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 |
|---|---|---|---|---|---|---|---|---|
Greymerk/python-rpg | src/entity/mobs/snake.py | Python | gpl-3.0 | 592 | 0.037162 | '''
Created on 2013-05-16
@author: brian
'''
import pygame
from entity import Entity
from src.ai import task
from src.abil | ities import *
class Snake(Entity):
living = "snake"
dead = "gore"
def __init__(self, world):
Entity.__init__(self, world)
self.world = world
self.hostile = True
self.health = self.maxHealth = 15
self.ai.addAI(task.Flee(self))
self.ai.addAI(task.Cast(self))
self.ai.addAI(task.Pursue(self))
... | (task.Wander(self))
self.singular = 'a snake'
def equip(self):
self.abilities = [Ability(self, Ability.lookup["PoisonBolt"])]
|
benedictpaten/cactus | src/cactus/blast/upconvertCoordinates.py | Python | mit | 4,797 | 0.001876 | #!/usr/bin/env python
from argparse import ArgumentParser
from collections import defaultdict
import sys
import os
from sonLib.bioio import cigarRead, cigarWrite, getTempFile, system
def getSequenceRanges(fa):
"""Get dict of (untrimmed header) -> [(start, non-inclusive end)] mappings
from a trimmed fasta."""
... | %d crosses "
"trimmed sequence boundary" %\
(contig,
minPos,
maxPos))
if contigNum == 1:
alignment.start2 -= currentRange[0]
... | alignment.start1 -= currentRange[0]
alignment.end1 -= currentRange[0]
alignment.contig1 = contig + ("|%d" % currentRange[0])
else:
raise RuntimeError("No trimmed sequence containing alignment "
"on %s:%... |
EricssonResearch/iot-framework-engine | semantic-adapter/test_pubsub/test_publisher.py | Python | apache-2.0 | 1,498 | 0.001335 | from lib import broker
__author__ = 'ehonlia'
import pika
import logging
logging.basicConfig()
connection = pika.BlockingConnection(pika.ConnectionParameters(host=broker.HOST))
channel = connection.channel()
channel.exchange_declare(exchange=broker.STREAM_EXCHANGE, type=broker.EXCHANGE_TYPE)
message = '''
{
"_i... | ",
"tags": "battery c | harge",
"max_val": "255"
},
"_id": "abcdef",
"_type": "stream",
"_score": 1
}
'''
channel.basic_publish(exchange=broker.STREAM_EXCHANGE,
routing_key=broker.STREAM_ROUTING_KEY,
body=message)
print " [x] Sent %r:%r" % (broker.STREAM_ROUTING_KEY, message)
connection.... |
claudelee/Wi-FiTestSuite-UCC | python/myutils.py | Python | isc | 97,701 | 0.005466 | ###################################################################
#
# Copyright (c) 2014 Wi-Fi Alliance
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copi... | .xml"
InitEnv = "\InitEnv.txt"
uccPath = '..\\..\\cmds'
DUTFeatureInfoFile = "./log/DUTFeatureInfo.html"
doc = ""
STD_INPUT_HANDLE = -10
STD_OUTPUT_HANDLE = -11
STD_ERROR_HANDLE = -12
FOREGROUND_BLUE = 0x01 # text color contains blue.
FOREGROUND_GREEN = 0x02 # text color contains green.
FOREGROUND_RED = 0x04 # text c... | ext color is intensified.
#Define extra colours
FOREGROUND_WHITE = FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_GREEN
FOREGROUND_YELLOW = FOREGROUND_RED | FOREGROUND_GREEN
FOREGROUND_CYAN = FOREGROUND_BLUE | FOREGROUND_GREEN
FOREGROUND_MAGENTA = FOREGROUND_RED | FOREGROUND_BLUE
#FOREGROUND_WHITE = FOREGROUND_GREEN | ... |
sklam/numba | numba/cuda/tests/cudapy/test_nondet.py | Python | bsd-2-clause | 1,378 | 0.001451 | import numpy as np
from numba import cuda, float32
from numba.cuda.testing import unittest, CUDATestCase
def generate_input(n):
A = np.array(np.arange(n * n).reshape(n, n), dtype=np.float32)
B = np.array(np.arange | (n) + 0, dtype=A.dtype)
return A, B
class TestCudaNonDet(CUDATestCase):
de | f test_for_pre(self):
"""Test issue with loop not running due to bad sign-extension at the for loop
precondition.
"""
@cuda.jit(argtypes=[float32[:, :], float32[:, :], float32[:]])
def diagproduct(c, a, b):
startX, startY = cuda.grid(2)
gridX = cuda.gridD... |
groovey/Documentation | sphinx/demo_docs/source/conf.py | Python | mit | 8,213 | 0.007062 | # -*- coding: utf-8 -*-
#
# Sphinx RTD theme demo documentation build configuration file, created by
# sphinx-quickstart on Sun Nov 3 11:56:36 2013.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated... | # This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Output file | base name for HTML help builder.
htmlhelp_basename = 'SphinxRTDthemedemodoc'
# -- Options for LaTeX output --------------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt... |
Netflix/security_monkey | scripts/secmonkey_role_setup.py | Python | apache-2.0 | 7,737 | 0.00517 | #!/usr/bin/env python
# Copyright 2014 Rocket-Internet
# Luca Bruno <[email protected]>
#
# 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... | figrules",
"config:describ | econfigurationrecorders",
"directconnect:describeconnections",
"ec2:describeaddresses",
"ec2:describedhcpoptions",
"ec2:describeflowlogs",
"ec2:describeimages",
"ec2:describeimageattribute",
"ec2:describeinstances",
"ec2:describeint... |
iFighting/flask | tests/test_templating.py | Python | bsd-3-clause | 11,202 | 0.005981 | # -*- coding: utf-8 -*-
"""
tests.templating
~~~~~~~~~~~~~~~~
Template functionality
:copyright: (c) 2014 by Armin Ronacher.
:license: BSD, see LICENSE for more details.
"""
import pytest
import flask
import logging
from jinja2 import TemplateNotFound
def test_context_processing():
app = f... | )
assert app.jinja_env.tests['boolean'] == boolean
assert app.jinja_env.tests['boolean'](False)
def test_add_tem | plate_test():
app = flask.Flask(__name__)
def boolean(value):
return isinstance(value, bool)
app.add_template_test(boolean)
assert 'boolean' in app.jinja_env.tests.keys()
assert app.jinja_env.tests['boolean'] == boolean
assert app.jinja_env.tests['boolean'](False)
def test_template_test... |
USStateDept/FPA_Core | openspending/forum/utils/decorators.py | Python | agpl-3.0 | 1,481 | 0.002026 | # -*- coding: utf-8 -*-
"""
flaskbb.utils.decorators
~~~~~~~~~~~~~~~~~~~~~~~~
A place for our decorators.
:copyright: (c) 2014 by the FlaskBB Team.
:license: BSD, see LICENSE for more details.
"""
from functools import wraps
from flask import abort
from flask_login import current_user
from opens... | opic_id = kwargs['topic_id'] if 'topic_id' in kwargs else args[1]
# from openspending.forum.forum.models import Forum, Topic
# topic = Topic.query.filter_by(id=topic_id).first()
# user_forums = Forum.query.all()
# if len(user_forums) < 1:
# abort(403)
|
# return func(*args, **kwargs)
return decorated
|
yukondude/Twempest | build-readme.py | Python | gpl-3.0 | 1,279 | 0.002346 | #!/usr/bin/env python
""" (Re)build the README.md file from README-template.md.
"""
# This file is part of Twempest. Copyright 2018 Dave Rogers <[email protected]>. Licensed under the GNU General Publ | ic
# License, version 3. Refer to the attached LICENSE file or see <http://www.gnu.org/licenses/> for details.
import datetime
import os
import subprocess
import twempest
if __name__ == '__main__':
here = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(here, "README-template.md"), "r") as... | read()
today = datetime.date.today().strftime("%B %-d, %Y")
version = twempest.__version__
readme = readme.replace("@@TODAY@@", today)
readme = readme.replace("@@VERSION@@", version)
help_text = subprocess.check_output(["twempest", "--help"]).decode("utf-8").strip()
readme = readme.replace("@... |
openstack/python-heatclient | heatclient/osc/v1/resource_type.py | Python | apache-2.0 | 4,711 | 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
# distrib... | on v1 resource type implementations"""
import logging
from osc_lib.command import command
from osc_lib import exceptions as exc
from osc_lib.i18n import _
import six
from heatclient.common import format_utils
from heatclient.common import utils as heat_utils
from heatclie | nt import exc as heat_exc
class ResourceTypeShow(format_utils.YamlFormat):
"""Show details and optionally generate a template for a resource type."""
log = logging.getLogger(__name__ + ".ResourceTypeShow")
def get_parser(self, prog_name):
parser = super(ResourceTypeShow,
s... |
caot/intellij-community | python/testData/inspections/PyTypeCheckerInspection/MetaClassIteration.py | Python | apache-2.0 | 340 | 0.014706 | class M1(type):
def __it | er__(self):
pass
class M2(type):
| pass
class C1(object):
__metaclass__ = M1
class C2(object):
__metaclass__ = M2
class B1(C1):
pass
for x in C1:
pass
for y in <warning descr="Expected 'collections.Iterable', got 'C2' instead">C2</warning>:
pass
for z in B1:
pass
|
cpodlesny/lisbon | src/contacts/views.py | Python | mit | 6,745 | 0.000593 | from django.contrib import messages
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.core.urlresolvers import reverse
from django.shortcuts import render, redirect, get_object_or_404
from django.utils.translation import ugettext_lazy as _
from helpers.models import Helpers
from offe... | instance.save()
messages.success(request, _('Contact Created'))
return redirect('contact:list')
context = {
'footer': {
'about': footer[lang],
'icon': Helpers.objects.get(id=1).footer_icon
},
'nav': {
... | y.objects.all(),
},
'company': get_company(),
'title': _('Create Contact'),
'breadcrumbs': breadcrumbs,
'value': _('Add'),
'form': form
}
return render(request, 'templates/_form.html', context)
def contact_update(request, pk=None... |
datamade/nyc-councilmatic | nyc/models.py | Python | mit | 4,078 | 0.002946 | from django.conf import settings
from councilmatic_core.models import Bill, Organization, Action
from datetime import datetime
import pytz
app_timezone = pytz.timezone(settings.TIME_ZONE)
class NYCBill(Bill):
class Meta:
proxy = True
def __str__(self):
return self.friendly_name
# NYC CU... | def _is_stale(self, last_acti | on_date):
# stale = no action for 6 months
if last_action_date:
timediff = datetime.now().replace(tzinfo=app_timezone) - last_action_date
return (timediff.days > 150)
else:
return True
# NYC CUSTOMIZATION
# whether or not a bill has reached its final ... |
ruxkor/pulp-or | setup.py | Python | mit | 1,930 | 0.013472 | #!/usr/bin/env/python
"""
Setup script for PuLP added by Stuart Mitchell 2007
Copyright 2007 Stuart Mitchell
"""
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup
Description = open('README').read()
License = open('LICENSE').read()
Version = open('VERSION').read().strip()
setup(name=... | ],
package_dir={'':'src'},
packages = ['pulp', 'pulp.solverdir'],
package_data = {'pulp' : ["AUTHORS","LICENSE",
"pulp.cfg.linux",
"pulp.cfg.win",
"LICENSE.CoinMP.txt",
"AUTH... | 'pulp.solverdir' : ['*','*.*']},
install_requires = ['pyparsing>=1.5.2'],
entry_points = ("""
[console_scripts]
pulptest = pulp:pulpTestAll
pulpdoctest = pulp:pulpDoctest
"""
),
)
|
synapse-wireless/bulk-reprogramming | snappyImages/synapse/sysInfo.py | Python | apache-2.0 | 4,335 | 0.026298 | # (c) Copyright 2008-2015 Synapse Wireless, Inc.
"""System Info IDs - used in 'getInfo()' and 'getStat()' calls"""
# Types
SI_TYPE_VENDOR = 0
SI_TYPE_RADIO = 1
SI_TYPE_CPU = 2
SI_TYPE_PLATFORM = 3
SI_TYPE_BUILD = 4
SI_TYPE_VERSION_MAJOR = ... | cast only
SI_MULTI_PKT_GROUP = 27 # Multicast or Directed Multicast only
SI_MULTI_PKT_ORIGINAL_TTL = 28 # Directed Multicast only
# Vendors
SI_VENDOR_SYNAPSE = 0
SI_VENDOR_FREESCALE = 2 # value = 1 skipped
SI_VENDOR_CEL = 3
SI_VENDOR_ATMEL = 4
SI_VENDOR_SILICON_LABS = 5
# Radio... | O_802_15_4 = 0
SI_RADIO_NONE = 1
SI_RADIO_900 = 2
# CPUs
SI_CPU_MC9S08GT60A = 0
SI_CPU_8051 = 1
SI_CPU_MC9S08QE = 2
SI_CPU_COLDFIRE = 3
SI_CPU_ARM7 = 4
SI_CPU_ATMEGA = 5
SI_CPU_SI1000 = 6
SI_CPU_SI1000 = 6
SI_CPU_X86 = 7
SI_CPU_UNKNOWN = 8
SI_CPU_SPARC_LEON = 9
SI_CPU_ARM_CO... |
BizarroSolutions/mcg | cli/init.py | Python | gpl-3.0 | 1,266 | 0.00079 | from cement.utils.misc import init_defaults
from configparser import NoSectionError
from cli.Mcg import Mcg
from core.db.MongoDB import MongoDB
def main():
# Logging config (mcg section in file mcg.conf)
defaults = init_defaults('mcg', 'log.logging')
defaults['log.logging']['file'] = 'mcg.log'
with M... | config.ge | t('mongodb', 'db')
}
)
except NoSectionError:
print("Configuration File Not Found or [mongodb] Section Not Found")
print("Create the file /etc/mcg/mcg.conf for Linux Systems")
print("Create the file C:/mcg/mcg.conf for Windows Systems")
ap... |
zasdfgbnm/qutip | qutip/tests/test_metrics.py | Python | bsd-3-clause | 5,002 | 0.0002 | # -*- coding: utf-8 -*-
"""
Simple tests for metrics and pseudometrics implemented in
the qutip.metrics module.
"""
# This file is part of QuTiP: Quantum Toolbox in Python.
#
# Copyright (c) 2011 and later, Paul D. Nation and Robert J. Johansson.
# All rights reserved.
#
# Redistribution and use in source and... | """
Metrics: Fidelity, mixed state inequality
"""
for k in range(10):
rho1 = rand_dm(25, 0.25)
rho2 = rand_dm(25, 0.25)
F = | fidelity(rho1, rho2)
assert_(1-F <= sqrt(1-F**2))
def test_fidelity2():
"""
Metrics: Fidelity, invariance under unitary trans.
"""
for k in range(10):
rho1 = rand_dm(25, 0.25)
rho2 = rand_dm(25, 0.25)
U = rand_unitary(25, 0.25)
F = fidelity(rho1, rho2)
F... |
qsnake/werkzeug | examples/plnt/utils.py | Python | bsd-3-clause | 3,618 | 0.000276 | # -*- coding: utf-8 -*-
"""
plnt.utils
~~~~~~~~~~
The planet utilities.
:copyright: (c) 2009 by the Werkzeug Team, see AUTHORS for more details.
:license: BSD.
"""
import re
from os import path
from jinja2 import Environment, FileSystemLoader
from werkzeug import Response, Local, LocalManager, url... | atch, _striptags_re.sub('', s))
class Pagination(object):
"""
Paginate a SQLAlchemy query object.
"""
def __init__(self, query, per_page, page, endpoint):
self.query = query
self.per_page = per_page
self.page | = page
self.endpoint = endpoint
@cached_property
def entries(self):
return self.query.offset((self.page - 1) * self.per_page) \
.limit(self.per_page).all()
@cached_property
def count(self):
return self.query.count()
has_previous = property(lambda x... |
arjitc/librenms | LibreNMS/service.py | Python | gpl-3.0 | 24,575 | 0.004557 | import LibreNMS
import json
import logging
import os
import pymysql
import subprocess
import threading
import sys
import time
from datetime import timedelta
from datetime import datetime
from logging import debug, info, warning, error, critical, exception
from platform import python_version
from time import sleep
fro... | alling populate()
"""
self._uuid = str(uuid1())
self.set_name(gethostname())
def set_name(self, name):
if name:
self.name = name.strip()
self.unique_name = "{}-{}".format(self.name, self._uuid)
class PollerConfig:
def __init__(self, workers, freq... | ulate = calculate
# config variables with defaults
BASE_DIR = os.path.abspath(os.path.join(os.path.dirname(os.path.realpath(__file__)), os.pardir))
node_id = None
name = None
unique_name = None
single_instance = True
distributed = False
group = 0
debug = False
log_level = 20
... |
nlgcoin/guldencoin-official | test/functional/feature_minchainwork.py | Python | mit | 4,129 | 0.003875 | #!/usr/bin/env python3
# Copyright (c) 2017-2018 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test logic for setting nMinimumChainWork on command line.
Nodes don't consider themselves out of "init... | ng
# block relay to inbound peers.
self.setup_nodes()
for i in range(self.num_nodes-1):
connect_nodes(self.nodes[i+1], i)
def run_test(self):
# Start building a chain on node0. node2 shouldn't be able to sync until node1's
| # minchainwork is exceeded
starting_chain_work = REGTEST_WORK_PER_BLOCK # Genesis block's work
self.log.info("Testing relay across node %d (minChainWork = %d)", 1, self.node_min_work[1])
starting_blockcount = self.nodes[2].getblockcount()
num_blocks_to_generate = int((self.node_min... |
kornai/4lang | exp/corp/xsum.py | Python | mit | 63 | 0 | import sys
print(sum(in | t(line.stri | p()) for line in sys.stdin))
|
ecolell/aquire | version.py | Python | mit | 86 | 0.023256 | # D | o not edit this file, pipeline versioning is governed by git tags
__versio | n__=0.0.0 |
cread/ec2id | cherrypy/test/test_proxy.py | Python | apache-2.0 | 4,957 | 0.006052 | from cherrypy.test import test
test.prefer_parent_path()
import cherrypy
script_names = ["", "/path/to/myapp"]
def setup_server():
# Set up site
cherrypy.config.update({
'environment': 'test_suite',
'tools.proxy.on': True,
'tools.proxy.base': 'www.mydomain.test',
... | def pageurl(self):
return self.thisnewpage
pageurl.exposed = True
def index(self) | :
raise cherrypy.HTTPRedirect('dummy')
index.exposed = True
def remoteip(self):
return cherrypy.request.remote.ip
remoteip.exposed = True
def xhost(self):
raise cherrypy.HTTPRedirect('blah')
xhost.exposed = True
... |
nburn42/tensorflow | tensorflow/python/kernel_tests/identity_op_py_test.py | Python | apache-2.0 | 2,642 | 0.007949 | # Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed unde | r the Apache License, Version 2.0 (the "License");
# you may not use t | his 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 A... |
pivotaccess2007/RapidSMS-Rwanda | apps/poll/urls.py | Python | lgpl-3.0 | 992 | 0.027218 | import os
import views as pv
from django.conf.urls.defaults import *
urlpatterns = patterns('',
# serve assets via django, during development
(r'^poll/assets/(?P<path>.*)$', "django.views.static.serve",
{"document_root": os.path.dirname(__file__) + "/assets"}),
# graphs are generated and stored to be v... | ,
(r'^poll/dashboard$', pv.dashboard),
(r'^poll/dashboard/(?P<id>\d+)$', pv.dashboard),
(r'^poll/questions$', pv.manage_questions),
(r'^poll/question/(?P<id>\d+)$', pv.manage_questions),
(r'^poll/question/(?P<id>\d+)/edit$', pv.edit_question),
(r'^poll/question/add$', pv.a | dd_question),
(r'^poll/log$', pv.message_log),
# ajax
(r'^poll/moderate/(?P<id>\d+)/(?P<status>win|fail)$', pv.moderate),
(r'^poll/correct/(?P<id>\d+)$', pv.correction),\
)
|
belokop-an/agenda-tools | code/htdocs/categoryConfCreationControl.py | Python | gpl-2.0 | 677 | 0.048744 | import MaKaC.webinterface.rh.categoryMod as categoryMod
def index(req, **params):
return catego | ryMod.RHCategoryConfCreationControl( req ).process( param | s )
def setCreateConferenceControl( req, **params ):
return categoryMod.RHCategorySetConfControl( req ).process( params )
def selectAllowedToCreateConf( req, **params ):
return categoryMod.RHCategorySelectConfCreators( req ).process( params )
def addAllowedToCreateConferences( req, **params ):
return cat... |
kayak/pypika | pypika/tests/dialects/test_postgresql.py | Python | apache-2.0 | 9,532 | 0.003462 | import unittest
from collections import OrderedDict
from pypika import (
Array,
Field,
JSON,
QueryException,
Table,
)
from pypika.dialects import PostgreSQLQuery
class InsertTests(unittest.TestCase):
table_abc = Table("abc")
def test_array_keyword(self):
q = PostgreSQLQuery.into(... | PostgreSQLQuery.from_(self.table_abc)
.where(self.table_abc.foo == sel | f.table_abc.bar)
.delete()
.returning(field_from_diff_table)
)
def test_queryexception_if_returning_used_on_invalid_query(self):
with |
chaicko/AlgorithmicToolbox | test/data_structures/test_binary_search_trees.py | Python | gpl-3.0 | 7,486 | 0.001336 | # import data_structures.binary_search_trees.rope as rope
import data_structures.binary_search_trees.set_range_sum as set_range_sum
import data_structures.binary_search_trees.tree_orders as | tree_orders
import pytest
import os
import sys
import resource
CI = os.environ.get('CI') == 'true'
# Helpers
class BinarySearchTree:
def __init__(self):
self.root = None
self.size = 0
def length(self):
return self.size
def __len__(self):
return self.size
def __ite... | :
if self.root:
res = self.find(key, self.root)
if res and res.key == key:
return res.payload
else:
return None
else:
return None
def find(self, key, node):
if node.key == key:
return node
i... |
newvem/pytz | pytz/zoneinfo/America/Inuvik.py | Python | mit | 5,554 | 0.206338 | '''tzinfo timezone information for America/Inuvik.'''
from pytz.tzinfo import DstTzInfo
from pytz.tzinfo import memorized_datetime as d
from pytz.tzinfo import memorized_ttinfo as i
class Inuvik(DstTzInfo):
'''America/Inuvik timezone definition. See datetime.tzinfo for details'''
zone = 'America/Inuvik'
... | 25,8,0,0),
d(199 | 3,4,4,9,0,0),
d(1993,10,31,8,0,0),
d(1994,4,3,9,0,0),
d(1994,10,30,8,0,0),
d(1995,4,2,9,0,0),
d(1995,10,29,8,0,0),
d(1996,4,7,9,0,0),
d(1996,10,27,8,0,0),
d(1997,4,6,9,0,0),
d(1997,10,26,8,0,0),
d(1998,4,5,9,0,0),
d(1998,10,25,8,0,0),
d(1999,4,4,9,0,0),
d(1999,10,31,8,0,0),
d(2000,4,2,9,0,0),
d(2000,10,29,8,0,0),
d(200... |
babyliynfg/cross | tools/project-creator/Python2.6.6/Lib/test/test_scope.py | Python | mit | 16,217 | 0.003761 | import unittest
from test.test_support import (check_syntax_error, _check_py3k_warnings,
check_warnings, run_unittest)
class ScopeTests(unittest.TestCase):
def testSimpleNesting(self):
def make_adder(x):
def adder(y):
return x + y
... | urn n * fact(n - 1)
if x >= 0:
return fact(x)
else:
raise ValueError, | "x must be >= 0"
self.assertEqual(f(6), 720)
def testUnoptimizedNamespaces(self):
check_syntax_error(self, """\
def unoptimized_clash1(strip):
def f(s):
from string import *
return strip(s) # ambiguity: free or local
return f
""")
check_syntax_err... |
iambocai/ansible | v2/test/errors/test_errors.py | Python | gpl-3.0 | 3,194 | 0.003444 | # (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... | icense
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from ansible.compat.tests import unittest
from ansible.parsing.yaml.objects import Ansible | BaseYAMLObject
from ansible.errors import AnsibleError
from ansible.compat.tests import BUILTINS
from ansible.compat.tests.mock import mock_open, patch
class TestErrors(unittest.TestCase):
def setUp(self):
self.message = 'This is the error message'
self.obj = AnsibleBaseYAMLObject()
def tea... |
Ecotrust/forestplanner | lot/trees/tests/__init__.py | Python | bsd-3-clause | 25 | 0 | from .unittest | s import *
| |
prakashpp/trytond-google-merchant | channel.py | Python | bsd-3-clause | 797 | 0 | # -*- coding: utf-8 -*-
"""
channel.py
:copyright: (c) 2015 by Fulfil.IO Inc.
:license: see LICENSE for more details.
"""
from trytond.pool import PoolMeta
from trytond.model import fields
__all__ = ['Channel']
__metaclass__ = PoolMeta
def submit_to_google(url, data):
import requests
import json... | 39DUnsNGb9I6U5FQqRJXNyPb3a0Dk1OWzA', # noqa
}
)
class Channel:
__name__ = "sale.channel"
website = fields.Many2One('nereid.website', 'Website', s | elect=True)
@classmethod
def upload_products_to_google_merchant(cls):
pass
|
elena/django | tests/check_framework/test_multi_db.py | Python | bsd-3-clause | 1,726 | 0.000579 | from unittest import mock
from django.db import connections, models
from django.test import SimpleTestCase
from django.test.utils import isolate_apps, override_settings
class TestRouter:
"""
Routes to the 'other' database if the model name starts with 'Other'.
"""
def allow_ | migrate(self, db, app_label, model_name=None, **hints):
return db == ('other' if model_name.startswith('other') else 'default')
@override_settings(DATABASE_ROUTERS=[TestRouter()])
@isolate_apps('check_framework')
class TestMultiDBChecks(SimpleTestCase):
def _patch_check_field_on(self, db):
return... | ns[db].validation, 'check_field')
def test_checks_called_on_the_default_database(self):
class Model(models.Model):
field = models.CharField(max_length=100)
model = Model()
with self._patch_check_field_on('default') as mock_check_field_default:
with self._patch_check... |
popazerty/try | lib/python/Plugins/Extensions/IniLastFM/LastFMConfig.py | Python | gpl-2.0 | 3,064 | 0.014687 | from Screens.Screen import Screen
from Components.config import config, getConfigListEntry, ConfigSubsection, ConfigText
from Components.ConfigList import ConfigListScreen
from Components.Label import Label
from Components.ActionMap import ActionMap
# for localized messages
from . import _
class LastFMConfigS... | ), config.plugins.LastFM.description),
getConfigListEntry(_("Last.FM Username"), config.plugins.LastFM.us | ername),
getConfigListEntry(_("Password"), config.plugins.LastFM.password),
getConfigListEntry(_("Send now playing Audio Tracks"), config.plugins.LastFM.sendSubmissions),
getConfigListEntry(_("Use LastFM Proxy"), config.plugins.LastFM.useproxy),
getConfigListEntry(_("LastFM Proxy port"), config.plugins.Last... |
bjolivot/ansible | lib/ansible/modules/notification/telegram.py | Python | gpl-3.0 | 2,822 | 0.007087 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2016, Artem Feofanov <[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... | sible. If not, see <http://www.gnu.org/licenses/>.
#
ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = """
module: telegram
version_added: "2.2"
author: "Artem Feofanov (@tyouxa)"
short_description: module fo... | ou will require a telegram account and create telegram bot to use this module.
options:
msg:
description:
- What message you wish to send.
required: true
token:
description:
- Token identifying your telegram bot.
required: true
chat_id:
description:
- Telegram group or user c... |
azilya/Zaliznyak-s-grammatical-dictionary | gdictionary/getfinal.py | Python | lgpl-3.0 | 1,310 | 0.012977 | import csv, os
def adding(lemma_noun, file_noun, tags_noun, lemma_verb, file_verb, tags_verb):
"""
Creates a file with final results: lemmas for unknown words and Zaliznyak's tags for them. | """
outfile = open('predicted.csv', 'w', encoding = 'utf-8')
writer = csv.writer(outfile, lineterminator='\n', delimiter=',')
writer.writerow(['Word', 'Class', 'Gender']) #csv format
infile_noun = open(file_noun, 'r', encoding ='utf-8')
gen =[]
for line in infile_noun:
elems = l... | emove(gen[0])
for i, elem in enumerate(lemma_noun):
one = elem
three = gen[i]
two = tags_noun[i]
writer.writerow([one, two, three])
infile_noun.close()
os.remove(file_noun)
##########################
##########################
infile_... |
opendaylight/netvirt | resources/tools/odltools/odltools/cli_utils.py | Python | epl-1.0 | 1,857 | 0.000539 | # Copyright 2018 Red Hat, Inc. and others. 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 appli... | parser.add_argument("--path",
help="the directory that the parsed data is written into")
parser.add_argument("--transport", default="http",
choices=["http", "https"],
help="transport for connections")
| parser.add_argument("-i", "--ip", default="localhost",
help="OpenDaylight ip address")
parser.add_argument("-t", "--port", default="8181",
help="OpenDaylight restconf port, default: 8181")
parser.add_argument("-u", "--user", default="admin",
... |
cornell-brg/pydgin | arm/bootstrap.py | Python | bsd-3-clause | 8,853 | 0.029369 | #=======================================================================
# bootstrap.py
#=======================================================================
from machine import State
from pydgin.utils import r_uint
#from pydgin.storage import Memory
EMULATE_GEM5 = False
EMULATE_SIMIT = True
# Currently... | lignment - 1)
# calculate padding to align boundary
# NOTE: MIPs approach (but ignored by gem5)
#stack_nbytes[3] = 16 - (sum_(stack_nbytes[:3]) % 16)
# NOTE: gem5 ARM approach
stack_nbytes[3] = round_up( sum_(stack_nbytes) ) - sum_(stack_nbytes)
if EMULATE_SIMIT:
stack_nby | tes[3] = 0
def round_down( val ):
alignment = 16
return val & ~(alignment - 1)
# calculate stack pointer based on size of storage needed for args
# TODO: round to nearest page size?
stack_ptr = round_down( stack_base - sum_( stack_nbytes ) )
if EMULATE_SIMIT:
stack_ptr = stack_base - MAX_ENVIRON... |
JohnJakeChambers/break-the-vigenere | VigenereCracker.py | Python | gpl-3.0 | 3,920 | 0.009949 | class VigenereCracker:
def __init__(self, language, minLen, maxLen):
self.LANGUAGE = language
#Key length could be from 1 to 13 bytes
self.KEYLENBOUNDS = range(minLen,maxLen)
self.SUMQPSQUARE = 0.065
self.KEYLENGTHFOUND = -1
self.KEY = []
... | = []
def | __FoundKeyLen(self):
if not self.CONTENT:
return None
_KEYLENDICT_ = {}
for i in self.KEYLENBOUNDS:
retChar = self.takeCharEveryKPos(0, i, self.CONTENT)
mapChar = self.countOccurrenceAndFrequency(retChar)
_KEYLENDICT_[i] = mapChar
... |
openstack/heat | heat/tests/test_stack_lock.py | Python | apache-2.0 | 12,477 | 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/li | censes/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limi... | tils
from heat.engine import stack_lock
from heat.objects import stack as stack_object
from heat.objects import stack_lock as stack_lock_object
from heat.tests import common
from heat.tests import utils
class StackLockTest(common.HeatTestCase):
def setUp(self):
super(StackLockTest, self).setUp()
s... |
amiraliakbari/static-inspector | inspector/utils/visualization/graph.py | Python | mit | 1,351 | 0.004441 | # -*- coding: utf-8 -*-
import os
from inspector.utils.strings import render_template
def generate_graph_html(graph, filename):
"""
:type graph: networkx.Graph
:param str filename: path to save the generated html file
"""
params = {
'nodes': [],
'links': [],
}
ids... | e):
params['links'].append('{source:%d,target:%d,value:%d,group:%d}' % (ids[unicode(u)],
ids[unicode(v)],
data.get('weight', 1),
... | data.get('group', 1)))
params['nodes'] = ','.join(params['nodes'])
params['links'] = ','.join(params['links'])
# generating output
current_dir = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(current_dir, 'templates', 'force_directed_graph.h... |
Herpinemmanuel/Oceanography | Cas_1/Salinity/A_General_Salinity.py | Python | mit | 983 | 0.016277 | import numpy as np
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
from xmitgcm import open_mdsdataset
from car | topy.mpl.gridliner import LONGITUDE_FORMATTER, LATITUDE_FORMATTER
plt.ion()
dir1 = '/homedata/bderembl/runmit/test_southatlgyre'
ds1 = open_mdsdataset(dir1,prefix=['S'])
nt = 0
nz = 0
# Cartography S : Salinity
plt.figure(1)
ax = plt.subplot | (projection=ccrs.PlateCarree());
ds1['S'][nt,nz,:,:].plot.pcolormesh('XC', 'YC', ax=ax);
plt.title('Case 1 : Salinity')
ax.coastlines()
gl = ax.gridlines(draw_labels=True, alpha = 0.5, linestyle='--');
gl.xlabels_top = False
gl.ylabels_right = False
gl.xformatter = LONGITUDE_FORMATTER
gl.yformatter = LATITUDE_FORMATTER... |
YtoTech/latex-on-http | latexonhttp/resources/fetching.py | Python | agpl-3.0 | 4,503 | 0.000666 | # -*- coding: utf-8 -*-
"""
latexonhttp.resources.fetching
~~~~~~~~~~~~~~~~~~~~~
Fetchers for resources.
:copyright: (c) 2019 Yoan Tournade.
:license: AGPL, see LICENSE for more details.
"""
import base64
import requests
import logging
logger = logging.getLogger(__name__)
# ; # TODO Extract the f... | compressed file upload?
}
def fetch_resources(resources, on_fetched, get_from_cache=None):
"""
on_fetched(resource, data)
get_from_cache(resource)
"""
# TODO Fetch cache? (URL, git, etc.)
# Managed by each fetcher, with options provided in input.
| # (No fetch cache by default)
# TODO Passing options to fetcher:
# (for eg. retries and follow_redirects for URL, encoding, etc.)
# - default option dict;
# - override by input.
for resource in resources:
resource_fetcher = FETCHERS.get(resource["type"])
if not resource_fetcher:
... |
dcristoloveanu/qpid-proton | proton-c/env.py | Python | apache-2.0 | 2,444 | 0.003682 | #
# 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... | express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
#
#
# A platform-agnostic tool for running a program in a modified environment.
#
import sys
import os
import subprocess
from optparse import OptionParser
def main(argv=None):
parser = Opt... | on("-i", "--ignore-environment",
action="store_true", default=False,
help="Start with an empty environment (do not inherit current environment)")
(options, args) = parser.parse_args(args=argv)
if options.ignore_environment:
new_env = {}
else:
new... |
EdDev/vdsm | tests/vmapi_test.py | Python | gpl-2.0 | 3,422 | 0 | #
# Copyright 2014-2017 Red Hat, Inc.
#
# 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 distributed ... | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
#
# Refer to the README and COPYING files for full details of the license
#
from __future__ import absolute_import
from vdsm.virt import vmexitreason
from virt import vm
from vdsm.common import cache
from vdsm.common import define
from test... | tValidation import brokentest
from monkeypatch import MonkeyPatch, MonkeyPatchScope
import vmfakelib as fake
class TestSchemaCompliancyBase(TestCaseBase):
@cache.memoized
def _getAPI(self):
paths = [vdsmapi.find_schema()]
return vdsmapi.Schema(paths, True)
def assertVmStatsSchemaComplianc... |
scrapinghub/exporters | tests/test_persistence.py | Python | bsd-3-clause | 3,967 | 0.002017 | import unittest
from mock import patch
from exporters.exporter_config import ExporterConfig
from exporters.persistence.base_persistence import BasePersistence
from exporters.persistence.pickle_persistence import PicklePersistence
from exporters.utils import remove_if_exists
from .utils import valid_config_with_updates... | tence(expor | ter_config.persistence_options, meta())
persistence.generate_new_job()
def test_delete_instance(self):
exporter_config = ExporterConfig(self.config)
with self.assertRaises(NotImplementedError):
persistence = BasePersistence(exporter_config.persistence_options, meta())
... |
AlSayedGamal/python_zklib | zklib/zkRegevent.py | Python | gpl-2.0 | 2,460 | 0.01748 | from struct import pack, unpack
from datetime import datetime, date
import sys
from zkconst import *
def reverseHex(hexstr):
tmp = ''
for i in reversed( xrange( len(hexstr)/2 ) ):
tmp += hexstr[i*2:(i*2)+2]
return tmp
def zkRegevent(self):
"""register for live events"""
print "r... | lens = len(data_recv[:8]) / 2
fstr = str(lens) + "H"
if unpack(fstr, data_recv[:8])[0] == CMD_DATA:
i = i +1
| print "data package " , unpack(fstr, data_recv[:8])[0]
lens = len(data_recv) / 2
fstr = str(lens) + "H"
print "data unpack", unpack(fstr, data_recv)
if i == 1:
self.attendancedata.append(data_recv)
elif i == 2:
... |
carver/ens.py | tests/test_setup_name.py | Python | mit | 3,383 | 0.001478 |
import pytest
from unittest.mock import Mock
from ens.main import UnauthorizedError, AddressMismatch, UnownedName
'''
API at: https://github.com/carver/ens.py/issues/2
'''
@pytest.fixture
d | ef ens2(ens, mocker, addr1, addr9, hash9):
mocker.patch.object(ens, '_setup_reverse')
mocker.patch.object(ens, 'address', return_value=None)
mocker.patch.object(ens, 'owner', return_value=None)
| mocker.patch.object(ens.web3, 'eth', wraps=ens.web3.eth, accounts=[addr1, addr9])
mocker.patch.object(ens, 'setup_address')
'''
mocker.patch.object(ens, '_resolverContract', return_value=Mock())
mocker.patch.object(ens, '_first_owner', wraps=ens._first_owner)
mocker.patch.object(ens, '_claim_owner... |
GenericMappingTools/gmt-python | examples/gallery/images/track_sampling.py | Python | bsd-3-clause | 1,614 | 0.005576 | """
Sampling along tracks
---------------------
The :func:`pygmt.grdtrack` function samples a raster grid's value along specified
points. We will need to input a 2D raster to ``grid`` which can be an
:class:`xarray.DataArray`. The argument passed to the ``points`` parameter can be a
:class:`pandas.DataFrame` table whe... | e world's ocean ridges at specified track points
track = pygmt.grdtrack(points=points, grid=grid, newcolname="bathymetry")
fig = pygmt.Figure()
# Plot the earth relief grid on Cylindrical Stereographic projection, masking land areas
fig.basemap(region="g", projection="Cyl_stere/150/-20/15c", frame=True)
fig.grdimag | e(grid=grid, cmap="gray")
fig.coast(land="#666666")
# Plot the sampled bathymetry points using circles (c) of 0.15 cm size
# Points are colored using elevation values (normalized for visual purposes)
fig.plot(
x=track.longitude,
y=track.latitude,
style="c0.15c",
cmap="terra",
color=(track.bathymetry... |
Microvellum/Fluid-Designer | win64-vc/2.78/Python/lib/site-packages/PIL/_binary.py | Python | gpl-3.0 | 1,855 | 0.001078 | #
# The Python Imaging Library.
# $Id$
#
# Binary input/output support routines.
#
# Copyright (c) 1997-2003 by Secret Labs AB
# Copyright (c) 1995-2003 by Fredrik Lundh
# Copyright (c) 2012 by Brian Crowell
#
# See the README file for information on usage and redistribution.
#
from struct import unpack, pack
if byte... | :o+2])[0]
def si16le(c, o=0):
"""
Converts a 2-by | tes (16 bits) string to a signed integer.
c: string containing bytes to convert
o: offset of bytes to convert in string
"""
return unpack("<h", c[o:o+2])[0]
def i32le(c, o=0):
"""
Converts a 4-bytes (32 bits) string to an unsigned integer.
c: string containing bytes to convert
o: off... |
michaelnetbiz/mistt-solution | app/models/cases.py | Python | mit | 114 | 0 | from | app import db, GenericRecord
class Case(GenericRecord):
__collection__ = 'cases' |
db.register([Case])
|
elebihan/grissom | grissom/__init__.py | Python | gpl-3.0 | 909 | 0 | # -*- coding: utf-8 -*-
#
# grissom - FOSS compliance tools
#
# Copyright (c) Eric Le Bihan <[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 3 of the ... |
# 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 this program. If not, see <http://www.gnu.org/licenses/>.
#... | ort formatters
from . import legal
# vim: ts=4 sts=4 sw=4 et ai
|
ShengRang/c4f | leetcode/combination-sum-ii.py | Python | gpl-3.0 | 1,342 | 0.007452 | # coding: utf-8
class Solution(object):
@staticmethod
def dfs(candidates, target, vis, res, cur_idx, sum):
if sum > target:
return
if sum == target:
ans = [candidates[i] for i in cur_idx if i >= 0]
res.append(ans)
return
if sum | < target:
for i, v in enumerate(candidates):
if sum + v > target:
break
if i != cur_idx[-1] + 1 and candidates[ | i] == candidates[i-1]:
continue
if i >= cur_idx[-1] and (not vis[i]):
vis[i] = 1
cur_idx.append(i)
Solution.dfs(candidates, target, vis, res, cur_idx, sum+v)
vis[i] = 0
cur_idx.pop()
... |
tmfoltz/worldengine | tests/drawing_functions_test.py | Python | mit | 1,681 | 0.004164 | import unittest
from worldengine.drawing_functions import draw_ancientmap, gradient, draw_rivers_on_image
from worldengine.world import World
from tests.draw_test import TestBase, PixelCollector
class TestDrawingFunctions(TestBase):
def setUp(self):
super(TestDrawingFunctions, self).setUp()
self... | l((0, 128, 240),
gradient(1.0, 0.0, 1.0, (10, 20, 40), (0, 128, 240)))
| self._assert_are_colors_equal((5, 74, 140),
gradient(0.5, 0.0, 1.0, (10, 20, 40), (0, 128, 240)))
def test_draw_rivers_on_image(self):
target = PixelCollector(self.w.width * 2, self.w.height * 2)
draw_rivers_on_image(self.w, target, factor=2)
self._ass... |
jptomo/rpython-lang-scheme | rpython/jit/backend/x86/vector_ext.py | Python | mit | 29,220 | 0.001711 | import py
from rpython.jit.metainterp.compile import ResumeGuardDescr
from rpython.jit.metainterp.history import (ConstInt, INT, REF,
FLOAT, VECTOR, TargetToken)
from rpython.jit.backend.llsupport.descr import (ArrayDescr, CallDescr,
unpack_arraydescr, unpack_fielddescr, unpack_interiorfielddescr)
from rpython.... | r %s not impl." % arg)
def _genop_vec_getarrayitem(self, op, arglocs, resloc):
| # considers item scale (raw_load does not)
base_loc, ofs_loc, size_loc, ofs, integer_loc, aligned_loc = arglocs
scale = get_scale(size_loc.value)
src_addr = addr_add(base_loc, ofs_loc, ofs.value, scale)
self._vec_load(resloc, src_addr, integer_loc.value,
si... |
tdely/freischutz | tools/freischutz-client.py | Python | bsd-3-clause | 6,393 | 0.001252 | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
CLI client for interacting with Freischutz RESTful APIs
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:see: https://gitlab.com/tdely/freischutz/ Freischutz on GitLab
:author: Tobias Dély (tdely) <[email protected]>
:copyright: (c) 2018-... | "
payload += "{}\n"
payload += "{}\n"
payload = payload.format(ctype, data)
payload_hash = base64.b64encode(crypto(payload).digest())
nonce = ''.join(
random.choice(string.ascii_lowercase + string.digits) for _ in range(6)
)
if ext:
| ext = "alg={};{}".format(alg, ext)
else:
ext = "alg={}".format(alg)
msg = "hawk.1.header\n"
msg += "{}\n"
msg += "{}\n"
msg += "{}\n"
msg += "{}\n"
msg += "{}\n"
msg += "{}\n"
msg += "{}\n"
msg += "{}\n"
msg = msg.format(ts, nonce, method, uri, host, port, payload_h... |
adamgreig/sheepdog | examples/numpy_example.py | Python | mit | 531 | 0.00565 | """
Example Sheepdog script with numpy.
We'll import and make global numpy inside our Sheepdog function,
and th | en any other function can also use it.
"""
import sheepdog
def f(a, b):
import numpy as np
global np
return g(a, b)
def g(a, b):
return np.mean(np.array((a, b)))
args = [(1, 1), (1, 2), (2, 2)]
print("Running f(a,b) for arguments:")
print(args)
config = {
"host": "fear",
}
namespace = {"g": g... | ts)
|
mstrisoline/ufb | run.py | Python | gpl-2.0 | 181 | 0.01105 | #!/usr/bin/en | v python
#Run the modularized application
from ufb import app, db
if __name__ == "__main__":
app.debug = True
db.create_all(app | =app)
app.run(debug=True)
|
fifengine/fifengine | engine/python/fife/extensions/loaders.py | Python | lgpl-2.1 | 2,646 | 0.015495 | # -*- coding: utf-8 -*-
# ####################################################################
# Copyright (C) 2005-2019 by the FIFE team
# http://www.fifengine.net
# This file is part of FIFE.
#
# FIFE is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# ... | flag to activate / deactivate print statements
@rtype object
@return FIFE map object
"""
(filename, extension) = os.path.splitext(path)
map_loader = mapFileMapping[extension[1:]](engine, callback, debug, extensions)
map = map_loader.loadResource(path)
if debug: print("--- Loading map took: ", map_loader.time_to_... | tension: The file extension the loader is registered for
@type loaderClass: object
@param loaderClass: A fife.ResourceLoader implementation that loads maps
from files with the given fileExtension
"""
mapFileMapping[fileExtension] = loaderClass
_updateMapFileExtensions()
def _updateM... |
wispwisp/supportNotebook | responseTemplates/admin.py | Python | mit | 325 | 0 | from django.contrib | import admin
from responseTemplates.models import ResponseTemplate, Paragraph
class ParagraphInline(admin.StackedInline):
model = Paragraph
extra = 1
class ResponseTemplateAdmin(admin.ModelAdmin):
inlines = [ParagraphInline]
admin.site.register(R | esponseTemplate, ResponseTemplateAdmin)
|
Azure/azure-sdk-for-python | sdk/monitor/azure-monitor-query/azure/monitor/query/aio/__init__.py | Python | mit | 492 | 0.002033 | # 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.
# --------------------------------------------------------------------------
from ._logs_query_cli... | |
MahjongRepository/mahjong | mahjong/hand_calculating/yaku.py | Python | mit | 1,121 | 0.001784 | import warnings
class Yaku:
yaku_id = None
tenhou_id = None
name = None
han_open = None
han_closed = None
is_yakuman = None
def __init__(self, yaku_id=None):
self.tenhou_id = None
self.yaku_id = yaku_id
self.set_attributes()
def __str__(self):
return ... | s):
"""
Is this yaku exists in the hand?
:param: hand
:param: args: some yaku requires additional attributes
:return: boolean
"""
raise NotImplementedError
def set_attributes(self):
"""
Set id, name, han related to the yaku
"""
... | dError
@property
def english(self):
warnings.warn("Use .name attribute instead of .english attribute", DeprecationWarning)
return self.name
@property
def japanese(self):
warnings.warn("Use .name attribute instead of .japanese attribute", DeprecationWarning)
return self.... |
ipa-led/airbus_coop | airbus_plugins/airbus_plugin_log_manager/setup.py | Python | apache-2.0 | 888 | 0.003378 | #!/usr/bin/env python
#
# Copyright 2015 Airbus
# Copyright 2017 Fraunhofer Institute for Manufacturing Engineering and Automation (IPA)
#
# 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 req | uired by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from distutils.... |
hwaf/hwaf | py-hwaftools/orch/waffuncs.py | Python | bsd-3-clause | 4,382 | 0.006846 | #!/usr/bin/env python
# encoding: utf-8
## stdlib imports
import os
from glob import glob
## 3rd party
from . import pkgconf
from . import envmunge
from . import features as featmod
from . import util
## waf imports
import waflib.Logs as msg
import waflib.Context as context
# NOT from the waf book. The waf book ex... | msg.info('orch: delegating to %s' % other_wscript)
to_recurse.append(pkgn | ame)
continue
pkgcfg = bld.env.orch_package_dict[pkgname]
featlist = util.string2list(pkgcfg.get('features'))
msg.debug('orch: features for %s: "%s"' % (pkgname, '", "'.join(featlist)))
for feat in featlist:
try:
feat_f... |
vladsaveliev/bcbio-nextgen | bcbio/rnaseq/cufflinks.py | Python | mit | 10,844 | 0.000738 | """Assess transcript abundance in RNA-seq experiments using Cufflinks.
http://cufflinks.cbcb.umd.edu/manual.html
"""
import os
import shutil
import tempfile
import pandas as pd
from bcbio import bam
from bcbio.utils import get_in, file_exists, safe_makedir
from bcbio.distributed.transaction import file_transaction
fro... | ign_file))
fpkm_file = gene_tracking_to_fpkm(tracking_file, fpkm_file)
fpkm_file_isoform = gene_tracking_to_fpkm(tracking_file_isoform, fpkm_file_isoform)
return out_dir, fpkm_file, fpkm_file_isoform
def gene_tracking_to_fpkm(tracking_file, out_file):
"""
take a gene-level tracking file fr... | KM from the same genes into one FPKM value to fix
this bug: http://seqanswers.com/forums/showthread.php?t=5224&page=2
"""
if file_exists(out_file):
return out_file
df = pd.io.parsers.read_csv(tracking_file, sep="\t", header=0)
df = df[['tracking_id', 'FPKM']]
df = df.groupby(['tracking_i... |
liam2/larray | larray/inout/xw_reporting.py | Python | gpl-3.0 | 35,378 | 0.003307 | import warnings
from pathlib import Path
from typing import Union
try:
import xlwings as xw
except ImportError:
xw = None
from larray.util.misc import _positive_integer
from larray.core.group import _translate_sheet_name
from larray.core.array import asarray, zip_array_items
from larray.example import load_ex... | per_row.setter
def graphs_per_row(self, graphs_per_row):
_positive_integer(graphs_per_row)
self._graphs_per_row = graphs_per_row
class AbstractReportSheet(AbstractReportItem):
r"""
Represents a sheet dedicated to contains only graphical items (title banners, graphs).
See :py:obj:`Excel... | template_dir : str or Path, optional
Path to the directory containing the Excel template files (with a '.crtx' extension).
Defaults to None.
template : str or Path, optional
Name of the template to be used as default template.
The extension '.crtx' will be added if not given.
... |
mofei2816/mervinz | blog/apps.py | Python | mit | 1,239 | 0 | # -*- coding: utf-8 -*-
"""
The MIT License (MIT)
Copyright (c) 2016 Mervin <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation... | l
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 notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND... | D TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
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... |
stack-of-tasks/rbdlpy | tutorial/lib/python2.7/site-packages/OpenGL/raw/WGL/EXT/pbuffer.py | Python | lgpl-3.0 | 1,629 | 0.031921 | '''Autogenerated by xml_generate script, do not edit!'''
from OpenGL import platform as _p, arrays
# Code generation uses this
from OpenGL.raw.WGL import _types as _cs
# End users want this...
from OpenGL.raw.WGL._types import *
from OpenGL.raw.WGL import _errors
from OpenGL.constant import Constant as _C
import ctype... | types(_cs.HPBUFFEREXT,_cs.HDC,_cs.c_int,_cs.c_int,_cs.c_int,ctypes.POINTER(_cs.c_int))
def wglCreatePbufferEXT(hDC,iPixelFormat,iWidth,iHeight,piAttribList):pass
@_f
@_p.types(_cs.BOOL,_cs.HPBUFFEREXT)
def wglDestroyPbufferEXT(hPbuffer):pass
@_f
@_p.types(_cs.HDC,_cs.HPBUFFEREXT)
def wglGetPbufferDC | EXT(hPbuffer):pass
@_f
@_p.types(_cs.BOOL,_cs.HPBUFFEREXT,_cs.c_int,ctypes.POINTER(_cs.c_int))
def wglQueryPbufferEXT(hPbuffer,iAttribute,piValue):pass
@_f
@_p.types(_cs.c_int,_cs.HPBUFFEREXT,_cs.HDC)
def wglReleasePbufferDCEXT(hPbuffer,hDC):pass
|
eric-stanley/freeciv-android | lib/freeciv/dropbox_civsync.py | Python | gpl-2.0 | 1,258 | 0.007154 | import sync
import ui
import features
import functools
import save as _save
from freeciv.dropbox import get_download_path
def _impl_save(name, path):
def _do():
data = open(path, 'rb').read()
sync.request_with_sid('/sync/upload_save',
name=name,
... | box():
ui.message('Listing saves from Dropbox...')
ui.async(
lambda: sync.json_request_with_sid('/sync/list'),
then=load_dialog)
def load_dialog(entries):
menu = ui.LinearLayoutWidget()
menu.add(ui.Label('Save your games to folder /Applications/Freeciv in your Dropbox.'))
for entry ... | crollWrapper(menu))
def load_dropbox_save(name):
def load_save(data):
with open(get_download_path(), 'wb') as f:
f.write(data)
_save.load_game(get_download_path())
ui.message('Fetching save...')
return ui.async(lambda: sync.request_with_sid('/sync/download', name=name),
... |
mdavid8/WebSpark | spark_webservice_demo.py | Python | mit | 1,997 | 0.031047 | # Copyright 2015 David Wang. All rights reserved.
# Use of this source c | ode is governed by MIT license.
# Please see LICENSE file
# WebSpark
# Spark web service demo
# version 0.2
# use REPL or define sc SparkContext
import urllib2, urllib
import math
import time
import traceback
# Spark Web Application demo with parallel processing
# see demoservice function
ServerAddr="http://<e... | -group-item">first prime above %d is %d</li>'
with open('template.html') as f:
template = f.read()
def slow_isprime(num):
if num<2:
return False
for i in range(2, int(math.sqrt(num))+1):
if num%i==0:
return False
return True
def firstprimeabove(num):
i=num+1
while True:
if slow_isprime(i):
return... |
pinax/pinax-teams | pinax/teams/tests/urls.py | Python | mit | 178 | 0 | from django.conf.ur | ls import include, url
|
urlpatterns = [
url(r"^account/", include("account.urls")),
url(r"^", include("pinax.teams.urls", namespace="pinax_teams")),
]
|
derekperry/oaxmlapi | oaxmlapi/__init__.py | Python | mit | 123 | 0 | # Set module | s to be exported with "from oaxmlapi | import *"
__all__ = ['commands', 'connections', 'datatypes', 'utilities']
|
herove/dotfiles | sublime/Packages/Package Control/package_control/http/debuggable_http_response.py | Python | mit | 2,329 | 0.000429 | try:
# Python 3
from http.client import HTTPResponse, IncompleteRead
str_cls = str
except (ImportError):
# Python 2
from httplib import HTTPResponse, IncompleteRead
str_cls = unicode
from ..console_write import console_write
class DebuggableHTTPResponse(HTTPResponse):
"""
A custom HT... | 9: u'HTTP/0.9',
10: u'HTTP/1.0',
11: u'HTTP/1.1'
}
status_line = u'%s %s %s' % (versions[self.version], str_cls(self.status), self.reason)
headers.insert(0, status_line)
indented_headers = u'\n '.join(headers)
console... | u'''
Urllib %s Debug Read
%s
''',
(self._debug_protocol, indented_headers)
)
return return_value
def is_keep_alive(self):
# Python 2
if hasattr(self.msg, 'headers'):
connection = self.msg.gethea... |
kennethlove/django_bookmarks | dj_bookmarks/bookmarks/urls/collections.py | Python | bsd-3-clause | 278 | 0.003597 | from django.conf.urls imp | ort url
from ..views import collec | tions as views
urlpatterns = [
url('^create/$', views.Create.as_view(), name='create'),
url('^c:(?P<slug>[-\w]+)/$', views.Detail.as_view(), name='detail'),
url('^$', views.List.as_view(), name='list'),
]
|
mryanlam/f5-ansible | library/iworkflow_service.py | Python | gpl-3.0 | 14,907 | 0.001006 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright 2017 F5 Networks Inc.
#
# 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
# ... | cription:
- The tenant whose service is going to be managed. This is a required
option when using the system's C(admin) acc | ount as the admin is not
a tenant, and therefore cannot manipulate any of the L4/L7 services
that exist. If the C(user) option is not the C(admin) account, then
this tenant option is assumed to be the user who is connecting to
the BIG-IP. This assumption can always be changed by setting ... |
jwir3/gitbranchhealth | tests/testutil.py | Python | mpl-2.0 | 2,053 | 0.006332 | import unittest
import tempfile
import os
from os.path import join
import zipfile
from git import *
from shutil import rmtree
from gitbranchhealth.branchhealth import BranchHealthConfig
class GitRepoTest(unittest.TestCase):
def setUp(self):
self.__mOriginTempDir = tempfile.mkdtemp(prefix='gitBranchHealthTest')
... | tRepoPath = os.path.join(self.__mTempDir, 'testrepo')
originRepo.clone(self.__mGitRepoPath)
self.assertTrue(os.path.exists(self.__mGitRepoPath))
self.__mConfig = BranchHealthConfig(self.__mGitRepoPath)
self.__trackAllRemoteBranches()
def tearDow | n(self):
pass
# rmtree(self.__mTempDir)
# rmtree(self.__mOriginTempDir)
def getConfig(self):
return self.__mConfig
def getTempDir(self):
return self.__mTempDir
## Private API ###
def __trackAllRemoteBranches(self):
repo = Repo(self.__mGitRepoPath)
for remote in repo.remotes:
... |
dvdmgl/django-pg-fts | pg_fts/__init__.py | Python | bsd-2-clause | 63 | 0 | from __future__ import unicode_literals
__VERSION__ | = ' | 0.1.1'
|
hufman/flask_rdf | examples/browser_default.py | Python | bsd-2-clause | 751 | 0.002663 | #!/usr/bin/env python
from rdflib import Graph, BNode, Literal, URIRef
from rdflib.namespace import FOAF
from flask import Flask
import fl | ask_rdf
import random
app = Flask(__name__)
# set up a custom formatter to return turtle in text/plain to browsers
custom_formatter = flask_rdf.FormatSelector()
custom_formatter.wildcard_mimetype = 'text/plain'
custom_formatter.add_format('text/plain', 'turtle')
custom_decorator = flask_rdf.flask.Decorator(custom_fo... | path), FOAF.age, Literal(random.randint(20, 50))))
return graph
if __name__ == '__main__':
app.run(host='0.0.0.0', debug=True)
|
jucimarjr/IPC_2017-1 | lista02/lista02_exercicio01_questao06.py | Python | apache-2.0 | 781 | 0.019481 | #-----------------------------------------------------------------------------------------------------------------------
#Introdução a Programação de Computadores - IPC
#Universidade do Estado do Amazonas - UEA
#Prof. Jucimar Jr.
#Alexandre Marques Uchôa 1715310028
#Jandinne Duarte de Oliveira 1... | ------------------------- | -------------------------------------
r = float(input("Digite um raio"))
area = (3.14*r*r)
print ('Sua área é', area)
|
bitmazk/cmsplugin-django-outlets | cmsplugin_outlets/cms_app.py | Python | mit | 360 | 0 | """CMS apphook for the django- | outlets app."""
from django.utils.translation import ugettext_lazy as _
from cms.app_base import CMSApp
from cms.apphook_pool import apphook_pool
from . import men | u
class OutletsApphook(CMSApp):
name = _("Outlets Apphook")
urls = ["outlets.urls"]
menus = [menu.OutletsMenu]
apphook_pool.register(OutletsApphook)
|
KhronosGroup/COLLADA-CTS | StandardDataSets/collada/library_cameras/camera/optics/orthographic/optics_orthographic_zfar/optics_orthographic_zfar.py | Python | mit | 4,007 | 0.009234 | # Copyright (c) 2012 The Khronos Group Inc.
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and /or associated documentation files (the "Materials "), to deal in the Materials without restriction, including without limitation the rights to use, copy, modify, merge, publis... | self.status_exemplary = False
self.__assistant = JudgeAssistant.JudgeAssistant()
# Baseline
def JudgeBaseline(self, context):
# No step should crash
self.__assistant.CheckCrashes(context)
# Imp | ort/export/validate must exist and pass, while Render must only exist.
self.__assistant.CheckSteps(context, ["Import", "Export", "Validate"], ["Render"])
self.status_baseline = self.__assistant.GetResults()
return self.status_baseline
# Superior
def JudgeSuperior(self, contex... |
UKPLab/sentence-transformers | examples/training/sts/training_stsbenchmark_continue_training.py | Python | apache-2.0 | 3,514 | 0.005407 | """
This example loads the pre-trained SentenceTransformer model 'nli-distilroberta-base-v2' from the server.
It then fine-tunes this model for some epochs on the STS benchmark dataset.
Note: In this example, you must specify a SentenceTransformer model.
If you want to fine-tune a huggingface/transformers model like b... | output_path=model_save_path)
##############################################################################
#
# Load the stored model and evaluate its performance on STS benchmark dataset
#
##############################################################################
model = SentenceTransformer(model_save_path... | test')
test_evaluator(model, output_path=model_save_path) |
alfred82santa/dirty-validators | tests/dirty_validators/tests_basic.py | Python | mit | 26,469 | 0.002909 | from unittest import TestCase
from dirty_validators.basic import (BaseValidator, EqualTo, NotEqualTo, StringNotContaining, Length, NumberRange,
Regexp, Email, IPAddress, MacAddress, URL, UUID, AnyOf, NoneOf,
IsEmpty, NotEmpty, NotEmptyString, IsNon... | ess(self):
self.assertTrue(self.validator.is_valid(["1a", "32d", "tr", "wq"]))
self.assertDictEqual(self.validator.messages, {})
def test_validate_list_fail_short(self):
self.assertFalse(self.validator.is_valid(["1a"]))
self.assertDictEqual(self.validator.messages, {Length.TOO_SHORT... | ", "er"]))
self.assertDictEqual(self.validator.messages,
{Length.TOO_LONG:
"'['1a', '32d', 'tr', 'wq', 'qwqw', 'dd', 'as', 'er']' is more than 6 unit length"})
class TestNumberRange(TestCase):
def setUp(self):
self.validator = NumberRange... |
beschulz/kyototycoon | bench/benchmark.py | Python | gpl-2.0 | 3,361 | 0.046712 | # -*- coding: utf-8 -*-
#from pykt import *
from pykt import KyotoTycoon as kt1
from kyototycoon import DB as kt2
from pykt_emu import KyotoTycoon as kt3
import timeit
from cPickle import dumps, loads
key = "A" * 12
val = "B" * 1024
def bench_set(Impl):
db = Impl()
db.open()
ret = db.set(key, val)
assert ret ==... | ('replace' , bench_replace),
#('append' , bench_append),
)
if __name__ == "__main__":
print ' '*16 + '\t'.join(map(lambda x: '%15s' % (x[0]), ops)) + ' total'
for impl_name, impl in implementations:
db=impl()
db.open()
db.clear()
print '%15s' % (impl_name),
total = 0.0
for op_name, op in o... | %(res),
print '%2.13f'%(total)
'''
res = timeit.timeit("pykt_set()", "from __main__ import pykt_set", number=1000)
print "pykt_set %f" % res
#res = timeit.timeit("pykt_replace()", "from __main__ import pykt_replace", number=1000)
#print "pykt_replace %f" % res
res = timeit.timeit("kyoto_set()", "from __main__ ... |
dpaiton/OpenPV | pv-core/analysis/python/plot_hamming.py | Python | epl-1.0 | 3,742 | 0.031267 | """
Plots the Histogram
"""
import os
import sys
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
import matplotlib.cm as cm
import PVReadWeights as rw
import PVConversions as conv
from pylab import save
import math
import random
if len(sys.argv) < 3:
print "usage: hamming filename ... | 5 = []
fe6 = []
fe7 = []
fe8 = []
fe9 = []
fe10 = []
fcomp = []
f = w.normalize(f)
f2 = w.normalize(f2)
# vertical lines from right side
f = np.zeros([w.nxp, w.nyp]) # first line
f[:,0] = 1
fe1.append(f)
f = np.zeros([w.nxp, w.nyp]) # second line
f[:,1] = 1
fe2.append(f)
f2 = np.zeros([w.nxp, w.nyp]) # third line
... | fe3.append(f2)
f = np.zeros([w.nxp, w.nyp])
f[:,3] = 1
fe4.append(f)
f = np.zeros([w.nxp, w.nyp])
f[:,4] = 1
fe5.append(f)
#horizontal lines from the top
f = np.zeros([w.nxp, w.nyp])
f[0,:] = 1
fe6.append(f)
f = np.zeros([w.nxp, w.nyp])
f[1,:] = 1
fe7.append(f)
f = np.zeros([w.nxp, w.nyp])
f[2,:] = 1
fe8.append(f)... |
home-assistant/home-assistant | homeassistant/components/vesync/__init__.py | Python | apache-2.0 | 4,023 | 0.000746 | """VeSync integration."""
import logging
from pyvesync import VeSync
from homeassistant.const import CONF_PASSWORD, CONF_USERNAME, Platform
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.dispatcher import async_dispatcher_send
from .common import async_process_devices
from .cons... | s_devices(hass, manager)
switch_devs = dev_dict.get(VS_SWITCHES, [])
fan_devs = dev_dict.get(VS_FANS, [])
light_devs = dev_dict.get(VS_LIGHTS, [])
switch_set = set(switch_devs)
new_switches = list(switch_set.difference(switches))
if new_switches and switches:
... | es)
return
if new_switches and not switches:
switches.extend(new_switches)
hass.async_create_task(forward_setup(config_entry, "switch"))
fan_set = set(fan_devs)
new_fans = list(fan_set.difference(fans))
if new_fans and fans:
fans.extend(ne... |
erja-gp/openthread | tools/harness-automation/cases/sed_9_2_13.py | Python | bsd-3-clause | 1,871 | 0.001603 | #!/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
# notic... | older nor the
# names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
#... | T HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# ... |
timeu/PyGWAS | pygwas/core/plot.py | Python | mit | 4,855 | 0.006591 | import scipy as sp
import matplotlib
import matplotlib.pyplot as plt
def simple_log_qqplot(quantiles_list, png_file=None, pdf_file=None, quantile_labels=None, line_colors=None,
max_val=5, title=None, text=None, plot_label=None, ax=None, **kwargs):
storeFig = False
if ax is None:
f = plt.fig... | se:
return
if png_file != None:
f.savefig(png_file)
if pdf_file != None:
f.savefig(pdf_file, format='pdf')
def simple_qqplot(quantiles_list, png_file=None, pdf_file=None, quantile_labels=None, line_colors=None,
title=None, text=None, ax=None, plot_label=None, **kwargs):
... | lt.figure(figsize=(5.4, 5))
ax = f.add_axes([0.11, 0.09, 0.87, 0.86])
storeFig = True
ax.plot([0, 1], [0, 1], 'k--', alpha=0.5, linewidth=2.0)
num_dots = len(quantiles_list[0])
exp_quantiles = sp.arange(1, num_dots + 1, dtype='single') / (num_dots + 1)
for i, quantiles in enumerate(quant... |
sherpya/archiver | backend_xmlrpc.py | Python | gpl-2.0 | 2,693 | 0.00557 | #!/usr/bin/env python
# -*- Mode: Python; tab-width: 4 -*-
#
# Netfarm Mail Archiver - release 2
#
# Copyright (C) 2005-2007 Gianluigi Tiesi <[email protected]>
# Copyright (C) 2005-2007 NetFarm S.r.l. [http://www.netfarm.it]
#
# This program is free software; you can redistribute it and/or modify
# it under the term... | ARRANTY; without even the implied warranty of MERCHANTIBILITY
# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
# for more details.
# ======================================================================
## @file backend_xmlrpc.py
## XMLrpc Storage and Archive Backend
__doc__ = '''Netfarm Arc... | Backend' ]
from archiver import *
from sys import exc_info
from xmlrpclib import ServerProxy, Error
from urlparse import urlparse
from time import mktime
_prefix = 'XmlRpc Backend: '
##
class BadUrlSyntax(Exception):
"""BadUrlSyntax Bad url syntax in config file"""
pass
class Backend(BackendBase):
"""XM... |
ross128/pybus | bus.py | Python | agpl-3.0 | 2,629 | 0.030049 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import zmq
import threading
impo | rt logging
import logging.handlers
import util
class Logger(threading.Thread):
"""logger for all messages and events"""
def __init__(self, stop_logging, filename='bus.log'):
super(Logger, self).__init__()
self.filename = filename
self.stop_logging = stop_logging
# receiving socket
self.context = zmq.Conte... | )
self.log_in.setsockopt(zmq.RCVTIMEO, 1000)
# logger parameters for stdout and compressed file
log_format = logging.Formatter('%(asctime)s [%(levelname)s] %(message)s')
file_log_handler = util.TimedCompressingRotatingFileHandler(self.filename, when='midnight', backupCount=7)
file_log_handler.setFormatter(lo... |
isawnyu/textnorm | textnorm/__init__.py | Python | agpl-3.0 | 4,388 | 0.000228 | """Normalize whitespace and Unicode forms in Python 3.
Functions:
normalize_space() -- collapse whitespace and trim
normalize_unicode() -- return specified Unicode normal form
"""
__author__ = 'Tom Elliott'
__copyright__ = 'Copyright ©️ 2017 New York University'
__license__ = 'See LICENSE.txt'
__version__ = '0.3'
im... | {}'.format(repr(vi) | ))
logger.debug('si: {}'.format(repr(si)))
if si == len(s) and len(v) > vi:
last = ' '
s = first + s + last
return s
def normalize_unicode(v: str, target='NFC', check_compatible=False):
"""Normalize Unicode form.
Keyword arguments:
* v: the Unicod... |
RealTimeWeb/Blockpy-Server | static/programs/temperatures.py | Python | mit | 634 | 0.012618 | Plot the forecasted temperatures of Miami in Celsius. You'll need t | o use the "<a href='#'>create empty list</a>" and "<a href='#'>append</a>" blocks to create a new list of Celsius temperatures from the forecasted temperatures in Blacksburg, and then plot these new temperatures against the old ones.
#####
import weather
import matplotlib.pyplot as plt
celsius_temperatures = []
for ... | _temperatures.append(celsius)
plt.plot(celsius_temperatures)
plt.title("Temperatures in Miami")
plt.show()
#####
def on_run(code, output, properties):
return True |
chenyyx/scikit-learn-doc-zh | examples/zh/applications/plot_prediction_latency.py | Python | gpl-3.0 | 11,475 | 0 | """
==================
Prediction Latency
==================
This is an example showing the prediction latency of various scikit-learn
estimators.
The goal is to measure the latency one can expect when doing predictions
either in bulk or atomic (i.e. one by one) mode.
The plots represent the distribution of the pred... | t_title('Prediction Time per Instance - | %s, %d feats.' % (
pred_type.capitalize(),
configuration['n_features']))
ax1.set_ylabel('Prediction Time (us)')
plt.show()
def benchmark(configuration):
"""Run the whole benchmark."""
X_train, y_train, X_test, y_test = generate_dataset(
configuration['n_train'], configuration... |
12019/pyscard | smartcard/Examples/wx/apdumanager/apdumanager.py | Python | lgpl-2.1 | 1,988 | 0.004527 | #! /usr/bin/env python
"""
Simple application to send APDUs to a card.
__author__ = "http://www.gemalto.com"
Copyright 2001-2010 gemalto
Author: Jean-Daniel Aussel, mailto:[email protected]
This file is part of pyscard.
pyscard is free software; you can redistribute it and/or modify
it under the terms ... | we are frozen using py2exe. From WhereAmI page on py2exe wiki."""
if we_are_frozen():
return os.path.dirname( unicode(sys.executable, sys.getfilesystemencoding( )) )
return os.path.dirname(unicode(__file__, sys.getfilesystemencoding( )))
def main(argv):
app = SimpleSCardApp(
appname='A ... |
appicon=os.path.join( module_path(), 'images', 'mysmartcard.ico'),
size=(800, 600))
app.MainLoop()
if __name__ == "__main__":
import sys
main(sys.argv)
|
homeworkprod/byceps | byceps/signals/shop.py | Python | bsd-3-clause | 362 | 0 | """
byceps.signals.shop
~~~~~~~~~~~~~ | ~~~~~~
:Copyright: 2006-2021 Jochen Kupperschmidt
:License: Revised BSD (see `LICENSE` file for details)
"""
from blinker import Namespace
shop_signals = Namespace()
order_placed = shop_signals.signal('order-placed')
order | _canceled = shop_signals.signal('order-canceled')
order_paid = shop_signals.signal('order-paid')
|
tldavies/RackHD | test/tests/rackhd20/test_rackhd20_api_files.py | Python | apache-2.0 | 3,026 | 0.00727 | '''
Copyright 2016, EMC, Inc.
Author(s):
George Paulos
'''
import os
import sys
import subprocess
# set path to common libraries
sys.path.append(subprocess.check_output("git rev-parse --show-toplevel", shell=True).rstrip("\n") + "/test/common")
import fit_common
# Select test group here using @attr
from nose.plugin... | api/2.0/files/' + fileid)
self.assertEqual(api_data['status'], 200, 'Incorrect HTTP return code, expected 200, got:' + str(api_da | ta['status']))
self.assertEqual(open(fit_common.TEST_PATH + 'testfile').read(), api_data['text'], 'File corrupted, ID: ')
# list all
api_data = fit_common.rackhdapi('/api/2.0/files')
self.assertIn(fileid, fit_common.json.dumps(api_data['json']), 'File ID missing in file list.')
#... |
pfederl/CARTAvis | carta/scriptedClient/layer2.py | Python | gpl-2.0 | 2,551 | 0.001176 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import struct
from layer1 import VarLenMessage, VarLenSocket
class TagMessage:
"""
TagMessage contains a string tag and string data.
Paramters
---------
tag: string
The type of the message. Currently supported tags are "json" and
"asyn... | f the input VarLenMessage.
"""
# | find the position of the '\0'
end = vlm.data.find('\0')
if end < 0:
raise NameError('received tag message has no null char')
# extract the tag (null terminated string)
fmt = "{0}s".format(end)
tag = struct.unpack_from(fmt, vlm.data)[0]
# the data is the rest ... |
tomwhartung/edison_python | my_examples/02.Digital/08-buttonTurnsOnLed.py | Python | gpl-3.0 | 672 | 0.040179 | #!/usr/bin/python
#
# 08-buttonTurnsOnLed.py: when the button is pressed, turn on the led
# -------------------------------------------------------------------
#
import mraa
import time
LOW = 0
HIGH = 1
digitalInPin = 8
digitalInGpio = mraa.Gpio( digitalInPin )
ledOutPin = 3
ledOutGpio = mraa.Gpio( ledOutPin )
ledOu... | UT)
##
# loop: what to do "forever"
#
def loop() :
digitalInInteger = digitalInGpio.read()
print( 'digitalInInteger: ' + str(digitalInInteger) )
if( digitalInInteger == 1 ) :
ledOutGpio.write( HIGH )
else :
ledOutGpio.write( LOW )
#
# mainline loop:
#
sleepSecs = 0.5
while True:
loop()
time.s | leep( sleepSecs )
exit(0)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.