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
Karel-van-de-Plassche/bokeh
bokeh/server/server.py
Python
bsd-3-clause
14,928
0.00201
''' Provide basic Bokeh server objects that use a Tornado ``HTTPServer`` and ``BokeTornado`` Tornado Application to service Bokeh Server Applications. There are two public classes in this module: :class:`~bokeh.server.server.BaseServer` This is a lightweight class to explicitly coordinate the components needed ...
t and stop the loop yourself, i.e. this method is typically useful when you are already explicitly managing an ``IOLoop`` yourself. To start a
Bokeh server and immediately "run forever" in a blocking manner, see :func:`~bokeh.server.server.BaseServer.run_until_shutdown`. ''' assert not self._started, "Already started" self._started = True self._tornado.start() def stop(self, wait=True): ''' Stop the Bokeh ...
Eternali/synk
synk-pre/synk-pre.py
Python
gpl-3.0
5,279
0.002084
''' Synk - Sublime Text Plugin ''' import os import socket import sublime import sublime_plugin from threading import Thread, Timer # variables for storing user defined settings settings_filename = "synk_pre.sublime-settings" enabled_field = "enabled" server_ips_field = "project_server_ips" # NOTE: add feature ...
"downlink_ports" all_files_field = "synk_all_files" current_file_field = "synk_current_file" delay_field = "delay_in_seconds" # Object for connecting to the server class
ServerConnection(object): def __init__(self, attempts=5): self.settings = sublime.load_settings(settings_filename) self.delay = self.settings.get(delay_field) self.server = self.settings.get(server_ips_field) self.up_port = self.settings.get(uplink_ports_field) self.down_por...
varundrogba/mySquareMeal
295 Project/profile_operations/user_registration.py
Python
mit
1,777
0.004502
import pymongo from pymongo import MongoClient import json try: MONGODB_URI = "mongodb://mysquaremeal:mysquaremeal@ds157653.mlab.com:57653/mysquaremeal_user_profile_database" mlab_client = MongoCli
ent(MONGODB_URI, connectTimeoutMS=30000) db = mlab_client.mysquaremeal_user_profile_database except ConnectionError: raise class registration: def check_existing_user(email): print('checking user existance') if db.user_profile_collection.find({'email':email}).count() > 0: prin...
print(user_data) try: email = user_data["email"] password = user_data["password"] allergies = user_data["allergies"] allergies_list = allergies.split(",") print('--------------------------------------------------------------\n'+email) ...
benedictpaten/pecan
bp/pecan/SparsePecan.py
Python
mit
4,509
0.01242
#!/usr/bin/env python #Copyright (C) 2006-2011 by Benedict Paten (benedictpaten@gmail.com) # #Released under the MIT license, see LICENSE.txt #!/usr/bin/env python import sys import os import re import math import SparseAlign def getStartStates(stateMachine): def fn(i): if i == MATCH: re...
ckGapFn[(MATCH, GAP)], backGapFn[(GAP, GAP)], join(diagStart, posteriorProbs.diagStart), join(diagBuilder, posteriorProbs.diagBuilder), join(diagEnd, posteriorProbs.diagEnd), forw
ardFn[(GAP, MATCH)], forwardFn[(MATCH, MATCH)], posteriorProbs.total, rescale, diagTraceBackLimit) out = open(outputFile, 'w') for i in pPA.keys(): out.write("%s %s %s \n" % (i[0] + xStart, i[1] + yStart, pPA[i])) out.close()...
chr15m/Infinite8BitPlatformer
I8BPTestClient-random-linedraws.py
Python
gpl-3.0
3,693
0.033035
# Tests out multiple simultaneous draw commands import sys from time import sleep from random import choice, random, randint from string import letters from PodSixNet.Connection import connection, ConnectionListener from server.version import VERSION class TestClientException(Exception): pass class TestClient(Con...
o the server" # randomly have an ID already (clients which have connected before) if randint(0, 1) and len(self.demo_ids): self.playerID = self.demo_ids.pop() self.Send({"action": "playerid", "id": self.playerID, "version": VERSION}) else: # request a new UUID secret player ID to begin with self.Send(...
['progress'] == "end": self.SendWithID({'action': 'move', 'velocity': [0, 0], 'move': 'StopRight', 'center': [0.71414136419120788, 0.29951459060388141]}) self.SendWithID({'action': 'activate'}) def Network_error(self, data): print self.playerID, 'error:', data['error'][1] self.serverconnection = 2 connec...
diegocortassa/TACTIC
src/pyasm/widget/project_wdg.py
Python
epl-1.0
4,702
0.007231
########################################################### # # Copyright (c) 2005, Southpaw Technology # All Rights Reserved # # PROPRIETARY INFORMATION. This software is proprietary to # Southpaw Technology, and is not to be reproduced, transmitted, # or disclosed in any way without written permi...
bleElementWdg #TODO: to be replaced by the same file in tactic.ui.table class ProjectWdg(BaseTableElementWdg): def get_title(self): return "Database" def preprocess(self): self.version = E
nvironment.get_release_version() def get_display(self): widget = Widget() project = self.get_current_sobject() table = Table() widget.add(table) table.add_style("width: 140px") table.add_row() table.add_cell("Exists: ") table.add_cell(" ") ...
venetay/Photo-Competition
competition/models.py
Python
mit
434
0.002304
from django.db import models from teams.models import Team from categories.models import Category class Competition(models.Model): competition_name = models.CharField(max_
length=100) categories = models.ManyToManyField(Category) involved_teams = models.ManyToManyField(Team) def __unicode__(self): return unicode(self.competition_name) def competition(self):
return str(self.competition_name)
TresAmigosSD/SMV
src/test/python/testRunCmdLine.py
Python
apache-2.0
3,127
0.005117
# # This file is 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 # distr...
Test(RunCmdLineBaseTest): @classmethod def whatToRun(cls): return ['-m', 'tooth-fary'] def test_should_report_non_existing_module(self): with self.assertRaisesRegexp(SmvRuntimeError, "Can't find name tooth-fary"):
self.smvApp.run() class RunModuleAmbiguousTest(RunCmdLineBaseTest): @classmethod def whatToRun(cls): return ['-m', 'A'] def test_should_report_ambiguous_modules(self): with self.assertRaisesRegexp(SmvRuntimeError, r"Partial name A is ambiguous"): self.smvApp.run(...
lsst-sqre/ltd-keeper
migrations/versions/1ba709663f26_edition_surrogate_key.py
Python
mit
430
0.004651
"""edition surrogate key Revision ID: 1ba709663f26 Revises: d9a390ebdf1e Create Date: 2016-04-29 15:59:12.144102 """ # revi
sion identifiers, used by Alembic. revision = "1ba709663f26" down_revision = "d9a390ebdf1e" import sqlalchemy as sa from alembic import op def upgrade(): op.add_column("editi
ons", sa.Column("surrogate_key", sa.String(length=32))) def downgrade(): op.drop_column("editions", "surrogate_key")
acthp/ucsc-xena-client
js/data/getCentromere.py
Python
apache-2.0
820
0.007317
#!/usr/bin/env python from itertools import groupby, tee import json, os assemblies = ['hg38', 'hg19', 'hg18'] chroms = ['chr' + str(i + 1) for i in range(22)] + ['chrX', 'chrY'] Kchrom = 0 def parseLine(line): [chrom, start, end, id, _] = line return [int(start), int(end), id] def write(name):
with open('cytoBand_%s.json' % name, 'r') as fh: cb = json.loads(fh.read()) lastp = {chrom: [x for x in cb[chrom] if x[2][0] == 'p'][-1][1] for chrom i
n chroms} firstq = {chrom: [x for x in cb[chrom] if x[2][0] == 'q'][0][0] for chrom in chroms} if lastp != firstq: raise Exception('Indeterminate centromere position') with open('centromere_%s.json' % name, 'w') as wfh: wfh.write(json.dumps(firstq)) for name in assemblie...
minrk/sympy
sympy/integrals/integrals.py
Python
bsd-3-clause
31,617
0.00098
from sympy.core import (Basic, Expr, S, C, Symbol, Wild, Add, sympify, diff, oo, Tuple, Dummy, Equality, Interval) from sympy.core.symbol import Dummy from sympy.core.compatibility import ordered_iter from sympy.integrals.trigonometry import trigintegrate from sympy.integrals.deltafunctions imp...
>>> from sympy import Integral >>> from sympy.abc import x, y >>> Integral(x).is_number False >>> Integral(x, y).is_number False >>> Integral(x, (y, 1, x)).is_number False >>> Integral(x, (y, 1, 2)).is_number False >>> Integral(x, (y, 1, ...
Integral(x*y, (x, 1, 2), (y, 1, 3)).is_number True >>> Integral(1, x, (x, 1, 2)).is_number True """ integrand, limits = self.function, self.limits isyms = integrand.atoms(Symbol) for xab in limits: if len(xab) == 1: isyms.add(xab[0]) ...
pozetroninc/micropython
tests/micropython/viper_cond.py
Python
mit
497
0.014085
# using False
as a conditional @micropython.viper def f(): x = False if x: pass else: print("not x", x) f() # using True as a conditional @micropython.viper def f(): x = True if x: print("x", x) f() # using an int as a conditional @micropython.viper def g():
y = 1 if y: print("y", y) g() # using an int as a conditional that has the lower 16-bits clear @micropython.viper def h(): z = 0x10000 if z: print("z", z) h()
davidshepherd7/oomph-lib-micromagnetics
self_test/nodal_quadrature_bem/validate.py
Python
gpl-2.0
1,780
0.010674
#!/usr/bin/env python3 # Python 2/3 compatability from __future__ import print_function from __future__ import division from __future__ import absolute_import import sys import argparse import os import os.path import itertools as it from os.path import join as pjoin # Make sure *this* versions oomphpy is in the p...
name(__file__), "../../etc")) import oomphpy import oomphpy.micromagnetics as mm import oomphpy.tests as tests def main(): # Look for parallel in args parser = argparse.ArgumentParser() parser.add_argument('--parallel', action = "store_true") args = parser.parse_args() # What to run argdict...
driver" : 'llg', '-mesh' : 'ut_sphere', '-tmax' : 10, '-damping' : 1, '-ts' : 'imr', '-dt' : 0.1, '-ms-method' : 'implicit', '-quadrature' : 'lnodal', '-newton-tol' : 1e-12, "-solver" : "gmres", "-matrix-type" : "som", "-prec" : ...
ByStudent666/XsCrypto
XsCrypto/zhanzhuanxc.py
Python
mit
592
0.027027
#!/usr/b
in/env python # -*- coding: utf-8 -*- __author__ = 'ByStudent' def zhanzhuanxc(p,q,e): def egcd(a, b): x,y, u,v = 0,1, 1,0 while a != 0: q, r = b//a, b%a m, n = x-u*q, y-v*q b,a, x,y, u,v = a,r, u,v, m,n gcd = b return gcd, x, y def modinv(a, m...
m phi_n = (p - 1) * (q - 1) d = modinv(e, phi_n) return int(d) # print zhanzhuanxc(18443,49891,19)
udienz/status
lib/python/sedot/report/__init__.py
Python
gpl-2.0
28
0.035714
from re
port import
Report
antoinecarme/pyaf
tests/model_control/detailed/transf_RelativeDifference/model_control_one_enabled_RelativeDifference_ConstantTrend_NoCycle_LSTM.py
Python
bsd-3-clause
164
0.04878
import tests.model_control.test_ozone_custom_models_enabled
as testmod testmod.build_model(
['RelativeDifference'] , ['ConstantTrend'] , ['NoCycle'] , ['LSTM'] );
devs1991/test_edx_docmode
venv/lib/python2.7/site-packages/newrelic-2.46.0.37/newrelic/api/memcache_trace.py
Python
agpl-3.0
1,655
0.003625
import functools from .time_trace import TimeTrace from .transaction import current_transaction from ..core.memcache_node import MemcacheNode from ..common.object_wrapper import FunctionWrapper, wrap_object class MemcacheTrace(TimeTrace): def __init__(self, transaction, command): super(MemcacheTrace, sel...
*kwargs) else: _command = command with MemcacheTrace(tr
ansaction, _command): return wrapped(*args, **kwargs) return FunctionWrapper(wrapped, _nr_wrapper_memcache_trace_) def memcache_trace(command): return functools.partial(MemcacheTraceWrapper, command=command) def wrap_memcache_trace(module, object_path, command): wrap_object(module, object_pat...
awslabs/chalice
chalice/deploy/sweeper.py
Python
apache-2.0
7,626
0
from typing import List, Dict # noqa from chalice.config import Config, DeployedResources # noqa from chalice.deploy import models MarkedResource = Dict[str, List[models.RecordResource]] class ResourceSweeper(object): def execute(self, plan, config): # type: (models.Plan, Config) -> None ins...
'topic'] referenced_topic = [instruction for instruction in marked[name] if instruction.name == 'topic' and
isinstance(instruction, models.RecordResourceValue)][0] if referenced_topic.value != existing_topic: remaining.append(name) elif resource_values['resource_type'] == 'sqs_event': existing_queue = reso...
kelle/astropy
astropy/config/tests/test_configs.py
Python
bsd-3-clause
10,072
0.0003
# -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst from __future__ import (absolute_import, division, print_function, unicode_literals) import io import os import sys import subprocess import pytest from ...tests.helper import catch_warnings from ...exter...
with('astropy.cfg') cfgsec =
get_config('astropy.config') assert cfgsec.depth == 1 assert cfgsec.name == 'config' assert cfgsec.parent.filename.endswith('astropy.cfg') reload_config('astropy') def test_configitem(): from ..configuration import ConfigNamespace, ConfigItem, get_config ci = ConfigItem(34, 'this is a Descr...
epsylon3/torrentflux
html/bin/clients/mainline/BitTorrent/Storage_IOCP.py
Python
gpl-2.0
16,006
0.002062
# The contents of this file are subject to the BitTorrent Open Source License # Version 1.1 (the License). You may not copy or use this file, in either # source code or executable form, except in compliance with the License. You # may obtain a copy of the License at http://www.bittorrent.com/license/. # # Software di...
for filename in files: del self.file_to_torrent[filename] def _ensure_exists(self, filename, length=0): if not os.path.exists(filename):
f = os.path.split(filename)[0] if f != '' and not os.path.exists(f): os.makedirs(f) f = file(filename, 'wb') make_file_sparse(filename, f, length) f.close() def get_open_file_count(self): t = self.open_file_to_handles.total_length() ...
brusznicki/multi-user-blog
handlers/post/__init__.py
Python
mit
171
0.005848
from delete import PostDeleteHandler from show import PostShowHandler from edit i
mport PostEditHandler from create impor
t PostNewHandler from index import BlogIndexHandler
r0mai/metashell
3rd/templight/llvm/projects/compiler-rt/test/lsan/lit.common.cfg.py
Python
gpl-3.0
3,311
0.011779
# -*- Python -*- # Common configuration for running leak detection tests under LSan/ASan. import os import re import lit.util def get_required_attr(config, attr_name): attr_value = getattr(config, attr_name, None) if attr_value == None: lit_config.fatal( "No attribute %r in test configuration! You may...
vocation(compile_flags): return " " + " ".join([config.clang] + compile_flags) + " " config.substitutions.append( ("%clang ", build_invocation(clang_cflags)) ) config.substitutions.append( ("%clangxx ", build_invocation(clang_cxxflags)) ) config.substitutions.append( ("%clang_lsan ", build_invocation(clang
_lsan_cflags)) ) config.substitutions.append( ("%clangxx_lsan ", build_invocation(clang_lsan_cxxflags)) ) # LeakSanitizer tests are currently supported on x86-64 Linux, PowerPC64 Linux, arm Linux, mips64 Linux, and x86_64 Darwin. supported_linux = config.host_os is 'Linux' and config.host_arch in ['x86_64', 'ppc64', '...
lucventurini/mikado
util/asm_collect.py
Python
lgpl-3.0
2,792
0.003223
#!/usr/bin/env python3 import os import argparse class AsmStats: file = "" genes = 0 monoexonic_genes = 0 transcripts = 0 transcripts_per_gene = 0.0 transcript_len_mean = 0.0 monoexonic_transcripts = 0 exons = 0 exons_per_transcript = 0.0 exon_len_mean = 0.0 def __init__...
noexonic_genes = c
ol2 elif parts[0] == "Transcripts per gene": s.transcripts = col2 s.transcripts_per_gene = col3 elif parts[0] == "CDNA lengths": s.transcript_len_mean = col3 elif parts[0] == "Monoexonic transcripts": ...
hustodemon/spacewalk
backend/common/rhnCache.py
Python
gpl-2.0
12,026
0.000998
# Copyright (c) 2008--2012 Red Hat, Inc. # # This software is licensed to you under the GNU General Public License, # version 2 (GPLv2). There is NO WARRANTY for this software, express or # implied, including the implied warranties of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. You should have received a cop...
Error(name) return fd def close_fd(self): pass class WriteLockedFile(LockedFile): def get_fd(self, name, user, group, mode): try: fd = _safe_create(self.fname, user, group, mode) except Unreada
bleFileError: raise OSError, "cache entry exists, but is not accessible: %s" % \ name, sys.exc_info()[2] # now we have the fd open, lock it fcntl.lockf(fd, fcntl.LOCK_EX) return os.fdopen(fd, 'w') def close_fd(self): # Set the file's mtime if necessary ...
nke001/attention-lvcsr
libs/Theano/theano/tensor/subtensor.py
Python
mit
84,816
0.000153
from copy import copy import sys from textwrap import dedent import warnings import logging import numpy from six.moves import xrange import theano from theano.compat import izip from six import integer_types from theano.gradient import DisconnectedType from theano import gof from theano.gof import Apply, Constant, h...
inplace_increment except ImportError: pass _logger = logging.getLogger("theano.tensor.subtensor") # Do a lazy import of the sparse module sparse_module_ref = None class AdvancedIndexingError(TypeError): """ Raised when Subtensor is asked to perform advanced indexing. """ def __init__(se...
nstant(args): """ Convert python litterals to theano constants in subtensor arguments. """ def conv(a): if a is None: return a elif isinstance(a, slice): return slice(conv(a.start), conv(a.stop), ...
hkage/django-issue-synchronisation
example/settings.py
Python
gpl-3.0
2,567
0.004285
import os PROJECT_PATH = os.path.realpath(os.path.dirname(__file__)) os.sys.path.insert(0, os.path.dirname(PROJECT_PATH)) DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = () MANAGERS = ADMINS DATABASES = { 'd
efault': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'dev.db', } } TIME_ZONE = 'America/Chicago' LANGUAGE_CODE = 'en-us'
SITE_ID = 1 USE_I18N = True USE_L10N = True USE_TZ = True MEDIA_ROOT = '' MEDIA_URL = '' STATIC_ROOT = '' STATIC_URL = '/static/' STATICFILES_DIRS = ( ) STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', # 'django.contri...
me-ankur/openmano
openmano/nfvo.py
Python
apache-2.0
79,462
0.016499
# -*- coding: utf-8 -*- ## # Copyright 2015 Telefónica Investigación y Desarrollo, S.A.U. # This file is part of openmano # 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 ...
'user','passwd') else: from_ = 'datacenters as d' select_ = ('type','config','d.uuid as datacenter_id', 'vim_url', 'vim_url_admin', 'd.name as datacenter_name') result, content = mydb.get_table(FROM=from_, SELECT=select_, WHERE=WHERE_dict ) if result < 0: print "nfv...
ound a valid VIM with the input params " + str(WHERE_dict) return -HTTP_Not_Found, "datacenter not found for " + json.dumps(WHERE_dict) #print content vim_dict={} for vim in content: extra={'vim_tenants_uuid': vim.get('vim_tenants_uuid')} if vim["config"] != None: extra....
neiyk/JSONMock.py
jsonmock/utils.py
Python
mit
925
0.003243
__author__ = 'anass' def path_to_property(obj, props, id_tag='id'): """ Get t
he property value from a path""" if isinstance(obj, list): # If it is a list it means we need the id to return the value # add if value equal nan ==> no resource found if len(props) is 1: res = [o for o in obj if o.get(id_tag) == int(p
rops[0])] if not len(res): # no resource found return return props[0], res[0] return props[0], [o for o in obj] #return path_to_property([o for o in obj if o.get(id_tag).__eq__(props[0])][0], props[1:]) # filter ID if len(props) == 1: ...
scopely-devops/rolemodel
rolemodel/role.py
Python
apache-2.0
1,204
0
# Copyright (c) 2015 Scopely, Inc. # # Licensed under the Apache License, Version
2.0 (the "License"). You # may not use this file except in compliance with the License. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file accompanying this file. This file is # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF # ANY KIND, either ...
nd limitations under the License. import logging LOG = logging.getLogger(__name__) class Role(object): def __init__(self, session, data): self._session = session self.logical_name = data['LogicalResourceId'] self.physical_name = data['PhysicalResourceId'] self.stack_arn = data['...
mrcouts/Nyquist-Attack
Robotics/RxRxPx.py
Python
gpl-3.0
1,308
0.021407
from Serial import * R = Serial("RxRxPx", '', Matrix([['x','x','0'],['y','y','x']]).T) n_mot = 2 mot = [Motor("mot"+str(i+1),str(R.dof+i+1)) for i in range(n_mot)] R.StaticBal = solve(R.gh_, R.lg) R.Mh_sb_ = simplify(R.Mh_.subs(R.StaticBal)) R.vh_sb_ = simplify(R.vh_.subs(R.StaticBal)) R.gh_sb_ = simplify(R.gh_.subs...
x([mot[i].p_ for i in range(n_
mot)]) p_ = Matrix([ph_,po_]) M_ = R.Mh_sb_ for i in range(n_mot): M_ = diag(M_, mot[i].M_) v_ = Matrix([R.vh_sb_] + [mot[i].v_ for i in range(n_mot)]) g_ = Matrix([R.gh_sb_] + [mot[i].g_ for i in range(n_mot)]) phi_ = po_ - Matrix([R.vw_[0][0]+ph_[1],0,0,R.vw_[0][0]+symbols('beta')*ph_[1],0,0]).subs(R.StaticBal) A...
nathanbjenx/cairis
cairis/bin/quick_setup_headless.py
Python
apache-2.0
3,003
0.031968
#!/usr/bin/python # 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 # "...
otDir = os.path.split(os.path.split(os.path.realpath(os.path.dirname(__file__)))[0])[0] parser.add_argument('--rootDir',dest='rootDir',help='
Root directory',default=defaultRootDir + '/cairis') parser.add_argument('--imageDir',dest='imageDir',help='Default image directory',default='/tmp') homeDir = os.environ['HOME'] parser.add_argument('--configFile',dest='configFile',help='CAIRIS configuration file name (fully qualified path)',default=homeDir + '/cai...
britcey/ansible
test/units/modules/cloud/openstack/test_os_server.py
Python
gpl-3.0
6,519
0
import mock import pytest import yaml import inspect import collections from ansible.module_utils.six import string_types from ansible.modules.cloud.openstack import os_server class AnsibleFail(Exception): pass class AnsibleExit(Exception): pass def params_from_doc(func): '''This function extracts th...
id(self): ''' - os_server: nics: port-id=1234 ''' args =
os_server._network_args(self.module, self.cloud) assert(args[0]['port-id'] == '1234') def test_nics_string_net_name(self): ''' - os_server: nics: net-name=network1 ''' args = os_server._network_args(self.module, self.cloud) assert(args[0]['net-id'] == '5...
Jacotsu/pepenet
pepenet.py
Python
agpl-3.0
3,777
0.000794
#!/usr/bin/env python3 import ipfsapi import os import pepe import requests import socket import base64 from flask import Flask, request, redirect, render_template from werkzeug.utils import secure_filename from argparse import ArgumentParser import logging from threading import Thread from time import sleep parser = ...
'.jpeg') if not os.path.exists(UPLOAD_FOLDER): os.makedirs(UPLOAD_FOLDER) app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER ipfs = None pman = None for _ in range(5): try: ipfs = ipfsapi.connect(ipfs_host, ipfs_port) pman = pepe.PepeMan(ipfs, ipfs_host) break except ipfsapi.exceptions.ConnectionError: sleep(10) def get_pepes(): result = [] for pe...
wdv4758h/rst2html5
setup.py
Python
mit
1,706
0.00176
# -*- encoding: utf-8 -*- import io import re from os.path import dirname from os.path import join from setuptools import find_packages from setuptools import setup def read(*names, **kwargs): return io.open( join(dirname(__file__), *names), encoding=kwargs.get("encoding", "utf8") ).read() se...
ation', 'Topic :: Utilities', 'Topic :: Text Processing :: Markup :: HTML', ], zip_safe=False, packages=find_packages("src"), package_dir={"": "src"}, py_modules=['rst2html5'],
include_package_data=True, entry_points={ 'console_scripts': [ 'rst2html5 = rst2html5:main', ], }, )
czpython/django-cms
cms/tests/test_wizards.py
Python
bsd-3-clause
17,882
0.000391
# -*- coding: utf-8 -*- from django import forms from django.core.urlresolvers import reverse from django.core.exceptions import ImproperlyConfigured from django.forms.models import ModelForm from django.template import TemplateSyntaxError from django.test.utils import override_settings from django.utils.encoding impo...
lf.assertEqual(len(wizard_pool._entries), 1) self.assertTrue(wizard_pool.is_registered(self.page_wizard)) self.assertTrue(wizard_pool.unregister(self.page_wizard)) self.assertEqual(len(wiz
ard_pool._entries), 0) # Now, try to unregister something that is not registered self.assertFalse(wizard_pool.unregister(self.user_settings_wizard)) def test_get_entry(self): wizard_pool._clear() wizard_pool.register(self.page_wizard) entry = wizard_pool.get_entry(self.page...
daishichao/coral
examples/httpMethods.py
Python
apache-2.0
963
0.011423
import json import requests api = 'http://localhost:8000' headers = {'Content-Type': 'application/vnd.api+json', 'Accept': 'application/vnd.api+json'} def post(path, payload={}) : r = requests.post(api+path, data=json.dumps(payload), headers=headers) if (r.text): print json.dumps(json.loads(r.text), i...
{}) : r = requests.patch(api+path, data=json.dumps(payload), headers=headers) if (r.text): print json.dumps(json.loads(r.text), indent=2) def put(path, payload={}) : r = requests.put(api+path, data=json.dumps(payload), headers=headers) if (r.text): print json.dumps(json.loads(r.text), i...
h, headers=headers) if (r.text): print json.dumps(json.loads(r.text), indent=2) def delete(path) : r = requests.delete(api+path, headers=headers) if (r.text): print json.dumps(json.loads(r.text), indent=2)
felixbb/forseti-security
google/cloud/security/iam/explain/importer/importer.py
Python
apache-2.0
6,988
0
# Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, s...
pe())) def run(self): """Runs the import.""" self.model.set_inprogress(self.session) self.model.
kick_watchdog(self.session) for res_type, obj in self.forseti_importer: if res_type == "organizations": self.session.add(self._convert_organization(obj)) elif res_type == "projects": self.session.add(self._convert_project(obj)) elif res_type =...
idaholab/raven
tests/framework/fail_xml/calc.py
Python
apache-2.0
899
0.006674
# Copyright 2017 Battelle Energy Alliance, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Un
less required by applicable law or agreed to in writing, software # distributed under the License is distributed
on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import math import numpy def run(self, Input): number_of_steps = 16 self.time = numpy.zeros(number_of_steps) unif...
sergio-garcia/learning-django
polls/middleware.py
Python
mit
492
0.00813
from threading import local from django.contrib.sites.models import Site import os _locals = local() def get_current_request(): return getattr(_locals, 'request', None) def get_current_site(): request = get_current_request() host = request.get_host() try: return Site.objects.get(domain__ie
xact=host) except: return Site.objects.all()[0]
class GlobalRequestMiddleware(object): def process_request(self, request): _locals.request = request
vkastyniuk/scrapy-tracker
tests/test_storage.py
Python
bsd-3-clause
2,541
0.000394
# -*- coding: utf-8 -*- from unittest import TestCase from scrapy.settings import Settings from scrapy_tracker.storage.memory import MemoryStorage from scrapy_tracker.storage.redis import RedisStorage from scrapy_tracker.storage.sqlalchemy import SqlAlchemyStorage from tests import TEST_KEY, TEST_CHECKSUM, mock cla...
SH_DB': True })) def test_getset(self): result = self.storage.g
etset(TEST_KEY, TEST_CHECKSUM) self.assertIsNone(result) found = self.storage.getset(TEST_KEY, 'new_checksum') self.assertEqual(TEST_CHECKSUM, found) found = self.storage.getset(TEST_KEY, TEST_CHECKSUM) self.assertEqual('new_checksum', found) result = self.storage.gets...
Bionetbook/bionetbook
bnbapp/protocols/forms/verbs/centrifuge.py
Python
mit
585
0.006838
from protocols.forms import forms from core.utils import S
PEED_UNITS class CentrifugeForm(forms.VerbForm): name = "Centrifuge" slug = "centrifuge" has_machine = True # duration = forms.IntegerField(help_text='this is the minimal time this should take', initial = 'sec') # min_speed = forms.IntegerField() # max_speed = forms.IntegerField(required = Fa...
# comment_why = forms.CharField(required = False)
Darkkey/erlamsa
clients/frida/erlamsa_from_frida.py
Python
mit
1,282
0.0117
#!/usr/bin/python3 import frida import sys import base64 import http.client erlamsa_url = '127.0.0.1:17771' def call_erlamsa(data): original_string = data httpconn = http.client.HTTPConnection(erlamsa_url) headers = {"content-t
ype": "application/octet-stream"} httpconn.request('POST', '/erlamsa/erlamsa_esi:fuzz', original_string, headers) response = httpconn.getresponse() fuzzed_string = response.read() return fuzzed_string def main(target_process): pid = frida.spawn([target_process]) session = frida.attach(pid) ...
def on_message(message, data): new_data = call_erlamsa(data)[:11] print(str(data) + ' erlamsed to ' + str(new_data)) script.post(message = {'type': 'input'}, data = new_data) script.on('message', on_message) script.load() frida.resume(pid) print("[!] Ctrl+D on UNIX, C...
felipedau/pyaxo
setup.py
Python
gpl-3.0
624
0
try: from setuptools import setup except Import
Error: from distutils.core import setup import versioneer setup( name='pyaxo', version=versioneer.get_version(), cmdclass=versioneer.get_cmdclass(), description='Python implementation of the Axolotl ratchet protocol', author='David R. Anders
en', author_email='k0rx@RXcomm.net', url='https://github.com/rxcomm/pyaxo', py_modules=[ 'pyaxo' ], install_requires=[ 'passlib>=1.6.1', 'pynacl>=1.0.1', ], setup_requires=[ 'pytest-runner', ], tests_require=[ 'pytest', ], )
Dino0631/RedRain-Bot
cogs/notinusecogs/react.py
Python
gpl-3.0
19,223
0.00674
# -*- coding: utf-8 -*- """ The MIT License (MIT) Copyright (c) 2017 SML Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy...
emojis.append(x) if(lastlist == new_emojis): new_emojis.append(e) # await self.bot.say(message.id) # await self.bot.say(type(emojis[0])) # await self.bot.say(type(server.emojis[0])) # await self.bot.add_reaction(message, server.emojis[0]) for emoji in...
ew_emojis: try: await self.bot.add_reaction(message, emoji) except discord.HTTPException: # reaction add failed pass except discord.Forbidden: await self.bot.say( "I don’t have permission to react to ...
allthroughthenight/aces
python/drivers/cnoidal_wave_theory.py
Python
gpl-3.0
21,381
0.010102
import sys import math import numpy as np import scipy.special as sp import matplotlib.pyplot as plt sys.path.append('../functions') from base_driver import BaseDriver from helper_objects import BaseField import USER_INPUT from ERRWAVBRK1 import ERRWAVBRK1 from EXPORTER import EXPORTER ## ACES Update to python #----...
.labelUnitDist) print(self.errorMsg) self.fileOutputWriteMain(dataDict, caseI
ndex) return # First Order Approximation if O == 1: #determining m using bisection method a = 1.0*10**-12 b = 1.0-10**-12 loopCount = 0 while (b - a)/2.0 >= 0.00001: xi = (a + b) / 2.0 if self.F1(xi...
correlatedmaterialslaboratory/metal_insulator_interface
transition/ftns_Fourier.py
Python
mit
2,953
0.029123
from scipy import * from scipy import linalg from scipy import interpolate import sys import time def log_mesh(om,nom, ntail_,del_nom = 1): """Creates logarithmic mesh on Matsubara axis Takes first istart points from mesh om and the rest of om mesh is replaced by ntail poinst redistribued log...
qual.append(equal) oms_equal=[] for ind in ind_oms_equal: oms_eq
ual.append( array([om[i] for i in ind]) ) return (ind_om,oms_equal) def Spline_Real(Arr,mesh_log,mesh_reg): #Arr = 1D real array #Arr = Arr[:10] #mesh_log = mesh_log[:10] #print Arr, mesh_log Re = interpolate.UnivariateSpline(mesh_log,Arr,s=0) Arr_large = Re(mesh_reg) #Nmesh = len(mesh_log) #print...
asymptopia/stepintochinese
StepIntoChinese/button.py
Python
gpl-2.0
789
0.025349
""" /********************************************************** Organization :AsymptopiaSoftware | Software@theLimit Website :www.asymptopia.org Support :www.asymptopia.org/forum Author
:Charles B. Cosse Email :ccosse@asymptopia.org Copyright :(C) 2006-2015 Asymptopia Software License :GPLv3 ***********************************************************/ """ import pygame,os from pygame.locals import * class Button(pygame.sprite.Sprite): def __init__(sel...
t_rect() def get_height(self): return self.rect[3]-self.rect[1] def get_width(self): return self.rect[2]-self.rect[0]
telerik/cloudbase-init
cloudbaseinit/plugins/windows/userdataplugins/cloudboothook.py
Python
apache-2.0
1,051
0
# Copyright 2014 Cloudbase Solutions Srl # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable l...
OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from cloudbaseinit.openstack.common import log as logging
from cloudbaseinit.plugins.windows.userdataplugins import base LOG = logging.getLogger(__name__) class CloudBootHookPlugin(base.BaseUserDataPlugin): def __init__(self): super(CloudBootHookPlugin, self).__init__("text/cloud-boothook") def process(self, part): LOG.info("%s content is currentl...
Teamxrtc/webrtc-streaming-node
third_party/webrtc/src/chromium/src/third_party/tlslite/tlslite/handshakesettings.py
Python
mit
9,606
0.003331
# Authors: # Trevor Perrin # Dave Baggett (Arcode Corporation) - cleanup handling of constants # Yngve Pettersen (ported by Paul Sokolovsky) - TLS 1.2 # # See the LICENSE file for legal information regarding use of this file. """Class for setting handshake parameters.""" from .constants import CertificateType ...
ompletes. @type enableChannelID: bool @ivar enableChannelID: If true, the server supports channel ID. @type enableExtendedMasterSecret: bool @ivar enableExtended
MasterSecret: If true, the server supports the extended master secret TLS extension and will negotiated it with supporting clients. @type supportedTokenBindingParams: list @ivar supportedTokenBindingParams: A list of token binding parameters that the server supports when negotiating token binding. List...
jordanemedlock/psychtruths
temboo/core/Library/Mixpanel/Events/Track.py
Python
apache-2.0
4,842
0.00475
# -*- coding: utf-8 -*- ############################################################################### # # Track # Records an event in Mixpanel. # # Python versions 2.6, 2.7, 3.x # # Copyright 2014, Temboo Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in c...
""" Set the value of the Time input for this Choreo. ((optional, date) A unix timestamp representing the time the event occurred. If not provided, Mixpanel will use the time the event arrives at the server.) """ super(TrackInputSet, self)._set_input('Time', value) def set_Token(self, value):...
e value of the Token input for this Choreo. ((required, string) The token provided by Mixpanel. You can find your Mixpanel token in the project settings dialog in the Mixpanel app.) """ super(TrackInputSet, self)._set_input('Token', value) def set_Verbose(self, value): """ Set the va...
fmichalo/n9k-programmability
Python nxapi scripts/cisco/ospf.py
Python
apache-2.0
11,049
0.006154
# Copyright (C) 2013 Cisco Systems Inc. # All rights reserved import ipaddress import re from .feature import Feature from .vrf import VRF from .cisco_secret import CiscoSecret from .nxcli import * import nxos_utils class OSPFSession(Feature): ''' Use this class to configure the OSPF feature. ''' de...
. Any configuration done on this OSPFSession object
will be applied to this VRF. Arguments: vrf: VRF name (string) or the VRF ID (int). Returns: Nothing ''' if type(vrf) in [int, str]: self.vrf = VRF(vrf) elif isinstance(vrf, VRF): self.vrf = vrf else: raise ValueE...
jlant/playground
python/hello-decorators/as_json_decorator.py
Python
mit
375
0.010667
import json def as_json(func): def
inner(*args, **kwargs): result = func(*args, **kwargs) return json.dumps(result) return inner @as_json def func(x, y): return {"result": x + y} # func(3, 4) -> "{result: 7}" print("calling func with decora
tor that serializes the resulting dictionary returned by func to a json object: {}".format(func(3, 4)))
christopherjbly/calendar-indicator
src/widget.py
Python
gpl-3.0
20,729
0.037725
#!/usr/bin/python3 # -*- coding: utf-8 -*- # # Copyright (C) 2012 Lorenzo Carbonell # lorenzo.carbonell.cerezo@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 Foundation, either version 3 of th...
rom_pixbuf(GdkPixbuf.Pixbuf.new_from_file_at_scale(os.path.join(comun.IMAGESDIR,'pinup.svg'),36,36,1)) self.hide() s
elf.show() def load_preferences(self): pass ''' configuration = Configuration() self.a24h = configuration.get('24h') if self.widgetnumber == 1: x = configuration.get('wp1-x') y = configuration.get('wp1-y') self.location = configuration.get('location') self.showwidget = configuration.get('wid...
red-hood/calendarserver
txdav/caldav/datastore/scheduling/test/test_work.py
Python
apache-2.0
30,721
0.002702
## # Copyright (c) 2013-2015 Apple 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 l...
)) self.assertEqual(len(jobs), 0) work = yield ScheduleOrganizerWork.all(self.transactionUnderTest()) self.assertEqual(len(work), 0) baseWork = yield ScheduleWork.all(self.transactionUnderTest()) self.assertEqual(len(baseWork), 0) @inlineCallbacks
def test_cascade_delete_cleanup(self): """ Test that when work associated with L{txdav.caldav.datastore.scheduling.work.ScheduleWork} is removed with the L{ScheduleWork} item being removed, the associated L{JobItem} runs and removes itself and the L{ScheduleWork}. """ ...
dgonyeo/brandrethstats
dbpopulator.py
Python
mit
3,641
0.023345
#!/usr/bin/python import httplib2 import sys,zipfile,re,os,csv from apiclient.discovery import build from apiclient.http import MediaFileUpload from oauth2client.client import OAuth2WebServerFlow from apiclient import errors from openpyxl import Workbook from open
pyxl import load_workbook from pyquery import PyQuery as pq
from lxml.cssselect import CSSSelector BrandrethSpreadsheetName = 'Brandreth Guest Books' def authenticateUser(): # Copy your credentials from the APIs Console CLIENT_ID = '461198277388-s5p2aps1d23005tgjasb6ihbmnc1va9v.apps.googleusercontent.com' CLIENT_SECRET = 'BkZbOMhTil0DFPxZ1FWT2Da3' # Check https://develo...
sametmax/Django--an-app-at-a-time
ignore_this_directory/django/contrib/gis/db/backends/postgis/introspection.py
Python
mit
4,388
0.001367
from django.contrib.gis.gdal import OGRGeomType from django.db.backends.postgresql.introspection import DatabaseIntrospection class GeoIntrospectionError(Exception): pass class PostGISIntrospection(DatabaseIntrospection): # Reverse dictionary for PostGIS geometry types not populated until # introspectio...
d keyword arguments th
at are not the default. dim = row[0] srid = row[1] field_params = {} if srid != 4326: field_params['srid'] = srid if dim != 2: field_params['dim'] = dim return field_type, field_params
baojiwei/WavelengthCalibration
SinglePeak.py
Python
mit
1,344
0.054315
# -*- uft-8 -*- import matplotlib class SinglePeak(): """Creat a class as a Peak Container""" def __init__(self,StandardPeak): self.StandardPeak=StandardPeak self.Indicator=False self.RecordIntegration
Time=0 self.MaxCounts=0 self.PeakPixel=0 self.pixel=[] self.CountsRange=[20000,50000] def GetPixel(self,Wavelength): # get pixel of the peak Wavelength=list(Wavelength)
for i in range(0,len(Wavelength)-1): if Wavelength[i]<self.StandardPeak-5: a=i if Wavelength[i]<self.StandardPeak+5: b=i+1 self.pixel=[a,b] self.Wavelength=Wavelength[a:b] # get wavelength of the peak return self.pixel def GetSingleSpectrum(self,Spectrum): # get spectrum of the peak Spectrum...
GoogleCloudPlatform/PerfKitBenchmarker
perfkitbenchmarker/providers/aws/aws_sqs.py
Python
apache-2.0
3,444
0.003775
"""AWS SQS interface for resources. This class handles resource creation/cleanup for SQS benchmark on AWS. """ import json import os from absl import flags from perfkitbenchmarker import messaging_service as msgsvc from perfkitbenchmarker import providers from perfkitbenchmarker import vm_util from perfkitbenchmarke...
message_size: str): """Runs remote commands on client VM - benchmark's run phase.""" command = (f'python3 -m aws_benchmark ' f'--queue_name={self.queue_name} '
f'--region={self.region} ' f'--benchmark_scenario={benchmark_scenario} ' f'--number_of_messages={number_of_messages} ' f'--message_size={message_size}') stdout, _ = self.client_vm.RemoteCommand(command) results = json.loads(stdout) return results @pro...
megancarney/elastalert
tests/alerts_test.py
Python
apache-2.0
19,021
0.002313
# -*- coding: utf-8 -*- import datetime import json import subprocess from contextlib import nested import mock from jira.exceptions import JIRAError from elastalert.alerts import BasicMatchString from elastalert.alerts import CommandAlerter from elastalert.alerts import EmailAlerter from elastalert.alerts import Jir...
5}} alert_text = str(BasicMatchString(ea.rules[0], match)) assert 'anytest' in alert_text assert 'some stuff happened' in alert_text assert 'username' in alert_text assert 'bob: 10' in alert_text assert 'f
ield: value' in alert_text # Non serializable objects don't cause errors match['non-serializable'] = {open: 10} alert_text = str(BasicMatchString(ea.rules[0], match)) # Pretty printed objects match.pop('non-serializable') match['object'] = {'this': {'that': [1, 2, "3"]}} alert_text = str(B...
efajardo/osg-test
osgtest/library/mysql.py
Python
apache-2.0
2,716
0.005155
import os import re from osgtest.library import core from osgtest.librar
y import service def name(): if core.el_release() < 7: return 'mysql' else: return 'mariadb' def daemon_name(): if core.el_release() < 7: return 'mysqld' else: return 'mariadb' def pidfile():
return os.path.join('/var/run', daemon_name(), daemon_name() + '.pid') def server_rpm(): return name() + '-server' def client_rpm(): return name() def start(): service.check_start(daemon_name()) def stop(): service.check_stop(daemon_name()) def is_running(): return service.is_running(daemon_nam...
enjaz/enjaz
bulb/forms.py
Python
agpl-3.0
15,723
0.004644
# -*- coding: utf-8 -*- import re from django import forms from django.contrib.auth.models import User from django.forms import formset_factory from django.forms.widgets import TextInput from django.utils import timezone from dal import autocomplete from tagging.fields import TagField import accounts.utils from bulb...
available_until', 'is_publicly_owned'] class RequestForm(forms.ModelForm): def __init__(self, *args, **kwargs): instance = kwargs.get('instance', None) super(RequestForm, self).__init__(*args, **kwargs) if instance.book.contribution == 'L': self.fields['borrowing_end_date'].requ...
t? Yeah. data = self.cleaned_data['delivery'] if not data: return data requester_gender = accounts.utils.get_user_gender(self.instance.requester) owner_gender = accounts.utils.get_user_gender(self.instance.book.submitter) if data == 'I' or requester_gender != owner...
delfick/harpoon
harpoon/option_spec/harpoon_specs.py
Python
mit
16,378
0.030101
""" Here we define the yaml specification for Harpoon options, task options and image options. The specifications are responsible for sanitation, validation and normalisation. """ from harpoon.option_spec.command_specs import command_spec from harpoon.formatter import MergedOptionStringFormatter from harpoon.option_s...
h a tty", "chosen_image": "The image that we want to run", "silent_build": "Don't print out log information", "only_pushable": "Ignore images that don't have an ``image_index`` option", "keep_replaced": "Don't auto remove replaced images", "ignore_missing": "Don't raise errors if...
ally)", "no_intervention": "Don't create intervention images when an image breaks", "intervene_afterwards": "Create an intervention image even if the image succeeds", "docker_context_maker": "Function that makes a new docker context object (set internally)", } @hp.memoized_property ...
anarchivist/worldcat
worldcat/request/xid.py
Python
gpl-3.0
4,907
0.001834
# Copyright (C) 2008-2009 Mark A. Matienzo # # This file is part of worldcat, the Python WorldCat API module. # # worldcat 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 # ...
Base class for requests from xID APIs. All xIDRequests require a record number ('rec_num') to be passed when a class is instantiated. Depending on
the request, this will either be an ISBN, an ISSN, or an OCLC record number. xIDRequests by default have their 'method' set as 'getEditions' and their response format set as 'python'. """ def __init__(self, rec_num=None, **kwargs): """Constructor for xIDRequests.""" if 'method' n...
pgmpy/pgmpy
pgmpy/utils/optimizer.py
Python
mit
3,651
0.002739
import logging from math import isclose try: # pragma: no cover import torch optim = torch.optim except ImportError: # pragma: no cover optim = None def pinverse(t): """ Computes the pseudo-inverse of a matrix using SVD. Parameters ---------- t: torch.tensor The matrix wh...
ize. It must return a torch.Tensor object. params: dict {str: torch.Tensor} The parameters which need to be optim
ized along with their initial values. The dictionary should be of the form: {variable name: initial value} loss_args: dict {str: torch.Tensor} Extra parameters which loss function needs to compute the loss. opt: str | Instance of torch.optim.Optimizer The optimizer to use. Should eithe...
organic-interactive/steamaccountcreator
account_create.py
Python
gpl-2.0
4,499
0.011558
import urllib, urllib2, re import pygtk, os, time pygtk.require('2.0') import gtk import mechanize
class CaptchaQuestion: def set_image(self,widget,data=None): self.image.set_from_file("captcha.png") def refresh(self,widget,data=None): self.session = SteamPoweredSession() self.session.set_captcha_img(self.session.captchagid) self.set_image(se
lf) def submit(self,widget,data=None): print self.session.captchagid + ":" + self.entry.get_text() self.session.submit_form(self.entry.get_text()) def submit_and_refresh(self,widget,data=None): self.submit(self) self.refresh(self) def delete_event(self,widget,event,data=None)...
cwgreene/Nanostructure-Simulator
driftscatter.py
Python
mit
1,432
0.048883
import ctypes import random import math import
numpy import stats import constants #energy = mesh.bandstructure.random_ ext = ctypes.cdll.LoadLibrary("c_optimized/driftscatter.so") def randomElectronMovement(particle,electric_field,density_func,mesh,reaper): # global avg_lifetime #
lifetime = .001#lifetime(cell) p = particle dt = mesh.dt p.momentum += drift(mesh,electric_field,p)*dt dx = (p.momentum*dt/mesh.length_scale)/p.mass #stats.avg_dx += numpy.linalg.norm(dx) #stats.avg_momentum += numpy.linalg.norm(p.momentum) #p.dx += dx p.pos += dx # scatter(mesh,particle) #check for out of bo...
jimmyshen/sunset
sunset/parser.py
Python
mit
2,091
0.001913
import re import datetime import logging log = logging.getLogger(__name__) class Marker(object): __slots__ = ['line_start', 'line_end', 'expires'] def __init__(self, lineno): self.line_start = lineno self.line_end = lineno self.expires = None def __str__(se
lf): if self.line_start == self.line_end: line = str(self.line_start) else: line = '{0}-{1}'.format(self.line_start, self.l
ine_end) return 'Marker(line={0}, expires={1})'.format(line, self.expires) def __repr__(self): return str(self) class Parser(object): re_sunset_begin = re.compile( r'>>SUNSET' r'\s+(?P<date>([1-9][0-9]{3})-(1[1-2]|0?[1-9])-([1-2][0-9]|3[0-1]|0?[1-9]))\s*' r'(?P<end><<...
dbrgn/mopidy
tests/audio/test_actor.py
Python
apache-2.0
19,047
0.000368
from __future__ import absolute_import, unicode_literals import threading import unittest import gobject gobject.threads_init() import mock import pygst pygst.require('0.10') import gst # noqa import pykka from mopidy import audio from mopidy.audio.constants import PlaybackState from mopidy.internal import path ...
o.wait_for_state_change().get() call = mock.call('stream_changed', uri=None) self.assertIn(call, send_mock.call_args_list) def test_position_changed_on_pause(self, send_mock): self.audio.prepare_change() self.audio.set_uri(self.uris[0]) self.audio.pause_playback() s...
self.assertIn(call, send_mock.call_args_list) def test_position_changed_on
argivaitv/argivaitv
repo/plugin.video.phstreams/resources/lib/resolvers/videowood.py
Python
gpl-2.0
1,483
0.003372
# -*- coding: utf-8 -*- ''' Genesis Add-on Copyright (C) 2015 lambda This program is free soft
ware: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distribute
d in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. ...
koparasy/gemfi
configs/example/ruby_mem_test.py
Python
bsd-3-clause
6,922
0.012713
# Copyright (c) 2006-2007 The Regents of The University of Michigan # Copyright (c) 2009 Advanced Micro Devices, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: redistributions of source co...
MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DAT...
G IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # Authors: Ron Dreslinski # Brad Beckmann import m5 from m5.objects import * from m5.defines import buildEnv from m5.util import addToPath import os, optparse, sys addToPath('../common') addToPath('../ruby') a...
syci/ingadhoc-odoo-addons
account_interests/interest.py
Python
agpl-3.0
1,803
0.000555
# -*- coding: utf-8 -*- from openerp import fields, models, api, _ class account_account_interest(models.Model): _name = "account.account.interest" _description = 'Account Account Interest' account_id = fields.Many2one( 'account.account', 'Account', required=True, ondelete...
cr, uid, interest_ids[0], context=context) return res
BartSaelen/kubb_match
kubb_match/views/html.py
Python
apache-2.0
4,089
0.002201
# -*- coding: utf-8 -*- import collections from pyramid.view import view_defaults, view_config from kubb_match.data.models import Round @view_defaults(request_method='GET', accept='text/html') class HtmlView(object): def __init__(self, request): self.request = request self.data_manager = request.d...
games.sort(key=lambda x
: x.field, reverse=False) current_games[r.label] = games positions = {} r.positions.sort(key=lambda x: x.position, reverse=False) for pos in r.positions: if pos.position in positions: positions[pos.position].appe...
niwinz/Green-Mine
src/rawinclude/settings.py
Python
bsd-3-clause
122
0
#
-*- coding: utf-8 -*- from django.conf import settings RAWINCLUDE_CACHE = getattr(settings, 'RAWINCLUDE_CACHE', Tr
ue)
plotnick/prettyprinter
prettyprinter.py
Python
mit
13,549
0.001845
from __future__ import with_statement import sys from collections import deque from charpos import CharposStream from bindings import bindings import printervars __all__ = ["PrettyPrinter", "pprint"] class PrintLevelExceeded(StopIteration): pass class Token(object): """Base class for prettyprinter tokens. ...
prefix self.per_line = per_line def output(self, pp): offset = pp.charpos if self.prefix: pp._write(self.prefix) if self.per_line: # Following XP, per-line prefixes are arranged to print directly # below the occurrence of the prefix on the first l...
pp.charpos - len(pp.prefix), self.size <= pp.space)) class End(Token): """End a logical block.""" def __init__(self, suffix=""): self.suffix = suffix def output(self, pp): if self.suffix: pp._write(self.suffix) ...
eldarion/braintree_python
braintree/address_gateway.py
Python
mit
2,190
0.005023
import re import braintree from braintree.address import Address from braintree.error_result import ErrorResult from braintree.exceptions.not_found_error import NotFoundError from braintree.resource import Resource from braintree.successful_result import SuccessfulResult class AddressGateway(object): def __init__(...
+ address_id, {"a
ddress": params} ) if "address" in response: return SuccessfulResult({"address": Address(self.gateway, response["address"])}) elif "api_error_response" in response: return ErrorResult(self.gateway, response["api_error_response"])
alexgorban/models
samples/outreach/blogs/blog_estimators_dataset.py
Python
apache-2.0
6,320
0.000949
# Copyright 2017 The TensorFlow Au
thors. 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 WARRANTI...
igemsoftware/HFUT-China_2015
system/gene.py
Python
apache-2.0
15,855
0.004478
""" gene.py realize the methods that are related to system recommendation. @author: Bowen """ from system.models import gene, reaction, compound, reaction_compound, compound_gene, pathway, pathway_compound, organism from system.fasta_reader import parse_fasta_str from elasticsearch import Elasticsearch import traceba...
""" constructor for gene_graph class @param cid_list: compound id list @type cid_list: str @param ogm: organisms @type ogm:str
""" if cid_list.startswith('_'): cid_list = cid_list[1:] if cid_list.endswith('_'): cid_list = cid_list[:-1] self.cid_list = cid_list.split('_') self.nodes = list() self.edges = list() self.index_dict = dict() self.index = 0 ...
srcLurker/home-assistant
homeassistant/components/sensor/efergy.py
Python
mit
3,862
0
""" Support for Efergy sensors. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/sensor.efergy/ """ import logging import voluptuous as vol from requests import RequestException, get import homeassistant.helpers.config_validation as cv from homeassistant...
url_string = _RESOURCE + 'getInstant?token=' + self.app_token
response = get(url_string) self._state = response.json()['reading'] / 1000 elif self.type == 'budget': url_string = _RESOURCE + 'getBudget?token=' + self.app_token response = get(url_string) self._state = response.json()['status'] ...
apache/incubator-systemml
src/main/python/tests/matrix/test_rand.py
Python
apache-2.0
4,213
0.000237
# ------------------------------------------------------------- # # 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 unde...
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 A...
nguage governing permissions and limitations # under the License. # # ------------------------------------------------------------- import math import random import unittest import numpy as np import scipy.stats as st from systemds.context import SystemDSContext np.random.seed(7) # TODO Remove the randomness of the ...
tingtingths/cipherhelper
demo.py
Python
mit
2,028
0.004931
#!/usr/bin/python3 import sys import getpass import helper from argparse import ArgumentParser if __name__ == "__main__": parser = ArgumentParser(description="Simple file password based encryption/decryption tools. When run as pipe, use standard in/out.") parser.add_argument("-a", "--action", choices=["encrypt...
rgument("-d", "--debug", action="store_true", help="debug print") args = parser.parse_args() if not args.password: passwd = getpass.getpass("Password: ") if args.action == "encrypt" and getpass
.getpass("Verify password: ") != passwd: print("Password mismatch...") exit() else: passwd = args.password # setup params inF = sys.stdin.buffer if not sys.stdin.isatty() else args.INPUT if not sys.stdin.isatty(): args.OUTPUT = args.INPUT outF = sys.stdout.bu...
PaesslerAG/django-currentuser
django_currentuser/middleware.py
Python
bsd-3-clause
1,343
0
from django.conf import settings from django.contrib.auth.models import AnonymousUser from threading import local USER_ATTR_NAME = getattr(settings, 'LOCAL_USER_ATTR_NAME', '_current_user') _thread_locals = local() def _do_set_current_user(user_fun)
: setattr(_thread_locals, USER_ATTR_NAME, user_fun.__get__(user_
fun, local)) def _set_current_user(user=None): ''' Sets current user in local thread. Can be used as a hook e.g. for shell jobs (when request object is not available). ''' _do_set_current_user(lambda self: user) class ThreadLocalUserMiddleware(object): def __init__(self, get_response):...
nive-cms/nive
nive/tests/test_tool.py
Python
gpl-3.0
1,714
0.007001
import time import unittest from nive.definitions import * from nive.tools import * from nive.security import User from nive.components.tools.example import configuration import db_app # ----------------------------------------------------------------- class ToolTest1(unittest.TestCase): def test_tool(self):...
="aaaaa") t.AppliesTo("type1") self.assert_(t.GetAllParameters()) self.assert_(t.GetParameter("test")) class ToolTest(unittest.TestCase): def setUp(self): self.app = db
_app.app_db() def tearDown(self): self.app.Close() def test_toolapp(self): t = self.app.GetTool("nive.components.tools.example") self.assert_(t) r,v = t() self.assert_(r) def test_toolapp2(self): self.app.Register("nive.components.tools.example") t ...
dya2/python-for-android
python3-alpha/python3-src/Lib/warnings.py
Python
apache-2.0
13,836
0.001446
"""Python part of the warnings subsystem.""" # Note: function level imports should *not* be used # in this module as it may cause import lock deadlock. # See bug 683658. import linecache import sys __all__ = ["warn", "showwarning", "formatwarning", "filterwarnings", "resetwarnings", "catch_warnings"] def...
""" import re assert action in ("error", "ignore", "always", "default", "module", "once"), "invalid action: %r" % (action,) assert isinstance(message, str), "message must be a string" assert isins
tance(category, type), "category must be a class" assert issubclass(category, Warning), "category must be a Warning subclass" assert isinstance(module, str), "module must be a string" assert isinstance(lineno, int) and lineno >= 0, \ "lineno must be an int >= 0" item = (action, re.compile(mes...
fujicoin/fujicoin
contrib/seeds/makeseeds.py
Python
mit
8,060
0.003598
#!/usr/bin/env python3 # Copyright (c) 2013-2020 The Fujicoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # # Generate seeds.txt from Pieter's DNS seeder # import re import sys import dns.resolver import collec...
t(m.group(i+2)) < 0 or int(m.group(i+2)) > 255: return None ip = ip + (int(m.group(i+2)) << (8*(3-i))) if ip == 0: return None
net = 'ipv4' sortkey = ip ipstr = m.group(1) port = int(m.group(6)) # Skip bad results. if sline[1] == 0: return None # Extract uptime %. uptime30 = float(sline[7][:-1]) # Extract Unix timestamp of last success. lastsuccess = int(sline[2]) # Extract proto...
Ultimaker/Cura
cura/Machines/Models/CustomQualityProfilesDropDownMenuModel.py
Python
lgpl-3.0
2,352
0.007228
# Copyright (c) 2019 Ultimaker B.V. # Cura is released under the terms of the LGPLv3 or higher. from typing import Optional, TYPE_CHECKING from UM.Logger import Logger import cura.CuraApplication # Imported this way to prevent circular references. from cura.Machines.ContainerTree import ContainerTree from cura.Mach...
l_stack = cura.CuraApplication.CuraApplication.getInstance().getMachineManager().activeMachine if active_global_stack is None: self.setItems([]) Logger.log("d", "No active GlobalStack, set %s as empty.", self.__class__.__nam
e__) return quality_changes_list = ContainerTree.getInstance().getCurrentQualityChangesGroups() item_list = [] for quality_changes_group in sorted(quality_changes_list, key = lambda qgc: qgc.name.lower()): item = {"name": quality_changes_group.name, ...
Dapid/pywt
pywt/setup.py
Python
mit
811
0.002466
#!/usr/bin/env python from __future__ import division, print_function, absolute_import def configuration(parent_package='',top_path=None): from num
py.distutils.misc_util import Configuration import numpy as np config = Configuration('pywt', parent_package, top_path) config.add_data_dir('tests') config.add_subpackage('_tools') # add main PyWavelets module config.add_extension('_pywt', sources=["src/_pywt.c", "src/common.c"
, "src/convolution.c", "src/wavelets.c", "src/wt.c"], include_dirs=["src", np.get_include()], define_macros=[("PY_EXTENSION", None)], ) config.make_config_py() return config if __name__ == '__main__': from numpy.distutils.core import setup setup(**configuratio...
icot/sapi_client
sapi_client/models/volume_read.py
Python
gpl-3.0
17,549
0.002108
# coding: utf-8 """ CERN Unified Storage API A unified storage API for all data-storage back-ends. OpenAPI spec version: 3.3.0 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from pprint import pformat from six import iteritems import re class VolumeRead(object): """...
n_time = None self._filer_address = None self._percentage_snapshot_reserve_used = None self._size_used = None self._state = None self._uuid = None self.discrim
inator = None if active_policy_name is not None: self.active_policy_name = active_policy_name if autosize_enabled is not None: self.autosize_enabled = autosize_enabled if autosize_increment is not None: self.autosize_increment = autosize_increment if cachin...
dansimau/coke
app/config/default.py
Python
bsd-3-clause
418
0.002538
from os.path im
port join, dirname # dd bs=1 count=32 if=/dev/random |pbcopy SECRET_KEY = """îOfi˙0ç;≥4˸î”aƒ§G°3∆˛“'±?5T„ÂK""" # Debug is off by default DEBUG = False # URL to the upstream coke tweet API API_URL = 'http://adaptive-test-api.herokuapp.com/tweets.json' # Databases DSNs SQLALCHEMY_BINDS = { 'tweets': 'sqlite:///...
}
wangheda/youtube-8m
youtube-8m-zhangteng/train_autoencoder.py
Python
apache-2.0
24,941
0.007698
# 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 ...
ata_pattern must be frame-level features. " "Otherwise, --train_data_pattern must be aggregated video-level " "features. The model must also be set appropriately (i.e. to read 3D " "batches VS 4D batches.") flags.DEFINE_string( "model", "LogisticModel", "Which architecture
to use for the model. Models are defined " "in models.py.") flags.DEFINE_bool( "start_new_model", False, "If set, this will not resume from a checkpoint and will instead create a" " new model instance.") # Training flags. flags.DEFINE_integer("batch_size", 1024, "H...
logpai/logparser
logparser/MoLFI/test/org/core/test_validation/test_oracle.py
Python
mit
466
0.004292
import unittest from
definitions import ROOT_DIR from main.org.core.validation.oracle import OracleTemplates class Test(unittest.TestCase): def test_oracle(self): templates = ROOT_DIR + '/test/resources/oracle_test.txt' Oracle = OracleTemplates(templates)
self.assertEqual(Oracle.messages[4][0], ['*', '*', ':', '*']) for msg in Oracle.messages: print(msg) print(Oracle.messages[msg])
theJollySin/pytextgame
pytextgame/actions.py
Python
mit
3,233
0.000619
'''General action classes.''' import sys class Action(object): def __init__(self, situation, name, suffix=None): '''Actions subclass nothing, but require situations to hold them''' # a situation is like "outdoors", "indoors", or "fighting" self._situation = situation s...
): '''getting the name of this action''' return self._name def suffix(self): '''getting the suffix of this action name (e.g. "Move" might be the name, and "West" might be th
e suffix.) ''' return self._suffix def game(self): '''getting the current subclass of game''' return self._game def situation(self): '''getting the situation this action is related to''' return self._situation def info(self): '''placeho...
mogria/rtsh
srv/setup.py
Python
gpl-2.0
512
0.044922
from setuptools import setup, find_packages setup( name = 'rtsh.srv', version = '0.1', description = 'Python Server for the Real Time Strategy Shell Game', author = 'wtjerry, mogria', author_email = 'wtjerry123@gmail.com, m0gr14@gmail.com', keywords = 'real-time strategy game server', url =...
ind_packages(), scripts = ['srv.py'], license = 'GPLv2+', install_require
s = [ 'numpy', 'fake-factory' ] )
iivvoo/two.ol
two/ol/context_processors.py
Python
bsd-2-clause
419
0.002387
from django.utils.encoding import iri_to_uri from urlparse import urljoin def utility
(request): """ Add some useful niceties to the context """ base_uri = "%s://%s" % (request.is_secure() and 'https' or 'http', request.get_host()) return dict( site_base_uri=iri_to_u
ri(base_uri), absolute_uri=iri_to_uri(urljoin(base_uri, request.get_full_path())))
robertwbrandt/ZarafaAdmin
bin/zarafa-session.py
Python
gpl-3.0
7,650
0.024314
#!/usr/bin/env python """ Python wrapper for kopano-stats --session """ import argparse, textwrap, fnmatch, datetime import xml.etree.cElementTree as ElementTree import subprocess # Import Brandt Common Utilities import sys, os sys.path.append( os.path.realpath( os.path.join( os.path.dirname(__file__), "/opt/brandt/co...
" print args['delimiter'].join(headers) print "\n".join(
[ session.replace(";",args['delimiter']) for session in sessions ] ) sys.exit(0) else: xml = ElementTree.Element('sessions') today = datetime.datetime.today() for session in sessions: tmp = session.split(';') attribs = {} for i in range(len(tmp)): if tmp[i]: if i <...
OCA/stock-logistics-warehouse
stock_picking_cancel_confirm/models/__init__.py
Python
agpl-3.0
156
0
# Copyright 2020 Ecosoft Co., Ltd. (http://ecosoft.co.th) # Licen
se AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from . import stock_picking
SqueezeStudioAnimation/omtk
tests/test_animtools.py
Python
mit
2,815
0.004618
import os import mayaunittest from maya import cmds import pymel.core as pymel import omtk import omtk import libSerialization from omtk.libs import libRigging from omtk.modules.rigArm import Arm from omtk.animation import ikfkTools from omtk.animation import ikfkTools
class SampleTests(mayaunittest.TestCase): def _create_simple_arm_build_and_export(self): jnt_1 = pymel.joint(position=[0,0,0]) jnt_2 = pymel.joint(position=[10,0,10]) jnt_3 = pymel.joint(position=[20,0,0])
rig = omtk.create() module = Arm([jnt_1, jnt_2, jnt_3]) rig.add_module(module) rig.build() libSerialization.export_network(rig) return rig, module def _verify_ik_fk_match(self, module): ctrl_ik = module.sysIK.ctrl_ik.node ctrl_swivel = module.sysIK.ctrl_s...
KRHS-GameProgramming-2014/Arkansas-Smith
EndBlock.py
Python
bsd-2-clause
630
0.088889
import pygame class EndBlock(pygame.sprite.Sprite): locked = True def __init__(self, p
os = [0,0]): pygame.sprite.Sprite.__init__(self, self.containers) # always initialize locked endblock self.lock() self.rect = self.image.get_rect() self.place(pos) self.living = True def lock(self): self.image = pygame.image.load("Art/ExitBlockLocked.png") self.locked = True def unlock(self): s...
def update(*args): self = args[0]
mniemela/kirppu
kirppu/app/checkout/__init__.py
Python
mit
23
0
__author__ = '
jyrkila'
jacobajit/ion
intranet/apps/eighth/migrations/0038_merge.py
Python
gpl-2.0
329
0
# -*- coding: utf-8 -*- # Generated by Django 1.9.4 on 2016-03-22 14
:09 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('eighth', '0036_eighthscheduledactivity_administrative'),
('eighth', '0037_auto_20160307_2342'), ]
pathakvaidehi2391/WorkSpace
azurecloudify/resourcegroup.py
Python
apache-2.0
4,763
0.006089
######## # Copyright (c) 2015 GigaSpaces Technologies Ltd. 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...
port utils from cloudify.exceptions import NonRecoverableError from cloudify import ctx from cloudify.decorators import operation import auth @operation def creation_validation(**_): for property_key in constants.RESOURCE_GROUP_REQUIRED_PROPERTIES: _validate_node_properties(property_key, ctx.node.properti...
_name = utils.set_resource_name(_get_resource_group_name, 'Resource group', constants.RESOURCE_GROUP_KEY, constants.EXISTING_RESOURCE_GROUP_KEY, constants.RESOURCE_GROUP_PREFIX) if resource_group_name is None: ...