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 |
|---|---|---|---|---|---|---|---|---|
edwintye/pygotools | pygotools/convex/__init__.py | Python | gpl-2.0 | 412 | 0.002427 | ''' direct
.. moduleauthor:: Edwin Tye <Edwin.Tye@gmai | l.com>
'''
from __future__ import division, print_function, absolute_import
from .sqp import *
from .ip import *
from .ipBar import *
from .ipPD import *
from .ipPDC import *
from .ipPDandPDC import *
from .approxH import *
from .trust import *
__ | all__ = [s for s in dir() if not s.startswith('_')]
from numpy.testing import Tester
test = Tester().test
|
SNoiraud/gramps | gramps/gen/filters/rules/family/_hasreltype.py | Python | gpl-2.0 | 2,354 | 0.005098 | #
# Gramps - a GTK+/GNOME based genealogy program
#
# Copyright (C) 2002-2006 Donald N. Allingham
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at you... | nse for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
#-------------------------------------------------------------------------
#
# Stan... | ---------------------------------------------------------------
#
# Gramps modules
#
#-------------------------------------------------------------------------
from ....lib.familyreltype import FamilyRelType
from .. import Rule
#-------------------------------------------------------------------------
#
# HasAttribute... |
dw/scratch | overalloc.py | Python | mit | 161 | 0.018634 |
def d(n):
tp = (n>>4) | + (n>>3)
if tp < 64:
tp = 64
if tp > 2048:
| tp = 2048
print[n,tp]
for x in range(0, 9999, 512):
d(x)
|
tushartushar/Puppeteer | SourceModel/SM_File.py | Python | apache-2.0 | 17,577 | 0.004153 | import re
import SourceModel.SM_CaseStmt
import SourceModel.SM_Class
import SourceModel.SM_Constants as SMCONSTS
import SourceModel.SM_Define
import SourceModel.SM_Define
import SourceModel.SM_Element
import SourceModel.SM_Exec
import SourceModel.SM_FileResource
import SourceModel.SM_IfStmt
import SourceModel.SM_Inclu... | d:
if self.fileText[curIndex] == '{':
found = True
curBracketC | ount = 1
curIndex += 1
while curBracketCount > 0 and curIndex < len(self.fileText):
if self.fileText[curIndex] == '}':
curBracketCount -= 1
if self.fileText[curIndex] == '{':
curBracketCount += 1
curIndex +=1
return se... |
edwardsdl/cryptopals | cryptopals/tests/test_common.py | Python | mit | 1,109 | 0.003607 | import pytest
import cryptopals.common as common
def test_base64_from_hex():
assert 'SGVsbG8sIHdvcmxkIQ==' == common.base64_from_hex('48656c6c6f2c20776f726c6421')
@pytest.mark.parametrize('first_bytes, second_bytes, expected_output', [
(b'Hello,', b'World! | ', 17),
(b'foo', b'bar', 8),
(b'baz', b'qux', 6)
])
def test_compute_hamming_distance(first_bytes, second_bytes, expected_output):
assert common.compute_hamming_distance(first_bytes, second_bytes) == expected_output
@pytest.mark.parametrize('message, expected_o | utput', [
('Now is the time for all good men to come to the aid of their country', 13),
('The quick brown fox jumps over the lazy dog', 4),
('ETAOIN SHRDLU', 0)
])
def test_score_message(message, expected_output):
assert common.score_message_using_word_list(message) == expected_output
def test_score_m... |
coll-gate/collgate | server/accession/models.py | Python | mit | 31,423 | 0.002355 | # -*- coding: utf-8; -*-
#
# @file models.py
# @brief coll-gate accession module models.
# @author Frédéric SCHERMA (INRA UMR1095), Medhi BOULNEMOUR (INRA UMR1095)
# @date 2016-09-01
# @copyright Copyright (c) 2016 INRA/CIRAD
# @license MIT (see LICENSE file)
# @details
import re
from django.contrib.auth.models impor... | result['comments'] = self.comments
return result
else:
return {
'name': self.name,
'code': self.code,
'primary_classification_entry': self.primary_classification_entr | y_id,
'descriptors': self.desc |
zmarvel/slowboy | tests/test_gpu.py | Python | mit | 7,556 | 0.000794 |
import unittest
import slowboy.gpu
import slowboy.interrupts
from tests.mock_interrupt_controller import MockInterruptController
STAT_IE_ALL_MASK = (slowboy.gpu.STAT_LYC_IE_MASK |
slowboy.gpu.STAT_OAM_IE_MASK |
slowboy.gpu.STAT_HBLANK_IE_MASK |
slowboy.gp... | elf.gpu.load_interrupt_controller(self.interrupt_controller)
self.assertEqual(self.gpu.stat & slowboy.gpu.STAT_LYC_IE_MASK, 0)
self.gpu.stat |= slowboy.gpu.STAT_LYC_IE_MASK
self.gpu.ly = self.gpu.lyc
self.a | ssertEqual(self.interrupt_controller.last_interrupt,
slowboy.interrupts.InterruptType.stat)
def test_stat_hblank_interrupt(self):
self.gpu.load_interrupt_controller(self.interrupt_controller)
self.assertEqual(self.gpu.stat & slowboy.gpu.STAT_HBLANK_IE_MASK, 0)
sel... |
thesecuritystoic/Packet2Snort | packet2snort.py | Python | gpl-3.0 | 9,018 | 0.026503 | try:
from scapy.all import *
except ImportError:
sys.stderr.write("ERROR: You must have scapy installed.\n")
sys.stderr.write("You can install it by running: sudo pip install -U 'scapy>=2.3,<2.4'")
exit(1)
try:
from scapy.layers import http
except ImportError:
sys.stderr.write("ERROR: You must have scapy-http ins... | ce:4; reference:Packet2S | nort; classtype:trojan-activity; sid:xxxx; rev:1;)"
else:
print ("alert udp $HOME_NET any -> any 53 (msg: \"Suspicious DNS request for {0} detected!\"; content:\"|01 00 00 01 00 00 00 00 00 00|\"; depth:10; offset:2; content:\"".format(hostname)),
dnsplit = hostname.split('.')
for word in dnsplit... |
ZacBlanco/adac | adac/consensus/__init__.py | Python | mit | 86 | 0.011628 | '''Thi | s module contains differnet implementations of distributed average cons | ensus'''
|
timj/scons | test/packaging/strip-install-dir.py | Python | mit | 2,169 | 0.003688 | #!/usr/bin/env python
#
# __COPYRIGHT__
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
... | # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
"""
Test stripping the InstallBuilder of th... | ect('TAR', 'tar')
if not tar:
test.skip_test('tar not found, skipping test\n')
test.write( 'main.c', '' )
test.write('SConstruct', """
prog = Install( '/bin', 'main.c' )
env=Environment(tools=['default', 'packaging'])
env.Package( NAME = 'foo',
VERSION = '1.2.3',
source = [ prog ],
... |
alextricity25/parse_apache_configs | parse_apache_configs/test/test_parse_config.py | Python | apache-2.0 | 1,118 | 0.013417 | from os import listdir
from os.path import isfile, join
import unittest
from parse_apache_configs import parse_config
import pprint
class testParseConfig(unittest.TestCase):
#print "ENTERING TEST_PARSE_CONFIG" + "-"*8
def test_parse_config(self):
test_files = [ f fo | r f in listdir("./test_conf_files") if isfile(join("./test_conf_files", f)) ]
for file_name in test_files:
pac = parse_config.ParseApacheConfig("./test | _conf_files/" + file_name)
conf_list = pac.parse_config()
def test_parse_config_string_file(self):
test_files = [ f for f in listdir("./test_conf_files") if isfile(join("./test_conf_files", f)) ]
for file_name in test_files:
full_file_path = "./test_conf_files/" + file_name
... |
vpetersson/docker-py | docker/api/network.py | Python | apache-2.0 | 10,566 | 0 | from ..errors import InvalidVersion
from ..utils import check_resource, minimum_version
from ..utils import version_lt
from .. import utils
class NetworkApiMixin(object):
@minimum_version('1.21')
def networks(self, names=None, ids=None, filters=None):
"""
List networks. Similar to the ``docker... | d
"""
url = self._url("/networks/{0}", net_id)
res = self._delete(url)
self._raise_for_status(res)
@minimum_version('1.21')
@check_resource('net_id')
def inspect_network(self, net_id, verbose=None, scope=None):
"""
Get detailed information about a network.
... | swarm mode.
scope (str): Filter the network by scope (``swarm``, ``global``
or ``local``).
"""
params = {}
if verbose is not None:
if version_lt(self._version, '1.28'):
raise InvalidVersion('verbose was introduced in API 1.28')
... |
manuco/Pot-commun | testrunner.py | Python | gpl-3.0 | 332 | 0.009036 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from unittest import TestLoader, TextTestRunner
from potcommuntests | import Tests
runner = TextTestRunner()
testsSuite = TestLo | ader().loadTestsFromTestCase(Tests)
#testsSuite = TestLoader().loadTestsFromName("potcommuntests.Tests.test_with_some_missing_items")
runner.run(testsSuite)
|
Teekuningas/mne-python | mne/preprocessing/_fine_cal.py | Python | bsd-3-clause | 2,954 | 0 | # -*- coding: utf-8 -*-
# Authors: Eric Larson <larson.eric.d@gmail.com>
# License: BSD (3-clause)
import numpy as np
from ..utils import check_fname, _check_fname
def read_fine_calibration(fname):
"""Read fine calibration information from a .dat file.
The fine calibration typically includes improved sens... | e '
'but found %s on line:\n%s'
% (len(vals), line))
# `vals` contains channel number
ch_name = vals[0]
if len(ch_name) in (3, 4): # heur | istic for Neuromag fix
try:
ch_name = int(ch_name)
except ValueError: # something other than e.g. 113 or 2642
pass
else:
ch_name = 'MEG' + '%04d' % ch_name
ch_names.append(ch_name)
# (x, ... |
MaCFP/macfp-db | Buoyant_Plumes/Sandia_Helium_Plume/Computational_Results/2021/SNL/SNL_plot_results.py | Python | mit | 754 | 0.005305 | #!/usr/bin/env python3
# McDermott
# March 2020
# first, make sure the macfp module directory is in your path
# if not, uncomment the lines below and re | place <path to macfp-db>
# with the path (absolute or relative) to your macfp-db repository
import sys
# sys.path.append('<path to macfp-db>/macfp-db/Util | ities/')
sys.path.append('../../../../../../macfp-db/Utilities/')
import macfp
import importlib
importlib.reload(macfp)
import matplotlib.pyplot as plt
macfp.dataplot(config_filename='SNL_dataplot_config.csv',
institute='Sandia National Laboratories',
expdir='../../../Experimental_Data/'... |
danduggan/hltd | cgi/harakiri_cgi.py | Python | lgpl-3.0 | 593 | 0.005059 | #!/usr/bin/env python2.6
import cgi
impor | t time
import os
import subprocess
""" |
problem: cgi scripts run as user 'nobody'
how can we handle signaling the daemon ?
"""
form = cgi.FieldStorage()
print "Content-Type: text/html" # HTML is following
print
print "<TITLE>CGI script output</TITLE>"
print "Hey I'm still here !"
try:
if os.path.exists('harakiri'):
os.remove('h... |
ravyg/algorithms | python/238_productArrayExceptSelf.py | Python | gpl-3.0 | 721 | 0.015257 | #!/usr/bin/python
# Given an array of n | integers where n > 1, nums, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i].
class Solution(object):
# @param {integer[]} nums
# @return {integer[]}
def productExceptSelf(self, nums):
p | = 1
n = len(nums)
output = []
# Forward range.
for i in range(0,n):
output.append(p)
p = p * nums[i]
p = 1
# Backword range.
for i in range(n-1,-1,-1):
output[i] = output[i] * p
p = p * nums[i]
return output... |
mcanthony/nupic | src/nupic/data/CategoryFilter.py | Python | agpl-3.0 | 2,276 | 0.003954 | #! /usr/bin/env python
# ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2013, Numenta, Inc. Unless you have an agreement
# with Numenta, Inc., for a separate license for this software code, the
# following terms and conditions... | oundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU Affero Public License for | more details.
#
# You should have received a copy of the GNU Affero Public License
# along with this program. If not, see http://www.gnu.org/licenses.
#
# http://numenta.org/licenses/
# ----------------------------------------------------------------------
'''
A category filter can be applied to any categorical fiel... |
multispot-software/transfer_convert | analyze.py | Python | mit | 3,069 | 0.000326 | #!/usr/bin/env python
from pathlib import Path
import nbrun
default_notebook_name = 'smFRET-PAX_single_pop.ipynb'
def run_analysis(data_filename, input_notebook=None, save_html=False,
working_dir=None, suffix='', dry_run=False):
"""
Run analysis notebook on the passed data file.
Argume... | dry_run (bool): just pretenting. Do not run or save any notebook.
"""
if input_notebook is None:
input_notebook = default_notebook_name
print(' * Running analysis for %s' % (data_filename.stem), flush=True)
| if working_dir is None:
working_dir = data_filename.parent
out_path_html = Path(data_filename.parent, 'reports_html',
data_filename.stem + suffix + '.html')
out_path_nb = Path(data_filename.parent,
data_filename.stem + suffix + '.ipynb')
out_path_html... |
jss-emr/openerp-7-src | openerp/addons/account/account_move_line.py | Python | agpl-3.0 | 70,268 | 0.005764 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU... | 'period_from'], context=context).company_id.id
first_period = fiscalperiod_obj.search(cr, uid, [('company_id', '=', period_company_id)], order='date_start', limit=1)[0]
context['periods'] = fiscalperiod_obj.build_ctx_peri | ods(cr, uid, first_period, context['period_from'])
else:
context['periods'] = fiscalperiod_obj.build_ctx_periods(cr, uid, context['period_from'], context['period_to'])
if context.get('periods', False):
if initial_bal:
query = obj+".state <> 'draft' AND "+o... |
leapp-to/prototype | leapp/utils/meta.py | Python | lgpl-2.1 | 1,358 | 0.001473 | import itertools
def with_metaclass(meta_class, base_class=obje | ct):
"""
:param meta_class: The desired metaclass to use
:param base_class: The desired base class to use, the default one is object
:type base_class: Type
:return: Metaclass type to inherit from
:Example:
.. code-blo | ck:: python
class MyMetaClass(type):
def __new__(mcs, name, bases, attrs):
klass = super(MyMetaClass, mcs).__new__(mcs, name, bases, attrs)
klass.added = "Added field"
return klass
class MyClass(with_metaclass(MyMetaClass)):
pass
... |
stxnext/intranet-open | src/intranet3/intranet3/asyncfetchers/fake.py | Python | mit | 416 | 0 |
class FakeFetcher(object):
| """
Used i.e. in Harvest tracker when we need credentials but don | 't fetcher
"""
def __init__(self, *args, **kwargs):
pass
def fetch_user_tickets(self, *args, **kwargs):
pass
def fetch_all_tickets(self, *args, **kwargs):
pass
def fetch_bugs_for_query(self, *args, **kwargs):
pass
def get_result(self):
return []
|
cristian99garcia/pilas-activity | pilas/fisica.py | Python | gpl-3.0 | 14,319 | 0.003006 | # -*- encoding: utf-8 -*-
# pilas engine - a video game framework.
#
# copyright 2010 - hugo ruscitti
# license: lgplv3 (see http://www.gnu.org/licenses/lgpl.html)
#
# website - http://www.pilas-engine.com.ar
import pilas
from pilas import colores
try:
import Box2D as box2d
except ImportError:
print "No esta... | dy()
if s.TestPoint(cuerpo.GetXForm(), (x, y)):
lista_de_cuerpos.append(cuerpo)
return lista_de_cuerpos
def definir_gravedad(self, x, y):
pilas.fisica.definir_gravedad(x, y)
class Figura(object):
"""Representa un figura que simula un cuerpo fisico.
Esta figu... | el resto
de las figuras cómo el Circulo o el Rectangulo simplemente."""
def obtener_x(self):
return self._cuerpo.position.x
def definir_x(self, x):
self._cuerpo.SetXForm((x, self.y), self._cuerpo.GetAngle())
def obtener_y(self):
return self._cuerpo.position.y
def definir_... |
ramsateesh/designate | designate/backend/agent_backend/impl_bind9.py | Python | apache-2.0 | 5,255 | 0 | # Copyright 2014 Rackspace Inc.
#
# Author: Tim Simmons <tim.simmons@rackspace.com>
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unl... | help='RNDC Config File'),
cfg.StrOpt('rndc-key-file', default=None, help='RNDC Key File'),
cfg.StrOpt('zone-file-path', default='$state_path/zones',
help='Path where zone files are stored'),
cfg.StrOpt('query-destination', default='127.0.0.1',... | tart(self):
LOG.info(_LI("Started bind9 backend"))
def find_domain_serial(self, domain_name):
LOG.debug("Finding %s" % domain_name)
resolver = dns.resolver.Resolver()
resolver.nameservers = [cfg.CONF[CFG_GROUP].query_destination]
try:
rdata = resolver.query(domai... |
DarkEnergySurvey/ugali | ugali/pipeline/run_04.0_peak_finder.py | Python | mit | 4,508 | 0.013088 | #!/usr/bin/env python
"""Perform object finding and association."""
import os, glob
from os.path import exists, join
import time
import fitsio
import numpy as np
from ugali.analysis.pipeline import Pipeline
from ugali.analysis.search import CandidateSearch
import ugali.candidate.associate
from ugali.utils.logger im | port logger
from ugali.utils.shell import mkdir
components = ['label','objects','associate','candidate','plot','www']
def load_candi | dates(filename,threshold=0):
""" Load candidates for plotting """
candidates = fitsio.read(filename,lower=True,trim_strings=True)
candidates = candidates[candidates['ts'] >= threshold]
return candidates
def run(self):
if 'label' in self.opts.run:
logger.info("Running 'label'...")
i... |
notmyname/swift | test/unit/cli/test_recon.py | Python | apache-2.0 | 44,459 | 0.000135 | # Copyright (c) 2013 Christian Schwede <christian.schwede@enovance.com>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required b... | pfile
import time
import unittest
import shutil
import string
import sys
import six
from eventlet.green import socket
from six import StringIO
from six.moves import urllib
from swift.cli import recon
from swift.common import utils
from swift.common.ring import builder
from swift.common.ring import utils as ring_utils... | quest as urllib2
else:
from eventlet.green import urllib2
class TestHelpers(unittest.TestCase):
def test_seconds2timeunit(self):
self.assertEqual(recon.seconds2timeunit(10), (10, 'seconds'))
self.assertEqual(recon.seconds2timeunit(600), (10, 'minutes'))
self.assertEqual(recon.seconds2t... |
nemobis/bots | iccd-trc2csv.py | Python | gpl-3.0 | 4,621 | 0.01926 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Script to convert an ICCD TRC file to CSV format.
The input file is assumed to be UTF-8 with UNIX line ending.
"""
#
# (C) Federico Leva, 2016
#
# Distributed under the terms of the MIT license.
#
__version__ = '0.1.0'
import codecs
import unicodecsv as csv
from collectio... | ].it | erkeys():
if key == "IDK":
description += "| source = {{Museoscienza|idk=%s}}\n" % data[i]['IDK']
else:
description += u"| %s = %s\n" % (key, data[i][key])
if re.match('FTA[0-9]+I', key):
filenames.append(directory + data[i][key])
description += u"}}"
# The filenames may have excess leading zeros, but... |
Semprini/cbe | cbe/cbe/wsgi.py | Python | apache-2.0 | 383 | 0 | """
WSGI config for cbe 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/wsgi/
"""
import os
from django.core.wsgi impor | t get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "cbe.settings")
application = get_wsgi_application()
|
vgteam/toil-vg | src/toil_vg/iostore.py | Python | apache-2.0 | 36,706 | 0.009562 | """
IOStore class originated here
https://github.com/BD2KGenomics/hgvm-graph-bakeoff-evaluations/blob/master/scripts/toillib.py
and was then here:
https://github.com/cmarkello/toil-lib/blob/master/src/toil_lib/toillib.py
In a perfect world, this would be deprecated and replaced with Toil's stores.
Actually did t... | tar, with a relative
# path
tar.add(os.path.join(path, file_name), arcname=file_name)
# Save the file on disk to the file store.
return file_store.writeGlobalFile(tee)
el | se:
with file_store.writeGlobalFileStream(cleanup=cleanup) as (file_handle,
file_id):
# We have a stream, so start taring into it
# TODO: don't duplicate this code.
with tarfile.open(fileobj=file_handle, mode=write_stream_mode) as tar:
# Open ... |
kjchalup/dtit | fcit/fcit.py | Python | mit | 7,474 | 0.001338 | """ A fast conditional independence test.
This implementation uses the joblib library to parallelize test
statistic computation over all available cores. By default, num_perm=8
(instead of num_perm=10 in the non-parallel version) as 8 cores is a
common number on current architectures.
Reference:
Chalupka, Krzysztof a... | z (n_samples, z_dim): | Optional auxiliary input data.
cv_grid (list of floats): List of hyperparameter values to try.
logdim (bool): If True, set max_features to 'log2'.
verbose (bool): If True, print out extra info.
prop_test (float): Proportion of validation data to use.
Returns:
DecisionTreeReg... |
xiangke/pycopia | mibs/pycopia/mibs/HOST_RESOURCES_MIB_OID.py | Python | lgpl-2.1 | 5,000 | 0.0164 | # python
# This file is generated by a program (mib2py).
import HOST_RESOURCES_MIB
OIDMAP = {
'1.3.6.1.2.1.25': HOST_RESOURCES_MIB.host,
'1.3.6.1.2.1.25.1': HOST_RESOURCES_MIB.hrSystem,
'1.3.6.1.2.1.25.2': HOST_RESOURCES_MIB.hrStorage,
'1.3.6.1.2.1.25.2.1': HOST_RESOURCES_MIB.hrStorageTypes,
'1.3.6.1.2.1.25.3': HOST... | URCES_MIB.hrStorageAllocationFailures,
'1.3.6.1.2.1.25.3.2.1.1': HOST_RESOURCES_MIB.hrDeviceIndex,
'1.3.6.1.2.1.25.3.2.1.2': HOST_RESOURCES_MIB.hrDeviceType,
'1.3.6.1.2.1.25.3.2.1.3': HOST_RESOURCES_MIB.hrDeviceDescr,
'1.3.6.1.2.1.25.3.2.1.4': HOST_RESOURCES_MIB.hrDeviceID,
'1.3.6.1.2.1.25.3.2.1.5': HOST_RESOURCES_MIB.... | .2.1.25.3.3.1.2': HOST_RESOURCES_MIB.hrProcessorLoad,
'1.3.6.1.2.1.25.3.4.1.1': HOST_RESOURCES_MIB.hrNetworkIfIndex,
'1.3.6.1.2.1.25.3.5.1.1': HOST_RESOURCES_MIB.hrPrinterStatus,
'1.3.6.1.2.1.25.3.5.1.2': HOST_RESOURCES_MIB.hrPrinterDetectedErrorState,
'1.3.6.1.2.1.25.3.6.1.1': HOST_RESOURCES_MIB.hrDiskStorageAccess,
'... |
AMOboxTV/AMOBox.LegoBuild | plugin.video.titan/resources/lib/resolvers/ishared.py | Python | gpl-2.0 | 1,793 | 0.016732 | # -*- coding: utf-8 -*-
'''
Genesis Add-on
Copyright (C) 2015 lambda
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 Fr | ee 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 Pu... | .
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
'''
import re,urllib
from resources.lib.libraries import client
from resources.lib.libraries import jsunpack
def resolve(url):
try:
headers = '|%s' % urllib.... |
zephyrplugins/zephyr | zephyr.plugin.jython/jython2.5.2rc3/Lib/test/test_list_jy.py | Python | epl-1.0 | 3,309 | 0.007555 | import unittest
import random
import threading
import time
from test import test_support
if test_support.is_jython:
from java.util import ArrayList
from java.lang import String
class ListT | estCase(unittest.TestCase):
def test_recursive_list_slices(self):
x = [1,2,3,4,5]
x[1:] = x
self.assertEquals(x, [1, 1, 2, 3, 4, 5],
"Recursive assignment to list slices failed")
def test_sub | class_richcmp(self):
# http://bugs.jython.org/issue1115
class Foo(list):
def __init__(self, dotstring):
list.__init__(self, map(int, dotstring.split(".")))
bar1 = Foo('1.2.3')
bar2 = Foo('1.2.4')
self.assert_(bar1 < bar2)
self.assert_(bar1 <= b... |
dhermes/google-cloud-python | spanner/google/cloud/spanner_v1/client.py | Python | apache-2.0 | 11,355 | 0.000264 | # Copyright 2016 Google LLC All rights reserved.
#
# Licensed under the Apache Lice | nse, Version 2.0 (the "License");
# you may not use this file except in compliance wit | h 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 implie... |
denniskline/garage-door | alarm_door_open.py | Python | apache-2.0 | 2,822 | 0.006378 | #!/usr/bin/python3
import os
import time
import logging
import getopt
import sys
from gdmod import ApplicationConfiguration
from gdmod import Database
from gdmod import DoorState
from gdmod import Sms
# ************************************************************************
# Schedule to run whenever you would like ... | *******************************************
def main():
# Check command options to see if a custom configuration directory was supplied
configDir = os.path.abspath(get_config_directory(sys.argv[1:], './conf'))
if not os.path.isdir(configDir):
| raise ValueError('No such configuration directory exists: {}'.format(configDir))
# Read in the configurations
config = ApplicationConfiguration(configDir, ['door.ini', 'account-settings.ini'])
# Setup logger
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
... |
IT-PM-OpenAdaptronik/Webapp | apps/projects/serializer.py | Python | mit | 2,086 | 0.011026 | from apps.projects.models import Experiment, Project, Datarow, Value
def project_serialize(project_id):
#get all experiments from that project into a nested list of dictionaries to post to the selected webservice
experiment_objects = list(Experiment.objects.filter(project=project_id))
for experiment_object... | datarow_attributes = {
'name' : datarow_object.name,
'unit' : datarow_object.unit,
'description' : datarow_object.description,
'function_type' : datarow_object.function_type,
'response_node' : datarow_object.response_node,
'... | datarow_object.response_name,
'response_dir' : datarow_object.response_dir,
'reference_node' : datarow_object.reference_node,
'reference_name' : datarow_object.reference_name,
'reference_dir' : datarow_object.reference_dir,
'data_format' :... |
ChrisCummins/intel-gpu-tools | tools/quick_dump/reg_access.py | Python | mit | 473 | 0.042283 | #!/usr/bin/env python3
import chipset
def read(reg):
reg = int(reg, 16)
val = chipset.intel_register_read(reg)
return val
def init():
pci_dev = chipset.intel_ge | t_pci_device()
ret = chipset.intel_register_access_init(pci_dev, 0)
if ret != 0:
print("Register access init failed");
return False
return True
if __name__ == "__main__":
import sys
if init() == Fal | se:
sys.exit()
reg = sys.argv[1]
print(hex(read(reg)))
chipset.intel_register_access_fini()
|
Laharah/calibre-access | calibre_access/__init__.py | Python | mit | 386 | 0.005181 | from .calibre_access import (print_record, calibre_downloads, calibre_searches,
| all_records, download_coro, search_coro, download_database,
locate_logs, get_database)
__all__ = (print_record, calibre_download | s, calibre_searches, all_records, download_coro,
search_coro, download_database, locate_logs, get_database)
|
aipescience/daiquiri-admin | daiquiri/machine.py | Python | apache-2.0 | 4,577 | 0.000874 | import os
import pwd
import spwd
import grp
import subprocess
class Machine():
def __init__(self, dryrun=False, default_gid=2000, uid_range=[2000, 3000]):
self.dryrun = dryrun
self.default_gid = default_gid
self.uid_range = uid_range
def call(self, cmd):
if self.dryrun:
... | uid = system_user.pw_uid
return uid + 1
def get_full_name(self, user):
return user['details']['firstname'] + ' ' + user['details']['lastname']
def create_user(self, user, password):
# get the username
username = user['username']
# check if the user exists... | ists.' % username)
except KeyError:
pass
# get the uid for the new user
try:
uid = int(user['details']['UID'])
except KeyError:
uid = self.get_new_uid()
# check if the uid is not already there
try:
pwd.getpwuid(uid)
... |
projeto-si-lansab/si-lansab | ARDrone/libARDrone.py | Python | gpl-2.0 | 36,206 | 0.016434 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
python library for the AR.Drone 1.0 (1.11.5) and 2.0 (2.2.9).
parts of code from Bastian Venthur, Jean-Baptiste Passot, Florian Lacrampe.
tested with Python 2.7.3 and AR.Drone vanilla firmware 1.11.5.
"""
# < imports >-------------------------------------------------... | mixed" )
# l_log.setLevel ( w_logLvl )
# l_log.debug ( ">>" )
# animation to play
li_anim = arDefs.ARDRONE_LED_A | NIMATION_DOUBLE_MISSILE
# frequence in HZ of the animation
lf_freq = 2.
# total duration in seconds of the animation
lf_secs = 4
# play LED animation
self.at ( arATCmds.at_led, li_anim, lf_freq, lf_secs )
# animation to play
li_anim = arDefs.AR... |
altendky/canmatrix | src/canmatrix/cli/convert.py | Python | bsd-2-clause | 10,309 | 0.006208 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (c) 2013, Eduard Broecker
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification, are permitted provided that
# the following conditions are met:
#
# Redistributions of source code must retain the above co... | lt="iso-8859-1", help="Import charset of dbf, maybe utf-8\ndefault iso-8859-1")
@click.option('--dbfExportEncoding', 'dbfExportEncoding', default="iso-8859-1", help="Export charset of dbf, maybe utf-8\ndefault iso-8859-1")
# sym switches
@click.option('--symImportEncoding', 'symImportEncoding', default="iso-8859-1", he... | e utf-8\ndefault iso-8859-1")
# xls/csv switches
@click.option('--xlsMotorolaBitFormat', 'xlsMotorolaBitFormat', default="msbreverse", help="Excel format for startbit of motorola codescharset signals\nValid values: msb, lsb, msbreverse\n default msbreverse")
@click.option('--additionalFrameAttributes', 'additionalFrame... |
apple/swift | utils/pass-pipeline/src/pass_pipeline_library.py | Python | apache-2.0 | 2,942 | 0 |
import pass_pipeline as ppipe
import passes as p
def simplifycfg_silcombine_passlist():
return ppipe.PassList([
p.SimplifyCFG,
p.SILCombine,
p.SimplifyCFG,
])
def highlevel_loopopt_passlist():
return ppipe.PassList([
p.LowerAggregateInstrs,
p.SILCombine,
... | ropagation,
p.DCE,
p.CSE,
p.SILCombine,
simplifycfg_silcombine_passlist(),
p.GlobalLoadStoreOpts,
| # Need to add proper argument here
p.CodeMotion,
p.GlobalARCOpts,
p.SpeculativeDevirtualizer,
p.SILLinker,
inliner_for_optlevel(optlevel),
p.SimplifyCFG,
p.CodeMotion,
p.GlobalARCOpts,
])
def lower_passlist():
return ppipe.PassList([
p.De... |
wheeler-microfluidics/microdrop | microdrop/core_plugins/command_plugin/microdrop_plugin.py | Python | bsd-3-clause | 3,275 | 0.000305 | import logging
from logging_helpers import _L
from pygtkhelpers.gthreads import gtk_threadsafe
import threading
import zmq
from .plugin import CommandZmqPlugin
from ...app_context import get_hub_uri
from ...plugin_helpers import hub_execute
from ...plugin_manager import (PluginGlobals, SingletonPlugin, IPlugin,
... | aunch background thread to monitor plugin ZeroMQ command socket.
Use :func:`gtk_threadsafe` decorator to wrap thread-related code
to ensure GTK/GDK | are initialized properly for a threaded
application.
"""
self.cleanup()
zmq_ready = threading.Event()
def _check_command_socket(wait_duration_s):
'''
Process each incoming message on the ZeroMQ plugin command socket.
Stop listening if :a... |
google-research/disentanglement_lib | disentanglement_lib/config/abstract_reasoning_study_v1/stage1/sweep.py | Python | apache-2.0 | 5,267 | 0.010442 | # coding=utf-8
# Copyright 2018 The DisentanglementLib 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
#
# Un... | , betas])
all_models = h.chainit([
config_beta_vae, config_factor_vae, config_dip_vae_i, config_dip_vae_ii,
config_beta_tc_vae, config_annealed_beta_vae
])
return all_models
def get_config():
"""Returns the hyperparameter configs for different experiments."""
arch_enc = h.fixed("encoder.encoder_... | "@conv_encoder", length=1)
arch_dec = h.fixed("decoder.decoder_fn", "@deconv_decoder", length=1)
architecture = h.zipit([arch_enc, arch_dec])
return h.product([
get_datasets(),
architecture,
get_default_models(),
get_seeds(5),
])
class AbstractReasoningStudyV1(study.Study):
"""Defin... |
BertrandBordage/django-tree | run_benchmark.py | Python | bsd-3-clause | 233 | 0 | #!/usr/bin/env python
import os
import django
if __name | __ == '__main__':
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'benchmark.settings')
django.setup()
from benchmark.base impor | t Benchmark
Benchmark().run()
|
Nodoka/Bioquality | graphing/tdwg_scatter.py | Python | mit | 1,350 | 0.002963 | #!/usr/local/bin/ipython -i
"""
A scatter graph of grid count vs grid area.
"""
import numpy as np
import matplotlib.pyplot as plt
# extract data from csv
file_name = "../data/tdwgsp_filtered.csv"
# columns (filtered):
# 1 - star_infs
# 2 - tdwgtotals
# 3 - tdwgareas
star_infs = np.genfromtxt(file_name, delimiter=','... | p_header=1, usecols=1)
tdwg_count = np.genfromtxt(file_name, deli | miter=',', dtype=None, skip_header=1, usecols=2)
tdwg_area = np.genfromtxt(file_name, delimiter=',', dtype=None, skip_header=1, usecols=3)
# remove "" from the text string
stars = [star[1:-1] for star in star_infs]
colours = map(lambda star_colour: 'k' if star_colour == 'BK' else 'y' if star_colour == 'GD' else 'b' i... |
gigitux/lollypop | src/pop_next.py | Python | gpl-3.0 | 2,854 | 0 | # Copyright (c) 2014-2015 Cedric Bellegarde <cedric.bellegarde@adishatz.org>
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later vers... | m_surface(art)
del art
self._cover.set_tooltip_text(Lp.player.next_track.album.name)
self._cover.show()
else:
self._cover.hide()
def do_show(self):
"""
Connect signal
"""
self._signal_id = Lp.player.connect('queue-changed',... | if self._signal_id is not None:
Lp.player.disconnect(self._signal_id)
Gtk.Popover.do_hide(self)
#######################
# PRIVATE #
#######################
def _on_skip_btn_clicked(self, btn):
"""
Skip next track
@param btn as Gtk.Button
... |
ytec/instaforex-web | app/pages/admin.py | Python | gpl-3.0 | 201 | 0 | from django.contrib import admin
fro | m cms.admin.pageadmin import PageAdmin
from cms.models import Page
from .models import page, Sub_Pages
admin.site.register(page)
admin.site.register(Sub_Pages | )
|
TylerTemp/tomorrow | lib/db/jolla.py | Python | gpl-3.0 | 11,853 | 0.000169 | import pymongo
import logging
import time
# import sys
# import os
# sys.path.insert(0, os.path.normpath(os.path.join(__file__, '..', '..', '..')))
# from lib.db.base import Base
from .base import Base
logger = logging.getLogger('db.jolla')
client = pymongo.MongoClient()
db = client['jolla']
# TODO: support more sit... | n cls.collection.find({'author': uid}).sort(
(
('create_t | ime', pymongo.DESCENDING),
)
)
@classmethod
def all(cls, offset=0, limit=None):
result = cls.collection.find({}).sort(
(
('create_time', pymongo.DESCENDING),
)
)
if limit is None:
return result[offset:]
return ... |
flypy/flypy | flypy/tests/test_control_flow.py | Python | bsd-2-clause | 2,894 | 0.001037 | # -*- coding: utf-8 -*-
from __future__ import print_function, division, absolute_import
import unittest
from flypy import jit
class TestControlFlow(unittest.TestCase):
def test_loop_carried_dep_promotion(self):
@jit
def f(n):
sum = 0
for i in range(n):
sum... | , f.py_func(3))
def test_for_continue(self):
@jit
def f(n):
sum = 0
for i in range(n):
if i > n - 4:
continue
sum += i
return sum
self.assertEqual(f(10), f.py_func(10) | )
def test_for_break(self):
@jit
def f(n):
sum = 0
for i in range(n):
if i > n - 4:
break
sum += i
return sum
self.assertEqual(f(10), f.py_func(10))
def test_while_continue(self):
@jit
... |
RyanChinSang/LeagueLatency | History/Raw/v2.2a Stable/LL.py | Python | gpl-3.0 | 21,253 | 0.00494 | import os
import sys
import math
import errno
import subprocess
import tkMessageBox
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from PIL import Image
from matplotlib import style
from datetime import datetime
from matplotlib.widgets import RadioBu... | le__) + '/static/buttons/dec.png')
inc_img = Image.open(os.path.dirname(__file__) + '/static/buttons/inc.png')
null_img = Image.open(os.path.dirname(__file__) + '/static/buttons/null.png')
stgd_img = Image.open(os.path.dirname(__file__) + '/static/buttons/stgd.png')
stwr_img = Image.open(os.path.dirname(__file__) + '/s... | file__) + '/static/buttons/stbd.png')
unstgd_img = Image.open(os.path.dirname(__file__) + '/static/buttons/unstgd.png')
unstwr_img = Image.open(os.path.dirname(__file__) + '/static/buttons/unstwr.png')
unstbd_img = Image.open(os.path.dirname(__file__) + '/static/buttons/unstbd.png')
unstlgd_img = Image.open(os.path.dir... |
ntymtsiv/tempest | tempest/services/identity/v3/json/policy_client.py | Python | apache-2.0 | 2,378 | 0 | # Copyright 2013 OpenStack Foundation
# 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 requ... | """Lists the policies."""
resp, body = self.get('policies')
body = json.loads(body)
return resp, body['policies']
def get_policy(self, policy_id):
"""Lists out the given policy."""
url = 'policies/%s' % policy_id
resp, body = self.get(url)
| body = json.loads(body)
return resp, body['policy']
def update_policy(self, policy_id, **kwargs):
"""Updates a policy."""
resp, body = self.get_policy(policy_id)
type = kwargs.get('type')
post_body = {
'type': type
}
post_body = json.dumps({'... |
haxsaw/actuator | src/actuator/provisioners/example_resources.py | Python | mit | 2,612 | 0.004977 | #
# Copyright (c) 2014 Tom Carroll
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, dis... | kwargs)
self.kwargs = kwargs
def get_init_args(self):
return ((self.name,), self.kwargs)
class Queue(ProvisionableWithFixer):
def __init__(self, name, **kwargs):
super(Queue, self).__init__(name)
self.provisionedName = None
s | elf.qmanager = None
self.host = None
self.port = None
object.__getattribute__(self, "__dict__").update(kwargs)
self.kwargs = kwargs
def get_init_args(self):
return((self.name,), self.kwargs)
|
wonkoderverstaendige/PyFL593FL | PyFL593FL/ui/__init__.py | Python | mit | 117 | 0.017094 | # -*- coding: utf-8 -*-
"""
Created on 05 Apr 2014 3:30 AM
@author: <'Ronny Eichler | '> ronny.eichler@gmai | l.com
UI
""" |
jfinkels/networkx | examples/drawing/circular_tree.py | Python | bsd-3-clause | 639 | 0.001565 | import networkx as nx
import matplotlib.pyplot as plt
try:
import pygraphviz
from networkx.drawing.nx_agraph import graphviz_layout
except ImportError:
try:
import pydot
from net | workx.drawing.nx_pydot import graphviz_layout
except ImportError:
raise ImportError("This example needs Graphviz and either "
"P | yGraphviz or pydot")
G = nx.balanced_tree(3, 5)
pos = graphviz_layout(G, prog='twopi', args='')
plt.figure(figsize=(8, 8))
nx.draw(G, pos, node_size=20, alpha=0.5, node_color="blue", with_labels=False)
plt.axis('equal')
plt.savefig('circular_tree.png')
plt.show()
|
threema-ch/threema-msgapi-sdk-python | threema/gateway/bin/callback_server.py | Python | mit | 4,446 | 0.0009 | """
The command line interface for the Threema Gateway Callback Server.
"""
import asyncio
import functools
import click
import logbook
import logbook.more
from threema.gateway import __version__ as _version
from threema.gateway import (
Connection,
util,
)
from threema.gateway.e2e import AbstractCallback
fro... | ion as exc:
click.echo('An error occurred:', err=True)
click.echo(exc, err=True)
raise
finally:
if _logging_handler is not None:
_logging_hand | ler.pop_application()
if __name__ == '__main__':
main()
|
pwittchen/learn-python-the-hard-way | exercises/exercise36.py | Python | mit | 105 | 0 | # Exercise 36: Designing and debugging
# No code |
# Read: http://learnpytho | nthehardway.org/book/ex36.html
|
power12317/weblate | weblate/trans/migrations/0011_add_file_format.py | Python | gpl-3.0 | 13,518 | 0.007843 | # -*- coding: utf-8 -*-
#
# Copyright © 2012 - 2013 Michal Čihař <michal@cihar.com>
#
# This file is part of Weblate <http://weblate.org/>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, eithe... | ango.db.models.fields.URLField', [], {'max_length': '200', 'blank': 'True'}),
'mail': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'merge_style': ('django.db.models.fields.CharField', [], {'default': "'merge'", 'max_length': '10'}),
'name': ('dja... | 00'}),
|
Emma926/paradnn | test.py | Python | apache-2.0 | 4,858 | 0.011116 | ''' A self-contained test file.
@author Emma Wang
'''
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
from tensorflow.contrib.tpu.python.tpu import tpu_config
from tensorflow.contrib.tpu.python.tpu import tpu_estimator
from tensorfl... | ph(),
options=ProfileOptionBuilder.trainable_variables_parameter())
fl_stats = tf.profiler.profile(
tf.get_default_graph(),
options=tf.profiler.ProfileOptionBuilder.fl | oat_operation())
return tpu_estimator.TPUEstimatorSpec(
mode=mode,
loss=loss,
train_op=train_op)
ProfileOptionBuilder = tf.profiler.ProfileOptionBuilder
def main(unused_argv):
start = time.time()
tf.logging.set_verbosity(tf.logging.INFO)
if FLAGS.use_tpu:
tf.logging.info("Using TPU... |
lipixun/newsanalyzer4w | newsanalyzer/utils.py | Python | gpl-3.0 | 329 | 0.006116 | # encoding=utf8
# pylint: disable=W0611
""" The utility
| Author: lipixun
Created Time : 日 2/12 14:14:50 2017
File Name: utils.py
Description:
"""
from spec import DataPath
# Import json
try:
import simplejson as json
except ImportError:
import json
# NLTK
import nltk
nltk.data.path = [ DataPa | th ]
|
johnskopis/naglib | naglib/config/command.py | Python | mit | 342 | 0.002924 | #!/usr/bin/env python
from base import *
""" A representation of a nagios service dependency"""
class Command(BaseObject):
TYPE = 'command'
TEMPLATE_CLASS = None
PARAMS = (
'command_name',
'command_line'
)
REQUIRED_PARAMS = PARAMS
@property
def identity(self | ):
return self.command_name
| |
ddimensia/RaceCapture_App | autosportlabs/racecapture/views/configuration/rcp/wireless/bluetoothconfigview.py | Python | gpl-3.0 | 3,672 | 0.004085 | import kivy
kivy.require('1.9.1')
from kivy.app import Builder
from kivy.uix.gridlayout import GridLayout
from kivy.properties import ObjectProperty
from kivy.logger import Logger
from settingsview import SettingsView, SettingsSwitch, SettingsButton
from autosportlabs.widgets.separator import HLineSeparator
from autosp... | ig = config
value = self.config.connectivityConfig.bluetoothConfig.btEnabled
bluetooth_enabled = self.ids.bt_enable
bluetooth_enabled.setControl(SettingsSwitch(active=value))
bluetooth_enabled.control.bind(active=self.on_bluetooth_enabled_change)
def on_modified(self):
pas... | _bt_configure(self, instance, value):
if not self._bt_popup:
content = AdvancedBluetoothConfigView(self.config.connectivityConfig)
popup = editor_popup(title="Configure Bluetooth", content=content,
answerCallback=self.on_bluetooth_popup_answer)
... |
stetie/postpic | postpic/_compat/functions.py | Python | gpl-3.0 | 3,618 | 0.000553 | #
# This file is part of postpic.
#
# postpic 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.
#
# postpic is distributed in the hope th... | 'lib',
'minver'])
replacements = [
ReplacementFunction('meshgrid', np, np_meshgrid, np, '1.9'),
ReplacementFunction('broadcast_to', np, np_broadcast_to, np, '1.10'),
ReplacementFunction('mov | eaxis', np, np_moveaxis, np, '1.11'),
ReplacementFunction('tukey', sps, sps_tukey, sp, '0.16')
]
|
jazzband/site | jazzband/projects/commands.py | Python | mit | 1,877 | 0.000533 | import logging
import click
import click_log
from flask.cli import with_appcontext
from ..account import github
from . import tasks
from .models import Project
logger = logging.getLogger(__name__)
click_log.basic_config(logger)
@click.command("projects")
@click_log.simple_verbosity_option(logger)
@with_appcontext
... | ppcontext
def sync_project_members():
"Syncs project members"
tasks.sync_project_members()
| @click.command("new_upload_notifications")
@click.option("--project_id", "-p", default=None)
@click_log.simple_verbosity_option(logger)
@with_appcontext
def send_new_upload_notifications(project_id):
tasks.send_new_upload_notifications(project_id)
@click.command("project_team")
@click.argument("name")
@click_log.... |
joke2k/faker | faker/providers/job/fi_FI/__init__.py | Python | mit | 6,120 | 0 | from .. import Provider as BaseProvider
class Provider(BaseProvider):
# jobs parsed from a list provided by State Treasury:
# http://www.valtiokonttori.fi/download/noname/%7BF69EA5BD-C919-49FE-8D51-91434E4B030D%7D/82158
jobs = [
"Agrologi",
"Aikuiskoulutusjohtaja",
"Aineenopettaja"... | -asiantuntija",
"Upseeri",
"Urakonsultti",
"Urheiluohjaaja",
"Vaaitsija",
"Vac-yhdyshenkilö",
"Vahingonkorvausasiantuntija",
"Vaihteenhoitaja",
"Vakuustoimittaja",
"Valaistusmestari",
"Vammaisasiamies",
"Vanhempi tutkijainsinööri",
... | asiantuntija",
"Yhdenvertaisuusvaltuutettu",
"Yhteinen tuntiopettaja",
"Yksikkösihteeri",
"Yleinen edunvalvoja",
"Yliaktuaari",
"Ylläpidon palvelupäällikkö",
"Yläasteen rehtori",
"Ympärintönsuojeluyksikön päällikkö",
"Yrittäjyysneuvoja",
"Y... |
LasLabs/python-helpscout | helpscout/tests/test_apis_tags.py | Python | mit | 1,513 | 0 | # -*- coding: utf-8 -*-
# Copyright 2017-TODAY LasLabs Inc.
# License MIT (https://opensource.org/licenses/MIT).
from .api_common import ApiCommon, recorder
class TestApisTags(ApiCommon):
"""Tests the Tags API endpoint."""
def setUp(self):
super(TestApisTags, self).setUp()
self.__endpoint__ ... | rtRaises(NotImplementedError):
self.__endpoint__.delete(None)
@recorder.use_cassette()
def test_apis_tags_update(self):
"""It should not be implemented."""
with self.assertRaises(NotImplementedError):
self.__endpoint__.update(None)
@recorder.use_cassette()
def t... | self.__endpoint__.create(None)
@recorder.use_cassette()
def test_apis_tags_list(self):
"""It should list the tags in the tag."""
self._test_list()
@recorder.use_cassette()
def test_apis_tags_search(self):
"""It should not be implemented."""
with self.assertRais... |
andres00157/Curso-de-javeriana | 4.py | Python | apache-2.0 | 1,335 | 0.03221 | print ("suma de los digitos de un numero")
print ("de cuantos digitos quere trabajar")
a = int(raw_input("numero de dijitos"))
if a == 2 :
print("escribe el numero")
b = int(raw_input("numero="))
c = b/10
d = b%10
print (c + d )
if a == 3 :
print("escribe el numero")
b = int(raw_input("numer... | )
if a == 7 :
print("escribe el numero")
b = int(raw_input("numero="))
c = b/10
d = b%10
p = c/10
q = c%10
u = p / 10
o = p % 10
i = u/10
e = u%10
m = i/10
n = i%10
l = m/10
j = m%10
print (q + d + o + e + n + j + l )
| |
shadowmint/nwidget | lib/cocos2d-0.5.5/test/test_remove.py | Python | apache-2.0 | 1,052 | 0.024715 | # This code is so you can run the samples without installing the package
import sys
import os
sys.path.insert(0, os.path | .join(os.path.dirname(__file__), '..'))
#
testinfo = "s, t 5.1, s, q"
|
tags = "CocosNode.remove"
import cocos
from cocos.director import director
from cocos.sprite import Sprite
from cocos.actions import *
import pyglet
class TestLayer(cocos.layer.Layer):
def __init__(self):
super( TestLayer, self ).__init__()
x,y = director.get_window_size()
... |
vallemrv/tpvB3 | cloud/contabilidad/__init__.py | Python | apache-2.0 | 192 | 0 | # @Author: Manuel Rodriguez <valle>
# @Date: 01-Jan-2018
# @Email: valle.mrv@gmail.c | om
# @Last modified by: valle
# @Last modified time: | 07-Jan-2018
# @License: Apache license vesion 2.0
|
Bobstin/AutomatedBrewery | automatedbrewery/PID.py | Python | mit | 23,167 | 0.01869 | import time
import numpy
#Based heavily on the Arduino PID library by Brett Beauregard
# By default, looks for an attribute called value for the input, and setting for the output
# If you want to change that, then you can change the input/outputAttributeName
# Input source must be available when PID is initialized to ... | self.outputPipeConn == None:
print('Error: outputPipeConn is not set')
self.stop = 1
else: |
#print(self.output)
if self._mode != "Off": self.outputPipeConn.send((self.outputAttributeName,self.output))
else:
if not(self.sentOffSignal):
... |
gazpachoking/Flexget | flexget/plugins/metainfo/metainfo_movie.py | Python | mit | 1,939 | 0.001031 | from __future__ import unicode_literals, division, absolute_import
import logging
from builtins import * # noqa pylint: disable=unused-import, redefined-builtin
from flexget import plugin
from flexget.event | import event
try:
# NOTE: Importing other plugins is discouraged!
from flexget.components.parsing.parsers import parser_common as plugin_parser_common
except ImportError:
raise plugin.DependencyError(issued_by=__name__, missing='parser_common')
log = logging.getLogger('metainfo_movie')
class MetainfoMo... | a movie, and populate movie info if so.
"""
schema = {'type': 'boolean'}
def on_task_metainfo(self, task, config):
# Don't run if we are disabled
if config is False:
return
for entry in task.entries:
# If movie parser already parsed this, don't touch it.
... |
OpenNingia/l5r-character-manager | l5rcm/models/advancements/rank.py | Python | gpl-3.0 | 3,132 | 0.014368 | # -*- coding: utf-8 -*-
# Copyright (C) 2014 Daniele Simonetti
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# Thi... | school'] = self.original_school
out['left_alternate_path'] = self.left_alternate_path
out['skills'] = []
for s in self.skills:
out['skills'].append( s.to_dict() )
return out
class StartingSkill(object):
def __init__(self, skill_id, rank = 1, emphasis ... | self.rank = rank
self.emphasis = emphasis
def to_dict(self):
out = {}
out['skill_id'] = self.skill_id
out['rank' ] = self.rank
out['emphasis'] = self.emphasis
return out
class CustomStartingSkill(object):
def __init__(self, options, rank = 1):
... |
djbaldey/django | django/core/serializers/python.py | Python | bsd-3-clause | 7,685 | 0.004294 | """
A Python "serializer". Doesn't do much serializing per se -- just converts to
and from basic Python data types (lists, dicts, strings, etc.). Useful as a basis for
other serializers.
"""
from __future__ import unicode_literals
from collections import OrderedDict
from django.apps import apps
from django.conf impor... | field):
if self.use_natural_foreign_keys and hasattr(field.remote_field.model, 'natural_key'):
related = getattr(obj, field.name)
if related:
value = related.natural_key()
else:
value = None
else:
value = getattr(obj, field... | def handle_m2m_field(self, obj, field):
if field.remote_field.through._meta.auto_created:
if self.use_natural_foreign_keys and hasattr(field.remote_field.model, 'natural_key'):
m2m_value = lambda value: value.natural_key()
else:
m2m_value = lambda value: f... |
wojnilowicz/git-cola | cola/models/dag.py | Python | gpl-2.0 | 8,995 | 0.000222 | from __future__ import division, absolute_import, unicode_literals
import json
from .. import core
from .. import utils
from ..git import git
from ..observable import Observable
# put summary at the end b/c it can contain
# any number of funky characters, including the separator
logfmt = 'format:%H%x01%P%x01%d%x01%an... | ls.root_generation)
except KeyError:
commit = | Commit(sha1=sha1,
log_entry=log_entry)
if not log_entry:
cls.root_generation += 1
commit.generation = max(commit.generation,
cls.root_generation)
cls.commits[sha1] = commit
return commit
... |
luisgustavossdd/TBD | client/pygameclient/widgets/regnancyStyle.py | Python | gpl-3.0 | 3,306 | 0.003932 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import pygame
import os
fullname = os.path.join('res', 'gui')
def init(gui):
buttonsurf = pygame.image.load(os.path.join(fullname, 'button.png')).convert_alpha()
closesurf = pygame.image.load(os.path.join(fullname,
'closebutton.png... | faultFont,
'font-color': (255, 255, 255),
'font-color-selecte | d': (0, 0, 0),
'bg-color': (55, 55, 55),
'bg-color-selected': (160, 180, 200),
'bg-color-over': (60, 70, 80),
'border-width': 1,
'border-color': (0, 0, 0),
'item-height': 22,
'padding': 2,
'autosize': False,
}
gui.defaultComboBoxStyle = gui.cr... |
lskillen/pylucene | test/test_PrefixFilter.py | Python | apache-2.0 | 4,217 | 0.000949 | # ====================================================================
# 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 re... | "/Computers/Windows"]
for category in categories:
doc = Document()
doc.add(Field("category", category, StringField.TYPE_STORED))
writer.addDocument(doc)
writer.close()
# PrefixFilter combined with ConstantScoreQuery
filter = PrefixFilter(Term... | archer()
topDocs = searcher.search(query, 50)
self.assertEqual(4, topDocs.totalHits,
"All documents in /Computers category and below")
# test middle of values
filter = PrefixFilter(Term("category", "/Computers/Mac"))
query = ConstantScoreQuery(filter)
... |
GhalebKhaled/fb-bot-test | bot/api/views.py | Python | apache-2.0 | 406 | 0.004926 | import FBBot
fb_client = FBBot.FBBotClient()
class WebhookView(FBBot.FBBotWebhookView):
| def handle_message(self, message, sender_id):
if m | essage == "logo":
fb_client.send_image(sender_id, "https://d2for33x7as0fp.cloudfront.net/static/images/53-logo.71a393299d20.png")
else:
fb_client.send_message(sender_id, "I can only repeat right now:{}".format(message))
|
JiaruZhang/Five | main/migrations/0002_auto_20170512_1731.py | Python | apache-2.0 | 2,835 | 0.001764 | # -*- coding: utf-8 -*-
# Generated by Django 1.11a1 on 2017-05-12 17:31
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('main', '0001_initial'),
]
operations = [
migrations.CreateModel(
... | ],
),
migrations.CreateModel(
name='Book',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('bookID', models.BigIntegerField()),
('ISBN', models.CharField(max_length=... | ],
),
migrations.CreateModel(
name='FavoredBook',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('userID', models.BigIntegerField()),
('bookID', models.BigIntegerFie... |
bellowsj/aiopogo | aiopogo/pogoprotos/networking/responses/add_fort_modifier_response_pb2.py | Python | mit | 4,943 | 0.00526 | # Generated by the protocol buffer compiler. DO NOT EDIT!
# source: pogoprotos/networking/responses/add_fort_modifier_response.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _messa... |
extensions=[
],
nested_types=[],
enum_types=[
_ADDFORTMODIFIERRESPONSE_RESULT,
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=163,
serialized_end=485,
)
_ADDFORTMODIFIERRESPONSE.fields_by_name['result'].enum_type = _ADDFORTMODIFIE... | AILSRESPONSE
_ADDFORTMODIFIERRESPONSE_RESULT.containing_type = _ADDFORTMODIFIERRESPONSE
DESCRIPTOR.message_types_by_name['AddFortModifierResponse'] = _ADDFORTMODIFIERRESPONSE
AddFortModifierResponse = _reflection.GeneratedProtocolMessageType('AddFortModifierResponse', (_message.Message,), dict(
DESCRIPTOR = _ADDFORT... |
dbxnr/redditbot | redditbot.py | Python | gpl-3.0 | 4,394 | 0.002048 | #!/usr/bin/env python3
import argparse
import feedparser
import logging
import praw
import requests
from config import *
from bs4 import BeautifulSoup
from html2text import html2text
logging.basicConfig(format='%(asctime)s::%(levelname)s:%(message)s',
filename='redditbot.log',
... | user_agent=user_agent)
else:
r = praw. | Reddit(client_id=client_id,
client_secret=client_secret,
refresh_token=refresh_token,
user_agent=user_agent)
logging.debug('Logged in as {}'.format(r.user.me()))
return r
# Steam news retrieval
def get_news(r, steam_app_id):
"""Pars... |
sandeep82945/audience-predictor | src/python/read_data.py | Python | cc0-1.0 | 396 | 0.037879 | #Read data from stdin
import sys, json
def read_sentence():
lines = sys.stdin.readlines()
#Since our input would only be having one | line, parse our JSON data from that
return json.loads(lines[0])
def read_sentence1():
line = sys.stdin.readline()
#Since our input would only be having one line, p | arse our JSON data from that
return line
def convert(obj):
return json.dumps(obj) |
angadpc/Alexa-Project- | twilio/rest/taskrouter/v1/workspace/__init__.py | Python | mit | 24,809 | 0.001491 | # coding=utf-8
"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from twilio.base import deserialize
from twilio.base import values
from twilio.base.instance_context import InstanceContext
from twilio.base.instance_resource import InstanceResource
from twilio.base.... | page = self.page(
friendly_name=friendly_name,
page_size=limits['page_size'],
)
return self._version.stream(page, limits['limit'], limits['page_limit'])
def list(self, friendly_name=values.unset, limit=None, page_size=None):
"""
Lists WorkspaceInstance reco... | ger and will load `limit` records into
memory before returning.
:param unicode friendly_name: The friendly_name
:param int limit: Upper limit for the number of records to return. list() guarantees
never to return more than limit. Default is no limit
:param int... |
Pylons/kai | kai/controllers/comments.py | Python | bsd-3-clause | 2,956 | 0.004736 | import logging
from pylons import request, response, session, tmpl_context as c, url
from pylons.controllers.util import abort, redirect
from pylons.templating import render_mako_def
from kai.lib.base import BaseController, render
from kai.lib.helpers import textilize
from kai.lib.serialization import render_feed
fro... | exists
doc = self.db.get(doc_id)
| if not doc:
abort(404)
comment = Comment(doc_id=doc_id, displayname=c.user.displayname,
email=c.user.email, human_id=c.user.id,
content=request.POST['content'])
comment.store(self.db)
return ''
def delete(self, ... |
maikodaraine/EnlightenmentUbuntu | bindings/python/python-efl/tests/elementary/test_01_basics.py | Python | unlicense | 652 | 0.003067 | #!/usr/bin/env python
import unittest
from efl.eo import Eo
from efl import elementary
from efl.elementary.window import Window, ELM_WIN_BASIC
from e | fl.elementary.button import Button
elementary.init()
class TestElmBasics(unittest.TestCase):
def setUp(self):
self.o = Window("t", ELM_WIN_BASIC)
def tearDown(self):
self.o.delete()
def testParentGet1(self):
self.assertIsNone(self.o.parent_get())
def testParentGet2(self):
... | f __name__ == '__main__':
unittest.main(verbosity=2)
elementary.shutdown()
|
blacksky0000/tools | tumblr/dbconnect.py | Python | mit | 463 | 0.008639 | import pymongo
import configparser
def db():
config = configparser.RawConfigParser()
config.read('./.config')
host = config.get('tumblr', 'host')
port = config.get('tumblr', 'port')
user = config.get('tumblr', 'user')
passwd = config.get('tumblr', 'passwd')
client = pymongo.MongoClient(hos... |
return testDB
| |
ProfessorX/Config | .PyCharm30/system/python_stubs/-1247972723/PyQt4/QtGui/__init__/QGestureEvent.py | Python | gpl-2.0 | 2,497 | 0.007609 | # encoding: utf-8
# module PyQt4.QtGui
# from /usr/lib/python2.7/dist-packages/PyQt4/QtGui.so
# by generator 1.135
# no doc
# imports
import PyQt4.QtCore as __PyQt4_QtCore
class QGestureEvent(__PyQt4_QtCore.QEvent):
"""
QGestureEvent(list-of-QGesture)
QGestureEvent(QGestureEvent)
"""
def accept(s... | return QGesture
def gestures(self): # real signature unknown; restored from __doc__
""" QGestureEvent.gestures() -> list-of-QGesture """
pass
def ignore(self, *__args): # real signature unknown; restored from __doc__ with multiple overloads
"""
QGestureEvent.ignore()
... | def isAccepted(self, *__args): # real signature unknown; restored from __doc__ with multiple overloads
"""
QGestureEvent.isAccepted() -> bool
QGestureEvent.isAccepted(QGesture) -> bool
QGestureEvent.isAccepted(Qt.GestureType) -> bool
"""
return False
def mapToGraphic... |
chichaj/PyFont | PyFont/FontRuntime.py | Python | mit | 5,128 | 0.00117 | #!/usr/bin/python3
import tkinter
import PIL.Image
import PIL.ImageTk
from tkinter.ttk import Progressbar as pbar
from PyFont import Font, SVG
class TkFont():
CHARY = 200
CHARX = 50
LINEY = CHARY / 2
MAIN_COLOR = '#FFFFFF'
def set_label(self):
tmp = self.words[-1].export_png_to_str()
... | svg.link_with(self.font.chr2svg(" "))
elif c == "\n":
word = False
svg.newline()
elif not word:
word = True
svg.link_with | (self.words[0])
self.words = self.words[1:]
self.gui.the_end(svg)
def get_svg(self):
if self.words:
svg = self.font.generate_svg("")
word = False
for c in self.string:
if c == " ":
word = False
... |
Southpaw-TACTIC/TACTIC | 3rd_party/python2/site-packages/cherrypy/test/test_httpauth.py | Python | epl-1.0 | 6,303 | 0 | from hashlib import md5, sha1
import cherrypy
from cherrypy._cpcompat import ntob
from cherrypy.lib import httpauth
from cherrypy.test import helper
class HTTPAuthTest(helper.CPWebCase):
@staticmethod
def setup_server():
class Root:
@cherrypy.expose
def index(self):
... | )
auth = base_auth % (nonce, '', '00000001')
params = httpauth.parseAuthorization(auth)
response = httpauth._computeDigestResponse(params, 'test')
auth = base_auth % (nonce, response, '00000001')
self.getPage('/digest | /', [('Authorization', auth)])
self.assertStatus('200 OK')
self.assertBody("Hello test, you've been authorized.")
|
RaumZeit/gdesklets-core | shell2/MenuBar.py | Python | gpl-2.0 | 1,254 | 0.008772 | import gtk
# TODO: the *_menu.append() calls here | cause a GTK assertion failure
# in the form of "GtkWarning: gtk_accel_label_set_accel_closure: assertion
# `gtk_accel_group_from_accel_closure (accel_closure) != NULL' failed"
# the exact reason is the create_menu_item-call, but I can't figure why
class MenuBar(gtk.MenuBar):
def __init__(self, main):
... | n
ac = main.get_action_group('global')
file_menu = gtk.Menu()
file_mitem = gtk.MenuItem("_File")
file_mitem.set_submenu(file_menu)
file_menu.append(ac.get_action('quit').create_menu_item())
edit_menu = gtk.Menu()
edit_mitem = gtk.MenuItem("_Edit"... |
jabesq/home-assistant | homeassistant/components/tradfri/switch.py | Python | apache-2.0 | 4,263 | 0 | """Support for IKEA Tradfri switches."""
import logging
from homeassistant.components.switch import SwitchDevice
from homeassistant.core import callback
from . import DOMAIN as TRADFRI_DOMAIN, KEY_API, KEY_GATEWAY
from .const import CONF_GATEWAY_ID
_LOGGER = logging.getLogger(__name__)
IKEA = 'IKEA of Sweden'
TRADF... | rol.set_state(False))
async def async_turn_on(self, **kwargs):
"""Instruct the switch to turn on."""
await self._api(self._socket_control.set_state(True))
@callback
def _async_start_observe(self, exc=None):
"""Start observation o | f switch."""
from pytradfri.error import PytradfriError
if exc:
self._available = False
self.async_schedule_update_ha_state()
_LOGGER.warning("Observation failed for %s", self._name,
exc_info=exc)
try:
cmd = self._switc... |
gaborbernat/tox | tests/unit/package/test_package_parallel.py | Python | mit | 4,272 | 0.000936 | import os
import traceback
import py
from flaky import flaky
from tox.session.commands.run import sequential
@flaky(max_runs=3)
def test_tox_parallel_build_safe(initproj, cmd, mock_venv, monkeypatch):
initproj(
"env_var_test",
filedefs={
"tox.ini": """
[tox]
... | t1 = threading.Thread(target=invoke_tox_in_thread, args=("t1",))
t1.start()
t1_build_started.wait()
with monkeypatch.context() as m:
def build_package(config, session):
t2_build_started.set( | )
try:
return prev_build_package(config, session)
finally:
t2_build_finished.set()
m.setattr(tox.package, "build_package", build_package)
t2 = threading.Thread(target=invoke_tox_in_thread, args=("t2",))
t2.start()
# t2 should get... |
pllim/astropy | astropy/coordinates/funcs.py | Python | bsd-3-clause | 13,747 | 0.0008 | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
This module contains convenience functions for coordinate-related functionality.
This is generally just wrapping around the object-oriented coordinates
framework, but it is useful for some users who are used to more functional
interfaces.
"""
import... | e::
This is a low-level function used internally in
`astropy.co | ordinates`. It is provided for users if they really
want to use it, but it is recommended that you use the
`astropy.coordinates` coordinate systems.
Parameters
----------
r : scalar, array-like, or `~astropy.units.Quantity`
The radial coordinate (in the same units as the inputs).
... |
tpubben/SequoiaStacking | parrotStacking.py | Python | mit | 3,776 | 0.005297 | ''' This script is prepared by Tyler Pubben and is licensed under the MIT license framework.
It is free to use and distribute however please reference http://www.tjscientific.c | om or my
GIT repository at https://github.com/tpubben/SequoiaStacking/'''
import numpy as np
import cv2
import os
def align_images(in_fldr, out_fldr, moving, fixed):
MIN_MATCH_COUNT = 10
moving_im = cv2.imread(moving, 0) # image to be distorted
fixed_im = cv2.imread(fixed, 0) | # image to be matched
# Initiate SIFT detector
sift = cv2.xfeatures2d.SIFT_create()
# find the keypoints and descriptors with SIFT
kp1, des1 = sift.detectAndCompute(moving_im, None)
kp2, des2 = sift.detectAndCompute(fixed_im, None)
# use FLANN method to match keypoints. Brute force ... |
hlin117/statsmodels | statsmodels/stats/tests/test_diagnostic.py | Python | bsd-3-clause | 40,146 | 0.007163 | # -*- coding: utf-8 -*-
"""Tests for Regression Diagnostics and Specification Tests
Created on Thu Feb 09 13:19:47 2012
Author: Josef Perktold
License: BSD-3
current | ly all tests are against R
"""
#import warnings
#warnings.simplefilter("default")
# ResourceWarning doesn't | exist in python 2
#warnings.simplefilter("ignore", ResourceWarning)
import os
import numpy as np
from numpy.testing import (assert_, assert_almost_equal, assert_equal,
assert_approx_equal, assert_allclose)
from nose import SkipTest
from statsmodels.regression.linear_model import OLS, GLSAR... |
dzoep/khal | khal/ui/widgets.py | Python | mit | 14,425 | 0.000971 | # Copyright (c) 2013-2016 Christian Geier et al.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, ... | ncrease` and `self.decrease`"""
try:
new_date = fun(self._get_current_value(), self.timedelta)
self.on_date_change(new_date)
self.set_edit_text(new_date.strftime(self.dateformat))
except DateConversionError:
pass
def set_value(self, new_date):
... | _date.strftime(self.dateformat))
class DateWidget(DateTimeWidget):
dtype = date
timedelta = timedelta(days=1)
def _get_current_value(self):
try:
new_date = datetime.strptime(self.get_edit_text(), self.dateformat).date()
except ValueError:
raise DateConversionError
... |
lnhubbell/tweetTrack | tweetTrack/wsgi.py | Python | mit | 651 | 0 | """WSGI application."""
import os
from sys import argv
from werkzeug.serving import run_simple
from werkzeug.wsgi import DispatcherMiddleware
from tweetTrack.app import app
application = DispatcherMiddleware(app)
if __ | name__ == '__main__':
if len(argv) < 2 or argv[1] == 'Dev':
os.environ['FLASK_CONFIG'] = 'Dev'
run_simple(
'localhost',
5000,
application,
__debug__
)
else:
os.environ['FLASK_CONFIG'] = argv[1].title()
print(os.enviro | n['FLASK_CONFIG'])
run_simple(
'localhost',
5000,
application,
)
|
kevinconway/PyPerf | tests/profilers/test_runtime.py | Python | apache-2.0 | 672 | 0 | """Test suite for the runtime profiler."""
from __future__ import division
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
from pyperf.profilers import runtime
def test_runtime_gives_reasonable_results():
"""Ensure runtime is measured within s... | in range(100): pass')
large, _ = profiler(setup='pass', code='for x in range(10000): pass')
assert small < larg | e
|
niklasf/python-prompt-toolkit | examples/system-prompt.py | Python | bsd-3-clause | 331 | 0.003021 | #!/usr/bin/env python
from __future__ import unicode_literals
from prompt_toolkit import prompt
if __name__ == '__main__':
print('If you press meta-! or esc-! at the | following p | rompt, you can enter system commands.')
answer = prompt('Give me some input: ', enable_system_bindings=True)
print('You said: %s' % answer)
|
jorgemira/euler-py | p025.py | Python | apache-2.0 | 383 | 0.002611 | '''Problem 25 from project Euler: 1000-digit Fibonacci number
https://projecteuler.net/problem=25'''
RESULT = 478 | 2
def solve():
'''Main function'''
digits = 1000
fib1 = 1
fib2 = 1
nth = 2
top = 10 ** (digits - 1)
while fib2 < top:
fib | 1, fib2 = fib2, fib1 + fib2
nth += 1
return nth
if __name__ == '__main__':
print solve()
|
si618/pi-time | pi_time/laptimer/laptimer/laptimer.py | Python | gpl-3.0 | 1,522 | 0.003285 | i | mport pi_time
from os import path
from autobahn.twisted.wamp import ApplicationSession
from autobahn.twisted.util import sleep
from autobahn.wamp.exception import ApplicationError
from twisted.interne | t.defer import inlineCallbacks
from twisted.python import log
from pi_time import settings
from pi_time.api import Api
class LaptimerAppSession(ApplicationSession):
@inlineCallbacks
def onJoin(self, details):
config_dir = path.dirname(path.dirname(path.realpath(__file__)))
config_file = pat... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.