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 |
|---|---|---|---|---|---|---|---|---|
bassosimone/libneubot | test/pollable1.py | Python | gpl-3.0 | 892 | 0.005605 | #!/usr/bin/env python
# Public domain, 2013 Simone Basso <bassosimone@gmail.com>.
""" Test for NeubotPollable """
import ctypes
import os
import sys
sys.path.insert(0, "/usr/local/share/libneubot")
from libneubot import Pollable
from libneubot import Poller
class EchoPollable(Pollable):
def __init__(self, pol... | def handle_read(self):
data = os.read(0, 1024)
if not data:
self.poller.break_loop()
return
sys.stdout.write(data)
def handle_error(self):
sys.stderr.write("error!\ | n")
self.poller.break_loop()
def main():
poller = Poller()
pollable = EchoPollable(poller)
pollable.attach(0)
pollable.set_timeout(7.0)
pollable.set_readable()
poller.loop()
pollable.close()
if __name__ == "__main__":
main()
|
harsh-a1/repeater-testing | dulwich/dulwich/client.py | Python | gpl-2.0 | 5,919 | 0.001521 | # server.py -- Implementation | of the server side git protocols
# Copryight (C) 2008 Jelmer Vernooij <jelme | r@samba.org>
#
# 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
# or (at your option) a later version of the License.
#
# This program is distributed in the hope that it will be ... |
jaideepcoder/PyBN | tests/Tests.py | Python | mit | 112 | 0 | imp | ort unittest
class TestPyBN(unittest.TestCase):
def sample_test(self):
self.assertEqual(1, | 1)
|
bitglue/shinysdr | shinysdr/test/plugins/test_dsd.py | Python | gpl-3.0 | 937 | 0.004269 | # Copyright 2015 Kevin Reid <kpreid@switchb.org>
#
# This file is part of ShinySDR.
#
# ShinySDR 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 lat... | t will be useful,
# 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 c | opy of the GNU General Public License
# along with ShinySDR. If not, see <http://www.gnu.org/licenses/>.
from __future__ import absolute_import, division
from shinysdr.test.testutil import DemodulatorTestCase
class TestDSD(DemodulatorTestCase):
def setUp(self):
self.setUpFor(mode='DSD', skip_if_unavail... |
tigerxy/pymailinglist | mailerconfig.py | Python | gpl-3.0 | 307 | 0.003257 | #!/usr/bin/env python
# -*- cod | ing: UT | F-8 -*-
imapHost = "mail.me.com"
imapUser = "user"
imapPassword = "pw"
smtpHost = "mail.me.com"
smtpUser = "user"
smtpPassword = "pw"
fromAddress = "list@me.com"
listName = "PyMailinglist"
mailingList = ['user1@me.com','user2@me.com']
adminsList = ['admin@me.com']
|
nasa-gibs/onearth | src/test/oe_test_utils.py | Python | apache-2.0 | 44,219 | 0.002058 | # Copyright (c) 2002-2016, California Institute of Technology.
# All rights reserved. Based on Government Sponsored Research under contracts NAS7-1407 and/or NAS7-03001.
#
# Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
# ... | if list(element.items()):
aDict.update(dict(list(element.items())))
if childrenNames.count(element.tag) > 1:
try:
currentValue = self[element.tag]
currentValue.append(aDict)
self.up... | except: #the first of its kind, an empty list must be created
self.update({
element.tag: [aDict]
}) #aDict is written in [], i.e. it will be a list
else:
self.update({element.tag: aDict})
... |
reedessick/event_supervisor2 | pe/__init__.py | Python | mit | 75 | 0 | # Copyright (C) | Reed Essick (2016)
#
# a module for PE follow-up processe | s
|
ayys/siya | pyBSDate/cexceptions.py | Python | gpl-3.0 | 162 | 0.024691 | __author__ = 'sushil'
cla | ss InvalidDateFormat(BaseException):
pass
class DateOutOfRange(BaseException):
pass
class InvalidDate(BaseE | xception):
pass |
danesc87/dotsAndConfs | .config/custom_scripts/nvidia_info.py | Python | gpl-3.0 | 3,282 | 0.001524 | #!/usr/bin/env python3
"""
Description: Simple GTK3 App that shows info from NVIDIA cards
Author: Daniel Córdova A.
E-Mail : danesc87@gmail.com
Github : @danesc87
Released under GPLv3
"""
import gi
from xml.etree import ElementTree
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
class NvidiaInfo(Gtk.... | y", Gtk.main_quit)
self.show_all()
Gtk.main()
|
def set_window_properties(self):
self.get_style_context().add_class('primary-toolbar')
self.set_border_width(10)
self.set_position(Gtk.WindowPosition.MOUSE)
self.set_resizable(False)
self.set_skip_taskbar_hint(True)
self.set_keep_above(True)
self.stick()
... |
Mariana-Tek/django-oscar-accounts | sandbox/settings.py | Python | bsd-3-clause | 7,854 | 0.002292 | import os
from django.utils.translation import ugettext_lazy as _
PROJECT_DIR = os.path.dirname(__file__)
location = lambda x: os.path.join(os.path.dirname(os.path.realpath(__file__)), x)
DEBUG = True
TEMPLATE_DEBUG = True
SQL_DEBUG = True
ADMINS = (
# ('Your Name', 'your_email@domain.com'),
)
EMAIL_BACKEND = 'd... | romotions.context_processors.promotions',
'oscar.apps.checkout.context_processors.checkout',
'oscar.core.context_processors.metadata',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddle... | dleware.FlatpageFallbackMiddleware',
'debug_toolbar.middleware.DebugToolbarMiddleware',
'oscar.apps.basket.middleware.BasketMiddleware',
)
INTERNAL_IPS = ('127.0.0.1',)
ROOT_URLCONF = 'urls'
from oscar import OSCAR_MAIN_TEMPLATE_DIR
from accounts import TEMPLATE_DIR as ACCOUNTS_TEMPLATE_DIR
TEMPLATE_DIRS = (... |
sjsrey/pysal | pysal/explore/__init__.py | Python | bsd-3-clause | 96 | 0 | import esda
import giddy
import inequality
import pointpats
import spaghe | tti
import segrega | tion
|
garyjyao1/ansible | lib/ansible/modules/extras/cloud/cloudstack/cs_staticnat.py | Python | gpl-3.0 | 9,096 | 0.003629 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# (c) 2015, René Moser <mail@renemoser.net>
#
# 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 Lice... | args['ipaddressid'] = ip_address['id']
args['vmguestip'] = self.get_vm_guest_ip()
# make an alias, so we | can use _has_changed()
ip_address['vmguestip'] = ip_address['vmipaddress']
if self._has_changed(args, ip_address):
self.result['changed'] = True
if not self.module.check_mode:
res = self.cs.disableStaticNat(ipaddressid=ip_address['id'])
if 'errort... |
kcrandall/Kaggle_Mercedes_Manufacturing | spark/experiements/reza/random_forest.py | Python | mit | 5,051 | 0.018214 | # imports
import h2o
import numpy as np
import pandas as pd
from h2o.estimators.gbm import H2OGradientBoostingEstimator
from h2o.estimators.random_forest import H2ORandomForestEstimator
from h2o.grid.grid_search import H2OGridSearch
import sys
from operator import add
from pyspark import SparkContext
from pyspark.sql... | ckedEnsembleEstimator
import xgboost as xgb
import matplotlib
matplotlib.use('Agg') #Need this if running matplot on a server w/o display
from pysparkling import *
#Define your s3 bucket to load an | d store data
S3_BUCKET = 'rza-ml-1'
#Create a custom logger to log statistics and plots
logger = LoggingController()
logger.s3_bucket = S3_BUCKET
#.config('spark.executor.cores','6') \
spark = SparkSession.builder \
.appName("App") \
.getOrCreate()
# .master("local[*]") \
# .config('sp... |
whummer/moto | moto/ec2/responses/instances.py | Python | apache-2.0 | 30,036 | 0.001265 | from __future__ import unicode_literals
from boto.ec2.instancetype import InstanceType
from moto.autoscaling import autoscaling_backends
from moto.core.responses import BaseResponse
from moto.core.utils import camelcase_to_underscores
from moto.ec2.utils import filters_from_querystring, \
dict_from_querystring
c... | self.ec2_backend.all_instances()
else:
instances = self.ec2_backend.all_running_instances()
template = self.response_template(EC2_INSTANCE_STATUS)
return template.render(instances=instances)
def describe_instance_types(self):
| instance_types = [InstanceType(
name='t1.micro', cores=1, memory=644874240, disk=0)]
template = self.response_template(EC2_DESCRIBE_INSTANCE_TYPES)
return template.render(instance_types=instance_types)
def describe_instance_attribute(self):
# TODO this and modify below sh... |
csirtgadgets/csirtg-smrt-py | test/stix/test_stix.py | Python | mpl-2.0 | 1,012 | 0.001976 | import pytest
from csirtg_smrt import Smrt
from csirtg_smrt.rule import Rule
from csirtg_smrt.constants import REMOTE_ADDR
from pprint import pprint
import os
DISABLE_TESTS = True
if os.environ.get('CSIRTG_SMRT_STIX_TEST'):
if os.environ['CSIRTG_SMRT_STIX_TEST'] == '1':
DISABLE_TESTS = False
if not DISAB... | ImportError:
raise ImportError('STIX not installed by default, install using `pip install stix`')
rule = 'test/stix/test.yml'
rule = Rule(path=rule)
s = Smrt(REMOTE_ADDR, 1234, client='dummy')
@pytest.mark.skipif(DISABLE_TESTS, reason='need to set CSIRTG_SMRT_STIX_TEST=1 to run')
def test_stix():
x = s.... | ert 'http://efax.pfdregistry.org/efax/37486.zip' not in indicators
assert 'www.cderlearn.com' in indicators
|
happyleavesaoc/home-assistant | homeassistant/components/switch/litejet.py | Python | apache-2.0 | 2,283 | 0 | """
Support for LiteJet switch.
For more de | tails about this platform, please refer to the documentation at
https://home-assistant.io/components/switch.litejet/
"""
import logging
import homeassistant.components.litejet | as litejet
from homeassistant.components.switch import SwitchDevice
DEPENDENCIES = ['litejet']
ATTR_NUMBER = 'number'
_LOGGER = logging.getLogger(__name__)
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Set up the LiteJet switch platform."""
litejet_ = hass.data['litejet_system']
... |
sgarrad/hicks | hicks/hicks_language/models.py | Python | gpl-3.0 | 720 | 0.001389 | from django.db import models
from django.utils. | encoding import python_2_unicode_compatible
@python_2_unicode_compatible
class Language(models.Model):
code = models.CharField(max_length=50,
null=False,
unique=True,
verbose_name='Code',
help_text='htt... | cles/language-tags')
display_name = models.CharField(max_length=255,
null=False,
verbose_name='Display Name')
class Meta:
ordering = ['code']
def __str__(self):
return u"{0} - {1}".format(self.display_name, self.code)
|
f41c0r/Cipher-Frequency-Analyzer | translator.py | Python | gpl-3.0 | 717 | 0.07113 | #!/usr/bin/env python2
import sys
myFile = open(sys.argv[1],"r")
myFile2 = open("output.txt","w")
nl = ''
ciphertext = myFile.read()
freqDict = {
"A" :"t",
"O" :"h",
"U" :"d",
"B" :"e",
"V" :"a",
"M" :"n",
"X" :"o",
"P" :"i",
"N" :"g",
"F... |
"T" :"u",
"I" :"m",
"Q" :"f",
"S" :"l",
"L" :"b",
"R" :"w",
"H" :"y",
"Z" :"c",
"Y" :"k",
"G" :"v",
"K" :"j",
"D" :"q",
"C" :"p"
}
for letter in ciphertext:
if letter in freqDict:
letter = freqDi... | t[letter]
myFile2.write(letter)
myFile.close()
|
leleobhz/phonetica | high_experimental/mvuorine/correl.py | Python | gpl-2.0 | 3,929 | 0.030033 | #!/usr/bin/python
# -*- coding: utf-8 -*-
from four1 import four1
from math import sin
def correl(data1, data2, n):
ans=(2*n+1)*[0.0]
correl_r(data1[:], data2[:], n, ans)
return ans
# Computes the correlation of two real data sets data1[1..n] and data2[1..n]
# (including any user-specified zero-padding). n MUST b... | input arrays data1[0..n-1] and data2[0..n-1], | this routine calls
# four1 and returns a tuple of complex output arrays, fft1[0..n-1] and fft2[0..n-1],
# each of complex length n, which contains the discrete
# Fourier transforms of the respective data arrays.
def twofft(data1, data2, fft1, fft2, n):
nn2 = n + n + 2
nn3 = nn2 + 1
for j in range(1, n+1):
... |
ghchinoy/tensorflow | tensorflow/contrib/eager/python/examples/densenet/densenet_test.py | Python | apache-2.0 | 12,967 | 0.006401 | # 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... | e,) + shape
num_classes = 1000
images = tf.random_uniform(shape)
labels = tf.random_uniform(
[batch_size], minval=0, maxval=num_classes, dtype=tf.int32)
one_hot = tf.one_hot(labels, num_classes)
return images, one_hot
class MockIterator(object):
def __init__(self, tensors):
self._tensors = [t... | k(tf.test.Benchmark):
def __init__(self):
self.depth = 121
self.growth_rate = 32
self.num_blocks = 4
self.output_classes = 1000
self.num_layers_in_each_block = [6, 12, 24, 16]
def _train_batch_sizes(self):
"""Choose batch sizes based on GPU capability."""
for device in device_lib.list_... |
tvieira/did | did/plugins/bugzilla.py | Python | gpl-2.0 | 16,426 | 0 | # coding: utf-8
"""
Bugzilla stats such as verified, filed or fixed bugs
This plugin uses ``python-bugzilla`` module to gather the stats.
Use the ``bugzilla login`` command to initialize Bugzilla cookies
which then will be used for authentication. Reports will contain
only publicly available issues if cookies are not... | bje | ct):
""" Bugzilla investigator """
def __init__(self, parent):
""" Initialize url """
self.parent = parent
self._server = None
@property
def server(self):
""" Connection to the server """
if self._server is None:
self._server = bugzilla.Bugzilla(url=... |
srmagura/potential | solver.py | Python | gpl-3.0 | 4,466 | 0.000896 | import itertools as it
import numpy as np
from domain_util import cart_to_polar
from extend import SolverExtend
class Result:
u_act = None
a_error = None
class Solver(SolverExtend):
"""
A generic solver for a difference potentials problem.
The functionality in this class is expected to apply t... | t the rectangular coordinates of grid point (i,j)
"""
x = self.AD_len * (i / self.N - 1/2)
y = self.AD_len * (j / self.N - 1/2)
return x, y
def get_coord_inv(self, x, y):
"""
Inverse of get_coord(). For testing purposes.
"""
i = self.N * (x / self.AD_... | i, j):
"""
Get the polar coordinates of grid point (i,j)
"""
x, y = self.get_coord(i, j)
return cart_to_polar(x, y)
def construct_grids(self, scheme_order):
"""
Construct the various grids used in the algorithm.
"""
self.N0 = set(it.product(ra... |
grpc/grpc | src/python/grpcio_admin/grpc_version.py | Python | apache-2.0 | 703 | 0.001422 | # Copyright 2021 The gRPC Authors
#
# Licensed under the Apache License, Version 2. | 0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to i | n 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.
# AUTO-GENERATED FROM `$REPO_ROOT/templates/src/pytho... |
openstack/python-neutronclient | neutronclient/tests/unit/lb/test_cli20_healthmonitor.py | Python | apache-2.0 | 8,574 | 0 | # Copyright 2013 Mirantis Inc.
# All Rights Reserved
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by ... | '200-202,204'
http_method = 'HEAD'
max_retries = '2'
timeout = '10'
type = 'TCP'
tenant_id = 'my-tenant'
url_path = '/health'
my_id = 'my-id'
args = ['--admin-state-down',
'--delay', delay,
| '--expected-codes', expected_codes,
'--http-method', http_method,
'--max-retries', max_retries,
'--timeout', timeout,
'--type', type,
'--tenant-id', tenant_id,
'--url-path', url_path]
position_names = ['admin_s... |
on-three/weeabot | weeabot/info.py | Python | mit | 2,639 | 0.009473 | # vim: set ts=2 expandtab:
# -*- coding: utf-8 -*-
"""
Module: info.py
Desc: print current stream info
Author: on_three
Email: on.three.email@gmail.com
DATE: Sat, Oct 4th 2014
This could become very elaborate, showing stream status (up/down)
and number of viewers, etc, but at present i'm just going to
display... | ?P<command>\.status)$'
STATUS_REGEX = re.compile(STATUS_REGEX_STR, re.UNICODE)
class Info(object):
'''
Display some stream data
'''
def __init__(self, parent):
'''
constructor
'''
self._parent = parent
def is_msg_of_interest(self, us | er, channel, msg):
'''
PLUGIN API REQUIRED
Is the rx'd irc message of interest to this plugin?
'''
m = re.match(COMMAND_REGEX, msg) or re.match(STATUS_REGEX, msg)
if m:
return True
else:
return False
def handle_msg(self, user, channel, msg):
'''
PLUGIN API REQUIRED
... |
anilgulecha/trelby | setup.py | Python | gpl-2.0 | 415 | 0.009639 | # se | tup.py
from distutils.core import setup
import py2exe
includes = [
"encodings",
"encodings.*",
"lxml._elementpath"
]
options = {
"py2exe": {
"compressed": 1,
"optimize": 2,
"includes": includes,
}
}
target = { "script" : "trelby.py",
"icon_resources": [(1, "icon... | e="library.zip", windows=[target])
|
masahir0y/buildroot-yamada | support/testing/tests/package/sample_python_cbor_dec.py | Python | gpl-2.0 | 281 | 0 | import cbor
with open("/tmp/data.cbor", "rb") as f:
serialized = f.read()
data = cbor.loads(serialized)
print(data)
assert(data["name"] == "py | thon-c | bor")
assert(data["versions"] == ["1", "2"])
assert(data["group"]["is_a_package"] is True)
assert(data["group"]["value"] == 42)
|
wrbutros/condominios | geoname/migrations/0001_initial.py | Python | gpl-3.0 | 1,067 | 0.002812 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.5 on 2016-04-27 02:19
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migra | tions.CreateModel(
name='Ciudad',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('nombre', models.CharField(max_length=50)),
],
options={
'verbose_name_plural': '... | ame='Comuna',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('nombre', models.CharField(max_length=50)),
('ciudad', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='geoname.Ciudad'... |
dadisigursveinn/VEF-Lokaverkefni | myphotos/admin.py | Python | bsd-3-clause | 118 | 0.016949 | from djang | o.contrib import admin
# Register your models here.
from .models import Photos
admin.site.register(Pho | tos) |
f5devcentral/f5-cccl | f5_cccl/resource/ltm/profile/test/test_profile.py | Python | apache-2.0 | 1,931 | 0.001036 | #!/usr/bin/env python
# Copyright (c) 2017-2021 F5 Networks, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appl... | le
# verify all cfg items
for k,v in list(cfg_test.items()):
assert profile.data[k] == v
def test_eq():
"""Test Profile equality."""
pa | rtition = 'Common'
name = 'tcp'
profile1 = Profile(
**cfg_test
)
profile2 = Profile(
**cfg_test
)
assert profile1
assert profile2
assert id(profile1) != id(profile2)
assert profile1 == profile2
# not equal
profile2.data['context'] = 'serverside'
assert p... |
natduca/py_trace_event | trace_event_impl/trace_test.py | Python | bsd-3-clause | 1,133 | 0.009709 | # Copyright 2011 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import tempfile
import unittest
from .log import *
from .parsed_trace_events import *
class TraceTest(unittest.TestCase):
def __init__(self, *args):
... | enable(open(self._file.name, 'a+'))
try:
cb()
finally:
trace_disable()
e = ParsedTraceEvents(trace_filename = self._file.name)
self._file.close()
self._file = None
return e
@property
def trace_filename(self):
return self._file.name
def tearDown(self):
if trace_i | s_enabled():
trace_disable()
if self._file:
self._file.close()
|
tazo90/lux | lux/extensions/odm/query.py | Python | bsd-3-clause | 4,708 | 0 |
class QueryMixin:
"""The default query object used for models, and exposed as
:attr:`~SQLAlchemy.Query`. This can be subclassed and
replaced for individual models by setting the :attr:`~Model.query_class`
attribute. This is a subclass of a standard SQLAlchemy
:class:`~sqlalchemy.orm.query.Query` c... | l, items)
class Pagination(object):
"""Internal helper class returned by :meth:`BaseQuery.paginate`. You
can also construct it from any other SQLAlchemy query object if you are
working with other libraries. Additionally it is possible to pass `None`
as query object in which case the :meth:`prev` and... | ge, total, items):
#: the unlimited query object that was used to create this
#: pagination object.
self.query = query
#: the current page number (1 indexed)
self.page = page
#: the number of items to be displayed on a page.
self.per_page = per_page
#: the... |
gaqzi/flake8 | flake8/mccabe.py | Python | mit | 8,485 | 0.000118 | """ Meager code path measurement tool.
Ned Batchelder
http://nedbatchelder.com/blog/200803/python_code_complexity_microtool.html
MIT License.
"""
try:
from compiler import parse # NOQA
iter_child_nodes = None # NOQA
except ImportError:
from ast import parse, iter_child_nodes # N... | lf.classname
self.classname += node.name + "."
self.default(node)
self.classname = old_classname
def appendPathNode(self, name):
if not self.tail:
return
pathnode = PathNode(name)
self.graph.connect(self.tail, pathnode)
self.tail = pathnode
... | else:
lineno = node.lineno
name = "Stmt %d" % lineno
self.appendPathNode(name)
visitAssert = visitAssign = visitAssTuple = visitPrint = \
visitPrintnl = visitRaise = visitSubscript = visitDecorators = \
visitPass = visitDiscard = visitGlobal = visitReturn = \
... |
ychen820/microblog | y/google-cloud-sdk/platform/google_appengine/google/appengine/ext/mapreduce/operation/counters.py | Python | bsd-3-clause | 1,239 | 0.00565 | #!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... | class Increment(base.Operation):
"""Increment counter operation."""
def __init__(self, counter_name, delta=1):
"""Constructor.
Args:
counter_name: name of the counter as string
delta: increment delta as int.
"""
self.counter_name = counter_name
self.delta = delta
def __call__(se... | xt._counters.increment(self.counter_name, self.delta)
|
mrphlip/lrrbot | common/__init__.py | Python | apache-2.0 | 179 | 0 | # scripts | can set this to True before lrrbot.main is imported, if they want to
# be able | to call utility functions without actually creating the bot object
FRAMEWORK_ONLY = False
|
InfluxGraph/influxgraph | tests/test_c_node_tree.py | Python | apache-2.0 | 7,573 | 0.000396 | import sys
import unittest
from string import ascii_letters
from random import randint, choice
import logging
from influxgraph.templates import parse_influxdb_graphite_templates
from influxgraph.utils import parse_series as parse_py_series
try:
from influxgraph.ext.nodetrie import Node
from influxgraph.ext.tem... | e_series(self):
all_series = [u'b1.b1.b1.b1.leaf1',
u'b1.b1.b1.b2.leaf1',
u'b1.b1.b2.b2.leaf1',
u'b1.b1.b1.b1.leaf2',
u'b1.b1.b1.b2.leaf2',
u'b1.b1.b2.b2.leaf2'
]
i | ndex = parse_series(all_series, None, None)
result = list(index.query(u'*'))
self.assertTrue(len(result) > 0)
self.assertEqual(result[0][0], 'b1')
result = list(index.query('b1'))
self.assertTrue(result[0][0] == 'b1')
result = list(index.query('b1.*'))
self.assert... |
edisonlz/fruit | web_project/base/site-packages/bitfield/types.py | Python | apache-2.0 | 6,530 | 0.000766 | from six import string_types
class Bit(object):
"""
Represents a single Bit.
"""
def __init__(self, number, is_set=True):
self.number = number
self.is_set = bool(is_set)
self.mask = 2 ** int(number)
self.children = []
if not self.is_set:
self.mask = ... | _get_mask(self):
return self._value
mask = property(_get_mask)
def evaluate(self, evaluator, qn, connection):
return self.mask, []
def get_bit(self, bit_number):
mask = 2 ** int(bit_number)
return Bit(bit_number, self._value & mask != 0)
def set_bit(self, bit_number, ... | self._value |= mask
else:
self._value &= (~mask)
return Bit(bit_number, self._value & mask != 0)
def keys(self):
return self._keys
def iterkeys(self):
return iter(self._keys)
def items(self):
return list(self.iteritems())
def iteritems(self):
... |
stg7/papyrus | loader.py | Python | gpl-3.0 | 464 | 0.00432 | #!/usr/bin/env python3
"""
Loader
import modules from zip files that are stored in ./libs/ directory
author: Steve Göring
contact: stg7@gmx.de
2014
"""
import os
import sys
for m in filter(lambda x: ".zip" in x, os.listdir(os.path.dirname(os.path.realpath(__file__) | ) + "/libs")):
sys.path.insert(0, os.path.dirname(os.path.realpath(__file__)) + "/libs/" + m)
s | ys.path.insert(0, os.path.dirname(os.path.realpath(__file__)) + "/libs/")
|
Bugheist/website | comments/models.py | Python | agpl-3.0 | 679 | 0.001473 |
from django.contrib.auth.models import User
from django.db import models
from django.utils import timezone
from website.models import Issue
# Create your models here.
class Comment(models.Model):
parent = models.ForeignKey('self', null=True, on_delete=models.CASCADE)
issue = models.ForeignKey(Issue, on_de... | omments')
author = models.CharField(max_length=200)
author_url = models.CharField(max_length=200)
text = models.TextField()
created_date = mo | dels.DateTimeField(default=timezone.now)
def __str__(self):
return self.text
def children(self):
return Comment.objects.filter(parent=self)
|
fweik/espresso | testsuite/python/lb_electrohydrodynamics.py | Python | gpl-3.0 | 2,426 | 0 | # Copyright (C) 2010-2019 The ESPResSo project
#
# This file is part of ESPResSo.
#
# ESPResSo 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 v... | spressomd
import unittest as ut
import unittest_decorators as utx
import numpy as np
@utx.skipIfMissingFeatures(["LB_ELECTROHYDRODYNAMICS"])
class LBEHTest(ut.TestCase):
from espressomd import lb
s = espressomd.System(box_l=[6.0, 6.0, 6.0])
def setUp(self):
self.params = {'time_step': 0.01,
... | ': 0.02,
'agrid': 0.5,
'dens': 0.85,
'viscosity': 30.0,
'friction': 3.0,
'temp': 0.0,
'skin': 0.2,
'muE': [0.1, 0.2, 0.3]}
self.s.periodicity = [1, 1,... |
sonali0901/zulip | zerver/lib/test_runner.py | Python | apache-2.0 | 8,664 | 0.003232 | from __future__ import print_function
from typing import Any, Callable, Iterable, List, Optional, Set, Tuple
from django.test import TestCase
from django.test.runner import DiscoverRunner
from django.test.signals import template_rendered
from unittest import loader # type: ignore # Mypy cannot pick this up.
from z... | e)
def get_shallow_tested_templates(self):
# type: () -> Set[str]
return self.shallow_tested_templates
def run_tests(self, test_labels, extra_tests=None,
full_suite=False, **kwargs):
# type: (List[str], Optional[List[TestCase]], bool, **Any) -> bool
self.setup... | d_suite(test_labels, extra_tests)
except AttributeError:
traceback.print_exc()
print()
print(" This is often caused by a test module/class/function that doesn't exist or ")
print(" import properly. You can usually debug in a `manage.py shell` via e.g. ")
... |
David-Amaro/odoo-brazil-banking | l10n_br_account_payment_boleto/models/__init__.py | Python | gpl-3.0 | 1,146 | 0 | # -*- encoding: utf-8 -*-
##############################################################################
#
# Account Payment Boleto module for Odoo
# Copyright (C) 2012 | -2015 KMEE (http://www.kmee.com.br)
# @author Luis Feli | pe Miléo <mileo@kmee.com.br>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is... |
sofian/qualia | examples/makefiletests/avr_gxx.py | Python | gpl-3.0 | 4,490 | 0.037416 | #!/usr/bin/env python
# encoding: utf-8
# Thomas Nagy, 2006-2010 (ita)
# Ralf Habacker, 2006 (rh)
# Yinon Ehrlich, 2009
"""
g++/llvm detection.
"""
import os, sys
from waflib import Configure, Options, Utils
from waflib.Tools import ccroot, ar
from waflib.Configure import conf
@conf
def find_avr_gxx(conf):
"""
Fin... | ib%s.a'
# osx stuff
v['LINKFLAGS_MACBUNDLE'] = ['-bundle', '-undefined', 'dynamic_lookup']
v['CXXFLAGS_MACBUNDLE'] = ['-fPIC | ']
v['macbundle_PATTERN'] = '%s.bundle'
@conf
def avr_gxx_modifier_win32(conf):
"""Configuration flags for executing gcc on Windows"""
v = conf.env
v['cxxprogram_PATTERN'] = '%s.exe'
v['cxxshlib_PATTERN'] = '%s.dll'
v['implib_PATTERN'] = 'lib%s.dll.a'
v['IMPLIB_ST'] = '-Wl,--out-implib,%s'... |
Patola/Cura | plugins/UM3NetworkPrinting/src/Cloud/Models/CloudClusterPrinterConfigurationMaterial.py | Python | lgpl-3.0 | 3,000 | 0.01 | from typing import Optional
from UM.Logger import Logger
from cura.CuraApplication import CuraApplication
from cura.PrinterOutput.Models.MaterialOutputModel import MaterialOutputModel
from .BaseCloudModel import BaseCloudModel
## Class representing a cloud cluster printer configuration
# Spec: https://api-staging.... | l_group_list = list(filter(lambda x: x.is_read_only, material_group_list))
non_read_only_material_group_list = list(filter(lambda x: not x.is_read_only, material_group_list))
material_group = None
if read_only_material_group_list:
read_only_material_group_list = sorted(read_only_mate... | ]
elif non_read_only_material_group_list:
non_read_only_material_group_list = sorted(non_read_only_material_group_list, key = lambda x: x.name)
material_group = non_read_only_material_group_list[0]
if material_group:
container = material_group.root_material_node.getC... |
alon/polinax | projects/polinax/apps/groups/views.py | Python | gpl-2.0 | 1,679 | 0.004765 | from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from django.http import HttpResponseRedirect, Http404
from django.contrib.auth.decorators import login_required
from groups.models import Group, Membership
from groups.forms import AwayForm
def members(request... |
if away_form is None:
away_form = form_class()
active_members = group_members.filter(away=False)
away_members = group_members.filter(a | way=True).order_by('away_since')
return render_to_response(template_name, {
"group": group,
"is_member": is_member,
"group_member": group_member,
"away_form": away_form,
"active_members": active_members,
"away_members": away_members,
}, context_instance=Reque... |
mattbasta/perfalator | tests/test_submain_package.py | Python | bsd-3-clause | 1,268 | 0 | from mock import patch
from nose.tools import eq_
from helper import TestCase
import appvalidator.submain as submain
class TestSubmainPackage(TestCase):
@patch("appvalidator.submain.test_inner_package",
lambda x, z: "success")
def test_package_pass(self):
"Tests the test_package function ... | test_package function fails with a corrupt file"
self.setup_err()
name = "tests/resources/corrupt.xpi"
result = submain.test_package(self.err, name, name)
self.assert_failed(with_errors=True, wi | th_warnings=True)
|
gena701/Seleniun_php4dvd_lesson2_Rovinsky | php4dvd/php4dvd_negative.py | Python | apache-2.0 | 2,371 | 0.005061 | # -*- coding: utf-8 -*-
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import NoAlertPresentException... | or("img[alt=\"Own\"]").click()
def is_element_present(self, how, what):
try: self.driver.find_element(by=how, value=what)
except NoSuchElementException as e: return False
return True
def is_alert_present(self):
try: self.driver.switch_to_alert()
except NoAlertPresentExc... |
alert = self.driver.switch_to_alert()
alert_text = alert.text
if self.accept_next_alert:
alert.accept()
else:
alert.dismiss()
return alert_text
finally: self.accept_next_alert = True
def tearDown(self):
sel... |
twc-openstack/jenkins-job-builder | jenkins_jobs/modules/notifications.py | Python | apache-2.0 | 3,900 | 0 | # Copyright 2012 Hewlett-Packard Development Company, L.P.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law... | 'Endpoint')
supported_formats = ['JSON', 'XML']
format = data.get('format', 'JSON').upper()
if format not in supported_formats:
raise JenkinsJobsException(
"format must be one of %s" %
", ".join(supported_formats))
else:
XML.Sub... | int_element, 'format').text = format
XML.SubElement(endpoint_element, 'protocol').text = 'HTTP'
supported_events = ['started', 'completed', 'finalized', 'all']
event = data.get('event', 'all').lower()
if event not in supported_events:
raise JenkinsJobsException(
"event must be one ... |
JJscott/single_header_math | scripts/vecops.py | Python | mit | 2,770 | 0.025632 |
assign_ops = [
('+=', 'add_assign', None),
('-=', 'sub_assign', None),
('*=', 'mul_assign', None),
('/=', 'div_assign', None),
('%=', 'mod_assign', 'remainder (mod) assign'),
('<<=', 'lshift_assign', None),
('>>=', 'rshift_assign', None),
('|=', 'bitwise_or_assign', None),
('^=', 'bitwise_xor_assign', None),
... | _t<VecT1, VecT2> = 0>
inline VecT1 & operator{op}(VecT1 &lhs, const VecT2 &rhs) {{
zip_with(detail::op::{func}(), lhs, rhs);
return lhs;
}}
// vec {comment} scalar
template <typename VecT, typename T, enable_if_vector_scalar_compatible_t<VecT, T> = 0>
inline VecT & operator{op}(VecT &lhs, const T &rhs) {{
zip_with(... | hs, repeat_vec<T, array_size<VecT>::value>(rhs));
return lhs;
}}
'''
unary_op_str= '''// vec {comment}
template <typename VecT, enable_if_vector_t<VecT> = 0>
inline auto operator{op}(const VecT &rhs) {{
return zip_with(detail::op::{func}(), rhs);
}}
'''
binary_op_str = '''// vec {comment}
template <typename VecT1, ... |
Valuehorizon/valuehorizon-people | people/settings/sphinx_documentation.py | Python | mit | 66 | 0 | SECRET_KEY = 't_piw=&emz%!%*l504d | vqor1iy1eu+nss&_^i&!@i@_32qrt | l+'
|
MaxTyutyunnikov/lino | obsolete/ui_old/qx/qx_store.py | Python | gpl-3.0 | 18,650 | 0.023378 | ## Copyright 2009-2011 Luc Saffre
## This file is part of the Lino project.
## Lino 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.... | cket/15497 is open
self.parse_form_value = delegate.parse_form_value
#~ def parse_form_value(self,v):
#~ return self.field.parse_form_value( | v)
def obj2list(self,request,obj |
mgp/sharebears | sharebears/url_decoder_twitter.py | Python | apache-2.0 | 1,894 | 0.019535 | import re
from url_decoder import UrlDecoder
class _TwitterUrlDecoder(UrlDecoder):
@staticmethod
def can_decode_url(url, parsed_url):
if not pars | ed_url.netloc.startswith("twitter."):
return False
return True
class TwitterTimelineItem:
"""A Twitter timeline for a RenderableItem."""
def __init__(self, decoded_url):
self.url = decoded_url["url"]
class TwitterTimelineUrlDecoder(_TwitterUrlDecoder):
"""Embeds the timeline of a Twitter user.... | parsed_url):
if not _TwitterUrlDecoder.can_decode_url(url, parsed_url):
return False
elif not TwitterTimelineUrlDecoder._PATH_REGEX.match(parsed_url.path):
return False
return True
def decode_url(self, url, parsed_url):
# Use an embedded timeline.
# See https://dev.twitter.com/web/em... |
level12/keg-bouncer | keg_bouncer_test_app/app.py | Python | bsd-3-clause | 790 | 0.001266 | from __future__ import absolute_import
from flask_login im | port LoginManager
from keg.app import Keg
from .model import entities as ents
from .views import blueprint
|
class KegBouncerTestApp(Keg):
import_name = 'keg_bouncer_test_app'
db_enabled = True
use_blueprints = [blueprint]
keyring_enable = False
def init(self, *args, **kwargs):
super(KegBouncerTestApp, self).init(*args, **kwargs)
self.login_manager = LoginManager()
self.login_man... |
quaddra/engage-utils | setup.py | Python | apache-2.0 | 547 | 0.003656 | from setuptools import setup, find_packages
setup(
name='engage_utils',
version='1.0',
author='genForma Corporation',
author_email='code@genforma.com',
url='https://github.com/genforma/engage-utils',
packages=find_packages(),
include_package_data=True,
zip_safe=False,
entry_points =... | ]},
install_requires=[],
license='Apache V2.0',
d | escription='common utilities for Engage and Datablox',
long_description='common utilities for Engage and Datablox'
)
|
FCP-INDI/C-PAC | CPAC/utils/docs.py | Python | bsd-3-clause | 503 | 0 | """Utilties for documentation."""
def docstring_parameter(*args, **kwargs):
"""Decorator to parameterize docstrings.
Examples
--------
| >>> @docstring_parameter('test', answer='Yes it does.')
... def do_nothing():
... '''Does this {} do anything? {answer}'''
... pass
>>> print(do_noth | ing.__doc__)
Does this test do anything? Yes it does.
"""
def dec(obj):
obj.__doc__ = obj.__doc__.format(*args, **kwargs)
return obj
return dec
|
jumpstarter-io/neutron | neutron/agent/securitygroups_rpc.py | Python | apache-2.0 | 15,480 | 0.000258 | # Copyright 2012, Nachi Ueno, NTT MCL, Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unles... | ces = devices_info['devices']
security_groups = devices_info['security_groups']
security_group_member_ips = devices_info['sg_member_ips']
else:
devices = self.plugin_rpc.security_group_rules_for_devices(
self.context, list(device_ids))
with self.firew... | rpc:
LOG.debug("Update security |
wh-acmer/minixalpha-acm | LeetCode/Python/convert_sorted_array_to_binary_search_tree.py | Python | mit | 583 | 0.008576 | #!/usr/bin/env python
#coding: utf-8
## Definition for a bina | ry tree node
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# @param num, a list of integers
# @return a tree node
def sortedArrayToBST(self, num):
if not num: return None
ln = len(num)
if ln | == 1: return TreeNode(num[0])
m = ln / 2
root = TreeNode(num[m])
root.left = self.sortedArrayToBST(num[:m])
root.right = self.sortedArrayToBST(num[m+1:])
return root
|
jakehaas/p2pool-dash | p2pool/networks.py | Python | gpl-3.0 | 2,185 | 0.006865 | from p2pool.dash import networks
from p2pool.util import math
# CHAIN_LENGTH = number of shares back client keeps
# REAL_CHAIN_LENGTH = maximum number of shares back client uses to compute payout
# REAL_CHAIN_LENGTH must always be <= CHAIN_LENGTH
# REAL_CHAIN_LENGTH must be changed in sync with all other clients
# cha... | 'dash'],
SHARE_PERIOD=20, # seconds
CHAIN_LENGTH=24*60*60//20, # shares
REAL_CHAIN_LENGTH=24*60*60//20, # shares
TARGET_LOOKBEHIND=100, # shares //with that the pools sha | re diff is adjusting faster, important if huge hashing power comes to the pool
SPREAD=10, # blocks
IDENTIFIER='7242ef345e1bed6b'.decode('hex'),
PREFIX='3b3e1286f446b891'.decode('hex'),
COINBASEEXT='0D2F5032506F6F6C2D444153482F'.decode('hex'),
P2P_PORT=8999,
MIN_TARGET=0,
... |
steveandroulakis/mytardis | tardis/tardis_portal/managers.py | Python | bsd-3-clause | 12,213 | 0.002948 | """
managers.py
.. moduleauthor:: Ulrich Felzmann <ulrich.felzmann@versi.edu.au>
"""
from datetime import datetime
from django.db import models
from django.db.models import Q
from django.core.exceptions import PermissionDenied
from django.contrib.auth.models import User, Group
from tardis.tardis_portal.auth.local... | d
if not request.user.is_authenticated():
return super(Experime | ntManager, self).get_empty_query_set()
return self.owned_by_user_id(request.user.id)
def owned_by_user_id(self, userId):
"""
Return all experiments which are owned by a particular user id
:param userId: a User ID
:type userId: integer
"""
# build the query... |
erix5son/Tennis-Modelling | setup.py | Python | mit | 1,109 | 0.011722 | '''
Setup.py script.
'''
__author__ = 'riko'
from Cython.Build import cythonize
import numpy
from setuptools import setup, Extension, find_packages
try:
use_cython = True
from Cython.Distutils import build_ext
except ImportError:
use_cython = False
ext = '.pyx' if use_cython else '.c'
ext_modules = [... | t': build_ext })
print ext_modules
setup(name='TennisModelling',
version='1.0',
description='Tennis modelling tool.',
author='Erik Grabljevec',
author_email='erikgrabljevec5@gmail.com',
url='https://github.com/erix5son/TennisModelling',
packages=['data_tools', 'models', 'ranking_sy... |
ext_modules=ext_modules,
include_dirs=[include_dirs, numpy.get_include()]
) |
Cancercoin/Cancercoin | contrib/wallettools/walletchangepass.py | Python | mit | 220 | 0 | f | rom jsonrpc import ServiceProxy
access = ServiceProxy("http://127.0.0.1:9666")
pwd = raw_input("Enter old wallet passphrase: ")
pwd2 = raw_input("Enter new wallet passphrase: ")
access.walletpassphrasechange | (pwd, pwd2)
|
js850/pele | pele/potentials/tests/_base_test.py | Python | gpl-3.0 | 1,834 | 0.022901 | import numpy as np
import unittest
import logging
class _BaseTest(unittest.TestCase):
# def energy_test(self, x, e):
# e = self.pot.getEnergy(x)
# print e
# self.assertAlmostEqual(e, self.target_E, 4)
def grad_t(self, x):
log= logging.getLogger( "BaseTest.grad_t" )
... | "BaseTest.test_gra_min" )
e, g = self.pot.getEnergyGradient(self.xmin)
log.debug( "e= %r", e )
log.debug( "g= %r", g)
self.assertAlmostEqual(e, self.Emin, 4)
self.assertLess(np.max(np.abs(g)), 1e-3)
self.grad_t(self.xmin)
def test_hess_min(self):
log= loggin... | ian(self.xmin)
eigenvals = np.linalg.eigvals(h)
log.debug( "e= %r", eigenvals )
self.assertGreater(np.min(eigenvals), -1e-4)
def test_hess_analytical_against_numerical(self):
log= logging.getLogger( "BaseTest.test_hess_analytical_against_numerical" )
h = self.pot.getHess... |
tKroopy/tkroopy | src/modules/table.py | Python | gpl-3.0 | 8,168 | 0.004652 | #-------------------------------------------------------------------------------
# Name: Table
# Purpose: Tabularise data
#
# Author: James Burke
# Created: 8/09/2014
#
# Copyright: (c) James Burke 2014
# Licence: MIT
# Permission is hereby granted, free of charge, to any person obtaining a co... | CTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#-------------------------------------------------------------------------------
im | port Tkinter
from functools import partial
import logging
from contrib.pydal import DAL
format = '%(name)s - %(levelname)s - %(filename)s - %(lineno)d - %(message)s'
logging.basicConfig(format=format, level=logging.NOTSET)
log = logging.getLogger(__package__)
class Table(Tkinter.Frame):
def __init__(self, paren... |
greenoaktree/pfp | pfp/interp.py | Python | mit | 50,954 | 0.037465 | #!/usr/bin/env python
"""
Python format parser
"""
import collections
import copy
import glob
import logging
import os
import re
import six
import sys
import traceback
import py010parser
import py010parser.c_parser
from py010parser import c_ast as AST
import pfp.fields as fields
import pfp.errors as errors
import p... | functions
import pfp.native as native
import pfp.utils as utils
logging.basicConfig(level=logging.CRITICAL)
class Decls(object):
def __init__(self, decls, coord):
self.decls = decls
self.coord = coord
class UnionDecls(Decls): pass
cl | ass StructDecls(Decls): pass
def StructUnionDef(typedef_name, interp, node):
if isinstance(node, AST.Struct):
cls = fields.Struct
decls = StructDecls(node.decls, node.coord)
elif isinstance(node, AST.Union):
cls = fields.Union
decls = UnionDecls(node.decls, node.coord)
def __init__(self, stream=None, metad... |
MTG/dunya | makam/test/test_artist.py | Python | agpl-3.0 | 5,233 | 0.00344 | import uuid
from django.test import TestCase
import data.models
from makam import models
class ArtistTest(TestCase):
fixtures = ["makam_instrument"]
def test_collaborating_artists(self):
a1 = models.Artist.objects.create(name="a1")
a2 = models.Artist.objects.create(name="a2")
a3 = m... | self.rel2.artists.add(self.a2, self.a3)
# artist1 also performs on a rel1 recording, so rel1 won't show
# on accomp recordings
models.InstrumentPerformance.objects.create(recording=rec1, artist=self.a1)
# but also performs on rel2, and will show here
models.InstrumentPerforma... | rformance.objects.create(recording=rec1, artist=self.a4)
def test_main_releases(self):
main_rels = self.a1.main_releases()
self.assertEqual(1, len(main_rels))
main_rels = self.a2.main_releases()
self.assertEqual(2, len(main_rels))
# limit this query to only one collection ... |
k-vinogradov/noclite | reports/models.py | Python | bsd-3-clause | 66 | 0.015152 | # -*- coding: utf-8 -*-
from reports.accidents.models im | port * | |
siketh/ASR | catkin_ws/devel/lib/python2.7/dist-packages/navfn/srv/_MakeNavPlan.py | Python | mit | 20,872 | 0.014373 | """autogenerated by genpy from navfn/MakeNavPlanRequest.msg. Do not edit."""
import sys
python3 = True if sys.hexversion > 0x03000000 else False
import genpy
import struct
import geometry_msgs.msg
import std_msgs.msg
class MakeNavPlanRequest(genpy.Message):
_md5sum = "2fe3126bd5b2d56edd5005220333d4fd"
_type = "na... | coordinate frame and timestamp
Header header
Pose pose
================================================================================
MSG: std_msgs/Header
# Standard metadata for higher-level stamped data t | ypes.
# This is generally used to communicate timestamped data
# in a particular coordinate frame.
#
# sequence ID: consecutively increasing ID
uint32 seq
#Two-integer timestamp that is expressed as:
# * stamp.sec: seconds (stamp_secs) since epoch (in Python the variable is called 'secs')
# * stamp.nsec: nanoseconds... |
frappe/erpnext | erpnext/patches/v13_0/rename_discharge_date_in_ip_record.py | Python | gpl-3.0 | 291 | 0.010309 | impo | rt frappe
from frappe.model.utils.rename_field import rename_field
def execute():
frappe.reload_doc("Healthcare", "doctype", "Inpatient Record")
if frappe.db.has_column("Inpatient Record", "discharge_date"):
rename_field("Inpatient Record", "discharge | _date", "discharge_datetime")
|
moneypark/whydjango | referral_module/tests/test_user_registered.py | Python | mit | 3,083 | 0.002595 | from django.test import TestCase
from django.contrib.auth.models import User
from django.http import HttpRequest
from .factories import UserReferrerFactory, UserFactory, CampaignFactory
from referral_module import constants
from referral_module import models
def make_cookie_file(user_referrer):
cookie_file = '{... | elf.user_referrer.key).reward
reward_afte | r_adding_user = reward_before_new_user + self.user_referrer.campaign.bonus_policy['registration']
self.assertEqual(reward_of_referrer_user, reward_after_adding_user)
def test_unreferred_user_registered(self):
request = HttpRequest()
models.associate_registered_user_with_referral("", user=se... |
amjames/psi4 | psi4/driver/qcdb/molecule.py | Python | lgpl-3.0 | 87,073 | 0.003744 | #
# @BEGIN LICENSE
#
# Psi4: an open-source quantum chemistry software package
#
# Copyright (c) 2007-2018 The Psi4 Developers.
#
# The copyrights for code used from other parties are included in
# the corresponding fil | es.
#
# This file is part of Psi4.
#
# Psi4 is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, version 3.
#
# Psi4 is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without eve... | ore details.
#
# You should have received a copy of the GNU Lesser General Public License along
# with Psi4; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# @END LICENSE
#
from __future__ import absolute_import
from __future__ import print_function... |
tijko/IO-Mon | lib/taskstats/controller.py | Python | mit | 3,616 | 0.010509 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import struct
import socket
from netlink import *
NETLINK_ROUTE = 0
NETLINK_UNUSED = 1
NETLINK_USERSOCK = 2
NETLINK_FIREWALL = 3
NETLINK_SOCK_DIAG = 4
NETLINK_NFLOG = 5
NETLINK_XFRM = 6
NETLINK_SELINUX ... | c netlink connection with
family of the supplied 'genl_name'.
'''
def __init__(self, genl_name):
super(Controller, self).__init__(NETLINK_GENERIC)
self.genl_ | name = genl_name
self.genlhdr = Genlmsg(CTRL_CMD_GETFAMILY, Nlattr(CTRL_ATTR_FAMILY_NAME,
self.genl_name))
self.attrs = dict()
self.pid = os.getpid()
self.fam_id = self.get_family_id
@property
def get_family_id(self... |
OCA/account-analytic | analytic_tag_dimension_enhanced/tests/test_analytic_dimension.py | Python | agpl-3.0 | 7,081 | 0.000847 | # Copyright 2019 Ecosoft Co., Ltd (http://ecosoft.co.th/)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html)
from odoo.exceptions import ValidationError
from odoo | .addons.analytic_tag_dimension.tests.test_analytic_dimension import (
TestAnalyticDimensionBase,
)
class TestAnalyticDimensionCase(TestAnalyticDimensionBase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.account_obj = cls.env["account.account"]
cls.model_obj = cls.env... | ": cls.partner.id}
)
# Mock data for testing model dimension, by_sequence with fitered
vals = {
"name": "A",
"line_ids": [ # use sequence as record identifier
(0, 0, {"value": "percent", "sequence": 1001}),
(0, 0, {"value": "balance", "seq... |
MBARIMike/recipy | recipyGui/views.py | Python | apache-2.0 | 3,208 | 0.003117 | from flask import Blueprint, request, render_template, redirect, url_for, \
escape, make_response
from recipyGui import recipyGui
from .forms import SearchForm, AnnotateRunForm
from tinydb import TinyDB, where
import re
from dateutil.parser import parse
import os
from ast import literal_eval
from json import dumps
... | :
runs = db.all()
else:
# Search run outputs using the query string
runs = db.search(
where('outputs').any(lambda x: | re.match(".+%s.+" % query, x)) |
where('notes').contains(query) |
where('unique_id').contains(query))
runs = sorted(runs, key = lambda x: parse(x['date'].replace('{TinyDate}:', '')) if x['date'] is not None else x['eid'], reverse=True)
run_ids = []
for run in runs:
if 'notes... |
mbuesch/toprammer | libtoprammer/chips/hm62256dip28.py | Python | gpl-2.0 | 1,359 | 0.036056 | """
# TOP2049 Open Source programming suite
#
# HM62256 DIP28 SRAM support
#
# Co | pyright (c) 2011 Michael Buesch <m@bues.ch>
#
# This program is free software; you can redist | ribute 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 in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without ... |
StackStorm/python-mistralclient | mistralclient/tests/unit/v2/test_cli_workbooks.py | Python | apache-2.0 | 3,625 | 0 | # Copyright 2014 - Mirantis, Inc.
# Copyright 2015 - StackStorm, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unl... | elf):
self.call(workbook_cmd.Delete, app_args=['name'])
self.client.workbooks.delete.assert_called_once_with('name')
def test_delete_with_multi_names(self):
self.call(workbook_cmd.Delete, app_args=['name1', 'name2'])
self.assertEqual(2, self.client.workbooks.delete.call_count)
... | efinition(self):
self.client.workbooks.get.return_value = WORKBOOK_WITH_DEF
self.call(workbook_cmd.GetDefinition, app_args=['name'])
self.app.stdout.write.assert_called_with(WB_DEF)
@mock.patch('argparse.open', create=True)
def test_validate(self, mock_open):
self.client.workb... |
lafranceinsoumise/api-django | agir/system_pay/forms.py | Python | agpl-3.0 | 9,006 | 0.001777 | from django import forms
from django.forms import fields
from phonenumbers import phonenumberutil, PhoneNumberType
from agir.lib.utils import front_url_lazy
from agir.system_pay.utils import get_trans_id_from_order_id, get_recurrence_rule
from .crypto import get_signature
class SystempayBaseForm(forms.Form):
for... | rency = fields.IntegerField(widget=forms.HiddenInput())
vads_ext_info_type = fields.CharField(widget=forms.HiddenInput())
vads_page_action = fields.CharField(initial="PAYMENT", widget=forms.HiddenInput())
vads_payment_config = fields.CharField(initial="SINGLE", widget=forms.HiddenInput())
vads_capture_... | ut())
vads_validation_mode = fields.IntegerField(initial=0, widget=forms.HiddenInput())
@classmethod
def get_form_for_transaction(cls, transaction, sp_config):
person_id = (
str(transaction.payment.person.pk)
if transaction.payment.person
else "anonymous"
... |
FluidityStokes/fluidity | tests/Stokes_square_convection_1e4_p2p1/src/generate_mesh.py | Python | lgpl-2.1 | 386 | 0.002591 | #!/usr/bin/env pyth | on3
import fluidity.diagnostics.annulus_mesh as annulus_mesh
import fluidity.diagnostics.triangletools as triangletools
coordsY = annulus_mesh.SliceCoordsLinear(0.0, 1.0, 0.01, 20)
coordsX = annulus_mesh.SliceCoordsLinear(0.0, 1.0, 0. | 01, 20)
mesh = annulus_mesh.GenerateRectangleMesh(coordsX, coordsY)
triangletools.WriteTriangle(mesh, "square-structured-linear")
|
genevolv/dbrev | py/freevolv/utils/misc.py | Python | bsd-2-clause | 4,799 | 0.005001 |
# Copyright (c) 2016, Genevolv LLC. All rights reserved.
''' A module for miscellaneous utility functions.'''
import logging
LOG = logging.getLogger(__name__)
# LOG.setLevel(logging.INFO)
import decimal
import re
import string
import sys
import os
#-------------------
# Type translations
#-------------------
def... | ------------
def get_rcs_change(path):
''' Grep a file for the RCS keyword "Change" and extract the number.'''
rtn = str(0)
if getattr(sys, 'frozen', None):
# Running .exe, get temp path to bundled data file
basedir = sys._MEIPASS
else:
basedir = os.path.dirname(path)
# LOG.... | edir: " + basedir)
path = os.path.join(basedir, path)
# LOG.debug("path: " + path)
filep = open(path)
for line in filep:
# LOG.debug(line)
match = re.match('.*\\$Change: (.*) \\$', line)
if match != None:
# LOG.debug('line: ' + line)
# LOG.debug('match: ' ... |
norus/procstat-json | tornado/process.py | Python | gpl-3.0 | 9,841 | 0.000406 | #!/usr/bin/env python
#
# Copyright 2011 Facebook
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... |
import signal
import subprocess
import sys
import time
from binascii import hexlify
from tornado import ioloop
from tornado.iostream import PipeIOStream
from tornado.log import gen_log
from tornado import stack_context
try:
import multiprocessing # Pyt | hon 2.6+
except ImportError:
multiprocessing = None
def cpu_count():
"""Returns the number of processors on this machine."""
if multiprocessing is not None:
try:
return multiprocessing.cpu_count()
except NotImplementedError:
pass
try:
return os.sysconf("... |
GladeRom/android_external_chromium_org | tools/telemetry/telemetry/page/__init__.py | Python | bsd-3-clause | 5,716 | 0.009447 | # Copyright 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import inspect
import os
import re
import urlparse
_next_page_id = 0
class Page(object):
def __init__(self, url, page_set=None, base_dir=None, name=''):
... | de', 'static'))
result.append('DELAY(%s;%s)' % (delay, options))
return result
def __lt__(self, other):
return self.ur | l < other.url
def __cmp__(self, other):
x = cmp(self.name, other.name)
if x != 0:
return x
return cmp(self.url, other.url)
def __str__(self):
return self.url
def AddCustomizeBrowserOptions(self, options):
""" Inherit page overrides this to add customized browser options."""
pass
... |
lxki/pjsip | tests/pjsua/scripts-sendto/311_srtp1_recv_avp.py | Python | gpl-2.0 | 826 | 0.01937 | # $Id: 311_srtp1_recv_avp.py 203 | 6 2008-06-20 17:43:55Z nanang $
import inc_sip as sip
i | mport inc_sdp as sdp
sdp = \
"""
v=0
o=- 0 0 IN IP4 127.0.0.1
s=tester
c=IN IP4 127.0.0.1
t=0 0
m=audio 4000 RTP/AVP 0 101
a=rtpmap:0 PCMU/8000
a=sendrecv
a=rtpmap:101 telephone-event/8000
a=fmtp:101 0-15
a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:WnD7c1ksDGs+dIefCEo8omPg4uO8DYIinNGL5yxQ
a=crypto:2 AES_CM_128_HMAC_SHA1... |
ThatRfernand/or-tools | examples/python/bus_schedule.py | Python | apache-2.0 | 3,339 | 0.013477 | # Copyright 2010 Hakan Kjellerstrand hakank@bonetmail.com
#
# 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 ... | ' : http://www.hakank.org/tailor/bus_schedule.eprime
* SICStus: http://hakank.org/sicstus/bus_schedule.pl
This model was created by Hakan Kjellerstrand (hakank@bonetmail.com)
Also see my other Google CP Solver models:
http://www.hakank.org/google_or_tools/
"""
from __future__ | import print_function
import sys
from ortools.constraint_solver import pywrapcp
def main(num_buses_check=0):
# Create the solver.
solver = pywrapcp.Solver("Bus scheduling")
# data
time_slots = 6
demands = [8, 10, 7, 12, 4, 4]
max_num = sum(demands)
# declare variables
x = [solver.IntVar(0, max_num... |
pynag/pynag | pynag/Utils/nsca.py | Python | gpl-2.0 | 1,761 | 0.001136 | """Module for dealing with NSCA."""
from __future__ import absolute_import
from pynag.Utils import bytes2str
import platform
import subprocess
import six
def send_nsca(code, message, nscahost, hostname=None, service=None, nscabin="send_nsca", nscaconf=None):
""" Send data via send_nsca for passive service checks
... | ss of NSCA server.
hostname (str): Hostname the check results apply to.
service (str): Service the check results apply to.
nscabin (str): Location of send_nsca binary. If none specified whatever
is in the path will be used.
nscaconf (str): Location of the NSCA configuration t... | d command
command = [nscabin, '-H', nscahost]
if nscaconf:
command += ['-c', nscaconf]
# Just in case, status code was sent in as an integer:
code = str(code)
# Build the input string
if service:
input_string = '\t'.join([hostname, service, code, message]) + '\n'
else:
... |
Donkyhotay/MoonPy | zope/app/form/browser/tests/test_choicecollections.py | Python | gpl-3.0 | 3,109 | 0.002573 | ##############################################################################
#
# Copyright (c) 2001, 2002 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# T... | i.provideMultiView((IList, IIterableVocabulary), IBrowserRequest,
IDisplayWidget, '', ItemsMultiDisplay | Widget)
field = List(value_type=Choice(values=[1, 2, 3]))
bound = field.bind(object())
widget = CollectionDisplayWidget(bound, TestRequest())
self.assert_(isinstance(widget, ItemsMultiDisplayWidget))
self.assertEqual(widget.context, bound)
self.assertEqual(widget.vocabula... |
xjw1001001/IGCexpansion | SwapTest/Run_unfinished.py | Python | gpl-3.0 | 9,886 | 0.031863 | from IGCexpansion.CodonGeneconv import ReCodonGeneconv
from DirGeneconv import DirGeneconv
from gBGCDirGeneconv import gBGCDirGeneconv
from gBGCCodonGeneconv import gBGCCodonGeneconv
import argparse
from Pdiff import *
def main(args):
model = args.model
paralog = [args.paralog1, args.paralog2]
alignment_f... |
main(parser.parse_args())
## model = 'HKY'
## paralog = ['TLR5a', 'TLR5b']
## alignment_file = './ZebraFish/' + '_'.join(paralog) + '_input.fasta'
## switched_alignment_file = './ZebraFish/' + '_'.join(paralog) + '_input.fasta'
## newicktree = './ZebraFish/FishTree.newick'
## path = '.... | omega_guess = 0.1
## force = False
## gBGC = False
## Dir = False
## clock = False
## pairs = []
## all_pairs = './Filtered_pairs.txt'
## with open(all_pairs, 'r') as f:
## for line in f.readlines():
## pairs.append(line.replace('\n','').split('_'))
## #pairs = [pairs[0]]... |
HyperloopTeam/FullOpenMDAO | lib/python2.7/site-packages/Pyevolve-0.6-py2.7.egg/pyevolve/G1DBinaryString.py | Python | gpl-2.0 | 5,158 | 0.011632 | """
:mod:`G1DBinaryString` -- the classical binary string chromosome
=====================================================================
This is the classical chromosome representation on GAs, it is the 1D
Binary String. This string looks like "00011101010".
Default Parameters
-------------------------------------... | eate the initial population.
"""
mutator = None
""" This is the mutator function slot, you can change the default
mutator using the slot *set* function: ::
genome.mutator.set(Mutators.G1DBinaryStringMutatorSwap)
"""
crossover = None
""" This is the reproduction function slot, the crossove... | ssover.set(Crossovers.G1DBinaryStringXUniform)
"""
def __init__(self, length=10):
""" The initializator of G1DList representation """
GenomeBase.__init__(self)
G1DBase.__init__(self, length)
self.genomeList = []
self.stringLength = length
self.initializator.set(Consts.CDefG1D... |
matthewwardrop/formulaic | tests/materializers/test_base.py | Python | mit | 6,711 | 0.002384 | import pandas
import py | test
from formulaic.errors import FactorEncodingError, FormulaMaterializerNotFoundError
from formulaic.materializers.types import (
EvaluatedFactor,
FactorValues,
ScopedFactor,
ScopedTerm,
)
from formulaic.materializers.base import FormulaMaterializer
from formulaic.materializers.pandas import PandasMa... | r
class TestFormulaMaterializer:
def test_registrations(self):
assert sorted(FormulaMaterializer.REGISTERED_NAMES) == ["arrow", "pandas"]
assert sorted(FormulaMaterializer.REGISTERED_INPUTS) == [
"pandas.core.frame.DataFrame",
"pyarrow.lib.Table",
]
def test_re... |
id4zs2008/blob-dyn | ca-multicore.py | Python | gpl-3.0 | 4,857 | 0.008441 | #!/usr/bin/python
import numpy as np
from sklearn.metrics import mutual_info_score
import MDAnalysis
import os
import re
import math
import sys
from itertools import combinations_with_replacement,permutations
from concurrent.futures import ProcessPoolExecutor, Future, wait
usecpus = 10#how many cores to use
frms_num ... | n th | e cases whereas after the transition time of Y,
no transtion occurred in X, wait time is assigned to 0
"""
def tau_ex(X, Y, tx, ty):
TX = tx
TY = ty
observ_t_Y = TY[-1]
sum = 0
for i in range(0,len(TY)-1):
w1 = wait_time(X, trans_time_n(Y,i+1,TY), TX)
w2 = wait_time(Y, trans_time_n(... |
kontza/sigal | sigal/settings.py | Python | mit | 5,695 | 0 | # Copyright (c) 2009-2020 - Simon Conseil
# Copyright (c) 2013 - Christophe-Marie Duquesne
# Copyright (c) 2017 - Mate Lakat
# 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... | False,
'output_filename': 'index.html',
'piwik': {'tracker_url': '', 'site_id': 0},
'plugin_paths | ': [],
'plugins': [],
'site_logo': '',
'show_map': False,
'source': '',
'theme': 'colorbox',
'thumb_dir': 'thumbnails',
'thumb_fit': True,
'thumb_fit_centering': (0.5, 0.5),
'thumb_prefix': '',
'thumb_size': (200, 150),
'thumb_suffix': '',
'thumb_video_delay': '0',
't... |
ChemiKhazi/Sprytile | rx/core/anonymousobservable.py | Python | mit | 628 | 0 | from .observablebase import Obser | vableBase
class AnonymousObservable(ObservableBase):
"""Class to create an Observable instance from a delegate-based
implementation of the Subscribe method." | ""
def __init__(self, subscribe):
"""Creates an observable sequence object from the specified
subscription function.
Keyword arguments:
:param types.FunctionType subscribe: Subscribe method implementation.
"""
self._subscribe = subscribe
super(AnonymousObse... |
terhorstd/nest-simulator | pynest/nest/tests/test_weight_recorder.py | Python | gpl-2.0 | 11,135 | 0.00009 | # -*- coding: utf-8 -*-
#
# test_weight_recorder.py
#
# This file is part of NEST.
#
# Copyright (C) 2004 The NEST Initiative
#
# NEST 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 Li... | "parrot_neuron", 5)
nest.Connect(pre, post, syn_spec="stdp_synapse_rec")
nest.Connect(sg, pre)
nest.SetStatus(wr, {"senders": pre[1:3], | "targets": post[:3]})
# simulate before GetConnections
# as order of connections changes at beginning of simulation (sorting)
nest.Simulate(1)
connections = nest.GetConnections(pre[1:3], post[:3])
targets = np.array([])
for i in range(1):
nest.Simulate(1)
... |
adalke/rdkit | rdkit/ML/DecTree/BuildSigTree.py | Python | bsd-3-clause | 7,724 | 0.019291 | ## Automatically adapted for numpy.oldnumeric Jun 27, 2008 by -c
# $Id$
#
# Copyright (C) 2003-2008 Greg Landrum and Rational Discovery LLC
# All Rights Reserved
#
"""
"""
from __future__ import print_function
import numpy
from rdkit.ML.DecTree import SigTree
from rdkit.ML import InfoTheory
try:
from rdkit.ML... |
if availBits:
ranker.SetMaskBits(availBits)
#print(' 2:'*depth,availBits)
useCollections=isinstance(examples[0][1],VectCollectio | n)
for example in examples:
#print(' '*depth,example[1].ToBitString(),example[-1])
if not useCollections:
ranker.AccumulateVotes(example[1],example[-1])
else:
example[1].Reset()
ranker.AccumulateVotes(example[1].orVect,example[-1])
try:
bitInfo = ranker.... |
stefan-jonasson/home-assistant | tests/components/climate/test_generic_thermostat.py | Python | mit | 31,078 | 0 | """The tests for the generic_thermostat."""
import asyncio
import datetime
import pytz
import unittest
from unittest import mock
import homeassistant.core as ha
from homeassistant.core import callback
from homeassistant.setup import setup_component, async_setup_component
from homeassistant.const import (
ATTR_UNIT... | s TestClimateGenericThermostat(unittest.TestCase):
"""Test the Generic thermostat."""
def setUp(self): # pylint: disable=invalid-name
"""Setup things to be run when tests are start | ed."""
self.hass = get_test_home_assistant()
self.hass.config.units = METRIC_SYSTEM
assert setup_component(self.hass, climate.DOMAIN, {'climate': {
'platform': 'generic_thermostat',
'name': 'test',
'cold_tolerance': 2,
'hot_tolerance': 4,
... |
charles-dyfis-net/koan | koan/vmwcreate.py | Python | gpl-2.0 | 4,966 | 0.009263 | """
Virtualization installation functions.
Copyright 2007-2008 Red Hat, Inc.
Michael DeHaan <mdehaan@redhat.com>
This program is free software; you can redistribute | it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MER... | Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA
"""
import os, sys, time, stat
import tempfile
import random
from optparse impor... |
bne/hortee | hortee/tracktor/api/resources.py | Python | apache-2.0 | 4,323 | 0.006477 | from django.contrib.auth.models import User
from django.conf import settings
from django.conf.urls.defaults import url
from django.shortcuts import get_object_or_404
from tastypie.resources import ModelResource
from tastypie import fields
from tastypie.authorization import Authorization
from utils import DjangoAuthent... | '):
kwargs['author'] = kwargs['request'].user
return super(ActionResource, self).obj_update(*args, **kwargs)
def get_object_list(self, request):
"""Restrict to Plots owned by user
"""
object_list = self._meta.queryset
return object_list.filter(actor__plot... | ate(self, bundle):
bundle.data['date'] = date_to_timestamp(bundle.data['date'])
return bundle
class Meta:
queryset = Action.objects.all()
authorization = Authorization()
authentication = Authentication()
filtering = {
'actor': ('exact'),
... |
rfriesen/GAS | GAS/utils.py | Python | mit | 2,765 | 0 | import catalogs
import numpy as np
def VlsrByCoord(RA, Dec, region='OrionA', regionCatalog=None, **kwargs):
"""
For the GAS regions determine the appropriate v0 given coordinates.
If a velocity gradient has been fit, it is hard-coded here. Otherwise,
this uses the catalog velocities.
Parameters... | + 1.29725507 * (Dec - 31.2380245486)
return(v0)
if 'OrionA' in region:
coeffs = [3.1792362, 2.36881382, 9.25135413]
v0 = coeffs[2] + | \
coeffs[0] * (RA - 83.8214130221) + \
coeffs[1] * (Dec + 5.60497968304)
return(v0)
if regionCatalog is None:
regionCatalog = catalogs.GenerateRegions()
try:
v0 = regionCatalog[regionCatalog['Region name'] ==
region]['VLSR'].data.data... |
AnthonyBriggs/Python-101 | hello_python_source_py3/chapter 03/difference_engine_5_inorder.py | Python | mit | 2,533 | 0.004343 |
import hashlib
import os
import sys
if len(sys.argv) < 3: #1
print("You need to specify two directories:") #1
print(sys.argv[0], "<directory 1> <directory 2>") #1
sys.exit() #1
directory1 = sys.argv[1] ... | )
print(directory1)
print(directory2)
for directory in [directory1, directory2]:
if not os.access(directory, os.F_OK):
print(directory, "is not a valid directory!")
sys.exit()
def md5(file_path):
read_file = open(file_path, "rb")
the_hash = hashlib.md5()
for line in read_file.readlines... | ine)
return the_hash.hexdigest()
def directory_listing(directory_name):
dir_file_list = {}
dir_root = None
dir_trim = 0
for path, dirs, files in os.walk(directory_name):
if dir_root is None:
dir_root = path
dir_trim = len(dir_root)
print("dir", directory_... |
rfhk/awo-custom | website_timecheck/models/__init__.py | Python | lgpl-3.0 | 103 | 0 | # -*- | codin | g: utf-8 -*-
from . import product_template
from . import sale_order
from . import website
|
DropD/flask-mongorest | flask_mongorest/views.py | Python | bsd-3-clause | 8,990 | 0.002225 | import json
import mimerender
import mongoengine
from flask import request, render_template
from werkzeug.exceptions import NotFound, Unauthorized
from flask.ext.mongorest.exceptions import ValidationError
from flask.ext.mongorest.utils import MongoEncoder
from flask.ext.mongorest import methods
from flask.ext.views.... | er)
render_html = lambda **payload: render_template('mongorest/debug.html', data=json.dumps(payload, cls=MongoEncoder, sort_keys=True, indent=4))
def serialize_mongoengine_validation_error(e):
def serialize_errors(errors):
if hasattr(errors, 'iteritems'):
return dict((k, serialize_errors(v)) fo... | rn unicode(errors)
if e.errors:
return {'field-errors': serialize_errors(e.errors)}
else:
return {'error': e.message}
class ResourceView(View):
resource = None
methods = []
authentication_methods = []
def __init__(self):
assert(self.resource and self.methods)
@mim... |
cudos/trady | trady/views.py | Python | gpl-3.0 | 736 | 0.002717 | # -*- coding: utf-8 -*-
import math
import os
from pyramid.view import view_config
from pyramid.renderers import render
from pyramid.httpexceptions import (
HTTPMovedPermanently,
HTTPFound,
HTTPNotFound,
)
import trady
here = os.path.dirname(__file__)
@view_config(route_name="stock-report", renderer... | dex().to_json(o | rient="records", date_format="epoch")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.