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
zephyrzoom/douyu
test/comment-douyu.py
Python
mit
8,896
0.016355
import socket import time import random import threading import re import json import sys import os import platform import notify2 from urllib import request g_rid= b'265352' g_username= b'visitor42' g_ip= b'danmu.douyutv.com' g_port= 8601 g_gid= b'0' g_exit= False sysinfo = platform.system() def notify(title, messag...
ding.Thread(target=keepalive_recv).start() return ret def get_danmu(ri
d=b'5275', ip=b'danmu.douyutv.com', port=8001, username=b'visitor42', gid=b'0'): "args needs bytes not str" print('==========danmu') s= socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((ip,int(port))) sendmsg(s,b'type@=loginreq/username@='+username+b'/password@=1234567890123456/roomid@='...
franek/weboob
modules/imdb/browser.py
Python
agpl-3.0
9,076
0.000662
# -*- coding: utf-8 -*- # Copyright(C) 2013 Julien Veyssier # # This file is part of weboob. # # weboob is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your op...
de(m['title'])) movie.other_titles = NotLoaded movie.rel
ease_date = NotLoaded movie.duration = NotLoaded movie.short_description = latin2unicode(short_description) movie.pitch = NotLoaded movie.country = NotLoaded movie.note = NotLoaded movie.roles = NotLo...
ptthiem/nose2
nose2/tools/such.py
Python
bsd-2-clause
12,153
0.000494
from contextlib import contextmanager import logging import sys import six import unittest from nose2 import util from nose2.main import PluggableTestProgram log = logging.getLogger(__name__) __unittest = True LAYERS_PLUGIN_NOT_LOADED_MESSAGE = 'Warning: Such will not function properly if the "nose2.plugins.layers...
method will run before each of the tests in the containing group. A group may define any number of test case :func:`teardown` functions. They will execute in the order in which they are defined. Test :func:`teardown` functions may optionally take one argument. If they ...
will be passed the :class:`unittest.TestCase` instance generated for the test. .. code-block :: python @it.has_test_teardown def teardown(case): # ... """ self._group.addTestTearDown(func) def should(self, desc): """Define a test case....
landism/pants
contrib/android/src/python/pants/contrib/android/tasks/unpack_libraries.py
Python
apache-2.0
14,015
0.009062
# coding=utf-8 # Copyright 2015 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import os from hashl...
:return: A new a
ndroid resources target. :rtype::class:`pants.contrib.android.targets.AndroidResources` """ address = Address(os.path.relpath(self.workdir, get_buildroot()), '{}-resources'.format(coordinate.artifact_filename)) new_target = self.context.add_new_target(address, AndroidResources, ...
foursquare/pants
tests/python/pants_test/util/test_process_handler.py
Python
apache-2.0
1,506
0.005312
# coding=utf-8 # Copyright 2015 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import absolute_import, division, print_function, unicode_literals import unittest from pants.util.process_handler import SubprocessProcessHandler, subproc...
ho >&2 "1err" sleep 0.05 echo >&2 "2err" echo "2out" sleep 0.05 echo "3out" sleep 0.05 echo >&2 "3err" sleep 0.05 exit 1 """], stdout=subprocess.PIPE, stderr=subprocess.PIPE) process_handler = SubprocessProcessHandler(process)
self.assertEquals(process_handler.communicate_teeing_stdout_and_stderr(), ( b"""1out 2out 3out """, b"""1err 2err 3err """)) # Sadly, this test doesn't test that sys.std{out,err} also receive the output. # You can see it when you run it, but any way we have of spying on sys.std{out,err} # isn't picklabl...
beiko-lab/gengis
bin/Lib/site-packages/wx-2.8-msw-unicode/wx/tools/Editra/src/syntax/_php.py
Python
gpl-3.0
30,237
0.001951
############################################################################### # Name: php.py # # Purpose: Define PHP syntax for highlighting and other features # # Author: Cody Precord <cprecord@editra.org> # ...
roke cpdf_fill cpdf_finalize_pa
ge " "cpdf_finalize cpdf_global_set_document_limits cpdf_import_jpeg " "cpdf_lineto cpdf_moveto cpdf_newpath cpdf_open cpdf_output_buffer " "cpdf_page_init cpdf_place_inline_image cpdf_rect cpdf_restore " "cpdf_rlineto cpdf_rmoveto cpdf_rotate_text cpdf_rotate " ...
matt-gardner/deep_qa
deep_qa/layers/masked_layer.py
Python
apache-2.0
786
0.006361
from keras.layers import Layer class MaskedLayer(Layer): """ Keras 2.0 allowed for arbitrary differences in arguments to the ``call`` method of ``Layers``. As part of this, they removed the default ``mask=None`` argument, which means that if you want to
implement ``call`` with a mask, you need to disable a pylint warning. Instead of disabling it in every single layer in our codebase, which
could lead to uncaught errors, we'll have a single place where we disable it, and have other layers inherit from this class. """ def __init__(self, **kwargs): self.supports_masking = True super(MaskedLayer, self).__init__(**kwargs) def call(self, inputs, mask=None): # pylint: disable=...
klen/adrest
tests/main/api.py
Python
lgpl-3.0
929
0
from .resources import ( AuthorResource, BookPrefixResource, ArticleResource, SomeOtherResource, CustomResource, CSVResource) from adrest.api import Api from adrest.utils.auth import AnonimousAuthenticator, AccessKeyAuthenticator, \
UserAuthenticator from adrest.utils.emitter import XMLTemplateEmitter, JSONEmitter from adrest.utils.throttle imp
ort CacheThrottle class CustomUserAuth(UserAuthenticator): username_fieldname = 'nickname' API = Api( version=(1, 0, 0), emitters=(XMLTemplateEmitter, JSONEmitter), throttle=CacheThrottle, api_prefix='main') API.register(AuthorResource, authenticators=(CustomUserAuth, AnonimousAuthenticato...
PaddlePaddle/Paddle
python/paddle/fluid/tests/unittests/auto_parallel/test_auto_parallel_while_op.py
Python
apache-2.0
17,997
0.000835
# Copyright (c) 2022 PaddlePaddle 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 ap...
addle.distributed.auto_parallel as auto from paddle.distributed import fleet from paddle.distributed.auto_parallel.partitioner import Partitioner from paddle.distributed.auto_parallel.utils import make_data_unshard from paddle.distributed.auto_parallel.dist_attribute import OperatorDistributedAttribute, TensorDistrib...
ted.auto_parallel.operators import find_best_compatible_distributed_operator_impl paddle.enable_static() batch_size = 4 epoch_num = 10 hidden_size = 1024 sequence_len = 512 _g_process_mesh = auto.ProcessMesh([0, 1]) def get_random_inputs_and_labels(input_shape, label_shape): input = np.random.random(size=input_...
1up3d/Stallman
src/MCAD/openscad_utils.py
Python
gpl-3.0
1,933
0.007243
import py, re, os, signal, time, commands from subprocess import Popen, PIPE mod_re = (r"\bmodule\s+(", r")\s*\(\s*") func_re = (r"\bfunction\s+(", r")\s*\(") def extract_definitions(fpath, name_re=r"\w+", def_re=""): regex = name_re.join(def_re) matcher = re.compile(regex) return (m.group(1) for m in mat...
modules = extract_mod_names(fpath, r"te
st\w*") #functions = extract_func_names(fpath, r"test\w*") test_files[fpath] = modules return test_files class Timeout(Exception): pass def call_openscad(path, stlpath, timeout=5): command = ['openscad', '-s', str(stlpath), str(path)] print command if timeout: try: ...
nwjs/chromium.src
third_party/android_deps/libs/com_google_android_material_material/3pp/fetch.py
Python
bsd-3-clause
1,395
0.000717
#!/usr/bin/env python # Copyright 2021 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # This is generated, do not edit. Update BuildConfigGenerator.groovy and # 3ppFetch.template instead. from __future__ import print_fun...
raise Exception('Unsupported extension for %s' % _FILE_U
RL) partial_manifest = { 'url': [_FILE_URL], 'name': [_FILE_NAME], 'ext': ext, } print(json.dumps(partial_manifest)) def main(): ap = argparse.ArgumentParser() sub = ap.add_subparsers() latest = sub.add_parser("latest") latest.set_defaults(func=lambda _opts: do_la...
wmaier/treetools
trees/transformconst.py
Python
gpl-3.0
4,747
0.012429
"""treetools: Tools for transforming treebank trees. transformations: constants and utilities Author: Wolfgang Maier <maierw@hhu.de> """ from . import trees # Head rules for PTB (WSJ) from Collins (1999, p. 240) HEAD_RULES_PTB = { 'adjp' : [('left-to-right', 'nns qp nn $ advp jj vbn vbg adjp jjr np jjs dt fw rbr...
-right', 'prtzu appr ptkzu')], 'np' : [('right-to-left', 'nn ne mpn np cnp pn car')], 'ap' : [('right-to-left', 'adjd adja cap aa adv')], 'pp' : [('left-to-right', 'kokom appr proav')], 'co' : [('left-to-right', '')], 'avp' : [(
'right-to-left', 'adv avp adjd proav pp')], 'aa' : [('right-to-left', 'adjd adja')], 'cnp' : [('right-to-left', 'nn ne mpn np cnp pn car')], 'cap' : [('right-to-left', 'adjd adja cap aa adv')], 'cpp' : [('right-to-left', 'appr proav pp cpp')], 'cs' : [('right-to-left', 's cs')], 'cvp' : [('right...
sorgerlab/belpy
indra/tests/test_indranet_assembler.py
Python
mit
13,200
0.000076
import numpy as np import pandas as pd import networkx as nx from indra.statements import * from indra.assemblers.indranet.net import default_sign_dict from indra.assemblers.indranet import IndraNetAssembler, IndraNet ev1 = Evidence(pmid='1') ev2 = Evidence(pmid='2') ev3 = Evidence(pmid='3') st1 = Activation(Agent('a...
ce_api='sparser')]) ab2 = Phosphorylation(Agent('a'), Agent('b'),evidence=[ Evidence(source_api='sparser'), Evidence(source_api='reach')]) ab3 = Inhibiti
on(Agent('a'), Agent('b'), evidence=[ Evidence(source_api='sparser'), Evidence(source_api='reach')]) ab4 = IncreaseAmount(Agent('a'), Agent('b'), evidence=[ Evidence(source_api='trips')]) bc1 = Activation(Agent('b'), Agent('c'), evidence=[ Evidence(source_api='trips')]) bc2 = Inhibition(Agent('b'), Agent('c...
ericem/sprintkit
src/sprintkit/services.py
Python
mit
44,648
0.006092
""" sprintkit.services ================== Implementations of most Developer Sandbox Services. :Copyright: (c) 2011 by Sprint. :License: MIT, see LICENSE for more details. """ from ConfigParser import SafeConfigParser from datetime import datetime from hashlib import md5 import json import os import time import urlpa...
loper_secret> host = test.sprintdevelopersandbox.com path = /developerSandbox/resources/v1 :class:`Config` will also try to read the Sandbox Key and Sandbox Secret from the environment variables `SPRINTKEY` and `SPRINTSECRET`. It will try these last so they can be used to overri...
:class:`Config` does not provide file writing capabilities, so any changes made to a config instance programatically will need to be also made in the config file in order to make the changes permanent. ''' def __init__(self, path=None): if path == None: home_dir = os.path.exp...
nok/sklearn-porter
tests/estimator/classifier/BernoulliNB/BernoulliNBJSTest.py
Python
mit
1,182
0.000846
# -*- coding: utf-8 -*- import unittest from unittest import TestCase from sklearn.naive_bayes import BernoulliNB from tests.estimator.classifier.Classifier import Classifier from tests.language.JavaScript import JavaScript class BernoulliNBJSTest(JavaScript, Classifier, TestCase): def setUp(self): su...
ttest.skip('BernoulliNB is just suitable for discrete data.') def test_existing_features__binary_data__default(self): pass @unittest.skip('BernoulliNB is just suitable for discrete data.') def test_random_features__binary_data__default(self): pass @unittest.skip('BernoulliNB is just su...
def test_existing_features__digits_data__default(self): pass
quells/MarkdownToReport
MDToLatex.py
Python
mit
4,002
0.037481
#!/usr/bin/python # -*- coding: utf-8 -*- import sys import re import MDToLatexTemplates as Templates import subprocess def match(string, regex): return True if re.match(re.compile(regex), string) else False def ConvertMetadata(text): metadata_regex = r'^---\n(.*\n)+---$' if match(text, metadata_regex): metadat...
with open(filename) as file: text = file.read() blocks = text.split('\n\n') latex = Templates.BuildDocument(doctype) for i in range(len(blocks)): b = blocks[i] if i == 0: metadata = ConvertMetadata(b) if metadata != b: title = metadata.get('title', None) subtitle = metadata.get('subtitle', No...
emplates.BeginDocument(doctype) Class = metadata.get('class', None) due = metadata.get('due', None) received = metadata.get('received', None) latex += Templates.BuildInfoTable(Class, due, received) thanks = metadata.get('thanks', None) latex += Templates.BuildThanks(thanks) ab...
misel228/piwindow
piw_nonet.py
Python
mit
1,082
0.020333
#!/usr/bin/python from __future__ import abs
olute_import, division, print_function, unicode_literals import pi3d import ConfigParser from PIL import Image import sys #read config Config = ConfigParser.ConfigParser() Config.read("config.in
i") xloc = int(Config.get("client",'x_offset')) yloc = int(Config.get("client",'y_offset')) x_virtual = int(Config.get("client",'x_virtual')) y_virtual = int(Config.get("client",'y_virtual')) ifile = Config.get("client","default_image") im = Image.open(ifile) xsize,ysize = im.size zindex = 5 DISPLAY = pi3d.Disp...
AstrorEnales/CodeEval
Easy/Armstrong Numbers/main.py
Python
mit
248
0
import sys lines = open(sy
s.argv[1], 'r') for line in lines: line = line.replace('\n', '').replace('\r', '') if len(line) > 0: num = int(line) print(num == sum([int(x) ** len(line) for x in line])) lines.close(
)
rsnakamura/oldape
apetools/proletarians/hortator.py
Python
apache-2.0
2,913
0
# python Libraries from collections import namedtuple # apetools Libraries from apetools.baseclass import BaseClass from errors import OperatorError from countdown import CountDown ELAPSED_TIME = 'Elapsed Time: {t}' class CrashRecord(namedtuple("CrashRecord", "id start_time crash_time...
ash_times = [] for operation_count, operation in enumerate(self.operations): operation_start = self.countdown.now
try: operation() except OperatorError as error: crash_time = self.countdown.now self.logger.error(error) crash_times.append(CrashRecord(id=operation_count, start_time=operation_start, ...
arider/wikimodel
wiki_model.py
Python
mit
4,572
0
import numpy from wiki_scraper import ( parse_html_simple, crawl_page) import pickle from sklearn.feature_extraction.text import CountVectorizer from sklearn.naive_bayes import MultinomialNB import os.path from parallel_webscrape import scrape_wikipedia PATH = 'wikimodel/' class WikiModel(): def __init_...
. args: domain - the domain part of the url page - the other part of the url depth - how deep to crawl returns: a list of predicted probabilities for each instance belonging to each class """ # get the documents docume...
age, depth=0) # parse the documents string_data = [] for page, doc in documents.iteritems(): words = parse_html_simple(doc) parsed = [] for word in words: if (word in self.english_words and word not in self.stop_words ...
FuelCellUAV/FC_datalogger
quick2wire/quick2wire/syscall.py
Python
cc0-1.0
503
0.001988
import
ctypes libc = ctypes.CDLL(None, use_errno=True) def errcheck(result, func, args): if result < 0: e = ctypes.get_errno() raise OSError(e, errno.strerror(e)) return result def lookup(restype, name, argtypes): f = libc[name] f.restye = restype f.argtypes = argtypes f.errcheck ...
lf): return self def __exit__(self, *exc): self.close() return False
tensorflow/similarity
tensorflow_similarity/visualization/confusion_matrix_viz.py
Python
apache-2.0
3,526
0.000284
# Copyright 2021 The TensorFlow 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 ...
linalg.trace(cm) / tf.math.reduce_sum(cm) misclass = 1 - accuracy if normalize: cm = tf.math.divide_no_nan( cm, tf.math.reduce_sum(cm, axis=1)[:, np.newaxis] ) f, ax = plt.subplots(figsize=(8, 6)) im = ax.imshow(cm, interp...
bels is not None: tick_marks = np.arange(len(labels)) ax.set_xticks(tick_marks) ax.set_xticklabels(labels, rotation=45) ax.set_yticks(tick_marks) ax.set_yticklabels(labels) cm_max = tf.math.reduce_max(cm) thresh = cm_max / 1.5 if normalize els...
hibooboo2/validation-tests
tests/validation/cattlevalidationtest/core/test_services.py
Python
apache-2.0
33,141
0
from common_fixtures import * # NOQA TEST_SERVICE_OPT_IMAGE = 'ibuildthecloud/helloworld' TEST_SERVICE_OPT_IMAGE_LATEST = TEST_SERVICE_OPT_IMAGE + ':latest' TEST_SERVICE_OPT_IMAGE_UUID = 'docker:' + TEST_SERVICE_OPT_IMAGE_LATEST LB_IMAGE_UUID = "docker:sangeetha/testlbsd:latest" SSH_IMAGE_UUID = "docker:sangeetha/te...
ost = "/test/container" volume_in_container = "/test/vol1" docker_vol_value = volume_in_host + ":" + volume_in_container + ":ro" cap_add = ["CHOWN"] cap_drop = ["KILL"] restart_policy = {"maximumRetryCount": 10, "name": "on-failure"} dns_search = ['1.2.3.4'] dns_name = ['1.2.3.4'] domai...
memory = 8000000 cpu_set = "0" cpu_shares = 400 launch_config = {"imageUuid": TEST_SERVICE_OPT_IMAGE_UUID, "command": command, "dataVolumes": [docker_vol_value], "dataVolumesFrom": [vol_container.id], "environment": env_va...
bkeroack/elita
elita/dataservice/root_tree.py
Python
apache-2.0
2,449
0.003267
__author__ = 'bkeroack' import logging import collections import pprint class RootTree(collections.MutableMapping): def __init__(self, db, updater, tree, doc, *args, **kwargs): self.pp = pprin
t.PrettyPrinter(indent=4) self.db = db self.tree = tree self.doc = doc self.updater = updater def is_action(self): return self.doc and s
elf.doc['_class'] == 'ActionContainer' def __getitem__(self, key): key = self.__keytransform__(key) if self.is_action(): return self.tree[key] if key in self.tree: if key == '_doc': return self.tree[key] doc = self.db.dereference(self.tree...
lfcnassif/MultiContentViewer
release/modules/ext/libreoffice/program/python-core-3.3.0/lib/encodings/iso8859_1.py
Python
lgpl-3.0
13,225
0.02155
""" Python Character Mapping Codec is
o8859_1 generated from 'MAPPINGS/ISO8859/8859-1.TXT' with gencodec.py. """#" import codecs ### Codec APIs class Codec(codecs.Codec): def encode(self,input,errors='strict'): return codecs.charmap_encode(input,errors,encoding_table) def decode(self,input,errors='strict'): return codecs.charm...
coding_table)[0] class IncrementalDecoder(codecs.IncrementalDecoder): def decode(self, input, final=False): return codecs.charmap_decode(input,self.errors,decoding_table)[0] class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings modu...
parmes/parmes
trs/tr2/shortest-runtime-reldelta.py
Python
mit
2,349
0.046403
import subprocess reldelta = ['minWii', 'avgWii', 'maxWii'] kinem = ['RG', 'PR'] cases = ['A', 'B', 'C'] X_label = ['delta', 'delta', 'delta'] Y_label = ['epsilon', 'm', '(m, eps)'] X_index = [6, 6, 6] Y_index = [8, 9, (8, 9)] print 'Decompressing data files...' process
= subprocess.Popen('unzip -o data.zip', shell=True) process.wait(
) print 'Scanning runtimes...' for kin in kinem: for rldl in reldelta: mintime = 1E10 mintdelta = 0 minteps = 0.0 mintm = 0 minrun = '' for case in cases: ic = cases.index(case) with open('data/tr2-dru100-reldelta-runtimes', 'r') as inp: ln = inp.readline() ln = ln.split(' = ') ...
hydroshare/hydroshare
hs_core/management/commands/migrate_generic_resources.py
Python
bsd-3-clause
1,841
0.003259
import logging from django.core.management.base import BaseCommand from hs_core.models import GenericResource from hs_core.hydroshare import current_site_url, set_dirty_bag_flag class Command(BaseCommand): help = "Convert all generic resources to composite resource" def handle(self, *args, **options): ...
resource object - CompositeResource comp_res
= gen_res.get_content_model() # update url attribute of the metadata 'type' element type_element = comp_res.metadata.type type_element.url = '{0}/terms/{1}'.format(current_site_url(), to_resource_type) type_element.save() # set resource to dirty so that reso...
erigones/esdc-ce
api/mon/log.py
Python
apache-2.0
2,678
0.003361
from logging import CRITICAL, getLevelName from functools import wraps from django.utils.decorators import available_attrs from celery import states from celery.utils.log import get_task_logger from api.decorators import catch_exception from api.task.utils import task_log logger = get_task_logger(__name__) class De...
(the "vm_zoneid_changed" case) def add(self, level, message): return self.append((level, message)) def get_detail(self): return '\n'.join('%s: %s' % (getLevelName(level), message) for level, message in self) @cat
ch_exception def save(self, status): """Save task log entry if result is not None""" if hasattr(status, '__iter__'): status = [i for i in status if i is not None] # remove None from result if status: success = all(status) else: su...
noironetworks/heat
heat/objects/software_config.py
Python
apache-2.0
2,376
0
# Copyright 2014 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 writing, soft...
'id': fields.StringField(), 'name': fields.StringField(nullable=True), 'group': fields.StringField(nullable=True), 'tenant': fields.StringField(nullable=True), 'config': heat_fields.JsonField(nullable=True), 'created_at': fields.DateTimeField(read_only=True), 'updated_at'...
bject(context, config, db_config): # SoftwareDeployment._from_db_object may attempt to load a None config if db_config is None: return None for field in config.fields: config[field] = db_config[field] config._context = context config.obj_reset_changes() ...
sasukeh/acos-client
acos_client/v30/slb/virtual_port.py
Python
apache-2.0
3,458
0.000289
# Copyright 2014, Jeff Buttars, A10 Networks. # # 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 appli...
OXY = "tcp-proxy" url_server_tmpl = '/slb/virtual-server/{name}/port/' url_port_tmpl = '{port_number}+{protocol}' def all(self, virtual_server_name, **kwargs): url = self.url_server_tmpl.format(name=virtual_server_name) return self._get(url, **kwargs) def _set(self, virtual_server_nam...
*kwargs): params = { "port": self.minimal_dict({ "name": name, "service-group": service_group_name, "protocol": protocol, "port-number": int(port), "template-persist-source-ip": s_pers_name, "template-pe...
lukleh/TwistedBot
twistedbot/plugins/core/chat_debug.py
Python
mit
1,061
0.000943
from twistedbot.plugins.base import PluginChatBase from twistedbot.behavior_tree import InventorySelectActive class Debug(PluginChatBase): @property def command_verb(self): return "debug" @property def help(self): return "help for debug" def command(self, sender, command, args):...
item_name = " ".join(subject[1:]) if not item_name:
self.send_chat_message("specify item") return itemstack = InventorySelectActive.parse_parameters(item_name) if itemstack is not None: self.world.bot.behavior_tree.new_command(InventorySelectActive, itemstack=itemstack) ...
Aukan96/Diario-bot-1.0
InteligenciaBot.py
Python
apache-2.0
18,967
0.032863
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import re import random import sys import unicodedata import my_conexion sys.stdout.encoding 'UTF-8' # PROCESAR MENSAJE DE USUARIO def generarRespuesta(mensaje, STATES, username): message_=sinAcentos(mensaje) ans='' ve...
if NO_MATCH: my_conexion.cambiar_estado('papa',username
) ev = random.randint(1, 2) if ev == 1: STATES['papa'] = True ans =ans + "\nLo siento mucho, se que es algo demaciado doloroso, ¿Quieres seguir platicando?..." if ev == 2: STATES['papa'] = True ans =ans + "\nQue fuerte, lo siento ¿Quieres seguir platicando?..." ...
mrjacobagilbert/gnuradio
gr-dtv/python/dtv/atsc_rx_filter.py
Python
gpl-3.0
2,537
0.007095
#!/usr/bin/env /usr/bin/python # # Copyright 2014 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio 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, or (at your o...
_(self, "atsc_rx_filter", gr.io_signature(1, 1, gr.sizeof_gr_complex), # Input signature gr.io_signature(1, 1, gr.sizeof_gr_complex)) # Output signature # Create matched RX filter with RRC response fo
r fractional # interpolator. nfilts = 16 output_rate = ATSC_SYMBOL_RATE*sps # Desired oversampled sample rate filter_rate = input_rate*nfilts symbol_rate = ATSC_SYMBOL_RATE / 2.0 # One-sided bandwidth of sideband excess_bw = 0.1152 #1.0-(0.5*ATSC_SYMBOL_RATE/ATSC_CHANNEL_...
xiiicyw/Data-Wrangling-with-MongoDB
Lesson_1_Data_Extraction_Fundamentals/14-JSON_Playground/musicbrainz.py
Python
agpl-3.0
1,596
0.000627
# To experiment with this code freely you will have to run this code locally. # We have provided an example json output here for you to look at, # but you will not be able to run any queries through our UI. import json import requests BASE_URL = "http://musicbrainz.org/ws/2/" ARTIST_URL = BASE_URL + "artist/" query_...
nt "requesting", r.url if r.status_code == requests.codes.ok: return r.json() else: r.raise_for_status() def query_by_name(url, params, name): params["query"] = "artist:" + name return query_site(url,
params) def pretty_print(data, indent=4): if type(data) == dict: print json.dumps(data, indent=indent, sort_keys=True) else: print data def main(): results = query_by_name(ARTIST_URL, query_type["simple"], "First Aid Kit") pretty_print(results) artist_id = results["artists"][1]...
KartikKannapur/Programming_Challenges
Project-Euler-Solutions/011.py
Python
mit
1,639
0.015863
def format(): text = "" stopword = "" while True: line = raw_input() if line.strip() == stopword: break text += "%s\n" % line text_arr = text.split('\n') global arr arr = [[] for _ in range(21)] for i in range(21): arr[i].append(text_arr[i]) ...
test = 0 for i in range(20): for j in range(16): # horizontal products prod = arr[i][0][j]*arr[i][0][j+1]*arr[i][0][j+2]*arr[i][0][j+3] if prod > greatest: greatest = prod # vertical products prod = arr[j][0][i]*arr[j+1][0][...
j+2][0][i]*arr[j+3][0][i] if prod > greatest: greatest = prod # diagonal products for i in range(16): for j in range(16): prod = arr[i][0][j]*arr[i+1][0][j+1]*arr[i+2][0][j+2]*arr[i+3][0][j+3] if prod > greatest: greatest = prod ...
lamby/django-append-url-to-sql
append_url_to_sql/models.py
Python
bsd-3-clause
2,204
0.001815
""" :mod:`django-append-url-to-sql` --- Appends the request URL to SQL statements in Django ======================================================================================= Whilst the `Django Debug Toolbar <https://github.com/robhudson/django-debug-toolbar>`_ is invaluable for development in a local environment...
``SHOW PROCESSLIST`` output to the view that is execut
ing it. If the current request URL cannot be determined, nothing is appended. Installation ------------ 1. Add ``append_url_to_sql`` to your ``INSTALLED_APPS``:: INSTALLED_APPS = ( ... 'append_url_to_sql', ... ) Configuration ------------- ``APPEND_URL_TO_SQL_ENABLED`` ~~~~~~~~~~~~...
msabramo/PyHamcrest
src/hamcrest/library/collection/isdict_containingentries.py
Python
bsd-3-clause
5,168
0.001161
from hamcrest.core.base_matcher import BaseMatcher from hamcrest.core.helpers.hasmethod import hasmethod from hamcrest.core.helpers.wrap_matcher import wrap_matcher __author__ = "Jon Reid" __copyright__ = "Copyright 2011 hamcrest.org" __license__ = "BSD, see License.txt" class IsDictContainingEntries(BaseMatcher): ...
their value matchers: .. function:: has_entries(key1, value_matcher1[, ...]) :param key1: A key (not a matcher) to look u
p. :param valueMatcher1: The matcher to satisfy for the value, or an expected value for :py:func:`~hamcrest.core.core.isequal.equal_to` matching. Examples:: has_entries('foo', equal_to(1), 'bar', equal_to(2)) has_entries('foo', 1, 'bar', 2) """ if len(keys_valuematchers) == 1:...
witcxc/scipy
scipy/cluster/hierarchy.py
Python
bsd-3-clause
94,372
0.000138
""" ======================================================== Hierarchical clustering (:mod:`scipy.cluster.hierarchy`) ======================================================== .. currentmodule:: scipy.cluster.hierarchy These functions cut hierarchical clusterings into flat clusterings or find the roots of the forest f...
gle': 0, 'complete': 1, 'average': 2, 'weighted': 6} _cpy_euclid_methods = {'centroid': 3, 'median': 4, 'ward': 5} _cpy_linkage_methods = set(_cpy_non_euclid_methods.keys()).union( set(_cpy_euclid_methods.keys())) __all__ = ['ClusterNode', 'average', 'ce
ntroid', 'complete', 'cophenet', 'correspond', 'dendrogram', 'fcluster', 'fclusterdata', 'from_mlab_linkage', 'inconsistent', 'is_isomorphic', 'is_monotonic', 'is_valid_im', 'is_valid_linkage', 'leaders', 'leaves_list', 'linkage', 'maxRstat', 'maxdists', 'maxinconsts', ...
yourcelf/btb
scanblog/btb/registration_migrations/0002_auto_20150902_1253.py
Python
agpl-3.0
479
0.002088
# -*- coding: utf-8 -*- from __future__ import unicode_literals from dja
ngo.db import models, migrations from django.conf import settings class Migration(migrations.Migration): dependencies = [ ('registration', '0001_initial'), ] operations = [ migrations.AlterField(
model_name='registrationprofile', name='user', field=models.OneToOneField(verbose_name='user', to=settings.AUTH_USER_MODEL), ), ]
dictoss/active-task-summary
ats/libs.py
Python
bsd-2-clause
3,533
0.000283
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import sys import time import datetime import logging import csv import six from datetime import date from django.apps import apps from django.utils import timezone logger = logging.getLogger(__name__) ats_settings = apps.get_app_config('ats') def get_user_rea...
_line.append(d['task__userdata5'])
_line.append(d['comment']) if six.PY2: for i in range(len(_line)): _line[i] = _line[i].encode('utf8') _writer.writerow(_line) _s = bufffer.getvalue() bufffer.close() if six.PY3: _s ...
Chris7/django-referral
referral/tests/test_middlewares.py
Python
mit
2,092
0
from django.test import TestCase from django.http import HttpRequest from referral.middleware import ReferrerMiddleware from referral.models import Referrer from referral import settings class ReferrerMiddlewareTest(TestCase): def setUp(self): self.ref_middleware = ReferrerMiddleware() self.reque...
lf.request.GET[settings.GET_PARAMETER] = "new_ref" self.ref_middleware.process_request(self.request) self.assertEqual(Referrer.objects.all()[0].name, "new_ref") def test_process_request_new_ref_no_autocreate(self): settings.AUTO_
CREATE = False self.request.GET[settings.GET_PARAMETER] = "new_ref" self.ref_middleware.process_request(self.request) self.assertEqual(Referrer.objects.count(), 0) settings.AUTO_CREATE = True def test_referral_case_sensitive(self): settings.CASE_SENSITIVE = True self...
TACCProjects/tacc_stats
tacc_stats_web/apps/tacc_stats/urls.py
Python
lgpl-2.1
1,061
0.012253
from django.conf.urls.defaults import patterns, url from django.views.generic import DetailView, ListView from tacc_stats.models import Job from tacc_stats.views import index, job_memused_hist, job_timespent_hist, create_heatmap, search, JobListView, render_json, get_job, data, list_hosts urlpatterns = patterns('', ...
url(r'^$', index), url(r'^joblist$', JobListView.as_view()), url(r'^job/(?P<pk>\d+)/$', DetailView.as_view( model=Job, # template_name='tacc_stats/detail.html', )), url(r'^job_memused_hist$', job_memused_hist ), url(r'^job_timespent_hist$', job_timespent_h...
ob_flops_heatmap/(\d+)/$', create_heatmap, {'trait' : 'flops'}), url(r'^search/$', search ), url(r'^render/jobs/$', render_json), url(r'^(\w+)/(\d+)/$', get_job ), url(r'^data/$', data ), url(r'^hosts/$', list_hosts ), )
aguirrem/skyeye
utils/pycli/skyeye_common_module.py
Python
gpl-2.0
970
0.002062
#### SkyEye common module #### import
os from ctypes import * libcommon_path = os.getenv("SKYEYEBIN") + "/../lib/skyeye/libcommon.so" libcommon = CDLL(libcommon_path, RTLD_GLOBAL) #### SkyEye other modules #### libdisasm_path = os.getenv("SKYEYEBIN") + "/../lib/skyeye/libdisasm.so" libpmon_path = os.getenv("SKYEYEBIN") + "/../lib/skyeye/libpmon.so" lib...
+ "/../lib/skyeye/libbus_log.so" libgdbserver_path = os.getenv("SKYEYEBIN") + "/../lib/skyeye/libgdbserver.so" # Generate CDLL handlers libdisasm = CDLL(libdisasm_path, RTLD_LOCAL) libpmon = CDLL(libpmon_path, RTLD_LOCAL) libuart_16550 = CDLL(libuart_16550_path, RTLD_LOCAL) libcodecov = CDLL(libcodecov_path, RTLD_LOCA...
cmin764/cloudbase-init
cloudbaseinit/exception.py
Python
apache-2.0
1,184
0
# Copyright 2014 Cloudbase Solutions Srl # # 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 L
icense at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the sp...
eInitException): pass class WindowsCloudbaseInitException(CloudbaseInitException): def __init__(self, msg="%r", error_code=None): if error_code is None: error_code = ctypes.GetLastError() description = ctypes.FormatError(error_code) try: formatted_msg = msg % d...
ChawalitK/odoo
addons/payment_stripe/controllers/main.py
Python
gpl-3.0
2,191
0.002738
# -*- coding: utf-8 -*- import logging import pprint import werkzeug from odoo import http from odoo.http import request _logger = logging.getLogger(__name__) class StripeController(http.Controller): @http.route(['/payment/stripe/s2s/create_json'], type='json', auth='public') def stripe_s2s_create_json(sel...
th='public') def stripe_s2s_create(self, **post): acquirer_id = int(post.get('acquirer_id')) acquirer = request.env['payment.acquirer'].browse(acquirer_id) acquirer.s2s_process(post) return werkzeug.utils.redirect(post.get('return_url', '/')) @http.route(['/payment/stripe/create...
popup""" acquirer = request.env['payment.acquirer'].browse(int(post.get('acquirer_id'))) order = request.env['sale.order'].sudo().browse(int(request.session.get('sale_order_id'))) tx = request.env['payment.transaction'].sudo().create({ 'acquirer_id': acquirer.id, 'referen...
vsoch/singularity-python
singularity/analysis/reproduce/hash.py
Python
agpl-3.0
6,435
0.004507
''' Copyright (C) 2016-2019 Vanessa Sochat. This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distribute...
e a level_filter manually with level_filter (for custom levels) :param level: the level of reproducibility to use, which maps to a se
t regular expression to match particular files/folders in the image. Choices are in notes. :param skip_files: an optional list of files to skip :param include_files: an optional list of files to keep (only if level not defined) :param version: the version to use. If not defined, default is 2.3 ::no...
noahgift/devml
devml/code_counts.py
Python
mit
2,797
0.006435
import os from subprocess import (Popen, PIPE) import pandas as pd from sensible.loginit import logger log = logger(__name__) LINES_COUNT="""git ls-files | grep py | while read f; do git blame -w -M -C -C --line-porcelain "$f" | grep \'^author \'; done | sort -f | uniq -ic | sort -n""" def subdirs(path): """Yiel...
rame of churned files in a git repository""" os.chdir(path) #change directory to process git log count_msg = "Running lines/python cmd: [%s] at path [%s]" % (LINES_COUNT, path) log.info(count_msg) p = Popen(LINES_COUNT, shell=True, stdout=PIPE) (line_count, _) = p.communicate() retu
rn line_count def clean_line_count_output(out): """Clean shell output into list based records""" record = [] count_lines = out.split(b"\n") #import ipdb;ipdb.set_trace() for line in count_lines: if line: line = line.split() log.debug(len(line)) if len(l...
enthought/etsproxy
enthought/mayavi/filters/collection.py
Python
bsd-3-clause
94
0
# proxy
module from __future__ import absolute_import from mayavi.filters.collection impo
rt *
rspavel/spack
var/spack/repos/builtin/packages/py-localcider/package.py
Python
lgpl-2.1
788
0.003807
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-
2.0 OR MIT) from spack import *
class PyLocalcider(PythonPackage): """Tools for calculating sequence properties of disordered proteins""" homepage = "http://pappulab.github.io/localCIDER" url = "https://pypi.io/packages/source/l/localcider/localcider-0.1.14.tar.gz" version('0.1.14', sha256='54ff29e8a011947cca5df79e96f3c69a76c4...
madprof/alpha-hub
prototype/pool.py
Python
agpl-3.0
6,257
0.001438
# |ALPHA| Hub - an authorization server for alpha-ioq3 # See files README and COPYING for copyright and licensing details. """ A throwaway thread pool with thread-local storage. Throwaway Tasks =============== A throwaway task is one you'd *like* to get done, but it's not a big deal if it doesn't actually get done. ...
rker thread main loop.""" storage = self.__make_local() self.__run_forever(storage) def __make_local(self): """Create and initialize thread-local storage.""" storage = T.local() if self.__init_local is not None:
self.__init_local(storage) return storage def __run_forever(self, storage): """Grab the next task and run it.""" while True: task = self.__task_queue.get() self.__run_task(task, storage) self.__task_queue.task_done() def __run_task(self, task,...
nttdots/go-dots
config-helper/utils.py
Python
apache-2.0
492
0
# -*- coding: utf-8 -*- import yaml def getRows(cur, col, table): cur.execute("select %s from %s" % (col, table)) rows = [row[0] for row in cur] return rows def printYamlDump(d): try: print(yaml.dump(d, default_flow_style=False)) except yaml.YAMLError as err:
print(err) def fileYamlLoad(filename): with open(filename, 'r') as f: try:
a = yaml.load(f) except yaml.YAMLError as err: print(err) return a
taleinat/fuzzysearch
src/fuzzysearch/levenshtein_ngram.py
Python
mit
7,129
0.000982
from fuzzysearch.common import Match from fuzzysearch.compat import xrange from fuzzysearch.search_exact import search_exact __all__ = ['find_near_matches_levenshtein_ngrams'] def _expand(subsequence, sequence, max_l_dist): """Expand a partial match of a Levenstein search. An expansion must begin at the be...
after = subsequence[ngram_end:] start_index = max(0, ngram_start - max_l_dist) end_index = min(seq_len, seq_len - subseq_len + ngram_end + max_l_dist) for ind
ex in search_exact(subsequence[ngram_start:ngram_end], sequence, start_index, end_index): # try to expand left and/or right according to n_ngram dist_right, right_expand_size = _expand( subseq_after, sequence[index + ngram_len:index - ngram_start + subseq_len + ma...
ethdeveloper/ethdeveloper
blog/urls.py
Python
mit
329
0.006079
from django.conf.urls import include, url
from . import views urlpatterns = [ url(r'^$', views.BlogListView.as_view(), name="blog_list"),
url(r'^(?P<slug>[\w-]+)/$', views.BlogSingleView.as_view(), name="blog_single"), url(r'^category/(?P<slug>[\w-]+)/$', views.BlogCategoryView.as_view(), name="blog_category"), ]
openqt/algorithms
leetcode/python/lc996-number-of-squareful-arrays.py
Python
gpl-3.0
993
0.008056
# coding=utf-8 import unittest """996. Number of Squareful Arrays http
s://leetcode.com/problems/number-of-squareful-arrays/description/ Given an array `A` of non-negati
ve integers, the array is _squareful_ if for every pair of adjacent elements, their sum is a perfect square. Return the number of permutations of A that are squareful. Two permutations `A1` and `A2` differ if and only if there is some index `i` such that `A1[i] != A2[i]`. **Example 1:** **Input:** ...
Beeblio/wechat-python-sdk
setup.py
Python
bsd-2-clause
622
0.041391
# -*- coding: utf-8 -*- #!/usr/bin/env python from setuptools import setup, find_packages setup( name = 'wechat-python-sdk', version = '0.5.7', keywords = ('wechat', 'sdk', 'wechat sdk'), description = u'微信公众平台Python开发包', long_description = open("README.rst").read(), licen
se = 'BSD License', url = 'https://github.com/doraemonext/wechat-python-sdk', author = 'doraemonext', author_email = 'doraemonext@gma
il.com', packages = find_packages(), include_package_data = True, platforms = 'any', install_requires=open("requirements.txt").readlines(), )
DevHugo/zds-site
zds/member/api/tests.py
Python
gpl-3.0
52,616
0.003307
# coding: utf-8 from django.conf import settings from django.contrib.auth.models import User from django.core import mail from django.core.urlresolvers import reverse from oauth2_provider.models import Application, AccessToken from rest_framework import status from rest_framework.test import APITestCase from rest_fram...
ries import ProfileFactory, StaffProfileFactory, ProfileNotSyncFactory from zds.member.models import TokenRegister from rest_framework_extensions.settings import extensions_api_settings from django.core.cache import caches, get_cache class MemberListAPITest(APITestCase): def setUp(self): self.client = API...
""" Gets empty list of users in the database. """ response = self.client.get(reverse('api:member:list')) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response.data.get('count'), 0) self.assertEqual(response.data.get('results'), []) ...
GenericStudent/home-assistant
homeassistant/components/google_assistant/helpers.py
Python
apache-2.0
17,008
0.000353
"""Helper classes for Google Assistant integration.""" from abc import ABC, abstractmethod from asyncio import gather from collections.abc import Mapping import logging import pprint from typing import List, Optional from aiohttp.web import json_response from homeassistant.components import webhook from homeassistant...
_user(self, agent_user_id: str): """Add an synced and known agent_user_id. Called when a completed sync response have been sent to Google. """ self._store.add_agent_user_id(agent_user_id) async def async_disconnect_agent_user(self, agent_user_id: str): """Turn off report st...
ts their account from Google. """ self._store.pop_agent_user_id(agent_user_id) @callback def async_enable_local_sdk(self): """Enable the local SDK.""" webhook_id = self.local_sdk_webhook_id if webhook_id is None: return webhook.async_register( ...
wtsi-hgi/irobot
irobot/precache/__init__.py
Python
gpl-3.0
238
0
from irobot.precache._abc import AbstractDataObject, AbstractPrecache from iro
bot.precache._do import DataObject from irobot.precache._types import PrecacheFull, InProgress, InProgressWithETA from irobot.pre
cache.precache import Precache
Fedik/gramps
gramps/gui/editors/displaytabs/surnametab.py
Python
gpl-2.0
16,204
0.004258
# # Gramps - a GTK+/GNOME based genealogy program # # Copyright (C) 2000-2006 Donald N. Allingham # Copyright (C) 2010 Benny Malengier # # 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; ei...
art': self.on_edit_start, 'edited': self.on_edit_inline}, 1: {'edit_start': self.on_edit_start,
'edited': self.on_edit_inline}, 2: {'edit_start': self.on_edit_start, 'edited': self.on_edit_inline}} def get_data(self): return self.obj.get_surname_list() def is_empty(self): return len(self.model)==0 def _get_surn_from_model(self): """ ...
emofeedback/facedetection
tests/test_fd.py
Python
gpl-3.0
247
0.012146
import f
acedetect import cv2 def test_fd(): image = cv2.imread('abba.jpg') print image.shape FD = facedetect.FeatureDetect(image) FD.detectEyes() FD.detectFace() print FD.features if __name__ == '__main__': test
_fd()
jjhelmus/artview
tests/qt.py
Python
bsd-3-clause
1,431
0.004892
""" Test if Matplotlib is using PyQt4 as backend """ def test_matplotlib_qt_backend(): print ("testing matplotlib qt backend ...") try: # Matplot changed its file structure several times in history, so we # must test all try: from matplotlib.backends.qt_compat import QtCore...
L\n" + " Matplotlib is using %s\n" % using + " It must use %s\n" % expect + " Possible reasons for that are that " + "%s is not installed " % expect + "
or the envoriment variable QT_API is overwriting it.") return False except: import traceback print(traceback.format_exc()) print ("... Test fail is an expected way! We would like to know why, " "please report in 'https://github.com/nguy/artview/issues'") re...
HaroldMills/Vesper
vesper/mpg_ranch/nfc_coarse_classifier_3_1/classifier.py
Python
mit
14,590
0.00939
""" Module containing MPG Ranch NFC coarse classifier, version 3.1. An NFC coarse classifier classifies an unclassified clip as a `'Call'` if it appears to be a nocturnal flight call, or as a `'Noise'` otherwise. It does not classify a clip that has already been classified, whether manually or automatically. This cla...
None: # have classifier for this clip type num_clips_classified += self._annotate_clips(clips, clas
sifier) return num_clips_classified def _get_clip_lists(self, clips): """Gets a mapping from clip types to lists of clips to classify.""" clip_lists = defaultdict(list) for clip in clips: ...
liverbirdkte/searchlight
searchlight/api/v1/router.py
Python
apache-2.0
3,261
0
# Copyright 2014 Hewlett-Packard Development Company, L.P. # 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...
# 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 t...
t wsgi class API(wsgi.Router): """WSGI router for Searchlight v1 API requests.""" def __init__(self, mapper): reject_method_resource = wsgi.Resource(wsgi.RejectMethodController()) search_catalog_resource = search.create_resource() mapper.connect('/search', co...
Microsoft/PTVS
Python/Product/PythonTools/ptvsd/repl/ipython_client.py
Python
apache-2.0
15,596
0.00513
# Python Tools for Visual Studio # Copyright(c) Microsoft Corporation # All rights reserved. # # Licensed under the Apache License, Version 2.0 (the License); you may not use # this file except in compliance with the License. You may obtain a copy of the # License at http://www.apache.org/licenses/LICENSE-2.0 # # THI...
): self.handle_execute_output(content) def handle_execute_output(self, content): # called when an expression statement is printed, we treat # identical to stream output but it always goes to stdout output = content['data'] execution_count = content['execution_count'] ...
1), ' ' + ('.' * (len(str(execution_count + 1)) + 2)) + ': ', allow_multiple_statements=True ) self.write_data(output, execution_count) def write_data(self, data, execution_count = None): output_xaml = data.get('application/xaml+xml', None) if outp...
raghuraju/Simple-Project-Management
src/tasks/admin.py
Python
apache-2.0
223
0
# -*- coding: utf-8 -*- from __future__ import unicode_literals f
rom django.contrib import admin from .models import (Task, Epic, Project) admin.site.register(Task) admin.site.register(Epic) admin.site.register(Proje
ct)
Feneric/structspec
structspec/languages/c.py
Python
gpl-2.0
8,617
0
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Lang C: Support for the C language Provides everything needed to output files that support the binary format in the C programming language. """ from os.path import basename from zope.interface import moduleProvides from structspec.common import writeOut, writeOutBlock...
structure['size'][1:]) else: sizeLabel = structure['size'] try: sizeInBits = int(sizeLabel) except ValueError: sizeInBits = 0 if sizeInBits != typeSizes.get(typeName, -1):
line.append(' : {}'.format(sizeLabel)) if 'title' in structure: line.append(' /** {} */'.format(structure['title'])) line.append(';') writeOut(hFile, ''.join(line), ' ') writeOut(hFile, "}} {};".format(packetName)) writeOut(hFile, '') ...
amilcarsj/analytic
analytic/classify_all.py
Python
gpl-3.0
3,695
0.003518
import math import numpy as np from collections import defaultdict import json from sklearn.naive_bayes import MultinomialNB, GaussianNB, BernoulliNB from sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier from sklearn.linear_model import LogisticRegression from sklearn.neighbors import KNeighborsClassi...
in all_data_dict[tid_key]['properties']: # data_line.append(all_data_dict[tid_key]['properties'][feature]) for feature in all_data_traj_feats[tid_key]: data_line.append(all_data_traj_feats[tid_key][feature]) data_to_train_array.append(data_line) index += 1 possible...
{} numeric_label = 0 numeric_labels = [] for l in possible_labels: map_label_bin[l] = numeric_label numeric_label += 1 for l in provided_labels: numeric_labels.append(map_label_bin[l]) # print "numeric labels", numeric_labels #print "tids not labeled", [map_tid_to_inde...
radinformatics/som-tools
som/cli/search.py
Python
mit
3,872
0.005165
''' Copyright (c) 2017 Vanessa Sochat, All Rights Reserved Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge...
t except ImportError:
from urllib2 import urlopen, Request def summary(project): '''summarize counts of collections, images, entities for a project''' bot.spinner.start() requester = RetryRequester(project=project) collections = requester.get_collection() images = requester.get_image() entities = requester.get...
AnchorFree/python_example
example_code.py
Python
gpl-2.0
2,648
0.004154
#!/bin/python2.7 def add_scalar_to_list(my_scalar, my_list=[]): '''Given a scalar and a list, append the scalar to the list. If no list is provided, return a new list containing just the scalar value. ''' return my_list.append(my_scalar) extra_credit = 0 # DO NOT CHANGE ANYTHING BELOW THIS LINE # Te...
t(v, self
.input_list) self.assertListEqual(r, self.input_list.extend([mock.sentinel.a, mock.sentinel.b])) if __name__ == '__main__': unittest2.main()
CompassionCH/compassion-switzerland
child_sync_wp/models/project_compassion.py
Python
agpl-3.0
986
0
############################################################################## # # Copyright (C) 2016 Compassion CH (http://www.compassion.ch) # Releasing children from poverty in Jesus' name # @author: Emanuel Cino <ecino@compassion.ch> # # The licence is in the file __manifest__.py # #####################...
################################ from odoo import models from ..tools.wp_sync import WPSync class CompassionProject(models.Model): _inherit = "compassion.project
" def suspend_funds(self): """ Remove children from the website when FCP Suspension occurs. """ children = self.env["compassion.child"].search( [("project_id", "in", self.ids), ("state", "=", "I")] ) if children: wp_config = self.env["wordpress.configuration"...
vmalloc/mongomock
tests/diff.py
Python
bsd-3-clause
3,079
0.000974
import datetime import decimal from platform import python_version import re import uuid from six import integer_types, string_types, text_type try: from bson import decimal128, Regex _HAVE_PYMONGO = True except ImportError: _HAVE_PYMONGO = False class _NO_VALUE(object): pass # we don't use NOTHIN...
\ string_types + integer_types + (text_type, bytes, type, type(re.compile('')),) if _HAVE_PYMONGO: _SUPPORTED_TYPES = _SUPPORTED_BASE_TYPES + (decimal.Decimal, decimal128.Decimal128) else:
_SUPPORTED_TYPES = _SUPPORTED_BASE_TYPES if python_version() < '3.0': dict_type = dict else: from collections import abc dict_type = abc.Mapping def diff(a, b, path=None): path = _make_path(path) if isinstance(a, (list, tuple)) and isinstance(b, (list, tuple)): return _diff_sequences(...
followcat/predator
tools/mail.py
Python
lgpl-3.0
884
0.003394
import smtplib import email.mime.text mail_host = "" # "smtp.xxx.com" mail_user = "" # "xxx@xxx.com" mail_pass = "" # "xxx" mail_postfix = "" # "xxx.com" mailto_list = [""] # ["xxx@xxx.com"] def send_mail(to_list, sub, content): me = "hello"+"<"+mail_user+"@"+mail_postfix+">" msg = email.mim...
ext(content, _subtype='plain', _charset='gb2312') msg['Subject'] = sub msg['From
'] = me msg['To'] = ";".join(to_list) try: server = smtplib.SMTP() server.connect(mail_host) server.login(mail_user, mail_pass) server.sendmail(me, to_list, msg.as_string()) server.close() return True except Exception, e: print str(e) return Fa...
chris4795/u-boot-novena
tools/binman/entry_test.py
Python
gpl-2.0
873
0.001145
# # Copyright (c) 2016 Google, Inc # Written by Simon Glass <sjg@chromium.org> # # SPDX-License-Identifier: GPL-2.0+ # # Test for th
e Entry class import collections import unittest import entry class TestEntry(unittest.TestCase): def testEntryContents(self): """Test the Entry bass class""" base_entry = entry.Entry(None, None, None, read_node=
False) self.assertEqual(True, base_entry.ObtainContents()) def testUnknownEntry(self): """Test that unknown entry types are detected""" Node = collections.namedtuple('Node', ['name', 'path']) node = Node('invalid-name', 'invalid-path') with self.assertRaises(ValueError) as e...
elventear/psutil
test/_posix.py
Python
bsd-3-clause
5,491
0.002914
#!/usr/bin/env python # # $Id$ # import unittest import subprocess import time import sys import os import psutil from test_psutil import (get_test_subprocess, reap_children, PYTHON, LINUX, OSX, ignore_access_denied) def ps(cmd): """Expects a ps command with a -o argument and parse the...
cess([PYTHON, "-E", "-O"]).pid def tearDown(self): reap_children() def test_process_parent_pid(self): ppid_ps = ps("ps --no-headers -o ppid -p %s" %self.pid) ppid_psutil = psutil.Process(self.pid).ppid self.a
ssertEqual(ppid_ps, ppid_psutil) def test_process_uid(self): uid_ps = ps("ps --no-headers -o uid -p %s" %self.pid) uid_psutil = psutil.Process(self.pid).uids.real self.assertEqual(uid_ps, uid_psutil) def test_process_gid(self): gid_ps = ps("ps --no-headers -o rgid -p %s" %self....
drmpeg/gr-ule
python/bindings/bind_oot_file.py
Python
gpl-3.0
2,100
0.004286
import warnings import argparse import os from gnuradio.bindtool import BindingGenerator import pathlib import sys import tempfile parser = argparse.ArgumentParser(description='Bind a GR Out of Tree Block') parser.add_argument('--module', type=str, help='Name of gr module containing file to bind (e...
ndingGenerator(prefix, namespace, prefix_include_root, output_dir, define_symbols=defines, addl_includes=includes, catch_exceptions=False, write_json_output=False, st
atus_output=args.status, flag_automatic=True if args.flag_automatic.lower() in [ '1', 'true'] else False, flag_pygccxml=True if args.flag_pygccxml.lower() in ['1', 'true'] else False) bg.gen_file_binding(args.filename)
invisiblek/python-for-android
python3-alpha/python3-src/Lib/test/test_codeop.py
Python
apache-2.0
7,630
0.006946
""" Test cases for codeop.py Nick Mathewson """ import unittest from test.support import run_unittest, is_jython from codeop import compile_command, PyCF_DONT_IMPLY_DEDENT import io if is_jython: import sys def unify_callables(d): for n,v in d.items(): if hasattr(v, '__call__'): ...
ef x():\n pass") ai("a = 9+ \\") ai("a = 'a\\") ai("a = '''xy") ai("","eval") ai("\n","eval") ai("(","eval") ai("(\n\n\n","eval") ai("(9+","eval") ai("9+ \\","eval") ai("lambda z: \\","eval") ai("if True:\n if True:\n if True: ...
c") ai("@a(b,c,") ai("from a import (") ai("from a import (b") ai("from a import (b,") ai("from a import (b,c") ai("from a import (b,c,") ai("["); ai("[a"); ai("[a,"); ai("[a,b"); ai("[a,b,"); ai("{"); ai("{a"); ...
jonykalavera/django-tastypie-batch
example/manage.py
Python
mit
418
0
#!/usr/bin/env python import os import sys from importlib import import_module if __name__ == "__main__": settings_module
= "example.settings" os.environ.setdefault("DJANGO_SETTINGS_MODULE", settings_module) sys.path.insert( 0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
chili-epfl/pyrobots
src/robots/introspection.py
Python
isc
885
0.00791
# coding=utf-8 import logging; logger =
logging.getLogger("robots.introspection") import threading introspection = None # disable introspection for now if False: try: import Pyro4 import Pyro4.errors uri = "PYRONAME:robots.introspection" # uses name server try: introspection = Pyro4.Proxy(uri) int...
process logger.info("Connection to the introspection server established.") except Pyro4.errors.CommunicationError: logger.warning("Introspection server not running. No introspection.") introspection = None except Pyro4.errors.NamingError: logger.warning("I...
msimacek/freeipa
ipaserver/install/ldapupdate.py
Python
gpl-3.0
33,389
0.001168
# Authors: Rob Crittenden <rcritten@redhat.com> # # Copyright (C) 2008 Red Hat # see file 'COPYING' for use and warranty information # # 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 ver...
to be exhaustive given the limited scope of types of values that the updater manages. This only supports lists, tuples and strings. If you pass a dict you may get a string back. """ sensitive_attributes = ['krbmkey', 'userpassword', 'passwordhistory', 'krb
principalkey', 'sambalmpassword', 'sambantpassword', 'ipanthash'] if attr.lower() in sensitive_attributes: if type(values) in (tuple, list): # try to still look a little like what is in LDAP return ['XXXXXXX'] * len(values) else: return 'XXXXXXXX' if values ...
DMS-Aus/Roam
src/roam/listmodulesdialog.py
Python
gpl-2.0
7,739
0.000905
import os from qgis.PyQt.QtCore import pyqtSignal, QSize, Qt from qgis.PyQt.QtGui import QPixmap from qgis.PyQt.QtWidgets import QListWidgetItem, QWidget import roam.api import roam.api.utils import roam.project import roam.updater import roam.utils from roam.ui.ui_listmodules import Ui_ListModules from roam.ui.ui_pr...
def show_close(self, showclose): self.closeProjectButton.setVisible(showclose) def request_update(self): if self.is_new: self.install_project.emit(self.serverinfo) else: self.update_project.emit(self.serverinfo) class ProjectsWidget(Ui_ListModules, QWidget): r...
: super(ProjectsWidget, self).__init__(parent) self.setupUi(self) roam.api.utils.install_touch_scroll(self.moduleList) self.serverurl = None self.moduleList.itemClicked.connect(self.openProject) self.projectitems = {} self.project_base = None self.progres...
Callek/build-relengapi
relengapi/blueprints/tokenauth/tables.py
Python
mpl-2.0
1,677
0.001789
# 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/. import sqlalchemy as sa from relengapi.blueprints.tokenauth import types from relengapi.lib import db from relengapi.li...
) for permissionstr in self._permissions.split(',')] # silentl
y ignore any nonexistent permissions; this allows us to remove unused # permissions without causing tokens permitting those permissions to fail # completely return [a for a in token_permissions if a]
jelly/Utils
unassignedbugs.py
Python
gpl-3.0
2,592
0.015046
#!/usr/bin/env python2 import urllib2 import urllib from BeautifulSoup import BeautifulSoup import smtplib import ConfigParser # Retreive user information config = ConfigParser.ConfigParser() config.read('config.cfg') user = config.get('data','user') password = config.get('data','password') fromaddr = config.get('dat...
\n\n' # build opener with HTTPCookieProcessor o = urllib2.build_opener( urllib2.HTTPCookieProcessor() ) urllib2.install_opener( o ) p = urllib.urlencode( { 'user_name': user, 'password': password, 'remember_login' : 'on',} ) f = o.open(login_page, p) data = f.read() # Archlinux url = "https://bugs.archlinux.org/in...
ri%5B%5D=&due%5B%5D=0&reported%5B%5D=&cat%5B%5D=&status%5B%5D=1&percent%5B%5D=&opened=&dev=&closed=&duedatefrom=&duedateto=&changedfrom=&changedto=&openedfrom=&openedto=&closedfrom=&closedto=&do=index" # Community url2= "https://bugs.archlinux.org/index.php?string=&project=5&search_name=&type%5B%5D=&sev%5B%5D=&pri%5B%...
ygol/odoo
addons/im_livechat_mail_bot/__manifest__.py
Python
agpl-3.0
449
0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing detail
s. { 'name': 'OdooBot for livechat', 'version': '1.0', 'category': 'Productivity/Discuss', 'summary': 'Add livechat support for OdooBot', 'description': "", 'website': 'https://www.odoo.com/page/discuss', 'depends': ['mail_bot', 'im_livechat'],
'installable': True, 'application': False, 'auto_install': True, }
theyosh/TerrariumPI
hardware/sensor/__init__.py
Python
gpl-3.0
18,830
0.016888
# -*- coding: utf-8 -*- import terrariumLogging logger = terrariumLogging.logging.getLogger(__name__) from pathlib import Path import inspect from importlib import import_module import sys import statistics from hashlib import md5 from time import time, sleep from operator import itemgetter from func_timeout import fu...
'power_mngt' : None, 'erratic_errors' : 0, 'last_update' : 0, 'value' : None} self._sensor_cache = terrariumCache() self.__unit_value_callback = unit_value_callback self.__trigger_callback = trigger_callback # S...
when not set self.load_hardware() # REMINDER: We do not take a measurement at this point. That is up to the developer to explicit request an update. def __power_management(self, on): # Some kind of 'power management' with the last gpio pin number :) https://raspberrypi.stackexchange.com/questions/68123/p...
Julian/home-assistant
homeassistant/components/zwave.py
Python
mit
16,822
0
""" Support for Z-Wave. For more details about this component, please refer to the documentation at https://home-assistant.io/components/zwave/ """ import logging import os.path import time from pprint import pprint from homeassistant.const import ( ATTR_BATTERY_LEVEL, ATTR_ENTITY_ID, ATTR_LOCATION, CONF_CUST...
for key in dir(obj) if key[0] != '_' and not hasattr(getattr(obj, key), '__call__')} def _node_name(node): """Return the name of the node.""" return node.name or "{} {}".format( node.manufacturer_name, node.product_name) def _value_name(value): """Return the name of the v...
ject_id contains node_id and value instance id to not collide with other entity_ids. """ object_id = "{}_{}".format(slugify(_value_name(value)), value.node.node_id) # Add the instance id if there is more than one instance for the value if value.instance > 1: r...
pixelated-project/pixelated-user-agent
service/pixelated/resources/mails_resource.py
Python
agpl-3.0
8,824
0.001927
# # Copyright (c) 2015 ThoughtWorks, Inc. # # Pixelated is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Pixelated is distrib...
n_deferred({'message': str(error.value)}, request, status_code=503) else: log.error('error occurred while sending: %s' % error.getErrorMessage())
respond_json_deferred({'message': 'an error occurred while sending'}, request, status_code=422) deferred = self._handle_post(request) deferred.addErrback(onError) return server.NOT_DONE_YET def render_PUT(self, request): def onError(error): log.error('error saving...
awd4/spnss
datasets/loaders.py
Python
mit
1,541
0.00584
import os import numpy as np import creators from utils import schema_split_helper BASE_DIR = os.path.dirname( os.path.realpath(__file__) ) ''' Load datasets from disk. ''' def load_gd(name, schema=False, split=False): GDIR = os.path.join(BASE_DIR, 'gens.domingos/') trn = np.loadtxt(GDIR+name+'.ts.data',...
ssert trn.ndim == vld.ndim == tst.ndim == 2 n1, n2, n3 = len(trn), len(vld), len(tst) n = n1 + n2 + n3 m = trn.shape[1] data = np.zeros((n,m)) data[:n1,:] = trn data[n1:n1+n2,:] = vld data[n1+n2:,:] = tst return schema_split_helper(data, schema, split, n1, n2, [2]*m) def load
_mnperm(n, schema=False, split=False): assert 2 <= n <= 12 filename = os.path.join(BASE_DIR, 'permanent/mnperm.%.2d.npy'%n) try: data = np.load(filename) except IOError, e: data = creators.create_mnperm(n) np.save(filename, data) m1 = max(1, int(round(data.shape[0]/1.3))) ...
vyos-legacy/vyconfd
vyconf/tests/integration/reference_tree/test_tree_loader.py
Python
lgpl-2.1
3,032
0.00033
#!/usr/bin/env python # # reference_node_loader.py: unit tests for # vyconf.tree.referencetree.ReferenceTreeLoader # Copyright (C) 2014 VyOS Development Group <maintainers@vyos.net> # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General ...
lid_interface_definition(self): with testtools.ExpectedException(reftree.ReferenceTreeLoaderError): self.get_loader( 'interface_definition_invalid.xml', {"mock": MockType}, 'schemas/interface_definition.rng') def test_duplicate_node(self): ...
MockType}, 'schemas/interface_definition.rng') t = reftree.ReferenceNode("root") l.load(t) l.load(t)
okroener/autokey
src/lib/gtkui/notifier.py
Python
gpl-3.0
12,947
0.007492
# -*- coding: utf-8 -*- # Copyright (C) 2011 Chris Dekter # # 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 pr...
) def notify_error(self, message): self.sho
w_notify(message, Gtk.STOCK_DIALOG_ERROR) self.errorItem = Gtk.MenuItem(_("View script error")) self.errorItem.connect("activate", self.on_show_error) self.icon.set_from_icon_name(common.ICON_FILE_NOTIFICATION_ERROR) def on_show_error(self, widget, data=None): self.app.show_...
geofrenzy/utm-mbsb
beacon/dkbeacon.py
Python
apache-2.0
5,335
0.002624
from dronekit import connect import time import argparse import pprint import rospy import copy from gf_beacon.srv import * import hostapd import beaconencoder import findap class sample_beacon_data: def __init__(self, connect_string): print "init" self.missing_AP = False try: ...
mylevel = 100 self.beacon_dict["battery_level"] = mylevel elif att
r_name == "location.global_relative_frame": vardict = vars(value) self.beacon_dict["lng_deg"] = float(vardict["lon"]) self.beacon_dict["lat_deg"] = float(vardict["lat"]) self.beacon_dict["alt_agl_m"] = float(vardict["alt"]) else: print attr_name, " : "...
nicopace/procesado_kmz_cole
pcontrol_reader.py
Python
gpl-3.0
1,070
0.008411
from zipfile import ZipFile import codecs from pykml import parser def extraer_info_punto(punto): datos = { 'coordinates': punto.Point.coordinates } fo
r dato in punto.ExtendedData.Data: name = dato.values()[0] value = dato.value datos[name] = value return datos def recuperar_puntos(coche): return map(extraer_info_punto, coche.Placemark) def pcontrol_read(filename): kmz = ZipFile(filename, 'r'
) files = kmz.namelist() # there must be just one file kmltext = kmz.open(files[0], 'r').read().decode('iso-8859-1') kmltext = kmltext.replace(' encoding="UTF-8"', '') k = parser.fromstring(kmltext) compania = k.Document.Folder[0] compania_nombre = compania.name coche = compania.Fold...
ColumbiaCMB/kid_readout
apps/data_taking_scripts/2017-10-jpllfn1/sweep_and_stream_attens.py
Python
bsd-2-clause
2,500
0.012
from kid_readout.interactive import * import time #setup = hardware.Hardware() ri = Roach2Baseband() ri.set_modulation_output('high') initial_f0s = np.load('/data/readout/resonances/2017-10-JPL-LF-N1.npy')/1e6 nf = len(initial_f0s) atonce = 128 if nf % atonce > 0: print "extending list of resonators to make a ...
les=nsamp, length_seconds=0, verbose=True, ) ncf.write(swpa) current_f0s = [] for sidx in range(initial_f0s.shape[0]): swp = swpa.sweep(sidx) res = swp.resonator print res.f_0, res.Q, res.current_result.redchi, (initial_f0...
0e3: current_f0s.append(initial_f0s[sidx]*1e6) print "using original frequency for ",initial_f0s[sidx] else: current_f0s.append(res.f_0) print "fits complete", (time.time()-tic)/60. current_f0s = np.array(current_f0s)/1e6 current_f0s.sort() if np.any(np.diff(c...
moyogo/robofontmechanic
src/lib/mechanic/ui/tabs/install.py
Python
mit
3,390
0.000295
from vanilla import * from mechanic.threaded import ThreadedObject from mechanic.extension import Extension from mechanic.registry import Registry from mechanic.ui import progress from mechanic.ui.tabs.base import BaseTab from mechanic.ui.lists.installation import InstallationList class InstallTab(BaseTab, ThreadedO...
stall_button) except Registry.ConnectionError: self.disable("Couldn't connect to the registry server...") def disable(self, *args, **kwargs): self.list.enable(False) super(InstallTab, self).disable(*args, **kwargs) def enable(self, *args, **kwargs): self.list.enable...
elf.update_uninstall_button_label() def update_uninstall_button_label(self, sender=None): self.uninstall_button.enable(len(self.uninstallable) > 0) def update_install_button_label(self, sender=None): selections = self.list.getSelection() self.install_button.enable(selections) i...
gmr/tredis
tredis/client.py
Python
bsd-3-clause
25,877
0.000039
""" Cluster Supporting Redis Client """ import collections import logging import hiredis from tornado import concurrent from tornado import ioloop from tornado import locks from tornado import iostream from tornado import tcpclient from tredis import common from tredis import crc16 from tredis import exceptions from...
LOGGER.error('Redis connection closed') self.connected = False self._on_close() self._stream = None def _on_connected(self, stream_future, connect_future): """Invoked when the socket stream has connected, setting up the stream callbacks and invoking the on connect callback...
future :type stream_future: :class:`~tornado.concurrent.Future` :param stream_future: The connection response future :type stream_future: :class:`~tornado.concurrent.Future` :raises: :exc:`tredis.exceptions.ConnectError` """ if stream_future.exception(): con...
harshilasu/GraphicMelon
y/google-cloud-sdk/platform/gsutil/third_party/boto/boto/ec2/elb/listelement.py
Python
gpl-3.0
1,512
0
# Copyright (c) 2006-2012 Mitch Garnaat http://garnaat.org/ # Copyright (c) 2012 Amazon.com, Inc. or its affiliates. # All Rights Reserved # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software wi...
and to permit # persons to whom the Software is furnished to do so, subject to the fol- # lowing conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE
IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL- # ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT # SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, # WHETHER IN AN ACTION OF CONTRACT, TORT...
Wintellect/WintellectWebinars
2019-06-06-ten-tips-python-web-devs-kennedy/code/top_10_web_explore/ex07_viewmodels/pypi_vm/views/home_view.py
Python
apache-2.0
359
0
import flask from pypi_vm.infrastructure.view_modifiers import response from pypi_vm.viewmodels.home.home_index_viewmodel import HomeIndexViewModel blueprint = flask.Blueprint('home', __name__, template_folder='templates') @blueprint.route('/') @response(template_file='home/index.html') def index(): vm = HomeIn...
ct()
precice/elastictube1d
fluid-python/tubePlotting.py
Python
gpl-3.0
1,595
0.009404
import matplotlib.pyplot as plt from matplotlib.patches import Rectangle import numpy as np scaling_factor = 50 r0 = 1/np.sqrt(np.pi) def plotTube(ax, crossSection, velocity, pressure, dx, t): radius0 = np.sqrt(crossSection/np.pi) N = velocity.shape[0] u0 = 10 ampl = 3 ax.plot(np.arange(N) * d...
aling_factor), 'k') iii = 0 rects = [] map = plt.get_cmap('RdBu') for x in np.arange(N)*dx: dy = (r0 + (radius0[iii] - r0) * scaling_factor) rect = Rectangle((x-.5*dx,-dy), dx, 2 * dy, color=map((velocity[iii] + u0) / ampl)) ax.add_patch(rect) iii += 1 rects.appen...
#plt.imshow(np.vstack((velocity,velocity)),origin="upper") ax.set_ylim([-2,2]) def plotVar(ax, crossSection, dx, t): radius0 = np.sqrt(crossSection/np.pi) radius_mean = np.mean(np.sqrt(crossSection/np.pi)) N = crossSection.shape[0] plt.plot(np.arange(N) * dx, (radius_mean-radius0)*scaling_fac...
c3cashdesk/c6sh
src/postix/backoffice/report.py
Python
agpl-3.0
15,278
0.000852
import json from io import BytesIO from tempfile import TemporaryFile import qrcode from django.core.files.base import ContentFile from django.core.files.storage import default_storage from django.utils import timezone from reportlab.lib import colors from reportlab.lib.units import mm from reportlab.platypus import P...
'', '', '', CURRENCY.format(sum([p['value_total'] for p in sales_raw_data])), ] ] last_row = len(data) - 1 sales = Table( data=data, colWidths=[120] + [(doc.width - 120) / 5] * 5, style=Table
Style( [ ('FONTSIZE', (0, 0), (5, last_row), FONTSIZE), # TODO: register bold font and use here: ('FACE', (0,0), (3,0), 'boldfontname'), ('ALIGN', (0, 0), (0, last_row), 'LEFT'), ('ALIGN', (1, 0), (5, last_row), 'RIGHT'), ('LINE...
googlei18n/nototools
nototools/summary.py
Python
apache-2.0
5,034
0.001788
#!/usr/bin/env python # # Copyright 2014 Google Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless require...
else: version = noto_lint.printable_font_revision(font) # default 2 num_glyphs = len(font.getGlyphOrder()) full_name = font_data.get_name_records(font)[4] cmap = set(get_largest_cmap(font).keys()) # copy needed? what's the lifespan? num_chars =
len(cmap) font.close() return relpath, version, full_name, size, num_glyphs, num_chars, cmap, table_info def summarize(root, name=None): result = [] name_re = re.compile(name) if name else None for parent, _, files in os.walk(root): for f in sorted(files): if f.endswith(".ttf"...
mekarpeles/iiify
niiifty/configs/__init__.py
Python
gpl-3.0
1,589
0.000629
#!/usr/bin/env python # -*-coding: utf-8 -*- """ __init__.py ~~~~~~~~~~~ Configurations for iiify :copyright: (c) 2015 by AUTHORS :license: see LICENSE for more details """ import os import types import configparser path = os.path.dirname(os.path.realpath(__file__)) approot = os.path.abspath(os....
'debug': DEBUG, 'host': HOST, 'port': PORT} if CRT and KEY: options['ssl_context'] = (CRT, KEY) # Enable CORS to allow cross-domain loading of tilesets from this server # Especially useful for SeaDragon viewers running locally cors = bool(int(config.getdef('server', 'cors', 0))) media_root = config.getdef('media'...
= os.path.join(approot, media_root) if not os.path.exists(media_root): os.makedirs(media_root) cache_root = config.getdef('cache', 'root', 'cache') if not os.path.isabs(cache_root): cache = os.path.join(approot, cache_root) if not os.path.exists(cache_root): os.makedirs(cache_root) cache_expr = config.get...