repo_name stringlengths 5 100 | path stringlengths 4 231 | language stringclasses 1
value | license stringclasses 15
values | size int64 6 947k | score float64 0 0.34 | prefix stringlengths 0 8.16k | middle stringlengths 3 512 | suffix stringlengths 0 8.17k |
|---|---|---|---|---|---|---|---|---|
0todd0000/spm1d | spm1d/examples/nonparam/0d/ex_anova3.py | Python | gpl-3.0 | 635 | 0.037795 |
import numpy as np
import spm1d
#(0) Load dataset:
# dataset = spm1d.data.uv0d.anova3.RSItalian( | )
dataset = spm1d.data.uv0d.anova3.SouthamptonFullyCrossedMixed()
y,A,B,C = dataset.get_data()
print( dataset )
#(1) Conduct non-parametric test:
np.random.seed(0)
alpha = 0.05
snpmlist = spm1d.stats.nonparam.anova3(y, A, B, C)
snpmilist = snpmlist.inference(alpha, iterations=1000)
print( 'Non-parametric... | arametric results:')
print( spmilist )
|
cdrttn/fragmon | gamequery/query_scorebot.py | Python | mit | 6,268 | 0.008456 | import fragmon
import irc
from fragmon import Player
#some CTCP command handlers
def on_version(mask, location, cmd, args):
irc.ctcp(mask.nick, 'VERSION', fragmon.APPNAME, fragmon.VERSION, fragmon.WEBSITE)
irc.on_ctcp('*', 'version', on_version)
class SumBot(fragmon.ScoreBot):
""" This is an example scorebot... | if ls:
irc.msg(self.channel, 'Pts Ping Name (%s)' % name)
irc.msg(self.channel, '----------------')
for plr in ls:
irc.msg(self.channel, '%-5d %-5d %s' % (plr.score, plr.ping, plr.name))
if not alist and not blist and not flist:
... |
#XXX: note that this example is very basic and likely doesn't account for lineup changes
score = 0
for p in newlist:
score += p.score
return score
def broadcast(self):
""" Print scores to channel using the broadcast format configured by user.
... |
Pyrrvs/txdbus | txdbus/test/test_authentication.py | Python | mit | 17,765 | 0.011934 | import os
import os.path
import binascii
import tempfile
import shutil
import getpass
import time
from twisted.trial import unittest
from twisted.internet.protocol import Factory
from twisted.internet import reactor, defer, protocol, error
from txdbus import bus, endpoints, authentication
from txdbus.authentication ... | .s1(0,k))
finally:
shutil.rmtree(t)
def test_step1_create_user_keyring_dir(self):
t = tempfile.mkdtemp()
k = os.path.join(t,'keyring')
try:
| self.assertTrue( not os.path.exists(k) )
self.ae(self.s1(0,k)[0], 'CONTINUE')
self.assertTrue( os.path.exists(k) )
finally:
shutil.rmtree(t)
def test_step2_fail(self):
t = tempfile.mkdtemp()
k = os.path.join(t,'keyring'... |
jtamiace/fle-home | fle_site/apps/about/urls.py | Python | mit | 636 | 0.004717 | from django.conf.urls import patterns, include, url
from django.views.generic import TemplateView
urlpatterns = patterns('fle_site.apps.about.views',
url(r'^$', TemplateView.as_view(template_name='about/mission.html'), name='miss | ion'),
url(r'^values/$', TemplateView.as_view(template_name='about/values.html'), name='values'),
url(r'^team/$', 'team', name='team'),
url(r'^board/$', 'board', name='board'),
url(r'^supporters/$', 'suppo | rters', name='supporters'),
url(r'^press/$', 'press', name='press'),
url(r'^jobs/$', 'jobs', name='jobs'),
url(r'^internships/$', 'internships', name='internships'),
)
|
cbuahin/SWMMOpenMIComponent | Source/SWMMOpenMINoGlobalsPythonTest/SWMMOpenMINoGlobalsPythonTest.py | Python | lgpl-3.0 | 1,641 | 0.014033 | from ctypes import*
import math
lib = cdll.LoadLibrary("Z:\\Documents\Projects\\SWMMOpenMIComponent\\Source\\SWMMOpenMIComponent\\bin\\Debug\\SWMMComponent.dll")
print(lib)
print("\n")
finp = b"Z:\\Documents\\Projects\\SWMMOpenMIComponent\\Source\\SWMMOpenMINoGlobalsPythonTest\\test.inp"
frpt = b"Z:\\Documents\\Pr... | b\b\b\b\b\b\b")
#print("\n")
print "Hour " , str(theHour) , " Day " , str(theDay) , ' \r',
| #print("\n")
oldHour = newHour
if(elapsedTime.value <= 0 or not lib.swmm_getErrorCode(project) == 0):
break
lib.swmm_end(project)
lib.swmm_report(project)
lib.swmm_close(project)
|
uniphil/chitin | chitin.py | Python | mit | 5,548 | 0.001081 | #!/usr/bin/env python
from __future__ import print_function
import os
import json
import shutil
import jinja2
from jinja2 import nodes
from jinja2.ext import Extension
from jinja2.parser import describe_token
SITE_DIR = 'site'
CONTENT_DIR = 'data'
OUTPUT_DIR = 'build'
SKIP_PREFIX = '_'
LOAD_PREFIX = '%'
COPY_PREFIX... | data = [data]
for datum in data:
sub_context[loadable_name] = datum
do_loadable(site_directory, sub_context, prefixed_name, loadable_name, rest, output_path)
else:
do_loadable(site_directory, sub_context, prefixed_name, loadable_name, rest, outp | ut_path)
def do_loadable(site_directory, context, prefixed_name, loadable_name, prop, output_path):
# copying stuff
if prop.startswith(COPY_PREFIX):
unprefixed = prop[len(COPY_PREFIX):]
filenames = context[loadable_name][unprefixed]
if not isinstance(filenames, list):
file... |
ihabunek/toot | tests/test_console.py | Python | gpl-3.0 | 20,144 | 0.001193 | # -*- coding: utf-8 -*-
import io
import pytest
import re
from collections import namedtuple
from unittest import mock
from toot import console, User, App, http
from toot.exceptions import ConsoleError
from tests.utils import MockResponse
app = App('habunek.com', 'https://habunek.com', 'foo', 'bar')
user = User('ha... | 'created_at': '2017-04-12T15:53: | 18.174Z',
'account': {
'display_name': 'Frank Zappa',
'acct': 'fz'
},
'reblog': {
'account': {
'display_name': 'Johnny Cash',
'acct': 'jc'
},
'content': "<p>The computer can't tell you the emotional ... |
ARTFL-Project/PhiloLogic5 | python/philologic/LoadFilters.py | Python | gpl-3.0 | 11,328 | 0.001148 | #!/usr/bin/env python3
"""Load Filters used in Loader"""
import os
import pickle
import sys
import unicodedata
from json import dumps, loads
from subprocess import PIPE, Popen
from philologic.OHCOVector import Record
# Default filters
def get_word_counts(_, text):
"""Lowercase and count words"""
attrib_set ... | tem(refscommand)
def generate_lines(_, text):
lines_command = 'cat %s | egrep "^line" > %s' % (text["raw"], text["lines"])
os.system(lines_command)
def make_max_id(_, text):
max_id = [0, 0, 0, 0, 0, 0, 0, 0, 0]
with open(text["words"]) as filehandle:
for line in filehandle:
(key,... | zip(philo_id, max_id)]
with open(text["results"], "wb") as rf:
# write the result out--really just the resulting omax vector, which the parent will merge in below.
pickle.dump(max_id, rf)
def store_in_plain_text(*philo_types):
object_types = {"doc": 1, "div1": 2, "div2": 3, "div3": 4, "para":... |
christianmemije/kolibri | kolibri/utils/cli.py | Python | mit | 20,522 | 0.000731 | from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
import importlib # noqa
import logging # noqa
import os # noqa
import signal # noqa
import sys # noqa
from . import env
# Setup the environment before loading anything else from the application
#... | nf import KOLIBRI_HOME
return os.path.join(KOLIBRI_HOME, '.data_version')
def initialize(debug=False):
"""
Currently, always called before running commands. This may change in case
commands that conflict with this behavior show up.
:param: debug: Tells initialization to setup logging etc.
"""... | h.isfile(version_file()):
django.setup()
setup_logging(debug=debug)
_first_run()
else:
# Do this here so that we can fix any issues with our configuration file before
# we attempt to setup django.
from .conf import autoremove_unavailable_plugins, enable_default_plug... |
laurentbeost/subliminal | bierdopje.py | Python | gpl-2.0 | 2,133 | 0.027661 | #!/usr/bin/python
import xmlrpclib
import struct
import os
import urllib2
from xml.dom import minidom
class bierdopje:
def __init__(self, bierdopjeaddr, bierdopjeapi, useragent, db, logging):
self.useragent = useragent
self.db = db
self.cur = self.db.cursor()
self.bierdopjeurl = "http://" + bierdopjeaddr + "... | "
self.logging = logging
def do_request(self, url):
headers = { 'User-Agent' : self.useragent }
self.req = urllib2.Request(url, None, headers)
try:
self.resp = urllib2.urlopen(self.req)
except:
self.resp = None
def RetrieveSubs(self, tvdbid, season, episode, language):
self.logging.debug(" ... | season) + "/" + str(episode) + "/" + language + "/true"
self.do_request(url)
try:
dom = minidom.parse(self.resp)
except:
return False
for node in dom.getElementsByTagName("result"):
filename = node.getElementsByTagName("filename")[0].firstChild.data
link = node.getElementsByTagName("downloadlink")[0... |
phasedscum/python-as-a-waffle | xcelip.py | Python | mit | 398 | 0.012563 | from openpyxl import Workbook, load_workbook
xl = load_workbook(filename='./ipaddr.xl | sx', data_only=True)
xs = xl.active
col_rang = xl['Sheet1']
cell_rang = xs['A1':'A2']
#print(col_rang['A'].value)
print ('Getting Data From :', xl.get_sheet_names())
for row in xs.iter_rows():
for cell in r | ow:
iprecs = cell.value
#print(ipaddr)
#print(file=open(ipaddr + ".txt", "a")) |
freedomofpress/securethenews | manage.py | Python | agpl-3.0 | 344 | 0 | #!/usr/bin/env python
from __future | __ import absolute_import, unicode_literals
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE",
| "securethenews.settings.dev")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
|
aichaos/rivescript-python | tests/test_unicode.py | Python | mit | 3,441 | 0.000917 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals, absolute_import
import re
from rivescript.exceptions import RS_ERR_MATCH
from .config import RiveScriptTestCase
class UnicodeTest(RiveScriptTestCase):
"""UTF-8 Tests."""
def test_unicode(self):
self.new("""
... | , bot", "Hello human!")
self.reply("Hello: bot", "Hello human!")
self.reply("Hello... bot?", "Hell | o human!")
# Edit the punctuation regexp.
self.rs.unicode_punctuation = re.compile(r'xxx')
self.reply("Hello bot", "Hello human!")
self.reply("Hello, bot!", RS_ERR_MATCH)
def test_unicode_with_optionals(self):
templates = ["({})", "[{}]"] # Test both alternatives and optio... |
LLNL/spack | var/spack/repos/builtin/packages/mii/package.py | Python | lgpl-2.1 | 900 | 0.002222 | # Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class Mii(MakefilePackage):
"""Mii is an inverted indexing system for environment modules.
... | se see the README
on the homepage for more information."""
homepage = "https://github.com/codeandkey/mii"
url = "https://github.com/codeandkey/mii/archive/v1.0.4.tar.gz"
version('1.0.4', sha256='3c4e7e6e8c21969da8dade05fecab35be61f2bb82d75eeaf19db8cc97f8058b5')
def setup_build_environment... | efix)
|
goshow-jp/Kraken | Python/kraken/__init__.py | Python | bsd-3-clause | 1,147 | 0.004359 | """Kraken Framework."""
import logging
import os
__all__ = ['core', 'helpers', 'plugins', 'ui']
krakenPath = os.path.abspath(os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', '..'))
if os.environ.get('KRAKEN_PATH', None) is None:
os.environ['KRAKEN_PATH'] = krakenPath
krakenExtsPath = os.path.joi... | ')
if 'FABRIC_DFG_PATH' in os.environ:
if krakenPresetsPath not in os.environ['FABRIC_DFG_PATH']:
os.environ['FABRIC_DFG_PATH'] = krakenPresetsPath + os.pathsep + os.environ['FABRIC_DFG_PATH']
logging.basicConfig(format='[KRAKEN] %(levelname)s: %(message)s', level=logging.INFO)
# Custom inform level for | use with UI label getting added to the status bar.
logging.INFORM = 25
logging.addLevelName(logging.INFORM, 'INFORM')
logging.Logger.inform = lambda inst, msg, *args, **kwargs: inst.log(logging.INFORM, msg, *args, **kwargs)
|
xtrementl/focus | focus/parser/lexer.py | Python | mit | 9,227 | 0 | """ This module provides a lexical scanner component for the `parser` package.
"""
class SettingLexer(object):
""" Simple lexical scanner that tokenizes a stream of configuration data.
See ``SettingParser`` for further information about grammar rules and
specifications.
Example Usage:... | ter classes
WHITESPACE = ' \n\r\t'
COMMENT_START = '#'
NEWLINES = '\n\r'
TOKENS = '{},;'
QUOTES = '\'"'
ESCAPE = '\\'
SPACE = ' '
# lexer states
ST_TOKEN = 1
ST_STRING = 2
ST_COMMENT = 3
| def __init__(self, filename=None):
self._tokens = []
self._filename = None
self._token_info = {}
self._state_info = {}
self._reset_token()
self._state = self.ST_TOKEN
if filename:
self.read(filename)
def _reset_token(self):
""" Resets cu... |
mattgreen/hython | test/control/if.py | Python | gpl-3.0 | 494 | 0 | print("Before")
if 1:
p | rint("In if")
if True:
print("True")
if 42:
print("42")
if 0:
print("Shouldn't see this: 0")
if False:
print("Shouldn't see this: False")
if None:
print("Shouldn't see this: None")
else:
print("Else")
if True:
if 1:
print("Nested If")
a = 5
if a == 7:
print("Shouldn't see this... | ("After")
|
bakhtout/odoo-educ | addons/openeducat_erp/op_exam_attendees/op_exam_attendees.py | Python | agpl-3.0 | 1,616 | 0.006807 | # -*- coding: utf-8 -*-
#/#############################################################################
#
# Tech-Receptives Solutions Pvt. Ltd.
# Copyright (C) 2004-TODAY Tech-Receptives(<http://www.tech-receptives.com>).
#
# This program is free software: you can redistribute it and/or modify
# it under th... | censes/>.
#
#/#############################################################################
from openerp.osv import osv, fields
class op_exam_attendees(osv.osv):
_name = 'op.exam.attendees'
_rec_name = 'student_id'
_columns = {
'student_id': fields.many2one('op.student', string='Student', requ... | required=True),
'marks': fields.float(string='Marks'),
'note': fields.text(string='Note'),
'exam_id': fields.many2one('op.exam', string='Exam', required=True),
}
op_exam_attendees()
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
|
ruibarreira/linuxtrail | usr/lib/python3/dist-packages/orca/scripts/apps/liferea/script.py | Python | gpl-3.0 | 5,941 | 0.003871 | # Orca
#
# Copyright 2005-2008 Sun Microsystems Inc.
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This... | nline/offline"
# button near the status bar that has an image without a description.
# We speak and braille "Online/Offline button" here, until the
# developer of the application adds a description to the images
# associated with the button, which | shows the online or offline
# work mode.
#
rolesList = [pyatspi.ROLE_PUSH_BUTTON,
pyatspi.ROLE_FILLER,
pyatspi.ROLE_FILLER,
pyatspi.ROLE_FRAME]
# We are checking if the button with the focus is the button to
# tur... |
lancezlin/ml_template_py | lib/python2.7/site-packages/IPython/core/completerlib.py | Python | mit | 11,780 | 0.004499 | # encoding: utf-8
"""Implementations for various useful completers.
These are all loaded by default by IPython.
"""
#-----------------------------------------------------------------------------
# Copyright (C) 2010-2011 The IPython Development Team.
#
# Distributed under the terms of the BSD License.
#
# The full ... | d(m.group('name'))
return list(set(modules))
def get_root_modules():
"""
Returns a list containing the names of all the modules available in the
folders of the pythonpath.
ip | .db['rootmodules_cache'] maps sys.path entries to list of modules.
"""
ip = get_ipython()
rootmodules_cache = ip.db.get('rootmodules_cache', {})
rootmodules = list(sys.builtin_module_names)
start_time = time()
store = False
for path in sys.path:
try:
modules = rootmodules... |
ojarva/home-info-display | homedisplay/info_weather/migrations/0001_initial.py | Python | bsd-3-clause | 1,193 | 0.000838 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Weather',
fields=[
('id', models.AutoField(verb... | ('dewpoint', models.IntegerField()),
('feels_like', models.IntegerField()),
('humidity', models.PositiveSmallIntegerField()),
('temperature', models.IntegerField()),
('description', models.TextField()),
('wind_direction', models.TextField()... | },
bases=(models.Model,),
),
]
|
richter-t/espresso | samples/python/slice_input.py | Python | gpl-3.0 | 2,860 | 0.017133 | #
# Copyright (C) 2013,2014,2015,2016 The ESPResSo project
#
# This file is part of ESPResSo.
#
# ESPResSo is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option)... | system.part[:2].f=[[3,4,5],[4,5,6]]
print("F_NEW\n%s"%system.part[:].f)
if "MASS" in code_info.features():
print("MASS\n%s"%system.part[:].mass)
system.part[:2].mass=[2,3]
print("MASS_NEW\n%s"%system.part[:].mass)
if "ELECTROSTATICS" in code_info.features():
print("Q\n%s"%system.part[:].q)
system.... | %s"%system.part[:].q)
|
F-Secure/see | see/hooks.py | Python | apache-2.0 | 3,119 | 0 | # Copyright 2015-2017 F-Secure
# Licensed under the Apache License, Version 2.0 (the "License"); you
# may not use this file except in compliance with the License. You may
# obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agr | eed to in writing, software
# distributed under the License is distributed o | n an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied. See the License for the specific language governing
# permissions and limitations under the License.
import logging
from collections import namedtuple
from see.interfaces import Hook
from see.helpers import lookup_class... |
zvezdan/pip | tests/unit/test_unit_outdated.py | Python | mit | 6,190 | 0 | import datetime
import os
import sys
from contextlib import contextmanager
import freezegun
import pretend
import pytest
from pip._vendor import lockfile
from pip._internal.index import InstallationCandidate
from pip._internal.utils import outdated
class MockPackageFinder(object):
BASE_URL = 'https://pypi.pyth... | ache_dir / 'selfcheck.json'
assert | fake_lock.calls == [pretend.call(expected_path)]
assert fake_open.calls == [
pretend.call(expected_path),
pretend.call(expected_path),
pretend.call(expected_path, 'w'),
]
# json.dumps will call this a number of times
assert len(fake_file.write.calls)
|
agoose77/hivesystem | bee/bind.py | Python | bsd-2-clause | 17,026 | 0.003172 | # a worker factory class
# the worker has input "bind" (taking a tuple containing the bindantenna parameters)
# "pause"/"resume" (to control the eventmatcher taking keyboard/mouse events; the eventmatcher also checks that the bound hive has not been stopped)
# "stop" (taking a bindname), which ends the event dispatchi... | ses.socket_supplier(bridge.cleanup_functions.append)
libcontext.socket("cleanupfunction", s)
class newhive(self.hive):
zzz_bindbridgedrone = bindbridge()
raiser = raiser()
hiveconnec | t("evexc", raiser)
hive = newhive().getinstance()
try:
libcontext.push(self._context.contextname)
hive.build(bind_name)
hive.place()
finally:
libcontext.pop()
... |
flocca/flocca_dot_com | fabfile.py | Python | gpl-3.0 | 4,507 | 0.002663 | # This Python file uses the following encoding: utf-8
"""
Copyright 2013 Giacomo Antolini <giacomo.antolini@gmail.com>.
This file is part of flocca_dot_com.
flocca_dot_com is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
... | ases/{release}/cic/settings_local.py'.format(**env))
# Install and enable Apache2 site
sudo('cd {path}/releases/{release}; cp apache2.conf /etc/apache2/sites-available/{project_name}'.format(**env))
sudo('a2ensite {project_name}'.format(**env))
# Sync DB
with cd('{path}/releases/current'.format(**... | in the same directory
with cd('{path}/releases/current'.format(**env)):
sudo('../../bin/python manage.py collectstatic -v0 --noinput', user='www-data')
sudo('invoke-rc.d apache2 restart')
def setup_directories():
require('path')
# Crea la directory dove far risiedere la webapp
with sett... |
fdavies93/irc-mafia | bot/irc_bot.py | Python | gpl-2.0 | 8,251 | 0.037692 | import math
import random
import os
import platform
class vote:
def __init__(self,myManager,callback):
self.peopleVoting = [] #people allowed to vote
self.choices = [] #list of voteOptions available to vote for
self.onFinish = callback #a function taking a list of choices
self.hasSpoofing = False
self.voter... | eVoting.append(person)
elif(person.isDead == False):
werewolfVote.choices.append(voteOption(person.name))
#for person in self.people:
# if(person.type == "Werewolf"):
# self.inte | rface.sendMessageToPlayer("Werewolf, choose your victim!", person)
# else:#generic villager message
# self.interface.sendMessageToPlayer("Villager, stay asleep and await the slaughter!", person)
werewolfVote.runVote()
self.testForVictory()
def testForVictory(self):
numWerewolves = 0
numVillagers = 0
fo... |
internetfett/grocerylist | backend/grocerylist/__init__.py | Python | mit | 215 | 0 | FRACTIONS = (
(0, ''),
(.25, '1/4'),
(.5, '1/2'),
(.75, '3/4'),
)
UNITS = (
(' | unit', 'unit'),
('tsp | ', 'tsp'),
('tbsp', 'tbsp'),
('cup', 'cup'),
('oz', 'oz'),
('lb', 'lb'),
)
|
hcrlab/access_teleop | rosbridge_suite/rosbridge_library/src/rosbridge_library/capabilities/unadvertise_service.py | Python | mit | 2,016 | 0.00496 | import fnmatch
from rosbridge_library.capability import Capability
class UnadvertiseService(Capability):
# unadvertise_service_msg_fields = [(True, "ser | vice", (str, unicode))]
services_glob = None
def __init__(self, protocol):
# Call superclass constructor
Capability.__init__(self, protocol)
# Register the operations that this capability provides
protocol.register_operation("unadver | tise_service", self.unadvertise_service)
def unadvertise_service(self, message):
# parse the message
service_name = message["service"]
if UnadvertiseService.services_glob is not None and UnadvertiseService.services_glob:
self.protocol.log("debug", "Service security glob enabled... |
tcstewar/farm_game | farm_game/model.py | Python | gpl-2.0 | 8,819 | 0.005329 | from collections import OrderedDict
import numpy as np
import farm_model
class Model:
farm_width = 7
farm_height = 7
farm_count = farm_width * farm_height
products = [
'peachesRedhaven',
'peachesBabyGold',
'peachesOrganicRedhaven',
'peache... | hile model.steps < 0 :
model.step()
model_cache[(seed, ())] = -1, copy.deepcopy(model)
return -1, model
@memoize
def run(seed, *actions):
step, model = find_cached_model(seed, actions)
for i, act in enumerate(actions):
if i > step:
| for action in act.split(';'):
# add intervention
interv = None
if action == 'init':
pass
elif action == 'none':
pass
elif action.startswith('subsidy:'):
product, percent = act... |
brychanrobot/orrt-star-cpp | scripts/plot_trials.py | Python | mit | 437 | 0.018307 | import json
import numpy as np
import matplotlib.pyplot as plt
j = json.load(open('scripts/fullTrials.json', 'r'))
for scenario in j[-6:]:
obst = []
ave_score = []
for t in scenario['results']:
obst.append(t['obstacles'])
ave_score.append(np.mean(t['scores']))
plt.plot(obst, ave_score, label=scenar | io['scenario'])
plt.xti | cks(obst, map(str, obst))
plt.xlabel('# obstacles')
plt.ylabel('average score')
plt.legend()
plt.show() |
emacsmirror/stgit | stgit/lib/git/person.py | Python | gpl-2.0 | 2,200 | 0 | import re
from stgit.compat import environ_get
from stgit.config import config
from .base import Immutable
from .date import Date
class Person(Immutable):
"""Represents an author or committer in a Git commit object.
Contains :attr:`name`, :attr:`email` and :attr:`timestamp`.
"""
def __init__(self... | cls._committer = cls(
environ_get('GIT_COMMITTER_NAME', user.name),
environ_get('GIT_COMMITTER_EMAIL', user.email),
Date.maybe(environ_get('GIT_COMMITTER_DATE')),
)
return cls._commi | tter
|
gotclout/PythonJunk | 3.py | Python | mit | 429 | 0.039627 | #!/usr/bin/env python
from math import *
def i321():
n = 0L
mn = | 0L
tn = 0L
sn = 0L
n3 = 0L
n9 = 0L
n = 372889431
mn = 139046528497282623
tn = 1L + 8L * mn
print "M(%i) = %i\n" % (n, mn)
print "sqrt(%d) = %i\n" % (n, sqrt(n))
print "sqrt(%d) = %i\n" % (tn, sqrt(tn))
print "sqrt(%i) mod 1 = %i\n" % (tn, sqrt(tn) % 1)
prin | t "%i mod 3 = %i\n %i mod 9 = %i\n" % (mn, mn % 3L, mn, mn % 9L)
i321()
|
mattHawthorn/sk-torch | sktorch/interface.py | Python | mit | 40,749 | 0.008614 | #coding:utf-8
from typing import Any, Tuple, List, Iterable, Callable, Union, IO, Optional as Opt
import pickle
from time import time
from numpy import ndarray
from torch import autograd, nn, optim, from_numpy, stack
from torch.nn.modules import loss
from torch.nn.utils import clip_grad_norm
from .util import cuda_ava... | self.num_dataloader_workers = num_dataloader_workers
@property
def should_normalize(self):
return self.norm_n_samples is not None
def estimate_normalization(self, sample: Union[FloatTensorType, ndarray]):
"""Estimate the input normalization parameters (mean and sd) | per input dimension and store them for input
normalization during fitting and prediction"""
if not self.should_normalize:
raise ValueError("This model does not require normalization of inputs; inputs may be class labels or "
"pre-normalized")
mean = sampl... |
nathangeffen/tbonline-old | tbonlineproject/archive/urls.py | Python | mit | 1,184 | 0.010135 | from django.conf.urls.defaults import *
from django.views.generic import DetailView, ListView
from archive.models import Catalogue, Document
urlpatterns = patterns('archive.views',
url(r'^$',
ListView.as_view(
context_object_name="catalogues",
queryset=Catalogu... | queryset=Catalogue.objects.all(),
template_name='archive/catalogue.html'), name='catalogue-detail'),
url(r'^documents/ | $',
ListView.as_view(
context_object_name="documents",
queryset=Document.objects.all(),
template_name='archive/documents.html'), name='document-list'),
url(r'^document/(?P<pk>\d+)/$',
DetailView.as_view(
context_... |
LearnEra/LearnEraPlaftform | lms/djangoapps/instructor_analytics/basic.py | Python | agpl-3.0 | 12,491 | 0.003122 | """
Student and course analytics.
Serve miscellaneous course and student data
"""
from shoppingcart.models import PaidCourseRegistration, CouponRedemption, Invoice, RegistrationCodeRedemption
from django.contrib.auth.models import User
import xmodule.graders as xmgraders
from django.core.exceptions import ObjectDoesNo... | profile = student.profile
if profile is not None:
profile_dict = dict((feature, getattr(profile, feature))
for feature in profile_features)
student_dict.update(profile_dict)
return student_dict
return [extract_student(student, | features) for student in students]
def coupon_codes_features(features, coupons_list):
"""
Return list of Coupon Codes as dictionaries.
coupon_codes_features
would return [
{'course_id': 'edX/Open_DemoX/edx_demo_course,, 'discount': '213' ..... }
{'course_id': 'edX/Open_DemoX/edx_dem... |
punalpatel/st2 | st2tests/st2tests/resources/packs/pythonactions/actions/test.py | Python | apache-2.0 | 209 | 0 | # Python action which uses the same module name as built-in Python module
# (test)
from st2common.runners.base_action imp | ort Action
class TestAction(Action | ):
def run(self):
return 'test action'
|
google/jax-cfd | jax_cfd/base/pressure.py | Python | apache-2.0 | 3,942 | 0.006342 | # Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | array_utils
from jax_cfd.base import boundaries
from jax_cfd.base import fast_diagonalization
from jax_cfd.base import finite_differences as fd
from jax_cfd.base import grids
Array = grids.Array
GridArray = grids.GridArray
GridArrayVector = grids.GridArrayVector |
GridVariable = grids.GridVariable
GridVariableVector = grids.GridVariableVector
BoundaryConditions = grids.BoundaryConditions
# Specifying the full signatures of Callable would get somewhat onerous
# pylint: disable=g-bare-generic
# TODO(pnorgaard) Implement bicgstab for non-symmetric operators
def solve_cg(v: Gr... |
google/osv | gcp/appengine/monorail.py | Python | apache-2.0 | 1,791 | 0.002233 | # Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | ests
_API_BASE = 'https://api-dot-monorail-prod.appspot.com/prpc'
_TARGET_AUDIENCE = 'https://monorail-prod.appspot.com'
_XSSI_PREFIX = ')]}\'\n'
class Client:
"""Monorail client."""
def __init__(self, project, service_account_info):
self.project = project
self._s | ervice_account_info = service_account_info
def get_issue(self, issue_id):
"""Get issue data."""
credentials = service_account.IDTokenCredentials.from_service_account_info(
self._service_account_info, target_audience=_TARGET_AUDIENCE)
credentials.refresh(google_requests.Request())
headers = {... |
multidadosti-erp/multidadosti-addons | project_attachment_tags/models/ir_attachment.py | Python | agpl-3.0 | 676 | 0 | from odoo import api, fields, models
class IrAttachment(models.Model):
_inherit = "ir.attachment"
tag_ | id = fields.Many2one(comodel_name='attach.category.tag',
string='Tag')
@api.onchange('res_id')
def _onchange_res_id(self):
# TODO Corrigir uso do domain quando o record e editado
if self.res_model == 'project.project':
category_id = self.env['project.pro... | else []
return {'domain': {'tag_id': [('id', 'in', tag_ids)]}}
|
Bouke/django-two-factor-auth | tests/test_yubikey.py | Python | mit | 5,356 | 0.00112 | import unittest
from unittest.mock import patch
from django import forms
from django.conf import settings
from django.shortcuts import resolve_url
from django.test import TestCase
from django.urls import reverse
from .utils import UserMixin
try:
from otp_yubikey.models import ValidationService, RemoteYubikeyDevi... | 'auth-password': 'secret',
'login_view-current_step': 'auth'})
self.assertContains(response, 'YubiKey:')
| self.assertIsInstance(response.context_data['wizard']['form'].fields['otp_token'],
forms.CharField)
# Should call verify_token
token = 'cjikftknbiktlitnbltbitdncgvrbgic'
response = self.client.post(reverse('two_factor:login'),
... |
tylert/chirp.hg | chirp/drivers/icf.py | Python | gpl-3.0 | 23,992 | 0 | # Copyright 2008 Dan Smith <dsmith@danplanet.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is ... | _data
|
if not nolimit and len(self.data) > 128 and "\xFD" in self.data:
break # Give us a chance to do some status
if len(self.data) > 1024:
break # Avoid an endless loop of chewing garbage
if not self.data:
return []
return self._process... |
cognitiveclass/edx-platform | lms/startup.py | Python | agpl-3.0 | 6,065 | 0.002968 | """
Module for code that should run during LMS startup
"""
import django
from django.conf import settings
# Force settings to run so that the python path is modified
settings.INSTALLED_APPS # pylint: disable=pointless-statement
from openedx.core.lib.django_startup import autostartup
import edxmako
import logging
im... | mes+to+Application-centric+runtimes
xmodule.x_module.descriptor_global_handler_url = lms_xblock.runtime.handler_url
xmodule.x_module.descriptor_global_local_resource_url = lms_xblock.runtime.local_resource_url
def add_mimetypes():
"""
Add extra m | imetypes. Used in xblock_resource.
If you add a mimetype here, be sure to also add it in cms/startup.py.
"""
import mimetypes
mimetypes.add_type('application/vnd.ms-fontobject', '.eot')
mimetypes.add_type('application/x-font-opentype', '.otf')
mimetypes.add_type('application/x-font-ttf', '.ttf... |
chubbymaggie/almc | amdc/tri_model.py | Python | gpl-2.0 | 9,709 | 0.007416 | __author__ = 'Dongwoo Kim'
import numpy as np
from sklearn.metrics import precision_recall_curve, auc
import path_tool
heaviside = lambda x: 1 if x >= 0 else 0
class TAMDC:
"""
Implementation of Active Multi-relational Data Construction (AMDC) method.
Reference:
Kajino, H., Kishimoto, A., Botea, A.... | R[:, :, a_bar] = np.dot(U, V)
U, sigma, V = np.linalg.svd(R[:, :, b_bar])
R[:, :, b_bar] = np.dot(U, V)
else:
next_idx = np.random.randint(len(n_idx))
next_nn_idx = np.random.randint(len(nn_idx))
i, j, k = np.... | dot(A[i], R[:, :, k]), A[j])
- np.dot(np.dot(A[i_bar], R[:, :, k_bar]), A[j_bar]))
I_4 = heaviside(self.gamma_p + np.dot(np.dot(A[i], R[:, :, k]), A[j]))
if I_3 != 0 or I_4 != 0:
a_i, a_j, r_k = A[i].copy(), A[j].copy(), R[:, :, k].cop... |
timomiao/timomiao.github.io | licensetestv1.0/py/servequestion.py | Python | gpl-2.0 | 1,083 | 0.036011 | #!/usr/bin/python
from mod_python import apache
from mod_python import util
import simplejson
import os
#path relative to app ( e.g. /var/www/licensetest/ <jsonfile> )
jsonfile = 'denyall/testdata.json'
#get cwd
abspath = os.path.dirname(os.path.realpath(__file_ | _))
#cd .. (second os.path.dirname) and add rel. dir
filepath = os.path.dirname( abspath ) + '/' + jsonfile;
try:
fp = open( filepath )
testdata = simplejson.lo | ad( fp )
except IOError:
apache.log_error(__file__+': Can\' read data from '+filepath)
else:
apache.log_error(__file__+': [noerror] Init complete (datafile: '+filepath+' )');
fp.close()
def handler(req):
req.content_type = 'application/json'
req.send_http_header()
if req.method == "GET" and r... |
mitenjain/protpore | proteinhmmvisualize.py | Python | mit | 5,023 | 0.033048 | '''
Author: Hannah Meyers
This file contains the experiment code for attempting to model
protein nanopore traces via HMMs. Please see inline comments
for an explanation of what each piece of the code is doing.
'''
from __future__ import print_function
from PyPore.parsers import *
from PyPore.DataTypes impor... | rofile_data/profilemeans.csv' )
profile_stds = pd.read_csv( 'profile_data/profilestds.csv' )
#Convert CSV data to distribution objects
dists_means = [ NormalDistribution( profile_means[col].mean(), profile_means[col].std() ) for col in profile_means ]
dists_stds = [ LogNormalDistribution( np.log( profile_stds[co... | ution([ mean, std ]) for mean, std in it.izip( dists_means, dists_stds ) ]
#profile[5] = MultivariateDistribution([ ExtremeValueDistribution( 20, 10 ), LogNormalDistribution( np.log(4.5), np.log(3.5) ) ])
#print(profile[5])
#list of board functions corresponds to the 11 profile positions
boardlist = [ProteinDom... |
fedorpatlin/ansible | lib/ansible/plugins/action/junos.py | Python | gpl-3.0 | 5,656 | 0.001768 | #
# (c) 2016 Red Hat Inc.
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is d... | if self._play_context.conne | ction != 'local':
return dict(
failed=True,
msg='invalid connection specified, expected connection=local, '
'got %s' % self._play_context.connection
)
module = module_loader._load_module_source(self._task.action, module_loader.find_plu... |
jeremiah-c-leary/vhdl-style-guide | vsg/tests/loop_statement/test_rule_005.py | Python | gpl-3.0 | 1,273 | 0.003928 |
import os
import unittest
from vsg.rules import loop_statement
from vsg import vhdlFile
from vsg.tests import utils
sTestDir = os.path.dirname(__file__)
lFile, eError =vhdlFile.utils.read_vhdlfile(os.path.join(sTestDir,'rule_005_test_input.vhd'))
dIndentMap = utils.read_indent_file()
lExpected = []
lExpected.appe... | ne(eError)
self.oFile.set_indent_map(dIndentMap)
| def test_rule_005(self):
oRule = loop_statement.rule_005()
self.assertTrue(oRule)
self.assertEqual(oRule.name, 'loop_statement')
self.assertEqual(oRule.identifier, '005')
lExpected = [16, 19, 22]
oRule.analyze(self.oFile)
self.assertEqual(lExpected, utils.ext... |
tantSinnister/doto | doto/cli/parser.py | Python | bsd-3-clause | 762 | 0.002625 | """
This module holds a common parser for the add and modify command.
"""
import datetime
import pytz
def init_id_flag(command, subparser):
"""
Init the parser
It adds the id argument to the argument parser
"""
parser = subparser.add_parser(command, help="")
parser.add_argument("id", type=in... | format_str)
return local_tz.localize(date).astimezone(pyt | z.utc)
global date_parser
date_parser = local_date_parser_2_utc
date_parser = None
set_date_parser("UTC", "%Y.%m.%d-%H:%M")
|
hammerlab/pyensembl | test/test_exon_id.py | Python | apache-2.0 | 3,958 | 0.001516 | """
Exon IDs of the TP53 gene and one of its transcripts (TP53-026) were copied
from the Ensembl website, make sure same IDs are found by pyensembl.
"""
from __future__ import absolute_import
from pyensembl import cached_release
ensembl = cac | hed_release(77)
# all exons associated with TP53 gene in Ensembl release 77
TP53_EXON_IDS_RELEASE_77 = [
'ENSE00002337729' | , 'ENSE00002419584',
'ENSE00003625790', 'ENSE00003518480',
'ENSE00003723991', 'ENSE00003712342',
'ENSE00001657961', 'ENSE00003725258',
'ENSE00003740946', 'ENSE00002204316',
'ENSE00002064269', 'ENSE00003750554',
'ENSE00003634848', 'ENSE00003492844',
'ENSE00003735852', 'ENSE00003545950',
'... |
turdusmerula/kipartman | kipartbase/swagger_server/models/storage_data.py | Python | gpl-3.0 | 2,758 | 0.000363 | # coding: utf-8
from __future__ import absolute_import
from .base_model_ import Model
from datetime import date, datetime
from typing import List, Dict
from ..util import deserialize_model
class StorageData(Model):
"""
NOTE: This class is auto generated by the swagger code generator program.
Do not edit ... | name(self, name):
"""
Sets the name of this StorageData.
:param name: The name of this StorageData.
:type name: str
"""
self._name = name
@property
def description(self):
"""
Gets the description of this StorageData.
:return: The descr... | ription(self, description):
"""
Sets the description of this StorageData.
:param description: The description of this StorageData.
:type description: str
"""
self._description = description
@property
def comment(self):
"""
Gets the comment of th... |
LeonPoon/XMLExplode | src-test/test/xmlxplode/test_xml_walk.py | Python | apache-2.0 | 1,191 | 0.004198 | # Copyright 2016 Leon Poon and Contributors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... | writing, s | oftware
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import unittest
from xml.dom import minidom
from test i... |
usig/normalizador-amba | tests/CallejeroTestCase.py | Python | mit | 7,895 | 0.00268 | # coding: UTF-8
import unittest
from usig_normalizador_amba.Callejero import Callejero
from usig_normalizador_amba.Partido import Partido
from usig_normalizador_amba.Calle import Calle
from tests.test_commons import cargarCallejeroEstatico
class CallejeroTestCase(unittest.TestCase):
p = Partido('jose_c_paz', '... | self._checkCalle(res[0], 183044, 'Puerto Príncipe', 'jose_c_paz', 'José C. Paz')
def testCallejero_buscarCalle_calle_con_parentesis(self):
res | = self.c.buscarCalle('Coliqueo (JCP)')
self.assertTrue(isinstance(res, list))
self.assertEqual(len(res), 1, 'Debería haber 1 matching.')
self._checkCalle(res[0], 186501, 'Intendente Arricau (SM) / Cacique Coliqueo (JCP)', 'jose_c_paz', 'José C. Paz')
def testCallejero_buscarCalle_caracteres... |
fernando-cardenas/newspaper | newspaper/newspaper/news/urls.py | Python | apache-2.0 | 186 | 0.005376 | fro | m django.conf.urls import url
from newspaper.news.views import *
urlpatterns = [
url(r'^$', news_list, name='news_list'),
url(r'^news_list/', news_list, na | me='news_list')
]
|
sqlalchemy/sqlalchemy | test/orm/declarative/test_clsregistry.py | Python | mit | 12,127 | 0 | from sqlalchemy import Column
from sqlalchemy import exc
from sqlalchemy import Integer
from sqlalchemy import MetaData
from sqlalchemy import testing
from sqlalchemy.orm import clsregistry
from sqlalchemy.orm import registry
from sqlalchemy.orm import relationship
from sqlalchemy.testing import assert_raises_message
f... | xpect_warnings(
"This declarative base already contains a class with the "
"same class name and module name as foo.bar.Foo, and "
"will be replaced in the string-lookup table."
):
clsregistry.add_class(
"Foo",
f2,
ba... | ss_registry,
)
def test_resolve(self):
base = registry()
f1 = MockClass(base, "foo.bar.Foo")
f2 = MockClass(base, "foo.alt.Foo")
clsregistry.add_class("Foo", f1, base._class_registry)
clsregistry.add_class("Foo", f2, base._class_registry)
name_resolver, r... |
NiekB4/2016_Group07_Transit-BuiltEnvironment | PTStopCalc_Plugin_Neeraj/test/test_pt_stop_calc_dockwidget.py | Python | gpl-2.0 | 1,110 | 0.001802 | # coding=utf-8
"""DockWidget test.
.. note:: This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
"""
__author__ = ... | ate__ = '2016-12-20'
__copyright__ = 'Copyright 2016, neeraj'
import unittest
from PyQt4.Qt | Gui import QDockWidget
from pt_stop_calc_dockwidget import PTStopCalcDockWidget
from utilities import get_qgis_app
QGIS_APP = get_qgis_app()
class PTStopCalcDockWidgetTest(unittest.TestCase):
"""Test dockwidget works."""
def setUp(self):
"""Runs before each test."""
self.dockwidget = PTSto... |
idea4bsd/idea4bsd | python/testData/inspections/DictComprehensionToCall.py | Python | apache-2.0 | 163 | 0.04908 | var = <warning descr="Python version 2.4, 2.5, 2.6, 3.0 do not support dictionary com | prehensions">{k: v for k, v | in zip('abc', <caret>range(3)) if k % 2}</warning> |
ubuntunux/GuineaPig | PyEngine3D/App/GameBackend/GameBackend_pygame.py | Python | bsd-2-clause | 10,816 | 0.00037 | import os
import pygame
from pygame.locals import *
from PyEngine3D.Common import logger
from .GameBackend import GameBackend, Keyboard, Event
class PyGame(GameBackend):
def __init__(self, core_manager):
GameBackend.__init__(self, core_manager)
logger.info('GameBackend : pygame %s' % pygame.__v... | UOTE
Keyboard.A = K_a
Keyboard.B = K_b
Keyboard.C = K_c
Keyboard.D = K_d
Keyboard.E = K_e
Keyboard.F = K_f
Keyboard.G = K_g
Keyboard.H = K_h
Keyboard.I = K_i
Keyboard.J = K_j
Keyboard.K = K_k
Keyboard.L = K_l
Keyboar... | Keyboard.S = K_s
Keyboard.T = K_t
Keyboard.U = K_u
Keyboard.V = K_v
Keyboard.W = K_w
Keyboard.X = K_x
Keyboard.Y = K_y
Keyboard.Z = K_z
# Keyboard.BRACELEFT = K_LEFTBRACE
# Keyboard.BAR = K_BAR
# Keyboard.BRACERIGHT = K_BRACERIGHT
... |
rdio/sentry | src/sentry/migrations/0053_auto__del_projectmember__del_unique_projectmember_project_user.py | Python | bsd-3-clause | 19,934 | 0.008227 | # encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Removing unique constraint on 'ProjectMember', fields ['project', 'user']
db.delete_unique('sentry_projectmember... | elds.CharField', [], {'default': "'root'", 'max_length': '64', 'db_index': 'True', 'blank': 'True'}),
'message': ('django.db.models.fields.TextField', [], {}),
'project': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['sentry.Project']", 'null': 'True'}),
'score': ('d... | o.db.models.fields.PositiveIntegerField', [], |
batxes/4Cin | SHH_WT_models/SHH_WT_models_final_output_0.1_-0.1_11000/mtx1_models/SHH_WT_models31195.py | Python | gpl-3.0 | 17,577 | 0.02509 | import _surface
import chimera
try:
import chimera.runCommand
except:
pass
from VolumePath import markerset as ms
try:
from VolumePath import Marker_Set, Link
new_marker_set=Marker_Set
except:
from VolumePath import volume_path_dialog
d= volume_path_dialog(True)
new_marker_set= d.new_marker_set
marker_set... | 9)
if "particle_26 geometry" not in marker_sets:
s=new_marker_set('particle_26 geometry')
marker_sets["particle_26 geometry"]=s
s= marker_sets["particle_26 geometry"]
mark=s.place_marker((4523.23, 8516.54, 7731.83), (0.7, 0.7, 0.7), 644.694)
if "particle_27 geometry" not in marker_sets:
s=new_marker_set('particle... | , 0.7, 0.7), 896.802)
if "particle_28 geometry" not in marker_sets:
s=new_marker_set('particle_28 geometry')
marker_sets["particle_28 geometry"]=s
s= marker_sets["particle_28 geometry"]
mark=s.place_marker((4263.05, 7164.49, 5825.1), (0.7, 0.7, 0.7), 576.38)
if "particle_29 geometry" not in marker_sets:
s=new_mar... |
ndp-systemes/odoo-addons | base_res_config_improved/__openerp__.py | Python | agpl-3.0 | 1,290 | 0 | # -*- coding: utf8 -*-
#
# Copyright (C) 2018 NDP Systèmes (<http://www.ndp-systemes.fr>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License,... |
{
'name': 'Base res config improved',
'version': '0.1',
'author': 'NDP Systèmes',
'maintainer': 'NDP Systèmes',
'category': 'Generic Modules',
'depends': ['base'],
'description': """
Base res config improved
========================
This module impr | oved the base res config.""",
'website': 'http://www.ndp-systemes.fr',
'data': [],
'demo': [],
'test': [],
'installable': True,
'auto_install': True,
'license': 'AGPL-3',
'application': False,
}
|
placiflury/gridmonitor-sft | sft/db/sft_handler.py | Python | bsd-3-clause | 3,142 | 0.00732 | """
Dealing with SFT tests.
"""
import logging
import sft_meta
import sft_schema as schema
from sft.utils.helpers import strip_args
class SFTPool():
""" This class defines all site functional tests (SFT)s
that shall be executed.
"""
def __init__(self):
self.log = logging.getLogger(__... | bug("Initialization finished")
def __del__(self):
self.session.close()
@strip_args
def add_sft(self, name, cluster_grp, vo_grp,test_su | it):
""" Adding a new SFT to the 'global' pool of SFTS.
params: name - the name of the SFT, must be unique
cluster_grp - the name of the cluster group (see ClusterGroupPool)
to which SFTs shall apply
vo_grp - the name of t... |
foundit/Piped | piped/providers/test/test_web_provider.py | Python | mit | 19,532 | 0.006553 | # Copyright (c) 2011, Found IT A/S and Piped Project Contributors.
# See LICENSE for details.
import json
from StringIO import StringIO
from twisted.application import service
from twisted.internet import defer, address
from twisted.python import filepath, failure
from twisted.trial import unittest
from twisted.web im... | , [''])
self.asse | rtConfiguredWithProcessor(web_resource, 'pipeline.a_pipeline')
def test_no_resource_processor_routing(self):
config = dict(
routing = dict(
__config__ = dict(processor='pipeline.root_pipeline', no_resource_processor='pipeline.root_no_resource_pipeline'),
foo = di... |
jjrennie/GHCNpy | test.py | Python | bsd-3-clause | 360 | 0.005556 | import ghcnpy
# Provide introduction
ghcnpy.intro()
# Print Latest Ver | sion
ghcnpy.get_ghcnd_version()
# Testing Search Capabilities
print("\nTESTING SEARCH CAPABILITIES")
ghcnpy.find_station("Asheville")
# Testing Search Capabilities
print("\nTESTING PULL CAPABILITIES")
| outfile=ghcnpy.get_data_station("USW00003812")
print(outfile," has been downloaded")
|
SickGear/SickGear | lib/subliminal/language.py | Python | gpl-3.0 | 54,782 | 0.001775 | # -*- coding: utf-8 -*-
# Copyright 2011-2012 Antoine Bertin <diaoulael@gmail.com>
#
# This file is part of subliminal.
#
# subliminal is free software; you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation; either version 3 of... | a'),
('LI', 'LIE', '438', u'Liechtenstein'),
('LT', 'LTU', '440', u'Lithuania'),
('LU', 'LUX', '442', u'Luxembourg'),
('MO', 'MAC', '446', u'Macao'),
('MK', 'MKD', '807', u'Mace | donia, Republic of'),
('MG', 'MDG', '450', u'Madagascar'),
('MW', 'MWI', '454', u'Malawi'),
('MY', 'MYS', '458', u'Malaysia'),
('MV', 'MDV', '462', u'Maldives'),
('ML', 'MLI', '466', u'Mali'),
('MT', 'MLT', '470', u'Malta'),
('MH... |
citrix-openstack-build/heat | heat/tests/test_server.py | Python | apache-2.0 | 35,624 | 0.000056 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable... | server.networks['private'][0]
self.assertEqual(
| server.FnGetAtt('addresses')['private'][0]['addr'], private_ip)
self.assertEqual(
server.FnGetAtt('networks')['private'][0], private_ip)
self.assertIn(
server.FnGetAtt('first_address'), (private_ip, public_ip))
self.m.VerifyAll()
def test_server_create_imag... |
ppwwyyxx/tensorflow | tensorflow/lite/testing/op_tests/rfft2d.py | Python | apache-2.0 | 2,231 | 0.003138 | # Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org | /licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations... | der the License.
# ==============================================================================
"""Test configs for rfft2d."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
from tensorflow.lite.testing.zip_test_utils import create... |
onnovalkering/sparql-over-sms | sos-service/src/processing/filters/sparqldecompress.py | Python | mit | 635 | 0.001575 | from | utilities.compression import SoSCompression
class SparqlDecompress:
"""Performs SPARQL sos-decompression"""
name = "SparqlCompress"
d | escription = "Performs SPARQL sos-decompression"
@staticmethod
def execute(token):
message = token.message
body = message.get_body()
decompressed_body_parts = SoSCompression.decompress_sparql(body)
decompressed_body = (b' '.join(decompressed_body_parts)).decode('utf-8')
... |
boxed/CMi | web_frontend/send2trash/plat_win.py | Python | mit | 1,660 | 0.004819 | # Copyright 2013 Hardcoded Software (http://www.hardcoded.net)
# This software is licensed under the "BSD" License as described in the "LICENSE" file,
# which should be included with this package. The terms are also available at
# http://www.hardcoded.net/licenses/bsd_license
from __future__ import unicode_literals... | ypes import HWND, UINT, LPCWSTR, BOOL
import os.path as op
from .compat import text_type
shell32 = windll.shell32
SHFileOperationW = shell32.SHFileOperationW
class SHFILEOPSTRUCTW(Structure):
_fi | elds_ = [
("hwnd", HWND),
("wFunc", UINT),
("pFrom", LPCWSTR),
("pTo", LPCWSTR),
("fFlags", c_uint),
("fAnyOperationsAborted", BOOL),
("hNameMappings", c_uint),
("lpszProgressTitle", LPCWSTR),
]
FO_MOVE = 1
FO_COPY = 2
FO_DELETE = 3
FO_RENAME = 4
... |
natla/softuni-python | SoftUni-L3-Functions/t2_average_price_by_sex_age.py | Python | mit | 2,695 | 0.004082 | # Find average price of products in a text file, grouped by sex and age
# Infant, Kid, Men, Unisex, Woman
def average(prices):
return sum(prices) / len(prices)
infant_prices = []
kid_prices = []
men_prices = []
unisex_prices = []
woman_prices = []
with open('catalogs/catalog_sample.csv') as f:
for line in f... | unisex_prices.append(float(product[-1]))
elif "Woman" in product:
woman_prices.append(float(product[-1]))
print('Infant average price: {:.2f} fo | r {} items'.format(average(infant_prices), len(infant_prices)))
print('Kid average price: {:.2f} for {} items'.format(average(kid_prices), len(kid_prices)))
print('Men average price: {:.2f} for {} items'.format(average(men_prices), len(men_prices)))
print('Unisex average price: {:.2f} for {} items'.format(a... |
savinash47/openstack-doc-tools | os_doc_tools/handle_pot.py | Python | apache-2.0 | 8,610 | 0.000116 | #!/usr/bin/env python
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, softwar... | # As used in security-doc and operations-guide
newxml = newxml.replace('SYSTEM "openstack.ent">',
'SYSTEM "openstack.ent"> %openstack;')
try:
dom = xml.dom.minidom.parseString(newxml)
except xml.parsers.expat.ExpatError as e:
print("Error: parsing of file '%s' f... | |
dietrichc/streamline-ppc-reports | examples/dfp/v201405/contact_service/get_uninvited_contacts.py | Python | apache-2.0 | 2,206 | 0.00816 | #!/usr/bin/python
#
# Copyright 2014 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required b... | s.py.
The LoadFromStorage method is pulling credentials and properties from a
"googleads.yaml" file. By default, it looks for this file in your home
directory. For more information, see the "Caching authentication information"
section of our README.
Tags: ContactService.getContactsByStatement
"""
__author__ = ('Nicho... | port dfp
def main(client):
# Initialize appropriate service.
contact_service = client.GetService('ContactService', version='v201405')
# Create statement object to only select contacts that are uninvited.
values = [{
'key': 'status',
'value': {
'xsi_type': 'TextValue',
'value':... |
pupils/pupils | pupils/tablon/models.py | Python | agpl-3.0 | 566 | 0.017699 | # -*- coding: utf-8 -*-
from django.db import models
from django.contrib.auth.models import User
from users.models import Hijo
class Post(models.Model):
title = models.TextField(null=True, blank=True) # | Título
content = models.TextField(null=True, blank=True) #Contenido de la entrada
url = models.URLField(max_length=200, null=True, blank=True)
hijo = models.ForeignKey(Hijo, blank=True, null=True)
date_creati | on = models.DateTimeField(auto_now_add=True)
published_by = models.ForeignKey(User, blank=True, null=True)
|
rexshihaoren/algorithms | algorithms/searching/rabinkarp_search.py | Python | bsd-3-clause | 950 | 0 | """
Implementation of Rabin-Karp search on a given string.
Rabin-Karp Search
-----------------
Search for a substring in a given string, by comparing hash values
of the strings.
Time Complexity: O(nm)
Psuedo Code: http://en.wikipedia.org/wiki/Rabin-Karp_algorithm
"""
from hashlib import... | Uses hashing to find any one of a set of pattern strings in a | text.
:param s: The string to be searched.
:param sub: The substring to be searched for.
:rtype: The indices of all occurences of where the substring is found in
the string.
"""
n, m = len(s), len(sub)
hsub_digest = md5(sub.encode('utf-8')).digest()
offsets = []
if m > n:
... |
indico/indico | indico/web/http_api/responses.py | Python | mit | 1,367 | 0 | # This file is part of Indico.
# Copyright (C) 2002 - 2022 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
import time
from marshmallow import fields
from marshmallow.decorators import post_dump
from indico.core... | is | None:
ts = int(time.time())
self.results = results
self.path = path
self.query = query
self.ts = ts
self.extra = extra or {}
@property
def url(self):
prefix = config.BASE_URL
if self.query:
return f'{prefix}{self.path}?{self.query... |
vacancy/TensorArtist | tartist/core/utils/context.py | Python | mit | 328 | 0.006098 | # -*- coding:utf8 -*-
# File : context.py
# Author : Jiayuan Mao
# Email : maojiayuan@gmail.com
# Date : 12/31/16
#
# This file is part | of TensorArtist.
__all__ = ['EmptyContext']
class EmptyContext(object):
def __enter__(self):
return
def __exit__(self, exc_type, exc_val, exc_tb):
| return
|
janpipek/hlava | hlava/items/__init__.py | Python | mit | 2,350 | 0.00383 | import os
import glob
import importlib
import logging
logger = logging.getLogger(__name__)
class UnknownFormatError(RuntimeError):
pass
item_classes = []
supported_protocols = []
def constructor_exists(path):
for klass in item_classes:
if klass.applies(path):
return True
return Fal... | th.isfile(f) and not os.path.basename(f).startswith('_'),
py_files)
modules = [os.path.basename(py_file[:-3]) for py_file in py_files]
subpackage = importlib.import_module("." + subdir, __package__)
for module | _name in modules:
try:
importlib.import_module("." + module_name, subpackage.__name__)
except Exception as i:
logger.warning("Module %s could not be imported, reason: %s" % (module_name, i))
from . import directory
_auto_import()
|
colaftc/webtool | top/api/rest/TradeAmountGetRequest.py | Python | mit | 317 | 0.031546 | '''
Created by auto_sdk on 2015.04.24
'''
from top.api.base import RestApi
class TradeAmountGetRequest(RestApi):
def __init__(sel | f,domain='gw.api.taobao.com',port=80):
RestApi.__init__(self,domain, port)
self.fields = None
self.tid = None
def getapiname(self):
return 't | aobao.trade.amount.get'
|
slozier/ironpython2 | Src/StdLib/Lib/site-packages/isapi/test/build/bdist.win32/winexe/temp/_winreg.py | Python | apache-2.0 | 344 | 0.011628 |
def __load():
import imp, os, sys
try:
dirname = os.path.dirname(__loa | der__.archive)
e | xcept NameError:
dirname = sys.prefix
path = os.path.join(dirname, '_winreg.pyd')
#print "py2exe extension module", __name__, "->", path
mod = imp.load_dynamic(__name__, path)
## mod.frozen = 1
__load()
del __load
|
hypertable/hypertable | tests/integration/thrift-table-refresh/thrift_hql.py | Python | gpl-3.0 | 438 | 0.022831 | #!/usr/bin/env python
import | sys
import time
from hypertable.thriftclient import *
from hyperthrift.gen.ttypes import *
if (len(sys.argv) < 2):
print sys.argv[0], "<hql>"
sys.exit(1);
try:
client = ThriftClient("localhost", 15867)
namespace = client.open_namespace("/")
res = client.hql_query(namespace, sys.argv[1]);
print res
c... | ientException, e:
print '%s' % (e.message)
|
CiuffysHub/MITMf | mitmflib-0.18.4/mitmflib/impacket/dhcp.py | Python | gpl-3.0 | 8,466 | 0.026813 | # Copyright (c) 2003-2015 CORE Security Technologies
#
# This software is provided under under a slightly modified version
# of the Apache Software License. See the accompanying LICENSE file
# for more information.
#
import pcapy
import socket
import time
from random import randint
from mitmflib.impacket import struc... | client-id':(61,':'),
# other non-rfc1533 options
'slp-directory-agent':(78,':'), # http://www.ietf.org/rfc/rfc2610.txt
'slp-service-scope':(79,':'), # http://www.ietf.org/rfc/rfc2610.txt
'fully-qualified-domain-name':(81,':'), # http://www.ietf.org/rfc | /rfc4702.txt
'auto-configuration':(116,'B'), # http://www.ietf.org/rfc/rfc2563.txt
'domain-search-list':(119,'B'), # http://www.ietf.org/rfc/rfc3397.txt
'classless-route-121':(121, ':'), # http://www.ietf.org/rfc/rfc3442.txt
'classless-route-249':(249, ':'), ... |
NJ-zero/Android | Request/Client/client_getProductTypes.py | Python | mit | 2,677 | 0.041091 | #coding=utf-8
#author='Shichao-Dong'
import requests
def client_getProductTypes():
url= | "http://172.31.3.73:8888/client/v1/clientAuth.action"
headers={"Connection": "keep-alive",
# "Referer": "http://172.31.3.73:6020/layout_new/login.jsp?url=http://172.31.3.73:6020/layout_new/login.html",
#"Accept-Language": " | zh-CN",
#"x-requested-with": "XMLHttpRequest",
"Content-Type": "application/x-www-form-urlencoded",
"Accept-Encoding": "gzip",
#"Pragm": "=no-cache",
#"Accept": "application/json, text/javascript, */*; q=0.01",
"User-Agent": "waiqin_android_5216010622618132075",
"... |
kernsuite-debian/lofar | SAS/TriggerServices/django_rest/restinterface/triggerinterface/views.py | Python | gpl-3.0 | 9,604 | 0.006247 | """
Handles GET / POST requests by users.
"""
import os
from rest_framework import viewsets
from rest_framework import views
from rest_framework.response import Response
from rest_framework import status
#from serializers import TriggerSerializer
from rest_framework.renderers import JSONRenderer
from rest_framework.p... | g = EventMessage(subject=TRIGGER_SUBMISSION_NOTIFICATION_SUBJECT, content="Trigger received by "+str(user)+" (IP:"+IP+")")
try:
notification_bus.send(msg)
except Exception as err:
logger.error("Could not send notification ->" + str(err))
class TriggerView(views.APIView):
... | ger (i.e. POST for an existing trigger ID), sorry!", status=status.HTTP_405_METHOD_NOT_ALLOWED)
def get(self,request, format=None, **kwargs):
logger.debug('got GET from: '+str(request.META['REMOTE_ADDR']))
try:
if 'pk' in kwargs:
identifier = kwargs.get('pk')
... |
geggo/pyface | pyface/grid/inverted_grid_model.py | Python | bsd-3-clause | 180 | 0.005556 | import logging
logger = logging.getLogger(__name__)
logger.warning('DEPRECATED: pyface.grid, us | e pyface.ui.wx.grid instead.')
from pyface.ui.wx.grid.inverted_grid_mo | del import *
|
kivio/python-structured-logging | tests/test_tracking_logger.py | Python | bsd-3-clause | 3,755 | 0 | import logging
import pytest
def test_tracing_by_function_if_enable(track_logger, handler):
msg1 = 'TEST1'
msg2 = 'TEST2'
msg3 = 'TEST3'
track_logger.setLevel(logging.INFO)
track_logger.enable_tracking()
track_logger.debug(msg1)
track_logger.info(msg2)
track_logger.disable_... | tra | ck_logger, handler):
msg1 = 'TEST1'
msg2 = 'TEST2'
msg3 = 'TEST3'
track_logger.setLevel(logging.INFO)
@track_logger.trace
def trace_func():
track_logger.debug(msg1)
track_logger.info(msg2)
trace_func()
track_logger.debug(msg3)
record = handler.pop()
... |
Flexget/Flexget | flexget/api/__init__.py | Python | mit | 216 | 0 | from .app import A | PIClient, APIResource, api, api_app # noqa
from .core import ( # noqa
authentication,
cached,
database,
format_checker,
plugins,
schema,
| server,
tasks,
user,
)
|
laurentb/weboob | modules/bouygues/module.py | Python | lgpl-3.0 | 2,730 | 0.002568 | # -*- coding: utf-8 -*-
# Copyright(C) 2019 Budget Insight
#
# This file is part of a weboob module.
#
# This weboob module is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the ... | Public License
# along with this weboob module. If not, see <http://www.gnu.org/licenses/>.
from __future__ import unicode_literals
from weboob.tools.backend import Module, BackendConfig
from weboob.capabilities.base import find_object
from weboob.capabilities.bill import CapDocument, Document, SubscriptionNotFound... | alue import Value, ValueBackendPassword
from .browser import BouyguesBrowser
__all__ = ['BouyguesModule']
class BouyguesModule(Module, CapDocument):
NAME = 'bouygues'
DESCRIPTION = 'Bouygues Télécom'
MAINTAINER = 'Florian Duguet'
EMAIL = 'florian.duguet@budget-insight.com'
LICENSE = 'LGPLv3+'
... |
OpenTreeOfLife/peyotl | examples/collection_stats.py | Python | bsd-2-clause | 2,554 | 0.001566 | #!/usr/bin/env python
# Examp | le of getting trees from a collection, and properties for those
# trees and studies
# | Specifically, prints properties important for synthesis for trees in a
# collection
from __future__ import print_function
from peyotl.api import PhylesystemAPI
from peyotl import collection_to_included_trees, read_as_json
from peyotl.nexson_syntax import get_nexml_el
from peyotl.nexson_proxy import NexsonProxy
if __... |
fengtaijun/py_text | src/regex/regex_map.py | Python | apache-2.0 | 2,376 | 0.015812 | #coding=utf-8
'''
Created on 2013年7月13日
@author: huiyugeng
'''
import types
import ndb
import regex
'''
载入解析映射
'''
def load_map(map_file):
map_struct = ndb.load(map_file)
map_list = ndb.execute(map_struct, 'select: map')
return map_list
'''
规则匹配及字段映射
'''
def reflect(map_list,... | if rule_type == '':
rule_type = 'regex'
pattern = map_item.get('pattern') if map_item.has_key('pattern') else ''
if rule_type == 'regex':
if regex.check_line(pattern, line):
value_list = regex.get_line(pattern, line)
map_index = __... | rule_type == 'split':
match = map_item.get('match') if map_item.has_key('match') else ''
if __is_match(match, line):
value_list = line.split(pattern)
map_index = __build_map_index(map_item)
break
map_value = {}
index = ... |
nalabelle/druid-django | query/serializers/QuerySerializer.py | Python | mit | 449 | 0.004454 | from rest_framework import serializers
from druidapi.query.models import QueryModel
class QuerySerializer(serializers.Serializer):
pk = serializers.Inte | gerField(read_only=True)
start_date | = serializers.DateTimeField(required=False)
end_date = serializers.DateTimeField(required=False)
filters = serializers.CharField(required=False)
def create(self, validated_data):
return QueryModel.objects.create(**validated_data)
|
Johnetordoff/osf.io | addons/onedrive/migrations/0003_rename_deleted_field.py | Python | apache-2.0 | 997 | 0.002006 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.15 on 2019-06-27 20:29
from __future__ import unicode_literals
from django.db import migrations
import osf.utils.fields
class Migration(migrations.Migration):
dependencies = [
('addons_onedrive', '000 | 2_auto_20171121_1426'),
]
operations = [
migrations.RenameField(
model_name='nodesettings',
new_name='is_deleted',
old_name='deleted',
),
migrations.RenameField(
model_name='usersettings',
new_name='is_deleted',
old... | model_name='nodesettings',
name='deleted',
field=osf.utils.fields.NonNaiveDateTimeField(blank=True, null=True),
),
migrations.AddField(
model_name='usersettings',
name='deleted',
field=osf.utils.fields.NonNaiveDateTimeField(blank=True, ... |
ddico/odoo | addons/rating/tests/__init__.py | Python | agpl-3.0 | 128 | 0 | # -*- coding: utf-8 -*-
# Part | of Odoo. See LICENSE file for full copyright and licens | ing details.
from . import test_security
|
inFullMobile/BEAM-Framework | beam/config_parser.py | Python | mit | 4,098 | 0.003172 | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
import ConfigParser
from os import path as p
import re
from beam.constans import BEAM_PROJECT_CONF_NAME, BEAM_ROOT_DIR
from beam.cli import UI
from beam.errors import BEAMConfParserException
_sentinel = object()
class PBase(... | f secti | on == self.type:
continue
self.check_for_disallowed_characters(None, section)
if self.get_option(bool, 'ACTIVE', section):
active_components_names[section] = self.get_option(str, 'REPO_SSH_URL', section)
self.check_for_disallowed_characters('REPO_S... |
benosment/generators | generators-for-system-programmers/gentrace.py | Python | gpl-2.0 | 385 | 0.007792 | # gentrace.py
#
# Trace a generator by printing items received
def trace(source):
for item in source:
print item
yield item
# Example use
if __name__ == '__main__':
from apachelog imp | ort *
lines = open("access-log")
| log = trace(apache_log(lines))
r404 = (r for r in log if r['status'] == 404)
for r in r404:
pass
|
jbittel/django-signage | signage/templatetags/active.py | Python | bsd-3-clause | 413 | 0 | import re
from | django import template
from django.core.urlresolvers import NoReverseMatch
from django.core.urlresolvers import reverse
register = template.Library()
@register.simple_tag(takes_context=True)
def active(context, name):
try:
pat | tern = reverse(name)
except NoReverseMatch:
return ''
if re.match(pattern, context['request'].path):
return 'active'
return ''
|
sarvex/tensorflow | tensorflow/python/dlpack/dlpack.py | Python | apache-2.0 | 2,227 | 0.002694 | # Copyright 2020 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | erlying memory to other
framework. This PyCapsule can be consumed only once.
"""
return pywrap_tfe.TFE_ToDlpackCapsule(tf_tensor)
@tf_export("experimental.dlpack.from_dlpack", v1=[])
def from_dlpack(dlcapsule):
"""Returns the Tensorflow eager tensor.
The returned tensor uses the memory shared by dlpack ... | ython
a = tf.experimental.dlpack.from_dlpack(dlcapsule)
# `a` uses the memory shared by dlpack
```
Args:
dlcapsule: A PyCapsule named as dltensor
Returns:
A Tensorflow eager tensor
"""
context.context().ensure_initialized()
return pywrap_tfe.TFE_FromDlpackCapsule(dlcapsule, context.conte... |
xuru/pyvisdk | pyvisdk/do/customization_started_event.py | Python | mit | 1,190 | 0.010084 |
import logging
from pyvisdk.exceptions import InvalidArgumentError
########################################
# Automatically generated, do not edit.
########################################
log = logging.getLogger(__name__)
def CustomizationStartedEvent(vim, *args, **kwargs):
'''The customization sequence has st... | in the VM guest.'''
obj = vim.client.factory.create('ns0:CustomizationStartedEvent')
# do some validation checking...
if (len(args) + len(kwargs)) < 5:
raise IndexError('Expected at least 6 arguments got: %d' % len(args))
required = [ 'template', 'chainId', 'createdTime', 'key', 'userName... | ource', 'datacenter', 'ds', 'dvs',
'fullFormattedMessage', 'host', 'net', 'vm', 'dynamicProperty', 'dynamicType' ]
for name, arg in zip(required+optional, args):
setattr(obj, name, arg)
for name, value in kwargs.items():
if name in required + optional:
setattr(obj, name, va... |
ContinuumIO/ashiba | enaml/enaml/qt/q_resource_helpers.py | Python | bsd-3-clause | 4,734 | 0.000422 | #------------------------------------------------------------------------------
# Copyright (c) 2013, Nucleic Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#-------------------------------------------------... | return qimage
def QIcon_from_Icon(icon):
""" Convert the given Enaml Icon into a QIcon.
Parameters
----------
icon : Icon
The Enaml Icon object.
Returns
-------
result : QIcon
The QIcon instance for the given Enaml icon.
"""
qicon = QIcon()
for icon_image in ... | image:
continue
mode = ICON_MODE[icon_image.mode]
state = ICON_STATE[icon_image.state]
qimage = get_cached_qimage(image)
qpixmap = QPixmap.fromImage(qimage)
qicon.addPixmap(qpixmap, mode, state)
return qicon
def get_cached_qicon(icon):
""" Get the cached QI... |
pp-mo/iris | lib/iris/tests/integration/test_climatology.py | Python | lgpl-3.0 | 3,683 | 0.000272 | # Copyright Iris contributors
#
# This file is part of Iris and is released under the LGPL license.
# See COPYING and COPYING.LESSER in the root of the repository for full
# licensing details.
"""Integration tests for loading and saving netcdf files."""
# Import iris.tests first so that some things can be initialised ... | files.
cls.temp_dir = tempfile.mkdtemp()
cls.path_ref_cdl = path_join(cls.temp_dir, "standard.cdl")
cls.path_ref_nc = path_join(cls.temp_dir, "standard.nc")
# Create reference CDL file.
with open(cls.path_ref_cdl, "w") as f_out:
f_out.write(cls._simple_cdl_string()) |
# Create reference netCDF file from reference CDL.
command = "ncgen -o {} {}".format(cls.path_ref_nc, cls.path_ref_cdl)
check_call(command, shell=True)
cls.path_temp_nc = path_join(cls.temp_dir, "tmp.nc")
# Create reference cube.
cls.cube_ref = stock.climatology_3d()
... |
google/mobly | mobly/controllers/attenuator.py | Python | apache-2.0 | 5,038 | 0.003573 | # Copyright 2016 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | attenuator device. Right now we only
# use telnet lib. This can be refactored when the need | for a different
# communication protocol arises.
KEY_ADDRESS = "address"
KEY_PORT = "port"
# A string that is the model of the attenuator used. This is essentially the
# module name for the underlying driver for the attenuator hardware.
KEY_MODEL = "model"
# A list of strings, each describing what's the connected to t... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.