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
iandennismiller/mdx_journal
setup.py
Python
mit
1,319
0.000758
# mdx_journal (c) Ian Dennis Miller from setuptools import setup import os import re # from https://github.com/flask-admin/flask-admin/blob/master/setup.py def fpath(name): return os.path.join(os.path.dirname(__file__), name) def read(fname): return open(fpath(fname)).read() file_text = read(fpath('mdx_j...
ers=[ 'Development Status :: 4 - Beta', 'Operating System :: OS Independent', 'License :: OSI Approved :: BSD License', 'Intended Audience :
: Developers', 'Environment :: Web Environment', 'Programming Language :: Python', 'Topic :: Text Processing :: Filters', 'Topic :: Text Processing :: Markup :: HTML', ] )
Jenselme/mappyfile
mappyfile/ordereddict.py
Python
mit
1,542
0.001297
from collections import OrderedDict, Callable class DefaultOrderedDict(OrderedDict): # Source: http://stackoverflow.com/a/6190500/562769 # http://code.activestate.com/recipes/523034-emulate-collectionsdefaultdict/ def __init__(self, default_factory=None, *a, **kw): if (default_factory is not None a...
else: args = self.default_factory, return type(self), args, None, None, self.items() def copy(self): return self.__copy__() def __copy__(self): return type(self)(self.default_factory, self) def __deepcopy__(self, memo): import copy return
type(self)(self.default_factory, copy.deepcopy(self.items())) def __repr__(self): return 'DefaultOrderedDict(%s, %s)' % (self.default_factory, OrderedDict.__repr__(self))
wxue/xiakelite
appengine_console.py
Python
mit
973
0.004111
#!/usr/bin/env python """ For more information on the remote api: http://code.google.com/appengine/articles/remote_api.html How do you use this? python appengine_console.py <your_app_name_here> """ import code import getpass import sys from utils import find_gae_sdk find_gae_sdk() from google.appengine.ext...
f auth_func(): return raw_input('Username:'), getpass.getpass('Password:') def
main(): if len(sys.argv) < 2: print "Usage: %s app_id [host]" % (sys.argv[0]) app_id = sys.argv[1] if len(sys.argv) > 2: host = sys.argv[2] else: host = '%s.appspot.com' % app_id remote_api_stub.ConfigureRemoteDatastore(app_id, '/remote_api', ...
ging/keystone
keystone/contrib/oauth2/validator.py
Python
apache-2.0
16,189
0.002965
# Copyright (C) 2014 Universidad Politecnica de Madrid # # 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...
one associated with their one allowed grant type. # FIXME(garcianavalon) we need to support multiple grant types # for the same consumers right now. In the future we should # separate them and only allow one grant type (registering
# each client one time for each grant or allowing components) # or update the tools to allow to create clients with # multiple grants # client_dict = self.oauth2_api.get_consumer(client_id) # allowed_response_type = client_dict['response_type'] # return allowed_response_type ==...
kexinrong/macrobase
tools/py_analysis/plot_distribution.py
Python
apache-2.0
7,071
0.012445
""" Plots a scatter plot of 2 metrics provided. Data could be given from postgres or a csv file. """ from matplotlib.colors import LogNorm from mpl_toolkits.mplot3d import Axes3D import sys import numpy as np import argparse import matplotlib import matplotlib.pyplot as plt import pandas as pd from common import add_db...
es.keys()): df = interesting_data.query('{column} == "{label}"'.format(
column=args.labels, label=label)) if df.shape[0] < args.miscellaneous_cutoff * data_size: miscellaneous_labels.add(label) misc_frame = pd.concat([misc_frame, df[args.histogram]]) misc_color = color continue labels_to_show.append('{l...
wavefancy/BIDMC-PYTHON
Exome/beagle/IBDPairByPos/IBDPairByPos.py
Python
mit
1,899
0.006846
#!/usr/bin/env python3 """ Compute the number of IBD pair at each position. @Author: wavefancy@gmail.com Usage: IBDPairByPos.py IBDPairByPos.py -h | --h
elp | -v | --version | -f | --format Notes: 1. Read results from stdin(output from beagle3 fibd), and output results to stdout. 2. See example by -
f. Options: -h --help Show this screen. -v --version Show version. -f --format Show input/output file format example. """ import sys from docopt import docopt from signal import signal, SIGPIPE, SIG_DFL signal(SIGPIPE, SIG_DFL) def ShowFormat(): '''Input File format example:'''...
npuichigo/ttsflow
third_party/tensorflow/tensorflow/python/estimator/canned/linear.py
Python
apache-2.0
12,659
0.00237
# Copyright 2017 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...
ucket(...) sparse_feature_a_x_sparse_feature_b = crossed_column(...) # Estimator using the default optimizer. estimator = LinearClassifier( feature_columns=[sparse_column_a, sparse_feat
ure_a_x_sparse_feature_b]) # Or estimator using the FTRL optimizer with regularization. estimator = LinearClassifier( feature_columns=[sparse_column_a, sparse_feature_a_x_sparse_feature_b], optimizer=tf.train.FtrlOptimizer( learning_rate=0.1, l1_regularization_strength=0.001 )) ...
kidsfm/cms
team/migrations/0003_auto_20170315_1421.py
Python
gpl-3.0
532
0.00188
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-03-15 18:21 from __future__ import unicode_literals from django.db import migrations, mod
els import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('team', '0002_auto_20170315_1342'), ] operations = [ migrations.AlterField( model_name='interest', name='member', field=models.ForeignKey(on_delete=django.db....
to='team.Member'), ), ]
oscar6echo/ezhc
ezhc/__init__.py
Python
mit
463
0
# from ._config import load_js_libs from ._proxy import Proxy from ._highcharts import Highcharts from ._highstock import Highsto
ck from ._global_options import GlobalOptions from ._theme import Theme from . import sample from . import build from ._clock import Clock __all__ = ['Highcharts', 'Highstock', 'GlobalOptions', 'Theme', 'sample', 'build', 'Clock', ] # load...
genzgd/Lampost-Mud
lampmud/env/room.py
Python
mit
9,037
0.001107
import itertools import random from collections import defaultdict from lampost.di.app import on_app_start from lampost.di.config import on_config_change, config_value from lampost.di.resource import Injected, module_inject from lampost.event.zone import Attachable from lampost.gameops.action import ActionCache from l...
_each from lampmud.comm.broadcast import Broadcast from lampmud.env.movement import Direction log = Injected('log') ev = Injected('dispatcher') db = Injected('datastore') module_inject(__name__) @on_app_start @on_co
nfig_change def _config(): global room_reset_time room_reset_time = config_value('room_reset_time') class Exit(CoreDBO): class_id = 'exit' destination = DBOLField(dbo_class_id='room', required=True) direction = DBOField() desc = DBOField() aliases = DBOField([]) match_args = 'source',...
flyaos/Luoo.net
luoo_Download.py
Python
gpl-2.0
5,357
0.01232
import url
lib2 import os import re import time print '---------------------------------------------------------------' print 'Name: Luoo.net-Mp3 crawler ' print 'version: v1.0' print 'author: ChenYao' print 'data: 2013/9/4' print 'Introductions: the music will Downloaded to path D:\\Luoo.net\\' print '----------------------...
['?', '!' , '\\' , '/' , '#' ,'%' , '*', '^' , '~'] sourUrl = 'http://www.luoo.net/radio/radio' rawPath = "d:\\Luoo.net\\" coverRaw = 'http://www.luoo.net/wp-content/uploads/' htmlRaw = 'http://www.luoo.net/' #sourUrl_296 = 'http://www.luoo.net/radio/radio296/mp3.xml' #sourUrl_1 = 'http://www.luoo.net/radio/radio1/...
jfroco/atari800-rpi
atari5200.py
Python
gpl-2.0
3,320
0.000904
#!/usr/bin/python import os, struct, array from fcntl import ioctl SDL_JOY_0_SELECT = 8 SDL_JOY_0_START = 9 SDL_JOY_0_TRIGGER1 = 0 SDL_JOY_0_TRIGGER2 = 1 SDL_JOY_0_ASTERISK = 2 SDL_JOY_0_HASH = 3 SDL_JOY_0_SECOND_AXIS = 2 # Iterate over the joystick devices. # print('Available devices:') devices = sorted(os.listdir...
SDL_JOY_0_TRIGGER2 = p[1].replace('"', '') elif p[0] == "input_x_btn": SDL_JOY_0_ASTERISK = p[1].replace('"', '') elif p[0] == "input_y_btn": SDL_JOY_0_HASH = p[1].replace('"', '') elif p[0] == "input_r_x_minus_axis": SDL_JOY_0_SECOND_AXIS = p[1].replace('"...
s" % SDL_JOY_0_SELECT print "SDL_JOY_0_START=%s" % SDL_JOY_0_START print "SDL_JOY_0_TRIGGER1=%s" % SDL_JOY_0_TRIGGER1 print "SDL_JOY_0_TRIGGER2=%s" % SDL_JOY_0_TRIGGER2 print "SDL_JOY_0_ASTERISK=%s" % SDL_JOY_0_ASTERISK print "SDL_JOY_0_HASH=%s" % SDL_JOY_0_HASH print "SDL_JOY_0_SECOND_AXIS=%s" % SDL_JOY_0_SECOND_AXIS ...
opennode/nodeconductor-assembly-waldur
src/waldur_openstack/openstack/tests/helpers.py
Python
mit
282
0
impor
t copy from django.conf import settings from django.test import override_settings def override_openstack_settings(**kwargs): os_settings = copy.deepcopy(settings.WALDUR_OPENSTACK) os_settings.update(kwargs) return override_settings(WALDUR_OPEN
STACK=os_settings)
solintegra/addons
payment_sips/controllers/main.py
Python
agpl-3.0
1,864
0
# -*- coding: utf-8 -*- try: import simplejson as json except ImportError: import json import logging import werkzeug from openerp import http from openerp.http import request _logger = logging.getLogger(__name__) class SipsController(http.Controller): _notify_url = '/payment/sips/ipn/' _return_url...
return_url', '') if not return_url: tx_obj = request.registry['payment.transaction'] data = tx_obj._sips_data_to_object(post.get('Data')) custom = json.loads(data.pop('returnContext', False) or '{}') return_url = custom.get('return_url', '/') return return...
env['payment.transaction'] acquirer_obj = env['payment.acquirer'] sips = acquirer_obj.search([('provider', '=', 'sips')], limit=1) security = sips._sips_generate_shasign(post) if security == post['Seal']: _logger.debug('Sips: validated data') res = tx_obj.sudo(...
eviljeff/olympia
src/olympia/applications/api_urls.py
Python
bsd-3-clause
185
0
from django.urls import path from .views import AppVersionView urlpatterns = [ path('<str
:application>/<str:version>/', AppVersionView.as_view(), name='appversions'
), ]
ro-kue/pynv
app/forms.py
Python
mit
3,240
0.001852
from flask_wtf import FlaskForm from flask_login import current_user from wtforms import StringField, PasswordField, BooleanField, HiddenField, SubmitField, IntegerField, DateField from wtforms.validators import DataRequired, EqualTo, ValidationError, NumberRange from config import CURRENCY, DECIMAL, THOUSANDS import b...
ield("remember_me", default=False) def validate_username(self
, field: StringField): if not userDao.user_exists(self.username.data): raise ValidationError(lazy_gettext("User doesn't exist")) class TableEditForm(FlaskForm): update = HiddenField("update", default="insert") art_num = StringField("art_num", validators=[DataRequired()]) kat = StringFi...
takeshineshiro/keystone
keystone/tests/unit/test_backend_sql.py
Python
apache-2.0
37,925
0
# -*- coding: utf-8 -*- # Copyright 2012 OpenStack Foundation # # 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 applic...
main', sql.Boolean, False)) self.assertExpectedSchema('project', cols) def test_role_as
signment_model(self): cols = (('type', sql.Enum, None), ('actor_id', sql.String, 64), ('target_id', sql.String, 64), ('role_id', sql.String, 64), ('inherited', sql.Boolean, False)) self.assertExpectedSchema('assignment', cols) def test...
dieterv/gnome-python-desktop
examples/gnomeprint/example_02.py
Python
lgpl-2.1
2,964
0.012483
#! /usr/bin/env python #/* # * example_02.c: sample gnome-print code # * # * This program is free software; you can redistribute it and/or # * modify it under the terms of the GNU Library General Public License # * as published by the Free Software Foundation; either version 2 of # * the License, or (at your optio...
(x + y) >> 1, (x + (pixels - 1 - y)) >> 1, ((pixels - 1 - x) + y) >> 1)) # All images in postscript are printed on a 1 x 1 square, since we # want an image which has a size of 2" by 2" inches, we have to scale # t
he CTM (Current Transformation Matrix). Save the graphic state and # restore it after we are done so that our scaling does not affect the # drawing calls that follow. gpc.gsave() gpc.scale(144, 144) gpc.rgbimage("".join(color_image), pixels, pixels, pixels * 3) gpc.grestore() def my_draw(gpc):...
kondrak/graph_bfs_solver
solver.py
Python
mit
7,116
0.00534
# *** BFS Graph Solver *** # (c) Krzysztof Kondrak (at) gmail (dot) com import sys import os import itertools import getopt import pickle from graph import * from pathFinding import * from tools import ProgressBar, usage, processGraphFile sys.path.append(os.getcwd()) SILENT_MODE = False def Message(msg): if no...
try: opts, args = getopt.getopt(argv, "?gst:l:f:i:a:chr:", ["help", "guiFormat", "silent", "travellers=", "limit=", "filename=", "min=", "
max=", "cyclic", "allowHomes", "allowhomes", "redundancy="]) for opt, arg in opts: if opt in ("-?", "--help"): usage() sys.exit(1) if opt in ("-t", "--travellers"): numTravellers = int(arg) if opt in ("-l",...
wadobo/etruekko
etruekko/truekko/migrations/0013_auto__add_field_userprofile_receive_notification.py
Python
agpl-3.0
15,657
0.007473
# -*- coding: 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 field 'UserProfile.receive_notification' db.add_column('truekko_userprofile', 'receive_notification...
th': '500'}), 'photo': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'web': ('django.db.models.fields.URLField', [], {'default': "''", 'max_length': '200', 'null': 'True', 'b
lank': 'True'}) }, 'truekko.item': { 'Meta': {'ordering': "['-pub_date']", 'object_name': 'Item'}, 'description': ('django.db.models.fields.TextField', [], {}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.m...
Azure/azure-sdk-for-python
sdk/storage/azure-mgmt-storage/azure/mgmt/storage/v2015_06_15/_configuration.py
Python
mit
3,327
0.004208
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may ...
self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs) self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs) self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLog
gingPolicy(**kwargs) self.http_logging_policy = kwargs.get('http_logging_policy') or ARMHttpLoggingPolicy(**kwargs) self.retry_policy = kwargs.get('retry_policy') or policies.RetryPolicy(**kwargs) self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs) ...
ClusterLabs/crmsh
crmsh/utils.py
Python
gpl-2.0
85,016
0.001176
# Copyright (C) 2008-2011 Dejan Muhamedagic <dmuhamedagic@suse.de> # See COPYING for license information. import os import sys from tempfile import mkstemp import subprocess import re import glob import time import datetime import shutil import shlex import bz2 import fnmatch import gc import ipaddress import argparse...
(prog): """Is this program available?""" def isexec(filename): return os.path.isfile(filename) and os.access(filename, os.X_OK) for p in os.getenv("PATH").split(os.pathsep): f = os.path.join(p, prog) if isexec(f):
return f return None def pacemaker_20_daemon(new, old): "helper to discover renamed pacemaker daemons" if is_program(new): return new return old @memoize def pacemaker_attrd(): return pacemaker_20_daemon("pacemaker-attrd", "attrd") @memoize def pacemaker_based(): return...
theo-l/django
tests/auth_tests/test_management.py
Python
bsd-3-clause
41,076
0.001388
import builtins import getpass import os import sys from datetime import date from io import StringIO from unittest import mock from django.apps import apps from django.contrib.auth import get_permission_codename, management from django.contrib.auth.management import ( create_permissions, get_default_username, ) f...
@staticmethod def getpass(prompt=b'Password: ', stream=None): if callable(inputs['password']): return inputs['password']() return inputs['password'] def mock_input(prompt): assert '__proxy__' n
ot in prompt response = None for key, val in inputs.items(): if val == 'KeyboardInterrupt': raise KeyboardInterrupt # get() fallback because sometimes 'key' is the actual # prompt rather than a shortcut n...
kenelite/vmapi
005reset.py
Python
mit
4,622
0.000649
#!/usr/bin/env python import atexit import argparse import getpass import sys import textwrap import time from pyVim import connect from pyVmomi import vim import requests requests.packages.urllib3.disable_warnings() import ssl try: _create_unverified_https_context = ssl._create_unverified_context except Att...
ng this means you don't need to remember to disconnect your script/objects atexit.register(connect.Disconnect, si) # search the whole inventory tree recursively... a brutish but effective tactic vm = None entity_stack = si.content.rootFolder.childEntity while entity_stack: entity = enti
ty_stack.pop() if entity.name == args.name: vm = entity del entity_stack[0:len(entity_stack)] elif hasattr(entity, 'childEntity'): entity_stack.extend(entity.childEntity) elif isinstance(entity, vim.Datacenter): entity_stack.append(entity.vmFolder) if not isinstance(vm, vim...
t-wissmann/qutebrowser
tests/unit/misc/test_pastebin.py
Python
gpl-3.0
3,668
0
# vim: ft=python fileencoding=utf-8 sts=4 sw=4 et: # Copyright 2016-2020 Florian Bruhin (The-Compiler) <me@the-compiler.org> # Copyright 2016-2018 Anna Kobak (avk) <awerk@onet.eu>: # # This file is part of qutebrowser. # # qutebrowser is free software: you can redistribute it and/or modify # it under the terms of the ...
tle": "the title", "text": "some Text", "reply": "some parent", "apikey": "ihatespam", } ]) def test_paste_with_parent(data, pbclient): http_stub = pbclient._client pbclient.paste(data["name"], data["title"], data["text"], data["reply"]) assert http_stub.data == data assert h...
'data', [ { "name": "XYZ", "title": "hello world", "text": "xyz. 123 \n 172ANB", "apikey": "ihatespam", }, { "name": "the name", "title": "the title", "text": "some Text", "apikey": "ihatespam", } ]) def test_paste_without_parent(data, pbcl...
EdwardJKim/nbgrader
nbgrader/tests/apps/test_nbgrader_assign.py
Python
bsd-3-clause
13,634
0.002934
import os import sys import pytest from os.path import join from sqlalchemy.exc import InvalidRequestError from textwrap import dedent from ...api import Gradebook from .. import run_nbgrader from .base import BaseTestApp class TestNbGraderAssign(BaseTestApp): def test_help(self): """Does the help disp...
", "a") as fh: fh.write("""c.NbGrader.db_assignments = [dict(name="ps1")]\n""") run_nbgrader(["assign", "ps1"])
assert os.path.isfile(join(course_dir, 'release', 'ps1', 'test.ipynb')) assert os.path.isfile(join(course_dir, 'release', 'ps1', 'foo.txt')) assert os.path.isfile(join(course_dir, 'release', 'ps1', 'data', 'bar.txt')) assert not os.path.isfile(join(course_dir, 'release', 'ps1', 'blah.py...
DarthThanatos/citySimNG
citySimNGView/CreatorView/RelativePaths.py
Python
apache-2.0
200
0.005
relative_music_path = "resources\\Music\\" relative_textures_path = "resources\\Te
xtures\\" relative_text_files_path = "resources\\TextFiles\\" relative_dependencies_path = "resources\\dependencies\\
"
zyzyis/monetdb
sql/test/BugTracker-2013/Tests/binary_copy_into.Bug-3345.SQL.py
Python
mpl-2.0
1,040
0.026923
import os, sys, shutil try: from MonetDBtesting import process except ImportError: import process src = os.environ['RELSRCDIR'] dst = os.environ['TSTTRGDIR'] clt = process.client('sql', stdin = process.PIPE, stdout = process.PIPE, stderr = process...
in(src,'n_regionkey.sorted'), os.path.join(dst,'n_regionkey.sorted')) clt.stdin.write('start transaction;'); clt.stdin.write('create table bug (n_nationkey INTEGER,n_r
egionkey INTEGER);\n') clt.stdin.write('copy binary into bug from \'%s/n_nationkey.sorted\', \'%s/n_regionkey.sorted\';\n'% (dst,dst)) out, err = clt.communicate() sys.stdout.write(out.replace(os.environ['TSTTRGBASE'],'${TSTTRGBASE}').replace('\\','/')) sys.stderr.write(err.replace(os.environ['TSTTRGBASE'],'${TSTTRGBA...
nguyenngochuy91/Ancestral-Blocks-Reconstruction
checkGGPS2.py
Python
gpl-3.0
107
0.009346
#!/usr/bin/
env python2 # -*- coding: utf-8 -*- """ Created
on Tue Jun 12 13:45:31 2018 @author: huyn """
jcalazan/glucose-tracker
glucosetracker/core/migrations/0003_auto__del_usersettingsmodel__add_usersettings.py
Python
mit
5,638
0.007804
# -*- coding: 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): # Deleting model 'UserSettingsModel' db.delete_table(u'core_usersettingsmodel') # Adding model 'Use...
=True, blank=True)), ('user', self.gf('django.db.models.fields.related.ForeignKey')(related_name='settings', unique=True, to=orm['auth.User'])), ('time_zone', self.gf('django.db.models.fields.CharField')(max_length=155)), )) db.send_create_signal(u'core', ['UserSe
ttings']) def backwards(self, orm): # Adding model 'UserSettingsModel' db.create_table(u'core_usersettingsmodel', ( ('created', self.gf('django.db.models.fields.DateTimeField')(auto_now_add=True, blank=True)), ('time_zone', self.gf('django.db.models.fields.CharField')(max_l...
gordonzola/naobot
plugins/karma.py
Python
agpl-3.0
6,939
0.000145
# -*- coding: utf-8 -*- import re import random from stdPlugin import stdPlugin # Universal quantifier on a sequence. def forall(sequence, predicate): return reduce(lambda x, y: x and y, map(predicate, sequence), True) class karma(stdPlugin): u'''Chaque terme suivi de '++' ou '--' se voit attribuer un kar...
changed = True if changed:
self.save_karmadb(chan) def match_words(self, serv, chan, message): """Try to match a word known in the karma database, and react accordingly. To (somewhat) avoid spam, we only react to one word in the message, the one with the greatest absolute karma.""" words = [w.stri...
xolox/python-humanfriendly
humanfriendly/deprecation.py
Python
mit
9,499
0.001053
# Human friendly input/output in Python. # # Author: Peter Odding <peter@peterodding.com> # Last Change: March 2, 2020 # URL: https://humanfriendly.readthedocs.io """ Support for deprecation warnings when importing names from old locations. When software evolves, things tend to move around. This is usually detrimenta...
ional) keyword arguments as
my code evolves to support more use cases. .. [#] In my experience positional argument order implicitly becomes part of API compatibility whether intended or not. While this makes sense for functions that over time adopt more and more optional arguments, at a certain poi...
joshuajnoble/ofxPython
example_ScriptTester/bin/data/mytest.py
Python
mit
756
0.055556
#test import random from openframeworks import * print "-"
*30 class myApp(object): def __init__(self): self.x = 50.0 self.y = 50.0 self.d = 10 self.fbo = ofFbo() self.fbo.allocate(100,100) def update(self): self.x += random.random()-.5 self.y += random.random()-.5 def
draw(self): self.fbo.begin() ofClear(0) color = ofColor(255,0,0) ofSetColor(color) ofCircle(self.x,self.y,self.d) self.fbo.end() self.fbo.draw(200,200) def mouseMoved(self, x, y): pass def mousePressed(self, x, y, button): pass def mouseDragged(self, x, y, buton): pass def mouseReleased(self...
MarkWh1te/xueqiu_predict
crawler/init_db.py
Python
mit
65
0
from utils import Base, engine Base.metadata.cr
eate_all(engi
ne)
statisticalbiotechnology/GPTime
GPTime/peptides/load.py
Python
apache-2.0
1,114
0.012567
import numpy as np from .peptide import peptide def _check_duplicates(peptides): candiates = [] rt = [] for pp in peptides: if pp.sequence not in candiates: candiates.append(pp.sequence) rt.append(pp.rt) if len(candiates) == len(peptides): return "No duplicated ...
e have same RT" def load( fname, check_duplicates=True, randomize=False ): with open(fname, 'r') as ff : lines = ff.readlines() peptides = [] for l in lines : l = l.strip() values = l.split('\t') peptides.append(peptide(values[0],float(values[1]))) ...
) return peptides
nttks/edx-platform
common/lib/xmodule/xmodule/course_module.py
Python
agpl-3.0
61,092
0.003241
""" Django module container for classes and operations related to the "Course Module" content type """ import logging from cStringIO import StringIO from lxml import etree from path import Path as path from pytz import utc import requests from datetime import datetime from lazy import lazy from xmodule import course_m...
we already fetched this if toc_url in _cached_toc: (table_of_contents, timestamp) = _cached_toc[toc_url] age = datetime.now(utc) - timestamp # expire every 10 minutes if age.seconds
< 600: return table_of_contents except Exception as err: pass # Get the table of contents from S3 log.info("Retrieving textbook table of contents from %s", toc_url) try: r = requests.get(toc_url) except Exception as err: ms...
petewarden/tensorflow
tensorflow/python/keras/distribute/dataset_creator_model_fit_test.py
Python
apache-2.0
8,765
0.005362
# Lint as: python3 # Copyright 2021 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 requ...
nput_context x = random_ops.random_uniform((10, 10)) y = random_ops.rando
m_uniform((10,)) return dataset_ops.DatasetV2.from_tensor_slices( (x, y)).shuffle(10).repeat().batch(2) x = x or dataset_creator.DatasetCreator(dataset_fn) model.fit( x, epochs=10, steps_per_epoch=steps_per_epoch, verbose=0, callbacks=callbacks, ...
ssuljic/language-correlation
languagecorrelation/settings.py
Python
mit
2,352
0.001276
""" Django settings for languagecorrelation project. For more information on this file, see https://docs.djangoproject.com/en/1.6/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.6/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_...
e.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ) DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } ROOT_URLCONF = 'languagecorrelation.urls' WSGI_APPLICATION = 'languagecorrelation.wsgi.application' # Internationalization # https://docs.djangoproject.com/en/1.6/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True ...
xuru/pyvisdk
pyvisdk/do/vim_esx_cl_iiscsiadaptertargetlist_target.py
Python
mit
1,164
0.007732
import logging from pyvisdk.exceptions import InvalidArgumentError # This module is NOT auto-generated # Inspired by decompiled Java classes from vCenter's internalvim25stubs.jar # Unless states otherside, the methods and attributes were not used by esxcli, # and thus not tested log = logging.getLogger(__name__) de...
daptertargetlistTarget(vim, *args, **kwargs): obj = vim.client.factory.create('ns0:VimEsxCLIiscsiadaptertargetlistTarget') # do some validation checking... if (len(args) + len(kwargs)) < 0: raise IndexError('Expected at least 1 arguments got: %d' % len(args)) required = [ ] optiona
l = [ 'Adapter', 'Alias', 'DiscoveryMethod', 'ID', 'LastError', 'MaxConnections', 'SendTargetsDiscoveryEnabled', 'SendTargetsDiscoverySettable', 'Target' ] for name, arg in zip(required + optional, args): setattr(obj, name, arg) for name, value in kwargs.items(): if name in required + optional...
open-craft/django-lti-tool-provider
django_lti_tool_provider/tests/test_views.py
Python
agpl-3.0
12,681
0.00205
import ddt from django.contrib.auth import login, authenticate from importlib import import_module from django_lti_tool_provider import AbstractApplicationHookManager from mock import patch, Mock from oauth2 import Request, Consumer, SignatureMethod_HMAC_SHA1 from django.contrib.auth.models import User from django.te...
mousLtiRequestTests(LtiRequestsTestBase): def setUp
(self): super(AnonymousLtiRequestTests, self).setUp() self.hook_manager.anonymous_redirect_to = Mock(return_value=self.DEFAULT_REDIRECT) def test_given_incorrect_payload_throws_bad_request(self): response = self.send_lti_request(self.get_incorrect_lti_payload()) self.assertEqual(res...
kapilrastogi/Impala
tests/common/impala_test_suite.py
Python
apache-2.0
23,340
0.01024
# Copyright (c) 2012 Cloudera, 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 o...
host_port=host_port, use_kerberos=pytest.config.option.use_kerberos) client.connect() return client @classmethod def create_impala_service(cls
, host_port=IMPALAD, webserver_port=25000): host, port = host_port.split(':') return ImpaladService(host, beeswax_port=port, webserver_port=webserver_port) @classmethod def create_hdfs_client(cls): if pytest.config.option.namenode_http_address is None: hdfs_client = get_hdfs_client_from_conf(HDFS...
fenhl/lazyjson
lazyjson/__init__.py
Python
mit
15,325
0.00398
import abc try: import collections.abc as collectionsabc except ImportError: import collections as collectionsabc import decimal import io import json import locale import os import os.path import subprocess import threading import time def parse_version_string(): path = os.path.abspath(__file__) while...
json_value = self.value() item = json_value if len(key_path) == 0: json_value = new_value else: for key in key_path[:-1]: item = item[key] item[key_path[-1]] = new_value self.set(json_value) @abc.abstractmethod def valu...
et class File(BaseFile): """A file based on a file-like object, a pathlib.Path, or anything that can be opened.""" def __init__(self, file_info, file_is_open=None, tries=10, init=..., **kwargs): super().__init__() self.open_args = dict(kwargs) self.file_is_open = isinstance(file_info, i...
singingwolfboy/seamless-karma
seamless_karma/config/test_postgres.py
Python
mit
172
0
# testing co
nfiguration DEBUG = True TESTING = True SECRET_KEY = "dummy" CACHE_NO_NULL_WARNING
= True SQLALCHEMY_DATABASE_URI = "postgres://localhost/seamless_karma_test"
brain-tec/partner-contact
partner_contact_in_several_companies/models/ir_actions.py
Python
agpl-3.0
922
0
# -*- coding: utf-8 -*- # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import api, models class IRActionsWindow(models.Model): _inherit = 'ir.actions.act_window' @api.multi def read(self, fields=None, context=None, load='_classic_read'): actions = super(IRActionsW...
load=load) for action in actions: if action.get('res_model', '') == 'res.partner': # By default, only show standalone contact action_context = action.get('context', '{}') or '{}' if 'searc
h_show_all_positions' not in action_context: action['context'] = action_context.replace( '{', ("{'search_show_all_positions': " "{'is_set': True, 'set_value': False},"), 1) return actions
infobloxopen/infoblox-netmri
infoblox_netmri/api/broker/v3_8_0/auth_cac_cert_broker.py
Python
apache-2.0
26,153
0.001912
from ..broker import Broker class AuthCacCertBroker(Broker): controller = "au
th_cac_certs" def index(self, **kwargs): """Lists the available auth cac certs. Any of the inputs listed may be be used to narrow the list; other inputs will be
ignored. Of the various ways to query lists, using this method is most efficient. **Inputs** | ``api version min:`` 3.7 | ``api version max:`` None | ``required:`` False | ``default:`` None :param auth_server_id: ID of auth server of OCSP ...
andersx/fml
tests/test_aras.py
Python
mit
6,751
0.08695
#!/usr/bin/env python2 import sys sys.path.append('../fml/') import os import numpy as np import fml import random t_width = np.pi / 4.0 # 0.7853981633974483 d_width = 0.2 cut_distance = 6.0 r_width = 1.0 c_width = 0.5 PTP = {\ 1 :[1,1] ,2: [1,8]#Row1 ,3 :[2,1] ,4: [2,2]#Row2\ ...
for j in range(n2): d = 0.0 for k in range(n1): e = 0.0 for l in range(n2): e += ksi2[l] * np.exp(-(atom1[i+3,k] - atom2[j+3,l])**2 / (4.0 * t_width**2)) d += e * ksi1[k] c += d * np.exp(-(atom1[0,i] - atom2[0...
= a * b return dist def aras_distance(mol1, mol2, max_size=30): d = np.zeros((mol1.natoms, mol2.natoms)) aa = np.zeros((mol1.natoms)) bb = np.zeros((mol2.natoms)) for i in range(mol1.natoms): atom1 = mol1.aras_descriptor[i] aa[i] = aras_scalar(atom1, atom1, mol1.nuc...
google/trax
trax/layers/activation_fns_test.py
Python
apache-2.0
1,833
0.003273
# coding=utf-8 # Copyright 2022 The Trax 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 applicable law or a...
ing import absltest import numpy as
np import trax.layers as tl class ActivationFnsTest(absltest.TestCase): def test_relu(self): layer = tl.Relu() x = np.array([-2.0, -1.0, 0.0, 2.0, 3.0, 5.0]) y = layer(x) self.assertEqual(tl.to_list(y), [0.0, 0.0, 0.0, 2.0, 3.0, 5.0]) def test_parametric_relu(self): layer = tl.ParametricRe...
kernsuite-debian/lofar
MAC/Services/TaskManagement/Server/test/t_taskmanagement.py
Python
gpl-3.0
6,040
0.00298
#!/usr/bin/env python3 # Copyright (C) 2017 ASTRON (Netherlands Institute for Radio Astronomy) # P.O. Box 2, 7990 AA Dwingeloo, Th
e Netherlands # # This file is part of the LOFAR software suite. # The LOFAR software suite 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 vers...
he 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. # # You should have received a copy of the GNU General Public License along # with the LOFAR software suite. I...
seanli9jan/tensorflow
tensorflow/python/kernel_tests/gather_op_test.py
Python
apache-2.0
10,957
0.008305
# Copyright 2015 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...
_ops.gather( tf_params, tf_indices, axis=tf_negative_axis) gather_value, gather_negative_axis_value = sess.run( [gather, gather_negative_axis]) gather_np = np.take(params, indices, axis) self.assertAllEqual(gather_np, gather_value) self.ass...
self.assertEqual(expected_shape, gather.shape) self.assertEqual(expected_shape, gather_negative_axis.shape) # Test gradients gather_grad = np.random.randn( *gather.get_shape().as_list()).astype(dtype.as_numpy_dtype) if dtype.is_complex: ...
williamFalcon/pytorch-lightning
pytorch_lightning/utilities/warnings.py
Python
apache-2.0
1,609
0.000622
# Copyright The PyTorch Lightning team. # # 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.a
pache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # li...
under the License. """Warning-related utilities""" import warnings from functools import partial from pytorch_lightning.utilities.distributed import rank_zero_only def _warn(*args, stacklevel: int = 2, **kwargs): warnings.warn(*args, stacklevel=stacklevel, **kwargs) @rank_zero_only def rank_zero_warn(*args, st...
TiVo/kafka
tests/kafkatest/tests/streams/streams_eos_test.py
Python
apache-2.0
9,430
0.004136
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use ...
self.stop_streams(processor1) processor1.clean_node_enabled = True self.driver.stop()
verifier.start() verifier.wait() verifier.node.account.ssh("grep ALL-RECORDS-DELIVERED %s" % verifier.STDOUT_FILE, allow_fail=False) @cluster(num_nodes=9) @parametrize(processing_guarantee="exactly_once") @parametrize(processing_guarantee="exactly_once_v2") def test_failure_and_re...
eirikgje/healpy
setup.py
Python
gpl-2.0
19,062
0.00362
#!/usr/bin/env python # Bootstrap setuptools installation. We require setuptools >= 3.2 because of a # bug in earlier versions regarding C++ sources generated with Cython. See: # https://pypi.python.org/pypi/setuptools/3.6#id171 try: import pkg_resources pkg_resources.require("setuptools >= 3.2") except: ...
for token in check_output(cmd, env=self._environ).split()] if args: for key in keys: kw.setdefault(key, []).extend(args) return kw def finalize_options(self):
"""Run 'autoreconf -i' for any bundled libraries to generate the configure script.""" build_clib.finalize_options(self) for lib_name, build_info in self.libraries: if 'sources' not in build_info: log.info("checking if configure script for library '%s' exists", ...
gmr/pamqp
tools/codegen.py
Python
bsd-3-clause
45,302
0.000177
#!/usr/bin/env python """Generates the pamqp/specification.py file used as a foundation for AMQP communication. """ import copy import dataclasses import functools import json import keyword import logging import pathlib import sys import textwrap import typing import lxml.etree, lxml.objectify import requests from y...
synchronous commands and if so, what the expected responses are. Each commands arguments are detailed in the class and are listed in the attributes property. .. note:: All AMQ classes and methods extend :class:`pamqp.base.Frame`. """ # Auto-generated, do not edit this file. import datetime import typing import warnin...
DER = ''' # Auto-generated, do not edit this file. import re ''' EXCEPTIONS = pathlib.Path('./pamqp/exceptions.py') EXCEPTIONS_HEADER = ''' # Auto-generated, do not edit this file. class PAMQPException(Exception): """Base exception for all pamqp specific exceptions.""" class UnmarshalingException(PAMQPExceptio...
brguez/TEIBA
src/python/clusterClippedReads.py
Python
gpl-3.0
25,308
0.010881
#!/usr/bin/env python #coding: utf-8 #### CLASSES #### class fasta(): """ """ def __init__(self): """ """ self.fastaDict = {} #### FUNCTIONS #### def fasta_reader(self, fastaFile): """ """ fastaDict = {} subHeader("Fasta reader") ...
dPairedClusters(chrPlus, begPlus, endPlus, chrMinus, begMinus, endMinus, rgType, bamFile, windowSize): """ """ ## 1. Extract clipped reads for positive cluster chrom = chrPlus if (rgType == "DUP"): beg = int(begPlus) - windowSize end = int(begPlus)
+ windowSize else: beg = int(endPlus) - windowSize end = int(endPlus) + windowSize clippedBegPlusList, clippedEndPlusList = getClippedInterval(chrom, beg, end, bamFile) ## 2. Extract clipped reads for negative cluster chrom = chrMinus if (rgType == "DUP"): beg = int(endMin...
sh4wn/vispy
vispy/visuals/tests/test_rectangle.py
Python
bsd-3-clause
6,191
0
# -*- coding: utf-8 -*- """ Tests for RectPolygonVisual All images are of size (100,100) to keep a small file size """ from vispy.scene import visuals, transforms from vispy.testing import (requires_application, TestingCanvas, run_tests_if_main, raises) from vispy.testing.image_tester impor...
: """Test drawing rectpolygons without transform using RectPolygonVisual""" with TestingCanvas() as c: rectpolygon = visuals.Recta
ngle(center=(50, 50, 0), height=40., width=80., color='red', parent=c.scene) assert_image_approved(c.render(), 'visuals/rectpolygon1.png') rectpolygon.parent = None rectpolygon = visuals.Rectangle(center=(50, 50, 0...
richardliaw/ray
rllib/examples/rock_paper_scissors_multiagent.py
Python
apache-2.0
5,789
0
"""A simple multi-agent env with two agents playing rock paper scissors. This demonstrates running the following policies in competition: (1) heuristic policy of repeating the same move (2) heuristic policy of beating the last opponent move (3) LSTM/feedforward PG policies (4) LSTM policy with custom e...
"policy_mapping_fn": select_policy, }, "framework": "torch" if args.torch else "tf", } cls = get_agent_class(trainer) if isinstance(trainer, str) else trainer trainer_obj = cls(config=config) env = trainer_obj.workers.local_worker().env for _ in range(args.stop_iters): resul...
boulder-python/boulderpython.org
tests/mocks/trello.py
Python
mit
1,457
0
# -*- coding: utf-8 -*- """ tests.trello.py ~~~~~~~~~ a Trello mock for testing """ from flask import current_app as app class MockTrelloCard: id = 1 url = "http://mock.trello.com/card/1" def __init__(self): return class MockTrelloLabel: def __init__(self, _id, name, *args, **kw...
get_list(self, _id, *args, **kwargs): return MockTrelloList(_id) class MockTrelloClient: def __init__(self, *args, **kwargs): return @property def board(self): return self.get_board(1) def get_board(self, board_id): return MockTrelloBoard() @property def new...
elf.board.get_list(1) @property def labels(self): label_idx = 0 labels = {} for label_group in app.config["DEFAULT_TRELLO_LABELS"].values(): for label_name in label_group: labels[label_name] = label_idx label_idx += 1 return labels
xkmato/tracpro
tracpro/msgs/migrations/0003_remove_message_issue.py
Python
bsd-3-clause
349
0
# -*- coding:
utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('msgs', '0002_auto_20150204_1116'), ] operations = [ migrations.RemoveField( model_name='message', name='issue', ...
gertjanvanzwieten/vimdecrypt
setup.py
Python
gpl-2.0
216
0
#! /usr/
bin/env python3 import setuptools setuptools.setup( name='vimdecrypt', version='2.0', author='Gertjan van Zwieten', py_modules=['vimdecrypt'], scripts=['vimdecrypt'], test_sui
te='vimdecrypt', )
himanshu-dixit/oppia
core/controllers/moderator.py
Python
apache-2.0
2,847
0
# Copyright 2014 The Oppia Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable ...
featured_activity_references() ], }) @acl_decorators.can_access_moderator_page def post(self): """Handles POST requests.""" featured_activity_reference_dicts = self.payload.get( 'featured_activity_reference_dicts') featured_activity_references = [ ...
reference_dict['type'], reference_dict['id']) for reference_dict in featured_activity_reference_dicts] try: summary_services.require_activities_to_be_public( featured_activity_references) except Exception as e: raise self.InvalidInputExcepti...
Iliricon/hero-manager
src/hero/views.py
Python
gpl-3.0
7,791
0.000898
from django.http import HttpResponseRedirect from django.shortcuts import redirect from django.urls import reverse_lazy, reverse from django.views.generic import ListView, DetailView, FormView, CreateView, \ UpdateView from django.views.generic.base import TemplateView, View from django.contrib.auth.mixins import L...
game_master=self.request.user ) group.save() return HttpResponseRedirect(self.get_success_url()) def get_success_url(self): return reverse_lazy('hero:group_detail', args=(self.object.name,)) class Pl
ayerDetailView(LoginRequiredMixin, DetailView): pass class GroupAddHeroView(LoginRequiredMixin, CreateView): template_name = "groups_add_hero.html" form_class = HeroAddForm def get_context_data(self, **kwargs): context = super(CreateView, self).get_context_data(**kwargs) context['grou...
securesocketimproved/ssi
socksv/socksvRemoteServer.py
Python
gpl-3.0
5,289
0.002269
import socket import threading from socksv.tcpRelay import tcpRelay from pluginHelper.IPlugin import ILoginSocketProvider from socksv.socksvSocketServer import socksvSocketServer from pluginHelper.pluginStackPrototype import pluginStackPrototype class socksvRemoteServer(socksvSocketServer): CMD_CONNECT...
return conn = socket.socket() try: print("connecting remote server.") conn.connect((addr, port)) except socket.error: print("connection failed.") self.loginPlugin.sendReply(clien...
SocketProvider.REPLY_FAILED, "0.0.0.0", 0) self.tryCloseConnection(client) return srv_addr, srv_prt = conn.getsockname() print("sending reply:", ILoginSocketProvider.REPLY_OK, srv_addr, srv_prt) self.loginPlugin.sendReply(cli...
endlessm/chromium-browser
testing/scripts/test_traffic_annotation_auditor.py
Python
bsd-3-clause
2,554
0.006656
#!/usr/bin/env python # Copyright 2017 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. """//testing/scripts wrapper for the network traffic annotation auditor checks. This script is used to run traffic_annotation_auditor_t...
s that help it run fast and spam free on trybots are disabled.""" import json import os import sys import tempfile import common SHEET_CONFIG = { "spreadsheet_id": "1TmBr9jnf1-hrjntiVBzT9EtkINGrtoBYFMWad2MBeaY", "annotations_sheet_name": "Annotations", "changes_sheet_name": "Changes Sta
ts", "silent_change_columns": [], "last_update_column_name": "Last Update", } def is_windows(): return os.name == 'nt' def main_run(args): annotations_file = tempfile.NamedTemporaryFile() annotations_filename = annotations_file.name annotations_file.close() command_line = [ sys.executable, ...
mmlacak/crochess
build.py
Python
gpl-3.0
8,163
0.025239
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright (c) 2021 Mario Mlačak, mmlacak@gmail.com # Licensed under GNU GPL v3+ license. See LICENSING, COPYING files for details. import sys import os # import os.path import subprocess import py.paths as P import py.run_subproc as RS import py.run_compiler as RC im...
tem_in( ['-d', '--debug'], script_argv) else False is_debug_build = True if RS.any_item_in( ['-D', '--debug-build'], script_argv) else False is_release_build = True if not is_debug_build and RS.any_item_in( ['-R', '-
-release'], script_argv) else False is_build = is_release_build or is_debug_build is_release_or_debug = is_release_build and not is_debug_build is_extra_warnings = True if RS.any_item_in( ['-XW', '--extra-warnings'], script_argv) else False is_silence = True if RS.any_item_in( ['-S', '--silence'], scr...
AnthonyBriggs/Python-101
hello_python_source_py3/chapter 09/ship-6-alien.py
Python
mit
9,407
0.005634
#!/usr/bin/python import pyglet from pyglet.gl import * from pyglet.window import key import math import random window = pyglet.window.Window(fullscreen=True) pyglet.resource.path.append('./images') pyglet.resource.reindex() center_x = int(window.width/2) center_y = int(window.height/2) def center_anchor(img): ...
prite): def __init__(self, x=0, y=0, dx=0, dy=0, batch=None): super(Bullet, self).__init__(bullet_image, x, y, batch=batch) self.x = x self.y = y self.dx = dx self.dy = dy self.radius = self.image.width / 2 self.timer = 1.5 def update(self, dt): ...
dx * dt self.y += self.dy * dt self.x = wrap(self.x, window.width) self.y = wrap(self.y, window.height) self.timer -= dt # collide with planet, or remove after 5 seconds distance, angle = dist_vec_to(planet, self) if distance <= planet.radius or self.time...
brendanzhao/GoogleCodeJam2014
src/1b/the_repeater.py
Python
mit
3,010
0.006977
import itertools from os import sys FILEPATH = 'A-large-practice' sys.stdin = open(FILEPATH + '.in', 'r') sys.stdout = open(FILEPATH + '.out', 'w') def get_line(): return raw_input() def get_int(): return int(get_line()) def get_str(): return str(get_line()) # def generate_char_count_table(strings): # char_count_...
in groupby(string)) for string in strings]) # if len(base_strings) != 1: # return 'Fegla Won' # unique_char_count =
len(list(base_strings)[0]) # char_count_table = generate_char_count_table(strings) # char_medians = get_char_medians(char_count_table, unique_char_count, len(strings)) # ideal_char_count = sum(char_medians) # return sum([abs(ideal_char_count - len(string)) for string in strings]) def the_repeater(strings): ...
reviewboard/reviewboard
reviewboard/hostingsvcs/hook_utils.py
Python
mit
5,621
0
import logging import re from django.conf import settings from django.db.models import Q from django.shortcuts import get_object_or_404 from reviewboard.reviews.models import ReviewRequest from reviewboard.scmtools.models import Repository from reviewboard.site.models import LocalSite def get_git_branch_name(ref_na...
quest ID (list of strings). Commits that are not associated with any review requests have the key None. """ if local_site_name: try: local_site = LocalSite.objects.get(name=local_site_name) except LocalSite.DoesNotExist: logging.error('close_all_review_requests: Local...
ay have 'None' keys, so filter them out. review_request_ids = [ review_request_id for review_request_id in review_request_id_to_commits if review_request_id is not None ] if not review_request_ids: return # Look up all review requests that match the given repository, ho...
dgouldin/django-avatar
setup.py
Python
bsd-3-clause
5,532
0.002892
from setuptools import setup, find_packages version = '1.1a1' LONG_DESCRIPTION = """ Using django-avatar =================== Basics ------ To integrate ``django-avatar`` with your site, there are relatively few things that are required. A minimal integration can work like this: 1. List this application in the `...
eter, ``request.GET`` will be searched. If ``request.GET`` has no ``next`` parameter, the ``HTTP_REFERER`` header will be inspected. If that header does not exist, the user will be redirected back to the current URL. Deleting an avatar ~~~~~~~~~~~~~~~~
~~ The actual view function is located at ``avatar.views.delete``, and this can be referenced by the url name ``avatar_delete``. It takes the same two keyword arguments as ``avatar.views.change`` and follows the same redirection rules as well. Template Tags ------------- To begin using these template tags, you mus...
willium/browser-extension
tools/addon-sdk-1.16/python-lib/cuddlefish/tests/test_licenses.py
Python
mit
3,564
0.005892
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. import unittest import os.path parent = os.path.dirname test_dir = parent(os.path.abspath(__file__)) sdk_root = parent...
.missing = [] self.scan_file(from_sdk_top(os.path.join("python-lib", "jetpack_sdk_env.py"))) self.scan(os.pa
th.join("python-lib", "cuddlefish"), [".js", ".py"], skipdirs=["sdk-docs"], # test_generate.py makes this ) self.scan(os.path.join("python-lib", "mozrunner"), [".py"]) for sdk_package in ["addon-kit", "api-utils", "test-harness"]: self.scan(os.path.join("...
SRabbelier/Melange
app/soc/modules/gsoc/views/org_app.py
Python
apache-2.0
2,789
0.003944
#!/usr/bin/env python2.5 # # Copyright 2011 the Melange 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 applic...
estHandler from soc.modules.gsoc.views.helper import url_patterns class OrgAppForm(OrgAppSurveyForm, forms.ModelForm): """Form for Organization Applications inherited from Surveys. """ #TODO: Rewrite this class while refactoring surveys def __init__(self, *args, **kwargs): """Act as a bridge between the...
, }) super(OrgAppForm, self).__init__(*args, **kwargs) class OrgApp(RequestHandler): """View methods for Organization Application Applications. """ def templatePath(self): return 'v2/modules/gsoc/org_app/apply.html' def djangoURLPatterns(self): """Returns the list of tuples for containi...
MOA-2011/enigma2-plugin-extensions-openwebif
plugin/controllers/views/ajax/boxinfo.py
Python
gpl-2.0
18,406
0.01983
#!/usr/bin/env python ################################################## ## DEPENDENCIES import sys import os import os.path try: import builtins as builtin except ImportError: import __builtin__ as builtin from os.path import getmtime, exists import time import types from Cheetah.Version import MinCompatib...
Expr=u"$tstrings['box_uptime']")) # from line 42, col 29. write(u''':</td> \t\t\t\t\t\t\t<td class="inforight">''') _v = VFFSL(SL,"uptime",True) # u'$uptime' on line 43, col
30 if _v is not None: write(_filter(_v, rawExpr=u'$uptime')) # from line 43, col 30. write(u'''</td> \t\t\t\t\t\t</tr> \t\t\t\t\t</table> \t\t\t\t</td> \t\t\t</tr> \t\t\t<tr> \t\t\t\t<td width="100%"> \t\t\t\t\t<table cellspacing="0" class="infomain" > \t\t\t\t\t\t<tr> \t\t\t\t\t\t\t<th colspan="2" clas...
hzlf/openbroadcast
website/shop/shop/models/defaults/bases.py
Python
gpl-3.0
16,866
0.00166
# -*- coding: utf-8 -*- from decimal import Decimal from distutils.version import LooseVersion from django.contrib.auth.models import User from django.core.urlresolvers import reverse from django.db import models from django.db.models.aggregates import Sum from django.utils.translation import ugettext_lazy as _ from po...
cart_item.save() self.save() # to get the last updated timestamp return cart_item def update_q
uantity(self, cart_item_id, quantity): """ Updates the quantity for given cart item or deletes it if its quantity reaches `0` """ cart_item = self.items.get(pk=cart_item_id) if quantity == 0: cart_item.delete() else: cart_item.quantity = qu...
BenWibking/nbody-slicer
slicer.py
Python
gpl-2.0
3,467
0.031151
#!/usr/bin/env python ## ## nbody-slicer, an n-body viz tool written in python ## ben wibking <ben.wibking@gmail.com> ## basefilename = "" leftfile = basefilename+"" rightfile = basefilename+"" boxsize = 1000. numbins = 100 zaxis = 0 zmin = 0. zmax = 10. xmin = 500. xmax = 1000. ymin = 500. ymax = 1000. ####### ...
s..." from matplotlib.widgets import Slider, Button, RadioButtons f, (left, right) = plt.subplots(1,2) plt.subplots_adjust(left=0.1, bottom=0.25) rightindex = (rightparticles[:,zaxis] > zmin) & (rightparticles[:,zaxis] < zmax) & (rightparticles[:,(zaxis+1)%3] > xmin) & (rightparticles[:,(zaxis+1)%3] < xmax) & (rig
htparticles[:,(zaxis+2)%3] > xmin) & (rightparticles[:,(zaxis+2)%3] < ymax) leftindex = (leftparticles[:,zaxis] > zmin) & (leftparticles[:,zaxis] < zmax) & (leftparticles[:,(zaxis+1)%3] > xmin) & (leftparticles[:,(zaxis+1)%3] < xmax) & (leftparticles[:,(zaxis+2)%3] > xmin) & (leftparticles[:,(zaxis+2)%3] < ymax) ## we...
fhdk/eordre-app.pyqt
util/sanitizeDataFn.py
Python
agpl-3.0
3,012
0.000996
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Copyright: Frede Hundewadt <echo "ZmhAdWV4LmRrCg==" | base64 -d> # License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html """Data Sanitize Functions""" from configuration import config from util.passwdFn import check_password __appname__ = "Eor...
trip(), line[1].strip(), line[2].strip(), line[3].strip(), line[4].strip(), line[5], line[6], line[7], line[8], line[9], line[10], line[11], line[12], line[13], line[14], line[15], line[16].strip()) product_list.append(product) ret
urn product_list
lsa-pucrs/Player
client_libs/libplayerc/bindings/python/test/test_laser.py
Python
lgpl-2.1
1,681
0.002974
#/* # * Player - One Hell of a Robot Server # * Copyright (C) 2004 # * Andrew Howard # * # * # * This library is free software; you can redistribute it and/or # *
modify it under the terms of the GNU Lesser General Public # * License as publis
hed by the Free Software Foundation; either # * version 2.1 of the License, or (at your option) any later version. # * # * This library 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 ...
WilsonWangTHU/neural_graph_evolution
util/parallel_util.py
Python
mit
825
0
# ------------------------------------
----------------------------------------- # @brief: Define some signals used during parallel # ----------------------------------------------------
------------------------- # it makes the main trpo agent push its weights into the tunnel START_SIGNAL = 1 # it ends the training END_SIGNAL = -1 # ends the rollout END_ROLLOUT_SIGNAL = -2 # ask the rollout agents to collect the ob normalizer's info AGENT_COLLECT_FILTER_INFO = 23 # ask the rollout agents to synchr...
geimer/easybuild-easyblocks
easybuild/easyblocks/w/wps.py
Python
gpl-2.0
14,725
0.003396
## # Copyright 2009-2013 Ghent University # # This file is part of EasyBuild, # originally created by the HPC team of Ghent University (http://ugent.be/hpc/en), # with support of Ghent University (http://ugent.be/hpc), # the Flemish Supercomputer Centre (VSC) (https://vscentrum.be/nl/en), # the Hercules foundation (htt...
wnbuildtypes[bt]) cmd = "./configure" qa = {} no_qa = [".*compiler is.*"] std_qa = { # named group in match will be used to construct answer
r"%s(.*\n)*Enter selection\s*\[[0-9]+-[0-9]+\]\s*:" % build_type_question: "%(nr)s", } run_cmd_qa(cmd, qa, no_qa=no_qa, std_qa=std_qa, log_all=
RyanHope/AutobahnPython
examples/twisted/wamp/rpc/arguments/frontend.py
Python
mit
3,404
0.000588
############################################################################### # # The MIT License (MIT) # # Copyright (c) Tavendo GmbH # # 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 with...
ee', limit=10) print("Orders 2: {}".format(orders))
arglengths = yield self.call(u'com.arguments.arglen') print("Arglen 1: {}".format(arglengths)) arglengths = yield self.call(u'com.arguments.arglen', 1, 2, 3) print("Arglen 2: {}".format(arglengths)) arglengths = yield self.call(u'com.arguments.arglen', a=1, b=2, c=3) print("...
mscuthbert/abjad
abjad/tools/lilypondparsertools/test/test_lilypondparsertools_LilyPondParser__contexts__Score.py
Python
gpl-3.0
460
0.002174
# -*- encoding: utf-8 -*- from abjad import * from abjad.tools.lilypondparsertools import LilyPondParser def test_lilypondparsertools_LilyPondParser__contexts__Score_01(): target = Score() assert systemtools.TestManager.compare( target, r''' \new S
core << >> ''' ) parser = LilyPondParser() result = parser(format(target)) assert format(target) == format(result) and
target is not result
xiejianying/pjsip_trunk
pjsip-apps/src/pygui/log.py
Python
gpl-2.0
3,628
0.033352
# $Id$ # # pjsua Python GUI Demo # # Copyright (C)2013 Teluu Inc. (http://www.teluu.com) # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) ...
ntry.level, entry.msg) def addLog2(self, level, msg): if level==5: tags = ('trace',) elif level==3: tags = ('info',) elif level==2: tags = ('warning',) elif level<=1: tags = ('error',) else: tags = None self.text.insert(tk.END, msg, tags) self.text.see(tk.END) def _createWidgets(sel...
1, weight=0) self.text = tk.Text(self, font=('Courier New', '8'), wrap=tk.NONE, undo=False, padx=4, pady=5) self.text.grid(row=0, column=0, sticky='nswe', padx=5, pady=5) scrl = ttk.Scrollbar(self, orient=tk.VERTICAL, command=self.text.yview) self.text.config(yscrollcommand=scrl.set) scrl.grid(row=0, co...
idf/tagr
rake_app/rake/rake.py
Python
bsd-3-clause
6,809
0.003378
# Implementation of RAKE - Rapid Automtic Keyword Exraction algorithm # as described in: # Rose, S., D. Engel, N. Cramer, and W. Cowley (2010). # Automatic keyword extraction from indi-vidual documents. # In M. W. Berry and J. Kogan (Eds.), Text Mining: Applications and Theory.unknown: John Wiley and Sons, Ltd. impo...
alKeywords print sortedKeywords[0:(totalKeywords/3)] rake = Rake(stoppath) keywords = rake.run(text) pri
nt keywords
gravyboat/spotify-puzzles
zipfsong/test/test_zipfSong.py
Python
mit
1,421
0.001407
#/usr/bin/python2.6 import unittest import sys sys.path.insert(0, '../') simpleList = [('', , ), ('', , )] complexList = [('', , ), ('', , )] equalPopularity = [('', , ), ('', , )] checkAllSongs = [('', , ), ('', , )] class zipfSongTestCase(unittest.TestCase): def setUp(self): self.simpleList = simpleL...
mplexList = complexList self.equalPopularity = equalPopularity self.checkAllSongs = checkAllSongs def test_simpleList(self): fro
m zipfSong import topSongs topSongsInstance = topSongs() testSongExample = topSongs.sortSongs(self.simpleList) self.assertEqual(testSongExample, , 'Songs do not match') def test_complexList(self): from zipfSong import topSongs topSongsInstance = topSongs() testSongsE...
jimwaldo/HarvardX-Tools
src/main/python/convertfiles/convertCSVtoJSON.py
Python
bsd-3-clause
22,982
0.028457
#!/nfs/projects/c/ci3_jwaldo/MONGO/bin/python """ This is generic CSV to JSON converter containing newline delimited formatting Input is a comma delimited CSV file Output is a newline delimited JSON formatted Usage: python convertCSVtoJSON [-options] OPTIONS: --input Name of input filename --output Name of output fi...
STRING': unicode, 'FLOAT': float,
'BOOLEAN': int, 'TIMESTAMP': unicode, } TYPE_RECORD = 'RECORD' # Define Schema Stats SCHMA_SUMMARY_COLS = ['Correct', 'Incorrect', 'Fixed', 'Not Fixed', '% Incorrect', '% Corrected'] SCHMA_KEY_IGNORE = {'i4x-': re.compile('^i4x.*'), 'input_i4x': re.compile('^input_i4x.*'), '...
Petr-Kovalev/nupic-win32
tests/unit/py2/nupic/frameworks/opf/opf_metrics_test.py
Python
gpl-3.0
27,219
0.020794
#!/usr/bin/env python # ---------------------------------------------------------------------- # Numenta Platform for Intelligent Computing (NuPIC) # Copyright (C) 2013, Numenta, Inc. Unless you have purchased from # Numenta, Inc. a separate commercial license for this software code, the # following terms and conditio...
gt.extend([2*i for i in range(110)]) p = [i for i in range(1000)] res = [] for i in xrange(len(gt)): movingMeanAAE.addInstance(gt[i], p[i]) res.append(movingMeanAAE.getMetric()["value"]) self.assertTrue(max(res[1:890]) == 2.0) self.asse
rtTrue(min(res[891:])
Chasego/cod
lintcode/239-[DUP]-Sliding-Window-Maximum/SlidingWindowMaximum_001.py
Python
mit
673
0
class Solution(object): def maxSlidingWindow(self, nums, k): """ :type nums: List[int] :type k: int :rtyp
e: List[int] """ if nums == []: return [] dq = [(nums[0], 0)] for i in range(1, k): while dq != [] and nums[i] > dq[-1][0]: dq.pop() dq.append((nums[i], i)) res = [dq[0][0]] for j in range(k, len(nums)): if d...
) while dq != [] and nums[j] > dq[-1][0]: dq.pop() dq.append((nums[j], j)) res.append(dq[0][0]) return res
jedie/DragonPy
dragonpy/CoCo/config.py
Python
gpl-3.0
3,796
0.001581
""" CoCo config ================ :create
d: 2014 by Jens Diemer - www.jensdiemer.de :copyleft: 2014-2015 by the DragonPy team, see AUTHORS for more details. :license: GNU GPL v3 or abo
ve, see LICENSE for more details. """ import logging from dragonlib.api import CoCoAPI from dragonpy import constants from dragonpy.CoCo.CoCo2b_rom import CoCo2b_Basic13_ROM, CoCo2b_ExtendedBasic11_ROM from dragonpy.CoCo.mem_info import get_coco_meminfo from dragonpy.Dragon32.config import Dragon32Cfg from dragonpy...
jaredlunde/cargo-orm
unit_tests/fields/Double.py
Python
mit
1,916
0
#!/usr/bin/python3 -S # -*- coding: utf-8 -*- from cargo.fields import Double from unit_tests.fields.Numeric import TestNumeric, TestEncNumeric from unit_tests import configure class TestDouble(TestNumeric): ''' value: value to populate the field with not_null: bool() True if the field cannot be Null ...
index in your table, that is, not unique or primary default: default value to set the field to validation: callable() custom validation plugin, must return True if the field validates, and False if it does not decimal_places: int() maximum digit precision ''' @property def base(s...
ble() self.assertEqual(base.value, base.empty) self.assertIsNone(base.primary) self.assertIsNone(base.unique) self.assertIsNone(base.index) self.assertIsNone(base.default) self.assertIsNone(base.not_null) self.assertEqual(base.minval, base.MINVAL) self.ass...
ColeLab/informationtransfermapping
TheoreticalResults/analysis.py
Python
gpl-3.0
9,130
0.015772
# Demo code for statistical analysis of computational model (simulated data) Ito et al., 2017 # Takuya Ito (takuya.ito@rutgers.edu) # Citation: Ito T, Kulkarni KR, Schultz DH, Mill RD, Chen RH, Solomyak LI, Cole MW (2017). Cognitive task information is transferred between brain regions via resting-state netw ork top...
re(Ci==net)[0
] #net_ind = np.arange(net*nodespercommunity,net*nodespercommunity+nodespercommunity) indir = datadir + '/task_betas/' indcount = 0 for task in tasks: filename = 'subj'+str(subj)+'_task'+str(task)+'_allblocks.txt' betas = np.loadtxt(indir + filename, delimiter=',') # Get relevan...
diego0020/correlation_viewer
vcorr/gui/correlations_gui.py
Python
mit
4,968
0.002415
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'C:/Users/Diego/Documents/GitHub/correlation_viewer/vcorr\gui\correlations_gui.ui' # # Created: Wed May 14 20:22:30 2014 # by: PyQt4 UI code generator 4.10.3 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtC...
lf.centralwidget) self.reg_frame.setFrameShape(QtGui.QFrame.NoFrame) self.reg_frame.setFrameShadow(QtGui.QFrame.Raised) self.reg_frame.setObjectName(_fromUtf8("reg_frame")) self.horizontalLayout.addWidget(self.reg_frame) self.horizontalLayout.setStretch(1, 5) self.horizon...
correlation_app) self.menubar.setGeometry(QtCore.QRect(0, 0, 1285, 26)) self.menubar.setObjectName(_fromUtf8("menubar")) self.menuFile = QtGui.QMenu(self.menubar) self.menuFile.setObjectName(_fromUtf8("menuFile")) correlation_app.setMenuBar(self.menubar) self.statusbar = ...
mileto94/Data-Mining
homework9/kmeans.py
Python
mit
3,653
0.000821
import numpy MAX_ITERATIONS = 100 INFINITY = 1000 class Point: def __init__(self, coordinates, label=None): # self.x = x # self.y = y self.coordinates = coordinates self.label = label def __str__(self): return '{coordinates} labeled {label}'.format( coordi...
distances = [ (centroid, get_distance(point, centroid)) for centroid in centroids ] min_dist = sorted(distances, key=lambda pair: pair[1])[0] # print(sorted(distances, key=lambda pair: pair[1])) # print(min_dist) point.label
= min_dist[0] labels[point] = min_dist[0] # print(point) # print('**********************************************************') return labels # Function: Get Centroids # ------------- # Returns k random centroids, each of dimension n. def get_centroids(data_set, labels, k): # Each centr...
openaid-IATI/OIPA
OIPA/traceability/models.py
Python
agpl-3.0
3,823
0
from django.db import models from django.utils.timezone import now from iati.models import Activity # Networks should be based upon orgs in the org standard # class Network(models.Model): # class NetworkLink(models.Model): # class NetworkError(models.Model): # class NetworkOrganisation(models.Model): class Chai...
k=False) tier = models.IntegerField(null=True, default=None) bol = models.BooleanField(default=False) eol = models.BooleanField(default=False) checked = models.BooleanField(default=False) treated_as_end_node = models.BooleanField(default=False) def __unicode__(self): return self.activit...
), ('error', u"Error") ) error_type_choices = ( ('1', u"provider-org not set on incoming fund"), ('2', u"provider-activity-id not set on incoming fund"), ('3', u"given provider-activity-id set on incoming fund does not exist"), ('4', u"receiver-org not set o...
CyberLabs-BR/face_detect
pyimagesearch/nn/conv/fcheadnet.py
Python
mit
604
0.023179
# import the necessary packages from keras.layers.core import Dropout from keras.layers.core import Flatten from keras.layers.core import Dense class FCHeadNet: @staticmethod def build(baseModel, classes,
D): # initialize the head model that will be placed on top of # the base, then add a FC layer headModel = baseModel.output headModel = Flatten(name="flatten")(headModel) headMo
del = Dense(D, activation="relu")(headModel) headModel = Dropout(0.5)(headModel) # add a softmax layer headModel = Dense(classes, activation="softmax")(headModel) # return the model return headModel
sympsi/sympsi
sympsi/pauli.py
Python
bsd-3-clause
23,329
0.000086
"""Pauli operators and states""" from sympy import I, Mul, Add, Pow, exp, Integer from sympsi import Operator, Ket, Bra from sympsi import ComplexSpace from sympy.matrices import Matrix from sympy.functions.special.tensor_functions import KroneckerDelta __all__ = [ 'SigmaX', 'SigmaY', 'SigmaZ', 'SigmaMinus', 'Sig...
args): if self.use_name: return r'{\sigma_x^{(%s)}}' % str(self.name) else: return r'{\sigma_x}' def _print_contents(self, printer, *args): return 'SigmaX()' def _eval_power(self, e): if e.is_Integer and e.is_positive: return SigmaX(self.name...
tance(other, SigmaOpBase) and self.name != other.name: # Pauli matrices with different labels commute; sort by name if self.name < other.name: return Mul(self, other) else: return Mul(other, self) if isinstance(other, SigmaX) and self.name == ...
victor-cortez/Heimdall
pile/timer.py
Python
mit
914
0.012035
import pile import matplotlib.pyplot as plt import time import random x,y = [],[] fo
r i in range(0,10): p = 10 ** i print(i) start = time.time() pile.pile(p) final = time.time() delta = final - start x.append(p) y.append(delta) plt.plot(x,y) plt.ylabel("The time taken to compute the pile splitting of a pile os size n") print(y) plt.show() plt.savefig("data.jpg") def cut...
n in p: if n == 1: soma += 0 else: a = random.randint(1,n-1) b = n - a soma += a*b update.append(a) update.append(b) p = list(update) size = len(p) print(update,soma) retur...
ESG-USA/python-sample-project
setup.py
Python
mit
4,015
0
"""A setuptools based setup module. See: https://packaging.python.org/en/latest/distributing.html https://github.com/pypa/sampleproject """ # Always prefer setuptools over distu
tils from setuptools import setup, find_packages # To use a consistent encoding from codecs import open from os import path here = path.abspath(path.dirname(__file__)) # Get the long description from the README file with open(path.join(h
ere, 'README.rst'), encoding='utf-8') as f: long_description = f.read() setup( name='sample', # Versions should comply with PEP440. For a discussion on single-sourcing # the version across setup.py and the project code, see # https://packaging.python.org/en/latest/single_source_version.html v...
alexander-alvarez/django_polymorphic
runtests.py
Python
bsd-3-clause
2,214
0.00542
#!/usr/bin/env python import django import os import sys from django.conf import settings from django.core.management import execute_from_command_line from django.conf import settings, global_settings as default_settings from django.core.management import call_command from os.path import dirname, realpath # Give fee...
list(default_settings.TEMPLATE_CONTEXT_PROCESSORS) + [ 'django.core.context_processors.request', ] ), TEST_RUNNER = 'django.test.runner.DiscoverRunner' if django.VERSION >= (1, 7) else 'django.test.simple.DjangoTestSuiteRunner', INSTALLED_APPS = ( 'djang...
'polymorphic', ), MIDDLEWARE_CLASSES = (), SITE_ID = 3, ) DEFAULT_TEST_APPS = [ 'polymorphic', ] def runtests(): other_args = list(filter(lambda arg: arg.startswith('-'), sys.argv[1:])) test_apps = list(filter(lambda arg: not arg.startswith('-'), sys.argv[1:])) or DEF...
nachtmaar/androlyze
androlyze/storage/exception/__init__.py
Python
mit
6,046
0.007939
# encoding: utf-8 __author__ = "Nils Tobias Schmidt" __email__ = "schmidt89 at informatik.uni-marburg.de" from androlyze.error.WrapperException import WrapperException ############################################################ #---Helper functions ############################################################ def _...
def _msg(self): return _create_delete_error_msg(self.content, self.db) class S3StorageStoreException(ES3StorageException): def _msg(self): return
_create_store_error_msg(self.content, self.db) class S3StorageLoadException(ES3StorageException): def _msg(self): return _create_load_error_msg(self.content, self.db) class S3StorageOpenError(ES3StorageException): def __init__(self, db_name, **kwargs): super(ES3StorageException, self).__ini...
migp11/consistency-analysis
modules/utils.py
Python
gpl-2.0
9,286
0.011307
# Python script to perform consistency analysis on metabolic models # Copyright (C) 2015 Miguel Ponce de Leon # Contact: miguelponcedeleon@gmail.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 Foundat...
ff}) if 'EX_cpd11416_c' in model.reactions: model.remove_reactions(['EX_cpd11416_c']) if 'rxn05029' in model.reactions: model.remove_reactions(['rxn05029']) return model def prepare_model(model,metamodel,reactions_to_remove=[],correct_seed=False): model = model.copy() ...
l.remove_reactions(reactions_to_remove) if correct_seed: correct_seed_model(model,metamodel) list_of_reactions = [r for r in model.reactions] for r in list_of_reactions: if r not in metamodel.reactions: print "%s not in metamodel %s" % (r.id,metamodel.id) conti...
krypticnetworks/ipblisted
ipblisted.py
Python
gpl-3.0
14,612
0.004791
# # ipblisted - A python tool to check an IP against black lists # Author: Brian Carroll # Created: 2016-07-18 # Modified: 2016-07-18 # Version: 0.8 # import os import re import csv import sys import time import json import urllib import requests import datetime import threading import collections import dns.resolver ...
otation, do the normal IP check if self.format == "cidr": for cidr in [IPNetwork(cidr) for cidr in re.findall("((?:\d{1,3}\.){3}\d{1,3}(?:/\d\d?))", result.content)]: if IPAddress(ip) in cidr: return "Found" return "No Result"...
lse: matches = re.findall(ip, result.content) if matches: return "Found" else: return "No Result" else: cprint("[!] There was an issue attemping to connect to: {url}".format(url=self.url), RED) ...
MDBrothers/FluidMechanicsToys
vortex_dynamics/vortex_ring_pair.py
Python
mit
12,889
0.023353
#!/usr/bin/python #Author: Michael Brothers #Date: 10-22-2013 #Title: Vortex Ring Pair Interaction # #Note: must be run with four ranks import matplotlib.pyplot as plt import matplotlib.animation as animation import numpy as np import numpy.ma as ma from mpl_toolkits.mplot3d import Axes3D from mpi4py import MPI comm...
dl = self.Radius_One* 2.0*np.pi * np.power(self.numpoints, -1.0) delta_x = x - x_prime H_cubed = np.power(np.sum(np.power(delta_x, 2.0), axis = 1), 3.0/2.0) dU[self_point] = self.Strength_One*np.power(4.0*np.pi, -1.0) * dl * np.power(H_cubed, -1.0)[:, np.newax...
self.both_vortex_cart_velocities[self_point] = np.sum(dU[self_point], axis=0) return 0 def compute_U_One_On_Two_Vectorized(self): m = self.angle_sweep s = self.angle_sweep dU = np.zeros((self.numpoints, self.numpoints -1, 3)) dl = 0.0 H_cubed = np.zeros...