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
dnorth/BZRFlag
src/kalman_pigeon.py
Python
gpl-3.0
4,604
0.006516
from bzrc import BZRC, Command import math, numpy, argparse from numpy import dot from random import randint from time import sleep desc=''' Example: python kalman_pigeon.py -p localhost -s 57413 -t [1, 2, 3] ''' class Point(): def __init__(self, x, y): self.x = x self.y = y # self...
arget_y): x = 1000 y = 1000 while True: x = randint(target_x-300, target_x+300) y = randint(target_y-300, target_x+300) if getDistance(Point(x, y), Point(target_x, target_y)) <= 325: return Point(x, y) def readCommandLine(): parser
= argparse.ArgumentParser(description=desc, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument('--host', '-p', required=True, default='localhost', help='Hostname to connect to') parser.add_argument('--socket', '-s', required=True, default=0, help='Team socket to connect to') parser.ad...
zzeleznick/zDjango
venv/lib/python2.7/site-packages/pystache/tests/main.py
Python
mit
5,854
0.000342
# coding: utf-8 """ Exposes a main() function that runs all tests in the project. This module is for our test console script. """ import os import sys import unittest from unittest import TestCase, TestProgram import pystache from pystache.tests.common import PACKAGE_DIR, PROJECT_DIR, UNITTEST_FILE_PREFIX from pys...
de # the spec t
est directory). print("pystache: skipping spec tests: spec test directory " "not found") else: spec_test_dir = _spec_test_dir if len(sys_argv) <= 1 or sys_argv[-1].startswith("-"): # Then no explicit module or test names were provided, so ...
Parkayun/flask
tests/test_appctx.py
Python
bsd-3-clause
4,034
0.003966
# -*- coding: utf-8 -*- """ tests.appctx ~~~~~~~~~~~~ Tests the application context. :copyright: (c) 2016 by Armin Ronacher. :license: BSD, see LICENSE for more details. """ import pytest import flask def test_basic_url_generation(): app = flask.Flask(__name__) app.config['SERVER_NAME'...
pp.teardown_request def teardown_req(error=None): called.append('request') @app.teardown_appcontext def teardown_app(error=None): called.append('app') @app.route('/') def index(): with flask._app_ctx_stack.top: with flask._request_ctx_stack.
top: pass env = flask._request_ctx_stack.top.request.environ assert env['werkzeug.request'] is not None return u'' c = app.test_client() res = c.get('/') assert res.status_code == 200 assert res.data == b'' assert called == ['request', 'app']
djangonauts/django-hstore
django_hstore/__init__.py
Python
mit
443
0
VERS
ION = (1, 5, 0, 'alpha') __version__ = VERSION def get_version(): version = '%s.%s' % (VERSION[0], VERSION[1]) if VERSION[2]: version = '%s.%s' % (version, VERSION[2]) if VERSION[3:] == ('alpha', 0): version = '%s pre-alpha' % version else: if VERSION[3] != 'final': ...
oreConfig'
chop-dbhi/varify-data-warehouse
vdw/variants/migrations/0013_auto__add_unique_evs_variant__add_unique_thousandg_variant.py
Python
bsd-2-clause
18,006
0.008053
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding unique constraint on 'EVS', fields ['variant'] db.create_unique('evs', ['variant_id']) # A...
egerField', [], {'primary_key': 'True'}) }, 'phenotypes.phenotype': { 'Meta': {'object_name': 'Phenotype', 'db_table': "'phenotype'"}, 'articles': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['literature.PubMed']", 'symmetrical': 'False'}), 'des...
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'term': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '1000'}) }, 'variants.effect': { 'Meta': {'ordering': "['order']", 'object_name': 'Effect', 'db_table': "'effect...
thiagopena/PySIGNFe
pysignfe/nfse/bhiss/v10/ConsultarLoteRps.py
Python
lgpl-2.1
2,448
0.009395
# -*- coding: utf-8 -*- from pysignfe.xml_sped import * from .ConsultarSituacaoLoteRps import ListaMensagemRetorno from .Rps import IdentificacaoPrestador, IdentificacaoRps from .Nfse import CompNfse import os DIRNAME = os.path.dirname(__file__) class ConsultarLoteRpsEnvio(XMLNFe): def _...
LoteRpsEnvio, self).__init__() self.versao = TagDecimal(nome=u'ConsultarLoteRpsEnvio', propriedade=u'versao', namespace=NAMESPACE_NFSE, valor=u'1.00', raiz=u'/') self.Prestador = IdentificacaoP
restador() self.Protocolo = TagCaracter(nome=u'Protocolo', tamanho=[ 1, 50], raiz=u'/') self.caminho_esquema = os.path.join(DIRNAME, u'schema/') self.arquivo_esquema = u'nfse.xsd' def get_xml(self): xml = XMLNFe.get_xml(self) xml += ABERTURA xml += u'<ConsultarL...
skylines-project/skylines
migrations/env.py
Python
agpl-3.0
2,099
0.000476
from __future__ import with_statement from alembic import context from sqlalchemy import engine_from_config, pool from logging.config import fileConfig # this is the Alembic Config object, which provides # access to the values within the .ini file in use. config = context.config # Interpret the config file for Python...
le_name) # add your model's MetaData object here # for 'autogenerate' support # from myapp import mymodel # target_metadata = mymodel.Base.metadata from flask import current_app config.set_main_option( "sqlalchemy.url", current_app.config.get("SQLALCHEMY_DATABASE_URI") ) target_metadata = current_app.extensions["...
option") # ... etc. def run_migrations_offline(): """Run migrations in 'offline' mode. This configures the context with just a URL and not an Engine, though an Engine is acceptable here as well. By skipping the Engine creation we don't even need a DBAPI to be available. Calls to context.exe...
katmagic/arm
src/interface/torrcPanel.py
Python
gpl-3.0
9,156
0.014963
""" Panel displaying the torrc or armrc with the validation done against it. """ import math import curses import threading from util import conf, panel, torConfig, uiTools DEFAULT_CONFIG = {"features.config.file.showScrollbars": True, "features.config.file.maxLinesPerEntry": 8} # TODO: The armrc ...
ULT): lineComp["option"][1] = curses.A_BOLD | uiTools.getColor("blue") lineComp["argument"][1] = curses.A_BOLD | uiTools.getColor("blue") elif lineIssue == torConfig.VAL_MISMATCH: lineComp["argument"][1] = curses.A_BOLD | uiTool
s.getColor("red") lineComp["correction"][0] = " (%s)" % lineIssueMsg else: # For some types of configs the correction field is simply used to # provide extra data (for instance, the type for tor state fields). lineComp["correction"][0] = " (%s)" % lineIssueMsg l...
moreati/ppeg
pegmatcher.py
Python
mit
3,520
0.012784
from _ppeg import Pattern as P class Var: def __getattr__(self, name): return P.Var(name) V = Var() EndOfFile = P(-1) EndOfLine = P("\r\n") | P("\r") | P("\n") Space = P(" ") | P("\t") | V.EndOfLine Comment = P("#") + (-V.EndOfLine + P(1))**0 + V.EndOfLine Spacing = (V.Space | V.Comment)...
S) ** -1 + V.Spacing Prefix = (V.AND | V.NOT)**-1 + V.Suffix Sequence = V.Prefix**0 Expression = V.Sequence + (V.SLASH + V.Sequence)**0 Definition = V.Identifier + V.LEFTARROW + V.Expression Grammar = V.Spacing + V.
Definition**1 + V.EndOfFile PEG = P.Grammar( start="Grammar", Grammar=Grammar, Definition=Definition, Expression=Expression, Sequence=Sequence, Prefix=Prefix, Suffix=Suffix, Primary=Primary, Identifier=Identifier, IdentStart=IdentStart, IdentCont=IdentCont, Literal=Liter...
geobricks/geobricks_trmm
geobricks_trmm/__init__.py
Python
gpl-2.0
170
0.005882
__package__ = 'geobricks_trmm' __author__ = 'Barbaglia, Guido -
Murzilli, Simone' __email__ = 'guido.barbaglia@gmail.com; simone.murzil
li@gmail.com;' __license__ = 'GPL2'
kgn/cssutils
src/cssutils/css/property.py
Python
gpl-3.0
18,511
0.002323
"""Property is a single CSS property in a CSSStyleDeclaration.""" __all__ = ['Property'] __docformat__ = 'restructuredtext' __version__ = '$Id$' from cssutils.helper import Deprecated from value import PropertyValue import cssutils import xml.dom class Property(cssutils.util.Base): """A CSS property in a StyleDec...
lf._log.error(u'Property: No property name found: %r.' % self._valuestr(cssText)) cssText = property(fget=_getC
ssText, fset=_setCssText, doc="A parsable textual representation.") def _setName(self, name): """ :exceptions: - :exc:`~xml.dom.SyntaxErr`: Raised if the specified name has a syntax error and is unparsable. """ # for closures: must be ...
anthraxx/diffoscope
tests/comparators/test_fonts.py
Python
gpl-3.0
1,846
0.002713
# -*- coding: utf-8 -*- # # diff
oscope: in-depth comparison of files, archives, and directories # # Copyright © 2015 Jérémy Bobbio <lunar@debian.org> # # diffoscope 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 Lice...
ful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with diffoscope. If not, see <https://www.gnu.org/licenses/>...
McKenzieKohn/scopus_spider
setup.py
Python
mit
604
0.009934
from setuptools import setup def readme(): with open('README.rst') as f: return f.read() setup(name='scopus_spider', version='0.1',
description='Search and scrape scopus database', long_description=readme(), url='', author='Robert Vesco', author_email='rv_spam@hotmail.com', license='MIT', packages=['scopus_spider','scopus_spider.scraping'], z
ip_safe=False, entry_points = { 'console_scripts': ['scopus_spider=scopus_spider.command_line:main'], }, install_requires=[ 'sys', ], )
ParadropLabs/Paradrop
paradrop/daemon/paradrop/base/cxbr.py
Python
apache-2.0
7,211
0.002496
''' Wamp utility methods. ''' from autobahn.twisted import wamp, websocket from autobahn.twisted.wamp import ApplicationSession from autobahn.wamp.types import ComponentConfig from twisted.internet import reactor from twisted.internet.defer import inlineCallbacks, Deferred from twisted.internet.protocol import Reconne...
lf, connector, reason): out.info("Connection lost with reason: " + str(reason)) ReconnectingClientFactory.clientConnectionLost(self, connector, reason) class BaseSessionFactory(wamp.ApplicationSessionFactory): def __init_
_(self, config, deferred=None): super(BaseSessionFactory, self).__init__(config) self.dee = deferred def __call__(self, *args, **kwargs): sess = super(BaseSessionFactory, self).__call__(*args, **kwargs) sess.dee = self.dee return sess class BaseSession(ApplicationSession):...
artdent/mingus-python3
mingus/midi/Sequencer.py
Python
gpl-3.0
14,289
0.002869
#!/usr/bin/python # -*- coding: utf-8 -*- """ ================================================================================ mingus - Music theory Python package, general purpose sequencer Copyright (C) 2008-2009, Bart Spaans This program is free software: you can redistribute it and/or modify ...
.play_Note(note, channel, velocity): return False return Tru
e def stop_NoteContainer(self, nc, channel=1): """Stops playing the notes in NoteContainer nc.""" self.notify_listeners(self.MSG_PLAY_NC, {'notes': nc, 'channel' : channel}) if nc is None: return True for note in nc: if not self...
edx/django-openid-auth
example_consumer/urls.py
Python
bsd-2-clause
2,002
0
# django-openid-auth - OpenID integration for django.contrib.auth # # Copyright (C) 2007 Simon Willison # Copyright (C) 2008-2013 Canonical Ltd. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions o...
S OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. try: from django.urls import path, include, url except ImportError: from django.conf.urls import include, url from django.contrib import admin from django.contrib.auth import logout from exam...
eufarn7sp/egads-eufar
egads/algorithms/transforms/isotime_to_seconds.py
Python
bsd-3-clause
5,348
0.012528
__author__ = "mfreer" __date__ = "2012-07-06 17:42" __version__ = "1.3" __all__ = ['IsotimeToSeconds'] import egads.core.egads_core as egads_core import egads.core.metadata as egads_metadata import dateutil.parser import datetime from convert_time_format import convert_time_format class IsotimeToSeconds(egads_core.Eg...
sforms PURPOSE Calculates seconds elapsed from a series of ISO 8601 date/time strings DESCRIPTION Calculates seconds elapsed from a series of ISO 8601 date/time strings (yyyymmddThhmmss, yyyy-mm-ddThh:mm:ss,yyyymmdd or similar) using the Python dateutil and datetime modul...
ymmddThhmmss ISO 8601 date-time string yyyymmdd ISO 8601 date string t_ISO_ref string, optional Reference time (ISO 8601 string). default is 1970010...
kovidgoyal/kitty
kittens/broadcast/main.py
Python
gpl-3.0
4,940
0.001619
#!/usr/bin/env python # License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net> import sys from base64 import standard_b64e
ncode from gettext import gettext as _ from typing import Any, Dict, List, Optional, Tuple from kitty.cli import parse_args from k
itty.cli_stub import BroadcastCLIOptions from kitty.key_encoding import encode_key_event from kitty.rc.base import MATCH_TAB_OPTION, MATCH_WINDOW_OPTION from kitty.remote_control import create_basic_command, encode_send from kitty.short_uuid import uuid4 from kitty.typing import KeyEventType, ScreenSize from ..tui.han...
nephila/djangocms-blog
djangocms_blog/migrations/0013_auto_20160201_2235.py
Python
bsd-3-clause
514
0.001946
# Generated by Django 1.9.2 on 2016-02-01 21:35 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [
("djangocms_blog", "0012_auto_20151220_1734"), ] operations = [ migrations.AlterField( model_name="post", name="categories",
field=models.ManyToManyField( blank=True, related_name="blog_posts", to="djangocms_blog.BlogCategory", verbose_name="category" ), ), ]
Cinntax/home-assistant
homeassistant/components/hue/light.py
Python
apache-2.0
15,809
0.000506
"""Support for the Philips Hue lights.""" import asyncio from datetime import timedelta import logging from time import monotonic import random import aiohue import async_timeout from homeassistant.helpers.entity_registry import async_get_registry as get_ent_reg from homeassistant.helpers.device_registry import async...
# Assistant and take control ourselves. This works great for polling as now # we trigger from 1 time update an update to all entities. However it gets # tricky from i
nside async_turn_on and async_turn_off. # # If automatic polling is enabled, Home Assistant will call the entity # update method after it is done calling all the services. This means that # when we update, we know all commands have been processed. If we trigger # the update from inside async_turn_on...
xmunoz/rubberband
rubberband/handlers/common/__init__.py
Python
mit
1,084
0.000923
"""Common methods f
or request handlers.""" from rubberband.models import TestSet def search(query): """ Execute a search to elasticsearch database, gives by default the 100 first results. Parameters ---------- query : dict Search parameters Results ------- Response elasticsearch-dsl Res...
) if "tags" in query: tags = query["tags"] tags = tags.split(",") tags = list(map(str.strip, tags)) s = s.filter("terms", tags=tags) del(query["tags"]) # return 100 items unless a limit is explicitly set limit = query.pop("limit", None) or 100 limit = int(limit)...
RodrigoToledoA/Blog
blog/urls.py
Python
gpl-2.0
1,094
0.015539
from django.conf.urls import patterns, include, url urlpatterns = patterns('', url(r'^$', 'blog.views.home', name='home'), url(r'^ver_post/(?P<id_post>[0-9]+)/$', 'blog.views.ver_post', name='vermipost'), url(r'^contactame/$', 'blog.views.contact', na...
g.views.curriculum', name='curriculum'), url(r'^contacto/$', 'blog.views.contacto', name='contacto')
)
RIPE-NCC/ripe-atlas-cousteau
ripe/atlas/cousteau/api_meta_data.py
Python
gpl-3.0
6,704
0.000895
# Copyright (c) 2015 RIPE NCC # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any
later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied war
ranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from datetime import datetime from dateutil.tz import tzut...
RaoUmer/django
tests/modeltests/invalid_models/invalid_models/models.py
Python
bsd-3-clause
29,360
0.004564
#encoding=utf-8 """ 26. Invalid models This example exists purely to point out errors in models. """ from __future__ import unicode_literals from django.db import connection, models class FieldErrors(models.Model): charfield = models.CharField() charfield2 = models.CharField(max_length=-1) charfield3 =...
odel): tgt_safe = models.CharField(max_length=10) clash1 = models.CharField(max_length=10) clash2 = models.C
harField(max_length=10) clash1_set = models.CharField(max_length=10) class Clash1(models.Model): src_safe = models.CharField(max_length=10) foreign = models.ForeignKey(Target) m2m = models.ManyToManyField(Target) class Clash2(models.Model): src_safe = models.CharField(max_length=10) forei...
ConstantinT/jAEk
crawler/tests/databasetest.py
Python
gpl-3.0
7,988
0.012271
''' Copyright (C) 2015 Constantin Tschuertz 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 any later version. This program is distributed in the hope that it wi...
orm = HtmlForm([form_input1,form_input2], TEST_URL1, "POST", dom_address= None) self.database.insert_form(SESSION,form, WEBPAGE_ID) self.assertEqual(self.database.forms.count(), 2) def te
st_web_page_extend_ajax(self): web_page = deepcopy(WEBPAGE) clickable = deepcopy(CLICKABLE) web_page.clickables.extend([clickable]) self.database.insert_page_into_db(SESSION, web_page) ajax = deepcopy(AJAXREQUEST) self.database.extend_ajax_requests_to_webpage(SESSION, web...
ofaurax/LeechCoin
leechcoin.py
Python
gpl-3.0
12,394
0.010999
#!/usr/bin/env python # coding=utf-8 import argparse import urllib2 # python 2.7 import re import sqlite3 import traceback import datetime import csv headers = { 'User-Agent' : 'Mozilla/5.0 (compatible; Googlebot/2.1;' +' +http://www.google.com/bot.html)' } ...
,') tmp = c.fetchone() for cpi in cp: for i in range(page, 0, -1): print 'Leech', cpi, i leechpage(i,c
pi) if cmd == 'stats': try: cp = int(args.params[0]) except: cp = 0 conn = sqlite3.connect(database) c = conn.cursor() prix_m2_cp = {} prix_m2_cp_pro = {} if cp: c.execute('SELECT * FROM apparts WHERE cp=?', (cp,)) else: c.execute('SELECT * FROM appar...
obi-two/Rebelion
data/scripts/templates/object/tangible/shipcontrol/shared_shipcontrol_corvette.py
Python
mit
472
0.04661
#### NOTICE: THI
S 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 = Tangible() result.template = "object/tangible/shipcontrol/shared_shipcontrol_corvette.iff" result.attribute_template_id = 8 result.stfName("space/space_item","shipcontrol_corvette") #### BEGIN MODIFICATIONS #### #### END MODIFICATIONS #### return result
aarongarrett/inspyred
inspyred/ec/variators/variators.py
Python
mit
1,660
0.008434
""" ================ :mod:`variators` ================ .. Copyright 2012 Aaron Garrett .. 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...
AUTHORS OR COPYRIGHT HOLDERS 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 OR OTHER DEALINGS IN THE SOFTWARE. .. module:: variators .. moduleautho...
thout variation. .. Arguments: random -- the random number generator object candidates -- the candidate solutions args -- a dictionary of keyword arguments """ return candidates
mjtamlyn/django-denorm
setup.py
Python
bsd-3-clause
1,083
0.001847
#!/usr/bin/python from setuptools import setup setup( name='django-denorm', version='0.2.0', description='Denormalization magic for Django', long_description='django-denorm is a Django application to provide automatic management of deno
rmalized database fields.', author=', '.
join(( 'Christian Schilling <initcrash@gmail.com>', 'James Turnbull <james@incuna.com>', )), author_email='django-denorm@googlegroups.com', url='http://initcrash.github.com/django-denorm/', download_url='http://github.com/initcrash/django-denorm/downloads', classifiers=[ "Dev...
msarfati/dodecahedron
dodecahedron/tests/fixtures.py
Python
mit
318
0
from .. import models import datetime def typical_user(): username = 'alice' if
not
models.User.query.filter_by(username=username).first(): return models.User.register( username=username, password='qqq', confirmed=True, ) def typical_dataset(): pass
Smarsh/django
tests/regressiontests/multiple_database/models.py
Python
bsd-3-clause
1,653
0.004235
from django.conf
import settings from django.contrib.auth.models import User from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes import generic from django.db import models class Review(models.Model): source = models.CharField(max_length=100) content_type = mode
ls.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = generic.GenericForeignKey() def __unicode__(self): return self.source class Meta: ordering = ('source',) class PersonManager(models.Manager): def get_by_natural_key(self, name): return se...
Bitergia/allura
scripts/scrub-allura-data.py
Python
apache-2.0
4,865
0.002672
import logging import sys from ming.orm import ThreadLocalORMSession import mock from pylons import c, g from allura import model as M from forgediscussion import model as DM from forgetracker import model as TM from allura.lib import utils log = logging.getLogger(__name__) def public(obj, project=None): if n...
if not options.dry_run: p.delete() return for ac in p.app_configs: ac.project = p c.app = p.app_instance(ac) mount_point = ac.options.get('mount_point') tool_name = ac.tool_name.lower() if tool_name in ('admin', 'search', 'profile'):
continue if not public(ac, project=p): log.info('%s tool %s/%s on project "%s"' % ( preamble, tool_name, mount_point, p.shortname)) if not options.dry_run: p.uninstall_app(mount_point) continue q = dict(app_config_id=ac._id) ...
TheVirtualLtd/bda.plone.discount
src/bda/plone/discount/tests/test_discount.py
Python
bsd-3-clause
592
0
# -*- coding: utf-8 -*- from bda.plone.discount import UUID_PLONE_ROOT from bda.plone.discount.tests import Discount_INTEGRATION_TESTING from bda.plone.discount.tests import set_browserlayer from plone.uuid.interfaces import IUUID impor
t unittest2 as unittest class TestDiscount(unittest.TestCase): layer = Discount_INTEGRATION_TESTING def setUp(self): self.portal = self.layer['portal'
] self.request = self.layer['request'] set_browserlayer(self.request) def test_plone_root_uuid(self): self.assertEquals(IUUID(self.portal), UUID_PLONE_ROOT)
jon2718/ipycool_2.0
section.py
Python
mit
1,443
0.002772
from regularregioncontainer import * class Section(RegularRegionContainer): """ SECTION Start of cooling section region definition. The data must end with an ENDSECTION. It can enclose any number of other commands. If it is desired to repeat the section definitions, the control variable NSECTIONS s...
utput', 'Refp', 'Ref2', 'Reset',
'RKick', 'Rotate', 'Tilt', 'Transport', 'Comment', 'Repeat', ] command_params = { } def __init__(self, **kwargs): ICoolObject.check_command_params_init(self, Section.command_params, **kwargs) Container.__init__(self) def __setattr__(sel...
theheros/kbengine
kbe/res/scripts/common/Lib/test/test_sys.py
Python
lgpl-3.0
32,876
0.001764
import unittest, test.support import sys, io, os import struct import subprocess import textwrap import warnings import operator import codecs # count the number of test runs, used to create unique # strings to intern in test_intern() numruns = 0 try: import threading except ImportError: threa...
l(out.getvalue(), "") self.assertTrue(not hasattr(builtins, "_")) dh(42)
self.assertEqual(out.getvalue(), "42\n") self.assertEqual(builtins._, 42) del sys.stdout self.assertRaises(RuntimeError, dh, 42) def test_lost_displayhook(self): del sys.displayhook code = compile("42", "<string>", "single") self.assertRaises(Runti...
sdispater/orator-cache
orator_cache/cache.py
Python
mit
197
0
# -*- coding: utf-8
-*- from cachy import CacheManager from cachy.serializers import PickleSerializer class Cache(CacheManager): _serializers = { 'pickle': P
ickleSerializer() }
rambler-digital-solutions/aioriak
aioriak/tests/base.py
Python
mit
1,399
0
import asyncio from aioriak import RiakClient from aioriak.tests import HOST, PORT import unittest import random class IntegrationTest: @classmethod def randname(cls, length=12): out = '' for i in range(length): out += chr(random.randint(ord('a'), ord('z'))) return out ...
ST port = port or PORT return self.loop.run_until_complete( RiakClient.create(host, port, loop=self.loop, **client_args)) async def async_create_client(self, host=None, port=None, **client_args): host = host or HOST port = port or PORT ...
**client_args) def setUp(self): super().setUp() asyncio.set_event_loop(None) self.loop = asyncio.new_event_loop() self.client = self.create_client() def tearDown(self): super().tearDown() self.client.close() self.loop.stop() s...
mgp/coding-in-the-real-world-code-samples
code-samples/ch-bittorrent-client-case-study/use_parseargs.py
Python
apache-2.0
196
0.010204
from parseargs import parseargs opts, args = parseargs(('arg1 --opt1 val1 arg2'.split()), (('opt1', 'default1',
''), ('opt2', 'default2', ''))) print 'opts=%
s' % opts print 'args=%s' % args
ibotdotout/coe-pairing
tests/poker_hands_test.py
Python
mit
13,620
0
# http://www.codingdojo.org/cgi-bin/index.pl?KataPokerHands import poker_hands as pk import unittest class PokerHandsTest(unittest.TestCase): def test_case_1_should_lose_high_card_ace(self): a = ["2H", "3D", "5S", "9C", "KD"] b = ["2C", "3H", "4S", "8C", "AH"] result = pk.poker_hands(a, ...
(cards) self.assertEqual(False, answer) def test_give_straight_flush_should_false(self): cards = ["TC", "JC", "QC", "KC", "AC"] answer = pk.is_flush_rank(cards) self.assertEqual(False, answer) class CheckStraightTest(unittest.TestCase): def test_give_straight_flush_should_fal...
self.assertEqual(False, answer) def test_give_10_J_Q_K_A_should_ture(self): cards = ["TC", "JD", "QH", "KC", "AH"] answer = pk.is_straight_rank(cards) self.assertEqual(True, answer) def test_give_2_to_6_should_true(self): cards = ["2C", "3D", "4H", "5C", "6H"] ...
vritant/subscription-manager
src/initial-setup/com_redhat_subscription_manager/ks/rhsm_ks.py
Python
gpl-2.0
1,679
0
# # Copyright (C) 2015 Red Hat, Inc. # # This
copyrighted material is made available to anyone wishing to use, # mod
ify, copy, or redistribute it subject to the terms and conditions of # the GNU General Public License v.2, or (at your option) any later version. # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY expressed or implied, including the implied warranties of # MERCHANTABILITY or FI...
111pontes/ydk-py
cisco-ios-xr/ydk/models/cisco_ios_xr/Cisco_IOS_XR_ipv4_acl_cfg.py
Python
apache-2.0
83,998
0.018227
""" Cisco_IOS_XR_ipv4_acl_cfg This module contains a collection of YANG definitions for Cisco IOS\-XR ipv4\-acl package configuration. This module contains definitions for the following management objects\: ipv4\-acl\-and\-prefix\-list\: IPv4 ACL configuration data Copyright (c) 2013\-2016 by Cisco Systems, Inc. ...
fset settings **type**\: :py:class:`FragmentOffset <ydk.models.cisco_ios_xr.Cisco_IOS_XR_ipv4_acl_cfg.Ipv4AclAndPrefixList.Accesses.Access.AccessListEntries.AccessListEntry.FragmentOffset>` .. attribute:: fra
gments Check non\-initial fragments. Item is mutually exclusive with TCP, SCTP, UDP, IGMP and ICMP comparions and with logging **type**\: :py:class:`Empty<ydk.types.Empty>` .. attribute:: grant ...
1995parham/Learning
python/calc-with-tokenizer/calc.py
Python
gpl-2.0
2,753
0.001816
from typing import NamedTuple, Iterable, Union import re class Token(NamedTuple): type: str value: Union[str, float, int] column: int def tokenize(expression: str) -> Iterable[Token]: token_specification = [ ('NUMBER', r'\d+(\.\d*)?'), ('OPEN_PARN', r'\('), ('CLOSE_PARN', ...
cation) for mo in re.finditer(tok_regex, expression): kind = mo.lastgroup value = mo.group()
column = mo.start() if kind == 'NUMBER': value = float(value) if '.' in value else int(value) elif kind == 'SKIP': continue elif kind == 'MISMATCH' or kind is None: raise RuntimeError(f'{value!r} unexpected on {column}') yield Token(kind, valu...
arju88nair/projectCulminate
venv/lib/python3.5/site-packages/pylint/test/functional/reimported.py
Python
apache-2.0
540
0.009259
# pylint: disable=missing-docstring,unused-import,import-error, wildcard-import,unused-wildcard-impo
rt,redefined-builtin,no-name-in-module,ungrouped-imports,wrong-import-order from time import sleep, sleep # [reimported] from lala import missing, missing # [reimported] import missing1 import missing1 # [reimported] from collections import deque from itertools import deque # [reimported] from collection...
import OrderedDict from itertools import OrderedDict as NotOrderedDict from itertools import * from os import *
Kriechi/mitmproxy
test/mitmproxy/addons/test_save.py
Python
mit
3,060
0.000327
import pytest from mitmproxy.test import taddons from mitmproxy.test import tflow from mitmproxy import io from mitmproxy import exceptions from mitmproxy.addons import save from mitmproxy.addons import view def test_configure(tmpdir): sa = save.Save() with taddons.context(sa) as tctx: with pytest.r...
e_stream_file=None) assert len(rd(p)) == 2 def test_save_command(tmpdir): sa = save.Save() with taddons.context() as tctx: p = str(tmpdir.join("foo")) sa.save([tflow.tflow(resp=True)], p) assert len(rd(p)) == 1
sa.save([tflow.tflow(resp=True)], p) assert len(rd(p)) == 1 sa.save([tflow.tflow(resp=True)], "+" + p) assert len(rd(p)) == 2 with pytest.raises(exceptions.CommandError): sa.save([tflow.tflow(resp=True)], str(tmpdir)) v = view.View() tctx.master.addons.a...
corvorepack/REPOIVAN
plugin.video.tv.ultra.7k/resources/regex/directwatch.py
Python
gpl-2.0
6,185
0.038835
# -*- coding: utf-8 -*- #------------------------------------------------------------ # TV Ultra 7K Regex de direct2watch # Version 0.1 (02.11.2014) #------------------------------------------------------------ # License: GPL (http://www.gnu.org/licenses/gpl-3.0.html) # Gracias a la librería plugintools de Jesús (www.m...
://watch.direct2watch.com/direct2watch' url_user["swfurl"]='http://www.direct2watch.com/player/player2.swf' # Construimos diccionario... url = params.get("url") url_extracted = url.split(" ") for entry in url_extracted: if entry.startswith("playpath"): entry = entry...
ith("pageUrl"): pageurl = entry.replace("pageUrl=", "") pageurl = pageurl.replace("&amp;", "&") url_user["pageurl"]=pageurl elif entry.startswith("token"): entry = entry.replace("token=", "") url_user["token"]=entry elif entry.startsw...
sourcepole/qgis
qgis/python/plugins/GdalTools/tools/doGrid.py
Python
gpl-2.0
8,154
0.015085
# -*- coding: utf-8 -*- from PyQt4.QtCore import * from PyQt4.QtGui import * from qgis.core import * from qgis.gui import * from osgeo import ogr from ui_widgetGrid import Ui_GdalToolsWidget as Ui_Widget from widgetPluginBase import GdalToolsBasePluginWidget as BasePluginWidget import GdalTools_utils as Utils class G...
Filter(), lastUsedFilter ) if outputFile.isEmpty(): return Utils.FileFilter.setLastUsedRasterFilter(lastUsedFilter) self.outputFormat = Utils.fillRasterOutputFormat( lastUsedFilter, outputFile ) self.outputFileEdit.setText(outputFile) def getArguments(self): arguments = QString...
st() if self.zfieldCheck.isChecked() and self.zfieldCombo.currentIndex() >= 0: arguments << "-zfield" arguments << self.zfieldCombo.currentText() if self.inputLayerCombo.currentIndex() >= 0: arguments << "-l" arguments << QFileInfo(self.layers[ self.inputLayerCombo.currentInd...
Vagab0nd/SiCKRAGE
lib3/guessit/rules/properties/other.py
Python
gpl-3.0
16,391
0.00421
#!/usr/bin/env python # -*- coding: utf-8 -*- """ other property """ import copy from rebulk import Rebulk, Rule, RemoveMatch, RenameMatch, POST_PROCESS, AppendMatch from rebulk.remodule import re from ..common import dash from ..common import seps from ..common.pattern import is_disabled from ..common.validators imp...
', tags=['at-end', 'not-a-release-group']) rebulk.string('Extras', value='Extras', tags='has-neighbor') rebulk.regex('Digital-?Extras?', value='Extras') rebulk.string('Proof', value='Proof', tags=['at-end', 'not-a-release-group']) rebulk.str
ing('Obfuscated', 'Scrambled', value='Obfuscated', tags=['at-end', 'not-a-release-group']) rebulk.string('xpost', 'postbot', 'asrequested', value='Repost', tags='not-a-release-group') rebulk.rules(RenameAnotherToOther, ValidateHasNeighbor, ValidateHasNeighborAfter, ValidateHasNeighborBefore, V...
pypa/warehouse
tests/functional/manage/test_views.py
Python
apache-2.0
1,614
0.001239
# 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 Li...
"public_email": ""}) views.ManageAccountViews(db_request).save_account() user = user_service.get_user(user.id)
assert user.name == "new name" assert user.public_email is None
messense/wechatpy
wechatpy/client/api/cloud.py
Python
mit
12,240
0.000371
# -*- coding: utf-8 -*- import json from enum import IntEnum import requests from wechatpy.client.api.base import BaseWeChatAPI class FileType(IntEnum): JSON = 1 CSV = 2 class ConflictMode(IntEnum): INSERT = 1 UPSERT = 2 class WeChatCloud(BaseWeChatAPI): API_BASE_URL = 'https://api.weixin.q...
"" return self._post( 'tcb/databasequery', data={ 'env': env, 'query': query, } ) def db_aggregate(self, env, query): """ 数据库聚合 详情请参考 https://devel
opers.weixin.qq.com/miniprogram/dev/wxcloud/reference-http-api/database/databaseAggregate.html :param env: 云开发环境 ID :param query: 数据库操作语句 :return: 返回记录列表 """ return self._post( 'tcb/databaseaggregate', data={ 'env': env, 'q...
thelostt/reddit-weekly
rewe.py
Python
mit
5,215
0.00441
#!/bin/python3 import praw import smtplib import requests import parsel import re import io import json import os from email.header import Header from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from argparse import ArgumentParser from premailer import Premailer HEADERS = requests....
, encoding='utf-8') as f: return weekly_page(subreddit, file=f, css=css) r = requests.get("https://www.reddit.com/r/{}/top/?sort=top&t=week".format(subreddit), headers=HEADERS) if r.status_code != 200: ra
ise RuntimeError("Request status code is {}.".format(r.status_code)) if r.encoding.lower() != 'utf-8': raise RuntimeError("Request didn't return a UTF-8 output.") sel = parsel.Selector(text=r.text) file.write('<!DOCTYPE html>') file.write('<html>') if css == 1: # Download External ...
Microvellum/Fluid-Designer
win64-vc/2.78/scripts/startup/bl_ui/properties_data_mesh.py
Python
gpl-3.0
15,183
0.003227
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distrib...
s=False)
elif index > 0: row.prop(key_block, "value", text="", emboss=False) else: row.label(text="") row.prop(key_block, "mute", text="", emboss=False) elif self.layout_type == 'GRID': layout.alignment = 'CENTER' layout.label(text...
ThunderGemios10/The-Super-Duper-Script-Editor
setup_wizard.py
Python
gpl-3.0
22,165
0.0185
################################################################################ ### Copyright © 2012-2013 BlackDragonHunt ### ### This file is part of the Super Duper Script Editor. ### ### The Super Duper Script Editor is free software: you can redistribute it ### and/or modify it under the terms of the GNU Genera...
[0][1:] for line in file_order.readlines() if not line == ""] for filename in file_list: full_name = os.path.join(iso_dir, filename) if not os.path.isfile(full_name): validated = False
self.show_error("%s missing from ISO directory." % full_name) break if not validated: return self.iso_dir = iso_dir self.show_info("ISO directory looks good.") self.ui.grpStep1.setEnabled(False) self.ui.grpStep2.setEnabled(True) ###############################...
OliverCole/ZeroNet
src/Content/ContentDbDict.py
Python
gpl-2.0
4,975
0.001206
import time import os import ContentDb from Debug import Debug from Config import config class ContentDbDict(dict): def __init__(self, site, *args, **kwargs): s = time.time() self.site = site self.cached_keys = [] self.log = self.site.log self.db = ContentDb.getContentDb()...
il.Process(os.getpid())
s_mem = process.memory_info()[0] / float(2 ** 20) root = "data-live/1MaiL5gfBM1cyb4a8e3iiL8L5gXmoAJu27" contents = ContentDbDict("1MaiL5gfBM1cyb4a8e3iiL8L5gXmoAJu27", root) print "Init len", len(contents) s = time.time() for dir_name in os.listdir(root + "/data/users/")[0:8000]: contents["d...
MetaArchive/metaarchive-qa-tools
lockss-manifest-validate/lockss-manifest-validate.py
Python
bsd-3-clause
2,391
0.002928
#!/usr/bin/python """ This is a tool to verify checksum hashes produced by LOCKSS against hashes provided by a BagIt manifest document. Invoke with -h for usage help. Written by Stephen Eisenhauer At University of North Texas Libraries On 2013-04-17 Notes: * The LOCKSS hash list will have more entries than we ac...
S") parser.add_argument('manifest', help="path to the bag manifest (e.g. mybag/manifest-md5.txt") return parser if __name__ == "__main__": parser = _make_arg_parser() args = parser.parse_args() hascus_path = os.path.abspath(args.HashCUS) manifest_path = os.path.abspath(args.manif...
shes)
gjcarneiro/pybindgen
pybindgen/pytypeobject.py
Python
lgpl-2.1
18,888
0.001271
""" The class PyTypeObject generates a PyTypeObject structure contents. """ class PyTypeObject(object): TEMPLATE = ( 'PyTypeObject %(typestruct)s = {\n' ' PyVarObject_HEAD_INIT(NULL, 0)\n' ' (char *) "%(tp_name)s", /* tp_name */\n' ' %(tp_basicsize)s, ...
func) %(nb_rshift)s,\n' '
(binaryfunc) %(nb_and)s,
mineo/picard
test/test_similarity.py
Python
gpl-2.0
339
0
from test.picardtestcase import
PicardTestCase from picard.similarity import similarity class Similarity
Test(PicardTestCase): def test_correct(self): self.assertEqual(similarity(u"K!", u"K!"), 1.0) self.assertEqual(similarity(u"BBB", u"AAA"), 0.0) self.assertAlmostEqual(similarity(u"ABC", u"ABB"), 0.7, 1)
SUSE/azure-sdk-for-python
azure-mgmt-network/azure/mgmt/network/v2017_06_01/models/flow_log_status_parameters.py
Python
mit
1,037
0
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
-------------------------------------------------------------------------- from msrest.serializ
ation import Model class FlowLogStatusParameters(Model): """Parameters that define a resource to query flow log status. :param target_resource_id: The target resource where getting the flow logging status. :type target_resource_id: str """ _validation = { 'target_resource_id': {'req...
alexpilotti/compute-hyperv
hyperv/nova/migrationops.py
Python
apache-2.0
15,767
0
# Copyright 2013 Cloudbase Solutions Srl # 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 r...
=instance) self._check_target_flavor(instance, flavor) self._vmops.power_off(instance, timeout, retry_interval) (disk_files, volume_drives) = self._vmutils.get_vm_storage_paths(instance.name) if disk_files:
self._migrate_disk_files(instance.name, disk_files, dest) self._vmops.destroy(instance, destroy_disks=False) # disk_info is not used return "" def confirm_migration(self, context, migration, instance, network_info): LOG.debug("confirm_migration called", instance=instance) ...
mmpagani/oq-hazardlib
openquake/hazardlib/tests/gsim/convertito_2012_test.py
Python
agpl-3.0
1,218
0
# The Hazard Library # Copyright (C) 2014, GEM Foundation # # 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. # # T...
ICULAR PURPOSE. See the # GNU A
ffero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from openquake.hazardlib.gsim.convertito_2012 import ( ConvertitoEtAl2012Geysers ) from openquake.hazardlib.tests.gsim.u...
ratschlab/ASP
examples/undocumented/python_modular/classifier_mpdsvm_modular.py
Python
gpl-2.0
1,097
0.039198
from tools.load import LoadMatrix lm=LoadMatrix() traindat = lm.load_numbers('../data/fm_train_real.dat') testdat = lm.load_numbers('../data/fm_test_real.dat') label_traindat = lm.load_labels('../data/label_train_twoclass.dat') parameter_list = [[traindat,testdat,label_traindat,1,1e-5],[traindat,testdat,label_trainda...
om shogun.Kernel import GaussianKernel from shogun.Classifier import MPDSVM feats_train=RealFeatures(fm_train_real) feats_test=RealFeatures(fm_test_real) width=2.1 kernel=GaussianKernel(feats_train, feats_train, width) labels=BinaryLabels(label_train_twoclass) svm=MPDSVM(C, kernel, labels) svm.set_epsilon(ep...
vm, predictions.get_labels() if __name__=='__main__': print('MPDSVM') classifier_mpdsvm_modular(*parameter_list[0])
Azure/azure-sdk-for-python
sdk/network/azure-mgmt-network/azure/mgmt/network/v2018_11_01/aio/operations/_inbound_nat_rules_operations.py
Python
mit
22,205
0.004999
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may ...
ode, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat
) return pipeline_response return AsyncItemPaged( get_next, extract_data ) list.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}/inboundNatRules'} # type: ignore async d...
valuehack/scholarium.at
Grundgeruest/migrations/0008_stufe_unterstuetzung.py
Python
mit
1,682
0.003567
# -*- coding: utf-8 -*- # Generated by Django 1.11.6 on 2018-03-27 15:30 from __future__ import unicode_literals import datetime from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('Grundgeruest', '0007_auto_20180323_1503'), ...
=False, verbose_name='ID')), ('datum', models.DateField(default=datetime.date(2018, 3, 27))), ('zahlungsmethode', models.CharField(blank=True, max_length=100)), ('stufe', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='Grundgeruest.Stu
fe')), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='Grundgeruest.ScholariumProfile')), ], options={ 'verbose_name_plural': 'Unterstuetzungen', }, ), ]
donkirkby/live-py-plugin
test/PySrc/tools/sublime_publish.py
Python
mit
3,794
0.000264
""" Copy Python scripts to Sublime Text package. This creates the /docs/sublime-package/vX.Y.Z.zip file with the contents of the sublime and space_tracer folders, then it updates the version number in the package.json file. """ import json from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter, ArgumentErr...
xt_version = about['__version__'] out_path: Path = args.out package_details_path = out_path / 'package.json' package_details = json.loads(package_details_path.read_text()) releases: list = package_details['packages'][0]['releases'] for release in releases: if releas
e['version'] == next_version: exit(f'Version {next_version} has already been published.') next_release = create_release(next_version) releases.insert(0, next_release) package_details_path.write_text(json.dumps(package_details, indent=2)) print('Packaging', next_version) package_path = o...
ampyche/ampyche
ampyche_setup.py
Python
mit
3,407
0.034635
#!/usr/bin/python3 import os import cgi import cgitb import json from pprint import pprint import setup.common as co import setup.sqlcommon as sqlc import setup.defaultpaths as dfp import setup.getinput as gi import setup.dbsetup as dbs import setup.gettags as gt import setup.createsongsjson as csj import setup.create...
ilename in files: fn = os.path.join(p, filename) if fn[:-4] == "json": os.remove(fn) for (p, d, files) in os.walk(self.dbpath['programpath'] + "/db"): for filename in files: fn = os.path.join(p, filename) if os.path.exists(fn): os.re
move(fn) # for (p, d, files) in os.walk(self.dbpath['programpath'] + "/music"): # for filename in files: # fn = os.path.join(p, filename) # if os.path.exists(fn): # os.remove(fn) # def _get_input_values(self): inputs = self.GI._get_inputs() return inputs # zelda = {}...
Submanifold/Aleph
utilities/make_pinched_torus.py
Python
mit
1,687
0.017783
#!/usr/bin/env python3 # # This file is part of the utilities shipped with 'Aleph - A Library for # Exploring Persistent Homology'. It contains test code to parametrize a # 'pinched torus'. The parametrization follows a sine pattern as the gap # towards the singular point is approached. # # Original author: Bastian Rie...
the torus is modified # if this distance is smaller than the gap size. dist = abs(fmod(2*pi+phi,2*pi) - pi) if dist <= gap_si
ze: # Use a simple linear model to decrease the radius as we are # coming towards the gap. r_= r / gap_size * dist else: r_ = r x = (R+r_*cos(theta))*cos(phi) y = (R+r_*cos(theta))*sin(phi) z = r_ * sin(theta) X.append(x) Y.append(y) Z.append(z) df = pd.DataFrame(...
akshayaurora/kivy
kivy/modules/__init__.py
Python
mit
9,461
0.000106
''' Modules ======= Modules are classes that can be loaded when a Kivy application is starting. The loading of modules is managed by the config file. Currently, we include: * :class:`~kivy.modules.touchring`: Draw a circle around each touch. * :class:`~kivy.modules.monitor`: Add a red topbar that indicates th...
o_configure
= [x[0] for x in Config.items('modules')] for name in modules_to_configure: if name not in self.mods: Logger.warning('Modules: Module <%s> not found' % name) continue self._configure_module(name) def _configure_module(self, name): if 'module'...
google/llvm-propeller
lldb/test/API/tools/lldb-server/TestGdbRemoteAuxvSupport.py
Python
apache-2.0
8,049
0.000745
import gdbremote_testcase from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil class TestGdbRemoteAuxvSupport(gdbremote_testcase.GdbRemoteTestCaseBase): mydir = TestBase.compute_mydir(__file__) AUXV_SUPPORT_FEATURE_NAME = "qXfer:auxv:read" @s...
se
lf.init_llgs_test() self.build() self.set_inferior_startup_launch() self.auxv_data_is_correct_size() def auxv_keys_look_valid(self): (word_size, auxv_data) = self.get_raw_auxv_data() self.assertIsNotNone(auxv_data) # Grab endian. self.reset_test_sequence() ...
ziplokk1/python-amazon-mws-tools
mwstools/requesters/base.py
Python
unlicense
920
0.003261
from ..parsers.errors import ErrorResponse from warnings import warn def raise_for_error(f): """ Wrapper method to parse any error response and raise the ErrorResponse instance if an error is encountered. :param f: :return: """ def inner(*args, **kwargs): warn('`raise_for_error` is de...
per method to parse a response object and raise the ErrorResponse instance if an error is encountered in the response body. :param f: :return: """ def inner(*args, **kwargs): warn('`raise_response_for
_error` is deprecated and will not process any response content.') return f(*args, **kwargs) return inner
wangyang59/tf_models
video_prediction/prediction_model_flo_edge.py
Python
apache-2.0
9,575
0.014099
# 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 applicab...
fied or more than 1 mask specified for DNA model. """ batch_size, img_height, img_width, color_channels = image.get_shape()[0:4] lstm_size = np.int32(np.array([32, 32, 64, 64, 128, 128, 256, 256,
512, 256, 128, 64, 32])) ############################# #128*128 enc0_s = slim.layers.conv2d( image, 32, [5, 5], stride=2, scope='scale1_conv1_s', normalizer_fn=tf_layers.layer_norm, normalizer_params={'scope': 'layer_norm1_s'}) hidden1_s = slim.layers.conv2d( en...
akalicki/stratus
config.py
Python
mit
73
0.041096
co
nfig = { 'app_key': 'YOUR_APP_KEY', 'app_secr
et': 'YOUR_APP_SECRET' }
BMJHayward/infusionsoft_xpmt
src/matplotchart.py
Python
mit
1,300
0.006154
''' using matplotlib to viz dates.txt ''' from collections import Counter import numpy as np import matplotlib.pyplot as plt from matplotlib import dates as pltdates import pandas as pd import sqlite3 import dataserv def getdatesfromfile(): datefile = input('please enter datefile name: ') dates = eval(open(dat...
ge(len(labels)) width = 1 plt.bar(indexes, values, width) plt.xticks(indexes + width * 0.5, labels) plt.show() def pandas_histogram(dates): datesdf = pd.DataFrame(dates) plt.figure() datesdf.plot(kind='bar', alpha=0.5) plt
.show() def plotdates(datelist, valuelist): yerp=dataserv.Leadtime() newdatelist = [] for i in datelist: if not isinstance(i, str): i=i[0] j = yerp.convert_datestring(i) newdatelist.append(j) dates = pltdates.date2num(newdatelist) plt.plot_date(dates, valuelist) ...
DXCanas/kolibri
kolibri/core/content/test/test_downloadcontent.py
Python
mit
2,896
0.002417
import hashlib import mimetypes import os import tempfile from django.test import Client from django.test import TestCase from le_utils.constants import file_formats from le_utils.constants import format_presets from kolibri.core.auth.test.helpers import provision_device from kolibri.core.content.models import Conten...
= hashlib.md5("DUMMYDATA".encode()).hexdigest() self.extension = file_formats.PDF self.filename = "{}.{}".format
(self.hash, self.extension) self.title = "abc123!@#$%^&*();'[],./?><" self.contentnode = ContentNode(title=self.title) self.available = True self.preset = format_presets.DOCUMENT self.local_file = LocalFile(id=self.hash, extension=self.extension, available=self.available) ...
joe-jordan/minimalisp
minimalisp/maths.py
Python
mit
2,519
0.001588
from __future__ import print_function, division import math from values import Value, Symbol from vm import numbers, pre_execute def instance_validate_value_type(types=(object,)): def inner_decorator(execute): def actual_validate(self, context, *terms): for t in terms: if not...
re_execute("ATAN", 2, 2) @validate_valu
e_type("ATAN", numbers) def atan2(context, a, b): return Value(math.atan2(a.v, b.v), actual=True) maths_functions = { Symbol('sin'): sin, Symbol('cos'): cos, Symbol('tan'): tan, Symbol('asin'): asin, Symbol('acos'): acos, Symbol('atan'): atan, Symbol('atan2'): atan2, Symbol('log'):...
luwei0917/awsemmd_script
GenSswight_from_mass_jpred.py
Python
mit
619
0.030695
#!/usr/bin/env python3 import sys if len(sys.argv) != 3: print("\n" + sys.argv[0] + " inpute_file output_file\n") exit() input_file = sys.argv[1] output_file = sys.argv[2] with open(output_file, "w") as out: with open(input_file, "r") as f: next(f) for line in f: name, data = line.rstrip().split(":")...
for s in data[:-1]: a = 0.0 b = 0.0 if s == 'H': a = 1.0 elif s =
= 'E': b = 1.0 out.write(str(round(a, 1))) out.write(' ') out.write(str(round(b, 1))) out.write('\n')
golismero/golismero
thirdparty_libs/geopy/location.py
Python
gpl-2.0
850
0.009412
from geopy.point impor
t Point class Location(object): def __init__(self, name="", point=None, attributes=None, **kwargs): self.name = name if point is not None: self.point = Point(point) if attributes is None: attributes = {} self.attributes = dict(attributes, **kwargs) d...
return (self.name, self.point)[index] def __repr__(self): return "Location(%r, %r)" % (self.name, self.point) def __iter__(self): return iter((self.name, self.point)) def __eq__(self, other): return (self.name, self.point) == (other.name, other.point) d...
sogeti-esec-lab/LKD
windows/native_exec/simple_x86.py
Python
bsd-3-clause
29,548
0.001828
import collections import struct class BitArray(object): def __init__(self, size, bits): self.size = size if len(bits) > size: raise ValueError("size > len(bits)") bits_list = [] for bit in bits: x = int(bit) if x not in [0, 1]: ...
if X86.reg_size(item) == 16: raise NotImplementedError("16bits modrm") if 'base' not in parsed_items: parsed_items['base'] = item continue # Already have base + index -> cannot avec another register in expression ...
Error("Multiple index / index*scale in mem expression <{0}>".format(data)) parsed_items['index'] = item continue try: disp = int(item, 0) except ValueError: raise ValueError("Invalid base/index or displacement <{0}> in mem access".f...
pcampese/codewars
roman_numerals3.py
Python
gpl-3.0
3,539
0.032778
# https://www.codewars.com/kata/roman-numerals-encoder/train/python def solution(n): # Print the arguments print('n = {}'.format(n)) roman_blueprint = [] # List of lists to store format structure: [[<letter>, <count>], ...] result = [] # Store the final roman numeral result # Calculate for roman numerals # C...
999 numM = 1 elif (1900 <= numM <= 2899): # (1 * 1000) + 0 <= (numM - 900) <= (1 * 1000) + 999 numM = 2 elif (2900 <= numM <= 3899): # (2 * 1000) + 0 <= (numM - 900) <= (2 * 1000) + 999 numM
= 3 elif (3900 <= numM <= 4899): # (3 * 1000) + 0 <= (numM - 900) <= (3 * 1000) + 99 numM = 4 else: numM = 5 roman_blueprint.append(['M', numM]) # Format the output # Format from largest to smallest for numeral, count in roman_blueprint[::-1]: if (count < 0): # We have an M to be used for subtraction ...
angea/corkami
misc/challenges/codecs/whitespace.py
Python
bsd-2-clause
495
0.006061
#whitespace-length codec def enc(fn)
: f = open(fn, "rb") r = f.read() f.close() s = [] for c in r: s += [ " " * (ord(c) + 1)] # +1 to avoid stupid extra lines by outlook w = open(fn + ".enc", "wt") w.write("\n".join(s)) w.close() def dec(fn): f = open(fn, "r
t") r = f.readlines() f.close() w = open(fn + ".dec", "wb") for c in r: if len(c) > 1: w.write(chr(len(c) - 2)) w.close()
flp9001/clevenus
clevenus/config/settings/base.py
Python
gpl-3.0
3,640
0.002473
""" Django settings for astrology project. Generated by 'django-admin startproject' using Django 1.8. For more information on this file, see https://docs.djangoproject.com/en/1.8/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.8/ref/settings/ """ # Build path...
dleware.locale.LocaleMiddleware'
, 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clic...
tcstewar/2015-Embodied_Benchmarks
code/plot_vary_neurons_all.py
Python
gpl-2.0
2,046
0.003421
import os import sys import numpy as np import pylab pylab.figure(figsize=(12,8)) do_logx = True index = 1 for D in [1, 5, 10, 15]: path = 'vary_neuronsD%d' % D data_x = [] data_y = [] for fn in os.listdir(path): if fn.endswith('.txt'): with open(os.path.join(path, fn)) as f: ...
:30] data_x = np.array(data_x) data_y = np.array(data_y) pylab.subplot(2, 2, index) def weighted_av
g_and_std(values, weights): average = np.average(values, weights=weights) variance = np.average((values-average)**2, weights=weights) return (average, np.sqrt(variance)) low = [] high = [] var = 1.0 x = np.linspace(0,10, 100) for xx in x: w = np.exp(-((data_x-xx)**2)...
dholm/voidwalker
voidwalker/application/cpus/generic.py
Python
gpl-3.0
1,397
0
# (void)walker CPU architecture support # Copyright (C) 2013 David Holm <dholmster@gmail.com> # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your opti...
ture.Generic def stack_pointer(self): return self.register('sp') def program_counter(self): return self.register('p
c')
giuseppe/virt-manager
virtconv/parsers/virtimage.py
Python
gpl-2.0
8,776
0.002279
# # Copyright 2013 Red Hat, Inc. # Copyright 2008 Sun Microsystems, Inc. All rights reserved. # Use is subject to license terms. # # 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...
if disk.format in format_mappings: fmt = format_mappings[disk.format] else: raise ValueError(_("Unknown
disk format '%s'"), disk.format) devid = (bus, nr_disk) vm.disks[devid] = diskcfg.disk(bus=bus, typ=diskcfg.DISK_TYPE_DISK) vm.disks[devid].format = fmt vm.disks[devid].path = disk.file nr_disk = nr_disk + 1 nics = domain.interface ...
oscurart/BlenderAddons
oscurart_bake_pbr_maps_linear.py
Python
gpl-2.0
13,463
0.018049
import bpy import os def setSceneOpts(): global channels global sizex global sizey global selected_to_active # VARIABLES sizex = bpy.context.scene.bake_pbr_channels.sizex sizey = bpy.context.scene.bake_pbr_channels.sizey selected_to_active= bpy.context.scene.bake_pbr_channels.selt...
_ def removeMatProps(): global mat #saco los metales en las copias de copy for mat in copyMats: desmetalizar(mat) destransparentizar(mat) #saco los metales en las copias de glossy for mat in glossyMats: desespecular(mat) mix...
r(mat) baseColorA1(mat) destransparentizar(mat) # saco metales para transmisiones for mat in transMats: desmetalizar(mat) desespecular(mat) baseColorA1(mat) #___________________________________________________________________________...
Azure/azure-sdk-for-python
sdk/network/azure-mgmt-network/azure/mgmt/network/v2020_05_01/operations/_virtual_routers_operations.py
Python
mit
24,380
0.004881
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may ...
me=virtual_router_name, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_respon
se): if cls: return cls(pipeline_response, None, {}) path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'virtualRouterName': self._serialize.url("virtual_router_name", virtual_router_name, 's...
samuto/Honeybee
src/Honeybee_Radiance Mirror Material By Color.py
Python
gpl-3.0
4,158
0.01443
# # Honeybee: A Plugin for Environmental Analysis (GPL) started by Mostapha Sadeghipour Roudsari # # This file is part of Honeybee. # # Copyright (c) 2013-2015, Mostapha Sadeghipour Roudsari <Sadeghipour@gmail.com> # Honeybee is free software; you can redistribute it and/or modify # it under the terms of the GNU Ge...
lues should be between 0 and 1" e = gh.GH_RuntimeMessageLevel.Error ghenv.Component.AddRuntimeMessage(e, msg) else: p
rint "You should first let Honeybee to fly..." w = gh.GH_RuntimeMessageLevel.Warning ghenv.Component.AddRuntimeMessage(w, "You should first let Honeybee to fly...") RADMaterial = main()
OpenCMISS/neon
src/opencmiss/neon/core/serializers/base.py
Python
apache-2.0
832
0
''' Copyright 2015 University of Auckland 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 un
der the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ''' class BaseSerialiser(object): def __init__(self): pass def seri...
fesh0r/xnb_parse
xnb_parse/trackball_camera.py
Python
mit
12,635
0.000475
"""trackball_camera.py - An OpenGL Trackball Camera Class for Pyglet by Roger Allen, July 2008 roger@rogerandwendy.com A class for simple-minded 3d example apps. Usage: Initialize with a radius from the center/focus point: tbcam = TrackballCamera(5.0) After adjusting your projection matrix, set the modelview m...
2] def v3cross(vec1, vec2): return [vec1[1] * vec2[2] - vec1[2] * vec2[1], vec1[2] * vec2[0] - vec1[0] * vec2[2], vec1[0] * vec2[1] - vec1[1] * vec2[0]] def v3length(vec): return math.sqrt(vec[0] * vec[0] + ve
c[1] * vec[1] + vec[2] * vec[2]) def v3normalize(vec): try: return v3scale(vec, 1.0 / v3length(vec)) except ZeroDivisionError: return vec # Some quaternion routines def q_add(quat1, quat2): """Given two quaternions, add them together to get a third quaternion. Adding quaternions to ...
Xeralux/tensorflow
tensorflow/python/keras/_impl/keras/layers/advanced_activations.py
Python
apache-2.0
8,770
0.004675
# Copyright 2015 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...
def __init__(self, alpha=1.0, **kwargs): super(ELU, self).__init__(**kwargs) self.supports_masking = True self.alpha = K.cast_to_floatx(alpha) def call(self, inputs): return K.elu(inputs, self.alpha) def get_config(self): config = {'alpha': float(self.alpha)} base_config = super(ELU, sel...
turn input_shape @tf_export('keras.layers.ThresholdedReLU') class ThresholdedReLU(Layer): """Thresholded Rectified Linear Unit. It follows: `f(x) = x for x > theta`, `f(x) = 0 otherwise`. Input shape: Arbitrary. Use the keyword argument `input_shape` (tuple of integers, does not include the sa...
rickerc/cinder_audit
cinder/volume/drivers/solidfire.py
Python
apache-2.0
29,104
0.000103
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2013 SolidFire 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/l...
See the # License for the specific language governing permissions and limitations # under the License. import base64 import httplib import json import math import random import socket import string import time import uuid from oslo.config import cfg from cinder import context from cinder import exception from...
stack.common import log as logging from cinder.openstack.common import timeutils from cinder.volume.drivers.san.san import SanISCSIDriver from cinder.volume import volume_types LOG = logging.getLogger(__name__) sf_opts = [ cfg.BoolOpt('sf_emulate_512', default=True, help='Set 512 b...
Strilanc/Qubery
src/CubeFinder.py
Python
mit
11,417
0.004292
#!/usr/bin/python # coding=utf-8 """ Cube finding program. """ from __future__ import division # so 1/2 returns 0.5 instead of 0 from rotation import * import cv2 import cube import geom import imag import numpy as np from gates import QuantumOperation # entangle = [QuantumOperation(Rotation(x=0.25).as_pauli_opera...
red_corners[2
] top_right = ordered_corners[3] top_mid = (top_left + top_right)/2 past_left = geom.lerp(bottom_left, top_left, 1.5) past_right = geom.lerp(bottom_right, top_right, 1.5) past_mid = (past_left + past_right)/2 whole_contour = scale_around([past_left, past_right, top_right, top_left], 0.5, mid) ...
btovar/autopyfactory
autopyfactory/plugins/queue/sched/WeightedActivated.py
Python
apache-2.0
3,777
0.007678
#! /usr/bin/env python # from autopyfactory.interfaces import SchedInterface import logging class WeightedActivated(SchedInterface): id = 'weightedactivated' def __init__(self, apfqueue, config, section): try: self.apfqueue = apfqueue self.log = logging.g...
in=%s,activated=%s,weightedactivated=%s,pending=%s,weightedpen
ding=%s,ret=%s" %(n, activated_jobs, activated_jobs_w, pending_pilots, pending_pilots_w, out) self.log.info(msg) return (out, msg)
airbnb/airflow
airflow/www/api/experimental/endpoints.py
Python
apache-2.0
13,782
0.001524
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not...
jsonify({'error': error_message}) response.status_code = 400 return response replace_microseconds = execution_date is None if 'replace_microseconds' in data: replace_microseconds = to_boolean(data['replace_microseconds']) try: dr = trigger.trigger_dag(dag_id
, run_id, conf, execution_date, replace_microseconds) except AirflowException as err: log.error(err) response = jsonify(error=f"{err}") response.status_code = err.status_code return response if getattr(g, 'user', None): log.info("User %s created %s", g.user, dr) res...
seankelly/buildbot
master/buildbot/test/unit/test_mq_wamp.py
Python
gpl-2.0
7,469
0.000134
# This file is part of Buildbot. Buildbot 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, version 2. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without eve...
elf.mq.startConsuming(callback, ('a', 'b')) # _produce returns a deferred yield self.mq._produce(('a', 'b'), 'foo') # calling produce should eventually call the callback with decoding of # topic yield d callback.assert_called_with(('a', 'b'), 'foo') @defer.inlineCall...
suming(callback, ('a', None)) # _produce returns a deferred yield self.mq._produce(('a', 'b'), 'foo') # calling produce should eventually call the callback with decoding of # topic yield d callback.assert_called_with(('a', 'b'), 'foo')
glasnost/kremlin
kremlin/forms.py
Python
bsd-2-clause
2,312
0.007785
""" # # #### ##### # # ##### # # # # # # # # # ## ## # # # ## # # ### #### #### # # # # # # # # ##### # # # # # # # # ## # # # # # # ##### # # # # # # # # Kremlin Mag...
50), Email(),
] ) password = PasswordField('Password', validators = [ DataRequired(), EqualTo('confirm', message='Passwords must match!'), ] ) confirm = PasswordField('Repeat Password') # accept_tos = BooleanField(u'I accept the TOS', # validators=[validators.R...
NREL/OpenWARP
source/openwarpgui/nemoh/models.py
Python
apache-2.0
6,037
0.001656
#!/usr/bin/env python """ This module defines nemoh custom types or models. Changes in version 1.1 (OpenWarp - Add Logging Functionality) Added support for logging. Changes in version 1.2 (OPENWARP - PROVIDE A COMMAND LINE INTERFACE USING PYTHON): Added models for Mesh Format. """ import numpy as np impor...
ormat the mesh format :return True if the file is of the expected mesh format """ return os.path.splitext(filename)[1] == mesh_format @staticmethod def is_dat_file(filename): "
"" Check if a given file is of the dat mesh format :param filename the filename :return True if the file is of the dat mesh format """ return MeshFormat.is_mesh_file(filename, MeshFormat.DAT)
frappe/frappe
frappe/desk/doctype/number_card/number_card.py
Python
mit
5,717
0.027812
# -*- coding: utf-8 -*- # Copyright (c) 2020, Frappe Technologies and contributors # License: MIT. See LICENSE import frappe from frappe.model.document import Document from frappe.utils import cint from frappe.model.naming import append_number_if_name_exists from frappe.modules.export_file import export_to_files from ...
lues) @frappe.whitelist() def create_report_number_card(ar
gs): card = create_number_card(args) args = frappe.parse_json(args) args.name = card.name if args.dashboard: add_card_to_dashboard(frappe.as_json(args)) @frappe.whitelist() def add_card_to_dashboard(args): args = frappe.parse_json(args) dashboard = frappe.get_doc('Dashboard', args.dashboard) dashboard_link =...
skitazaki/python-school-ja
src/cmdline-3.py
Python
mit
139
0.007194
fr
om pprint import pprint import settings pprint(dir(settings)) pprint({'DEBUG': settings.DEBUG}) pprint(settings.DATABASES['default'])
informationsea/Hyokai
scripts/make-sampledb/geneontololgy/import-go.py
Python
gpl-3.0
2,759
0.005437
#!/usr/bin/env python # -*- coding: utf-8 -*- import argparse import sqlite3 import collections import re def _main(): parser = argparse.ArgumentParser(description="Import GO term into sqlite3") parser.add_argument('go', default='go.obo', type=argparse.FileType('r'), help='default: %(default)s', nargs='?') ...
TABLE IF EXISTS term_info') conn.execute('CREATE TABLE dbinfo(key TEXT, value TEXT)') conn.execute('CREATE TABLE term(GOID TEXT PRIMARY KEY, name TEXT, namespace TEXT, def TEXT)') conn.execute('CREATE TABLE term_info(GOID TEXT, key TEXT, value TEXT)') mode = 'DBINFO' current_dic = collections.defau...
current_dic.clear() elif line.startswith('[') and line.endswith(']'): mode = line[1:-1] else: elements = line.split(': ', 1) current_dic[elements[0]].append(elements[1]) register(conn, mode, current_dic) conn.execute('CREATE INDEX IF NOT EXISTS term__...
hmpf/nav
tests/unittests/eventengine/plugin_test.py
Python
gpl-3.0
2,039
0
from __future__ import unicode_literals import pytest from mock import Mock from django.utils import six from nav.eventengine.config import EventEngineConfig from nav.eventengine.engine import EventEngine from nav.eventengine.plugin import UnsupportedEvent, EventHandler from nav.eventengine.plugin import _find_package...
es_is_list(): modules = _find_package_modules('nav.eventengine.plugins') assert not isinstance(modules, six.string_types) assert len(modules) >= 0 def test_
boxstate_plugin_should_be_found(): from nav.eventengine.plugins.boxstate import BoxStateHandler classes = EventHandler.load_and_find_subclasses() assert BoxStateHandler in classes def test_delayedhandler_sets_timeouts_from_config(): class TestHandler(DelayedStateHandler): handled_types = ('te...
j4ve1in/dotfiles
src/.config/ranger/colorschemes/abyss.py
Python
mit
4,804
0.000208
# This file is part of ranger, the console file manager. # License: GNU GPL version 3, see the file "AUTHORS" for details. from ranger.gui.colorscheme import ColorScheme from ranger.gui.color import * color = {'blue': 27} class Default(ColorScheme): progress_bar_color = color['blue'] def use(self, context):...
fg = color['blue'] if context.selected: attr |= reverse if context.loaded: if context.selected: fg = self.progress_bar_color else: bg = self.progress_bar_color if context.vcsfile and not context....
ict: fg = magenta elif context.vcschanged: fg = red elif context.vcsunknown: fg = red elif context.vcsstaged: fg = green elif context.vcssync: fg = green elif context.vcsignored: ...