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
claudep/translate
translate/tools/porestructure.py
Python
gpl-2.0
5,484
0.002371
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2005, 2006 Zuza Software Foundation # # This file is part of translate. # # translate 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 ...
hould only allow it to be created, otherwise # we mess up an existing tree. os.mkdir(options.output) except: self.error(optrecurse.optparse.OptionValueError("Output directory does not exist, attempt to create failed")) if self.isrecursive(option
s.input, 'input') and getattr(options, "allowrecursiveinput", True): if isinstance(options.input, list): inputfiles = self.recurseinputfilelist(options) else: inputfiles = self.recurseinputfiles(options) else: if options.input: ...
aricaldeira/PySPED
pysped/nfe/leiaute/nfe_310.py
Python
lgpl-2.1
81,201
0.005439
# -*- coding: utf-8 -*- # # PySPED - Python libraries to deal with Brazil's SPED Project # # Copyright (C) 2010-2012 # Copyright (C) Aristides Caldeira <aristides.caldeira at tauga.com.br> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public Lice...
n xml def set_xml(self, arquivo): if self._le_xml(arquivo): self.vBC.xml = arquivo self.vAliq.xml = arquivo self.vISSQN.xml = arquivo self.c
MunFG.xml = arquivo self.cListServ.xml = arquivo self.vDeducao.xml = arquivo self.vOutro.xml = arquivo self.vDescIncond.xml = arquivo self.vDescCond.xml = arquivo self.vISSRet.xml = arquivo self.indISS.xml = arquivo ...
miyataken999/weblate
weblate/trans/autofixes/whitespace.py
Python
gpl-3.0
1,794
0
# -*- coding: utf-8 -*- # # Copyright © 2012 - 2015 Michal Čihař <michal@cihar.com> # # This file is part of Weblate <https://weblate.org/> # # 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, eith...
# # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # import re from django.utils.translation import uget
text_lazy as _ from weblate.trans.autofixes.base import AutoFix NEWLINES = re.compile(r'\r\n|\r|\n') START = re.compile(r'^(\s+)', re.UNICODE) END = re.compile(r'(\s+)$', re.UNICODE) class SameBookendingWhitespace(AutoFix): ''' Help non-techy translators with their whitespace ''' name = _('Trailing ...
Johnzero/erp
openerp/addons/membership/report/report_membership.py
Python
agpl-3.0
6,097
0.003444
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU...
te"), 'num_waiting': fields.integer('# Waiting', readonly=True), 'num_invoiced': fields.integer('# Invoiced', readonly=True), 'num_paid': fields.integer('# Paid', readonly=True), 'tot_pending': fields.float('Pending Amount', digits_compute= dp.get_precision('Account'), readonly=True), ...
e('res.partner', 'Member', readonly=True), 'associate_member_id': fields.many2one('res.partner', 'Associate Member', readonly=True), 'membership_id': fields.many2one('product.product', 'Membership Product', readonly=True), 'membership_state': fields.selection(STATE, 'Current Membership State', r...
siosio/intellij-community
python/testData/multipleArgumentsCompletion/slashParameter.after.py
Python
apache-2.0
87
0.034483
def foo(a, /, b): print(a, b)
def egg():
a = 1 b = 2 foo(a, b)<caret>
stephane-martin/salt-debian-packaging
salt-2016.3.3/tests/unit/transport/ipc_test.py
Python
apache-2.0
3,969
0.000252
# -*- coding: utf-8 -*- ''' :codeauthor: :email:`Mike Place <mp@saltstack.com>` ''' # Import python libs from __future__ import absolute_import import os import logging import tornado.gen import tornado.ioloop import tornado.testing import salt.utils import salt.config import salt.exceptions import salt.transpor...
l(self.payloads[:-1], ['foo', 'foo']) def test_multistream_errors(self): local_channel = self._get_channel() for c in (self.channel, local_cha
nnel): c.send(None) for c in (self.channel, local_channel): c.send('foo') self.channel.send({'stop': True}) self.wait() self.assertEqual(self.payloads[:-1], [None, None, 'foo', 'foo']) if __name__ == '__main__': from integration import run_tests run_te...
Southpaw-TACTIC/TACTIC
src/install/backup/tactic_backup.py
Python
epl-1.0
4,220
0.007583
#!/usr/bin/env python3 # This is a simple command line script that can be used to backup the # TACTIC database. It is independent of TACTIC, so can be run on # servers where TACTIC is not install with the database. import datetime import os import time import subprocess import tacticenv from pyasm.common import Env...
base_dir = "%s%s" % (BACKUP_DIR, PROJECT_DIR) zip_exe = ZIP_EXE now = datetime.datetime
.now() date = now.strftime("%Y%m%d_%H%M") file_path = '%s/tactic_%s.zip' % (base_dir, date) # Check if base_dir is exists and writable. if not os.path.exists(base_dir): os.mkdir(base_dir) # Create backup, and if successful, prune old # backup...
ulif/pail
docs/conf.py
Python
lgpl-3.0
8,125
0.007508
# -*- coding: utf-8 -*- # # pail documentation build configuration file, created by # sphinx-quickstart on Sat May 4 03:26:35 2013. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All co
nfiguration values have a default; values that are commented out # serve to show the default. import sys, os # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make i...
neral configuration ----------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. exten...
bhavanaananda/DataStage
test/FileShare/tests/TestWebDAVAccess.py
Python
mit
7,828
0.010731
# $Id: TestWebDAVAccess.py 1047 2009-01-15 14:48:58Z graham $ # # Unit testing for FileAccess module # import os # Make sure python-kerberos package is installed import kerberos import sys import httplib import urllib2 import urllib2_kerberos import re import base64 import unittest from urlparse import urlparse sys.p...
"File "+filename1+" not deleted" except: pass # Test and delete second file try: s = os.stat(filename2) except: assert (False), "File "+filename2+" not found or other stat error" os.remove(filename2) try: s = os.stat(filenam...
assert (False), "File "+filename2+" not deleted" except: pass # Test and delete third file try: s = os.stat(filename3) except: assert (False), "File "+filename3+" not found or other stat error" os.remove(filename3) try: ...
Akagi201/learning-python
pyramid/MyShop/setup.py
Python
mit
1,213
0
import os from setuptools import setup, find_packages here = os.path.abspath(os.path.dirname(__file__)) with open(os.path.join(here, 'README.txt')) as f: README = f.read
() with open(os.path.join(here, 'CHANGES.txt')) as f: CHANGES = f.read() requires = [ 'pyramid', 'pyramid_chameleon', 'pyramid_debugtoolbar', 'pyramid_tm', 'SQLAlchemy', 'transaction', 'zope.sqlalchemy', 'waitress', 'pyramid_layout' ] setup(name='MyShop', version='0.0...
thon", "Framework :: Pyramid", "Topic :: Internet :: WWW/HTTP", "Topic :: Internet :: WWW/HTTP :: WSGI :: Application", ], author='', author_email='', url='', keywords='web wsgi bfg pylons pyramid', packages=find_packages(), include_package_data=True, ...
dogancankilment/Yemekci
manage.py
Python
gpl-2.0
250
0
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "yemekci.settings") from django.core.management
import execute_from_command_line
execute_from_command_line(sys.argv)
tscalf/aws-rds-replica-tools
query_profiler.py
Python
gpl-3.0
5,180
0.003475
#!/usr/bin/env python ''' Query Profiler Profile a list of queries from a file. Put the output on stdout. ''' import os import json import logging import time import pymysql import boto3 LOGGER = logging.getLogger('query_profile') LOGGER.setLevel(logging.DEBUG) # create file handler which logs even debug messages ...
on ''' beg_ts = time.time() retval = func(*args, **kwargs) end_ts = time.time() LOGGER.info("Function '%s' elapsed time: %f s", func.__name__, (end_ts - beg_ts)) return retval return wrapper def get_db_credentials(landscape, environment, dbinstanceidentifier, dbschem...
param landscape: The landscape where the product is deployed. Typical Contry Code: uk, eu, na, us, ca :param environment: The environment for the product. Typically: preprod or production :param dbinstanceidentifier: The RDS DB instance Identifier. Load parameters into SSM as JSON arrays with the fo...
MuckRock/muckrock
muckrock/accounts/migrations/0042_auto_20180803_0915.py
Python
agpl-3.0
709
0
# -*- coding: utf-8 -*- # Generated by Django 1.11.4 on 2018-08-03 13:15 # Django from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('accounts', '0041_profile_avatar_url'), ] operations = [ migrations.RemoveField( model_name='p...
model_name='profile', name='full_name', field=models.CharField(blank=True, max_length=255), ),
migrations.AddField( model_name='profile', name='uuid', field=models.UUIDField(blank=True, null=True), ), ]
razvanm/fs-expedition
heatmap.py
Python
unlicense
464
0.00431
#!/usr/bin/env python import sys line = sys.stdin.readline() # skip the header line = sys.stdin.readline() all
= {} while line: v = line.split() if v[0] not in all: all[v[0]] = set() all[v[0]].add(v[1]) line = sys.stdin.readline() s = [k for (_, k) in sorted([(len(v), k) for (k,v) in all.items()])] print ' '.join(reversed(s)) for i
in s: print i, for j in reversed(s): print len(all[i].intersection(all[j])), print
adam-iris/mailman
src/mailman/bin/checkdbs.py
Python
gpl-3.0
7,696
0.00104
# Copyright (C) 1998-2014 by the Free Software Foundation, Inc. # # This file is part of GNU Mailman. # # GNU Mailman 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 you...
r request in requestsdb.of_type(RequestType.held_message): if first: pending.append(_('\nPending posts:')) first = False key, data = requestsdb.get_request(request.id) when = data['when'] sender = data['sender'] subject = data['subject'] reason = d...
text = data['text'] msgdata = data['msgdata'] subject = Utils.oneline(subject, lcset) date = time.ctime(when) reason = _(reason) pending.append(_("""\ From: $sender on $date Subject: $subject Cause: $reason""")) pending.append('') # Coerce all items in pendin...
jammers-ach/pywolf3d
pywolf3d/player.py
Python
mit
3,285
0.008219
from ursina import * class Wolf3dPlayer(Entity): def __init__(self, **kwargs): super().__init__() self.speed = 5 self.position = (1,5,1) self.height = 0.5 self.camera_pivot = Entity(parent=self, y=self.height) self.cursor = Entity(parent=camera.ui, model='quad', col...
te(self): rotate_sprites = False if application.development_mode: self.y -= held_keys['e'] self.y += held_keys['q'] if held_keys['a']: self.rotation_y -= 1 rotate_sprites = True if held_keys['d']: self.rotation_y += 1 ...
ection = Vec3( self.forward * (held_keys['w'] - held_keys['s']) ).normalized() origin = self.world_position + (self.up*.5) hit_info = raycast(origin , self.direction, ignore=[self,], distance=.5, debug=False) if not hit_info.hit: self.position += self.directi...
ucsd-ccbb/Oncolist
src/restLayer/app/ingest.py
Python
mit
2,103
0.000476
import re import csv import pymongo import itertools from bioservices import WikiPathways import app from util import save_file_metadata, split_id, is_numeric, is_boolean log = app.get_logger('ingest') def ingest(filepath): _id, _ = split_id(filepath) client = pymongo.MongoClient() meta = client.file...
sv.reader(fid, delimiter='\t') header = reader.next() log.debug("%d columns: %s", len(header), ", ".join(header)) if len(header) == 0: raise ValueError('header row must contain at least one column') keys = [normalize_column_name(h) for h in header] def parse(row): ...
reader] parsed = [v for v in parsed if v is not None] header = [{'raw': h, 'key': k} for h, k in itertools.izip(header, keys)] for h in header: data = [p[h['key']] for p in parsed] if all(is_boolean(d) for d in data): h['datatype'] = 'boolean' ...
relic7/prodimages
mozu/RESTClient.py
Python
mit
22,278
0.009875
#!/usr/bin/env python # coding: utf-8 from os import environ from mozu_image_util_functions import log ## Import and set static connection environmental variables -- sql_alchemy_uri, mozu_tenant etc. from base_config import authenticate, set_environment set_environment() # Import initial static vars and Auth func Ca...
0}://t{1}.{2}".format(__base_protocol__, __tenant_name__,__base_url__ ) __document_data_api__
= __tenant_url__ + "/api/content/documentlists/" + __listFQN__ + "/documents" __document_tree_api__ = __tenant_url__ + "/api/content/documentlists/" + __listFQN__ + "/documentTree" ### valid keys for filtering insert fields and other query fields or args` __mozu_image_table_valid_keys__ = [ 'id', 'bf_im...
tonytan4ever/canary
canary/openstack/common/gettextutils.py
Python
apache-2.0
16,232
0.00037
# Copyright 2012 Red Hat, Inc. # Copyright 2013 IBM Corp. # 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....
use lazy gettext functionality. This is useful if your project is importi
ng _ directly instead of using the gettextutils.install() way of importing the _ function. """ global USE_LAZY USE_LAZY = True def _(msg): if USE_LAZY: return Message(msg, domain='billing') else: if six.PY3: return _t.gettext(msg) return _t.ugettext(msg) d...
DhrubajyotiDas/PyAbel
abel/tests/test_tools_circularize.py
Python
mit
1,075
0.002791
from __future__ import absolute_import from __future__ import division from __future__ import print_function
import numpy as np from numpy.testing import assert_equal, assert_almost_equal import abel def test_circularize_image(): IM = abel.tools.analytical.sample_image(n=511, name='Ominus', sigma=2) # flower image distortion def flower_scaling(theta, freq=2, am
p=0.1): return 1 + amp*np.sin(freq*theta)**4 IMdist = abel.tools.circularize.circularize(IM, radial_correction_function=flower_scaling) IMcirc, angle, scalefactor, spline =\ abel.tools.circularize.circularize_image(IMdist, method='lsq', dr...
fmrchallenge/fmrbenchmark
domains/dubins_traffic/dub_sim/src/genroad.py
Python
bsd-3-clause
434
0
#!/usr/bin/env python from __future__ import print_function import argparse from fmrb
.dubins_traffic import gen
_worldsdf, RoadNetwork if __name__ == '__main__': parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('FILE', type=str, help='road network description file') args = parser.parse_args() with open(args.FILE, 'rt') as f: roads = RoadNetwork(f) print(gen_worldsdf(roads)...
VitalPet/addons-onestein
base_directory_files_download/models/__init__.py
Python
agpl-3.0
218
0
# -*- coding: utf-8 -*- # Copyright 2017
Onestein (<http://www.onestein.eu>) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from . import ir_filesystem_directory from . import
ir_filesystem_file
strogo/djpcms
tests/regression/editing/tests.py
Python
bsd-3-clause
4,078
0.01692
import json from djpcms import test from djpcms.plugins.text import Text class Editing(test.TestCase): def setUp(self): super(Editing,self).setUp() p = self.get()['page'] p.set_template(p.create_template('thre-columns', '{{ content0...
Text,2) def postdata(self): return {self.sites.settings.HTML_CLASSES.post_view_key:'rearrange'} def geturl(self, block): return '{0}{1}/{2}/{3}/'.format(self.sites.settings.CONTENT_INLINE_EDITING['pagecontent'],
block.page.id, block.block, block.position) def _getcontent(self, block, toblock): '''Do as jQuery does''' data = self.postdata() if toblock.position: if to...
Dziolas/inspire-next
inspire/dojson/utils.py
Python
gpl-2.0
3,011
0.000664
# -*- coding: utf-8 -*- # # This file is part of INSPIRE. # Copyright (C) 2015 CERN. # # INSPIRE 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...
for field in value: export += ['\t<datafield tag="%s" ind1="%s" ' 'ind2="%s">\n'.expandtabs(tabsize) % (tag, ind1, ind2)] for code, subfieldvalue in six.iteritems(field): if subfieldvalue: ...
code="%s">%s' '</subfield>\n'.expandtabs(tabsize) % (code, encode_for_marcxml(val))] else: export += ['\t\t<subfield code="%s">%s' '</subfield...
spookylukey/django-autocomplete-light
test_project/ajax_create/models.py
Python
mit
216
0
from django.db import models class Creatable(models.
Model): name = models.CharField(max_length=100) related = models.ManyToManyField('self', blank=Tr
ue) def __unicode__(self): return self.name
datalogics/scons
src/engine/SCons/Tool/Perforce.py
Python
mit
3,456
0.004051
"""SCons.Tool.Perforce.py Tool-specific initialization for Perforce Source Code Management system. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ # # __COPYRIGHT__ # # Permission is hereby granted, free of ...
odify, merge, publish, # distribute, sublicense, and/or sell copies 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 Softw...
DING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 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 # WI...
clarinsi/reldi-api
index.py
Python
gpl-3.0
3,105
0.005801
# -*- coding: utf-8 -*- import sys import os import atexit from ConfigParser import NoSectionError from flask import Flask, url_for from flask.ext.cors import CORS from src.core.cmstiser import Csmtiser from src.core.ner_tagger import NerTagger from src.di import DependencyContainer from src.core.lexicon import Lexi...
import Lematiser from src.core.dependency_parser import DependencyParser from src.core.restorer import DiacriticRestorer from src.routers.api_router import ApiRouter from src.routers.web_router import WebRouter from src.services.mail_service import MailService from src.helpers import jsonify from flask import ma
ke_response, redirect from werkzeug.contrib.fixers import ProxyFix import traceback reload(sys) sys.setdefaultencoding('utf-8') from src.helpers import config def init(): languages = ['hr', 'sl', 'sr'] app = Flask(__name__) app.secret_key = 'super secret key' app.config['SESSION_TYPE'] = 'filesyst...
fkmhrk/kiilib_python
test/sample_test.py
Python
apache-2.0
155
0.006452
import unittest class ExampleTest(uni
ttest.TestCase): def test_a(self): self.assertEq
ual(1, 1) self.assertEqual([1, 2, 3], [1, 2, 3])
jenshnielsen/HJCFIT
likelihood/python/optimization.py
Python
gpl-3.0
5,973
0.01557
######################## # DCProgs computes missed-events likelihood as described in # Hawkes, Jalali and Colquhoun (1990, 1992) # # Copyright (C) 2013 University College London # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as ...
n used to set matrix components. """ for i, row in enumerate(graph_matrix): for j, value in enumerate(row): if i == j: continue if not isinstance(value, str): fixed[i, j] = True elif value.lower().rstrip().lstrip() == 'v': va
riable[i, j] = True else: expressions.append((i, j, value)) if expressions is None: expressions = None # sanity check for i, row in enumerate(graph_matrix): for j, value in enumerate(row): if fixed[i, j] == False: continue if abs(value) > 1e-8: continue if fixed[j, i] == False or abs(...
Bismarrck/pymatgen
scripts/feff_plot_dos.py
Python
mit
2,040
0.002941
#!/usr/bin/env python # coding: utf-8 # Copyright (c) Pymatgen Development Team. # Distributed under the terms of the MIT License. """ Script to plot density of states (DOS) generated by an FEFF run either by site, element, or orbital """ from __future__ import division __author__ = "Alan Dozier" __credits__= "Anub...
Jain, Shyue Ping Ong" __copyright__ = "Copyright 2012, The Materials Project" __version__ = "1.0" __maintainer__ = "Alan Dozier" __email__ = "adozier@uky.edu" __date__ =
"April 7, 2012" import argparse from collections import OrderedDict from pymatgen.io.feff import FeffLdos from pymatgen.electronic_structure.plotter import DosPlotter parser = argparse.ArgumentParser(description='''Convenient DOS Plotter for Feff runs. Author: Alan Dozier Version: 1.0 Last updated: April, 2013''') ...
jordanemedlock/psychtruths
temboo/core/Library/RunKeeper/GeneralMeasurements/UpdateEntry.py
Python
apache-2.0
3,693
0.004335
# -*- coding: utf-8 -*- ############################################################################### # # UpdateEntry # Updates a body measurement entry in a user’s feed. # # Python versions 2.6, 2.7, 3.x # # Copyright 2014, Temboo Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may no...
Choreo. The InputSet object is used to specify input parameters when executing this Choreo. """ def set_Entry(self, value): """ Set the value of the Entry input for this Choreo. ((required, json) A JSON string containing the key/value pairs
for the fields to be updated in the body measurement entry. See documentation for formatting examples.) """ super(UpdateEntryInputSet, self)._set_input('Entry', value) def set_AccessToken(self, value): """ Set the value of the AccessToken input for this Choreo. ((required, string) T...
sputnick-dev/weboob
modules/carrefourbanque/__init__.py
Python
agpl-3.0
810
0
# -*- coding: utf-8 -*- # Copyright(C) 2013 Romain Bignon # # This file is part of weboob. # # w
eboob 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. # # weboob is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABIL...
Gebesa-Dev/Addons-gebesa
product_code_unique/__openerp__.py
Python
agpl-3.0
701
0
# -*- coding: utf-8 -*- # © <YEAR(S)> <AUTHOR(S)> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "Product Code Unique", "summary": "Add the unique property to default_code field", "version": "9.0.1.0.0", "category": "Product", "website": "https://odoo-community.org/",...
corro>, Odoo Community Association (OCA)", "license":
"AGPL-3", "application": False, "installable": True, "external_dependencies": { "python": [], "bin": [], }, "depends": [ "base", "product", ], "data": [ "views/product_view.xml" ], "demo": [ ], "qweb": [ ] }
mitenjain/R3N
tests/nnTests.py
Python
mit
5,157
0.006011
#!/usr/bin/env python import sys sys.path.append("../") import unittest import numpy as np from toy_datasets import load_digit_dataset from lib.optimization import mini_batch_sgd, mini_batch_sgd_with_annealing class skLearnDigitTest(unittest.TestCase): def setUp(self): tr_data, xtr_data, ts_data = load_di...
ta] self.xtr = np.array([x[0] for x in xtr_data]) self.xtr_l = [x[1] for x in xtr_data] self.ts = np.array([x[0] for x in ts_data]) self.ts_l = [x[1] for x in ts_data] def checkModel(self, test_name, model_type, hidden_dim, verbose, epochs, batch_size=10, extra_args=None): n...
_data=self.tr, labels=self.tr_l, xTrain_data=self.xtr, xTrain_targets=self.xtr_l, learning_rate=0.001, L1_reg=0.0, L2_reg=0.0, epochs=epochs, batch_size=batch_size, hidden_dim=hidden_dim, model_type=model_t...
lijunxyz/leetcode_practice
pow_x_n_medium/Solution1.py
Python
mit
1,612
0.011166
# https://oj.leetcode.com/problems/powx-n/ # Implement pow(x, n). # The idea of this problem is very similar to the "divide two integers" problem. Try to match n with # 2^(2^(k-1)) series. # But still, there are various detailed corner cases to consider. class Solution: # @param x, a float # @param n, a intege...
00001 return 1.0 # Now make x and n both positive for convenience if x<0 and n%2==1: sign = -1 else: sign = 1 x = abs(x) if n<0: x = 1.0/float(x) n =
-n p = 1 # final product while n>=1: a = 1 # a temporary probe x2 = x # a copy of x, reset every iteration <-- this line is easy to forget while a<<1 < n: a <<= 1 x2 = x2*x2 p *= x2 n -= a if p...
commonsearch/cosr-back
cosrlib/es.py
Python
apache-2.0
4,391
0.001139
from __future__ import absolute_import, division, print_function, unicode_literals import time import logging import ujson as json from elasticsearch import Elasticsearch from elasticsearch.client import IndicesClient from elasticsearch.exceptions import ConnectionTimeout from .config import config from .es_mappings...
() return IndicesClient(self.client) def create(self, empty=False): """ Creates the ES index """ if empty: self.empty() mappings = ES_MAPPINGS[self.index_name] self.indices().create(index=self.index_name, body={ "settings": { # TO...
(cosr-ops?) "number_of_shards": 5, "number_of_replicas": 0, # In prod we don't refresh manually so this is the only setting # that will make ES periodically refresh to avoid storing only in temporary files # as we index "re...
jgosmann/psyrun
psyrun/mapper.py
Python
mit
5,215
0
"""Map functions onto parameter spaces.""" from multiprocessing import Pool import os.path import warnings from psyrun.exceptions import IneffectiveExcludeWarning from psyrun.pspace import dict_concat, missing, Param def get_result(fn, params, exclude=None): """Evaluates a function with given parameters. E...
len(pspace) // pool_size) for r in Pool(pool_size).imap_unordered( _get_result_single_arg, ((fn,
p, exclude) for p in pspace.iterate()), chunksize): store.append(filename, dict_concat((r,))) if not os.path.exists(filename): store.save(filename, {}) if return_data: return store.load(filename) def map_pspace_parallel( fn, pspace, n_jobs=-1, backend='multiprocessing', exclude...
kennedyshead/home-assistant
homeassistant/components/evohome/__init__.py
Python
apache-2.0
25,207
0.001547
"""Support for (EMEA/EU-based) Honeywell TCC climate systems. Such systems include evohome, Round Thermostat, and others. """ from __future__ import annotations from datetime import datetime as dt, timedelta import logging import re from typing import Any import aiohttp.client_exceptions import evohomeasync import e...
til.parse_datetime(tokens[ACCESS_TOKEN_EXPI
RES]) ) user_data = tokens.pop(USER_DATA, None) return (tokens, user_data) store = hass.helpers.storage.Store(STORAGE_VER, STORAGE_KEY) tokens, user_data = await load_auth_tokens(store) client_v2 = evohomeasync2.EvohomeClient( config[DOMAIN][CONF_USERNAME], con...
agvergara/Python
X-Serv-XML-ContentApp-Barrapunto/barrapunto/contentApp/admin.py
Python
gpl-3.0
118
0.008475
from django.contrib import admin from models import Content # Register your models here
. admin.site.r
egister(Content)
jakobmoss/tsa
utils/makeweights.py
Python
mit
2,350
0
# -*- coding: utf-8 -*- # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Time Series Analysis -- Generate statistical weigts from scatter # # Author: Jakob Rørsted Mosumgaard # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ##############################...
th to scatter file (with same time points!) """ # Pretty print print('Generating weights for {0} !'.format(dpath)) # Load data and weights t, d = np.loadtxt
(dpath, unpack=True) tt, sig = np.loadtxt(wpath, unpack=True) # Check that times are indeed the same tdif = t - tt if tdif.any() != 0: print('Error! Not the same time points! Quitting!') exit() # Moving variance (Hans: M = 50 - 100) M = 70 movstd = bn.move_std(sig, M, min_c...
fablab-ka/OpenSCAD2D
src/openscad2d.py
Python
gpl-2.0
2,313
0.002162
# pylint: disable-msg=E0611 from __future__ import print_function import sys from PySide import QtCore, QtGui from src.documentwatcher import DocumentWatcher from src.geometrywidget import GeometryWidget from src.cadfileparser import FcadParser from src.printcapturecontext i
mport PrintCaptureContext from src.svggenerator import SvgGenerator from src.geometrygenerator import GeometryGenerator class OpenSCAD2D(object): def __init__(self, filename): self.screen_width, self.screen_height = 800.0, 600.0 self.file_generator = SvgGenerator() self.geometry_generato...
loadFile(self, filename): self.filename = filename if self.watcher: self.watcher.stop_monitor() self.watcher = DocumentWatcher(self.filename, self.on_file_change) self.watcher.monitor() self.parser = FcadParser(filename) self.update() def update(self):...
talkincode/txradius
txradius/openvpn/setup_config.py
Python
lgpl-3.0
520
0.003846
#!/usr/bin/env py
thon # -*- coding: utf-8 -*- confstr = '''[DEFAULT] nas_id=txovpn nas_coa_port=3799 nas_addr=127.0.0.1 radius_addr=127.0.0.1 radius_auth_port=18121 radius_acct_port=18131 radius_secret=secret radius_timeout=3 acct_interval=60 session_timeout=864000 logfile=/var/log/txovpn.log statusfile=/etc/openvpn/openvpn-status.log...
): print confstr if __name__ == '__main__': print confstr
nylas/sync-engine
migrations/versions/144_update_calendar_index.py
Python
agpl-3.0
1,080
0.001852
"""Update Calendar index. Revision ID: 1c73ca99c03b Revises: 1d7a72222b7c Create Date: 2015-02-26 00:50:52
.322510 """ # revision identifiers, used by Alembic. revision = '1c73ca99c03b' down_revision = '1d7a72222b7c' from alembic import op def upgrade(): op.drop_constraint('calendar_ibfk_1', 'calendar', type_='foreignkey') op.drop_constraint('uuid', 'calendar', type_='unique') op.create_index('uuid', 'calen...
['namespace_id', 'provider_name', 'name', 'uid'], unique=True) op.create_foreign_key('calendar_ibfk_1', 'calendar', 'namespace', ['namespace_id'], ['id']) def downgrade(): op.drop_constraint('calendar_ibfk_1', 'calendar', type_='foreignkey') op.drop_...
isudox/leetcode-solution
python-algorithm/leetcode/problem_231.py
Python
mit
1,321
0
"""231. Power of Two https://leetcode.com/problems/power-of-two/ Given an integer n, return true if it is a power of two. Otherwise, return false. An integer n is a power of two, if there exists an integer x such that n == 2^x. Example
1: Input: n = 1 Output: true Explanation: 2^0 = 1 Example 2: Input: n = 16 Output: true Explanation: 2^4 = 16 Example 3: Input: n = 3 Output: false Example 4: Input: n = 4 Output: true Example 5: Input: n = 5 Output: false Constraints: -2^31 <= n <= 2^31 - 1 """ class Solution: def is_power_of_two(self...
if n <= 0: return False if n == 1: return True n, rem = divmod(n, 2) if rem == 1: return False return self.is_power_of_two(n) def is_power_of_two2(self, n: int) -> bool: if n < 1: return False while n: ...
calee88/ParlAI
parlai/tasks/opensubtitles/agents.py
Python
bsd-3-clause
872
0
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. An additional grant # of patent rights can be found in the PATENTS file in the same directory. from parlai.core.fbdialog_...
copy import os def _path(opt, filtered): # Build the data if it doesn't exist. build(opt) dt = opt['datatype'].split(':')[0] return os.pa
th.join(opt['datapath'], 'OpenSubtitles', dt + filtered + '.txt') class DefaultTeacher(FbDialogTeacher): def __init__(self, opt, shared=None): opt = copy.deepcopy(opt) opt['datafile'] = _path(opt, '') opt['cands_datafile'] = opt['datafile'] super().__init__(...
zappyk-github/zappyk-python
lib/lib_external/postgresql/bin/pg_python.py
Python
gpl-2.0
3,516
0.039818
## # .bin.pg_python - Python console with a connection. ## """ Python command with a PG-API connection(``db``). """ import os import sys import re import code import optparse import contextlib from .. import clientparameters from ..python import command as pycmd from .. import project from ..driver import default as p...
# authspec error thrown last time, so force prompt. cond['
prompt_password'] = True try: clientparameters.resolve_password(cond, prompt_title = 'pg_python') except EOFError: raise SystemExit(1) connector = pg_driver.fit(category = cat, **cond) connection = connector() if trace_file is not None: connection.tracer = trace_file.write connect...
anurag03/integration_tests
cfme/tests/services/test_pxe_service_catalogs.py
Python
gpl-2.0
5,998
0.002834
# -*- coding: utf-8 -*- import fauxfactory import pytest from widgetastic.utils import partial_match from cfme import test_requirements from cfme.infrastructure.provider import InfraProvider from cfme.infrastructure.provider.rhevm import RHEVMProvider from cfme.infrastructure.pxe import get_pxe_server_from_config, get...
ements.service, pytest.mark.tier(2) ] def pytest_generate_tests(metafunc): # Filter out providers without provisioning data or hosts defined argnames, argvalues, idlist = testgen.providers_by_class( metafunc, [InfraProvider], required_fields=[ ['provisioning', 'pxe_server'], ...
ng', 'pxe_image'], ['provisioning', 'pxe_image_type'], ['provisioning', 'pxe_kickstart'], ['provisioning', 'pxe_template'], ['provisioning', 'datastore'], ['provisioning', 'host'], ['provisioning', 'pxe_root_password'], ['provisioning',...
tinloaf/home-assistant
tests/components/test_device_sun_light_trigger.py
Python
apache-2.0
3,831
0
"""The tests device sun light trigger component.""" # pylint: disable=protected-access from datetime import datetime from asynctest import patch import pytest from homeassistant.setup import async_setup_component import homeassistant.loader as loader from homeassistant.const import CONF_PLATFORM, STATE_HOME, STATE_NOT...
ger.DOMAIN, { device_sun_light_trigger.DOMAIN: {}}) common_light.async_turn_off(hass) await hass.async_block_till_done() test_time = test_time.replace(hour=3) with patch('homeassistant.util.dt.utcnow', return_value=test_time): async_fire_time_changed(hass, test_time) a...
assert light.is_on(hass) async def test_lights_turn_off_when_everyone_leaves(hass, scanner): """Test lights turn off when everyone leaves the house.""" common_light.async_turn_on(hass) await hass.async_block_till_done() assert await async_setup_component( hass, device_sun_light_trigger...
NetEaseGame/git-webhook
app/utils/DateUtil.py
Python
mit
535
0
# -*- coding: utf-8 -*- ''' C
reated on 2015年8月24日 @author: hustcc ''' import datetime import time # 当前时间,可用于mysql datetime def now_datetime_string(): return datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") def now_datetime(): return datetime.datetime.now() def now_date_string(): return datetime.datetime.now().strftime("%Y-%...
t(now_datetime()) print(now_timestamp()) print(now_date_string())
dcvetko/cybld
cybld/cybld_command_handler.py
Python
mit
10,981
0.002823
#!/usr/bin/python # -------------------------------------------------------------------------- # # MIT License # # -------------------------------------------------------------------------- import atexit import logging import os import pty import subprocess import tempfile import threading import time import termios ...
"""
Helper function to execute the given command and call the success/fail callbacks :param cmd: The command (full string) which should be executed :param nvim_ipc: The NVIM IPC name, if available """ assert self.busy is False self.shared_status.set_running() ...
apbard/scipy
scipy/_lib/_numpy_compat.py
Python
bsd-3-clause
23,885
0.000837
"""Functions copypasted from newer versions of numpy. """ from __future__ import division, print_function, absolute_import import warnings import sys from warnings import WarningMessage import re from functools import wraps import numpy as np from scipy._lib._version import NumpyVersion def import_nose(): """ ...
If True, also return the number of times each unique value comes up in `ar`. .. versionadded:: 1.9.0 Returns ------- unique : ndarray The sorted unique value
s. unique_indices : ndarray, optional The indices of the first occurrences of the unique values in the (flattened) original array. Only provided if `return_index` is True. unique_inverse : ndarray, optional The indices to reconstruct the (flattened) original array fro...
OCA/l10n-italy
l10n_it_website_portal_fiscalcode/__manifest__.py
Python
agpl-3.0
585
0
# Copyright 2019 Simone Rubino # Copyright 2019 Lorenzo Battistini # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). { "name": "ITA - Website portal fiscalcode", "summary": "Add fiscal code to details of frontend user", "version": "14.0.1.
0.0", "author": "Odoo Community Association (OCA)", "category": "Localization/Italy", "website": "https://github.com/OCA/l10n-italy", "license": "AGPL-3", "depends": ["l
10n_it_fiscalcode", "portal"], "data": ["views/l10n_it_website_portal_fiscalcode_templates.xml"], "auto_install": True, }
hgl888/chromium-crosswalk
third_party/mojo/src/mojo/public/tools/dart_pkg.py
Python
bsd-3-clause
7,740
0.001034
#!/usr/bin/env python # # Copyright 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Utility for dart_pkg and dart_pkg_app rules""" import argparse import errno import os import shutil import sys # Disable lint ch...
er.add_argument('--package-name', action='store', type=str, metavar='package_name', help='Name of p
ackage', required=True) parser.add_argument('--gen-directory', metavar='gen_directory', help="dart-gen directory", required=True) parser.add_argument('--pkg-directory', metavar='pkg_directory'...
spaceone/pyjs
tests/test026.py
Python
apache-2.0
179
0
class SchoolCalendarWidget: def setDayIncluded(self, day, included): if (self.daysFilter[day] == included): retu
rn self.daysFilter[
day] = included
battlecat/Spirit
HelloWorld/HelloWorld/view.py
Python
mit
96
0.03125
from django.http import
HttpResponse def hello(request): return HttpResponse("Hell
o world ! ")
leapcode/bitmask-dev
src/leap/bitmask/mail/imap/mailbox.py
Python
gpl-3.0
30,254
0
# *- coding: utf-8 -*- # mailbox.py # Copyright (C) 2013-2015 LEAP # # 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. # #...
:rtype: int :return: the UID of the message. """ # TODO support relative sequences. The (imap) message should # receive a sequence number attribute: a deferred is not expected return message_number def getUIDNext(self): """ Return the likely UID for the ...
mailbox. Currently it returns the higher UID incremented by one. :return: deferred with int :rtype: Deferred """ d = self.collection.get_uid_next() return d def getMessageCount(self): """ Returns the total count of messages in this mailbox. ...
manassolanki/erpnext
erpnext/buying/utils.py
Python
gpl-3.0
3,898
0.025654
# Copyright (c) 2015, Frapp
e Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import frappe from frappe.utils import flt, cstr, cint from frappe import _ import json from erpnext.stock.doctype.item.item import get_last_purchase_details from erpnext.stock.d...
em table for each item""" import frappe.utils this_purchase_date = frappe.utils.getdate(doc.get('posting_date') or doc.get('transaction_date')) for d in doc.get("items"): # get last purchase details last_purchase_details = get_last_purchase_details(d.item_code, doc.name) # compare last purchase date and thi...
takeTrace/UrHouseBot
UrHouseBot/UrHouseBot/middlewares.py
Python
mit
7,809
0.001194
# -*- coding: utf-8 -*- # Define here the models for your spider middleware # # See documentation in: # http://doc.scrapy.org/en/latest/topics/spider-middleware.html from UrHouseBot.settings import PROXY_HOST from scrapy import signals, Request import requests from UrHouseBot.spiders import doubanGroup proxy_host =...
equest(self, reque
st, spider): delay = request.meta.get('302delay', 0) if delay > 0: logging.debug(f'🌙🌙🌙🌙🌙之前302, 这次请求睡眠: {delay}: {request.url}') time.sleep(delay) return request
ossem/member_database
nfc_lib.py
Python
apache-2.0
1,047
0.010506
import random def append_letter_or_number(): alphabet = ['a','b','c','d','e','f']
use_number = 0 use_letter = 1 letter_or_string = random.randrange(2) if letter_or_string == use_number: result = str(random.randrange(0,9)) elif letter_or_string == use_letter: next_character = random.randrange(len(alphabet)) result = str(alphabet[next_character]) else:
print("Uh-oh! You've got a bug. This should have selected number or letter.") return -1 return result # generates a random 16-byte NFC ID tag when a NFC is unavailable def create_nfc_tag(): random_nfc_tag = '' tag_size = 7 # number of hex pairs end_of_tag = tag_size - 1 current_byt...
arthurwolf/fabrica
smoothie-upload.py
Python
gpl-3.0
2,305
0.019089
#!/usr/bin/env python """\ Upload a file to Smoothie over the network """ from __future__ import print_function import sys import argparse import socket import os # Define command line argument interface parser = argparse.ArgumentParser(description='Upload a file to Smoothie over network.') parser.add_argument('file',...
args.ipaddr + " as " + output + " size: " + str(filesize) ) # make connection to sftp server s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.settimeout(4.0) s.connect((args.ipaddr, 115)) tn= s.makefile() # read startup prompt ln= tn.readline() if not ln.startswith("+") :
print("Failed to connect with sftp: " + ln) sys.exit(); if verbose: print("RSP: " + ln.strip()) # Issue initial store command tn.write("STOR OLD /sd/" + output + "\n") tn.flush() ln= tn.readline() if not ln.startswith("+") : print("Failed to create file: " + ln) sys.exit(); if verbose: print("RSP: " ...
acsone/acsone-addons
hr_timesheet_project_access_restriction/models/__init__.py
Python
agpl-3.0
63
0
# -*- coding: utf-8 -*- from .
import account_analytic_ac
count
ianawilson/kafka-python
kafka/producer/simple.py
Python
apache-2.0
1,893
0.001585
from __future__ import absolute_import from itertools import cycle import logging import random import six from six.moves import xrange from .base import Producer log = logging.getLogger(__name__) class SimpleProducer(Producer): """A simple, round-robin producer. See Producer class for Base Arguments ...
roducer, self)._
_init__(*args, **kwargs) def _next_partition(self, topic): if topic not in self.partition_cycles: if not self.client.has_metadata_for_topic(topic): self.client.load_metadata_for_topics(topic) self.partition_cycles[topic] = cycle(self.client.get_partition_ids_for_top...
alexhunterlang/natural_bm
natural_bm/datasets/random.py
Python
mit
1,299
0.009238
"""Tiny dataset that is just used for tests """ #%% import numpy as np from natural_bm.datasets.common import Dataset #%% def _make_random(data_type): num_pixels = 10 dataset = {} for dset in ['train', 'valid', 'test']: if dset == 'train': num_samples = 12 else...
num_samples = 6 if data_type == 'probability': dataset[dset+'.data'] = np.random.u
niform(size=(num_samples, num_pixels)) else: dataset[dset+'.data'] = np.random.randint(2, size=(num_samples, num_pixels)) dataset[dset+'.lbl'] = np.random.randint(2, size=(num_samples,)) return dataset #%% class Random(Dataset): def __init__(self, datatype): ...
nimily/backgammon-ai
backgammon/utils.py
Python
gpl-3.0
878
0
from collections import Counter def is_subplay(moves, play): play_counter = Counter() for m in play[0]: play_counter[m] += 1 moves_counter = Counter() for m in moves: moves_counter[m] += 1 for m, c in moves_counter.items(): if m not in play_counter.keys(): ret...
return False return True def is_legal_play(moves, plays): """ :param moves: candidate moves :param plays: set of all legal plays to be considered :return: """ moves = sorted(moves) for play in plays: match = True if len(play[0]) != len(moves): continue ...
break if match: return True return False
ConsenSys/testrpc
tests/endpoints/test_personal_newAccount.py
Python
mit
283
0
def test_
personal_newAccount(rpc_client): initial_accounts = rpc_client('personal_listAccounts') new_account = rpc_client('personal_newAccount', ['some-pass
word']) assert new_account not in initial_accounts assert new_account in rpc_client('personal_listAccounts')
sonyahanson/yank
Yank/tests/test_examples.py
Python
lgpl-3.0
1,826
0.011501
#!/usr/bin/python #============================================================================================= # MODULE DOCSTRING #============================================================================================= """ Test examples. """ #=================================================================...
=1 ./run.sh', shell=True, executable='/bin/bash') # Restore working directory. os.chdir(cwd) if returncode: raise Exception('Example %s returned exit code %d' % (example, returncode)) return def get_immediate_subdirectories(path): return [name for name in os.listdir(path) if os.path.isdi...
sts(os.path.join(path, name, 'run.sh'))] @attr('slow') # Skip on Travis-CI def test_examples(): # Get example path. from pkg_resources import resource_filename path = resource_filename('yank', '../examples') # Get list of examples. directories = get_immediate_subdirectories(path) # Test examp...
hpproliant/proliantutils
proliantutils/ilo/ribcl.py
Python
apache-2.0
17,546
0.005813
# Copyright 2014 Hewlett-Packard Development Company, L.P. # # 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 ...
s or {} etree.SubElement(tagname, cmdname) if six.PY2: root_iterator = root.getiterator(cmdname) else: r
oot_iterator = root.iter(cmdname) for cmd in root_iterator: for key, value in subelements.items(): cmd.set(key, value) return root def _serialize_xml(self, root): """It serializes the dynamic xml created and converts it to a string. This is done before ...
tzpBingo/github-trending
codespace/python/tencentcloud/yunjing/v20180228/yunjing_client.py
Python
mit
122,172
0.002542
# -*- coding: utf8 -*- # Copyright (c) 2017-2021 THL A29 Limited, a Tencent company. 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...
["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise
else: raise TencentCloudSDKException(e.message, e.message) def CreateBaselineStrategy(self, request): """根据策略信息创建基线策略 :param request: Request instance for CreateBaselineStrategy. :type request: :class:`tencentcloud.yunjing.v20180228.models.CreateBaselineStrategy...
ivanprjcts/sdklib
tests/test_session.py
Python
bsd-2-clause
1,479
0.000676
import unittest from sdklib.compat import cookies from sdklib.http.session import Cookie class TestSession(unittest.TestCase): @classmethod def setUpClass(cls): cls.cookie = Cookie({"Set-Cookie": "chips=ahoy; vienna=finger"}) def test_as_cookie_header_value(self): res = self.cookie.as_c...
res = cookie.as_cookie_header_value() self.assertEqual(res, "") def test_get_cookie_morsel(self): res = self.cookie.get("chips") self.assertEqual(res.value, "ahoy") def test_get_cookie(self): res = self.cookie.getcookie() self.assertTrue(isinstance(res, cookies.Simple...
date(self.cookie) res = c.as_cookie_header_value() self.assertIn("chips=ahoy", res) self.assertIn("vienna=finger", res) self.assertIn("new_param=marcos", res) self.assertIn("another_new=ivan", res)
schleichdi2/OPENNFR-6.0-CORE
opennfr-meta-openembedded/contrib/oe-stylize.py
Python
gpl-2.0
11,631
0.006534
#!/usr/bin/env python """\ Sanitize a bitbake file following the OpenEmbedded style guidelines, see http://openembedded.org/wiki/StyleGuide (C) 2006 Cyril Romain <cyril.romain@gmail.com> MIT license TODO: - add the others OpenEmbedded variables commonly used: - parse command arguments and print usage on misuse ...
/!\ startswith('SOMETHING') is not taken into account due to the previous startswith('S'). - count rule breaks and displays them in the order frequence """ from __future__ import print_function import fileinput import string import re __author__ = "Cyril Romain <cyril.romain@gmail.com>" __version__ =
"$Revision: 0.5 $" # The standard set of variables often found in .bb files in the preferred order OE_vars = [ 'SUMMARY', 'DESCRIPTION', 'AUTHOR', 'HOMEPAGE', 'SECTION', 'LICENSE', 'LIC_FILES_CHKSUM', 'DEPENDS', 'PROVIDES', 'SRCREV', 'SRCDATE', 'PE', 'PV', 'PR', ...
Alberdi/marcestats
bgplays/services.py
Python
gpl-3.0
3,592
0.003341
from .models import * from django.db.models import Count, F, Max, Sum # Game info services def get_median_points(game_id): return median_value(Team.objects.filter(play__game__id=game_id) \ .exclude(play__team__points__isnull=True), 'play__team__points') def get_pl...
ct() is probably not working as expected # But there are not counterexamples in the current data set plays_ids = get_play_ids(player_id) return Player.objects.filter(team__play__id__in=plays_ids) \ .exclude(id=player_id) \ .values('name', 'team__play__id') \ .distinct() \ .va...
cts.filter(team__players__id=player_id).values('id').distinct() def median_value(queryset, term): count = queryset.count() values = queryset.values_list(term, flat=True).order_by(term) if count % 2 == 1: return values[int(round(count / 2))] elif count > 0: return sum(values[count / 2 -...
geokrety/geokrety-api
tests/unittests/api/news/test_news_collection.py
Python
gpl-3.0
933
0
# -*- coding: utf-8 -*- from parameteri
zed import parameterized from tests.unittests.utils.base_test_case import BaseTestCase, request_context from tests.unittests.utils.payload.news import NewsPayload class TestNewsCollection(BaseTestCase): """Test News collection""" @parameterized.expand([ [None, 200], ['admin', 200], [...
200], ]) @request_context def test_news_collection_can_be_accessed_as(self, username, expected): news = self.blend_news(author=self.user_1, count=3) user = getattr(self, username) if username else None response = NewsPayload()\ .get_collection(user=user, code=expected)\...
tivek/conan
conans/test/model/manifest_test.py
Python
mit
2,065
0.002421
import unittest from conans.util.files import save, load, md5 import os from conans.model.manifest import FileTreeManifest from conans.test.utils.test_files import temp_folder class ManifestTest(unittest.TestCase): def test_tree_manifest(self): tmp_dir = temp_folder() files = {"one.ext": "aalakjs...
content in files.items(): save(os.path.join(tmp_dir, filename), content) manifest = FileTreeManifest.create(tmp_dir) save(os.path.join(tmp_dir, "THEMANIFEST.txt"), st
r(manifest)) readed_manifest = FileTreeManifest.loads(load(os.path.join(tmp_dir, "THEMANIFEST.txt"))) self.assertEqual(readed_manifest.time, manifest.time) self.assertEqual(readed_manifest, manifest) # Not included the pycs or pyo self.assertEquals(set(manifest.file_sums.keys()...
ahwillia/tensortools
tensortools/optimize/ncp_hals.py
Python
mit
6,382
0.00094
""" Nonnegative CP decomposition by Hierarchical alternating least squares (HALS). Author: N. Benjamin Erichson <erichson@uw.edu> """ import numpy as np import numba from tensortools.operations import unfold, khatri_rao from tensortools.tensors import KTensor from tensortools.optimize import FitResult, optim_utils ...
or, ``result.factors``. Notes ----- This implemenation is using the Hierarcial Alternating Least Squares Method. References ---------- Cichocki, Andrzej, and P. H. A. N. Anh-Huy. "Fast local algorithms for large scale nonnegative matrix and tensor factorizations." IEICE transactions ...
ssing elements. if mask is not None: X = np.copy(X) X[~mask] = np.mean(X[mask]) # Check inputs. optim_utils._check_cpd_inputs(X, rank) # Initialize problem. U, normX = optim_utils._get_initial_ktensor(init, X, rank, random_state) result = FitResult(U, 'NCP_HALS', **options) ...
danstoner/python_experiments
playing_with_kivy/kivi-examples/demo/touchtracer/main.py
Python
gpl-2.0
2,938
0.002383
import kivy kivy.require('1.0.6') from kivy.app import App from kivy.uix.floatlayout import FloatLayout from kivy.uix.label import Label from kivy.graphics import Color, Rectangle, Point, GraphicException from random import random from math import sqrt def calculate_points(x1, y1, x2, y2, steps=5): dx = x2 - x1 ...
return Touchtracer() def on_pause(self):
return True if __name__ == '__main__': TouchtracerApp().run()
socialplanning/opencore
opencore/project/browser/add.py
Python
gpl-3.0
7,853
0.003566
""" project and subproject adding # @@ needs tests """ from Acquisition import aq_inner from Products.CMFCore.utils import getToolByName from Products.Five.browser.pagetemplatefile import ZopeTwoPageTemplateFile from opencore.browser.formhandler import OctopoLite, action from opencore.i18n import _ from opencore.inter...
Please choose an image in gif, jpeg, png, or bmp format.') return False return True @action('add') def handle_request(self, target=None, fields=None): #XXX all of the errors that are reported back here are not going # through the translation machinery putils = getToo...
'plone_utils') self.request.set('__initialize_project__', True) self.errors = {} title = self.request.form.get('project_title') title = strip_extra_whitespace(title) if not isinstance(title, unicode): title = unicode(title, 'utf-8') self.request.form['projec...
LaMi-/pmatic
update-file-headers.py
Python
gpl-2.0
2,611
0.002298
#!/usr/bin/env python # encoding: utf-8 # # pmatic - Python API for Homematic. Easy to use. # Copyright (C) 2016 Lars Michelsen <lm@larsmichelsen.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 Found...
gram; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Fl
oor, Boston, MA 02110-1301 USA. # Add Python 3.x behaviour to 2.7 from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import os import time import glob new_header = '''#!/usr/bin/env python # encoding: utf-8 # # pmatic -...
PayPal-Opportunity-Hack-Chennai-2015/AID-India
server/aiserverproj/aiserverapp/centre_helper.py
Python
apache-2.0
1,656
0.007246
from aiserverapp.models import Child from aiserverapp.models import Assessment from aiserverapp.models import Village from aiserverapp.models import Centre from aiserverapp.models import Block from aiserverapp.models import District def consolidate_centre_info(centre_id): print('CENTER:', centre_id) centre_inf...
= 0 #Get all children in this centre # for child in Child.objects.filter(centre_id=centre_id): # centre_info['children_count'] = centre_info['children_count'] + 1 # #Get assement of that child # print('CHILD:', child) # for assement in Assessment.objects.filter(c
hild_id=child.child_id): # print('assement:', assement) return centre_info
Lapin-Blanc/django_beid
__init__.py
Python
gpl-3.0
57
0
defa
ult_app_config = "django_beid.apps.DjangoBeidConfi
g"
geekaia/edx-platform
cms/djangoapps/contentstore/management/commands/export_all_courses.py
Python
agpl-3.0
1,450
0.001379
""" Script for exporting all courseware from Mongo to a directory """ from django.core.management.base import BaseCommand, CommandError from xmodule.modulestore.xml_exporter import export_to_xml from xmodule.modulestore.django import modulestore from xmodule.contentstore.django import contentstore class Command(BaseC...
led to export %s" % course_id) print("Error:")
print(err)
build18-fpga-on-the-web/server
fpga_process.py
Python
mit
1,898
0.035827
import time import multiprocessing sev_seg = \ {0 : [ 1, 1, 1, 1, 1, 1, 0], 1 : [ 0, 1, 1, 0, 0, 0, 0], 2 : [ 1, 1, 0, 1, 1, 0, 1], 3 : [ 1, 1, 1, 1, 0, 0, 1], 4 : [ 0, 1, 1, 0, 0, 1, 1], 5 : [ 1, 0, 1, 1, 0, 1, 1], 6 : [ 1, 0, 1, 1, 1, 1, 1], 7 : [ 1, 1, 1, 0, 0, 1, 0], 8 : [ 1, 1, 1, 1, 1, 1, 1], 9 : [ 1, 1, 1, 1, 0...
outputs = self.get_outputs(inputs) if outputs != prev_outputs: self.outp
utQ.put(outputs) prev_outputs = outputs time.sleep(0.01)
2ndy/RaspIM
usr/lib/python2.6/distutils/text_file.py
Python
gpl-2.0
15,086
0.004242
"""text_file provides the TextFile class, which gives an interface to text files that (optionally) takes care of stripping comments, ignoring blank lines, and joining lines with backslashes.""" __revision__ = "$Id$" from types import * import sys, os, string class TextFile: """Provides a file-like object that...
options) It bombs (RuntimeError) if both 'filename' and 'file' are None; 'filename' should be a string, and 'file' a file object (or something that provides 'readline()' and 'close()' methods). It is recommended that you supply at least 'filename', so that TextFile can include it in...
boolean, and affect the value returned by 'readline()': strip_comments [default: true] strip from "#" to end-of-line, as well as any whitespace leading up to the "#" -- unless it is escaped by a backslash lstrip_ws [default: false] strip leading whitespace from ...
devalfrz/django-image-styles
image_styles/views.py
Python
bsd-2-clause
8,038
0.011072
from django.shortcuts import render, HttpResponse, get_object_or_404 from django.http import Http404 from django.utils.decorators import method_decorator from django.contrib.auth.decorators import login_required from django.contrib.admin.views.decorators import staff_member_required from django.urls import reverse,reve...
_title(self): if self.form_class != EffectForm: return _('Create Effect') return super().get_title() def get_action(self): if self.action == '.': return reverse('image_styles:effect_create_init',kwargs={'style_id':self.style.id}) return self.action
def form_valid(self,form): effect_name = form.cleaned_data.get('effect') self.form_class = get_effect_form_class(effect_name=effect_name) self.action = reverse( 'image_styles:effect_create', kwargs={'style_id':self.style.id,'effect_name':effect_name} ) ...
tomasstorck/diatomas
blender/rendermonitor.py
Python
mit
5,383
0.007988
#!/usr/bin/python # -*- coding: utf-8 -*- # Generic rendering function that can handle all simulations, but makes poor renders. Nice for sketching. import os, time, subprocess, re def Say(text, verbosity=0, end='\n', suppressTime=False): if verbosity<=VERBOSITY: if suppressTime: timeStr = ''...
'drawStick':False, 'renderDir':'render' }
#renderpySettingsDict['suppressRender'] = True if re.match('^aom', d): renderpySettingsDict['model.L'] = 'array([20e-6,20e-6,20e-6])' renderpySettingsDict['offset'] = 'array([10,10,10])' renderpySettingsDict['configMaterial'] = 'ConfigAOM' renderpySettingsDict[...
mbookman/dsub
dsub/lib/job_util.py
Python
apache-2.0
2,587
0.002319
# Copyright 2016 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 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, ...
under the License. """Classes for dsub job script and resource.""" import collections class JobResources( collections.namedtuple('JobResources', [ 'min_cores', 'min_ram', 'disk_size', 'boot_disk_size', 'preemptible', 'image', 'logging', 'zones', 'scopes', 'keep_alive' ])): """Job resource...
luisbg/gst-introspection
gstgengui/gtk_controller.py
Python
lgpl-2.1
13,592
0.004194
#!/usr/bin/env python import pygtk pygtk.require('2.0') import gtk import gobject # TODOs # * refresh is unstable # * auto video embed is unstable (black contours ? lag ?) class VideoWidget(gtk.DrawingArea): def __init__(self): gtk.DrawingArea.__init__(self) self.imagesink = None self.un...
TOMATIC, gtk.POLICY_ALWAYS) scrolled_window.add_with_viewport(self.properties_container) # play/stop/pause controls pipeline_controls = self._create_pipeline_cont
rols(pipeline_launcher) #self.main_container.pack_start(self.preview_container, True, True, 3) #self.main_container.pack_start(pipeline_controls, False, False, 3) #self.main_container.pack_end(scrolled_window, True, True, 3) #self.main_container.add1(self.preview_container) self...
genos/online_problems
rosalind/lia.py
Python
mit
431
0
#!/usr/bin/env python # coding: utf-8 from rosalind import binom def pbinom(n, p, r):
return binom(n, r) * pow(p, r) * pow(1 - p, n - r) def dbinom(n, p, r): return sum(pbinom(n, p, i) for i in range(r + 1)) def lia(k, N): t = 1 << k return 1 - dbinom(t, .25, N - 1) if __name__ == "__main__": with open("data/rosalind_lia.txt") as f: k, N = map(int, f.read().split()) ...
k, N))
philanthropy-u/edx-platform
openedx/core/djangoapps/user_api/helpers.py
Python
agpl-3.0
20,700
0.001787
""" Helper functions for the account/profile Python APIs. This is NOT part of the public API. """ import json import logging import traceback from collections import defaultdict from functools import wraps from django import forms from django.core.serializers.json import DjangoJSONEncoder from django.http import HttpR...
orator that ensures the required POST params are present. If not, returns an HTTP response with status 400. Args: required_params (list): The required parameter keys. Returns: HttpResponse """ def _decorator(func): # pyl
int: disable=missing-docstring @wraps(func) def _wrapped(*args, **_kwargs): request = args[0] missing_params = set(required_params) - set(request.POST.keys()) if len(missing_params) > 0: msg = u"Missing POST parameters: {missing}".format( ...
lukovnikov/teafacto
test/test_tensorWrapped.py
Python
mit
687
0.001456
from unittest import TestCase from teafacto.core.base import Val, tensorops as T import numpy as np class TestTensorWrapped(TestCase): def test_dimswap(self): xval = np.random.randint(0, 5, (2, 3, 4)) x = Val(xval) y = x.dimswap(1, 0) eyval = xval
.transpose(1, 0, 2) self.assertTrue(np.allclose(eyval, y.eval())) def test_reverse(self): xval = np.random.randint(0, 5, (2, 3, 4)) x = Val(xval) y = x.reverse(1) yval = xval[:, ::-1, :] self.assertTrue(np.allclose(yval, y.ev
al())) y = x.reverse(0, 1) yval = xval[::-1, ::-1, :] self.assertTrue(np.allclose(yval, y.eval()))
the-blue-alliance/the-blue-alliance
old_py2/helpers/insight_manipulator.py
Python
mit
1,096
0.001825
from helpers.manipulator_base import ManipulatorBase class InsightManipulator(ManipulatorBase): """ Handle Insight database writes. """ @classmethod def updateMerge(self, new_insight, old_insight, auto_union=True): """ Given an "old" and a "new" Insight object, replace the fields ...
t, but keep fields from the "old" Insight that are null in the "new" insight. """ attrs = [ 'name', 'year', 'data_json', ] for attr in attrs: if getattr(new_insight, attr) is not None: if geta
ttr(new_insight, attr) != getattr(old_insight, attr): setattr(old_insight, attr, getattr(new_insight, attr)) old_insight.dirty = True if getattr(new_insight, attr) == "None": if getattr(old_insight, attr, None) != None: setattr(old_...
swift-lang/swift-e-lab
parsl/tests/integration/test_early_attach_bug.py
Python
apache-2.0
1,099
0.00273
"""Testing early attach behavior with LoadBalanced view Test setup: Start the ipcontroller and 1 ipengine, and run this script. The time to finish the 10 apps should be ~10s. In the second run, start the parsl script, and as soon as the run starts, start additional ipengines. The time to finish the 10 apps should st...
f rebalancing the apps among the engine once it has been sent to the the engine's queue. """ from parsl import * import time from parsl.tests.configs.local_ipp import config dfk = DataFlowKernel(config=config) @App('python', dfk) def sleep_double(x): import time time.sleep(1) return x * 2 def test_z_...
leanup(): dfk.cleanup() if __name__ == "__main__": print("Starting launch") jobs = {} for i in range(0, 20): jobs[i] = sleep_double(i) start = time.time() for i in range(0, 10): print(jobs[i].result()) print("Time to finish : ", time.time() - start)
h2oai/h2o-3
h2o-py/tests/testdir_algos/targetencoder/pyunit_te_deprecated_params.py
Python
apache-2.0
7,090
0.003385
from __future__ import print_function import os import sys import warnings sys.path.insert(1, os.path.join("..","..","..","..")) import h2o from h2o.estimators import H2OTargetEncoderEstimator from h2o.exceptions import H2ODeprecationWarning from h2o.utils.metaclass import fullname from tests import pyunit_utils as p...
te_k.train(y=ds.target, training_frame=ds.train) encoded_k = te_k.predict(ds.test) # print(encoded_k) te_ip = H2OTargetEncoderEstimator(noise=0, inflection_point=5, blending=True) te_ip.train(y=ds.target, training_frame=ds.train) encoded_ip = te_ip.p
redict(ds.test) # print(encoded_ip) try: pu.compare_frames(encoded_k, encoded, 0, tol_numeric=1e-5) assert False, "should have raised" except AssertionError as ae: assert "should have raised" not in str(ae) assert pu.compare_frames(encoded_k, encoded_ip, 0, tol_numeric=1e-5) de...
noinil/memory
kana_table_test.py
Python
gpl-2.0
3,595
0.00428
#!/usr/bin/env python3 # coding: utf-8 romaji = [] hiragana = [] katakana = [] def num_permuts(N): """Permutation of 0 -- 46 """ from random import shuffle as shf from random import seed seed() a = [i for i in range(N)] shf(a) return a[:] def main(ts): import time # ---------...
nums = num_permuts(46) l_test = romaji elif ts == 2:
nums = num_permuts(46) l_test = katakana elif ts == 3: nums = num_permuts(46) l_test = hiragana elif ts == 4: nums = num_permuts(46 * 3) l_test = romaji + hiragana + katakana else: print(' Wrong testing style!') exit() # Begin testing, log time...
plotly/python-api
packages/python/plotly/plotly/tests/test_core/test_figure_messages/test_plotly_restyle.py
Python
mit
2,977
0.00168
import sys from unittest import TestCase import plotly.graph_objs as go if sys.version_info >= (3, 3): from unittest.mock import MagicMock else: from mock import MagicMock class TestRestyleMes
sage(TestCase): def setUp(self): # Construct with mocked _send_restyle_msg method self.figure = go.
Figure( data=[ go.Scatter(), go.Bar(), go.Parcoords(dimensions=[{}, {"label": "dim 2"}, {}]), ] ) # Mock out the message method self.figure._send_restyle_msg = MagicMock() def test_property_assignment_toplevel(self): ...
jbarlow83/OCRmyPDF
src/ocrmypdf/hocrtransform.py
Python
gpl-3.0
17,755
0.000846
#!/usr/bin/env python3 # # Copyright (c) 2010, Jonathan Brinley # Original version from: https://github.com/jbrinley/HocrConverter # # Copyright (c) 2013-14, Julien Pfefferkorn # Modifications # # Copyright (c) 2015-16, James R. Barlow # Set text to transparent # # Permission is hereby granted, free of charge, to...
ent) -> Tuple[float, float]: """ Returns a tuple containing the baseline slope and intercept. """ if 'title' in element.attrib: matches = cls.baseline_pattern.search(element.attrib['title']) if matches: return float(matches.group(1)), int(matches.g...
DF units (pt) given quantity in pixels """ return Rect._make((c / self.dpi * inch) for c in pxl) def _child_xpath(self, html_tag: str, html_class: Optional[str] = None) -> str: xpath = f".//{self.xmlns}{html_tag}" if html_class: xpath += f"[@class='{html_class}']" ...
nagyistoce/devide
modules/vtk_basic/vtkFeatureEdges.py
Python
bsd-3-clause
485
0.002062
# class generated by DeVIDE::createDeVIDEModuleFromVTKObject from module_kits.vtk_kit.mixins import SimpleVTKClassModuleBase import vtk class vtkFeatureEdges(SimpleVTKClassModuleBase): def __init__(self, module_manager): SimpleVTKClassModuleBase.__init__( self, module_manager, vtk.v...
ata',), ('vtkPolyData',),
replaceDoc=True, inputFunctions=None, outputFunctions=None)
zearom32/SmartBooks
books/admin.py
Python
mit
402
0.032338
from django.contrib import admin from books.models import * # Register your models here. # Register your models here. class BookInfoAdmin(admin.ModelAdmin): list_display
=('title','isbn','price') class GoodInfoAdmin(admin.ModelAdmin): list_display=
('seller','book','price') admin.site.register(UserInfo) admin.site.register(BookInfo,BookInfoAdmin) admin.site.register(GoodsInfo,GoodInfoAdmin)
mastizada/kuma
kuma/wiki/forms.py
Python
mpl-2.0
19,906
0.000301
import re from tower import ugettext_lazy as _lazy from tower import ugettext as _ from django import forms from django.conf import settings from django.forms.widgets import CheckboxSelectMultiple from kuma.contentflagging.forms import ContentFlagForm import kuma.wiki.content from kuma.core.form_fields import Strip...
TLE_SHORT, 'max_length': TITLE_LONG}) slug = StrippedCharField(min_length=1, max_length=255,
widget=forms.TextInput(), label=_lazy(u'Slug:'), help_text=_lazy(u'Article URL'), error_messages={'required': SLUG_REQUIRED, 'min_length': SLUG_SHORT, ...
jstitch/gift_circle
gift_circle/config.py
Python
gpl-3.0
273
0.014652
# email = { "email_server" : "localhost", "email_from_addr" : "email@example.com", } twilio = { "account_sid": "twilio_account_sid", "auth_token" : "twilio_auth_token", "from_number": "twilio_from_number", "cod
e"
: "intl_code", }
mppmu/secdec
pySecDec/integral_interface.py
Python
gpl-3.0
37,101
0.013369
""" Integral Interface ------------------ An interface to libraries generated by :func:`pySecDec.code_writer.make_package` or :func:`pySecDec.loop_integral.loop_package`. """ from ctypes import CDLL, c_void_p, c_char_p, c_bool, c_int, c_uint, c_longlong, c_double, c_ulonglong from threading import Thread try: fr...
nstructed with. .. warning:: The :class:`MultiIntegrator` cannot be used with :class:`.CudaQmc`. ''' def __init__(self,integral_library,low_dim_integrator,high_dim_integrator,critical_dim): self.low_dim_integrator = low_dim_integrator # keep reference to avoid deallocation self.hig...
tegrator # keep reference to avoid deallocation self.c_lib = integral_library.c_lib self.c_lib.allocate_MultiIntegrator.restype = c_void_p self.c_lib.allocate_MultiIntegrator.argtypes = [c_void_p, c_void_p, c_int] self.c_integrator_ptr = self.c_lib.allocate_MultiIntegrator(low_dim_integr...