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
SillyFreak/django-graphene-jwt
graphene_jwt/settings.py
Python
agpl-3.0
629
0.00318
from django.core.exceptions import ImproperlyConfigured from django.conf import settings from rest_framework.setti
ngs import APISettings USER_SETTINGS = getattr(settings, 'JWT_GRAPHENE', None) DEFAULTS = { 'JWT_GRAPHENE_USER_ONLY_FIELDS': None, 'JWT_GRAPHENE_USER_EXCLUDE_FIELDS': None, } IMPORT_STRINGS = ( ) api_settings = APISettings(USER_SETTINGS, DEFAULTS, IMPORT_STRINGS) if api_settings.JWT_GRAPHENE_USER_ONLY_FIE...
PHENE_USER_ONLY_FIELDS and JWT_GRAPHENE_USER_EXCLUDE_FIELDS")
lfcnassif/MultiContentViewer
release/modules/ext/libreoffice/program/python-core-3.3.0/lib/_osx_support.py
Python
lgpl-3.0
18,472
0.001462
"""Shared OS X support functions.""" import os import re import sys __all__ = [ 'compiler_fixup', 'customize_config_vars', 'customize_compiler', 'get_platform_osx', ] # configuration variables that may contain universal build flags, # like "-arch" or "-isdkroot", that may need customization for # the...
ils is used to build standard library # extensions). global _SYSTEM_VERSION if _SYSTEM_VERSION is None:
_SYSTEM_VERSION = '' try: f = open('/System/Library/CoreServices/SystemVersion.plist') except IOError: # We're on a plain darwin box, fall back to the default # behaviour. pass else: try: m = re.search(r'<key>ProductU...
gems-uff/noworkflow
capture/noworkflow/resources/demo/2016_ipaw_paper/step4/convert.py
Python
mit
449
0.002227
# Dummy calls for
representing openings def pgmtoppm(atlas_slice): result = atlas_slice[:-3] + "ppm" with open(atlas_slice, "rb") as aslice, \ open(result, "w") as gif: gif.write(atlas_slice + ".ppm") return result def pnmtojpeg(ppm_slice): result = ppm_slice[:-3] + "jpg" with open(ppm_slice, "r...
slice + ".jpg") return result
pavelchristof/gomoku-ai
tensorflow/python/debug/lib/grpc_debug_server.py
Python
apache-2.0
16,574
0.004827
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
r in its summary.value[0] field. Args: event: The Event proto from the stream to be processed. """ raise NotImplementedError( "on_value_event() is not implemented in the base servicer class") class EventListenerBaseServicer(d
ebug_service_pb2_grpc.EventListenerServicer): """Base Python class for gRPC debug server.""" def __init__(self, server_port, stream_handler_class): """Constructor. Args: server_port: (int) Port number to bind to. stream_handler_class: A class of the base class `EventListenerBaseStreamH...
ianmiell/shutit-distro
less/less.py
Python
gpl-2.0
877
0.039909
"""ShutIt module. See http://shutit.tk """ from shutit_module import ShutItModule class less(ShutItModule): def build(self, shutit): shutit.send('mkdir -p /tmp/build/less') shutit.send('cd /tmp/build/l
ess') shutit.send('wget -qO- http://www.greenwoodsoftware.com/less/less-458.tar.gz | tar -zxf -') shutit.send('cd less*') shuti
t.send('./configure --prefix=/usr --sysconfdir=/etc') shutit.send('make') shutit.send('make install') return True #def get_config(self, shutit): # shutit.get_config(self.module_id,'item','default') # return True def finalize(self, shutit): shutit.send('rm -rf /tmp/build/less') return True #def remove(...
christianurich/VIBe2UrbanSim
3rdparty/opus/src/psrc_parcel/opus_package_info.py
Python
gpl-2.0
318
0.009434
# Opus/UrbanSim urban simulation software. # Copyright (C) 2005-2009 University of W
ashington # See opus_core/LICENSE from opus_core.opus_package import OpusPackage
class package(OpusPackage): name = 'psrc_parcel' required_opus_packages = ["opus_core", "opus_emme2", "urbansim", "urbansim_parcel"]
metocean/tugboat-py
setup.py
Python
apache-2.0
1,239
0.003228
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import unicode_literals from __future__ import absol
ute_import from setuptools import setup, find_packages import codecs import os import re import sys def read(*parts): path = os.path.join(os.path.dirname(__file__), *parts) with codecs.open(path, encoding='utf-8') as fobj: return fobj.read() def find_version(*file_paths): version_file = read(*file...
(r"^__version__ = ['\"]([^'\"]*)['\"]", version_file, re.M) if version_match: return version_match.group(1) raise RuntimeError("Unable to find version string.") install_requires = [ 'docker-compose >= 1.6.0, < 1.8' ] setup( name='tug', version=find_version("tug", "__init__.py"), descri...
jk977/twitch-plays
bot/chat/twitchchat.py
Python
gpl-3.0
4,289
0.002098
import re import socket import threading import time from chat.message import Message from chat.user import User from interfaces.chat import Chat class TwitchChat(Chat): host = 'irc.twitch.tv' port = 6667 rate = 1.5 def __init__(self, username, passwd, channel): ''' Creates IRC clien...
d.') else: return raw_message def _parse_message(raw_message): ''' Parses raw message from server and returns a Message object. :param raw_message: UTF-8 encoded message from server. ''' result = re.search('^:(\\w+)!\\w+@[\\w.]+ [A-Z]+ #\\w+ :(.+)...
result.groups() author = User(author) return Message(author, content) def send_message(self, content, max_attempts=2): ''' Sends message to server and sleeps. :param content: The message to send. :param max_attempts: The maximum number of failed attempts to allow wh...
Teamxrtc/webrtc-streaming-node
third_party/webrtc/src/chromium/src/third_party/markdown/odict.py
Python
mit
7,934
0.001008
# markdown is released under the BSD license # Copyright 2007, 2008 The Python Markdown Project (v. 1.7 and later) # Copyright 2004, 2005, 2006 Yuri Takhteyev (v. 0.2-1.6b) # Copyright 2004 Manfred Stienstra (the original version) # # All rights reserved. # # Redistribution and use in source and binary forms, with or...
if key not in self: self.keyOrder.append(key) # But override with last value in data (dict() does this) super_set(key, value) def __deepcopy__(self, memo): return self.__class__([(key, deepcopy(value, memo)) for key,...
jplevyak/pyc
tests/t39.py
Python
bsd-3-clause
42
0
a = "hel
lo" a += " " a += "world" print a
hgpestana/chronos
apps/task/forms.py
Python
mit
630
0.025397
from django.forms import ModelForm, Mo
delChoiceField from django.utils.translation import ugettext_lazy as _ from apps.task.models import Task class FormChoiceField(ModelChoiceField): def label_from_instance(self, obj): return obj.name class TaskForm(ModelForm): """ Task form used to add or update a task in the Chronos platform. TODO: Develop th...
d( queryset=Task.objects.all().order_by('name'), empty_label=_('Please select an option'), required=False, ) class Meta: model = Task fields = ['name', 'description', 'comments', 'price', 'parenttask', 'is_visible']
google-research/heatnet
test/test_processing.py
Python
gpl-3.0
9,568
0.010033
"""Tests for functions and classes in data/processing.py.""" import glob import os from absl.testing import absltest import heatnet.data.processing as hdp import heatnet.file_util as file_util import heatnet.test.test_util as test_util import numpy as np import xarray as xr class CDSPreprocessorTest(absltest.TestCas...
hdp.CDSPreprocessor(data_paths, base_out_path=proc_path, mode='ext') self.assertEqual(pp.raw_files, data_paths) self.assertEqual(pp.base_out_path, proc_path)
self.assertEqual(pp.lead_times, [1]) self.assertEqual(pp.past_times, [0]) pp.close() pp = hdp.CDSPreprocessor( data_paths[0], base_out_path=proc_path, mode='ext') self.assertEqual(pp.raw_files, data_paths[0]) self.assertEqual(pp.base_out_path, proc_path) self.assertEqual...
xenserver/transfervm
transfertests/getrecord_test.py
Python
gpl-2.0
6,109
0.00442
import base64 import httplib import logging import unittest import testsetup import transferclient import moreasserts def clean_up(): hostname = testsetup.HOST testsetup.clean_host(hostname) class GetRecordTest(unittest.TestCase): def assertRecordFields(self, record, fields): for field in field...
moreasserts.assertRaisesXenapiFailure(self, 'ArgumentError', transferclient.get_record, hostname) clean_up() def testG
etRecordRaisesVDINotFoundIfThereIsNoSuchVDIOnTheHost(self): hostname, network, vdi = testsetup.setup_host_and_network(templates=1, vdi_mb=10) invalidvdi = vdi[:-6] + 'abcdef' moreasserts.assertRaisesXenapiFailure(self, 'VDINotFound', transferclient.get_record, ...
wglass/zoonado
zoonado/protocol/children.py
Python
apache-2.0
746
0
from __future__ import unicode_literals from .request import Request from .response import Response from .stat import Stat from .primitives import Bool, UString, Vector class GetChildrenRequest(Request): """ """ opcode = 8 parts = ( ("path", UString), ("watch", Bool), ) class G...
("watch", Bool), ) class GetChildren2Response(Response): """ """ opcode = 12 parts = ( ("children", Vector.of(UString)), ("stat", Stat), )
muhummadPatel/raspied
students/migrations/0002_add_Booking_model.py
Python
mit
923
0.002167
# -*- coding: utf-8 -*- # Generated by Django 1.9.7 on 2016-09-06 17:16 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependen...
model'), ] operations = [ migrations.CreateModel( name='Booking', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('start_time', models.DateTimeField()), ('end_time', mode...
ttings.AUTH_USER_MODEL)), ], ), ]
cbonoz/codehealth
dependencies/baron/render.py
Python
mit
34,151
0.000439
import sys def render(node, strict=False): """Recipe to render a given FST node. The FST is composed of branch nodes which are either lists or dicts and of leaf nodes which are strings. Branch nodes can have other list, dict or leaf nodes as childs. To render a string, simply output it. To rende...
("formatting", "formatting", "formatting"), ("string", "value", True), ], "ternary_operator": [ ("key", "first", True), ("formatting", "first_formatting", True), ("constant", "if", True), ("...
True), ("key", "value", True), ("formatting", "third_formatting", True), ("constant", "else", True), ("formatting", "fourth_formatting", True), ("key", "second", True), ], "ellipsis": [ ...
anhstudios/swganh
data/scripts/templates/object/draft_schematic/vehicle/component/shared_structural_reinforcement_heavy.py
Python
mit
477
0.046122
#### NOTICE: THIS FILE IS
AUTOGENERATED #### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY #### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES from swgpy.object import * def create(kernel): result = Intangible() result.template = "object/draft_schematic/vehicle/component/shared_structural_reinforcement_heavy.iff" result.attribute_templ...
S #### #### END MODIFICATIONS #### return result
blabla1337/defdev
demos/input-validation/SQLI/config/initializer.py
Python
gpl-3.0
1,100
0.012727
#!/usr/bin/python # -*- coding: utf-8 -*- import sqlite3 as lite import
sys con = lite.connect('Database.db') with con: cur = con.cursor() #Create data for the user table cur.execute("CREATE TABLE users(UserId INT, UserName TEXT, Password TEXT)") cur.execute("INSERT INTO users VALUES(1,'Admin','0cef1fb10f60529028a71f58e54
ed07b')") cur.execute("INSERT INTO users VALUES(2,'User','022b5ac7ea72a5ee3bfc6b3eb461f2fc')") cur.execute("INSERT INTO users VALUES(3,'Guest','94ca112be7fc3f3934c45c6809875168')") cur.execute("INSERT INTO users VALUES(4,'Plebian','0cbdc7572ff7d07cc6807a5b102a3b93')") #Create some data for pageinfo...
MarkWh1te/xueqiu_predict
python3_env/lib/python3.4/site-packages/sqlalchemy/engine/__init__.py
Python
mit
18,857
0.000159
# engine/__init__.py # Copyright (C) 2005-2016 the SQLAlchemy authors and contributors # <see AUTHORS file> # # This module is part of SQLAlchemy and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php """SQL connections, SQL execution and high-level DB-API interface. The engine pa...
ize ) from . import util, strategies # backwards compat from ..sql import ddl default_strategy = 'plain' def create_engine(*args, **kwargs): """Create a new :class:`.Engine` instance. The standard calling form is to send the URL as the first positional argument, usually a string that indica
tes database dialect and connection arguments:: engine = create_engine("postgresql://scott:tiger@localhost/test") Additional keyword arguments may then follow it which establish various options on the resulting :class:`.Engine` and its underlying :class:`.Dialect` and :class:`.Pool` construct...
mchung94/latest-versions
versions/software/sevenzip.py
Python
mit
718
0
import re from versions.software.utils import get_command_stdout, get_soup, \ get_text_between def name(): """Return the preci
se name for the software.""" return '7-Zip' def installed_version(): """Return the installed version of 7-Zip, or None if not installed.""" try: version_string = get_command_stdout('7z') return version_string.s
plit()[1] except FileNotFoundError: pass def latest_version(): """Return the latest version of 7-Zip available for download.""" soup = get_soup('http://www.7-zip.org/') if soup: tag = soup.find('b', string=re.compile('^Download')) if tag: return tag.text.split()[2] ...
JoshuaRLi/notquite
notquite/constants.py
Python
mit
2,903
0.000344
# -*- coding: UTF-8 -*- HMAP = { ' ': u'\u00A0\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F', '!': u'\uFF01\u01C3\u2D51\uFE15\uFE57', '"': u'\uFF02', '#': u'\uFF03\uFE5F', '$': u'\uFF04\uFE69', '%': u'\uFF05\u066A\u2052\uFE6A', '&': u'\uFF06\uFE60', "'":...
u'\u13EE', '7': u'', '8': u'', '9': u'\u13ED', ':': u'\uFF1A\u02D0\u02F8\u0589\u1361\u16EC\u205A\u2236\u2806\uFE13\uFE55', ';': u'\uFF1B\u037E\uFE14\uFE54', '<': u'\uFF1C\u02C2\u2039\u227A\u276E\u2D66\uFE64', '=': u'\uFF1D\u2550\u268C\uFE66', '>': u'\uFF1E\u02C3\u203A\u227B\u276F\uFE65'...
u03F9\u0421\u13DF\u216D\u2CA4', 'D': u'\u13A0\u15EA\u216E', 'E': u'\u0395\u0415\u13AC', 'F': u'\u15B4', 'G': u'\u050C\u13C0', 'H': u'\u0397\u041D\u12D8\u13BB\u157C\u2C8E', 'I': u'\u0399\u0406\u2160', 'J': u'\u0408\u13AB\u148D', 'K': u'\u039A\u13E6\u16D5\u212A\u2C94', 'L': u'\u13DE\u1...
LLNL/spack
var/spack/repos/builtin/packages/py-threadpoolctl/package.py
Python
lgpl-2.1
857
0.002334
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) class PyThreadpoolctl(PythonPackage): """Python helpers to limit the number of threads used in the threadpool-bac...
36a3026afc6dde3fb49c085cd0c004bbcf') depends_on('[email protected]:', type=('build', 'run')) depends_on('[email protected]:', type=('build', 'run'), whe
n='@3.0.0:')
mtpain/metacorps
app/models.py
Python
bsd-3-clause
6,238
0
import json import numpy as np import os import requests from datetime import datetime from flask_security import UserMixin, RoleMixin from .app import db DOWNLOAD_BASE_URL = 'https://archive.org/download/' class Instance(db.EmbeddedDocument): text = db.StringField(required=True) source_id = db.ObjectIdFi...
'epa/kill': [instance0, instance1, ...], 'epa/strangle': [instance0, ...], 'regulations/rob': [.
..] } ''' facets = [] for facet_label, search_results in faceted_search_results.items(): instances = [] for res in search_results: doc = IatvDocument.from_search_result(res) doc.save() new_instance = Instan...
w495/python-video-shot-detector
shot_detector/utils/repr_hash.py
Python
bsd-3-clause
2,296
0.00784
# -*- coding: utf8 -*- """ This is part of shot detector. Produced by w495 at 2017.05.04 04:18:27 """ from __future__ import absolute_import, division, print_function import datetime from collections import Iterable from enum import Enum from types import BuiltinFunctionType, FunctionType from uuid import UUI...
: """ var_dict = self.object_fields(obj) repr_tuple = tuple(var_dict) return repr_tuple def object_fields(self, obj): """ :param obj: :return: """ tuple_seq = self.object_field_seq(obj) repr_tuple = tuple(tuple_seq)
return repr_tuple @dispatch(dict) def raw_item(self, value): """ :param value: :return: """ tuple_seq = self.raw_item_seq(value) repr_tuple = tuple(tuple_seq) return repr_tuple @dispatch(list) def raw_item(self, value): ""...
Rhadow/leetcode
lintcode/Medium/074_First_Bad_Version.py
Python
mit
742
0.001348
#class SVNRepo: # @classmethod # def isBadVersion(cls, id) # # Run unit tests to check whether verison `id` is a bad version # # return true if unit tests passed else false. # You can use SVNRepo.isBadVersion(10) to check whether version 10 is a # bad version. class Solution: """ @param n:...
urn:
An integer which is the first bad version. """ def findFirstBadVersion(self, n): # write your code here start, end = 1, n if (n == 1): return 1 while (start <= end): i = (start + end) / 2 if (not SVNRepo.isBadVersion(i)): start...
FederatedAI/FATE
examples/pipeline/hetero_feature_binning/pipeline-hetero-binning-sparse-optimal-chi-square.py
Python
apache-2.0
2,362
0.00127
# # Copyright 2019 The FATE 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 applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BA
SIS, # 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. # import argparse import os import sys cur_path = os.path.realpath(__file__) for i in range(4): cur_path = os.path.dirname(cur_p...
rbreitenmoser/snapcraft
snapcraft/wiki.py
Python
gpl-3.0
2,447
0
# -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*- # # Copyright (C) 2015 Canonical Ltd # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3 as # published by the Free Software Foundation. # # This program is distributed in the h...
if content.endswith(_WIKI_CLOSE): content = content[:-len(_WIKI_CLOSE)] self.wiki_parts = yaml.load(content) def get_part(self, name): self._fetch() if name in self.wiki_parts: if 'plugin' and 'type' in self.wiki_parts[name]: del self.wi...
return self.wiki_parts[name] def compose(self, name, properties): """Return properties composed with the ones from part name in the wiki. :param str name: The name of the part to query from the wiki :param dict properties: The current set of properties :return: Part pr...
nbbl/ger-trek
app/__init__.py
Python
gpl-2.0
1,012
0.008893
from flask import Flask from flas
k.ext.sqlalchemy import SQLAlchemy from default_config import config db = SQLAlchemy() def create_app(config_name): # Define the WSGI application object app = Flask(__name__) # Configurations app.config.from_object(config[config_name]) config[config_name].init_app(app) # Define the...
se object which is imported # by modules and controllers db.init_app(app) return app # Import modules/components using their blueprint handler variables # TODO: try this at the beginning and see if it still works (circular deps?!) # from app.auth.controllers import auth as auth # .. ...
g1franc/lets-encrypt-preview
letsencrypt/crypto_util.py
Python
apache-2.0
8,163
0.000123
"""Let's Encrypt client crypto utility functions. .. todo:: Make the transition to use PSS rather than PKCS1_v1_5 when the server is capable of handling the signatures. """ import logging import os import OpenSSL import zope.component from acme import crypto_util as acme_crypto_util from acme import jose from ...
_or_req = load_func(typ, cert_or_req_str) except OpenSSL.crypto.Error as error: logger.exception(error) raise # py
lint: disable=protected-access return acme_crypto_util._pyopenssl_cert_or_req_san(cert_or_req) def get_sans_from_cert(cert, typ=OpenSSL.crypto.FILETYPE_PEM): """Get a list of Subject Alternative Names from a certificate. :param str cert: Certificate (encoded). :param typ: `OpenSSL.crypto.FILETYPE_PEM...
teltek/edx-platform
lms/djangoapps/courseware/tests/test_favicon.py
Python
agpl-3.0
961
0
from django.test import TestCase from django.test.utils import override_settings from util.testing import UrlResetMixin class FaviconTestCase(UrlResetMixin, TestCase): """ Tests of the courseware favicon. """ shard = 1 def test_favicon_redirect(self): resp = self.client.get("/favicon.ico...
code=404 # @@@ how to avoid 404? ) @override_se
ttings(FAVICON_PATH="images/foo.ico") def test_favicon_redirect_with_favicon_path_setting(self): self.reset_urls() resp = self.client.get("/favicon.ico") self.assertEqual(resp.status_code, 301) self.assertRedirects( resp, "/static/images/foo.ico", ...
fsalamero/pilas
pilas/actores/menu.py
Python
lgpl-3.0
7,370
0.004755
# -*- encoding: utf-8 -*- # Pilas engine - A video game framework. # # Copyright 2010 - Hugo Ruscitti # License: LGPLv3 (see http://www.gnu.org/licenses/lgpl.html) # # Website - http://www.pilas-engine.com.ar from pilas.actores import Actor import pilas DEMORA = 14 class Menu(Actor): """Un actor que puede mostra...
self.mover_cursor(1) self.demora_al_responder = DEMORA elif self.control_menu.arriba: self.mover_cursor(-1) self.demora_al_responder = DEMORA self.demora_al_responder -= 1 def seleccionar_opcion_actual(self): """Se e
jecuta para activar y lanzar el item actual.""" opcion = self.opciones_como_actores[self.opcion_actual] opcion.seleccionar() def mover_cursor(self, delta): """Realiza un movimiento del cursor que selecciona opciones. :param delta: El movimiento a realizar (+1 es avanzar y -1 retroc...
caioserra/apiAdwords
examples/adspygoogle/dfp/v201306/get_team.py
Python
apache-2.0
1,511
0.001985
#!/usr/bin/python # # Copyright 2013 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required b...
classes from the
client library. from adspygoogle import DfpClient # Initialize client object. client = DfpClient(path=os.path.join('..', '..', '..', '..')) # Initialize appropriate service. team_service = client.GetService('TeamService', version='v201306') # Set the ID of the team to get. team_id = 'INSERT_TEAM_ID_HERE' # Get te...
our-city-app/oca-backend
src/rogerthat/dal/activation.py
Python
apache-2.0
1,112
0.000899
# -*- coding: utf-8 -*- # Copyright 2020 Green Valley Belgium NV # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You m
ay obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License f...
erthat.dal import generator from rogerthat.models import ActivationLog from mcfw.rpc import returns, arguments @returns([ActivationLog]) @arguments(min_timestamp=int, max_timestamp=int) def get_activation_log(min_timestamp, max_timestamp): qry = ActivationLog.gql("WHERE timestamp > :min_timestamp AND timestamp < ...
DenBaum/lolm8guesser
friendship.py
Python
mit
3,046
0.043664
from riotwatcher import * from time import sleep import logging log = logging.getLogger('log') def getTeamOfSummoner( summonerId, game ): for p in game['participants']: if p['summonerId'] == summonerId: return p['teamId'] def getSummonerIdsOfOpponentTeam( summonerId, game ): teamId = getTeamOfS...
dd(game['gameId']) sets[id] = s return sets def computeFriendship( IdSets ): searchedSets = set() friendships = {} for id in IdSets: friendships[id] = {} for id in IdSets: searchedSets.add(id) for
gameId in IdSets[id]: for id2 in IdSets: if not id2 in searchedSets: if gameId in IdSets[id2]: if not id2 in friendships[id]: friendships[id][id2] = 1 if not id in friendships[id2]: friendships[id2][id] = 1 friendships[id][id2] += 1 friendships[id2][id] += 1 ...
Truth0906/PTTCrawlerLibrary
PyPtt/_api_post.py
Python
lgpl-3.0
6,653
0
try: from . import i18n from . import connect_core from . import screens from . import exceptions from . import command except ModuleNotFoundError: import i18n import connect_core import screens import exceptions import command def fast_post_step0( api: object, ...
n(i18n.NoPermission) def fast_post_step1(api: object, sign_file) -> None:
cmd = '\r' target_list = [ connect_core.TargetUnit( i18n.HasPostPermission, '發表文章於【', break_detect=True, ), connect_core.TargetUnit( i18n.NoPermission, '使用者不可發言', break_detect=True, ), connect_core.T...
emersonp/roguelike
rl.py
Python
mit
45,673
0.021085
import libtcodpy as libtcod import math import shelve import textwrap ############################################# # Constants and Big Vars ############################################# # Testing State TESTING = True # Size of the window SCREEN_WIDTH = 100 SCREEN_HEIGHT = 70 # Size of the Map MAP_WIDTH = SCREEN_WI...
quipped ' + self.owner.name + ' on ' + self.slot + '.', libtcod.light_green) fov_recompute = True def d
equip(self): # Dequip object and show a message about it. if not self.is_equipped: return self.is_equipped = False message('Dequipped ' + self.owner.name + ' from ' + self.slot + '.', libtcod.light_yellow) fov_recompute = True def check_equip(self): return self.is_equipped class Fighte...
lukfor/mkdocs
mkdocs/__main__.py
Python
bsd-2-clause
8,721
0.00172
#!/usr/bin/env python # coding: utf-8 from __future__ import unicode_literals import logging import click import socket from mkdocs import __version__ from mkdocs import utils from mkdocs import exceptions from mkdocs import config from mkdocs.commands import build, gh_deploy, new, serve log = logging.getLogger(__na...
type=click.Choice(theme_choices), help=theme_help) @click.option('-e', '--theme-dir', type=click.Path(), help=theme_dir_help) @click.option('-d', '--site-dir', type=click.Path(), help=site_dir_help) @common_options def build_command(clean, config_file, strict, theme, theme_dir, site_dir): """Build the MkDocs docume...
rride config value if user did not specify --strict flag # Conveniently, load_config drops None values strict = strict or None try: build.build(config.load_config( config_file=config_file, strict=strict, theme=theme, theme_dir=theme_dir, s...
tensorflow/probability
tensorflow_probability/python/experimental/linalg/no_pivot_ldl_test.py
Python
apache-2.0
4,358
0.00413
# Copyright 2021 The TensorFlow Probability 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 o...
=None, seed=42): np.random.seed(seed) shape = batch_shape + [n] diag = np.random.uniform(low, high, size=shape) if forcemin: assert forcemin < low diag = np.where(diag ==
np.min(diag, axis=-1)[..., np.newaxis], forcemin, diag) return diag def _randomTril(self, n, batch_shape, seed=42): np.random.seed(seed) unit_tril = np.random.standard_normal(batch_shape + [n, n]) unit_tril = np.tril(unit_tril) unit_tril[..., range(n), range(n)] = 1. ret...
ylatuya/Flumotion
flumotion/ui/fgtk.py
Python
gpl-2.0
2,667
0.000375
# -*- Mode: Python; test-case-name: flumotion.test.test_ui_fgtk -*- # vi:si:et:sw=4:sts=4:ts=4 # # Flumotion - a streaming media server # Copyright (C) 2004,2005,2006,2007 Fluendo, S.L. (www.fluendo.com). # All rights reserved. # This file may be distributed and/or modified under the terms of # the GNU General Public ...
ced Streaming Server Commercial License Agreement. # See "LICENSE.Flumotion" in the source distribution for more information. # Headers in this file shall remain intact. """ I am a collection of extended GTK widgets for use in Flumotion. """ import gobject from kiwi.ui.widgets.checkbutton import ProxyChec
kButton from kiwi.ui.widgets.combo import ProxyComboBox from kiwi.ui.widgets.entry import ProxyEntry from kiwi.ui.widgets.radiobutton import ProxyRadioButton from kiwi.ui.widgets.spinbutton import ProxySpinButton __version__ = "$Rev$" class FProxyComboBox(ProxyComboBox): def set_enum(self, enum_class, value_fil...
ToAruShiroiNeko/revscoring
revscoring/languages/french.py
Python
mit
1,905
0
import sys from .space_delimited import SpaceDelimited try: from nltk.stem.snowball import SnowballStemmer stemmer = SnowballStemmer("french") except ValueError: raise ImportError("Could not load stemmer for {0}. ".format(__name__)) try: from nltk.corpus import stopwords as nltk_stopwords stopwor...
. autoattribute:: parent_revision.content_words .. autoattribute:: parent_revision.badwords .. autoattribute:: parent_revision.misspellings .. autoattribute:: parent_revision.infonoise diff ---- .. autoattribute:: diff.words_added .. autoattribute:: diff.words_removed .. autoattribute:: diff.badwords_added .. autoattr...
dictionary=dictionary, stemmer=stemmer, stopwords=stopwords )
rahushen/ansible
test/units/modules/network/f5/test_bigip_monitor_tcp_echo.py
Python
gpl-3.0
10,010
0.001199
# -*- coding: utf-8 -*- # # Copyright (c) 2017 F5 Networks Inc. # GNU General Public License v3.0 (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import (absolute_import, division, print_function) __metaclass__ = type import os import json import sys import pytest from nose.plugins.skip imp...
e=self.spec.supports_check_mode ) # Override methods in the specific type of manager mm = ModuleManager(module=module) mm.exists = Mock(return_value=True) mm.read_current_from_device = Mock(return_value=current) mm.update_on_device = Mock(return_value=True) with...
n" in str(ex) def test_update_interval_larger_than_new_timeout(self, *args): set_module_args(dict( name='foo', interval=10, timeout=5, server='localhost', password='password', user='admin' )) current = Parameters(param...
BasicWolf/minicash
src/minicash/app/settings/heroku.py
Python
apache-2.0
472
0
# R
equired environmental variables: # * DATABASE_URL # * MINICASH_LOCAL_DIR # * MINICASH_SECRET_KEY from .base import * DEBUG = False # Allow all host headers ALLOWED_HOSTS = ['*'] # Simplified static file serving. # https://warehouse.python.org/project/whitenoise/ STATICFILES_STORAGE = 'whitenoise.django.GzipManife...
HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
ksrajkumar/openerp-6.1
openerp/addons/itara_customer_commission/__openerp__.py
Python
agpl-3.0
1,639
0.005491
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU...
later version. # # This pro
gram is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public ...
jmaher/treeherder
treeherder/perf/management/commands/compute_criteria_formulas.py
Python
mpl-2.0
5,956
0.002183
import time from datetime import timedelta from typing import List from treeherder.config import settings from treeherder.perf.sheriffing_criteria import ( EngineerTractionFormula, FixRatioFormula, CriteriaTracker, TotalAlertsFormula, ) from treeherder.perf.sheriffing_criteria import criteria_tracking...
pretty_enumerated(formulas: List[str]) -> str: comma = ', ' return ' & '.join(co
mma.join(formulas).rsplit(comma, maxsplit=1)) class Command(BaseCommand): ENGINEER_TRACTION = 'engineer traction' FIX_RATIO = 'fix ratio' FORMULAS = [ENGINEER_TRACTION, FIX_RATIO] # register new formulas here help = f''' Compute the {pretty_enumerated(FORMULAS)} for multiple framework/suite comb...
LegoStormtroopr/comet-indicator-registry
comet/__init__.py
Python
bsd-2-clause
54
0.018519
default_ap
p_config = 'comet.apps.Comet
IndicatorConfig'
vladcalin/gemstone
gemstone/core/container.py
Python
mit
1,639
0
import abc class Container(abc.ABC): """ A container for exposed methods and/or event handlers for a better modularization of the application. Example usage :: # in users.py class UsersModule(gemstone.Container): @gemstone.exposed_method("users.register") ...
return self.microservice.get_executor() def get_io_loop(self): """ Returns the current IOLoop used by the microservice. :return: """ return self.microservice.get_io_loop() def get_exposed_methods(self): exposed = [] for item in se
lf._iter_methods(): if getattr(item, "_exposed_public", False) or \ getattr(item, "_exposed_private", False): exposed.append(item) return exposed def get_event_handlers(self): handlers = [] for item in self._iter_methods(): if geta...
nwoeanhinnogaehr/live-python-jacker
examples/pvoc5.py
Python
gpl-3.0
431
0.00232
from numpy import * from stft import * from pvoc import * stft = STFT(16384, 2, 4) pvoc = PhaseVocoder(stft
) time = 0 def proce
ss(i, o): global time for x in stft.forward(i): x = pvoc.forward(x) x = pvoc.to_bin_offset(x) x = pvoc.shift(x, lambda y: sin(y + time*0.01)*mean(y)) x = pvoc.from_bin_offset(x) x = pvoc.backward(x) stft.backward(x) stft.pop(o) time += 1
hugoArregui/ff-bookmarks-backup
ff-bookmarks-backup.py
Python
bsd-3-clause
867
0.005767
#!/usr/bin/env python import telnetlib, argparse parser = argparse.ArgumentParser(description='Firefox bookmarks backup tool') parser.add_argument('output', metavar='FILE', type=str) parser.add_argument('--host', metavar='host', type=str, default="localhost", help="mozrep host") parser.add_argument('--port', metavar=...
up_to = arg
s.output print("Connecting to mozrep at %s:%s" % (host, port)) t = telnetlib.Telnet(host, port=port) t.write(b'Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");') t.write(b'XPCOMUtils.defineLazyModuleGetter(this, "PlacesBackups", "resource://gre/modules/PlacesBackups.jsm");') t.write(('PlacesBackups.sa...
ryanss/holidays.py
holidays/countries/australia.py
Python
mit
9,872
0
# -*- coding: utf-8 -*- # python-holidays # --------------- # A fast, efficient Python library for generating country, province and state # specific sets of holidays on the fly. It aims to make determining whether a # specific date is a holiday as fast and flexible as possible. # # Authors: dr-prodigy <maurizio....
self[date(year, SEP, 28)] = name elif year == 2016: self[date(year, SEP, 26)] = name elif year == 2017: self[date(year, S
EP, 25)] = name # Reconciliation Day if self.prov == "ACT": name = "Reconciliation Day" if year >= 2018: self[date(year, 5, 27) + rd(weekday=MO)] = name if self.prov == "VIC": # Grand Final Day if year == 2020: # R...
TheTimmy/spack
var/spack/repos/builtin/packages/r-limma/package.py
Python
lgpl-2.1
1,617
0.001237
############################################################################## # Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, [email protected], All rights reserved. # LLNL-CODE-64...
ace, Suite 330, Boston, MA 02111-1307 USA ############################################################################## from sp
ack import * class RLimma(RPackage): """Data analysis, linear models and differential expression for microarray data.""" homepage = "https://www.bioconductor.org/packages/limma/" url = "https://www.bioconductor.org/packages/release/bioc/src/contrib/limma_3.32.6.tar.gz" list_url = homepage ...
bytejive/lazy-docker
CommandBuilder.py
Python
apache-2.0
828
0
import Utils from Utils import printe class CommandBuilder(object): def __init__(self, *command_args): self.command_args = list(command_args) def append(self, *args): for
arg in args: if isinstance(arg, str): self.command_args += [arg] elif isinstance(arg, list) or isinstance(arg, tuple): for sub_arg in arg: self.append(sub_arg) else: printe('Error appending argument of unknown type: ...
str(type(arg))), terminate=True) return self def debug(self): return Utils.debug(*self.command_args) def run(self, replaceForeground=False): return Utils.run(*self.command_args, replaceForeground=replaceForeground)
sumara/ansible-lint-deb
deb_dist/ansible-lint-2.1.3/lib/ansiblelint/utils.py
Python
gpl-2.0
9,195
0.000218
# Copyright (c) 2013-2014 Will Thames <[email protected]> # # 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...
n = task.get("action") args = " ".join(["k=v" for (k, v) in action.items() if k != "module_arguments"] + action.get("module_arguments")) return "{0} {1}".format(action["module"], args) def get_action_tasks(yaml, file): tasks = list() if file['type'] in ['tasks', 'handlers']: ...
in ['tasks', 'handlers', 'pre_tasks', 'post_tasks']: if s
respawner/peering-manager
peering/migrations/0004_auto_20171004_2323.py
Python
apache-2.0
1,014
0
# -*- coding: utf-8 -*- # Generated by Django 1.11.5 on 2017-10-04 21:23 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [("peering", "0003_auto_20170903_1235")] operations = [ migrations.AlterField( model_name="autonomoussystem", ...
ld(blank=True, null=True), ), migrations.AlterField( model_name="autonomoussystem", name="ipv6_as_set", field=models.CharField(blank=True, max_length=128, null=True), ), migrations.AlterField(
model_name="autonomoussystem", name="ipv6_max_prefixes", field=models.PositiveIntegerField(blank=True, null=True), ), ]
peter-ch/MultiNEAT
setup.py
Python
lgpl-3.0
5,190
0.005202
#!/usr/bin/python3 #from __future__ import print_function from setuptools import setup, Extension import sys import os import psutil # monkey-patch for parallel compilation def parallelCCompile(self, sources, output_dir=None, macros=None, include_dirs=None, debug=0, extra_preargs=None, extra_postargs=None, depends=No...
OOST_RANDOM', #'-O0', #'-DVDEBUG', ]) exx = Extension('MultiNEAT._MultiNEAT', sources,
libraries=libs, extra_compile_args=extra) print(dir(exx)) print(exx) print(exx.extra_compile_args) extensionsList.append(exx) else: raise AttributeError('Unknown tool: {}'.format(build_sys)) return extensionsList setup(name='multineat', ...
emacsway/ascetic
ascetic/tests/test_mappers.py
Python
mit
11,813
0.00254
#!/usr/bin/env python import unittest from sqlbuilder import smartsql from ascetic import exceptions, validators from ascetic.databases import databases from ascetic.mappers import Mapper, mapper_registry from ascetic.relations import ForeignKey Author = Book = None class TestMapper(unittest.TestCase): maxDif...
db_table = 'ascetic_tests_author' defaults = {'bio': 'No bio available'} validations = {'first_name': validators.Length(), 'last_name': (validators.Length(), lambda x: x != 'BadGuy!' or 'Bad last name', )} AuthorMapper(Author) class Book(object): ...
_id=None): self.id = id self.title = title self.author_id = author_id class BookMapper(Mapper): db_table = 'books' relationships = { 'author': ForeignKey(Author, related_name='books') } BookMapper(Book)...
vizual54/MissionPlanner
Scripts/example1.py
Python
gpl-3.0
1,491
0.031565
# cs.???? = currentstate, any variable on the status tab in the planner can be used. # Script = options are # Script.Sleep(ms) # Script.ChangeParam(name,value) # Script.GetParam(name) # Script.ChangeMode(mode) - same as displayed in mode setup screen 'AUTO' # Script.WaitFor(string,timeout) # Script.SendRC(chan...
- -45 Script.Sleep(5) Script.SendRC(5,1500,False) # stabalise Script.SendRC(1,1500,True) # level roll Script.Sleep(2000) # 2 sec to stabalise Script.SendRC(3,1300,True) # throttle back to land thro = 1350 # will
decend while cs.alt > 0.1: Script.Sleep(300) Script.SendRC(3,1000,False) Script.SendRC(4,1000,True) Script.WaitFor('DISARMING MOTORS',30000) Script.SendRC(4,1500,True) print 'Roll complete'
crazy-canux/xnagios
nagios/__init__.py
Python
apache-2.0
451
0.002217
#!/usr/bin/env python # -*- coding
: utf-8 -*- """ Automatic config nagios configurations. Copyright (C) 2015 Canux CHENG All rights reserved Name: __init__.py Author: Canux [email protected] Version: V1.0 Time: Wed 09 Sep 2015 09:20:51 PM EDT Exaple: ./nagios -h """ __version__ = "3.1.0.0" __description__ = """Config nagios automatic. Any que...
_ = "Canux CHENG"
dfm/transit
transit/transit.py
Python
mit
20,191
0.00005
# -*- coding: utf-8 -*- from __future__ import division, print_function import fnmatch import logging import numpy as np from ._transit import C
ythonSolver __all__ = ["Central", "Body", "System"] try: from itertools import izip, imap except ImportError: izip, imap = zip, map # Newton's constant in $R_\odot^3 M_\odot^{-1} {days}^{-2}$. _G = 2945.4625385377644 # A constant to convert between solar radii per da
y and m/s. _rvconv = 1.242271746944644082e-04 # Solar mass & radius in cgs units _Msun = 1.9891e33 _Rsun = 6.95508e10 class Central(object): """ The "central"---in this context---is the massive central body in a :class:`System`. :param mass: The mass of the body measured in Solar masses. (de...
ColOfAbRiX/ansible
lib/ansible/modules/network/nxos/nxos_pim.py
Python
gpl-3.0
9,817
0.001834
#!/usr/bin/python # # 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, or # (at your option) any later version. # # Ansible is distribut...
ol Independent Multicast (PIM) instance. author: Gabriele Gerbino (@GGabriele) extends_documentation_fragment: nxos options: ssm_range: description: - Configure group ranges for Source Specific Multicast (SSM). Valid values are multicast addresses or the keyword 'none'. req...
assword: "{{ pwd }}" host: "{{ inventory_hostname }}" ''' RETURN = ''' proposed: description: k/v pairs of parameters passed into module returned: verbose mode type: dict sample: {"ssm_range": "232.0.0.0/8"} existing: description: k/v pairs of existing PIM configuration returned: verbose mo...
jimgoo/zipline-fork
zipline/examples/olmar.py
Python
apache-2.0
5,460
0.002198
import numpy as np from datetime import datetime import pytz from zipline.algorithm import TradingAlgorithm #from zipline.utils.factory import load_from_yahoo from pulley.zp.data.loader import load_bars_from_yahoo from zipline.finance import commission #STOCKS = ['AMD', 'CERN', 'COST', 'DELL', 'GPS', 'INTC', 'MMM'] S...
pdate portfolio algo.b_t = b_norm def rebalance_portfolio(algo, data, desired_port): # rebalance portfolio de
sired_amount = np.zeros_like(desired_port) current_amount = np.zeros_like(desired_port) prices = np.zeros_like(desired_port) if algo.init: positions_value = algo.portfolio.starting_cash else: positions_value = algo.portfolio.positions_value + \ algo.portfolio.cash for i...
vipshop/twemproxies
tests/conf/conf.py
Python
apache-2.0
436
0.013761
#coding: utf-8 import os import sys PWD = os.path.dirname(os.path.realpath(__file__)) WORKDIR = os.
path.join(PWD, '../') BINARYS = { 'REDIS_SERVER_BINS' : os.path.join(WORKDIR, '_binaries/redis-*'), 'REDIS_CLI' : os.path.join(WORKDIR, '_binaries/redi
s-cli'), 'MEMCACHED_BINS' : os.path.join(WORKDIR, '_binaries/memcached'), 'NUTCRACKER_BINS' : os.path.join(WORKDIR, '_binaries/nutcrackers'), }
watonyweng/horizon
horizon/test/tests/tables.py
Python
apache-2.0
64,222
0
# Copyright 2012 Nebula, Inc. # Copyright 2014 IBM 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...
= ("Downed", "Upped") data_type_singular = "Item" data_type_plural = "Items" def allowed(self, request, obj=None): if not obj: return False self.down = getattr(obj, 'status', None) == 'down' if self.down: self.current_present_action = 1 return self.d...
= 1 class MyDisabledAction(MyToggleAction): def allowed(self, request, obj=None): return False class MyFilterAction(tables.FilterAction): def filter(self, table, objs, filter_string): q = filter_string.lower() def comp(obj): if q in obj.name.lower(): ret...
jmcanterafonseca/fiware-cygnus
test/acceptance/integration/notifications/mysql/steps.py
Python
agpl-3.0
5,768
0.009193
# -*- coding: utf-8 -*- # # Copyright 2015 Telefonica Investigación y Desarrollo, S.A.U # # This file is part of fiware-cygnus (FI-WARE project). # # fiware-cygnus 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 Foun...
tadata_data_type) # ------------------------------------------------------------------------------------------------------------------ @step (u'Verify that the attribute value is stored in mysql') def verify_that_the_attribute_value_is_st
ored_in_mysql(step): """ Validate that the attribute value and type are stored in mysql per column :param step: """ world.cygnus.verify_table_search_values_by_column() @step (u'Verify the metadatas are stored in mysql') def verify_the_metadatas_are_stored_in_mysql(step): """ Validate that t...
sinneb/pyo-patcher
webroot/transformer.py
Python
mit
791
0.012642
from scipy.io.wavf
ile import read import matplotlib.pyplot as plt from pylab import * import PIL from PIL import Image, ImageOps import wave, struct, sys import glob, os for file in os.listdir("./"): if file.endswith(".wav"): print(file) outputfile = file[:-4] + '.png' input_data = read(file) audio ...
") fig.savefig(outputfile) img = Image.open(outputfile) img = img.resize((100, 40), PIL.Image.ANTIALIAS) img = ImageOps.expand(img,border=1,fill='black') img.save(outputfile) # plt.axis('off') # plt.plot(audio[0:600]/1000.0) # #plt.show() # plt.savefig('foo.png')
mivdnber/roetsjbaan
roetsjbaan/__init__.py
Python
mit
69
0
from roetsjbaan.migrator import * from roetsjbaan.versioner i
mport *
gosom/flask-mysqlpool
setup.py
Python
bsd-3-clause
1,227
0.002445
#-*- coding: utf-8 -*- #!/usr/bin/env python """ Flask-Mysqlpool ----------- Adds support to flask to connect to a MySQL server using mysqldb
extension and a connection pool. """ from setuptools import setup setup( name='Flask-Mysqlpool', version='0.1', url='', license='BSD', author='Giorgos Komninos', author_email='[email protected]', description='Flask simple mysql client using a connection pool', long_description=__doc_...
any', install_requires=[ 'Flask', 'mysql-python', ], test_suite='test_mysqlpool', classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operat...
wxgeo/geophar
wxgeometrie/sympy/physics/unitsystems/dimensions.py
Python
gpl-2.0
17,933
0.000725
# -*- coding:utf-8 -*- """ Definition of physical dimensions. Unit systems will be constructed on top of these dimensions. Most of the examples in the doc use MKS system and are presented from the computer point of view: from a human point, adding length to time is not legal in MKS but it is in natural system; for a...
ion(length=1) == Dimension(length=1, symbol="L") True >>> Dimension(length=1) == Dimension(length=1, name="length", ... symbol="L") True """ is_commutative = True is_number = False # make sqrt(M**2) --> M is_positive = True def _...
s are (examples given with list/tuple work also with tuple/list): >>> from sympy.physics.unitsystems.dimensions import Dimension >>> Dimension(length=1) {'length': 1} >>> Dimension({"length": 1}) {'length': 1} >>> Dimension([("length", 1),...
filias/django
django/core/handlers/wsgi.py
Python
bsd-3-clause
9,048
0.000553
from __future__ import unicode_literals import cgi import codecs import logging import re import sys from io import BytesIO from django import http from django.conf import settings from django.core import signals from django.core.handlers import base from django.urls import set_script_prefix from django.utils import ...
esponse = environ['wsgi.file_wrapper'](response.file_to_stream) return response def get_path_info(environ): """ Returns the HTTP request's PATH_INFO as a unicode string. """ path_info = get_bytes_from_wsgi(environ, 'PATH_INFO', '/') return path_info.decode(UTF_8) def get_script_name(env...
script name prior to any rewriting (so it's the script name as seen from the client's perspective), unless the FORCE_SCRIPT_NAME setting is set (to anything). """ if settings.FORCE_SCRIPT_NAME is not None: return force_text(settings.FORCE_SCRIPT_NAME) # If Apache's mod_rewrite had a whack ...
reviewboard/reviewboard
reviewboard/site/evolutions/__init__.py
Python
mit
67
0
SEQUENCE = [
'localsite_public', 'localsite_extra_d
ata', ]
XianliangJ/collections
CNUpdates/updates/examples/hypercube.py
Python
gpl-3.0
753
0.027888
# import sys # sys.path.append('/home/openflow/frenetic/updates/examples') from nxtopo import NetworkXTopo from mininet.topo import Node import networkx as nx class MyTopo( NetworkXTopo ): def __init__( self, enable_all = True ): comp_graph = nx.complete_graph(32) graph = nx.Graph() ...
raph.add_node(node+1) for edge in comp_graph.edges(): (src,dst) = edge graph.add_edge(src+1,dst+1) host_location = {} for host in range(1,graph.order()+1): host_location[host+graph.order()] = (host, 4) super( MyTopo, self ).__init__(graph...
topos = { 'mytopo': ( lambda: MyTopo() ) }
SentimensRG/txCelery
txcelery/__init__.py
Python
mit
100
0
#!/usr/
bin/env python from pkg_resources import require from . import
defer __version__ = '1.1.3'
JulienMcJay/eclock
windows/Python27/Lib/site-packages/pywin32-218-py2.7-win32.egg/win32com/client/util.py
Python
gpl-2.0
2,965
0.03339
"""General client side utilities. This module contains utility functions, used primarily by advanced COM programmers, or other COM modules. """ import pythoncom from win32com.client import Dispatch, _get_good_object_ PyIDispatchType = pythoncom.TypeIIDs[pythoncom.IID_IDispatch] def WrapEnum(ob, resultCLS
ID = None): """Wrap an object in a VARIANT enumerator. All VT_DISPATCHs returned by the enumerator are converted to wrapper objects (which may be either a class instance, or a dynamic.Dispatch type object). """ if type(ob) != pyt
honcom.TypeIIDs[pythoncom.IID_IEnumVARIANT]: ob = ob.QueryInterface(pythoncom.IID_IEnumVARIANT) return EnumVARIANT(ob, resultCLSID) class Enumerator: """A class that provides indexed access into an Enumerator By wrapping a PyIEnum* object in this class, you can perform natural looping and indexing into the Enum...
ballesterus/UPhO
Consensus.py
Python
gpl-3.0
5,860
0.025256
#!/usr/bin/env python import argparse import re from sys import argv #Globals NT= ('A','C','G','T','U','R','Y','K','M','S','W','B','D','H','V','N', '-', '?') AA =('A','B','C','D','E','F','G','H','I','K','L','M','N','P','Q','R','S','T','U','V','W','Y','Z','X', '-', '*', '?') #dictionary of ambiguity: Ambigs = { ...
ents T = arguments.percentage
M = arguments.blocks D = arguments.delimiter for File in arguments.alignments: F = Fasta_to_Dict(File) Con = make_Consensus(F, T) with open ("%s_consensus.fasta" % File.split('.')[0], 'w') as out: out.write('>%s consensus sequence\n%s\n' % (File, Con)) if M ...
alexbredo/ipfix-receiver
base/cache.py
Python
bsd-2-clause
4,389
0.030987
# Copyright (c) 2014 Alexander Bredo # 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. Redistributions of source code must retain the above # copyright notice, this list of conditions ...
) ''' lock = Lock() def __init__(self, ttl=30):
self.cache = dict() self.ttl = ttl def insert(self, index, data, ignore_fields=[]): IndexedTimeCache.lock.acquire() if index in self.cache: # UPDATE + AGGREGATE self.cache[index]['data'] = self.__aggregate(self.cache[index]['data'], data, ignore_fields) else: # NEW self.cache[index] = { ...
laysakura/shellstreaming
test/master/test_master_functional.py
Python
apache-2.0
139
0
# -*- coding: utf-8 -*- from subprocess import check_call def test_shellstre
aming_help
(): check_call(["shellstreaming", "--help"])
dmpalyvos/web-scripts
spider.py
Python
gpl-2.0
5,655
0.001945
#!/usr/bin/python3 """ Analyze the word frequencies on the main articles of a website """ import argparse import requests from bs4 import BeautifulSoup import re import itertools import string from collections import defaultdict import time import json import os import operator def load_ignored_words(words_file): ...
[*] Saving cache file {0}'.format(cache_fname)) with open(cache_fname, 'w') as cache_file: json.dump(pages, cache_file) return pages def mine_url(url, ignored_words): '''Given a url, follow all the links and return lists of words on each page ''' pages = follow_links(url) paragraph_l...
_list(paragraphs, ignored_words) for paragraphs in paragraph_list] return word_lists def calculate_tf(word_list): '''Calculate relative term frequencies for a list of words ''' tf = defaultdict(int) max_freq = 0 for word in word_list: tf[word] += 1 if tf[word] > max_freq: ...
PyGithub/PyGithub
github/StatsContributor.py
Python
lgpl-3.0
4,872
0.005542
############################ Copyrights and license ############################ # # # Copyright 2013 Vincent Jacques <[email protected]> # # Copyright 2014 Vincent Jacques <[email protected]> ...
property def w(self): """ :type: datetime.datetime """ return self._w.value @property def a(self): """ :type: int """ return self._a.value @property def d(self): """ ...
:type: int """ return self._c.value def _initAttributes(self): self._w = github.GithubObject.NotSet self._a = github.GithubObject.NotSet self._d = github.GithubObject.NotSet self._c = github.GithubObject.NotSet def _useAttributes...
Darthkpo/xtt
openpyxl/styles/tests/test_colors.py
Python
mit
1,719
0.000582
from openpyxl.styles.colors import Color import pytest @pytest.mark.parametrize("value", ['00FFFFFF', 'efefef']) def test_argb(value): from ..colors import aRGB_REGEX assert aRGB_REGEX.match(value) is not None class TestColor: def test_ctor(self): c = Color() assert c.value == "00000000...
assert c.type == "rgb" assert dict(c) == {'rgb': 'FFFFFF
FF'} def test_indexed(self): c = Color(indexed=4) assert c.value == 4 assert c.type == "indexed" assert dict(c) == {'indexed': "4"} def test_auto(self): c = Color(auto=1) assert c.type is "auto" assert c.value is True assert dict(c) == {'auto': "...
tellian/muddpy
muddpy/Commands.py
Python
gpl-3.0
1,696
0.055425
# Parser from util import sTu, getSFChar, sTr, sTup, checkAware import world as w import settings as s from commands import movement from commands import inform from commands import admin from commands import objects command_list = { 'look':"1", 'score':"1", 'move':"1", 'sit':"1", 'stand':"1", 'sleep':"1", 'wak...
e(ch, cmdStr): # Full Command String, character object if cmdStr == "": sTup(ch.sId) return # split up cmdStr into useful stuff. if len(cmdStr.split(None, 1)) > 1: firstword, rest = cmdStr.split(None, 1) command = firstword.lower() rawArgs = rest.strip() else: rawArgs = "" command = cmdStr.lower() co...
in alias_list: tmpcmd = alias_list[command] sizearray = tmpcmd.split(" ") if len(sizearray) == 2: rawArgs = str(sizearray[1]) + " " + str(rawArgs) command = sizearray[0] else: command = alias_list[command] if command in command_list: rawArgs = rawArgs.strip() func = function_list[command] func(c...
jonparrott/google-cloud-python
ndb/src/google/cloud/ndb/model.py
Python
apache-2.0
97,630
0
# Copyright 2018 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
, self.id)) class ModelAdapter: __slots__ = () def __init__(self, *args, **kwargs): raise NotImplementedError def make_connection(*args, **kwargs):
raise NotImplementedError class ModelAttribute: """Base for classes that implement a ``_fix_up()`` method.""" __slots__ = () def _fix_up(self, cls, code_name): """Fix-up property name. To be implemented by subclasses. Args: cls (type): The model class that owns the property....
waqasbhatti/astroph-coffee
src/coffeehandlers.py
Python
mit
91,422
0.002439
#!/usr/bin/env python '''coffeehandlers.py - Waqas Bhatti ([email protected]) - Jul 2014 This contains the URL handlers for the astroph-coffee web-server. ''' import os.path import logging import base64 import re LOGGER = logging.getLogger(__name__) from datetime import datetime, timedelta from pytz imp...
listing (in rev-chron order) to be made: YEAR X Month X: Date X --- <strong>YY<strong> papers . . . YEAR 1 Month 1: Date 1 --- <strong>YY<strong> papers ''' years, months = [], [] for x in dates: years.append(x.year) months.append(x.month) ...
_months: yeardict[year][MONTH_NAMES[month]] = [ (x,y,z,w) for (x,y,z,w) in zip(dates, npapers, nlocal, nvoted) if (x.year == year and x.month == month) ] for month in yeardict[year].copy(): if not yeardict[year][month]: del ...
KiChjang/servo
tests/wpt/web-platform-tests/tools/webdriver/webdriver/client.py
Python
mpl-2.0
26,422
0.000719
from . import error from . import protocol from . import transport from urllib import parse as urlparse def command(func): def inner(self, *args, **kwargs): if hasattr(self, "session"): session = self.session else: session = self if session.session_id is None: ...
twist=twist, altitude_angle=altitude_angle, azimuth_angle=azimuth_angle) return self def pointer_up(self, button=0): """Queue a pointerUp action for `button`. :param button: Pointer button to perform action with. Default: 0, which represents ma
in device button. """ self._pointer_action("pointerUp", button=button) return self def pointer_down(self, button=0, width=None, height=None, pressure=None, tangential_pressure=None, tilt_x=None, tilt_y=None, twist=None, altitude_angle=None, azimuth_...
pjryan126/solid-start-careers
store/api/zillow/venv/lib/python2.7/site-packages/pandas/tests/indexes/test_multi.py
Python
gpl-2.0
78,143
0.000013
# -*- coding: utf-8 -*- from datetime import timedelta from itertools import product import nose import re import warnings from pandas import (date_range, MultiIndex, Index, CategoricalIndex, compat) from pandas.core.common import PerformanceWarning from pandas.indexes.base import InvalidIndexErro...
new_names = [name + "SUFFIX" for name in self.index_names] ind = self.index.set_names(new_names) self.assertEqual(self.index.names, self.index_names) self.assertEqual(ind.names, new_names) with assertRaisesRegexp(ValueError, "^Leng
th"): ind.set_names(new_names + new_names) new_names2 = [name + "SUFFIX2" for name in new_names] res = ind.set_names(new_names2, inplace=True) self.assertIsNone(res) self.assertEqual(ind.names, new_names2) # set names for specific level (# GH7792) ind = self....
tonihr/pyGeo
Controladores/UTM2Geo.py
Python
gpl-2.0
7,615
0.016419
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' Created on 17/2/2015 @author: Antonio Hermosilla Rodrigo. @contact: [email protected] @organization: Antonio Hermosilla Rodrigo. @copyright: (C) 2015 by Antonio Hermosilla Rodrigo @version: 1.0.0 ''' import sys from PyQt4 import QtCore from PyQt4 import QtGui from ...
_setPrecision) def __CargarElipsoides(self): '''! ''' import BasesDeDatos.SQLite.SQLiteManager try: db=BasesDeDatos.SQLite.SQLiteManager.SQLiteManager(self.__rutaroot+'/Geodesi
a/Elipsoides/Elipsoides.db') Nombres=db.ObtenerColumna('Elipsoides','Nombre') Nombres=[i[0] for i in Nombres] Nombres.sort() self.comboBox.addItems(Nombres) self.comboBox.setCurrentIndex(28) self.comboBox_2.addItems(Nombres) self.comboB...
Onirik79/aaritmud
src/socials/social_poke.py
Python
gpl-2.0
95
0.010526
# -*- coding: utf-8 -*- def social_poke(entity, argument): return True #- Fine Funzi
one -
vtorshyn/voltdb-shardit-src
voltdb-3.7/lib/python/voltcli/voltadmin.d/restore.py
Python
apache-2.0
1,943
0.006691
# This file is part of VoltDB. # Copyright (C) 2008-2013 VoltDB Inc. # # This file contains original code and/or modifications of original code. # Any modifications made by VoltDB Inc. are licensed under the following # terms and conditions: # # Permission is hereby granted, free of charge, to any person obtaining # a...
IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING
BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. # IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE O...
VitalPet/hr
hr_holidays_compute_days/tests/__init__.py
Python
agpl-3.0
180
0
# -*- coding: utf-8 -*- # © 2015 iDT LABS (http://[email protected]) # License AGPL-3.0 or later (
http://www.gnu.org/licenses/agpl.html). from .
import test_holidays_compute_days
bac/horizon
openstack_dashboard/dashboards/identity/roles/views.py
Python
apache-2.0
3,528
0
# Copyright 2013 Hewlett-Packard Development Company, L.P. # # 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 requir...
_('Unable to update role.'), redirect=redirect) def get_context_data(self, **kwargs): context = super(UpdateView, self).get_context_data(**kwargs)
args = (self.get_object().id,) context['submit_url'] = reverse(self.submit_url, args=args) return context def get_initial(self): role = self.get_object() return {'id': role.id, 'name': role.name} class CreateView(forms.ModalFormView): template_name = 'identity...
django-salesforce/django-salesforce
salesforce/apps.py
Python
mit
286
0.003497
"""This f
ile is useful only if 'salesforce' is a duplicit name in Django registry then put a string 'salesforce.apps.SalesforceDb' instead of simple 'salesforce' """ from django.apps import AppConfig class SalesforceDb(AppConfig): name = 'salesforce' label = 'salesforce_db
'
bbfamily/abu
abupy/MetricsBu/ABuMetricsFutures.py
Python
gpl-3.0
4,134
0.002949
# -*- encoding:utf-8 -*- """期货度量模块""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import matplotlib.pyplot as plt import numpy as np import seaborn as sns from ..CoreBu import ABuEnv from ..ExtBu.empyrical import stats from ..MetricsBu.ABuMetricsBase im...
filter __author__ = '阿布' __weixin__ = 'abu_quant' class AbuMetricsFutures(AbuMetricsBase): """期货度量类,主要区别在于不涉及benchmark""" def _metrics_base_stats(self)
: """度量真实成交了的capital_pd,即涉及资金的度量,期货相关不涉及benchmark""" # 平均资金利用率 self.cash_utilization = 1 - (self.capital.capital_pd.cash_blance / self.capital.capital_pd.capital_blance).mean() self.algorithm_returns = np.round(self.capital.capital_pd['capital_blance'...
alexm92/sentry
src/sentry/api/serializers/models/release_file.py
Python
bsd-3-clause
515
0
from __future__ import absolute_import import six from sent
ry.api.serializers import Serializer, register from sentry.models import ReleaseFile @register(ReleaseFile) class ReleaseFileSerializer(Serializer): def serialize(self, obj, attrs, user): return { 'id': six.text_type(obj.id), 'name': obj.name, 'headers': obj.file.header...
}
GuLinux/PySpectrum
stack_images.py
Python
gpl-3.0
9,262
0.009177
from pyui.stack_images import Ui_StackImages from PyQt5.QtWidgets import QDialog, QAction, QLineEdit, QProgressDialog, QApplication, QToolBar from PyQt5.QtGui import QIcon, QStandardItemModel, QStandardItem from PyQt5.QtCore import Qt, QObject, pyqtSignal, QStandardPaths, QByteArray from pyspectrum_commons import * fro...
stack(self): dataset = self.__files_data() median = MedianStacker(dataset).median() self.f
its_file[0].data = median class MedianStacker: def __init__(self, matrices): self.matrices = matrices def final_shape(self):
vesellov/bitdust.devel
services/service_proxy_server.py
Python
agpl-3.0
2,236
0.001789
#!/usr/bin/python # service_proxy_server.py # # Copyright (C) 2008-2018 Veselin Penev, https://bitdust.io # # This file (service_proxy_server.py) is part of BitDust Software. # # BitDust is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by...
] def enabled(self): from main import settings return settings.enableProxyServer() def start(self): from transport.proxy import proxy_router proxy_router.A('init') proxy_rout
er.A('start') return True def stop(self): from transport.proxy import proxy_router proxy_router.A('stop') proxy_router.A('shutdown') return True def request(self, json_payload, newpacket, info): from transport.proxy import proxy_router proxy_router.A('re...
alirizakeles/tendenci
tendenci/apps/invoices/forms.py
Python
gpl-3.0
4,200
0.001905
from django import forms from django.db.models.fields import CharField, DecimalField from django.utils.translation import ugettext_lazy as _ from tendenci.apps.invoices.models import Invoice from tendenci.apps.events.models import Event class AdminNotesForm(forms.ModelForm): class Meta: model = Invoice ...
S = ( ('starts_with', _('Starts With')), ('contains', _('Contains')), ('exact', _('Exact')), ) TENDERED_CHOICES = ( ('', _('Show All')), ('
tendered', _('Tendered')), ('estimate', _('Estimate')), ('void', _('Void')), ) BALANCE_CHOICES = ( ('', _('Show All')), ('0', _('Zero Balance')), ('1', _('Non-zero Balance')), ) search_criteria = forms.ChoiceField(choices=[], ...
collinmelton/DDCloudServer
DDServerApp/ORM/Mappers/WorkflowTemplates.py
Python
gpl-2.0
22,461
0.012466
''' Created on Dec 11, 2015 @author: cmelton ''' from DDServerApp.ORM import orm,Column,relationship,String,Integer, PickleType, Float,ForeignKey,backref,TextReader, joinedload_all from DDServerApp.ORM import BASE_DIR, Boolean from User import User import os, copy class Credentials(orm.Base): ''' classdocs ...
image self.disk_size = disk_size self.disk_type = disk_type self.location = location self.disk_vars = {} def dictForJSON(self): re
turn {"id": str(self.id), "name": self.name, "l
Performante/pyFormante
pyFormante/validation/exact_length.py
Python
gpl-2.0
411
0.002433
from .validator import Validator from ..util import register_as_validator class ExactL
ength(Validator): __validator_name__ = 'exact_length' def __init__(self, exact_length): super(ExactLength, self).__init__() self.exact_length = exact_length def validate(self, data, request=None, session=None): re
turn len(data) >= self.exact_length register_as_validator(ExactLength)
QuinDiesel/CommitSudoku-Project-Game
Definitief/timer.py
Python
mit
1,135
0.013216
import pygame def timer(): event = pygame.USEREVENT pygame.init() screen = pygame.display.set_mode((800, 600)) clock = pygame.time.Clock() counter, text = 50, '50' pygame.time.set_timer(event, 1000) font = pygame.font.SysFont('comicsansms', 20) while True: f...
screen.blit(font.render(text, True
, (0,255,0)), (700, 30)) if counter < 25: screen.blit(font.render(text, True, (255, 255, 0)), (700, 30)) if counter < 10: screen.blit(font.render(text, True, (255,0,0)), (700, 30)) pygame.display.flip() clock.tick(60) con...
20tab/python-gmaps
setup.py
Python
bsd-2-clause
1,557
0.001285
# -*- coding: utf-8 -*- from setuptools import setup, find_packages import os def strip_comments(l): return l.split('#', 1)[0].strip() def reqs(*f): return list(filter(None, [strip_comments(l) for l in open( os.path.join(os.getcwd(), *f)).readlines()])) def get_version(version_tuple): if not i...
LL_REQUIRES = reqs('requirement
s.txt') README = open(os.path.join(os.path.dirname(__file__), 'README.md')).read() PACKAGES = find_packages('src') PACKAGE_DIR = {'': 'src'} setup( name='python-gmaps', version=VERSION, author='Michał Jaworski', author_email='[email protected]', description='Google Maps API client', long_desc...
lefnire/tensorforce
tensorforce/core/preprocessors/normalize.py
Python
apache-2.0
1,635
0.001835
# Copyright 2017 reinforce.io. 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 # # Unle
ss required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ========...
dfm/twitterick
twitterick/syllabifier.py
Python
mit
6,769
0.027921
# # Retrieved from: https://svn.code.sf.net/p/p2tk/code/python/syllabify/syllabifier.py # on 2014-09-05. # # According to https://www.ling.upenn.edu/phonetics/p2tk/, this is licensed # under MIT. # # This is the P2TK automated syllabifier. Given a string of phonemes, # it automatically divides the phonemes into syllab...
of phonemes from the CMU pronouncing dictionary set (with optional stress numbers after vowels), or a Python li
st of phonemes, e.g. "B AE1 T" or ["B", "AE1", "T"]''' if type(word) == str : word = word.split() syllables = [] # This is the returned data structure. internuclei = [] # This maintains a list of phonemes between nuclei. for phoneme in word : phoneme = phoneme.strip() if phoneme == "" : continue ...