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
MediaSapiens/autonormix
django/forms/formsets.py
Python
bsd-3-clause
14,683
0.001703
from forms import Form from django.core.exceptions import ValidationError from django.utils.encoding import StrAndUnicode from django.utils.safestring import mark_safe from django.utils.translation import ugettext as _ from fields import IntegerField, BooleanField from widgets import Media, HiddenInput from util import...
L_FORM_COUNT] else: # Use the length of the inital data if it's there, 0 otherwise. initial_forms = self.initial and len(self.initial) or 0 if initial_forms > self.max_num >= 0: initial_forms = self.max_num
return initial_forms def _construct_forms(self): # instantiate all the forms and put them in self.forms self.forms = [] for i in xrange(self.total_form_count()): self.forms.append(self._construct_form(i)) def _construct_form(self, i, **kwargs): """ Instanti...
knitori/shanghai-doll
shanghai/irc/parse.py
Python
gpl-3.0
2,638
0
from collections import namedtuple import re import logging logger = logging.getLogger(__name__) Line = namedtuple('Line', 'prefix command middle params trailing') Prefix = namedtuple('Prefix', 'nick ident hostname') def unpack_prefix(prefix): match = re.match( r'^(?P<nick>[^!@]+)' r'(?:!(?P<ide...
1:]) if ' :' in line: tmp_str, trailing = line.split(' :', 1) tmp_args = tmp_str.split() else: trailing = None tmp_args = line.split() command, *middle = tmp_args params = middle[:] if trailing is not None: params.append(trailing) return Line(prefix, c...
refix) prefix_str = prefix.nick if prefix.ident is not None: prefix_str += '!' + prefix.ident if prefix.hostname is not None: prefix_str += '@' + prefix.hostname return prefix_str def pack_message(msg): if not isinstance(msg, Line): msg = Line(*msg) if msg.prefix is Non...
Reachpodofficial/python-linkedin
linkedin/exceptions.py
Python
mit
872
0
# -*- coding: utf-8 -*- class LinkedInError(Exception): pass class LinkedInBadRequestError(LinkedInError): pass class LinkedInUnauthorizedError(LinkedInError): pass class LinkedInPaymentRequiredError(LinkedInError): pass class LinkedInNotFoundError(LinkedInError)
: pass class LinkedInCon
flictError(LinkedInError): pass class LinkedInForbiddenError(LinkedInError): pass class LinkedInInternalServiceError(LinkedInError): pass ERROR_CODE_EXCEPTION_MAPPING = { 400: LinkedInBadRequestError, 401: LinkedInUnauthorizedError, 402: LinkedInPaymentRequiredError, 403: LinkedInForbi...
anatolieGhebea/contatore
python/RPi.GPIO-0.6.3/RPi/GPIO/__init__.py
Python
mit
1,112
0
""" Copyright (c) 2012-2016 Ben Croston Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribut...
of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRES...
T HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ from RPi._GPIO import * VERSION = '0.6.3'
AQuadroTeam/CellsCycle
CellCycle/MemoryModule/LinkedList.py
Python
mit
3,571
0.010361
# Linked List Utils - LIFO #Interface required: # # Linked List class must have attributes: # - lltail (tail node linker) # - llhead (head node linker) # # Node class must have attributes: # - llprev (previous node linker) # - llnext (next node linker) # Node class must have methods (for debug): # __in...
f getHead(ll): return ll.llhead def push(ll, new): if isEmpty(ll): ll.lltail = new ll.llhead = n
ew new.llnext = None new.llprev = None return tail = ll.lltail #update tail ll.lltail = new #update link of new node new.llprev = tail new.llnext = None #update link of old tail tail.llnext = new def pop(ll): # empty list if isEmpty(ll): retur...
sparkslabs/kamaelia_
Sketches/MPS/BugReports/FixTests/Kamaelia/Examples/Backplane/Forwarding.py
Python
apache-2.0
1,406
0.002845
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1) # # (1) Kamaelia Contributors are listed in the AUTHORS file and at # http://www.kamaelia.org/AUTHORS - please extend this file, # not this notice. # # Licensed under the Apache License, Ver...
eline( Source(), SubscribeTo("broadcast"), ConsoleEchoer(), ).activate() Pipeline( ConsoleReader(), PublishTo("broadcast
", forwarder=True), ConsoleEchoer(), ).run()
Stargrazer82301/CAAPR
CAAPR/CAAPR_AstroMagic/PTS/pts/modeling/fitting/modelgenerators/generator.py
Python
mit
7,222
0.002908
#!/usr/bin/env python # -*- coding: utf8 -*- # ***************************************************************** # ** PTS -- Python Toolkit for working with SKIRT ** # ** © Astronomical Observatory, Ghent University ** # ***************************************************************** ##...
meters self.parameters = OrderedDict() # ----------------------------------------------------------------- @property def parameter_names(self): """ This function ... :return: """
return self.ranges.keys() # ----------------------------------------------------------------- @property def nparameters(self): """ This function ... :return: """ return len(self.ranges) # ----------------------------------------------------------------- ...
AMOboxTV/AMOBox.LegoBuild
script.module.liveresolver/lib/js2py/translators/std_nodes.py
Python
gpl-2.0
15,390
0.008577
from pyjsparserdata import * class BaseNode: def finish(self): pass def finishArrayExpression(self, elements): self.type = Syntax.ArrayExpression self.elements = elements self.finish() return self def finishArrayPattern(se...
ression self.operator
= operator self.argument = argument self.prefix = False self.finish() return self def finishProgram(self, body): self.type = Syntax.Program self.body = body self.finish() return self def finishPyi...
rrauenza/factory_boy
setup.py
Python
mit
2,431
0.001235
#!/usr/bin/env python # -*- coding: utf-8 -*- import codecs import os import re import sys from setuptools import setup root_dir = os.path.abspath(os.path.dirname(__file__)) def get_version(package_name): version_re = re.compile(r"^__version__ = [\"']([\w_.-]+)[\"']$") package_components = package_name.spl...
uptools>=0.8', ], tests_require=[ #'mock', ], classifiers=[ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "Framework :: Django", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Pr...
hon", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.4", "Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6", "Programming Lan...
gymnasium/edx-platform
lms/djangoapps/courseware/tests/test_video_mongo.py
Python
agpl-3.0
91,091
0.002582
# -*- coding: utf-8 -*- """ Video xmodule tests in mongo. """ import json from collections import OrderedDict from uuid import uuid4 from tempfile import mkdtemp import shutil import ddt from django.conf import settings from django.core.files import File from django.core.files.base import ContentFile from django.test...
c="example.mp4"/> <source src="example.webm"/> </video> """ MODEL_DATA = { 'data': DATA, } METADATA = {} def test_video_constructor(self): """Make sure that if the 'youtube' attribute is omitted in XML, then the templat
e generates an empty string for the YouTube streams. """ context = self.item_descriptor.render(STUDENT_VIEW).content sources = [u'example.mp4', u'example.webm'] expected_context = { 'autoadvance_enabled': False, 'branding_info': None, 'license': None,...
google/google-ctf
third_party/edk2/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/analyze_dxp.py
Python
apache-2.0
4,312
0.000696
""" Some helper functions to analyze the output of sys.getdxp() (which is only available if Python was built with -DDYNAMIC_EXECUTION_PROFILE). These will tell you which opcodes have been executed most frequently in the current process, and, if Python was also built with -DDXPAIRS, will tell you which instruction ...
""" if profile is None: profile = snapshot_profile() def seq(): for _, ops, count in common_pairs(profile): yield "%s: %s\n" % (count, ops) return ''
.join(seq())
chen0031/nupic
tests/integration/nupic/opf/opf_description_template_test/opf_description_template_test.py
Python
agpl-3.0
10,082
0.008133
#!/usr/bin/env python # ---------------------------------------------------------------------- # Numenta Platform for Intelligent Computing (NuPIC) # Copyright (C) 2014, Numenta, Inc. Unless you have an agreement # with Numenta, Inc., for a separate license for this software code, the # following terms and conditions ...
ent in filesystem" % self.__opfExperimentsParentDir _debugOut("self.__opfExperimentsParentDir=<%s>" % self.__opfExperimentsParentDir) def getOpfRunExperimentPyPath(self): return os.path.join(self.__opfBinDir, "run_opf_experiment.py") def getOpfExperimentPath(self, experimentName): """ ex...
eriment. Returns: absolute path to the experiment directory """ path = os.path.join(self.__opfExperimentsParentDir, experimentName) assert os.path.isdir(path), \ "Experiment path %s doesn't exist or is not a directory" % (path,) return path class MyTestCaseBase(HelperTestCaseBas...
pf4d/dolfin-adjoint
dolfin_adjoint/projection.py
Python
lgpl-3.0
3,054
0.003929
import solving import backend if backend.__name__ == "dolfin": import backend.fem.projection import misc import libadjoint import adjglobals import adjlinalg import utils def project_dolfin(v, V=None, bcs=None, mesh=None, solver_type="cg", preconditioner_type="default", form_comp
iler_parameters=None, annotate=None, name=None): '''The project call performs an equation solve, and so it too must be annotated so that the adjoint and tangent linear models may be constructed automatically by libadjoint. To disable the annotation of this function, just pass :py:data:`annotate=False`. Thi...
rrelevant or diagnostic for the purposes of the adjoint computation (such as projecting fields to other function spaces for the purposes of visualisation).''' to_annotate = utils.to_annotate(annotate) if isinstance(v, backend.Expression) and (annotate is not True): to_annotate = False if ...
saketkc/pyseqlogo
tests/__init__.py
Python
mit
64
0
# -*- coding: utf-8 -
*- """Unit test package for pyseqlo
go."""
syscoin/syscoin
test/functional/rpc_misc.py
Python
mit
4,423
0.002261
#!/usr/bin/env python3 # Copyright (c) 2019-2021 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test RPC misc output.""" import xml.etree.ElementTree as ET from test_framework.test_framework import ...
stFramework): def set_test_params(self): self.num_nodes = 1 self.supports_cli = False
def run_test(self): node = self.nodes[0] self.log.info("test CHECK_NONFATAL") assert_raises_rpc_error( -1, 'Internal bug detected: \'request.params[9].get_str() != "trigger_internal_bug"\'', lambda: node.echo(arg9='trigger_internal_bug'), ) ...
evrom/genitag
controllers/config/profile/name.py
Python
gpl-2.0
1,881
0
from bottle import request from sqlalchemy import exc from libraries.database import engine as db from libraries.template import view from libraries.status import Status from libraries.authentication import login_required from libraries.forms import Name as Form from libraries.forms import Blank as BlankForm from libra...
us.success = "Updated name" except exc.SQLAlchemyError as message: status.danger = message if request.method == 'POST' and\ request.query['action'] == 'delete': blank_form = BlankForm(re
quest.forms) if blank_form.validate(): try: conn = db.engine.connect() conn.execute(name_delete, username=username) conn.close() status.success = "Deleted name" except exc.SQLAlchemyError as mess...
StackStorm/st2
st2tests/st2tests/config.py
Python
apache-2.0
16,363
0.00275
# Copyright 2020 The StackStorm Authors. # Copyright 2019 Extreme Networks, 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 ...
le used to identify the local connection (client).", ), cfg
.StrOpt( "ssl_cert_reqs", default=None, choices="none, optional, required", help="Specifies whether a certificate is required from the other side of the " "connection, and whether it will be validated if provided.", ), cfg.StrOpt( "...
rtrouton/Recipes-for-AutoPkg
android_sdk/AndroidExtraXMLParser.py
Python
bsd-3-clause
5,235
0.009169
#!/usr/bin/python # # Copyright 2014-2015 Facebook, 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 l...
cord.find('%sname-display' % schema).text != self.env['name']: continue for key, outputVar in self.env['tags'].
iteritems(): print "Key: %s" % key if key == 'license': # Look for license - it's a special case match = root.findall('%s%s' % (schema, 'license')) self.env[self.env['tags']['license']] = \ match[-1].text.encode('ascii', 'ignore').encode('string-escape')...
opensciencegrid/osg-build
osgbuild/svn.py
Python
apache-2.0
10,034
0.002691
"""Helper functions for an SVN build.""" from __future__ import absolute_import from __future__ import print_function import re import os import errno from .constants import SVN_ROOT, SVN_REDHAT_PATH, SVN_RESTRICTED_BRANCHES, KOJI_RESTRICTED_TARGETS from .error import Error, SVNError, UsageError from . import utils ...
code %d getting SVN listing of %s (rev %s). Output:\n%s" % (err, url, rev, out)) for line in out.split("\n"): if line.startswith('osg/') or line.startswith('upstream/'): return True return False # # Branch checking # # We need to forbid building from certain SVN branches into certain Koji ...
aining the restricted SVN branches and one containing the # restricted Koji targets. # # We're permissive by default: if neither the branch nor the target match any # of the regexps in their respective dicts, the build is allowed. On the other # hand, if both are restricted then the branch name has to match the target ...
kenshay/ImageScript
ProgramData/SystemFiles/Python/Lib/site-packages/elan/onHoldScripts/1_SetIRTemplatesToManual.py
Python
gpl-3.0
383
0.010444
from elan import * #Set_Location_And_Weather_By_Country_City.py Configurator.Start() Configurator.Wait() sleep(3) Configura
tor.media.Click() Configurator.interfacetemplates.Click() for i in range(100): try: Configurator.ComboBox.Select(0,1) break
except: sleep(2) print("Try again") Configurator.apply.Click() Configurator.CloseAndClean()
bhansa/fireball
pyvenv/Lib/site-packages/pygame/tests/color_test.py
Python
gpl-3.0
37,664
0.013727
#################################### IMPORTS ################################### if __name__ == '__main__': import sys import os pkg_dir = os.path.split(os.path.abspath(__file__))[0] parent_dir, pkg_name = os.path.split(pkg_dir) is_pygame_pkg = (pkg_name == 'tests' and os.path....
ng_ import math import operator ################################### CONSTANTS ################################## rgba_vals = [0, 1, 62, 63, 126, 127, 255] rgba_combinations = [ (r,g,b,a) for r in rgba_vals for g in rgba_vals for b in rgba_vals ...
gba_combos_Color_generator (): for rgba in rgba_combinations: yield pygame.Color(*rgba) # Python gamma correct def gamma_correct (rgba_0_255, gamma): corrected = round(255.0 * math.pow(rgba_0_255/255.0, gamma)) return max(min( int(corrected), 255), 0) ##############################################...
lepistone/server-tools
users_ldap_mail/__init__.py
Python
agpl-3.0
1,000
0
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # This module copyright (C) 2013 Daniel Reis. # # 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, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTAB...
he GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from . import users_ldap_model
smileboywtu/SQLite3
coffee-shop/demon/select-like.py
Python
gpl-2.0
1,166
0.004288
# select the data using the like API # use the python 3.5 as default import sqlite3 def select_data(db_name, table_name, condition): "find all the data with the same kind" with sqlite3.connect(db_name) as db: cursor = db.cursor() cursor.execute("SELECT title, releaseYear FROM {0} WHERE title L...
sult) table_name = ("film", "genre") condition = (
"Die Hard", "Action", "Thriller") result = select_from_multi(db_name, table_name, condition) print(result)
tanglei528/nova
nova/tests/api/openstack/compute/contrib/test_services.py
Python
apache-2.0
22,424
0.002809
# Copyright 2012 IBM Corp. # # 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 t...
e_get_all(fake_services_list)) self.stubs.Set(
db, "service_get_by_args", fake_db_service_get_by_host_binary(fake_services_list)) self.stubs.Set(db, "service_update", fake_db_service_update(fake_services_list)) def test_services_list(self): req = FakeRequest() res_dict = self.controller.inde...
sveiow/doitpy
AutoAnswer/oldversion/kemuyimoni/字典加工/合并字典方式二.py
Python
gpl-2.0
758
0.028767
#coding=utf-8 #介紹:合併字典方式二 import pickle import os hashdataS = {} hashdataP = {} def updata(self,hashdic): dic = open(self, 'rb') newdata = cPickle.load(dic) hashdic.update(newdata) def main(dict1,dict2,hashname,new): try: updata(dict1,hashname) #载入 print 'befor: %s' %...
cPickle.dump(hashname, output) output.close() except IOError: pass os.rename('DictS.K','Dict
S.old') os.rename('DictP.K','DictP.old') main('DictS.old','oneDictS.kmy',hashdataS,'DictS.K') main('DictP.old','oneDictP.kmy',hashdataP,'DictP.K')
havard024/prego
reports/models.py
Python
mit
2,739
0.00073
# encoding: utf-8 # Copyright 2011 Tree.io Limited # This file is part of Treeio. # License www.tree.io/license """ Reports models """ from django.db import models from django.core.urlresolvers import reverse from django.utils.translation import ugettext as _ from treeio.core.models import Object from jinja2.filters ...
ctions.has_key(self.aggregation): return _(aggregate_functions[self.aggregation]['description']) return '' class Chart(Object): name = models.CharField(max_length=255) report = models.ForeignKey(Report) options = models.TextField(blank=True, null=True) access_inherit = ('report', ...
return self.name def get_absolute_url(self): "Returns absolute URL for the Report" try: return reverse('reports_report_view', args=[self.report_id]) except Exception: pass
acmaheri/sms-tools
lectures/6-Harmonic-model/plots-code/f0-TWM-errors-1.py
Python
agpl-3.0
3,586
0.01952
import numpy as np import matplotlib.pyplot as plt from scipy.signal import hamming, triang, blackman import math import sys, os, functools, time sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), '../../../software/models/')) import dftModel as DFT import utilFunctions as UF def TWM (pfreq, p...
np.zeros(harmonic.size) # initialize MP errors MaxNMP = min(10, pfreq.size) for i in range(0, f0c.size) : # measured to predicted mismatch error nharm = np.round(pfreq[:MaxNMP]/f0c[i]) nharm = (nharm>=1)*nharm + (nharm<1) FreqDistance = abs(pfreq[:MaxNMP] - nharm*f0c[i...
Mag-Amax)/20) ErrorMP[i] = sum(MagFactor * (Ponddif + MagFactor*(q*Ponddif-r))) Error = (ErrorPM[0]/MaxNPM) + (rho*ErrorMP/MaxNMP) # total error f0index = np.argmin(Error) # get the smallest error f0 = f0c[f0index] # f0 with the smallest error return f...
hoidn/LCLS
dataccess/tests/test_psget.py
Python
gpl-3.0
30
0.033333
from data
ccess import
psget
presidentielcoin/presidentielcoin
contrib/devtools/fix-copyright-headers.py
Python
mit
1,400
0.017143
#!/usr/bin/env python ''' Run this script to upd
ate all the copyright headers of files that were changed this year. For example: // Copyright (c) 2009-2012 The Presidentielcoin Core developers it will change it to // Copyright (c) 2009-2015 The Presidentielcoin Core developers ''' import os import time import re year = time.gmtime()[0] CMD_GIT_DATE = 'git log -...
"perl -pi -e 's/(20\d\d)(?:-20\d\d)? The Presidentielcoin/$1-%s The Presidentielcoin/' %s" REGEX_CURRENT= re.compile("%s The Presidentielcoin" % year) CMD_LIST_FILES= "find %s | grep %s" FOLDERS = ["./qa", "./src"] EXTENSIONS = [".cpp",".h", ".py"] def get_git_date(file_path): r = os.popen(CMD_GIT_DATE % file_path...
Nymphet/sexinsex-crawler
page_aids_extractor.py
Python
apache-2.0
1,319
0.009856
# -*- coding: utf-8 -*- ''' Used to extract attachment ids from html files in ./html folder. Extracted ids are saved in ./pickle folder''' from urllib import parse import os, re, pickle from config import path attachment = re.compile(r'''<a href="attachment\.php\?aid=(\d+)" target="_blank">''') failcnt = 0 ai...
if p: flag = False print('Failed to extract from',parse.unquote_plus(htmlfile)) failcnt += 1 break if flag: for line in lin
es: a = attachment.search(line) if a: aids_list.append(a.group(1)) print('OK') s_aids_list = list(set(aids_list)) print(s_aids_list) print('%d attachment ids found'%len(s_aids_list)) print('saving attachment ids to pickle/aids_list.p') with open('%s/pickl...
sairon/score-phorum
src/score/settings/debug.py
Python
bsd-3-clause
451
0
from .base import * DEBUG = True INSTALLED
_APPS += ( 'debug_toolbar', ) SENDFILE_BACKEND = "sendfile.backends.development" MIDDLEWARE = ( 'debug_toolbar.middleware.DebugToolbarMiddleware', ) + MIDDLEWARE # Use default Google test keys and silence error del RECAPTCHA_PUBLIC_KEY del RECAPTCHA_PRIVATE_KEY SILENCED_SYSTEM_CHECKS = ['captcha.recapt
cha_test_key_error'] DEBUG_TOOLBAR_CONFIG = { "SHOW_TOOLBAR_CALLBACK": lambda x: True }
tommyip/zulip
zerver/tests/test_auth_backends.py
Python
apache-2.0
153,893
0.002918
# -*- coding: utf-8 -*- from django.conf import settings from django.core import mail from django.http import HttpResponse from django.test import override_settings from django_auth_ldap.backend import LDAPBackend, _LDAPUser from django.test.client import RequestFactory from django.utils.timezone import now as timezone...
use_dummy_backend=False)) def setup_subdomain(self, user_profile: UserProfile) -> None: realm = user_profile.realm realm.string_id = 'zulip' realm.sa
ve() def test_email_auth_backend(self) -> None: username = self.get_username() user_profile = self.example_user('hamlet') password = "testpassword" user_profile.set_password(password) user_profile.save() with mock.patch('zproject.backends.email_auth_enabled', ...
By0ute/pyqt-collapsable-widget
code/FrameLayout.py
Python
mit
3,949
0.001773
__author__ = 'Caroline Beyne' from PyQt4 import QtGui, QtCore class FrameLayout(QtGui.QWidget): def __init__(self, parent=None, title=None): QtGui.QFrame.__init__(self, parent=parent) self._is_collasped = True self._title_frame = None self._content, self._content_layout = (None, N...
arrow_horizontal = (QtCore.QPointF(7.0, 8.0), QtCore.QPointF(17.0, 8.0), QtCore.QPointF(12.0, 13.0))
# vertical == 1 self._arrow_vertical = (QtCore.QPointF(8.0, 7.0), QtCore.QPointF(13.0, 12.0), QtCore.QPointF(8.0, 17.0)) # arrow self._arrow = None self.setArrow(int(collapsed)) def setArrow(self, arrow_dir): if arrow_dir: self._ar...
FuzzyHobbit/django-bitcoin
django_bitcoin/migrations/0003_auto__add_unique_bitcoinaddress_address.py
Python
mit
5,057
0.007317
# 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): # Adding unique constraint on 'BitcoinAddress', fields ['address'] db.create_unique('django_bitcoin_bitcoi...
'django_bitcoin.Wallet']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'to_bitcoinaddress': ('django.db.models.fields.CharField', [], {'max_length': '50', 'blank': 'True'}), 'to_wallet': ('django.db.models.fields.related
.ForeignKey', [], {'related_name': "'received_transactions'", 'null': 'True', 'to': "orm['django_bitcoin.Wallet']"}) } } complete_apps = ['django_bitcoin']
Akagi201/learning-python
lpthw/ex33.py
Python
mit
288
0
#!/usr/bin/e
nv python # Exercis
e 33: While Loops i = 0 numbers = [] while i < 6: print "At the top i is %d" % i numbers.append(i) i = i + 1 print "Numbers now: ", numbers print "At the bottom i is %d" % i print "The numbers: " for num in numbers: print num
javierj/kobudo-katas
Kata-RestConsumer/gindex.py
Python
apache-2.0
1,259
0.001589
__author__ = 'Javier' class Project(object): def __init__(self, forks, stars, watchs): self._forks = int(forks) self._stars = int(stars) self._watchs = int(watchs) @property def forks(self): return self._forks @property def stars(self): return self._stars...
ks * 3 + project.stars + project.watchs class ProjectRepositoryService(object): def __init__(self, conector): self.conector = conector self.project_factory = ProjectFactory() def find(self, user, repo_name): raw_json = self._read_repo(user, repo_name) return self.project_fact...
repo(self, user, repo_name): repos = self.conector.read_all(user) for repo in repos: if repo['name'] == repo_name: return repo return None class ProjectFactory(object): def build_from(self, json_project): return Project(json_project['forks_count'], ...
yosisa/TracBlockdiag
tests/test_cache.py
Python
mit
2,291
0
# -*- coding: utf-8 -*- import time import unittest from tracblockdiag import cache class TestFunction(unittest.TestCase): def test_is_obsolete(self): entry = {'time': time.time()} self.assertTrue(cache.is_obsolete(entry, 0)) self.assertFalse(cache.is_obsolete(entry, 3600)) def test...
c.run() self.assertEqual(cache.cache, expect) # not run yet cache.cache['b']['time'] -= 60 cache.cache['c'] = {'time': time.time() - 60} expect = cache.cache.copy() self.gc.run() self.assertEqual(cache.cache, expect) # run and collect all entry sel...
def setUp(self): cache.cache = {} self.args = (1, 2) self.key = cache.compute_key(self.foo_meth, self.args, {}) def foo_meth(self, a, b): return a + b def test_memoize(self): # execute function and cache result meth = cache.memoize(300)(self.foo_meth) ...
crossroadchurch/paul
tests/interfaces/openlp_plugins/songs/forms/__init__.py
Python
gpl-2.0
1,544
0
# -*- coding: utf-8 -*- # vim: autoindent shiftwidth=4 expandtab textwidth=120 tabstop=4 softtabstop=4 ############################################################################### # OpenLP - Open Source Lyrics Projection # # ------------------------------------------------------...
# # This program is distributed in the hope that it will be useful, but WITHOUT
# # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # # FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for # # more details. # # ...
rameshbabu79/fabric
bddtests/orderer/ab_pb2_grpc.py
Python
apache-2.0
2,507
0.003989
import grpc from grpc.framework.common import cardinality from grpc.framework.interfaces.face import utilities as face_utilities import common.common_pb2 as common_dot_common__pb2 import orderer.ab_pb2 as orderer_dot_ab__pb2 import common.common_pb2 as common_dot_common__pb2 import orderer.ab_pb2 as orderer_dot_ab__pb...
_dot_common__pb2.Envelope.FromString, response_serializer=orderer_dot_ab__pb2.DeliverResponse.SerializeToString, ), } generic_handler = grpc.method_handlers_generic_handler( 'orderer.AtomicBroadcast', rpc_meth
od_handlers) server.add_generic_rpc_handlers((generic_handler,))
eayunstack/neutron
neutron/db/migration/alembic_migrations/versions/liberty/expand/34af2b5c5a59_add_dns_name_to_port.py
Python
apache-2.0
1,230
0
# Copyright 2015 Rackspace # # 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 t...
015-08-23 00:22:47.618593 """ from alembic import op from neutron_lib.db import constants import sqlalchemy as sa from neutron.db import migration # revision identifiers, used by Alembic. revision = '34af2b5c5a59' down_revision = '9859ac9c136' # milestone identifier, used by neutron-db-manage neutron_milestone = [...
FIELD_SIZE), nullable=True))
yunlzheng/tomatodo
tt/handle/backbone.py
Python
mit
3,975
0.000505
# coding: utf-8 import json import functools import tornado.web from tornado.log import app_log from tornado.util import import_object from .base import Base from tt.model.user import User def load_model(func): """注入一个Model参数给函数.""" @functools.wraps(func) def wrapper(self, *args, **kwargs): ...
raise tornado.web.HTTPError(404) print 'revice request args: {0} kwargs: {1}'.format(args, kwargs) return func(self, *args, **kwargs) return wrapper class BackboneHandler(Base): def initialize(self, auth=True): self.auth = auth def prepare(self): if self...
rrent_user(): raise tornado.web.HTTPError(403) def encode(self, data): return json.dumps(data) def decode(self, data): return json.loads(data) def get(self, *args, **kwargs): self.set_header("Content-Type", "application/json; charset=UTF-8") if s...
tensorflow/datasets
tensorflow_datasets/text/quac/quac_test.py
Python
apache-2.0
1,116
0.00448
# coding=utf-8 # Copyright 2022 The TensorFlow Datasets Authors. # # 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 appl...
): """Tests for quac dataset.""" DATASET_CLASS = quac.Quac DL_EXTRACT_RESULT = { "train": "train_v0.2.json", "val": "val_v0.2.json", } SPLITS = { "train": 8, # Number of
fake train example "validation": 8, # Number of fake validation example } if __name__ == "__main__": tfds.testing.test_main()
oVirt/jenkins
test3/test_usrc_updater.py
Python
gpl-3.0
2,549
0
from typing import Callable from unittest.mock import MagicMock import pytest import yaml from stdci_tools.usrc_updater import updater_main_cli from stdci_libs.git_utils import git_rev_parse @pytest.fixture def upstream_repo(gitrepo): return gitrepo( 'upstream', { 'msg': 'First upstr...
{ 'msg': 'First commit', 'files': { 'upstream_sources.yaml': yaml.safe_dump({ 'git': [ { 'url': f'{str(upstream_repo)}', 'commit': 'this-should-be-updated-by-usrc', ...
}, ], }) }, } ) @pytest.mark.parametrize('call_with_env', [True, False]) def test_updater_main( tmpdir, upstream_repo, midstream_repo, git_at, monkeypatch, gerrit_push_map, run_click_command, call_with_env): monkeypa...
chemelnucfin/tensorflow
tensorflow/python/tpu/tpu_strategy_util.py
Python
apache-2.0
4,954
0.005652
# 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 applica...
OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """TPU specific APIs to
be used in conjunction with TPU Strategy.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.core.protobuf import config_pb2 from tensorflow.python.client import session as session_lib from tensorflow.python.distribute.cluster_resolver impor...
matrix-org/synapse
synapse/config/emailconfig.py
Python
apache-2.0
22,741
0.002946
# Copyright 2015-2016 OpenMarket Ltd # Copyright 2017-2018 New Vector Ltd # Copyright 2019 The Matrix.org Foundation C.I.C. # # 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....
enabled on this homeserver due to a partial 'email' block. However, the following required keys are missing: %s """ DEFAULT_SUBJECTS = { "message_from_person_in_room": "[%(app)s] You h
ave a message on %(app)s from %(person)s in the %(room)s room...", "message_from_person": "[%(app)s] You have a message on %(app)s from %(person)s...", "messages_from_person": "[%(app)s] You have messages on %(app)s from %(person)s...", "messages_in_room": "[%(app)s] You have messages on %(app)s in the %(ro...
open-power-host-os/builds
lib/subcommands/update_metapackage.py
Python
gpl-3.0
2,543
0.000393
# Copyright (C) IBM Corp. 2017. # # 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 distributed in the...
or "Update {} dependencies".format(METAPACKAGE_NAME)) versions_repo.commit_changes( commit_message, updater_name, updater_email) if push_updates: LOG.info("Pushing updated {} files".format(METAPACKAGE
_NAME)) versions_repo.push_head_commits(push_repo_url, push_repo_branch) LOG.info("Metapackage updated succesfully")
xingyepei/edx-platform
openedx/core/djangoapps/credit/migrations/0014_auto__add_field_creditprovider_fulfillment_instructions.py
Python
agpl-3.0
12,629
0.00776
# -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'CreditProvider.fulfillment_instructions' db.add_column('c...
'Meta': {'object_name': 'CreditCourse'}, 'course_key': ('xmodule_django.models.CourseKeyField', [], {'unique': 'True', 'max_length': '255', 'db_index': 'True'}), 'enabled': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'id': ('django.db.models.fields.Auto...
}, 'credit.crediteligibility': { 'Meta': {'unique_together': "(('username', 'course'),)", 'object_name': 'CreditEligibility'}, 'course': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'eligibilities'", 'to': "orm['credit.CreditCourse']"}), 'created': ...
eigenholser/jpeg_rename
tests/test_filemap_build_new_fn.py
Python
mit
1,352
0.007396
import os import re import sys import pytest from mock import Mock, patch app_path = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, app_path + '/../') f
rom photo_rename import Filemap from photo_rename import * from .stubs import * from . import TEST_FILEMAP_BUILD_DST_FN class TestFilemapBuildNewFn(object): """ Tests for method build_dst_fn() are in this class. """ skiptests = not TEST
_FILEMAP_BUILD_DST_FN @pytest.mark.skipif(skiptests, reason="Work in progress") @pytest.mark.parametrize( "src_fn, image_type, expected_dst_fn, exif_data", [ (SRC_FN_JPG_LOWER, IMAGE_TYPE_JPEG, EXIF_DATA_VALID['expected_dst_fn'], EXIF_DATA_VALID['exif_data'],), (...
alex/raven
raven/utils/serializer/__init__.py
Python
bsd-3-clause
287
0
""" raven.utils.serializer ~~~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2010 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from raven.utils.serializer.base import Serializer from raven.utils.serializer.manager import register, transfo
rm
aalto-trafficsense/regular-routes-server
pyfiles/prediction/run_test.py
Python
mit
836
0.009569
#!/usr/bin/python """ Testing the database connection ------------------------------- Connect to the surver and request a list of device IDs """ from numpy import * set_printoptions(precision=5, suppress=True) from .db_utils import get_cursor def dev_ids(cur): try: cur.execute("""SELECT DIS...
e_data""") except: return "I can't SELECT from device_data" return cur.fetchall() def num_trace(cur, d_id): try: cur.execute("""SELECT COUNT(*) from averaged_location WHERE device_id = %s """, (str(d_id),)) except: return "I can't SELECT from device_data" return cur.fetch...
int("[%d] trace: %d" % (i_d, c))
mindbody/API-Examples
SDKs/Python/swagger_client/models/get_contracts_request.py
Python
bsd-2-clause
8,098
0.000123
# coding: utf-8 """ MINDBODY Public API No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501 OpenAPI spec version: v6 Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint import re # noqa: F401 impor...
@property def limit(self): """Gets the limit of this GetContractsRequest. # noqa: E501 Number of results to include, defaults to 100 # noqa: E501 :return: The limit of this GetContractsRequest. # noqa: E501 :rtype: int """ return self._limit @limit.setter ...
lf, limit): """Sets the limit of this GetContractsRequest. Number of results to include, defaults to 100 # noqa: E501 :param limit: The limit of this GetContractsRequest. # noqa: E501 :type: int """ self._limit = limit @property def offset(self): """...
RedeNeural/estacao-meteorologica
estacaometeorologica/core/tests/test_views.py
Python
gpl-3.0
1,274
0.002355
# -*- coding:utf-8 -*- import vcr from django.conf import settings from django.test import TestCase from django.urls import reverse_lazy from estacaometeorologica.core.models import EstacaoMeteorologica from estacaometeorologica.core.api_morangos import get_data class IndexViewTestCase(TestCase): @vcr.use_cas...
ologica.objects.count(), 987) response = self.client.get(reverse_lazy('index'))
self.assertTrue(response.context_data.get('temperature')) self.assertTrue(response.context_data.get('humidity')) self.assertTrue(response.context_data.get('date')) class EstacaoMeteorologicaViewTestCase(TestCase): @vcr.use_cassette(settings.BASE_DIR + '/estacaometeorologica/core/tests/cas...
tryolabs/luminoth
luminoth/tools/dataset/readers/object_detection/imagenet.py
Python
bsd-3-clause
5,855
0
import json import os import six import tensorflow as tf from PIL import Image from luminoth.tools.dataset.readers import InvalidDataDirectory from luminoth.tools.dataset.readers.object_detection import ( ObjectDetectionReader ) from luminoth.utils.dataset import read_xml, read_image WNIDS_FILE = 'data/imagenet_...
on' class ImageNetReader(ObjectDetectionReader): def __init__(self, data_dir, split, **kwargs): super(ImageNetReader, self).__init__(**kwargs) self._split = split self._data_dir = data_dir self._imagesets_path = os.path.join(self._dat
a_dir, 'ImageSets', 'DET') self._images_path = os.path.join(self._data_dir, 'Data', 'DET',) self._annotations_path = os.path.join( self._data_dir, 'Annotations', 'DET' ) self.yielded_records = 0 self.errors = 0 # Validate Imagenet structure in `data_dir`. ...
PATechmasters/techmaster-ctf
api/api/setup.py
Python
mit
873
0.001145
""" Setup for the API """ import api log = api.logger.use(__name__) def index_mongo(): """ Ensure the mongo collections are indexed. """ db = api.common.get_conn() log.debug("Ensuring mongo is indexed.") db.users.ensure_index("uid", unique=True, name="unique uid")
db.users.ensure_index("username", unique=True, name="unique username") db.groups.ensure_index("gid", unique=True, name="unique gid") db.problems.ensure_index("pid", unique=True, name="unique pid") db.submissions.ensure_index("tid", name="submission tids") d
b.ssh.ensure_index("tid", unique=True, name="unique ssh tid") db.teams.ensure_index("team_name", unique=True, name="unique team names") db.cache.ensure_index("expireAt", expireAfterSeconds=0) db.cache.ensure_index("kwargs", name="kwargs") db.cache.ensure_index("args", name="args")
wxgeo/geophar
wxgeometrie/sympy/liealgebras/tests/test_weyl_group.py
Python
gpl-2.0
1,501
0.00533
from sympy.liealgebras.weyl_group import WeylGroup from sympy.matrices import Matrix def test_weyl_group(): c = WeylGroup("A3") assert c.matrix_form('r1*r2') == Matrix([[0, 0, 1, 0], [1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 1]]) assert c.generators() == ['r1', 'r2', 'r3'] assert c.group_order() ==...
2') == 3 assert f.element_order('r2*r1*r1*r2') == 1 assert f.matrix_form('r1*r2*r1*r2') == Matrix([[0, 1, 0], [0, 0, 1], [1, 0, 0]]) g =
WeylGroup("F4") assert g.matrix_form('r2*r3') == Matrix([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, -1], [0, 0, 1, 0]]) assert g.element_order('r2*r3') == 4 h = WeylGroup("E6") assert h.group_order() == 51840
fabteam1/komsukomsuhuhu
komsukomsuhuu/entities/admin.py
Python
mit
504
0.001984
from django.contrib import admin # Register your models here. from .models import Topic, Post class PostAdmin(admin.ModelAdmin): list_display = ['owner', 'topic', 'date_created'] class PostInline(admin.TabularInline): model = Post
extra = 0 fields = ['owner', 'con
tent', 'date_created'] class TopicAdmin(admin.ModelAdmin): inlines = [PostInline] list_display = ['group', 'owner', 'date_created'] admin.site.register(Post, PostAdmin) admin.site.register(Topic, TopicAdmin)
johnbachman/indra
indra/ontology/app/app.py
Python
bsd-2-clause
2,290
0
"""This service implements all base functions of the ontology graph as a REST service. The three key functions that most ontology methods rely on are child_rel, parent_rel, and get_node_property. There are a few other bookkeeping functions that also need to be implemented here since they access ontology attributes dire...
et_node_property', methods=['GET']) def get_node_property(): ont = request.json.get('ontology') ontology = ontologies.get(ont) kwargs = ('ns', 'id', 'property') return jsonify(ontology.get_node_property(
**{k: v for k, v in request.json.items() if k in kwargs})) @app.route('/get_id_from_name', methods=['GET']) def get_id_from_name(): ont = request.json.get('ontology') ontology = ontologies.get(ont) kwargs = ('ns', 'name') return jsonify(ontology.get_id_from_name( **{k: v for k, v in r...
CloudI/CloudI
src/service_api/python/jsonrpclib/tests/test_server.py
Python
mit
1,597
0
#!/usr/bin/python # -- Content-Encoding: UTF-8 -- """ Tests the pooled server :license: Apache License 2.0 """ # JSON-RPC library from jsonrpclib import ServerProxy from jso
nrpclib.SimpleJSONRPCServer import PooledJSONRPCServer from jsonrpclib.threadpool import ThreadPool # Standard library import random import threading import unittest # ------------------------------------------------------------------------------ def add(a, b): return a+b class PooledServerTests(unittest.Te
stCase): """ These tests verify that the pooled server works correctly """ def test_default_pool(self, pool=None): """ Tests the default pool """ # Setup server server = PooledJSONRPCServer(("localhost", 0), thread_pool=pool) server.register_function(add) ...
open-synergy/social
mass_mailing_statistic_extra/tests/test_mail_mail.py
Python
agpl-3.0
2,279
0
# -*- coding: utf-8 -*- # © 2015 Antiun Ingenieria S.L. - Antonio Espinosa # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from openerp.tests.common import TransactionCase from openerp import fields from email.utils import formataddr # One test case per method class TestResPartner(TransactionCas...
'model': 'res.partner', 'res_id': partn
er_a.id, })], 'model': 'res.partner', 'res_id': partner_a.id, }) orig_list = [ partner_a.email, formataddr((partner_b.name, partner_b.email)), formataddr((partner_c.name, partner_c.email)), ] self.assertEqual(len(ma...
xpybuild/xpybuild
tests/correctness/targets/CCompilationNoIncludes/run.py
Python
apache-2.0
468
0.017094
from pysys.constants import * from xpybuild.xpybuild_basetest import XpybuildBaseTest class PySysTe
st(XpybuildBaseTest): def execute(self): msg = self.xpybuild(shouldFail=False, args=[], buildfile='root.xpybuild.py') self.startProcess(self.output+'/build-output/test', [], stdout='test.out', stderr='test.err') def validate(self): self.assertGrep(file='xpybuild.out', expr="ERROR .*", contains=False) self.a...
ogram")
rjfarmer/mesaTest
test.py
Python
gpl-2.0
1,941
0.052035
#Copyright (c) 2015, Robert Farmer rjfarmer@asu.edu #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. #This program is distr...
l be useful, #but WITHOUT ANY WARRANTY; without even the implied warranty of #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #GN
U General Public License for more details. #You should have received a copy of the GNU General Public License #along with this program; if not, write to the Free Software #Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. from __future__ import print_function,unicode_literals import os ...
gaberger/pybvc
pybvc/openflowdev/ofswitch.py
Python
bsd-3-clause
118,713
0.000059
# Copyright (c) 2015, BROCADE COMMUNICATIONS SYSTEMS, INC # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # 1. Redistributions of source code must retain the above copyright notice, # this list...
IBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SER...
couchbase/perfrunner
perfrunner/remote/context.py
Python
apache-2.0
1,512
0.000661
from typing import Callable, List from decorator import decorator from fabric.api import execute, parallel, settings @decorator def all_servers(task, *args, **kwargs): """Execute the decorated function on all remote server nodes.""" helper = args[0] hosts = helper.cluster_spec.servers return execut...
oles: hosts += helper.cluster_spec.servers_by_role(role=role) execute(parallel(task), *args, hosts=hosts, **kwargs) return wrapper @decorator def all_clients(task: Callable, *args, **kwargs): """Execute the decorated function on all remote client machines.""" helper = args[0] ho...
xecute(parallel(task), *args, hosts=hosts, **kwargs) @decorator def master_client(task: Callable, *args, **kwargs): """Execute the decorated function on master client.""" self = args[0] with settings(host_string=self.cluster_spec.workers[0]): return task(*args, **kwargs)
makinacorpus/Geotrek
geotrek/celery.py
Python
bsd-2-clause
463
0
from celery import Celery import os # set the default Django settings module for the 'celery' program. os.enviro
n.setdefault('DJANGO_SETTINGS_MODULE', 'geotrek.settings') app = Celery('geotrek') # Using a string here means the worker will not have to # pickle the object when using Windows. app.config_from_object('geotrek.settings.celery') app.autodiscover_tasks() @app.task(bind=
True) def debug_task(self): print('Request: {0!r}'.format(self.request))
palfrey/kitling
frontend/videos/migrations/0008_auto_20151028_1154.py
Python
agpl-3.0
633
0
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models import jsonfield.fields class Migration(mig
rations.Migration): dependencies = [ ('videos', '0007_auto_20151027_2338'), ] operations = [ migrations.RemoveField( model_name='video', name='account',
), migrations.RemoveField( model_name='video', name='events', ), migrations.AddField( model_name='video', name='extra', field=jsonfield.fields.JSONField(default={}), ), ]
geotagx/pybossa
test/test_uploader/test_rackspace_uploader.py
Python
agpl-3.0
16,878
0.001066
# -*- coding: utf8 -*- # This file is part of PyBossa. # # Copyright (C) 2015 SciFabric LTD. # # PyBossa is free software: you can redistribute it and/or modi
fy # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # PyBossa is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MER...
he # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with PyBossa. If not, see <http://www.gnu.org/licenses/>. """This module tests the Uploader class.""" from default import Test, with_context from pybossa.uploader.rackspace imp...
ohgodscience/Python
Exercises/AlphabetSoup.py
Python
gpl-2.0
109
0.055046
def AlphabetS
oup(str): temp = list(str) temp.sort() for x in temp: print x AlphabetSoup(raw_i
nput())
nkgilley/home-assistant
homeassistant/components/directv/__init__.py
Python
apache-2.0
3,350
0.000896
"""The DirecTV integration.""" import asyncio from datetime import timedelta from typing import Any, Dict from directv import DIRECTV, DIRECTVError import voluptuous as vol from homeassistant.config_entries import SOURCE_IMPORT, ConfigEntry from homeassistant.const import ATTR_NAME, CONF_HOST from homeassistant.core ...
: """Return device information about this DirecTV receiver.""" return { ATTR_IDENTIFIERS: {(DOMAIN, self._device_id)}, ATTR_NAME: self.name, ATTR_MANUFACTURER: self.dtv.device.info.brand, ATTR_MODEL: None, ATTR_SOFTWARE_VERSION: self.dtv.device...
ATTR_VIA_DEVICE: (DOMAIN, self.dtv.device.info.receiver_id), }
cherryc/dynet
python_tests/test_grads.py
Python
apache-2.0
421
0.014252
import dynet as dy import numpy as np # create model m=dy.Model() # add parameter p=m.parameters_from_numpy(np.ones((1,5))) # create cg dy.renew_cg() # input tensor x= dy.inputTensor(np.arange(5).reshape((5,1))) # add parameter to computation graph e_p=dy.parameter(p) # compute dot product res = e_p * x # Run forward ...
d backward pass res.forward() res.backward() # Shou
ld print the value of x print p.grad_as_array()
dokipen/trac-announcer-plugin
announcer/resolvers/specified.py
Python
bsd-3-clause
3,186
0.00408
# -*- coding: utf-8 -*- # # Copyright (c) 2008, Stephen Hansen # Copyright (c) 2009, Robert Corsaro # Copyright (c) 2010, Steffen Hoffmann # # All rights reserved. # # Redistribution and use in source and binary
forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright...
of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of the <ORGANIZATION> nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior wr...
markleent/Guardian
auth/redirectors/redirectorManager.py
Python
mit
513
0.007797
import sys from .. import config from . import nullRedirector from .
import flaskRedirector from . import
tornadoRedirector ADAPTERS = { 'dict': 'nullRedirector', 'Flask': 'flaskRedirector', 'tornado': 'tornadoRedirector' } current_module = thismodule = sys.modules[__name__] class rManager(object): @staticmethod def set_redirector(adapter = None): sess_adapter = adapter if adapter else conf...
parenthetical-e/modelmodel
stats.py
Python
bsd-2-clause
1,951
0.012301
import numpy as np def conjunction(stats, ps=None): """Run a conjunction test. Parameters ---------- stats : np.array([float, ...]) A list of statistics, e.g *t*-values. ps : np.array([float, ...]), None A list of (optional) p-values matching elements in stats. ...
really `A > 0 AND B > 0` (or as null `A = 0 OR B = 0`), and implemented a way to do that. It more-or-less reduces down to `test_stat = np.min(stats)`. - This approach is used here. * Friston, Penny and Glaser
(2005) replied that while Nichols is right in their idea, the test design is too conservative. They offered an alternative. Given this package is designed for model-based comparisons, and as I (EJP) have concerns about the precision and utility of NHT for relating computational models to BOLD...
sathnaga/virt-test
libvirt/tests/src/virsh_cmd/domain/virsh_attach_detach_disk.py
Python
gpl-2.0
10,666
0.001313
import os, logging from autotest.client.shared import error from virttest import aexpect, virt_vm, virsh, remote from virttest.libvirt_xml import vm_xml def run_virsh_attach_detach_disk(test, params, env): """ Test virsh {at|de}tach-disk command. The command can attach new disk/detach disk. 1.Prepare ...
"rpm -qa | grep redhat-release") if s_vd != 0: session.close() return False if o_vd.find("5Server") != -1: s_mod, o_mod = session.cmd_status_output( "modprobe...
session.close() return False session.close() return True except (remote.LoginError, virt_vm.VMError, aexpect.ShellError), e: logging.error(str(e)) return False vm_ref = params.get("at_dt_disk_vm_ref", "name") at_options = para...
deanishe/alfred-appscripts
active_app_benchmarks/active_app_02_objc_bridge.py
Python
mit
1,286
0
#!/usr/bin/env python # encoding: utf-8 # # Copyright (c) 2015 deanishe@deanishe.net # # MIT Licence. See http://opensource.org/licenses/MIT # # Created on 2015-11-23 # """Get app info with
AppKit via objc bridge.""" from __future__ import print_function, unicode_literals, absolute_import import time import unicodedata from AppKit import NSWorkspace def decode(s): """Decode bytestring to Unicode.""" if isinstance(s, str): s = unicode(s, 'utf-8') elif not isinstance(s, unicode): ...
or("str or unicode required, not {}".format(type(s))) return unicodedata.normalize('NFC', s) def get_frontmost_app(): """Return (name, bundle_id and path) of frontmost application. Raise a `RuntimeError` if frontmost application cannot be determined. """ for app in NSWorkspace.sharedWorkspac...
mellanox-openstack/vsa
src/vsa/model/vsa_collections/vsa_collections.py
Python
apache-2.0
7,719
0.020469
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # # Copyright 2013 Mellanox Technologies, Ltd # # 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 # #...
of __init__ comes here. @param typ @param owner @param path @param candelete @param altidx @param indexed @param desc @param icon @return """
self.cclass=typ self.path=path self.description=iif(desc,desc,path.capitalize()) self.can_delete=candelete self._owner = owner self.handlerclass='' self.fullpath=owner.fullpath+'/'+path self.altidx=altidx self.altdict={} self.indexed=indexe...
cloudbase/nova-virtualbox
nova/api/metadata/handler.py
Python
apache-2.0
8,152
0.000123
# Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics
and Space Administration. # 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 appl...
ther express or implied. See the # License for the specific language governing permissions and limitations # under the License. """Metadata request handler.""" import hashlib import hmac import os from oslo_config import cfg from oslo_log import log as logging import six import webob.dec import webob.exc from ...
richm/designate
designate/tests/test_agent/__init__.py
Python
apache-2.0
749
0
# Copyright 2012 Hewlett-Packard Development Company, L.P. All Rights Reserved. # # Author: Kiall Mac Innes <kiall@hp.com> # # 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....
uired 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 f
or the specific language governing permissions and limitations # under the License. from designate.tests import TestCase class AgentTestCase(TestCase): pass
BARCproject/barc
workspace/src/labs/src/lab1/remapping.py
Python
mit
721
0.01387
#!/usr/bin/env python import rospy from geometry_msgs.msg import Twist def callback_function(data): #FILL IN HERE global publisher_name, msg msg.linear.x = -data.linear.x msg.angular.z = -data.angular.z publisher_name.publish(msg) def subscriber_name(): # Initialize node rospy.init_node('...
uptException:
pass
barche/k3d
share/k3d/guide/content/wiki2asciidoc.py
Python
gpl-2.0
1,764
0.027778
from optparse import OptionParser from uuid import uuid4 import re def main(): parser = OptionParser() #parser.add_option("--skip-rows", type="int", dest="skip_rows", default="0", help="Number of lines/rows to skip when using --lines or --csv. Default: %default") (options, arguments) = parser.parse_args() listing...
ng: # Convert varying numbers of single-quo
tes to Asciidoc "emphasis" markup = re.sub("('{2,5})([^']+('[^']+)*)\\1", "'\\2'", markup) # Markup double-quotes markup = re.sub("\"([^\"]*)\"", "``\\1''", markup) # Eliminate article categories markup = re.sub("\\[\\[Category:[^\]]*\\]\\]", "", markup) # Convert wiki links to Asciidoc links ...
mafagafogigante/algorithms-and-data-structures
python/other/shash.py
Python
unlicense
1,412
0.003541
""" Consider adding prime numbers to the hashing function. Although there is no evidence whatsoever that using prime numbers increases bit entropy (or is there?), it seems that this is a too widespread practice for an amateur such as myself not to follow. There is no one-size-fits-all hashing methodology, what can be...
:return: a hash integer """ global alpha # Each character lies between 0 and 255, inclusively. total = 0 length = len(string) for i in range(length): total += ord(string[i]) * alpha ** (length - i - 1) return total def shash_roll(h, size, old, new): """ 'Rolls' a hash forwa...
e first of the string that generated the hash) :param new: the new character (the last of the current string) :return: a new hash integer """ global alpha h -= ord(old) * alpha ** (size - 1) h *= alpha h += ord(new) return h
the-blue-alliance/the-blue-alliance
src/backend/common/queries/dict_converters/event_details_converter.py
Python
mit
2,401
0.002499
from collections import defaultdict from typing import cast, Dict, List, NewType from backend.common.consts.api_version import ApiMajorVersion from backend.common.models.event_details import EventDetails from backend.common.models.keys import TeamKey from backend.common.queries.dict_converters.converter_base import Co...
s)) @classmethod def eventDetailsConverter_v3(cls, event_details: EventDetails) -> EventDetailsDict: normalized_oprs = defaultdict(dict) if event_deta
ils and event_details.matchstats: for stat_type, stats in event_details.matchstats.items(): if stat_type in {"oprs", "dprs", "ccwms"}: for team, value in cast(Dict[TeamKey, float], stats).items(): if "frc" not in team: # Normalize output ...
grigorisg9gr/menpowidgets
menpowidgets/base.py
Python
bsd-3-clause
100,134
0.000509
from collections import Sized, OrderedDict import matplotlib.pyplot as plt from matplotlib import collections as mc import numpy as np import ipywidgets import IPython.display as ipydisplay from menpo.image import MaskedImage, Image from menpo.image.base import _convert_patches_list_to_single_array from .options imp...
text_per_line.append('> {}'.format(msg)) info_wid.set_widget_state(text_per_line=text_per_line) # Create widgets axes_mode_wid = ipywidgets.RadioButtons( options={'Image': 1, 'Point cloud': 2}, description='Axes mode:', value=1) axes_mode_wid.observe(render_function, names='...
s_x_limits=0.1, axes_y_limits=0.1, render_function=render_function, style=renderer_style, tabs_style=renderer_tabs_style) renderer_options_box = ipywidgets.VBox( children=[axes_mode_wid, renderer_options_wid], align='center', margin='0.1cm') info_wid = TextPrintWidget(text_per_li...
bquast/rnnlib
utils/min_max.py
Python
gpl-3.0
1,350
0.015556
#Copyri
ght 2009,2010 Alex Graves # # This file is part of RNNLIB. # # RNNLIB 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. # # RNNLIB is d...
will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with RNNLIB. If not, see <http://www.gnu.org/lic...
crantila/cats
publishconf.py
Python
gpl-3.0
551
0.001815
#!/usr/bin/env python # -*- coding: utf-8 -*- # from __future__ import unicode_literals # This file is only used if you use `make publish` or # explicitly specify it as your config file. i
mport os import sys sys.path.append(os.curdir) from pelicanconf import * PUBLISH = True SITEURL = 'https://meow.antila.ca' RELATIVE_URLS = False DELETE_OUTPUT_DIRECTORY = True # Theme (Custom Settings) # ======================= IMAGE_WIDTHS = ['300', '400', '500', '600', '700', '800', '9
00', '1000'] IMAGES_URL = '{siteurl}/images'.format(siteurl=SITEURL)
Tosche/Glyphs-Scripts
Path/Report Compatibility by Numbers.py
Python
apache-2.0
1,305
0.024521
#MenuTitle: Report Compatibility by Numbers # -*- coding: utf-8 -*- from __future__ import pri
nt_function, division, unicode_literals __doc__=""" Outputs path count, node count, anchor count etc. of selected glyphs in the Macro Window. """ import GlyphsApp font = Glyphs.font # frontmost font fontMaster = font.selectedFontMaster # active master selectedLayers = font.selectedLayers # active layers of selected g...
og() for layer in selectedLayers: glyph = layer.parent print(glyph.name) for l in glyph.layers: if l.pathCount() == 1: pathCount = "1 path" else: pathCount = str(l.pathCount()) + " paths" nCount = 0 for p in l.paths: nCount += len(p.nodes) print("\t%s\n\t\t%s, %s nodes, %s components, %s anchors"...
reinforceio/tensorforce
tensorforce/core/memories/recent.py
Python
apache-2.0
3,719
0.002151
# Copyright 2020 Tensorforce Team. 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 la...
n(num_args=3) def retrieve_timesteps(self, *, n, past_horizon, future_horizon): one = tf_util.constant(value=1, dtype='int') capacity = tf_util.constant(value=self.capacity, dtype='int') # Check whether memory contai
ns at least one valid timestep num_timesteps = tf.math.minimum(x=self.buffer_index, y=capacity) num_timesteps -= (past_horizon + future_horizon) num_timesteps = tf.math.maximum(x=num_timesteps, y=self.episode_count) # Check whether memory contains at least one timestep assertion...
Anthony25/python_tc_qos
pyqos/tests/backend/test_tc.py
Python
bsd-2-clause
6,670
0
import pytest import pyqos.backend.tc from pyqos.backend import tc NETIF = "eth0" @pytest.fixture def fixture_disable_commands(monkeypatch, mocker): monkeypatch.setattr("pyqos.backend.tc.launch_command", mocker.stub()) launch_cmd_spy = pyqos.backend.tc.launch_command return launch_cmd_spy def test_...
tc.qos_class(action="add", **kwargs) tc.qos_class_add(**kwargs) calls = launch_cmd_spy.call_args_list assert calls[0] == calls[1] def test_qos_class_del(fixture_qos_class_wrapper): """ Ensure that qos_class and qos_class
_del call the same command at the end """ launch_cmd_spy, kwargs = fixture_qos_class_wrapper tc.qos_class(action="delete", **kwargs) tc.qos_class_del(**kwargs) calls = launch_cmd_spy.call_args_list assert calls[0] == calls[1] def test_qos_class_show(fixture_disable_commands): launch_cmd_s...
lrowe/rdflib
setup.py
Python
bsd-3-clause
5,590
0.002147
#!/usr/bin/env python import sys import os import re def setup_python3(): # Taken from "distribute" setup.py from distutils.filelist import FileList from distutils import dir_util, file_util, util, log from os.path import join, exists tmp_src = join("build", "src") # Not covered by "setup.py ...
ner="RDFLib Team", maintainer_email="rdflib-dev@google.com", url="https://github.com/RDFLib/rdflib", license="https://raw.github.com/RDFLib/rdflib/master/LICENSE", platforms=["any"], classifiers=[
"Programming Language :: Python", "Programming Language :: Python :: 2", "Programming Language :: Python :: 3", "Programming Language :: Python :: 2.5", "Programming Language :: Python :: 2.6", "Programming Language :: Python :: 2.7", "Program...
chrsrds/scikit-learn
sklearn/decomposition/tests/test_online_lda.py
Python
bsd-3-clause
15,351
0
import sys import numpy as np from scipy.linalg import block_diag from scipy.sparse import csr_matrix from scipy.special import psi import pytest from sklearn.decomposition import LatentDirichletAllocation from sklearn.decomposition._online_lda import (_dirichlet_expectation_1d, ...
', LatentDirichletAllocation(learning_offset=-1)), ) for param, model in invalid_models: regex = r"^Invalid %r parameter" % param as
sert_raises_regexp(ValueError, regex, model.fit, X) def test_lda_negative_input(): # test pass dense matrix with sparse negative input. X = np.full((5, 10), -1.) lda = LatentDirichletAllocation() regex = r"^Negative values in data passed" assert_raises_regexp(ValueError, regex, lda.fit, X) def t...
WGBH/FixIt
mla_game/apps/transcript/migrations/0026_transcript_active.py
Python
mit
486
0
# -*-
coding: utf-8 -*- # Generated by Django 1.11.6 on 2018-01-25 18:50 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('transcript', '0025_transcriptphrasecorrectionvote_original_phrase'), ] operations = [ ...
eanField(default=True), ), ]
mlperf/training_results_v0.7
Fujitsu/benchmarks/resnet/implementations/implementation_open/mxnet/3rdparty/onnx-tensorrt/third_party/onnx/onnx/defs/gen_doc.py
Python
apache-2.0
18,681
0.002462
#!/usr/bin/env python from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from collections import defaultdict import io import os import sys import numpy as np # type: ignore from onnx import defs, FunctionProto, helper...
f this function: {
}\n'.format( ', '.join(display_function_version_link(domain_prefix + function.name, v) for v in versions if v != function.since_version)) # inputs s += '\n#### Inputs' s += '\n\n' if function.input: s += '<dl>\n' for input in function.input: s += '<dt>{}; </dt>\n...
LuizArmesto/trellonotify
src/lib/trello/__init__.py
Python
gpl-3.0
69
0
# -*- coding:
utf-8 -*- from .trello import * from .mod
els import *
xgvargas/xeda
sw/objects.py
Python
apache-2.0
2,224
0.019784
class ObjectXEDA: kind= -1 name= '' posX= 0 posY= 0 centerX= 0 centerY= 0 w= 0 h= 0 angle= 0 selected= False mirrored= False locked= False glow= False dragging= False def is_over(self, x, y): '''responde se a coordenada indicado esta sobre esse o...
def draw(self): pass class PCBObject(ObjectXEDA): ''' componentes (como descritos aqui) pad isolado via linhas arcos (partindo do centro e dos extermos) textos ''' def __init__(self): self.foot= 'sop23' s
elf.ref= 'U12' self.comment= 'teste' self.pads= [(0, 0, 'id', 'quadrado', 'w', 'h', 'top', 'furo-diametro', 'net-name', 'mask'), (25, 0, 'id', 'quadrado', 'w', 'h', 'top', 'furo-diametro', 'net-name', 'mask') ] self.drawns= [] def draw(self): ...
JasonVann/CLRS
S5_AdvancedDataStructures/C20_vanEmdeBoasTrees/vEB_Tree.py
Python
mit
3,635
0.003851
class vEB_Tree(): import math def __init__(self, u): self.min = None self.max = None self.u = u self.summary = None self.ul = math.floor(math.sqrt(self.u)) self.uh = math.ceil(math.sqrt(self.u)) #self.cluster = [None] * self.uh if not self.is_leaf(...
er, offset) def empty_tree_insert(self, x): self.min = x self.max = x def insert(self, x): if self.min ==
None: self.empty_tree_insert(x) else: if x < self.min: self.min, x = x, self.min if self.u > 2: if self.minimum(self.cluster[self.high(x)]) == None: self.insert(self.summary, self.high(x)) self.empty_tre...
joereynolds/Mr-Figs
src/game_object/particle_emitter.py
Python
gpl-3.0
1,025
0.002927
import pygame import src.colours as colours import random from pygame.math import Vector2 from src.entity import Entity from src.game_object.particle import Particle from src.game_object.particle_factory import ParticleFactory class ParticleEmitter(Entity): def __init__(self, x, y, level, emits): Entity._...
es = pygame.sprite.LayeredUpdates() self.emits = emits self.particle_factory = ParticleFactory() def create_particle(self, x: int, y: int, velocity: Vector2) -> Particle: return self.particle_factory.build(x, y, velocity, self.emits) def update(self, dt, x ,y, velocity: Vector2, partic...
: if len(self.particles) <= particle_count: particle = self.create_particle(x, y, velocity) self.particles.add(particle) self.level.sprites.add(particle)
Adriel-M/HackerRank
Learn/Algorithms/Warmup/Plus Minus/plusminus.py
Python
mit
331
0.003021
# Given code n = int(input().strip()) arr = [int(arr_temp) for arr_temp in input().strip().split(' ')] # Start pos = 0.0 zero = 0.0 neg
= 0.0 for i in arr: if i == 0: zero += 1 elif i > 0: pos += 1 else: neg += 1 print("%.6f" % (pos
/ n)) print("%.6f" % (neg / n)) print("%.6f" % (zero / n))
amwelch/a10sdk-python
a10sdk/core/enable/enable_management_service_ssh_acl_v4.py
Python
apache-2.0
3,405
0.009104
from a10sdk.common.A10BaseClass import A10BaseClass class VeCfg(A10BaseClass): """This class does not support CRUD Operations please use parent. :param ve_end: {"type": "number", "description": "VE port", "format": "number"} :param ve_start: {"type": "number", "description": "VE port (VE Interface n...
": 1, "optional": false} :param uuid: {"description": "uuid of the object", "format": "string", "minLength": 1, "modify-not-allowed": 1, "optional": true, "maxLength": 64, "type": "string"} :param eth_cfg: {"minItems": 1, "items": {"type": "object"}, "uniqueItems": true, "type": "array", "arra
y": [{"properties": {"ethernet-start": {"type": "number", "description": "Ethernet port (Ethernet Interface number)", "format": "interface"}, "ethernet-end": {"type": "number", "description": "Ethernet port", "format": "interface"}, "optional": true}}]} :param DeviceProxy: The device proxy for REST operations and s...
jorgecarleitao/public-contracts
contracts/urls.py
Python
bsd-3-clause
1,749
0
from django.conf.urls import patterns, url, include from django.utils.translation import ugettext_lazy as _ from . import feed from . import views from . import views_analysis from . import views_data from . import entity_urls from . import contract_urls from . import category_urls urlpatterns = patterns( '', ...
ta_selector', ), url(r'%s/' % _('contract'), include(contract_urls)), url(r'%s/' % _('entity'), include(entity_urls)), url(r'%s/' % _('category'), include(category_urls)), ) # lists urlpatterns += patterns( '', url(r'^%s$' % _('contracts'), views.contracts_list, name='contracts_list'), ...
% _('contracts'), feed.ContractsFeed(), name='contracts_list_feed'), url(r'^%s$' % _('categories'), views.categories_list, name='categories_list'), url(r'^%s$' % _('tenders'), views.tenders_list, name='tenders_list'), url(r'^%s/rss$' % _('tenders'), feed.TendersFeed(), name='tende...
Amarchuk/2FInstability
core/VelocityDispersion.py
Python
gpl-3.0
5,226
0.006889
__author__ = 'amarch' # -*- coding: utf-8 -*- from bisect import bisect import sys import numpy from scipy import interpolate from core.velocityEllipsoidReconstr import * from utils import strutils as infoutils from utils.bcolors import * import matplotlib.pyplot as plt class VelocityDispersion(): def __init__(s...
print_info(self, indent): infoutils.print_header("Velocity Dispersion", self.name, self.description, indent) infoutils.print_simple_param(indent+1, "fake data points count", str(self.fake_data_points.__len__())) if self.poly_fit != poly1d([0]): infoutils.print_simple_param(inden
t+1, "polyfit degree", self.poly_fit.coeffs.__len__()-1) infoutils.print_simple_param(indent+1, "polyfit coeffs", list(self.poly_fit.coeffs)) infoutils.print_list_summary(1+indent, "radii in arcsec", self.radii(), description=self.description) infoutils.print_list_summary(1+indent, "disper...
nharmon/bogie-five
src/turn.py
Python
gpl-3.0
356
0.005618
#!/usr/bin/python # Nathan Harmon # https://github.com/
nharmon/bogie-five # # Turn program # from Motion import * import sys if __name__ == '__main__': if len(sys.argv) < 2: exit("Must specify target image file") try: drive = Drive() drive.turn(float(sys.argv[1]))
except: exit("Specify direction change")