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
ryabina-krasnaya/kpk2016
task_dm1.py
Python
gpl-3.0
166
0.066265
from drawman import * import
time A = [(0,0),(100,0),(100,100),(0,100)] pen_down() for x,y in A: to_point(x,y) to_point(A[0][0],A[0][1]) pen_up() time
.sleep(10)
thonkify/thonkify
src/lib/future/types/newmemoryview.py
Python
mit
654
0
""" A pretty lame implementation of a memoryview object for Python 2.6. """ from collections import Iterable from
numbers import Integral import string from future.utils import istext, isbytes, PY3, with_metaclass from future.types import no, issubset # class BaseNewBytes(type): # def __instancecheck__(cls, instance): # return isinstance(instance, _builtin_bytes) class newmemoryview(object): # with_metaclass(Base...
iew object to Py2.6. """ def __init__(self, obj): return obj __all__ = ['newmemoryview']
davy39/eric
QScintilla/Ui_SearchWidget.py
Python
gpl-3.0
4,989
0.002205
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file './QScintilla/SearchWidget.ui' # # Created: Tue Nov 18 17:53:58 2014 # by: PyQt5 UI code generator 5.3.2 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_SearchWidget(object):...
self.label = QtWidgets.QLabel(SearchWidget) self.label.setObjectName("label") self.horizontalLayout.addWidget(self.label) self.findtextCombo = QtWidgets.QComboBox(SearchWidget) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Fixed) s...
setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.findtextCombo.sizePolicy().hasHeightForWidth()) self.findtextCombo.setSizePolicy(sizePolicy) self.findtextCombo.setMinimumSize(QtCore.QSize(300, 0)) self.findtextCombo.setEditable(True) ...
iulian787/spack
var/spack/repos/builtin/packages/r-gdsfmt/package.py
Python
lgpl-2.1
1,729
0.000578
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class RGdsfmt(RPackage): """R Interface to CoreArray Genomic Data Structure (GDS) Files. ...
d decompression are available with relatively efficient random access. It is
also allowed to read a GDS file in parallel with multiple R processes supported by the package parallel.""" homepage = "https://bioconductor.org/packages/gdsfmt" git = "https://git.bioconductor.org/packages/gdsfmt.git" version('1.20.0', commit='b1fbaba0a5ace3dc45daecc85168651cd85dce00'...
vdrhtc/Measurement-automation
resonator_tools/resonator_tools/calibration.py
Python
gpl-3.0
4,324
0.04371
import numpy as np from scipy import sparse from scipy.interpolate import interp1d class calibration(object): ''' some useful tools for manual calibration ''' def normalize_zdata(self,z_data,cal_z_data): return z_data/cal_z_data def normalize_amplitude
(self,z_data,cal_ampdata): return z_data/cal_ampdata def normalize_phase(self,z_data,cal_phase): return z_data*np.exp(-1j*cal_phase) def normalize_by_func(self,f_data,z_data,func): return z_data/func(f_data) def _baseline_als(self,y, lam, p, niter=10): ''' see http://zanran_storage.s3.amazonaws.co...
ilers and H. Boelens in 2005. http://stackoverflow.com/questions/29156532/python-baseline-correction-library "There are two parameters: p for asymmetry and lambda for smoothness. Both have to be tuned to the data at hand. We found that generally 0.001<=p<=0.1 is a good choice (for a trace with positive peaks) a...
CollabQ/CollabQ
middleware/verify.py
Python
apache-2.0
608
0.009868
# Copyright 2010 http://www.collabq.com import logging from django.conf impor
t settings from django.http import HttpResponseRedirect from common import api from common import exception class VerifyInstallMiddleware(object): def process_request(self, request): logging.info("
VerifyInstallMiddleware") logging.info("Path %s" % request.path) if not request.path == '/install': try: root_user = api.actor_get(api.ROOT, settings.ROOT_NICK) logging.info("Root Exists") except: logging.info("Root Does Not Exists") return HttpResponseRedirect('/inst...
mishka28/NYU-Python
intro-programming/final_project/binomial_tree.py
Python
mit
1,850
0.018378
#!/usr/bin/env python3 from datetime import date import math import numpy as np import sys today = date(2015
, 11, 20) expiry = date(2017, 1, 20) #Global inputs s = 138.65 k = 133 t = (expiry - today).days / 365 r = 0.0106161830925 sig = 0.22545538993 div = .027000 def tree(steps, flavor): Dt = t / steps r_Dt = r * Dt exp_r_Dt = math.exp(r_Dt) exp_neg_r_Dt = math.exp(-r_Dt) exp_div_Dt = math.exp(div * Dt...
exp_neg_div_Dt = math.exp(-div * Dt) sig_sqrt_Dt = sig * math.sqrt(Dt) exp_sig_sqrt_Dt = math.exp(sig_sqrt_Dt) u = exp_sig_sqrt_Dt d = 1/u q = (exp_r_Dt * exp_neg_div_Dt - d) / (u -d) p = 1 - q sv = np.zeros((steps + 1,steps +1), dtype = np.float64) sv[0,0] = s z1 = 0 for i i...
gangadhar-kadam/sapphire_app
stock/doctype/purchase_receipt/purchase_receipt.py
Python
agpl-3.0
13,048
0.032036
# Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import webnotes from webnotes.utils import cstr, flt, cint from webnotes.model.bean import getlist from webnotes.model.code import get_obj from webnotes import msgpr...
ate_uom_is_integer("uom", ["qty", "received_qty"]) self.validate_uom_is_integer("stock_uom", "stock_qty")
self.validate_challan_no() pc_obj = get_obj(dt='Purchase Common') pc_obj.validate_for_items(self) pc_obj.get_prevdoc_date(self) self.check_for_stopped_status(pc_obj) # sub-contracting self.validate_for_subcontracting() self.update_raw_materials_supplied("pr_raw_material_details") self.update_valu...
jongha/gedit-indent
src/gedit/plugins/indent.py
Python
mit
4,209
0.002138
#!/usr/bin/env python from gi.repository import GObject, Gtk, Gedit, PeasGtk import ConfigParser UI_XML = '''<ui> <menubar name="MenuBar"> <menu name="ToolsMenu" action="Tools"> <placeholder name="ToolsOps_2"> <menuitem name="Change Indent" action="ChangeIndentPlugin"/> </placeholder> </me...
Box(spacing=10) label = Gtk.Label('Spaces') section.pack_start(label, False, False, 0) adjustment = Gtk.Adjustment(self.spaces, 2, 10, 1, 10, 0) spinbutton = Gtk.SpinButton() spinbutton.set_adjustment(adjustment) spinbutton.connect("value-changed", self.on_spaces_value_c...
change_tab = Gtk.CheckButton("Spaces to Tab") change_tab.connect("toggled", self.on_change_tab_toggled) change_tab.set_active(True if self.tab == 1 else False) section.pack_start(change_tab, False, False, 0) box.pack_start(section, False, False, 0) return box def on_space...
aarontuor/antk
setup.py
Python
mit
1,606
0.003113
try: from setuptools import setup, find_packages except ImportError: from distutils.core import setup setup(name='antk', version=0.3, description='Automated Neural-graph Toolkit: A Tensorflow wrapper for ' 'common deep learning tasks and rapid development of innovative' ...
. Developed at Hutch Research, Western Washing
ton University.' 'Support for multiple input and output neural network graphs. ' 'Model visualizations and extensively documented interface. ' 'Explore tensorflow functionality and deep learning fundamentals.', url='http://aarontuor.xyz', author='Aaron T...
chujieyang/ice
python/test/Ice/ami/run.py
Python
gpl-2.0
907
0.006615
#!/usr/bin/env python # ********************************************************************** # # Copyright (c) 2003-2015 ZeroC, Inc. All rights reserved. # # This copy of Ice is licensed to you un
der the terms described in the # ICE_LICENSE file included in this distribution. # # ***************************************************
******************* import os, sys path = [ ".", "..", "../..", "../../..", "../../../.." ] head = os.path.dirname(sys.argv[0]) if len(head) > 0: path = [os.path.join(head, p) for p in path] path = [os.path.abspath(p) for p in path if os.path.exists(os.path.join(p, "scripts", "TestUtil.py")) ] if len(path) == 0: ...
LACNIC/simon
simon-web/simon_app/migrations/0003_probeapipingresult_probeapi_id.py
Python
gpl-2.0
494
0
# -*- cod
ing: utf-8 -*- # Generated by Django 1.11.29 on 2020-11-22 11:59 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration):
dependencies = [ ('simon_app', '0002_probeapirequest_test_settings'), ] operations = [ migrations.AddField( model_name='probeapipingresult', name='probeapi_id', field=models.CharField(default=b'', max_length=128), ), ]
ueg1990/github3.py
tests/test_repos.py
Python
bsd-3-clause
25,952
0.000154
import os import github3 import pytest from github3 import repos from tests.utils import (BaseCase, load, mock) class TestRepository(BaseCase): def __init__(self, methodName='runTest'): super(TestRepository, self).__init__(methodName) self.repo = repos.Repository(load('repo')) def setUp(self)...
', 201) title = 'Construct _api attribute on our own' self.post(self.api + 'issues')
self.conf = {'data': {'title': title}} self.assertRaises(github3.GitHubError, self.repo.create_issue, title) self.login() assert isinstance(self.repo.create_issue(title), github3.issues.Issue) self.mock_assertions() body = 'Fake body' #self.conf['data'].update(body=bo...
T-R0D/JustForFun
aoc2016/aoc2016/day14/test/test_solution.py
Python
gpl-2.0
2,254
0.002662
# This file is part of aoc2016. # # aoc2016 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. # # aoc2016 is distributed in the hope th...
', solution.OTPGenerator.find_runs(h, 3)) h = hashlib.md5('abc200'.encode()).digest().hex() self.assertEqual('9', solution.OTPGenerator.find_runs(h, 5)) def test_get_otps(self): generator = solution.OTPGenerator(salt='abc') otps = generator.get_otps(n_needed=64, proximity=1000) ...
ssertTrue(39 in otps, 'The first triple (39) could not be found in the set of keys.') self.assertEqual(22728, otps[-1], 'The last OTP was not 22728.')
aldryn/aldryn-boilerplate-bootstrap3
tools/server/src/wsgi.py
Python
bsd-3-clause
378
0.002646
""" WSGI config for this project. It exposes the
WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.7/howto/deployment/wsgi/ """ import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings")
from django.core.wsgi import get_wsgi_application application = get_wsgi_application()
bwasti/caffe2
caffe2/python/brew_test.py
Python
apache-2.0
9,590
0
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from caffe2.python import brew, core, scope, workspace from caffe2.python.modeling.parameter_info import ParameterTags from caffe2.python.model_helper import ModelHelper ...
ith self.assertRaises(AttributeError): brew.Register(myhelper) def test_has_helper(self): self.assertTrue(brew.has_helper(brew.conv)) self.assertTrue(brew.has_helper("conv")) def myhelper3(): pass self.assertFalse(brew.has_helper(m
yhelper3)) def test_model_helper(self): X = np.random.rand(64, 32, 32, 3).astype(np.float32) - 0.5 workspace.FeedBlob("x", X) my_arg_scope = {'order': 'NHWC'} model = ModelHelper(name="test_model", arg_scope=my_arg_scope) with brew.arg_scope( brew.conv, ...
paulhybryant/powerline-shell
segments/vimode.py
Python
mit
143
0
def add_vimode_s
egment(powerline): vimode_prompt = ' \n${VIMODE}' power
line.append(vimode_prompt, Color.NEWLINE_FG, Color.NEWLINE_BG)
yarikoptic/NiPy-OLD
nipy/core/reference/tests/test_coordinate_map.py
Python
bsd-3-clause
13,061
0.011025
import numpy as np from nipy.testing import assert_true, assert_equal, assert_raises, \ assert_fa
lse, assert_array_equal, parametric from nipy.core.reference.coordinate_map import CoordinateMap, Affine, \ compose, CoordinateSystem, reorder_input, reorder_output, product, \ replicate, linearize, drop_io_dim, append_io_dim class empty: pass E = empty() def setup(): def f(x): return 2*x ...
x, x) E.b = CoordinateMap(f, x, x, inverse_mapping=g) E.c = CoordinateMap(g, x, x) E.d = CoordinateMap(g, x, x, inverse_mapping=f) E.e = Affine.identity('ijk') A = np.identity(4) A[0:3] = np.random.standard_normal((3,4)) E.mapping = Affine.from_params('ijk' ,'xyz', A) ...
aurule/npc
npc/character/tags/tag.py
Python
mit
9,073
0.002094
from collections import UserList from copy import copy from npc.util import print_err class Tag(UserList): """ Defines a mult-value tag object """ def __init__(self, name: str, *args, required: bool=False, hidden: bool=False, limit: int=-1): """ Create a new Tag object Args: ...
}, required={req}, hidden={hidden}, hidden_values={hidden_vals}, limit={limit})".format( cls=type(self).__name__, name=self.name,
data=self.data, req=self.required, hidden=self.hidden, hidden_vals=self.hidden_values, limit=self.limit ) def update(self, values): """ Add the strings in values to our own list of values Args: values (list[str]): List ...
ddico/odoo
addons/account/models/chart_template.py
Python
agpl-3.0
68,522
0.005079
# -*- coding: utf-8 -*- from odoo.exceptions import AccessError from odoo import api, fields, models, _ from odoo import SUPERUSER_ID from odoo.exceptions import UserError, ValidationError from odoo.http import request from odoo.addons.account.models.account_tax import TYPE_TAX_USE import logging _logger = logging.g...
de_digits = fields.Integer(string='# of Digits', required=True, default=6, help="No. of Digits to use for account code") visible = fields.Boolean(string='Can be Visible?', default=True, help="Set this to False if you don't want this template to be used actively in the wizard that generate Chart of Accounts ...
ful when you want to generate accounts of this template only when loading its child template.") currency_id = fields.Many2one('res.currency', string='Currency', required=True) use_anglo_saxon = fields.Boolean(string="Use Anglo-Saxon accounting", default=False) complete_tax_set = fields.Boolean(string='Compl...
gregoil/rotest
src/rotest/api/resource_control/update_fields.py
Python
mit
1,869
0
# pylint: disable=unused-argument, no-self-use from __future__ import absolute_import from six.moves import http_client from django.db import transaction from swaggapi.api.builder.server.response import Response from swaggapi.api.builder.server.request import DjangoRequestView from rotest.api.common.responses import ...
filter (dict): arguments to filter by.
changes (dict): the additional arguments are the changes to apply on the filtered instances. """ model = extract_type(request.model.resource_descriptor.type) filter_dict = request.model.resource_descriptor.properties kwargs_vars = request.model.changes w...
jaufrec/whatnext
clog/migrations/0010_auto_20160410_2149.py
Python
gpl-3.0
710
0
# -*- coding: utf-8 -*- # Generated by Django 1.9.5 on 2016-04-10 21:49 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('clog', '0009_auto_20160410_0452'), ] operations = [ migrations.AlterModelOpt...
y', options=
{'verbose_name_plural': 'Log Entries'}, ), migrations.AlterField( model_name='variable', name='order', field=models.IntegerField(), ), migrations.AlterUniqueTogether( name='variable', unique_together=set([('user', 'order')]), ...
home-assistant/home-assistant
homeassistant/components/tibber/__init__.py
Python
apache-2.0
2,333
0.000857
"""Support for Tibber.""" import asyncio import logging import aiohttp import tibber from homeassistant.const import ( CONF_ACCESS_TOKEN, CONF_NAME, EVENT_HOMEASSISTANT_STOP, Platform, ) from homeassistant.exceptions import ConfigEntryNotReady from homeassistant.helpers import discovery from homeassis...
ientsession import homeassistant.helpers.config_validation as cv from homeassistant.util import dt as dt_util from .const import DATA_HASS_CONFIG, DOMAIN PLATFORMS = [Platform.SENSOR] CON
FIG_SCHEMA = cv.removed(DOMAIN, raise_if_present=False) _LOGGER = logging.getLogger(__name__) async def async_setup(hass, config): """Set up the Tibber component.""" hass.data[DATA_HASS_CONFIG] = config return True async def async_setup_entry(hass, entry): """Set up a config entry.""" tibber_...
magopian/amo-validator
extras/jslibfetcher.py
Python
bsd-3-clause
9,177
0.001417
import urllib import os def process(url, destination): destination = "jslibs/%s" % destination if os.path.exists(destination): return try: print url urllib.urlretrieve(url, destination) except Exception as e: print "Failed", e def get_pattern(prefix, url_pattern, ve...
-1])) process("https://addons.cdn.mozilla.net/en-US/firefox/files/browse/149703/" "file-serve/bootstrap.js?token=f885db28-1ec2-419d-8b35-72300523befb", "PersonasInteractive_bootstrap.js") BACKBONE_VERSIONS = [ "1
.0.0", "1.1.0", "1.1.1", "1.1.2", ] BACKBONE_LOCALSTORAGE_VERSIONS = [ "1.1.10", "1.1.12", "1.1.13", "1.1.14", "1.1.15", "1.1.16", ] DOJO_VERSIONS = [ "1.4.0", "1.4.1", "1.4.3", "1.5", "1.5.1", "1.6", "1.6.1", "1.7.0", "1.7.1", "1.7.2", "1...
openstack/octavia
octavia/db/migration/alembic_migrations/versions/35dee79d5865_initial_create.py
Python
apache-2.0
13,662
0
# Copyright 2014 Rackspace # # 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 agree...
EATE'}, {'name': 'PENDING_UPDATE'}, {'name': 'PENDING_DELETE'}, {'name': 'DELETED'}, {'name': 'ERROR'} ] ) op.create_table( u'operating_status', sa.Column(u'name', sa.String(30), primary_key=True), sa.Column(u'description', sa.Stri...
e = sql.table( u'operating_status', sql.column(u'name', sa.String), sql.column(u'description', sa.String) ) op.bulk_insert( insert_table, [ {'name': 'ONLINE'}, {'name': 'OFFLINE'}, {'name': 'DEGRADED'}, {'name': 'ERROR'} ...
dhowland/EasyAVR
keymapper/easykeymap/boards/tokyo60.py
Python
gpl-2.0
8,879
0.000676
""" Keyboard definition for the Tokyo60 custom keyboard. Auto-generated from 'D:\\Users\\dave\\Desktop\\tokyo60.json' """ # # READ THIS # # This file contains a description of the various parameters that # must be defined in order to completely describe the new keyboard. # This file must be correct for the firmware to...
o that LED. LED # functions must be strings as defined in led_assignments
of gui.py. # Choices are 'Num Lock', 'Caps Lock', 'Scroll Lock', 'Compose', 'Kana', # 'Win Lock', 'Fn1 Active', 'Fn2 Active', 'Fn3 Active', 'Fn4 Active', # 'Fn5 Active', 'Fn6 Active', 'Fn7 Active', 'Fn8 Active', 'Fn9 Active', # 'Any Fn Active', 'Recording', 'USB Init', 'USB Error', 'USB Suspend', # 'USB Normal', 'Back...
Alberto-Beralix/Beralix
i386-squashfs-root/usr/share/doc/python-pexpect/examples/ssh_session.py
Python
gpl-3.0
2,839
0.007397
#!/usr/bin/env python # # Eric S. Raymond # # Greatly modified by Nigel W. Moriarty # April 2003 # from pexpect import * import os, sys import getpass import time class ssh_session: "Session with extra state including the password to be used." def __init__(self, user, host, password=None, verbose=0): ...
child.sendline(self.password) child.readline() time.sleep(5) # Added to allow the background running of remote process if not child.isalive(): seen = child.expect(self.keys) if seen == 2: lines = child.readlines() self.f.w...
tr(child.after)+'\n') except: pass self.f.close() return child.before def ssh(self, command): return self.__exec("ssh -l %s %s \"%s\"" \ % (self.user,self.host,command)) def scp(self, src, dst): return self.__ex...
ThorsteinnAdal/webcrawls_in_singapore_shippinglane
db_format_helpers/get_all_ship_fields.py
Python
apache-2.0
302
0.003311
__author__
= 'thorsteinn' def get_all_ship_fields(db): ships = db.keys() fields = [] for ship in ships: shipDB = db[ship] shipKeys = shipDB.keys() for oneKey in shipKeys: if oneKey not in fields:
fields.append(oneKey) return fields
Pythagorists/pypiwik
tests/test_api.py
Python
mit
620
0.001613
import json from nose.tools i
mport * import responses from pypiwik.api import ApiConnection from tests import PywikTestCase class ApiTestCase(PywikTestCase): def setUp(self): self.api = ApiConnection( url='http://example.test', token_auth='abc', ) @responses.activate def test_version(self): ...
) assert_equal( response, {'value': '2.7.0'} )
Rombur/Cap
python/test/test_property_tree_wrappers.py
Python
bsd-3-clause
5,738
0
# Copyright (c) 2016, the Cap authors. # # This file is subject to the Modified BSD License and may not be distributed # without copyright and license information. Please refer to the file LICENSE # for the text and further information on this license. from pycap import PropertyTree from os import remove import unitte...
3.14), 3.14) ptree.put_double('present_double', 1.41) self.assertEqual(ptree.g
et_double_with_default_value('present_double', 3.14), 1.41) # string self.assertEqual(ptree.get_string_with_default_value('missing_string', 'missing'), 'miss...
weijia/djangoautoconf
djangoautoconf/auto_conf_signals.py
Python
bsd-3-clause
523
0.001912
import sys __author__ = 'weijia' import django.dispatch before_server_start = django.dispatch.Signal(providing_args=[]) before_server_stop = django.dispatch.Signal(p
roviding_args=[]) class ServerSignalTrigger(object): def trigger_server_start_if_needed(self): if sys.argv[1] == "runserver": before_server_start.send(sender=self) def trigger_server_stop_if_needed(self): if sys.argv[1] == "runserver": before_server_stop.send(sender=se...
ss exiting"
cmoutard/mne-python
mne/channels/tests/test_layout.py
Python
bsd-3-clause
14,277
0.00007
from __future__ import print_function # Authors: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr> # Denis Engemann <denis.engemann@gmail.com> # Martin Luessi <mluessi@nmr.mgh.harvard.edu> # Eric Larson <larson.eric.d@gmail.com> # # License: Simplified BSD import copy import os.pa...
'tests', 'data') fname_ctf_raw = op.join(op.dirname(__file__), '..', '..', 'io', 'tests', 'data', 'test_ctf_comp_raw.fif') fname_kit_157 = op.join(op.dirname(__file__), '..', '..', 'io', 'kit', 'tests', 'data', 'test.sqd') test_info = _empty_inf
o(1000) test_info.update({ 'ch_names': ['ICA 001', 'ICA 002', 'EOG 061'], 'chs': [{'cal': 1, 'ch_name': 'ICA 001', 'coil_type': 0, 'coord_Frame': 0, 'kind': 502, 'loc': np.array([0., 0., 0., 1., 0., 0., 0., 1., 0., 0., 0., 1.], ...
zmap/ztag
ztag/transforms/fox.py
Python
apache-2.0
2,652
0.000754
from ztag.transform import * from ztag import protocols, errors class NiagaraFoxTransform(ZGrabTransform): name = "fox/device_id" port = 1911 protocol = protocols.FOX subprotocol = protocols.FOX.DEVICE_ID def _transform_object(self, obj): zout = ZMapTransformOutput() wrapped = Tra...
e = fox['language'].resolve() time_zone = fox['time_zone'].resolve() host_id = fox['host_id'].resolve() vm_uuid = fox['vm_uuid'].resolve() brand_id = fox['brand_id'].resolve() sys_info = fox['sys_info'
].resolve() auth_agent_type = fox['auth_agent_type'].resolve() out = dict() out["support"] = True if instance_number: out["instance_number"] = instance_number if version: out["version"] = version if id_: out["id"] = id_ if host...
ace0/safeid
safeid/common.py
Python
mit
1,125
0.022222
""" Common routines """ import hmac as HMAC from base64 import urlsafe_b64encode as b64encode import hashlib, os HASH_ALG = hashlib.sha256 HASH_LENGTH = 32 TAG_PASSWORD = "TAG_SAFEID_PASSWORD" TAG_USER = "TAG_SAFEID_USER" def hmac(tag, message, key, alg=HASH_ALG): """ Generates a hashed message authentication code...
).digest() return b64encode(d) def secureRandom(n=HASH_LENGTH): """ Gets a secure random string (base64 encoded) of @n bytes. """ return str(b64encode(os.urandom(n))[:n]) def dp(**kwargs): """ Debugging print. Prints a list of labels and values, each on their own line. """ for label,value in kwargs.iterit...
nt "{0}\t{1}".format(label, value)
jamiebull1/geomeppy
tests/test_intersect_match.py
Python
mit
15,469
0.002263
"""Tests for intersecting and matching.""" import itertools import pytest from eppy.iddcurrent import iddcurrent from six import StringIO from geomeppy.geom.surfaces import minimal_set from geomeppy.idf import IDF from geomeppy.geom.intersect_match import ( get_adjacencies, intersect_idf_surfaces, match_i...
(0, 1, 0), (0, 0, 0), (1, 0, 0), (1, 1, 0)]) poly2 = Polygon3D([
(1, 1, 0), (1, 0, 0), (0, 0, 0), (0, 1, 0)]) adjacencies = [(poly1, poly2)] result = intersect(*adjacencies[0]) expected = [poly1, poly2] assert len(result) == len(expected) for poly in expected: assert poly in result def test_simple_overlap(self): # type...
Intel-Corporation/tensorflow
tensorflow/python/kernel_tests/array_ops/stack_op_test.py
Python
apache-2.0
14,594
0.008154
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
= self.evaluate(array_ops.stack(list(x)))
self.assertAllEqual(p, x) p = self.evaluate(array_ops.parallel_stack(list(x))) self.assertAllEqual(p, x) def testZeroSizeGPU(self): # tf.parallel_stack is only supported in graph mode. with ops.Graph().as_default(): # Verify that stack doesn't crash for zero size in...
Juniper/euca2ools
euca2ools/commands/iam/uploadservercertificate.py
Python
bsd-2-clause
3,276
0
# Copyright 2009-2014 Eucalyptus Systems, Inc. # # 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 ab
ove c
opyright notice, # this list of conditions and the following disclaimer. # # Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDE...
dadawangweb/ukl-gsvc-web
app/api_1_0/webModifySqlAPI.py
Python
mit
3,719
0.002003
# -*- coding: utf-8 -*- """ webModifySqlAPI ~~~~~~~~~~~~~~ 为web应用与后台数据库操作(插入,更新,删除操作)的接口 api_functions 中的DataApiFunc.py为其接口函数汇聚点,所有全局变量设置都在此;所有后台函数调用都在此设置 Implementation helpers for the JSON support in Flask. :copyright: (c) 2015 by Armin kissf lu. :license: ukl, see LICENSE for more detail...
:return: """ if request.method == 'POST': arrayData = request.get_array(field_name='file') return deleManuleVsimSrc(array_data=arrayData) else: returnJsonData = {'err': True, 'errinfo': '操作违法!', 'data': []} return json.dumps(returnJsonData, sort_keys=True, indent=4, d...
OST']) def insert_manulVsim(): """ :return: """ if request.method == 'POST': arrayData = request.get_array(field_name='file') return insertManuleVsimSrc(array_data=arrayData) else: returnJsonData = {'err': True, 'errinfo': '操作违法!', 'data': []} return json.dumps(re...
memtoko/django
tests/migrations/test_multidb.py
Python
bsd-3-clause
6,893
0.001886
import unittest from django.db import connection, migrations, models from django.db.migrations.state import ProjectState from django.test import override_settings from .test_operations import OperationTestBase try: import sqlparse except ImportError: sqlparse = None class AgnosticRouter(object): """ ...
self._test_run_python("test_mltdb_runpython", should_run=False) @override_settings(DATABASE_ROUTERS=[MigrateWhenFooRouter()]) def test_run_python2(self): self._test_run_python("test_mltdb_runpython2", should_run
=False) self._test_run_python("test_mltdb_runpython2", should_run=True, hints={'foo': True})
lovelylain/pyctp
example/pyctp2/test/test_coordinator.py
Python
mit
49,136
0.018901
# -*- coding:utf-8 -*- import logging import unittest import unittest.mock as mock import operator import time import os from ..trader.coordinator import Coordinator, POSITION_HANDLE_TICK from ..common.base import TEST_PATH,TICK,BaseObject,LONG,SHORT,ZERO_TICK,TEST_STATE_PATH from ..common.contract_type import M,P,Con...
positions[1].contract == p1501 assert agent._position_holder._active_positions[2].contract == m1501 assert agent._position_holder._active_positions[0].volume_holding == 2 assert agent._position_holder._active_positions[1].volume_holding == 1 assert agent._position_holder._active_positions[2].volume_hold...
ssert agent.position_holder.get_volume_holding("m1501")==3 assert agent.position_holder.get_volume_holding("p1501")==1 return agent def _prepare_agent_to(coordinator): m1505 = ContractInfo("m1505",1505,M) p1505 = ContractInfo("p1505",1505,P) m1505._minutes = [BaseObject()] p1505._minutes = [B...
misilences/incipe
var/www/test/crawler/rbt.py
Python
mit
266
0.007519
#!/usr/bin/python import urllib2 url = "http://localhost:8888/test/test.txt" html = ur
llib2.urlopen(url).read() print html send_headers = { 'range':'bytes=10-' } req = urllib2.Re
quest(url, headers=send_headers) html = urllib2.urlopen(req).read() print html
ngageoint/geoq
geoq/proxy/apps.py
Python
mit
120
0.016667
from django.apps import AppCo
nfig class Proxy
Config(AppConfig): name = 'geoq.proxy' verbose_name = 'GeoQ Proxy'
yavwa/Shilling
test/functional/mempool_limit.py
Python
mit
2,527
0.007519
#!/usr/bin/env python3 # Copyright (c) 2014-2017 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test mempool limiting together/eviction with the wallet.""" from test_framework.test_framework import ...
is larger than minrelytxfee') assert_equal(self.nodes[0].getmempoolinfo()['minrelaytxfee'], Decimal('0.00001000')) assert_greater_than(self.nodes[0].getmempoolinfo()['mempoolminfee'], D
ecimal('0.00001000')) if __name__ == '__main__': MempoolLimitTest().main()
abhishekgahlot/kivy
kivy/input/providers/mactouch.py
Python
mit
7,345
0.001361
''' Native support of MultitouchSupport framework for MacBook (MaxOSX platform) =========================================================================== ''' __all__ = ('MacMotionEventProvider', ) import ctypes import threading import collections import os from kivy.input.provider import MotionEventProvider from ki...
event_type, touch = self.que
ue.popleft() dispatch_fn(event_type, touch) except: pass def stop(self): # i don't known how to stop it... pass @MTContactCallbackFunction def _mts_callback(device, data_ptr, n_fingers, timestamp, frame): global _instance devid = str(devi...
dasseclab/dasseclab
clones/routersploit/tests/payloads/cmd/test_netcat_reverse_tcp.py
Python
gpl-2.0
398
0
from routersploit.mo
dules.payloads.cmd.netcat_reverse_tcp import Payload # netcat reverse tcp payload with
lhost=192.168.1.4 lport=4321 reverse_tcp = ( "nc 192.168.1.4 4321 -e /bin/sh" ) def test_payload_generation(): """ Test scenario - payload generation """ payload = Payload() payload.lhost = "192.168.1.4" payload.lport = 4321 assert payload.run() == reverse_tcp
eicher31/compassion-switzerland
partner_compassion/models/res_users.py
Python
agpl-3.0
145
0.006897
from odoo import mode
ls, fields class ResUsers(models.Model): _inherit = "res.users" partner_id = fiel
ds.Many2one(ondelete='cascade')
squisher/llvmlite
examples/parseasm.py
Python
bsd-2-clause
738
0.001355
from llvmlite import binding as llvm from llvmlite import ir as lc llvm.initialize() llvm.initialize_native_target() mod = lc.Module() mod.triple = llvm.get_default_triple() func = lc.Function(mod, lc.FunctionType(lc.VoidType(), [lc.IntType(32)]), name='foo') builder = lc.IRBuilder(func.append_basi...
assembly(str(mod)) mod.verify() print(repr(mod)) print(mod) with llvm.create_module_pa
ss_manager() as pm: with llvm.create_pass_manager_builder() as pmb: pmb.populate(pm) pm.run(mod) print(mod) ee = llvm.create_jit_compiler(mod) func = mod.get_function(name="foo") print(func, ee.get_pointer_to_global(func)) ee.close() llvm.shutdown()
varses/awsch
lantz/drivers/legacy/olympus/ixbx.py
Python
bsd-3-clause
8,205
0.002681
# -*- coding: utf-8 -*- """ lantz.drivers.legacy.olympus.ixbx ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ When talking about the z-axis of a microscope, use "near" and "far" instead of "up" and "down." "Nearer" always means the objective ends closer to the sample; "farther" means the objective ends farther away. On ...
mera_port_enabled= ofeat('PRISM', 'Prism position', values=ONE_TWO) class BX2A(IXBX): """ Olympus BX2A Body """ shutter_closed = ofeat('SHUTTER', 'Shutter RFAA', values=IN_OUT) aperture_stop_diameter = ofeat('EAS', 'Aperture stop diameter (EPI AS RLAA)', procs=(INTSTR, )) aperture_stop_diameter =...
stop diameter (DIA AS UCD)', procs=(INTSTR, )) condenser_top_lens_enabled = ofeat('CDTOP', 'Condenser top lens (UCD)', values=IN_OUT) turret = ofeat('TURRET', 'Turret position (UCD)', procs=(INTSTR, )) cube = ofeat('CUBE', 'Cube position (RFAA/RLAA)', procs=(INTSTR, )) configure_filterwheel = ofeat('FW'...
leonardo-modules/leonardo-channels
leonardo_channels/widgets/consumers.py
Python
bsd-3-clause
4,060
0
import json import logging from django.contrib.admin.util import NestedObjects from leonardo.utils import render_region from leonardo_channels import Group from leonardo_channels.auth import (channel_session_user, channel_session_user_from_http) from leonardo_channels.consumers impo...
): for widget in instances: msg = { "widget": widget, "sender": widget.__class__, "path": "/widgets/update"} self.sender.send("http.request", msg)
return # get related models and refresh it collector = NestedObjects( using=instance._state.db) # database name collector.collect([instance]) for w_cls, models in collector.data.items(): if hasattr(w_cls, 'parent') and hasattr(w_cls, 'fe_identifier'): ...
IkeC/evo-league
Sixserver/lib/fiveserver/admin.py
Python
mit
32,438
0.004686
from twisted.web import static, server, resource from twisted.internet import reactor, defer from twisted.words.xish import domish from xml.sax.saxutils import escape import log from fiveserver.model.lobby import MatchState, Match, Match6 from fiveserver.model import util import os import urllib import sys import hash...
it) d.addErrback(self.renderError, request) return server.NOT_DONE_YET class UsersOnlineResource(B
aseXmlResource): def render_GET(self, request): request.setHeader('Content-Type','text/xml') users = domish.Element((None,'users')) users['count'] = str(len(self.config.onlineUsers)) users['href'] = '/home' keys = self.config.onlineUsers.keys() keys.sort() fo...
skioo/django-customer-billing
billing/migrations/0015_auto_20181223_0907.py
Python
mit
722
0.001385
# Generated by Django 2.1.4 on 2018-12-23 15:07 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration
): dependencies = [ ('billing', '0014_deleting_invoice_detaches_charges'), ] operations = [ migrations.AlterField( model_name='transaction', name='psp_content_type', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCA...
), migrations.AlterField( model_name='transaction', name='psp_object_id', field=models.UUIDField(blank=True, db_index=True, null=True), ), ]
EssaAlshammri/django-by-example
e-learning/educa/courses/models.py
Python
mit
2,631
0.00038
from django.contrib.auth.models import User from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.db import models from django.template.loader import render_to_string from django.utils.safestring import mark_safe from .fields import Orde...
ey(Module, related_name='contents') content_type = models.ForeignKey(ContentType, limit_choices_to={ 'model__in': ['text', 'file', 'image', 'video'] }) object_id = models.PositiveIntegerField() item = GenericForeignKey('content_type', 'object_id') order = OrderField(blank=True, for_fields=['...
ordering = ['order'] class ItemBase(models.Model): owner = models.ForeignKey(User, related_name='%(class)s_related') title = models.CharField(max_length=250) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Meta: abstract = True ...
openstack/ironic
devstack/files/hooks/qemu.py
Python
apache-2.0
3,351
0
#!/usr/bin/python3 # Copyright (c) 2017 Intel Corporation # # 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...
h("%LOG_DIR%") # Regular expression to find ANSI escape sequences at the beginning of a string ANSI_ESCAPE_RE = re.compile(r""" ^\x1b\[ # ANSI escape codes
are ESC (0x1b) [ ?([\d;]*)(\w)""", re.VERBOSE) NOW = datetime.datetime.now().strftime("%Y-%m-%d-%H:%M:%S") def main(): if len(sys.argv) < 3: return guest_name = sys.argv[1] action = sys.argv[2] if action == "started": interfaces = subprocess.check_output( ['ip', 'li...
ddico/odoo
addons/sale_expense/models/__init__.py
Python
agpl-3.0
208
0
# -*- coding: utf-8 -*- # Part of Odoo.
See LICENSE file for full copyright and licensing details. from . import hr_expense from . import sale_order from
. import product_template from . import account_move
StealthMicro/OctoPi-Makerbot
env/Lib/site-packages/serial/__init__.py
Python
agpl-3.0
2,971
0.004039
#!/usr/bin/env python # portable serial port access with python # this is a wrapper module for different platform implementations # # (C) 2001-2010 Chris Liechti <cliechti@gmx.net> # this is distributed under a free software license, see license.txt #this variable is kept for backwards compatability VERSION = '2.7-m...
instantiate and open when desired instance = klass(None, *args, **kwargs) instance.port = url if do_open: instance.open() return instance
v-iam/azure-sdk-for-python
azure-mgmt-network/azure/mgmt/network/v2017_06_01/models/load_balancing_rule.py
Python
mit
5,338
0.001311
# 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 ...
re: 'Updating', 'Deleting', and 'Failed'. :type provisioning_state: str :param name: The name of the resource that is unique within a resource group. This name can be used to access the resource. :type name: str :param etag: A
unique read-only string that changes whenever the resource is updated. :type etag: str """ _validation = { 'protocol': {'required': True}, 'frontend_port': {'required': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'frontend_ip_configuration'...
lino-framework/noi
lino_noi/lib/groups/models.py
Python
bsd-2-clause
749
0.001335
# -*- coding: UTF-8 -*- # Copyright 2019 Rumma & Ko Ltd # License: GNU Affero General Public License v3 (see file COPYING for details) from lino.api import dd, _ from lino.utils import join_words from lino_xl.lib.groups.models import * from lino.modlib.users.m
ixins import UserAuthored class Group(Group, UserAuthored): class Meta(Group.Meta): app_label =
'groups' abstract = dd.is_abstract_model(__name__, 'Group') verbose_name = _("Team") verbose_name_plural = _("Teams") dd.update_field(Group, 'user', verbose_name=_("Team manager")) Groups.column_names = 'ref name user *' Groups.detail_layout = """ ref:10 name:60 user id description Memberships...
rty65tt/oper-reader
oper/wsgi.py
Python
gpl-3.0
410
0
#
-*- coding: utf-8 -*- """ WSGI config for oper project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.8/howto/deployment/wsg
i/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "oper.settings") application = get_wsgi_application()
Uberlearner/uberlearner
uberlearner/uberlearner/settings/base/__init__.py
Python
mit
5,935
0.001516
from os.path import join, abspath, dirname, normpath DEBUG = False TEMPLATE_DEBUG = DEBUG PROJECT_ROOT = abspath(join(dirname(__file__), '..', '..', '..')) ADMINS = ( ('Uber Mailman', 'mailman@uberlearner.com'), ) MANAGERS = ADMINS # Local time zone for this installation. Choices can be found here: # http://en...
MEDIA_ROOT. Make sure to use a # trailing
slash. # Examples: "http://media.lawrence.com/media/", "http://example.com/media/" MEDIA_URL = '/media/' # Absolute path to the directory static files should be collected to. # Don't put anything in this directory yourself; store your static files # in apps' "static/" subdirectories and in STATICFILES_DIRS. # Example:...
HomeHabbit/stt-watson
stt_watson/SttWatsonLogListener.py
Python
mit
490
0
from stt_watson.SttWatsonAbstractL
istener import SttWatsonAbstractListener class SttWatsonLogListener(SttWatsonAbstractListener): def __init__(self): pass def listenHypothesis(self, hypothesis): print "Hypothesis: {0}".format(hypothesis) def listenPayload(self, payload): print(u"Text message received: {0}".format...
Hypothesis)
j-be/vj-control-server
vj_serial.py
Python
mit
2,458
0.028885
import logging import struct import threading import serial import serial.tools.list_ports COMMAND_TO_CHANNEL = { 'F': 0x00, 'W': 0x01, 'H': 0x02, 'C': 0x03 } class SerialPort(object): def __init__(self, port_name): self.port_name = port_name self.serial_port = None self.serial_lock = None self.log_thr...
2bin(value) if self.serial_port: try: self.serial_lock.acquire(True
) ret = self.serial_port.write(message) logging.debug("Sent %s Bytes, being", ret) for x in message: logging.debug("%s", self.bin2int(x)) finally: self.serial_lock.release() else: logging.error("Not sending %s, %s - no serial port?", command, value) def send_serial_command(self, command, ...
crancerkill/pokeploud
server/TirageModele.py
Python
apache-2.0
159
0.006289
from google.appengine.ext import ndb class Tirage(ndb.Mode
l):
nomtirage = ndb.StringProperty() datecreation = ndb.DateTimeProperty(auto_now_add=True)
Yury191/brownstonetutors
Client/models.py
Python
unlicense
1,491
0.011402
from django.db import models from django.db.models.signals import post_save, pre_save from django.dispatch import receiver from allauth.account.models import Profile from easymoney import MoneyField def create_client(sender, instance, created, **kwargs): if created and hasattr(instance.user, 'groups') and \ ...
27, blank=True, null=True) def __unicode__(self): if self.billing_name: return unicode(self.billing_name)
return unicode(self.profile) def clean(self): if self.bill_day > 28 or self.bill_day < 1: raise ValidationError("Please enter a day between 1 and 28.")
prashanthpai/swift
swift/proxy/controllers/base.py
Python
apache-2.0
79,133
0
# Copyright (c) 2010-2016 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 the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agree...
opy from sys import exc_info from swift import gettext_ as _ from eventlet import sleep from eventlet.t
imeout import Timeout import six from swift.common.wsgi import make_pre_authed_env from swift.common.utils import Timestamp, config_true_value, \ public, split_path, list_from_csv, GreenthreadSafeIterator, \ GreenAsyncPile, quorum_size, parse_content_type, \ document_iters_to_http_response_body from swift....
akintolga/superdesk-core
apps/publish/formatters/field_mappers/locator_mapper.py
Python
agpl-3.0
4,312
0.000928
# -*- coding: utf-8; -*- # # This file is part of Superdesk. # # Copyright 2013, 2014 Sourcefabric z.u. and contributors. # # For the full copyright and license information, please see the # AUTHORS and LICENSE files distributed with this source code, or # at https://www.sourcefabric.org/superdesk/license from apps.pu...
OLO', '15030000': 'RACE', '15048000': 'RL', '15047000': 'ROW', '15049000': 'RU',
'15050000': 'SAIL', '15051000': 'SHOOT', '15002000': 'SKI', '15010000': 'SNOOK', '15000000': 'SPO', '15054000': 'SOC', '15055000': 'SOFT', '15059000': 'SQSH', '15062025': 'SSWIM', '15062026': 'SSWIM', '15061000': 'SURF', '1506...
jemofthewest/GalaxyMage
src/gui/Input.py
Python
gpl-2.0
12,695
0.002757
# Copyright (C) 2005 Colin McMillen <mcmillen@cs.cmu.edu> # # This file is part of GalaxyMage. # # GalaxyMage 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 opti...
.USEREVENT + 20 RAISE_F_FR_CORNER = pygame.USEREVENT + 21 RAISE_R_BR_CORNER = pygame.USEREVENT + 19 LOWER_B_BL_CORNER = pygame.USEREVENT + 22 LOWER_L_FL_CORNER = pygame.USEREVENT + 24 LOWER_F_FR_CORNER = pygame.USEREVENT + 25 LOWER_R_BR_CORNER = pygame.USEREVENT + 23 RAISE_WATER = pygame.USEREVENT + 26 LOWER_WATER = py...
= pygame.USEREVENT + 32 _input = None def get(): return _input class Event(object): def __init__(self, type_, data): self.type = type_ self.__dict__.update(data) def postUserEvent(type_, data={}): e = Event(type_, data) pygame.event.post(pygame.event.Event(pygame.USEREVENT, ...
vstoykov/django-cms
cms/tests/menu_utils.py
Python
bsd-3-clause
3,494
0.000859
from django.http import HttpResponse from cms.test_utils.testcases import CMSTestCase from cms.test_utils.util.mock import AttributeObject from menus.templatetags.menu_tags import PageLanguageUrl from menus.utils import (simple_language_changer, find_selected, language_changer_decorator) cla...
self.assertEqual(func.__name__, decorated_view.__name__) request = self.get_request('/', 'en') response = decorated_view(request) self.assertEqual(response.content, b'') fake_context = {'request': request} tag = DumbPageLanguageUrl() output = tag.get_context(fake_conte...
.get_context(fake_context, 'ja') url = output['content'] self.assertEqual(url, '/ja/') def test_default_language_changer(self): view = self.get_simple_view() # check we maintain the view name self.assertEqual(view.__name__, view.__name__) request = self.get_request('...
uzumaxy/pyvalid
pyvalid/__init__.py
Python
bsd-3-clause
1,170
0.004281
"""The pyvalid is the Python validation tool for checking a function's input parameters and return values. Purposes of the pyvalid package: #. Provide an ability to validate a user input (such as usernames, phone numbers, emails, dates and times, etc) and minimize t
he amount of code required for the implementation of the comprehensive validat
ion systems; #. Add an additional layer of dynamic code analysis for the development and testing stages — pyvalid will raise the exception if a function accepts or returns unexpected values and it's always possible to disable pyvalid in production if needed. #. Help to catch runtime issues. """ from pyvalid.__a...
thiagodasilva/home_automation
sample/transform_load.py
Python
mit
663
0.001508
#!/usr/bin/env python import json import datetime from influxdb import InfluxDBClient with open('/tmp/temperature.json'
) as temp_json: data = json.load(temp_json) cd = [] m_tim
e = datetime.datetime.today() data_s = sorted(data, key=lambda x: x['created_at'], reverse=True) for m in data_s: m_time = m_time - datetime.timedelta(seconds=20) p = { "measurement": "temp", "time": m_time.strftime("%Y-%m-%d %H:%M:%S"), "tags": { "device": "attic" },...
j00bar/django-widgy
widgy/contrib/urlconf_include/admin.py
Python
apache-2.0
170
0
from django.contrib import admin from
mezzanine.pages.admin import PageAdmin from .models import UrlconfIncludePage
admin.site.register(UrlconfIncludePage, PageAdmin)
Samuel789/MediPi
MedManagementWeb/env/lib/python3.5/site-packages/pyasn1/type/namedtype.py
Python
apache-2.0
14,896
0.001544
# # This file is part of pyasn1 software. # # Copyright (c) 2005-2017, Ilya Etingof <etingof@gmail.com> # License: http://pyasn1.sf.net/license.html # import sys from pyasn1.type import tag, tagmap from pyasn1 import error __all__ = ['NamedType', 'OptionalNamedType', 'DefaultedNamedType', 'NamedTypes'] class NamedTy...
ther): return self.__namedTypes <= other def __gt__(self, other): return self.__namedTypes > other def __ge__(self, other): return self.__namedTypes >= other def __hash__(self): return hash(self.__namedTypes) def __getitem__(self, idx): try: return...
def __iter__(self): return (x[0] for x in self.__namedTypes) if sys.version_info[0] <= 2: def __nonzero__(self): return self.__namedTypesLen > 0 else: def __bool__(self): return self.__namedTypesLen > 0 def __len__(self): return self.__namedTypes...
gencer/sentry
src/sentry/plugins/base/v2.py
Python
bsd-3-clause
13,753
0.000873
""" sentry.plugins.base.v2 ~~~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2010-2013 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from __future__ import absolute_import, print_function __all__ = ('Plugin2', ) import logging import six from django.http import HttpResponse...
eral rule all inherited methods should allow ``**kwargs`` to ensure ease of future compatibility. """ # Generic plugin information title = None slug = None description = None version = None author = None author_url = None resource_links = () # Configuration specifics
conf_key = None conf_title = None project_conf_form = None project_conf_template = 'sentry/plugins/project_configuration.html' # Global enabled state enabled = True can_disable = True # Should this plugin be enabled by default for projects? project_default_enabled = False def _...
marhar/cx_OracleTools
cx_Logging/test/test_threading.py
Python
bsd-3-clause
968
0.017562
import cx_Logging import os import sys import threading if len(sys.argv) > 1: numThreads = int(sys.argv[1]) else: numThreads = 5 if len(sys.argv) > 2: numIterations = int(sys.argv[2]) else: numIterations = 1000 def Run(threadNum): cx_Logging.Debug("Thread-%d: starting", threadNum) iterationsLe...
ions left", threadNum, numFiles, iterationsLeft) iterationsLeft -= 1 cx_Logging.StartLogging("test_threading.log", level = cx_Logging.DEBUG, maxFiles = 10, maxFileSize = 5 * 1024 * 1024, prefix = "[%i] %t") cx_Logging.Debug("Testing logging with %s threads.", numThreads) threads = [] fo...
target = Run, args = (i + 1,)) threads.append(thread) thread.start() for thread in threads: thread.join()
grhawk/ASE
tools/ase/gui/scaling.py
Python
gpl-2.0
19,786
0.003791
# encoding: utf-8 "Module for homogeneous deformation and calculations of elastic constants." import gtk from gettext import gettext as _ from ase.gui.simulation import Simulation from ase.gui.minimize import MinimizeMixin from ase.gui.energyforces import OutputFieldMixin from ase.gui.widgets import oops, pack, AseGu...
utton(None, _("On ")) self.radio_relax_off = gtk.RadioButton(self.radio_relax_on, _("Off")) self.radio_relax_off.set_active(True) pack(vbox2, [
self.radio_relax_on, self.radio_relax_off]) self.make_minimize_gui(vbox2) for r in (self.radio_relax_on, self.radio_relax_off): r.connect("toggled", self.relax_toggled) self.relax_toggled() pack(vbox, [framedef, gtk.Label(" "), framerel]) pack(vbox, gtk.Label("")) ...
veltzer/demos-python
src/examples/short/exception_handling/catch_more_than_one_exception_type.py
Python
gpl-3.0
344
0.005814
#!/usr/bin/env python """ This example shows how to catch more than one exception type in python. The syntax is: except <tuple of exception types> as e: """ def raise_it(a_type): raise a_type('hello') for x in ValueError, RuntimeError: try: raise_it(x) except (ValueError, RuntimeError) as e:...
e))
meisamhe/GPLshared
Programming/MPI — AMath 483 583, Spring 2013 1.0 documentation_files/insertion_deletion_bst.py
Python
gpl-3.0
3,515
0
from binary_tree_prototype import BinaryTreeNode # @include class BinarySearchTree: def __init__(self): self._root = None
# @exclude def empty(self): return self._root is None # @include def insert(self, key): if self.empty(): self._root = BinaryTreeNode(key) else: parent = None curr = self._root while curr: parent = curr ...
curr = curr.left else: # key > curr.data. curr = curr.right # Inserts key according to key and parent. if key < parent.data: parent.left = BinaryTreeNode(key) else: parent.right = BinaryTreeNode(key) return...
s62305/ddgtesting
api-lvl-tests/test_ddg_api_instant_answers.py
Python
gpl-2.0
1,981
0.002527
"""Our instant answers come from a variety of sources, including Wikipedia, Wikia, CrunchBase, GitHub, WikiHow, The Free Dictionary – over 100 in total. Our long-term goal is for all of our instant answers to be available through this open API. Many of these instant answers are open source via our DuckDuckHack platfor...
.get(params=url_params) r.raise_for_status() with pytest.allure.step("'AnswerType' in the response is {!r}".format(expecte
d_ans_type)): data = r.json() ans_type = data['AnswerType'] logger.debug("Expected AnswerType: {!r}".format(expected_ans_type)) logger.debug("Actual AnswerType: {!r}".format(ans_type)) assert ans_type == expected_ans_type with pytest.allure.step("'Answer' in the response is...
stephanepechard/projy
projy/templates/PythonScriptTemplate.py
Python
gpl-3.0
1,236
0.0089
# -*- coding: utf-8 -*- """ Projy template for Python script. """ # system from datetime import date # parent class from projy.templates.ProjyTemplate import ProjyTemplate # collectors from projy.collectors.AuthorCollector import AuthorCollector class PythonScriptTemplate(ProjyTemplate): """ Projy template for a...
lector.collect() ) return sub
stitute_dict
khoulihan/micropython-tmp102
tmp102/extendedmode.py
Python
mit
765
0.003922
def _extend_class(): from tmp102._tmp102 import Tmp102 from tmp102._tmp102 import
_set_bit_for_boolean, EXTENDED_MODE_BIT def _apply_extended_mode(self, config, mode_set): config[1] = _set_bit_for_boolean( config[1], EXTENDED_MODE_BIT, mode_set ) return config def _get_extended_mode(self): return
self._extended_mode def _set_extended_mode(self, val): self._set_config( self._apply_extended_mode( bytearray(self._get_config()), val ) ) Tmp102._apply_extended_mode = _apply_extended_mode Tmp102.extended_mode = property(_get_extended_...
mcclurmc/juju
juju/control/destroy_environment.py
Python
agpl-3.0
1,199
0
from twisted.internet.defer import inlineCallbacks, returnValue from juju.control.utils import get_environment def configure_subparser(subparsers): """Configure destroy-environment subcommand""" sub_parser = subparsers.add_parser( "destroy-environ
ment", help=command.__doc__) sub_parser.add_argument( "--environment", "-e", help="juju environment to operate in.") return sub_parser @inlineCallbacks def command(options): """ Terminate all machines and other as
sociated resources for an environment. """ environment = get_environment(options) provider = environment.get_machine_provider() value = raw_input( "WARNING: this command will destroy the %r environment (type: %s).\n" "This includes all machines, services, data, and other resources. " ...
jroyal/OTTGaaS
generator.py
Python
mit
1,651
0.00848
from PIL import Image from PIL import ImageFont from PIL import ImageDraw from name_generator import get_random_name FONT_SIZE = 14 FONT = ImageFont.truetype("appletext.ttf", FONT_SIZE) def generate_new_tombstone(name, inscription): img = Image.open("created_tombstones/base_tombstone.png") draw = ImageDraw.Dr...
n = 26 split_list = split_inscription(inscription) for i, insc in enumerate(split_list): d
istance = 210 + ((i + 1) * (FONT_SIZE + 10)) draw.text((center(len(insc)), distance), insc, (0,0,0), font=FONT) def center(text_len): mid = text_len / 2 if text_len % 2 == 0: start_loc = 330 + ((4-mid) * FONT_SIZE) + (FONT_SIZE / 2) else: start_loc = 330 + ((4-mid) * FONT_SIZE) ...
JoakimLindbom/agocontrol
devices/squeezebox/pylmsserver.py
Python
gpl-3.0
14,264
0.00673
#!/usr/bin/python # -*- coding: utf-8 -*- """ PyLMS: Python Wrapper for Logitech Media Server CLI (Telnet) Interface Copyright (C) 2013 Tang <tanguy [dot] bonneau [at] gmail [dot] com> LMSServer class is based on JingleManSweep <jinglemansweep [at] gmail [dot] com> This program is free software; you can ...
dify 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 MERCHANTAB...
re 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 telnetlib import urllib from pylmsplayer import Player import threading import...
rendermotion/RMPY
creators/creators.py
Python
lgpl-3.0
1,110
0.001802
from RMPY.creators import curve as CurveCreator from RMPY.creators import spaceLocator from RMPY.creators.skinCluster import SkinCluster from RMPY.creators import group as groupCreator from RMPY.creators import joint as join
tCreator from RMPY.creators import connect as connectCreator from RMPY.creators import controls as controlsCreator from RMPY.creators import constraint as constraintCreator from RMPY.creators import cluste
r as clusterCreator from RMPY.creators import follicle as follicleCreator from RMPY.creators import motionPath as motionPathCreator constraint = constraintCreator.Constraint() controls = controlsCreator.Controls() cluster = clusterCreator.Cluster() curve = CurveCreator.Curve() space_locator = spaceLocator.SpaceLocator...
jumoconnect/openjumo
jumodjango/cust_admin/forms.py
Python
mit
198
0.005051
from django import forms class HiddenRankModelForm(forms.ModelForm): class Meta: widgets = { 'rank': forms.HiddenInput, 'p
osition': forms.HiddenInput,
}
ggabriel96/cfg_analyzer
Symbol.py
Python
unlicense
299
0
class Symbol(): def __init__(self, name, isterm): self.name = name self.isterm = isterm def __str__(self): if self.isterm: if self.name == "": return "&" return "'{}'".format(self.name) r
eturn "<{}>".format(sel
f.name)
aio-libs/sockjs
tests/test_transport_htmlfile.py
Python
apache-2.0
2,175
0.00046
from unittest import mock from aiohttp import web import pytest from aiohttp.test_utils import make_mocked_coro from sockjs.transports import htmlfile @pytest.fixture def make_transport(make_manager, make_request, make_handler, make_fut): def maker(method="GET", path="/", query_params={}): handler = mak...
request = make_request(method, path, query_params=query_params) request.app.freeze() session = manager.get("TestSessionHtmlFile", create=True, request=request) return htmlfile.HTMLFileTransport(manager, session, request) return maker async def test_streaming_send(make_transport): tra...
ake_transport() resp = trans.response = mock.Mock() resp.write = make_mocked_coro(None) stop = await trans.send("text data") resp.write.assert_called_with(b'<script>\np("text data");\n</script>\r\n') assert not stop assert trans.size == len(b'<script>\np("text data");\n</script>\r\n') tran...
haupt235/waldo
modules.py
Python
mit
2,660
0.032707
import pdb import itertools as it def scinot(string): """Takes a string in MCNP scientific notation (without 'E' character), and returns a string of standard scientific notation.""" """If there is no '+' or '-' character in string, returns it as it is.""" """If the argument is not string, returns the argument""" i...
nts.index(event)-1]["cell"]: vtk_file.write(event["x"] + " " + event["y"] + " " + event["z"] + "\n") num_lines = num_events - 1 vtk_file.write("LINES " + str(num_lines) + " " + str(3*num_lines) + "\n") for i in range(num_events-1): vtk_file.write("2 " + str(i) + " " + str(i+1) + "\n") vtk_file.write("CELL_DA
TA 1\n") vtk_file.write("POINT_DATA " + str(num_events) + "\n") vtk_file.write("scalars pointvar float\nLOOKUP_TABLE default\n") vtk_file.write("1.2 1.3 1.4 1.5") def vtk_builder(readable): for event_titles in readable: vtk_file(readable[event_titles], event_titles)
chuck1/web_sheets
old/web_sheets_django/manage.py
Python
mit
822
0.001217
#!/usr/bin/env python3 import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "web_sheets_django.settings.local") try: from django.core.management import execute_from_command_line except ImportError: # The above import may fail for some other reason....
really that Django is missing to avoid masking other # exceptions on Python 2. try:
import django except ImportError: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) raise...
maxalbert/blaze
blaze/compute/sql.py
Python
bsd-3-clause
28,997
0.000138
""" >>> from blaze import * >>> accounts = symbol('accounts', 'var * {name: string, amount: int}') >>> deadbeats = accounts[accounts['amount'] < 0]['name'] >>> from sqlalchemy import Table, Column, MetaData, Integer, String >>> t = Table('accounts', MetaData(), ... Column('name', String, primary_key = True...
import compute_up, compute, base from ..expr import ( Projection, Selection, Field, Broadcast, Expr, IsIn, Slice, BinOp, UnaryOp, Join, mea
n, var, std, Reduction, count, FloorDiv, UnaryStringFunction, strlen, DateTime, Coerce, nunique, Distinct, By, Sort, Head, Label, Concat, ReLabel, Merge, common_subexpression, Summary, Like, nelements, notnull ) from ..expr.broadcast import broadcast_collect from ..expr.math import isnan from ..compatibility ...
flavoi/diventi
diventi/landing/migrations/0011_auto_20180220_0805.py
Python
apache-2.0
786
0.001272
# -*- coding: utf-8 -*- # Ge
nerated by Django 1.11.5 on 2018-02-20 07:05 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('landing', '0010_auto_20180220_0747'), ] operations = [ migrations.RemoveField( model_name='...
name='presentation_covers', ), migrations.AddField( model_name='presentation', name='presentation_covers', field=models.ManyToManyField(blank=True, null=True, to='landing.PresentationCover', verbose_name='presentation covers'), ), ]
johnlb/strange_wp
strange_bak/layout/tables.py
Python
gpl-3.0
32,363
0
# coding: utf-8 """ weasyprint.layout.tables ------------------------ Layout for tables and internal table boxes. :copyright: Copyright 2011-2016 Simon Sapin and contributors, see AUTHORS. :license: BSD, see LICENSE for details. """ from __future__ import division, unicode_literals ...
= None resolve_percentages(group, containing_block=table) group.position_x = rows_x group.position_y = position_y group.width = rows_width new_group_children = [] # For each rows, cells for which this is the last row (with rowspan) ending_cells_by_row = [[]...
in group.children] is_group_start = skip_stack is None if is_group_start: skip = 0 else: skip, skip_stack = skip_stack assert not skip_stack # No breaks inside rows for now for index_row, row in group.enumerate_skip(skip): resol...
huntxu/fuel-web
nailgun/nailgun/extensions/volume_manager/extension.py
Python
apache-2.0
3,207
0
# -*- coding: utf-8 -*- # Copyright 2015 Mirantis, 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 requi...
def set_no
de_volumes(cls, node, volumes): from .objects.volumes import VolumeObject return VolumeObject.set_volumes(node, volumes) @classmethod def set_default_node_volumes(cls, node): from .objects.volumes import VolumeObject try: VolumeObject.set_default_node_volumes(node) ...
BTCfork/hardfork_prototype_1_mvf-core
qa/pull-tester/rpc-tests.py
Python
mit
16,972
0.0033
#!/usr/bin/env python2 # Copyright (c) 2014-2015 The Bitcoin Core developers # Copyright (c) 2016 The Bitcoin developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """ Run Regression Test Suite This module calls down into in...
extended: for t in testScriptsExt: print t else: for t in testScripts: print t if option_passed('extended'): for t in testScriptsExt: print t sys.exit(0) if ENABLE_COVERAGE: coverage = RP...
1 and ENABLE_UTILS == 1 and ENABLE_BITCOIND == 1): rpcTestDir = buildDir + '/qa/rpc-tests/' run_extended = option_passed('exte
dougwig/a10-neutron-lbaas
a10_neutron_lbaas/tests/db/session.py
Python
apache-2.0
1,905
0.000525
# Copyright 2015, A10 Networks # # 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 agr...
odels(): return [model for model in Base._decl_class_registry.values() if model.__module__.startswith('a10_neutron_lbaas.')] def fake_migration_connection(): a10_neutron_lbaas_tables = [model.__tablename__ for model in a10_neutron_lbaas_models()] other_tabl
es = [table for table in Base.metadata.sorted_tables if table.name not in a10_neutron_lbaas_tables] return fake_connection(other_tables)
pmarkiewicz/speedtest
speedtest.py
Python
mit
2,637
0.001896
import argparse import daemon import dateutil.parser import redis_collections import redislite import schedule import subprocess import time from daemon import pidfile from datetime import datetime, timedelta from os import path import sys from helpers import * from log import get_logger MB = 1024.0...
'] = float(info['ping']) return info def save_speed_data(): try: data.append(get_speed()) except Exception as ex: if not is_daemon: print (ex) logger.error(ex) def run_jobs(): try: while True: schedule.run_pending() ...
Exception as ex: if not is_daemon: print (ex) logger.error(ex) finally: redis.shutdown() sys.exit() def start_daemon(): with daemon.DaemonContext(umask=0o002, # -rw-r--r-- pidfile=pidfile.TimeoutPIDLockFile(PID_FILE), ...
electrolinux/pootle
pootle/apps/pootle_app/management/commands/revision.py
Python
gpl-3.0
1,022
0.003914
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # # This file is a part of the Pootle project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. import os os.environ[...
help = "Print the number of the current revision." def handle_noargs(self, **options): if optio
ns.get('restore'): from pootle_store.models import Unit Revision.set(Unit.max_revision()) self.stdout.write('%s' % Revision.get())
amlyj/pythonStudy
2.7/standard_library/study_os.py
Python
mit
3,462
0.000612
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 17-4-19 上午11:02 # @Author : Tom.Lee # @Description : # @File : helper_os.py # @Product : PyCharm import commands import os import sys def shell(): command_ls = 'ls -al /opt' command_docker = 'docker ps -a' # 使用...
s.path.dirname(os.path.dirname(__file__)), "templates") print '添加文件路径到系统环境变量: ' if root_path not in sys.path: sys.path.append(root_path) print sys.path if '__main__' == __name__: """TEST MAIN""" # sh
ell() # sys_path() # print os.path.abspath(os.path.join('/opt/tom/', '..', 'bin')) # /opt/bin # print os.path.dirname('/opt/tom') print '\033[1;31;m os.listdir() ==> \033[0m', os.listdir(os.getcwd()) print'\033[1;31;m os.getcwd() ==> \033[0m', os.getcwd() print '\033[1;31;m os.getcwdu() ==> \03...
jeremiahsavage/bam_reheader
bam_reheader/main.py
Python
apache-2.0
2,824
0.012394
#!/usr/bin/env python import argparse import logging import os import subprocess import sys def setup_logging(args, bam_name): log
ging.basicConfig( filename=os.path.join(bam_n
ame + '.log'), level=args.level, filemode='w', format='%(asctime)s %(levelname)s %(message)s', datefmt='%Y-%m-%d_%H:%M:%S_%Z', ) logger = logging.getLogger(__name__) return logger def get_bam_header(bam_path): bam_name = os.path.basename(bam_path) header_name = bam_n...
houssine78/addons
mrp_brewing/models/stock.py
Python
agpl-3.0
3,749
0
# -*- coding: utf-8 -*- # Part of Open Architechts Consulting sprl. See LICENSE file for full copyright and licensing details. # noqa # Copyright 2019 Coop IT Easy SCRLfs from openerp import api, fields, models, _, SUPERUSER_ID class StockMove(models.Model): _inherit = "stock.move" @api.model ...
l") @api.multi @api.depends('location_id', 'location_dest_id') def _compute_is_internal(self): for move in self: move.is_internal = ( move.location_id.usage == 'internal' and move.location_dest_id.usage == 'internal' ) ...
pute_product_domain(self, is_internal): if is_internal: domain = [('type', 'in', ['product', 'consu']), ('sale_ok', '=', True)] else: domain = [('type', 'in', ['product', 'consu'])] return domain @api.onchange('is_internal') def o...
jaimeantena4040/MiSitioWeb
lib/bb/tests/fetch.py
Python
gpl-2.0
36,571
0.007137
# ex:ts=4:sw=4:sts=4:et # -*- tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- # # BitBake Tests for the Fetcher (fetch2/) # # Copyright (C) 2012 Richard Purdie # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # publis...
'hostport': 'cvs.handhelds.org', 'path': '/cvs', 'userinfo': 'anoncvs:anonymous', 'username': 'anoncvs', 'password': 'anonymous
', 'params': { 'tag': 'V0-99-81', 'module': 'familiar/dist/ipkg' }, 'query': {}, 'relative': False }, "file://example.diff": { # NOTE: Not RFC compliant! 'uri': 'file:example.diff', 'scheme': 'file', ...