prefix stringlengths 0 918k | middle stringlengths 0 812k | suffix stringlengths 0 962k |
|---|---|---|
import os
import battlenet
try:
import unittest2 as unittest
except ImportError:
import uni | ttest as unittest
PUBLIC_KEY = os.environ.get('BNET_PUBLIC_KEY')
PRIVATE_KEY = os.environ.get('BNET_PRIVATE_ | KEY')
class RegionsTest(unittest.TestCase):
def setUp(self):
self.connection = battlenet.Connection(public_key=PUBLIC_KEY, private_key=PRIVATE_KEY)
def test_us(self):
realms = self.connection.get_all_realms(battlenet.UNITED_STATES)
self.assertTrue(len(realms) > 0)
def test_eu(sel... |
"""Disassembler of Python byte code into mnemonics."""
import sys
import types
from opcode_25 import *
from opcode_25 import __all__ as _opcodes_all
__all__ = ["dis","disassemble","distb","disco"] + _opcodes_all
del _opcodes_all
def dis(x=None):
"""Disassemble classes, methods, functions, or code.
With no ... | jrel:
label = i+oparg
elif op in hasjabs:
label = oparg
if label >= 0:
if label not in labels:
labels.append(label)
return labels
def _test():
"""Simple test program to disassemble a file."""
if sys.argv[1:]:
... | = "-":
fn = None
else:
fn = None
if fn is None:
f = sys.stdin
else:
f = open(fn)
source = f.read()
if fn is not None:
f.close()
else:
fn = "<stdin>"
code = compile(source, fn, "exec")
dis(code)
if __name__ == "__main__":
_test()
|
x=None):
o = copy.deepcopy(self)
if x: o.validates(x)
return o
def render(self):
out = ''
out += self.rendernote(self.note)
out += '<table class="formtab table table-bordered">\n'
out += '<thead ><tr class=active><th>%s</th><th class=rtd><a class="btn"\
... | ' % net.websafe(note)
| else: return ""
def addatts(self):
# add leading space for backward-compatibility
return " " + str(self.attrs)
class AttributeList(dict):
def copy(self):
return AttributeList(self)
def __str__(self):
return " ".join(['%s="%s"' % (k, net.websafe(v)) for k, ... |
stream_info.iteritems():
self._construct_stream_and_publisher(stream_name, stream_config)
log.debug | ("%r: PlatformAgentStreamPublisher complete", self._platform | _id)
def _construct_stream_and_publisher(self, stream_name, stream_config):
if log.isEnabledFor(logging.TRACE): # pragma: no cover
log.trace("%r: _construct_stream_and_publisher: "
"stream_name:%r, stream_config:\n%s",
self._platform_id, stream_name... |
pe().name
# Commands that list configuration list *all* scopes by default.
default_list_scope = None
# cmd has a submodule called "list" so preserve the python list module
python_list = list
# Patterns to ignore in the commands directory when looking for commands.
ignore_files = r'^\.|^__init__.py$|^#'
SETUP_PARSER ... | lize:
spec.normalize()
return specs
except spack.parse.ParseError as e:
tty.error(e.message, e.string, e.pos * " " + "^")
sys.exit(1)
|
except spack.spec.SpecError as e:
tty.error(e.message)
sys.exit(1)
def elide_list(line_list, max_num=10):
"""Takes a long list and limits it to a smaller number of elements,
replacing intervening elements with '...'. For example::
elide_list([1,2,3,4,5,6], 4)
gives... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
'''
使用paramiko模块远程管理服务器
通过key登录
'''
import paramiko
private_key_path = 'D:\workspace\Python-oldboy\day07\zhangyage_pass'
#key = paramiko.RSAKey.from_private_key_file(filename, password)
key = paramiko.RSAKey.from_private_key_file(private_key_path,'1234 | 5678') #private_key_path是秘钥文件的位置,'12345678'是秘钥的口令
ssh = paramiko.SSHClient() #实例化一个客户端
ssh.set | _missing_host_key_policy(paramiko.AutoAddPolicy()) #自动恢复yes,在我们使用ssh客户端链接的时候第一次的时候都会让我们输入一个yes确定的
ssh.connect('192.168.75.133', 22, username='root', pkey=key)
stdin,stdout,stderr = ssh.exec_command('ifconfig') #定义三个变量进行输出,默认输出是个元组会赋值给三个变量
print stdout.read()
ssh.close() |
import exifread
import os
import shutil
import dmcutils
from dmcutils import mylog
report = {}
trashFiles = [
'.DS_Store',
'Thumbs.db',
'.picasa.ini'
]
def processVideo(file):
vp = os.path.join(args.targetFolder,'videos')
if not os.path.exists(vp):
os.mkdir(vp)
outPath = os.path.j... | not os.path.isfile(file):
mylog("File %s does not exist." % file)
return
if str(file).lower().endswith(('.jpg', '.jpeg')):
processImage(file)
report["processImageCount"] += 1
elif str(file).lower().endswith(('.mp4', '.mov', '.avi')):
processVideo(file)
pass
e... | ash" % file)
os.remove(file)
pass
else:
mylog("Unhandled %s " % file)
def scanAndProcessFolders(inputDir):
mylog("Starting in " + inputDir)
fileList = []
for root, dirs, files in os.walk(inputDir):
for file in files:
candidate = os.path.join(root, file)
... |
class _HSPConsumer(object):
def start_hsp(self):
self._hsp = Record.HSP()
def score(self, line):
self. | _hsp.bits, self._hsp.score = _re_search(
r"Score =\s*([0-9.e+]+) bits \(([0-9]+)\)", line,
| "I could not find the score in line\n%s" % line)
self._hsp.score = _safe_float(self._hsp.score)
self._hsp.bits = _safe_float(self._hsp.bits)
x, y = _re_search(
r"Expect\(?(\d*)\)? = +([0-9.e\-|\+]+)", line,
"I could not find the expect in line\n%s" % line)
i... |
pixel width.
Similarly, the number of scanlines must be bigger than of equal to
the pixel height.
Furthermore, we recommend that pitches and lines be multiple of 32
to not break assumption that might be made by various optimizations
in the video decoders, video filters and/or video converters.
'''
VideoCleanup... | char_p),
]
class MediaStats(_Cstruct):
_fields_ = [
('read_bytes', ctypes.c_int ),
('input_bitrate', ctypes.c_float),
('demux_read_bytes', ctypes.c_int ),
('demux_bitrate', ctypes.c_float),
( | 'demux_corrupted', ctypes.c_int ),
('demux_discontinuity', ctypes.c_int ),
('decoded_video', ctypes.c_int ),
('decoded_audio', ctypes.c_int ),
('displayed_pictures', ctypes.c_int ),
('lost_pictures', ctypes.c_int ),
('played_abuffers', cty... |
#!/usr/bin/env python
#
# Jetduino Example for using the Grove Thumb Joystick (http://www.seeedstudio.com/wiki/Grove_-_Thumb_Joystick)
#
# The Jetduino connects the Jetson and Grove sensors. You can learn more about the Jetduino here: http://www.NeuroRoboticTech.com/Projects/Jetduino
#
# Have a question about t... | re 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.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTA... |
# -*- coding: utf-8 -*-
"""
.. module:: MyCapytain.errors
:synopsis: MyCapytain errors
.. moduleauthor:: Thibault Clérice <leponteineptique@gmail.com>
"""
class MyCapytainException(BaseException):
""" Namespacing errors
"""
class JsonLdCollectionMissing(MyCapytainException):
""" Error thrown when ... |
class | DuplicateReference(SyntaxWarning, MyCapytainException):
""" Error generated when a duplicate is found in CtsReference
"""
class RefsDeclError(Exception, MyCapytainException):
""" Error issued when an the refsDecl does not succeed in xpath (no results)
"""
pass
class InvalidSiblingRequest(Excepti... |
# Copyright 2016 Internap
#
# 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, sof... |
class Server(object):
def __init__(self, modul | es):
self.router = router.Router()
self.app = Flask(__name__)
self.api = api.Api(modules, self.app, self.router)
def run(self, *args, **kwargs):
self.app.run(*args, **kwargs) |
sed in static content response. These
headers are contained in an appinfo.HttpHeadersDict, which maps header
names to values (both strings).
"""
return self._FirstMatch(path).http_headers or appinfo.HttpHeadersDict()
def ReadDataFile(data_path, openfile=file):
"""Reads a file on disk, returni... | ders: mimetools.Message containing the HTTP headers of the response.
body: File-like object containing the body of the response.
large_response: Indicates that r | esponse is permitted to be larger than
MAX_RUNTIME_RESPONSE_SIZE.
"""
__slots__ = ['status_code',
'status_message',
'headers',
'body',
'large_response']
def __init__(self, response_file=None, **kwds):
"""Initializer.
Args:
respons... |
PORT = {}
PORT['m | etaManager'] = 10087
CGI_SOCK = {}
CGI_SOCK[ 'metaManager' ] = '/tmp/metaManager_fcgi_so | ck'
SOCK = {}
SOCK[ 'logqueue' ] = '/tmp/logqueue_sock'
PIDPATH = {}
PIDPATH[ 'metaManager' ] = '/var/run/metaManager.server.pid'
PIDPATH[ 'managerChewer' ] = '/var/run/data.chewer.pid'
|
#!/usr/bin/env python3
"""
bootstrap.py will set up a virtualenv for you and update it as required.
Usage:
bootstrap.py # update virtualenv
bootstrap.py fake # just update the virtualenv timestamps
bootstrap.py clean # delete the virtualenv
bootstrap.py -h | --help # p... | -f, --force # do the virtualenv update even if it is up to date
-r, --full-rebuild # delete the virtualenv before rebuilding
-q, --quiet # don't ask for user input
"""
# a script to set up the virtualenv so we can use fabric and tasks
import sys
import getopt
import ve_mgr
def pr... |
# check python version is high enough
ve_mgr.check_python_version(2, 6, __file__)
force_update = False
full_rebuild = False
fake_update = False
clean_ve = False
devel = False
if argv:
try:
opts, args = getopt.getopt(argv[1:], 'hfqr',
['help', 'force... |
ystem.DEBIAN: "/etc/mysql/my.cnf",
operating_system.SUSE: "/etc/my.cnf"}[OS_NAME]
MYSQL_SERVICE_CANDIDATES = ["mysql", "mysqld", "mysql-server"]
MYSQL_BIN_CANDIDATES = ["/usr/sbin/mysqld", "/usr/libexec/mysqld"]
MYCNF_OVERRIDES = "/etc/mysql/conf.d/overrides.cnf"
MYCNF_OVERRIDES_TMP = "/tmp/overrides.cn... | rser(mycnf_contents).parse())
DATADIR = mycnf['datadir']
return DATADIR
class MySqlAppStatus(service.BaseDbStatus):
@classmethod
def get(cls):
if not cl | s._instance:
cls._instance = MySqlAppStatus()
return cls._instance
def _get_actual_db_status(self):
try:
out, err = utils.execute_with_timeout(
"/usr/bin/mysqladmin",
"ping", run_as_root=True, root_helper="sudo",
log_output_on_... |
# The MIT License (MIT)
#
# Copyright (c) 2016 WUSTL ZPLAB
#
# 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, modif... | ng to return a unique causes PyQt to return a wrapper of the wrong type when retrieving an instance of this item as a base
# class pointer from C++. For example, if this item has a child and that child calls self.parentItem(), it would receive a Python object of type
# Qt.QGraphicsRectItem rather than PointIte... | nless PointItem has a correct .type() implementation.
QGRAPHICSITEM_TYPE = UNIQUE_QGRAPHICSITEM_TYPE()
def __init__(self, picker, x, y, w, h, parent_item):
super().__init__(x, y, w, h, parent_item)
self.picker = picker
flags = self.flags()
self.setFlags(
flags |
... |
y = query
def __repr__(self):
return f'{self._token}'
@staticmethod
def tokens2sql(token: Token,
query: 'query_module.BaseQuery'
) -> Iterator[all_token_types]:
from .functions import SQLFunc
if | isinstance(token, Identifier):
# Bug fix for sql parse
if isinstance(token[0], Parenthesi | s):
try:
int(token[0][1].value)
except ValueError:
yield SQLIdentifier(token[0][1], query)
else:
yield SQLConstIdentifier(token, query)
elif isinstance(token[0], Function):
yield SQLFu... |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | s = parser.parse_args()
# Connect to Kudu master server(s).
client = kudu.connect(host=args.masters, port=args.ports)
# Define a schema for | a new table.
builder = kudu.schema_builder()
builder.add_column('key').type(kudu.int64).nullable(False).primary_key()
builder.add_column('ts_val', type_=kudu.unixtime_micros, nullable=False, compression='lz4')
schema = builder.build()
# Define the partitioning schema.
partitioning = Partitioning().add_hash_partitions(... |
import os
import json
from ss_rule_scheme import update_outbound_rules, init_inbound_rules, init_outbound_rules, msg_clear_all_outbound, ss_process_policy_change
base_path = os.path.abspath(os.path.join(os.path.realpath(__file__),
".."))
test_file = os.path.join(base_path, "blackholin... | witch)
#print ("Rule Messages OUTBOUND:: "+str(rule_msgs2))
#if 'changes' in rule_msgs2:
# if 'changes' not in rule_msgs:
# rule_msgs['changes'] = []
# rule_msgs['changes'] += rule_msgs2['changes']
#TODO: Initialize Outbound Policies from RIB
print ("Rule Messages:: "+str(rule_msgs))
for rule in... | Msgs: %s" % rule_msgs) |
###################################### | ########################################
#
# Copyright (C) 2018-2020 Compassion CH (http://www.compassion.ch)
# Releasing children from poverty in Jesus' name
# @author: Emanuel Cino <ecino@compassion.ch>
#
# The licence is in the file __manifest__.py
#
######################################################... | mport reports
|
# -*- coding: utf-8 -*-
""" Validators for wx widgets.
Copyright (c) Karol Będkowski, 2006-2013
This file is part of wxGTD
This is free software; you can redistribute it and/or modify it under the
t | erms of the GNU General Public License as published by the Free Software
Foundation, version 2.
"""
__author__ = "Karol Będkowski"
__copyright__ = "Copyright (c) Karol Będkowski, 2006-2013"
__version__ = '2013-04-21'
__all__ = ['ValidatorDv', 'Validator', 'ValidatorDate', 'ValidatorTime',
'ValidatorColorStr']
... | lidator import Validator, ValidatorDv, ValidatorDate, ValidatorTime, \
ValidatorColorStr
|
#!/usr/bin/env python
import scipy.sparse as sps
from apgl.graph.GeneralVertexList import GeneralVertexList
from apgl.graph.SparseGraph import SparseGraph
numVertices = 10
vList = GeneralVertexList(numVertices)
Wght = sps.lil_matrix((numVertices, numVertices))
graph = SparseGraph(vLis | t, W=Wght, undirected=False)
# Add some edges to the graph.
# Vertices are indexed starting from | 0.
graph[0, 1] = 1
graph[0, 2] = 1
# Set the label of the 0th vertex to [2, 3].
graph.setVertex(0, "abc")
graph.setVertex(1, 123)
print(graph.inDegreeDistribution())
|
import numpy as np
from scipy.stats import skew, kurtosis, shapiro, pearsonr, ansari, mood, levene, fligner, bartlett, mannwhitneyu
from scipy.spatial.distance import braycurtis, canberra, chebyshev, cityblock, correlation, cosine, euclidean, hamming, jaccard, kulsinski, matching, russellrao, sqeuclidean
from sklearn.p... | e, average_precision_score, f1_score, hinge_loss, matthews_corrcoef, precision_score, recall_score, zero_one_loss
from sklearn.metrics.cluster import adjusted_mutual_info_score, adjusted_rand_score, completeness_score, homogeneity_completeness_v_measure, homogeneity_score, mutual_info_score, normalized_mutual_info_scor... | .aggregators import to_aggregator
from boomlet.metrics import max_error, error_variance, relative_error_variance, gini_loss, categorical_gini_loss
from boomlet.transform.type_conversion import Discretizer
from autocause.feature_functions import *
from autocause.converters import NUMERICAL_TO_NUMERICAL, NUMERICAL_TO_CA... |
# Copyright (C) 2014-2015 Andrey Antukh <niwi@niwi.be>
# Copyright (C) 2014-2015 Jesús Espino <jespinog@gmail.com>
# Copyright (C) 2014-2015 David Barragán <bameda@dbarragan.com>
# This program is free software | : you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; ... | ERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from django.db import transaction
from django.db import... |
from __future__ import unicode_literals, division, absolute_import
from builtins import * # pylint: disable=unused-import, redefined-builtin
import os
import logging
import tempfile
from flexget import plugin
from flexget.event import event
log = logging.getLogger('check_subtitles')
class MetainfoSubs(object):
... | info(self, task, config):
# check if explicitly disabled (value set to false)
if config is False:
return
for entry in task.entries:
entry.register_lazy_func(self.get_subtitles, ['subtitles'])
def get_subtitles(self, entry):
if entry.get('subtitles', | eval_lazy=False) or not ('location' in entry) or \
('$RECYCLE.BIN' in entry['location']) or not os.path.exists(entry['location']):
return
from subliminal.core import search_external_subtitles
try:
subtitles = list(search_external_subtitles(entry['location']).valu... |
# Opus/UrbanSim urban simulation software.
# Copyright (C) 2005-2009 University of Washington
# See opus_core/LICENSE
# This is a simple test variable for the interaction of gridcells and households.
from opus_core.variables.variable import Variable
from urbansim.functions import attribute_label
class hhnp... | ble(self.variable_name,
#{"neighborhood":{
#"dept":dept},
| #"household":{
#"prev_dept":prev_dept}},
#dataset = "household_x_neighborhood")
#should_be = array([[1, 0, 0],
#[0, 0, 0],
#[0, 1, 0],
#[0, 0, 1]])
... |
# *****************************************************************************
# Copyright (c) 2020, Intel Corporation All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# Redistributions of sou... | OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
# OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
# OTHERWISE) ARISING IN ANY WAY OUT... | ****************************************
import pandas as pd
from numba import njit
@njit
def series_lt():
s1 = pd.Series([5, 4, 3, 2, 1])
s2 = pd.Series([0, 2, 3, 6, 8])
return s1.lt(s2) # Expect series of False, False, False, True, True
print(series_lt())
|
#!/usr/bin/env python
'''
##BOILERPLATE_COPYRIGHT
##BOILERPLATE_COPYRIGHT_END
'''
import unittest, copy
from testRoot import RootClass
from noink.user_db import UserDB
from noink.entry_db import EntryDB
class AddEntry(Ro | otClass):
def test_AddEntry(self):
userDB = UserDB()
entryDB = EntryDB()
u = userDB.add("jontest", "pass", "Jon Q. Testuser")
title = 'Little Buttercup'
entry = 'There once was a man from Nantucket,' + \
'who kept his wife in a Bucket.' + \
| "Wait... how'd she fit in that bucket anyway?"
e = entryDB.add(copy.deepcopy(title), entry, u)
self.assertTrue(e.title == title)
if __name__ == '__main__':
unittest.main()
|
import io
import pytest
from contextlib import redirect_stdout
from mock import patch
from mythril.mythril import MythrilLevelDB, MythrilConfig
from mythril.exceptions import CriticalError
@patch("mythril.ethereum.interface.leveldb.client.EthLevelDB.search")
@patch("mythril.ethereum.interface.leveldb.client.ETH_DB",... | ("mythril.ethereum.interface.leveldb.client.LevelDBWriter", return_value=None)
def test_leveldb_hash_search_incorrect_input(f1, f2, f3):
config = MythrilConfig()
config.set_api_leveldb("some path")
leveldb | _search = MythrilLevelDB(leveldb=config.eth_db)
with pytest.raises(CriticalError):
leveldb_search.contract_hash_to_address("0x23")
@patch(
"mythril.ethereum.interface.leveldb.client.EthLevelDB.contract_hash_to_address",
return_value="0xddbb615cb2ffaff7233d8a6f3601621de94795e1",
)
@patch("mythril.e... |
# -*- coding: utf-8 -*-
"""
Contains functions to plot the results of the dustydiffusion test.
@author: ibackus
"""
import matplotlib.pyplot as plt
import numpy as np
import pynbody
import diskpy
#sim, epsEstimator, ts, runpars = analyze.loadSim(simdir)
def crossSection(sim, ts, crossSectionTimes=[0, 1, 10]):
""... | ectionTimes = crossSectionTimes.reshape(crossSectionTimes.size)
if np.ndim(crossSectionTimes) == 0:
crossSectionTimes = crossSectionTimes[None]
nPlots = len(crossSectionTimes)
# Plot
axs = diskpy.plot.gridplot(1, nPlots, square=True)
fig = plt.gcf()
for iPlot in range(... | ts):
ax = axs[iPlot]
iTime = abs(ts - crossSectionTimes[iPlot]).argmin()
t = ts[iTime]
f = sim[iTime]
im=pynbody.plot.sph.image(f, 'dustFrac', width=1, log=False, vmin=0,
vmax = 0.11, cmap='cubehelix_r',
... |
s), "1234")
self.assertEqual(s.value, 0x1234)
s = c_ushort.__ctype_le__(0x1234)
self.assertEqual(bin(struct.pack("<h", 0x1234)), "3412")
self.assertEqual(bin(s), "3412")
self.assertEqual(s.value, 0x1234)
def test_endian_int(self):
if sys.byteorder == "littl... |
self.assertIs(c_double.__ctype_le__, c_double)
self.assertIs(c_double.__ctype_be__.__ctype_le__, c_double)
else:
self.assertIs(c_double.__ctype_be__, c_double)
self.assertIs(c_double.__ctype_le__.__ctype_be__, c_double)
s = c_double(math.pi | )
self.assertEqual(s.value, math.pi)
self.assertEqual(bin(struct.pack("d", math.pi)), bin(s))
s = c_double.__ctype_le__(math.pi)
self.assertEqual(s.value, math.pi)
self.assertEqual(bin(struct.pack("<d", math.pi)), bin(s))
s = c_double.__ctype_be__(math.pi)
... |
# coding: utf-8
"""
An API to insert and retrieve metadata on cloud artifacts.
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501
OpenAPI spec version: v1alpha1
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
... | t indicates the status of the current scan. # noqa: E501
:return: The operation of this DiscoveryDiscoveredDetails. # noqa: E501
:rtype: GooglelongrunningOperation
"""
return self._operation
@operatio | n.setter
def operation(self, operation):
"""Sets the operation of this DiscoveryDiscoveredDetails.
Output only. An operation that indicates the status of the current scan. # noqa: E501
:param operation: The operation of this DiscoveryDiscoveredDetails. # noqa: E501
:type: Googlel... |
#
# Copyright (c) 2013-2018 Quarkslab.
# This file is part of IRMA project.
#
# 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 in the top-level directory
# of this distribution and at:
#
# http:... | sess.disconnect()
self._sess = None
def _upload(self, remote, fobj):
mode = LIBSSH2_SFTP_S_IRUSR | LIBSSH2_SFTP_S_IWUSR | \
LIBSSH2_SFTP_S_IRGRP | LIBSSH2_SFTP_S_IROTH
opt = LIBSSH2_FXF_CREAT | LIBSSH2_FXF_WRITE
with self._client.open(remote, opt, mode) as rfh:
... | for chunk in iter(lambda: fobj.read(1024*1024), b""):
rfh.write(chunk)
def _download(self, remote, fobj):
with self._client.open(remote, 0, 0) as rfh:
for size, data in rfh:
fobj.write(data)
def _ls(self, remote):
with self._client.opendir(remote) a... |
#/usr/bin/env python
import QtTesting
import QtTestingImage
object1 = 'pqClientMainWindow/MainControlsToolbar/actionOpenData'
QtTesting.playCommand(object1, 'activate', '')
object2 = 'pqClientMainWindow/FileOpenDialog'
QtTesting.playCommand(object2, 'filesSelected', '$PARAVIEW_DATA_ROOT/SPCTH/Dave_Karelitz_Small/spct... | and(object4, 'activate', '')
object9 = 'pqClientMainWindow/proxyTabDock/proxyTabWidget/qt_tabwidget_stackedwidget/objectInspector/ScrollArea/qt_scrollarea_viewport/PanelArea/Editor/CutFunction/pqImplicitPlaneWidget/show3DWidget'
QtTesting.playCommand(object9, 'set_boolean', 'false')
# DO_IMAGE_COMPARE
snapshotWidget = ... | mage.compareImage(snapshotWidget, 'CTHAMRClip.png', 300, 300)
|
# -*- coding: utf-8 -*-
from __future__ import uni | code_literals
from django.apps import AppConfig
class PluginrepoCo | nfig(AppConfig):
name = 'pluginrepo'
|
from ritoapi.endpoints.match_v3 import MatchV3
import threading
def _load_matches(match_v3, sample_region, sample_match_id, count):
for i | in range(count):
data = match_v3.matches(sample_region, sample_match_id)
assert(data['gameId'] == sample_match_id)
def test_matches_stress(sample_api_key, sample_rate_limit, sample_region, sample_match_id):
match_v3 = MatchV3(sample_api_key, sample_rate_limit)
threads = []
for i in range(... | )
for t in threads:
t.join()
|
from future import standard_library
standard_library.install_aliases()
from builtins import object
import threading
from time import time
import random
import queue
from ..common import log
class Scheduler(object):
"""
A simple scheduler which schedules the periodic or once event
"""
import sortedcon... |
if ready_jobs:
log.logger.info("Get %d ready jobs, next duration is %f, "
"and there are %s jobs scheduling",
| len(ready_jobs), sleep_time, total_jobs)
ready_jobs.sort(key=lambda job: job.get("priority", 0), reverse=True)
return (sleep_time, ready_jobs)
def add_jobs(self, jobs):
with self._lock:
now = time()
job_set = self._jobs
for job in jobs:
... |
]])
def test_assignment_indexerror(self):
self.assertRaises(IndexError, self.phi.assignment, [10])
self.assertRaises(IndexError, self.phi.assignment, [1, 3, 10, 5])
self.assertRaises(IndexError, self.phi.assignment, np.array([1, 3, 10, 5]))
self.assertRaises(IndexError, self.phi4.a... | [self.tup1, self.tup3]),
{self.tup1: 2, self.tup3: 4})
def test_get_cardinality_scopeerror(self):
self.assertRaises(ValueError, self.phi.get_cardinality, ['x4'])
self.assertRaises(ValueError, self.phi4.get_cardinality, [('x1', 'x4')])
self.assertRaises(ValueError, ... | 'x4'))])
def test_get_cardinality_typeerror(self):
self.assertRaises(TypeError, self.phi.get_cardinality, 'x1')
def test_marginalize(self):
self.phi1.marginalize(['x1'])
np_test.assert_array_equal(self.phi1.values, np.array([[6, 8],
... |
from collections import deque
from threading import RLock, Condition, currentThread
import sys
import time
class OnRequestQueue:
ListUsedModFunctions = ("append", "popleft")
class QueueEnd:
def __init__(self, queueList=None):
if queueList is not None:
self.q = queueList
else:
self.q = deque()
se... | , reprname=None, extraCall=None):
self.targetQueue = targetQueue
self.name = name
self.rep | rname = reprname
self.extraCall = extraCall
def __call__(self, *args, **kwargs):
if not "timestamp" in kwargs:
kwargs["timestamp"] = time.time()
if self.extraCall:
self.extraCall(*args, **kwargs)
self.targetQueue.put((self, args, kwargs))
def __repr__(self):
if self.reprname:
return self.reprname
... |
import random
from cloudbot.util import http, formatting
def api_get(kind, query):
"""Use the RESTful Google Search API"""
url = 'http://ajax.googleapis.com/ajax/services/search/%s?' \
'v=1.0&safe=moderate'
return http.get_json(url % kind, q=query)
# @hook.command("googleimage", "gis", "image... | sed['responseStatus'] < 300:
raise IOError('error searching for pages: {}: {}'.format(parsed['responseStatus'], ''))
if not parsed['responseData']['results']:
return 'No | results found.'
result = parsed['responseData']['results'][0]
title = http.unescape(result['titleNoFormatting'])
title = formatting.truncate_str(title, 60)
content = http.unescape(result['content'])
if not content:
content = "No description available."
else:
content = http.htm... |
#!/usr/bin/env python2
import os
import sys
import json
import yaml
def main():
with open(sys.argv[1], 'rb') as f:
known_issues = yaml.safe_load(f.read())
skipstrings = [
'passed in strict mode',
'passed in non-strict mode',
'failed in strict mode as expected',
'failed... |
print(line) # print error list as is, then refined version later
if 'failed tests' in line.lower():
in_failed_tests = True
continue
if in_failed_tests and line.strip() == '':
in_failed_tests = False
continue
if in_failed_tests:
... |
tmp = line.strip().split(' ')
test = tmp[0]
matched = False
for kn in known_issues:
if kn.get('test', None) != test:
continue
if kn.has_key('diagnosed'):
tofix_count += 1
diagnos... |
import unittest
from katas.kyu_6.longest_2_character_substring import substring
class SubstringTestCase(unittest.TestCase):
def test_equals(self):
self.assertEqual(substring(''), '')
def test_equals_2(self):
self.assertEqual(substring('a'), 'a')
def test_equals_3(self):
self.ass... | (self):
self.assertEqual(substring('abc'), 'ab')
def test_equals_8(self):
self.assertEqual(substring('abacd'), 'aba')
def test_equals_9(self):
self.assertEqual(substring('abcba' | ), 'bcb')
def test_equals_10(self):
self.assertEqual(substring('bbacc'), 'bba')
def test_equals_11(self):
self.assertEqual(substring('ccddeeff'), 'ccdd')
def test_equals_12(self):
self.assertEqual(substring('abacddcd'), 'cddcd')
def test_equals_13(self):
self.assertEq... |
import sip
sip.setdestroyonexit(0)
import os, shutil
import numpy as np
from sparkle.QtWrapper import Q | tGui
tempfolder = os.path.join(os.path.abspath(os.path.dirname(__file__)), u"tmp")
app = None
# executes once before all tests
def setup():
if not os.path.exists(tempfolder):
os.mkdir(tempfolder)
np.warnings.filterwarnings('ignore', "All-NaN axis encountered", RuntimeWarning)
global app
app =... | app = None
|
# -*- coding: utf-8 -*-
# Resource object code
#
# Created by: The Resource Compiler for PyQt5 (Qt v5.7.1)
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore
qt_resource_data = b"\
\x00\x00\x05\x96\
\x89\
\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\
\x00\x00\x18\x0... | x6c\x90\x59\x48\x60\x00\x00\x00\x18\x74\x45\x58\x74\x43\x72\x65\
\x61\x74\x69\x6f\x6e\x20\x54\x69\x6d | \x65\x00\x32\x30\x30\x38\x2d\
\x31\x32\x2d\x31\x32\x58\x2e\x3b\xbf\x00\x00\x00\x52\x74\x45\x58\
\x74\x43\x6f\x70\x79\x72\x69\x67\x68\x74\x00\x43\x43\x20\x41\x74\
\x74\x72\x69\x62\x75\x74\x69\x6f\x6e\x2d\x53\x68\x61\x72\x65\x41\
\x6c\x69\x6b\x65\x20\x68\x74\x74\x70\x3a\x2f\x2f\x63\x72\x65\x61\
\x74\x69\x76\x65\x63\x6f\x... |
#!/usr/bin/env python
from efl import evas
import unittest
class TestBoxBasics(u | nittest.TestCase):
def setUp(self):
self.canvas = evas.Canvas(method="buffer",
size=(400, 500),
viewport=(0, 0, 400, 500))
self.canvas.engine_info_set(self.canvas.engine_info_get())
def tearDown(self):
self.canvas.delet... | ructor(self):
box = evas.Box(self.canvas)
self.assertEqual(type(box), evas.Box)
box.delete()
def testConstructorBaseParameters(self):
size = (20, 30)
pos = (40, 50)
geometry = (60, 70, 80, 90)
color = (110, 120, 130, 140)
# create box using size/pos
... |
""" Return the values at the given indices. """
@_convert
@_vcheckother
@schemed(BACKEND_PREFIX)
def dot(self, other):
""" Return the dot product"""
@schemed(BACKEND_PREFIX)
def _getvalue(self, index):
"""Helper function to return a single v... | @_convert
def trim_zeros(self):
"""Remove the leading and trailing zeros.
"""
tmp = self.numpy()
f = len(self)-len(_numpy.trim_zeros(tmp, trim='f'))
b = len(self)-len(_numpy.trim_zeros(tmp, trim='b'))
r | eturn self[f:len(self)-b]
@_returntype
@_convert
def view(self, dtype):
"""
Return a 'view' of the array with its bytes now interpreted according
to 'dtype'. The location in memory is unchanged and changing elements
in a view of an array will also change the original array.
... |
#!/usr/bin/env python
import socket, ssl
# This is a copy of _RESTRICTED_SERVER_CIPHERS from the current tip of ssl.py
# <https://hg.python.org/cpython/file/af793c7580f1/Lib/ssl.py#l174> except that
# RC4 has been added back in, since it was removed in Python 2.7.10,
# but SSLStreamConnection only supports RC4 cipher... | he problem, but it didn't do so for me, and it cause | d the error:
# ssl.SSLError: [SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:581)
#
# Whereas the SSLEOFError doesn't prevent the server from working
# (it seems to happen only when the server is first started, and it
# stops happening if we simply ignore it and try ag... |
from pystorm.bolt import BasicBolt
class SentenceSplitterBolt(BasicBolt):
def p | rocess(self, tup):
sentence = tup.values[0]
| for word in sentence.split(' '):
BasicBolt.emit(word)
if __name__ == '__main__':
SentenceSplitterBolt().run()
|
#!/usr/bin/python
#
# Copyright 2014 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required b... | ate
class AddCampaign(webapp2.RequestHandler):
"""View that either adds a Campaign or displays an error message."""
def post(self):
| """Handle post request."""
client_customer_id = self.request.get('clientCustomerId')
campaign_name = self.request.get('campaignName')
ad_channel_type = self.request.get('adChannelType')
budget = self.request.get('budget')
template_values = {
'back_url': '/showCampaigns?clientCustomerId=%... |
# -*- coding: utf-8 -*-
#
# 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
... | 4bf1dff
Revises: bdaa763e6c56
Create Date: 2017-08-15 15:12:13.845074
"""
# revision identifiers, used by Alembic.
revision = '947454bf1dff'
down_revision = 'bdaa763e6c56 | '
branch_labels = None
depends_on = None
from alembic import op
import sqlalchemy as sa
def upgrade():
op.create_index('ti_job_id', 'task_instance', ['job_id'], unique=False)
def downgrade():
op.drop_index('ti_job_id', table_name='task_instance')
|
# -*- coding: utf-8 -*-
# Generated by Django 1.10.1 on 2016-12-08 19:59
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migratio... | gistics.Fleet'),
),
migrations.AddField(
model_name='driver',
name='pending_fleets',
field=models.ManyToManyField(blank=True, related_name='pending_fleets', to='logistics.Fleet'),
),
migrations.AddField(
| model_name='driver',
name='user',
field=models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL),
),
]
|
import sys
def find_motif_locations(dna, motif):
motif_locations = []
if len(dna) < len(motif):
raise ValueError('Motif can\'t be shorter tha | n sequence')
if len(motif) == len(dna) and motif != dna:
return motif_locations
for _ in range(len(dna) - len(motif) + 1):
if dna[_:_ + len(motif)] == motif:
motif_locations.append(_ + 1)
return motif_locations
if __name__ == '__main__':
sequences = open(sys.argv[1]).read... | for _ in
find_motif_locations(
sequences[0],
sequences[1]
)
)
)
|
"""
==============
Blob Detection
==============
Blobs are bright on dark or dark on bright regions in an image. In
this example, blobs are detected using 3 algorithms. The image used
in this case is the Hubble eXtreme Deep Field. Each bright dot in the
image is a star or a galaxy.
Laplacian of Gaussian (LoG)
-------... | arey=True,
subplot_kw={'adjustable': 'box-forced'})
ax = axes.ravel()
for idx, (blobs, color, title) in enumerate(sequence):
ax[idx].set_title(title)
ax[idx].imshow(image, interpolation='nearest')
for blob in blobs:
y, x, r = blob
c = plt.Circle((x, | y), r, color=color, linewidth=2, fill=False)
ax[idx].add_patch(c)
ax[idx].set_axis_off()
plt.tight_layout()
plt.show()
|
__author__ = 'yusaira-khan'
import unittest
import un_iife_ize.un_iife_ize as un_iife_ize
class CheckVar(unittest.TestCase):
def test_simple(self):
statement = [('var hello,world=5;', 0)]
exp = [('hello=undefined,world=5;', 0)]
v = un_iife_ize.Var(statement)
v.extract_all()
... | print(ret)
self.assertEqual(ret, exp)
def test_deliberate_iife_barc(self):
statement = [('var hello = (function(){;}())', 0)]
exp = [(' hello = (function(){;}())', 0)]
v = un_iife_ize.Var(statement)
v.extract_all()
ret = v.all
print(ret, len(exp[0][0]),... | [0]))
self.assertEqual(ret, exp)
def test_double_assignment(self):
statement = [('var hello=wow=;', 0)]
exp = [('hello=wow=', 0)]
v = un_iife_ize.Var(statement)
v.extract_all()
ret = v.all
print(ret)
self.assertEqual(ret, exp)
def test_inside_fu... |
i, ei, ei_start_pc)
i += 2
ei_end_pc, = struct.unpack('>H', s[i : i + 2])
print '0x%08x exception_table[%d].end_pc=%d' % (
i, ei, ei_end_pc)
i += 2
ei_handler_pc, = struct.unpack('>H', s[i : i + 2])
print '0x%08x exception_table[%d].handler_pc=%d' % (
i, ei, ei_end_pc)
... | s, i, i + ai_attribute_length,
constant_class=constant_class, constant_utf8=constant_utf8,
const | ant_name_and_type=constant_name_and_type,
constant_method_ref=constant_method_ref,
constant_interface_method_ref=constant_interface_method_ref)
else:
ai_info = s[i : i + ai_attribute_length]
print '0x%08x method[%d].attribute[%d].info=%r' % (
i, fi, ai, ai_info)... |
import socket
from selectors import DefaultSelector, EVENT_WRITE, EVENT_READ
sock = socket.socket()
sock.setblocking(False)
selector = DefaultSelector()
urls_todo = set(['/'])
seen_urls = set(['/'])
class Fetcher:
def __init__(self, url):
self.response = b''
self.url = url
self.sock = ... | def connected(self, key, mask):
print('connected!')
selector.unregister(key.fd)
request = 'GET {} HTTP/1.0\r\nHost: xkcd.com\r\n\r\n'.format(self.url)
self.sock.send(request.encode('ascii'))
# Register the next callback
selector.register(key.fd,
... | # 4K chunks of data
if chunk:
self.response += chunk
else:
selector.unregister(key.fd) # Done reading
links = self.parse_links()
# Set logic
for link in links.difference(seen_urls):
urls_todo.add(link)
Fetcher... |
ue = batch_size//repeats
# Batch it up.
patches = tf.train.shuffle_batch(
[patches],
batch_size=unique,
num_threads=2,
capacity=min_queue + 3 * batch_size,
enqueue_many=True,
min_after_dequeue=min_queue)
print('PATCHES =================',patches.get_shape().as_lis... | ring),
'channelgain': tf.FixedLenFeatur | e([], tf.string),
'burst_raw': tf.FixedLenFeature([], tf.string),
'merge_raw': tf.FixedLenFeature([], tf.string),
'depth': tf.FixedLenFeature([], tf.int64),
'height': tf.FixedLenFeature([], tf.int64),
'width': tf.FixedLenFeature([], tf.int64),
})
return decode(... |
#!/usr/bin/python
__version__ = '0.0.1'
im | port p | ysimplesoap.client
import pysimplesoap.simplexml
from zimbrasoap.soap import soap,admin,mail
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('lumos', '0009_proglang_slug'),
]
operations = [
migra | tions.AddField(
mo | del_name='softskills',
name='slug',
field=models.SlugField(default=''),
preserve_default=False,
),
]
|
from __future__ import absolute_import
import momoko
from tornado import gen
from psycopg2.extras import RealDictConnection
def initialize_database():
| db = momoko.Pool(
dsn='''dbname=nightson user=vswamy password=vswamy host=localhost port=5432''',
size=5,
connection_factory=RealDictConnection,
)
db.connect()
return db
class BaseEntityManager(object):
db = initialize_database()
def __init__(self):
pass
def | __init__(self, request):
self.request = request
@gen.coroutine
def execute_sql(self, sql):
''' Executes an sql statement and returns the value '''
cursor = yield BaseEntityManager.db.execute(sql)
raise gen.Return(cursor)
def get_value(self, key):
''' Gets a value g... |
from enum import Enum
clas | s EnumContainerStatus(Enum):
running = "running"
halted = "halted"
networkKilled = "networkKil | led"
|
#
# This file is part of pysmi software.
#
# Copyright (c) 2015-2016, Ilya Etingof <ilya@glas.net>
# License: http://pysmi.sf.net/license.html
#
import os
import sys
import time
from pysmi.reader.base import AbstractReader
from pysmi.mibinfo import MibInfo
from pysmi.compat import decode
from pysmi import debug
from py... | ignoreErrors (bool): ignore filesystem access errors
"""
self._path = os.path.normpath(path)
self._recursive = recursive
self._ignoreErrors = ignoreErrors
self._indexLoaded = False
def __str__(self): return '% | s{"%s"}' % (self.__class__.__name__, self._path)
def getSubdirs(self, path, recursive=True, ignoreErrors=True):
if not recursive:
return [path]
dirs = [path]
try:
subdirs = os.listdir(path)
except OSError:
if ignoreErrors:
return d... |
# -*- coding: utf-8 -*-
# This file is part of emesene.
#
# emesene is free software; you can redistribute it and/or m | odify
# it under the terms of the GNU General Public License as published by
# | the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# emesene is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU ... |
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
('My Name', 'your_email@domain.com'),
)
MANAGERS = ADMINS
import tempfile, os
from django import contrib
tempdata = tempfile.mkdtemp()
approot = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
adminroot = os.path.join(contrib.__path__[0], 'admin')
DATAB... | sors.auth",
"django.core.context_processors.request",
"django.core.context_processors.debug",
#"django.core.context_processors.i18n", this is AMERICA
"django.core.context_processors.media",
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.staticfile... | 'djcelery',
'delegate',
'signalqueue',
)
LOGGING = dict(
version=1,
disable_existing_loggers=False,
formatters={ 'standard': { 'format': '%(asctime)s [%(levelname)s] %(name)s: %(message)s' }, },
handlers={
'default': { 'level':'DEBUG', 'class':'logging.StreamHandler', 'formatter':'stan... |
# -*- coding:utf-8 -*-
'''
fio测试工具执行脚本
'''
import os,shutil,re,time,sys,copy
from test import BaseTest
from lpt.lib.error import *
from lpt.lib import lptxml
from lpt.lib import lptlog
from lpt.lib.share import utils
from lpt.lib import lptreport
class TestControl(BaseTest):
'''
继承BaseTest属性和方法
'''
... | [1]
dict1 = result_list[-2][1]
parallel_dict = copy.deepcopy(parallel_template)
parallel_dict['parallel'] = str(count / 2)
parallel_dict['iter'] = 'Average'
tmp_list.append(parallel_dict)
tmp_list.app... | esult_dict = {}
line = line.replace(',','')
line = line.split()
for l,v in zip(labels, (line[1].split('=')[1][:-2], line[2].split('=')[1][:-4], line[3].split('=')[1][:-4], line[4].split('=')[1][:-4], line[5].split('=')[1][:-4], line[6].split('=')[1][:-4])):
result_dict[l] = "%s" % v
... |
0:
self.upper_preview_node = (point, i)
m = Marker(vector3D([point]), dynamic=False)
m.set_color('blue')
self.temp_point += [m]
break
def add_line(self, event_callback):
event = event_callback.getEvent()
... | e
return False
def show_upper_att_widget(objs):
for obj in objs:
if not isinstance(obj, Upper_Att_Marker):
return False
return True
def show_lower_att_widget(objs):
for obj in objs:
if not isinstance(ob... | return False
return True
selected_objs = self.shape.selected_objects
if selected_objs:
self.layer_selection.setEnabled(True)
self.target_length.setEnabled(True)
self.layer_selection.setItemByText(selected_objs[0].layer)
# self... |
from proboscis import test
@test(groups=['benchmark.discovery'])
class BenchmarkDiscoveryTests(object):
def __init__(self):
| pass
| |
'''
Creat | ed on May 26, 2012
@author: Charlie
'''
class MyPackageMod0 | 1(object):
def __init__(self):
pass |
"""Controllers for | the mo | zzarella application."""
|
# -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2017-01-12 17:08
from __future__ import unicode_literals
from django.db | import migrations, models
class Migration(migrations.Migration):
dependencies = [
('themes', '0002_auto_20170110_1809'),
]
operations = [
migrations.AlterField(
model_name='themes',
name='css_style',
field=models.CharField(choices=[('green', 'Green'), ... | ax_length=50, verbose_name='Css Style'),
),
]
|
from django.shortcuts import redirect
from django.template.response import TemplateResponse
from ..forms import AnonymousUserShippingForm, ShippingAddressesForm
from ...userprofile.forms import get_address_form
from ...userprofile.models import Address
from ...teamstore.utils import get_team
def anonymous_user_shipp... | country.code,
initial={'country': request.country})
addresses_form = ShippingAddressesForm(
data, additional_addresses=additional_addresses,
initial={'address': shipping_address.id})
elif shipping_address:
address | _form, preview = get_address_form(
data, country_code=shipping_address.country.code,
instance=shipping_address)
addresses_form = ShippingAddressesForm(
data, additional_addresses=additional_addresses)
else:
address_form, preview = get_address_form(
dat... |
ice, SwitchEntity):
"""Represent a Rachio state that can be toggled."""
def __init__(self, controller):
"""Initialize a new Rachio switch."""
super().__init__(controller)
self._state = None
@property
def name(self) -> str:
"""Get a name for this switch."""
retur... | ER]
self._zone_enabled = | data[KEY_ENABLED]
self._entity_picture = data.get(KEY_IMAGE_URL)
self._person = person
self._shade_type = data.get(KEY_CUSTOM_SHADE, {}).get(KEY_NAME)
self._zone_type = data.get(KEY_CUSTOM_CROP, {}).get(KEY_NAME)
self._slope_type = data.get(KEY_CUSTOM_SLOPE, {}).get(KEY_NAME)
... |
#!/usr/bin/python
import time
import RPi.GPIO as GPIO
# remember to change the GPIO values below to match your sensors
# GPIO output = the pin that's connected to "Trig" on the sensor
# GPIO input = the pin that's connected to "Echo" on the sensor
def reading(sensor):
# Disable any warning message such as GPIO pins... | rasonic burst to be received
# to get a pulse length of 10Us we need to start the pulse, then
# wait for 10 microseconds, then stop the pulse. This will
# result in the pulse length being 10Us.
# start the pulse on the GPIO pin
# change this value to the pin you are using
# GPIO output = the pin that's co... | ep(0.00001)
# stop the pulse after the time above has passed
# change this value to the pin you are using
# GPIO output = the pin that's connected to "Trig" on the sensor
GPIO.output(22, False)
# listen to the input pin. 0 means nothing is happening. Once a
# signal is received the value will be 1 so the ... |
import configparser
CONFIG_PATH = 'accounting.conf'
class MyConfigParser():
def __init__(self, config_path=CONFIG_PATH):
self.config = configparser.ConfigParser(allow_no_value=True)
self.config.read(config_path)
def config_section_map(self, section):
""" returns all configuration op... | key: config_option and | value: the read value in the file"""
dict1 = {}
options = self.config.options(section)
for option in options:
try:
dict1[option] = self.config.get(section, option)
if dict1[option] == -1:
DebugPrint("skip: %s" % option)
... |
import os
from bs4 import BeautifulSoup
count = pd.DataFrame(columns = ['filename', 'count'])
for folder, subs, files in os.walk('data | /xml'):
for filename in files:
try:
if ('.xml' in filename) and (filename[0] != '.'):
f = open(os.path.join(folder, filename))
soup = BeautifulSoup(f.read())
tokens = soup.findAll('token')
tokens_arr = [token.text for token in tokens]
text = ' '.join(tokens_arr)
f = open('data/text/'+... | except Exception as e:
print e
continue |
Cache jedi environments to avoid startup cost."""
try:
return _cached_jedi_environments[venv]
except KeyError:
logger.info('Creating jedi environment: %s', venv)
if venv is None:
jedienv = jedi.api.environment.get_default_environment()
else... | get_script_path_kwargs(cls, sys_path, virtual_envs, sys_path_append):
result = {}
if jedi_create_environment:
# Need to specify some environment explicitly to workaround
# https://github.com/davidhalter/jedi/issues/1242. Otherwise jedi
# will create a lot of child pro... | primary_env, virtual_envs = virtual_envs[0], virtual_envs[1:]
primary_env = path_expand_vars_and_user(primary_env)
else:
primary_env = None
try:
result['environment'] = jedi_create_environment(primary_env)
except Exception:
... |
# Copyright (c) LinkedIn Corporation. All rights reserved. Licensed under the BSD-2 Clause license.
# See LICENSE in the project root for license information.
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import urllib.parse
import requests
from testutils import prefix, api_v0
HOUR = 60 * 60
DAY = HOUR * 24
@prefix... | les/' + schedule_id), json={'team': team_name, 'roster': roster_name})
assert re.status_code == 200
# test delete schedule
re = requests.delete(api_v0('schedules/' + schedule_id))
assert re.status_code == 200
# verify schedule was deleted
re = requests.get(api_v0('teams/%s/rosters/%s/schedules... | st_v0_advanced_schedule')
def test_api_v0_advanced_schedule(team, roster, role, schedule):
team_name = team.create()
roster_name = roster.create(team_name)
role_name = role.create()
schedule_id = schedule.create(team_name,
roster_name,
... |
# Copyright (c) 2010 ActiveState Software Inc. All rights reserved.
"""
pypm.common.util
~~~~~~~~~~~~~~~~
Assorted utility code
"""
import os
from os import path as P
import sys
import re
from contextlib import contextmanager
import logging
import time
import textwrap
from datetime import datetime
f... | ttp://pypm-free.as.com
be = http://pypm-be.as.com
staging = http://pypm-staging.as.com
default = be free
QA = staging default
What this class produces (self.mapping):
{
'free': [factory('free', 'http://pypm-free.as.com')],
'be': [fac | tory('be', 'http://pypm-be.as.com')],
'staging': [factory('staging', 'http://pypm-staging.as.com')],
'default': [factory('be', 'http://pypm-be.as.com'),
factory('free', 'http://pypm-free.as.com')],
'QA': [factory('staging', 'http://pypm-staging.as.com'),
... |
from typing import Any
# Copyright (c) | 2016 Google Inc. (under http://www.apache.org/licenses/LICENSE-2.0)
# If not annotate_pep484, info in pyi files is augmented with heuristics to decide if un-annotated
# arguments are "Any" or "" (like "self")
class B(object):
def __init__(self):
pass
def f(self, x):
# type: (e1) -> None
... |
pass
@staticmethod
def f3(x, y):
# type: (Any, e3) -> None
pass
@classmethod
def f4(cls):
pass
|
# Copyright: (c) 2018, Toshio Kuratomi <tkuratomi@ansible.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
"""
Context of the running Ansible.
In the... | lCLIArgs.from_options(cli_args)
def cliargs_deferred_ge | t(key, default=None, shallowcopy=False):
"""Closure over getting a key from CLIARGS with shallow copy functionality
Primarily used in ``FieldAttribute`` where we need to defer setting the default
until after the CLI arguments have been parsed
This function is not directly bound to ``CliArgs`` so that ... |
from django.test.testcases import SimpleTestCase
from corehq.apps.app_manager.const import APP_V2
from corehq.apps.app_manager.models import Application, Module, OpenCaseAction, ParentSelect, OpenSubCaseAction, \
AdvancedModule, LoadUpdateAction, AdvancedOpenCaseAction
from mock import patch
class CaseMetaTest(Si... | rence_id='parent'
))
m2 = self._make_module(app, 2, 'grand child')
m3 = app.add_module(AdvancedModule.new_mod | ule('Module3', lang='en'))
m3.case_type = 'other grand child'
m3f0 = m3.new_form('other form', 'en')
m3f0.actions.load_update_cases.append(LoadUpdateAction(
case_type='child',
case_tag='child'))
m3f0.actions.open_cases.append(AdvancedOpenCaseAction(
na... |
import aifc
import sndhdr
import utils
class Aiff:
def __init__(self, filename):
assert sndhdr.what(filename).filetype == 'aiff'
x = aifc.open(filename)
data = x.readframes(x.getnframes())
self.nchannels = x.getnchannels()
self.sampwidth = x.getsampwidth()
self.f... | .from_buffer(data).reshape(-1, x.getnchannels())
def save(self, filename):
y = aifc.open(filename, 'wb')
y.setnchannels(self.nchannels)
y.setsampwidth(self.sampwidth)
y | .setframerate(self.framerate)
y.writeframes(self.sig.flatten().tobytes())
def save_channel(self, filename, channel):
y = aifc.open(filename, 'wb')
y.setnchannels(1)
y.setsampwidth(self.sampwidth)
y.setframerate(self.framerate)
y.writeframes(self.sig[:, channel].flatt... |
from pythonforandroid.recipe import PythonRecipe
class Asn1cryptoRecipe(PythonRecipe):
name = 'asn1crypto'
version = '0.23.0'
url = 'https://pypi.python.org/packages/31/53/8bca924b30cb79d6d70dbab6a99e8731d1e4dd3b090b7f3d8412a8d8ffbc/asn1crypto-0.23.0.tar.gz#md5=97d54665c397b72b165768398dfdd876'
depend... | lse
recipe = Asn1cryptoRecipe()
| |
# is set to its default value, we don't write it out.
if value:
if key in self.fields and self.fields[key].is_set_on(self):
try:
xml.set(key, six.text_type(value))
except UnicodeDecodeError:
exception_me... | # it doesn't matter what the actual speed is for the purposes of deserializing.
youtube_id = deserialize_field(cls.youtube_id_1_0, pieces[1])
ret[speed] = youtube_id
ex | cept (ValueError, IndexError):
log.warning('I |
"""Provide functionality to keep track of devices."""
import asyncio
import voluptuous as vol
from homeassistant.loader import bind_hass
from homeassistant.components import group
from homeassistant.helpers import discovery
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.typing import ... |
from . import legacy, setup
from .config_entry import ( # noqa # pylint: disable=unused-import
async_setup_entry,
async_unload_entry,
)
from .legacy import DeviceScanner # noqa # pylint: disable=unused-import
from .const import (
ATTR_ATTRIBUTES,
ATTR_BATTERY,
ATTR_CONSIDER_HOME,
ATTR_DEV_... | TR_SOURCE_TYPE,
CONF_AWAY_HIDE,
CONF_CONSIDER_HOME,
CONF_NEW_DEVICE_DEFAULTS,
CONF_SCAN_INTERVAL,
CONF_TRACK_NEW,
DEFAULT_AWAY_HIDE,
DEFAULT_CONSIDER_HOME,
DEFAULT_TRACK_NEW,
DOMAIN,
PLATFORM_TYPE_LEGACY,
SOURCE_TYPE_BLUETOOTH_LE,
SOURCE_TYPE_BLUETOOTH,
SOURCE_TYPE_GP... |
import logging
import os
from tempfile import mkdtemp
from .repositories import Repository, AuthenticatedRepository
log = logging.getLogger(__name__)
class RepoManager(object):
"""
Manages creation and deletion of `Repository` objects.
"""
to_cleanup = {}
def __init__(self, authenticated=False,... | ols,
self.executor,
shallow=self.shallow_clone)
return (dirname, repo)
def clone_repo(self, repo_name, remote_repo, ref):
"""Clones the given repo and returns the Repository object."""
self.shallow_clone = False
| dirname, repo = self.set_up_clone(repo_name, remote_repo)
if os.path.isdir("%s/.git" % dirname):
log.debug("Updating %s to %s", repo.download_location, dirname)
self.executor(
"cd %s && git checkout master" % dirname)
self.pull(dirname)
else:
... |
"""Default website configurations, used only for testing.
"""
from donut import environment
# Public Test Database |
TEST = environment.Environment(
db_hostname="localhost",
db_name="donut_test",
db_user="donut_test",
db_password="public",
debug=True,
testing=True,
secret_key="1234567890",
imgur_api={
"id": "b579f690cacf867",
"secret": "*************************** | *************"
},
restricted_ips=r"127\.0\.0\.1")
|
e(b, (list, tuple)):
setattr(self, a, [dict_wrapper(x) if isinstance(x, dict) else x for x in b])
else:
setattr(self, a, dict_wrapper(b) if isinstance(b, dict) else b)
class spritesheet(object):
"""
A sprite sheet is a series of images (usually animation frames) com... |
break
seq_name = anim.next
class framerate_regulator(object):
"""
Implements a variable sleep mechanism to give the appearance of a consistent
frame rate. Using a fixed-time sleep will cause animations to be jittery
(looking like they are speeding up or slowing down, depe... | mooth out
the jitter.
:param fps: The desired frame rate, expressed numerically in
frames-per-second. By default, this is set at 16.67, to give a frame
render time of approximately 60ms. This can be overridden as necessary,
and if no FPS limiting is required, the ``fps`` can be set to ... |
"
klass = self._select_struct_union_class(p[1])
p[0] = klass(
name=p[2],
decls=p[4],
coord=self._coord(p.lineno(2)))
def p_struct_or_union(self, p):
""" struct_or_union : STRUCT
| UNION
"""
p[0] = p[1]
# Co... | YPEID brace_open enumerator_list brace_close
"""
p[0] = c_ast.Enum(p[2], p[4], self._coord(p.lineno(1 | )))
def p_enumerator_list(self, p):
""" enumerator_list : enumerator
| enumerator_list COMMA
| enumerator_list COMMA enumerator
"""
if len(p) == 2:
p[0] = c_ast.EnumeratorList([p[1]], p[1].coord)
elif len(p) == 3:
... |
BODY_SCOPE), ('a', 'a[0]'), ('a[0]',))
def test_return_vars_are_read(self):
def test_fn(a, b, c): # pylint: disable=unused-argument
return c
node, _ = self._parse_and_analyze(test_fn)
fn_node = node
self.assertScopeIs(anno.getanno(fn_node, NodeAnno.BODY_SCOPE), ('c',), ())
self.assertSco... | ses_names(self):
def test_fn(a, b, c): # pylint: disable=unused-argument
try:
pass
except: # pylint: disable=bare-except
b = c
node, _ = self._parse_and_analyze(test_fn)
fn_node = node
self.assertScopeIs(
| anno.getanno(fn_node, NodeAnno.BODY_SCOPE), ('c',), ('b',))
def test_except_hides_exception_var_name(self):
def test_fn(a, b, c): # pylint: disable=unused-argument
try:
pass
except a as e:
b = e
node, _ = self._parse_and_analyze(test_fn)
fn_node = node
self.assertSco... |
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import *
import logging
import emission.core.wrapper.transition as et
import emission... | ype.END_TRIP_TRACKING,
"T_DATA_PUSHED": et.TransitionType.DATA_PUSHED,
"T_TRIP_ENDED": et.TransitionType.STOPPED_MOVING,
"T_FORCE_STOP_TRACKING": et.TransitionType.STOP_TRACKING,
"T_TRACKING_STOPPED": et.TransitionType.TRACKING_STOPPED,
"T_VISIT_STARTED": et.TransitionType.VISIT_STARTED,
"T_VISI... | et.TransitionType.NOP,
"T_START_TRACKING": et.TransitionType.START_TRACKING
}
def format(entry):
formatted_entry = ad.AttrDict()
formatted_entry["_id"] = entry["_id"]
formatted_entry.user_id = entry.user_id
m = entry.metadata
fc.expand_metadata_times(m)
formatted_entry.metadata = m
... |
#!/usr/bin/env python
"""
A toolkit for identifying and advertising service resources.
Uses a specific naming convention for the Task Definition of services. If you
name the Task Definition ending with "-service", no configuration is needed.
This also requires that you not use that naming convention for task definiti... | rvice_info(service_name):
info = {
"name": service_name,
"tasks": []
}
if service_name[-8:] == '-service':
info['name'] = service_name[:-8]
task_arns = get_task_arns(service_name)
if not task_arns:
logging.info('{0} is NOT RUNNING'.format(service_name))
retu... | esponse']['DescribeTasksResult']['tasks']
for task in tasks:
interface = get_ec2_interface(task['containerInstanceArn'])
task_info = {
'ip': interface.private_ip_address,
'ports': {}
}
for container in task['containers']:
... |
# -*- coding: utf8 -*-
from urllib.request import Request, urlopen
import logging
import parsing
__author__ = 'carlos'
class Downloader(object):
def __init__(self, url):
self.url = url
def read(self):
request = Request( self.url )
request.add_header('Accept-encoding', 't... | g.debug('Read %u | bytes from %s (%s)' % (len(data), self.url, charset))
return data
class StocksInfoUpdater(object):
def __init__(self, url):
self.downloader = Downloader(url)
self.parser = parsing.StockParser()
def update(self):
dataread = self.downloader.read()
self.p... |
# coding: utf-8
#
# Copyright 2018 The Oppia Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requi... | .payload.get('target_version_at_submission'),
self.user_id, self.payload.get('change_cmd'),
self.payload.get('description'),
self.payload.get('final_reviewer_id'))
self.render_json(self.values)
class SuggestionToExplorationActionHandler(base.BaseHandler):
"""Handles act... | ed on suggestions to explorations."""
ACTION_TYPE_ACCEPT = 'accept'
ACTION_TYPE_REJECT = 'reject'
# TODO (nithesh): Add permissions for users with enough scores to review
# Will be added as part of milestone 2 of the generalized review system
# project.
@acl_decorators.can_edit_exploration
... |
# SPDX-FileCopyr | ightText: 2020 The Kapitan Authors <kapitan-admins@googlegroups.com>
#
# SPDX-License-Identifier: Apache-2.0
import logging
logger = logging.getLogger(__name__)
class Validator(object):
def __init__(self, cache_dir, **kwargs):
self.cache_dir = cache | _dir
def validate(self, validate_obj, **kwargs):
raise NotImplementedError
|
# Copyright (c) 2017-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the LICENSE file in
# the root directory of this source tree. An additional gra | nt of patent rights
# can be found in the PATENTS file in the same directory.
import torch
class GradMultiply(torch.autograd.Function):
@staticmethod
def forward(ctx, x, scale):
ctx.scale = scale
res = x.new(x)
return res
@staticmethod
def backward(ctx, grad):
return ... | e
|
fr | om django.apps import AppConfig
from django.utils.translation import gettext_lazy as _
class WagtailTestsAppConfig(AppConfig):
name = 'wagtail.tests.modeladmintest'
label = ' | modeladmintest'
verbose_name = _("Test Wagtail Model Admin")
|
ee the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Tests for `tf.data.Dataset.from_sparse_tensor_slices()`."""
from absl.testing import parameterized
import numpy as np
from tensorflow.p... | s(errors.OutOfRangeError):
sess.run(get_next)
@combinations.generate(combinations.combine(tf_api_version=1, mode=["graph"]))
def testEmptySparseTensorSlicesInvalid(self):
"""Test a dataset based on invalid `tf.sparse.SparseTensor`."""
st = array_ops.sparse_placeholder(dtypes.float64)
iterator =... | sparse_tensor_slices(st))
init_op = iterator.initializer
with self.cached_session() as sess:
# Test with an empty sparse tensor but with non empty values.
empty_indices = np.empty((0, 4), dtype=np.int64)
non_empty_values = [1, 2, 3, 4]
empty_dense_shape = [0, 4, 37, 9]
sparse_feed... |
from __future__ import absolute_import, division, print_function
from builtins import * # @UnusedWildImport
from mcculw import ul
from mcculw.ul import ULError
from mcculw.enums import (BoardInfo, InfoType, ErrorCode, EventType,
ExpansionInfo)
from .ai_info import AiInfo
from .ao_info import... | return self._daqi_info
@property
def supports_daq_output(self): # -> boolean
return self._daqo_info.is_supported
def get_daqo_info(self): # -> DaqoInfo
return self._daqo_info
@property
def supports_digital_io(self): # -> boolean
return self._dio_info.is_supported
d... | ntType]
event_types = []
for event_type in EventType:
try:
ul.disable_event(self._board_num, event_type)
event_types.append(event_type)
except ULError:
pass
return event_types
@property
def num_expansions(self): ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.