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 |
|---|---|---|---|---|---|---|---|---|
andrew-blake/evohome-client | evohomeclient2/__init__.py | Python | apache-2.0 | 5,034 | 0.005165 | from __future__ import print_function
import requests
import json
import codecs
from .location import Location
from .base import EvohomeBase
class EvohomeClient(EvohomeBase):
def __init__(self, username, password, debug=False):
super(EvohomeClient, self).__init__(debug)
self.username = username
... | m = None
if len(self.locations)==1:
location = self.locations[0]
else:
raise Exception("More than one location available")
if len(location._gateways)==1:
gateway = location._gateways[0]
else:
raise Exception("More than... | else:
raise Exception("More than one control system available")
return control_system
def _login(self):
url = 'https://rs.alarmnet.com:443/TotalConnectComfort/Auth/OAuth/Token'
headers = {
'Authorization': 'Basic YjAxM2FhMjYtOTcy... |
mrawcliffe/gouda3 | gouda/utils/web.py | Python | mit | 132 | 0 | import requests
from bs4 import BeautifulSo | up
def | get_page_contents(url):
request = requests.get(url)
return request.text
|
Distrotech/scons | test/Fortran/F03FILESUFFIXES.py | Python | mit | 3,937 | 0.00127 | #!/usr/bin/env python
#
# __COPYRIGHT__
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and asso | ciated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the f... | Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIA... |
jmchilton/lwr | lwr/lwr_client/path_mapper.py | Python | apache-2.0 | 4,232 | 0.00189 | import os.path
from .action_mapper import FileActionMapper
from .action_mapper import path_type
from .util import PathHelper
from galaxy.util import in_directory
class PathMapper(object):
""" Ties together a FileActionMapper and remote job configuration returned
by the LWR setup method to pre-determine the l... | T]:
return self.output_directory
elif | dataset_path_type in [path_type.WORKDIR, path_type.OUTPUT_WORKDIR]:
return self.working_directory
elif dataset_path_type in [path_type.INPUT]:
return self.input_directory
else:
message = "PathMapper cannot handle path type %s" % dataset_path_type
raise Exc... |
akash1808/glance | glance/tests/unit/v2/test_tasks_resource.py | Python | apache-2.0 | 32,063 | 0.000031 | # Copyright 2013 IBM Corp.
# All Rights Reserved.
#
#
# Licensed under the Apache License, Version 2.0 (the "License"); | you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/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, WIT... | rning permissions and limitations
# under the License.
import datetime
import uuid
import mock
from oslo_config import cfg
from oslo_serialization import jsonutils
from oslo_utils import timeutils
# NOTE(jokke): simplified transition to py3, behaves like py2 xrange
from six.moves import range
import webob
import ... |
pombredanne/SourceForge-Allura | ForgeTracker/forgetracker/tests/functional/test_root.py | Python | apache-2.0 | 50,244 | 0.004539 | # -*- coding: utf-8 -*-
import os
import time
import json
import Image, StringIO
import allura
from mock import patch
from nose.tools import assert_true, assert_false, assert_equal, assert_in
from formencode.variabledecode import variable_encode
from alluratest.controller import TestController
from allura import mode... | form = response.forms[1]
form['ticket_form.summary'] = 'test new ticket form'
form['ticket_form.assigned_to'] = 'test_admin'
response = for | m.submit().follow()
assert 'Test Admin' in response
def test_private_ticket(self):
ticket_view = self.new_ticket(summary='Public Ticket').follow()
assert_true('<label class="simple">Private:</label> No' in ticket_view)
ticket_view = self.new_ticket(summary='Private Ticket',
... |
etsinko/oerplib | tests/test_inspect.py | Python | lgpl-3.0 | 3,308 | 0.001209 | # -*- coding: UTF-8 -*-
try:
import unittest2 as unittest
except:
import unittest
from args import ARGS
import oerplib
class TestInspect(unittest.TestCase):
def setUp(self):
self.oerp = oerplib.OERP(
ARGS.server, protocol=ARGS.protocol, port=ARGS.port,
version=ARGS.vers... | ['*'], attrs_blacklist=[])
self.assertIsInstance(graph, oerplib.service.inspect.relations.Relations)
def test_relations_maxdepth_null(self):
graph = self.oerp.inspect.relations(['res.users'], maxdepth=0)
self.assert | IsInstance(graph, oerplib.service.inspect.relations.Relations)
def test_relations_maxdepth_negative(self):
graph = self.oerp.inspect.relations(['res.users'], maxdepth=-1)
self.assertIsInstance(graph, oerplib.service.inspect.relations.Relations)
def test_dependencies(self):
graph = self... |
suraj-deshmukh/myCodes | sir.py | Python | mit | 1,321 | 0.065102 | def sir(n,I,tt):
import matplotlib.pyplot as pt
#n=int(input('enter no of population='))
#I=int(input('enter initial infected people='))
#t=int(input('enter time period='))
#dt=int(input('enter step size'))
size= | tt
s=[0 for j in range(size)]
i=[0 for j in range(size)]
r=[0 for j in range(size)]
s[0]=n-I
i[0]=I
b=0.9
k=0.2
#print(s[0],'\t',i[0],'\t',r[0],'\t\t',s[0]+i[0]+r[0])
for j in range(1,size):
s[j]=s[j-1] - (b*s[j-1]*i[j-1])/n
i[j]=i[j-1] + (b*s[j-1]*i[j-1])/n - k*i[j-1]
r[j]=r[j-1] + k*i[j-1]
#print(s[j... | '\t',i[j],'\t',r[j],'\t\t',s[j]+i[j]+r[j])
tt=list(range(size))
pt.plot(tt,s,tt,i,tt,r)
pt.legend(('S','I','R'),'upper right')
pt.xlabel('time')
pt.ylabel('population')
pt.title('sir model')
pt.show()
def print_val():
sir(int(t.get()),int(y.get()),int(u.get()))
import sys
import Tkinter
top=Tkinter.Tk()
Tk... |
zeutrap/tiaotiao | app/model/feed.py | Python | mit | 350 | 0.028571 | # -*- coding: utf-8 -*-
from datetime import date | time
from app.model import db
class FeedRecord(db.Model):
__tablename__ = 'feeds'
id = db.Column(db.Integer, primary_key=True)
time = db.Column(db.DateTime, default=datetime.now())
quant = db.Column(db.Integer)
def __repr__(self):
return 'At %s eat %d ml' % (str(se | lf.time), self.quant)
|
devs1991/test_edx_docmode | venv/lib/python2.7/site-packages/sphinx/util/png.py | Python | agpl-3.0 | 1,652 | 0 | # -*- coding: utf-8 -*-
"""
sphinx.util.png
~~~~~~~~~~~~~~~
PNG image manipulation helpers.
:copyright: Copyright 2007-2011 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import struct
import binascii
from sphinx.util.pycompat import b
LEN_IEND = 12
LEN_DEPTH = 22
... | CHUNK_START = b('tEXtDepth\x00')
IEND_CHUNK = b('\x00\x00\x00\x00IEND\xAE\x42\x60\x82')
def read_png_depth(filename):
"""Read the special tEXt chunk indicating the depth from a PNG file."""
result = None
f = open(filename, 'rb')
try:
f.seek(- (LEN_IEND + LEN_DEPTH), 2)
depthchunk = f.r... |
return None
result = struct.unpack('!i', depthchunk[14:18])[0]
finally:
f.close()
return result
def write_png_depth(filename, depth):
"""Write the special tEXt chunk indicating the depth to a PNG file.
The chunk is placed immediately before the special IEND chunk.
"""... |
SebWouters/PyDMET | oldstuff/HubbardDMETshiwei.py | Python | gpl-2.0 | 12,673 | 0.02383 | '''
PyDMET: a python implementation of density matrix embedding theory
Copyright (C) 2014, 2015 Sebastian Wouters
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 versio... | OEI[cnt1,cnt2] = HamDMET.getTmatCorr(cnt1, cnt2)
energiesDMETOEI, solutionDMETOEI = LinalgWrappers.RestrictedHartreeFock( OEI, N | elecActiveSpace/2, True )
print OEI
print energiesDMETOEI - np.average(energiesDMETOEI)
EnergyPerSiteCorr, OneRDMcorr, GSenergyFCI, GSvectorFCI = SolveCorrelated.SolveGS( HamDMET, NelecActiveSpace )
umat_new = MinimizeCostFunction.Minimize( umat_new, OneRDMcorr,... |
charanpald/sandbox | sandbox/predictors/profile/TreeRankProfile.py | Python | gpl-3.0 | 1,271 | 0.006294 | import numpy
import logging
import sys
from apgl.graph import *
from apgl.generator import *
from sandbox.u | til.ProfileUtils import ProfileUtils
from exp.sandbox.predictors.leafrank.SVMLeafRank import SVMLeafRank
from exp.sandbox.predictors.TreeRank import TreeRank
logging.basicConfig(s | tream=sys.stdout, level=logging.DEBUG)
class TreeRankProfile(object):
def __init__(self):
self.folds = 3
self.paramDict = {}
self.paramDict["setC"] = 2**numpy.arange(-5, 5, dtype=numpy.float)
self.leafRanklearner = SVMLeafRank(self.paramDict, self.folds)
def profileLearnMod... |
pgk/kountanis.com | _code_examples/greek_numerals.py | Python | mit | 1,783 | 0.001748 | # coding: utf8
# Greek Numeral Converter
#
# https://en.wikipedia.org/wiki/Greek_numerals
keraia = 'ʹ'
# Multiply by 10000
myriads = 'Μ'
numbers_to_letters = {
1: 'Α',
2: 'Β',
3: 'Γ',
4: 'Δ',
5: 'Ε',
6: 'ΣΤ',
7: 'Ζ',
8: 'Η',
9: 'Θ',
10: 'Ι',
20: 'Κ',
30: 'Λ',
40: '... | ms = list(numbers_to_letters.keys()); nums.reverse()
initial = []
for n in nums:
if num - n >= 0:
in | itial.append(numbers_to_letters[n])
num = num - n
return ''.join(initial) + keraia
def date_string_to_greek_number(datestring):
parts = datestring.split('/')
return '/'.join(list(to_greek_numeral(int(p)) for p in parts))
if __name__ == '__main__':
import unittest
class GreekNumeri... |
AunShiLord/sympy | sympy/polys/partfrac.py | Python | bsd-3-clause | 14,785 | 0.001217 | """Algorithms for partial fraction decomposition of rational functions. """
from __future__ import print_function, division
from sympy.polys import Poly, RootSum, cancel, factor
from sympy.polys.polytools import parallel_poly_from_expr
from sympy.polys.polyoptions import allowed_flags, set_defaults
from sympy.polys.p... | so be a list of explicit roots. However, at the moment ``apart_list``
never returns a result this way, but the related ``assemble_partfrac_list``
function accepts this format as input.)
- The numerator of the fraction, written as a function of the root `w`
- The linear denominator of the f... | xponent*,
written as a function of the root `w`.
- The power to which the denominator has to be raised.
On can always rebuild a plain expression by using the function ``assemble_partfrac_list``.
Examples
========
|
bgribble/mfp | mfp/builtins/vcq12.py | Python | gpl-2.0 | 1,819 | 0.004948 | #! /usr/bin/env python
'''
vcq12.py: 12TET quantizer for V/oct control voltages
Copyright (c) 2020 Bill Gribble <grib@billgribble.com>
'''
from ..processor import Processor
from ..mfp_app import MFPApp
from ..bang import Uninit
from mfp | import log
class VCQ12(Processor):
doc_tooltip_obj = "Quantize to 12TET semitones"
doc_tooltip_inlet = [
"Signal input", "Map of quantized tones"
]
maps = {
'major': [
(0, 0), (1, 0), (2, 2), (3, 2),
(4, 4), (5, 5), (6, 5), (7, 7),
(8, 7), (9, 9),... | ), (9, 8), (10, 10), (11, 10),
],
'semitone': [
(0, 0), (1, 1), (2, 2), (3, 3),
(4, 4), (5, 5), (6, 6), (7, 7),
(8, 8), (9, 9), (10, 10), (11, 11),
],
}
def __init__(self, init_type, init_args, patch, scope, name):
Processor.__init__(self, 2, ... |
phariel/fabric | test/feature/environment.py | Python | apache-2.0 | 3,050 | 0.004262 | # C | opyright IBM Corp. 2017 All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agree... | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import subprocess
import shutil
def getDockerComposeFileArgsFromYamlFile(composeYaml):
parts = composeYaml.split()
args = []
fo... |
zerothi/scipy | scipy/interpolate/_bsplines.py | Python | bsd-3-clause | 51,763 | 0.000811 | import operator
import numpy as np
from numpy.core.multiarray import normalize_axis_index
from scipy.linalg import (get_lapack_funcs, LinAlgError,
cholesky_banded, cho_solve_banded,
solve, solve_banded)
from . import _bspl
from . import _fitpack_impl
from . import _f... | x)/(t[i+k+1] - t[i+1]) * B(x, k-1, i+1, t)
... return c1 + c2
>>> def bspline(x, t, c, k):
... n = len(t) - k - 1
... assert (n >= k+1) and (len(c) >= n)
... return sum(c[i] * B(x, k, i, t) for i in range(n))
Note | that this is an inefficient (if straightforward) way to
evaluate B-splines --- this spline class does it in an equivalent,
but much more efficient way.
Here we construct a quadratic spline function on the base interval
``2 <= x <= 4`` and compare with the naive way of evaluating the spline:
>>> f... |
SmartInfrastructures/fuel-web-dev | nailgun/nailgun/statistics/oswl/collector.py | Python | apache-2.0 | 4,429 | 0 | # -*- coding: utf-8 -*-
# Copyright 2013 Mirantis, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requi... |
error_clusters = ClusterCollection.filter_by(
iterable=None, status=consts.CLUSTER_STATUSES.error).all()
all_envs_last_recs = \
OpenStackWorkloadStatsCollection.get_last_by_resource_type(
resource_type)
ready_or_error_ids = set([c.id for c in operational... | envs_ids_to_clear = set(r.cluster_id for r in all_envs_last_recs) - \
ready_or_error_ids
# Clear current resource data for unavailable clusters.
# Current OSWL data is cleared for those clusters which status is not
# 'operational' nor 'error' or when cluster was removed. Data is
... |
mckerrj/ansible | lib/ansible/executor/play_iterator.py | Python | gpl-3.0 | 27,494 | 0.004255 | # (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) an... | splay = Display()
class HostS | tate:
def __init__(self, blocks):
self._blocks = blocks[:]
self.cur_block = 0
self.cur_regular_task = 0
self.cur_rescue_task = 0
self.cur_always_task = 0
self.cur_role = None
self.cur_dep_chain = None
self.run_... |
secimTools/SECIMTools | src/scripts/standardized_euclidean_distance.py | Python | mit | 20,242 | 0.011313 | #!/usr/bin/env python
##################################################################
# AUTHOR: Miguel A. Ibarra-Arellano (miguelib@ufl.edu)
#
# DESCRIPTION: Pairwise and mean standarized euclidean comparisons
##################################################################
import os
import logging
import argpars... | ribution associated with the dimension of the vector. Thus,
samples with SEDs higher than the cutoff are dubious and conflict with the
multinormal assumption.
The scripts estimate the variance according to the input data and calculate
the SEDs from all samples to the estimated Mean and also the sample ... |
parser = argparse.ArgumentParser(description=description, formatter_class=
argparse.RawDescriptionHelpFormatter)
# Standard Input
standard = parser.add_argument_group(description="Standard Input")
standard.add_argument("-i","--input", dest="input", action='store',re... |
arpitprogressive/arpittest | intergration_test/banner.py | Python | bsd-3-clause | 18,254 | 0.005478 | # -*- coding: utf-8 -*-
"""
banner
Description goes here...
:copyright: (c) 2014 by Openlabs Technologies & Consulting (P) Limited
:license: BSD, see LICENSE for more details.
"""
import unittest
from selenium.webdriver.common.by import By
from selenium.common.exceptions import NoSuchElementException... | rograms-tools-resources/ssc-nasscom-training-programs/bpm/")
def test_central_overnment(self):
driver = self.driver
driver.get("http://pur | suite.openlabs.us/ssc-article/it-ites-initiative/developing-tomorrows-workforce-today/research/government-research/central-government/")
self.assertTrue(self.is_element_present(By.CSS_SELECTOR, "div.mid-box-flip"))
self.assertTrue(self.is_element_present(By.XPATH, "//div[@id='contentAndSidebars']/div/di... |
pymango/pymango | misc/python/mango/mpi/__init__.py | Python | bsd-2-clause | 14,935 | 0.005691 | __doc__ = \
"""
======================================================
Message Passing Interface Utilities (:mod:`mango.mpi`)
======================================================
.. _mpi4py: http://mpi4py.scipy.org
.. currentmodule:: mango.mpi
Convenience functions for MPI (`mpi4py`_). This module imports
everything... | e get added to the logger on the rootRank process.
:type formatter: logging.Formatter
:param formatter: Gets set as the formatter on the rootRank process.
:type rootRank: int
:param rootRank: MPI rank of the root process on which logging events are to be recorded. |
:rtype: logging.Logger
:return: A logger object for logging from the root-rank MPI process only.
"""
global rank, size
if (not haveMpi4py):
rank = rootRank
logr = logging.getLogger("root." + logrNameSuffix)
if (formatter == None):
formatter = getFormatter()
e... |
live4thee/zstack-utility | fusionstorbackupstorage/setup.py | Python | apache-2.0 | 810 | 0.003704 | from setuptools import setup, find_packages
import sys, os
version = ' | 2.3.0'
setup(name='fusionstorbackupstorage',
version=version,
description="ZStack FU | SIONSTOR backup storage agent",
long_description="""\
ZStack FUSIONSTOR backup storage agent""",
classifiers=[], # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers
keywords='fusionstor zstack',
author='Frank Zhang',
author_email='xing5820@gmail.com',
url='http:... |
zzacharo/inspire-next | inspirehep/modules/records/api.py | Python | gpl-3.0 | 16,705 | 0 | # -*- coding: utf-8 -*-
#
# This file is part of INSPIRE.
# Copyright (C) 2014-2017 CERN.
#
# INSPIRE 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 ... | and figures from this record's files
iterator before downloading them, for exam | ple to merge existing
records.
"""
files_src_record = kwargs.pop('files_src_record', None)
super(InspireRecord, self).update(*args, **kwargs)
self.download_documents_and_figures(
only_new=True,
src_record=files_src_record,
)
def merge(... |
fallingduck/snifter | snifter/utils.py | Python | bsd-3-clause | 2,266 | 0.000883 | import email.utils
import collections
import time
import cgi
from .core import py3
if py3:
def parse_return(content):
if isinstance(content, str):
content = content.encode('utf-8', 'xmlcharrefreplace')
if isinstance(content, bytes):
return (content,)
elif isinstanc... | xlen
else: # bytes=100-200 -> bytes 100-200 (inclusive)
start, end = int(start), min(int(end)+1, maxlen)
if 0 <= start < end <= ma | xlen:
yield start, end
except ValueError:
pass
def file_iter_range(fp, offset, bytes_, maxread=1024*1024):
"""Adapted from Bottle"""
fp.seek(offset)
while bytes_ > 0:
part = fp.read(min(bytes_, maxread))
if not part: break
bytes_ -= len(part)
... |
linan7788626/brut | bubbly/test/test_field.py | Python | mit | 288 | 0 | from ..field import get_field
def test_get_field():
f1 = get_field(30)
assert f1.lon == 30
def test_field_cached():
f1 = get_field(30)
f2 = get_field(30)
assert f1 is f2
f3 = get_field(31)
assert f3 is not f2
f3 = ge | t_field(30)
| assert f3 is not f2
|
EnigmaCK/Python_training | fixture/group.py | Python | apache-2.0 | 3,962 | 0.000757 |
from model.group import Group
class GroupHelper:
def __init__(self, app):
self.app = app
def open_groups_page(self):
wd = self.app.wd
if not (wd.current_url.endswith("/group.php") and len(wd.find_elements_by_name("new")) > 0):
wd.find_element_by_link_text("groups").click... | # submit deletion
| wd.find_element_by_name("delete").click()
self.return_to_groups_page()
self.group_cache = None
def modify_first_group(self):
self.modify_group_by_index(0)
def modify_group_by_index(self, index, new_group_data):
wd = self.app.wd
self.open_groups_page()
self... |
kashif/chainer | chainer/optimizers/ada_delta.py | Python | mit | 2,971 | 0 | import numpy
from chainer import cuda
from chainer import optimizer
_default_hyperparam = optimizer.Hyperparameter()
_default_hyperparam.rho = 0.95
_default_hyperparam.eps = 1e-6
class AdaDeltaRule(optimizer.UpdateRule):
"""Update rule of Zeiler's ADADELTA.
See :class:`~chainer.optimizers.AdaDelta` for t... | rder
moments.
eps (float): Small value for the numerical stability.
"""
def __init__(self, parent_hyperparam=None, rho=None, eps=None):
super(AdaDeltaRule, self).__init__(
parent_hyperparam or _default_hyperparam)
if rho is not None:
self.hyperparam.... |
def init_state(self, param):
xp = cuda.get_array_module(param.data)
with cuda.get_device_from_array(param.data):
self.state['msg'] = xp.zeros_like(param.data)
self.state['msdx'] = xp.zeros_like(param.data)
def update_core_cpu(self, param):
grad = param.grad
... |
jedie/django-cms-tools | django_cms_tools/version.py | Python | gpl-3.0 | 39 | 0 | # codin | g: utf-8
__version__ = '0.7.1' | |
amatellanes/fixerio | setup.py | Python | mit | 1,602 | 0 | import re
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
with open('fixerio/__init__.py', 'r') as fd:
version = re.search(r'^__version__\s*=\s*[\'" | ]([^\'"]*)[\'"]',
fd.read(), re.MULTILINE).group(1)
if not version:
raise RuntimeError('Cannot find version information')
with open('README.rst') as f:
readme = f.read()
with open('CHANGELOG.rst') as f:
changelog = f.read()
requi | rements = ['requests>=2.0']
setup(
name='fixerio',
version=version,
description='A Python client for Fixer.io',
long_description=readme + '\n\n' + changelog,
author="Adrian Matellanes",
author_email='matellanesadrian@gmail.com',
url='https://github.com/amatellanes/fixerio',
install_requ... |
kerimlcr/ab2017-dpyo | ornek/moviepy/moviepy-0.2.2.12/moviepy/video/tools/interpolators.py | Python | gpl-3.0 | 2,120 | 0.006132 | """
Classes for easy interpolation of trajectories and Curves.
Requires Scipy installed.
"""
import numpy as np
class Interpolator:
""" Poorman's linear interpolator, doesn't require Scipy. """
def __init__(self, tt=None, ss=None, ttss = None, l | eft=None, right=None):
if ttss is not None:
tt, ss = zip(*ttss)
self.tt = 1.0*np.array(tt)
self.ss = 1.0*np.array(ss)
self.left = left
self.right = right
self.tmin, self.tmax = min(tt), max(tt)
def __call__(self, t):
return np.in | terp(t, self.tt, self.ss, self.left, self.right)
class Trajectory:
def __init__(self, tt, xx, yy):
self.tt = 1.0*np.array(tt)
self.xx = np.array(xx)
self.yy = np.array(yy)
self.update_interpolators()
def __call__(self, t):
return np.array([self.xi(t), self.yi(t)])
... |
aaron0browne/github-pr-form | setup.py | Python | mit | 1,355 | 0.02214 | from setuptools import setup, find_packages
with open('README.md', 'r') as f:
long_description = f.read()
setup(
name = 'github-pr-form',
version = '0.1.1',
author = 'Aaron N Browne',
author_email = 'aaron0browne@gmail.com',
url = 'https://github.com/aaron0browne/github-pr-form',
descripti... | url = 'httpd://github.com/aaron0browne/github-pr-form/tarball/v0.1.1',
license = 'MIT License',
keywords = ['github', 'rfc', 'change control', 'form', 'pull request'],
classifiers = [
'Development Status :: | 4 - Beta',
'Environment :: Console',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Programming Language :: Python',
'Topic :: Software Development :: Version Control'
],
packages = find_packages(),
... |
ESOedX/edx-platform | openedx/features/discounts/apps.py | Python | agpl-3.0 | 220 | 0 |
"""
Discounts application configuration
"""
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from django.a | pps import AppConfig
class DiscountsConfig(AppConfig):
name = 'op | enedx.features.discounts'
|
qianwenming/mapnik | src/build.py | Python | lgpl-2.1 | 15,637 | 0.003965 | #
# This file is part of Mapnik (c++ mapping toolkit)
#
# Copyright (C) 2013 Artem Pavlenko
#
# Mapnik is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your op... | -h %s' % mapnik_libname
else:
mapnik_lib_link_flag += ' -Wl,-h,%s' % mapnik_libname
else: # Linux and others
lib_env['LIBS'].append('dl')
mapnik_lib_link_flag += ' -Wl,-rpath-link,.'
if env['ENABLE_SONAME']:
mapnik_lib_link_flag += ' -Wl,-soname,%s' % mapnik_... | z,origin -Wl,-rpath=\$$ORIGIN'
source = Split(
"""
expression_grammar.cpp
fs.cpp
request.cpp
well_known_srs.cpp
params.cpp
image_filter_types.cpp
miniz_png.cpp
color.cpp
conversions.cpp
image_compositing.cpp
image_scaling.cpp
box2d.cpp
datasource_cache.cpp
da... |
citrix-openstack-build/glance | glance/tests/unit/test_domain_proxy.py | Python | apache-2.0 | 10,170 | 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 req... | st_get(self):
self._test_method('get', 'snarf', 'abcd')
def test_list(self):
self._test_method('list', ['sniff', 'snarf'], 2, filter='^sn')
def test_add(self):
self._test_method('add', 'snuff', 'enough')
def test_save(self):
self._test_method('save', 'snuff', 'enough')
... | t_utils.BaseTestCase):
def setUp(self):
super(TestProxyRepoWrapping, self).setUp()
self.fake_repo = FakeRepo()
self.proxy_repo = proxy.Repo(self.fake_repo,
item_proxy_class=FakeProxy,
item_proxy_kwargs={'a': 1})
d... |
persandstrom/home-assistant | homeassistant/components/sensor/mitemp_bt.py | Python | apache-2.0 | 5,585 | 0 | """
Support for Xiaomi Mi Temp BLE environmental sensor.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.mitemp_bt/
"""
import logging
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.helpers... | the units of measurement."""
return self._unit
@property
def force_update(self):
"""Force update."""
return self._force_update
def update(self):
"""
Update current conditions.
This uses a rolling median over 3 values to filter out outliers.
"""
... | self.poller.parameter_value(self.parameter)
except IOError as ioerr:
_LOGGER.warning("Polling error %s", ioerr)
return
except BluetoothBackendException as bterror:
_LOGGER.warning("Polling error %s", bterror)
return
if data is not None:
... |
aperigault/ansible | lib/ansible/modules/cloud/google/gcp_compute_instance_template_info.py | Python | gpl-3.0 | 22,686 | 0.005246 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2017 Google
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# ----------------------------------------------------------------------------
#
# *** AUTO GENERATED CODE *** AUTO GENERATED CODE ***
#
... | to reference the device
for mounting, resizing, and so on, from within the instance.
returned: success
type: str
diskEncryptionKey:
description:
- Encrypts or decrypts a disk using a customer- | supplied encryption key.
returned: success
type: complex
contains:
rawKey:
description:
- Specifies a 256-bit customer-supplied encryption key, encoded
in RFC 4648 base64 to either encrypt or decrypt this r... |
roman-kutlak/nlglib | nlglib/macroplanning/struct.py | Python | mit | 14,242 | 0.000843 | import inspect
from nlglib.features import category, NEGATED
from nlglib.microplanning import String, Element
class SignatureError(Exception):
"""Exception for PredicateMsgSpec."""
pass
class Document:
"""Document represents a container holding information about a document.
This includes the docum... | : | param sections: document sections (`Document` or `Element` type)
"""
self._title = promote_to_string(title)
self._sections = [promote_to_string(s) for s in sections]
def __eq__(self, other):
return (
isinstance(other, Document) and other.category == self.category and
... |
sahana/Turkey | modules/templates/Magnu/config.py | Python | mit | 14,482 | 0.016617 | # -*- coding: utf-8 -*-
try:
# Python 2.7
from collections import OrderedDict
except:
# Python 2.6
from gluon.contrib.simplejson.ordered_dict import OrderedDict
from gluon import current
from gluon.storage import Storage
def config(settings):
"""
Template settings for a hosted environment... | to the main map
settings.gis.poi_create_resources = \
(dict(c="event",
f="incident_report",
table="event_incident_report",
type=" | point",
label=T("Add Incident"),
layer="Incident Reports",
),
#dict(c="gis",
# f="poi",
# table="gis_poi",
# type="polygon",
# label=T("Add Area"),
# layer="Areas",
# ),
#dict(c="gis... |
yutakakn/MyScript | Python/lambda.py | Python | bsd-3-clause | 301 | 0.02952 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# ラムダ式(Python3)
#
def sub(price, money):
change = money - (int)( (lambda | a:a*1.0 | 8)(price) )
print("おつりは{}円 {}".format(change, "(´・ω・`)"))
def main():
sub(100, 500)
if __name__ == "__main__":
main()
|
tritoanst/ccxt | python/ccxt/async/qryptos.py | Python | mit | 12,912 | 0.000852 | # -*- coding: utf-8 -*-
from ccxt.async.base.exchange import Exchange
import math
import json
from ccxt.base.errors import ExchangeError
from ccxt.base.errors import InsufficientFunds
from ccxt.base.errors import InvalidOrder
from ccxt.base.errors import OrderNotFound
class qryptos (Exchange):
def describe(self... | vate': {
'get': [
'accounts/balance',
'crypto_accounts',
'executions/me',
'fiat_accounts',
'loan_bids',
'loans',
'orders',
... | 'trading_accounts',
'trading_accounts/{id}',
],
'post': [
'fiat_accounts',
'loan_bids',
'orders',
],
'put': [
... |
awislowski/elasticsearch | dev-tools/create_bwc_index.py | Python | apache-2.0 | 18,266 | 0.012701 | # Licensed to Elasticsearch under one or more contributor
# license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright
# ownership. Elasticsearch licenses this file to you under
# the Apache License, Version 2.0 (the "License"); you may
# not use this file except... | _asserts(es, index_name, type, num_docs):
count = es.count(index=index_name)['count']
assert count | == num_docs, 'Expected %r but got %r documents' % (num_docs, count)
for _ in range(0, num_docs):
random_doc_id = random.randint(0, num_docs-1)
doc = es.get(index=index_name, doc_type=type, id=random_doc_id)
assert doc, 'Expected document for id %s but got %s' % (random_doc_id, doc)
assert_sort(es.sear... |
lariodiniz/OramaBankTest | OramaBank/menu.py | Python | gpl-2.0 | 1,161 | 0 | """
This file was generated with the custommenu management command, it contains
the classes for the admin menu, you can customize this class as you want.
To activate your custom menu add the following to your settings.py::
ADMIN_TOOLS_MENU = 'OramaBank.menu.CustomMenu'
"""
from django.core.urlresolvers import rev... | text_lazy as _
from admin_tools.menu import items, Menu
class CustomMenu(Menu):
"""
Custom Menu for OramaBank admin site.
"""
def __init__(self, **kwargs):
Menu.__init__(self, **kwargs)
self.children += [
items.MenuItem(_('Dashboard'), reverse('admin:index')),
... | exclude=('django.contrib.*',)
),
items.AppList(
_('Administration'),
models=('django.contrib.*',)
)
]
def init_with_context(self, context):
"""
Use this method if you need to access the request context.
... |
Lucas-Pinheiro/BroadClass | questions/migrations/0002_auto_20151130_0016.py | Python | mit | 672 | 0 | # -*- coding: utf-8 -*-
from __future__ | import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('questions', '0001_initial'),
]
operations = [
migrations.RenameField(
model_name='choic | e',
old_name='description',
new_name='meta',
),
migrations.RenameField(
model_name='questiontype',
old_name='description',
new_name='meta',
),
migrations.RenameField(
model_name='statement',
old_name='des... |
iainr/fridgid | Fridge.py | Python | lgpl-3.0 | 9,372 | 0.040013 | import RPi.GPIO as GPIO
import datetime
import time
import pandas as pd
import logging
import logging.handlers
import sys
logger = logging.getLogger('fridge')
handler = logging.StreamHandler()
fHandler = logging.FileHandler('fridge.log')
formatter = logging.Formatter("%(asctime)s %(levelname)s %(message)s", "%Y-... | omCode):
self.initGpio(heaterGpio, coolerGpio)
self.heater = TemperatureElement(heaterGpio, name='heater')
self.cooler = T | emperatureElement(coolerGpio, name='cooler')
self.ambientTempSensor = DS18B20(ambientTempSensorRomCode, name='TempSens')
self.resultPeriod = datetime.timedelta(minutes=10)
self.maxResults = 1000
self.lastResultTime = None
self.resultTime = datetime.datetime.now()
self.resultsFile = 'results.txt'... |
LRGH/amoco | amoco/cas/smt.py | Python | gpl-2.0 | 9,247 | 0.000865 | # -*- coding: utf-8 -*-
# This code is part of Amoco
# Copyright (C) 2015 Axel Tillequin (bdcht3@gmail.com)
# published under GPLv2 license
"""
cas/smt.py
==========
The smt module defines the amoco interface to the SMT solver.
Currently, only z3 is supported. This module allows to translate
any amoco expression int... | form"
return e.base.to_smtlib(slv) + e.disp
def mem_to_z3(e, slv=None):
"translate mem expression into z3 a Concat of BitVec bytes"
e.simpli | fy()
M = z3.Array("M", z3.BitVecSort(e.a.size), z3.BitVecSort(8))
p = e.a.to_smtlib(slv)
b = []
for i in range(0, e.length):
b.insert(0, M[p + i])
if e.endian == -1:
b.reverse() # big-endian case
if len(b) > 1:
return z3.Concat(*b)
return b[0]
def cast_z3_bool(x, s... |
Firefly-Automation/Firefly | Firefly/components/zwave/ecolink/contact_sensor.py | Python | apache-2.0 | 940 | 0.011702 | from openzwave.network import ZWaveNode
from openzwave.value import ZWaveValue
from Firefly import logging
from Firefly.components.zwave.device_types.contact_sensor import ZwaveContactSensor
TITLE = 'Ecolink Contact Sensor'
def Setup(firefly, package, **kwargs):
logging.message('Entering %s setup' % TITLE)
sens... | ctSensor):
def __init__(self, firefly, package, **kwargs):
super().__init__(firefly, package, TITLE, **kwargs)
def update_from_zwave(self, node: ZWaveNode = None, ignore_update=False, values: ZWaveValue = None, values_only=False, **kwargs):
if node is None:
return
if not node.values[self.value_m... | _update, values, values_only, **kwargs)
|
Gebesa-Dev/Addons-gebesa | mrp_segment/report/cut_order_production.py | Python | agpl-3.0 | 3,883 | 0.000258 | # -*- coding: utf-8 -*-
# © <YEAR(S)> <AUTHOR(S)>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from openerp import api, fields, models
class ParticularReport(models.AbstractModel):
_name = 'report.mrp_segment.report_cut_order_production'
@api.multi
def render_html(self, data=None... | cut in products[product.id]['cut_line'][prod_line]:
| if cut['name'] == bom_line_det.name and \
cut['caliber'] == bom_line_det.caliber_id and \
cut['width'] == bom_line_det.width_cut and \
cut['long'] == bom_line_det.long_cut:
cut['qty'] += bom_... |
filaboia/colorsegmentation | py/colorsegmentation/maxtree/MaxTree.py | Python | gpl-3.0 | 11,619 | 0.004475 | # This Python file uses the following encoding: utf-8
from __future__ import division
from colorsegmentation.image.ImageService import *
from colorsegmentation.image.Points import *
import numpy as np
import numpy.ma as ma
import copy as cp
from ia870 import *
import sys
sys.setrecursionlimit(10000)
class MaxTree(ob... | de.mask.getY().min() < ymin:
ymin = node.mask.getY().min()
if node.mask.getY().max() > ymax:
ymax = node.mask.getY().max()
return (xmin, xmax, ymin, ymax)
def getImage(self):
toprocess = [self]
xmin, xmax, ymin, ymax = self.getOffset()
... | toprocess:
node = toprocess.pop()
image[node.mask.getX() - xmin, node.mask.getY() - ymin] = node.level
toprocess += node.children
return image
def getNodes(self, level, index=None):
nodes = []
if self.level == level and (index is None or index == self... |
googleapis/python-debugger-client | samples/generated_samples/clouddebugger_v2_generated_debugger2_get_breakpoint_sync.py | Python | apache-2.0 | 1,557 | 0.000642 | # -*- coding: utf-8 -*-
# Copyright 2022 Google LLC
#
# 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... | ger2Client()
# Initialize request argument(s)
request = debugger_v2.GetBreakpointRequest(
debuggee | _id="debuggee_id_value",
breakpoint_id="breakpoint_id_value",
client_version="client_version_value",
)
# Make the request
response = client.get_breakpoint(request=request)
# Handle the response
print(response)
# [END clouddebugger_v2_generated_Debugger2_GetBreakpoint_sync]
|
bsavelli/jubilant-lamp | Class10/PyEZ.py | Python | apache-2.0 | 1,092 | 0.007326 | from jnpr.junos import Device
from jnpr.junos.op.ethport import EthPortTable
from getpass import g | etpass
from | pprint import pprint
pwd = getpass()
a_device = Device(host='50.242.94.227', user='pyclass', password=pwd)
a_device.open()
pprint(a_device.facts)
ports = EthPortTable(a_device)
ports.get()
ports.keys()
ports.items()
ports.values()
ports['fe-0/0/1']
ports['fe-0/0/1'].items()
for k,v in ports['fe-0/0/1'].items()... |
astro-pi/SpaceCRAFT | spacecraft/mcdisplays.py | Python | bsd-3-clause | 5,395 | 0.006487 | from mcpi.minecraft import Minecraft
from mcpi import block
from mcmodels import ISS, Stairs, Rocket, LaunchPad
from mcsensors import DisplayTube
from ti | me import sleep, time
from mcclock import Clock
"""
SpaceCRAFT - Astro Pi competition[http://astro-pi.org/] entry
Conceived by Hannah Belshaw
Created by Martin O'Hanlon[http://www.stuffaboutcode.com]
For the Raspberry Pi Foundation[https://www.raspberrypi.org]
mcdisplays.py
Displays information from the Astro Pi in ... | TO
class ISSTowerMinecraftDisplay():
"""
Hannah's vision of how we would display the data in Minecraft
A minecraft display which is 3 towers showing sensor data leading up to
the ISS, with a clock and rocket launch tower
"""
def __init__(self, mc, pos):
self.mc = mc
self.p... |
jyejare/robottelo | tests/foreman/installer/test_installer.py | Python | gpl-3.0 | 60,651 | 0.00028 | """Smoke tests to check installation health
:Requirement: Installer
:CaseAutomation: Automated
:CaseLevel: Acceptance
:CaseComponent: Installer
:Assignee: desingh
:TestType: Functional
:CaseImportance: High
:Upstream: No
"""
import re
import pytest
from robottelo import ssh
from robottelo.config import settin... | S_INSTALLER_OPTIONS = {
'--[no-]colors',
'--[no-]enable-certs',
'--[no-]enable-foreman',
'--[no-]enable-foreman-cli',
'--[no-]enable-foreman-compute-ec2',
'--[no-]enable-foreman-compute-gce',
'--[no-]enable-foreman- | compute-libvirt',
'--[no-]enable-foreman-compute-openstack',
'--[no-]enable-foreman-compute-ovirt',
'--[no-]enable-foreman-compute-vmware',
'--[no-]enable-foreman-cli-kubevirt',
'--[no-]enable-foreman-cli-katello',
'--[no-]enable-foreman-cli-remote-execution',
'--[no-]enable-foreman-plugin-a... |
HimariO/VideoSum | tasks/video/Visualize/MemoryView.py | Python | mit | 2,318 | 0.001294 | import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import getopt
import sys
import math
options, _ = getopt.getopt(sys.argv[1:], '', ['f | ile='])
filename = 'Ugb_uH72d0I_8_17_memView_27K.npy'
dpi = 150
fig_size = (2560 / dpi, 144 | 0 / dpi)
for opt in options:
if opt[0] == '--file':
filename = opt[1]
mem_dict = np.load(filename)[()]
Ww = np.reshape(mem_dict['write_weightings'], mem_dict['write_weightings'].shape[1:])
Wr = np.reshape(mem_dict['read_weightings'], mem_dict['read_weightings'].shape[1:])
Vu = np.reshape(mem_dict['usage_... |
mirkospasic/hobbit_snb_datagen | tools/sparkbench/distributions_extractor.py | Python | gpl-3.0 | 2,223 | 0.017544 |
import sys, os
input_file = open(sys.argv[1])
def parse_line( input_file ):
line = input_file.readline()
if len(line) > 0:
if line[0] == '(':
output = line.replace("\n","").replace(" ","")
while output.find(')') == -1:
line = inp | ut_file.readline()
output = output.replace("\n","").replace(" ","") + line.replace("\n","").replace(" ","")
return output
return line
def parse_distribution(input_file, output_file):
line = parse_line(input_file)
accum = 0
entry_labels = []
entry_freq = []
while(l... | line = line.replace("(","")
line = line.replace(")","")
line = line.split(",")
freq = int(line[0])
accum += freq
prev = 0
if(len(entry_freq) > 0):
prev = entry_freq[len(entry_freq)-1]
entry_freq.append(prev + freq)
entry_labels.append(line[... |
AMOboxTV/AMOBox.LegoBuild | plugin.video.salts/scrapers/iflix_proxy.py | Python | gpl-2.0 | 989 | 0.001011 | """
SALTS XBMC Addon
Copyright (C) 2014 tknorris
This program is free software: you can | redistribute it and/or modify
it under the term | s 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... |
tmilicic/networkx | networkx/classes/multidigraph.py | Python | bsd-3-clause | 34,318 | 0.000932 | """Base class for MultiDiGraph."""
# Copyright (C) 2004-2015 by
# Aric Hagberg <hagberg@lanl.gov>
# Dan Schult <dschult@colgate.edu>
# Pieter Swart <swart@lanl.gov>
# All rights reserved.
# BSD license.
from copy import deepcopy
import networkx as nx
from networkx.classes.graph import Graph # for doc... | d attribute dictionary (the keys must be hashable).
By default these are empty, but can be added or changed using
add_edge, add_node or direct manipulation of the attribute
di | ctionaries named graph, node and edge respectively.
>>> G = nx.MultiDiGraph(day="Friday")
>>> G.graph
{'day': 'Friday'}
Add node attributes using add_node(), add_nodes_from() or G.node
>>> G.add_node(1, time='5pm')
>>> G.add_nodes_from([3], time='2pm')
>>> G.node[1]
{'time': '5pm'}
... |
bitcoin-hivemind/hivemind | qa/rpc-tests/python-hivemindrpc/hivemindrpc/authproxy.py | Python | mit | 5,785 | 0.001556 |
"""
Copyright 2011 Jeff Garzik
AuthServiceProxy has the following improvements over python-jsonrpc's
ServiceProxy class:
- HTTP connections persist for the life of the AuthServiceProxy object
(if server supports HTTP/1.1)
- sends protocol 'version', per JSON-RPC 1.1
- sends proper, incrementing 'id'
... | ()
def _get_response(self):
http_response = self.__conn.getresponse()
if http_response is None:
raise JSONRPCException({
'code': -342, 'message': 'missing HTTP response from server'})
responsedata = http_response.read().decode('utf8')
response = json.loa... | rror" in response and response["error"] is None:
log.debug("<-%s- %s"%(response["id"], json.dumps(response["result"], default=EncodeDecimal)))
else:
log.debug("<-- "+responsedata)
return response
|
thelazier/dash | contrib/devtools/security-check.py | Python | mit | 8,242 | 0.005945 | #!/usr/bin/env python3
# Copyright (c) 2015-2016 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
'''
Perform basic ELF security checks on a series of executables.
Exit status will be 0 if successful, and... | set the permission diffe | rently
# This does not affect security: the permission flags of the GNU_RELRO program header are ignored, the PT_LOAD header determines the effective permissions.
# However, the dynamic linker need to write to this area so these are RW.
# Glibc itself takes care of mprotecting this area R after ... |
lhotchkiss/mousetrap | src/mousetrap/app/commons.py | Python | gpl-2.0 | 1,477 | 0.01151 | # -*- coding: utf-8 -*-
# MouseTrap
#
# Copyright 2009 Flavio Percoco Premoli
#
# This file is part of mouseTrap.
#
# MouseTrap is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License v2 as published
# by the Free Software Foundation.
#
# mouseTrap is distributed ... | gnu.org/licenses/>.
""" Common MouseTrap Functions. """
__id__ = "$Id$"
__version__ = "$Revision$"
__date__ = "$Date$"
__copyright__ = "Copyright (c) 2008 Flavio Percoco Premoli."
__license__ = "GPLv2"
import os
import re
def get_py_list(dirlist):
"""
Checks for .py files on directories in d... | irectories list.
"""
if not type(dirlist) is list:
dirlist = [dirlist]
reg = re.compile(r'([A-Za-z0-9]+)\.py$', re.DOTALL)
group = []
for dir in dirlist:
if not os.path.isdir(dir):
continue
group.append([ mod[0] for mod in [ reg.findall(f) for f in os.l... |
w1ll1am23/home-assistant | homeassistant/components/home_plus_control/__init__.py | Python | apache-2.0 | 5,808 | 0.001033 | """The Legrand Home+ Control integration."""
import asyncio
from datetime import timedelta
import logging
import async_timeout
from homepluscontrol.homeplusapi import HomePlusControlApiError
import voluptuous as vol
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_CLIENT_ID, C... | g interval. Will only be polled if there are subscribers.
update_interval=timedelta(seconds=6 | 0),
)
hass_entry_data[DATA_COORDINATOR] = coordinator
async def start_platforms():
"""Continue setting up the platforms."""
await asyncio.gather(
*[
hass.config_entries.async_forward_entry_setup(config_entry, platform)
for platform in PLATFORMS
... |
isandlaTech/cohorte-3rdparty | pelix/src/test/python/tests/ipopo/test_field_callbacks.py | Python | apache-2.0 | 6,606 | 0.000151 | #!/usr/bin/env python
# -- Content-Encoding: UTF-8 --
"""
Tests the iPOPO @Bind/Update/UnbindField decorators.
:author: Thomas Calmant
"""
# Tests
from tests.ipopo import install_bundle, install_ipopo
# Pelix
from pelix.framework import FrameworkFactory
# Standard library
try:
import unittest2 as unittest
excep... | svc_b._prop, -123, "Value not changed")
self.assertEqual(compo.states, [self.module.UPDATE_FIELD_B],
"Service B updated: not called")
del compo.states[:]
# Kill service B
s | elf.ipopo.kill("svcB")
self.assertEqual(compo.states, [self.module.UNBIND_FIELD_B],
"Service B unbound: not called")
del compo.states[:]
# Restart Service B
svc_b = self.ipopo.instantiate(self.module.FACTORY_B, "svcB")
self.assertEqual(compo.states, [sel... |
foxtrotmike/pairpred | calcEC.py | Python | gpl-3.0 | 2,206 | 0.026292 |
# -*- coding: utf-8 -*-
"""
Created on Thu May 2 14:02:07 2013
Wrapper for calcEC.m to compute the mutual and direct information from a MSA
@author: root
"""
import os
import tempfile
# import pdb
import sys
mlabpath='/s/parsons/l/sys/matlab64/bin/'
if mlabpath not in os.environ["PATH"]:
print 'Adding '+mlabpat... | nterest in the first msa file
ofile (optional): When specified the output of calcEC.m is saved here
mlab: matlab path
pgm: path to calcEC.m
Return (same as for parseECfile)
"""
msal=msa
if type(msa)==type([]):
| msal=','.join(msa)
msa='{'+msal+'}'
if ofile is None:
out_file = tempfile.NamedTemporaryFile(suffix='.ec')
out_file.close()
ofname=out_file.name
else:
ofname=ofile
cmdstr=mlab+' -nosplash -nodesktop -nodisplay -nojvm -wait -r \"'+pgm+' '+ msa +' ' +cid+ ' '+ofname+';... |
rew4332/tensorflow | tensorflow/python/kernel_tests/shape_ops_test.py | Python | apache-2.0 | 18,807 | 0.00989 | # Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | 5]), -4)
def testExpandDimsErrors(self):
with self.test_session():
self.assertRaises(ValueError, tf.expand_dims, np.zeros([2, 3, 5]), -5)
self.assertRaises(ValueError, tf.expand_dims, np.zeros([2, 3, 5]), 4)
def testExpandDimsGradient(self):
with self.test_session():
inp = tf.constant(n... |
self.assertLess(err, 1e-3)
def testExpandDimsScalar(self):
with self.test_session():
inp = tf.constant(7)
self.assertAllEqual([7], tf.expand_dims(inp, 0).eval())
self.assertAllEqual([7], tf.expand_dims(inp, -1).eval())
def _compareSqueeze(self, x, squeeze_dims, use_gpu):
with self.t... |
ReservoirWebs/GrowChinook | Test_test.py | Python | gpl-3.0 | 429 | 0.002331 | #!/usr/bin/python
import os
import glob
import cgi
impo | rt PrintPages_test as pt
address = cgi.escape(os.environ["REMOTE_ADDR"])
script = "Main Model Form"
pt.write_log_entry(script, address)
pt.print_header('GrowChinook', 'Std')
pt.print_full_form(None, None, 'in', 'RunModel.py')
extension = 'csv'
os.chdir('uploads')
result = [i for i in glob.glob('*.csv')]
print('''
{}
... | ('</html>')
|
babyliynfg/cross | tools/project-creator/Python2.6.6/Lib/test/test_pydoc.py | Python | mit | 12,989 | 0.002541 | import sys
import os
import os.path
import difflib
import subprocess
import re
import pydoc
import inspect
import unittest
import xml.etree
import test.test_support
from contextlib import contextmanager
from test.test_support import TESTFN, forget, rmtree, EnvironmentVarGuard
from test import pydoc_mod
... | fied module. Returns the stripped
output of pydoc.
"""
cmd = [sys.executable, pydoc.__file__, " ".join(args), module_name]
output = subprocess.Popen(cmd, stdout=subprocess.PIPE).stdout.read()
return outp | ut.strip()
def get_pydoc_html(module):
"Returns pydoc generated output as html"
doc = pydoc.HTMLDoc()
output = doc.docmodule(module)
loc = doc.getdocloc(pydoc_mod) or ""
if loc:
loc = "<br><a href=\"" + loc + "\">Module Docs</a>"
return output.strip(), loc
def get_pydoc_text... |
rjschwei/azure-sdk-for-python | azure-mgmt-logic/azure/mgmt/logic/models/as2_message_connection_settings.py | Python | mit | 2,072 | 0.003378 | # 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 ... | 'type': 'bool'},
}
def __init__(self, ignore_certificate_name_mismatch=None, support_http_status_code_continue=None, keep_http_connection_alive=None, unfold_http_headers=None):
self.ignore_certifi | cate_name_mismatch = ignore_certificate_name_mismatch
self.support_http_status_code_continue = support_http_status_code_continue
self.keep_http_connection_alive = keep_http_connection_alive
self.unfold_http_headers = unfold_http_headers
|
CTSRD-SOAAP/chromium-42.0.2311.135 | native_client/pnacl/prune_test.py | Python | bsd-3-clause | 6,842 | 0.007454 | #!/usr/bin/python
# Copyright (c) 2012 The Native Client Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Tests that a set of symbols are truly pruned from the translator.
Compares the pruned down "on-device" translator with the "fa... | n it would look like everything is pruned out. Look for a symbol
that's guaranteed not to be pruned out.
"""
pruned = self.size_of_matching_syms('stream_init.*NaClSrpc',
TestTranslatorPruned.pruned_symbols)
self.assertNotEqual(pruned, 0)
def test_didPrune(self... | ned.
Check that the symbols are not present anymore in the translator,
and check that the symbols actually do exist in the developer tools.
That prevents the test from accidentally passing if the symbols
have been renamed to something else.
"""
total = 0
pruned_list = [
'LLParser', ... |
dcf21/4most-4gp-scripts | src/scripts/pipeline/run_pipeline_on_spectrum_library.py | Python | mit | 7,282 | 0.003433 | #!../../../../virtualenv/bin/python3
# -*- coding: utf-8 -*-
# NB: The shebang line above assumes you've installed a python virtual environment alongside your working copy of the
# <4most-4gp-scripts> git repository. It also only works if you invoke this python script from the directory where it
# is located. If these... | object to be analysed
"""
# If we have done all the spectra already, return None
if self.spectrum_counter >= len(self.input_library_items):
return None
# Fetch next spectrum to analyse
test_spectrum_array = self.input_library.open(ids=self.input_library_ids[self.sp... | pectrum': spectrum,
'spectrum_identifier': spectrum_id
}
def post_result(self, spectrum_analysis):
"""
Post the results from analysing a spectrum back to whatever database you are using to store the pipeline's
output
:param spectrum_analysis:
A Spect... |
supermurat/hamsi-manager | Amarok/Operations.py | Python | gpl-3.0 | 5,993 | 0.002503 | # This file is part of HamsiManager.
#
# Copyright (c) 2010 - 2015 Murat Demir <mopened@gmail.com>
#
# Hamsi Manager 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 yo... | late("Amarok/Operations", "Artist")), str(currentArtistName),
artistName)
for musicFilePath in musicFilePathAndArtist[2]:
if fu.isWritableFileOrDir(musicFilePath, False, True):
Records.add(str(translate("... | ill be updated")), str(musicFilePath))
currentArtistName = ""
tagger = Taggers.getTagger()
if tagger is not None:
try:
tagger.loadFileForWrite(musicFilePath)
... |
smnslwl/project_euler | 18/18.py | Python | gpl-3.0 | 1,238 | 0.000808 | """
By starting at the | top of the triangle below and moving to adjacent
numbers on the row below, the maximum total from top to bottom is 23.
3
7 4
2 4 6
8 5 9 3
That is, 3 + 7 + 4 + 9... | nly 16384 routes, it is possible to solve this problem
by trying every route. However, Problem 67 is the same challenge with
a triangle containing one-hundred rows; it cannot be solved by brute
force, and requires a clever method! ;o)
"""
from os.path import dirname, abspath, join
if __name__ == '__main__':
... |
euri10/zipline | zipline/finance/trading.py | Python | apache-2.0 | 19,394 | 0 | #
# Copyright 2014 Quantopian, 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 wr... |
# market hours. The TradingEnvironment maintains two time keeping
# facilities:
# - a DatetimeIndex of trading days for calendar calculations
# - a timezone name, which should be local to the exchange
# hosting the benchmark index. All dates are normalized to UTC
# for serialization and storage, and the timezo... | module maintains a global variable, environment, which is
# subsequently referenced directly by zipline financial
# components. To set the environment, you can set the property on
# the module directly:
# from zipline.finance import trading
# trading.environment = TradingEnvironment()
#
# or if you want to ... |
YanjieGao/magellan | python/__init__.py | Python | apache-2.0 | 626 | 0 | #
# Copyright 2015 Ram Sriharsha
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may | not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS | " BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
"""
This is the Python API for SpatialSDK.
"""
|
andrijan/csgostats | cs-stats/stats/migrations/0001_initial.py | Python | bsd-3-clause | 3,104 | 0.003222 | # -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2015-12-11 22:01
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateM... | ls.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('username', models.CharField(max_length=255)),
('rank', models.CharField(blank=True, choices=[(1, 'Silver I'), (2, 'Silver II'), (3, 'Silver III'), (4, 'Silver IV'), (5, 'Silver Elite'), (6, 'Silver ... | '), (12, 'Master Guardian II'), (13, 'Master Guardian Elite'), (14, 'Distinguished Master Guardian'), (15, 'Legendary Eagle'), (16, 'Legendary Eagle Master'), (17, 'Supreme Master First Class'), (18, 'The Global Elite')], max_length=255, null=True)),
],
),
migrations.AddField(
mo... |
gorbinphilip/PyRegistrar | pyregistrar/test/test_console.py | Python | mit | 577 | 0.024263 | from .. import console, fields
from ..exceptions import ConsoleError
from . im | port mock
import pytest
console.raw_input=mock.raw_input
def test_prompt():
field=fields.Field("test_field", "test field", fields.Field.TYPE_TEXT_ONELINE, "this is a test field")
assert console.prompt(field)=="999"
def test_input_parser():
sys_args=['-f', 'myfile']
exts=["test"]
models=["test_mod... | rser("", "", sys_args)
|
qwertie64982/Coding4Medicine-2017 | Jigsaw/debruijn.py | Python | mit | 2,134 | 0.004217 | # DOCUMENTATION (explain args too)
from bidict import bidict
import sys
pieces = []
kmers = []
debruijn = bidict()
# filename = raw_input("Filename: ")
filename = sys.argv[1]
if filename[-4:] == ".csv":
with open(filename, "r") as infile:
for line in infile:
line = line.strip()
... | kmers.append(piece[i:i + kSize])
# build debruijn graph
for i in range(0, len(kmers)):
for j in range(0, len(kmers)):
if i != j: # don't look at itself
# print "Testing if %s is %s" % (kmers[i][leftover:], kmers[j][:overlapSize])
if kmers[i][leftover:] == kmers[j][:over... | # print "%s and %s make %s" % (kmers[i], kmers[j], (kmers[i] + kmers[j][-leftover:]))
debruijn[kmers[i]] = kmers[j]
# assemble from graph
finalString = debruijn.keys()[20] # just picked a random number, no puzzle will ever have < 20 pieces
while finalString[-kSize:] in debruijn.keys(): # build... |
tantalor/emend | app/emend/stubs.py | Python | mit | 712 | 0.022472 | from google.appengine.api import apiproxy_stub_map, urlfetch_stub
from google.appengine.api.memcache import memcache_stub
from megaera import env
def urlfetch():
if env.server_software():
return
apiproxy_stub_map.apiproxy = apiproxy_stub_map.APIProxyStubMap()
apiproxy_stub_map.apiproxy.RegisterStub('urlfet... |
urlfetch_stub.URLFetchServiceStub())
def memcache():
if env.server_software():
return
apiproxy_stub_map.apiproxy.RegisterStub('memcache',
memcache_stub.MemcacheServiceStub())
def all():
if env. | server_software():
return
from google.appengine.tools import dev_appserver_main, dev_appserver
dev_appserver.SetupStubs('emend', **dev_appserver_main.DEFAULT_ARGS)
|
yephper/django | tests/template_tests/test_engine.py | Python | bsd-3-clause | 1,984 | 0 | import os
from django.template import Context
from django.template.engine import Engine
from django.test import SimpleTestCase
from .utils import ROOT, TEMPLATE_DIR
OTHER_DIR = os.path.join(ROOT, 'other_templates')
class RenderToStringTest(SimpleTestCase):
def setUp(self):
self.engine = ... | ATE_DIR], loaders=loaders)
template = engine.get_template('priority/foo.html')
self.assertEqual(template.render(Context()), 'priority\n')
def test_cached_loader_priority(se | lf):
"""
Check that the order of template loader works. Refs #21460.
"""
loaders = [
('django.template.loaders.cached.Loader', [
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
... |
kaarolch/ansible | lib/ansible/modules/cloud/openstack/os_project_facts.py | Python | gpl-3.0 | 4,920 | 0.001626 | #!/usr/bin/python
# Copyright (c) 2016 Hewlett-Packard Enterprise Corporation
#
# This module 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 ve... |
domain_id:
description: Domain ID containing the project (keystone v3 clouds only)
returned: success
type: bool
'''
def main():
argument_spec = openstack_full_argument_spec(
name=dict(required=False, default=No | ne),
domain=dict(required=False, default=None),
filters=dict(required=False, type='dict', default=None),
)
module = AnsibleModule(argument_spec)
if not HAS_SHADE:
module.fail_json(msg='shade is required for this module')
try:
name = module.params['name']
domain... |
RamonGuiuGou/l10n-spain | l10n_es_account_invoice_sequence/__init__.py | Python | agpl-3.0 | 167 | 0 | # | -*- coding: utf-8 -*-
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
from .hooks import post_init_h | ook
from . import models
from . import wizards
|
weijia/djangoautoconf | djangoautoconf/base_settings.py | Python | bsd-3-clause | 1,467 | 0.000682 | # Base setting file, content will be imported in DjangoAutoConf
# Default database name, can be override in extra_settings.settings
from .django_dev_server_auto_conf import DjangoDevServerAutoConf
MYSQL_DATABASE_NAME = "test"
AUTHENTICATION_BACKENDS = []
DATABASE_ROUTERS = []
MEDIA_URL = "/media/"
MEDIA_ROOT = "/m... | {
'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend',)
}
for attr in dir(final_settings):
vars()[attr] = getattr(final_settings, attr)
MIDDLEWARE_CLASSES = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'djang... | are.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.Common... |
yamila-moreno/api-example | src/utils/middlewares/sqlalchemy.py | Python | gpl-3.0 | 876 | 0.004566 | import functools
from repositories.session import session_manager
def wrap_sqlalchemy_session(
func=None,
*,
allow_origin='*',
allow_headers=set(["Origin", "X-Requested-With", "Content-Type", "Accept"])):
"""
| A middleware that creates a sqlalchemy session at the start of the request, and close it at the end.
| If there isn't an exception on the execution, the session is commited. Otherwise, it is rollbacked.
"""
@functools.wraps(func)
def wrapper(request, *args, **kwargs):
session_manager.create_session()
try:
response = func(request, *args, **kwargs)
session_manager.co... |
cangencer/hazelcast-python-client | hazelcast/protocol/codec/multi_map_contains_value_codec.py | Python | apache-2.0 | 1,156 | 0.000865 | from hazelcast.serialization.bits import *
from hazelcast.protocol.client_message import ClientMessage
from hazelcast.protocol.custom_codec import *
from hazelcast.util import ImmutableLazyDataList
from hazelcast.protocol.codec.multi_map_message_type im | port *
REQUEST_TYPE = MULTIMAP_CONTAINSVALUE
RESPONSE_TYPE = 101
RETRYABLE = True
def calculate_size(name, value):
""" Calculates the request payl | oad size"""
data_size = 0
data_size += calculate_size_str(name)
data_size += calculate_size_data(value)
return data_size
def encode_request(name, value):
""" Encode request into client_message"""
client_message = ClientMessage(payload_size=calculate_size(name, value))
client_message.set_me... |
kishoredbn/barrelfish | tools/harness/machines/eth_machinedata.py | Python | mit | 22,961 | 0.022081 | ##########################################################################
# Copyright (c) 2009, 2016, ETH Zurich.
# All rights reserved.
#
# This file is distributed under the terms in the attached LICENSE file.
# If you do not find this file, copies can be found by writing to:
# ETH Zurich D-INFK, Universitaetstr 6, ... | cores' : 57,
'xphi_ncards' : 2,
'xphi_tickrate' : 1140,
'xphi_ram_gb' : 6,
'pci_args' : [ "skb_bridge_program=bridge_bios" ],
'eth0' : (4, 0, 0),
},
'babybel3': {'ncores' : 20,
... | 'buildarchs' : ['x86_64', 'k1om'],
'cores_per_socket': 10,
'perfcount_type' : 'intel',
'tickrate' : 2500,
'boot_timeout' : 360,
'xphi_ncores' : 57,
'xphi_ncards' : 2,
'xphi_... |
JuhaniImberg/DragonPy | misc/filter_xroar_trace.py | Python | gpl-3.0 | 10,452 | 0.004018 | #!/usr/bin/env python
# encoding:utf-8
"""
Filter Xroar trace files.
see README for more information.
:created: 2014 by Jens Diemer - www.jensdiemer.de
:license: GNU GPL v3 or above, see LICENSE for more details.
"""
import os
import time
import sys
import argparse
class XroarTraceFilter(object):
... | ddresses with more than %i calls:\n" % max_count
)
addr_filter = {}
for addr, count in self.addr_stat.items():
if count >= max_count:
addr_filter[addr] = count
return addr_filter
def filter(self, addr_filter):
sys.stderr.write(
"Filter... | addresses.\n" % len(addr_filter)
)
total_skiped_lines = 0
skip_count = 0
last_line_no = 0
next_update = time.time() + 1
for line_no, line in enumerate(self.infile):
if time.time() > next_update:
sys.stderr.write(
"\rFilter %... |
vetalypp/e2openplugin-CrossEPG | src/enigma2/python/crossepg_downloader.py | Python | lgpl-2.1 | 5,637 | 0.037254 | from enigma import getDesktop, iPlayableService, eTimer, eServiceReference
from Components.Label import Label
from Components.Pixmap import Pixmap
from Components.ProgressBar import ProgressBar
from Components.ServiceEventTracker import ServiceEventTracker
from Components.ActionMap import NumberActionMap
from Screens... | apFromFile("%s/images/background.png" % (os.path.dirname(sys.modules[__name__].__file__)))
self.wrappertimer.start(100, 1)
def initWrapper(self):
if len(self.providers) == 0:
self.closeAndCallback(True)
else:
self.wrapper.init(CrossEPG_Wrapper.CMD_DOWNLOADER, self.config.db_root)
def download(self):
... | hannelProtocol(self.providers[self.provider_index]) != "script":
if not self.open:
self.wrapper.open()
self.open = True
self.saved = False
else:
if self.open:
self.wrapper.save()
self.saved = True
self.provider_index -= 1
return
service = self.config.getChannelID(self.providers... |
entrepidea/projects | python/tutorials/algo/leetcode/easy/binary_tree_traversal.py | Python | gpl-3.0 | 489 | 0.030675 | """
inorder traverse a binary tree
https://leetcode.com/problems/binary-tree-inorder-traversal/
date: 10/09/21
"""
import sys
sys.path.append('utils/')
from TreeUtils import TreeNode
from TreeUtils import insert_level_order
def in_order( | root):
if root != None:
in_order(root.left)
print(root.data,end=" ")
in_order(root.right)
if __name__ == '__main__':
arr = [1, 2, 3, 4, 5, 6, | 6, 6, 6]
n = len(arr)
root = None
root = insert_level_order(arr, root, 0, n)
in_order(root)
|
jbarlow83/tesseract | src/training/tesstrain.py | Python | apache-2.0 | 4,301 | 0.002325 | #!/usr/bin/env python3
# (C) Copyright 2014, Google Inc.
# (C) Copyright 2018, James R Barlow
# 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... | %(name)s - %(message)s"
)
logfile.setFormatter(logfile_formatter)
log.addHandler(logfile)
def main():
setup_logging_console()
ctx = parse_flags()
setup_logging_logfile(ctx.log_file)
if not ctx.linedata:
log.error("--linedata_only is required since only LSTM is supported")
... | set_lang_specific_parameters(ctx, ctx.lang_code)
initialize_fontconfig(ctx)
phase_I_generate_image(ctx, par_factor=8)
phase_UP_generate_unicharset(ctx)
if ctx.linedata:
phase_E_extract_features(ctx, ["--psm", "6", "lstm.train"], "lstmf")
make_lstmdata(ctx)
cleanup(ctx)
log.inf... |
lilydjwg/you-get | src/you_get/extractors/miaopai.py | Python | mit | 1,495 | 0.012709 | #!/usr/bin/env python
__all__ = ['miaopai_download']
from ..common import *
import urllib.error
def miaopai_download(url, output_dir = '.', merge = False, info_only = False, **kwargs):
'''Source: Android mobile'''
if re.match(r'http://video.weibo.com/show\?fid=(\d{4}:\w{32})\w*', url):
fake_headers_m... | 'Accept': 'text/html,application/xhtml+xml,application/x | ml;q=0.9,*/*;q=0.8',
'Accept-Charset': 'UTF-8,*;q=0.5',
'Accept-Encoding': 'gzip,deflate,sdch',
'Accept-Language': 'en-US,en;q=0.8',
'User-Agent': 'Mozilla/5.0 (Linux; Android 4.4.2; Nexus 4 Build/KOT49H) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.114 Mobile ... |
HBEE/odoo-addons | stock_voucher/wizard/stock_print_remit.py | Python | agpl-3.0 | 3,068 | 0 | # -*- coding: utf-8 -*-
##############################################################################
# For copyright and license notices, see __openerp__.py file in module root
# directory
##############################################################################
from openerp import fields, api, models
from math ... | def _get_printed(self):
printed = False
if self.picking_id.voucher_ids:
printed = True
self.printed = printed
@api.onchange('bo | ok_id', 'picking_id')
def get_estimated_number_of_pages(self):
lines_per_voucher = self.lines_per_voucher
if lines_per_voucher == 0:
estimated_number_of_pages = 1
else:
operations = len(self.picking_id.pack_operation_ids)
estimated_number_of_pages = ceil(
... |
ZTH1970/alcide | alcide/personnes/management/commands/fix-group-holiday-services.py | Python | agpl-3.0 | 450 | 0.002222 | from django.core.ma | nagement.base import BaseCommand, CommandError
class Command(BaseCommand):
def handle(self, *args, **kwargs):
from alcide.personnes.models import Holiday
from alcide.ressources.models import Service
all_services = list(Service.objects.all())
for holiday in Holiday.objects.filter(... | r service in all_services:
holiday.services.add(service)
|
anortef/calico | calico/felix/test/test_frules.py | Python | apache-2.0 | 11,864 | 0.003119 | # -*- coding: utf-8 -*-
# Copyright 2015 Metaswitch Networks
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicab... | elix-INPUT --protocol ipencap --match set ! --match-set felix-hosts src --jump DROP',
'--append felix-INPUT ! --in-interface tap+ --jump RETURN',
'--append felix-INPUT --match conntrack --ctstate INVALID --jump DROP',
'--append felix-INPUT --match conntrack --ctstate RELATED,ESTABLIS... | '--append felix-INPUT --protocol udp --sport 546 --dport 547 --jump ACCEPT',
'--append felix-INPUT --protocol udp --dport 53 --jump ACCEPT',
'--append felix-INPUT --jump DROP',
])
self.assertEqual(deps, set())
def test_build_input_chain_return(self):
chain, deps... |
jmesteve/openerpseda | openerp/addons_extra/partner_sequence_unify/partner_sequence_unify.py | Python | agpl-3.0 | 2,771 | 0.00397 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (c) 2013 jmesteve All Rights Reserved
# https://github.com/jmesteve
# <jmesteve@me.com>
#
# This program is... | rtner, self).create(cr, uid, vals, context)
# edit register
def write(self, cr, uid, ids, vals, context=None):
if not h | asattr(ids, '__iter__'):
ids = [ids]
partners_without_code = self.search(cr, uid, [
('ref', 'in', [False, '/']), ('id', 'in', ids)], context=context)
direct_write_ids = set(ids) - set(partners_without_code)
super(res_partner, self).write(
cr, uid, list(direct_... |
apavlo/h-store | third_party/python/boto/roboto/awsqueryservice.py | Python | gpl-3.0 | 4,196 | 0.001192 | import os
import urlparse
import boto
import boto.connection
import boto.jsonresponse
import boto.exception
import awsqueryrequest
class NoCredentialsError(boto.exception.BotoClientError):
def __init__(self):
s = 'Unable to find credentials'
boto.exception.BotoClientError.__init__(self, s)
class ... | edentialsError()
def check_for_credential_file(self):
"""
Checks for the existance of an AWS credential file.
If the environment variable AWS_CREDENTIAL_FILE is
set and po | ints to a file, that file will be read and
will be searched credentials.
Note that if credentials have been explicitelypassed
into the class constructor, those values always take
precedence.
"""
if 'AWS_CREDENTIAL_FILE' in os.environ:
path = os.environ['AWS_CR... |
tiagoshibata/exrsplit | tests/cmdargs.py | Python | mit | 129 | 0.007752 | import collections
| CmdArgs = collections.namedtuple('CmdArgs', ['split_channels', 'merge', 'image', ' | prefix', 'list', 'layer'])
|
endlessm/chromium-browser | third_party/llvm/lldb/test/API/functionalities/breakpoint/dummy_target_breakpoints/TestBreakpointsWithNoTargets.py | Python | bsd-3-clause | 2,430 | 0.001235 | """
Test b | reakpoint commands set before we have a target
"""
import lldb
from lldbsui | te.test.lldbtest import *
import lldbsuite.test.lldbutil as lldbutil
class BreakpointInDummyTarget (TestBase):
mydir = TestBase.compute_mydir(__file__)
def test(self):
"""Test breakpoint set before we have a target. """
self.build()
self.dummy_breakpoint_test()
def setUp(self):
... |
kohout/drf-demo | src/demo1/migrations/0002_auto__add_field_book_price_net.py | Python | unlicense | 1,122 | 0.006239 | # -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'Book.price_net'
db.add_column(u'demo1_book', 'price_net',... | al_places=2 | ),
keep_default=False)
def backwards(self, orm):
# Deleting field 'Book.price_net'
db.delete_column(u'demo1_book', 'price_net')
models = {
u'demo1.book': {
'Meta': {'ordering': "('title',)", 'object_name': 'Book'},
'abstract': ('django.db... |
iottly/iottly-core | iottly_core/brokerapi.py | Python | apache-2.0 | 2,191 | 0.005021 | """
Copyright 2015 Stefano Terna
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... | = "{}/{}/{}".format(settings.XMPP_MGMT_REST_URL, username, "roster")
res = yield http_client.fetch(xmpp_api_url, method='POST', headers=HEADERS, body=body)
if res.error:
raise Exception("Create roster: " + res.error)
@gen.coroutine
def delete_user(username):
#call xmppbroke... | nt.AsyncHTTPClient()
xmpp_api_url = "{}/{}".format(settings.XMPP_MGMT_REST_URL, username)
logging.info(xmpp_api_url)
res = yield http_client.fetch(xmpp_api_url, method="DELETE", headers=HEADERS, body=None)
if res.error:
raise Exception("Create user: " + res.error)
|
dims/cinder | cinder/tests/unit/api/contrib/test_volume_type_access.py | Python | apache-2.0 | 13,838 | 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
# ... | context, id, inactive=False, expected_fields=None):
vol = VOLUME_TYPES[id]
if expected_fields and 'projects' in expected_fields:
vol['projects'] = [a['project_id']
for a in ACCESS_LIST if a['volume_type_id'] == id]
return vol
def _has_type_access(type_id, project_id):
... | t_id:
return True
return False
def fake_volume_type_get_all(context, inactive=False, filters=None,
marker=None, limit=None, sort_keys=None,
sort_dirs=None, offset=None, list_result=False):
if filters is None or filters['is_public'] is None:... |
emile2016/flaskbb | tests/unit/utils/test_widgets.py | Python | bsd-3-clause | 1,131 | 0 | """Tests for the utils/widgets.py file."""
from flaskbb.utils.widgets import SelectBirthdayWidget
def test_select_birthday_widget():
"""Test the SelectDateWidget."""
assert SelectBirthdayWidget.FORMAT_CHOICES['%d'] == [
(x, str(x)) for x in range(1, 32)
]
assert SelectBirthdayWidget.FORMAT_CH... | (x, str(x)) for x in range(1, 13)
]
assert SelectBirthdayWidget.FORMAT_CLASSES == {
'%d': 'select_date_day',
'%m': 'select_date_month',
'%Y': 'select_date_year'
}
select_birthday_widget = SelectBirthdayWidget(years=[0, 1])
assert select_birthday_widget.FORMAT_CHOICES... | select_birthday_widget(field=Field(), surrounded_div="test-div")
assert 'world' in html
assert 'helloWorld' in html
assert 'class="select_date_day"' in html
assert 'class="select_date_month"' in html
assert 'class="select_date_year"' in html
assert '<div class="test-div">' in html
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.