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
gnrhxni/CS542
multiple_nn.py
Python
gpl-3.0
7,175
0.018815
#!/usr/bin/python import os import re import sys import numpy import pybrain import pickle import math import time import random from nettalk_data import * from constants import * from pybrain.datasets import SupervisedDataSet from pybrain.supervised.trainers import BackpropTrainer from pybrain.structure.modules impor...
arLayer, Sigm
oidLayer, BiasUnit from pybrain.structure.networks import FeedForwardNetwork from pybrain.structure import FullConnection from pybrain.datasets import SupervisedDataSet from sigmoidsparselayer import SigmoidSparseLayer from pybrain.tools.shortcuts import buildNetwork from prevent_overtraining import PreventOverTrainer...
MacHu-GWU/elementary_math-project
start-a-project/init_project.py
Python
mit
3,304
0.001211
#!/usr/bin/env python # -*- coding: utf-8 -*- """ This script can generate automate scripts for open source python project. Scroll to ``if __name__ == "__main__":`` for more info. """ from __future__ import print_function import sys import datetime from os import walk, mkdir from os.path import join, abspath, dirnam...
ackage_name) # make destination direc
tory try: print(" Create '%s' ..." % dst_dir) mkdir(dst_dir) except: pass # files for filename in file_list: src = join(src_dir, filename) dst = join(dst_dir, filename) content = read(src).\ repl...
shackra/thomas-aquinas
tests/test_accelerate.py
Python
bsd-3-clause
833
0.02401
# coding: utf-8 testinfo = "s, t 4, s, t 8, s, t 10.1, s, q" tags = "Accelerate" from summa.layer import Layer from summa.director import director from summa.actions import Accelerate, Rotate from summa.sprite import Sprite import customstuff import pyglet import os pyglet.resource.path.append( os.path.join(os.pa...
) class TestLayer(Layer): def __init__(self): super( TestLayer, self ).__init__() x, y = director.get_window_size() self.sprite = Sprite( 'grossini.png', (x/2, y/2) ) self.add( self.sprite ) self.sprite.do( Accelerate( Rotate( 360, 10 ), 4 ) ) def test_accelerate(): ...
init() test_layer = TestLayer() main_scene = customstuff.TimedScene(test_layer) director.run(main_scene)
Rocky5/XBMC-Emustation
Mod Files/emustation/scripts/not used/Other/Remove _Resources.py
Python
gpl-3.0
1,405
0.036299
import os, shutil, xbmc, xbmcgui pDialog = xbmcgui.DialogProgress() dialog = xbmcgui.Dialog() Game_Directories = [ "E:\\Games\\", "F:\\Games\\", "G:\\Games\\", "E:\\Applications\\", "F:\\Applications\\", "G:\\Applications\\", "E:\\Homebrew\\", "F:\\Homebrew\\", "G:\\Homebrew\\", "E:\\Apps\\", "F:\\Apps\\", "G:\\Apps...
( Game_Directories, Items ) _Resources = os.path.join( Game_Directory, "_Resources" ) DefaultTBN = os.path.join( Ga
me_Directory, "default.tbn" ) FanartJPG = os.path.join( Game_Directory, "fanart.jpg" ) if os.path.isdir(_Resources): shutil.rmtree(_Resources) else: print "Cannot find: " + _Resources if os.path.isfile(DefaultTBN): os.remove(DefaultTBN) else: print "Cannot find: " + Defa...
stdweird/aquilon
lib/python2.6/aquilon/worker/formats/network_environment.py
Python
apache-2.0
1,413
0.001415
# -*- cpy-indent-level: 4; indent-tabs-mode: nil -*- # ex: set expandtab softtabstop=4 shiftwidth=4: # # Copyright (C) 2009,2010,2011,2012,2013 Contributor # # 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 t...
"""Network environment formatter.""" from aquilon.aqdb.model import NetworkEnvironment from aquilon.worker.formats.formatters import ObjectFormatter class NetworkEnvironmentFormatter(ObjectFormatter): def format_raw(self, netenv, indent=""): details = [indent + "{0:c}: {0.name}".format(nete
nv)] details.append(self.redirect_raw(netenv.dns_environment, indent + " ")) if netenv.location: details.append(self.redirect_raw(netenv.location, indent + " ")) if netenv.comments: details.append(indent + " Comments: %s" % netenv.comments) return "\n".join(det...
desbma/glances
glances/plugins/glances_mem.py
Python
lgpl-3.0
11,139
0.002335
# -*- coding: utf-8 -*- # # This file is part of Glances. # # Copyright (C) 2015 Nicolargo <[email protected]> # # Glances is free software; you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the Lic...
'shared': '1.3.6.1.4.1.2021.4.13.0', 'buffers': '1.3.6.1.4.1.2021.4.14.0', 'cached': '1.3.6.1.4.1.2021.4.15.0'}, 'windows': {'mnt_point': '1.3.6.1.2.1.25.2.3.1.3', 'alloc_unit': '1.3.6.1.2.1.25.2.3.1.4', ...
'esxi': {'mnt_point': '1.3.6.1.2.1.25.2.3.1.3', 'alloc_unit': '1.3.6.1.2.1.25.2.3.1.4', 'size': '1.3.6.1.2.1.25.2.3.1.5', 'used': '1.3.6.1.2.1.25.2.3.1.6'}} # Define the history items list # All items in this list will be historised if the --ena...
alirizakeles/tendenci
tendenci/apps/directories/choices.py
Python
gpl-3.0
692
0.013006
from django.utils.translation import ugettext_lazy as _ DURATION_CHOICES = ( (14, _('14 Days from Activation date')), (60, _('60 Days from Activation date')), (90,_('90 Days from Activation date')), (120,_('120 Days from Activation date')), (365,_('1 Year from Activation date')), ) ADMIN_DURATION_C...
nlimited')), (14,_('14 Days from Activation date')), (30,_('30 Days from Activation date')), (60,_('60 Days from Activation date')), (90,_('90 Days from Activation date')), (120,_('120 Days from Activation date')),
(365,_('1 Year from Activation date')), ) STATUS_CHOICES = ( (1, _('Active')), (0, _('Inactive')), )
intellij-rust/intellij-rust.github.io
changelog.py
Python
mit
9,091
0.00176
#!/usr/bin/env python3 import argparse import datetime import os import re import urllib.request from dataclasses import dataclass from typing import Set, List, Optional, Dict, TextIO # https://github.com/PyGithub/PyGithub from github import Github from github.Milestone import Milestone from github.Repository import R...
er.login) for label in labels: changelog.add_item(label, changelog_item) return changelog def main(): pars
er = argparse.ArgumentParser() parser.add_argument("-c", action='store_true', help="add contributor links") parser.add_argument("--offline", action='store_true', help="do not preform net requests") parser.add_argument("--token", type=str, help="github token") parser.add_argument("--login", type=str, hel...
lionheart/pyavatax
test_avalara.py
Python
bsd-3-clause
23,475
0.00443
from pyavatax.base import Document, Line, Address, TaxOverride, AvalaraException, AvalaraTypeException, AvalaraValidationException, AvalaraServerNotReachableException from pyavatax.api import API import settings_local # put the below settings into this file, it is in .gitignore import datetime import pytest import uui...
dd_from_address(from_address)
assert e.value.code == AvalaraException.CODE_HAS_FROM with pytest.raises(AvalaraException) as e: doc.add_to_address(to_address) assert e.value.code == AvalaraException.CODE_HAS_TO line = Line(Amount=10.00) doc.add_line(line) doc.validate() api = get_api() lat = 47.627935 lng = -...
mark-me/Pi-Jukebox
venv/Lib/site-packages/pygame/examples/vgrade.py
Python
agpl-3.0
3,320
0.005422
#!/usr/bin/env python """This example demonstrates creating an image with numpy python, and displaying that through SDL. You can look at the method of importing numpy and pygame.surfarray. This method will fail 'gracefully' if it is not available. I've tried mixing in a lot of comments where the code might not be self...
reating the gradient and blitting the array. The final 40% goes to flipping/updating the display surface If using an SDL version at least 1.1.8 the window will have no border decorations. The code also demonstrates use of the timer events.""" import os, pygame from pygame.locals import * try: from numpy import...
m numpy.random import * except ImportError: raise SystemExit('This example requires numpy and the pygame surfarray module') pygame.surfarray.use_arraytype('numpy') timer = 0 def stopwatch(message = None): "simple routine to time python code" global timer if not message: timer = pygame.time.get...
dhuang/incubator-airflow
tests/providers/microsoft/azure/hooks/test_azure_data_factory.py
Python
apache-2.0
15,858
0.004414
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
t_delete_factory(hook: AzureDataFactoryHook, user_args, sdk_args): hook.delete_factory(*user_args) hook._conn.factories.delete.assert_called_with(*sdk_args) @parametrize( explicit_factory=((NAME, RESOURCE_GROUP, FACTORY), (RESOURCE_GROUP, FACTORY, NAME)), implicit_factory=((NA
ME,), (DEFAULT_RESOURCE_GROUP, DEFAULT_FACTORY, NAME)), ) def test_get_linked_service(hook: AzureDataFactoryHook, user_args, sdk_args): hook.get_linked_service(*user_args) hook._conn.linked_services.get.assert_called_with(*sdk_args) @parametrize( explicit_factory=((NAME, MODEL, RESOURCE_GROUP, FACTORY), ...
kyungmi/webida-server
src/ext/cordova-weinre/weinre.build/scripts/build-target-scripts.py
Python
apache-2.0
5,339
0.008054
#!/usr/bin/env python # --- # 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 (th...
includedFiles.append("weinre/target/%s" % entry) includedFiles.append("interfaces/all-json-idls-min.js") for includedFile in includedFiles: baseScriptFile = includedFile sc
riptFile = os.path.join(srcDirName, baseScriptFile) if not os.path.exists(scriptFile): error("script file not found: '" + scriptFile + "'") scripts.append(scriptFile) scriptNames[scriptFile] = baseScriptFile with open(scriptFile, "r") as iFile: scriptSrc[scriptF...
azavea/nyc-trees
src/nyc_trees/apps/core/migrations/0021_auto_20150408_1216.py
Python
agpl-3.0
660
0
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): de
pendencies = [ ('core', '0020_auto_20150323_1457'), ] operations = [ migrations.AddField( model_name='user', name='progress_page_help_shown', field=models.BooleanField(default=False),
preserve_default=True, ), migrations.AddField( model_name='user', name='reservations_page_help_shown', field=models.BooleanField(default=False), preserve_default=True, ), ]
gppezzi/easybuild-framework
easybuild/toolchains/cgmvapich2.py
Python
gpl-2.0
1,589
0.001888
## # Copyright 2013-2019 Ghent University # # T
his file is triple-licensed under GPLv2 (see below), MIT, and # BSD three-clause licenses. # # This file is part of EasyBuild, # originally created by the HPC team of Ghent University (http://ugent.be/hpc/en), # with support of Ghent Univ
ersity (http://ugent.be/hpc), # the Flemish Supercomputer Centre (VSC) (https://www.vscentrum.be), # Flemish Research Foundation (FWO) (http://www.fwo.be/en) # and the Department of Economy, Science and Innovation (EWI) (http://www.ewi-vlaanderen.be/en). # # https://github.com/easybuilders/easybuild # # EasyBuild is fr...
aweisberg/cassandra-dtest
sstable_generation_loading_test.py
Python
apache-2.0
17,757
0.003097
import os import subprocess import time import distutils.dir_util from distutils.version import LooseVersion import pytest import logging from ccmlib import common as ccmcommon from dtest import Tester, create_ks, create_cf, MAJOR_VERSION_4 from tools.assertions import assert_all, assert_none, assert_one since = py...
e_dir = os.path.join(data_dir, ddir) if os.path.isdir(keyspace_dir) and ddir != 'system': copy_dir = os.path.join(copy_root, ddir) distutils.dir_util.copy_tree(keyspace_dir, copy_dir) def load_sstables(self, cluster, node, ks): cdir = node.get_i
nstall_dir() sstableloader = os.path.join(cdir, 'bin', ccmcommon.platform_binary('sstableloader')) env = ccmcommon.make_cassandra_env(cdir, node.get_path()) host = node.address() for x in range(0, cluster.data_dir_count): sstablecopy_dir = os.path.join(node.get_path(), 'data{...
timkral/horn
heimdall/setup/__init__.py
Python
bsd-3-clause
21
0
__author__
= 'tkral
'
bootswithdefer/ansible
v2/ansible/errors/__init__.py
Python
gpl-3.0
6,977
0.004586
# (c) 2012-2014, Michael DeHaan <[email protected]> # # 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) an...
for some common quoting mistakes else: parts = target_line.split(":
") if len(parts) > 1: middle = parts[1].strip() match = False unbalanced = False if middle.startswith("'") and not middle.endswith("'"): match = True ...
sburnett/seattle
repy/tests/ut_repytests_veryslownetsend-testrecv.py
Python
mit
382
0.065445
#pragma out #pragma repy restri
ctions.veryslownetsend def foo(ip,port,sock, mainch, ch): data = sock.recv(1000) print ip,port,data stopcomm(ch) stopcomm(mainch) if callfunc == 'initialize': ip = getmyip() waitforconn(ip,<connport>,foo) sleep(.1) csock = openconn(ip,<connport>) csock.send(
'Hello, this is too long for such a short time') sleep(.5) exitall()
zstackorg/zstack-woodpecker
integrationtest/vm/ha/test_all_nodes_recovery_with_one_cmd_create_vm.py
Python
apache-2.0
1,972
0.005578
''' Integration Test for creating KVM VM with all nodes shutdown and recovered. @author: Quarkonics ''' import zstackwoodpecker.test_util as test_util import zstackwoodpecker.test_state as test_state import zstackwoodpecker.test_lib as test_lib import zstackwoodpecker.operations.resource_operations as res_...
vm = test_stub.create_basic_vm() vm.check() vm.destroy() test_util.test_pass('After Recover Node with One command, Create VM Test Success') #Will be called
only if exception happens in test(). def error_cleanup(): global vm if vm: try: vm.destroy() except: pass
karllessard/tensorflow
tensorflow/python/training/saving/saveable_object.py
Python
apache-2.0
3,646
0.004663
# 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...
D, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # =====================================================================
========= """Types for specifying saving and loading behavior.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function class SaveSpec(object): """Class used to describe tensor slices that need to be saved.""" def __init__(self, tensor, slice_spec, name, dty...
HydrelioxGitHub/home-assistant
homeassistant/helpers/config_validation.py
Python
apache-2.0
26,479
0
"""Helpers for config validation using voluptuous.""" import inspect import logging import os import re from datetime import (timedelta, datetime as datetime_sys, time as time_sys, date as date_sys) from socket import _GLOBAL_DEFAULT_TIMEOUT from typing import Any, Union, TypeVar, Callable, Sequen...
id %s, please update with %s. This " "will become a breaking change.", value, fixed ) return value raise vol.Invalid('Entity ID {} is an invalid entity id'.format(value)) def entity_ids(value: Union[str, Sequence]) -> Sequence[str]: """Validate Entity IDs.""" if va...
ot be None') if isinstance(value, str): value = [ent_id.strip() for ent_id in value.split(',')] return [entity_id(ent_id) for ent_id in value] comp_entity_ids = vol.Any( vol.All(vol.Lower, ENTITY_MATCH_ALL), entity_ids ) def entity_domain(domain: str): """Validate that entity belong to ...
guoci/autokey-py3
lib/autokey/iomediator/_iomediator.py
Python
gpl-3.0
9,297
0.00484
import threading import queue import logging from ..configmanager import ConfigManager from ..configmanager_constants import INTERFACE_TYPE from ..interface import XRecordInterface, AtSpiInterface from autokey.model import SendMode from .key import Key from .constants import X_RECORD_INTERFACE, KEY_SPLIT_RE, MODIFIER...
n(self, modifier): """ Updates the state of the given modifier key to 'pressed'
""" _logger.debug("%s pressed", modifier) if modifier in (Key.CAPSLOCK, Key.NUMLOCK): if self.modifiers[modifier]: self.modifiers[modifier] = False else: self.modifiers[modifier] = True else: self.modifiers[modifier] = True ...
dbmi-pitt/DIKB-Micropublication
scripts/mp-scripts/Bio/PDB/Residue.py
Python
apache-2.0
4,886
0.010847
# Copyright (C) 2002, Thomas Hamelryck ([email protected]) # This code is part of the Biopython distribution and governed by its # license. Please see the LICENSE file that should have been included # as part of this package. # My Stuff from PDBExceptions import PDBConstructionException from Entity import Entity,...
, icode=self.get_id() full_id=(resname, hetflag, resseq, icode) return "<Residue %s het=%s resseq=%s icode=%s>" % full_id # Private methods def _sort(self, a1, a2): """Sort the Atom objects. Atoms are sorted alphabetically according to their name, but N, CA, C, O alwa...
irst. Arguments: o a1, a2 - Atom objects """ name1=a1.get_name() name2=a2.get_name() if name1==name2: return(cmp(a1.get_altloc(), a2.get_altloc())) if _atom_name_dict.has_key(name1): index1=_atom_name_dict[name1] else: ...
figo-connect/schwifty
schwifty/__init__.py
Python
mit
248
0
try: from importlib.metadata import version except ImportError: from importlib_metadata import version # type:
ignore from schwifty.bic import BIC from schwifty.
iban import IBAN __all__ = ["IBAN", "BIC"] __version__ = version(__name__)
genius1611/Keystone
keystone/backends/sqlalchemy/api/role.py
Python
apache-2.0
8,044
0.002362
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2010 OpenStack LLC. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/...
t in next_page: next_page = t if len(prev_page) == 0: prev_page = first else: for t in prev_page: prev_page = t if prev_page.id == marker:
prev_page = None else: prev_page = prev_page.id if next_page.id == last.id: next_page = None else: next_page = next_page.id return (prev_page, next_page) def ref_get_page_markers(self, user_id, tenant_id, marker, limit, session=N...
Azure/azure-sdk-for-python
sdk/appservice/azure-mgmt-web/azure/mgmt/web/v2021_01_15/operations/_domain_registration_provider_operations.py
Python
mit
5,798
0.004484
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microso
ft 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 cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------...
----------------------------- import functools from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar import warnings from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.paging import ItemPaged from ...
lrowe/rdflib
test/test_trig.py
Python
bsd-3-clause
1,653
0.012704
import unittest import rdflib import re from rdflib.py3compat import b class
TestTrig(unittest.TestCase): def testEmpty(self): g=rdflib.Graph() s=g.serialize(format='trig') self.assertTrue(s is not None) def testRepeatTriples(self): g=rdflib.ConjunctiveGraph() g.get_context('urn:a').add(( rdflib.URIRef('urn:1'), ...
rdflib.URIRef('urn:3') )) g.get_context('urn:b').add(( rdflib.URIRef('urn:1'), rdflib.URIRef('urn:2'), rdflib.URIRef('urn:3') )) self.assertEqual(len(g.get_context('urn:a')),1) self.assertEqual(len(g...
rgeorgiev583/BrainfuckInterpreter
main.py
Python
gpl-3.0
263
0.003802
__author__ = 'radoslav' import bfplatform bfi = bfplatform.create_bfi_stdio_c
har( "++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++." ) bfi.run() bfi = bfplatform.create_bfi_st
dio_numeric() bfi.run()
mosquito/TelePY
pytils/test/templatetags/helpers.py
Python
gpl-3.0
2,137
0.006083
# -*- coding: utf-8 -*- # pytils - russian-specific string utils # Copyright (C) 2006-2009 Yury Yurevich # # http://pyobject.ru/projects/pytils/ # # 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...
A PARTICULAR PURPOSE. See the # GNU General Public License for more details. """ He
lpers for templatetags' unit tests in Django webframework """ from django.conf import settings encoding = 'utf-8' settings.configure( TEMPLATE_DIRS=(), TEMPLATE_CONTEXT_PROCESSORS=(), TEMPLATE_LOADERS=(), INSTALLED_APPS=('pytils',), DEFAULT_CHARSET=encoding, ) from django import template from dj...
Valloric/ycmd
.ycm_extra_conf.py
Python
gpl-3.0
7,079
0.022461
# This file is NOT licensed under the GPLv3, which is the license for the rest # of YouCompleteMe. # # Here's the license text for this file: # # This
is free and unencumbered software released into the public domain. # # Anyone is free to copy, modify, publish, use, compile, sell
, or # distribute this software, either in source code form or as a compiled # binary, for any purpose, commercial or non-commercial, and by any # means. # # In jurisdictions that recognize copyright laws, the author or authors # of this software dedicate any and all copyright interest in the # software to the public d...
k0pernicus/giwyn
giwyn/lib/settings/settings.py
Python
gpl-3.0
261
0
def init(): global ARGS global CONFIG_FILE_CONTENT global CONFIG_FILE_NAME global CONFIG_FILE_PATH global GIT_OBJECTS
ARGS = [] CONFIG_FILE_CONTENT = [] CONFIG_FILE_NAME = "
.giwyn" CONFIG_FILE_PATH = "" GIT_OBJECTS = []
vlukes/sfepy
tests/test_input_thermo_elasticity_ess.py
Python
bsd-3-clause
219
0.009132
from __future__ import absolute_import input_name = '../examples/multi_physics/thermo_elasticity_
ess.py' output_name = 'test_thermo_elasticity_ess.vtk' from tests
_basic import TestInput class Test(TestInput): pass
caspyyy/SCRAPY_DDS
example_project/example_project/settings.py
Python
bsd-3-clause
5,820
0.001546
# Django settings for example_project project. import os DEBUG = True TEMPLATE_DEBUG = DEBUG PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__)) ADMINS = ( # ('Your Name', '[email protected]'), ) MANAGERS = ADMINS DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', # Add '...
'django.contrib.staticfiles', 'django.contrib.admin', # Uncomment the next line to enable admin documentation: # 'django.contrib.admindocs',
'south', 'kombu.transport.django', 'djcelery', 'dynamic_scraper', 'open_news', ) # A sample logging configuration. The only tangible logging # performed by this configuration is to send an email to # the site admins on every HTTP 500 error when DEBUG=False. # See http://docs.djangoproject.com/en/de...
Vogtinator/micropython
tests/pyb/can.py
Python
mit
841
0.002378
from pyb import CAN CAN.initfilterbanks(14) can = CAN(1) print(can) can.init(CAN.LOOPBACK) print(can) print(can.any(0)) # Catch all filter can.setfilter(0, CAN.MASK16, 0, (0, 0, 0, 0)) can.send('abcd', 123) print(can.any(0)) print(can.recv(0)) can.send('abcd', -1) print(can.recv(0)) can.send('abcd', 0x7FF + 1) pr...
can.send('abcde', 0x7
FF + 1) except ValueError: print('failed') else: r = can.recv(0) if r[0] == 0x7FF+1 and r[3] == b'abcde': print('passed') else: print('failed, wrong data received')
ballouche/navitia
source/sql/alembic/versions/5a590ae95255_manage_frames.py
Python
agpl-3.0
1,090
0.013761
"""manage frames Revision ID: 5a590ae95255 Revises: 59f4456a029 Create Date: 2015-11-25 16:43:10.104442 """ # revision identifiers, used by Alembic. revision = '5a590ae95255' down_revision = '14346346596e' from alembic import op import sqlalchemy as sa def upgrade(): op.create_table('frame', sa.Column('id'...
lumn('contributor_id', sa.BIGINT(), nullable=False), sa.ForeignKeyConstraint(['contributor_id'], [u'navitia.contributor.id'], name=u'contributor_frame_fkey'), sa.PrimaryKeyConstraint('id'), schema='navitia' ) op.a
dd_column('vehicle_journey', sa.Column('frame_id', sa.BIGINT(), nullable=True), schema='navitia') def downgrade(): op.drop_column('vehicle_journey', 'frame_id', schema='navitia') op.drop_table('frame', schema='navitia')
repotvsupertuga/tvsupertuga.repository
script.module.openscrapers/lib/openscrapers/sources_openscrapers/de/cine.py
Python
gpl-2.0
3,466
0.003174
# -*- coding: UTF-8 -*- # ..#######.########.#######.##....#..######..######.########....###...########.#######.########..######. # .##.....#.##.....#.##......###...#.##....#.##....#.##.....#...##.##..##.....#.##......##.....#.##....## # .##.....#.##.....#.##......####..#.##......##......##.....#..##...##.##.....#....
-------------
-- ####################################################################### # Addon Name: Placenta # Addon id: plugin.video.placenta # Addon Provider: Mr.Blamo import json import re import urllib import urlparse from openscrapers.modules import client from openscrapers.modules import source_utils class source: ...
munin/munin
deprecated/cajbook.py
Python
gpl-2.0
7,158
0.002375
""" Loadable.Loadable subclass """ # This file is part of Munin. # Munin 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. # Munin is ...
elf.cursor.execute(query, (nick, p.id, tick, uid)) if uid: reply = "Booked landing on %s:%s:%s tick %s for user %s" % ( p.x, p.y, p.z, tick, user,
) else: reply = "Booked landing on %s:%s:%s tick %s for nick %s" % ( p.x, p.y, p.z, tick, nick, ) except psycopg.IntegrityError: query = "SELECT t1...
ukgovdatascience/classifyintentsapp
app/__init__.py
Python
mit
1,824
0
from flask import Flask from flask_bootstrap import Bootstrap from flask_moment import Moment from flask_sqlalchemy import SQLAlchemy from flask_login import LoginManager from flask_pagedown import PageDown bootstrap = Bootstrap() moment = Moment() db = SQLAlchemy() pagedown = PageDown() login_manager = LoginManager(...
CSS should be cached as normal.) @app.after_request def apply_caching(response): if response.headers.get('Content-Type', '').startswith('text/html'): response.headers['Cache-control'] = 'no-store' response.headers['Pragma'
] = 'no-cache' return response return app
LeZhang2016/openthread
tests/scripts/thread-cert/Cert_9_2_18_RollBackActiveTimestamp.py
Python
bsd-3-clause
6,936
0.001153
#!/usr/bin/env python # # Copyright (c) 2016, The OpenThread Authors. # 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 # ...
es[ROUTER2].add_whitelist(self.nodes[ROUTER1].get_addr64()) self.nodes[ROUTER2].enable_whitelist() self.nodes[ROUTER2].set_router_selection_jitter(1) self.nodes[ED1].set_channel(CHANNEL_INIT) self.nodes[ED1].set_masterkey(KEY1) self.nodes[ED1].set_mode('rsn
') self.nodes[ED1].set_panid(PANID_INIT) self.nodes[ED1].add_whitelist(self.nodes[ROUTER1].get_addr64()) self.nodes[ED1].enable_whitelist() self.nodes[SED1].set_channel(CHANNEL_INIT) self.nodes[SED1].set_masterkey(KEY1) self.nodes[SED1].set_mode('s') self.nodes[S...
sigurdga/samklang-menu
samklang_menu/widgets.py
Python
agpl-3.0
420
0
class Widget(obje
ct): def __init__(self, options, *args, **kwargs): super(Widget, self).__init__(*args, **kwargs) self.options = options def get_display_name(self): raise NotImplementedError
def render(self, request): raise NotImplementedError def render_option_form(self): raise NotImplementedError def get_option_dict(self): return self.options
arve0/leicacam
async_client.py
Python
mit
715
0
"""Test client using asyncio.""" import asyncio from leicacam.async_cam import AsyncCAM async def run(loop): """Run client.""" cam = AsyncCAM(loop=loop) await cam.connect() print(cam.welcome_msg) await cam.send(b"/cmd:deletelist") print(await cam.receive()) await cam.send(b"/cmd:deletelis...
t_for(cmd="cmd", timeout=0.1)) await cam.send(b"/cmd:deletelist") print(await cam.wait_for(cmd="cmd", timeout=0)) print(await cam.wait_for(cmd="cmd", timeout=0.1)) print(await cam.wait_for(cmd="test", timeout=0.1)) cam.close() if __na
me__ == "__main__": LOOP = asyncio.new_event_loop() LOOP.run_until_complete(run(LOOP)) LOOP.close()
lkorigin/laniakea
src/synchrotron/synchrotron/syncengine.py
Python
gpl-3.0
24,637
0.003937
# Copyright (C) 2016-2020 Matthias Klumpp <[email protected]> # # Licensed under the GNU Lesser General Public License Version 3 # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, eith...
the
re. # (dak will fetch the files referenced in the .dsc file from the same directory) if f.fname.endswith('.dsc'): dscfile = self._source_repo.get_file(f) self._source_repo.get_file(f) if not dscfile: log.error('Critical consistency error: Source p...
curly-brace/VkCheckerPy
vk_api/utils.py
Python
mit
1,122
0.000941
# -*- coding: utf-8 -*- """ @author: Kirill Python @contact: https://vk.com/python273 @license Apache License, Version 2.0, see LICENSE file Copyright (C) 2016 """ try: import simplejson as json except ImportError:
import json def search_re(reg, string): """ Поиск по регулярке """ s = reg.search(string) if s: groups = s.groups() return groups[0] def clean_string(s): if s: return s.strip().replace('&nbsp;', '') def code_from_number(prefix, postfix, number): prefix_len = len(prefi...
n = len(postfix) if number[0] == '+': number = number[1:] if (prefix_len + postfix_len) >= len(number): return # Сравниваем начало номера if number[:prefix_len] != prefix: return # Сравниваем конец номера if number[-postfix_len:] != postfix: return return...
obi-two/Rebelion
data/scripts/templates/object/tangible/hq_destructible/shared_power_regulator.py
Python
mit
453
0.046358
#### NOTICE: THIS FILE IS AUTOGENERATED #### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY #### PLEAS
E SEE THE ONLINE DOCUMENTATION FOR EXAMPLES from swgpy.object import * def create(kernel): result = Tangible() result.template = "object/tangible/hq_destructible/shared_power_regulator.iff" result.attribute_template_id = -1 result.stfName("hq","power_regulator") #### BEGIN MODIFICATIONS #### #### END MOD...
return result
lcoandrade/DsgTools
core/DSGToolsProcessingAlgs/Algs/LayerManagementAlgs/groupLayersAlgorithm.py
Python
gpl-2.0
8,547
0.000819
# -*- coding: utf-8 -*- """ /*************************************************************************** DsgTools A QGIS plugin Brazilian Army Cartographic Production Tools ------------------- be
gin :
2019-04-26 git sha : $Format:%H$ copyright : (C) 2019 by Philipe Borba - Cartographic Engineer @ Brazilian Army email : [email protected] ***************************************************************************...
zeeshanali/blaze
blaze/compute/ops/__init__.py
Python
bsd-3-clause
136
0.007353
# -*- coding: utf-8
-*- from __future__ import print_function, division, absolute_import from .ufuncs import * from .reduct
ion import *
venthur/pyff
src/lib/speller/__init__.py
Python
gpl-2.0
4,287
0.000233
__copyright__ = """ Copyright (c) 2011 Torsten Schmits 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 distrib...
urn f self.__stim_gen_kw = kw return decorate @classmethod def sequences(self, f): self.__sequences = f return f def setup_speller(self): self._setup_trial() self._setup_input_handler() self._setup_experiment() def _setup_trial(self):
trial_type = self._trial_name + 'Trial' self._trial = eval(trial_type)(self._view, self._trigger, self._iter, self) if self.__stimulus: self._trial._sequence = getattr(self, self.__stimulus.__name__) elif self.__stim_gen: self._tri...
andyofmelbourne/crappy-crystals
utils/gpu/__init__.py
Python
gpl-3.0
15
0
impo
rt phasin
g
MSusik/invenio
invenio/modules/webhooks/signatures.py
Python
gpl-2.0
1,447
0.010366
# -*- coding: utf-8 -*- ## ## This file is part of Invenio. ## Copyright (C) 2014 CERN. ## ## Inven
io 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. ## ## Invenio is distributed in the hope that it will be useful, but ## WITHOUT ANY WARRANTY; withou...
ClinGen/clincoded
src/clincoded/upgrade/evidenceScore.py
Python
mit
250
0
from contentbase.upgrader import upgrade_step @upgrade_step('evidenceScore', '1', '2') def evidenceScore_1_2(val
ue, system): # https://github.com/ClinGen/clincoded/issues/1507 # Add affiliation
property and update schema version return
pmeier82/SpikePlot
spikeplot/plot_cluster.py
Python
mit
3,737
0.002944
# -*- coding: utf-8 -*- # # spikeplot - plot_cluster.py # # Philipp Meier <pmeier82 at googlemail dot com> # 2011-09-29 # """scatter plot for clustering data""" __docformat__ = 'restructuredtext' __all__ = ['cluster'] ##---IMPORTS from .common import COLOURS, save_figure, check_plotting_handle, mpl, plt ##---FUNC...
mew=1, mec='k') # plot density estimates if plot_mean is not True: ax.add_artist( mpl.patches.Ellipse( xy=my_mean, width=plot_mean * 2,
height=plot_mean * 2, facecolor='none', edgecolor=col_lst[col_idx % len(col_lst)])) col_idx += 1 # fancy stuff if title is not None: ax.set_title(title) if xlabel is not None: ax.set_xlabel(xlabel) if ylabel is not...
dermoth/gramps
gramps/gui/editors/editlink.py
Python
gpl-2.0
9,653
0.002486
# # Gramps - a GTK+/GNOME based genealogy program # # Copyright (C) 2010 Doug Blank <[email protected]> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or ...
--------------------------- from gramps.gen.const import GRAMPS_LOCALE as glocale _ = glocale.translation.sgettext from ..managed
window import ManagedWindow from ..display import display_help from ..glade import Glade from gramps.gen.simple import SimpleAccess from gramps.gen.const import URL_MANUAL_SECT2 #------------------------------------------------------------------------- # # Constants # #-------------------------------------------------...
PythonProgramming/Pattern-Recognition-for-Forex-Trading
machFX10.py
Python
mit
11,354
0.01189
''' main issue here was to global patforrec. youll probs forget. ''' import matplotlib import matplotlib.pyplot as plt import matplotlib.ticker as mticker import matplotlib.dates as mdates import numpy as np from numpy import loadtxt import time totalStart = time.time() date,bid,ask = np.loadtxt('GBPUSD1d.txt', u...
atForRec.append(cp25) patForRec.append(cp26) patForRec.append(cp27) patForRec.append(cp28) patForRec.append(cp29) patForRec.append(cp30) def graphRawFX(): fig=plt.figure(figsize=(10,7)) ax1 = plt.subplot2grid((40,40), (0,0), rowspan=40, colspan=40) ax1.plot(date,bid) ax1.plot...
t_major_formatter(mdates.DateFormatter('%Y-%m-%d %H:%M:%S')) plt.grid(True) for label in ax1.xaxis.get_ticklabels(): label.set_rotation(45) plt.gca().get_yaxis().get_major_formatter().set_useOffset(False) ax1_2 = ax1.twinx() ax1_2.fill_between(date, 0, (ask-bid), facecolor='g',alpha=.3) ...
crazy-canux/xplugin_nagios
plugin/plugins/check-file-existence/src/check_ssh_file_existence.py
Python
gpl-2.0
10,389
0.004717
#!/usr/bin/env python2.7 # -*- coding: utf-8 -*- #=============================================================================== # Filename : check_ssh_file_existence # Author : Canux CHENG <[email protected]> # Description : Check on remote server if some files are present using SSH. #---------------...
True else: logger.debug('We are not in check period...') elif (self.options.stime and not self.options.etime) or (not self.options.stime and self.options.etime): self.unknown('Missing start/end time information, check syntax !') de
f search_files(self, files): found = [] regexp = self.options.regexp for file in files: if regexp.search(file): logger.debug('\tFound file \'%s\'.' % file) found.append(file) return found plugin = PluginCheckFileExistence(description='Check o...
jmdevince/cifpy3
lib/cif/feeder/parsers/csv.py
Python
gpl-3.0
2,069
0.0029
import csv from ..parser import Parser __author__ = 'James DeVincentis <[email protected]>' class Csv(Parser): def __init__(self, **kwargs): self.csv = csv.reader(self.file) def parsefile(self, filehandle, max_objects=1000): """Parse file provided by `filehandle`. Return `max_objects` at ...
bles.append(observable) objects += 1 self.total_objects += 1 if self.ending an
d self.total_objects >= self.end: self.parsing = False break self.writejournal() return observables
lukaszo/picar_worhshop
picar/car.py
Python
apache-2.0
3,163
0.001265
# -*- coding: UTF-8 -*- import pigpio class Car(object): PINS = ['left_pin', 'right_pin', 'forward_pin', 'backward_pin', 'enable_moving', 'enable_turning'] def __init__(self, left_pin, right_pin, forward_pin, backward_pin, enable_moving, enable_turning, start_power=65): s...
ard(self): self._pi.write(self._forward_pin, False) self._pi.write(self._backward_pin, True) self._start_moving_pwm() def faster(self, change_value=15): if self._power + change_value > 100: self._power = 100 else:
self._power += change_value self._change_power() def slower(self, change_value=15): if self._power - change_value < 30: self._power = 30 else: self._power -= change_value self._change_power() def stop_moving(self): self._pi.set_PWM_dutycycle(...
obulpathi/poppy
poppy/transport/pecan/models/request/provider_details.py
Python
apache-2.0
1,024
0
# Copyright (c) 2014 Rackspace, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance
with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # i...
ions under the License. from poppy.model.helpers import provider_details def load_from_json(json_data): access_urls = json_data.get("access_urls") error_info = json_data.get("error_info", ) provider_service_id = json_data.get("id") status = json_data.get("status") return provider_details.Provider...
BartDeCaluwe/925r
ninetofiver/migrations/0072_auto_20180502_0834.py
Python
gpl-3.0
2,929
0.002048
# -*- coding: utf-8 -*- # Generated by Django 1.11.6 on 2018-05-02 08:34 from __future__ import unicode_literals import dirtyfields.dirtyfields from django.conf import settings from django.db import migrations, models import django.db.models.deletion import django.db.models.manager class Migration(migrations.Migrati...
odels.deletion.CASCADE, related_name='polymorphic_ninetofiver.whereaboutdate_set+', to='contenttypes.ContentType')), ('timesheet', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='ninetofiver.Timesheet')), ], options={ 'ordering': ['id'], ...
'abstract': False, 'base_manager_name': 'base_objects', }, bases=(dirtyfields.dirtyfields.DirtyFieldsMixin, models.Model), managers=[ ('objects', django.db.models.manager.Manager()), ('base_objects', django.db.models.manager.Manage...
kubeflow/kfp-tekton-backend
samples/contrib/image-captioning-gcp/src/models.py
Python
apache-2.0
3,943
0.001014
# Copyright 2019 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
# x shape == (batch_size * max_length, hidden_size) x = tf.reshape(x, (-1, x.shape[2])) # output shape == (batch
_size * max_length, vocab) x = self.fc2(x) return x, state, attention_weights def reset_state(self, batch_size): return tf.zeros((batch_size, self.units))
zvezdan/pip
tests/functional/test_install_user.py
Python
mit
11,608
0
""" tests specific to "pip install --user" """ import os import textwrap from os.path import curdir, isdir, isfile import pytest from pip._internal.compat import cache_from_source, uses_pycache from tests.lib import pyversion from tests.lib.local_repos import local_checkout def _patch_dist_in_site_packages(script):...
e virtualenv site virtualenv.system_site_packages = True script.environ["PYTHONPATH"] = script.base_path / script.user_site _patch_dist_in_site_packages(script) script.pip('install', 'INITools==0.2', '--no-binary=:all:') result2 = script.pip( 'install', '--user', '-...
ary=:all:') # usersite has 0.3.1 egg_info_folder = ( script.user_site / 'INITools-0.3.1-py%s.egg-info' % pyversion ) initools_folder = script.user_site / 'initools' assert egg_info_folder in result2.files_created, str(result2) assert initools_folder in result...
DarthMaulware/EquationGroupLeaks
Leak #5 - Lost In Translation/windows/Resources/Dsz/PyScripts/Lib/dsz/mca/survey/cmd/registryhive/errors.py
Python
unlicense
1,689
0.009473
# uncompyle6 version 2.9.10 # Python bytecode 2.7 (62211) # Decompiled from: Python 3.6.0b2 (default, Oct 11 2016, 05:27:10) # [GCC 6.2.0 20161005] # Embedded file name: errors.py import mcl.status ERR_SUCCESS = mcl.status.MCL_SUCCESS ERR_INVALID_PARAM = mcl.status.framework.ERR_START ERR_INVALID_HIVE = mcl.status.fra...
ction', ERR_MARSHAL_FAILED: 'Marshaling data failed', ERR_OPEN_FAILED: 'Failed to open registry key', ERR_API_UNAVAILABLE: 'Unable to acc
ess the registry API', ERR_LOAD_FAILED: 'Failed to load hive', ERR_UNLOAD_FAILED: 'Failed to unload hive', ERR_SAVE_FAILED: 'Failed to save hive to file', ERR_RESTORE_FAILED: 'Failed to restore key from file', ERR_UNLOAD_LIST_LOCKED: 'Unable to add hive to list of hives to unload. Unload list is current...
OCA/server-tools
module_prototyper/tests/test_prototype_module_export.py
Python
agpl-3.0
2,979
0.000336
# ############################################################################# # # OpenERP, Open Source Management Solution # This module copyright (C) 2010 - 2014 Savoir-faire Linux # (<http://www.savoirfairelinux.com>). # # This program is free software: you can redistribute it and/or modify # it under the terms of ...
self.assertEqual(exporter.name, "{}.zip".format(self.prototype.name)) def test_zip_files_returns_tuple(self): """Test the method return of the method that generate the zip file.""" ret = self.main_model.zip_files(self.exporter, [self.prototype])
self.assertIsInstance(ret, tuple) self.assertIsInstance(ret.zip_file, zipfile.ZipFile) self.assertIsInstance(ret.BytesIO, io.BytesIO)
patricksnape/imageio
tests/test_avbin.py
Python
bsd-2-clause
5,018
0.007373
""" Test imageio avbin functionality. """ from pytest import raises from imageio.testing import run_tests_if_main, get_test_dir, need_internet import imageio from imageio import core from imageio.core import get_remote_file # if IS_PYPY: # skip('AVBIn not supported on pypy') test_dir = get_test_dir() mean = la...
80, 3) assert mean(im) > 100 and mean(im) < 115 def test_stream(): need_internet() with raises(IOError): imageio.read
(get_remote_file('images/cockatoo.mp4'), 'avbin', stream=5) def test_invalidfile(): need_internet() filename = test_dir+'/empty.mp4' with open(filename, 'w'): pass with raises(IOError): imageio.read(filename, 'avbin') # Check AVbinResult imageio.plugins.avbin...
Techcable/pygit2
test/test_treebuilder.py
Python
gpl-2.0
2,526
0.001188
# -*- coding: utf-8 -*- # # Copyright 2010-2014 The pygit2 contributors # # This file is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License, version 2, # as published by the Free Software Foundation. # # In addition to the permissions in the GNU General Public Li...
bld = self.repo.TreeBuilder(TREE_SHA) result = bld.write() self.assertEqual(len(bld), len(tree)) self.assertEqual(tree.id, result) def test_noop_treebuild
er_from_tree(self): tree = self.repo[TREE_SHA] bld = self.repo.TreeBuilder(tree) result = bld.write() self.assertEqual(len(bld), len(tree)) self.assertEqual(tree.id, result) def test_rebuild_treebuilder(self): tree = self.repo[TREE_SHA] bld = self.repo.Tree...
dezelin/scons
scons-local/SCons/Tool/CVS.py
Python
mit
2,859
0.007345
"""SCons.Tool.CVS.py Tool-specific initialization for CVS. There normally shouldn't be any need to import this module directl
y. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ # Copyright (c) 2001 - 2014 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"),
to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright n...
lavizhao/keyword
lucene/mult_search.py
Python
apache-2.0
2,456
0.015391
#coding: utf-8 import csv import threading import lucene from lucene import getVMEnv print "预处理" INDEX_DIR = '../index/' nt = 100000 WRITE_DIR = "../data/mult/" lucene.initVM() directory = lucene.SimpleFSDirectory(lucene.File(INDEX_DIR)) analyzer = lucene.StandardAnalyzer(lucene.Version.LUCENE_CURRENT) class sub...
label = g.readlines() label = [word.strip() for word in label] label = label[1:] for i in range(len(turn)-1): sub_cont = content[turn[i] : turn[i+1] ] sub_label = label[turn[i] : turn[i+1]][:] mthread = sub_thread(sub_cont,sub_label,i) mthread.start() if __name__ == '__ma...
print "hello world" main()
silburt/rebound2
examples/planetesimals2/movie/body_movie_output.py
Python
gpl-3.0
2,192
0.015055
#This macro outputs 3D plots of the x,y,z co-ordinates of the particles. Main movie script import sys import matplotlib.pyplot as plt import numpy as np import glob import math pi = math.pi from mpl_toolkits.mplot3d import Axes3D import re from subprocess import call def natural_key(string_): return [int(s) if s....
open(f, 'r') lines = ff.readlines() data.append(lines) except: print 'couldnt open', f, 'exiting' exit(0) n_it = len(data[0]) #calc num of lines limit = 1 #size limits for plots = (x,y,z/2)
print 'deleting any existing .png images in output_movie folder' call("rm output_movie/*.png",shell=True) collision = np.zeros(N_bodies) for iteration in xrange(0,n_it): fig = plt.figure() ax = fig.add_subplot(111, projection='3d') for i in xrange(0,N_bodies): try: line = data[i][itera...
jboeuf/grpc
tools/run_tests/python_utils/antagonist.py
Python
apache-2.0
688
0
#!/usr/bin/env python
# Copyright 2015 gRPC authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writin...
# See the License for the specific language governing permissions and # limitations under the License. """This is used by run_tests.py to create cpu load on a machine""" while True: pass
nithyanandan/general
astroutils/__init__.py
Python
mit
473
0.016913
import os as _os __version__='2.0.1' __description__='General Purpose Radio Astronomy and Data Analysis Utilities' __author__='Nithyanandan Thyagarajan' __authoremail__='[email protected]' __maintainer__='Nithyanandan Thyagarajan' __maintaineremail__='[email protected]'
__url__='http://github.com/nithyanandan/general' with open(_os.path.dirname(_os.path.abspath(__file__))+'/githash.txt', 'r') as _githash_file: __githash__ =
_githash_file.readline()
andyxhadji/incubator-airflow
airflow/contrib/hooks/gcp_kms_hook.py
Python
apache-2.0
4,060
0.001478
# -*- coding: utf-8 -*- # # 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 #...
loud Platform connection. """ def
__init__(self, gcp_conn_id='google_cloud_default', delegate_to=None): super(GoogleCloudKMSHook, self).__init__(gcp_conn_id, delegate_to=delegate_to) def get_conn(self): """ Returns a KMS service object. :rtype: apiclient.discovery.Resource """ http_authorized = sel...
akiokio/centralfitestoque
src/.pycharm_helpers/docutils/transforms/components.py
Python
bsd-2-clause
2,003
0.000999
# $Id: components.py 4564 2006-05-21 20:44:42Z wiemann $ # Author: David Goodger <[email protected]> # Copyright: This module has been placed in the public domain. """ Docutils component-related transforms. """ __docformat__ = 'reStructure
dText' import sys import os import re import time from docutils import nodes, utils from docutils import ApplicationError, DataError from docutils.transforms import Transform,
TransformError class Filter(Transform): """ Include or exclude elements which depend on a specific Docutils component. For use with `nodes.pending` elements. A "pending" element's dictionary attribute ``details`` must contain the keys "component" and "format". The value of ``details['component...
RevansChen/online-judge
Codewars/7kyu/remove-anchor-from-url/Python/solution1.py
Python
mit
102
0.019608
# Python - 3.6.0 remove_url_anchor = lambda url: url[:(('#' in
url) and url.index('#')
) or len(url)]
iw3hxn/LibrERP
export_customers/__openerp__.py
Python
agpl-3.0
2,043
0.000979
# -*- encoding: utf-8 -*- ############################################################################## # # Copyright (c) 2014 Didotech SRL (info at didotech.com) # All Rights Reserved. # # WARNING: This program as such is intended to be used by professional # programmers who take the whole re...
###################################################################### { "name": "Export Customers - Exporting customer's data in .csv file for italian fiscal program.", 'version': '2.0.1.0', 'category': 'Generic Modules/Sales customers', "descripti
on": """Exporting customer's data in .csv file """, "author": "Didotech SRL", 'website': 'http://www.didotech.com', "depends": [ "base", "base_partner_ref", "sale", "account", #"l10n_it", "l10n_it_base", "l10n_it_account" ], "init_xml": [], ...
joberembt/PokeAlarm
alarms/alarm.py
Python
gpl-3.0
1,134
0.054674
#Setup Logging import logging log = logging.getLogger(__name__) #Python modules #Local modules #External modules class Alarm(object): _defaults = { "pokemon":{}, "lures":{}, "gyms":{} } #Gather settings and create alarm def __init__(self): raise NotImplementedError("This is an abstract method.") ...
top_alert
(self, pokelure_info): raise NotImplementedError("This is an abstract method.") #Trigger an alert based on PokeGym info def gym_alert(self, pokegym_info): raise NotImplementedError("This is an abstract method.")
ddemidov/ev3dev-lang-python-1
spec_version.py
Python
mit
108
0
# ~autogen spec_ver
sion spec_version = "spec: 0.9.3-pre-r2, kernel: v3.16.7-ckt16-7-ev3dev-ev3"
# ~autogen
plxaye/chromium
src/build/android/pylib/gtest/test_runner.py
Python
apache-2.0
15,830
0.004296
# Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import glob import logging import os from pylib import android_commands from pylib import constants from pylib import perf_tests_helper from pylib.andro...
'content/test/data/sync_xmlhttprequest_during_unload.html', 'content/test/data/browser_plugin_dragging.html', 'content/test/data/fileapi', 'content/test/data/npapi', 'content/test/data/nosniff-test.html.mock-http-headers', 'content/test/data/accessibility', 'content/tes...
ld.html', 'content/test/data/rwhv_compositing_animation.html', 'content/test/data/click-noreferrer-links.html', 'content/test/data/browser_plugin_focus.html', 'content/test/data/media', ] return [] def _GetOpt
ruscito/pycomm
pycomm/ab_comm/__init__.py
Python
mit
39
0
__author__ = 'ago
stino' import logg
ing
idf/FaceReader
facerec_py/facedet/detector.py
Python
mit
5,760
0.003125
import sys import os import cv2 import numpy as np class Detector: def detect(self, src): raise NotImplementedError("Every Detector must implement the detect method.") class SkinDetector(Detector): """ Implements common color thresholding rules for the RGB, YCrCb and HSV color space. The val...
self._R3(srcHSV) return np.asarray(skinPixels, dtype=np.uint8) class CascadedDetector(Detector): """ Uses
the OpenCV cascades to perform the detection. Returns the Regions of Interest, where the detector assumes a face. You probably have to play around with the scaleFactor, minNeighbors and minSize parameters to get good results for your use case. From my personal experience, all I can say is: there's no parame...
leppa/home-assistant
tests/components/rfxtrx/test_light.py
Python
apache-2.0
12,456
0.000723
"""The tests for the Rfxtrx light platform.""" import unittest import RFXtrx as rfxtrxmod import pytest from homeassistant.components import rfxtrx as rfxtrx_core from homeassistant.setup import setup_component from tests.common import get_test_home_assistant, mock_component @pytest.mark.skipif("os.environ.get('RF...
assert entity.brightness == 255 entity.turn_off() entity_id = rfxtrx_core.RFX_DEVICES["213c7f216"].entity_id entity_hass = self.
hass.states.get(entity_id) assert "Test" == entity_hass.name assert "off" == entity_hass.state entity.turn_on() entity_hass = self.hass.states.get(entity_id) assert "on" == entity_hass.state entity.turn_off() entity_hass = self.hass.states.get(entity_id) ...
Tatsh-ansible/ansible
lib/ansible/modules/cloud/openstack/os_server_facts.py
Python
gpl-3.0
3,271
0.001529
#!/usr/bin/python # Copyright (c) 2014 Hewlett-Packard Development Company, L.P. # # This module 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 late...
'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: os_server_facts short_description: Retrieve facts about one or more compute instances author: Monty version_added: "2.0" description: - Retrieve facts about server instances from OpenStack. notes: ...
- This module creates a new top-level C(openstack_servers) fact, which contains a list of servers. requirements: - "python >= 2.6" - "shade" options: server: description: - restrict results to servers with names or UUID matching this glob expression (e.g., C<web*>). required:...
fedora-infra/fedora-packages
fedoracommunity/widgets/package/package.py
Python
agpl-3.0
4,090
0.001711
import mako import uuid import moksha.common.utils import logging import tw2.core as twc import tg from fedoracommunity.lib.utils import OrderedDict from mako.template import Template from fedoracommunity.connectors.api import get_connector log = logging.getLogger(__name__) class TabWidget(twc.Widget): template...
uilds'), ('Updates', 'package_updates'), ('Bugs', 'package_bugs'), ('Problems', 'package_problems'), ('Contents', 'package_cont
ents'), ('Changelog', 'package_changelog'), ('Sources', 'package_sources')]) #('Relationships', 'package_relationships')]) base_url = Template(text='/${kwds["package_name"]}/'); default_tab = 'Overview' args = twc.Param(default=None) ...
Achint08/open-event-orga-server
tests/unittests/views/guest/test_search.py
Python
gpl-3.0
5,392
0.002782
import unittest import urllib from datetime import datetime, timedelta from flask import url_for from app import current_app as app from app.helpers.data import save_to_db from app.helpers.flask_ext.helpers import slugify from tests.unittests.object_mother import ObjectMother from tests.unittests.utils import OpenEve...
directs=True) self.assertTrue("Super Event" in rv.data, msg=rv.data) self.assertTrue("Random Event" not in rv.data, msg=rv.data) rv = self.app.get(url_for('explore.explore_view', location=slugify('United States')), follow_redirects=True) self.assertTrue("Super Event" not ...
est_request_context(): event_one = get_event() save_to_db(event_one, "Event Saved") event_two = get_event_two() event_two.topic = 'Home & Lifestyle' event_two.sub_topic = 'Home & Garden' save_to_db(event_two, "Event Saved") query_param...
waseem18/oh-mainline
vendor/packages/Django/tests/regressiontests/generic_views/base.py
Python
agpl-3.0
14,853
0.00101
from __future__ import absolute_import import time from django.core.exceptions import ImproperlyConfigured from django.http import HttpResponse from django.test import TestCase, RequestFactory from django.utils import unittest from django.views.generic import View, TemplateView, RedirectView from . import views cla...
ew.as_view()( self.rf.get('/', REQUEST_METHOD='FAKE') ).status_code, 405) def test_invalid_keyword_argument(self): """ Test that view arguments must be predefined on the class and can't be named like a HTTP method. """ # Check each of the allowed method n...
kwargs = dict(((method, "value"),)) self.assertRaises(TypeError, SimpleView.as_view, **kwargs) # Check the case view argument is ok if predefined on the class... CustomizableView.as_view(parameter="value") # ...but raises errors otherwise. self.assertRaises(TypeError,...
Bayonet-Client/bayonet-python
bayonet/exceptions.py
Python
mit
1,465
0
import json class BayonetError(Exception): """All errors related to making an API request extend this.""" def __init__(self, message=None, request_body=None, request_headers=None, http_response_code=None, http_response_message=None): super(BayonetError, self).__init_...
s = request_headers self.http_response_code = http_response_code self.http_response_message = http_response_message # Get reason_code and reason_message from response tr
y: response_as_json = json.loads(http_response_message) if 'reason_code' in response_as_json: self.reason_code = response_as_json['reason_code'] else: self.reason_code = None if 'reason_message' in response_as_json: self.rea...
flacjacket/sympy
examples/intermediate/differential_equations.py
Python
bsd-3-clause
579
0.001727
#!/usr/bin/env python """Differential equations example Demonstrates solvin
g 1st and 2nd degree linear ordinary differential equations. """ from sympy import dsolve, Eq, Function, sin, Symbol def main(): x = Symbol("x") f = Function("f") eq = Eq(f(x).diff(x), f(x)) print "Solution for ", eq, " : ", dsolve(eq, f(x)) eq = Eq(f(x).diff(x, 2), -f(x)) print "Solution fo...
(x)) if __name__ == "__main__": main()
kumar303/addons-server
src/olympia/users/tests/test_commands.py
Python
bsd-3-clause
2,353
0
import json import uuid from django.core.management import call_command from unittest.mock import ANY, patch from six import StringIO from olympia.amo.tests import TestCase from olympia.users.management.commands.createsuperuser import ( Command as CreateSuperUser) from olympia.users.models import UserProfile @...
'[email protected]', } input.side_effect = lambda label: responses[label] count = UserProfile.objects.count() CreateSuperUser().handle() assert UserProfile.objects.count() == count + 1 user = UserProfile.objects.get(username='myusername') assert user.email == 'me@moz...
mmand( 'createsuperuser', interactive=False, username='myusername', email='[email protected]', add_to_supercreate_group=True, fxa_id=fxa_id, stdout=out) user = UserProfile.objects.get(username='myusername') assert user.ema...
barentsen/iphas-dr2
paper/figures/caldiagram/plot.py
Python
mit
2,297
0.003483
"""Plots the calibrated and uncalibrated CCD over a large area.""" import os import numpy as np import matplotlib import matplotlib.pyplot as plt from astropy.io import fits from astropy import log from dr2 import constants fields = constants.IPHASQC[constants.IPHASQC_COND_RELEASE] mask = (fields['l'] > 160.0) & (fiel...
) vmax = 500 hist, xedges, yedges = np.hist
ogram2d(np.concatenate(rmi), np.concatenate(rmha), range=[[-0.3, 3.1], [-0.1, 2.1]], bins=[320, 300]) extent = [xedges[0], xedges[-1], yedges[0], yedges[-1] ] hist[hist == 0] = np.nan plt.imshow(hist.T, extent=extent, interpol...
chfoo/cloaked-octo-nemesis
sandbox.yoyogames.com/bouncer.py
Python
gpl-3.0
1,876
0.010128
from http.server import HTTPServer, BaseHTTPRequestHandler import http.client import re import requests import urllib.parse import logging class Handler(BaseHTTPRequestHandler): def do_GET(self): path, delim, query_string = self.path.partition('?') if path != '/': self.send_er...
ttp://sandbox.yoyogames.com/games/{}/download' response = requests.get(url.format(game_id), head
ers={'Accept-Encoding': 'gzip'}) logging.info('Fetch %s', url.format(game_id)) if response.status_code != 200: logging.info('Failed fetch %s %s', response.status_code, response.reason) self.send_error(500, explain='Got {} {}'.format(response.sta...
nanaze/pystitch
pystitch/examples/closest_colors.py
Python
apache-2.0
562
0.021352
""" Find
the closest DMC colors for a hex color. Usage: python closest_colors.py <hexcolor> """ import sys from .. import color from .. import dmc_colors def main(): if len(sys.argv) < 2: sys.exit(__doc__) hex_color = sys.argv[1] rgb_color = color.RGBColorFromHexString(hex_color) print 'Given RGB color', r...
print 'Distance:', pair[1], dmc_colors.GetStringForDMCColor(pair[0]) if __name__ == '__main__': main()
plotly/plotly.py
packages/python/plotly/plotly/validators/barpolar/marker/line/_colorsrc.py
Python
mit
423
0.002364
import _plotly_utils.basevalidators class ColorsrcValidator
(_plotly_utils.basevalidators.SrcValidator): def __init__( self, plotly_name="colorsrc", parent_name="barpolar.marker.line", **kwargs ): super(ColorsrcValidator, self).__init__( plotl
y_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "none"), **kwargs )
devs1991/test_edx_docmode
venv/lib/python2.7/site-packages/numpy/oldnumeric/precision.py
Python
agpl-3.0
4,239
0.004246
# Lifted from Precision.py. This is for compatibility only. # # The character strings are still for "new" NumPy # which is the only Incompatibility with Numeric __all__ = ['Character', 'Complex', 'Float', 'PrecisionError', 'PyObject', 'Int', 'UInt', 'UnsignedInt', 'UnsignedInteger', 'string',...
all__.append('Int0') except(PrecisionError): pass try: Int8 = _lookup(_code_table, 'Integer', 8) __all__.append('Int8') except(PrecisionError): pass try: Int16 = _lookup(_code_table, 'Integer', 16) __all__.append('Int16') except(PrecisionError): pass try:
Int32 = _lookup(_code_table, 'Integer', 32) __all__.append('Int32') except(PrecisionError): pass try: Int64 = _lookup(_code_table, 'Integer', 64) __all__.append('Int64') except(PrecisionError): pass try: Int128 = _lookup(_code_table, 'Integer', 128) __all__.append('Int128') except(Precis...
ProjectALTAIR/Simulation
mdp/reward.py
Python
gpl-2.0
288
0.03125
""" Computes and stores
a lookup table for a given environment and reward function. A list of reward functions will be added here and refered to by the keyword "rType". """ class Reward: def __init__(self,environment,rTy
pe): def exampleReward(self,environment): return
reggieroby/devpack
frameworks/djangoApp/djangoApp/settings.py
Python
mit
3,105
0.001288
""" Django settings for djangoApp project. Generated by 'django-admin startproject' using Django 1.10.5. For more information on this file, see https://docs.djangoproject.com/en/1.10/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.10/ref/settings/ """ import ...
D': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.con...
GI_APPLICATION = 'djangoApp.wsgi.application' # Database # https://docs.djangoproject.com/en/1.10/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.c...
stitchfix/pybossa
test/test_authorization/__init__.py
Python
agpl-3.0
1,072
0
# -*- coding: utf8 -*- # This file is part of PyBossa. # # Copyright (C) 2013 SF Isle of Man Limited # # PyBossa 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...
the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with PyBossa. If not, see <http://www.gnu.org/licenses/>. from default import db from mock import Mock from pybossa.model.user import User def mock_current_user(anonymous=Tr...
_anonymous.return_value = anonymous mock.is_authenticated.return_value = not anonymous mock.admin = admin mock.id = id return mock
pombredanne/https-gitlab.lrde.epita.fr-vcsn-vcsn
tests/python/minimize.py
Python
gpl-3.0
5,086
0.007868
#! /usr/bin/env python import vcsn from test import * algos = ['hopcroft', 'moore', 'signature', 'weighted'] def aut(file): return vcsn.automaton(filename = medir + "/" + file) def file_to_string(file): return open(medir + "/" + file, "r").read().strip() def check(algo, aut, exp):
if isinstance(algo, list): for a in algo: check(a, aut, exp) else: print("checking minimize with algorithm ", algo) CHECK_EQ(exp, aut.minimize(algo)) # Chec
k that repeated minimization still gives the same type of # automaton. We don't want to get partition_automaton of # partition_automaton: one "layer" suffices. CHECK_EQ(exp, aut.minimize(algo).minimize(algo)) # Cominimize. # # Do not work just on the transpose_automaton...
sijie/bookkeeper
stream/clients/python/tests/unit/bookkeeper/test_futures.py
Python
apache-2.0
3,929
0
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under th...
future = _future() future.set_result('12345') callback = mock.Mock(spec=()) future.add_done_callback(callback) callback.assert_called_once_with(future) def te
st_trigger(): future = _future() callback = mock.Mock(spec=()) future.add_done_callback(callback) assert callback.call_count == 0 future.set_result('12345') callback.assert_called_once_with(future) def test_set_result_once_only(): future = _future() future.set_result('12345') with ...
4shadoww/usploit
modules/network_kill.py
Python
mit
1,182
0.002542
# Copyright (C) 2015 – 2021 Noa-Emil Nissine
n (4shadoww) from core.hakkuframework import * import os import signal from time import sleep import logging import scapy.all as scapy from core import colors conf = { "name": "network_kill", "version": "1.0", "shortdesc": "bloc
ks communication between router and target", "author": "4shadoww", "github": "4shadoww", "email": "[email protected]", "initdate": "2016-02-24", "lastmod": "2021-07-11", "apisupport": False, "needroot": 1 } # List of variables variables = OrderedDict(( ('target', ['192.168.1.2', "targ...
benoitsteiner/tensorflow-opencl
tensorflow/contrib/bayesflow/python/kernel_tests/hmc_test.py
Python
apache-2.0
14,192
0.004087
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
the log-pdf with respect to x. """ return (math_ops.reduce_sum(self._shape_param * x - self._rate_param * math_ops.exp(x), event_dims), self._shape_param - self._rate_param * math_ops.exp(x)) def _n_event_dims(self, x_shape, event_di...
p.prod([int(x_shape[i]) for i in event_dims]) def _integrator_conserves_energy(self, x, event_dims, sess, feed_dict=None): def potential_and_grad(x): log_prob, grad = self._log_gamma_log_prob_grad(x, event_dims) return -log_prob, -grad step_size = array_ops.pla...
johnbeard/kicad-git
qa/testcases/test_002_board_class.py
Python
gpl-2.0
2,834
0.009174
import code import unittest import os import pcbnew import pdb import tempfile from pcbnew import * class TestBoardClass(unittest.TestCase): def setUp(self): self.pcb = LoadBoard("data/complex_hierarchy.kicad_pcb") self.TITLE="Test Board" self.COMMENT1="For load/save test" self.F...
ad(self): pcb = BOARD() module = MODULE(pcb) pcb.Add(module) pad = D_PAD(module) module.Add(pad) pad.SetShape(P
AD_OVAL) pad.SetSize(wxSizeMM(2.0, 3.0)) pad.SetPosition(wxPointMM(0,0)) # easy case p1 = pcb.GetPad(wxPointMM(0,0)) # top side p2 = pcb.GetPad(wxPointMM(0.9,0.0)) # bottom side p3 = pcb.GetPad(wxPointMM(0,1.4)) # TODO: get pad == p1 ev...
forkbong/qutebrowser
tests/unit/misc/test_msgbox.py
Python
gpl-3.0
3,129
0
# Copyright 2015-2021 Florian Bruhin (The Compiler) <[email protected]> # vim: ft=python fileencoding=utf-8 sts=4 sw=4 et: # This file is part of qutebrowser. # # qutebrowser 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 Sof...
ef test_plain_text(qtbot, plain_text, expected): box = msgbox.msgbox(parent=None, title='foo', text='foo', icon=QMessageBox.Information, plain_text=plain_text) qtbot.add_widget(box) assert box.textFormat() == expected
def test_finished_signal(qtbot): """Make sure we can pass a slot to be called when the dialog finished.""" signal_triggered = False def on_finished(): nonlocal signal_triggered signal_triggered = True box = msgbox.msgbox(parent=None, title='foo', text='foo', ic...