commit
stringlengths
40
40
subject
stringlengths
1
1.49k
old_file
stringlengths
4
311
new_file
stringlengths
4
311
new_contents
stringlengths
1
29.8k
old_contents
stringlengths
0
9.9k
lang
stringclasses
3 values
proba
float64
0
1
481b822125de1d29de09975a6607c4fa038b98df
Add model List
todo/models.py
todo/models.py
from django.db import models from django.utils.text import slugify from common.models import TimeStampedModel class List(TimeStampedModel): name = models.CharField(max_length=50) slug = models.CharField(max_length=50, editable=False) def save(self, *args, **kwargs): self.slug = slugify(self.name) super(List, self).save(*args, **kwargs)
Python
0.000001
d64e28b6aabf83711faca5853a01b590c5f89548
Create topicmining.py
topicmining.py
topicmining.py
from gensim import corpora, models from itertools import chain from urllib import urlopen from operator import itemgetter import csv import simplejson as json #The code for extracting entities from referata was taken by fnielsen git repository # Define a url as a Python string (note we are only getting 100 documents) url = "http://wikilit.referata.com/" + \ "wiki/Special:Ask/" + \ "-5B-5BCategory:Publications-5D-5D/" + \ "-3FHas-20author%3DAuthor(s)/-3FYear/" + \ "-3FPublished-20in/-3FAbstract/-3FHas-20topic%3DTopic(s)/" + \ "-3FHas-20domain%3DDomain(s)/" + \ "format%3D-20csv/limit%3D-20100/offset%3D0" # Get and read the web page doc = urlopen(url).read() # Object from urlopen has read function # Show the first 1000 characters #print(doc[:1000]) web = urlopen(url) # 'web' is now a file-like handle lines = csv.reader(web, delimiter=',', quotechar='"') # JSON format instead that Semantic MediaWiki also exports url_json = "http://wikilit.referata.com/" + \ "wiki/Special:Ask/" + \ "-5B-5BCategory:Publications-5D-5D/" + \ "-3FHas-20author/-3FYear/" + \ "-3FPublished-20in/-3FAbstract/-3FHas-20topic)/" + \ "-3FHas-20domain/" + \ "format%3D-20json" # Read JSON into a Python structure response = json.load(urlopen(url_json)) # response['printrequests'] is a list, map iterates over the list columns = map(lambda item: item['label'], response['printrequests']) # gives ['', 'Has author', 'Year', 'Published in', 'Abstract', # 'Has topic)', 'Has domain'] # Reread CSV lines = csv.reader(urlopen(url), delimiter=',', quotechar='"') # Iterate over 'lines' and insert the into a list of dictionaries header = [] papers = [] for row in lines: # csv module lacks unicode support! line = [unicode(cell, 'utf-8') for cell in row] if not header: # Read the first line as header header = line continue papers.append(dict(zip(header, line))) # 'papers' is now an list of dictionaries abstracts=[] for abstract,i in enumerate(papers): abstracts.append(papers[abstract]['Abstract']) stoplist = set('for a of the and to in'.split()) texts = [[word for word in abstract.lower().split() if word not in stoplist] for abstract in abstracts] all_tokens = sum(texts, []) tokens_once = set(word for word in set(all_tokens) if all_tokens.count(word) == 1) texts = [[word for word in text if word not in tokens_once] for text in texts] #print texts dictionary = corpora.Dictionary(texts) dictionary.save('C:/Users/Ioanna/abstracts.dict') corpus = [dictionary.doc2bow(text) for text in texts] corpora.MmCorpus.serialize('C:/Users/Ioanna/abstracts.mm', corpus) # store to disk, for later use dictionary = corpora.Dictionary.load('C:/Users/Ioanna/abstracts.dict') corpus = corpora.MmCorpus('C:/Users/Ioanna/abstracts.mm') tfidf = models.TfidfModel(corpus) # step 1 -- initialize a model corpus_tfidf = tfidf[corpus] #lsi = models.LsiModel(corpus_tfidf, id2word=dictionary, num_topics=50) #corpus_lsi = lsi[corpus_tfidf] #lsi.print_topics(20) lda = models.LdaModel(corpus=corpus_tfidf, id2word=dictionary, num_topics=50) for i in range(0, 50): temp = lda.show_topic(i, 10) terms = [] for term in temp: terms.append(term[1]) print "Top 10 terms for topic #" + str(i) + ": "+ ", ".join(terms) print print 'Which LDA topic maximally describes a document?\n' print 'Original document: ' + abstracts[0] print 'Preprocessed document: ' + str(texts[0]) print 'Matrix Market format: ' + str(corpus[0]) print 'Topic probability mixture: ' + str(lda[corpus[0]]) print 'Maximally probable topic: topic #' + str(max(lda[corpus[0]],key=itemgetter(0))[0])
Python
0.000001
744d7971926bf7672ce01388b8617be1ee35df0e
Add missing test data folder
xunit-autolabeler-v2/ast_parser/core/test_data/parser/exclude_tags/exclude_tags_main.py
xunit-autolabeler-v2/ast_parser/core/test_data/parser/exclude_tags/exclude_tags_main.py
# 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. # [START main_method] def main(): return 'main method' # [START_EXCLUDE] # [END_EXCLUDE] def not_main(): return 'not main' # [END main_method]
Python
0.000001
c2f1a5b84497132c6b7b15797493082c865e737d
add twitter_bot
twitter_bot.py
twitter_bot.py
import tweepy import feedparser import re import requests import os # pip3 install tweepy feedparser feed_url = "https://lambdan.se/blog/rss.xml" database_file = "./tweeted_by_twitter_bot.txt" # txt with urls that have been tweeted (one url per line) twitter_consumer_api_key = "" twitter_api_secret_key = "" twitter_access_token = "" twitter_access_token_secret = "" def auth_twitter(): auth = tweepy.OAuthHandler(twitter_consumer_api_key, twitter_api_secret_key) auth.set_access_token(twitter_access_token, twitter_access_token_secret) api = tweepy.API(auth) return api # read already tweeted links already_tweeted = [] if os.path.isfile(database_file): with open(database_file) as f: lines = f.readlines() for line in lines: already_tweeted.append(line.rstrip()) print(len(already_tweeted), "urls in", database_file) # read rss print ("Grabbing rss feed", feed_url) feed = feedparser.parse(feed_url) print("Got", len(feed.entries), "posts") for entry in reversed(feed.entries): # reverse it to get newest last (makes sense if posting a backlog) title = entry.title url = entry.link text = entry.summary tweet_text = str(title) + " " + str(url) # check here if url in tweeted links if url not in already_tweeted: print(">>> Tweeting", title, url) # auth twitter twitter_api = auth_twitter() # find first image images = [] images = re.findall('src="([^"]+)"', text) # dont tweet if first pic is a gif if len(images) > 0 and str(os.path.splitext(images[0])[1]).lower() == '.gif': print("*** First image is a gif, not dealing with that. Posting without image instead.") images = [] if len(images) > 0: # tweet with image picture_url = images[0] # download image - https://stackoverflow.com/a/31748691 temp_filename = "twitter_temp_" + os.path.basename(picture_url) # this should get us the file extension etc req = requests.get(picture_url, stream=True) if req.status_code == 200: with open(temp_filename, 'wb') as img: for chunk in req: img.write(chunk) twitter_api.update_with_media(temp_filename, status=tweet_text) os.remove(temp_filename) else: print("!!! ERROR: Unable to download image") sys.exit(1) else: # tweet without image twitter_api.update_status(tweet_text) with open(database_file, 'a') as d: d.write(str(url) + '\n') else: print("Already tweeted:", title, "-", url)
Python
0.000808
156c0b09930bd7700cb7348197a9e167831dca6d
ADD initial syft.lib.util tests
packages/syft/tests/syft/lib/util_test.py
packages/syft/tests/syft/lib/util_test.py
#absolute from syft.lib.util import full_name_with_name from syft.lib.util import full_name_with_qualname class TSTClass: pass class FromClass: @staticmethod def static_method(): pass def not_static_method(self): pass class ToClass: pass def test_full_name_with_name(): assert full_name_with_name(TSTClass) == f"{TSTClass.__module__}.{TSTClass.__name__}" def test_full_name_with_qualname(): class LocalTSTClass: pass assert full_name_with_qualname(LocalTSTClass) == f"{LocalTSTClass.__module__}.{LocalTSTClass.__qualname__}"
Python
0
2eb849578b7306762f1e9dc4962a9db2ad651fc9
add solution for Linked List Cycle II
src/linkedListCycleII.py
src/linkedListCycleII.py
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: # @param head, a ListNode # @return a list node def detectCycle(self, head): slow = fast = head no_loop = True while fast and fast.next: slow = slow.next fast = fast.next.next if slow == fast: no_loop = False break if no_loop: return None fast = head while slow != fast: slow = slow.next fast = fast.next return slow
Python
0
855f9afa6e8d7afba020dc5c1dc8fabfc84ba2d4
add new package : jafka (#14304)
var/spack/repos/builtin/packages/jafka/package.py
var/spack/repos/builtin/packages/jafka/package.py
# Copyright 2013-2019 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class Jafka(Package): """ Jafka is a distributed publish-subscribe messaging system. """ homepage = "https://github.com/adyliu/jafka" url = "https://github.com/adyliu/jafka/releases/download/3.0.6/jafka-3.0.6.tgz" version('3.0.6', sha256='89c9456360ace5d43c3af52b5d2e712fc49be2f88b1b3dcfe0c8f195a3244e17') version('3.0.5', sha256='43f1b4188a092c30f48f9cdd0bddd3074f331a9b916b6cb566da2e9e40bc09a7') version('3.0.4', sha256='a5334fc9280764f9fd4b5eb156154c721f074c1bcc1e5496189af7c06cd16b45') version('3.0.3', sha256='226e902af7754bb0df2cc0f30195e4f8f2512d9935265d40633293014582c7e2') version('3.0.2', sha256='c7194476475a9c3cc09ed5a4e84eecf47a8d75011f413b26fd2c0b66c598f467') version('3.0.1', sha256='3a75e7e5bb469b6d9061985a1ce3b5d0b622f44268da71cab4a854bce7150d41') version('3.0.0', sha256='4c4bacdd5fba8096118f6e842b4731a3f7b3885514fe1c6b707ea45c86c7c409') version('1.6.2', sha256='fbe5d6a3ce5e66282e27c7b71beaeeede948c598abb452abd2cae41149f44196') depends_on('java@7:', type='run') def install(self, spec, prefix): install_tree('.', prefix)
Python
0
665a373f12f030d55a5d004cbce51e9a86428a55
Add the main rohrpost handler
rohrpost/main.py
rohrpost/main.py
import json from functools import partial from . import handlers # noqa from .message import send_error from .registry import HANDLERS REQUIRED_FIELDS = ['type', 'id'] def handle_rohrpost_message(message): """ Handling of a rohrpost message will validate the required format: A valid JSON object including at least an "id" and "type" field. It then hands off further handling to the registered handler (if any). """ _send_error = partial(send_error, message, None, None) if not message.content['text']: return _send_error('Received empty message.') try: request = json.loads(message.content['text']) except json.JSONDecodeError as e: return _send_error('Could not decode JSON message. Error: {}'.format(str(e))) if not isinstance(request, dict): return _send_error('Expected a JSON object as message.') for field in REQUIRED_FIELDS: if field not in request: return _send_error("Missing required field '{}'.".format(field)) if not request['type'] in HANDLERS: return send_error( message, request['id'], request['type'], "Unknown message type '{}'.".format(request['type']), ) HANDLERS[request['type']](message, request)
Python
0.00017
8084a3be60e35e5737047f5b2d2daf8dce0cec1a
Update sliding-window-maximum.py
Python/sliding-window-maximum.py
Python/sliding-window-maximum.py
# Time: O(n) # Space: O(k) # Given an array nums, there is a sliding window of size k # which is moving from the very left of the array to the # very right. You can only see the k numbers in the window. # Each time the sliding window moves right by one position. # # For example, # Given nums = [1,3,-1,-3,5,3,6,7], and k = 3. # # Window position Max # --------------- ----- # [1 3 -1] -3 5 3 6 7 3 # 1 [3 -1 -3] 5 3 6 7 3 # 1 3 [-1 -3 5] 3 6 7 5 # 1 3 -1 [-3 5 3] 6 7 5 # 1 3 -1 -3 [5 3 6] 7 6 # 1 3 -1 -3 5 [3 6 7] 7 # Therefore, return the max sliding window as [3,3,5,5,6,7]. # # Note: # You may assume k is always valid, ie: 1 <= k <= input array's size for non-empty array. # # Follow up: # Could you solve it in linear time? from collections import deque class Solution(object): def maxSlidingWindow(self, nums, k): """ :type nums: List[int] :type k: int :rtype: List[int] """ dq = deque() max_numbers = [] for i in xrange(len(nums)): while dq and nums[i] >= nums[dq[-1]]: dq.pop() dq.append(i) if i >= k and dq and dq[0] == i - k: dq.popleft() if i >= k - 1: max_numbers.append(nums[dq[0]]) return max_numbers
# Time: O(n) # Space: O(k) # Given an array nums, there is a sliding window of size k # which is moving from the very left of the array to the # very right. You can only see the k numbers in the window. # Each time the sliding window moves right by one position. # # For example, # Given nums = [1,3,-1,-3,5,3,6,7], and k = 3. # # Window position Max # --------------- ----- # [1 3 -1] -3 5 3 6 7 3 # 1 [3 -1 -3] 5 3 6 7 3 # 1 3 [-1 -3 5] 3 6 7 5 # 1 3 -1 [-3 5 3] 6 7 5 # 1 3 -1 -3 [5 3 6] 7 6 # 1 3 -1 -3 5 [3 6 7] 7 # Therefore, return the max sliding window as [3,3,5,5,6,7]. # # Note: # You may assume k is always valid, ie: 1 <= k <= input array's size for non-empty array. # # Follow up: # Could you solve it in linear time? from collections import deque class Solution(object): def maxSlidingWindow(self, nums, k): """ :type nums: List[int] :type k: int :rtype: List[int] """ dq = deque() max_numbers = [] for i in xrange(len(nums)): while dq and nums[i] >= nums[dq[-1]]: dq.pop() dq.append(i) if i >= k and dq and dq[0] <= i - k: dq.popleft() if i >= k - 1: max_numbers.append(nums[dq[0]]) return max_numbers
Python
0.000001
f8bd2205e57e7a3b457e20b678d69065b620c965
Create __init__.py
votesim/__init__.py
votesim/__init__.py
Python
0.000429
24baf3e5e7a608d0b34d74be25f96f1b74b7622e
Add feed update task for social app
web/social/tasks.py
web/social/tasks.py
from celery.task import PeriodicTask from datetime import timedelta from social.utils import FeedUpdater, UpdateError class UpdateFeedsTask(PeriodicTask): run_every = timedelta(minutes=15) def run(self, **kwargs): logger = self.get_logger() updater = FeedUpdater(logger) print "Updating feeds" updater.update_feeds() print "Feed update done"
Python
0.000014
b5dfae3c80b08616401604aad211cedd31783f33
Add benchmarks.py script
benchmarks.py
benchmarks.py
from pathops import union as pathops_union from booleanOperations import union as boolops_union from defcon import Font as DefconFont from ufoLib2 import Font as UfoLib2Font import math import timeit REPEAT = 10 NUMBER = 1 def remove_overlaps(font, union_func, pen_getter, **kwargs): for glyph in font: contours = list(glyph) if not contours: continue glyph.clearContours() pen = getattr(glyph, pen_getter)() union_func(contours, pen, **kwargs) def mean_and_stdev(runs, loops): timings = [t / loops for t in runs] n = len(runs) mean = math.fsum(timings) / n stdev = (math.fsum([(x - mean) ** 2 for x in timings]) / n) ** 0.5 return mean, stdev def run( ufo, FontClass, union_func, pen_getter, repeat=REPEAT, number=NUMBER, **kwargs, ): all_runs = timeit.repeat( stmt="remove_overlaps(font, union_func, pen_getter, **kwargs)", setup="font = FontClass(ufo); list(font)", repeat=repeat, number=number, globals={ "ufo": ufo, "FontClass": FontClass, "union_func": union_func, "pen_getter": pen_getter, "remove_overlaps": remove_overlaps, "kwargs": kwargs, }, ) mean, stdev = mean_and_stdev(all_runs, number) class_module = FontClass.__module__.split(".")[0] func_module = union_func.__module__.split(".")[0] print( f"{class_module}::{func_module}: {mean:.3f} s +- {stdev:.3f} s per loop " f"(mean +- std. dev. of {repeat} run(s), {number} loop(s) each)" ) def main(): import sys try: ufo = sys.argv[1] except IndexError: sys.exit("usage: %s FONT.ufo [N]" % sys.argv[0]) if len(sys.argv) > 2: repeat = int(sys.argv[2]) else: repeat = REPEAT for FontClass in [DefconFont, UfoLib2Font]: for union_func, pen_getter, kwargs in [ (boolops_union, "getPointPen", {}), (pathops_union, "getPen", {}), # (pathops_union, "getPen", {"keep_starting_points": True}), ]: run( ufo, FontClass, union_func, pen_getter, repeat=repeat, **kwargs ) # import os # import shutil # font = UfoLib2Font(ufo) # font = DefconFont(ufo) # union_func = pathops_union # pen_getter = "getPen" # union_func = boolops_union # pen_getter = "getPointPen" # remove_overlaps(font, union_func, pen_getter) # output = ufo.rsplit(".", 1)[0] + "_ro.ufo" # if os.path.isdir(output): # shutil.rmtree(output) # font.save(output) if __name__ == "__main__": main()
Python
0.000001
a62e0bb3bfe192dcf080f28405a41ce7eb298b9b
Add tests for soc.logic.helper.prefixes.
tests/app/soc/logic/helper/test_prefixes.py
tests/app/soc/logic/helper/test_prefixes.py
#!/usr/bin/env python2.5 # # Copyright 2011 the Melange 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 soc.logic.helper.prefixes. """ __authors__ = [ '"Praveen Kumar" <praveen97uma@gmail.com>', ] import unittest from google.appengine.api import users from soc.logic.helper import prefixes from soc.models.organization import Organization from soc.models.program import Program from soc.models.site import Site from soc.models.user import User from soc.modules.gci.models.organization import GCIOrganization from soc.modules.gci.models.program import GCIProgram from soc.modules.gsoc.models.organization import GSoCOrganization from soc.modules.gsoc.models.program import GSoCProgram from soc.modules.gsoc.models.timeline import GSoCTimeline from soc.modules.seeder.logic.seeder import logic as seeder_logic class TestPrefixes(unittest.TestCase): """Tests for prefix helper functions for models with document prefixes. """ def setUp(self): self.user = seeder_logic.seed(User) self.program_timeline = seeder_logic.seed(GSoCTimeline) program_properties = {'timeline': self.program_timeline, 'scope': self.user} self.program = seeder_logic.seed(Program, program_properties) self.gsoc_program = seeder_logic.seed(GSoCProgram, program_properties) self.gci_program = seeder_logic.seed(GCIProgram, program_properties) self.site = seeder_logic.seed(Site,) self.organization = seeder_logic.seed(Organization) self.gsoc_organization = seeder_logic.seed(GSoCOrganization) self.gci_organization = seeder_logic.seed(GCIOrganization) self.user_key_name = self.user.key().name() self.program_key_name = self.program.key().name() self.gsoc_program_key_name = self.gsoc_program.key().name() self.gci_program_key_name = self.gci_program.key().name() self.site_key_name = self.site.key().name() self.org_key_name = self.organization.key().name() self.gsoc_org_key_name = self.gsoc_organization.key().name() self.gci_org_key_name = self.gci_organization.key().name() def testGetOrSetScope(self): """Not tested because it is used in soc.logic.models.survey and soc.logic.models.document and soc.logic.models will be removed. """ pass def testGetScopeForPrefix(self): """Tests if the scope for a given prefix and key_name is returned. """ prefix = 'user' key_name = self.user_key_name scope_returned = prefixes.getScopeForPrefix(prefix, key_name) self.assertEqual(scope_returned.key().name(), key_name) self.assertEqual(type(scope_returned), type(self.user)) prefix = 'site' key_name = self.site_key_name scope_returned = prefixes.getScopeForPrefix(prefix, key_name) self.assertEqual(scope_returned.key().name(), key_name) self.assertEqual(type(scope_returned), type(self.site)) prefix = 'org' key_name = self.org_key_name scope_returned = prefixes.getScopeForPrefix(prefix, key_name) self.assertEqual(scope_returned.key().name(), key_name) self.assertEqual(type(scope_returned), type(self.organization)) prefix = 'gsoc_org' key_name = self.gsoc_org_key_name scope_returned = prefixes.getScopeForPrefix(prefix, key_name) self.assertEqual(scope_returned.key().name(), key_name) self.assertEqual(type(scope_returned), type(self.gsoc_organization)) prefix = 'gci_org' key_name = self.gci_org_key_name scope_returned = prefixes.getScopeForPrefix(prefix, key_name) self.assertEqual(scope_returned.key().name(), key_name) self.assertEqual(type(scope_returned), type(self.gci_organization)) prefix = 'program' key_name = self.program_key_name scope_returned = prefixes.getScopeForPrefix(prefix, key_name) self.assertEqual(scope_returned.key().name(), key_name) self.assertEqual(type(scope_returned), type(self.program)) prefix = 'gsoc_program' key_name = self.gsoc_program_key_name scope_returned = prefixes.getScopeForPrefix(prefix, key_name) self.assertEqual(scope_returned.key().name(), key_name) self.assertEqual(type(scope_returned), type(self.gsoc_program)) prefix = 'gci_program' key_name = self.gci_program_key_name scope_returned = prefixes.getScopeForPrefix(prefix, key_name) self.assertEqual(scope_returned.key().name(), key_name) self.assertEqual(type(scope_returned), type(self.gci_program)) #When prefix is invalid. prefix = 'invalid_prefix' key_name = 'some_key_name' self.assertRaises( AttributeError, prefixes.getScopeForPrefix, prefix, key_name)
Python
0
115145da5063c47009e93f19aa5645e0dbb2580f
add missing migration for tests
tests/migrations/0002_auto_20210712_1629.py
tests/migrations/0002_auto_20210712_1629.py
# Generated by Django 2.2.24 on 2021-07-12 21:29 import django.contrib.gis.db.models.fields from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('tests', '0001_initial'), ] operations = [ migrations.CreateModel( name='Pizzeria', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('hq', django.contrib.gis.db.models.fields.PointField(srid=4326)), ('directions', django.contrib.gis.db.models.fields.LineStringField(srid=4326)), ('floor_plan', django.contrib.gis.db.models.fields.PolygonField(srid=4326)), ('locations', django.contrib.gis.db.models.fields.MultiPointField(srid=4326)), ('routes', django.contrib.gis.db.models.fields.MultiLineStringField(srid=4326)), ('delivery_areas', django.contrib.gis.db.models.fields.MultiPolygonField(srid=4326)), ('all_the_things', django.contrib.gis.db.models.fields.GeometryCollectionField(srid=4326)), ('rast', django.contrib.gis.db.models.fields.RasterField(srid=4326)), ], ), migrations.AlterField( model_name='chef', name='email_address', field=models.EmailField(max_length=254), ), migrations.AlterField( model_name='chef', name='twitter_profile', field=models.URLField(), ), migrations.AlterField( model_name='pizza', name='thickness', field=models.CharField(choices=[(0, 'thin'), (1, 'thick'), (2, 'deep dish')], max_length=50), ), migrations.AlterField( model_name='pizza', name='toppings', field=models.ManyToManyField(related_name='pizzas', to='tests.Topping'), ), ]
Python
0.000001
319d74685a0bd44ca0c62bf41dae2f9515b5e327
Add tests for nilrt_ip._load_config
tests/pytests/unit/modules/test_nilrt_ip.py
tests/pytests/unit/modules/test_nilrt_ip.py
import io import pytest import salt.modules.nilrt_ip as nilrt_ip from tests.support.mock import patch @pytest.fixture(autouse=True) def setup_loader(request): setup_loader_modules = {nilrt_ip: {}} with pytest.helpers.loader_mock(request, setup_loader_modules) as loader_mock: yield loader_mock @pytest.fixture def patched_config_file(): config_file = io.StringIO( """ [some_section] name = thing fnord = bar icanhazquotes = "this string is quoted" icannothazquotes = this string is unquoted number_value = 42 """ ) with patch("salt.utils.files.fopen", return_value=config_file): yield def test_when_config_has_quotes_around_string_they_should_be_removed( patched_config_file, ): expected_value = "this string is quoted" option = "icanhazquotes" actual_value = nilrt_ip._load_config("some_section", [option])[option] assert actual_value == expected_value def test_when_config_has_no_quotes_around_string_it_should_be_returned_as_is( patched_config_file, ): expected_value = "this string is unquoted" option = "icannothazquotes" actual_value = nilrt_ip._load_config("some_section", [option])[option] assert actual_value == expected_value @pytest.mark.parametrize( "default_value", [ 42, -99.9, ('"', "some value", 42, '"'), ['"', "a weird list of values", '"'], {"this": "dictionary", "has": "multiple values", 0: '"', -1: '"'}, ], ) def test_when_default_value_is_not_a_string_and_option_is_missing_the_default_value_should_be_returned( patched_config_file, default_value ): option = "non existent option" actual_value = nilrt_ip._load_config( "some_section", options=[option], default_value=default_value )[option] assert actual_value == default_value
Python
0
211e2963915589dcc735f90e9de304fa6bea3343
Work in progress. Added the braintree payment gateway code.
billing/gateways/braintree_payment_gateway.py
billing/gateways/braintree_payment_gateway.py
from billing import Gateway from billing.signals import * from billing.utils.credit_card import InvalidCard from django.conf import settings import braintree class BraintreePaymentGateway(Gateway): def _build_request_hash(self, options): request_hash = { "order_id": options.get("order_id", ""), "merchant_account_id": settings.BRAINTREE_MERCHANT_ACCOUNT_ID, } if options.get("customer"): name = options["customer"].get("name", "") try: first_name, last_name = name.split(" ", 1) except ValueError: first_name = name last_name = "" request_hash.update({ "customer": { "first_name": first_name, "last_name": last_name, "company": options["customer"].get("company", ""), "phone": options["customer"].get("phone", ""), "fax": options["customer"].get("fax", ""), "website": options["customer"].get("website", ""), "email": options["customer"].get("email", options.get("email", "")) } }) if options.get("billing_address"): name = options["billing_address"].get("name", "") try: first_name, last_name = name.split(" ", 1) except ValueError: first_name = name last_name = "" request_hash.update({ "billing": { "first_name": first_name, "last_name": last_name, "company": options["billing_address"].get("company", ""), "street_address": options["billing_address"].get("address1", ""), "extended_address": options["billing_address"].get("address2", ""), "locality": options["billing_address"].get("city", ""), "region": options["billing_address"].get("state", ""), "postal_code": options["billing_address"].get("zip", ""), "country_code_alpha2": options["billing_address"].get("country", "") } }) if options.get("shipping_address"): name = options["shipping_address"].get("name", "") try: first_name, last_name = name.split(" ", 1) except ValueError: first_name = name last_name = "" request_hash.update({ "shipping": { "first_name": first_name, "last_name": last_name, "company": options["shipping_address"].get("company", ""), "street_address": options["shipping_address"].get("address1", ""), "extended_address": options["shipping_address"].get("address2", ""), "locality": options["shipping_address"].get("city", ""), "region": options["shipping_address"].get("state", ""), "postal_code": options["shipping_address"].get("zip", ""), "country_code_alpha2": options["shipping_address"].get("country", "") } }) return request_hash def purchase(self, money, credit_card, options = None): if not options: options = {} if not self.validate_card(credit_card): raise InvalidCard("Invalid Card") request_hash = self._build_request_hash(options) request_hash["amount"] = money request_hash["credit_card"] = { "number": credit_card.number, "expiration_date": "%s/%s" %(credit_card.month, credit_card.year), "cardholder_name": "%s %s" %(credit_card.first_name, credit_card.last_name), "cvv": credit_card.verification_value, } braintree_options = options.get("options", {}) braintree_options.update({"submit_for_settlement": True}) request_hash.update({ "options": braintree_options }) response = braintree.Transaction.sale(request_hash) if response.is_success: status = "SUCCESS" transaction_was_successful.send(sender=self, type="purchase", response=response) else: status = "FAILURE" transaction_was_unsuccessful.send(sender=self, type="purchase", response=response) return {"status": status, "response": response} def authorize(self, money, credit_card, options = None): if not options: options = {} if not self.validate_card(credit_card): raise InvalidCard("Invalid Card") request_hash = self._build_request_hash(options) request_hash["amount"] = money request_hash["credit_card"] = { "number": credit_card.number, "expiration_date": "%s/%s" %(credit_card.month, credit_card.year), "cardholder_name": "%s %s" %(credit_card.first_name, credit_card.last_name), "cvv": credit_card.verification_value, } braintree_options = options.get("options", {}) if braintree_options: request_hash.update({ "options": braintree_options }) response = braintree.Transaction.sale(request_hash) if response.is_success: status = "SUCCESS" transaction_was_successful.send(sender=self, type="authorize", response=response) else: status = "FAILURE" transaction_was_unsuccessful.send(sender=self, type="authorize", response=response) return {"status": status, "response": response} def capture(self, money, authorization, options = None): response = braintree.Transaction.submit_for_settlement(authorization, money) if response.is_success: status = "SUCCESS" transaction_was_successful.send(sender=self, type="capture", response=response) else: status = "FAILURE" transaction_was_unsuccessful.send(sender=self, type="capture", response=response) return {"status": status, "response": response} def void(self, identification, options = None): response = braintree.Transaction.void(identification) if response.is_success: status = "SUCCESS" transaction_was_successful.send(sender=self, type="void", response=response) else: status = "FAILURE" transaction_was_unsuccessful.send(sender=self, type="void", response=response) return {"status": status, "response": response} def credit(self, money, identification, options = None): response = braintree.Transaction.refund(identification, money) if response.is_success: status = "SUCCESS" transaction_was_successful.send(sender=self, type="credit", response=response) else: status = "FAILURE" transaction_was_unsuccessful.send(sender=self, type="credit", response=response) return {"status": status, "response": response} def recurring(self, money, creditcard, options = None): pass def store(self, creditcard, options = None): pass def unstore(self, identification, options = None): pass
Python
0
80bb830979f0da2a7def0fd4dd00ed6ff516df0e
Add report generation script
tracking/reporting/generate_email_report.py
tracking/reporting/generate_email_report.py
#!/usr/bin/env python import sys import datetime import pymongo def get_week_start(date=None): """ Return a datetime corresponding to the start of the week for the given date E.g. if tuesday 7/8/2014 is passed in, monday 7/7/2014 00:00:00 would be returned """ if date is None: start_date = datetime.date.today() else: start_date = date week_start = start_date - datetime.timedelta(days=start_date.isoweekday()) return week_start def get_mongodb_client(): """ Return a mongodb client instance setup to access the correct database """ db_client = pymongo.MongoClient(host='db.mwt2.org', port=27017) db = db_client.module_usage return db def get_site_modulelist(start_date=None, top=None): """ Give up to the top N modules used per site """ db = get_mongodb_client() if start_date is None: start_date = get_week_start() else: start_date = get_week_start(start_date) if top is None: top = 10 site_list = {} for record in db.weekly_count.find({"date": start_date}, sort=('count', -1)): site = record['site'] if site not in site_list: site_list[site] = [] if len(site_list[site]) < top: site_list[site].append((record['module'], record['count'])) return site_list def get_top_modules(start_date, top=None): """ Return a json representation of the top N modules used in the last week """ db = get_mongodb_client() if start_date is None: start_date = get_week_start() else: start_date = get_week_start(start_date) if top is None: top = 10 module_list = [] for record in db.weekly_count.aggregate([{"$match": {"date": start_date.isoformat()}}, {"$group": {"_id": "$module", "sum": {"$sum": 1}}}, {"$sort": {"sum": -1}}, {"$limit": top}])['result']: module_list.append((record['_id'], record['sum'])) return module_list def get_top_sites(start_date, top=None): """ Return a json representation of the top N sites used in the last week """ db = get_mongodb_client() if top is None: top = 10 site_list = [] for record in db.weekly_count.aggregate([{"$match": {"date": start_date.isoformat()}}, {"$group": {"_id": "$site", "sum": {"$sum": 1}}}, {"$sort": {"sum": -1}}, {"$limit": top}])['result']: site_list.append((record['_id'], record['sum'])) return site_list def get_moduleloads(start_date, top=None): """ Return a json representation of the number of times modules where used in the week containing start_date """ db = get_mongodb_client() if top is None: top = 10 return db.weekly_count.aggregate([{"$match": {"date": start_date.isoformat()}}, {"$group": {"_id": "$date", "sum": {"$sum": 1}}}, {"$sort": {"sum": -1}}, {"$limit": top}])['result']['sum'] def generate_report(email=False): """ Generate a report of module usage over the week and optionally email it :param email: boolean that indicates whether to email report or not :return: None """ start_date = get_week_start() report_text = "" report_text += "{0:^80}\n".format("Modules usage report for week of " + start_date) report_text += "{0:-^80}\n".format(' Top 10 modules used') report_text += "\n\n" report_text += "|{0:^30}|{1:^30}|".format('Module', '# of times used') module_list = get_top_modules(start_date) for module, count in module_list: report_text += "|{0:^30}|{1:^30}|".format(module, count) report_text += "\n\n" report_text += "{0:-^80}\n".format(' Top 10 sites used') report_text += "\n\n" report_text += "|{0:^30}|{1:^30}|".format('Site', '# of times used') site_list = get_top_sites(start_date) for site, count in site_list: report_text += "|{0:^30}|{1:^30}|".format(site, count) report_text += "\n\n" report_text += "{0:-^80}\n".format(' Top 10 modules used at each site') report_text += "\n\n" report_text += "|{0:^20}|{1:^20}|{0:^20}|".format('Site', 'Module', '# of times used') site_module_list = get_site_modulelist(start_date) sites = site_module_list.keys() sites.sort() for site in sites: for module, count in sites[site]: report_text += "|{0:^20}|{1:^20}|{0:^20}|".format(site, module, count) report_text += "\n\n" if email: pass else: sys.stdout.write(report_text) if __name__ == "__main__": if len(sys.argv) == 2 and sys.argv[1] == 'email': generate_report(email=True) else: generate_report()
Python
0.000001
e810ecb5362496f72485220ab4e9cecd5467b3a6
kill leftover webpagereplay servers.
build/android/pylib/utils/test_environment.py
build/android/pylib/utils/test_environment.py
# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import logging import os import psutil import signal from pylib import android_commands def _KillWebServers(): for s in [signal.SIGTERM, signal.SIGINT, signal.SIGQUIT, signal.SIGKILL]: signalled = [] for server in ['lighttpd', 'webpagereplay']: for p in psutil.process_iter(): try: if not server in ' '.join(p.cmdline): continue logging.info('Killing %s %s %s', s, server, p.pid) p.send_signal(s) signalled.append(p) except Exception as e: logging.warning('Failed killing %s %s %s', server, p.pid, e) for p in signalled: try: p.wait(1) except Exception as e: logging.warning('Failed waiting for %s to die. %s', p.pid, e) def CleanupLeftoverProcesses(): """Clean up the test environment, restarting fresh adb and HTTP daemons.""" _KillWebServers() did_restart_host_adb = False for device in android_commands.GetAttachedDevices(): adb = android_commands.AndroidCommands(device, api_strict_mode=True) # Make sure we restart the host adb server only once. if not did_restart_host_adb: adb.RestartAdbServer() did_restart_host_adb = True adb.RestartAdbdOnDevice() adb.EnableAdbRoot() adb.WaitForDevicePm()
# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import logging import os import psutil from pylib import android_commands def _KillWebServers(): for retry in xrange(5): for server in ['lighttpd', 'web-page-replay']: pids = [p.pid for p in psutil.process_iter() if server in p.name] for pid in pids: try: logging.warning('Killing %s %s', server, pid) os.kill(pid, signal.SIGQUIT) except Exception as e: logging.warning('Failed killing %s %s %s', server, pid, e) def CleanupLeftoverProcesses(): """Clean up the test environment, restarting fresh adb and HTTP daemons.""" _KillWebServers() did_restart_host_adb = False for device in android_commands.GetAttachedDevices(): adb = android_commands.AndroidCommands(device, api_strict_mode=True) # Make sure we restart the host adb server only once. if not did_restart_host_adb: adb.RestartAdbServer() did_restart_host_adb = True adb.RestartAdbdOnDevice() adb.EnableAdbRoot() adb.WaitForDevicePm()
Python
0.000002
6f90115ce12b0577c8be9737a29d3062e906d2ef
Create aqgd.py
qiskit/aqua/components/optimizers/aqgd.py
qiskit/aqua/components/optimizers/aqgd.py
# -*- coding: utf-8 -*- # Copyright 2018 IBM. # # 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 from copy import deepcopy from numpy import pi, absolute, array, zeros from qiskit.aqua.components.optimizers import Optimizer logger = logging.getLogger(__name__) class AQGD(Optimizer): """Analytic Quantum Gradient Descent (AQGD) optimizer class. Performs optimization by gradient descent where gradients are evaluated "analytically" using the quantum circuit evaluating the objective function. """ CONFIGURATION = { 'name': 'AQGD', 'description': 'Analytic Quantum Gradient Descent Optimizer', 'input_schema': { '$schema': 'http://json-schema.org/schema#', 'id': 'aqgd_schema', 'type': 'object', 'properties': { 'maxiter': { 'type': 'integer', 'default': 1000 }, 'eta': { 'type': 'number', 'default': 1e-2 }, 'tol': { 'type': ['number', 'null'], 'default': 1e-4 }, 'disp': { 'type': 'boolean', 'default': False }, }, 'additionalProperties': False }, 'support_level': { 'gradient': Optimizer.SupportLevel.ignored, 'bounds': Optimizer.SupportLevel.ignored, 'initial_point': Optimizer.SupportLevel.required }, 'options': ['maxiter', 'eta', 'tol', 'disp'], 'optimizer': ['local'] } def __init__(self, maxiter=1000, eta=2.0, tol=None, disp=False, momentum = 0.25): """ Constructor. Performs Analytical Quantum Gradient Descent (AQGD). Args: maxiter (int): Maximum number of function evaluations. eta (float): The coefficient of the gradient update. Increasing this value results in larger step sizes: param = previous_param - eta * deriv tol (float): The convergence criteria that must be reached before stopping. Optimization stops when: absolute(loss - previous_loss) < tol disp (bool): Set to true to display convergence messages. momentum (float): Bias towards the previous gradient momentum in current update. Must be within the bounds: [0,1) """ self.validate(locals()) super().__init__() self._eta = eta self._maxiter = maxiter self._tol = tol if tol is not None else 1e-6 self._disp = disp self._momentum_coeff = momentum assert momentum >= 0 and momentum < 1, ("Momentum must be within bounds: [0,1) however " +str(momentum)+" was given.") def deriv(self, j, params, obj): """ Obtains the analytical quantum derivative of the objective function with respect to the jth parameter. Args: j (int): Index of the parameter to compute the derivative of. params (array): Current value of the parameters to evaluate the objective function at. obj (callable): Objective function. Returns: (float) The derivative of the objective function w.r.t. j """ # create a copy of the parameters with the positive shift plus_params = deepcopy(params) plus_params[j] += pi / 2 # create a copy of the parameters with the negative shift minus_params = deepcopy(params) minus_params[j] -= pi / 2 # return the derivative value return 0.5 * (obj(plus_params) - obj(minus_params)) def update(self, j, params, deriv, mprev): ''' Updates the jth parameter based on the derivative and previous momentum Args: j (int): Index of the parameter to compute the derivative of. params (array): Current value of the parameters to evaluate the objective function at. deriv (float): Value of the derivative w.r.t. the jth parameter mprev (array): Array containing all of the parameter momentums ''' mnew = self._eta * (deriv * (1-self._momentum_coeff) + mprev[j] * self._momentum_coeff) params[j] -= mnew return params, mnew def converged(self, objval, n = 2): ''' Determines if the objective function has converged by finding the difference between the current value and the previous n values. Args: objval (float): Current value of the objective function. n (int): Number of previous steps which must be within the convergence criteria in order to be considered converged. Using a larger number will prevent the optimizer from stopping early. Returns: (bool) Whether or not the optimization has converged. ''' if not hasattr(self, '_previous_loss'): self._previous_loss = [objval + 2 * self._tol] * n if all([ absolute(objval - prev) < self._tol for prev in self._previous_loss ]): # converged return True # store previous function evaluations for i in range(n): if i < n - 1: self._previous_loss[i] = self._previous_loss[i+1] else: self._previous_loss[i] = objval return False def optimize(self, num_vars, objective_function, gradient_function=None, variable_bounds=None, initial_point=None): super().optimize(num_vars, objective_function, gradient_function, variable_bounds, initial_point) params = array(initial_point) it = 1 momentum = zeros(shape=(num_vars,)) objval = objective_function(params) if self._disp: print("Iteration: "+str(it)+" \t| Energy: "+str(objval)) minobj = objval minparams = params while it < self._maxiter and not self.converged(objval): for j in range(num_vars): # update parameters in order based on quantum gradient derivative = self.deriv(j, params, objective_function) params, momentum[j] = self.update(j, params, derivative, momentum) # check the value of the objective function objval = objective_function(params) # keep the best parameters if objval < minobj: minobj = objval minparams = params # update the iteration count it += 1 if self._disp: print("Iteration: "+str(it)+" \t| Energy: "+str(objval)) return minparams, minobj, it
Python
0
082f28198b76c93ee7dc06ed3ea68bfe9a596b97
create Spider for France website of McDonalds
locations/spiders/mcdonalds_fr.py
locations/spiders/mcdonalds_fr.py
# -*- coding: utf-8 -*- import scrapy import json import re from locations.items import GeojsonPointItem class McDonalsFRSpider(scrapy.Spider): name = "mcdonalds_fr" allowed_domains = ["www.mcdonalds.fr"] start_urls = ( 'https://prod-dot-mcdonaldsfrance-storelocator.appspot.com/api/store/nearest?center=2.695842500000026:47.0169289&limit=1000&authToken=26938DBF9169A7F39C92BDCF1BA7A&db=prod', ) def store_hours(self, data): day_groups = [] this_day_group = {} weekdays = ['Su', 'Mo', 'Th', 'We', 'Tu', 'Fr', 'Sa'] for day_hour in data: if day_hour['idx'] > 7: continue hours = '' start, end = day_hour['value'].split("-")[0].strip(), day_hour['value'].split("-")[1].strip() short_day = weekdays[day_hour['idx'] - 1] hours = '{}:{}-{}:{}'.format(start[:2], start[3:], end[:2], end[3:]) if not this_day_group: this_day_group = { 'from_day': short_day, 'to_day': short_day, 'hours': hours, } elif hours == this_day_group['hours']: this_day_group['to_day'] = short_day elif hours != this_day_group['hours']: day_groups.append(this_day_group) this_day_group = { 'from_day': short_day, 'to_day': short_day, 'hours': hours, } day_groups.append(this_day_group) if not day_groups: return None opening_hours = '' if len(day_groups) == 1 and not day_groups[0]: return None if len(day_groups) == 1 and day_groups[0]['hours'] in ('00:00-23:59', '00:00-00:00'): opening_hours = '24/7' else: for day_group in day_groups: if day_group['from_day'] == day_group['to_day']: opening_hours += '{from_day} {hours}; '.format(**day_group) else: opening_hours += '{from_day}-{to_day} {hours}; '.format(**day_group) opening_hours = opening_hours [:-2] return opening_hours def parse(self, response): match = re.search(r'(HTTPResponseLoaded\()({.*})(\))', response.body_as_unicode()) if not match: return results = json.loads(match.groups()[1]) results = results["poiList"] for item in results: data = item["poi"] properties = { 'city': data['location']['city'], 'ref': data['id'], 'addr_full': data['location']['streetLabel'], 'phone': data['datasheet']['tel'], 'state': data['location']['countryISO'], 'postcode': data['location']['postalCode'], 'name': data['name'], 'lat': data['location']['coords']['lat'], 'lon': data['location']['coords']['lon'], 'website': 'https://www.restaurants.mcdonalds.fr' + data['datasheet']['web'] } opening_hours = self.store_hours(data['datasheet']['descList']) if opening_hours: properties['opening_hours'] = opening_hours yield GeojsonPointItem(**properties)
Python
0
6afc97b8f262555b3f706bbf37a370bedd3291ba
create the Spider for Hong Kong of McDonalds
locations/spiders/mcdonalds_hk.py
locations/spiders/mcdonalds_hk.py
# -*- coding: utf-8 -*- import scrapy import json import re from locations.items import GeojsonPointItem class McDonalsHKSpider(scrapy.Spider): name = "mcdonalds_hk" allowed_domains = ["www.mcdonalds.com.hk"] start_urls = ( 'http://www.mcdonalds.com.hk/googleapps/GoogleHongKongSearchAction.do?method=searchLocation&searchTxtLatlng=(22.25%2C%20114.16669999999999)&actionType=searchRestaurant&country=hk&language=en', ) def normalize_time(self, time_str): match = re.search(r'([0-9]{1,2}):([0-9]{1,2}) ([ap.m]{2})', time_str) if not match: match = re.search(r'([0-9]{1,2}) ([ap.m]{2})', time_str) h, am_pm = match.groups() m = "0" else: h, m, am_pm = match.groups() return '%02d:%02d' % ( int(h) + 12 if am_pm == 'p.' else int(h), int(m), ) def store_hours(self, data): day_groups = [] this_day_group = {} weekdays = ['Mo', 'Th', 'We', 'Tu', 'Fr', 'Sa', 'Su'] if "timeings" not in data.keys(): return None day_hours = data["timeings"] index = 0 for day_hour in day_hours: hours = '' start = day_hour['openTime'] if not start: continue end = day_hour['closeTime'] short_day = weekdays[index] hours = '{}:{}-{}:{}'.format(start[:2], start[3:], end[:2], end[3:]) if not this_day_group: this_day_group = { 'from_day': short_day, 'to_day': short_day, 'hours': hours, } elif hours == this_day_group['hours']: this_day_group['to_day'] = short_day elif hours != this_day_group['hours']: day_groups.append(this_day_group) this_day_group = { 'from_day': short_day, 'to_day': short_day, 'hours': hours, } index = index + 1 day_groups.append(this_day_group) if not day_groups: return None opening_hours = '' if len(day_groups) == 1 and day_groups[0]['hours'] in ('00:00-23:59', '00:00-00:00'): opening_hours = '24/7' else: for day_group in day_groups: if day_group['from_day'] == day_group['to_day']: opening_hours += '{from_day} {hours}; '.format(**day_group) else: opening_hours += '{from_day}-{to_day} {hours}; '.format(**day_group) opening_hours = opening_hours [:-2] return opening_hours def parse_address(self, address): address = address['address'] match = re.search(r'<p>(.*)<', address) data = match.groups() if data: return data[0] return None def parse(self, response): results = json.loads(response.body_as_unicode()) results = results['results'] for data in results: properties = { 'city': data['district'], 'ref': data['id'], 'phone': data['telephone'].strip(), 'lon': data['longitude'], 'lat': data['latitude'], 'name': data['name'] } address = self.parse_address(data['addresses'][0]) if address: properties['addr_full'] = address opening_hours = self.store_hours(data) if opening_hours: properties['opening_hours'] = opening_hours yield GeojsonPointItem(**properties)
Python
0
d77cb643c7762401209f1f9d9693ee352e6672cb
Create mqttEampleRemoteBrain.py
home/kyleclinton/mqttEampleRemoteBrain.py
home/kyleclinton/mqttEampleRemoteBrain.py
from java.lang import String from time import sleep pi = Runtime.createAndStart("pi","RasPi") #Load Pub/Sub Service (MQTT) execfile("../py_scripts/mqttPubSubConfig.py") # Add in controller for head, neck and antenna servos SHOULD be using i2c 16 servo controller #Load Juniors mouth! execfile("../py_scripts/juniors_voice.py") #Load Juniors Eyes! execfile("../py_scripts/juniors_eyes_4.py") #####for testing mouth.speakBlocking("Testing 1, 2, 3") drawEyes() sleep(2) drawClosedEyes() sleep(1) drawEyes() mqtt.subscribe("myrobotlab/speaking", 0) #mqtt.publish("hello myrobotlab world") python.subscribe("mqtt", "publishMqttMsgString") # or mqtt.addListener("publishMqttMsgString", "python") # MQTT call-back # publishMqttMsgString --> onMqttMsgString(msg) def onMqttMsgString(msg): # print "message : ", msg mouth.speakBlocking(msg[0]) print "message : ",msg[0] print "topic : ",msg[1] mqtt.publish("What is your name?")
Python
0.000013
188c4af91f2a3dbb98997da6cdc3e43df488e791
add ALCE examples
examples/alce.py
examples/alce.py
#!/usr/bin/env python3 """ Cost-Senstive Multi-Class Active Learning` """ import copy import os import numpy as np from sklearn.model_selection import StratifiedShuffleSplit import sklearn.datasets from sklearn.linear_model import LinearRegression # libact classes from libact.base.dataset import Dataset, import_libsvm_sparse from libact.models import LogisticRegression from libact.query_strategies import ActiveLearningWithCostEmbedding as ALCE from libact.query_strategies import UncertaintySampling, RandomSampling from libact.labelers import IdealLabeler from libact.utils import calc_cost def run(trn_ds, tst_ds, lbr, model, qs, quota, cost_matrix): C_in, C_out = [], [] for _ in range(quota): # Standard usage of libact objects ask_id = qs.make_query() X, _ = zip(*trn_ds.data) lb = lbr.label(X[ask_id]) trn_ds.update(ask_id, lb) model.train(trn_ds) trn_X, trn_y = zip(*trn_ds.get_labeled_entries()) tst_X, tst_y = zip(*tst_ds.get_labeled_entries()) C_in = np.append(C_in, calc_cost(trn_y, model.predict(trn_X), cost_matrix)) C_out = np.append(C_out, calc_cost(tst_y, model.predict(tst_X), cost_matrix)) return C_in, C_out def split_train_test(test_size, n_labeled): data = sklearn.datasets.fetch_mldata('segment') X = data['data'] target = np.unique(data['target']) # mapping the targets to 0 to n_classes-1 y = np.array([np.where(target == i)[0][0] for i in data['target']]) sss = StratifiedShuffleSplit(1, test_size=test_size, random_state=1126) for trn_idx, tst_idx in sss.split(X, y): X_trn, X_tst = X[trn_idx], X[tst_idx] y_trn, y_tst = y[trn_idx], y[tst_idx] trn_ds = Dataset(X_trn, np.concatenate( [y_trn[:n_labeled], [None] * (len(y_trn) - n_labeled)])) tst_ds = Dataset(X_tst, y_tst) fully_labeled_trn_ds = Dataset(X_trn, y_trn) return trn_ds, tst_ds, y_trn, fully_labeled_trn_ds def main(): # Specifiy the parameters here: test_size = 0.33 # the percentage of samples in the dataset that will be # randomly selected and assigned to the test set n_labeled = 10 # number of samples that are initially labeled # Load dataset trn_ds, tst_ds, y_train, fully_labeled_trn_ds = \ split_train_test(test_size, n_labeled) trn_ds2 = copy.deepcopy(trn_ds) trn_ds3 = copy.deepcopy(trn_ds) lbr = IdealLabeler(fully_labeled_trn_ds) n_classes = len(np.unique(y_train)) # = 7 cost_matrix = np.random.RandomState(1126).rand(n_classes, n_classes) np.fill_diagonal(cost_matrix, 0) quota = 500 # number of samples to query # Comparing UncertaintySampling strategy with RandomSampling. # model is the base learner, e.g. LogisticRegression, SVM ... etc. qs = UncertaintySampling(trn_ds, method='lc', model=LogisticRegression()) model = LogisticRegression() E_in_1, E_out_1 = run(trn_ds, tst_ds, lbr, model, qs, quota, cost_matrix) qs2 = RandomSampling(trn_ds2) model = LogisticRegression() E_in_2, E_out_2 = run(trn_ds2, tst_ds, lbr, model, qs2, quota, cost_matrix) qs3 = ALCE(trn_ds3, cost_matrix, LinearRegression()) model = LogisticRegression() E_in_3, E_out_3 = run(trn_ds3, tst_ds, lbr, model, qs3, quota, cost_matrix) print("Uncertainty: ", E_out_1[::20].tolist()) print("Random: ", E_out_2[::20].tolist()) print("ALCE: ", E_out_3[::20].tolist()) if __name__ == '__main__': main()
Python
0
fae70ff8284e01b1b850e0b03ab2c651f1808f24
add a little exercise which I faced with in this article: http://habrahabr.ru/post/200190/
python/habra_task/habratask_main.py
python/habra_task/habratask_main.py
""" Recently I have seen this article http://habrahabr.ru/post/200190/ so I have decided to find the solution of this task by myself. Short description of this task for a case if the link above will be broken: 1. we have a two-dimensional positive integer numbers array 2. if we will display this data in the manner of a walls (see image below) then we need to calculate the volume which could be filled by an imaginary water ? ___ ___ |7 7|_ |7 7|_ _ | 6| _ | 6| |5| | | fill with water |5|x x x x x| | volume is | | _ | | ----------------> | |x x x x x| | -----------> 19 _| | |3| _ | | _| |x|3|x x x| | |2 |_| |_|2|_| | |2 |x| |x|2|x| | |____1___1___1______| |____1___1___1______| 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 My solution is: 1. We are moving step by step from left to right. 2. If we are stepping down then we put the previous cell value with the current cell index into stack. 3. If we are stepping up then: 3.1. We are popping one value from the stack and flood all cells between stacked index and current step index up to the floodLevel = min(stackedValue, currentValue). 3.2. Increase Result value in the next way: result += (currentStepIndex - stackedIndex) * (min(stackedValue, currentValue) - prevValue) 3.3. calculate difference between currentValue and stackedValue. If the currentValue > stackedValue then pop next value from the stack and repeat steps (3.1 - 3.3). If the currentValue < stackedValue then put this stackedValue with its stackedIndex back to stack. That's all, we will always have a filled holes from the left, and the highest wall which we were visited before will be always stored on the bottom of this stack (of course if it wasn't already filled up to its edge, in that case the stack would be empty). """ import random def generateData(): """ Generates source data for this exercise """ # data = [2, 5, 1, 3, 1, 2, 1, 7, 7, 6] data = [int(10 * random.random()) for i in xrange(10)] return data def calculate(data): """ Main program algorithm with some debug instruments """ stack = [] result = 0 prevVal = 0 filledCells = {} # for debug purpose only for col in range(0, len(data)): val = data[col] if val < prevVal: stack.append((col, prevVal)) elif val > prevVal: while len(stack) > 0 and val > prevVal: stackItem = stack.pop(-1) if val >= stack[-1][1] else stack[-1] floodLevel = min(val, stackItem[1]) result += (col - stackItem[0]) * (floodLevel - prevVal) if __debug__: for row, cell in [(row, cell) for row in range(prevVal, floodLevel) for cell in range(stackItem[0], col)]: filledCells[row, cell] = True display(data, filledCells, col, stack, result) prevVal = floodLevel prevVal = val display(data, filledCells, len(data) - 1, stack, result) def display(data, filledCells, step, stack, result): """ Renders current state of program execution in a human readable format """ maxValue = max(data) colCount = len(data) valueWidth = len(str(maxValue)) stackHeight = 5 text = '' for row in range(maxValue + 1, -1, -1): emptyFill = '_' if row == 0 else ' ' line = '' line += '|' if data[0] > row else emptyFill # put left side of first column for col in range(0, colCount): # fill inner column space if filledCells.has_key((row, col)): # fill cell with water line += ('{:' + emptyFill + '^' + str(valueWidth) + '}').format('x') elif data[col] == row + 1: line += ('{:' + emptyFill + '>' + str(valueWidth) + '}').format(data[col]) elif data[col] == row: line += '_' * valueWidth else: line += emptyFill * valueWidth # add right column border if ((col < colCount - 1 and (data[col] <= row < data[col + 1] or data[col] > row >= data[col + 1])) or (col == colCount - 1 and data[col] > row)): line += '|' elif col < colCount - 1 and data[col] == data[col + 1] == row: line += '_' else: line += emptyFill text += line + '\n' # fill bottom row with an indexes of array for col in range(0, colCount): text += (' {:>' + str(valueWidth) + '}').format(col) text += ' \n' # add current step indicator for col in range(0, colCount): text += (' {:^' + str(valueWidth) + '}').format('^' if col == step else ' ') text += " \n" # render stack text += '\nstack:\n' colIndexWidth = len(str(len(data))) for row in range(max(len(stack), stackHeight), 0, -1): if row >= len(stack): text += '[' + (' ' * (colIndexWidth + valueWidth + 4)) + ']\n' else: text += ('[ {1:>' + str(colIndexWidth) + '}, {1:>' + str(valueWidth) + '} ]\n').format(stack[row][0], stack[row][1]) text += '[' + ('_' * (colIndexWidth + valueWidth + 4)) + ']\n' # render sum text += '\nresult = {0}'.format(result) print text if __name__ == '__main__': data = generateData() calculate(data)
Python
0.000002
3fb4d7b630fb7a4b34dcc4e1b72947e61f73a80f
Create script to dowload requisite test urls.
TestData/download_test_data.py
TestData/download_test_data.py
def set_test_db(): from sys import path path.insert(0, "..") from MyEdgarDb import get_list_sec_filings, get_cik_ticker_lookup_db, lookup_cik_ticker get_list_sec_filings (7, 'test_idx.db') get_cik_ticker_lookup_db ('test_idx.db') def download_test_data(): import sqlite3 from datetime import datetime import pandas as pd testDir = "..\\TestData\\" testTickers = { "AAPL": [datetime(2014, 8, 1), datetime(2018, 8, 1)], "ACLS": [datetime(2014, 8, 31), datetime(2018, 8, 31)], "ADSK": [datetime(2014, 4, 15), datetime(2018, 4, 15)], "ALEX": [datetime(2015, 12, 31), datetime(2019, 12, 31)], "MMM": [datetime(2015, 7, 1), datetime(2019, 7, 1)], "NRP": [datetime(2015, 12, 31), datetime(2019, 12, 31)], "NVDA": [datetime(2015, 12, 31), datetime(2019, 12, 31)] } conn3 = sqlite3.connect('test_idx.db') cursor = conn3.cursor() for ticker in testTickers: #cursor.execute('''SELECT * FROM idx WHERE Symbol=?;''', ("ABBV",)) cursor.execute('''SELECT * FROM cik_ticker_name WHERE ticker=?;''',(ticker,)) res = cursor.fetchall() print(res) cursor.execute('''SELECT * FROM idx WHERE cik=?;''', (res[0][0],)) recs = cursor.fetchall() print(len(recs)) names = list(map(lambda x: x[0], cursor.description)) #print(names) df = pd.DataFrame(data=recs, columns=names) df['date'] = pd.to_datetime(df['date']) beginDate = testTickers[ticker][0] endDate = testTickers[ticker][1] df1 = df[(df.date >= beginDate) & (df.date <= endDate)] ## Sort by date in descending order (most recent is first) df1.sort_values(by=['date'], inplace=True, ascending=False) df1[df1.type == "10-Q"].to_csv(testDir+ticker.lower()+"_all_10qs.csv", index=None) df1[df1.type == "10-K"].to_csv(testDir+ticker.lower()+"_all_10ks.csv", index=None) conn3.close() if __name__ == "__main__": #set_test_db() download_test_data()
Python
0
df8206b01eb2298651099c5e701d269a0e6cd8c6
add test case for tuple attribute error #35
test/test_flake8.py
test/test_flake8.py
import subprocess def test_call_flake8(tmpdir): tmp = tmpdir.join('tmp.py') tmp.write('') output = subprocess.check_output( ['flake8', str(tmp)], stderr=subprocess.STDOUT, ) assert output == b''
Python
0
ecae1fa205c88d1d503663c5fbec80a1943146ad
add resources comparator
pynodegl-utils/pynodegl_utils/tests/cmp_resources.py
pynodegl-utils/pynodegl_utils/tests/cmp_resources.py
#!/usr/bin/env python # # Copyright 2020 GoPro Inc. # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # import os import csv import tempfile import pynodegl as ngl from .cmp import CompareSceneBase, get_test_decorator _COLS = ( 'Textures memory', 'Buffers count', 'Buffers total', 'Blocks count', 'Blocks total', 'Medias count', 'Medias total', 'Textures count', 'Textures total', 'Computes', 'GraphicCfgs', 'Renders', 'RTTs', ) class _CompareResources(CompareSceneBase): def __init__(self, scene_func, columns=_COLS, **kwargs): super(_CompareResources, self).__init__(scene_func, width=320, height=240, scene_wrap=self._scene_wrap, **kwargs) self._columns = columns def _scene_wrap(self, scene): # We can't use NamedTemporaryFile because we may not be able to open it # twice on some systems fd, self._csvfile = tempfile.mkstemp(suffix='.csv', prefix='ngl-test-resources-') os.close(fd) return ngl.HUD(scene, export_filename=self._csvfile) def get_out_data(self): for frame in self.render_frames(): pass # filter columns with open(self._csvfile) as csvfile: reader = csv.DictReader(csvfile) data = [self._columns] for row in reader: data.append([v for k, v in row.items() if k in self._columns]) # rely on base string diff ret = '' for row in data: ret += ','.join(row) + '\n' os.remove(self._csvfile) return ret test_resources = get_test_decorator(_CompareResources)
Python
0.000001
885aac79c2e31fc74dc143fc2527e02c2c0a8941
add duckduckgo crawler
scholarly_citation_finder/api/crawler/Duckduckgo.py
scholarly_citation_finder/api/crawler/Duckduckgo.py
#!/usr/bin/python # -*- coding: utf-8 -*- import requests from bs4 import BeautifulSoup class Duckduckgo: API_URL = 'https://duckduckgo.com/html/' CSS_RESULT_ELEMENT = 'a' CSS_RESULT_ELEMENT_CLASS = 'large' CSS_RESULT_TYPE_ELEMENT = 'span' CSS_RESULT_TYPE_ELEMENT_CLASS = 'result__type' def __init__(self): pass def query(self, keywords, filetype='pdf'): ''' :see: https://duck.co/help/results/syntax :see: https://duckduckgo.com/params :param keywords: :param filetype: ''' if filetype: keywords = 'filetype:{} {}'.format(filetype, keywords) r = requests.get(self.API_URL, {'q': keywords}) if r.status_code != 200: raise Exception('Expected response code 200, but is {}'.format(r.status_code)) self.__get_links(r.text) def __get_links(self, html): soup = BeautifulSoup(html, 'lxml') for link in soup.findAll(self.CSS_RESULT_ELEMENT, class_=self.CSS_RESULT_ELEMENT_CLASS): url, title, type = self.__get_link_items(link) print('%s: %s "%s"' % (type, url, title)) def __get_link_items(self, html_a_element): url = html_a_element.get('href') title = html_a_element.text if url: soup = BeautifulSoup(str(html_a_element), 'lxml') type = soup.find(self.CSS_RESULT_TYPE_ELEMENT, class_=self.CSS_RESULT_TYPE_ELEMENT_CLASS) if type: type = type.text return url, title, type if __name__ == '__main__': searchengine = Duckduckgo() searchengine.query('kernel completion for learning consensus support vector machines in bandwidth limited sensor networks')
Python
0.999999
60f01c055405fea9e3672821a1188774f7517707
add 140
vol3/140.py
vol3/140.py
if __name__ == "__main__": L = 30 sqrt5 = 5 ** 0.5 f = [7, 14, 50, 97] for i in range(L - 4): f.append(7 * f[-2] - f[-4]) print sum(int(x / sqrt5) - 1 for x in f)
Python
0.999989
7d6b04bc60270d357fdf9401174ece249f9f3568
add 153
vol4/153.py
vol4/153.py
import math import fractions if __name__ == "__main__": L = 10 ** 8 ans = 0 for i in xrange(1, L + 1): ans += (L / i) * i if i * i < L: j = 1 while j <= i: if fractions.gcd(i, j) == 1: div = i * i + j * j k = 1 v = 2 * i if i == j else 2 * (i + j) while div * k <= L: ans += (L / (div * k)) * k * v k += 1 j += 1 print ans
Python
0.999996
b67250ca02705d47a124353207a1f60546919c0f
add versiondb.Manifest class
codekit/versiondb.py
codekit/versiondb.py
"""versionDB related utility functions.""" from codekit.codetools import debug from public import public import logging import re import requests import textwrap default_base_url =\ 'https://raw.githubusercontent.com/lsst/versiondb/master/manifests' @public def setup_logging(verbosity=0): # enable requests debugging # based on http://docs.python-requests.org/en/latest/api/?highlight=debug if verbosity > 1: from http.client import HTTPConnection HTTPConnection.debuglevel = 1 requests_log = logging.getLogger("urllib3") requests_log.setLevel(logging.DEBUG) requests_log.propagate = True # ~duplicates the Manifest class in lsst_buid/python/lsst/ci/prepare.py but # operates over http rather than on a local git clone class Manifest(object): """Representation of a "versionDB" manifest. AKA `bNNNN`. AKA `bxxxx`. AKA `BUILD`. AKA `BUILD_ID`. AKA `manifest`. Parameters ---------- name: str Name of the manifest . Eg., `b1234` base_url: str Base url to the path for `manifest` files`. Optional. Eg.: `https://raw.githubusercontent.com/lsst/versiondb/master/manifests` """ def __init__(self, name, base_url=None): self.name = name self.base_url = default_base_url if base_url: self.base_url = base_url def __fetch_manifest_file(self): # construct url tag_url = '/'.join((self.base_url, self.name + '.txt')) debug("fetching: {url}".format(url=tag_url)) r = requests.get(tag_url) r.raise_for_status() self.__text = r.text def __parse_manifest_text(self): products = {} for line in self.__text.splitlines(): if not isinstance(line, str): line = str(line, 'utf-8') # skip commented out and blank lines if line.startswith('#') or line == '': continue if line.startswith('BUILD'): pat = r'^BUILD=(b\d{4})$' m = re.match(pat, line) if not m: raise RuntimeError(textwrap.dedent(""" Unparsable versiondb manifest: {line} """).format( line=line, )) parsed_name = m.group(1) continue # min of 3, max of 4 fields fields = line.split()[0:4] (name, sha, eups_version) = fields[0:3] products[name] = { 'name': name, 'sha': sha, 'eups_version': eups_version, 'dependencies': [], } # the 4th field, if present, is a csv list of deps if len(fields) == 4: dependencies = fields[3:4][0].split(',') products[name]['dependencies'] = dependencies # sanity check tag name in the file if not self.name == parsed_name: raise RuntimeError(textwrap.dedent(""" name in data : ({dname}) does not match file name: ({fname})\ """).format( dname=parsed_name, fname=self.name, )) self.__products = products def __process(self): self.__fetch_manifest_file() self.__parse_manifest_text() @property def products(self): """Return Dict of products described by the manifest""" # check for cached data try: return self.__products except AttributeError: pass self.__process() return self.__products
Python
0
f6f12b1194fde3fc4dc355535ca88f472962d3a3
add camera color histogram
python/ocv4/camera_color_histogram.py
python/ocv4/camera_color_histogram.py
#!/usr/bin/env python ''' Video histogram sample to show live histogram of video Keys: ESC - exit ''' # Python 2/3 compatibility from __future__ import print_function import numpy as np import cv2 as cv # built-in modules import sys # local modules import video class App(): def set_scale(self, val): self.hist_scale = val def run(self): hsv_map = np.zeros((180, 256, 3), np.uint8) h, s = np.indices(hsv_map.shape[:2]) hsv_map[:,:,0] = h hsv_map[:,:,1] = s hsv_map[:,:,2] = 255 hsv_map = cv.cvtColor(hsv_map, cv.COLOR_HSV2BGR) cv.imshow('hsv_map', hsv_map) cv.namedWindow('hist', 0) self.hist_scale = 10 cv.createTrackbar('scale', 'hist', self.hist_scale, 32, self.set_scale) try: fn = sys.argv[1] except: fn = 0 cam = video.create_capture(fn, fallback='synth:bg=baboon.jpg:class=chess:noise=0.05') while True: flag, frame = cam.read() cv.imshow('camera', frame) small = cv.pyrDown(frame) hsv = cv.cvtColor(small, cv.COLOR_BGR2HSV) dark = hsv[...,2] < 32 hsv[dark] = 0 h = cv.calcHist([hsv], [0, 1], None, [180, 256], [0, 180, 0, 256]) h = np.clip(h*0.005*self.hist_scale, 0, 1) vis = hsv_map*h[:,:,np.newaxis] / 255.0 cv.imshow('hist', vis) ch = cv.waitKey(1) if ch == 27: break print('Done') if __name__ == '__main__': print(__doc__) App().run() cv.destroyAllWindows()
Python
0
3ebb2731d6389170e0bef0dab66dc7c4ab41152e
Add a unit-test for thread_pool.py.
thread_pool_test.py
thread_pool_test.py
import thread_pool import unittest from six.moves import queue class TestThreadPool(unittest.TestCase): def _producer_thread(self, results): for i in range(10): results.put(i) def _consumer_thread(self, results): for i in range(10): self.assertEqual(results.get(), i) def testContextManager(self): results = queue.Queue(maxsize=1) with thread_pool.ThreadPool(2) as pool: pool.add(self._producer_thread, results) pool.add(self._consumer_thread, results) def testJoin(self): results = queue.Queue(maxsize=1) pool = thread_pool.ThreadPool(2) pool.add(self._producer_thread, results) pool.add(self._consumer_thread, results) pool.join()
Python
0
f6d4116ed5122868dbc10bf41dfc44053d0a0edf
write annotation parser for PASCAL VOC 2006
src/pascal_utils.py
src/pascal_utils.py
import re def which_one(str, arr): for a in arr: if a in str: return a return '' class VOC2006AnnotationParser(object): SKIP_CHARACTER = '#' OBJECT_SUMMARY = 'Objects with ground truth' PREPEND = 'PAS' TRUNC = 'Trunc' DIFFICULT = 'Difficult' CLASSES = ['bicycle', 'bus', 'car', 'motorbike', 'cat', 'cow', 'dog', 'horse', 'sheep', 'person'] VIEWS = ['Frontal', 'Rear', 'Left', 'Right'] RE_OBJECT_DEF = r"Original label for object (\d+) \"(\S+)\" : \"(\S+)\"" RE_OBJECT_BB = r"Bounding box for object %d \"%s\" \(Xmin, Ymin\) - \(Xmax, Ymax\) : \((\d+), (\d+)\) - \((\d+), (\d+)\)" def __init__(self, annotation_file_contet): self.annotation_file_contet = annotation_file_contet def get_objects(self, trunc=True, difficult=False): objects = [] for match in re.finditer(self.RE_OBJECT_DEF, self.annotation_file_contet): obj_index, obj_label, original_obj_label = match.groups() obj_index = int(obj_index) xmin, ymin, xmax, ymax = re.search(self.RE_OBJECT_BB % (obj_index, obj_label), self.annotation_file_contet).groups() xmin, ymin, xmax, ymax = int(xmin), int(ymin), int(xmax), int(ymax) if not trunc and self.TRUNC in original_obj_label: continue if not difficult and self.DIFFICULT in original_obj_label: continue objects.append({'ind': obj_index, 'label': obj_label, 'original_label': original_obj_label, 'xmin': xmin, 'ymin': ymin, 'xmax': xmax, 'ymax': ymax, 'trunc': self.TRUNC in original_obj_label, 'difficult': self.DIFFICULT in original_obj_label, 'class': which_one(original_obj_label, self.CLASSES), 'view': which_one(original_obj_label, self.VIEWS)}) return objects
Python
0
cc1dd96f66061da19855c050bb2567004aeb428a
add a tool to build a regular grid with a revert morton code for each cell
tools/build_grid.py
tools/build_grid.py
#! /bin/sh import yaml import sys from binascii import hexlify from struct import Struct, pack import codecs import io from struct import pack import numpy as np import math import argparse import glob import pymorton import liblas from lopocs.database import Session def get_infos(files): infos = {} paths = glob.glob(files) npoints = 0 xmin = float('inf') ymin = float('inf') zmin = float('inf') xmax = 0 ymax = 0 zmax = 0 for path in paths: lasfile = liblas.file.File(path, mode='r') bbox_min = lasfile.header.get_min() bbox_max = lasfile.header.get_max() if bbox_min[0] < xmin: xmin = bbox_min[0] if bbox_min[1] < ymin: ymin = bbox_min[1] if bbox_min[2] < zmin: zmin = bbox_min[2] if bbox_max[0] > xmax: xmax = bbox_max[0] if bbox_max[1] > ymax: ymax = bbox_max[1] if bbox_max[2] > zmax: zmax = bbox_max[2] npoints += lasfile.header.get_count() infos['npoints'] = npoints infos['xmin'] = xmin infos['ymin'] = ymin infos['zmin'] = zmin infos['xmax'] = xmax infos['ymax'] = ymax infos['zmax'] = zmax infos['dx'] = xmax-xmin infos['dy'] = ymax-ymin infos['dz'] = zmax-zmin infos['volume'] = infos['dx']*infos['dy']*infos['dz'] infos['density'] = npoints / infos['volume'] return infos def regular_grid(infos, pa_volume): # size of patch side in m pa_side = math.pow(pa_volume, 1/3) # number of cells for each dimensions nx = math.ceil(infos['dx'] / pa_side) ny = math.ceil(infos['dy'] / pa_side) nz = math.ceil(infos['dz'] / pa_side) # number of cells for a regular grid based on 4^x n = nx*ny n_regular = int(math.sqrt(math.pow(2, math.ceil(math.log(n)/math.log(2))))) pa_volume_regular = infos['volume'] / n_regular pa_side_regular = math.pow(pa_volume_regular, 1/3) # rest restx = (infos['dx'] - (n_regular-1)*pa_side_regular)/(n_regular-1) resty = (infos['dy'] - (n_regular-1)*pa_side_regular)/(n_regular-1) restz = (infos['dz'] - (n_regular-1)*pa_side_regular)/(n_regular-1) c = 0 for i in range(0, n_regular): for j in range(0, n_regular): #for k in range(0, nz): pa_minx = infos['xmin'] + i*(pa_side_regular+restx) pa_miny = infos['ymin'] + j*(pa_side_regular+resty) #pa_minz = infos['zmin'] + k*(pa_side_regular+restz) pa_minz = infos['zmin'] #+ k*(pa_side_regular+restz) dx = pa_side_regular + restx dy = pa_side_regular + resty #dz = pa_side_regular + restz dz = infos['dz'] c += 1 print("{0}/{1}\r".format(c, n_regular*n_regular), end='') yield [pa_minx, pa_miny, pa_minz, dx, dy, dz, i, j] def morton_revert_code(infos, cell): mcode = pymorton.interleave2(cell[6], cell[7]) mcode_str = "{0:b}".format(mcode) nfill = 16-len(mcode_str) mcode_str = ("0"*nfill) + mcode_str mcode_str_revert = mcode_str[::-1] mcode_revert = int(mcode_str_revert, 2) return mcode_revert def store_grid(infos, grid_gen): # create a table for the grid with a morton code for each cell sql = ("drop table if exists grid;" "create table grid(" "id serial," "points pcpatch(10)," "revert_morton integer," "i integer, j integer)") Session.db.cursor().execute(sql) for cell in grid_gen: # store a cell p0b = np.array([cell[0], cell[1], cell[2]]) p0u = np.array([cell[0], cell[1], cell[2]+cell[5]]) p1b = np.array([cell[0]+cell[3], cell[1], cell[2]]) p1u = np.array([cell[0]+cell[3], cell[1], cell[2]+cell[5]]) p2b = np.array([cell[0]+cell[3], cell[1]+cell[4], cell[2]]) p2u = np.array([cell[0]+cell[3], cell[1]+cell[4], cell[2]+cell[5]]) p3b = np.array([cell[0], cell[1]+cell[4], cell[2]]) p3u = np.array([cell[0], cell[1]+cell[4], cell[2]+cell[5]]) p4 = np.array([cell[0]+cell[3]/2, cell[1]+cell[4]/2, cell[2]+cell[5]/2]) patch = np.array([p0b, p0u, p1b, p1u, p2b, p2u, p3b, p3u, p4]) pa_header = pack('<b3I', *[1, 10, 0, len(patch)]) point_struct = Struct('<3d') pack_point = point_struct.pack points = [] for pt in patch: points.append(pack_point(*pt)) hexa = codecs.encode(pa_header + b''.join(points), 'hex').decode() morton_revert = morton_revert_code(infos, cell) rows = [str(morton_revert), hexa, str(cell[6]), str(cell[7])] Session.db.cursor().copy_from( io.StringIO('\t'.join(rows)), 'grid', columns=('revert_morton', 'points', 'i', 'j')) if __name__ == '__main__': # arg parse descr = 'Build a regular grid with a revert morton code for each cell' parser = argparse.ArgumentParser(description=descr) cfg_help = 'configuration file for the database' parser.add_argument('cfg', metavar='cfg', type=str, help=cfg_help) pa_size_help = 'mean size of a patch to deduce the volume in m3' parser.add_argument('pa_size', metavar='pa_size', type=float, help=pa_size_help) files_help = 'list of files where we want to build the grid (regex)' parser.add_argument('files', metavar='files', type=str, help=files_help) args = parser.parse_args() # open config file ymlconf_db = None with open(args.cfg, 'r') as f: try: ymlconf_db = yaml.load(f)['flask'] except: print("ERROR: ", sys.exc_info()[0]) f.close() sys.exit() app = type('', (), {})() app.config = ymlconf_db # open database Session.init_app(app) # extract infos from files infos = get_infos(args.files) print(infos) # compute the volume patch in m3 according to the mean patch size pa_volume = args.pa_size/infos['density'] # build the regular grid as a generator grid_gen = regular_grid(infos, pa_volume) # store the grid in database store_grid(infos, grid_gen)
Python
0
c6b1cbddec20fae0daeece0ea859a7227e16e3bf
Add primitive name space registry for event types
common/shregistry.py
common/shregistry.py
#!/usr/local/bin/python3 -u __author__ = 'Oliver Ratzesberger <https://github.com/fxstein>' __copyright__ = 'Copyright (C) 2015 Oliver Ratzesberger' __license__ = 'Apache License, Version 2.0' # ALL event types need to be registered here # ATTENTION: type must be unique to avoid event name space polution # Registry structure: # key = unique identifier of event type # name = unique namespace of event should be same as key in most cases # class = class of events for grouping and statistics # desc = description of event types # tags = list of freeform tags # # Notes: # keys and types should be kept short and shpuld be kept constant for the life # of the project shRegistry = { 'autelis' : {'name': 'autelis', 'class': 'Pool', 'desc': 'Autelis Pool Controller', 'tags': ['Pool', 'Autelis', 'Pentair']}, 'eagle' : {'name': 'eagle', 'class': 'Power', 'desc': 'Rainforest Eagle Gateway', 'tags':['Rinaforest', 'Eagle', 'Power', 'Electricity']}, 'gfinance' : {'name': 'gfinance', 'class': 'Finance', 'desc': 'Google Finance', 'tags': ['Google', 'Finance', 'Stock', 'Currency', 'Index']}, 'isy' : {'name': 'isy', 'class': 'Automation', 'desc': 'ISY994 Home Automation Controller', 'tags':['ISY', 'Insteon', 'X10']}, 'nesttherm': {'name': 'nesttherm','class': 'Climate', 'desc': 'Nest Thermostat', 'tags':['Nest', 'Thermostat']}, 'nestfire' : {'name': 'nestfire', 'class': 'Protection', 'desc': 'Nest Fire & CO Alarm', 'tags':['Nest', 'Protect', 'Fire Alarm', 'CO Alarm']}, 'netatmo' : {'name': 'netatmo', 'class': 'Climate', 'desc': 'Netatmo Climate Station', 'tags':['Climate', 'Indoor', 'Outdoor']}, 'twitter' : {'name': 'twitter', 'class': 'Social', 'desc': 'Twitter Feed', 'tags':['Twitter', 'Social', 'Tweet']}, 'usgsquake': {'name': 'usgsquake','class': 'Geological', 'desc': 'USGS Earthquakes', 'tags':['USGS', 'Earthquake']}, 'zillow' : {'name': 'zillow', 'class': 'Finance', 'desc': 'Zillow Home Valuation', 'tags':['Zillow', 'House', 'Home', 'Value', 'Fiance']}, # Sentient Home Internal Event Types 'tracer' : {'name': 'tracer', 'class': 'Internal', 'name': 'Sentient Home Periodic Tracer', 'tags': ['Sentient Home', 'Tracer']}, 'loadtest' : {'name': 'loadtest', 'class': 'Internal', 'name': 'Sentient Home Load Test Event Generator', 'tags': ['Sentient Home', 'Test']}, } # # Do nothing # (syntax check) # if __name__ == "__main__": import __main__ print(__main__.__file__) print("syntax ok") exit(0)
Python
0.000001
167872381e16090b1b47184a1a80bbe948d5fd91
Add test and test_suite function to svm module
scikits/learn/machine/svm/__init__.py
scikits/learn/machine/svm/__init__.py
""" A Support Vector Machine, this module defines the following classes: - `LibSvmCClassificationModel`, a model for C-SV classification - `LibSvmNuClassificationModel`, a model for nu-SV classification - `LibSvmEpsilonRegressionModel`, a model for epsilon-SV regression - `LibSvmNuRegressionModel`, a model for nu-SV regression - `LibSvmOneClassModel`, a model for distribution estimation (one-class SVM) Kernel classes: - `LinearKernel`, a linear kernel - `PolynomialKernel`, a polynomial kernel - `RBFKernel`, a radial basis function kernel - `SigmoidKernel`, a sigmoid kernel - `CustomKernel`, a kernel that wraps any callable Dataset classes: - `LibSvmClassificationDataSet`, a dataset for training classification models - `LibSvmRegressionDataSet`, a dataset for training regression models - `LibSvmOneClassDataSet`, a dataset for training distribution estimation (one-class SVM) models - `LibSvmTestDataSet`, a dataset for testing with any model Data type classes: - `svm_node_dtype`, the libsvm data type for its arrays How To Use This Module ====================== (See the individual classes, methods, and attributes for details.) 1. Import it: ``import svm`` or ``from svm import ...``. 2. Create a training dataset for your problem:: traindata = LibSvmClassificationDataSet(labels, x) traindata = LibSvmRegressionDataSet(y, x) traindata = LibSvmOneClassDataSet(x) where x is sequence of NumPy arrays containing scalars or svm_node_dtype entries. 3. Create a test dataset:: testdata = LibSvmTestDataSet(u) 4. Create a model and fit it to the training data:: model = LibSvmCClassificationModel(kernel) results = model.fit(traindata) 5. Use the results to make predictions with the test data:: p = results.predict(testdata) v = results.predict_values(testdata) """ from classification import * from regression import * from oneclass import * from dataset import * from kernel import * from predict import * from numpy.testing import NumpyTest test = NumpyTest().test def test_suite(*args): # XXX: this is to avoid recursive call to itself. This is an horrible hack, # I have no idea why infinite recursion happens otherwise. if len(args) > 0: import unittest return unittest.TestSuite() return NumpyTest().test(level = -10)
""" A Support Vector Machine, this module defines the following classes: - `LibSvmCClassificationModel`, a model for C-SV classification - `LibSvmNuClassificationModel`, a model for nu-SV classification - `LibSvmEpsilonRegressionModel`, a model for epsilon-SV regression - `LibSvmNuRegressionModel`, a model for nu-SV regression - `LibSvmOneClassModel`, a model for distribution estimation (one-class SVM) Kernel classes: - `LinearKernel`, a linear kernel - `PolynomialKernel`, a polynomial kernel - `RBFKernel`, a radial basis function kernel - `SigmoidKernel`, a sigmoid kernel - `CustomKernel`, a kernel that wraps any callable Dataset classes: - `LibSvmClassificationDataSet`, a dataset for training classification models - `LibSvmRegressionDataSet`, a dataset for training regression models - `LibSvmOneClassDataSet`, a dataset for training distribution estimation (one-class SVM) models - `LibSvmTestDataSet`, a dataset for testing with any model Data type classes: - `svm_node_dtype`, the libsvm data type for its arrays How To Use This Module ====================== (See the individual classes, methods, and attributes for details.) 1. Import it: ``import svm`` or ``from svm import ...``. 2. Create a training dataset for your problem:: traindata = LibSvmClassificationDataSet(labels, x) traindata = LibSvmRegressionDataSet(y, x) traindata = LibSvmOneClassDataSet(x) where x is sequence of NumPy arrays containing scalars or svm_node_dtype entries. 3. Create a test dataset:: testdata = LibSvmTestDataSet(u) 4. Create a model and fit it to the training data:: model = LibSvmCClassificationModel(kernel) results = model.fit(traindata) 5. Use the results to make predictions with the test data:: p = results.predict(testdata) v = results.predict_values(testdata) """ from classification import * from regression import * from oneclass import * from dataset import * from kernel import * from predict import *
Python
0.000006
5a27a8e0c7ae2e0cef787db107305251d096d81f
Add test runner.
lib/rapidsms/tests/runtests.py
lib/rapidsms/tests/runtests.py
#!/usr/bin/python from test_component import * if __name__ == "__main__": unittest.main()
Python
0
2f9152d5cc0ad4123522b054dd2b6458c602b1fd
add script for dataset
moses/scripts/download_dataset.py
moses/scripts/download_dataset.py
import argparse import os import pandas as pd from urllib import request def get_parser(): parser = argparse.ArgumentParser() parser.add_argument('--output_dir', type=str, default='./data', help='Directory for downloaded dataset') parser.add_argument('--dataset_url', type=str, default='https://media.githubusercontent.com/media/neuromation/mnist4molecules/master-fixes/data/dataset.csv?token=AORf9_1XuBXJjCmYV--t6f1Ui5aVe-WEks5bvLClwA%3D%3D', help='URL of dataset') parser.add_argument('--no_subset', action='store_true', help='Do not create subsets for training and testing') parser.add_argument('--train_size', type=int, default=200000, help='Size of training dataset') parser.add_argument('--test_size', type=int, default=10000, help='Size of testing dataset') parser.add_argument('--seed', type=int, default=0, help='Random state') return parser def main(config): if not os.path.exists(config.output_dir): os.mkdir(config.output_dir) dataset_path = os.path.join(config.output_dir, 'dataset.csv') request.urlretrieve(config.dataset_url, dataset_path) if config.no_subset: return data = pd.read_csv(dataset_path) train_data = data[data['SPLIT'] == 'train'] test_data = data[data['SPLIT'] == 'test'] test_scaffolds_data = data[data['SPLIT'] == 'test_scaffolds'] train_data = train_data.sample(config.train_size, random_state=config.seed) test_data = test_data.sample(config.test_size, random_state=config.seed) test_scaffolds_data = test_scaffolds_data.sample(config.test_size, random_state=config.seed) train_data.to_csv(os.path.join(config.output_dir, 'train.csv'), index=False) test_data.to_csv(os.path.join(config.output_dir, 'test.csv'), index=False) test_scaffolds_data.to_csv(os.path.join(config.output_dir, 'test_scaffolds.csv'), index=False) if __name__ == '__main__': parser = get_parser() config = parser.parse_known_args()[0] main(config)
Python
0.000001
19712e8e7b9423d4cb4bb22c37c7d8d2ea0559c5
Add example to show listing of USB devices
examples/list-usb.py
examples/list-usb.py
#!/usr/bin/env python2 # # This file is Public Domain and provided only for documentation purposes. # # Run : python2 ./list-usb.py # # Note: This will happily run with Python3 too, I just picked a common baseline # import gi gi.require_version('Ldm', '0.1') from gi.repository import Ldm, GObject class PretendyPlugin(Ldm.Plugin): # Not really needed but good practice __gtype_name__ = "PretendyPlugin" def __init__(self): Ldm.Plugin.__init__(self) def do_get_provider(self, device): """ Demonstrate basic matching with custom plugins """ if not device.has_type(Ldm.DeviceType.AUDIO): return None return Ldm.Provider.new(self, device, "pretendy-package") def main(): manager = Ldm.Manager() manager.add_plugin(PretendyPlugin()) for device in manager.get_devices(Ldm.DeviceType.USB): # Use gobject properties or methods print("USB Device: {} {}".format( device.props.vendor, device.get_name())) if device.has_type(Ldm.DeviceType.HID): print("\tHID Device!") for provider in manager.get_providers(device): plugin = provider.get_plugin() print("\tSuggested package: {}".format(provider.get_package())) if __name__ == "__main__": main()
Python
0
b56690d046021e036b5b15c484d86c92f3519600
Add partial evaluation tool to replace functools module for python < 2.5
scikits/learn/common/myfunctools.py
scikits/learn/common/myfunctools.py
# Last Change: Mon Aug 20 01:00 PM 2007 J # Implement partial application (should only be used if functools is not # available (eg python < 2.5) class partial: def __init__(self, fun, *args, **kwargs): self.fun = fun self.pending = args[:] self.kwargs = kwargs.copy() def __call__(self, *args, **kwargs): if kwargs and self.kwargs: kw = self.kwargs.copy() kw.update(kwargs) else: kw = kwargs or self.kwargs return self.fun(*(self.pending + args), **kw)
Python
0.000009
6219211d529d2dd58693ea93e6b799fd36259fee
Add tests
djangae/tests/test_async_multi_query.py
djangae/tests/test_async_multi_query.py
from django.test import override_settings from django.db import NotSupportedError from django.db import models from djangae.test import TestCase class MultiQueryModel(models.Model): field1 = models.IntegerField() class AsyncMultiQueryTest(TestCase): """ Specific tests for multiquery """ def test_hundred_or(self): for i in range(100): MultiQueryModel.objects.create(field1=i) self.assertEqual( len(MultiQueryModel.objects.filter(field1__in=list(range(100)))), 100 ) self.assertEqual( MultiQueryModel.objects.filter(field1__in=list(range(100))).count(), 100 ) self.assertItemsEqual( MultiQueryModel.objects.filter( field1__in=list(range(100)) ).values_list("field1", flat=True), list(range(100)) ) self.assertItemsEqual( MultiQueryModel.objects.filter( field1__in=list(range(100)) ).order_by("-field1").values_list("field1", flat=True), list(range(100))[::-1] ) @override_settings(DJANGAE_MAX_QUERY_BRANCHES=10) def test_max_limit_enforced(self): for i in range(11): MultiQueryModel.objects.create(field1=i) self.assertRaises(NotSupportedError, lambda: list(MultiQueryModel.objects.filter( field1__in=range(11) )) )
Python
0.000001
51e04ff17bccb4b71b8d5db4057a782fd2f8520c
Add script to synthesize all uploaded files. Patch by Dan Callahan.
tools/touch_all_files.py
tools/touch_all_files.py
#!/usr/bin/python """ This script touches all files known to the database, creating a skeletal mirror for local development. """ import sys, os import store def get_paths(cursor, prefix=None): store.safe_execute(cursor, "SELECT python_version, name, filename FROM release_files") for type, name, filename in cursor.fetchall(): yield os.path.join(prefix, type, name[0], name, filename) if __name__ == '__main__': import config try: config = config.Config(sys.argv[1]) except IndexError: print "Usage: touch_all_files.py config.ini" raise SystemExit datastore = store.Store(config) datastore.open() cursor = datastore.get_cursor() prefix = config.database_files_dir for path in get_paths(cursor, prefix): dir = os.path.dirname(path) if not os.path.exists(dir): print "Creating directory %s" % dir os.makedirs(dir) if not os.path.exists(path): print "Creating file %s" % path open(path, "a")
Python
0
2684aa6eabdeb3fa5ec4c7e910af04c7068c7cd8
add working loopback test
test_pastream.py
test_pastream.py
""" Loopback tests for pastream. """ from __future__ import print_function import os, sys import numpy as np import soundfile as sf import pytest import numpy.testing as npt import time import tempfile import platform import pastream as pas # Set up the platform specific device system = platform.system() if system == 'Windows': DEVICE_KWARGS = {'device': 'ASIO4ALL v2, ASIO', 'dtype': 'int24', 'blocksize': 512, 'channels': 8, 'samplerate':48000} elif system == 'Darwin': raise Exception("Currently no support for Mac devices") else: # This is assuming you're using the ALSA device set up by etc/.asoundrc DEVICE_KWARGS = {'device': 'aduplex', 'dtype': 'int32', 'blocksize': 512, 'channels': 8, 'samplerate':48000} if 'SOUNDDEVICE_DEVICE_NAME' in os.environ: DEVICE_KWARGS['device'] = os.environ['SOUNDDEVICE_DEVICE_NAME'] if 'SOUNDDEVICE_DEVICE_BLOCKSIZE' in os.environ: DEVICE_KWARGS['blocksize'] = os.environ['SOUNDDEVICE_DEVICE_BLOCKSIZE'] if 'SOUNDDEVICE_DEVICE_DTYPE' in os.environ: DEVICE_KWARGS['dtype'] = os.environ['SOUNDDEVICE_DEVICE_DTYPE'] if 'SOUNDDEVICE_DEVICE_CHANNELS' in os.environ: DEVICE_KWARGS['channels'] = os.environ['SOUNDDEVICE_DEVICE_CHANNELS'] if 'SOUNDDEVICE_DEVICE_SAMPLERATE' in os.environ: DEVICE_KWARGS['SAMPLERATE'] = os.environ['SOUNDDEVICE_DEVICE_SAMPLERATE'] PREAMBLE = 0x7FFFFFFF # Value used for the preamble sequence (before appropriate shifting for dtype) _dtype2elementsize = dict(int32=4,int24=3,int16=2,int8=1) vhex = np.vectorize('{:#10x}'.format) tohex = lambda x: vhex(x.view('u4')) def assert_loopback_equal(inp_fh, preamble, **kwargs): inpf2 = sf.SoundFile(inp_fh.name, mode='rb') devargs = dict(DEVICE_KWARGS) devargs.update(kwargs) delay = -1 found_delay = False nframes = mframes = 0 for outframes in pas.blockstream(inp_fh, **devargs): if not found_delay: matches = outframes[:, 0].view('u4') == preamble if np.any(matches): found_delay = True nonzeros = np.where(matches)[0] outframes = outframes[nonzeros[0]:] nframes += nonzeros[0] delay = nframes if found_delay: inframes = inpf2.read(len(outframes), dtype='int32', always_2d=True) mlen = min(len(inframes), len(outframes)) inp = inframes[:mlen].view('u4') out = outframes[:mlen].view('u4') npt.assert_array_equal(inp, out, "Loopback data mismatch") mframes += mlen nframes += len(outframes) assert delay != -1, "Preamble not found or was corrupted" print("Matched %d of %d frames; Initial delay of %d frames" % (mframes, nframes, delay)) class PortAudioLoopbackTester(object): def _gen_random(self, rdm_fh, nseconds, elementsize): """ Generates a uniformly random integer signal ranging between the minimum and maximum possible values as defined by `elementsize`. The random signal is preceded by a constant level equal to the maximum positive integer value for 100ms or N=sampling_rate/10 samples (the 'preamble') which can be used in testing to find the beginning of a recording. nseconds - how many seconds of data to generate elementsize - size of each element (single sample of a single frame) in bytes """ shift = 8*(4-elementsize) minval = -(0x80000000>>shift) maxval = 0x7FFFFFFF>>shift preamble = np.zeros((rdm_fh.samplerate//10, rdm_fh.channels), dtype=np.int32) preamble[:] = (PREAMBLE >> shift) << shift rdm_fh.write(preamble) for i in range(nseconds): pattern = np.random.randint(minval, maxval+1, (rdm_fh.samplerate, rdm_fh.channels)) << shift rdm_fh.write(pattern.astype(np.int32)) class TestDummyLoopback(PortAudioLoopbackTester): def test_wav(self, tmpdir): elementsize = _dtype2elementsize[DEVICE_KWARGS['dtype']] rdmf = tempfile.mktemp(dir=str(tmpdir)) rdm_fh = sf.SoundFile(rdmf, 'w+', DEVICE_KWARGS['samplerate'], DEVICE_KWARGS['channels'], 'PCM_'+['8', '16','24','32'][elementsize-1], format='wav') self._gen_random(rdm_fh, 5, elementsize) rdm_fh.seek(0) dtype = DEVICE_KWARGS['dtype'] if DEVICE_KWARGS['dtype'] == 'int24': # Tell the OS it's a 32-bit stream and ignore the extra zeros # because 24 bit streams are annoying to deal with dtype = 'int32' shift = 8*(4-elementsize) assert_loopback_equal(rdm_fh, (PREAMBLE>>shift)<<shift, dtype=dtype)
Python
0
e8b6c596a7627d1c4f3f6915236317b0730210a2
Rename ds_tree_max_min_depth.py to ds_tree_balanced_bt.py
leetcode/ds_tree_balanced_bt.py
leetcode/ds_tree_balanced_bt.py
# @file Balanced Binary Tree # @brief Given a binary tree, determine if it is height-balanced. # https://leetcode.com/problems/balanced-binary-tree/ ''' Given a binary tree, determine if it is height-balanced. For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1. ''' #Given a BT node, find the depth (1-based depth) def maxDepth(root): if (root == None): return 0 elif (root.left == None and root.right == None): return 1 else: return 1 + max(maxDepth(root.left), maxDepth(root.right)) def isBalanced(self, root): if(root == None): return True elif abs(maxDepth(root.left) - maxDepth(root.right)) > 1: return False elif self.isBalanced(root.left) == False: return False else: return self.isBalanced(root.right)
Python
0.998882
4a6edf85f755f62a2213ce09cd407621fe635cea
Add DB migration file
zou/migrations/versions/528b27337ebc_.py
zou/migrations/versions/528b27337ebc_.py
"""empty message Revision ID: 528b27337ebc Revises: f0567e8d0c62 Create Date: 2018-05-17 15:51:25.513852 """ from alembic import op import sqlalchemy as sa import sqlalchemy_utils from sqlalchemy.dialects import postgresql import sqlalchemy_utils import uuid # revision identifiers, used by Alembic. revision = '528b27337ebc' down_revision = 'f0567e8d0c62' branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table('asset_instance_link', sa.Column('entity_id', sqlalchemy_utils.types.uuid.UUIDType(binary=False), default=uuid.uuid4, nullable=False), sa.Column('asset_instance_id', sqlalchemy_utils.types.uuid.UUIDType(binary=False), default=uuid.uuid4, nullable=False), sa.ForeignKeyConstraint(['asset_instance_id'], ['asset_instance.id'], ), sa.ForeignKeyConstraint(['entity_id'], ['entity.id'], ), sa.PrimaryKeyConstraint('entity_id', 'asset_instance_id') ) op.add_column('asset_instance', sa.Column('scene_id', sqlalchemy_utils.types.uuid.UUIDType(binary=False), default=uuid.uuid4, nullable=True)) op.create_index(op.f('ix_asset_instance_scene_id'), 'asset_instance', ['scene_id'], unique=False) op.drop_constraint('asset_instance_name_uc', 'asset_instance', type_='unique') op.create_unique_constraint('asset_instance_name_uc', 'asset_instance', ['scene_id', 'name']) op.drop_constraint('asset_instance_uc', 'asset_instance', type_='unique') op.create_unique_constraint('asset_instance_uc', 'asset_instance', ['asset_id', 'scene_id', 'number']) op.drop_index('ix_asset_instance_entity_id', table_name='asset_instance') op.drop_index('ix_asset_instance_entity_type_id', table_name='asset_instance') op.drop_constraint('asset_instance_entity_id_fkey', 'asset_instance', type_='foreignkey') op.drop_constraint('asset_instance_entity_type_id_fkey', 'asset_instance', type_='foreignkey') op.create_foreign_key(None, 'asset_instance', 'entity', ['scene_id'], ['id']) op.drop_column('asset_instance', 'entity_type_id') op.drop_column('asset_instance', 'entity_id') op.add_column('output_file', sa.Column('temporal_entity_id', sqlalchemy_utils.types.uuid.UUIDType(binary=False), default=uuid.uuid4, nullable=True)) op.drop_constraint('output_file_uc', 'output_file', type_='unique') op.create_unique_constraint('output_file_uc', 'output_file', ['name', 'entity_id', 'asset_instance_id', 'output_type_id', 'task_type_id', 'temporal_entity_id', 'representation', 'revision']) op.create_foreign_key(None, 'output_file', 'entity', ['temporal_entity_id'], ['id']) op.drop_column('output_file', 'uploaded_movie_name') op.drop_column('output_file', 'uploaded_movie_url') # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.add_column('output_file', sa.Column('uploaded_movie_url', sa.VARCHAR(length=600), autoincrement=False, nullable=True)) op.add_column('output_file', sa.Column('uploaded_movie_name', sa.VARCHAR(length=150), autoincrement=False, nullable=True)) op.drop_constraint(None, 'output_file', type_='foreignkey') op.drop_constraint('output_file_uc', 'output_file', type_='unique') op.create_unique_constraint('output_file_uc', 'output_file', ['name', 'entity_id', 'output_type_id', 'task_type_id', 'representation', 'revision']) op.drop_column('output_file', 'temporal_entity_id') op.add_column('asset_instance', sa.Column('entity_id', postgresql.UUID(), autoincrement=False, nullable=False)) op.add_column('asset_instance', sa.Column('entity_type_id', postgresql.UUID(), autoincrement=False, nullable=False)) op.drop_constraint(None, 'asset_instance', type_='foreignkey') op.create_foreign_key('asset_instance_entity_type_id_fkey', 'asset_instance', 'entity_type', ['entity_type_id'], ['id']) op.create_foreign_key('asset_instance_entity_id_fkey', 'asset_instance', 'entity', ['entity_id'], ['id']) op.create_index('ix_asset_instance_entity_type_id', 'asset_instance', ['entity_type_id'], unique=False) op.create_index('ix_asset_instance_entity_id', 'asset_instance', ['entity_id'], unique=False) op.drop_constraint('asset_instance_uc', 'asset_instance', type_='unique') op.create_unique_constraint('asset_instance_uc', 'asset_instance', ['asset_id', 'entity_id', 'number']) op.drop_constraint('asset_instance_name_uc', 'asset_instance', type_='unique') op.create_unique_constraint('asset_instance_name_uc', 'asset_instance', ['entity_id', 'name']) op.drop_index(op.f('ix_asset_instance_scene_id'), table_name='asset_instance') op.drop_column('asset_instance', 'scene_id') op.drop_table('asset_instance_link') # ### end Alembic commands ###
Python
0
68f3c14c2ae7df9d9a5cdc44fe7a181760d54dfa
Add Exercise 3.10.
Kane1985/Chapter2/Ex3.10.py
Kane1985/Chapter2/Ex3.10.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """Exercise 3.10 from Kane 1985.""" from __future__ import division from sympy import cancel, collect, expand_trig, solve, symbols, trigsimp from sympy import sin, cos from sympy.physics.mechanics import ReferenceFrame, Point from sympy.physics.mechanics import dot, dynamicsymbols, msprint q1, q2, q3, q4, q5, q6, q7 = q = dynamicsymbols('q1:8') u1, u2, u3, u4, u5, u6, u7 = u = dynamicsymbols('q1:8', level=1) r, theta, b = symbols('r θ b', real=True, positive=True) # define reference frames R = ReferenceFrame('R') # fixed race rf, let R.z point upwards A = R.orientnew('A', 'axis', [q7, R.z]) # rf that rotates with S* about R.z # B.x, B.z are parallel with face of cone, B.y is perpendicular B = A.orientnew('B', 'axis', [-theta, A.x]) S = ReferenceFrame('S') S.set_ang_vel(A, u1*A.x + u2*A.y + u3*A.z) C = ReferenceFrame('C') C.set_ang_vel(A, u4*B.x + u5*B.y + u6*B.z) # define points pO = Point('O') pS_star = pO.locatenew('S*', b*A.y) pS_hat = pS_star.locatenew('S^', -r*B.y) # S^ touches the cone pS1 = pS_star.locatenew('S1', -r*A.z) # S1 touches horizontal wall of the race pS2 = pS_star.locatenew('S2', r*A.y) # S2 touches vertical wall of the race pO.set_vel(R, 0) pS_star.v2pt_theory(pO, R, A) pS1.v2pt_theory(pS_star, R, S) pS2.v2pt_theory(pS_star, R, S) # Since S is rolling against R, v_S1_R = 0, v_S2_R = 0. vc = [dot(p.vel(R), basis) for p in [pS1, pS2] for basis in R] vc_map = solve(vc, [u1, u2, u3]) pO.set_vel(C, 0) pS_star.v2pt_theory(pO, C, A) pS_hat.v2pt_theory(pS_star, C, S) # Since S is rolling against C, v_S^_C = 0. # Cone has only angular velocity in R.z direction. vc2 = [dot(pS_hat.vel(C), basis).subs(vc_map) for basis in A] vc2 += [dot(C.ang_vel_in(R), basis) for basis in [R.x, R.y]] vc_map = dict(vc_map.items() + solve(vc2, [u4, u5, u6]).items()) # Pure rolling between S and C, dot(ω_C_S, B.y) = 0. b_val = solve([dot(C.ang_vel_in(S), B.y).subs(vc_map).simplify()], b)[0][0] print('b = {0}'.format(msprint(collect(cancel(expand_trig(b_val)), r)))) b_expected = r*(1 + sin(theta))/(cos(theta) - sin(theta)) assert trigsimp(b_val - b_expected) == 0
Python
0.000002
df569fb5809e8d86945dc27aee7e190fae12331c
replace teh crazy exec with a slightly less crazy metaprogramming
topaz/gateway.py
topaz/gateway.py
import functools from rpython.rlib.unroll import unrolling_iterable from topaz.coerce import Coerce class WrapperGenerator(object): def __init__(self, name, func, argspec, self_cls): self.name = name self.func = func self.argspec = argspec self.self_cls = self_cls def generate_wrapper(self): code = self.func.__code__ if self.func.__defaults__ is not None: defaults = self.func.__defaults__ default_start = code.co_argcount - len(defaults) else: defaults = [] default_start = None argspec = self.argspec self_cls = self.self_cls func = self.func if hasattr(self.func, "__topaz_args__"): argnames = self.func.__topaz_args__ else: argnames = code.co_varnames[:code.co_argcount] argcount = 0 for arg in argnames: argcount += arg.startswith("w_") or arg in argspec unrolling_argnames = unrolling_iterable(enumerate(argnames)) takes_args_w = "args_w" in argnames @functools.wraps(self.func) def wrapper(self, space, args_w, block): if ((len(args_w) < (argcount - len(defaults)) or (not takes_args_w and len(args_w) > argcount))): raise space.error(space.w_ArgumentError, "wrong number of arguments (%d for %d)" % (len(args_w), argcount - len(defaults)) ) args = () arg_count = 0 for i, argname in unrolling_argnames: if argname == "self": assert isinstance(self, self_cls) args += (self,) elif argname == "args_w": # TODO: this should only include args that aren't already # processed args += (args_w,) elif argname == "block": args += (block,) elif argname == "space": args += (space,) elif argname.startswith("w_") or argname in argspec: if len(args_w) > arg_count: if argname.startswith("w_"): args += (args_w[arg_count],) elif argname in argspec: args += (getattr(Coerce, argspec[argname])(space, args_w[arg_count]),) elif default_start is not None and i >= default_start: args += (defaults[i - default_start],) else: raise SystemError("bad arg count") arg_count += 1 else: raise SystemError("%r not implemented" % argname) w_res = func(*args) if w_res is None: w_res = space.w_nil return w_res return wrapper
from topaz.coerce import Coerce class WrapperGenerator(object): def __init__(self, name, func, argspec, self_cls): self.name = name self.func = func self.argspec = argspec self.self_cls = self_cls def generate_wrapper(self): code = self.func.__code__ lines = [] lines.append("def %s(self, space, args_w, block):" % self.func.__name__) lines.append(" if ((len(args_w) < (argcount - len(defaults)) or") lines.append(" (not takes_args_w and len(args_w) > argcount))):") lines.append(" raise space.error(space.w_ArgumentError,") lines.append(" 'wrong number of arguments (%d for %d)' % (len(args_w), argcount - len(defaults))") lines.append(" )") lines.append(" args = ()") if self.func.__defaults__ is not None: default_start = code.co_argcount - len(self.func.__defaults__) else: default_start = None self.arg_count = 0 if hasattr(self.func, "__topaz_args__"): args = self.func.__topaz_args__ else: args = code.co_varnames[:code.co_argcount] for i, argname in enumerate(args): if argname in self.argspec or argname.startswith("w_"): if argname.startswith("w_"): coerce_code = "args_w[{:d}]".format(self.arg_count) else: spec = self.argspec[argname] coerce_code = "Coerce.{}(space, args_w[{:d}])".format(spec, self.arg_count) lines.append(" if len(args_w) > {}:".format(self.arg_count)) lines.append(" args += ({},)".format(coerce_code)) lines.append(" else:") if default_start is not None and i >= default_start: lines.append(" args += (defaults[{:d}],)".format(i - default_start)) else: lines.append(" raise SystemError('bad arg count')") self.arg_count += 1 elif argname == "self": lines.append(" assert isinstance(self, self_cls)") lines.append(" args += (self,)") elif argname == "args_w": lines.append(" args += (args_w,)") elif argname == "block": lines.append(" args += (block,)") elif argname == "space": lines.append(" args += (space,)") else: raise NotImplementedError(argname, self.func.__name__) lines.append(" w_res = func(*args)") lines.append(" if w_res is None:") lines.append(" w_res = space.w_nil") lines.append(" return w_res") source = "\n".join(lines) namespace = { "func": self.func, "self_cls": self.self_cls, "Coerce": Coerce, "defaults": self.func.__defaults__ or [], "argcount": self.arg_count, "takes_args_w": "args_w" in args, } exec source in namespace return namespace[self.func.__name__]
Python
0.000007
484e50b34c06785f1b1b48da5502f79ee5a2357b
add factories.py
tx_salaries/factories.py
tx_salaries/factories.py
import factory from tx_people.models import Organization, Membership, Person, Post from tx_salaries.models import Employee, EmployeeTitle, CompensationType, OrganizationStats # tx_people factories class OrganizationFactory(factory.DjangoModelFactory): FACTORY_FOR = Organization class PersonFactory(factory.DjangoModelFactory): FACTORY_FOR = Person class PostFactory(factory.DjangoModelFactory): FACTORY_FOR = Post organization = factory.SubFactory(OrganizationFactory) class MembershipFactory(factory.DjangoModelFactory): FACTORY_FOR = Membership person = factory.SubFactory(PersonFactory) organization = factory.SubFactory(OrganizationFactory) post = factory.SubFactory(PostFactory) # tx_salaries factories class CompensationTypeFactory(factory.DjangoModelFactory): FACTORY_FOR = CompensationType class EmployeeTitleFactory(factory.DjangoModelFactory): FACTORY_FOR = EmployeeTitle class EmployeeFactory(factory.DjangoModelFactory): FACTORY_FOR = Employee position = factory.SubFactory(MembershipFactory) compensation_type = factory.SubFactory(CompensationTypeFactory) title = factory.SubFactory(EmployeeTitleFactory) compensation = 1337 class OrganizationStatsFactory(factory.DjangoModelFactory): FACTORY_FOR = OrganizationStats
Python
0.000001
02d6dd700af4fad74592df5576c2ca5ea8bed5fe
Update hinton_diagram.py (#342)
scripts/hinton_diagram.py
scripts/hinton_diagram.py
#https://github.com/tonysyu/mpltools/blob/master/mpltools/special/hinton.py import numpy as np import matplotlib.pyplot as plt from matplotlib import collections from matplotlib import transforms from matplotlib import ticker # TODO: Add yutils.mpl._coll to mpltools and use that for square collection. class SquareCollection(collections.RegularPolyCollection): """Return a collection of squares.""" def __init__(self, **kwargs): super(SquareCollection, self).__init__(4, rotation=np.pi/4., **kwargs) def get_transform(self): """Return transform scaling circle areas to data space.""" ax = self.axes pts2pixels = 72.0 / ax.figure.dpi scale_x = pts2pixels * ax.bbox.width / ax.viewLim.width scale_y = pts2pixels * ax.bbox.height / ax.viewLim.height return transforms.Affine2D().scale(scale_x, scale_y) def hinton(inarray, max_value=None, use_default_ticks=True): """Plot Hinton diagram for visualizing the values of a 2D array. Plot representation of an array with positive and negative values represented by white and black squares, respectively. The size of each square represents the magnitude of each value. Unlike the hinton demo in the matplotlib gallery [1]_, this implementation uses a RegularPolyCollection to draw squares, which is much more efficient than drawing individual Rectangles. .. note:: This function inverts the y-axis to match the origin for arrays. .. [1] http://matplotlib.sourceforge.net/examples/api/hinton_demo.html Parameters ---------- inarray : array Array to plot. max_value : float Any *absolute* value larger than `max_value` will be represented by a unit square. use_default_ticks: boolean Disable tick-generation and generate them outside this function. """ ax = plt.gca() ax.set_facecolor('gray') # make sure we're working with a numpy array, not a numpy matrix inarray = np.asarray(inarray) height, width = inarray.shape if max_value is None: max_value = 2**np.ceil(np.log(np.max(np.abs(inarray)))/np.log(2)) values = np.clip(inarray/max_value, -1, 1) rows, cols = np.mgrid[:height, :width] pos = np.where(values > 0) neg = np.where(values < 0) for idx, color in zip([pos, neg], ['white', 'black']): if len(idx[0]) > 0: xy = list(zip(cols[idx], rows[idx])) circle_areas = np.pi / 2 * np.abs(values[idx]) squares = SquareCollection(sizes=circle_areas, offsets=xy, transOffset=ax.transData, facecolor=color, edgecolor=color) ax.add_collection(squares, autolim=True) ax.axis('scaled') # set data limits instead of using xlim, ylim. ax.set_xlim(-0.5, width-0.5) ax.set_ylim(height-0.5, -0.5) if use_default_ticks: ax.xaxis.set_major_locator(IndexLocator()) ax.yaxis.set_major_locator(IndexLocator()) class IndexLocator(ticker.Locator): def __init__(self, max_ticks=10): self.max_ticks = max_ticks def __call__(self): """Return the locations of the ticks.""" dmin, dmax = self.axis.get_data_interval() if dmax < self.max_ticks: step = 1 else: step = np.ceil(dmax / self.max_ticks) return self.raise_if_exceeds(np.arange(0, dmax, step)) plt.figure() A = np.random.uniform(-1, 1, size=(20, 20)) hinton(A) #special.hinton(A) plt.show()
#https://github.com/tonysyu/mpltools/blob/master/mpltools/special/hinton.py import numpy as np import matplotlib.pyplot as plt from matplotlib import collections from matplotlib import transforms from matplotlib import ticker # TODO: Add yutils.mpl._coll to mpltools and use that for square collection. class SquareCollection(collections.RegularPolyCollection): """Return a collection of squares.""" def __init__(self, **kwargs): super(SquareCollection, self).__init__(4, rotation=np.pi/4., **kwargs) def get_transform(self): """Return transform scaling circle areas to data space.""" ax = self.axes pts2pixels = 72.0 / ax.figure.dpi scale_x = pts2pixels * ax.bbox.width / ax.viewLim.width scale_y = pts2pixels * ax.bbox.height / ax.viewLim.height return transforms.Affine2D().scale(scale_x, scale_y) def hinton(inarray, max_value=None, use_default_ticks=True): """Plot Hinton diagram for visualizing the values of a 2D array. Plot representation of an array with positive and negative values represented by white and black squares, respectively. The size of each square represents the magnitude of each value. Unlike the hinton demo in the matplotlib gallery [1]_, this implementation uses a RegularPolyCollection to draw squares, which is much more efficient than drawing individual Rectangles. .. note:: This function inverts the y-axis to match the origin for arrays. .. [1] http://matplotlib.sourceforge.net/examples/api/hinton_demo.html Parameters ---------- inarray : array Array to plot. max_value : float Any *absolute* value larger than `max_value` will be represented by a unit square. use_default_ticks: boolean Disable tick-generation and generate them outside this function. """ ax = plt.gca() ax.set_axis_bgcolor('gray') # make sure we're working with a numpy array, not a numpy matrix inarray = np.asarray(inarray) height, width = inarray.shape if max_value is None: max_value = 2**np.ceil(np.log(np.max(np.abs(inarray)))/np.log(2)) values = np.clip(inarray/max_value, -1, 1) rows, cols = np.mgrid[:height, :width] pos = np.where(values > 0) neg = np.where(values < 0) for idx, color in zip([pos, neg], ['white', 'black']): if len(idx[0]) > 0: xy = list(zip(cols[idx], rows[idx])) circle_areas = np.pi / 2 * np.abs(values[idx]) squares = SquareCollection(sizes=circle_areas, offsets=xy, transOffset=ax.transData, facecolor=color, edgecolor=color) ax.add_collection(squares, autolim=True) ax.axis('scaled') # set data limits instead of using xlim, ylim. ax.set_xlim(-0.5, width-0.5) ax.set_ylim(height-0.5, -0.5) if use_default_ticks: ax.xaxis.set_major_locator(IndexLocator()) ax.yaxis.set_major_locator(IndexLocator()) class IndexLocator(ticker.Locator): def __init__(self, max_ticks=10): self.max_ticks = max_ticks def __call__(self): """Return the locations of the ticks.""" dmin, dmax = self.axis.get_data_interval() if dmax < self.max_ticks: step = 1 else: step = np.ceil(dmax / self.max_ticks) return self.raise_if_exceeds(np.arange(0, dmax, step)) plt.figure() A = np.random.uniform(-1, 1, size=(20, 20)) hinton(A) #special.hinton(A) plt.show()
Python
0
2633daf169d8fc3fbe3aa0d93b5126c1e835a2a0
Fix the form line restriction
accounting/apps/books/forms.py
accounting/apps/books/forms.py
from django.forms import ModelForm, BaseInlineFormSet from django.forms.models import inlineformset_factory from .models import ( Organization, TaxRate, TaxComponent, Invoice, InvoiceLine, Bill, BillLine, Payment) class RequiredFirstInlineFormSet(BaseInlineFormSet): """ Used to make empty formset forms required See http://stackoverflow.com/questions/2406537/django-formsets-\ make-first-required/4951032#4951032 """ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if len(self.forms) > 0: first_form = self.forms[0] first_form.empty_permitted = False class OrganizationForm(ModelForm): class Meta: model = Organization fields = ( "display_name", "legal_name", ) class TaxRateForm(ModelForm): class Meta: model = TaxRate fields = ( "name", "organization", ) class TaxComponentForm(ModelForm): class Meta: model = TaxComponent fields = ( "name", "percentage", ) TaxComponentFormSet = inlineformset_factory(TaxRate, TaxComponent, form=TaxComponentForm, formset=RequiredFirstInlineFormSet, min_num=1, extra=0) class RestrictLineFormToOrganizationMixin(object): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) instance = kwargs.get('instance', None) if instance: if isinstance(instance, InvoiceLine): organization = instance.invoice.organization elif isinstance(instance, BillLine): organization = instance.bill.organization else: raise NotImplementedError("The mixin has been applied to a " "form model that is not supported") self.fields['tax_rate'].queryset = organization.tax_rates.all() class InvoiceForm(ModelForm): class Meta: model = Invoice fields = ( "number", "organization", "client", "draft", "sent", "paid", "date_issued", "date_dued", ) class InvoiceLineForm(RestrictLineFormToOrganizationMixin, ModelForm): class Meta: model = InvoiceLine fields = ( "label", "description", "unit_price_excl_tax", "quantity", "tax_rate", ) InvoiceLineFormSet = inlineformset_factory(Invoice, InvoiceLine, form=InvoiceLineForm, formset=RequiredFirstInlineFormSet, min_num=1, extra=0) class BillForm(ModelForm): class Meta: model = Bill fields = ( "number", "client", "organization", "draft", "sent", "paid", "date_issued", "date_dued", ) class BillLineForm(RestrictLineFormToOrganizationMixin, ModelForm): class Meta: model = BillLine fields = ( "label", "description", "unit_price_excl_tax", "quantity", "tax_rate", ) BillLineFormSet = inlineformset_factory(Bill, BillLine, form=BillLineForm, formset=RequiredFirstInlineFormSet, min_num=1, extra=0) class PaymentForm(ModelForm): class Meta: model = Payment fields = ( "amount", "reference", "detail", "date_paid", )
from django.forms import ModelForm, BaseInlineFormSet from django.forms.models import inlineformset_factory from .models import ( Organization, TaxRate, TaxComponent, Invoice, InvoiceLine, Bill, BillLine, Payment) class RequiredFirstInlineFormSet(BaseInlineFormSet): """ Used to make empty formset forms required See http://stackoverflow.com/questions/2406537/django-formsets-\ make-first-required/4951032#4951032 """ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if len(self.forms) > 0: first_form = self.forms[0] first_form.empty_permitted = False class OrganizationForm(ModelForm): class Meta: model = Organization fields = ( "display_name", "legal_name", ) class TaxRateForm(ModelForm): class Meta: model = TaxRate fields = ( "name", "organization", ) class TaxComponentForm(ModelForm): class Meta: model = TaxComponent fields = ( "name", "percentage", ) TaxComponentFormSet = inlineformset_factory(TaxRate, TaxComponent, form=TaxComponentForm, formset=RequiredFirstInlineFormSet, min_num=1, extra=0) class RestrictLineFormToOrganization(object): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) instance = kwargs.get('instance', None) if instance: self.fields['tax_rate'].queryset = (instance .invoice .organization .tax_rates.all()) class InvoiceForm(ModelForm): class Meta: model = Invoice fields = ( "number", "organization", "client", "draft", "sent", "paid", "date_issued", "date_dued", ) class InvoiceLineForm(RestrictLineFormToOrganization, ModelForm): class Meta: model = InvoiceLine fields = ( "label", "description", "unit_price_excl_tax", "quantity", "tax_rate", ) InvoiceLineFormSet = inlineformset_factory(Invoice, InvoiceLine, form=InvoiceLineForm, formset=RequiredFirstInlineFormSet, extra=1) class BillForm(ModelForm): class Meta: model = Bill fields = ( "number", "client", "organization", "draft", "sent", "paid", "date_issued", "date_dued", ) class BillLineForm(RestrictLineFormToOrganization, ModelForm): class Meta: model = BillLine fields = ( "label", "description", "unit_price_excl_tax", "quantity", "tax_rate", ) BillLineFormSet = inlineformset_factory(Bill, BillLine, form=BillLineForm, formset=RequiredFirstInlineFormSet, extra=1) class PaymentForm(ModelForm): class Meta: model = Payment fields = ( "amount", "reference", "detail", "date_paid", )
Python
0.998355
533559e20e377ce042591709e53d7dc7031d6205
Add test for timer automatically inserted due to directive
tests/test_directives.py
tests/test_directives.py
"""tests/test_directives.py. Tests to ensure that directives interact in the etimerpected mannor Copyright (C) 2015 Timothy Edmund Crosley Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ import sys import hug api = sys.modules[__name__] def test_timer(): timer = hug.directives.timer() assert isinstance(timer.taken(), float) assert isinstance(timer.start, float) timer = hug.directives.timer('Time: {0}') assert isinstance(timer.taken(), str) assert isinstance(timer.start, float) @hug.get() def timer_tester(timer): return timer.taken() assert isinstance(hug.test.get(api, 'timer_tester').data, float)
"""tests/test_directives.py. Tests to ensure that directives interact in the etimerpected mannor Copyright (C) 2015 Timothy Edmund Crosley Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ import hug def test_timer(): timer = hug.directives.timer() assert isinstance(timer.taken(), float) assert isinstance(timer.start, float) timer = hug.directives.timer('Time: {0}') assert isinstance(timer.taken(), str) assert isinstance(timer.start, float)
Python
0
a3939b572c51b7a721b758cb5b93364e4b156c13
Add script that dumps the python path
dev_tools/syspath.py
dev_tools/syspath.py
#!/usr/bin/env python import sys # path[0], is the directory containing the script that was used to invoke the Python interpreter for s in sorted(sys.path[1:]): print s
Python
0.000002
f06a71a87daaaf0bc4b1f5701ce4c59805b70f6b
Format all local .json files for human readability
usr/bin/json_readable.py
usr/bin/json_readable.py
#!/usr/bin/env python import json, os for filename in os.listdir('.'): if os.path.isfile(filename) and os.path.splitext(filename)[1].lower() == '.json': with open(filename) as in_file: data = json.load(in_file) with open(filename, 'w') as out_file: json.dump(data, out_file, indent=4) # indent=4 makes the files human readable
Python
0
e736772d21aea0995a1948220e2dc2c6fa413fca
Add python zookeeper example
snippet/example/python/zookeeper.py
snippet/example/python/zookeeper.py
#!/usr/bin/env python # encoding: utf8 from __future__ import absolute_import, print_function, unicode_literals, division import zookeeper def refactor_path(f): def wrapper(*args, **kwargs): _refactor = kwargs.pop("refactor", True) if _refactor: path = kwargs.get("path", None) if path is not None: kwargs["path"] = args[0]._path(path) # args[0] is an instance of ZooKeeper return f(*args, **kwargs) return wrapper class ZooKeeper(object): DEFAULT_ACL = [{"perms": 0x1f, "scheme": "world", "id": "anyone"}] def __init__(self, connector, root="/", acl=None, flags=0): self.root = root.rstrip("/") if not self.root: self.root = "/" self.zk = zookeeper.init(connector) self.acl = acl if acl else self.DEFAULT_ACL self.flags = flags def _path(self, path): path = path.strip("/") if path: path = "/".join((self.root, path)) else: path = self.root return path @refactor_path def create(self, path="", value=""): try: zookeeper.create(self.zk, path, value, self.acl, self.flags) except zookeeper.NodeExistsException: pass except zookeeper.NoNodeException: self.create(path=path.rsplit("/", 1)[0], refactor=False) self.create(path=path, value=value, refactor=False) @refactor_path def delete(self, path="", recursion=True): try: zookeeper.delete(self.zk, path) except zookeeper.NoNodeException: pass except zookeeper.NotEmptyException: if recursion: for subpath in self.ls(path=path, refactor=False): self.delete(path="/".join((path, subpath)), recursion=recursion, refactor=False) self.delete(path=path, recursion=recursion, refactor=False) else: raise @refactor_path def set(self, path="", value=""): try: zookeeper.set(self.zk, path, value) except zookeeper.NoNodeException: self.create(path=path, value=value, refactor=False) self.set(path=path, value=value, refactor=False) @refactor_path def get(self, path=""): return zookeeper.get(self.zk, path) @refactor_path def ls(self, path=""): return zookeeper.get_children(self.zk, path) def close(self): zookeeper.close(self.zk)
Python
0.000235
798d9f39e9440f4f09cf83816c294f8ad9c06c4b
input api-method dummy
wa/api/input.py
wa/api/input.py
import sys def main(vars): import os import pickle for var in vars: variables = {} var_value = input(var + ": ") variables[var] = var_value if __name__ == "builtins": main(sys.argv[1:])
Python
0.999994
69997b088eba185864374bf55a311fa948dbda2f
Add yellow sign recognizer
street_sign_recognizer.py
street_sign_recognizer.py
#!/usr/bin/env python """ This is a script that walks through some of the basics of working with images with opencv in ROS. """ import rospy from sensor_msgs.msg import Image from cv_bridge import CvBridge import cv2 import numpy as np class StreetSignRecognizer(object): """ This robot should recognize street signs """ def __init__(self, image_topic): """ Initialize the ball tracker """ rospy.init_node('street_sign_recognizer') self.cv_image = None # the latest image from the camera self.bridge = CvBridge() # used to convert ROS messages to OpenCV rospy.Subscriber(image_topic, Image, self.process_image) cv2.namedWindow('video_window') self.use_slider = False self.use_mouse_hover = True # # # # # # # # # # # # # # color params, in HSV # # # # # # # # # # # # # # self.COLOR = "yellow" # which default color we binarize based on self.color_bounds = {} # tuned from the green hand ball self.color_bounds["green"] = ( np.array([60,76,2]) # min , np.array([80,255,255]) # max ) # tuned from yellow lturn sign self.color_bounds["yellow"] = ( np.array([23,175,130]) # min , np.array([32,255,255]) # max ) if self.use_mouse_hover: # when mouse hovers over video window cv2.setMouseCallback('video_window', self.process_mouse_event) if self.use_slider: cv2.namedWindow('threshold_image') self.hsv_lb = np.array([0, 0, 0]) cv2.createTrackbar('H lb', 'threshold_image', 0, 255, self.set_h_lb) cv2.createTrackbar('S lb', 'threshold_image', 0, 255, self.set_s_lb) cv2.createTrackbar('V lb', 'threshold_image', 0, 255, self.set_v_lb) self.hsv_ub = np.array([255, 255, 255]) cv2.createTrackbar('H ub', 'threshold_image', 0, 255, self.set_h_ub) cv2.createTrackbar('S ub', 'threshold_image', 0, 255, self.set_s_ub) cv2.createTrackbar('V ub', 'threshold_image', 0, 255, self.set_v_ub) # # # # # # # # # # # color callbacks # # # # # # # # # # # def set_h_lb(self, val): self.hsv_lb[0] = val def set_s_lb(self, val): self.hsv_lb[1] = val def set_v_lb(self, val): self.hsv_lb[2] = val def set_h_ub(self, val): self.hsv_ub[0] = val def set_s_ub(self, val): self.hsv_ub[1] = val def set_v_ub(self, val): self.hsv_ub[2] = val def process_image(self, msg): """ Process image messages from ROS and stash them in an attribute called cv_image for subsequent processing """ self.cv_image = self.bridge.imgmsg_to_cv2(msg, desired_encoding="bgr8") self.hsv_image = cv2.cvtColor(self.cv_image, cv2.COLOR_BGR2HSV) if self.use_slider: # binarize based on the slider values self.binarized_image = cv2.inRange(self.hsv_image, self.hsv_lb, self.hsv_ub) else: # binarize based on preset values self.binarized_image = cv2.inRange(self.hsv_image, self.color_bounds[self.COLOR][0], self.color_bounds[self.COLOR][1]) cv2.imshow('video_window', self.binarized_image) cv2.waitKey(5) def find_object_center(self, binary_image): moments = cv2.moments(binary_image) if moments['m00'] != 0: self.center_x, self.center_y = moments['m10']/moments['m00'], moments['m01']/moments['m00'] return True return False def process_mouse_event(self, event, x,y,flags,param): """ Process mouse events so that you can see the color values associated with a particular pixel in the camera images """ image_info_window = 255*np.ones((500,500,3)) # show hsv values cv2.putText(image_info_window, 'Color (h=%d,s=%d,v=%d)' % (self.hsv_image[y,x,0], self.hsv_image[y,x,1], self.hsv_image[y,x,2]), (5,50), # 5 = x, 50 = y cv2.FONT_HERSHEY_SIMPLEX, 1, (0,0,0)) # show bgr values cv2.putText(image_info_window, 'Color (b=%d,g=%d,r=%d)' % (self.cv_image[y,x,0], self.cv_image[y,x,1], self.cv_image[y,x,2]), (5,100), cv2.FONT_HERSHEY_SIMPLEX, 1, (0,0,0)) cv2.imshow('image_info', image_info_window) cv2.waitKey(5) def run(self): """ The main run loop, in this node it doesn't do anything """ r = rospy.Rate(5) while not rospy.is_shutdown(): r.sleep() if __name__ == '__main__': node = StreetSignRecognizer("/camera/image_raw") node.run()
Python
0.000001
101d334b80872c36adb5645ba0b3cda9b7c36a61
Add compliance with rule E261 to camo.py.
zerver/lib/camo.py
zerver/lib/camo.py
from django.conf import settings import codecs import hashlib import hmac from typing import Text # Encodes the provided URL using the same algorithm used by the camo # caching https image proxy def get_camo_url(url): # type: (Text) -> Text # Only encode the url if Camo is enabled if settings.CAMO_URI == '': return url encoded_url = url.encode("utf-8") encoded_camo_key = settings.CAMO_KEY.encode("utf-8") digest = hmac.new(encoded_camo_key, encoded_url, hashlib.sha1).hexdigest() hex_encoded_url = codecs.encode(encoded_url, "hex") # type: ignore # https://github.com/python/typeshed/issues/300 return "%s%s/%s" % (settings.CAMO_URI, digest, hex_encoded_url.decode("utf-8"))
from django.conf import settings import codecs import hashlib import hmac from typing import Text # Encodes the provided URL using the same algorithm used by the camo # caching https image proxy def get_camo_url(url): # type: (Text) -> Text # Only encode the url if Camo is enabled if settings.CAMO_URI == '': return url encoded_url = url.encode("utf-8") encoded_camo_key = settings.CAMO_KEY.encode("utf-8") digest = hmac.new(encoded_camo_key, encoded_url, hashlib.sha1).hexdigest() hex_encoded_url = codecs.encode(encoded_url, "hex") # type: ignore # https://github.com/python/typeshed/issues/300 return "%s%s/%s" % (settings.CAMO_URI, digest, hex_encoded_url.decode("utf-8"))
Python
0
c78dffb9b23e38fc980c06ff519e750f5d1e3678
add day1_short_palindrome.py - might work :)
10-days-of-stats/day1_short_palindrome.py
10-days-of-stats/day1_short_palindrome.py
#!/usr/bin/python3 # let's try to not do string comparisons and maybe list indexing # is faster than string indexing s = list(map(ord, list(input()))) slen = len(s) found = 0 # baseline optimization only (don't know if there is more possible) for a in range(0, slen-3): for d in range(a+3, slen): if not s[d] == s[a]: continue for b in range(a+1, d-1): for c in range(b+1, d): if s[b] == s[c]: found += 1 print(found % (10**9 + 7))
Python
0.000008
c0220578f4cd9b4c26879548751586615fe070e8
Add some freesurfer tools
cortex/freesurfer.py
cortex/freesurfer.py
import os import struct import tempfile import shlex import subprocess as sp import numpy as np import vtkutils_new as vtk def parse_curv(filename): with open(filename) as fp: fp.seek(15) return np.fromstring(fp.read(), dtype='>f4').byteswap() def show_surf(subject, hemi, type): from mayavi import mlab from tvtk.api import tvtk tf = tempfile.NamedTemporaryFile(suffix='.vtk') path = os.path.join(os.environ['SUBJECTS_DIR'], subject) surf_file = os.path.join(path, "surf", hemi+'.'+type) curv_file = os.path.join(path, "surf", hemi+'.curv') proc = sp.call(shlex.split('mris_convert {path} {tf}'.format(path=surf_file, tf=tf.name))) pts, polys, norms = vtk.read(tf.name) curv = parse_curv(curv_file) fig = mlab.figure() src = mlab.pipeline.triangular_mesh_source(pts[:,0], pts[:,1], pts[:,2], polys, scalars=curv, figure=fig) norms = mlab.pipeline.poly_data_normals(src, figure=fig) norms.filter.splitting = False surf = mlab.pipeline.surface(norms, figure=fig) surf.parent.scalar_lut_manager.set(lut_mode='RdBu', data_range=[-1,1], use_default_range=False) cursors = mlab.pipeline.scalar_scatter([0], [0], [0]) glyphs = mlab.pipeline.glyph(cursors, figure=fig) glyphs.glyph.glyph_source.glyph_source = glyphs.glyph.glyph_source.glyph_dict['axes'] fig.scene.background = (0,0,0) fig.scene.interactor.interactor_style = tvtk.InteractorStyleTerrain() def picker_callback(picker): if picker.actor in surf.actor.actors: npts = np.append(cursors.data.points.to_array(), [pts[picker.point_id]], axis=0) cursors.data.points = npts x, y, z = pts[picker.point_id] with open(os.path.join(path, 'tmp', 'edit.dat'), 'w') as fp: fp.write('%f %f %f\n'%(x, y, z)) picker = fig.on_mouse_pick(picker_callback) picker.tolerance = 0.01 return surf
Python
0
81806c7c66f501075937832f546765fecbd312fc
Fix HOPE tests
custom/hope/tests.py
custom/hope/tests.py
# Built-in imports from datetime import datetime # Django imports from django.test import TestCase # External libraries from casexml.apps.case.models import CommCareCase # CommCare HQ imports from corehq.apps.domain.models import Domain from corehq.apps.users.models import WebUser from custom.hope.models import HOPECase class TestHOPECaseResource(TestCase): """ Smoke test for the HOPECase wrapper on CommCareCase to make sure that the derived properties do not just immediately crash. """ def setUp(self): self.domain = Domain.get_or_create_with_name('qwerty', is_active=True) self.username = 'rudolph@qwerty.commcarehq.org' self.password = '***' self.user = WebUser.create(self.domain.name, self.username, self.password) self.user.set_role(self.domain.name, 'admin') self.user.save() def hit_every_HOPE_property(self, hope_case): """ Helper method that can be applied to a variety of HOPECase objects to make sure none of the _HOPE properties crash """ hope_case._HOPE_all_anc_doses_given hope_case._HOPE_all_dpt1_opv1_hb1_doses_given hope_case._HOPE_all_dpt2_opv2_hb2_doses_given hope_case._HOPE_all_dpt3_opv3_hb3_doses_given hope_case._HOPE_all_ifa_doses_given hope_case._HOPE_all_tt_doses_given hope_case._HOPE_bcg_indicator hope_case._HOPE_bpl_indicator hope_case._HOPE_delivery_type hope_case._HOPE_existing_child_count hope_case._HOPE_ifa1_date hope_case._HOPE_ifa2_date hope_case._HOPE_ifa3_date hope_case._HOPE_measles_dose_given hope_case._HOPE_num_visits hope_case._HOPE_opv_1_indicator hope_case._HOPE_patient_reg_num hope_case._HOPE_registration_date hope_case._HOPE_time_of_birth hope_case._HOPE_tubal_ligation def test_derived_properties(self): """ Smoke test that the HOPE properties do not crash on a pretty empty CommCareCase """ modify_date = datetime.utcnow() backend_case = CommCareCase(server_modified_on=modify_date, domain=self.domain.name) backend_case.save() # Rather than a re-fetch, this simulates the common case where it is pulled from ES hope_case = HOPECase.wrap(backend_case.to_json()) self.hit_every_HOPE_property(hope_case) backend_case.delete()
# Built-in imports from datetime import datetime # Django imports from django.test import TestCase # External libraries from casexml.apps.case.models import CommCareCase # CommCare HQ imports from corehq.apps.domain.models import Domain from corehq.apps.users.models import WebUser from custom.hope.models import HOPECase class TestHOPECaseResource(TestCase): """ Smoke test for the HOPECase wrapper on CommCareCase to make sure that the derived properties do not just immediately crash. """ def setUp(self): self.domain = Domain.get_or_create_with_name('qwerty', is_active=True) self.username = 'rudolph@qwerty.commcarehq.org' self.password = '***' self.user = WebUser.create(self.domain.name, self.username, self.password) self.user.set_role(self.domain.name, 'admin') self.user.save() def hit_every_HOPE_property(self, hope_case): """ Helper method that can be applied to a variety of HOPECase objects to make sure none of the _HOPE properties crash """ hope_case._HOPE_admission_date hope_case._HOPE_age_of_beneficiary hope_case._HOPE_all_anc_doses_given hope_case._HOPE_all_dpt1_opv1_hb1_doses_given hope_case._HOPE_all_dpt2_opv2_hb2_doses_given hope_case._HOPE_all_dpt3_opv3_hb3_doses_given hope_case._HOPE_all_ifa_doses_given hope_case._HOPE_all_tt_doses_given hope_case._HOPE_bpl_indicator hope_case._HOPE_child_age hope_case._HOPE_delivery_type hope_case._HOPE_discharge_date hope_case._HOPE_education hope_case._HOPE_existing_child_count hope_case._HOPE_ifa1_date hope_case._HOPE_ifa2_date hope_case._HOPE_ifa3_date hope_case._HOPE_measles_dose_given hope_case._HOPE_num_visits hope_case._HOPE_patient_reg_num hope_case._HOPE_registration_date hope_case._HOPE_time_of_birth hope_case._HOPE_tubal_ligation def test_derived_properties(self): """ Smoke test that the HOPE properties do not crash on a pretty empty CommCareCase """ modify_date = datetime.utcnow() backend_case = CommCareCase(server_modified_on=modify_date, domain=self.domain.name) backend_case.save() # Rather than a re-fetch, this simulates the common case where it is pulled from ES hope_case = HOPECase.wrap(backend_case.to_json()) self.hit_every_HOPE_property(hope_case) backend_case.delete()
Python
0.000005
ed4d07fb2a7fa8f1dd30a2b7982940a5fe78275b
Add the analysis driver for the run step of the study
dakota_run_driver.py
dakota_run_driver.py
#! /usr/bin/env python # Brokers communication between Dakota and SWASH through files. # # Arguments: # $1 is 'params.in' from Dakota # $2 is 'results.out' returned to Dakota import sys import os import shutil from subprocess import call def driver(): """Broker communication between Dakota and SWASH through files.""" # Files and directories. start_dir = os.path.dirname(os.path.realpath(__file__)) input_file = 'INPUT' input_template = input_file + '.template' output_file = 'bot07.mat' output_file_var = 'Botlev' data_file = 'sand.bot' run_script = 'run_swash.sh' # Use `dprepro` (from $DAKOTA_DIR/bin) to substitute parameter # values from Dakota into the SWASH input template, creating a new # SWASH input file. shutil.copy(os.path.join(start_dir, input_template), os.curdir) call(['dprepro', sys.argv[1], input_template, input_file]) # Copy the data file into the active directory. shutil.copy(os.path.join(start_dir, data_file), os.curdir) # Call SWASH through a PBS submission script. Note that `qsub` # returns immediately, so jobs do not block. job_name = 'SWASH-Dakota' + os.path.splitext(os.getcwd())[-1] call(['qsub', '-N', job_name, os.path.join(start_dir, run_script)]) # Provide a dummy results file to advance Dakota. with open(sys.argv[2], 'w') as fp: fp.write('0.0\n1.0\n') if __name__ == '__main__': driver()
Python
0.000003
ab9a0d25ded6a2c1410eea42fa4f85244671fa65
Add RethinkDB backend config file
mltsp/ext/rethinkdb_backend.py
mltsp/ext/rethinkdb_backend.py
# -*- coding: utf-8 -*- """ celery.backends.rethinkdb ~~~~~~~~~~~~~~~~~~~~~~~ RethinkDB result store backend. """ from __future__ import absolute_import import json try: import rethinkdb as r except ImportError: # pragma: no cover r = None # noqa from kombu.utils import cached_property from celery import states from celery.exceptions import ImproperlyConfigured from celery.five import string_t from celery.utils.timeutils import maybe_timedelta from celery.backends.base import BaseBackend __all__ = ['RethinkBackend'] class Bunch(object): def __init__(self, **kw): self.__dict__.update(kw) class RethinkBackend(BaseBackend): host = 'localhost' port = 28015 database_name = 'test' auth_key = '' timeout = 20 table_name = 'celery_taskmeta' options = None supports_autoexpire = False _connection = None def __init__(self, *args, **kwargs): """Initialize RethinkDB backend instance. :raises celery.exceptions.ImproperlyConfigured: if module :mod:`rethinkdb` is not available. """ self.options = {} super(RethinkBackend, self).__init__(*args, **kwargs) self.expires = kwargs.get('expires') or maybe_timedelta( self.app.conf.CELERY_TASK_RESULT_EXPIRES) if not r: raise ImproperlyConfigured( 'You need to install the rethinkdb library to use the ' 'RethinkDB backend.') config = self.app.conf.get('CELERY_RETHINKDB_BACKEND_SETTINGS') if config is not None: if not isinstance(config, dict): raise ImproperlyConfigured( 'RethinkDB backend settings should be grouped in a dict') config = dict(config) # do not modify original self.host = config.pop('host', self.host) self.port = int(config.pop('port', self.port)) self.database_name = config.pop('db', self.database_name) self.auth_key = config.pop('auth_key', self.auth_key) self.timeout = config.pop('timeout', self.timeout) self.table_name = config.pop('table', self.table_name) self.options = dict(config, **config.pop('options', None) or {}) def _get_connection(self): """Connect to the RethinkDB server.""" if self._connection is None: self._connection = r.connect(host=self.host, port=self.port, db=self.database_name, auth_key=self.auth_key, timeout=self.timeout, **self.options) return self._connection def process_cleanup(self): if self._connection is not None: # RethinkDB connection will be closed automatically when object # goes out of scope del(self.table) del(self.database) del(self.conn) self._connection.close() self._connection = None def _store_result(self, task_id, result, status, traceback=None, request=None, **kwargs): """Store return value and status of an executed task.""" meta = {'id': task_id, 'status': status, 'result': json.loads(self.encode(result)), 'date_done': r.now(), 'traceback': json.loads(self.encode(traceback)), 'children': json.loads(self.encode( self.current_task_children(request), ))} result = self.table.insert(meta, conflict='replace').run(self.conn) if result['errors']: raise Exception(result['first_error']) return meta def _get_task_meta_for(self, task_id): """Get task metadata for a task by id.""" obj = self.table.get(task_id).run(self.conn) if not obj: return {'status': states.PENDING, 'result': None} meta = { 'task_id': obj['id'], 'status': obj['status'], 'result': self.decode(json.dumps(obj['result'])), 'date_done': obj['date_done'], 'traceback': self.decode(json.dumps(obj['traceback'])), 'children': self.decode(json.dumps(obj['children'])), } return meta def _save_group(self, group_id, result): """Save the group result.""" meta = {'id': group_id, 'result': json.loads(self.encode(result)), 'date_done': r.now()} result = self.table.insert(meta, conflict='replace').run(self.conn) if result['errors']: raise Exception(result['first_error']) return meta def _restore_group(self, group_id): """Get the result for a group by id.""" obj = self.table.get(group_id).run(self.conn) if not obj: return meta = { 'task_id': obj['id'], 'result': self.decode(json.dumps(obj['result'])), 'date_done': obj['date_done'], } return meta def _delete_group(self, group_id): """Delete a group by id.""" result = self.table.get(group_id).delete().run(self.conn) if result['errors']: raise Exception(result['first_error']) def _forget(self, task_id): """ Remove result from RethinkDB. :raises celery.exceptions.OperationsError: if the task_id could not be removed. """ # By using safe=True, this will wait until it receives a response from # the server. Likewise, it will raise an OperationsError if the # response was unable to be completed. result = self.table.get(task_id).delete().run(self.conn) if result['errors']: raise Exception(result['first_error']) def cleanup(self): """Delete expired metadata.""" result = self.table.filter(r.row['date_done'].lt( self.app.now() - self.expires )).delete().run(self.conn) if result['errors']: raise Exception(result['first_error']) def __reduce__(self, args=(), kwargs={}): kwargs.update( dict(expires=self.expires)) return super(RethinkBackendRethinkBackend, self).__reduce__(args, kwargs) @cached_property def conn(self): """Get RethinkDB connection.""" conn = self._get_connection() return conn @cached_property def database(self): """Get database from RethinkDB connection.""" self._get_connection() db = r.db(self.database_name) # Ensure database exists if not self.database_name in r.db_list().run(self.conn): r.db_create(self.database_name).run(self.conn) return db @cached_property def table(self): """Get the metadata task table.""" table = self.database.table(self.table_name) # Ensure table exists if not self.table_name in self.database.table_list().run(self.conn): self.database.table_create(self.table_name).run(self.conn) # Ensure an index on date_done is there, if not process the index # in the background. Once completed cleanup will be much faster if not 'date_done' in table.index_list().run(self.conn): table.index_create('date_done').run(self.conn) return table
Python
0
ac5f30f9d58a25476c935d5266e9948b03efebf8
Add simple fetch tests
observatory/dashboard/tests/test_fetch.py
observatory/dashboard/tests/test_fetch.py
import pytest from dashboard.models import Project, Blog, Repository from emaillist.models import EmailAddress from django.contrib.auth.models import User @pytest.mark.django_db def test_fetch_warning(client): user = User.objects.create_user('a', 'vagrant@test.rcos.rpi.edu', 'bob') user.first_name = "testf" user.last_name = "testf" user.save() email = EmailAddress(address='vagrant@test.rcos.rpi.edu', user=user) email.save() ease_blog = Blog(from_feed = False) ease_blog.save() ease_repo = Repository(web_url = "http://git.gnome.org/browse/ease", clone_url = "git://git.gnome.org/ease", from_feed = False) ease_repo.save() ease = Project(title = "Ease", description = "A presentation application for the Gnome Desktop.", website = "http://www.ease-project.org", wiki = "http://live.gnome.org/Ease", blog_id = ease_blog.id, repository_id = ease_repo.id) ease.save() ease.authors.add(user) ease.save() ease.do_warnings() assert ease.blog_warn_level > 0 assert ease.repo_warn_level > 0
Python
0
7af99b98a9985aa1274c56ef8333b0c57a4679c9
add simple redis queue processor.
src/pyramid_weblayer/queue.py
src/pyramid_weblayer/queue.py
# -*- coding: utf-8 -*- """Provides a ``QueueProcessor`` utility that consumes and processes data from one or more redis channels. >>> redis_client = '<redis.Redis> instance' >>> input_channels = ['channel1', 'channeln'] >>> handle_data = lambda data_str: print data_str >>> processor = QueueProcessor(redis_client, input_channels, handle_data) Run in the main / current thread:: >>> # processor.start() Run in a background thread:: >>> # processor.start(async=True) If running in a background thread, call ``stop()`` to exit:: >>> # processor.stop() If you want jobs to be requeued (at the back of the queue) This provides a very simple inter-process messaging and / or background task processing mechanism. Queued messages / jobs are explictly passed as string messages. Pro: you're always in control of your code execution environment. Con: you have to deal with potentially tedious message parsing. """ import logging logger = logging.getLogger(__name__) import json import threading import time class QueueProcessor(object): """Consume data from a redis queue. When it arrives, pass it to ``self.handler_function``. """ running = False def stop(self): """Call ``stop()`` to stop processing the queue the next time a job is processed or the input queue timeout is reached. """ logger.info('QueueProcessor.stop()') self.running = False def _start(self): """Actually start processing the input queue(s) ad-infinitum.""" logger.debug('QueueProcessor.start()') logger.debug(self.channels) self.running = True while self.running: try: return_value = self.redis.blpop(self.channels, timeout=self.timeout) except Exception as err: logger.warn(err, exc_info=True) time.sleep(self.timeout) else: if return_value is not None: channel, body = return_value try: self.handle_function(body) except Exception as err: logger.warn(err, exc_info=True) logger.warn(return_value) if self.should_requeue: self.redis.rpush(channel, body) def start(self, async=False): """Either start running or start running in a thread.""" if self.running: return if async: threading.Thread(target=self._start).start() else: self._start() def __init__(self, redis_client, channels, handle_function, timeout=5, should_requeue=False): """Instantiate a queue processor:: >>> processor = QueueProcessor(None, None, None) """ self.redis = redis_client self.channels = channels self.handle_function = handle_function self.timeout = timeout self.should_requeue = should_requeue
Python
0
1975e6ebd57aac379ad19f5d4675f8f598c03c66
add utilNetworkIP
utilNetworkIP.py
utilNetworkIP.py
import socket import fcntl import struct ''' v0.1 2015/11/28 - add NetworkIP_get_ipAddress_eth0() - add get_ip_address() ''' def get_ip_address(ifname): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) return socket.inet_ntoa(fcntl.ioctl( s.fileno(), 0x8915, # SIOCGIFADDR struct.pack('256s', ifname[:15]) )[20:24]) def NetworkIP_get_ipAddress_eth0(): return get_ip_address('eth0')
Python
0.000024
eb4bf0e06920a6c14859b47d44e1a986a52e04a8
Add race-condition troubleshooting script.
xenserver/stress_test.py
xenserver/stress_test.py
""" This script concurrently builds and migrates instances. This can be useful when troubleshooting race-conditions in virt-layer code. Expects: novarc to be sourced in the environment Helper Script for Xen Dom0: # cat /tmp/destroy_cache_vdis #!/bin/bash xe vdi-list | grep "Glance Image" -C1 | grep "^uuid" | awk '{print $5}' | xargs -n1 -I{} xe vdi-destroy uuid={} """ import argparse import contextlib import multiprocessing import subprocess import sys import time DOM0_CLEANUP_SCRIPT = "/tmp/destroy_cache_vdis" def run(cmd): ret = subprocess.call(cmd, shell=True) if ret != 0: print >> sys.stderr, "Command exited non-zero: %s" % cmd @contextlib.contextmanager def server_built(server_name, image_name, flavor=1, cleanup=True): run("nova boot --image=%(image_name)s --flavor=%(flavor)s" " --poll %(server_name)s" % locals()) try: yield finally: if cleanup: run("nova delete %(server_name)s" % locals()) @contextlib.contextmanager def snapshot_taken(server_name, snapshot_name, cleanup=True): run("nova image-create %(server_name)s %(snapshot_name)s" " --poll" % locals()) try: yield finally: if cleanup: run("nova image-delete %(snapshot_name)s" % locals()) def migrate_server(server_name): run("nova migrate %(server_name)s --poll" % locals()) cmd = "nova list | grep %(server_name)s | awk '{print $6}'" % locals() proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True) stdout, stderr = proc.communicate() status = stdout.strip() if status.upper() != 'VERIFY_RESIZE': print >> sys.stderr, "Server %(server_name)s failed to rebuild"\ % locals() return False # Confirm the resize run("nova resize-confirm %(server_name)s" % locals()) return True def test_migrate(context): count, args = context server_name = "server%d" % count cleanup = args.cleanup with server_built(server_name, args.image, cleanup=cleanup): # Migrate A -> B result = migrate_server(server_name) if not result: return False # Migrate B -> A return migrate_server(server_name) def rebuild_server(server_name, snapshot_name): run("nova rebuild %(server_name)s %(snapshot_name)s --poll" % locals()) cmd = "nova list | grep %(server_name)s | awk '{print $6}'" % locals() proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True) stdout, stderr = proc.communicate() status = stdout.strip() if status != 'ACTIVE': print >> sys.stderr, "Server %(server_name)s failed to rebuild"\ % locals() return False return True def test_rebuild(context): count, args = context server_name = "server%d" % count snapshot_name = "snap%d" % count cleanup = args.cleanup with server_built(server_name, args.image, cleanup=cleanup): with snapshot_taken(server_name, snapshot_name, cleanup=cleanup): return rebuild_server(server_name, snapshot_name) def _parse_args(): parser = argparse.ArgumentParser( description='Test Nova for Race Conditions.') parser.add_argument('tests', metavar='TESTS', type=str, nargs='*', default=['rebuild', 'migrate'], help='tests to run: [rebuilt|migrate]') parser.add_argument('-i', '--image', help="image to build from", required=True) parser.add_argument('-n', '--num-runs', type=int, help="number of runs", default=1) parser.add_argument('-c', '--concurrency', type=int, default=5, help="number of concurrent processes") parser.add_argument('--no-cleanup', action='store_false', dest="cleanup", default=True) parser.add_argument('-d', '--dom0-ips', help="IP of dom0's to run cleanup script") return parser.parse_args() def main(): dom0_cleanup_script = DOM0_CLEANUP_SCRIPT args = _parse_args() if args.dom0_ips: dom0_ips = args.dom0_ips.split(',') else: dom0_ips = [] start_time = time.time() batch_size = min(args.num_runs, args.concurrency) pool = multiprocessing.Pool(processes=args.concurrency) results = [] for test in args.tests: test_func = globals().get("test_%s" % test) if not test_func: print >> sys.stderr, "test '%s' not found" % test sys.exit(1) contexts = [(x, args) for x in range(args.num_runs)] try: results += pool.map(test_func, contexts) finally: if args.cleanup: for dom0_ip in dom0_ips: run("ssh root@%(dom0_ip)s %(dom0_cleanup_script)s" % locals()) success = all(results) result = "SUCCESS" if success else "FAILED" duration = time.time() - start_time print "%s, finished in %.2f secs" % (result, duration) sys.exit(0 if success else 1) if __name__ == "__main__": main()
Python
0.000002
d8f5b31fab57cc009e87a8d62c8d03075f66e9bd
Add solution for Project Euler problem 72 (#3122)
project_euler/problem_072/sol2.py
project_euler/problem_072/sol2.py
""" Project Euler Problem 72: https://projecteuler.net/problem=72 Consider the fraction, n/d, where n and d are positive integers. If n<d and HCF(n,d)=1, it is called a reduced proper fraction. If we list the set of reduced proper fractions for d ≤ 8 in ascending order of size, we get: 1/8, 1/7, 1/6, 1/5, 1/4, 2/7, 1/3, 3/8, 2/5, 3/7, 1/2, 4/7, 3/5, 5/8, 2/3, 5/7, 3/4, 4/5, 5/6, 6/7, 7/8 It can be seen that there are 21 elements in this set. How many elements would be contained in the set of reduced proper fractions for d ≤ 1,000,000? """ def solution(limit: int = 1000000) -> int: """ Return the number of reduced proper fractions with denominator less than limit. >>> solution(8) 21 >>> solution(1000) 304191 """ primes = set(range(3, limit, 2)) primes.add(2) for p in range(3, limit, 2): if p not in primes: continue primes.difference_update(set(range(p * p, limit, p))) phi = [float(n) for n in range(limit + 1)] for p in primes: for n in range(p, limit + 1, p): phi[n] *= 1 - 1 / p return int(sum(phi[2:])) if __name__ == "__main__": print(f"{solution() = }")
Python
0
dab192db863fdd694bb0adbce10fa2dd6c05353b
Make the cli work again.
jrnl/__init__.py
jrnl/__init__.py
#!/usr/bin/env python # encoding: utf-8 """ jrnl is a simple journal application for your command line. """ __title__ = 'jrnl' __version__ = '1.0.3' __author__ = 'Manuel Ebert' __license__ = 'MIT License' __copyright__ = 'Copyright 2013 Manuel Ebert' from . import Journal from . import jrnl from .jrnl import cli
#!/usr/bin/env python # encoding: utf-8 """ jrnl is a simple journal application for your command line. """ __title__ = 'jrnl' __version__ = '1.0.3' __author__ = 'Manuel Ebert' __license__ = 'MIT License' __copyright__ = 'Copyright 2013 Manuel Ebert' from . import Journal from . import jrnl
Python
0
b7ea4cde920a69add4cbd4cfb76c651ec77910ce
Create __init__.py
bse/data/__init__.py
bse/data/__init__.py
Python
0.000429
ed36937ff6ccb2e676236b2bd128a2bb8fa9a760
add format_html util
dimagi/utils/html.py
dimagi/utils/html.py
from __future__ import absolute_import from django.utils.html import conditional_escape from django.utils.safestring import mark_safe def format_html(format_string, *args, **kwargs): escaped_args = map(conditional_escape, args) escaped_kwargs = dict([(key, conditional_escape(value)) for key, value in kwargs]) return mark_safe(format_string.format(*escaped_args, **escaped_kwargs))
Python
0.000002
8a668efbc266802a4f4e23c936d3589b230d9528
Add blink example on two different boards
nanpy/examples/blink_2boards.py
nanpy/examples/blink_2boards.py
#!/usr/bin/env python # Author: Andrea Stagi <stagi.andrea@gmail.com> # Description: keeps your led blinking on 2 boards # Dependencies: None from nanpy import (ArduinoApi, SerialManager) from time import sleep device_1 = '/dev/tty.usbmodem1411' device_2 = '/dev/tty.usbmodem1431' connection_1 = SerialManager(device=device_1) connection_2 = SerialManager(device=device_2) a1 = ArduinoApi(connection=connection_1) a1.pinMode(13, a1.OUTPUT) a2 = ArduinoApi(connection=connection_2) a2.pinMode(13, a2.OUTPUT) for i in range(10000): a1.digitalWrite(13, (i + 1) % 2) sleep(1) a2.digitalWrite(13, (i + 1) % 2) sleep(1)
Python
0
ee08eca3d8bb28819c2594bfdc855fbd7f743536
Add script to copy brifti files.
nipype/externals/copy_brifti.py
nipype/externals/copy_brifti.py
#!/usr/bin/env python """Script to copy brifti files from the git repos into nipype. I stole this from nipy.tools.copy_brifti.py. Matthew Brett is the original author, I've hacked the script to make it work with nipype. The script downloads the current pynifti git repository from my github account, pulls out the nifti python modules that we include in nipype, updates their impot paths, copies the modules into the nipype/externals/pynifti directory, then cleans up the temporary files/directories. Usage: ./copy_brifti.py It is assumed that this script lives in trunk/nipype/externals and that the python modules are in a subdirectory named 'pynifti'. """ import os import sys import shutil import tempfile import functools import subprocess import re # search replaces for imports subs = ( (re.compile(r'^([ >]*)(import|from) +nifti'), r'\1\2 nipype.externals.pynifti'), ) caller = functools.partial(subprocess.call, shell=True) #git_path = 'git://github.com/cburns/pynifti.git' # Working locally is much faster git_path = '/home/cburns/src/pynifti.git' git_tag = 'HEAD' # Assume this script resides in the trunk/nipype/externals directory, # and there is a subdirectory called pynifti where the brifti files # live. out_path = 'pynifti' def create_archive(out_path, git_path, git_tag): out_path = os.path.abspath(out_path) pwd = os.path.abspath(os.curdir) # put git clone in a tmp directory tmp_path = tempfile.mkdtemp() os.chdir(tmp_path) caller('git clone ' + git_path) # We only want the 'nifti' directory from the git repos, we'll # create an archive of that directory. os.chdir('pynifti') caller('git archive %s nifti > nifti.tar' % git_tag) os.chdir(tmp_path) # extract tarball and modify files before copying into out_path caller('tar xvf pynifti/nifti.tar') # done with git repository, remove it shutil.rmtree('pynifti') # For nipype, we don't copy the tests shutil.rmtree('nifti/derivations') shutil.rmtree('nifti/testing') shutil.rmtree('nifti/tests') # Walk through the nifti directory and update the import paths to # nipype paths. for root, dirs, files in os.walk('nifti'): for fname in files: if not fname.endswith('.py'): continue fpath = os.path.join(root, fname) lines = file(fpath).readlines() outfile = file(fpath, 'wt') for line in lines: for regexp, repstr in subs: if regexp.search(line): line = regexp.sub(repstr, line) continue outfile.write(line) outfile.close() # Create tarball of new files os.chdir('nifti') caller('tar cvf nifti.tar *') # Move the tarball to the nipype directory dst = os.path.join(out_path, 'nifti.tar') shutil.move('nifti.tar', dst) os.chdir(out_path) # Extract the tarball, overwriting existing files. caller('tar xvf nifti.tar') # Remove the tarball os.unlink(dst) # Remove temporary directory shutil.rmtree(tpm_path) if __name__ == '__main__': create_archive(out_path, git_path, git_tag)
Python
0.000006
61a005ffbc988b6a20441841112890bb397f8ca3
Create stub for 2016 NFLPool player picks
2016_player_picks.py
2016_player_picks.py
stone = {"firstname": "chris", "lastname": "stone", "timestamp": "9/6/2016", "email": "stone@usisales.com", "afc_east_1": "Patriots", "afc_east_2": "Jets", "afc_east_last": "Bills", "afc_north_1": "Steelers", "afc_north_2": "Bengals", "afc_north_last": "Browns", "afc_south_1": "Colts", "afc_south_2": "Colts", "afc_south_last": "Titans"} thaden = [] garber = [] fronczak = [] thomas = [] cutler = [] norred = [] oakland = []
Python
0
893e4292f6b1799bf5f1888fcbad41ec8b5a5951
Use Q-learning to learn all state-action values via self-play
examples/tic_ql_tabular_selfplay_all.py
examples/tic_ql_tabular_selfplay_all.py
''' In this example we use Q-learning via self-play to learn the value function of all Tic-Tac-Toe positions. ''' from capstone.environment import Environment from capstone.game import TicTacToe from capstone.mdp import GameMDP from capstone.rl import QLearningSelfPlay from capstone.rl.tabularf import TabularF from capstone.util import tic2pdf game = TicTacToe() env = Environment(GameMDP(game)) qlearning = QLearningSelfPlay(env, n_episodes=1000) qlearning.learn() for move in game.legal_moves(): print('-' * 80) value = qlearning.qf[(game, move)] new_game = game.copy().make_move(move) print(value) print(new_game)
Python
0
af9b64bcf99d0e2c13b9b6b05a6b4029a0bb7d28
Add theimdbapi provider, it's faster than myapifilms.
providers/moviedata/theimdbapi.py
providers/moviedata/theimdbapi.py
import re from providers.moviedata.provider import MoviedataProvider from application import ACCESS_KEYS, APPLICATION as APP try: from urllib import urlencode # Python 2.X except ImportError: from urllib.parse import urlencode # Python 3+ IDENTIFIER = "theimdbapi" class Provider(MoviedataProvider): def get_url(self, movie): parameters = { "title": movie["name"].encode("utf-8"), } if "year" in movie and movie["year"]: parameters["year"] = movie["year"] return "http://www.theimdbapi.org/api/find/movie?" + urlencode(parameters) def fetch_movie_data(self, movie): url = self.get_url(movie) APP.debug("Fetching url: %s" % url) data = self.parse_json(url) if not data: return {} for hit in data: # Return the first hit with a release date if hit and "release_date" in hit and hit["release_date"]: return self.transform_data(hit) return {} def get_data_mapping(self): return { "id": "imdb_id", "title": "title", "plot": "storyline", "genre": "genre", "director": "director", "country": "metadata.countries", "language": "metadata.languages", "runtime": "length", "released": "release_date", "age_rating": "content_rating", "year": "year", "imdb_url": "url", "imdb_poster": "poster.large", "imdb_rating": "rating", "imdb_rating_count": "rating_count", }
Python
0
a8419c46ceed655a276dad00a24e21f300fda543
Add py solution for 513. Find Bottom Left Tree Value
py/find-bottom-left-tree-value.py
py/find-bottom-left-tree-value.py
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def findBottomLeftValue(self, root): """ :type root: TreeNode :rtype: int """ q = [root] for v in q: if v.right: q.append(v.right) if v.left: q.append(v.left) return v.val
Python
0.000235
1e45505a94f23198d0ec464107c12d29d4d9aa16
Add tests for libdft
pyscf/lib/dft/test/test_libdft.py
pyscf/lib/dft/test/test_libdft.py
#!/usr/bin/env python import unittest import ctypes import itertools import numpy from pyscf.dft.numint import libdft class KnownValues(unittest.TestCase): def test_empty_blocks(self): ao_loc = numpy.array([0,51,60,100,112,165,172], dtype=numpy.int32) def get_empty_mask(non0tab_mask): non0tab_mask = numpy.asarray(non0tab_mask, dtype=numpy.uint8) shls_slice = (0, non0tab_mask.size) empty_mask = numpy.empty(4, dtype=numpy.int8) empty_mask[:] = -9 libdft.VXCao_empty_blocks( empty_mask.ctypes.data_as(ctypes.c_void_p), non0tab_mask.ctypes.data_as(ctypes.c_void_p), (ctypes.c_int*2)(*shls_slice), ao_loc.ctypes.data_as(ctypes.c_void_p)) return empty_mask.tolist() def naive_emtpy_mask(non0tab_mask): blksize = 56 ao_mask = numpy.zeros(ao_loc[-1], dtype=bool) for k, (i0, i1) in enumerate(zip(ao_loc[:-1], ao_loc[1:])): ao_mask[i0:i1] = non0tab_mask[k] == 1 valued = [m.any() for m in numpy.split(ao_mask, [56, 112, 168])] empty_mask = ~numpy.array(valued) return empty_mask.astype(numpy.int).tolist() def check(non0tab_mask): if get_empty_mask(non0tab_mask) != naive_emtpy_mask(non0tab_mask): raise ValueError(non0tab_mask) for mask in list(itertools.product([0, 1], repeat=6)): check(mask) if __name__ == "__main__": print("Test libdft") unittest.main()
Python
0
d2aca979f2c8a711bbc139675cf699b6ce5ce53d
Update keys-and-rooms.py
Python/keys-and-rooms.py
Python/keys-and-rooms.py
# Time: O(n!) # Space: O(n) # There are N rooms and you start in room 0. # Each room has a distinct number in 0, 1, 2, ..., N-1, # and each room may have some keys to access the next room. # # Formally, each room i has a list of keys rooms[i], # and each key rooms[i][j] is an integer in [0, 1, ..., N-1] # where N = rooms.length. # A key rooms[i][j] = v opens the room with number v. # # Initially, all the rooms start locked (except for room 0). # You can walk back and forth between rooms freely. # Return true if and only if you can enter every room. # # Example 1: # # Input: [[1],[2],[3],[]] # Output: true # Explanation: # We start in room 0, and pick up key 1. # We then go to room 1, and pick up key 2. # We then go to room 2, and pick up key 3. # We then go to room 3. Since we were able to go to every room, # we return true. # Example 2: # # Input: [[1,3],[3,0,1],[2],[0]] # Output: false # Explanation: We can't enter the room with number 2. # # Note: # - 1 <= rooms.length <= 1000 # - 0 <= rooms[i].length <= 1000 # - The number of keys in all rooms combined is at most 3000. class Solution(object): def canVisitAllRooms(self, rooms): """ :type rooms: List[List[int]] :rtype: bool """ lookup = set([0]) stack = [0] while stack: node = stack.pop() for nei in rooms[node]: if nei not in lookup: lookup.add(nei) if len(lookup) == len(rooms): return True stack.append(nei) return len(lookup) == len(rooms)
# There are N rooms and you start in room 0. # Each room has a distinct number in 0, 1, 2, ..., N-1, # and each room may have some keys to access the next room. # # Formally, each room i has a list of keys rooms[i], # and each key rooms[i][j] is an integer in [0, 1, ..., N-1] # where N = rooms.length. # A key rooms[i][j] = v opens the room with number v. # # Initially, all the rooms start locked (except for room 0). # You can walk back and forth between rooms freely. # Return true if and only if you can enter every room. # # Example 1: # # Input: [[1],[2],[3],[]] # Output: true # Explanation: # We start in room 0, and pick up key 1. # We then go to room 1, and pick up key 2. # We then go to room 2, and pick up key 3. # We then go to room 3. Since we were able to go to every room, # we return true. # Example 2: # # Input: [[1,3],[3,0,1],[2],[0]] # Output: false # Explanation: We can't enter the room with number 2. # # Note: # - 1 <= rooms.length <= 1000 # - 0 <= rooms[i].length <= 1000 # - The number of keys in all rooms combined is at most 3000. class Solution(object): def canVisitAllRooms(self, rooms): """ :type rooms: List[List[int]] :rtype: bool """ lookup = set([0]) stack = [0] while stack: node = stack.pop() for nei in rooms[node]: if nei not in lookup: lookup.add(nei) if len(lookup) == len(rooms): return True stack.append(nei) return len(lookup) == len(rooms)
Python
0.000001
29a2dcf4ab6684187d95e0faab171b5e071e1eee
Create main.py
python/using_sqlalchemy01/main.py
python/using_sqlalchemy01/main.py
from .models import User from .database import session_scope if __name__ == '__main__': with session_scope() as session: users = session.query( User ).order_by( User.id ) # Remove all object instances from this Session to make them available to accessed by outside users.expunge_all() for u in users: print u
Python
0.000001
95ff080685f01cbb368d9467f67076ce9f3eae08
add generic resource creator
stacker_blueprints/generic.py
stacker_blueprints/generic.py
""" Load dependencies """ from troposphere import ( Ref, Output ) from stacker.blueprints.base import Blueprint from stacker.blueprints.variables.types import ( CFNString, CFNCommaDelimitedList, ) class generic_resource_creator(Blueprint): """ Generic Blueprint for creating a resource """ def add_cfn_description(self): """ Boilerplate for CFN Template """ template = self.template template.add_version('2010-09-09') template.add_description('Generic Resource Creator - 1.0.0') """ *** NOTE *** Template Version Reminder Make Sure you bump up the template version number above if submitting updates to the repo. This is the only way we can tell which version of a template is in place on a running resouce. """ VARIABLES = { 'Class': {'type': str, 'description': 'The troposphere class to create'}, 'Output': {'type': str, 'description': 'The output to create'}, 'Properties': {'type': dict, 'description': 'The list of propertie to use for the troposphere class'}, } def setup_resource(self): template = self.template variables = self.get_variables() tclass = variables['Class'] tprops = variables['Properties'] output = variables['Output'] klass = self.get_class('troposphere.' + tclass) # we need to do the following because of type conversion issues tprops_string = {} for variable, value in tprops.items(): tprops_string[variable] = str(value) instance = klass.from_dict('ResourceRefName', tprops_string) template.add_resource(instance) template.add_output(Output( output, Description="The output", Value=Ref(instance) )) def create_template(self): """ Create the CFN template """ self.add_cfn_description() self.setup_resource() def get_class(self, kls): parts = kls.split('.') module = ".".join(parts[:-1]) m = __import__( module ) for comp in parts[1:]: m = getattr(m, comp) return m
Python
0
3dcf737fa6a6467e1c96d31325e26ecf20c50320
Add test cases for the logger
test/test_logger.py
test/test_logger.py
# encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com> """ from __future__ import print_function from __future__ import unicode_literals import logbook import pytest from sqliteschema import ( set_logger, set_log_level, ) class Test_set_logger(object): @pytest.mark.parametrize(["value"], [ [True], [False], ]) def test_smoke(self, value): set_logger(value) class Test_set_log_level(object): @pytest.mark.parametrize(["value"], [ [logbook.CRITICAL], [logbook.ERROR], [logbook.WARNING], [logbook.NOTICE], [logbook.INFO], [logbook.DEBUG], [logbook.TRACE], [logbook.NOTSET], ]) def test_smoke(self, value): set_log_level(value) @pytest.mark.parametrize(["value", "expected"], [ [None, LookupError], ["unexpected", LookupError], ]) def test_exception(self, value, expected): with pytest.raises(expected): set_log_level(value)
Python
0.000002
9100581d63f52281c42e89ad618b0e411907cb4a
Test to help develop psf measure
test_psf_measure.py
test_psf_measure.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # # test_recoverstats.py # # Copyright 2016 Bruno S <bruno.sanchez.63@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. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, # MA 02110-1301, USA. # # import os import shlex import subprocess import numpy as np import matplotlib.pyplot as plt from scipy.stats import stats import sep from astropy.convolution import convolve from astropy.convolution import convolve_fft from astropy.time import Time from astropy.io import fits from astropy.stats import sigma_clipped_stats from astropy.stats import signal_to_noise_oir_ccd from astropy.table import Table from astropy.modeling import fitting from astropy.modeling import models from astropy.nddata.utils import extract_array from photutils import psf from photutils import daofind from imsim import simtools import propercoadd as pc N = 512 # side FWHM = 12 test_dir = os.path.abspath('./test_images/measure_psf') x = np.linspace(5*FWHM, N-5*FWHM, 3) y = np.linspace(5*FWHM, N-5*FWHM, 3) xy = simtools.cartesian_product([x, y]) SN = 100. # SN para poder medir psf weights = list(np.linspace(10, 100, len(xy))) m = simtools.delta_point(N, center=False, xy=xy, weights=weights) im = simtools.image(m, N, t_exp=1, FWHM=FWHM, SN=SN, bkg_pdf='poisson') sim = pc.SingleImage(im) sim.subtract_back() srcs = sep.extract(sim.bkg_sub_img, thresh=30*sim.bkg.globalrms) posflux = srcs[['x','y', 'flux']] fitted_models = sim.fit_psf_sep() #Manual test prf_model = models.Gaussian2D(x_stddev=1, y_stddev=1) fitter = fitting.LevMarLSQFitter() indices = np.indices(sim.bkg_sub_img.shape) model_fits = [] best_srcs = srcs[srcs['flag'] == 0] fitshape = (4*FWHM, 4*FWHM) prf_model.x_mean = fitshape[0]/2. prf_model.y_mean = fitshape[1]/2. for row in best_srcs: position = (row['y'], row['x']) y = extract_array(indices[0], fitshape, position) x = extract_array(indices[1], fitshape, position) sub_array_data = extract_array(sim.bkg_sub_img, fitshape, position, fill_value=sim.bkg.globalback) prf_model.x_mean = position[1] prf_model.y_mean = position[0] fit = fitter(prf_model, x, y, sub_array_data) print fit model_fits.append(fit) plt.subplot(131) plt.imshow(fit(x, y)) plt.title('fit') plt.subplot(132) plt.title('sub_array') plt.imshow(sub_array_data) plt.subplot(133) plt.title('residual') plt.imshow(sub_array_data - fit(x,y)) plt.show() ## Things are running somewhat like expected # Again and simpler N = 128 # side FWHM = 6 SN = 100. # SN para poder medir psf m = simtools.delta_point(N, center=False, xy=[[50, 64]]) im = simtools.image(m, N, t_exp=1, FWHM=FWHM, SN=SN, bkg_pdf='gaussian') fitshape = (64,64)#(6*FWHM, 6*FWHM) prf_model = models.Gaussian2D(x_stddev=3, y_stddev=3, x_mean=fitshape[0], y_mean=fitshape[1]) fitter = fitting.LevMarLSQFitter() indices = np.indices(im) position = (50, 64) prf_model.y_mean, prf_model.x_mean = position y = extract_array(indices[0], fitshape, position) x = extract_array(indices[1], fitshape, position) sub_array_data = extract_array(im, fitshape, position) fit = fitter(prf_model, x, y, sub_array_data) print fit plt.subplot(221) plt.imshow(im) plt.subplot(222) plt.imshow(fit(x, y)) plt.title('fit') plt.subplot(223) plt.imshow(sub_array_data) plt.subplot(224) plt.imshow(sub_array_data - fit(x,y)) plt.show() print 'hola'
Python
0
b410facc9e7882ecec1bc1029caa3f35a3a28d03
Test for bundle API
tests/bundle_api.py
tests/bundle_api.py
#!/usr/bin/env python # pylint: disable-msg=C0103 """Implements an Execution Manager for the AIMES demo. """ __author__ = "Matteo Turilli, Andre Merzky" __copyright__ = "Copyright 2014, RADICAL" __license__ = "MIT" import os import radical.utils as ru import aimes.bundle import aimes.emanager.interface # Set environment directories to test the bundle API. CONF = os.getenv("BUNDLE_CONF") ORIGIN = os.getenv("BUNDLE_ORIGIN") # Create a reporter for the demo. Takes care of colors and font attributes. report = ru.Reporter(title='Bundle API test') bundle = aimes.emanager.interface.Bundle(CONF, ORIGIN) # Collect information about the resources to plan the execution strategy. bandwidth_in = dict() bandwidth_out = dict() # Get network bandwidth for each resource. for resource_name in bundle.resources: resource = bundle.resources[resource_name] bandwidth_in[resource.name] = resource.get_bandwidth(ORIGIN, 'in') bandwidth_out[resource.name] = resource.get_bandwidth(ORIGIN, 'out') # Report back to the demo about the available resource bundle. report.info("Target Resources") print "IDs: %s" % \ [bundle.resources[resource].name for resource in bundle.resources] # Print all the information available via the bundle API. for resource_name in bundle.resources: resource = bundle.resources[resource_name] report.info("resource.name : %s" % resource.name) print "resource.num_nodes: %s" % resource.num_nodes print "resource.container: %s" % resource.container print "resource.get_bandwidth(IP, 'in') : %s" % \ resource.get_bandwidth(ORIGIN, 'in') print "resource.get_bandwidth(IP, 'out'): %s" % \ resource.get_bandwidth(ORIGIN, 'out') print "resource.queues : %s" % resource.queues.keys() for queue_name in resource.queues: queue = resource.queues[queue_name] print print " queue.name : %s" % queue.name print " queue.resource_name : %s" % queue.resource_name print " queue.max_walltime : %s" % queue.max_walltime print " queue.num_procs_limit : %s" % queue.num_procs_limit print " queue.alive_nodes : %s" % queue.alive_nodes print " queue.alive_procs : %s" % queue.alive_procs print " queue.busy_nodes : %s" % queue.busy_nodes print " queue.busy_procs : %s" % queue.busy_procs print " queue.free_nodes : %s" % queue.free_nodes print " queue.free_procs : %s" % queue.free_procs print " queue.num_queueing_jobs: %s" % queue.num_queueing_jobs print " queue.num_running_jobs : %s" % queue.num_running_jobs
Python
0
8b0b7c19d2e2c015fd8ba7d5408b23334ee8874f
Add test case for configure failure.
test/Configure/VariantDir2.py
test/Configure/VariantDir2.py
#!/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__" """ Verify that Configure contexts work with SConstruct/SConscript structure """ import os import TestSCons test = TestSCons.TestSCons() test.write('SConstruct', """\ SConscript('SConscript', build_dir='build', src='.') """) test.write('SConscript', """\ env = Environment() config = env.Configure(conf_dir='sconf', log_file='config.log') config.TryRun("int main() {}", ".c") config.Finish() """) test.run() test.pass_test()
Python
0
1fd09e7328b1ebf41bc0790f2a96c18207b10077
Add sine wave sweep test
tests/test-sweep.py
tests/test-sweep.py
#!/usr/bin/env python try: from cStringIO import StringIO except ImportError: from io import StringIO class Makefile(object): def __init__(self): self._fp = StringIO() self._all = set() self._targets = set() def add_default(self, x): self._all.add(x) def build(self, target, deps, *cmds): if target in self._targets: return self._targets.add(target) fp = self._fp fp.write(target + ':') for dep in deps: fp.write(' ' + dep) fp.write('\n') for cmd in cmds: fp.write('\t' + cmd + '\n') def write(self, *line): for line in line: self._fp.write(line + '\n') def save(self): f = open('Makefile', 'w') f.write('all:') for t in sorted(self._all): f.write(' ' + t) f.write('\n') f.write(self._fp.getvalue()) make = Makefile() make.write( 'FR := ../build/product/fresample', 'SOX := sox') def test_sweep(depth, rate1, rate2): inpath = 'in_%dk%d.wav' % (rate1 // 1000, depth) make.build( inpath, ['Makefile'], '$(SOX) -b %d -r %d -n $@ synth 8 sine 0+%d vol 0.999' % (depth, rate1, rate1//2)) for q in range(4): outpath = 'out_%dk%d_%dk%dq' % \ (rate1 // 1000, depth, rate2/1000, q) make.build( outpath + '.wav', [inpath, '$(FR)', 'Makefile'], '$(FR) -q %d -r %d $< $@' % (q, rate2)) make.build( outpath + '.png', [outpath + '.wav', 'Makefile'], 'sox $< -n spectrogram -w kaiser -o $@') make.add_default(outpath + '.png') test_sweep(16, 96000, 44100) test_sweep(16, 96000, 48000) test_sweep(16, 48000, 44100) make.write( 'clean:', '\trm -f *.wav *.png') make.save()
Python
0
93b65dd6707093487dc702fd94cdb3c6017d873b
add unit tests for translate_ix_member_name in ixapi.py
tests/test_ixapi.py
tests/test_ixapi.py
from pyixia.ixapi import translate_ix_member_name from nose.tools import eq_ def test_translate_ix_member_name(): eq_(translate_ix_member_name('A'), 'a') eq_(translate_ix_member_name('b'), 'b') eq_(translate_ix_member_name('AA'), 'aa') eq_(translate_ix_member_name('bb'), 'bb') eq_(translate_ix_member_name('Ab'), 'ab') eq_(translate_ix_member_name('bA'), 'b_a') eq_(translate_ix_member_name('bbb'), 'bbb') eq_(translate_ix_member_name('AAA'), 'aaa') eq_(translate_ix_member_name('bAA'), 'b_aa') eq_(translate_ix_member_name('Abb'), 'abb') eq_(translate_ix_member_name('bbA'), 'bb_a') eq_(translate_ix_member_name('AAb'), 'a_ab') eq_(translate_ix_member_name('AbA'), 'ab_a') eq_(translate_ix_member_name('bAb'), 'b_ab') eq_(translate_ix_member_name('AAAA'), 'aaaa') eq_(translate_ix_member_name('bbbb'), 'bbbb') eq_(translate_ix_member_name('Abbb'), 'abbb') eq_(translate_ix_member_name('bAAA'), 'b_aaa') eq_(translate_ix_member_name('AAbb'), 'a_abb') eq_(translate_ix_member_name('bbAA'), 'bb_aa') eq_(translate_ix_member_name('AAAb'), 'aa_ab') eq_(translate_ix_member_name('bbbA'), 'bbb_a') eq_(translate_ix_member_name('AbAb'), 'ab_ab') eq_(translate_ix_member_name('bAbA'), 'b_ab_a') eq_(translate_ix_member_name('AbAA'), 'ab_aa') eq_(translate_ix_member_name('AAbA'), 'a_ab_a') eq_(translate_ix_member_name('bbAb'), 'bb_ab') eq_(translate_ix_member_name('bAbb'), 'b_abb') eq_(translate_ix_member_name('AbbA'), 'abb_a') eq_(translate_ix_member_name('bAAb'), 'b_a_ab') eq_(translate_ix_member_name('framerFCSErrors'), 'framer_fcs_errors') eq_(translate_ix_member_name('ID'), 'id')
Python
0
9b50c5c8082a39bf36b1f23303bf148b0cc4f345
Add proxy tests, some of them still broken
tests/test_proxy.py
tests/test_proxy.py
import unittest from kiwi import ValueUnset from kiwi.python import Settable from kiwi.ui.proxy import Proxy from kiwi.ui.widgets.checkbutton import ProxyCheckButton from kiwi.ui.widgets.entry import ProxyEntry from kiwi.ui.widgets.label import ProxyLabel from kiwi.ui.widgets.radiobutton import ProxyRadioButton from kiwi.ui.widgets.spinbutton import ProxySpinButton from kiwi.ui.widgets.textview import ProxyTextView class FakeView(object): def __init__(self): self.widgets = [] def add(self, name, data_type, widget_type): widget = widget_type() widget.set_property('model-attribute', name) widget.set_property('data-type', data_type) setattr(self, name, widget) self.widgets.append(name) return widget def handler_block(self, *args): pass def handler_unblock(self, *args): pass class Model(Settable): def __init__(self): Settable.__init__(self, entry='foo', checkbutton=True, radiobutton='first', label='label', spinbutton=100, textview='sliff') class TestProxy(unittest.TestCase): def setUp(self): self.view = FakeView() self.view.add('checkbutton', bool, ProxyCheckButton) self.view.add('entry', str, ProxyEntry) self.view.add('label', str, ProxyLabel) self.view.add('spinbutton', int, ProxySpinButton) self.view.add('textview', str, ProxyTextView) self.radio_first = self.view.add('radiobutton', str, ProxyRadioButton) self.radio_first.set_property('data_value', 'first') self.radio_second = ProxyRadioButton() self.radio_second.set_group(self.radio_first) self.radio_second.set_property('data_value', 'second') self.model = Model() self.proxy = Proxy(self.view, self.model, self.view.widgets) def testCheckButton(self): self.assertEqual(self.model.checkbutton, True) self.view.checkbutton.set_active(False) self.assertEqual(self.model.checkbutton, False) def testEntry(self): self.assertEqual(self.model.entry, 'foo') self.view.entry.set_text('bar') self.assertEqual(self.model.entry, 'bar') def testLabel(self): self.assertEqual(self.model.label, 'label') self.view.label.set_text('other label') self.assertEqual(self.model.label, 'other label') def testRadioButton(self): self.assertEqual(self.model.radiobutton, 'first') self.radio_second.set_active(True) self.assertEqual(self.model.radiobutton, 'second') self.radio_first.set_active(True) self.assertEqual(self.model.radiobutton, 'first') def testSpinButton(self): self.assertEqual(self.model.spinbutton, 100) self.view.spinbutton.set_text('200') #self.assertEqual(self.model.spinbutton, 200) def testTextView(self): self.assertEqual(self.model.textview, 'sliff') self.view.textview.get_buffer().set_text('sloff') #self.assertEqual(self.model.textview, 'sliff') def testEmptyModel(self): self.radio_second.set_active(True) self.proxy.set_model(None) self.assertEqual(self.view.entry.read(), '') self.assertEqual(self.view.checkbutton.read(), False) self.assertEqual(self.view.radiobutton.read(), 'first') self.assertEqual(self.view.label.read(), '') self.assertEqual(self.view.spinbutton.read(), ValueUnset) self.assertEqual(self.view.textview.read(), '')
Python
0
2e4111dda23e6d686c188cf832f7b6c7c19ea14b
Test ReadLengthStatistics
tests/test_stats.py
tests/test_stats.py
from cutadapt.statistics import ReadLengthStatistics class TestReadLengthStatistics: def test_empty_on_init(self): rls = ReadLengthStatistics() assert rls.written_reads() == 0 assert rls.written_bp() == (0, 0) lengths = rls.written_lengths() assert not lengths[0] and not lengths[1] def test_some_reads(self): rls = ReadLengthStatistics() rls.update("THEREAD") # length: 7 rls.update("YETANOTHER") # length: 10 rls.update2("FIRST", "SECOND") # lengths: 5, 6 rls.update("12345") assert rls.written_reads() == 4 assert rls.written_bp() == (7 + 10 + 5 + 5, 6) lengths = rls.written_lengths() assert sorted(lengths[0].items()) == [(5, 2), (7, 1), (10, 1)] assert sorted(lengths[1].items()) == [(6, 1)] def test_iadd(self): rls = ReadLengthStatistics() rls.update("THEREAD") # length: 7 rls.update("YETANOTHER") # length: 10 rls.update2("FIRST", "SECOND") # lengths: 5, 6 rls.update("12345") rls2 = ReadLengthStatistics() rls2.update("TESTING") # length: 7 rls2.update2("LEFT", "RIGHT") # lengths: 4, 5 rls += rls2 assert rls.written_reads() == 6 assert rls.written_bp() == (7 + 10 + 5 + 5 + 7 + 4, 6 + 5) lengths = rls.written_lengths() assert sorted(lengths[0].items()) == [(4, 1), (5, 2), (7, 2), (10, 1)] assert sorted(lengths[1].items()) == [(5, 1), (6, 1)]
Python
0
1165673d784eab36edcdc4ed4caf22dbd222874a
Add some preliminary code and function to enlarge image
whois-scraper.py
whois-scraper.py
from lxml import html from PIL import Image import requests def enlarge_image(image_file): image = Image.open(image_file) enlarged_size = map(lambda x: x*2, image.size) enlarged_image = image.resize(enlarged_size) return enlarged_image def extract_text(image_file): image = enlarge_image(image_file) # Use Tesseract to extract text from the enlarged image. Then Return it. domain = 'speedtest.net' page = requests.get('http://www.whois.com/whois/{}'.format(domain)) tree = html.fromstring(page.content)
Python
0
8f4d557023a84f1b532fe0843615179ebf3194ec
add setup.py
DateObjects/setup.py
DateObjects/setup.py
# coding: utf-8 from setuptools import setup import os README = os.path.join(os.path.dirname(__file__), 'README.md') setup(name='date-objects', version='1.0', description='helper for manipulating dates.', long_description=open(README).read(), author="Marcelo Fonseca Tambalo", author_email="marcelo.zokis@gmail.com", py_modules=['DateObjects'], zip_safe=False, platforms='any', include_package_data=True, classifiers=[ 'Development Status :: 5 - Production/Stable', 'Framework :: Django', 'Framework :: Flask', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Software Development :: Libraries', ], url='https://github.com/zokis/DateObjects/',)
Python
0.000001
7d1f6125d1f56b871e8d6515e7dd1844e36968b1
Add exception support, most code transferred from driver's code
zvmsdk/exception.py
zvmsdk/exception.py
import config import log import six CONF = config.CONF LOG = log.LOG class BaseException(Exception): """ Inherit from this class and define a 'msg_fmt' property. That msg_fmt will get printf'd with the keyword arguments provided to the constructor. """ msg_fmt = "An unknown exception occurred." code = 500 headers = {} safe = False def __init__(self, message=None, **kwargs): self.kw = kwargs if 'code' in self.kw: try: self.kw['code'] = self.code except AttributeError: pass if not message: try: message = self.msg_fmt % kwargs except Exception: LOG.exception('Exception in string format operation') for name, value in six.iteritems(kwargs): LOG.error("%s: %s" % (name, value)) message = self.msg_fmt self.message = message super(BaseException, self).__init__(message) def format_message(self): return self.args[0] class ZVMDriverError(BaseException): msg_fmt = 'z/VM driver error: %(msg)s' class ZVMXCATRequestFailed(BaseException): msg_fmt = 'Request to xCAT server %(xcatserver)s failed: %(msg)s' class ZVMInvalidXCATResponseDataError(BaseException): msg_fmt = 'Invalid data returned from xCAT: %(msg)s' class ZVMXCATInternalError(BaseException): msg_fmt = 'Error returned from xCAT: %(msg)s' class ZVMVolumeError(BaseException): msg_fmt = 'Volume error: %(msg)s' class ZVMImageError(BaseException): msg_fmt = "Image error: %(msg)s" class ZVMGetImageFromXCATFailed(BaseException): msg_fmt = 'Get image from xCAT failed: %(msg)s' class ZVMNetworkError(BaseException): msg_fmt = "z/VM network error: %(msg)s" class ZVMXCATXdshFailed(BaseException): msg_fmt = 'Execute xCAT xdsh command failed: %(msg)s' class ZVMXCATCreateNodeFailed(BaseException): msg_fmt = 'Create xCAT node %(node)s failed: %(msg)s' class ZVMXCATCreateUserIdFailed(BaseException): msg_fmt = 'Create xCAT user id %(instance)s failed: %(msg)s' class ZVMXCATUpdateNodeFailed(BaseException): msg_fmt = 'Update node %(node)s info failed: %(msg)s' class ZVMXCATDeployNodeFailed(BaseException): msg_fmt = 'Deploy image on node %(node)s failed: %(msg)s' class ZVMConfigDriveError(BaseException): msg_fmt = 'Create configure drive failed: %(msg)s' class ZVMRetryException(BaseException): pass
Python
0.000002
1d1f9d5d8f4873d6a23c430a5629eaeddfd50d2a
Add network set default route view
subiquity/ui/views/network_default_route.py
subiquity/ui/views/network_default_route.py
# Copyright 2015 Canonical, Ltd. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from urwid import Text, Pile, ListBox from subiquity.view import ViewPolicy from subiquity.ui.buttons import cancel_btn, done_btn from subiquity.ui.utils import Color, Padding import logging log = logging.getLogger('subiquity.network.set_default_route') class NetworkSetDefaultRouteView(ViewPolicy): def __init__(self, model, signal): self.model = model self.signal = signal self.is_manual = False body = [ Padding.center_50(self._build_disk_selection()), Padding.line_break(""), Padding.center_50(self._build_raid_configuration()), Padding.line_break(""), Padding.center_20(self._build_buttons()) ] super().__init__(ListBox(body)) def _build_default_routes(self): items = [ Text("Please set the default gateway:"), Color.menu_button(done_btn(label="192.168.9.1 (em1, em2)", on_press=self.done), focus_map="menu_button focus"), Color.menu_button( done_btn(label="Specify the default route manually", on_press=self.set_manually), focus_map="menu_button focus") ] return Pile(items) def _build_buttons(self): cancel = cancel_btn(on_press=self.cancel) done = done_btn(on_press=self.done) buttons = [ Color.button(done, focus_map='button focus'), Color.button(cancel, focus_map='button focus') ] return Pile(buttons) def set_manually(self, result): self.is_manual = True self.signal.emit_signal('refresh') def done(self, result): self.signal.emit_signal('network:show') def cancel(self, button): self.signal.emit_signal(self.model.get_previous_signal)
Python
0
8b8db4f78610b6c8b72270275a621d529091a74f
Set account_credit_control_dunning_fees to installable
account_credit_control_dunning_fees/__openerp__.py
account_credit_control_dunning_fees/__openerp__.py
# -*- coding: utf-8 -*- ############################################################################## # # Author: Nicolas Bessi # Copyright 2014 Camptocamp SA # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## {'name': 'Credit control dunning fees', 'version': '0.1.0', 'author': 'Camptocamp', 'maintainer': 'Camptocamp', 'category': 'Accounting', 'complexity': 'normal', 'depends': ['account_credit_control'], 'description': """ Dunning Fees for Credit Control =============================== This extention of credit control adds the notion of dunning fees on credit control lines. Configuration ------------- For release 0.1 only fixed fees are supported. You can specifiy a fixed fees amount, a product and a currency on the credit control level form. The amount will be used as fees values the currency will determine the currency of the fee. If the credit control line has not the same currency as the fees currency, fees will be converted to the credit control line currency. The product is used to compute taxes in reconciliation process. Run --- Fees are automatically computed on credit run and saved on the generated credit lines. Fees can be manually edited as long credit line is draft Credit control Summary report includes a new fees column. ------- Support of fees price list """, 'website': 'http://www.camptocamp.com', 'data': ['view/policy_view.xml', 'view/line_view.xml', 'report/report.xml', 'security/ir.model.access.csv'], 'demo': [], 'test': [], 'installable': True, 'auto_install': False, 'license': 'AGPL-3', 'application': False}
# -*- coding: utf-8 -*- ############################################################################## # # Author: Nicolas Bessi # Copyright 2014 Camptocamp SA # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## {'name': 'Credit control dunning fees', 'version': '0.1.0', 'author': 'Camptocamp', 'maintainer': 'Camptocamp', 'category': 'Accounting', 'complexity': 'normal', 'depends': ['account_credit_control'], 'description': """ Dunning Fees for Credit Control =============================== This extention of credit control adds the notion of dunning fees on credit control lines. Configuration ------------- For release 0.1 only fixed fees are supported. You can specifiy a fixed fees amount, a product and a currency on the credit control level form. The amount will be used as fees values the currency will determine the currency of the fee. If the credit control line has not the same currency as the fees currency, fees will be converted to the credit control line currency. The product is used to compute taxes in reconciliation process. Run --- Fees are automatically computed on credit run and saved on the generated credit lines. Fees can be manually edited as long credit line is draft Credit control Summary report includes a new fees column. ------- Support of fees price list """, 'website': 'http://www.camptocamp.com', 'data': ['view/policy_view.xml', 'view/line_view.xml', 'report/report.xml', 'security/ir.model.access.csv'], 'demo': [], 'test': [], 'installable': False, 'auto_install': False, 'license': 'AGPL-3', 'application': False}
Python
0.000001
d7c46e9bc205d8f5a3cf7e1871547eff8ae7164c
Implement performance testing script
tools/test-performance.py
tools/test-performance.py
#!/usr/bin/python3 import asyncio import random host = 'localhost' port = 5027 messageLogin = bytearray.fromhex('000F313233343536373839303132333435') messageLocation = bytearray.fromhex('000000000000002b080100000140d4e3ec6e000cc661d01674a5e0fffc00000900000004020100f0000242322318000000000100007a04') devices = 100 period = 1 class AsyncClient(asyncio.Protocol): def __init__(self, loop): self.loop = loop self.buffer = memoryview(messageLogin) def connection_made(self, transport): self.send_message(transport) def send_message(self, transport): transport.write(self.buffer) self.buffer = memoryview(messageLocation) delay = period * (0.9 + 0.2 * random.random()) self.loop.call_later(delay, self.send_message, transport) def data_received(self, data): pass def connection_lost(self, exc): self.loop.stop() loop = asyncio.get_event_loop() for i in range(0, devices): loop.create_task(loop.create_connection(lambda: AsyncClient(loop), host, port)) loop.run_forever() loop.close()
Python
0.000002
2c57f2143e21fa3d006d4e4e2737429fb60b4797
Call pip install before running server.
tornado/setup_pg.py
tornado/setup_pg.py
import os import subprocess import sys import time bin_dir = os.path.expanduser('~/FrameworkBenchmarks/installs/py2/bin') python = os.path.expanduser(os.path.join(bin_dir, 'python')) pip = os.path.expanduser(os.path.join(bin_dir, 'pip')) cwd = os.path.expanduser('~/FrameworkBenchmarks/tornado') def start(args, logfile, errfile): subprocess.call(pip + ' install -r requirements.txt', cwd=cwd, shell=True, stderr=errfile, stdout=logfile) subprocess.Popen( python + ' server.py --port=8080 --postgres=%s --logging=error' % (args.database_host,), shell=True, cwd=cwd, stderr=errfile, stdout=logfile) return 0 def stop(logfile, errfile): for line in subprocess.check_output(['ps', 'aux']).splitlines(): if 'server.py --port=8080' in line: pid = int(line.split(None, 2)[1]) os.kill(pid, 9) return 0 if __name__ == '__main__': class DummyArg: database_host = 'localhost' start(DummyArg(), sys.stderr, sys.stderr) time.sleep(1) stop(sys.stderr, sys.stderr)
from os.path import expanduser from os import kill import subprocess import sys import time python = expanduser('~/FrameworkBenchmarks/installs/py2/bin/python') cwd = expanduser('~/FrameworkBenchmarks/tornado') def start(args, logfile, errfile): subprocess.Popen( python + " server.py --port=8080 --postgres=%s --logging=error" % (args.database_host,), shell=True, cwd=cwd, stderr=errfile, stdout=logfile) return 0 def stop(logfile, errfile): for line in subprocess.check_output(["ps", "aux"]).splitlines(): if 'server.py --port=8080' in line: pid = int(line.split(None,2)[1]) kill(pid, 9) return 0 if __name__ == '__main__': class DummyArg: database_host = 'localhost' start(DummyArg(), sys.stderr, sys.stderr) time.sleep(1) stop(sys.stderr, sys.stderr)
Python
0
fdfc17628c34a4219fd61a6f54fc5d86fbb0d6d2
Add script to copy the files of selected edbo titles
copy_edbo_titles.py
copy_edbo_titles.py
"""Script that copies the files of edbo titles that are both available and selected. For convenience hard coded file paths are used. Usage: python copy_edbo_titles.py """ import pandas as pd import glob import shutil import os import re import requests from bs4 import BeautifulSoup def get_file_id(row): #print row #print type(row['file']) if type(row['file']) is str: a = row['file'].split('-')[-1] else: a = None #print a return a def get_delpher_id(row): if type(row['delpher']) is str: a = int(row['delpher'].split(':')[1]) else: a = None #print a return a def copy_file(row): output_dir = '/home/jvdzwaan/data/edbo/' if not os.path.exists(output_dir): os.makedirs(output_dir) fs = glob.glob('/home/jvdzwaan/Downloads/FROG/*{}*.gz'.format(row['file_id'])) if len(fs) == 1: shutil.copy(fs[0], output_dir) return os.path.basename(fs[0]).replace('.xml.gz', '') elif len(fs) == 0: print 'No file found for {}'.format(row['title']) else: print 'Multiple files found for {}'.format(row['title']) return None def get_genre(row): replacements = {'treurspel': 'tragedie/treurspel', 'klugt': 'klucht', 'klucht': 'klucht'} for s, r in replacements.iteritems(): if re.search(s, row['title'], re.I): return r return 'unknown' def get_year(row): url_template = 'http://www.delpher.nl/nl/boeken/view?identifier={}' r = requests.get(url_template.format(row['delpher'])) if r.status_code == 200: soup = BeautifulSoup(r.text) y = soup.find_all('h4', 'view-subtitle') if len(y) == 1: #print y[0].string year = y[0].string year = year.replace('XX', '50') year = year.replace('X', '0') return year return 'unknown' selected = pd.read_excel('/home/jvdzwaan/Downloads/edbo.xlsx', 'Toneelstukken', index_col=0, header=None, parse_cols=[1, 5], names=['id', 'title']) title_id2file_id = pd.read_csv('/home/jvdzwaan/Downloads/FROG/000README', sep='\t', header=None, skiprows=11, names=['file', 'delpher', 'genre']) # add column with file id title_id2file_id.loc[:, 'file_id'] = title_id2file_id.apply(get_file_id, axis=1) # add column with list id title_id2file_id.loc[:, 'list_id'] = title_id2file_id.apply(get_delpher_id, axis=1) # remove invalid rows title_id2file_id = title_id2file_id.dropna() title_id2file_id = title_id2file_id.set_index('list_id', verify_integrity=True) # merge dataframes result = pd.concat([selected, title_id2file_id], axis=1, join_axes=[selected.index]) result = result.dropna() result.loc[:, 'file_name'] = result.apply(copy_file, axis=1) result = result.dropna() # add unknown metadata result.loc[:, 'genre'] = result.apply(get_genre, axis=1) result.loc[:, 'year'] = result.apply(get_year, axis=1) # normalize title result['title'] = result.apply(lambda row: row['title'].replace('\t', ' '), axis=1) result = result.set_index('file_name', verify_integrity=True) # save edbo list to_save = pd.concat([result['year'], result['genre'], result['title']], axis=1) to_save.to_csv('/home/jvdzwaan/data/embem/corpus/edbo.csv', sep='\t', encoding='utf-8', header=None) #print result
Python
0
640c86e17b10d8f892a4036ade4ce7b8dca30347
Implement dragon-blood-clan module.
gygax/modules/dbc.py
gygax/modules/dbc.py
# -*- coding: utf-8 -*- """ :mod:`gygax.modules.dbc` --- Module for playing Dragon-Blood-Clan. ================================================================== """ import gygax.modules.roll as roll def dbc(bot, sender, text): need = 6 # The next die needed. dice_count = 5 # The number of dice to roll. rolls_left = 3 # The number of rolls left. reply = [] # The reply to the sender. # Roll until we have 6, 5 and 4 or we run out of rolls. while need > 3 and rolls_left > 0: results = roll.roll_dice(dice_count, 6) reply.append(" + ".join(map(str, results))) rolls_left -= 1 # Check for needed dice while need > 3 and need in results: results.remove(need) need -= 1 dice_count -= 1 if need > 3: reply.append("no luck") else: reply.append("score: {}".format(sum(results))) reply.append("rolls left: {}".format(rolls_left)) bot.reply(", ".join(reply)) dbc.command = ".dbc"
Python
0
2d81274953629e34cc4b0232782cb910d1d459c9
Add process_watcher mod (triggers Process.Creation event)
modder/mods/process_watcher.py
modder/mods/process_watcher.py
# coding: utf-8 import atexit import platform from modder import on, trigger if platform.system() == 'Windows': import pythoncom import wmi @on('Modder.Started') def watch_process_creation(event): pythoncom.CoInitialize() atexit.register(pythoncom.CoUninitialize) wmi_root = wmi.WMI() process_watcher = wmi_root.Win32_Process.watch_for( notification_type='Creation', delay_secs=2 ) try: while 1: try: new_process = process_watcher() trigger( 'Process.Created', data={ 'caption': new_process.wmi_property('Caption').value, 'process_name': new_process.wmi_property('Name').value, 'executable_path': new_process.wmi_property('ExecutablePath').value, 'pid': new_process.wmi_property('ProcessId').value, } ) except Exception as e: print 'innter error:', e pass except Exception as e: print 'outter error:', e pass finally: pythoncom.CoUninitialize() else: pass
Python
0
03618b710146cdfacb7a8913a65809227e71546c
add test
tests/transforms_tests/image_tests/test_ten_crop.py
tests/transforms_tests/image_tests/test_ten_crop.py
import unittest import numpy as np from chainer import testing from chainercv.transforms import ten_crop class TestTenCrop(unittest.TestCase): def test_ten_crop(self): img = np.random.uniform(size=(3, 48, 32)) out = ten_crop(img, (48, 32)) self.assertEqual(out.shape, (10, 3, 48, 32)) for crop in out[:5]: np.testing.assert_equal(crop, img) for crop in out[5:]: np.testing.assert_equal(crop[:, :, ::-1], img) out = ten_crop(img, (24, 12)) self.assertEqual(out.shape, (10, 3, 24, 12)) testing.run_module(__name__, __file__)
Python
0.000002