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
youtube/cobalt
third_party/v8/tools/release/PRESUBMIT.py
Python
bsd-3-clause
378
0.005291
# Copyright 2017 the V8
project authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. def CheckChangeOnCommit(input_api, output_api): tests = input_api.canned_checks.GetUnitTestsInDirectory( input_api, output_api, '.', files_to_check=['test_sc
ripts.py$']) return input_api.RunTests(tests)
staranjeet/fjord
fjord/search/tests/test_index.py
Python
bsd-3-clause
1,072
0
from fjord.base.tests import TestCase from fjord.feedback.models import ResponseDocType from fjord.feedback.tests import ResponseFactory from fjord.search.index import chunked from fjord.search.tests import ElasticTestCase class ChunkedTests(TestCase): def test_chunked(self): # chunking nothing yields not...
[(1, 2)
] # chunking list where len(list) > n assert list(chunked([1, 2, 3, 4, 5], 2)) == [(1, 2), (3, 4), (5,)] class TestLiveIndexing(ElasticTestCase): def test_live_indexing(self): search = ResponseDocType.docs.search() count_pre = search.count() s = ResponseFactory(happy=True...
androbwebb/JenniferVirtualAssistant
lessons/base/decorators.py
Python
mit
196
0.005102
def intent(func): """ This is us
ed inside the intent parser in `lessons.base.plugin._in
tent_dictionary()` :param func: :return: """ func.decorator = intent return func
devsim/devsim
testing/noise_res.py
Python
apache-2.0
2,229
0.004935
# Copyright 2013 Devsim 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 o
r agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # solid state resistor ssac import devsi...
r(name="botbias", value=0.0) res1.run_initial_bias(use_circuit_bias=True, net_doping=1e17) for v in (0.0, 1e-3): devsim.circuit_alter(name="V1", value=v) devsim.solve(type="dc", absolute_error=1e10, relative_error=1e-7, maximum_iterations=30) for contact in res1.contacts: test_common.printResistor...
ginabythebay/iddocs
apache_auth/management/commands/rewrite_htpasswd.py
Python
apache-2.0
618
0.001618
from django.core.management.base import BaseCommand, CommandError from apache_auth.middleware import rewrite_htpasswd class Command(BaseCommand): help = 'Rewrites the htpass
wd file' def handle(self, *args, **options): written_users = rewrite_htpasswd() verbosity = o
ptions['verbosity'] if verbosity >= 2: self.stdout.write('Wrote the following users:') for u in written_users: self.stdout.write(' %s' % u) if verbosity >= 1: self.stdout.write(self.style.SUCCESS( '%s users written' % len(written_user...
zhaochl/python-utils
random_simulators/simulate_user.py
Python
apache-2.0
1,284
0.017134
#!/usr/bin/env python # coding=utf-8 from constant import * from random import * from simulate_util import * from pdb import * def rd_cn_name(): _name ='' xing_index = randint(0,98) #print xing_index xing = CONST_XING[xing_index] #print xing _name = xing for i in range(randint(1,2)): ...
TION_LIST[action_index] if __name__=='__main__': #print 'main' num=5 for i in range(n
um): #cn_name= rd_cn_name() cn_name= gen_name() en_name = rd_en_name() action = rd_user_action() r = cn_name+","+"("+en_name+")"+action print r
squilter/MAVProxy
MAVProxy/modules/mavproxy_smartcamera/__init__.py
Python
gpl-3.0
16,290
0.006691
#!/usr/bin/env python #*************************************************************************** # Copyright Jaime Machuca #*************************************************************************** # Title : mavproxy_smartcamera.py # # Description : This file is intended to be added as ...
self.u8RetryTimeout = 0 self.u8MaxRetries = 5 self.__vRegisterCameras() #**************************************************************************** # Method Name : __vRegisterQXCamera # # Description : Tries to connect to a QX camera on the specified Wireless # ...
Author : Jaime Machuca # #**************************************************************************** def __vRegisterQXCamera(self,u8CamNumber): if (self.u8RetryTimeout < self.u8MaxRetries): new_camera = SmartCamera_SonyQX(u8CamNumber, self.WirelessPort) if new_camera.b...
takeshineshiro/horizon
openstack_dashboard/api/rest/__init__.py
Python
apache-2.0
1,343
0.006701
# Copyright 2014, Rackspace, US, 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...
tions under the License. """This package holds the REST API that supports the Horizon dashboard Javascript code. It is not intended to be used outside of Horizon, and makes no promises of stability or fitness for purpose outside of that scope. It does not promise to adhere to the general OpenStack API Guidelines set ...
ke8: noqa from . import config #flake8: noqa from . import glance #flake8: noqa from . import heat #flake8: noqa from . import keystone #flake8: noqa from . import network #flake8: noqa from . import neutron #flake8: noqa from . import nova #flake8: noqa from . import policy ...
mahajrod/MACE
MACE/Routines/Drawing.py
Python
apache-2.0
49,658
0.005981
#!/usr/bin/env python import os import math from collections import Iterable, OrderedDict import numpy as np import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt plt.ioff() from matplotlib.patches import Rectangle from matplotlib.colors import LinearSegmentedColormap from matplotlib import cm fro...
ist = list(scaffold_set) #print "PPPPPPPPPPP" #print scaffold_list if sort_scaffolds: scaffold_list.sort() final_scaffold_list = [] if scaffold_ordered_list: for en
try in scaffold_ordered_list: if entry in scaffold_list: final_scaffold_list.append(entry) scaffold_list.remove(entry) else: print("WARNING!!!Entry(%s) from order list is absent in list of scaffolds!" % entry) final_...
kyelewisstgc/EventMaster-Python
tests/test_offline.py
Python
mit
4,308
0.003714
#Import Libraries import eventmaster as EM from time import sleep import random import sys """ Create new Instance of EventMasterSwitcher and turn off logging """ s3 = EM.EventMasterSwitcher() s3.setVerbose(0) with open('example_settings_.xml', 'r') as content_file: content = content_file.read() s3.loadFromXML(...
string_pgm = " Layer is not on PGM " source_string_p
gm = "" size_string = " {4!s} is on PGM - {0!s}x{1!s} at {2!s},{3!s}".format(layer_hsize_pgm, layer_vsize_pgm, layer_hpos_pgm, layer_vpos_pgm, layer_name_pgm) source_string = " current source is {0!s}".format(layer_source_name_pgm) print(" ({0!s}) {1!s}\n {2!s}\n {3!s}\n ...
simonspa/django-datacollect
datacollect/survey/migrations/0045_record_coords.py
Python
gpl-3.0
498
0.002008
# -*- coding: utf-8 -*- # Generated by Django 1.9.7 on 2016-06-21 15:44 from __future__ import unicode_literals from django.db import migrations import djgeojson.fields class Migration(
migrations.Migration): dependencies = [ ('survey', '0044_auto_20160618_1412'), ] operations = [ migrations.AddField( model_name='record', name='coords', fie
ld=djgeojson.fields.PointField(blank=True, editable=False, null=True), ), ]
shivupa/pyci
methods/misc/fcidump.py
Python
gpl-3.0
2,153
0.020437
#!/usr/bin/env python # # Author: Qiming Sun <osirpt.sun@gmail.com> # from functools import reduce import numpy from pyscf imp
ort gto, scf, ao2mo from pyscf import tools from pyscf import symm ''' Write FCIDUMP file ''' mol = gto.M( atom = [['H', 0, 0, i] for i in range(6)], basis = '6-31g', verbose = 0, symmetry = 1, ) myhf = scf.RHF(mol) myhf.kernel() c = myhf.mo_coeff # # FCIDUMP for given 1e and 2e integrals # h1e = red...
m_integrals('fcidump.example1', h1e, eri, c.shape[1], mol.nelectron, ms=0) print "shit",h1e print "shit", eri print "shit", c.shape[1] # # Bypass small matrix elements in FCIDUMP # tools.fcidump.from_integrals('fcidump.example2', h1e, eri, c.shape[1], mol.nelec...
RomanZacharia/pyethapp
pyethapp/tests/test_genesis.py
Python
mit
1,593
0.001255
from pprint import pprint import pytest from ethereum import blocks from ethereum.db import DB from ethereum.config import Env from pyethapp.utils import merge_dict from pyethapp.config import update_config_from_genesis_json import pyethapp.config as konfig from pyethapp.profiles import PROFILES def test_genesis_conf...
e(address) == value @pytest.mark.parametrize('profile', PROFILES.keys()) def test_profile(profile): config = dict(
eth=dict()) konfig.update_config_with_defaults(config, {'eth': {'block': blocks.default_config}}) # Set config values based on profile selection merge_dict(config, PROFILES[profile]) # Load genesis config update_config_from_genesis_json(config, config['eth']['genesis']) bc = config['eth']['b...
travelbird/validictory
validictory/tests/test_type.py
Python
mit
4,940
0
from unittest import TestCase from decimal import Decimal import datetime import sys if sys.version_info[0] == 3: unicode_str = '\u2603' else: unicode_str = unicode('snowman') import validictory class TestType(TestCase): def test_schema(self): schema = { "type": [ {"...
, "bad", 123, [32, 49], None, True]
self._test_type('object', valids, invalids) def test_array(self): valids = [[1, 89], [48, {"test": "blah"}, "49", 42], (47, 11)] invalids = [1.2, "bad", {"test": "blah"}, 1234, None, True] self._test_type('array', valids, invalids) def test_null(self): valids = [None] i...
Blub/pkgdepdb
pypkgdepdb/__init__.py
Python
bsd-3-clause
29,250
0.005573
import ctypes from .common import * from . import functions from .functions import p_cfg, p_db, p_pkg, p_elf from .utils import * SONAME = 'libpkgdepdb.so.1' class LogLevel(object): Debug = 0 Message = 1 Print = 2 Warn = 3 Error = 4 class PkgEntry(object): Depends = 0 OptDe...
- start if stop else None if step == 0: raise ValueError('step cannot be zero') if coun
t == 0: return [] if step > 0: if count < 0: return [] return self.get(start, count)[::step] else: if count > 0: return [] return self.get(start+count, -count)[-count:0:step] def __contains__(self, value): retur...
poliastro/poliastro
contrib/CR3BP/test_run_CR3BP.py
Python
mit
6,277
0
""" ******************************************************************** Test file for implementation check of CR3BP library. ******************************************************************** Last update: 21/01/2022 Description ----------- Contains a few sample orbit propagations to test the CR3BP l...
would complete 9 orbits in the NRHO for every 2 lunar month (slightly different from lunar orbit period). The exact orbital elements presented here are from the auther's simulations. The orbit states were obtained starting form guess solutions given in various references. A few are provide
d below: Ref: White Paper: Gateway Destination Orbit Model: A Continuous 15 Year NRHO Reference Trajectory - NASA, 2019 Ref: Strategies for Low-Thrust Transfer Design Based on Direct Collocation Techniques - Park, Howell and Folta The NRHO are subfamily of the Halo orbits. The 'Near-Rectilinear' term c...
edmorley/django
tests/file_storage/tests.py
Python
bsd-3-clause
38,661
0.001397
import os import shutil import sys import tempfile import threading import time import unittest from datetime import datetime, timedelta from io import StringIO from urllib.request import urlopen from django.core.cache import cache from django.core.exceptions import SuspiciousFileOperation from django.core.files.base ...
_class('django.core.files.storage.NonexistentStorage') def test_get_nonexisten
t_storage_module(self): """ get_storage_class raises an error if the requested module don't exist. """ with self.assertRaisesMessage(ImportError, "No module named 'django.core.files.nonexistent_storage'"): get_storage_class('django.core.files.nonexistent_storage.NonexistentSt...
jh0ker/scambot
bot.py
Python
lgpl-3.0
21,774
0.000643
import logging from datetime import datetime from io import BytesIO, BufferedReader from telegram.ext import Updater, CommandHandler, RegexHandler, \ MessageHandler, Filters, CallbackQueryHandler from telegram.ext.dispatcher import run_async from telegram import ParseMode, ReplyKeyboardMarkup, ReplyKeyboardHide, \...
ge_preview=True) def get_admin(from_user): admin = Admin.get(id=from_user.id) if admin: admin.first_name = from_user.first_name admin.last_name = from_user.last_name
admin.username = from_user.username return admin def get_reporter(from_user): reporter = Reporter.get(id=from_user.id) if reporter: reporter.first_name = from_user.first_name reporter.last_name = from_user.last_name reporter.username = from_user.username return reporter de...
rossengeorgiev/aprs-python
aprslib/__init__.py
Python
gpl-2.0
1,577
0.002536
# aprslib - Python library for working with APRS # Copyright (C) 2013-2014 Rossen Georgiev # # 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 Fo
undation; either version 2 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 General Public License for more d...
if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. """ APRS library in Python Currently the library provides facilities to: - parse APRS packets - Connect and listen to an aprs-is packet feed """ # Py2 & Py3 compability import sys if sys.versio...
CodyKochmann/sync_lab
simple_notepad_server/cherrypy/wsgiserver/wsgiserver2.py
Python
mit
90,364
0.000266
"""A high-speed, production ready, thread pooled, generic HTTP server. Simplest example on how to use this module directly (without using CherryPy's application machinery):: from cherrypy import wsgiserver def my_crazy_app(environ, start_response): status = '200 OK' response_headers = [('Cont...
off and then handling each connection in turn. Each connection can co
nsist of an arbitrary number of requests and their responses, so we run a nested loop:: while True: conn = server.requests.get() conn.communicate() -> while True: req = HTTPRequest(...) req.parse_request() -> # Read the Request-Line, e.g. "G...
KlubbAlfaRomeoNorge/members
constants.py
Python
gpl-2.0
1,596
0
# -*- coding: utf-8 -*- # ------------------------------------------------------------------------- # Portello membership system # Copyright (C) 2014 Klubb Alfa Romeo Norge # # 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 program is dis
tributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if...
PyBossa/pybossa
test/test_jobs/test_schedule_jobs.py
Python
agpl-3.0
3,216
0.001555
# -*- coding: utf8 -*- # This file is part of PYBOSSA. # # Copyright (C) 2015 Scifabric LTD. # # PYBOSSA is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your op...
_job(a_job, self.scheduler) assert success_message == 'Scheduled a_function([], {}) to run every 1 seconds' assert failure_message == 'WARNING: Job a_function([], {}) is already scheduled' def test_failed_attempt_to_schedule_does_not_polute_redis(self): schedule_job(a_job, self.scheduler) ...
ction.keys('rq:job*') assert len(stored_values) == 1, len(stored_values)
chbrandt/zyxw
eada/io/fits.py
Python
gpl-2.0
9,491
0.018544
""" Module to deal with FITS catalog read/access """ ##@file fits_data import sys; import pyfits; import string; import numpy as np; import re; # --- def sort_by_column(tbhdu,fieldname): """ Sort a FITS table HDU by "fieldname" column in increasing order. Inputs: - tbhdu: FITS table HDU ...
po = valores.dtype ndim = valores.ndim except AttributeError: valores = [ is_numeric(s_i) for s_i in dic[_arg] ]; tipo = np.asarray(valores).dtype ndim = np.asarray(valores).ndim try: if tipo == np.dtype('int64'): tipo ...
r(ndim)+'J' elif tipo == np.dtype('float64') or tipo == np.dtype('float'): tipo = str(ndim)+'D' elif tipo == np.dtype('float32'): tipo = str(ndim)+'E' elif tipo == np.dtype('complex'): tipo =
GbalsaC/bitnamiP
venv/lib/python2.7/site-packages/shapely/geometry/proxy.py
Python
agpl-3.0
1,342
0.000745
"""Proxy for coordinates stored outside Shapely geometries """ from shapely.geos import lgeos from shapely import wkb EMPTY = wkb.deserialize('010700000000000000'.decode('hex')) class CachingGeometryProxy(object): context = None factory = No
ne __geom__ = EMPTY _gtag = None def __init__(self, context): self.context = context
@property def _is_empty(self): return self.__geom__ in [EMPTY, None] def empty(self): if not self._is_empty: lgeos.GEOSGeom_destroy(self.__geom__) self.__geom__ = EMPTY @property def _geom(self): """Keeps the GEOS geometry in synch with the context.""" ...
ofermend/medicare-demo
socialite/jython/Lib/pickle.py
Python
apache-2.0
44,792
0.002366
"""Create portable serialized representations of Python objects. See module cPickle for a (much) faster implementation. See module copy_reg for a mechanism for registering custom picklers. See module pickletools source for extensive comments. Classes: Pickler Unpickler Functions: dump(object, file) ...
is None: protocol = 0 if protocol < 0: protocol = HIGHEST_PROTOCOL elif not 0 <= protocol <= HIGHEST_PROTOCOL: raise ValueError("pickle protocol must be <= %d" % HIGHEST_PROTOCOL) self.write = file.write self.memo = {} self.proto = int(protoc
ol) self.bin = protocol >= 1 self.fast = 0 def clear_memo(self): "
globus/globus-release-tools
share/python/repo/__init__.py
Python
apache-2.0
17,563
0
# Copyright 2014-2015 University of Chicago # # 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 ...
None: return [ (package) for package_list in self.packages for package in self.packages[package_list] if package.source_name == source.source_name and package.version == source.version ] elif name is not None...
if version is not None: package_candidates = [ (package) for package_list in self.packages for package in self.packages[package_list] if name == package.name and package.version == version ...
dhylands/upy-examples
uctypes_test.py
Python
mit
763
0.011796
import uctypes ACCEL_CONFIG = { 'x_self_test' : uctypes.BFUINT8 | 0 | 7 << uctypes.BF_POS | 1 << uctypes.BF_LEN, 'y_self_test' : uctypes.BFUINT8 | 0 | 6 << uctypes.BF_POS | 1 << uctypes.BF_LEN, 'z_self_test' : uctypes.BFUINT8 | 0 | 5 << uctypes.BF_POS | 1 << uctypes.BF_LEN, 'range' : ucty...
_LEN
, } buf = bytearray(1) buf[0] = 0xa8 print('buf[0] =', hex(buf[0])) accel_config = uctypes.struct(ACCEL_CONFIG, uctypes.addressof(buf)) print('x_self_test =', accel_config.x_self_test) print('y_self_test =', accel_config.y_self_test) print('z_self_test =', accel_config.z_self_test) print('range =', accel_config.range...
wxue/xiakelite
libs/flask/module.py
Python
mit
8,422
0.000712
# -*- coding: utf-8 -*- """ flask.module ~~~~~~~~~~~~ Implements a class that represents module blueprints. :copyright: (c) 2010 by Armin Ronacher. :license: BSD, see LICENSE for more details. """ from .helpers import _PackageBoundObject, _endpoint_from_view_func def _register_module(module, st...
domain setting for URL rules that do not have a subdomain setting set. :param static_path: can be used to specify a different path for the static files on the web. Defaults to ``/stat
ic``. This does not affect the folder the files are served *from*. """ def __init__(self, import_name, name=None, url_prefix=None, static_path=None, subdomain=None): if name is None: assert '.' in import_name, 'name required i...
jandom/rdkit
rdkit/Chem/Draw/__init__.py
Python
bsd-3-clause
14,830
0.014295
# # Copyright (C) 2006-2016 Greg Landrum # All Rights Reserved # import os, re from rdkit.six import iteritems from rdkit.Chem.Draw.MolDrawing import MolDrawing, DrawingOptions from rdkit.Chem.Draw.rdMolDraw2D import * def _getCanvas(): useAGG = False useCairo = False useSping = False Canvas = None if not ...
anvas = Canvas(size) if opt
ions is None: options = DrawingOptions() options.bgColor = None if fitImage: drawingOptions.dotsPerAngstrom = int(min(size) / 10) options.wedgeDashedBonds = wedgeBonds drawer = MolDrawing(canvas=canvas, drawingOptions=options) omol = mol if kekulize: from rdkit import Chem mol = Chem.Mol(m...
jeffreychan637/fb-cal-tpa-production
app/server/wix_verifications.py
Python
bsd-2-clause
1,411
0.002126
"""This file handles parsing the Wix Instance which is key to the security of this app. """ from os import environ from base64 import urlsafe_b64encode, urlsafe_b64decode from hmac import new from hashlib import sha256 from json import loads if "HEROKU" in environ: wix_secret = environ["wix_secret"] else: fro...
parses the Wix instance that comes with every call to t
he server. If the parse is successful (the instance is from Wix and the permission is set to owner), the call is from a valid source and the request it came with should be performed. The function returns the parsed instance on success and false otherwise. """ try: signature, encoded_json...
DailyActie/Surrogate-Model
01-codes/scipy-master/scipy/special/add_newdocs.py
Python
mit
189,015
0.001508
# Docstrings for generated ufuncs # # The syntax is designed to look like the function add_newdoc is being # called from numpy.lib, but in this file add_newdoc puts the # docstrings in a dictionary. This dictionary is used in # generate_ufuncs.py to generate the docstrings for the ufuncs in # scipy.special at the C lev...
irye : exponentially scaled Airy functions. References ---------- .. [1] Cephes Mathematical Functions Library,
http://www.netlib.org/cephes/index.html .. [2] Donald E. Amos, "AMOS, A Portable Package for Bessel Functions of a Complex Argument and Nonnegative Order", http://netlib.org/amos/.org/amos/ """) add_newdoc("scipy.special", "airye", """ ...
Arcbot-Org/Arcbot
bolt/discord/permissions.py
Python
gpl-3.0
2,442
0.00041
""" This module provides an enum containing permission flags as per discord API This module provides a class for talking about permissions within the bot Contributors: - Patrick Hennessy """ from enum import Enum class PermissionFlag(Enum): CREATE_INSTANT_INVITE = 0x00000001 KICK_MEMBERS...
self.bitarray & permission) def add(self, permission_name): self.bitarray |= self._get_permission_value(permission_name) def remove(self, permission_name): self.bitarray &= ~self._get_permission_value(permission_name) @staticmethod def _get_permission_value(name): return getat...
self.allows(flag.name)]
mcallaghan/tmv
BasicBrowser/scoping/management/commands/check_query_file.py
Python
gpl-3.0
1,107
0.004517
from django.core.management.base import BaseCommand, CommandError from django
.core import management from django.db.models import Count from scoping.models import * class Command(B
aseCommand): help = 'check a query file - how many records' def add_arguments(self, parser): parser.add_argument('qid',type=int) def handle(self, *args, **options): qid = options['qid'] q = Query.objects.get(pk=qid) p = 'TY - ' if q.query_file.name is not '': ...
koduj-z-klasa/python101
docs/mcpi/figury/mcsim-2dKzK.py
Python
mit
1,853
0
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import local.minecraft as minecraft # import modułu minecraft import local.block as block # import modułu block os.environ["USERNAME"] = "Steve" # nazwa użytkownika os.environ["COMPUTERNAME"] = "mykomp" # nazwa komputera # utworzenie połaczenia z symulatore...
stuff as mcstuff mcfig = mcstuff.MinecraftDrawing(mc) mcfig.drawLine(-14, 0, -14, -14, 0, 14, block.LEAVES) mcfig.drawLine(-14, 0, 0, -7, 0, 14, block.LEAVES) mcfig.drawLine(-14, 0, 0, -7, 0, -14, block.LEAVES) mcfig.drawLine(-5, 0, 0, 5, 0, 0, block.LEAVES) mcfig.drawLine(5, 0, 0, -5, 0, 14, bl...
4, block.LEAVES) mcfig.drawLine(7, 0, -14, 7, 0, 14, block.LEAVES) mcfig.drawLine(7, 0, 0, 14, 0, 14, block.LEAVES) mcfig.drawLine(7, 0, 0, 14, 0, -14, block.LEAVES) return 0 if __name__ == '__main__': print "Uruchamianie... Proszę czekać..." main()
maszczyn/shim
tests/test_system_load_monitor.py
Python
mit
1,207
0.001657
#!/usr/bin/env python # -*- coding: utf-8 -*- import unittest import mock from shim import SystemLoadMonitor, Monito
rCheckFailure class TestSystemLoadMonitor(unittest.TestCase): def setUp(self): self.monitor_id = "monitor_id" self.monitor_options = { 'upper_threshold': 1.0, } self.monitor = self._create_system_load_monitor() def _create_system_load_monitor(self): return ...
n("SystemLoadMonitor", self.monitor.name) @mock.patch("shim.Monitor._get_raw_value") def test_get_current_value_returns_the_load_if_command_returned_properly_formatted_data(self, raw_value_patch): raw_value_patch.return_value = "0.18 0.29 0.31 1/345 16151" self.assertEqual(self.monitor.get_curr...
GabMus/lithium-projman
server/projman/models.py
Python
gpl-3.0
3,701
0.037287
# This file is part of Lithium-Projman. # # Lithium-Projman 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. # # Lithi...
se) date_time = m
odels.DateTimeField(auto_now_add = True) class Note(models.Model): # id is already defined as default in django author = models.ForeignKey('ProjmanUser', null = False) parent_project = models.ForeignKey('Project', null = False) title = models.TextField(blank = False) content = models.TextField(blank = True) pinn...
ex-nerd/health-stats
health_stats/dataset.py
Python
mit
1,067
0.000937
from collections import OrderedDict class DataSet(object): __slots__ = ( 'events', # List of all events in this data set 'group', # Iterable containing groups of events ) def __init__(self, query, group_function): self.events = query.all() if group_function is None: ...
elf.group[key].append(event) else: raise ValueError("group_function is not callable") def __pretty__(self, p, cycle): p.text('<{0}: '.format(type(self)
.__name__)) if cycle: p.text('...') else: p.pretty({ 'events': self.events, 'group': self.group.keys(), }) p.text('>')
nanchenchen/emoticon-analysis
emoticonvis/apps/corpus/models.py
Python
mit
5,332
0.003188
import operator from django.db import models from django.db.models import Q from django.db.models import Count from caching.base import CachingManager, CachingMixin from emoticonvis.apps.base import models as base_models from emoticonvis.apps.corpus import utils import numpy class Dataset(models.Model): """A to...
('En', 'English'), ('Fr', 'French'), ) detected_language = models.CharField(max_length=2, choices=LANG_CHOICES, default='No') def __repr__(self): retu
rn self.text def __unicode__(self): return self.__repr__()
mudyc/libvob-c
py/setup.py
Python
gpl-2.0
760
0.028947
from distutils.core import setup, Extension import os import popen2 line = popen2.popen2('pkg-config --cflags glib-2.0')[0].readline() print line inc_dirs = ['../src/'] for s in line.split(" "): if s.startswith('-I'): inc_dirs.append(s[2:]) #print inc_dirs module1 = Extension('libvob', ...
vob-c', 'glib-2.0', 'mcheck'], runtime_library_dirs = [os.path.abspath('.
.')], ) setup (name = 'PyLibvob', version = '0.0.1', description = 'A python bindings for Libvob-c', #ext_package='libvob', ext_modules = [module1])
Sashkiv/sneakers_shop
sneakers_shop/pkg/main/urls.py
Python
gpl-3.0
382
0
from django.conf.urls import url from sneakers_shop.pkg.main.views import IndexView, AboutView, ContactsView, \ CatalogView, DeliveryView urlpatterns = [ url(r'^$', IndexView.as_view()), url(r'^about/', AboutView.as_view()), url(r'^contacts/', ContactsView.as_view()), url(r'^c
atalog/', CatalogView.as_view()), url(r'^delivery/', D
eliveryView.as_view()), ]
asoplata/dynasim-benchmark-brette-2007
output/Brian2/brian2_benchmark_CUBA_nosyn_250/brian2_benchmark_CUBA_nosyn_250.py
Python
gpl-3.0
2,003
0.003498
""" # Notes: - This simulation seeks to emulate the CUBA benchmark simulations of (Brette et al. 2007) using the Brian2 simulator for speed benchmark comparison to DynaSim. However, this simulation
does NOT include synapses, for better comparison to Figure 5 of (Goodman and Brette, 2008). - The time taken to simulate will be indicated in the stdout log file '~/batchdirs/brian_benchmark_CUBA_nosyn_250/pbsout/brian_benchmark_CUBA_nosyn_250.out' - Note that this code has been slightly modified from the original...
ale.edu/modeldb/showModel.cshtml?model=83319 in order to work with version 2 of the Brian simulator (aka Brian2), and also modified to change the model being benchmarked, etc. # References: - Brette R, Rudolph M, Carnevale T, Hines M, Beeman D, Bower JM, et al. Simulation of networks of spiking neurons: A review ...
google-research/graph-attribution
tests/test_training.py
Python
apache-2.0
3,709
0.003235
# Copyright 2020 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 agreed to in writing, ...
return model @parameterized.named_parameters(('constant', 1024, 256, 4), ('droplast', 1000, 256, 3)) def test_get_batch_indices(self, n, batch_size, expected_n_b
atches): batch_indices = training.get_batch_indices(n, batch_size) self.assertEqual(batch_indices.shape, (expected_n_batches, batch_size)) @parameterized.parameters([0.2, 1.0]) def test_augment_binary_task(self, fraction): """Check that data augmention sizes are correct.""" initial_n = 10 x, y ...
airbnb/airflow
tests/providers/apache/hive/sensors/test_hive_partition.py
Python
apache-2.0
1,659
0.002411
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not...
TS is not set") @patch( 'airflow.providers.apache.hive.sensors.hive_partit
ion.HiveMetastoreHook', side_effect=MockHiveMetastoreHook, ) class TestHivePartitionSensor(TestHiveEnvironment): def test_hive_partition_sensor(self, mock_hive_metastore_hook): op = HivePartitionSensor( task_id='hive_partition_check', table='airflow.static_babynames_partitioned', dag=self.da...
emirot/codefights
python/simpleSort.py
Python
apache-2.0
248
0
def simpleSort(arr): n = len(arr) for i in range
(n): j = 0 stop = n -
i while j < stop - 1: if arr[j] > arr[j + 1]: arr[j], arr[j+1] = arr[j+1], arr[j] j += 1 return arr
cemmanouilidis/naturalscrolling
naturalscrolling/indicator.py
Python
gpl-3.0
3,094
0.000646
### BEGIN LICENSE # Copyright (C) 2011 Guillaume Hain <zedtux@zedroot.org> # # This program 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 that it will be...
, see <http://www.gnu.org/licenses/> ### END LICENSE import gtk import appindicator from naturalscrolling_lib import naturalscrollingconfig from naturalscrolling_lib.gconfsettings impor
t GConfSettings from naturalscrolling_lib.udevobservator import UDevObservator from naturalscrolling.indicatormenu import IndicatorMenu class Indicator(object): # Singleton _instance = None _init_done = False def __new__(cls, *args, **kwargs): if not cls._instance: cls._instance =...
arneck/Macropores
biopore_detect.py
Python
gpl-3.0
12,967
0.022056
# coding: utf-8 import numpy as np import matplotlib.pyplot as plt import scipy.ndimage as snd import seaborn as sns from skimage import img_as_float, morphology, measure from skimage.color import rgb2hsv from skimage.morphology import reconstruction from skimage.exposure import rescale_intensity from skimage.measure...
---------- fi : input image ('.png'-format, either as rgb or rgba image) mp_threshold : lower limit for removing small macropores patch_threshold : min [0] and max [1] of the desired patch size limits (usually min=100,max=10000) perc : value up to which percentile gray values among to bi...
] plot : True/False: whether results should be plotted (default:True) morph : if True the morphology of detected biopores will be plotted, otherwise pores are displayed as scatterplot and distinguished whether stained or not (default) testing : if True no distances are calculated and only the det...
LLNL/spack
var/spack/repos/builtin.mock/packages/git-test/package.py
Python
lgpl-2.1
396
0
# Copyright 2013-2021 Lawrence Livermore National Secu
rity, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import * class GitTest(Package): """Mock package that uses git for fetching.""" homepage = "http://www.git-fetch-example.com" version('git', git='to-be-filled-in-by-test')
unreal666/outwiker
src/outwiker/gui/dialogs/overwritedialog.py
Python
gpl-3.0
3,191
0.000331
# -*- coding: utf-8 -*- import wx from outwiker.gui.testeddialog import TestedDialog class OverwriteDialog(TestedDialog): def __init__(self, *args, **kwds): super(OverwriteDialog, self).__init__(*args, **kwds) self.textLabel = wx.StaticText(self, -1, ...
flag=wx.ALIGN_CENTER_HORIZONTAL | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=4) self.SetSizer(sizer_1) self.Fit() def ShowDialog(self, text): """ Показать диалог, если нужно спросить, что делать с файлов. Этот метод вызывается вместо Show/Sho...
lf.flag == 0: self.textLabel.SetLabel(text) self.Layout() return self.ShowModal() return self.flag def onOverwrite(self, event): self.EndModal(self.ID_OVERWRITE) def onOverwriteAll(self, event): self.flag = self.ID_OVERWRITE self.EndModal(se...
tyc85/nwsdr-3.6.3-dsc
gr-uhd/grc/gen_uhd_usrp_blocks.py
Python
gpl-3.0
11,243
0.038246
""" Copyright 2010-2011 Free Software Foundation, Inc. This file is part of GNU Radio GNU Radio Companion 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 ...
uradio. Wire Format: This parameter controls the form of the data
over the bus/network. \ Complex bytes may be used to trade off precision for bandwidth. \ Not all formats are supported on all devices. Stream Args: Optional arguments to be passed in the UHD streamer object. \ Streamer args is a list of key/value pairs; usage is determined by the implementation. Ex: the scalar key af...
StackHut/stackhut-toolkit
stackhut_toolkit/common/runtime/rpc.py
Python
apache-2.0
9,386
0.003729
# Copyright 2015 StackHut Ltd. # # 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, so...
############################################################################################### # Error handling ERR_SERVICE = -32002 class ParseError(RpcException): def __init__(self, data=None): super().__init__(ERR_PARSE, 'Parse Error', data) class InvalidReqError(RpcException): def __init__(self, ...
r(RpcException): def __init__(self, data=None): super().__init__(ERR_METHOD_NOT_FOUND, 'Method Not Found', data) class InternalError(RpcException): def __init__(self, msg='', data=None): super().__init__(ERR_INTERNAL, 'Internal Error - {}'.format(msg), data) class ServiceError(RpcException): ...
moloch--/RootTheBox
alembic/versions/5ca019edf61f_cascade_on_delete.py
Python
apache-2.0
12,722
0.001572
"""Cascade on Delete Revision ID: 5ca019edf61f Revises: 469f428604aa Create Date: 2019-06-23 05:49:26.061932 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = "5ca019edf61f" down_revision = "469f428604aa" branch_labels = None depends_on = None def upgrade(): ...
k_1", type_="foreignkey") batch_op.drop_constraint("penalty_ibfk_2", type_="foreignkey") op.create_foreign_key( "penalty_ibfk_1", "penalty", "team", ["team_id"], ["id"], ondelete="CASCADE" )
op.create_foreign_key( "penalty_ibfk_2", "penalty", "flag", ["flag_id"], ["id"], ondelete="CASCADE" ) with op.batch_alter_table("snapshot_team") as batch_op: batch_op.drop_constraint("snapshot_team_ibfk_1", type_="foreignkey") op.create_foreign_key( "snapshot_team_ibfk_1", ...
ZellMechanik-Dresden/ShapeOut
shapeout/gui/controls_statistics.py
Python
gpl-2.0
2,684
0.001863
#!/usr/bin/python # -*- coding: utf-8 -*- """Shape-Out - statistics display""" from __future__ import division, print_function, unicode_literals import wx import wx.grid as gridlib from .. import util from .controls_subpanel import SubPanel class SubPanelStatistics(SubPanel): def __init__(self, *args, **kwargs)...
is): self.ClearSubPanel() # Create three boxes containing information sizer = wx.BoxSizer(wx.HORIZONTAL) statbox = self._box_statistics(analysis) # same size h = statbox.GetMinSize()[1] h = max(h, 50) statbox.SetMinSize((-1, h
)) sizer.Add(statbox) self.SetSizer(sizer) sizer.Fit(self)
animesh21/booklogue
config.py
Python
mit
204
0
import os basedir = os.path.abspath(os.path.dirname(__file__
)) SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://user:user@localhost/booklogue' SQLALCHEMY_MIGRATE_REPO = os.path.join(basedir, 'db.repository'
)
bdfoster/blumate
tests/util/test_location.py
Python
mit
1,684
0
"""Test Home Assistant location util methods.""" # pylint: disable=too-many-public-methods import unittest import blumate.util.location as location_util # Paris COORDINATES_PARIS = (48.864716, 2.349014) # New York COORDINATES_NEW_YORK = (40.730610, -73.935242) # Results for the assertion (vincenty algorithm): # ...
COORDINATES_NEW_YORK) self.assertEqual(round(kilometers, 2), DISTANCE_KM) def test_get_miles(self): """Test getting the distance between given coordinates in miles.""" miles = location_util.vincenty(COORDINA
TES_PARIS, COORDINATES_NEW_YORK, miles=True) self.assertEqual(round(miles, 2), DISTANCE_MILES)
Sinar/popit_ng
popit/tests/test_update_es.py
Python
agpl-3.0
1,573
0.005086
from popit.tasks import update_node from django.test import TestCase from mock import patch from popit.models import * from popit.serializers import * class UpdateESTask(TestCase): fixtures = ["api_request_test_data.yaml"] @patch("popit_search.utils.search.SerializerSearch") def test_update_node_first_in...
organization = Organization.objects.language("en").get(id="3d62d9ea-0600-4f29-8ce6-f7720fd49aa3") instance.add.assert_called_with(organization, OrganizationSeriali
zer) @patch("popit_search.utils.search.SerializerSearch") def test_delete_node(self, mock_search): instance = mock_search.return_value node = ("organizations", "3d62d9ea-0600-4f29-8ce6-f7720fd49aa3", "delete") update_node(node) instance.delete_by_id.assert_called_with("3d62d9ea-...
abztrakt/uw-skilltree
skilltreeapp/views/pages.py
Python
apache-2.0
4,046
0.003707
from django.conf import settings from django.template import RequestContext from django.shortcuts import render_to_response from django.contrib.auth import authenticate, login, logout from django.core.context_processors import csrf from skilltreeapp.forms import LoginForm from django.shortcuts import render_to_response...
locations = request.user.location_set.a
ll() now = datetime.datetime.now() notifications = Notification.objects.all() events = [] alerts = [] for noti in notifications: if noti.due_date: if now.date() - noti.due_date.date() >= datetime.timedelta(days=1): noti.archived =...
timjarman/seeds
seeds/seedsdb/tests/unit/test_models.py
Python
mit
4,829
0.000828
from django.test import TestCase from seedsdb.models import ( Plant, Tag, Harvest, Activity ) class TestPlant(TestCase): def tearDown(self): Plant.objects.all().delete() def make_test_plant(self, aliases=None): if aliases: aliases = "|".join(aliases) else: ...
plant = self.make_test_plant() self.assertEqual(u"Love in idleness", unicode(plant)) def test_slug_create(self): "Creating a new plant sets the slug as expected " plant = self.make_test_plant() self.assertEqual("love-in-idleness", plant.slug) def test_slug_update(self): ...
ertEqual("love-lies-oozing", plant.slug) def test_get_absolute_url(self): plant = self.make_test_plant() expected_url = "/plants/detail/love-in-idleness/" self.assertEqual(expected_url, plant.get_absolute_url()) def test_aliases_string_none(self): "Ensure the liases_string pro...
jhseu/tensorflow
tensorflow/python/keras/mixed_precision/experimental/autocast_variable.py
Python
apache-2.0
17,110
0.009936
# Copyright 2019 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...
able interface and delegates to the wrapped variable, but it additionally will cast the wrapped variable under a `Graph._enable_variable_auto_cast(dtype)` context manager. For example: ``` v = tf.Variable(1.0, dtype=tf.float32) v = AutoCastVariable(v) print(tf
.identity(v).dtype) # tf.float32 with ops.get_default_graph()._enable_variable_auto_cast(tf.float16): print(tf.identity(v).dtype) # tf.float16, as v will cast itself to float16 print(v.dtype) # tf.float16, as v.dtype also changes under the ctx manager. ``` The purpose of this class is to allow Keras l...
SELO77/seloPython
3.X/ex/asyncIOex.py
Python
mit
5,486
0.004063
# def custom_range(end): # i = 0 # z = "How generator works!!??" # while i < end: # yield i #coroutine : 진입점이 여러개인 함수 # print('custom_range.i :%s'%i) # i += 1 # yield z # gen = custom_range(5) # for i in gen: # print(i, end=',') # list(gen) # print(next(gen)) # def s...
Done https://google.com # Done https://apple.com # Done https://github.com/ssut # 1.3564843910025957 # 스레드 갯수는 OS에 의해 한정되어 있습니다. # 공유 메모리 문제가 있습
니다. 락(Mutex)을 사용해야 하죠. # 그런데 파이썬에는 GIL이라는 괴상한 놈이 있습니다. # 파이썬 스레드를 스레드답게 쓰지 못하게(?) 해주는 놈인데요. 뭐 자세한 설명은 구글링을.. (이 글에서는 aio에 대해서만 다룹니다. ㅠㅠ) # ========================================== # import timeit # from concurrent.futures import ProcessPoolExecutor # from urllib.request import urlopen # # urls = ['http://naver.com...
hdm-dt-fb/rvt_model_services
commands/audit_no_ws/__init__.py
Python
mit
979
0.001021
import datetime import rjm from pathlib import Path def cmd_journal(project_code, model_path, jrn_path, com_dir, log_dir): command_path = Path(__file__).parent command_name = command_path.name time_stamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S") rvt_jrn = rjm.JournalMaker() com_data = { ...
tab_name='Add-Ins', panel_name=' Revit Model Services (RMS) ', command_module='RMSCmdExecutor', command_class='RMSCmdExecutorCommand', command_data=com_data, ) rvt_jrn.close_model() rvt_jrn.write_journal(jrn_path) register = { "name": "audit_no_ws", "rjm": c...
nal, }
UCSD-CCAL/ccal
ccal/_identify_what_to_count.py
Python
mit
2,352
0.001276
def _identify_what_to_count(signature_component_weight): signature_component_dict = {} signature_component_differing_dict = {} signature_component_before_dict = {} signature_component_before_differing_dict = {} for signature_component, weight in signature_component_weight.items(): sign...
signature_component_before_differing_dict[k]["weight"] = max( weight, signature_component_before_differing
_dict[k]["weight"] ) return ( signature_component_dict, signature_component_differing_dict, signature_component_before_dict, signature_component_before_differing_dict, )
openai/CLIP
setup.py
Python
mit
491
0
import os import pkg_resources from setuptools import setup, find_packages setup( name="clip", py_modules=["clip"], version="1.0", description="", author="OpenAI", packages=find_packages(exclude=["tests*"]), install_requires=[ str(r) for r in pkg_resources.parse_requirement...
), "requirements.txt")) ) ], include_package_data=True, extras_require={'dev': ['pytest']}, )
ajaniv/django-core-models
django_core_models/core/views.py
Python
mit
2,384
0
""" .. module:: django_core_models.core.views :synopsis: django_core_models core application views module. *django_core_models* core application views module. """ from __future__ import absolute_import from rest_framework.decorators import api_view from django_core_utils.views import (instance_list, instance_d...
ate a new category instance. """ return instance_list(request, models.Category, serializers.CategorySerializer, format) @api_view(['GET', 'PUT', 'DELETE']) def category_detail(request, pk, content_format=None): """ Retrieve, up
date or delete a category. """ return instance_detail(request, pk, models.Category, serializers.CategorySerializer, format) class AnnotationMixin(object): """Annotation mixin class.""" queryset = models.Annotation.objects.all() serializer_class...
bqbn/addons-server
src/olympia/addons/migrations/0001_initial.py
Python
bsd-3-clause
26,975
0.004708
# Generated by Django 2.2.5 on 2019-09-12 13:31 from django.conf import settings from django.db import migrations, models import django.db.models.deletion import django.db.models.manager import django.utils.timezone import django_extensions.db.fields.json import olympia.amo.fields import olympia.amo.models import olym...
'created', models.DateTimeField(blank=True, default=django.utils.timezone.now, editable=False)), ('modified', models.DateTimeField(auto_now=True)), ('id', olympia.amo.fields.PositiveAutoField(primary_key=True, serialize=False)), ('guid', model
s.CharField(max_length=255, unique=True)), ('comments', models.TextField(blank=True, default='')), ], options={ 'db_table': 'denied_guids', }, bases=(olympia.amo.models.SearchMixin, olympia.amo.models.SaveUpdateMixin, models.Model), ...
Naftoreiclag/Genre-Entities
tool/SyncEngineCodelite.py
Python
apache-2.0
2,659
0.002633
# Copyright 2017 James Fong # # 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 i...
' Converts a path into a list of directory names leading up to the tail (filename) and the filename. ''' path, filename = os.path.split(path) decomposed = []
while True: head, tail = os.path.split(path) if tail: decomposed.append(tail) path = head else: break decomposed.reverse() return decomposed path = decomposePath(sourcePath) parentElem = myprojectV...
Azure/azure-sdk-for-python
sdk/network/azure-mgmt-network/azure/mgmt/network/v2019_08_01/operations/_application_gateways_operations.py
Python
mit
73,707
0.005088
# 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 ...
iptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } if polling is True: polling_method = ARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, path_format_arguments=path_format_arguments, **kwargs) elif polling is False: polling_m...
hod = NoPolling() else: polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_runni...
the-it/WS_THEbotIT
archive/online/2015/150914_add_pages_Saint_Germain.py
Python
mit
3,440
0.006412
# -*- coding: utf-8 -*- __author__ = 'eso' import sys sys.path.append('../../') from tools.petscan import PetScan import re import requests import pywikibot list_of_pages =[1134, 1135, 1136, 1137, 1138, 1139, 1140, ...
1159,
1160, 1161, 1162, 1163, 1164, 1165, 1166, 1167, 1168, 1169, 1170, 1171, 1172, 1173, 1174, ...
virantha/scanpdf
docs/conf.py
Python
apache-2.0
10,696
0.006638
# -*- coding: utf-8 -*- # # scanpdf documentation build configuration file, created by # sphinx-quickstart on Wed Oct 23 13:43:29 2013. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # A...
a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names...
# Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_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 lett...
LLNL/spack
lib/spack/spack/util/log_parse.py
Python
lgpl-2.1
3,781
0
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from __future__ import print_function import sys from ctest_log_parser import BuildError, BuildWarning, CTestLogParser f...
t=6, jobs=None, profile=False): """Extract interesting events from a log file as a list of LogEvent. Args: stream (str or typing.IO): build log name or file object context (int): lines of context to extract around each log event job
s (int): number of jobs to parse with; default ncpus profile (bool): print out profile information for parsing Returns: (tuple): two lists containig ``BuildError`` and ``BuildWarning`` objects. This is a wrapper around ``ctest_log_parser.CTestLogParser`` that lazily constructs ...
clic-lab/blocks
BlockWorldRoboticAgent/agent_no_model.py
Python
gpl-3.0
5,392
0.002411
import sys import logger import message_protocol_util as mpu import reliable_connect as rc import generic_policy as gp import random ORACLE, RANDOM_WALK, STOP = range(3) class AgentModelLess: """" The block world agent that implements oracle, random walk and the stop baseline. Requires no parameters to be tu...
"" sum_bisk_metric = 0 for i in range(0, dataset_size): (_, bisk_metric, current_env, instruction, trajectory) = self.receive_instruction_and_image() sum_bisk_metric = sum_bisk_metric + bisk_metric logger.Log.info("Bisk Metric " + str(bisk_metric)) logge...
steps = 0 sample_expected_reward = 0 running_gamma = 1.0 while True: # sample action from the likelihood distribution if self.agent_type == ORACLE: action_id = trajectory[steps] elif self.agent_type == RANDOM_WALK...
chromium/chromium
third_party/android_deps/libs/org_robolectric_shadows_multidex/3pp/fetch.py
Python
bsd-3-clause
2,494
0
#!/usr/bin/env python3 # Copyright 2021 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. # This is generated, do not edit. Update BuildConfigGenerator.groovy and # 3ppFetch.template instead. import argparse import json imp...
IDE_LATEST + f'.{_PATCH_VERSION}') return maven_metadata_url = '{}/{}/{}/maven-metadata.xml'.format( _REPO_URL, _GROUP_NAME, _MODULE_NAME) metadata = urllib.request.urlopen(maven_metadata_url).read().decode( 'utf-8') # Do not parse xml with the python included parser
since it is susceptible # to maliciously crafted xmls. Only use regular expression parsing to be # safe. RE should be enough to handle what we need to extract. match = re.search('<latest>([^<]+)</latest>', metadata) if match: latest = match.group(1) else: # if no latest info was foun...
RadoRado/EuroPython2017
run_python_run/repl/migrations/0001_initial.py
Python
mit
665
0.001504
# -*- coding: utf-8 -*- # Generated by Django 1.11.3 on 2017-07-06 20:01 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel(
name='CodeRun', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('run_id', models.PositiveIntegerField()), ('run_status', models.CharField(max_length=255)),
('output', models.TextField()), ], ), ]
lbenning/Evolutionary
Symbolic Regression/main.py
Python
mit
2,227
0.042209
#! /usr/bin/python from gp import simulate from gp import randomSearch import multiprocessing as mp from plot import graph import sys ''' Main script for execution of genetic program for symbolic regression. Written by Luke Benning Last Edited : 1/16/2015 ''' # Retrieve 2d point data from file def getData(fileName...
tions m > 0 arg4 : Number of interval points to plot i > 0 (in addition to 1) arg5 : Maximum number of processes for multiprocessing pool ''' if __name__ == '__main__': main(sys.argv[1], int(sys.argv[2]), int(sys.argv[3]), int(sys.argv[4]), int(sys.argv[5])
)
stephanehenry27/Sickbeard-anime
sickbeard/scheduler.py
Python
gpl-3.0
2,593
0.002314
# Author: Nic Wolfe <nic@wolfeden.ca> # URL: http://code.google.com/p/sickbeard/ # # This file is part of Sick Beard. # # Sick Beard 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 Lice...
details. # # You should have received a copy of the GNU General Public License # along with Sick Beard. If not, see <http://www.gnu.org/licenses/>. import dateti
me import time import threading import traceback from sickbeard import logger from sickbeard.exceptions import ex class Scheduler: def __init__(self, action, cycleTime=datetime.timedelta(minutes=10), runImmediately=True, threadName="ScheduledThread", silent=False): if runImmediately: self.la...
kxgames/kingdoms-of-life
seacow.py
Python
gpl-2.0
5,188
0.001542
#!/usr/bin/env python import os, kxg, pyglet import tokens, gui, messages class SandboxLoop (kxg.Loop): def __init__(self): world = tokens.World() referee = tokens.Referee() window = pyglet.window.Window() actor = gui.Gui(window) actor.setup_pregame() actors_to_g...
self.host, self.port + 1) def get_successor(self): return self.successor cla
ss ClientConnectionStage (kxg.Stage): def __init__(self, name, host, port): kxg.Stage.__init__(self) self.name = name self.host = host self.port = port self.update = self.update_connection self.client = kxg.network.Client( host, port, callback=self....
stefanv/selective-inference
selection/distributions/discrete_multiparameter.py
Python
bsd-3-clause
8,134
0.003319
""" This module contains a class for discrete multiparameter exponential families. The main use for this is (post-selection) maximum likelihood estimation. Unlike the single parameter family, we do not provide tools for exact hypothesis tests and selection intervals. Approximate (Wald) tests and interva...
setter def theta(self, _theta):
_theta = np.asarray(_theta) if not np.all(np.equal(_theta, self._theta)): _thetaX = np.dot(self.sufficient_stat, _theta) _largest = _thetaX.max() + 4 # try to avoid over/under flow, 4 seems arbitrary _exp_thetaX = np.exp(_thetaX - _largest) _prod = _exp_t...
ArtemMIPT/sentiment_analysis
app.py
Python
mit
4,310
0.00464
import functools import re import os from flask import Flask, render_template, request, jsonify from extensions import db, login_manager, csrf import config from sentiment_classifiers import SentimentClassifier, files, binary_dict from vk_parser import VkFeatureProvider app = Flask(__name__) ########################...
OST': text = request.form['text'] prediction_message = classifier.get_prediction_message(text) return render_template('goods_binary_sentiment.html', text=text, prediction_message=prediction_message) ############################################################################### # ...
############################################################################ @app.route('/algo.html') def algo(): return render_template('algo.html') @app.route('/about.html') def about(): return render_template('about.html') if __name__ == "__main__": app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT' ...
terracoin/terracoin
qa/rpc-tests/nodehandling.py
Python
mit
3,440
0.011047
#!/usr/bin/env python3 # Copyright (c) 2014-2016 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # # Test node handling # from test_framework.test_framework import BitcoinTestFramework from test_framew...
2) #make 100% sure we expired 192.168.0.1 node time #stop node stop_node(self.nodes[2], 2) self.nodes[2] = start_node(2, self.options.tmpdir) listAfterShutdown = self.nodes[2].listbanned() assert_equal("127.0.0.0/24", listAfterShutdown[0]['address']) assert_equal("127.0...
# RPC disconnectnode test # ########################### url = urllib.parse.urlparse(self.nodes[1].url) self.nodes[0].disconnectnode(url.hostname+":"+str(p2p_port(1))) time.sleep(2) #disconnecting a node needs a little bit of time for node in self.nodes[0].getpeerinfo(): ...
15th/simpleat
simpleat/core/log/writer.py
Python
mit
1,220
0.00838
#!/usr/bin/env python #coding=utf-8 # Filename: writer.py ''' 日志记录 @author: 1th @data: 2017.2.28 ''' from time import sleep import datetime from simpleat.conf import settings, globalvar from simpleat.core import exceptions from .logger import write_log _CMD_OUT = settings.CMD_OUT # 是否在命令行进行输出 _LOG_OUT = settings.LOG...
int unicode(wle) def logger(): ''' 自动检查LOG_MESSAGE中是否有需要记录的日志 ''' while True: if not globalvar.g_hold_lognote.empty():
content, level = globalvar.g_hold_lognote.get() if _LOG_OUT: log(content, level) sleep(0.5)
asposecells/Aspose_Cells_Cloud
Examples/Python/Examples/SetModifyPassword.py
Python
mit
1,577
0.008878
import asposecellscloud from asposecellscloud.CellsApi import CellsApi fr
om asposecellscloud.CellsApi import ApiException from asposecellscloud.models import PasswordRequest import asposestoragecloud from asposestoragecloud.StorageApi import StorageApi apiKey = "XXXXX" #sepcify App Key appSid = "XXXXX" #sepcify App SID apiServe
r = "http://api.aspose.com/v1.1" data_folder = "../../data/" #Instantiate Aspose Storage API SDK storage_apiClient = asposestoragecloud.ApiClient.ApiClient(apiKey, appSid, True) storageApi = StorageApi(storage_apiClient) #Instantiate Aspose Cells API SDK api_client = asposecellscloud.ApiClient.ApiClient(apiKey, appSid...
Linkid/fofix
fofix/game/Lobby.py
Python
gpl-2.0
37,782
0.007967
##################################################################### # -*- coding: utf-8 -*- # # # # Frets on Fire X # # Copyright (C) 2006 Sami Kyöstilä ...
e.world.allowGuitar: self.allowed[i] = False else: self.yes.extend([Player.CONTROLS[i][Player.KEY1], Play
er.CONTROLS[i][Player.KEY1A], Player.CONTROLS[i][Player.START]]) self.no.extend([Player.CONTROLS[i][Player.KEY2], Player.CONTROLS[i][Player.KEY2A], Player.CONTROLS[i][Player.CANCEL]]) self.conf.extend([Player.CONTROLS[i][Player.KEY3], Player.CONTROLS[i][Player.KEY3A]]) ...
gtrdotmcs/gunicorn
tests/test_gaiohttp.py
Python
mit
6,628
0.001056
# -*- coding: utf-8 - # # This file is part of gunicorn released under the MIT license. # See the NOTICE for more information. import unittest import pytest aiohttp = pytest.importorskip("aiohttp") from aiohttp.wsgi import WSGIServerHttpProtocol import asyncio from gunicorn.workers import gaiohttp from gunicorn.wor...
'sockets', 'app', 'timeout', Config(), 'log') def tearDown(self): self.loop.close() ...
# to mask incomplete initialization of AiohttWorker instance: # we pass invalid values for ctor args pass self.assertTrue(m_asyncio.get_event_loop.return_value.close.called) self.assertTrue(m_asyncio.new_event_loop.called) self.assertTrue(m_asyncio.set_event_loop.cal...
carlosbeatortega/sociedades
web/node/node_modules/npm/node_modules/node-gyp/legacy/tools/gyp/pylib/gyp/MSVSSettings.py
Python
mit
42,889
0.002868
# Copyright (c) 2011 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. """Code to validate and convert settings of the Microsoft build tools. This file contains code to validate and convert settings of the Microsoft build t...
sbuild_settings.setdefault(tool.msbuild_name, {}) class _Type(object): """Type of settings (Base class).""" def ValidateMSVS(self, value): """Verifies that the value is legal for MSVS. Args: value: the value to check for this type. R
aises: ValueError if value is not valid for MSVS. """ def ValidateMSBuild(self, value): """Verifies that the value is legal for MSBuild. Args: value: the value to check for this type. Raises: ValueError if value is not valid for MSBuild. """ def ConvertToMSBuild(self, value...
MichelDeudon/neural-combinatorial-optimization-rl-tensorflow
Self_Net_TSP/config.py
Python
mit
3,341
0.022448
#-*- coding: utf-8 -*- import argparse import numpy as np parser = argparse.ArgumentParser(description='Configuration file') arg_lists = [] def add_argument_group(name): arg = parser.add_argument_group(name) arg_lists.append(arg) return arg def str2bool(v): return v.lower() in ('true', '1') # Network net...
add_argument_group('User options') ##################################################### misc_arg.add_argument('--inference_mode', type=str2bool, default=True, help='switch to inference mode when model is trained') misc_arg.add_argum
ent('--restore_model', type=str2bool, default=True, help='whether or not model is retrieved') misc_arg.add_argument('--save_to', type=str, default='20/model', help='saver sub directory') misc_arg.add_argument('--restore_from', type=str, default='20/model', help='loader sub directory') ### misc_arg.add_argument('--log...
max1k/cbs
cbs/settings.py
Python
gpl-2.0
2,196
0
""" Django settings for cbs project. For more information on this file, see https://docs.djangoproject.com/en/1.7/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.7/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import...
.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'p311', 'p365', ) MIDDLEWARE_CLASSES = ( 'django.contrib.
sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMi...
mapzen/vector-datasource
integration-test/1178-earlier-piers.py
Python
mit
3,414
0
# -*- encoding: utf-8 -*- from shapely.wkt import loads as wkt_loads import dsl from . import FixtureTest class EarlierPiers(FixtureTest): def test_very_large_pier(self): # a very, very large pier which alters the coastline visually, so # should be kept until z11. self.generate_fixtures(d...
49, -117.175576505495 32.71128
00846483, -117.175587195447 32.71127222384509, -117.174076408802 32.7098766179425, -117.174094464939 32.7098630124915, -117.173743762653 32.70953239939531, -117.173824341534 32.70947366895718, -117.175814469214 32.71132656919218))'), {u'source': u'openstreetmap.org', u'way_area': u'4734.17', u'man_made': u'pier', u'are...
Ecpy/ecpy
exopy/instruments/user.py
Python
bsd-3-clause
1,868
0
# -*- coding: utf-8 -*- # ----------------------------------------------------------------------------- # Copyright 2015-2018 by Exopy Authors, see AUTHORS for more details. # # Distributed under the terms of the BSD license. # # The full license is in the file LICENCE, distributed with this software. # ---------------...
workbench : Application workbench. profiles : list[unicode] List of profiles the manager is requesting the user to release. Returns
------- released_profiles : list[unicode] List of the profiles that have been released. """ raise NotImplementedError()
battlemidget/conjure-up
macumba/ws.py
Python
mit
2,690
0
from ws4py.client.threadedclient import WebSocketClient import json import threading import logging from .errors import ConnectionClosedError, UnknownRequestError log = logging.getLogger('macumba') class JujuWS(WebSocketClient): def __init__(self, url, password, protocols=['https-only'],
extensions=None, ssl_options=None, headers=None, start_reqid=1): WebSocketClient.__init__(self, url, protocols, extensions, ssl_options=ssl_options, headers=headers) self.open_done = threading.Event() self.rid_lock = threading.RLock() ...
_id = start_reqid # WebSocketClient subclass overrides, run in private thread: def opened(self): self.open_done.set() def received_message(self, m): msg = json.loads(m.data.decode('utf-8')) msg_req_id = msg['RequestId'] with self.msglock: self.messages[msg_req_i...
sysr-q/fah
fah/room.py
Python
mit
759
0.02635
#!/usr/bin/env python2 from __future__ import print_function from collections import defaultdict import uuid class Room(object): def __init__(self): self.name = None self.users = {}
self.expansions = [0] # 0 -> Base class User(object): def __init__(self, handle, trip=None, first=False): self.uuid = uuid.uuid4() self.handle = handle self.trip = trip se
lf.first = first self.rooms = [] # {name: _, owner: _} self.cards = [] # list of ids (usually 10) # NOTE: don't remove these, they might keep shit working. Can't remember. # Sorry, future maintainer(s). def __new__(cls, *args, **kwargs): return super(User, cls).__new__(cls, *args, **kwargs) def __co...
fkolacek/FIT-VUT
bp-revok/python/lib/python2.7/site-packages/cryptography-0.5.2-py2.7-linux-x86_64.egg/cryptography/hazmat/primitives/serialization.py
Python
apache-2.0
909
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...
_key(data, password, backend): return backend.load_traditional_openssl_pem_private_key( data, password ) def load_pem_pkc
s8_private_key(data, password, backend): return backend.load_pkcs8_pem_private_key( data, password )
tanutarou/OptBoard
optboard/wsgi.py
Python
mit
394
0
""" WSGI config for optboard project. It exposes the WSGI callable as a module-leve
l variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.11/howto
/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "optboard.settings") application = get_wsgi_application()
zozo123/buildbot
master/buildbot/schedulers/base.py
Python
gpl-3.0
10,933
0.000823
# This file is part of Buildbot. Buildbot 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, version 2. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without eve...
ption is complete before we are done stopping consumption def stop(): if self._change_c
onsumer: self._change_consumer.stopConsuming() self._change_consumer = None return self._change_consumption_lock.run(stop) def gotChange(self, change, important): raise NotImplementedError # starting builds def addBuildsetForSourceStampsWithDefaults(self, r...
CrowdStrike/mellon
mellon/interfaces.py
Python
mit
4,243
0.007778
from zope import component from zope import interface from zope.interface.interfaces import IObjectEvent from zope import location from sparc.configuration.container import ISparcPyContainerConfiguredApplication #EVENTS class ISnippetAvailableForSecretsSniffEvent(IObjectEvent): """An object providing ISnippet is r...
interface.Attribute("Number of read_size data packets to jump after "+ "snippet return.") snippet_bytes_coverage = \ interface.Attribute("Number of read_size data packets to include in "+ "each snippet. 0 indicates all data packets.") class IB...
hecker""" def check(): """True indicates the data was found to be binary""" # SNIFFERS, SECRETS, WHITELISTS class ISecretSniffer(interface.Interface): """Looks for a secret""" def __iter__(): """Iterator of found ISecret providers""" class ISecret(location.ILocation): """A secret found...
PGer/incubator-hawq
tools/bin/gppylib/parseutils.py
Python
apache-2.0
22,013
0.005497
#!/usr/bin/env python # Line too long - pylint: disable=C0301 # Invalid name - pylint: disable=C0103 """ parseutils.py Routines to parse "flexible" configuration files for tools like gpaddmirrors, gprecoverseg, gpexpand, etc. Copyright (c) EMC/Greenplum Inc 2011. All Rights Rese...
ith('['): return None, rest, 'does not begin with [' p = rest.find(']') if p < 0: return None, rest, 'does not contain ending ]' if len(rest[p+1:]) < 1: return rest[1:p], None, None if rest[p+1] != delimiter: return None, rest, 'characters not allowed after ending ]' ...
one def read_to_possibly_bracketed(delimiter, rest): """ Behave as read_bracketed above when rest starts with a '[', otherwise as read_to_colon. This is intended to support fields which may contain an IPv6 address, an IPv4 address or a hostname. Examples -------- >>> read_to_possibly_b...
yieldbot/singularity-py
singularity/commands/cmd_request.py
Python
mit
10,225
0.004988
import click from json import dumps, load import os import sys from tabulate import tabulate @click.group('request') @click.pass_context def cli(ctx): pass @cli.command(name='unpause', help='Unpause a request') @click.argument('request-id') @click.pass_context def request_unpause(ctx, request_id): res = ctx.o...
g=True, default=False, help='Kill tasks when paused') @click.argument('request-id') @click.pass_context def request_pause(ctx, request_id, kill_tasks): res = ctx.obj['client'].pause_request(request_id, kill_tasks) if 'error' in res: click.echo('error during pause request {0}: {1}'.format(request_id, res...
else: click.echo('paused request {0} with killTasks={1}'.format(request_id, kill_tasks)) @cli.command(name='scale', help='Scale a request up/down') @click.argument('request-id') @click.argument('instances', '-i', type=click.INT) @click.pass_context def request_scale(ctx, request_id, instances): res = c...
ChuanleiGuo/AlgorithmsPlayground
LeetCodeSolutions/python/72_Edit_Distance.py
Python
mit
727
0
class Solution(object): def minDistance(self, word1, word2): """ :type word1: str :type word2: str :rtype:
int """ row = len(word1) + 1 col = len(word2) + 1 dp = [[0] * col for _ in range(row)] for i in range(col): dp[0][i] = i for i in range(row): dp[i][0] = i for i in range(1, row): for j in range(1, col): if w...
lse: dp[i][j] = dp[i - 1][j - 1] + 1 dp[i][j] = min(dp[i][j], dp[i - 1][j] + 1, dp[i][j - 1] + 1) return dp[row - 1][col - 1]
joergkappes/opengm
src/interfaces/python/opengm/__init__.py
Python
mit
10,979
0.027689
#from opengmcore import _opengmcore.adder as adder from opengmcore import * from __version__ import version from functionhelper import * from _inf_param import _MetaInfParam , InfParam from _visu import visualizeGm from _misc ...
adder instead? (inference.adder.logsumexp.solver.__dict__, 'adder', 'logsumexp'), (inference.multiplier.minimizer.solver.__dict__, 'multiplier', 'minimizer' ), (inference.multiplier.maximizer.solver.__dict__, 'multiplier', 'maximizer' ), (inference.multiplier.integrator.solver.__dict__,'multip...
s class Timer: def __init__(self, name=None , verbose = True): self.name = name self.verbose = verbose def __enter__(self): if self.name and self.verbose: print '[%s]' % self.name self.tstart = time.time() return self def __exit__(self, type, value, tr...
Titan-C/scikit-learn
sklearn/feature_selection/tests/test_mutual_info.py
Python
bsd-3-clause
6,881
0
from __future__ import division import numpy as np from numpy.testing import run_module_suite from scipy.sparse import csr_matrix from sklearn.utils.testing import (assert_array_equal, assert_almost_equal, assert_false, assert_raises, assert_equal, ...
ef test_mutual_info_classif_discrete(): X = np.array([[0, 0, 0], [1, 1, 0], [2, 0, 1], [2, 0, 1], [2, 0, 1]]) y = np.array([0, 1, 2, 2, 1]) # Here X[:, 0] is the most informative feature, and X[:, 1] is weakly # informative. mi...
l_info_regression(): # We generate sample from multivariate normal distribution, using # transformation from initially uncorrelated variables. The zero # variables after transformation is selected as the target vector, # it has the strongest correlation with the variable 2, and # the weakest correla...
crossbario/crossbarexamples
xbr/teststack1/_init/set_xbrmm_key.py
Python
apache-2.0
521
0.007678
import sys import binascii from init_data import MARKETS xbrmm_key_file = sys.argv[1] #from init_data import ACCOUNTS, _ACCOUNT_K
EYS #xbr_marketmaker = 'marketop1-marketmaker1' #addr, pkey = _ACCOUNT_KEYS[ACCOUNTS[xbr_marketmaker]] addr = MARK
ETS[0]['maker'] pkey = MARKETS[0]['maker_pkey'] print(xbrmm_key_file) with open(xbrmm_key_file, 'wb') as f: pkey = binascii.a2b_hex(pkey[2:]) f.write(pkey) print('XBR market maker with address 0x{}: private key written to file "{}"'.format(addr, xbrmm_key_file))
killbill/killbill-client-python
killbill/models/tenant_key_value.py
Python
apache-2.0
4,248
0.001177
# coding: utf-8 # # Copyright 2010-2014 Ning, Inc. # Copyright 2014-2020 Groupon, Inc # Copyright 2020-2021 Equinix, Inc # Copyright 2014-2021 The Billing Project, LLC # # The Billing Project, LLC licenses this f
ile to you 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 t...
ND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # """ Kill Bill Kill Bill is an open-source billing and payments platform # noqa: E501 OpenAPI spec version: 0.22.22-SNAPSHOT Generated by: https://github.com/s...