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
ajnelson/dfxmlfs
dfxmlfs.py
Python
lgpl-2.1
10,784
0.006677
#!/usr/bin/env python # HelloFS Copyright (C) 2006 Andrew Straw <strawman@astraw.com> # # DFXMLFS Copyright (C) 2015 Prometheus Computing, LLC. # Implemented by Alex Nelson <a.nelson@prometheuscomputing.com> # # This program can be distributed under the terms of the GNU LGPL v2.1. # See the file CO...
th.basename(filepath) dirname = os.path.dirname(filepath) self.dir_lists_by_path["/" + dirname].append(basename) #Shorten reading DFXML files in debug settings if "debug" in self.fuse_args.optlist and tup_no > 50:
_logger.debug("Shortening object parsing while in debug mode: Only 50 file objects read from XML.") break #Assign inode numbers for objects that were in the stream first for obj in objects_without_inode_numbers: obj.inode = self._next_inode_number() #Creating ...
saurabh6790/medsyn-app1
selling/doctype/patient_encounter_entry/patient_encounter_entry.py
Python
agpl-3.0
25,080
0.016627
from __future__ import unicode_literals import webnotes from webnotes.utils import flt, fmt_money, cstr, cint from selling.doctype.customer.customer import DocType import datetime from webnotes import msgprint, _ from selling.doctype.lead.lead import create_contact from webnotes.model.code import get_obj from webnotes...
&dcs="+ args["dcs"]+ "&msgtxt=" + msg +"&state=" +args["state"] # webnotes.errprint(url) import requests r = requests.get(url) def create_new_contact(self): details = {} detail...
.mobile or '' details['doc']='Customer' details['link']=self.doc.name or '' create_contact(details) def create_customer(self, patient_id): from webnotes.model.doc import Document d = Document('Customer') d.customer_...
shalomeir/snippod-boilerplate
snippod_boilerplate/wsgi.py
Python
mit
471
0.006369
""" WSGI config for thinkster_django_angular_boilerpla
te 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.7/howto/deployment/wsgi/ """ import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "snippod_boilerplate.settings.prod") from django
.core.wsgi import get_wsgi_application from dj_static import Cling application = Cling(get_wsgi_application())
Germanika/plover
test/test_key_combo.py
Python
gpl-2.0
4,119
0.005098
from plover.key_combo import parse_key_combo from . import TestCase class KeyComboParserTest(TestCase): def test_noop(self): for combo_string in ('', ' '): self.assertEqual(parse_key_combo(combo_string), []) def test_syntax_error(self): for combo_string in ( # Inv...
[(10, True), (10, False), (10, True), (10, False)]) for combo_string in ( '1 ( exclam )', 'exclam(1)', ): msg = 'parse_key_combo(%r): ValueError not raised' % ( combo_string, ) with self.as...
ing, key_name_to_key_code=name2code.get)
ResearchSoftwareInstitute/MyHPOM
hs_app_netCDF/tests/test_netcdf_metadata.py
Python
bsd-3-clause
34,897
0.003754
import os import tempfile import shutil from django.test import TransactionTestCase from django.core.exceptions import ValidationError from django.core.files.uploadedfile import UploadedFile from django.contrib.auth.models import Group from django.db import IntegrityError from hs_core import hydroshare from hs_core.h...
target_temp_netcdf_file = os.path.join(self.temp_dir, self.netcdf_file_name) shutil.copy(self.netcdf_file, target_temp_netcdf_file) sel
f.netcdf_file_obj = open(target_temp_netcdf_file, 'r') self.temp_dir = tempfile.mkdtemp() self.netcdf_file_name_crs = 'netcdf_valid_crs.nc' self.netcdf_file_crs = 'hs_app_netCDF/tests/{}'.format(self.netcdf_file_name_crs) target_temp_netcdf_file_crs = os.path.join(self.temp_dir, self.ne...
mbrucher/AudioTK
tests/Python/EQ/PyATKEQ_custom_test.py
Python
bsd-3-clause
1,779
0.023609
#!/usr/bin/env python from ATK.EQ import DoubleCustomFIRFilter, DoubleCustomIIRFilter import numpy as np from nose.tools import raises sampling = 48000 @raises(ValueError) def customFIR_bad_dim_test(): import numpy as np filter = DoubleCustomFIRFilter() filter.coefficients_in = np.ones(()) @raises(ValueErro...
ilter.coefficients_in = np.ones((10)) assert_almost_equal(filter.coefficients_in, np.ones((10))) @raises(ValueError) def customIIR_bad_dim_test(): import numpy as np filter = DoubleCustomIIRFilter() filter.coefficients_in = np.ones(()) @raises(ValueError) def customIIR_bad_size_test(): import numpy as np ...
): import numpy as np from numpy.testing import assert_almost_equal filter = DoubleCustomIIRFilter() filter.coefficients_in = np.ones((10)) assert_almost_equal(filter.coefficients_in, np.ones((10))) @raises(ValueError) def customIIR_bad_dim2_test(): import numpy as np filter = DoubleCustomIIRFilter() ...
hswhite33/picturegame-bot
src/utils/MarkdownUtils.py
Python
mit
279
0.007168
def escapeChar
s(name): '''Escape markdown characters to avoid usernames getting rendered weirdly in som
e cases. The only known case is with underscores, and that is only in a special case, but we'll do a generalized fix here. ''' return name.replace('_', '\\_')
florian-f/sklearn
sklearn/cluster/tests/test_hierarchical.py
Python
bsd-3-clause
6,780
0
""" Several basic tests for hierarchical clustering procedures """ # Authors: Vincent Michel, 2010, Gael Varoquaux 2012 # License: BSD-like import warnings from tempfile import mkdtemp import numpy as np from scipy import sparse from scipy.cluster import hierarchy from sklearn.utils.testing import assert_true from s...
10) # Check that we raise a TypeError on dense matrices clustering = Ward(n_clusters=10, connectivity=connectivity.todense()) assert_raises(TypeError, clustering.fit, X) clustering = Ward(n_clusters=10, connectivity=sparse.lil_matrix( ...
we obtain the correct solution in a simplistic case """ rnd = np.random.RandomState(0) mask = np.ones([10, 10], dtype=np.bool) X = rnd.randn(50, 100) connectivity = grid_to_graph(*mask.shape) ward = WardAgglomeration(n_clusters=5, connectivity=connectivity) ward.fit(X) assert_true(np.siz...
akx/shoop
shoop/core/taxing/_context.py
Python
agpl-3.0
720
0.002778
# This file is part of Shoop. # # Copyright (c) 2012-2016, Shoop Ltd. All rights reserved. # # This source code is licensed under the AGPLv3 license found in the # LICENSE file in the root directory of this source tree. class TaxingContext(object): def __init__(self, customer_tax_group=None, customer_tax_number=N...
ustomer_tax_number = customer_tax_number self.country_code = getattr(location, "country_code", None) or getattr(location, "country", None) self.region_code = geta
ttr(location, "region_code", None) self.postal_code = getattr(location, "postal_code", None) self.location = location
nathanbjenx/cairis
cairis/gui/OMPanel.py
Python
apache-2.0
3,444
0.01626
# 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...
') def addObject(self): grid = self.FindWindowById(ID_REQGRID) pos = grid.GetGridCursorR
ow() grid.InsertRows(pos)
xaxa89/mitmproxy
test/mitmproxy/addons/test_streamfile.py
Python
mit
1,682
0
import pytest from mitmproxy.test import taddons from mitmproxy.test import tflow from mitmproxy import io from mitmproxy import exceptions from mitmproxy import options from mitmproxy.addons import streamfile def test_configure(tmpdir): sa = streamfile.StreamFile() with taddons.context(options=options.Opti...
a.filt def rd(p): x = io.FlowReader(open(p, "rb")) return list(x.stream()) def test_tcp(tmpdir): sa = streamfile.StreamFile() with taddons.context() as tctx: p = str
(tmpdir.join("foo")) tctx.configure(sa, streamfile=p) tt = tflow.ttcpflow() sa.tcp_start(tt) sa.tcp_end(tt) tctx.configure(sa, streamfile=None) assert rd(p) def test_simple(tmpdir): sa = streamfile.StreamFile() with taddons.context() as tctx: p = str(tm...
valhallasw/phabricator-tools
py/abd/abdt_rbranchnaming__t.py
Python
apache-2.0
3,352
0
"""Test suite for abdt_rbranchnaming.""" # ============================================================================= # TEST PLAN # ----------------------------------------------------------------------------- # Here we detail the things we are concerned to test and specify which te...
ns. # # Concerns: # [XB] review names that are globally known to be bad are not accepted # [XB] tracker names that are globally known to be bad are not accepted # [XC] names that are known to be potential reviews aren't accepted as trackers # [XC] names that
are known to be potential trackers aren't accepted as reviews # [XD] ReviewBranches created by the scheme have the expected attributes # [XD] ReviewBranches created by the scheme can create expected TrackerBranches # [XD] TrackerBranches created by the scheme have the expected attributes # [XD] there is a 1-1 relation...
ildelusion/JSBot
hangupsbot/handlers/commands.py
Python
gpl-3.0
2,643
0.001933
import re, shlex import hangups from hangupsbot.utils import text_to_segments from hangupsbot.handlers import handler, StopEventHandling from hangupsbot.commands import command default_bot_alias = '/bot' def find_bot_alias(aliases_list, text): """Return True if text starts with bot alias""" command = text...
egister(priority=5, event=hangups.ChatMessageEvent) def handle_command(bot, event): """Handle command messages""" # Test if message is not empty if not event.text: return # Get list of bot aliases aliases_li
st = bot.get_config_suboption(event.conv_id, 'commands_aliases') if not aliases_list: aliases_list = [default_bot_alias] # Test if message starts with bot alias if not find_bot_alias(aliases_list, event.text): return # Test if command handling is enabled if not bot.get_config_subop...
zstackio/zstack-woodpecker
integrationtest/vm/virt_plus/image_store/test_crt_2_vms_imgs_from_same_img.py
Python
apache-2.0
2,414
0.006628
''' Create 2 VMs with same image. Then commit 2 new images from 2 VMs. @author: Youyk ''' import time import os import apibinding.inventory as inventory import zstackwoodpecker.test_util as test_util import zstackwoodpecker.test_state as test_state import zstackwoodpecker.test_lib as test_lib import zstackwoodpecker...
zstackwoodpecker.zstack_test.zstack_test_image as test_image import zstackwoodpecker.zstack_test.zstack_test_vm as test_vm test_stub = test_lib.lib_get_specific_stub() test_obj_dict = test_state.TestStateDict() def test(): vm1 = test_stub.create_vm(vm_name = 'basic-test-vm') test_obj_dict.add_vm(vm1) #vm1...
= test_lib.lib_get_backup_storage_list_by_vm(vm1.vm) for bs in backup_storage_list: if bs.type in [inventory.IMAGE_STORE_BACKUP_STORAGE_TYPE, inventory.CEPH_BACKUP_STORAGE_TYPE]: image_creation_option.set_backup_storage_uuid_list([backup_storage_list[0].uuid]) break else: ...
obsidianforensics/unfurl
unfurl/tests/integration/test_api.py
Python
apache-2.0
729
0.004115
import unittest from unfurl.core import app as my_app class TestApi(unittest.TestCase): def setUp(self): my_app.config["testing"] = True self.client = my_app.test_client() def test_home_ok(self):
self.assertEqual(self.client.get("/", follow_redirects=True).status_code, 200) def test_api_without_url_ok
(self): self.assertEqual(self.client.get("/api/", follow_redirects=True).status_code, 200) def test_api_call_ok(self): response = self.client.get("/https://mastodon.cloud/@TimDuran/103453805855961797", follow_redirects=True) self.assertEqual(response.status_code, 200) def tearDown(self...
jxta/cc
vendor/Twisted-10.0.0/twisted/web/_auth/digest.py
Python
apache-2.0
1,700
0.001765
# -*- test-case-name: twisted.web.test.test_httpauth -*- # Copyright (c) 2009 Twisted Matrix Laboratories. # See LICENSE for details. """ Implementation of RFC2617: HTTP Digest Authentication @see: U{http://www.faqs.org/rfcs/rfc2617.html} """ from zope.interface import implements from twisted.cred import credentials...
ory class DigestCredentialFactory(object): """ Wrapper for L{digest.DigestCredentialFactory} that implements the L{ICredentialFactory} interface. """ implements(ICredentialFactory) scheme = 'digest' def __init__(self, algorithm, authenticationRealm): """ Create the digest ...
""" self.digest = credentials.DigestCredentialFactory(algorithm, authenticationRealm) def getChallenge(self, request): """ Generate the challenge for use in the WWW-Authenticate header @param request: The L{IRequest} to wit...
ScOrPiOn9/FIT
ISJ/Projekt - automatické stahování titulků k filmům/Aplikace.py
Python
mit
17,098
0.017838
import xmlrpc.client import sys, re, base64, gzip, os , io # Autor Jan Hrivnak # ISJ projekt # Soubor: Aplikace.py # spoustet s : export LC_ALL=cs_CZ.UTF-8; class Aplikace: def __init__(self): self.IMDBid=0 #IMDB id filmu self.subID=0 #ID zadanych titulku self.nazevFilmu="" self.aut...
################## #
POROVNEJ ############################################################################################################################## def porovnej(self): czech=self.nacti(self.vybraneCZ[0]['SubtitleName'], "cze") posledniCZtit=czech[-1][0]['konec'] for titulek in self.vsechnyEN: ...
ewanbarr/reynard
reynard/__init__.py
Python
mit
31
0
impo
rt mo
nitors import servers
freedesktop-unofficial-mirror/gstreamer__cerbero
test/test_packages_common.py
Python
lgpl-2.1
3,804
0.000263
# cerbero - a multi-platform build system for Open Source software # Copyright (C) 2012 Andoni Morales Alastruey <ylatuya@gmail.com> # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Library General Public # License as published by the Free Software Foundation; eit...
= "GStreamer Project" org = 'net.gstreamer' app_recipe = 'recipe3' deps = ['gstreamer-test1'] icon = "share/images/gstreamer.png" embed_deps = True class DummyConfig(object):
pass def create_store(config): cookbook = create_cookbook(config) store = PackagesStore(config, False) for klass in [Package1, Package2, Package3, Package4, App]: package = klass(config, store, cookbook) package.__file__ = 'test/test_packages_common.py' store.add_package(package)...
emsrc/daeso-dutch
lib/daeso_nl/string/ascii.py
Python
gpl-3.0
3,263
0.006384
# -*- coding: utf-8 -*- """ encode a unicode string as an ascii byte string with smart replacement Support for encoding in ascii where iso-88591-1 characters (i.e. those code points which can be encoded in iso-8859-1 aka latin-1) beyond ascii chars (i.e. those code points which can be encoded in ascii) are replaced w...
Y 222 Þ P 223 ß B 224 à a 225 á a 226 â a 227 ã a 228 ä a 229 å a 230 æ a 231 ç c 232 è e 233 é e 234 ê e 235 ë e 236 ì i 237 í i 238 î i 239 ï i 240 ð o 241 ñ n 242 ò o 243 ó o 244 ô o 245 õ o 246 ö o 247 ÷ 248 ø o 249 ù u 250 ú u 251 û u 252 ü u 253 ý y 254 þ p 255 ÿ y """ # the unicode char that will be subsituted...
encoded in iso-8859-1 # to unicode points which can be encoded in ascii translation = {} for l in _iso_to_ascii_map.split("\n"): try: n, iso_char, ascii_char = l.strip().split() except ValueError: continue # this file is utf-8 encoded, so we hav...
onepercentclub/onepercentclub-site
apps/cowry/factory.py
Python
bsd-3-clause
3,526
0.002836
import sys from apps.cowry.exceptions import PaymentMethodNotFound from django.utils.importlib import import_module def _load_from_module(path): package, attr = path.rsplit('.', 1) module = import_module(package) return getattr(module, attr) # TODO read django settings to find out what adapters to load. ...
ount, currency=currency, country=country, recurring=recurring, pm_ids=pm_ids): payment_method_ids.append(pm['id']) return payment_method_ids def get_payment_submethods(payment_method_id): adapter = _adapter_for_payment_method(payment_method_id) for payment_methods in adapter.get_payment_met
hod_config(): for pmi in payment_methods.keys(): config = payment_methods[pmi] return config.get('submethods')
ctrlaltdel/neutrinator
vendor/keystoneauth1/loading/adapter.py
Python
gpl-3.0
14,041
0
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under t...
new options. This should be a dict from the name of the new option to a list of oslo.DeprecatedOpts that correspond to the new option. (optional) For example, to support the ``
api_endpoint`` option pointing to the new ``endpoint_override`` option name:: old_opt = oslo_cfg.DeprecatedOpt('api_endpoint', 'old_group') deprecated_opts={'endpoint_override': [old_opt]} :returns: A list of oslo_config options. """ cfg = _utils....
riking/youtube-dl
test/test_youtube_signature.py
Python
unlicense
4,167
0.00504
#!/usr/bin/env python from __future__ import unicode_literals # Allow direct execution import os import sys import unittest sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) import io import re import string from youtube_dl.extractor import YoutubeIE from youtube_dl.utils import compa...
de) src_sig = ( compat_str(string.printable[:sig_input]) if isinstance(sig_input, int) else sig_input) got_sig = func(src_sig) self.assertEqual(got_sig, expected_sig) test_func.__name__ =
str('test_signature_' + stype + '_' + test_id) setattr(TestSignature, test_func.__name__, test_func) for test_spec in _TESTS: make_tfunc(*test_spec) if __name__ == '__main__': unittest.main()
SilverWingedSeraph/corewar32
toroid/toroid/warrior.py
Python
apache-2.0
188
0
c
lass Warrior(object): def __init__(self, name, author, source, score=0): self.name = name self.author = author self.source = source self.score
= score
jobovy/flexgp
flexgp/trainingSet.py
Python
bsd-3-clause
5,727
0.015191
############################################################################### # trainingSet: training-set class for training a GP # # main routine: __init__ # # example usage: # # trainingSetObject= trainingSet(listx=,listy=,noise=) # # where listx is a list of abcissae, listy is the corresponding set or...
],numpy.ndarray): s
elf.noiseCovar= kwargs['noiseCovar'] self.uniformNoise= True else: try: kwargs['noiseCovar'][0] except TypeError: try: tmpnoise= float(kwargs['noiseCovar']) except ValueError: ...
mlecours/fake-switches
tests/cisco/test_cisco_auto_enabled_switch.py
Python
apache-2.0
1,464
0.002049
import unittest from flexmock import flexmock_teardown from tests.util.global_reactor import cisco_switch_ip, \ cisco_auto_enabled_switch_ssh_port, cisco_auto_enabled_switch_telnet_port from tests.util.protocol_util import SshTester, TelnetTester, with_protocol class TestCiscoAutoEnabledSwitchProtocol(unittest.T...
'root') class Test
CiscoSwitchProtocolTelnet(TestCiscoAutoEnabledSwitchProtocol): __test__ = True def create_client(self): return TelnetTester("telnet", cisco_switch_ip, cisco_auto_enabled_switch_telnet_port, 'root', 'root')
Cloudzero/cloudzero-reactor-aws
reactor/common/plugin_loader.py
Python
bsd-3-clause
2,965
0.005059
# -*- coding: utf-8 -*- # Copyright (c) 2016-present, CloudZero, Inc. All rights reserved. # Licensed under the BSD-style license. See LICENSE file in the project root for full license information. """ Module that provides the core functionality used by various plugins. """ import re import importlib import os.path a...
y resource_type. """ plugin_paths = glob.glob(path.dirname(loader_module.__file__) + "/**/*.py") function_list = [ (path.dirname(f).split('/')[-1], path.basename(f)[:-3].replace('_', '-')) for f in plugin_paths if path.isfile(
f) and not f.endswith('__init__.py') ] return function_list def find_plugin(import_template, *args): """ Args: import_template (str): A string template used to build an import expression, for example 'reactor.plugins.{}.{}' *args (iterable(str): The keys...
optima-ict/odoo
addons/professional_templates/controllers/__init__.py
Python
agpl-3.0
58
0.017241
# -*- coding: utf-8 -*- impo
rt controllers #imp
ort models
jason-weirather/AlignQC
scripts/alignqc_annotation_to_bed_depth.py
Python
apache-2.0
2,431
0.032086
#!/usr/bin/env python import sys, argparse, gzip from Bio.Format.GPD import GPD from Bio.Range import ranges_to_coverage def main(): parser = argparse.ArgumentParser(description="",formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('input',help="Use - for STDIN") parser.add_argument('gen...
f args.input[-3:]=='.gz': inf = gzip.open(args.input) else: inf = open(args.input) genes = {} sys.stderr.write("Reading annotation file\n") for line in inf: f = line.rstrip().split("\t") gene = f[2] tx = f[3] type = f[4] if a
rgs.full and type != 'full': continue if gene not in genes: genes[gene] = {} genes[gene]['transcripts'] = {} genes[gene]['cnt'] = 0 if tx not in genes[gene]['transcripts']: genes[gene]['transcripts'][tx] = 0 genes[gene]['cnt'] += 1 genes[gene]['transcripts'][tx] += 1 inf.close(...
geekone/mitiyu
mitiyu/wsgi.py
Python
apache-2.0
387
0.002584
""" WSGI c
onfig for mitiyu 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.6/howto/deployment/wsgi/ """ import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mitiyu.settings") from django.core.wsgi import g...
sgi_application application = get_wsgi_application()
cocosli/antlr4
runtime/Python3/src/antlr4/PredictionContext.py
Python
bsd-3-clause
24,709
0.008256
# # [The "BSD license"] # Copyright (c) 2012 Terence Parr # Copyright (c) 2012 Sam Harwell # Copyright (c) 2014 Eric Vergnaud # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redis...
the above copyright # notice, this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # 3. The ...
IS'' AND ANY EXPRESS OR # IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES # OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. # IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT...
zhyq0826/test-lab
tornado-lab/main4.py
Python
mit
2,107
0.009732
#-*- coding:utf-8 -*- from tornado.httpclient import HTTPClient, AsyncHTTPClient import tornado.ioloop from tornado.concurrent import Future from tornado import gen import time from concurrent.fut
ures import ThreadPoolExecutor executor = ThreadPoolExecutor(max_workers=4) #同步方法调用 def synchronous_fetch(url, callback): http_client = HTTPClient() def handle_response(response): callback(response) http_client.fetch(url, callback=handle_response) #异步调用, 当完成时 调用回调 def asynchronous_fetch(url, call...
ent() def handle_response(response): callback(response) http_client.fetch(url, callback=handle_response) #把异步结果封装成feture def asyn_fetch_feture(url): http_client = AsyncHTTPClient() my_future = Future() fetch_future = http_client.fetch(url) def handler_feture(feture): my_future.s...
GregorioDiStefano/integration
tests/MenderAPI/inventory.py
Python
apache-2.0
3,224
0.003102
#!/usr/bin/python # Copyright 2017 Northern.tech AS # # 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 a...
en() devurl = "%s%s/%s" % (self.get_inv_base_path(), "device", device_id) ret = requests.get(devurl, headers=self.auth.get_auth_token(), verify=False)
return ret def get_groups(self): ret = requests.get(self.get_inv_base_path() + "groups", headers=self.auth.get_auth_token(), verify=False) assert ret.status_code == requests.status_codes.codes.ok return ret.json() def get_devices_in_group(self, group): req = "groups/%s/...
erjohnso/ansible
lib/ansible/playbook/play_context.py
Python
gpl-3.0
27,712
0.00232
# -*- coding: utf-8 -*- # (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License,...
FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # Make coding more python3-ish from __future__ import (absolute_import, division, print_function) _...
e import constants as C from ansible.errors import AnsibleError from ansible.module_utils.six import iteritems from ansible.module_utils.six.moves import shlex_quote from ansible.module_utils._text import to_bytes from ansible.module_utils.parsing.convert_bool import boolean from ansible.playbook.attribute import Field...
skynetera/skynet
skynet-agent/plugins/linux/iostats.py
Python
apache-2.0
1,028
0.001953
#!/usr/bin/env python # coding: utf-8 __author__ = 'whoami' """ @version: 1.0 @author: whoami @license: Apache Licence 2.0 @contact: skutil@gmail.com @site: http://www.itweet.cn @software: PyCharm Community Edition @file: disk.py @time: 2015-11-28 下午1:53 """ import time import psutil def monitor(frist_invoke=2): ...
disk. """ sdiskio = psutil.disk_io_counters() # sleep some time value_dic = { 'iostats': { 'io.disks_read': sdiskio.read_bytes/(1024*1024), 'io.disks_write': sdiskio.write_bytes/(1024*1024), 'io.disks_read_count': sdiskio.read_count/(1024 * 1024), ...
write_time': sdiskio.write_time/1000, 'io.disks_busy_time': sdiskio.write_time/1000, } } return value_dic if __name__ == '__main__': print monitor()
opcode81/ProbCog
src/main/python/configMLN.py
Python
gpl-3.0
3,791
0.011606
# configuration script for the MLN query & parameter learning tools # # If you want to use PyMLNs with the Alchemy System (http://alchemy.cs.washington.edu), # set the path where it is installed on your system in the alchemy_versions dictionary below. # # Depending on your naming convention for mln and database f...
"-numChains" } default_infer_usage = new_usage # the usage that is to apply when the "usage" of an Alchemy installation is not set explicitl
y in the dictionary below # installed Alchemy versions: # - Keys are names of the installations as they should appear in the two tools. # - Values should be either paths to the Alchemy root or "bin" directory or # a dictionary with at least the key "path" set to the Alchemy root or bin directory. # The dictionary ...
CaterHatterPillar/wolfy
lw.py
Python
mit
2,977
0.00739
#!/bin/python # lw.py # Create a Lone Wolf character. # System errors: # 1 - Erronous arguments given. # 2 - Command line syntax error. # 3 - Specified file already exists. import os import sys import argparse import wolfy_util import wolfy_config argparser = argparse.ArgumentParser(prog='lw', description= ...
fy_util.castD10() + 20) print('Character ENDURANCE not given. ENDURANCE is randomized to: ' + endurance) file.write('# ' + filename + '\n' '# wolfy character file for Joe Dever\'s Lone Wolf series.\n' '# See https://github.com/CaterHatterPillar/wolfy\n' '# v. ' + wolfy_u...
ctiveChar(name) print('Set ' + name + ' as the active Lone Wolf character in the wolfy' ' repository configuration.') file.close()
iafan/zing
pootle/apps/pootle_store/unit/filters.py
Python
gpl-3.0
5,933
0.000169
# -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # Copyright (C) Zing contributors. # # This file is a part of the Zing project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. from django...
ct=False): result = self.qs.none() words = self.get_
words(text, exact) for k in self.get_search_fields(sfields): result = result | self.search_field(k, words) return result def search_field(self, k, words): subresult = self.qs for word in words: subresult = subresult.filter( **{("%s__icontains...
AliZafar120/NetworkStimulatorSPl3
rapidnet_visualizer/runner.py
Python
gpl-2.0
884
0.03733
#!/usr/bin/python import os, sys log_file = 'py_ns3_visualizer.log' # Remove log file if os.path.exists (log_file): os.system ('rm %s' % log_file) if len (sys.argv) == 2 and sys.argv[1] == 'help': #not in [1, 2, 3]: print 'Usage: runner [<events.log>] [<interval>]' sys.exit (0) if len (sys.argv) >= 2: event...
ents_log): print 'File does not exist:', events_log sys.exit (0) if len (sys.argv) >= 3: interval = sys.argv[2] else: interval = '500' sys.argv = [sys.argv[0], events_log, 'styles/node-styles010', 'styles/link-styles010', interval] sys.path.append ('src') from ns3.rapidnet.rapidnet_visualizer import ma
in main ()
messiasthi/Dduplicated
dduplicated/scans.py
Python
gpl-2.0
1,093
0.028362
from os import path as opath, walk from dduplicated import hashs ignored = ['..'] files = {} visited = [] def add_file(path): global files if not opath.islink(path): file_hash = hashs.get_hash(path) if file_hash in files: if path not in files[file_hash]: files[file_hash].append(path) else: files.u...
ths) in files.items(): if len(paths) > 1: paths.sort() duplicates[file_hash] = paths
return duplicates
yuanzhao/gpdb
gpMgmt/bin/gppylib/gparray.py
Python
apache-2.0
94,119
0.009467
#!/usr/bin/env python # # Copyright (c) Greenplum Inc 2008. All Rights Reserved. # """ gparray.py: Contains three classes representing configuration information of a Greenplum array: GpArray - The primary interface - collection of all GpDB within an array GpDB - represents configuration infor...
n other than this will cause the # FTS Prober to bring down the master postmaster until the # con
figuration is corrected. Here, primary and mirror refer # to the segments current role, not the preferred_role. # # The format of the tuples are: # (<primary status>, <prmary mode>, <mirror status>, <mirror_mode>) VALID_SEGMENT_STATES = [ (STATUS_UP, MODE_CHANGELOGGING, STATUS_DOWN, MODE_SYNCHRONIZED), (STA...
roubert/python-phonenumbers
python/phonenumbers/data/region_IO.py
Python
apache-2.0
1,488
0.009409
"""Auto-generated file, do not edit by hand. IO metadata""" from ..phonemetadata import NumberFormat, PhoneNumberDesc, PhoneMetadata PHONE_METADATA_IO = PhoneMetadata(id='IO', country_code=246, international_prefi
x='00', general_desc=PhoneNumberDesc(national_number_pattern='3\\d{6}', possible_number_pattern='\\d{7}'), fixed_line=PhoneNumberDesc(national_number_pattern='37\\d{5}', possible_number_pattern='\\d{7}', example_number='3709100'), mobile=PhoneNumberDesc(national_number_pattern='38\\d{5}', possible_number_pa...
_number_pattern='NA', possible_number_pattern='NA'), shared_cost=PhoneNumberDesc(national_number_pattern='NA', possible_number_pattern='NA'), personal_number=PhoneNumberDesc(national_number_pattern='NA', possible_number_pattern='NA'), voip=PhoneNumberDesc(national_number_pattern='NA', possible_number_patter...
Haddy1/ClusterMDS
lib/libSMACOF_theano.py
Python
gpl-3.0
10,508
0.0059
#!/usr/bin/python from __future__ import print_function import numpy as np from sklearn.decomposition import PCA import theano import theano.tensor as T class SMACOF(): """ Multidimensional Scaling Multidimensional Scaling using the "Scaling by MAjorizing a COmplicated Function" (SMACOF) alghorithm ...
nsional distances Parameters -------- distX: array-like
distance matrix of low dimensional X for current iteration step delta: array-like distance matrix of high dimensional input data Returns ------ s: float stress between high and low dimensional data """ s = T.sum(T.square(distX - delta)) ...
CSF-JH/crossbarexamples
rest/needs_cleanup/python/example/auth/__init__.py
Python
apache-2.0
2,784
0.023707
############################################################################### ## ## Copyright 2012 Tavendo 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...
print "Challenge:", data if data['authkey'] == APP
KEY: sig = authSignature(request.data, APPSECRET) print "Signature:", sig return sig except Expection, e: print e return "" if __name__ == "__main__": app.run(host = "0.0.0.0", port = 8000, debug = True)
DailyActie/Surrogate-Model
01-codes/tensorflow-master/tensorflow/models/rnn/ptb/ptb_word_lm.py
Python
mit
10,596
0.000566
# Copyright 2015 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 a...
tmax_w = tf.get_variable("softmax_w", [size, vocab_size])
softmax_b = tf.get_variable("softmax_b", [vocab_size]) logits = tf.matmul(output, softmax_w) + softmax_b loss = tf.nn.seq2seq.sequence_loss_by_example( [logits], [tf.reshape(self._targets, [-1])], [tf.ones([batch_size * num_steps])]) self._cost = cost =...
AlanZatarain/opencamlib
scripts/issues/issue20data.py
Python
gpl-3.0
4,416
0.009284
import ocl trilist = [] trilist.append(ocl.Triangle(ocl.Point(2.91337, 1, 3.93857), ocl.Point(2.89783, -7.09741e-016, 4.07462), ocl.Point(4, -9.79685e-016, 3))) trilist.append(ocl.Triangle(ocl.Point(2.91337, 1, 3.93857), ocl.Point(4,...
.Point(0, 0.335345, 4.98874))) trilist.append(ocl.Triangle(ocl.Point(0, 0.5, 2.5), ocl.Point(0, 0, 0), ocl.
Point(3.06152e-016, -7.4983e-032, 5))) trilist.append(ocl.Triangle(ocl.Point(0, 0.5, 2.5), ocl.Point(0, 1, 0), ocl.Point(0, 0, 0))) trilist.append(ocl.Triangle(ocl.Point(4, 1, 0), ocl.Point(0, 0, 0), ocl.Point(0, 1, 0))) trilist.append(ocl.Triangle(ocl.Point(4, 1, 0), ocl.Point(4, 0, 0), ocl.Point(0, 0, 0)))
tic-ull/portal-del-investigador
core/tests/test_user.py
Python
agpl-3.0
1,261
0
# -*- encoding: UTF-8 -*- # # Copyright 2014-2015 # # STIC-Investigación - Universidad de La Laguna (ULL) <gesinv@ull.edu.es> # # This file is part of Portal del Investigador. # # Portal del Investigador is free software: you can redistribute it and/or # modify it under the terms of the GNU Affero Gen...
ed a copy of the GNU Affero General Public License # along with Portal del Investigador. If not, see # <http://www.gnu.org/licenses/>. # from core.models import UserProfile from django.test import TestCase from factories impor
t UserFactory class UserTests(TestCase): def test_user_profile_created_on_user_creation(self): user = UserFactory.create() profile = UserProfile.objects.filter(user__username=user.username) self.assertEqual(len(profile), 1)
tylertian/Openstack
openstack F/glance/glance/common/animation.py
Python
apache-2.0
6,628
0.000754
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2012 OpenStack LLC. # 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/...
percent += ' ' + self._get_speed() + 'ETA ' + self._calc_eta() sys.stdout.write(percent) sys.stdout.write("\b" * len(percent)) sys.stdout.flush() def _get_speed(self): speed, unit = self._calc_speed() if speed > 0.0: if speed >= 99.95: ...
rate = "%4.2f" % speed return " " + rate + unit + ", " else: return " ?B/s " def _calc_eta(self): if self.stalled or self.current_size < self.size * 0.01: return "ETA ??h ??m ??s" if self.CALC_ETA_WITH_AVE_RATE: eta = ((self.size - sel...
OPENi-ict/ntua_demo
openiPrototype/openiPrototype/APIS/Products_and_Services/Card/models.py
Python
apache-2.0
585
0
__author__ = 'mpetyx' from django.db import models from OPENiapp.APIS.Context.models import OpeniContextAwareModel class OpeniCard(Open
iContextAwareModel): # id is missing because it is the default url = models.TextField() object_type = models.TextField() service = models.TextField()
From = models.TextField() billing_address = models.TextField() number = models.TextField() card_owner_date_of_birth = models.TextField() card_type = models.TextField() expiration_date = models.TextField() card_verification_number = models.TextField()
kikocorreoso/brython
www/src/Lib/test/test_fork1.py
Python
bsd-3-clause
3,761
0.002659
"""This test checks for correct fork() behavior. """ import _imp as imp import os import signal import sys import threading import time import unittest from test.fork_wait import ForkWait from test.support import reap_children, get_attribute, verbose # Skip test if fork does not exist. get_attribute(os, 'fork') cl...
release = 0 in_child = False try: try: for i in range(level): imp.acquire_
lock() release += 1 pid = os.fork() in_child = not pid finally: for i in range(release): imp.release_lock() except RuntimeError: if in_child: if ver...
twstrike/tor_guardsim
lib/main.py
Python
cc0-1.0
1,345
0.005948
#!/usr/bin/python from __future__ import pri
nt_function from py3hax import * import tornet import simtime import client def trivialSimulation(): net = tornet.Network(100) # Decorate the network. # Uncomment one or two of these at a time, kthx! #net = tornet.FascistNetwork(net) #net = tornet.FlakyNetwork(net) #net = tornet.EvilFilterin...
#net = tornet.SniperNetwork(net) c = client.Client(net, client.ClientParams()) ok = 0 bad = 0 for period in xrange(30): # one hour each for subperiod in xrange(30): # two minutes each if (subperiod % 10) == 0: # nodes left and arrived net.do_churn()...
tparks5/tor-stem
stem/manual.py
Python
lgpl-3.0
20,582
0.009523
# Copyright 2015-2017, Damian Johnson and The Tor Project # See LICENSE for licensing information """ Information available about Tor from `its manual <https://www.torproject.org/docs/tor-manual.html.en>`_. This provides three methods of getting this information... * :func:`~stem.manual.Manual.from_cache` provides ma...
old us what our torrc options do... .. literalinclude:: /_static/example/manual_config_options.py :language: python | .. image:: /_static/manual_output.png | **Module Overview:** :: is_important - In
dicates if a configuration option is of particularly common importance. download_man_page - Downloads tor's latest man page. Manual - Information about Tor available from its manual. | |- from_cache - Provides manual information cached with Stem. | |- from_man - Retrieves manual information from its man page...
drakedevel/pass
passgen/__init__.py
Python
bsd-2-clause
2,565
0.00039
#!/usr/bin/env python """Dictionary-based password generator. Usage: pass.py [options] Options: -h --help Show this help text -d --dictionary=<path> Specify a non-default dictionary -n --length=N Specify number of words to use [default: 4] -v --verbose Print entropy estimat...
__doc__) word_count = int(args['--length']) # Read and transform dictionary file if args['--dictionary']: dict_path = args['--dictionary'] else: dict_path = os.path.join(os.path.dirname(__file__), 'words.txt') dictionary = [w for w in
[l.strip() for l in open(dict_path)] if w] if args['--truncate']: dictionary = dictionary[:int(args['--truncate'])] elif not args['--dictionary']: # Default truncation for built-in dictionary dictionary = dictionary[:8192] # Basic entropy calculation if args['--uncontrolled']: ...
AlexKuhnle/ShapeWorld
models/agreement/always_true.py
Python
mit
371
0.005391
from models.TFMacros.tf_macros import * def model(model, inputs, dataset_parameters): agreement = (
Input(name='world', shape=dataset_parameters['world_shape'], tensor=inputs.get('wor
ld')) >> Constant(value=True, dtype='float') >> Binary(name='agreement', binary_transform=False, tensor=inputs.get('agreement')) ) return agreement
MalloyPower/parsing-python
front-end/testsuite-python-lib/Python-2.3/Lib/plat-mac/Carbon/QuickTime.py
Python
mit
40,695
0.000737
# Generated from 'Movies.h' def FOUR_CHAR_CODE(x): return x MovieFileType = FOUR_CHAR_CODE('MooV') MovieScrapType = FOUR_CHAR_CODE('moov') MovieResourceType = FOUR_CHAR_CODE('moov') MovieForwardPointerResourceType = FOUR_CHAR_CODE('fore') MovieBackwardPointerResourceType = FOUR_CHAR_CODE('back') MovieResourceAtomType ...
kActionStatusString = 6153 kActionSendQTEventToTrackObject = 6154 kActionAddChannelSubscription = 6155 kAction
RemoveChannelSubscription = 6156 kActionOpenCustomActionHandler = 6157 kActionDoScript = 6158 kActionDoCompressedActions = 6159 kActionSendAppMessage = 6160 kActionLoadComponent = 6161 kActionSetFocus = 6162 kActionDontPassKeyEvent = 6163 kActionSpriteTrackSetVariable = 7168 kActionSpriteTrackNewSprite = 7169 kActionSp...
ezequielpereira/Time-Line
libs64/wx/lib/agw/flatmenu.py
Python
gpl-3.0
215,487
0.007267
# --------------------------------------------------------------------------------- # # FLATMENU wxPython IMPLEMENTATION # # Andrea Gavana, @ 03 Nov 2006 # Latest Revision: 21 Sep 2010, 23.00 GMT # # TODO List # # 1. Work is still in progress, so other functionalities may be added in the future; # 2. No shadows under M...
processes the following events: ================================= ================================================== Event Name Description ================================= ================================================== ``EVT_FLAT_MENU_DISMISSED`` Used internally. ``EVT_FLAT_MENU_ITEM...
n the mouse enters a `FlatMenuItem`. ``EVT_FLAT_MENU_SELECTED`` Fires the `wx.EVT_MENU` event for `FlatMenu`. ================================= ================================================== License And Version =================== FlatMenu is distributed under the wxPython license. Latest Revision: Andre...
globality-corp/microcosm-pubsub
microcosm_pubsub/tests/sentry_fixture.py
Python
apache-2.0
4,744
0.005902
sample_event = { 'level': 'error', 'exception': { 'values': [ { 'module': None, 'type': 'TypeError', 'value': 'Testing stuff', 'mechanism': None, 'stacktrace': { 'frames': [ { 'filename': ...
ssage):', ' try:' ], 'context_line': ' succ
ess = handler(message.content)', 'post_context': [ ' return cls.from_result(message, bool(success))', ' except Exception as error:', ' return cls.from_error(message, e...
MADindustries/WhatManager2
books/utils.py
Python
mit
566
0.003534
from subprocess import call isbn_regex = '^(97(8|9)-?)?\d{9}(\d|X)$' def fix_author(author): parts = author.split(u', ') if len(parts) == 2: return parts[1] + u' ' + parts[0] return author def call_mktorrent(target, torrent_filename, announce, torrent_name=None): args = [ 'mktorren...
if torrent_name: args.extend(('-n', torrent_name)) args.append(target) if call(args) != 0: raise Exception('mktorrent returned non-ze
ro')
ProjectSWGCore/NGECore2
scripts/loot/lootPools/tatooine/re_junk_escaped_criminal.py
Python
lgpl-3.0
107
0.093458
def itemNames(): return ['id_chip','ledger','magseal_detector'
] def itemCha
nces(): return [33,33,34]
florianfesti/CocktailOverlord
cocktailoverlord/db.py
Python
gpl-3.0
14,288
0.006789
""" Copyright (C) 2017 - The CocktailOverlord Authors This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distribu...
"CREATE TABLE IF NOT EXISTS storage (location INTEGER PRIMARY KEY, ingredient INTEGER REFERENCES ingredient(id) ON DELETE SET
NULL, amount REAL NOT NULL)""") self.cur.execute("CREATE VIEW IF NOT EXISTS available_ingredients (ingredient, amount) AS SELECT ingredient, SUM(amount) FROM storage GROUP BY ingredient") self.cur.execute("""CREATE VIEW IF NOT EXISTS recipe_plus_storage (cocktail, ingredient, amount, stored, enough) AS ...
giubil/trackit
api/files/api/migrations/versions/b6533e0a4e58_make_the_aws_bucket_optional.py
Python
apache-2.0
605
0.016529
"""M
ake the AWS bucket optional. Revision ID: b6533e0a4e58 Revises: eca04db5c363 Create Date: 2017-02-06 02:16:03.
926797 """ # revision identifiers, used by Alembic. revision = 'b6533e0a4e58' down_revision = 'eca04db5c363' from alembic import op import sqlalchemy as sa def upgrade(): op.alter_column('aws_key', column_name='billing_bucket_name', existing_type=sa.String(length=63), nullable=True, ...
martinrusev/amonone
amon/apps/servers/tests/views_tests.py
Python
mit
2,693
0.012254
from django.test.client import Client from django.test import TestCase from django.urls import reverse from nose.tools import * from django.contrib.auth import get_user_model User = get_user_model() from amon.apps.servers.models import server_model class TestServerViews(TestCase): def setUp(self): User....
server_model.collection.remove() server_model.collection.insert({'name': 'test' , 'check_every': 60,'keep_data': 30, "key": "test"}) server = server_model.collection.find_one() url = reverse('edit_server', kwargs={'server_id': server['_id']}) response = self.c.get(url) asse...
updated_server = server_model.collection.find_one() self.assertRedirects(response, reverse('servers')) eq_(updated_server['name'], 'changetest') eq_(updated_server['check_every'], 300) server_model.collection.remove() def delete_server_test(se...
Acehaidrey/incubator-airflow
airflow/providers/google/marketing_platform/hooks/campaign_manager.py
Python
apache-2.0
11,618
0.001635
# # 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...
.reports() .run(profileId=profile_id, reportId=report_id, synchronous=synchronous) .execute(num_retries=self.num_retries) ) return response def update_report(self, profile_id: str, report_id: str) -> Any: """ Updates a report. :param
profile_id: The DFA user profile ID. :param report_id: The ID of the report. """ response = ( self.get_conn() .reports() .update(profileId=profile_id, reportId=report_id) .execute(num_retries=self.num_retries) ) return response ...
hasadna/OpenCommunity
src/communities/forms.py
Python
bsd-3-clause
4,808
0.002912
from communities.models import Community, SendToOption from datetime import datetime, date, time from django.utils import timezone from django.utils.translation import ugettext_lazy as _ from ocd.formfields import HTMLArea, OCSplitDateTime, OCCheckboxSelectMultiple from users.models import OCUser, Membership import flo...
ants: board
_in.append(b.id) self.fields['board'].choices = board_choices self.initial['board'] = board_in self.fields['upcoming_meeting_participants'].queryset = self.instance.get_members() self.fields['upcoming_meeting_participants'].label = "" class CommunitySearchForm(ModelSearchForm)...
grammarware/slps
shared/python/MBGF.py
Python
bsd-3-clause
5,360
0.031951
#!/Library/Frameworks/Python.framework/Versions/3.1/bin/python3 import os, sys sys.path.append(os.getcwd().split('slps')[0]+'slps/shared/python') import slpsns, BGF3 import xml.etree.ElementTree as ET cx = {} class TopModel: def getData(self, id): if id in self.data.keys(): return self.data[id] else: retur...
[]] for p in ss.findall(slpsns.bgf_('pro
duction')): xp = BGF3.Production() xp.parse(p) self.data[s][0].append(xp) self.data[s][1] = ss.findall('in/*') # # <sources> # <src name="dcg">snapshot/dcg.bgf</src> # <src name="sdf">snapshot/sdf.bgf</src> # <src name="rsc">snapshot/rascal.bgf</src> # </sources> class Sources (SrcSimpleModel): ...
manuelep/openshift_v3_test
wsgi/web2py/gluon/xmlrpc.py
Python
mit
748
0
#!/usr/bin/env python # -*- co
ding: utf-8 -*- """ | This file is part of the web2py Web Framework | Copyrighted by Massimo Di Pierro <mdipierro@cs.depaul.edu> | License: LGPLv3 (http://www.
gnu.org/licenses/lgpl.html) """ from SimpleXMLRPCServer import SimpleXMLRPCDispatcher def handler(request, response, methods): response.session_id = None # no sessions for xmlrpc dispatcher = SimpleXMLRPCDispatcher(allow_none=True, encoding=None) for method in methods: dispatcher.register_functi...
manassolanki/erpnext
erpnext/setup/doctype/email_digest/email_digest.py
Python
gpl-3.0
18,380
0.029489
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import frappe from frappe import _ from frappe.utils import fmt_money, formatdate, format_time, now_datetime, \ get_url_to_form, get_url_to_list, flt f...
px; font-size: 16px;' context.line_item = 'padding: 5px 0px; margin: 0; border-bottom: 1px solid #d1d8dd;' context.link_css = 'color: {text_color}; text-decoration: none;'.format(text_color = context.text_color) def get_notifications(self): """Get notifications for user""" notifications = frappe.desk.notifi...
tions() notifications = sorted(notifications.get("open_count_doctype", {}).items(), lambda a, b: 1 if a[1] < b[1] else -1) notifications = [{"key": n[0], "value": n[1], "link": get_url_to_list(n[0])} for n in notifications if n[1]] return notifications def get_calendar_events(self): """Get calendar e...
vincentschen/tab_clustering
server/server.py
Python
mit
645
0.012403
from flask import Flask, request im
port cluster import json app = Flask(__name__) @app.route('/cluster/', methods=['GET', 'POST']) def similarities(): if request.method == 'POST': data = json.loads(request.data) docs = data['docs'] # docs = request.form.getlist('docs') print "docs: ", len(docs) pri...
ut_ = data['input'] # print "input:", input_ sims = cluster.compute_similarity(docs, input_) response = json.dumps(sims) print response return response
biosustain/memote
src/memote/support/consistency_helpers.py
Python
apache-2.0
11,239
0.000356
# -*- coding: utf-8 -*- # Copyright 2017 Novo Nordisk Foundation Center for Biosustainability, # Technical University of Denmark. # # 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...
t find_biomass_reaction __all__ = ("stoichiometry_matrix", "nullspace") LOGGER = logging.getLogger(__name__) def add_reaction_constraints(model, reactions, Constraint): """ Add the stoichiometric coefficients as constraints. Parameters ---------- model : optlang.Model The transposed st...
int : optlang.Constraint The constraint class for the specific interface. """ constraints = [] for rxn in reactions: expression = add( [c * model.variables[m.id] for m, c in rxn.metabolites.items()] ) constraints.append(Constraint(expression, lb=0, ub=0, name=rxn...
mas178/Fragments
bot/twitter2.py
Python
mit
934
0.004283
from __future__ import print_function import random import boto3 from requests_oauthlib import OAuth1Session def lambda_handler(event, context): bucket = boto3.resource('s3').Bucket('gengo-hacker') # Quotes quotes = bucket.Object('quotes.txt').get()['Body'].read().decode('utf-8') quotes = [q.split("\...
or t in token.split("\n")]) tw = OAuth1Session(token['consumer_key'], token['consumer_secret'], token['access_token_key'], token['access_token_secret']) return tw.post('https://api.twitter.com/1.1/statuses/update.json', params
={"status": random.choice(quotes)})
zmsp/AIY-data-center-assistant
src/aiy/cloudspeech.py
Python
apache-2.0
4,262
0.001408
# Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
izer(object): """A speech recognizer backed by the Google CloudSpeech APIs. """ def __init__(self, credentials_file): self._request = aiy._apis._speech.CloudSpeechRequest(credentials_file) self._recorder = aiy.audio.get_recorder() self._hotwords = [] def recognize(self): ...
cognizes the user's speech and transcript it into text. This function listens to the user's speech via the VoiceHat speaker. Then it contacts Google CloudSpeech APIs and returns a textual transcript if possible. If hotword list is populated this method will only respond if hotword is said. ...
salopensource/sal
sal/tests/test_decorators.py
Python
apache-2.0
6,760
0.001183
"""General functional tests for the server app.""" from django.http.response import Http404, HttpResponseServerError from django.contrib.auth.models import User from django.core.exceptions import PermissionDenied from django.test import TestCase, RequestFactory from django.urls import reverse from sal.decorators imp...
# Elevate user to RW status. request = self.factory.get('/test/') user_profile = self.normal_user.userprofile user_profile.level = 'RW' user_profile.save() request.user = self.normal_user response = test_view(request) self.assertEqual(response, SUCCESS) #...
request = self.factory.get('/test/') user_profile = self.staff_user.userprofile user_profile.level = 'GA' user_profile.save() request.user = self.staff_user response = test_view(request) self.assertEqual(response, SUCCESS) def test_staff_required(self): ...
relrod/pib
bot.py
Python
bsd-3-clause
1,205
0.033195
#!/usr/bin/env python from django.core.management import setup_environ import settings setup_environ(settings) import socket from trivia.models import * irc = socket.socket(socket.AF_INET, socket.SOCK_STREAM) irc.connect((settings.IRC_SERVER, settings.IRC_PORT)) def send(msg): irc.send(msg + "\r\n") print "{SE...
T} " + msg return def msg(user, msg): send("PRIVMSG " + user + " :" + msg) return def processline(line): parts = line.split(' :',1) args = parts[0].split(' ') if (len(parts) > 1): args.append(parts[1]) if args[0] == "PING": send("PONG :" + args[1]) return try:
if args[3] == "!questions": questions = str(Question.objects.all()) msg(args[2], questions) return except IndexError: return # When we're done, remember to return. return send("USER " + (settings.IRC_NICKNAME + " ")*4) send("NICK " + settings.IRC_NICKNAME) for chann...
regular/pyglet-avbin-optimizations
pyglet/input/darwin_hid.py
Python
bsd-3-clause
17,379
0.005179
#!/usr/bin/env python ''' ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import ctypes import pyglet from pyglet.libs.darwin import carbon, _oscheck, create_cfstring from pyglet.libs.darwin.constants import * from base import Device, Control, AbsoluteAxis, RelativeAxis, Button from base import Joyst...
('getAsyncEventSource', ctypes.c_void_p), ('createAsyncPort', ctypes.c_void_p), ('getAsyncPort', ctypes.c_void_p), ('create', ctypes.CFUNCTYPE(IOReturn, Self, ctypes.c_uint32, ctypes.c_uint32)), ('dispose', ctypes.CFUNCTYPE(IOReturn, Self)), ('addElem...
art', ctypes.CFUNCTYPE(IOReturn, Self)), ('stop', ctypes.CFUNCTYPE(IOReturn, Self)), ('getNextEvent', ctypes.CFUNCTYPE(IOReturn, Self, ctypes.POINTER(IOHIDEventStruct), AbsoluteTime, ctypes.c_uint32)), ('setEventCallout', ctypes.CFUNCTYPE(IOReturn,...
lmazuel/azure-sdk-for-python
azure-mgmt-network/azure/mgmt/network/v2017_08_01/models/express_route_circuits_routes_table_list_result.py
Python
mit
1,282
0.00078
# 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 ...
'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, } def __init__(
self, **kwargs): super(ExpressRouteCircuitsRoutesTableListResult, self).__init__(**kwargs) self.value = kwargs.get('value', None) self.next_link = kwargs.get('next_link', None)
CroissanceCommune/autonomie
autonomie/tests/utils/test_files.py
Python
gpl-3.0
850
0.002364
# -*- coding: utf-8 -*- # * Authors: # * TJEBBES Gaston <g.t@majerti.fr> # * Arezki Feth <f.a@majerti.fr>; # * Miotte Julien <j.m@majerti.fr>; from autonomie.utils.files import ( encode_path, decode_path, issubdir, filesizeformat, ) def test_encode_decode(): st = u"$deù % ù$ùdeù ...
ssubdir(): assert(issubdir("/root/foo", "/root/foo/bar")) assert(not issubdir("/root/foo", "/root/bar")) assert(not issubdir("/root/foo", "/root/../../foo/bar")) def test_filesizeformat(): a
ssert(filesizeformat(1024, 0) == "1ko") assert(filesizeformat(1024, 1) == "1.0ko") assert(filesizeformat(1024*1024, 0) == "1Mo") assert(filesizeformat(1024*1024, 1) == "1.0Mo")
ramcn/demo3
venv/lib/python3.4/site-packages/rest_framework/authtoken/south_migrations/0001_initial.py
Python
mit
3,298
0.006064
# -*- coding: utf-8 -*- from south.db import db from south.v2 import SchemaMigration try: from django.contrib.auth import get_user_model except ImportError: # django < 1.5 from django.contrib.auth.models import User else: User = get_user_model() class Migration(SchemaMigration): def forwards(self, ...
'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('dj
ango.db.models.fields.CharField', [], {'max_length': '100'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) ...
LeonNie52/dk-plus
formation.py
Python
gpl-3.0
20,767
0.002841
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2017/3/5 # @Author : Leon.Nie # @Site : # @File : formation.py """ Drones proceed in formation base on the algorithm Artificial Potential Field """ from geo_tools import * import numpy as np import logging import logging.config logging.config.fileConfi...
ocity[i] + velocity[i] for i in range(len(velocity))] cenVel = [x
/ float(len(teammate) + 1) for x in velocity] return cenVel def DampForce(self): dampForce = self.dampForce_K * np.array(self.network.vehicle_params.velocity) return dampForce def LeadForce(self, teammate, single): if len(teammate) == 0 or single: cenPos_NED = get...
sparkslabs/guild
examples/blog/accounts-stm-3.py
Python
apache-2.0
3,204
0.000624
#!/usr/bin/python import random import time from guild.actor import * from guild.stm import Store, ConcurrentUpdate, BusyRetry, retry import logging logger = logging.getLogger('__main__.' + "MischiefMaker") ch = logging.StreamHandler() ch.setLevel(logging.D
EBUG) formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') ch.setFormatter(formatter) logger.addHandler(ch) class InsufficientFunds(ActorEx
ception): pass class Account(object): def __init__(self, balance=10): self.account_info = Store() curr_balance = self.account_info.checkout("balance") curr_balance.set(balance) curr_balance.commit() @retry # Retries until transaction succeeds def dep...
DamCB/tyssue
tyssue/core/history.py
Python
gpl-3.0
16,124
0.001985
import os import warnings import traceback import logging import pandas as pd import numpy as np from pathlib import Path from collections import defaultdict from .sheet import Sheet from .objects import Epithelium logger = logging.getLogger(name=__name__) def _filter_columns(cols_hist, cols_in, element): if n...
y = None self.datasets = {} self.columns = {} vcols = sheet.coords + extra_cols["vert"] vcols = list(set(vcols)) self.vcols = _filter_columns(vcols, sheet.vert_df.columns, "vertex") _vert_h = sheet.vert_df[self.vcols].reset_index(drop=False) if not "time" in self...
_vert_h self.columns["vert"] = self.vcols fcols = extra_cols["face"] self.fcols = _filter_columns(fcols, sheet.face_df.columns, "face") _face_h = sheet.face_df[self.fcols].reset_index(drop=False) if not "time" in self.fcols: _face_h["time"] = 0 self.datasets...
mcgettin/ditOldProgramming
yr2/sem2/Labs/2_animal/dogObj.py
Python
mit
66
0.060606
class
Doge(object): def __init__(
self,)
rubydhash/webradius
webradius-project/webradius/util.py
Python
lgpl-2.1
783
0.007663
# -*- coding: utf-8 -*- from django.core import except
ions from django.conf import settings from django.db.models import fields class BigAutoField(fields.AutoField): def db_type(self, connection=None): for item in settings.DATABASES: if settings.DATABASES[item]['ENGINE'] == 'django.db.backends.postgresql_psycopg2': return "...
else: raise NotImplemented def get_internal_type(self): return "BigAutoField" def to_python(self, value): if value is None: return value try: return long(value) except (TypeError, ValueError): raise exceptions.Validati...
kalgynirae/subjunctive
setup.py
Python
mit
290
0
from setuptools
import find_packages, setup setup( name='subjunctive', version='0.1', install_requires=[ 'PySDL2 ==0.8.0', ], packages=find_packages(), scripts=[ 'games/think-green/think-green.py', 'games/floorpaint/floorpaint.p
y', ], )
ktan2020/legacy-automation
win/Lib/ctypes/test/test_callbacks.py
Python
mit
8,245
0.001577
import unittest from ctypes import * import _ctypes_test class Callbacks(unittest.TestCase): functype = CFUNCTYPE ## def tearDown(self): ## import gc ## gc.collect() def callback(self, *args): self.got_args = args return args[-1] def check_type(self, typ, ...
ampleCallbacksTestCase(unittest.TestCase): def test_integrate(self): # Derived from some then non-working code, posted by David Foster dll = CDLL(_ctypes_test.__file__) # The function prototype called by 'integrate': double func(double); CALLBACK = CFUNCTYPE(c_double, c_doub...
egrate integrate.argtypes = (c_double, c_double, CALLBACK, c_long) integrate.restype = c_double def func(x): return x**2 result = integrate(0.0, 1.0, CALLBACK(func), 10) diff = abs(result - 1./3.) self.assertLess(diff, 0.01, "%s not less than 0.01...
sckasturi/saltlake
commands/stopwatch.py
Python
gpl-2.0
3,644
0.001372
# Copyright (C) 2013-2014 Fox Wilson, Peter Foley, Srijay Kasturi, Samuel Damashek and James Forcier # # 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 y...
d = session.query(Stopwatches).filter(Stopwatches.active == 0).all() send("%d active and %d paused stopwatches." % (len(active), len(paused))) for x in active: send('Active stopwatch #%d started at %d' % (x.id, x.time), target=nick) for x in paused: send('Paused stopwatch #%d started at %d t...
"""Start/stops/resume/get stopwatch Syntax: {command} <start|stop|resume|get|list> """ if not msg: send("Invalid Syntax.") return msg = msg.split() command = msg[0] msg = " ".join(msg[1:]) session = args['db'] if command == "start": send(create_sw(session)) e...
xuender/test
testAdmin/itest/migrations/0002_auto__del_field_test_modify_at__del_field_test_create_by__del_field_te.py
Python
apache-2.0
2,475
0.006061
# -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Deleting field 'Test.modify_at' db.delete_column(u'itest_test', 'modify...
d') # Deleting field 'Test.modify_by' db.delete_column(u'itest_test', 'modify_by_id') def backwards(self, orm): # Adding field 'Test.modify_at' db.add_column(u'itest_test', 'modify_at', self.gf('django.db.models.fields.DateTimeField')(default=datetime.datetim...
# Adding field 'Test.create_by' db.add_column(u'itest_test', 'create_by', self.gf('django.db.models.fields.related.ForeignKey')(default=1, related_name='+', to=orm['auth.User']), keep_default=False) # Adding field 'Test.modify_by' db.add_column(u'ites...
openstack/aodh
aodh/tests/functional/storage/test_storage_scenarios.py
Python
apache-2.0
22,582
0
# # Copyright 2013 Intel Corp. # # 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 writin...
staticmethod def create_side_effect(method, exception_type, test_except
ion): def side_effect(*args, **kwargs): if test_exception.pop(): raise exception_type else: return method(*args, **kwargs) return side_effect def setUp(self): super(DBTestBase, self).setUp() patcher = mock.patch.object(timeutil...
aikramer2/spaCy
spacy/lang/fr/tokenizer_exceptions.py
Python
mit
5,710
0.003355
# coding: utf8 from __future__ import unicode_literals import regex as re from ._tokenizer_exceptions_list import FR_BASE_EXCEPTIONS from .punctuation import ELISION, HYPHENS from ..tokenizer_exceptions import URL_PATTERN from ..char_classes import ALPHA_LOWER from ...symbols import ORTH, LEMMA, TAG, NORM, PRON_LEMMA...
pronoun}] for verb, verb_lemma in [ ("est","être")]: for orth in [verb, verb.title()]: token = "{}-ce".format(orth) _exc[token] = [ {LEMMA: verb_lemma, ORTH: orth, TAG: "VERB"}, {LEMMA: 'ce', ORTH: '-ce'}] for pre, pre_lemma in [ ("qu'", "que"), ("n'", "ne")]: ...
"}, {LEMMA: 'être', ORTH: "est", TAG: "VERB"}, {LEMMA: 'ce', ORTH: '-ce'}] _infixes_exc = [] for elision_char in ELISION: for hyphen_char in ['-', '‐']: _infixes_exc += [infix.replace("'", elision_char).replace('-', hyphen_char) for infix in FR_BASE_EXCEPTI...
LernaProject/Lerna
achievements/models.py
Python
gpl-2.0
3,400
0.009412
import collections from django.db import models as md from django.db.models import Q from users.models import User from core.models import Contest from core.models import Problem from core.models import Attempt
AchievementStatus = collections.namedtuple('AchievementStatus', 'achievement unlocked earned_at progress_percent') class Achievement(md.Model): name = md.CharField(max_length=255) description = md.TextField(null=True, blank=True, default=None) points = md.PositiveIntegerField() icon_path ...
d.CharField(max_length=255, null=True, blank=True, default=None) created_at = md.DateTimeField(auto_now_add=True) updated_at = md.DateTimeField(auto_now=True) # filters: amount = md.IntegerField(null=True, blank=True, default=None) problem = md.ForeignKey(Problem, null=True, blank=True, d...
joakim-hove/ert
tests/ert_tests/shared/test_log_abort.py
Python
gpl-3.0
626
0.001597
import logging from unittest.mock import MagicMock, call from ert_logging._log_util_abort import _log_util_abort def test_log_util_abort(caplog, monkeypatch): shutdown_mock = MagicMock() monkeypatch.setattr(logging, "shutdown", shutdown_mock) with caplog.at_level(logging.ERROR): _log_util_abort("f...
ktrace \nwith message: er
r_message \nfrom file: " "fname in some_func at line: 1\n\nPython backtrace:" ) in caplog.text shutdown_mock.assert_called_once_with() # must shutdown to propagate message
HKV-products-services/hkvfewspy
hkvfewspy/io/rest_fewspi.py
Python
bsd-3-clause
21,087
0.001518
import json import requests import types import pandas as pd from datetime import datetime, date import gzip import io from ..utils.simplenamespace import * from ..utils.query_helper import query from ..utils.pi_helper import * import collections class PiRest(object): """create Pi object that can interact with R...
etime abbreviation of the server timezone [eg: 'Etc/GMT'] tz_client : datetime abbreviation of the client timezone [eg: 'Europe/Amsterdam'] return event_client_time : an dateti
me object of the event in client timezome """ # convert XML element date string to integer list event_server_date = list( map(int, event["date"].split("-")) ) # -> [yyyy, MM, dd] event_server_time = list( map(int, event["time"...
digitalocean/netbox
netbox/extras/forms.py
Python
apache-2.0
11,110
0.00108
from django import forms from django.contrib.auth.models import User from django.contrib.contenttypes.models import ContentType from django.utils.safestring import mark_safe from dcim.models import DeviceRole, Platform, Region, Site from tenancy.models import Tenant, TenantGroup from utilities.forms import ( add_b...
'add_tags'] = DynamicModelMultipleChoiceField( queryset=Tag.objects.all(), required=False ) self.fields['remove_tags'] = DynamicModelMultipleChoiceField( queryset=Tag.objects.all(), required=False ) class TagFil
terForm(BootstrapMixin, forms.Form): model = Tag q = forms.CharField( required=False, label='Search' ) class TagBulkEditForm(BootstrapMixin, BulkEditForm): pk = forms.ModelMultipleChoiceField( queryset=Tag.objects.all(), widget=forms.MultipleHiddenInput ) color ...
sbuss/pydockerfile
tests/fixtures.py
Python
mit
884
0
import pytest from pydockerfile.parser import DockerfileParser DOCKERFILE_PATH = 'tests/dockerfiles/basic.Dockerfile' DOCKERFILE_LINE_CONT_PATH = 'tests/dockerfiles/line-cont.Dockerfile' DOCKERFILE_WITH_COMMENTS_PATH = 'tes
ts/dockerfiles/with-comments.Dockerfile' @pytest.fixture def dockerfile_str(): with open(DOCKERFILE_PATH) as f: return f.read() @pytest.fixture def dockerfile_line_cont_str(): with open(DOCKERFILE_LINE_CONT_PATH) as f: return f.read() @pytest.fixture def dockerfile_with_comments_str(): ...
return parser.from_string(dockerfile_str()) @pytest.fixture def dockerfile_with_comments(): parser = DockerfileParser() return parser.from_string(dockerfile_with_comments_str())
endlessm/chromium-browser
third_party/grpc/src/src/python/grpcio_tests/tests/unit/test_common.py
Python
bsd-3-clause
4,042
0.000247
# Copyright 2015 gRPC 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 applicable law or agreed to in writing...
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. """Common code used throughout tests of gRPC.""" import collections import threading from concurrent import futures import grpc ...
six INVOCATION_INITIAL_METADATA = ( ('0', 'abc'), ('1', 'def'), ('2', 'ghi'), ) SERVICE_INITIAL_METADATA = ( ('3', 'jkl'), ('4', 'mno'), ('5', 'pqr'), ) SERVICE_TERMINAL_METADATA = ( ('6', 'stu'), ('7', 'vwx'), ('8', 'yza'), ) DETAILS = 'test details' def metadata_transmitted(orig...
anbangr/trusted-juju
juju/charm/tests/test_url.py
Python
agpl-3.0
5,620
0.000178
from juju.charm.errors import CharmURLError from juju.charm.url import CharmCollection, CharmURL from juju.lib.testing import TestCase class CharmCollectionTest(TestCase): def test_str(self): self.assertEquals( str(CharmCollection("foo", "bar", "baz")), "foo:~bar/baz") self.assertEqua...
ries/name': invalid series (URL " "inferred from 'name')") err = self.assertRaises( CharmURLError, CharmURL.infer, "~user/name", "default") self.assertEquals( str(err), "Bad charm URL '~user/name': a URL with a user must specify a "
"schema")
dpaiton/OpenPV
pv-core/analysis/python/image_shuffle.py
Python
epl-1.0
491
0.040733
import sys import numpy as np import matplotlib.image as mpimg import numpy.random as npr import Image mode = 'L' for i in range(len(sys.argv)-1): i+=1 mi = mpimg.imread(sys.argv[i]) x =
np.shape(mi)[0] mi = np.reshape(mi, (x*x)) mi = npr.permutation(mi) mi = np.reshape(mi, (x,x)) size = np.shape(mi) imNew=Image.new(mode , size) data = np.ravel(mi) data = np.floor(data * 256) imNew.putdata(data) im
New.save("../new-images/%s" %(sys.argv[i]))
mesos-magellan/enrique
enrique/package.py
Python
mit
4,717
0.000212
import os import shutil from urlparse import urlparse from hashlib import sha1 from plumbum.cmd import git, tar, wget, pip, sudo from plumbum import ProcessExecutionError def mkdir_p(path): path = os.path.abspath(os.path.expanduser(path)) if not os.path.exists(path): os.makedirs(path) return path...
lif url_parsed.scheme in ["http", "https"]: if url.endswith("tar.gz"): package_cls = GzipArchive if url.endswith(".git"): package_cls = GitRepo if package_cls is None: raise ValueError return package_cls def get_name_from_url(url): return sha1(url).hexdige...
package.fetch() package.setup() return package class Package(object): def __init__(self, name, url): self.name = name self.url = url self._problem_path = None mkdir_p(self.package_path) def fetch(self): raise NotImplementedError def remove(self): ...
rohitranjan1991/home-assistant
tests/components/marytts/test_tts.py
Python
mit
3,689
0.000271
"""The tests for the MaryTTS speech platform.""" import os import shutil from unittest.mock import patch import pytest from homeassistant.components.media_player.const import ( ATTR_MEDIA_CONTENT_ID, DOMAIN as DOMAIN_MP, SERVICE_PLAY_MEDIA, ) import homeassistant.components.tts as tts from homeassistant.s...
calls = async_mock_service(hass, DOMAIN_MP, SERVICE_PLAY_MEDIA) config = {tts.DOMAIN: {"platform": "marytts", "effect": {"Volum
e": "amount:2.0;"}}} with assert_setup_component(1, tts.DOMAIN): await async_setup_component(hass, tts.DOMAIN, config) await hass.async_block_till_done() with patch( "homeassistant.components.marytts.tts.MaryTTS.speak", return_value=b"audio", ) as mock_speak: await ...
citrix-openstack-build/sahara
sahara/utils/general.py
Python
apache-2.0
3,962
0
# Copyright (c) 2013 Mirantis 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 writ...
ter): hosts = "127.0.0.1 localhost\n" for node_group in cluster.node_groups: for instanc
e in node_group.instances: hosts += "%s %s %s\n" % (instance.internal_ip, instance.fqdn(), instance.hostname()) return hosts def generate_instance_name(cluster_name, node_group_name, index): return ("%s-%s-%03d" % (cluster_...
andrewyoung1991/supriya
supriya/tools/documentationtools/SupriyaDocumentationManager.py
Python
mit
25,757
0.000233
# -*- encoding: utf-8 -*- from __future__ import print_function import enum import inspect import importlib import os import re import shutil import types class SupriyaDocumentationManager(object): @staticmethod def build_attribute_section( cls, attrs, directive, title, ...
result.append(documentationtools.ReSTHeading( level=3, text='Bases', )) mro = inspect.getmro(cls)[1:] for cls in mro: parts = cls.__module__.split('.') + [cls.__name__] while 1 < len(parts) and parts[-1] == parts[-2]: parts.po...
agraph( text=text, wrap=False, ) result.append(paragraph) return result @staticmethod def build_enumeration_section(cls): from abjad.tools import documentationtools result = [] if not issubclass(cls, enum.Enum): ...