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
Kraymer/keroaek
keroaek/vlc.py
Python
mit
292,112
0.005402
#! /usr/bin/python # Python ctypes bindings for VLC # # Copyright (C) 2009-2012 the VideoLAN team # $Id: $ # # Authors: Olivier Aubert <contact at olivieraubert.net> # Jean Brouwers <MrJean1 at gmail.com> # Geoff Salmon <geoff.salmon at gmail.com> # # This library is free software; you can redistribu...
et__(self, obj, objtype): """Support instance methods. """ retur
n functools.partial(self.__call__, obj) # Default instance. It is used to instanciate classes directly in the # OO-wrapper. _default_instance = None def get_default_instance(): """Return the default VLC.Instance. """ global _default_instance if _default_instance is None: _default_instance = In...
sebastienbarbier/723e_server
seven23/models/accounts/migrations/0002_auto_20161128_1335.py
Python
mit
1,974
0.003546
# -*- coding: utf-8 -*- # Generated by Django 1.10.1 on 2016-11-28 13:35 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_depende...
model_name='accountrules', name='user', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL), ), migrations.AddField( model_name='account', name='users', field=models.ManyToManyField(relat...
), ]
antong/ldaptor
ldaptor/test/test_server.py
Python
lgpl-2.1
24,613
0.008451
""" Test cases for ldaptor.protocols.ldap.ldapserver module. """ from twisted.trial import unittest import sets, base64 from twisted.internet import protocol, address from twisted.python import components from ldaptor import inmemory, interfaces, schema, delta, entry from ldaptor.protocols.ldap import ldapserver, ldap...
ltCode=ldaperrors.LDAPNoSuchObject.resultCode), id=2)),
) def test_search_matchAll_oneResult(self): self.server.dataReceived(str(pureldap.LDAPMessage( pureldap.LDAPSearchRequest( baseObject='cn=thingie,ou=stuff,dc=example,dc=com', ), id=2))) self.assertEquals(self.server.transport.value(), ...
flgiordano/netcash
+/google-cloud-sdk/lib/surface/logging/sinks/update.py
Python
bsd-3-clause
7,511
0.003595
# Copyright 2014 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 ag...
if args.service: result = util.TypedLogSink(self.UpdateLogServiceSink(sink_data), service_name=args.service) else: if args.output_version_format: sink_data['outputVersionFormat'] = args.output_version_format else: sink_data['outputVersionFormat'] = ...
ef) return result def Display(self, unused_args, result): """This method is called to print the result of the Run() method. Args: unused_args: The arguments that command was run with. result: The value returned from the Run() method. """ list_printer.PrintResourceList('logging.typedS...
j2sol/ansible
plugins/inventory/yaml.py
Python
gpl-3.0
7,145
0.003779
#!/usr/bin/env python # Support a YAML file hosts.yml as external inventory in Ansible # Copyright (C) 2012 Jeroen Hoekx <jeroen@hoekx.be> # # 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, eit...
for test_host in all_hosts.get_h
osts(): ### all hosts contains only hosts already in groups if test_host.name == entry['host']: host = test_host break else: host = Host(entry['host']) all_hosts.add_host(host) no_group = ...
rzarzynski/tempest
tempest/api/compute/admin/test_aggregates.py
Python
apache-2.0
10,395
0
# Copyright 2013 NEC Corporation. # 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...
otIn(self.ho
st, body['hosts']) @test.attr(type='gate') @test.idempotent_id('7f6a1cc5-2446-4cdb-9baa-b6ae0a919b72') def test_aggregate_add_host_list(self): # Add an host to the given aggregate and list. self.useFixture(fixtures.LockFixture('availability_zone')) aggregate_name = data_utils.rand_n...
mitmedialab/MediaCloud-Web-Tools
server/views/topics/__init__.py
Python
apache-2.0
3,391
0.002359
import logging import datetime import mediacloud.api import re from server import mc from server.auth import is_user_logged_in from server.util.csv import SOURCE_LIST_CSV_METADATA_PROPS logger = logging.getLogger(__name__) TOPIC_MEDIA_INFO_PROPS = ['media_id', 'name', 'url'] TOPIC_MEDIA_PROPS = ['story_count', 'me...
if len(media_ids) > 0 and len(tags_ids) > 0: query += " OR " # add in the collections they specified if len(tags_ids) > 0:
tags_ids = tags_ids.split(',') if isinstance(tags_ids, str) else tags_ids query_tags_ids = " ".join(map(str, tags_ids)) query_tags_ids = re.sub(r'\[*\]*', '', str(query_tags_ids)) query_tags_ids = " tags_id_media:({})".format(query_tags_ids) query += '(' + query_tag...
izadorozhna/tempest
tempest/tests/cmd/test_javelin.py
Python
apache-2.0
18,257
0
#!/usr/bin/env python # # 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 ...
cked_function.assert_called_once_with(self.fake_object['container']) mocked_function = self.fake_client.objects.create_object mocked_function.assert_called_once_with(self.fake_object['container'], self.fake_object['name'], ...
self.fake_client.images.create_image.return_value = \ self.fake_object['body'] self.useFixture(mockpatch.PatchObject(javelin, "client_for_user", return_value=self.fake_client)) self.useFixture(mockpatch.PatchObject(javelin, "_get_image_by_name...
pycontw/pycontw2016
src/sponsors/migrations/0013_auto_20180305_1339.py
Python
mit
624
0.001603
# -*- coding: utf-8 -*- # Generated by Django 1.10.4 on 2018-03-05
05:39 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('sponsors', '0012_sponsor_level_smallint'), ] operations = [ migrations.AlterField( model_name='sponsor', name='confere...
odels.SlugField(choices=[('pycontw-2016', 'PyCon Taiwan 2016'), ('pycontw-2017', 'PyCon Taiwan 2017'), ('pycontw-2018', 'PyCon Taiwan 2018')], default='pycontw-2018', verbose_name='conference'), ), ]
nielsbuwen/ilastik
tests/launch_workflow.py
Python
gpl-3.0
4,466
0.008509
############################################################################### # ilastik: interactive learning and segmentation toolkit # # Copyright (C) 2011-2014, the ilastik developers # <team@ilastik.org> # # This program is free software; you can redistribute it and/or # mod...
tik.org/license.html ############################################################################### import sys from functools import partial fro
m PyQt4.QtGui import QApplication import threading # This function was copied from: http://bugs.python.org/issue1230540 # It is necessary because sys.excepthook doesn't work for unhandled exceptions in other threads. def install_thread_excepthook(): """ Workaround for sys.excepthook thread bug (https://sou...
surajshanbhag/Indoor_SLAM
src/control/piControl/encoderRun.py
Python
gpl-3.0
1,623
0.021565
from __future__ import division import encoder import socket_class as socket import threading import time import sys rightC,leftC = (0,0) s = None IP = "10.42.0.1" host = 50679 class sendData(threading.Thread): def __init__(self,waitTime): self.waitTime = waitTime threading.Thread.__init__(self) ...
__main__": """if 2 arguments are passed in overwrite IP and port number to those values else u
se IP = 10.42.0.1 and 50679""" encoder.encoderSetup() if len(sys.argv) in (1,3): checkArgs() s = socket.initSocket() while True: try: socket.connect(s,IP,host) break except: pass #start thread to sen...
jzbontar/orange-tree
Orange/classification/linear_regression.py
Python
gpl-3.0
4,108
0.000974
import numpy
as np import scipy.sparse as sp from scipy.optimize import fmin_l_bfgs_b from Orange.classification import Learner, Model __all__ = ["Lin
earRegressionLearner"] class LinearRegressionLearner(Learner): def __init__(self, lambda_=1.0, preprocessors=None, **fmin_args): '''L2 regularized linear regression (a.k.a Ridge regression) This model uses the L-BFGS algorithm to minimize the linear least squares penalty with L2 regulariz...
clifforloff/opmservice
opmapp/tests.py
Python
gpl-2.0
24,082
0.008139
""" Test for opmapp application. """ # from python import datetime # from selenium from selenium.webdriver.firefox.webdriver import WebDriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import Select from selenium.common.exceptions import NoSuchElementException from django.test i...
driver.find_element_by_id("id_end_date").send_keys("2012-12-31") Select(driver.find_element_by_id("id_unit")).select_by_visible_text("5209 CV") driver.find_element_by_id("id_permanent_address1").clear() driver.find_element_by_id("id_permanent_address1").send_keys("1220 Montg
omery St.") driver.find_element_by_id("id_permanent_address2").clear() driver.find_element_by_id("id_permanent_address2").send_keys("1995 Shattuck St.") driver.find_element_by_id("id_permanent_city").clear() driver.find_element_by_id("i
igorgue/zeromqlogs
docs/conf.py
Python
mit
7,723
0.00764
# -*- coding: utf-8 -*- # # sample documentation build configuration file, created by # sphinx-quickstart on Mon Apr 16 21:22:43 2012. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All ...
efault_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = T
rue # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlig...
robotii/notemeister
src/lib/Note.py
Python
gpl-2.0
439
0.029613
#!/usr/bin/env python import gtk #import NoteBuffer import notemeister class Note: def __init__(self, path=None, title='', body='', link='', wrap="1"): self.path = path self.title = title self.
body = body self.link = link self.wrap = wrap self.buffer = notemeister.NoteBuffer.NoteBuffer() self.buffer.set_text(self.body) def
__str__(self): return '(%d) Note "%s" has body: %s' % (self.index, self.title, self.body)
orwell-int/agent-server-game-python
setup.py
Python
bsd-3-clause
1,239
0.000807
#!/usr/bin/env python import setuptools # Hack to prevent stupid TypeError: 'NoneType' object is not callable error on # exit of python setup.py test # in multiprocessing/
util.py _exit_function when # running python setup.py test (see # http://www.eby-sarna.com/pipermail/peak/2010-May/003357.html) try: import multiprocessing assert multiprocessing except ImportError: pass setuptools.s
etup( name='orwell.agent', version='0.0.1', description='Agent connecting to the game server.', author='', author_email='', packages=setuptools.find_packages(exclude="test"), test_suite='nose.collector', install_requires=['pyzmq', 'cliff'], tests_require=['nose', 'coverage',...
oilshell/blog-code
fd-passing/py_fanos_test.py
Python
apache-2.0
2,191
0.01141
#!/usr/bin/env python3 """ py_fanos_test.py: Tests for py_fanos.py """ import socket import sys import unittest import py_fanos # module under test class FanosTest(unittest.TestCase): def testSendReceive(self): left, right = socket.socketpair() py_fanos.send(left, b'foo') fd_out = [] msg = py_f...
len(fd_out)) print(fd_out) left.close() msg = py_fanos.recv(right) self.assertEqual(None, msg) # Valid EOF right.close() class InvalidMessageTests(unittest.TestCase): """COPIED to native/fanos_test.py.""" def testInvalidColon(self): left, right = socket.socketpair() left.send(b':'...
oo, try: msg = py_fanos.recv(right) except ValueError as e: print(type(e)) print(e) else: self.fail('Expected failure') left.close() right.close() def testInvalidDigits(self): left, right = socket.socketpair() left.send(b'34') # EOF in the middle of length l...
sniperganso/python-manilaclient
manilaclient/v2/share_snapshots.py
Python
apache-2.0
6,363
0
# Copyright 2012 NetApp # 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 applic...
e, 'name': name, 'description': description}} return s
elf._create('/snapshots', body, 'snapshot') def get(self, snapshot): """Get a snapshot. :param snapshot: The :class:`ShareSnapshot` instance or string with ID of snapshot to delete. :rtype: :class:`ShareSnapshot` """ snapshot_id = common_base.getid(snapshot) ...
cmcerove/pyvxl
pyvxl/tests/run.py
Python
mit
884
0.002262
#!/usr/bin/env python """Run pytest with coverage and generate an html report.""" from sys import argv from os import system as run # To run a spec
ific file with debug logging prints: # py -3 -m pytest test_can.py --log-cli-format="%(asctime)s.%(msecs)d %(levelname)s: %(message)s (%(filename)s:%(lineno)d)" --log-cli-level=debug def main(): # noqa run_str = 'python -m coverage run --include={} --omit=./* -m pytest {} {}' arg = '' # All source f...
if ':' in argv[1]: includes = argv[1].split('::')[0] other_args = ' '.join(argv[2:]) run(run_str.format(includes, arg, other_args)) # Generate the html coverage report and ignore errors run('python -m coverage html -i') if __name__ == '__main__': main()
iovation/launchkey-python
features/steps/directory_device_steps.py
Python
mit
7,152
0.00028
from uuid import uuid4, UUID from behave import given, when, then from formencode import Invalid, validators @given("I made a Device linking request") @given("I have made a Device linking request") @when("I make a Device linking request") def make_device_linking_request(context): current_directory = context.enti...
ing response contains a valid QR Code URL") def linking_response_contains_
valid_qr_code_url(context): try: validators.URL().to_python( context.entity_manager.get_current_linking_response().qrcode ) except Invalid as e: raise Exception("Could not parse QR Code as URL: %s" % e) @then("the Device linking response contains a valid Linking Code") def ...
handbaggerli/DbInstaller
Python/DbInstaller.py
Python
gpl-3.0
6,513
0.005236
# -*- coding: utf-8 -*- import sys from argparse import ArgumentParser from DatabaseLogin import DatabaseLogin from GlobalInstaller import GlobalInstaller from PyQt5 import QtWidgets from Ui_MainWindow import Ui_MainWindow # import damit Installer funktioniert. auch wenn diese nicht hier benoetigt werd...
_sequence', action='store_true', default=False, help=r"Setzt Flag für die Installation von Sequenzen.") parser.add_argument('--inst_tab_save', action='store_true', default=False, help=r"Setzt Flag für die Installation von Tab Save Tabellen.") parser.add_argume...
rue, help=r"Entfernt Flag für die Installation von Tab Tabellen.") parser.add_argument('--inst_view', action='store_false', default=True, help=r"Entfernt Flag für die Installation von Views.") parser.add_argument('--inst_package', action='store_false', default...
CongLi/avocado-vt
virttest/libvirt_vm.py
Python
gpl-2.0
106,547
0.000319
""" Utility classes and functions to handle Virtual Machine creation using libvirt. :copyright: 2011 Red Hat Inc. """ import time import string import os import logging import fcntl import re import shutil import tempfile import platform import aexpect from avocado.utils import process from avocado.utils import cryp...
= ("://%s/%s" % (dest_ip, transport_uri
_dest)) return ("%s%s" % (transport_uri_driver, transport_uri_dest)) class VM(virt_vm.BaseVM): """ This class handles all basic VM operations for libvirt. """ def __init__(self, name, params, root_dir, address_cache, state=None): """ Initialize the object and set a few attributes...
xHeliotrope/injustice_dropper
env/lib/python3.4/site-packages/django_twilio/settings.py
Python
mit
242
0
#
-*- coding: utf-8 -*- from __future__ import unicode_literals, absolute_import """ django_twilio specific settings. """ from .utils import discover_twilio_credentials TWILIO_ACCOUNT_SID, TWILIO
_AUTH_TOKEN = discover_twilio_credentials()
esc/dask
dask/array/tests/test_ghost.py
Python
bsd-3-clause
9,623
0.009145
import pytest pytest.importorskip('numpy') import numpy as np from numpy.testing import assert_array_almost_equal, assert_array_equal import dask import dask.array as da from dask.array.ghost import (Array, fractional_slice, getitem, trim_internal, ghost_internal, nearest, constant, boun...
arr, {0: 5, 1: 5}) assert_array_almost_equal(tarr, a) def test_0_depth(): expected = np.arange(100).reshape(10, 10) darr = da.from_array(expected, chunks=(5, 2)) depth = {0: 0, 1: 0} reflected = ghost(darr, depth=depth, bound
ary='reflect') nearest = ghost(darr, depth=depth, boundary='nearest') periodic = ghost(darr, depth=depth, boundary='periodic') constant = ghost(darr, depth=depth, boundary=42) result = trim_internal(reflected, depth) assert_array_equal(result, expected) result = trim_internal(nearest, depth) ...
shail2810/nova
nova/tests/unit/virt/vmwareapi/test_vmops.py
Python
apache-2.0
114,813
0.000575
# Copyright 2013 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...
bridge_interface=None, injected=True) s
elf._network_values = { 'id': None, 'address': 'DE:AD:BE:EF:00:00', 'network': network, 'type': None, 'devname': None, 'ovs_interfaceid': None, 'rxtx_cap': 3 } self.network_info = network_model.NetworkInfo([ ...
ESS-LLP/erpnext
erpnext/healthcare/doctype/medication/medication.py
Python
gpl-3.0
2,862
0.025507
# -*- coding: utf-8 -*- # Copyright (c) 2020, Frappe Technologies Pvt. Ltd. and contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe, json from frappe import _ from frappe.model.document import Document from frappe.model.rename_doc import rename_doc clas...
(self): if self.change_in_item: self.update_item_and_item_price() def enable_disable_item(self): if self.is_billable: if self.disabled: frappe.db.set_value('Item', self.item, 'disabled', 1) else: frappe.db.set_value('Item', self.item, 'disabled', 0) def update_item_and_item_price(self): if
self.is_billable and self.item: item_doc = frappe.get_doc('Item', {'item_code': self.item}) item_doc.item_name = self.medication_name item_doc.item_group = self.item_group item_doc.description = self.description item_doc.stock_uom = self.stock_uom item_doc.disabled = 0 item_doc.save(ignore_permiss...
thethomaseffect/travers-media-tools
traversme/encoder/media_object.py
Python
mit
2,000
0
""" TODO: Add docstring """ import re import pexpect class MediaObject(object): """Represents an encodable object""" def __init__(self, input_filename, output_filename): self.input_filename = input_filename self.output_filename = output_filename self.media_duration = self.get_media_d...
y be put here too def get_media_duration(self): """ Spawns an avprobe process to get the media duration. Spawns an avprobe process and saves the output to a list, then uses regex to find the duration of the media and return it as an integer. """ info_process = pexp...
tion: ' followed by # number in form 00:00:00:00 regex_group = re.compile(".*?Duration: .*?(\\d+):(\\d+):(\\d+).(\\d+)", re.IGNORECASE | re.DOTALL) # Exits as soon as duration is found # PERF: Perform some tests to find the min number of lines # c...
shuang1330/tf-faster-rcnn
lib/model/test.py
Python
mit
8,856
0.015583
# -------------------------------------------------------- # Tensorflow Faster R-CNN # Licensed under The MIT License [see LICENSE for details] # Written by Xinlei Chen # -------------------------------------------------------- from __future__ import absolute_import from __future__ import division from __future__ impor...
nds = np.where((x2 > x1) & (y2 > y1) & (scores > cfg.TEST.DET_THRESHOLD))[0] dets = dets[inds,:] if dets == []: continue keep = nms(dets, thresh) if len(keep) == 0: continue nms_boxes[cls_ind][im_ind] = dets[keep, :]
.copy() return nms_boxes def test_net(sess, net, imdb, weights_filename, experiment_setup=None, max_per_image=100, thresh=0.05): np.random.seed(cfg.RNG_SEED) """Test a Fast R-CNN network on an image database.""" num_images = len(imdb.image_index) # num_images = 2 # all detections are collected...
e-gob/plataforma-kioscos-autoatencion
scripts/ansible-play/.venv/lib/python2.7/site-packages/ansible/module_utils/service.py
Python
bsd-3-clause
7,923
0.002398
# This code is part of Ansible, but is an independent component. # This particular file snippet, and this file snippet only, is BSD licensed. # Modules you write using this snippet, which is embedded dynamically by Ansible # still belong to the author of the module, and may assign their own license # to the complete wo...
enting the command and options to run This is complex because daemonization is hard for people. What we do is daemonize a part of this module, the daemon runs the c
ommand, picks up the return code and output, and returns it to the main process. ''' # init some vars chunk = 4096 # FIXME: pass in as arg? errors = 'surrogate_or_strict' # start it! try: pipe = os.pipe() pid = os.fork() except OSError: module.fail_json(msg="Er...
Transkribus/TranskribusDU
TranskribusDU/ObjectModel/XMLDSTEXTClass.py
Python
bsd-3-clause
12,221
0.013504
# -*- coding: utf-8 -*- """ XML object class Hervé Déjean cpy Xerox 2009 a class for TEXT from a XMLDocument """ from __future__ import absolute_import from __future__ import print_function from __future__ import unicode_literals from .XMLDSObjectClass import XMLDSObjectClass from .XMLDS...
def getSetOfListedAttributes(self,TH,lAttributes,myObject): """ Generate a set of features: X start of the lines """ from spm.feature import featureObject if self._lBasicFeatures is None: self._lBasicFeatures = [] # needed t...
tSetofFeatures() != []: return self.getSetofFeatures() lHisto = {} for elt in self.getAllNamedObjects(myObject): for attr in lAttributes: try:lHisto[attr] except KeyError:lHisto[attr] = {} if elt.hasAttribute(attr): ...
fengbohello/practice
python/pdb/sample.py
Python
lgpl-3.0
81
0.037037
def add(x, y): return
x + y x = 0 import pdb; pdb.set_trace() x = ad
d(1, 2)
cloudify-cosmo/cloudify-manager-blueprints
components/manager-ip-setter/scripts/create-internal-ssl-certs.py
Python
apache-2.0
1,346
0
# This script has to run using the Python executable found in: # /opt/mgmtworker/env/bin/python in order to properly load the manager # blueprints utils.py module. import argparse import logging import utils class CtxWithLogger(object): logger = logging.getLogger('internal-ssl-certs-logger') utils.ctx = CtxWi...
parse.ArgumentParser() parser.add_argument('--metadata', default=utils.CERT_METADATA_FILE_PATH, help='File containing the cert metadata. It should be a ' 'JSON file containing an object with the ' '"internal_rest_host" and "networks" fields.') parser...
this machine on the default network') if __name__ == '__main__': args = parser.parse_args() cert_metadata = utils.load_cert_metadata(filename=args.metadata) internal_rest_host = args.manager_ip or cert_metadata['internal_rest_host'] networks = cert_metadata.get('networks', {}) networks['default'] ...
ekumenlabs/terminus
terminus/geometry/enu.py
Python
apache-2.0
1,657
0.002414
""" Copyright (C) 2017 Open Source Robotics Foundation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LI
CENSE-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 CONDIT
IONS 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 as np import latlon import ecef class Enu(object): def __init__(self, e, n, u): self.e = e self.n = n self.u = u ...
benosteen/pairtree
pairtree/pairtree_revlookup.py
Python
apache-2.0
3,270
0.015596
#!/usr/bin/python # -*- coding: utf-8 -*- """ FS Pairtree storage - Reverse lookup ==================================== Conventions used: From http://www.cdlib.org/inside/diglib/pairtree/pairtreespec.html version 0.1 This is an implementation of a reverse lookup index, using the pairtree path spec to record the li...
rl = PairtreeReverseLookup(storage_dir="ROOT") >>> rl["issn:1234-1234"].append("uuid:1e4f...") >>> rl["issn:1234-1234"] ["uuid:1
e4f"] >>> rl["issn:1234-1234"] = ["id:1", "uuid:32fad..."] >>> Notes ===== This was created to avoid certain race conditions I had with a pickled dictionary for this index. A sqllite or similar lookup would also be effective, but this one relies solely on pairtree. """ import os from pairtree.pairtree_path impor...
saltstack/libnacl
doc/conf.py
Python
apache-2.0
10,276
0.007201
# -*- coding: utf-8 -*- # # libnacl documentation build configuration file, created by # sphinx-quickstart on Thu May 29 10:29:25 2014. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # A...
onal_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the
index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown i...
django-danceschool/django-danceschool
danceschool/discounts/migrations/0011_auto_20210127_2052.py
Python
bsd-3-clause
525
0
# Generated by Django 2.2.17 on 2021-01-28 01:52 from django.db import migrations
, models class Migration(migrations.Migration): dependencies = [ ('discounts', '0010_merge_20191028_1925'), ] operations = [ migrations.AddField( model_name='registrationdiscount', name='applied', field=models.BooleanField(null=True, verbose_name='Use ...
tions.DeleteModel( name='TemporaryRegistrationDiscount', ), ]
jsachs/infer
infer/lib/python/inferlib/issues.py
Python
bsd-3-clause
9,001
0.000222
# Copyright (c) 2015 - present Facebook, Inc. # All rights reserved. # # This source code is licensed under the BSD style license found in the # LICENSE file in the root directory of this source tree. An additional grant # of patent rights can be found in the PATENTS file in the same directory. from __future__ import ...
if report[JSON_INDEX_KIND] == ISSUE_KIND_WARNING: msg = colorize.color(msg, colorize.WARNING, formatter) elif report[JSON_INDEX_KIND] == ISSUE_KIND_ADVICE: msg = colorize.color(msg, colorize.ADVICE, formatter) text =
'%s%s' % (msg, source_context) text_errors_list.append(text) error_types_count = {} for report in reports: t = report[JSON_INDEX_TYPE] # assert failures are not very informative without knowing # which assertion failed if t == 'Assert_failure' and JSON_INDEX_INFER_SOURCE...
Azure/azure-sdk-for-python
sdk/network/azure-mgmt-network/azure/mgmt/network/v2019_04_01/aio/operations/_network_security_groups_operations.py
Python
mit
30,870
0.005248
# 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 ...
tion_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return AsyncLROPoller(self._client, r
aw_result, get_long_running_output, polling_method) begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkSecurityGroups/{networkSecurityGroupName}'} # type: ignore async def get( self, resource_group_name: str, ...
arthurdarcet/aiohttp
tools/check_changes.py
Python
apache-2.0
1,224
0
#!/usr/bin/env python3 import sys from pathlib import Path ALLOWED_SUFFIXES = ['.feature', '.bugfix', '.doc', '.removal', '.misc'] def get_root(script_path): folder = script_path.absolute().parent while not (folder / '.git').ex...
/ 'CHANGES' failed = False for fname in changes.iterdir(): if fname.name in ('.gitignore', '.TEMPLATE.rst'): continue if fname.suffix not in ALLOWED_SUFFIXES: if not failed: print('') print(fname, 'has illegal suffix', file=sys.stderr) ...
print('', file=sys.stderr) print('Allowed suffixes are:', ALLOWED_SUFFIXES, file=sys.stderr) print('', file=sys.stderr) else: print('OK') return int(failed) if __name__ == '__main__': sys.exit(main(sys.argv))
aaniin/AliPhysics
PWGMM/MC/aligenqa/aligenqa/roofie/figure.py
Python
bsd-3-clause
20,665
0.002516
import string import random import logging import os from rootpy import asrootpy, log from rootpy.plotting import Legend, Canvas, Pad, Graph from rootpy.plotting.base import Color, MarkerStyle from rootpy.plotting.utils import get_limits import ROOT # from external import husl # suppress some nonsense logging messa...
. This function performs a copy of the passed object and assigns it a random name. Once commited, these should not be touched any more by the user!!! Parameters ---------- obj : Hist1D, Graph, N
one A root plottable object; If none, this object will only show up in the legend legend_title : string Title for this plottable as shown in the legend """ # Make a copy if we got a plottable if obj is not None: p = asrootpy(obj.Clone(gen_random_name()...
ZeitOnline/zeit.redirect
src/zeit/redirect/redirect.py
Python
bsd-3-clause
710
0
from pyramid.httpexceptions import HTTPMovedPerma
nently from pyramid.view import view_config from zeit.redirect.db import Redirect import json @view_config(route_name='redirect', renderer='string') def check_redirect(request): redirect = Redirect.query().filter_by(source=request.path).first() if redirect: # XXX Should we be protocol-relative (https ...
tc.)? raise HTTPMovedPermanently( 'http://' + request.headers['Host'] + redirect.target) else: return '' @view_config(route_name='add', renderer='string', request_method='POST') def add_redirect(request): body = json.loads(request.body) Redirect.add(body['source'], body['target...
Staffjoy/client_python
staffjoy/resources/organization.py
Python
mit
959
0
from staffjoy.resource import Resource from staffjoy.resources.location import Location from staffjoy.resources.admin import Admin from staffjoy.resources.organization_worker import OrganizationWorker class Organization(Resource): PATH = "organizations/{organization_id}" ID_NAME = "organization_id" def g...
n.get(parent=self, id=id) def create_location(self, **kwargs): return Location.create(parent=self, **kwargs) def get_admins(self): return Admin.get_all(parent=self) def get_admin(self, id): return Admin.get(parent=self, id=id) def create_admin(self, **kwargs): """Typi...
rgs)
pnwairfire/fccsmap
setup.py
Python
gpl-3.0
1,292
0.001548
from setuptools import setup, find_packages from fccsmap import __version__ test_requirements = [] with open('requirements-test.txt') as f: test_requirements = [r for r in f.read().splitlines()] setup( name='fccsmap', version=__version__, author='Joel Dubowy', license='GPLv3+', author_email='...
bowy@gmail.com', packages=find_packages(), scripts=[ 'bin/fccsmap' ], package_data={ 'fccsmap': ['data/*.nc'] }, classifiers=[ "Development Status :: 3 - Alpha", "Intended Audience :: Developers",
"License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)", "Programming Language :: Python :: 3.8", "Operating System :: POSIX", "Operating System :: MacOS" ], url='https://github.com/pnwairfire/fccsmap/', description='supports the look-up of FCCS fuelbed inf...
davvi/Hardway3
ex30.py
Python
mit
492
0
#!/usr/bin/env python people = 30 cars = 40 trucks = 15 if cars > people: print("We should take the cars.") elif cars < p
eople: print("We should not take the cars") else: print("We can't decide.") if trucks > cars: print("That's too many trucks.") elif trucks < cars: print("Maybe we coudl take the trucks.") else: print("We still can't dec
ide.") if people > trucks: print("Alright, let's just take the trucks.") else: print("Fine, let's stay home then.")
hkariti/mopidy-youtube
mopidy_youtube/backend.py
Python
apache-2.0
5,359
0.000187
# -*- coding: utf-8 -*- from __future__ import unicode_literals import re import string from urlparse import urlparse, parse_qs from mopidy import backend from mopidy.models import SearchResult, Track, Album, Artist import pykka import pafy import requests import unicodedata from mopidy_youtube import logger yt_api_e...
unicode(uri) ).encode('ASCII', 'ignore')
return re.sub( '\s+', ' ', ''.join(c for c in safe_uri if c in valid_chars) ).strip() def resolve_url(url, stream=False): video = pafy.new(url) if not stream: uri = 'youtube:video/%s.%s' % ( safe_url(video.title), video.videoid ) else: uri = ...
AlanZatarain/pysal
pysal/region/tests/test_maxp.py
Python
bsd-3-clause
1,770
0
import unittest import pysal import numpy as np import random class Test_Maxp(unittest.TestCase): def setUp(self): random.seed(100) np.random.seed(100) def test_Maxp(self): w = pysal.lat2W(10, 10) z = np.random.random_sample((w.n, 2)) p = np.ones((w.n, 1), float) ...
r, floor_variable=p, initial=100) self.assertEquals(solution.p, 29) self.assertEquals(solution.regions[0], [4, 14, 5, 24, 3, 25, 15, 23]) def test_inference(self): w = pysal.weights.lat2W(5, 5) z = np.random.random_sample((w.n, 2)) p = np.ones((w.n, 1), float) floor ...
00000000001, 10) def test_cinference(self): w = pysal.weights.lat2W(5, 5) z = np.random.random_sample((w.n, 2)) p = np.ones((w.n, 1), float) floor = 3 solution = pysal.region.Maxp( w, z, floor, floor_variable=p, initial=100) solution.cinference(nperm=9, m...
helloworldC2/VirtualRobot
Node.py
Python
mit
260
0.019231
class Node(object):
def __init__(self,pos,parent,costSoFar,distanceToEnd): self.pos = pos self.parent = parent self.costSoFar = costSoFar
self.distanceToEnd = distanceToEnd self.totalCost = distanceToEnd +costSoFar
Hattivat/hypergolic-django
hypergolic/catalog/views/astronaut_views.py
Python
agpl-3.0
1,773
0
from django.views.generic.detail import DetailView from django.views.generic.edit import UpdateView, DeleteView from catalog.views.base import GenericListView, GenericCreateView from catalog.models import Astronaut, CrewedMission from catalog.forms import AstronautForm from catalog.filters import AstronautFilter from d...
"catalog/astronaut_detail.html" class AstronautCreateView(GenericCreateView): model = Astronaut form_class = AstronautForm success_url = reverse_lazy("astronaut_list") def form_valid(self, form): obj = form.save(commit=False) obj.creator = self.request.user obj.save() ...
(self): return reverse("astronaut_detail", args=(self.object.pk,)) class AstronautUpdateView(UpdateView): model = Astronaut form_class = AstronautForm template_name = "catalog/generic_update.html" initial = {} def form_valid(self, form): obj = form.save(commit=False) obj.m...
rudyryk/python-samples
hello_tornado/hello_asyncio.py
Python
cc0-1.0
3,463
0.001733
# hello_asyncio.py import asyncio import tornado.ioloop import tornado.web import tornado.gen from tornado.httpclient import AsyncHTTPClient try: import aioredis except ImportError: print("Please install aioredis: pip install aioredis") exit(0) class AsyncRequestHandler(tornado.web.Requ
estHandler): """Base class for request handlers with `asyncio` coroutines support. It runs methods on Tornado's ``AsyncIOMainLoop`` instance. Subclasses have to implement one of `get_async()`, `post_async()`, etc. Asynchronous method should be decorated with `@asyncio.coroutine`. Usage example:: ...
/python.org') self.write({'html': html}) You may also just re-define `get()` or `post()` methods and they will be simply run synchronously. This may be convinient for draft implementation, i.e. for testing new libs or concepts. """ @tornado.gen.coroutine def get(self, *args, **k...
teeple/pns_server
work/install/Python-2.7.4/Doc/conf.py
Python
gpl-2.0
5,857
0.001195
# -*- coding: utf-8 -*- # # Python documentation build configuration file # # This file is execfile()d with the current directory set to its containing dir. # # The contents of this file are pickled, so don't put values in the namespace # that aren't pickleable (module imports are okay, they're removed automatically). ...
/' # Additional static files. html_static_path = ['tools/sphinxext/static'] # Output file base name for HTML help builder. htmlhelp_basename = 'python' + release.replace('.', '') # Split the index html_split_index = True # Options for LaTeX output # ------------------------ # The paper size ('letter' or 'a4'). la...
LaTeX files. List of tuples # (source start file, target name, title, author, document class [howto/manual]). _stdauthor = r'Guido van Rossum\\Fred L. Drake, Jr., editor' latex_documents = [ ('c-api/index', 'c-api.tex', 'The Python/C API', _stdauthor, 'manual'), ('distutils/index', 'distutils.tex', 'D...
fredericojordan/fast-chess
scripts/hashfileStats.py
Python
mit
900
0.004444
import zlib, base64, sys MAX_DEPTH = 50 if __name__ == "__main__": try: hashfile = open("hashfile", "r") except: print("ERROR: While opening hash file!") sys.exit(-1) line_number = 0 depths
= [0 for _ in range(MAX_DEPTH)] for line in hashfile.readlines(): line_number += 1 l = line.strip().split() if len(l) < 7: print( "Bad entry on line " + str(line_number) + " (ignored): " + line.strip() ) continue hash...
]) fen = " ".join(l[3:]) depths[depth] += 1 hashfile.close() print("-- Depths --") for i in range(MAX_DEPTH): if not depths[i]: continue print("{:2d}: {:8d}".format(i, depths[i])) print("------------")
r26zhao/django_blog
blog/migrations/0012_auto_20170621_1250.py
Python
mit
586
0
# -*- coding: utf-8 -*- # Generated by Django 1.11.2 on 2017-06-21 04:50 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('blog', '0011_auto_20170621_1224'), ] operations = [
migrations.AddField( model_name='category', name='slug', field=models
.SlugField(default=''), ), migrations.AddField( model_name='tag', name='slug', field=models.SlugField(default=''), ), ]
chop-dbhi/serrano
serrano/resources/exporter.py
Python
bsd-2-clause
3,758
0
from django.conf.urls import patterns, url from django.core.urlresolvers import reverse from django.http import Http404 from modeltree.tree import MODELTREE_DEFAULT_ALIAS, trees from restlib2.params import Parametizer, IntParam, StrParam from avocado.export import BaseExporter, registry as exporters from avocado.query...
ME, row_data) post = get def delete(self, request, export_type, **kwargs): query_name = self._get_query_name(request, export_type) canceled = utils.cancel_query(query_name)
return self.render(request, {'canceled': canceled}) exporter_resource = ExporterResource() exporter_root_resource = ExporterRootResource() # Resource endpoints urlpatterns = patterns( '', url(r'^$', exporter_root_resource, name='exporter'), url(r'^(?P<export_type>\w+)/$', exporter_resource, name='exp...
BjoernT/python-openstackclient
openstackclient/object/v1/container.py
Python
apache-2.0
7,719
0
# Copyright 2013 Nebula 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...
parser.add_argument( '--long', action='store_true', default=False, help='List additional fields in output', ) parser.add_argument(
'--all', action='store_true', default=False, help='List all containers (default is 10000)', ) return parser @utils.log_method(log) def take_action(self, parsed_args): if parsed_args.long: columns = ('Name', 'Bytes', 'Count') else:...
palantir/typedjsonrpc
tests/test_server.py
Python
apache-2.0
10,750
0.001023
# coding: utf-8 # # Copyright 2015 Palantir Technologies, 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 applic...
_registry() server = Server(mock_registry, "/foo") with pytest.raises(HTTPException) as excinfo: server(environ, None) assert excinfo.value.code == 404 def test_wsgi_app_dispatch(self): environ = { "SERVER_NAME": "localhost",
"SERVER_PORT": "5060", "PATH_INFO": "/foo", "REQUEST_METHOD": "POST", "wsgi.url_scheme": "http", } mock_registry = self._create_mock_registry() server = Server(mock_registry, "/foo") mock_start_response = mock.Mock() server(environ...
greenaddress/pycoin
pycoin/test/ecdsa_test.py
Python
mit
1,478
0.012855
#!/usr/bin/env python import unittest from pycoin.ecdsa import generator_secp256k1, sign, verify, public_pair_for_secret_exponent class ECDSATestCase(unittest.TestCase): def test_sign_verify(self): def do_test(secret_exponent, val_list): public_point = public_pair_for_secret_exponent(generat...
ttps://github.com/bitcoin/bips/blob/master/bip-0062.mediawiki#low-s-values-in-signatures assert signature[1] <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0 assert r == True signature = signature[0],signature[1]+1 r = verify(generator...
val_list = [100,20000,30000000,400000000000,50000000000000000,60000000000000000000000] do_test(0x1111111111111111111111111111111111111111111111111111111111111111, val_list) do_test(0xdddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd, val_list) do_test(0x47f7616ea6f9b923...
acevest/monitor
utils.py
Python
gpl-2.0
6,848
0.017251
#!/usr/bin/env python # -*- coding: utf-8 -*- # ------------------------------------------------------------------------ # File Name: utils.py # Author: Zhao Yanbai # Thu Oct 30 06:33:24 2014 # Description: none #
----------------------------------------------------
-------------------- import logging import struct import socket import web import MySQLdb import commands import json import time from mail import SendMail from weixin import SendWeiXinMsg def init_logging(path) : logging.basicConfig(filename=path, level = logging.INFO, format ='%(levelname)s\t%(asctime)s: %(mes...
tpltnt/SimpleCV
SimpleCV/MachineLearning/MLTestSuite.py
Python
bsd-3-clause
9,967
0.019063
from __future__ import print_function from SimpleCV import * print("") print("This program runs a list of test for machine learning on") print("the SimpleCV library. Not all scores will be high, this") print("is just to ensure that the libraries are functioning correctly") print("on your system") print("") print("****...
xtend(glob.glob( os.path.join(path[0], ext))) for i
in range(10): img = Image(files[i]) cname = classifierSVMP.classify(img) print(files[i]+' -> '+cname) classifierSVMP.save('PolySVM.pkl') print('Reloading from file') testSVM = SVMClassifier.load('PolySVM.pkl') #testSVM.setFeatureExtractors(extractors) files = glob.glob( os.path.join(path[0], '*.jpg')) for ...
eezee-it/server-tools
auto_backup/models/db_backup.py
Python
agpl-3.0
10,250
0.000195
# -*- coding: utf-8 -*- # © 2004-2009 Tiny SPRL (<http://tiny.be>). # © 2015 Agile Business Group <http://www.agilebg.com> # © 2016 Grupo ESOC Ingeniería de Servicios, S.L.U. - Jairo Llopis # License AGPL-3.0 or later (http://www.gnu.org/licenses/gpl.html). import os import shutil import tempfile import traceback from...
e the connection with self.sftp_connection(): raise exceptions.Warning(_("Connection Test Succeeded!")) e
xcept (pysftp.CredentialException, pysftp.ConnectionException): _logger.info("Connection Test Failed!", exc_info=True) raise exceptions.Warning(_("Connection Test Failed!")) @api.multi def action_backup(self): """Run selected backups.""" backup = None filename = ...
Dhandapani/gluster-ovirt
backend/manager/tools/engine-image-uploader/src/ovf/ovfenvelope.py
Python
apache-2.0
398,478
0.004236
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Generated Fri Dec 2 15:05:18 2011 by generateDS.py version 2.7b. # import sys import getopt import re as re_ etree_ = None Verbose_import_ = False ( XMLParser_import_none, XMLParser_import_lxml, XMLParser_import_elementtree ) = range(3) XMLParser_import_li...
except ImportError: raise ImportError("Failed to import ElementTree from any known place") def parsexml_(*args, **kwargs): if (XMLParser_import_library == XMLParser_import_lxml and
'parser' not in kwargs): # Use the lxml ElementTree compatible parser so that, e.g., # we ignore comments. kwargs['parser'] = etree_.ETCompatXMLParser() doc = etree_.parse(*args, **kwargs) return doc # # User methods # # Calls to the methods in these classes are generated by generateD...
valdecar/Murka
pyttsx-master/setup.py
Python
gpl-3.0
1,287
0.002331
''' pyttsx setup script. Copyright (c) 2009, 2013 Peter Parente Permission to use, copy, modify, and distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED 'AS IS' AND THE AUTHO...
license='BSD License', pa
ckages=['pyttsx', 'pyttsx.drivers'] )
kevinkirkup/hedge
python/hedge/stock.py
Python
gpl-3.0
309
0.003236
#!/usr/bin/env py
thon # encoding: utf-8 """ Generic stock functions """ class Stock(object): """ Generic Stock information """ def __init__(self, symbol, name, sector): super(Stock, self).__init__()
self.symbol = symbol self.name = name self.sector = sector
Liuchang0812/slides
pycon2015cn/ex6_auto_install/autoinstall.py
Python
mit
590
0.00339
from __future__ import print_function import sys import subprocess class AutoInstall(object): _loaded = set() @classmethod def find_module(cls, name, path, target=None): if path is None and name not in cls._loa
ded: cls._loaded.add(name) print("Installing", name) try: out = subprocess.check_output(['sudo', sys.executable, '-m', 'pip', 'install', name]) print(out) except Exception as e: print("Failed" + e.message) return Non...
)
josenavas/labman
labman/db/configuration_manager.py
Python
bsd-3-clause
5,785
0
# ---------------------------------------------------------------------------- # Copyright (c) 2017-, labman development team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file LICENSE, distributed with this software. # -----------------------------------------------------...
ion""" self.user = config.get('postgres', 'USER') self.admin_user = config.get('postgres', 'ADMIN_USER') or None self.password = config.get('postgres', 'PASSWORD') if not self.password: self.password = None self.admin_password = config.get('postgres', 'ADMIN_PASSWOR...
lf.database = config.get('postgres', 'DATABASE') self.host = config.get('postgres', 'HOST') self.port = config.getint('postgres', 'PORT') def _get_qiita(self, config): self.qiita_server_cert = config.get('qiita', 'SERVER_CERT') CONFIG_TEMPLATE = """# Configuration file generated by labman...
CiuffysHub/MITMf
mitmflib-0.18.4/mitmflib/argh/decorators.py
Python
gpl-3.0
5,296
0.000756
# coding: utf-8 # # Copyright © 2010—2014 Andrey Mikhaylenko and contributors # # This file is part of Argh. # # Argh is free software under terms of the GNU Lesser # General Public License version 3 (LGPLv3) as published by the Free # Software Foundation. See the file README.rst for copying conditions. # """ Comm...
decorator inserts its value before the innermost's: declared_args.insert(0, dict(option_strings=args, **kwargs)) setattr(func, ATTR_ARGS, declared_args) return func return wrapper def wrap_errors(errors=None, processor=None, *args): """ Decorator. Wraps given exceptions into :c...
) def foo(x=None, y=None): assert x or y, 'x or y must be specified' If the assertion fails, its message will be correctly printed and the stack hidden. This helps to avoid boilerplate code. :param errors: A list of exception classes to catch. :param processor: A ca...
IljaGrebel/OpenWrt-SDK-imx6_HummingBoard
staging_dir/host/lib/scons-2.3.5/SCons/Options/EnumOption.py
Python
gpl-2.0
1,980
0.001515
# # Copyright (c) 2001 - 2015 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obt
aining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software ...
ission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL T...
xuru/pyvisdk
pyvisdk/do/extension_fault_type_info.py
Python
mit
1,025
0.00878
import logging from pyvisdk.exceptions import InvalidArgumentError ######################################## # Automatically generated, do not edit. ######################################## log = logging.getLogger(__name__) def ExtensionFaultTypeInfo(vim, *args, **kwargs): '''This data object type describes faul...
tattr(obj, name, arg) for name, value
in kwargs.items(): if name in required + optional: setattr(obj, name, value) else: raise InvalidArgumentError("Invalid argument: %s. Expected one of %s" % (name, ", ".join(required + optional))) return obj
ViennaRNA/forgi
test/forgi/threedee/utilities/test_dssr.py
Python
gpl-3.0
2,377
0.000841
import unittest import json import forgi.threedee.utilities._dssr as ftud import forgi.threedee.model.coarse_grain as ftmc import forgi.graph.residue as fgr class TestHelperFunctions(unittest.TestCase): def test_dssr_to_pdb_atom_id_validIds(self): self.assertEqual(ftud.dssr_to_pdb_resid( "B.C24...
class TestCoaxialStacks(unittest.TestCase): def setUp(self): cg = ftmc.CoarseGrainRNA.from_bg_file("test/forgi/threedee/data/1J1U.cg") with open("test/forgi/threedee/data/1J1U.json") as f: j = json.load(f) self.dssr = ftud.DSSRAnnotation(j, cg) def test_coaxial_stacks(self):...
r.coaxial_stacks()), sorted([["s2", "s1"], ["s0", "s3"]])) @unittest.skip("Currently not working. TODO") def test_compare_coaxial_stacks(self): forgi, dssr = self.dssr.compare_coaxial_stack_annotation() self.assertEqual(len(dssr), 2) self.assertGreaterEqual(len(...
pointhi/PySplat
PySplat/util/__init__.py
Python
gpl-3.0
682
0.004399
''' pysplat 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. pysplat 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 shoul
d have received a copy of the GNU General Public License along with kicad-footprint-generator. If not, see < http://www.gnu.org/licenses/ >. (C) 2016 by Thomas Pointhuber, <thomas.pointhuber@gmx.at> '''
liushuaikobe/GitArchiveUtils
gitradar/config.py
Python
gpl-2.0
375
0
#
-*- coding: utf-8 -*- from tornado.options import define define('debug', default=False, type=bool) # Tornado的监听端口 define('port', default=8888, type=int) # WHoosh Search相关 define('whoosh_ix_
path', default='/Users/liushuai/Desktop/index', type=str) # MongoDB define('mongo_addr', default='127.0.0.1', type=str) define('mongo_port', default=27017, type=int)
JakubPetriska/poker-cfr
test/sampling_tests.py
Python
mit
2,099
0.003335
import unittest import os import numpy as np from tools.sampling import read_log_file from tools.walk_trees import walk_trees_with_data from tools.game_tree.nodes import ActionNode, BoardCardsNode, HoleCardsNode LEDUC_POKER_GAME_FILE_PATH = 'games/leduc.limit.2p.game' class SamplingTests(unittest.TestCase): def...
return [cards == (43,) or cards == (47,) for cards in node.children] elif isinstance(node, BoardCardsNode): return [data if cards == (50,) else False for cards in node.children] else: return [data for _ in node.children] for name in players: ...
walk_trees_with_data(node_callback, True, player_tree) self.assertTrue(callback_was_called_at_least_once) def test_log_parsing_to_sample_trees_performance(self): players = read_log_file( LEDUC_POKER_GAME_FILE_PATH, 'test/sample_log-large.log', ['CFR_traine...
himaaaatti/qtile
libqtile/manager.py
Python
mit
59,989
0.000267
# Copyright (c) 2008, Aldo Cortesi. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify,...
for key in self.config.keys: self.mapKey(key) # It fixes problems with focus when clicking windows of some specific clients like xterm def noop(qtile): pass
self.config.mouse += (Click([], "Button1", command.lazy.function(noop), focus="after"),) self.mouseMap = {} for i in self.config.mouse: if self.mouseMap.get(i.button_code) is None: self.mouseMap[i.button_code] = [] self.mouseMap[i.button_code].append(i) ...
godiard/sugar
src/jarabe/frame/frameinvoker.py
Python
gpl-2.0
1,411
0
# Copyright (C) 2007, Eduardo Silva <edsiper@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 2 of the License, or # (at your option) any later version. # # This progr...
screen_area.x = screen_area.y = frame_thickness screen_area.w
idth = Gdk.Screen.width() - frame_thickness screen_area.height = Gdk.Screen.height() - frame_thickness return screen_area class FrameWidgetInvoker(WidgetInvoker): def __init__(self, widget): WidgetInvoker.__init__(self, widget, widget.get_child()) self._position_hint = self.ANCHORED ...
thinksabin/wafw00f
wafw00f/plugins/f5trafficshield.py
Python
bsd-3-clause
408
0
#!/usr/bin/env python NAME = 'F5
Trafficshield' def is_waf(self): for hv in [['cookie',
'^ASINFO='], ['server', 'F5-TrafficShield']]: r = self.matchheader(hv) if r is None: return elif r: return r # the following based on nmap's http-waf-fingerprint.nse if self.matchheader(('server', 'F5-TrafficShield')): return True return False
devs1991/test_edx_docmode
venv/lib/python2.7/site-packages/sympy/polys/domains/sympyrealdomain.py
Python
agpl-3.0
1,456
0.00206
"""Implementation of :class:`SymPyRealDomain` class. """ from sympy.polys.domains.realdomain import RealDomain from sympy.polys.domains.groundtypes import SymPyRealType class SymPyRealDomain(RealDomain): """Domain for real numbers based on
SymPy Float type. """ dtype = SymPyRealType zero = dtype(0) one = dtype(1) alias = 'RR_sympy' def __init__(self): pass def from_ZZ_python(K1, a, K0): """Convert a Python `int` object to `dtype`. """ return SymPyRealType(a) def from_QQ_python(K1, a,
K0): """Convert a Python `Fraction` object to `dtype`. """ return SymPyRealType(a.numerator) / a.denominator def from_ZZ_sympy(K1, a, K0): """Convert a SymPy `Integer` object to `dtype`. """ return SymPyRealType(a.p) def from_QQ_sympy(K1, a, K0): """Convert a SymPy `Rat...
adieu/authentic2
authentic2/saml/migrations/0022_auto__chg_field_libertysession_django_session_key__chg_field_libertyar.py
Python
agpl-3.0
24,009
0.006872
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models from authentic2.compat import user_model_label class Migration(SchemaMigration): def forwards(self, orm): # Changing field 'LibertySession.django_session_key' db.al...
'LibertyAssertion.provider_id' db.alter_column(u'saml_libertyassertion', 'provider_id', self.gf('django.db.models.fields.CharField')(max_length=256)) # Changing field 'LibertyAssertion.assertion_id' db.alter_column(u'saml_libertyassertion', 'assertion_id', self.gf('django.db.models.fields.Char...
self.gf('django.db.models.fields.CharField')(max_length=128)) # Changing field 'LibertySessionDump.django_session_key' db.alter_column(u'saml_libertysessiondump', 'django_session_key', self.gf('django.db.models.fields.CharField')(max_length=128)) def backwards(self, orm): # Changing field...
pingiun/keybaseproofbot
keybaseproofbot/handlers.py
Python
mit
15,489
0.003168
import time import json import logging import re import requests from telegram import InlineQueryResultArticle, InputTextMessageContent, ParseMode from telegram.ext import ConversationHandler from keybaseproofbot.models import Proof from keybaseproofbot.proof_handler import check_proof_message, lookup_proof, store_pr...
ilter_private def notusername(bot, u
pdate): bot.send_message( chat_id=update.message.chat_id, text="Please enter a username like @pingiun, or /cancel to cancel " "the current command.") @filter_private def notkbusername(bot, update): bot.send_message( chat_id=update.message.chat_id, text="Please enter a corr...
MetrodataTeam/incubator-airflow
tests/contrib/operators/test_sftp_operator.py
Python
apache-2.0
9,161
0.001092
# -*- coding: 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 in writing, software ...
# create a test file remotely create_file_task = SSHOperator( task_id="test_create_file", ssh_hook=self.hook, command="echo '{0}' > {1}".format(test_remote_file_content, sel
f.test_remote_filepath), do_xcom_push=True, dag=self.dag ) self.assertIsNotNone(create_file_task) ti1 = TaskInstance(task=create_file_task, execution_date=datetime.now()) ti1.run() # get remote file to local get_test_task = SFTPOperator( ...
IntelBUAP/Python3
codigo27.py
Python
gpl-2.0
388
0.033679
#! /usr/bin/python3 # -*- coding:utf-8 -*- # Funciones y parametros arbitrarios def funcion(**nombres): print (type(nombres))
for alumno in nombres: print ("%s es alumno y tiene %d años" % (alumno, nombres[alumno])) retu
rn nombres #diccionario = {"Adrian":25, "Niño":25, "Roberto":23, "Celina":23} print (funcion(Adrian = 25, Nino = 25, Roberto = 23, Celina = 23))
bram85/topydo
topydo/commands/AddCommand.py
Python
gpl-3.0
3,836
0.000261
# Topydo - A todo.txt client written in Python. # Copyright (C) 2014 - 2015 Bram Schoenmakers <bram@topydo.org> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License,...
ers (C)" * Dependencies using before, after, partof, parents-of and children-of tags. These are translated to the corresponding 'id' and 'p' tags. The values of these tags correspond to the todo number (not the dependency number). Example: add "Subtask partof:1" -f : Add t
odo items from specified FILE or from standard input.\ """
hpcleuven/easybuild-framework
easybuild/toolchains/iompi.py
Python
gpl-2.0
1,514
0.001982
## # Copyright 2012-2016 Ghent University # # This file is part of EasyBuild, # originally created by the HPC team of Ghent University (http://ugent.be/hpc/en), # with support of Ghent University (http://ugent.be/hpc), # the Flemish Supe
rcomputer Centre (VSC) (https://www.vscentrum.be), # Flemish Research Foundation (FWO) (http://www.fwo.be/en) # and the Department of Economy, Scien
ce and Innovation (EWI) (http://www.ewi-vlaanderen.be/en). # # http://github.com/hpcugent/easybuild # # EasyBuild 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 v2. # # EasyBuild is distributed in the hope tha...
wasit7/tutorials
django/Pieng/myclass/myclass/settings.py
Python
mit
3,183
0.001257
""" Django settings for myclass project. Generated by 'django-admin startproject' using D
jango 1.9.5. For more information on this file, see https://docs.djangoproject.com/en/1.9/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.9/ref/settings/ """ import os # Build pat
hs inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in pr...
solefaucet/sole-server
fabfile.py
Python
mit
1,674
0.005376
from fabric.api import env from fabric.context_managers import cd from fabric.operations import run, local, put env.shell = '/bin/bash -l -c' env.user = 'd' env.roledefs.update({ 'staging': ['staging.solebtc.com'], 'production': ['solebtc.com'] }) # Heaven will execute fab -R staging deploy:branch_name=master...
ebtc_prod';") run('go get bitbucket.org/liamstask/goose/cmd/goose') run('goose -env production up') # restart solebtc service with supervisorctl run('supervisorctl restart solebtc') def deployProduction(branch_name): printMessage("production") # TODO # scp executable file from sta...
y def printMessage(server): print("Deploying to %s server at %s as %s" % (server, env.host, env.user))
sdu14SoftwareEngineering/GameOfLife_WEB
game/method/ready_game.py
Python
apache-2.0
3,728
0
from game import models from game.method.in_game import thread_fields, Thread_field from game.tool.room_tool import * from game.tool.tools import to_json # 实时获得房间信息 room_id def get_room_info(request): room_id = int(request.POST['room_id']) room = get_room_by_id(room_id) print(room_id) print...
u_id in room.users: find_user = models.User.objects.filter(id=u_id) if find_user: find_user = find_user[0] u_
dict = { 'user_id': find_user.id, 'user_name': find_user.username, 'win': find_user.win, 'fail': find_user.fail, 'user_status': room.users_status[u_id] } users_array.append(u_dict) # 结果 response = { 'status': room.stat...
Shouqun/node-gn
tools/depot_tools/tests/gclient_test.py
Python
mit
40,396
0.003688
#!/usr/bin/env python # Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Unit tests for gclient.py. See gclient_smoketest.py for integration tests. """ import Queue import copy import logging import ...
ty', obj.dependencies[2].name) self._check_requirements( obj.dependencies[0], { 'foo/dir1': ['bar', 'bar/empty', 'foo'], 'foo/dir1/dir2/dir3': ['bar', 'bar/empty', 'foo', 'foo/dir1', 'foo/dir1/dir2'], 'foo/dir1/dir2/dir3/dir4': [
'bar', 'bar/empty', 'foo', 'foo/dir1', 'foo/dir1/dir2', 'foo/dir1/dir2/dir3'], }) self._check_requirements( obj.dependencies[1], { 'foo/dir1/dir2': ['bar', 'bar/empty', 'foo', 'foo/dir1'], }) self._check_requirements( obj.dependencies[2], ...
limingzju/ClearCacheServer
server.py
Python
bsd-2-clause
617
0.024311
from os import system import xmlrpclib from SimpleXMLRPC
Server import SimpleXMLRPCServer def clear_buffer_cache(): system('free -g') system('sync') system("sudo sed -n 's/0/3/w /proc/sys/vm/drop_caches' /proc/sys/vm/drop_caches") system('sync') system("sudo sed -n 's/3/0/w /proc/sys/vm/drop_caches' /proc/sys/vm/drop_caches") system('free -g') return True def is_eve...
SimpleXMLRPCServer(('0.0.0.0', 8888)) print 'Listening on port 8888...' server.register_function(clear_buffer_cache, 'clear_buffer_cache') server.register_function(is_even, 'is_even') server.serve_forever()
joshzarrabi/e-mission-server
emission/tests/client_tests/TestGamified.py
Python
bsd-3-clause
7,135
0.004905
# Standard imports import unittest import json import logging from datetime import datetime, timedelta # Our imports from emission.clients.gamified import gamified from emission.core.get_database import get_db, get_mode_db, get_section_db from emission.core.wrapper.user import User from emission.core.wrapper.client im...
ata/testCarbonFile") self.SectionsColl = get_section_db(
) self.walkExpect = 1057.2524056424411 self.busExpect = 2162.668467546699 self.busCarbon = 267.0/1609 self.airCarbon = 217.0/1609 self.driveCarbon = 278.0/1609 self.busOptimalCarbon = 92.0/1609 self.allDriveExpect = (self.busExpect * self.driveCarbon + self.walk...
buckbaskin/Insight
service1/app/__init__.py
Python
apache-2.0
125
0.008
from flask import Flask server =
Flask(_
_name__) server.config['SERVER_NAME'] = '127.0.0.1:5001' from app import endpoints
verdimrc/nfldb
nfldb/sql.py
Python
unlicense
15,501
0.000129
from __future__ import absolute_import, division, print_function from nfldb.db import _upsert class Entity (object): """ This is an abstract base class that handles most of the SQL plumbing for entities in `nfldb`. Its interface is meant to be declarative: specify the schema and let the methods defin...
ntity's `_sql_field` method (overriding the one defined on `nfldb.Entity`). The derived fields must be listed here so that the SQL generation code is aware of them.
""" @classmethod def _sql_columns(cls): """ Returns all columns defined for this entity. Every field corresponds to a single column in a table. The first `N` columns returned correspond to this entity's primary key, where `N` is the number of columns in the prim...
apatriciu/OpenStackOpenCL
computeOpenCL/nova/contrib/OpenCLServer/OpenCLServer.py
Python
apache-2.0
23,459
0.01006
from queues import queue_opencl_devices from queues import queue_opencl_contexts from queues import queue_opencl_buffers from queues import queue_opencl_programs from queues import queue_opencl_kernels from queues import queue_opencl_command_queues from queues import queue_opencl_notify import sys from oslo.config impo...
'GetPr
ogramProperties': try: nid = int(args['id']) result = PyOpenCLInterface.GetProgramProperties(nid) except: print "Exception caught in DispatchPrograms.%s " % method print "Exception info %s " % sys.exc_info()[0] nErr = -128 Propert...
destenson/bitcoin--bitcoin
contrib/devtools/github-merge.py
Python
mit
14,113
0.014667
#!/usr/bin/env python3 # Copyright (c) 2016-2017 Bitcoin Core Developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # This script will locally construct a merge commit for a pull request on a # github repository, inspect it, ...
parser.add_argument('branch', metavar='BRANCH', type=str, nargs='?', default=None, help='Branch to merge against (default: githubmerge.branch setting, or base branch for pull, or \'master\')') return parser.parse_args() def main(): # Extract settings from git repo repo = git_config_get('githubmerge...
opt_branch = git_config_get('githubmerge.branch',None) testcmd = git_config_get('githubmerge.testcmd') signingkey = git_config_get('user.signingkey') if repo is None: print("ERROR: No repository configured. Use this command to set:", file=stderr) print("git config githubmerge.repository...
aliyun/oss-ftp
python27/win32/Lib/site-packages/cryptography/x509/name.py
Python
mit
2,116
0
# This file is dual licensed under the terms of the Apache License, Version # 2.0, and the BSD License
. See the LICENSE file in the root of this repository # for complete details. from __future__ import absolute_import, division, print_function impo
rt six from cryptography import utils from cryptography.x509.oid import ObjectIdentifier class NameAttribute(object): def __init__(self, oid, value): if not isinstance(oid, ObjectIdentifier): raise TypeError( "oid argument must be an ObjectIdentifier instance." ) ...
y4n9squared/HEtest
hetest/python/circuit_generation/ibm/ibm_wire.py
Python
bsd-2-clause
1,345
0.003717
# ***************************************************************** # Copyright (c) 2013 Massachusetts Institute of Technology # # Developed exclusively at US Government expense under US Air Force contract # FA8721-05-C-002. The rights of the United States Government to use, modify, # reproduce, release, perform, disp...
SY # Description: IBM TA2 wire class # # Modifications: # Date Name Modification # ---- ---- ------------ # 22 Oct 2012 SY Original Version # ***************************************************************** import ibm_circuit_object as ico clas...
o.IBMCircuitObject): """ This class represents a single IBM input wire. """ def __init__(self, displayname, circuit): """Initializes the wire with the display name and circuit specified.""" ico.IBMCircuitObject.__init__(self, displayname, 0.0, 0, circuit)
david-ragazzi/nupic
nupic/encoders/coordinate.py
Python
gpl-3.0
6,560
0.00564
# ---------------------------------------------------------------------- # Numenta Platform for Intelligent Computing (NuPIC) # Copyright (C) 2014, Numenta, Inc. Unless you have an agreement # with Numenta, Inc., for a separate license for this software code, the # following terms and conditions apply: # # This progra...
mport Encoder class CoordinateEncoder(Encoder): """ Given a
coordinate in an N-dimensional space, and a radius around that coordinate, the Coordinate Encoder returns an SDR representation of that position. The Coordinate Encoder uses an N-dimensional integer coordinate space. For example, a valid coordinate in this space is (150, -49, 58), whereas an invalid coordin...
tensorflow/agents
tf_agents/bandits/policies/loss_utils.py
Python
apache-2.0
3,764
0.002125
# coding=utf-8 # Copyright 2020 The TF-Agents 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable la...
rsio
n-import from tf_agents.typing import types def pinball_loss( y_true: types.Tensor, y_pred: types.Tensor, weights: types.Float = 1.0, scope: Optional[Text] = None, loss_collection: tf.compat.v1.GraphKeys = tf.compat.v1.GraphKeys.LOSSES, reduction: tf.compat.v1.losses.Reduction = tf.compat.v1....
ee08b397/dpark
examples/jit.py
Python
bsd-3-clause
757
0.007926
''' Notice: 1. The function for jit should locate in mfs 2. For the usage of jit types and signatures, please refer Numba documentation <http://numba.github.com/numba-doc/0.10/index.html> ''' from dpark import _ctx as dpark, jit, autojit import numpy @jit('f8(f8[:])') def add1(x): sum = 0
.0 for i in xrange(x.shape[0]): sum += i*x[i] return sum @autojit def add2(x): sum = 0.0 for i in xrange(x.shape[0]): sum += i*x[i] return sum def add3(x): sum = 0.0 for i in
xrange(x.shape[0]): sum += i*x[i] return sum rdd = dpark.makeRDD(range(0, 10)).map(lambda x: numpy.arange(x*1e7, (x+1)*1e7)) print rdd.map(add1).collect() print rdd.map(add2).collect() print rdd.map(add3).collect()
MalloyPower/parsing-python
front-end/testsuite-python-lib/Python-3.5.0/Lib/nntplib.py
Python
mit
43,081
0.000696
"""An NNTP client class based on: - RFC 977: Network News Transfer Protocol - RFC 2980: Common NNTP Extensions - RFC 3977: Network News Transfer Protocol (version 2) Example: >>> from nntplib import NNTP >>> s = NNTP('news') >>> resp, count, first, last, name = s.group('comp.lang.python') >>> print('Group', name, 'ha...
rror(NNTPError): """4xx errors""" pass class NNTPPermanentError(NNTPError): """5xx errors""" pass class NNTPProtocolError(NNTPError): """Response does not begin with [1-5]""" pass class NNTPDataError(NNTPError): ""
"Error in response data""" pass # Standard port used by NNTP servers NNTP_PORT = 119 NNTP_SSL_PORT = 563 # Response numbers that are followed by additional text (e.g. article) _LONGRESP = { '100', # HELP '101', # CAPABILITIES '211', # LISTGROUP (also not multi-line with GROUP) '215', # ...
AnshulYADAV007/Lean
Algorithm.Python/CustomDataIndicatorExtensionsAlgorithm.py
Python
apache-2.0
3,632
0.013499
# QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. # Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. # # 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 Lice...
HOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from clr import AddReference AddReference("System") AddReference("QuantConnect.Algorithm") AddReference("QuantConnect.Common") AddReference("Quant...
ndicators") from System import * from QuantConnect import * from QuantConnect.Indicators import * from QuantConnect.Data import * from QuantConnect.Data.Market import * from QuantConnect.Data.Custom import * from QuantConnect.Algorithm import * from QuantConnect.Python import PythonQuandl ### <summary> ### The algor...
electric-cloud/metakit
python/setup.py
Python
mit
7,317
0.009703
from distutils.core import setup, Extension, Command from distutils.command.build import build from distutils.command.build_ext import build_ext from distutils.command.config import config from distutils.msvccompiler import MSVCCompiler from distutils import sysconfig import string import sys mkobjs = ['column', 'cust...
ts[i] if nm in mkobjs: if string.find(nm, '.') == -1:
nm = nm + suffix nm = prefix + nm ext.extra_objects[i] = nm build_ext.build_extension(self, ext) class test_regrtest(Command): # Original version of this class posted # by Berthold Hoellmann to distutils-sig@python.org description = "test the distribution...
raphael-group/comet
run_comet_full.py
Python
mit
10,224
0.010172
#!/usr/bin/python # Load required modules import sys, os, json, re, time, comet as C, multiprocessing as mp, random from math import exp import run_comet_simple as RC def get_parser(): # Parse arguments import argparse description = 'Runs CoMEt on permuted matrices.' parser = argparse.ArgumentParser(d...
help='Initial solution to use.') parser.add_argument('-r', '--num_initial', default=1, type=int, help='Number of different initial starts to use with MCMC.') parser.add_argument('-tv', '--total_distance_cutoff', type=float, default=0.005, help='stop conditi...
convergence (total distance).') # Parameters for determining the test to be applied in CoMEt parser.add_argument('--exact_cut', default=0.001, type=float, help='Maximum accumulated table prob. to stop exact test.') parser.add_argument('--binom_cut', type=float, default=0.005, ...