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 |
|---|---|---|---|---|---|---|---|---|
SF-Zhou/TinyDNN | tiny_dnn/net/__init__.py | Python | gpl-3.0 | 22 | 0 | from . | net import | Net
|
MungoRae/home-assistant | tests/components/config/test_init.py | Python | apache-2.0 | 1,851 | 0 | """Test config init."""
import asyncio
from unittest.mock import patch
import pytest
from homeassistant.const import EVENT_COMPO | NENT_LOADED
from homeassistant.setup import async_setup_component, ATTR_COMPONENT
from homeassistant.components import config
from tests.common import mock_http_component, mock_coro, mock_component
@pytest.fixture(autouse=True)
def stub_http(hass):
"""Stub the HTTP component."""
mock_http_component(hass)
@... | n hass.config.components
@asyncio.coroutine
def test_load_on_demand_already_loaded(hass, test_client):
"""Test getting suites."""
mock_component(hass, 'zwave')
with patch.object(config, 'SECTIONS', []), \
patch.object(config, 'ON_DEMAND', ['zwave']), \
patch('homeassistant.compone... |
shucommon/little-routine | python/AI/tensorflow/MNIST_data/download.py | Python | gpl-3.0 | 745 | 0.001342 | import urllib.request
def download(path):
print('Beginning file download with urllib2...')
| url = []
url.append('http://yann.lecun.com/exdb/mnist/train-images-idx3-ubyte.gz')
url.append('http://yann.lecun.com/exdb/mnist/train-labels-idx1-ubyte.gz')
url.append('http://yann.lecun.com/exdb/mnist/t10k-images-idx3-ubyte.gz')
url.append('http://yann.lecun.com/exdb/mnist/t10k-labels-idx1-ubyte.gz')
... | -idx1-ubyte.gz')
name.append('t10k-images-idx3-ubyte.gz')
name.append('t10k-labels-idx1-ubyte.gz')
for i in range(4):
print("downloading " + name[i])
urllib.request.urlretrieve(url[i], path + '/' + name[i])
|
gaiusm/pge | examples/springs/catapult.py | Python | gpl-3.0 | 2,508 | 0.027113 | #!/usr/bin/env python3
import pge, sys
from pygame.locals import *
print("starting catapult")
# pge.batch ()
pge.interactive ()
t = pge.rgb (1.0/2.0, 2.0/3.0, 3.0/4.0)
wood_light = pge.rgb (166.0/256.0, 124.0/256.0, 54.0/256.0)
wood_dark = pge.rgb (76.0/256.0, 47.0/256.0, 0.0)
red = pge.rgb (1.0, 0.0, 0.0)
green = ... | 0.0
damping = 10.0
snap_length = 0.1
projectile = placeBall (wood_dark, mouse[0], mouse[1], 0.03).mass (0.9)
bungee = pge.spring (connection, projectile, spring_power, damping, snap_length).draw (yellow, 0.002)
bungee.when (snap_length, snap_it)
def main ():
global gb, side... | (0.01, wood_dark)
connection = placeBall (wood_light, 0.75, 0.45, 0.01).fix ()
print("before run")
pge.record ()
pge.draw_collision (True, False)
pge.collision_colour (red)
pge.gravity ()
pge.dump_world ()
pge.slow_down (6.0) # slows down real time by a factor of
pge.register_hand... |
pkess/beets | test/_common.py | Python | mit | 10,605 | 0.000094 | # -*- coding: utf-8 -*-
# This file is part of beets.
# Copyright 2016, Adrian Sampson.
#
# 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 t... | class LibTestCase(TestCase):
"""A test case that includes an in-memory library object (`lib`) and
an item added to the library (`i`).
"""
def setUp(self):
super(LibTestCase, self).setUp()
self.lib = beets.library.Library(':memory:')
self.i = item(self.lib)
def tearDown(self)... | ject):
"""Mocks the timing system (namely time() and sleep()) for testing.
Inspired by the Ruby timecop library.
"""
def __init__(self):
self.now = time.time()
def time(self):
return self.now
def sleep(self, amount):
self.now += amount
def install(self):
se... |
HEPData/hepdata-converter | hepdata_converter/parsers/yaml_parser.py | Python | gpl-2.0 | 4,770 | 0.003354 | import yaml
# We try to load using the CSafeLoader for speed improvements.
try:
from yaml import CSafeLoader as Loader
except ImportError: #pragma: no cover
from yaml import SafeLoader as Loader #pragma: no cover
from hepdata_validator import LATEST_SCHEMA_VERSION
from hepdata_validator.submission_file_validat... | (data_in, 'r') as submission_file:
submission_data = list(yaml.load_all(submission_file, Loader=Loader))
if len(submission_data) == 0:
raise RuntimeError("Submission file (%s) is empty" % data_in)
submission_file_validator = SubmissionFileValidator(schema_version=se... | path=data_in,
data=submission_data):
raise RuntimeError(
"Submission file (%s) did not pass validation: %s" %
(data_in, self._pretty_print_errors(
submission_file_validator.get_messages(... |
audetto/playlist_generator | generate.py | Python | gpl-3.0 | 2,088 | 0.001916 | import os
import sys
import traceback
VALID = ['.mp3', '.ogg', '.m4a']
ENCODING = 'utf-8'
M3U = '.m3u'
SKIP_FOLDERS = ['SCS.4DJ_', 'RECYCLE.BIN', 'System Volume Information']
def skipFolder(name):
for s in SKIP_FOLDERS:
if s in name:
return True # SKIP
return False # ACCEPT
def norma... |
base = sys.argv[1]
for path, dirs, files in os.walk(base):
for dir in dirs:
| absolute = os.path.abspath(os.path.join(path, dir))
if skipFolder(dir):
print('Skipping {}'.format(absolute))
else:
print('Processing {}'.format(absolute))
# this will recurse inside
processFolder(absolute)
print(... |
ui/django-rq | django_rq/__init__.py | Python | mit | 151 | 0.019868 | VERSION = (2, 4, 1)
| from .decorators import job
from .queues import enqueue, get_connection, get_queue, get_scheduler
from .workers import get_worker | |
fqez/JdeRobot | src/drivers/MAVLinkServer/MAVProxy/modules/mavproxy_param.py | Python | gpl-3.0 | 10,340 | 0.002611 | #!/usr/bin/env python
'''param command handling'''
import time, os, fnmatch
from pymavlink import mavutil, mavparm
from MAVProxy.modules.lib import mp_util
from MAVProxy.modules.lib import mp_module
class ParamState:
'''this class is separated to make it possible to use the parameter
functions on a second... | lse:
param_wildcard = "*"
self.mav_param.sav | e(args[1], param_wildcard, verbose=True)
elif args[0] == "diff":
wildcard = '*'
if len(args) < 2 or args[1].find('*') != -1:
if self.vehicle_name is None:
print("Unknown vehicle type")
return
filename = mp_util.dot_m... |
gmist/ctm-5studio | main/auth/twitter.py | Python | mit | 1,468 | 0.006812 | # coding: utf-8
from __future__ import absolute_import
import flask
import auth
import config
import model
import util
from main import app
twitter_config = dict(
access_token_url='https://api.twitter.com/oauth/access_token',
authorize_url='h | ttps://api.twitter.com/oauth/authorize',
base_url='https://api.twitter.com/1.1/',
consumer_key=config.CONFIG_DB.twitter_consumer_key,
consumer_secret=config.CONFIG_DB.twitter_consumer_secret,
request_token_url='https://api.twitter.com/oauth/request_token',
)
twitter = auth.crea | te_oauth_app(twitter_config, 'twitter')
@app.route('/api/auth/callback/twitter/')
def twitter_authorized():
response = twitter.authorized_response()
if response is None:
flask.flash('You denied the request to sign in.')
return flask.redirect(util.get_next_url())
flask.session['oauth_token'] = (
res... |
django-school-management/ssms | ssms/common/facilities/hostel/apps.py | Python | lgpl-3.0 | 128 | 0 | from __future__ imp | ort unicode_literals
from django.app | s import AppConfig
class HostelConfig(AppConfig):
name = 'hostel'
|
RedhawkSDR/integration-gnuhawk | components/multiply_ff_2i/tests/test_multiply_ff_2i.py | Python | gpl-3.0 | 4,535 | 0.006615 | #!/usr/bin/env python
#
# This file is protected by Copyright. Please refer to the COPYRIGHT file
# distributed with this source distribution.
#
# This file is part of GNUHAWK.
#
# GNUHAWK is free software: you can redistribute it and/or modify is under the
# terms of the GNU General Public License as published by ... | L:CF/Resource:1.0"), True)
self.assertEqual(self.spd.get_id(), self.comp.ref._get_identifier())
|
#######################################################################
# Simulate regular component startup
# Verify that initialize nor configure throw errors
self.comp.initialize()
configureProps = self.getPropertySet(kinds=("configure",), modes=("readwrite", "writeonl... |
edisonlz/fruit | web_project/base/site-packages/bitfield/models.py | Python | apache-2.0 | 9,420 | 0.001062 | from django.db.models import signals
from django.db.models.sql.expressions import SQLEvaluator
from django.db.models.fields import Field, BigIntegerField
from django.db.models.fields.subclassing import Creator
try:
from django.db.models.fields.subclassing import SubfieldBase
except ImportError:
# django 1.2
... | new_value |= Bit(flags.index(flag))
default = new_value
BigIntegerField.__init__(self, default= | default, *args, **kwargs)
self.flags = flags
self.labels = labels
def south_field_triple(self):
"Returns a suitable description of this field for South."
from south.modelsinspector import introspector
field_class = "django.db.models.fields.BigIntegerField"
args, kwar... |
jimga150/HealthNet | HealthNet/prescriptions/apps.py | Python | mit | 101 | 0 | from django.apps import AppConfig |
class PerscriptionsConfig(AppConfig):
n | ame = 'prescriptions'
|
evancich/apm_motor | modules/waf/waflib/extras/pep8.py | Python | gpl-3.0 | 3,477 | 0.032787 | #! /usr/bin/env python
# encoding: utf-8
#
# written by Sylvain Rouquette, 2011
'''
Install pep8 module:
$ easy_install pep8
or
$ pip install pep8
To add the boost tool to the waf file:
$ ./waf-light --tools=compat15,pep8
or, if you have waf >= 1.6.2
$ ./waf update --files=pep8
Then add this to your wscript:
[at... | ences of the same error")
opt.add_option('--exclude', metavar='patterns',
default=pep8.DEFAULT_EXCLUDE,
help="exclude files or directories which match these "
"comma separated patterns (default: %s)" %
pep8.DEFAULT_EXCLUDE,
dest='exclu | de')
opt.add_option('--filename', metavar='patterns', default='*.py',
help="when parsing directories, only check filenames "
"matching these comma separated patterns (default: "
"*.py)")
opt.add_option('--select', metavar='errors', default='',
help="select errors and warnings (e.g. E,W6)")... |
coldnight/homu | homu/server.py | Python | mit | 27,593 | 0 | import hmac
import json
import urllib.parse
import subprocess
from .main import (
PullReqState,
parse_commands,
db_query,
INTERRUPTED_BY_HOMU_RE,
synchronize,
)
from . import utils
from . import gitlab
from .utils import lazy_debug
import jinja2
import requests
import pkg_resources
from bottle impor... | tes[label].values()
except KeyError:
abort(404, 'No such repository: {}'.format(label))
pull_states = sorted(states)
rows = []
for state in pull_states:
treeclosed = (single_repo_closed or
state.priority < g.repos[state.repo_label].treeclosed)
statu... | .try_:
status_ext += ' (try)'
if treeclosed:
status_ext += ' [TREE CLOSED]'
rows.append({
'status': state.get_status(),
'status_ext': status_ext,
'priority': 'rollup' if state.rollup else state.priority,
'url': '{}/{}/{}/merge_req... |
mozilla/amo-validator | validator/unicodehelper.py | Python | bsd-3-clause | 1,360 | 0 | import codecs
import re
# Many thanks to nmaier for inspiration and code in this module
UNICODE_BOMS = [
(codecs.BOM_UTF8, 'utf-8'),
(codecs.BOM_UTF32_LE, 'utf-32-le'),
(codecs.BOM_UTF32_BE, 'utf-32-be'),
(codecs.BOM_UTF16_LE, 'utf-16-le'),
(codecs.BOM_UTF16_BE, 'utf-16-be'),
]
COMMON_ENCODINGS =... | some charset detection and including unicode BOM
stripping.
"""
if isinstance(data, unicode):
return data
# Detect standard unicode BOMs.
for bom, encoding in UNICODE_BOMS:
if data.startswith(bom):
return data[len(bom):].decode(encoding, errors='ignore')
# Try stra... | ry:
return data.decode('utf-8')
except UnicodeDecodeError:
pass
# Test for various common encodings.
for encoding in COMMON_ENCODINGS:
try:
return data.decode(encoding)
except UnicodeDecodeError:
pass
# Anything else gets filtered.
return NON... |
keras-team/keras | keras/engine/training_distributed_v1.py | Python | apache-2.0 | 29,172 | 0.006822 | # Copyright 2018 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... | llbacks = cbks.configure_callbacks(
callbacks,
model,
do_validation=do_validation,
epochs=epochs,
steps_per_epoch=steps_per_epoch,
verbose=verbose,
count_mode='steps',
mode=mode)
# Calculate the steps each time on the device.
steps_to_run = | ([current_strategy.extended.steps_per_run] *
(steps_per_epoch //
current_strategy.extended. |
rayene/buildall | buildall/core.py | Python | mit | 4,402 | 0.000227 | import datetime
from pathlib import PosixPath as PythonPathClass
from subprocess import Popen as PythonPopenClass
# TODO: find a better value
END_OF_TIME = datetime.datetime(2100, 1, 1)
BEGINNING_OF_TIME = datetime.datetime(1970, 1, 1)
class BaseTask:
_indent_level = 0
silent = False
_child_tasks = []
... | plementedError | ('You should implement your own build()')
def target(self):
return None
def debug(self, msg):
indent = self._indent_level * '\t'
if not self.silent:
print(indent + '<%s> ' % self + msg)
def set_indent_level(self, level):
self._indent_level = level
def is_u... |
michaelaye/vispy | examples/basics/visuals/arrows_quiver.py | Python | bsd-3-clause | 2,742 | 0.000365 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2015, Vispy Development Team.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.
"""
This example shows how to use the `ArrowVisual` for a quiver plot
"""
from __future__ import division
import sys
import itertools
import numpy as ... | oords)
def on_resize(self, event):
self.generate_grid()
self.rotate_arrows(np.array(self.last_mouse))
vp = (0, 0, self.physical_size[0], self.physical_size[1])
self.context.set_viewport(*vp)
self.visual.transforms.configure(canvas=self, viewport=vp)
def rotate_arrows(s... | irection_vectors = (self.grid_coords - point_towards).astype(
np.float32)
norms = np.sqrt(np.sum(direction_vectors**2, axis=-1))
direction_vectors[:, 0] /= norms
direction_vectors[:, 1] /= norms
vertices = np.repeat(self.grid_coords, 2, axis=0)
vertices[::2] = vertic... |
toenuff/treadmill | lib/python/treadmill/kafka/__init__.py | Python | apache-2.0 | 6,933 | 0 | """Treadmill Kafka API"""
import fnmatch
import logging
import os
import re
import socket
from .. import admin as tadmin
from .. import context
from .. import dnsutils
from .. import discovery
from .. import fs
from .. import zkutils
_LOGGER = logging.getLogger(__name__)
KAFKA_ZK_ROOT = 'kafka'
DEFAULT_KAFKA_DIR =... | DEFAULT_BROKER_ENDPOINT_NAME
:type endpoint: string
:param watcher_cb: ZK watcher callback; if the endpoints change, call this.
Only valid if you set both app_pattern and endpoint
:type watcher_cb: func
"""
brokers = get_master_brokers(cellname, domain)
if brokers:
for hostport... | s setup but no Kafka broker
# servers running on the hosts.
if _is_broker_up(hostport):
return brokers
brokers = []
admin_cell = tadmin.Cell(context.GLOBAL.ldap.conn)
cell = admin_cell.get(cellname)
for master in cell.get('masters', []):
port = master.get... |
qilicun/python | python2/PyMOTW-1.132/PyMOTW/mailbox/mailbox_maildir_folders.py | Python | gpl-3.0 | 855 | 0.004678 | #!/usr/bin/env python
# encoding: utf-8
#
# Copyright (c) 2008 Doug Hellmann All rights reserved.
#
"""
"""
__version__ = "$Id$"
#end_pymotw_header
import mailbox
import os
def show_maildir(name):
os.system('find %s -print' % name)
mbox = mailbox.Maildir('Example')
print 'Before:', mbox.list_folders()
show_mail... | ample')
subfolder = mbox.get_folder('subfolder')
print 'subfolder contents:', subfo | lder.list_folders()
print
print '#' * 30
print
subfolder.add_folder('second_level')
print 'second_level created:', subfolder.list_folders()
show_maildir('Example')
print
print '#' * 30
print
subfolder.remove_folder('second_level')
print 'second_level removed:', subfolder.list_folders()
show_maildir('Example') |
leouieda/tesseroids-original | cookbook/simple_tess/plot.py | Python | bsd-3-clause | 1,058 | 0.008507 | """
| Plot the columns of the output files
"""
import sys
import pylab
from mpl_toolkits.basemap import Basemap
# Set up a projection
bm = Basemap | (projection='ortho', lon_0=0, lat_0=0,
resolution='l', area_thresh=10000)
data = pylab.loadtxt(sys.argv[1], unpack=True)
shape = (int(sys.argv[2]), int(sys.argv[3]))
lon = pylab.reshape(data[0], shape)
lat = pylab.reshape(data[1], shape)
glon, glat = bm(lon, lat)
for i, value in enumerate(data[3:]):
... |
hugombarreto/credibility_allocation | visualizations/utility.py | Python | mit | 645 | 0.021773 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import numpy as np
import matplotlib
matplotlib.use('Agg')
import seaborn as sns
import matplotlib.pyplot as plt
from matplotlib import rc
x = np.arange(-10, 10, 0.1)
y = np.minimum(x,2)
z = np.minimum(0,x+2)
fig, axes = plt.subplots(1, 2, sharey=True)
fig.set_size_in... | s:
| ax.set_xlim([-4,5])
ax.set_ylim([-4,3])
ax.set_xlabel(u"Alocação ($o_i$)")
ax.set_ylabel('Utilidade ($u_i$)')
axes[0].set_title("$\\theta_i=2$")
axes[1].set_title('$\\theta_i=-2$')
plt.savefig('../plots/utility.pdf', bbox_inches='tight')
# plt.show()
|
spring-week-topos/cinder-week | cinder/image/glance.py | Python | apache-2.0 | 18,489 | 0.000216 | # Copyright 2010 OpenStack Foundation
# Copyright 2013 NTT corp.
# 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/LIC... | te_glance_client(context, netloc, use_ssl,
version=CONF.glance_api_version):
"""Instantiate a new glanceclient.Client object."""
if | version is None:
version = CONF.glance_api_version
params = {}
if use_ssl:
scheme = 'https'
# https specific params
params['insecure'] = CONF.glance_api_insecure
params['ssl_compression'] = CONF.glance_api_ssl_compression
else:
scheme = 'http'
if CONF.aut... |
xR86/ml-stuff | labs-python/gists/stub-graceful-shutdown.py | Python | mit | 581 | 0.003442 | import time
while True:
try:
time.sleep(1) # do something here
print '.',
except KeyboardInterrupt:
print '\nPausing... (Hit ENTER to continue | , type quit to exit.)'
try:
response = raw_input()
if response == ' | quit':
break
print 'Resuming...'
except KeyboardInterrupt:
print 'Resuming...'
continue
'''
import errno
try:
# do something
result = conn.recv(bufsize)
except socket.error as (code, msg):
if code != errno.EINTR:
raise
''' |
xinpuyuandu/awesome-python3-webapp | www/models.py | Python | gpl-3.0 | 1,617 | 0.005566 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import time, uuid
from orm import Model, StringField, BooleanField, FloatField, TextField
def next_id():
return '%015d%s000' % (int(time.time() * 1000), uuid.uuid4().hex)
class User(Model):
__table__ = 'users'
id = StringField(primary_key=T | rue, default=next_id, ddl='varchar(50)')
email = StringField(ddl='varchar(50)')
passwd = StringField(ddl='varchar(50)')
admin = BooleanField()
name = StringField(ddl='varchar(50)')
image = StringField(ddl='varchar(500)')
created_at = FloatField(default=time.time)
def __init__(self, **kw... | d(ddl='varchar(50)')
user_name = StringField(ddl='varchar(50)')
user_image = StringField(ddl='varchar(500)')
name = StringField(ddl='varchar(50)')
summary = StringField(ddl='varchar(200)')
content = TextField()
created_at = FloatField(default=time.time)
def __init__(self, **kw):
sup... |
mkli90/tekmate | setup.py | Python | gpl-2.0 | 765 | 0 | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
from setuptools import setup
setup(name="tekmate",
version="0.0.1",
description="Tekmate - Stargate-Based Point'n'Click",
author="Max",
p | ackages=['tekmate'],
license="GPLv3",
url="https://github.com/mkli90/tekmate",
package_data={
| 'tmz': ['LICENSE']
},
classifiers=[
"Development Status :: 1 - Planning",
"License :: OSI Approved :: GNU General Public License v3 (GPLv3)",
"Natural Language :: English",
"Programming Language :: Python :: 3.4",
"Programming Language :: Python ::... |
lmazuel/azure-sdk-for-python | azure-mgmt-network/azure/mgmt/network/v2018_01_01/models/route_filter.py | Python | mit | 2,621 | 0.000763 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | erRule]
:param peerings: A collection of references to express route circuit
peerings.
:type peerings:
list[~azure.mgmt.network.v2018_01_01.models.ExpressRouteCircuitPeering]
:ivar provisioning_state: The provisioning state of the resource. Possible
values are: 'Updating', 'Deleting', 'Succee... | that changes whenever the
resource is updated.
:vartype etag: str
"""
_validation = {
'name': {'readonly': True},
'type': {'readonly': True},
'provisioning_state': {'readonly': True},
'etag': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', ... |
ihartung/460-Lab1 | networks/network.py | Python | gpl-2.0 | 3,070 | 0.001303 | import re
import sys
sys.path.append('..')
from src.link import Link
from src.node import Node
class Network(object):
def __init__(self, config):
self.config = config
self.nodes = {}
self.address = 1
self.build()
def build(self):
state = 'network'
with open(s... | link.bandwi | dth = numeric_rate * 1000000
elif rate.endswith("Kbps"):
link.bandwidth = numeric_rate * 1000
elif rate.endswith("bps"):
link.bandwidth = numeric_rate
def set_delay(self, link, delay):
numeric_delay = self.convert(delay)
if delay.endswith("ms"):
l... |
jawilson/home-assistant | tests/components/myq/test_cover.py | Python | apache-2.0 | 1,603 | 0.001871 | """The scene tests for the myq platform."""
from homeassistant.const import STATE_CLOSED
from .util import async_init_integration
async def test | _create_covers(hass):
"""Test creation of covers."""
await async_init_integration(hass)
state = hass.states.get("cover.large_garage_door")
assert state.state == STATE_CLOSED
expected_attributes = {
"device_class": "garage",
"friendly_name": "Large Garage Door",
"supported_f... | utes[key] for key in expected_attributes
)
state = hass.states.get("cover.small_garage_door")
assert state.state == STATE_CLOSED
expected_attributes = {
"device_class": "garage",
"friendly_name": "Small Garage Door",
"supported_features": 3,
}
# Only test for a subset of... |
pausan/python-maven | mavenrepo.py | Python | mit | 9,533 | 0.021609 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import re
import requests
import shutil
import xmltodict
from maven import Maven
from mavencoord import MavenCoord
from mavenversiondb import MavenVersionDb
import mavenversioncmp as mavenvercmp
import mavenparser
class MavenRepo:
""" Manages the dependencies... | ersioning = metadata.get ('versio | ning', {})
lastReleaseVersion = versioning.get ('release', None)
if not lastReleaseVersion:
return None
coord.version = lastReleaseVersion
return coord
def fetchOne (self, coord):
""" Fetch maven file from coordinate
"""
coord = self.resolveCoord (coord)
if not coord:
... |
mchristopher/PokemonGo-DesktopMap | app/pylibs/win32/Cryptodome/SelfTest/Util/test_asn1.py | Python | mit | 29,700 | 0.007407 | #
# SelfTest/Util/test_asn.py: Self-test for the Cryptodome.Util.asn1 module
#
# ===================================================================
#
# Copyright (c) 2014, Legrandin <[email protected]>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modificat... | der.payload = b('\x45')
self.assertEquals(der.encode(), b('\x02\x01\x45'))
# Invariant
self.assertEquals(der.encode(), b('\x02\x01\x45'))
# Initialize with numerical tag
der = DerObject(0x04)
der.payload = b('\x45')
| self.assertEquals(der.encode(), b('\x04\x01\x45'))
# Initialize with constructed type
der = DerObject(b('\x10'), constructed=True)
self.assertEquals(der.encode(), b('\x30\x00'))
def testObjEncode2(self):
# Initialize with payload
der = DerObject(0x03, b('\x12\x12'))
... |
Sylvaner/Mosquito | test/scripts/create_config_file.py | Python | gpl-2.0 | 1,564 | 0.033887 | #!/usr/bin/python3
##
# Mosquito Media Player.
# one line to give the program's name and an idea of what it does.
# Copyright (C) 2015 - Sylvain Dangin
#
# 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 Sof... | )
config = json.load(configFile)
configFile.close()
except FileNotFoundError:
print("Config file not found.")
sys.exit(1)
# Open test config file for database
try:
configFile = open(os.getcwd()+"/test/config/config_test.json")
configTest = json | .load(configFile)
config["database"] = configTest["database"]
configFile.close()
except FileNotFoundError:
print("Config file not found.")
sys.exit(1)
tmpConfigFilePath = os.getcwd()+"/test/tmp/config.json"
tmpConfigFile = open(tmpConfigFilePath, 'w+')
json.dump(config, tmpConfigFile)
tmpConfigFile.close()
|
sid88in/incubator-airflow | airflow/migrations/versions/1507a7289a2f_create_is_encrypted.py | Python | apache-2.0 | 2,203 | 0 | # -*- 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
#... | pends_on = None
connectionhelper = sa.Table(
'connection',
sa.MetaData(),
sa.Column('id', sa.Integer, prim | ary_key=True),
sa.Column('is_encrypted')
)
def upgrade():
# first check if the user already has this done. This should only be
# true for users who are upgrading from a previous version of Airflow
# that predates Alembic integration
conn = op.get_bind()
inspector = Inspector.from_engine(conn)
... |
botswana-harvard/ambition-subject | ambition_subject/admin/education_admin.py | Python | gpl-3.0 | 1,171 | 0 | from django.contrib import admin
from edc_model_admin import audit_fieldset_tuple
from ..admin_site import ambition_subject_admin
from ..forms import EducationForm
from ..models import Education
from .modeladmin_mixins import CrfModelAdminMixin
@admin.register(Education, si | te=ambition_subject_admin)
class EducationAdmin(CrfModelAdminMixin, admin.ModelAdmin):
form = EducationForm
additional_instructions = (
'The following questions refer to the educational background of '
'the patient.')
fieldsets = (
(None, {
'fields': [
... |
'education_certificate',
'elementary',
'attendance_years',
'secondary',
'secondary_years',
'higher_education',
'higher_years',
'household_head']}
), audit_fieldset_tuple)
radio_... |
marionleborgne/nupic.research | tests/layers/physical_objects_test.py | Python | agpl-3.0 | 4,977 | 0.005626 | # | ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2016, Numenta, Inc. Unless you have an agreement
# with Numenta, Inc., for a separate license for this software code, the
# following terms and conditions apply:
#
# This program... | terms of the GNU Affero Public License version 3 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU Affero Public Licens... |
allisnone/pytrade | low_high33_backtest.py | Python | gpl-2.0 | 42,194 | 0.019829 | # -*- coding:utf-8 -*-
import tradeStrategy as tds
import sendEmail as se
import tradeTime as tt
import tushare as ts
import pdSql_common as pds
from pdSql import StockSQL
import numpy as np
import sys,datetime
from pydoc import describe
from multiprocessing import Pool
import os, time
import file_config ... | raw_h | ist_df(code_str=symbol)
if dest_df.empty:
pass
else:
dest_df_last_date = dest_df.tail(1).iloc[0]['date']
if dest_df_last_date==last_date_str:
exit_price = dest_df.tail(3)
return
#get_exit_data(symbols=['000029'],last_date_str='2016/08/23')
... |
Foxugly/medagenda | patient/views.py | Python | gpl-3.0 | 1,514 | 0.000661 | # -*- coding: utf-8 -*-
#
# Copyright 2015, Foxugly. All rights reserved.
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or (at
# your option) any late... | rom patient.models import Patient
from django.http import HttpResponse
import json
from agenda.models import Slot
from django.shortcuts import render
from django.shortcuts import get_object_or_404
def search_patient(request):
if request.is_ajax():
email = request.GET['email']
if len(email) > 5:
... | umps({'return': True, 'patient': p[0].as_json()}))
else:
return HttpResponse(json.dumps({'return': False}))
else:
return HttpResponse(json.dumps({'return': False}))
def confirm_create(request, patient_id, text):
p = get_object_or_404(Patient, id=patient_id, confirm=... |
glic3rinu/basefs | basefs/tests/test_mount.py | Python | mit | 2,043 | 0.001468 | import shutil
import tempfile
import time
import os
import random
import subprocess
import unittest
from basefs.keys import Key
from basefs.logs import Log
from . import utils
class MountTests(unittest.TestCase):
def setUp(self):
__, self.logpath = tempfile.mkstemp()
__, self.logpath_b = tempfil... | leanup(time.sleep, 1)
self.addCleanup(proc.kill)
self.addCleanup(shutil.rmtree, self.mountpath)
self.addCleanup(shutil.rmtree, self.mountpath_b)
| time.sleep(1)
def test_mount(self):
pass
|
NeptuneFramework/neptune | neptune/response.py | Python | apache-2.0 | 2,350 | 0.000426 | import os
import json
from jinja2 import Template
class NResponse(object):
"""
Main Handler for all HTTP Responses
"""
def __init__(self, http_version='', status='', headers={}, body=''):
self.http_version = http_version
self.headers = headers
self.status = status
sel... | self.headers,
self.body) |
return self.response.encode()
def _generate_response(self, http_version, status, headers, body):
base = "{0} {1}\r\n".format(http_version, status)
for header in headers:
base += "{0}: {1}\r\n".format(header, headers[header])
# Also add custom headers (Server: Neptune)
... |
argv0/cloudstack | tools/test/apisession.py | Python | apache-2.0 | 2,419 | 0.004134 | # 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... | WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import cookielib
import hashlib
import json
import os
import random
import sys
import urllib2
import urllib
class ApiSession:
"""an Ap... | __init__(self, url, username, password):
self._username = username
self._password = hashlib.md5(password).hexdigest()
self._url = url
self._cj = cookielib.CookieJar()
self._opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(self._cj))
def _get(self, parameters):
... |
trooble/census_plot | demo1/demo1/__init__.py | Python | gpl-3.0 | 726 | 0.004132 | # Copyright 2012 Karim Sumun
#
# This file is part of Simple Census Plotter.
#
# S | imple Census Plotter is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be usefu... | OSE. 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/>.
|
lndbrg/flowirc | flowirc/tests/test_IRCClientProtocol.py | Python | mit | 2,853 | 0.000701 | from unittest import TestCase
from unittest.mock import Mock, patch, call, MagicMock
from flowirc.protocol import IRCClientProtocol
__author__ = 'Olle Lundberg'
class TestIRCClientProtocol(TestCase):
def setUp(self):
self.proto = IRCClientProtocol()
self.transport = Mock()
self.proto.mes... | et\r\n')
self.assertEqual(1, ircmessage.from_str.call_count)
self.proto.message_received.assert_called_once_with(ping)
@patch('asyncio.Task')
@patch('flowirc.protocol.IRCMessage')
def test_data_received_3(self, ircmessage, task):
self.proto.message_received = Mock()
mock = ... | lf.assertEqual(1, ircmessage.from_str.call_count)
self.assertEqual(0, self.proto.message_received.call_count)
|
kennedyshead/home-assistant | homeassistant/components/tasmota/fan.py | Python | apache-2.0 | 3,093 | 0.000647 | """Support for Tasmota fans."""
from hatasmota import const as tasmota_const
from homeassistant.components import fan
from homeassistant.components.fan import FanEntity
from homeassistant.core import callback
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from homeassistant.util.percentage impo... | not included
async def async_se | tup_entry(hass, config_entry, async_add_entities):
"""Set up Tasmota fan dynamically through discovery."""
@callback
def async_discover(tasmota_entity, discovery_hash):
"""Discover and add a Tasmota fan."""
async_add_entities(
[TasmotaFan(tasmota_entity=tasmota_entity, discovery... |
nexiles/odoo | addons/project_timesheet/project_timesheet.py | Python | agpl-3.0 | 15,625 | 0.00704 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU... | ,
prod_id, amount, False, unit, vals_line['journal_id'], context=context)
if amount_unit and 'amount' in amount_unit.get('value',{}):
updv = { 'amount': amount_unit['value']['amount'] }
| timesheet_obj.write(cr, uid, [timeline_id], updv, context=context)
return timeline_id
def create(self, cr, uid, vals, *args, **kwargs):
context = kwargs.get('context', {})
if not context.get('no_analytic_entry',False):
vals['hr_analytic_timesheet_id'] = self._create_analyt... |
dnanexus/rseqc | rseqc/lib/qcmodule/annoGene.py | Python | gpl-3.0 | 9,403 | 0.064554 | import collections
from bx.intervals import *
from qcmodule import BED
'''Compare given bed entry to reference gene model'''
def getCDSExonFromFile(bedfile):
'''Only Extract CDS exon regions from input bed file (must be 12-column).'''
ret_lst=[]
for f in open(bedfile,'r'):
f = f.strip().split()
chrom = f[0... | .rstrip(',').split(','))
exon_start=map((lambda x: x + txStart),exon_start)
exon_end=map(int,fields[10].rstrip(',').split(','))
exon_end=map((lambda x,y:x+y),exon_start,exon_end)
key = chrom + ":" + txstart + "-" + txEnd + ":" + strand + ':' + geneName
except:
print >>sys.stderr,"[NOTE:input bed must b... | ,
continue
for st,end in zip(exon_start,exon_end):
tmp.append(exon_start,exon_end)
ret_dict_full[key] = set(tmp)
#ret_dict_inner[key] = set(tmp[1:-1])
return ret_dict_full
def getUTRExonFromLine(bedline,utr=35):
'''Extract UTR regions from input bed line. When utr=35 [default], extract both
5' and 3' ... |
dokipen/trac | trac/resource.py | Python | bsd-3-clause | 15,270 | 0.001506 | # -*- coding: utf-8 -*-
#
# Copyright (C) 2006-2009 Edgewall Software
# Copyright (C) 2006-2007 Alec Thomas <[email protected]>
# Copyright (C) 2007 Christian Boos <[email protected]>
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distr... | or indicating the latest version
>>> main = Resource('wiki', 'WikiStart')
>>> repr(main)
"<Resource u'wiki:WikiStart'>"
>>> Resource(main) is main
True
>>> main3 = Resource(main, version=3)
>>> repr(main3)
"<Resource u'wiki:WikiStart@3'>"
... | main0 = main3(version=0)
>>> repr(main0)
"<Resource u'wiki:WikiStart@0'>"
In a copy, if `id` is overriden, then the original `version` value
will not be reused.
>>> repr(Resource(main3, id="WikiEnd"))
"<Resource u'wiki:WikiEnd'>"
>>> repr(Resource(None))
... |
Byron/bcore | src/python/bcontext/tests/__init__.py | Python | lgpl-3.0 | 243 | 0.00823 | #-*-coding:utf-8-*-
"""
@package bcontext.tests
@brief tests for bcontext
@author Sebastian Thiel
@copyright [G | NU Lesser General Public License](https://www.gnu.org/licenses/lgpl.html)
"""
from __future__ import unico | de_literals
__all__ = []
|
yolanother/script.pseudotv.live | pseudotv.py | Python | gpl-3.0 | 1,802 | 0.007769 | # Copyright (C) 2011 Jason Anderson
#
#
# This file is part of PseudoTV.
#
# PseudoTV 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.... | y.TVOverlay("script.pseudotv.live.TVOverlay.xml", __cwd__, Skin_Select)
for curthread in threading.enumerate():
try:
log("Active Thread: " + str(curthread.name), xbmc.LOGERROR)
|
if curthread.name != "MainThread":
try:
curthread.join()
except:
pass
log("Joined " + curthread.name)
except:
pass
del MyOverlayWindow
xbmcgui.Window(10000).setProperty("PseudoTVRunning", "False")
|
Pipe-s/dynamic_machine | dynamic_machine/cli_process_json_test.py | Python | mit | 4,232 | 0.008979 | '''
Created on Jun 19, 2014
@author: lwoydziak
'''
from dynamic_machine.cli_process_json import CliProcessingJson
from mockito.mocking import mock
from mockito.matchers import any
from mockito.mockito import when, verifyNoMoreInteractions, verify
from _pytest.runner import fail
from dynamic_machine.cli_commands import... | on.loadJsonFile()
verify(jsonObject).load(any())
def test_unsuccessfullLoadFromFile():
jsonObject = mock | ()
cliProcessingJson = CliProcessingJson("garbage", jsonObject=jsonObject)
when(jsonObject).load(any()).thenRaise(Exception())
cliProcessingJson.loadJsonFile()
def test_commandCreatedCorrectly():
cliProcessingJson = CliProcessingJson("garbage")
assert 'pwd' in str(cliProcessingJson.getCommand("... |
vitay/ANNarchy | ANNarchy/generator/Projection/OpenMP/__init__.py | Python | gpl-2.0 | 1,202 | 0.002496 | """
The OpenMP package does contain all code templates required for the openMP |
code generation in ANNarchy.
BaseTemplates:
defines the basic defintions common to all sparse matrix formates, e. g. projection header
[FORMAT]_SingleThread:
defines the format specific defintions for the currently available formats:
* LIL: list-in-list
* COO: coordinate
* CSR: com... | th array
* Dense: a full matrix representation
there are some special purpose implementations:
* CSR_T: compressed sparse row (transposed)
* LIL_P: a partitioned LIL representation
"""
from . import LIL as LIL_OpenMP
from . import LIL_P as LIL_Sliced_OpenMP
from . import COO as COO_OpenMP
... |
atakan/Fractal-Trails | trail_maker.py | Python | gpl-3.0 | 6,471 | 0.014219 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (C) 2011 Mehmet Atakan Gürkan
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3 as
# published by the Free Software Foundation.
#
# This program is distributed i... | help='initial value of x component (for 3D)')
parser.add_argument('-P0y',
type=float, default=0.0, dest='P0y',
help='initial value of y component (for 3D)')
parser.add_argument('-P0z',
type=float, default=0.0, dest='P0z',
help='initial val... | dest='outfile',
type=argparse.FileType('w'),
default=sys.stdout,
help='output filename (if not given, use stdout)')
parser.add_argument('--numpy', dest='outputformat', action='store_const',
const='numpy', default='undecided',
... |
zugaldia/capitalbikeshare | appengine/app/shared/models/user_model.py | Python | apache-2.0 | 2,057 | 0 | from appython.components.api.common_fields import IsSetField
from appython.components.models.base_model import BaseModel
from appython.components.user.base_manager import BaseManager
from flask.ext.restful import fields, marshal
from google.appengine.ext import ndb
class UserModel(BaseModel):
# Every user must ha... | l
'''
Getters
'''
@classmethod
def get_by_email(cls, email):
email_ready = BaseManager.prepare_email(email=email)
return cls.query(cls.email == email_ready).get()
@classmethod
def get_by_api_key(cls, api_key):
return cls.query(cls.ap | i_key == api_key).get()
'''
Required by Flask-Login. Note that @property doesn't work here because
it only works with new-style classes.
'''
def is_active(self):
return False if self.deleted else True
def is_authenticated(self):
return True
def is_anonymous(self):
... |
ballouche/navitia | source/jormungandr/jormungandr/autocomplete/abstract_autocomplete.py | Python | agpl-3.0 | 1,893 | 0.000528 | # coding=utf-8
# Copyright (c) 2001-2014, Canal TP and/or its affiliates. All rights reserved.
#
# This file is part of Navitia,
# the software to build cool stuff with public transport.
#
# Hope you'll enjoy and contribute to this project,
# powered by Canal TP (www.canaltp.fr).
# Help us simplify mobility an... |
__metaclass__ = ABCMeta
@abstractmethod
def get(self, query, instance):
pass
@abstractmethod
def geo_status(self, instance):
pass
class GeoStatusResponse(object):
def __init__(self):
self.street_network_sources = []
self.poi_sources = []
self.nb_admin... | ses = None
self.nb_pois = None
|
matslindh/codingchallenges | adventofcode2016/25.py | Python | mit | 3,632 | 0.005507 | instr = [x.strip().split(' ') for x in open("input/dec25").readlines()]
skip = {}
modified = {}
#instr[1] = ['add', 'a', '2572']
#skip[2] = skip[3] = skip[4] = skip[5] = skip[6] = skip[7] = skip[8] = skip[9] = True
#instr[6] = ['add', 'a', 'c'] # adds c to d, sets c to 0
#skip[7] = True
#skip[8] = True
#modified[6] =... | jnz':
if (inst[1] in reg and reg[inst[1]] != 0) or (inst[1] not in reg and int(inst[1]) != 0):
if inst[2] in reg:
pc += reg[inst[2]]
else:
pc += int(inst[2])
else:
pc += 1
elif inst[0] == 'tgl':
... |
# valid
if d < len(instr) and d >= 0:
if d in modified:
print("modified instruction tggled")
if len(instr[d]) == 2:
if instr[d][0] == 'inc':
instr[d][0] = 'dec'
... |
power12317/Chrome-Data-Compression-Proxy-Standalone-Python | google.py | Python | gpl-2.0 | 6,470 | 0.007419 | #!/usr/bin/env python
#coding:utf-8
# Author: Beining --<cnbeining#gmail.com>
# Purpose: A Chrome DCP handler.
# Created: 07/15/2015
#Original copyright info:
#Author: Xiaoxia
#Contact: [email protected]
#Website: xiaoxia.org
import sys
import argparse
from th | reading import Thread, Lock
from struct import unpack
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
from httplib import HTTPResponse, HTTPSConnection
from Socket | Server import ThreadingMixIn
import socket, os, select
import time, sys, random
import threading
import select
import socket
import ssl
import socket
import urllib2
# Minimize Memory Usage
threading.stack_size(128*1024)
BufferSize = 8192
RemoteTimeout = 15
from hashlib import md5
global PROXY_MODE
PROXY_MODE = '... |
quasiben/bokeh | bokeh/models/formatters.py | Python | bsd-3-clause | 13,993 | 0.001358 | """ Models for controlling the text and visual formatting of tick
labels on Bokeh plot axes.
"""
from __future__ import absolute_import
from .tickers import Ticker
from ..model import Model
from ..core.properties import abstract
from ..core.properties import Bool, Int, String, Enum, Auto, List, Dict, Either, Instance... | r with that ASCII value
- ``d`` or ``i`` --- yields an integer as a signed decimal number
- ``e`` --- yields a float using scientific notation
- ``u`` --- yields an integ | er as an unsigned decimal number
- ``f`` --- yields a float as is
- ``o`` --- yields an integer as an octal number
- ``s`` --- yields a string as is
- ``x`` --- yields an integer as a hexadecimal number (lower-case)
- ``X`` --- yields an integer as a hexadecimal number (upper-cas... |
buchbend/astrolyze | test/test_astro_functions.py | Python | bsd-3-clause | 526 | 0.003802 | import unittest
import doctest
import os
import astrolyze.functions.astro_functions
class Test(unittest.TestCase):
"""Unit t | ests for astro_functions."""
def test_doctests(self):
"""Run astro_functions doctests"""
doctest.testmod(astrolyze.functions.astro_functions)
os.system('/usr/bin/convert black_body.eps testfigures/black_body.jpg')
os.system('cp testfigures/black_body.jpg ../d | oc/figures/')
os.system('rm black_body.eps')
if __name__ == "__main__":
unittest.main()
|
ABusers/A-Certain-Magical-API | funimation/api.py | Python | mit | 3,784 | 0.001057 | # -*- coding: utf-8 -*-
from .httpclient import HTTPClient
from .models import Video, Show
__all__ = ['Funimation']
class Funimation(object):
def __init__(self):
super(Funimation, self).__init__()
self.http = HTTPClient('http://www.funimation.com/',
[('User-Agent'... | deo_split[0]+video_split[split_len-2]+video_split[split_len-1]
return request
def get_featured(self, limit=3000, offset=0):
query = self._build_query(locals())
return self._request('feeds/ps/featured', query)
def search(self, search):
query = self._build_query(locals())
... | ser':
sort = 'SortOptionLatestSubscription'
else:
sort = 'SortOptionLatestFree'
return self.get_shows(limit, offset, sort)
def get_simulcast(self, limit=3000, offset=0):
return self.get_shows(limit, offset, filter='FilterOptionSimulcast')
def get_genres(self):
... |
SivagnanamCiena/nxapi-learning-labs | setup.py | Python | apache-2.0 | 3,329 | 0.001802 | """A setuptools based setup module.
See:
https://packaging.python.org/en/latest/distributing.html
https://github.com/pypa/sampleproject
"""
# Always prefer setuptools over distutils
from setuptools import setup, find_packages
# To use a consistent encoding
from codecs import open
from os import path
here = path.absp... | if your project is
# simple. Or you can use find_packages().
# packages=find_packages(exclude=['config', 'test']),
packages=['nxapi'],
# List run-time dependencies here. These will be installed by pip when
# your project is installed. For an analysis of "install_requires" vs pip's
# requireme... | iles see:
# https://packaging.python.org/en/latest/requirements.html
install_requires=[
"requests",
"ipaddress",
"tabulate",
"future",
],
# List additional groups of dependencies here (e.g. development
# dependencies). You can install these using the following syntax... |
adamcaudill/yawast | tests/test_print_header.py | Python | mit | 640 | 0.001563 | # Copyright (c) 2013 - 2020 Adam Caudill and Contributors.
# This file is part of YAWAST which is released under the MIT license.
# See the LICENSE file or go to https://yawast.org/license/ for full license details.
from unittest import TestCase
from tests import utils
from yawast import main
from yawast._version ... | with utils.capture_sys_output() as (stdout, stderr):
| main.print_header()
self.assertIn("(v%s)" % get_version(), stdout.getvalue())
|
inwotep/lava-dispatcher | lava_dispatcher/tests/test_device_version.py | Python | gpl-2.0 | 3,007 | 0.00133 | # Copyright (C) 2012 Linaro Limited
#
# Author: Antonio Terceiro <[email protected]>
#
# This file is part of LAVA Dispatcher.
#
# LAVA Dispatcher 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; eith... | name(__file__), 'test-config', 'bin', 'fake-qemu')
target = _create_qemu_target({'qemu_binary': fake_qemu})
device_version = target.get_device_version()
assert(re.search('^[0-9.]+', device_version))
class TestDevice(LavaDispatcherTestCase):
def setUp(self):
super(TestDevice, self)... | t_cmds_preprocessing(boot_cmds)
self.assertEqual(return_value, expexted)
def test_boot_cmds_preprocessing(self):
boot_cmds = ["foo", "bar", ""]
expected = ["foo", "bar"]
return_value = self.target._boot_cmds_preprocessing(boot_cmds)
self.assertEqual(return_value, expected)
|
dreams6/pyerpcn | pyerp/fnd/api/user.py | Python | gpl-3.0 | 1,030 | 0.010373 | # -*- coding: utf-8 -*-
"""
这个模块实现了用户管理相关功能。
create_user() 用于创建用户。
为指定用户绑定职责。
"""
from datetime im | port datetime, date
from pyerp.fnd import models
from pyerp.fnd.gbl import fnd_global
from pyerp.fnd.utils.version import get_svn_revision, get_version
__svnid__ = '$Id: user.py 98 2010-02-01 13:52:36Z yuhere $'
__svn__ = get_svn_revision(__name__)
def create_user(username, password, description, email,
... | _expiration_type=0, pwd_lifespan=0,
start_date_active=date.today(), end_date_active=None):
user = models.User()
user.username = username
user.set_password(password)
user.description = description
user.email = email
user.fax = None
user.pwd_expiration_type ... |
ypwalter/evennia | evennia/utils/eveditor.py | Python | bsd-3-clause | 26,775 | 0.001793 | """
EvEditor (Evennia Line Editor)
This implements an advanced line editor for editing longer texts
in-game. The editor mimics the command mechanisms of the "VI" editor
(a famous line-by-line editor) as far as reasonable.
Features of the editor:
- undo/redo.
- edit/replace on any line of the buffer.
- search&repl... | part2 = arglist[0].split(':')
if part1 and part1.isdigit(): |
lstart = min(max(0, int(part1)) - 1, nlines)
linerange = True
if part2 and part2.isdigit():
lend = min(lstart + 1, int(part2)) + 1
linerange = True
elif arglist and arglist[0].isdigit():
lstart = min(max(0, int(arglist[0]) ... |
dl1ksv/gnuradio | gnuradio-runtime/python/pmt/__init__.py | Python | gpl-3.0 | 1,351 | 0.00148 | #
# Copyright 2011 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# SPDX-License-Identifier: GPL-3.0-or-later
#
#
# The presence of this file turns this directory into a Python package
'''
Poly | morphic Types.
The type can really be used to store anything, but also has simple
conversion methods for common data types such as bool, long, or | a
vector.
The polymorphic type simplifies message passing between blocks, as all
of the data is of the same type, including the message. Tags also use
PMTs as data type, so a stream tag can be of any logical data type. In
a sense, PMTs are a way to extend C++' strict typing with something
more flexible.
The PMT libra... |
franramirez688/common | test/edition/changevalidator_test.py | Python | mit | 2,188 | 0.000914 | import unittest
from biicode.common.edition.hive import Hive
from biicode.common.model.blob import Blob
from biicode.common.exception import BiiException
from biicode.common.edition import changevalidator
from biicode.common.edition.processors.processor_changes import ProcessorChanges
from biicode.common.conf import BI... | ion.changevalidator import BII_FILE_SIZE_LIMIT_STR
from biicode.common.output_stream import OutputStream
from biicode.common.model.content import Content
class ChangeValidatorTest(unittest.TestCase):
def setUp(self):
self.load = Blob()
def te | st_large_cell_reject(self):
self.load.binary = bytearray(BII_FILE_SIZE_LIMIT)
files = {"user/block/file": (None, self.load)}
biiout = OutputStream()
changevalidator.remove_large_cells(files, biiout)
self.assertEquals(0, len(files))
self.assertEquals("WARN: File user/bloc... |
ifduyue/sentry | src/sentry/plugins/sentry_interface_types/models.py | Python | bsd-3-clause | 998 | 0.001002 | """
sentry.plugins.sentry_interface_types.models
~~~~~~~~~~~~~~~~~~~~~ | ~~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import
import six
import sentry
from sentry.plugins import register
from sentry.plugins.bases.tag import TagPlugin
class InterfaceTyp... | face (e.g. Http, Stacktrace, Exception).
"""
descrption = __doc__
slug = 'interface_types'
title = 'Auto Tag: Interface Types'
version = sentry.VERSION
author = "Sentry Team"
author_url = "https://github.com/getsentry/sentry"
tag = 'interface_type'
project_default_enabled = False
... |
ajkxyz/cuda4py | src/cuda4py/blas/__init__.py | Python | bsd-2-clause | 2,953 | 0.000339 | """
Copyright (c) 2014, Samsung Electronics Co.,Ltd.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and... | e documentation
and/or other materia | ls provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CO... |
srvasn/basic-chat-server | constants.py | Python | gpl-3.0 | 513 | 0 | # Declaring constants for use throughout the program
STATE_AUTH = 'AUTH' |
STATE_CHAT = 'CHAT'
SIGN_UP = 'SIGN_UP'
LOGIN = 'REGISTER'
EXIT = 'EXIT'
EXIT_COMMAND = '.quit' # This is what the user types when he/she wants to quit
DB_URL = 'storage.db'
PORT = 1236
LOG_FILE_URL = 'chatserver.log'
TEST_USER_FILE = 'sim_users.js | on'
TEST_MESSAGES = ["Sample Message 1",
"Sample Message 2",
"Sample Message 3",
"Sample Message 4",
"Sample Message 5"]
|
orbeckst/RecSQL | recsql/csv_table.py | Python | gpl-3.0 | 4,336 | 0.003921 | # -*- Mode: python; tab-width: 4; indent-tabs-mode:nil; coding:utf-8 -*-
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
#
# RecSQL -- a simple mash-up of sqlite and numpy.recsql
# Copyright (C) 2007-2016 Oliver Beckstein <[email protected]>
# Released under the GNU Public License, version 3 or higher (your choi... | v examples: http://docs.python.org/library/csv.html#csv-examples
import codecs
class UTF8Recoder(object):
"""
Iterator that reads an encoded stream and reencodes the input to UTF-8
"""
def __init__(self, f, encoding):
self.reade | r = codecs.getreader(encoding)(f)
def __iter__(self):
return self
def next(self):
return self.reader.next().encode("utf-8")
class UnicodeReader(object):
"""
A CSV reader which will iterate over lines in the CSV file "f",
which is encoded in the given encoding.
"""
def __i... |
letolab/airy | airy/utils/unittest/signals.py | Python | bsd-2-clause | 1,682 | 0.002973 | import signal
import weakref
from airy.utils.unittest.compatibility import wraps
__unittest = True
class _InterruptHandler(object):
def __init__(self, default_handler):
self.called = False
self.default_handler = default_handler
def __call__(self, signum, frame):
installed_handler = ... | if self.called:
self.default_handler(signum, frame)
self.called = True
for result in _results.keys():
result.stop()
_results = weakref.W | eakKeyDictionary()
def registerResult(result):
_results[result] = 1
def removeResult(result):
return bool(_results.pop(result, None))
_interrupt_handler = None
def installHandler():
global _interrupt_handler
if _interrupt_handler is None:
default_handler = signal.getsignal(signal.SIGINT)
... |
BitWriters/Zenith_project | zango/lib/python3.5/site-packages/django/conf/locale/es_PR/formats.py | Python | mit | 738 | 0 | # | -*- encoding: utf-8 - | *-
# This file is distributed under the same license as the Django package.
#
from __future__ import unicode_literals
DATE_FORMAT = r'j \d\e F \d\e Y'
TIME_FORMAT = 'H:i'
DATETIME_FORMAT = r'j \d\e F \d\e Y \a \l\a\s H:i'
YEAR_MONTH_FORMAT = r'F \d\e Y'
MONTH_DAY_FORMAT = r'j \d\e F'
SHORT_DATE_FORMAT = 'd/m/Y'
SHORT_... |
ales-erjavec/orange-bio | orangecontrib/bio/widgets3/OWGeneNetwork.py | Python | gpl-3.0 | 16,602 | 0.000723 | import sys
from collections import namedtuple
from AnyQt.QtWidgets import QSizePolicy, QLayout
from AnyQt.QtCore import Slot
import Orange.data
from Orange.widgets.utils.datacaching import data_hints
from Orange.widgets import widget, gui, settings
from Orange.widgets.utils import itemmodels
from Orange.widgets.uti... | include_neighborhood=include_neighborhood,
min_score=min_score,
progress=methodinvoke(self, "set_progress", (float,)))
self.nettask = Task(function=fetch_network)
self.nettask.finished.connect(self._on_result_ready)
se... | = False
self._update_info()
@Slot()
def _on_result_ready(self,):
self.progressBarFinished()
self.setBlocking(False)
self.setEnabled(True)
net = self.nettask.result()
self._update_info()
self.send("Network", net)
def _on_source_db_changed(self):
... |
ClearCorp/odoo-clearcorp | account_payment_report/report/account_payment_report.py | Python | agpl-3.0 | 2,163 | 0 | # -*- coding: utf-8 -*-
# © 2016 ClearCorp
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
import re
from openerp.report import report_sxw
from openerp import models, _
from openerp.exceptions import Warning
CURRENCY_NAMES = {
'USD': {
'en': 'Dollars',
'es': 'DOLARES',
},
... | RRENCY_NAMES[currency.name][lang]
raise Warning(_('Currency not supported by this rep | ort.'))
def _get_text_amount(self, amount, currency_id):
es_regex = re.compile('es.*')
en_regex = re.compile('en.*')
lang = self.localcontext.get('lang')
if es_regex.match(lang):
from openerp.addons.l10n_cr_amount_to_text import amount_to_text
return amount_t... |
aipescience/daiquiri-admin | daiquiri/data.py | Python | apache-2.0 | 2,181 | 0.001834 | from daiquiri.exceptions import Dai | quiriException
class Data():
def __init__(self, connection, dryrun=False):
self.connection = connection
self.dryrun = dryrun
def | fetch_databases(self):
response = self.connection.get('/data/databases/')
if response['status'] != 'ok':
raise DaiquiriException(response['errors'])
else:
return response['databases']
def update_table(self, table_id, table):
if not self.dryrun:
r... |
rfhk/rqn-custom | purchase_order_sale_order_nrq/models/purchase_order.py | Python | agpl-3.0 | 349 | 0.002865 | # -*- coding: utf-8 -*-
# Copyright 2018 Quartile Limited
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import fields, models
class PurchaseOrder(models.Model):
_inherit = "purchase.order"
sale_ids = fields.Many2many(
"sa | le.order", related="order_line.sale_ids", string="Related Sales Order(s)" |
)
|
a25kk/vfu | src/vfu.events/vfu/events/myform.py | Python | mit | 3,814 | 0.014421 | import random
import zope.schema
import zope.interface
from zope.i18nmessageid import MessageFactory
from zope.component import getUtility, getMultiAdapter
from zope.browserpage.viewpagetemplatefile import ViewPageTemplateFile as Zope3PageTemplateFile
from Products.Five.browser.pagetemplatefile import ViewPageTemplat... | cing = data['pricing'],
comments = data['comments'])
portal = getToolByName(self, 'portal_url').getPortalObject()
encoding = portal.getProperty('email_charset', 'utf-8')
trusted_template = | trusted(portal.registration_email)
mail_text = trusted_template(
self, charset=encoding, reg_data = new_obj, event = self.context)
subject = self.context.translate(_(u"New registration"))
m_to = data['email']
## notify admin about new registration
if isinstance(... |
paninski-lab/yass | tests/conftest.py | Python | apache-2.0 | 2,794 | 0 | import shutil
import tempfile
import numpy as np
import os
from os.path import getsize
import pytest
import yaml
from util import PATH_TO_TESTS, seed, dummy_predict_with_threshold
PATH_TO_ASSETS = os.path.join(PATH_TO_TESTS, 'assets')
PATH_TO_RETINA_DIR = os.path.join(PATH_TO_ASSETS, 'recordings', 'retina')
PATH_TO_R... | eline_output')
@pytest.fixture()
def path_to_standardized_data | ():
return os.path.join(PATH_TO_RETINA_DIR,
'sample_pipeline_output', 'preprocess',
'standardized.bin')
@pytest.fixture()
def path_to_output_reference():
return os.path.join(PATH_TO_ASSETS, 'output_reference')
@pytest.fixture
def path_to_config():
return _... |
johm/infoshopkeeper | popups/checkout.py | Python | gpl-2.0 | 2,958 | 0.008114 | # Copyright 2006 John Duda
# This file is part of Infoshopkeeper.
# Infoshopkeeper 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 any later version.
# Infoshopkeeper ... | UT 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 Infoshopkeeper; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
# USA
from wxPython.wx import *
import os
import datetime
from objects.emprunt import Emprunt
from popups.members import AddMemberPanel, ShowMembersPanel
class CheckoutP... |
jerodg/hackerrank-python | python/02.Strings/04.FindAString/template.py | Python | mit | 209 | 0 | def c | ount_substring(string, sub_string):
return
if __name__ == '__main__':
string = input().strip()
sub_string = in | put().strip()
count = count_substring(string, sub_string)
print(count)
|
istartsev/aws_helper-git | tests/test_s3.py | Python | apache-2.0 | 2,939 | 0.000681 | import filecmp
import shutil
import errno
import os
from unittest import TestCase
import time
from faker import Faker
from aws_helper.s3 import s3_helper as s3
from tests.settings import S3Settings
class BaseTest(TestCase):
@classmethod
def _clearTestFolder(cls):
try:
shutil.rmtree(S3Se... | en(cls._filename, 'w') as file:
file.write(cls._fake.text())
def testUploadDownloadFile(self):
dw_filename = self._filename + '_dw'
self._client.upload_file(self._filename, self._filename)
| self._client.download_file_new(self._filename, dw_filename)
result = filecmp.cmp(self._filename, dw_filename)
self.assertTrue(result)git
class TestS3Bucket(BaseTest):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls._bucket_name = 'TEST_AWS_Helper_bucket_%f' % ... |
endlessm/chromium-browser | third_party/llvm/lldb/test/API/python_api/interpreter/TestCommandInterpreterAPI.py | Python | bsd-3-clause | 3,209 | 0 | """Test the SBCommandInterpreter APIs."""
from __future__ import print_function
import lldb
from lldbsuite.test.decorators import *
from lldbsuite.test.lldbtest import *
from lldbsuite.test import lldbutil
class CommandInterpreterAPICase(TestBase):
mydir = TestBase.compute_mydir(__file__)
NO_DEBUG_INFO_TE... | COMMAND_INTERPRETER)
# T | est that a command which produces no output returns "" instead of
# None.
res = lldb.SBCommandReturnObject()
ci.HandleCommand("settings set use-color false", res)
self.assertTrue(res.Succeeded())
self.assertIsNotNone(res.GetOutput())
self.assertEquals(res.GetOutput(), "")... |
bernard357/shellbot | tests/updaters/test_elastic.py | Python | apache-2.0 | 2,830 | 0.000353 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import unittest
from elasticsearch import ConnectionError
import gc
import logging
import mock
from multiprocessing import Process, Queue
import os
import sys
from shellbot import Context, Engine
from shellbot.events import Message
from shellbot.updaters import Elasticsea... | self.assertEqual(u.get_host(), 'localhost:9200')
u = ElasticsearchUpdater(engine=my_engine, host='')
self.assertEqual(u.get_host(), 'localhost:9200')
u = ElasticsearchUpdater(engine=my_engine, host= | 'elastic.acme.com')
self.assertEqual(u.get_host(), 'elastic.acme.com')
def test_on_bond(self):
logging.info('***** on_bond')
u = ElasticsearchUpdater(host='this.does.not.exist')
with self.assertRaises(Exception):
u.on_bond(bot='*dummy')
def test_put(self):
... |
ekcs/congress | congress/tests/api/test_driver_model.py | Python | apache-2.0 | 3,604 | 0 | # Copyright (c) 2015 OpenStack Foundation
#
# 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 | he License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an | "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from oslo_config import cfg
from congress.api.system import driver_model
from congress.api import webservice
from congress ... |
olgamelnichuk/NGSPyEasy | examples/trivial/library/dockercmd.py | Python | gpl-2.0 | 2,283 | 0.001314 | #!/usr/bin/env python
import glob
def main():
module = AnsibleModule(
argument_spec=dict(
command=dict(required=True, default=None, type='str'),
image=dict(required=True, default=None, type='str'),
volumes=dict(required=False, default=[], type='list'),
envir... | module.params['rm']
creates = module.params['creates']
if len(creates) > 0:
uncreated = [x for x in creates if not glob.glob(os.path.expanduser(x))]
if len(uncreated) == 0:
module.exit_json(
cmd=command,
stdout="skipped, since %s exi | st" % creates,
changed=False,
stderr=False,
rc=0
)
cmd = []
if secure:
cmd.append("sudo dockercmd run")
else:
cmd.append(("sudo " if sudo else "") + "docker run")
if rm:
cmd.append("--rm")
if working_dir is not No... |
openstack/python-openstacksdk | openstack/tests/unit/identity/v3/test_application_credential.py | Python | apache-2.0 | 2,214 | 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 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 openstack.tests.unit import base
from openstack.identity.v3 import application_credential
EXAMPLE = {
"user": {
"id": "8ac43bb0926245cead88676a96c750d3"},
"name": 'monitoring',
"secret": 'rEaqvJka48mpv',
"roles": [
{"name": "Reader"}
],
"expires_at":... |
Kniyl/mezzanine | mezzanine/twitter/models.py | Python | bsd-2-clause | 6,647 | 0.00015 | from __future__ import unicode_literals
from future.builtins import str
from datetime import datetime
import re
try:
from urllib.parse import quote
except ImportError:
# Python 2
from urllib import quote
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from djang... | eld(_("Twitter ID"), max_length=50)
created_at = models.DateTimeField(_("Date/time"), null=True)
text = models.TextField(_("Message"), null=True)
profile_image_url = models.URLField(_("Profile image URL"), null=True)
user_name = models.CharField(_("User name"), max_length=100, null=True)
full_name =... | x_length=100, null=True)
retweeter_profile_image_url = models.URLField(
_("Profile image URL (Retweeted by)"), null=True)
retweeter_user_name = models.CharField(
_("User name (Retweeted by)"), max_length=100, null=True)
retweeter_full_name = models.CharField(
_("Full name (Retweeted ... |
Lamzin/myPython | Algebra/matrix_extreme.py | Python | gpl-2.0 | 8,779 | 0.003303 | import random
import copy
from fractions import Fraction
def get_matrix(file_name="matrix_new.txt"):
file = open(file_name, "r")
A = []
for line in file:
A.append([Fraction(x) for x in line.split()])
return A
def print_file(A, comment = ""):
file = open("matrix_show.txt", "a")
file.wr... | le(item, file_addition)
for item in tmp:
print_in_file(item, file_addition)
for item in fund_syst_array[i]:
print_in_file(item, file_addition)
file_addition.close()
chain.append(vector_ser | ies(A, alpha_current))
print_file([], "Chain #")
for it in chain[-1]:
print_file(it)
first_vector = []
for chain_vect in chain:
for chain_chain in chain |
ade25/wigo | src/wigo.statusapp/wigo/statusapp/setuphandlers.py | Python | mit | 802 | 0.001247 | from plone import api
from plone.app.controlpanel.security import ISecuritySchema
def setup_workspaces(portal):
mp = api.portal.get_tool(name | ='portal_membership')
# set type to custom member type
mp.setMemberAreaType('wigo.workspaces.workspace')
# set member folder name
mp.setMembersFolderById('sqa')
def setup_security(portal):
""" Add security controlpanel settings.
"""
site = api.portal.get()
#si | te security setup!
security = ISecuritySchema(site)
security.set_enable_user_folders(True)
security.use_uuid_as_userid(True)
def setupVarious(context):
if context.readDataFile('wigo.statusapp-various.txt') is None:
return
portal = api.portal.get()
setup_workspaces(portal)
# call up... |
nicememory/pie | pyglet/pyglet/media/drivers/directsound/adaptation.py | Python | apache-2.0 | 17,118 | 0.001402 | # ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2008 Alex Holkner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * R... | def delete(self):
if self.driver and self.driver.worker:
self.driver.worker.remove(self)
with self._lock:
self._ds_buffer = None
def play(self | ):
assert _debug('DirectSound play')
self.driver.worker.add(self)
with self._lock:
if not self._playing:
self._get_audiodata() # prebuffer if needed
self._playing = True
self._ds_buffer.play()
assert _debug('return ... |
fbradyirl/home-assistant | homeassistant/util/aiohttp.py | Python | apache-2.0 | 1,432 | 0 | """Utilities to help with aiohttp."""
import json
from urllib.parse import parse_qsl
from typing import Any, Dict, Optional
from multidict import CIMultiDict, MultiDict
class MockRequest:
"""Mock an aiohttp request."""
def __init__(
self,
content: bytes,
method: str = "GET",
... |
query_string: Optional[str] = None,
url: str = "",
) -> None:
"""Initialize a request."""
self.method = method
self.url = url
self.status = status
self.headers = CIMultiDict(headers or {}) # type: CIMultiDict[str]
self.query_string = query_string or ... | query(self) -> "MultiDict[str]":
"""Return a dictionary with the query variables."""
return MultiDict(parse_qsl(self.query_string, keep_blank_values=True))
@property
def _text(self) -> str:
"""Return the body as text."""
return self._content.decode("utf-8")
async def json(s... |
leaen/Codeeval-solutions | mth-to-last-element.py | Python | mit | 325 | 0.006154 | import sys
def main():
| with open(sys.argv[1]) as input_file:
for line in input_file.readlines():
input_list = list(reversed(line.strip().split(' ')))
index = int(input_list[0])
del input_l | ist[0]
print(input_list[index - 1])
if __name__ == '__main__':
main()
|
ubuntu-core/snapcraft | tests/unit/sources/test_bazaar.py | Python | gpl-3.0 | 7,406 | 0.00054 | # -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*-
#
# Copyright (C) 2015-2019 Canonical Ltd
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3 as
# published by the Free Software Foundation.
#
# This program is distributed in ... | self.fake_check_call.mock.assert_called_once_with(
["bzr", "pull", self.working_tree, "-d", self.source_dir],
stderr=-3,
stdout=-3,
)
def test_bzr_details_tag(self):
bzr = sources.Bazaar(
| self.working_tree, self.source_dir, source_tag="mock-tag", silent=True
)
bzr.pull()
source_details = bzr._get_source_details()
self.assertThat(source_details["source-tag"], Equals("mock-tag"))
self.fake_check_output.mock.assert_not_called()
self.fake_check_cal... |
sampathweb/cs109_twitterapp | app/blueprints/__init__.py | Python | mit | 48 | 0 | from | main.views imp | ort main
__all__ = ['main']
|
thaumos/ansible | lib/ansible/modules/cloud/azure/azure_rm_virtualmachine.py | Python | gpl-3.0 | 97,131 | 0.00384 | #!/usr/bin/python
#
# Copyright (c) 2016 Matt Davis, <[email protected]>
# Chris Houseknecht, <[email protected]>
#
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANS... | disabled by setting ssh_password_enabled to false.
ssh_password_enabled:
description:
- When the os_type is Linux, setting ssh_password_enabled to false will disable SSH password authentication
and require use of SSH keys.
default: true
type: bool
ssh_public_ke... | uld be a dictionary where the
dictionary contains two keys: path and key_data. Set the path to the default location of the
authorized_keys files. On an Enterprise Linux host, for example, the path will be
/home/<admin username>/.ssh/authorized_keys. Set key_data to the actual v... |
ddsc/ddsc-core | ddsc_core/migrations/0006_add_model_MeasuringMethod.py | Python | mit | 6,529 | 0.007352 | # -*- cod | ing: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'MeasuringMethod'
db.create_table(u'ddsc_core_measuringmethod', (
| ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('code', self.gf('django.db.models.fields.CharField')(unique=True, max_length=12)),
('description', self.gf('django.db.models.fields.CharField')(unique=True, max_length=60)),
('begin_date', self.gf('django.d... |
ToontownUprising/src | toontown/chat/WhisperPopup.py | Python | mit | 11,313 | 0.000088 | from panda3d.core import TextNode, PGButton, Point3
from toontown.chat import ChatGlobals
from toontown.chat.ChatBalloon import ChatBalloon
from toontown.margins import MarginGlobals
from toontown.margins.MarginVisible import MarginVisible
fr | om to | ontown.nametag import NametagGlobals
from toontown.toontowngui.Clickable2d import Clickable2d
class WhisperQuitButton(Clickable2d):
CONTENTS_SCALE = 12
def __init__(self, whisperPopup):
Clickable2d.__init__(self, 'WhisperQuitButton')
self.whisperPopup = whisperPopup
self.contents.se... |
gholms/euca2ools | euca2ools/commands/iam/removeclientfromopenidconnectprovider.py | Python | bsd-2-clause | 1,921 | 0 | # Copyright (c) 2016 Hewlett Packard Enterprise Development LP
#
# Redistribution and use of this software in source and binary forms,
# with or without modification, are permitted provided that the following
# conditions are met:
#
# Redistributions of source code must retain the above copyright notice,
# this lis... | IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT... | N ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from requestbuilder import Arg
from euca2ools.commands.iam import IAMRequest, AS_ACCOUNT
class Re... |
stefan2904/activismBot | activistManager/models.py | Python | mit | 477 | 0 | from django.db import models
from botManager.models import Bot
class Activist(models.Model):
identifier = models.CharField(max_length= | 200)
name = models.CharField(ma | x_length=200)
username = models.CharField(max_length=200)
reg_date = models.DateTimeField('Date registered', auto_now_add=True)
bot = models.ForeignKey(Bot) # on_delete=models.CASCADE)
def __str__(self):
return '{} ({}: {})'.format(self.name, self.bot.name, self.identifier)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.