'), methods=['GET'])
+@login_required
+def public_dashboard(token, org_slug=None):
+ if current_user.is_api_user():
+ dashboard = current_user.object
+ else:
+ api_key = get_object_or_404(models.ApiKey.get_by_api_key, token)
+ dashboard = api_key.object
+
+ record_event(current_org, current_user, {
+ 'action': 'view',
+ 'object_id': dashboard.id,
+ 'object_type': 'dashboard',
+ 'public': True,
+ 'headless': 'embed' in request.args,
+ 'referer': request.headers.get('Referer')
+ })
+ return render_index()
diff --git a/pool/shard009/Python/0083128_sqrt.py b/pool/shard009/Python/0083128_sqrt.py
new file mode 100644
index 0000000000000000000000000000000000000000..3b3f045378fc11bba832b8f7b3544923dcf01b9a
--- /dev/null
+++ b/pool/shard009/Python/0083128_sqrt.py
@@ -0,0 +1,93 @@
+import numpy
+
+from chainer.backends import cuda
+from chainer import function_node
+from chainer import utils
+from chainer.utils import type_check
+
+
+class Sqrt(function_node.FunctionNode):
+
+ @property
+ def label(self):
+ return 'sqrt'
+
+ def check_type_forward(self, in_types):
+ type_check.expect(
+ in_types.size() == 1,
+ in_types[0].dtype.kind == 'f',
+ )
+
+ def forward(self, x):
+ self.retain_outputs((0,))
+ xp = cuda.get_array_module(*x)
+ return utils.force_array(xp.sqrt(x[0], dtype=x[0].dtype)),
+
+ def backward(self, indexes, grad_outputs):
+ gx = self.get_retained_outputs()[0]
+ gy = grad_outputs[0]
+ return gy / (gx * 2.0),
+
+
+class RsqrtGPU(function_node.FunctionNode):
+
+ @property
+ def label(self):
+ return 'rsqrt'
+
+ def check_type_forward(self, in_types):
+ type_check.expect(
+ in_types.size() == 1,
+ in_types[0].dtype.kind == 'f',
+ )
+
+ def forward_gpu(self, inputs):
+ self.retain_outputs((0,))
+ x, = inputs
+ out = cuda.cupyx.rsqrt(x, dtype=x.dtype)
+ return utils.force_array(out),
+
+ def backward(self, indexes, grad_outputs):
+ y, = self.get_retained_outputs()
+ gy, = grad_outputs
+ return gy * (y ** 3) * -0.5,
+
+
+def sqrt(x):
+ """Elementwise square root function.
+
+ .. math::
+ y_i = \\sqrt x_i.
+
+ If the value of :math:`x_i` is negative, it returns ``Nan`` for :math:`y_i`
+ respect to underlying numpy and cupy specification.
+
+ Args:
+ x (~chainer.Variable): Input variable.
+
+ Returns:
+ ~chainer.Variable: Output variable.
+ """
+ return Sqrt().apply((x,))[0]
+
+
+def rsqrt(x):
+ """Computes elementwise reciprocal of square root of input :math:`x_i`.
+
+ .. math::
+ y_i = {1 \\over \\sqrt x_i}.
+
+ Args:
+ x (~chainer.Variable): Input variable.
+
+ Returns:
+ ~chainer.Variable: Output variable.
+
+ .. seealso:: :func:`~chainer.functions.sqrt`
+ """
+ xp = cuda.get_array_module(x)
+ if xp is numpy:
+ return 1.0 / sqrt(x)
+
+ # CuPy provides `rsqrt` which is faster than `1.0 / sqrt(x)`.
+ return RsqrtGPU().apply((x,))[0]
diff --git a/pool/shard009/Python/0083131_jmodeltest.py b/pool/shard009/Python/0083131_jmodeltest.py
new file mode 100644
index 0000000000000000000000000000000000000000..d996f1064eeb36ffa985ffa0fdbe32172f5ba8ec
--- /dev/null
+++ b/pool/shard009/Python/0083131_jmodeltest.py
@@ -0,0 +1,113 @@
+from __future__ import absolute_import
+# #START_LICENSE###########################################################
+#
+#
+# This file is part of the Environment for Tree Exploration program
+# (ETE). http://etetoolkit.org
+#
+# ETE 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.
+#
+# ETE 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 ETE. If not, see .
+#
+#
+# ABOUT THE ETE PACKAGE
+# =====================
+#
+# ETE is distributed under the GPL copyleft license (2008-2015).
+#
+# If you make use of ETE in published work, please cite:
+#
+# Jaime Huerta-Cepas, Joaquin Dopazo and Toni Gabaldon.
+# ETE: a python Environment for Tree Exploration. Jaime BMC
+# Bioinformatics 2010,:24doi:10.1186/1471-2105-11-24
+#
+# Note that extra references to the specific methods implemented in
+# the toolkit may be available in the documentation.
+#
+# More info at http://etetoolkit.org. Contact: huerta@embl.de
+#
+#
+# #END_LICENSE#############################################################
+import os
+import logging
+log = logging.getLogger("main")
+
+from ..master_task import ModelTesterTask
+from ..master_job import Job
+from ..utils import basename, PhyloTree
+
+__all__ = ["JModeltest"]
+
+class JModeltest(ModelTesterTask):
+ def __init__(self, nodeid, alg_fasta_file, alg_phylip_file, conf):
+ GLOBALS["citator"].add('jmodeltest')
+
+ self.conf = conf
+ base_args = {
+ '-d': alg_fasta_file,
+ }
+ args = self.conf["jmodeltest"]
+ if args.get("-t", "ML") == "ML":
+ task_type = "tree"
+ else:
+ task_type = "mchooser"
+
+ ModelTesterTask.__init__(self, nodeid, task_type, "Jmodeltest",
+ base_args, self.conf[confname])
+
+ # set app arguments and options
+ self.alg_fasta_file = alg_fasta_file
+ self.alg_phylip_file = alg_phylip_file
+ self.seqtype = "nt"
+ self.models = "see jmodeltest params"
+
+ self.init()
+ self.best_model_file = os.path.join(self.taskdir, "best_model.txt")
+ if task_type == "tree":
+ self.tree_file = os.path.join(self.taskdir, "final_tree.nw")
+ else:
+ self.tree_file = None
+
+
+ def load_jobs(self):
+ tree_job = Job(self.conf["app"]["jmodeltest"], self.args, parent_ids=[self.nodeid])
+ self.jobs.append(tree_job)
+
+ def finish(self):
+ # first job is the raxml tree
+ best_model = None
+ best_model_in_next_line = False
+ t = None
+ for line in open(self.jobs[-1].stdout_file, "r"):
+ line = line.strip()
+ if best_model_in_next_line and line.startswith("Model"):
+ pass#best_model = line.split("=")[1].strip()
+ elif best_model_in_next_line and line.startswith("partition"):
+ best_model = line.split("=")[1].strip()
+ best_model_in_next_line = False
+ elif line.startswith("Model selected:"):
+ best_model_in_next_line = True
+ elif line.startswith("ML tree (NNI) for the best AIC model ="):
+ nw = line.replace("ML tree (NNI) for the best AIC model =", "")
+ t = PhyloTree(nw)
+
+ open(self.best_model_file, "w").write(best_model)
+ log.log(26, "Best model: %s" %best_model)
+ if self.ttype == "tree":
+ tree_job = self.jobs[-1]
+ tree_file = os.path.join(tree_job.jobdir,
+ "jModelTest_tree."+self.nodeid)
+ t.write(outfile=self.tree_file)
+ self.model = best_model
+
+
+ ModelTesterTask.finish(self)
diff --git a/pool/shard009/Python/0083132_setup.py b/pool/shard009/Python/0083132_setup.py
new file mode 100644
index 0000000000000000000000000000000000000000..20a817fda0357c3d685d136e0357f689b7a63677
--- /dev/null
+++ b/pool/shard009/Python/0083132_setup.py
@@ -0,0 +1,52 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+try:
+ import setuptools
+except ImportError:
+ import distutils.core as setuptools
+
+
+__author__ = 'Chris Jin'
+__copyright__ = 'Copyright 2014'
+__credits__ = []
+
+__license__ = 'Apache 2.0'
+__version__ = '0.1.0'
+__maintainer__ = 'Chris Jin'
+__email__ = 'chrisjin@outlook.com'
+__status__ = 'Dev'
+
+__title__ = 'docker-registry-driver-alioss'
+__build__ = 0x000000
+
+__url__ = 'https://github.com/chris-jin/docker-registry-driver-alioss'
+__description__ = 'Docker registry ali oss driver'
+d = 'https://github.com/chris-jin/docker-registry-driver-alioss/archive/master.zip'
+
+setuptools.setup(
+ name=__title__,
+ version=__version__,
+ author=__author__,
+ author_email=__email__,
+ maintainer=__maintainer__,
+ maintainer_email=__email__,
+ url=__url__,
+ description=__description__,
+ long_description=open('./README.md').read(),
+ download_url=d,
+ classifiers=['Development Status :: 4 - Beta',
+ 'Intended Audience :: Developers',
+ 'Programming Language :: Python',
+ 'Programming Language :: Python :: 2.7',
+ 'Programming Language :: Python :: Implementation :: CPython',
+ 'Operating System :: OS Independent',
+ 'Topic :: Utilities',
+ 'License :: OSI Approved :: Apache Software License'],
+ platforms=['Independent'],
+ license=open('./LICENSE').read(),
+ namespace_packages=['docker_registry', 'docker_registry.drivers'],
+ packages=['docker_registry', 'docker_registry.drivers'],
+ install_requires=open('./requirements.txt').read(),
+ zip_safe=False
+)
diff --git a/pool/shard009/Python/0083134_thegutters.py b/pool/shard009/Python/0083134_thegutters.py
new file mode 100644
index 0000000000000000000000000000000000000000..993434301e550f85a5462614c376bf94dae1c66d
--- /dev/null
+++ b/pool/shard009/Python/0083134_thegutters.py
@@ -0,0 +1,28 @@
+import re
+
+from comics.aggregator.crawler import CrawlerBase, CrawlerImage
+from comics.core.comic_data import ComicDataBase
+
+
+class ComicData(ComicDataBase):
+ name = "The Gutters"
+ language = "en"
+ url = "http://the-gutters.com/"
+ rights = "Blind Ferret Entertainment"
+ active = False
+
+
+class Crawler(CrawlerBase):
+ history_capable_days = 180
+ schedule = "Tu,Fr"
+ time_zone = "America/Montreal"
+
+ def crawl(self, pub_date):
+ feed = self.parse_feed("http://feeds.feedburner.com/TheGutters")
+ for entry in feed.for_date(pub_date):
+ title = entry.title
+ url = entry.summary.src('img[src*="/wp-content/uploads/"]')
+ if not url:
+ continue
+ url = re.sub(r"-\d+x\d+.jpg", ".jpg", url)
+ return CrawlerImage(url, title)
diff --git a/pool/shard009/Python/0083139_0006_auto_20170502_1246.py b/pool/shard009/Python/0083139_0006_auto_20170502_1246.py
new file mode 100644
index 0000000000000000000000000000000000000000..cbab054c761b6710999a36e9d02ca72e66a672c5
--- /dev/null
+++ b/pool/shard009/Python/0083139_0006_auto_20170502_1246.py
@@ -0,0 +1,26 @@
+# Generated by Django 1.10.7 on 2017-05-02 12:46
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [("gallery", "0005_image_phash")]
+
+ operations = [
+ migrations.AddField(
+ model_name="image",
+ name="gallery_ready",
+ field=models.BooleanField(default=False),
+ ),
+ migrations.AddField(
+ model_name="image",
+ name="preview_ready",
+ field=models.BooleanField(default=False),
+ ),
+ migrations.AddField(
+ model_name="image",
+ name="thumbnail_ready",
+ field=models.BooleanField(default=False),
+ ),
+ ]
diff --git a/pool/shard009/Python/0083144_CUTEFLOW_0023.py b/pool/shard009/Python/0083144_CUTEFLOW_0023.py
new file mode 100644
index 0000000000000000000000000000000000000000..59e41460b4efed65dd3db0533e61ba0e9b87d562
--- /dev/null
+++ b/pool/shard009/Python/0083144_CUTEFLOW_0023.py
@@ -0,0 +1,53 @@
+
+# Copyright 2013 University of Maryland. All rights reserved.
+# Use of this source code is governed by a BSD-style
+# license that can be found in the LICENSE.TXT file.
+
+
+import sys
+import os
+import time
+
+from selenium.common.exceptions import NoAlertPresentException
+
+import framework
+
+class Exploit (framework.Exploit):
+
+ attributes = {'Name' : "CUTEFLOW_0023",
+ 'Description' : "CuteFlow v2.11.2 cross site scripting attack.",
+ 'References' : [['http://itsecuritysolutions.org/2012-07-01-CuteFlow-2.11.2-multiple-security-vulnerabilities/']],
+ 'Target' : "CuteFlow 2.11.2",
+ 'TargetLicense' : '',
+ 'VulWikiPage' : "",
+ 'Type' : 'XSS'
+ }
+
+ def __init__(self, visible=False):
+ framework.Exploit.__init__(self, visible)
+ self.verified = False
+ return
+
+ def exploit(self):
+ driver = self.create_selenium_driver()
+ driver.get("http://localhost/cuteflow/pages/showmaillist.php?language=\">
+#
+# EventGhost is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# EventGhost 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 EventGhost; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+#
+#
+# Last change: 2009-10-15 10:11
+
+u"""
+Plugin for `Igor \u010Ce\u0161ko's UDP IR`__ receiver.
+
+This device is connected directly to twisted pair 10/100 BASE TX network.
+It receives signal from standard infrared remote control
+(used for TV, DVD players, ... ) and send it to group of computers
+on the network (UDP broadcast).
+Therefore signal can be collected by more computers also.
+
+__ http://www.cesko.host.sk/IgorPlugUDP/IgorPlug-UDP%20%28AVR%29_eng.htm
+"""
+
+import eg
+from threading import Thread, Event
+from socket import socket, AF_INET, SOCK_DGRAM, SOL_SOCKET, SO_REUSEADDR
+from socket import error as socket_error
+import asyncore
+from locale import getdefaultlocale as localeEncoding
+
+eg.RegisterPlugin(
+ name = "IgorPlug-UDP",
+ author = "Pako/Bitmonster",
+ version = "0.1.1",
+ kind = "remote",
+ description = __doc__,
+ icon = (
+ "iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAMAAABEpIrGAAADAFBMVEUAAACAAAAAgACA"
+ "gAAAAICAAIAAgICAgIDAwMD/AAAA/wD//wAAAP//AP8A//////8AAAAAAAAAAAAAAAAA"
+ "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
+ "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
+ "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
+ "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
+ "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
+ "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
+ "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
+ "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
+ "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
+ "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
+ "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
+ "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
+ "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
+ "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABYBAnEAAAA"
+ "0klEQVR4nJWQ2xKDIAxEwwMDIw75/78tuZKU2mlXRckeNhkBftB1yUPLRSou9dkwoJRN"
+ "1HBe7pKAegBk7hZ1DOsgEBnZH3FEA6xDrTUDwHWfYbkKmEoS5yfgzef8CFC1Lfl5Bk5f"
+ "iId8BzT/eUCbf875BHD+nJs4ATm/IzQybHiXgZkA8TcQAjQ/BQDknfidlEs6unx/9RGR"
+ "fcScr52DjyFh/5jgI2RC/d4NaHDK/QW0Bjes+77pRQvnu5oDvkCP+hfgFn2Ea/k54QCo"
+ "4vN9ANb+BYRyE8/VBob3AAAAAElFTkSuQmCC"
+ ),
+)
+
+
+class Text:
+ eventPrefix = "Event prefix:"
+ remIP = "IgorPlug-UDP IP address:"
+ locPort = "Local UDP port:"
+
+class udpReceiver(asyncore.dispatcher):
+
+ def __init__(self, address, port, plugin):
+ self.irCommand = []
+ self.remAddress=address
+ self.plugin=plugin
+ asyncore.dispatcher.__init__(self)
+ self.create_socket(AF_INET, SOCK_DGRAM)
+ eg.RestartAsyncore()
+ self.bind(('', port))
+
+ def writable(self):
+ return False # we don't have anything to send !
+
+ def handle_connect(self):
+ pass
+
+ def handle_close(self):
+ self.close()
+
+ def handle_expt(self):
+ self.close()
+
+ def handle_read(self):
+ payload, address = self.socket.recvfrom(128)
+ if self.remAddress == address[0]:
+ if len(payload)==44:
+ weight = 1
+ byte = 0
+ flag = True
+ for i in range(4,44,5):
+ if payload[i] == '\x80':
+ byte += weight
+ elif payload[i:i+5] == 5*'\x00':
+ pass
+ else:
+ flag = False
+ break
+ weight *= 2
+ if flag:
+ self.irCommand.append(chr(byte))
+ if byte == 0xFF:
+ datagram = ''.join(self.irCommand)
+ if len(datagram) > 4:
+ if datagram[:4]==4*"\x00":
+ datagram = datagram[4:]
+ if len(datagram) > 4 and ord(datagram[0]) == len(datagram)-4:
+ self.plugin.irDecoder.Decode(datagram[3:],len(datagram)-3)
+ self.irCommand = []
+ else:
+ self.plugin.TriggerEvent('DataError')
+ self.irCommand = []
+
+
+class IgorPlugUDP(eg.IrDecoderPlugin):
+ canMultiLoad = True
+ text = Text
+
+ def __init__(self):
+ eg.IrDecoderPlugin.__init__(self, 51.2)
+
+ def __start__(self, prefix="IgorUDP", locPort=6668, remAddress="192.168.1.7"):
+ self.info.eventPrefix = prefix
+ try:
+ self.receiver = udpReceiver(remAddress, locPort, self)
+ except socket_error, exc:
+ raise self.Exception(exc[1].decode(localeEncoding()[1]))
+
+ def __stop__(self):
+ if self.receiver:
+ self.receiver.close()
+ self.receiver = None
+
+ def __close__(self):
+ self.irDecoder.Close()
+
+ def Configure(self, prefix="IgorUDP", locPort=6668, remAddress="192.168.1.7"):
+ panel = eg.ConfigPanel(self)
+ prefixCtrl = panel.TextCtrl(prefix)
+ ipAddressCtrl = panel.TextCtrl(remAddress)
+ locPortCtrl = panel.SpinIntCtrl(locPort, min=1, max=65535)
+ panel.AddLine(self.text.eventPrefix, prefixCtrl)
+ panel.AddLine(self.text.remIP, ipAddressCtrl)
+ panel.AddLine(self.text.locPort, locPortCtrl)
+
+ while panel.Affirmed():
+ panel.SetResult(
+ prefixCtrl.GetValue(),
+ int(locPortCtrl.GetValue()),
+ ipAddressCtrl.GetValue(),
+ )
+
+
+
diff --git a/pool/shard009/Python/0083150_server.py b/pool/shard009/Python/0083150_server.py
new file mode 100644
index 0000000000000000000000000000000000000000..232fccdc5010b7cba3ab918cf3aafc75a211a686
--- /dev/null
+++ b/pool/shard009/Python/0083150_server.py
@@ -0,0 +1,38 @@
+from flask import Flask, json, jsonify
+app = Flask(__name__)
+
+
+@app.route("/strawpolls")
+def polls():
+ return jsonify(json.load(open("static/strawpolls.json")))
+
+
+@app.route("/strawpolls/")
+def votes(id):
+ polls = json.load(open("static/strawpolls.json"))
+ return jsonify(polls['data'][id])
+
+
+@app.route("/")
+def root():
+ return open("static/index.html").read()
+
+
+@app.route("/strawpolls//vote/", methods=["POST"])
+def vote(id, choice):
+ polls = json.load(open("static/strawpolls.json"))
+ polls['data'][id]['choices'][choice] += 1
+ json.dump(polls, open("static/strawpolls.json", "w"))
+ return jsonify(polls['data'][id])
+
+
+@app.route("/")
+def other(page):
+ print(page)
+ content = open("static/{}.html".format(page)).read()
+ print(content)
+ return content
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/pool/shard009/Python/0083159_test_shortcuts.py b/pool/shard009/Python/0083159_test_shortcuts.py
new file mode 100644
index 0000000000000000000000000000000000000000..041f724d80370a3858e72a4386f47073f81e84c3
--- /dev/null
+++ b/pool/shard009/Python/0083159_test_shortcuts.py
@@ -0,0 +1,30 @@
+# -*- coding: utf-8 -*-
+
+from __future__ import unicode_literals
+
+import pytest
+from faker import Faker
+
+from machina.apps.forum.models import Forum
+from machina.core.shortcuts import get_object_or_none
+from machina.test.factories import create_forum
+
+
+faker = Faker()
+
+
+@pytest.mark.django_db
+class TestCoreShortcuts(object):
+ @pytest.fixture(autouse=True)
+ def setup(self):
+ self.forum = create_forum()
+
+ def test_can_get_an_object_or_none(self):
+ # Setup
+ forum_pk = self.forum.pk
+ # Run
+ forum = get_object_or_none(Forum, pk=forum_pk)
+ unknown_forum = get_object_or_none(Forum, pk=10000)
+ # Check
+ assert self.forum.pk == forum.pk
+ assert unknown_forum is None
diff --git a/pool/shard009/Python/0083161_serial_list.py b/pool/shard009/Python/0083161_serial_list.py
new file mode 100644
index 0000000000000000000000000000000000000000..c90919230f4a39946e5940967b5cb7663844bf5f
--- /dev/null
+++ b/pool/shard009/Python/0083161_serial_list.py
@@ -0,0 +1,35 @@
+import sys
+import glob
+import serial
+
+
+def serial_ports():
+ """Lists serial ports
+
+ :raises EnvironmentError:
+ On unsupported or unknown platforms
+ :returns:
+ A list of available serial ports
+ """
+ if sys.platform.startswith('win'):
+ ports = ['COM' + str(i + 1) for i in range(256)]
+
+ elif sys.platform.startswith('linux') or sys.platform.startswith('cygwin'):
+ # this is to exclude your current terminal "/dev/tty"
+ ports = glob.glob('/dev/tty[A-Za-z]*')
+
+ elif sys.platform.startswith('darwin'):
+ ports = glob.glob('/dev/tty.*')
+
+ else:
+ raise EnvironmentError('Unsupported platform')
+
+ result = []
+ for port in ports:
+ try:
+ s = serial.Serial(port)
+ s.close()
+ result.append(port)
+ except (OSError, serial.SerialException):
+ pass
+ return result
diff --git a/pool/shard009/Python/0083163_cpython3.py b/pool/shard009/Python/0083163_cpython3.py
new file mode 100644
index 0000000000000000000000000000000000000000..fcd92b82f61fc17564718c0f90325effe15574a8
--- /dev/null
+++ b/pool/shard009/Python/0083163_cpython3.py
@@ -0,0 +1,91 @@
+from __future__ import absolute_import, unicode_literals
+
+import abc
+from textwrap import dedent
+
+from six import add_metaclass
+
+from virtualenv.create.describe import Python3Supports
+from virtualenv.create.via_global_ref.builtin.ref import PathRefToDest
+from virtualenv.create.via_global_ref.store import is_store_python
+from virtualenv.util.path import Path
+
+from .common import CPython, CPythonPosix, CPythonWindows, is_mac_os_framework
+
+
+@add_metaclass(abc.ABCMeta)
+class CPython3(CPython, Python3Supports):
+ """ """
+
+
+class CPython3Posix(CPythonPosix, CPython3):
+ @classmethod
+ def can_describe(cls, interpreter):
+ return is_mac_os_framework(interpreter) is False and super(CPython3Posix, cls).can_describe(interpreter)
+
+ def env_patch_text(self):
+ text = super(CPython3Posix, self).env_patch_text()
+ if self.pyvenv_launch_patch_active(self.interpreter):
+ text += dedent(
+ """
+ # for https://github.com/python/cpython/pull/9516, see https://github.com/pypa/virtualenv/issues/1704
+ import os
+ if "__PYVENV_LAUNCHER__" in os.environ:
+ del os.environ["__PYVENV_LAUNCHER__"]
+ """,
+ )
+ return text
+
+ @classmethod
+ def pyvenv_launch_patch_active(cls, interpreter):
+ ver = interpreter.version_info
+ return interpreter.platform == "darwin" and ((3, 7, 8) > ver >= (3, 7) or (3, 8, 3) > ver >= (3, 8))
+
+
+class CPython3Windows(CPythonWindows, CPython3):
+ """ """
+
+ @classmethod
+ def setup_meta(cls, interpreter):
+ if is_store_python(interpreter): # store python is not supported here
+ return None
+ return super(CPython3Windows, cls).setup_meta(interpreter)
+
+ @classmethod
+ def sources(cls, interpreter):
+ for src in super(CPython3Windows, cls).sources(interpreter):
+ yield src
+ if not cls.has_shim(interpreter):
+ for src in cls.include_dll_and_pyd(interpreter):
+ yield src
+
+ @classmethod
+ def has_shim(cls, interpreter):
+ return interpreter.version_info.minor >= 7 and cls.shim(interpreter) is not None
+
+ @classmethod
+ def shim(cls, interpreter):
+ shim = Path(interpreter.system_stdlib) / "venv" / "scripts" / "nt" / "python.exe"
+ if shim.exists():
+ return shim
+ return None
+
+ @classmethod
+ def host_python(cls, interpreter):
+ if cls.has_shim(interpreter):
+ # starting with CPython 3.7 Windows ships with a venvlauncher.exe that avoids the need for dll/pyd copies
+ # it also means the wrapper must be copied to avoid bugs such as https://bugs.python.org/issue42013
+ return cls.shim(interpreter)
+ return super(CPython3Windows, cls).host_python(interpreter)
+
+ @classmethod
+ def include_dll_and_pyd(cls, interpreter):
+ dll_folder = Path(interpreter.system_prefix) / "DLLs"
+ host_exe_folder = Path(interpreter.system_executable).parent
+ for folder in [host_exe_folder, dll_folder]:
+ for file in folder.iterdir():
+ if file.suffix in (".pyd", ".dll"):
+ yield PathRefToDest(file, dest=cls.to_dll_and_pyd)
+
+ def to_dll_and_pyd(self, src):
+ return self.bin_dir / src.name
diff --git a/pool/shard009/Python/0083164_requisition_label.py b/pool/shard009/Python/0083164_requisition_label.py
new file mode 100644
index 0000000000000000000000000000000000000000..a9c3fbfbf34fd8c0bb414e59f779a3609dbf6c61
--- /dev/null
+++ b/pool/shard009/Python/0083164_requisition_label.py
@@ -0,0 +1,53 @@
+from arrow.arrow import Arrow
+from django.apps import apps as django_apps
+from django.conf import settings
+from edc_label import Label
+
+
+class RequisitionLabel(Label):
+
+ label_template_name = 'requisition'
+ registered_subject_model = 'edc_registration.registeredsubject'
+
+ def __init__(self, requisition=None, item=None, user=None, label_template_name=None):
+ self._registered_subject = None
+ self.label_template_name = label_template_name or self.label_template_name
+ super().__init__(label_template_name=self.label_template_name)
+ self.item = item or 1
+ self.requisition = requisition
+ self.user = user
+ self.label_name = self.requisition.human_readable_identifier
+
+ @property
+ def registered_subject(self):
+ if not self._registered_subject:
+ model_cls = django_apps.get_model(self.registered_subject_model)
+ self._registered_subject = model_cls.objects.get(
+ subject_identifier=self.requisition.subject_identifier)
+ return self._registered_subject
+
+ @property
+ def label_context(self):
+ edc_protocol_app_config = django_apps.get_app_config('edc_protocol')
+ utc = Arrow.fromdatetime(
+ self.requisition.drawn_datetime or self.requisition.created)
+ dte = utc.to(settings.TIME_ZONE).datetime
+ formatted_date = dte.strftime("%Y-%m-%d %H:%M")
+ printed = 'PRINTED: ' if not self.requisition.drawn_datetime else 'DRAWN: '
+ return {
+ 'requisition_identifier': self.requisition.requisition_identifier,
+ 'item': self.item,
+ 'item_count': self.requisition.item_count or 1,
+ 'primary': '',
+ 'barcode_value': self.requisition.requisition_identifier,
+ 'protocol': edc_protocol_app_config.protocol,
+ 'site': str(self.requisition.site.id),
+ 'site_name': str(self.requisition.site.name),
+ 'clinician_initials': self.user.username[0:2].upper(),
+ 'drawn_datetime': f'{printed}{formatted_date}',
+ 'subject_identifier': self.registered_subject.subject_identifier,
+ 'gender': self.registered_subject.gender,
+ 'dob': self.registered_subject.dob,
+ 'initials': self.registered_subject.initials,
+ 'alpha_code': self.requisition.panel_object.alpha_code,
+ 'panel': self.requisition.panel_object.abbreviation}
diff --git a/pool/shard009/Python/0083167_model.py b/pool/shard009/Python/0083167_model.py
new file mode 100644
index 0000000000000000000000000000000000000000..e2ac12e84fc13288de5b96dcf913f9905f08f198
--- /dev/null
+++ b/pool/shard009/Python/0083167_model.py
@@ -0,0 +1,159 @@
+from abc import ABCMeta,abstractmethod,abstractproperty
+from numpy import inf
+from array import array
+from .parameter import LivePoint
+from numpy.random import uniform
+
+import logging
+LOGGER = logging.getLogger('cpnest.model') # <--- for module-level logging
+
+
+class Model(object):
+ """
+ Base class for user's model. User should subclass this
+ and implement log_likelihood, names and bounds
+ """
+ __metaclass__ = ABCMeta
+ names=[] # Names of parameters, e.g. ['p1','p2']
+ bounds=[] # Bounds of prior as list of tuples, e.g. [(min1,max1), (min2,max2), ...]
+
+ def in_bounds(self,param):
+ """
+ Checks whether param lies within the bounds
+
+ -----------
+ Parameters:
+ param: :obj:`cpnest.parameter.LivePoint`
+
+ -----------
+ Return:
+ True: if all dimensions are within the bounds
+ False: otherwise
+ """
+ return all(self.bounds[i][0] < param.values[i] < self.bounds[i][1] for i in range(param.dimension))
+
+ def new_point(self):
+ """
+ Create a new LivePoint, drawn from within bounds
+
+ -----------
+ Return:
+ p: :obj:`cpnest.parameter.LivePoint`
+ """
+ logP=-inf
+ while(logP==-inf):
+ p = LivePoint(self.names,
+ d=array('d',
+ [uniform(self.bounds[i][0],
+ self.bounds[i][1])
+ for i, _ in enumerate(self.names) ]
+ )
+ )
+ logP=self.log_prior(p)
+ return p
+
+ @abstractmethod
+ def log_likelihood(self,param):
+ """
+ returns log likelihood of given parameter
+
+ ------------
+ Parameter:
+ param: :obj:`cpnest.parameter.LivePoint`
+ """
+ pass
+
+ def log_prior(self,param):
+ """
+ Returns log of prior.
+ Default is flat prior within bounds
+
+ ----------
+ Parameter:
+ param: :obj:`cpnest.parameter.LivePoint`
+
+ ----------
+ Return:
+ 0 if param is in bounds
+ -np.inf otherwise
+ """
+ if self.in_bounds(param):
+ return 0.0
+ else: return -inf
+
+ def potential(self,param):
+ """
+ returns the potential energy as minus the log prior
+ ----------
+ Parameter:
+ param: :obj:`cpnest.parameter.LivePoint`
+
+ ----------
+ Return:
+ :obj: -`cpnest.model.log_prior`
+ """
+ return -self.log_prior(param)
+
+ def force(self,param):
+ """
+ returns the force (-grad potential)
+ Required for Hamiltonian sampling
+
+ ----------
+ Parameter:
+ param: :obj:`cpnest.parameter.LivePoint`
+ """
+ pass
+
+ def strsample(self,sample):
+ """
+ Return a string representation for the sample to be written
+ to the output file. User may overload for additional output
+ ----------
+ Parameter:
+ param: :obj:`cpnest.parameter.LivePoint`
+ ----------
+ Return:
+ line: :string:
+ """
+ line='\t'.join('{0:.20e}'.format(sample[n]) for n in sample.names)
+ line+='{0:20e}'.format(sample.logL)
+ return line
+
+ def header(self):
+ """
+ Return a string with the output file header
+ """
+ return '\t'.join(self.names) + '\tlogL'
+
+ def from_normalised(self, normalised_value):
+ """
+ Maps from [0,1]^Ndim to the full range of the parameters
+ Inverse of to_normalised()
+ ----------
+ Parameter:
+ normalised_vaue: array-like values in range (0,1)
+ ----------
+ Returns:
+ point: :obj:`cpnest.parameter.LivePoint`
+ """
+ d=array('d',
+ [self.bounds[i][0]
+ + normalised_value[i] * (self.bounds[i][1] - self.bounds[i][0])
+ for i, _ in enumerate(self.names)]
+ )
+ return LivePoint(self.names, d=d)
+
+ def to_normalised(self, point):
+ """
+ Maps the bounds of the parameters onto [-1,1]
+ ----------
+ Parameter:
+ point: :obj:`cpnest.parameter.LivePoint`
+ ----------
+ Returns:
+ normalised_value: :obj:`array.array`
+ The values of the parameter mapped into the Ndim-cube
+ """
+ return array('d', [(v-b[0])/(b[1]-b[0]) for v, b
+ in zip(value.values, self.bounds)])
diff --git a/pool/shard009/Python/0083168_mfi.py b/pool/shard009/Python/0083168_mfi.py
new file mode 100644
index 0000000000000000000000000000000000000000..42abe75af60c60508fcae5584221cde62e88047a
--- /dev/null
+++ b/pool/shard009/Python/0083168_mfi.py
@@ -0,0 +1,103 @@
+"""
+homeassistant.components.switch.mfi
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+Support for Ubiquiti mFi switches.
+
+For more details about this platform, please refer to the documentation at
+https://home-assistant.io/components/switch.mfi/
+"""
+import logging
+
+from homeassistant.components.switch import DOMAIN, SwitchDevice
+from homeassistant.const import CONF_PASSWORD, CONF_USERNAME
+from homeassistant.helpers import validate_config
+
+REQUIREMENTS = ['mficlient==0.2.2']
+
+_LOGGER = logging.getLogger(__name__)
+
+SWITCH_MODELS = [
+ 'Outlet',
+ 'Output 5v',
+ 'Output 12v',
+ 'Output 24v',
+]
+
+
+# pylint: disable=unused-variable
+def setup_platform(hass, config, add_devices, discovery_info=None):
+ """ Sets up mFi sensors. """
+
+ if not validate_config({DOMAIN: config},
+ {DOMAIN: ['host',
+ CONF_USERNAME,
+ CONF_PASSWORD]},
+ _LOGGER):
+ _LOGGER.error('A host, username, and password are required')
+ return False
+
+ host = config.get('host')
+ port = int(config.get('port', 6443))
+ username = config.get('username')
+ password = config.get('password')
+
+ from mficlient.client import MFiClient
+
+ try:
+ client = MFiClient(host, username, password, port=port)
+ except client.FailedToLogin as ex:
+ _LOGGER.error('Unable to connect to mFi: %s', str(ex))
+ return False
+
+ add_devices(MfiSwitch(port)
+ for device in client.get_devices()
+ for port in device.ports.values()
+ if port.model in SWITCH_MODELS)
+
+
+class MfiSwitch(SwitchDevice):
+ """ An mFi switch-able device. """
+ def __init__(self, port):
+ self._port = port
+ self._target_state = None
+
+ @property
+ def should_poll(self):
+ return True
+
+ @property
+ def unique_id(self):
+ return self._port.ident
+
+ @property
+ def name(self):
+ return self._port.label
+
+ @property
+ def is_on(self):
+ return self._port.output
+
+ def update(self):
+ self._port.refresh()
+ if self._target_state is not None:
+ self._port.data['output'] = float(self._target_state)
+ self._target_state = None
+
+ def turn_on(self):
+ self._port.control(True)
+ self._target_state = True
+
+ def turn_off(self):
+ self._port.control(False)
+ self._target_state = False
+
+ @property
+ def current_power_mwh(self):
+ return int(self._port.data.get('active_pwr', 0) * 1000)
+
+ @property
+ def device_state_attributes(self):
+ attr = {}
+ attr['volts'] = round(self._port.data.get('v_rms', 0), 1)
+ attr['amps'] = round(self._port.data.get('i_rms', 0), 1)
+ return attr
diff --git a/pool/shard009/Python/0083176_forms.py b/pool/shard009/Python/0083176_forms.py
new file mode 100644
index 0000000000000000000000000000000000000000..8a4fa96ea48a85e6d0148148c482d90eb7b9157d
--- /dev/null
+++ b/pool/shard009/Python/0083176_forms.py
@@ -0,0 +1,69 @@
+# -*- coding: utf-8 -*-
+#
+# Copyright (C) Zing contributors.
+#
+# This file is a part of the Zing project. It is distributed under the GPL3
+# or later license. See the LICENSE file for a copy of the license and the
+# AUTHORS file for copyright and authorship information.
+
+from django import forms
+from django.utils.translation import gettext_lazy as _
+
+from accounts.models import CURRENCIES
+
+from .models import PaidTask, PaidTaskTypes
+
+
+class UserRatesForm(forms.Form):
+ username = forms.CharField(widget=forms.HiddenInput())
+ currency = forms.ChoiceField(
+ label=_("Currency"),
+ choices=CURRENCIES,
+ initial=CURRENCIES[0],
+ widget=forms.Select(attrs={"class": "rate"}),
+ )
+ rate = forms.FloatField(
+ label=_("Translation Rate"),
+ widget=forms.TextInput(
+ attrs={"step": "0.01", "type": "number", "class": "rate"}
+ ),
+ )
+ review_rate = forms.FloatField(
+ label=_("Review Rate"),
+ widget=forms.TextInput(
+ attrs={"step": "0.01", "type": "number", "class": "rate"}
+ ),
+ )
+ hourly_rate = forms.FloatField(
+ label=_("Hourly Rate"),
+ widget=forms.TextInput(
+ attrs={"step": "0.01", "type": "number", "class": "rate"}
+ ),
+ )
+ effective_from = forms.DateField(
+ label=_("Effective from"),
+ widget=forms.DateInput(attrs={"placeholder": "YYYY-MM-DD"}),
+ required=False,
+ )
+
+
+class PaidTaskForm(forms.ModelForm):
+ class Meta(object):
+ model = PaidTask
+ fields = ("task_type", "amount", "rate", "datetime", "description", "user")
+ widgets = {
+ "user": forms.HiddenInput(),
+ "rate": forms.HiddenInput(attrs={"id": "id_paid_task_rate"}),
+ }
+
+ def __init__(self, *args, **kwargs):
+ user = kwargs.pop("user", None)
+ super().__init__(*args, **kwargs)
+
+ if user is not None and user.hourly_rate == 0:
+ choices = [
+ item
+ for item in self.fields["task_type"].choices
+ if item[0] != PaidTaskTypes.HOURLY_WORK
+ ]
+ self.fields["task_type"].choices = choices
diff --git a/pool/shard009/Python/0083181_face_detect.py b/pool/shard009/Python/0083181_face_detect.py
new file mode 100644
index 0000000000000000000000000000000000000000..2b553f48beb9e65fc7d1b6ac3aa0f998f1f48e60
--- /dev/null
+++ b/pool/shard009/Python/0083181_face_detect.py
@@ -0,0 +1,26 @@
+import sys.os
+import cv
+
+def detectObject(image):
+ size = cv.GetSize(image)
+ grayscale = cv.CreateImage(size, 8, 1)
+ cv.cvtColor(image, grayscale, cv.CV_BGR2GRAY)
+ storage = cv.CreateMemStorage(0)
+ cv.EqualizeHist(grayscale, grayscale)
+ cascade = cv.Load("haarcascade_frontalface_alt.xml")
+ faces = cv.HarrDetectObjects(grayscale, cascade, storage, 1.2, 2
+ cv.CV_HAAR_DO_CANNY_PRUNING, (100, 100))
+ for i in faces:
+ ((x, y, w, h), d) = i
+ cv.Rectangle(image, (int(x), int(y)),
+ (int(x+w), int(y+h)),
+ cv.CV_RGB(0, 255, 0), 3, 8, 0)
+
+def displayObject(image):
+ cv.ShowImage("face", image)
+ cv.WaitKey(0)
+
+if __name__ == "__main__":
+ image = cv.LoadImage("face.png")
+ detectObject(image)
+ displayObject(image)
diff --git a/pool/shard009/Python/0083186_20d6dfa4bb1_.py b/pool/shard009/Python/0083186_20d6dfa4bb1_.py
new file mode 100644
index 0000000000000000000000000000000000000000..ea8236dded8641a388ee3f6bfb7448512cf8e7d6
--- /dev/null
+++ b/pool/shard009/Python/0083186_20d6dfa4bb1_.py
@@ -0,0 +1,52 @@
+"""empty message
+
+Revision ID: 20d6dfa4bb1
+Revises: 80d3aa6008
+Create Date: 2015-06-17 14:46:42.969164
+
+"""
+
+# revision identifiers, used by Alembic.
+revision = '20d6dfa4bb1'
+down_revision = '80d3aa6008'
+
+from alembic import op
+import sqlalchemy as sa
+from sqlalchemy.dialects import mysql
+
+def upgrade():
+ ### commands auto generated by Alembic - please adjust! ###
+ op.create_table('user_profile',
+ sa.Column('id', sa.Integer(), nullable=False),
+ sa.Column('uid', sa.Integer(), nullable=True),
+ sa.Column('age', sa.SmallInteger(), nullable=True),
+ sa.Column('sex', sa.SmallInteger(), nullable=True),
+ sa.Column('head', sa.String(length=255), nullable=True),
+ sa.Column('photo', sa.String(length=255), nullable=True),
+ sa.Column('about', sa.Text(), nullable=True),
+ sa.ForeignKeyConstraint(['uid'], ['user.id'], ),
+ sa.PrimaryKeyConstraint('id')
+ )
+ op.create_index(op.f('ix_user_profile_uid'), 'user_profile', ['uid'], unique=False)
+ op.drop_table('userinfo')
+ ### end Alembic commands ###
+
+
+def downgrade():
+ ### commands auto generated by Alembic - please adjust! ###
+ op.create_table('userinfo',
+ sa.Column('id', mysql.INTEGER(display_width=11), nullable=False),
+ sa.Column('uid', mysql.INTEGER(display_width=11), autoincrement=False, nullable=True),
+ sa.Column('age', mysql.SMALLINT(display_width=6), autoincrement=False, nullable=True),
+ sa.Column('sex', mysql.SMALLINT(display_width=6), autoincrement=False, nullable=True),
+ sa.Column('head', mysql.VARCHAR(length=255), nullable=True),
+ sa.Column('photo', mysql.VARCHAR(length=255), nullable=True),
+ sa.Column('about', mysql.TEXT(), nullable=True),
+ sa.ForeignKeyConstraint(['uid'], ['user.id'], name='userinfo_ibfk_1'),
+ sa.PrimaryKeyConstraint('id'),
+ mysql_default_charset='latin1',
+ mysql_engine='InnoDB'
+ )
+ op.drop_index(op.f('ix_user_profile_uid'), table_name='user_profile')
+ op.drop_table('user_profile')
+ ### end Alembic commands ###
diff --git a/pool/shard009/Python/0083187_threads.py b/pool/shard009/Python/0083187_threads.py
new file mode 100644
index 0000000000000000000000000000000000000000..8f89fb1b8b01a500996ad9381a87ebdca022e007
--- /dev/null
+++ b/pool/shard009/Python/0083187_threads.py
@@ -0,0 +1,217 @@
+#!/usr/bin/env python
+
+"""
+Copyright (c) 2006-2017 sqlmap developers (http://sqlmap.org/)
+See the file 'doc/COPYING' for copying permission
+"""
+
+import difflib
+import random
+import threading
+import time
+import traceback
+
+from lib.core.data import conf
+from lib.core.data import kb
+from lib.core.data import logger
+from lib.core.datatype import AttribDict
+from lib.core.enums import PAYLOAD
+from lib.core.exception import SqlmapConnectionException
+from lib.core.exception import SqlmapThreadException
+from lib.core.exception import SqlmapUserQuitException
+from lib.core.exception import SqlmapValueException
+from lib.core.settings import MAX_NUMBER_OF_THREADS
+from lib.core.settings import PYVERSION
+
+shared = AttribDict()
+
+class _ThreadData(threading.local):
+ """
+ Represents thread independent data
+ """
+
+ def __init__(self):
+ self.reset()
+
+ def reset(self):
+ """
+ Resets thread data model
+ """
+
+ self.disableStdOut = False
+ self.hashDBCursor = None
+ self.inTransaction = False
+ self.lastCode = None
+ self.lastComparisonPage = None
+ self.lastComparisonHeaders = None
+ self.lastComparisonCode = None
+ self.lastComparisonRatio = None
+ self.lastErrorPage = None
+ self.lastHTTPError = None
+ self.lastRedirectMsg = None
+ self.lastQueryDuration = 0
+ self.lastPage = None
+ self.lastRequestMsg = None
+ self.lastRequestUID = 0
+ self.lastRedirectURL = None
+ self.random = random.WichmannHill()
+ self.resumed = False
+ self.retriesCount = 0
+ self.seqMatcher = difflib.SequenceMatcher(None)
+ self.shared = shared
+ self.validationRun = 0
+ self.valueStack = []
+
+ThreadData = _ThreadData()
+
+def getCurrentThreadUID():
+ return hash(threading.currentThread())
+
+def readInput(message, default=None, checkBatch=True, boolean=False):
+ # It will be overwritten by original from lib.core.common
+ pass
+
+def getCurrentThreadData():
+ """
+ Returns current thread's local data
+ """
+
+ global ThreadData
+
+ return ThreadData
+
+def getCurrentThreadName():
+ """
+ Returns current's thread name
+ """
+
+ return threading.current_thread().getName()
+
+def exceptionHandledFunction(threadFunction, silent=False):
+ try:
+ threadFunction()
+ except KeyboardInterrupt:
+ kb.threadContinue = False
+ kb.threadException = True
+ raise
+ except Exception, ex:
+ if not silent:
+ logger.error("thread %s: %s" % (threading.currentThread().getName(), ex.message))
+
+def setDaemon(thread):
+ # Reference: http://stackoverflow.com/questions/190010/daemon-threads-explanation
+ if PYVERSION >= "2.6":
+ thread.daemon = True
+ else:
+ thread.setDaemon(True)
+
+def runThreads(numThreads, threadFunction, cleanupFunction=None, forwardException=True, threadChoice=False, startThreadMsg=True):
+ threads = []
+
+ kb.multiThreadMode = True
+ kb.threadContinue = True
+ kb.threadException = False
+
+ if threadChoice and numThreads == 1 and not (kb.injection.data and not any(_ not in (PAYLOAD.TECHNIQUE.TIME, PAYLOAD.TECHNIQUE.STACKED) for _ in kb.injection.data)):
+ while True:
+ message = "please enter number of threads? [Enter for %d (current)] " % numThreads
+ choice = readInput(message, default=str(numThreads))
+ if choice:
+ skipThreadCheck = False
+ if choice.endswith('!'):
+ choice = choice[:-1]
+ skipThreadCheck = True
+ if choice.isdigit():
+ if int(choice) > MAX_NUMBER_OF_THREADS and not skipThreadCheck:
+ errMsg = "maximum number of used threads is %d avoiding potential connection issues" % MAX_NUMBER_OF_THREADS
+ logger.critical(errMsg)
+ else:
+ conf.threads = numThreads = int(choice)
+ break
+
+ if numThreads == 1:
+ warnMsg = "running in a single-thread mode. This could take a while"
+ logger.warn(warnMsg)
+
+ try:
+ if numThreads > 1:
+ if startThreadMsg:
+ infoMsg = "starting %d threads" % numThreads
+ logger.info(infoMsg)
+ else:
+ threadFunction()
+ return
+
+ # Start the threads
+ for numThread in xrange(numThreads):
+ thread = threading.Thread(target=exceptionHandledFunction, name=str(numThread), args=[threadFunction])
+
+ setDaemon(thread)
+
+ try:
+ thread.start()
+ except Exception, ex:
+ errMsg = "error occurred while starting new thread ('%s')" % ex.message
+ logger.critical(errMsg)
+ break
+
+ threads.append(thread)
+
+ # And wait for them to all finish
+ alive = True
+ while alive:
+ alive = False
+ for thread in threads:
+ if thread.isAlive():
+ alive = True
+ time.sleep(0.1)
+
+ except (KeyboardInterrupt, SqlmapUserQuitException), ex:
+ print
+ kb.threadContinue = False
+ kb.threadException = True
+
+ if numThreads > 1:
+ logger.info("waiting for threads to finish%s" % (" (Ctrl+C was pressed)" if isinstance(ex, KeyboardInterrupt) else ""))
+ try:
+ while (threading.activeCount() > 1):
+ pass
+
+ except KeyboardInterrupt:
+ raise SqlmapThreadException("user aborted (Ctrl+C was pressed multiple times)")
+
+ if forwardException:
+ raise
+
+ except (SqlmapConnectionException, SqlmapValueException), ex:
+ print
+ kb.threadException = True
+ logger.error("thread %s: %s" % (threading.currentThread().getName(), ex.message))
+
+ except:
+ from lib.core.common import unhandledExceptionMessage
+
+ print
+ kb.threadException = True
+ errMsg = unhandledExceptionMessage()
+ logger.error("thread %s: %s" % (threading.currentThread().getName(), errMsg))
+ traceback.print_exc()
+
+ finally:
+ kb.multiThreadMode = False
+ kb.bruteMode = False
+ kb.threadContinue = True
+ kb.threadException = False
+
+ for lock in kb.locks.values():
+ if lock.locked():
+ try:
+ lock.release()
+ except:
+ pass
+
+ if conf.get("hashDB"):
+ conf.hashDB.flush(True)
+
+ if cleanupFunction:
+ cleanupFunction()
diff --git a/pool/shard009/Python/0083193_snr_goodpdf.py b/pool/shard009/Python/0083193_snr_goodpdf.py
new file mode 100644
index 0000000000000000000000000000000000000000..52ccd005441b3275f99f881dc58694202ef0a661
--- /dev/null
+++ b/pool/shard009/Python/0083193_snr_goodpdf.py
@@ -0,0 +1,90 @@
+import numpy as np
+import matplotlib.pyplot as plt
+import matplotlib as mpl
+import astropy.table as t
+from astropy.io import fits
+
+import os, sys, glob
+from itertools import product as iterprod
+
+from importer import *
+
+# personal
+import manga_tools as m
+
+from figures_tools import savefig, gen_gridspec_fig
+
+class PDFvsSNRFig(object):
+ def __init__(self, fracs):
+ self.fracs = fracs
+ self.nfracs = len(fracs)
+
+ # load figure and gridspec object
+ self.gs, self.fig = gen_gridspec_fig(
+ self.nfracs, spsize=(2.5, 1.))
+ self.subplot_inds = list(iterprod(range(self.gs._nrows), range(self.gs._ncols)))
+
+ self.fracs_plot_ix = dict(zip(sorted(fracs), self.subplot_inds))
+ self.fig_axes = {f: self.fig.add_subplot(self.gs[ix[0], ix[1]])
+ for f, ix in self.fracs_plot_ix.items()}
+
+ for f_, ax_ in self.fig_axes.items():
+ ax_.tick_params(labelsize='x-small')
+ ax_.set_xscale('log')
+ ax_.set_xlim([.1, 200.])
+ ax_.text(x=.2, y=.1, s='f = {:.2f}'.format(f_), size='x-small')
+
+ self.fig.suptitle('SNR vs PDF population', size='x-small')
+
+ @classmethod
+ def from_PDFSNR_Result(cls, res):
+ if not isinstance(res, PDFSNR_Result):
+ raise TypeError('res must be an instance of PDFSNR_Result class')
+ fracs = res.frac_dict.keys()
+ return cls(fracs)
+
+ def add_object(self, frac_dict, snr, **kwargs):
+ for fk, fv in frac_dict.items():
+ self.add_to_subplot(key=fk, frac=fv, snr=snr)
+
+ def add_to_subplot(self, key, frac, snr, **kwargs):
+ plotting_kwargs = dict(s=.5, edgecolor='None', alpha=.5)
+ kw = {**plotting_kwargs, **kwargs}
+ self.fig_axes[key].scatter(snr.flatten(), frac.flatten(), **kw)
+
+ def savefig(self):
+ savefig(self.fig, fname='snr_vs_goodpdf.png', fdir='.')
+
+class PDFSNR_Result(object):
+ def __init__(self, frac_dict, snr):
+ self.snr = snr
+ self.frac_dict = frac_dict
+
+ @classmethod
+ def from_fname(cls, fname):
+ return cls(*retrieve_snr_fracs(fname))
+
+ def __getitem__(self, k):
+ return self.frac_dict[k]
+
+def retrieve_snr_fracs(fn):
+ hdulist = fits.open(fn)
+ nfracs = hdulist['GOODFRAC'].data.shape[0]
+ fracs = {hdulist['GOODFRAC'].header['FRAC{}'.format(fri)]: \
+ hdulist['GOODFRAC'].data[fri, :, :] for fri in range(nfracs)}
+ snrs = hdulist['SNRMED'].data
+ hdulist.close()
+ return fracs, snrs
+
+if __name__ == '__main__':
+ res_fnames = glob.glob('results/*/*_res.fits')
+
+ pdfsnr_results = list(map(PDFSNR_Result.from_fname, res_fnames))
+
+ snrfig = PDFvsSNRFig.from_PDFSNR_Result(pdfsnr_results[0])
+
+ for i, res in enumerate(pdfsnr_results):
+ snrfig.add_object(frac_dict=res.frac_dict, snr=res.snr,
+ facecolor='C{}'.format(i % 10))
+
+ snrfig.savefig()
diff --git a/pool/shard009/Python/0083198_test_vis.py b/pool/shard009/Python/0083198_test_vis.py
new file mode 100644
index 0000000000000000000000000000000000000000..30f08980a2c2a1d1762decb2951d3327d2491b2e
--- /dev/null
+++ b/pool/shard009/Python/0083198_test_vis.py
@@ -0,0 +1,118 @@
+#!/usr/bin/env python3
+# -*- coding: utf-8 -*-
+"""
+test_data
+Test for visualization class
+@author: baihan
+"""
+import unittest
+import numpy as np
+import pyrsa.vis as rsv
+import pyrsa.rdm as rsr
+from scipy.spatial.distance import pdist
+
+
+class TestVIS(unittest.TestCase):
+
+ def test_vis_mds_output_shape_corresponds_to_inputs(self):
+ dis = np.random.rand(8, 10)
+ mes = "Euclidean"
+ des = {'session': 0, 'subj': 0}
+ rdms = rsr.RDMs(dissimilarities=dis,
+ dissimilarity_measure=mes,
+ descriptors=des)
+ mds_emb = rsv.mds(rdms)
+ self.assertEqual(mds_emb.shape, (8, 5, 2))
+
+ def test_vis_3d_mds_output_shape_corresponds_to_inputs(self):
+ dis = np.random.rand(8, 10)
+ mes = "Euclidean"
+ des = {'session': 0, 'subj': 0}
+ rdms = rsr.RDMs(dissimilarities=dis,
+ dissimilarity_measure=mes,
+ descriptors=des)
+ mds_emb = rsv.mds(rdms, dim=3)
+ self.assertEqual(mds_emb.shape, (8, 5, 3))
+
+ def test_vis_weighted_mds_output_shape_corresponds_to_inputs(self):
+ dis = np.random.rand(8, 10)
+ wes = np.random.random((8, 10))
+ mes = "Euclidean"
+ des = {'session': 0, 'subj': 0}
+ rdms = rsr.RDMs(dissimilarities=dis,
+ dissimilarity_measure=mes,
+ descriptors=des)
+ mds_emb = rsv.mds(rdms, weight=wes)
+ self.assertEqual(mds_emb.shape, (8, 5, 2))
+
+ def test_vis_3d_weighted_mds_output_shape_corresponds_to_inputs(self):
+ dis = np.random.rand(8, 10)
+ wes = np.random.random((8, 10))
+ mes = "Euclidean"
+ des = {'session': 0, 'subj': 0}
+ rdms = rsr.RDMs(dissimilarities=dis,
+ dissimilarity_measure=mes,
+ descriptors=des)
+ mds_emb = rsv.mds(rdms, dim=3, weight=wes)
+ self.assertEqual(mds_emb.shape[0], 8)
+ self.assertEqual(mds_emb.shape[1], 5)
+ self.assertEqual(mds_emb.shape[2], 3)
+
+ def test_vis_weighted_mds_output_behaves_like_mds(self):
+ dis = np.random.rand(8, 10)
+ wes = np.ones((8, 10))
+ mes = "Euclidean"
+ des = {'session': 0, 'subj': 0}
+ rdms = rsr.RDMs(dissimilarities=dis,
+ dissimilarity_measure=mes,
+ descriptors=des)
+ mds_emb = rsv.mds(rdms)
+ wmds_emb = rsv.mds(rdms, weight=wes)
+ np.testing.assert_allclose(pdist(mds_emb[0]), pdist(wmds_emb[0]),
+ atol=3e-1)
+
+ def test_vis_3d_weighted_mds_output_behaves_like_mds(self):
+ dis = np.random.rand(8, 10)
+ wes = np.ones((8, 10))
+ mes = "Euclidean"
+ des = {'session': 0, 'subj': 0}
+ rdms = rsr.RDMs(dissimilarities=dis,
+ dissimilarity_measure=mes,
+ descriptors=des)
+ mds_emb = rsv.mds(rdms, dim=3)
+ wmds_emb = rsv.mds(rdms, dim=3, weight=wes)
+ np.testing.assert_allclose(pdist(mds_emb[0]), pdist(wmds_emb[0]),
+ atol=3e-1)
+
+
+class Test_Icon(unittest.TestCase):
+
+ def test_Icon_no_error(self):
+ import PIL
+ from pyrsa.vis import Icon
+ import matplotlib.pyplot as plt
+ test_im = PIL.Image.fromarray(255 * np.random.rand(50, 100))
+ ic5 = Icon(image=test_im, col='red', border_width=5,
+ make_square=True, resolution=20)
+ ic5.plot(0.8, 0.8)
+ ic = Icon(image=255 * np.random.rand(50, 100), cmap='Blues')
+ ax = plt.axes(label='test')
+ ic.plot(0.5, 0.5, ax=ax)
+ ic2 = Icon(image=test_im, col='black', border_width=15,
+ string='test')
+ ic2.plot(0.8, 0.2, ax=ax, size=0.4)
+ ic2.x_tick_label(0.5, 0.15, offset=7)
+ ic2.y_tick_label(0.5, 0.25, offset=7)
+ ic3 = Icon(image=test_im, col='red', border_width=5,
+ make_square=True)
+ ic3.plot(0.2, 0.2, size=0.4)
+ ic4 = Icon(string='test')
+ ic4.plot(0.2, 0.8, size=0.4)
+ ic4.x_tick_label(0.75, 0.15, offset=7)
+ ic4.y_tick_label(0.75, 0.25, offset=17)
+
+ self.assertEqual(ic2.image, test_im)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/pool/shard009/Python/0083200_api2_test.py b/pool/shard009/Python/0083200_api2_test.py
new file mode 100644
index 0000000000000000000000000000000000000000..fdb7b3cf8ba634c5175ba9581f2e427fee9b28a1
--- /dev/null
+++ b/pool/shard009/Python/0083200_api2_test.py
@@ -0,0 +1,59 @@
+'''Test cases for PySide API2 support'''
+
+
+import unittest
+import sys
+
+from PySide2.QtGui import QIntValidator, QValidator
+from PySide2.QtWidgets import QWidget, QSpinBox, QApplication
+
+from helper import UsesQApplication
+
+class WidgetValidatorQInt(QWidget, QIntValidator):
+ def __init__(self, parent=None):
+ QWidget.__init__(self, parent)
+ QIntValidator.__init__(self, parent)
+
+class WidgetValidatorQSpinBox(QSpinBox):
+ def __init__(self, parent=None):
+ QSpinBox.__init__(self, parent)
+
+ def fixup(self, text):
+ print("It was called!")
+
+class DoubleQObjectInheritanceTest(UsesQApplication):
+
+ def testDouble(self):
+ '''Double inheritance from QObject classes'''
+
+ obj = WidgetValidatorQInt()
+
+ #QIntValidator methods
+ state, string, number = obj.validate('Test', 0)
+ self.assertEqual(state, QValidator.Invalid)
+ state, string, number = obj.validate('33', 0)
+ self.assertEqual(state, QValidator.Acceptable)
+
+ def testQSpinBox(self):
+ obj = WidgetValidatorQSpinBox()
+
+ obj.setRange(1, 10)
+ obj.setValue(0)
+ self.assertEqual(obj.value(), 1)
+
+class QClipboardTest(UsesQApplication):
+
+ def testQClipboard(self):
+ #skip this test on MacOS because the clipboard is not available during the ssh session
+ #this cause problems in the buildbot
+ if sys.platform == 'darwin':
+ return
+ clip = QApplication.clipboard()
+ clip.setText("Testing this thing!")
+
+ text, subtype = clip.text("")
+ self.assertEqual(subtype, "plain")
+ self.assertEqual(text, "Testing this thing!")
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/pool/shard009/Python/0083204_test_json.py b/pool/shard009/Python/0083204_test_json.py
new file mode 100644
index 0000000000000000000000000000000000000000..222d87e79f5d2a7567632cb0dd14eb15b399037c
--- /dev/null
+++ b/pool/shard009/Python/0083204_test_json.py
@@ -0,0 +1,88 @@
+# -*- coding: utf-8 -*-
+#
+# Copyright (C) 2014 Carlos Jenkins
+#
+# 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.
+
+"""
+Test confspec.providers.json module.
+"""
+
+from __future__ import absolute_import, division, print_function
+
+from pytest import raises
+
+from confspec.manager import ConfigMg
+from confspec.providers.json import JSONFormatProvider
+
+from ..options import spec
+
+
+input_str = """\
+{
+ "collectionconfigopts": {
+ "configlistint": [
+ 1,
+ 2,
+ 3,
+ 4,
+ 5
+ ]
+ },
+ "entityconfigopts": {
+ "configboolean": true,
+ "configfloat": 100.0,
+ "configint": 0
+ }
+}
+"""
+
+bad_inputs = [
+ # Bad input
+ ("""dasdsdaddP{,,},11""", ValueError),
+ # Valid JSON, not object
+ ("""100""", SyntaxError),
+ # First level keys are no categories
+ ("""{"foo": 100}""", SyntaxError),
+ # Unknown category
+ ("""{"mynonexistantcategory": {"foo": 100}}""", None),
+ # Unknown key
+ ("""{"entityconfigopts": {"unknownkey": 99}}""", None),
+ # Known key in wrong category
+ ("""{"collectionconfigopts": {"configint": 99}}""", SyntaxError),
+ # Setting a bad value
+ ("""{"entityconfigopts": {"configint": "abc"}}""", ValueError),
+]
+
+
+def test_JSONFormatProvider():
+
+ mgr = ConfigMg(spec)
+ JSONFormatProvider.do_import(mgr, input_str)
+ output_str = JSONFormatProvider.do_export(mgr)
+ print('Expected output:')
+ print(output_str)
+ assert input_str.strip() == output_str.strip()
+
+ # Check bad input (default safe=True)
+ mgr._safe = True
+ for bad, exc in bad_inputs:
+ JSONFormatProvider.do_import(mgr, bad)
+
+ # Check bad input (safe=False)
+ mgr._safe = False
+ for bad, exc in bad_inputs:
+ if exc is not None:
+ with raises(exc):
+ JSONFormatProvider.do_import(mgr, bad)
diff --git a/pool/shard009/Python/0083205_conanfile.py b/pool/shard009/Python/0083205_conanfile.py
new file mode 100644
index 0000000000000000000000000000000000000000..fe2a1a476bd7cdd500c16cc176b28b194106a95a
--- /dev/null
+++ b/pool/shard009/Python/0083205_conanfile.py
@@ -0,0 +1,17 @@
+from conans import ConanFile, CMake, tools
+import os
+
+
+class HelloWorldConan(ConanFile):
+ settings = "os", "compiler", "build_type", "arch"
+ generators = "cmake"
+ name = "helloworld"
+ version = "0.0.1"
+
+ requires = "grpc/1.27.3@orbitdeps/stable"
+ build_requires = "grpc_codegen/1.27.3@orbitdeps/stable"
+
+ def build(self):
+ cmake = CMake(self)
+ cmake.configure()
+ cmake.build()
diff --git a/pool/shard009/Python/0083206_pbkdf2.py b/pool/shard009/Python/0083206_pbkdf2.py
new file mode 100644
index 0000000000000000000000000000000000000000..6a297ef85a733bce00135c97ddc808cba21ec833
--- /dev/null
+++ b/pool/shard009/Python/0083206_pbkdf2.py
@@ -0,0 +1,172 @@
+# -*- coding: utf-8 -*-
+"""
+ pbkdf2
+ ~~~~~~
+
+ This module implements pbkdf2 for Python. It also has some basic
+ tests that ensure that it works. The implementation is straightforward
+ and uses stdlib only stuff and can be easily be copy/pasted into
+ your favourite application.
+
+ Use this as replacement for bcrypt that does not need a c implementation
+ of a modified blowfish crypto algo.
+
+ Example usage:
+
+ >>> pbkdf2_hex('what i want to hash', 'the random salt')
+ 'fa7cc8a2b0a932f8e6ea42f9787e9d36e592e0c222ada6a9'
+
+ How to use this:
+
+ 1. Use a constant time string compare function to compare the stored hash
+ with the one you're generating::
+
+ def safe_str_cmp(a, b):
+ if len(a) != len(b):
+ return False
+ rv = 0
+ for x, y in izip(a, b):
+ rv |= ord(x) ^ ord(y)
+ return rv == 0
+
+ 2. Use `os.urandom` to generate a proper salt of at least 8 byte.
+ Use a unique salt per hashed password.
+
+ 3. Store ``algorithm$salt:costfactor$hash`` in the database so that
+ you can upgrade later easily to a different algorithm if you need
+ one. For instance ``PBKDF2-256$thesalt:10000$deadbeef...``.
+
+
+ :copyright: (c) Copyright 2011 by Armin Ronacher.
+ :license: BSD, see LICENSE for more details.
+"""
+from binascii import hexlify
+import hmac
+import hashlib
+import sys
+from struct import Struct
+from operator import xor
+from itertools import starmap
+
+PY3 = sys.version_info[0] == 3
+
+if not PY3:
+ from itertools import izip as zip
+
+if PY3:
+ text_type = str
+else:
+ text_type = unicode
+
+
+_pack_int = Struct('>I').pack
+
+
+def bytes_(s, encoding='utf8', errors='strict'):
+ if isinstance(s, text_type):
+ return s.encode(encoding, errors)
+ return s
+
+
+def hexlify_(s):
+ if PY3:
+ return str(hexlify(s), encoding="utf8")
+ else:
+ return s.encode('hex')
+
+
+def range_(*args):
+ if PY3:
+ return range(*args)
+ else:
+ return xrange(*args)
+
+
+def pbkdf2_hex(data, salt, iterations=1000, keylen=24, hashfunc=None):
+ """Like :func:`pbkdf2_bin` but returns a hex encoded string."""
+ return hexlify_(pbkdf2_bin(data, salt, iterations, keylen, hashfunc))
+
+
+def pbkdf2_bin(data, salt, iterations=1000, keylen=24, hashfunc=None):
+ """Returns a binary digest for the PBKDF2 hash algorithm of `data`
+ with the given `salt`. It iterates `iterations` time and produces a
+ key of `keylen` bytes. By default SHA-1 is used as hash function,
+ a different hashlib `hashfunc` can be provided.
+ """
+ hashfunc = hashfunc or hashlib.sha1
+ mac = hmac.new(bytes_(data), None, hashfunc)
+
+ def _pseudorandom(x, mac=mac):
+ h = mac.copy()
+ h.update(bytes_(x))
+ if PY3:
+ return [x for x in h.digest()]
+ else:
+ return map(ord, h.digest())
+ buf = []
+ for block in range_(1, -(-keylen // mac.digest_size) + 1):
+ rv = u = _pseudorandom(bytes_(salt) + _pack_int(block))
+ for i in range_(iterations - 1):
+ if PY3:
+ u = _pseudorandom(bytes(u))
+ else:
+ u = _pseudorandom(''.join(map(chr, u)))
+ rv = starmap(xor, zip(rv, u))
+ buf.extend(rv)
+ if PY3:
+ return bytes(buf)[:keylen]
+ else:
+ return ''.join(map(chr, buf))[:keylen]
+
+
+def test():
+ failed = []
+
+ def check(data, salt, iterations, keylen, expected):
+ rv = pbkdf2_hex(data, salt, iterations, keylen)
+ if rv != expected:
+ print('Test failed:')
+ print(' Expected: %s' % expected)
+ print(' Got: %s' % rv)
+ print(' Parameters:')
+ print(' data=%s' % data)
+ print(' salt=%s' % salt)
+ print(' iterations=%d' % iterations)
+ failed.append(1)
+
+ # From RFC 6070
+ check('password', 'salt', 1, 20,
+ '0c60c80f961f0e71f3a9b524af6012062fe037a6')
+ check('password', 'salt', 2, 20,
+ 'ea6c014dc72d6f8ccd1ed92ace1d41f0d8de8957')
+ check('password', 'salt', 4096, 20,
+ '4b007901b765489abead49d926f721d065a429c1')
+ check('passwordPASSWORDpassword', 'saltSALTsaltSALTsaltSALTsaltSALTsalt',
+ 4096, 25, '3d2eec4fe41c849b80c8d83662c0e44a8b291a964cf2f07038')
+ check('pass\x00word', 'sa\x00lt', 4096, 16,
+ '56fa6aa75548099dcc37d7f03425e0c3')
+ # This one is from the RFC but it just takes for ages
+ ##check('password', 'salt', 16777216, 20,
+ ## 'eefe3d61cd4da4e4e9945b3d6ba2158c2634e984')
+
+ # From Crypt-PBKDF2
+ check('password', 'ATHENA.MIT.EDUraeburn', 1, 16,
+ 'cdedb5281bb2f801565a1122b2563515')
+ check('password', 'ATHENA.MIT.EDUraeburn', 1, 32,
+ 'cdedb5281bb2f801565a1122b25635150ad1f7a04bb9f3a333ecc0e2e1f70837')
+ check('password', 'ATHENA.MIT.EDUraeburn', 2, 16,
+ '01dbee7f4a9e243e988b62c73cda935d')
+ check('password', 'ATHENA.MIT.EDUraeburn', 2, 32,
+ '01dbee7f4a9e243e988b62c73cda935da05378b93244ec8f48a99e61ad799d86')
+ check('password', 'ATHENA.MIT.EDUraeburn', 1200, 32,
+ '5c08eb61fdf71e4e4ec3cf6ba1f5512ba7e52ddbc5e5142f708a31e2e62b1e13')
+ check('X' * 64, 'pass phrase equals block size', 1200, 32,
+ '139c30c0966bc32ba55fdbf212530ac9c5ec59f1a452f5cc9ad940fea0598ed1')
+ check('X' * 65, 'pass phrase exceeds block size', 1200, 32,
+ '9ccad6d468770cd51b10e6a68721be611a8b4d282601db3b36be9246915ec82a')
+
+ raise SystemExit(bool(failed))
+
+
+if __name__ == '__main__':
+ test()
diff --git a/pool/shard009/Python/0083209_conftest.py b/pool/shard009/Python/0083209_conftest.py
new file mode 100644
index 0000000000000000000000000000000000000000..ac5c73198773b1b0ef85ffa3bca1c512b222b56d
--- /dev/null
+++ b/pool/shard009/Python/0083209_conftest.py
@@ -0,0 +1,83 @@
+import pytest
+
+import asyncio
+import threading
+
+from cloudbot import setup_bot
+from cloudbot.util import paths
+from cloudbot.bot import CloudBot
+
+
+class ThreadFixture(object):
+ def stop(self):
+ self.thread.join(15)
+
+ @property
+ def alive(self):
+ return self.thread.is_alive()
+
+
+@pytest.fixture(scope='session')
+def server(request):
+ """Return a miniircd server bound to localhost
+ """
+ from expp.cloudbot.test import miniircd
+ class IRCOptions(object):
+ listen = '127.0.0.1'
+ ports = [6667]
+ password = None
+ ssl_pem_file = None
+ motd = None
+ verbose = False
+ debug = False
+ logdir = None
+ chroot = False
+ setuid = False
+ statedir = None
+ ssl = False
+
+ server = miniircd.Server(IRCOptions())
+ thread = threading.Thread(target=server.start)
+ thread.daemon = True
+ thread.start()
+
+ def fin():
+ thread.join(5)
+ request.addfinalizer(fin)
+
+ return server
+
+
+def run_bot(loop):
+ asyncio.set_event_loop(loop)
+
+ paths.add_plugin_dir('plugins')
+ paths.set_path('config_file', 'test/conf.test.json')
+ paths.set_path('log_dir', 'test/logs')
+ paths.set_path('data_dir', 'test/data')
+ paths.reload_paths(daemon=True)
+ setup_bot()
+
+ bot = CloudBot(loop)
+ bot.run()
+
+
+@pytest.fixture(scope='session')
+def bot(request, server):
+ """Return a CloudBot instance connected to a local irc server
+ """
+
+ thread = threading.Thread(target=run_bot, args=(asyncio.get_event_loop(),))
+ thread.daemon = True
+ thread.start()
+
+ def fin():
+ thread.join(5)
+ request.addfinalizer(fin)
+
+
+@pytest.fixture(scope='session')
+def bot_blocking(request, server):
+ """Return a blocking CloudBot instance connected to a local irc server
+ """
+ run_bot(asyncio.get_event_loop())
diff --git a/pool/shard009/Python/0083218_block_storage.py b/pool/shard009/Python/0083218_block_storage.py
new file mode 100644
index 0000000000000000000000000000000000000000..bd58e17f291cff1f1a922231885f4a7895e02a03
--- /dev/null
+++ b/pool/shard009/Python/0083218_block_storage.py
@@ -0,0 +1,24 @@
+from oslo_config import cfg
+
+
+block_storage_group = cfg.OptGroup('block_storage',
+ title='Block Storage Options')
+
+# some config options here
+
+driver_path = cfg.StrOpt(
+ 'driver_path',
+ default='calplus.v1.block_storage.drivers',
+ help='Default path to block storage drivers',
+)
+
+ALL_OPTS = ([driver_path])
+
+
+def register_opts(conf):
+ conf.register_group(block_storage_group)
+ conf.register_opts(ALL_OPTS, group=block_storage_group)
+
+
+def list_opts():
+ return {block_storage_group: ALL_OPTS}
diff --git a/pool/shard009/Python/0083220_make_test_db.py b/pool/shard009/Python/0083220_make_test_db.py
new file mode 100644
index 0000000000000000000000000000000000000000..13fdd98b58a004ce0c42202b15d78f4c72c622db
--- /dev/null
+++ b/pool/shard009/Python/0083220_make_test_db.py
@@ -0,0 +1,148 @@
+# Copyright (c) 2017 Brian Ginsburg, Julie Rutherford-Fields
+# This work is available under the "3-clause ('new') BSD License”.
+# Please see the file COPYING in this distribution
+# for license terms.
+
+# Mocked data, for testing only
+
+import datetime
+from app import db
+from app.models import User, Message
+
+db.create_all()
+
+# create a few of users
+thope = User(name = 'Tony Hope'
+ , email = 'thope@yahoo.com'
+ , is_teergrube = True)
+
+rex = User(name = 'Rex'
+ , is_teergrube = False)
+
+steve = User(name = 'Steve'
+ , is_teergrube = False)
+
+
+# first thread tests multiple messages and a case with two replies to message
+# this tests threading in the database and the views
+# the first message has addressee
+first_rex = Message(message_id = '<00000000.0000001@infolost.party>'
+ , to = None
+ , to_name = None
+ , reply_to = 'rex345@yahoo.com'
+ , plus_tag = 'LAX1'
+ , datetime = datetime.datetime.fromtimestamp(1284286794)
+ , subject = 'URGENT'
+ , body = 'Root of the first thread'
+ , sender = rex
+ , parent = None)
+
+first_thope = Message(message_id = '<00000000.0000002@serif.mail>'
+ , to = 'Rex'
+ , to_name = 'rex345@yahoo.com'
+ , reply_to = 'thope@yahoo.com'
+ , plus_tag = 'LAX1'
+ , datetime = datetime.datetime.fromtimestamp(1284296134)
+ , subject = 'Re: URGENT'
+ , body = 'First message from teergrube in first thread'
+ , sender = thope
+ , parent = first_rex)
+
+second_rex = Message(message_id='<00000000.0000003@infolost.party>'
+ , to = 'thope@yahoo.com'
+ , to_name = 'Tony Hope'
+ , reply_to = 'rex345@yahoo.com'
+ , plus_tag = 'LAX1'
+ , datetime = datetime.datetime.fromtimestamp(1284396134)
+ , subject = 'Re: URGENT'
+ , body = 'Second message from Rex in first thread'
+ , sender = rex
+ , parent = first_thope)
+
+second_thope = Message(message_id='<00000000.0000004@serif.mail>'
+ , to = 'rex345@yahoo.com'
+ , to_name = 'Rex'
+ , reply_to = 'thope@yahoo.com'
+ , plus_tag = 'LAX1'
+ , datetime = datetime.datetime.fromtimestamp(1284496134)
+ , subject = 'Re: URGENT'
+ , body = 'Second message from teergrube in first thread'
+ , sender = thope
+ , parent = second_rex)
+
+third_rex = Message(message_id='<00000000.0000005@infolost.party>'
+ , to = 'thope@yahoo.com'
+ , to_name = 'Tony Hope'
+ , reply_to = 'rex345@yahoo.com'
+ , plus_tag = 'LAX1'
+ , datetime = datetime.datetime.fromtimestamp(1284596134)
+ , subject = 'Re: URGENT'
+ , body = 'Third message from Rex in first thread'
+ , sender = rex
+ , parent = second_thope)
+
+fourth_rex = Message(message_id='<00000000.0000006@infolost.party>'
+ , to = 'thope@yahoo.com'
+ , to_name = 'Tony Hope'
+ , reply_to = 'rex345@yahoo.com'
+ , plus_tag = 'LAX1'
+ , datetime = datetime.datetime.fromtimestamp(1284596934)
+ , subject = 'Re: URGENT'
+ , body = 'Fourth message from Rex in first thread (has no reply).'
+ , sender = rex
+ , parent = second_thope)
+
+third_thope = Message(message_id='<00000000.0000007@serif.mail>'
+ , to = 'rex345@yahoo.com'
+ , to_name = 'Rex'
+ , reply_to = 'thope@yahoo.com'
+ , plus_tag = 'LAX1'
+ , datetime = datetime.datetime.fromtimestamp(1284696134)
+ , subject = 'Re: URGENT'
+ , body = 'Third message from teergrube in first thread (reply to Rex\'s third message)'
+ , sender = thope
+ , parent = third_rex)
+
+
+# second thread has an initial addressee
+# the first and second threads may be interleaved by id in the database
+# this test checks the threads will be displayed separately in the views
+first_steve = Message(message_id='<00000000.0000008@infolost.party>'
+ , to = 'thope@yahoo.com'
+ , to_name = None
+ , reply_to = 'steve6734@yahoo.com'
+ , plus_tag = 'IAD1'
+ , datetime = datetime.datetime.fromtimestamp(1284296484)
+ , subject = 'Dear Friend,'
+ , body = 'Root of a second thread'
+ , sender = steve
+ , parent = None)
+
+fourth_thope = Message(message_id='<00000000.0000009@serif.mail>'
+ , to = 'steve6734@yahoo.com'
+ , to_name = 'Steve'
+ , reply_to = 'thope@yahoo.com'
+ , plus_tag = 'IAD1'
+ , datetime = datetime.datetime.fromtimestamp(1284699934)
+ , subject = 'Re: Dear Friend,'
+ , body = 'First message from teergrube in second thread'
+ , sender = thope
+ , parent = first_steve)
+
+second_steve = Message(message_id='<00000000.0000010@lost.party>'
+ , to = 'thope@yahoo.com'
+ , to_name = 'Tony Hope'
+ , reply_to = 'steve6734@yahoo.com'
+ , plus_tag = 'IAD1'
+ , datetime = datetime.datetime.fromtimestamp(1284299999)
+ , subject = 'Re: Dear Friend,'
+ , body = 'Second message from Steve in first thread'
+ , sender = steve
+ , parent = fourth_thope)
+
+
+db.session.add_all( [thope, rex, steve, first_rex, first_thope, second_rex,
+ second_thope, third_rex, fourth_rex, third_thope,
+ first_steve, fourth_thope, second_steve] )
+
+db.session.commit()
diff --git a/pool/shard009/Python/0083222_sequence_cnn_encoder.py b/pool/shard009/Python/0083222_sequence_cnn_encoder.py
new file mode 100644
index 0000000000000000000000000000000000000000..a0642da265a169c8bb48b76b7e78483cbdb0945a
--- /dev/null
+++ b/pool/shard009/Python/0083222_sequence_cnn_encoder.py
@@ -0,0 +1,148 @@
+"""Encoder for sentence classification with 1D convolutions and max-pooling."""
+
+from typing import Optional, Tuple, List
+
+from typeguard import check_argument_types
+import tensorflow as tf
+
+from neuralmonkey.dataset import Dataset
+from neuralmonkey.decorators import tensor
+from neuralmonkey.model.model_part import ModelPart, FeedDict, InitializerSpecs
+from neuralmonkey.model.stateful import Stateful
+from neuralmonkey.nn.utils import dropout
+from neuralmonkey.vocabulary import Vocabulary
+from neuralmonkey.tf_utils import get_variable
+
+
+class SequenceCNNEncoder(ModelPart, Stateful):
+ """Encoder processing a sequence using a CNN."""
+
+ # pylint: disable=too-many-arguments
+ def __init__(self,
+ name: str,
+ vocabulary: Vocabulary,
+ data_id: str,
+ embedding_size: int,
+ filters: List[Tuple[int, int]],
+ max_input_len: Optional[int] = None,
+ dropout_keep_prob: float = 1.0,
+ save_checkpoint: Optional[str] = None,
+ load_checkpoint: Optional[str] = None,
+ initializers: InitializerSpecs = None) -> None:
+ """Create a new instance of the CNN sequence encoder.
+
+ Based on: Yoon Kim: Convolutional Neural Networks for Sentence
+ Classification (http://emnlp2014.org/papers/pdf/EMNLP2014181.pdf)
+
+ Arguments:
+ vocabulary: Input vocabulary
+ data_id: Identifier of the data series fed to this encoder
+ name: An unique identifier for this encoder
+ max_input_len: Maximum length of an encoded sequence
+ embedding_size: The size of the embedding vector assigned
+ to each word
+ filters: Specification of CNN filters. It is a list of tuples
+ specifying the filter size and number of channels.
+ dropout_keep_prob: The dropout keep probability
+ (default 1.0)
+ """
+ check_argument_types()
+ ModelPart.__init__(self, name, save_checkpoint, load_checkpoint,
+ initializers)
+
+ self.vocabulary = vocabulary
+ self.data_id = data_id
+ self.max_input_len = max_input_len
+ self.embedding_size = embedding_size
+ self.dropout_keep_prob = dropout_keep_prob
+ self.filters = filters
+
+ # pylint: disable=no-self-use
+ @tensor
+ def train_mode(self) -> tf.Tensor:
+ return tf.placeholder(tf.bool, shape=[], name="train_mode")
+
+ @tensor
+ def inputs(self) -> tf.Tensor:
+ return tf.placeholder(
+ tf.int32, shape=[None, None], name="encoder_input")
+
+ @tensor
+ def input_mask(self) -> tf.Tensor:
+ return tf.placeholder(
+ tf.float32, shape=[None, None], name="encoder_padding")
+ # pylint: enable=no-self-use
+
+ @tensor
+ def embedded_inputs(self) -> tf.Tensor:
+ with tf.variable_scope("input_projection"):
+ embedding_matrix = get_variable(
+ "word_embeddings",
+ [len(self.vocabulary), self.embedding_size],
+ initializer=tf.glorot_uniform_initializer())
+ return dropout(
+ tf.nn.embedding_lookup(embedding_matrix, self.inputs),
+ self.dropout_keep_prob,
+ self.train_mode)
+
+ @tensor
+ def output(self) -> tf.Tensor:
+ pooled_outputs = []
+ for filter_size, num_filters in self.filters:
+ with tf.variable_scope("conv-maxpool-%s" % filter_size):
+ # Convolution Layer
+ filter_shape = [filter_size, self.embedding_size, num_filters]
+ w_filter = get_variable(
+ "conv_W", filter_shape,
+ initializer=tf.glorot_uniform_initializer())
+ b_filter = get_variable(
+ "conv_bias", [num_filters],
+ initializer=tf.zeros_initializer())
+ conv = tf.nn.conv1d(
+ self.embedded_inputs,
+ w_filter,
+ stride=1,
+ padding="VALID",
+ name="conv")
+
+ # Apply nonlinearity
+ conv_relu = tf.nn.relu(tf.nn.bias_add(conv, b_filter))
+
+ # Max-pooling over the outputs
+ pooled = tf.reduce_max(conv_relu, 1)
+ pooled_outputs.append(pooled)
+
+ # Combine all the pooled features
+ return tf.concat(pooled_outputs, axis=1)
+
+ def feed_dict(self, dataset: Dataset, train: bool = False) -> FeedDict:
+ """Populate the feed dictionary with the encoder inputs.
+
+ Encoder input placeholders:
+ ``encoder_input``: Stores indices to the vocabulary,
+ shape (batch, time)
+ ``encoder_padding``: Stores the padding (ones and zeros,
+ indicating valid words and positions after the end
+ of sentence, shape (batch, time)
+ ``train_mode``: Boolean scalar specifying the mode (train
+ vs runtime)
+
+ Arguments:
+ dataset: The dataset to use
+ train: Boolean flag telling whether it is training time
+ """
+ # pylint: disable=invalid-name
+ fd = {} # type: FeedDict
+ fd[self.train_mode] = train
+ sentences = dataset.get_series(self.data_id)
+
+ vectors, paddings = self.vocabulary.sentences_to_tensor(
+ list(sentences), self.max_input_len, pad_to_max_len=False,
+ train_mode=train)
+
+ # as sentences_to_tensor returns lists of shape (time, batch),
+ # we need to transpose
+ fd[self.inputs] = list(zip(*vectors))
+ fd[self.input_mask] = list(zip(*paddings))
+
+ return fd
diff --git a/pool/shard009/Python/0083228_hyper_tuner.py b/pool/shard009/Python/0083228_hyper_tuner.py
new file mode 100644
index 0000000000000000000000000000000000000000..8ee8a7b50faefe89a15ed8ed20290fc22ee1bc9f
--- /dev/null
+++ b/pool/shard009/Python/0083228_hyper_tuner.py
@@ -0,0 +1,64 @@
+#! /usr/bin/env python
+# -*- coding: utf-8 -*-
+
+__author__ = 'maxim'
+
+import numpy as np
+import time
+
+from ..base import *
+from ..spec import ParsedSpec
+from ..bayesian.sampler import DefaultSampler
+from ..bayesian.strategy import BayesianStrategy, BayesianPortfolioStrategy
+
+
+strategies = {
+ 'bayesian': lambda sampler, params: BayesianStrategy(sampler, **params),
+ 'portfolio': lambda sampler, params: BayesianPortfolioStrategy(sampler, **params),
+}
+
+
+class HyperTuner(object):
+ def __init__(self, hyper_params_spec, solver_generator, **strategy_params):
+ self._solver_generator = solver_generator
+
+ self._parsed = ParsedSpec(hyper_params_spec)
+ info('Spec size:', self._parsed.size())
+
+ sampler = DefaultSampler()
+ sampler.add_uniform(self._parsed.size())
+
+ strategy_gen = as_function(strategy_params.get('strategy', 'bayesian'), presets=strategies)
+ self._strategy = strategy_gen(sampler, strategy_params)
+
+ self._timeout = strategy_params.get('timeout', 0)
+ self._max_points = strategy_params.get('max_points', None)
+
+ def tune(self):
+ info('Start hyper tuner')
+
+ while True:
+ if self._max_points is not None and len(self._strategy.values) >= self._max_points:
+ info('Maximum points reached: max_points=%d. Aborting hyper tuner' % self._max_points)
+ break
+
+ point = self._strategy.next_proposal()
+ hyper_params = self._parsed.instantiate(point)
+ solver = self._solver_generator(hyper_params)
+
+ accuracy = solver.train()
+
+ previous_max = np.max(self._strategy.values) if len(self._strategy.values) > 0 else -np.inf
+ self._strategy.add_point(point, accuracy)
+ index = len(self._strategy.values)
+
+ marker = '!' if accuracy > previous_max else ' '
+ info('%s [%d] accuracy=%.4f, params: %s' % (marker, index, accuracy, smart_str(hyper_params)))
+ info('Current top-%d:' % min(len(self._strategy.values), 5))
+ for value in sorted(self._strategy.values, reverse=True)[:5]:
+ info(' accuracy=%.4f' % value)
+
+ if self._timeout:
+ time.sleep(self._timeout)
+
+ solver.terminate()
diff --git a/pool/shard009/Python/0083230_firewall.py b/pool/shard009/Python/0083230_firewall.py
new file mode 100644
index 0000000000000000000000000000000000000000..727ad21ce5f9d0cc8df5eb2a7c657abb5fd42434
--- /dev/null
+++ b/pool/shard009/Python/0083230_firewall.py
@@ -0,0 +1,269 @@
+#
+# Chris Lumens
+#
+# Copyright 2005, 2006, 2007 Red Hat, Inc.
+#
+# This copyrighted material is made available to anyone wishing to use, modify,
+# copy, or redistribute it subject to the terms and conditions of the GNU
+# General Public License v.2. This program is distributed in the hope that it
+# will be useful, but WITHOUT ANY WARRANTY expressed or implied, including the
+# implied warranties of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+# See the GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License along with
+# this program; if not, write to the Free Software Foundation, Inc., 51
+# Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. Any Red Hat
+# trademarks that are incorporated in the source code or documentation are not
+# subject to the GNU General Public License and may only be used or replicated
+# with the express permission of Red Hat, Inc.
+#
+from pykickstart.version import FC3, F9, F10, F14, F20, F28
+from pykickstart.base import KickstartCommand
+from pykickstart.options import ExtendAction, ExtendConstAction, KSOptionParser, commaSplit
+
+class FC3_Firewall(KickstartCommand):
+ removedKeywords = KickstartCommand.removedKeywords
+ removedAttrs = KickstartCommand.removedAttrs
+
+ def __init__(self, writePriority=0, *args, **kwargs):
+ KickstartCommand.__init__(self, writePriority, *args, **kwargs)
+ self.op = self._getParser()
+
+ self.enabled = kwargs.get("enabled", None)
+ self.ports = kwargs.get("ports", [])
+ self.trusts = kwargs.get("trusts", [])
+
+ def __str__(self):
+ extra = []
+ filteredPorts = []
+
+ retval = KickstartCommand.__str__(self)
+
+ if self.enabled is None:
+ return retval
+
+ if self.enabled:
+ # It's possible we have words in the ports list instead of
+ # port:proto (s-c-kickstart may do this). So, filter those
+ # out into their own list leaving what we expect.
+ for port in self.ports:
+ if port == "ssh:tcp":
+ extra.append(" --ssh")
+ elif port == "telnet:tcp":
+ extra.append(" --telnet")
+ elif port == "smtp:tcp":
+ extra.append(" --smtp")
+ elif port == "http:tcp":
+ extra.append(" --http")
+ elif port == "ftp:tcp":
+ extra.append(" --ftp")
+ else:
+ filteredPorts.append(port)
+
+ # All the port:proto strings go into a comma-separated list.
+ portstr = ",".join(filteredPorts)
+ if portstr:
+ portstr = " --port=" + portstr
+
+ extrastr = "".join(extra)
+ truststr = ",".join(self.trusts)
+
+ if truststr:
+ truststr = " --trust=" + truststr
+
+ # The output port list consists only of port:proto for
+ # everything that we don't recognize, and special options for
+ # those that we do.
+ retval += "# Firewall configuration\nfirewall --enabled%s%s%s\n" % (extrastr, portstr, truststr)
+ else:
+ retval += "# Firewall configuration\nfirewall --disabled\n"
+
+ return retval
+
+ def _getParser(self):
+ def firewall_port_cb(value):
+ retval = []
+ for p in value.split(","):
+ p = p.strip()
+ if p.find(":") == -1:
+ p = "%s:tcp" % p
+
+ retval.append(p)
+
+ return retval
+
+ op = KSOptionParser(prog="firewall", description="""
+ This option corresponds to the Firewall Configuration
+ screen in the installation program""",
+ version=FC3)
+ op.add_argument("--disable", "--disabled", dest="enabled",
+ action="store_false", version=FC3,
+ help="Do not configure any iptables rules.")
+ op.add_argument("--enable", "--enabled", dest="enabled",
+ action="store_true", default=True, help="""
+ Reject incoming connections that are not in response
+ to outbound requests, such as DNS replies or DHCP
+ requests. If access to services running on this machine
+ is needed, you can choose to allow specific services
+ through the firewall.""", version=FC3)
+ op.add_argument("--ftp", dest="ports", action="append_const",
+ const="21:tcp", version=FC3,
+ help="Open port 21:tcp")
+ op.add_argument("--http", dest="ports", action=ExtendConstAction,
+ const=["80:tcp", "443:tcp"], nargs=0, version=FC3,
+ help="Open ports 80:tcp and 443:tcp")
+ op.add_argument("--smtp", dest="ports", action="append_const",
+ const="25:tcp", version=FC3,
+ help="Open port 25:tcp")
+ op.add_argument("--ssh", dest="ports", action="append_const",
+ const="22:tcp", version=FC3,
+ help="Open port 22:tcp")
+ op.add_argument("--telnet", dest="ports", action="append_const",
+ const="23:tcp", version=FC3,
+ help="Open port 23:tcp")
+ op.add_argument("--high", deprecated=FC3, help="")
+ op.add_argument("--medium", deprecated=FC3, help="")
+ op.add_argument("--port", dest="ports", action=ExtendAction,
+ type=firewall_port_cb, help="""
+ You can specify that ports be allowed through the firewall
+ using the port:protocol format. You can also specify ports
+ numerically. Multiple ports can be combined into one option
+ as long as they are separated by commas. For example::
+
+ ``firewall --port=imap:tcp,1234:ucp,47``""",
+ version=FC3)
+ op.add_argument("--trust", dest="trusts", action="append", help="""
+ Listing a device here, such as eth0, allows all traffic
+ coming from that device to go through the firewall. To
+ list more than one device, use --trust eth0 --trust eth1.
+ Do NOT use a comma-separated format such as
+ --trust eth0, eth1.""", version=FC3)
+ return op
+
+ def parse(self, args):
+ ns = self.op.parse_args(args=args, lineno=self.lineno)
+ self.set_to_self(ns)
+ return self
+
+class F9_Firewall(FC3_Firewall):
+ removedKeywords = FC3_Firewall.removedKeywords
+ removedAttrs = FC3_Firewall.removedAttrs
+
+ def _getParser(self):
+ op = FC3_Firewall._getParser(self)
+ op.remove_argument("--high", version=F9)
+ op.remove_argument("--medium", version=F9)
+ return op
+
+class F10_Firewall(F9_Firewall):
+ removedKeywords = F9_Firewall.removedKeywords
+ removedAttrs = F9_Firewall.removedAttrs
+
+ def __init__(self, writePriority=0, *args, **kwargs):
+ F9_Firewall.__init__(self, writePriority, *args, **kwargs)
+ self.services = kwargs.get("services", [])
+
+ def __str__(self):
+ if self.enabled is None:
+ return ""
+
+ retval = F9_Firewall.__str__(self)
+ if self.enabled:
+ retval = retval.strip()
+
+ svcstr = ",".join(self.services)
+ if svcstr:
+ svcstr = " --service=" + svcstr
+
+ return retval + "%s\n" % svcstr
+ else:
+ return retval
+
+ def _getParser(self):
+ op = F9_Firewall._getParser(self)
+ op.add_argument("--service", dest="services", action=ExtendAction,
+ type=commaSplit, help="""
+ This option provides a higher-level way to allow services
+ through the firewall. Some services (like cups, avahi, etc.)
+ require multiple ports to be open or other special
+ configuration in order for the service to work. You could
+ specify each individual service with the ``--port`` option,
+ or specify ``--service=`` and open them all at once.
+
+ Valid options are anything recognized by the
+ firewall-cmd program in the firewalld package.
+ If firewalld is running::
+
+ ``firewall-cmd --get-services``
+
+ will provide a list of known service names.""",
+ version=F10)
+ op.add_argument("--ftp", dest="services", action="append_const",
+ const="ftp", version=F10, help="Open the ftp service port")
+ op.add_argument("--http", dest="services", action="append_const",
+ const="http", version=F10, help="Open the http service port")
+ op.add_argument("--smtp", dest="services", action="append_const",
+ const="smtp", version=F10, help="Open the smtp service port")
+ op.add_argument("--ssh", dest="services", action="append_const",
+ const="ssh", version=F10, help="Open the ssh service port")
+ op.add_argument("--telnet", deprecated=F10)
+ return op
+
+class F14_Firewall(F10_Firewall):
+ removedKeywords = F10_Firewall.removedKeywords + ["telnet"]
+ removedAttrs = F10_Firewall.removedAttrs + ["telnet"]
+
+ def _getParser(self):
+ op = F10_Firewall._getParser(self)
+ op.remove_argument("--telnet", version=F14)
+ return op
+
+class F20_Firewall(F14_Firewall):
+ def __init__(self, writePriority=0, *args, **kwargs):
+ F14_Firewall.__init__(self, writePriority, *args, **kwargs)
+ self.remove_services = kwargs.get("remove_services", [])
+
+ def _getParser(self):
+ op = F14_Firewall._getParser(self)
+ op.add_argument("--remove-service", dest="remove_services",
+ help="Close ports for the comma-separated list of services",
+ action=ExtendAction, type=commaSplit, version=F20)
+ return op
+
+ def __str__(self):
+ if self.enabled is None:
+ return ""
+
+ retval = F14_Firewall.__str__(self)
+ if self.enabled:
+ retval = retval.strip()
+
+ svcstr = ",".join(self.remove_services)
+ if svcstr:
+ svcstr = " --remove-service=" + svcstr
+
+ return retval + "%s\n" % svcstr
+ else:
+ return retval
+
+class F28_Firewall(F20_Firewall):
+ def __init__(self, writePriority=0, *args, **kwargs):
+ F20_Firewall.__init__(self, writePriority, *args, **kwargs)
+ self.use_system_defaults = kwargs.get("use_system_defaults", None)
+
+ def _getParser(self):
+ op = F20_Firewall._getParser(self)
+ op.add_argument("--use-system-defaults", dest="use_system_defaults",
+ action="store_true", default=False, version=F28, help="""
+ Don't configure the firewall at all. This instructs anaconda
+ to do nothing and allows the system to rely on the defaults
+ that were provided with the package or ostree. If this option
+ is used with other options then all other options will be
+ ignored.""")
+ return op
+
+ def __str__(self):
+ if self.use_system_defaults:
+ return "# Firewall configuration\nfirewall --use-system-defaults\n"
+ else:
+ return F20_Firewall.__str__(self)
diff --git a/pool/shard009/Python/0083243_Bluetooth.py b/pool/shard009/Python/0083243_Bluetooth.py
new file mode 100644
index 0000000000000000000000000000000000000000..e9eca1dea63b676a14a297aca53a39fd85fdc4bd
--- /dev/null
+++ b/pool/shard009/Python/0083243_Bluetooth.py
@@ -0,0 +1,65 @@
+from cement.core import controller
+from colorama import init, Fore, Back, Style
+from config import Config
+
+import bluetooth
+# import pprint
+
+
+class Bluetooth(controller.CementBaseController):
+ nearby_devices = ''
+ device = ''
+ cfg = config('resrc/Msgs.cfg')
+
+ class Meta:
+ interface = controller.IController
+ label = 'Bluetooth'
+ description = 'Used to control bluetooth adapter for connections'
+ stacked_on = 'base'
+
+ @controller.expose(hide=False, help='Scans for bluetooth devices')
+ def scan(self):
+ print("Scanning for bluetooth devices ...")
+
+ # scans for nearby bluetooth devices
+ self.nearby_devices = bluetooth.discover_devices(lookup_names=True)
+
+ print("Found %d devices" % len(self.nearby_devices))
+
+ # lists each device for user to select to pair with
+ for index, item in enumerate(self.nearby_devices):
+ if index == 0:
+ print("ID\tHardware Addr\tName")
+
+ print("%d)\t%s\t%s" % (index + 1, item[0], item[1]))
+
+ print("\n * Please enter the device ID you wish to pair with")
+
+ # gets users selection (index + 1) of the device
+ hid = input(Style.BRIGHT + "\nEnter device ID: " + Style.RESET_ALL)
+ #subtracts 1 to be proper index num
+ hid = int(hid) - 1
+
+ # connects to device
+ self.connect(hid);
+
+ def connect(self, hid):
+ hwd = self.nearby_devices[hid]
+ port = 1
+
+ print("Connecting Device: %s ... " % hwd[1])
+
+ try:
+ dsock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
+ dsock.connect((hwd[0],port))
+ dsock.close()
+
+ print("Socket now closed")
+
+ except bluetooth.BluetoothError as be:
+ print(Fore.RED + Style.BRIGHT + 'Bluetooth Error: %s' % str(be))
+ except Exception as e:
+ print(Fore.RED + Style.BRIGHT + 'Error: %s' % str(e))
+
+
+
diff --git a/pool/shard009/Python/0083260_options.py b/pool/shard009/Python/0083260_options.py
new file mode 100644
index 0000000000000000000000000000000000000000..3bbfbe352a43e61819776050dfed5e2757b3fd2f
--- /dev/null
+++ b/pool/shard009/Python/0083260_options.py
@@ -0,0 +1,39 @@
+"""
+Parse query arguments.
+"""
+
+def parse_args(args):
+ """
+ Parse arguments and options.
+ Replace short options with their long counterparts.
+ """
+ result = {
+ 'add_comments': True,
+ }
+
+ query = ""
+ newargs = {}
+ for key, val in args.items():
+ if val == "" or val == [] or val == ['']:
+ query += key
+ continue
+ if val == 'True':
+ val = True
+ if val == 'False':
+ val = False
+ newargs[key] = val
+
+ options_meaning = {
+ "c": dict(add_comments=False, unindent_code=False),
+ "C": dict(add_comments=False, unindent_code=True),
+ "Q": dict(remove_text=True),
+ 'q': dict(quiet=True),
+ 'T': {'no-terminal': True},
+ }
+ for option, meaning in options_meaning.items():
+ if option in query:
+ result.update(meaning)
+
+ result.update(newargs)
+
+ return result
diff --git a/pool/shard009/Python/0083266_0001_squashed_0002_auto_20200123_1843.py b/pool/shard009/Python/0083266_0001_squashed_0002_auto_20200123_1843.py
new file mode 100644
index 0000000000000000000000000000000000000000..35f5dfb218254266f9ea8a62092aeb35f817d77b
--- /dev/null
+++ b/pool/shard009/Python/0083266_0001_squashed_0002_auto_20200123_1843.py
@@ -0,0 +1,82 @@
+# Generated by Django 1.11.28 on 2020-03-08 19:27
+from django.conf import settings
+from django.db import migrations, models
+import django.db.models.deletion
+
+
+class Migration(migrations.Migration):
+
+ initial = True
+
+ dependencies = [
+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),
+ ("base", "0002_auto_20200322_1821"),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name="ActionLog",
+ fields=[
+ (
+ "id",
+ models.AutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
+ ),
+ (
+ "action_type",
+ models.CharField(
+ choices=[
+ ("translation:created", "Translation created"),
+ ("translation:deleted", "Translation deleted"),
+ ("translation:approved", "Translation approved"),
+ ("translation:unapproved", "Translation unapproved"),
+ ("translation:rejected", "Translation rejected"),
+ ("translation:unrejected", "Translation unrejected"),
+ ("comment:added", "Comment added"),
+ ],
+ max_length=50,
+ ),
+ ),
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ (
+ "entity",
+ models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ to="base.Entity",
+ ),
+ ),
+ (
+ "locale",
+ models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ to="base.Locale",
+ ),
+ ),
+ (
+ "performed_by",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="actions",
+ to=settings.AUTH_USER_MODEL,
+ ),
+ ),
+ (
+ "translation",
+ models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ to="base.Translation",
+ ),
+ ),
+ ],
+ ),
+ ]
diff --git a/pool/shard009/Python/0083269_wsgi_soap_application_test.py b/pool/shard009/Python/0083269_wsgi_soap_application_test.py
new file mode 100644
index 0000000000000000000000000000000000000000..7cb6c65a39285cfa3e00a434c6556671d49f929b
--- /dev/null
+++ b/pool/shard009/Python/0083269_wsgi_soap_application_test.py
@@ -0,0 +1,60 @@
+# -*- coding: utf-8 -*-
+
+from __future__ import absolute_import, unicode_literals
+
+from io import BytesIO
+
+from pythonic_testcase import *
+
+from soapfish.soap_dispatch import SOAPDispatcher, WsgiSoapApplication
+from soapfish.testutil import echo_service
+
+
+class WsgiSoapApplicationTest(PythonicTestCase):
+ def test_can_dispatch_soap_request_with_plain_wsgi(self):
+ dispatcher = SOAPDispatcher(echo_service())
+ app = WsgiSoapApplication(dispatcher)
+ start_response = self._response_mock()
+ soap_message = (b''
+ b''
+ b''
+ b''
+ b'foobar '
+ b' '
+ b' '
+ b' ')
+ response = app(self._wsgi_env(soap_message), start_response)
+ assert_equals(WsgiSoapApplication.HTTP_200, start_response.code)
+ assert_equals('text/xml', dict(start_response.headers)['Content-Type'])
+ expected_xml = (
+ b'\n'
+ b' \n'
+ b' \n'
+ b' foobar \n'
+ b' \n'
+ b' \n'
+ b' \n'
+ )
+ assert_equals(expected_xml, b''.join(response))
+
+ def _response_mock(self):
+ class StartResponse():
+ self.code = None
+ self.headers = None
+ def __call__(self, code, headers):
+ self.code = code
+ self.headers = headers
+ return StartResponse()
+
+ def _wsgi_env(self, soap_xml):
+ return {
+ 'SOAPACTION': 'echo',
+ 'PATH_INFO': '/service',
+ 'CONTENT_LENGTH': len(soap_xml),
+ 'QUERY_STRING': '',
+ 'SERVER_NAME': 'localhost',
+ 'SERVER_PORT': '7000',
+ 'REQUEST_METHOD': 'POST',
+ 'wsgi.url_scheme': 'http',
+ 'wsgi.input': BytesIO(soap_xml),
+ }
diff --git a/pool/shard009/Python/0083277_setup.py b/pool/shard009/Python/0083277_setup.py
new file mode 100644
index 0000000000000000000000000000000000000000..f92dd14ac6fd3c7dcc009241a37aa72bbc833abe
--- /dev/null
+++ b/pool/shard009/Python/0083277_setup.py
@@ -0,0 +1,121 @@
+#!/usr/bin/env python
+
+# Copyright 2013-present Barefoot Networks, Inc.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in 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.
+#
+
+#
+# Antonin Bas (antonin@barefootnetworks.com)
+#
+#
+
+# -*- coding: utf-8 -*-
+
+import p4c_bm
+import os
+import sys
+
+SETUP_PY_PATH = os.path.dirname(__file__)
+SRC_PATH = os.path.relpath(os.path.join(os.path.dirname(__file__), "p4c_bm"))
+
+from setuptools import setup
+from setuptools.command.install import install
+from setuptools.command.install_scripts import install_scripts
+
+with open(os.path.join(SETUP_PY_PATH, 'README.rst')) as readme_file:
+ readme = readme_file.read()
+
+with open(os.path.join(SETUP_PY_PATH, 'HISTORY.rst')) as history_file:
+ history = history_file.read().replace('.. :changelog:', '')
+
+with open(os.path.join(SRC_PATH, "_version_str.py"), 'w') as version_f:
+ version_f.write("# This file is auto-generated\n")
+ version_f.write("version_str = '{}'\n".format(p4c_bm.__version__))
+
+requirements = [
+ # TODO: put package requirements here
+ 'p4-hlir',
+ 'Tenjin'
+]
+
+install_lib = None
+
+class CustomInstall(install):
+ def run(self):
+ # in this step we simply retrieve the installation path that we need to
+ # append to the PYTHONPATH dynamically
+ global install_lib
+ assert(install_lib is None)
+ install_lib = os.path.abspath(self.install_lib)
+ # if a root was specified we remove it from the install path
+ if self.root is not None:
+ assert(install_lib.startswith(self.root))
+ install_lib = install_lib[len(self.root):]
+ install.run(self)
+
+class CustomInstallScripts(install_scripts):
+ def run(self):
+ # in this second step we edit the script in the build directory to
+ # replace @pythondir@ with the value of install_lib and we rename the
+ # script; the modified script will be copied to the installation
+ # directory by setuptools
+ assert(install_lib is not None)
+ in_path = os.path.join(self.build_dir, 'p4c-bmv2.in')
+ out_path = os.path.join(self.build_dir, 'p4c-bmv2')
+ with open(in_path, "r") as fin:
+ with open(out_path, "w") as fout:
+ for line in fin:
+ # we use the platform-dependent install path computed by
+ # setuptools
+ fout.write(line.replace('@pythondir@', install_lib))
+ os.remove(os.path.join(self.build_dir, 'p4c-bmv2.in'))
+ install_scripts.run(self)
+
+setup(
+ name='p4c_bm',
+ version=p4c_bm.__version__,
+ description="Generates the JSON configuration for the behavioral-model",
+ long_description=readme + '\n\n' + history,
+ author="Antonin Bas",
+ author_email='antonin@barefootnetworks.com',
+ url='https://github.com/antoninbas/p4c_bm',
+ packages=[
+ 'p4c_bm', 'p4c_bm.util',
+ ],
+ package_dir={'p4c_bm': SRC_PATH},
+ include_package_data=True,
+ install_requires=requirements,
+ # entry_points={
+ # 'console_scripts': [
+ # 'p4c-bmv2=p4c_bm.__main__:main',
+ # ],
+ # },
+ # we use the "template" here, because it is better if this script exists
+ # (otherwise I need to provide a custom command for the build step as well
+ scripts=['p4c-bmv2.in'],
+ license="Apache",
+ zip_safe=False,
+ keywords='p4c_bm',
+ classifiers=[
+ 'Development Status :: 2 - Pre-Alpha',
+ 'Intended Audience :: Developers',
+ 'License :: OSI Approved :: Apache License',
+ 'Natural Language :: English',
+ "Programming Language :: Python :: 2",
+ 'Programming Language :: Python :: 2.7',
+ ],
+ test_suite='tests',
+ cmdclass={'install': CustomInstall,
+ 'install_scripts': CustomInstallScripts},
+)
diff --git a/pool/shard009/Python/0083278_res_partner.py b/pool/shard009/Python/0083278_res_partner.py
new file mode 100644
index 0000000000000000000000000000000000000000..94e8471e00b602fae3cf2f5a7990d26b1588475b
--- /dev/null
+++ b/pool/shard009/Python/0083278_res_partner.py
@@ -0,0 +1,173 @@
+# -*- coding: utf-8 -*-
+# Part of Odoo. See LICENSE file for full copyright and licensing details.
+
+import random
+import werkzeug.urls
+
+from collections import defaultdict
+from datetime import datetime, timedelta
+
+from odoo import api, exceptions, fields, models, _
+
+class SignupError(Exception):
+ pass
+
+def random_token():
+ # the token has an entropy of about 120 bits (6 bits/char * 20 chars)
+ chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
+ return ''.join(random.SystemRandom().choice(chars) for _ in range(20))
+
+def now(**kwargs):
+ return datetime.now() + timedelta(**kwargs)
+
+
+class ResPartner(models.Model):
+ _inherit = 'res.partner'
+
+ signup_token = fields.Char(copy=False, groups="base.group_erp_manager")
+ signup_type = fields.Char(string='Signup Token Type', copy=False, groups="base.group_erp_manager")
+ signup_expiration = fields.Datetime(copy=False, groups="base.group_erp_manager")
+ signup_valid = fields.Boolean(compute='_compute_signup_valid', string='Signup Token is Valid')
+ signup_url = fields.Char(compute='_compute_signup_url', string='Signup URL')
+
+ @api.depends('signup_token', 'signup_expiration')
+ def _compute_signup_valid(self):
+ dt = now()
+ for partner, partner_sudo in zip(self, self.sudo()):
+ partner.signup_valid = bool(partner_sudo.signup_token) and \
+ (not partner_sudo.signup_expiration or dt <= partner_sudo.signup_expiration)
+
+ def _compute_signup_url(self):
+ """ proxy for function field towards actual implementation """
+ result = self.sudo()._get_signup_url_for_action()
+ for partner in self:
+ if any(u.has_group('base.group_user') for u in partner.user_ids if u != self.env.user):
+ self.env['res.users'].check_access_rights('write')
+ partner.signup_url = result.get(partner.id, False)
+
+ def _get_signup_url_for_action(self, url=None, action=None, view_type=None, menu_id=None, res_id=None, model=None):
+ """ generate a signup url for the given partner ids and action, possibly overriding
+ the url state components (menu_id, id, view_type) """
+
+ res = dict.fromkeys(self.ids, False)
+ for partner in self:
+ base_url = partner.get_base_url()
+ # when required, make sure the partner has a valid signup token
+ if self.env.context.get('signup_valid') and not partner.user_ids:
+ partner.sudo().signup_prepare()
+
+ route = 'login'
+ # the parameters to encode for the query
+ query = dict(db=self.env.cr.dbname)
+ signup_type = self.env.context.get('signup_force_type_in_url', partner.sudo().signup_type or '')
+ if signup_type:
+ route = 'reset_password' if signup_type == 'reset' else signup_type
+
+ if partner.sudo().signup_token and signup_type:
+ query['token'] = partner.sudo().signup_token
+ elif partner.user_ids:
+ query['login'] = partner.user_ids[0].login
+ else:
+ continue # no signup token, no user, thus no signup url!
+
+ if url:
+ query['redirect'] = url
+ else:
+ fragment = dict()
+ base = '/web#'
+ if action == '/mail/view':
+ base = '/mail/view?'
+ elif action:
+ fragment['action'] = action
+ if view_type:
+ fragment['view_type'] = view_type
+ if menu_id:
+ fragment['menu_id'] = menu_id
+ if model:
+ fragment['model'] = model
+ if res_id:
+ fragment['res_id'] = res_id
+
+ if fragment:
+ query['redirect'] = base + werkzeug.urls.url_encode(fragment)
+
+ url = "/web/%s?%s" % (route, werkzeug.urls.url_encode(query))
+ if not self.env.context.get('relative_url'):
+ url = werkzeug.urls.url_join(base_url, url)
+ res[partner.id] = url
+
+ return res
+
+ def action_signup_prepare(self):
+ return self.signup_prepare()
+
+ def signup_get_auth_param(self):
+ """ Get a signup token related to the partner if signup is enabled.
+ If the partner already has a user, get the login parameter.
+ """
+ res = defaultdict(dict)
+
+ allow_signup = self.env['res.users']._get_signup_invitation_scope() == 'b2c'
+ for partner in self:
+ partner = partner.sudo()
+ if allow_signup and not partner.user_ids:
+ partner.signup_prepare()
+ res[partner.id]['auth_signup_token'] = partner.signup_token
+ elif partner.user_ids:
+ res[partner.id]['auth_login'] = partner.user_ids[0].login
+ return res
+
+ def signup_cancel(self):
+ return self.write({'signup_token': False, 'signup_type': False, 'signup_expiration': False})
+
+ def signup_prepare(self, signup_type="signup", expiration=False):
+ """ generate a new token for the partners with the given validity, if necessary
+ :param expiration: the expiration datetime of the token (string, optional)
+ """
+ for partner in self:
+ if expiration or not partner.signup_valid:
+ token = random_token()
+ while self._signup_retrieve_partner(token):
+ token = random_token()
+ partner.write({'signup_token': token, 'signup_type': signup_type, 'signup_expiration': expiration})
+ return True
+
+ @api.model
+ def _signup_retrieve_partner(self, token, check_validity=False, raise_exception=False):
+ """ find the partner corresponding to a token, and possibly check its validity
+ :param token: the token to resolve
+ :param check_validity: if True, also check validity
+ :param raise_exception: if True, raise exception instead of returning False
+ :return: partner (browse record) or False (if raise_exception is False)
+ """
+ partner = self.search([('signup_token', '=', token)], limit=1)
+ if not partner:
+ if raise_exception:
+ raise exceptions.UserError(_("Signup token '%s' is not valid") % token)
+ return False
+ if check_validity and not partner.signup_valid:
+ if raise_exception:
+ raise exceptions.UserError(_("Signup token '%s' is no longer valid") % token)
+ return False
+ return partner
+
+ @api.model
+ def signup_retrieve_info(self, token):
+ """ retrieve the user info about the token
+ :return: a dictionary with the user information:
+ - 'db': the name of the database
+ - 'token': the token, if token is valid
+ - 'name': the name of the partner, if token is valid
+ - 'login': the user login, if the user already exists
+ - 'email': the partner email, if the user does not exist
+ """
+ partner = self._signup_retrieve_partner(token, raise_exception=True)
+ res = {'db': self.env.cr.dbname}
+ if partner.signup_valid:
+ res['token'] = token
+ res['name'] = partner.name
+ if partner.user_ids:
+ res['login'] = partner.user_ids[0].login
+ else:
+ res['email'] = res['login'] = partner.email or ''
+ return res
diff --git a/pool/shard009/Python/0083280_processor.py b/pool/shard009/Python/0083280_processor.py
new file mode 100644
index 0000000000000000000000000000000000000000..9525cdcf85e290399d6151a022188fb7390668c1
--- /dev/null
+++ b/pool/shard009/Python/0083280_processor.py
@@ -0,0 +1,169 @@
+#!/usr/bin/env python
+# -*- encoding: utf-8 -*-
+# vim: set et sw=4 ts=4 sts=4 ff=unix fenc=utf8:
+# Author: Binux
+# http://binux.me
+# Created on 2014-02-16 22:59:56
+
+import sys
+import time
+import Queue
+import logging
+import project_module
+from libs.response import rebuild_response
+logger = logging.getLogger("processor")
+
+def build_module(project, env={}):
+ assert 'name' in project, 'need name of project'
+ assert 'script' in project, 'need script of project'
+
+ env = dict(env)
+ env.update({
+ 'project': project,
+ 'debug': project.get('status', 'DEBUG') == 'DEBUG',
+ })
+
+ script = project['script']
+ if isinstance(script, unicode):
+ script = script.encode('utf8')
+
+ module = project_module.ProjectModule(project['name'], script, env)
+ module.rethrow()
+ _class = module.get('__class__')
+ assert _class is not None, "need BaseHandler in project module"
+ instance = _class()._init(project)
+
+ return {
+ 'module': module,
+ 'class': _class,
+ 'instance': instance,
+ 'info': project
+ }
+
+class Processor(object):
+ CHECK_PROJECTS_INTERVAL = 5*60
+
+ def __init__(self, projectdb, inqueue, status_queue, newtask_queue):
+ self.inqueue = inqueue
+ self.status_queue = status_queue
+ self.newtask_queue = newtask_queue
+ self.projectdb = projectdb
+
+ self._quit = False
+ self.projects = {}
+ self.last_check_projects = 0
+
+ def _init_projects(self):
+ for project in self.projectdb.get_all():
+ try:
+ self._update_project(project)
+ except Exception, e:
+ logger.exception("exception when init projects for %s" % project.get('name', None))
+ continue
+ self.last_check_projects = time.time()
+
+ def _need_update(self, task):
+ if task['project'] not in self.projects:
+ return True
+ if task.get('project_updatetime', 0) > self.projects[task['project']]['info'].get('updatetime', 0):
+ return True
+ if time.time() - self.last_check_projects < self.CHECK_PROJECTS_INTERVAL:
+ return True
+ return False
+
+ def _check_projects(self, task):
+ if not self._need_update(task):
+ return
+ for project in self.projectdb.check_update(self.last_check_projects):
+ try:
+ logger.debug("project: %s updated." % project['name'])
+ self._update_project(project)
+ except Exception, e:
+ logger.exception("exception when check update for %s" % project.get('name', None))
+ continue
+ self.last_check_projects = time.time()
+
+ def _update_project(self, project):
+ self.projects[project['name']] = build_module(project)
+
+ def on_task(self, task, response):
+ start_time = time.time()
+ try:
+ response = rebuild_response(response)
+ assert 'taskid' in task, 'need taskid in task'
+ project = task['project']
+ if project not in self.projects:
+ raise LookupError("not such project: %s" % project)
+ project_data = self.projects[project]
+ ret = project_data['instance'].run(project_data['module'], task, response)
+ except Exception, e:
+ logger.exception(e)
+ return False
+ process_time = time.time() - start_time
+
+ if not ret.extinfo.get('not_send_status', False):
+ status_pack = {
+ 'taskid': task['taskid'],
+ 'project': task['project'],
+ 'url': task.get('url'),
+ 'track': {
+ 'fetch': {
+ 'ok': not response.error,
+ 'time': response.time,
+ 'status_code': response.status_code,
+ 'headers': dict(response.headers),
+ 'encoding': response.encoding,
+ #'content': response.content,
+ },
+ 'process': {
+ 'ok': not ret.exception,
+ 'time': process_time,
+ 'follows': len(ret.follows),
+ 'result': unicode(ret.result)[:100],
+ 'logs': ret.logstr()[:200],
+ 'exception': unicode(ret.exception),
+ }
+ }
+ }
+ self.status_queue.put(status_pack)
+
+ for task in ret.follows:
+ self.newtask_queue.put(task)
+
+ for project, msg in ret.messages:
+ self.inqueue.put(({
+ 'taskid': 'data:,on_message',
+ 'project': project,
+ 'url': 'data:,on_message',
+ 'process': {
+ 'callback': '_on_message',
+ }
+ }, {
+ 'status_code': 200,
+ 'url': 'data:,on_message',
+ 'save': (task['project'], msg),
+ }))
+
+ if response.error or ret.exception:
+ logger_func = logger.error
+ else:
+ logger_func = logger.info
+ logger_func('process %s:%s %s -> [%d] len:%d -> fol:%d msg:%d err:%r' % (task['project'], task['taskid'],
+ task.get('url'), response.status_code, len(response.content),
+ len(ret.follows), len(ret.messages), ret.exception))
+ return True
+
+ def run(self):
+ while not self._quit:
+ try:
+ task, response = self.inqueue.get()
+ self._check_projects(task)
+ self.on_task(task, response)
+ except Queue.Empty, e:
+ time.sleep(1)
+ continue
+ except KeyboardInterrupt:
+ break
+ except Exception, e:
+ logger.exception(e)
+ continue
diff --git a/pool/shard009/Python/0083285_init__.py b/pool/shard009/Python/0083285_init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..65bded05e839f5262a22c9a2c5c46d5f4d1c1840
--- /dev/null
+++ b/pool/shard009/Python/0083285_init__.py
@@ -0,0 +1,67 @@
+# -*- coding: utf-8 -*-
+__version__ = '0.1'
+
+from flask import Flask
+
+from lib.AfricasTalkingGateway import (
+ AfricasTalkingGateway, AfricasTalkingGatewayException)
+from datetime import timedelta
+
+import logging
+import settings
+import redis
+
+app = Flask('app')
+app.config.from_pyfile('settings.py', silent=True)
+
+
+red = redis.StrictRedis(host='localhost', port=6379, db=0)
+app.config['ONLINE_LAST_MINUTES'] = settings.ONLINE_LAST_MINUTES
+app.secret_key = settings.SECRET_KEY
+
+app.permanent_session_lifetime = timedelta(minutes=5760)
+logging.basicConfig(filename='octopus.log', level=logging.DEBUG)
+
+"""
+def db_setup():
+ connection = r.connect(host=settings.RDB_HOST, port=settings.RDB_PORT,
+ auth_key=settings.rethinkdb_auth)
+ try:
+ r.db_create(settings.TARGET_DB).run(connection)
+ r.db(settings.TARGET_DB).table_create('User').run(connection)
+ logging.info('Database setup completed')
+ except RqlError:
+ logging.info('App database already exists')
+ except RqlRuntimeError:
+ logging.info('App database already exists')
+ finally:
+ connection.close()
+
+
+@app.before_request
+def before_request():
+ try:
+ logging.info('before_request')
+ g.rdb_conn = r.connect(host=settings.RDB_HOST, port=settings.RDB_PORT,
+ db=settings.TARGET_DB, auth_key=settings.rethinkdb_auth)
+
+ except RqlDriverError:
+ logging.info('DB Connect Failed')
+ abort(503, "No database connection could be established")
+
+
+@app.teardown_request
+def teardown_request(exception):
+ try:
+ logging.info('teardown_request')
+ g.rdb_conn.close()
+ except AttributeError:
+ logging.info('Database failure - check your connection', exception)
+
+"""
+
+from api import routes
+from api import voice
+from api import ussd
+from api import short_code
+from api import airtime
\ No newline at end of file
diff --git a/pool/shard009/Python/0083290_work-around-vs-dependency-tracking-bugs.py b/pool/shard009/Python/0083290_work-around-vs-dependency-tracking-bugs.py
new file mode 100644
index 0000000000000000000000000000000000000000..51d650f7fbc5ac4914ebe3d299e74e798878731c
--- /dev/null
+++ b/pool/shard009/Python/0083290_work-around-vs-dependency-tracking-bugs.py
@@ -0,0 +1,66 @@
+#!/usr/bin/env python
+
+import glob
+import os
+import re
+import sys
+
+
+# It's fragile to rely on the location of this script to find the top-level
+# source directory.
+TOP_LEVEL_DIRECTORY = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
+WEBKIT_LIBRARIES = os.environ['WEBKIT_LIBRARIES'];
+
+def main():
+ react_to_vsprops_changes()
+ react_to_webkit1_interface_changes()
+
+
+def react_to_vsprops_changes():
+ vsprops_directory = os.path.join(WEBKIT_LIBRARIES, 'tools', 'vsprops')
+ newest_vsprops_time = mtime_of_newest_file_matching_glob(os.path.join(vsprops_directory, '*.props'))
+
+ obj_directory = os.path.join(os.environ['CONFIGURATIONBUILDDIR'], 'obj32')
+
+ # Visual Studio isn't smart enough to figure out it needs to rebuild these file types when
+ # .vsprops files change (even if we touch wtf/Platform.h below), so we delete them to force them
+ # to be rebuilt.
+ for extension in ('dep', 'manifest', 'pch', 'res'):
+ for filepath in glob.iglob(os.path.join(obj_directory, '*', '*.%s' % extension)):
+ delete_if_older_than(filepath, newest_vsprops_time)
+
+ # Touch wtf/Platform.h so all files will be recompiled. This is necessary
+ # to pick up changes to preprocessor macros (e.g., ENABLE_*).
+ wtf_platform_h = os.path.join(TOP_LEVEL_DIRECTORY, 'Source', 'WTF', 'wtf', 'Platform.h')
+ touch_if_older_than(wtf_platform_h, newest_vsprops_time)
+
+
+def react_to_webkit1_interface_changes():
+ interfaces_directory = os.path.join(TOP_LEVEL_DIRECTORY, 'Source', 'WebKit', 'win', 'Interfaces')
+ newest_idl_time = mtime_of_newest_file_matching_glob(os.path.join(interfaces_directory, '*.idl'))
+ # WebKit.idl includes all the other IDL files, so needs to be rebuilt if any IDL file changes.
+ # But Visual Studio isn't smart enough to figure this out, so we touch WebKit.idl to ensure that
+ # it gets rebuilt.
+ touch_if_older_than(os.path.join(interfaces_directory, 'WebKit.idl'), newest_idl_time)
+
+
+def mtime_of_newest_file_matching_glob(glob_pattern):
+ files = glob.glob(glob_pattern)
+ assert len(files), "Couldn't find any files matching glob %s" % glob_pattern
+ return max(map(os.path.getmtime, files))
+
+
+def delete_if_older_than(path, reference_time):
+ if os.path.getmtime(path) < reference_time:
+ print 'Deleting %s' % path
+ os.remove(path)
+
+
+def touch_if_older_than(path, reference_time):
+ if os.path.getmtime(path) < reference_time:
+ print 'Touching %s' % path
+ os.utime(path, None)
+
+
+if __name__ == '__main__':
+ sys.exit(main())
diff --git a/pool/shard009/Python/0083291_models.py b/pool/shard009/Python/0083291_models.py
new file mode 100644
index 0000000000000000000000000000000000000000..c99040cf39eb0e5319e80bc745040424402e53de
--- /dev/null
+++ b/pool/shard009/Python/0083291_models.py
@@ -0,0 +1,99 @@
+from moto.core import BaseBackend
+
+
+class FakeHealthCheck(object):
+ def __init__(self, timeout, healthy_threshold, unhealthy_threshold,
+ interval, target):
+ self.timeout = timeout
+ self.healthy_threshold = healthy_threshold
+ self.unhealthy_threshold = unhealthy_threshold
+ self.interval = interval
+ self.target = target
+
+
+class FakeListener(object):
+ def __init__(self, load_balancer_port, instance_port, protocol):
+ self.load_balancer_port = load_balancer_port
+ self.instance_port = instance_port
+ self.protocol = protocol.upper()
+
+
+class FakeLoadBalancer(object):
+ def __init__(self, name, zones, ports):
+ self.name = name
+ self.health_check = None
+ self.instance_ids = []
+ self.zones = zones
+ self.listeners = []
+ for protocol, lb_port, instance_port in ports:
+ listener = FakeListener(
+ protocol=protocol,
+ load_balancer_port=lb_port,
+ instance_port=instance_port,
+ )
+ self.listeners.append(listener)
+
+ @classmethod
+ def create_from_cloudformation_json(cls, resource_name, cloudformation_json):
+ properties = cloudformation_json['Properties']
+
+ new_elb = elb_backend.create_load_balancer(
+ name=properties.get('LoadBalancerName', resource_name),
+ zones=properties.get('AvailabilityZones'),
+ ports=[],
+ )
+
+ instance_ids = cloudformation_json.get('Instances', [])
+ for instance_id in instance_ids:
+ elb_backend.register_instances(new_elb.name, [instance_id])
+ return new_elb
+
+ @property
+ def physical_resource_id(self):
+ return self.name
+
+
+class ELBBackend(BaseBackend):
+
+ def __init__(self):
+ self.load_balancers = {}
+
+ def create_load_balancer(self, name, zones, ports):
+ new_load_balancer = FakeLoadBalancer(name=name, zones=zones, ports=ports)
+ self.load_balancers[name] = new_load_balancer
+ return new_load_balancer
+
+ def describe_load_balancers(self, names):
+ balancers = self.load_balancers.values()
+ if names:
+ return [balancer for balancer in balancers if balancer.name in names]
+ else:
+ return balancers
+
+ def delete_load_balancer(self, load_balancer_name):
+ self.load_balancers.pop(load_balancer_name, None)
+
+ def get_load_balancer(self, load_balancer_name):
+ return self.load_balancers.get(load_balancer_name)
+
+ def configure_health_check(self, load_balancer_name, timeout,
+ healthy_threshold, unhealthy_threshold, interval,
+ target):
+ check = FakeHealthCheck(timeout, healthy_threshold, unhealthy_threshold,
+ interval, target)
+ load_balancer = self.get_load_balancer(load_balancer_name)
+ load_balancer.health_check = check
+ return check
+
+ def register_instances(self, load_balancer_name, instance_ids):
+ load_balancer = self.get_load_balancer(load_balancer_name)
+ load_balancer.instance_ids.extend(instance_ids)
+ return load_balancer
+
+ def deregister_instances(self, load_balancer_name, instance_ids):
+ load_balancer = self.get_load_balancer(load_balancer_name)
+ new_instance_ids = [instance_id for instance_id in load_balancer.instance_ids if instance_id not in instance_ids]
+ load_balancer.instance_ids = new_instance_ids
+ return load_balancer
+
+elb_backend = ELBBackend()
diff --git a/pool/shard009/Python/0083294_xx.py b/pool/shard009/Python/0083294_xx.py
new file mode 100644
index 0000000000000000000000000000000000000000..a067c319ee6a8cd4617626bf9bde28de1836af5f
--- /dev/null
+++ b/pool/shard009/Python/0083294_xx.py
@@ -0,0 +1,59 @@
+#!/usr/bin/python
+
+import os
+import sys
+
+csound = "../../csound"
+flags = "-d -W -m0"
+
+testFiles = [
+ cpumeter
+]
+
+
+
+if len(sys.argv) == 2:
+ csound = sys.argv[1]
+else:
+ print "Testing git version"
+
+
+print "Using Csound Command: " + csound
+
+try:
+ os.remove("Old_OutputX")
+except OSError:
+ pass
+
+try:
+ os.remove("CheckSumsX")
+ os.remove("OutputX")
+except OSError:
+ pass
+
+try:
+ os.rename("Output1", "Old_Output")
+except OSError:
+ pass
+
+for filename in testFiles:
+
+ replaceText = (csound, flags, filename, filename)
+ csCommand = "%s %s %s.csd -o ./%s.wav >> OutputX 2>&1"%replaceText
+
+ md5sumCommand = "md5sum -b %s.wav >> CheckSumsX"%filename
+
+ print csCommand
+ os.system(csCommand)
+ os.system(md5sumCommand)
+
+ try:
+ os.remove(filename + ".wav")
+ except OSError:
+ print "Error: %s.wav was not generated"%filename
+
+print "********Comparing checksums"
+os.system("diff CheckSumsX SAFESumsX")
+print "********Comparing output"
+os.system("sed -e /Elapsed/d < OutputX > OutputX1")
+os.system("diff OutputX1 Old_OutputX | grep -v Elapsed")
diff --git a/pool/shard009/Python/0083296_test_lookups_aws.py b/pool/shard009/Python/0083296_test_lookups_aws.py
new file mode 100644
index 0000000000000000000000000000000000000000..4d330b9c991d55cba4494a9b6b18a0f4b850dd34
--- /dev/null
+++ b/pool/shard009/Python/0083296_test_lookups_aws.py
@@ -0,0 +1,81 @@
+# -*- coding: utf-8 -*-
+from __future__ import unicode_literals, print_function
+
+import pytest
+
+from gcdt_testtools.helpers_aws import check_preconditions, check_normal_mode
+from gcdt_testtools.helpers_aws import awsclient # fixtures!
+from gcdt_lookups.lookups import _acm_lookup, _resolve_lookups
+
+
+@pytest.mark.aws
+@check_preconditions
+def test_acm_lookup(awsclient):
+ # we decided to use placebo recording for this testcase since the certificate
+ # information is public anyway
+ # * if we deploy new certificates this might break
+ # * we do not want to have all the certificate details in github
+ host_list = ['*.infra.glomex.cloud', '*.dev.infra.glomex.cloud']
+ cert_arn = _acm_lookup(awsclient, host_list)
+ assert cert_arn is not None
+ assert cert_arn.split(':')[3] == 'eu-west-1'
+
+
+@pytest.mark.aws
+@check_preconditions
+def test_acm_lookup_is_yugen(awsclient):
+ # for API Gateway certs need to come from us-east-1
+ host_list = ['*.infra.glomex.cloud', '*.dev.infra.glomex.cloud']
+ cert_arn = _acm_lookup(awsclient, host_list, 'us-east-1')
+ assert cert_arn is not None
+ assert cert_arn.split(':')[3] == 'us-east-1'
+
+
+@pytest.mark.aws
+@check_preconditions
+def test_stack_lookup_stack_output(awsclient):
+ # lookup:stack: w/o value gets us the whole stack_output
+ context = {
+ '_awsclient': awsclient,
+ 'tool': 'ramuda'
+ }
+
+ config = {
+ 'stack_output': 'lookup:stack:infra-dev'
+ }
+ _resolve_lookups(context, config, ['stack'])
+
+ assert config.get('stack_output', {}).get('AWSAccountId') == '420189626185'
+
+
+@pytest.mark.aws
+@check_preconditions
+def test_stack_lookup_value(awsclient):
+ # lookup:stack: w/o value gets us the whole stack_output
+ context = {
+ '_awsclient': awsclient,
+ 'tool': 'ramuda'
+ }
+
+ config = {
+ 'AWSAccountId': 'lookup:stack:infra-dev:AWSAccountId'
+ }
+ _resolve_lookups(context, config, ['stack'])
+
+ assert config.get('AWSAccountId') == '420189626185'
+
+
+@pytest.mark.aws
+@check_preconditions
+@check_normal_mode
+def test_secret_lookup(awsclient):
+ context = {
+ '_awsclient': awsclient,
+ 'tool': 'kumo'
+ }
+ config = {
+ 'BaseAMIID': 'lookup:secret:ops.dev.base_ami'
+ }
+ _resolve_lookups(context, config, ['secret'])
+
+ assert config.get('BaseAMIID') == 'ami-1370b36a'
diff --git a/pool/shard009/Python/0083297_urlview.py b/pool/shard009/Python/0083297_urlview.py
new file mode 100644
index 0000000000000000000000000000000000000000..bdcf419355dee5a5766ccef1cc6a48ce4356f98b
--- /dev/null
+++ b/pool/shard009/Python/0083297_urlview.py
@@ -0,0 +1,47 @@
+#!/bin/python
+import os, subprocess
+import logging
+
+from autotest.client import test
+from autotest.client.shared import error
+
+class urlview(test.test):
+
+ """
+ Autotest module for testing basic functionality
+ of urlview
+
+ @author Kingsuk Deb ##
+ """
+ version = 1
+ nfail = 0
+ path = ''
+
+ def initialize(self):
+ """
+ Sets the overall failure counter for the test.
+ """
+ self.nfail = 0
+ logging.info('\n Test initialize successfully')
+
+ def run_once(self, test_path=''):
+ """
+ Trigger test run
+ """
+ try:
+ os.environ["LTPBIN"] = "%s/shared" %(test_path)
+ ret_val = subprocess.call(test_path + '/urlview' + '/urlview.sh', shell=True)
+ if ret_val != 0:
+ self.nfail += 1
+
+ except error.CmdError, e:
+ self.nfail += 1
+ logging.error("Test Failed: %s", e)
+
+ def postprocess(self):
+ if self.nfail != 0:
+ logging.info('\n nfails is non-zero')
+ raise error.TestError('\nTest failed')
+ else:
+ logging.info('\n Test completed successfully ')
+
diff --git a/pool/shard009/Python/0083298_f_expression.py b/pool/shard009/Python/0083298_f_expression.py
new file mode 100644
index 0000000000000000000000000000000000000000..1eab82fb68f96f7764d771fb0938f9e163b76a9c
--- /dev/null
+++ b/pool/shard009/Python/0083298_f_expression.py
@@ -0,0 +1,110 @@
+import string
+import conditions
+
+def parse_expression(exp):
+ if isinstance(exp, list):
+ functionsymbol = exp[0]
+ return PrimitiveNumericExpression(functionsymbol,
+ [conditions.parse_term(arg) for arg in exp[1:]])
+ elif exp.replace(".","").isdigit():
+ return NumericConstant(string.atof(exp))
+ else:
+ return PrimitiveNumericExpression(exp,[])
+
+def parse_assignment(alist):
+ assert len(alist) == 3
+ op = alist[0]
+ head = parse_expression(alist[1])
+ exp = parse_expression(alist[2])
+ if op == "=":
+ return Assign(head, exp)
+ elif op == "increase":
+ return Increase(head, exp)
+ else:
+ assert False, "Assignment operator not supported."
+
+class FunctionalExpression(object):
+ def __init__(self, parts):
+ self.parts = tuple(parts)
+ def dump(self, indent=" "):
+ print "%s%s" % (indent, self._dump())
+ for part in self.parts:
+ part.dump(indent + " ")
+ def _dump(self):
+ return self.__class__.__name__
+ def instantiate(self, var_mapping, init_facts):
+ raise ValueError("Cannot instantiate condition: not normalized")
+
+class NumericConstant(FunctionalExpression):
+ parts = ()
+ def __init__(self, value):
+ self.value = value
+ def __eq__(self, other):
+ return (self.__class__ == other.__class__ and self.value == other.value)
+ def __str__(self):
+ return "%s %s" % (self.__class__.__name__, self.value)
+ def _dump(self):
+ return str(self)
+ def instantiate(self, var_mapping, init_facts):
+ return self
+
+class PrimitiveNumericExpression(FunctionalExpression):
+ parts = ()
+ def __init__(self, symbol, args):
+ self.symbol = symbol
+ self.args = tuple(args)
+ def __eq__(self, other):
+ return (self.__class__ == other.__class__ and self.symbol == other.symbol
+ and self.args == other.args)
+ def __str__(self):
+ return "%s %s(%s)" % ("PNE", self.symbol, ", ".join(map(str, self.args)))
+ def dump(self, indent=" "):
+ print "%s%s" % (indent, self._dump())
+ for arg in self.args:
+ arg.dump(indent + " ")
+ def _dump(self):
+ return str(self)
+ def instantiate(self, var_mapping, init_facts):
+ args = [conditions.ObjectTerm(var_mapping.get(arg.name, arg.name))
+ for arg in self.args]
+ pne = PrimitiveNumericExpression(self.symbol, args)
+ assert not self.symbol == "total-cost"
+ # We know this expression is constant. Substitute it by corresponding
+ # initialization from task.
+ for fact in init_facts:
+ if isinstance(fact, FunctionAssignment):
+ if fact.fluent == pne:
+ return fact.expression
+ assert False, "Could not find instantiation for PNE!"
+
+class FunctionAssignment(object):
+ def __init__(self, fluent, expression):
+ self.fluent = fluent
+ self.expression = expression
+ def __str__(self):
+ return "%s %s %s" % (self.__class__.__name__, self.fluent, self.expression)
+ def dump(self, indent=" "):
+ print "%s%s" % (indent, self._dump())
+ self.fluent.dump(indent + " ")
+ self.expression.dump(indent + " ")
+ def _dump(self):
+ return self.__class__.__name__
+ def instantiate(self, var_mapping, init_facts):
+ if not (isinstance(self.expression, PrimitiveNumericExpression) or
+ isinstance(self.expression, NumericConstant)):
+ raise ValueError("Cannot instantiate assignment: not normalized")
+ # We know that this assignment is a cost effect of an action (for initial state
+ # assignments, "instantiate" is not called). Hence, we know that the fluent is
+ # the 0-ary "total-cost" which does not need to be instantiated
+ assert self.fluent.symbol == "total-cost"
+ fluent = self.fluent
+ expression = self.expression.instantiate(var_mapping, init_facts)
+ return self.__class__(fluent, expression)
+
+class Assign(FunctionAssignment):
+ def __str__(self):
+ return "%s := %s" % (self.fluent, self.expression)
+
+class Increase(FunctionAssignment):
+ pass
+
diff --git a/pool/shard009/Python/0083300_namelist.py b/pool/shard009/Python/0083300_namelist.py
new file mode 100644
index 0000000000000000000000000000000000000000..17fca270ef4b5d1e2ccbad54727abf2928009e3c
--- /dev/null
+++ b/pool/shard009/Python/0083300_namelist.py
@@ -0,0 +1,89 @@
+# Copyright (C) British Crown (Met Office) & Contributors.
+# This file is part of Rose, a framework for meteorological suites.
+#
+# Rose 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.
+#
+# Rose 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 Rose. If not, see .
+# -----------------------------------------------------------------------------
+"""Process namelist: sections in a metomi.rose.config.ConfigNode matching a
+name."""
+
+
+from functools import cmp_to_key
+import re
+
+import metomi.rose.config
+from metomi.rose.config_processor import ConfigProcessError
+from metomi.rose.env import UnboundEnvironmentVariableError, env_var_process
+from metomi.rose.reporter import Event
+
+RE_NAMELIST_GROUP = re.compile(r"\Anamelist:(\w+).*\Z")
+
+
+class NamelistEvent(Event):
+
+ LEVEL = Event.VV
+
+
+class NamelistLocHandler:
+ """Handler of namelists."""
+
+ SCHEME = "namelist"
+
+ def __init__(self, manager):
+ self.manager = manager
+
+ def can_pull(self, loc):
+ return loc.name.startswith(self.SCHEME + ":")
+
+ def parse(self, loc, conf_tree):
+ """Set loc.scheme, loc.loc_type."""
+ loc.scheme = self.SCHEME
+ loc.loc_type = loc.TYPE_BLOB
+ if loc.name.endswith("(:)"):
+ name = loc.name[0:-2]
+ sections = [
+ k for k in list(conf_tree.node.value) if k.startswith(name)
+ ]
+ else:
+ sections = [k for k in list(conf_tree.node.value) if k == loc.name]
+ for section in list(sections):
+ section_value = conf_tree.node.get_value([section])
+ if section_value is None:
+ sections.remove(section)
+ if not sections:
+ raise ValueError(loc.name)
+ return sections
+
+ async def pull(self, loc, conf_tree):
+ """Write namelist to loc.cache."""
+ sections = self.parse(loc, conf_tree)
+ if loc.name.endswith("(:)"):
+ sections.sort(key=cmp_to_key(metomi.rose.config.sort_settings))
+ with open(loc.cache, "wb") as handle:
+ for section in sections:
+ section_value = conf_tree.node.get_value([section])
+ group = RE_NAMELIST_GROUP.match(section).group(1)
+ nlg = "&" + group + "\n"
+ for key, node in sorted(section_value.items()):
+ if node.state:
+ continue
+ try:
+ value = env_var_process(node.value)
+ except UnboundEnvironmentVariableError as exc:
+ raise ConfigProcessError(
+ [section, key], node.value, exc
+ )
+ nlg += "%s=%s,\n" % (key, value)
+ nlg += "/" + "\n"
+ handle.write(nlg.encode('UTF-8'))
+ self.manager.handle_event(NamelistEvent(nlg))
diff --git a/pool/shard009/Python/0083305_midata.py b/pool/shard009/Python/0083305_midata.py
new file mode 100644
index 0000000000000000000000000000000000000000..3ad0d08b80694d6f4985b854b4de15090d16d5b9
--- /dev/null
+++ b/pool/shard009/Python/0083305_midata.py
@@ -0,0 +1,77 @@
+from midata.jsonapi import MidataObject
+import requests
+import collections.abc
+
+class Person(MidataObject):
+ _field_name = 'people'
+
+ def __init__(self, inner_json, full_json):
+ super().__init__(inner_json, full_json)
+
+ self.first_name = inner_json['first_name']
+ self.last_name = inner_json['last_name']
+
+ @property
+ def roles(self):
+ role_ids = set(int(x) for x in self._inner_json['links']['roles'])
+ return (role for role in Role.extract_linked(self._full_json)
+ if role.id in role_ids)
+
+ def __str__(self):
+ return "{} {}".format(self.first_name, self.last_name)
+
+class Group(MidataObject):
+ _field_name = 'groups'
+
+ def __init__(self, inner_json, full_json):
+ super().__init__(inner_json, full_json)
+
+ self.name = inner_json['name']
+ self.group_type = inner_json['group_type']
+
+ @property
+ def children(self):
+ return (int(x) for x in self._inner_json['links'].get('children', []))
+
+class Role(MidataObject):
+ _field_name = 'roles'
+
+ def __init__(self, inner_json, full_json):
+ super().__init__(inner_json, full_json)
+
+ self.description = inner_json['label'] or inner_json['role_type']
+ self.role_type = inner_json['role_type']
+
+ # TODO cache all_groups
+ @property
+ def group(self):
+ group_id = int(self._inner_json['links']['group'])
+ all_groups = Group.extract_linked(self._full_json)
+ # extract first matching group
+ return next(x for x in all_groups if x.id == group_id)
+
+def get_person(auth_info, person_id):
+ json = _fetch_content(auth_info, '/groups/1/people/{}'.format(person_id))
+ people = list(Person.extract_primary(json))
+ assert len(people) == 1
+ return people[0]
+
+def get_group(auth_info, group_id):
+ json = _fetch_content(auth_info, '/groups/{}'.format(group_id))
+ groups = list(Group.extract_primary(json))
+ assert len(groups) == 1
+ return groups[0]
+
+def get_members(auth_info, group_id):
+ json = _fetch_content(auth_info, '/groups/{}/people'.format(group_id))
+ return Person.extract_primary(json)
+
+def _fetch_content(auth_info, url):
+ r = requests.get(auth_info.server + url.format(auth_info.user_id),
+ headers=auth_info.http_headers())
+
+ if r.status_code != 200:
+ raise Exception("Error!")
+
+ return r.json()
+
diff --git a/pool/shard009/Python/0083307_logging.py b/pool/shard009/Python/0083307_logging.py
new file mode 100644
index 0000000000000000000000000000000000000000..d511999c159f6fca271517c49f1327932092ae8a
--- /dev/null
+++ b/pool/shard009/Python/0083307_logging.py
@@ -0,0 +1,89 @@
+# coding: utf-8
+
+from __future__ import absolute_import, division, unicode_literals, print_function
+
+import logging
+
+from .exceptions import APIError
+from . import api
+
+import config
+
+
+class GitHubIssueHandler(logging.Handler):
+ """Emit logged messages as issues on GitHub."""
+
+ headers = {'Accept': "application/vnd.github.v3+json"}
+
+ def __init__(self, owner, repo, user, access_token):
+ super(GitHubIssueHandler, self).__init__()
+
+ self.known_issues = set()
+ self.url = "https://api.github.com/repos/{}/{}/issues".format(owner, repo)
+ self._auth = (user, access_token)
+
+ def _detect_duplicate(self, title, labels=None):
+ if title in self.known_issues:
+ return True
+
+ params = {'state': "open", 'sort': "created", 'direction': "desc"}
+ if labels:
+ params['labels'] = ','.join(labels)
+
+ issues = []
+ try:
+ r = api.request_api(self.url, params=params, headers=self.headers)
+ issues.extend(i['title'] for i in r.json())
+ while 'next' in r.links:
+ r = api.request_api(r.links['next']['url'], headers=self.headers)
+ issues.extend(i['title'] for i in r.json())
+ except APIError:
+ pass
+
+ self.known_issues.update(issues)
+ return title in self.known_issues
+
+ def emit(self, record):
+ payload = {}
+ body = self.format(record)
+
+ if '\n' in body:
+ payload['title'], payload['body'] = body.split('\n', 1)
+ else:
+ payload['title'] = body
+
+ if hasattr(record, "gh_labels"):
+ payload['labels'] = record.gh_labels
+
+ if self._detect_duplicate(payload['title'], payload.get('labels', None)):
+ return
+
+ try:
+ r = api.request_api(self.url, json=payload, auth=self._auth,
+ headers=self.headers, method="POST")
+ except APIError:
+ self.handleError(record)
+ else:
+ if r.status_code == 201:
+ self.known_issues.add(payload['title'])
+
+
+def setup_logging(main_handler):
+ logger = logging.getLogger("vmbot")
+ logger.setLevel(logging.DEBUG)
+ cc_logger = logging.getLogger("cachecontrol")
+ cc_logger.setLevel(logging.WARNING)
+
+ main_handler.setFormatter(logging.Formatter("%(asctime)s %(levelname)s: %(message)s",
+ "%Y-%m-%d %H:%M:%S"))
+ main_handler.setLevel(config.LOGLEVEL)
+ logger.addHandler(main_handler)
+ cc_logger.addHandler(main_handler)
+
+ gh = config.GITHUB
+ if gh['user'] and gh['token']:
+ esi_handler = GitHubIssueHandler("XVMX", "VMBot", gh['user'], gh['token'])
+ esi_handler.setLevel(logging.WARNING)
+ logging.getLogger("vmbot.helpers.api.esi").addHandler(esi_handler)
+
+ return logger
diff --git a/pool/shard009/Python/0083316_ajax.py b/pool/shard009/Python/0083316_ajax.py
new file mode 100644
index 0000000000000000000000000000000000000000..76d41830e04f229192bbfb1ee2969424c2ac17b6
--- /dev/null
+++ b/pool/shard009/Python/0083316_ajax.py
@@ -0,0 +1,98 @@
+# -*- coding: utf-8 -*-
+
+from dajaxice.decorators import dajaxice_register
+from dajax.core import Dajax
+
+from django.template.loader import get_template
+from django.template import Context
+
+from django.core.urlresolvers import reverse
+from django.utils.translation import ugettext
+
+from pompadour_wiki.apps.filemanager.models import Attachment
+from pompadour_wiki.apps.wiki.models import Wiki
+from pompadour_wiki.apps.utils import urljoin, decode_unicode_references
+
+import os
+
+@dajaxice_register
+def remove_doc(request, wiki=None, files=None):
+ dajax = Dajax()
+
+ if not wiki or not files:
+ return dajax.json()
+
+ try:
+ w = Wiki.objects.get(slug=wiki)
+
+ except Wiki.DoesNotExist:
+ return dajax.json()
+
+ for f in files:
+ path = os.path.join('__media__', *f.split('/'))
+
+ w.repo.delete(path)
+ w.repo.commit(request.user, ugettext(u'Update Wiki: {0} deleted'.format(path)).encode('utf-8'))
+
+ # Remove attachments
+ Attachment.objects.filter(file=f).delete()
+
+
+ dajax.redirect(reverse('filemanager-index', args=[wiki, '']))
+
+ return dajax.json()
+
+@dajaxice_register
+def attach_doc(request, wiki=None, files=None, page=None):
+ dajax = Dajax()
+
+ if not wiki or not files or not page:
+ return dajax.json()
+
+ try:
+ w = Wiki.objects.get(slug=wiki)
+
+ except Wiki.DoesNotExist:
+ return dajax.json()
+
+ page = decode_unicode_references(page)
+
+ for f in files:
+ urlpage = urljoin(wiki, page.encode('utf-8'))
+
+ # check if the attachment already exist
+ if not Attachment.objects.filter(wiki=w, page=urlpage, file=f):
+ # the attachment doesn't exist, we can add it
+ a = Attachment()
+ a.wiki = w
+ a.page = urlpage
+ a.file = f
+ a.mimetype = w.repo.mimetype(os.path.join('__media__', *f.split('/')))
+
+ a.save()
+
+ tmpl = get_template('wiki/attachitem.html')
+ rendered = tmpl.render(Context({
+ 'wiki': {
+ 'obj': w,
+ },
+ 'doc': a,
+ }))
+
+ dajax.add_data(rendered, 'append_attached_document')
+ dajax.alert(ugettext(u'{0} attached to {1}').format(f, page))
+
+ return dajax.json()
+
+@dajaxice_register
+def remove_attach(request, attachment=None):
+ dajax = Dajax()
+
+ if not attachment:
+ return dajax.json()
+
+ Attachment.objects.filter(pk=attachment).delete()
+
+ dajax.script('window.location.reload();')
+
+ return dajax.json()
\ No newline at end of file
diff --git a/pool/shard009/Python/0083317_monitorparser.py b/pool/shard009/Python/0083317_monitorparser.py
new file mode 100644
index 0000000000000000000000000000000000000000..a8bc1a3843a52bd24a8c57c0829818c9df8c6747
--- /dev/null
+++ b/pool/shard009/Python/0083317_monitorparser.py
@@ -0,0 +1,56 @@
+from datetime import datetime
+from time import mktime
+from commands import getoutput
+from collections import defaultdict
+import sys
+
+def getdate(line):
+ return line.split('\t')[0]
+
+def gettimestamp(date):
+ t = mktime(datetime.strptime(date, "%Y-%m-%d %H:%M:%S" ).timetuple())
+ return int(t)
+
+def rrdupdate(ts, usercount, bw):
+ rrdupdate = "rrdtool update monitor_db.rrd --template bandwidth:usercount {0}:{1}:{2}"
+ r = rrdupdate.format(ts, bw, usercount)
+ if "-v" in sys.argv: print r
+ rrd = getoutput(r)
+ if rrd.startswith("ERROR"):
+ print rrd
+ return rrd
+
+def parseline(line):
+ date, text = line.split('\t')
+ ts = gettimestamp(date)
+ return (ts, text)
+
+if __name__ == "__main__":
+ with open('monitor.log', 'r') as f:
+ monitor = f.readlines()
+
+ print "preprocessing"
+ pre = list()
+ for i in xrange(len(monitor)):
+ line = monitor[i]
+ nextline = monitor[i+1] if i+1 < len(monitor) else ""
+
+ try:
+ ts, msg = parseline(line)
+ nextts, nextmsg = parseline(nextline)
+ except ValueError:
+ continue
+
+ if msg.startswith("Usercount:"):
+ usercount = int(msg.split(": ")[1])
+ if nextmsg.startswith("Bandwidth usage: "):
+ bw = float(nextmsg.split(": ")[1].split(" ")[0])
+ else:
+ bw = 0
+ pre.append((ts, usercount, bw))
+
+ print "done, count:", len(monitor)
+ print "rrdtool..."
+ for value in pre:
+ rrdupdate(*value)
+ print "done."
diff --git a/pool/shard009/Python/0083321_files.py b/pool/shard009/Python/0083321_files.py
new file mode 100644
index 0000000000000000000000000000000000000000..750ac32c642e8ce758345fc48adf32392c525574
--- /dev/null
+++ b/pool/shard009/Python/0083321_files.py
@@ -0,0 +1,107 @@
+# Copyright 2013 Hewlett-Packard Development Company, L.P.
+# 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 os
+import sys
+
+from pbr import find_package
+from pbr.hooks import base
+
+
+def get_manpath():
+ manpath = 'share/man'
+ if os.path.exists(os.path.join(sys.prefix, 'man')):
+ # This works around a bug with install where it expects every node
+ # in the relative data directory to be an actual directory, since at
+ # least Debian derivatives (and probably other platforms as well)
+ # like to symlink Unixish /usr/local/man to /usr/local/share/man.
+ manpath = 'man'
+ return manpath
+
+
+def get_man_section(section):
+ return os.path.join(get_manpath(), 'man%s' % section)
+
+
+class FilesConfig(base.BaseConfig):
+
+ section = 'files'
+
+ def __init__(self, config, name):
+ super(FilesConfig, self).__init__(config)
+ self.name = name
+ self.data_files = self.config.get('data_files', '')
+
+ def save(self):
+ self.config['data_files'] = self.data_files
+ super(FilesConfig, self).save()
+
+ def expand_globs(self):
+ finished = []
+ for line in self.data_files.split("\n"):
+ if line.rstrip().endswith('*') and '=' in line:
+ (target, source_glob) = line.split('=')
+ source_prefix = source_glob.strip()[:-1]
+ target = target.strip()
+ if not target.endswith(os.path.sep):
+ target += os.path.sep
+ for (dirpath, dirnames, fnames) in os.walk(source_prefix):
+ # As source_prefix is always matched, using replace with a
+ # a limit of one is always going to replace the path prefix
+ # and not accidentally replace some text in the middle of
+ # the path
+ new_prefix = dirpath.replace(source_prefix, target, 1)
+ finished.append("%s = " % new_prefix)
+ finished.extend(
+ [" %s" % os.path.join(dirpath, f) for f in fnames])
+ else:
+ finished.append(line)
+
+ self.data_files = "\n".join(finished)
+
+ def add_man_path(self, man_path):
+ self.data_files = "%s\n%s =" % (self.data_files, man_path)
+
+ def add_man_page(self, man_page):
+ self.data_files = "%s\n %s" % (self.data_files, man_page)
+
+ def get_man_sections(self):
+ man_sections = dict()
+ manpages = self.pbr_config['manpages']
+ for manpage in manpages.split():
+ section_number = manpage.strip()[-1]
+ section = man_sections.get(section_number, list())
+ section.append(manpage.strip())
+ man_sections[section_number] = section
+ return man_sections
+
+ def hook(self):
+ packages = self.config.get('packages', self.name).strip()
+ expanded = []
+ for pkg in packages.split("\n"):
+ if os.path.isdir(pkg.strip()):
+ expanded.append(find_package.smart_find_packages(pkg.strip()))
+
+ self.config['packages'] = "\n".join(expanded)
+
+ self.expand_globs()
+
+ if 'manpages' in self.pbr_config:
+ man_sections = self.get_man_sections()
+ for (section, pages) in man_sections.items():
+ manpath = get_man_section(section)
+ self.add_man_path(manpath)
+ for page in pages:
+ self.add_man_page(page)
diff --git a/pool/shard009/Python/0083323_urls.py b/pool/shard009/Python/0083323_urls.py
new file mode 100644
index 0000000000000000000000000000000000000000..69cc80d71f768460ec21eb84a95c7841de03c587
--- /dev/null
+++ b/pool/shard009/Python/0083323_urls.py
@@ -0,0 +1,15 @@
+from django.conf.urls import patterns, include, url
+from django.contrib.gis import admin
+
+from world.views import IndexView,MapaDetailView
+
+urlpatterns = patterns('',
+ # Examples:
+ # url(r'^$', 'geodjango.views.home', name='home'),
+ # url(r'^blog/', include('blog.urls')),
+
+ url(r'^admin/', include(admin.site.urls)),
+ # url(r'^$', 'world.views.index', name='index'),
+ url(r'^$',IndexView.as_view()),
+ url(r'^mapa/(?P[-\w]+)/$', MapaDetailView.as_view()),
+)
diff --git a/pool/shard009/Python/0083333_p301_remove_invalid_parentheses.py b/pool/shard009/Python/0083333_p301_remove_invalid_parentheses.py
new file mode 100644
index 0000000000000000000000000000000000000000..6cf601233494c2b014eba2e9255ad2966550f5ac
--- /dev/null
+++ b/pool/shard009/Python/0083333_p301_remove_invalid_parentheses.py
@@ -0,0 +1,96 @@
+# coding: utf-8
+
+# author: Fei Gao
+
+# Problem: remove invalid parentheses
+#
+# Remove the minimum number of invalid parentheses in order to make the input
+# string valid. Return all possible results.
+# Note: The input string may contain letters other than the parentheses ( and
+# ).
+#
+# Examples:
+#
+# "()())()" -> ["()()()", "(())()"]
+# "(a)())()" -> ["(a)()()", "(a())()"]
+# ")(" -> [""]
+#
+# Credits:Special thanks to @hpplayer for adding this problem and creating all
+# test cases.
+#
+# Subscribe to see which companies asked this question
+#
+# Show Tags
+#
+# Depth-first Search
+# Breadth-first Search
+#
+# Show Similar Problems
+#
+# (E) Valid Parentheses
+
+
+class Solution(object):
+ def removeInvalidParentheses(self, s):
+ """
+ :type s: str
+ :rtype: List[str]
+ """
+ results = []
+ lps, rps = [], []
+ for i, c in enumerate(s):
+ if c == '(':
+ lps.append(i)
+ elif c == ')':
+ rps.append(i)
+ lp, rp = len(lps), len(rps)
+ if lp <= rp:
+ dl, dr = 0, rp - lp
+ else:
+ dl, dr = lp - rp, 0
+
+ def is_valid(s):
+ lp, rp = 0, 0
+ for c in s:
+ if c == '(':
+ lp += 1
+ elif c == ')':
+ rp += 1
+ if lp < rp:
+ return False
+ return lp == rp
+
+ from itertools import combinations
+ while True:
+ for dlps in combinations(lps, dl):
+ for drps in combinations(rps, dr):
+ r = ''.join(c for i, c in enumerate(s) if i not in dlps + drps)
+ if is_valid(r):
+ results.append(r)
+ if results:
+ break
+ else:
+ dl, dr = dl + 1, dr + 1
+ return list(set(results))
+
+
+def main():
+ solver = Solution()
+ tests = [
+ (("()())()",), ["()()()", "(())()"]),
+ (("(a)())()",),["(a)()()", "(a())()"]),
+ ((")(",), [""])
+ ]
+ for params, expect in tests:
+ print('-' * 5 + 'TEST' + '-' * 5)
+ print('Input: ' + str(params))
+ print('Expect: ' + str(expect))
+
+ result = solver.removeInvalidParentheses(*params)
+ print('Result: ' + str(result))
+ pass
+
+
+if __name__ == '__main__':
+ main()
+ pass
diff --git a/pool/shard009/Python/0083336_session_test.py b/pool/shard009/Python/0083336_session_test.py
new file mode 100644
index 0000000000000000000000000000000000000000..2b055e85f3296617c0cca1f5f5273f5cce1a4ba3
--- /dev/null
+++ b/pool/shard009/Python/0083336_session_test.py
@@ -0,0 +1,113 @@
+#-*- coding:utf-8 -*-
+from __future__ import absolute_import, division, print_function, with_statement
+
+import sys
+import signal
+import random
+import time
+import logging
+import requests
+import multiprocessing
+import time
+import os
+
+
+from turbo import app
+from turbo.conf import app_config
+from turbo import register
+from turbo.session import RedisStore
+
+app_config.app_name = 'app_test'
+app_config.web_application_setting = {
+ 'xsrf_cookies': False,
+ 'cookie_secret': 'asdf/asdfiw872*&^2/'
+}
+
+from turbo.test.util import unittest
+
+
+class HomeHandler(app.BaseHandler):
+
+ session_initializer = {
+ 'time': time.time(),
+ 'uid': None,
+ }
+
+ def get(self):
+ assert self.session.uid is None
+ assert self.session.session_id is not None
+ self.write('get')
+
+ def post(self):
+ self.session.uid = '7787'
+ self.write('post')
+
+ def put(self):
+ assert self.session.uid == '7787'
+ self.write('put')
+
+
+class RedisStoreHandler(app.BaseHandler):
+
+ session_initializer = {
+ 'time': time.time(),
+ 'uid': None,
+ }
+
+ session_store = RedisStore(timeout=3600)
+
+ def get(self):
+ assert self.session.uid is None
+ assert self.session.session_id is not None
+ self.write('get')
+
+ def post(self):
+ self.session.uid = '7787'
+ self.write('post')
+
+ def put(self):
+ assert self.session.uid == '7787'
+ self.write('put')
+
+
+def run_server():
+ register.register_url('/', HomeHandler)
+ register.register_url('/redis', RedisStoreHandler)
+ app.start()
+
+
+class SessionTest(unittest.TestCase):
+
+ def setUp(self):
+ server = multiprocessing.Process(target=run_server)
+ server.start()
+ self.home_url = 'http://localhost:8888'
+ self.redis_url = 'http://localhost:8888/redis'
+ self.pid = server.pid
+ time.sleep(1)
+
+ def tearDown(self):
+ os.kill(self.pid, signal.SIGKILL)
+
+ def test_session(self):
+ resp = requests.get(self.home_url, headers={'refer':'http://127.0.0.1:8888'})
+ self.assertEqual(resp.status_code, 200)
+ cookies = resp.cookies
+ resp = requests.post(self.home_url, cookies=cookies)
+ self.assertEqual(resp.status_code, 200)
+
+ resp = requests.put(self.home_url, cookies=cookies)
+ self.assertEqual(resp.status_code, 200)
+
+ def test_redis_store_session(self):
+ resp = requests.get(self.redis_url, headers={'refer':'http://127.0.0.1:8888'})
+ self.assertEqual(resp.status_code, 200)
+ cookies = resp.cookies
+ resp = requests.post(self.redis_url, cookies=cookies)
+ self.assertEqual(resp.status_code, 200)
+
+ resp = requests.put(self.redis_url, cookies=cookies)
+ self.assertEqual(resp.status_code, 200)
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/pool/shard009/Python/0083337_tests.py b/pool/shard009/Python/0083337_tests.py
new file mode 100644
index 0000000000000000000000000000000000000000..e9c7877a8a80c0bddba2781b1840b55dc8b20bbb
--- /dev/null
+++ b/pool/shard009/Python/0083337_tests.py
@@ -0,0 +1,46 @@
+# -*- encoding: utf-8 -*-
+from django.test import TestCase
+from django.test.client import Client
+from django.contrib.sites.models import Site
+from allauth.account.models import EmailAddress, EmailConfirmation
+from apps.account_system.models import User
+from django.conf import settings
+from django.test.utils import override_settings
+
+@override_settings(
+SITE_ID = 2
+)
+class CrearUsuarioTestCase(TestCase):
+
+ def setUp(self):
+ if 'allauth.socialaccount' in settings.INSTALLED_APPS:
+ # Otherwise ImproperlyConfigured exceptions may occur
+ from allauth.socialaccount.models import SocialApp
+ sa = SocialApp.objects.create(name='testfb',
+ provider='facebook')
+ sa.sites.add(Site.objects.get_current())
+
+
+ def test_index(self):
+ resp = self.client.get('/')
+ self.assertEqual(resp.status_code, 200)
+
+ def test_login(self):
+ # First check for the default behavior
+ response = self.client.get('/accounts/login/')
+ self.assertEqual(response.status_code, 200)
+ response = c.post('/accounts/login/', {'username': '1', 'password': '1'})
+
+ def test_username_containing_at(self):
+ user = User.objects.create(username='@raymond.penners')
+ user.set_password('psst')
+ user.save()
+ EmailAddress.objects.create(user=user,
+ email='raymond.penners@gmail.com',
+ primary=True,
+ verified=True)
+ resp = self.client.post(reverse('account_login'),
+ {'login': '@raymond.penners',
+ 'password': 'psst'})
+ self.assertEqual(resp['location'],
+ 'http://testserver'+settings.LOGIN_REDIRECT_URL)
diff --git a/pool/shard009/Python/0083340_sieve.py b/pool/shard009/Python/0083340_sieve.py
new file mode 100644
index 0000000000000000000000000000000000000000..a3cac1e628fdb84ce2e37507385906a64f01078a
--- /dev/null
+++ b/pool/shard009/Python/0083340_sieve.py
@@ -0,0 +1,98 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+#
+# Lets data Packets pass-through, "sieve", based on criteria in their data.
+# See issue: https://github.com/geopython/stetl/issues/78
+#
+# A concrete example is AttrValueRecordSieve which sieves records matching
+# specific attribute values. One can also think of Sieves based on XPath expressions
+# (e.g. for XML, GML), or geospatial, based on for example WFS-like filters like bounding boxes.
+#
+# Author: Just van den Broecke
+#
+from stetl.component import Config
+from stetl.filter import Filter
+from stetl.util import Util
+from stetl.packet import FORMAT
+
+log = Util.get_log('Sieve')
+
+
+class Sieve(Filter):
+ """
+ ABC for specific Sieves that pass-through, "sieve", Packets based on criteria in their data.
+ """
+
+ def __init__(self, configdict, section, consumes, produces):
+ Filter.__init__(self, configdict, section, consumes, produces)
+
+ def invoke(self, packet):
+ if packet.data is None:
+ return packet
+ return self.sieve(packet)
+
+ def sieve(self, packet):
+ """
+ To be implemented in subclasses.
+ :param packet:
+ :return:
+ """
+ return packet
+
+
+class AttrValueRecordSieve(Sieve):
+ """
+ Sieves by attr/value(s) in Record Packets.
+ """
+
+ @Config(ptype=str, required=True)
+ def attr_name(self):
+ """
+ Name of attribute whose value(s) are to be sieved.
+ """
+ pass
+
+ @Config(ptype=list, default=list(), required=False)
+ def attr_values(self):
+ """
+ Value(s) for attribute to be to sieved. If empty any value is passed through (existence
+ of attr_name is criterium).
+ """
+ pass
+
+ def __init__(self, configdict, section):
+ Sieve.__init__(self, configdict, section, consumes=[FORMAT.record_array, FORMAT.record], produces=[FORMAT.record_array, FORMAT.record])
+
+ def sieve(self, packet):
+ """
+ Filter out Packets that are not matching designated attr value(s).
+ :param packet:
+ :return:
+ """
+
+ # Start with empty result: fill with matching records
+ record_data = packet.data
+ packet.data = None
+
+ # Data can be list or single record
+ if type(record_data) is list:
+ packet.data = list()
+ for record in record_data:
+ if self.matches_attr(record):
+ packet.data.append(record)
+ elif type(record_data) is dict:
+ if self.matches_attr(record_data):
+ packet.data = record_data
+
+ return packet
+
+ def matches_attr(self, record):
+ # Attr not even in record: no use going on
+ if self.attr_name not in record:
+ return False
+
+ # Match if no value
+ if not self.attr_values:
+ return True
+
+ return record[self.attr_name] in self.attr_values
diff --git a/pool/shard009/Python/0083344_cargo.py b/pool/shard009/Python/0083344_cargo.py
new file mode 100644
index 0000000000000000000000000000000000000000..9d970eff79e8800d8039f738c1a0c76252a80691
--- /dev/null
+++ b/pool/shard009/Python/0083344_cargo.py
@@ -0,0 +1,47 @@
+import os
+import toml
+
+rust_src = os.environ['RUSTC_SRC']
+orig_cargo = os.environ['ORIG_CARGO'] if 'ORIG_CARGO' in os.environ else None
+
+base = {
+ 'package': {
+ 'name': 'nixpkgs-sysroot-stub-crate',
+ 'version': '0.0.0',
+ 'authors': ['The Rust Project Developers'],
+ 'edition': '2018',
+ },
+ 'dependencies': {
+ 'compiler_builtins': {
+ 'version': '0.1.0',
+ 'features': ['rustc-dep-of-std', 'mem'],
+ },
+ 'core': {
+ 'path': os.path.join(rust_src, 'core'),
+ },
+ 'alloc': {
+ 'path': os.path.join(rust_src, 'alloc'),
+ },
+ },
+ 'patch': {
+ 'crates-io': {
+ 'rustc-std-workspace-core': {
+ 'path': os.path.join(rust_src, 'rustc-std-workspace-core'),
+ },
+ 'rustc-std-workspace-alloc': {
+ 'path': os.path.join(rust_src, 'rustc-std-workspace-alloc'),
+ },
+ },
+ },
+}
+
+if orig_cargo is not None:
+ with open(orig_cargo, 'r') as f:
+ src = toml.loads(f.read())
+ if 'profile' in src:
+ base['profile'] = src['profile']
+
+out = toml.dumps(base)
+
+with open('Cargo.toml', 'x') as f:
+ f.write(out)
diff --git a/pool/shard009/Python/0083350_coin.py b/pool/shard009/Python/0083350_coin.py
new file mode 100644
index 0000000000000000000000000000000000000000..9f16825b18183ae872596919e74fe07a693f3078
--- /dev/null
+++ b/pool/shard009/Python/0083350_coin.py
@@ -0,0 +1,19 @@
+from collections import Counter
+import random
+
+from .base import MessageHandler
+from ..util import parse_int
+
+class CoinHandler(MessageHandler):
+
+ TRIGGERS = ['coin', 'flip']
+ HELP = 'flip the given number of coins; default 1'
+
+ def handle_message(self, event, triggers, query):
+ times = parse_int(query, default=1)
+ flips_gen = (random.choice(('heads', 'tails')) for _ in xrange(times))
+ if times > 10:
+ counter = Counter(flips_gen)
+ return '%s heads, %s tails' % (counter['heads'], counter['tails'])
+ else:
+ return ', '.join(flips_gen)
diff --git a/pool/shard009/Python/0083353_dirac-jobexec.py b/pool/shard009/Python/0083353_dirac-jobexec.py
new file mode 100644
index 0000000000000000000000000000000000000000..21b9bccd9dbd5ef381b0117524ce8f5e6c5b3622
--- /dev/null
+++ b/pool/shard009/Python/0083353_dirac-jobexec.py
@@ -0,0 +1,102 @@
+#!/usr/bin/env python
+########################################################################
+# File : dirac-jobexec
+# Author : Stuart Paterson
+########################################################################
+""" The dirac-jobexec script is equipped to execute workflows that
+ are specified via their XML description. The main client of
+ this script is the Job Wrapper.
+"""
+
+__RCSID__ = "$Id$"
+
+
+import os
+import os.path
+import sys
+
+import DIRAC
+from DIRAC.Core.Base import Script
+
+# Register workflow parameter switch
+Script.registerSwitch('p:', 'parameter=', 'Parameters that are passed directly to the workflow')
+Script.parseCommandLine()
+
+# from DIRAC.Core.Workflow.Parameter import *
+from DIRAC import gLogger
+from DIRAC.Core.Workflow.Workflow import fromXMLFile
+from DIRAC.WorkloadManagementSystem.Client.JobReport import JobReport
+from DIRAC.AccountingSystem.Client.DataStoreClient import DataStoreClient
+from DIRAC.RequestManagementSystem.Client.Request import Request
+
+# Forcing the current directory to be the first in the PYTHONPATH
+sys.path.insert(0, os.path.realpath('.'))
+gLogger.showHeaders(True)
+
+
+def jobexec(jobxml, wfParameters):
+ jobfile = os.path.abspath(jobxml)
+ if not os.path.exists(jobfile):
+ gLogger.warn('Path to specified workflow %s does not exist' % (jobfile))
+ sys.exit(1)
+ workflow = fromXMLFile(jobfile)
+ gLogger.debug(workflow)
+ code = workflow.createCode()
+ gLogger.debug(code)
+ jobID = 0
+ if 'JOBID' in os.environ:
+ jobID = os.environ['JOBID']
+ gLogger.info('DIRAC JobID %s is running at site %s' % (jobID, DIRAC.siteName()))
+
+ workflow.addTool('JobReport', JobReport(jobID))
+ workflow.addTool('AccountingReport', DataStoreClient())
+ workflow.addTool('Request', Request())
+
+ # Propagate the command line parameters to the workflow if any
+ for pName, pValue in wfParameters.items():
+ workflow.setValue(pName, pValue)
+
+ # Propagate the command line parameters to the workflow module instances of each step
+ for stepdefinition in workflow.step_definitions.itervalues():
+ for moduleInstance in stepdefinition.module_instances:
+ for pName, pValue in wfParameters.iteritems():
+ if moduleInstance.parameters.find(pName):
+ moduleInstance.parameters.setValue(pName, pValue)
+
+ return workflow.execute()
+
+
+positionalArgs = Script.getPositionalArgs()
+if len(positionalArgs) != 1:
+ gLogger.debug('Positional arguments were %s' % (positionalArgs))
+ DIRAC.abort(1, "Must specify the Job XML file description")
+
+if 'JOBID' in os.environ:
+ gLogger.info('JobID: %s' % (os.environ['JOBID']))
+
+jobXMLfile = positionalArgs[0]
+parList = Script.getUnprocessedSwitches()
+parDict = {}
+for switch, parameter in parList:
+ if switch == "p":
+ name, value = parameter.split('=')
+ value = value.strip()
+
+ # The comma separated list in curly brackets is interpreted as a list
+ if value.startswith("{"):
+ value = value[1:-1].replace('"', '').replace(" ", '').split(',')
+ value = ';'.join(value)
+
+ parDict[name] = value
+
+gLogger.debug('PYTHONPATH:\n%s' % ('\n'.join(sys.path)))
+jobExec = jobexec(jobXMLfile, parDict)
+if not jobExec['OK']:
+ gLogger.debug('Workflow execution finished with errors, exiting')
+ if jobExec['Errno']:
+ sys.exit(jobExec['Errno'])
+ else:
+ sys.exit(1)
+else:
+ gLogger.debug('Workflow execution successful, exiting')
+ sys.exit(0)
diff --git a/pool/shard009/Python/0083354_fsck.py b/pool/shard009/Python/0083354_fsck.py
new file mode 100644
index 0000000000000000000000000000000000000000..5274f13a5b0e35d05688bf812f91ba234c9a6707
--- /dev/null
+++ b/pool/shard009/Python/0083354_fsck.py
@@ -0,0 +1,152 @@
+# fsck.py
+# Filesystem check functionality.
+#
+# Copyright (C) 2015 Red Hat, Inc.
+#
+# This copyrighted material is made available to anyone wishing to use,
+# modify, copy, or redistribute it subject to the terms and conditions of
+# the GNU General Public License v.2, or (at your option) any later version.
+# This program is distributed in the hope that it will be useful, but WITHOUT
+# ANY WARRANTY expressed or implied, including the implied warranties of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
+# Public License for more details. You should have received a copy of the
+# GNU General Public License along with this program; if not, write to the
+# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+# 02110-1301, USA. Any Red Hat trademarks that are incorporated in the
+# source code or documentation are not subject to the GNU General Public
+# License and may only be used or replicated with the express permission of
+# Red Hat, Inc.
+#
+# Red Hat Author(s): Anne Mulhern
+
+import abc
+
+from six import add_metaclass
+
+from ..errors import FSError
+from .. import util
+
+from . import availability
+from . import fstask
+from . import task
+
+_UNKNOWN_RC_MSG = "Unknown return code: %d"
+
+
+@add_metaclass(abc.ABCMeta)
+class FSCK(task.BasicApplication, fstask.FSTask):
+
+ """An abstract class that represents actions associated with
+ checking consistency of a filesystem.
+ """
+ description = "fsck"
+
+ options = abc.abstractproperty(
+ doc="Options for invoking the application.")
+
+ # IMPLEMENTATION methods
+
+ @abc.abstractmethod
+ def _error_message(self, rc):
+ """ Error message corresponding to rc.
+
+ :param int rc: the fsck program return code
+ :returns: an error message corresponding to the code, or None
+ :rtype: str or NoneType
+
+ A return value of None indicates no error.
+ """
+ raise NotImplementedError()
+
+ @property
+ def _fsck_command(self):
+ """The command to check the filesystem.
+
+ :return: the command
+ :rtype: list of str
+ """
+ return [str(self.ext)] + self.options + [self.fs.device]
+
+ def do_task(self):
+ """ Check the filesystem.
+
+ :raises FSError: on failure
+ """
+ error_msgs = self.availability_errors
+ if error_msgs:
+ raise FSError("\n".join(error_msgs))
+
+ try:
+ rc = util.run_program(self._fsck_command)
+ except OSError as e:
+ raise FSError("filesystem check failed: %s" % e)
+
+ error_msg = self._error_message(rc)
+ if error_msg is not None:
+ hdr = "%(type)s filesystem check failure on %(device)s: " % \
+ {"type": self.fs.type, "device": self.fs.device}
+
+ raise FSError(hdr + error_msg)
+
+
+class DosFSCK(FSCK):
+ _fsck_errors = {1: "Recoverable errors have been detected or dosfsck has "
+ "discovered an internal inconsistency.",
+ 2: "Usage error."}
+
+ ext = availability.DOSFSCK_APP
+ options = ["-n"]
+
+ def _error_message(self, rc):
+ if rc < 1:
+ return None
+ try:
+ return self._fsck_errors[rc]
+ except KeyError:
+ return _UNKNOWN_RC_MSG % rc
+
+
+class Ext2FSCK(FSCK):
+ _fsck_errors = {4: "File system errors left uncorrected.",
+ 8: "Operational error.",
+ 16: "Usage or syntax error.",
+ 32: "e2fsck cancelled by user request.",
+ 128: "Shared library error."}
+
+ ext = availability.E2FSCK_APP
+ # "Force checking even if the file system seems clean." (we might get false results otherwise)
+ # + "Automatically repair ("preen") the file system."
+ options = ["-f", "-p"]
+
+ def _error_message(self, rc):
+ msgs = (self._fsck_errors[c] for c in self._fsck_errors.keys() if rc & c)
+ return "\n".join(msgs) or None
+
+
+class HFSPlusFSCK(FSCK):
+ _fsck_errors = {3: "Quick check found a dirty filesystem; no repairs done.",
+ 4: "Root filesystem was dirty. System should be rebooted.",
+ 8: "Corrupt filesystem, repairs did not succeed.",
+ 47: "Major error found; no repairs attempted."}
+ ext = availability.FSCK_HFSPLUS_APP
+ options = []
+
+ def _error_message(self, rc):
+ if rc < 1:
+ return None
+ try:
+ return self._fsck_errors[rc]
+ except KeyError:
+ return _UNKNOWN_RC_MSG % rc
+
+
+class NTFSFSCK(FSCK):
+ ext = availability.NTFSRESIZE_APP
+ options = ["-c"]
+
+ def _error_message(self, rc):
+ return _UNKNOWN_RC_MSG % (rc,) if rc != 0 else None
+
+
+class UnimplementedFSCK(fstask.UnimplementedFSTask):
+ pass
diff --git a/pool/shard009/Python/0083355_systemCheck.py b/pool/shard009/Python/0083355_systemCheck.py
new file mode 100644
index 0000000000000000000000000000000000000000..538a5c772ede8554f7dac06bbc80a8ac06ae27fe
--- /dev/null
+++ b/pool/shard009/Python/0083355_systemCheck.py
@@ -0,0 +1,152 @@
+import os
+import subprocess
+import sys
+
+#from module import InitHomeDir
+
+#very ugly prints, but at least it works with python 3
+
+def main():
+ print("##### System Information #####\n")
+ print("Platform:", sys.platform)
+ print("Operating System:", os.name)
+ print("Python:", sys.version.replace("\n", "")+ "\n")
+
+ try:
+ import pycurl
+ print("pycurl:", pycurl.version)
+ except:
+ print("pycurl:", "missing")
+
+ try:
+ import Crypto
+ print("py-crypto:", Crypto.__version__)
+ except:
+ print("py-crypto:", "missing")
+
+ try:
+ import OpenSSL
+ print("OpenSSL:", OpenSSL.version.__version__)
+ except:
+ print("OpenSSL:", "missing")
+
+ try:
+ from PIL import Image
+ print("image library:", Image.VERSION)
+ except:
+ try:
+ import Image
+ print("image library:", Image.VERSION)
+ except:
+ print("image library:", "missing")
+
+ try:
+ import PyQt4.QtCore
+ print("pyqt:", PyQt4.QtCore.PYQT_VERSION_STR)
+ except:
+ print("pyqt:", "missing")
+
+ from module.common import JsEngine
+ js = JsEngine.ENGINE if JsEngine.ENGINE else "missing"
+ print("JS engine:", js)
+
+
+ print("\n\n##### System Status #####")
+ print("\n## pyLoadCore ##")
+
+ core_err = []
+ core_info = []
+
+ if sys.version_info > (2, 8):
+ core_err.append("Your python version is to new, Please use Python 2.6/2.7")
+
+ if sys.version_info < (2, 5):
+ core_err.append("Your python version is to old, Please use at least Python 2.5")
+
+ try:
+ import pycurl
+ except:
+ core_err.append("Please install py-curl to use pyLoad.")
+
+ try:
+ from pycurl import AUTOREFERER
+ except:
+ core_err.append("Your py-curl version is to old, please upgrade!")
+
+ try:
+ from PIL import Image
+ except:
+ try:
+ import Image
+ except:
+ core_err.append("Please install py-imaging/pil/pillow to use Hoster, which uses captchas.")
+
+ pipe = subprocess.PIPE
+ try:
+ p = subprocess.call(["tesseract"], stdout=pipe, stderr=pipe)
+ except:
+ core_err.append("Please install tesseract to use Hoster, which uses captchas.")
+
+ try:
+ import OpenSSL
+ except:
+ core_info.append("Install OpenSSL if you want to create a secure connection to the core.")
+
+ if not js:
+ print("no JavaScript engine found")
+ print("You will need this for some Click'N'Load links. Install Spidermonkey, ossp-js, pyv8 or rhino")
+
+ if core_err:
+ print("The system check has detected some errors:\n")
+ for err in core_err:
+ print(err)
+ else:
+ print("No Problems detected, pyLoadCore should work fine.")
+
+ if core_info:
+ print("\nPossible improvements for pyload:\n")
+ for line in core_info:
+ print(line)
+
+ print("\n## pyLoadGui ##")
+
+ gui_err = []
+
+ try:
+ import PyQt4
+ except:
+ gui_err.append("GUI won't work without pyqt4 !!")
+
+ if gui_err:
+ print("The system check has detected some errors:\n")
+ for err in gui_err:
+ print(err)
+ else:
+ print("No Problems detected, pyLoadGui should work fine.")
+
+ print("\n## Webinterface ##")
+
+ web_err = []
+ web_info = []
+
+ try:
+ import flup
+ except:
+ web_info.append("Install Flup to use FastCGI or optional webservers.")
+
+ if web_err:
+ print("The system check has detected some errors:\n")
+ for err in web_err:
+ print(err)
+ else:
+ print("No Problems detected, Webinterface should work fine.")
+
+ if web_info:
+ print("\nPossible improvements for webinterface:\n")
+ for line in web_info:
+ print(line)
+
+if __name__ == "__main__":
+ main()
+
+ raw_input("Press Enter to Exit.")
diff --git a/pool/shard009/Python/0083358_lookups.py b/pool/shard009/Python/0083358_lookups.py
new file mode 100644
index 0000000000000000000000000000000000000000..0b4a673d759281de47ae1367d0c4b1dacdd2db8e
--- /dev/null
+++ b/pool/shard009/Python/0083358_lookups.py
@@ -0,0 +1,150 @@
+from functools import reduce
+import operator
+import re
+
+from dal import autocomplete
+from django.contrib.auth.models import Group
+from django.conf.urls import url
+from django.db.models import Q, Count
+
+from workshops import models
+from workshops.util import OnlyForAdminsNoRedirectMixin
+
+
+class EventLookupView(OnlyForAdminsNoRedirectMixin,
+ autocomplete.Select2QuerySetView):
+ def get_queryset(self):
+ results = models.Event.objects.all()
+
+ if self.q:
+ results = results.filter(slug__icontains=self.q)
+
+ return results
+
+
+class TTTEventLookupView(OnlyForAdminsNoRedirectMixin,
+ autocomplete.Select2QuerySetView):
+ def get_queryset(self):
+ results = models.Event.objects.filter(tags__name='TTT')
+
+ if self.q:
+ results = results.filter(slug__icontains=self.q)
+
+ return results
+
+
+class OrganizationLookupView(OnlyForAdminsNoRedirectMixin,
+ autocomplete.Select2QuerySetView):
+ def get_queryset(self):
+ results = models.Organization.objects.all()
+
+ if self.q:
+ results = results.filter(
+ Q(domain__icontains=self.q) | Q(fullname__icontains=self.q)
+ )
+
+ return results
+
+
+class PersonLookupView(OnlyForAdminsNoRedirectMixin,
+ autocomplete.Select2QuerySetView):
+ def get_queryset(self):
+ results = models.Person.objects.all()
+
+ if self.q:
+ filters = [
+ Q(personal__icontains=self.q),
+ Q(family__icontains=self.q),
+ Q(email__icontains=self.q),
+ Q(username__icontains=self.q)
+ ]
+
+ # split query into first and last names
+ tokens = re.split('\s+', self.q)
+ if len(tokens) == 2:
+ name1, name2 = tokens
+ complex_q = (
+ Q(personal__icontains=name1) & Q(family__icontains=name2)
+ ) | (
+ Q(personal__icontains=name2) & Q(family__icontains=name1)
+ )
+ filters.append(complex_q)
+
+ # this is brilliant: it applies OR to all search filters
+ results = results.filter(reduce(operator.or_, filters))
+
+ return results
+
+
+class AdminLookupView(OnlyForAdminsNoRedirectMixin,
+ autocomplete.Select2QuerySetView):
+ """The same as PersonLookup, but allows only to select administrators.
+
+ Administrator is anyone with superuser power or in "administrators" group.
+ """
+
+ def get_queryset(self):
+ admin_group = Group.objects.get(name='administrators')
+ results = models.Person.objects.filter(
+ Q(is_superuser=True) | Q(groups__in=[admin_group])
+ )
+
+ if self.q:
+ results = results.filter(
+ Q(personal__icontains=self.q) |
+ Q(family__icontains=self.q) |
+ Q(email__icontains=self.q) |
+ Q(username__icontains=self.q)
+ )
+
+ return results
+
+
+class AirportLookupView(OnlyForAdminsNoRedirectMixin,
+ autocomplete.Select2QuerySetView):
+ def get_queryset(self):
+ results = models.Airport.objects.all()
+
+ if self.q:
+ results = results.filter(
+ Q(iata__icontains=self.q) | Q(fullname__icontains=self.q)
+ )
+
+ return results
+
+
+class LanguageLookupView(OnlyForAdminsNoRedirectMixin,
+ autocomplete.Select2QuerySetView):
+ def dispatch(self, request, *args, **kwargs):
+ self.subtag = 'subtag' in request.GET.keys()
+ return super().dispatch(request, *args, **kwargs)
+
+ def get_queryset(self):
+ results = models.Language.objects.all()
+
+ if self.q:
+ results = results.filter(
+ Q(name__icontains=self.q) | Q(subtag__icontains=self.q)
+ )
+
+ if self.subtag:
+ return results.filter(subtag__iexact=self.q)
+
+ results = results.annotate(person_count=Count('person')) \
+ .order_by('-person_count')
+
+ return results
+
+
+# trainees lookup?
+
+
+urlpatterns = [
+ url(r'^events/$', EventLookupView.as_view(), name='event-lookup'),
+ url(r'^ttt_events/$', TTTEventLookupView.as_view(), name='ttt-event-lookup'),
+ url(r'^organizations/$', OrganizationLookupView.as_view(), name='organization-lookup'),
+ url(r'^persons/$', PersonLookupView.as_view(), name='person-lookup'),
+ url(r'^admins/$', AdminLookupView.as_view(), name='admin-lookup'),
+ url(r'^airports/$', AirportLookupView.as_view(), name='airport-lookup'),
+ url(r'^languages/$', LanguageLookupView.as_view(), name='language-lookup'),
+]
diff --git a/pool/shard009/Python/0083359_test_pin_search.py b/pool/shard009/Python/0083359_test_pin_search.py
new file mode 100644
index 0000000000000000000000000000000000000000..b9c4470d2c243c7873aaa2ca21a32edca82599d6
--- /dev/null
+++ b/pool/shard009/Python/0083359_test_pin_search.py
@@ -0,0 +1,18 @@
+# -*- coding: utf-8 -*-
+
+# The MIT License (MIT) - Copyright (c) 2016-2021 Dave Vandenbout.
+
+import pytest
+
+from skidl import Part, Pin
+
+from .setup_teardown import setup_function, teardown_function
+
+
+def test_pin_search_1():
+ codec = Part("xess.lib", "ak4520a")
+ bidir = codec.get_pins(func=Pin.BIDIR)
+ pwrin = codec.get_pins(func=Pin.PWRIN)
+ assert len(bidir) == 24
+ assert len(pwrin) == 4
+ assert len(bidir) + len(pwrin) == len(codec)
diff --git a/pool/shard009/Python/0083360_amber.py b/pool/shard009/Python/0083360_amber.py
new file mode 100644
index 0000000000000000000000000000000000000000..cd0e49ce3ff6ff1d3a4465cdfb97d780c8ddf55b
--- /dev/null
+++ b/pool/shard009/Python/0083360_amber.py
@@ -0,0 +1,49 @@
+from __future__ import print_function, absolute_import, division
+from future.builtins import *
+from future import standard_library
+standard_library.install_aliases()
+
+# Copyright 2017 Autodesk Inc.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in 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 moldesign as mdt
+
+from .. import data
+from ..utils import exports
+from . import TLeapForcefield
+
+
+@exports
+class TLeapLib(TLeapForcefield):
+ """ A forcefield from TLeap's library
+ """
+ def __init__(self, *ffnames):
+ self.names = ffnames
+ sourcelines = ['source %s' % data.AMBER_LEAPRC[ffn] for ffn in ffnames]
+ super().__init__(sourcelines)
+
+ def __str__(self):
+ return "TLeap data: %s" % ','.join(self.names)
+
+
+@exports
+class DefaultAmber(TLeapLib):
+ def __init__(self):
+ super().__init__(*data.AMBER_DEFAULT)
+
+
+@exports
+class GAFF2ForceField(TLeapLib):
+ def __init__(self):
+ super().__init__('gaff2')
diff --git a/pool/shard009/Python/0083361_testimonials.py b/pool/shard009/Python/0083361_testimonials.py
new file mode 100644
index 0000000000000000000000000000000000000000..274a027a747edc066173c1e4d48049be7f2245bc
--- /dev/null
+++ b/pool/shard009/Python/0083361_testimonials.py
@@ -0,0 +1,74 @@
+#!/usr/bin/python3
+# testimonials.py by Bill Weinman
+# Copyright (c) 2010 The BearHeart Group, LLC
+# created 2010-04-23
+#
+
+from bwDB import bwDB
+from bwConfig import configFile
+import random
+import os
+
+__version__ = "1.0.1"
+
+g = dict(
+ config_file = 'db.conf',
+ table_name = 'testimonial'
+)
+
+def main():
+ init()
+ db = g['db']
+ idlist = []
+
+ # build a list of ids
+ for r in db.sql_query(' SELECT id FROM {} '.format(g['table_name'])):
+ idlist.append(r[0])
+
+ # get the count of records to display
+ try: count = int(os.environ.get('QUERY_STRING', 3))
+ except ValueError: error("Invalid query string, must be a number")
+ idcount = len(idlist)
+
+ # check that the count is not too big
+ maxcount = idcount // 4
+ if count > maxcount:
+ error('There are {} records in the database. '.format(idcount) +
+ 'For good randomness, you cannot display more than {} at a time.'.format( maxcount )
+ )
+
+ # build the list of random ids
+ result_ids = []
+ while len(result_ids) < count:
+ randindex = random.randint(0, len(idlist) - 1)
+ randid = idlist[randindex]
+ del idlist[randindex] # don't use that one again
+ result_ids += [ randid ]
+
+ # display them
+ for id in result_ids:
+ printrec(id)
+
+def printrec(id):
+ db = g['db']
+ rec = db.getrec(id)
+ print('')
+ print('
{}
'.format(rec['testimonial']))
+ print('
—{}
'.format(rec['byline']))
+ print('
')
+
+
+def init():
+ send_header()
+ g['config'] = configFile(g['config_file']).recs()
+ g['db'] = bwDB(filename = g['config']['db'], table = g['table_name'])
+
+def send_header():
+ print('Content-type: text/html\n\n', end = '')
+
+def error(e):
+ print(e)
+ exit(0)
+
+if __name__ == "__main__": main()
+
diff --git a/pool/shard009/Python/0083362_RectangularDetectorTest.py b/pool/shard009/Python/0083362_RectangularDetectorTest.py
new file mode 100644
index 0000000000000000000000000000000000000000..7af401d2990601f7f45c0bec45cce04481ea3c7b
--- /dev/null
+++ b/pool/shard009/Python/0083362_RectangularDetectorTest.py
@@ -0,0 +1,41 @@
+# Mantid Repository : https://github.com/mantidproject/mantid
+#
+# Copyright © 2018 ISIS Rutherford Appleton Laboratory UKRI,
+# NScD Oak Ridge National Laboratory, European Spallation Source
+# & Institut Laue - Langevin
+# SPDX - License - Identifier: GPL - 3.0 +
+from __future__ import (absolute_import, division, print_function)
+
+import unittest
+from mantid.geometry import *
+from testhelpers import can_be_instantiated, WorkspaceCreationHelper
+
+class RectangularDetectorTest(unittest.TestCase):
+
+ def test_RectangularDetector_cannot_be_instantiated(self):
+ self.assertFalse(can_be_instantiated(RectangularDetector))
+
+ def test_RectangularDetector_has_expected_attributes(self):
+ attrs = dir(RectangularDetector)
+ expected_attrs = ['idfillbyfirst_y','idstart', 'idstep','idstepbyrow', 'maxDetectorID', 'minDetectorID', 'xpixels', 'xsize', 'xstart', 'xstep', 'ypixels', 'ysize', 'ystart', 'ystep','type','nelements']
+ for att in expected_attrs:
+ self.assertTrue(att in attrs)
+
+ def test_RectangularDetector_getattributes(self):
+ testws = WorkspaceCreationHelper.create2DWorkspaceWithRectangularInstrument(3,5,5)
+ i = testws.getInstrument()
+ self.assertEquals(i[2].getName(),'bank3')
+ self.assertEquals(i[2][2].getName(),'bank3(x=2)')
+ self.assertEquals(i[2][2][2].getName(),'bank3(2,2)')
+ self.assertEquals(i[2].nelements(),5)
+ self.assertEquals(i[2].xstart()+i[2].xstep()*i[2].xpixels(),0.04)
+ self.assertEquals(i[1].ystart()+i[1].ystep()*i[1].ypixels(),0.04)
+ self.assertEquals(i[0].xsize(),0.04)
+ self.assertEquals(i[2].idstart(),75)
+ self.assertEquals(i[0].idstep(),1)
+ self.assertEquals(i[1].idstepbyrow(),5)
+ self.assertEquals(i[1].maxDetectorID(),74)
+ self.assertEquals(i[1].minDetectorID(),50)
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/pool/shard009/Python/0083363_test_job.py b/pool/shard009/Python/0083363_test_job.py
new file mode 100644
index 0000000000000000000000000000000000000000..6008690e02f6a12cbc6be22092bf9adc03017484
--- /dev/null
+++ b/pool/shard009/Python/0083363_test_job.py
@@ -0,0 +1,173 @@
+import time
+import os
+
+import ray
+from ray.job_config import JobConfig
+from ray.test_utils import (
+ run_string_as_driver,
+ run_string_as_driver_nonblocking,
+ wait_for_condition,
+ wait_for_num_actors,
+)
+
+
+def test_job_gc(call_ray_start):
+ address = call_ray_start
+
+ ray.init(address=address)
+ driver = """
+import ray
+
+ray.init(address="{}")
+
+@ray.remote
+class Actor:
+ def __init__(self):
+ pass
+
+_ = Actor.remote()
+""".format(address)
+
+ p = run_string_as_driver_nonblocking(driver)
+ # Wait for actor to be created
+ wait_for_num_actors(1)
+
+ actor_table = ray.state.actors()
+ assert len(actor_table) == 1
+
+ job_table = ray.state.jobs()
+ assert len(job_table) == 2 # dash
+
+ # Kill the driver process.
+ p.kill()
+ p.wait()
+
+ def actor_finish():
+ actor_table = ray.state.actors()
+ if (len(actor_table) == 0):
+ return True
+ else:
+ return False
+
+ wait_for_condition(actor_finish)
+
+
+def test_job_gc_with_detached_actor(call_ray_start):
+ address = call_ray_start
+
+ ray.init(address=address, namespace="")
+ driver = """
+import ray
+
+ray.init(address="{}", namespace="")
+
+@ray.remote
+class Actor:
+ def __init__(self):
+ pass
+
+ def value(self):
+ return 1
+
+_ = Actor.options(lifetime="detached", name="DetachedActor").remote()
+# Make sure the actor is created before the driver exits.
+ray.get(_.value.remote())
+""".format(address)
+
+ p = run_string_as_driver_nonblocking(driver)
+ # Wait for actor to be created
+ wait_for_num_actors(1, ray.gcs_utils.ActorTableData.ALIVE)
+
+ actor_table = ray.state.actors()
+ assert len(actor_table) == 1
+
+ job_table = ray.state.jobs()
+ assert len(job_table) == 2 # dash
+
+ # Kill the driver process.
+ p.kill()
+ p.wait()
+
+ detached_actor = ray.get_actor("DetachedActor")
+ assert ray.get(detached_actor.value.remote()) == 1
+
+
+def test_job_timestamps(ray_start_regular):
+ driver_template = """
+import ray
+from time import sleep
+
+ray.init(address="{}")
+
+print("My job id: ", str(ray.get_runtime_context().job_id))
+
+{}
+ray.shutdown()
+ """
+
+ non_hanging = driver_template.format(ray_start_regular["redis_address"],
+ "sleep(1)")
+ hanging_driver = driver_template.format(ray_start_regular["redis_address"],
+ "sleep(60)")
+
+ out = run_string_as_driver(non_hanging)
+ p = run_string_as_driver_nonblocking(hanging_driver)
+ # The nonblocking process needs time to connect.
+ time.sleep(1)
+
+ jobs = list(ray.state.jobs())
+ jobs.sort(key=lambda x: x["JobID"])
+
+ driver = jobs[0]
+ finished = jobs[1]
+ running = jobs[2]
+
+ # The initial driver timestamp/start time go down a different code path.
+ assert driver["Timestamp"] == driver["StartTime"]
+ assert finished["Timestamp"] == finished["EndTime"]
+ assert running["Timestamp"] == running["StartTime"]
+
+ assert finished["EndTime"] > finished["StartTime"] > 0, out
+ lapsed = finished["EndTime"] - finished["StartTime"]
+ assert 0 < lapsed < 2000, f"Job should've taken ~1s, {finished}"
+
+ assert running["StartTime"] > 0
+ assert running["EndTime"] == 0
+
+ p.kill()
+ # Give the second job time to clean itself up.
+ time.sleep(1)
+
+ jobs = list(ray.state.jobs())
+ jobs.sort(key=lambda x: x["JobID"])
+
+ # jobs[0] is the test case driver.
+ finished = jobs[1]
+ prev_running = jobs[2]
+
+ assert finished["EndTime"] > finished["StartTime"] > 0, f"{finished}"
+ assert finished["EndTime"] == finished["Timestamp"]
+ lapsed = finished["EndTime"] - finished["StartTime"]
+ assert 0 < lapsed < 2000, f"Job should've taken ~1s {finished}"
+
+ assert prev_running["EndTime"] > prev_running["StartTime"] > 0
+
+
+def test_config_metadata(shutdown_only):
+ job_config = JobConfig(metadata={"abc": "xyz"})
+ job_config.set_metadata("xyz", "abc")
+
+ ray.init(job_config=job_config)
+
+ from_worker = ray.worker.global_worker.core_worker.get_job_config()
+
+ assert dict(from_worker.metadata) == job_config.metadata
+
+
+if __name__ == "__main__":
+ import pytest
+ import sys
+ # Make subprocess happy in bazel.
+ os.environ["LC_ALL"] = "en_US.UTF-8"
+ os.environ["LANG"] = "en_US.UTF-8"
+ sys.exit(pytest.main(["-v", __file__]))
diff --git a/pool/shard009/Python/0083366_active_learning.py b/pool/shard009/Python/0083366_active_learning.py
new file mode 100644
index 0000000000000000000000000000000000000000..769e9df50af79059d4c6e6a1efcfd26d71a481d1
--- /dev/null
+++ b/pool/shard009/Python/0083366_active_learning.py
@@ -0,0 +1,73 @@
+from model import *
+
+# ------------------------------------------------------------------ helpers and mgmt
+def get_feed_dic_obs(obs):
+ # needing to create all the nessisary feeds
+ obs_x = []
+ obs_y = []
+ obs_tf = []
+
+ for _ in range(OBS_SIZE):
+ obs_x.append(np.zeros([N_BATCH,L]))
+ obs_y.append(np.zeros([N_BATCH,L]))
+ obs_tf.append(np.zeros([N_BATCH,2]))
+
+ num_obs = len(obs)
+ for ob_idx in range(num_obs):
+ ob_coord, ob_lab = obs[ob_idx]
+ ob_x, ob_y = vectorize(ob_coord)
+ obs_x[ob_idx] = np.tile(ob_x, [50,1])
+ obs_y[ob_idx] = np.tile(ob_y, [50,1])
+ obs_tf[ob_idx] = np.tile(ob_lab, [50,1])
+
+ feed_dic = dict(zip(ph_obs_x + ph_obs_y + ph_obs_tf,
+ obs_x + obs_y + obs_tf))
+ return feed_dic
+
+def get_inv(sess, obs):
+ num_obs = len(obs)
+ return get_inv_tr(sess, obs)[num_obs]
+
+def get_inv_tr(sess, obs):
+ num_obs = len(obs)
+ feed_dic = get_feed_dic_obs(obs)
+ x_invss = [np.argmax(x[0]) for x in sess.run(x_invs, feed_dict = feed_dic)]
+ y_invss = [np.argmax(x[0]) for x in sess.run(y_invs, feed_dict = feed_dic)]
+ return zip(x_invss, y_invss)
+
+def get_most_confuse(sess, obs):
+ feed_dic = get_feed_dic_obs(obs)
+ key_ob = len(obs)
+
+ all_querys = []
+ for i in range(L):
+ for j in range(L):
+ all_querys.append((i,j))
+
+ most_conf = (1.0, None)
+
+ for q in all_querys:
+ q_x, q_y = vectorize(q)
+ feed_dic[ph_new_ob_x] = np.tile(q_x, [N_BATCH,1])
+ feed_dic[ph_new_ob_y] = np.tile(q_y, [N_BATCH,1])
+ pred_tf = sess.run(query_preds, feed_dict=feed_dic)[key_ob][0]
+ most_conf = min(most_conf, (abs(pred_tf[0] - pred_tf[1]), q))
+
+ return most_conf[1]
+
+def get_random_inv(sess, query):
+ ob_pts = [(np.random.randint(0, L), np.random.randint(0,L)) for _ in range(OBS_SIZE)]
+ obs = [(op, query(op)) for op in ob_pts]
+ return zip([None] + obs, get_inv_tr(sess, obs))
+
+def get_active_inv(sess, query):
+ obs = []
+
+ for i in range(OBS_SIZE):
+ try_inv = get_inv(sess, obs)
+ most_conf = get_most_confuse(sess, obs)
+ print "chosen observation ", most_conf
+ obs.append((most_conf, query(most_conf)))
+
+ return zip([None] + obs, get_inv_tr(sess, obs))
+
diff --git a/pool/shard009/Python/0083369_omega_virus.py b/pool/shard009/Python/0083369_omega_virus.py
new file mode 100644
index 0000000000000000000000000000000000000000..0067cde17cfb9b6e6eba39c509bc1b9813441e14
--- /dev/null
+++ b/pool/shard009/Python/0083369_omega_virus.py
@@ -0,0 +1,226 @@
+#!/usr/bin/python
+
+'''
+# Insert docopt user help menu here?
+
+# Good resource for game mechanics w/o having to get game manual :D
+# https://boardgamegeek.com/thread/372462/omega-virus-human-scum-review
+
+# End docopt
+'''
+
+# Lets define some imports! :D
+import sys
+import random
+from random import randint
+import time
+
+
+def difficulty():
+ # Define the length of the game (these values are probably wrong :D Need to check rulebook.
+ # 0 - 30 Minutes
+ # 1 - 20 Minutes
+ # 2 - 15 Minutes
+ # 3 - Custom -- Do we -REALLY- want to do this?
+
+ usrDiff = raw_input("Select a difficulty [0,1 or 2]: ")
+
+ if usrDiff == "0":
+ gameDiff = 30
+
+ elif usrDiff == "1":
+ gameDiff = 20
+
+ elif usrDiff == "2":
+ gameDiff = 15
+
+ elif usrDiff == "4":
+ gameDiff = raw_input("Fine... pick two numbers then: ")
+
+ else:
+ print("Don't like those options? NO GAME 4 U!")
+ quit()
+
+ return gameDiff
+
+def numPlayers():
+ # In the orginal game, the Computer asks each player to enter their secret code at the beginning of the game.
+ # This then defines which colors are active. There may be a simpler way of doing this though...
+
+
+
+
+ return playerCount
+
+def timer():
+ run = raw_input("Start? > ")
+ mins = gameDiff
+ # Only run if the user types in "start"
+ if run == "start":
+ # When 9 minutes are left one sector is shut down, and every 3 minutes after this another is shut down.
+ while mins != 9:
+ # Keep playing
+ # Sleep for a minute
+ time.sleep(60)
+
+ sectorList = ['blue', 'green', 'red', 'yellow']
+ shutdown = random.choice(sectorList)
+ print(shutdown + "Sector Shutdown!")
+
+ # Build new sector list
+ sectorList == sectorList - shutdown
+
+ # Move all players to docking bay of random sector on the new list
+ teleport = random.choice(sectorList)
+
+ # Wash, rinse, repeat until: Virus wins (all sectors shutdown) OR Players win (kill virus)
+ # I KNOW there is a better way to loop this...
+ '''
+ while mins != 6:
+ # Keep playing
+ # Sleep for a minute
+ time.sleep(60)
+
+ sectorList = ['blue', 'green', 'red', 'yellow']
+ shutdown = random.choice(sectorList)
+ print(shutdown + "Sector Shutdown!")
+
+ # Build new sector list
+ sectorList == sectorList - shutdown
+
+ # Move all players to docking bay of random sector on the new list
+ teleport = random.choice(sectorList
+ '''
+
+
+# Commenting this out because we -probably- don't need it.
+'''
+def sectors():
+ # Docking Bays (Blue, Green, Red, Yellow)
+ # Blue Rooms
+ # Green Rooms
+ # Red Rooms
+ # Yellow Rooms
+'''
+
+
+def roomList():
+ # Docking Bays (Blue, Green, Red, Yellow)
+ # List of rooms
+ # Green (open rooms)
+ # Blue (requires blue key)
+ # Red (requires red key)
+ # Yellow (requires yellow key)
+
+def roomContents():
+ # Each room can have one of:
+ # 1. An ADV
+ # 2. An access card
+ # 3. A Probe (more on this in a little bit)
+ # 4. A hazard
+ # 5. The virus (presumably chilling out)
+ # 6. Nothing at all
+
+def items():
+ # Four of each, to be distributed across the map.
+ # Access keys (Blue, Red, Yellow)
+ # Decoder - yellow
+ # Disruptor - blue
+ # Negatron - red
+ # Probe
+
+def playerBag():
+ # A place to define inventory.
+ def bluePlayer():
+ blueKey = boolean
+ redKey = boolean
+ yellowKey = boolean
+ blueProbe = boolean
+ decoder = boolean
+ disruptor = boolean
+ negatron = boolean
+ return blueInventory
+
+ def greenPlayer():
+ blueKey = boolean
+ redKey = boolean
+ yellowKey = boolean
+ blueProbe = boolean
+ decoder = boolean
+ disruptor = boolean
+ negatron = boolean
+ return blueInventory
+
+ def redPlayer():
+ blueKey = boolean
+ redKey = boolean
+ yellowKey = boolean
+ blueProbe = boolean
+ decoder = boolean
+ disruptor = boolean
+ negatron = boolean
+ return blueInventory
+
+ def yellowPlayer():
+ blueKey = boolean
+ redKey = boolean
+ yellowKey = boolean
+ blueProbe = boolean
+ decoder = boolean
+ disruptor = boolean
+ negatron = boolean
+ return blueInventory
+
+def probes():
+ # Probes can move, explore and be attacked just like players. However they cannot attack themselves.
+ # Blue
+ # Green
+ # Red
+ # Yellow
+
+def rng():
+ # Random number generator ranging from 0-2
+ rng = randint(0,2)
+ return rng
+
+def secretCode():
+ # Secret codes let players know where the virus is provided:
+ # a) They enter a room where the virus is
+ # b) They do not have all three weapons
+ # c) Should we let probes find the virus?
+
+def userInput():
+ # We will need a way for players to input numbers (0,1,2)
+ # This is for room numbers, secret codes, and combat
+ blueCode = raw_input("Blue player enter secret code: ")
+ greenCode = raw_input("Green player enter secret code: ")
+ redCode = raw_input("Red player enter secret code: ")
+ yellowCode = raw_input("Yellow player enter secret code: ")
+
+def combat():
+ # Combat includes, players attacking one another (or their drones) as well as attaking the virus.
+ # Defender picks a value (0,1 or 2), and the Attacker picks one as well.
+ # If both match, then the attacker wins. I.e. the Virus is killed, the player looses an item (at random),
+ # or the drone dies.
+
+def phrasing():
+ # This is a placeholder for all of the phrases that are used throuout the game.
+ # --Virus--
+ # "You Human Scum!"
+ # "Which room?"
+ # "Help me! Help me!" (Mockingly)
+ # "Blue Sector, Shut Down."
+ # "Green Sector, Shut Down."
+ # "Red Sector, Shut Down."
+ # "Yellow Sector, Shut Down."
+ # "You have [time] minutes until -I- take over!"
+ # "Mwahahaha!"
+ # "You missed!"
+ # "You killed me! You, human... scum."
+ # "I win!"
+ # "[player_color] is attacking [player_color] hahaha"
+ # "[player_color] is attacking [player_color] done how amusing"
+ #
+ # --Computer--
+ # "[player_color] enter secret code"
+ # "[player_color] help me"
diff --git a/pool/shard009/Python/0083371_debconf.py b/pool/shard009/Python/0083371_debconf.py
new file mode 100644
index 0000000000000000000000000000000000000000..468f0b5725e6bf5e5e143ca80979252045b31dde
--- /dev/null
+++ b/pool/shard009/Python/0083371_debconf.py
@@ -0,0 +1,191 @@
+#!/usr/bin/python
+# -*- coding: utf-8 -*-
+
+"""
+Ansible module to configure .deb packages.
+(c) 2014, Brian Coca
+
+This file is part of Ansible
+
+Ansible is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+Ansible 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 Ansible. If not, see .
+"""
+
+DOCUMENTATION = '''
+---
+module: debconf
+short_description: Configure a .deb package
+description:
+ - Configure a .deb package using debconf-set-selections. Or just query
+ existing selections.
+version_added: "1.6"
+notes:
+ - This module requires the command line debconf tools.
+ - A number of questions have to be answered (depending on the package).
+ Use 'debconf-show ' on any Debian or derivative with the package
+ installed to see questions/settings available.
+ - Some distros will always record tasks involving the setting of passwords as changed. This is due to debconf-get-selections masking passwords.
+requirements: [ debconf, debconf-utils ]
+options:
+ name:
+ description:
+ - Name of package to configure.
+ required: true
+ default: null
+ aliases: ['pkg']
+ question:
+ description:
+ - A debconf configuration setting
+ required: false
+ default: null
+ aliases: ['setting', 'selection']
+ vtype:
+ description:
+ - The type of the value supplied.
+ - C(seen) was added in 2.2.
+ required: false
+ default: null
+ choices: [string, password, boolean, select, multiselect, note, error, title, text, seen]
+ value:
+ description:
+ - Value to set the configuration to
+ required: false
+ default: null
+ aliases: ['answer']
+ unseen:
+ description:
+ - Do not set 'seen' flag when pre-seeding
+ required: false
+ default: False
+author: "Brian Coca (@bcoca)"
+
+'''
+
+EXAMPLES = '''
+# Set default locale to fr_FR.UTF-8
+- debconf:
+ name: locales
+ question: locales/default_environment_locale
+ value: fr_FR.UTF-8
+ vtype: select
+
+# set to generate locales:
+- debconf:
+ name: locales
+ question: locales/locales_to_be_generated
+ value: en_US.UTF-8 UTF-8, fr_FR.UTF-8 UTF-8
+ vtype: multiselect
+
+# Accept oracle license
+- debconf:
+ name: oracle-java7-installer
+ question: shared/accepted-oracle-license-v1-1
+ value: true
+ vtype: select
+
+# Specifying package you can register/return the list of questions and current values
+- debconf:
+ name: tzdata
+'''
+
+def get_selections(module, pkg):
+ cmd = [module.get_bin_path('debconf-show', True), pkg]
+ rc, out, err = module.run_command(' '.join(cmd))
+
+ if rc != 0:
+ module.fail_json(msg=err)
+
+ selections = {}
+
+ for line in out.splitlines():
+ (key, value) = line.split(':', 1)
+ selections[ key.strip('*').strip() ] = value.strip()
+
+ return selections
+
+
+def set_selection(module, pkg, question, vtype, value, unseen):
+
+ setsel = module.get_bin_path('debconf-set-selections', True)
+ cmd = [setsel]
+ if unseen:
+ cmd.append('-u')
+
+ if vtype == 'boolean':
+ if value == 'True':
+ value = 'true'
+ elif value == 'False':
+ value = 'false'
+ data = ' '.join([pkg, question, vtype, value])
+
+ return module.run_command(cmd, data=data)
+
+def main():
+
+ module = AnsibleModule(
+ argument_spec = dict(
+ name = dict(required=True, aliases=['pkg'], type='str'),
+ question = dict(required=False, aliases=['setting', 'selection'], type='str'),
+ vtype = dict(required=False, type='str', choices=['string', 'password', 'boolean', 'select', 'multiselect', 'note', 'error', 'title', 'text', 'seen']),
+ value = dict(required=False, type='str', aliases=['answer']),
+ unseen = dict(required=False, type='bool'),
+ ),
+ required_together = ( ['question','vtype', 'value'],),
+ supports_check_mode=True,
+ )
+
+ #TODO: enable passing array of options and/or debconf file from get-selections dump
+ pkg = module.params["name"]
+ question = module.params["question"]
+ vtype = module.params["vtype"]
+ value = module.params["value"]
+ unseen = module.params["unseen"]
+
+ prev = get_selections(module, pkg)
+
+ changed = False
+ msg = ""
+
+ if question is not None:
+ if vtype is None or value is None:
+ module.fail_json(msg="when supplying a question you must supply a valid vtype and value")
+
+ if not question in prev or prev[question] != value:
+ changed = True
+
+ if changed:
+ if not module.check_mode:
+ rc, msg, e = set_selection(module, pkg, question, vtype, value, unseen)
+ if rc:
+ module.fail_json(msg=e)
+
+ curr = { question: value }
+ if question in prev:
+ prev = {question: prev[question]}
+ else:
+ prev[question] = ''
+ if module._diff:
+ after = prev.copy()
+ after.update(curr)
+ diff_dict = {'before': prev, 'after': after}
+ else:
+ diff_dict = {}
+
+ module.exit_json(changed=changed, msg=msg, current=curr, previous=prev, diff=diff_dict)
+
+ module.exit_json(changed=changed, msg=msg, current=prev)
+
+# import module snippets
+from ansible.module_utils.basic import *
+
+main()
diff --git a/pool/shard009/Python/0083372_frequency_map_test.py b/pool/shard009/Python/0083372_frequency_map_test.py
new file mode 100644
index 0000000000000000000000000000000000000000..b7f6c26f20c27bb9d0a8ed4397831f89d1a1c4f3
--- /dev/null
+++ b/pool/shard009/Python/0083372_frequency_map_test.py
@@ -0,0 +1,23 @@
+__author__ = 'yue'
+
+
+import unittest
+import frequency_map as fmap
+
+
+class TestFrequencyMap(unittest.TestCase):
+
+ def test_ctor(self):
+ fm = fmap.FrequencyMap('aaabbc')
+ self.assertEqual(3, fm.dictionary['a'])
+ self.assertEqual(2, fm.dictionary['b'])
+ self.assertEqual(1, fm.dictionary['c'])
+
+ def test_frequency_to_bytes(self):
+ self.assertEqual([0x01], fmap.FrequencyMap.frequency_to_bytes(0x01))
+ self.assertEqual([0xab, 0xcd], fmap.FrequencyMap.frequency_to_bytes(0xabcd))
+ self.assertEqual([0x0b, 0xcd], fmap.FrequencyMap.frequency_to_bytes(0xbcd))
+
+ def test_str(self):
+ fm = fmap.FrequencyMap('aaabbc')
+ self.assertEqual(12, len(str(fm)))
diff --git a/pool/shard009/Python/0083374_auto_20200504_134507_39a2a2285c4e.py b/pool/shard009/Python/0083374_auto_20200504_134507_39a2a2285c4e.py
new file mode 100644
index 0000000000000000000000000000000000000000..8ace5f768b83efd95d484240599543f97cadb756
--- /dev/null
+++ b/pool/shard009/Python/0083374_auto_20200504_134507_39a2a2285c4e.py
@@ -0,0 +1,73 @@
+# 2020-05-04 13:45:07.486536
+from alembic import op
+import sqlalchemy as sa
+
+
+revision = '39a2a2285c4e'
+down_revision = None
+branch_labels = None
+depends_on = None
+
+
+def upgrade():
+ # ### commands auto generated by Alembic - please adjust! ###
+ op.create_table('groups',
+ sa.Column('id', sa.BigInteger(), nullable=False),
+ sa.Column('name', sa.String(), nullable=False),
+ sa.Column('locale', sa.String(), nullable=True),
+ sa.PrimaryKeyConstraint('id')
+ )
+ op.create_table('users',
+ sa.Column('id', sa.BigInteger(), nullable=False),
+ sa.Column('login', sa.String(), nullable=True),
+ sa.Column('name', sa.String(), nullable=False),
+ sa.Column('is_mute_enabled', sa.Boolean(), nullable=False),
+ sa.Column('is_known', sa.Boolean(), nullable=False),
+ sa.Column('locale', sa.String(), nullable=True),
+ sa.PrimaryKeyConstraint('id')
+ )
+ op.create_table('group_members',
+ sa.Column('user_id', sa.BigInteger(), nullable=True),
+ sa.Column('group_id', sa.BigInteger(), nullable=True),
+ sa.ForeignKeyConstraint(['group_id'], ['groups.id'], onupdate='CASCADE', ondelete='CASCADE'),
+ sa.ForeignKeyConstraint(['user_id'], ['users.id'], onupdate='CASCADE', ondelete='CASCADE')
+ )
+ op.create_table('pending_actions',
+ sa.Column('id', sa.BigInteger().with_variant(sa.Integer(), 'sqlite'), autoincrement=True, nullable=False),
+ sa.Column('user_id', sa.BigInteger(), nullable=False),
+ sa.Column('chat_id', sa.BigInteger(), nullable=False),
+ sa.Column('action', sa.String(), nullable=False),
+ sa.ForeignKeyConstraint(['user_id'], ['users.id'], onupdate='CASCADE', ondelete='CASCADE'),
+ sa.PrimaryKeyConstraint('id')
+ )
+ op.create_table('requests',
+ sa.Column('id', sa.BigInteger().with_variant(sa.Integer(), 'sqlite'), autoincrement=True, nullable=False),
+ sa.Column('message_id', sa.BigInteger(), nullable=False),
+ sa.Column('chat_id', sa.BigInteger(), nullable=False),
+ sa.Column('created_at', sa.DateTime(), nullable=False),
+ sa.Column('author_id', sa.BigInteger(), nullable=False),
+ sa.Column('title', sa.String(), nullable=False),
+ sa.ForeignKeyConstraint(['author_id'], ['users.id'], onupdate='CASCADE', ondelete='CASCADE'),
+ sa.PrimaryKeyConstraint('id')
+ )
+ op.create_table('responses',
+ sa.Column('id', sa.BigInteger().with_variant(sa.Integer(), 'sqlite'), autoincrement=True, nullable=False),
+ sa.Column('user_id', sa.BigInteger(), nullable=False),
+ sa.Column('request_id', sa.BigInteger(), nullable=False),
+ sa.Column('answer', sa.BigInteger(), nullable=False),
+ sa.ForeignKeyConstraint(['request_id'], ['requests.id'], onupdate='CASCADE', ondelete='CASCADE'),
+ sa.ForeignKeyConstraint(['user_id'], ['users.id'], onupdate='CASCADE', ondelete='CASCADE'),
+ sa.PrimaryKeyConstraint('id')
+ )
+ # ### end Alembic commands ###
+
+
+def downgrade():
+ # ### commands auto generated by Alembic - please adjust! ###
+ op.drop_table('responses')
+ op.drop_table('requests')
+ op.drop_table('pending_actions')
+ op.drop_table('group_members')
+ op.drop_table('users')
+ op.drop_table('groups')
+ # ### end Alembic commands ###
diff --git a/pool/shard009/Python/0083375_base.py b/pool/shard009/Python/0083375_base.py
new file mode 100644
index 0000000000000000000000000000000000000000..4bf4a6d2332e74cb62000c3bebae253ec4038615
--- /dev/null
+++ b/pool/shard009/Python/0083375_base.py
@@ -0,0 +1,58 @@
+import unittest
+
+from app import create_app
+from app.database import db
+from app.profile.models import User, Publisher, PublisherUser, UserRoleEnum
+from app.package.models import Package
+import app.logic as logic
+
+
+def make_fixtures(app, package, publisher, user_id):
+ with app.app_context():
+ user = User(
+ id=user_id,
+ email='test@test.com',
+ name=publisher,
+ secret='super_secret'
+ )
+ pub = Publisher(name=publisher)
+ pub.packages.append(Package(name=package))
+ association = PublisherUser(role=UserRoleEnum.owner)
+ association.publisher = pub
+ user.publishers.append(association)
+
+ user1 = User(id=2, name='test1',
+ secret='super_secret1', email="test1@test.com")
+ pub1 = Publisher(name='test1')
+ association1 = PublisherUser(role=UserRoleEnum.owner)
+ association1.publisher = pub1
+ user1.publishers.append(association1)
+
+ db.session.add(user)
+ db.session.add(user1)
+ db.session.commit()
+
+def create_test_package(publisher='demo', package='demo-package', descriptor={}, readme=''):
+ user = User(name=publisher, secret='supersecret', email='test@test.com')
+ publisher = Publisher(name=publisher)
+ association = PublisherUser(role=UserRoleEnum.owner)
+ association.publisher = publisher
+ user.publishers.append(association)
+
+ package = Package(name=package, descriptor=descriptor, readme=readme)
+ publisher.packages.append(package)
+
+ db.session.add(user)
+ db.session.commit()
+
+def get_valid_token(username):
+ user = User.query.filter_by(name=username).one()
+ return logic.get_jwt_token(secret=user.secret, username=username)
+
+
+class TestBase(unittest.TestCase):
+ def setup_class(self):
+ db.drop_all()
+ db.create_all()
+ create_test_package()
+
diff --git a/pool/shard009/Python/0083378_generate-seeds.py b/pool/shard009/Python/0083378_generate-seeds.py
new file mode 100644
index 0000000000000000000000000000000000000000..37188381d0f75b2462795a1eac409f136f51b27e
--- /dev/null
+++ b/pool/shard009/Python/0083378_generate-seeds.py
@@ -0,0 +1,135 @@
+#!/usr/bin/python
+# Copyright (c) 2014 Wladmir J. van der Laan
+# Distributed under the MIT software license, see the accompanying
+# file COPYING or http://www.opensource.org/licenses/mit-license.php.
+'''
+Script to generate list of seed nodes for chainparams.cpp.
+
+This script expects two text files in the directory that is passed as an
+argument:
+
+ nodes_main.txt
+ nodes_test.txt
+
+These files must consist of lines in the format
+
+
+ :
+ []
+ []:
+ .onion
+ 0xDDBBCCAA (IPv4 little-endian old pnSeeds format)
+
+The output will be two data structures with the peers in binary format:
+
+ static SeedSpec6 pnSeed6_main[]={
+ ...
+ }
+ static SeedSpec6 pnSeed6_test[]={
+ ...
+ }
+
+These should be pasted into `src/chainparamsseeds.h`.
+'''
+from __future__ import print_function, division
+from base64 import b32decode
+from binascii import a2b_hex
+import sys, os
+import re
+
+# ipv4 in ipv6 prefix
+pchIPv4 = bytearray([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff])
+# tor-specific ipv6 prefix
+pchOnionCat = bytearray([0xFD,0x87,0xD8,0x7E,0xEB,0x43])
+
+def name_to_ipv6(addr):
+ if len(addr)>6 and addr.endswith('.onion'):
+ vchAddr = b32decode(addr[0:-6], True)
+ if len(vchAddr) != 16-len(pchOnionCat):
+ raise ValueError('Invalid onion %s' % s)
+ return pchOnionCat + vchAddr
+ elif '.' in addr: # IPv4
+ return pchIPv4 + bytearray((int(x) for x in addr.split('.')))
+ elif ':' in addr: # IPv6
+ sub = [[], []] # prefix, suffix
+ x = 0
+ addr = addr.split(':')
+ for i,comp in enumerate(addr):
+ if comp == '':
+ if i == 0 or i == (len(addr)-1): # skip empty component at beginning or end
+ continue
+ x += 1 # :: skips to suffix
+ assert(x < 2)
+ else: # two bytes per component
+ val = int(comp, 16)
+ sub[x].append(val >> 8)
+ sub[x].append(val & 0xff)
+ nullbytes = 16 - len(sub[0]) - len(sub[1])
+ assert((x == 0 and nullbytes == 0) or (x == 1 and nullbytes > 0))
+ return bytearray(sub[0] + ([0] * nullbytes) + sub[1])
+ elif addr.startswith('0x'): # IPv4-in-little-endian
+ return pchIPv4 + bytearray(reversed(a2b_hex(addr[2:])))
+ else:
+ raise ValueError('Could not parse address %s' % addr)
+
+def parse_spec(s, defaultport):
+ match = re.match('\[([0-9a-fA-F:]+)\](?::([0-9]+))?$', s)
+ if match: # ipv6
+ host = match.group(1)
+ port = match.group(2)
+ else:
+ (host,_,port) = s.partition(':')
+
+ if not port:
+ port = defaultport
+ else:
+ port = int(port)
+
+ host = name_to_ipv6(host)
+
+ return (host,port)
+
+def process_nodes(g, f, structname, defaultport):
+ g.write('static SeedSpec6 %s[] = {\n' % structname)
+ first = True
+ for line in f:
+ comment = line.find('#')
+ if comment != -1:
+ line = line[0:comment]
+ line = line.strip()
+ if not line:
+ continue
+ if not first:
+ g.write(',\n')
+ first = False
+
+ (host,port) = parse_spec(line, defaultport)
+ hoststr = ','.join(('0x%02x' % b) for b in host)
+ g.write(' {{%s}, %i}' % (hoststr, port))
+ g.write('\n};\n')
+
+def main():
+ if len(sys.argv)<2:
+ print(('Usage: %s ' % sys.argv[0]), file=sys.stderr)
+ exit(1)
+ g = sys.stdout
+ indir = sys.argv[1]
+ g.write('#ifndef H_CHAINPARAMSSEEDS\n')
+ g.write('#define H_CHAINPARAMSSEEDS\n')
+ g.write('/**\n')
+ g.write(' * List of fixed seed nodes for the bitcoin network\n')
+ g.write(' * AUTOGENERATED by share/seeds/generate-seeds.py\n')
+ g.write(' *\n')
+ g.write(' * Each line contains a 16-byte IPv6 address and a port.\n')
+ g.write(' * IPv4 as well as onion addresses are wrapped inside a IPv6 address accordingly.\n')
+ g.write(' */\n')
+ with open(os.path.join(indir,'nodes_main.txt'),'r') as f:
+ process_nodes(g, f, 'pnSeed6_main', 3764)
+ g.write('\n')
+ with open(os.path.join(indir,'nodes_test.txt'),'r') as f:
+ process_nodes(g, f, 'pnSeed6_test', 13764)
+ g.write('#endif\n')
+
+if __name__ == '__main__':
+ main()
+
diff --git a/pool/shard009/Python/0083380_go.py b/pool/shard009/Python/0083380_go.py
new file mode 100644
index 0000000000000000000000000000000000000000..64bbc2e34aa9be967809de777a30f2191329f16c
--- /dev/null
+++ b/pool/shard009/Python/0083380_go.py
@@ -0,0 +1,69 @@
+##
+# Copyright 2014 Ghent University
+#
+# This file is part of EasyBuild,
+# originally created by the HPC team of Ghent University (http://ugent.be/hpc/en),
+# with support of Ghent University (http://ugent.be/hpc),
+# the Flemish Supercomputer Centre (VSC) (https://vscentrum.be/nl/en),
+# the Hercules foundation (http://www.herculesstichting.be/in_English)
+# and the Department of Economy, Science and Innovation (EWI) (http://www.ewi-vlaanderen.be/en).
+#
+# http://github.com/hpcugent/easybuild
+#
+# EasyBuild 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 v2.
+#
+# EasyBuild 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 EasyBuild. If not, see .
+##
+"""
+EasyBuild support for building and installing Go, implemented as an easyblock
+
+@author: Adam DeConinck (NVIDIA)
+@author: Kenneth Hoste (HPC-UGent)
+"""
+import os
+import shutil
+
+from easybuild.easyblocks.generic.configuremake import ConfigureMake
+from easybuild.tools.filetools import rmtree2, run_cmd
+
+class EB_Go(ConfigureMake):
+ """
+ Build Go compiler
+ """
+ def configure_step(self):
+ """No dedicated configure step."""
+ pass
+
+ def build_step(self):
+ """No dedicated build step, building & installing is done in one go."""
+ pass
+
+ def install_step(self):
+ """
+ Execute the all.bash script to build and install the Go compiler,
+ specifying the final installation prefix by setting $GOROOT_FINAL.
+ """
+ srcdir = os.path.join(self.cfg['start_dir'], 'src')
+ try:
+ os.chdir(srcdir)
+ except OSError, err:
+ self.log.error("Failed to move to %s: %s" % (srcdir, err))
+
+ # $GOROOT_FINAL only specifies the location of the final installation, which gets baked into the binaries
+ # the installation itself is *not* done by the all.bash script, that needs to be done manually
+ cmd = "GOROOT_FINAL=%s ./all.bash" % self.installdir
+ run_cmd(cmd, log_all=True, simple=False)
+
+ try:
+ rmtree2(self.installdir)
+ shutil.copytree(self.cfg['start_dir'], self.installdir, symlinks=self.cfg['keepsymlinks'])
+ except OSError, err:
+ self.log.error("Failed to copy installation to %s: %s" % (self.installdir, err))
diff --git a/pool/shard009/Python/0083381_services.py b/pool/shard009/Python/0083381_services.py
new file mode 100644
index 0000000000000000000000000000000000000000..0db7971cdef1cb2bb6be452f618ab2f001e263aa
--- /dev/null
+++ b/pool/shard009/Python/0083381_services.py
@@ -0,0 +1,112 @@
+# -*- coding: utf-8 -*-
+import attr
+
+from cfme.utils.appliance.plugin import AppliancePlugin
+from cfme.utils.appliance.plugin import AppliancePluginException
+from cfme.utils.log import logger_wrap
+from cfme.utils.quote import quote
+from cfme.utils.wait import wait_for
+
+
+class SystemdException(AppliancePluginException):
+ pass
+
+
+@attr.s
+class SystemdService(AppliancePlugin):
+ unit_name = attr.ib(type=str)
+
+ @logger_wrap('SystemdService command runner: {}')
+ def _run_service_command(
+ self,
+ command,
+ expected_exit_code=None,
+ unit_name=None,
+ log_callback=None
+ ):
+ """Wrapper around running the command and raising exception on unexpected code
+
+ Args:
+ command: string command for systemd (stop, start, restart, etc)
+ expected_exit_code: the exit code to expect, otherwise raise
+ unit_name: optional unit name, defaults to self.unit_name attribute
+ log_callback: logger to log against
+
+ Raises:
+ SystemdException: When expected_exit_code is not matched
+ """
+ unit = self.unit_name if unit_name is None else unit_name
+ with self.appliance.ssh_client as ssh:
+ cmd = 'systemctl {} {}'.format(quote(command), quote(unit))
+ log_callback('Running {}'.format(cmd))
+ result = ssh.run_command(cmd,
+ container=self.appliance.ansible_pod_name)
+
+ if expected_exit_code is not None and result.rc != expected_exit_code:
+ # TODO: Bring back address
+ msg = 'Failed to {} {}\nError: {}'.format(
+ command, self.unit_name, result.output)
+ if log_callback:
+ log_callback(msg)
+ else:
+ self.logger.error(msg)
+ raise SystemdException(msg)
+ return result
+
+ def stop(self, log_callback=None):
+ return self._run_service_command(
+ 'stop',
+ expected_exit_code=0,
+ log_callback=log_callback
+ )
+
+ def start(self, log_callback=None):
+ return self._run_service_command(
+ 'start',
+ expected_exit_code=0,
+ log_callback=log_callback
+ )
+
+ def restart(self, log_callback=None):
+ return self._run_service_command(
+ 'restart',
+ expected_exit_code=0,
+ log_callback=log_callback
+ )
+
+ def enable(self, log_callback=None):
+ return self._run_service_command(
+ 'enable',
+ expected_exit_code=0,
+ log_callback=log_callback
+ )
+
+ @property
+ def enabled(self):
+ return self._run_service_command('is-enabled').rc == 0
+
+ @property
+ def is_active(self):
+ return self._run_service_command('is-active').rc == 0
+
+ @property
+ def running(self):
+ return self._run_service_command("status").rc == 0
+
+ def wait_for_running(self, timeout=600):
+ result, wait = wait_for(
+ lambda: self.running,
+ num_sec=timeout,
+ fail_condition=False,
+ delay=5,
+ )
+ return result
+
+ def daemon_reload(self, log_callback=None):
+ """Call daemon-reload, no unit name for this"""
+ return self._run_service_command(
+ command='daemon-reload',
+ expected_exit_code=0,
+ unit_name='',
+ log_callback=log_callback
+ )
diff --git a/pool/shard009/Python/0083386_0009_auto_20150529_1413.py b/pool/shard009/Python/0083386_0009_auto_20150529_1413.py
new file mode 100644
index 0000000000000000000000000000000000000000..1f58bd311f40f122db16b3b48e08cbc1b14ceeaf
--- /dev/null
+++ b/pool/shard009/Python/0083386_0009_auto_20150529_1413.py
@@ -0,0 +1,33 @@
+# -*- coding: utf-8 -*-
+from __future__ import unicode_literals
+
+from django.conf import settings
+from django.db import migrations
+from django.db import models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ('orchestra', '0008_auto_20150520_1953'),
+ ]
+
+ operations = [
+ migrations.AlterField(
+ model_name='certification',
+ name='required_certifications',
+ field=models.ManyToManyField(
+ blank=True, to='orchestra.Certification', related_name='required_certifications_rel_+'),
+ ),
+ migrations.AlterField(
+ model_name='task',
+ name='step_slug',
+ field=models.CharField(max_length=200, choices=[
+ ('content_extraction', ' Content Extraction'), ('copy_pass', 'Copy Pass')]),
+ ),
+ migrations.AlterField(
+ model_name='worker',
+ name='user',
+ field=models.OneToOneField(on_delete=models.CASCADE, to=settings.AUTH_USER_MODEL),
+ ),
+ ]
diff --git a/pool/shard009/Python/0083388_deoplete_emoji.py b/pool/shard009/Python/0083388_deoplete_emoji.py
new file mode 100644
index 0000000000000000000000000000000000000000..596289492e3c0452673795eec55c6493a74ce41b
--- /dev/null
+++ b/pool/shard009/Python/0083388_deoplete_emoji.py
@@ -0,0 +1,47 @@
+from pathlib import Path
+import sys
+
+from deoplete.base.source import Base
+from emoji.unicode_codes.en import EMOJI_ALIAS_UNICODE_ENGLISH
+
+sys.path.append(str(Path(__file__).absolute().parent.parent.parent))
+
+
+class Source(Base):
+ MAX_CANDIDATES_PER_GROUP = 5
+
+ def __init__(self, vim):
+ super().__init__(vim)
+ self.name = "emoji"
+ self.mark = "[emoji]"
+ self.rank = 500
+ self.filetypes = ["markdown"]
+ self.input_pattern = r":[a-z_]+:?"
+ self.is_volatile = True
+ self.matcher_key = "match"
+ self.matchers = ["matcher_full_fuzzy"]
+ self.sorters = ["sorter_rank"]
+
+ def get_complete_position(self, context):
+ if context["input"].endswith(":"):
+ return context["input"].rfind(":", 0, -1)
+ else:
+ return context["input"].rfind(":")
+
+ def gather_candidates(self, context):
+ text: str
+ if context["input"].endswith(":"):
+ text = ":" + context["input"].split(":")[-2].strip() + ":"
+ if text in EMOJI_ALIAS_UNICODE_ENGLISH:
+ return [
+ {"word": EMOJI_ALIAS_UNICODE_ENGLISH[text], "kind": "[alias]", "match": text}
+ ]
+ else:
+ return []
+ else:
+ out = []
+ text = ":" + context["input"].split(":")[-1].strip()
+ for k, v in EMOJI_ALIAS_UNICODE_ENGLISH.items():
+ if k.startswith(text):
+ out.append({"word": v, "kind": "[alias]", "match": k})
+ return out
diff --git a/pool/shard009/Python/0083390_fx_dialog.py b/pool/shard009/Python/0083390_fx_dialog.py
new file mode 100644
index 0000000000000000000000000000000000000000..bd1f6f1f0f93d450fd72f04330a271ebd58764e4
--- /dev/null
+++ b/pool/shard009/Python/0083390_fx_dialog.py
@@ -0,0 +1,109 @@
+from kivy.app import App
+from kivy.factory import Factory
+from kivy.properties import ObjectProperty
+from kivy.lang import Builder
+
+Builder.load_string('''
+
+ id: popup
+ title: 'Fiat Currency'
+ size_hint: 0.8, 0.8
+ pos_hint: {'top':0.9}
+ BoxLayout:
+ orientation: 'vertical'
+
+ Widget:
+ size_hint: 1, 0.1
+
+ BoxLayout:
+ orientation: 'horizontal'
+ size_hint: 1, 0.1
+ Label:
+ text: _('Currency')
+ height: '48dp'
+ Spinner:
+ height: '48dp'
+ id: ccy
+ on_text: popup.on_currency(self.text)
+
+ Widget:
+ size_hint: 1, 0.1
+
+ BoxLayout:
+ orientation: 'horizontal'
+ size_hint: 1, 0.1
+ Label:
+ text: _('Source')
+ height: '48dp'
+ Spinner:
+ height: '48dp'
+ id: exchanges
+ on_text: popup.on_exchange(self.text)
+
+ Widget:
+ size_hint: 1, 0.2
+
+ BoxLayout:
+ orientation: 'horizontal'
+ size_hint: 1, 0.2
+ Button:
+ text: 'Cancel'
+ size_hint: 0.5, None
+ height: '48dp'
+ on_release: popup.dismiss()
+ Button:
+ text: 'OK'
+ size_hint: 0.5, None
+ height: '48dp'
+ on_release:
+ root.callback()
+ popup.dismiss()
+''')
+
+
+from kivy.uix.label import Label
+from kivy.uix.checkbox import CheckBox
+from kivy.uix.widget import Widget
+from kivy.clock import Clock
+
+from electrum_arg_gui.kivy.i18n import _
+from functools import partial
+
+class FxDialog(Factory.Popup):
+
+ def __init__(self, app, plugins, config, callback):
+ Factory.Popup.__init__(self)
+ self.app = app
+ self.config = config
+ self.callback = callback
+ self.fx = self.app.fx
+ self.fx.set_history_config(True)
+ self.add_currencies()
+
+ def add_exchanges(self):
+ exchanges = sorted(self.fx.get_exchanges_by_ccy(self.fx.get_currency(), True)) if self.fx.is_enabled() else []
+ mx = self.fx.exchange.name() if self.fx.is_enabled() else ''
+ ex = self.ids.exchanges
+ ex.values = exchanges
+ ex.text = (mx if mx in exchanges else exchanges[0]) if self.fx.is_enabled() else ''
+
+ def on_exchange(self, text):
+ if not text:
+ return
+ if self.fx.is_enabled() and text != self.fx.exchange.name():
+ self.fx.set_exchange(text)
+
+ def add_currencies(self):
+ currencies = [_('None')] + self.fx.get_currencies(True)
+ my_ccy = self.fx.get_currency() if self.fx.is_enabled() else _('None')
+ self.ids.ccy.values = currencies
+ self.ids.ccy.text = my_ccy
+
+ def on_currency(self, ccy):
+ b = (ccy != _('None'))
+ self.fx.set_enabled(b)
+ if b:
+ if ccy != self.fx.get_currency():
+ self.fx.set_currency(ccy)
+ self.app.fiat_unit = ccy
+ Clock.schedule_once(lambda dt: self.add_exchanges())
diff --git a/pool/shard009/Python/0083394_config_flow.py b/pool/shard009/Python/0083394_config_flow.py
new file mode 100644
index 0000000000000000000000000000000000000000..00ddd9335a3cb2f8b32918fb3ef5738ec0cc1fd3
--- /dev/null
+++ b/pool/shard009/Python/0083394_config_flow.py
@@ -0,0 +1,157 @@
+"""Config flow for Fronius integration."""
+from __future__ import annotations
+
+import asyncio
+import logging
+from typing import Any, Final
+
+from pyfronius import Fronius, FroniusError
+import voluptuous as vol
+
+from homeassistant import config_entries
+from homeassistant.components.dhcp import DhcpServiceInfo
+from homeassistant.const import CONF_HOST, CONF_RESOURCE
+from homeassistant.core import HomeAssistant
+from homeassistant.data_entry_flow import FlowResult
+from homeassistant.exceptions import HomeAssistantError
+from homeassistant.helpers.aiohttp_client import async_get_clientsession
+
+from .const import DOMAIN, FroniusConfigEntryData
+
+_LOGGER: Final = logging.getLogger(__name__)
+
+DHCP_REQUEST_DELAY: Final = 60
+
+STEP_USER_DATA_SCHEMA = vol.Schema(
+ {
+ vol.Required(CONF_HOST): str,
+ }
+)
+
+
+def create_title(info: FroniusConfigEntryData) -> str:
+ """Return the title of the config flow."""
+ return (
+ f"SolarNet {'Datalogger' if info['is_logger'] else 'Inverter'}"
+ f" at {info['host']}"
+ )
+
+
+async def validate_host(
+ hass: HomeAssistant, host: str
+) -> tuple[str, FroniusConfigEntryData]:
+ """Validate the user input allows us to connect.
+
+ Data has the keys from STEP_USER_DATA_SCHEMA with values provided by the user.
+ """
+ fronius = Fronius(async_get_clientsession(hass), host)
+
+ try:
+ datalogger_info: dict[str, Any]
+ datalogger_info = await fronius.current_logger_info()
+ except FroniusError as err:
+ _LOGGER.debug(err)
+ else:
+ logger_uid: str = datalogger_info["unique_identifier"]["value"]
+ return logger_uid, FroniusConfigEntryData(
+ host=host,
+ is_logger=True,
+ )
+ # Gen24 devices don't provide GetLoggerInfo
+ try:
+ inverter_info = await fronius.inverter_info()
+ first_inverter = next(inverter for inverter in inverter_info["inverters"])
+ except FroniusError as err:
+ _LOGGER.debug(err)
+ raise CannotConnect from err
+ except StopIteration as err:
+ raise CannotConnect("No supported Fronius SolarNet device found.") from err
+ first_inverter_uid: str = first_inverter["unique_id"]["value"]
+ return first_inverter_uid, FroniusConfigEntryData(
+ host=host,
+ is_logger=False,
+ )
+
+
+class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
+ """Handle a config flow for Fronius."""
+
+ VERSION = 1
+
+ def __init__(self) -> None:
+ """Initialize flow."""
+ self.info: FroniusConfigEntryData
+
+ async def async_step_user(
+ self, user_input: dict[str, Any] | None = None
+ ) -> FlowResult:
+ """Handle the initial step."""
+ if user_input is None:
+ return self.async_show_form(
+ step_id="user", data_schema=STEP_USER_DATA_SCHEMA
+ )
+
+ errors = {}
+
+ try:
+ unique_id, info = await validate_host(self.hass, user_input[CONF_HOST])
+ except CannotConnect:
+ errors["base"] = "cannot_connect"
+ except Exception: # pylint: disable=broad-except
+ _LOGGER.exception("Unexpected exception")
+ errors["base"] = "unknown"
+ else:
+ await self.async_set_unique_id(unique_id, raise_on_progress=False)
+ self._abort_if_unique_id_configured(updates=dict(info))
+
+ return self.async_create_entry(title=create_title(info), data=info)
+
+ return self.async_show_form(
+ step_id="user", data_schema=STEP_USER_DATA_SCHEMA, errors=errors
+ )
+
+ async def async_step_import(self, conf: dict) -> FlowResult:
+ """Import a configuration from config.yaml."""
+ return await self.async_step_user(user_input={CONF_HOST: conf[CONF_RESOURCE]})
+
+ async def async_step_dhcp(self, discovery_info: DhcpServiceInfo) -> FlowResult:
+ """Handle a flow initiated by the DHCP client."""
+ for entry in self._async_current_entries(include_ignore=False):
+ if entry.data[CONF_HOST].lstrip("http://").rstrip("/").lower() in (
+ discovery_info.ip,
+ discovery_info.hostname,
+ ):
+ return self.async_abort(reason="already_configured")
+ # Symo Datalogger devices need up to 1 minute at boot from DHCP request
+ # to respond to API requests (connection refused until then)
+ await asyncio.sleep(DHCP_REQUEST_DELAY)
+ try:
+ unique_id, self.info = await validate_host(self.hass, discovery_info.ip)
+ except CannotConnect:
+ return self.async_abort(reason="invalid_host")
+
+ await self.async_set_unique_id(unique_id, raise_on_progress=False)
+ self._abort_if_unique_id_configured(updates=dict(self.info))
+
+ return await self.async_step_confirm_discovery()
+
+ async def async_step_confirm_discovery(
+ self, user_input: dict[str, Any] | None = None
+ ) -> FlowResult:
+ """Attempt to confirm."""
+ title = create_title(self.info)
+ if user_input is not None:
+ return self.async_create_entry(title=title, data=self.info)
+
+ self._set_confirm_only()
+ self.context.update({"title_placeholders": {"device": title}})
+ return self.async_show_form(
+ step_id="confirm_discovery",
+ description_placeholders={
+ "device": title,
+ },
+ )
+
+
+class CannotConnect(HomeAssistantError):
+ """Error to indicate we cannot connect."""
diff --git a/pool/shard009/Python/0083398_geocode_to_csv.py b/pool/shard009/Python/0083398_geocode_to_csv.py
new file mode 100644
index 0000000000000000000000000000000000000000..53e6d911c2e925b75247f6ad6d9face120c3ffc2
--- /dev/null
+++ b/pool/shard009/Python/0083398_geocode_to_csv.py
@@ -0,0 +1,68 @@
+# geocoding with geopy
+# from address field in one csv into new csv with X,Y fields
+# also outputs table of any records that failed
+
+import csv
+import os
+import time
+from geopy.geocoders import GoogleV3
+
+# input csv dir/name.csv
+csv_in = 'path/in.csv'
+
+# output csv dir/name.csv
+csv_out = 'path/geocoded.csv'
+csv_out_fail = 'path/fail.csv'
+
+
+# name of geocoding service
+geolocator = GoogleV3()
+
+# outputs
+out_table = []
+fail_table = []
+
+with open(csv_in, 'r') as csvfile:
+ reader = csv.reader(csvfile)
+ for row in reader:
+ header = row
+ break
+ counter = 0
+ for row in reader:
+ if row != header:
+ try:
+ address = row[2] + ", " + row[3] + ", " + row[15] # will be different for each csv - choose wisely
+ print address
+ time.sleep(1)
+ location = geolocator.geocode(address, timeout=60)
+ if location is None:
+ location = geolocator.geocode(row[15], timeout=60) # just geocode postal code
+ lat = location.latitude
+ lon = location.longitude
+ print lon, lat
+
+ out_row = row + [lon,lat]
+
+ out_table.append(out_row)
+
+ except:
+ print 'FAIL'
+ fail_table.append(row)
+
+ counter += 1
+
+# write outputs to file
+
+with open(csv_out, 'w') as csvw:
+ writer = csv.writer(csvw)
+ for row in out_table:
+ writer.writerow(row)
+
+
+with open(csv_out_fail, 'w') as csvw:
+ writer = csv.writer(csvw)
+ for row in fail_table:
+ writer.writerow(row)
+
+# print those that fail
+print len(fail_table)
diff --git a/pool/shard009/Python/0083400_references_api.py b/pool/shard009/Python/0083400_references_api.py
new file mode 100644
index 0000000000000000000000000000000000000000..547e391720675b408263036ab5842a0b1f8755d4
--- /dev/null
+++ b/pool/shard009/Python/0083400_references_api.py
@@ -0,0 +1,54 @@
+from werkzeug.exceptions import Gone
+from flask import Blueprint, g
+from restpager import Pager
+
+from storyweb import authz
+from storyweb.model import db, Card, Reference
+from storyweb.util import jsonify, obj_or_404, request_data
+
+
+blueprint = Blueprint('references_api', __name__)
+
+
+@blueprint.route('/api/1/cards//references', methods=['GET'])
+def index(card_id):
+ authz.require(authz.logged_in())
+ card = obj_or_404(Card.by_id(card_id))
+ references = db.session.query(Reference)
+ references = references.filter(Reference.card == card)
+ pager = Pager(references, card_id=card_id)
+ return jsonify(pager, index=True)
+
+
+@blueprint.route('/api/1/cards//references', methods=['POST', 'PUT'])
+def create(card_id):
+ authz.require(authz.logged_in())
+ card = obj_or_404(Card.by_id(card_id))
+ reference = Reference().save(request_data(), card, g.user)
+ db.session.commit()
+ return jsonify(reference, status=201)
+
+
+@blueprint.route('/api/1/cards//references/', methods=['GET'])
+def view(card_id, id):
+ authz.require(authz.logged_in())
+ reference = obj_or_404(Reference.by_id(id, card_id=card_id))
+ return jsonify(reference)
+
+
+@blueprint.route('/api/1/cards//references/', methods=['POST', 'PUT'])
+def update(card_id, id):
+ authz.require(authz.logged_in())
+ reference = obj_or_404(Reference.by_id(id, card_id=card_id))
+ reference.save(request_data(), reference.card, g.user)
+ db.session.commit()
+ return jsonify(reference)
+
+
+@blueprint.route('/api/1/cards//references/', methods=['DELETE'])
+def delete(card_id, id):
+ authz.require(authz.logged_in())
+ reference = obj_or_404(Reference.by_id(id, card_id=card_id))
+ db.session.delete(reference)
+ db.session.commit()
+ raise Gone()
diff --git a/pool/shard009/Python/0083404_uplink.py b/pool/shard009/Python/0083404_uplink.py
new file mode 100644
index 0000000000000000000000000000000000000000..3a662b64ab579f0e05527ee38cb6d78657e3935c
--- /dev/null
+++ b/pool/shard009/Python/0083404_uplink.py
@@ -0,0 +1,206 @@
+#####################################################################################
+#
+# Copyright (c) Crossbar.io Technologies GmbH
+#
+# Unless a separate license agreement exists between you and Crossbar.io GmbH (e.g.
+# you have purchased a commercial license), the license terms below apply.
+#
+# Should you enter into a separate license agreement after having received a copy of
+# this software, then the terms of such license agreement replace the terms below at
+# the time at which such license agreement becomes effective.
+#
+# In case a separate license agreement ends, and such agreement ends without being
+# replaced by another separate license agreement, the license terms below apply
+# from the time at which said agreement ends.
+#
+# LICENSE TERMS
+#
+# This program is free software: you can redistribute it and/or modify it under the
+# terms of the GNU Affero General Public License, version 3, as published by the
+# Free Software Foundation. This program is distributed in the hope that it will be
+# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+#
+# See the GNU Affero General Public License Version 3 for more details.
+#
+# You should have received a copy of the GNU Affero General Public license along
+# with this program. If not, see .
+#
+#####################################################################################
+
+from __future__ import absolute_import
+
+from twisted.internet.defer import Deferred, inlineCallbacks
+
+from autobahn.wamp import auth
+from autobahn.wamp.types import SubscribeOptions, PublishOptions
+from autobahn.twisted.wamp import ApplicationSession, ApplicationRunner
+
+from txaio import make_logger
+
+__all__ = ('LocalSession',)
+
+
+class BridgeSession(ApplicationSession):
+
+ log = make_logger()
+
+ @inlineCallbacks
+ def _setup_event_forwarding(self, other):
+
+ self.log.info("setup event forwarding between {me} and {other} ..", me=self, other=other)
+
+ self._subs = {}
+
+ # listen to when new subscriptions are created on the router
+ #
+ @inlineCallbacks
+ def on_subscription_create(sub_id, sub_details, details=None):
+ self.log.info(
+ "Subscription created: {me} {sub_id} {sub_details} {details}",
+ me=self,
+ sub_id=sub_id,
+ sub_details=sub_details,
+ details=details,
+ )
+
+ self._subs[sub_id] = sub_details
+
+ uri = sub_details['uri']
+
+ def on_event(*args, **kwargs):
+ details = kwargs.pop('details')
+ # FIXME: setup things so out (the node's) identity gets disclosed
+ self.publish(uri, *args, options=PublishOptions(), **kwargs)
+ self.log.info(
+ "forwarded from {other} event to {me} ({dir}): args={args}, details={details}",
+ other=other,
+ me=self,
+ dir=self._DIR,
+ args=args,
+ details=details,
+ )
+
+ sub = yield other.subscribe(on_event, uri, options=SubscribeOptions(details_arg="details"))
+ self._subs[sub_id]['sub'] = sub
+
+ self.log.info("{other} subscribed to {me}".format(other=other, me=uri))
+
+ yield self.subscribe(on_subscription_create, u"wamp.subscription.on_create", options=SubscribeOptions(details_arg="details"))
+
+ # listen to when a subscription is removed from the router
+ #
+ @inlineCallbacks
+ def on_subscription_delete(session_id, sub_id, details=None):
+ self.log.info(
+ "Subscription deleted: {me} {session} {sub_id} {details}",
+ me=self,
+ session=session_id,
+ sub_id=sub_id,
+ details=details,
+ )
+
+ sub_details = self._subs.get(sub_id, None)
+ if not sub_details:
+ self.log.info("subscription not tracked - huh??")
+ return
+
+ uri = sub_details['uri']
+
+ yield self._subs[sub_id]['sub'].unsubscribe()
+
+ del self._subs[sub_id]
+
+ self.log.info("{other} unsubscribed from {uri}".format(other=other, uri=uri))
+
+ yield self.subscribe(on_subscription_delete, u"wamp.subscription.on_delete", options=SubscribeOptions(details_arg="details"))
+
+ # get current subscriptions on the router
+ #
+ subs = yield self.call(u"wamp.subscription.list")
+ for sub_id in subs['exact']:
+ sub = yield self.call(u"wamp.subscription.get", sub_id)
+ yield on_subscription_create(sub['id'], sub)
+
+ self.log.info("event forwarding setup done.")
+
+
+class LocalSession(BridgeSession):
+ """
+ This session is the local leg of the router uplink and runs embedded inside the local router.
+ """
+
+ log = make_logger()
+
+ _DIR = "=>"
+
+ @inlineCallbacks
+ def onJoin(self, details):
+ uplink_config = self.config.extra['uplink']
+ uplink_realm = details.realm
+ uplink_transport = uplink_config['transport']
+
+ extra = {
+ 'onready': Deferred(),
+ 'local': self,
+ }
+ runner = ApplicationRunner(url=uplink_transport['url'], realm=uplink_realm, extra=extra)
+ yield runner.run(RemoteSession, start_reactor=False)
+
+ edge_session = yield extra['onready']
+
+ yield self._setup_event_forwarding(edge_session)
+
+ if self.config.extra and 'onready' in self.config.extra:
+ self.config.extra['onready'].callback(self)
+
+
+class RemoteSession(BridgeSession):
+ """
+ This session is the remote leg of the router uplink.
+ """
+
+ log = make_logger()
+
+ _DIR = "<="
+
+ def onConnect(self):
+ self.log.info("Uplink connected")
+
+ realm = self.config.realm
+ authid = self.config.extra.get('authid', None)
+ if authid:
+ self.log.debug("Uplink - joining realm '{realm}' as '{authid}' ..", realm=realm, authid=authid)
+ self.join(realm, [u"wampcra"], authid)
+ else:
+ self.log.debug("Uplink - joining realm '{realm}' ..", realm=realm)
+ self.join(realm)
+
+ def onChallenge(self, challenge):
+ if challenge.method == u"wampcra":
+ authkey = self.config.extra['authkey'].encode('utf8')
+ signature = auth.compute_wcs(authkey, challenge.extra['challenge'].encode('utf8'))
+ return signature.decode('ascii')
+ else:
+ raise Exception("don't know how to compute challenge for authmethod {}".format(challenge.method))
+
+ @inlineCallbacks
+ def onJoin(self, details):
+ self.log.info("Uplink joined realm '{realm}' on uplink router", realm=details.realm)
+
+ yield self._setup_event_forwarding(self.config.extra['local'])
+
+ if self.config.extra and 'onready' in self.config.extra:
+ self.config.extra['onready'].callback(self)
+
+ self.log.info("Uplink ready.")
+
+ def onLeave(self, details):
+ if details.reason != u"wamp.close.normal":
+ self.log.warn("Uplink left: {defailts}", details=details)
+ else:
+ self.log.debug("Uplink detached: {details}", details=details)
+ self.disconnect()
+
+ def onDisconnect(self):
+ self.log.info("Uplink disconnected")
diff --git a/pool/shard009/Python/0083412_cmdline.py b/pool/shard009/Python/0083412_cmdline.py
new file mode 100644
index 0000000000000000000000000000000000000000..ab02144ae7f28db6385909cc6382a55c90ef9ee8
--- /dev/null
+++ b/pool/shard009/Python/0083412_cmdline.py
@@ -0,0 +1,97 @@
+from __future__ import unicode_literals
+import os
+import sys
+import tempfile
+
+# Importing from green (other than config) is done after coverage initialization
+import green.config as config
+
+
+def _main(argv, testing):
+ args = config.parseArguments(argv)
+ args = config.mergeConfig(args, testing)
+
+ if args.shouldExit:
+ return args.exitCode
+
+ # Clear out all the passed-in-options just in case someone tries to run a
+ # test that assumes sys.argv is clean. I can't guess at the script name
+ # that they want, though, so we'll just leave ours.
+ sys.argv = sys.argv[:1]
+
+ # Set up our various main objects
+ from green.loader import GreenTestLoader, getCompletions
+ from green.runner import run
+ from green.output import GreenStream, debug
+ import green.output
+ from green.suite import GreenTestSuite
+
+ GreenTestSuite.args = args
+
+ if args.debug:
+ green.output.debug_level = args.debug
+
+ stream = GreenStream(sys.stdout, disable_windows=args.disable_windows)
+
+ # Location of shell completion file
+ if args.completion_file:
+ print(os.path.join(os.path.dirname(__file__), "shell_completion.sh"))
+ return 0
+
+ # Argument-completion for bash and zsh (for test-target completion)
+ if args.completions:
+ print(getCompletions(args.targets))
+ return 0
+
+ # Option-completion for bash and zsh
+ if args.options:
+ print("\n".join(sorted(args.store_opt.options)))
+ return 0
+
+ # Add debug logging for stuff that happened before this point here
+ if config.files_loaded:
+ debug("Loaded config file(s): {}".format(", ".join(config.files_loaded)))
+
+ # Discover/Load the test suite
+ if testing:
+ test_suite = None
+ else: # pragma: no cover
+ loader = GreenTestLoader()
+ test_suite = loader.loadTargets(args.targets, file_pattern=args.file_pattern)
+
+ # We didn't even load 0 tests...
+ if not test_suite:
+ debug("No test loading attempts succeeded. Created an empty test suite.")
+ test_suite = GreenTestSuite()
+
+ # Actually run the test_suite
+ result = run(test_suite, stream, args, testing)
+
+ # Generate a test report if required
+ if args.junit_report:
+ from green.junit import JUnitXML
+
+ adapter = JUnitXML()
+ with open(args.junit_report, "w") as report_file:
+ adapter.save_as(result, report_file)
+
+ return int(not result.wasSuccessful())
+
+
+def main(argv=None, testing=False):
+ # create the temp dir only once (i.e., not while in the recursed call)
+ if os.environ.get("TMPDIR") is None: # pragma: nocover
+ with tempfile.TemporaryDirectory() as temp_dir_for_tests:
+ try:
+ os.environ["TMPDIR"] = temp_dir_for_tests
+ tempfile.tempdir = temp_dir_for_tests
+ return _main(argv, testing)
+ finally:
+ del os.environ["TMPDIR"]
+ tempfile.tempdir = None
+ else:
+ return _main(argv, testing)
+
+
+if __name__ == "__main__": # pragma: no cover
+ sys.exit(main())
diff --git a/pool/shard009/Python/0083413_tests.py b/pool/shard009/Python/0083413_tests.py
new file mode 100644
index 0000000000000000000000000000000000000000..4fdb793feb0b8fa46885e0024c77ba774566fc79
--- /dev/null
+++ b/pool/shard009/Python/0083413_tests.py
@@ -0,0 +1,88 @@
+"""
+A series of tests to establish that the command-line bash completion works.
+"""
+import os
+import sys
+
+from django.conf import settings
+from django.core.management import ManagementUtility
+from django.utils import unittest
+from django.utils.six import StringIO
+
+
+class BashCompletionTests(unittest.TestCase):
+ """
+ Testing the Python level bash completion code.
+ This requires setting up the environment as if we got passed data
+ from bash.
+ """
+
+ def setUp(self):
+ self.old_DJANGO_AUTO_COMPLETE = os.environ.get('DJANGO_AUTO_COMPLETE')
+ os.environ['DJANGO_AUTO_COMPLETE'] = '1'
+ self.output = StringIO()
+ self.old_stdout = sys.stdout
+ sys.stdout = self.output
+
+ def tearDown(self):
+ sys.stdout = self.old_stdout
+ if self.old_DJANGO_AUTO_COMPLETE:
+ os.environ['DJANGO_AUTO_COMPLETE'] = self.old_DJANGO_AUTO_COMPLETE
+ else:
+ del os.environ['DJANGO_AUTO_COMPLETE']
+
+ def _user_input(self, input_str):
+ os.environ['COMP_WORDS'] = input_str
+ os.environ['COMP_CWORD'] = str(len(input_str.split()) - 1)
+ sys.argv = input_str.split(' ')
+
+ def _run_autocomplete(self):
+ util = ManagementUtility(argv=sys.argv)
+ try:
+ util.autocomplete()
+ except SystemExit:
+ pass
+ return self.output.getvalue().strip().split('\n')
+
+ def test_django_admin_py(self):
+ "django_admin.py will autocomplete option flags"
+ self._user_input('django-admin.py sqlall --v')
+ output = self._run_autocomplete()
+ self.assertEqual(output, ['--verbosity='])
+
+ def test_manage_py(self):
+ "manage.py will autocomplete option flags"
+ self._user_input('manage.py sqlall --v')
+ output = self._run_autocomplete()
+ self.assertEqual(output, ['--verbosity='])
+
+ def test_custom_command(self):
+ "A custom command can autocomplete option flags"
+ self._user_input('django-admin.py test_command --l')
+ output = self._run_autocomplete()
+ self.assertEqual(output, ['--list'])
+
+ def test_subcommands(self):
+ "Subcommands can be autocompleted"
+ self._user_input('django-admin.py sql')
+ output = self._run_autocomplete()
+ self.assertEqual(output, ['sql sqlall sqlclear sqlcustom sqldropindexes sqlflush sqlindexes sqlinitialdata sqlsequencereset'])
+
+ def test_help(self):
+ "No errors, just an empty list if there are no autocomplete options"
+ self._user_input('django-admin.py help --')
+ output = self._run_autocomplete()
+ self.assertEqual(output, [''])
+
+ def test_runfcgi(self):
+ "Command arguments will be autocompleted"
+ self._user_input('django-admin.py runfcgi h')
+ output = self._run_autocomplete()
+ self.assertEqual(output, ['host='])
+
+ def test_app_completion(self):
+ "Application names will be autocompleted for an AppCommand"
+ self._user_input('django-admin.py sqlall a')
+ output = self._run_autocomplete()
+ app_labels = [name.split('.')[-1] for name in settings.INSTALLED_APPS]
+ self.assertEqual(output, sorted(label for label in app_labels if label.startswith('a')))
diff --git a/pool/shard009/Python/0083418_contributors.py b/pool/shard009/Python/0083418_contributors.py
new file mode 100644
index 0000000000000000000000000000000000000000..9bcf860dbf32bdb06a6a0a813238cb48ac3605f9
--- /dev/null
+++ b/pool/shard009/Python/0083418_contributors.py
@@ -0,0 +1,125 @@
+from random import shuffle
+from models import FriendsModel
+
+class Contributors(object):
+ def __init__(self,similarity):
+ self.similarity = similarity
+ self.model = self.similarity.get_model()
+ return
+ #0:all
+ def get_neighbors(self, user_id, num=0):
+ raise NotImplementedError("cannot instantiate Abstract Base Class")
+
+ def get_model(self):
+ return self.similarity.get_model()
+
+
+
+class Neighbors(Contributors):
+ def __init__self(self,similarity):
+ super(Neighbors,self).__init__(similarity)
+ return
+
+ def get_neighbors(self,user_id,num=0):
+ nbs = self.similarity.get_similarities(user_id)
+ if num < 1:
+ return nbs
+ return nbs[:num]
+
+class JphNeighbors(Contributors):
+ def __init__self(self,similarity):
+ super(JphNeighbors,self).__init__(similarity)
+ return
+
+ def get_neighbors(self,user_id,num=0):
+ nbs = self.similarity.get_similarities(user_id)
+ new_nbs = nbs[::2]
+ return new_nbs[:num]
+
+#DANGER CODE
+class Neighbors_Friends(Contributors):
+ def __init__self(self,similarity,):
+ super(Neighbors_Friends,self).__init__(similarity)
+ #self.check_model_type(self.model)
+ return
+
+ def check_model_type(self,model):
+ if not type(model) is FriendsModel:
+ raise TypeError("model should be an instance of FriendsModel")
+ return True
+
+
+ def get_neighbors(self,user_id,num=0):
+ t_ids = self.model.get_strangers_in_roster(user_id)
+ nbs = self.similarity.get_similarities(user_id,t_ids)
+ if num == 0:
+ return nbs
+ if num < 0:
+ num = len(self.model.get_friends(user_id,level=2))
+ return nbs[:num]
+
+
+class Friends(Contributors):
+ def __init__(self,similarity):
+ super(Friends,self).__init__(similarity)
+ #self.check_model_type(self.model)
+ return
+
+ def check_model_type(self,model):
+ if not type(model) is FriendsModel:
+ raise TypeError("model should be an instance of FriendsModel")
+ return True
+
+
+ def get_neighbors(self,user_id,num=0):
+ f_ids = self.model.get_friends(user_id,level=2)
+ nbs = self.similarity.get_similarities(user_id,f_ids)
+ if num < 1:
+ return nbs
+ return nbs[:num]
+
+class Friends_Strangers(Contributors):
+ def __init__(self,similarity, f_n, t_n):
+ super(Friends_Strangers,self).__init__(similarity)
+ self.f_n = f_n
+ self.t_n = t_n
+
+ # This function is implemented slightly different with the other child classes.
+ def get_neighbors(self,user_id,num=0):
+ # get friends
+ f_ids = self.model.get_friends(user_id,level=1)
+ shuffle(f_ids)
+ frs = f_ids[:self.f_n]
+ fnbs = self.similarity.get_similarities(user_id,frs)
+
+ # get stranger
+ t_ids = self.model.get_strangers_in_roster(user_id)
+ shuffle(t_ids)
+ sts = t_ids[:self.t_n]
+ st_sim = [1.0]*len(sts) #specific sim for esorics prefictor
+ stnbs = zip(sts,st_sim)
+
+ return (fnbs, stnbs)
+
+ def get_rand_friends(self, user_id):
+ f_ids = self.model.get_friends(user_id,level=1)
+
+ shuffle(f_ids)
+ frs = f_ids[:self.f_n]
+ fnbs = self.similarity.get_similarities(user_id,frs)
+ #print "fnbs: ", len(fnbs)
+ return fnbs
+
+ def get_rand_strangers(self, user_id):
+ t_ids = self.model.get_strangers_in_roster(user_id)
+ shuffle(t_ids)
+ sts = t_ids[:self.t_n]
+ st_sim = [1.0]*len(sts) #specific sim for esorics prefictor
+ stnbs = zip(sts,st_sim)
+ return stnbs
+
+
+
+
+
+
diff --git a/pool/shard009/Python/0083420_async_iterator.py b/pool/shard009/Python/0083420_async_iterator.py
new file mode 100644
index 0000000000000000000000000000000000000000..b59689bdb8df1120a6ce9ea6fa4190e5b9e68332
--- /dev/null
+++ b/pool/shard009/Python/0083420_async_iterator.py
@@ -0,0 +1,43 @@
+from queue import Queue
+from threading import Thread
+
+import asyncio
+
+class AsyncIterator:
+
+ POLL_INTERVAL = .5
+
+ def __init__(self):
+ self.queue = Queue()
+ self.thread = None
+ self.done = False
+ self.stop_iteration_cls = StopAsyncIteration
+
+ def start(self, call, *args, **kwargs):
+
+ def run():
+ for line in call(*args, **kwargs):
+ self.queue.put(line)
+ self.done = True
+
+ self.thread = Thread(target=run)
+ self.thread.start()
+
+ return self
+
+ def throw(self, cls):
+ self.stop_iteration_cls = cls
+
+ async def __aiter__(self):
+ return self
+
+ async def __anext__(self):
+ while self.queue.empty():
+ if self.done:
+ raise self.stop_iteration_cls
+
+ await asyncio.sleep(AsyncIterator.POLL_INTERVAL)
+
+ item = self.queue.get()
+ self.queue.task_done()
+ return item
diff --git a/pool/shard009/Python/0083423_parser.py b/pool/shard009/Python/0083423_parser.py
new file mode 100644
index 0000000000000000000000000000000000000000..abc40ee78b0afb2213fcb4b48e68c6364e809b3e
--- /dev/null
+++ b/pool/shard009/Python/0083423_parser.py
@@ -0,0 +1,111 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+'''
+The Parser parses output usually ini file output from
+multiple hosts, or output from CLI operations.
+'''
+
+import rex
+from prettytable import PrettyTable
+import textwrap
+#import pprint
+
+
+class Parser(object):
+ '''
+ Parser class - To parse results from remote hosts.
+ '''
+ def __init__(self):
+
+ '''
+ Initialize comparator.
+ '''
+
+ def parse_dataset(self, **kwargs):
+ '''
+ parse the dataset which can be results from multiple
+ hosts and return a dictionary of parsed results.
+ '''
+ dataset = kwargs.get('datalist', None)
+
+ results = {}
+ for data in dataset:
+ result = {}
+ node_data = rex.parse_lrvalue_string(data['output'],
+ delimiter="=")
+ # If the data is not a LR value, then
+ # the result will be an empty {} dict. In that case
+ # save it as text only.
+
+ if not node_data:
+ result['data'] = data['output']
+ result['data_type'] = "str"
+ else:
+ result['data'] = node_data
+ result['data_type'] = "dict"
+ results[data['node']] = result
+
+ return results
+
+ def display_tabular(self, **kwargs):
+ '''
+ Compare operation. Main function
+ '''
+ datalist = kwargs.get('datalist', None)
+ if not datalist:
+ return
+
+ newresults = self.parse_dataset(**kwargs)
+
+ fields = set()
+ for node in newresults.keys():
+ print "node: ", node
+ nodeobj = newresults[node]
+ if nodeobj['data_type'] == 'dict':
+ for key in nodeobj['data'].keys():
+ fields.add(key)
+
+ header = []
+ header.append("Key")
+ for node in newresults.keys():
+ header.append(node)
+
+ x = PrettyTable(header)
+ x.align["key"] = "l"
+ for node in newresults.keys():
+ x.align[node] = "l"
+
+ if fields:
+ for val in fields:
+ row = []
+ row.append(val)
+ for node in newresults.keys():
+ nodeobj = newresults[node]
+ if val in nodeobj['data'].keys():
+ data_str = textwrap.fill(nodeobj['data'][val].strip(),
+ width=20)
+ row.append(data_str)
+ else:
+ row.append("None")
+ x.add_row(row)
+ else:
+ row = []
+ row.append("NA")
+ for node in newresults.keys():
+ nodeobj = newresults[node]
+ data_str = textwrap.fill(nodeobj['data'].strip(),
+ width=20)
+ row.append(data_str)
+ x.add_row(row)
+
+ print x
+
+
+def main():
+ print "main"
+
+
+
+if __name__ == '__main__':
+ main()
diff --git a/pool/shard009/Python/0083424_safe_float_10.3.7.py b/pool/shard009/Python/0083424_safe_float_10.3.7.py
new file mode 100644
index 0000000000000000000000000000000000000000..6fd8b0050e1daab7b680d221abd88b68c171a813
--- /dev/null
+++ b/pool/shard009/Python/0083424_safe_float_10.3.7.py
@@ -0,0 +1,34 @@
+def safe_float(obj):
+ 'safe version of float()'
+ try:
+ retval = float(obj)
+ except (TypeError,ValueError),diag:
+ retval = str(diag)
+ return retval
+def main():
+ 'handles all the data processing'
+ log=open('cardlog.txt','w')
+ try:
+ ccfile=open('carddata.txt','r')
+ except IOError,e:
+ log.write('no txns this month\n')
+ log.close()
+ return
+ txns=ccfile.readlines()
+ ccfile.close()
+ total=0.00
+ log.write('account log:\n')
+
+ for eachTxn in txns:
+ result = safe_float(eachTxn)
+ if isinstance(result,float):
+ print result
+ total+=result
+ log.write('data...processed\n')
+ else:
+ log.write('ignored:%s' %result)
+ print '$%.2f (new balance)' %(total)
+ log.close()
+
+if __name__ == '__main__':
+ main()
diff --git a/pool/shard009/Python/0083426_MultiOutput.py b/pool/shard009/Python/0083426_MultiOutput.py
new file mode 100644
index 0000000000000000000000000000000000000000..591a6f268c6298ed5a99dacd4ea503b79469f7d7
--- /dev/null
+++ b/pool/shard009/Python/0083426_MultiOutput.py
@@ -0,0 +1,45 @@
+import weakref
+
+class YLayer(object):
+ def __init__(self, model, i):
+ self.model = model
+ self.i = i
+ self.dY = None
+ self.next_layers = []
+ @property
+ def Y(self):
+ return self.model.Y[self.i]
+ @Y.setter
+ def Y(self, value):
+ self.model.Y[self.i] = value
+ @property
+ def shape(self):
+ return self.model.Y[self.i].shape
+ def forward(self):
+ self.model.forward()
+ def backward(self):
+ self.model.backward()
+ def reshape(self):
+ self.model.reshape()
+ def input_models(self):
+ yield self.model
+ def input_models_with_index(self):
+ yield (self.model, self.i)
+
+class MultiDY(object):
+ def __init__(self, model):
+ self.model = weakref.proxy(model)
+ def __getitem__(self, i):
+ return self.model.get_YLayers(i).dY
+ def __setitem__(self, i, value):
+ self.model.get_YLayers(i).dY = value
+ def __iter__(self):
+ for dy in self.model.get_YLayers():
+ yield dy
+ def __len__(self):
+ return len(self.model.YLayers)
+
+def get_layer_parent(md):
+ if isinstance(md, YLayer):
+ return md.model
+ return md
diff --git a/pool/shard009/Python/0083427_librator.py b/pool/shard009/Python/0083427_librator.py
new file mode 100644
index 0000000000000000000000000000000000000000..02c4a2e0b6dcd64fca16baac5ebb4d5bfa34c0ad
--- /dev/null
+++ b/pool/shard009/Python/0083427_librator.py
@@ -0,0 +1,66 @@
+"""Command line entry points."""
+from argparse import ArgumentParser
+from os.path import splitext, exists, dirname
+from os import makedirs
+from .packing import pack, unpack
+
+
+def main(clargs=None):
+ """The primary entry point, can pack or unpack a **Librarian** library."""
+ parser = ArgumentParser(
+ description="Handles Librarian card database packaging.")
+ parser.add_argument("cards", type=str,
+ help="Directory of single .crd card files")
+ parser.add_argument("library", type=str,
+ help="Library database file")
+ parser.add_argument("-u", "--unpack", action="store_true", default=False,
+ help="Unpack existing library")
+ args = parser.parse_args(clargs)
+
+ if not exists(dirname(args.cards)):
+ if args.unpack:
+ makedirs(dirname(args.card))
+ else:
+ print("cards directory not found!")
+ return None
+ if args.unpack and not exists(args.library):
+ print("library database not found!")
+ return None
+
+ if args.unpack:
+ unpack(args.library, args.cards)
+ else:
+ pack(args.library, args.cards)
+
+
+CARDTEMPLATE = """
+name: card
+code: 0
+attributes:
+- alive
+abilities:
+ open:
+ - attack
+info:
+ art:
+ - ""
+"""
+
+
+def cardmain(clargs=None):
+ """Generate a blank card file."""
+ parser = ArgumentParser(
+ description="Create a black card file template.")
+ parser.add_argument("cardfile", type=str,
+ help="Card filename")
+ args = parser.parse_args(clargs)
+
+ filename, _ = splitext(args.cardfile)
+ filename += ".crd"
+ filedir = dirname(filename)
+
+ if filedir and not exists(filedir):
+ makedirs(filedir)
+
+ with open(filename, "w") as cardfile:
+ cardfile.write(CARDTEMPLATE.strip())
diff --git a/pool/shard009/Python/0083433_test_robinson.py b/pool/shard009/Python/0083433_test_robinson.py
new file mode 100644
index 0000000000000000000000000000000000000000..a424b752d36fff6b78aff55232c328f9ae3f678b
--- /dev/null
+++ b/pool/shard009/Python/0083433_test_robinson.py
@@ -0,0 +1,187 @@
+# (C) British Crown Copyright 2013 - 2018, Met Office
+#
+# This file is part of cartopy.
+#
+# cartopy is free software: you can redistribute it and/or modify it under
+# the terms of the GNU Lesser General Public License as published by the
+# Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# cartopy is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public License
+# along with cartopy. If not, see .
+"""
+Tests for Robinson projection.
+
+"""
+
+from __future__ import (absolute_import, division, print_function)
+
+import numpy as np
+from numpy.testing import assert_almost_equal, assert_array_almost_equal
+import pytest
+
+import cartopy.crs as ccrs
+from .helpers import check_proj_params
+
+
+_CRS_PC = ccrs.PlateCarree()
+_CRS_ROB = ccrs.Robinson()
+
+# Increase tolerance if using older proj releases
+_TOL = -1 if ccrs.PROJ4_VERSION < (4, 9) else 7
+_LIMIT_TOL = -1 # if ccrs.PROJ4_VERSION < (5, 2, 0) else 7
+
+
+def test_default():
+ robin = ccrs.Robinson()
+ other_args = {'a=6378137.0', 'lon_0=0'}
+ check_proj_params('robin', robin, other_args)
+
+ assert_almost_equal(robin.x_limits,
+ [-17005833.3305252, 17005833.3305252])
+ assert_almost_equal(robin.y_limits,
+ [-8625154.6651000, 8625154.6651000], _LIMIT_TOL)
+
+
+def test_sphere_globe():
+ globe = ccrs.Globe(semimajor_axis=1000, ellipse=None)
+ robin = ccrs.Robinson(globe=globe)
+ other_args = {'a=1000', 'lon_0=0'}
+ check_proj_params('robin', robin, other_args)
+
+ assert_almost_equal(robin.x_limits, [-2666.2696851, 2666.2696851])
+ assert_almost_equal(robin.y_limits, [-1352.3000000, 1352.3000000],
+ _LIMIT_TOL)
+
+
+def test_ellipse_globe():
+ globe = ccrs.Globe(ellipse='WGS84')
+ with pytest.warns(UserWarning,
+ match='does not handle elliptical globes.') as w:
+ robin = ccrs.Robinson(globe=globe)
+ assert len(w) == 1
+
+ other_args = {'ellps=WGS84', 'lon_0=0'}
+ check_proj_params('robin', robin, other_args)
+
+ # Limits are the same as default since ellipses are not supported.
+ assert_almost_equal(robin.x_limits, [-17005833.3305252, 17005833.3305252])
+ assert_almost_equal(robin.y_limits, [-8625154.6651000, 8625154.6651000],
+ _LIMIT_TOL)
+
+
+def test_eccentric_globe():
+ globe = ccrs.Globe(semimajor_axis=1000, semiminor_axis=500,
+ ellipse=None)
+ with pytest.warns(UserWarning,
+ match='does not handle elliptical globes.') as w:
+ robin = ccrs.Robinson(globe=globe)
+ assert len(w) == 1
+
+ other_args = {'a=1000', 'b=500', 'lon_0=0'}
+ check_proj_params('robin', robin, other_args)
+
+ # Limits are the same as spheres since ellipses are not supported.
+ assert_almost_equal(robin.x_limits, [-2666.2696851, 2666.2696851])
+ assert_almost_equal(robin.y_limits, [-1352.3000000, 1352.3000000],
+ _LIMIT_TOL)
+
+
+def test_offset():
+ crs = ccrs.Robinson()
+ crs_offset = ccrs.Robinson(false_easting=1234, false_northing=-4321)
+ other_args = {'a=6378137.0', 'lon_0=0', 'x_0=1234', 'y_0=-4321'}
+ check_proj_params('robin', crs_offset, other_args)
+ assert tuple(np.array(crs.x_limits) + 1234) == crs_offset.x_limits
+ assert tuple(np.array(crs.y_limits) - 4321) == crs_offset.y_limits
+
+
+@pytest.mark.parametrize('lon', [-10.0, 10.0])
+def test_central_longitude(lon):
+ robin = ccrs.Robinson(central_longitude=lon)
+ other_args = {'a=6378137.0', 'lon_0={}'.format(lon)}
+ check_proj_params('robin', robin, other_args)
+
+ assert_almost_equal(robin.x_limits,
+ [-17005833.3305252, 17005833.3305252],
+ decimal=5)
+ assert_almost_equal(robin.y_limits,
+ [-8625154.6651000, 8625154.6651000], _LIMIT_TOL)
+
+
+def test_transform_point():
+ """
+ Mostly tests the workaround for a specific problem.
+ Problem report in: https://github.com/SciTools/cartopy/issues/23
+ Fix covered in: https://github.com/SciTools/cartopy/pull/277
+ """
+
+ # this way has always worked
+ result = _CRS_ROB.transform_point(35.0, 70.0, _CRS_PC)
+ assert_array_almost_equal(result, (2376187.27182751, 7275317.81573085),
+ _TOL)
+
+ # this always did something, but result has altered
+ result = _CRS_ROB.transform_point(np.nan, 70.0, _CRS_PC)
+ assert np.all(np.isnan(result))
+
+ # this used to crash + is now fixed
+ result = _CRS_ROB.transform_point(35.0, np.nan, _CRS_PC)
+ assert np.all(np.isnan(result))
+
+
+def test_transform_points():
+ """
+ Mostly tests the workaround for a specific problem.
+ Problem report in: https://github.com/SciTools/cartopy/issues/23
+ Fix covered in: https://github.com/SciTools/cartopy/pull/277
+ """
+
+ # these always worked
+ result = _CRS_ROB.transform_points(_CRS_PC,
+ np.array([35.0]),
+ np.array([70.0]))
+ assert_array_almost_equal(result,
+ [[2376187.27182751, 7275317.81573085, 0]], _TOL)
+
+ result = _CRS_ROB.transform_points(_CRS_PC,
+ np.array([35.0]),
+ np.array([70.0]),
+ np.array([0.0]))
+ assert_array_almost_equal(result,
+ [[2376187.27182751, 7275317.81573085, 0]], _TOL)
+
+ # this always did something, but result has altered
+ result = _CRS_ROB.transform_points(_CRS_PC,
+ np.array([np.nan]),
+ np.array([70.0]))
+ assert np.all(np.isnan(result))
+
+ # this used to crash + is now fixed
+ result = _CRS_ROB.transform_points(_CRS_PC,
+ np.array([35.0]),
+ np.array([np.nan]))
+ assert np.all(np.isnan(result))
+
+ # multipoint case
+ x = np.array([10.0, 21.0, 0.0, 77.7, np.nan, 0.0])
+ y = np.array([10.0, np.nan, 10.0, 77.7, 55.5, 0.0])
+ z = np.array([10.0, 0.0, 0.0, np.nan, 55.5, 0.0])
+ expect_result = np.array(
+ [[9.40422591e+05, 1.06952091e+06, 1.00000000e+01],
+ [11.1, 11.2, 11.3],
+ [0.0, 1069520.91213902, 0.0],
+ [22.1, 22.2, 22.3],
+ [33.1, 33.2, 33.3],
+ [0.0, 0.0, 0.0]])
+ result = _CRS_ROB.transform_points(_CRS_PC, x, y, z)
+ assert result.shape == (6, 3)
+ assert np.all(np.isnan(result[[1, 3, 4], :]))
+ result[[1, 3, 4], :] = expect_result[[1, 3, 4], :]
+ assert not np.any(np.isnan(result))
+ assert np.allclose(result, expect_result)
diff --git a/pool/shard009/Python/0083434_models.py b/pool/shard009/Python/0083434_models.py
new file mode 100644
index 0000000000000000000000000000000000000000..80bde0972873c5a83bb8a38c2a2f3e8114811d3c
--- /dev/null
+++ b/pool/shard009/Python/0083434_models.py
@@ -0,0 +1,119 @@
+"""An organization is an customer, an install. It can be a company,
+a non-profit, a social group (such as a running club), a municipality, etc.
+ Each org can have multiple Campaigns, and can brand the site.
+"""
+
+# Copyright 2010,2011 Good Energy Research Inc. ,
+#
+# This file is part of Good Energy.
+#
+# Good Energy is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Affero General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# Good Energy is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU Affero General Public License for more details.
+#
+# You should have received a copy of the GNU Affero General Public License
+# along with Good Energy. If not, see .
+#
+
+
+# Disable the pylint check for dynamically added attributes. This happens a lot
+# with Django DB model usage.
+# pylint: disable-msg=E1101
+# pylint: disable-msg=E1103
+
+from django.db import models
+from django.core.cache import cache
+
+
+def org_files_dir(instance, filename):
+ """The path to store files for an instance of Organization,
+ relative to MEDIA_ROOT"""
+ return 'organization/' + instance.slug + '/' + filename
+
+
+class OrganizationManager(models.Manager): # pylint: disable-msg=R0904
+ """Methods above the level of a single org"""
+
+ def get_cached(self, domain):
+ """The Organization who's domain is 'domain'"""
+ cache_key = 'ge_org_map'
+ org_map = cache.get(cache_key)
+
+ if not org_map:
+ org_map = {}
+ for org in Organization.objects.all():
+ org_map[org.domain] = org
+ cache.set(cache_key, org_map)
+
+ try:
+ org = org_map[domain]
+ except KeyError:
+ # Maybe a new org - try loading
+ org = self.get(domain=domain)
+ org_map[domain] = org
+ cache.set(cache_key, org_map)
+
+ return org
+
+
+class Organization(models.Model):
+ """Top level object - has Campaigns, branding, etc"""
+
+ objects = OrganizationManager()
+
+ name = models.CharField(max_length=100)
+ slug = models.SlugField(max_length=100)
+
+ logo = models.ImageField(upload_to=org_files_dir, blank=True, null=True)
+ css = models.FileField(upload_to=org_files_dir, blank=True, null=True)
+
+ header_html = models.FileField(
+ upload_to=org_files_dir, blank=True, null=True)
+ footer_html = models.FileField(
+ upload_to=org_files_dir, blank=True, null=True)
+ favicon = models.FileField(
+ upload_to=org_files_dir, blank=True, null=True)
+
+ domain = models.CharField(max_length=100)
+ home_url = models.CharField(max_length=100, null=True, blank=True)
+
+ def __unicode__(self):
+ return self.name
+
+ def has_custom_header(self):
+ """Does this organization provide HTML for it's own header?"""
+ return self.header_html
+
+ def has_custom_footer(self):
+ """Does this organization provide HTML for it's own footer?"""
+ return self.footer_html
+
+ def header(self):
+ """The HTML for this organization's header"""
+
+ header_file = open(self.header_html.path, 'rt')
+ html = header_file.read()
+ header_file.close()
+ return html
+
+ def footer(self):
+ """The HTML for this organization's footer"""
+
+ footer_file = open(self.footer_html.path, 'rt')
+ html = footer_file.read()
+ footer_file.close()
+ return html
+
+ def home(self):
+ """The URL of companies home page"""
+ if self.home_url:
+ return self.home_url
+ else:
+ return '/'
+
diff --git a/pool/shard009/Python/0083435_convert_funnel_original_tf_checkpoint_to_pytorch.py b/pool/shard009/Python/0083435_convert_funnel_original_tf_checkpoint_to_pytorch.py
new file mode 100644
index 0000000000000000000000000000000000000000..b13d6dcd1007a78b482148bd9f487e4d2a8ee7ea
--- /dev/null
+++ b/pool/shard009/Python/0083435_convert_funnel_original_tf_checkpoint_to_pytorch.py
@@ -0,0 +1,66 @@
+# coding=utf-8
+# Copyright 2020 The HuggingFace Inc. team.
+#
+# 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.
+"""Convert Funnel checkpoint."""
+
+
+import argparse
+
+import torch
+
+from transformers import FunnelBaseModel, FunnelConfig, FunnelModel, load_tf_weights_in_funnel
+from transformers.utils import logging
+
+
+logging.set_verbosity_info()
+
+
+def convert_tf_checkpoint_to_pytorch(tf_checkpoint_path, config_file, pytorch_dump_path, base_model):
+ # Initialise PyTorch model
+ config = FunnelConfig.from_json_file(config_file)
+ print(f"Building PyTorch model from configuration: {config}")
+ model = FunnelBaseModel(config) if base_model else FunnelModel(config)
+
+ # Load weights from tf checkpoint
+ load_tf_weights_in_funnel(model, config, tf_checkpoint_path)
+
+ # Save pytorch-model
+ print(f"Save PyTorch model to {pytorch_dump_path}")
+ torch.save(model.state_dict(), pytorch_dump_path)
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser()
+ # Required parameters
+ parser.add_argument(
+ "--tf_checkpoint_path", default=None, type=str, required=True, help="Path to the TensorFlow checkpoint path."
+ )
+ parser.add_argument(
+ "--config_file",
+ default=None,
+ type=str,
+ required=True,
+ help="The config json file corresponding to the pre-trained model. \n"
+ "This specifies the model architecture.",
+ )
+ parser.add_argument(
+ "--pytorch_dump_path", default=None, type=str, required=True, help="Path to the output PyTorch model."
+ )
+ parser.add_argument(
+ "--base_model", action="store_true", help="Whether you want just the base model (no decoder) or not."
+ )
+ args = parser.parse_args()
+ convert_tf_checkpoint_to_pytorch(
+ args.tf_checkpoint_path, args.config_file, args.pytorch_dump_path, args.base_model
+ )
diff --git a/pool/shard009/Python/0083436_intersphinx.py b/pool/shard009/Python/0083436_intersphinx.py
new file mode 100644
index 0000000000000000000000000000000000000000..c889e4c1603dc1dae83f38cea546edfa2dc6c770
--- /dev/null
+++ b/pool/shard009/Python/0083436_intersphinx.py
@@ -0,0 +1,76 @@
+"""
+Parsers for intersphinx inventory files
+
+Taken from `sphinx.ext.intersphinx`
+
+"""
+
+import re
+import codecs
+import zlib
+
+b = str
+UTF8StreamReader = codecs.lookup('utf-8')[2]
+
+
+def read_inventory_v1(f, uri, join):
+ f = UTF8StreamReader(f)
+ invdata = {}
+ line = f.next()
+ projname = line.rstrip()[11:]
+ line = f.next()
+ version = line.rstrip()[11:]
+ for line in f:
+ name, type, location = line.rstrip().split(None, 2)
+ location = join(uri, location)
+ # version 1 did not add anchors to the location
+ if type == 'mod':
+ type = 'py:module'
+ location += '#module-' + name
+ else:
+ type = 'py:' + type
+ location += '#' + name
+ invdata.setdefault(type, {})[name] = (projname, version, location, '-')
+ return invdata
+
+
+def read_inventory_v2(f, uri, join, bufsize=16*1024):
+ invdata = {}
+ line = f.readline()
+ projname = line.rstrip()[11:].decode('utf-8')
+ line = f.readline()
+ version = line.rstrip()[11:].decode('utf-8')
+ line = f.readline().decode('utf-8')
+ if 'zlib' not in line:
+ raise ValueError
+
+ def read_chunks():
+ decompressor = zlib.decompressobj()
+ for chunk in iter(lambda: f.read(bufsize), b''):
+ yield decompressor.decompress(chunk)
+ yield decompressor.flush()
+
+ def split_lines(chunkiter):
+ buf = b''
+ for chunk in chunkiter:
+ buf += chunk
+ lineend = buf.find(b'\n')
+ while lineend != -1:
+ yield buf[:lineend].decode('utf-8')
+ buf = buf[lineend + 1:]
+ lineend = buf.find(b'\n')
+ assert not buf
+
+ for line in split_lines(read_chunks()):
+ # be careful to handle names with embedded spaces correctly
+ m = re.match(r'(?x)(.+?)\s+(\S*:\S*)\s+(\S+)\s+(\S+)\s+(.*)',
+ line.rstrip())
+ if not m:
+ continue
+ name, type, prio, location, dispname = m.groups()
+ if location.endswith('$'):
+ location = location[:-1] + name
+ location = join(uri, location)
+ invdata.setdefault(type, {})[name] = (projname, version,
+ location, dispname)
+ return invdata
diff --git a/pool/shard009/Python/0083438_iotop.py b/pool/shard009/Python/0083438_iotop.py
new file mode 100644
index 0000000000000000000000000000000000000000..06f8d2accdcca115c98a2ed852e06645e7445e30
--- /dev/null
+++ b/pool/shard009/Python/0083438_iotop.py
@@ -0,0 +1,163 @@
+#!/usr/bin/env python
+
+# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
+# Use of this source code is governed by a BSD-style license that can be
+# found in the LICENSE file.
+
+"""
+A clone of iotop (http://guichaz.free.fr/iotop/) showing real time
+disk I/O statistics.
+
+It works on Linux only (FreeBSD and OSX are missing support for IO
+counters).
+It doesn't work on Windows as curses module is required.
+
+Author: Giampaolo Rodola'
+"""
+
+import os
+import sys
+import psutil
+if not hasattr(psutil.Process, 'io_counters') or os.name != 'posix':
+ sys.exit('platform not supported')
+import time
+import curses
+import atexit
+
+
+# --- curses stuff
+def tear_down():
+ win.keypad(0)
+ curses.nocbreak()
+ curses.echo()
+ curses.endwin()
+
+win = curses.initscr()
+atexit.register(tear_down)
+curses.endwin()
+lineno = 0
+
+
+def print_line(line, highlight=False):
+ """A thin wrapper around curses's addstr()."""
+ global lineno
+ try:
+ if highlight:
+ line += " " * (win.getmaxyx()[1] - len(line))
+ win.addstr(lineno, 0, line, curses.A_REVERSE)
+ else:
+ win.addstr(lineno, 0, line, 0)
+ except curses.error:
+ lineno = 0
+ win.refresh()
+ raise
+ else:
+ lineno += 1
+# --- /curses stuff
+
+
+def bytes2human(n):
+ """
+ >>> bytes2human(10000)
+ '9.8 K/s'
+ >>> bytes2human(100001221)
+ '95.4 M/s'
+ """
+ symbols = ('K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y')
+ prefix = {}
+ for i, s in enumerate(symbols):
+ prefix[s] = 1 << (i + 1) * 10
+ for s in reversed(symbols):
+ if n >= prefix[s]:
+ value = float(n) / prefix[s]
+ return '%.2f %s/s' % (value, s)
+ return '%.2f B/s' % (n)
+
+
+def poll(interval):
+ """Calculate IO usage by comparing IO statics before and
+ after the interval.
+ Return a tuple including all currently running processes
+ sorted by IO activity and total disks I/O activity.
+ """
+ # first get a list of all processes and disk io counters
+ procs = [p for p in psutil.process_iter()]
+ for p in procs[:]:
+ try:
+ p._before = p.io_counters()
+ except psutil.Error:
+ procs.remove(p)
+ continue
+ disks_before = psutil.disk_io_counters()
+
+ # sleep some time
+ time.sleep(interval)
+
+ # then retrieve the same info again
+ for p in procs[:]:
+ try:
+ p._after = p.io_counters()
+ p._cmdline = ' '.join(p.cmdline())
+ if not p._cmdline:
+ p._cmdline = p.name()
+ p._username = p.username()
+ except psutil.NoSuchProcess:
+ procs.remove(p)
+ disks_after = psutil.disk_io_counters()
+
+ # finally calculate results by comparing data before and
+ # after the interval
+ for p in procs:
+ p._read_per_sec = p._after.read_bytes - p._before.read_bytes
+ p._write_per_sec = p._after.write_bytes - p._before.write_bytes
+ p._total = p._read_per_sec + p._write_per_sec
+
+ disks_read_per_sec = disks_after.read_bytes - disks_before.read_bytes
+ disks_write_per_sec = disks_after.write_bytes - disks_before.write_bytes
+
+ # sort processes by total disk IO so that the more intensive
+ # ones get listed first
+ processes = sorted(procs, key=lambda p: p._total, reverse=True)
+
+ return (processes, disks_read_per_sec, disks_write_per_sec)
+
+
+def refresh_window(procs, disks_read, disks_write):
+ """Print results on screen by using curses."""
+ curses.endwin()
+ templ = "%-5s %-7s %11s %11s %s"
+ win.erase()
+
+ disks_tot = "Total DISK READ: %s | Total DISK WRITE: %s" \
+ % (bytes2human(disks_read), bytes2human(disks_write))
+ print_line(disks_tot)
+
+ header = templ % ("PID", "USER", "DISK READ", "DISK WRITE", "COMMAND")
+ print_line(header, highlight=True)
+
+ for p in procs:
+ line = templ % (
+ p.pid,
+ p._username[:7],
+ bytes2human(p._read_per_sec),
+ bytes2human(p._write_per_sec),
+ p._cmdline)
+ try:
+ print_line(line)
+ except curses.error:
+ break
+ win.refresh()
+
+
+def main():
+ try:
+ interval = 0
+ while 1:
+ args = poll(interval)
+ refresh_window(*args)
+ interval = 1
+ except (KeyboardInterrupt, SystemExit):
+ pass
+
+if __name__ == '__main__':
+ main()
diff --git a/pool/shard009/Python/0083440_root_to_leaf.py b/pool/shard009/Python/0083440_root_to_leaf.py
new file mode 100644
index 0000000000000000000000000000000000000000..8dc6bc15ef928f1a9c8fd6556ea0be1597d362bf
--- /dev/null
+++ b/pool/shard009/Python/0083440_root_to_leaf.py
@@ -0,0 +1,21 @@
+class Node(object):
+ def __init__(self,val, left = None, right = None):
+ self.val = val
+ self.left = left
+ self.right = right
+
+def root_to_leaf(root,path):
+ if root.left is None and root.right is None:
+ path.append(root.val)
+ print(" ".join(map(str,path)))
+ return
+
+ path.append(root.val)
+ root_to_leaf(root.left, path)
+ path.pop()
+ root_to_leaf(root.right, path)
+ path.pop()
+
+tree = Node(1,Node(2,Node(4),Node(5)),Node(3,Node(6),Node(7)))
+
+root_to_leaf(tree,[])
diff --git a/pool/shard009/Python/0083441_AddNodeToPCU.py b/pool/shard009/Python/0083441_AddNodeToPCU.py
new file mode 100644
index 0000000000000000000000000000000000000000..29044569030877b0dd5d269ea955c6bb5d7d0b69
--- /dev/null
+++ b/pool/shard009/Python/0083441_AddNodeToPCU.py
@@ -0,0 +1,74 @@
+from PLC.Faults import *
+from PLC.Method import Method
+from PLC.Parameter import Parameter, Mixed
+from PLC.Nodes import Node, Nodes
+from PLC.PCUs import PCU, PCUs
+from PLC.Sites import Site, Sites
+from PLC.Auth import Auth
+
+class AddNodeToPCU(Method):
+ """
+ Adds a node to a port on a PCU. Faults if the node has already
+ been added to the PCU or if the port is already in use.
+
+ Non-admins may only update PCUs at their sites.
+
+ Returns 1 if successful, faults otherwise.
+ """
+
+ roles = ['admin', 'pi', 'tech']
+
+ accepts = [
+ Auth(),
+ Mixed(Node.fields['node_id'],
+ Node.fields['hostname']),
+ PCU.fields['pcu_id'],
+ Parameter(int, 'PCU port number')
+ ]
+
+ returns = Parameter(int, '1 if successful')
+
+ def call(self, auth, node_id_or_hostname, pcu_id, port):
+ # Get node
+ nodes = Nodes(self.api, [node_id_or_hostname])
+ if not nodes:
+ raise PLCInvalidArgument("No such node")
+ node = nodes[0]
+
+ if node['peer_id'] is not None:
+ raise PLCInvalidArgument("Not a local node")
+
+ # Get PCU
+ pcus = PCUs(self.api, [pcu_id])
+ if not pcus:
+ raise PLCInvalidArgument("No such PCU")
+ pcu = pcus[0]
+
+ if 'admin' not in self.caller['roles']:
+ ok = False
+ sites = Sites(self.api, self.caller['site_ids'])
+ for site in sites:
+ if pcu['pcu_id'] in site['pcu_ids']:
+ ok = True
+ break
+ if not ok:
+ raise PLCPermissionDenied("Not allowed to update that PCU")
+
+ # Add node to PCU
+ if node['node_id'] in pcu['node_ids']:
+ raise PLCInvalidArgument("Node already controlled by PCU")
+
+ if node['site_id'] != pcu['site_id']:
+ raise PLCInvalidArgument("Node is at a different site than this PCU")
+
+ if port in pcu['ports']:
+ raise PLCInvalidArgument("PCU port already in use")
+
+ pcu.add_node(node, port)
+
+ # Logging variables
+ self.event_objects = {'Node': [node['node_id']],
+ 'PCU': [pcu['pcu_id']]}
+ self.message = 'Node %d added to pcu %d on port %d' % \
+ (node['node_id'], pcu['pcu_id'], port)
+ return 1
diff --git a/pool/shard009/Python/0083442_unittests_test.py b/pool/shard009/Python/0083442_unittests_test.py
new file mode 100644
index 0000000000000000000000000000000000000000..f65db75ecba9067e55e78cca3900cd9a47a438bf
--- /dev/null
+++ b/pool/shard009/Python/0083442_unittests_test.py
@@ -0,0 +1,204 @@
+#!/usr/bin/env python
+
+# Copyright (C) 2017-2019 SignalFx, Inc. All rights reserved.
+# Copyright (C) 2020 Splunk, Inc. All rights reserved.
+
+from httmock import all_requests, HTTMock
+import json
+import unittest
+from six.moves.urllib import parse
+import signalfx.signalflow.ws
+import struct
+
+responses_map = {
+ 'GET_DETECTOR': {
+ 'path': '/v2/detector/abc123',
+ 'content': open('tests/fixtures/get_detector_abc123.json').read(),
+ 'status_code': 200,
+ 'method': 'GET',
+ },
+ 'GET_DETECTOR_INCIDENTS': {
+ 'path': '/v2/detector/abc123/incidents',
+ 'content': '[]',
+ 'status_code': 200,
+ 'method': 'GET',
+ },
+ 'GET_DETECTOR_EVENTS': {
+ 'path': '/v2/detector/abc123/events',
+ 'content': '[]',
+ 'status_code': 200,
+ 'method': 'GET',
+ },
+ 'GET_INCIDENTS': {
+ 'path': '/v2/incident',
+ 'content': open('tests/fixtures/get_incidents.json').read(),
+ 'status_code': 200,
+ 'method': 'GET',
+ 'params': {
+ 'include_resolved': 'true',
+ 'offset': '0',
+ }
+ },
+ 'GET_INCIDENT': {
+ 'path': '/v2/incident/abc123',
+ 'content': open('tests/fixtures/get_incident_abc123.json').read(),
+ 'status_code': 200,
+ 'method': 'GET',
+ },
+ 'CLEAR_INCIDENT': {
+ 'path': '/v2/incident/abc123/clear',
+ 'content': '',
+ 'status_code': 200,
+ 'method': 'PUT',
+ },
+ 'GET_DATALINK': {
+ 'path': '/v2/crosslink/abc123',
+ 'content': open('tests/fixtures/get_datalink_abc123.json').read(),
+ 'status_code': 200,
+ 'method': 'GET',
+ }
+}
+
+
+# Generates a function that can be used with HTTMock to test the endpoint. It
+# will validate the params, URL and Method, whilst returning a spec response.
+def mock_maker(name):
+ @all_requests
+ def mock_responder(url, request):
+ spec = responses_map.get(name)
+ if spec is None:
+ raise Exception("Unknown mock")
+
+ if spec.get('path') != url.path or \
+ request.method != spec.get('method'):
+ return {
+ 'content': 'Unknown URL' + url.path,
+ 'status_code': 400,
+ }
+
+ if spec.get('params') is not None:
+ incoming_params = parse.parse_qs(url.query)
+ for k, v in spec.get('params').items():
+ param = incoming_params.get(k)
+ if param is None or param[0] != v:
+ return {
+ 'content': 'Missing or incorrection query param: ' + k,
+ 'status_code': 400
+ }
+
+ return {
+ 'content': spec.get('content'),
+ 'status_code': spec.get('status_code'),
+ }
+ return mock_responder
+
+
+class RESTTest(unittest.TestCase):
+
+ def test_get_detector(self):
+ name = 'GET_DETECTOR'
+ with HTTMock(mock_maker(name)):
+ with signalfx.SignalFx().rest('authkey') as sfx:
+ orig_detector = json.loads(responses_map[name]['content'])
+ detector = sfx.get_detector('abc123')
+ self.assertEqual(orig_detector['id'], detector['id'])
+
+ def test_get_detector_incidents(self):
+ name = 'GET_DETECTOR_INCIDENTS'
+ with HTTMock(mock_maker(name)):
+ with signalfx.SignalFx().rest('authkey') as sfx:
+ incidents = sfx.get_detector_incidents('abc123')
+ self.assertEqual(0, len(incidents))
+
+ def test_get_detector_events(self):
+ name = 'GET_DETECTOR_EVENTS'
+ with HTTMock(mock_maker(name)):
+ with signalfx.SignalFx().rest('authkey') as sfx:
+ events = sfx.get_detector_events('abc123')
+ self.assertEqual(0, len(events))
+
+ def test_get_incidents(self):
+ name = 'GET_INCIDENTS'
+ with HTTMock(mock_maker(name)):
+ with signalfx.SignalFx().rest('authkey') as sfx:
+ orig_incidents = json.loads(responses_map[name]['content'])
+ incidents = sfx.get_incidents(include_resolved=True)
+ self.assertEqual(len(orig_incidents), len(incidents))
+
+ def test_get_incident(self):
+ name = 'GET_INCIDENT'
+ with HTTMock(mock_maker(name)):
+ with signalfx.SignalFx().rest('authkey') as sfx:
+ orig_incident = json.loads(responses_map[name]['content'])
+ incident = sfx.get_incident('abc123')
+ self.assertEqual(orig_incident['incidentId'],
+ incident['incidentId'])
+
+ def test_clear_incident(self):
+ name = 'CLEAR_INCIDENT'
+ with HTTMock(mock_maker(name)):
+ with signalfx.SignalFx().rest('authkey') as sfx:
+ resp = sfx.clear_incident('abc123')
+ self.assertEqual(200, resp.status_code)
+
+ def test_get_datalink(self):
+ name = 'GET_DATALINK'
+ with HTTMock(mock_maker(name)):
+ with signalfx.SignalFx().rest('authkey') as sfx:
+ dl = sfx.get_datalink('abc123')
+ self.assertEqual(dl['id'], 'abc123')
+
+
+class WebSocketTransportTest(unittest.TestCase):
+
+ def test_decode_binary_format_v1(self):
+ data = struct.pack(
+ '!BBxx16sqiBqqBqd',
+ 1, 5, b'foo', 1234,
+ 2, 1, 10, 42, 2, 11, 3.14)
+ ws = signalfx.signalflow.ws.WebSocketTransport('token')
+ decoded = ws.decode_binary_message(data)
+ self.assertEqual(decoded, {
+ 'type': 'data',
+ 'channel': u'foo',
+ 'logicalTimestampMs': 1234,
+ 'maxDelayMs': None,
+ 'data': [{
+ 'tsId': u'AAAAAAAAAAo',
+ 'value': 42,
+ }, {
+ 'tsId': u'AAAAAAAAAAs',
+ 'value': 3.14,
+ }]
+ })
+
+ def test_decode_binary_format_v3(self):
+ data = struct.pack(
+ '!BBxx16sqqiBqqBqdBqqBqq',
+ 3, 5, b'foo', 1234, 4321,
+ 4, 1, 10, 42, 2, 11, 3.14, 0, 12, 0, 3, 13, 42)
+ ws = signalfx.signalflow.ws.WebSocketTransport('token')
+ decoded = ws.decode_binary_message(data)
+ self.assertEqual(decoded, {
+ 'type': 'data',
+ 'channel': u'foo',
+ 'logicalTimestampMs': 1234,
+ 'maxDelayMs': 4321,
+ 'data': [{
+ 'tsId': u'AAAAAAAAAAo',
+ 'value': 42,
+ }, {
+ 'tsId': u'AAAAAAAAAAs',
+ 'value': 3.14,
+ }, {
+ 'tsId': u'AAAAAAAAAAw',
+ 'value': None,
+ }, {
+ 'tsId': u'AAAAAAAAAA0',
+ 'value': 42
+ }]
+ })
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/pool/shard009/Python/0083446_setup.py b/pool/shard009/Python/0083446_setup.py
new file mode 100644
index 0000000000000000000000000000000000000000..0d8723c4e53a1d512c24cbd2d9896f667fb75c76
--- /dev/null
+++ b/pool/shard009/Python/0083446_setup.py
@@ -0,0 +1,230 @@
+#!/usr/bin/env python
+# -*- coding: UTF-8 -*-
+# vim: set fileencoding=utf-8
+# Run as root
+
+'''
+ This script allows to install latch plugin in ssh Server in some UNIX systems (like Linux)
+ Copyright (C) 2013 Eleven Paths
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Lesser General Public
+ License as published by the Free Software Foundation; either
+ version 2.1 of the License, or (at your option) any later version.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public
+ License along with this library; if not, write to the Free Software
+ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+'''
+
+
+import sys
+import os
+import shutil
+
+from latchHelper import *
+from translation import *
+
+
+
+if len(sys.argv) == 3 and sys.argv[1] == "-f":
+ secret_key = getConfigParameter("secret_key", sys.argv[2])
+ app_id = getConfigParameter("app_id", sys.argv[2])
+ if app_id == None or secret_key == None:
+ print(CANT_READ_CONFIG_FILE_MSG);
+ exit(1)
+
+ replaceConfigParameters(app_id, secret_key)
+else:
+ print(INCORRECT_SETUP_USE_MSG);
+ exit(1);
+
+'''
+if os.path.isfile(SSHD_PAM_CONFIG_FILE):
+ # read openvpn PAM config file
+ f = open(SSHD_PAM_CONFIG_FILE,"r")
+ lines = f.readlines()
+ f.close()
+ # find latch
+ found = False
+ for line in lines:
+ if line.find(LATCH_PAM_CONFIG) != -1 :
+ found = True
+ break
+ if not found:
+ # add latch PAM configuration
+ f = open(SSHD_PAM_CONFIG_FILE,"a")
+ f.write(LATCH_PAM_CONFIG)
+ f.close()
+else:
+ exit(1)
+'''
+
+if os.path.isfile(SSHD_PAM_CONFIG_FILE):
+ # read sshd PAM config file
+ f = open(SSHD_PAM_CONFIG_FILE,"r")
+ lines = f.readlines()
+ f.close()
+
+ shutil.copy(SSHD_PAM_CONFIG_FILE, SSHD_PAM_CONFIG_FILE + "~")
+
+ f = open(SSHD_PAM_CONFIG_FILE,"w");
+ # find password-auth
+ found = False
+ for line in lines:
+ if equalSplit(line, AUTH_INCLUDE_PASSWORD_AUTH):
+ f.write(AUTH_INCLUDE_PASSWD_AUTH_SSHD + "\n")
+ found = True
+ else:
+ f.write(line)
+ f.close()
+ if not found:
+ # ubuntu version
+ # add latch PAM configuration
+ f = open(SSHD_PAM_CONFIG_FILE,"a")
+ f.write(AUTH_REQUIRED_LATCH_PAM + "\n")
+ f.close()
+ else:
+ # centos version
+ if os.path.isfile(PASSWORD_AUTH_PAM_CONFIG_FILE):
+ # read password-auth config file
+ f = open(PASSWORD_AUTH_PAM_CONFIG_FILE,"r")
+ lines = f.readlines()
+ f.close()
+ # write password-auth-sshd config file
+ f = open(PASSWORD_AUTH_SSHD_PAM_CONFIG_FILE,"w");
+ # find 'auth sufficient pam_unix.so nullok try_first_pass'
+ for line in lines:
+ if equalSplit(line, AUTH_SUFFICIENT_PAM_UNIX):
+ f.write(AUTH_REQUISITE_PAM_UNIX + "\n")
+ f.write(AUTH_SUFFICIENT_LATCH_PAM + "\n")
+ else:
+ f.write(line)
+ f.close()
+
+ else:
+ exit(1)
+else:
+ exit(1)
+
+
+
+# read sshd_config file
+f = open(SSHD_CONFIG,"r")
+lines = f.readlines()
+f.close()
+
+#forceCommandWrapper = False
+authenticationMethodsKey = False
+passwordAuthenticationKey = False
+challengeResponseAuthenticationKey = False
+usePamKey = False
+
+shutil.move(SSHD_CONFIG, SSHD_CONFIG + "~")
+
+# Put ChallengeResponseAuthentication yes
+# Put UsePAM yes
+# Put PasswordAuthentication no
+f = open(SSHD_CONFIG,"w");
+for line in lines:
+ if "ChallengeResponseAuthentication" in line and "#" not in line:
+ f.write("ChallengeResponseAuthentication yes\n")
+ challengeResponseAuthenticationKey = True
+ elif "UsePAM" in line and "#" not in line:
+ f.write("UsePAM yes\n")
+ usePamKey = True
+ elif "PasswordAuthentication" in line and "#" not in line:
+ f.write("PasswordAuthentication no\n")
+ passwordAuthenticationKey = True
+ elif "AuthenticationMethods" in line and "#" not in line:
+ #f.write("AuthenticationMethods keyboard-interactive\n")
+ authenticationMethodsKey = True
+ else:
+ f.write(line)
+ '''
+ if line.find("ForceCommand " + WRAPPER_EXE) != -1 :
+ forceCommandWrapper = True
+ '''
+f.close();
+
+if not usePamKey:
+ f = open(SSHD_CONFIG,"a")
+ f.write("UsePAM yes\n")
+ f.close()
+if not challengeResponseAuthenticationKey:
+ f = open(SSHD_CONFIG,"a")
+ f.write("ChallengeResponseAuthentication yes\n")
+ f.close()
+if not passwordAuthenticationKey:
+ f = open(SSHD_CONFIG,"a")
+ f.write("PasswordAuthentication no\n")
+ f.close()
+'''
+if not authenticationMethodsKey:
+ f = open(SSHD_CONFIG,"a")
+ f.write("AuthenticationMethods keyboard-interactive\n")
+ f.close()
+'''
+'''
+if not forceCommandWrapper:
+ # add latch to ssh configuration
+ f = open(SSHD_CONFIG,"a")
+ f.write("ForceCommand " + WRAPPER_EXE + "\n")
+ f.close()
+'''
+'''
+# install the wrapper sshd.sh in /usr/sbin
+if not os.path.isfile(WRAPPER_SH):
+ os.open (WRAPPER_SH, os.O_CREAT, int("0554",8))
+ shutil.copyfile('sshd.sh', WRAPPER_SH)
+'''
+'''
+if not os.path.isfile(WRAPPER_PY):
+ os.open (WRAPPER_PY, os.O_CREAT, int("0500",8))
+ shutil.copyfile('sshd.py', WRAPPER_PY)
+'''
+
+# install latch in /usr/lib/openssh
+if not os.path.isdir(LATCH_PATH):
+ os.mkdir(LATCH_PATH)
+if not os.path.isdir(LATCH_OPENSSH_PATH):
+ os.mkdir(LATCH_OPENSSH_PATH)
+if not os.path.isfile(LATCH_PLUGIN_GUI):
+ os.open (LATCH_PLUGIN_GUI, os.O_CREAT, int("0100",8))
+ shutil.copyfile('latchPluginGUI.py', LATCH_PLUGIN_GUI)
+if not os.path.isfile(SETTINGS_PLUGIN_GUI):
+ os.open (SETTINGS_PLUGIN_GUI, os.O_CREAT, int("0100",8))
+ shutil.copyfile('settingsGUI.py', SETTINGS_PLUGIN_GUI)
+if not os.path.isfile(PAIR_PLUGIN):
+ os.open (PAIR_PLUGIN, os.O_CREAT, int("0100",8))
+ shutil.copyfile('pair.py', PAIR_PLUGIN)
+if not os.path.isfile(UNPAIR_PLUGIN):
+ os.open (UNPAIR_PLUGIN, os.O_CREAT, int("0100",8))
+ shutil.copyfile('unpair.py', UNPAIR_PLUGIN)
+if not os.path.isfile(SETTINGS_PLUGIN):
+ os.open (SETTINGS_PLUGIN, os.O_CREAT, int("0100",8))
+ shutil.copyfile('settings.py', SETTINGS_PLUGIN)
+if not os.path.isfile(LATCH_HELPER_PLUGIN):
+ os.open (LATCH_HELPER_PLUGIN, os.O_CREAT, int("0400",8))
+ shutil.copyfile('latchHelper.py', LATCH_HELPER_PLUGIN)
+if not os.path.isfile(TRANSLATION_PLUGIN):
+ os.open (TRANSLATION_PLUGIN, os.O_CREAT, int("0400",8))
+ shutil.copyfile('translation.py', TRANSLATION_PLUGIN)
+if not os.path.isfile(LATCH_API):
+ os.open (LATCH_API, os.O_CREAT, int("0400",8))
+ shutil.copyfile('latch.py', LATCH_API)
+
+if not os.path.isdir('/lib/security/'):
+ os.mkdir('/lib/security/')
+
+# add latch_accounts file
+if not os.path.isfile(LATCH_ACCOUNTS):
+ fd = os.open (LATCH_ACCOUNTS, os.O_CREAT, int("0600",8))
+
+print(INSTALLING_MSG)
+exit(0)
diff --git a/pool/shard009/Python/0083447_hello.py b/pool/shard009/Python/0083447_hello.py
new file mode 100644
index 0000000000000000000000000000000000000000..b6151e0af626705cced12a5140a911489e70d107
--- /dev/null
+++ b/pool/shard009/Python/0083447_hello.py
@@ -0,0 +1,63 @@
+#!/usr/bin/env python
+#
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+#
+# Michael A.G. Aivazis
+# California Institute of Technology
+# (C) 1998-2005 All Rights Reserved
+#
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+#
+
+
+def main():
+
+
+ from opal.applications.CGI import CGI
+
+
+ class HelloApp(CGI):
+
+ class Inventory(CGI.Inventory):
+
+ import pyre.inventory
+
+ name = pyre.inventory.str("name", default="world")
+ name.meta['tip'] = "the target of the greeting"
+
+
+ def main(self):
+ import os
+ pid = os.getpid()
+ euid = os.geteuid()
+ uid = os.getuid()
+
+ print ''
+ print "(%d, %s): Hello %s!" % (pid, uid, self.inventory.name)
+ print ' '
+ return
+
+
+ def __init__(self):
+ CGI.__init__(self, 'hello')
+ return
+
+
+ import journal
+ journal.info('opal.cmdline').activate()
+ journal.debug('opal.commandline').activate()
+
+ app = HelloApp()
+ return app.run()
+
+
+# main
+if __name__ == '__main__':
+ # invoke the application shell
+ main()
+
+
+# version
+__id__ = "$Id: hello.py,v 1.1.1.1 2005/03/15 06:09:10 aivazis Exp $"
+
+# End of file
diff --git a/pool/shard009/Python/0083451_get_diagram_data.py b/pool/shard009/Python/0083451_get_diagram_data.py
new file mode 100644
index 0000000000000000000000000000000000000000..cd88be02dd2f2002ded5189c514b1eaabcfa8a58
--- /dev/null
+++ b/pool/shard009/Python/0083451_get_diagram_data.py
@@ -0,0 +1,28 @@
+import numpy as np
+
+def get_diagram_data( y, p, n_bins ):
+
+ n_bins = float( n_bins ) # a float to take care of division
+
+ # we'll append because some bins might be empty
+ mean_predicted_values = np.empty(( 0, ))
+ true_fractions = np.zeros(( 0, ))
+
+ for b in range( 1, int( n_bins ) + 1 ):
+ i = np.logical_and( p <= b / n_bins, p > ( b - 1 ) / n_bins ) # indexes for p in the current bin
+
+ # skip bin if empty
+ if np.sum( i ) == 0:
+ continue
+
+ mean_predicted_value = np.mean( p[i] )
+ # print "***", np.sum( y[i] ), np.sum( i )
+ true_fraction = np.sum( y[i] ) / np.sum( i ) # y are 0/1; i are logical and evaluate to 0/1
+
+ print mean_predicted_value, true_fraction
+
+ mean_predicted_values = np.hstack(( mean_predicted_values, mean_predicted_value ))
+ true_fractions = np.hstack(( true_fractions, true_fraction ))
+
+ return ( mean_predicted_values, true_fractions )
+
\ No newline at end of file
diff --git a/pool/shard009/Python/0083452_optionsScreen.py b/pool/shard009/Python/0083452_optionsScreen.py
new file mode 100644
index 0000000000000000000000000000000000000000..28f8e2ea544a08b3dcaacb16ffdd617b086c43e5
--- /dev/null
+++ b/pool/shard009/Python/0083452_optionsScreen.py
@@ -0,0 +1,98 @@
+'''
+OptionsScreen
+'''
+
+import sys
+
+import pygame
+from pygame.locals import *
+from pygame.color import *
+from screen_ import Screen_
+
+sys.path.append('../')
+import utils
+from utils import save,load,exist
+
+
+class OptionsScreen(Screen_):
+ def __init__(self):
+ super(OptionsScreen, self).__init__()
+
+ self.font = utils.getFont('VolterGoldfish', 44)
+ self.infofont = utils.getFont('VolterGoldfish', 18)
+ self.keyfont = utils.getFont('VolterGoldfish', 24)
+ self.background = pygame.image.load("../img/backgrounds/options.png").convert()
+ self.soundBar = pygame.image.load("../img/backgrounds/soundBar.png").convert_alpha()
+ self.musicBar = pygame.image.load("../img/backgrounds/soundBar.png").convert_alpha()
+ self.keyImg = pygame.image.load("../img/backgrounds/key.png").convert_alpha()
+ self.volumeTest = pygame.mixer.Sound("../sounds/volumeTest.wav")
+ self.menuEntries = ["Music","Sound","Controls","Back"]
+ self.menuPositions = [(200,100),(200,200),(200,300),(200,500)]
+ self.menuChoice = 0
+ self.activeColor = THECOLORS["black"]
+ self.inactiveColor = THECOLORS["grey64"]
+ self.soundLevel = 0
+ if exist('soundLevel'):
+ self.soundLevel = load('soundLevel')
+ self.musicLevel = 0
+ if exist('musicLevel'):
+ self.musicLevel = load('musicLevel')
+ self.actionKeys = ['slow time','shield','trap','left','jump','right']
+ self.keys = ['w','x','c','<','^','>']
+ self.actionKeysPos = [(200,450),(330,450),(430,450),(530,450),(630,450),(730,450)]
+
+
+
+
+ def render(self, backgroundScreen):
+ backgroundScreen.blit(self.background, (0,0))
+ for i in range(len(self.menuEntries)):
+ if i == self.menuChoice:
+ backgroundScreen.blit(self.font.render(self.menuEntries[i], 1, self.activeColor), self.menuPositions[i])
+ else:
+ backgroundScreen.blit(self.font.render(self.menuEntries[i], 1, self.inactiveColor), self.menuPositions[i])
+ for i in range(len(self.actionKeys)):
+ backgroundScreen.blit(self.infofont.render(self.actionKeys[i],1,self.inactiveColor),(200+(i>0)*(i*100+30),450))
+ backgroundScreen.blit(self.keyImg,(200+(i>0)*(i*100+30),380))
+ backgroundScreen.blit(self.keyfont.render(self.keys[i],1,self.inactiveColor),(200+(i>0)*(i*100+30)+20,390))
+ for i in range(5):
+ backgroundScreen.blit(self.soundBar, (400+i*40,120), (0, (self.soundLevel > i)*30, 30, 30))
+ backgroundScreen.blit(self.musicBar, (400+i*40,220), (0, (self.musicLevel > i)*30, 30, 30))
+
+
+ def handle_events(self, events):
+ for event in events:
+ if event.type == KEYDOWN:
+ if event.key == K_ESCAPE:
+ save([('soundLevel',self.soundLevel),('musicLevel',self.musicLevel)])
+ self.manager.go_to('mainMenuScreen')
+ if event.key == K_RETURN:
+ if self.menuChoice == 3:
+ save([('soundLevel',self.soundLevel),('musicLevel',self.musicLevel)])
+ self.manager.go_to('mainMenuScreen')
+ if event.key == K_UP:
+ self.menuChoice = (self.menuChoice - 1) % len(self.menuEntries)
+ if event.key == K_DOWN:
+ self.menuChoice = (self.menuChoice + 1) % len(self.menuEntries)
+ if event.key == K_LEFT:
+ if self.menuChoice == 0:
+ self.soundLevel = max(0,self.soundLevel-1)
+ self.volumeTest.set_volume(self.soundLevel*0.2)
+ self.volumeTest.play()
+ if self.menuChoice == 1:
+ self.musicLevel = max(0,self.musicLevel-1)
+ pygame.mixer.music.set_volume(self.musicLevel*0.2)
+ self.volumeTest.set_volume(self.musicLevel*0.2)
+ self.volumeTest.play()
+ if event.key == K_RIGHT:
+ if self.menuChoice == 0:
+ self.soundLevel = min(5,self.soundLevel+1)
+ self.volumeTest.set_volume(self.soundLevel*0.2)
+ self.volumeTest.play()
+ if self.menuChoice == 1:
+ self.musicLevel = min(5,self.musicLevel+1)
+ pygame.mixer.music.set_volume(self.musicLevel*0.2)
+ self.volumeTest.set_volume(self.musicLevel*0.2)
+ self.volumeTest.play()
+ if event.type == QUIT:
+ save([('soundLevel',self.soundLevel),('musicLevel',self.musicLevel)])
\ No newline at end of file
diff --git a/pool/shard009/Python/0083463_setup.py b/pool/shard009/Python/0083463_setup.py
new file mode 100644
index 0000000000000000000000000000000000000000..db4c0861475445d808266f442f08833405315f1c
--- /dev/null
+++ b/pool/shard009/Python/0083463_setup.py
@@ -0,0 +1,29 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+from __future__ import with_statement
+from setuptools import setup
+
+with open("README.md") as f:
+ long_description = f.read()
+
+setup(
+ name="pyplyr",
+ version="0.0.1",
+ description="dplyr like method chains for pandas DataFrame.",
+ author="airtoxin",
+ author_email="airtoxin@icloud.com",
+ url="https://github.com/airtoxin/pyplyr",
+ py_modules=["pyplyr"],
+ include_package_data=True,
+ install_requires=[
+ "pandas"
+ ],
+ tests_require=[
+ "nose"
+ ],
+ license="MIT",
+ keywords="",
+ zip_safe=False,
+ classifiers=[]
+)
diff --git a/pool/shard009/Python/0083468_galaxywh.py b/pool/shard009/Python/0083468_galaxywh.py
new file mode 100644
index 0000000000000000000000000000000000000000..7f113514fbffd05ecee8d9cc6aab7187d2a1affb
--- /dev/null
+++ b/pool/shard009/Python/0083468_galaxywh.py
@@ -0,0 +1,25 @@
+import random
+import pygame as pg
+import copy
+
+class Galaxy(pg.sprite.Sprite):
+ """This class represents the block."""
+ def __init__(self, image, position, *groups):
+ pg.sprite.Sprite.__init__(self, *groups)
+ self.image = image
+ self.rect = self.image.get_rect(topleft=position)
+ self.speed = 0
+
+ def reset_pos(self, screen_rect):
+ """Reset block to a random location slightly above the screen."""
+ self.rect.x = random.randrange(screen_rect.width-self.rect.width)
+ self.rect.y = random.randrange(-100, -20)
+
+ def update(self, keys, screen_rect):
+ """Update the position of the block; reset if it leaves the screen."""
+ self.rect.y += self.speed
+ if self.rect.y > screen_rect.bottom:
+ self.reset_pos(screen_rect)
+
+ def get_copy(self):
+ return copy.copy(self)
diff --git a/pool/shard009/Python/0083470_ex14.py b/pool/shard009/Python/0083470_ex14.py
new file mode 100644
index 0000000000000000000000000000000000000000..94ca28a302da8a2f9bf734b2384955af43357919
--- /dev/null
+++ b/pool/shard009/Python/0083470_ex14.py
@@ -0,0 +1,25 @@
+#!/usr/bin/env python
+
+# Exercise 14: Prompting and Passing
+
+from sys import argv
+
+script, user_name = argv
+prompt = '> '
+
+print "Hi %s, I'm the %s script." % (user_name, script)
+print "I'd like to ask you a few questions."
+print "Do you like me %s?" % user_name
+likes = raw_input(prompt)
+
+print "Where do you live %s?" % user_name
+lives = raw_input(prompt)
+
+print "What kind of computer do you have?"
+computer = raw_input(prompt)
+
+print """
+Alright, so you said %r about liking me.
+You live in %r. Not sure where that is.
+And you have a %r computer. Nice.
+""" % (likes, lives, computer)
diff --git a/pool/shard009/Python/0083472_mavlink-zmq-bridge.py b/pool/shard009/Python/0083472_mavlink-zmq-bridge.py
new file mode 100644
index 0000000000000000000000000000000000000000..3f1c87435e32036b1b63a056e3c7bfec064e9b93
--- /dev/null
+++ b/pool/shard009/Python/0083472_mavlink-zmq-bridge.py
@@ -0,0 +1,46 @@
+import zmq
+
+from argparse import ArgumentParser
+from pymavlink import mavutil
+
+def main():
+ parser = ArgumentParser()
+ parser.add_argument("--device", help="MAVLink device to add to zmq", required=True)
+ parser.add_argument("--zmq", help="zmq url", required=True)
+ parser.add_argument("--prefix", help="Prefix for topic for this device", default="unnamed")
+ args = parser.parse_args()
+
+ try:
+ msrc = mavutil.mavlink_connection(args.device, planner_format=False,
+ notimestamps=True, robust_parsing=True)
+ except Exception, e:
+ print 'Could not connect to mavlink device at %s' % args.device
+ print e
+ return False
+
+ context = zmq.Context()
+ zmq_socket = context.socket(zmq.PUB)
+ try:
+ zmq_socket.connect(args.zmq)
+
+ except Exception, e:
+ print 'Failed to establish connection with zmq gateway'
+ print e
+
+ #send messages from mavlink connection to zmq gateway
+ try:
+ while True:
+ mav_msg = msrc.recv_match()
+ if mav_msg is not None:
+ topic = "%s.%s"%(args.prefix,mav_msg.get_type())
+ zmq_socket.send(topic,zmq.SNDMORE)
+ zmq_socket.send_pyobj(mav_msg)
+ except Exception, e:
+ print 'Bridge failed'
+ print e
+
+ zmq_socket.close()
+ context.term()
+
+if __name__ == "__main__":
+ main()
diff --git a/pool/shard009/Python/0083480_utils.py b/pool/shard009/Python/0083480_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..84c2cb835ad94ea95ec8d1ab8fd3a60d94c41b00
--- /dev/null
+++ b/pool/shard009/Python/0083480_utils.py
@@ -0,0 +1,138 @@
+import os
+import cStringIO
+import base64
+
+from Crypto.Cipher import AES
+from Crypto import Random
+import paramiko
+
+from settings import AES_KEY
+
+
+class StringIO(object):
+
+ def __init__(self, *args, **kwargs):
+ self.s = cStringIO.StringIO(*args)
+ self.name = kwargs.get("name", '')
+
+ @property
+ def size(self):
+ current = self.tell()
+ self.seek(0, os.SEEK_END)
+ value = self.tell()
+ self.seek(current)
+ return value
+
+ def __getattr__(self, key):
+ return getattr(self.s, key)
+
+ def __iter__(self):
+ for line in self.readlines():
+ yield line
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, type, value, traceback):
+ self.close()
+
+
+class SSHClient(paramiko.SSHClient):
+
+ def __init__(self, *args, **kwargs):
+ super(SSHClient, self).__init__(*args, **kwargs)
+ self.base = ""
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, type, value, traceback):
+ self.close()
+
+ def exec_command(self, command, *args, **kwargs):
+ command = self.base + command
+ return super(SSHClient, self).exec_command(command, *args, **kwargs)
+
+ def connect(self, *args, **kwargs):
+ super(SSHClient, self).connect(*args, **kwargs)
+ self.determine_base()
+
+ def determine_base(self):
+ bases = [". ~/.bash_profile; ", "source .login; ", ". ~/.bashrc; "]
+ for base in bases:
+ _, _, err = self.exec_command(base)
+ if not err.readlines():
+ self.base = base
+ return
+ raise ValueError("Could not find command base")
+
+
+class SFTPClient(paramiko.SFTPClient):
+
+ def __init__(self, *args, **kwargs):
+ super(SFTPClient, self).__init__(*args, **kwargs)
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, type, value, traceback):
+ self.close()
+
+
+def get_sftp_connection(hostname, username, key=None, password=None, port=22):
+ if key is None and password is None:
+ raise Exception("no key or password")
+
+ transport = paramiko.Transport((hostname, port))
+ transport.use_compression(compress=True)
+ if key:
+ pkey = paramiko.RSAKey.from_private_key(key)
+ transport.connect(username=username, pkey=pkey)
+ else:
+ transport.connect(username=username, password=password)
+ return SFTPClient.from_transport(transport)
+
+
+def get_ssh_connection(hostname, username, key=None, password=None,
+ port=22, timeout=None):
+ if key is None and password is None:
+ raise Exception("no key or password")
+ client = SSHClient()
+ client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
+ if key:
+ pkey = paramiko.RSAKey.from_private_key(key)
+ client.connect(hostname, username=username, pkey=pkey, port=port,
+ allow_agent=False, look_for_keys=False, compress=True,
+ timeout=timeout)
+ else:
+ client.connect(hostname, username=username, password=password,
+ port=port, allow_agent=False, look_for_keys=False,
+ compress=True, timeout=timeout)
+ return client
+
+
+class AESCipher(object):
+ # http://stackoverflow.com/questions/12524994/encrypt-decrypt-using-pycrypto-aes-256
+ BS = AES.block_size
+
+ def __init__(self, key=AES_KEY):
+ self.key = key
+
+ def _pad(self, s):
+ pad = (self.BS - len(s) % self.BS) * chr(self.BS - len(s) % self.BS)
+ return s + pad
+
+ def _unpad(self, s):
+ return s[0:-ord(s[-1])]
+
+ def encrypt(self, plain_text):
+ raw = self._pad(plain_text)
+ iv = Random.new().read(AES.block_size)
+ cipher = AES.new(self.key, AES.MODE_CBC, iv)
+ return base64.b64encode(iv + cipher.encrypt(raw))
+
+ def decrypt(self, cipher_text):
+ raw = base64.b64decode(cipher_text)
+ iv = raw[:self.BS]
+ cipher = AES.new(self.key, AES.MODE_CBC, iv)
+ return self._unpad(cipher.decrypt(raw[self.BS:]))
diff --git a/pool/shard009/Python/0083482_alert_spark_thrift_port.py b/pool/shard009/Python/0083482_alert_spark_thrift_port.py
new file mode 100644
index 0000000000000000000000000000000000000000..6874cb4beb0391f355b596e83cea7f46893236b6
--- /dev/null
+++ b/pool/shard009/Python/0083482_alert_spark_thrift_port.py
@@ -0,0 +1,160 @@
+"""
+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.
+"""
+
+import os
+import socket
+import time
+import logging
+import traceback
+from resource_management.libraries.functions import format
+from ambari_commons.os_family_impl import OsFamilyFuncImpl, OsFamilyImpl
+from resource_management.libraries.script.script import Script
+from resource_management.libraries.functions import get_kinit_path
+from resource_management.core.resources import Execute
+from resource_management.core import global_lock
+from resource_management.core.signal_utils import TerminateStrategy
+
+stack_root = Script.get_stack_root()
+
+OK_MESSAGE = "TCP OK - {0:.3f}s response on port {1}"
+CRITICAL_MESSAGE = "Connection failed on host {0}:{1} ({2})"
+
+HIVE_SERVER_THRIFT_PORT_KEY = '{{spark-hive-site-override/hive.server2.thrift.port}}'
+HIVE_SERVER_TRANSPORT_MODE_KEY = '{{spark-hive-site-override/hive.server2.transport.mode}}'
+SECURITY_ENABLED_KEY = '{{cluster-env/security_enabled}}'
+
+HIVE_SERVER2_AUTHENTICATION_KEY = '{{hive-site/hive.server2.authentication}}'
+HIVE_SERVER2_KERBEROS_KEYTAB = '{{hive-site/hive.server2.authentication.kerberos.keytab}}'
+HIVE_SERVER2_PRINCIPAL_KEY = '{{hive-site/hive.server2.authentication.kerberos.principal}}'
+
+# The configured Kerberos executable search paths, if any
+KERBEROS_EXECUTABLE_SEARCH_PATHS_KEY = '{{kerberos-env/executable_search_paths}}'
+
+THRIFT_PORT_DEFAULT = 10001
+HIVE_SERVER_TRANSPORT_MODE_DEFAULT = 'binary'
+
+HIVEUSER_DEFAULT = 'hive'
+
+CHECK_COMMAND_TIMEOUT_KEY = 'check.command.timeout'
+CHECK_COMMAND_TIMEOUT_DEFAULT = 60.0
+
+logger = logging.getLogger('ambari_alerts')
+
+@OsFamilyFuncImpl(os_family=OsFamilyImpl.DEFAULT)
+def get_tokens():
+ """
+ Returns a tuple of tokens in the format {{site/property}} that will be used
+ to build the dictionary passed into execute
+ """
+ return (HIVE_SERVER_THRIFT_PORT_KEY, HIVE_SERVER_TRANSPORT_MODE_KEY, SECURITY_ENABLED_KEY, KERBEROS_EXECUTABLE_SEARCH_PATHS_KEY,
+ HIVEUSER_DEFAULT, HIVE_SERVER2_KERBEROS_KEYTAB, HIVE_SERVER2_PRINCIPAL_KEY)
+
+@OsFamilyFuncImpl(os_family=OsFamilyImpl.DEFAULT)
+def execute(configurations={}, parameters={}, host_name=None):
+ """
+ Returns a tuple containing the result code and a pre-formatted result label
+
+ Keyword arguments:
+ configurations (dictionary): a mapping of configuration key to value
+ parameters (dictionary): a mapping of script parameter key to value
+ host_name (string): the name of this host where the alert is running
+ """
+
+ spark_home = os.path.join(stack_root, "current", 'spark-client')
+
+ if configurations is None:
+ return ('UNKNOWN', ['There were no configurations supplied to the script.'])
+
+ transport_mode = HIVE_SERVER_TRANSPORT_MODE_DEFAULT
+ if HIVE_SERVER_TRANSPORT_MODE_KEY in configurations:
+ transport_mode = configurations[HIVE_SERVER_TRANSPORT_MODE_KEY]
+
+ port = THRIFT_PORT_DEFAULT
+ if transport_mode.lower() == 'binary' and HIVE_SERVER_THRIFT_PORT_KEY in configurations:
+ port = int(configurations[HIVE_SERVER_THRIFT_PORT_KEY])
+
+ security_enabled = False
+ if SECURITY_ENABLED_KEY in configurations:
+ security_enabled = str(configurations[SECURITY_ENABLED_KEY]).upper() == 'TRUE'
+
+ hive_kerberos_keytab = None
+ if HIVE_SERVER2_KERBEROS_KEYTAB in configurations:
+ hive_kerberos_keytab = configurations[HIVE_SERVER2_KERBEROS_KEYTAB]
+
+ if host_name is None:
+ host_name = socket.getfqdn()
+
+ hive_principal = None
+ if HIVE_SERVER2_PRINCIPAL_KEY in configurations:
+ hive_principal = configurations[HIVE_SERVER2_PRINCIPAL_KEY]
+ hive_principal = hive_principal.replace('_HOST',host_name.lower())
+
+ # Get the configured Kerberos executable search paths, if any
+ if KERBEROS_EXECUTABLE_SEARCH_PATHS_KEY in configurations:
+ kerberos_executable_search_paths = configurations[KERBEROS_EXECUTABLE_SEARCH_PATHS_KEY]
+ else:
+ kerberos_executable_search_paths = None
+
+ kinit_path_local = get_kinit_path(kerberos_executable_search_paths)
+
+ hiveruser = HIVEUSER_DEFAULT
+
+ if security_enabled:
+ kinitcmd = format("{kinit_path_local} -kt {hive_kerberos_keytab} {hive_principal}; ")
+ # prevent concurrent kinit
+ kinit_lock = global_lock.get_lock(global_lock.LOCK_TYPE_KERBEROS)
+ kinit_lock.acquire()
+ try:
+ Execute(kinitcmd, user=hiveruser)
+ finally:
+ kinit_lock.release()
+
+ result_code = None
+ try:
+ if host_name is None:
+ host_name = socket.getfqdn()
+
+ if security_enabled:
+ beeline_url = ["'jdbc:hive2://{host_name}:{port}/default;principal={hive_principal}'","transportMode={transport_mode}"]
+ else:
+ beeline_url = ["'jdbc:hive2://{host_name}:{port}/default'","transportMode={transport_mode}"]
+ # append url according to used transport
+
+ beeline_cmd = os.path.join(spark_home, "bin", "beeline")
+ cmd = "! beeline -u %s -e '' 2>&1| awk '{print}'|grep -i -e 'Connection refused' -e 'Invalid URL'" % \
+ (format(" ".join(beeline_url)))
+
+ start_time = time.time()
+ try:
+ Execute(cmd,
+ user=hiveruser,
+ path=[beeline_cmd],
+ timeout=CHECK_COMMAND_TIMEOUT_DEFAULT,
+ timeout_kill_strategy=TerminateStrategy.KILL_PROCESS_TREE,
+ )
+ total_time = time.time() - start_time
+ result_code = 'OK'
+ label = OK_MESSAGE.format(total_time, port)
+ except:
+ result_code = 'CRITICAL'
+ label = CRITICAL_MESSAGE.format(host_name, port, traceback.format_exc())
+ except:
+ label = traceback.format_exc()
+ result_code = 'UNKNOWN'
+
+ return (result_code, [label])
diff --git a/pool/shard009/Python/0083494_TornadoConfigurationHandler.py b/pool/shard009/Python/0083494_TornadoConfigurationHandler.py
new file mode 100644
index 0000000000000000000000000000000000000000..7b196f29e04c522713c9e9f343053b40f5c927c3
--- /dev/null
+++ b/pool/shard009/Python/0083494_TornadoConfigurationHandler.py
@@ -0,0 +1,131 @@
+""" The CS! (Configuration Service)
+
+Modified to work with Tornado
+Encode data in base64 because of JSON limitations
+In client side you must use a specific client
+
+"""
+
+from __future__ import absolute_import
+from __future__ import division
+from __future__ import print_function
+
+__RCSID__ = "$Id$"
+
+from base64 import b64encode, b64decode
+
+from DIRAC import S_OK, S_ERROR, gLogger
+from DIRAC.ConfigurationSystem.private.ServiceInterfaceTornado import ServiceInterfaceTornado as ServiceInterface
+from DIRAC.Core.Tornado.Server.TornadoService import TornadoService
+
+sLog = gLogger.getSubLogger(__name__)
+
+
+class TornadoConfigurationHandler(TornadoService):
+ """
+ The CS handler
+ """
+
+ ServiceInterface = None
+ PilotSynchronizer = None
+
+ @classmethod
+ def initializeHandler(cls, serviceInfo):
+ """
+ Initialize the configuration server
+ Behind it starts thread which refresh configuration
+ """
+ cls.ServiceInterface = ServiceInterface(serviceInfo["URL"])
+ return S_OK()
+
+ def export_getVersion(self):
+ """
+ Returns the version of the configuration
+ """
+ return S_OK(self.ServiceInterface.getVersion())
+
+ def export_getCompressedData(self):
+ """
+ Returns the configuration
+ """
+ sData = self.ServiceInterface.getCompressedConfigurationData()
+ return S_OK(b64encode(sData).decode())
+
+ def export_getCompressedDataIfNewer(self, sClientVersion):
+ """
+ Returns the configuration if a newer configuration exists, if not just returns the version
+
+ :param sClientVersion: Version used by client
+ """
+ sVersion = self.ServiceInterface.getVersion()
+ retDict = {"newestVersion": sVersion}
+ if sClientVersion < sVersion:
+ retDict["data"] = b64encode(self.ServiceInterface.getCompressedConfigurationData()).decode()
+ return S_OK(retDict)
+
+ def export_publishSlaveServer(self, sURL):
+ """
+ Used by slave server to register as a slave server.
+
+ :param sURL: The url of the slave server.
+ """
+ self.ServiceInterface.publishSlaveServer(sURL)
+ return S_OK()
+
+ def export_commitNewData(self, sData):
+ """
+ Write the new configuration
+ """
+ credDict = self.getRemoteCredentials()
+ if "DN" not in credDict or "username" not in credDict:
+ return S_ERROR("You must be authenticated!")
+ sData = b64decode(sData)
+ return self.ServiceInterface.updateConfiguration(sData, credDict["username"])
+
+ def export_writeEnabled(self):
+ """
+ Used to know if we can change the configuration on this server
+ """
+ return S_OK(self.ServiceInterface.isMaster())
+
+ def export_getCommitHistory(self, limit=100):
+ """
+ Get the history of modifications in the configuration
+ """
+ if limit > 100:
+ limit = 100
+ history = self.ServiceInterface.getCommitHistory()
+ if limit:
+ history = history[:limit]
+ return S_OK(history)
+
+ def export_getVersionContents(self, versionList):
+ """
+ Get an old version of the configuration, can also be used to get more than one version.
+
+ :param versionList: List of the version we are trying to get
+ """
+ contentsList = []
+ for version in versionList:
+ retVal = self.ServiceInterface.getVersionContents(version)
+ if retVal["OK"]:
+ contentsList.append(retVal["Value"])
+ else:
+ return S_ERROR("Can't get contents for version %s: %s" % (version, retVal["Message"]))
+ return S_OK(contentsList)
+
+ def export_rollbackToVersion(self, version):
+ """
+ Rollback to an older version of the configuration
+
+ :param version: The version we want to apply
+ """
+ retVal = self.ServiceInterface.getVersionContents(version)
+ if not retVal["OK"]:
+ return S_ERROR("Can't get contents for version %s: %s" % (version, retVal["Message"]))
+ credDict = self.getRemoteCredentials()
+ if "DN" not in credDict or "username" not in credDict:
+ return S_ERROR("You must be authenticated!")
+ return self.ServiceInterface.updateConfiguration(
+ retVal["Value"], credDict["username"], updateVersionOption=True
+ )
diff --git a/pool/shard009/Python/0083497_sweet.py b/pool/shard009/Python/0083497_sweet.py
new file mode 100644
index 0000000000000000000000000000000000000000..5984bdb057f5b2dbdc8e65ac3b561e2c886bd546
--- /dev/null
+++ b/pool/shard009/Python/0083497_sweet.py
@@ -0,0 +1,26 @@
+# -*- coding utf-8 -*-
+# classes/views/sweet.py
+
+
+from flask import Module, render_template, abort
+
+from swtstore.classes.models import Sweet
+
+
+sweet = Module(__name__)
+
+
+@sweet.route('/', methods=['GET'])
+def showSweet(id):
+ #current_user = User.getCurrentUser()
+ #if current_user is None:
+ # return redirect(url_for('index'))
+
+ #user = current_user.to_dict()
+ print "recvd sweet id: %s" % (id)
+ sweet = Sweet.query.get(id)
+ if sweet:
+ print "sweet found %s" % (sweet)
+ return render_template('sweet/specific.html', sweet=sweet.to_dict())
+ else:
+ abort(404)
diff --git a/pool/shard009/Python/0083501_patch_applier.py b/pool/shard009/Python/0083501_patch_applier.py
new file mode 100644
index 0000000000000000000000000000000000000000..d2380a51cc8c4de7881aaa997d6e67f105eb0129
--- /dev/null
+++ b/pool/shard009/Python/0083501_patch_applier.py
@@ -0,0 +1,58 @@
+def apply_patch(string_to_patch, patch, reverse=False):
+ """Apply a diff file to a specified string
+ """
+
+ # The strings are now represented as arrays with every element being one line
+ patch_lines = patch.split("\n")
+ final_text = string_to_patch.split("\n")
+
+ current_line_number = 0
+ for line in patch_lines:
+
+ current_line_number += 1
+
+ # Header for the patch file
+ if line.startswith("---") or line.startswith("+++"):
+ pass
+
+ # Start of new diff "hunk"
+ # Get info about the line numbers the new hunk takes place over
+ elif line.startswith("@"):
+
+ # TODO: A lot of this is probably unneeded
+ old_lines, new_lines = line.replace("-", "").replace("+", "").strip("@").strip().split(" ")
+ old_lines = old_lines.split(",")
+ new_lines = new_lines.split(",")
+
+ # Change the current line number to skip over ones that didn't change
+ current_line_number = int(old_lines[0]) - 1
+
+ # If a line was removed
+ elif line.startswith("-"):
+
+ if not reverse:
+ # If applying patch to original string, remove the line
+ del final_text[current_line_number - 1]
+ current_line_number -= 1
+
+ else:
+ # If in reverse, add the line
+ # This will change the line from "-*rest of the line*" to "*rest of the line*"
+ line = line[1:]
+ final_text.insert(current_line_number - 1, line)
+
+ # If a line was added
+ elif line.startswith("+"):
+ if not reverse:
+ # If applying patch to the original string, add the line
+ # This will change the line from "+*rest of the line*" to "*rest of the line*"
+ line = line[1:]
+ final_text.insert(current_line_number - 1, line)
+
+ else:
+ # If in reverse, remove the line
+ del final_text[current_line_number - 1]
+ current_line_number -= 1
+
+ # This will return it as one string with newlines between every line
+ return "\n".join(final_text)
diff --git a/pool/shard009/Python/0083503_secret.py b/pool/shard009/Python/0083503_secret.py
new file mode 100644
index 0000000000000000000000000000000000000000..c7174db044f15dfa6ff14bda49d6cb311b0cf66e
--- /dev/null
+++ b/pool/shard009/Python/0083503_secret.py
@@ -0,0 +1,127 @@
+# Copyright 2013 Donald Stufft and individual contributors
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from __future__ import absolute_import, division, print_function
+
+import nacl.bindings
+from nacl import encoding
+from nacl import exceptions as exc
+from nacl.utils import EncryptedMessage, StringFixer, random
+
+
+class SecretBox(encoding.Encodable, StringFixer, object):
+ """
+ The SecretBox class encrypts and decrypts messages using the given secret
+ key.
+
+ The ciphertexts generated by :class:`~nacl.secret.Secretbox` include a 16
+ byte authenticator which is checked as part of the decryption. An invalid
+ authenticator will cause the decrypt function to raise an exception. The
+ authenticator is not a signature. Once you've decrypted the message you've
+ demonstrated the ability to create arbitrary valid message, so messages you
+ send are repudiable. For non-repudiable messages, sign them after
+ encryption.
+
+ :param key: The secret key used to encrypt and decrypt messages
+ :param encoder: The encoder class used to decode the given key
+
+ :cvar KEY_SIZE: The size that the key is required to be.
+ :cvar NONCE_SIZE: The size that the nonce is required to be.
+ """
+
+ KEY_SIZE = nacl.bindings.crypto_secretbox_KEYBYTES
+ NONCE_SIZE = nacl.bindings.crypto_secretbox_NONCEBYTES
+
+ def __init__(self, key, encoder=encoding.RawEncoder):
+ key = encoder.decode(key)
+ if not isinstance(key, bytes):
+ raise exc.TypeError("SecretBox must be created from 32 bytes")
+
+ if len(key) != self.KEY_SIZE:
+ raise exc.ValueError(
+ "The key must be exactly %s bytes long" %
+ self.KEY_SIZE,
+ )
+
+ self._key = key
+
+ def __bytes__(self):
+ return self._key
+
+ def encrypt(self, plaintext, nonce=None, encoder=encoding.RawEncoder):
+ """
+ Encrypts the plaintext message using the given `nonce` (or generates
+ one randomly if omitted) and returns the ciphertext encoded with the
+ encoder.
+
+ .. warning:: It is **VITALLY** important that the nonce is a nonce,
+ i.e. it is a number used only once for any given key. If you fail
+ to do this, you compromise the privacy of the messages encrypted.
+ Give your nonces a different prefix, or have one side use an odd
+ counter and one an even counter. Just make sure they are different.
+
+ :param plaintext: [:class:`bytes`] The plaintext message to encrypt
+ :param nonce: [:class:`bytes`] The nonce to use in the encryption
+ :param encoder: The encoder to use to encode the ciphertext
+ :rtype: [:class:`nacl.utils.EncryptedMessage`]
+ """
+ if nonce is None:
+ nonce = random(self.NONCE_SIZE)
+
+ if len(nonce) != self.NONCE_SIZE:
+ raise exc.ValueError(
+ "The nonce must be exactly %s bytes long" % self.NONCE_SIZE,
+ )
+
+ ciphertext = nacl.bindings.crypto_secretbox(plaintext,
+ nonce, self._key)
+
+ encoded_nonce = encoder.encode(nonce)
+ encoded_ciphertext = encoder.encode(ciphertext)
+
+ return EncryptedMessage._from_parts(
+ encoded_nonce,
+ encoded_ciphertext,
+ encoder.encode(nonce + ciphertext),
+ )
+
+ def decrypt(self, ciphertext, nonce=None, encoder=encoding.RawEncoder):
+ """
+ Decrypts the ciphertext using the `nonce` (explicitly, when passed as a
+ parameter or implicitly, when omitted, as part of the ciphertext) and
+ returns the plaintext message.
+
+ :param ciphertext: [:class:`bytes`] The encrypted message to decrypt
+ :param nonce: [:class:`bytes`] The nonce used when encrypting the
+ ciphertext
+ :param encoder: The encoder used to decode the ciphertext.
+ :rtype: [:class:`bytes`]
+ """
+ # Decode our ciphertext
+ ciphertext = encoder.decode(ciphertext)
+
+ if nonce is None:
+ # If we were given the nonce and ciphertext combined, split them.
+ nonce = ciphertext[:self.NONCE_SIZE]
+ ciphertext = ciphertext[self.NONCE_SIZE:]
+
+ if len(nonce) != self.NONCE_SIZE:
+ raise exc.ValueError(
+ "The nonce must be exactly %s bytes long" % self.NONCE_SIZE,
+ )
+
+ plaintext = nacl.bindings.crypto_secretbox_open(ciphertext,
+ nonce, self._key)
+
+ return plaintext
diff --git a/pool/shard009/Python/0083504_compat.py b/pool/shard009/Python/0083504_compat.py
new file mode 100644
index 0000000000000000000000000000000000000000..5329cb66842c4cc328f588a2177f4da8acca744d
--- /dev/null
+++ b/pool/shard009/Python/0083504_compat.py
@@ -0,0 +1,38 @@
+# -*- coding: utf-8 -*-
+"""
+ sphinx.util.compat
+ ~~~~~~~~~~~~~~~~~~
+
+ Stuff for docutils compatibility.
+
+ :copyright: Copyright 2007-2016 by the Sphinx team, see AUTHORS.
+ :license: BSD, see LICENSE for details.
+"""
+import warnings
+
+from docutils import nodes
+from docutils.parsers.rst import Directive # noqa
+
+from docutils import __version__ as _du_version
+docutils_version = tuple(int(x) for x in _du_version.split('.')[:2])
+
+
+def make_admonition(node_class, name, arguments, options, content, lineno,
+ content_offset, block_text, state, state_machine):
+ warnings.warn('make_admonition is deprecated, use '
+ 'docutils.parsers.rst.directives.admonitions.BaseAdmonition '
+ 'instead', DeprecationWarning, stacklevel=2)
+ text = '\n'.join(content)
+ admonition_node = node_class(text)
+ if arguments:
+ title_text = arguments[0]
+ textnodes, messages = state.inline_text(title_text, lineno)
+ admonition_node += nodes.title(title_text, '', *textnodes)
+ admonition_node += messages
+ if 'class' in options:
+ classes = options['class']
+ else:
+ classes = ['admonition-' + nodes.make_id(title_text)]
+ admonition_node['classes'] += classes
+ state.nested_parse(content, content_offset, admonition_node)
+ return [admonition_node]
diff --git a/pool/shard009/Python/0083505_test_measurement.py b/pool/shard009/Python/0083505_test_measurement.py
new file mode 100644
index 0000000000000000000000000000000000000000..0af0dd9dcec7c4efd51ea2a884c2bc8c97de00f2
--- /dev/null
+++ b/pool/shard009/Python/0083505_test_measurement.py
@@ -0,0 +1,99 @@
+from unittest import TestCase
+from tests import fixture
+from datetime import datetime
+from pyprol import measurement
+
+import sys
+import os
+
+class TimingStatTestCase(TestCase):
+ def test_timingstat(self):
+ obj = measurement.TimingStat(
+ datetime.utcnow(), "testing", "test", "test.code.py", 1, 0,
+ 0.4, 0.2, None)
+
+ assert hasattr(obj, 'timestamp')
+ assert hasattr(obj, 'session')
+ assert hasattr(obj, 'name')
+ assert hasattr(obj, 'code')
+ assert hasattr(obj, 'call_count')
+ assert hasattr(obj, 'recursive_call_count')
+ assert hasattr(obj, 'time_total')
+ assert hasattr(obj, 'time_function')
+ assert hasattr(obj, 'calls')
+
+class MeasurementTestCase(TestCase):
+ def assertEqualTiming(self, a, b):
+ self.assertEqual(a.code, b.code)
+ self.assertEqual(a.call_count, b.call_count)
+ self.assertEqual(a.recursive_call_count, b.recursive_call_count)
+ self.assertEqual(a.time_total, b.time_total)
+ self.assertEqual(a.time_function, b.time_function)
+ self.assertEqual(a.calls, b.calls)
+
+ if a.calls is not None and b.calls is not None:
+ try:
+ # Check if we should use the python 2 xrange function
+ indexes = xrange(0, len(a.calls))
+ except NameError:
+ # Use the xrange function, that is named range in python 3
+ indexes = range(0, len(a.calls))
+
+ for i in indexes:
+ self.assertEqualTiming(a.calls[i], b.calls[i])
+
+ def assertEqualMeasure(self, a, b):
+ self.assertIsInstance(a, measurement.Measure)
+ self.assertIsInstance(b, measurement.Measure)
+
+ self.assertEqual(a.point_name, b.point_name)
+ if hasattr(a, "timings") and hasattr(b, "timings"):
+ self.assertEqual(len(a.timings), len(b.timings))
+
+ try:
+ indexes = xrange(0, len(a.timings))
+ except NameError:
+ indexes = range(0, len(a.timings))
+
+ for i in indexes:
+ self.assertEqualTiming(a.timings[i], b.timings[i])
+
+ elif hasattr(a, "timing"):
+ assert False
+
+ elif hasattr(b, "timing"):
+ assert False
+
+ def setUp(self):
+ self.config = fixture.Configuration()
+
+ def test_init_shutdown(self):
+ measurement.init(self.config)
+ self.assertTrue(measurement.measurement._save_process.is_alive())
+ self.assertIsNotNone(measurement.measurement._save_queue)
+
+ measurement.shutdown()
+ self.assertIsNone(measurement.measurement._save_process)
+ self.assertIsNone(measurement.measurement._save_queue)
+
+ def test_save_load(self):
+ queue = fixture.Queue()
+ send_measure = measurement.Measure("testing", "run_test", queue)
+ send_measure.start().stop().save()
+
+ recv_measure = measurement.Measure(data=queue.get())
+
+ self.assertEqual(recv_measure.timings, send_measure.timings)
+ self.assertEqual(recv_measure.point_name, send_measure.point_name)
+
+ def test_enable_disable(self):
+ storage = fixture.Storage(self.config)
+ measurement.init(self.config, fixture.Storage)
+
+ measure = measurement.enable("testing")
+ fixture.nop()
+ measurement.disable(measure)
+ measurement.shutdown()
+
+ self.assertEqualMeasure(fixture.Storage().last(), measure)
+
diff --git a/pool/shard009/Python/0083511_qgis-sample-QgsDialog.py b/pool/shard009/Python/0083511_qgis-sample-QgsDialog.py
new file mode 100644
index 0000000000000000000000000000000000000000..565550e0fcf3da2f1fb64e790a4d34be4e186678
--- /dev/null
+++ b/pool/shard009/Python/0083511_qgis-sample-QgsDialog.py
@@ -0,0 +1,14 @@
+# coding: utf-8
+from PyQt4.QtCore import Qt # http://doc.qt.io/qt-4.8/qwidget.html#windowFlags-prop
+from PyQt4.QtGui import QDialogButtonBox # http://doc.qt.io/qt-4.8/qcolor.html
+from qgis.gui import QgsDialog
+from qgis.utils import iface
+
+main_window = iface.mainWindow()
+dialog = QgsDialog(main_window,
+ fl=Qt.WindowFlags(),
+ buttons=QDialogButtonBox.Close,
+ orientation=Qt.Horizontal)
+dialog.resize(600, 400)
+
+dialog.show()
diff --git a/pool/shard009/Python/0083514_app.py b/pool/shard009/Python/0083514_app.py
new file mode 100644
index 0000000000000000000000000000000000000000..1aeabfd385436ec1c01b0d6f225c94c484e6e718
--- /dev/null
+++ b/pool/shard009/Python/0083514_app.py
@@ -0,0 +1,47 @@
+import os
+from flask import Flask, render_template, request, abort
+from seck.model import User, Post
+from config import config
+app = Flask(__name__)
+
+if config.env == "development":
+ app.debug = True
+
+user = config.user
+
+@app.route('/')
+def home():
+ return render_template("home.html",
+ user = user)
+
+#@app.route('/blog')
+def blog():
+ post_id = request.args.get('post')
+ tag = request.args.get('tag')
+ if post_id:
+ post = Post.find_one(post_id)
+ if not post:
+ abort(404)
+ post.render()
+ return render_template("blog-page.html",
+ user = user,
+ post = post)
+ elif tag:
+ posts = Post.find_by_tag(tag)
+ return render_template("blog.html",
+ user = user,
+ posts = posts)
+ else:
+ post_idx = request.args.get('page') or 0
+ posts = Post.all()
+ return render_template("blog.html",
+ user= user,
+ posts = posts)
+
+@app.errorhandler(404)
+def page_not_found(e):
+ return render_template("404.html",
+ user = user), 404
+
+if __name__ == '__main__':
+ app.run(host='127.0.0.1', port=5000)
diff --git a/pool/shard009/Python/0083520_pyminer.py b/pool/shard009/Python/0083520_pyminer.py
new file mode 100644
index 0000000000000000000000000000000000000000..e8967f5bd4e1595e2f93f39186ff43e1eee7888f
--- /dev/null
+++ b/pool/shard009/Python/0083520_pyminer.py
@@ -0,0 +1,252 @@
+#!/usr/bin/python
+#
+# Copyright (c) 2011 The Bitcoin developers
+# Distributed under the MIT/X11 software license, see the accompanying
+# file COPYING or http://www.opensource.org/licenses/mit-license.php.
+#
+
+import time
+import json
+import pprint
+import hashlib
+import struct
+import re
+import base64
+import httplib
+import sys
+from multiprocessing import Process
+
+ERR_SLEEP = 15
+MAX_NONCE = 1000000L
+
+settings = {}
+pp = pprint.PrettyPrinter(indent=4)
+
+class BitcoinRPC:
+ OBJID = 1
+
+ def __init__(self, host, port, username, password):
+ authpair = "%s:%s" % (username, password)
+ self.authhdr = "Basic %s" % (base64.b64encode(authpair))
+ self.conn = httplib.HTTPConnection(host, port, False, 30)
+ def rpc(self, method, params=None):
+ self.OBJID += 1
+ obj = { 'version' : '1.1',
+ 'method' : method,
+ 'id' : self.OBJID }
+ if params is None:
+ obj['params'] = []
+ else:
+ obj['params'] = params
+ self.conn.request('POST', '/', json.dumps(obj),
+ { 'Authorization' : self.authhdr,
+ 'Content-type' : 'application/json' })
+
+ resp = self.conn.getresponse()
+ if resp is None:
+ print "JSON-RPC: no response"
+ return None
+
+ body = resp.read()
+ resp_obj = json.loads(body)
+ if resp_obj is None:
+ print "JSON-RPC: cannot JSON-decode body"
+ return None
+ if 'error' in resp_obj and resp_obj['error'] != None:
+ return resp_obj['error']
+ if 'result' not in resp_obj:
+ print "JSON-RPC: no result in object"
+ return None
+
+ return resp_obj['result']
+ def getblockcount(self):
+ return self.rpc('getblockcount')
+ def getwork(self, data=None):
+ return self.rpc('getwork', data)
+
+def uint32(x):
+ return x & 0xffffffffL
+
+def bytereverse(x):
+ return uint32(( ((x) << 24) | (((x) << 8) & 0x00ff0000) |
+ (((x) >> 8) & 0x0000ff00) | ((x) >> 24) ))
+
+def bufreverse(in_buf):
+ out_words = []
+ for i in range(0, len(in_buf), 4):
+ word = struct.unpack('@I', in_buf[i:i+4])[0]
+ out_words.append(struct.pack('@I', bytereverse(word)))
+ return ''.join(out_words)
+
+def wordreverse(in_buf):
+ out_words = []
+ for i in range(0, len(in_buf), 4):
+ out_words.append(in_buf[i:i+4])
+ out_words.reverse()
+ return ''.join(out_words)
+
+class Miner:
+ def __init__(self, id):
+ self.id = id
+ self.max_nonce = MAX_NONCE
+
+ def work(self, datastr, targetstr):
+ # decode work data hex string to binary
+ static_data = datastr.decode('hex')
+ static_data = bufreverse(static_data)
+
+ # the first 76b of 80b do not change
+ blk_hdr = static_data[:76]
+
+ # decode 256-bit target value
+ targetbin = targetstr.decode('hex')
+ targetbin = targetbin[::-1] # byte-swap and dword-swap
+ targetbin_str = targetbin.encode('hex')
+ target = long(targetbin_str, 16)
+
+ # pre-hash first 76b of block header
+ static_hash = hashlib.sha256()
+ static_hash.update(blk_hdr)
+
+ for nonce in xrange(self.max_nonce):
+
+ # encode 32-bit nonce value
+ nonce_bin = struct.pack(" Upstream RPC result:", result
+
+ def iterate(self, rpc):
+ work = rpc.getwork()
+ if work is None:
+ time.sleep(ERR_SLEEP)
+ return
+ if 'data' not in work or 'target' not in work:
+ time.sleep(ERR_SLEEP)
+ return
+
+ time_start = time.time()
+
+ (hashes_done, nonce_bin) = self.work(work['data'],
+ work['target'])
+
+ time_end = time.time()
+ time_diff = time_end - time_start
+
+ self.max_nonce = long(
+ (hashes_done * settings['scantime']) / time_diff)
+ if self.max_nonce > 0xfffffffaL:
+ self.max_nonce = 0xfffffffaL
+
+ if settings['hashmeter']:
+ print "HashMeter(%d): %d hashes, %.2f Khash/sec" % (
+ self.id, hashes_done,
+ (hashes_done / 1000.0) / time_diff)
+
+ if nonce_bin is not None:
+ self.submit_work(rpc, work['data'], nonce_bin)
+
+ def loop(self):
+ rpc = BitcoinRPC(settings['host'], settings['port'],
+ settings['rpcuser'], settings['rpcpass'])
+ if rpc is None:
+ return
+
+ while True:
+ self.iterate(rpc)
+
+def miner_thread(id):
+ miner = Miner(id)
+ miner.loop()
+
+if __name__ == '__main__':
+ if len(sys.argv) != 2:
+ print "Usage: pyminer.py CONFIG-FILE"
+ sys.exit(1)
+
+ f = open(sys.argv[1])
+ for line in f:
+ # skip comment lines
+ m = re.search('^\s*#', line)
+ if m:
+ continue
+
+ # parse key=value lines
+ m = re.search('^(\w+)\s*=\s*(\S.*)$', line)
+ if m is None:
+ continue
+ settings[m.group(1)] = m.group(2)
+ f.close()
+
+ if 'host' not in settings:
+ settings['host'] = '127.0.0.1'
+ if 'port' not in settings:
+ settings['port'] = 56377
+ if 'threads' not in settings:
+ settings['threads'] = 1
+ if 'hashmeter' not in settings:
+ settings['hashmeter'] = 0
+ if 'scantime' not in settings:
+ settings['scantime'] = 30L
+ if 'rpcuser' not in settings or 'rpcpass' not in settings:
+ print "Missing username and/or password in cfg file"
+ sys.exit(1)
+
+ settings['port'] = int(settings['port'])
+ settings['threads'] = int(settings['threads'])
+ settings['hashmeter'] = int(settings['hashmeter'])
+ settings['scantime'] = long(settings['scantime'])
+
+ thr_list = []
+ for thr_id in range(settings['threads']):
+ p = Process(target=miner_thread, args=(thr_id,))
+ p.start()
+ thr_list.append(p)
+ time.sleep(1) # stagger threads
+
+ print settings['threads'], "mining threads started"
+
+ print time.asctime(), "Miner Starts - %s:%s" % (settings['host'], settings['port'])
+ try:
+ for thr_proc in thr_list:
+ thr_proc.join()
+ except KeyboardInterrupt:
+ pass
+ print time.asctime(), "Miner Stops - %s:%s" % (settings['host'], settings['port'])
+
diff --git a/pool/shard009/Python/0083525_brew.py b/pool/shard009/Python/0083525_brew.py
new file mode 100644
index 0000000000000000000000000000000000000000..5bd88f01aed67f7997b190185b20a2a01c238333
--- /dev/null
+++ b/pool/shard009/Python/0083525_brew.py
@@ -0,0 +1,176 @@
+#!/usr/bin/python
+# encoding: utf-8
+
+import sys
+import os
+import subprocess
+
+from workflow import Workflow, MATCH_SUBSTRING
+from workflow.background import run_in_background
+
+import brew_refresh
+
+WF = Workflow(update_settings={
+ 'github_slug': 'fniephaus/alfred-homebrew',
+ 'version': open(os.path.join(os.path.dirname(__file__), 'version')).read(),
+})
+
+FORMULA_URL = 'https://github.com/Homebrew/homebrew/tree/master/Library/Formula'
+
+
+# name and description are search keys
+def search_key_for_action(action):
+ elements = []
+ elements.append(action['name'])
+ elements.append(action['description'])
+ return u' '.join(elements)
+
+
+def get_all_packages(query):
+ formulas = WF.cached_data(
+ 'brew_all_formulas', brew_refresh.get_all_packages, max_age=3600)
+
+ query_filter = query.split()
+ if len(query_filter) > 1:
+ return WF.filter(query_filter[1],
+ formulas, match_on=MATCH_SUBSTRING)
+ return formulas
+
+
+def get_installed_packages(query):
+ formulas = WF.cached_data(
+ 'brew_installed_formulas', brew_refresh.get_installed_packages, max_age=3600)
+
+ query_filter = query.split()
+ if len(query_filter) > 1:
+ return WF.filter(query_filter[1],
+ formulas, match_on=MATCH_SUBSTRING)
+ return formulas
+
+
+def get_open_link_command(formula):
+ return 'open %s/%s.rb && exit' % (FORMULA_URL, formula)
+
+
+def brew_not_installed():
+ _, err = subprocess.Popen(
+ ['command', '/usr/local/bin/brew'], stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
+ return err != ''
+
+
+def get_icon(name):
+ name = '%s-dark' % name if is_dark() else name
+ return "icons/%s.png" % name
+
+
+def is_dark():
+ rgb = [int(x) for x in WF.alfred_env['theme_background'][5:-6].split(',')]
+ return (0.299 * rgb[0] + 0.587 * rgb[1] + 0.114 * rgb[2] ) / 255 < 0.5
+
+if __name__ == '__main__':
+ from brew_actions import ACTIONS
+
+ if WF.update_available:
+ WF.add_item(
+ "An update is available!",
+ autocomplete='workflow:update',
+ valid=False,
+ icon=get_icon("cloud-download")
+ )
+
+ if WF.cached_data('brew_not_installed', brew_not_installed, max_age=0):
+ WF.add_item(
+ 'Brew does not seem to be installed!',
+ 'Hit enter to see what you need to do...',
+ arg='open http://brew.sh/#install && exit',
+ valid=True
+ )
+ WF.add_item(
+ 'I trust this workflow',
+ 'Hit enter to install brew...',
+ arg='ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"',
+ valid=True
+ )
+ # delete cached file
+ WF.cache_data('brew_not_installed', None)
+ else:
+ # extract query
+ query = WF.args[0] if len(WF.args) else None
+
+ if query and query.startswith('install'):
+ for formula in get_all_packages(query):
+ WF.add_item(
+ formula, "Install formula",
+ arg='brew install %s' % formula,
+ valid=True,
+ icon=get_icon("package")
+ )
+ elif query and query.startswith('search'):
+ for formula in get_all_packages(query):
+ WF.add_item(
+ formula, "Open formula on GitHub",
+ arg=get_open_link_command(formula),
+ valid=True,
+ icon=get_icon("package")
+ )
+ elif query and query.startswith('uninstall'):
+ for formula in get_installed_packages(query):
+ name = formula.rsplit()[0]
+ WF.add_item(
+ formula, "Uninstall formula",
+ arg='brew uninstall %s' % name,
+ valid=True,
+ icon=get_icon("package")
+ )
+ elif query and query.startswith('list'):
+ for formula in get_installed_packages(query):
+ name = formula.rsplit()[0]
+ WF.add_item(
+ formula, "Open formula on GitHub",
+ arg=get_open_link_command(name),
+ valid=True,
+ icon=get_icon("package")
+ )
+ elif query and query.startswith('info'):
+ info = WF.cached_data(
+ 'brew_info', brew_refresh.get_info, max_age=3600)
+ WF.add_item(
+ info,
+ autocomplete='',
+ icon=get_icon("info")
+ )
+ else:
+ # filter actions by query
+ if query:
+ ACTIONS = WF.filter(
+ query, ACTIONS, key=search_key_for_action, match_on=MATCH_SUBSTRING)
+
+ if len(ACTIONS) > 0:
+ for action in ACTIONS:
+ WF.add_item(
+ action['name'], action['description'],
+ uid=action['name'],
+ autocomplete=action['autocomplete'],
+ arg=action['arg'],
+ valid=action['valid'],
+ icon=get_icon("chevron-right")
+ )
+ else:
+ WF.add_item(
+ "No action found for '%s'" % query,
+ autocomplete="",
+ icon=get_icon("info")
+ )
+
+ if len(WF._items) == 0:
+ WF.add_item(
+ "No formula found for '%s'" % query[query.find(" ") + 1:],
+ autocomplete="%s " % query[:query.find(" ")],
+ icon=get_icon("info")
+ )
+
+ WF.send_feedback()
+
+ # refresh cache
+ cmd = ['/usr/bin/python', WF.workflowfile('brew_refresh.py')]
+ run_in_background('brew_refresh', cmd)
diff --git a/pool/shard009/Python/0083531_setup.py b/pool/shard009/Python/0083531_setup.py
new file mode 100644
index 0000000000000000000000000000000000000000..dd4328780a3f4151401f965e23f9317c01132f38
--- /dev/null
+++ b/pool/shard009/Python/0083531_setup.py
@@ -0,0 +1,166 @@
+#!/usr/bin/env python
+#
+# Copyright (C) 2011, One Laptop Per Child
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+#
+import sys
+import os
+import shutil
+import zipfile
+import tarfile
+from fnmatch import fnmatch
+from sugar3.activity import bundlebuilder
+
+import utils
+
+INCLUDE_DIRS = ['activity', 'binarylibs', 'icons', 'locale', 'bin',
+ 'mwlib', 'po', 'seek-bzip2', 'static', 'tools2']
+IGNORE_FILES = ['.gitignore', 'MANIFEST', '*.pyc', '*~', '*.bak', 'pseudo.po']
+
+
+def list_files(base_dir, filter_directories=False, data_file=None):
+ if filter_directories:
+ include_dirs = INCLUDE_DIRS
+ else:
+ include_dirs = None
+
+ ignore_files = IGNORE_FILES
+ result = []
+
+ base_dir = os.path.abspath(base_dir)
+
+ for root, dirs, files in os.walk(base_dir):
+
+ if ignore_files:
+ for pattern in ignore_files:
+ files = [f for f in files if not fnmatch(f, pattern)]
+
+ rel_path = root[len(base_dir) + 1:]
+ for f in files:
+ result.append(os.path.join(rel_path, f))
+
+ if root == base_dir:
+ n = 0
+ while n < len(dirs):
+ directory = dirs[n]
+ if include_dirs is not None and directory not in include_dirs:
+ dirs.remove(directory)
+ else:
+ n = n + 1
+
+ if data_file is not None:
+ # Add the data files
+ needed_sufix = ['.processed.bz2', '.processed.bz2t']
+ for sufix in needed_sufix:
+ file_name = data_file + sufix
+ result.append(file_name)
+
+ data_dir = os.path.dirname(data_file)
+
+ # add index
+ result.append(os.path.join(data_dir, 'search.db'))
+
+ # add images
+ images_path = os.path.join(base_dir, data_dir, 'images')
+ if os.path.exists(images_path):
+ for file_name in list_files(images_path):
+ result.append(os.path.join(data_dir, 'images', file_name))
+
+ return result
+
+
+class WikiXOPackager(bundlebuilder.XOPackager):
+
+ def __init__(self, builder):
+ bundlebuilder.Packager.__init__(self, builder.config)
+ self.builder = builder
+ self.builder.build_locale()
+ self.package_path = os.path.join(self.config.dist_dir,
+ self.config.xo_name)
+
+ def package(self):
+ bundle_zip = zipfile.ZipFile(self.package_path, 'w',
+ zipfile.ZIP_DEFLATED)
+
+ for f in list_files(self.config.source_dir, True, data_file):
+ if os.path.exists(os.path.join(self.config.source_dir, f)):
+ bundle_zip.write(os.path.join(self.config.source_dir, f),
+ os.path.join(self.config.bundle_root_dir, f))
+ bundle_zip.close()
+
+
+class WikiSourcePackager(bundlebuilder.Packager):
+
+ def __init__(self, config):
+ bundlebuilder.Packager.__init__(self, config)
+ self.package_path = os.path.join(self.config.dist_dir,
+ self.config.tar_name)
+
+ def package(self):
+ tar = tarfile.open(self.package_path, 'w:bz2')
+ for f in list_files('./', True, data_file):
+ tar.add(os.path.join(self.config.source_dir, f),
+ os.path.join(self.config.tar_root_dir, f))
+ tar.close()
+
+
+valid_data_param = False
+if len(sys.argv) >= 3 and not sys.argv[2].startswith('--'):
+ valid_data_param = True
+ data_file = sys.argv[2]
+ if not data_file.endswith(".xml"):
+ print "Data file should be a .xml file"
+ exit()
+
+ lang = data_file[:data_file.find('/')]
+
+ if not os.path.exists(lang):
+ print "Lang directory '%s' does not exist" % lang
+ exit()
+
+ sys.argv.pop()
+
+ # copy activty/activity.info.lang as activty/activity.info
+ f = 'activity/activity.info.' + lang
+ if os.path.exists(f):
+ shutil.copyfile(f, 'activity/activity.info')
+
+if not valid_data_param:
+ config = utils.read_conf_from_info('./')
+ data_file = config['path']
+ lang = data_file[:data_file.find('/')]
+ print "data_file parameter not set, taking config from activity.info file"
+ print "using %s" % data_file
+
+print
+print "Lang:", lang
+print
+
+if lang == 'base':
+ print 'Without a data file will create a .xo/tar.bz2 file with ' \
+ 'sources only'
+ print
+
+print 'To create a wikipedia activity for a specific language'
+print 'add a parameter with the xml data file, like:'
+print
+print './setup.py dist_xo fr/frwiki-20111231-pages-articles.xml'
+print
+
+bundlebuilder.XOPackager = WikiXOPackager
+bundlebuilder.SourcePackager = WikiSourcePackager
+
+bundlebuilder.start()
diff --git a/pool/shard009/Python/0083537_polarisation_dependence_sim.py b/pool/shard009/Python/0083537_polarisation_dependence_sim.py
new file mode 100644
index 0000000000000000000000000000000000000000..7de4aca45fb9986a69a2f0f991047404cbd3ee02
--- /dev/null
+++ b/pool/shard009/Python/0083537_polarisation_dependence_sim.py
@@ -0,0 +1,202 @@
+# -*- coding: utf8 -*-
+"""
+This file contains a simulator for testing polarisation-dependence measurment tools
+
+Qudi 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.
+
+Qudi 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 Qudi. If not, see .
+
+Copyright (c) the Qudi Developers. See the COPYRIGHT.txt file at the
+top-level directory of this distribution and at
+"""
+
+import numpy as np
+import random
+import time
+
+from core.module import Base, Connector
+from interface.motor_interface import MotorInterface
+from interface.slow_counter_interface import SlowCounterInterface
+from qtpy import QtCore
+
+
+class PolarizationDependenceSim(Base, SlowCounterInterface, MotorInterface):
+
+ """ This class wraps the slow-counter dummy and adds polarisation angle dependence in order to simulate dipole polarisation measurements.
+ """
+
+ _modclass = 'polarizationdepsim'
+ _modtype = 'hardware'
+
+ # Connectors
+ counter1 = Connector(interface='SlowCounterInterface')
+
+ _move_signal = QtCore.Signal()
+
+ def on_activate(self):
+ """ Activation of the class
+ """
+ # name connected modules
+ self._counter_hw = self.get_connector('counter1')
+
+ # Required class variables to pretend to be the counter hardware
+ self._photon_source2 = None
+
+ # initialize class variables
+ self.hwp_angle = 0
+
+ self.dipole_angle = random.uniform(0,360)
+
+ self.velocity = 10
+ self.clock_frequency = 50
+ self.forwards_motion = True
+ self.moving = False
+
+ # Signals
+ self._move_signal.connect(self._move_step, QtCore.Qt.QueuedConnection)
+
+ def on_deactivate(self):
+ self._counter_hw.close_counter()
+ self._counter_hw.close_clock()
+
+ # Wrapping the slow counter methods
+ def set_up_clock(self, clock_frequency = None, clock_channel = None):
+ """ Direct pass-through to the counter hardware module
+ """
+ self.clock_frequency = clock_frequency
+ return self._counter_hw.set_up_clock(clock_frequency = clock_frequency, clock_channel = clock_channel)
+
+ def get_constraints(self):
+ """ Pass through counter constraints. """
+ return self._counter_hw.get_constraints()
+
+ def set_up_counter(self,
+ counter_channel=None,
+ photon_source=None,
+ counter_channel2=None,
+ photon_source2=None,
+ clock_channel=None):
+ """ Direct pass-through to the counter hardware module
+ """
+ return self._counter_hw.set_up_counter(counter_channel=counter_channel,
+ photon_source=photon_source,
+ counter_channel2=counter_channel2,
+ photon_source2=photon_source2,
+ clock_channel=clock_channel)
+
+ def get_counter(self, samples=None):
+ """ Direct pass-through to the counter hardware module
+ """
+ raw_count = self._counter_hw.get_counter(samples=samples)
+
+ # modulate the counts with a polarisation dependence
+ angle = np.radians(self.hwp_angle - self.dipole_angle)
+ count = raw_count * np.sin(angle) * np.sin(angle) + random.uniform(-0.1, 0.1)
+ return count
+
+ def close_counter(self):
+ """ Direct pass-through to the counter hardware module
+ """
+ return self._counter_hw.close_counter()
+
+ def close_clock(self, power=0):
+ """ Direct pass-through to the counter hardware module
+ """
+ return self._counter_hw.close_clock(power=power)
+
+ # Satisfy the motor interface
+
+ def move_rel(self, axis=None, distance=None):
+ """ Move the polarisation angle by relative degrees
+ """
+ if distance is None:
+ #TODO warning
+ pass
+
+ self.destination = self.hwp_angle + distance
+
+ # Keep track of the motion direction so we will know when we are past the destination
+ if distance > 0:
+ self.forwards_motion = True
+ else:
+ self.forwards_motion = False
+
+ self.moving = True
+ self._move_signal.emit()
+ return 0
+
+ def move_abs(self, axis=None, position=None):
+ """ Move the polarisation angle to absolute degrees
+ """
+ if position is None:
+ #TODO warning
+ pass
+ self.destination = position
+
+ # Keep track of the motion direction so we will know when we are past the destination
+ if position > self.hwp_angle:
+ self.forwards_motion = True
+ else:
+ self.forwards_motion = False
+
+ self.moving = True
+ self._move_signal.emit()
+ return 0
+
+ def _move_step(self):
+ """Make movement steps in a threaded loop
+ """
+
+ # if abort is requested, then stop moving
+ if not self.moving:
+ return
+
+ # If we have reached the destination then stop the movement
+ if self.forwards_motion:
+ if self.hwp_angle > self.destination:
+ return
+ else:
+ if self.hwp_angle < self.destination:
+ return
+
+ # Otherwise make a movement step
+
+ step_size = self.velocity / self.clock_frequency
+
+ if self.forwards_motion:
+ self.hwp_angle += step_size
+ else:
+ self.hwp_angle -= step_size
+
+ time.sleep(1./self.clock_frequency)
+ self._move_signal.emit()
+
+ def abort(self):
+ self.moving = False
+ return 0
+
+ def get_pos(self, axis=None):
+ return self.hwp_angle
+
+ def get_status(self):
+ return 0
+
+ def calibrate(self, axis=None):
+ self.hwp_angle = 0
+ return 0
+
+ def get_velocity(self, axis=None):
+ return self.velocity
+
+ def set_velocity(self, axis=None, velocity=None):
+ self.velocity = velocity
+ return 0
diff --git a/pool/shard009/Python/0083539_eulerian_cycle.py b/pool/shard009/Python/0083539_eulerian_cycle.py
new file mode 100644
index 0000000000000000000000000000000000000000..ea6f60991446466f89ad31f11c48a742564ddaf8
--- /dev/null
+++ b/pool/shard009/Python/0083539_eulerian_cycle.py
@@ -0,0 +1,143 @@
+# python3
+import queue
+
+
+class Edge:
+ def __init__(self, u, v):
+ self.u = u
+ self.v = v
+
+
+class Graph:
+ def __init__(self, n):
+ self.edges = []
+ self.incoming_edges = []
+ self.graph = [[] for _ in range(n)]
+ self.incoming_graph = [[] for _ in range(n)]
+
+
+ def add_edge(self, from_, to):
+ edge = Edge(from_, to)
+ self.graph[from_].append(len(self.edges))
+ self.edges.append(edge)
+ self.incoming_graph[to].append(len(self.incoming_edges))
+ self.incoming_edges.append(edge)
+
+ def size(self):
+ return len(self.graph)
+
+ def get_ids(self, from_):
+ return self.graph[from_]
+
+ def get_incoming_ids(self, to):
+ return self.incoming_graph[to]
+
+ def get_edge(self, id):
+ return self.edges[id]
+
+ def get_incoming_edge(self, id):
+ return self.incoming_edges[id]
+
+
+
+def read_data():
+ vertex_count, edge_count = map(int, input().split())
+ graph = Graph(vertex_count)
+ for _ in range(edge_count):
+ u, v = map(int, input().split())
+ graph.add_edge(u - 1, v - 1)
+ return graph, vertex_count, edge_count
+
+
+def check_if_balanced(graph):
+ n = graph.size()
+ for v in range(n):
+ out_ids = graph.get_ids(v)
+ in_ids = graph.get_incoming_ids(v)
+ if len(out_ids) != len(in_ids):
+ return False
+ return True
+
+
+def find_next_start(used_vertices):
+ for vertex, is_used in enumerate(used_vertices):
+ if is_used and find_unused_edge(vertex) is not None:
+ return vertex
+
+
+def find_unused_edge(vertex):
+ global used_edges
+ for o_id in graph.get_ids(vertex):
+ if not used_edges[o_id]:
+ return o_id
+
+
+def find_a_cycle(start):
+ global used_edges
+ global used_vertices
+
+ v = -1
+ s = start
+ used_vertices[s] = True
+ cycle = [s]
+ while v != start:
+ o_id = find_unused_edge(s)
+ v = graph.get_edge(o_id).v
+ used_edges[o_id] = True
+ used_vertices[v] = True
+ s = v
+ cycle.append(s)
+
+ cycle = cycle[:-1]
+
+ return cycle
+
+
+def get_result(order_dict, start=0):
+ res = []
+ res.append(start + 1)
+ for v in order_dict[start][1:]:
+ if order_dict.get(v) is None or v + 1 in res:
+ res.append(v + 1)
+ else:
+ res.extend(get_result(order_dict, v))
+ res.append(start + 1)
+ return res
+
+
+def eulerian_cycle(graph):
+ global used_edges
+ global used_vertices
+ global order
+
+ if not check_if_balanced(graph):
+ print(0)
+ exit()
+ else:
+ print(1)
+
+ start = 0
+ #order.append(str(start))
+ while False in used_edges:
+ cycle = find_a_cycle(start)
+ if order.get(start) is None:
+ order[start] = cycle
+ else:
+ order[start] = order[start] + cycle
+ start = find_next_start(used_vertices)
+ if start is None:
+ break
+
+ result = get_result(order)[:-1]
+ print(' '.join(map(str, result)))
+
+
+
+
+
+
+graph, vertex_count, edge_count = read_data()
+used_edges = [False] * edge_count
+used_vertices = [False] * vertex_count
+order = {}
+eulerian_cycle(graph)
\ No newline at end of file
diff --git a/pool/shard009/Python/0083541_parse_go.py b/pool/shard009/Python/0083541_parse_go.py
new file mode 100644
index 0000000000000000000000000000000000000000..391352d80944db74254d33b2ba28b6802bf20e42
--- /dev/null
+++ b/pool/shard009/Python/0083541_parse_go.py
@@ -0,0 +1,63 @@
+from GO import GO
+
+def main():
+ species_prefix = "sgd" # "goa_human"
+ go = GO("../data/gene_ontology.1_2-20_2_2012.obo",
+ False,
+ "../data/gene_association." + species_prefix + ".gz?rev=HEAD", #"../../../data/go/gene_association.goa_uniprot.gz",
+ exclude_evidences=[])
+ print len(go.g.nodes()), len(go.go_id_to_genes)
+ result = []
+ for go_id, data in go.g.nodes(data=True):
+ if go_id not in go.go_id_to_genes:
+ continue
+ desc = data['n']
+ result.append( (desc, [(gene, tax_id) for gene, tax_id in go.go_id_to_genes[go_id]] ) )
+ return
+
+
+def get_go_annotations(file_name, key_identifier="genesymbol", evidences_to_filter=None, tax_id=None):
+ """
+ key_identifier: genesymbol | uniprot
+ tax_id: 9606
+ evindeces_to_filter: ['IKR', 'HMP', 'HEP', 'EXP', 'TAS', 'ISS', 'IEP', 'IPI', 'ND', 'NAS', 'ISM', 'ISO', 'IGI', 'HDA', 'IBA', 'IEA', 'ISA', 'IC', 'IMP', 'IDA']
+ """
+ gene_to_go_ids = {}
+ go_id_to_genes = {}
+ evidences_to_filter = set()
+ if evidences_to_filter is not None:
+ evidences_to_filter = set(evidences_to_filter)
+ molecules_all = set()
+ evidences_all = set()
+ with open(file_name) as f:
+ for line in f.readlines():
+ if line[0] == "!":
+ continue
+ words = line.strip("\n").split("\t")
+ if key_identifier == "genesymbol":
+ gene = words[2]
+ else:
+ gene = words[1]
+ go_term = words[4]
+ evidence = words[6]
+ genes = words[10]
+ molecule = words[11]
+ tax = words[12]
+ molecules_all.add(molecule)
+ evidences_all.add(evidence)
+ #print words
+ #print gene, go_term, evidence, molecule, tax, genes
+ if evidences_to_filter is not None and evidence in evidences_to_filter:
+ continue
+ if tax != "taxon:"+tax_id:
+ continue
+ go_id_to_genes.setdefault(go_term, set()).add(gene)
+ gene_to_go_ids.setdefault(gene, set()).add(go_term)
+ #print molecules_all
+ #print evidences_all
+ return go_id_to_genes, gene_to_go_ids
+
+
+if __name__ == "__main__":
+ main()
+
diff --git a/pool/shard009/Python/0083549_images.py b/pool/shard009/Python/0083549_images.py
new file mode 100644
index 0000000000000000000000000000000000000000..e67707550e5e6e14517d5e1d52d0430ccb52d6db
--- /dev/null
+++ b/pool/shard009/Python/0083549_images.py
@@ -0,0 +1,165 @@
+#!/usr/bin/env python
+
+""" TODO:
+
+We should find a good way in which to store files elsewhere than _static
+
+Make sure that downloaded files are copied to build dir on build
+This must (probably) be done *after* compilation because otherwise dirs
+may not exist.
+
+"""
+
+from urllib2 import urlopen, HTTPError
+import os
+from sys import executable
+
+srcpath = 'http://wiki.fysik.dtu.dk/gpaw-files'
+
+def get(path, names, target=None, source=None):
+ """Get files from web-server.
+
+ Returns True if something new was fetched."""
+
+ if target is None:
+ target = path
+ if source is None:
+ source = srcpath
+ got_something = False
+ for name in names:
+ src = os.path.join(source, path, name)
+ dst = os.path.join(target, name)
+
+ if not os.path.isfile(dst):
+ print dst,
+ try:
+ data = urlopen(src).read()
+ sink = open(dst, 'w')
+ sink.write(data)
+ sink.close()
+ print 'OK'
+ got_something = True
+ except HTTPError:
+ print 'HTTP Error!'
+ return got_something
+
+
+literature = """
+askhl_10302_report.pdf mortensen_gpaw-dev.pdf rostgaard_master.pdf
+askhl_master.pdf mortensen_mini2003talk.pdf rostgaard_paw_notes.pdf
+marco_master.pdf mortensen_paw.pdf
+""".split()
+
+logos = """
+logo-csc.png logo-fmf.png logo-hut.png logo-tree.png
+logo-dtu.png logo-gpaw.png logo-jyu.png logo-tut.png logo-anl.png
+""".split()
+
+
+# flowchart.pdf flowchart.sxd <-- where?
+devel_stuff = """
+gpaw-logo.svg gpaw-logo.odg overview.odg overview.pdf svn-refcard.pdf
+""".split()
+
+architectures_stuff = """
+dynload_redstorm.c
+numpy-1.0.4-gnu.py.patch
+numpy-1.0.4-gnu.py.patch.powerpc-bgp-linux-gfortran
+numpy-1.0.4-site.cfg.lapack_bgp_esslbg
+numpy-1.0.4-system_info.py.patch.lapack_bgp_esslbg
+setup
+unixccompiler.py
+""".split()
+
+get('logos', logos, '_static')
+get('architectures', architectures_stuff, '_static')
+get('doc/literature', literature, '_static')
+get('doc/devel', devel_stuff, '_static')
+get('devel', ['bslogo.png', 'overview.png', 'stat.png'])
+
+# Note: bz-all.png is used both in an exercise and a tutorial. Therefore
+# we put it in the common dir so far, rather than any of the two places
+get('.', ['bz-all.png'], '_static')
+get('exercises/band_structure', ['silicon_banddiagram.png'])
+get('exercises/wavefunctions', ['co_bonding.jpg'])
+
+get('tutorials/bandstructures', ['sodium_bands.png'])
+get('tutorials/ensembles', ['ensemble.png'])
+
+get('.', ['2sigma.png', 'co_wavefunctions.png', 'molecules.png'], '_static')
+get('exercises/lrtddft', ['spectrum.png'])
+get('documentation/xc', 'g2test_pbe0.png g2test_pbe.png results.png'.split())
+get('performance', 'dacapoperf.png goldwire.png gridperf.png'.split(),
+ '_static')
+
+get('tutorials/negfstm', ['fullscan.png', 'linescan.png'])
+
+
+
+
+get('tutorials/xas', ['h2o_xas_3.png', 'h2o_xas_4.png'])
+
+jjwww = 'http://dcwww.camp.dtu.dk/~jensj'
+
+def setup(app):
+ # Generate one page for each setup:
+ if get('setups', ['setups-data.tar.gz'], '_static'):
+ print 'Extracting setup data ...'
+ os.system('tar -C _static -xzf _static/setups-data.tar.gz')
+ print 'Generating setup pages ...'
+ os.system('cd setups; %s make_setup_pages.py' % executable)
+
+ # Retrieve latest code coverage pages:
+ if get('.', ['gpaw-coverage-latest.tar.gz'], '_static',
+ source='http://dcwww.camp.dtu.dk/~chlg'):
+ print 'Extracting coverage pages ...'
+ os.system('tar -C devel -xzf _static/gpaw-coverage-latest.tar.gz')
+
+ # Fallback in case coverage pages were not found
+ if not os.path.isfile('devel/testsuite.rst'):
+ open('devel/testsuite.rst', 'w').write( \
+ '\n'.join(['.. _testsuite:',
+ '', '==========', 'Test suite', '==========',
+ '', '.. warning::', ' Coverage files not found!']))
+ if not os.path.isdir('devel/coverage'):
+ os.mkdir('devel/coverage', 0755)
+ if not os.path.isfile('devel/coverage/index.rst'):
+ open('devel/coverage/index.rst', 'w').write( \
+ '\n'.join(['-----------------------------------',
+ 'List of files with missing coverage',
+ '-----------------------------------',
+ '', 'Back to :ref:`code coverage `.',
+ '', '.. warning::', ' Coverage files not found!']))
+ if not os.path.isfile('devel/coverage/ranking.txt'):
+ open('devel/coverage/ranking.txt', 'w').write( \
+ '\n'.join(['-------------------------------------',
+ 'Distribution of coverage by developer',
+ '-------------------------------------',
+ '', '.. warning::', ' Coverage files not found!']))
+ if not os.path.isfile('devel/coverage/summary.txt'):
+ open('devel/coverage/summary.txt', 'w').write( \
+ '\n'.join(['-------', 'Summary', '-------',
+ '', '.. warning::', ' Coverage files not found!']))
+
+ # Get png files and other stuff from the AGTS scripts that run
+ # every weekend:
+ from gpaw.test.big.agts import AGTSQueue
+ queue = AGTSQueue()
+ queue.collect()
+ names = set()
+ for job in queue.jobs:
+ if job.creates:
+ for name in job.creates:
+ assert name not in names, "Name '%s' clashes!" % name
+ names.add(name)
+ get('gpaw-files', [name], job.dir, source=jjwww)
+
+ # Get files that we can't generate:
+ for dir, file in [
+ ('.', 'camd.png'),
+ ('tutorials/xas', 'xas_illustration.png'),
+ ('tutorials/xas', 'xas_h2o_convergence.png'),
+ ('install/BGP', 'bgp_mapping_intranode.png'),
+ ('install/BGP', 'bgp_mapping1.png'),
+ ('install/BGP', 'bgp_mapping2.png')]:
+ get('gpaw-stuff', [file], dir, jjwww)
diff --git a/pool/shard009/Python/0083554_parallel_runner.py b/pool/shard009/Python/0083554_parallel_runner.py
new file mode 100644
index 0000000000000000000000000000000000000000..1505d85138404f374352e2ec4c81ee1529040f81
--- /dev/null
+++ b/pool/shard009/Python/0083554_parallel_runner.py
@@ -0,0 +1,227 @@
+from lettuce.core import Feature, TotalResult
+
+from lettuce.terrain import after
+from lettuce.terrain import before
+from lettuce.terrain import world
+
+from lettuce.decorators import step
+from lettuce.registry import call_hook
+from lettuce.registry import STEP_REGISTRY
+from lettuce.registry import CALLBACK_REGISTRY
+from lettuce.exceptions import StepLoadingError
+from lettuce.plugins import (
+ xunit_output,
+ autopdb
+)
+from lettuce import fs
+from lettuce import exceptions
+
+from multiprocessing import Pool
+from cStringIO import StringIO
+from itertools import chain
+import os.path
+import sys
+import traceback
+import copy
+
+from importlib import import_module
+
+try:
+ from colorama import init as ms_windows_workaround
+ ms_windows_workaround()
+except ImportError:
+ pass
+
+try:
+ terrain = fs.FileSystem._import("terrain")
+ reload(terrain)
+except Exception, e:
+ if not "No module named terrain" in str(e):
+ string = 'Lettuce has tried to load the conventional environment ' \
+ 'module "terrain"\nbut it has errors, check its contents and ' \
+ 'try to run lettuce again.\n\nOriginal traceback below:\n\n'
+
+ sys.stderr.write(string)
+ sys.stderr.write(exceptions.traceback.format_exc(e))
+ raise SystemExit(1)
+
+
+class ParallelRunner(object):
+ """Parallel lettuce test runner. Runs each feature in a separate process,
+ up to a fixed number in parallel.
+
+ Takes a base path as parameter (string), so that it can look for
+ features and step definitions on there.
+ """
+ def __init__(self, base_path, parallelization=5, scenarios=None,
+ verbosity=0, random=False, enable_xunit=False,
+ xunit_filename=None, tags=None, failfast=False,
+ auto_pdb=False):
+ """ lettuce.Runner will try to find a terrain.py file and
+ import it from within `base_path`
+ """
+
+ self.tags = tags
+ self.explicit_features = []
+
+ if isinstance(base_path, list):
+ self.explicit_features = base_path
+ base_path = os.path.dirname(base_path[0])
+
+ sys.path.insert(0, base_path)
+ self.loader = fs.FeatureLoader(base_path)
+ self.verbosity = verbosity
+ self.scenarios = scenarios and map(int, scenarios.split(",")) or None
+ self.failfast = failfast
+ if auto_pdb:
+ autopdb.enable(self)
+
+ sys.path.remove(base_path)
+
+ if verbosity is 0:
+ output = 'non_verbose'
+ elif verbosity is 1:
+ output = 'dots'
+ elif verbosity is 2:
+ output = 'scenario_names'
+ elif verbosity is 3:
+ output = 'shell_output'
+ else:
+ output = 'colored_shell_output'
+
+ self.random = random
+
+ if enable_xunit:
+ xunit_output.enable(filename=xunit_filename)
+
+ self._output = output
+
+ self.parallelization = parallelization
+
+ @property
+ def output(self):
+ module = import_module('.' + self._output, 'lettuce.plugins')
+ reload(module)
+ return module
+
+ def run(self):
+ """ Find and load step definitions, and them find and load
+ features under `base_path` specified on constructor
+ """
+ try:
+ self.loader.find_and_load_step_definitions()
+ except StepLoadingError, e:
+ print "Error loading step definitions:\n", e
+ return
+
+ results = []
+ if self.explicit_features:
+ features_files = self.explicit_features
+ else:
+ features_files = self.loader.find_feature_files()
+ if self.random:
+ random.shuffle(features_files)
+
+ if not features_files:
+ self.output.print_no_features_found(self.loader.base_dir)
+ return
+
+ processes = Pool(processes=self.parallelization)
+ test_results_it = processes.imap_unordered(
+ worker_process, [(self, filename) for filename in features_files]
+ )
+
+ all_total = ParallelTotalResult()
+ for result in test_results_it:
+ all_total += result['total']
+ sys.stdout.write(result['stdout'])
+ sys.stderr.write(result['stderr'])
+
+ return all_total
+
+def worker_process(args):
+ self, filename = args
+ sys.stdout = StringIO()
+ sys.stderr = StringIO()
+
+ failed = False
+ results = []
+ try:
+ self.output
+ call_hook('before', 'all')
+ feature = Feature.from_file(filename)
+ results.append(
+ feature.run(self.scenarios,
+ tags=self.tags,
+ random=self.random,
+ failfast=self.failfast))
+
+ except exceptions.LettuceSyntaxError, e:
+ sys.stderr.write(e.msg)
+ failed = True
+ except:
+ if not self.failfast:
+ e = sys.exc_info()[1]
+ print "Died with %s" % str(e)
+ traceback.print_exc()
+ else:
+ print
+ print ("Lettuce aborted running any more tests "
+ "because was called with the `--failfast` option")
+
+ failed = True
+
+ finally:
+ total = TotalResult(results)
+ call_hook('after', 'all', total)
+
+ return {
+ 'stdout': sys.stdout.getvalue(),
+ 'stderr': sys.stderr.getvalue(),
+ 'failed': failed,
+ 'total': ParallelTotalResult(total),
+ }
+
+class ParallelTotalResult(object):
+ def __init__(self, total=None):
+ self.steps_passed = 0
+ self.steps_failed = 0
+ self.steps_skipped = 0
+ self.steps_undefined = 0
+ self.steps = 0
+ scenario_results = []
+ if total:
+ feature_results = total.feature_results
+ self.features_ran = len(feature_results)
+ self.features_passed = len([result for result in feature_results if result.passed])
+ for feature_result in feature_results:
+ for scenario_result in feature_result.scenario_results:
+ self.steps_passed += len(scenario_result.steps_passed)
+ self.steps_failed += len(scenario_result.steps_failed)
+ self.steps_skipped += len(scenario_result.steps_skipped)
+ self.steps_undefined += len(scenario_result.steps_undefined)
+ self.steps += scenario_result.total_steps
+ scenario_results.append(scenario_result)
+ self.scenarios_ran = len(scenario_results)
+ self.scenarios_passed = len([result for result in scenario_results if result.passed])
+ else:
+ self.features_ran = 0
+ self.features_passed = 0
+ self.scenarios_ran = 0
+ self.scenarios_passed = 0
+
+ def _filter_proposed_definitions(self):
+ raise NotImplementedError()
+
+ @property
+ def proposed_definitions(self):
+ raise NotImplementedError()
+
+ def __add__(self, other):
+ new_ptr = copy.copy(self)
+ for attr in new_ptr.__dict__:
+ if isinstance(getattr(new_ptr, attr), int):
+ setattr(new_ptr, attr,
+ getattr(new_ptr, attr) + getattr(other, attr))
+ return new_ptr
+
diff --git a/pool/shard009/Python/0083556_config.py b/pool/shard009/Python/0083556_config.py
new file mode 100644
index 0000000000000000000000000000000000000000..118316473a84de1ade03a216321f9aea80382ee8
--- /dev/null
+++ b/pool/shard009/Python/0083556_config.py
@@ -0,0 +1,47 @@
+# -*- coding: utf-8 -*-
+
+"""
+Module :mod:`config` contains the configurable features
+"""
+
+import os
+
+__author__ = "Begon Jean-Michel "
+__copyright__ = "3-clause BSD License"
+
+
+__CT_FOLDER__ = "clustertools_data"
+
+__CT_FOLDER_ENVVAR__ = "CT_FOLDER" # environment variable for the folder
+__CT_ENVIRONMENT_ENVVARS__ = "CT_ENVIRONMENT" # env var for preferred environment
+
+
+def get_ct_folder():
+ folder = os.environ.get(__CT_FOLDER_ENVVAR__)
+ if folder is None:
+ folder = os.path.join(os.path.expanduser("~"), __CT_FOLDER__)
+ return folder
+
+
+def get_default_environment(environment_cls=None):
+ if environment_cls is not None:
+ return environment_cls
+
+ from .environment import __CT_ENVIRONMENTS__
+
+ # Check environment variable
+ env_name_var = os.environ.get(__CT_ENVIRONMENT_ENVVARS__)
+ if env_name_var is not None:
+ for env_name, environment_cls in __CT_ENVIRONMENTS__:
+ if env_name == env_name_var:
+ return environment_cls
+
+ # Check config file
+ # TODO later
+
+ # Check what exists
+ for _, environment_cls in __CT_ENVIRONMENTS__:
+ if environment_cls.is_usable():
+ return environment_cls
+
+
diff --git a/pool/shard009/Python/0083563_fastfibonacci.py b/pool/shard009/Python/0083563_fastfibonacci.py
new file mode 100644
index 0000000000000000000000000000000000000000..21ce5913362e845c817ffacfe9071176fab1edc2
--- /dev/null
+++ b/pool/shard009/Python/0083563_fastfibonacci.py
@@ -0,0 +1,31 @@
+# https://www.nayuki.io/res/fast-fibonacci-algorithms/fastfibonacci.py
+# Acessado em 21/01/2017
+
+#
+# Fast doubling Fibonacci algorithm (Python)
+#
+# Copyright (c) 2015 Project Nayuki
+# All rights reserved. Contact Nayuki for licensing.
+# https://www.nayuki.io/page/fast-fibonacci-algorithms
+#
+
+
+# (Public) Returns F(n).
+def fibonacci(n):
+ if n < 0:
+ raise ValueError("Negative arguments not implemented")
+ return _fib(n)[0]
+
+
+# (Private) Returns the tuple (F(n), F(n+1)).
+def _fib(n):
+ if n == 0:
+ return (0, 1)
+ else:
+ a, b = _fib(n // 2)
+ c = a * (b * 2 - a)
+ d = a * a + b * b
+ if n % 2 == 0:
+ return (c, d)
+ else:
+ return (d, c + d)
diff --git a/pool/shard009/Python/0083570_checkpoint.py b/pool/shard009/Python/0083570_checkpoint.py
new file mode 100644
index 0000000000000000000000000000000000000000..a4acc639e4cd750034515b5fca5084f526c80cd0
--- /dev/null
+++ b/pool/shard009/Python/0083570_checkpoint.py
@@ -0,0 +1,20 @@
+from geo_point import GeoPoint
+
+class Checkpoint(object):
+
+ def __init__(self):
+ self.id = None
+ self.location = None
+
+ @staticmethod
+ def row_to_object(row):
+ checkpoint = Checkpoint()
+ checkpoint.id = row.id
+ checkpoint.location = GeoPoint.row_to_object(row.location)
+ return checkpoint
+
+ def to_dict(self):
+ dict_data = {};
+ dict_data['id'] = str(self.id)
+ dict_data['location'] = self.location.to_dict()
+ return dict_data
\ No newline at end of file
diff --git a/pool/shard009/Python/0083576_pconf.py b/pool/shard009/Python/0083576_pconf.py
new file mode 100644
index 0000000000000000000000000000000000000000..ba00ce27a7d926ab6568ae72fe8c4c9d9542ece6
--- /dev/null
+++ b/pool/shard009/Python/0083576_pconf.py
@@ -0,0 +1,118 @@
+#!/usr/bin/python2
+# -*- coding=utf-8 -*-
+
+
+import getpass, json, os, datetime
+
+default_config = {}
+default_config['debug'] = True
+default_config['version'] = "0.0.2"
+default_config['user_agent'] = "Mozilla/5.0 (X11; Linux i686; rv:58.0) Gecko/20100101 Firefox/58.0"
+default_config['urls'] = {}
+default_config['urls']['login'] = "https://securelogin.poste.it/jod-fcc/login"
+default_config['urls']['logout'] = "https://securelogin.poste.it/jod-fcc/logout?_referer=https://www.poste.it/index.html"
+default_config['urls']['home'] = "https://www.poste.it/myposte/index.html"
+default_config['urls']['bpol'] = {}
+default_config['urls']['bpol']['home'] = "https://bancoposta.poste.it/bpol/public/BPOL_ListaMovimentiAPP/index.html#/"
+default_config['urls']['bpol']['lista_mov'] = "https://bancoposta.poste.it/bpol/BPOL_ListaMovimentiAPP/rest/listaMovimenti"
+default_config['urls']['bpol']['conti'] = "https://bancoposta.poste.it/bpol/BPOL_ListaContiAPP/rest/conti"
+default_config['urls']['bpol']['titolare'] = "https://bancoposta.poste.it/bpol/BPOL_ListaContiAPP/rest/titolareEffettivo"
+default_config['urls']['bpol']['conf'] = "https://bancoposta.poste.it/bpol/bpol/BPOL_ConfigurazioniAPP/rest/configurazioni"
+default_config['urls']['postepay'] = {}
+default_config['urls']['postepay']['home'] = "https://postepay.poste.it/portalppay/startListaMovimentiAction.do"
+default_config['urls']['postepay']['view'] = "https://postepay.poste.it/portalppay/viewListaMovimentiAction.do"
+
+
+class Config:
+ def __init__(self):
+ self.__dir_conf = os.environ['HOME'] + "/.config/posteit"
+
+ if not os.path.exists(self.__dir_conf):
+ os.makedirs(self.__dir_conf)
+
+ self.__dir_log = self.__dir_conf + "/log"
+ self.__file_conf = self.__dir_conf + "/config.json"
+ self.__file_cookie = self.__dir_conf + "/header.json"
+ self.__file_csv = self.__dir_conf + "/summary.csv"
+
+ if not os.path.exists(self.__dir_log):
+ os.makedirs(self.__dir_log)
+
+ #load config or make it
+ if not os.path.exists(self.__file_conf):
+ self.__makeConf()
+ with open(self.__file_conf) as data_file:
+ self.__data_conf = json.load(data_file)
+
+ def getData(self):
+ return self.__data_conf
+
+ def getLogDir(self):
+ return self.__dir_log
+
+ def getConfDir(self):
+ return self.__dir_conf
+
+ def __makeConf(self):
+ self.__data = default_config
+ self.__data['username'] = raw_input("Inserisci il nome utente:\n")
+ print
+ print "Inserisci la password:"
+ self.__data['password'] = getpass.getpass()
+ print
+ self.__data['numero_conto'] = raw_input("Inserisci il numero conto:\n")
+ print
+ print "i valori verranno salvati in " + self.__file_conf
+
+ file = open(self.__file_conf, "w")
+ data = json.dumps(self.__data, indent=4, separators=(',', ': '), sort_keys=True)
+ file.write(data)
+ file.close()
+
+ def getCookie(self):
+ #load file cookie
+ if os.path.exists(self.__file_cookie):
+ with open(self.__file_cookie) as data_file:
+ cookie_json = json.load(data_file)
+ return cookie_json['dict']['set-cookie']
+ else:
+ return None
+
+ def setCookie(self, headers):
+ file = open(self.__file_cookie, "w")
+ data = json.dumps(headers.__dict__, indent=4, separators=(',', ': '), sort_keys=True)
+ file.write(data)
+ file.close()
+
+ def delCookie(self):
+ if os.path.exists(self.__file_cookie):
+ os.remove(self.__file_cookie)
+
+ def write_csv(self, content):
+ f = open(self.__file_csv, "w")
+ f.write(content)
+ f.close()
+
+ def write_html(self, name, contents):
+ f = self.__getFile(name, ".html")
+ f.write(contents)
+ f.close()
+
+
+ def write_json(self, name, contents):
+ f = self.__getFile(name, ".json")
+ data = json.dumps(contents, indent=4, separators=(',', ': '))
+ f.write(data)
+ f.close()
+
+ def __getFile(self, name, ext):
+ date = self.__getDate()
+ logDir = self.getLogDir()
+ filename = logDir + "/" + name + date + ext
+ f = open(filename, "w")
+ print "DEBUG: write " + filename
+ return f
+
+ def __getDate(self):
+ date_now = datetime.datetime.now()
+ return date_now.strftime("%Y%m%d-%H%M%s")
diff --git a/pool/shard009/Python/0083577_test_endpoint.py b/pool/shard009/Python/0083577_test_endpoint.py
new file mode 100644
index 0000000000000000000000000000000000000000..6247fc9f486fc29a04bd0bccc9122dec46571cfe
--- /dev/null
+++ b/pool/shard009/Python/0083577_test_endpoint.py
@@ -0,0 +1,53 @@
+import unittest
+import urllib
+
+from urlparse import urlunparse
+from restkit import Resource, request, BasicAuth
+from restkit.errors import Unauthorized
+from config import server
+
+try:
+ from json import loads
+except ImportError:
+ from simplejson import loads
+
+try:
+ from urlparse import parse_qsl
+except ImportError:
+ from cgi import parse_qsl
+
+class AuthToken(object):
+ def __init__(self, token):
+ self.token = token
+
+ def on_request(self, request):
+ parsed_url = request.parsed_url
+ params = {'auth_token': self.token}
+ params.update(parse_qsl(parsed_url.query))
+ request.url = urlunparse((parsed_url.scheme, parsed_url.netloc, parsed_url.path,
+ parsed_url.params, urllib.urlencode(params, True),
+ parsed_url.fragment))
+
+class TestEndpoint(unittest.TestCase):
+ def setUp(self):
+ auth = BasicAuth('john', 'teste')
+ res = Resource(server, filters=[auth, ])
+ r = res.get('/authenticate')
+ data = loads(r.body_string())
+
+ self.auth = AuthToken(data.get('token'))
+ self.res = Resource(server, filters=[self.auth, ])
+
+ def testAuthentication(self):
+ r = self.res.get('/')
+ self.assertEqual(200, r.status_int)
+
+ try:
+ res = Resource(server)
+ r = res.get('/')
+ self.assertTrue(False)
+ except Unauthorized, e:
+ self.assertTrue(True)
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/pool/shard009/Python/0083579_setup.py b/pool/shard009/Python/0083579_setup.py
new file mode 100644
index 0000000000000000000000000000000000000000..d08c0c313d1b097c8b088b1439f2f5a5019be86b
--- /dev/null
+++ b/pool/shard009/Python/0083579_setup.py
@@ -0,0 +1,143 @@
+from setuptools import setup, Extension, find_packages, distutils
+from setuptools.command.build_ext import build_ext
+import sys, os
+
+# if we want to use conda compilers (which pick up llvm-openmp and fftw3 automatically)
+if sys.platform == "darwin":
+ os.environ["CC"]="clang"
+ os.environ["CXX"]="clang++"
+
+class get_pybind_include(object):
+ """Helper class to determine the pybind11 include path
+ The purpose of this class is to postpone importing pybind11
+ until it is actually installed, so that the ``get_include()``
+ method can be invoked. """
+
+ def __init__(self, user=False):
+ self.user = user
+
+ def __str__(self):
+ import pybind11
+ return pybind11.get_include(self.user)
+
+ext_modules = [
+ Extension(
+ 'basic_cpp',
+ ['pyms/basic/basic_cpp.cpp'],
+ include_dirs=[
+ # Path to pybind11 headers
+ get_pybind_include(),
+ get_pybind_include(user=True),
+ 'pyms/mlpy/'
+ ],
+ libraries=[],
+ extra_compile_args=[],
+ extra_link_args=[],
+ language='c++'
+ ),
+ Extension(
+ 'bandpass_filter_cpp',
+ ['pyms/basic/bandpass_filter_cpp.cpp','pyms/basic/bandpass_filter_kernel.cpp'],
+ include_dirs=[
+ # Path to pybind11 headers
+ get_pybind_include(),
+ get_pybind_include(user=True),
+ 'pyms/mlpy/'
+ ],
+ libraries=[],
+ extra_compile_args=[],# flags ignored here? hardcoded below ( https://github.com/pybind/python_example/issues/23 )
+ extra_link_args=['-fopenmp', '-lfftw3'], # -fopenmp -lfftw3 also needs to be passed to the linker
+ language='c++'
+ )]
+
+# As of Python 3.6, CCompiler has a `has_flag` method.
+# cf http://bugs.python.org/issue26689
+def has_flag(compiler, flagname):
+ """Return a boolean indicating whether a flag name is supported on
+ the specified compiler.
+ """
+ import tempfile
+ with tempfile.NamedTemporaryFile('w', suffix='.cpp') as f:
+ f.write('int main (int argc, char **argv) { return 0; }')
+ try:
+ compiler.compile([f.name], extra_postargs=[flagname])
+ except distutils.errors.CompileError:
+ return False
+ return True
+
+# Note C++11 is needed by pybind11, not by the project:
+def cpp_flag(compiler):
+ """Return the -std=c++[11/14] compiler flag.
+ The c++14 is prefered over c++11 (when it is available).
+ """
+ if has_flag(compiler, '-std=c++14'):
+ return '-std=c++14'
+ elif has_flag(compiler, '-std=c++11'):
+ return '-std=c++11'
+ else:
+ raise RuntimeError('Unsupported compiler -- at least C++11 support '
+ 'is needed!')
+
+
+class BuildExt(build_ext):
+ """A custom build extension for adding compiler-specific options."""
+ c_opts = {
+ 'msvc': ['/EHsc'],
+ 'unix': [],
+ }
+
+ if sys.platform == 'darwin':
+ c_opts['unix'] += ['-stdlib=libc++', '-mmacosx-version-min=10.7']
+
+ def build_extensions(self):
+ ct = self.compiler.compiler_type
+ opts = self.c_opts.get(ct, [])
+ if ct == 'unix':
+ opts.append('-fopenmp')
+ opts.append('-lfftw3')
+ opts.append('-DVERSION_INFO="%s"' % self.distribution.get_version())
+ opts.append(cpp_flag(self.compiler)) # AHB: C++11 not used now, but David Stein says needed.
+ if has_flag(self.compiler, '-fvisibility=hidden'):
+ opts.append('-fvisibility=hidden')
+ elif ct == 'msvc':
+ opts.append('/DVERSION_INFO=\\"%s\\"' % self.distribution.get_version())
+ for ext in self.extensions:
+ ext.extra_compile_args = opts
+ build_ext.build_extensions(self)
+
+pkgs = find_packages()
+print('found these packages:', pkgs)
+
+with open("README.md", "r") as fh:
+ long_description = fh.read()
+
+setup(
+ name="ml_pyms",
+ version="0.0.1",
+ author="Jeremy Magland",
+ author_email="",
+ description="python processors for legacy mountainsort 3",
+ long_description=long_description,
+ long_description_content_type="text/markdown",
+ url="https://github.com/magland/mountainsort",
+ packages=pkgs,
+ package_data={
+ '': ['*.mp'], # Include all processor files
+ },
+ ext_modules=ext_modules,
+ cmdclass={'build_ext': BuildExt},
+ install_requires=
+ [
+ 'pybind11>=2.2',
+ 'numpy',
+ 'numpydoc',
+ 'scipy',
+ 'matplotlib',
+ 'sklearn'
+ ],
+ classifiers=(
+ "Programming Language :: Python :: 3",
+ "License :: OSI Approved :: Apache Software License",
+ "Operating System :: OS Independent",
+ ),
+)
diff --git a/pool/shard009/Python/0083580_form.py b/pool/shard009/Python/0083580_form.py
new file mode 100644
index 0000000000000000000000000000000000000000..52da31b191cb4c1c3778ad541487b431dfd78b8e
--- /dev/null
+++ b/pool/shard009/Python/0083580_form.py
@@ -0,0 +1,198 @@
+import inspect
+
+from flask.ext.admin.form import BaseForm, rules
+from flask.ext.admin._compat import iteritems
+
+
+def converts(*args):
+ def _inner(func):
+ func._converter_for = frozenset(args)
+ return func
+ return _inner
+
+
+class InlineBaseFormAdmin(object):
+ """
+ Settings for inline form administration.
+
+ You can use this class to customize displayed form.
+ For example::
+
+ class MyUserInfoForm(InlineBaseFormAdmin):
+ form_columns = ('name', 'email')
+ """
+ _defaults = ['form_base_class', 'form_columns', 'form_excluded_columns', 'form_args', 'form_extra_fields']
+
+ def __init__(self, **kwargs):
+ """
+ Constructor
+
+ :param kwargs:
+ Additional options
+ """
+ for k in self._defaults:
+ if not hasattr(self, k):
+ setattr(self, k, None)
+
+ for k, v in iteritems(kwargs):
+ setattr(self, k, v)
+
+ # Convert form rules
+ form_rules = getattr(self, 'form_rules', None)
+
+ if form_rules:
+ self._form_rules = rules.RuleSet(self, form_rules)
+ else:
+ self._form_rules = None
+
+ def get_form(self):
+ """
+ If you want to use completely custom form for inline field, you can override
+ Flask-Admin form generation logic by overriding this method and returning your form.
+ """
+ return None
+
+ def postprocess_form(self, form_class):
+ """
+ Post process form. Use this to contribute fields.
+
+ For example::
+
+ class MyInlineForm(InlineFormAdmin):
+ def postprocess_form(self, form):
+ form.value = TextField('value')
+ return form
+
+ class MyAdmin(ModelView):
+ inline_models = (MyInlineForm(ValueModel),)
+ """
+ return form_class
+
+ def on_model_change(self, form, model):
+ """
+ Called when inline model is about to be saved.
+
+ :param form:
+ Inline form
+ :param model:
+ Model
+ """
+ pass
+
+
+class InlineFormAdmin(InlineBaseFormAdmin):
+ """
+ Settings for inline form administration. Used by relational backends (SQLAlchemy, Peewee), where model
+ class can not be inherited from the parent model definition.
+ """
+ def __init__(self, model, **kwargs):
+ """
+ Constructor
+
+ :param model:
+ Model class
+ """
+ self.model = model
+
+ super(InlineFormAdmin, self).__init__(**kwargs)
+
+
+class ModelConverterBase(object):
+ def __init__(self, converters=None, use_mro=True):
+ self.use_mro = use_mro
+
+ if not converters:
+ converters = {}
+
+ for name in dir(self):
+ obj = getattr(self, name)
+ if hasattr(obj, '_converter_for'):
+ for classname in obj._converter_for:
+ converters[classname] = obj
+
+ self.converters = converters
+
+ def get_converter(self, column):
+ if self.use_mro:
+ types = inspect.getmro(type(column.type))
+ else:
+ types = [type(column.type)]
+
+ # Search by module + name
+ for col_type in types:
+ type_string = '%s.%s' % (col_type.__module__, col_type.__name__)
+
+ if type_string in self.converters:
+ return self.converters[type_string]
+
+ # Search by name
+ for col_type in types:
+ if col_type.__name__ in self.converters:
+ return self.converters[col_type.__name__]
+
+ return None
+
+ def get_form(self, model, base_class=BaseForm,
+ only=None, exclude=None,
+ field_args=None):
+ raise NotImplemented()
+
+
+class InlineModelConverterBase(object):
+ form_admin_class = InlineFormAdmin
+
+ def __init__(self, view):
+ """
+ Base constructor
+
+ :param view:
+ View class
+ """
+ self.view = view
+
+ def get_label(self, info, name):
+ """
+ Get inline model field label
+
+ :param info:
+ Inline model info
+ :param name:
+ Field name
+ """
+ form_name = getattr(info, 'form_label', None)
+ if form_name:
+ return form_name
+
+ column_labels = getattr(self.view, 'column_labels', None)
+
+ if column_labels and name in column_labels:
+ return column_labels[name]
+
+ return None
+
+ def get_info(self, p):
+ """
+ Figure out InlineFormAdmin information.
+
+ :param p:
+ Inline model. Can be one of:
+
+ - ``tuple``, first value is related model instance,
+ second is dictionary with options
+ - ``InlineFormAdmin`` instance
+ - Model class
+ """
+ if isinstance(p, tuple):
+ return self.form_admin_class(p[0], **p[1])
+ elif isinstance(p, self.form_admin_class):
+ return p
+
+ return None
+
+
+class FieldPlaceholder(object):
+ """
+ Field placeholder for model convertors.
+ """
+ def __init__(self, field):
+ self.field = field
diff --git a/pool/shard009/Python/0083581_LRUCache.py b/pool/shard009/Python/0083581_LRUCache.py
new file mode 100644
index 0000000000000000000000000000000000000000..b98ee474875931c3d2869c79d8ad39287e1a786b
--- /dev/null
+++ b/pool/shard009/Python/0083581_LRUCache.py
@@ -0,0 +1,58 @@
+'''
+ * PTStemmer - A Stemming toolkit for the Portuguese language (C) 2008-2010 Pedro Oliveira
+ *
+ * This file is part of PTStemmer.
+ * PTStemmer is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * PTStemmer is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with PTStemmer. If not, see .
+'''
+
+class LRUCache(object):
+ '''
+ Simple Least Recently Used (LRU) Cache implementation
+ @author: Pedro Oliveira
+ '''
+
+ def __init__(self,size):
+ self.size = size
+ self.__cache = {}
+ self.__lru = []
+
+ def __len__(self):
+ return len(self.__lru)
+
+ def __contains__(self, key):
+ return self.__cache.has_key(key)
+
+ def __setitem__(self, key, obj):
+ if self.__cache.has_key(key):
+ self.__lru.remove(key)
+ else:
+ if len(self.__lru) == self.size:
+ self.__cache.pop(self.__lru.pop())
+ self.__cache[key] = obj
+ self.__lru.insert(0, key)
+
+ def __getitem__(self, key):
+ if self.__cache.has_key(key):
+ n = self.__cache[key]
+ self.__lru.remove(key)
+ self.__lru.insert(0, key)
+ return n
+ return None
+
+if __name__ == "__main__":
+ cache = LRUCache(10)
+ for i in range(11):
+ cache[i] = str(i)
+ print cache[0], cache[1]
+
\ No newline at end of file
diff --git a/pool/shard009/Python/0083587_wowin.py b/pool/shard009/Python/0083587_wowin.py
new file mode 100644
index 0000000000000000000000000000000000000000..53cea6e27a54078568e2638662dd5649f4a0527b
--- /dev/null
+++ b/pool/shard009/Python/0083587_wowin.py
@@ -0,0 +1,125 @@
+#!/usr/bin/python
+# -*- coding: utf-8 -*-
+"""wowin.py: A client for automatize WoW (3.3.5) login
+ using sockets and a variation of SRP6.
+It is be able to autovote too.
+Edit accounts.txt file in the following format to use this script:
+
+username:password
+username2:password2
+
+Requirements:
+ pip install bs4
+ pip install schedule
+"""
+
+import socket
+import time
+import schedule
+import datetime
+from wrsp import Wrsp
+import sys
+import requests
+from BeautifulSoup import BeautifulSoup # A wonderful module for HTML parsing
+# import json
+
+
+def hilite(string, status=False, bold=False):
+ """If tty highligth the output."""
+
+ if not sys.stdout.isatty():
+ return string
+ attr = []
+ if status:
+ attr.append('32') # Green
+ else:
+ attr.append('31') # Red
+ if bold:
+ attr.append('1')
+ return '\x1b[%sm%s\x1b[0m' % (';'.join(attr), string)
+
+
+def autovote(username, password):
+ """Starts the autovote."""
+
+ url_0 = 'http://www.warmane.com/account/login'
+ url = 'http://www.warmane.com/account'
+ # Start a new session, to preserve the cookie
+ global s
+ s = requests.session()
+ # Take session and anti-csrf Token
+ t = s.get(url)
+ soup = BeautifulSoup(t.text)
+ #
+ token = soup.find("meta", {"name": "csrf-token"})['content']
+ # The login POST payload
+ login_payload = {
+ 'userID': username,
+ 'userPW': password
+ }
+ # The vote POST payload
+ vote_payload = {
+ 'collectpoints': 'true'
+ }
+ login_headers = {
+ 'Accept': 'application/json, text/javascript, */*; q=0.01',
+ 'Origin': 'http://www.warmane.com',
+ 'X-CSRF-Token': token,
+ 'X-Requested-With': 'XMLHttpRequest',
+ 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
+ 'Referer': url_0,
+ 'Accept-Encoding': 'gzip, deflate'
+ }
+ vote_headers = {
+ 'Accept': 'application/json, text/javascript, */*; q=0.01',
+ 'Origin': 'http://www.warmane.com',
+ 'X-CSRF-Token': token,
+ 'X-Requested-With': 'XMLHttpRequest',
+ 'Accept-Language': 'it-it',
+ 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
+ 'Referer': url,
+ 'Accept-Encoding': 'gzip, deflate'
+ }
+ try:
+ l_response = s.post(url_0, data=login_payload, headers=login_headers)
+ vote_response = s.post(url, data=vote_payload, headers=vote_headers)
+ if vote_response.json()['messages'].has_key('error'):
+ print hilite("Error:", False, True) # Bold
+ # Show the site-returned error
+ print hilite(vote_response.json()['messages']['error'][0])
+ else:
+ print "Now you have: ",
+ print hilite(vote_response.json().get('points')[0], True),
+ print " votepoints"
+ except Exception:
+ print hilite("Login failed for " + username)
+
+
+def main():
+ # Server data
+ host = "logon.warmane.ru"
+ n_of_trying = 3
+ # port = 3724
+ # Get login data from file
+ f = file("accounts.txt", 'r')
+ for line in f.readlines():
+ user, password = line.rstrip().split(":")
+ # Connect to WoW server to emulate ingame-login!
+ mypacket = Wrsp(user, password, socket.gethostbyname(host))
+ for i in range(n_of_trying): # Trying to connect to server more than oncs
+ if mypacket.login():
+ print hilite("User " + user + " logged in-game succesfully!", True)
+ mypacket.show_realm()
+ break
+ else:
+ print "Login failed for: " + user
+ # Autovote also if ingame login failed. Just try (user was on on the last 24h?)
+ autovote(user, password)
+ print "End of daily vote:", str(datetime.date.today())
+
+main()
+schedule.every().day.at("03:00").do(main)
+#schedule.every(1).minute.do(main)
+while True:
+ schedule.run_pending()
+ time.sleep(20) # Wait one minute
diff --git a/pool/shard009/Python/0083593_test_backup.py b/pool/shard009/Python/0083593_test_backup.py
new file mode 100644
index 0000000000000000000000000000000000000000..814be0274097edb6aa3dbde1e2d8324e6734e670
--- /dev/null
+++ b/pool/shard009/Python/0083593_test_backup.py
@@ -0,0 +1,99 @@
+import mock
+import unittest
+import copy
+
+from backup.backup import Backup
+from fixtures import config
+
+
+class TestBackup(unittest.TestCase):
+
+ def setUp(self):
+ """Initializer, unittest-style"""
+ super(TestBackup, self).setUp()
+
+ def tearDown(self):
+ """Destructor, unittest-style"""
+ super(TestBackup, self).tearDown()
+
+ @mock.patch.object(Backup, 'set_tmp_folder')
+ def test_init_backup_defaults(self, mock_set_folder):
+ config_changed = copy.deepcopy(config)
+ del config_changed['tmp']
+ backup = Backup(config_changed)
+ # Just check we got defaults
+ self.assertEqual(backup.subFoldersNum, backup.subFoldersNumDefault)
+ self.assertTrue(mock_set_folder.called)
+
+ @mock.patch.object(Backup, 'set_tmp_folder')
+ def test_init_backup_with_config(self, mock_set_folder):
+ backup = Backup(config)
+ self.assertEqual(backup.subFoldersNum, config['tmp']['subFolders'])
+ self.assertTrue(mock_set_folder.called)
+
+ @mock.patch('backup.backup.os.path')
+ @mock.patch('backup.backup.os')
+ def test_set_tmp_folder_absolute(self, mock_os, mock_path):
+ mock_path.isdir.return_value = False
+ tmp_folder = '/some/path/to/nowhere'
+ backup = Backup(config)
+ backup.set_tmp_folder(tmp_folder)
+ self.assertEqual(backup.tmpFolder, tmp_folder)
+ mock_path.isdir.assert_called_with(tmp_folder)
+ # Temporary folder has been created
+ mock_os.makedirs.assert_called_with(tmp_folder)
+
+ def test_set_tmp_folder_relative(self):
+ pass
+
+ @mock.patch('backup.backup.os')
+ def test_create_current_folder_by_time(self, mock_os):
+ backup = Backup(config)
+ current_time = (2015, 12, 20, 23, 26, 30, 6, 354, 0)
+ folder_name = backup.create_current_folder_by_time(current_time)
+ self.assertTrue(mock_os.mkdir.called)
+ self.assertEqual(folder_name, ''.join(str(x) for x in current_time[:6]))
+
+ @mock.patch('backup.backup.call')
+ @mock.patch('backup.backup.os')
+ @mock.patch('backup.backup.rmtree')
+ @mock.patch('backup.backup.os.path')
+ def test_archive_with_directories(self, mock_path, mock_rmtree, mock_os, mock_call):
+ mock_os.listdir.return_value = ['123123123', '234234234']
+ mock_path.isdir.return_value = True
+ backup = Backup(config)
+ backup.archive()
+ self.assertTrue(mock_os.listdir.called)
+ self.assertTrue(mock_call.called)
+ self.assertTrue(mock_rmtree.called)
+
+ @mock.patch('backup.backup.call')
+ @mock.patch('backup.backup.os')
+ @mock.patch('backup.backup.rmtree')
+ @mock.patch('backup.backup.os.path')
+ def test_archive_without_directories(self, mock_path, mock_rmtree, mock_os, mock_call):
+ backup = Backup(config)
+ backup.archive()
+ self.assertTrue(mock_os.listdir.called)
+ self.assertFalse(mock_call.called)
+ self.assertFalse(mock_rmtree.called)
+
+ @mock.patch('backup.backup.os')
+ @mock.patch('backup.backup.os.path')
+ def test_cleanup_sub_folders_with_directories_less_than_required(self, mock_path, mock_os):
+ mock_os.listdir.return_value = ['123123123', '234234234']
+ mock_path.isfile.return_value = True
+ backup = Backup(config)
+ backup.cleanup_sub_folders()
+ self.assertTrue(mock_os.listdir.called)
+ self.assertFalse(mock_os.remove.called)
+
+ @mock.patch('backup.backup.os')
+ @mock.patch('backup.backup.os.path')
+ def test_cleanup_sub_folders_with_directories(self, mock_path, mock_os):
+ mock_os.listdir.return_value = ['1', '2', '3', '4', '5', '6', '7', '8']
+ mock_path.isfile.return_value = True
+ backup = Backup(config)
+ backup.cleanup_sub_folders()
+ self.assertTrue(mock_os.listdir.called)
+ self.assertTrue(mock_os.remove.called)
diff --git a/pool/shard009/Python/0083602_api.py b/pool/shard009/Python/0083602_api.py
new file mode 100644
index 0000000000000000000000000000000000000000..50b7103ca493ca3b397e3915f778f55feeb7253a
--- /dev/null
+++ b/pool/shard009/Python/0083602_api.py
@@ -0,0 +1,202 @@
+# coding: utf-8
+import json
+import logging
+import os
+import re
+import subprocess
+
+import coverage
+import requests
+import yaml
+
+from .reporter import CoverallReporter
+
+
+log = logging.getLogger('coveralls')
+
+
+class CoverallsException(Exception):
+ pass
+
+
+class Coveralls(object):
+ config_filename = '.coveralls.yml'
+ api_endpoint = 'https://coveralls.io/api/v1/jobs'
+ default_client = 'coveralls-python'
+
+ def __init__(self, **kwargs):
+ """ Coveralls!
+
+ * repo_token
+ The secret token for your repository, found at the bottom of your repository's
+ page on Coveralls.
+
+ * service_name
+ The CI service or other environment in which the test suite was run.
+ This can be anything, but certain services have special features
+ (travis-ci, travis-pro, or coveralls-ruby).
+
+ * [service_job_id]
+ A unique identifier of the job on the service specified by service_name.
+ """
+ self._data = None
+ self.config = kwargs
+ file_config = self.load_config() or {}
+ repo_token = self.config.get('repo_token') or file_config.get('repo_token', None)
+ if repo_token:
+ self.config['repo_token'] = repo_token
+
+ if os.environ.get('TRAVIS'):
+ is_travis = True
+ self.config['service_name'] = file_config.get('service_name', None) or 'travis-ci'
+ self.config['service_job_id'] = os.environ.get('TRAVIS_JOB_ID')
+ else:
+ is_travis = False
+ self.config['service_name'] = file_config.get('service_name') or self.default_client
+
+ if os.environ.get('COVERALLS_REPO_TOKEN', None):
+ self.config['repo_token'] = os.environ.get('COVERALLS_REPO_TOKEN')
+
+ if not self.config.get('repo_token') and not is_travis:
+ raise CoverallsException('You have to provide either repo_token in %s, or launch via Travis' % self.config_filename)
+
+ def load_config(self):
+ try:
+ return yaml.safe_load(open(os.path.join(os.getcwd(), self.config_filename)))
+ except (OSError, IOError):
+ log.debug('Missing %s file. Using only env variables.', self.config_filename)
+ return {}
+
+ def wear(self, dry_run=False):
+ """ run! """
+ try:
+ data = self.create_data()
+ except coverage.CoverageException as e:
+ return {'message': 'Failure to gather coverage: %s' % str(e)}
+ try:
+ json_string = json.dumps(data)
+ except UnicodeDecodeError as e:
+ log.error("ERROR: While preparing JSON received exception: %s" % e)
+ self.debug_bad_encoding(data)
+ raise
+ if not dry_run:
+ response = requests.post(self.api_endpoint, files={'json_file': json_string})
+ try:
+ result = response.json()
+ except ValueError:
+ result = {'message': 'Failure to submit data. Response [%(status)s]: %(text)s' % {
+ 'status': response.status_code,
+ 'text': response.text}}
+ else:
+ result = {}
+ json_string = re.sub(r'"repo_token": "(.+?)"', '"repo_token": "[secure]"', json_string)
+ log.debug(json_string)
+ log.debug("==\nReporting %s files\n==\n" % len(data['source_files']))
+ for source_file in data['source_files']:
+ log.debug('%s - %s/%s' % (source_file['name'],
+ sum(filter(None, source_file['coverage'])),
+ len(source_file['coverage'])))
+ return result
+
+ def create_data(self):
+ """ Generate object for api.
+ Example json:
+ {
+ "service_job_id": "1234567890",
+ "service_name": "travis-ci",
+ "source_files": [
+ {
+ "name": "example.py",
+ "source": "def four\n 4\nend",
+ "coverage": [null, 1, null]
+ },
+ {
+ "name": "two.py",
+ "source": "def seven\n eight\n nine\nend",
+ "coverage": [null, 1, 0, null]
+ }
+ ]
+ }
+ """
+ if not self._data:
+ self._data = {'source_files': self.get_coverage()}
+ self._data.update(self.git_info())
+ self._data.update(self.config)
+ return self._data
+
+ def get_coverage(self):
+ workman = coverage.coverage(config_file=self.config.get('config_file', True))
+ workman.load()
+ workman._harvest_data()
+ reporter = CoverallReporter(workman, workman.config)
+ return reporter.report()
+
+ def git_info(self):
+ """ A hash of Git data that can be used to display more information to users.
+
+ Example:
+ "git": {
+ "head": {
+ "id": "5e837ce92220be64821128a70f6093f836dd2c05",
+ "author_name": "Wil Gieseler",
+ "author_email": "wil@example.com",
+ "committer_name": "Wil Gieseler",
+ "committer_email": "wil@example.com",
+ "message": "depend on simplecov >= 0.7"
+ },
+ "branch": "master",
+ "remotes": [{
+ "name": "origin",
+ "url": "https://github.com/lemurheavy/coveralls-ruby.git"
+ }]
+ }
+ """
+
+ rev = run_command('git', 'rev-parse', '--abbrev-ref', 'HEAD').strip()
+ git_info = {'git': {
+ 'head': {
+ 'id': gitlog('%H'),
+ 'author_name': gitlog('%aN'),
+ 'author_email': gitlog('%ae'),
+ 'committer_name': gitlog('%cN'),
+ 'committer_email': gitlog('%ce'),
+ 'message': gitlog('%s'),
+ },
+ 'branch': os.environ.get('CIRCLE_BRANCH') or os.environ.get('TRAVIS_BRANCH', rev),
+ #origin git@github.com:coagulant/coveralls-python.git (fetch)
+ 'remotes': [{'name': line.split()[0], 'url': line.split()[1]}
+ for line in run_command('git', 'remote', '-v').splitlines() if '(fetch)' in line]
+ }}
+ return git_info
+
+ def debug_bad_encoding(self, data):
+ """ Let's try to help user figure out what is at fault"""
+ at_fault_files = set()
+ for source_file_data in data['source_files']:
+ for key, value in source_file_data.items():
+ try:
+ json.dumps(value)
+ except UnicodeDecodeError:
+ at_fault_files.add(source_file_data['name'])
+ if at_fault_files:
+ log.error("HINT: Following files cannot be decoded properly into unicode."
+ "Check their content: %s" % (', '.join(at_fault_files)))
+
+
+def gitlog(format):
+ try:
+ log = str(run_command('git', '--no-pager', 'log', "-1", '--pretty=format:%s' % format))
+ except UnicodeEncodeError:
+ log = unicode(run_command('git', '--no-pager', 'log', "-1", '--pretty=format:%s' % format))
+ return log
+
+
+def run_command(*args):
+ cmd = subprocess.Popen(list(args), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
+ assert cmd.wait() == 0
+ output = cmd.stdout.read()
+ try:
+ output = output.decode()
+ except UnicodeDecodeError:
+ output = output.decode('utf-8')
+ return output
diff --git a/pool/shard009/Python/0083603_pants_runner.py b/pool/shard009/Python/0083603_pants_runner.py
new file mode 100644
index 0000000000000000000000000000000000000000..f1b0270fb787b5110c15ad86e34210378d255d3c
--- /dev/null
+++ b/pool/shard009/Python/0083603_pants_runner.py
@@ -0,0 +1,102 @@
+# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md).
+# Licensed under the Apache License, Version 2.0 (see LICENSE).
+
+import logging
+import os
+import sys
+import warnings
+from dataclasses import dataclass
+from typing import List, Mapping
+
+from pants.base.exception_sink import ExceptionSink
+from pants.base.exiter import ExitCode
+from pants.engine.environment import CompleteEnvironment
+from pants.init.logging import initialize_stdio, stdio_destination
+from pants.init.util import init_workdir
+from pants.option.option_value_container import OptionValueContainer
+from pants.option.options_bootstrapper import OptionsBootstrapper
+
+logger = logging.getLogger(__name__)
+
+
+@dataclass(frozen=True)
+class PantsRunner:
+ """A higher-level runner that delegates runs to either a LocalPantsRunner or
+ RemotePantsRunner."""
+
+ args: List[str]
+ env: Mapping[str, str]
+
+ # This could be a bootstrap option, but it's preferable to keep these very limited to make it
+ # easier to make the daemon the default use case. Once the daemon lifecycle is stable enough we
+ # should be able to avoid needing to kill it at all.
+ def will_terminate_pantsd(self) -> bool:
+ _DAEMON_KILLING_GOALS = frozenset(["kill-pantsd", "clean-all"])
+ return not frozenset(self.args).isdisjoint(_DAEMON_KILLING_GOALS)
+
+ def _should_run_with_pantsd(self, global_bootstrap_options: OptionValueContainer) -> bool:
+ terminate_pantsd = self.will_terminate_pantsd()
+
+ if terminate_pantsd:
+ logger.debug(f"Pantsd terminating goal detected: {self.args}")
+
+ # If we want concurrent pants runs, we can't have pantsd enabled.
+ return (
+ global_bootstrap_options.pantsd
+ and not terminate_pantsd
+ and not global_bootstrap_options.concurrent
+ )
+
+ @staticmethod
+ def scrub_pythonpath() -> None:
+ # Do not propagate any PYTHONPATH that happens to have been set in our environment
+ # to our subprocesses.
+ # Note that don't warn (but still scrub) if RUNNING_PANTS_FROM_SOURCES is set. This allows
+ # scripts that run pants directly from sources, and therefore must set PYTHONPATH, to mute
+ # this warning.
+ pythonpath = os.environ.pop("PYTHONPATH", None)
+ if pythonpath and not os.environ.pop("RUNNING_PANTS_FROM_SOURCES", None):
+ logger.debug(f"Scrubbed PYTHONPATH={pythonpath} from the environment.")
+
+ def run(self, start_time: float) -> ExitCode:
+ self.scrub_pythonpath()
+
+ options_bootstrapper = OptionsBootstrapper.create(
+ env=self.env, args=self.args, allow_pantsrc=True
+ )
+ with warnings.catch_warnings(record=True):
+ bootstrap_options = options_bootstrapper.bootstrap_options
+ global_bootstrap_options = bootstrap_options.for_global_scope()
+
+ # We enable logging here, and everything before it will be routed through regular
+ # Python logging.
+ stdin_fileno = sys.stdin.fileno()
+ stdout_fileno = sys.stdout.fileno()
+ stderr_fileno = sys.stderr.fileno()
+ with initialize_stdio(global_bootstrap_options), stdio_destination(
+ stdin_fileno=stdin_fileno,
+ stdout_fileno=stdout_fileno,
+ stderr_fileno=stderr_fileno,
+ ):
+ # N.B. We inline imports to speed up the python thin client run, and avoids importing
+ # engine types until after the runner has had a chance to set PANTS_BIN_NAME.
+
+ if self._should_run_with_pantsd(global_bootstrap_options):
+ from pants.bin.remote_pants_runner import RemotePantsRunner
+
+ try:
+ remote_runner = RemotePantsRunner(self.args, self.env, options_bootstrapper)
+ return remote_runner.run(start_time)
+ except RemotePantsRunner.Fallback as e:
+ logger.warning(f"Client exception: {e!r}, falling back to non-daemon mode")
+
+ from pants.bin.local_pants_runner import LocalPantsRunner
+
+ # We only install signal handling via ExceptionSink if the run will execute in this process.
+ ExceptionSink.install(
+ log_location=init_workdir(global_bootstrap_options), pantsd_instance=False
+ )
+ runner = LocalPantsRunner.create(
+ env=CompleteEnvironment(self.env), options_bootstrapper=options_bootstrapper
+ )
+ return runner.run(start_time)
diff --git a/pool/shard009/Python/0083609_update_permissions_from_mc.py b/pool/shard009/Python/0083609_update_permissions_from_mc.py
new file mode 100644
index 0000000000000000000000000000000000000000..e1774c53e156c46092017b0bdda549733ab40c38
--- /dev/null
+++ b/pool/shard009/Python/0083609_update_permissions_from_mc.py
@@ -0,0 +1,34 @@
+# -*- coding: utf-8 -*-
+from django.conf import settings
+from django.core.management.base import BaseCommand
+
+from olympia.files.models import WebextPermissionDescription
+from olympia.files.tasks import update_webext_descriptions_all
+
+
+class Command(BaseCommand):
+ help = ('Download and update webextension permission descriptions from '
+ 'mozilla-central.')
+
+ def add_arguments(self, parser):
+ """Handle command arguments."""
+ parser.add_argument(
+ '--clear',
+ action='store_true',
+ dest='clear',
+ default=False,
+ help='Clear existing descriptions in the database first.')
+
+ def handle(self, *args, **options):
+ if options['clear']:
+ WebextPermissionDescription.objects.all().delete()
+
+ central_url = settings.WEBEXT_PERM_DESCRIPTIONS_URL
+ locales_url = settings.WEBEXT_PERM_DESCRIPTIONS_LOCALISED_URL
+ amo_locales = [l for l in settings.AMO_LANGUAGES
+ if l not in ('en-US', 'dbg', 'dbr', 'dbl')]
+ # Fetch canonical en-US descriptions first; then l10n after.
+ update_webext_descriptions_all.apply_async(
+ args=[(central_url, 'en-US'),
+ [(locales_url.format(locale=locale), locale)
+ for locale in amo_locales]])
diff --git a/pool/shard009/Python/0083613_sockshare.py b/pool/shard009/Python/0083613_sockshare.py
new file mode 100644
index 0000000000000000000000000000000000000000..a6a1520b3a3019efc0a86d63de76071f8caf850d
--- /dev/null
+++ b/pool/shard009/Python/0083613_sockshare.py
@@ -0,0 +1,94 @@
+# -*- coding: iso-8859-1 -*-
+#------------------------------------------------------------
+# pelisalacarta - XBMC Plugin
+# Conector para sockshare
+# http://blog.tvalacarta.info/plugin-xbmc/pelisalacarta/
+#------------------------------------------------------------
+
+import urlparse,urllib2,urllib,re
+import os
+
+from core import scrapertools
+from core import logger
+from core import config
+
+
+def get_video_url( page_url , premium = False , user="" , password="", video_password="" ):
+ logger.info("[sockshare.py] url="+page_url)
+ data = scrapertools.cache_page(page_url)
+
+ patron = 'value="([0-9a-f]+?)" name="hash"'
+ matches = re.compile(patron,re.DOTALL).findall(data)
+ if len(matches)==0:return []
+
+
+ post = "hash="+matches[0]+"&confirm=Continue as Free User"
+ data = scrapertools.cache_page( page_url , post=post, headers=[['User-Agent','Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.8.1.14) Gecko/20080404 Firefox/2.0.0.14'],['Referer',page_url]] )
+ logger.info("data="+data)
+ # Extrae el trozo cifrado
+ patron = "playlist: '(.+?)'"
+ matches = re.compile(patron,re.DOTALL).findall(data)
+ #scrapertools.printMatches(matches)
+ data = ""
+ if len(matches)>0:
+ xmlurl = urlparse.urljoin(page_url,matches[0])
+ logger.info("[sockshare.py] Playlis="+xmlurl)
+ else:
+ logger.info("[sockshare.py] No encuentra Playlist=")
+
+ return []
+
+
+ logger.info("xmlurl="+xmlurl)
+ data = scrapertools.downloadpageWithoutCookies(xmlurl)
+ # Extrae la URL
+ patron = '0:
+ video_urls.append( ["."+matches[0].rsplit('.',1)[1][0:3]+" [sockshare]",matches[0]])
+
+ for video_url in video_urls:
+ logger.info("[sockshare.py] %s - %s" % (video_url[0],video_url[1]))
+
+ return video_urls
+
+# Encuentra vídeos de este servidor en el texto pasado
+def find_videos(text):
+ encontrados = set()
+ devuelve = []
+
+ # http://www.peliculasaudiolatino.com/show/sockshare.php?url=CEE0B3A7DDFED758
+ patronvideos = 'sockshare.php\?url=([A-Z0-9]+)'
+ logger.info("[sockshare.py] find_videos #"+patronvideos+"#")
+ matches = re.compile(patronvideos,re.DOTALL).findall(text)
+
+ for match in matches:
+ titulo = "[sockshare]"
+ url = "http://www.sockshare.com/embed/"+match
+ if url not in encontrados:
+ logger.info(" url="+url)
+ devuelve.append( [ titulo , url , 'sockshare' ] )
+ encontrados.add(url)
+ else:
+ logger.info(" url duplicada="+url)
+
+ # http://www.sockshare.com/embed/CEE0B3A7DDFED758
+ patronvideos = 'http://www.sockshare.com/(?:file|embed)/([A-Z0-9]+)'
+ logger.info("[sockshare.py] find_videos #"+patronvideos+"#")
+ matches = re.compile(patronvideos,re.DOTALL).findall(text)
+
+ for match in matches:
+ titulo = "[sockshare]"
+ url = "http://www.sockshare.com/embed/"+match
+ if url not in encontrados:
+ logger.info(" url="+url)
+ devuelve.append( [ titulo , url , 'sockshare' ] )
+ encontrados.add(url)
+ else:
+ logger.info(" url duplicada="+url)
+
+ return devuelve
diff --git a/pool/shard009/Python/0083617_test_abstractvm.py b/pool/shard009/Python/0083617_test_abstractvm.py
new file mode 100644
index 0000000000000000000000000000000000000000..8148161c373c929a5347967ee21b2f50b4aeeed1
--- /dev/null
+++ b/pool/shard009/Python/0083617_test_abstractvm.py
@@ -0,0 +1,130 @@
+"""Tests for pytype.abstractvm."""
+
+import dis
+import textwrap
+import unittest
+
+
+from pytype import vm
+from pytype.pyc import pyc
+from pytype.tests import test_inference
+
+
+class TraceVM(vm.VirtualMachine):
+
+ def __init__(self, python_version):
+ super(TraceVM, self).__init__(python_version)
+ # There are multiple possible orderings of the basic blocks of the code, so
+ # we collect the instructions in an order-independent way:
+ self.instructions_executed = set()
+ # Extra stuff that's defined in infer.CallTracer:
+ # TODO(pludemann): refactor the classes?
+ self._call_trace = set()
+ self._functions = set()
+ self._classes = set()
+ self._unknowns = []
+
+ def run_instruction(self, op, state):
+ self.instructions_executed.add(op.index)
+ return super(TraceVM, self).run_instruction(op, state)
+
+
+def ListToString(lst):
+ return "".join(chr(c) for c in lst)
+
+
+class AncestorTraversalVirtualMachineTest(unittest.TestCase):
+
+ def setUp(self):
+ self.python_version = (2, 7) # used to generate the bytecode below
+ self.vm = TraceVM(self.python_version)
+
+ src_nested_loop = textwrap.dedent("""
+ y = [1,2,3]
+ z = 0
+ for x in y:
+ for a in y:
+ if x:
+ z += x*a
+ """)
+ code_nested_loop = ListToString([
+ dis.opmap["LOAD_CONST"], 0, 0, # [0], 0, arg=0
+ dis.opmap["LOAD_CONST"], 1, 0, # [1], 3, arg=1
+ dis.opmap["LOAD_CONST"], 2, 0, # [2], 6, arg=2
+ dis.opmap["BUILD_LIST"], 3, 0, # [3], 9, arg=3
+ dis.opmap["STORE_NAME"], 0, 0, # [4], 12, arg=0
+ dis.opmap["LOAD_CONST"], 3, 0, # [5], 15, arg=3
+ dis.opmap["STORE_NAME"], 1, 0, # [6], 18, arg=1
+ dis.opmap["SETUP_LOOP"], 54, 0, # [7], 21, dest=78
+ dis.opmap["LOAD_NAME"], 0, 0, # [8], 24, arg=0
+ dis.opmap["GET_ITER"], # [9], 27
+ dis.opmap["FOR_ITER"], 46, 0, # [10], 28, dest=77
+ dis.opmap["STORE_NAME"], 2, 0, # [11], 31, arg=2
+ dis.opmap["SETUP_LOOP"], 37, 0, # [12], 34, dest=74
+ dis.opmap["LOAD_NAME"], 0, 0, # [13], 37, arg=0
+ dis.opmap["GET_ITER"], # [14], 40
+ dis.opmap["FOR_ITER"], 29, 0, # [15], 41, dest=73
+ dis.opmap["STORE_NAME"], 3, 0, # [16], 44, arg=3
+ dis.opmap["LOAD_NAME"], 2, 0, # [17], 47, arg=2
+ dis.opmap["POP_JUMP_IF_FALSE"], 41, 0, # [18], 50, dest=41
+ dis.opmap["LOAD_NAME"], 1, 0, # [19], 53, arg=1
+ dis.opmap["LOAD_NAME"], 2, 0, # [20], 56, arg=2
+ dis.opmap["LOAD_NAME"], 3, 0, # [21], 59, arg=3
+ dis.opmap["BINARY_MULTIPLY"], # [22], 62
+ dis.opmap["INPLACE_ADD"], # [23], 63
+ dis.opmap["STORE_NAME"], 1, 0, # [24], 64, arg=1
+ dis.opmap["JUMP_ABSOLUTE"], 41, 0, # [25], 67, dest=41
+ dis.opmap["JUMP_ABSOLUTE"], 41, 0, # [26], 70 (unreachable), dest=41
+ dis.opmap["POP_BLOCK"], # [27], 73
+ dis.opmap["JUMP_ABSOLUTE"], 28, 0, # [28], 74, dest=28
+ dis.opmap["POP_BLOCK"], # [29], 77
+ dis.opmap["LOAD_CONST"], 4, 0, # [30], 78, arg=4
+ dis.opmap["RETURN_VALUE"], # [31], 81
+ ])
+
+ def testEachInstructionOnceLoops(self):
+ code_nested_loop = pyc.compile_src(src=self.src_nested_loop,
+ python_version=self.python_version,
+ filename="<>")
+ self.assertEqual(code_nested_loop.co_code,
+ self.code_nested_loop)
+ self.vm.run_program(self.src_nested_loop, run_builtins=False)
+ # We expect all instructions, except 26, in the above to execute.
+ self.assertItemsEqual(self.vm.instructions_executed,
+ set(range(32)) - {26})
+
+ src_deadcode = textwrap.dedent("""
+ if False:
+ x = 2
+ raise RuntimeError
+ x = 42
+ """)
+ code_deadcode = ListToString([
+ dis.opmap["LOAD_NAME"], 0, 0, # [0] 0, arg=0
+ dis.opmap["POP_JUMP_IF_FALSE"], 15, 0, # [1] 3, dest=15
+ dis.opmap["LOAD_CONST"], 0, 0, # [2] 6, arg=0
+ dis.opmap["STORE_NAME"], 1, 0, # [3] 9, arg=1
+ dis.opmap["JUMP_FORWARD"], 0, 0, # [4] 12, dest=15
+ dis.opmap["LOAD_NAME"], 2, 0, # [5] 15, arg=2
+ dis.opmap["RAISE_VARARGS"], 1, 0, # [6] 18, arg=1
+ dis.opmap["LOAD_CONST"], 1, 0, # [7] 21 (unreachable), arg=1
+ dis.opmap["STORE_NAME"], 1, 0, # [8] 24 (unreachable), arg=1
+ dis.opmap["LOAD_CONST"], 2, 0, # [9] 27 (unreachable), arg=2
+ dis.opmap["RETURN_VALUE"], # [10] 30 (unreachable)
+ ])
+
+ def testEachInstructionOnceDeadCode(self):
+ code_deadcode = pyc.compile_src(src=self.src_deadcode,
+ python_version=self.python_version,
+ filename="<>")
+ self.assertEqual(code_deadcode.co_code,
+ self.code_deadcode)
+ try:
+ self.vm.run_program(self.src_deadcode, run_builtins=False)
+ except vm.VirtualMachineError:
+ pass # The code we test throws an exception. Ignore it.
+ self.assertItemsEqual(self.vm.instructions_executed, range(7))
+
+
+if __name__ == "__main__":
+ test_inference.main()
diff --git a/pool/shard009/Python/0083625_fsg-to-dict_en.py b/pool/shard009/Python/0083625_fsg-to-dict_en.py
new file mode 100644
index 0000000000000000000000000000000000000000..1b60c552c3ad6b419c372bd2776620aa70be02fe
--- /dev/null
+++ b/pool/shard009/Python/0083625_fsg-to-dict_en.py
@@ -0,0 +1,59 @@
+#! /usr/bin/python
+
+import sys
+import re
+
+import os
+from subprocess import Popen, PIPE, STDOUT
+BASE_DICT="/usr/local/share/pocketsphinx/model/lm/en_US/cmu07a.dic"
+G2P=os.path.dirname(sys.argv[0]) + "/en-g2p.sh"
+
+words = {}
+for l in open(BASE_DICT):
+ ss = l.split()
+ word = ss[0]
+ word = re.sub(r"\(\d\)$", "", word)
+ try:
+ prob = float(ss[1])
+ pron = ss[2:]
+ except ValueError:
+ prob = 1
+ pron = ss[1:]
+
+ words.setdefault(word, []).append((pron, prob))
+
+input_words = set()
+
+for l in sys.stdin:
+ if l.startswith("TRANSITION"):
+ ss = l.split()
+ if len(ss) == 5:
+ input_words.add(ss[-1])
+
+g2p_words = []
+for w in input_words:
+ if w.lower() in words:
+ for (i, pron) in enumerate(words[w.lower()]):
+ if i == 0:
+ print w,
+ else:
+ print "%s(%d)" % (w, i+1),
+ print " ".join(pron[0])
+ else:
+ g2p_words.append(w)
+
+if len(g2p_words) > 0:
+ proc = Popen(G2P,stdin=PIPE, stdout=PIPE, stderr=STDOUT )
+ #stdout, stderr = proc.communicate()
+ for w in g2p_words:
+ print >>proc.stdin, w
+ proc.stdin.close()
+
+ #return_code = proc.wait()
+
+ for l in proc.stdout:
+ print l,
+
+
+
+
diff --git a/pool/shard009/Python/0083629_occur_every_day.py b/pool/shard009/Python/0083629_occur_every_day.py
new file mode 100644
index 0000000000000000000000000000000000000000..8f73685cd9c6ef65d1d57721782fb2bc923d3e9c
--- /dev/null
+++ b/pool/shard009/Python/0083629_occur_every_day.py
@@ -0,0 +1,224 @@
+# Outspline - A highly modular and extensible outliner.
+# Copyright (C) 2011-2014 Dario Giovannetti
+#
+# This file is part of Outspline.
+#
+# Outspline 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.
+#
+# Outspline 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 Outspline. If not, see .
+
+import time as _time
+import datetime as _datetime
+import random
+
+from outspline.static.pyaux.timeaux import UTCOffset
+from outspline.static.wxclasses.timectrls import TimeSpanCtrl
+import outspline.extensions.organism_basicrules_api as organism_basicrules_api
+import outspline.plugins.wxscheduler_api as wxscheduler_api
+
+import interface
+import msgboxes
+
+
+class Rule(object):
+ def __init__(self, parent, filename, id_, standard, rule):
+ self.original_values = self._compute_values(standard, rule)
+ self.ui = interface.Interface(parent, filename, id_,
+ (interface.StartTime,
+ interface.EndTime,
+ interface.AlarmTime,
+ interface.Standard),
+ self.original_values)
+
+ def apply_rule(self, filename, id_):
+ values = self.ui.get_values()
+ rstart = values['start_relative_time']
+ rstartH = values['start_hour']
+ rstartM = values['start_minute']
+ endtype = values['end_type']
+ rend = values['end_relative_time']
+ fend = values['end_next_day']
+ rendn = values['end_relative_number']
+ rendu = values['end_relative_unit']
+ rendH = values['end_hour']
+ rendM = values['end_minute']
+ alarmtype = values['alarm_type']
+ ralarm = values['alarm_relative_time']
+ palarm = values['alarm_previous_day']
+ ralarmn = values['alarm_relative_number']
+ ralarmu = values['alarm_relative_unit']
+ ralarmH = values['alarm_hour']
+ ralarmM = values['alarm_minute']
+ standard = values['time_standard']
+
+ refstart = int(_time.time()) // 86400 * 86400 + rstart
+
+ try:
+ if standard == 'UTC':
+ ruled = organism_basicrules_api.make_occur_regularly_rule_UTC(
+ refstart, 86400, rend, ralarm, ('1d', endtype, alarmtype))
+ else:
+ ruled = organism_basicrules_api.make_occur_regularly_rule_local(
+ refstart, 86400, rend, ralarm, ('1d', endtype, alarmtype))
+ except organism_basicrules_api.BadRuleError:
+ msgboxes.warn_bad_rule(msgboxes.generic).ShowModal()
+ else:
+ label = self._make_label(rstartH, rstartM, rendH, rendM, ralarmH,
+ ralarmM, rendn, rendu, ralarmn, ralarmu,
+ endtype, alarmtype, fend, palarm, standard)
+ wxscheduler_api.apply_rule(filename, id_, ruled, label)
+
+ @classmethod
+ def insert_rule(cls, filename, id_, rule, rulev):
+ standard = 'UTC' if rule['rule'] == 'occur_regularly_UTC' else 'local'
+ values = cls._compute_values(standard, rulev)
+ label = cls._make_label(values['start_hour'],
+ values['start_minute'],
+ values['end_hour'],
+ values['end_minute'],
+ values['alarm_hour'],
+ values['alarm_minute'],
+ values['end_relative_number'],
+ values['end_relative_unit'],
+ values['alarm_relative_number'],
+ values['alarm_relative_unit'],
+ values['end_type'],
+ values['alarm_type'],
+ values['end_next_day'],
+ values['alarm_previous_day'],
+ values['time_standard'])
+ wxscheduler_api.insert_rule(filename, id_, rule, label)
+
+ @classmethod
+ def _compute_values(cls, standard, rule):
+ # Remember to support also time zones that differ from UTC by not
+ # exact hours (e.g. Australia/Adelaide)
+ if not rule:
+ now = _datetime.datetime.now()
+ nextdate = _datetime.datetime(now.year, now.month, now.day,
+ now.hour) + _datetime.timedelta(hours=1)
+ refstart = int(_time.mktime(nextdate.timetuple())) - \
+ UTCOffset.compute2_current()
+
+ values = {
+ 'reference_start': refstart,
+ 'interval': 86400,
+ 'overlaps': 0,
+ 'bgap': 86400 - 3600,
+ 'end_relative_time': 3600,
+ 'alarm_relative_time': 0,
+ 'end_type': 0,
+ 'alarm_type': 0,
+ 'time_standard': standard,
+ }
+ else:
+ values = {
+ 'reference_start': rule[0],
+ 'interval': rule[1],
+ 'overlaps': rule[2],
+ 'bgap': rule[3],
+ 'end_relative_time': rule[4] if rule[4] is not None else 3600,
+ 'alarm_relative_time': rule[5] if rule[5] is not None else 0,
+ 'end_type': rule[6][1],
+ 'alarm_type': rule[6][2],
+ 'time_standard': standard,
+ }
+
+ values['end_relative_number'], values['end_relative_unit'] = \
+ TimeSpanCtrl.compute_widget_values(
+ values['end_relative_time'])
+
+ # ralarm could be negative
+ values['alarm_relative_number'], values['alarm_relative_unit'] = \
+ TimeSpanCtrl.compute_widget_values(
+ max((0, values['alarm_relative_time'])))
+
+ rrstart = values['reference_start'] % 86400
+
+ rrend = rrstart + values['end_relative_time']
+ values['end_next_day'] = False
+
+ # End time could be set after 23:59 of the start day
+ if rrend > 86399:
+ rrend = rrend % 86400
+ values['end_next_day'] = True
+
+ rralarm = rrstart - values['alarm_relative_time']
+ values['alarm_previous_day'] = False
+
+ # Alarm time could be set before 00:00 of the start day
+ if rralarm < 0:
+ rralarm = 86400 - abs(rralarm) % 86400
+ values['alarm_previous_day'] = True
+
+ values.update({
+ 'start_hour': rrstart // 3600,
+ 'start_minute': rrstart % 3600 // 60,
+ 'end_hour': rrend // 3600,
+ 'end_minute': rrend % 3600 // 60,
+ 'alarm_hour': rralarm // 3600,
+ 'alarm_minute': rralarm % 3600 // 60,
+ })
+
+ return values
+
+ @staticmethod
+ def _make_label(rstartH, rstartM, rendH, rendM, ralarmH, ralarmM, rendn,
+ rendu, ralarmn, ralarmu, endtype,
+ alarmtype, fend, palarm, standard):
+ label = 'Occur every day at {}:{} ({})'.format(str(rstartH).zfill(2),
+ str(rstartM).zfill(2), standard)
+
+ if endtype == 1:
+ label += ' for {} {}'.format(rendn, rendu)
+ elif endtype == 2:
+ label += ' until {}:{}'.format(str(rendH).zfill(2),
+ str(rendM).zfill(2))
+ if fend:
+ label += ' of the following day'
+
+ if alarmtype == 1:
+ label += ', activate alarm {} {} before'.format(ralarmn, ralarmu)
+ elif alarmtype == 2:
+ label += ', activate alarm at {}:{}'.format(
+ str(ralarmH).zfill(2), str(ralarmM).zfill(2))
+ if palarm:
+ label += ' of the previous day'
+
+ return label
+
+ @staticmethod
+ def create_random_rule():
+ refstart = int((random.gauss(_time.time(), 15000)) // 60 * 60)
+
+ endtype = random.randint(0, 2)
+
+ if endtype == 0:
+ rend = None
+ else:
+ rend = random.randint(1, 360) * 60
+
+ alarmtype = random.randint(0, 2)
+
+ if alarmtype == 0:
+ ralarm = None
+ else:
+ ralarm = random.randint(0, 360) * 60
+
+ stdn = random.randint(0, 1)
+
+ if stdn == 0:
+ return organism_basicrules_api.make_occur_regularly_rule_local(
+ refstart, 86400, rend, ralarm, ('1d', endtype, alarmtype))
+ else:
+ return organism_basicrules_api.make_occur_regularly_rule_UTC(
+ refstart, 86400, rend, ralarm, ('1d', endtype, alarmtype))
diff --git a/pool/shard009/Python/0083631_io.py b/pool/shard009/Python/0083631_io.py
new file mode 100644
index 0000000000000000000000000000000000000000..4a886cfb1ced8c06c4bf1feca68d3e1a6ec3c9a5
--- /dev/null
+++ b/pool/shard009/Python/0083631_io.py
@@ -0,0 +1,41 @@
+# -*- coding:utf-8 -*-
+# Author: hankcs
+# Date: 2020-12-16 22:38
+import json
+import os
+import pickle
+import sys
+from typing import Union
+
+
+def save_pickle(item, path):
+ with open(path, 'wb') as f:
+ pickle.dump(item, f)
+
+
+def load_pickle(path):
+ with open(path, 'rb') as f:
+ return pickle.load(f)
+
+
+def save_json(item: Union[dict, list, str, int, float], path: str, ensure_ascii=False, cls=None,
+ default=lambda o: repr(o), indent=2):
+ dirname = os.path.dirname(path)
+ if dirname:
+ os.makedirs(dirname, exist_ok=True)
+ with open(path, 'w', encoding='utf-8') as out:
+ json.dump(item, out, ensure_ascii=ensure_ascii, indent=indent, cls=cls, default=default)
+
+
+def load_json(path):
+ with open(path, encoding='utf-8') as src:
+ return json.load(src)
+
+
+def filename_is_json(filename):
+ filename, file_extension = os.path.splitext(filename)
+ return file_extension in ['.json', '.jsonl']
+
+
+def eprint(*args, **kwargs):
+ print(*args, file=sys.stderr, **kwargs)
diff --git a/pool/shard009/Python/0083633_playwith.py b/pool/shard009/Python/0083633_playwith.py
new file mode 100644
index 0000000000000000000000000000000000000000..79f2196df3a179b6d182cc6a35c457e69010be6f
--- /dev/null
+++ b/pool/shard009/Python/0083633_playwith.py
@@ -0,0 +1,127 @@
+import sys
+import xbmc,xbmcaddon,xbmcvfs
+import sqlite3
+import datetime
+import time
+import subprocess
+from subprocess import Popen
+import re
+from vpnapi import VPNAPI
+
+
+def log(what):
+ xbmc.log(repr(what))
+
+ADDON = xbmcaddon.Addon(id='script.tvguide.Vader')
+
+channel = sys.argv[1]
+start = sys.argv[2]
+
+def adapt_datetime(ts):
+ return time.mktime(ts.timetuple())
+
+def convert_datetime(ts):
+ try:
+ return datetime.datetime.fromtimestamp(float(ts))
+ except ValueError:
+ return None
+
+sqlite3.register_adapter(datetime.datetime, adapt_datetime)
+sqlite3.register_converter('timestamp', convert_datetime)
+
+ADDON.setSetting('playing.channel',channel)
+ADDON.setSetting('playing.start',start)
+
+path = xbmc.translatePath('special://profile/addon_data/script.tvguide.Vader/source.db')
+try:
+ conn = sqlite3.connect(path, detect_types=sqlite3.PARSE_DECLTYPES)
+ conn.row_factory = sqlite3.Row
+except Exception as detail:
+ xbmc.log("EXCEPTION: (script.tvguide.Vader) %s" % detail, xbmc.LOGERROR)
+
+ffmpeg = ADDON.getSetting('autoplaywiths.ffmpeg')
+if ffmpeg:
+ folder = ADDON.getSetting('autoplaywiths.folder')
+ c = conn.cursor()
+ c.execute('SELECT stream_url FROM custom_stream_url WHERE channel=?', [channel])
+ row = c.fetchone()
+ url = ""
+ if row:
+ url = row[0]
+ if not url:
+ quit()
+ startDate = datetime.datetime.fromtimestamp(float(start))
+ c.execute('SELECT DISTINCT * FROM programs WHERE channel=? AND start_date = ?', [channel,startDate])
+ for row in c:
+ title = row["title"]
+ season = row["season"]
+ episode = row["episode"]
+ if season and episode:
+ title += " S%sE%s" % (season, episode)
+ endDate = row["end_date"]
+ duration = endDate - startDate
+ before = int(ADDON.getSetting('autoplaywiths.before'))
+ after = int(ADDON.getSetting('autoplaywiths.after'))
+ extra = (before + after) * 60
+ #TODO start from now
+ seconds = duration.seconds + extra
+ if seconds > (3600*4):
+ seconds = 3600*4
+ break
+ player = xbmc.Player()
+ player.play(url)
+ count = 30
+ url = ""
+ while count:
+ count = count - 1
+ time.sleep(1)
+ if player.isPlaying():
+ url = player.getPlayingFile()
+ break
+ player.stop()
+
+ # Play with your own preferred player and paths
+ if url:
+ name = "%s - %s - %s" % (channel,title,time.strftime('%Y-%m-%d %H-%M'))
+ name = re.sub("\?",'',name)
+ name = re.sub(":|<>\/",'',name)
+ name = name.encode("cp1252")
+ filename = xbmc.translatePath("%s%s.ts" % (folder,name))
+ #seconds = 30
+ cmd = [ffmpeg, "-y", "-i", url, "-c", "copy", "-t", str(seconds), filename]
+ p = Popen(cmd,shell=True)
+ quit()
+
+script = "special://profile/addon_data/script.tvguide.Vader/playwith.py"
+if xbmcvfs.exists(script):
+ xbmc.executebuiltin('RunScript(%s,%s,%s)' % (script,channel,start))
+
+core = ADDON.getSetting('autoplaywiths.player')
+if not core:
+ quit()
+
+c = conn.cursor()
+c.execute('SELECT stream_url FROM custom_stream_url WHERE channel=?', [channel])
+row = c.fetchone()
+url = ""
+if row:
+ url = row[0]
+if not url:
+ quit()
+else:
+ if xbmc.getCondVisibility("System.HasAddon(service.vpn.manager)"):
+ try:
+ if ADDON.getSetting('vpnmgr.connect') == "true":
+ vpndefault = False
+ if ADDON.getSetting('vpnmgr.default') == "true":
+ vpndefault = True
+ api = VPNAPI()
+ if url[0:9] == 'plugin://':
+ api.filterAndSwitch(url, 0, vpndefault, True)
+ else:
+ if vpndefault: api.defaultVPN(True)
+ except:
+ pass
+
+xbmc.executebuiltin('PlayWith(%s)' % core)
+xbmc.executebuiltin('PlayMedia(%s)' % url)
diff --git a/pool/shard009/Python/0083638_test_rule_014.py b/pool/shard009/Python/0083638_test_rule_014.py
new file mode 100644
index 0000000000000000000000000000000000000000..81773252da52c7a7e61b17b3eeeca2fb8330ea3d
--- /dev/null
+++ b/pool/shard009/Python/0083638_test_rule_014.py
@@ -0,0 +1,71 @@
+
+import os
+import unittest
+
+from vsg.rules import port
+from vsg import vhdlFile
+from vsg.tests import utils
+
+sTestDir = os.path.dirname(__file__)
+
+lFile, eError =vhdlFile.utils.read_vhdlfile(os.path.join(sTestDir,'rule_014_test_input.vhd'))
+
+lExpected = []
+lExpected.append('')
+utils.read_file(os.path.join(sTestDir, 'rule_014_test_input.fixed.vhd'), lExpected)
+
+lExpected_move_left = []
+lExpected_move_left.append('')
+utils.read_file(os.path.join(sTestDir, 'rule_014_test_input.fixed_move_left.vhd'), lExpected_move_left)
+
+
+class test_port_rule(unittest.TestCase):
+
+ def setUp(self):
+ self.oFile = vhdlFile.vhdlFile(lFile)
+ self.assertIsNone(eError)
+
+ def test_rule_014(self):
+ oRule = port.rule_014()
+ self.assertTrue(oRule)
+ self.assertEqual(oRule.name, 'port')
+ self.assertEqual(oRule.identifier, '014')
+
+ lExpected = [17]
+
+ oRule.analyze(self.oFile)
+ self.assertEqual(lExpected, utils.extract_violation_lines_from_violation_object(oRule.violations))
+
+ def test_fix_rule_014(self):
+ oRule = port.rule_014()
+
+ oRule.fix(self.oFile)
+
+ lActual = self.oFile.get_lines()
+
+ self.assertEqual(lExpected, lActual)
+
+ oRule.analyze(self.oFile)
+ self.assertEqual(oRule.violations, [])
+
+ def test_rule_014_move_left(self):
+ oRule = port.rule_014()
+ oRule.action = "move_left"
+
+ lExpected = [7]
+
+ oRule.analyze(self.oFile)
+ self.assertEqual(lExpected, utils.extract_violation_lines_from_violation_object(oRule.violations))
+
+ def test_fix_rule_014_move_left(self):
+ oRule = port.rule_014()
+ oRule.action = "move_left"
+
+ oRule.fix(self.oFile)
+
+ lActual = self.oFile.get_lines()
+
+ self.assertEqual(lExpected_move_left, lActual)
+
+ oRule.analyze(self.oFile)
+ self.assertEqual(oRule.violations, [])
diff --git a/pool/shard009/Python/0083640_recover.py b/pool/shard009/Python/0083640_recover.py
new file mode 100644
index 0000000000000000000000000000000000000000..6199563a1c194fa51ffdee88c458ccfe832bbe89
--- /dev/null
+++ b/pool/shard009/Python/0083640_recover.py
@@ -0,0 +1,40 @@
+import os
+import logging
+import redistrib.command as comm
+from socket import error as SocketError
+from hiredis import ReplyError
+from redistrib.clusternode import Talker, pack_command
+
+import node as nm
+
+CMD_PING = pack_command('ping')
+
+
+def recover():
+ logging.info('Run recovering on process %d', os.getpid())
+ for node in nm.list_all_nodes():
+ _recover_instance(node)
+ logging.info('Recovering finished on process %d', os.getpid())
+
+
+def recover_by_addr(host, port):
+ t = Talker(host, port)
+ try:
+ m = t.talk_raw(CMD_PING)
+ if m.lower() != 'pong':
+ raise ValueError('Expect pong but recv: %s' % m)
+ node = nm.pick_by(host, port)
+ finally:
+ if t is not None:
+ t.close()
+
+
+def _recover_instance(node):
+ logging.info('Recover node %d(%s:%d)', node.id, node.host, node.port)
+ try:
+ comm.fix_migrating(node.host, node.port)
+ except (StandardError, SocketError), e:
+ logging.exception(e)
+ logging.error('Fail to recover %s:%d', node.host, node.port)
+ except ReplyError:
+ logging.info('%s:%d is not cluster enabled', node.host, node.port)
diff --git a/pool/shard009/Python/0083645_cluster_Kmean__030915.py b/pool/shard009/Python/0083645_cluster_Kmean__030915.py
new file mode 100644
index 0000000000000000000000000000000000000000..a955c5f69a66911b743d3b2a90276d4aeb925734
--- /dev/null
+++ b/pool/shard009/Python/0083645_cluster_Kmean__030915.py
@@ -0,0 +1,103 @@
+# -*- coding: utf-8 -*-
+"""
+Created on Tue Mar 10 05:04:23 2015
+
+@author: Sarunya Werasena
+"""
+from PIL import Image
+import cv2
+import numpy as np
+from scipy.cluster.vq import *
+import cPickle
+import os
+rootdir = 'dataset'
+
+def harris_response(img):
+ gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
+
+ gray = np.float32(gray)
+ dst = cv2.cornerHarris(gray,2,3,0.04)
+
+ #result is dilated for marking the corners, not important
+ dst = cv2.dilate(dst,None)
+
+ # Threshold for an optimal value, it may vary depending on the image.
+ img[dst>0.01*dst.max()]=[255,0,0]
+
+# cv2.imshow('dst',img)
+# if cv2.waitKey(0) & 0xff == 27:
+# cv2.destroyAllWindows()
+
+#def kmean_cluster():
+# class1 = 1.5 * np.random.randn(100,2)
+# class2 = np.random.randn(100,2) + np.array( [ 5,5] )
+# features = np.vstack((class1,class2))
+# centroids,variance = kmeans(features,2)
+# code,distance = vq(features,centroids)
+#
+# plt.figure()
+# ndx = np.where(code==0) [ 0]
+# plt.plot(features[ ndx,0] ,features[ ndx,1] , '*' )
+# ndx = np.where(code==1) [ 0]
+# plt.plot(features[ ndx,0] ,features[ ndx,1] , 'r.' )
+# plt.plot(centroids[ : ,0] ,centroids[ : ,1] , 'go' )
+# plt.axis('off')
+# plt.show()
+
+def readfiles():
+ all_im=[]
+ for root,dirs,files in os.walk(rootdir):
+ for f in files:
+ if f.endswith('jpg') or f.endswith('JPG'):
+ im = Image.open(os.path.join(root,f))
+ im = im.convert('LA')
+
+ # save image
+ plt.imshow(im)
+ # Remove axes and ticks
+ plt.axis('off')
+#
+ plt.show()
+# plt.contour(l, [60, 211])
+ all_im.append(np.asarray(im.getdata(),dtype=np.uint8))
+ return all_im
+
+def kmean_cluster(imlist):
+ # get list of images
+# imlist = imtools.get_imlist('selected_fontimages/')
+ imnbr = len(imlist)
+ # load model file
+# with open('a_pca_modes.pkl','rb' ) as f:
+ immean = pickle.load(open('a_pca_modes.pkl','rb' ))
+ V = pickle.load(f)
+ # create matrix to store all flattened images
+ immatrix = np.array([np.array(Image.open(im)).flatten() for im in imlist] , 'f' )
+ # project on the 40 first PCs
+ immean = immean.flatten()
+ projected = np.array( [np.dot(V[ :40] ,immatrix[i] - immean) for i in range(imnbr) ] )
+ # k- means
+ projected = np.whiten(projected)
+ centroids,distortion = kmeans(projected,4)
+ code,distance = vq(projected,centroids)
+
+# plot clusters
+ for k in range(4) :
+ ind = where(code==k) [ 0]
+ plt.figure()
+
+ plt.gray()
+ for i in range(minimum( len(ind),40)) :
+ plt.subplot(4,10,i+1)
+ plt.imshow(immatrix[ ind[ i] ] . reshape((25,25)))
+ plt.axis('off')
+ plt.show()
+
+def main():
+ img = cv2.imread('test.jpg')
+ harris_response(img)
+ a = readfiles()
+ kmean_cluster(a)
+
+
+if __name__ == '__main__':
+ main()
\ No newline at end of file
diff --git a/pool/shard009/Python/0083650_ej765.py b/pool/shard009/Python/0083650_ej765.py
new file mode 100644
index 0000000000000000000000000000000000000000..85513c60b8b837dfeca596ecc0327f8eef6fe67b
--- /dev/null
+++ b/pool/shard009/Python/0083650_ej765.py
@@ -0,0 +1,39 @@
+#!/usr/bin/env python3
+
+# Ejercicio 7.6.5. Dada una lista de números enteros, escribir una función que:
+# a) Devuelva una lista con todos los que sean primos.
+# b) Devuelva la sumatoria y el promedio de los valores.
+# c) Devuelva una lista con el factorial de cada uno de esos números.
+
+def es_primo(num):
+ divisores = 1
+ for x in range(1, num):
+ if num % x == 0:
+ divisores += 1
+ return divisores == 2
+
+def primos(lista):
+ lista_primos = []
+ for num in lista:
+ if es_primo(num):
+ lista_primos.append(num)
+ return lista_primos
+
+def sum_y_prom(lista):
+ sumatoria = sum(lista)
+ promedio = sumatoria/len(lista)
+ return sumatoria, promedio
+
+def factorial(num):
+ if num == 0 or num == 1:
+ return 1
+ return num * factorial(num - 1)
+
+def factoriales(lista):
+ lista_factoriales = []
+ for num in lista:
+ lista_factoriales.append(factorial(num))
+ return lista_factoriales
+
+print(factoriales([1,2,3,4,5,6]))
+
diff --git a/pool/shard009/Python/0083651_flowlayout.py b/pool/shard009/Python/0083651_flowlayout.py
new file mode 100644
index 0000000000000000000000000000000000000000..8579cfd59101fb6ff183f41893180b85b858c89a
--- /dev/null
+++ b/pool/shard009/Python/0083651_flowlayout.py
@@ -0,0 +1,130 @@
+#############################################################################
+##
+## Copyright (C) 2013 Riverbank Computing Limited.
+## Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
+## All rights reserved.
+##
+## This file is part of the examples of PyQt.
+##
+## $QT_BEGIN_LICENSE:BSD$
+## You may use this file under the terms of the BSD license as follows:
+##
+## "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.
+## * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor
+## the names of its contributors may be used to endorse or promote
+## products derived from this software without specific prior written
+## permission.
+##
+## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
+## $QT_END_LICENSE$
+##
+#############################################################################
+
+
+from qtpy.QtCore import QPoint, QRect, QSize, Qt
+from qtpy.QtWidgets import QLayout, QSizePolicy
+
+
+class FlowLayout(QLayout):
+ def __init__(self, parent=None, margin=0, spacing=-1):
+ super(FlowLayout, self).__init__(parent)
+
+ if parent is not None:
+ self.setContentsMargins(margin, margin, margin, margin)
+
+ self.setSpacing(spacing)
+
+ self.itemList = []
+
+ def __del__(self):
+ item = self.takeAt(0)
+ while item:
+ item = self.takeAt(0)
+
+ def addItem(self, item):
+ self.itemList.append(item)
+
+ def count(self):
+ return len(self.itemList)
+
+ def itemAt(self, index):
+ if index >= 0 and index < len(self.itemList):
+ return self.itemList[index]
+
+ return None
+
+ def takeAt(self, index):
+ if index >= 0 and index < len(self.itemList):
+ return self.itemList.pop(index)
+
+ return None
+
+ def expandingDirections(self):
+ return Qt.Orientations(Qt.Orientation(0))
+
+ def hasHeightForWidth(self):
+ return True
+
+ def heightForWidth(self, width):
+ height = self.doLayout(QRect(0, 0, width, 0), True)
+ return height
+
+ def setGeometry(self, rect):
+ super(FlowLayout, self).setGeometry(rect)
+ self.doLayout(rect, False)
+
+ def sizeHint(self):
+ return self.minimumSize()
+
+ def minimumSize(self):
+ size = QSize()
+
+ for item in self.itemList:
+ size = size.expandedTo(item.minimumSize())
+
+ margin, _, _, _ = self.getContentsMargins()
+
+ size += QSize(2 * margin, 2 * margin)
+ return size
+
+ def doLayout(self, rect, testOnly):
+ x = rect.x()
+ y = rect.y()
+ lineHeight = 0
+
+ for item in self.itemList:
+ wid = item.widget()
+ spaceX = self.spacing() + wid.style().layoutSpacing(QSizePolicy.PushButton, QSizePolicy.PushButton, Qt.Horizontal)
+ spaceY = self.spacing() + wid.style().layoutSpacing(QSizePolicy.PushButton, QSizePolicy.PushButton, Qt.Vertical)
+ nextX = x + item.sizeHint().width() + spaceX
+ if nextX - spaceX > rect.right() and lineHeight > 0:
+ x = rect.x()
+ y = y + lineHeight + spaceY
+ nextX = x + item.sizeHint().width() + spaceX
+ lineHeight = 0
+
+ if not testOnly:
+ item.setGeometry(QRect(QPoint(x, y), item.sizeHint()))
+
+ x = nextX
+ lineHeight = max(lineHeight, item.sizeHint().height())
+
+ return y + lineHeight - rect.y()
diff --git a/pool/shard009/Python/0083656_mcts_test.py b/pool/shard009/Python/0083656_mcts_test.py
new file mode 100644
index 0000000000000000000000000000000000000000..9cbfe5625b9e83a28e277ee2fc2c895696f20744
--- /dev/null
+++ b/pool/shard009/Python/0083656_mcts_test.py
@@ -0,0 +1,222 @@
+# Copyright 2018 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.
+# ==============================================================================
+"""Tests for mcts."""
+from __future__ import absolute_import
+from __future__ import division
+from __future__ import print_function
+
+import copy
+
+import tensorflow as tf # pylint: disable=g-bad-import-order
+
+import coords
+import go
+from mcts import MCTSNode
+import numpy as np
+import utils_test
+
+tf.logging.set_verbosity(tf.logging.ERROR)
+
+ALMOST_DONE_BOARD = utils_test.load_board('''
+ .XO.XO.OO
+ X.XXOOOO.
+ XXXXXOOOO
+ XXXXXOOOO
+ .XXXXOOO.
+ XXXXXOOOO
+ .XXXXOOO.
+ XXXXXOOOO
+ XXXXOOOOO
+''')
+
+TEST_POSITION = go.Position(
+ utils_test.BOARD_SIZE,
+ board=ALMOST_DONE_BOARD,
+ n=105,
+ komi=2.5,
+ caps=(1, 4),
+ ko=None,
+ recent=(go.PlayerMove(go.BLACK, (0, 1)),
+ go.PlayerMove(go.WHITE, (0, 8))),
+ to_play=go.BLACK
+)
+
+SEND_TWO_RETURN_ONE = go.Position(
+ utils_test.BOARD_SIZE,
+ board=ALMOST_DONE_BOARD,
+ n=75,
+ komi=0.5,
+ caps=(0, 0),
+ ko=None,
+ recent=(
+ go.PlayerMove(go.BLACK, (0, 1)),
+ go.PlayerMove(go.WHITE, (0, 8)),
+ go.PlayerMove(go.BLACK, (1, 0))),
+ to_play=go.WHITE
+)
+
+MAX_DEPTH = (utils_test.BOARD_SIZE ** 2) * 1.4
+
+
+class TestMctsNodes(utils_test.MiniGoUnitTest):
+
+ def test_action_flipping(self):
+ np.random.seed(1)
+ probs = np.array([.02] * (
+ utils_test.BOARD_SIZE * utils_test.BOARD_SIZE + 1))
+ probs += np.random.random(
+ [utils_test.BOARD_SIZE * utils_test.BOARD_SIZE + 1]) * 0.001
+ black_root = MCTSNode(
+ utils_test.BOARD_SIZE, go.Position(utils_test.BOARD_SIZE))
+ white_root = MCTSNode(utils_test.BOARD_SIZE, go.Position(
+ utils_test.BOARD_SIZE, to_play=go.WHITE))
+ black_root.select_leaf().incorporate_results(probs, 0, black_root)
+ white_root.select_leaf().incorporate_results(probs, 0, white_root)
+ # No matter who is to play, when we know nothing else, the priors
+ # should be respected, and the same move should be picked
+ black_leaf = black_root.select_leaf()
+ white_leaf = white_root.select_leaf()
+ self.assertEqual(black_leaf.fmove, white_leaf.fmove)
+ self.assertEqualNPArray(
+ black_root.child_action_score, white_root.child_action_score)
+
+ def test_select_leaf(self):
+ flattened = coords.to_flat(utils_test.BOARD_SIZE, coords.from_kgs(
+ utils_test.BOARD_SIZE, 'D9'))
+ probs = np.array([.02] * (
+ utils_test.BOARD_SIZE * utils_test.BOARD_SIZE + 1))
+ probs[flattened] = 0.4
+ root = MCTSNode(utils_test.BOARD_SIZE, SEND_TWO_RETURN_ONE)
+ root.select_leaf().incorporate_results(probs, 0, root)
+
+ self.assertEqual(root.position.to_play, go.WHITE)
+ self.assertEqual(root.select_leaf(), root.children[flattened])
+
+ def test_backup_incorporate_results(self):
+ probs = np.array([.02] * (
+ utils_test.BOARD_SIZE * utils_test.BOARD_SIZE + 1))
+ root = MCTSNode(utils_test.BOARD_SIZE, SEND_TWO_RETURN_ONE)
+ root.select_leaf().incorporate_results(probs, 0, root)
+
+ leaf = root.select_leaf()
+ leaf.incorporate_results(probs, -1, root) # white wins!
+
+ # Root was visited twice: first at the root, then at this child.
+ self.assertEqual(root.N, 2)
+ # Root has 0 as a prior and two visits with value 0, -1
+ self.assertAlmostEqual(root.Q, -1/3) # average of 0, 0, -1
+ # Leaf should have one visit
+ self.assertEqual(root.child_N[leaf.fmove], 1)
+ self.assertEqual(leaf.N, 1)
+ # And that leaf's value had its parent's Q (0) as a prior, so the Q
+ # should now be the average of 0, -1
+ self.assertAlmostEqual(root.child_Q[leaf.fmove], -0.5)
+ self.assertAlmostEqual(leaf.Q, -0.5)
+
+ # We're assuming that select_leaf() returns a leaf like:
+ # root
+ # \
+ # leaf
+ # \
+ # leaf2
+ # which happens in this test because root is W to play and leaf was a W win.
+ self.assertEqual(root.position.to_play, go.WHITE)
+ leaf2 = root.select_leaf()
+ leaf2.incorporate_results(probs, -0.2, root) # another white semi-win
+ self.assertEqual(root.N, 3)
+ # average of 0, 0, -1, -0.2
+ self.assertAlmostEqual(root.Q, -0.3)
+
+ self.assertEqual(leaf.N, 2)
+ self.assertEqual(leaf2.N, 1)
+ # average of 0, -1, -0.2
+ self.assertAlmostEqual(leaf.Q, root.child_Q[leaf.fmove])
+ self.assertAlmostEqual(leaf.Q, -0.4)
+ # average of -1, -0.2
+ self.assertAlmostEqual(leaf.child_Q[leaf2.fmove], -0.6)
+ self.assertAlmostEqual(leaf2.Q, -0.6)
+
+ def test_do_not_explore_past_finish(self):
+ probs = np.array([0.02] * (
+ utils_test.BOARD_SIZE * utils_test.BOARD_SIZE + 1), dtype=np.float32)
+ root = MCTSNode(utils_test.BOARD_SIZE, go.Position(utils_test.BOARD_SIZE))
+ root.select_leaf().incorporate_results(probs, 0, root)
+ first_pass = root.maybe_add_child(
+ coords.to_flat(utils_test.BOARD_SIZE, None))
+ first_pass.incorporate_results(probs, 0, root)
+ second_pass = first_pass.maybe_add_child(
+ coords.to_flat(utils_test.BOARD_SIZE, None))
+ with self.assertRaises(AssertionError):
+ second_pass.incorporate_results(probs, 0, root)
+ node_to_explore = second_pass.select_leaf()
+ # should just stop exploring at the end position.
+ self.assertEqual(node_to_explore, second_pass)
+
+ def test_add_child(self):
+ root = MCTSNode(utils_test.BOARD_SIZE, go.Position(utils_test.BOARD_SIZE))
+ child = root.maybe_add_child(17)
+ self.assertIn(17, root.children)
+ self.assertEqual(child.parent, root)
+ self.assertEqual(child.fmove, 17)
+
+ def test_add_child_idempotency(self):
+ root = MCTSNode(utils_test.BOARD_SIZE, go.Position(utils_test.BOARD_SIZE))
+ child = root.maybe_add_child(17)
+ current_children = copy.copy(root.children)
+ child2 = root.maybe_add_child(17)
+ self.assertEqual(child, child2)
+ self.assertEqual(current_children, root.children)
+
+ def test_never_select_illegal_moves(self):
+ probs = np.array([0.02] * (
+ utils_test.BOARD_SIZE * utils_test.BOARD_SIZE + 1))
+ # let's say the NN were to accidentally put a high weight on an illegal move
+ probs[1] = 0.99
+ root = MCTSNode(utils_test.BOARD_SIZE, SEND_TWO_RETURN_ONE)
+ root.incorporate_results(probs, 0, root)
+ # and let's say the root were visited a lot of times, which pumps up the
+ # action score for unvisited moves...
+ root.N = 100000
+ root.child_N[root.position.all_legal_moves()] = 10000
+ # this should not throw an error...
+ leaf = root.select_leaf()
+ # the returned leaf should not be the illegal move
+ self.assertNotEqual(leaf.fmove, 1)
+
+ # and even after injecting noise, we should still not select an illegal move
+ for _ in range(10):
+ root.inject_noise()
+ leaf = root.select_leaf()
+ self.assertNotEqual(leaf.fmove, 1)
+
+ def test_dont_pick_unexpanded_child(self):
+ probs = np.array([0.001] * (
+ utils_test.BOARD_SIZE * utils_test.BOARD_SIZE + 1))
+ # make one move really likely so that tree search goes down that path twice
+ # even with a virtual loss
+ probs[17] = 0.999
+ root = MCTSNode(utils_test.BOARD_SIZE, go.Position(utils_test.BOARD_SIZE))
+ root.incorporate_results(probs, 0, root)
+ leaf1 = root.select_leaf()
+ self.assertEqual(leaf1.fmove, 17)
+ leaf1.add_virtual_loss(up_to=root)
+ # the second select_leaf pick should return the same thing, since the child
+ # hasn't yet been sent to neural net for eval + result incorporation
+ leaf2 = root.select_leaf()
+ self.assertIs(leaf1, leaf2)
+
+
+if __name__ == '__main__':
+ tf.test.main()
diff --git a/pool/shard009/Python/0083661_init__.py b/pool/shard009/Python/0083661_init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..baad0c4141d4665d7891e3719975481c40866108
--- /dev/null
+++ b/pool/shard009/Python/0083661_init__.py
@@ -0,0 +1,193 @@
+# -*- coding: utf8 -*-
+# Text Tools Plugin
+#
+# Copyright (C) 2008 Shaddy Zeineddine
+#
+# 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 .
+# Some code was got from LineTools Plugin
+
+import gedit
+import gtk
+
+class TextToolsPlugin(gedit.Plugin):
+
+ line_tools_str = """
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ """
+
+ bookmarks = {}
+
+ def __init__(self):
+ gedit.Plugin.__init__(self)
+ self.__select_word_special = False
+
+ def activate(self, window):
+ actions = [
+ ('TextTools', None, 'Text Tools'),
+ ('ClearLine', None, 'Clear Line', 'c', 'Remove all the characters on the current line', self.clear_line),
+ ('DuplicateLine', None, 'Duplicate Line', 'd', 'Create a duplicate of the current line below the current line', self.duplicate_line),
+ ('RaiseLine', None, 'Move Line Up', 'Up', 'Transpose the current line with the line above it', self.raise_line),
+ ('LowerLine', None, 'Move Line Down', 'Down', 'Transpose the current line with the line below it', self.lower_line),
+ ('SelectEnclosed', None, 'Select Enclosed Text','9', 'Select the content between enclose chars, quotes or tags', self.select_enclosed),
+ ('SelectWord', None, 'Select Word', 'W', 'Select the word located under cursor', self.select_word),
+ ('SelectWordSpecial', None, 'Select Word Special','W', 'Select the word located under cursor ignoring any delimiter', self.select_word_special)
+ ]
+ windowdata = dict()
+ window.set_data("TextToolsPluginWindowDataKey", windowdata)
+ windowdata["action_group"] = gtk.ActionGroup("GeditTextToolsPluginActions")
+ windowdata["action_group"].add_actions(actions, window)
+ manager = window.get_ui_manager()
+ manager.insert_action_group(windowdata["action_group"], -1)
+ windowdata["ui_id"] = manager.add_ui_from_string(self.line_tools_str)
+ window.set_data("TextToolsPluginInfo", windowdata)
+
+ def deactivate(self, window):
+ windowdata = window.get_data("TextToolsPluginWindowDataKey")
+ manager = window.get_ui_manager()
+ manager.remove_ui(windowdata["ui_id"])
+ manager.remove_action_group(windowdata["action_group"])
+
+ def update_ui(self, window):
+ view = window.get_active_view()
+ windowdata = window.get_data("TextToolsPluginWindowDataKey")
+ windowdata["action_group"].set_sensitive(bool(view and view.get_editable()))
+
+ def clear_line(self, action, window):
+ # Got from LineTools plugin
+ doc = window.get_active_document()
+ doc.begin_user_action()
+ itstart = doc.get_iter_at_mark(doc.get_insert())
+ itstart.set_line_offset(0);
+ is_end = itstart.ends_line()
+ if is_end == False:
+ itend = doc.get_iter_at_mark(doc.get_insert())
+ is_end = itend.ends_line()
+ if is_end == False:
+ itend.forward_to_line_end()
+ doc.delete(itstart, itend)
+ doc.end_user_action()
+
+ def duplicate_line(self, action, window):
+ # Got from LineTools plugin
+ doc = window.get_active_document()
+ doc.begin_user_action()
+ itstart = doc.get_iter_at_mark(doc.get_insert())
+ itstart.set_line_offset(0);
+ itend = doc.get_iter_at_mark(doc.get_insert())
+ itend.forward_line()
+ line = doc.get_slice(itstart, itend, True)
+ doc.insert(itend, line)
+ doc.end_user_action()
+
+ def raise_line(self, action, window):
+ # Got from LineTools plugin
+ doc = window.get_active_document()
+ doc.begin_user_action()
+ itstart = doc.get_iter_at_mark(doc.get_insert())
+ itstart.set_line_offset(0);
+ itstart.backward_line()
+ itend = doc.get_iter_at_mark(doc.get_insert())
+ itend.set_line_offset(0);
+ line = doc.get_slice(itstart, itend, True)
+ doc.delete(itstart, itend)
+ itend.forward_line()
+ doc.insert(itend, line)
+ doc.end_user_action()
+
+ def lower_line(self, action, window):
+ # Got from LineTools plugin
+ doc = window.get_active_document()
+ doc.begin_user_action()
+ itstart = doc.get_iter_at_mark(doc.get_insert())
+ itstart.forward_line()
+ itend = doc.get_iter_at_mark(doc.get_insert())
+ itend.forward_line()
+ itend.forward_line()
+ line = doc.get_slice(itstart, itend, True)
+ doc.delete(itstart, itend)
+ itstart.backward_line()
+ doc.insert(itstart, line)
+ doc.end_user_action()
+
+ def select_enclosed(self, action, window):
+ """Select Characters enclosed by quotes or braces"""
+ starting_chars = ["`",'"', "'", "[", "(", "{", "<", ">", "/"]
+ ending_chars = ["`",'"', "'", "]", ")", "}", ">", "<", "/"]
+ beg_iter = None
+ end_iter = None
+ char_match = None
+ doc = window.get_active_document()
+ itr = doc.get_iter_at_mark(doc.get_insert())
+ while itr.backward_char():
+ if itr.get_char() in starting_chars:
+ char_match = ending_chars[starting_chars.index(itr.get_char())]
+ itr.forward_char()
+ beg_iter = itr.copy()
+ break
+ while itr.forward_char():
+ if itr.get_char() == char_match:
+ end_iter = itr.copy()
+ break
+ doc.select_range(beg_iter, end_iter)
+
+ def select_word_special(self, action, window):
+ self.__select_word_special = True
+ self.select_word(action, window)
+ self.__select_word_special = False
+
+ def select_word(self, action, window):
+ """Select Characters enclosed by quotes or braces"""
+ beg_iter = None
+ end_iter = None
+ if self.__select_word_special:
+ word_delimiter_chars = [" ","\n"]
+ else:
+ word_delimiter_chars = [" ","\n", '"', "'", "[", "(", "{", "]", ")", "}", ":", ";", "`", "="]
+ char_match = None
+ doc = window.get_active_document()
+ itr = doc.get_iter_at_mark(doc.get_insert())
+ while itr.backward_char():
+ if itr.get_char() in word_delimiter_chars:
+ itr.forward_char()
+ beg_iter = itr.copy()
+ break
+ if beg_iter == None:
+ beg_iter = itr.copy()
+
+ while itr.forward_char():
+ if itr.get_char() in word_delimiter_chars:
+ end_iter = itr.copy()
+ break
+ if end_iter == None:
+ end_iter = itr.copy()
+
+ if beg_iter and end_iter:
+ doc.select_range(beg_iter, end_iter)
+
diff --git a/pool/shard009/Python/0083664_utils.py b/pool/shard009/Python/0083664_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..ec0f0a4c46a9538b10a9d4e17206b92f7ad902d4
--- /dev/null
+++ b/pool/shard009/Python/0083664_utils.py
@@ -0,0 +1,37 @@
+#!/usr/bin/env python3
+
+from contextlib import contextmanager
+from typing import Generator
+
+import torch
+
+
+def approx_equal(self, other, epsilon=1e-4):
+ """
+ Determines if two tensors are approximately equal
+ Args:
+ - self: tensor
+ - other: tensor
+ Returns:
+ - bool
+ """
+ if self.size() != other.size():
+ raise RuntimeError(
+ "Size mismatch between self ({self}) and other ({other})".format(self=self.size(), other=other.size())
+ )
+ return torch.max((self - other).abs()) <= epsilon
+
+
+def get_cuda_max_memory_allocations() -> int:
+ """Get the `max_memory_allocated` for each cuda device"""
+ return torch.tensor([torch.cuda.max_memory_allocated(i) for i in range(torch.cuda.device_count())])
+
+
+@contextmanager
+def least_used_cuda_device() -> Generator:
+ """Contextmanager for automatically selecting the cuda device
+ with the least allocated memory"""
+ mem_allocs = get_cuda_max_memory_allocations()
+ least_used_device = torch.argmin(mem_allocs).item()
+ with torch.cuda.device(least_used_device):
+ yield
diff --git a/pool/shard009/Python/0083667_test_result_model.py b/pool/shard009/Python/0083667_test_result_model.py
new file mode 100644
index 0000000000000000000000000000000000000000..792fd521428cc6dc4a4ef749710ffda7e8339b1d
--- /dev/null
+++ b/pool/shard009/Python/0083667_test_result_model.py
@@ -0,0 +1,26 @@
+from django.db import models
+
+from edc_base.model.models import BaseUuidModel
+
+
+class TestResultModel(BaseUuidModel):
+
+ subject_identifier = models.CharField(max_length=25, db_index=True)
+ report_datetime = models.DateTimeField(null=True, db_index=True)
+ result = models.CharField(max_length=25)
+ result_datetime = models.DateTimeField()
+
+ def get_report_datetime(self):
+ return self.result_datetime
+
+ def get_test_code(self):
+ return 'HIV'
+
+ def get_result_datetime(self):
+ return self.result_datetime
+
+ def get_subject_identifier(self):
+ return self.subject_identifier
+
+ class Meta:
+ app_label = 'lab_tracker'
diff --git a/pool/shard009/Python/0083669_tf_should_use_test.py b/pool/shard009/Python/0083669_tf_should_use_test.py
new file mode 100644
index 0000000000000000000000000000000000000000..f421ff9b402b44a5e0197f423a742ee4ea56f4d1
--- /dev/null
+++ b/pool/shard009/Python/0083669_tf_should_use_test.py
@@ -0,0 +1,139 @@
+# Copyright 2017 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.
+# ==============================================================================
+"""Unit tests for tf_should_use."""
+
+# pylint: disable=unused-import
+import contextlib
+import gc
+import sys
+
+from tensorflow.python.eager import context
+from tensorflow.python.eager import def_function
+from tensorflow.python.framework import constant_op
+from tensorflow.python.framework import test_util
+from tensorflow.python.platform import test
+from tensorflow.python.platform import tf_logging
+from tensorflow.python.util import tf_should_use
+
+
+@contextlib.contextmanager
+def reroute_error():
+ """Temporarily reroute errors written to tf_logging.error into `captured`."""
+ with test.mock.patch.object(tf_should_use.tf_logging, 'error') as error:
+ yield error
+
+
+class TfShouldUseTest(test.TestCase):
+
+ def testAddShouldUseWarningWhenNotUsed(self):
+ c = constant_op.constant(0, name='blah0')
+ def in_this_function():
+ h = tf_should_use._add_should_use_warning(c, warn_in_eager=True)
+ del h
+ with reroute_error() as error:
+ in_this_function()
+ msg = '\n'.join(error.call_args[0])
+ self.assertIn('Object was never used', msg)
+ if not context.executing_eagerly():
+ self.assertIn('blah0:0', msg)
+ self.assertIn('in_this_function', msg)
+ self.assertFalse(gc.garbage)
+
+ def testAddShouldUseExceptionInEagerAndFunction(self):
+ def in_this_function():
+ c = constant_op.constant(0, name='blah0')
+ h = tf_should_use._add_should_use_warning(
+ c, warn_in_eager=True, error_in_function=True)
+ del h
+ if context.executing_eagerly():
+ with reroute_error() as error:
+ in_this_function()
+ msg = '\n'.join(error.call_args[0])
+ self.assertIn('Object was never used', msg)
+ self.assertIn('in_this_function', msg)
+ self.assertFalse(gc.garbage)
+
+ tf_fn_in_this_function = def_function.function(in_this_function)
+ with self.assertRaisesRegex(RuntimeError,
+ r'Object was never used.*blah0:0'):
+ tf_fn_in_this_function()
+ self.assertFalse(gc.garbage)
+
+ def _testAddShouldUseWarningWhenUsed(self, fn, name):
+ c = constant_op.constant(0, name=name)
+ with reroute_error() as error:
+ h = tf_should_use._add_should_use_warning(c, warn_in_eager=True)
+ fn(h)
+ del h
+ error.assert_not_called()
+
+ def testAddShouldUseWarningWhenUsedWithAdd(self):
+ def add(h):
+ _ = h + 1
+ self._testAddShouldUseWarningWhenUsed(add, name='blah_add')
+ gc.collect()
+ self.assertFalse(gc.garbage)
+
+ def testAddShouldUseWarningWhenUsedWithGetShape(self):
+ def get_shape(h):
+ _ = h.shape
+ self._testAddShouldUseWarningWhenUsed(get_shape, name='blah_get_name')
+ gc.collect()
+ self.assertFalse(gc.garbage)
+
+ def testShouldUseResult(self):
+ @tf_should_use.should_use_result(warn_in_eager=True)
+ def return_const(value):
+ return constant_op.constant(value, name='blah2')
+ with reroute_error() as error:
+ return_const(0.0)
+ msg = '\n'.join(error.call_args[0])
+ self.assertIn('Object was never used', msg)
+ if not context.executing_eagerly():
+ self.assertIn('blah2:0', msg)
+ self.assertIn('return_const', msg)
+ gc.collect()
+ self.assertFalse(gc.garbage)
+
+ def testShouldUseResultWhenNotReallyUsed(self):
+ @tf_should_use.should_use_result(warn_in_eager=True)
+ def return_const(value):
+ return constant_op.constant(value, name='blah3')
+ with reroute_error() as error:
+ with self.cached_session():
+ return_const(0.0)
+ # Creating another op and executing it does not mark the
+ # unused op as being "used".
+ v = constant_op.constant(1.0, name='meh')
+ self.evaluate(v)
+ msg = '\n'.join(error.call_args[0])
+ self.assertIn('Object was never used', msg)
+ if not context.executing_eagerly():
+ self.assertIn('blah3:0', msg)
+ self.assertIn('return_const', msg)
+ gc.collect()
+ self.assertFalse(gc.garbage)
+
+ # Tests that mark_used is available in the API.
+ def testMarkUsed(self):
+ @tf_should_use.should_use_result(warn_in_eager=True)
+ def return_const(value):
+ return constant_op.constant(value, name='blah3')
+
+ with self.cached_session():
+ return_const(0.0).mark_used()
+
+if __name__ == '__main__':
+ test.main()
diff --git a/pool/shard009/Python/0083673_oauth1.py b/pool/shard009/Python/0083673_oauth1.py
new file mode 100644
index 0000000000000000000000000000000000000000..d52dd106c8aeebd4c69d4a2978c12842172ac296
--- /dev/null
+++ b/pool/shard009/Python/0083673_oauth1.py
@@ -0,0 +1,229 @@
+# -*- coding: utf-8 -*-
+#
+# This file is part of Invenio.
+# Copyright (C) 2012 CERN.
+#
+# Invenio is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License as
+# published by the Free Software Foundation; either version 2 of the
+# License, or (at your option) any later version.
+#
+# Invenio is distributed in the hope that it will be useful, but
+# WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with Invenio; if not, write to the Free Software Foundation, Inc.,
+# 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
+
+"""
+This module contains functions and methods to authenticate with OAuth1
+providers.
+"""
+
+__revision__ = \
+ "$Id$"
+
+from invenio.utils.container import get_substructure
+from invenio.legacy.dbquery import run_sql
+from invenio.legacy.external_authentication import ExternalAuth
+
+class ExternalOAuth1(ExternalAuth):
+ """
+ Contains methods for authenticate with an OpenID provider.
+ """
+
+ @staticmethod
+ def __init_req(req):
+ req.g['oauth1_provider_name'] = ''
+ req.g['oauth1_debug'] = 0
+ req.g['oauth1_msg'] = ''
+ req.g['oauth1_debug_msg'] = ''
+ req.g['oauth1_response'] = None
+
+ def auth_user(self, username, password, req=None):
+ """
+ Tries to find email and identity of the user from OAuth1 provider. If it
+ doesn't find any of them, returns (None, None)
+
+ @param username: Isn't used in this function
+ @type username: str
+
+ @param password: Isn't used in this function
+ @type password: str
+
+ @param req: request
+ @type req: invenio.legacy.wsgi.SimulatedModPythonRequest
+
+ @rtype: str|NoneType, str|NoneType
+ """
+ from invenio.modules.access.local_config import CFG_OAUTH1_CONFIGURATIONS
+ from invenio.modules.access.local_config import CFG_OAUTH1_PROVIDERS
+ from invenio.ext.legacy.handler import wash_urlargd
+ from rauth.service import OAuth1Service
+
+ self.__init_req(req)
+
+ args = wash_urlargd(req.form, {'provider': (str, ''),
+ 'login_method': (str, ''),
+ 'oauth_token': (str, ''),
+ 'oauth_verifier': (str, ''),
+ 'denied': (str, '')
+ })
+ provider_name = req.g['oauth1_provider_name'] = args['provider']
+
+ if not provider_name in CFG_OAUTH1_PROVIDERS:
+ req.g['oauth1_msg'] = 22
+ return None, None
+
+ # Load the configurations to construct OAuth1 service
+ config = CFG_OAUTH1_CONFIGURATIONS[args['provider']]
+
+ req.g['oauth1_debug'] = config.get('debug', 0)
+
+ if not args['oauth_token']:
+ # In case of an error, display corresponding message
+ if args['denied']:
+ req.g['oauth1_msg'] = 21
+ return None, None
+ else:
+ req.g['oauth1_msg'] = 22
+ return None, None
+
+ provider = OAuth1Service(
+ name = req.g['oauth1_provider_name'],
+ consumer_key = config['consumer_key'],
+ consumer_secret = config['consumer_secret'],
+ request_token_url = config['request_token_url'],
+ access_token_url = config['access_token_url'],
+ authorize_url = config['authorize_url'],
+ header_auth = True)
+
+ # Get the request token secret from database and exchange it with the
+ # access token.
+ query = """SELECT secret FROM oauth1_storage WHERE token = %s"""
+ params = (args['oauth_token'],)
+ try:
+ # If the request token is already used, return
+ request_token_secret = run_sql(query, params)[0][0]
+ except IndexError:
+ req.g['oauth1_msg'] = 22
+ return None, None
+
+ response = provider.get_access_token(
+ 'GET',
+ request_token = args['oauth_token'],
+ request_token_secret = request_token_secret,
+ params = {
+ 'oauth_verifier': args['oauth_verifier']
+ }
+ )
+
+ if req.g['oauth1_debug']:
+ req.g['oauth1_debug_msg'] = str(response.content) + " "
+
+ # Some providers send the identity and access token together.
+ email, identity = self._get_user_email_and_id(response.content, req)
+
+ if not identity and 'request_url' in config:
+ # For some providers, to reach user profile we need to make request
+ # to a specific url.
+ params = config.get('request_parameters', {})
+ response = provider.get(config['request_url'],
+ params = params,
+ access_token = response.content['oauth_token'],
+ access_token_secret = response.content['oauth_token_secret']
+ )
+
+ if req.oauth1_debug:
+ req.g['oauth1_debug_msg'] += str(response.content) + " "
+
+ email, identity = self._get_user_email_and_id(response.content, req)
+
+ if identity:
+ # If identity is found, add the name of the provider at the
+ # beginning of the identity because different providers may have
+ # different users with same id.
+ identity = "%s:%s" % (req.g['oauth1_provider_name'], identity)
+ else:
+ req.g['oauth1_msg'] = 23
+
+ # Delete the token saved in the database since it is useless now.
+ query = """
+ DELETE FROM oauth1_storage
+ WHERE token=%s
+ OR date_creation < DATE_SUB(NOW(), INTERVAL 1 HOUR)
+ """
+ params = (args['oauth_token'],)
+ run_sql(query, params)
+
+ if req.g['oauth1_debug']:
+ req.g['oauth1_msg'] = "%s" % req.g['oauth1_debug_msg'].replace("\n", " ")
+ return None, None
+
+ return email, identity
+
+ def fetch_user_nickname(self, username, password=None, req=None):
+ """
+ Fetches the OAuth1 provider for nickname of the user. If it doesn't
+ find any, returns None.
+
+ This function doesn't need username, password or req. They are exist
+ just because this class is derived from ExternalAuth
+
+ @param username: Isn't used in this function
+ @type username: str
+
+ @param password: Isn't used in this function
+ @type password: str
+
+ @param req: Isn't used in this function
+ @type req: invenio.legacy.wsgi.SimulatedModPythonRequest
+
+ @rtype: str or NoneType
+ """
+ from invenio.modules.access.local_config import CFG_OAUTH1_CONFIGURATIONS
+
+ if req.g['oauth1_provider_name']:
+ path = None
+ if 'nickname' in CFG_OAUTH1_CONFIGURATIONS[req.g['oauth1_provider_name']]:
+ path = CFG_OAUTH1_CONFIGURATIONS[req.g['oauth1_provider_name']]['nickname']
+
+ if path:
+ return get_substructure(req.oauth1_response, path)
+ else:
+ return None
+
+ def _get_user_email_and_id(self, container, req):
+ """
+ Returns external identity and email address together. Since identity is
+ essential for OAuth1 authentication, if it doesn't find external
+ identity returns None, None.
+
+ @param container: container which contains email and id
+ @type container: list|dict
+
+ @rtype str|NoneType, str|NoneType
+ """
+ from invenio.modules.access.local_config import CFG_OAUTH1_CONFIGURATIONS
+
+ identity = None
+ email = None
+
+ if 'id' in CFG_OAUTH1_CONFIGURATIONS[req.g['oauth1_provider_name']]:
+ path = CFG_OAUTH1_CONFIGURATIONS[req.g['oauth1_provider_name']]['id']
+ identity = get_substructure(container, path)
+
+ if identity:
+ if 'email' in CFG_OAUTH1_CONFIGURATIONS[req.g['oauth1_provider_name']]:
+ path = CFG_OAUTH1_CONFIGURATIONS[req.g['oauth1_provider_name']]['email']
+ email = get_substructure(container, path)
+
+ req.g['oauth1_response'] = container
+
+ return email, identity
+
+ @staticmethod
+ def get_msg(req):
+ return req.g['oauth1_msg']
diff --git a/pool/shard009/Python/0083674_extract4category.py b/pool/shard009/Python/0083674_extract4category.py
new file mode 100644
index 0000000000000000000000000000000000000000..b3b0a4c116b64bc371ee9184d0e88f4c6a019110
--- /dev/null
+++ b/pool/shard009/Python/0083674_extract4category.py
@@ -0,0 +1,47 @@
+#!/usr/bin/python
+# -*- coding: utf-8 -*-
+# http://www.python.org/dev/peps/pep-0263/
+from __future__ import division;
+from decimal import Decimal;
+import re;
+from collections import OrderedDict
+import csv, json
+from argparse import ArgumentParser
+
+from bukvik.io.BukvikIO import BukvikIO
+from bukvik.debug.BukvikDebug import BukvikDebug
+
+class Extract4Category():
+ def __init__(self, name):
+ pass;
+
+ def process(self, task):
+ # TODO ... conversion
+
+ categories = task["parameters"]["categories"]
+ dataOut = {}
+
+ # TODO:
+
+ dataOutStr = json.dumps(dataOut, sort_keys=True, indent=4, separators=(',', ': '))
+
+ filenameOut = task["parameters"]["filenameOut"];
+ encoding = "utf-8";
+ io.saveFile(filenameOut, dataOutStr, encoding)
+
+a = Extract4Category("Extract Writers");
+
+parser = ArgumentParser(description='This Colabo Puzzle Extracts the list of wikipedia pages (references) that belongs to a specified category')
+parser.add_argument("-t", "--task", dest="task_filename",
+ help="JSON file with the task description", default=True, metavar="")
+
+args = parser.parse_args()
+
+io = BukvikIO();
+encoding = "utf-8";
+BukvikDebug.debug("__MAIN__", "",
+ "loading Task file, filenameIn = %s (encoding: %s)" % (args.task_filename, encoding))
+taskStr = io.loadFile(args.task_filename, encoding)
+taskObj = json.loads(taskStr)
+# print(taskObj)
+a.process(taskObj);
diff --git a/pool/shard009/Python/0083680_test_controller.py b/pool/shard009/Python/0083680_test_controller.py
new file mode 100644
index 0000000000000000000000000000000000000000..34f9c121ea14a51d158f0cd7c931e17a030b174a
--- /dev/null
+++ b/pool/shard009/Python/0083680_test_controller.py
@@ -0,0 +1,35 @@
+# Copyright 2014 The guava Authors. All rights reserved.
+# Use of this source code is governed by a BSD-style
+# license that can be found in the LICENSE file.
+
+import unittest
+import guava
+
+
+class MyController(guava.controller.Controller):
+
+ def index(self):
+ pass
+
+
+class TestController(unittest.TestCase):
+
+ def setUp(self):
+ pass
+
+ def test_controller(self):
+ c = MyController()
+
+ self.assertTrue(c.set_header != None)
+ self.assertTrue(c.write != None)
+ self.assertTrue(c.set_status_code != None)
+ self.assertTrue(c.redirect != None)
+ self.assertTrue(c.before_action != None)
+ self.assertTrue(c.after_action != None)
+ self.assertTrue(c.set_cookie != None)
+
+ self.assertEqual(c.GET, {})
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/pool/shard009/Python/0083682_template_filters.py b/pool/shard009/Python/0083682_template_filters.py
new file mode 100644
index 0000000000000000000000000000000000000000..f17d5de825b11cda9c03938d2359b53de2e33099
--- /dev/null
+++ b/pool/shard009/Python/0083682_template_filters.py
@@ -0,0 +1,47 @@
+# coding: utf-8
+
+# TODO load from blueprints
+
+import sys
+
+from flask import Blueprint
+from werkzeug.routing import Rule
+from quokka.core.app import QuokkaModule
+from quokka.core.models import Content
+from quokka_themes import Theme
+
+
+if sys.version_info.major == 3:
+ unicode = lambda x: u'{}'.format(x) # noqa
+ basestring = str # noqa
+
+basetypes = (
+ int, str, float, dict, list, tuple, Blueprint, QuokkaModule, Theme, Rule,
+ basestring, unicode)
+
+
+def is_instance(v, cls):
+ cls_map = {
+ tp.__name__: tp for tp in basetypes
+ }
+ return isinstance(v, cls_map.get(cls, str))
+
+
+def get_content(**kwargs):
+ try:
+ return Content.objects.get(**kwargs)
+ except:
+ return None
+
+
+def get_contents(limit=None, order_by="-created_at", **kwargs):
+ contents = Content.objects.filter(**kwargs).order_by(order_by)
+ if limit:
+ contents = contents[:limit]
+ return contents
+
+
+def configure(app):
+ app.jinja_env.filters['isinstance'] = is_instance
+ app.add_template_global(get_content)
+ app.add_template_global(get_contents)
diff --git a/pool/shard009/Python/0083684_db_tests.py b/pool/shard009/Python/0083684_db_tests.py
new file mode 100644
index 0000000000000000000000000000000000000000..55055fd525fe73f895c43ef478c9f8fe691cfe24
--- /dev/null
+++ b/pool/shard009/Python/0083684_db_tests.py
@@ -0,0 +1,40 @@
+# coding=UTF-8
+# Author: Dennis Lutter
+# URL: http://code.google.com/p/sickbeard/
+#
+# This file is part of Sick Beard.
+#
+# Sick Beard 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.
+#
+# Sick Beard 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 Sick Beard. If not, see .
+
+import unittest
+import test_lib as test
+
+
+class DBBasicTests(test.SickbeardTestDBCase):
+
+ def setUp(self):
+ super(DBBasicTests, self).setUp()
+ self.db = test.db.DBConnection()
+
+ def test_select(self):
+ self.db.select("SELECT * FROM tv_episodes WHERE showid = ? AND location != ''", [0000])
+
+
+if __name__ == '__main__':
+ print "=================="
+ print "STARTING - DB TESTS"
+ print "=================="
+ print "######################################################################"
+ suite = unittest.TestLoader().loadTestsFromTestCase(DBBasicTests)
+ unittest.TextTestRunner(verbosity=2).run(suite)
diff --git a/pool/shard009/Python/0083688_proxy.py b/pool/shard009/Python/0083688_proxy.py
new file mode 100644
index 0000000000000000000000000000000000000000..27b5fc3cd5fcbc0c4ba4b4659a7971c7a22b2f01
--- /dev/null
+++ b/pool/shard009/Python/0083688_proxy.py
@@ -0,0 +1,95 @@
+# -*- coding: utf-8 -*-
+
+# Pyhaa - Templating system for Python 3
+# Copyright (c) 2011 Tomasz Kowalczyk
+# Contact e-mail: code@fluxid.pl
+#
+# This library is free software: you can redistribute it and/or modify it under
+# the terms of the GNU Lesser General Public License as published by the Free
+# Software Foundation, either version 3 of the License, or (at your option) any
+# later version.
+#
+# This library is distributed in the hope that it will be useful, but WITHOUT
+# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
+# details.
+#
+# You should have received a copy of the GNU Lesser General Public License
+# along with this library in the file COPYING.LESSER. If not, see
+# .
+
+class BoundPartial:
+ def __init__(self, instance, parent, name, partial):
+ self.instance = instance
+ self.parent = parent
+ self.name = name
+ self.partial = partial
+
+ def __call__(self, *args, **kwargs):
+ return self.partial(self.instance, self.parent, *args, **kwargs)
+
+ def __repr__(self):
+ return '<{} {} {}>'.format(
+ self.__class__.__name__,
+ self.name,
+ self.partial,
+ )
+
+
+class NamespaceLookup:
+ def __getattr__(self, name):
+ #if name.startswith('_ph_'):
+ # getattr(super(NamespaceLookup, self), name)
+ try:
+ result = getattr(self._ph_template, name)
+ except AttributeError:
+ pass
+ else:
+ return result
+
+ partial = self._ph_template.get_partial(name)
+ if partial:
+ result = BoundPartial(self._ph_instance, self._ph_parent, name, partial)
+ return result
+ if self._ph_parent:
+ return getattr(self._ph_parent, name)
+
+ # TODO Template X has no attribyte Y
+ raise AttributeError(name)
+
+ def __call__(self, *args, **kwargs):
+ partial = getattr(self, '__body__')
+ return partial(*args, **kwargs)
+
+
+class ParentProxy(NamespaceLookup):
+ __slots__ = ('_ph_instance', '_ph_template', '_ph_parent')
+
+ def __init__(self, instance, template):
+ self._ph_instance = instance
+ self._ph_template = template
+ self._ph_parent = None
+
+
+class InstanceProxy(NamespaceLookup):
+ def __init__(self, inheritance_chain, environment):
+ iiter = iter(inheritance_chain)
+ template = next(iiter)
+
+ self._ph_instance = self
+ self._ph_template = template
+ self._ph_parent = None
+ self._ph_environment = environment
+
+ last_one = self
+ for parent_template in iiter:
+ last_one._ph_parent = parent = ParentProxy(self, parent_template)
+ last_one = parent
+
+
+ def __repr__(self):
+ return '<{} {}>'.format(
+ self.__class__.__name__,
+ repr(self._ph_template),
+ )
+
diff --git a/pool/shard009/Python/0083692_base_sync.py b/pool/shard009/Python/0083692_base_sync.py
new file mode 100644
index 0000000000000000000000000000000000000000..38f84230144dd2a554e5241d5f7432773725a9e3
--- /dev/null
+++ b/pool/shard009/Python/0083692_base_sync.py
@@ -0,0 +1,65 @@
+# Copyright (c) 2016-2021, NVIDIA CORPORATION.
+# SPDX-License-Identifier: Apache-2.0
+
+import os
+
+
+class BaseSync(object):
+ """
+ Base class for all classes that implement the sync functionality. Sets up
+ the swift client with the default configuration, which points to the local
+ Swift configuration. Supplies the skeleton methods that must be overwritten
+ by all child classes.
+ """
+
+ def __init__(self, status_dir, settings, per_account=False):
+ """Base class that all users of the ContainerCrawler should derive from
+
+ Arguments:
+ status_dir -- directory that contains the sync status files
+ settings -- sync settings; contains at least the following keys:
+ account -- the Swift account that is synced
+ container -- the specific container within the account
+ Any other keys are provider specific.
+
+ Keyword arguments:
+ per_account -- whether the operation is happening on every container in
+ the account.
+ """
+ self._status_dir = status_dir
+ self._account = settings['account']
+ self._container = settings['container']
+ if 'internal_account' in settings and 'internal_container' in settings:
+ # sharded containers maybe in a hidden account that we use for
+ # status file tracking
+ self._status_file = os.path.join(
+ self._status_dir,
+ settings['internal_account'],
+ settings['internal_container']).encode('utf-8')
+ self._status_account_dir = os.path.join(
+ self._status_dir, settings['internal_account']).encode('utf-8')
+ else:
+ self._status_file = os.path.join(self._status_dir, self._account,
+ self._container).encode('utf-8')
+ self._status_account_dir = os.path.join(
+ self._status_dir, self._account).encode('utf-8')
+ self._per_account = per_account
+
+ def handle(self, rows, swift_client):
+ raise NotImplementedError
+
+ def get_last_processed_row(self, db_id):
+ raise NotImplementedError
+
+ def save_last_processed_row(self, row_id, db_id):
+ raise NotImplementedError
+
+ def get_last_verified_row(self, db_id):
+ raise NotImplementedError
+
+ def save_last_verified_row(self, row_id, db_id):
+ raise NotImplementedError
+
+ def handle_container_info(self, broker_info, metadata):
+ # Optional to implement
+ pass
diff --git a/pool/shard009/Python/0083697_poller_allEgauge.py b/pool/shard009/Python/0083697_poller_allEgauge.py
new file mode 100644
index 0000000000000000000000000000000000000000..d73fc16084178a6d23f0a2fdbc73a5870497b84b
--- /dev/null
+++ b/pool/shard009/Python/0083697_poller_allEgauge.py
@@ -0,0 +1,134 @@
+import urllib2, code
+import xml.etree.cElementTree as ET
+import MySQLdb
+import datetime, threading, time
+
+# Reads eGauge XML data from an input URL and outputs pertinent data
+def readEgauge(uxmlurl,indices,includeTimeStamp):
+ # Open the URL and parse the xml data
+ try:
+ response = urllib2.urlopen(uxmlurl,timeout = 15)
+ # except urllib2.URLError, e:
+ except:
+ nValues = len(indices)
+ return [99999999] * nValues
+ html = response.read()
+ root = ET.fromstring(html)
+
+ # extract the relevant variables and return them
+ outputList = []
+
+ if includeTimeStamp:
+# outputList.append('timestamp')
+ outputList.append(int(root[0].text))
+ for i in indices:
+ outputList.append(float(root[i][2].text))
+# outputList.append(root[i].attrib['title'])
+ return outputList
+
+def timerLoop(db,cursor,commandString,url,indices):
+ global next_call
+
+ data = []
+ # Output the timestamp with the first reading
+ includeTimeStamp = True
+ data = data + readEgauge(url[0],indices[0],includeTimeStamp)
+ # Loop through the remaining measurements
+ includeTimeStamp = False
+ for i in range(1,6):
+ data = data + readEgauge(url[i],indices[i],includeTimeStamp)
+ insertString = commandString % tuple(data)
+# print(insertString)
+ print(datetime.datetime.now())
+ try:
+ cursor.execute(insertString)
+ db.commit()
+ except:
+ db.rollback()
+ next_call = next_call + 1
+ threading.Timer(next_call - time.time(), timerLoop,(db,cursor,commandString,url,indices)).start()
+
+#--------------------------------------
+# Begin Script
+#--------------------------------------
+
+# Connect to the MySQL Database
+db = MySQLdb.connect(host="localhost", port=3306,
+ user="crawler", passwd="disaggreg8tor",
+ db="energydata");
+cursor = db.cursor()
+
+# URLs for the eGauge XML files
+url_egauge = [
+ 'http://152.3.3.246/cgi-bin/egauge?noteam',
+ 'http://152.3.3.236/cgi-bin/egauge?noteam',
+ 'http://152.3.3.210/cgi-bin/egauge?noteam',
+ 'http://152.3.3.214/cgi-bin/egauge?noteam',
+ 'http://152.3.3.235/cgi-bin/egauge?noteam',
+ 'http://152.3.3.213/cgi-bin/egauge?noteam',
+]
+
+# Indices to the registers in the eGauge (as indexed in the xml file)
+# that correspond to the labels below (which are the MySQL column names)
+indices = [ [10,11,8,9],
+ [11,12,10,7,8,9],
+ [9,10,11,13,14,12],
+ [8,9,10,11,12],
+ [11,12,15,16,14,13],
+ [7,8,9,10,11,12]]
+
+labels = (
+ "timestamp",
+ "b7139_01_r_01_phase1",
+ "b7139_01_r_02_phase2",
+ "b7139_01_r_03_solar1",
+ "b7139_01_r_04_solar2",
+ "b7139_02_r_01_panelal2",
+ "b7139_02_r_02_panelal1",
+ "b7139_02_r_03_panelbl2",
+ "b7139_02_r_04_panelbl1",
+ "b7139_02_r_05_panelul2",
+ "b7139_02_r_06_panelul1",
+ "b7139_03_r_01_refrig",
+ "b7139_03_r_02_micro",
+ "b7139_03_r_03_dish",
+ "b7139_03_r_04_oven",
+ "b7139_03_r_06_cooktop",
+ "b7139_03_r_08_kitchen1",
+ "b7139_04_r_01_kitchen2",
+ "b7139_04_r_02_kitchen3",
+ "b7139_04_r_03_washer",
+ "b7139_04_r_04_dryer",
+ "b7139_04_r_06_hotbox",
+ "b7139_05_r_01_ahu1",
+ "b7139_05_r_03_ahu2",
+ "b7139_05_r_05_cu1",
+ "b7139_05_r_07_cu2",
+ "b7139_05_r_09_airrecunit",
+ "b7139_05_r_10_rwp",
+ "b7139_06_r_01_irrigation",
+ "b7139_06_r_02_erv",
+ "b7139_06_r_03_h10p",
+ "b7139_06_r_04_ef1",
+ "b7139_06_r_05_ef2",
+ "b7139_06_r_06_ef3"
+)
+
+labelString = 'INSERT INTO smart_home (' + '%s, ' * 33 + '%s' + ') VALUES ('
+commandString = labelString % labels + '%s, ' * 33
+commandString = commandString + '%s);'
+
+#url = 'http://152.3.3.246/cgi-bin/egauge?noteam'
+
+#code.interact(local=locals())
+
+print("Starting poller.py...\n")
+next_call = time.time()
+try:
+ timerLoop(db,cursor,commandString,url_egauge,indices)
+except:
+ db.close
+ raise
+else:
+ db.close
+# raise
diff --git a/pool/shard009/Python/0083698_utils_feature_selection.py b/pool/shard009/Python/0083698_utils_feature_selection.py
new file mode 100644
index 0000000000000000000000000000000000000000..ad73e0bfdb835855cccd0390b59d73b1309efafb
--- /dev/null
+++ b/pool/shard009/Python/0083698_utils_feature_selection.py
@@ -0,0 +1,120 @@
+from sklearn.base import BaseEstimator, TransformerMixin
+from sklearn.ensemble import RandomForestClassifier, RandomForestRegressor
+from sklearn.linear_model import RandomizedLasso, RandomizedLogisticRegression
+
+
+import scipy
+import itertools
+from sklearn.feature_selection import GenericUnivariateSelect, RFECV, SelectFromModel
+
+
+def get_feature_selection_model_from_name(type_of_estimator, model_name):
+ model_map = {
+ 'classifier': {
+ 'SelectFromModel': SelectFromModel(RandomForestClassifier(n_jobs=-1, max_depth=10, n_estimators=15), threshold='20*mean'),
+ 'RFECV': RFECV(estimator=RandomForestClassifier(n_jobs=-1), step=0.1),
+ 'GenericUnivariateSelect': GenericUnivariateSelect(),
+ 'RandomizedSparse': RandomizedLogisticRegression(),
+ 'KeepAll': 'KeepAll'
+ },
+ 'regressor': {
+ 'SelectFromModel': SelectFromModel(RandomForestRegressor(n_jobs=-1, max_depth=10, n_estimators=15), threshold='0.7*mean'),
+ 'RFECV': RFECV(estimator=RandomForestRegressor(n_jobs=-1), step=0.1),
+ 'GenericUnivariateSelect': GenericUnivariateSelect(),
+ 'RandomizedSparse': RandomizedLasso(),
+ 'KeepAll': 'KeepAll'
+ }
+ }
+
+ return model_map[type_of_estimator][model_name]
+
+
+class FeatureSelectionTransformer(BaseEstimator, TransformerMixin):
+
+
+ def __init__(self, type_of_estimator, column_descriptions, feature_selection_model='SelectFromModel'):
+
+ self.column_descriptions = column_descriptions
+ self.type_of_estimator = type_of_estimator
+ self.feature_selection_model = feature_selection_model
+
+
+ def get(self, prop_name, default=None):
+ try:
+ return getattr(self, prop_name)
+ except AttributeError:
+ return default
+
+
+ def fit(self, X, y=None):
+
+
+ self.selector = get_feature_selection_model_from_name(self.type_of_estimator, self.feature_selection_model)
+
+ if self.selector == 'KeepAll':
+ if scipy.sparse.issparse(X):
+ num_cols = X.shape[0]
+ else:
+ num_cols = len(X[0])
+
+ self.support_mask = [True for col_idx in range(num_cols) ]
+ else:
+ if self.feature_selection_model == 'SelectFromModel':
+ num_cols = X.shape[1]
+ num_rows = X.shape[0]
+ if self.type_of_estimator == 'regressor':
+ self.estimator = RandomForestRegressor(n_jobs=-1, max_depth=10, n_estimators=15)
+ else:
+ self.estimator = RandomForestClassifier(n_jobs=-1, max_depth=10, n_estimators=15)
+
+ self.estimator.fit(X, y)
+
+ feature_importances = self.estimator.feature_importances_
+
+ # Two ways of doing feature selection
+
+ # 1. Any feature with a feature importance of at least 1/100th of our max feature
+ max_feature_importance = max(feature_importances)
+ threshold_by_relative_importance = 0.01 * max_feature_importance
+
+ # 2. 1/4 the number of rows (so 100 rows means 25 columns)
+ sorted_importances = sorted(feature_importances, reverse=True)
+ max_cols = int(num_rows * 0.25)
+ try:
+ threshold_by_max_cols = sorted_importances[max_cols]
+ except IndexError:
+ threshold_by_max_cols = sorted_importances[-1]
+
+ threshold = max(threshold_by_relative_importance, threshold_by_max_cols)
+ self.support_mask = [True if x > threshold else False for x in feature_importances]
+
+ else:
+ self.selector.fit(X, y)
+ self.support_mask = self.selector.get_support()
+
+ # Get a mask of which indices it is we want to keep
+ self.index_mask = [idx for idx, val in enumerate(self.support_mask) if val == True]
+ return self
+
+
+ def transform(self, X, y=None):
+
+ if self.selector == 'KeepAll':
+ return X
+
+ if scipy.sparse.issparse(X):
+ if X.getformat() == 'csr':
+ # convert to a csc (column) matrix, rather than a csr (row) matrix
+ X = X.tocsc()
+
+ # Slice that column matrix to only get the relevant columns that we already calculated in fit:
+ X = X[:, self.index_mask]
+
+ # convert back to a csr matrix
+ return X.tocsr()
+
+ # If this is a dense matrix:
+ else:
+ pruned_X = [list(itertools.compress(row, self.support_mask)) for row in X]
+ return pruned_X
+
diff --git a/pool/shard009/Python/0083701_forms.py b/pool/shard009/Python/0083701_forms.py
new file mode 100644
index 0000000000000000000000000000000000000000..78f1644ddef75388e967562dc1d870409a932d39
--- /dev/null
+++ b/pool/shard009/Python/0083701_forms.py
@@ -0,0 +1,37 @@
+import logging
+
+import flask
+
+import form_models
+from repositories import posts
+
+def new_post():
+ form = form_models.NewPostForm()
+ if form.validate_on_submit():
+ logging.info('Valid form')
+ new_post = posts.create_from_form(form)
+ logging.info(new_post)
+ return flask.redirect('/')
+
+def edit_post(post_id):
+ form = form_models.NewPostForm()
+ if form.validate_on_submit():
+ logging.info('Valid form')
+ new_post = posts.update_from_form(post_id, form)
+ logging.info(new_post)
+ return flask.redirect('/')
+
+
+def delete_post(post_id):
+ form = form_models.DeletePostForm()
+ if form.validate_on_submit():
+ post_id = form.data.get('post_id')
+ post = posts.delete_post(post_id)
+ return flask.redirect('/')
+
+def search():
+ form = form_models.SearchForm(csrf_enabled=False)
+ if form.validate_on_submit():
+ logging.info('Valid search form')
+ posts.search(form.data.get('search_term'))
+ return flask.redirect('/')
\ No newline at end of file
diff --git a/pool/shard009/Python/0083709_init__.py b/pool/shard009/Python/0083709_init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..5f2b45bf8f65564437ce033cd433ac4d393f8ffc
--- /dev/null
+++ b/pool/shard009/Python/0083709_init__.py
@@ -0,0 +1,33 @@
+import transaction
+
+from sqlalchemy.exc import IntegrityError
+
+from sqlalchemy.ext.declarative import declarative_base
+
+from sqlalchemy.orm import scoped_session
+from sqlalchemy.orm import sessionmaker
+
+from zope.sqlalchemy import ZopeTransactionExtension
+
+from datetime import datetime
+
+DBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension()))
+Base = declarative_base()
+
+def initialize_sql(engine):
+ DBSession.configure(bind=engine)
+ Base.metadata.bind = engine
+ Base.metadata.create_all(engine)
+ try:
+ populate()
+ except IntegrityError:
+ DBSession.rollback()
+
+def populate():
+ from haven.models.account import Account
+ account = Account(name=u'admin', password=u'password',
+ email=u'noreply@example.com', activated=True,
+ is_admin = True, verify_code=u'')
+ DBSession.add(account)
+ DBSession.flush()
+ transaction.commit()
diff --git a/pool/shard009/Python/0083710_orm_event_handlers.py b/pool/shard009/Python/0083710_orm_event_handlers.py
new file mode 100644
index 0000000000000000000000000000000000000000..1a5da96812b410e9860e96f8baee7fe3e9d3b239
--- /dev/null
+++ b/pool/shard009/Python/0083710_orm_event_handlers.py
@@ -0,0 +1,88 @@
+#
+# 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.
+
+import logging
+import os
+import time
+import traceback
+
+from sqlalchemy import event, exc
+
+from airflow.configuration import conf
+
+log = logging.getLogger(__name__)
+
+
+def setup_event_handlers(engine):
+ """Setups event handlers."""
+
+ @event.listens_for(engine, "connect")
+ def connect(dbapi_connection, connection_record):
+ connection_record.info['pid'] = os.getpid()
+
+ if engine.dialect.name == "sqlite":
+
+ @event.listens_for(engine, "connect")
+ def set_sqlite_pragma(dbapi_connection, connection_record):
+ cursor = dbapi_connection.cursor()
+ cursor.execute("PRAGMA foreign_keys=ON")
+ cursor.close()
+
+ # this ensures sanity in mysql when storing datetimes (not required for postgres)
+ if engine.dialect.name == "mysql":
+
+ @event.listens_for(engine, "connect")
+ def set_mysql_timezone(dbapi_connection, connection_record):
+ cursor = dbapi_connection.cursor()
+ cursor.execute("SET time_zone = '+00:00'")
+ cursor.close()
+
+ @event.listens_for(engine, "checkout")
+ def checkout(dbapi_connection, connection_record, connection_proxy):
+ pid = os.getpid()
+ if connection_record.info['pid'] != pid:
+ connection_record.connection = connection_proxy.connection = None
+ raise exc.DisconnectionError(
+ "Connection record belongs to pid {}, "
+ "attempting to check out in pid {}".format(connection_record.info['pid'], pid)
+ )
+
+ if conf.getboolean('debug', 'sqlalchemy_stats', fallback=False):
+
+ @event.listens_for(engine, "before_cursor_execute")
+ def before_cursor_execute(conn, cursor, statement, parameters, context, executemany):
+ conn.info.setdefault('query_start_time', []).append(time.perf_counter())
+
+ @event.listens_for(engine, "after_cursor_execute")
+ def after_cursor_execute(conn, cursor, statement, parameters, context, executemany):
+ total = time.perf_counter() - conn.info['query_start_time'].pop()
+ file_name = [
+ f"'{f.name}':{f.filename}:{f.lineno}"
+ for f in traceback.extract_stack()
+ if 'sqlalchemy' not in f.filename
+ ][-1]
+ stack = [f for f in traceback.extract_stack() if 'sqlalchemy' not in f.filename]
+ stack_info = ">".join([f"{f.filename.rpartition('/')[-1]}:{f.name}" for f in stack][-3:])
+ conn.info.setdefault('query_start_time', []).append(time.monotonic())
+ log.info(
+ "@SQLALCHEMY %s |$ %s |$ %s |$ %s ",
+ total,
+ file_name,
+ stack_info,
+ statement.replace("\n", " "),
+ )
diff --git a/pool/shard009/Python/0083711_boot_storage_rational.py b/pool/shard009/Python/0083711_boot_storage_rational.py
new file mode 100644
index 0000000000000000000000000000000000000000..982d3511a5227eba03fcb99540e1bb5810ef1b18
--- /dev/null
+++ b/pool/shard009/Python/0083711_boot_storage_rational.py
@@ -0,0 +1,95 @@
+# Copyright 2018 AT&T Intellectual Property. All other 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 drydock_provisioner.orchestrator.validations.validators import Validators
+
+import drydock_provisioner.error as errors
+from drydock_provisioner.orchestrator.util import SimpleBytes
+
+
+class BootStorageRational(Validators):
+ def __init__(self):
+ super().__init__('Rational Boot Storage', 'DD1001')
+
+ def run_validation(self, site_design, orchestrator=None):
+ """
+ Ensures that root volume is defined and is at least 20GB and that boot volume is at least 1 GB
+ """
+ BYTES_IN_GB = SimpleBytes.calculate_bytes('1GB')
+
+ baremetal_node_list = site_design.baremetal_nodes or []
+
+ for baremetal_node in baremetal_node_list:
+ storage_devices_list = baremetal_node.storage_devices or []
+
+ root_set = False
+
+ for storage_device in storage_devices_list:
+ partitions_list = storage_device.partitions or []
+
+ for host_partition in partitions_list:
+ if host_partition.name == 'root':
+ size = host_partition.size
+ try:
+ cal_size = SimpleBytes.calculate_bytes(size)
+ root_set = True
+ # check if size < 20GB
+ if cal_size < 20 * BYTES_IN_GB:
+ msg = (
+ 'Root volume must be > 20GB on BaremetalNode '
+ '%s' % baremetal_node.name)
+ self.report_error(
+ msg, [baremetal_node.doc_ref],
+ "Configure a larger root volume")
+ except errors.InvalidSizeFormat as e:
+ msg = (
+ 'Root volume has an invalid size format on BaremetalNode'
+ '%s.' % baremetal_node.name)
+ self.report_error(msg, [
+ baremetal_node.doc_ref
+ ], "Use a valid root volume storage specification."
+ )
+
+ # check make sure root has been defined and boot volume > 1GB
+ if root_set and host_partition.name == 'boot':
+ size = host_partition.size
+
+ try:
+ cal_size = SimpleBytes.calculate_bytes(size)
+ # check if size < 1GB
+ if cal_size < BYTES_IN_GB:
+ msg = (
+ 'Boot volume must be > 1GB on BaremetalNode '
+ '%s' % baremetal_node.name)
+ self.report_error(
+ msg, [baremetal_node.doc_ref],
+ "Configure a larger boot volume.")
+ except errors.InvalidSizeFormat as e:
+ msg = (
+ 'Boot volume has an invalid size format on BaremetalNode '
+ '%s.' % baremetal_node.name)
+ self.report_error(msg, [
+ baremetal_node.doc_ref
+ ], "Use a valid boot volume storage specification."
+ )
+ # This must be set
+ if not root_set:
+ msg = (
+ 'Root volume has to be set and must be > 20GB on BaremetalNode '
+ '%s' % baremetal_node.name)
+ self.report_error(msg, [
+ baremetal_node.doc_ref
+ ], "All nodes require a defined root volume at least 20GB in size."
+ )
+
+ return
diff --git a/pool/shard009/Python/0083715_printer_test.py b/pool/shard009/Python/0083715_printer_test.py
new file mode 100644
index 0000000000000000000000000000000000000000..ae21520009f5eb266edde55b822de7a778aeaeaf
--- /dev/null
+++ b/pool/shard009/Python/0083715_printer_test.py
@@ -0,0 +1,85 @@
+"""Unit test for Treadmill server trace printer module.
+"""
+
+from __future__ import absolute_import
+from __future__ import division
+from __future__ import print_function
+from __future__ import unicode_literals
+
+import unittest
+import io
+
+import mock
+
+from treadmill.trace.server import events
+from treadmill.trace.server import printer
+
+
+class ServerTracePrinterTest(unittest.TestCase):
+ """Test printing trace events.
+ """
+
+ def setUp(self):
+ self.trace_printer = printer.ServerTracePrinter()
+
+ @mock.patch('sys.stdout', new_callable=io.StringIO)
+ def test_server_state(self, stdout_mock):
+ """Test printing ServerState event.
+ """
+ event = events.ServerStateTraceEvent(
+ timestamp=1,
+ source='tests',
+ servername='test.xx.com',
+ state='up',
+ payload={'foo': 'bar'}
+ )
+
+ self.trace_printer.process(event)
+
+ self.assertEqual(
+ stdout_mock.getvalue(),
+ 'Thu, 01 Jan 1970 00:00:01+0000 - '
+ 'test.xx.com up\n'
+ )
+
+ @mock.patch('sys.stdout', new_callable=io.StringIO)
+ def test_server_blackout(self, stdout_mock):
+ """Test printing ServerBlackout event.
+ """
+ event = events.ServerBlackoutTraceEvent(
+ timestamp=2,
+ source='tests',
+ servername='test.xx.com',
+ payload={'foo': 'bar'}
+ )
+
+ self.trace_printer.process(event)
+
+ self.assertEqual(
+ stdout_mock.getvalue(),
+ 'Thu, 01 Jan 1970 00:00:02+0000 - '
+ 'test.xx.com blackout\n'
+ )
+
+ @mock.patch('sys.stdout', new_callable=io.StringIO)
+ def test_server_blackout_cleared(self, stdout_mock):
+ """Test printing ServerBlackoutCleared event.
+ """
+ event = events.ServerBlackoutClearedTraceEvent(
+ timestamp=3,
+ source='tests',
+ servername='test.xx.com',
+ payload={'foo': 'bar'}
+ )
+
+ self.trace_printer.process(event)
+
+ self.assertEqual(
+ stdout_mock.getvalue(),
+ 'Thu, 01 Jan 1970 00:00:03+0000 - '
+ 'test.xx.com cleared\n'
+ )
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/pool/shard009/Python/0083718_Example_2_Brittle_Failure_Theory.py b/pool/shard009/Python/0083718_Example_2_Brittle_Failure_Theory.py
new file mode 100644
index 0000000000000000000000000000000000000000..bb5a1885505caaeffac81723f283f2ad54f04760
--- /dev/null
+++ b/pool/shard009/Python/0083718_Example_2_Brittle_Failure_Theory.py
@@ -0,0 +1,121 @@
+"""
+
+Rafael Radkowski
+Iowa State University
+Jan 2017
+rafael@iastate.edu
+
+All rights reserved
+"""
+
+# Import the failure theory envelopes
+
+from ME325Common.StressCalc import *
+
+## Values, note, the values should be positive
+## And all values in kpsi
+
+#-- Material parameters
+Sut = 50.0 # kpsi
+Suc = 110.0 # kpsi
+
+#-- factor of safety
+n = 1.2
+
+#-- Load is unknowns
+
+#-- Dimensions
+#dimensions of the first beam
+r1 = 1.0 #in
+l1 = 8.0 #in
+
+# dimensions of the second beam
+r2 = 0.6 #in
+l2 = 20.0 #in
+
+
+
+
+
+
+# 1. Compute the max. normal stress
+# since the load is unknown, we describe the load as function of F.
+def sigma_x(F, l, d):
+ return (F*l*32)/(math.pi * d**3)
+
+# 2. Compute the max. shear stress
+def tau_xz(T,d):
+ return (T * 16)/(math.pi * d**3)
+
+print sigma_x(1,l1,r1*2.0)
+print tau_xz(l2,r1*2.0)
+
+# 3. Compute the principle stresses as a factor of F
+[s1, s2, a] = PrincipleStress([sigma_x(1,l1,r1*2.0)], [tau_xz(l2,r1*2.0)] ) # x F
+print "Principle stresses for s1:", s1, "* F [kpsi] and \ts2: ", s2 ,"* F [kpsi]"
+
+
+# 4. Compute the missing forces
+F1 = 0.0
+F2 = 0.0
+if s1 > 0.0:
+ F1 = Sut * 1000.0 / (n * s1)
+else:
+ F1 = -Suc * 1000.0 / (n * s1)
+
+
+if s2 > 0.0:
+ F2 = Sut * 1000.0 / (n * s2)
+else:
+ F2 = -Suc * 1000.0 / (n * s2)
+
+# we proceed with the smaller one since the material would fail at the lower falue first.
+F = min(F1, F2)
+print "The force is F = ", F, " lbf"
+
+#-----------------------------------------------------------------
+# For Modified-Mohr and MNST Theory
+
+
+s1_f = s1 * F / 1000.0
+s3_f = s2 * F / 1000.0
+print "The final stress is sigma_1 = ", s1_f, "kpsi, and sigma_3 =", s3_f, 'kpsi'
+
+
+
+#-----------------------------------------------------------------
+# For Coulumb-Mohr Theory
+
+n_cm = brittle_coulumb_fos(s1_f, s3_f, Sut, Suc)
+print "Coulumb-Mohr failure theory factor of safety: ", n_cm
+
+print "---------\nCorrecting for Coulumb Mohr theory"
+F_cm = 1.0/( n *( (s1/Sut) - (s2/Suc) ) ) * 1000.0 # from psi to kpsi
+print "Max. force accoriding to Coulumb-Mohr theory: F=", F_cm, " lbf"
+
+s1_cm = s1 * F_cm / 1000.0
+s3_cm = s2 * F_cm / 1000.0
+print "The final stresses using CM theory sigma_1 = ", s1_cm, "kpsi, and sigma_3 =", s3_cm, 'kpsi'
+
+#######
+# PLOT
+
+fig = plt.figure(figsize=(8, 8))
+
+# Plot the stress point
+pl_s, = plt.plot([s1_f], [s3_f], 'ro')
+pl_s2, = plt.plot([s1_cm], [s3_cm], 'bo')
+
+# Plot the failure envelopes
+plotModMohrFailureTheory(Sut, Suc)
+plotCoulumbMohrFailureTheory(Sut, Suc)
+plotMaxNormalFailureTheory(Sut, Suc)
+
+
+# Axis
+plt.axis([-120, 120, -120, 120])
+
+plt.ylabel('sigma_3 [kpsi]')
+plt.xlabel('sigma_1 [kpsi]')
+plt.grid()
+plt.show()
\ No newline at end of file
diff --git a/pool/shard009/Python/0083724_test_server_profiling.py b/pool/shard009/Python/0083724_test_server_profiling.py
new file mode 100644
index 0000000000000000000000000000000000000000..7d157a3e41895c64e2781a503bea7ec3d94f7368
--- /dev/null
+++ b/pool/shard009/Python/0083724_test_server_profiling.py
@@ -0,0 +1,69 @@
+#!/usr/bin/env python
+
+# 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.
+import mxnet as mx
+import json
+
+key = '99'
+shape = (1200, 1200) # bigger than MXNET_KVSTORE_BIGARRAY_BOUND
+kv = mx.kv.create('dist_sync')
+
+def init_kv():
+ # init kv dns keys
+ kv.init(key, mx.nd.ones(shape))
+ kv.set_optimizer(mx.optimizer.create('sgd'))
+ return kv, kv.rank, kv.num_workers
+
+def test_sync_push_pull():
+ kv, my_rank, nworker = init_kv()
+ def check_default_keys(kv, my_rank):
+ nrepeat = 10
+ # checks pull after push in loop, because behavior during
+ # consecutive pushes doesn't offer any guarantees
+ for i in range(nrepeat):
+ kv.push(key, mx.nd.ones(shape, dtype='float32') * (my_rank+1))
+ val = mx.nd.zeros(shape, dtype='float32')
+ kv.pull(key, out=val)
+ mx.nd.waitall()
+ check_default_keys(kv, my_rank)
+
+if __name__ == "__main__":
+ server_filename_suffix = 'test_profile_server.json'
+ worker_filename_suffix = 'test_profile_worker.json'
+ mx.profiler.set_config(filename=server_filename_suffix, profile_all=True, profile_process='server')
+ mx.profiler.set_config(filename='rank' + str(kv.rank) + '_' + worker_filename_suffix, profile_all=True, profile_process='worker')
+ mx.profiler.set_state(state='run', profile_process='server')
+ mx.profiler.set_state(state='run', profile_process='worker')
+ test_sync_push_pull()
+ mx.profiler.set_state(state='stop', profile_process='server')
+ mx.profiler.set_state(state='stop', profile_process='worker')
+
+ import glob, os
+
+ # will only work when launcher mode is local, as used for integration test
+ if kv.rank == 0:
+ for rank in range(kv.num_workers):
+ for suffix in [worker_filename_suffix, server_filename_suffix]:
+ # throws value error if file is not proper json
+ filename = 'rank' + str(rank) + '_' + suffix
+ print(glob.glob('*'), os.getcwd())
+ with open(filename, 'r') as f:
+ j = json.load(f)
+
+
+
diff --git a/pool/shard009/Python/0083731_admin.py b/pool/shard009/Python/0083731_admin.py
new file mode 100644
index 0000000000000000000000000000000000000000..f2c40662665690a3bce8cc07883304f8d5a88d54
--- /dev/null
+++ b/pool/shard009/Python/0083731_admin.py
@@ -0,0 +1,190 @@
+# -*- coding: utf-8 -*-
+"""
+Admin site configuration for third party authentication
+"""
+from config_models.admin import KeyedConfigurationModelAdmin
+from django import forms
+from django.contrib import admin
+from django.core.urlresolvers import reverse
+
+from third_party_auth.provider import Registry
+
+from .models import (
+ _PSA_OAUTH2_BACKENDS,
+ _PSA_SAML_BACKENDS,
+ LTIProviderConfig,
+ OAuth2ProviderConfig,
+ ProviderApiPermissions,
+ SAMLConfiguration,
+ SAMLProviderConfig,
+ SAMLProviderData
+)
+from .tasks import fetch_saml_metadata
+from openedx.core.djangolib.markup import HTML
+
+
+class OAuth2ProviderConfigForm(forms.ModelForm):
+ """ Django Admin form class for OAuth2ProviderConfig """
+ backend_name = forms.ChoiceField(choices=((name, name) for name in _PSA_OAUTH2_BACKENDS))
+
+
+class OAuth2ProviderConfigAdmin(KeyedConfigurationModelAdmin):
+ """ Django Admin class for OAuth2ProviderConfig """
+ form = OAuth2ProviderConfigForm
+
+ def get_list_display(self, request):
+ """ Don't show every single field in the admin change list """
+ return (
+ 'name', 'enabled', 'provider_slug', 'site', 'backend_name', 'secondary', 'skip_registration_form',
+ 'skip_email_verification', 'change_date', 'changed_by', 'edit_link',
+ )
+
+admin.site.register(OAuth2ProviderConfig, OAuth2ProviderConfigAdmin)
+
+
+class SAMLProviderConfigForm(forms.ModelForm):
+ """ Django Admin form class for SAMLProviderConfig """
+ backend_name = forms.ChoiceField(choices=((name, name) for name in _PSA_SAML_BACKENDS))
+
+
+class SAMLProviderConfigAdmin(KeyedConfigurationModelAdmin):
+ """ Django Admin class for SAMLProviderConfig """
+ form = SAMLProviderConfigForm
+
+ def get_list_display(self, request):
+ """ Don't show every single field in the admin change list """
+ return (
+ 'name_with_update_link', 'enabled', 'site', 'entity_id', 'metadata_source',
+ 'has_data', 'mode', 'change_date', 'changed_by',
+ )
+
+ list_display_links = None
+
+ def name_with_update_link(self, instance):
+ """
+ Record name with link for the change view.
+ """
+ if not instance.is_active:
+ return instance.name
+
+ update_url = reverse('admin:{}_{}_add'.format(self.model._meta.app_label, self.model._meta.model_name))
+ update_url += '?source={}'.format(instance.pk)
+ return HTML(u'{} ').format(update_url, instance.name)
+
+ name_with_update_link.allow_tags = True
+ name_with_update_link.short_description = u'Name'
+
+ def has_data(self, inst):
+ """ Do we have cached metadata for this SAML provider? """
+ if not inst.is_active:
+ return None # N/A
+ data = SAMLProviderData.current(inst.entity_id)
+ return bool(data and data.is_valid())
+ has_data.short_description = u'Metadata Ready'
+ has_data.boolean = True
+
+ def mode(self, inst):
+ """ Indicate if debug_mode is enabled or not"""
+ if inst.debug_mode:
+ return 'Debug '
+ return "Normal"
+ mode.allow_tags = True
+
+ def save_model(self, request, obj, form, change):
+ """
+ Post save: Queue an asynchronous metadata fetch to update SAMLProviderData.
+ We only want to do this for manual edits done using the admin interface.
+
+ Note: This only works if the celery worker and the app worker are using the
+ same 'configuration' cache.
+ """
+ super(SAMLProviderConfigAdmin, self).save_model(request, obj, form, change)
+ fetch_saml_metadata.apply_async((), countdown=2)
+
+admin.site.register(SAMLProviderConfig, SAMLProviderConfigAdmin)
+
+
+class SAMLConfigurationAdmin(KeyedConfigurationModelAdmin):
+ """ Django Admin class for SAMLConfiguration """
+ def get_list_display(self, request):
+ """ Shorten the public/private keys in the change view """
+ return (
+ 'site', 'change_date', 'changed_by', 'enabled', 'entity_id',
+ 'org_info_str', 'key_summary', 'edit_link',
+ )
+
+ def key_summary(self, inst):
+ """ Short summary of the key pairs configured """
+ public_key = inst.get_setting('SP_PUBLIC_CERT')
+ private_key = inst.get_setting('SP_PRIVATE_KEY')
+ if not public_key or not private_key:
+ return u'Key pair incomplete/missing '
+ pub1, pub2 = public_key[0:10], public_key[-10:]
+ priv1, priv2 = private_key[0:10], private_key[-10:]
+ return u'Public: {}…{} Private: {}…{}'.format(pub1, pub2, priv1, priv2)
+ key_summary.allow_tags = True
+
+admin.site.register(SAMLConfiguration, SAMLConfigurationAdmin)
+
+
+class SAMLProviderDataAdmin(admin.ModelAdmin):
+ """ Django Admin class for SAMLProviderData (Read Only) """
+ list_display = ('entity_id', 'is_valid', 'fetched_at', 'expires_at', 'sso_url')
+ readonly_fields = ('is_valid', )
+
+ def get_readonly_fields(self, request, obj=None):
+ if obj: # editing an existing object
+ return [field.name for field in self.model._meta.get_fields()] # pylint: disable=protected-access
+ return self.readonly_fields
+
+
+admin.site.register(SAMLProviderData, SAMLProviderDataAdmin)
+
+
+class LTIProviderConfigAdmin(KeyedConfigurationModelAdmin):
+ """ Django Admin class for LTIProviderConfig """
+
+ exclude = (
+ 'icon_class',
+ 'icon_image',
+ 'secondary',
+ )
+
+ def get_list_display(self, request):
+ """ Don't show every single field in the admin change list """
+ return (
+ 'name',
+ 'enabled',
+ 'site',
+ 'lti_consumer_key',
+ 'lti_max_timestamp_age',
+ 'change_date',
+ 'changed_by',
+ 'edit_link',
+ )
+
+admin.site.register(LTIProviderConfig, LTIProviderConfigAdmin)
+
+
+class ApiPermissionsAdminForm(forms.ModelForm):
+ """ Django admin form for ApiPermissions model """
+ class Meta(object):
+ model = ProviderApiPermissions
+ fields = ['client', 'provider_id']
+
+ provider_id = forms.ChoiceField(choices=[], required=True)
+
+ def __init__(self, *args, **kwargs):
+ super(ApiPermissionsAdminForm, self).__init__(*args, **kwargs)
+ self.fields['provider_id'].choices = (
+ (provider.provider_id, "{} ({})".format(provider.name, provider.provider_id))
+ for provider in Registry.enabled()
+ )
+
+
+class ApiPermissionsAdmin(admin.ModelAdmin):
+ """ Django Admin class for ApiPermissions """
+ list_display = ('client', 'provider_id')
+ form = ApiPermissionsAdminForm
+
+admin.site.register(ProviderApiPermissions, ApiPermissionsAdmin)
diff --git a/pool/shard009/Python/0083733_waiters.py b/pool/shard009/Python/0083733_waiters.py
new file mode 100644
index 0000000000000000000000000000000000000000..563a479c7a17484899dd36df410066a8e0477063
--- /dev/null
+++ b/pool/shard009/Python/0083733_waiters.py
@@ -0,0 +1,216 @@
+# -*- coding: utf-8 -*-
+
+# Copyright (C) 2015 Yahoo! 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.
+
+try:
+ from contextlib import ExitStack
+except ImportError:
+ from contextlib2 import ExitStack
+
+import collections
+import contextlib
+
+from concurrent import futures
+from concurrent.futures import _base
+import six
+
+import futurist
+from futurist import _utils
+
+try:
+ from eventlet.green import threading as greenthreading
+except ImportError:
+ greenthreading = None
+
+
+#: Named tuple returned from ``wait_for*`` calls.
+DoneAndNotDoneFutures = collections.namedtuple(
+ 'DoneAndNotDoneFutures', 'done not_done')
+
+_DONE_STATES = frozenset([
+ _base.CANCELLED_AND_NOTIFIED,
+ _base.FINISHED,
+])
+
+
+@contextlib.contextmanager
+def _acquire_and_release_futures(fs):
+ # Do this to ensure that we always get the futures in the same order (aka
+ # always acquire the conditions in the same order, no matter what; a way
+ # to avoid dead-lock).
+ fs = sorted(fs, key=id)
+ with ExitStack() as stack:
+ for fut in fs:
+ stack.enter_context(fut._condition)
+ yield
+
+
+def _ensure_eventlet(func):
+ """Decorator that verifies we have the needed eventlet components."""
+
+ @six.wraps(func)
+ def wrapper(*args, **kwargs):
+ if not _utils.EVENTLET_AVAILABLE or greenthreading is None:
+ raise RuntimeError('Eventlet is needed to wait on green futures')
+ return func(*args, **kwargs)
+
+ return wrapper
+
+
+def _wait_for(fs, no_green_return_when, on_all_green_cb,
+ caller_name, timeout=None):
+ green_fs = sum(1 for f in fs if isinstance(f, futurist.GreenFuture))
+ if not green_fs:
+ done, not_done = futures.wait(fs, timeout=timeout,
+ return_when=no_green_return_when)
+ return DoneAndNotDoneFutures(done, not_done)
+ else:
+ non_green_fs = len(fs) - green_fs
+ if non_green_fs:
+ raise RuntimeError("Can not wait on %s green futures and %s"
+ " non-green futures in the same"
+ " `%s` call" % (green_fs, non_green_fs,
+ caller_name))
+ else:
+ return on_all_green_cb(fs, timeout=timeout)
+
+
+def wait_for_all(fs, timeout=None):
+ """Wait for all of the futures to complete.
+
+ Works correctly with both green and non-green futures (but not both
+ together, since this can't be guaranteed to avoid dead-lock due to how
+ the waiting implementations are different when green threads are being
+ used).
+
+ Returns pair (done futures, not done futures).
+ """
+ return _wait_for(fs, futures.ALL_COMPLETED, _wait_for_all_green,
+ 'wait_for_all', timeout=timeout)
+
+
+def wait_for_any(fs, timeout=None):
+ """Wait for one (**any**) of the futures to complete.
+
+ Works correctly with both green and non-green futures (but not both
+ together, since this can't be guaranteed to avoid dead-lock due to how
+ the waiting implementations are different when green threads are being
+ used).
+
+ Returns pair (done futures, not done futures).
+ """
+ return _wait_for(fs, futures.FIRST_COMPLETED, _wait_for_any_green,
+ 'wait_for_any', timeout=timeout)
+
+
+class _AllGreenWaiter(object):
+ """Provides the event that ``_wait_for_all_green`` blocks on."""
+
+ def __init__(self, pending):
+ self.event = greenthreading.Event()
+ self.lock = greenthreading.Lock()
+ self.pending = pending
+
+ def _decrement_pending(self):
+ with self.lock:
+ self.pending -= 1
+ if self.pending <= 0:
+ self.event.set()
+
+ def add_result(self, future):
+ self._decrement_pending()
+
+ def add_exception(self, future):
+ self._decrement_pending()
+
+ def add_cancelled(self, future):
+ self._decrement_pending()
+
+
+class _AnyGreenWaiter(object):
+ """Provides the event that ``_wait_for_any_green`` blocks on."""
+
+ def __init__(self):
+ self.event = greenthreading.Event()
+
+ def add_result(self, future):
+ self.event.set()
+
+ def add_exception(self, future):
+ self.event.set()
+
+ def add_cancelled(self, future):
+ self.event.set()
+
+
+def _partition_futures(fs):
+ done = set()
+ not_done = set()
+ for f in fs:
+ if f._state in _DONE_STATES:
+ done.add(f)
+ else:
+ not_done.add(f)
+ return done, not_done
+
+
+def _create_and_install_waiters(fs, waiter_cls, *args, **kwargs):
+ waiter = waiter_cls(*args, **kwargs)
+ for f in fs:
+ f._waiters.append(waiter)
+ return waiter
+
+
+@_ensure_eventlet
+def _wait_for_all_green(fs, timeout=None):
+ if not fs:
+ return DoneAndNotDoneFutures(set(), set())
+
+ with _acquire_and_release_futures(fs):
+ done, not_done = _partition_futures(fs)
+ if len(done) == len(fs):
+ return DoneAndNotDoneFutures(done, not_done)
+ waiter = _create_and_install_waiters(not_done,
+ _AllGreenWaiter,
+ len(not_done))
+ waiter.event.wait(timeout)
+ for f in not_done:
+ with f._condition:
+ f._waiters.remove(waiter)
+
+ with _acquire_and_release_futures(fs):
+ done, not_done = _partition_futures(fs)
+ return DoneAndNotDoneFutures(done, not_done)
+
+
+@_ensure_eventlet
+def _wait_for_any_green(fs, timeout=None):
+ if not fs:
+ return DoneAndNotDoneFutures(set(), set())
+
+ with _acquire_and_release_futures(fs):
+ done, not_done = _partition_futures(fs)
+ if done:
+ return DoneAndNotDoneFutures(done, not_done)
+ waiter = _create_and_install_waiters(fs, _AnyGreenWaiter)
+
+ waiter.event.wait(timeout)
+ for f in fs:
+ with f._condition:
+ f._waiters.remove(waiter)
+
+ with _acquire_and_release_futures(fs):
+ done, not_done = _partition_futures(fs)
+ return DoneAndNotDoneFutures(done, not_done)
diff --git a/pool/shard009/Python/0083734_test_time_zone_utils.py b/pool/shard009/Python/0083734_test_time_zone_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..cfab630cc0091b162a928856e4231d52680d31bd
--- /dev/null
+++ b/pool/shard009/Python/0083734_test_time_zone_utils.py
@@ -0,0 +1,80 @@
+"""Tests covering time zone utilities."""
+
+
+from django.test import TestCase
+from freezegun import freeze_time
+from pytz import timezone
+
+from openedx.core.lib.time_zone_utils import get_display_time_zone, get_time_zone_abbr, get_time_zone_offset
+from common.djangoapps.student.tests.factories import UserFactory
+
+
+class TestTimeZoneUtils(TestCase):
+ """
+ Tests the time zone utilities
+ """
+ def setUp(self):
+ """
+ Sets up user for testing with time zone utils.
+ """
+ super(TestTimeZoneUtils, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
+
+ self.user = UserFactory.build()
+ self.user.save()
+
+ def _display_time_zone_helper(self, time_zone_string):
+ """
+ Helper function to return all info from get_display_time_zone()
+ """
+ tz_str = get_display_time_zone(time_zone_string)
+ time_zone = timezone(time_zone_string)
+ tz_abbr = get_time_zone_abbr(time_zone)
+ tz_offset = get_time_zone_offset(time_zone)
+
+ return {'str': tz_str, 'abbr': tz_abbr, 'offset': tz_offset}
+
+ def _assert_time_zone_info_equal(self, display_tz_info, expected_name, expected_abbr, expected_offset):
+ """
+ Asserts that all display_tz_info is equal to the expected inputs
+ """
+ assert display_tz_info['str'] == '{name} ({abbr}, UTC{offset})'.format(
+ name=expected_name, abbr=expected_abbr, offset=expected_offset
+ )
+ assert display_tz_info['abbr'] == expected_abbr
+ assert display_tz_info['offset'] == expected_offset
+
+ def test_display_time_zone_without_dst(self):
+ """
+ Test to ensure get_display_time_zone() returns full display string when no kwargs specified
+ and returns just abbreviation or offset when specified
+ """
+ with freeze_time("2015-02-09"):
+ tz_info = self._display_time_zone_helper('America/Los_Angeles')
+ self._assert_time_zone_info_equal(tz_info, 'America/Los Angeles', 'PST', '-0800')
+
+ def test_display_time_zone_with_dst(self):
+ """
+ Test to ensure get_display_time_zone() returns modified abbreviations and
+ offsets during daylight savings time.
+ """
+ with freeze_time("2015-04-02"):
+ tz_info = self._display_time_zone_helper('America/Los_Angeles')
+ self._assert_time_zone_info_equal(tz_info, 'America/Los Angeles', 'PDT', '-0700')
+
+ def test_display_time_zone_ambiguous_before(self):
+ """
+ Test to ensure get_display_time_zone() returns correct abbreviations and offsets
+ during ambiguous time periods (e.g. when DST is about to start/end) before the change
+ """
+ with freeze_time("2015-11-01 08:59:00"):
+ tz_info = self._display_time_zone_helper('America/Los_Angeles')
+ self._assert_time_zone_info_equal(tz_info, 'America/Los Angeles', 'PDT', '-0700')
+
+ def test_display_time_zone_ambiguous_after(self):
+ """
+ Test to ensure get_display_time_zone() returns correct abbreviations and offsets
+ during ambiguous time periods (e.g. when DST is about to start/end) after the change
+ """
+ with freeze_time("2015-11-01 09:00:00"):
+ tz_info = self._display_time_zone_helper('America/Los_Angeles')
+ self._assert_time_zone_info_equal(tz_info, 'America/Los Angeles', 'PST', '-0800')
diff --git a/pool/shard009/Python/0083738_fields.py b/pool/shard009/Python/0083738_fields.py
new file mode 100644
index 0000000000000000000000000000000000000000..5d82227cd826c4f6c16b6dc3535a653801bfaf0d
--- /dev/null
+++ b/pool/shard009/Python/0083738_fields.py
@@ -0,0 +1,73 @@
+# -*- coding: utf-8 -*-
+#
+# Atizo - The Open Innovation Platform
+# http://www.atizo.com/
+#
+# Copyright (c) 2008-2010 Atizo AG. All rights reserved.
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+#
+from __future__ import unicode_literals
+from django.forms.util import flatatt
+from django.forms.widgets import Select
+from django.utils.safestring import mark_safe
+from django import forms
+
+from widgets import Html5DateTimeInput
+
+class InputLabelWidget(Select):
+
+ def render(self, name, value, attrs=None, choices=()):
+ if value is None: value = ''
+
+ final_attrs = self.build_attrs(attrs, name=name)
+ label = final_attrs.get('label','')
+ if label:
+ del final_attrs['label']
+
+ output = ['' % flatatt(final_attrs)]
+ if label:
+ output.append(self.render_option([], '', '- %s -' % label))
+
+ options = self.render_options(choices, [value])
+ if options:
+ output.append(options)
+ output.append(' ')
+
+ return mark_safe('\n'.join(output))
+
+class LabelCharField(forms.CharField):
+ widget = InputLabelWidget
+
+ def __init__(self, *args, **kwargs):
+ super(LabelCharField, self).__init__(*args, **kwargs)
+ self.label = kwargs.get('label', '')
+
+ def widget_attrs(self, widget):
+ if self.label:
+ return {'label': '%s' % self.label}
+ return {}
+
+class LabelIntegerField(forms.IntegerField):
+ widget = InputLabelWidget
+
+ def __init__(self, *args, **kwargs):
+ super(LabelIntegerField, self).__init__(*args, **kwargs)
+ self.label = kwargs.get('label', '')
+
+ def widget_attrs(self, widget):
+ if self.label:
+ return {'label': '%s' % self.label}
+ return {}
diff --git a/pool/shard009/Python/0083739_setup.py b/pool/shard009/Python/0083739_setup.py
new file mode 100644
index 0000000000000000000000000000000000000000..6c1831645667273cbf5a9a6afadf8fde595d5de1
--- /dev/null
+++ b/pool/shard009/Python/0083739_setup.py
@@ -0,0 +1,85 @@
+import os
+import re
+import sys
+
+from setuptools import setup
+
+execfile(os.path.join("openobject", "release.py"))
+
+version_dash_incompatible = False
+if 'bdist_rpm' in sys.argv:
+ version_dash_incompatible = True
+try:
+ import py2exe
+ from py2exe_utils import opts
+ version_dash_incompatible = True
+except ImportError:
+ opts = {}
+if version_dash_incompatible:
+ version = version.split('-')[0]
+
+FILE_PATTERNS = \
+ r'.+\.(py|cfg|po|pot|mo|txt|rst|gif|png|jpg|ico|mako|html|js|css|htc|swf)$'
+def find_data_files(source, patterns=FILE_PATTERNS):
+ file_matcher = re.compile(patterns, re.I)
+ out = []
+ for base, _, files in os.walk(source):
+ cur_files = []
+ for f in files:
+ if file_matcher.match(f):
+ cur_files.append(os.path.join(base, f))
+ if cur_files:
+ out.append(
+ (base, cur_files))
+
+ return out
+
+setup(
+ name=name,
+ version=version,
+ description=description,
+ long_description=long_description,
+ author=author,
+ author_email=author_email,
+ url=url,
+ download_url=download_url,
+ license=license,
+ install_requires=[
+ "CherryPy == 3.1.2",
+ "Mako >= 0.2.4",
+ "Babel >= 0.9.5",
+ "FormEncode >= 1.2.2",
+ "simplejson >= 2.0.9",
+ "python-dateutil >= 1.4.1",
+ "pytz >= 2009j"
+ ],
+ zip_safe=False,
+ packages=[
+ 'openobject',
+ 'openobject.admin',
+ 'openobject.admin.i18n',
+ 'openobject.controllers',
+ 'openobject.i18n',
+ 'openobject.test',
+ 'openobject.tools',
+ 'openobject.widgets'
+ ],
+ classifiers=[
+ 'Development Status :: 5 - Production/Stable',
+ 'Operating System :: OS Independent',
+ 'Programming Language :: Python',
+ 'Environment :: Web Environment',
+ 'Topic :: Office/Business :: Financial',
+ ],
+ scripts=['scripts/openerp-web'],
+ data_files=(find_data_files('addons/openerp')
+ + find_data_files('addons/view_calendar')
+ + find_data_files('addons/view_diagram')
+ + find_data_files('addons/view_graph')
+ + find_data_files('addons/widget_ckeditor')
+ + find_data_files('doc', patterns='')
+ + find_data_files('openobject', patterns=r'.+\.(cfg|css|js|mako|gif|png|jpg|ico)')
+ + opts.pop('data_files', [])
+ ),
+ **opts
+)
diff --git a/pool/shard009/Python/0083743_collection.py b/pool/shard009/Python/0083743_collection.py
new file mode 100644
index 0000000000000000000000000000000000000000..6ec298791e03203b799c18a4d1d2ef6480307cc5
--- /dev/null
+++ b/pool/shard009/Python/0083743_collection.py
@@ -0,0 +1,48 @@
+# Copyright 2013 Red Hat, 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 pecan
+from wsme import types as wtypes
+
+from ironic.api.controllers import base
+from ironic.api.controllers import link
+
+
+class Collection(base.APIBase):
+
+ next = wtypes.text
+ "A link to retrieve the next subset of the collection"
+
+ @property
+ def collection(self):
+ return getattr(self, self._type)
+
+ def has_next(self, limit):
+ """Return whether collection has more items."""
+ return len(self.collection) and len(self.collection) == limit
+
+ def get_next(self, limit, url=None, **kwargs):
+ """Return a link to the next subset of the collection."""
+ if not self.has_next(limit):
+ return wtypes.Unset
+
+ resource_url = url or self._type
+ q_args = ''.join(['%s=%s&' % (key, kwargs[key]) for key in kwargs])
+ next_args = '?%(args)slimit=%(limit)d&marker=%(marker)s' % {
+ 'args': q_args, 'limit': limit,
+ 'marker': self.collection[-1].uuid}
+
+ return link.Link.make_link('next', pecan.request.host_url,
+ resource_url, next_args).href
diff --git a/pool/shard009/Python/0083747_just-playing-module3.py b/pool/shard009/Python/0083747_just-playing-module3.py
new file mode 100644
index 0000000000000000000000000000000000000000..66dde308c8af212248fe7403c1a75b6e9f5ef333
--- /dev/null
+++ b/pool/shard009/Python/0083747_just-playing-module3.py
@@ -0,0 +1,76 @@
+# -*- coding: utf-8 -*-
+"""
+Created on Fri Nov 4 13:18:57 2016
+
+Module 3 on DAT210x course scripts
+
+More info on matplotlib histogram:
+http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.hist
+
+@author: Arthur Gouveia
+"""
+import pandas as pd
+import matplotlib as mpl
+from mpl_toolkits.mplot3d import Axes3D
+from pandas.tools.plotting import parallel_coordinates
+from sklearn.datasets import load_iris
+
+MENU = '''
+1: Single Histogram
+2: Multiple Histogram
+3: Scatter plot
+4: 3D Scatter plot
+5: Parallel Plot
+
+Enter your choice:
+'''
+
+
+def histplot(data, **kwargs):
+ data.plot.hist(**kwargs)
+
+
+def scatter2D(data, x, y, **kwargs):
+ data.plot.scatter(x=x, y=y, **kwargs)
+
+
+def scatter3D(data, **kwargs):
+ fig = mpl.pyplot.figure()
+ ax = fig.add_subplot(111, projection='3d')
+ ax.set_xlabel('Final Grade')
+ ax.set_ylabel('First Grade')
+ ax.set_zlabel('Daily Alcohol')
+
+ ax.scatter(data[0], data[1],
+ data[2], **kwargs)
+ mpl.pyplot.show()
+
+
+def menu():
+ return input(MENU)
+
+
+if __name__ == '__main__':
+ mpl.style.use('ggplot')
+ mpl.cm.cmapname = 'gray'
+
+ student_dataset = pd.read_csv("Datasets/students.data", index_col=0)
+ data = load_iris()
+ iris = pd.DataFrame(data.data, columns=data.feature_names)
+ iris['target_names'] = [data.target_names[i] for i in data.target]
+
+ choice = menu()
+
+ if choice == '1':
+ histplot(student_dataset.G3, alpha=0.5, normed=True)
+ elif choice == '2':
+ histplot(student_dataset[['G3', 'G2', 'G1']], alpha=0.5)
+ elif choice == '3':
+ scatter2D(student_dataset[['G1', 'G3']], x='G1', y='G3')
+ elif choice == '4':
+ scatter3D([student_dataset.G1, student_dataset.G3,
+ student_dataset['Dalc']], c='r', marker='o')
+ elif choice == '5':
+ parallel_coordinates(iris, 'target_names')
+ else:
+ print('Invalid option. Try again')
diff --git a/pool/shard009/Python/0083751_find_recursionlimit.py b/pool/shard009/Python/0083751_find_recursionlimit.py
new file mode 100644
index 0000000000000000000000000000000000000000..b2842a62efdbd682ce5f6a4f913d19d9823c32aa
--- /dev/null
+++ b/pool/shard009/Python/0083751_find_recursionlimit.py
@@ -0,0 +1,128 @@
+#! /usr/bin/env python3
+"""Find the maximum recursion limit that prevents interpreter termination.
+
+This script finds the maximum safe recursion limit on a particular
+platform. If you need to change the recursion limit on your system,
+this script will tell you a safe upper bound. To use the new limit,
+call sys.setrecursionlimit().
+
+This module implements several ways to create infinite recursion in
+Python. Different implementations end up pushing different numbers of
+C stack frames, depending on how many calls through Python's abstract
+C API occur.
+
+After each round of tests, it prints a message:
+"Limit of NNNN is fine".
+
+The highest printed value of "NNNN" is therefore the highest potentially
+safe limit for your system (which depends on the OS, architecture, but also
+the compilation flags). Please note that it is practically impossible to
+test all possible recursion paths in the interpreter, so the results of
+this test should not be trusted blindly -- although they give a good hint
+of which values are reasonable.
+
+NOTE: When the C stack space allocated by your system is exceeded due
+to excessive recursion, exact behaviour depends on the platform, although
+the interpreter will always fail in a likely brutal way: either a
+segmentation fault, a MemoryError, or just a silent abort.
+
+NB: A program that does not use __methods__ can set a higher limit.
+"""
+
+import sys
+import itertools
+
+class RecursiveBlowup1:
+ def __init__(self):
+ self.__init__()
+
+def test_init():
+ return RecursiveBlowup1()
+
+class RecursiveBlowup2:
+ def __repr__(self):
+ return repr(self)
+
+def test_repr():
+ return repr(RecursiveBlowup2())
+
+class RecursiveBlowup4:
+ def __add__(self, x):
+ return x + self
+
+def test_add():
+ return RecursiveBlowup4() + RecursiveBlowup4()
+
+class RecursiveBlowup5:
+ def __getattr__(self, attr):
+ return getattr(self, attr)
+
+def test_getattr():
+ return RecursiveBlowup5().attr
+
+class RecursiveBlowup6:
+ def __getitem__(self, item):
+ return self[item - 2] + self[item - 1]
+
+def test_getitem():
+ return RecursiveBlowup6()[5]
+
+def test_recurse():
+ return test_recurse()
+
+def test_cpickle(_cache={}):
+ import io
+ try:
+ import _pickle
+ except ImportError:
+ print("cannot import _pickle, skipped!")
+ return
+ k, l = None, None
+ for n in itertools.count():
+ try:
+ l = _cache[n]
+ continue # Already tried and it works, let's save some time
+ except KeyError:
+ for i in range(100):
+ l = [k, l]
+ k = {i: l}
+ _pickle.Pickler(io.BytesIO(), protocol=-1).dump(l)
+ _cache[n] = l
+
+def test_compiler_recursion():
+ # The compiler uses a scaling factor to support additional levels
+ # of recursion. This is a sanity check of that scaling to ensure
+ # it still raises RecursionError even at higher recursion limits
+ compile("()" * (10 * sys.getrecursionlimit()), "", "single")
+
+def check_limit(n, test_func_name):
+ sys.setrecursionlimit(n)
+ if test_func_name.startswith("test_"):
+ print(test_func_name[5:])
+ else:
+ print(test_func_name)
+ test_func = globals()[test_func_name]
+ try:
+ test_func()
+ # AttributeError can be raised because of the way e.g. PyDict_GetItem()
+ # silences all exceptions and returns NULL, which is usually interpreted
+ # as "missing attribute".
+ except (RecursionError, AttributeError):
+ pass
+ else:
+ print("Yikes!")
+
+if __name__ == '__main__':
+
+ limit = 1000
+ while 1:
+ check_limit(limit, "test_recurse")
+ check_limit(limit, "test_add")
+ check_limit(limit, "test_repr")
+ check_limit(limit, "test_init")
+ check_limit(limit, "test_getattr")
+ check_limit(limit, "test_getitem")
+ check_limit(limit, "test_cpickle")
+ check_limit(limit, "test_compiler_recursion")
+ print("Limit of %d is fine" % limit)
+ limit = limit + 100
diff --git a/pool/shard009/Python/0083760_dumper.py b/pool/shard009/Python/0083760_dumper.py
new file mode 100644
index 0000000000000000000000000000000000000000..fd178f42c6260be76e08a433bd980958b82c76d8
--- /dev/null
+++ b/pool/shard009/Python/0083760_dumper.py
@@ -0,0 +1,72 @@
+# -*- coding: utf-8 -*-
+import os
+
+
+class FastaDumper(object):
+ """
+ Class for dumping fasta data to file.
+
+ Create a files name composed from contig name followed by
+ the index of this file among all files for the contig.
+
+ Example: 5th nucleotide of Chromosome will be placed in a file called "Chromosome_0",
+ 10005th will be placed in a file called "Chromosome_1" file etc.
+ """
+ BUFFER_SIZE = 10000
+
+ def __init__(self, current_folder):
+ self.current_folder = current_folder
+ self.prefix = None
+ self.buffer = ''
+ self.index = 0
+
+ def _dump(self):
+ """
+ Dump buffer to the file in current folder named with ``index`` value and
+ increment ``index`` value by 1.
+
+ If buffer is empty does nothing,
+ If buffer is bigger then self.BUFFER_SIZE, dump only self.BUFFER_SIZE.
+ """
+ if not self.buffer or not self.prefix:
+ return
+ file_name = '%s_%s' % (self.prefix, self.index)
+ with open(os.path.join(self.current_folder, file_name), 'w') as f:
+ f.write(self.buffer[:self.BUFFER_SIZE])
+ self.index += 1
+ self.buffer = self.buffer[self.BUFFER_SIZE:]
+
+ def flush(self):
+ """
+ Save all data from buffer to file.
+
+ :return: None
+ """
+ if self.prefix:
+ self._dump()
+ self.index = 0
+ self.prefix = None
+
+ def set(self, prefix):
+ """
+ Flush current data and set new suffix.
+
+ :param prefix: current contig name
+ :type prefix: str
+ :return: None
+ """
+ self.flush()
+ self.prefix = prefix
+
+ def add(self, text):
+ """
+ Add chunk of data to the current folder.
+ If total length of all chunks in buffer is greater than self.BUFFER_SIZE
+ then they will be dumped into a file.
+
+ :param text: text to dump
+ :type text: str
+ """
+ self.buffer += text
+ if len(self.buffer) > self.BUFFER_SIZE:
+ self._dump()
diff --git a/pool/shard009/Python/0083761_0001_initial.py b/pool/shard009/Python/0083761_0001_initial.py
new file mode 100644
index 0000000000000000000000000000000000000000..6ecefc0e75b067c3becb49cafc610a1ca6d7bacd
--- /dev/null
+++ b/pool/shard009/Python/0083761_0001_initial.py
@@ -0,0 +1,33 @@
+# -*- coding: utf-8 -*-
+from __future__ import unicode_literals
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name='Comment',
+ fields=[
+ ('id', models.AutoField(verbose_name='ID', primary_key=True, serialize=False, auto_created=True)),
+ ],
+ options={
+ },
+ bases=(models.Model,),
+ ),
+ migrations.CreateModel(
+ name='Book',
+ fields=[
+ ('id', models.AutoField(verbose_name='ID', primary_key=True, serialize=False, auto_created=True)),
+ ('title', models.CharField(db_index=True, max_length=100)),
+ ('comments', models.ManyToManyField(to='commands_sql_migrations.Comment')),
+ ],
+ options={
+ },
+ bases=(models.Model,),
+ ),
+ ]
diff --git a/pool/shard009/Python/0083762_test_skymap.py b/pool/shard009/Python/0083762_test_skymap.py
new file mode 100644
index 0000000000000000000000000000000000000000..ce60ce3c1e90b4f6ce00211b091d88938a6e348d
--- /dev/null
+++ b/pool/shard009/Python/0083762_test_skymap.py
@@ -0,0 +1,45 @@
+# Licensed under a 3-clause BSD style license - see LICENSE.rst
+from __future__ import absolute_import, division, print_function
+import numpy as np
+from numpy.testing import assert_allclose
+from fermipy.hpx_utils import HPX
+from fermipy.fits_utils import write_fits_image
+from fermipy.skymap import HpxMap
+
+
+def test_hpxmap(tmpdir):
+ n = np.ones((10, 192), 'd')
+ hpx = HPX(4, False, 'GAL')
+
+ filename = str(tmpdir / 'test_hpx.fits')
+ hpx.write_fits(n, filename, clobber=True)
+
+ ebins = np.logspace(2, 5, 8)
+
+ hpx_2 = HPX(1024, False, 'GAL', region='DISK(110.,75.,2.)', ebins=ebins)
+ npixels = hpx_2.npix
+
+ n2 = np.ndarray((8, npixels), 'd')
+ for i in range(8):
+ n2[i].flat = np.arange(npixels)
+
+ hpx_map = HpxMap(n2, hpx_2)
+ wcs, wcs_data = hpx_map.make_wcs_from_hpx(normalize=True)
+
+ wcs_out = hpx_2.make_wcs(3)
+
+ filename = str(tmpdir / 'test_hpx_2_wcs.fits')
+ write_fits_image(wcs_data, wcs_out.wcs, filename)
+
+ assert_allclose(wcs_data[0, 160, 160], 87.28571429)
+ assert_allclose(wcs_data[4, 160, 160], 87.28571429)
+
+
+def test_hpx():
+
+ hpx0 = HPX(2**3, False, 'GAL', region='DISK(110.,75.,10.)')
+ assert_allclose(hpx0[hpx0._ipix], np.arange(len(hpx0._ipix)))
+
+ ebins = np.logspace(2, 5, 8)
+ hpx1 = HPX(2**3, False, 'GAL', region='DISK(110.,75.,10.)', ebins=ebins)
+ assert_allclose(hpx1[hpx1._ipix], np.arange(len(hpx1._ipix)))
diff --git a/pool/shard009/Python/0083766_dellos9_command.py b/pool/shard009/Python/0083766_dellos9_command.py
new file mode 100644
index 0000000000000000000000000000000000000000..e3d2063f5416d0eb5e70bb3d36f37c2317b1f4d5
--- /dev/null
+++ b/pool/shard009/Python/0083766_dellos9_command.py
@@ -0,0 +1,240 @@
+#!/usr/bin/python
+#
+# (c) 2015 Peter Sprygada,
+#
+# Copyright (c) 2016 Dell Inc.
+#
+# This file is part of Ansible
+#
+# Ansible is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# Ansible 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 Ansible. If not, see .
+#
+
+ANSIBLE_METADATA = {'metadata_version': '1.0',
+ 'status': ['preview'],
+ 'supported_by': 'community'}
+
+
+DOCUMENTATION = """
+---
+module: dellos9_command
+version_added: "2.2"
+author: "Dhivya P (@dhivyap)"
+short_description: Run commands on remote devices running Dell OS9
+description:
+ - Sends arbitrary commands to a Dell OS9 node and returns the results
+ read from the device. This module includes an
+ argument that will cause the module to wait for a specific condition
+ before returning or timing out if the condition is not met.
+ - This module does not support running commands in configuration mode.
+ Please use M(dellos9_config) to configure Dell OS9 devices.
+extends_documentation_fragment: dellos9
+options:
+ commands:
+ description:
+ - List of commands to send to the remote dellos9 device over the
+ configured provider. The resulting output from the command
+ is returned. If the I(wait_for) argument is provided, the
+ module is not returned until the condition is satisfied or
+ the number of retries has expired.
+ required: true
+ wait_for:
+ description:
+ - List of conditions to evaluate against the output of the
+ command. The task will wait for each condition to be true
+ before moving forward. If the conditional is not true
+ within the configured number of I(retries), the task fails.
+ See examples.
+ required: false
+ default: null
+ retries:
+ description:
+ - Specifies the number of retries a command should be tried
+ before it is considered failed. The command is run on the
+ target device every retry and evaluated against the
+ I(wait_for) conditions.
+ required: false
+ default: 10
+ interval:
+ description:
+ - Configures the interval in seconds to wait between retries
+ of the command. If the command does not pass the specified
+ conditions, the interval indicates how long to wait before
+ trying the command again.
+ required: false
+ default: 1
+
+notes:
+ - This module requires Dell OS9 version 9.10.0.1P13 or above.
+
+ - This module requires to increase the ssh connection rate limit.
+ Use the following command I(ip ssh connection-rate-limit 60)
+ to configure the same. This can be done via M(dellos9_config) module
+ as well.
+
+"""
+
+EXAMPLES = """
+# Note: examples below use the following provider dict to handle
+# transport and authentication to the node.
+vars:
+ cli:
+ host: "{{ inventory_hostname }}"
+ username: admin
+ password: admin
+ transport: cli
+
+tasks:
+ - name: run show version on remote devices
+ dellos9_command:
+ commands: show version
+ provider: "{{ cli }}"
+
+ - name: run show version and check to see if output contains OS9
+ dellos9_command:
+ commands: show version
+ wait_for: result[0] contains OS9
+ provider: "{{ cli }}"
+
+ - name: run multiple commands on remote nodes
+ dellos9_command:
+ commands:
+ - show version
+ - show interfaces
+ provider: "{{ cli }}"
+
+ - name: run multiple commands and evaluate the output
+ dellos9_command:
+ commands:
+ - show version
+ - show interfaces
+ wait_for:
+ - result[0] contains OS9
+ - result[1] contains Loopback
+ provider: "{{ cli }}"
+"""
+
+RETURN = """
+stdout:
+ description: The set of responses from the commands
+ returned: always
+ type: list
+ sample: ['...', '...']
+
+stdout_lines:
+ description: The value of stdout split into a list
+ returned: always
+ type: list
+ sample: [['...', '...'], ['...'], ['...']]
+
+failed_conditions:
+ description: The list of conditionals that have failed
+ returned: failed
+ type: list
+ sample: ['...', '...']
+
+warnings:
+ description: The list of warnings (if any) generated by module based on arguments
+ returned: always
+ type: list
+ sample: ['...', '...']
+"""
+
+from ansible.module_utils.basic import get_exception
+from ansible.module_utils.netcli import CommandRunner, FailedConditionsError
+from ansible.module_utils.network import NetworkModule, NetworkError
+from ansible.module_utils.six import string_types
+import ansible.module_utils.dellos9
+
+VALID_KEYS = ['command', 'prompt', 'response']
+
+def to_lines(stdout):
+ for item in stdout:
+ if isinstance(item, basestring):
+ item = str(item).split('\n')
+ yield item
+
+def parse_commands(module):
+ for cmd in module.params['commands']:
+ if isinstance(cmd, string_types):
+ cmd = dict(command=cmd, output=None)
+ elif 'command' not in cmd:
+ module.fail_json(msg='command keyword argument is required')
+ elif not set(cmd.keys()).issubset(VALID_KEYS):
+ module.fail_json(msg='unknown keyword specified')
+ yield cmd
+
+def main():
+ spec = dict(
+ # { command: , prompt: , response: }
+ commands=dict(type='list', required=True),
+ wait_for=dict(type='list'),
+ retries=dict(default=10, type='int'),
+ interval=dict(default=1, type='int')
+ )
+
+ module = NetworkModule(argument_spec=spec,
+ connect_on_load=False,
+ supports_check_mode=True)
+
+ commands = list(parse_commands(module))
+ conditionals = module.params['wait_for'] or list()
+
+ warnings = list()
+
+ runner = CommandRunner(module)
+
+ for cmd in commands:
+ if module.check_mode and not cmd['command'].startswith('show'):
+ warnings.append('only show commands are supported when using '
+ 'check mode, not executing `%s`' % cmd)
+ else:
+ if cmd['command'].startswith('conf'):
+ module.fail_json(msg='dellos9_command does not support running '
+ 'config mode commands. Please use '
+ 'dellos9_config instead')
+ runner.add_command(**cmd)
+
+ for item in conditionals:
+ runner.add_conditional(item)
+
+ runner.retries = module.params['retries']
+ runner.interval = module.params['interval']
+
+ try:
+ runner.run()
+ except FailedConditionsError:
+ exc = get_exception()
+ module.fail_json(msg=str(exc), failed_conditions=exc.failed_conditions)
+ except NetworkError:
+ exc = get_exception()
+ module.fail_json(msg=str(exc))
+
+ result = dict(changed=False)
+
+ result['stdout'] = list()
+ for cmd in commands:
+ try:
+ output = runner.get_command(cmd['command'])
+ except ValueError:
+ output = 'command not executed due to check_mode, see warnings'
+ result['stdout'].append(output)
+
+ result['warnings'] = warnings
+ result['stdout_lines'] = list(to_lines(result['stdout']))
+
+ module.exit_json(**result)
+
+
+if __name__ == '__main__':
+ main()
diff --git a/pool/shard009/Python/0083770_swarmrunner.py b/pool/shard009/Python/0083770_swarmrunner.py
new file mode 100644
index 0000000000000000000000000000000000000000..b13d0161d5d2b4c86a0a78e470841e94bcc213c4
--- /dev/null
+++ b/pool/shard009/Python/0083770_swarmrunner.py
@@ -0,0 +1,83 @@
+import os
+import pprint
+import json
+
+# add logging to output errors to stdout
+import logging
+logging.basicConfig()
+
+from nupic.swarming import permutations_runner
+
+
+def _modelParamsToString(modelParams):
+ pp = pprint.PrettyPrinter(indent=2)
+ return pp.pformat(modelParams)
+
+
+def touch(fname, times=None):
+ with open(fname, 'a'):
+ os.utime(fname, times)
+
+
+def _writeModelParamsToFile(modelParams, workingDir):
+ paramsName = "model_params.py"
+ outDir = os.path.join(workingDir, 'model_params')
+ if not os.path.isdir(outDir):
+ os.mkdir(outDir)
+ outPath = os.path.join(workingDir, 'model_params', paramsName)
+ with open(outPath, "wb") as outFile:
+ modelParamsString = _modelParamsToString(modelParams)
+ outFile.write("MODEL_PARAMS = \\\n%s" % modelParamsString)
+ touch(os.path.join(outDir, "__init__.py"))
+ return outPath
+
+
+
+def _swarmForBestModelParams(swarmConfig, name, workingDir, maxWorkers=8):
+ outputLabel = name
+ permWorkDir = os.path.join(workingDir, "swarm")
+ if not os.path.exists(permWorkDir):
+ os.mkdir(permWorkDir)
+ modelParams = permutations_runner.runWithConfig(
+ swarmConfig,
+ {"maxWorkers": maxWorkers, "overwrite": True},
+ outputLabel=outputLabel,
+ outDir=permWorkDir,
+ permWorkDir=permWorkDir,
+ verbosity=0
+ )
+ _writeModelParamsToFile(modelParams, workingDir)
+ return modelParams
+
+
+
+def _printSwarmSizeWarning(size):
+ if size.strip() == "small":
+ print "= THIS IS A DEBUG SWARM. DON'T EXPECT YOUR MODEL RESULTS TO BE GOOD."
+ elif size.strip() == "medium":
+ print "= Medium swarm. Sit back and relax, this could take awhile."
+ elif size.strip() == "large":
+ print "= LARGE SWARM! Might as well load up the Star Wars Trilogy."
+ else:
+ raise Exception("Unknown swarm size \"%s\"", size)
+
+
+
+def swarm(workingDir):
+ """
+ Runs a swarm in the giving working directory, assuming it was created by
+ Menorah.
+ :param workingDir: absolute or relative path to working directory created by
+ Menorah
+ """
+ name = os.path.splitext(os.path.basename(workingDir))[0]
+ swarmDescriptionFile = os.path.join(workingDir, "swarm_description.json")
+ with open(swarmDescriptionFile) as swarmDesc:
+ swarmDescription = json.loads(swarmDesc.read())
+ print "================================================="
+ print "= Swarming on %s data..." % name
+ _printSwarmSizeWarning(swarmDescription["swarmSize"])
+ print "================================================="
+ modelParams = _swarmForBestModelParams(swarmDescription, name, workingDir)
+ return modelParams
+
diff --git a/pool/shard009/Python/0083777_test_rollback_rollsback.py b/pool/shard009/Python/0083777_test_rollback_rollsback.py
new file mode 100644
index 0000000000000000000000000000000000000000..f3084e0ee475a1caf77d5b0e5592af18834cdd9d
--- /dev/null
+++ b/pool/shard009/Python/0083777_test_rollback_rollsback.py
@@ -0,0 +1,30 @@
+from os import path
+from nose import tools
+
+from tests.functional import single_machine_test
+
+from nixops import backends
+
+parent_dir = path.dirname(__file__)
+
+has_hello_spec = '%s/single_machine_has_hello.nix' % (parent_dir)
+
+rollback_spec = '%s/single_machine_rollback.nix' % (parent_dir)
+
+class TestRollbackRollsback(single_machine_test.SingleMachineTest):
+ _multiprocess_can_split_ = True
+
+ def setup(self):
+ super(TestRollbackRollsback,self).setup()
+ self.depl.nix_exprs = self.depl.nix_exprs + [ rollback_spec ]
+
+ def run_check(self):
+ self.depl.deploy()
+ with tools.assert_raises(backends.SSHCommandFailed):
+ self.check_command("hello")
+ self.depl.nix_exprs = self.depl.nix_exprs + [ has_hello_spec ]
+ self.depl.deploy()
+ self.check_command("hello")
+ self.depl.rollback(generation=1)
+ with tools.assert_raises(backends.SSHCommandFailed):
+ self.check_command("hello")
diff --git a/pool/shard009/Python/0083779_test_node_install_integration.py b/pool/shard009/Python/0083779_test_node_install_integration.py
new file mode 100644
index 0000000000000000000000000000000000000000..e215d8bca539f9b905109951a47c2200fb648a87
--- /dev/null
+++ b/pool/shard009/Python/0083779_test_node_install_integration.py
@@ -0,0 +1,36 @@
+# Copyright 2018 Pants project contributors (see CONTRIBUTORS.md).
+# Licensed under the Apache License, Version 2.0 (see LICENSE).
+
+from pants.testutil.pants_run_integration_test import PantsRunIntegrationTest
+
+
+class NodeInstallIntegrationTest(PantsRunIntegrationTest):
+ def test_node_install_with_prepublish(self):
+ command = [
+ "node-install",
+ # Use same install parameters as resolve.node in .pants.d, I.E. don't generate a new yarn.lock file
+ "--npm-resolver-force-option-override=True",
+ "contrib/node/examples/src/node/server-project",
+ ]
+ pants_run = self.run_pants(command=command)
+ self.assert_success(pants_run)
+
+ def test_node_install_preinstalled_node_module_project(self):
+ command = [
+ "node-install",
+ # Use same install parameters as resolve.node in .pants.d, I.E. don't generate a new yarn.lock file
+ "--npm-resolver-force-option-override=True",
+ "contrib/node/examples/src/node/preinstalled-project:unit",
+ ]
+ pants_run = self.run_pants(command=command)
+ self.assert_success(pants_run)
+
+ def test_node_install_yarn_workspaces(self):
+ command = [
+ "node-install",
+ # Use same install parameters as resolve.node in .pants.d, I.E. don't generate a new yarn.lock file
+ "--npm-resolver-force-option-override=True",
+ "contrib/node/examples/src/node/yarn-workspaces",
+ ]
+ pants_run = self.run_pants(command=command)
+ self.assert_success(pants_run)
diff --git a/pool/shard009/Python/0083781_0003_auto_20160204_1540.py b/pool/shard009/Python/0083781_0003_auto_20160204_1540.py
new file mode 100644
index 0000000000000000000000000000000000000000..441b026ad5f2ad1e23504bc684609caee1fe47b5
--- /dev/null
+++ b/pool/shard009/Python/0083781_0003_auto_20160204_1540.py
@@ -0,0 +1,27 @@
+# -*- coding: utf-8 -*-
+
+from django.db import migrations, models
+import datetime
+import django_extensions.db.fields
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ('coop_cms', '0002_auto_20160108_1628'),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name='newsletter',
+ name='created',
+ field=django_extensions.db.fields.CreationDateTimeField(default=datetime.datetime(2016, 2, 4, 15, 40, 3, 30106), verbose_name='created', auto_now_add=True),
+ preserve_default=False,
+ ),
+ migrations.AddField(
+ model_name='newsletter',
+ name='modified',
+ field=django_extensions.db.fields.ModificationDateTimeField(default=datetime.datetime(2016, 2, 4, 15, 40, 22, 708986), verbose_name='modified', auto_now=True),
+ preserve_default=False,
+ ),
+ ]
diff --git a/pool/shard009/Python/0083784_test_misc.py b/pool/shard009/Python/0083784_test_misc.py
new file mode 100644
index 0000000000000000000000000000000000000000..45a72ce146050caa20c35b8b2647f8f6f83746c6
--- /dev/null
+++ b/pool/shard009/Python/0083784_test_misc.py
@@ -0,0 +1,114 @@
+import os
+from unittest import TestCase
+
+from pcs.common import const
+from pcs.common.str_tools import format_list
+
+from pcs_test.tools.assertions import AssertPcsMixin
+from pcs_test.tools.misc import get_test_resource as rc
+from pcs_test.tools.misc import (
+ get_tmp_dir,
+ get_tmp_file,
+ outdent,
+ write_file_to_tmpfile,
+)
+from pcs_test.tools.pcs_runner import PcsRunner
+
+
+class ParseArgvDashDash(TestCase, AssertPcsMixin):
+ # The command will fail, that's ok. We are interested only in the argv
+ # parsing.
+ cmd = "constraint colocation add R1 with R2".split()
+
+ def setUp(self):
+ self.temp_cib = get_tmp_file("tier1_misc_dashdash")
+ write_file_to_tmpfile(rc("cib-empty.xml"), self.temp_cib)
+ self.pcs_runner = PcsRunner(self.temp_cib.name)
+ self.allowed_roles = format_list(const.PCMK_ROLES)
+
+ def tearDown(self):
+ self.temp_cib.close()
+
+ def test_negative_int(self):
+ self.assert_pcs_fail(
+ self.cmd + ["-123"],
+ outdent(
+ """\
+ Deprecation Warning: Using '-123' without '--' is deprecated, those parameters will be considered position independent options in future pcs versions
+ Error: Resource 'R1' does not exist
+ """
+ ),
+ )
+
+ def test_negative_float(self):
+ self.assert_pcs_fail(
+ self.cmd + ["-12.3"],
+ outdent(
+ f"""\
+ Deprecation Warning: Using '-12.3' without '--' is deprecated, those parameters will be considered position independent options in future pcs versions
+ Error: invalid role value 'R2', allowed values are: {self.allowed_roles}
+ """
+ ),
+ )
+
+ def test_negative_infinity(self):
+ self.assert_pcs_fail(
+ self.cmd + ["-inFIniTY"],
+ outdent(
+ f"""\
+ Deprecation Warning: Using '-inFIniTY' without '--' is deprecated, those parameters will be considered position independent options in future pcs versions
+ Error: invalid role value 'R2', allowed values are: {self.allowed_roles}
+ """
+ ),
+ )
+
+ def test_negative_int_dash_dash(self):
+ self.assert_pcs_fail(
+ ["--"] + self.cmd + ["-123"],
+ outdent(
+ """\
+ Error: Resource 'R1' does not exist
+ """
+ ),
+ )
+
+ def test_negative_float_dash_dash(self):
+ self.assert_pcs_fail(
+ ["--"] + self.cmd + ["-12.3"],
+ outdent(
+ f"""\
+ Error: invalid role value 'R2', allowed values are: {self.allowed_roles}
+ """
+ ),
+ )
+
+ def test_negative_infinity_dash_dash(self):
+ self.assert_pcs_fail(
+ ["--"] + self.cmd + ["-inFIniTY"],
+ outdent(
+ f"""\
+ Error: invalid role value 'R2', allowed values are: {self.allowed_roles}
+ """
+ ),
+ )
+
+
+class EmptyCibIsPcmk2Compatible(TestCase, AssertPcsMixin):
+ # This test verifies that a default empty CIB created by pcs when -f points
+ # to an empty file conforms to minimal schema version supported by
+ # pacemaker 2.0. If pcs prints a message that CIB schema has been upgraded,
+ # then the test fails and shows there is a bug. Bundle with promoted-max
+ # requires CIB compliant with schema 3.1, which was introduced in pacemaker
+ # 2.0.0.
+ def setUp(self):
+ self.cib_dir = get_tmp_dir("tier1_misc_empty_cib")
+ self.pcs_runner = PcsRunner(os.path.join(self.cib_dir.name, "cib.xml"))
+
+ def tearDown(self):
+ self.cib_dir.cleanup()
+
+ def test_success(self):
+ self.assert_pcs_success(
+ "resource bundle create b container docker image=my.img promoted-max=1".split(),
+ "",
+ )
diff --git a/pool/shard009/Python/0083788_vocab.py b/pool/shard009/Python/0083788_vocab.py
new file mode 100644
index 0000000000000000000000000000000000000000..137c4db334b09308db449bfb503b97ba9801c651
--- /dev/null
+++ b/pool/shard009/Python/0083788_vocab.py
@@ -0,0 +1,104 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+
+import random
+
+from flask import Flask, request, render_template
+from flask.ext.sqlalchemy import SQLAlchemy
+
+
+app = Flask(__name__)
+app.debug = True
+app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///data/data.db'
+db = SQLAlchemy(app)
+
+
+class Word(db.Model):
+ id = db.Column(db.Integer, primary_key=True)
+ word = db.Column(db.String)
+ ndef = db.Column(db.Integer)
+ list_name = db.Column(db.String)
+ ntested = db.Column(db.Integer)
+ nmistakes = db.Column(db.Integer)
+
+ def __init__(self, word, ndef, list_name, ntested=0, nmistakes=0):
+ self.word = word
+ self.ndef = ndef
+ self.list_name = list_name
+ self.ntested = ntested
+ self.nmistakes = nmistakes
+
+
+class List(db.Model):
+ id = db.Column(db.Integer, primary_key=True)
+ list_name = db.Column(db.String)
+
+ def __init__(self, list_name):
+ self.list_name = list_name
+
+
+@app.route('/', methods=['GET'])
+def index():
+ return render_template('index.html')
+
+
+@app.route('/upload_list', methods=['GET', 'POST'])
+def upload_list():
+ if request.method == 'GET':
+ return render_template('upload_list.html')
+ else:
+ list_name = request.form['list_name']
+ l = List(list_name)
+ db.session.add(l)
+ words = request.form['words']
+ word_list = words.split('\r\n')
+
+ for raw_word in word_list:
+ w, ndef = raw_word.split('\t')
+ word = Word(w, ndef, list_name)
+ db.session.add(word)
+ db.session.commit()
+ return 'Successful upload.'
+
+
+@app.route('/select_list')
+def select_list():
+ lists = List.query.all()
+ return render_template('select_list.html', lists=lists)
+
+
+@app.route('/show_list')
+@app.route('/show_list/')
+def show_list(list_name=None):
+ words = Word.query.filter_by(list_name=list_name).all()
+ random.shuffle(words)
+ return render_template('show_list.html', words=words)
+
+
+@app.route('/record', methods=['POST'])
+def record():
+ ids = [int(id) for id in request.form.keys()]
+ for id in ids:
+ w = Word.query.get(id)
+ new_nmistakes = w.nmistakes + 1
+ w.nmistakes = new_nmistakes
+ db.session.commit()
+ return 'Recorded.'
+
+
+@app.route('/view_mistakes')
+@app.route('/view_mistakes/')
+def view_mistakes(list_name=None):
+ if list_name is None:
+ lists = List.query.all()
+ return render_template('select_mistake_list.html', lists=lists)
+ else:
+ words = Word.query.filter_by(list_name=list_name).filter_by(nmistakes=1).all()
+ return render_template('view_mistakes.html', mistakes=words)
+
+
+
+if __name__ == '__main__':
+ app.run()
+ # db.create_all()
\ No newline at end of file
diff --git a/pool/shard009/Python/0083792_wordCountReducer_Sliding_StdDev.py b/pool/shard009/Python/0083792_wordCountReducer_Sliding_StdDev.py
new file mode 100644
index 0000000000000000000000000000000000000000..71f4d0e760b8e5cfee8639ece12ddf812edc17ab
--- /dev/null
+++ b/pool/shard009/Python/0083792_wordCountReducer_Sliding_StdDev.py
@@ -0,0 +1,187 @@
+#!/usr/bin/env python
+
+from operator import itemgetter
+import sys
+import math
+
+current_word = None
+current_count = 0
+word = None
+
+wordcount = {}
+count_list = []
+
+wordcountByFile = {}
+extrawordcount = {}
+wordAvg = {}
+wordStdDev = {}
+
+def addToDictionary(current_word, current_count):
+ wordkey = current_word.split("_")[0]
+ if wordcount.get(wordkey) == None:
+ count_list = []
+ count_list.append(current_count)
+ wordcount[wordkey] = count_list
+ else:
+ wordcount.get(wordkey).append(current_count)
+
+def addToDictByFile(current_word):
+ if wordcountByFile.get(current_word) == None:
+ wordcountByFile[current_word] = 1
+ else:
+ count_val = wordcountByFile.get(current_word)
+ wordcountByFile[current_word] = count_val + 1
+
+def addToWordCount(current_word):
+ if wordcount.get(current_word) == None:
+ wordcount[current_word] = 1
+ else:
+ count_val = wordcount.get(current_word)
+ wordcount[current_word] = count_val + 1
+
+def addToExtraWordCount(word):
+ if extrawordcount.get(word) == None:
+ extrawordcount[word] = 1
+ else:
+ extrawordcount[word] = extrawordcount[word] + 1
+
+def calculateMinMaxAvg():
+ average = -1
+ minimum = -1
+ maximum = -1
+ for word in wordcount:
+ #print wordcount.get(word)
+ minimum = min(wordcount.get(word))
+ maximum = max(wordcount.get(word))
+ average = sum(wordcount.get(word))/229.0
+ print '%s\t%s\t%s\t%s' % (word, minimum, maximum, average)
+
+def calculateAverage():
+ average = -1
+ for word in wordcount:
+ average = sum(wordcount.get(word))/5.0
+ return average
+
+def calculateStdDev():
+ stdDev = -1
+ average = -1
+ for word in wordcount:
+ partialSquare = -1
+ sumOfSquare = -1
+ average = sum(wordcount.get(word))/5.0
+ countlist = wordcount.get(word)
+ for count in countlist:
+ partialSquare = (count-average)**2
+ sumOfSquare += partialSquare
+ stdDev = math.sqrt(sumOfSquare/5.0)
+ print '%s\t%s\t%s' % (word, average, stdDev)
+
+#def slicedict(d, s):
+# return {k:v for k,v in d.iteritems() if k.startswith(s)}
+def slicedict(sourcedict, string):
+ #print sourcedict
+ #print string
+ newdict = {}
+ for key in sourcedict.keys():
+ if key.startswith(string):
+ newdict[key] = sourcedict[key]
+ return newdict
+
+def calculateStdDev2():
+ #stdDev = 0
+ average = 0
+ for word in wordcount:
+ #print word
+ #print "WordAverageWondow: " + word + "\t" + "wordcount: " + str(wordcount.get(word)) + "avg: " + "\t" + str(average)
+ average = (wordcount.get(word)/5.0)
+ #print "WordAverageWondow: " + word + "\t" + "wordcount: " + str(wordcount.get(word)) + "avg: " + "\t" + str(average)
+ partialSquare = 0
+ sumOfSquare = 0
+ stdDev = 0
+ tempdict = slicedict(wordcountByFile, word+"_")
+ #print tempdict
+ for tempkey in tempdict:
+ partialSquare = (int(tempdict.get(tempkey))-average)*(int(tempdict.get(tempkey))-average)
+ #print partialSquare
+ sumOfSquare += partialSquare
+ stdDev = math.sqrt(sumOfSquare/5.0)
+ #print "WordAverageWondow: " + word + "\t" + str(average)
+ wordAvg[word] = average
+ wordStdDev[word] = stdDev
+ #print '%s\t%s\t%s' % (word, average, stdDev)
+
+def calculateTwoStdDev():
+ calculateStdDev2()
+ for word in wordcount:
+ if wordAvg.get(word) == None or wordStdDev.get(word) == None:
+ continue
+ nWordAverage = wordAvg.get(word)
+ nWordStdDev = wordStdDev.get(word)
+ nTwoStdDev = nWordAverage + 2*nWordStdDev
+ nExtraWordCount = extrawordcount.get(word)
+ if nExtraWordCount == None:
+ continue
+ elif nExtraWordCount > nTwoStdDev:
+ print '%s\t%s\t%s\t%s\t%s' % (word, nExtraWordCount, nWordAverage, nWordStdDev, nTwoStdDev)
+
+
+# input comes from STDIN
+for line in sys.stdin:
+ # remove leading and trailing whitespace
+ line = line.strip()
+
+ # parse the input we got from mapper.py
+ word, count = line.split('\t', 1)
+
+ dict_word = ""
+ dic_count = ""
+ # convert count (currently a string) to int
+ try:
+ dict_word = word + "_" + count.split("_")[1]
+ dic_count = count.split("_")[0]
+ dic_count = int(dic_count)
+ except ValueError:
+ # count was not a number, so silently
+ # ignore/discard this line
+ continue
+
+ if "_file6" in dict_word:
+ addToExtraWordCount(word)
+ else:
+ addToDictByFile(dict_word)
+ addToWordCount(word)
+
+#calculateStdDev2()
+calculateTwoStdDev()
+
+
+'''
+ # convert count (currently a string) to int
+ try:
+ word = word + count.split("_")[1]
+ count = count.split("_")[0]
+ count = int(count)
+ except ValueError:
+ # count was not a number, so silently
+ # ignore/discard this line
+ continue
+
+ # this IF-switch only works because Hadoop sorts map output
+ # by key (here: word) before it is passed to the reducer
+ if current_word == word:
+ current_count += count
+ else:
+ if current_word:
+ # write result to STDOUT
+ #print '%s\t%s' % (current_word, current_count)
+ addToDictionary(current_word, current_count)
+ current_count = count
+ current_word = word
+
+# do not forget to output the last word if needed!
+if current_word == word:
+ #print '%s\t%s' % (current_word, current_count)
+ addToDictionary(current_word, current_count)
+'''
+
+#calculateStdDev(calculateAverage())
diff --git a/pool/shard009/Python/0083794_motd.py b/pool/shard009/Python/0083794_motd.py
new file mode 100644
index 0000000000000000000000000000000000000000..4f82b1b41e25822243c9ad3687aa4db3fff06d0f
--- /dev/null
+++ b/pool/shard009/Python/0083794_motd.py
@@ -0,0 +1,76 @@
+# minqlbot - A Quake Live server administrator bot.
+# Copyright (C) Mino