diff --git a/pool/shard006/Python/0057587_dnsimple.py b/pool/shard006/Python/0057587_dnsimple.py
new file mode 100644
index 0000000000000000000000000000000000000000..143d3af69ad9b962daaabcc49d7d45c252990e26
--- /dev/null
+++ b/pool/shard006/Python/0057587_dnsimple.py
@@ -0,0 +1,42 @@
+# -*- coding: utf-8 -*-
+"""
+Updater for https://dnsimple.com/ compatible dyndns services.
+
+This module depends on the python package dnsimple-dyndns from
+https://pypi.python.org/pypi/dnsimple-dyndns
+If installed, dyndnsc will be able to utilize it.
+
+Since dnsimple.com is a paid service, I have not had a chance to test this yet.
+"""
+
+import logging
+
+from dnsimple_dyndns import DNSimple # @UnresolvedImport pylint: disable=import-error
+
+from .base import UpdateProtocol
+
+LOG = logging.getLogger(__name__)
+
+
+class UpdateProtocolDnsimple(UpdateProtocol):
+ """Protocol handler for https://dnsimple.com/ ."""
+
+ configuration_key = "dnsimple"
+
+ def __init__(self, hostname, key, url=None, **kwargs):
+ """Initialize."""
+ self._recordname, _, self._domain = hostname.partition(".")
+ self.hostname = hostname
+ self.handler = DNSimple(domain=self._domain,
+ domain_token=key)
+ if url is not None:
+ # The url must be a format string like this:
+ # 'https://dnsimple.com/domains/%s/records'
+ self.handler._baseurl = url % self._domain
+
+ super(UpdateProtocolDnsimple, self).__init__()
+
+ def update(self, ip):
+ """Update the IP on the remote service."""
+ return self.handler.update_record(name=self._recordname,
+ address=ip)
diff --git a/pool/shard006/Python/0057590_joystick.py b/pool/shard006/Python/0057590_joystick.py
new file mode 100644
index 0000000000000000000000000000000000000000..f0d636b4db4b8569df73caf5e24587ded6b0b476
--- /dev/null
+++ b/pool/shard006/Python/0057590_joystick.py
@@ -0,0 +1,81 @@
+#!/usr/bin/env python
+
+import pygame
+import sys
+
+import multiprocessing
+import Queue #needed separately for the Empty exception
+import time, datetime
+
+class JoystickProcess(multiprocessing.Process):
+ def __init__(self, outputqueue):
+ multiprocessing.Process.__init__(self)
+ self.outputqueue = outputqueue
+ self.exit = multiprocessing.Event()
+ self.sleeping = multiprocessing.Event()
+
+ def shutdown(self):
+ self.exit.set()
+
+ def sleep(self):
+ self.sleeping.set()
+
+ def wake(self):
+ self.sleeping.clear()
+
+ def run(self):
+ try:
+ pygame.init()
+ self.j = pygame.joystick.Joystick(0)
+ self.j.init()
+ print 'Found Joystick: ', self.j.get_name()
+ sys.stdout.flush()
+
+ except Exception, e:
+ print "exception in joystick:", e
+ self.sleep()
+ time.sleep(0.1)
+ sys.stdout.flush()
+
+ while not self.exit.is_set():
+
+ if self.sleeping.is_set():
+ time.sleep(0.1)
+ continue
+
+ data = self.get()
+
+ if (data is not None):
+ tstamp = datetime.datetime.now()
+ try:
+ self.outputqueue.put((tstamp, data), False)
+ except Queue.Full:
+ continue
+
+ def get(self):
+ out = []
+ pygame.event.pump()
+
+ #Read input from joysticks
+ for i in range(self.j.get_numaxes()):
+ out.append(self.j.get_axis(i))
+
+ #Read input from buttons
+ for i in range(self.j.get_numbuttons()):
+ out.append(self.j.get_button(i))
+
+ return out
+
+if __name__ == '__main__':
+
+ q = multiprocessing.Queue(maxsize=1)
+ j = JoystickProcess(q)
+ j.start()
+
+ while(1):
+ try:
+ tstamp, data = q.get(False)
+ print tstamp, data
+ sys.stdout.flush()
+ except Queue.Empty:
+ pass
diff --git a/pool/shard006/Python/0057591_tests.py b/pool/shard006/Python/0057591_tests.py
new file mode 100644
index 0000000000000000000000000000000000000000..4a5ddfe6b093cb6a2decb8972fb5b1c73f5550ff
--- /dev/null
+++ b/pool/shard006/Python/0057591_tests.py
@@ -0,0 +1,101 @@
+from django_dynamic_fixture import G
+
+from fluent_contents.plugins.rawhtml.models import RawHtmlItem
+
+from icekit import models
+from icekit.page_types.layout_page.models import LayoutPage
+from icekit.utils import fluent_contents
+
+
+from .. import base_tests
+
+
+class PagesAPITests(base_tests._BaseAPITestCase):
+ API_NAME = 'page-api'
+ API_IS_PUBLIC_READ = True
+
+ def setUp(self):
+ super(PagesAPITests, self).setUp()
+
+ self.layout_1 = G(
+ models.Layout,
+ template_name='icekit/layouts/default.html',
+ )
+ self.layoutpage_1 = LayoutPage.objects.create(
+ author=self.superuser,
+ title='Test LayoutPage',
+ layout=self.layout_1,
+ )
+ self.content_instance_1 = fluent_contents.create_content_instance(
+ RawHtmlItem,
+ self.layoutpage_1,
+ html='test 1'
+ )
+ self.content_instance_2 = fluent_contents.create_content_instance(
+ RawHtmlItem,
+ self.layoutpage_1,
+ html='test 2'
+ )
+ self.content_instance_3 = fluent_contents.create_content_instance(
+ RawHtmlItem,
+ self.layoutpage_1,
+ html='test 3'
+ )
+
+ def test_list_pages_with_get_and_filtered_fields(self):
+ self.layoutpage_1.publish()
+ response = self.client.get(self.listing_url() + '?fields=title')
+ self.assertEqual(200, response.status_code)
+ self.assertEqual(
+ {
+ 'count': 1,
+ 'next': None,
+ 'previous': None,
+ 'results': [{
+ 'title': 'Test LayoutPage',
+ }]
+ },
+ response.data)
+
+ def test_page_api(self):
+ self.layoutpage_1.publish()
+ for j in range(20):
+ published_layoutpage = LayoutPage.objects.create(
+ author=self.superuser,
+ title='Test LayoutPage %s' % j,
+ layout=self.layout_1,
+ )
+ published_layoutpage.publish()
+
+ LayoutPage.objects.create(
+ author=self.superuser,
+ title='Draft LayoutPage %s' % j,
+ layout=self.layout_1,
+ )
+
+ response = self.client.get(self.listing_url())
+ self.assertEqual(response.status_code, 200)
+ self.assertEqual(len(response.data['results']), 5)
+ self.assertEqual(response.data['count'], 21)
+ response = self.client.get(self.detail_url(self.layoutpage_1.id))
+ self.assertEqual(response.status_code, 404)
+ response = self.client.get(
+ self.detail_url(self.layoutpage_1.get_published().id))
+ self.assertEqual(response.status_code, 200)
+ self.assertEqual(len(response.data), 6)
+ for key in response.data.keys():
+ if key is not 'content':
+ self.assertEqual(
+ response.data[key],
+ getattr(self.layoutpage_1.get_published(), key))
+ self.assertEqual(len(response.data['content']), 3)
+ for number, item in enumerate(response.data['content'], 1):
+ self.assertEqual(
+ item['content'],
+ getattr(self, 'content_instance_%s' % number).html)
+
+ def test_api_user_permissions_are_correct(self):
+ self.layoutpage_1.publish()
+ page_published_id = self.layoutpage_1.get_published().pk
+ self.assert_api_user_permissions_are_correct(
+ page_published_id, models.Layout)
diff --git a/pool/shard006/Python/0057592_init__.py b/pool/shard006/Python/0057592_init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..186416580eac636779bfea5303b7c2c8f262adfd
--- /dev/null
+++ b/pool/shard006/Python/0057592_init__.py
@@ -0,0 +1,66 @@
+import os
+
+from flask import Flask
+
+from samantha import config
+
+# configure Flask
+app = Flask(__name__)
+app.secret_key = os.urandom(32)
+
+#
+# Configure SQLAlchemy
+# @see http://flask.pocoo.org/docs/0.10/patterns/sqlalchemy/
+#
+from sqlalchemy import create_engine
+from sqlalchemy.orm import scoped_session, sessionmaker
+from sqlalchemy.ext.declarative import declarative_base
+
+engine = create_engine(
+ config.get('SQLALCHEMY_DATABASE_URI'),
+ convert_unicode=True
+)
+session = scoped_session(
+ sessionmaker(
+ autocommit=False,
+ autoflush=False,
+ bind=engine
+ )
+)
+Base = declarative_base()
+Base.query = session.query_property()
+
+
+@app.teardown_appcontext
+def shutdown_session(exception=None):
+ session.remove()
+
+
+#
+# Configure Celery
+# @see http://flask.pocoo.org/docs/0.10/patterns/celery/
+#
+from celery import Celery
+
+
+def make_celery(app):
+ celery = Celery(app.import_name, broker=app.config['CELERY_BROKER_URL'])
+ celery.conf.update(app.config)
+ TaskBase = celery.Task
+
+ class ContextTask(TaskBase):
+ abstract = True
+
+ def __call__(self, *args, **kwargs):
+ with app.app_context():
+ return TaskBase.__call__(self, *args, **kwargs)
+
+ celery.Task = ContextTask
+ return celery
+
+app.config.update(
+ CELERY_BROKER_URL=config.get('CELERY_BROKER_URL'),
+ CELERY_RESULT_BACKEND=config.get('CELERY_BROKER_URL'),
+ CELERY_ACCEPT_CONTENT=config.get('CELERY_ACCEPT_CONTENT').split(',')
+)
+celery = make_celery(app)
diff --git a/pool/shard006/Python/0057597_base.py b/pool/shard006/Python/0057597_base.py
new file mode 100644
index 0000000000000000000000000000000000000000..c48291f137ff189255aac2357434828ae2c4d297
--- /dev/null
+++ b/pool/shard006/Python/0057597_base.py
@@ -0,0 +1,57 @@
+from __future__ import print_function
+from __future__ import division
+from __future__ import absolute_import
+from builtins import object
+
+
+def not_implemented(method):
+ raise NotImplementedError("Provider does not support '%s' "
+ "method." % method)
+
+
+class BaseProviderBuilder(object):
+ def build(self, region=None):
+ not_implemented("build")
+
+
+class BaseProvider(object):
+ def get_stack(self, stack_name, *args, **kwargs):
+ # pylint: disable=unused-argument
+ not_implemented("get_stack")
+
+ def create_stack(self, *args, **kwargs):
+ # pylint: disable=unused-argument
+ not_implemented("create_stack")
+
+ def update_stack(self, *args, **kwargs):
+ # pylint: disable=unused-argument
+ not_implemented("update_stack")
+
+ def destroy_stack(self, *args, **kwargs):
+ # pylint: disable=unused-argument
+ not_implemented("destroy_stack")
+
+ def get_stack_status(self, stack_name, *args, **kwargs):
+ # pylint: disable=unused-argument
+ not_implemented("get_stack_status")
+
+ def get_outputs(self, stack_name, *args, **kwargs):
+ # pylint: disable=unused-argument
+ not_implemented("get_outputs")
+
+ def get_output(self, stack_name, output):
+ # pylint: disable=unused-argument
+ return self.get_outputs(stack_name)[output]
+
+
+class Template(object):
+ """A value object that represents a CloudFormation stack template, which
+ could be optionally uploaded to s3.
+
+ Presence of the url attribute indicates that the template was uploaded to
+ S3, and the uploaded template should be used for CreateStack/UpdateStack
+ calls.
+ """
+ def __init__(self, url=None, body=None):
+ self.url = url
+ self.body = body
diff --git a/pool/shard006/Python/0057598_test_configuration.py b/pool/shard006/Python/0057598_test_configuration.py
new file mode 100644
index 0000000000000000000000000000000000000000..04fc77120e6d3a46bd1019ca994c3e40cbf0c869
--- /dev/null
+++ b/pool/shard006/Python/0057598_test_configuration.py
@@ -0,0 +1,21 @@
+import os
+
+from paste.deploy.loadwsgi import appconfig
+
+from testery.tests import TestCase
+
+
+class TestConfiguration(TestCase):
+ """Check that the ini files track the same configuration types."""
+
+ def setUp(self):
+ super(TestConfiguration, self).setUp()
+ here = os.path.dirname(__file__)
+ self.project_root = os.path.abspath(os.path.join(here, '..', '..'))
+
+ def test_development_ini(self):
+ test_ini = os.path.join(self.project_root, 'test.ini')
+ test_settings = appconfig('config:' + test_ini)
+ dev_ini = os.path.join(self.project_root, 'development.ini')
+ dev_settings = appconfig('config:' + dev_ini)
+ self.assertEqual(test_settings.keys(), dev_settings.keys())
diff --git a/pool/shard006/Python/0057604_test_hinge.py b/pool/shard006/Python/0057604_test_hinge.py
new file mode 100644
index 0000000000000000000000000000000000000000..0e74e16e4c102b7e190e3ba0294805963ea10ab2
--- /dev/null
+++ b/pool/shard006/Python/0057604_test_hinge.py
@@ -0,0 +1,138 @@
+import unittest
+
+import numpy
+import six
+
+import chainer
+from chainer.backends import cuda
+from chainer import functions
+from chainer import gradient_check
+from chainer import testing
+from chainer.testing import attr
+
+
+@testing.parameterize(*testing.product_dict(
+ [{'dtype': numpy.float16,
+ 'forward_options': {'rtol': 3e-3, 'atol': 3e-3},
+ 'backward_options': {'rtol': 1e-1, 'atol': 1e-1}},
+ {'dtype': numpy.float32,
+ 'forward_options': {},
+ 'backward_options': {'rtol': 1e-1, 'atol': 1e-1}},
+ {'dtype': numpy.float64,
+ 'forward_options': {},
+ 'backward_options': {'rtol': 1e-1, 'atol': 1e-1}},
+ ],
+ [{'reduce': 'no'},
+ {'reduce': 'mean'},
+ ],
+ [{'norm': 'L1'},
+ {'norm': 'L2'},
+ ],
+ [{'label_dtype': numpy.int8},
+ {'label_dtype': numpy.int16},
+ {'label_dtype': numpy.int32},
+ {'label_dtype': numpy.int64},
+ ],
+))
+class TestHinge(unittest.TestCase):
+
+ def setUp(self):
+ self._config_user = chainer.using_config('dtype', self.dtype)
+ self._config_user.__enter__()
+
+ shape = (10, 5)
+ self.x = numpy.random.uniform(-1, 1, shape).astype(self.dtype)
+ # Avoid values around -1.0 for stability
+ self.x[numpy.logical_and(-1.01 < self.x, self.x < -0.99)] = 0.5
+ self.t = numpy.random.randint(
+ 0, shape[1], shape[:1]).astype(self.label_dtype)
+ if self.reduce == 'no':
+ self.gy = numpy.random.uniform(
+ -1, 1, self.x.shape).astype(self.dtype)
+
+ def tearDown(self):
+ self._config_user.__exit__(None, None, None)
+
+ def check_forward(self, x_data, t_data):
+ x_val = chainer.Variable(x_data)
+ t_val = chainer.Variable(t_data)
+ loss = functions.hinge(x_val, t_val, self.norm, self.reduce)
+ if self.reduce == 'mean':
+ self.assertEqual(loss.data.shape, ())
+ else:
+ self.assertEqual(loss.data.shape, self.x.shape)
+ self.assertEqual(loss.data.dtype, self.dtype)
+ loss_value = cuda.to_cpu(loss.data)
+
+ # Compute expected value
+ for i in six.moves.range(self.x.shape[0]):
+ self.x[i, self.t[i]] *= -1
+ for i in six.moves.range(self.x.shape[0]):
+ for j in six.moves.range(self.x.shape[1]):
+ self.x[i, j] = max(0, 1.0 + self.x[i, j])
+ if self.norm == 'L1':
+ loss_expect = self.x
+ elif self.norm == 'L2':
+ loss_expect = self.x ** 2
+ if self.reduce == 'mean':
+ loss_expect = numpy.sum(loss_expect) / self.x.shape[0]
+
+ testing.assert_allclose(
+ loss_expect, loss_value, **self.forward_options)
+
+ def test_forward_cpu(self):
+ self.check_forward(self.x, self.t)
+
+ @attr.gpu
+ def test_forward_gpu(self):
+ self.check_forward(cuda.to_gpu(self.x), cuda.to_gpu(self.t))
+
+ def check_backward(self, x_data, t_data):
+ def f(x, t):
+ return functions.hinge(x, t, self.norm)
+
+ gradient_check.check_backward(
+ f, (x_data, t_data), None, dtype='d', **self.backward_options)
+
+ def test_backward_cpu(self):
+ self.check_backward(self.x, self.t)
+
+ @attr.gpu
+ def test_backward_gpu(self):
+ self.check_backward(cuda.to_gpu(self.x), cuda.to_gpu(self.t))
+
+
+class TestHingeInvalidOption(unittest.TestCase):
+
+ def setUp(self):
+ self.x = numpy.random.uniform(-1, 1, (10, 5)).astype(numpy.float32)
+ self.t = numpy.random.randint(0, 5, (10,)).astype(numpy.int32)
+
+ def check_invalid_norm_option(self, xp):
+ x = xp.asarray(self.x)
+ t = xp.asarray(self.t)
+ with self.assertRaises(NotImplementedError):
+ functions.hinge(x, t, 'invalid_norm', 'mean')
+
+ def test_invalid_norm_option_cpu(self):
+ self.check_invalid_norm_option(numpy)
+
+ @attr.gpu
+ def test_invalid_norm_option_gpu(self):
+ self.check_invalid_norm_option(cuda.cupy)
+
+ def check_invalid_reduce_option(self, xp):
+ x = xp.asarray(self.x)
+ t = xp.asarray(self.t)
+ with self.assertRaises(ValueError):
+ functions.hinge(x, t, 'L1', 'invalid_option')
+
+ def test_invalid_reduce_option_cpu(self):
+ self.check_invalid_reduce_option(numpy)
+
+ @attr.gpu
+ def test_invalid_reduce_option_gpu(self):
+ self.check_invalid_reduce_option(cuda.cupy)
+
+
+testing.run_module(__name__, __file__)
diff --git a/pool/shard006/Python/0057605_stats_randint.py b/pool/shard006/Python/0057605_stats_randint.py
new file mode 100644
index 0000000000000000000000000000000000000000..c422dcd5cb92a483ad6aa6dbda6a210fb3df4b2d
--- /dev/null
+++ b/pool/shard006/Python/0057605_stats_randint.py
@@ -0,0 +1,21 @@
+#!/usr/bin/env python
+"""stats_randint.py: Demonstrate how ``scipy.stats.randint`` works.
+"""
+from scipy.stats import randint
+
+# pylint: disable=invalid-name
+
+# Define a dice model.
+low = 1
+high = 7
+dice = randint(low, high)
+
+# Compute moments.
+mean, var, skew, kurt = dice.stats(moments='mvsk')
+
+print(f"mean: {float(mean):.3f}")
+print(f"median: {dice.median():.3f}")
+print(f"var: {float(var):.3f}")
+print(f"skew: {float(skew):.3f}")
+print(f"kurt: {float(kurt):.3f}")
+print(f"std: {dice.std():.3f}") # Or np.sqrt(var).
diff --git a/pool/shard006/Python/0057607_foomodulegen4.py b/pool/shard006/Python/0057607_foomodulegen4.py
new file mode 100644
index 0000000000000000000000000000000000000000..3930cdefae380e853883e4d7a7ff9bb7b3233225
--- /dev/null
+++ b/pool/shard006/Python/0057607_foomodulegen4.py
@@ -0,0 +1,76 @@
+#! /usr/bin/env python
+from __future__ import unicode_literals, print_function
+
+import sys
+import os.path
+
+import pybindgen
+from pybindgen.module import MultiSectionFactory
+from pybindgen import (FileCodeSink)
+
+import foomodulegen_split
+import foomodulegen_common
+
+
+class MyMultiSectionFactory(MultiSectionFactory):
+
+ def __init__(self, main_file_name):
+ self.main_file_name = main_file_name
+ self.main_sink = FileCodeSink(open(main_file_name, "wt"))
+ self.header_name = "foomodule4.h"
+ header_file_name = os.path.join(os.path.dirname(self.main_file_name), self.header_name)
+ self.header_sink = FileCodeSink(open(header_file_name, "wt"))
+ self.section_sinks = {}
+
+ def get_section_code_sink(self, section_name):
+ if section_name == '__main__':
+ return self.main_sink
+ try:
+ return self.section_sinks[section_name]
+ except KeyError:
+ file_name = os.path.join(os.path.dirname(self.main_file_name), "%s.cc" % section_name)
+ sink = FileCodeSink(open(file_name, "wt"))
+ self.section_sinks[section_name] = sink
+ return sink
+
+ def get_main_code_sink(self):
+ return self.main_sink
+
+ def get_common_header_code_sink(self):
+ return self.header_sink
+
+ def get_common_header_include(self):
+ return '"%s"' % self.header_name
+
+ def close(self):
+ self.header_sink.file.close()
+ self.main_sink.file.close()
+ for sink in self.section_sinks.values():
+ sink.file.close()
+
+def my_module_gen():
+ out = MyMultiSectionFactory(sys.argv[1])
+ root_module = foomodulegen_split.module_init()
+ root_module.add_exception('exception', foreign_cpp_namespace='std', message_rvalue='%(EXC)s.what()')
+ foomodulegen_common.customize_module_pre(root_module)
+
+ foomodulegen_split.register_types(root_module)
+ foomodulegen_split.register_methods(root_module)
+ foomodulegen_split.register_functions(root_module)
+ foomodulegen_common.customize_module(root_module)
+
+ root_module.generate(out)
+
+ out.close()
+
+
+
+if __name__ == '__main__':
+ try:
+ import cProfile as profile
+ except ImportError:
+ my_module_gen()
+ else:
+ print("** running under profiler", file=sys.stderr)
+ profile.run('my_module_gen()', 'foomodulegen4.pstat')
+
diff --git a/pool/shard006/Python/0057610_shell.py b/pool/shard006/Python/0057610_shell.py
new file mode 100644
index 0000000000000000000000000000000000000000..89c9a3b01b1caeaf3e6b6fd0eec281670c6d4d78
--- /dev/null
+++ b/pool/shard006/Python/0057610_shell.py
@@ -0,0 +1,130 @@
+# -*- coding: utf-8 -*-
+
+import re
+import types
+import logging
+import subprocess
+
+from ..exceptions import (ExecuteRuntimeError, ScriptRuntimeError,
+ NetworkError)
+from .strings import mask_string
+
+
+block_fmt = ("\n============= %(title)s ==========\n%(content)s\n"
+ "======== END OF %(title)s ========")
+
+
+def execute(cmd, workdir=None, can_fail=True, mask_list=None,
+ use_shell=False, log=True):
+ """
+ Runs shell command cmd. If can_fail is set to False
+ ExecuteRuntimeError is raised if command returned non-zero return
+ code. Otherwise
+ """
+ mask_list = mask_list or []
+ repl_list = [("'", "'\\''")]
+
+ if not isinstance(cmd, types.StringType):
+ import pipes
+ masked = ' '.join((pipes.quote(i) for i in cmd))
+ else:
+ masked = cmd
+ masked = mask_string(masked, mask_list, repl_list)
+ if log:
+ logging.info("Executing command:\n%s" % masked)
+
+ proc = subprocess.Popen(cmd, stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE, cwd=workdir,
+ shell=use_shell, close_fds=True)
+ out, err = proc.communicate()
+ masked_out = mask_string(out, mask_list, repl_list)
+ masked_err = mask_string(err, mask_list, repl_list)
+ if log:
+ logging.debug(block_fmt % {'title': 'STDOUT', 'content': masked_out})
+
+ if proc.returncode:
+ if log:
+ logging.debug(block_fmt % {'title': 'STDERR',
+ 'content': masked_err})
+ if can_fail:
+ msg = 'Failed to execute command: %s' % masked_out
+ raise ExecuteRuntimeError(msg, stdout=out, stderr=err)
+ return proc.returncode, out
+
+
+class ScriptRunner(object):
+ _pkg_search = 'rpm -q --whatprovides'
+
+ def __init__(self, ip=None):
+ self.script = []
+ self.ip = ip
+
+ def append(self, s):
+ self.script.append(s)
+
+ def clear(self):
+ self.script = []
+
+ def execute(self, can_fail=True, mask_list=None, log=True):
+ mask_list = mask_list or []
+ repl_list = [("'", "'\\''")]
+ script = "\n".join(self.script)
+
+ masked = mask_string(script, mask_list, repl_list)
+ if log:
+ logging.info("[%s] Executing script:\n%s" %
+ (self.ip or 'localhost', masked))
+
+ _PIPE = subprocess.PIPE # pylint: disable=E1101
+ if self.ip:
+ cmd = ["ssh", "-o", "StrictHostKeyChecking=no",
+ "-o", "UserKnownHostsFile=/dev/null",
+ "root@%s" % self.ip, "bash -x"]
+ else:
+ cmd = ["bash", "-x"]
+ obj = subprocess.Popen(cmd, stdin=_PIPE, stdout=_PIPE, stderr=_PIPE,
+ close_fds=True, shell=False)
+
+ script = "function t(){ exit $? ; } \n trap t ERR \n" + script
+ out, err = obj.communicate(script)
+ masked_out = mask_string(out, mask_list, repl_list)
+ masked_err = mask_string(err, mask_list, repl_list)
+ if log:
+ logging.debug(block_fmt % {'title': 'STDOUT',
+ 'content': masked_out})
+
+ if obj.returncode:
+ if log:
+ logging.debug(block_fmt % {'title': 'STDERR',
+ 'content': masked_err})
+ if can_fail:
+ pattern = (r'^ssh\:')
+ if re.search(pattern, err):
+ raise NetworkError(masked_err, stdout=out, stderr=err)
+ else:
+ msg = 'Failed to run remote script: %s' % masked_out
+ raise ScriptRuntimeError(msg, stdout=out, stderr=err)
+ return obj.returncode, out
+
+ def template(self, src, dst, varsdict):
+ with open(src) as fp:
+ content = fp.read() % varsdict
+ self.append("cat > %s <<- EOF\n%s\nEOF\n" % (dst, content))
+
+ def if_not_exists(self, path, command):
+ self.append("[ -e %s ] || %s" % (path, command))
+
+ def if_exists(self, path, command):
+ self.append("[ -e %s ] && %s" % (path, command))
+
+ def if_installed(self, pkg, command):
+ self.append("%s %s && %s" % (self._pkg_search, pkg, command))
+
+ def if_not_installed(self, pkg, command):
+ self.append("%s %s || %s" % (self._pkg_search, pkg, command))
+
+ def chown(self, target, uid, gid):
+ self.append("chown %s:%s %s" % (uid, gid, target))
+
+ def chmod(self, target, mode):
+ self.append("chmod %s %s" % (mode, target))
diff --git a/pool/shard006/Python/0057612_node_power_control.py b/pool/shard006/Python/0057612_node_power_control.py
new file mode 100644
index 0000000000000000000000000000000000000000..30cb24c86ce1a7d8a1e23408f027b7b4dbeab120
--- /dev/null
+++ b/pool/shard006/Python/0057612_node_power_control.py
@@ -0,0 +1,52 @@
+#! /usr/bin/env python
+# -*- mode: python; coding: utf-8 -*-
+# Copyright 2018 the HERA Collaboration
+# Licensed under the 2-clause BSD license.
+
+"""script to control power of node elements (snaps, fem, pam)
+
+"""
+
+from hera_mc import mc, cm_utils, node
+
+valid_part_names = list(node.power_command_part_dict.keys())
+
+if __name__ == '__main__':
+ parser = mc.get_mc_argument_parser()
+ parser.description = """Power on or off node elements (snaps, fem, pam)"""
+ parser.add_argument('nodes', help="list of nodes to command "
+ "(integers, comma-separated, no spaces) or 'active'")
+ parser.add_argument('parts', help="list of parts to command "
+ "(comma-separated, no spaces) or 'all'."
+ " Valid part names are: " + ' ,'.join(valid_part_names) + ".")
+ parser.add_argument('command', help="command: 'on' or 'off'.")
+ parser.add_argument('--address', help="address for node server", default=None)
+ parser.add_argument('--dryrun', help="just print the list of NodePowerCommand "
+ "objects, do not issue the power commands or log them "
+ "to the database' [False]", action='store_true')
+ parser.add_argument('--testing', help="Testing: do not use anything that "
+ "requires connection to nodes (implies dryrun)' [False]",
+ action='store_true')
+
+ args = parser.parse_args()
+ db = mc.connect_to_mc_db(args)
+ session = db.sessionmaker()
+
+ if args.nodes.lower() == 'active':
+ from hera_mc import node
+ node_list = node.get_node_list(nodeServerAddress=args.address)
+ else:
+ node_list = cm_utils.listify(args.nodes)
+ node_list = [int(node) for node in node_list]
+
+ parts_list = cm_utils.listify(args.parts)
+
+ for nodeID in node_list:
+ command_list = session.node_power_command(nodeID, parts_list, args.command,
+ nodeServerAddress=args.address,
+ dryrun=args.dryrun,
+ testing=args.testing)
+ if args.testing or args.dryrun:
+ for cmd in command_list:
+ print(cmd)
+ session.commit()
diff --git a/pool/shard006/Python/0057613_init__.py b/pool/shard006/Python/0057613_init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..27319476ae1943fb17c405f220a62a73546abc4c
--- /dev/null
+++ b/pool/shard006/Python/0057613_init__.py
@@ -0,0 +1,48 @@
+#! /usr/bin/env python
+
+import re
+import sys
+import argparse
+
+from .litran import LIT
+
+__name__ = "litcm"
+__doc__ = "Language Identification and Transliteration system for Indian Languages in Roman script code mixed with English"
+__author__ = "Irshad Ahmad"
+__version__ = "1.0.0"
+__license__ = "MIT"
+__maintainer__ = "Irshad Ahmad"
+__email__ = "irshad.bhat@research.iiit.ac.in"
+__status__ = "Beta"
+__all__ = ["litran", "indictrans", "wxILP", "main", "blm_models", "decision_trees", "extras"]
+
+def main():
+ all_tags = ['ben', 'eng', 'guj', 'hin', 'kan', 'mal', 'tam', 'tel']
+ lang_help = 'Any language combination from the set: [%s]' %'|'.join(all_tags)
+ parser = argparse.ArgumentParser(prog="litcm", description="Language Identification & Transliteration in Code-Mixing")
+ parser.add_argument('--v', action='version', version="%(prog)s 1.0")
+ parser.add_argument('--i', metavar='input', dest="INFILE", type=argparse.FileType('r'), default=sys.stdin, help="")
+ parser.add_argument('--o', metavar='output', dest="OUTFILE", type=argparse.FileType('w'), default=sys.stdout, help="")
+ parser.add_argument('--l', metavar='languages', dest='lang_tags', nargs='+', help=lang_help)
+ parser.add_argument('--t', dest='flag', action='store_true', help="set this flag for back-transliteration of Indic words")
+
+ args = parser.parse_args()
+
+ if args.lang_tags:
+ labels = [tag.lower() for tag in args.lang_tags]
+ assert len(labels) >= 2
+ assert set(labels).issubset(set(all_tags))
+ else:
+ labels = ['hin', 'eng']
+
+ lit = LIT(labels, transliteration=args.flag)
+ for line in args.INFILE:
+ if not line.strip():
+ args.OUTFILE.write('\n')
+ continue
+ litsen = lit.identify(line)
+ args.OUTFILE.write("%s\n" %litsen)
+
+ #close files
+ args.INFILE.close()
+ args.OUTFILE.close()
diff --git a/pool/shard006/Python/0057617_MySQLInitial.py b/pool/shard006/Python/0057617_MySQLInitial.py
new file mode 100644
index 0000000000000000000000000000000000000000..3d38e5b9ebf7db7ed1d3d3935bd58ba7962c1484
--- /dev/null
+++ b/pool/shard006/Python/0057617_MySQLInitial.py
@@ -0,0 +1,42 @@
+# Copyright 2014 Open Connectome Project (http://openconnecto.me)
+#
+# 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.
+
+import MySQLdb
+import sys
+
+# Edit the following:
+# MySQLPass - MySQL root user password
+# password_here - the password for user(in this case brain) specified in the settings_secret.py file
+
+def setup(MySQLPass, BrainPass):
+
+ # Assuming ocpdjango (from settings_secret.py)
+
+ db = MySQLdb.connect("localhost","root",MySQLPass)
+ cursor = db.cursor()
+
+ # Create database for OCP
+ cursor.execute("create database ocpdjango;")
+
+ # Create users for OCP
+ cursor.execute("create user 'brain'@'localhost' identified by '" + BrainPass + "';")
+ cursor.execute("grant all privileges on *.* to 'brain'@'localhost' with grant option;")
+
+ cursor.execute("create user 'brain'@'%' identified by '" + BrainPass + "';")
+ cursor.execute("grant all privileges on *.* to 'brain'@'%' with grant option;")
+
+ db.close()
+
+if __name__ == '__main__':
+ setup(*sys.argv[1:])
diff --git a/pool/shard006/Python/0057619_playerdb.py b/pool/shard006/Python/0057619_playerdb.py
new file mode 100644
index 0000000000000000000000000000000000000000..e94e0a0394c04f76b5d47b7ddb847b7b76a566cc
--- /dev/null
+++ b/pool/shard006/Python/0057619_playerdb.py
@@ -0,0 +1,86 @@
+"""
+ Player datablock generator, written to test an experimental super-2046 DB count
+ patch.
+"""
+
+import sys
+import math
+
+class PseudoNumber:
+ _value = None
+ _digits = None
+ _decimal_value = None
+ _converted = None
+
+ def __init__(self, digits=None, value=None):
+ self._digits = digits
+ self._decimal_value = int(value)
+
+ self.convert()
+
+ def convert(self):
+ self._value = ''
+
+ if (self._decimal_value == 0):
+ self._value = self._digits[0]
+ return self._value
+
+ digit_count = len(self._digits) - 1
+
+ start_power = int(math.ceil(self._decimal_value / digit_count))
+ temporary = int(self._decimal_value)
+ for current_power in reversed(range(start_power + 1)):
+ for current_index, current_digit in enumerate(reversed(self._digits)):
+ actual_index = digit_count - current_index
+ actual_value = actual_index * pow(digit_count + 1, current_power)
+ if (actual_value <= temporary and actual_value != 0):
+ temporary -= actual_value
+ self._value += self._digits[actual_index % (digit_count + 1)]
+
+ if (temporary <= 0):
+ for power in range(current_power):
+ self._value += self._digits[0]
+ return self._value
+
+ return self._value
+
+ def __repr__(self):
+ return self.convert()
+
+ def __str__(self):
+ return self._value
+
+ def __int__(self):
+ return self._decimal_value
+
+ def __add__(self, other):
+ return PseudoNumber(self._digits, self._decimal_value + other)
+
+class Application:
+ def main(self):
+ if (len(sys.argv) != 3):
+ print("Usage: %s " % sys.argv[0])
+ return
+
+ datablock_count = int(sys.argv[2])
+ file_count = int(sys.argv[1])
+ datablock_iterations = datablock_count / file_count
+ current_digit = PseudoNumber('ABCDEFGHIJKLMNOPQRSTUVWXYZ', 0)
+
+ for file_iteration in range(file_count):
+ with open("out%u.cs" % file_iteration, "w") as handle:
+ handle.write("// Total Count: %u\n" % datablock_iterations)
+ for current_datablock_iteration in range(datablock_iterations):
+ handle.write("// Datablock #%u\n" % current_datablock_iteration)
+ handle.write("datablock PlayerData(%sMaleBiodermArmor) : LightMaleHumanArmor\n" % str(current_digit))
+ handle.write("{\n")
+ handle.write("\tshapeFile = \"bioderm_light.dts\";\n")
+ handle.write("};\n\n")
+
+ current_digit += 1
+
+ handle.write("exec(\"scripts/out%u.cs\");" % (file_iteration + 1))
+
+
+if __name__ == "__main__":
+ Application().main()
diff --git a/pool/shard006/Python/0057620_test_model_chat_analysis.py b/pool/shard006/Python/0057620_test_model_chat_analysis.py
new file mode 100644
index 0000000000000000000000000000000000000000..dae9b287211da2a791f8a7f94043d557f28eb5f0
--- /dev/null
+++ b/pool/shard006/Python/0057620_test_model_chat_analysis.py
@@ -0,0 +1,137 @@
+#!/usr/bin/env python3
+
+# Copyright (c) Facebook, Inc. and its affiliates.
+# This source code is licensed under the MIT license found in the
+# LICENSE file in the root directory of this source tree.
+"""
+Test the analysis code for the model chat task.
+"""
+
+import glob
+import os
+
+import pytest
+from pytest_regressions.file_regression import FileRegressionFixture
+
+import parlai.utils.testing as testing_utils
+
+
+try:
+
+ from parlai.crowdsourcing.tasks.model_chat.analysis.compile_results import (
+ ModelChatResultsCompiler,
+ )
+ from parlai.crowdsourcing.utils.tests import check_stdout
+
+ class TestCompileResults:
+ """
+ Test the analysis code for the model chat task.
+ """
+
+ # Dictionary of cases to test, as well as flags to use with those cases
+ CASES = {'basic': '--problem-buckets None', 'with_personas_and_buckets': ''}
+
+ @pytest.fixture(scope="module")
+ def setup_teardown(self):
+ """
+ Call code to set up and tear down tests.
+
+ Run this only once because we'll be running all analysis code before
+ checking any results.
+ """
+
+ outputs = {}
+
+ for case, flag_string in self.CASES.items():
+
+ # Paths
+ analysis_samples_folder = os.path.join(
+ os.path.dirname(os.path.abspath(__file__)), 'analysis_samples', case
+ )
+ analysis_outputs_folder = os.path.join(
+ os.path.dirname(os.path.abspath(__file__)),
+ 'test_model_chat_analysis',
+ )
+ outputs[f'{case}__expected_stdout_path'] = os.path.join(
+ analysis_outputs_folder, f'{case}__test_stdout.txt'
+ )
+
+ prefixes = ['results', 'worker_results']
+
+ with testing_utils.tempdir() as tmpdir:
+
+ # Run analysis
+ with testing_utils.capture_output() as output:
+ arg_string = f"""\
+--results-folders {analysis_samples_folder}
+--output-folder {tmpdir} \
+{flag_string}
+"""
+ parser_ = ModelChatResultsCompiler.setup_args()
+ args_ = parser_.parse_args(arg_string.split())
+ ModelChatResultsCompiler(vars(args_)).compile_and_save_results()
+ stdout = output.getvalue()
+
+ # Define output structure
+ filtered_stdout = '\n'.join(
+ [
+ line
+ for line in stdout.split('\n')
+ if not line.endswith('.csv')
+ ]
+ )
+ # Don't track lines that record where a file was saved to, because
+ # filenames are timestamped
+ outputs[f'{case}__stdout'] = filtered_stdout
+ for prefix in prefixes:
+ results_path = list(
+ glob.glob(os.path.join(tmpdir, f'{prefix}_*'))
+ )[0]
+ with open(results_path) as f:
+ outputs[f'{case}__{prefix}'] = f.read()
+
+ yield outputs
+ # All code after this will be run upon teardown
+
+ def test_stdout(self, setup_teardown):
+ """
+ Check the output against what it should be.
+ """
+ outputs = setup_teardown
+ for case in self.CASES.keys():
+ check_stdout(
+ actual_stdout=outputs[f'{case}__stdout'],
+ expected_stdout_path=outputs[f'{case}__expected_stdout_path'],
+ )
+
+ def test_results_file(
+ self, setup_teardown, file_regression: FileRegressionFixture
+ ):
+ """
+ Check the results file against what it should be.
+
+ We don't use DataFrameRegression fixture because the results might include
+ non-numeric data.
+ """
+ for case in self.CASES.keys():
+ prefix = f'{case}__results'
+ outputs = setup_teardown
+ file_regression.check(outputs[prefix], basename=prefix)
+
+ def test_worker_results_file(
+ self, setup_teardown, file_regression: FileRegressionFixture
+ ):
+ """
+ Check the worker_results file against what it should be.
+
+ We don't use DataFrameRegression fixture because the results might include
+ non-numeric data.
+ """
+ for case in self.CASES.keys():
+ prefix = f'{case}__worker_results'
+ outputs = setup_teardown
+ file_regression.check(outputs[prefix], basename=prefix)
+
+
+except ImportError:
+ pass
diff --git a/pool/shard006/Python/0057630_principals.py b/pool/shard006/Python/0057630_principals.py
new file mode 100644
index 0000000000000000000000000000000000000000..05cfdbc1c794bcf2c5186bfcf47cd97667d5fa44
--- /dev/null
+++ b/pool/shard006/Python/0057630_principals.py
@@ -0,0 +1,53 @@
+# This file is part of Indico.
+# Copyright (C) 2002 - 2021 CERN
+#
+# Indico is free software; you can redistribute it and/or
+# modify it under the terms of the MIT License; see the
+# LICENSE file for more details.
+
+from sqlalchemy.ext.declarative import declared_attr
+
+from indico.core.db import db
+from indico.core.db.sqlalchemy.principals import PrincipalPermissionsMixin, PrincipalType
+from indico.core.db.sqlalchemy.util.models import auto_table_args
+from indico.util.string import format_repr
+
+
+class EventPrincipal(PrincipalPermissionsMixin, db.Model):
+ __tablename__ = 'principals'
+ principal_backref_name = 'in_event_acls'
+ principal_for = 'Event'
+ unique_columns = ('event_id',)
+ allow_emails = True
+ allow_networks = True
+ allow_event_roles = True
+ allow_category_roles = True
+ allow_registration_forms = True
+
+ @declared_attr
+ def __table_args__(cls):
+ permissions = "ARRAY['paper_editing', 'slides_editing', 'poster_editing']"
+ condition = 'type NOT IN ({}, {}) OR (NOT (permissions::text[] && {}))'.format(
+ PrincipalType.local_group, PrincipalType.multipass_group, permissions
+ )
+ group_perm_constraint = db.CheckConstraint(condition, 'disallow_group_editor_permissions')
+ return (group_perm_constraint,) + auto_table_args(cls, schema='events')
+
+ #: The ID of the acl entry
+ id = db.Column(
+ db.Integer,
+ primary_key=True
+ )
+ #: The ID of the associated event
+ event_id = db.Column(
+ db.Integer,
+ db.ForeignKey('events.events.id'),
+ nullable=False,
+ index=True
+ )
+
+ # relationship backrefs:
+ # - event (Event.acl_entries)
+
+ def __repr__(self):
+ return format_repr(self, 'id', 'event_id', 'principal', read_access=False, full_access=False, permissions=[])
diff --git a/pool/shard006/Python/0057631_FingerprintUtils.py b/pool/shard006/Python/0057631_FingerprintUtils.py
new file mode 100644
index 0000000000000000000000000000000000000000..2c18cb67b542e90c4da7e47e6e4239c9188ee579
--- /dev/null
+++ b/pool/shard006/Python/0057631_FingerprintUtils.py
@@ -0,0 +1,112 @@
+# $Id$
+#
+# Copyright (C) 2009 Greg Landrum
+# All Rights Reserved
+#
+from __future__ import print_function
+from rdkit.six.moves import cPickle
+from rdkit.six import iterkeys
+from rdkit import DataStructs,Chem
+from rdkit import Chem
+
+similarityMethods={'RDK':DataStructs.ExplicitBitVect,
+ 'AtomPairs':DataStructs.IntSparseIntVect,
+ 'TopologicalTorsions':DataStructs.LongSparseIntVect,
+ 'Pharm2D':DataStructs.SparseBitVect,
+ 'Gobbi2D':DataStructs.SparseBitVect,
+ 'Morgan':DataStructs.UIntSparseIntVect
+ }
+supportedSimilarityMethods=list(iterkeys(similarityMethods))
+
+
+class LayeredOptions:
+ loadLayerFlags=0xFFFFFFFF
+ searchLayerFlags=0x7
+ minPath=1
+ maxPath=6
+ fpSize=1024
+ wordSize=32
+ nWords=fpSize//wordSize
+ @staticmethod
+ def GetFingerprint(mol,query=True):
+ if query:
+ flags=LayeredOptions.searchLayerFlags
+ else:
+ flags=LayeredOptions.loadLayerFlags
+ return Chem.LayeredFingerprint(mol,layerFlags=flags,
+ minPath=LayeredOptions.minPath,maxPath=LayeredOptions.maxPath,
+ fpSize=LayeredOptions.fpSize)
+ @staticmethod
+ def GetWords(mol,query=True):
+ txt = LayeredOptions.GetFingerprint(mol,query=query).ToBitString()
+ words = [int(txt[x:x+32],2) for x in range(0,len(txt),32)]
+ return words
+
+ @staticmethod
+ def GetQueryText(mol,query=True):
+ words = LayeredOptions.GetWords(mol,query=query)
+ colqs = []
+ for idx,word in enumerate(words):
+ if not word:
+ continue
+ idx = idx+1
+ colqs.append('%(word)d&Col_%(idx)d=%(word)d'%locals())
+ return ' and '.join(colqs)
+
+
+
+def BuildSigFactory(options=None,fdefFile=None,
+ bins=[(2,3),(3,4),(4,5),(5,6),(6,7),(7,8),(8,100)],
+ skipFeats=('LumpedHydrophobe','ZnBinder')):
+ if options:
+ fdefFile = options.fdefFile
+ if not fdefFile:
+ raise ValueError('bad fdef file')
+ from rdkit.Chem import ChemicalFeatures
+ from rdkit.Chem.Pharm2D import SigFactory
+ featFactory = ChemicalFeatures.BuildFeatureFactory(fdefFile)
+ sigFactory = SigFactory.SigFactory(featFactory,
+ skipFeats=skipFeats,
+ trianglePruneBins=False)
+ sigFactory.SetBins(bins)
+ return sigFactory
+
+def BuildAtomPairFP(mol):
+ from rdkit.Chem.AtomPairs import Pairs
+ fp=Pairs.GetAtomPairFingerprintAsIntVect(mol)
+ fp._sumCache = fp.GetTotalVal()
+ return fp
+def BuildTorsionsFP(mol):
+ from rdkit.Chem.AtomPairs import Torsions
+ fp=Torsions.GetTopologicalTorsionFingerprintAsIntVect(mol)
+ fp._sumCache = fp.GetTotalVal()
+ return fp
+def BuildRDKitFP(mol):
+ fp=Chem.RDKFingerprint(mol,nBitsPerHash=1)
+ return fp
+def BuildPharm2DFP(mol):
+ global sigFactory
+ from rdkit.Chem.Pharm2D import Generate
+ try:
+ fp=Generate.Gen2DFingerprint(mol,sigFactory)
+ except IndexError:
+ print('FAIL:',Chem.MolToSmiles(mol,True))
+ raise
+ return fp
+def BuildMorganFP(mol):
+ from rdkit.Chem import rdMolDescriptors
+ fp = rdMolDescriptors.GetMorganFingerprint(mol,2)
+ fp._sumCache = fp.GetTotalVal()
+ return fp
+
+def DepickleFP(pkl,similarityMethod):
+ if not isinstance(pkl,(bytes,str)):
+ pkl = str(pkl)
+ try:
+ klass=similarityMethods[similarityMethod]
+ fp = klass(pkl)
+ except:
+ import traceback
+ traceback.print_exc()
+ fp = cPickle.loads(pkl)
+ return fp
diff --git a/pool/shard006/Python/0057632_etl.py b/pool/shard006/Python/0057632_etl.py
new file mode 100644
index 0000000000000000000000000000000000000000..3796662ee7805a0fbae0cbe83df9cde9d53378d8
--- /dev/null
+++ b/pool/shard006/Python/0057632_etl.py
@@ -0,0 +1,64 @@
+#!/opt/zenoss/bin/python
+DEBUG_flag=False
+
+import os
+import sys
+import re
+import urllib2
+import json
+import time
+import datetime
+
+def help():
+ print "Usage:"
+ print "etl.py -url=YOUR_HOSTNAME -component=YOUR_COMPONENT_NAME -t=MAX_TIME_SINCE_LAST_UPDATE_IN_MINUTES"
+ sys.exit(3)
+
+if (len(sys.argv) == 4):
+ args_str = sys.argv[1] +" "+ sys.argv[2] +" "+ sys.argv[3]
+ args_str = args_str.lower()
+ if ("-url=" in args_str and "-component=" in args_str and "-t=" in args_str):
+ url_str = "http://" + sys.argv[1].replace("-url=","") + "/api/component/"
+ component_str = sys.argv[2].replace("-component=","")
+ time_str = sys.argv[3].replace("-t=", "")
+ if DEBUG_flag:
+ print url_str+component_str, component_str, time_str
+ try:
+ request = urllib2.urlopen(url_str+component_str)
+ content = request.read()
+ ### Here is the main part of code ###
+ json_dict = json.loads(content)
+ status = json_dict["status"].lower()
+ if (status == "ok"):
+ #Here we should check the time since last update
+ time_from_json = time.strptime(json_dict["updated"], "%Y-%m-%d %H:%M:%S")
+ time_now = time.localtime()
+ time_from_json = datetime.datetime(*time_from_json[0:6])
+ time_now = datetime.datetime(*time_now[0:6])
+ time_delta = time_now - time_from_json
+ if DEBUG_flag:
+ print time_from_json
+ print time_now
+ print time_delta.seconds
+ print time_delta.days
+ if (time_delta.days > 0 or ((time_delta.seconds/60) > int(time_str)) ):
+ print "WARNING - Time since last update is greater than %s minutes" % str(time_str)
+ sys.exit(1)
+ else:
+ print "OK - Time since last update is less than %s minutes" % str(time_str)
+ sys.exit(0)
+ else:
+ message = json_dict["message"]
+ print 'CRITICAL - %s' % (message)
+ sys.exit(2)
+ #####################################
+ except (urllib2.URLError, urllib2.HTTPError), e:
+ print 'CRITICAL - %s' % (e)
+ sys.exit(2)
+ else:
+ print "UNKNOWN - Wrong arguments"
+ help()
+ sys.exit(3)
+else:
+ print "UNKNOWN - Not enough arguments"
+ sys.exit(3)
\ No newline at end of file
diff --git a/pool/shard006/Python/0057637_utils.py b/pool/shard006/Python/0057637_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..2dff1e8d9a904a0438a546cc5fbe6559e700c750
--- /dev/null
+++ b/pool/shard006/Python/0057637_utils.py
@@ -0,0 +1,22 @@
+# -*- coding: utf-8 -*-
+# This file is part of Shuup.
+#
+# Copyright (c) 2012-2016, Shoop Commerce Ltd. All rights reserved.
+#
+# This source code is licensed under the AGPLv3 license found in the
+# LICENSE file in the root directory of this source tree.
+from shuup_tests.utils import replace_urls
+
+
+def get_admin_only_urls():
+ from django.conf.urls import patterns, url, include
+ from shuup.admin.urls import get_urls
+ class FauxUrlPatternsModule:
+ urlpatterns = get_urls()
+
+ return patterns('',
+ url(r'^sa/', include(FauxUrlPatternsModule, namespace="shuup_admin", app_name="shuup_admin")),
+ )
+
+def admin_only_urls():
+ return replace_urls(get_admin_only_urls())
diff --git a/pool/shard006/Python/0057641_link_finder.py b/pool/shard006/Python/0057641_link_finder.py
new file mode 100644
index 0000000000000000000000000000000000000000..8e7bffe0121ab7736bb02915c378d1a2a2fb1e69
--- /dev/null
+++ b/pool/shard006/Python/0057641_link_finder.py
@@ -0,0 +1,34 @@
+from __future__ import print_function
+from HTMLParser import HTMLParser
+from urllib2 import Request, urlopen
+from urlparse import urljoin
+
+class LinkFinder(HTMLParser):
+ def handle_starttag(self, tag, attrs):
+ if tag == 'a':
+ for (key, value) in attrs:
+ if key == 'href':
+ newUrl = urljoin(self.baseUrl, value)
+ self.links = self.links + [newUrl]
+
+ def getLinks(self, url):
+ self.links = []
+ self.baseUrl = url
+ response = urlopen(url)
+ try:
+ htmlBytes = response.read()
+ htmlString = htmlBytes.decode("utf-8")
+ self.feed(htmlString)
+ return list(set(self.links))
+ except Exception as e:
+ print(e)
+ return []
+
+def spider(url, maxPages):
+ parser = LinkFinder()
+ for link in parser.getLinks(url=url):
+ print(link)
+
+if __name__ == "__main__":
+ ## running ...
+ spider(url="http://eu.battle.net/wow/en/", maxPages=10)
diff --git a/pool/shard006/Python/0057645_sql.py b/pool/shard006/Python/0057645_sql.py
new file mode 100644
index 0000000000000000000000000000000000000000..1bd15af097328a4836d7a063a59873133bea8de7
--- /dev/null
+++ b/pool/shard006/Python/0057645_sql.py
@@ -0,0 +1,9 @@
+import sqlite3
+
+with sqlite3.connect("blog.db") as connection:
+ c = connection.cursor()
+ c.execute("""CREATE TABLE posts (title TEXT, post TEXT)""")
+ c.execute('INSERT INTO posts VALUES("Good", "I\'m good.")')
+ c.execute('INSERT INTO posts VALUES("Well", "I\'m well.")')
+ c.execute('INSERT INTO posts VALUES("Excellent", "I\'m excellent.")')
+ c.execute('INSERT INTO posts VALUES("Okay", "I\'m okay.")')
diff --git a/pool/shard006/Python/0057649_read.py b/pool/shard006/Python/0057649_read.py
new file mode 100644
index 0000000000000000000000000000000000000000..9867bdd0417cd993c1eccbc5bafb66cc0ae16211
--- /dev/null
+++ b/pool/shard006/Python/0057649_read.py
@@ -0,0 +1,26 @@
+#!/usr/bin/env python
+
+# Read the light level from a GPIO pin on a raspberry pi
+# Must be used with GPIO 0.3.1a or later - earlier verions
+# are not fast enough!
+
+import time
+
+class readLight:
+ def instantiate(self, input_gpio):
+ self.gpio = input_gpio
+ #self.gpio.setmode(self.gpio.BCM)
+ self.RCPIN = 38
+
+ def get_light_level(self):
+ reading = 0
+ self.gpio.setup(self.RCPIN, self.gpio.OUT)
+ self.gpio.output(self.RCPIN, self.gpio.LOW)
+ # 10 milliseconds
+ time.sleep(0.01)
+
+ self.gpio.setup(self.RCPIN, self.gpio.IN)
+ # This takes about 1 millisecond per loop cycle
+ while (self.gpio.input(self.RCPIN) == self.gpio.LOW):
+ reading += 1
+ return reading
diff --git a/pool/shard006/Python/0057651_euler38.py b/pool/shard006/Python/0057651_euler38.py
new file mode 100644
index 0000000000000000000000000000000000000000..66c7b241344f03037e4fdc5e8a88a6155ebd5fe3
--- /dev/null
+++ b/pool/shard006/Python/0057651_euler38.py
@@ -0,0 +1,50 @@
+#coding=utf-8
+dig='123456789'
+
+result=[]
+results=[]
+for i in range(5000,9999):
+ tmp=str(i)+str(i*2)
+ flag=True
+ for j in dig:
+ if j not in tmp:
+ flag=False
+ if flag:
+ result.append(i)
+ results.append(int(tmp))
+
+for i in range(100,333):
+ tmp=str(i)+str(i*2)+str(i*3)
+ flag=True
+ for j in dig:
+ if j not in tmp or len(tmp)!=9:
+ flag=False
+ break
+ if flag:
+ result.append(i)
+ results.append(int(tmp))
+
+for i in range(10,34):
+ tmp=str(i)+str(i*2)+str(i*3)+str(i*4)
+ flag=True
+ for j in dig:
+ if j not in tmp or len(tmp)!=9:
+ flag=False
+ break
+ if flag:
+ result.append(i)
+ results.append(int(tmp))
+
+for i in range(1,10):
+ tmp=str(i)+str(i*2)+str(i*3)+str(i*4)+str(i*5)
+ flag=True
+ for j in dig:
+ if j not in tmp or len(tmp)!=9:
+ flag=False
+ break
+ if flag:
+ result.append(i)
+ results.append(int(tmp))
+print result
+print results
+print max(results)
\ No newline at end of file
diff --git a/pool/shard006/Python/0057652_spacy-nlp.py b/pool/shard006/Python/0057652_spacy-nlp.py
new file mode 100644
index 0000000000000000000000000000000000000000..5ce70a2429467ac78cad07533541f15fe98bf627
--- /dev/null
+++ b/pool/shard006/Python/0057652_spacy-nlp.py
@@ -0,0 +1,122 @@
+import os
+import sys
+
+from spacy.en import English
+
+#INSTANTIATE SPACY PARSER
+nlp = English()
+
+def token_process(file_in):
+ #_doc = nlp(unicode(file_in, encoding="utf-8"))
+ _doc = nlp(file_in)
+ return _doc
+
+def sent_process(file_in):
+ #_doc = nlp(unicode(file_in, encoding="utf-8"))
+ _doc = nlp(file_in)
+ _sents = _doc.sents
+ return _sents
+
+def pos_process(file_in):
+ _pos_tagged = []
+ #_doc = nlp(unicode(file_in, encoding="utf-8"))
+ _doc = nlp(file_in)
+# _doc = _doc.decode("utf-8")
+# _doc = _doc.encode("ascii", "ignore")
+ for token in _doc:
+ token_pos = '{}/{}'.format(token.orth_.encode("ascii", "ignore"), token.pos_)
+ _pos_tagged.append(token_pos)
+ return _pos_tagged
+
+def lemma_process(file_in):
+ _lemmas = []
+ #_doc = nlp(unicode(file_in, encoding="utf-8"))
+ _doc = nlp(file_in)
+ for token in _doc:
+ token_lemma = '{}/{}/{}'.format(token.orth_.encode("ascii", "ignore"), token.lemma_.encode("ascii", "ignore"), token.pos_)
+ _lemmas.append(token_lemma)
+ return _lemmas
+
+def ner_process(file_in):
+ _ner_tagged = []
+ _doc = nlp(file_in)
+ #_doc = nlp(unicode(file_in, encoding="utf-8"))
+ for token in _doc:
+ if token.ent_type_ != "":
+ token_ner = '{}/{}/{}/{}'.format(token.orth_.encode('ascii', 'ignore'), token.lemma_.encode("ascii", "ignore"), token.pos_, '_')
+ else:
+ token_ner = '{}/{}/{}/{}'.format(token.orth_.encode('ascii', 'ignore'), token.lemma_.encode("ascii", "ignore"), token.pos_, token.ent_type_)
+ _ner_tagged.append(token_ner)
+ return _ner_tagged
+
+def main():
+ doc = []
+ sents = []
+ pos_tagged = []
+ lemmas = []
+ ner_tagged = []
+
+ file = ''
+ #Read file without line breaks
+ with open(sys.argv[1], 'r') as _file:
+ file = _file.read().replace('\n', ' ')
+
+ file = unicode(file, encoding="utf-8")
+
+ if file == '':
+ print 'File not read properly'
+ sys.exit()
+
+ if sys.argv[-1] == 'tokenize':
+ doc = token_process(file)
+ for token in doc:
+ print token
+
+ elif sys.argv[-1] == 'sent_split':
+ sents = sent_process(file)
+ for sent in sents:
+ print sent
+
+ elif sys.argv[-1] == 'pos_tag':
+ pos_tagged = pos_process(file)
+ for pos in pos_tagged:
+ print pos
+
+ elif sys.argv[-1] == 'lemmatize':
+ lemmas = lemma_process(file)
+ for lemma in lemmas:
+ print lemma
+
+ elif sys.argv[-1] == 'ner_tag':
+ ner_tagged = ner_process(file)
+ for ner in ner_tagged:
+ print ner
+
+#BEGIN PREPROCESSING EXECUTION
+main()
+
+#TO KEEP LINE BREAKS
+#with open('/Users/stc1563/programming/research/test-cases/_raw/lemmaCase-v6.txt', 'r') as f:
+# strIn=f.read();
+# for line in f:
+# tokenSents = nlp(unicode(line,encoding="utf-8"))
+# for span in tokenSents.sents:
+# sent = ''.join(tokenSents[i].string for i in range(span.start, span.end)).strip()
+# sents.append(sent)
+
+#spacy parser creates tokens objects with callable methods that return nlp component results
+#tokens = nlp(unicode(strIn,encoding="utf-8"))
+
+#Sents property returns spans
+#Spans have indices into original string
+#where each index value returns a token
+#SENTENCE SPLITTING
+#for span in tokens.sents:
+##go from the start to the end of the span, returning each token in the sentence
+##combine each token using join()
+# sent = ''.join(tokens[i].string for i in range(span.start, span.end)).strip()
+# sents.append(sent)
+#for sentence in sents:
+# tokenCount+=1
+# print '{}'.format(sentence.encode('ascii', 'ignore'))
+#END SENTENCE SPLITTING
\ No newline at end of file
diff --git a/pool/shard006/Python/0057655_app_initialization_test.py b/pool/shard006/Python/0057655_app_initialization_test.py
new file mode 100644
index 0000000000000000000000000000000000000000..acf8e2eaa4bd11870814fbddb10b38dac001c6de
--- /dev/null
+++ b/pool/shard006/Python/0057655_app_initialization_test.py
@@ -0,0 +1,51 @@
+from superdesk.tests import TestCase
+from .app_initialize import AppInitializeWithDataCommand
+from .app_scaffold_data import AppScaffoldDataCommand
+from superdesk import get_resource_service
+
+
+class AppInitializeWithDataCommandTestCase(TestCase):
+
+ def setUp(self):
+ super().setUp()
+
+ def test_app_initialization(self):
+ with self.app.app_context():
+ command = AppInitializeWithDataCommand()
+ result = command.run()
+ self.assertEquals(result, 0)
+
+ def test_app_initialization_multiple_loads(self):
+ with self.app.app_context():
+ command = AppInitializeWithDataCommand()
+ result = command.run()
+ self.assertEquals(result, 0)
+ result = command.run()
+ self.assertEquals(result, 0)
+
+ def data_scaffolding_test(self):
+ with self.app.app_context():
+ command = AppInitializeWithDataCommand()
+ result = command.run()
+ self.assertEquals(result, 0)
+
+ service = get_resource_service('text_archive')
+ docs = [{
+ 'type': 'text',
+ 'abstract': 'test abstract {}'.format(x),
+ 'headline': 'test headline {}'.format(x),
+ 'body_html': 'test long story body {}'.format(x)
+ } for x in range(0, 40)]
+ service.post(docs)
+
+ stories_per_desk = 2
+ existing_desks = 1
+ command = AppScaffoldDataCommand()
+ result = command.run(stories_per_desk)
+ self.assertEquals(result, 0)
+
+ cursor = get_resource_service('desks').get_from_mongo(None, {})
+ self.assertEquals(cursor.count(), existing_desks)
+
+ cursor = get_resource_service('archive').get_from_mongo(None, {})
+ self.assertEquals(cursor.count(), existing_desks * stories_per_desk)
diff --git a/pool/shard006/Python/0057662_filediff_comment.py b/pool/shard006/Python/0057662_filediff_comment.py
new file mode 100644
index 0000000000000000000000000000000000000000..42447693faa42e00ab5077aa547f29f5c5f211ec
--- /dev/null
+++ b/pool/shard006/Python/0057662_filediff_comment.py
@@ -0,0 +1,56 @@
+from djblets.util.decorators import augment_method_from
+
+from reviewboard.webapi.resources.base_diff_comment import \
+ BaseDiffCommentResource
+
+
+class FileDiffCommentResource(BaseDiffCommentResource):
+ """Provides information on comments made on a particular per-file diff.
+
+ The list of comments cannot be modified from this resource. It's meant
+ purely as a way to see existing comments that were made on a diff. These
+ comments will span all public reviews.
+ """
+ allowed_methods = ('GET',)
+ policy_id = 'diff_comment'
+ model_parent_key = 'filediff'
+ uri_object_key = None
+
+ mimetype_list_resource_name = 'file-diff-comments'
+ mimetype_item_resource_name = 'file-diff-comment'
+
+ def get_queryset(self, request, diff_revision, filediff_id,
+ *args, **kwargs):
+ """Returns a queryset for Comment models.
+
+ This filters the query for comments on the specified review request
+ and made on the specified diff revision, which are either public or
+ owned by the requesting user.
+
+ If the queryset is being used for a list of comment resources,
+ then this can be further filtered by passing ``?interdiff-revision=``
+ on the URL to match the given interdiff revision, and
+ ``?line=`` to match comments on the given line number.
+ """
+ q = super(FileDiffCommentResource, self).get_queryset(
+ request, *args, **kwargs)
+ return q.filter(filediff__diffset__revision=diff_revision,
+ filediff=filediff_id)
+
+ @augment_method_from(BaseDiffCommentResource)
+ def get_list(self, request, diff_revision=None, *args, **kwargs):
+ """Returns the list of comments on a file in a diff.
+
+ This list can be filtered down by using the ``?line=`` and
+ ``?interdiff-revision=``.
+
+ To filter for comments that start on a particular line in the file,
+ using ``?line=``.
+
+ To filter for comments that span revisions of diffs, you can specify
+ the second revision in the range using ``?interdiff-revision=``.
+ """
+ pass
+
+
+filediff_comment_resource = FileDiffCommentResource()
diff --git a/pool/shard006/Python/0057663_test_protocol_rdp_tpkt.py b/pool/shard006/Python/0057663_test_protocol_rdp_tpkt.py
new file mode 100644
index 0000000000000000000000000000000000000000..9e2779210e232809791f32678494caac1d896321
--- /dev/null
+++ b/pool/shard006/Python/0057663_test_protocol_rdp_tpkt.py
@@ -0,0 +1,115 @@
+#
+# Copyright (c) 2014 Sylvain Peyrefitte
+#
+# This file is part of rdpy.
+#
+# rdpy 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 .
+#
+
+"""
+unit test for rdpy.protocol.rdp.tpkt module
+"""
+
+import os, sys
+# Change path so we find rdpy
+sys.path.insert(1, os.path.join(sys.path[0], '..'))
+
+import unittest
+import rdpy.protocol.rdp.tpkt as tpkt
+import rdpy.core.type as type
+import rdpy.core.error as error
+
+class TPKTTest(unittest.TestCase):
+ """
+ @summary: test case for tpkt layer (RDP)
+ """
+
+ class TPKT_PASS(Exception):
+ pass
+
+ class TPKT_FAIL(Exception):
+ pass
+
+ def test_tpkt_layer_connect(self):
+ """
+ @summary: test forward connect event to presentation layer
+ """
+ class Presentation(object):
+ def connect(self):
+ raise TPKTTest.TPKT_PASS()
+
+ layer = tpkt.TPKT(Presentation())
+ self.assertRaises(TPKTTest.TPKT_PASS, layer.connect)
+
+ def test_tpkt_layer_recv(self):
+ """
+ @summary: test receive in classic case
+ """
+ class Presentation(object):
+ def connect(self):
+ pass
+ def recv(self, data):
+ data.readType(type.String("test_tpkt_layer_recv", constant = True))
+ raise TPKTTest.TPKT_PASS()
+
+ message = type.String("test_tpkt_layer_recv")
+
+ s = type.Stream()
+ s.writeType((type.UInt8(tpkt.Action.FASTPATH_ACTION_X224), type.UInt8(), type.UInt16Be(type.sizeof(message) + 4), message))
+
+ layer = tpkt.TPKT(Presentation())
+ layer.connect()
+ self.assertRaises(TPKTTest.TPKT_PASS, layer.dataReceived, s.getvalue())
+
+ def test_tpkt_layer_recv_fastpath(self):
+ """
+ @summary: test receive in fastpath case
+ """
+ class FastPathLayer(tpkt.IFastPathListener):
+ def setFastPathSender(self, fastPathSender):
+ pass
+ def recvFastPath(self, secFlag, fastPathS):
+ fastPathS.readType(type.String("test_tpkt_layer_recv_fastpath", constant = True))
+ raise TPKTTest.TPKT_PASS()
+
+ message = type.String("test_tpkt_layer_recv_fastpath")
+
+ s = type.Stream()
+ s.writeType((type.UInt8(tpkt.Action.FASTPATH_ACTION_FASTPATH), type.UInt8(type.sizeof(message) + 2), message))
+
+ layer = tpkt.TPKT(None)
+ layer.initFastPath(FastPathLayer())
+ layer.connect()
+ self.assertRaises(TPKTTest.TPKT_PASS, layer.dataReceived, s.getvalue())
+
+ def test_tpkt_layer_recv_fastpath_ext_length(self):
+ """
+ @summary: test receive in fastpath case with extended length
+ """
+ class FastPathLayer(tpkt.IFastPathListener):
+ def setFastPathSender(self, fastPathSender):
+ pass
+ def recvFastPath(self, secflag, fastPathS):
+ fastPathS.readType(type.String("test_tpkt_layer_recv_fastpath_ext_length", constant = True))
+ raise TPKTTest.TPKT_PASS()
+
+ message = type.String("test_tpkt_layer_recv_fastpath_ext_length")
+
+ s = type.Stream()
+ s.writeType((type.UInt8(tpkt.Action.FASTPATH_ACTION_FASTPATH), type.UInt16Be((type.sizeof(message) + 3) | 0x8000), message))
+
+ layer = tpkt.TPKT(None)
+ layer.initFastPath(FastPathLayer())
+ layer.connect()
+ self.assertRaises(TPKTTest.TPKT_PASS, layer.dataReceived, s.getvalue())
diff --git a/pool/shard006/Python/0057664_rest-server-v2.py b/pool/shard006/Python/0057664_rest-server-v2.py
new file mode 100644
index 0000000000000000000000000000000000000000..ff6acb174a9ccec84ce34f49c23fe70452a2f64b
--- /dev/null
+++ b/pool/shard006/Python/0057664_rest-server-v2.py
@@ -0,0 +1,118 @@
+#!flask/bin/python
+
+"""Alternative version of the ToDo RESTful server implemented using the
+Flask-RESTful extension."""
+
+from flask import Flask, jsonify, abort, make_response
+from flask.ext.restful import Api, Resource, reqparse, fields, marshal
+from flask.ext.httpauth import HTTPBasicAuth
+
+app = Flask(__name__, static_url_path="")
+api = Api(app)
+auth = HTTPBasicAuth()
+
+
+@auth.get_password
+def get_password(username):
+ if username == 'miguel':
+ return 'python'
+ return None
+
+
+@auth.error_handler
+def unauthorized():
+ # return 403 instead of 401 to prevent browsers from displaying the default
+ # auth dialog
+ return make_response(jsonify({'message': 'Unauthorized access'}), 403)
+
+tasks = [
+ {
+ 'id': 1,
+ 'title': u'Buy groceries',
+ 'description': u'Milk, Cheese, Pizza, Fruit, Tylenol',
+ 'done': False
+ },
+ {
+ 'id': 2,
+ 'title': u'Learn Python',
+ 'description': u'Need to find a good Python tutorial on the web',
+ 'done': False
+ }
+]
+
+task_fields = {
+ 'title': fields.String,
+ 'description': fields.String,
+ 'done': fields.Boolean,
+ 'uri': fields.Url('task')
+}
+
+
+class TaskListAPI(Resource):
+ decorators = [auth.login_required]
+
+ def __init__(self):
+ self.reqparse = reqparse.RequestParser()
+ self.reqparse.add_argument('title', type=str, required=True,
+ help='No task title provided',
+ location='json')
+ self.reqparse.add_argument('description', type=str, default="",
+ location='json')
+ super(TaskListAPI, self).__init__()
+
+ def get(self):
+ return {'tasks': [marshal(task, task_fields) for task in tasks]}
+
+ def post(self):
+ args = self.reqparse.parse_args()
+ task = {
+ 'id': tasks[-1]['id'] + 1,
+ 'title': args['title'],
+ 'description': args['description'],
+ 'done': False
+ }
+ tasks.append(task)
+ return {'task': marshal(task, task_fields)}, 201
+
+
+class TaskAPI(Resource):
+ decorators = [auth.login_required]
+
+ def __init__(self):
+ self.reqparse = reqparse.RequestParser()
+ self.reqparse.add_argument('title', type=str, location='json')
+ self.reqparse.add_argument('description', type=str, location='json')
+ self.reqparse.add_argument('done', type=bool, location='json')
+ super(TaskAPI, self).__init__()
+
+ def get(self, id):
+ task = [task for task in tasks if task['id'] == id]
+ if len(task) == 0:
+ abort(404)
+ return {'task': marshal(task[0], task_fields)}
+
+ def put(self, id):
+ task = [task for task in tasks if task['id'] == id]
+ if len(task) == 0:
+ abort(404)
+ task = task[0]
+ args = self.reqparse.parse_args()
+ for k, v in args.items():
+ if v is not None:
+ task[k] = v
+ return {'task': marshal(task, task_fields)}
+
+ def delete(self, id):
+ task = [task for task in tasks if task['id'] == id]
+ if len(task) == 0:
+ abort(404)
+ tasks.remove(task[0])
+ return {'result': True}
+
+
+api.add_resource(TaskListAPI, '/todo/api/v1.0/tasks', endpoint='tasks')
+api.add_resource(TaskAPI, '/todo/api/v1.0/tasks/', endpoint='task')
+
+
+if __name__ == '__main__':
+ app.run(debug=True)
diff --git a/pool/shard006/Python/0057665_word_extractor.py b/pool/shard006/Python/0057665_word_extractor.py
new file mode 100644
index 0000000000000000000000000000000000000000..33a804a72d3ea36d0e678fd0c3e1c333d725a5d6
--- /dev/null
+++ b/pool/shard006/Python/0057665_word_extractor.py
@@ -0,0 +1,75 @@
+# This file is part of Boomer Core.
+#
+# Boomer Core 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.
+#
+# Boomer Core 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 Boomer Core. If not, see .
+#
+# Forked from Mycroft Core on 2017-07-29
+
+from speech_recognition import AudioData
+
+__author__ = 'jdorleans'
+
+
+class WordExtractor:
+ SILENCE_SECS = 0.1
+ PRECISION_RATE = 0.01
+
+ def __init__(self, audio, recognizer, metrics):
+ self.audio = audio
+ self.recognizer = recognizer
+ self.audio_size = len(self.audio.frame_data)
+ self.delta = int(self.audio_size / 2)
+ self.begin = 0
+ self.end = self.audio_size
+ self.precision = int(self.audio_size * self.PRECISION_RATE)
+ self.silence_data = self.create_silence(self.SILENCE_SECS,
+ self.audio.sample_rate,
+ self.audio.sample_width)
+ self.metrics = metrics
+
+ def __add(self, is_begin, value):
+ if is_begin:
+ self.begin += value
+ else:
+ self.end += value
+
+ def __calculate_marker(self, is_begin):
+ dt = self.delta
+ sign = 1 if is_begin else -1
+
+ while dt > self.precision:
+ self.__add(is_begin, dt * sign)
+ segment = self.audio.frame_data[self.begin:self.end]
+ found = self.recognizer.is_recognized(segment, self.metrics)
+ if not found:
+ self.__add(is_begin, dt * -sign)
+ dt = int(dt / 2)
+
+ def calculate_range(self):
+ self.__calculate_marker(False)
+ self.__calculate_marker(True)
+
+ @staticmethod
+ def create_silence(seconds, sample_rate, sample_width):
+ return '\0' * int(seconds * sample_rate * sample_width)
+
+ def get_audio_data_before(self):
+ byte_data = self.audio.frame_data[0:self.begin] + self.silence_data
+ return AudioData(byte_data, self.audio.sample_rate,
+ self.audio.sample_width)
+
+ def get_audio_data_after(self):
+ byte_data = self.silence_data + self.audio.frame_data[self.end:
+ self.audio_size]
+ return AudioData(byte_data, self.audio.sample_rate,
+ self.audio.sample_width)
diff --git a/pool/shard006/Python/0057667_Choice.py b/pool/shard006/Python/0057667_Choice.py
new file mode 100644
index 0000000000000000000000000000000000000000..67b6d0757099f4d21524d1fd0053b500927b62f5
--- /dev/null
+++ b/pool/shard006/Python/0057667_Choice.py
@@ -0,0 +1,48 @@
+import random
+
+from CommandTemplate import CommandTemplate
+
+
+class Command(CommandTemplate):
+ triggers = ['choice', 'choose']
+ helptext = "Helps you make a choice between options in a comma-separated list"
+
+ possibleReplies = ["Hmm, I'd go with {}", "Out of those, {} sounds the least bad", "{}, obviously",
+ "Let's go with... {}. No wait! No, yeah, that one", "I don't know! *rolls dice* Seems you should go for {}",
+ "Pick {0}, pick {0}!", "Eh, {} will do", "Why not {}?", "The first one! The last one! {}!", "Just pick {}"]
+
+ def pickRandomReply(self):
+ #Based on a suggestion by ekimekim
+ while True:
+ #Shuffle the list initially
+ random.shuffle(self.possibleReplies)
+ #Then just feed a reply every time one is requested. Once we run out, the list is reshuffled, ready to start again
+ for reply in self.possibleReplies:
+ yield reply
+
+ def execute(self, message):
+ """
+ :type message: IrcMessage.IrcMessage
+ """
+ replytext = None
+ if message.messagePartsLength == 0:
+ replytext = "My choice would be to provide me with some choices, preferably separated by commas"
+ else:
+ if ';' in message.message:
+ choices = message.message.split(';')
+ elif ',' in message.message:
+ choices = message.message.split(',')
+ else:
+ choices = message.messageParts
+ #Remove all the empty choices from the list
+ choices = filter(bool, choices)
+ if len(choices) == 0:
+ replytext = "That's just an empty list of choices... I'll pick nothing then"
+ elif len(choices) == 1:
+ replytext = "Ooh, that's a tough one. I'd go with the first option, seeing as there is only one"
+ else:
+ #Make a new random generator with the choices as seed, so every time you ask the bot to make a choice from the same list, it picks the same outcome
+ choice = random.Random(tuple(sorted(choices))).choice(choices).strip()
+ #Pick a random reply sentence, and then add in the previously picked choice, enclosed in quotes
+ replytext = self.pickRandomReply().next().format('"' + choice + '"')
+ message.bot.sendMessage(message.source, replytext)
\ No newline at end of file
diff --git a/pool/shard006/Python/0057668_hog_template.py b/pool/shard006/Python/0057668_hog_template.py
new file mode 100644
index 0000000000000000000000000000000000000000..c5ce87c7713a5d79a0d8bafdc19efc39ee0d5175
--- /dev/null
+++ b/pool/shard006/Python/0057668_hog_template.py
@@ -0,0 +1,232 @@
+"""The Game of Hog."""
+
+from dice import four_sided, six_sided, make_test_dice
+from ucb import main, trace, log_current_line, interact
+
+GOAL_SCORE = 100 # The goal of Hog is to score 100 points.
+
+######################
+# Phase 1: Simulator #
+######################
+
+def roll_dice(num_rolls, dice=six_sided):
+ """Roll DICE for NUM_ROLLS times. Return either the sum of the outcomes,
+ or 1 if a 1 is rolled (Pig out). This calls DICE exactly NUM_ROLLS times.
+
+ num_rolls: The number of dice rolls that will be made; at least 1.
+ dice: A zero-argument function that returns an integer outcome.
+ """
+ # These assert statements ensure that num_rolls is a positive integer.
+ assert type(num_rolls) == int, 'num_rolls must be an integer.'
+ assert num_rolls > 0, 'Must roll at least once.'
+ "*** YOUR CODE HERE ***"
+
+def take_turn(num_rolls, opponent_score, dice=six_sided):
+ """Simulate a turn rolling NUM_ROLLS dice, which may be 0 (Free bacon).
+
+ num_rolls: The number of dice rolls that will be made.
+ opponent_score: The total score of the opponent.
+ dice: A function of no args that returns an integer outcome.
+ """
+ assert type(num_rolls) == int, 'num_rolls must be an integer.'
+ assert num_rolls >= 0, 'Cannot roll a negative number of dice.'
+ assert num_rolls <= 10, 'Cannot roll more than 10 dice.'
+ assert opponent_score < 100, 'The game should be over.'
+ "*** YOUR CODE HERE ***"
+ edits
+
+def select_dice(score, opponent_score):
+ """Select six-sided dice unless the sum of SCORE and OPPONENT_SCORE is a
+ multiple of 7, in which case select four-sided dice (Hog wild).
+ """
+ "*** YOUR CODE HERE ***"
+
+def bid_for_start(bid0, bid1, goal=GOAL_SCORE):
+ """Given the bids BID0 and BID1 of each player, returns three values:
+
+ - the starting score of player 0
+ - the starting score of player 1
+ - the number of the player who rolls first (0 or 1)
+ """
+ assert bid0 >= 0 and bid1 >= 0, "Bids should be non-negative!"
+ assert type(bid0) == int and type(bid1) == int, "Bids should be integers!"
+
+ # The buggy code is below:
+ if bid0 == bid1:
+ return 0, goal, goal
+ if bid0 == bid1 - 5:
+ return 0, 0, 0
+ if bid1 == bid0 + 5:
+ return 10, 0, 1
+ if bid1 > bid0:
+ return bid1, bid0, 0
+ else:
+ return bid0, bid1, 1
+
+def other(who):
+ """Return the other player, for a player WHO numbered 0 or 1.
+
+ >>> other(0)
+ 1
+ >>> other(1)
+ 0
+ """
+ return 1 - who
+
+def play(strategy0, strategy1, score0=0, score1=0, goal=GOAL_SCORE):
+ """Simulate a game and return the final scores of both players, with
+ Player 0's score first, and Player 1's score second.
+
+ A strategy is a function that takes two total scores as arguments
+ (the current player's score, and the opponent's score), and returns a
+ number of dice that the current player will roll this turn.
+
+ strategy0: The strategy function for Player 0, who plays first
+ strategy1: The strategy function for Player 1, who plays second
+ score0 : The starting score for Player 0
+ score1 : The starting score for Player 1
+ """
+ who = 0 # Which player is about to take a turn, 0 (first) or 1 (second)
+ "*** YOUR CODE HERE ***"
+ return score0, score1 # You may want to change this line.
+
+#######################
+# Phase 2: Strategies #
+#######################
+
+def always_roll(n):
+ """Return a strategy that always rolls N dice.
+
+ A strategy is a function that takes two total scores as arguments
+ (the current player's score, and the opponent's score), and returns a
+ number of dice that the current player will roll this turn.
+
+ >>> strategy = always_roll(5)
+ >>> strategy(0, 0)
+ 5
+ >>> strategy(99, 99)
+ 5
+ """
+ def strategy(score, opponent_score):
+ return n
+ return strategy
+
+# Experiments
+
+def make_averaged(fn, num_samples=1000):
+ """Return a function that returns the average_value of FN when called.
+
+ To implement this function, you will have to use *args syntax, a new Python
+ feature introduced in this project. See the project description.
+
+ >>> dice = make_test_dice(3, 1, 5, 6)
+ >>> averaged_dice = make_averaged(dice, 1000)
+ >>> averaged_dice()
+ 3.75
+ >>> make_averaged(roll_dice, 1000)(2, dice)
+ 6.0
+
+ In this last example, two different turn scenarios are averaged.
+ - In the first, the player rolls a 3 then a 1, receiving a score of 1.
+ - In the other, the player rolls a 5 and 6, scoring 11.
+ Thus, the average value is 6.0.
+ """
+ "*** YOUR CODE HERE ***"
+
+def max_scoring_num_rolls(dice=six_sided):
+ """Return the number of dice (1 to 10) that gives the highest average turn
+ score by calling roll_dice with the provided DICE. Assume that dice always
+ return positive outcomes.
+
+ >>> dice = make_test_dice(3)
+ >>> max_scoring_num_rolls(dice)
+ 10
+ """
+ "*** YOUR CODE HERE ***"
+
+def winner(strategy0, strategy1):
+ """Return 0 if strategy0 wins against strategy1, and 1 otherwise."""
+ score0, score1 = play(strategy0, strategy1)
+ if score0 > score1:
+ return 0
+ else:
+ return 1
+
+def average_win_rate(strategy, baseline=always_roll(5)):
+ """Return the average win rate (0 to 1) of STRATEGY against BASELINE."""
+ win_rate_as_player_0 = 1 - make_averaged(winner)(strategy, baseline)
+ win_rate_as_player_1 = make_averaged(winner)(baseline, strategy)
+ return (win_rate_as_player_0 + win_rate_as_player_1) / 2 # Average results
+
+def run_experiments():
+ """Run a series of strategy experiments and report results."""
+ if True: # Change to False when done finding max_scoring_num_rolls
+ six_sided_max = max_scoring_num_rolls(six_sided)
+ print('Max scoring num rolls for six-sided dice:', six_sided_max)
+ four_sided_max = max_scoring_num_rolls(four_sided)
+ print('Max scoring num rolls for four-sided dice:', four_sided_max)
+
+ if False: # Change to True to test always_roll(8)
+ print('always_roll(8) win rate:', average_win_rate(always_roll(8)))
+
+ if False: # Change to True to test bacon_strategy
+ print('bacon_strategy win rate:', average_win_rate(bacon_strategy))
+
+ if False: # Change to True to test swap_strategy
+ print('swap_strategy win rate:', average_win_rate(swap_strategy))
+
+ if False: # Change to True to test final_strategy
+ print('final_strategy win rate:', average_win_rate(final_strategy))
+
+ "*** You may add additional experiments as you wish ***"
+
+# Strategies
+
+def bacon_strategy(score, opponent_score, margin=8, num_rolls=5):
+ """This strategy rolls 0 dice if that gives at least MARGIN points,
+ and rolls NUM_ROLLS otherwise.
+ """
+ "*** YOUR CODE HERE ***"
+ return None # Replace this statement
+
+def swap_strategy(score, opponent_score, margin=8, num_rolls=5):
+ """This strategy rolls 0 dice when it would result in a beneficial swap and
+ rolls NUM_ROLLS if it would result in a harmful swap. It also rolls
+ 0 dice if that gives at least MARGIN points and rolls
+ NUM_ROLLS otherwise.
+ """
+ "*** YOUR CODE HERE ***"
+ return None # Replace this statement
+
+
+def final_strategy(score, opponent_score):
+ """Write a brief description of your final strategy.
+
+ *** YOUR DESCRIPTION HERE ***
+ """
+ "*** YOUR CODE HERE ***"
+ return 5 # Replace this statement
+
+
+##########################
+# Command Line Interface #
+##########################
+
+# Note: Functions in this section do not need to be changed. They use features
+# of Python not yet covered in the course.
+
+
+@main
+def run(*args):
+ """Read in the command-line argument and calls corresponding functions.
+
+ This function uses Python syntax/techniques not yet covered in this course.
+ """
+ import argparse
+ parser = argparse.ArgumentParser(description="Play Hog")
+ parser.add_argument('--run_experiments', '-r', action='store_true',
+ help='Runs strategy experiments')
+ args = parser.parse_args()
+
+ if args.run_experiments:
+ run_experiments()
diff --git a/pool/shard006/Python/0057670_test_image_lst.py b/pool/shard006/Python/0057670_test_image_lst.py
new file mode 100644
index 0000000000000000000000000000000000000000..91bb81ab58c59c17f7c11e0d1881a678ac9cbd6b
--- /dev/null
+++ b/pool/shard006/Python/0057670_test_image_lst.py
@@ -0,0 +1,142 @@
+# ===============================================================================
+# Copyright 2017 dgketchum
+#
+# 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.
+# ===============================================================================
+
+import os
+import unittest
+from fiona import open as fopen
+from rasterio import open as rasopen
+
+from sat_image.image import Landsat8, Landsat5, Landsat7
+
+
+class TestImageLST5(unittest.TestCase):
+ def setUp(self):
+ self.dir_name_LT5 = 'tests/data/ssebop_test/lt5/041_025/2000/LT50410252000194AAA01'
+ self.l5 = Landsat5(self.dir_name_LT5)
+ self.lst = self.l5.land_surface_temp()
+ self.lst_raster_path = os.path.join(self.dir_name_LT5, 'lst5_test.tif')
+ self.l5.save_array(self.lst, self.lst_raster_path)
+ self.point_file = 'tests/data/points/041_025_CA_Let_points.shp'
+ self.eef_lst_raster = os.path.join('tests/data/ssebop_test/lt5/041_025/2000/',
+ 'LT50410252000194AAA01',
+ 'LT50410252000194AAA01_LST_EEF.tif')
+
+ def test_surface_temps(self):
+ points_dict = raster_point_extract(lst_raster=self.lst_raster_path,
+ eef_raster=self.eef_lst_raster,
+ points=self.point_file)
+ for key, val in points_dict.items():
+ eef = val['eef_lst']
+ lst = val['lst_found']
+ ratio = eef / lst
+ print('Ratio at {} of EEFlux:LST calculated is {}.'.format(
+ key, ratio))
+ self.assertAlmostEqual(ratio, 1.0, delta=0.01)
+ os.remove(self.lst_raster_path)
+
+
+class TestImageLST7(unittest.TestCase):
+ def setUp(self):
+ self.dir_name_LT7 = 'tests/data/ssebop_test/le7/041_025/2000/LE70410252000234PAC00'
+ self.l7 = Landsat7(self.dir_name_LT7)
+ self.lst = self.l7.land_surface_temp()
+ self.lst_raster_path = os.path.join(self.dir_name_LT7, 'lst7_test.tif')
+ self.l7.save_array(self.lst, self.lst_raster_path)
+ self.point_file = 'tests/data/points/041_025_CA_Let_points.shp'
+ self.eef_lst_raster = os.path.join('tests/data/ssebop_test/le7/041_025/2000',
+ 'LE70410252000234PAC00/LE70410252000234PAC00_LST_EEF.tif')
+
+ def test_surface_temps(self):
+ points_dict = raster_point_extract(lst_raster=self.lst_raster_path,
+ eef_raster=self.eef_lst_raster,
+ points=self.point_file)
+ for key, val in points_dict.items():
+ eef = val['eef_lst']
+ lst = val['lst_found']
+ ratio = eef / lst
+ print('Ratio at {} of EEFlux:LST calculated is {}.'.format(
+ key, ratio))
+ self.assertAlmostEqual(ratio, 1.0, delta=0.01)
+ os.remove(self.lst_raster_path)
+
+
+class TestImageLST8(unittest.TestCase):
+ def setUp(self):
+ self.dir_name_LT8 = 'tests/data/ssebop_test/lc8/038_027/2014/LC80380272014227LGN01'
+ self.l8 = Landsat8(self.dir_name_LT8)
+ self.lst = self.l8.land_surface_temp()
+ # self.lst_raster_path = os.path.join(self.dir_name_LT8, 'lst8_test.tif')
+ self.lst_raster_path = '/data01/images/sandbox/lst8_test.tif'
+ self.l8.save_array(self.lst, self.lst_raster_path)
+ self.point_file = 'tests/data/points/038_027_US_Mj_points.shp'
+ self.eef_lst_raster = os.path.join('tests/data/ssebop_test/lc8/038_027',
+ '2014/LC80380272014227LGN01/LC80380272014227LGN01_LST_EEF.tif')
+
+ def test_surface_temps(self):
+ points_dict = raster_point_extract(lst_raster=self.lst_raster_path,
+ eef_raster=self.eef_lst_raster,
+ points=self.point_file)
+ for key, val in points_dict.items():
+ eef = val['eef_lst']
+ lst = val['lst_found']
+ ratio = eef / lst
+ print('Ratio at {} of EEFlux:LST calculated is {}.'.format(
+ key, ratio))
+ self.assertAlmostEqual(ratio, 1.0, delta=0.01)
+ os.remove(self.lst_raster_path)
+
+
+# ===================== ANCILLARY FUNCTIONS =================================
+
+def raster_point_extract(lst_raster, eef_raster, points):
+ point_data = {}
+ with fopen(points, 'r') as src:
+ for feature in src:
+ try:
+ name = feature['properties']['Name']
+ except KeyError:
+ name = feature['properties']['FID']
+ point_data[name] = {'coords': feature['geometry']['coordinates']}
+
+ with rasopen(lst_raster, 'r') as src:
+ lst_arr = src.read()
+ lst_arr = lst_arr.reshape(lst_arr.shape[1], lst_arr.shape[2])
+ lst_affine = src.transform
+
+ with rasopen(eef_raster, 'r') as src:
+ eef_lst = src.read()
+ eef_lst = eef_lst.reshape(eef_lst.shape[1], eef_lst.shape[2])
+ eef_affine = src.transform
+
+ for key, val in point_data.items():
+ x, y, z = val['coords']
+ col, row = ~lst_affine * (x, y)
+ val = lst_arr[int(row), int(col)]
+ point_data[key]['lst_found'] = val
+ point_data[key]['lst_row_col'] = int(row), int(col)
+
+ col, row = ~eef_affine * (x, y)
+ val = eef_lst[int(row), int(col)]
+ point_data[key]['eef_lst'] = val
+ point_data[key]['eef_row_col'] = int(row), int(col)
+
+ return point_data
+
+
+if __name__ == '__main__':
+ unittest.main()
+
+# ===============================================================================
diff --git a/pool/shard006/Python/0057672_rating.py b/pool/shard006/Python/0057672_rating.py
new file mode 100644
index 0000000000000000000000000000000000000000..7060c40b6582e830835c448dddba0740136567fc
--- /dev/null
+++ b/pool/shard006/Python/0057672_rating.py
@@ -0,0 +1,15 @@
+# coding: utf-8
+import json
+from django.http import HttpResponse
+from feedhoos.folder.models.folder import FolderModel
+
+
+def execute(request):
+ "folderのratingを変更する。"
+ folder_id = request.POST["id"]
+ rating = request.POST["rating"]
+ folder_model = FolderModel.objects.get(pk=folder_id)
+ folder_model.rating = int(rating)
+ folder_model.save()
+ response_json = json.dumps({"msg": "OK"}, ensure_ascii=False, skipkeys=True)
+ return HttpResponse(response_json, content_type='application/json')
diff --git a/pool/shard006/Python/0057673_get_build_status.py b/pool/shard006/Python/0057673_get_build_status.py
new file mode 100644
index 0000000000000000000000000000000000000000..a9fd8fbb25d47006e0675cad1e63b2c12391e753
--- /dev/null
+++ b/pool/shard006/Python/0057673_get_build_status.py
@@ -0,0 +1,33 @@
+#!/usr/bin/env python
+
+# Gets the build status of specific Bamboo builds from Jut's Bamboo instance
+
+import requests
+
+# The list of builds we're interested in
+builds = ["CAM-AMT", "CAM-CMT","CAM-SMOKE","CAM-IMT","CAM-QUAM","CAM-JUM","CAM-VIM","CAM-EAM","CAM-SMT"]
+#builds = ["CAM-PMT"]
+build_results = []
+
+# Get the status of each build and add it to the build_results list
+for build in builds:
+ r = requests.get('https://jut-io.atlassian.net/builds/rest/api/latest/result/' + build + '-latest.json', auth=('robot','mrroboto'))
+ build_results.append(r.json()['buildState'])
+ print r.json()['buildState']
+
+resultfile = open('/Users/davidcook/code/scratch/build-status-leds/build_status_display/data/build_results.txt', 'w+')
+
+failed_count = 0
+
+# Count the number of builds that failed
+for result in build_results:
+ if result == "Failed":
+ failed_count += 1
+
+# If any of the builds failed, write Failed to the file. If they all passed, write Successful
+if failed_count > 0:
+ resultfile.write("Failed\n")
+else:
+ resultfile.write("Successful\n")
+
+resultfile.close()
diff --git a/pool/shard006/Python/0057675_EurostagState.py b/pool/shard006/Python/0057675_EurostagState.py
new file mode 100644
index 0000000000000000000000000000000000000000..2671170250a8853572a7f05386540d63384f7776
--- /dev/null
+++ b/pool/shard006/Python/0057675_EurostagState.py
@@ -0,0 +1,118 @@
+# -*- coding: utf-8 -*-
+
+# Copyright (c) 2016, Pierre Saikaly (saikalypierre@gmail.com)
+
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this file,
+# You can obtain one at http://mozilla.org/MPL/2.0/.
+
+#===========================#
+# created on 07 sept 2016
+#===========================#
+
+# Import Python dependencies :
+# ----------------------------
+import os
+import sys
+import time
+import argparse
+
+# Script :
+# --------
+def CheckEurostagState(folder):
+ """
+ Reads eurostagOutputFile and check if the situation at the beginning is stable
+ or unstable
+ Inputs :
+ - eurostagOutputFile : file.out containing the informations
+ Outputs :
+ - 0 -> Situation is stable
+ - 1 -> Situation is unstable
+ Used in :
+ - main
+ """
+
+ etat = "ETAT D'EQUILIBRE A 0.10000D-02 VERIFIE POUR LES EQUATIONS MACHINE"
+ etat2 = "ETAT D'EQUILIBRE A 0.10000D-02 NON VERIFIE DANS LES EQUATIONS SUIVANTES"
+ eurostagOutputFile = os.path.join(folder,"sim_pre_fault.out")
+
+
+
+ # Checking Eurostag status :
+ # --------------------------
+ if etat in open(eurostagOutputFile, 'U').read():
+ # Eurostag returns stable
+ status = 0
+ else:
+ # Eurostag returns unstable :
+ # ---------------------------
+ equi_value = []
+ with open(eurostagOutputFile, 'U') as outfile:
+ lines = outfile.readlines()
+ for i, line in enumerate(lines):
+ if etat2 in line:
+ k = i+5
+ while (lines[k]!="1\n" and lines[k]!="\n"):
+ machine_name = lines[k].split()[0]
+ value_line = lines[k].split()[-2]
+ value_real = float(value_line.split("D")[0])*10**int(value_line.split("D")[1])
+ if (abs(value_real) > 0.01):
+ with open('ecart_groupe.csv','a') as egf:
+ egf.write(folder + ';' + machine_name + ';' + str(value_real) + '\n')
+ equi_value.append(abs(value_real))
+ k += 1
+ # Checking tolerance :
+ # --------------------
+ if (len(equi_value) > 0):
+ if (max(equi_value) < 0.01):
+ status = 0 # Stable state within tolerance
+ else:
+ status = 1 # Unstable state
+
+ else:
+ status = 0 # Stable state
+
+ return status
+
+def main():
+ """
+ Get list of eurostag simulation folders and check if thoses situations are
+ stable or not. The outputs are stored in eurostag_status.txt file
+ """
+
+ # Creating output file :
+ # ----------------------
+ print "Beginning writing outputs for folders in directory..."
+
+ with open('eurostag_status.txt','w') as f:
+ f.write("# " + time.strftime("%d/%m/%y") + "\n")
+
+ with open('ecart_groupe.csv','w') as egf:
+ egf.write(time.strftime("%d/%m/%y") + "\n")
+ egf.write("Situations;groupe;valeur\n")
+
+ # Checking folders and writing output :
+ # -------------------------------------
+ with open('eurostag_status.txt','a') as f:
+ for folder in os.listdir('.'):
+ if folder.startswith('itesla_eurostag_stabilization_'):
+ f.write(folder + " " + str(CheckEurostagState(folder)) + '\n')
+
+ print "Done writing outputs in eurostag_status.txt"
+ print "Done analysis in ecart_groupe.csv"
+
+if __name__=='__main__':
+
+ parser = argparse.ArgumentParser(description='Check eurostag status of working directory of specific folder')
+ parser.add_argument('-p','--eur_path', help='path of eurostag folder', required=False)
+ args = parser.parse_args()
+
+ if (args.eur_path):
+ with open('ecart_groupe.csv','w') as egf:
+ egf.write(time.strftime("%d/%m/%y") + "\n")
+ egf.write("Situations;groupe;valeur\n")
+
+ print args.eur_path, ' ', CheckEurostagState(args.eur_path)
+ print "Done analysis in ecart_groupe.csv"
+ else:
+ main()
\ No newline at end of file
diff --git a/pool/shard006/Python/0057680_pluginmanager.py b/pool/shard006/Python/0057680_pluginmanager.py
new file mode 100644
index 0000000000000000000000000000000000000000..f207d2c7c6de31f83e500f14fbc5962b03729866
--- /dev/null
+++ b/pool/shard006/Python/0057680_pluginmanager.py
@@ -0,0 +1,49 @@
+# -*- coding: utf-8 -*-
+
+'''
+@author: nick
+'''
+
+import imp
+import os
+import logging
+
+class PluginManager():
+
+ def __init__(self, directory):
+ self.pluginDirs = [directory]
+ self.plugins = {}
+ self.logger = logging.getLogger('picsort')
+
+ def addDirectory(self, directory):
+ self.pluginDirs.append(directory)
+
+
+ def getPlugin(self, name):
+ return self.plugins[name]
+
+
+ def listPlugins(self):
+ plugins = []
+
+ for directory in self.pluginDirs:
+ if os.path.exists(directory):
+ for f in os.listdir(directory):
+ if f.endswith(".py") and not f == "__init__.py":
+ plugins.append(os.path.join(directory, f))
+ else:
+ self.logger.warn("directory not exists: {}".format(directory))
+
+ return plugins
+
+
+ def loadPlugins(self):
+
+ for plugin in self.listPlugins():
+ try:
+ name, _ = os.path.splitext(os.path.split(plugin)[1])
+
+ submodule = imp.load_source(name, plugin)
+ self.plugins[name] = submodule
+ except Exception, e:
+ self.logger.error(e)
diff --git a/pool/shard006/Python/0057683_routing_metal.py b/pool/shard006/Python/0057683_routing_metal.py
new file mode 100644
index 0000000000000000000000000000000000000000..e095ed7359d23f7c2cbf129a360d11f7cd7e7d7a
--- /dev/null
+++ b/pool/shard006/Python/0057683_routing_metal.py
@@ -0,0 +1,31 @@
+"""
+FIXME: electrical connections should ignore port orientation
+"""
+
+import gdsfactory as gf
+
+
+if __name__ == "__main__":
+
+ c = gf.Component("mzi_with_pads")
+ c1 = c << gf.components.mzi_phase_shifter_top_heater_metal(length_x=70)
+ c2 = c << gf.components.pad_array90(columns=2)
+
+ c2.ymin = c1.ymax + 20
+ c2.x = 0
+ c1.x = 0
+
+ ports1 = c1.get_ports_list(width=11)
+ ports2 = c2.get_ports_list()
+
+ routes = gf.routing.get_bundle(
+ ports1=ports1,
+ ports2=ports2,
+ cross_section=gf.cross_section.metal1,
+ width=5,
+ bend=gf.components.wire_corner,
+ )
+ for route in routes:
+ c.add(route.references)
+
+ c.show()
diff --git a/pool/shard006/Python/0057685_rootramfs.py b/pool/shard006/Python/0057685_rootramfs.py
new file mode 100644
index 0000000000000000000000000000000000000000..0306587d9d60c1bb3b43dd62b9c20d6de301bd5a
--- /dev/null
+++ b/pool/shard006/Python/0057685_rootramfs.py
@@ -0,0 +1,175 @@
+#!/usr/bin/python
+
+
+__author__ = 'volodja'
+
+
+import os
+import re
+import sys
+
+
+def printList(name, list_):
+ print(name + ":")
+ for row in list_:
+ print(str(row).replace("\n", ""))
+
+
+def executeShellCommand(command):
+ print("exec: " + command)
+ result_pipe = os.popen(command)
+ result_ = result_pipe.readlines()
+ result = []
+ for line in result_:
+ result.append(line.replace('\n', ''))
+ return result
+
+
+def readFSTab():
+ file_fstab = open("/etc/fstab")
+ #file_fstab = open("/etc/fstab.1")
+ fstab_text = file_fstab.readlines()
+ fstab = []
+ file_fstab.close()
+
+ for line in fstab_text:
+ if line[0] != "#":
+ fstab_line = re.split(r"\s+", line.replace("\n", "").replace("UUID=", ""))
+ fstab.append(fstab_line)
+
+ #printList("fstab", fstab)
+ return fstab
+
+
+def mountSyncFSTab():
+ fstab = readFSTab()
+ mount = executeShellCommand("mount")
+
+ #print "fstab: " + str(fstab)
+ #print("mount: " + str(mount))
+
+ fstab_to_mount = []
+ for row_fstab in fstab:
+ if len(row_fstab) < 2:
+ continue
+ is_need_mount = True
+ if row_fstab[1] == "/":
+ mount_point = "/ram/sync"
+ else:
+ mount_point = "/ram/sync" + row_fstab[1]
+ for row_mount in mount:
+ if len(row_fstab) > 1 and (row_fstab[0][0:4] != "/ram" or (row_fstab[0][0:4] == "/ram" and row_mount.split(" ")[2] == mount_point)):
+ is_need_mount = False
+ break
+ if is_need_mount:
+ fstab_to_mount.append(row_fstab)
+
+ #print "fstab_to_mount = " + str(fstab_to_mount)
+ #exit(0)
+ for row_fstab in fstab_to_mount:
+ mount = executeShellCommand("mkdir -p /ram/sync" + row_fstab[1] + " && mount -t " + row_fstab[2] +
+ " /dev/disk/by-uuid/" + row_fstab[0][4:] + " /ram/sync" + row_fstab[1] + " || echo 'mount fail'")
+ if len(mount) > 0:
+ print("error: " + str(mount))
+ exit(1)
+
+
+def umountSyncFSTab():
+ #fstab = readFSTab()
+ mount = executeShellCommand("mount")
+ fstab_to_umount = []
+ is_was_root = False
+
+ for row_mount in mount:
+ mount_point = str(row_mount.split(" ")[2])
+ if mount_point[0:9] == "/ram/sync":
+ if len(mount_point) > 9:
+ fstab_to_umount.append(mount_point)
+ else:
+ is_was_root = True
+ if is_was_root:
+ fstab_to_umount.append("/ram/sync")
+
+ for row_umount in fstab_to_umount:
+ umount = executeShellCommand("umount " + row_umount)
+ if len(umount) > 0:
+ print("error: " + str(umount))
+ exit(1)
+
+
+def syncCommand(args, command_, is_reverse = False):
+ paths = []
+
+ for row_args in args:
+ if row_args != "--exclude":
+ paths.append(os.path.abspath(row_args))
+
+ if is_reverse:
+ src = "/ram/sync" + paths[0]
+ dst = paths[0]
+ else:
+ src = paths[0]
+ dst = "/ram/sync" + paths[0]
+
+
+ if os.path.isdir(paths[0]):
+ src = src + "/"
+
+ del paths[0]
+
+ #user_name = getpass.getuser()
+ command = command_ + " "
+ command = command + "--exclude '*/.gvfs' "
+ command = command + "--exclude '/run/user/*/gvfs' "
+ command = command + "--exclude '/media' "
+ command = command + "--exclude '/mnt' "
+ command = command + "--exclude '/dev' "
+ command = command + "--exclude '/sys' "
+ command = command + "--exclude '/proc' "
+ command = command + "--exclude '/selinux' "
+ command = command + "--exclude '/ram' "
+ command = command + "--exclude '/boot' "
+
+
+ for row_paths in paths:
+ command = command + "--exclude '" + row_paths + "' "
+
+ command = command + "\"" + src + "\" \"" + dst + "\" | grep -v 'xfer#' | grep -v 'xfr#' > /dev/tty && sync"
+ rsync = executeShellCommand(command)
+ #printList(command_, rsync)
+
+
+def syncPath(args):
+ syncCommand(args, "rsync --progress --delete -a")
+
+
+def diffPath(args):
+ syncCommand(args, "diff -r")
+
+
+def resetPath(args):
+ syncCommand(args, "rsync --progress --delete -a", True)
+
+
+if len(sys.argv) >= 3 and sys.argv[1] == "--sync":
+ mountSyncFSTab()
+ syncPath(sys.argv[2:])
+ umountSyncFSTab()
+ exit(0)
+
+if len(sys.argv) >= 3 and sys.argv[1] == "--reset":
+ mountSyncFSTab()
+ resetPath(sys.argv[2:])
+ umountSyncFSTab()
+ exit(0)
+
+if len(sys.argv) >= 3 and sys.argv[1] == "--diff":
+ mountSyncFSTab()
+ diffPath(sys.argv[2:])
+ umountSyncFSTab()
+ exit(0)
+
+
+print("usage: rootramfs --sync sync_path [exclude_path1] [exclude_path2] ...")
+print("usage: rootramfs --reset sync_path [exclude_path1] [exclude_path2] ...")
+print("usage: rootramfs --diff sync_path [exclude_path1] [exclude_path2] ...")
diff --git a/pool/shard006/Python/0057686_gotoread.py b/pool/shard006/Python/0057686_gotoread.py
new file mode 100644
index 0000000000000000000000000000000000000000..3a347b042d5ebbe469687916ddd2e6eeeea6efcb
--- /dev/null
+++ b/pool/shard006/Python/0057686_gotoread.py
@@ -0,0 +1,35 @@
+from scrapy.selector import Selector
+from scrapy.linkextractors import LinkExtractor
+from scrapy.spiders import CrawlSpider, Rule
+from crawlers.items import MagazineItem
+
+import urllib.parse
+
+class GotoreadSpider(CrawlSpider):
+ name = 'gotoread'
+ allowed_domains = ['gotoread.com']
+ start_urls = ['http://www.gotoread.com/scatalog3687.html',
+ 'http://www.gotoread.com/scatalog3078.html',
+ 'http://www.gotoread.com/scatalog3063.html',
+ 'http://www.gotoread.com/scatalog3010.html',
+ 'http://www.gotoread.com/scatalog3117.html',
+ 'http://www.gotoread.com/scatalog3533.html',
+ 'http://www.gotoread.com/scatalog3482.html',
+ 'http://www.gotoread.com/scatalog3477.html'
+ ]
+
+ rules = (
+ Rule(LinkExtractor(allow=r'/mag/\d+/$'), callback='parse_item', follow=False),
+ )
+
+ def parse_item(self, response):
+ sel = Selector(response)
+ i = MagazineItem()
+ i['name'] = sel.xpath("//div[@class='ProName']/h1/text()").extract()
+ i['description'] = sel.xpath("//div[@class='content box-line word']").extract()
+ i['price'] = sel.xpath("//em/del/text()").extract()[0]
+ i['category'] = sel.xpath("//div[@id='DaoHang']/a/text()").extract()[-1]
+ imgurl = sel.xpath("//img[@id='magcoverpic']/@src").extract()[0]
+ absurl = urlparse.urljoin("http://www.gotoread.com/", imgurl.strip())
+ i['image_urls'] = [absurl]
+ return i
diff --git a/pool/shard006/Python/0057692_mongodb_parameter.py b/pool/shard006/Python/0057692_mongodb_parameter.py
new file mode 100644
index 0000000000000000000000000000000000000000..2820982f0833d8afc079216b62f485e9001bedce
--- /dev/null
+++ b/pool/shard006/Python/0057692_mongodb_parameter.py
@@ -0,0 +1,216 @@
+#!/usr/bin/python
+# -*- coding: utf-8 -*-
+
+# (c) 2016, Loic Blot
+# Sponsored by Infopro Digital. http://www.infopro-digital.com/
+# Sponsored by E.T.A.I. http://www.etai.fr/
+#
+# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
+
+from __future__ import absolute_import, division, print_function
+__metaclass__ = type
+
+
+ANSIBLE_METADATA = {'metadata_version': '1.1',
+ 'status': ['preview'],
+ 'supported_by': 'community'}
+
+
+DOCUMENTATION = '''
+---
+module: mongodb_parameter
+short_description: Change an administrative parameter on a MongoDB server.
+description:
+ - Change an administrative parameter on a MongoDB server.
+version_added: "2.1"
+options:
+ login_user:
+ description:
+ - The username used to authenticate with
+ login_password:
+ description:
+ - The password used to authenticate with
+ login_host:
+ description:
+ - The host running the database
+ default: localhost
+ login_port:
+ description:
+ - The port to connect to
+ default: 27017
+ login_database:
+ description:
+ - The database where login credentials are stored
+ replica_set:
+ description:
+ - Replica set to connect to (automatically connects to primary for writes)
+ database:
+ description:
+ - The name of the database to add/remove the user from
+ required: true
+ ssl:
+ description:
+ - Whether to use an SSL connection when connecting to the database
+ type: bool
+ default: 'no'
+ param:
+ description:
+ - MongoDB administrative parameter to modify
+ required: true
+ value:
+ description:
+ - MongoDB administrative parameter value to set
+ required: true
+ param_type:
+ description:
+ - Define the parameter value (str, int)
+ default: str
+
+notes:
+ - Requires the pymongo Python package on the remote host, version 2.4.2+. This
+ can be installed using pip or the OS package manager. @see http://api.mongodb.org/python/current/installation.html
+requirements: [ "pymongo" ]
+author: "Loic Blot (@nerzhul)"
+'''
+
+EXAMPLES = '''
+# Set MongoDB syncdelay to 60 (this is an int)
+- mongodb_parameter:
+ param: syncdelay
+ value: 60
+ param_type: int
+'''
+
+RETURN = '''
+before:
+ description: value before modification
+ returned: success
+ type: string
+after:
+ description: value after modification
+ returned: success
+ type: string
+'''
+
+import os
+import traceback
+
+try:
+ from pymongo.errors import ConnectionFailure
+ from pymongo.errors import OperationFailure
+ from pymongo import version as PyMongoVersion
+ from pymongo import MongoClient
+except ImportError:
+ try: # for older PyMongo 2.2
+ from pymongo import Connection as MongoClient
+ except ImportError:
+ pymongo_found = False
+ else:
+ pymongo_found = True
+else:
+ pymongo_found = True
+
+from ansible.module_utils.basic import AnsibleModule
+from ansible.module_utils.six.moves import configparser
+from ansible.module_utils._text import to_native
+
+
+# =========================================
+# MongoDB module specific support methods.
+#
+
+def load_mongocnf():
+ config = configparser.RawConfigParser()
+ mongocnf = os.path.expanduser('~/.mongodb.cnf')
+
+ try:
+ config.readfp(open(mongocnf))
+ creds = dict(
+ user=config.get('client', 'user'),
+ password=config.get('client', 'pass')
+ )
+ except (configparser.NoOptionError, IOError):
+ return False
+
+ return creds
+
+
+# =========================================
+# Module execution.
+#
+
+def main():
+ module = AnsibleModule(
+ argument_spec=dict(
+ login_user=dict(default=None),
+ login_password=dict(default=None, no_log=True),
+ login_host=dict(default='localhost'),
+ login_port=dict(default=27017, type='int'),
+ login_database=dict(default=None),
+ replica_set=dict(default=None),
+ param=dict(default=None, required=True),
+ value=dict(default=None, required=True),
+ param_type=dict(default="str", choices=['str', 'int']),
+ ssl=dict(default=False, type='bool'),
+ )
+ )
+
+ if not pymongo_found:
+ module.fail_json(msg='the python pymongo module is required')
+
+ login_user = module.params['login_user']
+ login_password = module.params['login_password']
+ login_host = module.params['login_host']
+ login_port = module.params['login_port']
+ login_database = module.params['login_database']
+
+ replica_set = module.params['replica_set']
+ ssl = module.params['ssl']
+
+ param = module.params['param']
+ param_type = module.params['param_type']
+ value = module.params['value']
+
+ # Verify parameter is coherent with specified type
+ try:
+ if param_type == 'int':
+ value = int(value)
+ except ValueError:
+ module.fail_json(msg="value '%s' is not %s" % (value, param_type))
+
+ try:
+ if replica_set:
+ client = MongoClient(login_host, int(login_port), replicaset=replica_set, ssl=ssl)
+ else:
+ client = MongoClient(login_host, int(login_port), ssl=ssl)
+
+ if login_user is None and login_password is None:
+ mongocnf_creds = load_mongocnf()
+ if mongocnf_creds is not False:
+ login_user = mongocnf_creds['user']
+ login_password = mongocnf_creds['password']
+ elif login_password is None or login_user is None:
+ module.fail_json(msg='when supplying login arguments, both login_user and login_password must be provided')
+
+ if login_user is not None and login_password is not None:
+ client.admin.authenticate(login_user, login_password, source=login_database)
+
+ except ConnectionFailure as e:
+ module.fail_json(msg='unable to connect to database: %s' % to_native(e), exception=traceback.format_exc())
+
+ db = client.admin
+
+ try:
+ after_value = db.command("setParameter", **{param: value})
+ except OperationFailure as e:
+ module.fail_json(msg="unable to change parameter: %s" % to_native(e), exception=traceback.format_exc())
+
+ if "was" not in after_value:
+ module.exit_json(changed=True, msg="Unable to determine old value, assume it changed.")
+ else:
+ module.exit_json(changed=(value != after_value["was"]), before=after_value["was"],
+ after=value)
+
+
+if __name__ == '__main__':
+ main()
diff --git a/pool/shard006/Python/0057693_test_bigip_profile_udp.py b/pool/shard006/Python/0057693_test_bigip_profile_udp.py
new file mode 100644
index 0000000000000000000000000000000000000000..0cdb30f3dc53f5a56045eb8cc759f31f9ad60905
--- /dev/null
+++ b/pool/shard006/Python/0057693_test_bigip_profile_udp.py
@@ -0,0 +1,119 @@
+# -*- coding: utf-8 -*-
+#
+# Copyright: (c) 2017, F5 Networks Inc.
+# GNU General Public License v3.0 (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
+
+from __future__ import (absolute_import, division, print_function)
+__metaclass__ = type
+
+import os
+import json
+import pytest
+import sys
+
+if sys.version_info < (2, 7):
+ pytestmark = pytest.mark.skip("F5 Ansible modules require Python >= 2.7")
+
+from ansible.module_utils.basic import AnsibleModule
+
+try:
+ from library.modules.bigip_profile_udp import ApiParameters
+ from library.modules.bigip_profile_udp import ModuleParameters
+ from library.modules.bigip_profile_udp import ModuleManager
+ from library.modules.bigip_profile_udp import ArgumentSpec
+
+ # In Ansible 2.8, Ansible changed import paths.
+ from test.units.compat import unittest
+ from test.units.compat.mock import Mock
+
+ from test.units.modules.utils import set_module_args
+except ImportError:
+ from ansible.modules.network.f5.bigip_profile_udp import ApiParameters
+ from ansible.modules.network.f5.bigip_profile_udp import ModuleParameters
+ from ansible.modules.network.f5.bigip_profile_udp import ModuleManager
+ from ansible.modules.network.f5.bigip_profile_udp import ArgumentSpec
+
+ # Ansible 2.8 imports
+ from units.compat import unittest
+ from units.compat.mock import Mock
+
+ from units.modules.utils import set_module_args
+
+
+fixture_path = os.path.join(os.path.dirname(__file__), 'fixtures')
+fixture_data = {}
+
+
+def load_fixture(name):
+ path = os.path.join(fixture_path, name)
+
+ if path in fixture_data:
+ return fixture_data[path]
+
+ with open(path) as f:
+ data = f.read()
+
+ try:
+ data = json.loads(data)
+ except Exception:
+ pass
+
+ fixture_data[path] = data
+ return data
+
+
+class TestParameters(unittest.TestCase):
+ def test_module_parameters(self):
+ args = dict(
+ name='foo',
+ parent='bar',
+ idle_timeout='500',
+ datagram_load_balancing=False
+ )
+
+ p = ModuleParameters(params=args)
+ assert p.name == 'foo'
+ assert p.parent == '/Common/bar'
+ assert p.idle_timeout == 500
+ assert p.datagram_load_balancing is False
+
+ def test_api_parameters(self):
+ args = load_fixture('load_ltm_profile_udp_1.json')
+ p = ApiParameters(params=args)
+ assert p.name == 'foo'
+ assert p.idle_timeout == 60
+
+
+class TestManager(unittest.TestCase):
+
+ def setUp(self):
+ self.spec = ArgumentSpec()
+
+ def test_create(self, *args):
+ # Configure the arguments that would be sent to the Ansible module
+ set_module_args(dict(
+ name='foo',
+ parent='bar',
+ idle_timeout=500,
+ datagram_load_balancing=True,
+ provider=dict(
+ server='localhost',
+ password='password',
+ user='admin'
+ )
+ ))
+
+ module = AnsibleModule(
+ argument_spec=self.spec.argument_spec,
+ supports_check_mode=self.spec.supports_check_mode
+ )
+ mm = ModuleManager(module=module)
+
+ # Override methods to force specific logic in the module to happen
+ mm.exists = Mock(return_value=False)
+ mm.create_on_device = Mock(return_value=True)
+
+ results = mm.exec_module()
+
+ assert results['changed'] is True
+ assert results['idle_timeout'] == 500
diff --git a/pool/shard006/Python/0057699_user.py b/pool/shard006/Python/0057699_user.py
new file mode 100644
index 0000000000000000000000000000000000000000..aeb82c2c1cb67a95a4b5d9a9d2d6315ef2d7ccfa
--- /dev/null
+++ b/pool/shard006/Python/0057699_user.py
@@ -0,0 +1,127 @@
+"""
+sentry.models.user
+~~~~~~~~~~~~~~~~~~
+
+:copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details.
+:license: BSD, see LICENSE for more details.
+"""
+from __future__ import absolute_import
+
+import warnings
+
+from django.contrib.auth.models import AbstractBaseUser, UserManager
+from django.db import IntegrityError, models, transaction
+from django.utils import timezone
+from django.utils.translation import ugettext_lazy as _
+
+from sentry.db.models import BaseManager, BaseModel, BoundedAutoField
+
+
+class UserManager(BaseManager, UserManager):
+ pass
+
+
+class User(BaseModel, AbstractBaseUser):
+ id = BoundedAutoField(primary_key=True)
+ username = models.CharField(_('username'), max_length=128, unique=True)
+ # this column is called first_name for legacy reasons, but it is the entire
+ # display name
+ name = models.CharField(_('name'), max_length=200, blank=True,
+ db_column='first_name')
+ email = models.EmailField(_('email address'), blank=True)
+ is_staff = models.BooleanField(
+ _('staff status'), default=False,
+ help_text=_('Designates whether the user can log into this admin '
+ 'site.'))
+ is_active = models.BooleanField(
+ _('active'), default=True,
+ help_text=_('Designates whether this user should be treated as '
+ 'active. Unselect this instead of deleting accounts.'))
+ is_superuser = models.BooleanField(
+ _('superuser status'), default=False,
+ help_text=_('Designates that this user has all permissions without '
+ 'explicitly assigning them.'))
+ is_managed = models.BooleanField(
+ _('managed'), default=False,
+ help_text=_('Designates whether this user should be treated as '
+ 'managed. Select this to disallow the user from '
+ 'modifying their account (username, password, etc).'))
+
+ date_joined = models.DateTimeField(_('date joined'), default=timezone.now)
+
+ objects = UserManager(cache_fields=['pk'])
+
+ USERNAME_FIELD = 'username'
+ REQUIRED_FIELDS = ['email']
+
+ class Meta:
+ app_label = 'sentry'
+ db_table = 'auth_user'
+ verbose_name = _('user')
+ verbose_name_plural = _('users')
+
+ def delete(self):
+ if self.username == 'sentry':
+ raise Exception('You cannot delete the "sentry" user as it is required by Sentry.')
+ return super(User, self).delete()
+
+ def save(self, *args, **kwargs):
+ if not self.username:
+ self.username = self.email
+ return super(User, self).save(*args, **kwargs)
+
+ def has_perm(self, perm_name):
+ warnings.warn('User.has_perm is deprecated', DeprecationWarning)
+ return self.is_superuser
+
+ def has_module_perms(self, app_label):
+ warnings.warn('User.has_module_perms is deprecated', DeprecationWarning)
+ return self.is_superuser
+
+ def get_display_name(self):
+ return self.name or self.email or self.username
+
+ def get_full_name(self):
+ return self.name
+
+ def get_short_name(self):
+ return self.username
+
+ def merge_to(from_user, to_user):
+ # TODO: we could discover relations automatically and make this useful
+ from sentry.models import (
+ AuditLogEntry, Activity, AuthIdentity, GroupBookmark,
+ OrganizationMember, UserOption
+ )
+
+ for obj in OrganizationMember.objects.filter(user=from_user):
+ try:
+ with transaction.atomic():
+ obj.update(user=to_user)
+ except IntegrityError:
+ pass
+ for obj in GroupBookmark.objects.filter(user=from_user):
+ try:
+ with transaction.atomic():
+ obj.update(user=to_user)
+ except IntegrityError:
+ pass
+ for obj in UserOption.objects.filter(user=from_user):
+ try:
+ with transaction.atomic():
+ obj.update(user=to_user)
+ except IntegrityError:
+ pass
+
+ Activity.objects.filter(
+ user=from_user,
+ ).update(user=to_user)
+ AuditLogEntry.objects.filter(
+ actor=from_user,
+ ).update(actor=to_user)
+ AuditLogEntry.objects.filter(
+ target_user=from_user,
+ ).update(target_user=to_user)
+ AuthIdentity.objects.filter(
+ user=from_user,
+ ).update(user=to_user)
diff --git a/pool/shard006/Python/0057703_example_1.py b/pool/shard006/Python/0057703_example_1.py
new file mode 100644
index 0000000000000000000000000000000000000000..d035506a4533c544ac56b80f418dd1f9654833fe
--- /dev/null
+++ b/pool/shard006/Python/0057703_example_1.py
@@ -0,0 +1,100 @@
+#!/usr/bin/env python2
+
+import subprocess
+import atexit
+import sys
+from math import pi
+from chips.api.api import Chip, Stimulus, Response, Wire, Component
+
+#try:
+from matplotlib import pyplot
+#except ImportError:
+ #print "You need matplotlib to run this script!"
+ #exit(0)
+
+def test():
+
+ chip = Chip("square_root")
+
+ test_in = Stimulus(chip, "input", "float", [i*0.1 for i in range(100)])
+ test_out = Response(chip, "output", "float")
+
+ #create a filter component using the C code
+ sqrt = Component("sqrt.c")
+
+ #add an instance to the chip
+ sqrt(
+ chip,
+ inputs = {
+ "x":test_in,
+ },
+ outputs = {
+ "sqrt_x":test_out,
+ },
+ )
+
+ #run the simulation
+ chip.simulation_reset()
+ while len(test_out) < 100:
+ chip.simulation_step()
+
+ pyplot.plot(list(test_in), list(test_out))
+ pyplot.xlim(0, 10.1)
+ pyplot.title("Square Root of x")
+ pyplot.xlabel("x")
+ pyplot.ylabel("$\\sqrt{x}$")
+ pyplot.savefig("../docs/source/examples/images/example_1.png")
+ pyplot.show()
+
+def indent(lines):
+ return "\n ".join(lines.splitlines())
+
+def generate_docs():
+
+ documentation = """
+
+Calculate Square Root using Newton's Method
+===========================================
+
+In this example, we calculate the sqrt of a number using `Newton's method
+`_.
+The problem of finding the square root can be expressed as:
+
+.. math::
+
+ n = x^2
+
+Which can be rearranged as:
+
+.. math::
+
+ f(x) = x^2 - n
+
+Using Newton's method, we can find numerically the approximate point at which
+:math:`f(x) = 0`. Repeated applications of the following expression yield
+increasingly accurate approximations of the Square root:
+
+.. math::
+
+ f(x_k) = x_{k-1} - \\frac{{x_{k-1}}^2 - n}{2x_{k-1}}
+
+Turning this into a practical solution, the following code calculates the square
+root of a floating point number. An initial approximation is refined using
+Newton's method until further refinements agree to within a small degree.
+
+.. code-block:: c
+
+ %s
+
+Note that the code isn't entirely robust, and cannot handle special cases such
+as Nans, infinities or negative numbers. A simple test calculates
+:math:`\\sqrt{x}` where :math:`-10 < x < 10`.
+
+.. image:: images/example_1.png
+
+"""%indent(open("sqrt.c").read())
+
+ document = open("../docs/source/examples/example_1.rst", "w").write(documentation)
+
+test()
+generate_docs()
diff --git a/pool/shard006/Python/0057706_basehandlers.py b/pool/shard006/Python/0057706_basehandlers.py
new file mode 100644
index 0000000000000000000000000000000000000000..9be8f2bb8f711f8e4ed34c1d5e2e3dcda0e597c6
--- /dev/null
+++ b/pool/shard006/Python/0057706_basehandlers.py
@@ -0,0 +1,68 @@
+from __future__ import absolute_import
+from google.appengine.ext import ndb
+from google.appengine.api import users
+
+import webapp2
+from webapp2_extras import jinja2
+
+
+class BaseHandler(webapp2.RequestHandler):
+ """
+ All other handlers will extend this handler
+ """
+
+ def __init__(self, request, response):
+ self.initialize(request, response)
+ self.is_admin = users.is_current_user_admin()
+ self.login_url = users.create_login_url(self.request.uri)
+ self.logout_url = users.create_logout_url(webapp2.uri_for('home'))
+
+ self.jinja2_context = {
+ 'request': self.request,
+ 'user': self.current_user,
+ 'is_admin': self.is_admin,
+ 'login_url': self.login_url,
+ 'logout_url': self.logout_url
+ }
+
+ @webapp2.cached_property
+ def jinja2(self):
+ return jinja2.get_jinja2(app=self.app)
+
+ @webapp2.cached_property
+ def current_user(self):
+ user = users.get_current_user()
+ if user:
+ user.key = ndb.Key('User', user.user_id())
+ return user
+
+ def render_response(self, _template, **context):
+ ctx = self.jinja2_context.copy()
+ ctx.update(context)
+ rv = self.jinja2.render_template(_template, **ctx)
+ self.response.write(rv)
+
+ def render_response_string(self, template_string, **context):
+ ctx = self.jinja2_context.copy()
+ ctx.update(context)
+ self.response.write(self.jinja2.environment.from_string(
+ template_string).render(**ctx))
+
+
+class UserHandler(BaseHandler):
+ def dispatch(self):
+ if not self.current_user:
+ return self.redirect(self.login_url)
+
+ return super(UserHandler, self).dispatch()
+
+
+class AdminHandler(BaseHandler):
+ def dispatch(self):
+ if not self.current_user:
+ return self.redirect(self.login_url)
+
+ if not self.is_admin:
+ self.abort(403, detail="You need admin privileges to access this URL.")
+
+ super(AdminHandler, self).dispatch()
diff --git a/pool/shard006/Python/0057707_RiCIMU.py b/pool/shard006/Python/0057707_RiCIMU.py
new file mode 100644
index 0000000000000000000000000000000000000000..c0d70695116afbab4b9ac556d8038b6597f0bfe6
--- /dev/null
+++ b/pool/shard006/Python/0057707_RiCIMU.py
@@ -0,0 +1,148 @@
+import re
+from threading import Thread
+import rospy
+import rostopic
+from BAL.Handlers.keepAliveHandler import KeepAliveHandler
+from BAL.Header.Requests.PublishRequest import PublishRequest
+from BAL.Header.Requests.imuRequest import IMURequest
+from BAL.Header.Response.ParamBuildResponse import IMU
+
+__author__ = 'tom1231'
+from rospy import Publisher, Service
+from sensor_msgs.msg import Imu, MagneticField
+from BAL.Interfaces.Device import Device
+from tf.transformations import euler_from_quaternion, quaternion_from_euler
+from geometry_msgs.msg import Quaternion
+from math import pi
+from ric_board.srv._calibIMU import calibIMU, calibIMURequest
+from ric_board.msg._imuCalib import imuCalib
+
+CALIB_ID = 1
+PUB_ID = 2
+
+class RiCIMU(Device):
+ def __init__(self, param, output):
+ Device.__init__(self, param.getIMUName(), output)
+ self._frameId = param.getIMUFrameId()
+ self._angle = param.getIMUOrientation()
+ self._pub = Publisher('%s_AGQ' % self._name, Imu, queue_size=param.getIMUPubHz())
+ self._pubMag = Publisher('%s_M' % self._name, MagneticField, queue_size=param.getIMUPubHz())
+ self._pubCalib = Publisher('/imu_calib_publisher', imuCalib, queue_size=param.getIMUPubHz())
+ Service('/imu_Calibration', calibIMU, self.serviceCallBack)
+ self._haveRightToPublish = False
+ self._calib = False
+ self._xMax = 0.0
+ self._yMax = 0.0
+ self._zMax = 0.0
+ self._xMin = 0.0
+ self._yMin = 0.0
+ self._zMin = 0.0
+ #KeepAliveHandler('%s_AGQ' % self._name, Imu)
+
+ def getType(self):
+ return IMU
+
+ def serviceCallBack(self, request):
+ validStatus = True
+
+ if request.status == calibIMURequest.START_CALIB:
+ rospy.loginfo("Calibration begin")
+ self._output.write(IMURequest(calibIMURequest.START_CALIB).dataTosend())
+ self._calib = True
+
+ self._xMax = request.xMax
+ self._yMax = request.yMax
+ self._zMax = request.zMax
+ self._xMin = request.xMin
+ self._yMin = request.yMin
+ self._zMin = request.zMin
+
+ elif request.status == calibIMURequest.STOP_CALIB:
+ rospy.loginfo("Calibration end")
+ self._output.write(IMURequest(calibIMURequest.STOP_CALIB).dataTosend())
+ rospy.loginfo("Calibration setting saved")
+ self._calib = False
+
+ else:
+ validStatus = False
+ return {'ack': validStatus}
+
+ def publish(self, data):
+ if not self._calib and data.getImuMsgId() == PUB_ID:
+ q = data.getOrientation()
+ roll, pitch, yaw = euler_from_quaternion((q.y, q.z, q.w, q.x))
+ #array = quaternion_from_euler(yaw + (self._angle * pi / 180), roll, pitch)
+ #array = quaternion_from_euler(yaw + (self._angle * pi / 180), -1 (roll - 180), -1 * pitch)
+ array = quaternion_from_euler((yaw + (self._angle * pi / 180)), roll, -1 * pitch)
+ res = Quaternion()
+ res.w = array[0]
+ res.x = array[1]
+ res.y = array[2]
+ res.z = array[3]
+
+ msg = Imu()
+ msg.header.frame_id = self._frameId
+ msg.header.stamp = rospy.get_rostime()
+ msg.orientation = res
+ msg.linear_acceleration = data.getAcceleration()
+ msg.angular_velocity = data.getVelocity()
+
+ magMsg = MagneticField()
+ magMsg.header.frame_id = self._frameId
+ magMsg.header.stamp = rospy.get_rostime()
+ magMsg.magnetic_field = data.getMagnetometer()
+
+ self._pub.publish(msg)
+ self._pubMag.publish(magMsg)
+
+ elif data.getImuMsgId() == CALIB_ID:
+ x, y, z = data.getValues()
+ msg = imuCalib()
+
+ if x > self._xMax:
+ self._xMax = x
+ if x < self._xMin:
+ self._xMin = x
+
+ if y > self._yMax:
+ self._yMax = y
+ if y < self._yMin:
+ self._yMin = y
+
+ if z > self._zMax:
+ self._zMax = z
+ if z < self._zMin:
+ self._zMin = z
+
+
+ msg.x.data = x
+ msg.x.max = self._xMax
+ msg.x.min = self._xMin
+
+ msg.y.data = y
+ msg.y.max = self._yMax
+ msg.y.min = self._yMin
+
+ msg.z.data = z
+ msg.z.max = self._zMax
+ msg.z.min = self._zMin
+
+ self._pubCalib.publish(msg)
+
+ def checkForSubscribers(self):
+ try:
+ subCheck = re.search('Subscribers:.*', rostopic.get_info_text(self._pub.name)).group(0).split(': ')[1]
+ subMagCheck = re.search('Subscribers:.*', rostopic.get_info_text(self._pubMag.name)).group(0).split(': ')[1]
+ subCalibCheck = \
+ re.search('Subscribers:.*', rostopic.get_info_text(self._pubCalib.name)).group(0).split(': ')[1]
+
+ if not self._haveRightToPublish and (subCheck == '' or subMagCheck == '' or subCalibCheck == ''):
+ self._output.write(PublishRequest(IMU, 0, True).dataTosend())
+ self._haveRightToPublish = True
+
+ elif self._haveRightToPublish and (
+ subCheck == 'None' and subMagCheck == 'None' and subCalibCheck == 'None'):
+ self._output.write(PublishRequest(IMU, 0, False).dataTosend())
+ self._haveRightToPublish = False
+ except:
+ pass
diff --git a/pool/shard006/Python/0057709_test_fetch.py b/pool/shard006/Python/0057709_test_fetch.py
new file mode 100644
index 0000000000000000000000000000000000000000..4933ce54b852eff8355a19b93bda6378a4df1cd9
--- /dev/null
+++ b/pool/shard006/Python/0057709_test_fetch.py
@@ -0,0 +1,216 @@
+#!/usr/bin/env python
+# Copyright (c) 2012 Cloudera, Inc. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required 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.
+#
+
+import pytest
+import re
+from tests.hs2.hs2_test_suite import HS2TestSuite, needs_session
+from TCLIService import TCLIService
+
+# Simple test to make sure all the HS2 types are supported for both the row and
+# column-oriented versions of the HS2 protocol.
+class TestFetch(HS2TestSuite):
+ def __verify_result_precision_scale(self, t, precision, scale):
+ # This should be DECIMAL_TYPE but how do I get that in python
+ assert t.typeDesc.types[0].primitiveEntry.type == 15
+ p = t.typeDesc.types[0].primitiveEntry.typeQualifiers.qualifiers['precision']
+ s = t.typeDesc.types[0].primitiveEntry.typeQualifiers.qualifiers['scale']
+ assert p.i32Value == precision
+ assert s.i32Value == scale
+
+ @needs_session(TCLIService.TProtocolVersion.HIVE_CLI_SERVICE_PROTOCOL_V1)
+ def test_alltypes_v1(self):
+ execute_statement_req = TCLIService.TExecuteStatementReq()
+ execute_statement_req.sessionHandle = self.session_handle
+
+ execute_statement_req.statement =\
+ "SELECT * FROM functional.alltypessmall ORDER BY id LIMIT 1"
+ execute_statement_resp = self.hs2_client.ExecuteStatement(execute_statement_req)
+ HS2TestSuite.check_response(execute_statement_resp)
+ results = self.fetch(execute_statement_resp.operationHandle,
+ TCLIService.TFetchOrientation.FETCH_NEXT, 1, 1)
+ assert len(results.results.rows) == 1
+ self.close(execute_statement_resp.operationHandle)
+
+ execute_statement_req.statement =\
+ "SELECT d1,d5 FROM functional.decimal_tbl ORDER BY d1 LIMIT 1"
+ execute_statement_resp = self.hs2_client.ExecuteStatement(execute_statement_req)
+ HS2TestSuite.check_response(execute_statement_resp)
+ results = self.fetch(execute_statement_resp.operationHandle,
+ TCLIService.TFetchOrientation.FETCH_NEXT, 1, 1)
+ assert len(results.results.rows) == 1
+
+ # Verify the result schema is what we expect. The result has 2 columns, the
+ # first is decimal(9,0) and the second is decimal(10,5)
+ metadata_resp = self.result_metadata(execute_statement_resp.operationHandle)
+ column_types = metadata_resp.schema.columns
+ assert len(column_types) == 2
+ self.__verify_result_precision_scale(column_types[0], 9, 0)
+ self.__verify_result_precision_scale(column_types[1], 10, 5)
+
+ self.close(execute_statement_resp.operationHandle)
+
+ def __query_and_fetch(self, query):
+ execute_statement_req = TCLIService.TExecuteStatementReq()
+ execute_statement_req.sessionHandle = self.session_handle
+ execute_statement_req.statement = query
+ execute_statement_resp = self.hs2_client.ExecuteStatement(execute_statement_req)
+ HS2TestSuite.check_response(execute_statement_resp)
+
+ fetch_results_req = TCLIService.TFetchResultsReq()
+ fetch_results_req.operationHandle = execute_statement_resp.operationHandle
+ fetch_results_req.maxRows = 1024
+ fetch_results_resp = self.hs2_client.FetchResults(fetch_results_req)
+ HS2TestSuite.check_response(fetch_results_resp)
+
+ return fetch_results_resp
+
+ def __column_results_to_string(self, columns):
+ """Quick-and-dirty way to get a readable string to compare the output of a
+ columnar-oriented query to its expected output"""
+ formatted = ""
+ num_rows = 0
+ # Determine the number of rows by finding the type of the first column
+ for col_type in HS2TestSuite.HS2_V6_COLUMN_TYPES:
+ typed_col = getattr(columns[0], col_type)
+ if typed_col != None:
+ num_rows = len(typed_col.values)
+ break
+
+ for i in xrange(num_rows):
+ row = []
+ for c in columns:
+ for col_type in HS2TestSuite.HS2_V6_COLUMN_TYPES:
+ typed_col = getattr(c, col_type)
+ if typed_col != None:
+ indicator = ord(typed_col.nulls[i / 8])
+ if indicator & (1 << (i % 8)):
+ row.append("NULL")
+ else:
+ row.append(str(typed_col.values[i]))
+ break
+ formatted += (", ".join(row) + "\n")
+ return (num_rows, formatted)
+
+ @needs_session()
+ def test_alltypes_v6(self):
+ """Test that a simple select statement works for all types"""
+ fetch_results_resp = self.__query_and_fetch(
+ "SELECT *, NULL from functional.alltypes ORDER BY id LIMIT 1")
+
+ num_rows, result = self.__column_results_to_string(fetch_results_resp.results.columns)
+ assert num_rows == 1
+ assert result == \
+ "0, True, 0, 0, 0, 0, 0.0, 0.0, 01/01/09, 0, 2009-01-01 00:00:00, 2009, 1, NULL\n"
+
+ # Decimals
+ fetch_results_resp = self.__query_and_fetch(
+ "SELECT * from functional.decimal_tbl LIMIT 1")
+ num_rows, result = self.__column_results_to_string(fetch_results_resp.results.columns)
+ assert result == ("1234, 2222, 1.2345678900, "
+ "0.12345678900000000000000000000000000000, 12345.78900, 1\n")
+
+ # VARCHAR
+ fetch_results_resp = self.__query_and_fetch("SELECT CAST('str' AS VARCHAR(3))")
+ num_rows, result = self.__column_results_to_string(fetch_results_resp.results.columns)
+ assert result == "str\n"
+
+ # CHAR not inlined
+ fetch_results_resp = self.__query_and_fetch("SELECT CAST('car' AS CHAR(140))")
+ num_rows, result = self.__column_results_to_string(fetch_results_resp.results.columns)
+ assert result == "car" + (" " * 137) + "\n"
+
+ # CHAR inlined
+ fetch_results_resp = self.__query_and_fetch("SELECT CAST('car' AS CHAR(5))")
+ num_rows, result = self.__column_results_to_string(fetch_results_resp.results.columns)
+ assert result == "car \n"
+
+ @needs_session()
+ def test_show_partitions(self):
+ """Regression test for IMPALA-1330"""
+ for query in ["SHOW PARTITIONS functional.alltypes",
+ "SHOW TABLE STATS functional.alltypes"]:
+ fetch_results_resp = self.__query_and_fetch(query)
+ num_rows, result = \
+ self.__column_results_to_string(fetch_results_resp.results.columns)
+ assert num_rows == 25
+ # Match whether stats are computed or not
+ assert re.match(
+ r"2009, 1, -?\d+, -?\d+, \d*\.?\d+KB, NOT CACHED, TEXT", result) is not None
+
+ @needs_session()
+ def test_show_column_stats(self):
+ fetch_results_resp = self.__query_and_fetch("SHOW COLUMN STATS functional.alltypes")
+ num_rows, result = self.__column_results_to_string(fetch_results_resp.results.columns)
+ assert num_rows == 13
+ assert re.match(r"id, INT, -?\d+, -?\d+, (NULL|\d+), 4.0", result) is not None
+
+ @needs_session(TCLIService.TProtocolVersion.HIVE_CLI_SERVICE_PROTOCOL_V1)
+ def test_execute_select_v1(self):
+ """Test that a simple select statement works in the row-oriented protocol"""
+ execute_statement_req = TCLIService.TExecuteStatementReq()
+ execute_statement_req.sessionHandle = self.session_handle
+ execute_statement_req.statement = "SELECT COUNT(*) FROM functional.alltypes"
+ execute_statement_resp = self.hs2_client.ExecuteStatement(execute_statement_req)
+ HS2TestSuite.check_response(execute_statement_resp)
+
+ fetch_results_req = TCLIService.TFetchResultsReq()
+ fetch_results_req.operationHandle = execute_statement_resp.operationHandle
+ fetch_results_req.maxRows = 100
+ fetch_results_resp = self.hs2_client.FetchResults(fetch_results_req)
+ HS2TestSuite.check_response(fetch_results_resp)
+
+ assert len(fetch_results_resp.results.rows) == 1
+ assert fetch_results_resp.results.startRowOffset == 0
+
+ try:
+ assert not fetch_results_resp.hasMoreRows
+ except AssertionError:
+ pytest.xfail("IMPALA-558")
+
+ @needs_session()
+ def test_select_null(self):
+ """Regression test for IMPALA-1370, where NULL literals would appear as strings where
+ they should be booleans"""
+ execute_statement_req = TCLIService.TExecuteStatementReq()
+ execute_statement_req.sessionHandle = self.session_handle
+ execute_statement_req.statement = "select null"
+ execute_statement_resp = self.hs2_client.ExecuteStatement(execute_statement_req)
+ HS2TestSuite.check_response(execute_statement_resp)
+
+ # Check that the expected type is boolean (for compatibility with Hive, see also
+ # IMPALA-914)
+ get_result_metadata_req = TCLIService.TGetResultSetMetadataReq()
+ get_result_metadata_req.operationHandle = execute_statement_resp.operationHandle
+ get_result_metadata_resp = \
+ self.hs2_client.GetResultSetMetadata(get_result_metadata_req)
+ col = get_result_metadata_resp.schema.columns[0]
+ assert col.typeDesc.types[0].primitiveEntry.type == TCLIService.TTypeId.BOOLEAN_TYPE
+
+ # Check that the actual type is boolean
+ fetch_results_req = TCLIService.TFetchResultsReq()
+ fetch_results_req.operationHandle = execute_statement_resp.operationHandle
+ fetch_results_req.maxRows = 1
+ fetch_results_resp = self.hs2_client.FetchResults(fetch_results_req)
+ HS2TestSuite.check_response(fetch_results_resp)
+ assert fetch_results_resp.results.columns[0].boolVal is not None
+
+ assert self.__column_results_to_string(
+ fetch_results_resp.results.columns) == (1, "NULL\n")
+
+ @needs_session()
+ def test_compute_stats(self):
+ """Exercise the child query path"""
+ self.__query_and_fetch("compute stats functional.alltypes")
diff --git a/pool/shard006/Python/0057718_gmusic.py b/pool/shard006/Python/0057718_gmusic.py
new file mode 100644
index 0000000000000000000000000000000000000000..bc912e9c81e2927a12ff3e8332894d57f8255a28
--- /dev/null
+++ b/pool/shard006/Python/0057718_gmusic.py
@@ -0,0 +1,60 @@
+from gmusicapi import Mobileclient
+import getpass
+
+class GpmSession(object):
+ # Private Variables
+
+ # Public Variables
+ api = None
+ logged_in = False
+ songs = None
+ playlists = None
+
+ # Constructor with optionally passed credentials
+ # Omit credentials if you want to handle login, include for prompts from this module
+ def __init__(self, email=None, pw=None):
+ self.api = Mobileclient()
+ if not email and not pw == None:
+ email = input("Please enter an email address tied to a GPM account: ")
+ pw = getpass.getpass("Please enter the password associated with %s " % email)
+ self.logged_in = self.api.login(email, pw, Mobileclient.FROM_MAC_ADDRESS) # As per api protocol
+ if self.logged_in:
+ print("Google Play Music login successful")
+ else:
+ print("Google Play Music login failed")
+
+ def init(self, songs = True, playlists = True):
+ if songs:
+ self.songs = self.api.get_all_songs()
+ if playlists:
+ self.playlists = self.api.get_all_playlists()
+
+ def get_song_stream(self, title, artist=None):
+ print(not self.songs)
+ if not self.songs:
+ self.init(True, False)
+ song = next(iter((track for track in self.songs if self._filter_condition(track, title, artist)) or []), None)
+ if song:
+ return self.api.get_stream_url(song["id"])
+ else:
+ return None
+
+
+ def _filter_condition(self, song_obj, search_title, search_artist):
+ result = True
+ if search_title:
+ result = result & (song_obj["title"].lower().strip() == search_title.lower().strip())
+ if search_artist:
+ result = result & (song_obj["artist"].lower().strip() == search_artist.lower().strip())
+ return result
+
+def main():
+ session = GpmSession()
+ while not session.logged_in:
+ session = GpmSession()
+ session.init()
+ print(session.get_song_stream("Dirty Laundry", "Bitter Sweet"))
+ print(session.get_song_stream("1940"))
+
+if __name__ == "__main__":
+ main()
\ No newline at end of file
diff --git a/pool/shard006/Python/0057719_graphSim.py b/pool/shard006/Python/0057719_graphSim.py
new file mode 100644
index 0000000000000000000000000000000000000000..1bf7edf078a2b19e771c0618a280d17e38604e70
--- /dev/null
+++ b/pool/shard006/Python/0057719_graphSim.py
@@ -0,0 +1,77 @@
+#This program will run and graph the simulation, comparing serial and parallel
+import sys
+import ConfigParser
+from subprocess import call
+#If not the independent variable, these values will be used
+MOLECULES = 2112
+SIZE = 40
+STEPS = 10000
+DENSITY = .033 #the density of water
+#function to change the time steps in demoConfiguration.txt
+def changeConfigFile(timeSteps, molecules, size):
+ f = open('resources/demo.config','r')
+ lines = f.readlines()
+ lines[1] = str(size) + '\n'
+ lines[2] = str(size) + '\n'
+ lines[3] = str(size) + '\n'
+ lines[9] = str(timeSteps) + '\n'
+ lines[11] = str(molecules) + '\n'
+ f.close()
+ f = open('resources/demo.config','w')
+ for item in lines:
+ f.write(item)
+ f.close()
+#function to get the run-time from the last run
+def getRunTime():
+ config = ConfigParser.RawConfigParser()
+ config.read('run.results')
+ line = config.get('Results','Run-Time')
+ line = line.split()
+ return line[0]
+#function to print out the help information
+def printHelp():
+ print "***HELP***"
+ print "Usage: python graphing/graphSim.py xaxis interval"
+ print "xaxis is what parameter should be on the xaxis: 'steps', 'size', or 'density"
+ print "interval is the xvalues separated by spaces"
+ print "density is in number of molecules/volume"
+ print "Example: python graphing/graphSim density .01 .02 .03 .04\n"
+#Begin program
+input = sys.argv
+#check for invalud inputs
+if len(input) < 3:
+ printHelp()
+ exit(0)
+input.remove("graphing/graphSim.py")
+xaxis = input.pop(0)
+if xaxis != "steps" and xaxis != "size" and xaxis != "density":
+ print "Error: invalid format"
+ printHelp()
+ exit(0)
+#capitalize for ease of printing
+xaxis = xaxis.capitalize()
+#run simulation and prepare output
+f = open('graphing/simResults.txt', 'w')
+f.write(xaxis + '\tSerial\tParallel\n')
+for i in input:
+ if xaxis == "Steps":
+ changeConfigFile(i, MOLECULES, SIZE)
+ if xaxis == "Size":
+ changeConfigFile(STEPS, int(i)*int(i)*int(i)*DENSITY, i)
+ if xaxis == "Density":
+ changeConfigFile(STEPS, float(i)*SIZE*SIZE*SIZE, SIZE)
+ f.write(i+'\t')
+ call(["./bin/metrosim", "resources/demo.config", "-s"])
+ f.write(getRunTime()+'\t')
+ call(["./bin/metrosim", "resources/demo.config", "-p"])
+ f.write(getRunTime()+'\n')
+f.close()
+#set up gnuplot
+f = open('graphing/gnuplotScript','w')
+f.write("set terminal png\nset output 'graph.png'\nset key left top\n")
+f.write("set title 'Serial/Parallel Time Comparison'\n")
+f.write("set ylabel 'Time (s)'\nset xlabel '" + xaxis)
+f.write("'\nplot 'graphing/simResults.txt' using 1:2 w lp title 'Serial', 'graphing/simResults.txt' using 1:3 w lp title 'Parallel'")
+f.close()
+#call gnuplot
+call(["gnuplot", "graphing/gnuplotScript"])
\ No newline at end of file
diff --git a/pool/shard006/Python/0057724_plot_gait.py b/pool/shard006/Python/0057724_plot_gait.py
new file mode 100644
index 0000000000000000000000000000000000000000..c6903ff50413e98fde7aa4094b82106d51aa0125
--- /dev/null
+++ b/pool/shard006/Python/0057724_plot_gait.py
@@ -0,0 +1,270 @@
+# -*- coding: utf-8 -*-
+"""
+====================
+Gait (steps) example
+====================
+In this example, we use DiCoDiLe on an open dataset of gait (steps) IMU
+time-series to discover patterns in the data. We will then use those to attempt
+to detect steps and compare our findings with the ground truth.
+"""
+
+import matplotlib.pyplot as plt
+import numpy as np
+
+###############################################################################
+# # Retrieve trial data
+
+from dicodile.data.gait import get_gait_data
+
+trial = get_gait_data(subject=6, trial=1)
+
+###############################################################################
+# Let’s have a look at the data for one trial.
+
+trial.keys()
+
+###############################################################################
+# We get a dictionary whose keys are metadata items, plus a ‘data’ key that
+# contains a numpy array with the trial time series for each sensor axis, at
+# 100 Hz resolution.
+
+# right foot acceleration (vertical)
+plt.plot(trial['data']['RAV'])
+
+###############################################################################
+# Let’s look at a small portion of the series for both feet, overlaid on the
+# same plot.
+
+fig, ax = plt.subplots()
+ax.plot(trial['data']['LAV'][5000:5800],
+ label='left foot vertical acceleration')
+ax.plot(trial['data']['RAV'][5000:5800],
+ label='right foot vertical acceleration')
+ax.set_xlabel('time (x10ms)')
+ax.set_ylabel('acceleration ($m.s^{-2}$)')
+ax.legend()
+
+###############################################################################
+# We can see the alternating left and right foot movements.
+#
+# In the rest of this example, we will only use the right foot vertical
+# acceleration.
+
+###############################################################################
+# # Convolutional Dictionary Learning
+
+###############################################################################
+# Now, let’s use "dicodile" as solver_z to learn patterns from the data and
+# reconstruct the signal from a sparse representation.
+#
+# First, we initialize a dictionary from parts of the signal:
+
+X = trial['data']['RAV'].to_numpy()
+
+# reshape X to (n_trials, n_channels, n_times)
+X = X.reshape(1, 1, *X.shape)
+
+print(X.shape)
+
+###############################################################################
+# Note the use of reshape to shape the signal as per alphacsc requirements: the
+# shape of the signal should be (n_trials, n_channels, n_times). Here, we have
+# a single-channel time series so it is (1, 1, n_times).
+
+from alphacsc.init_dict import init_dictionary
+
+# set dictionary size
+n_atoms = 8
+
+# set individual atom (patch) size.
+n_times_atom = 200
+
+D_init = init_dictionary(X,
+ n_atoms=8,
+ n_times_atom=200,
+ rank1=False,
+ window=True,
+ D_init='chunk',
+ random_state=60)
+
+print(D_init.shape)
+
+""
+from alphacsc import BatchCDL
+
+cdl = BatchCDL(
+ # Shape of the dictionary
+ n_atoms,
+ n_times_atom,
+ rank1=False,
+ uv_constraint='auto',
+ # Number of iteration for the alternate minimization and cvg threshold
+ n_iter=3,
+ # number of workers to be used for dicodile
+ n_jobs=4,
+ # solver for the z-step
+ solver_z='dicodile',
+ solver_z_kwargs={'max_iter': 10000},
+ window=True,
+ D_init=D_init,
+ random_state=60)
+
+res = cdl.fit(X)
+
+""
+from dicodile.utils.viz import display_dictionaries
+
+D_hat = res._D_hat
+
+fig = display_dictionaries(D_init, D_hat)
+
+###############################################################################
+# # Signal reconstruction
+
+###############################################################################
+# Now, let's reconstruct the original signal.
+
+from alphacsc.utils import construct_X_multi
+
+z_hat = res._z_hat
+
+X_hat = construct_X_multi(z_hat, D_hat)
+
+###############################################################################
+# Plot a small part of the original and reconstructed signals
+
+fig_hat, ax_hat = plt.subplots()
+ax_hat.plot(X[0][0][5000:5800],
+ label='right foot vertical acceleration (ORIGINAL)')
+ax_hat.plot(X_hat[0][0][5000:5800],
+ label='right foot vertical acceleration (RECONSTRUCTED)')
+ax_hat.set_xlabel('time (x10ms)')
+ax_hat.set_ylabel('acceleration ($m.s^{-2}$)')
+ax_hat.legend()
+
+###############################################################################
+# Check that our representation is indeed sparse:
+
+
+np.count_nonzero(z_hat)
+
+###############################################################################
+# Besides our visual check, a measure of how closely we’re reconstructing the
+# original signal is the (normalized) cross-correlation. Let’s compute this:
+
+np.correlate(X[0][0], X_hat[0][0]) / np.sqrt(
+ np.correlate(X[0][0], X[0][0]) * np.correlate(X_hat[0][0], X_hat[0][0])
+)
+
+###############################################################################
+# # Multichannel signals
+
+###############################################################################
+# DiCoDiLe works just as well with multi-channel signals. The gait dataset
+# contains 16 signals (8 for each foot), in the rest of this tutorial, we’ll
+# use three of those.
+
+# Left foot Vertical acceleration, Y rotation and X acceleration
+channels = ['LAV', 'LRY', 'LAX']
+
+###############################################################################
+# Let’s look at a small portion of multi-channel data
+
+colors = plt.rcParams["axes.prop_cycle"]()
+mc_fig, mc_ax = plt.subplots(len(channels), sharex=True)
+
+for ax, chan in zip(mc_ax, channels):
+ ax.plot(trial['data'][chan][5000:5800],
+ label=chan, color=next(colors)["color"])
+mc_fig.legend(loc="upper center")
+
+###############################################################################
+# Let’s put the data in shape for alphacsc: (n_trials, n_channels, n_times)
+
+X_mc_subset = trial['data'][channels].to_numpy().T
+
+X_mc_subset = X_mc_subset.reshape(1, *X_mc_subset.shape)
+
+print(X_mc_subset.shape)
+
+###############################################################################
+# Initialize the dictionary (note that the call is identical to the
+# single-channel version)
+
+D_init_mc = init_dictionary(
+ X_mc_subset, n_atoms=8, n_times_atom=200, rank1=False,
+ window=True, D_init='chunk', random_state=60
+)
+
+print(D_init_mc.shape)
+
+###############################################################################
+# And run DiCoDiLe (note that the call is identical to the single-channel
+# version here as well)
+
+from alphacsc import BatchCDL
+
+cdl = BatchCDL(
+ # Shape of the dictionary
+ n_atoms,
+ n_times_atom,
+ rank1=False,
+ uv_constraint='auto',
+ # Number of iteration for the alternate minimization and cvg threshold
+ n_iter=3,
+ # number of workers to be used for dicodile
+ n_jobs=4,
+ # solver for the z-step
+ solver_z='dicodile',
+ solver_z_kwargs={'max_iter': 10000},
+ window=True,
+ D_init=D_init_mc,
+ random_state=60)
+
+res = cdl.fit(X_mc_subset)
+
+###############################################################################
+# # Signal reconstruction (multichannel)
+
+###############################################################################
+# Now, let’s reconstruct the original signal
+
+from alphacsc.utils import construct_X_multi
+
+z_hat_mc = res._z_hat
+
+D_hat_mc = res._D_hat
+
+X_hat_mc = construct_X_multi(z_hat_mc, D_hat_mc)
+
+###############################################################################
+# Let’s visually compare a small part of the original and reconstructed signal
+# along with the activations.
+
+z_hat_mc.shape
+
+""
+viz_start_idx = 4000
+viz_end_idx = 5800
+viz_chan = 2
+
+max_abs = np.max(np.abs(z_hat_mc), axis=-1)
+max_abs = max_abs.reshape(z_hat_mc.shape[1], 1)
+z_hat_normalized = z_hat_mc / max_abs
+
+fig_hat_mc, ax_hat_mc = plt.subplots(2, figsize=(12, 8))
+
+# plot original and constructed
+ax_hat_mc[0].plot(X_mc_subset[0][viz_chan][viz_start_idx:viz_end_idx],
+ label='ORIGINAL')
+ax_hat_mc[0].plot(X_hat_mc[0][viz_chan][viz_start_idx:viz_end_idx],
+ label='RECONSTRUCTED')
+
+ax_hat_mc[0].set_xlabel('time (x10ms)')
+ax_hat_mc[0].legend()
+
+# plot activations
+for idx in range(z_hat_normalized.shape[1]):
+ ax_hat_mc[1].stem(z_hat_normalized[0][idx][viz_start_idx:viz_end_idx],
+ linefmt=f"C{idx}-",
+ markerfmt=f"C{idx}o")
diff --git a/pool/shard006/Python/0057730_screenshot.py b/pool/shard006/Python/0057730_screenshot.py
new file mode 100644
index 0000000000000000000000000000000000000000..fdc8d38a7889bd23c5116cf1f1306b3580117376
--- /dev/null
+++ b/pool/shard006/Python/0057730_screenshot.py
@@ -0,0 +1,91 @@
+# Copyright 2016 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.
+
+from __future__ import absolute_import
+import datetime
+import logging
+import os
+import random
+import tempfile
+
+import py_utils
+from py_utils import cloud_storage # pylint: disable=import-error
+from telemetry.util import image_util
+from telemetry.internal.util import file_handle
+
+
+def TryCaptureScreenShot(platform, tab=None, timeout=None):
+ """ If the platform or tab supports screenshot, attempt to take a screenshot
+ of the current browser.
+
+ Args:
+ platform: current platform
+ tab: browser tab if available
+ timeout: An float denoting the number of seconds to wait for a successful
+ screenshot. If set to None, only attempts once.
+
+ Returns:
+ file handle of the tempoerary file path for the screenshot if
+ present, None otherwise.
+ """
+ try:
+ if platform.CanTakeScreenshot():
+ tf = tempfile.NamedTemporaryFile(delete=False, suffix='.png')
+ tf.close()
+ try:
+ py_utils.WaitFor(lambda: platform.TakeScreenshot(tf.name), timeout or 0)
+ except py_utils.TimeoutException:
+ logging.warning('Did not succeed in screenshot capture')
+ return file_handle.FromTempFile(tf)
+ if tab and tab.IsAlive() and tab.screenshot_supported:
+ tf = tempfile.NamedTemporaryFile(delete=False, suffix='.png')
+ tf.close()
+ image = tab.Screenshot()
+ image_util.WritePngFile(image, tf.name)
+ return file_handle.FromTempFile(tf)
+ logging.warning(
+ 'Either tab has crashed or browser does not support taking tab '
+ 'screenshot. Skip taking screenshot on failure.')
+ return None
+ except Exception as e: # pylint: disable=broad-except
+ logging.warning('Exception when trying to capture screenshot: %s', repr(e))
+ return None
+
+
+def TryCaptureScreenShotAndUploadToCloudStorage(platform, tab=None):
+ """ If the platform or tab supports screenshot, attempt to take a screenshot
+ of the current browser. If present it uploads this local path to cloud
+ storage and returns the URL of the cloud storage path.
+
+ Args:
+ platform: current platform
+ tab: browser tab if available
+
+ Returns:
+ url of the cloud storage path if screenshot is present, None otherwise
+ """
+ fh = TryCaptureScreenShot(platform, tab)
+ if fh is not None:
+ return _UploadScreenShotToCloudStorage(fh)
+
+ return None
+
+def _GenerateRemotePath(fh):
+ return ('browser-screenshot_%s-%s%-d%s' %
+ (fh.id, datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S'),
+ random.randint(1, 100000), fh.extension))
+
+def _UploadScreenShotToCloudStorage(fh):
+ """ Upload the given screenshot image to cloud storage and return the
+ cloud storage url if successful.
+ """
+ try:
+ return cloud_storage.Insert(cloud_storage.TELEMETRY_OUTPUT,
+ _GenerateRemotePath(fh), fh.GetAbsPath())
+ except cloud_storage.CloudStorageError as err:
+ logging.error('Cloud storage error while trying to upload screenshot: %s',
+ repr(err))
+ return ''
+ finally: # Must clean up screenshot file if exists.
+ os.remove(fh.GetAbsPath())
diff --git a/pool/shard006/Python/0057733_SpatialSoftMaxCUDNN.py b/pool/shard006/Python/0057733_SpatialSoftMaxCUDNN.py
new file mode 100644
index 0000000000000000000000000000000000000000..0bbfe50529f81f0d0a262e5fa16c700580a3350d
--- /dev/null
+++ b/pool/shard006/Python/0057733_SpatialSoftMaxCUDNN.py
@@ -0,0 +1,36 @@
+import DeepFried2 as df
+
+
+def spatial_softmax(img, algo, mode):
+ # check if we have 3D input
+ if img.ndim == 5:
+ # shape: bcd01
+ vol_shape = img.shape
+ # shape: bcd(0*1)
+ vol = df.T.flatten(img, outdim=4)
+ vol = df.th.sandbox.cuda.basic_ops.gpu_contiguous(vol)
+ res = df.th.sandbox.cuda.dnn.GpuDnnSoftmax(tensor_format='bc01', algo=algo, mode=mode)(vol)
+ # shape: bcd01
+ return res.reshape(vol_shape)
+ else:
+ img = df.th.sandbox.cuda.basic_ops.gpu_contiguous(img)
+ return df.th.sandbox.cuda.dnn.GpuDnnSoftmax(tensor_format='bc01', algo=algo, mode=mode)(img)
+
+
+class SpatialSoftMaxCUDNN(df.Module):
+ def __init__(self, algo='accurate', mode='channel'):
+ """
+ - `algo`: One of the following values:
+ - `'fast'`: Straightforward softmax, beware numerical problems.
+ - `'accurate'`: Use the "subtract max input" stabilization to avoid overflows.
+ - `'log'`: Compute the log-softmax instead.
+ - `mode`: One of the following values:
+ - `'instance'`: Computes a single whole softmax per image (across C,H,W; output is B).
+ - `'channel'`: Computs a softmax per-pixel per-image (across C; output is B,H,W).
+ """
+ df.Module.__init__(self)
+ self.algo = algo
+ self.mode = mode
+
+ def symb_forward(self, symb_input):
+ return spatial_softmax(symb_input, self.algo, self.mode)
diff --git a/pool/shard006/Python/0057735_na_ontap_command.py b/pool/shard006/Python/0057735_na_ontap_command.py
new file mode 100644
index 0000000000000000000000000000000000000000..1af0bb7c57e490729130fed1c61646bd162e6cd2
--- /dev/null
+++ b/pool/shard006/Python/0057735_na_ontap_command.py
@@ -0,0 +1,132 @@
+#!/usr/bin/python
+
+# (c) 2018, NetApp, Inc
+# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
+
+from __future__ import absolute_import, division, print_function
+__metaclass__ = type
+
+ANSIBLE_METADATA = {'metadata_version': '1.1',
+ 'status': ['preview'],
+ 'supported_by': 'certified'}
+
+DOCUMENTATION = '''
+author: NetApp Ansible Team (@carchi8py)
+description:
+ - "Run system-cli commands on ONTAP"
+extends_documentation_fragment:
+ - netapp.na_ontap
+module: na_ontap_command
+short_description: NetApp ONTAP Run any cli command, the username provided needs to have console login permission.
+version_added: "2.7"
+options:
+ command:
+ description:
+ - a comma separated list containing the command and arguments.
+ required: true
+ privilege:
+ description:
+ - privilege level at which to run the command.
+ choices: ['admin', 'advanced']
+ default: admin
+ version_added: "2.8"
+'''
+
+EXAMPLES = """
+ - name: run ontap cli command
+ na_ontap_command:
+ hostname: "{{ hostname }}"
+ username: "{{ admin username }}"
+ password: "{{ admin password }}"
+ command: ['version']
+
+ - name: run ontap cli command
+ na_ontap_command:
+ hostname: "{{ hostname }}"
+ username: "{{ admin username }}"
+ password: "{{ admin password }}"
+ command: ['network', 'interface', 'show']
+ privilege: 'admin'
+"""
+
+RETURN = """
+"""
+
+import traceback
+from ansible.module_utils.basic import AnsibleModule
+from ansible.module_utils._text import to_native
+import ansible.module_utils.netapp as netapp_utils
+
+HAS_NETAPP_LIB = netapp_utils.has_netapp_lib()
+
+
+class NetAppONTAPCommand(object):
+ ''' calls a CLI command '''
+
+ def __init__(self):
+ self.argument_spec = netapp_utils.na_ontap_host_argument_spec()
+ self.argument_spec.update(dict(
+ command=dict(required=True, type='list'),
+ privilege=dict(required=False, type='str', choices=['admin', 'advanced'],
+ default='admin')
+ ))
+ self.module = AnsibleModule(
+ argument_spec=self.argument_spec,
+ supports_check_mode=True
+ )
+ parameters = self.module.params
+ # set up state variables
+ self.command = parameters['command']
+ self.privilege = parameters['privilege']
+
+ if HAS_NETAPP_LIB is False:
+ self.module.fail_json(msg="the python NetApp-Lib module is required")
+ else:
+ self.server = netapp_utils.setup_na_ontap_zapi(module=self.module)
+
+ def asup_log_for_cserver(self, event_name):
+ """
+ Fetch admin vserver for the given cluster
+ Create and Autosupport log event with the given module name
+ :param event_name: Name of the event log
+ :return: None
+ """
+ results = netapp_utils.get_cserver(self.server)
+ cserver = netapp_utils.setup_na_ontap_zapi(module=self.module, vserver=results)
+ netapp_utils.ems_log_event(event_name, cserver)
+
+ def run_command(self):
+ ''' calls the ZAPI '''
+ self.asup_log_for_cserver("na_ontap_command: " + str(self.command))
+ command_obj = netapp_utils.zapi.NaElement("system-cli")
+ args_obj = netapp_utils.zapi.NaElement("args")
+ for arg in self.command:
+ args_obj.add_new_child('arg', arg)
+ command_obj.add_child_elem(args_obj)
+ command_obj.add_new_child('priv', self.privilege)
+
+ try:
+ output = self.server.invoke_successfully(command_obj, True)
+ return output.to_string()
+ except netapp_utils.zapi.NaApiError as error:
+ self.module.fail_json(msg='Error running command %s: %s' %
+ (self.command, to_native(error)),
+ exception=traceback.format_exc())
+
+ def apply(self):
+ ''' calls the command and returns raw output '''
+ changed = True
+ output = self.run_command()
+ self.module.exit_json(changed=changed, msg=output)
+
+
+def main():
+ """
+ Execute action from playbook
+ """
+ command = NetAppONTAPCommand()
+ command.apply()
+
+
+if __name__ == '__main__':
+ main()
diff --git a/pool/shard006/Python/0057738_example.py b/pool/shard006/Python/0057738_example.py
new file mode 100644
index 0000000000000000000000000000000000000000..97952a68a4ba9a2220242856684709db1f1fefaa
--- /dev/null
+++ b/pool/shard006/Python/0057738_example.py
@@ -0,0 +1,87 @@
+#!/usr/bin/env python
+
+import sys, os, getpass, datetime
+
+# PyGithub >= 1.13 is required https://pypi.python.org/pypi/PyGithub
+from github import Github
+from github_issues import GithubIssuesBase, GithubIssues
+
+# You could use OAuth here too for unattended access
+# see http://developer.github.com/v3/oauth/#create-a-new-authorization
+print "Enter github username:"
+username = sys.stdin.readline().strip()
+print
+password = getpass.getpass('Enter github password: ')
+
+gh = Github(login_or_token=username, password=password, user_agent='PyGithub/Python')
+# needed to fetch fresh rate_limiting data
+repo = gh.get_repo('autotest/virt-test')
+
+# Requests for logged in users are limited to 5000 per hour
+# or about 1 request every 0.7 seconds
+start = gh.rate_limiting
+# Open up cache and repository
+issues = GithubIssues(gh, 'autotest/virt-test')
+print "Issue #125: ",
+# Any issue can be referenced by number
+print issues[125]
+end = gh.rate_limiting
+print "Requests used: ", start[0] - end[0]
+print "Cache hits: %s misses: %s" % (issues.cache_hits, issues.cache_misses)
+
+# Pull requests are treated as issues
+issues = GithubIssues(gh, 'autotest/virt-test')
+start = end
+print "Pull #526: ",
+print issues[526]
+end = gh.rate_limiting
+print "Requests used: ", start[0] - end[0]
+print "Cache hits: %s misses: %s" % (issues.cache_hits, issues.cache_misses)
+
+# Listing issues requires finding the last issue
+# this takes a while when the cache is empty
+issues = GithubIssues(gh, 'autotest/virt-test')
+start = end
+print "Total number of issues (this could take a while):"
+# This len() is used to force the slower binary-search
+print GithubIssuesBase.__len__(issues)
+end = gh.rate_limiting
+print "Requests used: ", start[0] - end[0]
+print "Cache hits: %s misses: %s" % (issues.cache_hits, issues.cache_misses)
+
+# Searches are supported and return lists of issue-numbers
+issues = GithubIssues(gh, 'autotest/virt-test')
+start = end
+print "Open issues last few days without any label (could take 2-10 minutes):"
+two_days = datetime.timedelta(days=2)
+last_week = datetime.datetime.now() - two_days
+# Search criteria is put into a dictionary
+# state - str - 'open', 'closed'
+# assignee - list of str (login), "none" or "*"
+# mentioned - str (login)
+# labels - list of str (label name)
+# sort - str - 'created', 'updated', 'comments'
+# direction - str - 'asc', 'desc'
+# since - datetime.datetime
+criteria = {'state':'open', 'since':last_week}
+# Search results are cached for 10-minutes, otherwise searches can be slow
+for number in issues.search(criteria):
+ issue = issues[number]
+ # some items must be searched/compared manually
+ if len(issue['labels']) < 1:
+ print ('https://github.com/autotest/virt-test/issues/%s\t"%s"'
+ % (issue['number'], issue['summary']))
+print
+print "Requests used: ", start[0] - end[0]
+print "Cache hits: %s misses: %s" % (issues.cache_hits, issues.cache_misses)
+
+# Now that cache is populated, this will be very fast
+issues = GithubIssues(gh, 'autotest/virt-test')
+start = end
+print "Total number of issues (this should be a lot faster):"
+# This length uses a cached issue count plus a 'since' criteria search
+print len(issues)
+end = gh.rate_limiting
+print "Final Requests used: ", start[0] - end[0]
+print "Cache hits: %s misses: %s" % (issues.cache_hits, issues.cache_misses)
+del issues
diff --git a/pool/shard006/Python/0057739_processor.py b/pool/shard006/Python/0057739_processor.py
new file mode 100644
index 0000000000000000000000000000000000000000..808a0c447b2211474f0c6c2b3aa0e3a13edf3388
--- /dev/null
+++ b/pool/shard006/Python/0057739_processor.py
@@ -0,0 +1,67 @@
+from __future__ import unicode_literals
+
+from django.conf import settings
+from lib.core.utils import load_class
+from .exceptions import DeadConnectionException
+import logging
+logger = logging.getLogger(__name__)
+
+
+class MiddlewareCache(object):
+ _cache = None
+
+ def __init__(self):
+ self._cache = {}
+
+ def get(self, key):
+
+ if not key in self._cache:
+ self.set(key, self.load(key))
+
+ return self._cache.get(key)
+
+ def set(self, key, value):
+ self._cache[key] = value
+
+ def load(self, key):
+ return load_class(key)
+
+
+class MessageProcessor():
+
+ context = None
+ socket = None
+ middleware = None
+ _middleware_classes = None
+
+ def __init__(self, socket):
+ self.socket = socket
+ self.context = socket.context
+ self._middleware_classes = getattr(settings, 'SOCKET_MIDDLEWARE_CLASSES')
+ self.middleware = MiddlewareCache()
+
+ def process_message(self, message):
+
+ for middleware in self._middleware_classes:
+
+ try:
+ Middleware = self.middleware.get(middleware)
+ context, message = Middleware.inbound(self.context, message)
+ self.context = context
+ except KeyError:
+ logger.exception("KeyError in middleware '%s' at '%s' ", middleware, message)
+ except DeadConnectionException as e:
+ #raise e
+ pass
+ #except InterfaceError:
+ # close_connection()
+ except Exception as e:
+ logger.exception(
+ "Unknown Exception thrown in middleware '%s' [%s] [%s] with '%s'",
+ middleware,
+ e.message,
+ e.args,
+ message
+ )
+
+ return self.context
\ No newline at end of file
diff --git a/pool/shard006/Python/0057740_ProcCpuidCollector.py b/pool/shard006/Python/0057740_ProcCpuidCollector.py
new file mode 100644
index 0000000000000000000000000000000000000000..8bb482978094ed2978c0eab54a79668b5e110eaf
--- /dev/null
+++ b/pool/shard006/Python/0057740_ProcCpuidCollector.py
@@ -0,0 +1,51 @@
+# Copyright 2016 Casey Jaymes
+
+# This file is part of PySCAP.
+#
+# PySCAP 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.
+#
+# PySCAP 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 PySCAP. If not, see .
+
+import logging
+import re
+import pprint
+
+from scap.Collector import Collector
+from scap.model.cpe_matching_2_3.CPE import CPE
+
+logger = logging.getLogger(__name__)
+class ProcCpuidCollector(Collector):
+ def collect(self):
+ if 'devices' not in self.host.facts:
+ self.host.facts['devices'] = {}
+
+ if 'cpuinfo' in self.host.facts:
+ return
+
+ self.host.facts['devices']['processors'] = []
+
+ return_code, out_lines, err_lines = self.host.exec_command('cat /proc/cpuinfo')
+ if return_code == 0 and len(out_lines) >= 1:
+ self.host.facts['cpuinfo'] = '\n'.join(out_lines)
+ cur_proc = {}
+ for line in out_lines:
+ line = line.strip()
+ if line == '':
+ self.host.facts['devices']['processors'].append(cur_proc)
+ cur_proc = {}
+ continue
+
+ k, eq, v = line.partition(':')
+ k = k.strip()
+ v = v.strip()
+ cur_proc[k] = v
+ logger.debug(k + ' = ' + v)
diff --git a/pool/shard006/Python/0057745_test_util.py b/pool/shard006/Python/0057745_test_util.py
new file mode 100644
index 0000000000000000000000000000000000000000..f2bc918010f93c6e224f9695bb64c37b007aa43b
--- /dev/null
+++ b/pool/shard006/Python/0057745_test_util.py
@@ -0,0 +1,158 @@
+import unittest
+import os
+import sys
+if sys.version_info[0] >= 3:
+ from io import StringIO
+else:
+ from io import BytesIO as StringIO
+import utils
+TOPDIR = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
+utils.set_search_paths(TOPDIR)
+
+import allosmod.util # noqa:E402
+
+
+class Tests(unittest.TestCase):
+ def test_check_output(self):
+ """Test check_output()"""
+ out = allosmod.util.check_output(['/bin/echo', 'foo'],
+ universal_newlines=True)
+ self.assertEqual(out, 'foo\n')
+ self.assertRaises(OSError, allosmod.util.check_output,
+ ['/bin/echo', 'foo'], retcode=1)
+ out = allosmod.util.check_output(['/bin/cat'], input="foobar",
+ universal_newlines=True)
+ self.assertEqual(out, 'foobar')
+
+ def test_subst_file(self):
+ """Test subst_file"""
+ s_in = StringIO("@VAR1@ @@ @VAR2@\nfoo@VAR1@bar")
+ s_out = StringIO()
+ allosmod.util.subst_file(s_in, s_out,
+ {'VAR1': 'tvar1', 'VAR2': 'tvar2'})
+ self.assertEqual(s_out.getvalue(), 'tvar1 @ tvar2\nfootvar1bar')
+ s_in = StringIO("@VAR1@")
+ s_out = StringIO()
+ self.assertRaises(ValueError, allosmod.util.subst_file, s_in, s_out,
+ {'VAR2': 'tvar2'})
+
+ def test_read_templates(self):
+ """Test read_templates function"""
+ with open('lst', 'w') as fh:
+ fh.write('test1 A 1 10\ntest2\ntest3 B 4 5\n')
+ self.assertEqual(allosmod.util.read_templates('lst'),
+ ['test1', 'test2', 'test3'])
+ os.unlink('lst')
+
+ def test_fix_newlines(self):
+ """Test fix_newlines function"""
+ def assert_content(exp_content):
+ with open('testnl') as fh:
+ content = fh.read()
+ self.assertEqual(content, exp_content)
+ with open('testnl', 'w') as fh:
+ fh.write("test")
+ allosmod.util.fix_newlines("testnl")
+ assert_content("test")
+ with open('testnl', 'w') as fh:
+ fh.write("test\r\nbar\r\n")
+ allosmod.util.fix_newlines("testnl")
+ assert_content("test\nbar\n")
+ os.unlink('testnl')
+
+ def test_sequence(self):
+ """Test Sequence class"""
+ s = allosmod.util.Sequence()
+ s.primary = 'ACG/VT--W'
+ self.assertEqual(s.get_residues(), 'ACGVTW')
+
+ def test_pir_file_empty(self):
+ """Test read of empty PIR file"""
+ sio = StringIO("C; comment\nR; comment\n\n")
+ p = allosmod.util.PIRFile()
+ seqs = list(p.read(sio))
+ self.assertEqual(len(seqs), 0)
+
+ def test_pir_file_unterminated_midfile(self):
+ """Test read of PIR file with unterminated sequence midfile"""
+ sio = StringIO(""">P1;template
+structureX:::::::::
+AFVV
+>P1;seq
+sequence:::::::::
+AFVV*
+""")
+ p = allosmod.util.PIRFile()
+ self.assertRaises(allosmod.util.FileFormatError, list, p.read(sio))
+
+ def test_pir_file_unterminated_endfile(self):
+ """Test read of PIR file with unterminated sequence at end of file"""
+ sio = StringIO(""">P1;template
+structureX:::::::::
+AFVV*
+>P1;seq
+sequence:::::::::
+AFVV
+""")
+ p = allosmod.util.PIRFile()
+ self.assertRaises(allosmod.util.FileFormatError, list, p.read(sio))
+
+ def test_pir_file_ok(self):
+ """Test read of OK PIR file"""
+ sio = StringIO(""">P1; template
+structureX:::::::::
+A-
+FVV*
+>P1;seq
+:::::::::
+AF/VV*
+""")
+ p = allosmod.util.PIRFile()
+ seqs = list(p.read(sio))
+ self.assertEqual(len(seqs), 2)
+ self.assertEqual(seqs[0].primary, 'A-FVV')
+ self.assertEqual(seqs[1].primary, 'AF/VV')
+ # make sure whitespace is stripped from code
+ self.assertEqual(seqs[0].code, 'template')
+ self.assertEqual(seqs[0].prottyp, 'structureX')
+ self.assertEqual(seqs[1].prottyp, 'sequence')
+
+ def test_pir_file_bad_header(self):
+ """Test read of PIR file with bad header"""
+ sio = StringIO(""">P1;template
+garbage
+A-FVV*
+""")
+ p = allosmod.util.PIRFile()
+ self.assertRaises(allosmod.util.FileFormatError, list, p.read(sio))
+
+ def test_pir_file_no_header(self):
+ """Test read of PIR file with no header"""
+ sio = StringIO("AFVV*")
+ p = allosmod.util.PIRFile()
+ self.assertRaises(allosmod.util.FileFormatError, list, p.read(sio))
+
+ def test_pir_file_write(self):
+ """Test write of PIR file"""
+ sio = StringIO()
+ s = allosmod.util.Sequence()
+ s.code = "testcode"
+ s.primary = 'AFV'
+ p = allosmod.util.PIRFile()
+ p.write(sio, s, width=2)
+ self.assertEqual(sio.getvalue(),
+ ">P1;testcode\nsequence:::::::::\nAF\nV\n*\n")
+
+ def test_pdb_filters(self):
+ """Test PDB filters"""
+ self.assertTrue(allosmod.util.atom_filter("ATOM foo"))
+ self.assertFalse(allosmod.util.atom_filter("HETATM foo"))
+ self.assertFalse(allosmod.util.atom_filter("foo"))
+
+ self.assertTrue(allosmod.util.atom_hetatm_filter("ATOM foo"))
+ self.assertTrue(allosmod.util.atom_hetatm_filter("HETATM foo"))
+ self.assertFalse(allosmod.util.atom_hetatm_filter("foo"))
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/pool/shard006/Python/0057747_test_auto_DARTELNorm2MNI.py b/pool/shard006/Python/0057747_test_auto_DARTELNorm2MNI.py
new file mode 100644
index 0000000000000000000000000000000000000000..8af7fc0285005616faa3691e653ce19862af2965
--- /dev/null
+++ b/pool/shard006/Python/0057747_test_auto_DARTELNorm2MNI.py
@@ -0,0 +1,53 @@
+# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT
+from ....testing import assert_equal
+from ..preprocess import DARTELNorm2MNI
+
+
+def test_DARTELNorm2MNI_inputs():
+ input_map = dict(apply_to_files=dict(copyfile=False,
+ field='mni_norm.data.subjs.images',
+ mandatory=True,
+ ),
+ bounding_box=dict(field='mni_norm.bb',
+ ),
+ flowfield_files=dict(field='mni_norm.data.subjs.flowfields',
+ mandatory=True,
+ ),
+ fwhm=dict(field='mni_norm.fwhm',
+ ),
+ ignore_exception=dict(nohash=True,
+ usedefault=True,
+ ),
+ matlab_cmd=dict(),
+ mfile=dict(usedefault=True,
+ ),
+ modulate=dict(field='mni_norm.preserve',
+ ),
+ paths=dict(),
+ template_file=dict(copyfile=False,
+ field='mni_norm.template',
+ mandatory=True,
+ ),
+ use_mcr=dict(),
+ use_v8struct=dict(min_ver='8',
+ usedefault=True,
+ ),
+ voxel_size=dict(field='mni_norm.vox',
+ ),
+ )
+ inputs = DARTELNorm2MNI.input_spec()
+
+ for key, metadata in list(input_map.items()):
+ for metakey, value in list(metadata.items()):
+ yield assert_equal, getattr(inputs.traits()[key], metakey), value
+
+
+def test_DARTELNorm2MNI_outputs():
+ output_map = dict(normalization_parameter_file=dict(),
+ normalized_files=dict(),
+ )
+ outputs = DARTELNorm2MNI.output_spec()
+
+ for key, metadata in list(output_map.items()):
+ for metakey, value in list(metadata.items()):
+ yield assert_equal, getattr(outputs.traits()[key], metakey), value
diff --git a/pool/shard006/Python/0057752_travis_pypi_setup.py b/pool/shard006/Python/0057752_travis_pypi_setup.py
new file mode 100644
index 0000000000000000000000000000000000000000..df6d77757011a9e2d5ee855c72a1d98607f790fe
--- /dev/null
+++ b/pool/shard006/Python/0057752_travis_pypi_setup.py
@@ -0,0 +1,122 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+"""Update encrypted deploy password in Travis config file
+"""
+
+
+from __future__ import print_function
+import base64
+import json
+import os
+from getpass import getpass
+import yaml
+from cryptography.hazmat.primitives.serialization import load_pem_public_key
+from cryptography.hazmat.backends import default_backend
+from cryptography.hazmat.primitives.asymmetric.padding import PKCS1v15
+
+
+try:
+ from urllib import urlopen
+except:
+ from urllib.request import urlopen
+
+
+GITHUB_REPO = 'avsecz/concise'
+TRAVIS_CONFIG_FILE = os.path.join(
+ os.path.dirname(os.path.abspath(__file__)), '.travis.yml')
+
+
+def load_key(pubkey):
+ """Load public RSA key, with work-around for keys using
+ incorrect header/footer format.
+
+ Read more about RSA encryption with cryptography:
+ https://cryptography.io/latest/hazmat/primitives/asymmetric/rsa/
+ """
+ try:
+ return load_pem_public_key(pubkey.encode(), default_backend())
+ except ValueError:
+ # workaround for https://github.com/travis-ci/travis-api/issues/196
+ pubkey = pubkey.replace('BEGIN RSA', 'BEGIN').replace('END RSA', 'END')
+ return load_pem_public_key(pubkey.encode(), default_backend())
+
+
+def encrypt(pubkey, password):
+ """Encrypt password using given RSA public key and encode it with base64.
+
+ The encrypted password can only be decrypted by someone with the
+ private key (in this case, only Travis).
+ """
+ key = load_key(pubkey)
+ encrypted_password = key.encrypt(password, PKCS1v15())
+ return base64.b64encode(encrypted_password)
+
+
+def fetch_public_key(repo):
+ """Download RSA public key Travis will use for this repo.
+
+ Travis API docs: http://docs.travis-ci.com/api/#repository-keys
+ """
+ keyurl = 'https://api.travis-ci.org/repos/{0}/key'.format(repo)
+ data = json.loads(urlopen(keyurl).read().decode())
+ if 'key' not in data:
+ errmsg = "Could not find public key for repo: {}.\n".format(repo)
+ errmsg += "Have you already added your GitHub repo to Travis?"
+ raise ValueError(errmsg)
+ return data['key']
+
+
+def prepend_line(filepath, line):
+ """Rewrite a file adding a line to its beginning.
+ """
+ with open(filepath) as f:
+ lines = f.readlines()
+
+ lines.insert(0, line)
+
+ with open(filepath, 'w') as f:
+ f.writelines(lines)
+
+
+def load_yaml_config(filepath):
+ with open(filepath) as f:
+ return yaml.load(f)
+
+
+def save_yaml_config(filepath, config):
+ with open(filepath, 'w') as f:
+ yaml.dump(config, f, default_flow_style=False)
+
+
+def update_travis_deploy_password(encrypted_password):
+ """Update the deploy section of the .travis.yml file
+ to use the given encrypted password.
+ """
+ config = load_yaml_config(TRAVIS_CONFIG_FILE)
+
+ config['deploy']['password'] = dict(secure=encrypted_password)
+
+ save_yaml_config(TRAVIS_CONFIG_FILE, config)
+
+ line = ('# This file was autogenerated and will overwrite'
+ ' each time you run travis_pypi_setup.py\n')
+ prepend_line(TRAVIS_CONFIG_FILE, line)
+
+
+def main(args):
+ public_key = fetch_public_key(args.repo)
+ password = args.password or getpass('PyPI password: ')
+ update_travis_deploy_password(encrypt(public_key, password.encode()))
+ print("Wrote encrypted password to .travis.yml -- you're ready to deploy")
+
+
+if '__main__' == __name__:
+ import argparse
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument('--repo', default=GITHUB_REPO,
+ help='GitHub repo (default: %s)' % GITHUB_REPO)
+ parser.add_argument('--password',
+ help='PyPI password (will prompt if not provided)')
+
+ args = parser.parse_args()
+ main(args)
diff --git a/pool/shard006/Python/0057753_evoked.py b/pool/shard006/Python/0057753_evoked.py
new file mode 100644
index 0000000000000000000000000000000000000000..ff9af06cfd868665b2ea4140e076b111c08d593e
--- /dev/null
+++ b/pool/shard006/Python/0057753_evoked.py
@@ -0,0 +1,165 @@
+# Authors: Alexandre Gramfort
+# Daniel Strohmeier
+# Martin Luessi
+#
+# License: BSD (3-clause)
+import copy
+import warnings
+
+import numpy as np
+
+from ..io.pick import pick_channels_cov
+from ..forward import apply_forward
+from ..utils import check_random_state, verbose, _time_mask
+
+
+@verbose
+def simulate_evoked(fwd, stc, info, cov, snr=3., tmin=None, tmax=None,
+ iir_filter=None, random_state=None, verbose=None):
+ """Generate noisy evoked data.
+
+ .. note:: No projections from ``info`` will be present in the
+ output ``evoked``. You can use e.g.
+ :func:`evoked.add_proj ` or
+ :func:`evoked.set_eeg_reference `
+ to add them afterward as necessary.
+
+ Parameters
+ ----------
+ fwd : Forward
+ a forward solution.
+ stc : SourceEstimate object
+ The source time courses.
+ info : dict
+ Measurement info to generate the evoked.
+ cov : Covariance object
+ The noise covariance.
+ snr : float
+ signal to noise ratio in dB. It corresponds to
+ 10 * log10( var(signal) / var(noise) ).
+ tmin : float | None
+ start of time interval to estimate SNR. If None first time point
+ is used.
+ tmax : float | None
+ start of time interval to estimate SNR. If None last time point
+ is used.
+ iir_filter : None | array
+ IIR filter coefficients (denominator) e.g. [1, -1, 0.2].
+ random_state : None | int | np.random.RandomState
+ To specify the random generator state.
+ verbose : bool, str, int, or None
+ If not None, override default verbose level (see :func:`mne.verbose`
+ and :ref:`Logging documentation ` for more).
+
+ Returns
+ -------
+ evoked : Evoked object
+ The simulated evoked data
+
+ See Also
+ --------
+ simulate_raw
+ simulate_stc
+ simulate_sparse_stc
+
+ Notes
+ -----
+ .. versionadded:: 0.10.0
+ """
+ evoked = apply_forward(fwd, stc, info)
+ if snr < np.inf:
+ noise = simulate_noise_evoked(evoked, cov, iir_filter, random_state)
+ evoked_noise = add_noise_evoked(evoked, noise, snr, tmin=tmin,
+ tmax=tmax)
+ else:
+ evoked_noise = evoked
+ return evoked_noise
+
+
+def simulate_noise_evoked(evoked, cov, iir_filter=None, random_state=None):
+ """Create noise as a multivariate Gaussian.
+
+ The spatial covariance of the noise is given from the cov matrix.
+
+ Parameters
+ ----------
+ evoked : evoked object
+ an instance of evoked used as template
+ cov : Covariance object
+ The noise covariance
+ iir_filter : None | array
+ IIR filter coefficients (denominator)
+ random_state : None | int | np.random.RandomState
+ To specify the random generator state.
+
+ Returns
+ -------
+ noise : evoked object
+ an instance of evoked
+
+ Notes
+ -----
+ .. versionadded:: 0.10.0
+ """
+ noise = evoked.copy()
+ noise.data = _generate_noise(evoked.info, cov, iir_filter, random_state,
+ evoked.data.shape[1])[0]
+ return noise
+
+
+def _generate_noise(info, cov, iir_filter, random_state, n_samples, zi=None):
+ """Create spatially colored and temporally IIR-filtered noise."""
+ from scipy.signal import lfilter
+ noise_cov = pick_channels_cov(cov, include=info['ch_names'], exclude=[])
+ if set(info['ch_names']) != set(noise_cov.ch_names):
+ raise ValueError('Evoked and covariance channel names are not '
+ 'identical. Cannot generate the noise matrix. '
+ 'Channels missing in covariance %s.' %
+ np.setdiff1d(info['ch_names'], noise_cov.ch_names))
+
+ rng = check_random_state(random_state)
+ c = np.diag(noise_cov.data) if noise_cov['diag'] else noise_cov.data
+ mu_channels = np.zeros(len(c))
+ # we almost always get a positive semidefinite warning here, so squash it
+ with warnings.catch_warnings(record=True):
+ noise = rng.multivariate_normal(mu_channels, c, n_samples).T
+ if iir_filter is not None:
+ if zi is None:
+ zi = np.zeros((len(c), len(iir_filter) - 1))
+ noise, zf = lfilter([1], iir_filter, noise, axis=-1, zi=zi)
+ else:
+ zf = None
+ return noise, zf
+
+
+def add_noise_evoked(evoked, noise, snr, tmin=None, tmax=None):
+ """Add noise to evoked object with specified SNR.
+
+ SNR is computed in the interval from tmin to tmax.
+
+ Parameters
+ ----------
+ evoked : Evoked object
+ An instance of evoked with signal
+ noise : Evoked object
+ An instance of evoked with noise
+ snr : float
+ signal to noise ratio in dB. It corresponds to
+ 10 * log10( var(signal) / var(noise) )
+ tmin : float
+ start time before event
+ tmax : float
+ end time after event
+
+ Returns
+ -------
+ evoked_noise : Evoked object
+ An instance of evoked corrupted by noise
+ """
+ evoked = copy.deepcopy(evoked)
+ tmask = _time_mask(evoked.times, tmin, tmax, sfreq=evoked.info['sfreq'])
+ tmp = 10 * np.log10(np.mean((evoked.data[:, tmask] ** 2).ravel()) /
+ np.mean((noise.data ** 2).ravel()))
+ noise.data = 10 ** ((tmp - float(snr)) / 20) * noise.data
+ evoked.data += noise.data
+ return evoked
diff --git a/pool/shard006/Python/0057755_decorators.py b/pool/shard006/Python/0057755_decorators.py
new file mode 100644
index 0000000000000000000000000000000000000000..045c4250c39f687fc2f4bc39e2a828e9bb9d9b6e
--- /dev/null
+++ b/pool/shard006/Python/0057755_decorators.py
@@ -0,0 +1,16 @@
+from django.contrib.auth import REDIRECT_FIELD_NAME
+from django.contrib.auth.decorators import user_passes_test
+
+def not_anonymous_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url=None):
+ """
+ Decorator for views that checks that the user is logged in and his username is not contain 'anonymous',
+ redirecting to the log-in page if necessary.
+ """
+ actual_decorator = user_passes_test(
+ lambda u: u.is_authenticated() and 'anonymous' not in u.username,
+ login_url=login_url,
+ redirect_field_name=redirect_field_name
+ )
+ if function:
+ return actual_decorator(function)
+ return actual_decorator
\ No newline at end of file
diff --git a/pool/shard006/Python/0057756_module_utilities.py b/pool/shard006/Python/0057756_module_utilities.py
new file mode 100644
index 0000000000000000000000000000000000000000..5fad3146ae9e00b88aa7977e0b75c34e95f310d4
--- /dev/null
+++ b/pool/shard006/Python/0057756_module_utilities.py
@@ -0,0 +1,208 @@
+import sys
+import os
+import logging
+import getpass
+import platform
+import time
+#import pkg_resources
+import json
+
+import sassie.util.sasconfig as sasconfig
+
+if sasconfig.__level__ == "DEBUG": DEBUG = True
+
+class run_utils():
+
+ def __init__(self,app,txtOutput):
+ self.__application__ = app
+ self.txtOutput = txtOutput
+
+ def write_json_file(self):
+
+ self.logger.debug('in write_json_file')
+
+ self.logger.info('writing json files with input variables')
+
+ with open(self.parmfile,'w') as outfile:
+ json.dump([self.v],outfile)
+ self.logger.info('writing parameters to '+self.parmfile)
+
+ if(os.path.isfile('.last_sas.json')):
+ os.system('mv .last_sas.json .last_sas.json_backup')
+ self.logger.info('backing up existing .last_sas.json file to .last_sas.json_backup')
+
+ if(os.path.isfile('.last_sas_'+self.__application__+'.json')):
+ os.system('mv .last_sas_'+self.__application__+'.json .last_sas_'+self.__application__+'.json_backup')
+ self.logger.info('backing up existing .last_sas_'+self.__application__+'.json file to .last_sas_'+self.__application__+'.json_backup')
+
+ with open('.last_sas.json','w') as outfile:
+ json.dump([self.v],outfile)
+ self.logger.info('writing parameters to .last_sas.json file')
+
+ with open('.last_sas_'+self.__application__+'.json','w') as outfile:
+ json.dump([self.v],outfile)
+ self.logger.info('writing parameters to .last_sas_'+self.__application__+'.json file')
+
+ self.logger.info('input variables: '+json.dumps([self.v] ))
+
+ return
+
+ def general_setup(self,other_self):
+
+ ''' method to write json file of input variables and setup logging '''
+
+ ''' grab all of the variables in the variable class instance '''
+ log = other_self.log
+ mvars = other_self.mvars
+
+ log.debug('in general_setup')
+
+ input_vars = [attr for attr in dir(mvars) if not callable(getattr(mvars,attr)) and not attr.startswith("__")]
+
+ ''' put the variables into a dictionary to send to json '''
+
+ input_variables = {}
+
+ for var in input_vars:
+ input_variables[var] = getattr(mvars, var)
+
+ self.v = input_variables
+
+ self.write_json_file()
+ runname = self.v['runname']
+ self.runpath = os.path.join(runname,self.__application__)
+
+ self.logger.info('setting runpath directory to : '+self.runpath)
+
+ try:
+ if(not os.path.exists(runname)):
+ os.makedirs(self.runpath)
+ elif(not os.path.exists(self.runpath)):
+ os.mkdir(self.runpath)
+ self.logger.info('creating directory : '+self.runpath)
+ except:
+ self.logger.critical('FAILED to create '+self.runpath+' directory')
+
+ other_self.runpath = self.runpath
+ other_self.parmfile = self.parmfile
+
+ return
+
+ def preamble(self):
+
+ user = getpass.getuser()
+ current_path = os.getcwd()
+ self.logger.debug('in preamble')
+ #self.logger.info('sassie version(sassie) : '+sassie.__version__)
+ #self.logger.info('sassie version : '+pkg_resources.get_distribution("sassie_2").version)
+ self.logger.info('module_application : '+self.__application__)
+ self.logger.info('executed by user : '+user+' on '+time.ctime())
+ self.logger.info('current directory : '+current_path)
+ self.logger.info('hostname : '+platform.node())
+
+ return
+
+ def setup_logging(self,other_self):
+
+ self.logger = logging.getLogger(self.__application__)
+ if (sasconfig.__level__ == 'DEBUG'):
+ self.logger.setLevel(logging.DEBUG)
+ else:
+ self.logger.setLevel(logging.INFO)
+
+ timestr = time.strftime("%Y%m%d-%H%M%S")
+
+ self.logfile = self.__application__+'_'+timestr+'.sassie_log'
+ self.parmfile = self.logfile[:-3]+'json'
+ outfile = open(self.logfile,"w")
+ st = 'Date\t\tTime\t\tFile\t\tMethod\t\tLine\tLevel\tMessage\n'
+ outfile.write(st) #; print(st)
+ outfile.close()
+
+ file_handler = logging.FileHandler(self.logfile)
+ formatter = logging.Formatter('%(asctime)s - %(filename)s - %(funcName)s - %(lineno)d - %(levelname)s - %(message)s')
+ file_handler.setFormatter(formatter)
+
+ output_handler = logging.StreamHandler(sys.stdout)
+ output_handler.setLevel(logging.WARNING)
+ output_handler.setFormatter(formatter)
+
+ self.logger.addHandler(file_handler)
+ self.logger.addHandler(output_handler)
+
+ self.logger.debug('in setup_logging')
+ self.logger.info("Program started")
+
+ self.preamble()
+
+ other_self.log = self.logger
+ other_self.logfile = self.logfile
+
+ return
+
+ def print_gui(self,message):
+ '''
+ method to output message to logger and txtOutput (gui)
+ '''
+
+ self.logger.info(message)
+ self.txtOutput.put(message)
+ if DEBUG: print message
+
+ def clean_up(self,log):
+ '''
+ method to move files to runpath directory and finish tasks
+ '''
+
+ log.debug('in clean_up')
+
+ os.system('mv '+self.logfile+' '+self.runpath)
+ os.system('mv '+self.parmfile+' '+self.runpath)
+
+ def capture_exception(self,message):
+
+ ''' this method is a placehoder for a possible future exception handler ... notes are below for usage in-line in code '''
+
+
+ ''' This plain 'except:' catches all exceptions, not only system '''
+
+ # log = self.log
+ # try:
+ # something_that_may_fail()
+ # except:
+ # error = sys.exc_info()[0]
+ # log.error('ERROR: '+error)
+
+
+ ''' this is an example of EAFP ... easier to ask for forgiveness than permission ... the preferred way ... also allows some cleanup etc '''
+
+ #def display_username(user_id):
+ # try:
+ # db_connection = get_db_connection()
+ # except DatabaseEatenByGrueError:
+ # print('Sorry! Database was eaten by a grue.')
+ # else:
+ # print(db_connection.get_username(user_id))
+ # db_connection.cleanup()
+
+ ''' the following is an example of check first or look before you leap LBYL ... could still not work in all cases (race conditions possible) '''
+
+ #def print_object(some_object):
+ # # Check if the object is printable...
+ # try:
+ # printable = str(some_object)
+ # except TypeError:
+ # print("unprintable object")
+ # else:
+ # print(printable)
+
+
+ ''' see http://www.jeffknupp.com/blog/2013/02/06/write-cleaner-python-use-exceptions/ '''
+
+
+ ''' proper way to open a file to read to make sure that it closes correctly if there is an error '''
+
+ #with open("myfile.txt") as f:
+ # for line in f:
+ # print line,
+
diff --git a/pool/shard006/Python/0057761_model.py b/pool/shard006/Python/0057761_model.py
new file mode 100644
index 0000000000000000000000000000000000000000..3921a51364971aac852dd60778fdb20a375fbfc2
--- /dev/null
+++ b/pool/shard006/Python/0057761_model.py
@@ -0,0 +1,110 @@
+import math
+import random
+from queue import PriorityQueue
+from app.logic.device import Device
+from app.logic.incoming_event import IncomingEvent
+from app.logic.outcoming_first_event import OutcomingFirstEvent
+from app.logic.outcoming_second_event import OutcomingSecondEvent
+from app.logic.request import Request
+
+class Model:
+
+ event_list = None
+ work_time = None
+ inteval_time = None
+ model_time = None
+
+
+ @staticmethod
+ def initialize(work_time_value):
+ Model.event_list = PriorityQueue()
+ Model.work_time = work_time_value
+ Model.interval_time = 60
+ Model.model_time = 0.0
+ Model.device1 = Device(30, 70)
+ Model.device2 = Device(45, 60)
+ Model.add_event(IncomingEvent(0.0))
+
+ @staticmethod
+ def start():
+ while Model.model_time < Model.work_time:
+ present_event = Model.get_event()
+ Model.model_time = present_event.time
+ present_event.handle_self(Model)
+
+ @staticmethod
+ def add_event(event):
+ Model.event_list.put(event)
+
+ @staticmethod
+ def get_event():
+ return Model.event_list.get()
+
+ @staticmethod
+ def get_exp_interval():
+ return (-1) * math.log(1 - random.random()) * Model.interval_time
+
+ @staticmethod
+ def handle_incoming_event(time):
+ event_time = time + Model.get_exp_interval()
+ Model.add_event(IncomingEvent(event_time))
+ current_request_number = Model.device1.next_request_number
+ request = Request(current_request_number, time)
+ if Model.device1.present_request != None:
+ Model.device1.add_request(request)
+ else:
+ Model.process_device1(request)
+ #log function
+ print('[handle an incoming event]\t\t\t{0:.2f} sec.'.format(event_time))
+
+ @staticmethod
+ def process_device1(request):
+ Model.device1.present_request = request
+ Model.device1.next_request_number += 1
+ time = Model.device1.get_processing_time()
+ totalTime = Model.model_time - request.time
+ Model.add_event(OutcomingFirstEvent(Model.model_time + totalTime))
+ #log function
+ print('\t\t\trequest {0}'.format(request.number))
+
+ @staticmethod
+ def handle_outcoming_first_event(time):
+ present_request = Model.device1.present_request
+ Model.device1.present_request = None
+ if not Model.device1.is_empty_request_queue():
+ request = Model.device1.remove_request()
+ process_device1(request)
+ else:
+ Model.device1.preset_request = None
+ if Model.device2.present_request != None:
+ Model.device2.add_request(present_request)
+ else:
+ Model.process_device2(present_request)
+ #log function
+ print('[handle an outcoming event from 1-st device]\t{0:.2f} sec'.format(
+ time))
+
+ @staticmethod
+ def process_device2(request):
+ Model.device2.present_request = request
+ Model.device2.next_request_number += 1
+ time = Model.device2.get_processing_time()
+ totalTime = Model.model_time - request.time
+ Model.add_event(OutcomingSecondEvent(Model.model_time + totalTime))
+ #log function
+ print('\t\t\trequest {0}'.format(request.number))
+
+ @staticmethod
+ def handle_outcoming_second_event(time):
+ Model.device2.present_request = None
+ if not Model.device2.is_empty_request_queue():
+ request = Model.device2.remove_request()
+ process_device2(request)
+ else:
+ Model.device2.present_request = None
+ #log function
+ print('[handling an outcoming event from 2-nd device]\t{0:.2f} sec'.format(
+ time))
+
+
+
diff --git a/pool/shard006/Python/0057763_support.py b/pool/shard006/Python/0057763_support.py
new file mode 100644
index 0000000000000000000000000000000000000000..d8d8b7af3c9b1b967e7c81f9c4a22d633978b3db
--- /dev/null
+++ b/pool/shard006/Python/0057763_support.py
@@ -0,0 +1,139 @@
+"""Support Information module.
+
+The module provides functions to gain information to be included in issues.
+It neither contains normal functionality nor is it used by GitGutter.
+"""
+import os
+import subprocess
+import textwrap
+
+import sublime
+import sublime_plugin
+
+# get absolute path of the package
+PACKAGE_PATH = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+if os.path.isfile(PACKAGE_PATH):
+ # Package is a PACKAGE.sublime-package so get its filename
+ PACKAGE, _ = os.path.splitext(os.path.basename(PACKAGE_PATH))
+elif os.path.isdir(PACKAGE_PATH):
+ # Package is a directory, so get its basename
+ PACKAGE = os.path.basename(PACKAGE_PATH)
+else:
+ raise ValueError('Package is no file and no directory!')
+
+
+def git(*args):
+ """Read version of git binary."""
+ if os.name == 'nt':
+ startupinfo = subprocess.STARTUPINFO()
+ startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
+ else:
+ startupinfo = None
+ proc = subprocess.Popen(
+ args=['git'] + [arg for arg in args], startupinfo=startupinfo,
+ stdout=subprocess.PIPE, stdin=subprocess.PIPE,
+ # run command in package directory if exists.
+ cwd=PACKAGE_PATH if os.path.isdir(PACKAGE_PATH) else None)
+ stdout, _ = proc.communicate()
+ return stdout.decode('utf-8').strip() if stdout else None
+
+
+def git_version():
+ """Read version of git binary."""
+ try:
+ return git('--version')
+ except Exception as exception:
+ print('%s: %s' % (PACKAGE, exception))
+ return 'git version could not be acquired!'
+
+
+def gitgutter_version():
+ """Read commit hash or version of GitGutter."""
+ try:
+ return git('rev-parse', 'HEAD')[:7]
+ except:
+ try:
+ return sublime.load_resource(
+ 'Packages/%s/VERSION' % PACKAGE).strip()
+ except Exception as exception:
+ print('%s: %s' % (PACKAGE, exception))
+ return 'Version could not be acquired!'
+
+
+def module_version(module, attr):
+ """Format the module version."""
+ try:
+ version = getattr(module, attr)
+ if callable(version):
+ version = version()
+ except Exception as exception:
+ print('%s: %s' % (PACKAGE, exception))
+ version = 'version could not be acquired!'
+
+ if not isinstance(version, str):
+ version = '.'.join((str(x) for x in version))
+ return version
+
+
+def is_installed_by_package_control():
+ """Check if installed by package control."""
+ settings = sublime.load_settings('Package Control.sublime-settings')
+ return str(PACKAGE in set(settings.get('installed_packages', [])))
+
+
+class GitGutterSupportInfoCommand(sublime_plugin.ApplicationCommand):
+ """Support Information Command."""
+
+ @staticmethod
+ def run():
+ """Run command."""
+ info = {
+ 'platform': sublime.platform(),
+ 'st_version': sublime.version(),
+ 'arch': sublime.arch(),
+ 'package_version': gitgutter_version(),
+ 'pc_install': is_installed_by_package_control(),
+ 'git_version': git_version()
+ }
+
+ try:
+ import markdown
+ info['markdown'] = module_version(markdown, 'version')
+ except ImportError:
+ info['markdown'] = 'not installed!'
+
+ try:
+ import mdpopups
+ info['mdpopups'] = module_version(mdpopups, 'version')
+ except ImportError:
+ info['mdpopups'] = 'not installed!'
+
+ try:
+ import jinja2
+ info['jinja'] = module_version(jinja2, '__version__')
+ except ImportError:
+ info['jinja'] = 'not installed!'
+
+ try:
+ import pygments
+ info['pygments'] = module_version(pygments, '__version__')
+ except ImportError:
+ info['pygments'] = 'not installed!'
+
+ msg = textwrap.dedent(
+ """\
+ - Sublime Text %(st_version)s
+ - Platform: %(platform)s
+ - Arch: %(arch)s
+ - GitGutter %(package_version)s
+ - Install via PC: %(pc_install)s
+ - %(git_version)s
+ - mdpopups %(mdpopups)s
+ - markdown %(markdown)s
+ - pygments %(pygments)s
+ - jinja2 %(jinja)s
+ """ % info
+ )
+
+ sublime.message_dialog(msg + '\nInfo has been copied to clipboard.')
+ sublime.set_clipboard(msg)
diff --git a/pool/shard006/Python/0057767_sphinx_module_loader.py b/pool/shard006/Python/0057767_sphinx_module_loader.py
new file mode 100644
index 0000000000000000000000000000000000000000..dcb580c93230a499d836a680c96bd0a21d3af832
--- /dev/null
+++ b/pool/shard006/Python/0057767_sphinx_module_loader.py
@@ -0,0 +1,97 @@
+"""
+Command-module loader for CMU Pocket Sphinx.
+
+This script is based on 'dfly-loader-wsr.py' written by Christo Butcher and
+has been adapted to work with the Sphinx engine instead.
+
+This script can be used to look for Dragonfly command-modules for use with
+the CMU Pocket Sphinx engine. It scans the directory it's in and loads any
+``_*.py`` it finds.
+"""
+
+
+# TODO Have a simple GUI for pausing, resuming, cancelling and stopping
+# recognition, etc
+
+import os.path
+import logging
+
+
+from dragonfly import RecognitionObserver, get_engine
+from dragonfly.loader import CommandModuleDirectory
+from dragonfly.log import setup_log
+
+# --------------------------------------------------------------------------
+# Set up basic logging.
+
+setup_log()
+
+
+# --------------------------------------------------------------------------
+# Simple recognition observer class.
+
+class Observer(RecognitionObserver):
+ def on_begin(self):
+ print("Speech started.")
+
+ def on_recognition(self, words):
+ print(" ".join(words))
+
+ def on_failure(self):
+ print("Sorry, what was that?")
+
+
+# --------------------------------------------------------------------------
+# Main event driving loop.
+
+def main():
+ logging.basicConfig(level=logging.INFO)
+
+ try:
+ path = os.path.dirname(__file__)
+ except NameError:
+ # The "__file__" name is not always available, for example
+ # when this module is run from PythonWin. In this case we
+ # simply use the current working directory.
+ path = os.getcwd()
+ __file__ = os.path.join(path, "sphinx_module_loader.py")
+
+ engine = get_engine("sphinx")
+
+ # Try to import the local engine configuration object first. If there isn't one,
+ # use the default engine configuration.
+ log = logging.getLogger("config")
+ try:
+ import config
+ engine.config = config
+ log.info("Using local engine configuration module 'config.py'")
+ except ImportError:
+ pass
+ except Exception as e:
+ # Log errors caught when setting the configuration.
+ log.exception("Failed to set config using 'config.py': %s" % e)
+ log.warning("Falling back to the default engine configuration")
+
+ # You can also set any configuration options here instead of using a
+ # config.py file. For example:
+ # engine.config.START_ASLEEP = False
+
+ # Call connect() now that the engine configuration is set.
+ engine.connect()
+
+ # Register a recognition observer
+ observer = Observer()
+ observer.register()
+
+ directory = CommandModuleDirectory(path, excludes=[__file__])
+ directory.load()
+
+ # Start the engine's main recognition loop
+ try:
+ engine.recognise_forever()
+ except KeyboardInterrupt:
+ pass
+
+
+if __name__ == "__main__":
+ main()
diff --git a/pool/shard006/Python/0057771_test_volumes_negative.py b/pool/shard006/Python/0057771_test_volumes_negative.py
new file mode 100644
index 0000000000000000000000000000000000000000..92f5ea862790c5317fb126a279ab5845984d89fa
--- /dev/null
+++ b/pool/shard006/Python/0057771_test_volumes_negative.py
@@ -0,0 +1,111 @@
+# Copyright 2012 OpenStack Foundation
+# All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License"); you may
+# not use this file except in compliance with the License. You may obtain
+# a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+# License for the specific language governing permissions and limitations
+# under the License.
+
+from tempest.api.compute import base
+from tempest.common.utils import data_utils
+from tempest import config
+from tempest.lib import exceptions as lib_exc
+from tempest import test
+
+CONF = config.CONF
+
+
+class VolumesNegativeTest(base.BaseV2ComputeTest):
+
+ @classmethod
+ def skip_checks(cls):
+ super(VolumesNegativeTest, cls).skip_checks()
+ if not CONF.service_available.cinder:
+ skip_msg = ("%s skipped as Cinder is not available" % cls.__name__)
+ raise cls.skipException(skip_msg)
+
+ @classmethod
+ def setup_clients(cls):
+ super(VolumesNegativeTest, cls).setup_clients()
+ cls.client = cls.volumes_extensions_client
+
+ @test.attr(type=['negative'])
+ @test.idempotent_id('c03ea686-905b-41a2-8748-9635154b7c57')
+ def test_volume_get_nonexistent_volume_id(self):
+ # Negative: Should not be able to get details of nonexistent volume
+ # Creating a nonexistent volume id
+ # Trying to GET a non existent volume
+ self.assertRaises(lib_exc.NotFound, self.client.show_volume,
+ data_utils.rand_uuid())
+
+ @test.attr(type=['negative'])
+ @test.idempotent_id('54a34226-d910-4b00-9ef8-8683e6c55846')
+ def test_volume_delete_nonexistent_volume_id(self):
+ # Negative: Should not be able to delete nonexistent Volume
+ # Creating nonexistent volume id
+ # Trying to DELETE a non existent volume
+ self.assertRaises(lib_exc.NotFound, self.client.delete_volume,
+ data_utils.rand_uuid())
+
+ @test.attr(type=['negative'])
+ @test.idempotent_id('5125ae14-152b-40a7-b3c5-eae15e9022ef')
+ def test_create_volume_with_invalid_size(self):
+ # Negative: Should not be able to create volume with invalid size
+ # in request
+ v_name = data_utils.rand_name('Volume')
+ metadata = {'Type': 'work'}
+ self.assertRaises(lib_exc.BadRequest, self.client.create_volume,
+ size='#$%', display_name=v_name, metadata=metadata)
+
+ @test.attr(type=['negative'])
+ @test.idempotent_id('131cb3a1-75cc-4d40-b4c3-1317f64719b0')
+ def test_create_volume_with_out_passing_size(self):
+ # Negative: Should not be able to create volume without passing size
+ # in request
+ v_name = data_utils.rand_name('Volume')
+ metadata = {'Type': 'work'}
+ self.assertRaises(lib_exc.BadRequest, self.client.create_volume,
+ size='', display_name=v_name, metadata=metadata)
+
+ @test.attr(type=['negative'])
+ @test.idempotent_id('8cce995e-0a83-479a-b94d-e1e40b8a09d1')
+ def test_create_volume_with_size_zero(self):
+ # Negative: Should not be able to create volume with size zero
+ v_name = data_utils.rand_name('Volume')
+ metadata = {'Type': 'work'}
+ self.assertRaises(lib_exc.BadRequest, self.client.create_volume,
+ size='0', display_name=v_name, metadata=metadata)
+
+ @test.attr(type=['negative'])
+ @test.idempotent_id('f01904f2-e975-4915-98ce-cb5fa27bde4f')
+ def test_get_invalid_volume_id(self):
+ # Negative: Should not be able to get volume with invalid id
+ self.assertRaises(lib_exc.NotFound,
+ self.client.show_volume, '#$%%&^&^')
+
+ @test.attr(type=['negative'])
+ @test.idempotent_id('62bab09a-4c03-4617-8cca-8572bc94af9b')
+ def test_get_volume_without_passing_volume_id(self):
+ # Negative: Should not be able to get volume when empty ID is passed
+ self.assertRaises(lib_exc.NotFound, self.client.show_volume, '')
+
+ @test.attr(type=['negative'])
+ @test.idempotent_id('62972737-124b-4513-b6cf-2f019f178494')
+ def test_delete_invalid_volume_id(self):
+ # Negative: Should not be able to delete volume when invalid ID is
+ # passed
+ self.assertRaises(lib_exc.NotFound,
+ self.client.delete_volume, '!@#$%^&*()')
+
+ @test.attr(type=['negative'])
+ @test.idempotent_id('0d1417c5-4ae8-4c2c-adc5-5f0b864253e5')
+ def test_delete_volume_without_passing_volume_id(self):
+ # Negative: Should not be able to delete volume when empty ID is passed
+ self.assertRaises(lib_exc.NotFound, self.client.delete_volume, '')
diff --git a/pool/shard006/Python/0057775_test_delegated_factory_py2_py3.py b/pool/shard006/Python/0057775_test_delegated_factory_py2_py3.py
new file mode 100644
index 0000000000000000000000000000000000000000..7fde2a8728c10c01f6679b43eba80360d282cdc3
--- /dev/null
+++ b/pool/shard006/Python/0057775_test_delegated_factory_py2_py3.py
@@ -0,0 +1,25 @@
+"""DelegatedFactory provider tests."""
+
+from dependency_injector import providers
+
+from .common import Example
+
+
+def test_inheritance():
+ assert isinstance(providers.DelegatedFactory(object), providers.Factory)
+
+
+def test_is_provider():
+ assert providers.is_provider(providers.DelegatedFactory(object)) is True
+
+
+def test_is_delegated_provider():
+ assert providers.is_delegated(providers.DelegatedFactory(object)) is True
+
+
+def test_repr():
+ provider = providers.DelegatedFactory(Example)
+ assert repr(provider) == (
+ "".format(repr(Example), hex(id(provider)))
+ )
diff --git a/pool/shard006/Python/0057776_109-convert-sorted-list-to-binary-search-tree.py b/pool/shard006/Python/0057776_109-convert-sorted-list-to-binary-search-tree.py
new file mode 100644
index 0000000000000000000000000000000000000000..cc9341364c5550f91b1a9cf1b9ccf37675e7eff3
--- /dev/null
+++ b/pool/shard006/Python/0057776_109-convert-sorted-list-to-binary-search-tree.py
@@ -0,0 +1,41 @@
+# Definition for singly-linked list.
+class ListNode(object):
+ def __init__(self, x):
+ self.val = x
+ self.next = None
+
+# Definition for a binary tree node.
+class TreeNode(object):
+ def __init__(self, x):
+ self.val = x
+ self.left = None
+ self.right = None
+
+class Solution(object):
+ def sortedListToBST(self, head):
+ """
+ :type head: ListNode
+ :rtype: TreeNode
+ """
+ arr = []
+
+ while head:
+ arr.append(head.val)
+ head = head.next
+
+
+ def helper(begin, end):
+ if begin > end:
+ return None
+
+ middle = (begin+end) / 2
+
+ node = TreeNode(arr[middle])
+ node.left = helper(begin, middle-1)
+ node.right = helper(middle+1, end)
+
+ return node
+
+ return helper(0, len(arr)-1)
+
+
diff --git a/pool/shard006/Python/0057784_smlchecker.py b/pool/shard006/Python/0057784_smlchecker.py
new file mode 100644
index 0000000000000000000000000000000000000000..a8803dcf254687233ef594e90acecd661dc3f07c
--- /dev/null
+++ b/pool/shard006/Python/0057784_smlchecker.py
@@ -0,0 +1,62 @@
+import hashlib
+import logging
+
+from dns import resolver
+
+log = logging.getLogger(__name__)
+
+
+def check(peppoid):
+ '''
+ Checks whether the given PEPPOL identifier exists in the SML by doing an DNS lookup
+ returns True if so otherwise False
+
+ :param peppoid: a PEPPOL identifier
+ :return: True or False
+ '''
+
+ if smpaddress(peppoid) is None:
+ return False
+ else:
+ return True
+
+
+def smpaddress(peppoid):
+ '''
+ Checks whether the given participant id exists in the SML by doing a DNS lookup
+ returns None or the DNS A-record (ipaddress)
+
+ :param peppolid: a PEPPOL identifier
+ :return: str or None
+ '''
+
+ h = hostname(peppoid)
+ log.debug('Hostname to resolve %s', h)
+ # Look up the hostname in the SML; if the lookup succeeds, we know
+ # there is an SMP for this organization, and we are done.
+ # Normally, the calling application would then contact the SMP for
+ # endpoint details.
+ r = resolver.Resolver()
+ try:
+ answers = r.query(h, "A")
+ except resolver.NXDOMAIN:
+ log.error("Got NXDOMAIN for %s", h)
+ return None
+
+ for rdata in answers:
+ log.debug('DNS A record found: %'
+ 's', rdata)
+
+ return str(answers[0])
+
+
+def hostname(peppoid):
+ '''
+ Calculates the hostname for a specific PEPPOL identifier
+ :param peppoid:
+ :return:
+ '''
+ # Calculate the hash of the ID according to the SML specification
+ # peppol needs the organisation to be lower case
+ hash = hashlib.md5(str.lower(peppoid).encode('UTF-8')).hexdigest()
+ return "b-" + hash + ".iso6523-actorid-upis.edelivery.tech.ec.europa.eu"
diff --git a/pool/shard006/Python/0057786_test_comment02.py b/pool/shard006/Python/0057786_test_comment02.py
new file mode 100644
index 0000000000000000000000000000000000000000..e1660db8a25ae1b968612d3da8697ec607b0a3db
--- /dev/null
+++ b/pool/shard006/Python/0057786_test_comment02.py
@@ -0,0 +1,39 @@
+###############################################################################
+#
+# Tests for XlsxWriter.
+#
+# SPDX-License-Identifier: BSD-2-Clause
+# Copyright (c), 2013-2022, John McNamara, jmcnamara@cpan.org
+#
+
+from ..excel_comparison_test import ExcelComparisonTest
+from ...workbook import Workbook
+
+
+class TestCompareXLSXFiles(ExcelComparisonTest):
+ """
+ Test file created by XlsxWriter against a file created by Excel.
+
+ """
+
+ def setUp(self):
+
+ self.set_filename('comment02.xlsx')
+
+ def test_create_file(self):
+ """Test the creation of a simple XlsxWriter file with comments."""
+
+ workbook = Workbook(self.got_filename)
+
+ worksheet = workbook.add_worksheet()
+
+ worksheet.write('A1', 'Foo')
+ worksheet.write_comment('B2', 'Some text')
+ worksheet.write_comment('D17', 'More text')
+
+ # Set the author to match the target XLSX file.
+ worksheet.set_comments_author('John')
+
+ workbook.close()
+
+ self.assertExcelEqual()
diff --git a/pool/shard006/Python/0057787_scheduler.py b/pool/shard006/Python/0057787_scheduler.py
new file mode 100644
index 0000000000000000000000000000000000000000..b470bc489b3f2f9552415f4694e88a7ff9c69246
--- /dev/null
+++ b/pool/shard006/Python/0057787_scheduler.py
@@ -0,0 +1,51 @@
+# coding: utf8
+import time
+from gluon.scheduler import Scheduler
+
+def demo1(*args,**vars):
+ print 'you passed args=%s and vars=%s' % (args, vars)
+ return args[0]
+
+def demo2():
+ 1/0
+
+def demo3():
+ time.sleep(15)
+ print 1/0
+ return None
+
+def demo4():
+ time.sleep(15)
+ print "I'm printing something"
+ return dict(a=1, b=2)
+
+def demo5():
+ time.sleep(15)
+ print "I'm printing something"
+ rtn = dict(a=1, b=2)
+
+def demo6():
+ time.sleep(5)
+ print '50%'
+ time.sleep(5)
+ print '!clear!100%'
+ return 1
+
+import random
+def demo7():
+ time.sleep(random.randint(1,15))
+ print W2P_TASK, request.now
+ return W2P_TASK.id, W2P_TASK.uuid
+
+scheduler = Scheduler(db)
+
+##or, alternatively :
+#scheduler = Scheduler(db,
+# dict(
+# demo1=demo1,
+# demo2=demo2,
+# demo3=demo3,
+# demo4=demo4,
+# foo=demo5
+# )
+# )
diff --git a/pool/shard006/Python/0057789_randomWalks-segment4.py b/pool/shard006/Python/0057789_randomWalks-segment4.py
new file mode 100644
index 0000000000000000000000000000000000000000..d8b3b3e0ba1055208ad3ea2b13e6412e97959963
--- /dev/null
+++ b/pool/shard006/Python/0057789_randomWalks-segment4.py
@@ -0,0 +1,203 @@
+
+
+class Location(object):
+
+ def __init__(self, x, y):
+ """x and y are floats"""
+ self.x = x
+ self.y = y
+
+ def move(self, deltaX, deltaY):
+ """deltaX and deltaY are floats"""
+ return Location(self.x + deltaX, self.y + deltaY)
+
+ def getX(self):
+ return self.x
+
+ def getY(self):
+ return self.y
+
+ def distFrom(self, other):
+ ox = other.x
+ oy = other.y
+ xDist = self.x - ox
+ yDist = self.y - oy
+ return (xDist**2 + yDist**2)**0.5
+
+ def __str__(self):
+ return '<' + str(self.x) + ', ' + str(self.y) + '>'
+
+
+
+
+
+class Field(object):
+
+ def __init__(self):
+ self.drunks = {}
+
+ def addDrunk(self, drunk, loc):
+ if drunk in self.drunks:
+ raise ValueError('Duplicate drunk')
+ else:
+ self.drunks[drunk] = loc
+
+ def moveDrunk(self, drunk):
+ if not drunk in self.drunks:
+ raise ValueError('Drunk not in field')
+ xDist, yDist = drunk.takeStep()
+ currentLocation = self.drunks[drunk]
+ #use move method of Location to get new location
+ self.drunks[drunk] = currentLocation.move(xDist, yDist)
+
+ def getLoc(self, drunk):
+ if not drunk in self.drunks:
+ raise ValueError('Drunk not in field')
+ return self.drunks[drunk]
+
+
+
+
+
+
+
+
+
+
+import random
+
+
+class Drunk(object):
+ def __init__(self, name):
+ self.name = name
+ def __str__(self):
+ return 'This drunk is named ' + self.name
+
+class UsualDrunk(Drunk):
+ def takeStep(self):
+ stepChoices =\
+ [(0.0,1.0), (0.0,-1.0), (1.0, 0.0), (-1.0, 0.0)]
+ return random.choice(stepChoices)
+
+
+def walk(f, d, numSteps):
+ start = f.getLoc(d)
+ for s in range(numSteps):
+ f.moveDrunk(d)
+ return(start.distFrom(f.getLoc(d)))
+
+
+
+## import pylab
+
+## #set line width
+## pylab.rcParams['lines.linewidth'] = 6
+## #set font size for titles
+## pylab.rcParams['axes.titlesize'] = 20
+## #set font size for labels on axes
+## pylab.rcParams['axes.labelsize'] = 20
+## #set size of numbers on x-axis
+## pylab.rcParams['xtick.major.size'] = 5
+## #set size of numbers on y-axis
+## pylab.rcParams['ytick.major.size'] = 5
+## #set size of markers
+## pylab.rcParams['lines.markersize'] = 10
+
+
+###Start code added in Segment 4
+
+
+
+def drunkTestP(numTrials = 50):
+ stepsTaken = [10, 100, 1000, 10000]
+ meanDistances = []
+ for numSteps in stepsTaken:
+ distances = simWalks(numSteps, numTrials)
+ meanDistances.append(sum(distances)/len(distances))
+ pylab.plot(stepsTaken, meanDistances)
+ pylab.title('Mean Distance from Origin')
+ pylab.xlabel('Steps Taken')
+ pylab.ylabel('Steps from Origin')
+ pylab.show()
+
+
+
+
+
+def drunkTestP1(numTrials = 50):
+ stepsTaken = [10, 100, 1000, 10000]
+ meanDistances = []
+ squareRootOfSteps = []
+ for numSteps in stepsTaken:
+ distances = simWalks(numSteps, numTrials)
+ meanDistances.append(sum(distances)/len(distances))
+ squareRootOfSteps.append(numSteps**0.5)
+ pylab.plot(stepsTaken, meanDistances, 'b-',
+ label = 'Mean distance')
+ pylab.plot(stepsTaken, squareRootOfSteps, 'g-.',
+ label = 'Square root of steps')
+ pylab.title('Mean Distance from Origin')
+ pylab.xlabel('Steps Taken')
+ pylab.ylabel('Steps from Origin')
+ pylab.legend()
+ pylab.show()
+
+
+
+
+
+
+
+#Look at different kinds of drunks
+
+class UsualDrunk(Drunk):
+ def takeStep(self):
+ stepChoices =\
+ [(0.0,1.0), (0.0,-1.0), (1.0, 0.0), (-1.0, 0.0)]
+ return random.choice(stepChoices)
+
+class ColdDrunk(Drunk):
+ def takeStep(self):
+ stepChoices =\
+ [(0.0,0.95), (0.0,-1.0), (1.0, 0.0), (-1.0, 0.0)]
+ return random.choice(stepChoices)
+
+class EDrunk(Drunk):
+ def takeStep(self):
+ deltaX = random.random()
+ if random.random() < 0.5:
+ deltaX = -deltaX
+ deltaY = random.random()
+ if random.random() < 0.5:
+ deltaY = -deltaY
+ return (deltaX, deltaY)
+
+# New version of simWalks
+
+def simWalks(numSteps, numTrials, dClass):
+ homer = dClass('Homer')
+ origin = Location(0, 0)
+ distances = []
+ for t in range(numTrials):
+ f = Field()
+ f.addDrunk(homer, origin)
+ distances.append(walk(f, homer, numSteps))
+ return distances
+
+
+def drunkTestP(numTrials = 50):
+ stepsTaken = [10, 100, 1000, 10000]
+ for dClass in (UsualDrunk, ColdDrunk, EDrunk):
+ meanDistances = []
+ for numSteps in stepsTaken:
+ distances = simWalks(numSteps, numTrials, dClass)
+ meanDistances.append(sum(distances)/len(distances))
+ pylab.plot(stepsTaken, meanDistances,
+ label = dClass.__name__)
+ pylab.title('Mean Distance from Origin')
+ pylab.xlabel('Steps Taken')
+ pylab.ylabel('Steps from Origin')
+ pylab.legend(loc = 'upper left')
+ pylab.show()
+
+
diff --git a/pool/shard006/Python/0057790_change.py b/pool/shard006/Python/0057790_change.py
new file mode 100644
index 0000000000000000000000000000000000000000..624d981c879a7e8c8e70816bd12acee0f4083a9a
--- /dev/null
+++ b/pool/shard006/Python/0057790_change.py
@@ -0,0 +1,64 @@
+# encoding: utf-8
+"""
+change.py
+
+Created by Thomas Mangin on 2009-11-05.
+Copyright (c) 2009-2015 Exa Networks. All rights reserved.
+"""
+
+
+class Source (object):
+ UNSET = 0
+ CONFIGURATION = 1
+ API = 2
+ NETWORK = 3
+
+
+class Change (object):
+ SOURCE = Source.UNSET
+
+ __slots__ = ['nlri','attributes']
+
+ def __init__ (self, nlri, attributes):
+ self.nlri = nlri
+ self.attributes = attributes
+
+ def index (self):
+ return '%02x%02x' % self.nlri.family() + self.nlri.index()
+
+ def __eq__ (self, other):
+ return self.nlri == other.nlri and self.attributes == other.attributes
+
+ def __ne__ (self, other):
+ return self.nlri != other.nlri or self.attributes != other.attributes
+
+ def __lt__ (self, other):
+ raise RuntimeError('comparing Change for ordering does not make sense')
+
+ def __le__ (self, other):
+ raise RuntimeError('comparing Change for ordering does not make sense')
+
+ def __gt__ (self, other):
+ raise RuntimeError('comparing Change for ordering does not make sense')
+
+ def __ge__ (self, other):
+ raise RuntimeError('comparing Change for ordering does not make sense')
+
+ def extensive (self):
+ # If you change this you must change as well extensive in Update
+ return "%s%s" % (str(self.nlri),str(self.attributes))
+
+ def __str__ (self):
+ return self.extensive()
+
+
+class ConfigurationChange (Change):
+ SOURCE = Source.CONFIGURATION
+
+
+class APIChange (Change):
+ SOURCE = Source.API
+
+
+class NetworkChange (Change):
+ SOURCE = Source.NETWORK
diff --git a/pool/shard006/Python/0057791_0002_populate_usersettings.py b/pool/shard006/Python/0057791_0002_populate_usersettings.py
new file mode 100644
index 0000000000000000000000000000000000000000..b35bfc80b90cd81b9bf560adcf3f15c2f099dd0f
--- /dev/null
+++ b/pool/shard006/Python/0057791_0002_populate_usersettings.py
@@ -0,0 +1,51 @@
+# -*- coding: utf-8 -*-
+from django.contrib.auth import get_user_model
+from django.db import models, migrations
+
+from helpdesk.settings import DEFAULT_USER_SETTINGS
+
+
+def pickle_settings(data):
+ """Pickling as defined at migration's creation time"""
+ try:
+ import pickle
+ except ImportError:
+ import cPickle as pickle
+ from helpdesk.query import b64encode
+ return b64encode(pickle.dumps(data))
+
+
+# https://docs.djangoproject.com/en/1.7/topics/migrations/#data-migrations
+def populate_usersettings(apps, schema_editor):
+ """Create a UserSettings entry for each existing user.
+ This will only happen once (at install time, or at upgrade)
+ when the UserSettings model doesn't already exist."""
+
+ _User = get_user_model()
+ User = apps.get_model(_User._meta.app_label, _User._meta.model_name)
+
+ # Import historical version of models
+ UserSettings = apps.get_model("helpdesk", "UserSettings")
+
+ settings_pickled = pickle_settings(DEFAULT_USER_SETTINGS)
+
+ for u in User.objects.all():
+ try:
+ UserSettings.objects.get(user=u)
+ except UserSettings.DoesNotExist:
+ UserSettings.objects.create(user=u, settings_pickled=settings_pickled)
+
+
+noop = lambda *args, **kwargs: None
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ('helpdesk', '0001_initial'),
+ ]
+
+ operations = [
+ migrations.RunPython(populate_usersettings, reverse_code=noop),
+ ]
+
+
diff --git a/pool/shard006/Python/0057793_letterCombinations.py b/pool/shard006/Python/0057793_letterCombinations.py
new file mode 100644
index 0000000000000000000000000000000000000000..b11ba01f8d0b10a534e319f57ea917738ea5206a
--- /dev/null
+++ b/pool/shard006/Python/0057793_letterCombinations.py
@@ -0,0 +1,32 @@
+class Solution:
+ # @return a list of strings, [s1, s2]
+ def letterCombinations(self, digits):
+ if len(digits) <= 0:
+ return []
+ map = {
+ "0": (),
+ "1": (),
+ "2": ("a", "b", "c"),
+ "3": ("d", "e", "f"),
+ "4": ("g", "h", "i"),
+ "5": ("j", "k", "l"),
+ "6": ("m", "n", "o"),
+ "7": ("p", "q", "r", "s"),
+ "8": ("t", "u", "v"),
+ "9": ("w", "x", "y", "z")
+ }
+ result1 = [ "" ]
+ result2 = [ ]
+ for ch in digits:
+ list = map[ch]
+ if 0 == len(list):
+ continue
+ for str in result1:
+ for suffix in list:
+ result2.append(str + suffix)
+ result1 = result2
+ result2 = [ ]
+ return result1
+
+a = Solution()
+print a.letterCombinations('2')
\ No newline at end of file
diff --git a/pool/shard006/Python/0057803_urls.py b/pool/shard006/Python/0057803_urls.py
new file mode 100644
index 0000000000000000000000000000000000000000..1f893cdd8dbfd7358630edbae44e7e1dbfdf54ff
--- /dev/null
+++ b/pool/shard006/Python/0057803_urls.py
@@ -0,0 +1,16 @@
+
+from django.conf.urls import patterns, include, url
+
+urlpatterns = patterns('webhost.views',
+ url(r'^$', 'home', name='home'),
+ url(r'^about/$', 'about', name='about'),
+ url(r'^policy/$', 'pp', name='pp'),
+ url(r'^TOS/$', 'TOS', name='TOS'),
+ url(r'^contact/$', 'contact', name='contact'),
+ url(r'^copyright/$', 'copyright', name='copyright'),
+ url(r'^blog/$', 'blog', name='blog'),
+ url(r'^faq/$', 'faq', name='faq'),
+ url(r'^pk/$', 'pk', name='pk'),
+ #url(r'^so/$', 'my_view', name='my_view'),
+ url(r'^company/$', 'company', name='company'),
+)
diff --git a/pool/shard006/Python/0057806_signature_def_utils_impl.py b/pool/shard006/Python/0057806_signature_def_utils_impl.py
new file mode 100644
index 0000000000000000000000000000000000000000..7a3fb16825d8a45c4f1681fa716d45ba84853a22
--- /dev/null
+++ b/pool/shard006/Python/0057806_signature_def_utils_impl.py
@@ -0,0 +1,228 @@
+# 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 express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+# ==============================================================================
+"""SignatureDef utility functions implementation."""
+
+from __future__ import absolute_import
+from __future__ import division
+from __future__ import print_function
+
+from tensorflow.core.protobuf import meta_graph_pb2
+from tensorflow.python.framework import dtypes
+from tensorflow.python.framework import tensor_shape
+from tensorflow.python.saved_model import signature_constants
+from tensorflow.python.saved_model import utils
+
+
+def build_signature_def(inputs=None, outputs=None, method_name=None):
+ """Utility function to build a SignatureDef protocol buffer.
+
+ Args:
+ inputs: Inputs of the SignatureDef defined as a proto map of string to
+ tensor info.
+ outputs: Outputs of the SignatureDef defined as a proto map of string to
+ tensor info.
+ method_name: Method name of the SignatureDef as a string.
+
+ Returns:
+ A SignatureDef protocol buffer constructed based on the supplied arguments.
+ """
+ signature_def = meta_graph_pb2.SignatureDef()
+ if inputs is not None:
+ for item in inputs:
+ signature_def.inputs[item].CopyFrom(inputs[item])
+ if outputs is not None:
+ for item in outputs:
+ signature_def.outputs[item].CopyFrom(outputs[item])
+ if method_name is not None:
+ signature_def.method_name = method_name
+ return signature_def
+
+
+def regression_signature_def(examples, predictions):
+ """Creates regression signature from given examples and predictions.
+
+ Args:
+ examples: `Tensor`.
+ predictions: `Tensor`.
+
+ Returns:
+ A regression-flavored signature_def.
+
+ Raises:
+ ValueError: If examples is `None`.
+ """
+ if examples is None:
+ raise ValueError('examples cannot be None for regression.')
+ if predictions is None:
+ raise ValueError('predictions cannot be None for regression.')
+
+ input_tensor_info = utils.build_tensor_info(examples)
+ signature_inputs = {signature_constants.REGRESS_INPUTS: input_tensor_info}
+
+ output_tensor_info = utils.build_tensor_info(predictions)
+ signature_outputs = {signature_constants.REGRESS_OUTPUTS: output_tensor_info}
+ signature_def = build_signature_def(
+ signature_inputs, signature_outputs,
+ signature_constants.REGRESS_METHOD_NAME)
+
+ return signature_def
+
+
+def classification_signature_def(examples, classes, scores):
+ """Creates classification signature from given examples and predictions.
+
+ Args:
+ examples: `Tensor`.
+ classes: `Tensor`.
+ scores: `Tensor`.
+
+ Returns:
+ A classification-flavored signature_def.
+
+ Raises:
+ ValueError: If examples is `None`.
+ """
+ if examples is None:
+ raise ValueError('examples cannot be None for classification.')
+ if classes is None and scores is None:
+ raise ValueError('classes and scores cannot both be None for '
+ 'classification.')
+
+ input_tensor_info = utils.build_tensor_info(examples)
+ signature_inputs = {signature_constants.CLASSIFY_INPUTS: input_tensor_info}
+
+ signature_outputs = {}
+ if classes is not None:
+ classes_tensor_info = utils.build_tensor_info(classes)
+ signature_outputs[signature_constants.CLASSIFY_OUTPUT_CLASSES] = (
+ classes_tensor_info)
+ if scores is not None:
+ scores_tensor_info = utils.build_tensor_info(scores)
+ signature_outputs[signature_constants.CLASSIFY_OUTPUT_SCORES] = (
+ scores_tensor_info)
+
+ signature_def = build_signature_def(
+ signature_inputs, signature_outputs,
+ signature_constants.CLASSIFY_METHOD_NAME)
+
+ return signature_def
+
+
+def predict_signature_def(inputs, outputs):
+ """Creates prediction signature from given inputs and outputs.
+
+ Args:
+ inputs: dict of string to `Tensor`.
+ outputs: dict of string to `Tensor`.
+
+ Returns:
+ A prediction-flavored signature_def.
+
+ Raises:
+ ValueError: If inputs or outputs is `None`.
+ """
+ if inputs is None or not inputs:
+ raise ValueError('inputs cannot be None or empty for prediction.')
+ if outputs is None:
+ raise ValueError('outputs cannot be None or empty for prediction.')
+
+ signature_inputs = {key: utils.build_tensor_info(tensor)
+ for key, tensor in inputs.items()}
+ signature_outputs = {key: utils.build_tensor_info(tensor)
+ for key, tensor in outputs.items()}
+
+ signature_def = build_signature_def(
+ signature_inputs, signature_outputs,
+ signature_constants.PREDICT_METHOD_NAME)
+
+ return signature_def
+
+
+def _get_shapes_from_tensor_info_dict(tensor_info_dict):
+ """Returns a map of keys to TensorShape objects.
+
+ Args:
+ tensor_info_dict: map with TensorInfo proto as values.
+
+ Returns:
+ Map with corresponding TensorShape objects as values.
+ """
+ return {
+ key: tensor_shape.TensorShape(tensor_info.tensor_shape)
+ for key, tensor_info in tensor_info_dict.items()
+ }
+
+
+def _get_types_from_tensor_info_dict(tensor_info_dict):
+ """Returns a map of keys to DType objects.
+
+ Args:
+ tensor_info_dict: map with TensorInfo proto as values.
+
+ Returns:
+ Map with corresponding DType objects as values.
+ """
+ return {
+ key: dtypes.DType(tensor_info.dtype)
+ for key, tensor_info in tensor_info_dict.items()
+ }
+
+
+def get_signature_def_input_shapes(signature):
+ """Returns map of parameter names to their shapes.
+
+ Args:
+ signature: SignatureDef proto.
+
+ Returns:
+ Map from string to TensorShape objects.
+ """
+ return _get_shapes_from_tensor_info_dict(signature.inputs)
+
+
+def get_signature_def_input_types(signature):
+ """Returns map of output names to their types.
+
+ Args:
+ signature: SignatureDef proto.
+
+ Returns:
+ Map from string to DType objects.
+ """
+ return _get_types_from_tensor_info_dict(signature.inputs)
+
+
+def get_signature_def_output_shapes(signature):
+ """Returns map of output names to their shapes.
+
+ Args:
+ signature: SignatureDef proto.
+
+ Returns:
+ Map from string to TensorShape objects.
+ """
+ return _get_shapes_from_tensor_info_dict(signature.outputs)
+
+
+def get_signature_def_output_types(signature):
+ """Returns map of output names to their types.
+
+ Args:
+ signature: SignatureDef proto.
+
+ Returns:
+ Map from string to DType objects.
+ """
+ return _get_types_from_tensor_info_dict(signature.outputs)
diff --git a/pool/shard006/Python/0057807_gaussfit.py b/pool/shard006/Python/0057807_gaussfit.py
new file mode 100644
index 0000000000000000000000000000000000000000..d27f2d3e4876009e362bae40bfc049fff7d30aef
--- /dev/null
+++ b/pool/shard006/Python/0057807_gaussfit.py
@@ -0,0 +1,166 @@
+import os as _os
+on_rtd = _os.environ.get('READTHEDOCS', None) == 'True'
+if not on_rtd:
+ import numpy as _np
+ import matplotlib.pyplot as _plt
+
+from .curve_fit_unscaled import curve_fit_unscaled as _curve_fit_unscaled
+from ..matplotlib.figure import figure as _figure
+import logging
+logger = logging.getLogger(__name__)
+
+
+class GaussResults(object):
+ """
+ Fits a gaussian to a curve specified by pairs *x* and *y*, with error on *y* of *sigma_y*.
+
+ * *plot*: Determines whether the plot is shown
+ * *p0*: Initial guess given by amplitude *amp*, mean *mu*, and standard deviation *rms*, in the form of:
+
+ * :code:`[amp, mu, rms**2]` if *variance_bool* is true
+ * :code:`[amp, mu, rms]` if *variance_bool* is false
+
+ * *background_bool*: If true, uses a background term in the fit, with initial guess *bg*
+
+ Returns full statistical results in the form of an instance of class :class:`GaussResults `.
+ """
+ def __init__(self, x, y, sigma_y=None, p0=None, variance=False, background=False):
+ # ======================================
+ # Store things
+ # ======================================
+ self._x = x.flatten()
+ self._y = y.flatten()
+ self._sigma_y = sigma_y
+ self._p0 = p0
+ self._variance = variance
+ self._background = background
+
+ # ======================================
+ # Perform curve fit
+ # ======================================
+ self._popt, self._pcov, self._chisq_red = _curve_fit_unscaled(self.func, self.x, self.y, sigma=self.sigma_y, p0=self.p0)
+
+ # ======================================
+ # Keep sigma positive
+ # ======================================
+ self._popt[2] = _np.abs(self._popt[2])
+
+ @property
+ def popt(self):
+ """
+ The fit parameters for the fit function.
+ """
+ return self._popt
+
+ @property
+ def pcov(self):
+ """
+ The covariance for the fit parameters.
+ """
+ return self._pcov
+
+ @property
+ def chisq_red(self):
+ """
+ The reduced chi square.
+ """
+ return self._chisq_red
+
+ @property
+ def x(self):
+ return self._x
+
+ @property
+ def y(self):
+ return self._y
+
+ @property
+ def sigma_y(self):
+ return self._sigma_y
+
+ @property
+ def variance(self):
+ return self._variance
+
+ @property
+ def background(self):
+ return self._background
+
+ @property
+ def func(self):
+ # ======================================
+ # Determine whether to use the variance or std dev form
+ # in the gaussian equation
+ # ======================================
+ if self.variance:
+ if self.background:
+ return _gaussvar
+ else:
+ return _gaussvar_nobg
+ else:
+ if self.background:
+ return _gauss
+ else:
+ return _gauss_nobg
+
+ @property
+ def use_error(self):
+ return ( self.sigma_y is not None )
+
+ @property
+ def p0(self):
+ # ======================================
+ # Determine initial guesses
+ # ======================================
+ if (self._p0 is None):
+ amp = max(self.y)
+ mu = sum(self.x * self.y) / sum(self.y)
+ rms = _np.sqrt(sum((self.x-mu)**2 * self.y) / sum(self.y))
+
+ # ======================================
+ # Modify initial guess for variance
+ # ======================================
+ if self.variance:
+ self._p0 = _np.array((amp, mu, rms**2))
+ else:
+ self._p0 = _np.array((amp, mu, rms))
+
+ # ======================================
+ # Modify initial guess for background
+ # ======================================
+ if self.background:
+ self._p0 = _np.append(self._p0, min(self.y))
+
+ return self._p0
+
+ def plot(self):
+ xmin = min(self.x)
+ xmax = max(self.x)
+ x_fit = _np.linspace(xmin, xmax, 1000)
+ y_fit = self.func(x_fit, *self.popt)
+ _figure('MYTOOLS: Gauss Fit Routine')
+ if self.use_error:
+ sigma_y = self.sigma_y.flatten()
+ _plt.errorbar(self.x, self.y, yerr=sigma_y, fmt='o-')
+ _plt.plot(x_fit, y_fit)
+ else:
+ _plt.plot(self.x, self.y, 'o-', x_fit, y_fit)
+
+
+def _gauss(x, amp, mu, sigma, bg=0):
+ # print 'Sigma is {}.'.format(sigma)
+ return _np.abs(amp) * _np.exp( -(x - mu)**2 / (2 * sigma**2)) + bg
+ # return _np.abs(amp) * _np.exp(-(x - mu)**2 / (2 * sigma**2))
+
+
+def _gauss_nobg(x, amp, mu, sigma):
+ return _gauss(x, amp, mu, sigma)
+
+
+def _gaussvar(x, amp, mu, variance, bg=0):
+ return _np.abs(amp) * _np.exp(-(x - mu)**2 / (2 * variance)) + bg
+ # return _np.abs(amp) * _np.exp(-(x - mu)**2 / (2 * variance))
+
+
+def _gaussvar_nobg(x, amp, mu, variance):
+ return _gaussvar(x, amp, mu, variance)
diff --git a/pool/shard006/Python/0057811_logger.py b/pool/shard006/Python/0057811_logger.py
new file mode 100644
index 0000000000000000000000000000000000000000..97c076d9c34a96acdda53fa768fe497bd01601af
--- /dev/null
+++ b/pool/shard006/Python/0057811_logger.py
@@ -0,0 +1,119 @@
+'''
+Created on Aug 23, 2013
+
+@author: Brad
+'''
+import logging.handlers
+import os
+
+class Logger(object):
+ '''
+ This is a wrapper class for logging.
+
+ Levels When it is used
+ ------ ---------------
+ DEBUG Detailed information, typically of interest only when
+ diagnosing problems.
+ INFO Confirmation that things are working as expected.
+ WARNING An indication that something unexpected happened,
+ or indicative of some problem in the near future
+ (e.g. 'disk space low'). The software is still
+ working as expected.
+ ERROR Due to a more serious problem, the software has not
+ been able to perform some function.
+ CRITICAL A serious error, indicating that the program itself
+ may be unable to continue running.
+
+ '''
+
+ def __init__(self):
+ '''
+ Constructor
+ '''
+ # Default values.
+ self.LOG_DIR = './log/'
+ self.LOG_FILENAME = 'logging_rotatingfile_example.out'
+ self.level = logging.DEBUG
+ self.maxBytes = 1000000
+ self.backupCount = 4
+
+
+ def createLogger(self, name='MyLogger'):
+ '''
+ This method creates a logger using the default values.
+
+ Change default values before calling this method if you need
+ something different, such as a different logging directory.
+
+ Ex.
+ log = Logger()
+ log.LOG_DIR = '/tmp/'
+ log.createLogger(name='TestLogger')
+ '''
+
+ self.setLogDirAndName()
+
+ # Set up a specific logger with our desired output level.
+ my_logger = logging.getLogger(name)
+ my_logger.setLevel(self.level)
+
+ # Create file handler which logs even debug messages.
+ handler = logging.handlers.RotatingFileHandler(
+ self.LOG_DIR_AND_NAME, maxBytes=self.maxBytes, backupCount=self.backupCount)
+
+ # Create formatter.
+ # 2015-04-04 17:29:25,465 -
+ # DEBUG -
+ # /Users/bradfulton/GitRepos/RaspiCamPiWrap/RaspiCamPyWrap/test/utils/test_logger.py -
+ # test_format_VISUALLY -
+ # 66 -
+ # debug message
+ my_format = '%(asctime)s - %(levelname)s - %(pathname)s - %(funcName)s - %(lineno)d - %(message)s'
+ formatter = logging.Formatter(my_format)
+ # And add it to the handler.
+ handler.setFormatter(formatter)
+
+ # Add the log message handler to the logger.
+ my_logger.addHandler(handler)
+
+ return my_logger
+
+
+ def setLogDirAndName(self):
+ '''
+ This method creates the logging directory if needed and sets
+ the LOG_DIR_AND_NAME variable using the directory and file names.
+ '''
+ self.createLogDir()
+ self.LOG_DIR_AND_NAME = self.LOG_DIR + self.LOG_FILENAME
+
+
+ def createLogDir(self):
+ '''
+ This method creates the logging directory if it doesn't already exist.
+ If the directory cannot be created, then a local log directory will be
+ created.
+ '''
+ directory = self.LOG_DIR
+ try:
+ if not os.path.exists(directory):
+ os.makedirs(directory)
+ except Exception:
+ print 'Could not create: ' + os.path.realpath(self.LOG_DIR)
+ self.createDefaultLogDir()
+
+
+ def createDefaultLogDir(self):
+ '''
+ This method creates the default logging directory (./log/).
+ '''
+ self.LOG_DIR = './log/'
+ directory = self.LOG_DIR
+ try:
+ if not os.path.exists(directory):
+ os.makedirs(directory)
+
+ print 'Created: ' + os.path.realpath(self.LOG_DIR)
+ except Exception as e:
+ print e
+
diff --git a/pool/shard006/Python/0057813_energy_logger.py b/pool/shard006/Python/0057813_energy_logger.py
new file mode 100644
index 0000000000000000000000000000000000000000..68bc501663640d520375f08544fb9f4655baa31f
--- /dev/null
+++ b/pool/shard006/Python/0057813_energy_logger.py
@@ -0,0 +1,61 @@
+#!/usr/bin/python3.2
+
+'''
+Created on 05.06.2014
+
+@author: christoph
+'''
+import os
+from twill.commands import *
+import time as time
+import urllib2
+
+# Energenie Password
+password = ""
+
+# Energenie IP Address
+ip_addr = ""
+
+login_url= "http://%s/login.html" % ip_addr
+logger_url = "http://%s/energenie.html" % ip_addr
+
+def login():
+
+ go(login_url)
+ fv("1", "pw", password)
+ submit("0")
+
+
+def get_data():
+ log_file = open("energy.log", "a")
+ aResp = urllib2.urlopen(logger_url);
+ energy_data_log_webpage = aResp.read();
+
+ log_vars = energy_data_log_webpage.split("var")
+
+ for i, v in enumerate(log_vars):
+ v1 = v.split("=")
+ v2 = v1[1].split(";")
+# print v
+ if(i==10):
+ log_voltage = float(float(v2[0])/10)
+ elif(i==11):
+ log_current = float(float(v2[0])/100)
+ elif(i==12):
+ log_power = float(float(v2[0])/466)
+ elif(i==13):
+ log_energy = float(float(v2[0])/25600)
+
+ ttime = time.localtime()
+ log_string = "%s.%s.%s-%s:%s:%s;%sV;%sA;%sW;%skWh;\n" %(ttime[2],ttime[1],ttime[0],ttime[3],ttime[4],ttime[5],log_voltage,log_current,log_power,log_energy)
+# print log_string
+ log_file.write(log_string)
+ log_file.close()
+
+if __name__ == "__main__":
+ login()
+ while(1):
+ time.sleep(10)
+# login()
+ get_data()
+
diff --git a/pool/shard006/Python/0057815_forms.py b/pool/shard006/Python/0057815_forms.py
new file mode 100644
index 0000000000000000000000000000000000000000..67c785530e1c6186f5371bd8f9522f9470115883
--- /dev/null
+++ b/pool/shard006/Python/0057815_forms.py
@@ -0,0 +1,107 @@
+from django import forms
+from django.apps import apps
+from django.conf import settings
+from django.utils.translation import gettext as _
+
+from planb.storage import storage_pools
+
+from .models import Fileset, HostGroup
+
+
+class HostGroupAdminForm(forms.ModelForm):
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+ self.fields['blacklist_hours'].help_text = _(
+ 'Specify hours during which backups are disabled using notation '
+ 'h,h-h or none to disable blacklist hours. When left empty the '
+ 'system blacklist hours {} are used.'
+ ).format(settings.PLANB_BLACKLIST_HOURS)
+ self.fields['retention'].help_text = _(
+ 'The backup retention period using notation separated '
+ 'by comma: 1y,6m,3w,15d. When left empty the system retention '
+ '{} is used.').format(settings.PLANB_RETENTION)
+
+ class Meta:
+ model = HostGroup
+ fields = '__all__'
+
+
+class FilesetAdminForm(forms.ModelForm):
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+ if self.instance.pk:
+ blacklist_hours = self.instance.hostgroup.get_blacklist_hours()
+ retention = self.instance.hostgroup.get_retention()
+ else:
+ blacklist_hours = settings.PLANB_BLACKLIST_HOURS
+ retention = settings.PLANB_RETENTION
+ self.fields['blacklist_hours'].help_text = _(
+ 'Specify hours during which backups are disabled using notation '
+ 'h,h-h or none to disable blacklist hours. When left empty the '
+ 'hostgroup blacklist hours {} are used.'
+ ).format(blacklist_hours)
+ self.fields['retention'].help_text = _(
+ 'The backup retention period using notation separated '
+ 'by comma: 1y,6m,3w,15d. When left empty the hostgroup retention '
+ '{} is used.').format(retention)
+
+ if 'storage_alias' in self.fields:
+ storage_choices = tuple(
+ (storage.alias, storage.get_label())
+ for storage in storage_pools.values())
+ self.fields['storage_alias'] = forms.ChoiceField(
+ label=_('Storage'), choices=storage_choices)
+
+ if 'hostgroup' in self.fields:
+ self.fields['hostgroup'].queryset = (
+ self.fields['hostgroup'].queryset.order_by('name'))
+
+ class Meta:
+ model = Fileset
+ exclude = (
+ 'last_ok',
+ 'last_run',
+ 'first_fail',
+ )
+
+
+class FilesetRefForm(forms.ModelForm):
+ """
+ Generate FilesetRefForm tailored to the supplied class; so sorting
+ of the Filesets works.
+
+ Use in your admin class. For example:
+
+ from django.forms import modelform_factory
+ from planb.forms import FilesetRefForm
+
+ class MyModel(models.Model):
+ fileset = models.OneToOneField(Fileset)
+
+ class MyModelAdmin(admin.ModelAdmin):
+ form = modelform_factory(MyModel, form=FilesetRefForm)
+ """
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+
+ if 'fileset' in self.fields:
+ # Order.
+ self.fields['fileset'].queryset = (
+ self.fields['fileset'].queryset.order_by('friendly_name'))
+
+ # Get IDs of used filesets.
+ ids = set()
+ for transport_class_name in settings.PLANB_TRANSPORTS:
+ transport_class = apps.get_model(transport_class_name)
+ ids.update(transport_class.objects.values_list(
+ 'fileset', flat=True))
+
+ # Don't list used filesets.
+ # NOTE: This is not a fool-proof way to avoid
+ # MultipleObjectsReturned. But it will provide a better
+ # interface.
+ self.fields['fileset'].queryset = (
+ self.fields['fileset'].queryset.exclude(id__in=ids))
+
+ class Meta:
+ fields = '__all__'
diff --git a/pool/shard006/Python/0057818_make_website.py b/pool/shard006/Python/0057818_make_website.py
new file mode 100644
index 0000000000000000000000000000000000000000..e155402c94beb9d80968eeab9cc2a66dc08c2f60
--- /dev/null
+++ b/pool/shard006/Python/0057818_make_website.py
@@ -0,0 +1,165 @@
+"""
+Sun Oct 12 11:38:18 IDT 2014
+by xorpd.
+
+A script for auto generating the xorpd's website.
+"""
+
+from mako.template import Template
+from mako.lookup import TemplateLookup
+
+import os
+import shutil
+
+import lib.utils
+
+class MakeWebsiteError(Exception): pass
+
+
+# The content's directory name:
+CONTENT_DIR = "content"
+# The output's directory name:
+OUTPUT_DIR = "output"
+
+
+class ExceptStaticWeber(Exception):
+ pass
+
+class ExceptInvalidExtension(ExceptStaticWeber):
+ pass
+
+def change_extension(filename,new_ext):
+ """
+ Change the extension of a file to be new_ext
+ """
+ last_dot = filename.rfind(".")
+ return filename[:last_dot] + "." + new_ext
+
+def get_extension(filename):
+ """
+ Get the extension of a file (What comes right after the last dot).
+ """
+ return filename.split(".")[-1]
+
+def clean_empty_dirs(root_dir,ignore_prefixes=["."]):
+ """
+ Check the directory tree for any empty directories, or directories that
+ contain only empty directories (etc.)
+ Then delete any such directories.
+
+ Do not delete inside any directories which begin with one of the
+ ignore_prefixes.
+ """
+ # We don't get into directories which begin with
+ # one of the ignore prefixes:
+ for iprefix in ignore_prefixes:
+ if os.path.basename(root_dir).startswith(iprefix):
+ return
+
+ files = os.listdir(root_dir)
+
+ for f in files:
+ new_root = os.path.join(root_dir,f)
+ if os.path.isdir(new_root):
+ clean_empty_dirs(new_root)
+
+ # After some deleting, we get again the list of contents.
+ # Note that this will not be the same list from the first time.
+ files = os.listdir(root_dir)
+ if len(files) == 0:
+ # If there are no files inside the directory, remove it and exit:
+ os.rmdir(root_dir)
+
+
+class Website():
+ def __init__(self,path):
+ # Load the path of the website:
+ self.website_path = path
+
+ def build_website(self):
+
+ # Build the path of the content folder:
+ content_path = os.path.join(self.website_path,CONTENT_DIR)
+
+ # Build the path of the output folder:
+ output_path = os.path.join(self.website_path,OUTPUT_DIR)
+
+ # Directory lookup.
+ # This way include or inherit directive from any of the mako templates
+ # doesn't have to specify the full path.
+ wlookup = TemplateLookup(directories=[content_path])
+
+ # Remove output directory if it exists:
+ # try:
+ # shutil.rmtree(output_path)
+ # except FileNotFoundError:
+ # pass
+
+
+ # Iterate over all files inside the content directory, to find MAKO
+ # templates to render:
+ for root,dirs,files in os.walk(content_path):
+
+ # Copy to the equivalent at the output directory:
+ rel_root = os.path.relpath(root,content_path)
+ # Get equivalent path inside output directory:
+ root_output = os.path.join(output_path,rel_root)
+ # Create equivalent folder if necessary:
+ if not os.path.exists(root_output):
+ os.makedirs(root_output)
+
+
+ for fl in files:
+ # Get full path inside content directory:
+ fl_path = os.path.join(root,fl)
+ fl_ext = lib.utils.get_extension(fl)
+
+ props = lib.utils.get_ext_props(fl_ext)
+
+
+ if props.should_render:
+ # Build a template:
+ fl_tmp = Template(filename=fl_path,lookup=wlookup)
+ # Get the filename as target_ext extensioned file:
+ fl_with_ext = lib.utils.change_extension(fl,props.target_ext)
+ fl_with_ext_output = os.path.join(root_output,fl_with_ext)
+
+ try:
+ # Render the template:
+ res_render = fl_tmp.render(my_filename=fl,\
+ my_content_dir=content_path,\
+ my_output_dir=output_path,\
+ my_rel_dir=rel_root)
+ except Exception as e:
+ raise MakeWebsiteError('Failed rendering '
+ '{}'.format(fl)) from e
+
+
+
+ if props.render_output:
+ # Write the template's rendering result to a file at
+ # the output directory tree:
+ with open(fl_with_ext_output,"w") as fw:
+ fw.write(res_render)
+ continue
+
+ if props.should_copy:
+ # We copy the file to the destination folder:
+ # Get equivalent path inside output directory:
+ fl_output = os.path.join(root_output,fl)
+ # Copy to output directory:
+ shutil.copyfile(fl_path,fl_output)
+ # Continue to the next file:
+ continue
+
+ # Clean any empty directories inside output:
+ clean_empty_dirs(output_path,ignore_prefixes=["."])
+
+
+def go():
+ wb = Website(".")
+ wb.build_website()
+
+
+if __name__ == "__main__":
+ go()
diff --git a/pool/shard006/Python/0057830_fixup.py b/pool/shard006/Python/0057830_fixup.py
new file mode 100644
index 0000000000000000000000000000000000000000..85c962e869d6437f30e60ec0716fbdbbdd78ca68
--- /dev/null
+++ b/pool/shard006/Python/0057830_fixup.py
@@ -0,0 +1,80 @@
+import base64, hmac, marshal, mod_python.util, mod_python.Cookie
+from mod_python.Cookie import CookieError, PY2
+
+def fixup(self, value):
+ try:
+ if isinstance(value, str):
+ return bytes.__new__(self, value.encode())
+ else:
+ return bytes.__new__(self, value)
+ except:
+ raise ValueError(str(type(value)))
+mod_python.util.StringField.__new__ = fixup
+
+def fixup2(self):
+ m = base64.encodestring(marshal.dumps(self.value))
+ # on long cookies, the base64 encoding can contain multiple lines
+ # separated by \n or \r\n
+ if isinstance(m, bytes):
+ m = m.decode()
+ m = ''.join(m.split())
+
+ result = ["%s=%s%s" % (self.name, self.hexdigest(m), m)]
+ for name in self._valid_attr:
+ if hasattr(self, name):
+ if name in ("secure", "discard", "httponly"):
+ result.append(name)
+ else:
+ result.append("%s=%s" % (name, getattr(self, name)))
+ return "; ".join(result)
+mod_python.Cookie.MarshalCookie.__str__ = fixup2
+
+def fixup3(self, str):
+ import hmac
+ if not self.__data__["secret"]:
+ raise CookieError("Cannot sign without a secret")
+ if PY2:
+ _hmac = hmac.new(self.__data__["secret"], self.name)
+ _hmac.update(str)
+ else:
+ _hmac = hmac.new(self.__data__["secret"].encode(), self.name.encode())
+ _hmac.update(str.encode())
+ return _hmac.hexdigest()
+mod_python.Cookie.SignedCookie.hexdigest = fixup3
+
+def fixup4(self, secret):
+ import hmac
+ sig, val = self.value[:32], self.value[32:]
+
+ if PY2:
+ mac = hmac.new(secret, self.name)
+ mac.update(val)
+ else:
+ mac = hmac.new(secret.encode(), self.name.encode())
+ mac.update(val.encode())
+
+ if mac.hexdigest() == sig:
+ self.value = val
+ self.__data__["secret"] = secret
+ else:
+ raise mod_python.Cookie.CookieError("Incorrectly Signed Cookie: %s=%s" % (self.name, self.value))
+mod_python.Cookie.SignedCookie.unsign = fixup4
+
+def fixup5(self, secret):
+
+ self.unsign(secret)
+
+ try:
+ if PY2:
+ data = base64.decodestring(self.value)
+ else:
+ data = base64.decodestring(self.value.encode())
+ except:
+ raise mod_python.Cookie.CookieError("Cannot base64 Decode Cookie: %s=%s" % (self.name, self.value))
+
+ try:
+ self.value = marshal.loads(data)
+ except (EOFError, ValueError, TypeError):
+ raise CookieError("Cannot Unmarshal Cookie: %s=%s" % (self.name, self.value))
+mod_python.Cookie.MarshalCookie.unmarshal = fixup5
+
diff --git a/pool/shard006/Python/0057834_min_hill_sort.py b/pool/shard006/Python/0057834_min_hill_sort.py
new file mode 100644
index 0000000000000000000000000000000000000000..9e49930a5ada5569255b432b6c0e07cf08613017
--- /dev/null
+++ b/pool/shard006/Python/0057834_min_hill_sort.py
@@ -0,0 +1,49 @@
+"""
+
+"""
+import unittest
+
+
+def check_valid(arr, x):
+ temp_arr = arr[:]
+ temp_arr[0] = arr[0] - x
+ for i in range(1, len(arr)):
+ if temp_arr[i-1] < x + temp_arr[i]:
+ temp_arr[i] = max(temp_arr[i-1]+1, temp_arr[i]-x)
+ else:
+ return False
+ return True
+
+
+def min_to_sort(arr):
+ low = 1
+ high = 2**31 - 1
+ result = -1
+ while low < high:
+ mid = (high + low)//2
+ if check_valid(arr, mid):
+ result = mid
+ high = mid - 1
+ else:
+ low = mid + 1
+ return result
+
+
+class MyTestResults(unittest.TestCase):
+ def test_check_valid(self):
+ arr = [5, 4, 3, 2, 8]
+ self.assertTrue(check_valid(arr, 500))
+ self.assertTrue(check_valid(arr, 5))
+ self.assertTrue(check_valid(arr, 4))
+ self.assertTrue(check_valid(arr, 3))
+ self.assertFalse(check_valid(arr, 2))
+ self.assertFalse(check_valid(arr, 1))
+ self.assertFalse(check_valid(arr, 1))
+ arr = [52, 71, 36, 92, 48]
+ self.assertTrue(check_valid(arr, 23))
+
+ def test_min_to_sort(self):
+ arr = [5, 4, 3, 2, 8]
+ self.assertEqual(min_to_sort(arr), 3)
+ arr = [52, 71, 36, 92, 48]
+ self.assertEqual((check_valid(arr, 23)))
diff --git a/pool/shard006/Python/0057844_train_multiprocess.py b/pool/shard006/Python/0057844_train_multiprocess.py
new file mode 100644
index 0000000000000000000000000000000000000000..11ebe883f3eedc12f03da30c843fb011c7ffe4b5
--- /dev/null
+++ b/pool/shard006/Python/0057844_train_multiprocess.py
@@ -0,0 +1,98 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+#
+
+
+from singa import singa_wrap as singa
+from singa import opt
+import argparse
+import train
+import multiprocessing
+
+def run(args, local_rank, world_size, nccl_id):
+ sgd = opt.SGD(lr=args.lr, momentum=0.9, weight_decay=1e-5)
+ sgd = opt.DistOpt(sgd, nccl_id=nccl_id, local_rank=local_rank, world_size=world_size)
+ train.run(sgd.global_rank, sgd.world_size, sgd.local_rank,
+ args.max_epoch, args.batch_size, args.model, args.data, sgd, args.graph, args.dist_option, args.spars)
+
+
+if __name__ == '__main__':
+ # use argparse to get command config: max_epoch, model, data, etc. for single gpu training
+ parser = argparse.ArgumentParser(
+ description='Training using the autograd and graph.')
+ parser.add_argument('model',
+ choices=['resnet', 'xceptionnet', 'cnn', 'mlp'],
+ default='cnn')
+ parser.add_argument('data', choices=['cifar10', 'cifar100', 'mnist'], default='mnist')
+ parser.add_argument('--epoch',
+ '--max-epoch',
+ default=10,
+ type=int,
+ help='maximum epochs',
+ dest='max_epoch')
+ parser.add_argument('--bs',
+ '--batch-size',
+ default=64,
+ type=int,
+ help='batch size',
+ dest='batch_size')
+ parser.add_argument('--lr',
+ '--learning-rate',
+ default=0.005,
+ type=float,
+ help='initial learning rate',
+ dest='lr')
+ parser.add_argument('--ws',
+ '--world-size',
+ default=2,
+ type=int,
+ help='number of gpus to be used',
+ dest='world_size')
+ parser.add_argument('--op',
+ '--option',
+ default='fp32',
+ choices=['fp32','fp16','partialUpdate','sparseTopK','sparseThreshold'],
+ help='distibuted training options',
+ dest='dist_option') # currently partialUpdate support graph=False only
+ parser.add_argument('--spars',
+ '--sparsification',
+ default='0.05',
+ type=float,
+ help='the sparsity parameter used for sparsification, between 0 to 1',
+ dest='spars')
+ parser.add_argument('--no-graph',
+ '--disable-graph',
+ default='True',
+ action='store_false',
+ help='disable graph',
+ dest='graph')
+
+
+ args = parser.parse_args()
+
+ # Generate a NCCL ID to be used for collective communication
+ nccl_id = singa.NcclIdHolder()
+
+ process = []
+ for local_rank in range(0, args.world_size):
+ process.append(
+ multiprocessing.Process(target=run,
+ args=(args, local_rank, args.world_size, nccl_id)))
+
+ for p in process:
+ p.start()
diff --git a/pool/shard006/Python/0057847_testrungroup.py b/pool/shard006/Python/0057847_testrungroup.py
new file mode 100644
index 0000000000000000000000000000000000000000..cb7bc11731ea5a6e4a001fd8ae4349e8959ed548
--- /dev/null
+++ b/pool/shard006/Python/0057847_testrungroup.py
@@ -0,0 +1,97 @@
+__author__ = 'Jared Jorgensen'
+
+from slickqaweb.app import app
+from slickqaweb.model.testrunGroup import TestrunGroup
+from slickqaweb.model.testrun import Testrun
+from slickqaweb.model.serialize import deserialize_that
+from slickqaweb.model.query import queryFor
+from slickqaweb.utils import *
+import datetime
+from flask import request, g
+from .standardResponses import JsonResponse, read_request
+from bson import ObjectId
+from .apidocs import add_resource, accepts, returns, argument_doc, standard_query_parameters, note
+from mongoengine import ListField, ReferenceField
+
+add_resource('/testrungroups', 'Add, update, and delete testrungroups.')
+
+
+@app.route('/api/testrungroups')
+@standard_query_parameters
+@returns(ListField(ReferenceField(TestrunGroup)))
+def get_testrungroups():
+ """Query for testrungroups."""
+ return JsonResponse(queryFor(TestrunGroup))
+
+@app.route('/api/testrungroups/')
+@returns(TestrunGroup)
+@argument_doc('testrungroup_id', "A Testrun Group's id (the string representation of a BSON ObjectId).")
+def get_testrungroup_by_id(testrungroup_id):
+ """Find a testrungroup by it's id."""
+ return JsonResponse(TestrunGroup.objects(id=testrungroup_id).first())
+
+
+@app.route('/api/testrungroups', methods=["POST"])
+@returns(TestrunGroup)
+@accepts(TestrunGroup)
+@note("If you do not provide a created date, one will be created.")
+def add_testrungroup():
+ """Create a new testrungroup."""
+ new_trg = deserialize_that(read_request(), TestrunGroup())
+ if is_not_provided(new_trg, 'created'):
+ new_trg.created = datetime.datetime.now()
+ new_trg.save()
+ return JsonResponse(new_trg)
+
+@app.route('/api/testrungroups/', methods=["PUT"])
+@argument_doc('testrungroup_id', "A Testrun Group's id (the string representation of a BSON ObjectId).")
+@returns(TestrunGroup)
+@accepts(TestrunGroup)
+def update_testrungroup(testrungroup_id):
+ """Update a testrun group's properties."""
+ orig = TestrunGroup.objects(id=testrungroup_id).first()
+ deserialize_that(read_request(), orig)
+ orig.save()
+ return JsonResponse(orig)
+
+@app.route('/api/testrungroups/', methods=["DELETE"])
+@argument_doc('testrungroup_id', "A Testrun Group's id (the string representation of a BSON ObjectId).")
+@returns(TestrunGroup)
+def delete_testrungroup(testrungroup_id):
+ """Remove a testrun group"""
+ orig = TestrunGroup.objects(id=testrungroup_id).first()
+ orig.delete()
+ return JsonResponse(orig)
+
+@app.route('/api/testrungroups//addtestrun/', methods=["POST"])
+@argument_doc('testrungroup_id', "A Testrun Group's id (the string representation of a BSON ObjectId).")
+@argument_doc('testrun_id', "A Testrun's id (the string representation of a BSON ObjectId).")
+@returns(TestrunGroup)
+def add_testrun_to_testrun_group(testrungroup_id, testrun_id):
+ """Add a testrun to a testrun group"""
+ orig = TestrunGroup.objects(id=ObjectId(testrungroup_id)).first()
+ testrun = Testrun.objects(id=ObjectId(testrun_id)).first()
+ if (not hasattr(orig, 'testruns')) or orig.testruns is None:
+ orig.testruns = []
+ orig.testruns.append(testrun)
+ orig.save()
+ return JsonResponse(orig)
+
+@app.route('/api/testrungroups//removetestrun/', methods=["DELETE"])
+@argument_doc('testrungroup_id', "A Testrun Group's id (the string representation of a BSON ObjectId).")
+@argument_doc('testrun_id', "A Testrun's id (the string representation of a BSON ObjectId).")
+@returns(TestrunGroup)
+def remove_testrun_from_testrun_group(testrungroup_id, testrun_id):
+ """Remove a testrun from a testrun group"""
+ orig = TestrunGroup.objects(id=ObjectId(testrungroup_id)).first()
+ real_testrunid = ObjectId(testrun_id)
+ index = -1
+ for i in range(len(orig.testruns)):
+ if orig.testruns[i].id == real_testrunid:
+ index = i
+ break
+ if index >= 0:
+ del orig.testruns[index]
+ orig.save()
+ return JsonResponse(orig)
+
diff --git a/pool/shard006/Python/0057851_views.py b/pool/shard006/Python/0057851_views.py
new file mode 100644
index 0000000000000000000000000000000000000000..1b58af0ba7a5740d56897bb9709d3d4dac4bc8cf
--- /dev/null
+++ b/pool/shard006/Python/0057851_views.py
@@ -0,0 +1,44 @@
+# -*-coding: utf-8 -*-
+from django.shortcuts import render, redirect
+from django.contrib import auth
+from django.contrib.auth.forms import UserCreationForm
+from django.core.context_processors import csrf
+
+
+# Create your views here.
+def login(request):
+ args={}
+ args.update(csrf(request))
+ if request.POST:
+ username=request.POST.get('username','')
+ password=request.POST.get('password','')
+ user=auth.authenticate(username=username,password=password)
+ if user is not None:
+ auth.login(request,user)
+ return redirect('/idea')
+ else:
+ args['login_error']="Пользователь не найдкн"
+ return render(request,'login.html',args)
+ else:
+ return render(request,'login.html',args)
+
+def logout(request):
+ back_url = request.META['HTTP_REFERER']
+ auth.logout(request)
+ return redirect(back_url)
+
+def register(request):
+ args = {}
+ args['form'] = UserCreationForm()
+ if request.POST:
+ newuser_form = UserCreationForm()
+ args.update(csrf(request))
+ if newuser_form.is_valid():
+ newuser_form.save()
+ newuser = auth.authenticate(username=newuser_form.cleaned_data['username'], password=newuser_form.cleaned_data['password2'])
+ auth.login(request, newuser)
+ return redirect('/')
+ else:
+ args['form'] = UserCreationForm()
+ return render(request,'register.html', args)
+
diff --git a/pool/shard006/Python/0057859_netcmd.py b/pool/shard006/Python/0057859_netcmd.py
new file mode 100644
index 0000000000000000000000000000000000000000..fc77af8d12de8f806319815438a03576c5373e92
--- /dev/null
+++ b/pool/shard006/Python/0057859_netcmd.py
@@ -0,0 +1,215 @@
+# This code is part of Ansible, but is an independent component.
+# This particular file snippet, and this file snippet only, is BSD licensed.
+# Modules you write using this snippet, which is embedded dynamically by Ansible
+# still belong to the author of the module, and may assign their own license
+# to the complete work.
+#
+# Copyright (c) 2015 Peter Sprygada,
+#
+# Redistribution and use in source and binary forms, with or without modification,
+# are permitted provided that the following conditions are met:
+#
+# * Redistributions of source code must retain the above 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.
+#
+# 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 HOLDER 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.
+#
+
+import re
+import time
+import itertools
+import shlex
+
+from ansible.module_utils.basic import BOOLEANS_TRUE, BOOLEANS_FALSE
+
+class Conditional(object):
+ """Used in command modules to evaluate waitfor conditions
+ """
+
+ OPERATORS = {
+ 'eq': ['eq', '=='],
+ 'neq': ['neq', 'ne', '!='],
+ 'gt': ['gt', '>'],
+ 'ge': ['ge', '>='],
+ 'lt': ['lt', '<'],
+ 'le': ['le', '<='],
+ 'contains': ['contains'],
+ 'matches': ['matches']
+ }
+
+ def __init__(self, conditional, encoding='json'):
+ self.raw = conditional
+ self.encoding = encoding
+
+ key, op, val = shlex.split(conditional)
+ self.key = key
+ self.func = self.func(op)
+ self.value = self._cast_value(val)
+
+ def __call__(self, data):
+ value = self.get_value(dict(result=data))
+ return self.func(value)
+
+ def _cast_value(self, value):
+ if value in BOOLEANS_TRUE:
+ return True
+ elif value in BOOLEANS_FALSE:
+ return False
+ elif re.match(r'^\d+\.d+$', value):
+ return float(value)
+ elif re.match(r'^\d+$', value):
+ return int(value)
+ else:
+ return unicode(value)
+
+ def func(self, oper):
+ for func, operators in self.OPERATORS.items():
+ if oper in operators:
+ return getattr(self, func)
+ raise AttributeError('unknown operator: %s' % oper)
+
+ def get_value(self, result):
+ if self.encoding in ['json', 'text']:
+ return self.get_json(result)
+ elif self.encoding == 'xml':
+ return self.get_xml(result.get('result'))
+
+ def get_xml(self, result):
+ parts = self.key.split('.')
+
+ value_index = None
+ match = re.match(r'^\S+(\[)(\d+)\]', parts[-1])
+ if match:
+ start, end = match.regs[1]
+ parts[-1] = parts[-1][0:start]
+ value_index = int(match.group(2))
+
+ path = '/'.join(parts[1:])
+ path = '/%s' % path
+ path += '/text()'
+
+ index = int(re.match(r'result\[(\d+)\]', parts[0]).group(1))
+ values = result[index].xpath(path)
+
+ if value_index is not None:
+ return values[value_index].strip()
+ return [v.strip() for v in values]
+
+ def get_json(self, result):
+ parts = re.split(r'\.(?=[^\]]*(?:\[|$))', self.key)
+ for part in parts:
+ match = re.findall(r'\[(\S+?)\]', part)
+ if match:
+ key = part[:part.find('[')]
+ result = result[key]
+ for m in match:
+ try:
+ m = int(m)
+ except ValueError:
+ m = str(m)
+ result = result[m]
+ else:
+ result = result.get(part)
+ return result
+
+ def number(self, value):
+ if '.' in str(value):
+ return float(value)
+ else:
+ return int(value)
+
+ def eq(self, value):
+ return value == self.value
+
+ def neq(self, value):
+ return value != self.value
+
+ def gt(self, value):
+ return self.number(value) > self.value
+
+ def ge(self, value):
+ return self.number(value) >= self.value
+
+ def lt(self, value):
+ return self.number(value) < self.value
+
+ def le(self, value):
+ return self.number(value) <= self.value
+
+ def contains(self, value):
+ return str(self.value) in value
+
+ def matches(self, value):
+ match = re.search(value, self.value, re.M)
+ return match is not None
+
+
+class FailedConditionsError(Exception):
+
+ def __init__(self, msg, failed_conditions):
+ super(FailedConditionsError, self).__init__(msg)
+ self.failed_conditions = failed_conditions
+
+class CommandRunner(object):
+
+ def __init__(self, module):
+ self.module = module
+
+ self.items = list()
+ self.conditionals = set()
+
+ self.retries = 10
+ self.interval = 1
+
+ self._cache = dict()
+
+ def add_command(self, command, output=None):
+ self.module.cli.add_commands(command, output=output)
+
+ def get_command(self, command):
+ try:
+ cmdobj = self._cache[command]
+ return cmdobj.response
+ except KeyError:
+ for cmd in self.module.cli.commands:
+ if str(cmd) == command:
+ self._cache[command] = cmd
+ return cmd.response
+ raise ValueError("command '%s' not found" % command)
+
+
+ def add_conditional(self, condition):
+ self.conditionals.add(Conditional(condition))
+
+ def run_commands(self):
+ responses = self.module.cli.run_commands()
+ self.items = responses
+
+ def run(self):
+ while self.retries > 0:
+ self.run_commands()
+
+ for item in list(self.conditionals):
+ if item(self.items):
+ self.conditionals.remove(item)
+
+ if not self.conditionals:
+ break
+
+ time.sleep(self.interval)
+ self.retries -= 1
+ else:
+ failed_conditions = [item.raw for item in self.conditionals]
+ raise FailedConditionsError('timeout waiting for value', failed_conditions)
+
diff --git a/pool/shard006/Python/0057862_visual_confirmation.py b/pool/shard006/Python/0057862_visual_confirmation.py
new file mode 100644
index 0000000000000000000000000000000000000000..8e89d8b8b8b1793dfe032da0ecf43020d57e75a7
--- /dev/null
+++ b/pool/shard006/Python/0057862_visual_confirmation.py
@@ -0,0 +1,97 @@
+import numpy
+from investigators.visuals import cv2 # package includes a fallback cv2
+from investigators.visuals import TemplateFinder, ProportionalRegion, Grid
+from investigators.visuals import ImageIdentifier, TankLevel
+
+# Show the starting screenshot
+screenshot = cv2.imread('screenshot 1280x800, game 800x600.png')
+cv2.imshow('screenshot', screenshot)
+cv2.waitKey()
+
+# Use TemplateFinder to locate and show an image of the game on the screen
+template = cv2.imread('game 640x480.png')
+mask = cv2.imread('game mask 640x480.png')
+possible_sizes = (600, 800), (240, 320)
+finder = TemplateFinder(template, sizes=possible_sizes, mask=mask,
+ scale_for_speed=0.25)
+t, l, b, r = finder.locate_in(screenshot)
+game = screenshot[t:b, l:r]
+cv2.destroyWindow('screenshot')
+cv2.imshow('extracted game', game)
+cv2.waitKey()
+
+# Use ProportionalRegion to isolate the board within the game
+tlbr_proportions = (80.0 / 480, 135.0 / 640, 450.0 / 480, 504.0 / 640)
+proportional = ProportionalRegion(tlbr_proportions)
+t, l, b, r = proportional.region_in(game)
+board = game[t:b, l:r]
+cv2.imshow('extracted board', board)
+cv2.waitKey()
+
+# Use Grid to split the grid into image cells. record only the first four
+board_dimensions = 8, 8
+tile_padding = (0.1, 0.1, 0.1, 0.1) # just for demonstration
+grid = Grid(board_dimensions, tile_padding)
+first_four_tiles = list()
+for grid_p, cell_borders in grid.borders_by_grid_position(board):
+ if grid_p in ((0, 0), (0, 1), (0, 2), (0, 3)):
+ t, l, b, r = cell_borders
+ first_four_tiles.append(board[t:b, l:r])
+
+# Use ImageIdentifier to identify each of the first four tiles
+identifier = ImageIdentifier({'red': cv2.imread('r.png'),
+ 'blue': cv2.imread('b.png'),
+ 'coins': cv2.imread('m.png'),
+ 'skull': cv2.imread('s.png')})
+for tile in first_four_tiles:
+ name = identifier.identify(tile)
+ cv2.putText(tile, name, (2, 20), 0, 0.6, (255, 255, 255), 2)
+ cv2.imshow('identified original tile', tile)
+ cv2.waitKey()
+cv2.destroyWindow('identified original tile')
+cv2.destroyWindow('extracted board')
+
+# Use ProportionalRegion to isolate the player's health within the game
+tlbr_proportions = (76.0 / 480, 8.0 / 640, 87.0 / 480, 116.0 / 640)
+proportional = ProportionalRegion(tlbr_proportions)
+t, l, b, r = proportional.region_in(game)
+health = game[t:b, l:r]
+
+# Use TankLevel to measure how full the health bar is
+health_color = (4, 4, 110)
+empty_health_color = (15, 15, 50)
+ignore_color = (0, 0, 0)
+tank_level = TankLevel(health_color, empty_health_color, ignore_color)
+health = numpy.rot90(health) # make it upright for the TankLevel measurement
+health_pcnt = 100.0 * tank_level.how_full(health)
+health_string = '~{:2.0f}%'.format(health_pcnt)
+health = numpy.rot90(health, -1) # rotate and enlarge for display
+h, w = health.shape[0:2]
+health = cv2.resize(health, (w * 3, h * 3), interpolation=cv2.INTER_CUBIC)
+cv2.putText(health, health_string, (25, 25), 0, 0.8, (0, 255, 0), 2)
+cv2.imshow('player health bar', health)
+cv2.waitKey()
+
+# Use ProportionalRegion to isolate the extra actions area within the game
+tlbr_proportions = (120.0 / 960, 1100.0 / 1280, 160.0 / 960, 1220.0 / 1280)
+proportional = ProportionalRegion(tlbr_proportions)
+t, l, b, r = proportional.region_in(game)
+token_region = game[t:b, l:r]
+
+# Use TemplateFinder (multiple) to check for extra actions
+token_template = cv2.imread('extra_turn_token.png')
+possible_sizes = (17, 14),
+finder = TemplateFinder(token_template, sizes=possible_sizes,
+ acceptable_threshold=0.1, immediate_threshold=0.1)
+found_tokens = finder.locate_multiple_in(token_region)
+for borders in found_tokens:
+ t, l, b, r = borders
+ cv2.rectangle(token_region, (l, t), (r, b), (255, 255, 255), 2)
+h, w = token_region.shape[0:2]
+token_region = cv2.resize(token_region, (w * 3, h * 3),
+ interpolation=cv2.INTER_CUBIC)
+cv2.imshow('extra actions', token_region)
+cv2.waitKey()
+
+# clean up
+cv2.destroyAllWindows()
diff --git a/pool/shard006/Python/0057867_setup.py b/pool/shard006/Python/0057867_setup.py
new file mode 100644
index 0000000000000000000000000000000000000000..67e307f235ecc16a14d564fecacb308f1bbd5063
--- /dev/null
+++ b/pool/shard006/Python/0057867_setup.py
@@ -0,0 +1,165 @@
+# -*- coding: utf-8 -*-
+
+from __future__ import print_function
+from setuptools import setup, find_packages, Command
+from setuptools.command.sdist import sdist
+from setuptools.command.build_py import build_py
+from setuptools.command.egg_info import egg_info
+from subprocess import check_call
+import os
+import sys
+import platform
+
+here = os.path.dirname(os.path.abspath(__file__))
+node_root = os.path.join(here, 'js')
+is_repo = os.path.exists(os.path.join(here, '.git'))
+
+npm_path = os.pathsep.join([
+ os.path.join(node_root, 'node_modules', '.bin'),
+ os.environ.get('PATH', os.defpath),
+])
+
+from distutils import log
+log.set_verbosity(log.DEBUG)
+log.info('setup.py entered')
+log.info('$PATH=%s' % os.environ['PATH'])
+
+LONG_DESCRIPTION = 'A Python/ThreeJS bridge utilizing the Jupyter widget infrastructure.'
+
+def js_prerelease(command, strict=False):
+ """decorator for building minified js/css prior to another command"""
+ class DecoratedCommand(command):
+ def run(self):
+ jsdeps = self.distribution.get_command_obj('jsdeps')
+ if not is_repo and all(os.path.exists(t) for t in jsdeps.targets):
+ # sdist, nothing to do
+ command.run(self)
+ return
+
+ try:
+ self.distribution.run_command('jsdeps')
+ except Exception as e:
+ missing = [t for t in jsdeps.targets if not os.path.exists(t)]
+ if strict or missing:
+ log.warn('rebuilding js and css failed')
+ if missing:
+ log.error('missing files: %s' % missing)
+ raise e
+ else:
+ log.warn('rebuilding js and css failed (not a problem)')
+ log.warn(str(e))
+ command.run(self)
+ update_package_data(self.distribution)
+ return DecoratedCommand
+
+def update_package_data(distribution):
+ """update package_data to catch changes during setup"""
+ build_py = distribution.get_command_obj('build_py')
+ # distribution.package_data = find_package_data()
+ # re-init build_py options which load package_data
+ build_py.finalize_options()
+
+
+class NPM(Command):
+ description = 'install package.json dependencies using npm'
+
+ user_options = []
+
+ node_modules = os.path.join(node_root, 'node_modules')
+
+ targets = [
+ os.path.join(here, 'pythreejs', 'static', 'extension.js'),
+ os.path.join(here, 'pythreejs', 'static', 'index.js')
+ ]
+
+ def initialize_options(self):
+ pass
+
+ def finalize_options(self):
+ pass
+
+ def has_npm(self):
+ try:
+ check_call(['npm', '--version'])
+ return True
+ except:
+ return False
+
+ def should_run_npm_install(self):
+ package_json = os.path.join(node_root, 'package.json')
+ node_modules_exists = os.path.exists(self.node_modules)
+ return self.has_npm()
+
+ def run(self):
+ has_npm = self.has_npm()
+ if not has_npm:
+ log.error("`npm` unavailable. If you're running this command using sudo, make sure `npm` is available to sudo")
+
+ env = os.environ.copy()
+ env['PATH'] = npm_path
+
+ if self.should_run_npm_install():
+ log.info("Installing build dependencies with npm. This may take a while...")
+ check_call(['npm', 'install'], cwd=node_root, stdout=sys.stdout, stderr=sys.stderr)
+ os.utime(self.node_modules, None)
+
+ for t in self.targets:
+ if not os.path.exists(t):
+ msg = 'Missing file: %s' % t
+ if not has_npm:
+ msg += '\nnpm is required to build a development version of widgetsnbextension'
+ raise ValueError(msg)
+
+ # update package data in case this created new files
+ update_package_data(self.distribution)
+
+version_ns = {}
+with open(os.path.join(here, 'pythreejs', '_version.py')) as f:
+ exec(f.read(), {}, version_ns)
+
+setup_args = {
+ 'name': 'pythreejs',
+ 'version': version_ns['__version__'],
+ 'description': 'Interactive 3d graphics for the Jupyter notebook, using Three.js from Jupyter interactive widgets.',
+ 'long_description': LONG_DESCRIPTION,
+ 'License': 'BSD',
+ 'include_package_data': True,
+ 'data_files': [
+ ('share/jupyter/nbextensions/jupyter-threejs', [
+ 'pythreejs/static/extension.js',
+ 'pythreejs/static/index.js',
+ 'pythreejs/static/index.js.map',
+ ]),
+ ('share/jupyter/labextensions/jupyter-threejs', [
+ 'pythreejs/staticlab/jupyter-threejs.bundle.js',
+ 'pythreejs/staticlab/jupyter-threejs.bundle.js.manifest',
+ ]),
+ ],
+ 'install_requires': ['ipywidgets>=6.0.0'],
+ 'packages': find_packages(),
+ 'zip_safe': False,
+ 'cmdclass': {
+ 'build_py': js_prerelease(build_py),
+ 'egg_info': js_prerelease(egg_info),
+ 'sdist': js_prerelease(sdist, strict=True),
+ 'jsdeps': NPM,
+ },
+ 'author': 'PyThreejs Development Team',
+ 'author_email': 'jason@jasongrout.org',
+ 'url': 'https://github.com/jovyan/pythreejs',
+ 'keywords': ['ipython', 'jupyter', 'widgets', 'webgl', 'graphics', '3d'],
+ 'classifiers': [
+ 'Development Status :: 4 - Beta',
+ 'Intended Audience :: Developers',
+ 'Intended Audience :: Science/Research',
+ 'Topic :: Multimedia :: Graphics',
+ 'License :: OSI Approved :: BSD License',
+ 'Programming Language :: Python :: 2',
+ 'Programming Language :: Python :: 2.7',
+ 'Programming Language :: Python :: 3',
+ 'Programming Language :: Python :: 3.3',
+ 'Programming Language :: Python :: 3.4',
+ ],
+}
+
+setup(**setup_args)
diff --git a/pool/shard006/Python/0057871_test_existing_network.py b/pool/shard006/Python/0057871_test_existing_network.py
new file mode 100644
index 0000000000000000000000000000000000000000..d63e9f2d62e9b317beb08faa339ce096029ab7ed
--- /dev/null
+++ b/pool/shard006/Python/0057871_test_existing_network.py
@@ -0,0 +1,83 @@
+# 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.
+
+import mock
+
+from rally.plugins.openstack.context.network import existing_network
+from tests.unit import test
+
+CTX = "rally.plugins.openstack.context.network"
+
+
+class ExistingNetworkTestCase(test.TestCase):
+
+ def setUp(self):
+ super(ExistingNetworkTestCase, self).setUp()
+
+ self.config = mock.MagicMock()
+ self.context = test.get_test_context()
+ self.context.update({
+ "users": [
+ {"id": 1,
+ "tenant_id": "tenant1",
+ "endpoint": mock.Mock()},
+ {"id": 2,
+ "tenant_id": "tenant2",
+ "endpoint": mock.Mock()},
+ ],
+ "tenants": {
+ "tenant1": {},
+ "tenant2": {},
+ },
+ "config": {
+ "existing_network": self.config
+ },
+ })
+
+ @mock.patch("rally.osclients.Clients")
+ @mock.patch("rally.plugins.openstack.wrappers.network.wrap")
+ def test_setup(self, mock_network_wrap, mock_clients):
+ networks = [mock.Mock(), mock.Mock(), mock.Mock()]
+ net_wrappers = {
+ "tenant1": mock.Mock(
+ **{"list_networks.return_value": networks[0:2]}),
+ "tenant2": mock.Mock(
+ **{"list_networks.return_value": networks[2:]})
+ }
+ mock_network_wrap.side_effect = [net_wrappers["tenant1"],
+ net_wrappers["tenant2"]]
+
+ existing_network.ExistingNetwork(self.context).setup()
+
+ mock_clients.assert_has_calls([
+ mock.call(u["endpoint"]) for u in self.context["users"]])
+ mock_network_wrap.assert_has_calls([
+ mock.call(mock_clients.return_value, self.context["task"],
+ config=self.config),
+ mock.call(mock_clients.return_value, self.context["task"],
+ config=self.config)])
+ for net_wrapper in net_wrappers.values():
+ net_wrapper.list_networks.assert_called_once_with()
+
+ self.assertDictEqual(
+ self.context["tenants"],
+ {
+ "tenant1": {"networks": networks[0:2]},
+ "tenant2": {"networks": networks[2:]},
+ }
+ )
+
+ def test_cleanup(self):
+ # NOTE(stpierre): Test that cleanup is not abstract
+ existing_network.ExistingNetwork({"task": mock.MagicMock()}).cleanup()
diff --git a/pool/shard006/Python/0057874_users.py b/pool/shard006/Python/0057874_users.py
new file mode 100644
index 0000000000000000000000000000000000000000..e42da5674a732086032154a7e8649002fa45b775
--- /dev/null
+++ b/pool/shard006/Python/0057874_users.py
@@ -0,0 +1,114 @@
+# project/api/users.py
+
+
+from flask import Blueprint, jsonify, request, make_response
+from sqlalchemy import exc
+
+from project.api.utils import authenticate, is_admin
+from project.api.models import User
+from project import db
+
+
+users_blueprint = Blueprint('users', __name__)
+
+
+@users_blueprint.route('/ping', methods=['GET'])
+def ping_pong():
+ return jsonify({
+ 'status': 'success',
+ 'message': 'pong!'
+ })
+
+
+@users_blueprint.route('/users', methods=['POST'])
+@authenticate
+def add_user(resp):
+ if not is_admin(resp):
+ response_object = {
+ 'status': 'error',
+ 'message': 'You do not have permission to do that.'
+ }
+ return make_response(jsonify(response_object)), 401
+ post_data = request.get_json()
+ if not post_data:
+ response_object = {
+ 'status': 'fail',
+ 'message': 'Invalid payload.'
+ }
+ return make_response(jsonify(response_object)), 400
+ username = post_data.get('username')
+ email = post_data.get('email')
+ password = post_data.get('password')
+ try:
+ user = User.query.filter_by(email=email).first()
+ if not user:
+ db.session.add(User(
+ username=username,
+ email=email,
+ password=password))
+ db.session.commit()
+ response_object = {
+ 'status': 'success',
+ 'message': f'{email} was added!'
+ }
+ return make_response(jsonify(response_object)), 201
+ else:
+ response_object = {
+ 'status': 'fail',
+ 'message': 'Sorry. That email already exists.'
+ }
+ return make_response(jsonify(response_object)), 400
+ except (exc.IntegrityError, ValueError) as e:
+ db.session().rollback()
+ response_object = {
+ 'status': 'fail',
+ 'message': 'Invalid payload.'
+ }
+ return make_response(jsonify(response_object)), 400
+
+
+@users_blueprint.route('/users/', methods=['GET'])
+def get_single_user(user_id):
+ """Get single user details"""
+ response_object = {
+ 'status': 'fail',
+ 'message': 'User does not exist'
+ }
+ try:
+ user = User.query.filter_by(id=int(user_id)).first()
+ if not user:
+ return make_response(jsonify(response_object)), 404
+ else:
+ response_object = {
+ 'status': 'success',
+ 'data': {
+ 'username': user.username,
+ 'email': user.email,
+ 'created_at': user.created_at
+ }
+ }
+ return make_response(jsonify(response_object)), 200
+ except ValueError:
+ return make_response(jsonify(response_object)), 404
+
+
+@users_blueprint.route('/users', methods=['GET'])
+def get_all_users():
+ """Get all users"""
+ users = User.query.order_by(User.created_at.desc()).all()
+ users_list = []
+ for user in users:
+ user_object = {
+ 'id': user.id,
+ 'username': user.username,
+ 'email': user.email,
+ 'created_at': user.created_at
+ }
+ users_list.append(user_object)
+ response_object = {
+ 'status': 'success',
+ 'data': {
+ 'users': users_list
+ }
+ }
+ return make_response(jsonify(response_object)), 200
diff --git a/pool/shard006/Python/0057876_heatmap.py b/pool/shard006/Python/0057876_heatmap.py
new file mode 100644
index 0000000000000000000000000000000000000000..d85a815506b1b20d43a2c53faa51e27b0c7d4711
--- /dev/null
+++ b/pool/shard006/Python/0057876_heatmap.py
@@ -0,0 +1,85 @@
+import plotly.plotly as py
+import plotly.graph_objs as go
+from options_csv import OUTPUT_FILENAME_PREFIX_FORMAT
+import re
+import os
+import pandas as pd
+
+def build_heatmap(openInt_df):
+ trace = go.Heatmap(z=openInt_df.fillna(0).as_matrix(),
+ x=openInt_df.columns,
+ y=openInt_df.index)
+ data=[trace]
+ layout = go.Layout(
+ zaxis=dict(
+ type='log',
+ autorange=True
+ )
+ )
+ fig = go.Figure(data=data, layout=layout)
+ py.plot(fig, filename='expiration-heatmap')
+
+def build_colorscale(openInt_df):
+ data = [{
+ 'x': openInt_df.columns,
+ 'y': openInt_df.index,
+ 'z': openInt_df.fillna(0).as_matrix(),
+ 'type': 'heatmap',
+ 'colorscale': [
+ # [0, 'rgb(250, 250, 250)'], #0
+ # [1./10000, 'rgb(200, 200, 200)'], #10
+ # [1./1000, 'rgb(150, 150, 150)'], #100
+ # [1./100, 'rgb(100, 100, 100)'], #1000
+ # [1./10, 'rgb(50, 50, 50)'], #10000
+ # [1., 'rgb(0, 0, 0)'], #100000
+ [0, 'rgb(250, 250, 250)'], #0
+ [1./16.0, 'rgb(200, 200, 200)'], #10
+ [1./8.0, 'rgb(150, 150, 150)'], #100
+ [1./4.0, 'rgb(100, 100, 100)'], #1000
+ [1./2.0, 'rgb(50, 50, 50)'], #10000
+ [1., 'rgb(0, 0, 0)'], #100000
+ ],
+ 'colorbar': {
+ 'tick0': 0,
+ 'tickmode': 'array',
+ 'tickvals': [0, 1000, 10000, 100000]
+ }
+ }]
+
+ layout = {'title': 'Log Colorscale'}
+
+ fig = {'data': data, 'layout': layout}
+
+ py.plot(fig, filename='expiration-heatmap')
+
+def get_combined_options_data(csv_date, symbol, indir):
+ expected_prefix = OUTPUT_FILENAME_PREFIX_FORMAT.format(date=csv_date, ticker=symbol)
+ options_tables = {}
+ for root, dirs, files in os.walk(indir):
+ for file in files:
+ if file.startswith(str(csv_date)) and file.endswith(".csv"):
+ expiration_with_ext = file.split("_")[-1]
+ expiration = expiration_with_ext.split(".")[0][3:]
+ filename = os.path.join(root, file)
+ options_table = pd.DataFrame.from_csv(filename)
+ options_tables[expiration] = options_table
+ return pd.Panel(options_tables)
+
+
+if __name__ == "__main__":
+ import argparse
+ import datetime
+
+ parser = argparse.ArgumentParser(description="Makes a heatmap from a sequence of expirations")
+ parser.add_argument("--symbol", default="spx", help="Symbol in CSV files")
+ parser.add_argument("--indir", default=os.getcwd(), help="Directory to look for CSV files")
+ args = parser.parse_args()
+ # TODO: Add date selection (just use today for now...)
+ args.csv_date = datetime.date.today()
+
+ options_panel = get_combined_options_data(args.csv_date, args.symbol, args.indir)
+ print(options_panel)
+ call_openInt = options_panel.minor_xs('call_Open Int.')
+ print(call_openInt)
+ build_colorscale(call_openInt)
+
diff --git a/pool/shard006/Python/0057878_FileBot.py b/pool/shard006/Python/0057878_FileBot.py
new file mode 100644
index 0000000000000000000000000000000000000000..2c624ba3be3cd25c02a708450e6993b29f384d0d
--- /dev/null
+++ b/pool/shard006/Python/0057878_FileBot.py
@@ -0,0 +1,206 @@
+#!/usr/bin/env python3
+# -*- coding: utf-8 -*-
+
+__author__ = 'Chris Hamilton'
+__version__ = '1.2'
+
+import os
+import subprocess
+import sys
+
+##############################################################################
+### NZBGET POST-PROCESSING SCRIPT ###
+
+# FileBot.
+#
+# This script is a front-end wrapper for FileBot and the Automated Media Center script.
+#
+# Author: Chris Hamilton (clhamilton@me.com).
+# License: GPLv3 (http://www.gnu.org/licenses/gpl.html).
+# Version: 1.2.
+#
+# FileBot - http://www.filebot.net.
+# Automated Media Center script - http://www.filebot.net/forums/viewtopic.php?t=215.
+# Format Expressions - http://www.filebot.net/naming.html.
+# Command Line Interface - http://www.filebot.net/cli.html.
+#
+# Subtitles are provided by OpenSubtitles.org. An OpenSubtitles.org account is required for this feature to
+# function. See http://www.opensubtitles.org/en/newuser to register for an account. Once registered, run "filebot
+# -script fn:configure" from a command prompt and follow the instructions.
+#
+# NOTE: This script requires Python 2.x.
+#
+##############################################################################
+### OPTIONS
+
+# FileBot Path.
+# Path to FileBot run script.
+#FileBot=/usr/local/bin/filebot
+
+# Anime Format.
+# Format expression for Anime.
+#AnimeFormat={plex}
+
+# Movie Format.
+# Format expression for Movies.
+#MovieFormat={plex}
+
+# Music Format.
+# Format expression for Music.
+#MusicFormat={plex}
+
+# Series Format.
+# Format expression for Series or TV Shows.
+#SeriesFormat={plex}
+
+# Action (copy, hardlink, keeplink, move, reflink, symlink, test).
+# Rename action.
+#Action=move
+
+# Conflict Resolution (auto, skip).
+# This option determines how FileBot will resolve a conflict between existing media and new media that shares the same
+# file name. Choose "auto" to automatically overwrite existing media if new media is better. Choose "skip" to ignore
+# new media if existing media is downloaded again.
+#Conflict=auto
+
+# Output Path.
+# Output path for rename action.
+#Output=${DestDir}
+
+# Exclude List.
+# Keep a list of previously processed media to be ignored in future runs.
+#ExcludeList=${MainDir}/amc.txt
+
+# Minimum File Size.
+# Only process media files larger than the given number (in bytes).
+#MinFileSize=50000000
+
+# Minimum Video Length.
+# Only process videos longer than the given number (in milliseconds).
+#MinLengthMS=60000
+
+# Subtitle Languages.
+# ISO 639-1 (two-letter) language codes for subtitles. Use a comma (',') separate languages (e.g. en, de, fr,
+# es). See http://en.wikipedia.org/wiki/List_of_ISO_639-1_codes for the list of ISO 639-1 language codes.
+#Subtitles=
+
+# Pushover Key.
+# Send notifications using Pushover. Use a colon (':') to separate the user key and the optional, but recommended, API
+# key. See http://pushover.net/apps/clone/FileBot.
+#PushoverKey=
+
+# Clean (yes, no).
+# Automatically remove empty folders and clutter files that may be left behind after moving the media, or temporary
+# extracted files after copying.
+#Clean=yes
+
+# Log (all, fine, info, warning).
+# Level of detail to log.
+#Log=info
+
+# Log File.
+# Path to log file.
+#LogFile=${MainDir}/filebot.log
+
+# FileBot Options
+# FileBot Options
+#FileBotOptions=
+
+### NZBGET POST-PROCESSING SCRIPT ###
+##############################################################################
+
+POSTPROCESS_SUCCESS = 93
+POSTPROCESS_ERROR = 94
+POSTPROCESS_NONE = 95
+
+REQUIRED_OPTIONS = [
+ 'NZBPO_FILEBOT',
+ 'NZBPO_OUTPUT'
+]
+
+
+def main():
+ # NZBGet Parameters
+ nzbpp_category = os.getenv('NZBPP_CATEGORY')
+ nzbpp_directory = os.getenv('NZBPP_DIRECTORY')
+ nzbpp_totalstatus = os.getenv('NZBPP_TOTALSTATUS')
+ nzbpp_nzbname = os.getenv('NZBPP_NZBNAME')
+ for item in REQUIRED_OPTIONS:
+ if item not in os.environ:
+ print('[ERROR] Option {0} is missing from configuration file'.format(item[6:]))
+ sys.exit(POSTPROCESS_ERROR)
+ # User Parameters
+ nzbpo_action = os.getenv('NZBPO_ACTION')
+ nzbpo_animeformat = os.getenv('NZBPO_ANIMEFORMAT', '{plex}')
+ nzbpo_clean = os.getenv('NZBPO_CLEAN', 'no') == 'yes'
+ nzbpo_conflict = os.getenv('NZBPO_CONFLICT')
+ nzbpo_excludelist = os.getenv('NZBPO_EXCLUDELIST')
+ nzbpo_filebot = os.getenv('NZBPO_FILEBOT')
+ nzbpo_filebotoptions = os.getenv('NZBPO_FILEBOTOPTIONS')
+ nzbpo_log = os.getenv('NZBPO_LOG')
+ nzbpo_logfile = os.getenv('NZBPO_LOGFILE')
+ nzbpo_minfilesize = os.getenv('NZBPO_MINFILESIZE')
+ nzbpo_minlengthms = os.getenv('NZBPO_MINLENGTHMS')
+ nzbpo_movieformat = os.getenv('NZBPO_MOVIEFORMAT', '{plex}')
+ nzbpo_musicformat = os.getenv('NZBPO_MUSICFORMAT', '{plex}')
+ nzbpo_output = os.path.realpath(os.getenv('NZBPO_OUTPUT'))
+ nzbpo_pushoverkey = os.getenv('NZBPO_PUSHOVERKEY')
+ nzbpo_seriesformat = os.getenv('NZBPO_SERIESFORMAT', '{plex}')
+ nzbpo_subtitles = os.getenv('NZBPO_SUBTITLES')
+ if nzbpp_totalstatus != 'SUCCESS':
+ sys.exit(POSTPROCESS_NONE)
+ if not os.path.exists(nzbpo_output):
+ try:
+ os.mkdir(nzbpo_output)
+ except OSError as e:
+ print('[ERROR] {0}'.format(e))
+ sys.exit(POSTPROCESS_ERROR)
+ os.environ['FILEBOT_OPTS'] = nzbpo_filebotoptions
+ args = [
+ nzbpo_filebot,
+ '-no-index',
+ '-no-xattr',
+ '-non-strict',
+ '-script', 'fn:amc',
+ '--action', nzbpo_action,
+ '--conflict', nzbpo_conflict,
+ '--def', 'clean={0}'.format('y' if nzbpo_clean else 'n'),
+ '--def', 'excludeList={0}'.format(nzbpo_excludelist),
+ '--def', 'animeFormat={0}'.format(nzbpo_animeformat),
+ '--def', 'movieFormat={0}'.format(nzbpo_movieformat),
+ '--def', 'music=y',
+ '--def', 'musicFormat={0}'.format(nzbpo_musicformat),
+ '--def', 'seriesFormat={0}'.format(nzbpo_seriesformat),
+ '--def', 'skipExtract=y',
+ '--def', 'ut_dir={0}'.format(nzbpp_directory),
+ '--def', 'ut_label={0}'.format(nzbpp_category),
+ '--def', 'ut_kind=multi',
+ '--def', 'ut_title={0}'.format(nzbpp_nzbname),
+ '--log', nzbpo_log,
+ '--output', nzbpo_output
+ ]
+ if nzbpo_minfilesize:
+ args += ['--def', 'minFileSize={0}'.format(nzbpo_minfilesize)]
+ if nzbpo_minlengthms:
+ args += ['--def', 'minLengthMS={0}'.format(nzbpo_minlengthms)]
+ if nzbpo_logfile:
+ args += ['--log-file', nzbpo_logfile]
+ if nzbpo_pushoverkey:
+ args += ['--def', 'pushover={0}'.format(nzbpo_pushoverkey.replace(' ', ''))]
+ if nzbpo_subtitles:
+ args += ['--def', 'subtitles={0}'.format(nzbpo_subtitles.replace(' ', ''))]
+ if nzbpo_log in ('all', 'fine'):
+ print('[INFO] FILEBOT_OPTS = {0}'.format(nzbpo_filebotoptions))
+ print('[INFO] {0}'.format(args))
+ try:
+ with subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, bufsize=1, text=True) as process:
+ for line in process.stdout:
+ print('[INFO] {0}'.format(line), end='')
+ except FileNotFoundError as e:
+ print('[INFO] {0}'.format(e))
+ sys.exit(POSTPROCESS_ERROR)
+ sys.exit(POSTPROCESS_SUCCESS)
+
+
+if __name__ == '__main__':
+ main()
diff --git a/pool/shard006/Python/0057881_ksample.py b/pool/shard006/Python/0057881_ksample.py
new file mode 100644
index 0000000000000000000000000000000000000000..560773f6c9c112e882266e6441eb8052abe73036
--- /dev/null
+++ b/pool/shard006/Python/0057881_ksample.py
@@ -0,0 +1,250 @@
+"""
+K-sample permutation tests.
+"""
+
+
+import numpy as np
+from scipy.optimize import brentq, fsolve
+from scipy.stats import ttest_ind, ttest_1samp
+
+from .utils import get_prng, permute, permute_within_groups
+
+
+def k_sample(x, group, reps=10**5, stat='one-way anova',
+ keep_dist=False, seed=None, plus1=True):
+ r"""
+ k-sample permutation test for equality of more than 2 means,
+ with p-value estimated by simulated random sampling with
+ reps replications.
+
+ Tests the hypothesis that groupings are a random partition of x
+ against the alternative that at least one group comes from a
+ population with mean different from the rest
+
+ If ``keep_dist``, return the distribution of values of the test statistic;
+ otherwise, return only the number of permutations for which the value of
+ the test statistic and p-value.
+
+ Parameters
+ ----------
+ x : array-like
+ Sample values
+ group : array-like
+ Group labels for each observation
+ reps : int
+ number of repetitions
+ stat : {'one-way anova'}
+ The test statistic.
+
+ (a) If stat == 'one-way anova', use the sum of squared
+ distances between the group means and the overall mean
+ weighted by group size.
+ $\sum_{k=1}^K n_k(\overline{X_k} - \overline{X})^2$
+ keep_dist : bool
+ flag for whether to store and return the array of values
+ of the irr test statistic
+ seed : RandomState instance or {None, int, RandomState instance}
+ If None, the pseudorandom number generator is the RandomState
+ instance used by `np.random`;
+ If int, seed is the seed used by the random number generator;
+ If RandomState instance, seed is the pseudorandom number generator
+ plus1 : bool
+ flag for whether to add 1 to the numerator and denominator of the
+ p-value based on the empirical permutation distribution.
+ Default is True.
+
+ Returns
+ -------
+ float
+ the estimated p-value
+ float
+ the test statistic
+ list
+ The distribution of test statistics.
+ These values are only returned if `keep_dist` == True
+ """
+
+ prng = get_prng(seed)
+
+ # If stat is callable, use it as the test function. Otherwise, look in the
+ # dictionary
+ stats = {
+ "one-way anova" : one_way_anova
+ }
+ if callable(stat):
+ tst_fun = stat
+ else:
+ tst_fun = stats[stat]
+
+ xbar = np.mean(x)
+ observed_tst = tst_fun(x, group, xbar)
+
+ if keep_dist:
+ dist = np.empty(reps)
+ for i in range(reps):
+ group_perm = permute(group, prng)
+ dist[i] = tst_fun(x, group_perm, xbar)
+ pvalue = (plus1 + np.sum(dist >= observed_tst))/(plus1 + reps)
+ return pvalue, observed_tst, dist
+ else:
+ hits = 0
+ for i in range(reps):
+ group_perm = permute(group, prng)
+ tst = tst_fun(x, group_perm, xbar)
+ if tst >= observed_tst:
+ hits += 1
+ return (plus1 + hits)/(plus1 + reps), observed_tst
+
+
+def one_way_anova(x, group, overall_mean):
+ r"""
+ Test statistic for one-way ANOVA
+
+ Parameters
+ ----------
+ x : array-like
+ Sample values
+ group : array-like
+ Group labels for each observation
+ overall_mean : float
+ mean of x
+
+ Returns
+ -------
+ float
+ the one-way ANOVA statistic
+ $\sum_{k=1}^K n_k(\overline{X_k} - \overline{X})^2$
+ where $k$ indexes the groups
+ """
+ x = np.array(x)
+ tst = 0
+ for k in np.unique(group):
+ group_k = x[group == k]
+ group_mean = np.mean(group_k)
+ nk = len(group_k)
+ tst += (group_mean - overall_mean)**2 * nk
+ return tst
+
+
+def bivariate_k_sample(x, group1, group2, reps=10**5, stat='two-way anova',
+ keep_dist=False, seed=None, plus1=True):
+ r"""
+ k-sample permutation test for equality of more than 2 means,
+ with p-value estimated by simulated random sampling with
+ reps replications.
+
+ Tests the hypothesis that within grouping 1, grouping 2 is
+ a random partition of x against the alternative that at
+ least one group 2 comes from a population with mean different from the rest
+
+ If ``keep_dist``, return the distribution of values of the test statistic;
+ otherwise, return only the number of permutations for which the value of
+ the test statistic and p-value.
+
+ Parameters
+ ----------
+ x : array-like
+ Sample values
+ group1 : array-like
+ Fixed group labels for each observation
+ group2 : array-like
+ Group labels that, under the null, are exchangeable for each
+ level of group1
+ reps : int
+ number of repetitions
+ stat : {'two-way anova'}
+ The test statistic.
+;
+ (a) If stat == 'two-way anova', use a simpler statistic that
+ is permutationally equivalent to the F statistic:
+ $SSB/(SST - SSB).$
+ $SSB$ is the sum of squared deviations from the
+ overall mean for the group 2 means and $SST$ is
+ the sum of squared deviations of all observations
+ keep_dist : bool
+ flag for whether to store and return the array of values
+ of the irr test statistic
+ seed : RandomState instance or {None, int, RandomState instance}
+ If None, the pseudorandom number generator is the RandomState
+ instance used by `np.random`;
+ If int, seed is the seed used by the random number generator;
+ If RandomState instance, seed is the pseudorandom number generator
+ plus1 : bool
+ flag for whether to add 1 to the numerator and denominator of the
+ p-value based on the empirical permutation distribution.
+ Default is True.
+
+ Returns
+ -------
+ float
+ the estimated p-value
+ float
+ the test statistic
+ list
+ The distribution of test statistics.
+ These values are only returned if `keep_dist` == True
+ """
+
+ prng = get_prng(seed)
+
+ # If stat is callable, use it as the test function. Otherwise, look in the
+ # dictionary
+ stats = {
+ "two-way anova" : two_way_anova
+ }
+ if callable(stat):
+ tst_fun = stat
+ else:
+ tst_fun = stats[stat]
+
+ xbar = np.mean(x)
+ observed_tst = tst_fun(x, group1, group2, xbar)
+
+ if keep_dist:
+ dist = np.empty(reps)
+ for i in range(reps):
+ group2_perm = permute_within_groups(group2, group1, prng)
+ dist[i] = tst_fun(x, group1, group2_perm, xbar)
+ pvalue = (plus1 + np.sum(dist >= observed_tst))/(plus1 + reps)
+ return pvalue, observed_tst, dist
+ else:
+ hits = 0
+ for i in range(reps):
+ group2_perm = permute_within_groups(group2, group1, prng)
+ tst = tst_fun(x, group1, group2_perm, xbar)
+ if tst >= observed_tst:
+ hits += 1
+ return (plus1 + hits)/(plus1 + reps), observed_tst
+
+
+def two_way_anova(x, group1, group2, overall_mean):
+ """
+ Test statistic for two-way ANOVA. The test statistic
+ is permutationally equivalent to the F statistic.
+
+ Parameters
+ ----------
+ x : array-like
+ Sample values
+ group1 : array-like
+ Fixed group labels for each observation
+ group2 : array-like
+ Group labels that, under the null, are exchangeable for each
+ level of group1
+ overall_mean : float
+ mean of x
+
+ Returns
+ -------
+ float
+ the statistic $SSB/(SST - SSB),$ where
+ $SSB$ is the sum of squared deviations from the
+ overall mean for the group 2 means and $SST$ is
+ the sum of squared deviations of all observations
+ """
+ sst = np.sum((x - overall_mean)**2)
+ ss2 = 0
+ for g in np.unique(group2):
+ xx = x[group2 == g]
+ ss2 += (np.mean(xx) - overall_mean)**2
+ return ss2/(sst - ss2)
diff --git a/pool/shard006/Python/0057882_Databases.py b/pool/shard006/Python/0057882_Databases.py
new file mode 100644
index 0000000000000000000000000000000000000000..aa2c73e034c876fa108b73791439f00efc4f544d
--- /dev/null
+++ b/pool/shard006/Python/0057882_Databases.py
@@ -0,0 +1,221 @@
+#import os
+#os.environ['DYLD_LIBRARY_PATH'] = '/Library/PostgreSQL/9.5/lib'
+import psycopg2
+import time
+import itertools
+
+# Dictionary of database connections. Key is the database name (only within python relevant). Value is List of: [host, user, password, database, port]
+databaseSetups = {
+
+}
+
+
+class Database:
+
+ def __init__(self, setup):
+ '''
+ @param setup: string. Database Setup. Must match a key from the databaseSetups dictionary (see above)
+ Creates an connection to database
+ '''
+ self.setup = setup
+ self.db = self._getConnection()
+
+ def _getConnection(self):
+ '''
+ Returns database connection. Function checks if database connection is still alive and if this is not the case it automatically reconnects to database
+ @return: MySQLdb connection object
+ '''
+ try:
+ # check if database connection is still alive
+ db = self.db
+ cursor = db.cursor()
+ cursor.execute("SELECT VERSION()")
+ results = cursor.fetchone()
+
+ # if result is not empty connection is alive
+ if results:
+ return db
+ # create new connection
+ else:
+ connectionDetails = databaseSetups[self.setup]
+ self.db = psycopg2.connect(host = connectionDetails[0], user = connectionDetails[1], password = connectionDetails[2], database = connectionDetails[3], port = connectionDetails[4])
+ return self.db
+
+ except:
+ # if an exception occurs during checking if database connection is still alive create a new connection; if it's not possible to connect to Datbase Server wait 120 sec and try to connect again
+ reConnect = True
+ while reConnect is True:
+ try:
+ connectionDetails = databaseSetups[self.setup]
+ self.db = psycopg2.connect(host = connectionDetails[0], user = connectionDetails[1], password = connectionDetails[2], database = connectionDetails[3], port = connectionDetails[4])
+ reConnect = False
+ except:
+ time.sleep(120)
+ return self.db
+
+ def closeConnection(self):
+ '''
+ @summary: Closes connection to database
+ @author: JScelle
+ @version: 10.06.2013
+ '''
+ try:
+ self.db.close()
+ except:
+ # if closing of connection fails ignore it
+ pass
+
+ def getValuesFromTable(self, sqlQueryStatement):
+ '''
+ gets records from table
+ @param sqlQueryStatement: String, sql query statement e.g. "SELECT * FROM employee WHERE country = 'DE'"
+ @return: tuple of tuples
+ '''
+ # get database connection from runTimeController
+ try:
+ db = self.db
+ except Exception as exc:
+ print("EXCEPTION: Module: Database, Function: getValuesFromTable, Error: Could not get database connection. ", str(exc.args))
+ return ((),)
+
+ #excecute sql statement
+ try:
+ # prepare a cursor object using cursor() method
+ cursor = db.cursor()
+ # Execute the SQL command
+ cursor.execute(sqlQueryStatement)
+ # Fetch all the rows in a list of lists.
+ results = cursor.fetchall()
+ db.commit()
+ return results
+ except Exception as exc:
+ # Rollback in case there is any error
+ db.rollback()
+ print("EXCEPTION: Module: Database, Function: getValuesFromTable, Error: Could not execute query. ", str(exc.args))
+ return ((),)
+
+ def runQuery(self, sqlStatement):
+ '''
+ Executes any sql statement. For getting data from the database, please use the getValuesFromTable-method
+ @param sqlStatement: string. any sql statement e.g. Update, Delete
+ @return: Returns True if everything went good.
+ '''
+ # get database connection from runTimeController
+ try:
+ db = self.db
+ except Exception as exc:
+ print("EXCEPTION: Module: Database, Function: runQuery, Error: Could not get database connection. ", str(exc.args))
+ return False
+
+ #excecute sql statement
+ try:
+ # prepare a cursor object using cursor() method
+ cursor = db.cursor()
+ # Execute the SQL command
+ cursor.execute(sqlStatement)
+ # Commit your changes in the Settings.database
+ db.commit()
+ return True
+ except Exception as exc:
+ # Rollback in case there is any error
+ db.rollback()
+ print("EXCEPTION: Module: Database, Function: runQuery, Error: Could not execute query. ", str(exc.args))
+ return False
+
+ def runMultipleQueries(self, sqlStatements):
+ """
+ Executes multiple SQL-statements as one transaction
+ @param sqlStatements: List of strings. Each String is one SQL-statement
+ @return: Returns True if everything went good.
+ """
+ # get database connection from runTimeController
+ try:
+ db = self.db
+ except Exception as exc:
+ print("EXCEPTION: Module: Database, Function: runMultipleQueries, Error: Could not get database connection. ", str(exc.args))
+ return False
+
+ # excecute sql statement
+ try:
+ # prepare a cursor object using cursor() method
+ cursor = db.cursor()
+ for sqlStatement in sqlStatements:
+ # Execute the SQL command
+ cursor.execute(sqlStatement)
+ # Commit your changes in the Settings.database
+ db.commit()
+ return True
+ except Exception as exc:
+ # Rollback in case there is any error
+ db.rollback()
+ print("EXCEPTION: Module: Database, Function: runMultipleQueries, Error: One of the queries could not be executed. ", str(exc.args))
+ return False
+
+
+ def insertValuesIntoTable(self, tableName, fieldList, valueList):
+ """
+ calls _executeInsertValuesIntoTable which inserts values into table
+ @param tableName: String, name of table
+ @param fieldList: List of string, list of field names e.g ,["firstName", "lastName"]
+ @param valueList: List of list, e.g [["Sebastian", "Stuetz"],["Ingo", "Tschach"]]
+ @return: Returns True if everything went good.
+ """
+ try:
+ #define INSERT INTO part of sql query
+ insertIntoSqlPart = "INSERT INTO " + tableName + " (" + ",".join(fieldList) + ") VALUES"
+ #define ON DUPLICATE KEY part of sql query
+ onDuplicateKeyPart = " ON DUPLICATE KEY UPDATE "
+ for field in fieldList:
+ #replace old values with new values
+ onDuplicateKeyPart += str(field) + " = VALUES(" + str(field) + "), "
+ onDuplicateKeyPart = onDuplicateKeyPart[0:(len(onDuplicateKeyPart) - 2)]
+
+ return self._executeInsertValuesIntoTable(fieldList, valueList, insertIntoSqlPart, onDuplicateKeyPart)
+
+ except Exception as exc:
+ print("EXCEPTION: Module: Database, Function: insertValuesIntoTable, Error: Error when building the query frame. ", str(exc.args))
+ return False
+
+
+ def _executeInsertValuesIntoTable(self, fieldList, valueList, insertIntoSqlPart, onDuplicateKeyPart):
+ '''
+ inserts values into table
+ @param fieldList: List, list of field names e.g ,["firstName", "lastName"]
+ @param valueList: List of list, e.g [["Sebastian", "Stuetz"],["Ingo", "Tschach"]]
+ @return: Returns True if everything went good.
+ '''
+ # get database connection from runTimeController
+ try:
+ db = self.db
+ except Exception as exc:
+ print("EXCEPTION: Module: Database, Function: _executeInsertValuesIntoTable, Error: Could not get database connection. ", str(exc.args))
+ return False
+
+ try:
+ # prepare a cursor object using cursor() method
+ cursor = db.cursor()
+
+ #Insert data
+ #divide valueList into chunks to avoid that too big packets are send to sql server
+ maxPackets = 5000
+ for i in range(0, len(valueList), maxPackets):
+ chunk = valueList[i:i + maxPackets]
+ #define data part of sql query (string consisting of "%s" for each field for each row)
+ dataSqlPart = ",".join(["(" + ",".join(["%s"] * len(fieldList)) + ")"] * len(chunk))
+ #put sql parts together
+ sql = insertIntoSqlPart + dataSqlPart + onDuplicateKeyPart
+ #flatten data list
+ valueListChunk = tuple(itertools.chain(*chunk))
+ #Insert values into DB
+ cursor.execute(sql, valueListChunk)
+
+ # Commit your changes in the Settings.database
+ db.commit()
+
+ return True
+ except Exception as exc:
+ # Rollback in case there is any error
+ db.rollback()
+ print("EXCEPTION: Module: Database, Function: _executeInsertValuesIntoTable, Error: Could not insert values. ", str(exc.args))
+ return False
+
diff --git a/pool/shard006/Python/0057887_swarp.py b/pool/shard006/Python/0057887_swarp.py
new file mode 100644
index 0000000000000000000000000000000000000000..99773e3afd0a1c153b4c680ecde907834b8c6dc5
--- /dev/null
+++ b/pool/shard006/Python/0057887_swarp.py
@@ -0,0 +1,128 @@
+# -*- coding: utf-8 -*-
+"""
+Created on Thu Jul 27 16:39:59 2017
+
+@author: asadm2
+"""
+### DESCRIPTION
+#This script uses swarp to combine images taken using the same filter. Image
+#data is updated, zeropoint is scaled to 30, units are all set to counts/s.
+#The percentage of the coadd that's blank i.e. pixel value = 0 is calculated.
+
+from __future__ import division, print_function, absolute_import
+from astropy.io import fits
+import pandas as pd
+import numpy as np
+import subprocess
+import imp
+import os
+
+#Importing modules that are used in this script
+foo = imp.load_source('ECO_funcs', '../mods_swarp/ECO_funcs.py')
+
+### Paths
+path_to_raw = '/fs1/masad/Research/Repositories/ECO_Globular_Clusters/'\
+'data/raw/'
+path_to_interim = '/fs1/masad/Research/Repositories/ECO_Globular_Clusters/'\
+'data/interim/'
+
+#If re-running script then these files have to be removed since
+#they are being opened in 'append' mode in ECO_funcs.py
+if os.path.isfile(path_to_interim + 'Error_swarp.txt'):
+ os.remove(path_to_interim + 'Error_swarp.txt')
+if os.path.isfile(path_to_interim + 'percent_blankv2.txt'):
+ os.remove(path_to_interim + 'percent_blankv2.txt')
+
+#Formatted ECO catalog with filters and new_filename column and list of
+#good ECO objects
+ECOnew = path_to_interim + 'ECO_formatted.txt'
+goodObj = path_to_interim + 'goodObjv2.txt'
+
+#Using the make_dict function to return a dictionary whose keys are ECOID and
+#filter name and whose values are filenames, return the list of sorted keys,
+#and the formatted ECO catalog
+ECO_dict,ECO_keys,ECOcat = foo.make_dict(ECOnew,goodObj)
+
+for index,key in enumerate(ECO_keys):
+ print('Key {0}/{1}'.format(index+1,len(ECO_keys)))
+ obj = key[0]
+ filter_i = key[1]
+ print('Object: {0} and filter: {1}'.format(obj,filter_i))
+ dir_path = os.getcwd()
+ #Since this file is in src/ and we need to access the images we have to
+ #move to the data/raw folder the first time this code runs
+ if os.path.basename(dir_path) == 'main':
+ os.chdir(path_to_raw + obj)
+ #After the first time all that has to be done is to move out of the
+ #interim ECO object dir and into the raw ECO object dir
+ elif os.path.basename(dir_path) != obj:
+ os.chdir(path_to_raw + obj)
+ #Using the ECOID,filter key to acess the values in the new_filename column
+ #i.e. get a list of the images associated with this key pair
+ print("Getting images from catalog")
+ imgs_from_cat = ECO_dict.get_group(key)['new_filename'].values
+
+ #Images from prelim_checks_3 that passed the "object-in-image" check
+ #as well as the non-zero pixel value check
+ print("Getting images from text file")
+ goodimagesfile = obj+'_goodimages.txt'
+ goodimages = pd.read_csv(goodimagesfile,header=None,names=['filenames'])
+ imgs_from_txt = goodimages.values
+
+ #Common images between full list from catalog and good imaging left
+ print("Common images are")
+ imgs = []
+ for img in imgs_from_cat:
+ if img in imgs_from_txt:
+ print(img)
+ img = img + '.fits'
+ imgs.append(img)
+
+ #Using the update_header function to output the name of the text file
+ #that contains the names of the new versions of the fits images being
+ #input into the function
+ img_list_txt = foo.update_header(imgs,obj,filter_i)
+
+ #To check for case where all images were in Except clause of update_header
+ #and run swarp even for single images
+ if len(imgs) >= 1 and img_list_txt != 'error':
+ ra = np.unique(ECOcat.RA.loc[ECOcat.ECOID==obj])[0]
+ dec = np.unique(ECOcat.DEC.loc[ECOcat.ECOID==obj])[0]
+
+ #Running swarp with parameters. The only ones that change are the list
+ #of images, the RA and DEC of the object, the object name and the
+ #filter name
+ print('Starting to swarp')
+ subprocess.call(['swarp','@'+img_list_txt,'-CENTER_TYPE','MANUAL', \
+ '-CENTER',str(ra)+","+str(dec),'-NTHREADS','32', '-COPY_KEYWORDS', \
+ 'PHOTFLAM,MAGZPT,PHOTPLAM','-FSCALASTRO_TYPE','VARIABLE',\
+ '-COMBINE_BUFSIZE','10000','-MEM_MAX','1000','-VMEM_MAX','5000',\
+ '-IMAGE_SIZE','3960','-PIXELSCALE_TYPE','MANUAL','-PIXEL_SCALE',\
+ '0.05','-GAIN_KEYWORD','CCDGAIN','-GAIN_DEFAULT','1.0',\
+ '-SUBTRACT_BACK','Y','-IMAGEOUT_NAME',\
+ obj+'_'+filter_i+'_'+'coadd.fits','-WEIGHTOUT_NAME',\
+ obj+'_'+filter_i+'_'+'coadd.weight.fits','-XML_NAME',\
+ obj+'_'+filter_i+'_'+'swarp.xml'])
+ print('Finished swarping')
+
+ coadd = fits.open(obj+'_'+filter_i+'_'+'coadd.fits')
+ #Open the coadd and use the percent_blank function
+ foo.percent_blank(coadd,obj,filter_i)
+ #So that you can distinguish between interim object folder and raw
+ #object filder
+
+ else:
+ os.chdir('..') # Moving one level up when no imgs are found
+
+ #If the length of imgs is 1 then check if the new version that
+ #update_header function creates exists. If it does then calculate blank
+ #percentage. If the length is 0 i.e. since the original ECO catalog is
+ #being used some ECOID, filter pairs no longer exist since they were
+ #eliminated in preliminary exptime and >2filter checks so for those pairs
+ #the files won't exist. They are ignored which is why percent_blank doesn't
+ #print anything to the terminal.
+# else:
+# filename = imgs[0]+'_test_'+filter_i+'.fits'
+# if os.path.exists(filename): #avoid empty cases where files don't exist
+# single_img = fits.open(filename)
+# foo.percent_blank(single_img,obj,filter_i)
\ No newline at end of file
diff --git a/pool/shard006/Python/0057894_runners.py b/pool/shard006/Python/0057894_runners.py
new file mode 100644
index 0000000000000000000000000000000000000000..4659304a1ea8f9ebd0bcbb4d257a2d6c379bc092
--- /dev/null
+++ b/pool/shard006/Python/0057894_runners.py
@@ -0,0 +1,72 @@
+__all__ = 'run',
+
+from . import coroutines
+from . import events
+from . import tasks
+
+
+def run(main, *, debug=False):
+ """Execute the coroutine and return the result.
+
+ This function runs the passed coroutine, taking care of
+ managing the asyncio event loop and finalizing asynchronous
+ generators.
+
+ This function cannot be called when another asyncio event loop is
+ running in the same thread.
+
+ If debug is True, the event loop will be run in debug mode.
+
+ This function always creates a new event loop and closes it at the end.
+ It should be used as a main entry point for asyncio programs, and should
+ ideally only be called once.
+
+ Example:
+
+ async def main():
+ await asyncio.sleep(1)
+ print('hello')
+
+ asyncio.run(main())
+ """
+ if events._get_running_loop() is not None:
+ raise RuntimeError(
+ "asyncio.run() cannot be called from a running event loop")
+
+ if not coroutines.iscoroutine(main):
+ raise ValueError("a coroutine was expected, got {!r}".format(main))
+
+ loop = events.new_event_loop()
+ try:
+ events.set_event_loop(loop)
+ loop.set_debug(debug)
+ return loop.run_until_complete(main)
+ finally:
+ try:
+ _cancel_all_tasks(loop)
+ loop.run_until_complete(loop.shutdown_asyncgens())
+ finally:
+ events.set_event_loop(None)
+ loop.close()
+
+
+def _cancel_all_tasks(loop):
+ to_cancel = tasks.all_tasks(loop)
+ if not to_cancel:
+ return
+
+ for task in to_cancel:
+ task.cancel()
+
+ loop.run_until_complete(
+ tasks.gather(*to_cancel, loop=loop, return_exceptions=True))
+
+ for task in to_cancel:
+ if task.cancelled():
+ continue
+ if task.exception() is not None:
+ loop.call_exception_handler({
+ 'message': 'unhandled exception during asyncio.run() shutdown',
+ 'exception': task.exception(),
+ 'task': task,
+ })
diff --git a/pool/shard006/Python/0057898_init__.py b/pool/shard006/Python/0057898_init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..15e618e03c0d3e4878030beea994581bccc84aed
--- /dev/null
+++ b/pool/shard006/Python/0057898_init__.py
@@ -0,0 +1,28 @@
+"""Phpsploit framework core loader.
+
+This pseudo module is designed to be imported (import lib) from
+the phpsploit script launcher (./phpsploit).
+It also can be imported from phpsploit root directory through a
+python interpreter for debugging purposes.
+
+It loads the phpsploit core & overwrites sys.path's first element to
+the current directory (./lib/), making all self contained elements
+directly importable from python.
+
+"""
+import os
+import sys
+
+from . import utils
+
+BASEDIR = utils.path.truepath(sys.path[0]) + os.sep
+COREDIR = os.path.join(BASEDIR, __name__) + os.sep
+
+# use current directory as main python path
+sys.path[0] = COREDIR
+
+# add src/core/shnake-0.5/ to python path
+shnake_path = os.path.join(COREDIR, "shnake-0.5") + os.sep
+sys.path.insert(0, shnake_path)
+
+del sys, os, shnake_path # clean package's content
diff --git a/pool/shard006/Python/0057900_mysql.py b/pool/shard006/Python/0057900_mysql.py
new file mode 100644
index 0000000000000000000000000000000000000000..39db654cdfcf5d6deffdc248696266649f141b00
--- /dev/null
+++ b/pool/shard006/Python/0057900_mysql.py
@@ -0,0 +1,67 @@
+import MySQLdb as mdb
+import os
+import re
+import base64
+
+class MysqlEngine:
+ PASSWORD_LENGTH = 10
+ """
+ Create databases and users and manage cloning and dumping of
+ databases.
+ """
+ def __init__(self, host, user, password):
+ self.engine_name = "mysql"
+ self.host = host
+ self.user = user
+ self.password = password
+
+ def create_connection(self, database=""):
+ return mdb.connect(host=self.host, user=self.user, passwd=self.password, db=database)
+
+
+ def verify_site(self, site):
+ safe_name = re.sub(r"[^a-zA-Z]*", "", site.name).lower()
+ if not hasattr(site, "database"):
+ site.database = {}
+ if not "name" in site.database:
+ site.database["name"] = safe_name
+ if not "password" in site.database:
+ site.database["password"] = base64.urlsafe_b64encode(os.urandom(self.PASSWORD_LENGTH))
+ if not "user" in site.database:
+ site.database["user"] = safe_name
+ if not "host" in site.database:
+ site.database["host"] = site.platform.server.hostname
+ self.create_database(site.database["name"])
+ self.create_user(site.database["name"], site.database["password"])
+ self.grant_privileges(site.database["name"], site.database["user"], site.database["host"], site.database["password"])
+
+ def create_database(self, name):
+ db = self.create_connection()
+ with db:
+ cursor = db.cursor()
+ if not self._database_exists(cursor, name):
+ cursor.execute("CREATE DATABASE IF NOT EXISTS {0}".format(name))
+
+ def create_user(self, name, password):
+ db = self.create_connection("mysql")
+ with db:
+ cursor = db.cursor()
+ cursor.execute("SELECT count(User) FROM user WHERE User = %s", (name))
+ if cursor.fetchone() == 0:
+ cursor.execute("CREATE USER {0} IDENTIFIED BY '{1}'".format(name, password))
+
+ def grant_privileges(self, database, username, host, password):
+ db = self.create_connection()
+ with db:
+ cursor = db.cursor()
+ cursor.execute("GRANT ALL PRIVILEGES ON {0}.* TO '{1}'@'{2}' IDENTIFIED BY '{3}'".format(database, username, host, password))
+
+ def close_conection(self):
+ self.db.close()
+
+ def _database_exists(self, cursor, database):
+ cursor.execute("SHOW DATABASES")
+ for row in cursor.fetchall():
+ if row[0] == database:
+ return True
+ return False
diff --git a/pool/shard006/Python/0057902_io.py b/pool/shard006/Python/0057902_io.py
new file mode 100644
index 0000000000000000000000000000000000000000..fb729af5cdf27efdaeaed79b5b7ad1eae2d5c4ea
--- /dev/null
+++ b/pool/shard006/Python/0057902_io.py
@@ -0,0 +1,34 @@
+import os
+
+# TODO: use biopython
+
+
+def make_part(part):
+ name = part.get('name')
+ desc = part.get('description')
+ seq = part.get('sequence')
+
+ if name is None:
+ return
+
+ desc_line = ' ({})'.format(desc) if desc is not None else ''
+
+ if not os.path.exists(name):
+ os.makedirs(name)
+
+ fasta = '>{}{}\n{}'.format(name, desc_line, seq)
+ with open('{}/sequence.fasta'.format(name), 'w') as f:
+ f.write(fasta)
+
+
+def read_part():
+ with open('sequence.fasta', 'r') as f:
+ fasta = f.read()
+ line1, seq = fasta.split('\n', 1)
+ if ' ' in line1:
+ name = line1[1: line1.find(' ')]
+ desc = line1[line1.find('('): line1.find(')')]
+ else:
+ name = line1[1:]
+ desc = None
+ return {'name': name, 'description': desc, 'sequence': seq}
diff --git a/pool/shard006/Python/0057904_master_perf_cfg.py b/pool/shard006/Python/0057904_master_perf_cfg.py
new file mode 100644
index 0000000000000000000000000000000000000000..ec41bdc871b17285bf302179be52241c2f859b9e
--- /dev/null
+++ b/pool/shard006/Python/0057904_master_perf_cfg.py
@@ -0,0 +1,44 @@
+# Copyright 2014 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.
+
+from master import master_config
+from master.factory import annotator_factory, chromeos_factory
+
+from buildbot.schedulers.basic import SingleBranchScheduler as Scheduler
+
+def Builder(factory_obj, board):
+ config = '%s-telemetry' % (board,)
+ builder = {
+ 'name': config,
+ 'builddir': config,
+ 'category': '5chromiumos perf',
+ 'factory': chromeos_factory.ChromiteRecipeFactory(
+ factory_obj, 'cros/cbuildbot'),
+ 'gatekeeper': 'crosperf',
+ 'scheduler': 'chromium_src_perf',
+ 'notify_on_missing': True,
+ 'properties': {
+ 'cbb_config': config,
+ },
+ }
+ return builder
+
+
+def Update(_config, active_master, c):
+ factory_obj = annotator_factory.AnnotatorFactory(
+ active_master=active_master)
+
+ builders = [
+ Builder(factory_obj, 'x86-generic'),
+ Builder(factory_obj, 'amd64-generic'),
+ ]
+
+ c['schedulers'] += [
+ Scheduler(name='chromium_src_perf',
+ branch='master',
+ treeStableTimer=60,
+ builderNames=[b['name'] for b in builders],
+ ),
+ ]
+ c['builders'] += builders
diff --git a/pool/shard006/Python/0057905_run_regression_tests.py b/pool/shard006/Python/0057905_run_regression_tests.py
new file mode 100644
index 0000000000000000000000000000000000000000..a21208b644ea72ee42e21bb51b9b5aeb37d87cc4
--- /dev/null
+++ b/pool/shard006/Python/0057905_run_regression_tests.py
@@ -0,0 +1,139 @@
+#!/usr/bin/env python
+# Runs one or more regression tests. Retries tests up to 3 times.
+#
+# Example usage:
+# $ python run_regression_tests.py regression-tests/cartpole-es-[tf|torch].yaml
+#
+# When using in BAZEL (with py_test), e.g. see in ray/rllib/BUILD:
+# py_test(
+# name = "run_regression_tests",
+# main = "tests/run_regression_tests.py",
+# tags = ["learning_tests"],
+# size = "medium", # 5min timeout
+# srcs = ["tests/run_regression_tests.py"],
+# data = glob(["tuned_examples/regression_tests/*.yaml"]),
+# # Pass `BAZEL` option and the path to look for yaml regression files.
+# args = ["BAZEL", "tuned_examples/regression_tests"]
+# )
+
+import argparse
+import os
+from pathlib import Path
+import sys
+import yaml
+
+import ray
+from ray.tune import run_experiments
+from ray.rllib import _register_all
+from ray.rllib.utils.deprecation import deprecation_warning
+
+parser = argparse.ArgumentParser()
+parser.add_argument(
+ "--framework",
+ choices=["jax", "tf2", "tf", "tfe", "torch"],
+ default="tf",
+ help="The deep learning framework to use.")
+parser.add_argument(
+ "--yaml-dir",
+ type=str,
+ required=True,
+ help="The directory in which to find all yamls to test.")
+parser.add_argument(
+ "--local-mode",
+ action="store_true",
+ help="Run ray in local mode for easier debugging.")
+
+# Obsoleted arg, use --framework=torch instead.
+parser.add_argument(
+ "--torch",
+ action="store_true",
+ help="Runs all tests with PyTorch enabled.")
+
+if __name__ == "__main__":
+ args = parser.parse_args()
+
+ # Bazel regression test mode: Get path to look for yaml files.
+ # Get the path or single file to use.
+ rllib_dir = Path(__file__).parent.parent
+ print("rllib dir={}".format(rllib_dir))
+
+ abs_yaml_path = os.path.join(rllib_dir, args.yaml_dir)
+ # Single file given.
+ if os.path.isfile(abs_yaml_path):
+ yaml_files = [abs_yaml_path]
+ # Given path/file does not exist.
+ elif not os.path.isdir(abs_yaml_path):
+ raise ValueError("yaml-dir ({}) not found!".format(args.yaml_dir))
+ # Path given -> Get all yaml files in there via rglob.
+ else:
+ yaml_files = rllib_dir.rglob(args.yaml_dir + "/*.yaml")
+ yaml_files = sorted(
+ map(lambda path: str(path.absolute()), yaml_files), reverse=True)
+
+ print("Will run the following regression tests:")
+ for yaml_file in yaml_files:
+ print("->", yaml_file)
+
+ # Loop through all collected files.
+ for yaml_file in yaml_files:
+ experiments = yaml.load(open(yaml_file).read())
+ assert len(experiments) == 1,\
+ "Error, can only run a single experiment per yaml file!"
+
+ # Add torch option to exp config.
+ exp = list(experiments.values())[0]
+ exp["config"]["framework"] = args.framework
+ if args.torch:
+ deprecation_warning(old="--torch", new="--framework=torch")
+ exp["config"]["framework"] = "torch"
+ args.framework = "torch"
+
+ # Print out the actual config.
+ print("== Test config ==")
+ print(yaml.dump(experiments))
+
+ # Try running each test 3 times and make sure it reaches the given
+ # reward.
+ passed = False
+ for i in range(3):
+ try:
+ ray.init(num_cpus=5, local_mode=args.local_mode)
+ trials = run_experiments(experiments, resume=False, verbose=2)
+ finally:
+ ray.shutdown()
+ _register_all()
+
+ for t in trials:
+ # If we have evaluation workers, use their rewards.
+ # This is useful for offline learning tests, where
+ # we evaluate against an actual environment.
+ check_eval = \
+ exp["config"].get("evaluation_interval", None) is not None
+ reward_mean = \
+ t.last_result["evaluation"]["episode_reward_mean"] if \
+ check_eval else t.last_result["episode_reward_mean"]
+
+ # If we are using evaluation workers, we may have
+ # a stopping criterion under the "evaluation/" scope. If
+ # not, use `episode_reward_mean`.
+ if check_eval:
+ min_reward = t.stopping_criterion.get(
+ "evaluation/episode_reward_mean",
+ t.stopping_criterion.get("episode_reward_mean"))
+ # Otherwise, expect `episode_reward_mean` to be set.
+ else:
+ min_reward = t.stopping_criterion["episode_reward_mean"]
+
+ if reward_mean >= min_reward:
+ passed = True
+ break
+
+ if passed:
+ print("Regression test PASSED")
+ break
+ else:
+ print("Regression test FAILED on attempt {}".format(i + 1))
+
+ if not passed:
+ print("Overall regression FAILED: Exiting with Error.")
+ sys.exit(1)
diff --git a/pool/shard006/Python/0057906_views.py b/pool/shard006/Python/0057906_views.py
new file mode 100644
index 0000000000000000000000000000000000000000..e7acdd032f165808a4850ca0e0cd955e4a83205c
--- /dev/null
+++ b/pool/shard006/Python/0057906_views.py
@@ -0,0 +1,28 @@
+import logging
+from django.shortcuts import render
+
+# Create your views here.
+
+logger = logging.getLogger(__name__)
+
+
+def timetable_landing(request):
+ logger.info(request)
+ feature_list = (
+ {'icon': 'img/glasses2.svg', 'description': ('Перегляд розкладу '
+ 'групи (дізнайся, яка зараз пара)'), 'class': 'feature-block'},
+ {'icon': 'img/edit45.svg', 'description': ('Редагування розкладу '
+ '(доступне командирам груп)'), 'class': 'feature-block'},
+ {'icon': 'img/school84.svg', 'description': ('Перегляд розкладу'
+ ' викладача'), 'class': 'feature-block'},
+ {'icon': 'img/checkmark2.svg', 'description': ('Перегляд графіку '
+ 'екзаменів та практики'), 'class': 'feature-block'},
+ {'icon': 'img/sun127.svg', 'description': 'Канікули',
+ 'class': 'feature-block'},
+ )
+ return render(request, 'landing/promo.html',
+ {'feature_list': feature_list})
+
+
+def timetable_about(request):
+ return render(request, 'landing/about.html')
diff --git a/pool/shard006/Python/0057907_ordenacion.py b/pool/shard006/Python/0057907_ordenacion.py
new file mode 100644
index 0000000000000000000000000000000000000000..2931f457581d23bd2c313f57fd8322c9aeabc606
--- /dev/null
+++ b/pool/shard006/Python/0057907_ordenacion.py
@@ -0,0 +1,117 @@
+#!/usr/bin/python
+# -*- coding: utf-8 -*-
+
+# Practicas de Desarrollo de Aplicaciones para Internet (DAI)
+# Copyright (C) 2013 - Zerjillo (zerjioi@ugr.es)
+#
+# 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 .
+
+import random
+
+
+# Ordenacion burbuja
+def burbuja(lista):
+ for i in range(len(lista)):
+ for h in range(i, len(lista) - 1):
+ if (lista[h] > lista[h+1]):
+ aux = lista[h]
+ lista[h] = lista[h + 1]
+ lista[h + 1] = aux
+
+
+# Ordenacion burbuja con posible salida antes de tiempo
+def burbujaMejorada(lista):
+ for i in range(len(lista)):
+ cambio = False
+ for h in range(i, len(lista) - 1):
+ if (lista[h] > lista[h+1]):
+ aux = lista[h]
+ lista[h] = lista[h + 1]
+ lista[h + 1] = aux
+ cambio = True
+
+ if not cambio:
+ return
+
+# Ordenacion por reemplazo
+def reemplazo(lista):
+ for i in range(len(lista) - 1):
+ currentPos = i
+
+ for h in range(i + 1, len(lista)):
+ if (lista[h] < lista[currentPos]):
+ currentPos = h
+
+ aux = lista[i]
+ lista[i] = lista[currentPos]
+ lista[currentPos] = aux
+
+def mergeSort(lista):
+ listaTrabajo = list(lista)
+
+ mergeSort2(lista, 0, len(lista) - 1, listaTrabajo)
+
+
+
+
+def mergeSort2(lista, i1, i2, listaTrabajo):
+ if (i1 == i2): # Si un solo elemento, volvemos sin mas
+ return
+
+ medio = (i1 + i2) / 2
+
+ mergeSort2(lista, i1, medio, listaTrabajo) # Ordenamos la primera mitad (llamada recursiva!)
+ mergeSort2(lista, medio + 1, i2, listaTrabajo) # Ordenamos la segunda mitad (llamada recursiva!)
+
+ # Las dos mitades están cada una ordenada
+
+ punt1 = i1
+ punt2 = medio + 1
+ puntB = i1
+
+# Mergueamos
+
+ while ( (punt1 <= medio) and (punt2 <= i2) ):
+ if (lista[punt1] < lista[punt2]):
+ listaTrabajo[puntB] = lista[punt1]
+ punt1 += 1
+ else:
+ listaTrabajo[puntB] = lista[punt2]
+ punt2 += 1
+
+ puntB += 1
+
+ for i in range(punt1, medio + 1): # Terminamos de copiar los que queden en la primera mitad
+ listaTrabajo[puntB] = lista[i]
+ puntB += 1
+
+ for i in range(punt2, i2 + 1): # Terminamos de copiar los que queden en la segunda mitad
+ listaTrabajo[puntB] = lista[i]
+ puntB += 1
+
+ for i in range(i1, i2 + 1): # Copiamos el trozo en la original
+ lista[i] = listaTrabajo[i]
+
+
+
+# Genera una lista de numeros aleatorios
+def generaListaAleatoria():
+ tamanioLista = 10000;
+
+ lista = []
+
+ for i in range(tamanioLista):
+ lista.append(random.randint(0, 10000000));
+
+ return lista
\ No newline at end of file
diff --git a/pool/shard006/Python/0057916_views.py b/pool/shard006/Python/0057916_views.py
new file mode 100644
index 0000000000000000000000000000000000000000..2fd5db44f2f530d7da06f45ee99609c2ce62d58f
--- /dev/null
+++ b/pool/shard006/Python/0057916_views.py
@@ -0,0 +1,178 @@
+"""
+This Photo Roster LTI tool was build using the HUIT TLT bootstrap_lit_django
+basic lti app from
+https://github.com/penzance/bootstrap_lit_django
+
+This tool was adaped for use by:
+Matthew Coser
+IT Systems Coordinator
+Harvard Kennedy School
+Executive Education
+matthew_coser@hks.harvard.edu
+617-496-0319
+
+This Canvas Photo Roster Tool can be re-worked and re-distributed as you wish
+please credit the above parties.
+
+
+"""
+
+
+from django.shortcuts import (render, redirect)
+from django.views.decorators.http import require_http_methods
+from django.contrib.auth.decorators import login_required
+from django.core.urlresolvers import reverse
+from django.conf import settings
+from ims_lti_py.tool_config import ToolConfig
+from django.http import HttpResponse
+from canvas_sdk.methods import enrollments
+from canvas_sdk.methods import courses
+from canvas_sdk.methods import users
+from canvas_sdk.utils import get_all_list_data
+from canvas_sdk.exceptions import CanvasAPIError
+from canvas_sdk import RequestContext
+import logging
+
+logger = logging.getLogger(__name__)
+
+
+
+
+SDK_CONTEXT = request_context = RequestContext(**settings.CANVAS_SDK_SETTINGS)
+
+TOOL_NAME = "canvasPR_app"
+
+@require_http_methods(['GET'])
+def index(request):
+ """
+ Show the index file
+ """
+ return render(request, 'canvasPR_app/index.html')
+
+@login_required()
+@require_http_methods(['POST'])
+def lti_launch(request):
+ """
+ This method is here to build the LTI_LAUNCH dictionary containing all
+ the LTI parameters and place it into the session. This is nessesary as we
+ need to access these parameters throughout the application and they are only
+ available the first time the application loads.
+ """
+ if request.user.is_authenticated():
+ return redirect('canvasPR_app:main')
+ else:
+ return render(request, 'canvasPR_app/error.html', {'message': 'Error: user is not authenticated!'})
+
+@login_required()
+@require_http_methods(['GET'])
+def main(request):
+
+
+
+ #get the course ID of current course
+ canvas_course_id = request.session['LTI_LAUNCH'].get('custom_canvas_course_id')
+ logger.debug('////////////////////////////////////>')
+ logger.debug('canvas_course_id=%s' % canvas_course_id)
+ logger.debug('////////////////////////////////////>')
+
+
+ #call to get course name for roster header
+ canvas_course_name = get_all_list_data(SDK_CONTEXT, courses.get_single_course_courses, canvas_course_id, "all_courses")
+ logger.debug('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~>')
+ logger.debug(canvas_course_name)
+ logger.debug('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~>')
+
+ #get a list of STUDENTS in the current course, we will use only the user_id from the list
+ #the 'avatar_url' is just a required option, and we will actually use the avatar_url from the profile list below
+ enrollmentGet = {}
+ try:
+ enrollmentGet = get_all_list_data(SDK_CONTEXT, courses.list_users_in_course_users, canvas_course_id, 'avatar_url', enrollment_type='student')
+ except CanvasAPIError as api_error:
+ logger.debug((canvas_course_id, api_error))
+
+ #get a list of TEACHERS in the current course. Should be automatically hidden with js in lti_view.thml, and can be toggled with a switch
+ faculty = {}
+ try:
+ faculty = get_all_list_data(SDK_CONTEXT, courses.list_users_in_course_users, canvas_course_id, 'avatar_url', enrollment_type='teacher')
+ except CanvasAPIError as api_error:
+ logger.debug((canvas_course_id, api_error))
+
+ #for each student user in the course, get their user_id
+ userID = []
+ for d in enrollmentGet:
+ userIdSingle = d['id']
+ userID.append(userIdSingle)
+ logger.debug('*********************************************>')
+ logger.debug('userID=%s' %userID)
+ logger.debug('*********************************************>')
+
+ facultyID = []
+ for d in faculty:
+ facultyIdSingle = d['id']
+ facultyID.append(facultyIdSingle)
+ logger.debug('++++++++++++++++++++++++++++++++++++++++++++++++>')
+ logger.debug('facultyID=%s' %facultyID)
+ logger.debug('++++++++++++++++++++++++++++++++++++++++++++++++>')
+
+
+ #Run the user profile call for each student user_id we just got,
+ #and use what we need in the html
+ userGet = []
+ for l in userID:
+ try:
+ studentFull = get_all_list_data(SDK_CONTEXT, users.get_user_profile, l)
+ userGet.append(studentFull)
+ except CanvasAPIError as api_error:
+ logger.debug('CanvasAPIError in get_all_list_data enrollments.list_enrollments_courses call for canvas_course_id=%s. Exception=%s:' % (canvas_course_id, api_error))
+
+ facultyGet = []
+ for l in facultyID:
+ try:
+ facultyFull = get_all_list_data(SDK_CONTEXT, users.get_user_profile, l)
+ facultyGet.append(facultyFull)
+ except CanvasAPIError as api_error:
+ logger.debug('CanvasAPIError in get_all_list_data enrollments.list_enrollments_courses call for canvas_course_id=%s. Exception=%s:' % (canvas_course_id, api_error))
+
+
+
+ #dictionary definitions for the lti_view html
+ return render(request, 'canvasPR_app/lti_view.html', {'request': request, 'pages': enrollmentGet, 'userGet': userGet, 'facultyGet': facultyGet, 'courseName': canvas_course_name})
+
+
+
+
+
+
+
+
+@require_http_methods(['GET'])
+def tool_config(request):
+ """
+ This produces a Canvas specific XML config that can be used to
+ add this tool to the Canvas LMS
+ """
+ if request.is_secure():
+ host = 'https://' + request.get_host()
+ else:
+ host = 'http://' + request.get_host()
+
+ url = host + reverse('canvasPR_app:lti_launch')
+
+ lti_tool_config = ToolConfig(
+ title='Photo Roster - Test',
+ launch_url=url,
+ secure_launch_url=url,
+ )
+ account_nav_params = {
+ 'enabled': 'true',
+ 'visibility': 'admins',
+ # optionally, supply a different URL for the link:
+ # 'url': 'http://library.harvard.edu',
+ 'text': 'Photo Roster - Test',
+ }
+ lti_tool_config.set_ext_param('canvas.instructure.com', 'privacy_level', 'public')
+ lti_tool_config.set_ext_param('canvas.instructure.com', 'course_navigation', account_nav_params)
+ lti_tool_config.description = 'This LTI app shows all the LTI parameters'
+
+ resp = HttpResponse(lti_tool_config.to_xml(), content_type='text/xml', status=200)
+ return resp
\ No newline at end of file
diff --git a/pool/shard006/Python/0057919_MD_Cluster.py b/pool/shard006/Python/0057919_MD_Cluster.py
new file mode 100644
index 0000000000000000000000000000000000000000..2a4bb013b55941a50d0c5d874ba7e3869f747a42
--- /dev/null
+++ b/pool/shard006/Python/0057919_MD_Cluster.py
@@ -0,0 +1,91 @@
+# First a documentation string to describe the example
+"""An example script demonstrating an NVT MD simulation with Asap.
+
+This example runs a molecular dynamics simulation on a small copper
+cluster in the NVT ensemble, i.e. with constant particle number,
+constant volume and constant temperature. It uses Langevin dynamics
+to get the constant temperature.
+"""
+
+# Import ASAP and relatives
+from Asap import *
+from Asap.Dynamics.Langevin import Langevin
+from Asap.Trajectories import NetCDFTrajectory
+
+# Import other essential modules
+from Numeric import *
+
+# Set up an fcc crystal of copper.
+element = 29
+lattice_constant = 3.59 # Angstrom
+size = (10, 10, 10)
+fcc_basis = array([[0.0, 0.5, 0.5],
+ [0.5, 0.0, 0.5],
+ [0.5, 0.5, 0.0]])
+# Now make an array which looks like
+# [ [0, 0, 0]
+# [0, 0, 1]
+# ...
+# [0, 0, 9]
+# [0, 1, 0]
+# ...
+# [9, 9, 9] ]
+#
+# When it is multiplied with fcc_basis it gives a small crystal with 1000
+# atoms.
+#
+# The array is made with a simple loop, although fancy Numeric array
+# operations could do it faster (but it would be close to
+# unreadable).
+pos = []
+for i in range(size[0]):
+ for j in range(size[1]):
+ for k in range(size[2]):
+ pos.append([i,j,k])
+positions = matrixmultiply(pos, fcc_basis) * lattice_constant
+
+# Now the atoms are created from the positions and a sufficiently
+# large unit cell. The unit cell is uncritical as there are no
+# periodic boundaries, and the atoms are able to move outside the unit
+# cell, so in principle it should work with the default
+# 1-Angstrom-cube unit cell.
+
+atoms = ListOfAtoms(positions=positions, cell=[max(positions[:,0]),
+ max(positions[:,1]),
+ max(positions[:,2])])
+atoms.SetAtomicNumbers(element)
+
+# Now the standard EMT Calculator is attached
+atoms.SetCalculator(EMT())
+
+# Make an object doing Langevin dynamics at a temperature of 800 K
+dyn = Langevin(atoms, dt=5*femtosecond, temperature=800*kB, friction=0.005)
+
+# Make a trajectory
+traj = NetCDFTrajectory('MD_Cluster.nc', atoms, interval=500)
+dyn.Attach(traj)
+
+# Write the initial configuration
+traj.Update()
+
+# Print the energies
+def printenergy(a, step=[0,]):
+ n = len(a)
+ ekin = a.GetKineticEnergy() / n
+ epot = a.GetPotentialEnergy() / n
+ print ("%4d: E_kin = %-9.5f E_pot = %-9.5f E_tot = %-9.5f T = %.1f K" %
+ (step[0], ekin, epot, ekin+epot, 2.0/3.0*ekin/kB))
+ step[0] += 1
+
+printenergy(atoms)
+
+# Now do the dynamics, doing 5000 timesteps, writing energies every 50 steps
+for major in range(100):
+ dyn.Run(50)
+ printenergy(atoms)
+
+# Now increase the temperature to 2000 K and continue
+dyn.SetTemperature(2000 * kB)
+for major in range(100):
+ dyn.Run(50)
+ printenergy(atoms)
diff --git a/pool/shard006/Python/0057920_integration_server.py b/pool/shard006/Python/0057920_integration_server.py
new file mode 100644
index 0000000000000000000000000000000000000000..b5777a2cf4c9ca98b79853b09f0ca7160044e5bc
--- /dev/null
+++ b/pool/shard006/Python/0057920_integration_server.py
@@ -0,0 +1,169 @@
+import errno
+import io
+import os
+import random
+import re
+import shutil
+import subprocess
+import sys
+import tempfile
+
+
+class BaseIntegrationServer(object):
+ protocols = ('TCP', 'HTTP')
+
+ protocol_re = re.compile(' '.join([
+ r'(?P[A-Z]+):',
+ r'listening on',
+ r'(?P(?:[0-9]{1,3}\.){3}[0-9]{1,3}):(?P[0-9]+)',
+ ]))
+
+ version_re = re.compile(' '.join([
+ r'(?P[a-z]+)',
+ r'v(?P[0-9]+\.[0-9]+\.[0-9]+)(?:-[a-z]+)?',
+ r'\(built w\/(?P[a-z0-9.-]+)\)'
+ ]))
+
+ def __init__(self, address='127.0.0.1'):
+ self.address = address
+ self.protocol_ports = {}
+ self.data_path = tempfile.mkdtemp()
+ self.name, self.version, self.go_version = self._parse_version()
+
+ def _parse_version(self):
+ output = subprocess.check_output([self.executable, '--version'])
+ match = self.version_re.match(output.decode('utf-8'))
+ name = match.group('name')
+ version = tuple(int(v) for v in match.group('version').split('.'))
+ go_version = match.group('go_version')
+ return name, version, go_version
+
+ @property
+ def tcp_port(self):
+ return self.protocol_ports['TCP']
+
+ @property
+ def tcp_address(self):
+ return '%s:%d' % (self.address, self.tcp_port)
+
+ @property
+ def http_port(self):
+ return self.protocol_ports['HTTP']
+
+ @property
+ def http_address(self):
+ return '%s:%d' % (self.address, self.http_port)
+
+ def _random_port(self):
+ if self.version < (0, 3, 5):
+ return random.randint(10000, 65535)
+ return 0
+
+ def _random_address(self):
+ return '%s:%d' % (self.address, self._random_port())
+
+ def _parse_protocol_ports(self):
+ while len(self.protocol_ports) < len(self.protocols):
+ line = self.child.stderr.readline()
+ sys.stderr.write(line)
+
+ if not line:
+ raise Exception('server exited prematurely')
+
+ if 'listening on' not in line:
+ continue
+
+ match = self.protocol_re.search(line)
+ if not match:
+ raise Exception('unexpected line: %r' % line)
+
+ protocol = match.group('protocol')
+ if protocol not in self.protocols:
+ continue
+
+ port = int(match.group('port'), 10)
+ self.protocol_ports[protocol] = port
+
+ def __enter__(self):
+ sys.stderr.write('running: %s\n' % ' '.join(self.cmd))
+ self.child = subprocess.Popen(self.cmd, stderr=subprocess.PIPE)
+ if sys.version_info[0] == 3:
+ self.child.stderr = io.TextIOWrapper(self.child.stderr, 'utf-8')
+ self._parse_protocol_ports()
+ return self
+
+ def __exit__(self, exc_type, exc_value, traceback):
+ try:
+ self.child.terminate()
+ except OSError as error:
+ if error.errno == errno.ESRCH:
+ return
+ raise
+
+ while True:
+ line = self.child.stderr.readline()
+ if not line:
+ break
+ sys.stderr.write(line)
+
+ self.child.wait()
+ shutil.rmtree(self.data_path)
+
+
+class NsqdIntegrationServer(BaseIntegrationServer):
+ executable = 'nsqd'
+
+ tls_cert = os.path.join(os.path.dirname(__file__), 'cert.pem')
+ tls_key = os.path.join(os.path.dirname(__file__), 'key.pem')
+
+ def __init__(self, lookupd=None, **kwargs):
+ super(NsqdIntegrationServer, self).__init__(**kwargs)
+
+ if self.has_https():
+ self.protocols = ('TCP', 'HTTP', 'HTTPS')
+
+ self.lookupd = lookupd
+
+ def has_https(self):
+ return self.version >= (0, 2, 28)
+
+ @property
+ def https_port(self):
+ return self.protocol_ports['HTTPS']
+
+ @property
+ def https_address(self):
+ return '%s:%d' % (self.address, self.https_port)
+
+ @property
+ def cmd(self):
+ cmd = [
+ self.executable,
+ '--broadcast-address', self.address,
+ '--tcp-address', self._random_address(),
+ '--http-address', self._random_address(),
+ '--data-path', self.data_path,
+ '--tls-cert', self.tls_cert,
+ '--tls-key', self.tls_key,
+ ]
+
+ if self.has_https():
+ cmd.extend(['--https-address', self._random_address()])
+
+ if self.lookupd:
+ cmd.extend(['--lookupd-tcp-address', self.lookupd])
+
+ return cmd
+
+
+class LookupdIntegrationServer(BaseIntegrationServer):
+ executable = 'nsqlookupd'
+
+ @property
+ def cmd(self):
+ return [
+ self.executable,
+ '--broadcast-address', self.address,
+ '--tcp-address', self._random_address(),
+ '--http-address', self._random_address(),
+ ]
diff --git a/pool/shard006/Python/0057921_hemodynamicExample-4R-autoregulation-exe.py b/pool/shard006/Python/0057921_hemodynamicExample-4R-autoregulation-exe.py
new file mode 100644
index 0000000000000000000000000000000000000000..cd65c5405c29449af64beccc6da4750737bcdca8
--- /dev/null
+++ b/pool/shard006/Python/0057921_hemodynamicExample-4R-autoregulation-exe.py
@@ -0,0 +1,169 @@
+"""
+@author:
+ Timo
+ Lukas
+
+Beschreibung:
+Simulation eines Netzwerkes bestehend aus 4 Regionen.
+Grafik folgt.
+Inklusive nicht-linearer Erweiterung
+
+Pythonversion:
+3.5.1
+"""
+
+import numpy as np
+import matplotlib.pyplot as plt
+
+from programs import RK4 as RK4
+#from programs import Euler as RK1
+from programs import hemodynamicModel as HM
+#from programs import bilinearModel as BM
+
+#-----------------------------------------------------------------------------------------------------------------
+# Parameter Beispiel 1
+T = 25. # Endzeit
+t0 = 0. # Anfangszeit
+dt = 0.01 # Zeitschrittlaenge
+t = np.arange(t0,T,dt) # Zeitarray
+
+A = np.array([[-1.0, 0.0, 0.0, 0.0],
+ [ 0.4,-1.0, 0.0, 0.0],
+ [ 0.0, 0.9,-1.0, 0.0],
+ [ 0.4, 0.0, 0.0,-1.0]]) # Kopplung
+
+# Anzahl B muss Anzahl der Stimuli entsprechen
+# Induzierte Kopplungänderung durch Stimuli
+B1 = np.zeros((4,4))
+B = np.array([B1]) # Zusammenfassen der ind. Kopplung in ein Array
+
+C = np.array([[0.5],
+ [0.0],
+ [0.0],
+ [0.0]]) # äußerer Einfluss auf Hirnaktivität
+
+
+# Anzahl D muss Anzahl der Hirnregionen entsprechen
+# Neuronal induzierte Kopplungsänderung
+D1 = np.zeros((4,4))
+D2 = np.zeros((4,4))
+D3 = np.array([[ 0.0, 0.0, 0.0, 0.0],
+ [-10., 0.0, 0.0, 0.0],
+ [ 0.0, 0.0, 0.0, 0.0],
+ [ 0.0, 0.0, 0.0, 0.0]])
+D4 = np.zeros((4,4))
+D = np.array([D1, D2, D3, D4]) # Zusammenfassen der neuronalen Kopplungsänderung in ein Array
+
+# äußerer Stimulus
+u = np.zeros((len(B), len(t)))
+#u[0,1010:-990:2000] = 10. # Stimulus u1
+u[0,501:541] = 10. # Stimulus u1
+
+# Anfangsbedingunden
+x_0 = np.ones(20)
+x_0[0:8] = 0.
+
+# Zusammenfassen der Parameter für das "hemodynamicModel"
+theta = list([A,B,C,D])
+
+#-----------------------------------------------------------------------------------------------------------------
+# Simulation
+#z_0 = np.array([0,0,0])
+#z = RK4.RK4(BM.bilinearModel,theta,u,z_0,t0,T,dt)
+x = RK4.RK4(HM.stateEquations,theta,u,x_0,t0,T,dt) # Lösung mithilfe des RK4-Verfahrens
+#x = RK1.Euler(HM.stateEquations,theta,u,x_0,t0,T,dt) # Lösung mithilfe des expl. Euler-Verfahrens
+y = HM.BOLDsignal(x) # Berechnung des BOLD-Signals
+
+
+
+
+plt.rcParams['figure.figsize'] = (15.0, 10.0) # Fenstergröße anpassen
+plt.rcParams['axes.linewidth'] = 2
+
+#-----------------------------------------------------------------------------------------------------------------
+# Plotten Bilineares Modell
+#-------------------------- BOLD ------------------------------------
+f1 = plt.figure(1)
+f1.suptitle('Nichtlineares Modell', fontsize = 22)
+
+# Stimulus
+ax1 = plt.subplot(311)
+ax1.tick_params(width = 2)
+plt.plot(t,u[0,:],linewidth=2)
+plt.setp(ax1.get_xticklabels(), visible=False)
+plt.axis([0, 25, 0, 12])
+plt.ylabel('$u(t)$', fontsize = 22.)
+plt.title('Stimulus',fontsize = 20.)
+
+# Gehrinaktivität
+ax2 = plt.subplot(312,sharex = ax1)
+plt.setp(ax2.get_xticklabels(), visible=False)
+ax2.tick_params(width = 2)
+
+
+# Region 1:
+#plt.plot(t,x[0,:],'r',label='Region 1') #Gehirnaktivität
+#plt.plot(t,x[4,:],'r',label='Region 1') #Vasodilatorisches Signal
+#plt.plot(t,x[8,:],'r',label='Region 1') #Blutfluss
+#plt.plot(t,x[12,:],'r',label='Region 1') #Blutvolumen
+#plt.plot(t,x[16,:],'r',label='Region 1') #Deoxyhemoglobingehalt
+
+# Region 2:
+plt.plot(t,x[1,:],'r',label='Region 2',linewidth=2) #Gehirnaktivität
+#plt.plot(t,x[5,:],'g',label='Region 2') #Vasodilatorisches Signal
+#plt.plot(t,x[9,:],'g',label='Region 2') #Blutfluss
+#plt.plot(t,x[13,:],'g',label='Region 2') #Blutvolumen
+#plt.plot(t,x[17,:],'g',label='Region 2') #Deoxyhemoglobingehalt
+
+# Region 3:
+plt.plot(t,x[2,:],'g',label='Region 3',linewidth=2) #Gehirnaktivität
+#plt.plot(t,x[6,:],'b',label='Region 3') #Vasodilatorisches Signal
+#plt.plot(t,x[10,:],'b',label='Region 3') #Blutfluss
+#plt.plot(t,x[14,:],'b',label='Region 3') #Blutvolumen
+#plt.plot(t,x[18,:],'b',label='Region 3') #Deoxyhemoglobingehalt
+
+# Region 4:
+plt.plot(t,x[3,:],'b',label='Region 4',linewidth=2) #Gehirnaktivität
+#plt.plot(t,x[7,:],'c',label='Region 4') #Vasodilatorisches Signal
+#plt.plot(t,x[11,:],'c',label='Region 4') #Blutfluss
+#plt.plot(t,x[15,:],'c',label='Region 4') #Blutvolumen
+#plt.plot(t,x[19,:],'c',label='Region 4') #Deoxyhemoglobingehalt
+
+plt.ylabel('$z(t)$', fontsize = 22.)
+plt.axis([0,25,-0.05,0.3])
+plt.title('Gehirnaktivität nach Region',fontsize = 20.)
+
+# Bold-Signal
+ax3 = plt.subplot(313,sharex = ax1)
+plt.setp(ax3.get_xticklabels(), fontsize = 14.)
+#plt.xticks(np.arange(10,110,10))
+ax3.tick_params(width = 2)
+
+# Region 1:
+#plt.plot(t,y[0,:],'r',label='Region 1') #BOLD-Signal
+# Region 2:
+plt.plot(t,y[1,:],'r',label='Region 2',linewidth=2) #BOLD-Signal
+#Region 3:
+plt.plot(t,y[2,:],'g',label='Region 3',linewidth=2) #BOLD-Signal
+#Region 4:
+plt.plot(t,y[3,:],'b',label='Region 4',linewidth=2) #BOLD-Signal
+
+ax3.legend(loc='upper center', bbox_to_anchor=(0.5, -0.2),
+ fancybox=True, shadow=True, ncol=5)
+
+plt.xlabel('Zeit t', fontsize = 18.)
+plt.ylabel('$y(t)$', fontsize = 22.)
+plt.title('BOLD-Signal nach Region',fontsize = 20.)
+
+
+#f1.savefig('hemodynamicExample-4R-autoregulation.eps')
+
+
+
+
+
+
+
+
+
+
diff --git a/pool/shard006/Python/0057922_automation_horizontal_resharding.py b/pool/shard006/Python/0057922_automation_horizontal_resharding.py
new file mode 100644
index 0000000000000000000000000000000000000000..59f45bd3bb1ffb2648f0a6d3a9cefbd27299a026
--- /dev/null
+++ b/pool/shard006/Python/0057922_automation_horizontal_resharding.py
@@ -0,0 +1,144 @@
+#!/usr/bin/env python
+#
+# Copyright 2015, Google Inc. All rights reserved.
+# Use of this source code is governed by a BSD-style license that can
+# be found in the LICENSE file.
+"""End-to-end test for horizontal resharding automation."""
+
+# "unittest" is used indirectly by importing "worker", but pylint does
+# not grasp this.
+# Import it explicitly to make pylint happy and stop it complaining about
+# setUpModule, tearDownModule and the missing module docstring.
+import unittest # pylint: disable=unused-import
+
+import environment
+import utils
+import worker
+
+
+def setUpModule():
+ worker.setUpModule()
+ utils.Vtctld().start()
+
+
+def tearDownModule():
+ worker.tearDownModule()
+
+
+class TestAutomationHorizontalResharding(worker.TestBaseSplitClone):
+ """End-to-end test for horizontal resharding automation.
+
+ This test reuses worker.py because worker.py also covers the happy path
+ of the horizontal resharding code. Instead of running the different resharding
+ steps "manually" as part of the test, they will be run by the automation
+ cluster operation.
+ """
+
+ KEYSPACE = 'test_keyspace'
+
+ def test_regular_operation(self):
+ # Use a dedicated worker to run all vtworker commands.
+ worker_proc, _, worker_rpc_port = utils.run_vtworker_bg(
+ ['--cell', 'test_nj'],
+ auto_log=True)
+ vtworker_endpoint = 'localhost:' + str(worker_rpc_port)
+
+ automation_server_proc, automation_server_port = (
+ utils.run_automation_server())
+
+ source_shard_list = '0'
+ dest_shard_list = '-80,80-'
+ _, vtctld_endpoint = utils.vtctld.rpc_endpoint()
+ utils.run(
+ environment.binary_argstr('automation_client') +
+ ' --server localhost:' + str(automation_server_port) +
+ ' --task HorizontalReshardingTask' +
+ ' --param keyspace=' + self.KEYSPACE +
+ ' --param source_shard_list=' + source_shard_list +
+ ' --param dest_shard_list=' + dest_shard_list +
+ ' --param vtctld_endpoint=' + vtctld_endpoint +
+ ' --param vtworker_endpoint=' + vtworker_endpoint +
+ ' --param min_healthy_rdonly_tablets=1')
+
+ self.verify()
+
+ utils.kill_sub_process(automation_server_proc, soft=True)
+ utils.kill_sub_process(worker_proc, soft=True)
+
+ def verify(self):
+ self.assert_shard_data_equal(0, worker.shard_master,
+ worker.shard_0_tablets.replica)
+ self.assert_shard_data_equal(1, worker.shard_master,
+ worker.shard_1_tablets.replica)
+
+ # Verify effect of MigrateServedTypes. Dest shards are serving now.
+ utils.check_srv_keyspace(
+ 'test_nj', self.KEYSPACE,
+ 'Partitions(master): -80 80-\n'
+ 'Partitions(rdonly): -80 80-\n'
+ 'Partitions(replica): -80 80-\n')
+
+ # Check that query service is disabled (source shard) or enabled (dest).
+
+ # The 'rdonly' tablet requires an explicit healthcheck first because
+ # the following sequence of events is happening in this test:
+ # - SplitDiff returns 'rdonly' as 'spare' tablet (NOT_SERVING)
+ # - MigrateServedTypes runs and does not refresh then 'spare' tablet
+ # (still NOT_SERVING)
+ # Shard_TabletControl.DisableQueryService=true will be set in the topology
+ # - explicit or periodic healthcheck runs:
+ # a) tablet seen as caught up, change type from 'spare' to 'rdonly'
+ # (change to SERVING)
+ # b) post-action callback agent.refreshTablet() reads the topology
+ # and finds out that DisableQueryService=true is set.
+ # (change to NOT_SERVING)
+ #
+ # We must run an explicit healthcheck or we can see one of the two states:
+ # - NOT_SERVING, DisableQueryService=false, tablet type 'spare'
+ # (immediately after SplitDiff returned)
+ # - SERVING, DisableQueryService=false, tablet type 'rdonly'
+ # (during healthcheck before post-action callback is called)
+ utils.run_vtctl(['RunHealthCheck', worker.shard_rdonly1.tablet_alias],
+ auto_log=True)
+
+ # source shard: query service must be disabled after MigrateServedTypes.
+ utils.check_tablet_query_service(
+ self, worker.shard_rdonly1,
+ serving=False, tablet_control_disabled=True)
+ utils.check_tablet_query_service(
+ self, worker.shard_replica,
+ serving=False, tablet_control_disabled=True)
+ utils.check_tablet_query_service(
+ self, worker.shard_master,
+ serving=False, tablet_control_disabled=True)
+
+ # dest shard -80: query service must be disabled after MigrateServedTypes.
+ # Run explicit healthcheck because 'rdonly' tablet may still be 'spare'.
+ utils.run_vtctl(['RunHealthCheck', worker.shard_0_rdonly1.tablet_alias],
+ auto_log=True)
+ utils.check_tablet_query_service(
+ self, worker.shard_0_rdonly1,
+ serving=True, tablet_control_disabled=False)
+ utils.check_tablet_query_service(
+ self, worker.shard_0_replica,
+ serving=True, tablet_control_disabled=False)
+ utils.check_tablet_query_service(
+ self, worker.shard_0_master,
+ serving=True, tablet_control_disabled=False)
+
+ # dest shard 80-: query service must be disabled after MigrateServedTypes.
+ # Run explicit healthcheck because 'rdonly' tablet is still 'spare'.
+ utils.run_vtctl(['RunHealthCheck', worker.shard_1_rdonly1.tablet_alias],
+ auto_log=True)
+ utils.check_tablet_query_service(
+ self, worker.shard_1_rdonly1,
+ serving=True, tablet_control_disabled=False)
+ utils.check_tablet_query_service(
+ self, worker.shard_1_replica,
+ serving=True, tablet_control_disabled=False)
+ utils.check_tablet_query_service(
+ self, worker.shard_1_master,
+ serving=True, tablet_control_disabled=False)
+
+if __name__ == '__main__':
+ utils.main(test_options=worker.add_test_options)
diff --git a/pool/shard006/Python/0057931_main.py b/pool/shard006/Python/0057931_main.py
new file mode 100644
index 0000000000000000000000000000000000000000..fe1b8204f7824aa64fa60e32906fae2dc4d2c433
--- /dev/null
+++ b/pool/shard006/Python/0057931_main.py
@@ -0,0 +1,66 @@
+from couchpotato.core.helpers.variable import tryInt
+from couchpotato.core.logger import CPLog
+from couchpotato.core.providers.torrent.base import TorrentMagnetProvider
+import traceback
+
+log = CPLog(__name__)
+
+
+class Yify(TorrentMagnetProvider):
+
+ urls = {
+ 'test': '%s/api',
+ 'search': '%s/api/list.json?keywords=%s&quality=%s',
+ 'detail': '%s/api/movie.json?id=%s'
+ }
+
+ http_time_between_calls = 1 #seconds
+
+ proxy_list = [
+ 'http://yify.unlocktorrent.com',
+ 'http://yify-torrents.com.come.in',
+ 'http://yts.re',
+ 'http://yts.im'
+ 'https://yify-torrents.im',
+ ]
+
+ def search(self, movie, quality):
+
+ if not quality.get('hd', False):
+ return []
+
+ return super(Yify, self).search(movie, quality)
+
+ def _search(self, movie, quality, results):
+
+ search_url = self.urls['search'] % (self.getDomain(), movie['library']['identifier'], quality['identifier'])
+
+ data = self.getJsonData(search_url)
+
+ if data and data.get('MovieList'):
+ try:
+ for result in data.get('MovieList'):
+
+ try:
+ title = result['TorrentUrl'].split('/')[-1][:-8].replace('_', '.').strip('._')
+ title = title.replace('.-.', '-')
+ title = title.replace('..', '.')
+ except:
+ continue
+
+ results.append({
+ 'id': result['MovieID'],
+ 'name': title,
+ 'url': result['TorrentMagnetUrl'],
+ 'detail_url': self.urls['detail'] % (self.getDomain(), result['MovieID']),
+ 'size': self.parseSize(result['Size']),
+ 'seeders': tryInt(result['TorrentSeeds']),
+ 'leechers': tryInt(result['TorrentPeers'])
+ })
+
+ except:
+ log.error('Failed getting results from %s: %s', (self.getName(), traceback.format_exc()))
+
+ def correctProxy(self, data):
+ data = data.lower()
+ return 'yify' in data and 'yts' in data
diff --git a/pool/shard006/Python/0057936_test_urpmichannelsync.py b/pool/shard006/Python/0057936_test_urpmichannelsync.py
new file mode 100644
index 0000000000000000000000000000000000000000..51f700d2d71210da95cb5d59371d529af57e1081
--- /dev/null
+++ b/pool/shard006/Python/0057936_test_urpmichannelsync.py
@@ -0,0 +1,113 @@
+import os
+
+from smart.plugins.urpmichannelsync import syncURPMIChannels
+from smart import sysconf
+
+from tests.mocker import MockerTestCase
+
+
+URPMI_CONFIG_MAIN = """\
+{
+}
+
+Main ftp://ftp.free.fr/mirrors/ftp.mandriva.com/MandrivaLinux/official/2009.0/i586/media/main/release {
+ key-ids: 70771ff3
+}
+
+Main\ Updates ftp://ftp.free.fr/mirrors/ftp.mandriva.com/MandrivaLinux/official/2009.0/i586/media/main/updates {
+ key-ids: 22458a98
+ update
+}
+"""
+
+URPMI_CONFIG_CDROM = """\
+Mandriva\ Linux\ -\ 2009.0\ (Free)\ -\ Installer cdrom://i586/media/main {
+ ignore
+ key-ids: 70771ff3
+}
+"""
+
+PRODUCT_ID = """\
+vendor=mandriva,distribution=mandriva linux,type=base,version=2010.1,branch=final,arch=x86_64
+"""
+
+URPMI_CONFIG_MIRRORLIST = """\
+MirrorList http://ftp.sunet.se/pub/Linux/distributions/mandrakelinux/official/2010.1/x86_64 {
+ mirrorlist: $MIRRORLIST
+}
+"""
+
+RELEASE = """\
+Mandriva Linux release 2010.1 (Official) for x86_64
+"""
+
+URPMI_CONFIG_VARIABLES = """\
+Variables http://ftp.sunet.se/pub/Linux/distributions/mandrakelinux/official/2010.1/x86_64 {
+ mirrorlist: $RELEASE/$ARCH
+}
+"""
+
+class UrpmiChannelSyncTest(MockerTestCase):
+
+ def setUp(self):
+ self.config_dir = self.makeDir()
+ self.urpmi_dir = os.path.join(self.config_dir, "urpmi")
+ self.media_dir = os.path.join(self.config_dir, "media")
+ os.mkdir(self.urpmi_dir)
+ sysconf.remove("channels")
+
+ def tearDown(self):
+ sysconf.remove("channels")
+
+ def test_synchronize_config_main(self):
+ filename = self.makeFile(URPMI_CONFIG_MAIN, dirname=self.urpmi_dir, basename="urpmi.cfg")
+ syncURPMIChannels(filename, self.media_dir)
+ self.assertEquals(sysconf.get("channels"), {
+ "urpmisync-Main Updates":
+ {"type": "urpmi",
+ "name": "Main Updates",
+ "baseurl": "ftp://ftp.free.fr/mirrors/ftp.mandriva.com/MandrivaLinux/official/2009.0/i586/media/main/updates",
+ "hdlurl": "media_info/synthesis.hdlist.cz",
+ "disabled": False,
+ "removable": False,
+ "priority": 0},
+
+ "urpmisync-Main":
+ {"type": "urpmi",
+ "name": "Main",
+ "baseurl": "ftp://ftp.free.fr/mirrors/ftp.mandriva.com/MandrivaLinux/official/2009.0/i586/media/main/release",
+ "hdlurl": "media_info/synthesis.hdlist.cz",
+ "disabled": False,
+ "removable": False,
+ "priority": 0},
+ })
+
+ def test_synchronize_config_cdrom(self):
+ filename = self.makeFile(URPMI_CONFIG_CDROM, dirname=self.urpmi_dir, basename="urpmi.cfg")
+ syncURPMIChannels(filename, self.media_dir)
+ self.assertEquals(sysconf.get("channels"), {
+ "urpmisync-Mandriva Linux - 2009.0 (Free) - Installer":
+ {"type": "urpmi",
+ "name": "Mandriva Linux - 2009.0 (Free) - Installer",
+ "baseurl": "localmedia://i586/media/main",
+ "hdlurl": "media_info/synthesis.hdlist.cz",
+ "disabled": True,
+ "removable": True,
+ "priority": 0},
+ })
+
+ def test_synchronize_config_mirrorlist(self):
+ product_id = self.makeFile(PRODUCT_ID, dirname=self.config_dir, basename="product.id")
+ sysconf.set("product-id", product_id, soft=True)
+ filename = self.makeFile(URPMI_CONFIG_MIRRORLIST, dirname=self.urpmi_dir, basename="urpmi.cfg")
+ syncURPMIChannels(filename, self.media_dir)
+ self.assertEquals(sysconf.get("channels")["urpmisync-MirrorList"]["mirrorurl"],
+ "http://api.mandriva.com/mirrors/base.2010.1.x86_64.list")
+
+ def test_synchronize_config_variables(self):
+ release = self.makeFile(RELEASE, dirname=self.config_dir, basename="release")
+ sysconf.set("release", release, soft=True)
+ filename = self.makeFile(URPMI_CONFIG_VARIABLES, dirname=self.urpmi_dir, basename="urpmi.cfg")
+ syncURPMIChannels(filename, self.media_dir)
+ self.assertEquals(sysconf.get("channels")["urpmisync-Variables"]["mirrorurl"],
+ "2010.1/x86_64")
diff --git a/pool/shard006/Python/0057939_SwigRenamer.py b/pool/shard006/Python/0057939_SwigRenamer.py
new file mode 100644
index 0000000000000000000000000000000000000000..2cecfeda3048116535d64d3fccb83749be97f380
--- /dev/null
+++ b/pool/shard006/Python/0057939_SwigRenamer.py
@@ -0,0 +1,18 @@
+#!/usr/bin/env python
+# Copyright (c) 2013 Arista Networks, Inc. All rights reserved.
+# Arista Networks, Inc. Confidential and Proprietary.
+from __future__ import print_function
+import string
+import sys
+
+# Converts a string_like_this from stdin to a stringLikeThis. If the
+# --classname flag is provided, we capitalize the first letter:
+# StringLikeThis
+
+i = sys.stdin.readline().strip()
+if i.endswith('_t'):
+ i = i[:-2]
+i = string.capwords(i, '_').replace('_', '')
+if '--classname' not in sys.argv:
+ i = i[0].lower() + i[1:]
+print(i, end="")
diff --git a/pool/shard006/Python/0057942_mod_auth_pyanonymous.py b/pool/shard006/Python/0057942_mod_auth_pyanonymous.py
new file mode 100644
index 0000000000000000000000000000000000000000..e307c55e034de75024ef47801988433818690a2f
--- /dev/null
+++ b/pool/shard006/Python/0057942_mod_auth_pyanonymous.py
@@ -0,0 +1,59 @@
+from __future__ import unicode_literals
+from prosodypy.auth import ProsodyAuthPlugin
+
+class ProsodyPlugin(ProsodyAuthPlugin):
+ """
+ A rewrite of mod_auth_anonymous.lua in Python for an example of how to
+ write auth plugins in Python.
+ """
+ name = 'pyanonymous'
+
+ def __init__(self, *args):
+ super(ProsodyPlugin, self).__init__(*args)
+ self.datamanager = self.lua.require('util.datamanager')
+
+ def test_password(self, username, password):
+ raise NotImplementedError("Password based auth not supported.")
+
+ def get_password(self, username):
+ raise NotImplementedError("Password not available.")
+
+ def set_password(self, username, password):
+ raise NotImplementedError("Password based auth not supported.")
+
+ def user_exists(self, username):
+ # FIXME check if anonymous user is connected?
+ raise NotImplementedError("Only anonymous users are supported.")
+
+ def create_user(self, username, password):
+ raise NotImplementedError("Account creation/modification not supported.")
+
+ def get_sasl_handler(self, session):
+ anonymous_authentication_profile = self.lua.table_from({
+ 'anonymous': lambda sasl, username, realm: True,
+ })
+ return self.sasl.new(
+ self.module.host,
+ anonymous_authentication_profile,
+ )
+
+ def users(self):
+ return (
+ self.lua.eval('next'),
+ self.prosody.hosts[self.module.host].sessions,
+ None,
+ )
+
+ def dm_callback(self, username, host, datastore, data):
+ if host == self.module.host:
+ return False
+ return username, host, datastore, data
+
+ def load(self):
+ if not self.module.get_option_boolean("allow_anonymous_s2s", False):
+ self.module.hook("route/remote", lambda event: False, 300)
+ self.datamanager.add_callback(self.dm_callback)
+
+ def unload(self):
+ self.datamanager.remove_callback(self.dm_callback)
+
diff --git a/pool/shard006/Python/0057947_GrammarChecker.py b/pool/shard006/Python/0057947_GrammarChecker.py
new file mode 100644
index 0000000000000000000000000000000000000000..e6e957cddf0f257fba61ed2d19bdebed106ac414
--- /dev/null
+++ b/pool/shard006/Python/0057947_GrammarChecker.py
@@ -0,0 +1,132 @@
+# Libreoffice-voikko: Linguistic extension for LibreOffice
+# Copyright (C) 2015 Harri Pitkänen
+#
+# This Source Code Form is subject to the terms of the Mozilla Public License,
+# v. 2.0. If a copy of the MPL was not distributed with this file, You can
+# obtain one at http://mozilla.org/MPL/2.0/.
+#
+# Alternatively, the contents of this file may be used under the terms of
+# the GNU General Public License Version 3 or later (the "GPL"), in which
+# case the provisions of the GPL are applicable instead of those above.
+
+import logging
+import unohelper
+from com.sun.star.linguistic2 import XProofreader, ProofreadingResult, SingleProofreadingError
+from com.sun.star.lang import XServiceInfo, XInitialization, XServiceDisplayName
+from com.sun.star.beans import PropertyValue
+from com.sun.star.text.TextMarkupType import PROOFREADING
+from VoikkoHandlePool import VoikkoHandlePool
+from PropertyManager import PropertyManager
+
+class GrammarChecker(unohelper.Base, XServiceInfo, XProofreader, XInitialization, XServiceDisplayName):
+
+ def __init__(self, ctx, *args):
+ logging.debug("GrammarChecker.__init__")
+ self.__ignoredErrors = set() # Grammar checker error codes that should be ignored
+
+ # From XServiceInfo
+ def getImplementationName(self):
+ return GrammarChecker.IMPLEMENTATION_NAME
+
+ def supportsService(self, serviceName):
+ return serviceName in self.getSupportedServiceNames()
+
+ def getSupportedServiceNames(self):
+ return GrammarChecker.SUPPORTED_SERVICE_NAMES
+
+ # From XSupportedLocales
+ def getLocales(self):
+ return VoikkoHandlePool.getInstance().getSupportedGrammarLocales()
+
+ def hasLocale(self, aLocale):
+ return VoikkoHandlePool.getInstance().supportsGrammarLocale(aLocale)
+
+ # From XProofreader
+ def isSpellChecker(self):
+ return False
+
+ def doProofreading(self, aDocumentIdentifier, aText, aLocale, nStartOfSentencePos, nSuggestedBehindEndOfSentencePosition, aProperties):
+ logging.debug("GrammarChecker.doProofreading")
+ result = ProofreadingResult()
+ result.aDocumentIdentifier = aDocumentIdentifier
+ result.xFlatParagraph = None
+ result.aText = aText
+ result.aLocale = aLocale
+ result.nStartOfSentencePosition = nStartOfSentencePos
+ result.nBehindEndOfSentencePosition = nSuggestedBehindEndOfSentencePosition
+ result.xProofreader = self
+
+ VoikkoHandlePool.mutex.acquire()
+ try:
+ voikko = VoikkoHandlePool.getInstance().getHandle(aLocale)
+ if voikko is None:
+ logging.error("GrammarChecker.doProofreading called without initializing libvoikko")
+ return result
+
+ gcErrors = []
+ gcI = 0
+ vErrorCount = 0
+ for vError in voikko.grammarErrors(aText, PropertyManager.getInstance().getMessageLanguage()):
+ startPos = vError.startPos
+ errorLength = vError.errorLen
+
+ if startPos < result.nStartOfSentencePosition:
+ continue
+ if startPos >= result.nBehindEndOfSentencePosition:
+ break
+ if startPos + errorLength > result.nBehindEndOfSentencePosition:
+ result.nBehindEndOfSentencePosition = startPos + errorLength
+
+ # we have a real grammar error
+ errorCode = vError.errorCode
+ ruleIdentifier = str(errorCode)
+ if ruleIdentifier in self.__ignoredErrors:
+ # ignore this error
+ continue
+
+ suggestions = vError.suggestions
+
+ gcError = SingleProofreadingError()
+ gcErrors.append(gcError)
+ gcError.nErrorStart = startPos
+ gcError.nErrorLength = errorLength
+ gcError.nErrorType = PROOFREADING
+ comment = vError.shortDescription
+ gcError.aShortComment = comment
+ gcError.aFullComment = comment
+ gcError.aRuleIdentifier = ruleIdentifier
+
+ detailUrl = PropertyValue()
+ detailUrl.Name = "FullCommentURL"
+ detailUrl.Value = "https://voikko.puimula.org/gchelp/fi/" + ruleIdentifier + ".html"
+ gcError.aProperties = (detailUrl,)
+
+ # add suggestions
+ if len(suggestions) > 0:
+ gcError.aSuggestions = tuple(suggestions)
+
+ result.aErrors = tuple(gcErrors)
+ result.nStartOfNextSentencePosition = result.nBehindEndOfSentencePosition
+ return result
+ finally:
+ VoikkoHandlePool.mutex.release()
+
+ def ignoreRule(self, ruleIdentifier, locale):
+ self.__ignoredErrors.add(ruleIdentifier)
+
+ def resetIgnoreRules(self):
+ ignoredErrors.clear()
+
+ # From XInitialization
+ def initialize(self):
+ pass
+
+ # From XServiceDisplayName
+ def getServiceDisplayName(self, locale):
+ if locale.Language == "fi":
+ return "Kieliopin tarkistus (Voikko)"
+ else:
+ return "Grammar checker (Voikko)"
+
+GrammarChecker.IMPLEMENTATION_NAME = "voikko.GrammarChecker"
+GrammarChecker.SUPPORTED_SERVICE_NAMES = ("com.sun.star.linguistic2.Proofreader",)
diff --git a/pool/shard006/Python/0057952_UloziskoSk.py b/pool/shard006/Python/0057952_UloziskoSk.py
new file mode 100644
index 0000000000000000000000000000000000000000..7cbcb4d40e30ea69cf31625c6f8c4eb55df72fbb
--- /dev/null
+++ b/pool/shard006/Python/0057952_UloziskoSk.py
@@ -0,0 +1,73 @@
+# -*- coding: utf-8 -*-
+
+import re
+import urlparse
+
+from module.plugins.internal.SimpleHoster import SimpleHoster, create_getInfo
+
+
+class UloziskoSk(SimpleHoster):
+ __name__ = "UloziskoSk"
+ __type__ = "hoster"
+ __version__ = "0.26"
+ __status__ = "testing"
+
+ __pattern__ = r'http://(?:www\.)?ulozisko\.sk/.+'
+ __config__ = [("use_premium", "bool", "Use premium account if available", True)]
+
+ __description__ = """Ulozisko.sk hoster plugin"""
+ __license__ = "GPLv3"
+ __authors__ = [("zoidberg", "zoidberg@mujmail.cz")]
+
+
+ NAME_PATTERN = r'
(?P[^<]+)
'
+ SIZE_PATTERN = ur'Veľkosť súboru: (?P[\d.,]+) (?P[\w^_]+) '
+ OFFLINE_PATTERN = ur'Zadaný súbor neexistuje z jedného z nasledujúcich dôvodov:'
+
+ LINK_FREE_PATTERN = r'