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
repotvsupertuga/tvsupertuga.repository
script.module.universalscrapers/lib/universalscrapers/scraperplugins/unsure/filmapik.py
Python
gpl-2.0
5,801
0.022755
import requests import re,time import xbmc,xbmcaddon from ..scraper import Scraper from ..common import clean_title,clean_search,send_log,error_log dev_log = xbmcaddon.Addon('script.module.universalscrapers').getSetting("dev_log") requests.packages.urllib3.disable_warnings() s = requests.session() User_Age...
).content match = re.compile('data-movie-id=.+?href="(.+?)".+?<h2>(.+?)</h2>',re.DOTALL).findall(html) for item_url, name in match: #print item_url if clean_title(search_id).lower() == clean_title(name).lower(): item_url = self.base_link + '/...
eason,episode) #print item_url mode = 'tv' self.get_source(item_url,mode,title,year,season,episode,start_time) return self.sources except Exception, argument: if dev_log == 'true': error_log(self.name,arg...
catapult-project/catapult-csm
telemetry/telemetry/internal/browser/possible_browser.py
Python
bsd-3-clause
1,414
0.010608
# Copyright 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from telemetry.internal.app import possible_app class PossibleBrowser(possible_app.PossibleApp): """A browser that can be controlled. Call Create() to...
e NotImplementedError() def Create(self, finder_options): raise NotImplementedError() def SupportsOptions(self, browser_options): """Tests for extension support.""" raise NotImplementedError() def IsRemote(self): return False def RunRemote(self): pass def UpdateExecutableIfNeeded(self...
ast_modification_time(self): return -1 def SetCredentialsPath(self, credentials_path): self._credentials_path = credentials_path
SyntaxBlitz/syntaxblitz.github.io
mining-lear/process/step6.py
Python
mit
1,654
0.024788
import json f = open('text-stripped-3.json') out = open('text-lines.json', 'w') start_obj = json.load(f) end_obj = {'data': []} characters_on_stage = [] currently_speaking = None last_scene = '1.1' for i in range(len(start_obj['data'])): obj = start_obj['data'][i] if obj['type'] == 'entrance': if obj['characte...
arted with ' + str(characters_on_stage) + ' still on stage') last_scene = scene end_obj['data'].append({ 'type': 'line', 'identifier': obj['identifier'], 'text': obj['text'].strip()
, 'speaker': currently_speaking, 'characters': characters_on_stage }) if len(characters_on_stage) == 0: currently_speaking = None json.dump(end_obj, out)
salberin/libsigrokdecode
decoders/usb_signalling/pd.py
Python
gpl-3.0
7,715
0.002333
## ## This file is part of the libsigrokdecode project. ## ## Copyright (C) 2011 Gareth McMullin <[email protected]> ## Copyright (C) 2012-2013 Uwe Hermann <[email protected]> ## ## This program is free software; you can redistribute it and/or modify ## it under the terms of the GNU General Public License as pu...
lf.put(s - h, s + h, self.out_python, data) def putb(self, data): s, h = self.samplenum, self.halfbit self.put(s
- h, s + h, self.out_ann, data) def set_new_target_samplenum(self): bitpos = self.ss_sop + (self.bitwidth / 2) bitpos += self.bitnum * self.bitwidth self.samplenum_target = int(bitpos) def wait_for_sop(self, sym): # Wait for a Start of Packet (SOP), i.e. a J->K symbol change. ...
adhoc-dev/odoo-nautical
nautical/partner.py
Python
agpl-3.0
957
0.014629
# -*- coding: utf-8 -*- ############################################################################## # For copyright and license notices, see __openerp__.py file in module root # directory ##############################################################
################ import re from openerp import netsvc from openerp.osv import osv, fields class partner(osv.osv): """""" _name = 'res.partner' _inherits = { } _inherit = [ 'res.partn
er' ] _columns = { 'authorization_ids': fields.one2many('nautical.authorization', 'partner_id', string='Authorizations'), 'historical_record_ids': fields.one2many('nautical.partner_record', 'partner_id', string='historical_record_ids'), 'owned_craft_ids': fields.one2many('nautical.craft',...
callmealien/wazimap_zambia
censusreporter/api/config.py
Python
mit
106
0
# Database DB_NAME = 'censusreporter_ke' DB_USER = 'censusreporter_ke' DB_PASSWO
RD = 'census
reporter_ke'
mattyhall/North-South-Divide
divide.py
Python
bsd-3-clause
2,269
0.009255
from flask import Flask, render_template, request from lib.work import work from lib.loaders.policedata import PoliceData from lib.loaders.populationdata import PopulationData from lib.loaders.childpovertydata import ChildPovertyData from lib.loaders.cancerdata import CancerData import json app = Flask(__name__) @app...
opulation=request.args.get('population', 'false'), child_poverty=request.args.get('childpoverty', 'false'), cancer=request.args.get('cancer', 'false'), no_line=request.args.get('noline', 'false'),...
quest.args.get('step', '0.2')), realistic=request.args.get('realistic', 'false')) @app.route('/data') def data(): police = request.args.get('police', 'true') population = request.args.get('population', 'false') child_poverty = request.args.get('childpoverty', 'false...
factorlibre/odoomrp-wip
stock_picking_wave_management/models/stock_picking_wave.py
Python
agpl-3.0
3,408
0.000293
# -*- coding: utf-8 -*- ############################################################################## # For copyright and license notices, see __openerp__.py file in root directory ############################################################################## from openerp import models, fields, api, exceptions, _ c...
num_assigned = fields.Integer( compute="_count_assigned_pickings", string="Assigned pickings") partner = fields.Many2one('res.partner', 'Partner')
@api.multi def confirm_picking(self): picking_obj = self.env['stock.picking'] for wave in self: pickings = picking_obj.search([('wave_id', '=', wave.id), ('state', '=', 'draft')]) pickings.action_assign() wave.state...
kamyu104/LeetCode
Python/palindrome-pairs.py
Python
mit
4,503
0.001777
# Time: O(n * k^2), n is the number of the words, k is the max length of the words. # Space: O(n * k) # Given a list of unique words. Find all pairs of indices (i, j) # in the given list, so that the concatenation of the two words, # i.e. words[i] + words[j] is a palindrome. # # Example 1: # Given words = ["bat", "ta...
t[List[int]] """ res = [] lookup = {} for i, word in enumerate(words): lookup[word] = i for i in xrange(len(words)): for j in xrange(len(words[i]) + 1): prefix = words[i][j:] suffix = words[i][:j] if prefix ...
res.append([i, lookup[suffix[::-1]]]) if j > 0 and suffix == suffix[::-1] and \ prefix[::-1] in lookup and lookup[prefix[::-1]] != i: res.append([lookup[prefix[::-1]], i]) return res # Time: O(n * k^2), n is the number of the words, k is...
t3dev/odoo
addons/payment/models/account_invoice.py
Python
gpl-3.0
4,255
0.00423
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models, _ from odoo.exceptions import ValidationError class AccountInvoice(models.Model): _inherit = 'account.invoice' transaction_ids = fields.Many2many('payment.transaction'...
return self.transaction_ids.get_last_transaction() @api.multi def _create_payment_transaction(self, vals): '''Similar to self.env['payment.transaction'].create(vals) but the values are filled with the current invoices fields (e.g. the partner or the currency). :param vals: The values...
currencies are the same. currency = self[0].currency_id if any([inv.currency_id != currency for inv in self]): raise ValidationError(_('A transaction can\'t be linked to invoices having different currencies.')) # Ensure the partner are the same. partner = self[0].partner_id...
Azure/azure-sdk-for-python
sdk/iothub/azure-mgmt-iothub/azure/mgmt/iothub/v2021_03_03_preview/models/_models_py3.py
Python
mit
167,573
0.003473
# 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 ...
rincipal_id': {'key': 'principalId', 'type': 'str'}, 'tenant_id': {'key': 'tenantId', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'user_assigned_identi
ties': {'key': 'userAssignedIdentities', 'type': '{ArmUserIdentity}'}, } def __init__( self, *, type: Optional[Union[str, "ResourceIdentityType"]] = None, user_assigned_identities: Optional[Dict[str, "ArmUserIdentity"]] = None, **kwargs ): """ :keywor...
emimorad/smile_openerp_matrix_widget
smile_matrix_widget/widgets/__init__.py
Python
gpl-3.0
966
0
# -*- encoding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2011 Smile. All Rights Reserved # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Gener...
ense as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR...
ith this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## import matrix
yejingfu/samples
tensorflow/pyplot03.py
Python
mit
3,650
0.011233
#!/usr/bin/env python3 import numpy as np import matplotlib.pyplot as plt import re rootPath = "/Users/jeff/work/debug/20181216_hard_fe2k_15fps/" finalLogFile = "rosout.log.2" def appendTimestamps(arr, start, stop, flag): #flag = True d = stop - start if flag or (d > -10 and d < 2000): arr.append...
4 ] ## [ Camera OA(3) Fusion Flink V2X ] ## [ 0 1 2 3 4 5 ] ## [ Total(V2X - Camera), OA(OA-Camera), Fusion(Fusion-OA), Flink(Flink - Fusion), V2X(V2X - Flink) Fusion-CA
M ] delays = [[], [], [], [], [], [], [], []] for i in range(len(stamps[0])): if appendTimestamps(delays[0], stamps[0][i], stamps[4][i], False): # total appendTimestamps(delays[1], stamps[0][i], stamps[1][i * 4], True) # OA appendTimestamps(delays[2], stamps[1][i * 4], stamps[2][i], True) # Fusion...
sergeimoiseev/othodi
bokehm.py
Python
mit
4,203
0.012848
# -*- coding: UTF-8 -*- # to run by anaconda # from bokeh.plotting import figure, output_file, show import bokeh.plotting as bp import bokeh_gmapm import logging logger = logging.getLogger(__name__) class Figure(object): def __init__(self, *args, **kwargs): self._output_fname = kwargs.get('o...
dd_line(self, *args,**kwargs): logger.info("starting line add with points num = %d" % (len(args[0]))) if self._use_gmap: bokeh_gmapm.add_line(self._p,args[0],**kwargs) else: if len(args[0])==0: lats = [0,1,2,3] lngs = [2,3,4,5] ...
p.line([d['lat'] for d in args[0]], [d['lng'] for d in args[0]], size=c_size,color=c_color,alpha=0.5) self._p.circle([d['lat'] for d in args[0]], [d['lng'] for d in args[0]], line_width=c...
jakubroztocil/httpie
setup.py
Python
bsd-3-clause
2,890
0.000346
# This is purely the result of trial and error. import sys from setuptools import setup, find_packages import httpie # Note: keep requirements here to ease distributions packaging tests_require = [ 'pytest', 'pytest-httpbin>=0.0.6', 'responses', ] dev_require = [ *tests_require, 'flake8', '...
'Pygments>=2.5.2', 'requests-toolbelt>=0.9.1', 'multidict>=4.7.0', 'setuptools', ] install_requires_win_only = [ 'colorama>=0.2.4', ] # Conditional dependencies: # sdist if 'bdist_wheel' not in sys.argv: if 'win32' in str(sys.platform).lower(): # Terminal colors for Windows insta...
'test': tests_require, # https://wheel.readthedocs.io/en/latest/#defining-conditional-dependencies ':sys_platform == "win32"': install_requires_win_only, } def long_description(): with open('README.md', encoding='utf-8') as f: return f.read() setup( name='httpie', version=httpie.__ve...
kevinrombach/TNTNodeMonitorBot
src/commandhandler/node.py
Python
apache-2.0
10,737
0.011456
#!/usr/bin/env python3 import logging from src import util from src import etherscan from src import messages from crypto.prices import * logger = logging.getLogger("node") ###### # Telegram command handler for adding nodes for the user who fired the command. # # Command: /node :address0;name0 ... :addressN;nameN # ...
valid = True newNode = arg.split(";") if len(newNode) != 2: response += messages.invalidParameterError.format(arg) valid = False else: if not util.validateTntAddress( newNode[0] ): response += message...
dTntAddressError.format(newNode[0]) valid = False if not util.validateName( newNode[1] ): response += messages.invalidNameError.format(newNode[1]) valid = False if valid: address = newNode[0] ...
nuclear-wizard/moose
python/chigger/tests/utils/test_get_active_filenames.py
Python
lgpl-2.1
1,925
0.007792
#!/usr/bin/env python3 #pylint: disable=missing-docstring #* This file is part of the MOOSE framework #* https://www.mooseframework.org #* #* All rights reserved, see COPYRIGHT for full restrictions #* https://github.com/idaholab/moose/blob/master/COPYRIGHT #* #* Licensed under LGPL 2.1, please see LICENSE for details ...
""" Test that updating the files updates the active list. """ # Wai
t and the "update" the first few files time.sleep(1.5) for i in range(5): print(self.testfiles[i]) mooseutils.touch(self.testfiles[i]) active = chigger.utils.get_active_filenames(self.basename + '.e', self.basename + '.e-s*') self.assertEqual(len(active), 5) ...
GaretJax/ppc
fabfile.py
Python
mit
2,432
0.000411
import pipes from fabric.api import settings, task, local, hide from fabric.contrib.console import confirm def is_working_tree_clean(): with settings(hide('everything'), warn_only=True): local('git update-index -q --ignore-submodules --refresh') unstaged = local('git diff-files --quiet --ignore-s...
o check for modifications...' authors() if not is_working_tree_clean(): print ( 'Your working tree is not clean after the AUTHORS file was ' 'rebuilt.' ) print 'Please commit the changes before continuing.'
return # Get version version = 'v{}'.format(local('python setup.py --version', capture=True)) name = local('python setup.py --name', capture=True) # Tag tag_message = '{} release version {}.'.format(name, version) print '----------------------' print 'Proceeding will tag the relea...
dana-i2cat/felix
vt_manager/src/python/vt_manager/controller/dispatchers/xmlrpc/InformationDispatcher.py
Python
apache-2.0
7,769
0.022268
from vt_manager.controller.actions.ActionController import ActionController from vt_manager.controller.drivers.VTDriver import VTDriver from vt_manager.models.Action import Action from vt_manager.models.VirtualMachine import VirtualMachine import xmlrpclib, threading, logging, copy from vt_manager.communication.utils.X...
#if vm.getState() in ['deleting...', 'failed', 'on queue', 'unknown']: if vm.getState() in ["deleting...", "failed"]: child = vm.getChildObje
ct() server = vm.Server.get() #Action.objects.all().filter(objectUUID = vm.uuid).delete() server.deleteVM(vm) # Keep actions table up-to-date after each deletion ...
zpincus/RisWidget
ris_widget/qgraphicsitems/viewport_rect_item.py
Python
mit
1,046
0.002868
# This code is licensed under the MIT License (see LICENSE file for details) from PyQt5 import Qt class ViewportRectItem(Qt.QGraphicsObject): size_changed = Qt.pyqtSignal(Qt.QSizeF) def __init__(self): super().__init__() self.setFlags( Qt.QGraphicsItem.ItemIgnoresTransformations |...
uld appear over anything else rather than z-fighting self.setZValue(10) @property def size(self): return self._size @size.setter def size(self, v): if not isinstance(v, Qt.QSizeF): v = Qt.QSizeF(v) if self._size != v: self.prepareGeometryChange()...
(Qt.QPointF(), self._size)
AlexandreGazagnes/Unduplicator
Copier_coller_fichiers.py
Python
mit
2,039
0.02207
############################################################################### ############################################################################### # MODULE COPIER_COLLER_FICHIERS ############################################################################### ########################################...
######################################################## import os import shutil ############################################################################### # CONSTANTES / VARIABLES ##############################################################
################# ############################################################################### # CLASSES ############################################################################### ############################################################################### # FONCTIONS ####################...
alkorgun/blacksmith-2
expansions/user_stats/insc.py
Python
apache-2.0
813
0.048961
# coding: utf-8 if DefLANG in ("RU", "UA"): AnsBase_temp = tuple([line.decode("utf-8") for line in ( "\nВсего входов
- %d\nВремя последнего входа - %s\nПоследняя роль - %s", # 0 "\nВремя последнего выхода - %s\nПричина выхода - %s", # 1 "\nНики: %s", # 2 "Нет статистики.", # 3 "«%s» сидит здесь - %s.", # 4 "Ты провёл здесь - %s.", # 5 "Здесь нет такого юзера." # 6 )]) else: AnsBase_temp = ( "\nTotal joins - %d\nThe La...
- %s\nExit reason - %s", # 1 "\nNicks: %s", # 2 "No statistics.", # 3 "'%s' spent here - %s.", # 4 "You spent here - %s.", # 5 "No such user here." # 6 )
pacoqueen/odfpy
tests/testuserfields.py
Python
gpl-2.0
7,878
0.000127
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2007 Michael Howitz, gocept gmbh & co. kg # # This is free software. You may redistribute it under the terms # of the Apache license and the GNU General Public License Version # 2 or at your option any later version. # # This program is distributed in the h...
user_fields = get_user_fields(self.userfields_odt) user_fields.dest_file = self._get_dest_file_name() user_fields.update({'username': 'mac',
'firstname': 'mac', 'lastname': 'mac', 'address': 'Hall-Platz 3\n01234 Testheim'}) dest = odf.userfield.UserFields(user_fields.dest_file) self.assertEqual([('username', 'string', 'mac'), ('firstname', 's...
rl-institut/reegis_hp
reegis_hp/de21/scenario_tools.py
Python
gpl-3.0
22,415
0.000491
# -*- coding: utf-8 -*- import pandas as pd import os import os.path as path import logging from oemof import network from oemof.solph import EnergySystem from oemof.solph.options import BinaryFlow, Investment from oemof.solph.plumbing import sequence from oemof.solph.network import (Bus, Source, Sink, Flow, LinearTra...
'fixed', 'nominal_capacity', 'capacity_loss', 'inflow_conversion_factor', 'outflow_conversion_factor', 'initial_capacity', 'capacity_min', 'capacity_max', 'balanced', 'sort_index') INDEX = ('class', 'label', 'source', 'target') class SolphScenario(EnergySystem): def __init__(self, **kwargs): sup...
t('path', path.dirname(path.realpath(__file__))) self.name = kwargs.get('name') def create_parameter_table(self, additional_parameter=None): """Create an empty parameter table.""" if additional_parameter is None: additional_parameter = tuple() my_index = pd.MultiIndex(l...
JackDanger/sentry
src/sentry/api/endpoints/project_release_file_details.py
Python
bsd-3-clause
7,531
0.000266
from __future__ import absolute_import import posixpath from rest_framework import serializers from rest_framework.response import Response from sentry.api.base import DocSection from sentry.api.bases.project import ProjectEndpoint, ProjectReleasePermission from sentry.api.exceptions import ResourceDoesNotExist from ...
releasefile = ReleaseFile.objects.get(
release=release, id=file_id, ) except ReleaseFile.DoesNotExist: raise ResourceDoesNotExist download_requested = request.GET.get('download') is not None if download_requested and ( request.access.has_scope('project:write')): ...
lissyx/build-mozharness
mozharness/mozilla/release.py
Python
mpl-2.0
1,945
0.002571
#!/usr/bin/env python # ***** BEGIN LICENSE BLOCK ***** # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this file, # You can obtain one at http://mozilla.org/MPL/2.0/. # ***** END LICENSE BLOCK ***** """release.py """ import os fr...
return self.release_config c = self.config dirs = self.query_abs_dirs() if c.get("release_config_file"): self.info("Getting release config from %s..." % c["release_config_file"]) rc = None try: rc = parse_config_file( os....
" ) except IOError: self.fatal("Release config file %s not found!" % c["release_config_file"]) except RuntimeError: self.fatal("Invalid release config file %s!" % c["release_config_file"]) self.release_config['version'] = rc['version'] ...
timothyparez/PyBitmessage
src/bitmessageqt/migrationwizard.py
Python
mit
2,437
0.005334
#!/usr/bin/env python2.7 from PyQt4 import QtCore, QtGui class MigrationWizardIntroPage(QtGui.QWizardPage): def __init__(self): super(QtGui.QWizardPage, self).__init__() self.setTitle("Migrating configuration") label = QtGui.QLabel("This wizard will help you to migrate your configuration. ...
er(QtGui.QWizardPage, self).__init__() self.setTitle("All done!") label = QtGui.QLabel("You successfully migrated.") label.setWordWrap(True) layout = QtGui.QVBoxLayout() layout.addWidget(label) self.setLayout(layout) class Ui_MigrationWizard(QtGui.QWizard): def __...
e = MigrationWizardIntroPage() self.setPage(0, page) self.setStartId(0) page = MigrationWizardAddressesPage(addresses) self.setPage(1, page) page = MigrationWizardGPUPage() self.setPage(2, page) page = MigrationWizardConclusionPage() self.setPage(10, page)...
ProfessorX/Config
.PyCharm30/system/python_stubs/-1247972723/samba/dcerpc/dnsserver/DNS_RPC_ENUM_ZONES_FILTER.py
Python
gpl-2.0
1,215
0.00823
# encoding: utf-8 # module samba.dcerpc.dnsserver # from /usr/lib/python2.7/dist-packages/samba/dcerpc/dnsserver.so # by generator 1.135 """ dnsserver DCE/RPC """ # imports import dcerpc as __dcerpc import talloc as __talloc class DNS_RPC_ENUM_ZONES_FILTER(__talloc.Object): # no doc def __init__(self, *args,...
RpcStructureVersion = property(lambda self: object(), lambda self, v: None, lambda self: None) # default pszPartitionFqdn = property(lambda self: object(), lambda self, v: None, lambda self: None) # default pszQueryString = property(lambda self: object(), lambda self, v: None, lambda self: None) # default ...
property(lambda self: object(), lambda self, v: None, lambda self: None) # default
jhmatthews/cobra
source/disk_sub.py
Python
gpl-2.0
3,164
0.072377
import sys import numpy as np import pylab import matplotlib.pyplot as plt import scipy.integrate import scipy.optimize from collections import namedtuple import geo import astro_help as ah import disk_sub as disk RADIAN=57.29598 C=2.997925e10 MSOL=1.979e33 G=6.670e-8 YR=3.1556925e7 EPSILON=1e-6 PI=3.1416 STEFAN_BOLT...
eq=1000 freq=np.logspace(np.log10(f1),np.log10(f2),nfreq) spec=np.empty(nfreq) dfreq=freq[1]-freq[0] rtemp=np.logspace(np.log10(rmin),np.log10(rmax),num=100) rdisk=[] for j in range(len(rtemp)-1): rdisk.append((rtemp[j]+rtemp[j+1])/2.0) r=rdisk[j]/rmin area=PI*(rtemp[j+1]*rtemp[j+1]-rtemp[
j]*rtemp[j]) t=(disk.teff(tref,r)) for i in range(len(freq)-1): spec[i]=spec[i]+(ah.planck_nu(t,(freq[i+1]+freq[i])/2.0)*area*PI*2*(freq[i+1]-freq[i])) return (freq,spec) def lnu_disk (f,m,mdot,rmin,rmax): tref=tdisk(m, mdot, rmin) rtemp=np.logspace(np.log10(rmin),np.log10(rmax),num=100) rdisk=[] lnu=0.0 ...
JerryXia/fastgoagent
goagent/server/paas/wsgi.py
Python
mit
5,380
0.004833
#!/usr/bin/env python # coding=utf-8 # Contributor: # Phus Lu <[email protected]> __version__ = '3.1.1' __password__ = '' __hostsdeny__ = () # __hostsdeny__ = ('.youtube.com', '.youku.com') import gevent.monkey gevent.monkey.patch_all(subprocess=True) import sys import errno import time import itertools...
ream', '__key_gen'): return getattr(self.__stream, attr) def read(self, size=-1): return self.__cipher.encrypt(self.__stream.read(size)) def forward_socket(local, remote, timeout=60, tick=2, bufsize=8192, maxping=None, maxpong=None):
try: timecount = timeout while 1: timecount -= tick if timecount <= 0: break (ins, _, errors) = select.select([local, remote], [], [local, remote], tick) if errors: break if ins: for sock in ins...
ewandor/home-assistant
homeassistant/helpers/entity_component.py
Python
apache-2.0
17,208
0.000058
"""Helpers for components that manage entities.""" import asyncio from datetime import timedelta from homeassistant import config as conf_util from homeassistant.setup import async_prepare_setup_platform from homeassistant.const import ( ATTR_ENTITY_ID, CONF_SCAN_INTERVAL, CONF_ENTITY_NAMESPACE, DEVICE_DEFAULT...
"""Set up a full entity component. Loads the platforms from the config and will listen for supported discovered platforms. This method must be run in the event loop. """ self.config = config # Look in config for Domain, Domain 2, Domain 3 etc and load them t...
main): tasks.append(self._async_setup_platform(p_type, p_config)) if tasks: yield from asyncio.wait(tasks, loop=self.hass.loop) # Generic discovery listener for loading platform dynamically # Refer to: homeassistant.components.discovery.load_platform() @callback...
MarkWh1te/xueqiu_predict
python3_env/lib/python3.4/site-packages/bpython/test/test_autocomplete.py
Python
mit
16,423
0
# encoding: utf-8 from collections import namedtuple import inspect import keyword import sys try: import unittest2 as unittest except ImportError: import unittest try: import jedi has_jedi = True except ImportError: has_jedi = False from bpython import autocomplete from bpython._py3compat impor...
tEqual(sorted(self.completer.matches(2, '"x')), ['aaaaa', 'abcde']) @mock.patch(glob_function, new=lambda text: ['abcde', 'aaaaa']) @mock.patch('os.path.expanduser', new=lambda te
xt: text) @mock.patch('os.path.isdir', new=lambda text: True) @mock.patch('os.path.sep', new='/') def test_match_returns_dirs_when_dirs_exist(self): self.assertEqual(sorted(self.completer.matches(2, '"x')), ['aaaaa/', 'abcde/']) @mock.patch(glob_function, ...
anurag03/integration_tests
cfme/ansible/repositories.py
Python
gpl-2.0
13,574
0.001842
# -*- coding: utf-8 -*- """Page model for Automation/Ansible/Repositories""" import attr from navmazing import NavigateToAttribute, NavigateToSibling from widgetastic.exceptions import NoSuchElementException from widgetastic.widget import Checkbox, Fillable, ParametrizedView, Text, View from widgetastic_manageiq import...
try: navigate_to(self, "Details") return True except ItemNotFound: return False def delete(self): """Delete the repository in the UI."""
view = navigate_to(self, "Details") if self.appliance.version < "5.9": remove_str = "Remove this Repository" else: remove_str = "Remove this Repository from Inventory" view.toolbar.configuration.item_select(remove_str, handle_alert=True) repo_list_page = se...
mackorone/catan
src/view.py
Python
mit
8,044
0.001119
from color import Color from orientation import Orientation from tile import ( Terrain, Harbor, ) CENTER_TILE_TEMPLATE = [ list(' + -- + '), list(' / \ '), list('+ +'), list(' \ / '), list(' + -- + '), ] BORDER_TILE_TEMPLATE = [ list(' | -- | '), list(' - - ')...
= 1) == (col == 3) else '/' # tile_grid[row][col] = Color.GRAY.apply(char) return tile_grid def replace_resources(tile, tile_grid): if isinstance(tile, Terrain): if not tile.resource: return tile_grid spaces = RESOURCE_SPACES if isinstance(tile, Harbor): # T...
e.orientation: # return tile_grid return tile_grid spaces = NUMBER_SPACES char = '?' if tile.resource: char = tile.resource.color.apply(tile.resource.char) tile_grid = copy_grid(tile_grid) for row, col in spaces: tile_grid[row][col] = char return tile_grid...
tapomayukh/projects_in_python
classification/Classification_with_kNN/Single_Contact_Classification/Scaled_Features/best_kNN_PCA/objects/test11_cross_validate_objects_1200ms_scaled_method_v.py
Python
mit
4,915
0.020753
# Principal Component Analysis Code : from numpy import mean,cov,double,cumsum,dot,linalg,array,rank,size,flipud from pylab import * import numpy as np import matplotlib.pyplot as pp #from enthought.mayavi import mlab import scipy.ndimage as ni import roslib; roslib.load_manifest('sandbox_tapo_darpa_m3') import ro...
############# print 'PCA - COV-Method u
sed' val,vec = linalg.eig(Mcov) #return the projection matrix, the variance and the mean return vec,val,mean_X, M, Mcov def my_mvpa(Y,num2): #Using PYMVPA PCA_data = np.array(Y) PCA_label_2 = ['Styrofoam-Fixed']*5 + ['Books-Fixed']*5 + ['Bucket-Fixed']*5 + ['Bowl-Fixed']*5 + ['Can-Fixed']*...
skooda/passIon
index.py
Python
mit
1,879
0.002129
import logging import pickle from time import time from hashlib import md5 from base64 import urlsafe_b64encode from os import urandom import redis from flask import Flask, request, render_template import config logging.basicConfig(level=logging.DEBUG) app = Flask(__name__,static_folder='public') r = redis.Strict...
nfig.REDIS_HOST, port=config.REDIS_PORT, db=config.REDIS_DB, password=config.REDIS_PASSWORD ) @app.route('/set', methods=['post']) def setPass(): assert request.method == 'PO
ST' password = request.form['pass'] iv = request.form['iv'] uuid = urlsafe_b64encode(md5(urandom(128)).digest())[:8].decode('utf-8') with r.pipeline() as pipe: data = {'status': 'ok', 'iv': iv, 'pass': password} pipe.set(uuid, pickle.dumps(data)) pipe.expire(uuid, config.TTL) ...
commonsense/divisi
doc/demo/vendor_only_svd.py
Python
gpl-3.0
1,871
0.008017
# Put libraries such as Divisi in the PYTHONPATH. import sys, pickle, os sys.path = ['/stuff/openmind'] + sys.path from csc.divisi.cnet import * from csc.divisi.graphics import output_svg from vendor_db import iter_info from csamoa.corpus.models import * from csamoa.conceptnet.models import * # Load the OMCS language ...
r x in text.lower().replace('&', 'and').split() if x not in swords] for x in range(len(words)-wsize+1): pair = " ".join(words[x:x+wsize]) if check_concept(pair): windows.append(pair) if check_concept(words[x]): windows.ap
pend(words[x]) for c in range(wsize-1): if check_concept(words[c]): windows.append(words[c]) return windows if 'vendor_only.pickle' in os.listdir('.'): print "Loading saved matrix." matrix = pickle.load(open("vendor_only.pickle")) else: print "Creating New Tensor" matrix = SparseLabeled...
rbarlow/pulp_docker
plugins/test/unit/plugins/importers/data.py
Python
gpl-2.0
450
0.002222
import os busybox_tar_path = os.path.join(os.path.dirname(__file__), '../../../data/busyboxlight.tar')
# these are in correct ancestry order busybox_ids = ( '769b9341d937a3dba9e460f664b4f183a6cecdd62b337220a28b3deb50ee0a02', '48e5f45168b97799ad0aafb7e2fef9fac57b5f16f6db7f67ba2000eb947637eb', 'bf747efa0e2fa9f7c691588ce3938944c75607a7bb5e757f7369f86904d97c78',
'511136ea3c5a64f264b78b5433614aec563103b4d4702f3ba7d4d2698e22c158', )
hall-lab/svtools
svtools/bedpesort.py
Python
mit
1,152
0.008681
import sys import argparse from svtools.external_cmd import ExternalCmd class BedpeSort(ExternalCmd): def __init__(self): super(BedpeSort, self).__init__('bedpesort', 'bin/bedpesort') def description(): return 'sort a BEDPE file' def epilog(): return 'To read in stdin and output to a file, use /d...
def add_arguments_to_parser(parser): parser.add_argument('input', metavar='<BEDPE file>', nargs='?', help='BEDPE
file to sort') parser.add_argument('output', metavar='<output file>', nargs='?', help='output file to write to') parser.set_defaults(entry_point=run_from_args) def command_parser(): parser = argparse.ArgumentParser(description=description()) add_arguments_to_parser(parser) return parser def run_fr...
Alwnikrotikz/micolog2
plugins/akismet.py
Python
gpl-3.0
8,593
0.055148
#!/usr/bin/env python #coding=utf-8 ''' Created on 2010-4-27 GPL License @author: [email protected] ''' import urllib,pickle,StringIO from micolog_plugin import * from google.appengine.ext import db from model import OptionSet,Comment,Blog,Entry,Blog from google.appengine.api import urlfetch class akismet(Plugin): d...
en(apikey)<5: apikey = self
.AKISMET_default_Key api = AkismetManager(apikey,Blog.all()[0].baseurl) if not code: status = '' elif api.IsValidKey(): status = 'True' else: status = 'False' if rm==True: rmchecked='checked="checked"' else: rmchecked='' return u'''<h3>Akismet</h3> <form action="" method="post"> ...
deshmukhmayur/django-todo
todo/views.py
Python
mit
166
0.006024
from django.sh
ortcuts import render from django.http import HttpResponse # Creat
e your views here. def index(request): return render(request, 'todo/index.html')
swegener/micropython
ports/esp8266/modules/neopixel.py
Python
mit
836
0
# NeoPixel driver for MicroPython on ESP8266 # MIT license; Copyright (c) 2016 Damien P. George from esp import neopixel_write class NeoPixel: ORDER = (1, 0, 2, 3) def __init__(self, pin, n, bpp=3): self.pin = pin
self.n = n self.bpp = bpp self.buf = bytearray(n * bpp) self.pin.init(pin.OUT) def __setitem__(self, index, val): offset = index * self.bpp for i in range(self.bpp): self.buf[offset + self.ORDER[i]] = val[i] def __getitem__(self, index): offset...
for i in range(self.bpp)) def fill(self, color): for i in range(self.n): self[i] = color def write(self): neopixel_write(self.pin, self.buf, True)
headlins/tida
Tida.py
Python
lgpl-3.0
3,125
0.03296
#!/usr/bin/env python import os from gi.repository import Gtk from gi.repository import Vte from gi.repository import GLib from gi.repository import Keybinder from gi.repository import Gdk class Tida(Gtk.Window): """A micro-drop-down terminal like TILDA""" def __init__(self, config=None): Gtk.Window.__init__(sel...
llback function used when press the shortcut for copy to clipboard""" if self.is_visible(): self.term.copy_clipboard() return True return False def callback_paste(self, key, asd): """Callback function used when press the shortcut for paste from clipboard""" if self.is_visible(): self.term.paste_clip...
return True return False def callback_toggle_visibility(self, key, asd): """Callback function used when press the shortcut for toggle visibility of tida""" if self.is_visible(): self.hide() else: self.show_all()
0x1001/funornot
utils/image_convert.py
Python
gpl-2.0
593
0.025295
import md5 import os import sys path = sys.
argv[1] db_file = open(os.path.join(path,"pics_mysql.txt"),"w") for file_name in os.listdir(path): if not file_name.lower().endswith(".gif"): continue with open(os.path.join(path,file_name),"rb") as fp: contents = fp.read() new_file_name = md5.new(contents).hexdigest() + ".gif" ...
T INTO pics (name) VALUES ("' + new_file_name + '");\n') db_file.close()
TieWei/nova
nova/tests/objects/test_pci_device.py
Python
apache-2.0
12,888
0.000155
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright (c) 2012 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.a...
ing permissions and limitations # under the License. import copy from nova import context from nova import db from nova import exception from nova.objects import instance from nova.objects import pci_device from nova.tests.objects import test_objects dev_dict = { 'compute_node_id': 1, 'address': 'a', ...
eated_at': None, 'updated_at': None, 'deleted_at': None, 'deleted': None, 'id': 1, 'compute_node_id': 1, 'address': 'a', 'vendor_id': 'v', 'product_id': 'p', 'dev_type': 't', 'status': 'available', 'dev_id': 'i', 'label': 'l', 'instance_uuid': None, 'extra_info': ...
NickleDave/hybrid-vocal-classifier
tests/scripts/remake_model_files.py
Python
bsd-3-clause
3,608
0.00194
import os from pathlib import Path import shutil import joblib import hvc from config import rewrite_config HERE = Path(__file__).parent DATA_FOR_TESTS = HERE / ".." / "data_for_tests" TEST_CONFIGS = DATA_FOR_TESTS.joinpath("config.yml").resolve() FEATURE_FILES_DST = DATA_FOR_TESTS.joinpath("feature_files").resolv...
xtures find it from inside tmp directories model_file_dst = MODEL_FILES_DST.joinpath(model_name + ".model").resolve() shutil.move(src=model_file, dst=model_file_dst) meta_file = sorted(select_output_dir.glob("*/*.meta"))[-1] meta_file_dst = MODEL_FILES_DST.joinpath(model_name + ".meta") ...
le_dst)) # need to change 'model_filename' in .meta file meta_file = joblib.load(meta_file_dst) meta_file["model_filename"] = os.path.abspath(model_file_dst) joblib.dump(meta_file, meta_file_dst) # clean up -- delete all the other model files, directory, and config shut...
openstack/monasca-notification
monasca_notification/common/repositories/base/base_repo.py
Python
apache-2.0
1,519
0.003292
# Copyright 2015 FUJITSU LIMITED # (C) Copyright 2016 Hewlett Packard Enterprise Development LP # # 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 # ...
y applicable law or agreed to in writing, software distributed under the License # is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express # or implied. See the License for the specific language governing permissions and limitations under # the License. class BaseRepo(object):...
larm_action_sql = \ """SELECT id, type, name, address, period FROM alarm_action as aa JOIN notification_method as nm ON aa.action_id = nm.id WHERE aa.alarm_definition_id = %s and aa.alarm_state = %s""" self._find_alarm_state_sql = \ """SELECT ...
google-research/remixmatch
mixup.py
Python
apache-2.0
4,608
0.002604
# Copyright 2019 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
nt(labels_y) logits_y = get_logits(y) loss_xe = tf.nn.softmax_cross_entropy_with_logits_v2(labels=labels_x, logits=logits_x) loss_xe = tf.reduce_mean(loss_xe) loss_xeu = tf.nn.softmax_cross_entropy
_with_logits_v2(labels=labels_y, logits=logits_y) loss_xeu = tf.reduce_mean(loss_xeu) tf.summary.scalar('losses/xe', loss_xe) tf.summary.scalar('losses/xeu', loss_xeu) ema = tf.train.ExponentialMovingAverage(decay=ema) ema_op = ema.apply(utils.model_vars()) ema_getter = ...
YoshikawaMasashi/magenta
magenta/music/notebook_utils.py
Python
apache-2.0
1,557
0.001927
# Copyright 2016 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
s which run only within a Jupyter notebook.""" # internal imports import IPython
from magenta.music import midi_synth _DEFAULT_SAMPLE_RATE = 44100 def play_sequence(sequence, synth=midi_synth.synthesize, sample_rate=_DEFAULT_SAMPLE_RATE, **synth_args): """Creates an interactive player for a synthesized note sequence. This function shou...
jcherqui/searx
tests/unit/engines/test_bing_news.py
Python
agpl-3.0
7,039
0.000426
from collections import defaultdict import mock from searx.engines import bing_news from searx.testing import SearxTestCase import lxml class TestBingNewsEngine(SearxTestCase): def test_request(self): bing_news.supported_languages = ['en', 'fr'] query = 'test_query' dicto = defaultdict(di...
arch?q=test&amp;setmkt=en-US&amp;first=1&amp;format=RSS</link> </image> <copyright>Cop
yright</copyright> <item> <title>Title</title> <link>http://another.url.of.article/</link> <description>Article Content</description> <pubDate>garbage</pubDate> <News:Source>Infoworld</News:Source> <News:Image>http://another.bing.com/image<...
sloev/pycorm
setup.py
Python
mit
1,378
0.000726
#!/usr/bin/env python # -*- coding: utf-8 -*- try: from setuptools import setup except ImportError: from distutils.core import setup with open('README.rst') as readme_file: readme = readme_file.read() with open('HISTORY.rst') as history_file: history = history_file.read() requirements = [ "jso...
orm': 'pycorm'}, include_package_data=True, install_requires=requirements, license="MIT", zip_safe=False, keywords='pycorm', classifiers=[ 'Development Status :: 2 -
Pre-Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: ISC License (ISCL)', 'Natural Language :: English', "Programming Language :: Python :: 2", 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7' ], test_suite='te...
antoinecarme/sklearn2sql_heroku
tests/classification/BreastCancer/ws_BreastCancer_DummyClassifier_mysql_code_gen.py
Python
bsd-3-clause
142
0.014085
from sklearn2sql_hero
ku.tests.cla
ssification import generic as class_gen class_gen.test_model("DummyClassifier" , "BreastCancer" , "mysql")
yafeunteun/wikipedia-spam-classifier
revscoring/revscoring/scorer_models/test_statistics/precision_recall.py
Python
mit
3,506
0.001141
import io import logging from collections import defaultdict from numpy import linspace from scipy import interp from sklearn.metrics import (auc, average_precision_score, precision_recall_curve) from tabulate import tabulate from .test_statistic import ClassifierStatistic, TestStatistic ...
""" Constructs a precision/recall statistics generator. See https://e
n.wikipedia.org/wiki/Precision_and_recall When applied to a test set, the `score()` method will return a dictionary with four fields: * auc: the area under the precision-recall curve * precisions: a list of precisions * recalls: a list of recalls * thresholds: a list of probability thresho...
dimagi/commcare-hq
corehq/ex-submodules/casexml/apps/phone/tests/dummy.py
Python
bsd-3-clause
1,824
0.000548
from datetime import datetime from casexml.apps.case.xml.generator import date_to_xml_string DUMMY_ID = "foo" DUMMY_USERNAME = "mclovin" DUMMY_PASSWORD = "changeme" DUMMY_PROJECT = "domain" def dummy_user_xml(user=None): username = user.username if user else DUMMY_USERNAME password = user.password if user el...
ata> </Registration>""".format( username, password, user_id, date_to_xml_string(date_joined), project ) DUMMY_RESTORE_XML_TEMPLATE = (""" <OpenRosaResponse xmlns="http://openrosa.org/http/response"%(items_xml)s> <message nature="ota_restore_success">%(message)s</mess...
xmlns="http://commcarehq.org/sync"> <restore_id>%(restore_id)s</restore_id> </Sync> %(user_xml)s %(case_xml)s </OpenRosaResponse> """) def dummy_restore_xml(restore_id, case_xml="", items=None, user=None): return DUMMY_RESTORE_XML_TEMPLATE % { "restore_id": restore_id, "items_...
GoogleCloudPlatform/ai-platform-samples
prediction/xgboost/structured/base/prediction/predict.py
Python
apache-2.0
2,134
0
#!/usr/bin/env python # Copyright 2019 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/L
ICENSE-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 governing permissions and # limitations under the ...
se. # ============================================================================== from google.api_core.client_options import ClientOptions import os import logging import googleapiclient.discovery logging.basicConfig() # In this sample, we will reply on 6 features only: # trip_miles trip_seconds ...
rgayon/plaso
plaso/parsers/amcache.py
Python
apache-2.0
11,498
0.006784
# -*- coding: utf-8 -*- """File containing a Windows Registry plugin to parse the AMCache.hve file.""" from __future__ import unicode_literals import pyregf from dfdatetime import filetime from dfdatetime import posix_time from dfwinreg import definitions as dfwinreg_definitions from plaso.containers import events f...
ackage_code (str): package code of program. product_code (str):
product code of program. publisher (str): publisher of program. uninstall_key (str): unicode string of uninstall registry key for program. version (str): version of program. """ DATA_TYPE = 'windows:registry:amcache:programs' def __init__(self): """Initializes event data.""" super(AMCachePr...
cancerregulome/GeneSpot_1.0
websvcs/endpoints/storage/mongodb_lookups.py
Python
mit
10,153
0.002659
from tornado.options import options, logging from itertools import product import json import tornado.web import pymongo import csv class MongoDbLookupHandler(tornado.web.RequestHandler): def get(self, identity): logging.info("uri=%s [%s] [%s]" % (self.request.uri, identity, self.request.arguments)) ...
"features": { gene_label_1: map(self.jsonable_item, features_1),
gene_label_2: map(self.jsonable_item, features_2) }, "pairwise_results": map(self.jsonable_item, pairwise_results) } log_msg = "Features found: " log_msg += gene_label_1 + ": " + str(len(feature_ids_1)) log_msg += "\t" + gene_label_2 + ": " + str(len(feature_ids...
cxhernandez/mdentropy
mdentropy/metrics/mutinf.py
Python
gpl-3.0
2,347
0
from ..core import mi, nmi from .base import (AlphaAngleBaseMetric, ContactBaseMetric, DihedralBaseMetric, BaseMetric) import numpy as np from itertools import combinations_with_replacement as combinations from multiprocessing import
Pool from contextlib import closing __all__ = ['AlphaAngleMutualInformation', 'ContactMutualInformation', 'DihedralMutualInformation'] class MutualInformationBase(BaseMetric): """Base mutual information object""" def _pa
rtial_mutinf(self, p): i, j = p return self._est(self.n_bins, self.data[i].values, self.shuffled_data[j].values, rng=self.rng, method=self.method) def _exec(self): M = np.zeros((self.labels....
jworr/scheduler
model/staff.py
Python
gpl-2.0
1,931
0.052822
import model EmployeeColumns = ["name", "role_id", "is_active", "street_address", "city", "state", "zip", "phone"] class StaffMember(object): """ Represents a staff member """ def __init__(self, name, roleId, isActive, street=None, city=None, state=None, zipCode=None, phone=None): """ Creates a new staff me...
eColumns, sqlMap, self) #if a old name was given then do an update statement if oldName: query = model.updateString("employee", EmployeeColumns, "name = %(oldName)s") params["oldName"] = oldName #else do a create statement else: query = model.insertString("employee", EmployeeColumns) curs...
s) connection.commit() cursor.close()
hazelcast/hazelcast-python-client
benchmarks/map_bench.py
Python
apache-2.0
1,776
0.001689
import random import time import logging import sys from os.path import dirname sys.path.append(dirname(dirname(dirname(__file__)))) import hazelcast def do_benchmark(): THREAD_COUNT = 1 ENTRY_COUNT = 10 * 1000 VALUE_SIZE = 10000 GET_PERCENTAGE = 40 PUT_PERCENTAGE = 40 logging.basicConfig(f...
ing.") exit() logger.info("Remote Controller Server OK...") rc_cluster = rc.createCluster(None, None) rc_member = rc.startMember(rc_cluster.id) config.network.addresses.append('{}:{}'
.format(rc_member.host, rc_member.port)) except (ImportError, NameError): config.network.addresses.append('127.0.0.1') client = hazelcast.HazelcastClient(config) my_map = client.get_map("default") for i in range(0, 1000): key = int(random.random() * ENTRY_COUNT) operation = int(...
ulif/ulif.openoffice
src/ulif/openoffice/helpers.py
Python
gpl-2.0
22,408
0.000759
# # helpers.py # # Copyright (C) 2011, 2013, 2015 Uli Fouquet # 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 p...
k(linkto, dstname) elif os.path.isdir(srcname):
copytree(srcname, dstname, symlinks, ignore) else: shutil.copy2(srcname, dstname) # XXX What about devices, sockets etc.? except (IOError, os.error) as why: errors.append((srcname, dstname, str(why))) # catch the Error from the recursive copytree so...
sposs/DIRAC
WorkloadManagementSystem/PilotAgent/__init__.py
Python
gpl-3.0
215
0.004651
###############
############################################# # $HeadURL$ ############################################################ """
DIRAC.WorkloadManagementSystem.PilotAgent package """ __RCSID__ = "$Id$"
wibeasley/mayan-playground-1
teagen/chapter_02/calculations_and_variables.py
Python
apache-2.0
306
0.009804
print("-------------- assigning numbers -----------") fred =100 print(fred) print(fred) fred = 200 print(fred) print(fred) john =
fred fred = john print("-------------- assigning letters -----------") adam = "jj" print(adam) print("-------------- assign
ing coins -----------") number_of_coins = 200
citrix-openstack-build/cinder
cinder/scheduler/simple.py
Python
apache-2.0
3,857
0
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright (c) 2010 OpenStack, LLC. # Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # ...
.service_is_up(service): raise exception.WillNotSchedule(host=host) updated_volume = driver.volume_update_db(context, volume_id, host) self.volume_rpcapi.create_volume(context, updated_volume, ...
snapshot_id, image_id) return None results = db.service_get_all_volume_sorted(elevated) if zone: results = [(service, gigs) for (service, gigs) in results if service['availability_zone'] == zone] ...
zstackio/zstack-woodpecker
integrationtest/vm/virtualrouter/ceph_pool_capacity/test_ceph_pool_cap_crt_vm_image.py
Python
apache-2.0
989
0.001011
''' New Integration Test for Ceph Pool Capacity. @author: Legion ''' import zstackwoodpecker.test_util as test_util import zstackwoodpecker.test_lib as test_lib import zstackwoodpecker.test_state as test_state import time test_stub = test_lib.lib_get_test_stub() test_obj_dict = test_state.TestStateDict() pool_cap = ...
pool_cap.check_pool_cap([used1, avail1], bs=True) pool_cap.vm.destroy() test_obj_dict.rm_vm(pool_cap.vm) test_lib.lib_robot_cleanup(test_obj_dict) test_util.test_pass('Ceph Image Pool Capacity Test Success')
#Will be called only if exception happens in test(). def error_cleanup(): global test_obj_dict test_lib.lib_error_cleanup(test_obj_dict)
MungoRae/home-assistant
homeassistant/components/sensor/bme280.py
Python
apache-2.0
6,473
0
""" Support for BME280 temperature, humidity and pressure sensor. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/sensor.bme280/ """ import asyncio from datetime import timedelta from functools import partial import logging import voluptuous as vol from...
"""Return the state of the sensor.""" return self._state @property def unit_of_measurement(self): """Return the unit of measurement of the sensor.""" return self._unit_of_measuremen
t @asyncio.coroutine def async_update(self): """Get the latest data from the BME280 and update the states.""" yield from self.hass.async_add_job(self.bme280_client.update) if self.bme280_client.sensor.sample_ok: if self.type == SENSOR_TEMP: temperature = roun...
DBeath/flask-feedrsub
feedrsub/utils/profiler.py
Python
mit
386
0
import cProfile import StringIO import pstats import contextlib @contextlib.
contextmanager def profiled(): pr = cProfile.Profile() pr.enable() yield pr.disable() s = StringIO.StringIO() ps = pstats.Stats(pr, stream=s).sort_stats("cumulative") ps.print_stats() # uncomment this to see who's calling what # ps.print_callers() print(s.getvalue(
))
aspose-cells/Aspose.Cells-for-Cloud
Examples/Python/Examples/GetMergedCellFromWorksheet.py
Python
mit
1,392
0.010057
import asposecellscloud from asposecellscloud.CellsApi import CellsApi from asposecellscloud.CellsApi import ApiException import asposestoragecloud from asposestoragecloud.StorageApi import StorageApi apiKey = "XXXXX" #sepcify App Key appSid = "XXXXX" #sepcify App SID apiServer = "http://api.aspose.com/v1.1" data_fol...
piClient) #Instantiate Aspose Cells API SDK api_client = asposecellscloud.ApiClient.ApiClient(apiKey, appSid, True) cellsApi = CellsApi(api_client); #set input file name filename = "Sample_Test_Book.xls" sheetName = "Sheet1" mergedCellIndex = 0 #upload file to aspose cloud stora
ge #storageApi.PutCreate(Path=filename, file=data_folder + filename) try: #invoke Aspose.Cells Cloud SDK API to get merged cells from a worksheet response = cellsApi.GetWorkSheetMergedCell(name=filename, sheetName=sheetName, mergedCellIndex=mergedCellIndex) if response.Status == "OK": mergedCell =...
simphony/simphony-remote
remoteappmanager/cli/remoteappadmin/__main__.py
Python
bsd-3-clause
1,056
0
import sys # pragma: no cover from remoteappmanager.command_line_config import ( CommandLineConfig) # pragma: no cover from remoteappmanager.environment_config import ( EnvironmentConfig) # p
ragma: no cover from remoteappmanager.file_config import FileConfig # pragma: no cover
from tornado.options import print_help # pragma: no cover from remoteappmanager.admin_application import ( AdminApplication) # pragma: no cover def main(): # pragma: no cover try: command_line_config = CommandLineConfig() command_line_config.parse_config() file_config = FileConf...
dreamibor/Algorithms-and-Data-Structures-Using-Python
practice/implementation/linked_list/merge_k_sorted_list.py
Python
gpl-3.0
4,308
0.009749
""" Linked List: Merge K Sorted Lists (hard) Description: You are given an array of k linked-lists lists, each linked-list is sorted in ascending order. Merge all the linked-lists into one sorted linked-list and return it. Example: Input: lists = [[1,4,5],[1,3,4],[2,6]] Output: [1,1,2,3,4,4,5,6] Explanation: The li...
, 2->6 ] merging them into one sorted lis
t: 1->1->2->3->4->4->5->6 Solutions: 1. Brute force - Add all nodes in all lists into one list and then sort. 2. Brute force - Merge list one by one. 3. Divide and conquer - Merge half and half's half, ... 4. Priority queue - Get minimum element each time. Notes: For the priority queue based method, we need to Leet...
magicgoose/dr14_t.meter
dr14tmeter/table.py
Python
gpl-3.0
16,975
0.043122
# dr14_t.meter: compute the DR14 value of the given audiofiles # Copyright (C) 2011 Simone Riva # # 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...
def append_empty_line( self ): self.append_row( [ "" ] ) def add_title( self , title ): self._append_txt( title + self.nl() )
def new_table( self ): self._set_txt("") def end_table( self ): self._append_txt( self.nl() ) def new_row( self ): self._append_txt("") def end_row( self ): self._append_txt( self.nl() ) def new_cell( self ): self._append_txt("") def ...
superdesk/Live-Blog
plugins/livedesk-sync/livedesk/api/blog_sync.py
Python
agpl-3.0
3,125
0.0144
''' Created on April 26, 2013 @package: livedesk @copyright: 2013 Sourcefabric o.p.s. @license: http://www.gnu.org/licenses/gpl-3.0.txt @author: Mugur Rus API specifications for liveblo
g sync. ''' from ally.support.api.entity import Entity, IEntityService, QEntity from livedesk.api.blog import Blog from datetime import datetime from livedesk.api.domain_livedesk import modelLiveDesk from ally.api.c
onfig import query, service, LIMIT_DEFAULT, call, UPDATE from ally.api.criteria import AsRangeOrdered, AsDateTimeOrdered, AsBoolean from superdesk.source.api.source import Source from ally.api.type import Iter from superdesk.source.api.type import SourceType # ----------------------------------------------------------...
jrugis/cell_mesh
mesh2vtk.py
Python
gpl-3.0
2,909
0.024751
#!/usr/bin/python import numpy as np mdir = "mesh3d/" fname = "out_p6-p4-p8" #################### print "input mesh data file" f1 = open(mdir+fname+".mesh", 'r') for line in f1: if line.startswith("Vertices
"): break pcount = int(f1.next()) xyz = np.empty((pcount, 3), dtype=np.float) for t in range(pcount): xyz[t] = map(float,f1.n
ext().split()[0:3]) for line in f1: if line.startswith("Triangles"): break trisc = int(f1.next()) tris = np.empty((trisc,4), dtype=int) for t in range(trisc): tris[t] = map(int,f1.next().split()) for line in f1: if line.startswith("Tetrahedra"): break tetsc = int(f1.next()) tets = np.empty((tetsc,5), dtype=i...
blondegeek/pymatgen
pymatgen/__init__.py
Python
mit
3,203
0.002498
import sys import os import warnings import ruamel.yaml as yaml from fnmatch import fnmatch __author__ = "Pymatgen Development Team" __email__ ="[email protected]" __maintainer__ = "Shyue Ping Ong" __maintainer_email__ ="[email protected]" __version__ = "2019.7.2" SETTINGS_FILE = os.path.join(os.path.expandu...
raise ValueError("No structure with formula %s in Materials Project!" % formula) elif len(entries) > 1: warnings.warn("%d structures with formula %s found in Materials " "Project. The lowest energy structure will be returned." % (len(e...
if sys.version_info < (3, 5): warnings.warn(""" Pymatgen will drop Py2k support from v2019.1.1. Pls consult the documentation at https://www.pymatgen.org for more details.""") def loadfn(fname): """ Convenience method to perform quick loading of data from a filename. The type of object returned depen...
skrzym/monday-morning-quarterback
Application/Site/mmq/main/controllers.py
Python
mit
7,841
0.054202
<<<<<<< HEAD from flask import Blueprint, render_template, request, url_for, jsonify from config import mongo import pandas as pd import json from bson import json_util import retrieve_model as rmodel from collections import Counter main = Blueprint('main', __name__, template_folder='templates') @main.route('/') de...
meunder', 'yrdline100', 'scorediff'] ] calculations.append({'request':rmodel.predict_proba( arg_dict['quarter'], arg_dict['down'], arg_dict['yards'], arg_dict['clock'],
arg_dict['field'], arg_dict['score'], False) }) return jsonify(calculations) ======= scenarios=scenarios ) except: return "fail" >>>>>>> master
rabipanda/tensorflow
tensorflow/contrib/py2tf/impl/naming_test.py
Python
apache-2.0
2,895
0.003454
# Copyright 2017 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...
function_name_avoids_global_conflicts(self): def foo(): pass namer = naming.Namer({'tf__foo': 1}, True, None, ()) self.assertEqual(('tf__foo_1', True), namer.compiled_function_name('foo', foo)) def test_new_symbol_tracks_names(self):
namer = naming.Namer({}, True, None, ()) self.assertEqual('temp', namer.new_symbol('temp', set())) self.assertItemsEqual(('temp',), namer.generated_names) def test_new_symbol_avoids_duplicates(self): namer = naming.Namer({}, True, None, ()) self.assertEqual('temp', namer.new_symbol('temp', set())) ...
aforalee/rally
tests/unit/task/processing/test_charts.py
Python
apache-2.0
19,909
0
# Copyright 2015: Mirantis 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...
"atomic": {"foo": {}, "bar": {}}}) self.assertIsInstance(chart, charts.AvgChart) [chart.add_iteration({"atomic_actions": costilius.OrderedDict(a)}) for a in ([("foo", 2), ("bar", 5)], [("foo", 4)], [("bar", 7)])] self.assertEqual([("bar", 4.0), ("foo", 2.0)], so...
"tstamp_start": 12345, "kwargs": {"scale": 10}, "data": [
MounirMesselmeni/django
tests/utils_tests/test_lazyobject.py
Python
bsd-3-clause
11,862
0.000506
from __future__ import unicode_literals import copy import pickle import sys import warnings from unittest import TestCase from django.utils import six from django.utils.functional import LazyObject, SimpleLazyObject, empty from .models import Category, CategoryInfo class Foo(object): """ A simple class wi...
one'] = -1 self.assertEqual(lazydict['one'],
-1) self.assertIn('one', lazydict) self.assertNotIn('two', lazydict) self.asse
marcoconstancio/yanta
actions/horizontal_rule/horizontal_rule.py
Python
gpl-2.0
200
0.005
# -*- coding: utf-8 -*- class ho
rizontal_rule: def __init__(self): pa
ss @staticmethod def process(data, args): data['note_viewer'].call_function('insert_horizontal_rule')
mufaddalq/cloudstack-datera-driver
test/integration/smoke/test_loadbalance.py
Python
apache-2.0
25,268
0.001979
# 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 u...
ient, cls.services["server"]
, templateid=template.id, accountid=cls.account.name, domainid=cls.account.domainid, serviceofferingid=cls.service_offering.id ) cls...
mandli/surge-examples
harvey/setplot.py
Python
mit
12,304
0.002682
from __future__ import absolute_import from __future__ import print_function import os import numpy import matplotlib.pyplot as plt import datetime import clawpack.visclaw.colormaps as colormap import clawpack.visclaw.gaugetools as gaugetools import clawpack.clawutil.data as clawutil import clawpack.amrclaw.data as...
'Aransas Wildlife Refuge'), ('8775237', 'Port Aransas'), ('8775296', 'USS Lexington')] landfall_time = numpy.datetime64('2017-08-25T10:00') begin_date = datetime.datetime(2017, 8, 24) end_date = datetime.datetime(2017, 8, 28) def get_actual_water_levels(...
_noaa_tide_data(station_id, begin_date, end_date) # Calculate times relative to landfall seconds_rel_landfall = (date_time - landfall_time) / numpy.timedelta64(1, 's') # Subtract tide predictions from measured water levels water_level -= tide return seconds_rel_...
aedoler/is210-week-03-synthesizing
task_01.py
Python
mpl-2.0
183
0
#!/usr/bin/env pyth
on # -*- coding: utf-8 -*- """Contains expectations.""" import inquisition FISHY = inquisition.SPANISH FISH
Y = FISHY.replace('surprise', 'haddock') print FISHY
xaedes/PyCompuPipe
pycompupipe/components/processing/process_output.py
Python
mit
525
0.009579
#!/usr/bin/env python2 # -*- coding: utf-8 -*- from __future__ import division # Standardmäßig float division - Ganzzahldivision kann man explizit mit '//' durchführen from __future__ import absolute_import import pygame from pyecs import * # from pyecs.components import * # from components import * class Process...
string for ProcessOutput""" def __init__(self, process, *args,**kwargs): super(ProcessOutput, self).__init__(*args,**kwargs)
self.process = process
spectralflux/colossus
tests/test_route.py
Python
mit
458
0.004367
from colossus.game import Route def test_route_step(): route = R
oute(100.0, 1) route.add_packet() dmg = route.update(10.0) assert dmg <= 0.0 dmg = 0.0 dmg += route.update(100000.0) dmg += route.update(100000.0) assert dmg > 0.0 def test_route_removal_of_packet_after_action(): route = Route(1.0, 1) route.add_packet() assert route.packet_co
unt() == 1 route.update(100.0) assert route.packet_count() == 0
mscuthbert/abjad
abjad/tools/quantizationtools/test/test_quantizationtools_QGrid___call__.py
Python
gpl-3.0
3,905
0.000256
# -*- encoding: utf-8 -*- from abjad import * from abjad.tools.quantizationtools import * def test_quantizationtools_QGrid___call___01(): q_grid = QGrid() a = QEventProxy(SilentQEvent(0, ['A']), 0) b = QEventProxy(SilentQEvent((1, 20), ['B']), (1, 20)) c = QEventProxy(SilentQEvent((9, 20), [...
['G']), 1) q_grid.fit_q_events([a, b, c, d, e, f, g]) result = q_grid((1, 4)) assert isinstance(result, list) and len(result) == 1 assert systemtools.TestManager.compare( result[0], r''' \times 2/3 { c'8 c'16 c'16 \times 2/3...
'16 c'16 c'16 } } ''' ) leaf = result[0].select_leaves()[0] annotation = inspect_(leaf).get_indicators(indicatortools.Annotation)[0] assert isinstance(annotation.value, tuple) and len(annotation.value) == 2 assert annotation.value[0].a...
mikolajsacha/tweetsclassification
src/features/word_embeddings/iword_embedding.py
Python
mit
1,681
0.003569
""" Contains basic interface (abstract base class) for word embeddings. """ import os from abc import ABCMeta, abstractmethod class IWordEmbedding(object): """ Abstract base class for word embeddings """ __metaclass__ = ABCMeta def __init__(self, path, vector_length): self.model = None ...
not self.already_built: print("Loading pre-trained word embedding from
{0}...".format(self.path)) self._build() self.already_built = True print("Pre-trained word embedding from {0} loaded!".format(self.path)) def get_embedding_model_path(self): """ :return: absolute path to folder containing saved word embedding model """ return os...
deeplearning4j/deeplearning4j
libnd4j/include/graph/generated/nd4j/graph/FlatProperties.py
Python
apache-2.0
7,580
0.005937
# automatically generated by the FlatBuffers compiler, do not modify # namespace: graph import flatbuffers class FlatProperties(object): __slots__ = ['_tab'] @classmethod def GetRootAsFlatProperties(cls, buf, offset): n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) x ...
s.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) if o != 0: return self._tab.GetVectorAsNumpy(flatbuffers.number_types.Int32Flags, o) return
0 # FlatProperties def ILength(self): o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) if o != 0: return self._tab.VectorLen(o) return 0 # FlatProperties def L(self, j): o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offs...
mayhem/led-chandelier
software/patterns/sweep_two_color_shift.py
Python
mit
1,663
0.004811
#!/usr/bin/env python3 import os import sys import math from colorsys import hsv_to_rgb from random import random from hippietrap.hippietrap import HippieTrap, ALL, NUM_NODES from hippietrap.color import Color, ColorGenerator, random_color, hue_to_color from hippietrap.geometry import HippieTrapGeometry fro
m hippietrap.pattern import PatternBase, run_pattern from time import sleep, time class SweepTwoColorShiftPattern(PatternBase): geo = HippieTrapGeometry() cg = ColorGenerator() name = "sweep two colors" color_shift_between_rings = .045 def pattern(self): self.trap.send_decay(ALL, 90) ...
= 0.0 stop = False color_rings = [ random_color(), random_color(), random_color() , random_color() ] while not stop: for bottle, angle in self.geo.enumerate_all_bottles(index % 2 == 0): self.trap.set_color(bottle, color_rings[self.geo.get_ring_from_bottle(bottle)]) ...
ddurieux/alignak
alignak/db_oracle.py
Python
agpl-3.0
4,741
0.001477
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (C) 2015-2015: Alignak team, see AUTHORS.txt file for contributors # # This file is part of Alignak. # # Alignak 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 So...
n, [email protected] # Jean Gabes, [email protected] # Zoran Zaric, [email protected] # This file is part of Shinken. # # Shinken 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 ...
or # (at your option) any later version. # # Shinken is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have receiv...
vmlaker/mpipe
doc/source/conf.py
Python
mit
7,581
0.006068
# -*- coding: utf-8 -*- # # All configuration values have a default; values that are commented out # serve to show the default. import sys, os # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation r...
, # '**' : ['searchbox.html', 'search.html'], # '**' : ['searchbox.html'], } # Additional templates that should be rendered to pages, maps page names to # template names. html_additional_pages = { 'search' : 'search.html' } # If false, no module index is generated. html_domain_indices = False ...
tter. html_split_index = False # If true, links to the reST sources are added to the pages. html_show_sourcelink = False # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. html_show_copyr...
kevinwchang/Minecraft-Overviewer
overviewer_core/aux_files/genPOI.py
Python
gpl-3.0
21,247
0.003624
#!/usr/bin/env python2 ''' genPOI.py Scans regionsets for TileEntities and Entities, filters them, and writes out POI/marker info. A markerSet is list of POIs to display on a tileset. It has a display name, and a group name. markersDB.js holds a list of POIs in each group markers.js holds a list of which markerSet...
eld] = jsonText(poi[field]) return poi def handleEntities(rset, config, config_path, filters, markers): """ Add markers for Entities or TileEntities. For this every chunk of the regionset is parsed and filtered using multiple processes, if so configured. This function will not return anything...
es']; if numbuckets < 0: numbuckets = multiprocessing.cpu_count() if numbuckets == 1: for (x, z, mtime) in rset.iterate_chunks(): try: data = rset.get_chunk(x, z, entities_only=True) for poi in itertools.chain(data['TileEntities'], data['Entities']): ...
piotroxp/scibibscan
scib/lib/python3.5/site-packages/astropy/modeling/tests/test_parameters.py
Python
mit
21,265
0.000611
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ Tests models.parameters """ from __future__ import (absolute_import, division, print_function, unicode_literals) import itertools import numpy as np from numpy.testing import utils from . import irafutil from .. import model...
0, 0, 0, 0, 0, 0]) utils.assert_equal(p1.c0, [0, 0, 0]) p1.c0 = [10, 10, 10] utils.assert_equal(p1.parameters, [10.0, 10.0, 10.0, 0,
0, 0, 0, 0, 0, 0, 0, 0]) def test_par_slicing(self): """ Test assigning to a parameter slice """ p1 = models.Polynomial1D(3, n_models=3) p1.c0[:2] = [10, 10] utils.assert_equal(p1.parameters, [10.0, 10.0, 0.0, 0, 0, ...
cpcloud/numba
numba/tests/test_unicode.py
Python
bsd-2-clause
93,714
0.000151
# -*- coding: utf-8 -*- from itertools import product from itertools import permutations from numba import njit from numba.core import types, utils import unittest from numba.tests.support import (TestCase, no_pyobj_flags, MemoryLeakMixin) from numba.core.errors import TypingError, UnsupportedError from numba.cpython....
return l def title(x): return x.title() def literal_iter_usecase(): l = [] for i in '大处着眼,小处着手。': l.append(i) return l def enumerated_iter_usecase(x): buf = "" scan = 0 for i, s in enumerate(x): buf += s scan += 1 return buf, scan def iter_stopiteration...
l_iter_stopiteration_usecase(): s = '大处着眼,小处着手。' i = iter(s) n = len(s) for _ in range(n + 1): next(i) def islower_usecase(x): return x.islower() def lower_usecase(x): return x.lower() def ord_usecase(x): return ord(x) def chr_usecase(x): return chr(x) class BaseTest(Me...
blzq/infer
infer/lib/python/inferlib/capture/ant.py
Python
bsd-3-clause
2,914
0
# Copyright (c) 2015 - present Facebook, Inc. # All rights reserved. # # This source code is licensed under the BSD style license found in the # LICENSE file in the root directory of this source tree. An additional grant # of patent rights can be found in the PATENTS file in the same directory. import logging import o...
e_quotes(content) javac_arguments.append(arg) if j
avac_arguments != []: capture = jwlib.create_infer_command(javac_arguments) calls.append(capture) javac_arguments = [] return calls def capture(self): (code, verbose_out) = util.get_build_output(self.build_cmd) if code != os.EX_OK: return code...
ic-hep/DIRAC
src/DIRAC/FrameworkSystem/Service/TokenManagerHandler.py
Python
gpl-3.0
8,162
0.001715
""" TokenManager service .. literalinclude:: ../ConfigTemplate.cfg :start-after: ##BEGIN TokenManager: :end-before: ##END :dedent: 2 :caption: TokenManager options """ import pprint from DIRAC import gLogger, S_OK, S_ERROR from DIRAC.Core.Security import Properties from DIRAC.Core.Tornado....
credDict = self.getRemoteCredentials() result = Registry.getDNForUsername(credDict["username"]) if not result["OK"]: return result for dn in result["Value"]: result = Registry.getIDFromDN(dn
) if result["OK"]: result = self.__tokenDB.getTokensByUserID(result["Value"]) if not result["OK"]: gLogger.error(result["Message"]) tokensInfo += result["Value"] return tokensInfo def __generateUserTokensInfo(self): """...
arokem/bowties
params.py
Python
apache-2.0
464
0.064655
p = dict( subject = 'EG009', #Fixation size (in degrees)
: fixation_size = 0.4, monitor='testMonitor', scanner=True, screen_number = 1, full_screen = True, radial_cyc = 10, angular_cyc = 15, angular_width=30, size = 60, #This just needs to be larger than the screen temporal_freq = 2, sf = 10, n_blocks = 20, #20 blocks
= 200 sec = 3:20 minutes block_duration=10, color_dur = 1/3. # 2 Hz )
gomezstevena/x-wind
src/navierstokesRun.py
Python
gpl-3.0
709
0.004231
import os import sys from numpy imp
ort * from scipy.integrate import ode from scipy.interpolate import griddata from mesh import * from navierstokes import NavierStokes nE = 5000 dt = 0.0005 nsteps = 2000 Mach = 0.3 Re = 10000 HiRes = 1. z = load('data/navierstokesInit.npz') geom, v, t, b, soln = z['geom'], z['v'], z['t'], z['b'], z['soln'] solver =...
= {0}\n'.format(solver.time)); sys.stdout.flush() fname = 'data/navierstokesStep{0:06d}.npz'.format(istep) savez(fname, geom=array(geom), v=v, t=t, b=b, soln=solver.soln)
Curahelper/Cura
plugins/3MFWriter/ThreeMFWriter.py
Python
agpl-3.0
7,998
0.006627
# Copyright (c) 2015 Ultimaker B.V. # Uranium is released under the terms of the AGPLv3 or higher. from UM.Mesh.MeshWriter import MeshWriter from UM.Math.Vector import Vector from UM.Logger import Logger from UM.Math.Matrix import Matrix from UM.Application import Application import UM.Scene.SceneNode import Savitar ...
whereas cura uses the center of the # build volume. if global_container_stack: translation_vector = Vector(x=global_container_stack.getProperty("machine_width", "value") / 2,
y=global_container_stack.getProperty("machine_depth", "value") / 2, z=0) translation_matrix = Matrix() translation_matrix.setByTranslation(translation_vector) transformation_matrix.preMultiply(translation_matrix) ...
dhermyt/WONS
configuration/Encoder.py
Python
bsd-2-clause
258
0
import json class SettingsEncoder(json.JSONEncoder):
def default(self, obj): if isinstance(obj, type): return obj.__name__ if callable(obj):
return obj.__name__ return json.JSONEncoder.default(self, obj)
dankilman/clue
clue/tests/test_git.py
Python
apache-2.0
16,458
0
######## # Copyright (c) 2016 GigaSpaces Technologies Ltd. All rights reserved # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless...
git.reset('HEAD~') output = self.clue.git.status().stdout.strip() self.assertRegexpMatches(output, r'.*cloudify-rest-client.*\| .*3.3.1-build') self.assertRegexpMatches(output, r'.*cloudify-rest-client.*\| .*' ...
, 'HEAD') self.clue.feature.checkout('test') output = self.clue.git.status(active=True).stdout.strip() self.assertIn('cloudify-rest-client', output) self.assertNotIn('flask-securest', output) self.assertNotIn('cloudify-script-plugin', output) def test_checkout(self): ...