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
Chilledheart/chromium
tools/perf/page_sets/alexa1-10000.py
Python
bsd-3-clause
1,340
0.005224
# Copyright 2014 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. import json import os from telemetry.page import page as page_module from telemetry.page import shared_page_state from telemetry import story __location__ ...
. _TOP_10000_ALEXA_FILE = os.path.join(__location__, 'alexa1-10000-urls.
json') class Alexa1To10000Page(page_module.Page): def __init__(self, url, page_set): super(Alexa1To10000Page, self).__init__( url=url, page_set=page_set, shared_page_state_class=shared_page_state.SharedDesktopPageState) def RunPageInteractions(self, action_runner): with action_runner.Cre...
yola/hashcache
hashcache/hashcache.py
Python
mit
1,100
0.008182
from django.core.cache import cache as cache_impl from django.utils.encoding import smart_str import hashlib class Hashcache(object): """ Wrapper for django.core.cache.cache that hashes the keys to avoid key length errors. Maybe eventually it will do other cool things. You can optionally pass you...
he django cache module. >>> from yolango.util.hashcache import Hashcache >>> cache = Hashcache() >>> cache.set('my_key', 'hello, world!', 30) >>> cache.get('my_key') 'hello, world!' """
def __init__(self, cache = cache_impl): assert cache self.cache = cache def get(self, key): """Hash the key and retrieve it from the cache""" return self.cache.get(self._hashed(key)) def set(self, key, *args): """Hash the key and set it in the cache"""...
ic-labs/glamkit-sponsors
sponsors/__init__.py
Python
mit
52
0
defaul
t_app_config = '%s.apps.AppConfig' %
__name__
Orav/kbengine
kbe/src/lib/python/Lib/test/test_importlib/namespace_pkgs/project3/parent/child/three.py
Python
lgpl-3.0
29
0
attr
= 'parent child t
hree'
SunPower/PVMismatch
pvmismatch/contrib/gen_coeffs/two_diode.py
Python
bsd-3-clause
11,016
0.002179
""" Two diode model equations. """ import numpy as np from pvmismatch.contrib.gen_coeffs import diode def fdidv(isat1, isat2, rs, rsh, ic, vc, vt): """ Derivative of IV curve and its derivatives w.r.t. Isat1, Isat2, Rs, Rsh, Ic, Vc and Vt. :param isat1: diode 1 saturation current [A] :param isat...
[put condition here]. """ didv, _ = fdidv(isat1, isat2, rs, rsh, ic=isc, vc=0, vt=vt) vd, _ = diode.fvd(0.0, isc, rs) # vd = vc + ic * rs
= 0.0 + isc * rs # frsh = rsh + 1/didv frsh = vd * (1.0/rsh + didv) dfrsh_isat1 = vd*( 2.0*rs*rsh*( 2.0*isat1*rsh*np.exp(vd/vt) + isat2*rsh*np.exp(0.5*vd/vt) + 2.0*vt )*np.exp(vd/vt)/( 2.0*isat1*rs*rsh*np.exp(vd/vt) + isat2*rs*rsh*np.exp(0.5*vd/vt) + 2.0*...
yast/yast-python-bindings
examples/CheckBoxFrame1.py
Python
gpl-2.0
729
0.00823
# encoding: utf-8 from yast import import_module import_module('UI') from yast import * class CheckBoxFrame1Client: def main(self): UI.OpenDialog( VBox( MarginBox( 1, 0.5, CheckBoxFrame(
"E&xpert Settings", True, VBox( HBox( InputField("&Server"), ComboBox("&Mode", ["Automatic", "Manual", "Debug"])
), Left(CheckBox("&Logging")), InputField("&Connections") ) ) ), PushButton("&OK") ) ) UI.UserInput() UI.CloseDialog() CheckBoxFrame1Client().main()
prozorro-sale/openprocurement.auctions.dgf
openprocurement/auctions/dgf/tests/blanks/bidder_blanks.py
Python
apache-2.0
36,337
0.003444
# -*- coding: utf-8 -*- from copy import deepcopy from openprocurement.auctions.dgf.tests.base import ( test_auction_data, test_features_auction_data, test_financial_organization, test_financial_auction_data, test_bids, test_financial_bids, test_organization ) from openprocurement.api.tests...
lid(self): response = self.app.post_json('/auctions/some_id/bids', { 'data': {'tenderers': [self.initial_organization], "value": {"amount": 500}, 'qualified': True}}, status=404) self.assertEqual(response.status, '404 Not Found') self.assertEqual(response.content_type, 'application/json') self.a...
], [ {u'description': u'Not Found', u'location': u'url', u'name': u'auction_id'} ]) request_path = '/auctions/{}/bids'.format(self.auction_id) response = self.app.post(request_path, 'data', status=415) self.assertEqual(response.status, '415 Unsupported Media Type') self.assertEq...
LLNL/spack
var/spack/repos/builtin/packages/py-azure-mgmt-appconfiguration/package.py
Python
lgpl-2.1
985
0.00203
# Co
pyright 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) class PyAzureMgmtAppconfiguration(PythonPackage): """Microsoft Azure App Configuration Management Client Library for Pyth...
pi = "azure-mgmt-appconfiguration/azure-mgmt-appconfiguration-0.5.0.zip" version('0.5.0', sha256='211527511d7616a383cc196956eaf2b7ee016f2367d367924b3715f2a41106da') version('0.4.0', sha256='85f6202ba235fde6be274f3dec1578b90235cf31979abea3fcfa476d0b2ac5b6') depends_on('py-setuptools', type='build') dep...
EnSpec/SpecDAL
specdal/tests/test_groupby.py
Python
mit
1,667
0.0024
import os import sys import numpy as np import pandas as pd import pandas.util.testing as pdt import unittest sys.path.insert(0, os.path.abspath("../../")) from specdal.spectrum import Spectrum from specdal.collection import Collection class GroupByTests(unittest.TestCase): def setUp(self): # total 36 spe...
ps(self): groups = self.c.groupby(separator='_', indices=[0, 2]) for s in groups['A_0'].spectra: print(s.name) ''' def test_num_groups(self):
groups = self.c.groupby(separator='_', indices=[0]) self.assertEqual(len(groups), 3) groups = self.c.groupby(separator='_', indices=[1]) self.assertEqual(len(groups), 3) groups = self.c.groupby(separator='_', indices=[2]) self.assertEqual(len(groups), 4) groups = sel...
simon3z/virt-deploy
virtdeploy/errors.py
Python
gpl-2.0
1,201
0
# # Copyright 2015 Red Hat, Inc. # # 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 distributed in th...
, Boston, MA 02110-1301 USA # # Refer to the README and COPYING files for full details of the license # from __future__ import absolute_import class VirtDeployException(Exception): def __init__(self, message="Unknown error"): self.message = message def __str__(self): return self.message cl...
): super(InstanceNotFound, self).__init__( 'No such instance: {0}'.format(name))
zkota/pyblio-1.3
Legacy/Iterator.py
Python
gpl-2.0
2,270
0.01674
# This file is part of pybliographer # # Copyright (C) 1998-2004 Frederic GOBRY # Email : gobry@pybliographer.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 2 # of t...
ition += 1 def first (self): self.count = 0 return self.next () def next (self
): try: entry = self.database [self.keys [self.count]] except IndexError: entry = None self.count = self.count + 1 return entry
cmunk/protwis
build_gpcr/management/commands/build_drugs.py
Python
apache-2.0
109
0.009174
from build.management.comm
ands.build_drugs import Command as BuildDru
gs class Command(BuildDrugs): pass
pajlada/pajbot
pajbot/modules/maxmsglength.py
Python
mit
4,608
0.002821
import logging from datetime import timedelta from pajbot.managers.handler import HandlerManager from pajbot.modules import BaseModule from pajbot.modules import ModuleSetting log = logging.getLogger(__name__) class MaxMsgLengthModule(BaseModule): ID = __name__.split(".")[-1] NAME = "Maximum Message Lengt...
tings["disable_warnings"] is True: self.bot.timeout(source, self.settings["timeout_length"], reason=self.settings["timeout_reason"]) else: duration, punishment = self.bot.timeout_warn( source, self.settings["timeout_length"], reason=self.se...
one hour watching the stream. """ if duration > 0 and source.time_in_chat_online >= timedelta(hours=1): self.bot.whisper(source, self.settings["whisper_timeout_reason"].format(punishment=punishment)) return False else: if...
takahashikenichi/mozc
src/build_tools/copy_qt_frameworks_mac.py
Python
bsd-3-clause
4,010
0.008229
# -*- coding: utf-8 -*- # Copyright 2010-2015, Google Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this...
ectory. Typical usage: % python copy_qt_frameworks.py --qtdir=/path/to/qtdir/ \ --target=/path/to/target.app/Contents/Frameworks/ """ __author__ = "horo" import optparse import os from copy_file import CopyFiles from util import PrintErrorAndExit from util import RunOrDie def ParseOption(): """Parse co...
r.parse_args() return opts def main(): opt = ParseOption() if not opt.qtdir: PrintErrorAndExit('--qtdir option is mandatory.') if not opt.target: PrintErrorAndExit('--target option is mandatory.') qtdir = os.path.abspath(opt.qtdir) target = os.path.abspath(opt.target) # Copies QtCore. For ...
ibc/MediaSoup
worker/deps/gyp/test/external-cross-compile/src/tochar.py
Python
isc
317
0.003155
#!/usr/bin/python # Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is go
verned by a BSD-style license that can be # found in the LICENSE file. import sys src = open(sys.argv[1])
dst = open(sys.argv[2], 'w') for ch in src.read(): dst.write('%d,\n' % ord(ch)) src.close() dst.close()
googleapis/python-data-qna
samples/generated_samples/dataqna_generated_dataqna_v1alpha_question_service_create_question_sync.py
Python
apache-2.0
1,661
0.000602
# -*- coding: utf-8 -*- # 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, 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...
kchodorow/tensorflow
tensorflow/contrib/bayesflow/python/kernel_tests/stochastic_variables_test.py
Python
apache-2.0
6,122
0.00539
# Copyright 2016 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...
e.variable_scope( "stochastic_variables", custom_getter=sv.make_stochastic_variable_getter( dist_cls=dist.
NormalWithSoftplusScale, prior=prior_init)): w = variable_scope.get_variable("weights", (10, 20)) x = random_ops.random_uniform((8, 10)) y = math_ops.matmul(x, w) prior_map = vi._find_variational_and_priors(y, None) self.assertTrue(isinstance(prior_map[w], dist.Normal)) elbo = vi.elbo(y, kee...
kanellov/openstack_project_create
openstack_project_create/receivers.py
Python
mit
162
0.006173
fro
m django.dispatch import receiver from signals import sch_create_project @receiver(project_created) def project_networking(sender, **kwargs): return T
rue
UdK-VPT/Open_eQuarter
mole/extensions/eval_present_heritage/oeq_UPH_Wall.py
Python
gpl-2.0
2,921
0.008216
# -*- coding: utf-8 -*- import os,math from qgis.core import NULL from mole import oeq_global from mole.project import config from mole.extensions import OeQExtension from mole.stat_corr import rb_present_wall_uvalue_AVG_by_building_age_lookup, nrb_present_wall_uvalue_by_building_age_lookup, rb_contemporary_wall_uvalu...
if parameters['BLD_USAGE'] == "RB": if pa
rameters['HERIT_STAT'] == "0": if not oeq_global.isnull(parameters['YOC']): wl_uph = rb_present_wall_uvalue_AVG_by_building_age_lookup.get(parameters['YOC']) else: if not oeq_global.isnull(parameters['YOC']): wl_uph = rb_contemporary_wall_uvalue_by_buildin...
teppchan/tkintertips
py/label/align.py
Python
mit
166
0.024096
#!/usr/bin/env python import Tkinter as Tk roo
t=Tk.Tk() l=Tk.Label(root, text="Python\nPerl\n
C", justify="right", ) l.pack() root.mainloop()
vls/python_utils
log_handlers.py
Python
unlicense
1,677
0.003578
from logging.handlers import BaseRotatingHandler import string import time import datetime import os class TimePatternRotatingHandler(BaseRotatingHandler
): def __init__(self, filename, when, encoding=None, delay=0): self.when = string.upper(when) self.fname_pat = filename self.mock_dt = None self.computeNextRollover() BaseRotatingHandler.__init__(self, self.filename, 'a', encoding, delay) def get_now_dt(self):
if self.mock_dt is not None: return self.mock_dt return datetime.datetime.now() def computeNextRollover(self): now = self.get_now_dt() if self.when == 'MONTH': dtfmt = '%Y-%m' dt = (now.replace(day=1) + datetime.timedelta(days=40)).replace(day=1, hour=0,...
Williams224/davinci-scripts
kstaretappipig/MC_12_MagDown_kstar_rho_kpipipi.py
Python
mit
12,721
0.027121
#-- GAUDI jobOptions generated on Wed Jun 10 17:31:51 2015 #-- Contains event types : #-- 11104041 - 117 files - 2010995 events - 432.61 GBytes #-- Extra information about the data processing phases: #-- Processing Pass Step-124834 #-- StepId : 124834 #-- StepName : Reco14a for MC #-- ApplicationName : ...
sion : v43r2p7 #-- OptionFiles : $APPCONFIGOPTS/Brunel/DataType-2012.py;$APPCONFIGOPTS/Brunel/MC-WithTruth.py;$APPCONFIGOPTS/Persistency/Compression-ZLIB-1.py #-- DDDB : fromPreviousStep #-- CONDDB : fromPreviousStep #-- ExtraPackages : AppConfig.v3r164 #-- Visible : Y #-- Processing Pass Step-124620 #-...
ApplicationName : Boole #-- ApplicationVersion : v26r3 #-- OptionFiles : $APPCONFIGOPTS/Boole/Default.py;$APPCONFIGOPTS/Boole/DataType-2012.py;$APPCONFIGOPTS/Boole/Boole-SiG4EnergyDeposit.py;$APPCONFIGOPTS/Persistency/Compression-ZLIB-1.py #-- DDDB : fromPreviousStep #-- CONDDB : fromPreviousStep #-- ExtraPa...
Stiivi/brewery
examples/merge_multiple_files/merge_multiple_files.py
Python
mit
2,107
0.005695
""" Brewery Example - merge multiple CSV files Input: Multiple CSV files with different fields, but with common subset of fields. Output: Single CSV file with all fields from all files and with additional column with origin file name Run: $ python merge_multiple_files.py Afterwards display ...
= source["file"] # Initialize data source: skip reading of headers - we are preparing them ourselves # use XLSDataSource for XLS files # We ignore the fields in the header, because we have set-up fields
# previously. We need to skip the header row. src = ds.CSVDataSource(path,read_header=False,skip_rows=1) src.fields = ds.FieldList(source["fields"]) src.initialize() for record in src.records(): # Add file reference into ouput - to know where the row comes from record["file"] = p...
psicobyte/ejemplos-python
cap5/p54.py
Python
gpl-3.0
77
0
#
!/usr/bin/python # -*- coding: utf-8 -
*- un_numero = 75 otro_numero = -134
hycis/TensorGraph
tensorgraph/trainobject.py
Python
apache-2.0
3,080
0.003896
from .stopper import EarlyStopper from .progbar import ProgressBar from .utils import split_arr from .data_iterator import SequentialIterator from tensorflow.python.framework import ops import tensorflow as tf import logging logging.basicConfig(format='%(module)s.%(funcName)s %(lineno)d:%(message)s', level=logging.INF...
_arr) iter_train = SequentialIterator(*train_arrs, batchsize=batchsize) iter_valid = SequentialIterator(*valid_arrs
, batchsize=batchsize) es = EarlyStopper(max_epoch, epoch_look_back, percent_decrease) # required for BatchNormalization layer update_ops = ops.get_collection(ops.GraphKeys.UPDATE_OPS) with ops.control_dependencies(update_ops): train_op = optimizer.minimize(train_cost_sb) init = tf.global...
arju88nair/projectCulminate
venv/lib/python3.5/plat-x86_64-linux-gnu/_sysconfigdata_m.py
Python
apache-2.0
21,469
0.032559
# system configuration generated and used by the sysconfig module build_time_vars = {'ABIFLAGS': 'm', 'AC_APPLE_UNIVERSAL_BUILD': 0, 'AIX_GENUINE_CPLUSPLUS': 0, 'AR': 'x86_64-linux-gnu-gcc-ar', 'ARFLAGS': 'rc', 'ASDLGEN': 'python3.5 ../Parser/asdl_c.py', 'ASDLGEN_FILES': '../Parser/asdl.py ../Parser/asdl_c.py', ...
AVE_IPA_PURE_CONST_BUG': 0, 'HAVE_KILL': 1, 'HAVE_KILLPG': 1, 'HAVE_KQUEUE': 0, 'HAVE_LANGINFO_H': 1, 'HAVE_LARGEF
ILE_SUPPORT': 0, 'HAVE_LCHFLAGS': 0, 'HAVE_LCHMOD': 0, 'HAVE_LCHOWN': 1, 'HAVE_LGAMMA': 1, 'HAVE_LIBDL': 1, 'HAVE_LIBDLD': 0, 'HAVE_LIBIEEE': 0, 'HAVE_LIBINTL_H': 1, 'HAVE_LIBREADLINE': 1, 'HAVE_LIBRESOLV': 0, 'HAVE_LIBSENDFILE': 0, 'HAVE_LIBUTIL_H': 0, 'HAVE_LINK': 1, 'HAVE_LINKAT': 1, 'HAVE_LINUX_CAN_B...
dietrichc/streamline-ppc-reports
examples/adwords/v201406/basic_operations/add_ad_groups.py
Python
apache-2.0
2,698
0.004077
#!/usr/bin/python # # 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 b...
nfiguration': { 'bids': [ { 'xsi_type': 'CpcBid', 'bid': { 'microAmount': '1000000' }, } ] } } }, { 'operator': 'ADD', 'operand': { ...
to Venus Cruises #%s' % uuid.uuid4(), 'status': 'ENABLED', 'biddingStrategyConfiguration': { 'bids': [ { 'xsi_type': 'CpcBid', 'bid': { 'microAmount': '1000000' } ...
t3dev/odoo
addons/website_slides_survey/models/slide_channel.py
Python
gpl-3.0
488
0.004098
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details
. from odoo import fields, models class Channel(models.Model): _inherit = 'slide.channel' nbr_certification = fields.Integer("Number of Certifications", compute='_compute_slides_statistics', store=True) class Category(models.Model): _inherit = 'slide.category' nbr_certification = fields.Integer("...
e)
mvidalgarcia/indico
indico/modules/users/models/suggestions.py
Python
mit
2,186
0.002287
# This file is part of Indico. # Copyright (C) 2002 - 2019 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. from __future__ import unicode_literals from indico.core.db import db from indico.util.string import form...
nt=False ) is_ignored = db.Column(
db.Boolean, nullable=False, default=False ) score = db.Column( db.Float, nullable=False, default=0 ) category = db.relationship( 'Category', lazy=False, backref=db.backref( 'suggestions', lazy=True, ca...
robocomp/learnbot
learnbot_dsl/learnbotCode/VisualBlock.py
Python
gpl-3.0
29,715
0.00313
from __future__ import print_function, absolute_import from PySide2 import QtGui,QtCore,QtWidgets from math import * import pickle, os, json import learnbot_dsl.guis.EditVar as EditVar from learnbot_dsl.learnbotCode.Block import * from learnbot_dsl.learnbotCode.Language import getLanguage from learnbot_dsl.learnbotCode...
.typeBlock self.__type = self.parentBlock.type self.id = self.parentBlock.id self.connections = self.parentBlock.connections
self.highlighted = False for c in self.connections: c.setParent(self.parentBlock) self.dicTrans = parentBlock.dicTrans self.shouldUpdate = True if len(self.dicTrans) is 0: self.showtext = self.parentBlock.name else: self.showtext = self.dicT...
nailor/filesystem
filesystem/test/test_copyonwrite_mkdir.py
Python
mit
686
0.002915
from __future__ import with_statement from nose.tools import ( eq_ as eq, ) from filesystem.test.util import ( maketemp, assert_raises, ) import errno import os import filesystem import filesystem.copyonwrite def test_mkdir(): tmp = maketemp() filesystem.copyonwrite.path(filesystem.path...
, 'foo') assert not os.path.isdir(foo) def test_mkdir_bad_exists(): tmp = maketemp() p = filesystem.copyonwrite.path(filesystem.path(tmp)).child('foo') with p.open('w') as f: f.write('bar') e = assert_raises( OSError, p.mkdir,
) eq(e.errno, errno.EEXIST)
reflection/elasticsearch-dsl-py
elasticsearch_dsl/query.py
Python
apache-2.0
5,587
0.00358
from .utils import DslBase, BoolMixin, _make_dsl_class from .function import SF, ScoreFunction __all__ = [ 'Q', 'Bool', 'Boosting', 'Common', 'ConstantScore', 'DisMax', 'Filtered', 'FunctionScore', 'Fuzzy', 'FuzzyLikeThis', 'FuzzyLikeThisField', 'GeoShape', 'HasChild', 'HasParent', 'Ids', 'Indices', 'Match...
# not all are required, add a should list to the must with proper min_should_match else: q.must.append(Bool(should=qx.should, minimum_should_match=min_should_match)) else: q.must.append(other) return q __rand__ = __and__ # register thi...
lter'}, 'functions': {'type': 'score_function', 'multi': True}, } def __init__(self, **kwargs): if 'functions' in kwargs: pass else: fns = kwargs['functions'] = [] for name in ScoreFunction._classes: if name in kwargs: ...
barentsen/k2flix
k2flix/__init__.py
Python
mit
99
0.010101
#!/usr/bin/env python # -*- coding: utf-8 -*- from .version import __version__ from .core im
port *
maas/python-libmaas
maas/client/viscera/tests/test_boot_sources.py
Python
agpl-3.0
5,431
0.000368
"""Test for `maas.client.viscera.boot_sources`.""" import random from testtools.matchers import Equals, MatchesStructure from .. import boot_sources from ...testing import make_name_without_spaces, TestCase from ..testing import bind def make_origin(): # Create a new origin with BootSources and BootSource. The...
"keyring_filename": keyring_filename, "keyring_data": "", } source = BootSources.create(url, keyring_filename=keyring_filename) BootSources._handler.create.assert_called_once_with( url=url, keyring_filename=keyring_filename, keyring_data="" ) self.a...
sStructure.byEquality( id=source_id, url=url, keyring_filename=keyring_filename, keyring_data="", ), ) def test__create_calls_create_with_keyring_data(self): source_id = random.randint(0, 100) url = "http://images.m...
oscarlazoarjona/fast
fast/config.py
Python
gpl-3.0
1,912
0
# -*- coding: utf-8 -*- # *********************************************************************** # Copyright (C) 2014 - 2017 Oscar Gerardo Lazo Arjona * # <oscar.lazo@correo.nucleares.unam.mx> * # *...
********************************************************************** """The basic configuration of FAST.""" from fast import __file__ # Whether to use parallelization through OpenMP. parallel = True parallel = False # Whether to use NETCDF binary files
for data communication. use_netcdf = True use_netcdf = False # An integer between 0 and 2 to control which tests are ran. run_long_tests = 0 # The install directory for FAST: fast_path = __file__[:-len("__init__.pyc")]
JamesLinEngineer/RKMC
addons/plugin.video.phstreams/resources/lib/modules/proxy.py
Python
gpl-2.0
2,896
0.013812
# -*- coding: utf-8 -*- ''' Exodus Add-on Copyright (C) 2016 Exodus This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your opti...
result): return result.decode('iso-8859-1').encode('utf-8') except: pass def get(): return random.choice([ 'http://4freeproxy.com/browse.php?b=20&u=', 'https://www.3proxy.us/index.php?hl=2e5&q=', 'https://www.4proxy.us/index.php?hl=2e5&q=', 'http://www.accessmeproxy.
net/browse.php?b=20&u=', 'http://buka.link/browse.php?b=20&u=', 'http://fastrow.win/browse.php?b=20&u=', 'http://free-proxyserver.com/browse.php?b=20&u=', 'http://www.ipunblocker.com/browse.php?b=20&u=', 'http://www.mybriefonline.xyz/browse.php?b=20&u=', 'http://www.navigate-online.xyz/bro...
tech-teach/microservice-topology
tasks/core/cmetrics_run_test.py
Python
mit
878
0.003417
from ctyp
es import * import json import ast NN = CDLL('./libNN.so') for distance in range(15): file_rows = open("Data/tecator.csv", 'r').read().split('\n') file_con
tent = [ float(value) for row in file_rows for value in row.split(',') if value != '' ] numfil = len(file_rows) - 1 numcol = len(file_rows[0].split(',')) file_content_c = ( (c_float * len(file_content))(*file_content) ) NN.main.restype=c_char_p prin...
solashirai/edx-platform
lms/djangoapps/ccx/tests/test_models.py
Python
agpl-3.0
10,002
0.0007
""" tests for the models """ import json from datetime import datetime, timedelta from django.utils.timezone import UTC from mock import patch from nose.plugins.attrib import attr from student.roles import CourseCcxCoachRole from student.tests.factories import ( AdminFactory, ) from util.tests.test_date_utils impor...
se(self.ccx.has_started()) # pylint: disable=no-member def test_ccx_has_ended(self): """verify that a ccx that has a due date in the past has ended""" now = datetime.now(UTC()) delta = timedelta(1) then = now - delta self.set_ccx_override('due', then) self.assertTru...
"" now = datetime.now(UTC()) delta = timedelta(1) then = now + delta self.set_ccx_override('due', then) self.assertFalse(self.ccx.has_ended()) # pylint: disable=no-member def test_ccx_without_due_date_has_not_ended(self): """verify that a ccx without a due date has ...
titilambert/home-assistant
homeassistant/components/homeassistant/triggers/time.py
Python
apache-2.0
4,049
0.000247
"""Offer time listening automation rules.""" from datetime import datetime import logging import voluptuous as vol from homeassistant.const import CONF_AT, CONF_PLATFORM from homeassistant.core import callback from homeassistant.helpers import config_validation as cv from homeassistant.helpers.event import ( asyn...
tes["minute"] second
= new_state.attributes["second"] else: # If no time then use midnight. hour = minute = second = 0 if has_date: # If input_datetime has date, then track point in time. trigger_dt = dt_util.DEFAULT_TIME_ZONE.localize( ...
dcjohnston/geojs
dashboard/github_service/dashboard.py
Python
bsd-3-clause
5,762
0
#!/usr/bin/env python import os import shutil import socket from datetime import datetime import subprocess as sp import json from pymongo import MongoClient _ctest = ''' set(CTEST_SOURCE_DIRECTORY "{source}") set(CTEST_BINARY_DIRECTORY "{build}") include(${{CTEST_SOURCE_DIRECTORY}}/CTestConfig.cmake) set(CTEST_SI...
esult['status'] = status results.insert(result) queue.remove(item) notify(item, status) def continuous(sha, branch, user, queue, results): oldTest = results.find_one({'commit': sha}) item = { 'commit
': sha, 'user': user, 'branch': branch, 'time': datetime.now() } status = start_test(item, oldTest) if not oldTest: result = dict(item) result['time'] = datetime.now() result['status'] = status results.insert(result) notify(item, status) return...
bjuvensjo/scripts
vang/misc/s.py
Python
apache-2.0
1,135
0
#!/usr/bin/env python3 from argparse import ArgumentParser from re import compile from sys import argv def get_split(s): for ch in ('_', '-'): if ch in s: return s.split(ch) return compile('[A-Z]?[^A-Z]+').findall(s) def get_cases(s): split = get_split(s) capital = [w.capitalize(...
r[0]] + capital[1:]), ''.join(capital), ''.join(lower), ''.join(upper), '_'.join(lower), '_'.join(upper), '-'.join(lower), '-'.join(upper), ] def get_zipped_cases(strings): return zip(*[get_cases(s) for s in strings]) def parse_args(args): parser =...
('strings', nargs='+') return parser.parse_args(args) def main(strings): for items in get_zipped_cases(strings): print(' '.join(items)) if __name__ == '__main__': # pragma: no cover main(**parse_args(argv[1:]).__dict__)
sidnarayanan/BAdNet
train/gen/akt/paths.py
Python
mit
125
0
basedir =
'/data/t3serv014/snarayan/deep/v_deepgen_4_akt_small/' figsdir = '/home/snarayan/public_html/figs/deepgen/
v4_akt/'
stiphyMT/plantcv
plantcv/plantcv/visualize/obj_sizes.py
Python
mit
3,006
0.003327
# Visualize an annotated image with object sizes import os import cv2 import random import numpy as np from plantcv.plantcv import params from plantcv.plantcv import color_palette from plantcv.plantcv._debug import _debug def obj_sizes(img, mask, num_objects=100): """ Label the size of objects in an image. ...
otting_img = np.copy(img) # Convert grayscale images to color if len(np.shape(plotting_img)) == 2: plotting_img = cv2.cvtColor(plotting_img, cv2.COLOR_GRAY2BGR) # Store debug debug = params.debug params.debug = None # ID contours and sort them from largest to smallest id_objects, _...
, key=lambda x: cv2.contourArea(x)) # Function sorts smallest to largest so keep the last X objects listed # sorted_objects = sorted_objects[len(sorted_objects) - num_objects: len(sorted_objects)] # Reverse the sorted list to order contours from largest to smallest sorted_objects.reverse() rand_col...
joequery/joequery.me
joequery/blog/posts/code/python-builtin-functions/simple_functions.py
Python
mit
319
0.009404
import math def eve
n_numbers_only(thelist): ''' Returns a list of even numbers in thelist ''' return [x for x in thelist if x%2 == 0] def is_perfect_square(x): ''' Returns True if x is a perfect square, False otherwise ''' thesqrt = int(math.sqrt(x)) return thesqrt * thesqrt
== x
hunch/hunch-gift-app
django/contrib/gis/geos/polygon.py
Python
mit
6,672
0.003447
from ctypes import c_uint, byref from django.contrib.gis.geos.error import GEOSIndexError from django.contrib.gis.geos.geometry import GEOSGeometry from django.contrib.gis.geos.libgeos import get_pointer_arr, GEOM_PTR from django.contrib.gis.geos.linestring import LinearRing from django.contrib.gis.geos import pro...
n_holes = 0 elif isinstance(init_holes[0][0], LinearRing):
init_holes = init_holes[0] n_holes = len(init_holes) polygon = self._create_polygon(n_holes + 1, (ext_ring,) + init_holes) super(Polygon, self).__init__(polygon, **kwargs) def __iter__(self): "Iterates over each ring in the polygon." for i in xrang...
cogu/autosar
autosar/rte/generator.py
Python
mit
42,335
0.023597
import os import autosar.rte.partition import cfile as C import io import autosar.base import autosar.bsw.com innerIndentDefault=3 #default indendation (number of spaces) def _genCommentHeader(comment): lines = [] lines.append('/************************************************************************...
sar.datatype.RealDataType): if dataType.encoding == 'DOUBLE': platform_typename = 'float64' else: platform_typename = 'float32' hfile.code.append('typedef %s %s;'%(platform_typename, dataType.name)) else...
raise NotImplementedError(type(dataType)) #sys.stderr.write('not implemented: %s\n'%str(type(dataType))) else: raise ValueError(ref) if len(modeTypes)>0: lines=_genCommentHeader('Mode Types') tmp=[] hfile.co...
crossbario/autobahn-testsuite
autobahntestsuite/autobahntestsuite/case/case9_4_3.py
Python
apache-2.0
1,271
0.015736
############################################################################### ## ## Copyright (c) Crossbar.io Technologies GmbH ## ## Licensed under the Apache License, Version 2.0 (the "License"); ## you may not use this file except in compliance with the License. ## You may obtain
a copy of the License at ## ## http://www.apache.org/licenses/LICENSE-2.0 ## ## Unless required by applicable law or agreed to in writing, software ## distributed under the License is distributed on an "AS IS" BASIS, ## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ## See the ...
##################################################################### from case9_4_1 import Case9_4_1 class Case9_4_3(Case9_4_1): DESCRIPTION = """Send fragmented binary message message with message payload of length 4 * 2**20 (4M). Sent out in fragments of 1k.""" EXPECTATION = """Receive echo'ed bina...
evrenkutar/blog
blog/urls.py
Python
gpl-2.0
299
0.013378
__au
thor__ = 'evren kutar' from django.conf.urls import patterns, url urlpatterns = patterns('', url(r'^(?P<cslug>[\w-]+)/$', 'blog.views.post_category', name='category'), url(r'^(?P<cslug>[\w-]+)/(?P<slug>[\w-]+)/$', 'blog.views.po
st', name='post') )
cghall/salesforce-reporting
salesforce_reporting/parsers.py
Python
mit
10,296
0.003594
class ReportParser: """ Parser with generic functionality for all Report Types (Tabular, Summary, Matrix) Parameters ---------- report: dict, return value of Connection.get_report() """ def __init__(self, report): self.data = report self.type = self.data["reportMetadata"]["r...
lt=None): """ Return the total for the specified row. The default arg makes it possible to specify the return value if the column label is not found. Parameters ---------- row_
label: string default: string, optional, default None If row is not found determines the return value Returns ------- total: int """ grp_down_list = self.data["groupingsDown"]["groupings"] row_dict = {grp["label"]: int(grp["key"]) for grp in grp_down_...
twonds/trinine
trinine/t9.py
Python
mit
4,257
0.000235
""" """ import imp import os import sys KEY_MAP = {0: [], 1: [], 2: [u'a', u'b', u'c'], 3: [u'd', u'e', u'f'], 4: [u'g', u'h', u'i'], 5: [u'j', u'k', u'l'], 6: [u'm', u'n', u'o'], 7: [u'p', u'q', u'r', u's'], 8: [u't', u'u', u'v']...
t then use existing data to build it. """ if os.path.exists(self.data_module): self.data = imp.load_source('data', self.data_module) else: msg = "WARNING: Data module is not loaded. "
msg += "Please build by running `make build-data`" print msg sys.exit(1) def map_number(self, number): """ Map numbers from a dial pad to characters. @param number: A string of numbers dialed from a key pad. @type number: C{int} """ ret_...
prathamtandon/g4gproblems
Arrays/max_sum_not_adjacent.py
Python
mit
2,744
0.001093
import unittest """ Given an array of positive integers, find the maximum sum of a sub-sequence with the constraint that no two numbers in the sequence should be adjacent in the array. Input: 3 2 7 10 Output: 13 (3 + 10) Input 3 2 5 10 7 Output: 15 (3 + 5 + 7) """ """ Approach: 1. Similar to 0-1 Knapsack problem. 2. F...
t variable tracks the maximum sum obtained by excluding current element 3. Second variable is current element added to first variable 4. Return max(first variable, second variable) """ def max_sum_not_adjacent_helper(list_of_numbers, index): if
index >= len(list_of_numbers): return 0 return max(list_of_numbers[index] + max_sum_not_adjacent_helper(list_of_numbers, index+2), max_sum_not_adjacent_helper(list_of_numbers, index+1)) def max_sum_not_adjacent(list_of_numbers): return max_sum_not_adjacent_helper(list_of_numbers, 0) d...
matttilton/pySteg
pySteg.py
Python
mit
3,694
0.000541
"""This utility aims to provide an easy way to encode text inside of images.""" # TODO Write test cases. # TODO Write own version of cImage. # TODO Add interface. # TODO Add offset. # TODO Add random seed. from cImage import FileImage from cImage import EmptyImage class Encode: """Class""" def __init__(self...
directory self.key = FileImage(self.keyDirectory + key_file_name) self.resultDirectory = result_directory def Encode(self, data): """Take binary data and add it to an image.""" result = EmptyImage(self.key.getWidth(), self.key.getHeight()) count = 0 for row in range(...
(data)): if (int(data[count]) == 1): newPixel = self.flipLSB(keyPixel) else: newPixel = keyPixel count += 1 result.setPixel(col, row, newPixel) else: result...
Iconoclasteinc/tgit
tgit/countries.py
Python
gpl-3.0
11,846
0.000084
# -*- coding: utf-8 -*- # # TGiT, Music Tagger for Professionals # Copyright (C) 2013 Iconoclaste Musique Inc. # # 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...
ly", "JM": "Jamaica", "JP": "Japan", "JE": "Jersey", "JO": "Jordan", "KZ": "Kazakhstan", "KE": "Kenya", "KI": "Kiribati", "KP": "Korea, Democratic People's Republic of", "KR": "Korea, Republic of",
"KW": "Kuwait", "KG": "Kyrgyzstan", "LA": "Lao PDR", "LV": "Latvia", "LB": "Lebanon", "LS": "Lesotho", "LR": "Liberia", "LY": "Libya", "LI": "Liechtenstein", "LT": "Lithuania", "LU": "Luxembourg", "MK": "Macedonia, Republic of", "MG": "Madagascar", "M...
pyseed/objify
objify/test/test_core.py
Python
mit
13,959
0.002651
#!/usr/bin/env python # -*- coding: utf-8 -*- """ type 'pytest -v' to run u test series """ import codecs import json import os import pytest import tempfile import sys sys.path.insert(1, os.path.join(sys.path[0], '..')) import core class TestHelpers: @staticmethod def file_read(fd): """ fro...
or, create a new descriptor in read mode and read file content :return file content :rtype str """ with codecs.open(fd.name, 'r', 'utf-8') as f: res = f.read() return res @staticmethod def same_class(instance, should_cls): return str(instance.__class_...
d def json_compare(a, b): return json.dumps(a) == json.dumps(b) class Fake(object): pass @pytest.fixture() def fixture_dict_data(): return dict( id=1, active=True, name='foobar', nested=dict(id=1, name='nested'), items=[dict(id=1, name='item1'),], ) de...
jokajak/itweb
data/env/lib/python2.6/site-packages/tw.forms-0.9.9-py2.6.egg/tw/forms/__init__.py
Python
gpl-3.0
578
0.00173
""" Form widgets for ToscaWidgets. To download and install:: easy_install twForms """ from tw.api import Widget from tw.forms.core import * from tw.forms.fields import * from tw.form
s.datagrid import * from tw.forms.calendars import * # build all so doc tools introspect me properly from tw.forms.core import __all__ as __core_all from tw.forms.fields import __all__ as __fields_all from tw.forms.datagrid import __all__ as __datagrid_all from tw.forms.calendars import __all__ as __calendars_all __a...
l
tinkerinestudio/Tinkerine-Suite
TinkerineSuite/Cura/cura_sf/skeinforge_application/skeinforge_plugins/craft_plugins/hop.py
Python
agpl-3.0
8,736
0.025412
""" This page is in the table of contents. Hop is a script to raise the extruder when it is not extruding. Note: Note: In some cases where you have thin overhang this plugin can help solve the problem object being knocked off by the head The hop manual page is at: http://fabmetheus.crsndoo.com/wiki/index.php/Skeinf...
ght = 0.4 self.hopDistance = self.hopHeight sel
f.justDeactivated = False self.layerCount = settings.LayerCount() self.lineIndex = 0 self.lines = None self.oldLocation = None def getCraftedGcode( self, gcodeText, hopRepository ): "Parse gcode text and store the hop gcode." self.lines = archive.getTextLines(gcodeText) self.minimumSlope = math.tan( mat...
welex91/ansible-modules-core
windows/win_reboot.py
Python
gpl-3.0
1,679
0.00536
DOCUMENTATION=''' --- module: win_reboot short_description: Reboot a windows machine description: - Reboot a Windows machine, wait for it to go down, come back up, and respond to commands. version_added: "2.1" options: pre_reboot_delay_sec: description: - Seconds for shutdown to wait before requesting re...
: description: - Maximum seconds to wait for shutdown to occur - Increase this timeout for very slow hardware, large update applica
tions, etc default: 600 reboot_timeout_sec: description: - Maximum seconds to wait for machine to re-appear on the network and respond to a test command - This timeout is evaluated separately for both network appearance and test command success (so maximum clock time is actually twice this value) ...
Yurlungur/FLRW
MultiRegime.py
Python
mit
2,168
0.01476
#!/usr/bin/env python2 # multi-regime.py # Author: Jonah Miller (jonah.maxwell.miller@gmail.com) # Time-stamp: <2013-12-14 16:06:28 (jonah)> # This is a library to plot and fit for omega(rho) variable. We choose # omega so that we get the three distinct regimes for which we know # the analytic solution with continuou...
plotlib as mpl import matplotlib.pyplot as plt import plot_all_variables as pav from scipy.special import erf # ---------------------------------------------------------------------- # Constants # ---------------------------------------------------------------------- RHO_MIN=0 OMEGA_MIN = -1 ERF_MIN = -1 RHO_DARK_ENER...
,20] TRANSITION_WIDTH_MR=[1,5,12,20] NUM_ERFS = 2 DE_AMPLITUDE = 1.0/2.0 MATTER_AMPLITUDE = (1.0/3.0)* DE_AMPLITUDE XLABEL=r'$\rho$' YLABEL=r'$\omega$' # ---------------------------------------------------------------------- def omega(rho, rho_dark_energy,transition_width_de, rho_matter,transition_...
laurent-george/weboob
modules/feedly/browser.py
Python
agpl-3.0
4,193
0.000954
# -*- coding: utf-8 -*- # Copyright(C) 2014 Bezleputh # # This file is part of weboob. # # weboob 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 opt...
nd self.password is not None: return self.get_logged_categories() return self.essentials.go().get_categories() @need_login def get_logged_categories(self): user_categories = list(se
lf.preferences.go().get_categories()) user_categories.append(Collection([u'global.saved'], u'Saved')) return user_categories def get_feeds(self, category): if self.username is not None and self.password is not None: return self.get_logged_feeds(category) return self.esse...
python-frederick/hackathon-2016
hackathon/wsgi.py
Python
bsd-2-clause
395
0
""" WSGI config for hackathon project. It exposes the WSGI callable as a module-level variable named ``application`
`. For more information on this file, see https://docs.djangoproject.com/en/1.9/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "hackathon.settings")
application = get_wsgi_application()
Anatoscope/sofa
applications/plugins/SofaPython/python/SofaPython/script.py
Python
lgpl-2.1
2,609
0.010732
'''simpler & deprecated python script controllers''' import Sofa import inspect def deprecated(cls): # TODO maybe we should print a backtrace to locate the origin? # or even better, use: https://docs.python.org/2/library/warnings.html#warnings.warn line = '''class `{0}` from module `{1}` is deprecated. Y...
try: return Controller.instances.pop() # let's trust the garbage collector except AttributeError: # if this fails, you need to call # Controller.onLoaded(self, node) in
derived classes print "[SofaPython.script.Controller.__new__] instance not found, did you call 'SofaPython.script.Controller.onLoaded' on your overloaded 'onLoaded' in {} ?".format(cls) raise def onLoaded(self, node): Controller.instances.append(self) self.additionalArgumen...
django-danceschool/django-danceschool
danceschool/core/migrations/0037_remove_registration_expirationdate.py
Python
bsd-3-clause
1,183
0.002536
# Generated by Django 2.2.17 on 2021-02-02 03:43 from django.db import migrations, models
import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('core', '0036_fix_reg_invoice_link'), ] operations = [ migrations.AlterField( model_name='registration', name='final', field=models.BooleanField(null=False, defau...
migrations.AlterField( model_name='eventregistration', name='invoiceItem', field=models.OneToOneField(null=False, on_delete=django.db.models.deletion.CASCADE, related_name='eventRegistration', to='core.InvoiceItem', verbose_name='Invoice item'), ), migrations...
depet/scikit-learn
sklearn/ensemble/__init__.py
Python
bsd-3-clause
1,055
0
""" The :mod:`sklearn.ensemble` module includes ensemble-based methods for classification and regression. """ from .base import BaseEnsemble from .forest import RandomForestClassifier from .forest import RandomForestRegressor from .forest import RandomTreesEmbedding from .forest import ExtraTreesClassifier from .fores...
lassifier from .weight_boosting import AdaBoostRegressor from .gradient_boosting import GradientBoostingClassifier from .gradient_boosting import GradientBoostingRegressor from . import forest from . import weight_boosting from . import gradient_boosting from . import partial_dependence __all__ = ["BaseEnsemble", "Ra...
ingClassifier", "GradientBoostingRegressor", "AdaBoostClassifier", "AdaBoostRegressor", "forest", "gradient_boosting", "partial_dependence", "weight_boosting"]
skycucumber/Messaging-Gateway
webapp/venv/lib/python2.7/site-packages/twisted/names/tap.py
Python
gpl-2.0
4,832
0.001863
# -*- test-case-name: twisted.names.test.test_tap -*- # Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """ Domain Name Server """ import os, traceback from twisted.python import usage from twisted.names import dns from twisted.application import internet, service from twisted.names import ser...
(address[1],)) address = (address[0], port) self.secondaries.append((address, [args[1]])) def opt_verbose(self): """Increment verbosity level""" self['verbose'] += 1 def postOptions(self): if self[
'resolv-conf']: self['recursive'] = True self.svcs = [] self.zones = [] for f in self.zonefiles: try: self.zones.append(authority.PySourceAuthority(f)) except Exception: traceback.print_exc() raise usage.UsageEr...
druids/django-pyston
pyston/order/exceptions.py
Python
bsd-3-clause
175
0
class Or
derError(Exception): pass class
OrderIdentifierError(OrderError): """ Order exception that is raised if order identifier was not found. """ pass
Ebag333/Pyfa
service/damagePattern.py
Python
gpl-3.0
2,873
0.000348
# ============================================================================= # Copyright (C) 2010 Diego Duclos # # This file is part of pyfa. # # pyfa 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 ...
saveChanges(self, p):
eos.db.save(p) def importPatterns(self, text): lookup = {} current = self.getDamagePatternList() for pattern in current: lookup[pattern.name] = pattern imports, num = es_DamagePattern.importPatterns(text) for pattern in imports: if pattern.name ...
GreenJoey/My-Simple-Programs
python/Twisted/krondo Twisted Introduction/twisted-client-2/get-poetry-stack.py
Python
gpl-2.0
3,806
0.001051
# This is the Twisted Get Poetry Now! client, version 2.0 import datetime import optparse import os import traceback from twisted.internet.protocol import Protocol, ClientFactory def parse_args(): usage = """usage: %prog [options] [hostname]:port ... This is the Get Poetry Now! client, Twisted version 2.0. ...
nect to:", connector.getDestination()) self.poem_finished() if __name__ == '__main__': addresses = parse_args() start = datetime.datetime.now() factory = PoetryClientFactory(len(addresses)) from twisted.internet import reactor for address in addresses:
# Get the host and port from the returned tuples host, port = address # The .connectTCP method is of interest here. # It takes the host and port as first two parameter # And also a protocol factory to create the protocol objects on-demand reactor.connectTCP(host, port, fa...
bjolivot/ansible
lib/ansible/modules/network/avi/avi_analyticsprofile.py
Python
gpl-3.0
25,965
0.003967
#!/usr/bin/python # # Created on Aug 25, 2016 # @author: Gaurav Rastogi (grastogi@avinetworks.com) # Eric Anderson (eanderson@avinetworks.com) # module_check: supported # Avi Version: 16.3.8 # # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the te...
ue to timeo
ut. - Default value when not specified in API or module is interpreted by Avi Controller as 20. conn_server_lossy_total_rexmt_threshold: description: - A connection between avi and server is considered lossy when more than this percentage of packets are retransmitted. - D...
julien78910/CouchPotatoServer
version.py
Python
gpl-3.0
32
0.03125
V
ERSION
= None BRANCH = 'master'
zstackio/zstack-woodpecker
integrationtest/vm/mini/multiclusters/paths/multi_path173.py
Python
apache-2.0
2,948
0.018996
import zstackwoodpecker.test_state as ts_header import os TestAction = ts_header.TestAction def path(): return dict(initial_formation="template5", checking_point=1, faild_point=100000, path_list=[ [TestAction.create_mini_vm, 'vm1', 'cluster=cluster1'], [TestAction.reboot_vm, 'vm1'], [TestAction.create_mini_v...
ge1'] attached:['volume3', 'volume4', 'volume2'] Detached:[] Deleted:['vm1', 'volume3-backup5'] Expunged:['vm2', 'volume1', 'imag
e2'] Ha:[] Group: vm_backup2:['vm1-backup2', 'volume1-backup2']---vm1@volume1 vm_backup3:['vm3-backup4']---vm3@ vm_backup1:['vm2-backup1']---vm2@ '''
nisanick/Prisma_Machina
cogs/roleplay.py
Python
mit
45,290
0.004455
import asyncio import random import checks from TextChecker import TextChecker from database import Database from checks import * from data.rp_texts import * from data.links import * from web import Web from roleplay.Player import Player import discord from discord.ext import commands class Roleplay(commands.Cog): ...
""" channel = user.dm
_channel if channel is None: await user.create_dm() channel = user.dm_channel await channel.send(message) await ctx.message.add_reaction('✅') @commands.command(name='rm', case_insensitive=True) @commands.check(checks.can_manage_rp) @commands.check(checks....
rwightman/pytorch-image-models
tests/test_optim.py
Python
apache-2.0
24,464
0.001635
""" Optimzier Tests These tests were adapted from PyTorch' optimizer tests. """ import math import pytest import functools from copy import deepcopy import torch from torch.testing._internal.common_utils import TestCase from torch.autograd import Variable from timm.scheduler import PlateauLRScheduler from timm.opti...
ert torch.equal(weight, weight_c) #assert torch.equal(bias, bias_c) torch_tc.assertEqual(weight, weight_c) torch_tc.assertEqual(bias, bias_c) # Make sure state dict wasn't modified torch_tc.assertEqual(state_dict, state_dict_c) # Make sure state dict is deterministic with equal but n...
torch_tc.assertEqual(optimizer.state_dict(), optimizer_c.state_dict()) # Make sure repeated parameters have identical representation in state dict optimizer_c.param_groups.extend(optimizer_c.param_groups) torch_tc.assertEqual(optimizer.state_dict()['param_groups'][-1], optimizer_c.state_dict()['param_group...
Azure/azure-sdk-for-python
sdk/network/azure-mgmt-network/azure/mgmt/network/v2016_09_01/aio/operations/_load_balancers_operations.py
Python
mit
23,464
0.004773
# 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 ...
str] = None, **kwargs: Any ) -> "_models.LoadBalancer": """Ge
ts the specified load balancer. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param load_balancer_name: The name of the load balancer. :type load_balancer_name: str :param expand: Expands referenced resources. :type expand: s...
krzyzacy/test-infra
triage/summarize.py
Python
apache-2.0
21,103
0.002606
#!/usr/bin/env python3 # Copyright 2017 The Kubernetes Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appl...
d['pr'] = build['path'].split('/')[-3]
builds[build['path']] = build failed_tests = {} for tests_file in tests_files: with open(tests_file) as f: for line in f: test = json.loads(line) failed_tests.setdefault(test['name'], []).append(test) for tests in failed_tests.values(): ...
Tiendil/deworld
deworld/layers/vegetation_layer.py
Python
bsd-2-clause
5,066
0.003948
# coding: utf-8 import random from deworld.layers.base_layer import BaseLayer class VEGETATION_TYPE: DESERT = 0 GRASS = 1 FOREST = 2 class VegetationLayer(BaseLayer): MIN = 0.0 MAX = 1.0 HEIGHT_FOREST_BARIER_START = None HEIGHT_FOREST_BARIER_END = None HEIGHT_GRASS_BARIER_START ...
, border_start, border_end): if value < border_start: if value < border_end: power = 0 else: power *= 1 - float(border_start - value) / (border_start
- border_end) return power def can_spawn(self, x, y, type_): for y in range(y-1, y+1+1): for x in range(x-1, x+1+1): if not (0 <= y < self.h and 0 <= x < self.w): continue if self.data[y][x] in type_: return True ...
huhongbo/dd-agent
resources/processes.py
Python
bsd-3-clause
3,086
0.00162
# stdlib from collections import namedtuple # project from resources import ( agg, ResourcePlugin, SnapshotDescriptor, SnapshotField, ) from utils.subprocess_output import get_subprocess_output class Processes(ResourcePlugin): RESOURCE_KEY = "processes" FLUSH_INTERVAL = 1 # in minutes ...
ry: psl = PSLine(*line) self.add_to_snapshot([psl.user, float(psl.pct_cpu), float(psl.pct_mem), int(psl.vsz), int(psl.rss),
_compute_family(psl.command), 1]) except Exception: pass self.end_snapshot(group_by=self.group_by_family) def flush_snapshots(self, snapshot_group): self._flush_snapshots(snapshot_group=snapshot_group, ...
blossomica/airmozilla
airmozilla/closedcaptions/views.py
Python
bsd-3-clause
2,235
0
import pycaption from django import http from django.shortcuts import get_object_or_404 from airmozilla.closedcaptions.models import ClosedCaptions class TxtWriter(pycaption.base.BaseWriter): def write(self, caption_set): lang = caption_set.get_languages()[0] captions = caption_set.get_captions(...
) for caption in captions: line = caption.get_text().replace('\n', ' ') if line.startswith('- '): output += '\n\n' output += line
+ ' ' return output SUPPORTED_WRITERS = { 'dfxp': pycaption.DFXPWriter, 'ttml': pycaption.DFXPWriter, 'sami': pycaption.SAMIWriter, 'srt': pycaption.SRTWriter, 'scc': pycaption.SCCWriter, 'webvtt': pycaption.WebVTTWriter, 'txt': TxtWriter, } FILE_EXTENSIONS = { 'dfxp': 'dfxp.x...
wmayner/pyphi
pyphi/exceptions.py
Python
gpl-3.0
653
0
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # exceptions.py """PyPhi exceptions.""" class StateUnreachableError(ValueError): """The current state cannot be reached from any previous state.""" def __init__(self, state): self.state = state msg = "The state {} cannot be reached in the given ...
: """The TPM is conditionally dependent.""" class JSONVersionError(ValueError): """JSON was serialized with a different version of PyPhi.""" class WrongDirectionError(ValueError):
"""The wrong direction was provided."""
jerrylei98/Dailydos
wsgi.py
Python
mit
77
0.025974
fr
om app import application if __name__=="__main__": application.run()
mattr555/AtYourService-school
main/__init__.py
Python
mit
1,906
0.005771
from django.contrib.contenttypes.mo
dels import ContentType from django.contrib.auth.models import Permission, Group from django.contrib.sites.models import Site from django.db.models.signals import post_save, post_migrate from django.core.exceptions import ObjectDoesNotExist from main.models impor
t SiteSettings, UserProfile, User # custom user related permissions def add_user_permissions(sender, **kwargs): pass def add_groups(sender, **kwargs): ct = ContentType.objects.get(app_label='auth', model='user') perm, created = Permission.objects.get_or_create(codename='can_view', name='Can View Users', c...
hackerspace-ntnu/website
userprofile/migrations/0030_skill.py
Python
mit
955
0.004188
# Generated by Django 3.0.2 on 2020-03-04 20:08 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('files', '0004_image_compressed'), ('userprofile', '0029_auto_20200304_2007'), ] operations = [ migr...
=False, verbose_name='ID')), ('name', models.CharField(max_length=50)), ('description', models.TextField(
)), ('category', models.ManyToManyField(to='userprofile.Category')), ('prerequisites', models.ManyToManyField(blank=True, to='userprofile.Skill')), ('thumb', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='files.Image')), ...
chrisidefix/visvis
functions/volread.py
Python
bsd-3-clause
1,322
0.008321
# -*- coding: utf-8 -*- # Copyright (C) 2012, Almar Klein # # Visvis is distributed under the terms of the (new) BSD License. # The full license can be found in 'license.txt'. import visvis as vv import numpy as np import os # Try importing imagei
o imageio = None try: import imageio except ImportError: pass def volread(filename): """ volread(filename) Read volume from a file. If filename is 'stent', read a dedicated test dataset. For reading any other kind of volume, the imageio package is required. """ if filen...
Get full filename path = vv.misc.getResourceDir() filename2 = os.path.join(path, 'stent_vol.ssdf') if os.path.isfile(filename2): filename = filename2 else: raise IOError("File '%s' does not exist." % filename) # Load s = vv.ssdf.load(filename) ...
paulovn/aiml-chatbot-kernel
aimlbotkernel/__init__.py
Python
bsd-3-clause
97
0.010309
__version__ = '1.0.4' KERNEL_NAME = 'aimlbot' LANGUAGE = 'chatbot' DISPLAY_
NAME= 'AIML Chatbot'
coolman565/blu_two
commander/commander_impl.py
Python
mit
1,705
0.001173
import logging import os import re import subprocess import time from ctypes.wintypes import MAX_PATH from commander import Commander, Response logger = logging.get
Logger(__name__) class Com
manderImpl(Commander): def __init__(self): super().__init__() def call(self, cmd: str) -> Response: logger.info('Executing command, command: %s', cmd) start: int = time.time() completed = subprocess.run( cmd, shell=True, stdout=subprocess.PIP...
ajoshiusc/brainsuite-workflows
utility_scripts/main_check_remaining.py
Python
mit
1,120
0.000893
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Thu Apr 27 12:16:26 2017 @author: Anand A Joshi, Divya Varadarajan """ import glob from os.path import isfile, split import configparser config_file = u'/big_disk/ajoshi/ABIDE2/study.cfg' Config = configparser.ConfigParser() Config.read(config_file) Conf...
1 print outsurfname continue com += 1 pri
nt str(incom) + ' remaining ' + str(com) + ' done'
checkr/fdep
fdep/backends/http.py
Python
mit
750
0
import requests from fdep.backends import StorageBackend class HTTPBacken
d(StorageBackend): """Implement HTTP/HTTPS.""" SCHEME_NAME = 'http' def get_to(self, local_path): r = requests.get(self.url, stream=True) total_length = int(r.headers.get('content-length', 0)) self.progressbar.start_progress(total_length) with open(local_path, 'wb') as f: ...
) self.progressbar.progress_callback(len(chunk)) self.progressbar.end_progress() def put_from(self, local_path): raise NotImplementedError("HTTP backend does not support uploading") class HTTPSBackend(HTTPBackend): SCHEME_NAME = 'https'
Reality9/spiderfoot
modules/sfp_intfiles.py
Python
gpl-2.0
6,481
0.003395
# -*- coding: utf-8 -*- # ---------------------------------
---------------------------------------------- # Name: sfp_intfiles # Purpose:
From Spidering and from searching search engines, identifies # files of potential interest. # # Author: Steve Micallef <steve@binarypool.com> # # Created: 06/04/2014 # Copyright: (c) Steve Micallef 2014 # Licence: GPL # ----------------------------------------------------------...
estebistec/django-get-forms
examples/demo/demo/forms.py
Python
bsd-3-clause
127
0
# -*- coding: utf-8 -*- from
django import forms class SearchForm
(forms.Form): query = forms.CharField(required=False)
xtuyaowu/jtyd_python_spider
page_parse/user/public.py
Python
mit
6,454
0.000775
# -*-coding:utf-8 -*- import re import json from bs4 import BeautifulSoup from page_parse import status from decorators.decorator import parse_decorator from db.models import UserRelation from utils.filters import url_filter from db.user_relation import save_relations def get_userid(html): return status.get_useri...
_or_fol
lows(html, uid, type): """ Get fans or follows and store their relationships :param html: current page source :param uid: current user id :param type: type of relations :return: list of fans or followers """ if html == '': return list() pattern = re.compile(r'FM.view\((.*)\)...
thelastpickle/python-driver
cassandra/io/asyncorereactor.py
Python
apache-2.0
13,797
0.001667
# Copyright DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, softwa...
address) self._socket.setblocking(0) _AsyncoreDispatcher.__init__(self, self._socket) def handle_read(self): try: d = self._socket.recvfrom(1) while d and d[1]: d = s
elf._socket.recvfrom(1) except socket.error as e: pass self._notified = False def notify_loop(self): if not self._notified: self._notified = True self._socket.sendto(b'', self.bind_address) def loop(self, timeout): asyncore.loop(timeout=timeo...
XeCycle/indico
indico/web/flask/blueprints/event/display/misc.py
Python
gpl-3.0
2,063
0.005332
# This file is part of Indico. # Copyright (C) 2002 - 2015 European Organization for Nuclear Research (CERN). # # Indico 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 (a...
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 Licens
e for more details. # # You should have received a copy of the GNU General Public License # along with Indico; if not, see <http://www.gnu.org/licenses/>. from MaKaC.webinterface.rh import conferenceDisplay from indico.web.flask.blueprints.event.display import event # My conference event.add_url_rule('/my-conference...
ptomasroos/vitess
py/vtdb/keyrange_constants.py
Python
bsd-3-clause
450
0
# Copyright 2013, Google
Inc. 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 the shard name for when the keyrange covers the entire space # for unsharded database. SHARD_ZERO = '0' # Keyrange that spans the entire space, used # for unsharded database.
NON_PARTIAL_KEYRANGE = '' MIN_KEY = '' MAX_KEY = '' KIT_UNSET = '' KIT_UINT64 = 'uint64' KIT_BYTES = 'bytes'
mlperf/training_results_v0.6
Fujitsu/benchmarks/resnet/implementations/mxnet/3rdparty/tvm/topi/python/topi/nn/elemwise.py
Python
apache-2.0
1,936
0.002066
"""Elementwise operators""" from __future__ import absolute_import as _abs import tvm from .. import tag from ..util import get_const_int @tvm.tag_scope(tag=tag.ELEMWISE) def relu(x): """Take relu of input x. Parameters ---------- x : tvm.Tensor Input argument. Returns ------- y :...
elu(x, alpha): """Take leaky relu of input x. Parameters ---------- x : tvm.Tensor Input argument. alpha : float The slope for the small gradient when x < 0 Returns ------- y : tvm.Tensor The result. """ def _compute(*indices): value = x(*indice...
ef prelu(x, slope, axis=1): """ PReLU. It accepts two arguments: an input ``x`` and a weight array ``W`` and computes the output as :math:`PReLU(x) y = x > 0 ? x : W * x`, where :math:`*` is an elementwise multiplication for each sample in the batch. Arguments: x : tvm.Tensor Input a...
vkryachko/Vase
tests/test_multidict.py
Python
bsd-2-clause
640
0
import unittest from vase.util import MultiDict class MultiDictTests(unittest.TestCase): def test_setitem(self): md = MultiDict() key = 'hello' value = 'world' md[key] = value self.assertEqual(md[key], value) self.assertEqual(md.get(key), value) self.asser...
st(key), [value]) self.assertRaises(KeyError, md.__getitem__, "vasya") self.assertEqual(md.get("vasya"), None)
self.assertEqual(list(md.items()), [(key, value)]) self.assertEqual(list(md.lists()), [(key, [value])]) self.assertEqual(list(md.values()), [value])
nagyistoce/netzob
src/netzob/UI/Vocabulary/Views/MessageTableView.py
Python
gpl-3.0
29,245
0.003112
# -*- coding: utf-8 -*- #+---------------------------------------------------------------------------+ #| 01001110 01100101 01110100 01111010 01101111 01100010 | #| | #| Netzob : Inferring communication protocol...
| #| @sponsors : Amossys, http://www.amossys.fr | #| Supélec, http://www.rennes.supelec.
fr/ren/rd/cidre/ | #+---------------------------------------------------------------------------+ #+---------------------------------------------------------------------------+ #| Standard library imports #+---------------------------------------------------------------------------+ import os import logging ...
cliftonmcintosh/openstates
openstates/sd/__init__.py
Python
gpl-3.0
3,672
0.000272
from pupa.scrape import Jurisdiction, Organization import scrapelib import lxml.html from .people import SDLegislatorScraper from .bills import SDBillScraper class SouthDakota(Jurisdiction): division_id = "ocd-division/country:us/state:sd" classification = "government" name = "South Dakota" url = "htt...
ocratic'} ] legislative_sessions = [ { "_scraped_name": "2009 (84th) Session", "identifier": "2009",
"name": "2009 Regular Session" }, { "_scraped_name": "2010 (85th) Session", "identifier": "2010", "name": "2010 Regular Session" }, { "_scraped_name": "2011 (86th) Session", "identifier": "2011", "name": "2011 Regul...
dmartin35/pronosfoot
tools/utils.py
Python
mit
1,623
0.02711
""" UTILITIES """ def distinct(inlist): """ returns a list of distinct values (no duplicated values) """ outlist = [] for elem in inlist: if not elem in outlist: outlist.append(elem) return outlist def list_evolution(list1,list2): """ returns the index evolution ...
se: evo.append(None) return evo def list_to_dict(keyslist,valueslist): """ convert lists of keys and values to a dict
""" if len(keyslist) != len(valueslist): return {} mydict = {} for idx in range(0,len(keyslist)): mydict[keyslist[idx]] = valueslist[idx] return mydict #evo_progress: return the evolution of each item of a list compared to its left value evo_progress = lambda pos: [] if pos == [] e...
Erotemic/local
depricated/speech/Examples/_tortoisesvn.py
Python
gpl-3.0
6,848
0.003505
# coding=utf-8 # # (c) Copyright 2008 by Daniel J. Rocco # Licensed under the Creative Commons Attribution- # Noncommercial-Share Alike 3.0 United States License, see # <http://creativecommons.org/licenses/by-nc-sa/3.0/us/> # """ Command-module for controlling **TortoiseSVN** from Windows Explorer ==================...
ory": "repobrowser", "edit conflict": "conflicteditor", }, ) config.tortoisesvn.predef = Item({ "dragonfly | dee fly": r"C:\data\projects\Dra
gonfly\work dragonfly", }, ) #config.generate_config_file() config.load() #--------------------------------------------------------------------------- # Utility generator function for iterating over COM collections. def collection_iter(collection): ...
antoinecarme/sklearn2sql_heroku
tests/classification/FourClass_100/ws_FourClass_100_AdaBoostClassifier_db2_code_gen.py
Python
bsd-3-clause
144
0.013889
from skl
earn2sql_heroku.tests.classification import generic as class_gen class_gen.test_model("AdaBoostClassifier"
, "FourClass_100" , "db2")
sternshus/arelle2.7
svr-2.7/arelle/plugin/profileFormula.py
Python
apache-2.0
5,608
0.008559
''' Profile Formula Validation is an example of a plug-in to GUI menu that will profile formula execution. (c) Copyright 2012 Mark V Systems Limited, All rights reserved. ''' import os from tkinter import simpledialog, messagebox def profileFormulaMenuEntender(cntlr, menu): # Extend menu with an item for the prof...
rofileReportFile = cntlr.uiFileDialog("save", title=_("arelle - Save Formula Profile Report"), initialdir=cntlr.config.setdefault("formulaProfileReportDir","."), filetypes=[(_("Profile report file .log"), "*.log")], defaultextension=".log") if not profileReport
File: return False errMsg = "" maxRunTime = 0 while (1): timeout = simpledialog.askstring(_("arelle - Set formula run time limit"), _("{0}You may enter the maximum number of minutes to run formulas.\n" "(Leave empty for no run time limitation.)".format(errMs...