commit
stringlengths 40
40
| subject
stringlengths 1
3.25k
| old_file
stringlengths 4
311
| new_file
stringlengths 4
311
| old_contents
stringlengths 0
26.3k
| lang
stringclasses 3
values | proba
float64 0
1
| diff
stringlengths 0
7.82k
|
|---|---|---|---|---|---|---|---|
8f15a2964c1cbbd85ed8301997c05a38268c79a7
|
add script used during position comparison
|
scripts/pos_compare.py
|
scripts/pos_compare.py
|
Python
| 0.000001
|
@@ -0,0 +1,395 @@
+#!/usr/bin/python%0A%0Aimport sys%0A%0Athreshold = 100%0A%0Afor line in sys.stdin:%0A fields = line.split(' ')%0A aln_name = fields%5B0%5D%0A true_chr = fields%5B1%5D%0A true_pos = int(fields%5B2%5D)%0A aln_chr = fields%5B3%5D%0A aln_pos = int(fields%5B4%5D)%0A aln_mapq = int(fields%5B5%5D)%0A aln_correct = 1 if aln_chr == true_chr and abs(true_pos - aln_pos) %3C threshold else 0%0A print aln_name, aln_correct, aln_mapq%0A
|
|
bb2fa19aa09e5687e13dedf40da1c7a2507c4c62
|
add script to replace `@` and `.` in slugsin for input to gr1x
|
examples/slugsin_chars_for_gr1x.py
|
examples/slugsin_chars_for_gr1x.py
|
Python
| 0
|
@@ -0,0 +1,472 @@
+import argparse%0A%0A%0Adef main():%0A p = argparse.ArgumentParser()%0A p.add_argument('source', type=str,%0A help='input file')%0A p.add_argument('target', type=str,%0A help='output file')%0A args = p.parse_args()%0A with open(args.source, 'r') as f:%0A s = f.read()%0A snew = s.replace('.', 'dot')%0A snew = snew.replace('@', 'at')%0A with open(args.target, 'w') as f:%0A f.write(snew)%0A%0A%0Aif __name__ == '__main__':%0A main()%0A
|
|
1c615be1d3da720d2d0a1974808e3856cbd9d498
|
Create Virgil highlevel api implementation
|
virgil_sdk/api/virgil_api.py
|
virgil_sdk/api/virgil_api.py
|
Python
| 0
|
@@ -0,0 +1,2835 @@
+# Copyright (C) 2016 Virgil Security Inc.%0A#%0A# Lead Maintainer: Virgil Security Inc. %3Csupport@virgilsecurity.com%3E%0A#%0A# All rights reserved.%0A#%0A# Redistribution and use in source and binary forms, with or without%0A# modification, are permitted provided that the following conditions are%0A# met:%0A#%0A# (1) Redistributions of source code must retain the above copyright%0A# notice, this list of conditions and the following disclaimer.%0A#%0A# (2) Redistributions in binary form must reproduce the above copyright%0A# notice, this list of conditions and the following disclaimer in%0A# the documentation and/or other materials provided with the%0A# distribution.%0A#%0A# (3) Neither the name of the copyright holder nor the names of its%0A# contributors may be used to endorse or promote products derived from%0A# this software without specific prior written permission.%0A#%0A# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY EXPRESS OR%0A# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED%0A# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE%0A# DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,%0A# INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES%0A# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR%0A# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)%0A# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,%0A# STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING%0A# IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE%0A# POSSIBILITY OF SUCH DAMAGE.%0Afrom virgil_sdk.api import IdentitiesManager%0Afrom virgil_sdk.api import VirgilContext%0Afrom virgil_sdk.api.card_manager import CardManager%0Afrom virgil_sdk.api.key_manager import KeyManager%0A%0A%0Aclass Virgil(object):%0A %22%22%22The Virgil class is a high-level API that provides easy access to%0A Virgil Security services and allows to perform cryptographic operations by using two domain entities%0A VirgilKey and VirgilCard. Where the VirgilKey is an entity%0A that represents a user's Private key, and the VirgilCard is the entity that represents%0A user's identity and a Public key.%22%22%22%0A%0A def __init__(%0A self,%0A access_token=None, # type: str%0A context=None # type: VirgilContext%0A ):%0A # type: (...) -%3E None%0A self.__access_token = access_token%0A self._context = context%0A self.keys = KeyManager(self.__context)%0A self.cards = CardManager(self.__context)%0A self.identities = IdentitiesManager(self.__context)%0A%0A @property%0A def __context(self):%0A # type: () -%3E VirgilContext%0A %22%22%22Gets context for further use in api%22%22%22%0A if not self._context:%0A self._context = VirgilContext(self.__access_token)%0A return self._context%0A
|
|
cfc37e2556dc018f1150e647253f377c3e8b75ae
|
Add subtree_sim.py
|
scripts/subtree_sim.py
|
scripts/subtree_sim.py
|
Python
| 0.000008
|
@@ -0,0 +1,704 @@
+import numpy as np%0Afrom cogent import LoadTree%0A%0A%0ACLI = %22%22%22%0AUSAGE:%0A random_subtree %3Ctree%3E %3Cn%3E%0A%0ASubsamples %3Cn%3E taxa from the Newick tree in %3Ctree%3E, preserving the branch%0Alengths of subsampled taxa.%0A%22%22%22%0A%0Adef main(treefile, n):%0A n = int(n)%0A tree = LoadTree(%0A with open(treefile) as trees:%0A for tree in trees:%0A tree = ete.Tree(tree.strip())%0A leaves = tree.get_leaf_names()%0A subsample = %5Bleaves%5Bi%5D for i in np.random.choice(n, size=len(tree))%5D%0A tree.prune(subsample, preserve_branch_length=True)%0A print(tree.write())%0A%0Aif __name__ == %22__main__%22:%0A import docopt%0A opts = docopt.docopt(CLI)%0A main(opts%5B'%3Ctree%3E'%5D, int(opts%5B'%3Cn%3E'%5D))%0A
|
|
e81bfc0ddcfdc321af0608d553b123fa2188de38
|
Consolidate implementations
|
datashape/user.py
|
datashape/user.py
|
from __future__ import print_function, division, absolute_import
from datashape.dispatch import dispatch
from .coretypes import *
from .predicates import isdimension
from .util import dshape
import sys
from datetime import date, time, datetime
__all__ = ['validate', 'issubschema']
basetypes = np.generic, int, float, str, date, time, datetime
@dispatch(np.dtype, basetypes)
def validate(schema, value):
return np.issubdtype(type(value), schema)
@dispatch(CType, basetypes)
def validate(schema, value):
return validate(to_numpy_dtype(schema), value)
@dispatch(DataShape, (tuple, list))
def validate(schema, value):
head = schema[0]
return ((len(schema) == 1 and validate(head, value))
or (isdimension(head)
and (isinstance(head, Var) or int(head) == len(value))
and all(validate(DataShape(*schema[1:]), item) for item in value)))
@dispatch(DataShape, object)
def validate(schema, value):
if len(schema) == 1:
return validate(schema[0], value)
@dispatch(Record, dict)
def validate(schema, d):
return all(validate(sch, d.get(k)) for k, sch in schema.parameters[0])
@dispatch(String, str)
def validate(schema, value):
return True
@dispatch(Record, (tuple, list))
def validate(schema, seq):
return all(validate(sch, item) for (k, sch), item
in zip(schema.parameters[0], seq))
@dispatch(str, object)
def validate(schema, value):
return validate(dshape(schema), value)
@dispatch(type, object)
def validate(schema, value):
return isinstance(value, schema)
@dispatch(tuple, object)
def validate(schemas, value):
return any(validate(schema, value) for schema in schemas)
@dispatch(object, object)
def validate(schema, value):
return False
@dispatch(Time, time)
def validate(schema, value):
return True
@dispatch(Date, date)
def validate(schema, value):
return True
@dispatch(DateTime, datetime)
def validate(schema, value):
return True
@dispatch(DataShape, np.ndarray)
def validate(schema, value):
return issubschema(from_numpy(value.shape, value.dtype), schema)
@dispatch(object, object)
def issubschema(a, b):
return issubschema(dshape(a), dshape(b))
@dispatch(DataShape, DataShape)
def issubschema(a, b):
if a == b:
return True
# TODO, handle cases like float < real
# TODO, handle records {x: int, y: int, z: int} < {x: int, y: int}
return None # We don't know, return something falsey
|
Python
| 0.000008
|
@@ -1130,78 +1130,8 @@
)%0A%0A%0A
-@dispatch(String, str)%0Adef validate(schema, value):%0A return True%0A%0A%0A
@dis
@@ -1700,85 +1700,88 @@
%0A%0A%0A@
-dispatch(Time, time)%0Adef validate(schema, value):%0A return True%0A%0A%0A@dispatch
+validate.register(String, str)%0A@validate.register(Time, time)%0A@validate.register
(Dat
@@ -1789,28 +1789,25 @@
, date)%0A
-def
+@
validate
(schema,
@@ -1802,52 +1802,17 @@
date
-(schema, value):%0A return True%0A%0A%0A@dispatch
+.register
(Dat
@@ -1832,32 +1832,44 @@
me)%0Adef validate
+_always_true
(schema, value):
|
5d0c16c877fb445114d2b77ee7a4d14686320688
|
Add Python solution for day 19
|
day19/solution.py
|
day19/solution.py
|
Python
| 0
|
@@ -0,0 +1,2066 @@
+import re%0A%0Adata = open(%22data%22, %22r%22).read()%0A%0ApossibleReplacements = %7B%7D%0ApossibleReverseReplacements = %7B%7D%0Afor replacement in data.split(%22%5Cn%22):%0A%09lhs, rhs = replacement.split(%22 =%3E %22)%0A%0A%09if lhs in possibleReplacements:%0A%09%09if rhs not in possibleReplacements%5Blhs%5D:%0A%09%09%09possibleReplacements%5Blhs%5D.append(rhs)%0A%09else:%0A%09%09possibleReplacements%5Blhs%5D = %5Brhs%5D;%0A%0A%09if rhs in possibleReverseReplacements:%0A%09%09if lhs not in possibleReverseReplacements%5Brhs%5D:%0A%09%09%09possibleReverseReplacements%5Brhs%5D.append(lhs)%0A%09else:%0A%09%09possibleReverseReplacements%5Brhs%5D = %5Blhs%5D;%0A%0AinputMolecule = %22CRnSiRnCaPTiMgYCaPTiRnFArSiThFArCaSiThSiThPBCaCaSiRnSiRnTiTiMgArPBCaPMgYPTiRnFArFArCaSiRnBPMgArPRnCaPTiRnFArCaSiThCaCaFArPBCaCaPTiTiRnFArCaSiRnSiAlYSiThRnFArArCaSiRnBFArCaCaSiRnSiThCaCaCaFYCaPTiBCaSiThCaSiThPMgArSiRnCaPBFYCaCaFArCaCaCaCaSiThCaSiRnPRnFArPBSiThPRnFArSiRnMgArCaFYFArCaSiRnSiAlArTiTiTiTiTiTiTiRnPMgArPTiTiTiBSiRnSiAlArTiTiRnPMgArCaFYBPBPTiRnSiRnMgArSiThCaFArCaSiThFArPRnFArCaSiRnTiBSiThSiRnSiAlYCaFArPRnFArSiThCaFArCaCaSiThCaCaCaSiRnPRnCaFArFYPMgArCaPBCaPBSiRnFYPBCaFArCaSiAl%22%0A%0AinputAtoms = re.findall(r'%5BA-Z%5D%5Ba-z%5D?', inputMolecule)%0A%0Asynthesizeable = %5B%5D%0Afor inputAtom in inputAtoms:%0A%09if inputAtom in possibleReplacements:%0A%09%09synthesizeable.append(%5BinputAtom%5D + possibleReplacements%5BinputAtom%5D)%0A%09else:%0A%09%09synthesizeable.append(%5BinputAtom%5D)%0A%0Adef getCombinations(array):%0A%09combinations = %5B%5D%0A%0A%09firstElements = map(lambda a: a%5B0%5D, array)%0A%0A%09for index, current in enumerate(array):%0A%09%09before = %22%22.join(firstElements%5B:index%5D)%0A%09%09after = %22%22.join(firstElements%5Bindex + 1:%5D)%0A%0A%09%09for x in range(1, len(current)):%0A%09%09%09value = current%5Bx%5D%0A%0A%09%09%09combinations.append(before + value + after)%0A%0A%09return combinations%0A%0Aprint %22Distinct molecules after one replacement:%22, len(set(getCombinations(synthesizeable)))%0A%0A# This solution is credited to /u/askalski ; https://www.reddit.com/r/adventofcode/comments/3xflz8/day_19_solutions/cy4etju%0Aprint %22Replacements to get to medicine molecule from 'e':%22, %5C%0A%09len(inputAtoms) - %5C%0A%09len(filter(lambda a: a == %22Rn%22 or a == %22Ar%22, inputAtoms)) - %5C%0A%092 * len(filter(lambda a: a == %22Y%22, inputAtoms)) - 1%0A
|
|
cdfdf0646151c54001ccbc80eca5c0e8f83ff38a
|
add tests for Compose class
|
rhcephcompose/tests/test_compose.py
|
rhcephcompose/tests/test_compose.py
|
Python
| 0.000001
|
@@ -0,0 +1,770 @@
+import os%0Aimport time%0Afrom rhcephcompose.compose import Compose%0Afrom kobo.conf import PyConfigParser%0A%0ATESTS_DIR = os.path.dirname(os.path.abspath(__file__))%0AFIXTURES_DIR = os.path.join(TESTS_DIR, 'fixtures')%0A%0A%0Aclass TestCompose(object):%0A%0A conf_file = os.path.join(FIXTURES_DIR, 'basic.conf')%0A conf = PyConfigParser()%0A conf.load_from_file(conf_file)%0A%0A def test_constructor(self):%0A c = Compose(self.conf)%0A assert isinstance(c, Compose)%0A assert c.target == 'trees'%0A%0A def test_output_dir(self, tmpdir, monkeypatch):%0A monkeypatch.chdir(tmpdir)%0A c = Compose(self.conf)%0A compose_date = time.strftime('%25Y%25m%25d')%0A expected = 'trees/Ceph-2-Ubuntu-x86_64-%25s.t.0' %25 compose_date%0A assert c.output_dir == expected%0A
|
|
885bf944b7839e54a83ce0737b05ff11fa7d3d86
|
Create selfTest.py
|
searchSort/selfTest.py
|
searchSort/selfTest.py
|
Python
| 0.000002
|
@@ -0,0 +1,1257 @@
+from random import randrange, shuffle%0A%0A%0Adef quick_sort(collection, low, high):%0A if low %3C high:%0A p = partition(collection, low, high)%0A quick_sort(collection, low, p)%0A quick_sort(collection, p + 1, high)%0A%0A%0Adef partition(collection, low, high):%0A pivot = collection%5B(low + high) // 2%5D%0A low -= 1%0A high += 1%0A while True:%0A high -= 1%0A while collection%5Bhigh%5D %3E pivot:%0A high -= 1%0A low += 1%0A while collection%5Blow%5D %3C pivot:%0A low += 1%0A if low %3C high:%0A temp = collection%5Blow%5D%0A collection%5Blow%5D = collection%5Bhigh%5D%0A collection%5Bhigh%5D = temp%0A else:%0A return high%0A%0A%0Adef bubble_sort(collection):%0A for _ in range(len(collection)):%0A for index in range(len(collection) - 1):%0A if collection%5Bindex%5D %3E collection%5Bindex + 1%5D:%0A temp = collection%5Bindex%5D%0A collection%5Bindex%5D = collection%5Bindex + 1%5D%0A collection%5Bindex + 1%5D = temp%0A%0A%0Adef main():%0A test = %5Brandrange(100) for _ in range(100)%5D%0A fixture = sorted(test)%0A%0A quick_sort(test, 0, len(test) - 1)%0A assert test == fixture%0A shuffle(test)%0A%0A bubble_sort(test)%0A assert test == fixture%0A shuffle(test)%0A%0A%0Amain()%0A
|
|
20d1a1784f0831c14e6e03bbb86f5b8dd5ae49ea
|
Create learn.py
|
smalltwo/learn.py
|
smalltwo/learn.py
|
Python
| 0
|
@@ -0,0 +1 @@
+%0A
|
|
d0f268836f4096800f1deccf727724de2186ba0c
|
Make logging at debug levels more convenient
|
wal_e/log_help.py
|
wal_e/log_help.py
|
"""
A module to assist with using the Python logging module
"""
import datetime
import errno
import logging
import logging.handlers
import os
from os import path
# Minimum logging level to emit logs for, inclusive.
MINIMUM_LOG_LEVEL = logging.INFO
class IndentFormatter(logging.Formatter):
def format(self, record, *args, **kwargs):
"""
Format a message in the log
Act like the normal format, but indent anything that is a
newline within the message.
"""
return logging.Formatter.format(
self, record, *args, **kwargs).replace('\n', '\n' + ' ' * 8)
def configure(*args, **kwargs):
"""
Configure logging.
Borrowed from logging.basicConfig
Uses the IndentFormatter instead of the regular Formatter
Also, opts the caller into Syslog output, unless syslog could not
be opened for some reason or another, in which case a warning will
be printed to the other log handlers.
"""
level = kwargs.setdefault('level', logging.INFO)
handlers = []
# Add stderr output.
handlers.append(logging.StreamHandler())
def terrible_log_output(s):
import sys
print >>sys.stderr, s
places = [
# Linux
'/dev/log',
# FreeBSD
'/var/run/log',
# Macintosh
'/var/run/syslog',
]
default_syslog_address = places[0]
for p in places:
if path.exists(p):
default_syslog_address = p
break
syslog_address = kwargs.setdefault('syslog_address',
default_syslog_address)
try:
# Add syslog output.
handlers.append(logging.handlers.SysLogHandler(syslog_address))
except EnvironmentError, e:
if e.errno in [errno.ENOENT, errno.EACCES, errno.ECONNREFUSED]:
message = ('wal-e: Could not set up syslog, '
'continuing anyway. '
'Reason: {0}').format(errno.errorcode[e.errno])
terrible_log_output(message)
fs = kwargs.get("format", logging.BASIC_FORMAT)
dfs = kwargs.get("datefmt", None)
fmt = IndentFormatter(fs, dfs)
for handler in handlers:
handler.setFormatter(fmt)
handler.setLevel(level)
logging.root.addHandler(handler)
logging.root.setLevel(level)
class WalELogger(object):
def __init__(self, *args, **kwargs):
self._logger = logging.getLogger(*args, **kwargs)
@staticmethod
def _fmt_structured(d):
"""Formats '{k1:v1, k2:v2}' => 'time=... pid=... k1=v1 k2=v2'
Output is lexically sorted, *except* the time and pid always
come first, to assist with human scanning of the data.
"""
timeEntry = datetime.datetime.utcnow().strftime(
"time=%Y-%m-%dT%H:%M:%S.%f-00")
pidEntry = "pid=" + str(os.getpid())
rest = sorted('='.join([unicode(k), unicode(v)])
for (k, v) in d.items())
return ' '.join([timeEntry, pidEntry] + rest)
@staticmethod
def fmt_logline(msg, detail=None, hint=None, structured=None):
msg_parts = ['MSG: ' + msg]
if detail is not None:
msg_parts.append('DETAIL: ' + detail)
if hint is not None:
msg_parts.append('HINT: ' + hint)
# Initialize a fresh dictionary if structured is not passed,
# because keyword arguments are not re-evaluated when calling
# the function and it's okay for callees to mutate their
# passed dictionary.
if structured is None:
structured = {}
msg_parts.append('STRUCTURED: ' +
WalELogger._fmt_structured(structured))
return '\n'.join(msg_parts)
def log(self, level, msg, *args, **kwargs):
if level < MINIMUM_LOG_LEVEL:
return
detail = kwargs.pop('detail', None)
hint = kwargs.pop('hint', None)
structured = kwargs.pop('structured', None)
self._logger.log(
level,
self.fmt_logline(msg, detail, hint, structured),
*args, **kwargs)
# Boilerplate convenience shims to different logging levels. One
# could abuse dynamism to generate these bindings in a loop, but
# one day I hope to run with PyPy and tricks like that tend to
# lobotomize an optimizer something fierce.
def debug(self, *args, **kwargs):
self.log(logging.DEBUG, *args, **kwargs)
def info(self, *args, **kwargs):
self.log(logging.INFO, *args, **kwargs)
def warning(self, *args, **kwargs):
self.log(logging.WARNING, *args, **kwargs)
def error(self, *args, **kwargs):
self.log(logging.ERROR, *args, **kwargs)
def critical(self, *args, **kwargs):
self.log(logging.CRITICAL, *args, **kwargs)
# End convenience shims
|
Python
| 0.000001
|
@@ -1013,28 +1013,33 @@
level',
-logging.INFO
+MINIMUM_LOG_LEVEL
)%0A ha
|
ae93e08c8ebb5bd502d1a5ad3d96bd773c5efce2
|
fix for #1409
|
drivers/python/rethinkdb/errors.py
|
drivers/python/rethinkdb/errors.py
|
# Copyright 2010-2015 RethinkDB, all rights reserved.
__all__ = [
"ReqlCursorEmpty", "RqlCursorEmpty",
"ReqlError", "RqlError",
"ReqlCompileError", "RqlCompileError",
"ReqlDriverCompileError",
"ReqlServerCompileError",
"ReqlRuntimeError", "RqlRuntimeError",
"ReqlQueryLogicError",
"ReqlNonExistenceError",
"ReqlResourceLimitError",
"ReqlUserError",
"ReqlInternalError",
"ReqlTimeoutError", "RqlTimeoutError",
"ReqlAvailabilityError",
"ReqlOpFailedError",
"ReqlOpIndeterminateError",
"ReqlPermissionError",
"ReqlDriverError", "RqlDriverError", "RqlClientError",
"ReqlAuthError"
]
import sys
try:
unicode
def convertForPrint(inputString):
if type(inputString) == unicode:
encoding = 'utf-8'
if hasattr(sys.stdout, 'encoding') and sys.stdout.encoding:
encoding = sys.stdout.encoding
return inputString.encode(encoding or 'utf-8', 'replace')
else:
return str(inputString)
except NameError:
def convertForPrint(inputString):
return inputString
try:
{}.iteritems
dict_items = lambda d: d.iteritems()
except AttributeError:
dict_items = lambda d: d.items()
class ReqlCursorEmpty(Exception):
def __init__(self):
super(ReqlCursorEmpty, self).__init__("Cursor is empty.")
self.message = "Cursor is empty."
RqlCursorEmpty = ReqlCursorEmpty
class ReqlError(Exception):
def __init__(self, message, term=None, frames=None):
super(ReqlError, self).__init__(message)
self.message = message
self.frames = frames
if term is not None and frames is not None:
self.query_printer = QueryPrinter(term, self.frames)
def __str__(self):
if self.frames is None:
return convertForPrint(self.message)
else:
return convertForPrint("%s in:\n%s\n%s" % (
self.message.rstrip("."),
self.query_printer.print_query(),
self.query_printer.print_carrots()))
RqlError = ReqlError
class ReqlCompileError(ReqlError):
pass
RqlCompileError = ReqlCompileError
class ReqlDriverCompileError(ReqlCompileError):
pass
class ReqlServerCompileError(ReqlCompileError):
pass
class ReqlRuntimeError(ReqlError):
pass
RqlRuntimeError = ReqlRuntimeError
class ReqlQueryLogicError(ReqlRuntimeError):
pass
class ReqlNonExistenceError(ReqlQueryLogicError):
pass
class ReqlResourceLimitError(ReqlRuntimeError):
pass
class ReqlUserError(ReqlRuntimeError):
pass
class ReqlInternalError(ReqlRuntimeError):
pass
class ReqlAvailabilityError(ReqlRuntimeError):
pass
class ReqlOpFailedError(ReqlAvailabilityError):
pass
class ReqlOpIndeterminateError(ReqlAvailabilityError):
pass
class ReqlPermissionError(ReqlRuntimeError):
pass
class ReqlDriverError(ReqlError):
pass
RqlClientError = ReqlDriverError
RqlDriverError = ReqlDriverError
class ReqlAuthError(ReqlDriverError):
def __init__(self, msg, host=None, port=None):
if host is None or port is None:
super(ReqlDriverError, self).__init__(msg)
else:
super(ReqlDriverError, self).__init__(
"Could not connect to %s:%d: %s" %
(host, port, msg))
try:
class ReqlTimeoutError(ReqlDriverError, TimeoutError):
def __init__(self, host=None, port=None):
if host is None or port is None:
super(ReqlDriverError, self).__init__("Operation timed out.")
else:
super(ReqlDriverError, self).__init__(
"Could not connect to %s:%d, operation timed out." % (host, port))
except NameError:
class ReqlTimeoutError(ReqlDriverError):
def __init__(self, host=None, port=None):
if host is None or port is None:
super(ReqlDriverError, self).__init__("Operation timed out.")
else:
super(ReqlDriverError, self).__init__(
"Could not connect to %s:%d, operation timed out." % (host, port))
RqlTimeoutError = ReqlTimeoutError
class QueryPrinter(object):
def __init__(self, root, frames=[]):
self.root = root
self.frames = frames
def print_query(self):
return ''.join(self.compose_term(self.root))
def print_carrots(self):
return ''.join(self.compose_carrots(self.root, self.frames))
def compose_term(self, term):
args = [self.compose_term(a) for a in term._args]
optargs = {}
for k, v in dict_items(term.optargs):
optargs[k] = self.compose_term(v)
return term.compose(args, optargs)
def compose_carrots(self, term, frames):
# This term is the cause of the error
if len(frames) == 0:
return ['^' for i in self.compose_term(term)]
cur_frame = frames[0]
args = [self.compose_carrots(arg, frames[1:])
if cur_frame == i else self.compose_term(arg)
for i, arg in enumerate(term._args)]
optargs = {}
for k, v in dict_items(term.optargs):
if cur_frame == k:
optargs[k] = self.compose_carrots(v, frames[1:])
else:
optargs[k] = self.compose_term(v)
return [' ' if i != '^' else '^' for i in term.compose(args, optargs)]
# This 'enhanced' tuple recursively iterates over it's elements allowing us to
# construct nested heirarchies that insert subsequences into tree. It's used
# to construct the query representation used by the pretty printer.
class T(object):
# N.B Python 2.x doesn't allow keyword default arguments after *seq
# In Python 3.x we can rewrite this as `__init__(self, *seq, intsp=''`
def __init__(self, *seq, **opts):
self.seq = seq
self.intsp = opts.pop('intsp', '')
def __iter__(self):
itr = iter(self.seq)
for sub in next(itr):
yield sub
for token in itr:
for sub in self.intsp:
yield sub
for sub in token:
yield sub
|
Python
| 0
|
@@ -2194,16 +2194,120 @@
rots()))
+%0A %0A def __repr__(self):%0A return %22%3C%25s instance: %25s %3E%22 %25 (self.__class__.__name__, str(self))
%0A%0ARqlErr
|
6090dc1539bd0701381c73128a5ca0606adc09e4
|
Add SSDP unit test case (init)
|
tests/utils/test_ssdp.py
|
tests/utils/test_ssdp.py
|
Python
| 0
|
@@ -0,0 +1,706 @@
+# -*- coding: utf-8 -*-%0A'''%0A :codeauthor: :email:%60Bo Maryniuk %3Cbo@suse.de%3E%60%0A'''%0A%0Afrom __future__ import absolute_import, print_function, unicode_literals%0Afrom tests.support.unit import TestCase, skipIf%0Afrom tests.support.mock import (%0A NO_MOCK,%0A NO_MOCK_REASON,%0A MagicMock,%0A patch)%0A%0A# Import Salt libs%0Aimport salt.exceptions%0Aimport salt.state%0A%0Atry:%0A import pytest%0Aexcept ImportError as err:%0A pytest = None%0A%0A%0A@skipIf(NO_MOCK, NO_MOCK_REASON)%0A@skipIf(pytest is None, 'PyTest is missing')%0Aclass SSDPTestCase(TestCase):%0A '''%0A TestCase for SSDP-related parts.%0A '''%0A%0A def test_ssdp_base(self):%0A '''%0A Test SSDP base class main methods.%0A%0A :return:%0A '''%0A
|
|
b6d3ab372f57ad9e3c8427ba8bc211136bc1037b
|
Set version to 0.1.9a1
|
src/powerdns_manager/__init__.py
|
src/powerdns_manager/__init__.py
|
# -*- coding: utf-8 -*-
#
# This file is part of django-powerdns-manager.
#
# django-powerdns-manager is a web based PowerDNS administration panel.
#
# Development Web Site:
# - http://www.codetrax.org/projects/django-powerdns-manager
# Public Source Code Repository:
# - https://source.codetrax.org/hgroot/django-powerdns-manager
#
# Copyright 2012 George Notaras <gnot [at] g-loaded.eu>
#
# 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.
#
# Scheme: <major>.<minor>.<maintenance>.<maturity>.<revision>
# maturity: final/beta/alpha
VERSION = (0, 1, 8, 'alpha', 1)
def get_version():
version = '%s.%s' % (VERSION[0], VERSION[1])
if VERSION[2] is not None:
version = '%s.%s' % (version, VERSION[2])
if VERSION[3] != 'final':
if VERSION[4] > 0:
version = '%s%s%s' % (version, VERSION[3][0], VERSION[4])
else:
version = '%s%s' % (version, VERSION[3][0])
return version
__version__ = get_version()
def get_status_classifier():
if VERSION[3] == 'final':
return 'Development Status :: 5 - Production/Stable'
elif VERSION[3] == 'beta':
return 'Development Status :: 4 - Beta'
elif VERSION[3] == 'alpha':
return 'Development Status :: 3 - Alpha'
raise NotImplementedError
|
Python
| 0.001588
|
@@ -1060,17 +1060,17 @@
(0, 1,
-8
+9
, 'alpha
|
70b4afc095873ad226947edc757cbc4d29daf44a
|
Add test_incomplete_write.py test to reproduce #173
|
functests/test_incomplete_write.py
|
functests/test_incomplete_write.py
|
Python
| 0
|
@@ -0,0 +1,1623 @@
+from __future__ import print_function%0Aimport os%0Aimport sys%0Aimport socket%0Aimport datetime%0Aimport time%0Aimport akumulid_test_tools as att%0Aimport json%0Atry:%0A from urllib2 import urlopen%0Aexcept ImportError:%0A from urllib import urlopen%0Aimport traceback%0Aimport itertools%0Aimport math%0A%0AHOST = '127.0.0.1'%0ATCPPORT = 8282%0AHTTPPORT = 8181%0A%0Adef main(path):%0A akumulid = att.create_akumulid(path)%0A%0A # Reset database%0A akumulid.delete_database()%0A akumulid.create_database()%0A # start ./akumulid server%0A print(%22Starting server...%22)%0A akumulid.serve()%0A time.sleep(5)%0A try:%0A%0A chan = att.TCPChan(HOST, TCPPORT)%0A%0A # fill data in%0A invalid_sample = %22+cpuload host=machine1%5Cr%5Cn:1418224205000000000%5Cr%5Cr+25.0%5Cr%5Cn%22 # reportd in issue#173%0A chan.send(invalid_sample)%0A time.sleep(5) # wait untill all messagess will be processed%0A query = %7B%22select%22:%22cpuload%22,%22range%22: %7B%22from%22:1418224205000000000, %22to%22:1418224505000000000%7D%7D%0A queryurl = %22http://%7B0%7D:%7B1%7D/api/query%22.format(HOST, HTTPPORT)%0A response = urlopen(queryurl, json.dumps(query))%0A # response should be empty%0A for line in response:%0A print(%22Unexpected response: %7B0%7D%22.format(line))%0A raise ValueError(%22Unexpected response%22)%0A except:%0A traceback.print_exc()%0A sys.exit(1)%0A finally:%0A print(%22Stopping server...%22)%0A akumulid.stop()%0A time.sleep(5)%0A%0Aif __name__ == '__main__':%0A if len(sys.argv) %3C 2:%0A print(%22Not enough arguments%22)%0A sys.exit(1)%0A main(sys.argv%5B1%5D)%0Aelse:%0A raise ImportError(%22This module shouldn't be imported%22)%0A
|
|
27147c9691b49a420ddb51a37f19203416429224
|
test with isinstance(<X>, (list, tuple)) rather than type(<X>)==list
|
jsonrpc_http/Engine.py
|
jsonrpc_http/Engine.py
|
import inspect
#
import tabular_predDB.cython_code.State as State
import tabular_predDB.python_utils.sample_utils as su
def int_generator(start=0):
next_i = start
while True:
yield next_i
next_i += 1
class Engine(object):
def __init__(self, seed=0):
self.seed_generator = int_generator(seed)
def get_next_seed(self):
return self.seed_generator.next()
def initialize(self, M_c, M_r, T, initialization='from_the_prior'):
# FIXME: why is M_r passed?
SEED = self.get_next_seed()
p_State = State.p_State(M_c, T, initialization=initialization, SEED=SEED)
X_L = p_State.get_X_L()
X_D = p_State.get_X_D()
return M_c, M_r, X_L, X_D
def analyze(self, M_c, T, X_L, X_D, kernel_list=(), n_steps=1, c=(), r=(),
max_iterations=-1, max_time=-1):
SEED = self.get_next_seed()
p_State = State.p_State(M_c, T, X_L, X_D, SEED=SEED)
# FIXME: actually pay attention to max_iterations, max_time
p_State.transition(kernel_list, n_steps, c, r,
max_iterations, max_time)
X_L_prime = p_State.get_X_L()
X_D_prime = p_State.get_X_D()
return X_L_prime, X_D_prime
def simple_predictive_sample(self, M_c, X_L, X_D, Y, Q, n=1):
if type(X_L) == list:
assert type(X_D) == list
samples = su.simple_predictive_sample_multistate(M_c, X_L, X_D, Y, Q,
self.get_next_seed, n)
else:
samples = su.simple_predictive_sample(M_c, X_L, X_D, Y, Q,
self.get_next_seed, n)
return samples
def simple_predictive_probability(self, M_c, X_L, X_D, Y, Q, n):
p = None
return p
def impute(self, M_c, X_L, X_D, Y, Q, n):
e = su.impute(M_c, X_L, X_D, Y, Q, n, self.get_next_seed)
return e
def impute_and_confidence(self, M_c, X_L, X_D, Y, Q, n):
if type(X_L) == list:
assert type(X_D) == list
# TODO: multistate impute doesn't exist yet
e,confidence = su.impute_and_confidence_multistate(M_c, X_L, X_D, Y, Q, n, self.get_next_seed)
else:
e,confidence = su.impute_and_confidence(M_c, X_L, X_D, Y, Q, n, self.get_next_seed)
return (e,confidence)
def conditional_entropy(M_c, X_L, X_D, d_given, d_target,
n=None, max_time=None):
e = None
return e
def predictively_related(self, M_c, X_L, X_D, d,
n=None, max_time=None):
m = []
return m
def contextual_structural_similarity(self, X_D, r, d):
s = []
return s
def structural_similarity(self, X_D, r):
s = []
return s
def structural_anomalousness_columns(self, X_D):
a = []
return a
def structural_anomalousness_rows(self, X_D):
a = []
return a
def predictive_anomalousness(self, M_c, X_L, X_D, T, q, n):
a = []
return a
# helper functions
get_name = lambda x: getattr(x, '__name__')
get_Engine_attr = lambda x: getattr(Engine, x)
is_Engine_method_name = lambda x: inspect.ismethod(get_Engine_attr(x))
#
def get_method_names():
return filter(is_Engine_method_name, dir(Engine))
#
def get_method_name_to_args():
method_names = get_method_names()
method_name_to_args = dict()
for method_name in method_names:
method = Engine.__dict__[method_name]
arg_str_list = inspect.getargspec(method).args[1:]
method_name_to_args[method_name] = arg_str_list
return method_name_to_args
|
Python
| 0.001867
|
@@ -1318,63 +1318,89 @@
if
-type(X_L) == list:%0A assert type(X_D) == list
+isinstance(X_L, (list, tuple)):%0A assert isinstance(X_D, (list, tuple))
%0A
@@ -2054,63 +2054,89 @@
if
-type(X_L) == list:%0A assert type(X_D) == list
+isinstance(X_L, (list, tuple)):%0A assert isinstance(X_D, (list, tuple))
%0A
|
67328984667246325244c0eaba75de7413c3079f
|
add fibonacci example in redid-example
|
example/redis-example/Fibonacci.py
|
example/redis-example/Fibonacci.py
|
Python
| 0.000133
|
@@ -0,0 +1,1431 @@
+# import redis driver%0Aimport redis%0Aimport pymongo%0A%0A# import python-cache pycache package%0Afrom pycache.Adapter import RedisItemPool%0Afrom pycache.Adapter import MongoItemPool%0Afrom pycache import cached%0A%0Aclient = redis.Redis(host='192.168.99.100', port=32771)%0Apool = RedisItemPool(client)%0A%0Amongo_client = pymongo.MongoClient(host=%22192.168.99.100%22, port=27017)%0Amongo_pool = MongoItemPool(mongo_client)%0A%0Adef fib(num):%0A if num == 1 or num == 0:%0A return num%0A return fib(num-1) + fib(num-2)%0A%0A@cached(CacheItemPool=pool)%0Adef cached_fib(num):%0A if num == 1 or num == 0:%0A return num%0A return cached_fib(num - 1) + cached_fib(num - 2)%0A%0A@cached(CacheItemPool=mongo_pool)%0Adef mongo_cached_fib(num):%0A if num == 1 or num == 0:%0A return num%0A return mongo_cached_fib(num - 1) + mongo_cached_fib(num - 2)%0A%0A%0Afrom datetime import datetime%0Afor i in range(1, 50):%0A cur = datetime.utcnow()%0A fib(i)%0A diff = (datetime.utcnow() - cur)%0A nocached = float(diff.seconds) + float(diff.microseconds) / 1000000%0A%0A cur = datetime.utcnow()%0A cached_fib(i)%0A diff = (datetime.utcnow() - cur)%0A cached = float(diff.seconds) + float(diff.microseconds) / 1000000%0A pool.clear()%0A%0A cur = datetime.utcnow()%0A mongo_cached_fib(i)%0A diff = (datetime.utcnow() - cur)%0A mongo_cached = float(diff.seconds) + float(diff.microseconds) / 1000000%0A mongo_pool.clear()%0A%0A%0A%0A print i, nocached, cached, mongo_cached
|
|
e39415fbe6a325894abb8d098504150b1c515b57
|
Create split-linked-list-in-parts.py
|
Python/split-linked-list-in-parts.py
|
Python/split-linked-list-in-parts.py
|
Python
| 0.000003
|
@@ -0,0 +1,2412 @@
+# Time: O(n)%0A# Space: O(n)%0A%0A# Given a chemical formula (given as a string), return the count of each atom.%0A#%0A# An atomic element always starts with an uppercase character,%0A# then zero or more lowercase letters, representing the name.%0A#%0A# 1 or more digits representing the count of that element may follow if the count is greater than 1.%0A# If the count is 1, no digits will follow. For example, H2O and H2O2 are possible, but H1O2 is impossible.%0A#%0A# Two formulas concatenated together produce another formula. For example, H2O2He3Mg4 is also a formula.%0A#%0A# A formula placed in parentheses, and a count (optionally added) is also a formula.%0A# For example, (H2O2) and (H2O2)3 are formulas.%0A#%0A# Given a formula, output the count of all elements as a string in the following form:%0A# the first name (in sorted order), followed by its count (if that count is more than 1),%0A# followed by the second name (in sorted order),%0A# followed by its count (if that count is more than 1), and so on.%0A#%0A# Example 1:%0A# Input: %0A# formula = %22H2O%22%0A# Output: %22H2O%22%0A# Explanation: %0A# The count of elements are %7B'H': 2, 'O': 1%7D.%0A#%0A# Example 2:%0A# Input: %0A# formula = %22Mg(OH)2%22%0A# Output: %22H2MgO2%22%0A# Explanation: %0A# The count of elements are %7B'H': 2, 'Mg': 1, 'O': 2%7D.%0A#%0A# Example 3:%0A# Input: %0A# formula = %22K4(ON(SO3)2)2%22%0A# Output: %22K4N2O14S4%22%0A# Explanation: %0A# The count of elements are %7B'K': 4, 'N': 2, 'O': 14, 'S': 4%7D.%0A# Note:%0A#%0A# All atom names consist of lowercase letters, except for the first character which is uppercase.%0A# The length of formula will be in the range %5B1, 1000%5D.%0A# formula will only consist of letters, digits, and round parentheses,%0A# and is a valid formula as defined in the problem.%0A%0Aclass Solution(object):%0A def countOfAtoms(self, formula):%0A %22%22%22%0A :type formula: str%0A :rtype: str%0A %22%22%22%0A parse = re.findall(r%22(%5BA-Z%5D%5Ba-z%5D*)(%5Cd*)%7C(%5C()%7C(%5C))(%5Cd*)%22, formula)%0A stk = %5Bcollections.Counter()%5D%0A for name, m1, left_open, right_open, m2 in parse:%0A if name:%0A stk%5B-1%5D%5Bname%5D += int(m1 or 1)%0A if left_open:%0A stk.append(collections.Counter())%0A if right_open:%0A top = stk.pop()%0A for k, v in top.iteritems():%0A stk%5B-1%5D%5Bk%5D += v * int(m2 or 1)%0A%0A return %22%22.join(name + (str(stk%5B-1%5D%5Bname%5D) if stk%5B-1%5D%5Bname%5D %3E 1 else '') %5C%0A for name in sorted(stk%5B-1%5D))%0A
|
|
4709a38f67c80c1516b4eae6eb7d8f54cdd985e2
|
Create songsched.py
|
Songsched/songsched.py
|
Songsched/songsched.py
|
Python
| 0.000001
|
@@ -0,0 +1 @@
+%0A
|
|
9beaa2052b4e47a2fd075f4d9b7988b03a38a8ad
|
Create main.py
|
main.py
|
main.py
|
Python
| 0.000001
|
@@ -0,0 +1,793 @@
+import optparse, settings%0A%0Adef main():%0A parser = optparse.OptionParser()%0A %0A parser.add_option('-c',%0A '--charity',%0A dest='charity',%0A default=None,%0A action=%22store_true%22,%0A help='Sets whether you accept rewardless bounties')%0A parser.add_option('-l',%0A '--latency',%0A dest='accept_latency',%0A default=None,%0A help='Maximum acceptable latency from a server')%0A parser.add_option('-f',%0A '--propagation-factor',%0A dest='propagate-factor',%0A default=None,%0A help='Minimum funds:reward ratio you'll propagate bounties at')%0A
|
|
c36f36555b8fba183220456e51e04ccbaa08bb60
|
add a data file to play with.
|
cno/data/ToyMMB/__init__.py
|
cno/data/ToyMMB/__init__.py
|
Python
| 0
|
@@ -0,0 +1,153 @@
+from cellnopt.core import XMIDAS, CNOGraph%0A%0Apknmodel = CNOGraph(%22PKN-ToyMMB.sif%22)%0Adata = XMIDAS(%22MD-ToyMMB.csv%22)%0Adescription = open(%22README.rst%22).read()%0A
|
|
c1ef15e895d4f79a9ef5c83aa13964d30bc8dbff
|
Add main loop
|
main.py
|
main.py
|
Python
| 0
|
@@ -0,0 +1,523 @@
+from Board import *%0Afrom Player import *%0A%0Adef main():%0A board = Board()%0A players = (HumanPlayer('x', board), HumanPlayer('o', board))%0A turnNum = 0%0A currentPlayer = None%0A while not board.endGame():%0A currentPlayer = players%5BturnNum %25 2%5D%0A print %22%25s's turn%22 %25 currentPlayer%0A currentPlayer.takeTurn(board)%0A print board%0A turnNum += 1%0A if board.winner != None:%0A print %22%25ss win!%22 %25 board.winner%0A else:%0A print %22It's a tie!%22%0A%0Aif __name__ == %22__main__%22:%0A main()%0A
|
|
f31b42ae43e7cd2af53a504c1cc2ab398bf7810d
|
Add api call for Premier League standings
|
main.py
|
main.py
|
Python
| 0
|
@@ -0,0 +1,660 @@
+import json%0Aimport requests%0Afrom tabulate import tabulate%0A%0ABASE_URL = %22http://api.football-data.org/alpha/%22%0Asoccer_seasons = %22soccerseasons/%22%0A%0Aepl_current_season = %22soccerseasons/398/%22%0Aleague_table = %22leagueTable/%22%0A%0A%0Adef print_standings(table):%0A%09standings = %5B%5D%0A%09for team in table:%0A%09%09entry = %5Bteam%5B'position'%5D, team%5B'teamName'%5D, team%5B'points'%5D%5D%0A%09%09standings.append(entry)%0A%0A%09print tabulate(standings, headers=%5B'Pos', 'Club', 'Points'%5D, tablefmt=%22rst%22)%0A%0Adef main():%0A%09resp = requests.get(BASE_URL + epl_current_season + league_table)%0A%09data = resp.json()%0A%0A%09league_standings = data%5B'standing'%5D%0A%09%0A%09print_standings(league_standings)%0A%0Aif __name__ == '__main__':%0A%09main()%0A
|
|
c1d5dca7c487075229b384585e0eb11cd91bbef8
|
add import script for Chesterfield
|
polling_stations/apps/data_collection/management/commands/import_chesterfield.py
|
polling_stations/apps/data_collection/management/commands/import_chesterfield.py
|
Python
| 0
|
@@ -0,0 +1,386 @@
+from data_collection.management.commands import BaseXpressDemocracyClubCsvImporter%0A%0Aclass Command(BaseXpressDemocracyClubCsvImporter):%0A council_id = 'E07000034'%0A addresses_name = 'May 2017/ChesterfieldDemocracy_Club__04May2017a.txt'%0A stations_name = 'May 2017/ChesterfieldDemocracy_Club__04May2017a.txt'%0A elections = %5B'local.derbyshire.2017-05-04'%5D%0A csv_delimiter = '%5Ct'%0A
|
|
04155a80531e58422253e22635f1e496a27a5647
|
add import script for South Ribble
|
polling_stations/apps/data_collection/management/commands/import_south_ribble.py
|
polling_stations/apps/data_collection/management/commands/import_south_ribble.py
|
Python
| 0
|
@@ -0,0 +1,1648 @@
+from django.contrib.gis.geos import Point%0Afrom data_collection.management.commands import BaseHalaroseCsvImporter%0A%0Aclass Command(BaseHalaroseCsvImporter):%0A council_id = 'E07000126'%0A addresses_name = 'Properties.csv'%0A stations_name = 'Polling Stations.csv'%0A elections = %5B'local.lancashire.2017-05-04'%5D%0A%0A # South Ribble use Halarose, but they've split the standard export up into%0A # 2 files and removed some columns. They've also added grid refs for the%0A # stations :) We need to customise a bit..%0A%0A station_address_fields = %5B%0A 'pollingstationname',%0A 'pollingstationaddress_1',%0A 'pollingstationaddress_2',%0A 'pollingstationaddress_3',%0A 'pollingstationaddress_4',%0A %5D%0A%0A def get_station_hash(self, record):%0A raise NotImplementedError%0A%0A def get_station_point(self, record):%0A return Point(%0A float(record.easting),%0A float(record.northing),%0A srid=27700%0A )%0A%0A def get_residential_address(self, record):%0A%0A def replace_na(text):%0A if text.strip() == 'n/a':%0A return ''%0A return text.strip()%0A%0A address_line_1 = replace_na(record.housenumber)%0A street_address = replace_na(record.streetname)%0A address_line_1 = address_line_1 + ' ' + street_address%0A%0A address = %22%5Cn%22.join(%5B%0A address_line_1.strip(),%0A replace_na(record.locality),%0A replace_na(record.town),%0A replace_na(record.adminarea),%0A %5D)%0A%0A while %22%5Cn%5Cn%22 in address:%0A address = address.replace(%22%5Cn%5Cn%22, %22%5Cn%22).strip()%0A%0A return address%0A
|
|
e0d728519292377915983385285a3560d3207b19
|
Create main.py
|
main.py
|
main.py
|
Python
| 0.000001
|
@@ -0,0 +1,193 @@
+import webapp2%0A%0Aclass MainHandler(webapp2.RequestHandler):%0A def get(self):%0A self.response.write('Hello world!')%0A%0Aapp = webapp2.WSGIApplication(%5B%0A ('/', MainHandler)%0A%5D, debug=True)%0A
|
|
99b4a6fa8eb96f9228635142d2686b9601f293b5
|
Put main.py back
|
main.py
|
main.py
|
Python
| 0.000001
|
@@ -0,0 +1,776 @@
+import wysiweb%0Aimport shutil%0A%0Atry:%0A shutil.rmtree('./frozen')%0Aexcept:%0A pass%0A%0A# site_path: Where are the files that will build the website%0A# static_path: where are the static files? has to be within site_path%0A# static_route: what is the route to access static files: %3Ca href=%22/static/logo.jpg%22%3E for instance.%0Aw = wysiweb.WYSIWeb(%0A site_path= './www',%0A static_path='./www/static',%0A static_route='/static',%0A input_encoding='utf-8'%0A)%0Aapp = w.app # Needed if you want to serve with, say, nginx%0A%0A%0A%0A%0Aif __name__ == %22__main__%22:%0A # app.run(port=4000, debug=True) # Ready to serve Flask app from the templates in www%0A%0A # or%0A%0A static_app = w.freeze('./frozen')%0A #static_app.run(port=5000, debug=False) # Ready to serve Flask app that mimics a static server%0A
|
|
62df41780706161c4e25f854de0b6cc5d2664a39
|
Add test for templates in include_router path (#349)
|
tests/test_router_prefix_with_template.py
|
tests/test_router_prefix_with_template.py
|
Python
| 0
|
@@ -0,0 +1,471 @@
+from fastapi import APIRouter, FastAPI%0Afrom starlette.testclient import TestClient%0A%0Aapp = FastAPI()%0A%0Arouter = APIRouter()%0A%0A%0A@router.get(%22/users/%7Bid%7D%22)%0Adef read_user(segment: str, id: str):%0A return %7B%22segment%22: segment, %22id%22: id%7D%0A%0A%0Aapp.include_router(router, prefix=%22/%7Bsegment%7D%22)%0A%0A%0Aclient = TestClient(app)%0A%0A%0Adef test_get():%0A response = client.get(%22/seg/users/foo%22)%0A assert response.status_code == 200%0A assert response.json() == %7B%22segment%22: %22seg%22, %22id%22: %22foo%22%7D%0A
|
|
9123b90f21fc341cbb2e333eb53c5149dfda8e3b
|
Add Taiwan time transformed.
|
cttwt.py
|
cttwt.py
|
Python
| 0
|
@@ -0,0 +1,1661 @@
+#!/usr/bin/env python%0A# -*- coding: utf-8 -*-%0A# Copyright (c) 2011 Toomore Chiang, http://toomore.net/%0A#%0A# Permission is hereby granted, free of charge, to any person obtaining a copy%0A# of this software and associated documentation files (the %22Software%22), to deal%0A# in the Software without restriction, including without limitation the rights%0A# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell%0A# copies of the Software, and to permit persons to whom the Software is%0A# furnished to do so, subject to the following conditions:%0A#%0A# The above copyright notice and this permission notice shall be included in%0A# all copies or substantial portions of the Software.%0A#%0A# THE SOFTWARE IS PROVIDED %22AS IS%22, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR%0A# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,%0A# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE%0A# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER%0A# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,%0A# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN%0A# THE SOFTWARE.%0A%0Aimport time,datetime%0A%0Aclass TWTime(object):%0A ''' Transform localtime to Taiwan time in UTF+8 '''%0A def __init__(self,tz = 8):%0A try:%0A self.TimeZone = int(tz)%0A except:%0A self.TimeZone = 8%0A%0A @property%0A def now(self):%0A ''' Display Taiwan Time now '''%0A localtime = datetime.datetime.now()%0A return localtime + datetime.timedelta(hours = time.timezone/60/60 + self.TimeZone)%0A%0A @property%0A def localtime(self):%0A ''' Display localtime now '''%0A return datetime.datetime.now()%0A
|
|
4b7fb1ad3cd03e0593ecd3d0626bca385fb2800d
|
Add scroller example.
|
examples/scroller/scroller.py
|
examples/scroller/scroller.py
|
Python
| 0
|
@@ -0,0 +1,1815 @@
+# coding=utf8%0A%0A#%0A# python-aosd -- python bindings for libaosd%0A#%0A# Copyright (C) 2010 Armin H%C3%A4berling %3Carmin.aha@gmail.com%3E%0A#%0A# Based on the scroller example from libaosd.%0A#%0A%0Aimport sys%0A%0Aimport aosd%0A%0Adef scroll(osd, width, height):%0A pos = 8%0A step = 3%0A %0A osd.set_position(pos, width, height)%0A (x, y, _, _) = osd.get_geometry()%0A osd.set_position_offset(width, height)%0A osd.show()%0A%0A x -= 1%0A y += height - 1;%0A for i in range(1, height + 1, step):%0A osd.loop_for(20)%0A y -= step%0A osd.set_geometry(x, y, width, i)%0A%0A osd.set_position(pos, width, height)%0A osd.set_position_offset(-1, -1)%0A (x, y, _, _) = osd.get_geometry()%0A osd.loop_for(2000)%0A%0A for i in range(height, 0, -step):%0A y += step%0A osd.set_geometry(x, y, width, i);%0A osd.loop_for(20);%0A%0A osd.hide();%0A%0Adef setup():%0A osd = aosd.AosdText()%0A osd.set_transparency(aosd.TRANSPARENCY_COMPOSITE)%0A if osd.get_transparency() != aosd.TRANSPARENCY_COMPOSITE:%0A osd.set_transparency(aosd.TRANSPARENCY_NONE)%0A %0A osd.geom_x_offset = 10%0A osd.geom_y_offset = 10%0A %0A osd.back_color = %22white%22%0A osd.back_opacity = 80%0A%0A osd.shadow_color = %22black%22%0A osd.shadow_opacity = 127%0A osd.shadow_x_offset = 2%0A osd.shadow_y_offset = 2%0A%0A osd.fore_color = %22green%22%0A osd.fore_opacity = 255%0A %0A osd.set_font(%22Times New Roman Italic 24%22)%0A osd.wrap = aosd.PANGO_WRAP_WORD_CHAR%0A osd.alignment = aosd.PANGO_ALIGN_RIGHT%0A osd.set_layout_width(osd.get_screen_wrap_width())%0A return osd%0A%0Adef set_string(osd, text):%0A osd.set_text(text)%0A return osd.get_text_size()%0A%0Adef main(argv):%0A osd = setup()%0A for text in argv%5B1:%5D:%0A width, height = set_string(osd, text)%0A scroll(osd, width, height)%0A%0Aif __name__ == %22__main__%22:%0A main(sys.argv)%0A%0A
|
|
7dfc471a8fc9a2e68f3ef49708c4c309cd2ebea1
|
check license family is valid
|
conda_smithy/lint_recipe.py
|
conda_smithy/lint_recipe.py
|
import io
import itertools
import os
import re
import jinja2
import ruamel.yaml
# patch over differences between PY2 and PY3
try:
text_type = unicode
except NameError:
text_type = str
EXPECTED_SECTION_ORDER = ['package', 'source', 'build', 'requirements',
'test', 'app', 'about', 'extra']
REQUIREMENTS_ORDER = ['build', 'run']
class NullUndefined(jinja2.Undefined):
def __unicode__(self):
return text_type(self._undefined_name)
def __getattr__(self, name):
return text_type('{}.{}'.format(self, name))
def __getitem__(self, name):
return '{}["{}"]'.format(self, name)
def get_section(parent, name, lints):
section = parent.get(name, {})
if not isinstance(section, dict):
lints.append('The "{}" section was expected to be a dictionary, but '
'got a {}.'.format(name, type(section).__name__))
section = {}
return section
def lintify(meta, recipe_dir=None):
lints = []
major_sections = list(meta.keys())
# If the recipe_dir exists (no guarantee within this function) , we can
# find the meta.yaml within it.
meta_fname = os.path.join(recipe_dir or '', 'meta.yaml')
source_section = get_section(meta, 'source', lints)
build_section = get_section(meta, 'build', lints)
requirements_section = get_section(meta, 'requirements', lints)
about_section = get_section(meta, 'about', lints)
extra_section = get_section(meta, 'extra', lints)
# 1: Top level meta.yaml keys should have a specific order.
section_order_sorted = sorted(major_sections,
key=EXPECTED_SECTION_ORDER.index)
if major_sections != section_order_sorted:
lints.append('The top level meta keys are in an unexpected order. '
'Expecting {}.'.format(section_order_sorted))
# 2: The about section should have a home, license and summary.
for about_item in ['home', 'license', 'summary']:
# if the section doesn't exist, or is just empty, lint it.
if not about_section.get(about_item, ''):
lints.append('The {} item is expected in the about section.'
''.format(about_item))
# 3: The recipe should have some maintainers.
if not extra_section.get('recipe-maintainers', []):
lints.append('The recipe could do with some maintainers listed in '
'the `extra/recipe-maintainers` section.')
# 4: The recipe should have some tests.
if 'test' not in major_sections:
test_files = ['run_test.py', 'run_test.sh', 'run_test.bat',
'run_test.pl']
a_test_file_exists = (recipe_dir is not None and
any(os.path.exists(os.path.join(recipe_dir,
test_file))
for test_file in test_files))
if not a_test_file_exists:
lints.append('The recipe must have some tests.')
# 5: License cannot be 'unknown.'
license = about_section.get('license', '').lower()
if 'unknown' == license.strip():
lints.append('The recipe license cannot be unknown.')
# 6: Selectors should be in a tidy form.
if recipe_dir is not None and os.path.exists(meta_fname):
bad_selectors = []
# Good selectors look like ".*\s\s#\s[...]"
good_selectors_pat = re.compile(r'(.+?)\s{2,}#\s\[(.+)\](?(2).*)$')
with io.open(meta_fname, 'rt') as fh:
for selector_line in selector_lines(fh):
if not good_selectors_pat.match(selector_line):
bad_selectors.append(selector_line)
if bad_selectors:
lints.append('Selectors are suggested to take a '
'``<two spaces>#<one space>[<expression>]`` form.')
# 7: The build section should have a build number.
if build_section.get('number', None) is None:
lints.append('The recipe must have a `build/number` section.')
# 8: The build section should be before the run section in requirements.
requirements_order_sorted = sorted(requirements_section,
key=REQUIREMENTS_ORDER.index)
if list(requirements_section.keys()) != requirements_order_sorted:
lints.append('The `requirements/build` section should be defined '
'before the `requirements/run` section.')
# 9: Files downloaded should have a hash.
if ('url' in source_section and
not ({'sha1', 'sha256', 'md5'} & set(source_section.keys()))):
lints.append('When defining a source/url please add a sha256, sha1 '
'or md5 checksum (sha256 preferably).')
# 10: License should not include the word 'license'.
license = about_section.get('license', '').lower()
if 'license' in license.lower():
lints.append('The recipe `license` should not include the word '
'"License".')
# 11: There should be one empty line at the end of the file.
if recipe_dir is not None and os.path.exists(meta_fname):
with io.open(meta_fname, 'r') as f:
lines = f.read().split('\n')
# Count the number of empty lines from the end of the file
empty_lines = itertools.takewhile(lambda x: x == '', reversed(lines))
end_empty_lines_count = len(list(empty_lines))
if end_empty_lines_count != 1:
lints.append('There should be one empty line at the end of the '
'file.')
return lints
def selector_lines(lines):
# Using the same pattern defined in conda-build (metadata.py),
# we identify selectors.
sel_pat = re.compile(r'(.+?)\s*(#.*)?\[(.+)\](?(2).*)$')
for line in lines:
line = line.rstrip()
if line.lstrip().startswith('#'):
# Don't bother with comment only lines
continue
m = sel_pat.match(line)
if m:
m.group(3)
yield line
def main(recipe_dir):
recipe_dir = os.path.abspath(recipe_dir)
recipe_meta = os.path.join(recipe_dir, 'meta.yaml')
if not os.path.exists(recipe_dir):
raise IOError('Feedstock has no recipe/meta.yaml.')
env = jinja2.Environment(undefined=NullUndefined)
with io.open(recipe_meta, 'rt') as fh:
content = env.from_string(''.join(fh)).render(os=os)
meta = ruamel.yaml.load(content, ruamel.yaml.RoundTripLoader)
results = lintify(meta, recipe_dir)
return results
|
Python
| 0.000035
|
@@ -75,16 +75,75 @@
l.yaml%0A%0A
+from conda_build.metadata import allowed_license_families%0A%0A
# patch
@@ -5637,16 +5637,392 @@
file.')%0A
+%0A # 12: License family must be valid (conda-build checks for that)%0A license_family = about_section.get('license_family', '')%0A if license_family and not license_family in allowed_license_families:%0A lints.append('The recipe license_family %60%7B%7D%60 is invalid: must be one of %7B%7D.'%0A ''.format(license_family, ', '.join(allowed_license_families)))%0A%0A
retu
|
a9fee0cab6899effa865c73c38baf73e5272d87e
|
Create main.py
|
main.py
|
main.py
|
Python
| 0.000001
|
@@ -0,0 +1,263 @@
+### Command line interface for functions%0A%0Aimport freqs%0Aimport harmonize%0Aimport error%0Aimport enharmonic%0Aimport voice%0A%0A# 1. Take input from file or user%0A%0A# 2. Call desired function on input, specifying type of output (show, save to file, etc.)%0A%0A# 3. Display result%0A
|
|
370d6eb7fc4adb2f2769bdf94f56df239760ef0c
|
Create quiz2.py
|
laboratorio-f/quiz2.py
|
laboratorio-f/quiz2.py
|
Python
| 0.000001
|
@@ -0,0 +1,609 @@
+print(%22OFERTAS El Emperador%22)%0A%0Aofer1 = 0.30 %0Aofer2 = 0.20%0Aofer3 = 0.10%0A%0A%0Awhile clientes %3C5:%0A%09monto = int(input(%22Ingrese monto: %22))%0A%09clientes += 1%09%0A%09if monto %3E= 500:%0A%09%09subtotal = monto * ofer1%0A%09%09total = monto - subtotal%0A%09%09print(%22El total es %7B0%7D: %22.format(total)%0A%09%09if monto %3C 500 or monto %3E 200%0A%09%09%09subtotal = monto * ofer2%0A%09%09%09total = monto + subtotal%0A%09%09%09print(%22El total es %7B0%7D: %22.format(total)%0A%09%09if monto %3C 200: or monto %3E 100:%0A%09%09%09subtotal = monto * ofer3%0A%09%09%09total = monto + subtotal%0A%09%09%09print(%22El total es %7B0%7D: %22.format(total)%0A%09%09else%0A%09%09%09print(%22No hay descuento%22)%0A%09%09%0A%09%09%09print(%22gracias por su compra%22)%0A%09%09%09%09break%0A
|
|
c8e6fce132d1eaa9d789dd0c7bd2e5c53e4e5424
|
Add python user exception function example (#2333)
|
pulsar-functions/python-examples/user_exception.py
|
pulsar-functions/python-examples/user_exception.py
|
Python
| 0
|
@@ -0,0 +1,1036 @@
+#!/usr/bin/env python%0A#%0A# Licensed to the Apache Software Foundation (ASF) under one%0A# or more contributor license agreements. See the NOTICE file%0A# distributed with this work for additional information%0A# regarding copyright ownership. The ASF licenses this file%0A# to you under the Apache License, Version 2.0 (the%0A# %22License%22); you may not use this file except in compliance%0A# with the License. You may obtain a copy of the License at%0A#%0A# http://www.apache.org/licenses/LICENSE-2.0%0A#%0A# Unless required by applicable law or agreed to in writing,%0A# software distributed under the License is distributed on an%0A# %22AS IS%22 BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY%0A# KIND, either express or implied. See the License for the%0A# specific language governing permissions and limitations%0A# under the License.%0A#%0A%0Afrom pulsar import Function%0A%0A# Example function that throws an excpetion%0Aclass UserException(Function):%0A def __init__(self):%0A pass%0A%0A def process(self, input, context):%0A raise Exception('this will not work')
|
|
3aaee714d59650f36e3918e184905048a83d1cfc
|
Add new filesystem_stat module.
|
lib/filesystem_stat.py
|
lib/filesystem_stat.py
|
Python
| 0
|
@@ -0,0 +1,1940 @@
+import os%0Aimport stat%0Aimport snmpy%0Aimport time%0A%0Aclass filesystem_stat(snmpy.plugin):%0A def s_type(self, obj):%0A if stat.S_ISDIR(obj):%0A return 'directory'%0A if stat.S_ISCHR(obj):%0A return 'character special device'%0A if stat.S_ISBLK(obj):%0A return 'block special device'%0A if stat.S_ISREG(obj):%0A return 'regular file'%0A if stat.S_ISFIFO(obj):%0A return 'named pipe'%0A if stat.S_ISLNK(obj):%0A return 'symbolic link'%0A if stat.S_ISSOCK(obj):%0A return 'socket'%0A%0A return 'unknown'%0A%0A def s_time(self, obj):%0A return int(time.time() - obj)%0A%0A def s_pass(self, obj):%0A return obj%0A%0A def gather(self, obj):%0A try:%0A info = os.lstat(self.name)%0A for k, v in self.stat.items():%0A self.data%5B'2.%25s' %25 k%5D = v%5B2%5D(info.getattr('st_%25s' %25 v%5B0%5D, info.st_mode))%0A except:%0A for k, v in self.stat.items():%0A self.data%5B'2.%25s' %25 k%5D = v%5B1%5D%0A%0A def create(self):%0A self.stat = %7B%0A '1': ('name', self.name, self.s_pass),%0A '2': ('type', 'missing', self.s_type),%0A '3': ('atime', -1, self.s_time),%0A '4': ('mtime', -1, self.s_time),%0A '5': ('ctime', -1, self.s_time),%0A '6': ('nlink', -1, self.s_pass),%0A '7': ('size', -1, self.s_pass),%0A '8': ('ino', -1, self.s_pass),%0A '9': ('uid', -1, self.s_pass),%0A '10': ('gid', -1, self.s_pass),%0A %7D%0A%0A for k, v in self.stat.items():%0A snmp_type = 'integer' if type(v%5B1%5D) == int else 'string'%0A%0A self.data%5B'1.%25s' %25 k%5D = 'string', v%5B0%5D%0A if k == '1':%0A self.data%5B'2.%25s' %25 k%5D = snmp_type, v%5B1%5D%0A else:%0A self.data%5B'2.%25s' %25 k%5D = snmp_type, v%5B1%5D, %7B'run': self.gather%7D%0A
|
|
7ac6007e28740e0aff89925b10ae09fa6c0b63d3
|
add tests for g.current_user
|
backend/geonature/tests/test_users_login.py
|
backend/geonature/tests/test_users_login.py
|
Python
| 0.000001
|
@@ -0,0 +1,1414 @@
+import pytest%0A%0Afrom flask import g, url_for, current_app%0A%0Afrom geonature.utils.env import db%0A%0Afrom pypnusershub.db.models import User, Application, AppUser, UserApplicationRight, ProfilsForApp%0A%0Afrom . import login, temporary_transaction%0Afrom .utils import logged_user_headers%0A%0A%0A@pytest.mark.usefixtures(%22client_class%22, %22temporary_transaction%22)%0Aclass TestUsersLogin:%0A @pytest.fixture%0A def user(self, app):%0A id_app = app.config%5B'ID_APP'%5D%0A with db.session.begin_nested():%0A user = User(groupe=False, active=True, identifiant='user', password='password')%0A db.session.add(user)%0A application = Application.query.get(id_app)%0A profil = ProfilsForApp.query.filter_by(id_application=application.id_application) %5C%0A .order_by(ProfilsForApp.id_profil.desc()).first().profil%0A right = UserApplicationRight(role=user, id_profil=profil.id_profil, id_application=application.id_application)%0A db.session.add(right)%0A return user%0A%0A @pytest.fixture%0A def app_user(self, app, user):%0A return AppUser.query.filter_by(id_role=user.id_role, id_application=app.config%5B'ID_APP'%5D).one()%0A%0A%0A def test_current_user(self, app, user, app_user):%0A with app.test_request_context(headers=logged_user_headers(app_user)):%0A app.preprocess_request()%0A assert(g.current_user == user)%0A
|
|
563128f767167ed81469f13192950633874761f3
|
Simplify docstring in light of filter changes
|
flowlogs_reader/flowlogs_reader.py
|
flowlogs_reader/flowlogs_reader.py
|
# Copyright 2015 Observable Networks
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or 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.
from __future__ import print_function
from calendar import timegm
from datetime import datetime, timedelta
import boto3
ACCEPT = 'ACCEPT'
REJECT = 'REJECT'
SKIPDATA = 'SKIPDATA'
NODATA = 'NODATA'
class FlowRecord(object):
"""
Given a VPC Flow Logs event dictionary, returns a Python object whose
attributes match the field names in the event record. Integers are stored
as Python int objects; timestamps are stored as Python datetime objects.
"""
__slots__ = [
'version',
'account_id',
'interface_id',
'srcaddr',
'dstaddr',
'srcport',
'dstport',
'protocol',
'packets',
'bytes',
'start',
'end',
'action',
'log_status',
]
def __init__(self, event):
fields = event['message'].split()
self.version = int(fields[0])
self.account_id = fields[1]
self.interface_id = fields[2]
self.start = datetime.utcfromtimestamp(int(fields[10]))
self.end = datetime.utcfromtimestamp(int(fields[11]))
self.log_status = fields[13]
if self.log_status in (NODATA, SKIPDATA):
self.srcaddr = None
self.dstaddr = None
self.srcport = None
self.dstport = None
self.protocol = None
self.packets = None
self.bytes = None
self.action = None
else:
self.srcaddr = fields[3]
self.dstaddr = fields[4]
self.srcport = int(fields[5])
self.dstport = int(fields[6])
self.protocol = int(fields[7])
self.packets = int(fields[8])
self.bytes = int(fields[9])
self.action = fields[12]
def __eq__(self, other):
return all(
getattr(self, x) == getattr(other, x) for x in self.__slots__
)
def __hash__(self):
return hash(tuple(getattr(self, x) for x in self.__slots__))
def __str__(self):
ret = ['{}: {}'.format(x, getattr(self, x)) for x in self.__slots__]
return ', '.join(ret)
def to_dict(self):
return {x: getattr(self, x) for x in self.__slots__}
def to_message(self):
D_transform = {
'start': lambda dt: str(timegm(dt.utctimetuple())),
'end': lambda dt: str(timegm(dt.utctimetuple())),
}
ret = []
for attr in self.__slots__:
transform = D_transform.get(attr, lambda x: str(x) if x else '-')
ret.append(transform(getattr(self, attr)))
return ' '.join(ret)
@classmethod
def from_message(cls, message):
return cls({'message': message})
class FlowLogsReader(object):
"""
Returns an object that will yield VPC Flow Log records as Python objects.
* `log_group_name` is the name of the CloudWatch Logs group that stores
your VPC flow logs.
* `region_name` is the AWS region.
* `start_time` is a Python datetime.datetime object; only log streams that
were ingested at or after this time will be examined, and only events at
or after this time will be yielded.
* `end_time` is similar to start time. Only log streams and events after
this time will be considered.
* boto_client_kwargs - other keyword arguments to pass to boto3.client
"""
def __init__(
self,
log_group_name,
region_name='us-east-1',
start_time=None,
end_time=None,
boto_client_kwargs=None
):
boto_client_kwargs = boto_client_kwargs or {}
self.logs_client = boto3.client(
'logs', region_name=region_name, **boto_client_kwargs
)
self.log_group_name = log_group_name
# If no time filters are given use the last hour
now = datetime.utcnow()
start_time = start_time or now - timedelta(hours=1)
end_time = end_time or now
self.start_ms = timegm(start_time.utctimetuple()) * 1000
self.end_ms = timegm(end_time.utctimetuple()) * 1000
def __iter__(self):
self.iterator = self._reader()
return self
def __next__(self):
return next(self.iterator)
def next(self):
# For Python 2 compatibility
return self.__next__()
def _read_streams(self):
kwargs = {
'logGroupName': self.log_group_name,
'startTime': self.start_ms,
'endTime': self.end_ms,
'interleaved': True,
}
while True:
response = self.logs_client.filter_log_events(**kwargs)
for event in response['events']:
yield event
next_token = response.get('nextToken')
if next_token is not None:
kwargs['nextToken'] = next_token
else:
break
def _reader(self):
# Loops through each log stream and its events, yielding a parsed
# version of each event.
for event in self._read_streams():
yield FlowRecord(event)
|
Python
| 0.000001
|
@@ -3600,222 +3600,159 @@
nly
-log streams that%0A were ingested at or after this time will be examined, and only events at%0A or after this time will be yielded.%0A * %60end_time%60 is similar to start time. Only log streams and events after%0A
+the log events%0A from at or after this time will be considered.%0A * %60end_time%60 is a Python datetime.datetime object; only the log events%0A before
thi
|
205bbba27a89e6f89e26164dbf25ce9763865d36
|
add ping.py
|
ping.py
|
ping.py
|
Python
| 0.000003
|
@@ -0,0 +1,1210 @@
+#!/usr/bin/env python%0A# -*- coding:utf8 -*-%0Aimport Queue%0Aimport threading%0Aimport subprocess%0Aimport re%0Aimport sys%0A%0Alock = threading.Lock()%0Adef getip(ip):%0A a = re.match(r'(.*%5Cd+)%5C.(%5Cd+)-(%5Cd+)',ip)%0A print a.groups()%0A start = int(a.group(2))%0A end = int(a.group(3))+1%0A iplist = %5B%5D%0A for i in range(start,end):%0A iplist.append(a.group(1)+%22.%22+str(i))%0A return iplist%0A%0Adef ping(qlist):%0A while 1:%0A if qlist.empty(): %0A sys.exit() %0A ip = qlist.get()%0A ret=subprocess.call(%22ping -c 1 %25s%22 %5C%0A %25 ip,stdout=open('/dev/null','w'),%5C%0A stderr=subprocess.STDOUT,shell=True)%0A lock.acquire()%0A if ret==0:%0A print %22%25s is Alive %22 %25 ip%0A else:%0A pass%0A lock.release()%0A qlist.task_done() %0A%0Adef main():%0A queue = Queue.Queue()%0A for i in getip(sys.argv%5B1%5D):%0A queue.put(i)%0A%0A for q in range(int(sys.argv%5B2%5D)): %0A worker=threading.Thread(target=ping,args=(queue,)) %0A worker.setDaemon(True) %0A worker.start() %0A queue.join() %0A%0Aif __name__==%22__main__%22: %0A if len (sys.argv) != 3:%0A print %22usage %25s IP%E6%AE%B5(192.168.1.1-254) %E7%BA%BF%E7%A8%8B%E6%95%B0%22 %25 sys.argv%5B0%5D%0A else:%0A main()%0A
|
|
1266fd79369634e2a0399e857107487ae589ea20
|
add vpc vpc check script
|
plugins/aws/check_vpc_vpn.py
|
plugins/aws/check_vpc_vpn.py
|
Python
| 0
|
@@ -0,0 +1,1472 @@
+#!/usr/bin/python%0A%0Aimport argparse%0Aimport boto.ec2%0Afrom boto.vpc import VPCConnection%0Aimport sys%0A%0A%0Adef main():%0A try:%0A conn = boto.vpc.VPCConnection(aws_access_key_id=args.aws_access_key_id, aws_secret_access_key=args.aws_secret_access_key, region=boto.ec2.get_region(args.region))%0A except:%0A print %22UNKNOWN: Unable to connect to reqion %25s%22 %25 args.region%0A sys.exit(3)%0A%0A errors = %5B%5D%0A for vpn_connection in conn.get_all_vpn_connections():%0A for tunnel in vpn_connection.tunnels:%0A if tunnel.status != 'UP':%0A errors.append(%22%5Bgateway: %25s connection: %25s tunnel: %25s status: %25s%5D%22 %25 (vpn_connection.vpn_gateway_id, vpn_connection.id, tunnel.outside_ip_address, tunnel.status))%0A%0A if len(errors) %3E 1:%0A print 'CRITICAL: ' + ' '.join(errors)%0A sys.exit(2)%0A elif len(errors) %3E 0:%0A print 'WARN: ' + ' '.join(errors)%0A sys.exit(1)%0A else:%0A print 'OK'%0A sys.exit(0)%0A%0Aif __name__ == %22__main__%22:%0A parser = argparse.ArgumentParser(description='Check status of all existing AWS VPC VPN Tunnels')%0A%0A parser.add_argument('-a', '--aws-access-key-id', required=True, dest='aws_access_key_id', help='AWS Access Key')%0A parser.add_argument('-s', '--aws-secret-access-key', required=True, dest='aws_secret_access_key', help='AWS Secret Access Key')%0A parser.add_argument('-r', '--region', required=True, dest='region', help='AWS Region')%0A%0A args = parser.parse_args()%0A%0A main()
|
|
2d6d5c0a07a751a66c3f0495e3a3a67e4296dd77
|
Create subreddits_with_zero_gildings.py
|
subreddits_with_zero_gildings.py
|
subreddits_with_zero_gildings.py
|
Python
| 0.00012
|
@@ -0,0 +1,965 @@
+# Written by Jonathan Saewitz, released March 26th, 2016 for Statisti.ca%0A# Released under the MIT License (https://opensource.org/licenses/MIT)%0A%0Aimport json, plotly.plotly as plotly, plotly.graph_objs as go%0A%0A########################%0A# Config #%0A########################%0A%0Agraph_title=%22Largest Subreddits Who Have Given 0 Gold%22%0A%0Ax_axis_title=%22Subreddit%22%0Ay_axis_title=%22Subreddit size (subscribers)%22%0A%0Afilename=%22zero_gildings.json%22%0A########################%0A# End Config #%0A########################%0A%0A%0Asubreddits=%5B%5D%0Asubscribers=%5B%5D%0Af=open(filename, 'r')%0Afor i in range(10):%0A%09cur_line=json.loads(f.next())%0A%09subreddits.append(cur_line%5B'url'%5D)%0A%09subscribers.append(int(cur_line%5B'subscribers'%5D))%0Af.close()%0A%0Atrace = go.Bar(%0A x = subreddits,%0A y = subscribers%0A)%0A%0Alayout=go.Layout(%0A%09title=graph_title,%0A%09xaxis=dict(%0A%09%09title=x_axis_title,%0A%09),%0A%09yaxis=dict(%0A%09%09title=y_axis_title,%0A%09)%0A)%0A%0Adata=%5Btrace%5D%0Afig = go.Figure(data=data, layout=layout)%0Aplotly.plot(fig)%0A
|
|
29e18ed63177dbe8306a22e3c0583342f4591464
|
Exit routine for a controlled exit from ample
|
python/ample_exit.py
|
python/ample_exit.py
|
Python
| 0
|
@@ -0,0 +1,1449 @@
+'''%0ACreated on Mar 18, 2015%0A%0A@author: jmht%0A'''%0A%0Aimport logging%0Aimport sys%0Aimport traceback%0A%0A# external imports%0Atry: import pyrvapi%0Aexcept: pyrvapi=None%0A%0Adef exit(msg):%0A logger = logging.getLogger()%0A %0A #header=%22**** AMPLE ERROR ****%5Cn%5Cn%22%0A header=%22*%22*70+%22%5Cn%22%0A header+=%22*%22*20 + %22 %22*10 + %22AMPLE ERROR%22 + %22 %22*10 +%22*%22*19 + %22%5Cn%22 %0A header+=%22*%22*70+%22%5Cn%5Cn%22%0A %0A footer=%22%5Cn%5Cn%22 + %22*%22*70+%22%5Cn%5Cn%22%0A %0A # Bit dirty - get the name of the debug log file%0A debug_log=None%0A for d in logger.handlers:%0A n='baseFilename'%0A if hasattr(d,n) and d.level==logging.DEBUG:%0A debug_log=getattr(d, n)%0A if debug_log:%0A footer+=%22More information may be found in the debug log file: %7B0%7D%5Cn%22.format(debug_log) %0A %0A footer += %22%5CnIf you believe that this is an error with AMPLE, please email: ccp4@stfc.ac.uk%5Cn%22%0A footer += %22providing as much information as you can about how you ran the program.%5Cn%22%0A if debug_log: %0A footer += %22%5CnPlease include the debug logfile with your email: %7B0%7D%5Cn%22.format(debug_log) %0A %0A # String it all together%0A msg=header + msg + footer%0A %0A logger.critical(msg)%0A %0A # Get traceback of where we failed for the log file%0A logger.debug(%22AMPLE EXITING AT...%22)%0A logger.debug(%22%22.join(traceback.format_list(traceback.extract_stack())))%0A %0A # Make sure the error widget is updated%0A if pyrvapi: pyrvapi.rvapi_flush()%0A %0A sys.exit(1)%0A %0A %0A
|
|
fa3450a44621fab4a9a2f2ed1599d08f66860f70
|
Integrate densities to check normalization
|
integrate_density.py
|
integrate_density.py
|
Python
| 0
|
@@ -0,0 +1,1483 @@
+import argparse%0Aimport numpy as np%0Aimport h5py%0A%0Aif __name__ == '__main__':%0A%0A parser = argparse.ArgumentParser(description='Integrate probability ' +%0A 'densities to verify that they are ' +%0A 'normalized')%0A parser.add_argument('data_filenames', metavar='files', nargs='+',%0A help='List of hdf5 files containing densities')%0A args = parser.parse_args()%0A%0A data_files = %5Bh5py.File(data_filename, 'r') for data_filename in%0A args.data_filenames%5D%0A epsilons = %5Bdata_file%5B'densities'%5D.attrs%5B'epsilon'%5D for data_file in%0A data_files%5D%0A Density_meshes = %5Bdata_file%5B'densities'%5D%5B:%5D for data_file in data_files%5D%0A Phi_meshes = %5Bdata_file%5B'Phi'%5D%5B:%5D for data_file in data_files%5D%0A Theta_meshes = %5B-2*np.arccos(data_file%5B'R'%5D%5B:%5D/2) + np.pi for data_file in%0A data_files%5D%0A%0A Total_probs = %5B%5D%0A%0A for Density_mesh, Phi_mesh, Theta_mesh in zip(Density_meshes, Phi_meshes,%0A Theta_meshes):%0A # Scale Density_mesh so that the integration can be thought of as on a%0A # rectangle rather than a hemisphere%0A Scaled_density_mesh = Density_mesh*np.sin(Theta_mesh)%0A Total_probs.append(np.trapz(np.trapz(Scaled_density_mesh, Phi_mesh),%0A Theta_mesh%5B:,0%5D))%0A%0A for epsilon, prob in zip(epsilons, Total_probs):%0A print(epsilon, prob)%0A
|
|
72a573c24d5234003b9eeb9e0cc487d174908a2e
|
Add a Trie for storage of data string tokens.
|
typeahead_search/trie.py
|
typeahead_search/trie.py
|
Python
| 0
|
@@ -0,0 +1,1615 @@
+%22%22%22A Trie (prefix tree) class for use in typeahead search.%0A%0AEvery node in the TypeaheadSearchTrie is another TypeaheadSearchTrie instance.%0A%22%22%22%0A%0Afrom weakref import WeakSet%0A%0A%0Aclass TypeaheadSearchTrie(object):%0A def __init__(self):%0A # The children of this node. Because ordered traversals are not%0A # important, these are stored in a dictionary.%0A self.children = %7B%7D%0A%0A # Data entries associated with the word stored in the path to%0A # this node. Stored in a WeakSet so that entries disappear%0A # automatically when data entries are deleted.%0A self.entries = WeakSet()%0A%0A def add(self, word, entry):%0A %22%22%22Adds the given data entry to the given Trie word.%0A The word is created in the Trie if it doesn't already exist.%0A %22%22%22%0A if word:%0A self.children.setdefault(%0A word%5B0%5D,%0A TypeaheadSearchTrie()%0A ).add(word%5B1:%5D, entry)%0A%0A else:%0A self.entries.add(entry)%0A%0A def search(self, word):%0A %22%22%22Return a set of all data entries represented by prefix %60word%60.%0A Returns an empty set if this prefix is not in the Trie.%0A %22%22%22%0A if word:%0A try:%0A return self.children%5Bword%5B0%5D%5D.search(word%5B1:%5D)%0A except KeyError:%0A return set()%0A%0A else:%0A return self.gather_entries()%0A%0A def gather_entries(self):%0A %22%22%22Gather all data entries stored in this node and its children.%22%22%22%0A return set(self.entries).update(%0A child.gather_entries() for child in self.children.itervalues()%0A )%0A
|
|
060028a383279de41cfc7bcd2bb8322746b3ade6
|
set default config
|
pyethereum/slogging.py
|
pyethereum/slogging.py
|
import structlog
import logging
import sys
"""
See test_logging.py for examples
Basic usage:
log = get_logger('eth.vm.op')
log.trace('event name', some=data)
Use Namespaces for components and subprotocols
net
net.handshake
net.frames
p2p.peer
p2p.peermanager
eth.vm
eth.vm.op
eth.vm.mem
eth.chain
eth.chain.new_block
"""
class KeyValueRenderer(structlog.processors.KeyValueRenderer):
"""
Render `event_dict` as a list of ``Key=repr(Value)`` pairs.
Prefix with event
"""
def __call__(self, _, __, event_dict):
msg = event_dict.pop('event', '')
kvs = ' '.join(k + '=' + repr(v) for k, v in self._ordered_items(event_dict))
return "%s\t%s" % (msg, kvs)
######## TRACE ##########
class BoundLoggerTrace(structlog.stdlib.BoundLogger):
"adds trace"
def trace(self, event=None, **kw):
"""
Process event and call ``Logger.trace()`` with the result.
"""
return self._proxy_to_logger('trace', event, **kw)
def is_active(self, level_name='trace'):
"""
this is not faster, than logging.
can be used set flag in vm context
"""
# any listeners?
if self._processors and isinstance(self._processors[0], LogListeners) \
and self._processors[0].listeners:
return True
# log level filter
return self._logger.isEnabledFor(structlog.stdlib._nameToLevel[level_name])
structlog.stdlib.TRACE = TRACE = 5
structlog.stdlib._nameToLevel['trace'] = TRACE
logging.addLevelName(TRACE, "TRACE")
def _trace(self, message, *args, **kws):
# Yes, logger takes its '*args' as 'args'.
if self.isEnabledFor(TRACE):
self._log(TRACE, message, args, **kws)
logging.Logger.trace = _trace
logging.TRACE = TRACE
######### listeners ###############
class LogListeners(object):
"""
allow to register listeners
"""
def __init__(self):
self.listeners = []
def __call__(self, logger, name, event_dict):
#raise Exception
e = dict(event_dict)
for l in self.listeners:
l(e)
return event_dict
log_listeners = LogListeners()
class LogRecorder(object):
"""
temporarily records all logs, w/o level filtering
use only once!
"""
max_capacity = 10 * 1000 # check we are not forgotten or abused
def __init__(self):
self._records = []
log_listeners.listeners.append(self.add_log)
def add_log(self, msg):
self._records.append(msg)
assert len(self._records) < self.max_capacity
def pop_records(self):
# can only be called once
r = self._records[:]
self._records = None
log_listeners.listeners.remove(self.add_log)
return r
### configure #####################
DEFAULT_LOGLEVEL = logging.INFO
JSON_FORMAT = '%(message)s'
PRINT_FORMAT = '%(levelname)s:%(name)s\t%(message)s'
def set_level(name, level):
assert not isinstance(level, int)
logging.getLogger(name).setLevel(getattr(logging, level.upper()))
def configure_loglevels(config_string):
"""
config_string = ':debug,p2p:info,vm.op:trace'
"""
assert ':' in config_string
for name_levels in config_string.split(','):
name, level = name_levels.split(':')
set_level(name, level)
def setup_stdlib_logging(level, fmt):
logging.root = logging.RootLogger(level)
logging.Logger.root = logging.root
logging.Logger.manager = logging.Manager(logging.Logger.root)
stream = sys.stderr
hdlr = logging.StreamHandler(stream)
fmt = logging.Formatter(fmt, None)
hdlr.setFormatter(fmt)
logging.root.addHandler(hdlr)
def configure(config_string='', log_json=False):
# configure structlog
processors = [
log_listeners, # before level filtering
structlog.stdlib.filter_by_level,
structlog.processors.StackInfoRenderer()
]
if log_json:
processors.append(structlog.processors.JSONRenderer(sort_keys=True))
else:
processors.extend([
structlog.processors.ExceptionPrettyPrinter(file=None),
KeyValueRenderer(sort_keys=True, key_order=None)
])
structlog.configure(
processors=processors,
context_class=dict,
logger_factory=structlog.stdlib.LoggerFactory(),
wrapper_class=BoundLoggerTrace,
# later calls on configure() dont have any effect on already cached loggers
cache_logger_on_first_use=True,
)
# configure standard logging
if log_json:
format = JSON_FORMAT
else:
format = PRINT_FORMAT
setup_stdlib_logging(DEFAULT_LOGLEVEL, format)
if config_string:
configure_loglevels(config_string)
def get_configuration():
"""
get a configuration (snapshot) that can be used to call configure
snapshot = get_configuration()
configure(**snapshot)
"""
name_levels = [('', logging.getLevelName(logging.getLogger().level))]
for name, logger in logging.Logger.manager.loggerDict.items():
name_levels.append((name, logging.getLevelName(logger.level)))
config_string = ','.join('%s:%s' % x for x in name_levels)
struct_root = get_logger().bind()
log_json = bool([p for p in struct_root._processors if
isinstance(p, structlog.processors.JSONRenderer)])
return dict(config_string=config_string, log_json=log_json)
# helpers
known_loggers = set() # know to structlog (i.e. maybe not yet initialized w/ logging)
def get_logger_names():
# logging.Logger.manager.loggerDict.keys() # used ones
return sorted(known_loggers) # initialized at module load get_logger
def get_logger(name=None):
known_loggers.add(name)
return structlog.get_logger(name)
# quick debug
def DEBUG(msg, **kargs):
"temporary logger during development that is always on"
log = structlog.get_logger('DEBUG')
log.critical('-' * 20)
log.critical(msg, **kargs)
|
Python
| 0.000003
|
@@ -4721,24 +4721,117 @@
ig_string)%0A%0A
+configure_logging = configure # for unambigious imports%0A### setup default config%0Aconfigure()%0A
%0Adef get_con
|
e5dd1722911e580caca136fda9b81bb53221c65c
|
add table widget
|
ubuntui/widgets/table.py
|
ubuntui/widgets/table.py
|
Python
| 0
|
@@ -0,0 +1,1638 @@
+# Copyright 2014, 2015 Canonical, Ltd.%0A#%0A# This program is free software: you can redistribute it and/or modify%0A# it under the terms of the GNU Affero General Public License as%0A# published by the Free Software Foundation, either version 3 of the%0A# License, or (at your option) any later version.%0A#%0A# This program is distributed in the hope that it will be useful,%0A# but WITHOUT ANY WARRANTY; without even the implied warranty of%0A# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the%0A# GNU Affero General Public License for more details.%0A#%0A# You should have received a copy of the GNU Affero General Public License%0A# along with this program. If not, see %3Chttp://www.gnu.org/licenses/%3E.%0A%0Afrom __future__ import unicode_literals%0A%0Afrom urwid import (Columns, Pile, Divider)%0A%0A%0Aclass Cols:%0A%0A def __init__(self):%0A self.columns = %5B%5D%0A%0A def add(self, widget, width=None):%0A %22%22%22 Add a widget to a columns list%0A%0A Arguments:%0A widget: widget%0A width: width of column%0A %22%22%22%0A if width is None:%0A self.columns.append(widget)%0A else:%0A self.columns.append(('fixed', width, widget))%0A%0A def render(self):%0A %22%22%22 Renders columns with proper spacing%0A %22%22%22%0A return Columns(self.columns)%0A%0A%0Aclass Table:%0A def __init__(self):%0A self.rows = Pile(%5B%5D)%0A%0A def append(self, item):%0A %22%22%22 Appends widget to Pile%0A %22%22%22%0A self.rows.append((item, self.rows.options()))%0A self.rows.append((%0A Divider(%22%5CN%7BBOX DRAWINGS LIGHT HORIZONTAL%7D%22),%0A self.rows.options()))%0A%0A def render(self):%0A return self.rows%0A
|
|
51fc613214f20738270f37280fb465aea84ed065
|
test the wsgi logging
|
test/test_slimta_logging_wsgi.py
|
test/test_slimta_logging_wsgi.py
|
Python
| 0
|
@@ -0,0 +1,736 @@
+%0Aimport unittest%0A%0Afrom testfixtures import log_capture%0A%0Afrom slimta.logging import getWsgiLogger%0A%0A%0Aclass TestWsgiLogger(unittest.TestCase):%0A%0A def setUp(self):%0A self.log = getWsgiLogger('test')%0A self.environ = %7B'var': 'val'%7D%0A%0A @log_capture()%0A def test_request(self, l):%0A self.log.request(self.environ)%0A l.check(('test', 'DEBUG', 'http:%7B0%7D:request environ=%7B%7B%5C'var%5C': %5C'val%5C'%7D%7D'.format(id(self.environ))))%0A%0A @log_capture()%0A def test_response(self, l):%0A self.log.response(self.environ, '200 OK', %5B('Header', 'Value')%5D)%0A l.check(('test', 'DEBUG', 'http:%7B0%7D:response headers=%5B(%5C'Header%5C', %5C'Value%5C')%5D status=%5C'200 OK%5C''.format(id(self.environ))))%0A%0A%0A# vim:et:fdm=marker:sts=4:sw=4:ts=4%0A
|
|
8af510b18a3f0f8298f9a992bffdccc9aee2c8c2
|
add sandbox file
|
src/gmv/sandbox.py
|
src/gmv/sandbox.py
|
Python
| 0.000001
|
@@ -0,0 +1,235 @@
+'''%0ACreated on Jan 30, 2012%0A%0A@author: guillaume.aubert@gmail.com%0A'''%0A%0Afrom cmdline_utils import CmdLineParser%0A%0Aif __name__ == '__main__':%0A %0A global_parser = CmdLineParser()%0A global_parser.disable_interspersed_args()%0A %0A
|
|
65f149c33c1ec6e7d7262092def4b175aa52fe54
|
Create BinTreeRightSideView_001.py
|
leetcode/199-Binary-Tree-Right-Side-View/BinTreeRightSideView_001.py
|
leetcode/199-Binary-Tree-Right-Side-View/BinTreeRightSideView_001.py
|
Python
| 0
|
@@ -0,0 +1,550 @@
+# Definition for a binary tree node%0A# class TreeNode:%0A# def __init__(self, x):%0A# self.val = x%0A# self.left = None%0A# self.right = None%0A%0Aclass Solution:%0A # @param root, a tree node%0A # @return a list of integers%0A def rightSideView(self, root):%0A %0A if root == None: %0A return %5B%5D%0A %0A lv = self.rightSideView(root.left)%0A rv = self.rightSideView(root.right)%0A %0A if len(lv) %3E len(rv): %0A rv%5Blen(rv):%5D = lv%5Blen(rv):%5D %0A%0A return %5Broot.val%5D.extend(rv)%0A
|
|
01c74cfea946eac098a0e144380314cd4676cf2f
|
Split lowpass filtering into another script.
|
analysis/04-lowpass.py
|
analysis/04-lowpass.py
|
Python
| 0
|
@@ -0,0 +1,1470 @@
+#!/usr/bin/env python%0A%0Afrom __future__ import division%0A%0Aimport climate%0Aimport lmj.cubes%0Aimport pandas as pd%0Aimport scipy.signal%0A%0Alogging = climate.get_logger('lowpass')%0A%0Adef lowpass(df, freq=10., order=4):%0A '''Filter marker data using a butterworth low-pass filter.%0A%0A This method alters the data in %60df%60 in-place.%0A%0A Parameters%0A ----------%0A freq : float, optional%0A Use a butterworth filter with this cutoff frequency. Defaults to%0A 10Hz.%0A order : int, optional%0A Order of the butterworth filter. Defaults to 4.%0A '''%0A nyquist = 1 / (2 * pd.Series(df.index).diff().mean())%0A assert 0 %3C freq %3C nyquist%0A passes = 2 # filtfilt makes two passes over the data.%0A correct = (2 ** (1 / passes) - 1) ** 0.25%0A b, a = scipy.signal.butter(order / passes, (freq / correct) / nyquist)%0A for c in df.columns:%0A if c.startswith('marker') and c%5B-1%5D in 'xyz':%0A df.loc%5B:, c%5D = scipy.signal.filtfilt(b, a, df%5Bc%5D)%0A%0A%0A@climate.annotate(%0A root='load data files from this directory tree',%0A output='save smoothed data files to this directory tree',%0A pattern=('process only trials matching this pattern', 'option'),%0A freq=('lowpass filter at N Hz', 'option', None, float),%0A)%0Adef main(root, output, pattern='*', freq=None):%0A for t in lmj.cubes.Experiment(root).trials_matching(pattern):%0A lowpass(t.df, freq)%0A t.save(t.root.replace(root, output))%0A%0A%0Aif __name__ == '__main__':%0A climate.call(main)%0A
|
|
6a6b9eff5e5d0d7c4a1a969b15a2a4583cf79855
|
add game-of-throne-ii
|
algorithms/strings/game-of-throne-ii/game-of-throne-ii.py
|
algorithms/strings/game-of-throne-ii/game-of-throne-ii.py
|
Python
| 0.999371
|
@@ -0,0 +1,717 @@
+from collections import Counter%0A%0AMOD = 10**9 + 7%0A%0Adef factMod(x):%0A ret = 1%0A for i in range(1, x):%0A ret = (ret * (i + 1)) %25 MOD;%0A return ret%0A%0Adef powMod(x, y):%0A if y == 0:%0A return 1%0A if y == 1:%0A return x %25 MOD%0A temp = powMod(x, y / 2)%0A if y %25 2 == 0:%0A return (temp * temp) %25 MOD%0A else:%0A return (x * temp * temp) %25 MOD%0A%0Aif __name__ == '__main__':%0A word = raw_input()%0A counter = Counter(word)%0A denominator = 1%0A numerator = 0%0A for i in counter:%0A numerator += counter%5Bi%5D / 2%0A denominator = (denominator * factMod(counter%5Bi%5D / 2)) %25 MOD%0A answer = (factMod(numerator) * powMod(denominator, MOD - 2)) %25 MOD%0A print answer%0A %0A %0A
|
|
6a9b6f0227b37d9c4da424c25d20a2b7e9397a9f
|
Make `publication_date` column not nullable.
|
alembic/versions/3800f47ba771_publication_date_not_nullable.py
|
alembic/versions/3800f47ba771_publication_date_not_nullable.py
|
Python
| 0.000001
|
@@ -0,0 +1,450 @@
+%22%22%22Make the %60publication_date%60 column required.%0A%0ARevision ID: 3800f47ba771%0ARevises: 17c1af634026%0ACreate Date: 2012-12-13 21:14:19.363112%0A%0A%22%22%22%0A%0A# revision identifiers, used by Alembic.%0Arevision = '3800f47ba771'%0Adown_revision = '17c1af634026'%0A%0Afrom alembic import op%0Aimport sqlalchemy as sa%0A%0A%0Adef upgrade():%0A op.alter_column('tip', 'publication_date', nullable=False)%0A%0A%0Adef downgrade():%0A op.alter_column('tip', 'publication_date', nullable=True)%0A
|
|
57e2776a59214318d335f2fa0e2cc1854c33d488
|
Add lc0532_k_diff_pairs_in_an_array.py
|
lc0532_k_diff_pairs_in_an_array.py
|
lc0532_k_diff_pairs_in_an_array.py
|
Python
| 0.000015
|
@@ -0,0 +1,1239 @@
+%22%22%22Leetcode 532. K-diff Pairs in an Array%0AEasy%0A%0AURL: https://leetcode.com/problems/k-diff-pairs-in-an-array/%0A%0AGiven an array of integers and an integer k, you need to find the number %0Aof unique k-diff pairs in the array. Here a k-diff pair is defined as an%0Ainteger pair (i, j), where i and j are both numbers in the array and%0Atheir absolute difference is k.%0A%0AExample 1:%0AInput: %5B3, 1, 4, 1, 5%5D, k = 2%0AOutput: 2%0AExplanation: There are two 2-diff pairs in the array, (1, 3) and (3, 5).%0AAlthough we have two 1s in the input, we should only return the number%0Aof unique pairs.%0A%0AExample 2:%0AInput:%5B1, 2, 3, 4, 5%5D, k = 1%0AOutput: 4%0AExplanation: There are four 1-diff pairs in the array, (1, 2), (2, 3),%0A(3, 4) and (4, 5).%0A%0AExample 3:%0AInput: %5B1, 3, 1, 5, 4%5D, k = 0%0AOutput: 1%0AExplanation: There is one 0-diff pair in the array, (1, 1).%0A%0ANote:%0A- The pairs (i, j) and (j, i) count as the same pair.%0A- The length of the array won't exceed 10,000.%0A- All the integers in the given input belong to the range: %5B-1e7, 1e7%5D.%0A%22%22%22%0A%0Aclass Solution(object):%0A def findPairs(self, nums, k):%0A %22%22%22%0A :type nums: List%5Bint%5D%0A :type k: int%0A :rtype: int%0A %22%22%22%0A pass%0A%0A%0Adef main():%0A pass%0A%0A%0Aif __name__ == '__main__':%0A main()%0A%0A
|
|
a66ce55c2abcb434168aadb195fd00b8df6f4fd1
|
add scoreboard game test
|
tests/test_scoreboardGame.py
|
tests/test_scoreboardGame.py
|
Python
| 0.000002
|
@@ -0,0 +1,1143 @@
+from unittest import TestCase%0Afrom datetime import datetime%0A%0Afrom nba_data.data.scoreboard_game import ScoreboardGame%0Afrom nba_data.data.season import Season%0Afrom nba_data.data.team import Team%0Afrom nba_data.data.matchup import Matchup%0A%0A%0Aclass TestScoreboardGame(TestCase):%0A def test_instantiation(self):%0A game_id_value = %221234%22%0A season_value = Season.season_2016%0A start_time_value = datetime.now()%0A matchup_value = Matchup(home_team=Team.atlanta_hawks, away_team=Team.boston_celtics)%0A self.assertIsNotNone(ScoreboardGame(game_id=game_id_value, season=season_value, start_time=start_time_value,%0A matchup=matchup_value))%0A self.assertRaises(AssertionError, ScoreboardGame, 1234, season_value, start_time_value, matchup_value)%0A self.assertRaises(AssertionError, ScoreboardGame, game_id_value, 1234, start_time_value, matchup_value)%0A self.assertRaises(AssertionError, ScoreboardGame, game_id_value, season_value, 1234, matchup_value)%0A self.assertRaises(AssertionError, ScoreboardGame, game_id_value, season_value, start_time_value, 1234)%0A
|
|
6b1be6883ead01cc226226499644adb7e99542f8
|
Add functionality to load and test a saved model
|
Experiments/evaluate_model.py
|
Experiments/evaluate_model.py
|
Python
| 0
|
@@ -0,0 +1,2550 @@
+# import os%0Aimport sys%0Aimport tensorflow as tf%0A# sys.path.append(os.path.abspath(os.path.dirname(__file__) + '/' + '../..'))%0A%0Afrom Models.low_level_sharing_four_hidden import LowLevelSharingModel%0Afrom utils.data_utils.labels import Labels%0Afrom utils.data_utils.data_handler import fetch_data%0A%0A%0Aclass EvaluateModel(object):%0A def __init__(self, task_ids):%0A self.x_test = None%0A self.y_test = %7B%7D%0A self.input_dimension = 0%0A self.output_dimensions = %7B%7D%0A self.task_ids = task_ids%0A self.model = None%0A self.sess = None%0A%0A def load_model(self, model_file, model_class):%0A %22%22%22%0A Loads the model from the given checkpoint file.%0A%0A :param model_file: The checkpoint file from which the model should be loaded.%0A :param model_class: The :class:%60Model%60 class or any of its child classes.%0A %22%22%22%0A self.sess = tf.Session()%0A self.model = model_class(self.task_ids, self.input_dimension, self.output_dimensions)%0A self.model.create_model()%0A saver = tf.train.Saver()%0A saver.restore(self.sess, model_file)%0A sys.stderr.write(%22Model %22 + model_file + %22 loaded.%5Cn%22)%0A%0A def load_data(self):%0A %22%22%22%0A Loads the test dataset.%0A %22%22%22%0A _, _, self.x_test, _, _, self.y_test = fetch_data(self.task_ids)%0A self.input_dimension = self.x_test.shape%5B1%5D%0A self.train_samples = self.x_test.shape%5B0%5D%0A self.output_dimensions = %7Btask_id: self.y_test%5Btask_id%5D.shape%5B1%5D for task_id in self.task_ids%7D%0A%0A def evaluate_model(self):%0A %22%22%22%0A Returns a dictionary of errors indexed by task identifiers where each element denotes the error for that%0A task on the test set.%0A%0A :return dictionary of test errors%0A %22%22%22%0A feed_dict = dict()%0A feed_dict%5Bself.model.get_layer('input')%5D = self.x_test%0A for id_ in self.task_ids:%0A feed_dict%5Bself.model.get_layer(id_ + '-ground-truth')%5D = self.y_test%5Bid_%5D%0A errors = %7B%7D%0A for task_id in self.task_ids:%0A errors%5Btask_id%5D = self.model.get_layer(task_id + '-loss').eval(session=self.sess, feed_dict=feed_dict)%0A return errors%0A%0A%0Aif __name__ == '__main__':%0A model_file = sys.argv%5B1%5D%0A model_class = LowLevelSharingModel%0A task_ids = %5BLabels.hotness.value, Labels.duration.value, Labels.year.value%5D%0A%0A evaluation = EvaluateModel(task_ids)%0A evaluation.load_data()%0A evaluation.load_model(model_file, model_class)%0A errors = evaluation.evaluate_model()%0A sys.stderr.write(str(errors) + %22%5Cn%22)%0A
|
|
d883cfac71c9ec39abcd75e79b9bec0f53e7890d
|
Initialize transpositionHacker
|
books/CrackingCodesWithPython/Chapter12/transpositionHacker.py
|
books/CrackingCodesWithPython/Chapter12/transpositionHacker.py
|
Python
| 0.000672
|
@@ -0,0 +1,1967 @@
+# Transposition Cipher Hacker%0A# https://www.nostarch.com/crackingcodes/ (BSD Licensed)%0A%0Aimport pyperclip, detectEnglish, transpositionDecrypt%0A%0Adef main():%0A # You might want to copy & paste this text from the source code at%0A # https://www.nostarch.com/crackingcodes/:%0A myMessage = %22%22%22AaKoosoeDe5 b5sn ma reno ora'lhlrrceey e enlh na indeit n uhoretrm au ieu v er Ne2 gmanw,forwnlbsya apor tE.no euarisfatt e mealefedhsppmgAnlnoe(c -or)alat r lw o eb nglom,Ain one dtes ilhetcdba. t tg eturmudg,tfl1e1 v nitiaicynhrCsaemie-sp ncgHt nie cetrgmnoa yc r,ieaa toesa- e a0m82e1w shcnth ekh gaecnpeutaaieetgn iodhso d ro hAe snrsfcegrt NCsLc b17m8aEheideikfr aBercaeu thllnrshicwsg etriebruaisss d iorr.%22%22%22%0A%0A hackedMessage = hackTransposition(myMessage)%0A%0A if hackedMessage == None:%0A print('Failed to hack encryption.')%0A else:%0A print('Copying hacked message to clipboard:')%0A print('hackedMessage')%0A pyperclip.copy(hackedMessage)%0A%0A%0Adef hackTransposition(message):%0A print('Hacking...')%0A%0A # Python programs can be stopped at any time by pressing%0A # Ctrl-C (on Windows) or Ctrl-D (on macOS and Linux):%0A print('(Press Ctl-C (on Windows) or Ctrl-D (on macOS and Linux) to quit at any time.)')%0A%0A # Brute-force by looping through every possible key:%0A for key in range(1, len(message)):%0A print('Trying key #%25s...' %25 (key))%0A%0A decryptedText = transpositionDecrypt.decryptMessage(key, message)%0A%0A if detectEnglish.isEnglish(decryptedText):%0A # Ask user if this is the correct decryption:%0A print()%0A print('Possible encryption hack:')%0A print('Key %25s: %25s' %25 (key, decryptedText%5B:100%5D))%0A print()%0A print('Enter D if done, anything else to continue hacking:')%0A response = input('%3E ')%0A%0A if response.strip().upper().startswith('D'):%0A return decryptedText%0A%0A return None%0A%0Aif __name__ == '__main__':%0A main()
|
|
75805397dd62cfa00eb9a9d253259ea9c79f426b
|
Test Issue #605
|
spacy/tests/regression/test_issue605.py
|
spacy/tests/regression/test_issue605.py
|
Python
| 0
|
@@ -0,0 +1,577 @@
+from ...attrs import LOWER, ORTH%0Afrom ...tokens import Doc%0Afrom ...vocab import Vocab%0Afrom ...matcher import Matcher%0A%0A%0Adef return_false(doc, ent_id, label, start, end):%0A return False%0A%0A%0Adef test_matcher_accept():%0A doc = Doc(Vocab(), words=%5Bu'The', u'golf', u'club', u'is', u'broken'%5D)%0A%0A golf_pattern = %5B %0A %7B ORTH: %22golf%22%7D,%0A %7B ORTH: %22club%22%7D%0A %5D%0A matcher = Matcher(doc.vocab)%0A%0A matcher.add_entity('Sport_Equipment', acceptor=return_false)%0A matcher.add_pattern(%22Sport_Equipment%22, golf_pattern)%0A match = matcher(doc)%0A%0A assert match == %5B%5D%0A
|
|
38dd3604918b2e0d7770e855f775db9ff6720de8
|
Add initial DrugBank client
|
indra/databases/drugbank_client.py
|
indra/databases/drugbank_client.py
|
Python
| 0
|
@@ -0,0 +1,1481 @@
+import os%0Afrom indra.util import read_unicode_csv%0A%0A%0Amappings_file = os.path.join(os.path.dirname(os.path.abspath(__file__)),%0A os.pardir, 'resources', 'drugbank_mappings.tsv')%0A%0A%0Adef get_chebi_id(drugbank_id):%0A return drugbank_chebi.get(drugbank_id)%0A%0A%0Adef get_chembl_id(drugbank_id):%0A return drugbank_chembl.get(drugbank_id)%0A%0A%0Adef get_drugbank_from_chebi(chebi_id):%0A return chebi_drugbank.get(chebi_id)%0A%0A%0Adef get_drugbank_from_chembl(chembl_id):%0A return chembl_drugbank.get(chembl_id)%0A%0A%0Adef load_mappings():%0A drugbank_chebi = %7B%7D%0A chebi_drugbank = %7B%7D%0A drugbank_chembl = %7B%7D%0A chembl_drugbank = %7B%7D%0A for row in read_unicode_csv(mappings_file, delimiter='%5Ct', skiprows=1):%0A drugbank_id, db_ns, db_id, source = row%0A if db_ns == 'CHEBI':%0A chebi_id = 'CHEBI:%25s' %25 db_id%0A if drugbank_id in drugbank_chebi or chebi_id in chebi_drugbank:%0A import ipdb; ipdb.set_trace()%0A drugbank_chebi%5Bdrugbank_id%5D = chebi_id%0A chebi_drugbank%5Bchebi_id%5D = drugbank_id%0A elif db_ns == 'CHEMBL':%0A if drugbank_id in drugbank_chembl or db_id in chembl_drugbank:%0A import ipdb; ipdb.set_trace()%0A drugbank_chembl%5Bdrugbank_id%5D = db_id%0A chembl_drugbank%5Bdb_id%5D = drugbank_id%0A return drugbank_chebi, chebi_drugbank, drugbank_chembl, chembl_drugbank%0A%0A%0Adrugbank_chebi, chebi_drugbank, drugbank_chembl, chembl_drugbank = %5C%0A load_mappings()%0A
|
|
84fcbb34005c5bfa19d33e583ca48583b04baeb4
|
Create mp3tag.py
|
plugins/mp3tag.py
|
plugins/mp3tag.py
|
Python
| 0.000001
|
@@ -0,0 +1,2 @@
+.%0A
|
|
407e0b6596539a5f8fcac099c11f1fabc956ea26
|
add plugin to show available package updates
|
plugins/pacman.py
|
plugins/pacman.py
|
Python
| 0
|
@@ -0,0 +1,685 @@
+%22%22%22%0A@author Brian Bove https://github.com/bmbove%0A%22%22%22%0Aimport re%0Aimport subprocess%0Afrom .base import PluginBase%0A %0Aclass PacmanPlugin(PluginBase):%0A %0A def configure(self):%0A defaults = %7B%0A 'format': 'pacman %7Bupdates%7D'%0A %7D%0A return defaults%0A%0A def get_update_count(self):%0A lines = subprocess.check_output(%5B%22checkupdates%22%5D)%0A lines = lines.decode('ascii').strip()%0A return %7B'updates': len(lines.split(%22%5Cn%22))%7D%0A %0A def update(self):%0A res = self.get_update_count()%0A if type(res) == dict:%0A locals().update(res)%0A self.set_text(self.config%5B'format'%5D %25 locals())%0A else:%0A self.set_text(res)%0A
|
|
3501462ebafa15b19ef436231a5a0d9e3b5d430a
|
Add first implementation of virtual ontology
|
indra/ontology/virtual_ontology.py
|
indra/ontology/virtual_ontology.py
|
Python
| 0.000001
|
@@ -0,0 +1,1205 @@
+import requests%0Afrom .ontology_graph import IndraOntology%0A%0A%0Aclass VirtualOntology(IndraOntology):%0A def __init__(self, url, ontology='bio'):%0A super().__init__()%0A self.url = url%0A self.ontology = ontology%0A%0A def initialize(self):%0A self._initialized = True%0A%0A def _rel(self, ns, id, rel_types, direction):%0A url = self.url + '/%25s_rel' %25 direction%0A res = requests.get(url,%0A json=%7B'ns': ns,%0A 'id': id,%0A 'rel_types': rel_types,%0A 'ontology': self.ontology%7D)%0A return res.json()%0A%0A def child_rel(self, ns, id, rel_types):%0A return self._rel(ns, id, rel_types, 'child')%0A%0A def parent_rel(self, ns, id, rel_types):%0A return self._rel(ns, id, rel_types, 'parent')%0A%0A def get_node_property(self, ns, id, property):%0A url = self.url + '/get_node_property'%0A res = requests.get(url,%0A json=%7B'ns': ns,%0A 'id': id,%0A 'property': property,%0A 'ontology': self.ontology%7D)%0A return res.json()%0A%0A
|
|
1139ca1d7c9a4badeb0c3addb23bf0f80866beb5
|
Task5
|
project1/task5.py
|
project1/task5.py
|
Python
| 0.999999
|
@@ -0,0 +1,827 @@
+from sklearn.linear_model import RidgeCV, LassoCV%0Aimport utils%0Aimport pandas as pd%0A%0Adata = pd.read_csv(%22datasets/housing_data.csv%22)%0A%0AX = data.ix%5B:, %5B0, 1, 2, 3, 4, 6, 7, 8, 9, 10, 11, 12%5D%5D.values%0A%0AY = data.ix%5B:, 13%5D.values%0A%0A# Ridge regression%0A%0AtuningAlpha = %5B1,0.1,0.01,0.001%5D%0A%0Aridge = RidgeCV(normalize=True,alphas=tuningAlpha, cv=10)%0Aridge.fit(X, Y)%0Aprediction = ridge.predict(X)%0A%0Aprint %22Best Alpha value for Ridge Regression : %22 + str(ridge.alpha_)%0Aprint 'Best RMSE for corresponding Alpha =', utils.rmse(Y, prediction)%0A%0A%0A# Lasso Regression%0A%0AtuningAlpha = %5B1,0.1,0.01,0.001%5D%0Alasso = LassoCV(normalize=True, alphas=tuningAlpha, cv=10)%0Alasso.fit(X,Y)%0Aprediction = lasso.predict(X)%0A%0Aprint %22Best Alpha value for Lasso Regularization : %22 + str(lasso.alpha_)%0Aprint 'Best RMSE for corresponding Alpha =', utils.rmse(Y, prediction)%0A
|
|
2154c816cdb3ff0f4a98980a2d590888f6819c81
|
add signals
|
rest_arch/signals.py
|
rest_arch/signals.py
|
Python
| 0.000564
|
@@ -0,0 +1,172 @@
+# -*- coding: utf-8 -*-%0A%0Afrom blinker import signal%0A%0Abefore_api_called = signal('before_api_called')%0Aafter_api_called = signal('after_api_called')%0A%0A# TODO add more signals%0A
|
|
00c5dbbdeee045d9e474ce7b6094cd49df528b05
|
add container tests
|
tests/container_tests.py
|
tests/container_tests.py
|
Python
| 0
|
@@ -0,0 +1,798 @@
+import pytest%0A%0Afrom watir_snake.container import Container%0A%0A%0Aclass TestContainerExtractSelector(object):%0A def test_converts_2_arg_selector_into_a_dict(self):%0A assert Container()._extract_selector('how', 'what') == %7B'how': 'what'%7D%0A%0A def test_returns_the_kwargs_given(self):%0A assert Container()._extract_selector(how='what') == %7B'how': 'what'%7D%0A%0A def test_returns_an_empty_dict_if_given_no_args(self):%0A assert Container()._extract_selector() == %7B%7D%0A%0A def test_raises_correct_exception_if_given_1_arg(self):%0A with pytest.raises(ValueError):%0A Container()._extract_selector('how')%0A%0A def test_raises_correct_exception_if_given_over_2_args(self):%0A with pytest.raises(ValueError):%0A Container()._extract_selector('how', 'what', 'value')%0A
|
|
1aebdce5d2fb233927930175fe60e205bca50962
|
Fix test :)
|
tests/test_comicnames.py
|
tests/test_comicnames.py
|
# -*- coding: utf-8 -*-
# Copyright (C) 2012-2014 Bastian Kleineidam
# Copyright (C) 2016 Tobias Gruetzmacher
from dosagelib import scraper, util
class TestComicNames(object):
def test_names(self):
for scraperclass in scraper.get_scraperclasses():
name = scraperclass.getName()
assert name.count('/') <= 1
if '/' in name:
comicname = name.split('/')[1]
else:
comicname = name
assert util.asciify(comicname) == comicname
|
Python
| 0
|
@@ -17,16 +17,80 @@
f-8 -*-%0A
+# Copyright (C) 2004-2005 Tristan Seligmann and Jonathan Jacobs%0A
# Copyri
@@ -142,16 +142,21 @@
ght (C)
+2015-
2016 Tob
@@ -173,16 +173,93 @@
macher%0A%0A
+from __future__ import absolute_import, division, print_function%0A%0Aimport re%0A%0A
from dos
@@ -283,14 +283,8 @@
aper
-, util
%0A%0A%0Ac
@@ -628,21 +628,36 @@
ert
-util.asciify(
+re.sub(%22%5B%5E0-9a-zA-Z_%5D%22, %22%22,
comi
|
8b55c8a524dd853be2c72951f3656db1a991d0bc
|
test for Experiment class
|
tests/test_experiment.py
|
tests/test_experiment.py
|
Python
| 0.000002
|
@@ -0,0 +1,804 @@
+#!/usr/bin/env python%0A# %E2%88%92*%E2%88%92 coding: UTF%E2%88%928 %E2%88%92*%E2%88%92%0Afrom __future__ import division%0A%0Afrom odelab.solver import SingleStepSolver%0Afrom odelab.system import System%0Afrom odelab.scheme import ExplicitEuler%0Afrom odelab.experiment import Experiment%0A%0Aimport numpy as np%0Aimport nose.tools as nt%0A%0Adef f(t,u):%0A%09return -u%0A%0Adef test_experiment():%0A%09params = %7B%0A%09%09'family': 'tmpbank',%0A%09%09'name': 'tmpexp',%0A%09%09'system': System,%0A%09%09'system_params': %7B'f': f%7D,%0A%09%09'solver': SingleStepSolver,%0A%09%09'scheme': ExplicitEuler,%0A%09%09'scheme_params': %7B%7D,%0A%09%09'initialize': %7B%0A%09%09%09'u0' : np.array(%5B1.%5D),%0A%09%09%09'time': 1.,%0A%09%09%09'h': .1,%0A%09%09%09%7D,%0A%09%09%7D%0A%09exp = Experiment(params)%0A%09exp.run()%0A%09s = Experiment.load('tmpbank', 'tmpexp')%0A%09nt.assert_true(isinstance(s, SingleStepSolver))%0A%09nt.assert_true(isinstance(s.scheme, ExplicitEuler))%0A%09nt.assert_equal(len(s), 11)%0A%0A
|
|
cb788a5c82a4be58bb6b2d6d6608a17f914a42b4
|
Add basic tests for layer initialization.
|
test/graph_test.py
|
test/graph_test.py
|
import theanets
import numpy as np
import util
class TestNetwork(util.MNIST):
def _build(self, *hiddens):
return theanets.Regressor((self.DIGIT_SIZE, ) + hiddens)
def test_predict(self):
net = self._build(15, 13)
y = net.predict(self.images)
assert y.shape == (self.NUM_DIGITS, 13)
def test_feed_forward(self):
net = self._build(15, 13)
hs = net.feed_forward(self.images)
assert len(hs) == 7, 'got {}'.format(list(hs.keys()))
assert hs['in:out'].shape == (self.NUM_DIGITS, self.DIGIT_SIZE)
assert hs['hid1:out'].shape == (self.NUM_DIGITS, 15)
assert hs['out:out'].shape == (self.NUM_DIGITS, 13)
def test_decode_from_multiple_layers(self):
net = self._build(13, 14, dict(
size=15, inputs={'hid2:out': 14, 'hid1:out': 13}))
hs = net.feed_forward(self.images)
assert len(hs) == 9, 'got {}'.format(list(hs.keys()))
assert hs['in:out'].shape == (self.NUM_DIGITS, self.DIGIT_SIZE)
assert hs['hid1:out'].shape == (self.NUM_DIGITS, 13)
assert hs['hid2:out'].shape == (self.NUM_DIGITS, 14)
assert hs['out:out'].shape == (self.NUM_DIGITS, 15)
def test_updates(self):
assert not self._build(13).updates()
class TestMonitors(util.MNIST):
def setUp(self):
super(TestMonitors, self).setUp()
self.net = theanets.Regressor((self.DIGIT_SIZE, 15, 14, 13))
def assert_monitors(self, monitors, expected, sort=False):
mon = [k for k, v in self.net.monitors(monitors=monitors)]
if sort:
mon = sorted(mon)
assert mon == expected, 'expected {}, got {}'.format(expected, mon)
def test_dict(self):
self.assert_monitors({'hid1:out': 1}, ['err', 'hid1:out<1'])
def test_list(self):
self.assert_monitors([('hid1:out', 1)], ['err', 'hid1:out<1'])
def test_list_values(self):
self.assert_monitors({'hid1:out': [2, 1]},
['err', 'hid1:out<2', 'hid1:out<1'])
def test_dict_values(self):
self.assert_monitors({'hid1:out': dict(a=lambda e: e+1,
b=lambda e: e+2)},
['err', 'hid1:out:a', 'hid1:out:b'],
sort=True)
def test_not_found(self):
self.assert_monitors({'hid10:out': 1}, ['err'])
def test_param(self):
self.assert_monitors({'hid1.w': 1}, ['err', 'hid1.w<1'])
def test_wildcard(self):
self.assert_monitors({'*.w': 1}, ['err', 'hid1.w<1', 'hid2.w<1', 'out.w<1'])
self.assert_monitors({'hid?.w': 1}, ['err', 'hid1.w<1', 'hid2.w<1'])
|
Python
| 0
|
@@ -1271,16 +1271,802 @@
ates()%0A%0A
+ def test_layer_ints(self):%0A m = theanets.Regressor((1, 2, 3))%0A assert len(m.layers) == 3%0A%0A def test_layer_tuples(self):%0A m = theanets.Regressor((1, (2, 'relu'), 3))%0A assert len(m.layers) == 3%0A assert m.layers%5B1%5D.activation == 'relu'%0A%0A def test_layer_dicts(self):%0A m = theanets.Regressor((1, dict(size=2, activation='relu', form='rnn'), 3))%0A assert len(m.layers) == 3%0A assert m.layers%5B1%5D.activation == 'relu'%0A assert isinstance(m.layers%5B1%5D, theanets.layers.recurrent.RNN)%0A%0A def test_layer_tied(self):%0A m = theanets.Regressor((1, 2, (1, 'tied')))%0A assert len(m.layers) == 3%0A assert isinstance(m.layers%5B2%5D, theanets.layers.feedforward.Tied)%0A assert m.layers%5B2%5D.partner is m.layers%5B1%5D%0A%0A
%0Aclass T
|
5e52a7551b20f74d0b08393e8da89463bb6b5366
|
add new tests for busco
|
test/test_busco.py
|
test/test_busco.py
|
Python
| 0
|
@@ -0,0 +1,500 @@
+from sequana.busco import BuscoConfig, BuscoDownload%0Afrom sequana import sequana_data%0Afrom easydev import TempFile%0A%0Adef test_busco_config():%0A bc = BuscoConfig(%22species%22, outpath=%22test%22, sample_name=%22test%22,%0A conda_bin_path=%22test%22, tmp_path=%22test%22, hmmsearch_bin_path=%22itest%22,%0A Rscript_bin_path=None)%0A with TempFile as fh:%0A bc.save_config_file(fh.name)%0A%0Adef test_busco_download():%0A bd = BuscoDownload()%0A bd.filenames = %5B'proteobacteria_odb9'%5D%0A bd.download()%0A
|
|
a4ad209ba361ed07574de37598bcedd3ea499a0a
|
add test file for testing patches
|
test/test_patch.py
|
test/test_patch.py
|
Python
| 0
|
@@ -0,0 +1,1766 @@
+# The positive cases of patch are extensively tested in test_diff.py because a%0A# sensible way to validate a diff of two objects is to check that when you apply%0A# the patch to the first object you get the second.%0A# Here the testing mainly focuses on patch operations which would fail and some%0A# of the obscure positive cases. For example you should be able to apply a patch%0A# to an object that isn't one of the ones involved in the diff under certain%0A# conditions.%0Aimport unittest%0Afrom collections import namedtuple, OrderedDict%0Afrom copy import deepcopy%0Afrom differ import diff, patch%0Afrom differ.patch import (%0A patch_sequence,%0A patch_named_tuple,%0A patch_mapping,%0A patch_ordered_mapping,%0A patch_set)%0A%0A%0Aclass PatchSequenceTests(unittest.TestCase):%0A def patch_has_no_side_effects(self):%0A a = %5B1, 2, 3%5D%0A copy_of_a = deepcopy(a)%0A b = %5B3, 2, 1%5D%0A d = diff(a, b)%0A self.assertEqual(patch(a, d), b)%0A self.assertEqual(a, copy_of_a)%0A%0A%0Aclass PatchNamedTupleTests(unittest.TestCase):%0A def patch_has_no_side_effects(self):%0A ThreeDPoint = namedtuple('ThreeDPoint', ('x', 'y', 'z'))%0A a = ThreeDPoint(1, 2, 3)%0A copy_of_a = deepcopy(a)%0A b = ThreeDPoint(2, 3, 4)%0A d = diff(a, b)%0A self.assertEqual(patch(a, d), b)%0A self.assertEqual(a, copy_of_a)%0A self.assertTrue(False)%0A%0A%0Aclass PatchMappingTests(unittest.TestCase):%0A def patch_has_no_side_effects(self):%0A pass%0A%0A%0Aclass PatchOrderedMappingTests(unittest.TestCase):%0A def patch_has_no_side_effects(self):%0A pass%0A%0A%0Aclass PatchSetTests(unittest.TestCase):%0A def patch_has_no_side_effects(self):%0A pass%0A%0A%0Aclass PatchTests(unittest.TestCase):%0A def patch_has_no_side_effects(self):%0A pass%0A
|
|
3e8dad480392cc654bca0b0fdf3ac27f4f4be3c6
|
Add speed test script
|
test/test_speed.py
|
test/test_speed.py
|
Python
| 0.000001
|
@@ -0,0 +1,1406 @@
+import numpy%0Anumpy.random.seed(0)%0Aimport time%0Aimport cProfile%0Aimport pstats%0A%0Aimport pandas%0A%0Afrom mhcflurry import Class1AffinityPredictor%0Afrom mhcflurry.common import random_peptides%0A%0ANUM = 100000%0A%0ADOWNLOADED_PREDICTOR = Class1AffinityPredictor.load()%0A%0A%0Adef test_speed(profile=False):%0A starts = %7B%7D%0A timings = %7B%7D%0A profilers = %7B%7D%0A%0A def start(name):%0A starts%5Bname%5D = time.time()%0A if profile:%0A profilers%5Bname%5D = cProfile.Profile()%0A profilers%5Bname%5D.enable()%0A%0A def end(name):%0A timings%5Bname%5D = time.time() - starts%5Bname%5D%0A if profile:%0A profilers%5Bname%5D.disable()%0A%0A start(%22first%22)%0A DOWNLOADED_PREDICTOR.predict(%5B%22SIINFEKL%22%5D, allele=%22HLA-A*02:01%22)%0A end(%22first%22)%0A%0A peptides = random_peptides(NUM)%0A start(%22pred_%25d%22 %25 NUM)%0A DOWNLOADED_PREDICTOR.predict(peptides, allele=%22HLA-A*02:01%22)%0A end(%22pred_%25d%22 %25 NUM)%0A%0A print(%22SPEED BENCHMARK%22)%0A print(%22Results:%5Cn%25s%22 %25 str(pandas.Series(timings)))%0A%0A return dict(%0A (key, pstats.Stats(value)) for (key, value) in profilers.items())%0A%0A%0Aif __name__ == '__main__':%0A # If run directly from python, do profiling and leave the user in a shell%0A # to explore results.%0A%0A result = test_speed(profile=True)%0A result%5B%22pred_%25d%22 %25 NUM%5D.sort_stats(%22cumtime%22).reverse_order().print_stats()%0A%0A # Leave in ipython%0A locals().update(result)%0A import ipdb ; ipdb.set_trace()%0A
|
|
3283c9ac640112ab7a26ec3f82e051394ca72ecf
|
Add catapult presubmit with list of trybots.
|
PRESUBMIT.py
|
PRESUBMIT.py
|
Python
| 0
|
@@ -0,0 +1,631 @@
+# Copyright (c) 2015 The Chromium Authors. All rights reserved.%0A# Use of this source code is governed by a BSD-style license that can be%0A# found in the LICENSE file.%0A%0A%22%22%22Top-level presubmit script for catapult.%0A%0ASee https://www.chromium.org/developers/how-tos/depottools/presubmit-scripts%0Afor more details about the presubmit API built into depot_tools.%0A%22%22%22%0A%0A%0Adef GetPreferredTryMasters(project, change):%0A return %7B%0A 'tryserver.client.catapult': %7B%0A 'Catapult Linux Tryserver': set(%5B'defaulttests'%5D),%0A 'Catapult Mac Tryserver': set(%5B'defaulttests'%5D),%0A 'Catapult Windows Tryserver': set(%5B'defaulttests'%5D),%0A %7D%0A %7D
|
|
05a5599fd0cf08cf33c8a90673e8c71b4c1d6c36
|
Test implementation of convex hull
|
slides/ComputationalGeometry/convex-hull.py
|
slides/ComputationalGeometry/convex-hull.py
|
Python
| 0
|
@@ -0,0 +1,1802 @@
+import math%0A%0Aclass Vector:%0A def __init__(self, x, y):%0A self.x = x%0A self.y = y%0A %0A # add theta, so we can sort by it later%0A self.theta = math.atan2(y, x)%0A%0A def add(self, other):%0A return Vector(self.x + other.x, self.y + other.y)%0A %0A def negate(self):%0A return Vector(-self.x, -self.y)%0A%0A def subtract(self, other):%0A return self.add(other.negate())%0A%0A def dot(self, other):%0A return self.x * other.x + self.y * other.y%0A%0A def magnitude(self):%0A return (self.dot(self)) ** 0.5%0A%0A def cross(self, other):%0A return self.x * other.y - self.y * other.x%0A%0A def __repr__(self):%0A # update format, so we can just print the vectors%0A return %22(%7B0%7D,%7B1%7D)%22.format(self.x, self.y)%0A%0Adef parse_point(raw_string):%0A x,y = map(int, raw_string.split(','))%0A return Vector(x, y)%0A%0Adef turn_direction(p1, p2, p3):%0A d1 = p2.subtract(p1)%0A d2 = p3.subtract(p1)%0A%0A return d1.cross(d2)%0A%0Adef convex_hull(points):%0A # first get the point with min y value%0A %0A%0A # first, sort the points by their angle theta%0A sorted_points = sorted(points, key=lambda P : P.theta)%0A%0A N = len(points)%0A%0A hull = sorted_points%0A%0A for i in range(0, N + 1):%0A current_point = sorted_points%5Bi %25 N%5D%0A previous_point = sorted_points%5B(i + N - 1) %25 N%5D%0A next_point = sorted_points%5B(i + 1) %25 N%5D%0A%0A print(current_point, turn_direction(previous_point, current_point, next_point))%0A if turn_direction(previous_point, current_point, next_point) %3E= 0:%0A hull.append(current_point)%0A%0A return hull%0A%0Apoint_count = int(input().strip())%0Apoints = %5B%5D%0Afor i in range(point_count):%0A points.append(parse_point(input()))%0A%0Ahull = convex_hull(points)%0A%0A# Resort the hull, so the we get the %0A%0Aprint(hull)%0A
|
|
d30db10d1038301fe7b659e23d96a256f77bec6b
|
remove debug clause
|
beetsplug/mpdupdate.py
|
beetsplug/mpdupdate.py
|
# This file is part of beets.
# Copyright 2013, Adrian Sampson.
#
# 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,
# 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 following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
"""Updates an MPD index whenever the library is changed.
Put something like the following in your config.yaml to configure:
mpd:
host: localhost
port: 6600
password: seekrit
"""
from __future__ import print_function
from beets.plugins import BeetsPlugin
import os
import socket
from beets import config
# Global variable so that mpdupdate can detect database changes and run only
# once before beets exits.
database_changed = False
# No need to introduce a dependency on an MPD library for such a
# simple use case. Here's a simple socket abstraction to make things
# easier.
class BufferedSocket(object):
"""Socket abstraction that allows reading by line."""
def __init__(self, host, port, sep='\n'):
if host[0] in ['/', '~']:
self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self.sock.connect(os.path.expanduser(host))
else:
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.connect((host, port))
self.buf = ''
self.sep = sep
def readline(self):
while self.sep not in self.buf:
data = self.sock.recv(1024)
if not data:
break
self.buf += data
if '\n' in self.buf:
res, self.buf = self.buf.split(self.sep, 1)
return res + self.sep
else:
return ''
def send(self, data):
self.sock.send(data)
def close(self):
self.sock.close()
def update_mpd(host='localhost', port=6600, password=None):
"""Sends the "update" command to the MPD server indicated,
possibly authenticating with a password first.
"""
print('Updating MPD database...')
s = BufferedSocket(host, port)
resp = s.readline()
if 'OK MPD' not in resp:
print('MPD connection failed:', repr(resp))
return
if password:
s.send('password "%s"\n' % password)
resp = s.readline()
if 'OK' not in resp:
print('Authentication failed:', repr(resp))
s.send('close\n')
s.close()
return
s.send('update\n')
resp = s.readline()
if 'updating_db' not in resp:
print('Update failed:', repr(resp))
s.send('close\n')
s.close()
print('... updated.')
class MPDUpdatePlugin(BeetsPlugin):
def __init__(self):
super(MPDUpdatePlugin, self).__init__()
config['mpd'].add({
'host': u'localhost',
'port': 6600,
'password': u'',
})
# For backwards compatibility, use any values from the
# plugin-specific "mpdupdate" section.
for key in config['mpd'].keys():
if self.config[key].exists():
config['mpd'][key] = self.config[key].get()
@MPDUpdatePlugin.listen('database_change')
def handle_change(lib=None):
global database_changed
database_changed = True
@MPDUpdatePlugin.listen('cli_exit')
def update(lib=None):
if database_changed or True:
update_mpd(
config['mpd']['host'].get(unicode),
config['mpd']['port'].get(int),
config['mpd']['password'].get(unicode),
)
|
Python
| 0
|
@@ -3692,16 +3692,8 @@
nged
- or True
:%0A
|
df264f2ec00dc84a0a7ca637c568a3273f55fd03
|
remove unnecessary else
|
homeassistant/components/camera/__init__.py
|
homeassistant/components/camera/__init__.py
|
# pylint: disable=too-many-lines
"""
homeassistant.components.camera
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Component to interface with various cameras.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/camera/
"""
import requests
import logging
import time
import re
from homeassistant.helpers.entity import Entity
from homeassistant.const import (
ATTR_ENTITY_PICTURE,
HTTP_NOT_FOUND,
ATTR_ENTITY_ID,
)
from homeassistant.helpers.entity_component import EntityComponent
DOMAIN = 'camera'
DEPENDENCIES = ['http']
GROUP_NAME_ALL_CAMERAS = 'all_cameras'
SCAN_INTERVAL = 30
ENTITY_ID_FORMAT = DOMAIN + '.{}'
SWITCH_ACTION_RECORD = 'record'
SWITCH_ACTION_SNAPSHOT = 'snapshot'
SERVICE_CAMERA = 'camera_service'
STATE_RECORDING = 'recording'
DEFAULT_RECORDING_SECONDS = 30
# Maps discovered services to their platforms
DISCOVERY_PLATFORMS = {}
FILE_DATETIME_FORMAT = '%Y-%m-%d_%H-%M-%S-%f'
DIR_DATETIME_FORMAT = '%Y-%m-%d_%H-%M-%S'
REC_DIR_PREFIX = 'recording-'
REC_IMG_PREFIX = 'recording_image-'
STATE_STREAMING = 'streaming'
STATE_IDLE = 'idle'
CAMERA_PROXY_URL = '/api/camera_proxy_stream/{0}'
CAMERA_STILL_URL = '/api/camera_proxy/{0}'
ENTITY_IMAGE_URL = '/api/camera_proxy/{0}?time={1}'
MULTIPART_BOUNDARY = '--jpegboundary'
MJPEG_START_HEADER = 'Content-type: {0}\r\n\r\n'
# pylint: disable=too-many-branches
def setup(hass, config):
""" Track states and offer events for sensors. """
component = EntityComponent(
logging.getLogger(__name__), DOMAIN, hass, SCAN_INTERVAL,
DISCOVERY_PLATFORMS)
component.setup(config)
# -------------------------------------------------------------------------
# CAMERA COMPONENT ENDPOINTS
# -------------------------------------------------------------------------
# The following defines the endpoints for serving images from the camera
# via the HA http server. This is means that you can access images from
# your camera outside of your LAN without the need for port forwards etc.
# Because the authentication header can't be added in image requests these
# endpoints are secured with session based security.
# pylint: disable=unused-argument
def _proxy_camera_image(handler, path_match, data):
""" Proxies the camera image via the HA server. """
entity_id = path_match.group(ATTR_ENTITY_ID)
camera = None
if entity_id in component.entities.keys():
camera = component.entities[entity_id]
if camera:
response = camera.camera_image()
if response is not None:
handler.wfile.write(response)
else:
handler.send_response(HTTP_NOT_FOUND)
else:
handler.send_response(HTTP_NOT_FOUND)
hass.http.register_path(
'GET',
re.compile(r'/api/camera_proxy/(?P<entity_id>[a-zA-Z\._0-9]+)'),
_proxy_camera_image)
# pylint: disable=unused-argument
def _proxy_camera_mjpeg_stream(handler, path_match, data):
""" Proxies the camera image as an mjpeg stream via the HA server.
This function takes still images from the IP camera and turns them
into an MJPEG stream. This means that HA can return a live video
stream even with only a still image URL available.
"""
entity_id = path_match.group(ATTR_ENTITY_ID)
camera = None
if entity_id in component.entities.keys():
camera = component.entities[entity_id]
if not camera:
handler.send_response(HTTP_NOT_FOUND)
handler.end_headers()
return
try:
camera.is_streaming = True
camera.update_ha_state()
handler.request.sendall(bytes('HTTP/1.1 200 OK\r\n', 'utf-8'))
handler.request.sendall(bytes(
'Content-type: multipart/x-mixed-replace; \
boundary=--jpgboundary\r\n\r\n', 'utf-8'))
handler.request.sendall(bytes('--jpgboundary\r\n', 'utf-8'))
# MJPEG_START_HEADER.format()
while True:
img_bytes = camera.camera_image()
if img_bytes is None:
continue
else:
headers_str = '\r\n'.join((
'Content-length: {}'.format(len(img_bytes)),
'Content-type: image/jpeg',
)) + '\r\n\r\n'
handler.request.sendall(
bytes(headers_str, 'utf-8') +
img_bytes +
bytes('\r\n', 'utf-8'))
handler.request.sendall(
bytes('--jpgboundary\r\n', 'utf-8'))
except (requests.RequestException, IOError):
camera.is_streaming = False
camera.update_ha_state()
camera.is_streaming = False
hass.http.register_path(
'GET',
re.compile(
r'/api/camera_proxy_stream/(?P<entity_id>[a-zA-Z\._0-9]+)'),
_proxy_camera_mjpeg_stream)
return True
class Camera(Entity):
""" The base class for camera components """
def __init__(self):
self.is_streaming = False
@property
# pylint: disable=no-self-use
def is_recording(self):
""" Returns true if the device is recording """
return False
@property
# pylint: disable=no-self-use
def brand(self):
""" Should return a string of the camera brand """
return None
@property
# pylint: disable=no-self-use
def model(self):
""" Returns string of camera model """
return None
def camera_image(self):
""" Return bytes of camera image """
raise NotImplementedError()
@property
def state(self):
""" Returns the state of the entity. """
if self.is_recording:
return STATE_RECORDING
elif self.is_streaming:
return STATE_STREAMING
else:
return STATE_IDLE
@property
def state_attributes(self):
""" Returns optional state attributes. """
attr = {
ATTR_ENTITY_PICTURE: ENTITY_IMAGE_URL.format(
self.entity_id, time.time()),
}
if self.model:
attr['model_name'] = self.model
if self.brand:
attr['brand'] = self.brand
return attr
|
Python
| 0.000008
|
@@ -4255,34 +4255,8 @@
nue%0A
- else:%0A
@@ -4295,20 +4295,16 @@
.join((%0A
-
@@ -4372,36 +4372,32 @@
-
-
'Content-type: i
@@ -4424,20 +4424,16 @@
-
)) + '%5Cr
@@ -4449,36 +4449,32 @@
-
-
handler.request.
@@ -4474,36 +4474,32 @@
equest.sendall(%0A
-
@@ -4544,36 +4544,32 @@
-
-
img_bytes +%0A
@@ -4564,20 +4564,16 @@
bytes +%0A
-
@@ -4617,36 +4617,32 @@
-
handler.request.
@@ -4642,36 +4642,32 @@
equest.sendall(%0A
-
|
e0597427d93f2260dfce35cfdd3e2714037fb0fb
|
Implement cheb_dif for getting 1D chebyshev grids and differentiation matrices.
|
src/spatial_discretizations/FourierChebyshevSpatialDiscretization.py
|
src/spatial_discretizations/FourierChebyshevSpatialDiscretization.py
|
Python
| 0
|
@@ -0,0 +1,1592 @@
+import numpy as np%0Afrom numpy.fft import fft, ifft, fftshift, fft2, ifft2%0Afrom scipy.linalg import toeplitz%0A%0Aclass FourierChebyshevSpatialDiscretization:%0A def __init__(self, config):%0A self.length_x = config%5B'length_x'%5D%0A self.length_y = config%5B'length_y'%5D%0A self.num_points_x = config%5B'num_points_x'%5D%0A self.num_points_y = config%5B'num_points_y'%5D%0A%0A # self.__build_grid__()%0A # self.__build_wavenumbers__()%0A # self.__build_filter__()%0A%0A def cheb_dif(self, N, M):%0A I = np.eye(N)%0A%0A n1 = np.floor(N/2)%0A n2 = np.ceil(N/2)%0A%0A k = np.array(%5Bnp.arange(0, N)%5D).T%0A th = k*np.pi/(N-1)%0A%0A # Compute Chebyshev points.%0A vec = np.arange(N-1, 1-N-1, -2)%0A x = np.sin(np.pi*vec/(2*(N-1)))%0A%0A T = np.tile(th/2, (1, N)) # Like repmat(th/2, 1, N) for 2nd order tensors.%0A Tt = T.T%0A%0A DX = 2*np.sin(Tt+T)*np.sin(Tt-T)%0A DX = np.vstack(%5BDX%5B0:n1, :%5D, -np.flipud(np.fliplr(DX%5B0:n2, :%5D))%5D)%0A%0A for i in range(0,N):%0A DX%5Bi,i%5D = 1.0%0A%0A C = toeplitz((-1.0)**k)%0A C%5B0,:%5D = C%5B0,:%5D*2.0%0A C%5BN-1,:%5D = C%5BN-1,:%5D*2.0%0A C%5B:,0%5D = C%5B:,0%5D / 2.0%0A C%5B:,N-1%5D = C%5B:,N-1%5D / 2.0%0A%0A Z = 1.0 / DX%0A for i in range(0,N):%0A Z%5Bi,i%5D = 0.0%0A%0A D = np.eye(N)%0A DM = np.zeros(%5BN, N, M%5D)%0A%0A for ell in range(1,M+1):%0A D = ell*Z*(C*np.tile(np.array(%5Bnp.diag(D)%5D).T,(1,N)) - D)%0A diag = -np.sum(D,1)%0A for i in range(0,N):%0A D%5Bi,i%5D = diag%5Bi%5D%0A%0A DM%5B:,:,ell-1%5D = D%0A%0A return (x,DM)
|
|
23bd2cedbeeef22715fbd65229f881e7230507d8
|
Create decorator.py
|
notebook2/decorator.py
|
notebook2/decorator.py
|
Python
| 0.000001
|
@@ -0,0 +1,159 @@
+def decor(func):%0A%09def wrap():%0A%09%09print('===')%0A%09%09func()%0A%09%09print('===')%0A%09return wrap%0A%0Adef print_text():%0A%09print('Text')%0A%0Adecorated = decor(print_text)%0Adecorated()%0A
|
|
42c9ce432f1e5a328fe35eef64d0667a01eeeb19
|
allow it to have a name and a type
|
python/qidoc/template_project.py
|
python/qidoc/template_project.py
|
class TemplateProject(object):
def __init__(self, doc_worktree, worktree_project):
self.src = worktree_project.src
self.path = worktree_project.path
self.doc_worktree = doc_worktree
##
# Add self.doxfile_in, self.sphinx_conf_in, etc.
def __repr__(self):
return "<TemplateProject in %s>" % self.src
|
Python
| 0.000002
|
@@ -76,24 +76,90 @@
e_project):%0A
+ self.doc_type = %22template%22%0A self.name = %22template%22%0A
self
|
3f38f149cf357549006ed97364eb886287d0d2be
|
Add support for discovering k8s api info from service account
|
kubespawner/utils.py
|
kubespawner/utils.py
|
"""
Misc. general utility functions, not tied to Kubespawner directly
"""
import os
import yaml
from tornado.httpclient import HTTPRequest
def request_maker(path='~/.kube/config'):
"""
Return a function that creates Kubernetes API aware HTTPRequest objects
Reads a .kube/config file from the given path, and constructs a function
that can make HTTPRequest objects with all the authentication stuff
filled in to the kubernetes context set as current-context in that .kube/config
file.
TODO: Pick up info from service accounts + env variables too
"""
with open(os.path.expanduser(path)) as f:
config = yaml.safe_load(f)
current_context = config['current-context']
context = [c for c in config['contexts'] if c['name'] == current_context][0]['context']
cluster = [c for c in config['clusters'] if c['name'] == context['cluster']][0]['cluster']
if 'user' in context: # Since user accounts aren't strictly required
user = [u for u in config['users'] if u['name'] == context['user']][0]['user']
else:
user = {}
def make_request(url, **kwargs):
"""
Make & return a HTTPRequest object suited to making requests to a Kubernetes cluster
The following changes are made to the passed in arguments
* url
No hostname / protocol should be provided, only path (and query strings, if any).
The hostname / protocol / port will be automatically provided.
* client_key / client_cert:
These will be automatically set if required
* ca_certs
This will also be automatically set if required
"""
kwargs.update({
'url': cluster['server'] + url,
'ca_certs': cluster.get('certificate-authority', None),
'client_key': user.get('client-key', None),
'client_cert': user.get('client-certificate', None)
})
return HTTPRequest(**kwargs)
return make_request
|
Python
| 0
|
@@ -157,115 +157,2080 @@
ker(
-path='~/.
+):%0A %22%22%22%0A Return a k8s api aware HTTPRequest factory that autodiscovers connection info%0A %22%22%22%0A if os.path.exists('/var/run/secrets/kubernetes.io/serviceaccount/token'):%0A # We are running in a pod, and have access to a service account!%0A return request_maker_serviceaccount()%0A else:%0A return request_maker_
kube
-/
config
-'):%0A %22%22%22%0A Return a function that creates Kubernetes API aware HTTPRequest objects
+()%0A%0A%0Adef request_maker_serviceaccount():%0A %22%22%22%0A Return a k8s api aware HTTPRequest factory that discovers connection info from a service account%0A%0A Discovers the hostname, port, protocol & authentication details for talking to%0A the kubernetes API from a ServiceAccount. This requires that service accounts are%0A turned on in your kubernetes cluster and that the calling code is running in a pod.%0A %22%22%22%0A with open('/var/run/secrets/kubernetes.io/serviceaccount/token') as f:%0A token = f.read()%0A api_url = 'https://%7Bhost%7D:%7Bport%7D'.format(%0A host=os.environ%5B'KUBERNETES_SERVICE_HOST'%5D,%0A port=os.environ%5B'KUBERNETES_SERVICE_PORT'%5D%0A )%0A%0A def make_request(url, **kwargs):%0A %22%22%22%0A Make & return a HTTPRequest object suited to making requests to a Kubernetes cluster%0A%0A The following changes are made to the passed in arguments%0A * url%0A No hostname / protocol should be provided, only path (and query strings, if any).%0A The hostname / protocol / port will be automatically provided.%0A * headers%0A Appropriate Authorization header will be added%0A * ca_certs%0A Appropriate CA bundle path will be set%0A %22%22%22%0A headers = kwargs.get('headers', %7B%7D)%0A headers%5B'Authorization'%5D = 'Bearer %7Btoken%7D'.format(token=token)%0A kwargs.update(%7B%0A 'url': api_url + url,%0A 'ca_certs': '/var/run/secrets/kubernetes.io/serviceaccount/ca.crt',%0A 'headers': headers,%0A %7D)%0A return HTTPRequest(**kwargs)%0A%0A return make_request%0A%0A%0Adef request_maker_kubeconfig():%0A %22%22%22%0A Return a k8s api aware HTTPRequest factory that discovers connection info from a .kube/config file
%0A%0A
@@ -2473,74 +2473,8 @@
ile.
-%0A%0A TODO: Pick up info from service accounts + env variables too
%0A
@@ -2511,20 +2511,32 @@
anduser(
-path
+'~/.kube/config'
)) as f:
@@ -3441,130 +3441,172 @@
-These will be automatically set if required%0A * ca_certs%0A This will also be automatically set if required
+Appropriate client certificate / key will be set if specified in .kube/config%0A * ca_certs%0A Appropriate ca will be set if specified in .kube/config
%0A
|
283c049d3a3bdba4a35d71f44fb7a2c453713c9f
|
Calculate "minute" correctly.
|
opbeat/utils/traces.py
|
opbeat/utils/traces.py
|
from collections import defaultdict
import threading
import time
from datetime import datetime
class _RequestList(object):
def __init__(self, transaction, response_code, minute):
self.transaction = transaction
self.response_code = response_code
self.minute = minute
self.durations = []
@property
def fingerprint(self):
return (self.transaction, self.response_code, self.minute)
def add(self, elapsed):
self.durations.append(elapsed)
def as_dict(self):
return {
"transaction": self.transaction,
"result": self.response_code,
"timestamp": datetime.utcfromtimestamp(self.minute).isoformat() + "Z",
"durations": self.durations
}
class RequestsStore(object):
def __init__(self, collect_frequency):
self.cond = threading.Condition()
self.items = {}
self.collect_frequency = collect_frequency
self._last_collect = time.time()
def add(self, elapsed, transaction, response_code):
with self.cond:
requestlist = _RequestList(transaction, response_code,
int(time.time()/60))
if requestlist.fingerprint not in self.items:
self.items[requestlist.fingerprint] = requestlist
self.items[requestlist.fingerprint].add(elapsed)
self.cond.notify()
def get_all(self, blocking=False):
with self.cond:
# If blocking is true, always return at least 1 item
while blocking and len(self.items) == 0:
self.cond.wait()
items, self.items = self.items, {}
self._last_collect = time.time()
return [v.as_dict() for v in items.values()]
def should_collect(self):
return (
(time.time() - self._last_collect)
>= self.collect_frequency
)
def __len__(self):
with self.cond:
return len(self.items)
|
Python
| 0.998189
|
@@ -1194,16 +1194,19 @@
me()/60)
+*60
)%0A%0A
|
2a1e09f99c5c1c80286048a27d6ba0c2ef7fc5b3
|
Add none property store
|
txdav/base/propertystore/none.py
|
txdav/base/propertystore/none.py
|
Python
| 0.000001
|
@@ -0,0 +1,1789 @@
+# -*- test-case-name: txdav.base.propertystore.test.test_none,txdav.caldav.datastore,txdav.carddav.datastore -*-%0A##%0A# Copyright (c) 2010-2011 Apple Inc. All rights reserved.%0A#%0A# Licensed under the Apache License, Version 2.0 (the %22License%22);%0A# you may not use this file except in compliance with the License.%0A# You may obtain a copy of the License at%0A#%0A# http://www.apache.org/licenses/LICENSE-2.0%0A#%0A# Unless required by applicable law or agreed to in writing, software%0A# distributed under the License is distributed on an %22AS IS%22 BASIS,%0A# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.%0A# See the License for the specific language governing permissions and%0A# limitations under the License.%0A##%0A%0A%22%22%22%0AAlways-empty property store.%0A%22%22%22%0A%0Afrom __future__ import absolute_import%0A%0A__all__ = %5B%0A %22PropertyStore%22,%0A%5D%0A%0Afrom txdav.idav import PropertyChangeNotAllowedError%0Afrom txdav.base.propertystore.base import AbstractPropertyStore, validKey%0A%0Aclass PropertyStore(AbstractPropertyStore):%0A %22%22%22%0A Always-empty property store.%0A Writing properties is not allowed.%0A %22%22%22%0A def __init__(self, defaultuser, pathFactory):%0A super(PropertyStore, self).__init__(defaultuser)%0A del self.__setitem__%0A del self.__delitem__%0A%0A #%0A # Required implementations%0A #%0A%0A def _getitem_uid(self, key, uid):%0A validKey(key)%0A raise KeyError(key)%0A%0A def _setitem_uid(self, key, value, uid):%0A validKey(key)%0A raise PropertyChangeNotAllowedError(%22Property store is read-only.%22, (key,))%0A%0A def _delitem_uid(self, key, uid):%0A validKey(key)%0A raise KeyError(key)%0A%0A def _keys_uid(self, uid):%0A return ()%0A%0A #%0A # I/O%0A #%0A%0A def flush(self):%0A return None%0A%0A def abort(self):%0A return None%0A
|
|
d77dd62203e0898ab326092c410638a0274e53d9
|
Initialize P02_errorExample
|
books/AutomateTheBoringStuffWithPython/Chapter10/P02_errorExample.py
|
books/AutomateTheBoringStuffWithPython/Chapter10/P02_errorExample.py
|
Python
| 0.000006
|
@@ -0,0 +1,176 @@
+# This program raises an exception and automatically displays the traceback%0A%0A%0Adef spam():%0A bacon()%0A%0A%0Adef bacon():%0A raise Exception(%22This is the error message.%22)%0A%0A%0Aspam()%0A
|
|
61d0649925fae2d1eca1f512ec519f440f4a5528
|
Create OutputNeuronGroup_multiple_outputs_2.py
|
examples/OutputNeuronGroup_multiple_outputs_2.py
|
examples/OutputNeuronGroup_multiple_outputs_2.py
|
Python
| 0
|
@@ -0,0 +1,2836 @@
+'''%0AExample of a spike receptor (only receives spikes)%0A%0AIn this example spikes are received and processed creating a raster plot at the end of the simulation.%0A%0A'''%0A%0Afrom brian import *%0Aimport numpy%0A%0Afrom brian_multiprocess_udp import BrianConnectUDP%0A%0A# The main function with the NeuronGroup(s) and Synapse(s) must be named %22main_NeuronGroup%22.%0A# It will receive two objects: input_Neuron_Group and the simulation_clock. The input_Neuron_Group%0A# will supply the input spikes to the network. The size of the spike train received equals NumOfNeuronsInput.%0A# The size of the output spike train equals NumOfNeuronsOutput and must be the same size of the NeuronGroup who is%0A# going to interface with the rest of the system to send spikes.%0A# The function must return all the NeuronGroup objects and all the Synapse objects this way:%0A# (%5Blist of all NeuronGroups%5D,%5Blist of all Synapses%5D)%0A# and the FIRST (index 0) NeuronGroup of the list MUST be the one where the OUTPUT spikes will be taken by the simulation.%0A# %0A# Here is also possible to use %22dummy%22 NeuronGroups only to receive and/or send spikes.%0A%0Amy_neuron_input_number = 45%0A%0Adef main_NeuronGroup(input_Neuron_Group, simulation_clock):%0A print %22main_NeuronGroup!%22 #DEBUG!%0A%0A simclock = simulation_clock%0A%0A Nr=NeuronGroup(my_neuron_input_number, model='v:1', reset=0, threshold=0.5, clock=simclock)%0A Nr.v=0%0A%0A # SYNAPSES BETWEEN REAL NEURON NETWORK AND THE INPUT%0A Syn_iNG_Nr=Synapses(input_Neuron_Group, Nr, model='w:1', pre='v+=w', clock=simclock)%0A%0A Syn_iNG_Nr%5B:,:%5D='i==j'%0A%0A print %22Total Number of Synapses:%22, len(Syn_iNG_Nr) #DEBUG!%0A%0A Syn_iNG_Nr.w=1%0A%0A MExt=SpikeMonitor(Nr) # Spikes sent by UDP%0A%0A Mdummy=SpikeMonitor(input_Neuron_Group) # Spikes received by UDP%0A%0A return (%5BNr%5D,%5BSyn_iNG_Nr%5D,%5BMExt,Mdummy%5D)%0A%0Adef post_simulation_function(input_NG, simulation_NG, simulation_SYN, simulation_MN):%0A %22%22%22%0A input_NG: the neuron group that receives the input spikes%0A simulation_NG: the neuron groups list passed to the system by the user function (main_NeuronGroup)%0A simulation_SYN: the synapses list passed to the system by the user function (main_NeuronGroup)%0A simulation_MN: the monitors list passed to the system by the user function (main_NeuronGroup)%0A%0A This way it is possible to plot, save or do whatever you want with these objects after the end of the simulation!%0A %22%22%22%0A pass%0A figure()%0A raster_plot(simulation_MN%5B1%5D)%0A title(%22Spikes Received by UDP%22)%0A show(block=True) %0A # savefig('output.pdf')%0A%0A%0A%0A%0Aif __name__==%22__main__%22:%0A%0A my_simulation = BrianConnectUDP(main_NeuronGroup, NumOfNeuronsInput=my_neuron_input_number, post_simulation_function=post_simulation_function,%0A input_addresses=%5B(%22127.0.0.1%22, 12121, 45)%5D, simclock_dt=1, inputclock_dt=2, TotalSimulationTime=10000, sim_repetitions=0, brian_address=2)%0A
|
|
180a1cd82b02d23b824d706c44d4c6838eca0dd2
|
Add from_nailgun.py manager
|
f2s/resources/role_data/managers/from_nailgun.py
|
f2s/resources/role_data/managers/from_nailgun.py
|
Python
| 0.000001
|
@@ -0,0 +1,267 @@
+#!/usr/bin/env python%0A%0Aimport sys%0Aimport json%0A%0Afrom fuelclient.objects.environment import Environment%0A%0AARGS = json.loads(sys.stdin.read())%0A%0Aenv = Environment(ARGS%5B'env'%5D)%0Afacts = env.get_default_facts('deployment', %5BARGS%5B'uid'%5D%5D)%0A%0Asys.stdout.write(json.dumps(facts))%0A
|
|
9a25f2c9506ce2c35b9199a96d3106fcc8479d87
|
remove unused import
|
src/robotide/editor/sourceeditor.py
|
src/robotide/editor/sourceeditor.py
|
import wx
from wx import stc
from StringIO import StringIO
from robot.parsing.model import TestCaseFile
from robot.parsing.populators import FromFilePopulator
from robot.parsing.txtreader import TxtReader
from robotide.publish.messages import RideItemNameChanged
from robotide.widgets import VerticalSizer
from robotide.pluginapi import (Plugin, ActionInfo, RideSaving,
TreeAwarePluginMixin, RideTreeSelection, RideNotebookTabChanging)
class SourceEditorPlugin(Plugin, TreeAwarePluginMixin):
title = 'Edit Source'
def __init__(self, application):
Plugin.__init__(self, application)
self._editor_component = None
@property
def _editor(self):
if not self._editor_component:
self._editor_component = SourceEditor(self.notebook, self.title)
return self._editor_component
def enable(self):
self.register_action(ActionInfo('Edit', 'Edit Source', self.OnOpen))
self.add_self_as_tree_aware_plugin()
self.subscribe(self.OnSaving, RideSaving)
self.subscribe(self.OnTreeSelection, RideTreeSelection)
self.subscribe(self.OnTreeSelection, RideItemNameChanged)
self.subscribe(self.OnTabChange, RideNotebookTabChanging)
def disable(self):
self.unsubscribe_all()
self.remove_self_from_tree_aware_plugins()
self.unregister_actions()
self._editor_component = None
def OnOpen(self, event):
self.open()
def open(self):
self._editor.open(self.tree.get_selected_datafile_controller())
self.show_tab(self._editor)
def OnSaving(self, message):
if self._editor_component and self.is_focused():
self._editor.save()
self.tree.refresh_current_datafile()
def OnTreeSelection(self, message):
if self._editor_component and self.is_focused():
self._editor.open(self.tree.get_selected_datafile_controller())
def OnTabChange(self, message):
if message.newtab == self.title:
self.open()
return
if message.oldtab != self.title:
return
if self._editor._editor.dirty:
self._ask_and_apply()
def _ask_and_apply(self):
# TODO: use widgets.Dialog
ret = wx.MessageDialog(self._editor, 'Apply changes?', 'Source changed',
style=wx.YES_NO | wx.ICON_QUESTION).ShowModal()
if ret == wx.ID_YES:
self._editor.save()
self.tree.refresh_current_datafile()
def is_focused(self):
return self.tab_is_visible(self._editor)
class SourceEditor(wx.Panel):
def __init__(self, parent, title):
wx.Panel.__init__(self, parent)
self._parent = parent
self.SetSizer(VerticalSizer())
self._editor = RobotDataEditor(self)
self.Sizer.add_expanding(self._editor)
self._parent.AddPage(self, title)
self._data = None
def open(self, data_controller):
output = StringIO()
data_controller.datafile.save(output=output, format='txt')
self._editor.set_text(output.getvalue())
self._data = data_controller
def save(self):
if self._editor.dirty:
src = StringIO(self._editor.GetText().encode('UTF-8'))
target = self._create_target()
FromStringIOPopulator(target).populate(src)
self._data.set_datafile(target)
self._editor.dirty = False
def _create_target(self):
datafile_class = type(self._data.data)
target = datafile_class(source=self._data.source)
return target
class RobotDataEditor(stc.StyledTextCtrl):
def __init__(self, parent):
stc.StyledTextCtrl.__init__(self, parent)
self.Bind(wx.EVT_KEY_DOWN, self.OnKey)
self.dirty = False
def set_text(self, text):
self.SetText(text)
def OnKey(self, event):
self.dirty = True
event.Skip()
class FromStringIOPopulator(FromFilePopulator):
def populate(self, content):
TxtReader().read(content, self)
|
Python
| 0.000001
|
@@ -56,53 +56,8 @@
gIO%0A
-from robot.parsing.model import TestCaseFile%0A
from
|
cd444633870a83adc4220b0bc7025a4ee014ba69
|
Add e2e testing python file
|
tests/e2e/test_e2e_identidock.py
|
tests/e2e/test_e2e_identidock.py
|
Python
| 0.000001
|
@@ -0,0 +1,28 @@
+import sys%0A%0Aprint(sys.path)%0A
|
|
4c6de322d04504e4c0c2c46f686820d3d62b7dac
|
Add mdata grains as separate module
|
salt/grains/mdata.py
|
salt/grains/mdata.py
|
Python
| 0.000001
|
@@ -0,0 +1,2231 @@
+# -*- coding: utf-8 -*-%0A'''%0A test grains%0A'''%0Afrom __future__ import absolute_import%0A%0A# Import python libs%0Aimport os%0Aimport logging%0A%0A# Import salt libs%0Aimport salt.utils%0A%0A# Solve the Chicken and egg problem where grains need to run before any%0A# of the modules are loaded and are generally available for any usage.%0Aimport salt.modules.cmdmod%0A%0A__virtualname__ = 'mdata'%0A__salt__ = %7B%0A 'cmd.run': salt.modules.cmdmod.run,%0A 'cmd.run_all': salt.modules.cmdmod.run_all,%0A%7D%0A%0Alog = logging.getLogger(__name__)%0A%0A%0Adef __virtual__():%0A '''%0A Figure out if we need to be loaded%0A '''%0A ## collect mdata grains in a SmartOS zone%0A if salt.utils.is_smartos_zone():%0A return __virtualname__%0A ## collect mdata grains in a LX zone%0A if salt.utils.is_linux() and 'BrandZ virtual linux' in os.uname():%0A return __virtualname__%0A return False%0A%0A%0Adef mdata():%0A '''%0A Provide grains from the SmartOS metadata%0A '''%0A grains = %7B%7D%0A mdata_list = salt.utils.which('mdata-list')%0A mdata_get = salt.utils.which('mdata-get')%0A%0A # parse sdc metadata%0A grains%5B'hypervisor_uuid'%5D = __salt__%5B'cmd.run'%5D('%7B0%7D sdc:server_uuid'.format(mdata_get))%0A if %22FAILURE%22 in grains%5B'hypervisor_uuid'%5D or %22No metadata%22 in grains%5B'hypervisor_uuid'%5D:%0A grains%5B'hypervisor_uuid'%5D = %22Unknown%22%0A grains%5B'datacenter'%5D = __salt__%5B'cmd.run'%5D('%7B0%7D sdc:datacenter_name'.format(mdata_get))%0A if %22FAILURE%22 in grains%5B'datacenter'%5D or %22No metadata%22 in grains%5B'datacenter'%5D:%0A grains%5B'datacenter'%5D = %22Unknown%22%0A%0A # parse vmadm metadata%0A for mdata_grain in __salt__%5B'cmd.run'%5D(mdata_list).splitlines():%0A grain_data = __salt__%5B'cmd.run'%5D('%7B0%7D %7B1%7D'.format(mdata_get, mdata_grain))%0A%0A if mdata_grain == 'roles': # parse roles as roles grain%0A grain_data = grain_data.split(',')%0A grains%5B'roles'%5D = grain_data%0A else: # parse other grains into mdata%0A if not mdata_grain.startswith('sdc:'):%0A if 'mdata' not in grains:%0A grains%5B'mdata'%5D = %7B%7D%0A%0A mdata_grain = mdata_grain.replace('-', '_')%0A mdata_grain = mdata_grain.replace(':', '_')%0A grains%5B'mdata'%5D%5Bmdata_grain%5D = grain_data%0A%0A return grains%0A
|
|
ccdc943f4c0292d6046b32cacab410ba6cf1477a
|
Add the StatePass module
|
lib/game_states/state_pass.py
|
lib/game_states/state_pass.py
|
Python
| 0
|
@@ -0,0 +1,3073 @@
+%22%22%22This module contains the StatePass class which defines the data%0Aobject that will be passed between Game States.%0A%22%22%22%0Afrom pygame.mixer import Channel%0Afrom lib.custom_data.settings_data import SettingsData%0A%0A%0Aclass StatePass(object):%0A %22%22%22Stores common data that will be passed between Game States.%0A%0A All States should have reference to the same, singular StatePass%0A object. In this way, when one State modifies the StatePass details,%0A the details will automatically be updated for all other States as%0A well.%0A%0A Attributes:%0A announcer_channel: A PyGame Channel for playing announcer voice%0A clips.%0A ui_channel: A PyGame Channel for playing user interface sound%0A effects.%0A p1_channel_one: One of the two PyGame Channels that Player 1's%0A character can use when playing action sounds.%0A p2_channel_two: One of the two PyGame Channels that Player 1's%0A character can use when playing action sounds.%0A p2_channel_one: One of the two PyGame Channels that Player 2's%0A character can use when playing action sounds.%0A p2_channel_two: One of the two PyGame Channels that Player 2's%0A character can use when playing action sounds.%0A character_one: The integer line index for for player one's%0A character within the character list. Setting this to None%0A means no character has been chosen yet.%0A character_two: The integer line index for for player two's%0A character within the character list. Setting this to None%0A means no character has been chosen yet.%0A stage: The integer line index for the chosen battle Stage within%0A the stage list. Setting this to None means no Stage has%0A been chosen yet.%0A battle_rounds: The number of rounds for the current%0A battle. The possible values are 1, 3, and 5.%0A Note that setting this to 0 means that Training Mode has%0A been selected.%0A time_limit: The amount of time, in seconds, allotted to each%0A round in the upcoming battle. This can be 30, 60, or 99%0A seconds.%0A Note that setting this to 0 means that Training Mode has%0A been selected.%0A settings_data: A SettingsData object for various options that%0A can be set by the players via the Settings Screen.%0A %22%22%22%0A def __init__(self, settings_data):%0A %22%22%22Declare and initialize instance variables.%0A%0A Keyword arguments:%0A settings_data: The SettingsData object that will be%0A passed between all States.%0A %22%22%22%0A self.announcer_channel = Channel(0)%0A self.ui_channel = Channel(1)%0A self.p1_channel_one = Channel(2)%0A self.p1_channel_two = Channel(3)%0A self.p2_channel_one = Channel(4)%0A self.p2_channel_two = Channel(5)%0A self.character_one = None%0A self.character_two = None%0A self.stage = None%0A self.battle_rounds = 3%0A self.time_limit = 99%0A self.settings = settings_data%0A%0A
|
|
7d09120e1122c5b9888368e7d98b41fe8fdedf87
|
add script to send test messages to MNOs
|
scripts/test-MNOs.py
|
scripts/test-MNOs.py
|
Python
| 0
|
@@ -0,0 +1,1174 @@
+#!/usr/bin/env python%0A%0Aimport urllib2%0Aimport urllib%0Aimport sys%0Aimport datetime%0Aimport pytz%0A%0Atest_phones = %5B%0A ('MTN', '2348142235832'),%0A ('Etisalat', '2348183273915'),%0A ('Glo', '2348117159357'),%0A ('Airtel', '2347010915898'),%0A%5D%0A%0Awat = pytz.timezone('Africa/Lagos')%0Afor via_operator, _ in test_phones:%0A for phone_operator, phone in test_phones:%0A now = datetime.datetime.now(wat).strftime('%25H:%25M:%25S on %25d/%25m/%25Y')%0A params = %7B%0A 'username': 'rapidsms',%0A 'password': '', # XXX add password here%0A 'to': phone,%0A 'from': '55999',%0A 'smsc': 'starfish-%25s' %25 via_operator.lower(),%0A 'text': 'Test message to %25s via %25s. Sent at %25s' %25 (phone_operator, via_operator, now),%0A %7D%0A data = urllib.urlencode(params)%0A url = 'https://myvoice-testing.caktusgroup.com/sendsms?%25s' %25 data%0A print 'Loading %25s' %25 url%0A try:%0A result = urllib2.urlopen(url)%0A except urllib2.HTTPError, e:%0A result = e%0A print 'Status code and result for %25s via %25s: %25s' %25 (phone_operator, via_operator, result.getcode())%0A print result.read()%0A print ''%0A
|
|
308fb5c3cb69966d7f7bf20ea1e4753d68d3fe4b
|
Add init
|
scrapi/consumers/cmu/__init__.py
|
scrapi/consumers/cmu/__init__.py
|
Python
| 0.085164
|
@@ -0,0 +1,39 @@
+from consumer import consume, normalize
|
|
79343dda0711e34ef577ff37bddfe3f83d0035f5
|
add script to fetch NOMADS data
|
scripts/model/fetch_nomads_nc.py
|
scripts/model/fetch_nomads_nc.py
|
Python
| 0
|
@@ -0,0 +1,882 @@
+%22%22%22%0ADownload netcdf data from NOMADS Thredds service, run as%0A%0A/usr/local/python/bin/python fetch_nomads_nc.py%0A%22%22%22%0Aimport mx.DateTime%0Aimport subprocess%0A%0A# start time, GMT%0Asts = mx.DateTime.DateTime(2010,11,1)%0A# end time, GMT%0Aets = mx.DateTime.DateTime(2012,9,17)%0A# Interval%0Ainterval = mx.DateTime.RelativeDateTime(hours=6)%0A%0Anow = sts%0Awhile now %3C ets:%0A for F in %5B'000', '006', '012', '018', '024'%5D:%0A print 'Downloading', now.strftime(%22%25Y-%25m-%25d %25H%22), ' Forecast Hr:', F%0A command = now.strftime(%22wget -q -O '%25Y%25m%25d%25H-%22+F+%22.nc' 'http://nomads.ncdc.noaa.gov/thredds/ncss/grid/gfs-004/%25Y%25m/%25Y%25m%25d/gfs_4_%25Y%25m%25d_%25H00_%22+F+%22.grb2?var=Geopotential_height&spatial=all&north=90.0000&west=0.0000&east=-0.5000&south=-90.0000&temporal=all&time_start=%25Y-%25m-%25dT%25H:00:00Z&time_end=%25Y-%25m-%25dT%25H:00:00Z&horizStride='%22)%0A subprocess.call(command, shell=True)%0A %0A now += interval
|
|
44f81107d829f76d9f6338a0ba2545a68539515e
|
Introduce Partial differences class.
|
Core/Difference.py
|
Core/Difference.py
|
Python
| 0
|
@@ -0,0 +1,526 @@
+# -*- coding:utf-8 -*- %0A%0A%0A#--%0A#%0A# Copyright (C) 2013-2014 Micha%C3%ABl Roy%0A#%0A#--%0A%0A%0A#--%0A#%0A# External dependencies%0A#%0A#--%0A#%0Afrom numpy import array%0A%0A%0A#--%0A#%0A# Difference%0A#%0A#--%0A#%0A# Defines a class representing partial differences on triangular mesh%0A#%0Aclass Difference :%0A%0A%0A%09#--%0A%09#%0A%09# Initialisation%0A%09#%0A%09#--%0A%09#%0A%09def __init__( self, mesh=None ) :%0A%09%09%0A%09%09# Base mesh%0A%09%09self.mesh = mesh%0A%09%09%0A%09#--%0A%09#%0A%09# Gradient%0A%09#%0A%09#--%0A%09#%0A%09def Gradient( self ) :%0A%09%09%0A%09%09for u in range(len( self.vertices )) :%0A%09%09%09for v in self.mesh.neighbor_vertices%5B u %5D :%0A%09%09%09%09%0A%09%0A
|
|
059a9b14e6db26f6131d41e758d1f14b33bc25b8
|
add python script to jump to a random line
|
vim/goto-random.py
|
vim/goto-random.py
|
Python
| 0.000001
|
@@ -0,0 +1,652 @@
+import random%0Aimport vim%0A%0A%0A# Jumps to a random line inside the current buffer. Helpful if you have lots of%0A# testcases inside a single file and you want to minimize conflicts, i.e. just%0A# appending tests to the end of the file is a bad strategy.%0Adef main():%0A # Add an entry to the jump list.%0A vim.command(%22normal! m'%22)%0A%0A # Jump to a line.%0A line = random.choice(range(len(vim.current.buffer)))%0A # cursor() is 1-based.%0A vim.eval(%22cursor(%22 + str(line + 1) + %22, 0)%22)%0A%0A # Move the cursor to the center of the screen.%0A vim.command(%22normal! zz%22)%0A%0Aif __name__ == '__main__':%0A main()%0A%0A# vim: set shiftwidth=4 softtabstop=4 expandtab:%0A
|
|
ae6eb7d4716cab50e8850a94a93c96167337c150
|
add fourth tool of Ultimate family, Ultimate GemCutter
|
benchexec/tools/ultimategemcutter.py
|
benchexec/tools/ultimategemcutter.py
|
Python
| 0
|
@@ -0,0 +1,932 @@
+# This file is part of BenchExec, a framework for reliable benchmarking:%0A# https://github.com/sosy-lab/benchexec%0A#%0A# SPDX-FileCopyrightText: 2016-2021 Daniel Dietsch %3Cdietsch@informatik.uni-freiburg.de%3E%0A# SPDX-FileCopyrightText: 2016-2020 Dirk Beyer %3Chttps://www.sosy-lab.org%3E%0A#%0A# SPDX-License-Identifier: Apache-2.0%0A%0Afrom . import ultimate%0A%0A%0Aclass Tool(ultimate.UltimateTool):%0A %22%22%22%0A This is the tool info module for ULTIMATE GemCutter.%0A%0A You can download the latest release from GitHub or build the latest development snapshot by following the%0A instructions at https://github.com/ultimate-pa/ultimate/wiki/Usage%0A%0A Please report any issues to our issue tracker at https://github.com/ultimate-pa/ultimate/issues%0A%0A Latest release: https://github.com/ultimate-pa/ultimate/releases/latest%0A Git repository: https://github.com/ultimate-pa/ultimate.git%0A %22%22%22%0A%0A def name(self):%0A return %22ULTIMATE GemCutter%22%0A
|
|
772ebd24f21f69eacfaae2b1a6658b82031dbd75
|
add import script for North Norfolk
|
polling_stations/apps/data_collection/management/commands/import_north_norfolk.py
|
polling_stations/apps/data_collection/management/commands/import_north_norfolk.py
|
Python
| 0
|
@@ -0,0 +1,2127 @@
+from django.contrib.gis.geos import Point%0Afrom data_collection.management.commands import BaseCsvStationsCsvAddressesImporter%0Afrom data_finder.helpers import geocode_point_only, PostcodeError%0A%0Aclass Command(BaseCsvStationsCsvAddressesImporter):%0A council_id = 'E07000147'%0A addresses_name = 'PropertyPostCodePollingStationWebLookup-2017-01-16.CSV'%0A stations_name = 'PropertyPostCodePollingStationWebLookup-2017-01-16.CSV'%0A elections = %5B'local.norfolk.2017-05-04'%5D%0A%0A def get_station_hash(self, record):%0A return %22-%22.join(%5B%0A record.pollingplaceid,%0A %5D)%0A%0A def station_record_to_dict(self, record):%0A # format address%0A address = %22%5Cn%22.join(%5B%0A record.pollingplaceaddress1,%0A record.pollingplaceaddress2,%0A record.pollingplaceaddress3,%0A record.pollingplaceaddress4,%0A record.pollingplaceaddress5,%0A record.pollingplaceaddress6,%0A %5D)%0A while %22%5Cn%5Cn%22 in address:%0A address = address.replace(%22%5Cn%5Cn%22, %22%5Cn%22).strip()%0A%0A # no points supplied, so attempt to attach them by geocoding%0A try:%0A location_data = geocode_point_only(record.pollingplaceaddress7)%0A location = Point(%0A location_data%5B'wgs84_lon'%5D,%0A location_data%5B'wgs84_lat'%5D,%0A srid=4326)%0A except PostcodeError:%0A location = None%0A%0A return %7B%0A 'internal_council_id': record.pollingplaceid,%0A 'postcode' : record.pollingplaceaddress7,%0A 'address' : address,%0A 'location' : location%0A %7D%0A%0A def address_record_to_dict(self, record):%0A if record.propertynumber.strip() == '0' or record.propertynumber.strip() == '':%0A address = record.streetname.strip()%0A else:%0A address = '%25s %25s' %25 (record.propertynumber.strip(), record.streetname.strip())%0A%0A return %7B%0A 'address' : address,%0A 'postcode' : record.postcode.strip(),%0A 'polling_station_id': record.pollingplaceid%0A %7D%0A
|
|
912ec1162e18b6ffc05ecebaf74f0b946748fa00
|
fix device/proxy functions arguments names to
|
zmq/cffi_core/devices.py
|
zmq/cffi_core/devices.py
|
# coding: utf-8
from ._cffi import C, ffi, zmq_version_info
from .socket import Socket
from zmq.error import ZMQError
def device(device_type, isocket, osocket):
rc = C.zmq_device(device_type, isocket.zmq_socket, osocket.zmq_socket)
if rc != 0:
raise ZMQError(C.zmq_errno())
return rc
def proxy(isocket, osocket, msocket=None):
if isinstance(msocket, Socket):
msocket = msocket.zmq_socket
else:
msocket = ffi.NULL
rc = C.zmq_proxy(isocket.zmq_socket, osocket.zmq_socket, msocket)
if rc != 0:
raise ZMQError(C.zmq_errno())
return rc
__all__ = ['device', 'proxy']
|
Python
| 0
|
@@ -137,32 +137,33 @@
e_type,
-isocket, osocket
+frontend, backend
):%0A r
@@ -192,24 +192,26 @@
e_type,
-isocket.
+frontend._
zmq_sock
@@ -210,32 +210,33 @@
zmq_socket,
-osocket.
+backend._
zmq_socket)%0A
@@ -320,33 +320,34 @@
oxy(
-isocket, osocket, msocket
+frontend, backend, capture
=Non
@@ -368,23 +368,23 @@
nstance(
-msocket
+capture
, Socket
@@ -398,26 +398,27 @@
-msocket = msocket.
+capture = capture._
zmq_
@@ -442,23 +442,23 @@
-msocket
+capture
= ffi.N
@@ -487,16 +487,18 @@
oxy(
-isocket.
+frontend._
zmq_
@@ -509,16 +509,17 @@
et,
-osocket.
+backend._
zmq_
@@ -530,15 +530,15 @@
et,
-msocket
+capture
)%0A%0A
|
a9348b49b6e91046941fb3af3a6b85edd072d7d9
|
add a module for descriptors
|
cheeseprism/desc.py
|
cheeseprism/desc.py
|
Python
| 0.000001
|
@@ -0,0 +1,489 @@
+class updict(dict):%0A %22%22%22%0A A descriptor that updates it's internal represention on set, and%0A returns the dictionary to original state on deletion.%0A %22%22%22%0A %0A def __init__(self, *args, **kw):%0A super(updict, self).__init__(*args, **kw)%0A self.default = self.copy()%0A%0A def __get__(self, obj, objtype):%0A return self%0A%0A def __set__(self, val):%0A self.update(val)%0A%0A def __delete__(self, obj):%0A self.clear()%0A self.update(self.default)%0A
|
|
23d61ae75c505d0e57eea0a3e04301e5b8d52498
|
Change the backend to threading
|
skopt/learning/gbrt.py
|
skopt/learning/gbrt.py
|
import numpy as np
from sklearn.base import clone
from sklearn.base import BaseEstimator, RegressorMixin
from sklearn.ensemble import GradientBoostingRegressor
from sklearn.utils import check_random_state
from sklearn.externals.joblib import Parallel, delayed
def _parallel_fit(regressor, X, y):
return regressor.fit(X, y)
class GradientBoostingQuantileRegressor(BaseEstimator, RegressorMixin):
"""Predict several quantiles with one estimator.
This is a wrapper around `GradientBoostingRegressor`'s quantile
regression that allows you to predict several `quantiles` in
one go.
Parameters
----------
* `quantiles` [array-like]:
Quantiles to predict. By default the 16, 50 and 84%
quantiles are predicted.
* `base_estimator` [GradientBoostingRegressor instance or None (default)]:
Quantile regressor used to make predictions. Only instances
of `GradientBoostingRegressor` are supported. Use this to change
the hyper-parameters of the estimator.
* `n_jobs` [int, default=1]:
The number of jobs to run in parallel for `fit`.
If -1, then the number of jobs is set to the number of cores.
* `random_state` [int, RandomState instance, or None (default)]:
Set random state to something other than None for reproducible
results.
"""
def __init__(self, quantiles=[0.16, 0.5, 0.84], base_estimator=None,
n_jobs=1, random_state=None):
self.quantiles = quantiles
self.random_state = random_state
self.base_estimator = base_estimator
self.n_jobs = n_jobs
def fit(self, X, y):
"""Fit one regressor for each quantile.
Parameters
----------
* `X` [array-like, shape=(n_samples, n_features):
Training vectors, where `n_samples` is the number of samples
and `n_features` is the number of features.
* `y` [array-like, shape=(n_samples,)]:
Target values (real numbers in regression)
"""
rng = check_random_state(self.random_state)
if self.base_estimator is None:
base_estimator = GradientBoostingRegressor(loss='quantile')
else:
base_estimator = self.base_estimator
if not isinstance(base_estimator, GradientBoostingRegressor):
raise ValueError('base_estimator has to be of type'
' GradientBoostingRegressor.')
if not base_estimator.loss == 'quantile':
raise ValueError('base_estimator has to use quantile'
' loss not %s' % base_estimator.loss)
regressors = []
for q in self.quantiles:
regressor = clone(base_estimator)
regressor.set_params(alpha=q, random_state=rng)
regressors.append(regressor)
self.regressors_ = Parallel(n_jobs=self.n_jobs)(
delayed(_parallel_fit)(regressor, X, y)
for regressor in regressors)
return self
def predict(self, X, return_std=False):
"""Predict.
Predict `X` at every quantile if `return_std` is set to False.
If `return_std` is set to True, then return the mean
and the predicted standard deviation, which is approximated as
the (0.84th quantile - 0.16th quantile) divided by 2.0
Parameters
----------
* `X` [array-like, shape=(n_samples, n_features):
where `n_samples` is the number of samples
and `n_features` is the number of features.
"""
predicted_quantiles = np.asarray(
[rgr.predict(X) for rgr in self.regressors_])
if not return_std:
return predicted_quantiles.T
else:
std_quantiles = [0.16, 0.5, 0.84]
is_present_mask = np.in1d(std_quantiles, self.quantiles)
if not np.all(is_present_mask):
raise ValueError(
"return_std works only if the quantiles during "
"instantiation include 0.16, 0.5 and 0.84")
low = self.regressors_[self.quantiles.index(0.16)].predict(X)
high = self.regressors_[self.quantiles.index(0.84)].predict(X)
mean = self.regressors_[self.quantiles.index(0.5)].predict(X)
return mean, ((high - low) / 2.0)
|
Python
| 0.000487
|
@@ -2926,16 +2926,37 @@
f.n_jobs
+, backend='threading'
)(%0A
|
d38b352f9e8da872ab1ff007df6ada76dfa8991b
|
add generic parameter passing from UIDebug
|
ai/executors/debug_executor.py
|
ai/executors/debug_executor.py
|
# Under MIT License, see LICENSE.txt
import math
from RULEngine.Debug.ui_debug_command import UIDebugCommand
from RULEngine.Util.Pose import Pose, Position
from ai.STA.Strategy.HumanControl import HumanControl
from ai.executors.executor import Executor
from ai.states.world_state import WorldState
class DebugExecutor(Executor):
def __init__(self, p_world_state: WorldState):
"""initialise"""
super().__init__(p_world_state)
self.debug_in = []
def exec(self):
"""ouvre les packets, parse et applique les packets detinés à l'IA"""
self._execute_incoming_debug_commands()
def set_reference(self, debug_ref) -> None:
""" rentre la référence donné par le RULEngine"""
self.debug_in = debug_ref
def _execute_incoming_debug_commands(self) -> None:
"""
change les packets en commandes correspondant, et les applique.
:return: None
"""
for command in self.debug_in:
self._parse_command(UIDebugCommand(command))
def _parse_command(self, cmd: UIDebugCommand)->None:
"""
Choisit la méthode puor appliquer la commande de l'UI
:param cmd: (UIDebugCommand) la commande de l'UIDebug
:return: None
"""
if cmd.is_strategy_cmd():
self._parse_strategy(cmd)
elif cmd.is_tactic_cmd():
self._parse_tactic(cmd)
else:
pass
def _parse_strategy(self, cmd: UIDebugCommand)->None:
"""
Remplace la stratégie courante par celle demander dans la commande de l'UI
:param cmd: (UIDebugCommand) la commande envoyée de l'UI
:return: None
"""
# TODO revise this function please, thank you!
# TODO change this once UI-Debug send correct strategy names!
strategy_key = cmd.data['strategy']
if strategy_key == 'pStop':
self.ws.play_state.set_strategy(self.ws.play_state.
get_new_strategy("DoNothing")
(self.ws.game_state))
else:
self.ws.play_state.set_strategy(self.ws.play_state.
get_new_strategy(strategy_key)
(self.ws.game_state))
def _parse_tactic(self, cmd: UIDebugCommand)->None:
"""
Remplace la tactique courante d'un robot par celle demander dans la commande de l'UI
:param cmd: (UIDebugCommand) la commande envoyée de l'UI
:return: None
"""
# TODO make implementation for other tactic packets!
# FIXME this pid thingy is getting out of control
player_id = self._sanitize_pid(cmd.data['id'])
tactic_name = cmd.data['tactic']
# TODO ui must send better packets back with the args.
target = cmd.data['target']
target = Pose(Position(target[0], target[1]), 3.92 - 2 * math.pi)
args = cmd.data['args']
tactic = self.ws.play_state.get_new_tactic('Idle')(self.ws.game_state,
player_id,
target)
try:
tactic = self.ws.play_state.get_new_tactic(tactic_name)\
(self.ws.game_state, player_id, target)
except Exception as e:
print(e)
print("La tactique n'a pas été appliquée par "
"cause de mauvais arguments.")
if isinstance(self.ws.play_state.current_strategy, HumanControl):
hc = self.ws.play_state.current_strategy
hc.assign_tactic(tactic, player_id)
else:
hc = HumanControl(self.ws.game_state)
hc.assign_tactic(tactic, player_id)
self.ws.play_state.set_strategy(hc)
@staticmethod
def _sanitize_pid(pid: int)->int:
# TODO find something better for this whole scheme
if 0 <= pid < 6:
return pid
elif 6 <= pid < 12:
return pid - 6
else:
return 0
|
Python
| 0
|
@@ -2994,16 +2994,24 @@
data
-%5B
+.get(
'args'
-%5D
+, %22%22)
%0A
|
dc477c7b1f0e0ffca01b934919cd32cbd635baab
|
Implement web scraper for GitHub repos
|
cibopath/scraper.py
|
cibopath/scraper.py
|
Python
| 0.000019
|
@@ -0,0 +1,1872 @@
+# -*- coding: utf-8 -*-%0A%0Aimport asyncio%0Aimport logging%0A%0Aimport aiohttp%0A%0Afrom cibopath import readme_parser, github_api%0Afrom cibopath.templates import Template%0A%0Alogger = logging.getLogger('cibopath')%0A%0AJSON_STORE = 'templates.json'%0A%0A%0Aclass CibopathError(Exception):%0A %22%22%22Custom error class for the app.%22%22%22%0A%0A%0Aclass CookiecutterReadmeError(CibopathError):%0A %22%22%22Unable to retrieve readme from github.com/audreyr/cookiecutter.%22%22%22%0A%0A%0Aclass UnableToFindTemplateLinks(CibopathError):%0A %22%22%22Cannot find links to templates in README.%22%22%22%0A%0A%0Adef fetch_template_data(username, token):%0A semaphore = asyncio.Semaphore(10)%0A loop = asyncio.get_event_loop()%0A auth = aiohttp.BasicAuth(username, token)%0A%0A with aiohttp.ClientSession(loop=loop, auth=auth) as client:%0A logger.debug('Load Cookiecutter readme')%0A cookiecutter_readme = loop.run_until_complete(%0A github_api.get_readme(semaphore, client, 'audreyr', 'cookiecutter')%0A )%0A if not cookiecutter_readme:%0A raise CookiecutterReadmeError%0A%0A logger.debug('Find GitHub links in Cookiecutter readme')%0A github_links, _ = readme_parser.read(cookiecutter_readme)%0A if not github_links:%0A raise UnableToFindTemplateLinks%0A%0A tasks = %5B%0A github_api.get_template(semaphore, client, link)%0A for link in github_links%0A %5D%0A%0A logger.debug('Fetch template data from links')%0A results = loop.run_until_complete(asyncio.gather(*tasks))%0A yield from filter(None, results) # Ignore all invalid templates%0A%0A%0Adef load_templates(username, token):%0A templates = %5B%5D%0A template_data = fetch_template_data(username, token)%0A%0A for name, author, repo, context, readme in template_data:%0A _, tags = readme_parser.read(readme)%0A templates.append(Template(name, author, repo, context, tags))%0A return templates%0A
|
|
71f321452f735d84ce0cdd9088c9ac0a163f2016
|
set formatter for loggers
|
zstacklib/zstacklib/utils/log.py
|
zstacklib/zstacklib/utils/log.py
|
'''
@author: frank
'''
import logging
import logging.handlers
import sys
import os.path
class LogConfig(object):
instance = None
LOG_FOLER = '/var/log/zstack'
def __init__(self):
if not os.path.exists(self.LOG_FOLER):
os.makedirs(self.LOG_FOLER, 0755)
self.log_path = os.path.join(self.LOG_FOLER, 'zstack.log')
self.log_level = logging.DEBUG
self.log_to_console = True
def set_log_to_console(self, to_console):
self.log_to_console = to_console
def get_log_path(self):
return self.log_path
def set_log_path(self, path):
self.log_path = path
def set_log_level(self, level):
self.log_level = level
def configure(self):
dirname = os.path.dirname(self.log_path)
if not os.path.exists(dirname):
os.makedirs(dirname, 0755)
logging.basicConfig(filename=self.log_path, level=self.log_level)
def get_logger(self, name, logfd=None):
logger = logging.getLogger(name)
logger.setLevel(logging.DEBUG)
max_rotate_handler = logging.handlers.RotatingFileHandler(self.log_path, maxBytes=10*1024*1024, backupCount=3)
logger.addHandler(max_rotate_handler)
if self.log_to_console:
formatter = logging.Formatter('%(asctime)s %(levelname)s [%(name)s] %(message)s')
if not logfd:
logfd = sys.stdout
ch = logging.StreamHandler(logfd)
ch.setLevel(logging.DEBUG)
ch.setFormatter(formatter)
logger.addHandler(ch)
return logger
@staticmethod
def get_log_config():
if not LogConfig.instance:
LogConfig.instance = LogConfig()
return LogConfig.instance
def get_logfile_path():
return LogConfig.get_log_config().get_log_path()
def set_logfile_path(path):
LogConfig.get_log_config().set_log_path(path)
def configure_log(log_path, level=logging.DEBUG, log_to_console=False):
cfg = LogConfig.get_log_config()
log_dir = os.path.dirname(log_path)
if not os.path.exists(log_dir):
os.makedirs(log_dir)
cfg.set_log_path(log_path)
cfg.set_log_level(level)
cfg.set_log_to_console(log_to_console)
cfg.configure()
def get_logger(name, logfd=None):
return LogConfig.get_log_config().get_logger(name, logfd)
def cleanup_log(hostname, username, password):
import ssh
ssh.execute('''cd /var/log/zstack; tar --ignore-failed-read -zcf zstack-logs-`date +%y%m%d-%H%M%S`.tgz *.log.* *.log; find . -name "*.log"|while read file; do echo "" > $file; done''', hostname, username, password)
def cleanup_local_log():
import shell
shell.call('''cd /var/log/zstack; tar --ignore-failed-read -zcf zstack-logs-`date +%y%m%d-%H%M%S`.tgz *.log.* *.log; find . -name "*.log"|while read file; do echo "" > $file; done''')
|
Python
| 0
|
@@ -1251,16 +1251,211 @@
unt=3)%0D%0A
+ formatter = logging.Formatter('%25(asctime)s %25(levelname)s %5B%25(name)s%5D %25(message)s')%0D%0A max_rotate_handler.setFormatter(formatter)%0D%0A max_rotate_handler.setLevel(logging.DEBUG)%0D%0A
|
549562247018e9c51e8cb8023972c1cf73fc84f4
|
add gc01.py
|
trypython/stdlib/gc01.py
|
trypython/stdlib/gc01.py
|
Python
| 0.000001
|
@@ -0,0 +1,1339 @@
+# coding: utf-8%0A%22%22%22gc%E3%83%A2%E3%82%B8%E3%83%A5%E3%83%BC%E3%83%AB%E3%81%AB%E3%81%A4%E3%81%84%E3%81%A6%E3%81%AE%E3%82%B5%E3%83%B3%E3%83%97%E3%83%AB%E3%81%A7%E3%81%99%E3%80%82%22%22%22%0Aimport gc%0Aimport secrets%0Aimport string%0A%0Afrom trypython.common.commoncls import SampleBase, timetracer%0Afrom trypython.common.commonfunc import pr%0A%0A%0Aclass Sample(SampleBase):%0A def __init__(self) -%3E None:%0A super().__init__()%0A self._data_list = None%0A self._characters = string.ascii_letters + string.digits%0A%0A def exec(self):%0A # ------------------------------------------------%0A # gc%E3%83%A2%E3%82%B8%E3%83%A5%E3%83%BC%E3%83%AB%0A # ------------------------------------------------%0A # gc%E3%83%A2%E3%82%B8%E3%83%A5%E3%83%BC%E3%83%AB%E3%81%AB%E3%81%AF%E3%80%81%E3%81%9D%E3%81%AE%E5%90%8D%E5%89%8D%E3%81%AE%E9%80%9A%E3%82%8A%E3%82%AC%E3%83%99%E3%83%BC%E3%82%B8%E3%82%B3%E3%83%AC%E3%82%AF%E3%82%B7%E3%83%A7%E3%83%B3%0A # %E9%96%A2%E9%80%A3%E3%81%AE%E6%93%8D%E4%BD%9C%E3%81%8C%E8%A1%8C%E3%81%88%E3%82%8B%E3%83%A2%E3%82%B8%E3%83%A5%E3%83%BC%E3%83%AB%E3%81%A8%E3%81%AA%E3%81%A3%E3%81%A6%E3%81%84%E3%82%8B%E3%80%82%0A #%0A # gc.get_objects() %E3%81%AF%E3%80%81%E7%8F%BE%E5%9C%A8Python%E3%81%8C%E8%BF%BD%E8%B7%A1%E5%AF%BE%E8%B1%A1%E3%81%A8%0A # %E3%83%9E%E3%83%BC%E3%82%AF%E3%81%97%E3%81%A6%E3%81%84%E3%82%8B%E3%82%AA%E3%83%96%E3%82%B8%E3%82%A7%E3%82%AF%E3%83%88%E3%81%AE%E3%83%AA%E3%82%B9%E3%83%88%E3%82%92%E8%BF%94%E3%81%99%E3%80%82%0A # -----------------------------------------------%0A alive_objects = gc.get_objects()%0A pr('gc.get_objects()', len(alive_objects))%0A%0A with timetracer('heavy proc'):%0A self._heavy_proc()%0A%0A alive_objects = gc.get_objects()%0A pr('gc.get_objects()', len(alive_objects))%0A%0A def _heavy_proc(self, count=100000) -%3E None:%0A self._data_list = %5Bself._generate_password() for _ in range(count)%5D%0A%0A def _generate_password(self, nbytes=32) -%3E str:%0A return ''.join(secrets.choice(self._characters) for _ in range(nbytes))%0A%0A%0Adef go():%0A obj = Sample()%0A obj.exec()%0A%0A%0Aif __name__ == '__main__':%0A go()%0A
|
|
4593aa5edf05b014aa6c7fe9de8b239ab2fa91b8
|
Add snapshot_framework_stats.py script
|
scripts/snapshot_framework_stats.py
|
scripts/snapshot_framework_stats.py
|
Python
| 0
|
@@ -0,0 +1,1508 @@
+#!/usr/bin/env python%0A%22%22%22Change user password%0A%0AUsage:%0A snapshot_framework_stats.py %3Cframework_slug%3E %3Cstage%3E %3Capi_token%3E%0A%0AExample:%0A ./snapshot_framework_stats.py g-cloud-7 dev myToken%0A%22%22%22%0A%0Aimport sys%0Aimport logging%0A%0Alogger = logging.getLogger('script')%0Alogging.basicConfig(level=logging.INFO)%0A%0Afrom docopt import docopt%0A%0Afrom dmutils import apiclient%0Afrom dmutils.audit import AuditTypes%0A%0A%0Adef get_api_endpoint_from_stage(stage):%0A stage_prefixes = %7B%0A 'preview': 'preview-api.development',%0A 'staging': 'staging-api',%0A 'production': 'api'%0A %7D%0A%0A if stage in %5B'local', 'dev', 'development'%5D:%0A return 'http://localhost:5000'%0A%0A return %22https://%7B%7D.digitalmarketplace.service.gov.uk%22.format(%0A stage_prefixes%5Bstage%5D%0A )%0A%0A%0Adef snapshot_framework_stats(api_endpoint, api_token, framework_slug):%0A data_client = apiclient.DataAPIClient(api_endpoint, api_token)%0A%0A try:%0A stats = data_client.get_framework_stats(framework_slug)%0A data_client.create_audit_event(%0A AuditTypes.snapshot_framework_stats,%0A data=stats,%0A object_type='frameworks',%0A object_id=framework_slug%0A )%0A except apiclient.APIError:%0A sys.exit(1)%0A%0A logger.info(%22Framework stats snapshot saved%22)%0A%0A%0Aif __name__ == '__main__':%0A arguments = docopt(__doc__)%0A%0A snapshot_framework_stats(%0A get_api_endpoint_from_stage(arguments%5B'%3Cstage%3E'%5D),%0A arguments%5B'%3Capi_token%3E'%5D,%0A arguments%5B'%3Cframework_slug%3E'%5D,%0A )%0A
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.