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
MrSenko/Nitrate
tcms/testcases/migrations/0001_initial.py
Python
gpl-2.0
9,258
0.002916
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models import tcms.core.models.base from django.conf import setti
ngs import tcms.core.models.fields class Migration(migrations.Migration): dependencies = [ ('management', '0001_initial'), ('testplans', '0001_init
ial'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Contact', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('object...
Yukarumya/Yukarum-Redfoxes
testing/mozharness/mozharness/mozilla/merkle.py
Python
mpl-2.0
6,058
0.002146
#!/usr/bin/env python import struct def _round2(n): k = 1 while k < n: k <<= 1 return k >> 1 def _leaf_hash(hash_fn, leaf): return hash_fn(b'\x00' + leaf).digest() def _pair_hash(hash_fn, left, right): return hash_fn(b'\x01' + left + right).digest() class InclusionProof: """ Rep...
opaque NodeHash<32..2^8-1>; struct { LogID log_id; uint64 tree_size; uint64 leaf_inde
x; NodeHash inclusion_path<1..2^16-1>; } InclusionProofDataV2; In other words: - 1 + N octets of log_id (currently zero) - 8 octets of tree_size = self.n - 8 octets of leaf_index = m - 2 octets of path length, followed by * 1 + N octets of NodeHash """ # P...
morucci/repoxplorer
repoxplorer/controllers/projects.py
Python
apache-2.0
2,146
0
# Copyright 2017, Fabien Boucher # Copyright 2017, Red Hat # # 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 appli...
ES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from collections import OrderedDict from pecan import abort from pecan import expose from repoxplorer import version from repoxplorer.index.projects
import Projects rx_version = version.get_version() class ProjectsController(object): @expose('json') def projects(self, pid=None): projects_index = Projects() if pid: project = projects_index.get(pid) if not project: abort(404, detail="Project ID has n...
asiroliu/AnalysisWinPIRALog
AnalysisWinPIRALog_LINUX.py
Python
gpl-2.0
14,575
0.003019
# coding=utf-8 from __future__ import absolute_import, division, print_function, unicode_literals """ Name: AnalysisWinPIRALog_LINUX Author: Andy Liu Email : andy.liu.ud@hotmail.com Created: 3/24/2015 Copyright: Copyright ©Intel Corporation. All rights reserved. Licence: Th...
ff, Power- Interlock-', 'DEV_NAME': 'PCI bridge: Intel Corporation Haswell-E PCI Express Root Port 1 (rev 02) (prog-if 00 [Normal decode])', 'DevCap': 'MaxPayload 256 bytes, PhantFunc 0, Latency L0s <64ns, L1 <1us', 'DevCap2': 'Completion Timeout: Range BCD, TimeoutDis+, LTR-, OBFF Not Supported...
'DevCtl2': 'Completion Timeout: 260ms to 900ms, TimeoutDis-, LTR-, OBFF Disabled ARIFwd+', 'DevSta': 'CorrErr- UncorrErr- FatalErr- UnsuppReq- AuxPwr- TransPend-', 'Flags': 'PMEClk- DSI- D1- D2- AuxCurrent=0mA PME(D0+,D1-,D2-,D3hot+,D3cold+)', 'I/O behind bridge': '0000f000-00000fff', ...
jim-cooley/abletonremotescripts
remote-scripts/samples/Launchpad95/__init__.py
Python
apache-2.0
425
0.016471
from Launchpad import Launchpad def create_instance(c_instance): """ Creates and returns the Launchpad script """ return Launchpad(c_instance) from _Framework.Capab
ilities import
* # noqa def get_capabilities(): return { CONTROLLER_ID_KEY: controller_id(vendor_id=4661, product_ids=[14], model_name='Launchpad'), PORTS_KEY: [inport(props=[NOTES_CC, REMOTE, SCRIPT]), outport(props=[NOTES_CC, REMOTE, SCRIPT])]}
chambers-brian/SIG_Digital-Strategy_SI_ODP_Backend
dataactvalidator/scripts/loadFile.py
Python
cc0-1.0
4,378
0.001142
import os import logging import pandas as pd from dataactvalidator.app import createApp from dataactvalidator.scripts.loaderUtils import LoaderUtils from dataactcore.interfaces.db import GlobalDB from dataactcore.models.domainModels import CGAC, ObjectClass, ProgramActivity from dataactcore.config import CONFIG_BROKE...
ency_id": {"pad_to_length": 3}, "allocation_transfer_id": {"pad_to_length": 3, "keep_null": True}, "account_number": {"pad_to_length": 4} } ) # because we're only loading a subset of program activity info, #
there will be duplicate records in the dataframe. this is ok, # but need to de-duped before the db load. data.drop_duplicates(inplace=True) # insert to db table_name = model.__table__.name num = LoaderUtils.insertDataframe(data, table_name, sess.connection()) sess.commit...
kurikaesu/pytrade
PyTrade/source/models/user.py
Python
gpl-3.0
2,792
0.001074
from ..core import * class User: # Data header indexes USERNAME = 0 ENCRYPTED_NAME = 1 SALT = 2 PROFILE = 3 # data header in the user table COLUMN_HEADERS = [ 'username', 'encrypted_name', 'salt', 'profile', ] # variables to be stored in db __...
classmethod def load_user(cls, username, encrypted_username, salt): user = cls(username) user.set_salt(salt) user.set_encrypted_name(encrypted_username) return cls(username) def set_salt(self, salt=None): self.__crypt = Crypt() if not salt: salt = Cr...
def get_username(self): return self.__username def get_id(self): return self.__id def set_id(self, id): self.__id = id print(id) def get_data(self): return self.__data # Wrap user data into a structure for storing into db def save_data(self): i...
dswah/pyGAM
pygam/tests/test_GAMs.py
Python
apache-2.0
2,344
0.00384
# -*- coding: utf-8 -*- import pytest from pygam import * def test_can_build_sub_models(): """ check that the inits of all the sub-models are correct """ LinearGAM() LogisticGAM() PoissonGAM() GammaGAM() InvGaussGAM() ExpectileGAM() assert(True) def test_LinearGAM_uni(mcycle...
s_X_y): """ check that we can fit a InvGauss GAM on real data """ X, y = trees_X_y gam = InvGaussGAM().fit(X, y) assert(gam._is_fitted) def test_GammaGAM(trees_X_y): """ check that we can fit a Gamma GAM on real data """ X, y = trees_X_y gam = GammaGAM().fit(X, y) assert...
check that we can fit a Custom GAM on real data """ X, y = trees_X_y gam = GAM(distribution='gamma', link='inverse').fit(X, y) assert(gam._is_fitted) def test_ExpectileGAM_uni(mcycle_X_y): """ check that we can fit an Expectile GAM on real, univariate data """ X, y = mcycle_X_y g...
markuz/poster
poster_resources/__init__.py
Python
gpl-3.0
988
0.001012
#! /usr/bin/env python # -*- coding: utf-8 -*- # # This file is part of the Poster project # # Copyright (c) 2006-2009 Marco Antonio Islas Cruz # # Poster is free software; you can redistribute it and/or modify # it under the terms of the GNU
General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # Poster 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 P...
; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA # # @author Marco Antonio Islas Cruz <markuz@islascruz.org> # @copyright 2011 Marco Antonio Islas Cruz # @license http://www.gnu.org/licenses/gpl.txt
bjtrost/TCAG-WGS-CNV-workflow
CNVnator.py
Python
mit
1,274
0.067504
import SV import os import re class CNVnator: match_calltype={'deletion':'DEL', 'duplication':'DUP'} CNVtype=0 coordinates=1 CNVsize=2 normalizedRD=3 eval1=4 eval2=5 eval3=6 eval4=7 q0=8 @staticmethod def parse_coordinates (coordinates): coord=re.sub (':', '-', coordinates) E=coord.split ('-') re...
.doparse ( line ) if sv_line is not None: print(sv_line) f.close() # ----------------------
---------------------------------------
mindriot101/bokeh
bokeh/client/tests/test_session.py
Python
bsd-3-clause
6,568
0.004415
#----------------------------------------------------------------------------- # Co
pyright (c) 2012 - 2018, Anaconda, Inc. All rights reserved. # # Powered by the Bokeh Development Team. # # The full license is in the file LICENSE.txt, distributed with this software. #----------------------------------------------------------------------------- #------------------------------------------------------...
------------ # Boilerplate #----------------------------------------------------------------------------- from __future__ import absolute_import, division, print_function, unicode_literals import pytest ; pytest #----------------------------------------------------------------------------- # Imports #----------------...
skapfer/rubber
src/latex_modules/dvips.py
Python
gpl-2.0
278
0.010791
# This file is part of Rubber and thus covere
d by the GPL import rubber.dvip_tool import rubber.module_interface class Module (rubber.module_interface.Modu
le): def __init__ (self, document, opt): self.dep = rubber.dvip_tool.Dvip_Tool_Dep_Node (document, 'dvips')
bsmr-eve/Pyfa
eos/effects/remotetargetpaintentity.py
Python
gpl-3.0
366
0.002732
# remoteTargetPaintEntity # # U
sed by: # Drones named like: TP (3 of 3) type = "projected", "active" def handler(fit, container, context, *args, **kwargs): if "projected"
in context: fit.ship.boostItemAttr("signatureRadius", container.getModifiedItemAttr("signatureRadiusBonus"), stackingPenalties=True, *args, **kwargs)
mosajjal/mitmproxy
test/mitmproxy/addons/test_stickycookie.py
Python
mit
4,831
0.000828
import pytest from mitmproxy.test import tflow from mitmproxy.test import taddons from mitmproxy.addons impor
t stickycookie from mitmproxy.test import tutils as ntutils def test_domain_match(): assert stickycookie.domain_match("www.google.com", ".google.com")
assert stickycookie.domain_match("google.com", ".google.com") class TestStickyCookie: def test_config(self): sc = stickycookie.StickyCookie() with taddons.context() as tctx: with pytest.raises(Exception, match="invalid filter"): tctx.configure(sc, stickycookie="~b") ...
SleepProgger/another_shellshock_test
shellshock_cgi.py
Python
gpl-2.0
2,092
0.00956
#!/usr/bin/env python import urllib2 import time import random import string randstr = lambda n: ''.join(random.choice(string.ascii_letters + string.digits) for i in xrange(n)) def timing_attack(url, request_type="HEAD", data=None, headers=None, sleeptime = 3, cmd='() { :;}; PATH="/bin:/usr/bin:/usr/local/bin:$PATH" ...
time = -time.time() response = u
rllib2.urlopen(r) htime += time.time() return htime >= sleeptime and htime > otime def text_attack(url, request_type="GET", data=None, headers=None): request_type = request_type.upper() if request_type not in ("GET", "POST"): raise Exception("Illegal request type '%s'" % request_type) ...
jazzmes/pyroute2
examples/ipdb_routes.py
Python
gpl-2.0
503
0
from pyroute2 impo
rt IPDB ip = IPDB() # create dummy interface to host routes on ip.create(kind='dummy', ifname='pr2test').\ add_ip('172.16.1.1/24').\ up().\ commit() # create a route with ip.routes.add({'dst': '172.16.0.0/24', 'gateway': '172.16.1.2'}) as r: pass # modify it with ip.routes['172.1...
e().commit() ip.release()
edisonlz/fruit
web_project/base/youkuapi/show.py
Python
apache-2.0
2,122
0.005666
#coding=utf-8 from base import BaseApi import settings class ShowApi(BaseApi): """ 节目API """ FD = ['showid', 'pk_odshow', 'showname', 'showsubtitle', 'deschead', 'showdesc', 'show_thumburl', 'show_vthumburl', 'show_bannerurl', 'showlength', 'copyright_status', 'paid', 'pay_type', '
onlinetime', 'hasvideotype', 'firstepisode_videoid', 'firstepisode_videotitle', 'firstepisode_videorctitle', 'firstepisode_thumburl', 'firstepisode_thumburl_v2', 'lastepisode_videoid', 'lastepisode_videotitle', 'lastepisode_videorctitle', 'lastepisode_
thumburl', 'lastepisode_thumburl', 'showtotal_vv', 'device_disabled', 'trailer_videoid', 'episode_last', 'episode_total'] fd = ' '.join(FD) HOST = settings.SHOW_HOST FORMAT = "json" @classmethod def get_show_info(cls, show_id, fd=None, **kwargs): """ :param str show_id: y...
huan/Underscore
examples/class_method.py
Python
mit
84
0.02381
class Foo(o
bject): def run(self): return 3 print(Foo().run(
))
bobsummerwill/solidity
scripts/fix_homebrew_paths_in_standalone_zip.py
Python
gpl-3.0
2,861
0.001049
# ------------------------------------------------------------------------------ # This Python script is used within the OS X release process, to ensure # that the standalone OS X ZIP files which we make are actually # standalone, and not implicitly dependent on Homebrew installs for # external libraries which we use. ...
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. # # solidity is distributed in the
hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with solidity. If not, see <http://w...
MarioVilas/secondlife-experiments
SimProxy/udpfilter/FollowTeleports.py
Python
gpl-2.0
1,706
0.010551
from PacketFilterBase import * class FollowTeleportsFilter(PacketFilterBase): def __newSim(self, packet, info_key, ip_key, port_key): decodedData = packet.getDecodedData() circuit_info = decodedData[info_key]
sim_ip = circuit_info[ip_key] sim_port = circuit_info[port_key] new_ip, new_port = self.proxy.newSim( (sim_ip, sim_port) ) circuit_info[ip_key] = new_ip
circuit_info[port_key] = new_port packet.setDecodedData(decodedData) return packet def OpenCircuit(self, fromViewer, packet): if not fromViewer: packet = self.__newSim(packet, 'CircuitInfo', 'IP', 'Port') return False, packet def CrossedRegion(se...
tiborsimko/invenio-records-rest
invenio_records_rest/serializers/response.py
Python
mit
2,527
0
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2016-2018 CERN. # # Invenio is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. """Serialization response factories. Responsible for creating a HTTP response given ...
search_responsify(serializer, mimetype): """Create a Records-REST search result response serializer
. :param serializer: Serializer instance. :param mimetype: MIME type of response. :returns: Function that generates a record HTTP response. """ def view(pid_fetcher, search_result, code=200, headers=None, links=None, item_links_factory=None): response = current_app.response_cla...
dongjoon-hyun/tensorflow
tensorflow/python/autograph/core/errors_test.py
Python
apache-2.0
3,793
0.006591
# Copyright 2018 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...
ame in cm.exception.custom_traceback: _, _, function_name, _ = frame self.assertNotEqual('zero_div', function_name) self.assertIn(origin.as_frame(), set(cm.exception.custom_traceback)) def test_improved_errors_no_matching_lineno(self): loc, origin = self.fake_origin(zero_div, -1) zero_div_cal...
: with self.cached_session() as sess: sess.run(ops) all_function_names = set() for frame in cm.exception.custom_traceback: _, _, function_name, _ = frame all_function_names.add(function_name) self.assertNotEqual('test_function_name', function_name) self.assertIn('zero_di...
zhangjiajie/tax_benchmark
script/ete2/clustering/__init__.py
Python
gpl-3.0
1,549
0.008393
__VERS
ION__="ete2-2.2rev1026" # -*- coding: utf-8 -*- # #START_LICENSE########################################################### # # # This file is part of the Environment for Tree Exploration pro
gram # (ETE). http://ete.cgenomics.org # # ETE is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # ETE is distributed in the hope ...
alexa-infra/negine
thirdparty/boost-python/libs/python/pyste/src/Pyste/EnumExporter.py
Python
mit
2,214
0.006323
# Copyright Bruno da Silva de Oliveira 2003. Use, modification and # distribution is subject to the Boost Software License, Version 1.0. # (See accompanying file LICENSE_1_0.txt or copy at # http://www.boost.org/LICENSE_1_0.txt) from Exporter import Exporter from settings import * import utils #===========...
h('._'): unnamed_enum = True code = '' if not unnamed_enum: code += indent + namespaces.python code += 'enum_< %s >("%s")\n' % (full_nam
e, rename) for name in self.enum.values: rename = self.info[name].rename or name value_fullname = self.enum.ValueFullName(name) if not unnamed_enum: code += in_indent + '.value("%s", %s)\n' % (rename, value_fullname) else: ...
atsuyim/OpenBazaar
tests/test_transport.py
Python
mit
2,556
0.002347
import unittest from node.openbazaar_daemon import OpenBazaarContext import mock from node import transport def get_mock_open_bazaar_context(): return OpenBazaarContext.create_default_instance() class TestTransportLayerCallbacks(unittest.TestCase): """Test the callback features of the TransportLayer class....
self.callback4 = mock.Mock() self.callback5 = mock.Mock() self.validator4 = mock.Mock(return_value=True) self.validator5 = mock.Mock(return_value=False) self.transport_layer.add_callback('section_two', {'cb': self.callb
ack4, 'validator_cb': self.validator4}) self.transport_layer.add_callback('section_two', {'cb': self.callback5, 'validator_cb': self.validator5}) def _assert_called(self, one, two, three): self.assertEqual(self.callback1.call_count, one) self.assertEqual(self.callback2.call_count, two) ...
NovaPointGroup/purchase-workflow
purchase_all_shipments/__openerp__.py
Python
agpl-3.0
978
0
# Author: Leonardo Pistone # Copyright 2015 Camptocamp SA # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Fre
e Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. {'name': 'Purchase All Shipments', 'version': '1.0', 'author': "Camptocamp,Odoo Community Association (OCA)", ...
googleapis/python-dlp
samples/snippets/redact_test.py
Python
apache-2.0
1,601
0.000625
# 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 w
riting, 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 os import shutil import tempfile import pytest ...
radio-astro-tools/spectral-cube
spectral_cube/tests/test_casafuncs.py
Python
bsd-3-clause
9,896
0.003133
from __future__ import print_function, absolute_import, division import os import shutil from itertools import product import pytest import numpy as np from numpy.testing import assert_allclose from astropy.tests.helper import assert_quantity_allclose from astropy import units as u from casa_formats_io import coordsy...
Jy / u.beam) # Slice the cube assert_quantity_allclose(cube[:, 0, 0], [1, 1, 1] * u.Jy / u.beam) @pytest.mark.skipif(not CASA_INSTALLED, reason='CASA tests must be run in a CASA environment.') @pytest.mark.parametrize('filename', ('data_adv', 'data_advs', '
data_sdav', 'data_vad', 'data_vsad'), indirect=['filename']) def test_casa_read(filename, tmp_path): # Check that SpectralCube.read returns data with the same shape and values # if read from CASA as if read from FITS. cube = SpectralCube.read(...
forweipan/fimap
src/pybing/query/web.py
Python
gpl-2.0
514
0.005837
# This file is part of PyBing (http://pybing.googlecode.com). # # Copyright (C) 2009 JJ Geewax http://geewax.org/ # All rights reserved. # # This software is licensed as described in the file COPYING.txt, # which you should have received as pa
rt of this distribution. """ This module holds the Bing WebQuery class used to do web searches against Bing. """
from pybing import constants from pybing.query import BingQuery, Pagable class WebQuery(BingQuery, Pagable): SOURCE_TYPE = constants.WEB_SOURCE_TYPE
kjjuno/GitComponentVersion
docs/source/conf.py
Python
mit
4,802
0.000416
# -*- coding: utf-8 -*- # # GitComponentVersion documentation build configuration file, created by # sphinx-quickstart on Tue Apr 11 10:51:23 2017. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated...
General information about the project. project = u'GitComponentVersion' copyright = u'2017, Kevin Johnson' author = u'Kevin Johnson' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The shor...
a list of supported languages. # # This is also used if you do content translation via gettext catalogs. # Usually you set "language" from the command line for these cases. language = None # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # T...
mattmcd/PyAnalysis
mda/tutorial/pandastut.py
Python
apache-2.0
1,920
0.018229
#"10 Minutes to pandas" tutorial import pandas as pd import numpy as np import matplotlib.pyplot as plt class ObjectCreator: """Object creation demo""" def __init__(self): self.data = [] def createSeries(self): s = pd.Series( [1,3,5,np.nan,6,8] ); return s def createDataFram...
print "Tail: df.tail({})".format(lineCount) print self.df.tail(lineCount) def getIndex(self, lineCount=None): print "Data index: df.index" print self.df.index def getColumns(self, lineCount=None): print "Data columns: df.columns" print self.df.columns ...
int "Describe data: df.describe()" print self.df.describe()
vprusso/youtube_tutorials
twitter_python/part_5_sentiment_analysis_tweet_data/sentiment_anaylsis_twitter_data.py
Python
gpl-3.0
4,622
0.004976
from tweepy import API from tweepy import Cursor from tweepy.streaming import StreamListener from tweepy import OAuthHandler from tweepy import Stream from textblob import TextBlob import twitter_credentials import matplotlib.pyplot as plt import numpy as np import pandas as pd import re # # # # TWITTER CLIENT #...
entials.ACCESS_TOKEN, twitter_credentials.ACCESS_TOKEN_SECRET) return auth # # # # TWITTER STREAMER # # # # class TwitterStreamer(): """ Class for streaming and
processing live tweets. """ def __init__(self): self.twitter_autenticator = TwitterAuthenticator() def stream_tweets(self, fetched_tweets_filename, hash_tag_list): # This handles Twitter authetification and the connection to Twitter Streaming API listener = TwitterListener(fetc...
shanqing-cai/MRI_analysis
convert_dcm.py
Python
bsd-3-clause
3,563
0.006736
#!/usr/bin/env python import os import sys import glob import argparse from scai_utils import * help_doc = "Convert raw DICOM images to nii format. (scai)" # === Heuristics === # heur = [["functionalsparse", "bold"], ["DIFFUSIONHIGHRES10Min", "diffusion"], ["AAHeadScout32", "aascout"], ["tf...
= # assert(nfn.endswith(".nii.gz")) assert(nfn.count("_") == 1) ius = nfn.index("_") assert(ius >= 8) timeStr = nfn[ius - 8 : ius + 7] assert(nfn.count(timeStr) == 1) prefix = nfn[:ius - 8] nfn1 = nfn.replace(timeStr, "")
nfn2 = nfn1[len(prefix) :] suffix = nfn2.replace(imgStr, "").replace(".nii.gz", "") subDir = os.path.join(args.outputDir, imgType) check_dir(subDir, bCreate=True) if prefix == "": imgFN = os.path.join(subDir, \ "%s_%s_%s.nii.gz" \ ...
Akhail/Tebless
tebless/utils/keyboard.py
Python
mit
550
0
# Copyright (c) 2017 Michel Betancourt # # This software is released under the MIT Licens
e. # https://opensource.org/licenses/MIT """Global constants """ import sys import blessed TERM = blessed.Terminal() class Key
board(object): def __getattr__(self, name): assert isinstance(name, str) if name.startswith("KEY_") and name in TERM.__dict__: return TERM.__dict__.get(name) raise AttributeError( "type object 'Keyboard' has no attribute '{}'".format(name)) sys.modules[__name__] = ...
hardbyte/python-can
test/test_cantact.py
Python
lgpl-3.0
2,119
0.000944
#!/usr/bin/env python """ Tests for CANtact interfaces """ import unittest import can from can.interfaces import cantact class CantactTest(unittest.TestCase): def test_bus_creation(self): bus = can.Bus(channel=0, bustype="cantact", _testing=True) self.assertIsInstance(bus, cantact.CantactBus) ...
act.MockInterface.send.assert_called() def test_recv(self): bus = can.Bus(channel=0, bustype="cantact", _testing=True) frame = bus.recv(timeout=0.5) cantact.MockInterface.recv.assert_called() self.assertIsInstance(frame, can.Message) def test_recv_timeout(self):
bus = can.Bus(channel=0, bustype="cantact", _testing=True) frame = bus.recv(timeout=0.0) cantact.MockInterface.recv.assert_called() self.assertIsNone(frame) def test_shutdown(self): bus = can.Bus(channel=0, bustype="cantact", _testing=True) bus.shutdown() cantact...
berrange/nova
nova/tests/virt/baremetal/db/test_bm_node.py
Python
apache-2.0
6,886
0.000581
# Copyright (c) 2012 NTT DOCOMO, 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 requ...
self.assertEqual(len(r), 1) self.assertEqual(r[0]['pm_address'], '0') r = db.bm_node_get_all(self.conte
xt, service_host="host2") self.assertEqual(len(r), 5) pmaddrs = [x['pm_address'] for x in r] self.assertIn('1', pmaddrs) self.assertIn('2', pmaddrs) self.assertIn('3', pmaddrs) self.assertIn('4', pmaddrs) self.assertIn('5', pmaddrs) r = db.bm_node_get_all...
wyxpku/pkucourier
user/easemobSendMessage.py
Python
mit
1,201
0.004996
# -*- coding: UTF-8 -*- from urllib import request import json def send_message(user, message): # get token, do not change url_gettoken = "https://a1.easemob.com/ziyuanliu/pkucarrier/token" header = {"Content-Type":"application/json"} body = '{"grant_type": "client_credentials","client_id": "YXA6OlYUg...
s = json.loads(html) token = s['access_token'] # send message url = "https://a1.easemob.com/ziyuanliu/pkucarrier/messages" # need to change: # message: params[msg][msg] field # target user: params[target], must be a dict params = '{"target_type" : "users", "target" : ["%s"], "msg" : {"type"...
sage) header = {"Content-Type":"application/json", "Authorization":"Bearer %s" % (token)} params = params.encode() req = request.Request(url, params, header) resp = request.urlopen(req) html = resp.read().decode() return html # print(html) return html # print(html)
twbarber/pygooglevoice
googlevoice/voice.py
Python
bsd-3-clause
11,310
0.002122
from conf import config from util import * import settings import base64 qpat = re.compile(r'\?') if settings.DEBUG: import logging logging.basicConfig() log = logging.getLogger('PyGoogleVoice') log.setLevel(logging.DEBUG) else: log = None class Voice(object): """ Main voice instance for...
ive the specified message by removing it from the Inbox. """ if isinstance(msg, Message): msg = msg.id assert is_sha1(msg), 'Message id not a SHA1 hash' self.__messages_post('archive', msg, archive=archive) def delete(self, msg, trash=1): """ Moves th
is message to the Trash. Use ``message.delete(0)`` to move it out of the Trash. """ if isinstance(msg, Message): msg = msg.id assert is_sha1(msg), 'Message id not a SHA1 hash' self.__messages_post('delete', msg, trash=trash) def download(self, msg, adir=None): ""...
ufieeehw/IEEE2015
ros/ieee2015_controller/src/test.py
Python
gpl-2.0
436
0
import numpy as np mecanum_matrix = np.matrix([ [+1, +1, +1, +1], # Unitless! Shooting for ra
d/s [+1, -1, +1, -1], # Unitles
s! Shooting for rad/s [+1, +1, -1, -1], # Unitless! Shooting for rad/s # [+1, -1, -1, +1], # This is the error row (May not be necessary) ], dtype=np.float32) / 4.0 # All of the rows are divided by 4 v_target = np.array([0.0, 1.0, 0.0]) print np.linalg.lstsq(mecanum_matrix, v_target)[0]
uiri/pxqz
venv/lib/python2.7/site-packages/django/db/models/query.py
Python
gpl-3.0
69,558
0.001409
""" The main QuerySet implementation. This provides the public API for the ORM. """ import copy import itertools import sys from django.db import connections, router, transaction, IntegrityError from django.db.models.fields import AutoField from django.db.models.query_utils import (Q, select_related_descend, defe...
: """ Retrieves an item or slice from the set of results. """ if not isinstance(k, (slice, int, long)): raise TypeError assert ((not isinstance(k, slice) and (k >= 0)) or (isinstance(k, slice) and (k.start is None or k.start >= 0) a...
"Negative indexing is not supported." if self._result_cache is not None: if self._iter is not None: # The result cache has only been partially populated, so we may # need to fill it out a bit more. if isinstance(k, slice): if k.sto...
nlake44/UserInfuser
serverside/testing/test.py
Python
agpl-3.0
22,168
0.015292
# Copyright (C) 2011, CloudCaptive # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed i...
return "Error getting same account. Subtest 1" # purge from memcache and get from db memcache.delete(key=key, namespace=ent_type) sameent = memcache_db.get_entity(key, ent_type) if sameent.description != key: return "Error getting same account from DB (no cache). Subtest 2" # Set and get...
ret != ret2: self.response.out.write("Error getting key name") sameent = memcache_db.get_entity(key, ent_type) if sameent.isEnabled != "no" or sameent.permissions != "public": return "Error getting same account after altering entity. Subtest 3" try: memcache_db.delete_entity(sameent, key...
richrd/bx
modules/newpass.py
Python
apache-2.0
939
0.00426
from mod_base import* class NewPass(Command): """Change your password. Usage: newpass oldpassword newpassword newpassword """ def ru
n(self, win, user, data, caller=None): args = Args(data) if len(args) < 3: win.Send("Usage: newpass oldpassword newpassword n
ewpassword") return False if not user.IsAuthed(): win.Send("you've not logged in") return False oldpass, pass1, pass2 = args[0:3] if pass1 == pass2: if self.bot.config.ChangeAccountPass(user.account["name"], oldpass, pass1): win....
mzizzi/ansible
lib/ansible/playbook/play_context.py
Python
gpl-3.0
27,386
0.002347
# -*- coding: utf-8 -*- # (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License,...
seful, # 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 Ansible. If not, see <http://www.gnu.org/licenses/>. ...
ndom import re import string import sys from ansible import constants as C from ansible.errors import AnsibleError from ansible.module_utils.six import iteritems from ansible.module_utils.six.moves import shlex_quote from ansible.module_utils._text import to_bytes from ansible.module_utils.parsing.convert_bool import ...
OlegKlimenko/Plamber
app/tests/test_models.py
Python
apache-2.0
53,921
0.004636
# -*- coding: utf-8 -*- import copy import os from django.contrib import auth from django.contrib.auth.models import User from django.core.files.uploadedfile import SimpleUploadedFile from django.db.models import QuerySet from django.test import TestCase, Client, mock from django.urls import reverse from ..forms imp...
'name': 'Second Book', 'author': cls.author2, 'category': cls.category1, 'language': cls.language_en, 'file': SimpleUploadedFile('test_book.pdf', open(test_book_path, 'rb').read()),
'who_added': cls.the_user2, 'blocked_book': True }, { 'name': 'Third Book', 'author': cls.author2, 'category': cls.category1, 'language': cls.language_ru, 'file': SimpleUploadedFile('test_book.pdf'...
xflows/clowdflows-backend
services/tests.py
Python
mit
685
0.007299
from pysimplesoap.client import SoapClient def inspect(wsdl_url): client = SoapClient(wsdl=wsdl_url,trace=False) print("Target Namespace", client.namespace) for service in list(client.services.values()): for port in list(service['ports'].values()):
print(port['location']) for op in list(port['operations'].values()): print('Name:', op['name']) print('Docs:', op['documentation'].strip()) print('SOAPAction:', op['action']) print('Input', op['input']) # args type declaration ...
print('\n')
UNINETT/nav
python/nav/mibs/hp_httpmanageable_mib.py
Python
gpl-2.0
1,236
0
# # Copyright (C) 2015 Uninett AS # # This file is part of Network Administration Visualized (NAV). # # NAV is free software: you can redistribute it and/or modify it under # the terms of the GNU General Public License version 3 as published by # the Free Software Foundation. # # This program is distributed in the hope...
ld HP switches"""
serial = yield self.get_next('hpHttpMgSerialNumber') if serial: if isinstance(serial, bytes): serial = serial.decode("utf-8") defer.returnValue(serial)
GNUtn/eventoL
eventol/manager/migrations/0036_auto_20191015_2132.py
Python
gpl-3.0
624
0.001603
# -*- coding: utf-8 -*- # Genera
ted by Django 1.11.23 on 2019-10-15 21:32 from __future__ import unicode_literals import datetime from django.db import migrations, models class Migration(migrations.Migration): dependencies
= [ ('manager', '0035_auto_20191013_1705'), ] operations = [ migrations.AlterField( model_name='event', name='limit_proposal_date', field=models.DateField(default=datetime.date(2019, 10, 15), help_text='Limit date to submit talk proposals', verbose_name='Lim...
Azure/azure-sdk-for-python
sdk/keyvault/azure-mgmt-keyvault/azure/mgmt/keyvault/v2020_04_01_preview/operations/_private_link_resources_operations.py
Python
mit
4,897
0.004288
# 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 ...
a = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.KeyVault/vaults/{vaultName}/privateLinkResou
rces'} # type: ignore
mathjazz/pontoon
pontoon/checks/models.py
Python
bsd-3-clause
1,177
0.00085
from django.db import models from pontoon.base.models import Translation class FailedCheck(models.Model): """ Store checks performed on translations if they failed. Severity of failed checks are expressed by subclasses of this model. """ class Library(models.TextChoices): PONTOON = "p",...
ompare-locales" library = models.CharField( max_length=20, choices=Library.choices, db_index=True, ) message = models.TextField() class Meta: abstract = True def __repr__(self): return "[{}] {}: {}".format( self.__class__.__name__, self.get_libr...
nslation, models.CASCADE, related_name="warnings" ) class Meta(FailedCheck.Meta): unique_together = (("translation", "library", "message"),) class Error(FailedCheck): translation = models.ForeignKey(Translation, models.CASCADE, related_name="errors") class Meta(FailedCheck.Meta): uni...
pantsbuild/pex
pex/vendor/_vendored/pip/pip/_internal/vcs/git.py
Python
apache-2.0
15,599
0
# The following comment should be removed at some point in the future. # mypy: disallow-untyped-defs=False from __future__ import absolute_import import logging import os.path import re from pip._vendor.packaging.version import parse as parse_version from pip._vendor.six.moves.urllib import parse as urllib_parse fro...
` and ``git fetch --tags``). """ if rev.startswith("refs/"): # Always fetch remote refs. return True if not looks_like_hash(rev): # Git fetch would fail wi
th abbreviated commits. return False if cls.has_commit(dest, rev): # Don't fetch if we have the commit locally. return False return True @classmethod def resolve_revision(cls, dest, url, rev_options): # type: (str, HiddenText, RevOptions) -> RevOpti...
dcclogin/TextGenerator
TitleCrawler/ccf_conference/categories/database/apweb2015.py
Python
mit
3,395
0.028866
# -*- coding: utf-8 -*- import re import copy import random import os, sys import MySQLdb import requests from time import sleep from threading import Thread from bs4 import BeautifulSoup reload(sys) sys.setdefaultencoding('utf-8') clade = 'http://dblp.uni-trier.de/db/conf/apweb/' months = { 'January': '01', ...
== 200: soup = BeautifulSoup(r.text, 'lxml') leaves = [] late = soup.find('ul', class_='publ-list') tags = late.find_all('div', class_='data', itemprop='headline') for tag in tags: leaves.append(tag.find_all('a')[-1]['href']) return leaves def sub_months(match_obj): """ transfer months to digital form (in-p...
leaf) if r.status_code == 200: soup = BeautifulSoup(r.text, 'lxml') lat = soup.find('div', class_='data', itemprop='headline') tag = lat.find('span', class_='title', itemprop='name') txt = tag.get_text() try: match_obj_mons = re.search(pattern_mons, txt) match_obj_mons = match_obj_mons.group().strip() matc...
lcharleux/argiope
argiope/tests/mesh/triangulation.py
Python
gpl-3.0
1,193
0.004191
import argiope as ag import numpy as np import pandas as pd from matplotlib.tri import Triangulation mesh = ag.mesh.read_msh("demo.msh") conn = mesh.split("simplices").unstack() coords = mesh.nodes.coords.copy() node_map = pd.Series(data = np.arange(len(coords)), index = coords.index) conn = node_map.loc[conn.values....
ities.astype(np.int32) connectivities = nodes_map[connectivities] labels = np.array(elements.index) etype = np.array(elements.type.argiope).flatten() print(etype) #TRIANGLES x, y, tri = [], [], [] for i in range(len(etype)): triangles = connectivities[i][argiope.mesh.ELEMENTS[etype[i]]["simplices"]...
ds[:,0], coords[:,1], tri) """
h3l/rfw_utils
setup.py
Python
mit
1,054
0.015217
from setuptools import setup, find_packages import sys, os """
打包的用的setup必须引入 """ VERSION = '0.0.1' with open('README.md') as f: long_description = f.read() setup( name='rfw_utils', # 文件名 version=VERSION, # 版本(每次更新上传Pypi需要修改) description="Speed up restframework develop", long_description=long_description, # 放READM
E.md文件,方便在Pypi页展示 classifiers=[], # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers keywords='restframework utils', # 关键字 author='helvetica', # 用户名 author_email='xidianlz@gmail.com', # 邮箱 url='https://github.com/h3l/rfw_utils', # github上的地址,别的地址也可以 license='MI...
pgfoster/p4-phylogenetics
p4/geneticcode.py
Python
gpl-2.0
18,804
0.004733
import string import sys class GeneticCode: """A container for NCBI translation tables. See the ncbi translation tables, which this week are at http://www.ncbi.nlm.nih.gov/Taxonomy/Utils/wprintgc.cgi?mode=c (If they move, poke around the 'taxonomy browser' area.) This week we have - **1**...
CC*WLLLLPPPPHHQQRRRRIIIMTTTTNNKKSSRRVVVVAAAADDEEGGGG' Starts = '-----------------------------------M----------------------------'
Base1 = 'TTTTTTTTTTTTTTTTCCCCCCCCCCCCCCCCAAAAAAAAAAAAAAAAGGGGGGGGGGGGGGGG' Base2 = 'TTTTCCCCAAAAGGGGTTTTCCCCAAAAGGGGTTTTCCCCAAAAGGGGTTTTCCCCAAAAGGGG' Base3 = 'TCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAG' # tables 7 and 8 have been deleted from NCBI. elif ...
nuagenetworks/tempest
tempest/api/network/test_dhcp_ipv6.py
Python
apache-2.0
18,551
0.000054
# Copyright 2014 OpenStack Foundation # 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...
tateful'), ('dhcpv6-stateless', 'slaac'), ('slaac', 'dhcpv6-stateful'), ('dhcpv6-stateful', 'dhcpv6-stateless'), ('dhcpv6-stateful', 'slaac'), ('slaac', 'dhcpv6-stateless'), ): kwargs = {'ipv6_ra_mode': ra_mode, ...
f.assertRaises(lib_exc.BadRequest, self.create_subnet, self.network, **kwargs) @test.idempotent_id('21635b6f-165a-4d42-bf49-7d195e47342f') def test_dhcpv6_stateless_no_ra_no_dhcp(self): # NOTE: If no radvd option ...
wodiesan/senior_design_spring
night_sensor/night_feature.py
Python
mit
1,274
0.00157
""" @author: Sze "Ron" Chau @e-mail: chaus3@wit.edu @source: https://github.com/wodiesan/sweet-skoomabot @desc Night sensor-->RPi for Senior Design 1 """ import logging import os import RPi.GPIO as GPIO import serial import subprocess import sys import time import traceback # GPIO pins. Uses the BC...
RPi B+ board. IR1 = 26 IR2 = 19 IR3 = 13 IR4 = 6 def init_serial(): """Initialize the serial connection to the light sensor.""" ser = serial.Serial() #ser.port = "\\.\COM4" # Windows
ser.port = "/dev/ttyUSB0" # Linux ser.baudrate = 57600 try: ser.open() except Exception, e: logger.info("Possible open serial port: " + str(e)) print 'Check the serial USB port.' exit() return ser def init_leds(): """Initial setup for light sensor and IR LEDs....
SEL-Columbia/commcare-hq
corehq/apps/accounting/tests/base_tests.py
Python
bsd-3-clause
191
0
fr
om django.test import TestCase from corehq.apps.accounting import generator class BaseAccountingTest(TestCase): def setUp(self): generator.instantiate_accounting_for_tests()
yorkhackspace/pollution_graph
test_server.py
Python
gpl-3.0
3,182
0.002828
#!/usr/bin/env python3 """ Python half of the pollution monitor. This bit is the brains, such that they are. The arduino will be pretty dumb just driving the lights and display and also reading the rotary encoders. Arduino sends Lnn - Where nn is a number from 00 to 99 for locations. Tnn - Where nn is a number for t...
the LED value """ from test_data import * import serial import logging class Arduino(): def __init__(port, data_values): self.port == port self.data_values = data_values self.arduino = open_arduino(port) self.currentTime = 8 self.currentLocation = 1 def write(self, me...
ng to the arduino""" err = none debug("Sending {}".format(message)) self.arduino.writeline(b(message)) return err def arduino_read(self): msg = arduino.readline() if msg.startswith("T"): self.process_time(self, msg) elif msg.startswith("L"): ...
luozhaoyu/big-data-system
assignment3/partB/parsetweet.py
Python
mit
2,168
0.006919
#!/usr/bin/env python import os,sys import string import re import pickle stopword_file = './stopwords' class CleanTweet(object): """ case-sensitive, removed url, hashtag#, special term like 'RT', and reply@ """ _url = r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F])...
rgv[1] outfilename = sys.argv[2] tweets = [] stopwords = [] with open(stopword_file, 'rb') as fs: for word in fs: stopwords.append(word.strip()) fs.close() with open(infilename, 'rb') as fi, open(outfilename, 'wb') as fo: infile = fi.read()
start = '[' stop = ']' buf = '' flag = False for c in infile: if c == start: flag = True continue elif c == stop: tweetobj = CleanTweet(buf, stopwords).cleantweet() if tweetobj != '': tweets.append(tweetobj) ...
chungg/python-aodhclient
aodhclient/utils.py
Python
apache-2.0
4,174
0.00024
# -*- encoding: utf-8 -*- # # 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...
pp.hexnums, exact=n) uuid = pp.Combine(hex_string(8) + ("-" + hex_string(4)) * 3 + "-" + hex_string(12)) number = r"[+-]?\d+(:?\.\d*)?(:?[eE][+-]?\d+)?" number = pp.Regex(number).setParseAction(lambda t: float(t[0])) identifier = pp.Word(pp.alphas, pp.alphanums + "_") quoted_string = pp.QuotedString('...
mparison_term)) + pp.Suppress(']'))("list") comparison_term << (null | boolean | uuid | identifier | number | quoted_string | in_list) condition = pp.Group(comparison_term + operator + comparison_term) expr = pp.operatorPrecedence(condition, [ ("not", 1, pp.opAssoc.RIGHT, ), ...
rahulunair/nova
nova/tests/unit/policies/test_admin_actions.py
Python
apache-2.0
5,313
0
# 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 # d...
rule_name, self.controller._reset_state, self.req, self.instance.uuid, body={'os-resetState': {'state': 'active'}}) def test_inject_network_info_policy(self): rule_name = "os_
compute_api:os-admin-actions:inject_network_info" with mock.patch.object(self.controller.compute_api, "inject_network_info"): self.common_policy_check(self.admin_authorized_contexts, self.admin_unauthorized_contexts, ...
jameswatt2008/jameswatt2008.github.io
python/Python核心编程/网络编程/截图和代码/概述、SOCKET/多进程copy文件/test/string.py
Python
gpl-2.0
11,854
0.00194
"""A collection of string constants. Public module variables: whitespace -- a string containing all ASCII whitespace ascii_lowercase -- a string containing all ASCII lowercase letters ascii_uppercase -- a string containing all ASCII uppercase letters ascii_letters -- a string containing all ASCII letters digits -- a ...
###################################################################### # the Formatter class # see PEP 3101 for details and purpose of this class # The hard parts are reused from the C implementation. They're exposed as "_" # prefixed methods of str. # The overall parser is implemented in _string.formatter_parser. #...
TypeError("descriptor 'format' of 'Formatter' object " "needs an argument") self, *args = args # allow the "self" keyword be passed try: format_string, *args = args # allow the "format_string" keyword be passed except ValueError: if 'format_s...
OpenInkpot-archive/iplinux-xcb-proto
xcbgen/matcher.py
Python
mit
3,534
0.00764
''' XML parser. One function for each top-level element in the schema. Most functions just declare a new object and add it to the module. For typedefs, eventcopies, xidtypes, and other aliases though, we do not create a new type object, we just record the existing one under a new name. ''' from os.path import join f...
(id,) event = Event(name, node) event.add_opcode(node.get('number'), name, True) module.add_event(id, name, event) def eventcopy(node, module, namespace): id = node.get('name') name = namespace.prefix + (id,) event = module.get_event(node.get('ref')) event.add_opcode(node.get('number'), na...
(id,) error = Error(name, node) error.add_opcode(node.get('number'), name, True) module.add_error(id, name, error) def errorcopy(node, module, namespace): id = node.get('name') name = namespace.prefix + (id,) error = module.get_error(node.get('ref')) error.add_opcode(node.get('number'), na...
allenlavoie/tensorflow
tensorflow/python/ops/image_ops.py
Python
apache-2.0
2,576
0
# 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...
press or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== #
pylint: disable=g-short-docstring-punctuation """Image processing and decoding ops. See the @{$python/image} guide. @@decode_bmp @@decode_gif @@decode_jpeg @@decode_and_crop_jpeg @@encode_jpeg @@extract_jpeg_shape @@decode_png @@encode_png @@is_jpeg @@decode_image @@resize_images @@resize_area @@resize_bicubic @@resi...
YoannDupont/SEM
sem/__main__.py
Python
mit
3,899
0.002565
#!/usr/bin/python # -*- coding: utf-8 -*- """ file: __main__.py Description: the entry point to SEM. author: Yoann Dupont MIT License Copyright (c) 2018 Yoann Dupont Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), t...
ogging.getLogger("sem") def valid_module(m): return m.endswith(".py") and not (m.startswith(u"_") or m in ["sem_module.py", "pipeline.py"]) def main(args=None): def banter(): def username(): import os return os.environ.get("USERNAME", os.environ.get(
"USER", os.path.split(os.path.expanduser(u"~"))[-1])) import random l = [ u"Do thou mockest me?", u"Try again?", u"I'm sorry {0}, I'm afraid I can't do that.".format(username()), u'The greatest trick this module ever pulled what convincing the users it did...
googleapis/python-bigquery-storage
google/cloud/bigquery_storage_v1beta2/services/big_query_write/async_client.py
Python
apache-2.0
35,099
0.001368
# -*- coding: utf-8 -*- # Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
the default one; otherwise the client cert source is None. The API endpoint is determined in the following order: (1) if `client_options.api_endpoint` if provided, use the provided one. (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the default ...
dpoint; if the environment variabel is "never", use the default API endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise use the default API endpoint. More details can be found at https://google.aip.dev/auth/4114. Args: client_options (...
EdinburghGenomics/clarity_scripts
scripts/assign_workflow_finance.py
Python
mit
719
0.004172
#!/usr/bin/env python from EPPs.common import StepEPP, get_workflow_stage class Assign
WorkflowFinance(StepEPP): # All samples for the artifacts in the step will be queued to finance workflow def _run(self): artifacts_to_route = set() for art in self.artifacts: sample = art.samples[0] artifacts_to_route.add(sample.artifact) if artifacts_to_route: ...
self.lims.route_artifacts(list(artifacts_to_route), stage_uri=stage.uri) if __name__ == "__main__": AssignWorkflowFinance().run()
tkchafin/scripts
fastaFormatter.py
Python
gpl-3.0
3,828
0.049373
#!/usr/bin/python import sys import os import getopt from textwrap import wrap def main(): params = parseArgs() if params.many2one: seqs=dict() for f in read_fasta(params.many2one): seqs[f[0]] = f[1] write_fasta(params.out, seqs) elif params.one2many: seqs=dict() for f in read_fasta(params.one2many)...
== ">": #Found a header line #If we already loaded a contig, yield that contig and #start loading a new one if contig: yield([contig,seq]) #yield contig = "" #reset contig and seq seq = "" split_line = line.split() contig = (split_line[0].replace(">","")) else: ...
if contig and seq: yield([contig,seq]) except IOError: print("Could not read file ",fas) sys.exit(1) finally: fh.close() else: raise FileNotFoundError("File %s not found!"%fas) #Object to parse command-line arguments class parseArgs(): def __init__(self): #Define options try: options...
vnevoa/DiffTrike
SoapBox/sb_motor_njay.py
Python
gpl-3.0
8,501
0.030585
# # Copyright 2011 Vasco Nevoa. # # This file is part of DiffTrike. # # DiffTrike 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...
g mR = I2CMotorBridge('RIGHT', '/dev/i2c-1', 0x23, True) mRok = mR.ongoing pmin = -int(MAX_PWM/2) pmax = int(MAX_PWM/2) while mLok or mRok: for i in range(0, pmax+1) + range(pmin, 1): #print "Setting power = %d%%" % (100 * i/MA...
if mLok: mL.setPower(i/MAX_PWM) if mRok: mR.setPower(i/MAX_PWM) #if mLok: print "LEFT P %3d%%, B.T %3d, M.T %3d, I %2.1f A, U %2.1f V" % (mL.power*100, mL.getTemperature(), mL.getMotorTemperature(), mL.getCurrent(), mL.getVoltage()) ...
koery/win-sublime
Data/Packages/Package Control/package_control/package_renamer.py
Python
mit
5,516
0.003626
import os import time import sublime from .console_write import console_write from .package_disabler import PackageDisabler from .settings import pc_settings_filename, load_list_setting, save_list_setting class PackageRenamer(PackageDisabler): """ Class to handle renaming packages via the renamed_packages s...
tings_filename() settings = sublime.load_settings(filename) save_list_setting(settings, filename, 'installed_packages', installed_packages, s
elf.original_installed_packages)
Schevo/kiwi
examples/framework/hey/heyglade.py
Python
lgpl-2.1
194
0
#!/usr/bin/env python import gtk from kiwi.ui.gadgets import quit_if_last from kiwi.ui.views import BaseView app = BaseView(gladefile="hey", delete_handler
=quit_if_last) app.show() gtk.main()
TomasHofman/did
tests/test_did.py
Python
gpl-2.0
1,194
0.001675
# coding: utf-8 """ Tests for the command line script """ from __future__ import unicode_literals, absolute_import import os import re import did.cli import did.utils # Prepare path and config examples PATH = os.path.dirname(os.path.realpath(__file__)) MINIMAL = did.base.Config.example() EXAMPLE = "".join(open(PATH ...
~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~ def test_help_example(): """ Help message with example config """ did.base.Config(config=EXAMPLE) try: did.cli.main(["--help"]) except SystemExit: pass
callowayproject/django-viewpoint
viewpoint/syndication/blogger/urls.py
Python
apache-2.0
2,338
0.003849
# -*- coding: utf-8 -*- """Urls used in blogger API handling. :Authors: - Bruce Kroeze """ """ New BSD License =============== Copyright (c) 2008, Bruce Kroeze http://solidsitesolutions.com All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provide...
Solutions LLC, Zefamily LLC nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR I
MPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED ...
jantman/rebuildbot
rebuildbot/travis.py
Python
agpl-3.0
10,259
0.00039
""" rebuildbot/travis.py Wrapper around travispy The latest version of this package is available at: <https://github.com/jantman/rebuildbot> ################################################################################ Copyright 2015 Jason Antman <jason@jasonantman.com> <http://www.jasonantman.com> This file...
TravisPy.github_auth(github_token) self.user = self.travis.user() logger.debug("Authenticated to TravisCI as %s <%s> (user ID %s)", self.user.login, self.user.email, self.user.id) def get_repos(self, date_check=True): """ Return a list of all repo names for the ...
turn repos with a last build more than 24 hours ago. This only returns repos with a slug (<user_or_org>/<repo_name>) that begins with the user login; it ignores organization repos or repos that the user is a collaborator on. :param date_check: whether or not to only return repo...
johncosta/private-readthedocs.org
readthedocs/builds/urls.py
Python
mit
741
0.009447
from django.conf.urls.defaults import * urlpatterns = patterns('builds.views', url(r'^$', 'build_list', name='builds_list' ),
url(r'^(?P<project_slug>[-\w]+)/(?P<pk>\d+)/$', 'build_detail', name='builds_detail' ),
url(r'^(?P<username>\w+)/(?P<project_slug>[-\w]+)/(?P<pk>\d+)/$', 'legacy_build_detail', name='legacy_builds_detail' ), url(r'^(?P<project_slug>[-\w]+)/$', 'build_list', name='builds_project_list' ), url(r'^(?P<username>\w+)/(?P<project_slug>[-\w]+)/$', 'legacy_bu...
bnsantos/python-junk-code
tests/lists/linkedListTest.py
Python
gpl-2.0
4,159
0.00024
__author__ = 'bruno' import unittest import algorithms.lists.linkedList as LinkedList class TestLinkedList(unittest.TestCase): def setUp(self): pass def test_linked_list_1(self): linked_list = LinkedList.LinkedList(LinkedList.Element(5)) linked_list.add(LinkedList.Element(4)) ...
for i in range(300, 500):
self.assertEqual(True, linked_list.remove(0)) self.assertEqual(0, linked_list.count()) def test_linked_list_9(self): linked_list = LinkedList.LinkedList(LinkedList.Element(0)) for i in range(1, 500): linked_list.add(LinkedList.Element(i)) self.assertEqual(500, link...
IlyaDjurin/django-shop
shop/migrations/0010_auto_20170325_1640.py
Python
mit
729
0.001372
# -*- coding: utf-8 -*- # Generated by Django 1.10.6 on 2017-03-25 13:40 from __future__ import unicode_literals from django.db import migrations, models import django.utils.timezone class Migration(migratio
ns.Migration): dependencies = [ ('shop', '0009_auto_20170325_1625'), ] operations = [ migrations.AddField( model_name='tovar_img', name='tovar
_created', field=models.DateTimeField(auto_now_add=True, default=django.utils.timezone.now), preserve_default=False, ), migrations.AddField( model_name='tovar_img', name='tovar_updated', field=models.DateTimeField(auto_now=True), ), ...
fstagni/DIRAC
tests/Integration/AccountingSystem/Test_DataStoreClient.py
Python
gpl-3.0
1,561
0.019859
""" This is a test of the chain DataStoreClient -> DataStoreHandler -> AccountingDB It supposes that the DB is present, and that the service is running this is pytest! """ # pylint: disable=invalid-name,wrong-import-position from DIRAC.Core.Base.Script import parseCommandLine parseCommandLine() from DI...
ingDict) return oDataOperation def test_addAndRemove(): # just inserting one record record = createAccountingRecord() record.setStartTime()
record.setEndTime() res = gDataStoreClient.addRegister(record) assert res['OK'] res = gDataStoreClient.commit() assert res['OK'] # now removing that record res = gDataStoreClient.remove(record) assert res['OK']
kdimitrov92/Portfolio
portfolio/portfolio/views/comments.py
Python
gpl-2.0
789
0
from django.shortcuts import redirect from portfolio.models.comments import PhotoComment from portfolio.mod
els.photos import Photo from portfolio.views.base import AuthenticatedView class CommentPhotoView(AuthenticatedView): """ View that handles commenting on a photo """ def post(self, request): comment_content = request.POST.get('comment', '') photo = request.POST.get('photo', 0) if comme...
) comment.save() if not photo: return redirect('portfolio.home') return redirect('portfolio.photo.view', photo_id=photo)
mail-apps/translate
translate/misc/optrecurse.py
Python
gpl-2.0
32,292
0.002044
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2002-2006 Zuza Software Foundation # # This file is part of translate. # # translate is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2...
sting one of the same short name if neccessary...""" for short_opt in option._short_opts: if self.has_option(short_opt): self.remove_option(short_opt) for long_op
t in option._long_opts: if self.has_option(long_opt): self.remove_option(long_opt) self.add_option(option)
lmregus/Portfolio
python/design_patterns/env/lib/python3.7/site-packages/flake8/plugins/manager.py
Python
mit
17,752
0
"""Plugin loading and management logic and classes.""" import logging import sys import entrypoints from flake8 import exceptions from flake8 import utils if sys.version_info >= (3, 3): import collections.abc as collections_abc else: import collections as collections_abc LOG = logging.getLogger(__name__) _...
"plugin": self.plugin, "plugin_name": self
.plugin_name, } def is_in_a_group(self): """Determine if this plugin is in a group. :returns: True if the plugin is in a group, otherwise False. :rtype: bool """ return self.group() is not None def group(self): """Find and parse ...
google-research/google-research
tf3d/object_detection/box_utils/np_box_list_ops.py
Python
apache-2.0
21,691
0.006454
# coding=utf-8 # Copyright 2022 The Google Research 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 applicab...
tion_matrix() boxlist2_
rotation_matrix = boxlist2.get_rotation_matrix() if (boxlist1_rotation_matrix is not None) and (boxlist2_rotation_matrix is not None): return np_box_ops.iov3d_9dof_box( boxes1_length=boxlist1.get_length(), boxes1_height=boxlist1.get_height(), ...
ppyordanov/HCI_4_Future_Cities
Server/src/virtualenv/Lib/site-packages/pip/download.py
Python
mit
22,573
0.000487
import cgi import email.utils import hashlib import getpass import mimetypes import os import platform import re import shutil import sys import tempfile import pip from pip.backwardcompat import urllib, urlparse, raw_input from pip.exceptions import InstallationError, HashMismatch from pip.util import (splitext, rmt...
only care about 401 responses, anything else we want to just # pass through the actual response if resp.status_code != 401: return resp # We are not able to prompt the user so simple return the response if not self.prompting: return resp parsed = urlpar...
ed.netloc) password = getpass.getpass("Password: ") # Store the new username and password to use for future requests if username or password: self.passwords[parsed.netloc] = (username, password) # Consume content and release the original connection to allow our new ...
Blazemeter/taurus
tests/unit/modules/test_SoapUI.py
Python
apache-2.0
7,842
0.00204
from bzt.utils import SoapUIScriptConverter from tests.unit import BZTestCase, RESOURCES_DIR, ROOT_LOGGER class TestSoapUIConverter(BZTestCase): def test_minimal(self): obj = SoapUIScriptConverter(ROOT_LOGGER) config = obj.convert_script(RESOURCES_DIR + "soapui/project.xml") self.assertIn...
.assertIn("something", third_req["extract-jsonpath"]) self.assertEqual("$.baz", third_req["extract-jsonpath"]["something"]["jsonpath"]) def test_find_test_case(self): obj = SoapUIScriptConverter(ROOT_LOGGER) config = obj.convert_script(RESOURCES_DIR + "soapui/project.xml") scenario...
ase("index", scenarios) self.assertEqual(target_scenario, found_scenario) def test_find_test_case_empty(self): obj = SoapUIScriptConverter(ROOT_LOGGER) self.sniff_log(obj.log) config = obj.convert_script(RESOURCES_DIR + "soapui/project.xml") scenarios = config["scenarios"]...
kareemallen/beets
beetsplug/lastimport.py
Python
mit
6,738
0
# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Rafael Bodill http://github.com/rafi # # 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 #...
('title', title) ]) song = lib.items(query).get() if song: count = int(song.get('play_count', 0)) new_count = int(tracks[num]['playcount']) log.debug(u'match: {0} - {1} ({2}) ' u'updating: play_count {3} => {4}', ...
song['play_count'] = new_count song.store() total_found += 1 else: total_fails += 1 log.info(u' - No match: {0} - {1} ({2})', artist, title, album) if total_fails > 0: log.info('Acquired {0}/{1} play-counts ({2} unknown)', ...
JazzeYoung/VeryDeepAutoEncoder
theano/sparse/tests/test_basic.py
Python
bsd-3-clause
119,627
0.000594
from __future__ import absolute_import, print_function, division from itertools import product import time import unittest from nose.plugins.skip import SkipTest import numpy from six.moves import xrange try: import scipy.sparse as sp import scipy.sparse from scipy.sparse import csr_matrix except ImportErr...
ices: when True, we make sure there is unsorted indices in the returned sparse matrix. :return: (variable, data) where both `variable` and `data` are list. :note: explicit_zero and unsorted_indices was ad
ded in Theano 0.6rc4 """ if out_dtype is None: out_dtype = theano.config.floatX assert 0 <= p <= 1 assert len(shape) == 2 assert out_dtype in sparse.all_dtypes assert gap is None or isinstance(gap, (tuple, list)) if gap is not None and out_dtype.startswith('u'): assert gap[...
mitodl/lore
roles/tests/test_utils.py
Python
agpl-3.0
2,672
0
""" Test the roles utils """ from __future__ import unicode_literals from django.contrib.auth.models import Group from django.core.management import call_command from django.utils.text import slugify from guardian.shortcuts import get_perms from mock import patch from learningresources.api import create_repo from le...
""" def __init__(self, *args, **kwargs): super(TestRoleUtils, self).__init__(*args, **kwargs) self.repo_name = 'my little+test repo' self.repo_desc = 'test description' self.repo_slug = slugify(self.repo_name) self.group_admin = GroupTypes.REPO_ADMINISTRATOR.format(self.repo...
t(self.repo_slug) def check_group_permission(self, repo, group, expected_permissions): """ helper function """ self.assertListEqual( sorted(get_perms(group, repo)), sorted(expected_permissions) ) def test_sync_permissions(self): """ ...
Youwotma/splash
splash/exceptions.py
Python
bsd-3-clause
1,502
0.000666
# -*- coding:
utf-8 -*- from __future__ import absolute_import class BadOption(Exception): """ Incorrect HTTP API arguments """ pass class RenderError(Exception): """ Error rendering page """ pass class InternalError(Exception): """ Unhandled internal error """ pass class GlobalTimeoutError(Exception)...
nsupportedContentType(Exception): """ Request Content-Type is not supported """ pass class ExpiredArguments(Exception): """ Arguments stored with ``save_args`` are expired """ pass class ScriptError(BadOption): """ Error happened while executing Lua script """ LUA_INIT_ERROR = 'LUA_INIT_ERRO...
favien/favien
favien/canvas.py
Python
agpl-3.0
3,524
0.001419
""":mod:`favien.canvas` --- Canvas ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ """ import boto3 from botocore.client import Config from flask import current_app from sqlalchemy.orm import deferred, dynamic_loader, relationship from sqlalchemy.schema import Column, ForeignKey from sqlalchemy.sql.functions import now from sqlalc...
Collaboration', cascade='all, delete-orphan') #: (:class:`sqlalchemy.types.String`) Canvas title. title = Column(UnicodeText) #: (:class:`sqlalchemy.types.UnicodeText`) The description of the canvas. description = Column(UnicodeText) #: (:class:`sqlalchemy.dialects.postgres.JSON`) C
anvas brush strokes. strokes = deferred(Column(JSONB)) #: (:class:`sqlalchemy.types.Integer`) Canvas width in pixels. width = Column(Integer, nullable=False) #: (:class:`sqlalchemy.types.Integer`) Canvas height in pixels. height = Column(Integer, nullable=False) #: (:class:`sqlalchemy.types.B...
trb/Multicache
cache.py
Python
bsd-2-clause
5,341
0.001311
from types import FunctionType import backends __storage = backends.default() def set_storage(BackendInstance): global __storage __storage = BackendInstance def make_cached(make_key, f): def cached(*args, **kwargs): cache_key = make_key(args=args, kwargs=kwargs) if __storage...
e" + " instance") provider_function = __next_provider __next_provider = None old_init = cls.__init__ def new_init(self, *args, **kwargs): self.__in_init = True old_init(self, *args, **kwargs) self.__in_init = False ...
self, provider_function) cls.__init__ = new_init old_getattribute = cls.__getattribute__ def new_getattribute(self, key): if key != '__dict__' and key != '__cached__': if __should_do_queue(self): __do_queue() if ha...
InScience/DAMIS-old
src/damis/migrations/0039_auto__chg_field_parametervalue_value.py
Python
agpl-3.0
11,165
0.007613
# -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Changing field 'ParameterValue.value' db.alter_column(u'damis_paramete...
d', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyTo
ManyField', [], {'to': u"orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ('django.db.models.fields.Boo...
n9code/calm
tests/test_param.py
Python
mit
1,276
0
from unittest import TestCase from calm.param import ParameterJsonType class CodecTests(TestCase): def test_param_json_type(self): pjt = ParameterJsonType.from_python_type(int) self.assertEqual(pjt, 'integer') pjt = ParameterJsonType.from_python_type(float) self.a
ssertEqual(pjt, 'number') pjt = ParameterJsonType.from_python_type(str) self.assertEqual(pjt, 'string') pjt = ParameterJsonType.from_python_type(bool) self.assertEqual(pjt, 'boole
an') pjt = ParameterJsonType.from_python_type([bool]) self.assertEqual(pjt, 'array') self.assertEqual(pjt.params['items'], 'boolean') class CustomType(str): pass pjt = ParameterJsonType.from_python_type(CustomType) self.assertEqual(pjt, 'string') def t...
luzfcb/django-autocomplete-light
test_project/select2_tagging/urls.py
Python
mit
295
0
from dal import autocomplete from d
jango.conf.urls import url from tagging.models import Tag urlpatterns = [ url( 'test-autocomplete/$', autocomplete.Select2QuerySetView.as_view( q
ueryset=Tag.objects.all(), ), name='select2_tagging', ), ]
xanthics/gw2crafting---retired
Crafting.py
Python
mit
21,884
0.040121
#!/usr/bin/env python ''' Copyright (c) 2012 Jeremy Parks ( xanthic.9478 ) 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...
thread.start() q.put(thread,True) def consumer(q): num = 1 den = 0 for tier in recipeDict: den += len(recipeDict[tier]) while num <= den: thread = q.get(True) thread.join() tmp = thread.get_result() items.setdefault(tmp['result']['tier'],{})
items[tmp['result']['tier']].setdefault(tmp['result']['sub_type'],{}) items[tmp['result']['tier']][tmp['result']['sub_type']]['name'] = tmp['result']['name'] items[tmp['result']['tier']][tmp['result']['sub_type']]['cost'] = tmp['result']['min_sale_unit_price'] items[tmp['result']['tier']][tmp['result']['sub_...
voidfiles/lark
lark/ext/utils.py
Python
mit
800
0.0025
import datetime import json import random import string class RedisApiException(Exception): def __init__(self, message, status_code, *args, **kwargs): super(RedisApiException, self).__init__(message) self.status_code = status_code class DateTimeJSONEncoder(json.JSONEncoder): def default(sel...
return obj.isoformat()
if isinstance(obj, set): return list(obj) if obj and hasattr(obj, 'to_json'): obj = obj.to_json() return super(DateTimeJSONEncoder, self).default(obj) json_dumps = DateTimeJSONEncoder() def generate_random_string(length=13, chars=string.ascii_letters + string.digits, )...
dtroyer/python-openstacksdk
openstack/cloud/_network.py
Python
apache-2.0
104,230
0
# 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...
ess or imp
lied. # See the License for the specific language governing permissions and # limitations under the License. # import types so that we can reference ListType in sphinx param declarations. # We can't just use list, because sphinx gets confused by # openstack.resource.Resource.list and openstack.resource2.Resource.list ...
SkippsDev/Py-Slither
src/packet/BufferTypes.py
Python
mit
442
0.002262
import struct boolean = struct.Struct("<?") uint8 = struct.Struct("<B") uint16 = struct.Struct("<H") uint32 = s
truct.Struct("<I") uint64 = struct.Struct("<Q") int8 = struct.
Struct("<b") int16 = struct.Struct("<h") int24 = struct.Struct("<L") int32 = struct.Struct("<i") int64 = struct.Struct("<q") float32 = struct.Struct("<f") float64 = struct.Struct("<d") string = struct.Struct("<s") uoffset = uint32 soffset = int32 voffset = uint16
anhstudios/swganh
data/scripts/templates/object/tangible/ship/components/weapon/shared_wpn_rss_imperial_cannon.py
Python
mit
491
0.044807
#### NOTICE: THIS FILE IS AUTOGENERATED #### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY #### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES from swgpy.obj
ect import * def create(kernel): result = Tangible() result.template = "object/tangible/ship/components/weapon/shared_wpn_rss_imperial_cannon.iff" result.attribute_template_id = 8 result.stfName("space/space_item","wpn_rss_imperial_cannon_n") ###
# BEGIN MODIFICATIONS #### #### END MODIFICATIONS #### return result
kscharding/integral-solutions-smxq
codereview/urls.py
Python
apache-2.0
3,897
0.00077
# Copyright 2008 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, ...
tware # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, eith
er express or implied. # See the License for the specific language governing permissions and # limitations under the License. """URL mappings for the codereview package.""" # NOTE: Must import *, since Django looks for things here, e.g. handler500. from django.conf.urls.defaults import * import django.views.defaults ...
forcedotcom/distributions
distributions/util.py
Python
bsd-3-clause
7,375
0.000271
# Copyright (c) 2014, Salesforce.com, 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 code must retain the above copyright # notice, this list of conditions...
100, 'WARNING imprecision; use more samples' pairs = zip(samples
, probs) pairs.sort() samples = numpy.array([x for x, p in pairs]) probs = numpy.array([p for x, p in pairs]) density = numpy.sqrt(probs[1:] * probs[:-1]) gaps = samples[1:] - samples[:-1] unif01_samples = 1.0 - numpy.exp(-len(samples) * gaps * density) return unif01_goodness_of_fit(unif01_s...