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 |
|---|---|---|---|---|---|---|---|---|
emillon/glyr-debian | spec/provider/tests/artistphoto.py | Python | gpl-3.0 | 3,340 | 0.000599 | #################################################################
# This file is part of glyr
# + a command-line tool and library to download various sort of music related metadata.
# + Copyright (C) [2011-2012] [Christopher Pahl]
# + Hosted at: https://github.com/sahib/glyr
#
# glyr is free software: you can redistri... | _equal_0
}],
}, {
# }}}
# {{{
'name': 'flickr',
'data': [{
'options': {
'ge | t_type': 'artistphoto',
'artist': 'Die Ärzte'
},
'expect': len_greater_0
}, {
'options': not_found_options,
'expect': len_equal_0
}],
}, {
# }}}
# {{{
'name': 'google',
'data': [{
'options': {
'get_type': 'artistphot... |
MazaCoin/maza | test/functional/test_framework/messages.py | Python | mit | 38,295 | 0.002141 | #!/usr/bin/env python3
# Copyright (c) 2010 ArtForz -- public domain half-a-node
# Copyright (c) 2012 Jeff Garzik
# Copyright (c) 2010-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.
"""Bitcoin test... | lf.nSequence = struct.unpack("<I", f.read(4))[ | 0]
def serialize(self):
r = b""
r += self.prevout.serialize()
r += ser_string(self.scriptSig)
r += struct.pack("<I", self.nSequence)
return r
def __repr__(self):
return "CTxIn(prevout=%s scriptSig=%s nSequence=%i)" \
% (repr(self.prevout), bytes_to_h... |
RPCS3/ps3autotests | utils/convert-ps3-output.py | Python | gpl-2.0 | 868 | 0.008065 | import os
import sys
def main():
if len(sys.argv) <= 2:
print("This script generates the .expected file from your PS3's de | bug logs.")
print("")
print("Usage: convert-ps3-output.py <input> <output>")
print("Example: convert-ps3-output.py | hello_world.log hello_world.expected")
return False
#Parse and check arguments
inputFile = sys.argv[1]
outputFile = sys.argv[2]
if not os.path.isfile(inputFile):
print("[!] Input file does not exist")
return False
f = open(inputFile, 'rb')
w = open(outputFile, 'wb')
... |
mjlong/openmc | openmc/tallies.py | Python | mit | 100,934 | 0.000545 | from __future__ import division
from collections import Iterable, defaultdict
import copy
import os
import pickle
import itertools
from numbers import Integral, Real
from xml.etree import ElementTree as ET
import sys
import numpy as np
from openmc import Mesh, Filter, Trigger, Nuclide
from openmc.cross import CrossS... | self._sum = None
self._sum_sq = None
self._mean = None
self._std_dev = None
self._with_batch_statistics = False
self._derived = False
self._sp_filename = None
self._results_read = False
def __deepcopy__(self, memo):
existing | = memo.get(id(self))
# If this is the first time we have tried to copy this object, create a copy
if existing is None:
clone = type(self).__new__(type(self))
clone.id = self.id
clone.name = self.name
clone.estimator = self.estimator
clone.num_... |
KeyWeeUsr/KrySA | krysa/tests/test_tasks_basic_small.py | Python | gpl-3.0 | 3,977 | 0.000503 | import unittest
import os
import sys
import time
import sqlite3
import os.path as op
from shutil import rmtree
from functools import partial
from kivy.clock impor | t Clock
main_path = op.dirname(op.dirname(op.abspath(__file__)))
sys.path.append(main_path)
from main import KrySA, ErrorPop
from tasks.basic import Basic
class Test(unittest.TestCase):
def pause(*args):
time.sleep(0.000001)
def run_test(self, app, *args):
Clock.schedule_interval(self. | pause, 0.000001)
# open New -> Project popup, set inputs
app.root._new_project()
app.root.savedlg.view.selection = [self.folder, ]
app.root.savedlg.ids.name.text = 'Test.krysa'
app.root.savedlg.run([self.folder, ], 'Test.krysa')
project_folder = op.join(self.path, 'test_... |
google/sling | sling/nlp/parser/trainer/transition_generator.py | Python | apache-2.0 | 12,819 | 0.012637 | # Copyright 2017 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 or agreed to in writing, s... | e.info.handle)
elif action.type == Action.EMBED:
action.label = simple.info.type
action.target = attention.index(simple.other_info.handle)
elif action.type = | = Action.ELABORATE:
action.label = simple.info.type
action.source = attention.index(simple.other_info.handle)
elif action.type == Action.CONNECT:
action.source = attention.index(simple.info.handle)
action.target = attention.index(simple.other_info.handle)
elif action.type == Action.ASSIG... |
skosukhin/spack | var/spack/repos/builtin/packages/bpp-suite/package.py | Python | lgpl-2.1 | 1,771 | 0.001129 | ##############################################################################
# Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-64... | RANTY OF
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and
# conditions of the GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temp... | import *
class BppSuite(CMakePackage):
"""BppSuite is a suite of ready-to-use programs for phylogenetic and
sequence analysis."""
homepage = "http://biopp.univ-montp2.fr/wiki/index.php/BppSuite"
url = "http://biopp.univ-montp2.fr/repos/sources/bppsuite/bppsuite-2.2.0.tar.gz"
version('2.... |
rodrigods/keystone | keystone/tests/test_backend.py | Python | apache-2.0 | 205,792 | 0.000005 | # Copyright 2012 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 agreed to in... | y_api.authenticate(
co | ntext={},
user_id=self.user_sna['id'],
password=self.user_sna['password'])
# NOTE(termie): the password field is left in user_sna to make
# it easier to authenticate in tests, but should
# not be returned by the api
self.user_sna.pop('p... |
xiangke/pycopia | core/pycopia/OS/Linux/firewall.py | Python | lgpl-2.1 | 1,458 | 0.006173 | #!/usr/bin/python2.4
# vim:ts=4:sw=4:softtabstop=4:smarttab:expandtab
#
# $Id$
#
# Copyright (C) 1999-2006 Keith Dart <keith@kdart.com>
#
# This library 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... | t your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
"""
Module for managin... | rt socketlib
def port_forward(srcport, destport, rule=None):
"""Use firewall rule to forward a TCP port to a different port. Useful for
redirecting privileged ports to non-privileged ports. """
return NotImplemented
def add(rule, action):
return NotImplemented
def delete(rule):
return NotImplem... |
daverstephens/The-SOC-Shop | Threat_Intel/GScraper.py | Python | gpl-2.0 | 1,824 | 0.014254 | #requirements: selenium wget python2.7 Geckodriver
import time
import sys
import wget
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.keys ... | x in range(0,len(results)):
link = results[x].find_element_by_tag_name("a")
| href = link.get_attribute("href")
print href
wget.download(href)
browser.quit()
return
if len(sys.argv) == 3:
domain = sys.argv[1]
ftype = sys.argv[2]
url = "https://www.google.com/search?num=100&start=0&hl=em&meta=&q=site:"
url += domain
ur... |
cdecker/pycoin | tests/test_network.py | Python | bsd-3-clause | 8,572 | 0 | from bitcoin import network
from bitcoin import messages
from io import BytesIO
from mock import patch
from gevent import socket
import mock
import os
import unittest
__author__ = 'cdecker'
BASENAME = os.path.dirname(__file__)
class TestNetworkClient(unittest.TestCase):
def test_parser(self):
"""Test ... | connection.send(p.type, p)
wire = BytesIO(connection.socket.send.call_args[0][0])
def recv(n):
return wire.read(n)
connection.socket.recv = recv
message = connection.read_message()
self.assertTrue(isinstance(message, messages.GetDataPacket))
# This shou... | ertRaises(ValueError, connection.read_message)
# This will raise a non-matching magic error
wire = BytesIO("BEEF" + connection.socket.send.call_args[0][0][4:])
self.assertRaises(ValueError, connection.read_message)
class TestGeventNetworkClient(unittest.TestCase):
def test_init(self):
... |
micgro42/ReceiptEval | receipteval/receipt_collection.py | Python | gpl-3.0 | 3,399 | 0 | # -*- coding: utf-8 -*-
'''
Created on Nov 30, 2014
@author: Michael Große <mic.grosse@posteo.de>
'''
from collections import defaultdict
from receipteval.item_cat_dict import ItemCategoryDict
class ReceiptCollection(object):
'''
Collection of purchases with evaluation and output options.
'''
def __... | tems belonging to more than one category
'''
all_items = set()
for category in self.categories:
if category is '':
continue
for item in self.categories[category][1]:
if item in all_items:
self.unsane_items.append(item)
... | all_items.add(item)
def calculate_total(self):
'''
calculate the grand total across all categories
'''
self.total = 0.0
for category in self.categories:
self.total += self.categories[category][0]
def get_ledger(self, date='1900-01-01'):
'''
... |
raptorbird/RAVN | tests/runtests.py | Python | gpl-2.0 | 227,702 | 0.00004 | #! /usr/bin/env python
sources = """
eNrsvWt3HEl2IDa7fqy3bK0kW1577WOfnKKpzGwWkiCnJY2wXd3q4ZAjanqaPHxoWgcNFRNVCSAH
icpiZhYBaDR7/CP83T/CX/3df8v3Fc+MzCqwu2fkc9zSEEBVxI2IGzfuK+698b//69+9/1Hy9k82
t9miqs+zxaJcl91i8f5fvf276XQawWfn5fo8+vLl8yiJN0292i6Lpo2jfL2K4mW9brdX9Df8ui6W
XbGKPpR5dFncXtfNqk0jADKZvP/Xb/8NjtB2q/f/2Zv/81/96Ef... | htqNkks4piLG/OlThPZYX
bcRqvzcWgU3xjTPORZxFWDBo6FrO3dT7B48OkVqpTI+EWepJDqxlbHP1bQflbSnw335LDnMCPwRV
l9EY/lq8JRu625UfgjGcdJFfzZUpiwzuuilBVx/Utb7iwy+OXpcxaHNzYcI0RON0layQuq3lka2i
e5FLP7jS1N+ke8YO6OUSmFyWmRWNc4jZL7+hcNPhIR13wgElvAyPY/JdBhiosogZhJWD2HfJhRGn
LGptXgc6BnIfj3z3J+deKN+fNPdIadOIVcF1CLR9wnuthJalqTipJ9r4VNqIUvB7qr2... | 3YUiuAwfa1dFz1CxvfiGHwvMTEU2q6ZpqGZBXpm
L1Y8UiFN+eg7KLif9rXZ3tzsaHuxJ3kqxqbX22bCq/vVwmxn1B7+mHW/glOanRbI3ysaq08c4qJ5
8Xo8SSQUrYtCeb1BcSzimcGnoZR0otf1ZhICOyA+XEPASUUxd9X6sPRu35UGqq9HPPQZGNYNAoce
2vtrB88FEuC0PeBcHL7arrvyqggFc/QgmtG9SD0zCwpntFo6Xmt13+OIAqDlJpc0FWfKnPHEfLEf
R2du372wRQm+SHgmImJSm10hl+pxBLo9sx3vQQVBqQa0zb1wy... |
sqlalchemy/alembic | alembic/runtime/environment.py | Python | mit | 38,523 | 0 | from typing import Callable
from typing import ContextManager
from typing import Dict
from typing import List
from typing import Optional
from typing import overload
from typing import TextIO
from typing import Tuple
from typing import TYPE_CHECKING
from typing import Union
from .migration import MigrationContext
from... | This is only meaningful in "offline" mode.
Returns ``None`` if no value is available
or was configured.
This function does not require that the :class:`.MigrationContext`
has been configured.
"""
if self._migration_context is not None:
return self.script.a... | self.context_opts["starting_rev"]
)
else:
# this should raise only in the case that a command
# is being run where the "starting rev" is never applicable;
# this is to catch scripts which rely upon this in
# non-sql mode or similar
... |
yzl0083/orange | Orange/OrangeWidgets/Prototypes/OWPerformanceCurves.py | Python | gpl-3.0 | 7,520 | 0.007314 | """<name>Performance Curves</name>
<description>Model performance at different thresholds</description>
<icon>icons/PerformanceCurves.png</icon>
<priority>30</priority>
<contact>Janez Demsar (janez.demsar@fri.uni-lj.si)</contact>"""
from OWWidget import *
from OWGUI import *
from PyQt4.QtGui import *
from PyQt4.QtCore... | nd], alls[-4][ind], alls[-3][ind])
if self.selectedScores:
stat += "<b>Performance</b><br/>"
stat += "<br/>".join("%s: %.2f" % (self.scores[i], alls[i][ind]) for i in self.selectedScores)
self.statistics = | stat
def sendReport(self):
if self.res:
self.reportSettings(_("Performance Curves"),
[(_("Model"), self.res.classifierNames[self.selectedClassifier[0]]),
(_("Target class"), self.res.classValues[self.targetClass])])
... |
serge-sans-paille/pythran | pythran/tests/cases/monte_carlo.py | Python | bsd-3-clause | 1,346 | 0.008915 | # http://code.activestate.com/recipes/577263-numerical-integration-using-monte-carlo-method/
# Numerical Integration using Monte Carlo method
# FB - 201006137
#pythran export montecarlo_integration(float, float, int, float list, int)
#runas montecarlo_integration(1.,10.,100,[x/100. for x in range(100)],100)
#bench mont... | min)
numPoints = numSteps # bigger the better but slower!
ctr = 0
for j in range(numPoints):
x = xmin + (xmax - xmin) * rand[j%randsize]
y = ymin + (ymax - ymin) * rand[j%randsize]
if math.fabs(y) <= math.fabs(f(x)):
if f(x) | > 0 and y > 0 and y <= f(x):
ctr += 1 # area over x-axis is positive
if f(x) < 0 and y < 0 and y >= f(x):
ctr -= 1 # area under x-axis is negative
fnArea = rectArea * float(ctr) / numPoints
return fnArea
|
Telestream/telestream-cloud-python-sdk | telestream_cloud_qc_sdk/telestream_cloud_qc/models/active_format_test.py | Python | mit | 4,684 | 0 | # coding: utf-8
"""
Qc API
Qc API # noqa: E501
The version of the OpenAPI document: 3.0.0
Contact: cloudsupport@telestream.net
Generated by: https://openapi-generator.tech
"""
import pprint
import re # noqa: F401
import six
from telestream_cloud_qc.configuration import Configuration
class... | reject_on_error=None, checked=None, local_vars_configuration=None): # noqa: E501
"""ActiveFormatTest - a model defined in OpenAPI""" # noqa: E501
if local_vars_configuration is None:
local_vars_configuration = Configuration()
self.local_vars_configuration = local_vars_configuration... | on_error = None
self._checked = None
self.discriminator = None
if afd is not None:
self.afd = afd
if reject_on_error is not None:
self.reject_on_error = reject_on_error
if checked is not None:
self.checked = checked
@property
def afd(... |
altsen/diandiyun-platform | common/lib/xmodule/xmodule/modulestore/django.py | Python | agpl-3.0 | 7,244 | 0.001242 | """
Module that provides a connection to the ModuleStore specified in the django settings.
Passes settings.MODULESTORE as kwargs to MongoModuleStore
"""
from __future__ import absolute_import
from importlib import import_module
import re
from django.conf import settings
from django.core.cache import get_cache, Inval... | ave the request_cache module available
try:
from request_cache.middleware import RequestCache
HAS_REQUEST_CACHE = True
except ImportError:
HAS_REQUEST_CACHE = False
_MODULESTORES = {}
FUNCTION_KEYS = ['render_template']
def load_function(path):
"""
Load a function by name.
path is a string ... | rns the imported python object `function` from `path.to.module`
"""
module_path, _, name = path.rpartition('.')
return getattr(import_module(module_path), name)
def create_modulestore_instance(engine, doc_store_config, options, i18n_service=None):
"""
This will return a new instance of a modulesto... |
henrywm/URI | src/beginner/1042.py | Python | apache-2.0 | 431 | 0.027842 | a,b,c | = input().split(" ")
numbers = [int(a),int(b),int(c)]
cnumbers | = list(numbers)
for j in range(0,len(numbers)):
for i in range(0,len(numbers)-1):
if numbers[i] > numbers[i+1]:
aux = numbers[i+1]
numbers[i+1] = numbers[i]
numbers[i] = aux
for a in range(len(numbers)):
print(numbers[a])
print("")
for b in range(len(cnumb... |
perkinslr/schemepy | scheme/syntax_rules.py | Python | lgpl-2.1 | 1,919 | 0.007817 | from __future__ import unicode_literals
from zope.interface import implements, classProvides
from scheme.macro import Macro
from scheme.symbol import Symbol
from scheme.environment import Environment, SyntaxEnvironment
from scheme.syntax import SyntaxSymbol
from scheme.PatternMatcher import PatternMatcher
# from sche... | name))
import scheme.Globals
scheme.Gl | obals.Globals['syntax-rules'] = syntax_rules
|
blancltd/blanc-basic-pages | blanc_basic_pages/models.py | Python | bsd-3-clause | 2,112 | 0.002367 | from __future__ import unicode_literals
from blanc_basic_assets.fields import AssetForeignKey
from django.core.exceptions import ValidationError
from django.core.urlresolvers import get_script_prefix
from django.core.validators import RegexValidator
from django.db import m | odels
from django.utils.encoding import iri_to_uri, python_2_unicode_compatible
from mptt.managers import TreeManager
from mptt.models import MPTTModel, TreeForeignKey
# Validator from flatpages
url_valid | ator = RegexValidator(regex=r'^[-\w/\.~]+$',
message="This value must contain only letters, numbers, dots, "
"underscores, dashes, slashes or tildes.")
# Another validator to ensure the URL starts and ends with a slash
def slash_validator(url):
... |
hamsterbacke23/wagtail | wagtail/wagtailsnippets/edit_handlers.py | Python | bsd-3-clause | 2,653 | 0.001508 | from __future__ import absolute_import, unicode_literals
import warnings
from django.core.exceptions import ImproperlyConfigured
from django.template.loader import render_to_string
from django.utils.s | afestring import mark_safe
from wagtail.utils.deprecation import RemovedInWagtail16Warning
from wagtail.wagtailadmin.edit_handlers import BaseChooserPanel
from wagtail.wagtailcore.utils import resolve_model_string
from .widgets import AdminSnippetChooser
class BaseSnippetChooserPanel(BaseChooserPanel):
| object_type_name = 'item'
_target_model = None
@classmethod
def widget_overrides(cls):
return {cls.field_name: AdminSnippetChooser(model=cls.target_model())}
@classmethod
def target_model(cls):
if cls._target_model is None:
if cls.snippet_type:
# Rem... |
VaysseB/id_generator | src/parser.py | Python | gpl-3.0 | 15,217 | 0.00092 |
import string
import ast
from state_machine import PSM, Source
class SpecialPattern:
individual_chars = ('t', 'n', 'v', 'f', 'r', '0')
range_chars = ('d', 'D', 'w', 'W', 's', 'S')
special_chars = ('^', '$', '[', ']', '(', ')', '{', '}', '\\', '.', '*',
'?', '+', '|', '.')
rest... | p.UngreedyQuantified:
psm.error = | "quantifier repeated"
# <<< Quantifier
else:
t = ast.SingleChar()
t.char = psm.char
self.add(t)
return self.limited_prev
def _last_or_fail(self, psm: PSM):
if self.parent.g.group.seq:
return self.parent.g.group.seq[-1]
el... |
radiasoft/sirepo | sirepo/template/flash_views.py | Python | apache-2.0 | 27,201 | 0.00114 | # -*- coding: utf-8 -*-
u"""Flash Config parser.
:copyright: Copyright (c) 2021 RadiaSoft LLC. All Rights Reserved.
:license: http://www.apache.org/licenses/LICENSE-2.0.html
"""
from pykern import pkio
from pykern.pkcollections import PKDict
from pykern.pkdebug import pkdc, pkdp, pkdlog
import inspect
import re
def... | ble {}'],
['refine_cutoff_{}', 'Refine Variable {}'],
['derefine_cutoff_{}', 'Derefine Variable {}'],
], [str(v) for v in range(1, 7)]),
)
_VIEW_FUNC_PREFIX = '_view_'
def __init__(self):
self._view_fns = PKDict() |
for n, o in inspect.getmembers(self):
if n.startswith(self._VIEW_FUNC_PREFIX) and inspect.ismethod(o):
self._view_fns[n[len(self._VIEW_FUNC_PREFIX):]] = o
def update_schema(self, schema):
self._update_labels(schema)
self._update_views(schema)
return sche... |
abel-von/commons | tests/python/twitter/common/zookeeper/serverset/test_serverset_unit.py | Python | apache-2.0 | 2,836 | 0.0067 | # ==================================================================================================
# Copyright 2013 Twitter, Inc.
# --------------------------------------------------------------------------------------------------
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use thi... | 2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WAR | RANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==================================================================================================
from twitter.common.zookeeper.serverset.endpoint impo... |
UnbDroid/robomagellan | Codigos/Raspberry/desenvolvimentoRos/devel/lib/python2.7/dist-packages/tf2_msgs/srv/_FrameGraph.py | Python | gpl-3.0 | 7,187 | 0.016558 | # This Python file uses the following encoding: utf-8
"""autogenerated by genpy from tf2_msgs/FrameGraphRequest.msg. Do not edit."""
import sys
python3 = True if sys.hexversion > 0x03000000 else False
import genpy
import struct
class FrameGraphRequest(genpy.Message):
_md5sum = "d41d8cd98f00b204e9800998ecf8427e"
_... | lf
except struct.error as e:
raise genpy.Des | erializationError(e) #most likely buffer underfill
_struct_I = genpy.struct_I
class FrameGraph(object):
_type = 'tf2_msgs/FrameGraph'
_md5sum = '437ea58e9463815a0d511c7326b686b0'
_request_class = FrameGraphRequest
_response_class = FrameGraphResponse
|
namhyung/uftrace | tests/t139_kernel_dynamic2.py | Python | gpl-2.0 | 1,228 | 0.000814 | #!/usr/bin/env python
import os
from runtest import TestBase
class TestCase(TestBase):
def __init__(self):
TestBase.__init__(self, 'openclose', serial=True, result="""
# DURATION TID FUNCTION
[ 9875] | main() {
[ 9875] | fopen() {
14.416 us [ 9875] | sys_open();
1... | (self, cflags, result):
uname = os.uname()
# Linux v4.17 (x86_64) changed syscall routines
major, minor, release = uname[2].split('.')
if uname[0] == 'Linux' and uname[4] == 'x86_64' and \
int(major) >= 5 or (int(major) == 4 and int(minor) >= 17):
return result.re... | x64_sys_openat')
else:
return result.replace(' sys_open', ' sys_openat')
|
neuropil/boltons | boltons/dictutils.py | Python | bsd-3-clause | 24,228 | 0.000124 | # -*- coding: utf-8 -*-
"""Python has a very powerful mapping type at its core: the :class:`dict`
type. While versatile and featureful, the :class:`dict` prioritizes
simplicity and performance. As a result, it does not retain the order
of item insertion [1]_, nor does it store multiple values per key. It
is a fast, uno... | todict()`.
>>> pp(omd.todict())
{'a': 3, 'b': 2}
>>> pp(omd.todict(multi=True))
{'a': [1, 3], 'b': [2]}
With ``multi=False``, items appear with the keys in t | o original
insertion order, alongside the most-recently inserted value for
that key.
>>> OrderedMultiDict([('a', 1), ('b', 2), ('a', 3)]).items(multi=False)
[('a', 3), ('b', 2)]
"""
def __init__(self, *args, **kwargs):
if len(args) > 1:
raise TypeError('%s expected at most ... |
AutorestCI/azure-sdk-for-python | azure-mgmt-network/azure/mgmt/network/v2017_09_01/models/security_group_view_result.py | Python | mit | 1,116 | 0.000896 | # 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 ... | cified VM.
:param network_interfaces: List of network interfaces on the specified VM.
:type network_interfaces:
list[~azure.mgmt.network.v2017_09_01.models.SecurityGroupNetworkInterface]
"""
_attribute_map = {
'network_interfaces': {'key': 'networkInterfaces', 'type': '[SecurityGroupNetwo... | __init__(self, network_interfaces=None):
super(SecurityGroupViewResult, self).__init__()
self.network_interfaces = network_interfaces
|
j5shi/Thruster | pylibs/test/test_structmembers.py | Python | gpl-2.0 | 3,646 | 0.001646 | import unittest
from test import test_support
# Skip this test if the _testcapi module isn't available.
test_support.import_module('_testcapi')
from _testcapi import _test_structmembersType, \
CHAR_MAX, CHAR_MIN, UCHAR_MAX, \
SHRT_MAX, SHRT_MIN, USHRT_MAX, \
INT_MAX, INT_MIN, UINT_MAX, \
LONG_... | ReadWriteTests(unittest.TestCase):
def test_bool(self):
ts.T_BOOL = True
self.assertEqual(ts.T_BOOL, True)
ts.T_BO | OL = False
self.assertEqual(ts.T_BOOL, False)
self.assertRaises(TypeError, setattr, ts, 'T_BOOL', 1)
def test_byte(self):
ts.T_BYTE = CHAR_MAX
self.assertEqual(ts.T_BYTE, CHAR_MAX)
ts.T_BYTE = CHAR_MIN
self.assertEqual(ts.T_BYTE, CHAR_MIN)
ts.T_UBYTE... |
bjpop/berp | test/regression/features/assignment/assign_unpack.py | Python | bsd-3-clause | 796 | 0.04397 | # singleton tuple <- singleton tuple
| x, = 0,
print(x)
# singleton tuple <- singleton list
x, = [-1]
print(x)
# binary tuple <- binary tuple
x,y = 1,2
print(x,y)
# binary tuple swap
x,y = y,x
print(x,y)
# ternary tuple <- ternary tuple
x,y,z = 3,4,5
print(x,y,z)
# singleton list <- singleton list
[x] = [42]
print(x)
# singleton list <- singleton tuple
[x] ... | y] = [44,45]
print(x,y)
# binary tuple (parens) <- binary list
(x,y) = [7,8]
print(x,y)
# binary tuple <- result of function call
(x,y) = (lambda: (9,10))()
print(x,y)
# nested binary tuple (parens) <- nested binary tuple (parens)
((x,y),z) = ((11,12),13)
print(x,y,z)
# nested binary tuple <- nested binary tuple
(x,y),... |
cloudera/hue | apps/sqoop/src/sqoop/sqoop_properties.py | Python | apache-2.0 | 1,837 | 0.009799 | #!/usr/bin/env python
# Licensed to Cloudera, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Cloudera, Inc. licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you ma... | = 'org.apache.sqoop.security.authentication.type'
def reset():
global _PROPERTIES_DICT
_PROPERTIES_DICT = None
def get_props():
if _PROPERTIES_DICT is None:
_parse_properties()
return _PROPERTIES_DICT
def has_sqoop_has_security():
return get_props().get(_CONF_SQOOP_AUTHENTICATION_TYPE, 'SI | MPLE').upper() == 'KERBEROS'
def _parse_properties():
global _PROPERTIES_DICT
properties_file = os.path.join(SQOOP_CONF_DIR.get(), 'sqoop.properties')
_PROPERTIES_DICT = _parse_site(properties_file)
def _parse_site(site_path):
try:
with open(site_path, 'r') as f:
data = f.read()
except IOError... |
ovaistariq/mha-helper | mha_helper/__init__.py | Python | gpl-3.0 | 900 | 0 | # (c) 2013, Ovais Tariq <me@ovaistariq.net>
#
# This file is part of mha_helper
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version | 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without | even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# -*- coding: utf-8 -*-
__name__ = ... |
meganbkratz/acq4 | acq4/analysis/old/StdpCtrlTemplate.py | Python | mit | 3,654 | 0.00301 | # -*- coding: utf-8 -*-
from __future__ import print_function
# Form implementation generated from reading ui file './acq4/analysis/old/StdpCtrlTemplate.ui'
#
# Created: Tue Dec 24 01:49:15 2013
# by: PyQt4 UI code generator 4.10
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, ... | return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGu | i.QApplication.translate(context, text, disambig)
class Ui_StdpCtrlWidget(object):
def setupUi(self, StdpCtrlWidget):
StdpCtrlWidget.setObjectName(_fromUtf8("StdpCtrlWidget"))
StdpCtrlWidget.resize(227, 321)
self.gridLayout = QtGui.QGridLayout(StdpCtrlWidget)
self.gridLayout.setMarg... |
enfancemill/baobaocloud | baobaologic/config.py | Python | gpl-3.0 | 260 | 0 | # coding: utf-8
class ActMail | (object):
subject = '宝宝云帐号注册激活邮件'
content = '感谢您申请注册宝宝云账号! 请点击链接完成注册: '
source = 'enfancemill@gmail.com'
secret = 'kwhr8xkq4eoq6bvvh6nvr6 | 267lrdcqb2'
|
miteshvp/fabric8-analytics-worker | f8a_worker/workers/cvedbsync.py | Python | gpl-3.0 | 4,809 | 0.004367 | """Update vulnerability sources."""
from selinon import StoragePool
from f8a_worker.base import BaseTask
from f8a_worker.enums import EcosystemBackend
from f8a_worker.models import Ecosystem
from f8a_worker.solver import get_ecosystem_solver, OSSIndexDependencyParser
from f8a_worker.workers import CVEcheckerTask
clas... | ly_already_scanned' to run only
on already analysed packages
:return: EPV dict describing which packages should be analysed
"""
only_already_scanned = arguments.pop('only_already_scanned', True) if arguments else True
ignore_modification_time = (arguments.pop('ignore_modification... | if arguments else False)
CVEcheckerTask.update_victims_cve_db_on_s3()
self.log.debug('Updating sync associated metadata')
s3 = StoragePool.get_connected_storage('S3VulnDB')
previous_sync_timestamp = s3.update_sync_date()
if ignore_modification_time:
previous... |
cligu/gitdox | modules/gitdox_sql.py | Python | apache-2.0 | 8,292 | 0.032562 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Data access functions to read from and write to the SQLite backend.
"""
import sqlite3
import codecs
import os
import re
def setup_db():
dbpath = os.path.dirname(os.path.realpath(__file__)) + os.sep +".."+os.sep+"gitdox.db"
conn = sqlite3.connect(dbpath)
cur = co... | uery("DELETE FROM metadata WHERE docid=?", (id,))
def cell(text):
if isinstance(text, int):
text = str(text)
return "\n <td>" + text + "</td>"
def update_meta(meta_id,doc_id,key,value,corpus=False):
if corpus:
_, corpus_name, _, _, _, _, _ = get_doc_info(doc_id)
generic_query("REPLACE INTO metadata(metaid,do... | name))
else:
generic_query("REPLACE INTO metadata(metaid,docid,key,value,corpus_meta) VALUES(?,?,?,?,?)",(meta_id,doc_id,key,value,None))
invalidate_doc_by_id(doc_id)
def save_meta(doc_id,key,value,corpus=False):
if corpus:
_, corpus_name, _, _, _, _, _ = get_doc_info(doc_id)
new_id = generic_query("REPLACE... |
bwc126/MLND-Subvocal | simple_svr.py | Python | mit | 290 | 0.003448 | i | mport pcf8591read
"""
This is a barebones script for controlling the work flow of recording EMG words and associating the data with a specific word, captured in the filename.
"""
reader = pcf8591read.adc_reader()
filename = input('Current word:')
reader.record = True
reader.run(fil | ename)
|
plotly/python-api | packages/python/plotly/plotly/validators/volume/_reversescale.py | Python | mit | 457 | 0.002188 | import _plotly_utils.basevalidators
cl | ass ReversescaleValidator(_plotly_utils.basevalidators.BooleanValidator):
def __init__(self, plotly_name="reversescale", parent_name="volume", **kwargs):
super(ReversescaleValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop | ("edit_type", "calc"),
role=kwargs.pop("role", "style"),
**kwargs
)
|
dims/nova | nova/cmd/dhcpbridge.py | Python | apache-2.0 | 5,189 | 0.000193 | # Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# 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 ... | nova-dhcpbridge: %s'),
stacktrace)
raise exception.DBNotAllowed('nova-dhcpbridge')
nova.db.api.IMPL = NoDB()
def main():
"""Parse environment and arguments and call the appropriate action."""
config.parse_args(sys.argv,
default_config_files=jsonutils.loads(os.env... | NOTE(sdague): old is the most frequent message sent, and
# it's a noop. We should just exit immediately otherwise we
# can stack up a bunch of requests in dnsmasq. A SIGHUP seems
# to dump this list, so actions queued up get lost.
return
objects.register_all()
if not CONF.condu... |
rahulunair/nova | nova/objects/vcpu_model.py | Python | apache-2.0 | 2,317 | 0 | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# d... | one
return cls.obj_from_primitive(jso | nutils.loads(db_extra['vcpu_model']))
@base.NovaObjectRegistry.register
class VirtCPUFeature(base.NovaObject):
VERSION = '1.0'
fields = {
'policy': fields.CPUFeaturePolicyField(nullable=True),
'name': fields.StringField(nullable=False),
}
def obj_load_attr(self, attrname):
se... |
accpy/accpy | accpy/simulate/const.py | Python | gpl-3.0 | 1,881 | 0 | # -*- coding: utf-8 -*-
'''
accpy.simulate.const
Felix Kramer (felix.kramer@physik.hu-berlin.de)
'''
# ratio of circumference to diameter of circle
pi = 3.141592653589793115997963468544185161590576171875
# speed of light----------------------------------------/ (m/s)
cl = 299792458.
# elementary charge----------------... | 2)
# Planck constant---------------------------------------/ (Js)
hp = 6.62606957e-34
# reduced Planck constant-------------------------------/ (Js)
hb = hp/2/pi
# Boltzmann constant-------------------- | ----------------/ (J/K)
kb = 1.3806488e-23
# Avogadro number---------------------------------------/ (1/mole)
NA = 6.02214129e23
# gas constant------------------------------------------/ (J/Kmole)
RG = kb*NA
# gravitational constant--------------------------------/ (Nm^2/kg^2)
Gr = 6.67384e-11
# gravitational accelerat... |
aggendo/jDesigner | configuration.py | Python | gpl-2.0 | 5,488 | 0.013484 | import visualizer as v
import os as os
import json
from shutil import rmtree
from os.path import expanduser
from os.path import join as OSpathJoin
global appLoc
appLoc = "C:\Users\john\Desktop\jDesigner"#C:\\Program Files\\aggendo\\jCode\\"
configFold = "C:\Users\john\Desktop\jDesigner\config"
recent = ""
canvas = ""
s... | +")
recF.write(json.dumps(jRec, sort_keys=True, indent=4, separators=(',', ': ')))
recF.close()
del jRec
def printRecents():
recF = open(recent, "r")
print(recF.read())
recF.close()
def getSetting(name):
global prefs
prefF = open(prefs, "r")
jPref = json.loads(prefF.read())
... | efs, "w+")
jPref[name] = value
prefF.write(json.dumps(jPref, sort_keys=True, indent=4, separators=(',', ': ')))
prefF.close()
def createDefaultPrefs():
jPref = {}
jPref['recents'] = 3
jPref['sizeX'] = 700
jPref['sizeY'] = 600
jPref['defaultBitSize'] = 3.3
jPref["defaultFolder"] = ex... |
showell/zulip | zerver/migrations/0301_fix_unread_messages_in_deactivated_streams.py | Python | apache-2.0 | 909 | 0.0033 | from django.db import migrations
class Migration(migra | tions.Migration):
"""
We're changing the stream deactivation process to | make it mark all messages
in the stream as read. For things to be consistent with streams that have been
deactivated before this change, we need a migration to fix those old streams,
to have all messages marked as read.
"""
dependencies = [
('zerver', '0300_add_attachment_is_web_public'),
... |
hiteshgarg14/openstates | scrapers/de/__init__.py | Python | gpl-3.0 | 3,685 | 0.000271 | from utils import url_xpath, State
from .people import DEPersonScraper
from .bills import DEBillScraper
# from .events import DEEventScraper
# from .committees import DECommitteeScraper
class Delaware(State):
scrapers = {
"people": DEPersonScraper,
"bills": DEBillScraper,
# 'events': DEEv... | 9th General Assembly (2017-2018)",
"start_date": "2017-01-10",
"end_date": "2018-05-09",
},
{
"_scraped_name": "2018 - 2020 (GA 150)",
"identifier": "150",
"name": "150th General Assembly (2019-2020)",
"start_date": "2019-01-08",
... | "identifier": "151",
# "name": "151st General Assembly (2020-2022)",
# "start_date": "2021-01-12",
# "end_date": "2022-05-06",
# },
]
ignored_scraped_sessions = [
"2020 - 2022 (GA 151)"
]
def get_session_list(self):
url = "https://legis.de... |
Code4SA/umibukela | umibukela/forms.py | Python | mit | 5,345 | 0.001123 | from django import forms
from django.contrib.gis.geos import Point
from widgets import AddAnotherWidgetWrapper
from django.core.exceptions import ValidationError
from .models import (Site, CycleResultSet, Monitor, ProgrammeResources,
ProgrammeImage)
class SiteForm(forms.ModelForm):
latitude ... | a = args[0]
if data['latitude'] and data['longitude']:
latitude = float(data['latitude'])
longitude = float(data['longitude'])
data['coordinates'] = Point(longitude, latitude)
if 'instance' in kwargs and kwargs['instance'] is not None and kwargs['inst... | gs['instance'].coordinates.tuple
initial = kwargs.get('initial', {})
initial['longitude'] = coordinates[0]
initial['latitude'] = coordinates[1]
kwargs['initial'] = initial
super(SiteForm, self).__init__(*args, **kwargs)
class CycleResultSetForm(forms.ModelForm):... |
thiblahute/meson | run_project_tests.py | Python | apache-2.0 | 29,483 | 0.003426 | #!/usr/bin/env python3
# Copyright 2012-2016 The Meson development team
# 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... | all any other files
noinst_file = 'usr/no-installed-files'
expected = {}
ret_msg = ''
# Generate list of expected files
if os.path.exists(os.path.join(installdir, noinst_file)):
expected[no | inst_file] = False
elif os.path.exists(info_file):
with open(info_file) as f:
for line in f:
line = platform_fix_name(line.strip(), compiler, env)
if line:
expected[line] = False
# Check if expected files were found
for fname in expecte... |
TouK/vumi | vumi/transports/smpp/smpp_transport.py | Python | bsd-3-clause | 25,023 | 0 | # -*- test-case-name: vumi.transports.smpp.tests.test_smpp_transport -*-
import warnings
from uuid import uuid4
from twisted.internet import reactor
from twisted.internet.defer import (
inlineCallbacks, maybeDeferred, returnValue, Deferred, succeed)
from twisted.internet.task import LoopingCall
from vumi.reconne... | _smpp_bind(self, sequence_number):
d = maybeDeferred(EsmeTr | ansceiverFactory.protocol.on_smpp_bind,
self, sequence_number)
d.addCallback(lambda _: self.vumi_transport.unpause_connectors())
return d
def on_submit_sm_resp(self, sequence_number, smpp_message_id,
command_status):
cb = {
'ES... |
b1-systems/kiwi | kiwi/utils/sync.py | Python | gpl-3.0 | 3,632 | 0 | # Copyright (c) 2015 SUSE Linux GmbH. All rights reserved.
#
# This file is part of kiwi.
#
# kiwi 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 la... | se
# along with kiwi. If not, see <http://www.gnu.org | /licenses/>
#
import os
import logging
from stat import ST_MODE
import xattr
# project
from kiwi.command import Command
log = logging.getLogger('kiwi')
class DataSync:
"""
**Sync data from a source directory to a target directory
using the rsync protocol**
:param str source_dir: source directory pa... |
PressLabs/django-bnr | django_bnr/utils.py | Python | mit | 1,519 | 0.000658 | # -*- coding: utf-8 -*-
# vim: ft=python:sw=4:ts=4:sts=4:et:
import requests
import decimal
from datetime import timedelta
from xml.etree import ElementTree
from django_bnr.models import Rate
def get_bnr_rate(date, currency='USD'):
try:
rate = Rate.objects.get(date=date, currency=currency)
retur... | raise RuntimeError('Cannot get exchange rate for '
'%(currency)s from %(date)s' % {
'currency': currency,
'date': date
})
d = (date... | except:
pass
return rate
|
gyurisc/DigitsRest | use_archive.py | Python | mit | 8,394 | 0.005957 | #!/usr/bin/env python2
# Based on example.py from DIGITS
# https://github.com/NVIDIA/DIGITS
"""
Classify an image using individual model files imported from DIGITS
This tool is for testing your deployed model with images from the test folder.
All the configuration params are removed or commented out as compared to ... | mple - DIGITS')
### Positional arguments
parser.add_argument('caffemodel', help='Pa | th to a .caffemodel')
parser.add_argument('deploy_file', help='Path to the deploy file')
parser.add_argument('image_file',
nargs='+',
help='Path[s] to an image')
### Optional arguments
parser.add_argument('-m', '--mean',
help='Path to a mean... |
kidmaple/CoolWall | user/python/Lib/xml/dom/minidom.py | Python | gpl-2.0 | 14,813 | 0.004186 | """\
minidom.py -- a lightweight DOM implementation based on SAX.
parse( "foo.xml" )
parseString( "<foo><bar/></foo>" )
Todo:
=====
* convenience methods for getting elements and text.
* more testing
* bring some of the writer and linearizer code into conformance with this
interface
* SAX 2 namespaces
""... | y[:5], key[5:]
if prefix == "_get_":
self.inGetAttr = 1
if hasattr(self, attrname):
del self.inGetAttr
return (lambda self=self, attrname=attrname:
getattr(self, attrname))
else:
del self.inGetA... | ept AttributeError:
raise AttributeError, key
del self.inGetAttr
return func()
def __nonzero__(self):
return 1
def toxml(self):
writer = StringIO()
self.writexml(writer)
return writer.getvalue()
def hasChildNodes(self):
if se... |
ToontownUprising/src | toontown/building/DistributedBossElevator.py | Python | mit | 3,644 | 0.004665 | from pandac.PandaModules import *
from direct.distributed.ClockDelta import *
from direct.interval.IntervalGlobal import *
from ElevatorConstants import *
from ElevatorUtils import *
import DistributedElevator
import DistributedElevatorExt
from toontown.toonbase import ToontownGlobals
from direct.directnotify import Di... | setBossOfficeZone(self, zoneId):
if self.localToonOnBoard:
hoodId = self.cr.playGame.hood.hoodId
doneStatus = {'loader': 'cogHQLoader',
'where': 'cogHQBossBattle',
'how': 'movie',
| 'zoneId': zoneId,
'hoodId': hoodId}
self.cr.playGame.getPlace().elevator.signalDone(doneStatus)
def setBossOfficeZoneForce(self, zoneId):
place = self.cr.playGame.getPlace()
if place:
place.fsm.request('elevator', [self, 1])
hoodId = sel... |
alibaba/FlexGW | website/api/__init__.py | Python | bsd-3-clause | 92 | 0 | # -* | - coding: utf-8 -*-
"""
website.api
~~~~~~~~~~~
website api bluepri | nt.
"""
|
olivierlemasle/keystone-playground | keystoneplayground/tests/base.py | Python | apache-2.0 | 661 | 0 | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with | the License. You may obtain
# a copy of the License at
#
# http: | //www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions a... |
staffanm/layeredconfig | tests/test_withFuture.py | Python | bsd-3-clause | 984 | 0.005081 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
try:
from builtins import *
from future import standard_library
standard_library.install_aliases()
except:
# we might be on py3.2, which the future library doesn't support
pass
import os
import sys
if sys.versio... | : int}),
Environment(prefix="FERENDA_"))
self.ass | ertEqual(3, config.downloadmax)
self.assertIsInstance(config.downloadmax, int)
|
guduchango/pyafipws | wsbfev1.py | Python | gpl-3.0 | 25,642 | 0.006318 | #!/usr/bin/python
# -*- coding: latin-1 -*-
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by the
# Free Software Foundation; either version 3, or (at your option) any later
# version.
#
# This program is distributed in t... | er código de autorización electrónico (CAE) del web service
WSBFEv1 de AFIP (Bonos Fiscales electronicos v1.1 - Factu | ra Electrónica RG)
a fin de gestionar los Bonos en la Secretaría de Industria según RG 2557
"""
__author__ = "Mariano Reingart (reingart@gmail.com)"
__copyright__ = "Copyright (C) 2013-2015 Mariano Reingart"
__license__ = "GPL 3.0"
__version__ = "1.06c"
import datetime
import decimal
import os
import sys
... |
YJoe/SpaceShips | Desktop/Python/space_scroll/Game.py | Python | gpl-3.0 | 11,279 | 0.002394 | from Start_up import*
from Player import Player, HealthBar
from Bullet import Bullet
from Enemy import Enemy
from Stopper import Stopper
from Particle import Particle
from Stars import Star, create_stars
from Package import EnemyDrop, HealthPack
from Notes import NoteController
class Game:
def __init__(self, play... | (self.to_update[x], Stopper):
self.to_update[x].update(self.bullet_list, self.enemy_list, self.player, self.note_controller)
elif isinstance(self.to_update[x], HealthBar):
self.to_update[x].update()
def display_all( | self):
# fill screen with black and display all game information
main_s.fill((20, 20, 20))
for x in range(0, len(self.to_display)):
if isinstance(self.to_display[x], Player):
if self.to_display[x].alive:
self.to_display[x].display()
els... |
bslatkin/8-bits | appengine-ndb/mttest.py | Python | apache-2.0 | 947 | 0.019007 | """A torture test to ferret out problems with multi-threading."""
import sys
import threading
from ndb import tasklets
from ndb import eventloop
def main():
##sys.stdout.write('_State.__bases__ = %r\n' % (eventloop._State.__bases__,))
num = 10
try:
num = int(sys.argv[1])
except Exception:
pass
thr... | )
| if __name__ == '__main__':
main()
|
calvinmetcalf/arcsqlite | wkb.py | Python | mit | 3,451 | 0.031585 | from struct import pack
from sqlite3 import Binary
def pts(c):
return ["dd",[c.X,c.Y]]
def pt4mp(c):
return ["Bidd",[1,1,c.X,c.Y]]
def mp(coordinates):
partCount=coordinates.partCount
i=0
out = ["I",[0]]
while i<partCount:
pt = coordinates.getPart(i)
[ptrn,c]=pt4mp(pt... | return out
def linearRing(coordinates):
partCount=coordinates.count
i=0
values =[0]
outnum = "I"
out = ["I",[0]]
while i<partCount:
pt = coordinates[i]
if pt:
[ptrn,c]=pts(pt)
| outnum+=ptrn
values[0]+=1
values.extend(c)
else:
if values[0]<4:
return False
out[0]+=outnum
out[1][0]+=1
out[1].extend(values)
values =[0]
outnum = "I"
i+=1
if values[0... |
pombredanne/project_index | index/migrations/0005_project_related_project.py | Python | gpl-3.0 | 471 | 0 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migrat | ion):
dependencies = [
('index', '0004_repository_public'),
]
operations = | [
migrations.AddField(
model_name='project',
name='related_project',
field=models.ForeignKey(blank=True, to='index.Project', null=True),
preserve_default=True,
),
]
|
onitake/Uranium | UM/Qt/QtApplication.py | Python | agpl-3.0 | 13,585 | 0.005962 | # Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
import sys
import os
import signal
import platform
from PyQt5.QtCore import Qt, QObject, QCoreApplication, QEvent, pyqtSlot, QLocale, QTranslator, QLibraryInfo, QT_VERSION_STR, PYQT_VERSION_STR
from PyQt5.QtQml import Q... | elf.mainWindowChanged.emit()
# Handle a function that should be called later.
def functionEvent(self, event):
e = _QtFunctionEvent(event)
QCoreApplication.postEvent(self, e)
# Handle Qt events
def event(self, event):
if event.type() == _QtFunctionEvent.QtFunctionEvent:
... | tting down %s", self.getApplicationName())
self._shutting_down = True
try:
Preferences.getInstance().writeToFile(Resources.getStoragePath(Resources.Preferences, self.getApplicationName() + ".cfg"))
except Exception as e:
Logger.log("e", "Exception while saving preference... |
er1iang/hfut_stu_lib | hfut/util.py | Python | mit | 8,546 | 0.000944 | # -*- coding:utf-8 -*-
"""
一些能够帮你提升效率的辅助函数
"""
from __future__ import unicode_literals, division
from copy import deepcopy
from datetime import timedelta
from threading import Thread
import requests
import requests.exceptions
from six.moves import urllib
from .log import logger
from .value import ENV
__all__ = ['ge... | ), timedelta(hours=11)),
(timedelta(hours=11, minutes=10), timedelta(hours=12)),
(timedelta(hours=14), timedelta(hours=14, minutes=50)),
(timedelta(hours=15), timedelta(hours=15, minutes=50)),
(timedelta(hours=16), timedelta(hours=16, minutes=50)),
(tim | edelta(hours=17), timedelta(hours=17, minutes=50)),
(timedelta(hours=19), timedelta(hours=19, minutes=50)),
(timedelta(hours=19, minutes=50), timedelta(hours=20, minutes=40)),
(timedelta(hours=20, minutes=40), timedelta(hours=21, minutes=30))
)
for i, d in enumerate(curriculum):
... |
timlinux/qgis2web | olwriter.py | Python | gpl-2.0 | 18,993 | 0.002738 | # qgis-ol3 Creates OpenLayers map from QGIS layers
# Copyright (C) 2014 Victor Olaya (volayaf@gmail.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
# (... | except QgsCsException:
layerExtent = QgsRectangle(-20026376.39, -20048966.10, 20026376.39, 20048966.10)
if extent is None:
extent = layerExtent
else:
extent.combineExtentWith(layerExtent)
return "[%f, %f, %f, %f]" % (extent.xMinimu... | .yMinimum(),
extent.xMaximum(), extent.yMaximum())
def layerToJavascript(layer, scaleVisibility):
# TODO: change scale to resolution
if scaleVisibility and layer.hasScaleBasedVi |
ctogle/lattice | tests/test_lattice.py | Python | mit | 1,022 | 0.036204 | import unittest
import modular_core.libfundamental as lfu
from modular_core.libsimcomponents import ensemble_manager as mng
import os, sys, pdb
#log = open(os.path.join(os.getcwd(), 'test_ensemble.log'), 'w')
#sys.stdout = log
i | mport lattice as mod
class dummyTestCase(unittest.TestCase):
"""Tests for `dummy module`."""
simple_mcfg = os.path.join(os.getcwd(),
'lattice_dep_mcfgs',
'lattice_example.mcfg')
mn = mng()
en = mn.add_ensemble(module = mod.main.module_name)
| def pause(self, *args, **kwargs):
sys.stdout = sys.__stdout__
pdb.set_trace()
sys.stdout = log
def test_can_make_ensemble(self):
"""module successfully imported?"""
self.assertFalse(mod.main == None)
mod_name = mod.main.module_name
ensem = self.mn.add_ensemble(module = mod_name)
self.assertFalse(ense... |
panoptes/POCS | src/panoptes/pocs/mount/ioptron/ieq30pro.py | Python | mit | 12,613 | 0.001904 | import re
import time
from astropy import units as u
from astropy.coordinates import SkyCoord
from panoptes.utils.time import current_time
from panoptes.utils import error as error
from panoptes.pocs.mount.serial import AbstractSerialMount
class Mount(AbstractSerialMount):
"""
Mount class for iOptron mo... | 'Creating iOptron mount')
# Regexp to match the iOptron RA/Dec format
self._ra_format = r'(?P<ra_millisecond>\d{8})'
self._dec_format = r'(?P<dec_sign>[\+\-])(?P<dec_arcsec>\d{8})'
self | ._coords_format = re.compile(self._dec_format + self._ra_format)
self._raw_status = None
self._status_format = re.compile(
'(?P<gps>[0-2]{1})' +
'(?P<state>[0-7]{1})' +
'(?P<tracking>[0-4]{1})' +
'(?P<movement_speed>[1-9]{1})' +
'(?P<time_sour... |
hbbhbbh/TmallSingleCrawler | TmallSingleCrawler/spiders/tmall.py | Python | mit | 11,888 | 0.003456 | # -*- coding: utf-8 -*-
import scrapy
from scrapy.selector import Selector
from scrapy.loader import ItemLoader
from scrapy.xlib.pydispatch import dispatcher
from scrapy import signals
from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import exp... | onse.css("#J_ItemList .product"):
try:
item_loader = ItemLoader(item=TMallGoodsItem(), selector=item_blo | ck)
id = item_block.css("::attr(data-id)").extract_first()
# 如果 id 不存在,说明这个 商品块 是天猫的推荐商品,直接跳过
if id is None:
continue
item_loader.add_value("id", id)
item_loader.add_css("main_image", ".product... |
arsenovic/clifford | clifford/_conformal_layout.py | Python | bsd-3-clause | 2,999 | 0.001 | import numpy as np
from ._layout import Layout
from ._multivector import MultiVector
class ConformalLayout(Layout):
r"""
A layout for a | conformal algebra, which adds extra constants and helpers.
Typically these should be constructed via :func:`clifford.conformalize`.
.. versionadded:: 1.2.0
Attributes
----------
ep : MultiVector
The first added basis element, :math:`e_{+}`, usually with :math:`e_{+}^2 = +1`
en : Mult... | The null basis vector at the origin, :math:`e_o = 0.5(e_{-} - e_{+})`
einf : MultiVector
The null vector at infinity, :math:`e_\infty = e_{-} + e_{+}`
E0 : MultiVector
The minkowski subspace bivector, :math:`e_\infty \wedge e_o`
I_base : MultiVector
The pseudoscalar of the base ga, i... |
jamespcole/home-assistant | tests/components/deconz/test_climate.py | Python | apache-2.0 | 6,215 | 0 | """deCONZ climate platform tests."""
from unittest.mock import Mock, patch
import asynctest
from homeassistant import config_entries
from homeassistant.components import deconz
from homeassistant.helpers.dispatcher import async_dispatcher_send
from homeassistant.setup import async_setup_component
import homeassistan... | assert "climate.name" in hass.data[deconz.DOMAIN].deconz_ids
async def test_do_not_allow_clipsensor(hass):
"""Test that clip sensors can be ignored."""
await setup_gateway(hass, {}, allow_clip_sensor=False)
sensor = Mock()
sensor.name = 'name'
sensor.type = 'CLIPThermostat'
s | ensor.register_async_callback = Mock()
async_dispatcher_send(hass, 'deconz_new_sensor', [sensor])
await hass.async_block_till_done()
assert len(hass.data[deconz.DOMAIN].deconz_ids) == 0
async def test_unload_sensor(hass):
"""Test that it works to unload sensor entities."""
await setup_gateway(hass... |
Anderson-Lab/anderson-lab.github.io | csc_466_2021_spring/MLCode/Ch18/gp.py | Python | mit | 13,209 | 0.059959 |
# Code from Chapter 18 of Machine Learning: An Algorithmic Perspective (2nd Edition)
# by Stephen Marsland (http://stephenmonika.net)
# You are free to use, change, or redistribute the code in any way you wish for
# non-commercial purposes, but please maintain the name of the original author.
# This code comes with n... | ))
K[:,:,0] = k + measnoise*theta[2]**2*np.eye(d1,d2)
K[:,:,1] = 2.0 *k /theta[0]
K[:,:,2] = k*sumxy/(theta[1]**3)
K[:,:,3] = -4. | 0*k*np.sin(np.pi*sumxy)**2/(theta[2]**3)
K[:,:,4] = 2.0*theta[3]*np.eye(d1,d2)
return K
else:
return k + measnoise*theta[2]**2*np.eye(d1,d2)
def kernel2(data1,data2,theta,wantderiv=True,measnoise=1.):
# Uses exp(theta) to ensure positive hyperparams
theta = np.squeeze(theta)
theta = np.exp(theta)
# Squared... |
janpipek/chagallpy | setup.py | Python | mit | 782 | 0 | #!/usr/bin/env python
from | setuptools import setup, find_packages
import chagallpy
setup(
name='chagallpy',
version=chagallpy.__version__,
packages=find_packages(),
license='MIT',
description='CHArming GALLery in PYthon',
long_description_content_type="text/markdown",
long_description=open('README.md').read(),
au... | click"],
python_requires="~=3.6",
entry_points={
'console_scripts': [
'chagall = chagallpy:generate'
]
},
include_package_data=True,
package_data={
'resources': ['*.*'],
'templates': ['*.html']
},
)
|
mallconnectionorg/openerp | DTE/mc_dte_guia/__init__.py | Python | agpl-3.0 | 1,114 | 0 | #!/usr/bin/python
# -*- coding: utf-8 -*-
##############################################################################
#
# DTE Chile OpenERP 7
# Copyright (C) 2016 Cesar Lopez Aguillon Mall Connection
# <http://www.mallconnection.org>.
# This program is free software: you can redistribute it and/or modify
# ... | ee Softw | are Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Pu... |
kmtoki/qmk_firmware | lib/python/qmk/cli/config.py | Python | gpl-2.0 | 3,720 | 0.002151 | """Read and write configuration settings
"""
from milc import cli
def print_config(section, key):
"""Print a single config setting to stdout.
"""
cli.echo('%s.%s{fg_cyan}={fg_reset}%s', section, key, cli.config[section][key])
def show_config():
"""Print the current configuration to stdout.
"""
... | key in cli.config[section]:
print_config(section, key)
# Ending actions
if save_conf | ig:
cli.save_config()
return True
|
PrestonMonteWest/compmart | commerce/admin.py | Python | apache-2.0 | 1,286 | 0.004666 | from django.contrib import admin
from . import models
class OrderItemInline(admin.TabularInline):
fields = ('product', 'quantity')
raw_id_fields = ('product',)
model = models.OrderItem
extra = 1
class ProductAdmin(admin.ModelAdmin):
list_display = ('name', 'price', 'description', 'stock', 'discont... | 'image')
class ReviewAdmin(admin.ModelAdmin):
list_ | display = ('user', 'product', 'title', 'body', 'rating', 'pub_date')
search_fields = ('title', 'body')
list_filter = ('pub_date', 'rating')
date_hierarchy = 'pub_date'
fields = ('user', 'product', 'title', 'body', 'rating')
raw_id_fields = ('user', 'product')
class OrderAdmin(admin.ModelAdmin):
... |
arteria/django-shop-simplenotifications | shop_simplenotifications/__init__.py | Python | unlicense | 222 | 0.009009 | # | -*- coding: utf-8 -*-
VERSION = (0, 1, 6, 'final')
if VERSION[-1] != "final": # pragma: no cover
__version__ = '.'.join(map(str, VERSION))
else: # pragma: no cover
__version__ = '.'.join(map(str, | VERSION[:-1]))
|
josenavas/QiiTa | qiita_db/handlers/tests/oauthbase.py | Python | bsd-3-clause | 841 | 0 | # -----------------------------------------------------------------------------
# Copyright (c) 2014--, The Qiita D | evelopment Team.
#
# Distributed under the terms of the BSD 3-claus | e License.
#
# The full license is in the file LICENSE, distributed with this software.
# -----------------------------------------------------------------------------
from qiita_core.qiita_settings import r_client
from qiita_pet.test.tornado_test_base import TestHandlerBase
class OauthTestingBase(TestHandlerBase):... |
barthess/mavlink | pymavlink/tools/magfit_motors.py | Python | lgpl-3.0 | 4,813 | 0.009765 | #!/usr/bin/env python
'''
fit best estimate of magnetometer offsets, trying to take into account motor interference
'''
import sys, time, os, math
from argparse import ArgumentParser
parser = ArgumentParser(description=__doc__)
parser.add_argument("--no-timestamps",dest="notimestamps", action='store_true', help="Log... | mavlink import mavutil
from pymavlink.rotmat import Vector3
def noise():
'''a noise vector'''
from random import gauss
v = Vector3(gauss(0, 1), gauss(0, 1), gauss(0, 1))
v.normalize()
return v * | args.noise
def select_data(data):
ret = []
counts = {}
for d in data:
(mag,motor) = d
key = "%u:%u:%u" % (mag.x/20,mag.y/20,mag.z/20)
if key in counts:
counts[key] += 1
else:
counts[key] = 1
if counts[key] < 3:
ret.append(d)
pr... |
RCIX/RogueP | logic/menu_main.py | Python | mit | 668 | 0.02994 | import libtcodpy as libtcod
from menu import Menu
from menu_manager import MenuStatus
from menu_game import MenuGame
from ui.frame_main_menu import FrameMainMenu
class MenuMain(Menu) | :
def __init__(self, width, height):
Menu.__init__(self, width, height)
self.menu_frame = FrameMainMenu(width, height)
def update(self, delta):
self.menu_frame.update(delta)
key = libtcod.console_check_for_keypress(True) #libtcod.co | nsole_check_for_keypress
if key.c == ord("a"):
return MenuGame(self.width, self.height)
if key.c == ord("b"):
return MenuStatus.Exit
return MenuStatus.Okay
def draw(self):
#print("drawing MenuMain")
self.menu_frame.draw() |
cypreess/django-getpaid | example/paywall/admin.py | Python | mit | 195 | 0 | from django.contrib import admin
from django.contrib.admin | import ModelAdmin
from paywall.models import PaymentEntry
@admin.register(PaymentEntry)
class PaymentEn | tryAdmin(ModelAdmin):
pass
|
ashwinpilgaonkar/Flick | Bluetooth/Bluetooth.py | Python | apache-2.0 | 25,172 | 0.012871 | import serial
from sys import platform as platform
import serial.tools.list_ports
import serial.threaded
from pymouse import PyMouse
from Voice.GoogleTTS import speak
import threading
import math
import copy
import time
import json
data_repository_right = {
"id" : [],
"name" : [],
"short... | "min_acc_%R_y": [],
"25":[] | , # "min_acc_@R_z": [],
"26":[], # "min_acc_^R_z": [],
"27":[], # "min_acc_#R_z": [],
"28":[], # "min_acc_$R_z": [],
"29":[], # "min_acc_%R_z": [],
"30":[], # "start_angle_@R_x":[],
"31":[], # "start_angle_^R_x": [],
"32":[], # "start_angle_#R... |
brechin/pyrollout | pyrollout/rollout.py | Python | mit | 2,301 | 0.002608 | import logging
# noinspection PyUnresolvedReferences
import feature #noqa
logging.basicConfig(level=logging.DEBUG)
class Rollout(object):
__version__ = '0.3.5'
def __init__(self, feature_storage=None, user_storage=None, undefined_feature_access=False):
"""
Manage feature flags for groups, u... | """
Check whether | user has access to the given feature.
:param user: User object to check, must be compatible with user storage manager in use
:type user: dict or object
:param feature_name: Name of feature to check against
:type feature_name: basestring
:return: True if user has access, False o... |
logithr/djangocms-widgetbox | widgetbox/migrations/0011_auto_20150731_0958.py | Python | mit | 447 | 0 | # -*- coding: utf-8 -*-
from __future__ import unico | de_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('widgetbox', '0010_html'),
]
operations = [
migrations.AddField(
model_name='button',
name='extra_css_classes',
field=models.CharField(max_le... | ),
]
|
ushatil/wellness-tracker | ws/manage.py | Python | mit | 253 | 0 | #! | /usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "wellspring.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(s | ys.argv)
|
bkosciow/gfxlcd | gfxlcd/tests/test_ssd1306.py | Python | mit | 464 | 0.006466 | import sys
sys.path.append("../../")
from unittest.mock import patch, MagicMock
MockRPi = MagicMock()
MockSpidev = MagicMoc | k()
modules = {
"RPi": MockRPi,
"RPi.GPIO": MockRPi.GPIO,
"spidev": MockSpidev
}
patcher = patch.dict("sys.modules", | modules)
patcher.start()
from gfxlcd.driver.ssd1306.spi import SPI
from gfxlcd.driver.ssd1306.ssd1306 import SSD1306
class TestNJU6450(object):
def test_initialize(self):
SSD1306(128, 64, SPI())
|
NIASC/VirusMeta | diginorm_module/abundance-dist.py | Python | gpl-3.0 | 6,918 | 0 | #! /usr/bin/env python
# This file is part of khmer, https://github.com/dib-lab/khmer/, and is
# Copyright (C) 2010-2015, Michigan State University.
# Copyright (C) 2015, The Regents of the University of California.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted pro... | countgraph(
args.input_count_graph_filename)
if not countgrap | h.get_use_bigcount() and args.bigcount:
print("WARNING: The loaded graph has bigcount DISABLED while bigcount"
" reporting is ENABLED--counts higher than 255 will not be "
"reported.",
file=sys.stderr)
countgraph.set_use_bigcount(args.bigcount)
kmer_size = cou... |
nijel/weblate | weblate/trans/migrations/0094_project_language_aliases.py | Python | gpl-3.0 | 752 | 0.00266 | # Generated by Django 3.0.7 on 2020-08-03 08:42
from django.db import migrations, models
import weblate.utils.val | idators
class Migration(migrations.Migration):
dependencies = [
("trans", "0093_auto_20200730_1432"),
]
operations = [
migrations.AddField(
model_name="project",
name="language_aliases",
field=models.CharField(
default="",
... | tils.validators.validate_language_aliases],
verbose_name="Language aliases",
),
),
]
|
mozilla/moztrap | tests/runner.py | Python | bsd-2-clause | 1,224 | 0.001634 | from django.conf import settings
from django.test import TestCase, TransactionTestCase
from django.test.simple import DjangoTestSuiteRunner
from django. | test.runner import reorder_suite
from django.utils.importlib import import_module
from django.utils.unittest.loader import defaultTestLoader
class DiscoveryDjangoTestSuiteRunner(DjangoTestSuiteRunner):
def build_suite(self, test_labels, extra_tests=None, | **kwargs):
suite = None
discovery_root = settings.TEST_DISCOVERY_ROOT
if test_labels:
suite = defaultTestLoader.loadTestsFromNames(test_labels)
# if single named module has no tests, do discovery within it
if not suite.countTestCases() and len(test_labels) ==... |
AJBrodie/inflowProject | pyKratos/newton_raphson_strategy.py | Python | bsd-2-clause | 6,317 | 0.015197 | # ----------------------------------------------------------------------
# author : Martin Ruchti
# contact : martin.ruchti@tum.de
# ----------------------------------------------------------------------
from __future__ import print_function, absolute_import, division
from numpy import *
from .variables import *
'''... | do update
self.scheme.Update(self.builder_and_solver.dofset, self.dx)
#iterate if not converged
while(not is_converged and iteration_number < self.max_iteration_number):
# do build and solve
self.A, self.dx, self.b = self.builder_and_solver.BuildAndSolve(self.A... | call scheme to do update
self.scheme.Update(self.builder_and_solver.dofset, self.dx)
#check for convergence
error_L2_norm = 0.0
for i in range(0,len(self.dx)):
error_L2_norm += (self.dx[i])**2
#scale error... |
gem/geonode | geonode/layers/views.py | Python | gpl-3.0 | 29,767 | 0.000571 | # -*- coding: utf-8 -*-
#########################################################################
#
# Copyright (C) 2016 OSGeo
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 ... | rn resolve_object(request,
Layer,
{'typename': typename},
permission=permission,
permission_msg=msg,
**kwargs)
# Basic Layer Views #
@login_required
def layer_upload(... | saic=True).order_by('name')
ctx = {
'mosaics': mosaics,
'charsets': CHARSETS,
'is_layer': True,
}
return render_to_response(template, RequestContext(request, ctx))
elif request.method == 'POST':
form = NewLayerUploadForm(request.POST, request.FILES... |
sdh11/gnuradio | gr-filter/python/filter/design/filter_design.py | Python | gpl-3.0 | 91,770 | 0.004914 | # Copyright 2012 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# SPDX-License-Identifier: GPL-3.0-or-later
#
#
import sys
import os
import re
import csv
import copy
import warnings
from optparse import OptionParser
from gnuradio import filter, fft
try:
import numpy as np
except ImportError:... | self.mfoverlay = False
self.mtoverlay = False
| self.iir = False
self.mfmagresponse = True
self.mfphaseresponse = False
self.mfgroupdelay = False
self.mfphasedelay = False
self.mttaps = True
self.mtstep = False
self.mtimpulse = False
self.gui.designButton.setShortcut(QtCore.Qt.K... |
gmimano/commcaretest | corehq/apps/accounting/urls.py | Python | bsd-3-clause | 1,305 | 0.007663 | from django.conf.urls.defaults import *
from corehq import AccountingAdminInterfaceDispatcher
from corehq.apps.accounting.views import *
urlpatterns = patterns('corehq.apps.accounting.views',
url(r'^$', 'accounting_default', name='accounting_default'),
url(r'^accounts/(\d+)/$', ManageBillingAccountView.as_vie... | '^accounts/new/$', NewBillingAccountView.as_view(), name=NewBillingAccountView.urlname),
url(r'^subscriptions/(\d+)/$', EditSubscriptionView.as_view(), name=EditSubscriptionView.urlname),
url(r'^account | s/new_subscription/$', NewSubscriptionViewNoDefaultDomain.as_view(),
name=NewSubscriptionViewNoDefaultDomain.urlname),
url(r'^accounts/new_subscription/(\d+)/$', NewSubscriptionView.as_view(), name=NewSubscriptionView.urlname),
url(r'^software_plans/new/$', NewSoftwarePlanView.as_view(), name=NewSoftwar... |
fanout/webhookinbox | api/views.py | Python | mit | 12,930 | 0.030085 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from base64 import b64encode, b64decode
import datetime
import copy
import json
from django.conf import settings
from django.http import HttpResponse, HttpResponseBadRequest, HttpResponseNotFound, HttpResponseNotAllowed
from gripcontrol import Channel, Ht... | t('Bad Request: Invalid id\n')
except redis_ops.ObjectDoesNotExist:
return HttpResponseNotFound('Not Found\n')
except:
return HttpResponse('Service Unavailable\n', status=503)
out = dict()
out['id'] = inbox_id
out['base_url'] = 'http://' + host + '/i/' + inbox_id + '/'
out['ttl'] = inbox['ttl']
res... | ype='application/json')
elif req.method == 'DELETE':
try:
db.inbox_delete(inbox_id)
except redis_ops.InvalidId:
return HttpResponseBadRequest('Bad Request: Invalid id\n')
except redis_ops.ObjectDoesNotExist:
return HttpResponseNotFound('Not Found\n')
except:
return HttpResponse('Service Unavailable... |
emillynge/lasagne-caterer | lasagnecaterer/recipe.py | Python | gpl-3.0 | 50,854 | 0.001298 | """
Instructions on how to put together different kinds of lasagnas
"""
# builtins
from collections import (namedtuple, defaultdict, OrderedDict)
from functools import (lru_cache, partial)
from weakref import WeakKeyDictionary
# pip packages
from itertools import chain
import sys
from theano import tensor as T
import... | that takes (x, y) and trains the lasagne
Updates use default cost (e.g with dropout)
Does *not* return a cost.
:return: None
"""
return self.compiled_function([self.l_in.input_var, self.target_values],
| updates=self.train_updates,
allow_input_downcast=True)
@property
def f_cost(self):
"""
Compiled theano function that takes (x, y) and return cost.
No updates is made
:return:
"""
self.all_train_params
... |
pinterest/wheeljack | wheeljack/exceptions.py | Python | mit | 769 | 0 | __author__ = 'davedash'
class WheeljackEx | ception(Exception):
pass
class RepoNotFoundException(WheeljackException):
"""Exception thrown when we interact with an undefined Repo."""
pass
class RepoAlreadyInstalle | dException(WheeljackException):
"""Exception thrown when we try to re-install a repo."""
pass
class ReposConfigException(WheeljackException):
"""Exception raised when there is a configuration error."""
pass
class WheeljackCodeDirectoryMissing(WheeljackException):
"""Raised if we are missing our ... |
fujicoin/fujicoin | test/functional/wallet_startup.py | Python | mit | 2,543 | 0.00118 | #!/usr/bin/env python3
# Copyright (c) 2017-2020 The Fujicoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test wallet load on startup.
Verify that a fujicoind node can maintain list of wallets loading on sta... | des[0].listwallets()), set(('', 'w2', 'w4')))
self.nodes[0].unloadwallet(wallet_name='', load_on_startup=False)
self.nodes[0].unloadwallet(wa | llet_name='w4', load_on_startup=False)
self.nodes[0].loadwallet(filename='w3', load_on_startup=True)
self.nodes[0].loadwallet(filename='')
self.restart_node(0)
assert_equal(set(self.nodes[0].listwallets()), set(('w2', 'w3')))
if __name__ == '__main__':
WalletStartupTest().main()
|
FreeJournal/freejournal | models/collection.py | Python | mit | 6,736 | 0.007423 | from sqlalchemy import Column, ForeignKey, Integer, String, Text, DateTime, Table
from sqlalchemy.orm import relationship, backref
from models import DecBase
from models.document import Document
from models.keyword import Keyword
from jsonschema import *
from json_schemas import *
from models.collection_version import ... | ing to this collection
accesses: Number of times this collection is accessed by a user of this node (for cache pruning)
votes: Latest vote count from the Bitcoin network, used to rank collection
votes_last_checked: Latest poll of Bitcoin network for collection votes, to coordinate in... | ""
__tablename__ = 'collection'
title = Column(Text, nullable=False)
description = Column(String)
address = Column(String, primary_key=True)
btc = Column(String)
keywords = relationship("Keyword", secondary=collection_keywords, backref='collection')
documents = relationship("Document", secon... |
pknight007/electrum-vtc | plugins/labels/labels.py | Python | mit | 5,710 | 0.001576 | import hashlib
import requests
import threading
import json
import sys
import traceback
import base64
import electrum_vtc as electrum
from electrum_vtc.plugins import BasePlugin, hook
from electrum_vtc.i18n import _
class LabelsPlugin(BasePlugin):
def __init__(self, parent, config, name):
BasePlugin.... | ({'encryptedLabel': encoded_value,
'externalId': encoded_key})
self.do_request("POST", "/labels", True, bundle)
def pull_thread(self, wallet, force):
wallet_id = self.wallets[wallet][2]
n | once = 1 if force else self.get_nonce(wallet) - 1
self.print_error("asking for labels since nonce", nonce)
try:
response = self.do_request("GET", ("/labels/since/%d/for/%s" % (nonce, wallet_id) ))
if response["labels"] is None:
self.print_error('no new labels')
... |
saltstack/salt | tests/integration/modules/test_mac_timezone.py | Python | apache-2.0 | 7,775 | 0.00373 | """
Integration tests for mac_timezone
If using parallels, make sure Time sync is turned off. Otherwise, parallels will
keep changing your date/time settings while the tests are running. To turn off
Time sync do the following:
- Go to actions -> configure
- Select options at the top and 'More Options' on the l... | zone
self.assertEqual(
self.run_function("timezone.set_zone", ["spongebob"]),
"ERROR | executing 'timezone.set_zone': Invalid Timezone: spongebob",
)
@skipIf(
True,
"Skip until we can figure out why modifying the system clock causes ZMQ errors",
)
@pytest.mark.destructive_test
def test_get_offset(self):
"""
Test timezone.get_offset
"""
... |
brucexiejiaming/App_store | part1_crawler/appstore/appstore/settings.py | Python | mit | 579 | 0.005181 | # -*- coding: utf-8 -*-
# Scrapy settings for appstore project
#
# For simplicity, this file contains only the most important settings by
# default. All the other settings are documented here:
#
# http://doc.scrapy.org/en/latest/topics/settings.html
#
BOT_NAME = 'appstore'
SPIDER_MODULES = ['appstore.spiders']
N... | IPELINES = {
'appstore.pipelines.AppstorePipeline': 300,
}
DOWNLOAD_DELAY=5
# Crawl responsibly | by identifying yourself (and your website) on the user-agent
#USER_AGENT = 'appstore (+http://www.yourdomain.com)'
|
meduz/scikit-learn | sklearn/ensemble/tests/test_gradient_boosting.py | Python | bsd-3-clause | 40,613 | 0.000074 | """
Testing for the gradient boosting module (sklearn.ensemble.gradient_boosting).
"""
import warnings
import numpy as np
from itertools import product
from scipy.sparse import csr_matrix
from scipy.sparse import csc_matrix
from scipy.sparse import coo_matrix
from sklearn import datasets
from sklearn.base import clo... | tion_synthetic, presort, loss
def check_boston(presort, loss, subsample):
# Check consistency on dataset boston house prices with least squares
# and least absolute deviation.
ones = np.ones(len(boston.target))
last_y_pred = None
for sample_weight in None, ones, 2 * ones:
clf = GradientBoo... | loss=loss,
max_depth=4,
subsample=subsample,
min_samples_split=2,
random_state=1,
presort=presort)
assert_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.