commit
stringlengths
40
40
subject
stringlengths
1
3.25k
old_file
stringlengths
4
311
new_file
stringlengths
4
311
old_contents
stringlengths
0
26.3k
lang
stringclasses
3 values
proba
float64
0
1
diff
stringlengths
0
7.82k
7d66a720acb756291adc99ebe444c2c00bd37d84
Remove Ignite Dataset SSL tests by internal policy.
tensorflow/contrib/ignite/python/tests/ignite_dataset_test.py
tensorflow/contrib/ignite/python/tests/ignite_dataset_test.py
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in compliance with the License. You may obtain a copy of # the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations under # the License. # ============================================================================== """Tests for IgniteDataset.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os from tensorflow.contrib.ignite import IgniteDataset from tensorflow.python.client import session from tensorflow.python.framework import dtypes from tensorflow.python.framework import errors from tensorflow.python.platform import test class IgniteDatasetTest(test.TestCase): """The Apache Ignite servers have to setup before the test and tear down after the test manually. The docker engine has to be installed. To setup Apache Ignite servers: $ bash start_ignite.sh To tear down Apache Ignite servers: $ bash stop_ignite.sh """ def test_ignite_dataset_with_plain_client(self): """Test Ignite Dataset with plain client. """ self._clear_env() ds = IgniteDataset(cache_name="SQL_PUBLIC_TEST_CACHE", port=42300) self._check_dataset(ds) def test_ignite_dataset_with_ssl_client(self): """Test Ignite Dataset with ssl client. """ self._clear_env() os.environ["IGNITE_DATASET_CERTFILE"] = os.path.dirname( os.path.realpath(__file__)) + "/keystore/client.pem" os.environ["IGNITE_DATASET_CERT_PASSWORD"] = "123456" ds = IgniteDataset( cache_name="SQL_PUBLIC_TEST_CACHE", port=42301, certfile=os.environ["IGNITE_DATASET_CERTFILE"], cert_password=os.environ["IGNITE_DATASET_CERT_PASSWORD"]) self._check_dataset(ds) def test_ignite_dataset_with_ssl_client_and_auth(self): """Test Ignite Dataset with ssl client and authentication. """ self._clear_env() os.environ["IGNITE_DATASET_USERNAME"] = "ignite" os.environ["IGNITE_DATASET_PASSWORD"] = "ignite" os.environ["IGNITE_DATASET_CERTFILE"] = os.path.dirname( os.path.realpath(__file__)) + "/keystore/client.pem" os.environ["IGNITE_DATASET_CERT_PASSWORD"] = "123456" ds = IgniteDataset( cache_name="SQL_PUBLIC_TEST_CACHE", port=42302, certfile=os.environ["IGNITE_DATASET_CERTFILE"], cert_password=os.environ["IGNITE_DATASET_CERT_PASSWORD"], username=os.environ["IGNITE_DATASET_USERNAME"], password=os.environ["IGNITE_DATASET_PASSWORD"]) self._check_dataset(ds) def _clear_env(self): """Clears environment variables used by Ignite Dataset. """ if "IGNITE_DATASET_USERNAME" in os.environ: del os.environ["IGNITE_DATASET_USERNAME"] if "IGNITE_DATASET_PASSWORD" in os.environ: del os.environ["IGNITE_DATASET_PASSWORD"] if "IGNITE_DATASET_CERTFILE" in os.environ: del os.environ["IGNITE_DATASET_CERTFILE"] if "IGNITE_DATASET_CERT_PASSWORD" in os.environ: del os.environ["IGNITE_DATASET_CERT_PASSWORD"] def _check_dataset(self, dataset): """Checks that dataset provides correct data.""" self.assertEqual(dtypes.int64, dataset.output_types["key"]) self.assertEqual(dtypes.string, dataset.output_types["val"]["NAME"]) self.assertEqual(dtypes.int64, dataset.output_types["val"]["VAL"]) it = dataset.make_one_shot_iterator() ne = it.get_next() with session.Session() as sess: rows = [sess.run(ne), sess.run(ne), sess.run(ne)] with self.assertRaises(errors.OutOfRangeError): sess.run(ne) self.assertEqual({"key": 1, "val": {"NAME": b"TEST1", "VAL": 42}}, rows[0]) self.assertEqual({"key": 2, "val": {"NAME": b"TEST2", "VAL": 43}}, rows[1]) self.assertEqual({"key": 3, "val": {"NAME": b"TEST3", "VAL": 44}}, rows[2]) if __name__ == "__main__": test.main()
Python
0
@@ -1632,1342 +1632,8 @@ s)%0A%0A - def test_ignite_dataset_with_ssl_client(self):%0A %22%22%22Test Ignite Dataset with ssl client.%0A%0A %22%22%22%0A self._clear_env()%0A os.environ%5B%22IGNITE_DATASET_CERTFILE%22%5D = os.path.dirname(%0A os.path.realpath(__file__)) + %22/keystore/client.pem%22%0A os.environ%5B%22IGNITE_DATASET_CERT_PASSWORD%22%5D = %22123456%22%0A%0A ds = IgniteDataset(%0A cache_name=%22SQL_PUBLIC_TEST_CACHE%22,%0A port=42301,%0A certfile=os.environ%5B%22IGNITE_DATASET_CERTFILE%22%5D,%0A cert_password=os.environ%5B%22IGNITE_DATASET_CERT_PASSWORD%22%5D)%0A self._check_dataset(ds)%0A%0A def test_ignite_dataset_with_ssl_client_and_auth(self):%0A %22%22%22Test Ignite Dataset with ssl client and authentication.%0A%0A %22%22%22%0A self._clear_env()%0A os.environ%5B%22IGNITE_DATASET_USERNAME%22%5D = %22ignite%22%0A os.environ%5B%22IGNITE_DATASET_PASSWORD%22%5D = %22ignite%22%0A os.environ%5B%22IGNITE_DATASET_CERTFILE%22%5D = os.path.dirname(%0A os.path.realpath(__file__)) + %22/keystore/client.pem%22%0A os.environ%5B%22IGNITE_DATASET_CERT_PASSWORD%22%5D = %22123456%22%0A%0A ds = IgniteDataset(%0A cache_name=%22SQL_PUBLIC_TEST_CACHE%22,%0A port=42302,%0A certfile=os.environ%5B%22IGNITE_DATASET_CERTFILE%22%5D,%0A cert_password=os.environ%5B%22IGNITE_DATASET_CERT_PASSWORD%22%5D,%0A username=os.environ%5B%22IGNITE_DATASET_USERNAME%22%5D,%0A password=os.environ%5B%22IGNITE_DATASET_PASSWORD%22%5D)%0A self._check_dataset(ds)%0A%0A de
39668777b1f5579b37746521ba95b506bea08d1a
Prepare v1.2.295.dev
flexget/_version.py
flexget/_version.py
""" Current FlexGet version. This is contained in a separate file so that it can be easily read by setup.py, and easily edited and committed by release scripts in continuous integration. Should (almost) never be set manually. The version should always be set to the <next release version>.dev The jenkins release job will automatically strip the .dev for release, and update the version again for continued development. """ __version__ = '1.2.294'
Python
0.000001
@@ -443,7 +443,11 @@ 2.29 -4 +5.dev '%0A
f3bbb887d76ec428c4926f94c119220cc8c63cf8
add offline script to ingest IDOT archived road conditions
scripts/roads/idot_csv_ingest.py
scripts/roads/idot_csv_ingest.py
Python
0
@@ -0,0 +1,1641 @@ +%22%22%22Be able to merge a CSV file that IDOT provides%22%22%22%0Aimport pandas as pd%0Aimport psycopg2%0Aimport sys%0Aimport datetime%0A%0Apgconn = psycopg2.connect(database='postgis', host='localhost', user='mesonet',%0A port=5555)%0Acursor = pgconn.cursor()%0Axref = %7B%7D%0Acursor.execute(%22%22%22SELECT idot_id, segid from roads_base%22%22%22)%0Afor row in cursor:%0A xref%5Brow%5B0%5D%5D = row%5B1%5D%0A%0AROADCOND = %7B%0A 'dry pavement': 0,%0A 'wet': 1,%0A 'partially covered with frost': 3,%0A 'partially covered with snow': 39,%0A 'partially covered with ice': 27,%0A 'partially covered with slush': 56,%0A 'partially covered with mix': 15,%0A 'completely covered with frost': 11,%0A 'completely covered with snow': 47,%0A 'completely covered with ice': 35,%0A 'completely covered with slush': 64,%0A 'completely covered with mixed': 23,%0A 'travel not advised': 51,%0A 'impassable': 86,%0A 'partially covered with mixed snow ice or slush': 15,%0A 'completely covered with mixed snow ice or slush': 23,%0A 'icy bridges': 27,%0A 'seasonal': 0,%0A 'Seasonal': 0,%0A 'seasonal roadway conditions': 0,%0A 'impassable': 86,%0A %7D%0A%0Adf = pd.read_csv(sys.argv%5B1%5D)%0Afor i, row in df.iterrows():%0A segid = xref%5Bint(row%5B'SEGMENT_ID'%5D)%5D%0A condcode = ROADCOND%5Brow%5B'HL_PAVEMENT_CONDITION'%5D%5D%0A ts = datetime.datetime.strptime(str(row%5B'CARS_MSG_UPDATE_DATE'%5D),%0A '%25Y%25m%25d%25H%25M%25S')%0A cursor.execute(%22%22%22INSERT into roads_2015_2016_log(segid, valid, cond_code,%0A raw) VALUES (%25s, %25s, %25s, %25s)%22%22%22, (segid, ts, condcode,%0A row%5B'HL_PAVEMENT_CONDITION'%5D))%0A%0Acursor.close()%0Apgconn.commit()%0A
c2d1344c518dcf7c4cd20786bfa7cf649b977ca5
Create new package (#7378)
var/spack/repos/builtin/packages/perl-file-slurper/package.py
var/spack/repos/builtin/packages/perl-file-slurper/package.py
Python
0
@@ -0,0 +1,1587 @@ +##############################################################################%0A# Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC.%0A# Produced at the Lawrence Livermore National Laboratory.%0A#%0A# This file is part of Spack.%0A# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.%0A# LLNL-CODE-647188%0A#%0A# For details, see https://github.com/spack/spack%0A# Please also see the NOTICE and LICENSE files for our notice and the LGPL.%0A#%0A# This program is free software; you can redistribute it and/or modify%0A# it under the terms of the GNU Lesser General Public License (as%0A# published by the Free Software Foundation) version 2.1, February 1999.%0A#%0A# This program is distributed in the hope that it will be useful, but%0A# WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF%0A# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and%0A# conditions of the GNU Lesser General Public License for more details.%0A#%0A# You should have received a copy of the GNU Lesser General Public%0A# License along with this program; if not, write to the Free Software%0A# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA%0A##############################################################################%0Afrom spack import *%0A%0A%0Aclass PerlFileSlurper(PerlPackage):%0A %22%22%22A simple, sane and efficient module to slurp a file%22%22%22%0A%0A homepage = %22http://search.cpan.org/~leont/File-Slurper/lib/File/Slurper.pm%22%0A url = %22http://search.cpan.org/CPAN/authors/id/L/LE/LEONT/File-Slurper-0.011.tar.gz%22%0A%0A version('0.011', 'e0482d3d5a0522e39132ba54af9f1ce3')%0A
766eff22b8632ae8548fe30e5b44bc8ca5de29b5
Create near_ten.py
Python/CodingBat/near_ten.py
Python/CodingBat/near_ten.py
Python
0.000004
@@ -0,0 +1,100 @@ +# http://codingbat.com/prob/p165321%0A%0Adef near_ten(num):%0A return (num %25 10 %3C= 2) or (num %25 10 %3E= 8)%0A
e143ef5663f1fed402c9c941bd8b18adbf72c02b
add calebasse.url_utils module
calebasse/urls_utils.py
calebasse/urls_utils.py
Python
0.000001
@@ -0,0 +1,1073 @@ +from django.core.urlresolvers import RegexURLPattern, RegexURLResolver%0A%0Aclass DecoratedURLPattern(RegexURLPattern):%0A def resolve(self, *args, **kwargs):%0A result = super(DecoratedURLPattern, self).resolve(*args, **kwargs)%0A if result:%0A result.func = self._decorate_with(result.func)%0A return result%0A%0Aclass DecoratedRegexURLResolver(RegexURLResolver):%0A def resolve(self, *args, **kwargs):%0A result = super(DecoratedRegexURLResolver, self).resolve(*args, **kwargs)%0A if result:%0A result.func = self._decorate_with(result.func)%0A return result%0A%0Adef decorated_includes(func, includes, *args, **kwargs):%0A urlconf_module, app_name, namespace = includes%0A%0A for item in urlconf_module:%0A if isinstance(item, RegexURLPattern):%0A item.__class__ = DecoratedURLPattern%0A item._decorate_with = func%0A%0A elif isinstance(item, RegexURLResolver):%0A item.__class__ = DecoratedRegexURLResolver%0A item._decorate_with = func%0A%0A return urlconf_module, app_name, namespace%0A%0A
be0e28cfc4628491ba6a2c176cb5458279b94f8d
Create simple_fun_#270_evil_code_medal.py
simple_fun_#270_evil_code_medal.py
simple_fun_#270_evil_code_medal.py
Python
0.998977
@@ -0,0 +1,546 @@ +#Kunal Gautam%0A#Codewars : @Kunalpod%0A#Problem name: Simple Fun #270: Evil Code Medal%0A#Problem level: 7 kyu%0A%0Adef get_sec(time):%0A return time%5B0%5D*3600 + time%5B1%5D*60 + time%5B2%5D%0A%0Adef evil_code_medal(user_time, gold, silver, bronze):%0A user_time = get_sec(user_time.split(':'))%0A gold = get_sec(gold.split(':'))%0A silver = get_sec(silver.split(':'))%0A bronze = get_sec(bronze.split(':'))%0A if user_time %3C gold: return %22Gold%22%0A elif user_time %3C silver: return %22Silver%22%0A elif user_time %3C bronze: return %22Bronze%22%0A else: return %22None%22%0A
48d0578f32505702d63adc3c580749c4eb18326d
Create most_common_characters.py
most_common_characters.py
most_common_characters.py
Python
0.000177
@@ -0,0 +1,556 @@ +import operator%0A%0Adef most_common_characters(input_string, N):%0A count = %7B%7D%0A for char in inputString:%0A if char in count:%0A count%5Bchar%5D += 1%0A else:%0A count%5Bchar%5D = 1%0A %0A sorted_freq = sorted(count.iteritems(), key=operator.itemgetter(1), reverse=True)%0A%0A for i in range(min(N, len(sorted_freq))):%0A print sorted_freq%5Bi%5D%5B0%5D%0A %0Adef main():%0A most_common_characters(%22aaaaaaaaaaaaaaaaaaakkkkkkkkkkkkkkkkkkkddddddddddddhhhhhhhhhbbbbbbbeeeewqqqer%22, 10)%0A %0Aif __name__ == %22__main__%22:%0A main()%0A
c06de87c53a8e42660b885de9d14796cc928c687
add pwgen
pwgen.py
pwgen.py
Python
0.000001
@@ -0,0 +1,354 @@ +for a in range(10):%0A for b in range(10):%0A for c in range(10):%0A for d in range(10):%0A for e in range(10):%0A for f in range(10):%0A for g in range(10):%0A for h in range(10):%0A print(%22%7B%7D%7B%7D%7B%7D%7B%7D%7B%7D%7B%7D%7B%7D%7B%7D%22.format(a,b,c,d,e,f,g,h))%0A
43429ce9c2c21bc919baed5a831402e5c100e0f9
Fix bug related to last update
classes/headers.py
classes/headers.py
class ExtractHeaders(object): def __init__(self, cache, results, log=None): self.cache = cache self.results = results self.log = log self.headers = set() self.category = "Platform" def _split_server_line(self, line): if "(" in line: os = line[line.find('(')+1:line.find(')')] sh = line[:line.find('(')-1] + line[line.find(')')+1: ] return os, sh else: return False, line def add_header(self, response): for header in response.headers: # extract the headers and values. headers = [(hdr, value) for hdr, value, url in self.headers] # if the header and value is not in the header set, add them along with the url. # only the first header,value,url set should be added. if not (header, response.headers[header]) in headers: self.headers.add( (header, response.headers[header], response.url)) def run(self): # get all the headers seen during the scan for response in self.cache.get_responses(): self.add_header(response) # examine all the headers found for hdr,val,url in self.headers: # "server" can be used to identify the web server and operating system if hdr == 'Server': # extract the OS if present: (Apache/2.2 (Ubuntu) PHP/5.3.1 ) # os = Ubuntu # line = Apache/2.2 PHP/5.3.1 os, line = self._split_server_line(val) out = [] for part in line.split(" "): try: pkg,version = part.split('/') # add the results to the log and the results #self.log.add( {url: {pkg: [version]} } ) self.results.add(self.category, pkg, version, weight=1) except Exception as e: continue # "X-Powered-By" can be used to identify the PHP version (and potentially the OS) elif hdr == 'X-Powered-By': # 2014-07-27: the length of val.split('/') is not always 2 (e.g.: X-Powered-By: ASP.NET) vals = val.split('/') if len(vals) == 2: pkg,version = val.split('/') weight = 1 else: pkg,version,weight = val,'',0.1 #self.log.add( {url: {pkg: [version]} } ) self.results.add(self.category, pkg, version, weight) elif hdr == 'X-AspNet-Version': pkg = "ASP.NET" version = val #self.log.add( {url: {pkg: [version]} } ) self.results.add(self.category, pkg, version, weight=1) elif hdr == 'Set-Cookie': if 'ASP.NET_SessionId' in val: pkg = "ASP.NET" version = '' #self.log.add( {url: {pkg: [version]} } ) self.results.add(self.category, pkg, version, 0.1)
Python
0
@@ -2068,24 +2068,31 @@ g, version, +weight= weight)%0A%0A%09%09%09 @@ -2480,16 +2480,23 @@ ersion, +weight= 0.1)%09%0A%0A%0A
8681d011fabd4d3b3df105e05292699239a1b750
Fix a bug in disco to make jenkins happy again. is_matching_disco_datas datas is a list of tuples not a dict
shinken/objects/discoveryrule.py
shinken/objects/discoveryrule.py
#!/usr/bin/env python #Copyright (C) 2009-2010 : # Gabes Jean, naparuba@gmail.com # Gerhard Lausser, Gerhard.Lausser@consol.de # Gregory Starck, g.starck@gmail.com # Hartmut Goebel, h.goebel@goebel-consult.de # #This file is part of Shinken. # #Shinken is free software: you can redistribute it and/or modify #it under the terms of the GNU Affero General Public License as published by #the Free Software Foundation, either version 3 of the License, or #(at your option) any later version. # #Shinken is distributed in the hope that it will be useful, #but WITHOUT ANY WARRANTY; without even the implied warranty of #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #GNU Affero General Public License for more details. # #You should have received a copy of the GNU Affero General Public License #along with Shinken. If not, see <http://www.gnu.org/licenses/>. import re from item import Item, Items from service import Service from host import Host from shinken.property import StringProp, ListProp from copy import copy class Discoveryrule(Item): id = 1 #0 is always special in database, so we do not take risk here my_type = 'discoveryrule' properties = Item.properties.copy() properties.update({ 'discoveryrule_name': StringProp (), 'creation_type': StringProp (default='service'), # 'check_command': StringProp (), # 'service_description': StringProp (), # 'use': StringProp(), }) running_properties = { 'configuration_errors': ListProp(default=[]), } macros = {} # The init of a discovery will set the property of # Discoveryrule.properties as in setattr, but all others # will be in a list because we need to have all names # and not lost all in __dict__ def __init__(self, params={}): cls = self.__class__ # We have our own id of My Class type :) # use set attr for going into the slots # instead of __dict__ :) setattr(self, 'id', cls.id) cls.id += 1 self.matches = {} # for matching rules self.not_matches = {} # for rules that should NOT match self.writing_properties = {} # Get the properties of the Class we want if not 'creation_type' in params: params['creation_type'] = 'service' map = {'service' : Service, 'host' : Host} t = params['creation_type'] if not t in map: return tcls = map[t] # In my own property : # -> in __dict__ # In the properties of the 'creation_type' Class: # -> in self.writing_properties # if not, in matches or not match (if key starts # with a !, it's a not rule) # -> in self.matches or self.not_matches # in writing properties if start with + (means 'add this') for key in params: # Some key are quite special if key in ['use']: self.writing_properties[key] = params[key] elif key.startswith('+'): self.writing_properties[key] = params[key] elif key in cls.properties: setattr(self, key, params[key]) elif key in tcls.properties: self.writing_properties[key] = params[key] else: if key.startswith('!'): key = key.split('!')[1] self.not_matches[key] = params['!'+key] else: self.matches[key] = params[key] # Then running prop :) cls = self.__class__ # adding running properties like latency, dependency list, etc for prop, entry in cls.running_properties.items(): # Copy is slow, so we check type # Type with __iter__ are list or dict, or tuple. # Item need it's own list, so qe copy val = entry.default if hasattr(val, '__iter__'): setattr(self, prop, copy(val)) else: setattr(self, prop, val) #eatch istance to have his own running prop! # Output name def get_name(self): try: return self.discoveryrule_name except AttributeError: return "UnnamedDiscoveryRule" # Try to see if the key,value is matching one or # our rule. If value got ',' we must look for each value # If one match, we quit # We can find in matches or not_matches def is_matching(self, key, value, look_in='matches'): if look_in == 'matches': d = self.matches else: d = self.not_matches # If we do not even have the key, we bailout if not key.strip() in d: return False # Get my matching patern m = d[key] if ',' in m: matchings = [mt.strip() for mt in m.split(',')] else: matchings = [m] # Split the alue by , too values = value.split(',') for m in matchings: for v in values: #print "Try to match", m, v if re.search(m, v): return True return False # Look if we match all discovery data or not # a disco data look as a list of (key, values) def is_matching_disco_datas(self, datas): # If we got not data, no way we can match if len(datas) == 0: return False # First we look if it's possible to match # we must match All self.matches things for m in self.matches: #print "Compare to", m match_one = False for (k, v) in datas.iteritems(): # We found at least one of our match key if m == k: if self.is_matching(k, v): #print "Got matching with", m, k, v match_one = True continue if not match_one: # It match none #print "Match none, FAlse" return False #print "It's possible to be OK" # And now look if ANY of not_matches is reach. If so # it's False for m in self.not_matches: #print "Compare to NOT", m match_one = False for (k, v) in datas.iteritems(): #print "K,V", k,v # We found at least one of our match key if m == k: #print "Go loop" if self.is_matching(k, v, look_in='not_matches'): #print "Got matching with", m, k, v match_one = True continue if match_one: #print "I match one, I quit" return False # Ok we match ALL rules in self.matches # and NONE of self.not_matches, we can go :) return True class Discoveryrules(Items): name_property = "discoveryrule_name" inner_class = Discoveryrule
Python
0.999827
@@ -5723,36 +5723,24 @@ v) in datas -.iteritems() :%0A @@ -6390,20 +6390,8 @@ atas -.iteritems() :%0A
e47094d2b499ee2667384328194cd8f35ce17022
Add a forgotten file
sinus_subpixel/sinus_subpixel.py
sinus_subpixel/sinus_subpixel.py
Python
0.000004
@@ -0,0 +1,893 @@ +#!/usr/bin/env python3%0A# -*- coding: utf-8 -*-%0A%0Aimport pygame%0Afrom pygame.locals import *%0Afrom subpixel_surface import *%0Afrom math import sin, cos%0A%0ADOTS = 100%0A%0A%0Adef main():%0A%0A pygame.init()%0A screen = pygame.display.set_mode((640, 480))%0A clock = pygame.time.Clock()%0A dot = pygame.image.load(%22dot.png%22)%0A dot_subpixel = SubPixelSurface(dot, x_level=8)%0A%0A t = 0.%0A while True:%0A for event in pygame.event.get():%0A if event.type == QUIT:%0A return%0A%0A time_passed = clock.tick()%0A t += time_passed / 3000.%0A%0A for n in range(DOTS):%0A a = float(n)/DOTS * sin((t)*.1234)*100%0A x = sin((t+a)*sin(t/4)) * 200.*sin(t/5) + 320%0A y = cos(((t*1.234)+a)*sin(t/8)) * 200.*sin(t/4) + 220%0A screen.blit(dot_subpixel.at(x, y), (x, y))%0A%0A pygame.display.update()%0A%0A%0Aif __name__ == %22__main__%22:%0A main()%0A
a3d7561c3c8930a55f7496c817876e4cf6b187bd
Add migration I forgot
dataactcore/migrations/versions/cd1025ac9399_add_columns_to_AwardProcurement.py
dataactcore/migrations/versions/cd1025ac9399_add_columns_to_AwardProcurement.py
Python
0.000001
@@ -0,0 +1,1070 @@ +%22%22%22add columns to AwardProcurement%0ARevision ID: cd1025ac9399%0ARevises: a767facf8ea8%0ACreate Date: 2017-09-18 15:05:52.772251%0A%22%22%22%0A%0A# revision identifiers, used by Alembic.%0Arevision = 'cd1025ac9399'%0Adown_revision = 'a767facf8ea8'%0Abranch_labels = None%0Adepends_on = None%0A%0Afrom alembic import op%0Aimport sqlalchemy as sa%0A%0A%0Adef upgrade(engine_name):%0A globals()%5B%22upgrade_%25s%22 %25 engine_name%5D()%0A%0A%0Adef downgrade(engine_name):%0A globals()%5B%22downgrade_%25s%22 %25 engine_name%5D()%0A%0A%0A%0A%0A%0Adef upgrade_data_broker():%0A ### commands auto generated by Alembic - please adjust! ###%0A op.add_column('award_procurement', sa.Column('base_and_all_options_value', sa.Text(), nullable=True))%0A op.add_column('award_procurement', sa.Column('base_exercised_options_val', sa.Text(), nullable=True))%0A ### end Alembic commands ###%0A%0A%0Adef downgrade_data_broker():%0A ### commands auto generated by Alembic - please adjust! ###%0A op.drop_column('award_procurement', 'base_exercised_options_val')%0A op.drop_column('award_procurement', 'base_and_all_options_value')%0A ### end Alembic commands ###%0A
18f162d0260d3bb1de0d95105badb7b3d8ac577b
lucky_numbers solved
algorithms/dynamic_programming/lucky_numbers.py
algorithms/dynamic_programming/lucky_numbers.py
Python
0.999481
@@ -0,0 +1,2028 @@ +'''%0ACreated on Jul 21, 2013%0A%0A@author: nirvam%0A%0A%0AA number is called lucky if the sum of its digits, as well as the sum of the squares of its digits is a prime number. How many numbers between A and B are lucky?%0A%0AInput:%0AThe first line contains the number of test cases T. Each of the next T lines contains two integers, A and B.%0A%0AOutput:%0AOutput T lines, one for each case containing the required answer for the corresponding case.%0A%0AConstraints:%0A1 %3C= T %3C= 10000%0A1 %3C= A %3C= B %3C= 10%5E18%0A%0ASample Input:%0A2%0A1 20%0A120 130%0A%0ASample Output:%0A4%0A1%0A%0AExplanation:%0AFor the first case, the lucky numbers are 11, 12, 14, 16.%0AFor the second case, the only lucky number is 120.%0A'''%0A%0A#from numpy import random%0Aimport random%0A%0Adef _get_input():%0A numbers = %5B%5D%0A for l in range(int(input())):%0A temp=%5Bint(x) for x in input().split()%5D%0A numbers.append(range(temp%5B0%5D,temp%5B1%5D+1))%0A return numbers%0A%0A%0Adef _miller_rabin_pass(a, s, d, n):%0A a_to_power = pow(a, d, n)%0A if a_to_power == 1:%0A return True%0A for i in range(s-1):%0A if a_to_power == n - 1:%0A return True%0A #a_to_power = pow(a_to_power,2,n)%0A a_to_power = (a_to_power ** 2) %25 n%0A return a_to_power == n - 1%0A%0A%0Adef _miller_rabin(n):%0A if n == 2:%0A return True%0A elif n %25 2 == 0 or n == 1:%0A return False%0A d = n - 1%0A s = 0%0A while d %25 2 == 0:%0A d %3E%3E= 1%0A s += 1%0A %0A for repeat in range(20):%0A a = 0%0A while a == 0:%0A #a = random.randint(n-1)%0A a = random.randrange(n)%0A if not _miller_rabin_pass(a, s, d, n):%0A return False%0A return True%0A%0Aif __name__ == '__main__':%0A cases = _get_input()%0A for case in cases:%0A lucky_numbers=%5B%5D%0A for number in case:%0A number=str(number)%0A digits=%5Bint(x) for x in number%5D%0A sum1=sum(digits)%0A sum2=sum(%5Bx**2 for x in digits%5D)%0A if _miller_rabin(sum1) and _miller_rabin(sum2):%0A lucky_numbers.append(number)%0A print(len(lucky_numbers))%0A%0A
36e730ea3d984b8da8081397d4ac0c4dd3bb82f2
add mongoDB cache demo.
PersistenceSpider/demo_mongodb_persistence.py
PersistenceSpider/demo_mongodb_persistence.py
Python
0
@@ -0,0 +1,2181 @@ +import pymongo%0A'''%0APython3 MongoDB%E6%95%B0%E6%8D%AE%E5%BA%93%E6%8C%81%E4%B9%85%E5%8C%96%E6%BC%94%E7%A4%BA%0A'''%0A%0A%0Aclass MongoDBPersistence(object):%0A def __init__(self):%0A self.conn = None%0A self.database = None%0A%0A def connect(self, database):%0A try:%0A self.conn = pymongo.MongoClient('mongodb://localhost:27017/')%0A self.database = self.conn%5Bdatabase%5D%0A except Exception as e:%0A print(%22MongoDB connect failed.%22 + str(e))%0A%0A def close(self):%0A try:%0A if self.conn is not None:%0A self.conn.close()%0A except BaseException as e:%0A print(%22MongoDB close failed.%22+str(e))%0A%0A def insert_table_dict(self, dict_data=None):%0A if self.conn is None or self.database is None:%0A print('Please ensure you have connected to MongoDB server!')%0A return False%0A if dict_data is None:%0A return False%0A try:%0A collection = self.database%5B'DemoTable'%5D%0A collection.save(dict_data)%0A except BaseException as e:%0A print(%22MongoDB insert error.%22 + str(e))%0A return True%0A%0A def get_dict_by_name(self, name=None):%0A if self.conn is None or self.database is None:%0A print('Please ensure you have connected to MongoDB server!')%0A return None%0A collection = self.database%5B'DemoTable'%5D%0A if name is None:%0A documents = collection.find()%0A else:%0A documents = collection.find(%7B%22name%22: name%7D)%0A document_list = list()%0A for document in documents:%0A document_list.append(document)%0A return document_list%0A%0A%0Aif __name__ == '__main__':%0A t_mysql = MongoDBPersistence()%0A t_mysql.connect(%22DemoDatabase%22)%0A t_mysql.insert_table_dict(%7B'name': 'Test1', 'content': 'XXXXXXXXXXXXX'%7D)%0A t_mysql.insert_table_dict(%7B'name': 'Test2', 'content': 'vvvvvvvvvvvv'%7D)%0A t_mysql.insert_table_dict(%7B'name': 'Test3', 'content': 'qqqqqqqqqqqq'%7D)%0A t_mysql.insert_table_dict(%7B'name': 'Test4', 'content': 'wwwwwwwwwwwww'%7D)%0A print('MongoDBPersistence get Test2: ' + str(t_mysql.get_dict_by_name('Test2')))%0A print('MongoDBPersistence get All: ' + str(t_mysql.get_dict_by_name()))%0A t_mysql.close()
930630e886d8666844639e7cf9d273bd8e4c2115
Create rev_shell_server.py
Server/rev_shell_server.py
Server/rev_shell_server.py
Python
0.000003
@@ -0,0 +1,1189 @@ +#!/usr/bin/python%0A%0Aimport socket%0Aimport subprocess%0Aimport sys%0A%0A%0Adef main():%0A try:%0A RHOST = sys.argv%5B1%5D%0A RPORT = 9000%0A except:%0A print (%22Must provide hotst%22)%0A sys.exit()%0A s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)%0A s.connect((RHOST,RPORT))%0A%0A while True:%0A #recieve XOR encoded data%0A data = s.recv(1024)%0A %0A #XOR the data again with a '/x41' to get back to normal%0A en_data = bytearray(data)%0A for i in range(len(en_data)):%0A en_data%5Bi%5D %5E=0x41%0A%0A if en_data == 'killMe':%0A break%0A %0A #Execute decoded command%0A comm = subprocess.Popen(str(en_data), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)%0A STDOUT,STDERR = comm.communicate()%0A %0A #Encode output%0A if STDOUT:%0A en_STDOUT = bytearray(STDOUT)%0A else:%0A en_STDOUT = bytearray(%22Command not recognised%22)%0A for i in range(len(en_STDOUT)):%0A en_STDOUT%5Bi%5D %5E=0x41%0A try:%0A%09 s.send(en_STDOUT)%0A %09except:%0A sys.exit()%0A s.close()%0A%0A#Start Here!%0Aif __name__ == %22__main__%22:%0A main()%0A
89676cd523818f37e5601003c5859b169200d469
fix Channel window
kismon/windows/channel.py
kismon/windows/channel.py
from gi.repository import Gtk class ChannelWindow: def __init__(self, sources, client): self.sources = sources self.client = client self.changes = {} self.widgets = {} self.gtkwin = Gtk.Window() self.gtkwin.set_position(Gtk.WindowPosition.CENTER) self.gtkwin.set_default_size(320, 240) self.gtkwin.set_title("Configure Channel") vbox = Gtk.VBox() self.gtkwin.add(vbox) self.sources_list = Gtk.VBox() sources_list_scroll = Gtk.ScrolledWindow() sources_list_scroll.add_with_viewport(self.sources_list) sources_list_scroll.get_children()[0].set_shadow_type(Gtk.ShadowType.NONE) sources_list_scroll.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC) vbox.pack_start(sources_list_scroll, True, True, 0) for uuid in self.sources: self.widgets[uuid] = {} source = self.sources[uuid] frame = Gtk.Frame() frame.set_label(source["username"]) self.sources_list.pack_start(frame, False, False, 0) table = Gtk.Table(3, 3) frame.add(table) hop_button = Gtk.RadioButton(None, 'Hop') if source["hop"] > 0: hop_button.clicked() hop_button.connect("clicked", self.on_change_mode, uuid, "hop") hop_button.set_alignment(0,0) table.attach(hop_button, 0, 1, 0, 1) field = Gtk.SpinButton() field.set_numeric(True) field.set_max_length(3) field.set_increments(1,10) field.set_range(1,100) field.set_value(source["velocity"]) if source["hop"] == 0: field.set_sensitive(False) self.widgets[uuid]["hop"] = field field.connect("changed", self.on_change_value, uuid, "hop") table.attach(field, 1, 2, 0, 1, xoptions=Gtk.AttachOptions.SHRINK) label = Gtk.Label(label="rate") label.set_justify(Gtk.Justification.LEFT) label.set_alignment(0.1,0.5) table.attach(label, 2, 3, 0, 1, xoptions=Gtk.AttachOptions.FILL) lock_button = Gtk.RadioButton(hop_button, "Lock") if source["hop"] == 0: lock_button.clicked() lock_button.connect("clicked", self.on_change_mode, uuid, "lock") hop_button.set_alignment(0,0) table.attach(lock_button, 0, 1, 1, 2) field = Gtk.SpinButton() field.set_numeric(True) field.set_max_length(3) field.set_increments(1,10) field.set_range(1,100) if source["hop"] == 0: field.set_value(source["channel"]) else: field.set_value(1) field.set_sensitive(False) self.widgets[uuid]["lock"] = field field.connect("changed", self.on_change_value, uuid, "lock") table.attach(field, 1, 2, 1, 2, xoptions=Gtk.AttachOptions.SHRINK) label = Gtk.Label(label="channel") label.set_justify(Gtk.Justification.FILL) label.set_alignment(0.1,0.5) table.attach(label, 2, 3, 1, 2, xoptions=Gtk.AttachOptions.FILL) button_box = Gtk.HButtonBox() vbox.pack_end(button_box, False, False, 0) cancel_button = Gtk.Button(stock=Gtk.STOCK_CANCEL) cancel_button.connect("clicked", self.on_cancel) button_box.add(cancel_button) apply_button = Gtk.Button(stock=Gtk.STOCK_APPLY) apply_button.connect("clicked", self.on_apply) button_box.add(apply_button) self.gtkwin.show_all() def on_change_mode(self, widget, uuid, mode): if not widget.get_active(): return self.changes[uuid] = mode self.widgets[uuid][mode].set_sensitive(True) if mode == "lock": self.widgets[uuid]["hop"].set_sensitive(False) else: self.widgets[uuid]["lock"].set_sensitive(False) def on_change_value(self, widget, uuid, mode): self.changes[uuid] = mode def on_apply(self, widget): for uuid in self.changes: mode = self.changes[uuid] value = int(self.widgets[uuid][mode].get_value()) self.client.set_channel(uuid, mode, value) self.gtkwin.destroy() def on_cancel(self, widget): self.gtkwin.destroy()
Python
0.000001
@@ -1035,16 +1035,43 @@ ioButton +.new_with_label_from_widget (None, ' @@ -1894,16 +1894,43 @@ ioButton +.new_with_label_from_widget (hop_but
921e4fe305e7d39347635c99fd4f9cc84ed7e534
Add ImageTextAnnotation migration
app/grandchallenge/annotations/migrations/0005_imagetextannotation.py
app/grandchallenge/annotations/migrations/0005_imagetextannotation.py
Python
0
@@ -0,0 +1,1867 @@ +# Generated by Django 2.2.2 on 2019-07-11 10:35%0A%0Afrom django.conf import settings%0Afrom django.db import migrations, models%0Aimport django.db.models.deletion%0Aimport django.utils.timezone%0Aimport uuid%0A%0A%0Aclass Migration(migrations.Migration):%0A%0A dependencies = %5B%0A migrations.swappable_dependency(settings.AUTH_USER_MODEL),%0A (%22cases%22, %220011_auto_20190314_1453%22),%0A (%0A %22annotations%22,%0A %220004_imagepathologyannotation_imagequalityannotation_retinaimagepathologyannotation%22,%0A ),%0A %5D%0A%0A operations = %5B%0A migrations.CreateModel(%0A name=%22ImageTextAnnotation%22,%0A fields=%5B%0A (%0A %22id%22,%0A models.UUIDField(%0A default=uuid.uuid4,%0A editable=False,%0A primary_key=True,%0A serialize=False,%0A ),%0A ),%0A (%22modified%22, models.DateTimeField(auto_now=True)),%0A (%0A %22created%22,%0A models.DateTimeField(default=django.utils.timezone.now),%0A ),%0A (%22text%22, models.TextField()),%0A (%0A %22grader%22,%0A models.ForeignKey(%0A on_delete=django.db.models.deletion.CASCADE,%0A to=settings.AUTH_USER_MODEL,%0A ),%0A ),%0A (%0A %22image%22,%0A models.ForeignKey(%0A on_delete=django.db.models.deletion.CASCADE,%0A to=%22cases.Image%22,%0A ),%0A ),%0A %5D,%0A options=%7B%0A %22ordering%22: %5B%22-created%22%5D,%0A %22get_latest_by%22: %22created%22,%0A %22abstract%22: False,%0A %7D,%0A )%0A %5D%0A
9a567d283cc2e72e3590305f81b3879d7f2557fa
include json_io.py from another older project.
json_io.py
json_io.py
Python
0
@@ -0,0 +1,1656 @@ +%0Afrom __future__ import division, print_function, unicode_literals%0A%0Aimport numpy as np%0Aimport simplejson as json%0A%0A#%0A# Helpers.%0A#%0AMARKER = ':ndar!'%0A%0A%0Aclass NumpyJSONEncoder(json.JSONEncoder):%0A def default(self, obj):%0A if isinstance(obj, np.ndarray):%0A name = '%25s.%25s' %25 (MARKER, obj.dtype.name)%0A encoded_obj = %7Bname: obj.tolist()%7D%0A else:%0A encoded_obj = json.JSONEncoder.default(self, obj)%0A%0A # Done.%0A return encoded_obj%0A%0A%0Adef numpy_hook(decoded_obj):%0A if isinstance(decoded_obj, dict):%0A if len(decoded_obj) == 1:%0A key, val = decoded_obj.items()%5B0%5D%0A%0A if MARKER in key:%0A dtype_name = key%5Blen(MARKER) + 1:%5D%0A decoded_obj = np.asarray(val, dtype=dtype_name)%0A # Done.%0A return decoded_obj%0A%0A#################################################%0A%0A%0Adef read(fname):%0A %22%22%22Read serialized data from JSON file, decode into Python object(s).%0A%0A Parameters%0A ----------%0A fname : string file name.%0A%0A %22%22%22%0A # Read string from JSON file.%0A with open(fname, 'r') as fi:%0A serial = fi.read()%0A%0A # Decode.%0A decoder = json.JSONDecoder(object_hook=numpy_hook)%0A data = decoder.decode(serial)%0A%0A return data%0A%0A%0Adef write(fname, data):%0A %22%22%22Encode Python object(s), write to JSON file.%0A%0A Parameters%0A ----------%0A fname : string file name.%0A data : Data to be written to file. May include Numpy arrays.%0A%0A %22%22%22%0A # Encode to string.%0A encoder = NumpyJSONEncoder(check_circular=True, indent=' ')%0A serial = encoder.encode(data)%0A%0A # Write to file.%0A with open(fname, 'w') as fo:%0A fo.write(serial)%0A
55cc66bc6d1c2c6280bb959bea23e14b4f26c741
Add Two Numbers problem
add_two_numbers.py
add_two_numbers.py
Python
0.999442
@@ -0,0 +1,2674 @@ +'''%0AYou are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.%0A%0AInput: (2 -%3E 4 -%3E 3) + (5 -%3E 6 -%3E 4)%0AOutput: 7 -%3E 0 -%3E 8%0A'''%0A%0A'''%0AThe main idea is quite simple, but need to pay attention to edge cases, e.g. there is still carry after adding is done (1 + 99)%0A'''%0A%0A# Definition for singly-linked list.%0Aclass ListNode:%0A def __init__(self, x):%0A self.val = x%0A self.next = None%0A%0Aclass Solution:%0A # @return a ListNode%0A def addTwoNumbers(self, l1, l2):%0A c = 0%0A head = None%0A pre = None%0A while l1 and l2:%0A if l1.val + l2.val + c %3E= 10:%0A node = ListNode(l1.val + l2.val + c - 10)%0A c = 1;%0A else:%0A node = ListNode(l1.val + l2.val + c)%0A c = 0%0A if not head:%0A head = node%0A pre = node%0A else:%0A pre.next = node%0A pre = node%0A l1 = l1.next%0A l2 = l2.next%0A #l1 is longer than l2%0A while l1:%0A if l1.val + c %3E= 10:%0A node = ListNode(l1.val + c - 10)%0A c = 1%0A else:%0A node = ListNode(l1.val + c)%0A c = 0%0A pre.next = node%0A pre = node%0A l1 = l1.next%0A #ls is longer than l1%0A while l2:%0A if l2.val + c %3E= 10:%0A node = ListNode(l2.val + c - 10)%0A c = 1%0A else:%0A node = ListNode(l2.val + c)%0A c = 0%0A pre.next = node%0A pre = node%0A l2 = l2.next%0A # adding is done, check if still has carry%0A if c:%0A node = ListNode(c)%0A pre.next = node%0A pre = node%0A return head%0A%0Aif __name__ == '__main__':%0A s = Solution()%0A p1 = ListNode(2)%0A p2 = ListNode(4)%0A p3 = ListNode(3)%0A p4 = ListNode(5)%0A p1.next = p2%0A p2.next = p3%0A p3.next = p4%0A l1 = p1%0A n1 = ListNode(5)%0A n2 = ListNode(6)%0A n3 = ListNode(4)%0A n1.next = n2%0A n2.next = n3%0A l2 = n1%0A l = s.addTwoNumbers(l1, l2)%0A while l:%0A print l.val, ' -%3E ', %0A l = l.next%0A print %22%5Cn%22%0A l1 = ListNode(5)%0A l2 = ListNode(5)%0A l = s.addTwoNumbers(l1, l2)%0A while l:%0A print l.val, ' -%3E ', %0A l = l.next%0A print %22%5Cn%22%0A l1 = ListNode(1)%0A n1 = ListNode(9)%0A n2 = ListNode(9)%0A n1.next = n2%0A l2 = n1%0A l = s.addTwoNumbers(l1, l2)%0A while l:%0A print l.val, ' -%3E ', %0A l = l.next%0A print %22%5Cn%22%0A
a3f23b804265bd59473873c2aa071188a73a9a9e
Test fail cases for custom codegen
slumba/tests/test_numbaext.py
slumba/tests/test_numbaext.py
Python
0
@@ -0,0 +1,650 @@ +import pytest%0A%0Afrom numba import boolean, njit, int64, TypingError%0Afrom slumba.numbaext import not_null, sizeof, unsafe_cast%0A%0A%0Adef test_sizeof_invalid():%0A dec = njit(int64(int64))%0A%0A with pytest.raises(TypingError):%0A @dec%0A def bad_sizeof(x):%0A return sizeof(x)%0A%0A%0Adef test_not_null_invalid():%0A dec = njit(boolean(int64))%0A%0A with pytest.raises(TypingError):%0A @dec%0A def bad_not_null(x):%0A return not_null(x)%0A%0A%0Adef test_unsafe_case_invalid():%0A dec = njit(int64(int64))%0A%0A with pytest.raises(TypingError):%0A @dec%0A def bad_unsafe_cast(x):%0A return unsafe_cast(x, int64)%0A
a1ae01bada1d500bd7f9f7f0f2deb458bfa6d2d1
Add the serial python test
bin/serial_test.py
bin/serial_test.py
Python
0.000097
@@ -0,0 +1,543 @@ +#!/usr/bin/env python%0A%0Afrom serial import Serial%0Afrom time import sleep%0A%0Aser = Serial('/dev/ttyUSB0', 9600)%0Asleep(3) # wait for the board to reset%0A%0Aprint %22start%22%0Aprint %22write%22%0Aser.write(%22hello%5Cn%22)%0Aprint %22read%22%0Aline = ser.readline()%0Aprint %22GOT %25s%22%25line%0A%0Aprint %22write world...%22%0Aser.write(%22world%5Cn%22)%0Aprint %22read%22%0Aline = ser.readline()%0Aprint %22GOT %25s%22%25line%0Aline = ser.readline()%0Aprint %22GOT %25s%22%25line%0A%0Acmd = %22%22%0Awhile not cmd == %22q%22:%0A cmd = raw_input(%22%3E%3E %22)%0A ser.write(cmd+%22%5Cn%22)%0A out = ser.readline()%0A out = ser.readline()%0A print out %0A%0A
22e04237ab43673071acd82e31153e8869a07e8b
Fix faster rcnn example.
client/examples/faster-rcnn.py
client/examples/faster-rcnn.py
# Config of faster rcnn import sys, os sys.path.append('..') from ue4cv import * # RCNN config rcnn_path = '/home/qiuwch/workspace/py-faster-rcnn' sys.path.append(os.path.join(rcnn_path, 'tools')) import demo as D # Use demo.py provided in faster-rcnn import numpy as np import matplotlib.pyplot as plt net = None HOST, PORT = "localhost", 9000 def init_caffe(): # TODO: parse args into here global net prototxt = os.path.join(D.cfg.MODELS_DIR, D.NETS['vgg16'][0], 'faster_rcnn_alt_opt', 'faster_rcnn_test.pt') caffemodel = os.path.join(D.cfg.DATA_DIR, 'faster_rcnn_models' , D.NETS['vgg16'][1]) gpu_id = 0 D.caffe.set_mode_gpu() D.caffe.set_device(gpu_id) D.cfg.GPU_ID = gpu_id D.cfg.TEST.HAS_RPN = True net = D.caffe.Net(prototxt, caffemodel, D.caffe.TEST) # Warmup on a dummy image im = 128 * np.ones((300, 500, 3), dtype = np.uint8) for i in xrange(2): _, _ = D.im_detect(net, im) def plot_image(image, boxes, scores): ax.cla() # Clear axis ax.imshow(image, aspect='equal') CONF_THRESH = 0.8 NMS_THRESH = 0.3 for cls_ind, cls in enumerate(D.CLASSES[1:]): cls_ind += 1 # Skip background cls_boxes = boxes[:, 4*cls_ind:4*(cls_ind+1)] cls_scores = scores[:, cls_ind] dets = np.hstack((cls_boxes, cls_scores[:,np.newaxis])).astype(np.float32) keep = D.nms(dets, NMS_THRESH) dets = dets[keep, :] plot_bb(image, cls, dets, thresh=CONF_THRESH) fig.canvas.draw() def plot_bb(im, class_name, dets, thresh=0.5): inds = np.where(dets[:, -1] >= thresh)[0] # if len(inds) == 0: return for i in inds: bbox = dets[i, :4] score = dets[i, -1] patch = plt.Rectangle((bbox[0], bbox[1]), bbox[2] - bbox[0] , bbox[3] - bbox[1], fill=False, edgecolor='red', linewidth=3.5) ax.add_patch(patch) text = '{:s} {:.3f}'.format(class_name, score) ax.text(bbox[0], bbox[1] - 2, text, bbox=dict(facecolor='blue', alpha=0.5) , fontsize=14, color='white') def process_image(filename): print 'Process image: %s' % filename if not os.path.isfile(filename): print 'Image file %s not exist' % filename return image = D.cv2.imread(filename) timer = D.Timer() timer.tic() scores, boxes = D.im_detect(net, image) timer.toc() print ('Detection took {:.3f}s for ' '{:d} object proposals').format(timer.total_time, boxes.shape[0]) show_img = image[:,:, (2,1,0)] # Reorder to RGB plot_image(show_img, boxes, scores) # def message_handler(message): # # This is a different thread # filename = message # if not net: # init_caffe() # Caffe needs to be started in this thread, otherwise GIL will make it very slow # # print repr(message) # lines = message.split('\n') # if lines: # process_image(lines[0]) def onclick(event): image = ue4cv.client.request('vget /camera/0/lit') process_image(image) pass if __name__ == '__main__': image = np.zeros((300, 300)) # client = Client((HOST, PORT), message_handler) ue4cv.client.connect() # Initialize the matplotlib fig, ax = plt.subplots() fig.canvas.mpl_connect('button_press_event', onclick) ax.imshow(image) plt.axis('off') plt.tight_layout() plt.show() # client.wait() # Wait forever
Python
0
@@ -54,16 +54,17 @@ d('..')%0A +# from ue4 @@ -74,16 +74,29 @@ import * +%0Aimport ue4cv %0A%0A# RCNN @@ -988,24 +988,29 @@ e, boxes +=None , scores ):%0A a @@ -1001,16 +1001,21 @@ , scores +=None ):%0A a @@ -1073,16 +1073,61 @@ qual')%0A%0A + if boxes != None and scores != None:%0A CONF @@ -1144,16 +1144,20 @@ 0.8%0A + + NMS_THRE @@ -1165,24 +1165,28 @@ H = 0.3%0A + + for cls_ind, @@ -1223,24 +1223,28 @@ %5D):%0A + cls_ind += 1 @@ -1262,16 +1262,20 @@ kground%0A + @@ -1324,24 +1324,28 @@ 1)%5D%0A + cls_scores = @@ -1364,16 +1364,20 @@ ls_ind%5D%0A + @@ -1459,16 +1459,20 @@ + + keep = D @@ -1498,24 +1498,28 @@ SH)%0A + dets = dets%5B @@ -1527,16 +1527,20 @@ eep, :%5D%0A + @@ -2189,24 +2189,143 @@ (filename):%0A + if not net:%0A init_caffe() # Caffe needs to be started in this thread, otherwise GIL will make it very slow%0A%0A print 'P @@ -2795,16 +2795,43 @@ scores)%0A + # plot_image(show_img)%0A %0A%0A# def @@ -2891,16 +2891,16 @@ thread%0A + # fi @@ -2920,130 +2920,8 @@ age%0A -# if not net:%0A# init_caffe() # Caffe needs to be started in this thread, otherwise GIL will make it very slow%0A #%0A#
804b7aa609ce1fde97f81f839776501352a59a89
Create card-flipping-game.py
Python/card-flipping-game.py
Python/card-flipping-game.py
Python
0.000001
@@ -0,0 +1,1468 @@ +# Time: O(n)%0A# Space: O(n)%0A%0A# On a table are N cards, with a positive integer printed on the front%0A# and back of each card (possibly different).%0A#%0A# We flip any number of cards, and after we choose one card.%0A#%0A# If the number X on the back of the chosen card is not on the front of%0A# any card, then this number X is good.%0A#%0A# What is the smallest number that is good? If no number is good, output 0.%0A#%0A# Here, fronts%5Bi%5D and backs%5Bi%5D represent the number on the front and back of%0A# card i.%0A#%0A# A flip swaps the front and back numbers, so the value on the front is%0A# now on the back and vice versa.%0A#%0A# Example:%0A#%0A# Input: fronts = %5B1,2,4,4,7%5D, backs = %5B1,3,4,1,3%5D%0A# Output: 2%0A# Explanation: If we flip the second card, the fronts are %5B1,3,4,4,7%5D and%0A# the backs are %5B1,2,4,1,3%5D.%0A# We choose the second card, which has number 2 on the back,%0A# and it isn't on the front of any card, so 2 is good.%0A#%0A# Note:%0A# - 1 %3C= fronts.length == backs.length %3C= 1000.%0A# - 1 %3C= fronts%5Bi%5D %3C= 2000.%0A# - 1 %3C= backs%5Bi%5D %3C= 2000.%0A%0Aimport itertools%0A%0A%0Aclass Solution(object):%0A def flipgame(self, fronts, backs):%0A %22%22%22%0A :type fronts: List%5Bint%5D%0A :type backs: List%5Bint%5D%0A :rtype: int%0A %22%22%22%0A same = %7Bn for i, n in enumerate(fronts) if n == backs%5Bi%5D%7D%0A result = float(%22inf%22)%0A for n in itertools.chain(fronts, backs):%0A if n not in same:%0A result = min(result, n)%0A return result if result %3C float(%22inf%22) else 0%0A
a0bbb3b7befbac0ca13a9fc34df63a409cbe930c
Create plot_WRFtimeseries.py
Python/plot_WRFtimeseries.py
Python/plot_WRFtimeseries.py
Python
0.000003
@@ -0,0 +1,2434 @@ +#plot_WRFtimeseries.py%0A%0A%22%22%22plot time series of WRF output; %0A NOTE: we assume variables to have dimension %5Btime,y,x%5D or %5Btime,z,y,x%5D%0A If this is not the case, adapt the dimensions where variable is read%0A%0AAuthor: Ingrid Super%0ALast revisions: 2-6-2016%22%22%22%0A%0Aimport netCDF4 as nc %0Aimport numpy as np%0Aimport matplotlib.pyplot as plt%0Afrom maptools import *%0Afrom numpy import ma%0Aimport datetime as dtm%0Afrom matplotlib.colors import LogNorm%0A%0A##############################################################################################%0A%22%22%22specify the following:%22%22%22%0A%22%22%22directory of the WRF output and grid resolution %5Bm%5D for each domain:%22%22%22%0Awrfout_path='/Storage/WRF/super004/WRF/run_paper2/output'%0A%22%22%22x- and y-location of the location you want to plot, the WRF domain, WRF vertical level and variable of interest%22%22%22%0Axloc=22%0Ayloc=28%0Adomain=3 #1 being outer domain%0Alev=0 #0 being surface level%0Avar='U10'%0A##############################################################################################%0A%0A%22%22%22read in variable of interest%22%22%22%0Avars=%5B%5D%0Atimers=%5B%5D%0Awrfout_files=%5Bos.path.join(wrfout_path,filename) for filename in os.listdir(wrfout_path) if filename.startswith('wrfout_d%2502d'%25domain)%5D%0Afor each_file in wrfout_files:%0A mf=nc.Dataset(each_file)%0A dum=mf.variables%5Bvar%5D%5B:%5D%0A wrftime=mf.variables%5B'Times'%5D%5B:%5D%0A for j in range(len(wrftime)):%0A year=int(''.join(wrftime%5Bj%5D%5B0:4%5D))%0A month=int(''.join(wrftime%5Bj%5D%5B5:7%5D))%0A day=int(''.join(wrftime%5Bj%5D%5B8:10%5D))%0A hour=int(''.join(wrftime%5Bj%5D%5B11:13%5D))%0A dat=dtm.datetime(year,month,day,hour,0)%0A timers.append(dat)%0A if len(dum.shape)==3:%0A dum2=dum%5B:,yloc,xloc%5D%0A elif len(dum.shape)==4:%0A dum2=dum%5B:,lev,yloc,xloc%5D%0A vars.extend(dum2)%0A%0A%22%22%22make plot and lay-out%22%22%22%0Axvar=np.arange(1,len(timers)+1)%0Aplot(xvar,vars,label='time series',color='k',linestyle='-',linewidth=2)%0Alegend(loc='upper right')%0Axlabel('label') #please specify%0Aylabel('label') #please specify%0Atitle('title') #please specify%0Askp=len(timers)/4%0Aticks=%5Bxvar%5B0%5D,xvar%5Bskp%5D,xvar%5B2*skp%5D,xvar%5B3*skp%5D,xvar%5B4*skp%5D%5D%0A%22%22%22the following statement allows you to change the labels on the x-axis and can be adapted to your specific needs (e.g. including year)%22%22%22%0Alabels=%5Btimers%5B0%5D.strftime(%22%25d. %25B%22),timers%5Bskp%5D.strftime(%22%25d. %25B%22),timers%5B2*skp%5D.strftime(%22%25d. %25B%22),timers%5B3*skp%5D.strftime(%22%25d. %25B%22),timers%5B4*skp%5D.strftime(%22%25d. %25B%22)%5D%0Aplt.xticks(ticks,labels)%0Aplt.show()%0A
4db53b62f616edb61ce469ffb2f4cd642f925784
Add patch migration for missing constraints (#6276)
warehouse/migrations/versions/48def930fcfd_webauthn_and_macaroon_constraints.py
warehouse/migrations/versions/48def930fcfd_webauthn_and_macaroon_constraints.py
Python
0
@@ -0,0 +1,1412 @@ +# Licensed under the Apache License, Version 2.0 (the %22License%22);%0A# you may not use this file except in compliance with the License.%0A# You may obtain a copy of the License at%0A#%0A# http://www.apache.org/licenses/LICENSE-2.0%0A#%0A# Unless required by applicable law or agreed to in writing, software%0A# distributed under the License is distributed on an %22AS IS%22 BASIS,%0A# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.%0A# See the License for the specific language governing permissions and%0A# limitations under the License.%0A%22%22%22%0AWebAuthn and Macaroon constraints%0A%0ARevision ID: 48def930fcfd%0ARevises: 5ea52744d154%0ACreate Date: 2019-07-26 17:55:41.802528%0A%22%22%22%0A%0Afrom alembic import op%0A%0Arevision = %2248def930fcfd%22%0Adown_revision = %225ea52744d154%22%0A%0A%0Adef upgrade():%0A op.create_unique_constraint(%0A %22_user_macaroons_description_uc%22, %22macaroons%22, %5B%22description%22, %22user_id%22%5D%0A )%0A op.drop_index(%22user_security_keys_label_key%22, table_name=%22user_security_keys%22)%0A op.create_unique_constraint(%0A %22user_security_keys_label_key%22, %22user_security_keys%22, %5B%22label%22%5D%0A )%0A%0A%0Adef downgrade():%0A op.drop_constraint(%0A %22user_security_keys_label_key%22, %22user_security_keys%22, type_=%22unique%22%0A )%0A op.create_index(%0A %22user_security_keys_label_key%22, %22user_security_keys%22, %5B%22user_id%22%5D, unique=False%0A )%0A op.drop_constraint(%22_user_macaroons_description_uc%22, %22macaroons%22, type_=%22unique%22)%0A
2c6141656e0a0885dbcfecad5f227a950dafc3c3
Create predict-the-winner.py
Python/predict-the-winner.py
Python/predict-the-winner.py
Python
0.000403
@@ -0,0 +1,1916 @@ +# Time: O(n%5E2)%0A# Space: O(n)%0A%0A# Given an array of scores that are non-negative integers.%0A# Player 1 picks one of the numbers from either end of the array%0A# followed by the player 2 and then player 1 and so on.%0A# Each time a player picks a number, that number will not be available for the next player.%0A# This continues until all the scores have been chosen. The player with the maximum score wins.%0A#%0A# Given an array of scores, predict whether player 1 is the winner.%0A# You can assume each player plays to maximize his score.%0A#%0A# Example 1:%0A# Input: %5B1, 5, 2%5D%0A# Output: False%0A# Explanation: Initially, player 1 can choose between 1 and 2. %0A# If he chooses 2 (or 1), then player 2 can choose from 1 (or 2) and 5.%0A# If player 2 chooses 5, then player 1 will be left with 1 (or 2). %0A# So, final score of player 1 is 1 + 2 = 3, and player 2 is 5. %0A# Hence, player 1 will never be the winner and you need to return False.%0A# Example 2:%0A# Input: %5B1, 5, 233, 7%5D%0A# Output: True%0A# Explanation: Player 1 first chooses 1. Then player 2 have to choose between 5 and 7.%0A# No matter which number player 2 choose, player 1 can choose 233.%0A# Finally, player 1 has more score (234) than player 2 (12), so you need to return True representing player1 can win.%0A# Note:%0A# 1 %3C= length of the array %3C= 20.%0A# Any scores in the given array are non-negative integers and will not exceed 10,000,000.%0A# If the scores of both players are equal, then player 1 is still the winner.%0A%0Aclass Solution(object):%0A def PredictTheWinner(self, nums):%0A %22%22%22%0A :type nums: List%5Bint%5D%0A :rtype: bool%0A %22%22%22%0A if len(nums) %25 2 == 0 or len(nums) == 1:%0A return True%0A%0A dp = %5B0%5D * len(nums);%0A for i in reversed(xrange(len(nums))):%0A dp%5Bi%5D = nums%5Bi%5D%0A for j in xrange(i+1, len(nums)):%0A dp%5Bj%5D = max(nums%5Bi%5D - dp%5Bj%5D, nums%5Bj%5D - dp%5Bj - 1%5D)%0A%0A return dp%5B-1%5D %3E= 0%0A %0A
5de560e8458375a2e03200128ff046927cb3dbb5
Add first solution to LCq003
leetcode/q003/solution.py
leetcode/q003/solution.py
Python
0
@@ -0,0 +1,876 @@ +%0D%0AMAX_SUBSTRING_LENGTH = 26%0D%0A%0D%0Aclass Solution:%0D%0A def lengthOfLongestSubstring(self, s: str) -%3E int:%0D%0A %22%22%22%0D%0A for a given string, at each starting position within the string,%0D%0A check how far you can go without repeating a character%0D%0A %22%22%22%0D%0A max_length = 0%0D%0A total_length = len(s)%0D%0A%0D%0A for i in range(0, total_length):%0D%0A if max_length %3E (total_length - i):%0D%0A return max_length%0D%0A length = findUniqueLength(s%5Bi:%5D)%0D%0A if length %3E max_length:%0D%0A max_length = length%0D%0A if max_length == MAX_SUBSTRING_LENGTH:%0D%0A return max_length%0D%0A return max_length%0D%0A%0D%0Adef findUniqueLength(s: str) -%3E int:%0D%0A chars = %7B%7D%0D%0A for char in s:%0D%0A if char in chars:%0D%0A return len(chars)%0D%0A chars%5Bchar%5D = True%0D%0A return len(chars)%0D%0A%0D%0A
42ca9ddc91a213816183f20a985d5273de6a4312
compute bits set to 1
bits_set_to_one.py
bits_set_to_one.py
Python
0.999999
@@ -0,0 +1,219 @@ +def one_bits(x):%0A %22%22%22Given an integer, compute the number of bits set to 1%22%22%22%0A m = 1%0A count = 0%0A for i in range(x // 2 + 1):%0A if x & m == m:%0A count += 1%0A m = m %3C%3C 1%0A return count%0A
c80f789da36ad0c23a6cbbf20fd97808d62c3619
Create a simple Spinner.
py_clui/__init__.py
py_clui/__init__.py
Python
0
@@ -0,0 +1,1651 @@ +#!/usr/bin/env python%0A# https://en.wikipedia.org/wiki/ANSI_escape_code#Colors%0A# http://aurelio.net/shell/canivete/%0A# https://stackoverflow.com/questions/27265322/how-to-print-to-console-in-color%0A%0Aimport sys%0Aimport time%0A%0A#def colored(text, color):%0A# return COLORS%5Bcolor%5D + text + COLORS%5B'white'%5D%0A%0A%0A#def Gauge(value, max_value, width, danger_zone, suffix=None):%0A# if max_value == 0:%0A# return '%5B%5D'%0A#%0A# length = math.ceil(value / max_value * width)%0A#%0A# if length %3E width:%0A# length = width%0A#%0A# bar_color = 'green'%0A# if value %3E danger_zone:%0A# bar_color = 'red'%0A#%0A# return '%5B' + colored('%7C' * length, bar_color) + '-' * (width + 1 - length) + '%5D ' + colored(suffix, 'grey')%0A%0A%0A#COLORS = %7B%0A# 'white': '%5C033%5B0m', # White (normal)%0A# 'red': '%5C033%5B31m', # Red%0A# 'green': '%5C033%5B32m', # Green%0A# 'orange': '%5C033%5B33m', # Orange%0A# 'blue': '%5C033%5B34m', # Blue%0A# 'purple': '%5C033%5B35m', # Purple%0A# 'grey': '%5C033%5B30;1m', # Grey%0A#%7D%0A%0A%0Aclass Spinner:%0A def __init__(self, message, style=None):%0A self.message = message%0A self.style = %5B'%7C','/', '-', '%5C%5C'%5D%0A self._number = 0%0A #self.style = %5B'%E2%97%9C', '%E2%97%A0', '%E2%97%9D', '%E2%97%9E', '%E2%97%A1', '%E2%97%9F'%5D%0A self.style = %5B'%E2%A3%BE', '%E2%A3%BD', '%E2%A3%BB', '%E2%A2%BF', '%E2%A1%BF', '%E2%A3%9F', '%E2%A3%AF', '%E2%A3%B7'%5D%0A%0A def run(self):%0A self._draw()%0A%0A def update_msg(self, message):%0A self.message = message%0A%0A def _draw(self):%0A frames = %5B' %5Cu001b%5B96m%7B0%7D '.format(el) for el in self.style%5D%0A msg = '%5Cu001b%5B0G%7B0%7D%5Cu001b%5B90m%7B1%7D%5Cu001b%5B0m'%0A%0A self._number += 1%0A%0A print(msg.format(frames%5Bself._number %25 len(self.style)%5D, self.message), end='%5Cr', file=sys.stdout, flush=True)%0A
1f043dd959fa1e1d243a3278abeb66838a2f9305
Remove the IR target type in migration.
server/auvsi_suas/migrations/0013_remove_ir_as_target_type.py
server/auvsi_suas/migrations/0013_remove_ir_as_target_type.py
Python
0
@@ -0,0 +1,470 @@ +# -*- coding: utf-8 -*-%0Afrom __future__ import unicode_literals%0A%0Afrom django.db import models, migrations%0A%0A%0Aclass Migration(migrations.Migration):%0A%0A dependencies = %5B('auvsi_suas', '0012_missionclockevent'), %5D%0A%0A operations = %5B%0A migrations.AlterField(%0A model_name='target',%0A name='target_type',%0A field=models.IntegerField(choices=%5B(1, b'standard'), (2, b'qrc'), (%0A 3, b'off_axis'), (4, b'emergent')%5D), ),%0A %5D%0A
2f2e85a7f1df46c6f33969a9dd4a945c8dfa33dc
Add Cython-generated C code validator
powertrip.py
powertrip.py
#!/usr/bin/env python # ---------------------------------------------------------------------------- # Copyright (c) 2013--, scikit-bio development team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file COPYING.txt, distributed with this software. # ---------------------------------------------------------------------------- from __future__ import absolute_import, division, print_function import os import os.path import sys def main(): root = 'skbio' validators = [TestInitValidator(), ExecPermissionValidator()] return_code = 0 for validator in validators: success, msg = validator.validate(root) if not success: return_code = 1 sys.stderr.write('\n'.join(msg)) sys.stderr.write('\n\n') return return_code class Validator(object): def validate(self, root): raise NotImplementedError("Validator subclasses must implement " "validate.") class TestInitValidator(Validator): def __init__(self, test_dir_names=('test', 'tests'), init_name='__init__.py'): self.test_dir_names = test_dir_names self.init_name = init_name def validate(self, root): missing_inits = [] for root, dirs, files in os.walk(root): if (os.path.basename(root) in self.test_dir_names and self.init_name not in files): missing_inits.append(root) success = True msg = [] if missing_inits: success = False msg.append("Missing %s files inside test directories:" % self.init_name) for missing_init in missing_inits: msg.append(" %s" % missing_init) return success, msg class ExecPermissionValidator(Validator): def __init__(self, extensions=('.py', '.pyx', '.h', '.c')): self.extensions = extensions def validate(self, root): invalid_perms = [] for root, dirs, files in os.walk(root): for file_ in files: if os.path.splitext(file_)[1] in self.extensions: fp = os.path.join(root, file_) if os.access(fp, os.X_OK): invalid_perms.append(fp) success = True msg = [] if invalid_perms: success = False msg.append("Library code with execute permissions:") for invalid_perm in invalid_perms: msg.append(" %s" % invalid_perm) return success, msg if __name__ == '__main__': sys.exit(main())
Python
0.000009
@@ -569,16 +569,62 @@ idator() +,%0A GeneratedCythonValidator() %5D%0A%0A r @@ -2657,16 +2657,1085 @@ , msg%0A%0A%0A +class GeneratedCythonValidator(Validator):%0A def __init__(self, cython_extension='.pyx'):%0A self.cython_extension = cython_extension%0A%0A def validate(self, root):%0A missing_gen = %5B%5D%0A for root, dirs, files in os.walk(root):%0A for file_ in files:%0A base, ext = os.path.splitext(file_)%0A%0A if ext == self.cython_extension:%0A found_match = False%0A match = '%25s.c' %25 base%0A for f in files:%0A if (f == match and%0A os.path.getsize(os.path.join(root, f)) %3E 0):%0A found_match = True%0A break%0A%0A if not found_match:%0A missing_gen.append(os.path.join(root, file_))%0A%0A success = True%0A msg = %5B%5D%0A if missing_gen:%0A success = False%0A msg.append(%22Cython code missing generated C code:%22)%0A%0A for e in missing_gen:%0A msg.append(%22 %25s%22 %25 e)%0A%0A return success, msg%0A%0A%0A if __nam
e869920c2334e4d0bcd95d2805c8126952c97b51
Add tests for `cms.debug`.
cms/tests/test_debug.py
cms/tests/test_debug.py
Python
0
@@ -0,0 +1,1022 @@ +from django.test import TestCase%0A%0Afrom ..debug import print_exc, print_current_exc%0A%0Aimport os%0Afrom StringIO import StringIO%0Aimport sys%0A%0A%0Aclass TestDebug(TestCase):%0A%0A def test_print_exc(self):%0A def func():%0A return True%0A%0A def func_raise():%0A raise Exception%0A%0A self.assertEqual(print_exc(func), func)%0A%0A self.orig_stderr = sys.stderr%0A sys.stderr = open(os.devnull, 'w')%0A%0A with self.settings(DEBUG=True):%0A self.assertTrue(print_exc(func)())%0A%0A with self.assertRaises(Exception):%0A print_exc(func_raise)()%0A%0A sys.stderr = self.orig_stderr%0A%0A def test_print_current_exc(self):%0A # Redirect STDOUT so we can capture the %60print%60.%0A orig_stderr = sys.stderr%0A stderr = StringIO()%0A sys.stderr = stderr%0A%0A print_current_exc()%0A%0A with self.settings(DEBUG=True):%0A print_current_exc()%0A%0A self.assertEqual(stderr.getvalue().strip(), 'None')%0A%0A sys.stderr = orig_stderr%0A
f301dd2366f53a6cf4b0949942b8520502f54351
Fix import error when [jwt] not installed.
boxsdk/__init__.py
boxsdk/__init__.py
# coding: utf-8 from __future__ import unicode_literals from .auth.jwt_auth import JWTAuth from .auth.oauth2 import OAuth2 from .client import Client from .object import * # pylint:disable=wildcard-import,redefined-builtin
Python
0
@@ -51,16 +51,25 @@ terals%0A%0A +try:%0A from .au @@ -95,16 +95,115 @@ JWTAuth%0A +except ImportError:%0A JWTAuth = None # If extras are not installed, JWTAuth won't be available.%0A from .au
334961054d875641d150eec4d6938f6f824ea655
Add initializer for top-level '_gcloud_vendor' package.
_gcloud_vendor/__init__.py
_gcloud_vendor/__init__.py
Python
0
@@ -0,0 +1,244 @@ +%22%22%22Dependencies %22vendored in%22, due to dependencies, Python versions, etc.%0A%0ACurrent set%0A-----------%0A%0A%60%60apitools%60%60 (pending release to PyPI, plus acceptable Python version%0A support for its dependencies). Review before M2.%0A%22%22%22%0A
00e86dcc5633a4e381ec67bb4fd719b37633e9c4
solved with generators
problem_5.py
problem_5.py
Python
0.997103
@@ -0,0 +1,485 @@ +def test_get_smallest_evenly_divisible_by():%0A assert get_smallest_evenly_divisible_by(1, 10) == 2520%0A%0A%0Adef is_evenly_divisible(value, low, high):%0A high += 1%0A for i in range(low, high):%0A if value %25 i != 0:%0A return False%0A return True%0A%0A%0Adef infite_seq():%0A i = 1%0A%0A while True:%0A yield i%0A i += 1%0A%0A%0Adef get_smallest_evenly_divisible_by(low, high):%0A for i in infite_seq():%0A if is_evenly_divisible(i, low, high):%0A return i%0A
a6e02bdbc29c13b7a41d3848171fb80d8a29e05d
Revert unintended commit.
chrome/browser/sync/protocol/sync_proto.gyp
chrome/browser/sync/protocol/sync_proto.gyp
# Copyright (c) 2010 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. { 'variables': { 'chromium_code': 1, }, 'targets': [ { # Protobuf compiler / generate rule for sync.proto. This is used by # test code in net, which is why it's isolated into its own .gyp file. 'target_name': 'sync_proto', 'type': 'none', 'sources': [ 'sync.proto', 'encryption.proto', 'app_specifics.proto', 'autofill_specifics.proto', 'bookmark_specifics.proto', 'extension_specifics.proto', 'nigori_specifics.proto', 'password_specifics.proto', 'preference_specifics.proto', 'session_specifics.proto', 'test.proto', 'theme_specifics.proto', 'typed_url_specifics.proto', ], 'rules': [ { 'rule_name': 'genproto', 'extension': 'proto', 'inputs': [ '<(PRODUCT_DIR)/<(EXECUTABLE_PREFIX)protoc<(EXECUTABLE_SUFFIX)', ], 'outputs': [ '<(PRODUCT_DIR)/pyproto/sync_pb/<(RULE_INPUT_ROOT)_pb2.py', '<(SHARED_INTERMEDIATE_DIR)/protoc_out/chrome/browser/sync/protocol/<(RULE_INPUT_ROOT).pb.h', '<(SHARED_INTERMEDIATE_DIR)/protoc_out/chrome/browser/sync/protocol/<(RULE_INPUT_ROOT).pb.cc', ], 'action': [ '<(PRODUCT_DIR)/<(EXECUTABLE_PREFIX)protoc<(EXECUTABLE_SUFFIX)', '--proto_path=.', './<(RULE_INPUT_ROOT)<(RULE_INPUT_EXT)', '--cpp_out=<(SHARED_INTERMEDIATE_DIR)/protoc_out/chrome/browser/sync/protocol', '--python_out=<(PRODUCT_DIR)/pyproto/sync_pb', ], # 'message': 'Generating C++ and Python code from <(RULE_INPUT_PATH)', }, ], 'dependencies': [ '../../../../third_party/protobuf/protobuf.gyp:protoc#host', ], }, { 'target_name': 'sync_proto_cpp', 'type': 'none', 'export_dependent_settings': [ '../../../../third_party/protobuf/protobuf.gyp:protobuf_lite', 'sync_proto', ], 'dependencies': [ '../../../../third_party/protobuf/protobuf.gyp:protobuf_lite', 'sync_proto', ], 'direct_dependent_settings': { 'include_dirs': [ '<(SHARED_INTERMEDIATE_DIR)/protoc_out', ], }, }, ], } # Local Variables: # tab-width:2 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=2 shiftwidth=2:
Python
0.000009
@@ -1773,18 +1773,16 @@ - # 'messag
bbebd328c8b0b00bd86a0a8f7e86a5312c7fd3c8
fix double showing of entities.
aleph/views/documents_api.py
aleph/views/documents_api.py
import logging from werkzeug.exceptions import BadRequest from flask import Blueprint, redirect, send_file, request from apikit import jsonify, Pager, get_limit, get_offset from aleph.core import get_archive, url_for, db from aleph import authz from aleph.model import Document, Entity, Reference, Collection from aleph.views.cache import enable_cache from aleph.search.tabular import tabular_query, execute_tabular_query from aleph.search.util import next_params from aleph.views.util import get_document, match_ids from aleph.views.util import get_tabular, get_page log = logging.getLogger(__name__) blueprint = Blueprint('documents_api', __name__) @blueprint.route('/api/1/documents', methods=['GET']) def index(): collection_ids = match_ids('collection', authz.collections(authz.READ)) q = Document.all() clause = Collection.id.in_(collection_ids) q = q.filter(Document.collections.any(clause)) hashes = request.args.getlist('content_hash') if len(hashes): q = q.filter(Document.content_hash.in_(hashes)) return jsonify(Pager(q)) @blueprint.route('/api/1/documents/<int:document_id>') def view(document_id): doc = get_document(document_id) enable_cache() data = doc.to_dict() data['data_url'] = get_archive().generate_url(doc.meta) if data['data_url'] is None: data['data_url'] = url_for('documents_api.file', document_id=document_id) if doc.meta.is_pdf: data['pdf_url'] = data['data_url'] else: try: data['pdf_url'] = get_archive().generate_url(doc.meta.pdf) except Exception as ex: log.info('Could not generate PDF url: %r', ex) if data.get('pdf_url') is None: data['pdf_url'] = url_for('documents_api.pdf', document_id=document_id) data['collections'] = doc.collections return jsonify(data) @blueprint.route('/api/1/documents/<int:document_id>/references') def references(document_id): doc = get_document(document_id) q = db.session.query(Reference) q = q.filter(Reference.document_id == doc.id) q = q.join(Entity) q = q.filter(Entity.state == Entity.STATE_ACTIVE) clause = Collection.id.in_(authz.collections(authz.READ)) q = q.filter(Entity.collections.any(clause)) q = q.order_by(Reference.weight.desc()) return jsonify({'results': q.all()}) @blueprint.route('/api/1/documents/<int:document_id>/file') def file(document_id): document = get_document(document_id) enable_cache(server_side=True) url = get_archive().generate_url(document.meta) if url is not None: return redirect(url) local_path = get_archive().load_file(document.meta) fh = open(local_path, 'rb') return send_file(fh, as_attachment=True, attachment_filename=document.meta.file_name, mimetype=document.meta.mime_type) @blueprint.route('/api/1/documents/<int:document_id>/pdf') def pdf(document_id): document = get_document(document_id) enable_cache(server_side=True) if document.type != Document.TYPE_TEXT: raise BadRequest("PDF is only available for text documents") pdf = document.meta.pdf url = get_archive().generate_url(pdf) if url is not None: return redirect(url) local_path = get_archive().load_file(pdf) fh = open(local_path, 'rb') return send_file(fh, mimetype=pdf.mime_type) @blueprint.route('/api/1/documents/<int:document_id>/pages/<int:number>') def page(document_id, number): document, page = get_page(document_id, number) enable_cache(server_side=True) return jsonify(page) @blueprint.route('/api/1/documents/<int:document_id>/tables/<int:table_id>') def table(document_id, table_id): document, tabular = get_tabular(document_id, table_id) enable_cache(vary_user=True) return jsonify(tabular) @blueprint.route('/api/1/documents/<int:document_id>/tables/<int:table_id>/rows') def rows(document_id, table_id): document, tabular = get_tabular(document_id, table_id) query = tabular_query(document_id, table_id, request.args) query['size'] = get_limit(default=100) query['from'] = get_offset() result = execute_tabular_query(query) params = next_params(request.args, result) if params is not None: result['next'] = url_for('documents_api.rows', document_id=document_id, table_id=table_id, **params) return jsonify(result)
Python
0
@@ -2135,24 +2135,70 @@ == doc.id)%0A + q = q.filter(Reference.origin == 'regex')%0A q = q.jo
2039e9845e669ae83b1ec42fc631f48ff585427a
remove unused variable
cogs/friendcode.py
cogs/friendcode.py
import discord import hashlib import struct from cogs.converters import SafeMember from cogs.database import DatabaseCog from discord.ext import commands class FriendCode(DatabaseCog): """ Stores and obtains friend codes using an SQLite 3 database. """ # based on https://github.com/megumisonoda/SaberBot/blob/master/lib/saberbot/valid_fc.rb def verify_fc(self, fc): fc = int(fc.replace('-', '')) if fc > 0x7FFFFFFFFF: return None principal_id = fc & 0xFFFFFFFF checksum = (fc & 0xFF00000000) >> 32 return fc if hashlib.sha1(struct.pack('<L', principal_id)).digest()[0] >> 1 == checksum else None def fc_to_string(self, fc): fc = str(fc).rjust(12, '0') return f"{fc[0:4]} - {fc[4:8]} - {fc[8:12]}" @commands.command() async def fcregister(self, ctx, fc): """Add your friend code.""" fc = self.verify_fc(fc) if not fc: await ctx.send("This friend code is invalid.") return rows = await self.get_friendcode(ctx.author.id) for row in rows: # if the user already has one, this prevents adding another await ctx.send("Please delete your current friend code with `.fcdelete` before adding another.") return await self.add_friendcode(ctx.author.id, fc) await ctx.send(f"{ctx.author.mention} Friend code inserted: {self.fc_to_string(fc)}") @commands.command() async def fcquery(self, ctx, member: SafeMember): """Get other user's friend code. You must have one yourself in the database.""" rows = await self.get_friendcode(ctx.author.id) for row in rows: # assuming there is only one, which there should be rows_m = await self.get_friendcode(member.id) for row_m in rows_m: await ctx.send(f"{member.mention} friend code is {self.fc_to_string(row_m[1])}") try: member.send(f"{self.bot.help_command.remove_mentions(ctx.author)} has asked for your friend code! Their code is {self.fc_to_string(row[1])}.") except discord.errors.Forbidden: pass # don't fail in case user has DMs disabled for this server, or blocked the bot return await ctx.send("This user does not have a registered friend code.") return await ctx.send("You need to register your own friend code with `.fcregister <friendcode>` before getting others.") @commands.command() async def fcdelete(self, ctx): """Delete your friend code.""" c = self.bot.dbcon.cursor() await self.delete_friendcode(ctx.author.id) await ctx.send("Friend code removed from database.") self.bot.dbcon.commit() @commands.command() async def fctest(self, ctx, fc): fc = self.verify_fc(fc) if fc: await ctx.send(self.fc_to_string(fc)) else: await ctx.send("Invalid.") def setup(bot): bot.add_cog(FriendCode(bot))
Python
0.00003
@@ -2633,44 +2633,8 @@ %22%22%22%0A - c = self.bot.dbcon.cursor()%0A
906898f6b8139c364994b50e0d6c60da6e4ec549
Add train module, simplify the code in and modules
train.py
train.py
Python
0.000001
@@ -0,0 +1,1568 @@ +from nltk.corpus import PlaintextCorpusReader%0Aimport networkx as nx%0A%0Afrom collections import Counter%0Afrom itertools import chain%0Afrom itertools import tee%0A%0Aimport graph_utils as gutil%0A%0A%0Adef pairwise(itr):%0A a, b = tee(itr) # two version of itr%0A next(b, None) # b goes ahead one step%0A return zip(a, b) # return iterator%0A%0A%0Adef doc_to_sentences(root, ext):%0A return PlaintextCorpusReader(root, ext).sents()%0A%0A%0Adef doc_to_pairs(root, ext):%0A return chain.from_iterable(%5Bpairwise(s)%0A for s in doc_to_sentences(root, ext)%5D)%0A%0A%0Adef pairs_to_graph(pairs):%0A G = nx.DiGraph()%0A G.add_weighted_edges_from(%5B(n1, n2, count)%0A for ((n1, n2), count) in Counter(pairs).items()%5D)%0A return G%0A%0A%0Adef sum_path(G, p):%0A return sum(%5BG%5Bn1%5D%5Bn2%5D%5B'weight'%5D for (n1, n2) in pairwise(p)%5D)%0A%0A%0Adef all_path(G, src, dest, cutoff=4):%0A return sorted(%5Bpath%0A for path in nx.all_simple_paths(G, src, dest, cutoff)%5D,%0A key=lambda path: -1 * sum_path(G, path))%0A%0A%0Adef train_graph(model_name, data_root, file_ext=r'.*%5C.txt'):%0A pairs = doc_to_pairs(data_root, file_ext)%0A G = pairs_to_graph(pairs)%0A gutil.write_edges(G, model_name)%0A%0A%0Adef example():%0A pairs = %5B('a', 'b'), ('b', 'c'), ('c', 'd'), ('a', 'b'), ('c', 'd')%5D%0A%0A G = pairs_to_graph(pairs)%0A gutil.print_graph(G)%0A gutil.draw_graph(G, 'example.png')%0A gutil.write_edges(G, 'example.edge')%0A%0A res = all_path(G, 'a', 'd')%0A print(res)%0A%0A%0Aif __name__ == '__main__':%0A data_root = '/home/minhvu/Data/dummy/'%0A model_name = 'dummy_v1.edge'%0A train_graph(model_name, data_root)%0A
e411fcd647e3cdcf415465288e527aecfd026fc5
add additional data to flavor's ViewBuilder
nova/api/openstack/views/flavors.py
nova/api/openstack/views/flavors.py
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2010-2011 OpenStack LLC. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import os.path from nova.api.openstack import common class ViewBuilder(object): def build(self, flavor_obj, is_detail=False): """Generic method used to generate a flavor entity.""" if is_detail: flavor = self._build_detail(flavor_obj) else: flavor = self._build_simple(flavor_obj) self._build_extra(flavor) return flavor def _build_simple(self, flavor_obj): """Build a minimal representation of a flavor.""" return { "id": flavor_obj["flavorid"], "name": flavor_obj["name"], } def _build_detail(self, flavor_obj): """Build a more complete representation of a flavor.""" simple = self._build_simple(flavor_obj) detail = { "ram": flavor_obj["memory_mb"], "disk": flavor_obj["local_gb"], } detail.update(simple) return detail def _build_extra(self, flavor_obj): """Hook for version-specific changes to newly created flavor object.""" pass class ViewBuilderV11(ViewBuilder): """Openstack API v1.1 flavors view builder.""" def __init__(self, base_url, project_id=""): """ :param base_url: url of the root wsgi application """ self.base_url = base_url self.project_id = project_id def _build_extra(self, flavor_obj): flavor_obj["links"] = self._build_links(flavor_obj) def _build_links(self, flavor_obj): """Generate a container of links that refer to the provided flavor.""" href = self.generate_href(flavor_obj["id"]) bookmark = self.generate_bookmark(flavor_obj["id"]) links = [ { "rel": "self", "href": href, }, { "rel": "bookmark", "href": bookmark, }, ] return links def generate_href(self, flavor_id): """Create an url that refers to a specific flavor id.""" return os.path.join(self.base_url, self.project_id, "flavors", str(flavor_id)) def generate_bookmark(self, flavor_id): """Create an url that refers to a specific flavor id.""" return os.path.join(common.remove_version_from_href(self.base_url), self.project_id, "flavors", str(flavor_id))
Python
0
@@ -1536,24 +1536,206 @@ local_gb%22%5D,%0A + %22swap%22: flavor_obj%5B%22swap%22%5D,%0A %22rxtx_quota%22: flavor_obj%5B%22rxtx_quota%22%5D,%0A %22rxtx_cap%22: flavor_obj%5B%22rxtx_cap%22%5D,%0A %22vcpus%22: flavor_obj%5B%22vcpus%22%5D,%0A %7D%0A%0A
2e9e1f801653d4df60f5103d70ae91a7d307b200
add the management bare minimum to auto-create site.
oneflow/base/management/__init__.py
oneflow/base/management/__init__.py
Python
0
@@ -0,0 +1,677 @@ +# -*- coding: utf-8 -*-%0A%0Afrom django.contrib.sites import models%0Afrom django.db.models import signals%0Afrom django.conf import settings%0A%0A%0Adef create_site(app, created_models, verbosity, **kwargs):%0A %22%22%22 Create the default site when when we install the sites framework. %22%22%22%0A%0A if not models.Site in created_models:%0A return%0A%0A try:%0A models.Site.objects.get(pk=settings.SITE_ID)%0A%0A except models.Site.DoesNotExist:%0A models.Site.objects.create(pk=settings.SITE_ID,%0A name=settings.SITE_NAME,%0A domain=settings.SITE_DOMAIN).save()%0A%0Asignals.post_syncdb.connect(create_site, sender=models)%0A
0f9f4f1ee325d72d09625850ba6a153ae5616ab0
Update test to load plugin
nose2/tests/functional/test_collect_plugin.py
nose2/tests/functional/test_collect_plugin.py
import re from nose2.tests._common import FunctionalTestCase class CollectOnlyFunctionalTest(FunctionalTestCase): def test_collect_tests_in_package(self): self.assertTestRunOutputMatches( self.runIn('scenario/tests_in_package', '-v', '--collect-only'), stderr=EXPECT_LAYOUT1) # expectations EXPECT_LAYOUT1 = re.compile("""\ Ran 25 tests in \d.\d+s OK""")
Python
0
@@ -269,16 +269,73 @@ ct-only' +,%0A '--plugin=nose2.plugins.collect' ),%0A
8eddb8eafede9fa5aa9761ae53fa0d7081a4ba8f
Add setup.py
setup.py
setup.py
Python
0
@@ -0,0 +1,2266 @@ +from __future__ import print_function%0Afrom os import sys%0A%0Atry:%0A from skbuild import setup%0Aexcept ImportError:%0A print('scikit-build is required to build from source.', file=sys.stderr)%0A print('Please run:', file=sys.stderr)%0A print('', file=sys.stderr)%0A print(' python -m pip install scikit-build')%0A sys.exit(1)%0A%0Asetup(%0A name='itk-anisotropicdiffusionlbr',%0A version='0.1.0',%0A author='Insight Software Consortium',%0A author_email='community@itk.org',%0A packages=%5B'itk'%5D,%0A package_dir=%7B'itk': 'itk'%7D,%0A download_url=r'https://github.com/InsightSoftwareConsortium/ITKAnisotropicDiffusionLBR',%0A description=r'Smooth images while preserving edges or coherent structures.',%0A long_description='ITK is an open-source, cross-platform library that '%0A 'provides developers with an extensive suite of software '%0A 'tools for image analysis. This package implements anisotropic diffusion '%0A 'using Lattice Basis Reduction. For more information, see '%0A 'Mirebeau J., Fehrenbach J., Risser L., Tobji S. '%0A '%22Anisotropic Diffusion in ITK%22 '%0A 'http://insight-journal.org/browse/publication/953 '%0A 'http://hdl.handle.net/10380/3505 ',%0A classifiers=%5B%0A %22License :: OSI Approved :: Apache Software License%22,%0A %22Programming Language :: Python%22,%0A %22Programming Language :: C++%22,%0A %22Development Status :: 4 - Beta%22,%0A %22Intended Audience :: Developers%22,%0A %22Intended Audience :: Education%22,%0A %22Intended Audience :: Healthcare Industry%22,%0A %22Intended Audience :: Science/Research%22,%0A %22Topic :: Scientific/Engineering%22,%0A %22Topic :: Scientific/Engineering :: Medical Science Apps.%22,%0A %22Topic :: Scientific/Engineering :: Information Analysis%22,%0A %22Topic :: Software Development :: Libraries%22,%0A %22Operating System :: Android%22,%0A %22Operating System :: Microsoft :: Windows%22,%0A %22Operating System :: POSIX%22,%0A %22Operating System :: Unix%22,%0A %22Operating System :: MacOS%22%0A %5D,%0A license='Apache',%0A keywords='ITK InsightToolkit',%0A url=r'https://itk.org/',%0A install_requires=%5B%0A r'itk'%0A %5D%0A )%0A
a577c19e1296df413100f6858ded39ab71e757a8
Add setup.py
setup.py
setup.py
Python
0.000001
@@ -0,0 +1,289 @@ +#!/usr/bin/env python%0A%0Afrom distutils.core import setup%0A%0Asetup(name=%22sbd%22,%0A version=%220.1%22,%0A description=%22Iridium Short Burst Data DirectIP handling%22,%0A author=%22Pete Gadomski%22,%0A author_email=%22pete.gadomski@gmail.com%22,%0A url=%22https://github.com/gadomski/sbd%22,%0A )%0A
b3c13747dcb72d751dbc2322d240499cb0fa2764
Add shebang line to setup.py
setup.py
setup.py
import os from setuptools import setup, find_packages from homeassistant.const import __version__ PACKAGE_NAME = 'homeassistant' HERE = os.path.abspath(os.path.dirname(__file__)) DOWNLOAD_URL = ('https://github.com/balloob/home-assistant/archive/' '{}.zip'.format(__version__)) PACKAGES = find_packages(exclude=['tests', 'tests.*']) REQUIRES = [ 'requests>=2,<3', 'pyyaml>=3.11,<4', 'pytz>=2015.4', 'pip>=7.0.0', 'vincenty==0.1.3', 'jinja2>=2.8' ] setup( name=PACKAGE_NAME, version=__version__, license='MIT License', url='https://home-assistant.io/', download_url=DOWNLOAD_URL, author='Paulus Schoutsen', author_email='paulus@paulusschoutsen.nl', description='Open-source home automation platform running on Python 3.', packages=PACKAGES, include_package_data=True, zip_safe=False, platforms='any', install_requires=REQUIRES, keywords=['home', 'automation'], entry_points={ 'console_scripts': [ 'hass = homeassistant.__main__:main' ] }, classifiers=[ 'Intended Audience :: End Users/Desktop', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 3.4', 'Topic :: Home Automation' ] )
Python
0.000001
@@ -1,12 +1,35 @@ +#!/usr/bin/env python3%0A import os%0Afr
40183d3ef5b49626e62e2bfd830ad54cfa138df9
Add setup.py
setup.py
setup.py
Python
0.000001
@@ -0,0 +1,785 @@ +import os%0Afrom setuptools import setup%0A%0Adef read(fname):%0A return open(os.path.join(os.path.dirname(__file__), fname)).read()%0A%0Asetup(%0A name = %22energenie%22,%0A version = %220.1.0%22,%0A author = %22Ben Nuttall%22,%0A author_email = %22ben@raspberrypi.org%22,%0A description = %22Python module to control the Energenie add-on board for the Raspberry Pi used for remotely turning power sockets on and off.%22,%0A license = %22BSD%22,%0A keywords = %5B%0A %22energenie%22,%0A %22raspberry pi%22,%0A %5D%0A url = %22https://github.com/bennuttall/energenie%22,%0A packages = %5B%0A %22energenie%22,%0A %5D,%0A long_description = read('README.md'),%0A classifiers = %5B%0A %22Development Status :: 4 - Beta%22,%0A %22Topic :: Home Automation%22,%0A %22License :: OSI Approved :: BSD License%22,%0A %5D,%0A)%0A
28742e2ca822f0e970bf01dcd81ab5ddbbb1aa12
add droid/android to browser mapping
ua2os.py
ua2os.py
"""ua to os - from a user agent return operating system, architecture, and browser""" import sys,splunk.Intersplunk import re os_mapping = ( ('Windows .. 5.1', 'Windows XP'), ('Windows .. 5.2', 'Windows XP'), ('Windows NT 6.0', 'Windows Vista'), ('Windows 6.0', 'Windows Server 2008'), ('Windows NT 6.1', 'Windows 7'), ('OS X 10.7', 'MAC OS X 10.7.x'), ('OS X 10.6', 'MAC OS X 10.6.x'), ('OS X 10.5', 'MAC OS X 10.5.x'), ('OS X 10.4', 'MAC OS X 10.4.x'), ('OS X 10.3', 'MAC OS X 10.3.x'), ('SunOS', 'Solaris'), ('droid', 'Android'), ('Windows', 'Windows - Other'), ('iPad', 'ipad'), ('iPod', 'ipod'), ('iPhone', 'iphone'), ('OS X', 'MAC OS X other'), ('Darwin', 'MAC OS X other'), ('Linux ', 'Linux'), ('winhttp', 'Windows - Other'), ('MSIE 4.0;', 'Windows - Other'), ('Microsoft', 'Windows - Other'), ('Win32', 'Windows - Other'), ('BlackBerry', 'BlackBerry'), ('urlgrabber/.* yum', 'Linux - redhat/fedora'), ('Skype for Macintosh', 'MAC OS X other'), ('Xbox Live Client', 'Xbox'), ) browser_mapping = ( ('MSIE 7.*Trident/4.0', 'Internet Explorer 8.0'), ('MSIE 9.0', 'Internet Explorer 9.0'), ('MSIE 8.0', 'Internet Explorer 8.0'), ('MSIE 7.0', 'Internet Explorer 7.0'), ('MSIE 6.0', 'Internet Explorer 6.0'), ('iPhone', 'Safari - mobile'), ('Safari/', 'Safari'), ('iTunes', 'iTunes'), ('Firefox/3', 'Firefox 3'), ('Firefox/2', 'Firefox 2'), ('MSIE 5.00', 'Internet Explorer 5.0'), ('MSIE', 'Internet Explorer - Other'), ('Chrome', 'Chrome'), ('AppleWebKit', 'Safari'), ('Google Update', 'Google Update'), ('Firefox/1', 'Firefox 1'), ('Opera', 'Opera'), ('urlgrabber/.* yum', 'yum'), ('BlackBerry', 'Blackberry'), ) arch_mapping = ( ('Windows .. 5.2', 'x64'), ('x64', 'x64'), ('i386', 'i386'), ('x86_64', 'x64'), ('PPC', 'PowerPC'), ('Power.{1,3}Macint', 'PowerPC'), ('droid', 'android'), ('iPad', 'ipad'), ('iPod', 'ipod'), ('iPhone', 'iphone'), ('Intel', 'Intel'), ('BlackBerry', 'BlackBerry'), ) os_mapping = [(re.compile(a, re.IGNORECASE),b) for (a,b) in os_mapping] browser_mapping = [(re.compile(a, re.IGNORECASE),b) for (a,b) in browser_mapping] arch_mapping = [(re.compile(a, re.IGNORECASE),b) for (a,b) in arch_mapping] def get_thing(line, mapping): for r, name in mapping: if r.search(line): return name return 'unknown' def get_ua_info(line): i = {} i['operating_system'] = get_thing(line, os_mapping) i['architecture'] = get_thing(line, arch_mapping) i['browser'] = get_thing(line, browser_mapping) return i try: results,dummyresults,settings = splunk.Intersplunk.getOrganizedResults() for r in results: if "_raw" not in r: continue info = get_ua_info(r['_raw']) r.update(info) except: import traceback stack = traceback.format_exc() results = splunk.Intersplunk.generateErrorResults("Error : Traceback: " + str(stack)) splunk.Intersplunk.outputResults( results )
Python
0
@@ -1637,24 +1637,64 @@ orer 6.0'),%0A + ('droid', 'Android'),%0A ('iPhone
02a982614b26dae21c18308c6fc94998805484fb
Add ball collector component
components/collector.py
components/collector.py
Python
0
@@ -0,0 +1,289 @@ +%22%22%22%0ARuns the wheels on the front of the robot to pick up balls.%0A%22%22%22%0A%0Aclass BallCollector(object):%0A def __init__(self, motor):%0A self.motor = motor%0A%0A def run(self, trigger):%0A if (trigger == True):%0A self.motor.set(1)%0A else:%0A self.motor.set(0)%0A
dc3ee951363116b235ec96bef34b06a661fc4795
Add a test that fails if using an old version of chromedriver
examples/fail_if_old_driver_test.py
examples/fail_if_old_driver_test.py
Python
0.00001
@@ -0,0 +1,1221 @@ +from seleniumbase import BaseCase%0A%0A%0Aclass ChromedriverTests(BaseCase):%0A%0A def test_fail_if_using_an_old_chromedriver(self):%0A if self.browser != %22chrome%22:%0A print(%22%5Cn This test is only for Chrome!%22)%0A print(%22 (Run with: '--browser=chrome')%22)%0A self.skip(%22This test is only for Chrome!%22)%0A chrome_version = self.get_chrome_version()%0A major_chrome_version = chrome_version.split('.')%5B0%5D%0A chromedriver_version = self.get_chromedriver_version()%0A major_chromedriver_version = chromedriver_version.split('.')%5B0%5D%0A install_sb = %22sbase install chromedriver %25s%22 %25 major_chrome_version%0A if (%0A int(major_chromedriver_version) %3C 73%0A and int(major_chrome_version) %3E= 73%0A ):%0A message = (%0A 'Your version of chromedriver: %22%25s%22%5Cn '%0A 'is too old for your version of Chrome: %22%25s%22%5Cn'%0A 'You should upgrade chromedriver '%0A %22to receive important bug fixes!%5Cn%22%0A 'Run this command to upgrade: %22%25s%22'%0A %25 (chromedriver_version, chrome_version, install_sb)%0A )%0A raise Exception(message) # chromedriver is out-of-date%0A
2b1cc5fb7465ec0d14d01d2c5cdec9f3bd222016
Update import_cluster.py
tendrl/node_agent/gluster_integration/flows/import_cluster.py
tendrl/node_agent/gluster_integration/flows/import_cluster.py
import json import uuid from tendrl.node_agent.flows.flow import Flow class ImportCluster(Flow): def run(self): node_list = self.parameters['Nodes[]'] if len(node_list) > 1: # This is the master node for this flow for node in node_list: if self.node_id != node: new_params = self.parameters.copy() new_params['Nodes[]'] = [node] # create same flow for each node in node list except $this job = { "cluster_id": self.parameters['cluster_id'], "node_id": node, "run": self.name, "status": "new", "parameters": new_params } self.etcd_client.write("/queue/%s" % uuid.uuid4(), json.dumps(job)) super(ImportCluster, self).run()
Python
0.000002
@@ -788,16 +788,60 @@ w_params +,%0A %22type%22: %22node%22 %0A
b426522a82d9ba9caa98731d91b985933466aaf9
Create setup.py
setup.py
setup.py
Python
0.000001
@@ -0,0 +1,1055 @@ +from setuptools import setup, Extension, find_packages%0Afrom glob import glob%0A%0Asetup(%0A name='expresso',%0A version='0.2',%0A description='A symbolic expression manipulation library.',%0A author='Lars Melchior',%0A%0A author_email='thelartians@gmail.com',%0A%0A url='https://github.com/TheLartians/Expresso',%0A #include_package_data=True,%0A%0A packages=find_packages(exclude=%5B'tests*'%5D),%0A%0A extras_require=%7B%0A 'pycas':%5B'numpy','mpmath'%5D%0A %7D,%0A%0A zip_safe=False,%0A%0A classifiers=%5B%0A 'Programming Language :: Python :: 2.7'%0A %5D,%0A%0A ext_modules=%5B%0A Extension('_expresso',%0A sources = glob('source/expresso/*.cpp') + %5B'libs/sha256/sha256.cpp','source/python.cpp'%5D,%0A include_dirs=%5B'libs'%5D, # assuming your project include files are there%0A libraries=%5B'boost_python'%5D, # those are the linked libs%0A library_dirs=%5B'/'%5D,%0A extra_compile_args=%5B'-g','-std=c++11','-Wno-unknown-pragmas','-O3'%5D # some other compile args%0A ),%0A %5D%0A)%0A
ff61d42f2cc60713437277c69521041c36ee425c
Create Startup.py
plugins/events/Startup.py
plugins/events/Startup.py
Python
0.000001
@@ -0,0 +1,8 @@ +print 1%0A
dfb5a1146b44979f98dc8aa236f52f0393eeabab
Add a basic setup.py
setup.py
setup.py
Python
0.000016
@@ -0,0 +1,1492 @@ +from distutils.core import setup%0Aimport os.path%0A%0A%0Adef is_package(path):%0A return (%0A os.path.isdir(path) and%0A os.path.isfile(os.path.join(path, '__init__.py'))%0A )%0A%0A%0Adef find_packages(path, base=%22%22):%0A %22%22%22 Find all packages in path %22%22%22%0A packages = %7B%7D%0A for item in os.listdir(path):%0A dir = os.path.join(path, item)%0A if is_package(dir):%0A if base:%0A module_name = %22%25(base)s.%25(item)s%22 %25 vars()%0A else:%0A module_name = item%0A packages%5Bmodule_name%5D = dir%0A packages.update(find_packages(dir, module_name))%0A return packages%0A%0Asetup(%0A name='tx_highered',%0A version='0.1.0alpha',%0A description='Django app for Texas higher education data',%0A author='Texas Tribune',%0A author_email='tech@texastribune.org',%0A url='http://github.com/texastribune/tx_highered/',%0A license='Apache Software License',%0A install_requires=%5B%0A %5D,%0A packages=find_packages('./tx_highered', 'tx_highered').keys(),%0A package_data=%7B%0A 'tx_highered': %5B%0A 'tx_highered/fixtures/*.json',%0A %5D%0A %7D,%0A classifiers=%5B%0A 'Development Status :: 4 - Beta',%0A 'Environment :: Web Environment',%0A 'Framework :: Django',%0A 'Intended Audience :: Developers',%0A 'License :: OSI Approved :: Apache Software License',%0A 'Operating System :: OS Independent',%0A 'Programming Language :: Python',%0A 'Topic :: Other/NonlistedTopic'%0A %5D,%0A)%0A
38d7a3671afa0e2c76682c8c409959288b547f82
Prepare for tagging v4.0b3
setup.py
setup.py
# -*- coding: utf-8 -*- from setuptools import setup, find_packages setup(name="pymdptoolbox", version="0", author="Steven A. W. Cordwell", author_email="steven.cordwell@uqconnect.edu.au", url="https://github.com/sawcordwell/pymdptoolbox", description="Markov Decision Process (MDP) Toolbox", long_description="The MDP toolbox provides classes and functions for " "the resolution of descrete-time Markov Decision Processes. The list of " "algorithms that have been implemented includes backwards induction, " "linear programming, policy iteration, q-learning and value iteration " "along with several variations.", download_url="https://pypi.python.org/pypi/pymdptoolbox", classifiers=[ "Development Status :: 2 - Pre-Alpha", "Environment :: Console", "Intended Audience :: Education", "Intended Audience :: Science/Research", "License :: OSI Approved :: BSD License", "Natural Language :: English", "Operating System :: OS Independent", "Programming Language :: Python", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.3", "Programming Language :: Python :: 3.4", "Topic :: Scientific/Engineering", "Topic :: Scientific/Engineering :: Mathematics", "Topic :: Software Development :: Libraries :: Python Modules"], platforms=["Any"], license="New BSD", packages=find_packages("src", exclude=["tests"]), package_dir={"": "src"}, install_requires=["numpy", "scipy"], extras_require={"LP": "cvxopt"})
Python
0
@@ -108,9 +108,14 @@ on=%22 -0 +4.0-b3 %22,%0A @@ -795,20 +795,15 @@ :: -2 - Pre-Alph +4 - Bet a%22,%0A @@ -1263,24 +1263,75 @@ thon :: 3%22,%0A + %22Programming Language :: Python :: 3.2%22,%0A %22P
12267f2a6ac574924ec991a8719d1d1cbf42f85c
Add installation script
setup.py
setup.py
Python
0
@@ -0,0 +1,511 @@ +from setuptools import setup%0A%0Asetup(name='Flask-Static', license='MIT', author='Rolando Urquiza',%0A author_email='rolurquiza@gmail.com',%0A description='Task executioner similar to gulp for Python',%0A packages=%5B'flask_static'%5D, platforms='any',%0A install_requires=%5B'werkzeug'%5D,%0A classifiers=%5B'Environment :: Web Environment',%0A 'Intended Audience :: Developers',%0A 'Operating System :: OS Independent',%0A 'Programming Language :: Python'%5D)%0A
470617e0fad9381cf5fadf64d1a9ba18dbf5e101
Fix copy ec scenario files failed.
setup.py
setup.py
#!/usr/bin/python # Copyright (c) 2013 SwiftStack, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. import os import sys from glob import glob from setuptools import setup, find_packages thispath = os.path.dirname(__file__) sys.path.insert(0, thispath) import ssbench with open(os.path.join(thispath, 'requirements.txt'), 'r') as f: requires = [x.strip() for x in f if x.strip()] with open(os.path.join(thispath, 'test-requirements.txt'), 'r') as f: test_requires = [x.strip() for x in f if x.strip()] with open(os.path.join(thispath, 'README.rst'), 'r') as f: readme = f.read() setup( name='ssbench', version=ssbench.version, description='SwiftStack Swift Benchmarking Suite', long_description=readme, license='Apache License (2.0)', author='SwiftStack, Inc.', author_email='darrell@swiftstack.com', url='http://github.com/SwiftStack/ssbench', packages=find_packages(exclude=['ssbench.tests']), test_suite='nose.collector', tests_require=test_requires, classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Intended Audience :: Information Technology', 'Intended Audience :: System Administrators', 'Intended Audience :: Telecommunications Industry', 'License :: OSI Approved :: Apache Software License', 'Natural Language :: English', 'Operating System :: MacOS :: MacOS X', 'Operating System :: POSIX :: Linux', 'Programming Language :: Python :: 2.7', 'Topic :: Software Development :: Testing :: Traffic Generation', 'Topic :: System :: Benchmark', 'Topic :: Utilities', ], keywords='openstack swift object storage benchmark', install_requires=requires, scripts=[ 'bin/ssbench-master', 'bin/ssbench-worker', ], data_files=[('share/ssbench/scenarios', glob('scenarios/*')), ('share/ssbench', ['CHANGELOG', 'AUTHORS', 'LICENSE'])], )
Python
0
@@ -2409,16 +2409,136 @@ narios/* +.scenario')),%0A ('share/ssbench/scenarios/ec_test_scenarios', glob('scenarios/ec_test_scenarios/*.scenario ')),%0A
30f704c3e767462fefb5086bbf6b5f190cec7c1b
Add fibonacci search in python
search/fibonacci_search/python/fibonacci_search.py
search/fibonacci_search/python/fibonacci_search.py
Python
0.000004
@@ -0,0 +1,1225 @@ +#Fibonacci search for sorted algorithm%0Adef fibSearch(arr,x):%0A%0A #fibonacci numbers initialization%0A fib2 = 0%0A fib1 = 1%0A fib = fib2 + fib1%0A%0A n = len(arr)%0A #find the smallest fibonacci greater than or equal to array length%0A while (fib %3C n):%0A fib2 = fib1%0A fib1 = fib%0A fib = fib2 + fib1%0A%0A #the leftout list for the array%0A offset = -1%0A%0A while (fib %3E 1):%0A #check if fib2 is a valid index%0A i = min(offset+fib2, n-1)%0A%0A #if x is greater than the value at index fib2,%0A #cut the array from offset to i%0A if (arr%5Bi%5D %3C x):%0A fib = fib1%0A fib1 = fib2%0A fib2 = fib - fib1%0A offset = i%0A%0A #if x is smaller than the value at index fib2,%0A #cut the array after i+1%0A elif (arr%5Bi%5D %3E x):%0A fib = fib2%0A fib1 = fib1 - fib2%0A fib2 = fib - fib1%0A%0A #return i when element is found%0A else :%0A return i%0A%0A #compare last element with x%0A if (fib1 and arr%5Boffset+1%5D == x):%0A return offset+1%0A%0A #when element not found return -1%0A return -1%0A%0Aarr = %5B10, 22, 35, 40, 45, 50, 80, 82, 85, 90, 100%5D%0Ax = 85%0Aprint (%22Found at index: %22, fibSearch(arr, x))%0A
215ab7e04495f829caf3583237fbe6c41ec8b40e
add logout API
xos/core/xoslib/methods/loginview.py
xos/core/xoslib/methods/loginview.py
from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework.reverse import reverse from rest_framework import serializers from rest_framework import generics from rest_framework.views import APIView from core.models import * from services.hpc.models import * from services.requestrouter.models import * from django.forms import widgets from django.core.exceptions import PermissionDenied from django.contrib.contenttypes.models import ContentType import json import socket import time import django.middleware.csrf from xos.exceptions import * class LoginView(APIView): method_kind = "list" method_name = "login" def do_login(self, request, username, password): if not username: raise XOSMissingField("No username specified") if not password: raise XOSMissingField("No password specified") u = User.objects.filter(email=username) if not u: raise XOSNotFound("User %s does not exist" % username) u=u[0] if not u.check_password(password): raise PermissionDenied("Incorrect password") auth = {"username": username, "password": password} request.session["auth"] = auth request.session.save() return Response({"xoscsrftoken": django.middleware.csrf.get_token(request), "xossessionid": request.session.session_key}) def get(self, request, format=None): username = request.GET.get("username", None) password = request.GET.get("password", None) return self.do_login(request, username, password) def post(self, request, format=None): username = request.DATA.get("username", None) password = request.DATA.get("password", None) return self.do_login(request, username, password)
Python
0.000001
@@ -588,16 +588,128 @@ import * +%0Afrom django.contrib.sessions.backends.db import SessionStore%0Afrom django.contrib.sessions.models import Session %0A%0Aclass @@ -1958,9 +1958,1023 @@ sword)%0A%0A +class LogoutView(APIView):%0A method_kind = %22list%22%0A method_name = %22logout%22%0A%0A def do_logout(self, request, sessionid):%0A if not sessionid:%0A raise XOSMissingField(%22No xossessionid specified%22)%0A%0A # Make sure the session exists. This prevents us from accidentally%0A # creating empty sessions with SessionStore()%0A session = Session.objects.filter(session_key=sessionid)%0A if not session:%0A # session doesn't exist%0A raise PermissionDenied(%22Session does not exist%22)%0A%0A session = SessionStore(session_key=sessionid)%0A if %22auth%22 in session:%0A del session%5B%22auth%22%5D%0A session.save()%0A%0A return Response(%22Logged Out%22)%0A%0A def get(self, request, format=None):%0A sessionid = request.GET.get(%22xossessionid%22, None)%0A return self.do_logout(request, sessionid)%0A%0A def post(self, request, format=None):%0A sessionid = request.DATA.get(%22xossessionid%22, None)%0A return self.do_logout(request, sessionid)%0A %0A
f872501586dfe05c5b96402a3d8ea5194a9ff6b3
add the pseudocode for the reservation random generator
reservation/generate.py
reservation/generate.py
Python
0.000001
@@ -0,0 +1,1022 @@ +%22%22%22%0AUsage:%0A generate SERVERS RESERVATIONS DURATION%0A%0AArguments:%0A SERVERS Number of servers for which we generate reservations%0A RESERVATIONS Number of reservations per server%0A DURATION The maximum duration of a reservation (determined randomly)%0A %0A%22%22%22%0A%0Adef generate(arguments):%0A%0A print arguments%0A%0A servers = arguments%5B%22SERVERS%22%5D%0A reservations = arguments%5B%22RESERVATIONS%22%5D%0A duration = arguments%5B%22DURATION%22%5D%0A%0A for s in range(0,servers):%0A t_start%5Bs%5D = %5B%5D%0A%09 t_start%5Bs%5D%5B0%5D = random (0,duration)%0A %09t_end%5Bs%5D%5B0%5D = t_stat%5Bs%5D%5B0%5D + random (0,duration)%0A for s in range(0,servers):%0A for n in range(1,reservations):%0A t_start%5Bs%5D%5Bn%5D = t_end_%5Br,n-1%5D + random (0,duration)%0A t_end%5B%5Bs%5Bn%5D = t_start%5Br%5D%5Bn%5D + random (0,duration)%0A%0A%09for s in range(0,servers):%0A for n in range(0,reservations):%0A print s, n, t_start%5Bs%5D%5Bn%5D, t_end%5Bs%5D%5Bn%5D%0A%0A %0Aif __name__ == '__main__':%0A print(sys.argv)%0A arguments = docopt(__doc__)%0A%0A generate(arguments)%0A
68a7b8b87caca9e80cc827854fa362e8a2911a2a
use Qt4 instead of Tkinter. This will use less code and provide a better appearance
setup.py
setup.py
Python
0
@@ -0,0 +1,1083 @@ +%22%22%22%0AThis is a setup.py script generated by py2applet%0A%0AUsage:%0A python setup.py py2app%0A%22%22%22%0A%0Afrom setuptools import setup%0A%0AAPP = %5B'app.py'%5D%0ADATA_FILES = %5B%5D%0AOPTIONS = %7B'argv_emulation': True, 'includes': %5B'sip', 'PyQt4',%0A 'PyQt4.QtCore', 'PyQt4.QtGui'%5D%7D%0A%0Asetup(%0A name='CatDV to XLSX',%0A version='2.0',%0A description='Convert CatDV .txt output to .xlsx',%0A date='3-Dec-2015',%0A url='https://github.com/edsoncudjoe/CatDVText2XlsxGui',%0A%0A author='Edson Cudjoe',%0A author_email='bashpythonstuff@hotmail.co.uk',%0A license='MIT',%0A%0A classifiers=%5B%0A 'Development Status :: 4 - Beta',%0A 'Intended Audience :: Developers',%0A 'Topic :: Software Development :: Media',%0A 'License :: OSI Approved :: MIT License',%0A 'Programming Language :: Python :: 2',%0A 'Programming Language :: Python :: 2.6',%0A 'Programming Language :: Python :: 2.7',%0A %5D,%0A%0A keywords='catdv text xlsx',%0A%0A app=APP,%0A data_files=DATA_FILES,%0A options=%7B'py2app': OPTIONS%7D,%0A setup_requires=%5B'py2app'%5D,%0A)%0A
643a36b0d935bb11ea3e9d661b8da4525700b878
Add metadata_agent.ini to config_path in setup.py.
setup.py
setup.py
# Copyright 2011 OpenStack, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import setuptools from quantum.openstack.common import setup from quantum.version import version_info as version requires = setup.parse_requirements() depend_links = setup.parse_dependency_links() Name = 'quantum' Url = "https://launchpad.net/quantum" Version = version.canonical_version_string(always=True) License = 'Apache License 2.0' Author = 'Netstack' AuthorEmail = 'netstack@lists.launchpad.net' Maintainer = '' Summary = 'Quantum (virtual network service)' ShortDescription = Summary Description = Summary EagerResources = [ 'quantum', ] ProjectScripts = [ 'bin/quantum-rootwrap', ] config_path = 'etc/quantum/' init_path = 'etc/init.d' rootwrap_path = 'etc/quantum/rootwrap.d' ovs_plugin_config_path = 'etc/quantum/plugins/openvswitch' cisco_plugin_config_path = 'etc/quantum/plugins/cisco' linuxbridge_plugin_config_path = 'etc/quantum/plugins/linuxbridge' nvp_plugin_config_path = 'etc/quantum/plugins/nicira' ryu_plugin_config_path = 'etc/quantum/plugins/ryu' meta_plugin_config_path = 'etc/quantum/plugins/metaplugin' nec_plugin_config_path = 'etc/quantum/plugins/nec' DataFiles = [ (config_path, ['etc/quantum.conf', 'etc/rootwrap.conf', 'etc/api-paste.ini', 'etc/policy.json', 'etc/dhcp_agent.ini', 'etc/l3_agent.ini']), (rootwrap_path, ['etc/quantum/rootwrap.d/dhcp.filters', 'etc/quantum/rootwrap.d/iptables-firewall.filters', 'etc/quantum/rootwrap.d/l3.filters', 'etc/quantum/rootwrap.d/linuxbridge-plugin.filters', 'etc/quantum/rootwrap.d/nec-plugin.filters', 'etc/quantum/rootwrap.d/openvswitch-plugin.filters', 'etc/quantum/rootwrap.d/ryu-plugin.filters']), (init_path, ['etc/init.d/quantum-server']), (ovs_plugin_config_path, ['etc/quantum/plugins/openvswitch/ovs_quantum_plugin.ini']), (cisco_plugin_config_path, ['etc/quantum/plugins/cisco/credentials.ini', 'etc/quantum/plugins/cisco/l2network_plugin.ini', 'etc/quantum/plugins/cisco/nexus.ini', 'etc/quantum/plugins/cisco/ucs.ini', 'etc/quantum/plugins/cisco/cisco_plugins.ini', 'etc/quantum/plugins/cisco/db_conn.ini']), (linuxbridge_plugin_config_path, ['etc/quantum/plugins/linuxbridge/linuxbridge_conf.ini']), (nvp_plugin_config_path, ['etc/quantum/plugins/nicira/nvp.ini']), (ryu_plugin_config_path, ['etc/quantum/plugins/ryu/ryu.ini']), (meta_plugin_config_path, ['etc/quantum/plugins/metaplugin/metaplugin.ini']), (nec_plugin_config_path, ['etc/quantum/plugins/nec/nec.ini']), ] setuptools.setup( name=Name, version=Version, url=Url, author=Author, author_email=AuthorEmail, description=ShortDescription, long_description=Description, license=License, classifiers=[ 'Environment :: OpenStack', 'Intended Audience :: System Administrators', 'Intended Audience :: Information Technology', 'License :: OSI Approved :: Apache Software License', 'Operating System :: POSIX :: Linux', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', ], scripts=ProjectScripts, install_requires=requires, dependency_links=depend_links, include_package_data=False, setup_requires=['setuptools_git>=0.4'], packages=setuptools.find_packages('.'), cmdclass=setup.get_cmdclass(), data_files=DataFiles, eager_resources=EagerResources, entry_points={ 'console_scripts': [ 'quantum-dhcp-agent = quantum.agent.dhcp_agent:main', 'quantum-dhcp-agent-dnsmasq-lease-update =' 'quantum.agent.linux.dhcp:Dnsmasq.lease_update', 'quantum-netns-cleanup = quantum.agent.netns_cleanup_util:main', 'quantum-l3-agent = quantum.agent.l3_agent:main', 'quantum-linuxbridge-agent =' 'quantum.plugins.linuxbridge.agent.linuxbridge_quantum_agent:main', 'quantum-metadata-agent =' 'quantum.agent.metadata.agent:main', 'quantum-ns-metadata-proxy =' 'quantum.agent.metadata.namespace_proxy:main', 'quantum-openvswitch-agent =' 'quantum.plugins.openvswitch.agent.ovs_quantum_agent:main', 'quantum-ryu-agent = ' 'quantum.plugins.ryu.agent.ryu_quantum_agent:main', 'quantum-nec-agent = ' 'quantum.plugins.nec.agent.nec_quantum_agent:main', 'quantum-server = quantum.server:main', 'quantum-debug = quantum.debug.shell:main', ] }, )
Python
0.000052
@@ -1869,24 +1869,59 @@ 3_agent.ini' +,%0A 'etc/metadata_agent.ini' %5D),%0A (roo
f1907672f276ee7cf19dd9f14824e56361c8128d
Add tests
tests/lda_test.py
tests/lda_test.py
Python
0.000001
@@ -0,0 +1,358 @@ +# -*- coding:utf-8 -*-%0Aimport unittest%0Aimport nose%0Aimport dmr%0A%0Aclass LDATestCase(unittest.TestCase):%0A def test___init__(self):%0A '''%0A __init__ test%0A '''%0A corpus = dmr.Corpus.read(%22./doc.txt%22)%0A voca = dmr.Vocabulary()%0A docs = voca.read_corpus(corpus)%0A%0A%0Aif __name__ == '__main__':%0A nose.main(argv=%5B'nose', '-v'%5D)%0A
4ee28dbcdf631e3f328dcda5f901b0d4bf20ef3b
Create setup.py
setup.py
setup.py
Python
0.000001
@@ -0,0 +1,588 @@ +from distutils.core import setup%0Afrom Cython.Distutils import Extension%0Afrom Cython.Distutils import build_ext%0Aimport os%0Aimport numpy%0A%0Aext_modules = %5B%5D%0A%0Aext_modules.append(Extension(%22terminator%22,%0A %5B%22terminator.pyx%22%5D,%0A libraries=%5B%22m%22%5D,%0A extra_compile_args=%5B'-fopenmp'%5D,%0A extra_link_args=%5B'-fopenmp'%5D,%0A )%0A )%0A%0Asetup(include_dirs=%5Bnumpy.get_include()%5D,%0A cmdclass=%7B'build_ext': build_ext%7D,%0A ext_modules=ext_modules, %0A )%0A
10a2fb7d52ce9affcc6157eb7731191b940a7480
Write some tests
tests/test_for.py
tests/test_for.py
Python
0.000066
@@ -0,0 +1,931 @@ +import pytest%0A%0Afrom pyegs.compiler import compile as compile_%0A%0A%0A@pytest.mark.skip('Not implemented yet')%0Adef test_for():%0A assert (compile_('items = %5B11, 22, 33%5D%5Cnfor item in items: x = item') ==%0A 'p1z 11 p2z 22 p3z 33 p4z 1 '%0A 'p5z p4z+0 p5z p%5E5z p6z p5z '%0A 'p5z p4z+1 p5z p%5E5z p6z p5z '%0A 'p5z p4z+2 p5z p%5E5z p6z p5z')%0A%0A assert (compile_('for x in range(5): y = x') ==%0A 'p1z 0 p2z p1z '%0A 'p1z 1 p2z p1z '%0A 'p1z 2 p2z p1z '%0A 'p1z 3 p2z p1z '%0A 'p1z 4 p2z p1z')%0A%0A assert (compile_('items = %5B11, 22, 33%5D%5Cn'%0A 'for i, item in enumerate(items):%5Cn'%0A ' x = i'%0A ' y = item') ==%0A 'p1z 11 p2z 22 p3z 33 p4z 1 '%0A 'p5z 0 p6z p4z+p5z p7z p5z p8z p6z '%0A 'p5z 1 p6z p4z+p5z p7z p5z p8z p6z '%0A 'p5z 2 p6z p4z+p5z p7z p5z p8z p6z')%0A
3b38f7638d1d2e3903cc388cfb3103b1e9c11bc2
Add setup.py
setup.py
setup.py
Python
0.000001
@@ -0,0 +1,535 @@ +from setuptools import setup, find_packages%0A%0Asetup(name='whaler',%0A version='0.0.1',%0A author = %22Tristan R. Brown%22,%0A author_email = %22brown.tristan.r@gmail.com%22,%0A description = (%22Analytical package for computational chemistry software, %22%0A %22ORCA.%22),%0A url = 'https://github.com/tristanbrown/whaler',%0A license = %22MIT%22,%0A packages = find_packages(),%0A install_requires = %5B''%5D,%0A entry_points = %7B%0A 'console_scripts': %5B%0A 'whaler = my_project.__main__:main'%0A %5D%0A %7D,%0A )
54eca489024d3d8f354a44d161797edb8e916600
Add tests - now very simple and primitive
tests/test_saw.py
tests/test_saw.py
Python
0
@@ -0,0 +1,624 @@ +import unittest%0Afrom saw.saw import Saw%0A%0Aclass Test_Saw(unittest.TestCase):%0A%0A def setUp(self):%0A text = %22Starting right this second, it's way easier to merge Pull Requests! %5C%0A We usually merge them from the comfortable glow of our computers, but with the%5C%0A new mobile site we're comfortable merging smaller Pull Requests while sitting%5C%0A on the hyperloop (or while on the bus, I guess).%22%0A self.obj = Saw().load(text)%0A%0A def test_saw(self):%0A self.assertEqual(self.obj.paragraphs%5B0%5D.sentences%5B0%5D.blocks, self.obj.blocks)%0A%0A%0Aif __name__ == %22__main__%22:%0A unittest.main()
986fad3382aadfe636dd5b2a8b9a69ffcdd5bc20
increment version for release 1.14.1
setup.py
setup.py
# coding: utf-8 from setuptools import setup, find_packages try: from distutils.command.build_py import build_py_2to3 as build_py except ImportError: from distutils.command.build_py import build_py import os with open('README.rst') as file: long_description = file.read() MAJOR = 1 MINOR = 14 MICRO = 0 ISRELEASED = False VERSION = '%d.%d.%d' % (MAJOR, MINOR, MICRO) # BEFORE importing distutils, remove MANIFEST. distutils doesn't properly # update it when the contents of directories change. if os.path.exists('MANIFEST'): os.remove('MANIFEST') def _get_requirements_from_files(groups_files): groups_reqlist = {} for k,v in groups_files.items(): with open(v, 'r') as f: pkg_list = f.read().splitlines() groups_reqlist[k] = pkg_list return groups_reqlist def setup_package(): # get all file endings and copy whole file names without a file suffix # assumes nested directories are only down one level example_data_files = set() for i in os.listdir("pysal/examples"): if i.endswith(('py', 'pyc')): continue if not os.path.isdir("pysal/examples/" + i): if "." in i: glob_name = "examples/*." + i.split(".")[-1] else: glob_name = "examples/" + i else: glob_name = "examples/" + i + "/*" example_data_files.add(glob_name) _groups_files = { 'base': 'requirements.txt', 'plus': 'requirements_plus.txt', 'dev': 'requirements_dev.txt' } reqs = _get_requirements_from_files(_groups_files) install_reqs = reqs.pop('base') extras_reqs = reqs setup( name='PySAL', version=VERSION, description="A library of spatial analysis functions.", long_description=long_description, maintainer="PySAL Developers", maintainer_email='pysal-dev@googlegroups.com', url='http://pysal.org', download_url='https://pypi.python.org/pypi/PySAL', license='BSD', py_modules=['pysal'], test_suite='nose.collector', tests_require=['nose'], keywords='spatial statistics', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Science/Research', 'Intended Audience :: Developers', 'Intended Audience :: Education', 'Topic :: Scientific/Engineering', 'Topic :: Scientific/Engineering :: GIS', 'License :: OSI Approved :: BSD License', 'Programming Language :: Python', 'Programming Language :: Python :: 2.5', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.4' ], packages=find_packages(exclude=[".meta", "*.meta.*", "meta.*", "meta"]), package_data={'pysal': list(example_data_files)}, install_requires=install_reqs, extras_require=extras_reqs, cmdclass={'build_py': build_py} ) if __name__ == '__main__': setup_package()
Python
0.000001
@@ -315,9 +315,9 @@ O = -0 +1 %0AISR
9ae54aed54b308bab98031f9a855b1457df0378d
migrate mpl.cbook.iterable to numpy.iterable
metpy/cbook.py
metpy/cbook.py
# Copyright (c) 2008,2015,2018 MetPy Developers. # Distributed under the terms of the BSD 3-Clause License. # SPDX-License-Identifier: BSD-3-Clause """Collection of generally useful utility code from the cookbook.""" import os from matplotlib.cbook import iterable import numpy as np import pooch from . import __version__ try: string_type = basestring except NameError: string_type = str # TODO: This can go away when we remove Python 2 def is_string_like(s): """Check if an object is a string.""" return isinstance(s, string_type) POOCH = pooch.create( path=pooch.os_cache('metpy'), base_url='https://github.com/Unidata/MetPy/raw/{version}/staticdata/', version='v' + __version__, version_dev='master', env='TEST_DATA_DIR') # Check if we're running from a git clone and if so, bash the path attribute with the path # to git's local data store (un-versioned) # Look for the staticdata directory (i.e. this is a git checkout) if os.path.exists(os.path.join(os.path.dirname(__file__), '..', 'staticdata')): POOCH.path = os.path.join(os.path.dirname(__file__), '..', 'staticdata') POOCH.load_registry(os.path.join(os.path.dirname(__file__), 'static-data-manifest.txt')) def get_test_data(fname, as_file_obj=True): """Access a file from MetPy's collection of test data.""" path = POOCH.fetch(fname) # If we want a file object, open it, trying to guess whether this should be binary mode # or not if as_file_obj: return open(path, 'rb') return path class Registry(object): """Provide a generic function registry. This provides a class to instantiate, which then has a `register` method that can be used as a decorator on functions to register them under a particular name. """ def __init__(self): """Initialize an empty registry.""" self._registry = {} def register(self, name): """Register a callable with the registry under a particular name. Parameters ---------- name : str The name under which to register a function Returns ------- dec : callable A decorator that takes a function and will register it under the name. """ def dec(func): self._registry[name] = func return func return dec def __getitem__(self, name): """Return any callable registered under name.""" return self._registry[name] def broadcast_indices(x, minv, ndim, axis): """Calculate index values to properly broadcast index array within data array. See usage in interp. """ ret = [] for dim in range(ndim): if dim == axis: ret.append(minv) else: broadcast_slice = [np.newaxis] * ndim broadcast_slice[dim] = slice(None) dim_inds = np.arange(x.shape[dim]) ret.append(dim_inds[tuple(broadcast_slice)]) return tuple(ret) __all__ = ('Registry', 'broadcast_indices', 'get_test_data', 'is_string_like', 'iterable')
Python
0.000005
@@ -226,64 +226,53 @@ os%0A%0A -from matplotlib.cbook import iterable%0Aimport numpy as np +import numpy as np%0Afrom numpy import iterable %0Aimp
1bd21c7b35a100e0f72f03bd9e0d783dc136c41e
Check for multiple outcome codes occurring today
cla_backend/apps/cla_butler/management/commands/monitor_multiple_outcome_codes.py
cla_backend/apps/cla_butler/management/commands/monitor_multiple_outcome_codes.py
Python
0
@@ -0,0 +1,2594 @@ +# coding=utf-8%0Aimport logging%0Afrom django.core.management.base import BaseCommand%0Afrom django.db.models import Count, Max, Min%0Afrom django.utils.timezone import now%0Afrom cla_butler.stack import is_first_instance, InstanceNotInAsgException, StackException%0Afrom cla_eventlog.models import Log%0A%0Alogger = logging.getLogger(__name__)%0A%0A%0Aclass Command(BaseCommand):%0A help = 'LGA-294 specific monitoring command. Alert when multiple outcome codes ' %5C%0A 'that should only occur once are found for today (since 00:00)'%0A%0A def handle(self, *args, **options):%0A if self.should_run_housekeeping(**options):%0A self.check_for_multiple_outcome_codes()%0A else:%0A logger.debug('LGA-294 Skip check_for_multiple_outcome_codes: running on secondary instance')%0A%0A @staticmethod%0A def check_for_multiple_outcome_codes():%0A # Outcome codes defined to appear only once on a case:%0A # https://docs.google.com/spreadsheets/d/1hN64bA_H2a_0eC_5-k-0IY2-RKbCor2VGflp1ykQGa0/%0A start_of_today = now().replace(hour=0, minute=0, second=0, microsecond=0)%0A once_only_codes = %5B'PCB', 'COPE', 'DUPL', 'MRNB', 'NCOE', 'DESP', 'DECL', 'MRCC', 'NRES', 'CPTA',%0A 'COSPF', 'SPFM', 'SPFN', 'DREFER', 'COI', 'CLSP', 'MANALC', 'MANREF', 'MIS',%0A 'MIS-MEANS', 'MIS-OOS', 'REF-EXT', 'REF-INT', 'REFSP', 'REOPEN', 'SPOR', 'WROF'%5D%0A%0A once_only_events_today = Log.objects.filter(created__gte=start_of_today, code__in=once_only_codes)%0A once_only_codes_today = once_only_events_today.only('case__reference', 'code', 'created')%0A once_only_codes_today_counts = once_only_codes_today.values('case__reference', 'code') %5C%0A .annotate(total=Count('code'), earliest=Min('created'), latest=Max('created'))%0A multiple_codes_today = once_only_codes_today_counts.filter(total__gt=1).order_by('-total')%0A%0A if multiple_codes_today.exists():%0A for i in multiple_codes_today:%0A logger.warning('LGA-294 investigation. Multiple outcome codes today for case: %7B%7D'.format(i))%0A else:%0A logger.info('LGA-294 No multiple outcome codes found for today')%0A%0A @staticmethod%0A def should_run_housekeeping(**options):%0A if options.get('force', False):%0A return True%0A try:%0A return is_first_instance()%0A except InstanceNotInAsgException:%0A logger.info('EC2 instance not in an ASG')%0A return True%0A except StackException:%0A logger.info('Not running on EC2 instance')%0A return True%0A
f45b31b9d242ec85f66508f19b7b3561fb5ee165
Set development status: Production/Stable
setup.py
setup.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import sys import codecs extra = {} tests_require = ["nose", "nose-cover3"] if sys.version_info >= (3, 0): extra.update(use_2to3=True) elif sys.version_info <= (2, 6): tests_require.append("unittest2") elif sys.version_info <= (2, 5): tests_require.append("simplejson") if sys.version_info < (2, 4): raise Exception("Kombu requires Python 2.4 or higher.") try: from setuptools import setup, Extension, Feature, find_packages except ImportError: from distutils.core import setup, Extension, find_packages Feature = None from distutils.command.install_data import install_data from distutils.command.install import INSTALL_SCHEMES os.environ["KOMBU_NO_EVAL"] = "yes" import kombu os.environ.pop("KOMBU_NO_EVAL", None) sys.modules.pop("kombu", None) packages, data_files = [], [] root_dir = os.path.dirname(__file__) if root_dir != '': os.chdir(root_dir) src_dir = "kombu" def osx_install_data(install_data): def finalize_options(self): self.set_undefined_options("install", ("install_lib", "install_dir")) install_data.finalize_options(self) def fullsplit(path, result=None): if result is None: result = [] head, tail = os.path.split(path) if head == '': return [tail] + result if head == path: return result return fullsplit(head, [tail] + result) for scheme in list(INSTALL_SCHEMES.values()): scheme['data'] = scheme['purelib'] for dirpath, dirnames, filenames in os.walk(src_dir): # Ignore dirnames that start with '.' for i, dirname in enumerate(dirnames): if dirname.startswith("."): del dirnames[i] for filename in filenames: if filename.endswith(".py"): packages.append('.'.join(fullsplit(dirpath))) else: data_files.append([dirpath, [os.path.join(dirpath, f) for f in filenames]]) if os.path.exists("README.rst"): long_description = codecs.open('README.rst', "r", "utf-8").read() else: long_description = "See http://pypi.python.org/pypi/kombu" setup( name='kombu', version=kombu.__version__, description=kombu.__doc__, author=kombu.__author__, author_email=kombu.__contact__, url=kombu.__homepage__, platforms=["any"], packages=packages, data_files=data_files, zip_safe=False, test_suite="nose.collector", install_requires=[ 'anyjson>=0.3.1', 'amqplib>=0.6', ], tests_require=tests_require, classifiers=[ "Development Status :: 4 - Beta", "Framework :: Django", "Operating System :: OS Independent", "Programming Language :: Python", "Programming Language :: Python :: 3", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 2.6", "Programming Language :: Python :: 2.5", "Programming Language :: Python :: 2.4", "Programming Language :: Python :: 2", "License :: OSI Approved :: BSD License", "Intended Audience :: Developers", "Topic :: Communications", "Topic :: System :: Distributed Computing", "Topic :: Software Development :: Libraries :: Python Modules", ], long_description=long_description, **extra )
Python
0
@@ -2585,16 +2585,29 @@ :: -4 - Beta +5 - Production/Stable %22,%0A @@ -3194,16 +3194,57 @@ uting%22,%0A + %22Topic :: System :: Networking%22,%0A
81418934093eb1eb20862e7fb9f97d6bfbc3cf10
add setup.py
setup.py
setup.py
Python
0.000001
@@ -0,0 +1,1550 @@ +#!/usr/bin/python%0A%22%22%22Multiple dispatcher on arguments values.%22%22%22%0Afrom setuptools import setup%0A%0Along_description = %22%22%22%0A# dispatk%0A%0A## Description%0A%0AThis function is inspired by singledispatch of Python 3.4+ (PEP 443),%0Abut the dispatch happens on the key extracted fro the arguments values.%0A%0A%60%60%60%0Afrom dispatk import dispatk%0A%0A@dispatk(lambda n: int(n))%0Adef fib(n):%0A return fib(n-1) + fib(n-2)%0A@fib.register(0)%0Adef _(n):%0A return 0%0A@fib.register(1, 2)%0Adef _(n):%0A return 1%0A@fib.register(41)%0Adef _(n):%0A return 165580141%0A%60%60%60%0A%0A*register* accepts one or more keys, so%0A%0A%60%60%60%0A@fib.register(1, 2)%0Adef _(n):%0A return 1%0A%60%60%60%0A%0Ais equivalent to%0A%0A%60%60%60%0A@fib.register(1)%0A@fib.register(2)%0Adef _(n):%0A return 1%0A%60%60%60%0A%22%22%22%0A%0Asetup(%0A name='dispatk',%0A version='0.1',%0A author='hephaestus',%0A description=__doc__,%0A long_description=long_description,%0A url='https://github.com/hephs/dispatk',%0A keywords='multiple dispatch generic functions genericfunctions decorator',%0A platforms=('any',),%0A license='MIT',%0A py_modules=('dispatk',),%0A zip_safe=True,%0A install_requires=(),%0A classifiers=(%0A 'Intended Audience :: Developers',%0A 'License :: OSI Approved :: MIT License',%0A 'Natural Language :: English',%0A 'Operating System :: OS Independent',%0A 'Programming Language :: Python',%0A 'Programming Language :: Python :: 2',%0A 'Programming Language :: Python :: 3',%0A 'Topic :: Software Development :: Libraries',%0A 'Topic :: Software Development :: Libraries :: Python Modules',%0A ),%0A)%0A
af76038a7cbaa076b3fe0b57145a2fc72bc50b7b
Add basic setup script
setup.py
setup.py
Python
0.000001
@@ -0,0 +1,382 @@ +#!/usr/bin/env python%0A%0Afrom distutils.core import setup%0A%0Asetup(name='Numspell',%0A version='0.9',%0A description='A Python module for spelling numbers',%0A author='Alexei Sholik',%0A author_email='alcosholik@gmail.com',%0A url='https://github.com/alco/numspell',%0A license=%22MIT%22,%0A packages=%5B'numspell'%5D,%0A data_files=%5B('/usr/bin', %5B'spellnum'%5D)%5D,%0A )%0A
b05ede554c403bb3d03dbe65b02baa2a879f3310
Add pretty-printers for qi::Buffer
tools/printers.py
tools/printers.py
Python
0.00001
@@ -0,0 +1,704 @@ +%22%22%22Pretty printers for libqi.%0AAdd python execfile(%22/path/to/this/file%22) in your ~/.gdbinit or /etc/gdb/gdbinit%0AYour gdb need to be compile with python and version %3E 7.0%0A%22%22%22%0A%0Aimport gdb%0Aimport gdb.types%0A%0Aclass QiBufferPrinter:%0A def __init__(self, val):%0A self.val = val%0A%0A def to_string(self):%0A buf = self.val%5B'_p'%5D%5B'px'%5D.dereference()%0A return %22qi::Buffer of length %25i, capacity %25i, sub-buffers %25s%22 %25 (buf%5B%22used%22%5D, buf%5B%22available%22%5D, buf%5B'_subBuffers'%5D)%0A%0Adef lookup_type(val):%0A type = str(gdb.types.get_basic_type(val.type))%0A if type == 'qi::Buffer':%0A return QiBufferPrinter(val)%0A return None%0A%0Aif __name__ == %22__main__%22:%0A gdb.pretty_printers.append(lookup_type)%0A
2cc14dae641f41f76a8652f3431651c1300868f9
Update forward compatibility horizon to 2021-05-12
tensorflow/python/compat/compat.py
tensorflow/python/compat/compat.py
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Utilities for API compatibility between TensorFlow release versions. See [Version Compatibility](https://tensorflow.org/guide/version_compat#backward_forward) """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import datetime import os from tensorflow.python.platform import tf_logging as logging from tensorflow.python.util import tf_contextlib from tensorflow.python.util.tf_export import tf_export # This value changes every day with an automatic CL. It can be modified in code # via `forward_compatibility_horizon()` or with the environment variable # TF_FORWARD_COMPATIBILITY_DELTA_DAYS, which is added to the compatibility date. _FORWARD_COMPATIBILITY_HORIZON = datetime.date(2021, 5, 11) _FORWARD_COMPATIBILITY_DELTA_DAYS_VAR_NAME = "TF_FORWARD_COMPATIBILITY_DELTA_DAYS" _FORWARD_COMPATIBILITY_DATE_NUMBER = None def _date_to_date_number(year, month, day): return (year << 9) | (month << 5) | day def _update_forward_compatibility_date_number(date_to_override=None): """Update the base date to compare in forward_compatible function.""" global _FORWARD_COMPATIBILITY_DATE_NUMBER if date_to_override: date = date_to_override else: date = _FORWARD_COMPATIBILITY_HORIZON delta_days = os.getenv(_FORWARD_COMPATIBILITY_DELTA_DAYS_VAR_NAME) if delta_days: date += datetime.timedelta(days=int(delta_days)) if date < _FORWARD_COMPATIBILITY_HORIZON: logging.warning("Trying to set the forward compatibility date to the past" " date %s. This will be ignored by TensorFlow." % (date)) return _FORWARD_COMPATIBILITY_DATE_NUMBER = _date_to_date_number( date.year, date.month, date.day) _update_forward_compatibility_date_number() @tf_export("compat.forward_compatible") def forward_compatible(year, month, day): """Return true if the forward compatibility window has expired. See [Version compatibility](https://tensorflow.org/guide/version_compat#backward_forward). Forward-compatibility refers to scenarios where the producer of a TensorFlow model (a GraphDef or SavedModel) is compiled against a version of the TensorFlow library newer than what the consumer was compiled against. The "producer" is typically a Python program that constructs and trains a model while the "consumer" is typically another program that loads and serves the model. TensorFlow has been supporting a 3 week forward-compatibility window for programs compiled from source at HEAD. For example, consider the case where a new operation `MyNewAwesomeAdd` is created with the intent of replacing the implementation of an existing Python wrapper - `tf.add`. The Python wrapper implementation should change from something like: ```python def add(inputs, name=None): return gen_math_ops.add(inputs, name) ``` to: ```python from tensorflow.python.compat import compat def add(inputs, name=None): if compat.forward_compatible(year, month, day): # Can use the awesome new implementation. return gen_math_ops.my_new_awesome_add(inputs, name) # To maintain forward compatibility, use the old implementation. return gen_math_ops.add(inputs, name) ``` Where `year`, `month`, and `day` specify the date beyond which binaries that consume a model are expected to have been updated to include the new operations. This date is typically at least 3 weeks beyond the date the code that adds the new operation is committed. Args: year: A year (e.g., 2018). Must be an `int`. month: A month (1 <= month <= 12) in year. Must be an `int`. day: A day (1 <= day <= 31, or 30, or 29, or 28) in month. Must be an `int`. Returns: True if the caller can expect that serialized TensorFlow graphs produced can be consumed by programs that are compiled with the TensorFlow library source code after (year, month, day). """ return _FORWARD_COMPATIBILITY_DATE_NUMBER > _date_to_date_number( year, month, day) @tf_export("compat.forward_compatibility_horizon") @tf_contextlib.contextmanager def forward_compatibility_horizon(year, month, day): """Context manager for testing forward compatibility of generated graphs. See [Version compatibility](https://tensorflow.org/guide/version_compat#backward_forward). To ensure forward compatibility of generated graphs (see `forward_compatible`) with older binaries, new features can be gated with: ```python if compat.forward_compatible(year=2018, month=08, date=01): generate_graph_with_new_features() else: generate_graph_so_older_binaries_can_consume_it() ``` However, when adding new features, one may want to unittest it before the forward compatibility window expires. This context manager enables such tests. For example: ```python from tensorflow.python.compat import compat def testMyNewFeature(self): with compat.forward_compatibility_horizon(2018, 08, 02): # Test that generate_graph_with_new_features() has an effect ``` Args: year: A year (e.g., 2018). Must be an `int`. month: A month (1 <= month <= 12) in year. Must be an `int`. day: A day (1 <= day <= 31, or 30, or 29, or 28) in month. Must be an `int`. Yields: Nothing. """ try: _update_forward_compatibility_date_number(datetime.date(year, month, day)) yield finally: _update_forward_compatibility_date_number()
Python
0
@@ -1445,17 +1445,17 @@ 21, 5, 1 -1 +2 )%0A_FORWA
c21bca4fb2f83e3f68806920a928372c3566a04b
Update forward compatibility horizon to 2022-02-15
tensorflow/python/compat/compat.py
tensorflow/python/compat/compat.py
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Utilities for API compatibility between TensorFlow release versions. See [Version Compatibility](https://tensorflow.org/guide/version_compat#backward_forward) """ import datetime import os from tensorflow.python.platform import tf_logging as logging from tensorflow.python.util import tf_contextlib from tensorflow.python.util.tf_export import tf_export # This value changes every day with an automatic CL. It can be modified in code # via `forward_compatibility_horizon()` or with the environment variable # TF_FORWARD_COMPATIBILITY_DELTA_DAYS, which is added to the compatibility date. _FORWARD_COMPATIBILITY_HORIZON = datetime.date(2022, 2, 14) _FORWARD_COMPATIBILITY_DELTA_DAYS_VAR_NAME = "TF_FORWARD_COMPATIBILITY_DELTA_DAYS" _FORWARD_COMPATIBILITY_DATE_NUMBER = None def _date_to_date_number(year, month, day): return (year << 9) | (month << 5) | day def _update_forward_compatibility_date_number(date_to_override=None): """Update the base date to compare in forward_compatible function.""" global _FORWARD_COMPATIBILITY_DATE_NUMBER if date_to_override: date = date_to_override else: date = _FORWARD_COMPATIBILITY_HORIZON delta_days = os.getenv(_FORWARD_COMPATIBILITY_DELTA_DAYS_VAR_NAME) if delta_days: date += datetime.timedelta(days=int(delta_days)) if date < _FORWARD_COMPATIBILITY_HORIZON: logging.warning("Trying to set the forward compatibility date to the past" " date %s. This will be ignored by TensorFlow." % (date)) return _FORWARD_COMPATIBILITY_DATE_NUMBER = _date_to_date_number( date.year, date.month, date.day) _update_forward_compatibility_date_number() @tf_export("compat.forward_compatible") def forward_compatible(year, month, day): """Return true if the forward compatibility window has expired. See [Version compatibility](https://tensorflow.org/guide/version_compat#backward_forward). Forward-compatibility refers to scenarios where the producer of a TensorFlow model (a GraphDef or SavedModel) is compiled against a version of the TensorFlow library newer than what the consumer was compiled against. The "producer" is typically a Python program that constructs and trains a model while the "consumer" is typically another program that loads and serves the model. TensorFlow has been supporting a 3 week forward-compatibility window for programs compiled from source at HEAD. For example, consider the case where a new operation `MyNewAwesomeAdd` is created with the intent of replacing the implementation of an existing Python wrapper - `tf.add`. The Python wrapper implementation should change from something like: ```python def add(inputs, name=None): return gen_math_ops.add(inputs, name) ``` to: ```python from tensorflow.python.compat import compat def add(inputs, name=None): if compat.forward_compatible(year, month, day): # Can use the awesome new implementation. return gen_math_ops.my_new_awesome_add(inputs, name) # To maintain forward compatibility, use the old implementation. return gen_math_ops.add(inputs, name) ``` Where `year`, `month`, and `day` specify the date beyond which binaries that consume a model are expected to have been updated to include the new operations. This date is typically at least 3 weeks beyond the date the code that adds the new operation is committed. Args: year: A year (e.g., 2018). Must be an `int`. month: A month (1 <= month <= 12) in year. Must be an `int`. day: A day (1 <= day <= 31, or 30, or 29, or 28) in month. Must be an `int`. Returns: True if the caller can expect that serialized TensorFlow graphs produced can be consumed by programs that are compiled with the TensorFlow library source code after (year, month, day). """ return _FORWARD_COMPATIBILITY_DATE_NUMBER > _date_to_date_number( year, month, day) @tf_export("compat.forward_compatibility_horizon") @tf_contextlib.contextmanager def forward_compatibility_horizon(year, month, day): """Context manager for testing forward compatibility of generated graphs. See [Version compatibility](https://tensorflow.org/guide/version_compat#backward_forward). To ensure forward compatibility of generated graphs (see `forward_compatible`) with older binaries, new features can be gated with: ```python if compat.forward_compatible(year=2018, month=08, date=01): generate_graph_with_new_features() else: generate_graph_so_older_binaries_can_consume_it() ``` However, when adding new features, one may want to unittest it before the forward compatibility window expires. This context manager enables such tests. For example: ```python from tensorflow.python.compat import compat def testMyNewFeature(self): with compat.forward_compatibility_horizon(2018, 08, 02): # Test that generate_graph_with_new_features() has an effect ``` Args: year: A year (e.g., 2018). Must be an `int`. month: A month (1 <= month <= 12) in year. Must be an `int`. day: A day (1 <= day <= 31, or 30, or 29, or 28) in month. Must be an `int`. Yields: Nothing. """ try: _update_forward_compatibility_date_number(datetime.date(year, month, day)) yield finally: _update_forward_compatibility_date_number()
Python
0
@@ -1339,9 +1339,9 @@ 2, 1 -4 +5 )%0A_F
842a1062837a9c847f8bf89e298061eca9de4efd
Update forward compatibility horizon to 2021-04-14
tensorflow/python/compat/compat.py
tensorflow/python/compat/compat.py
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Utilities for API compatibility between TensorFlow release versions. See [Version Compatibility](https://tensorflow.org/guide/version_compat#backward_forward) """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import datetime import os from tensorflow.python.platform import tf_logging as logging from tensorflow.python.util import tf_contextlib from tensorflow.python.util.tf_export import tf_export # This value changes every day with an automatic CL. It can be modified in code # via `forward_compatibility_horizon()` or with the environment variable # TF_FORWARD_COMPATIBILITY_DELTA_DAYS, which is added to the compatibility date. _FORWARD_COMPATIBILITY_HORIZON = datetime.date(2021, 4, 13) _FORWARD_COMPATIBILITY_DELTA_DAYS_VAR_NAME = "TF_FORWARD_COMPATIBILITY_DELTA_DAYS" _FORWARD_COMPATIBILITY_DATE_NUMBER = None def _date_to_date_number(year, month, day): return (year << 9) | (month << 5) | day def _update_forward_compatibility_date_number(date_to_override=None): """Update the base date to compare in forward_compatible function.""" global _FORWARD_COMPATIBILITY_DATE_NUMBER if date_to_override: date = date_to_override else: date = _FORWARD_COMPATIBILITY_HORIZON delta_days = os.getenv(_FORWARD_COMPATIBILITY_DELTA_DAYS_VAR_NAME) if delta_days: date += datetime.timedelta(days=int(delta_days)) if date < _FORWARD_COMPATIBILITY_HORIZON: logging.warning("Trying to set the forward compatibility date to the past" " date %s. This will be ignored by TensorFlow." % (date)) return _FORWARD_COMPATIBILITY_DATE_NUMBER = _date_to_date_number( date.year, date.month, date.day) _update_forward_compatibility_date_number() @tf_export("compat.forward_compatible") def forward_compatible(year, month, day): """Return true if the forward compatibility window has expired. See [Version compatibility](https://tensorflow.org/guide/version_compat#backward_forward). Forward-compatibility refers to scenarios where the producer of a TensorFlow model (a GraphDef or SavedModel) is compiled against a version of the TensorFlow library newer than what the consumer was compiled against. The "producer" is typically a Python program that constructs and trains a model while the "consumer" is typically another program that loads and serves the model. TensorFlow has been supporting a 3 week forward-compatibility window for programs compiled from source at HEAD. For example, consider the case where a new operation `MyNewAwesomeAdd` is created with the intent of replacing the implementation of an existing Python wrapper - `tf.add`. The Python wrapper implementation should change from something like: ```python def add(inputs, name=None): return gen_math_ops.add(inputs, name) ``` to: ```python from tensorflow.python.compat import compat def add(inputs, name=None): if compat.forward_compatible(year, month, day): # Can use the awesome new implementation. return gen_math_ops.my_new_awesome_add(inputs, name) # To maintain forward compatibility, use the old implementation. return gen_math_ops.add(inputs, name) ``` Where `year`, `month`, and `day` specify the date beyond which binaries that consume a model are expected to have been updated to include the new operations. This date is typically at least 3 weeks beyond the date the code that adds the new operation is committed. Args: year: A year (e.g., 2018). Must be an `int`. month: A month (1 <= month <= 12) in year. Must be an `int`. day: A day (1 <= day <= 31, or 30, or 29, or 28) in month. Must be an `int`. Returns: True if the caller can expect that serialized TensorFlow graphs produced can be consumed by programs that are compiled with the TensorFlow library source code after (year, month, day). """ return _FORWARD_COMPATIBILITY_DATE_NUMBER > _date_to_date_number( year, month, day) @tf_export("compat.forward_compatibility_horizon") @tf_contextlib.contextmanager def forward_compatibility_horizon(year, month, day): """Context manager for testing forward compatibility of generated graphs. See [Version compatibility](https://tensorflow.org/guide/version_compat#backward_forward). To ensure forward compatibility of generated graphs (see `forward_compatible`) with older binaries, new features can be gated with: ```python if compat.forward_compatible(year=2018, month=08, date=01): generate_graph_with_new_features() else: generate_graph_so_older_binaries_can_consume_it() ``` However, when adding new features, one may want to unittest it before the forward compatibility window expires. This context manager enables such tests. For example: ```python from tensorflow.python.compat import compat def testMyNewFeature(self): with compat.forward_compatibility_horizon(2018, 08, 02): # Test that generate_graph_with_new_features() has an effect ``` Args: year: A year (e.g., 2018). Must be an `int`. month: A month (1 <= month <= 12) in year. Must be an `int`. day: A day (1 <= day <= 31, or 30, or 29, or 28) in month. Must be an `int`. Yields: Nothing. """ try: _update_forward_compatibility_date_number(datetime.date(year, month, day)) yield finally: _update_forward_compatibility_date_number()
Python
0
@@ -1445,17 +1445,17 @@ 21, 4, 1 -3 +4 )%0A_FORWA
9df8506f86c1f6e95b6c9d0bda2dd8001dc0459b
Disable maxAudioWithBaselineShift test (works locally but not on travis)
test/client/dynamic_energy_test.py
test/client/dynamic_energy_test.py
import unittest import audioop from speech_recognition import AudioSource from mycroft.client.speech.mic import ResponsiveRecognizer __author__ = 'seanfitz' class MockStream(object): def __init__(self): self.chunks = [] def inject(self, chunk): self.chunks.append(chunk) def read(self, chunk_size): result = self.chunks[0] if len(self.chunks) > 1: self.chunks = self.chunks[1:] return result class MockSource(AudioSource): def __enter__(self): return self def __exit__(self, exc_type, exc_value, traceback): pass def __init__(self, stream=None): self.stream = stream if stream else MockStream() self.CHUNK = 1024 self.SAMPLE_RATE = 16000 self.SAMPLE_WIDTH = 2 class DynamicEnergytest(unittest.TestCase): def setUp(self): pass def testMaxAudioWithBaselineShift(self): low_base = b"".join(["\x10\x00\x01\x00"] * 100) higher_base = b"".join(["\x01\x00\x00\x01"] * 100) source = MockSource() for i in xrange(100): source.stream.inject(low_base) source.stream.inject(higher_base) recognizer = ResponsiveRecognizer(None) sec_per_buffer = float(source.CHUNK) / (source.SAMPLE_RATE * source.SAMPLE_WIDTH) test_seconds = 30.0 while test_seconds > 0: test_seconds -= sec_per_buffer data = source.stream.read(source.CHUNK) energy = recognizer.calc_energy(data, source.SAMPLE_WIDTH) recognizer.adjust_threshold(energy, sec_per_buffer) higher_base_energy = audioop.rms(higher_base, source.SAMPLE_WIDTH) # after recalibration (because of max audio length) new threshold # should be >= 1.5 * higher_base_energy delta_below_threshold = ( recognizer.energy_threshold - higher_base_energy) min_delta = higher_base_energy * .5 assert abs(delta_below_threshold - min_delta) < 1
Python
0
@@ -859,32 +859,101 @@ :%0A pass%0A%0A + @unittest.skip('Disabled while unittests are brought upto date')%0A def testMaxA
84ae11ed02eabcc9c00167c710d9eb4e8462e7b0
Create router.py
router.py
router.py
Python
0.000002
@@ -0,0 +1,1013 @@ +import jnettool.tool.elements.NetworkElements%0Aimport jnettool.tool.Routing%0Aimport jnettool.tool.RouteInspector%0A ne = jnettool.tools.elements.NetworkElements('ip')%0A%09try%0A%09 routing_tableb = ne.getRoutingTable()%0A%09except jnettool.tools.elements.MissingVar:%0A%09 logging.exception('No routing_tableb found')%0A%09 ne.cleanup('rollback')%0A%09 %0A%09else%0A%09 num_routes =routing_table.getSize()%0A%09 for RToffset in range (num_routes):%0A%09 route = routing_table.getRouteByIndex(RToffset)%0A%09 name = route.getName()%0A%09 ipaddr = route.get.IPAddr()%0A%09 print %22$15s -%3E %25s%22 %25 (name ipaddr)%0A%09finally%0A%09 ne.cleanup ('commit')%0A%09 ne.dissconnect()%0A##########################################################%0Afrom nettools import NetworkElements%0A%0Awith NetworkElements ('IP') as ne:%0A for route in ne.routing_table:%0A%09print %22$15s -%3E %25s%22 %25 (route.name route.ipaddr)%0A%0Aclass NetworkElements (Exception):%0Apass%0A%09%0A%09class NetworkElements (object)%22%0A%09%0Adef __init__(self , ipaddr):%0A self.oldne == jnettool.tools.NetworkElements () %0Aclass%0A
5662e4277c77dc3be308934a1e389cf24259037a
Create remap.py
remap.py
remap.py
Python
0
@@ -0,0 +1,2071 @@ +#!/usr/bin/env python%0A%0A#Licence LGPL v2.1%0A#Creates copy of map db, leaving only specified(filtered) blocks.%0A#Can also be used for map backup, may-be even online backup.%0A%0Aimport sqlite3%0Aimport mt_block_parser%0A%0Aimport re%0A%0Adef getIntegerAsBlock(i):%0A x = unsignedToSigned(i %25 4096, 2048)%0A i = int((i - x) / 4096)%0A y = unsignedToSigned(i %25 4096, 2048)%0A i = int((i - y) / 4096)%0A z = unsignedToSigned(i %25 4096, 2048)%0A return x,y,z%0Adef unsignedToSigned(i, max_positive):%0A if i %3C max_positive:%0A return i%0A else:%0A return i - 2*max_positive%0A%0A%0Asource = r'%3CPut your path to world folder here%3E/map.sqlite'%0Atarget = r'%3CPut your path to world folder here%3E/map.sqlite.backup'%0A%0A#use compiled regular expression to filter blocks by block content. it is faster that checking %22in array%22.%0Auseful_block_evidence = re.compile(%0A %22default:cobble%7C%22+%0A %22protector:protect%7Cdefault:chest_locked%7Cdoors:door_steel%7C%22+%0A %22default:chest%7Cdefault:torch%7Cdefault:stonebrick%7Cdefault:glass%7Cdefault:obsidian_glass%7C%22+%0A %22default:ladder%7Cdefault:rail%7Cdefault:fence_wood%7C%22+%0A %22bones:bones%22%0A )%0A%0Asourceconn = sqlite3.connect(source)%0Atargetconn = sqlite3.connect(target)%0Asourcecursor = sourceconn.cursor()%0Atargetcursor = targetconn.cursor()%0Atargetcursor.execute(%22CREATE TABLE IF NOT EXISTS %60blocks%60 (%60pos%60 INT NOT NULL PRIMARY KEY, %60data%60 BLOB);%22)%0A%0Afor row in sourcecursor.execute(%22SELECT %60pos%60, %60data%60 %22+%22 FROM %60blocks%60;%22):%0A pos=getIntegerAsBlock(row%5B0%5D)%0A if pos%5B0%5D**2 + pos%5B2%5D**2 %3C (160/16)**2 and pos%5B1%5D%3E(-60/16): #160 nodes radius and 60 nodes deep%0A targetcursor.execute(%22INSERT OR IGNORE INTO %60blocks%60 VALUES (?, ?);%22, (row%5B0%5D, row%5B1%5D))%0A else:%0A try:%0A temp = mt_block_parser.MtBlockParser(row%5B1%5D)%0A if useful_block_evidence.search(temp.nameIdMappingsRead)!=None:%0A targetcursor.execute(%22INSERT OR IGNORE INTO %60blocks%60 VALUES (?, ?);%22, (row%5B0%5D, row%5B1%5D))%0A except:%0A print %22Block parse error:%22, pos%5B0%5D, pos%5B1%5D, pos%5B2%5D%0A %0Atargetconn.commit()%0A%0Asourceconn.close()%0Atargetconn.close()%0A
a049ecd3c3d46f42d145d6d02a9f4f100ab3f4d9
Create rules_cc.bzl for TSL
tensorflow/tsl/platform/rules_cc.bzl
tensorflow/tsl/platform/rules_cc.bzl
Python
0
@@ -0,0 +1,411 @@ +%22%22%22Provides an indirection layer to bazel cc_rules%22%22%22%0A%0Aload(%0A %22//tensorflow/tsl/platform/default:rules_cc.bzl%22,%0A _cc_binary = %22cc_binary%22,%0A _cc_import = %22cc_import%22,%0A _cc_library = %22cc_library%22,%0A _cc_shared_library = %22cc_shared_library%22,%0A _cc_test = %22cc_test%22,%0A)%0A%0Acc_binary = _cc_binary%0Acc_import = _cc_import%0Acc_library = _cc_library%0Acc_shared_library = _cc_shared_library%0Acc_test = _cc_test%0A
6d5f1afdfe963a927e510a9a2e044fbd4796184f
add tests for cliff, arete, ridge, valley
test/601-cliff-arete-ridge-valley.py
test/601-cliff-arete-ridge-valley.py
Python
0.000008
@@ -0,0 +1,639 @@ +#cliff in Yosemite%0Aassert_has_feature(%0A 13, 1374, 3166, %22earth%22,%0A %7B%22kind%22: %22cliff%22, %22id%22: 291684864,%0A %22sort_key%22: 227%7D)%0A%0A#arete in Yosemite%0Aassert_has_feature(%0A 13, 1379, 3164, %22earth%22,%0A %7B%22kind%22: %22arete%22, %22id%22: 375271242,%0A %22sort_key%22: 228%7D)%0A%0A#ridge with name in Santa Cruz Mountains, California%0Aassert_has_feature(%0A 13, 1317, 3182, %22earth%22,%0A %7B%22kind%22: %22ridge%22, %22id%22: 115675159,%0A %22name%22: %22Castle Rock Ridge%22, %22label_placement%22: 'yes'%7D)%0A%0A#valley with name in Yosemite%0Aassert_has_feature(%0A 13, 1381, 3164, %22earth%22,%0A %7B%22kind%22: %22valley%22, %22id%22: 407467016,%0A %22name%22: %22Lyell Canyon%22, %22label_placement%22: 'yes'%7D)
918723bb1cbaea66358bd0701728bfb89fa6f00c
add servo_SG90.py
code/servo_SG90.py
code/servo_SG90.py
Python
0.000006
@@ -0,0 +1,722 @@ +#!/usr/bin/env python%0A# -*- coding: utf-8 -*-%0A# servo_SG90.py%0A# author: Kentaro Wada %3Cwww.kentaro.wada@gmail.com%3E%0A%0Aimport time%0A%0Afrom RPi import GPIO%0A%0A%0Adef move_pos(pin, deg, speed):%0A %22%22%22%0A (int) deg: 0 - 60 %5Bdeg%5D%0A (float) speed: -1 - 1%0A %22%22%22%0A t_start = time.time()%0A duration = 0.1 * deg / 60%0A while time.time() - t_start %3C duration:%0A high_duration = 0.0015 + speed * 0.0005%0A GPIO.output(pin, GPIO.HIGH)%0A time.sleep(high_duration)%0A GPIO.output(pin, GPIO.LOW)%0A time.sleep(0.02 - high_duration)%0A%0A%0Aif __name__ == '__main__':%0A PIN_CTRL = 21%0A%0A GPIO.setmode(GPIO.BCM)%0A GPIO.setup(PIN_CTRL, GPIO.OUT)%0A%0A move_pos(PIN_CTRL, deg=40, speed=1)%0A%0A GPIO.cleanup()
d31ee1207292e1b6c9f874b500837f91e477728c
Create sender.py
sender.py
sender.py
Python
0.000004
@@ -0,0 +1,1198 @@ +%22%22%22IMAGE_ID=%22%22 #Paste image ID here%0AFLAVOR_ID=%22%22%09#Paste Flavor_ID here%0ASSH_KEY=%22%22%09#Paste key name here - Assuming key already exists%22%22%22%0Afrom wsgiref.simple_server import make_server%0Aimport json%0A%0Adef createvm(ip,instance_name,image_id,flavor_id,ssh_key=None):%0A%09%22%22%22Creates an instance remotely%22%22%22%0A%09if ssh_key==None:%0A%09%09print %22SSH key not found%22%0A%09%09print %22Create a new key and try again%22%0A%09%09%0A%09else:%0A%09%09global cmd %0A%09%09cmd= %22nova boot %22+instance_name+%22 --image %5C%22%22+image_id+%22%5C%22 --flavor %22+flavor_id+%22 --key-name %22+ssh_key%0A%09%09send(ip)%0A%09%09%22%22%22 Now, send cmd to the ip specified in the parameters through a server.%0A%09%09 Receive at the other end and execute as a command%22%22%22 %0A%0Adef deletevm(ip,instance_name):%0A%09global cmd%0A%09cmd = %22nova delete %22+instance_name%0A%09send(ip)%0A%09%0A%0Adef application(environ, start_response):%0A%09global cmd%0A%09#result = get_data %0A%09response_body = json.dumps(cmd)%0A%09status = '200 OK'%0A%09response_headers = %5B('Content-Type', 'application/json'),%0A %09 ('Content-Length', str(len(response_body)))%5D%0A start_response(status, response_headers)%0A%09print response_body%0A %09return %5Bresponse_body%5D%0A%0A%0Adef send(ip_addr):%0A%09httpd = make_server(ip_addr,8051,application)%0A%09httpd.handle_request()%09%0A
ff8c866675d8eece3c527a245ec17520f357203e
test the `fastfood` command
tests/functional/test_entry_point.py
tests/functional/test_entry_point.py
Python
0.999995
@@ -0,0 +1,928 @@ +%22%22%22Functional tests for command line use.%22%22%22%0A%0Aimport subprocess%0Aimport unittest%0A%0A%0Aclass TestFastfoodCLI(unittest.TestCase):%0A%0A def test_fastfood_command_is_there(self):%0A%0A cmd = %5B'fastfood', '--help'%5D%0A try:%0A subprocess.check_output(cmd, stderr=subprocess.STDOUT)%0A except (subprocess.CalledProcessError, OSError) as err:%0A msg = 'Error while running %60%25s%60' %25 subprocess.list2cmdline(cmd)%0A self.fail(msg='%25s --%3E %25r' %25 (msg, err))%0A%0A def test_help_output(self):%0A cmd = %5B'fastfood', '--help'%5D%0A try:%0A output = subprocess.check_output(cmd, stderr=subprocess.STDOUT)%0A except (subprocess.CalledProcessError, OSError) as err:%0A msg = 'Error while running %60%25s%60' %25 subprocess.list2cmdline(cmd)%0A self.fail(msg='%25s --%3E %25r' %25 (msg, err))%0A self.assertIn('usage', output.lower())%0A%0A%0Aif __name__ == '__main__':%0A unittest.main()%0A
ff151c8ea04268d2060cf8d281294a0d500ecbba
Test that data volumes now survive a crash when recreating
tests/integration/resilience_test.py
tests/integration/resilience_test.py
Python
0
@@ -0,0 +1,1026 @@ +from __future__ import unicode_literals%0Afrom __future__ import absolute_import%0A%0Aimport mock%0A%0Afrom compose.project import Project%0Afrom .testcases import DockerClientTestCase%0A%0A%0Aclass ResilienceTest(DockerClientTestCase):%0A def test_recreate_fails(self):%0A db = self.create_service('db', volumes=%5B'/var/db'%5D, command='top')%0A project = Project('composetest', %5Bdb%5D, self.client)%0A%0A container = db.create_container()%0A db.start_container(container)%0A host_path = container.get('Volumes')%5B'/var/db'%5D%0A%0A project.up()%0A container = db.containers()%5B0%5D%0A self.assertEqual(container.get('Volumes')%5B'/var/db'%5D, host_path)%0A%0A with mock.patch('compose.service.Service.create_container', crash):%0A with self.assertRaises(Crash):%0A project.up()%0A%0A project.up()%0A container = db.containers()%5B0%5D%0A self.assertEqual(container.get('Volumes')%5B'/var/db'%5D, host_path)%0A%0A%0Aclass Crash(Exception):%0A pass%0A%0A%0Adef crash(*args, **kwargs):%0A raise Crash()%0A
4606d80a6103fd7d358e0a8fb5a537c2a1e3f72b
Tweak doc generation script a bit.
script/generate_docs.py
script/generate_docs.py
#!/usr/bin/env python import glob import markdown import os import shutil import sys import time from datetime import datetime def compare_modification_times(path, out_path): # See if it's up to date. source_mod = os.path.getmtime(path) source_mod = max(source_mod, os.path.getmtime('doc/site/template.html')) dest_mod = 0 if os.path.exists(out_path): dest_mod = os.path.getmtime(out_path) return source_mod < dest_mod def format_file(path, skip_up_to_date): basename = os.path.basename(path) basename = basename.split('.')[0] out_path = "build/site/" + basename + ".html" if skip_up_to_date and compare_modification_times(path, out_path): # It's up to date. return title = "" # Read the markdown file and preprocess it. contents = "" with open(path, "r") as input: # Read each line, preprocessing the special codes. for line in input: stripped = line.lstrip() indentation = line[:len(line) - len(stripped)] if stripped.startswith("^"): command,_,args = stripped.rstrip("\n").lstrip("^").partition(" ") args = args.strip() if command == "title": title = args else: print "UNKNOWN COMMAND:", command, args elif stripped.startswith('#'): # Add anchors to the headers. index = stripped.find(" ") headertype = stripped[:index] header = stripped[index:].strip() anchor = header.lower().replace(' ', '-') anchor = anchor.translate(None, '.?!:/') contents += indentation + headertype contents += '{1} <a href="#{0}" name="{0}" class="header-anchor">#</a>\n'.format(anchor, header) else: contents = contents + line html = markdown.markdown(contents, ['def_list', 'codehilite']) modified = datetime.fromtimestamp(os.path.getmtime(path)) mod_str = modified.strftime('%B %d, %Y') fields = {'title': title, 'html': html, 'mod': mod_str} with open("doc/site/template.html") as f: template = f.read() # Write the html output. with open(out_path, 'w') as out: out.write(template.format(**fields)) print "converted", basename def format_files(skip_up_to_date): for f in glob.iglob("doc/site/*.markdown"): format_file(f, skip_up_to_date) # Copy the CSS file. css_in = "doc/site/style.css" css_out = "build/site/style.css" if skip_up_to_date and compare_modification_times(css_in, css_out): pass else: shutil.copyfile(css_in, css_out) print "copied css" # Clean the output directory. if not os.path.exists("build"): os.mkdir("build") if os.path.exists("build/docs"): shutil.rmtree("build/docs") os.mkdir("build/docs") # Process each markdown file. format_files(False) # Watch files if len(sys.argv) == 2 and sys.argv[1] == '--watch': while True: format_files(True) time.sleep(0.3)
Python
0
@@ -130,34 +130,21 @@ def -compare_modification_times +is_up_to_date (pat @@ -552,20 +552,20 @@ %22build/ -site +docs /%22 + bas @@ -610,34 +610,21 @@ and -compare_modification_times +is_up_to_date (pat @@ -2241,16 +2241,17 @@ o_date)%0A +%0A # Copy @@ -2316,20 +2316,20 @@ %22build/ -site +docs /style.c @@ -2361,34 +2361,21 @@ and -compare_modification_times +is_up_to_date (css @@ -2702,16 +2702,17 @@ ch files +. %0Aif len(
bb48a8a9a763e594efa06b397d7731f25cedd65d
add parallel perceptron
src/learn/spark_perceptron.py
src/learn/spark_perceptron.py
Python
0.999907
@@ -0,0 +1,2737 @@ +from __future__ import division%0Aimport logging%0Aimport multiprocessing%0Afrom hvector._mycollections import mydefaultdict%0Afrom hvector.mydouble import mydouble%0Afrom weight.weight_vector import *%0A# Time accounting and control%0Aimport debug.debug%0Aimport time%0Aimport sys%0A%0Afrom pyspark import SparkContext%0A%0A%0Alogging.basicConfig(filename='glm_parser.log',%0A level=logging.DEBUG,%0A format='%25(asctime)s %25(levelname)s: %25(message)s',%0A datefmt='%25m/%25d/%25Y %25I:%25M:%25S %25p')%0A%0Aclass AveragePerceptronLearner():%0A%0A def __init__(self, w_vector, max_iter=1):%0A %22%22%22%0A :param w_vector: A global weight vector instance that stores%0A the weight value (float)%0A :param max_iter: Maximum iterations for training the weight vector%0A Could be overridden by parameter max_iter in the method%0A :return: None%0A %22%22%22%0A logging.debug(%22Initialize AveragePerceptronLearner ... %22)%0A self.w_vector = w_vector%0A return%0A%0A def parallel_learn(self, f_argmax, data_pool=None, max_iter=-1, d_filename=None, dump_freq=1):%0A # sigma_s%0A self.weight_sum_dict.clear()%0A self.last_change_dict.clear()%0A self.c = 1%0A%0A data_list = %5B%5D%0A sentence = 0%0A while data_pool.has_next_data():%0A sentence_count+=1%0A data = dp.get_next_data()%0A data_list.append(data)%0A%0A sc = SparkContext(appName=%22iterParameterMixing%22)%0A train_data = sc.parallelize(data_list).cache()%0A def avg_perc_train(train_data,w_vector,f_argmax):%0A while train_data.has_next_data():%0A data_instance = data_pool.get_next_data()%0A gold_global_vector = data_instance.gold_global_vector%0A current_global_vector = f_argmax(data_instance)%0A # otherwise, the gold_global_vector will change because of the change in weights%0A w_vector.data_dict.iadd(gold_global_vector.feature_dict)%0A w_vector.data_dict.iaddc(current_global_vector.feature_dict, -1)%0A return weight_vector.items()%0A for round in range(0,epochs):%0A fv = %7B%7D%0A weight_vector = self.w_vector%0A feat_vec_list = train_data.mapPartitions(lambda t: avg_perc_train(t, weight_vector))%0A feat_vec_list = feat_vec_list.combineByKey((lambda x: (x,1)),%0A (lambda x, y: (x%5B0%5D + y, x%5B1%5D + 1)),%0A (lambda x, y: (x%5B0%5D + y%5B0%5D, x%5B1%5D + y%5B1%5D))).collect()%0A self.w_vector.data_dict.clear()%0A for (feat, (a,b)) in feat_vec_list:%0A fv%5Bfeat%5D = float(a)/float(b)%0A self.w_vector.data_dict.iadd(fv)%0A sc.stop()%0A%0A %0A
33a0b48ec475ec02f60ed27e572709136515763a
Create maxdiff.py
maxdiff.py
maxdiff.py
Python
0
@@ -0,0 +1,1224 @@ +__author__ = 'sebastiengenty'%0A%0Aimport numpy as np%0Aimport pandas as pd%0A%0A# This program is made to take the utilities from a MaxDiff estimation and compute the relative importances for%0A# the attributes tested. Input for now is .csv though also working on a .xlsx solution.%0A%0A%0Adef avg_imp(utilities_file, filter_var='none', weight='none'):%0A %22%22%22 Actual function doing all the heavy lifting. Takes in the utility scores and filters and computes the average%0A importances. Has the option of adding weights if need be.%0A :param utilities_file: CSV file containing the utility scores. Top row should be labels.%0A :param filter_var: CSV file containing the filter values. Each filter group should be its own variable, no overlaps%0A :param weight:%0A :return:%0A %22%22%22%0A raw = pd.read_csv(utilities_file, index_col='session')%0A rescaled = np.exp(raw)%0A rescaled = rescaled.divide(rescaled.sum(axis=0),axis=0)%0A%0A if weight is 'none':%0A rescaled = rescaled%0A else:%0A rescaled = rescaled*weight%0A%0A if filter_var is 'none':%0A output = rescaled.means()%0A else:%0A filts = pd.read_csv(filter_var, index_col='session')%0A data = pd.concat(rescaled, filts)%0A output = data.groupby()%0A%0A
1902351fc88c1e18b4d8de032ff2aa8da547dac0
Bump nydus testing requirement to 0.9.0
setup.py
setup.py
#!/usr/bin/env python """ Sentry ====== Sentry is a realtime event logging and aggregation platform. It specializes in monitoring errors and extracting all the information needed to do a proper post-mortem without any of the hassle of the standard user feedback loop. Sentry is a Server ------------------ The Sentry package, at its core, is just a simple server and web UI. It will handle authentication clients (such as `Raven <https://github.com/getsentry/raven-python>`_) and all of the logic behind storage and aggregation. That said, Sentry is not limited to Python. The primary implementation is in Python, but it contains a full API for sending events from any language, in any application. :copyright: (c) 2011-2012 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from setuptools import setup, find_packages # Hack to prevent stupid "TypeError: 'NoneType' object is not callable" error # in multiprocessing/util.py _exit_function when running `python # setup.py test` (see # http://www.eby-sarna.com/pipermail/peak/2010-May/003357.html) for m in ('multiprocessing', 'billiard'): try: __import__(m) except ImportError: pass tests_require = [ 'django-nose==1.1', 'eventlet==0.9.16', 'nose==1.2.1', 'nydus==0.8.2', 'mock>=0.8.0', 'redis', 'unittest2', ] install_requires = [ 'cssutils>=0.9.9', 'BeautifulSoup>=3.2.1', 'django-celery>=2.5.5', 'celery>=2.5.3', 'django-crispy-forms>=1.1.4', 'Django>=1.4.1,<=1.5', 'django-indexer>=0.3.0', 'django-paging>=0.2.4', 'django-picklefield>=0.2.0', 'django-templatetag-sugar>=0.1.0', 'gunicorn>=0.14.6', 'logan>=0.5.1', 'pynliner>=0.4.0', 'python-dateutil>=1.5.0,<2.0.0', 'raven>=2.0.6', 'simplejson>=2.1.6', 'South>=0.7.6', 'httpagentparser>=1.0.5', 'django-social-auth>=0.7.1,<1.0', 'django-social-auth-trello>=1.0.2', ] setup( name='sentry', version='5.0.14', author='David Cramer', author_email='dcramer@gmail.com', url='http://www.getsentry.com', description='A realtime logging and aggregation server.', long_description=__doc__, package_dir={'': 'src'}, packages=find_packages('src'), zip_safe=False, install_requires=install_requires, tests_require=tests_require, test_suite='runtests.runtests', license='BSD', include_package_data=True, entry_points={ 'console_scripts': [ 'sentry = sentry.utils.runner:main', ], }, classifiers=[ 'Framework :: Django', 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', 'Operating System :: OS Independent', 'Topic :: Software Development' ], )
Python
0
@@ -1311,11 +1311,11 @@ ==0. -8.2 +9.0 ',%0A
3d5787cd860b1b3baaa041e49efe6d4af09396ac
Add migrations package to setup.py
setup.py
setup.py
from distutils.core import setup setup( name='django-auditlog', version='0.2.1', packages=['auditlog',], package_dir={'': 'src'}, url='https://github.com/jjkester/django-auditlog', license='MIT', author='Jan-Jelle Kester', author_email='janjelle@jjkester.nl', description='Audit log app for Django', install_requires=[ 'Django>=1.5' ] )
Python
0.000001
@@ -108,16 +108,38 @@ ditlog', + 'auditlog.migrations' %5D,%0A p
5515fc7207404013ea9ba655b29bc414320971d9
add setup.py
setup.py
setup.py
Python
0.000001
@@ -0,0 +1,340 @@ +from setuptools import setup%0A%0Asetup(name='optimizely',%0A version='0.1',%0A description='An interface to Optimizely%5C's REST API.',%0A url='https://github.com/optimizely/optimizely-client-python',%0A author='Optimizely',%0A packages=%5B'optimizely'%5D,%0A install_requires=%5B%0A 'requests',%0A %5D,%0A zip_safe=False)
5aa8d60a7f702b71c902224394ac6bddf088c0ad
fix missing import
configure-aspen.py
configure-aspen.py
from __future__ import division import os import sys import threading import time import traceback import gittip import gittip.wireup from gittip import canonize from gittip.security import authentication, csrf, x_frame_options from gittip.utils import cache_static, set_cookie, timer import aspen from aspen import log_dammit # Monkey patch aspen.Response # =========================== if hasattr(aspen.Response, 'redirect'): raise Warning('aspen.Response.redirect() already exists') def _redirect(response, url): response.code = 302 response.headers['Location'] = url raise response aspen.Response.redirect = _redirect if hasattr(aspen.Response, 'set_cookie'): raise Warning('aspen.Response.set_cookie() already exists') def _set_cookie(response, *args, **kw): set_cookie(response.headers.cookie, *args, **kw) aspen.Response.set_cookie = _set_cookie # Wireup Algorithm # ================ version_file = os.path.join(website.www_root, 'version.txt') website.version = open(version_file).read().strip() website.renderer_default = "jinja2" website.renderer_factories['jinja2'].Renderer.global_context = { 'range': range, 'unicode': unicode, 'enumerate': enumerate, 'len': len, 'float': float, 'type': type, 'str': str } env = website.env = gittip.wireup.env() gittip.wireup.canonical(env) website.db = gittip.wireup.db(env) website.mail = gittip.wireup.mail(env) gittip.wireup.billing(env) gittip.wireup.username_restrictions(website) gittip.wireup.nanswers(env) gittip.wireup.other_stuff(website, env) gittip.wireup.accounts_elsewhere(website, env) tell_sentry = website.tell_sentry = gittip.wireup.make_sentry_teller(env) # The homepage wants expensive queries. Let's periodically select into an # intermediate table. def cron(period, func): def f(): if period <= 0: return sleep = time.sleep while 1: try: func() except Exception, e: tell_sentry(e) log_dammit(traceback.format_exc().strip()) sleep(period) t = threading.Thread(target=f) t.daemon = True t.start() def update_homepage_queries(): utils.update_global_stats(website) utils.update_homepage_queries_once(website.db) cron(env.update_homepage_every, update_homepage_queries) cron(env.check_db_every, website.db.self_check) # Server Algorithm # ================ def up_minthreads(website): # https://github.com/gittip/www.gittip.com/issues/1098 # Discovered the following API by inspecting in pdb and browsing source. # This requires network_engine.bind to have already been called. request_queue = website.network_engine.cheroot_server.requests request_queue.min = website.min_threads def setup_busy_threads_logging(website): # https://github.com/gittip/www.gittip.com/issues/1572 log_every = website.log_busy_threads_every if log_every == 0: return pool = website.network_engine.cheroot_server.requests def log_busy_threads(): time.sleep(0.5) # without this we get a single log message where all threads are busy while 1: # Use pool.min and not pool.max because of the semantics of these # inside of Cheroot. (Max is a hard limit used only when pool.grow # is called, and it's never called except when the pool starts up, # when it's called with pool.min.) nbusy_threads = pool.min - pool.idle print("sample#aspen.busy_threads={}".format(nbusy_threads)) time.sleep(log_every) thread = threading.Thread(target=log_busy_threads) thread.daemon = True thread.start() website.server_algorithm.insert_before('start', up_minthreads) website.server_algorithm.insert_before('start', setup_busy_threads_logging) # Website Algorithm # ================= def add_stuff_to_context(request): request.context['username'] = None def scab_body_onto_response(response): # This is a workaround for a Cheroot bug, where the connection is closed # too early if there is no body: # # https://bitbucket.org/cherrypy/cheroot/issue/1/fail-if-passed-zero-bytes # # This Cheroot bug is manifesting because of a change in Aspen's behavior # with the algorithm.py refactor in 0.27+: Aspen no longer sets a body for # 302s as it used to. This means that all redirects are breaking # intermittently (sometimes the client seems not to care that the # connection is closed too early, so I guess there's some timing # involved?), which is affecting a number of parts of Gittip, notably # around logging in (#1859). if not response.body: response.body = '*sigh*' algorithm = website.algorithm algorithm.functions = [ timer.start , algorithm['parse_environ_into_request'] , algorithm['tack_website_onto_request'] , algorithm['raise_200_for_OPTIONS'] , canonize , authentication.inbound , csrf.inbound , add_stuff_to_context , algorithm['dispatch_request_to_filesystem'] , algorithm['apply_typecasters_to_path'] , cache_static.inbound , algorithm['get_response_for_socket'] , algorithm['get_resource_for_request'] , algorithm['get_response_for_resource'] , tell_sentry , algorithm['get_response_for_exception'] , gittip.outbound , authentication.outbound , csrf.outbound , cache_static.outbound , x_frame_options , algorithm['log_traceback_for_5xx'] , algorithm['delegate_error_to_simplate'] , tell_sentry , algorithm['log_traceback_for_exception'] , algorithm['log_result_of_request'] , scab_body_onto_response , timer.end , tell_sentry ]
Python
0.008361
@@ -156,16 +156,23 @@ canonize +, utils %0Afrom gi
6f7abe8ea3e08ad15adab85c947ad4667e3dd3ab
Add simplejson requirement to setup
setup.py
setup.py
#!/usr/bin/env python """ Installation script: To release a new version to PyPi: - Ensure the version is correctly set in oscar.__init__.py - Run: python setup.py sdist upload """ from setuptools import setup, find_packages from oscar import get_version setup(name='django-oscar', version=get_version().replace(' ', '-'), url='https://github.com/tangentlabs/django-oscar', author="David Winterbottom", author_email="david.winterbottom@tangentlabs.co.uk", description="A domain-driven e-commerce framework for Django 1.3+", long_description=open('README.rst').read(), keywords="E-commerce, Django, domain-driven", license='BSD', platforms=['linux'], packages=find_packages(exclude=["sandbox*", "tests*"]), include_package_data=True, install_requires=[ 'django==1.4', 'PIL==1.1.7', 'South==0.7.3', 'django-extra-views==0.2.0', 'django-haystack==1.2.7', 'django-treebeard==1.61', 'sorl-thumbnail==11.12', 'python-memcached==1.48', 'django-sorting==0.1', ], # See http://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=['Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: Unix', 'Programming Language :: Python'] )
Python
0
@@ -1107,24 +1107,55 @@ ting==0.1',%0A + 'simplejson==2.5.2',%0A %5D,
b16f666af5e7dd1e2201e8e57c0590933b5b73e9
Add setup script
setup.py
setup.py
Python
0.000001
@@ -0,0 +1,825 @@ +# -*- coding: utf-8 -*-%0Afrom setuptools import setup%0A%0Asetup(%0A name='gymz',%0A version='0.0.1',%0A author='Jakob Jordan, Philipp Weidel',%0A author_email='j.jordan@fz-juelich.de',%0A description=('A light-weight ZMQ wrapper for the OpenAI Gym.'),%0A license='MIT',%0A keywords='openai-gym reinforcement-learning zmq',%0A url='https://github.com/INM-6/python-gymz',%0A packages=%5B'gymz', 'examples'%5D,%0A scripts=%5B'gymz-controller'%5D,%0A data_files=%5B'DefaultConfig.json'%5D,%0A long_description=open('README.md').read(),%0A classifiers=%5B%0A 'Development Status :: 3 - Alpha',%0A 'License :: OSI Approved :: MIT License',%0A 'Natural Language :: English',%0A 'Operating System :: OS Independent',%0A 'Programming Language :: Python :: 2.7',%0A 'Topic :: Scientific/Engineering',%0A %5D,%0A)%0A
82ec309f1c708071b4d1c9b8dc9d2c9b3b3ca1fb
Version update
setup.py
setup.py
import sys from setuptools import setup, find_packages deps = ["distribute", "PyYaml", "voluptuous"] if sys.version_info[:2] == (2, 6): deps.append('argparse') setup( name='toxer', version='0.1.0', packages=find_packages(exclude=("test.*",)), entry_points={ 'console_scripts': [ 'toxer = toxer.cli:main', 'toxer-build = toxer.cli:build_images', ], }, url='', license='MIT', author='Aleksandr Rudakov', author_email='ribozz@gmail.com', description='Run your tox tests inside docker with different linux distributions.', long_description=open('README.md').read(), install_requires=deps, # cmdclass={'test': PyTest}, extras_require={ 'dev': ['pytest', 'coverage', 'pytest-cov', 'mock'], 'travis': ['coveralls'], 'docs': ['sphinx==1.2b3', 'sphinx-argparse'] } )
Python
0
@@ -206,17 +206,17 @@ on='0.1. -0 +1 ',%0A p
9dc0619d6528e9fbef328faf56a982d4af7379ba
Prepare for Jinja 2.5.3
setup.py
setup.py
# -*- coding: utf-8 -*- """ Jinja2 ~~~~~~ Jinja2 is a template engine written in pure Python. It provides a `Django`_ inspired non-XML syntax but supports inline expressions and an optional `sandboxed`_ environment. Nutshell -------- Here a small example of a Jinja template:: {% extends 'base.html' %} {% block title %}Memberlist{% endblock %} {% block content %} <ul> {% for user in users %} <li><a href="{{ user.url }}">{{ user.username }}</a></li> {% endfor %} </ul> {% endblock %} Philosophy ---------- Application logic is for the controller but don't try to make the life for the template designer too hard by giving him too few functionality. For more informations visit the new `Jinja2 webpage`_ and `documentation`_. The `Jinja2 tip`_ is installable via `easy_install` with ``easy_install Jinja2==dev``. .. _sandboxed: http://en.wikipedia.org/wiki/Sandbox_(computer_security) .. _Django: http://www.djangoproject.com/ .. _Jinja2 webpage: http://jinja.pocoo.org/ .. _documentation: http://jinja.pocoo.org/2/documentation/ .. _Jinja2 tip: http://dev.pocoo.org/hg/jinja2-main/archive/tip.tar.gz#egg=Jinja2-dev """ import os import sys from setuptools import setup, Extension, Feature from distutils.command.build_ext import build_ext debugsupport = Feature( 'optional C debug support', standard=False, ext_modules = [ Extension('jinja2._debugsupport', ['jinja2/_debugsupport.c']), ], ) # tell distribute to use 2to3 with our own fixers. extra = {} if sys.version_info >= (3, 0): extra.update( use_2to3=True, use_2to3_fixers=['custom_fixers'] ) # ignore the old '--with-speedups' flag try: speedups_pos = sys.argv.index('--with-speedups') except ValueError: pass else: sys.argv[speedups_pos] = '--with-debugsupport' sys.stderr.write('*' * 74 + '\n') sys.stderr.write('WARNING:\n') sys.stderr.write(' the --with-speedups flag is deprecated, assuming ' '--with-debugsupport\n') sys.stderr.write(' For the actual speedups install the MarkupSafe ' 'package.\n') sys.stderr.write('*' * 74 + '\n') setup( name='Jinja2', version='2.5.2', url='http://jinja.pocoo.org/', license='BSD', author='Armin Ronacher', author_email='armin.ronacher@active-4.com', description='A small but fast and easy to use stand-alone template ' 'engine written in pure python.', long_description=__doc__, # jinja is egg safe. But we hate eggs zip_safe=False, classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'Topic :: Software Development :: Libraries :: Python Modules', 'Topic :: Text Processing :: Markup :: HTML' ], packages=['jinja2', 'jinja2.testsuite', 'jinja2.testsuite.res', 'jinja2._markupsafe'], extras_require={'i18n': ['Babel>=0.8']}, test_suite='jinja2.testsuite.suite', include_package_data=True, entry_points=""" [babel.extractors] jinja2 = jinja2.ext:babel_extract[i18n] """, features={'debugsupport': debugsupport}, **extra )
Python
0
@@ -2223,17 +2223,17 @@ on='2.5. -2 +3 ',%0A u
713e715fb3657a274f60c687eec60bad0d9c7da9
Update synth.py yaml location (#6480)
container/synth.py
container/synth.py
# Copyright 2018 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This script is used to synthesize generated parts of this library.""" import synthtool as s from synthtool import gcp gapic = gcp.GAPICGenerator() #---------------------------------------------------------------------------- # Generate container client #---------------------------------------------------------------------------- library = gapic.py_library( 'container', 'v1', config_path='/google/container/artman_container.yaml', artman_output_name='container-v1') s.move(library / 'google/cloud/container_v1') # Issues exist where python files should define the source encoding # https://github.com/googleapis/gapic-generator/issues/2097 s.replace( 'google/**/proto/*_pb2.py', r"(^.*$\n)*", r"# -*- coding: utf-8 -*-\n\g<0>")
Python
0
@@ -1011,16 +1011,19 @@ ontainer +_v1 .yaml',%0A
8e175782c3b79e64d543fb478b146d308d2a2ad8
Add small python script which calculates how much disk space we save by using CAS
bin/oneoffs/cas_statistic.py
bin/oneoffs/cas_statistic.py
Python
0.000001
@@ -0,0 +1,1911 @@ +import os%0Aimport pymongo%0Afrom collections import Counter%0A%0Adb_uri = os.getenv('SCITRAN_PERSISTENT_DB_URI', 'localhost:9001')%0Adb = pymongo.MongoClient(db_uri).get_database('scitran')%0A%0ACOLLECTIONS = %5B'projects', 'acquisitions', 'analyses'%5D%0ACOLLECTIONS_WITH_EMBEDDED = %5B('sessions', 'subject')%5D%0A%0A%0Adef files_of_collection(collection, embedded_doc=None):%0A hash_size_pairs = %5B%5D%0A cursor = db.get_collection(collection).find(%7B%7D)%0A for document in cursor:%0A hash_size_pairs += files_of_document(document)%0A if embedded_doc:%0A hash_size_pairs += files_of_document(document.get(embedded_doc, %7B%7D))%0A%0A return hash_size_pairs%0A%0A%0Adef files_of_document(document):%0A hash_size_pairs = %5B%5D%0A files = document.get('files', %5B%5D)%0A for f in files:%0A hash_size_pairs.append((f%5B'hash'%5D, f%5B'size'%5D))%0A%0A return hash_size_pairs%0A%0A%0Adef main():%0A hash_size_pairs = %5B%5D%0A for collection in COLLECTIONS:%0A hash_size_pairs += files_of_collection(collection)%0A%0A for collection, embedded_doc in COLLECTIONS_WITH_EMBEDDED:%0A hash_size_pairs += files_of_collection(collection, embedded_doc)%0A%0A counter = Counter(hash_size_pairs)%0A size_with_cas = 0%0A size_wo_cas = 0%0A file_count_cas = len(counter)%0A file_count_wo_cas = 0%0A%0A for hash_size_pair in counter:%0A size_with_cas += hash_size_pair%5B1%5D%0A size_wo_cas += hash_size_pair%5B1%5D * counter%5Bhash_size_pair%5D%0A file_count_wo_cas += counter%5Bhash_size_pair%5D%0A%0A saved_disk_space = size_wo_cas - size_with_cas%0A%0A print('Total size (CAS): %25s Bytes' %25 size_with_cas)%0A print('Total size (wo CAS): %25s Bytes' %25 size_wo_cas)%0A print('Number of files (CAS): %25s' %25 file_count_cas)%0A print('Number of files (wo CAS): %25s' %25 file_count_wo_cas)%0A print('Saved disk space: %25s Bytes (%25s%25%25)' %25 (%0A saved_disk_space, round(saved_disk_space / float(size_wo_cas) * 100, 2)))%0A%0A%0Aif __name__ == '__main__':%0A main()%0A
04a24befbaba975720acf5533bc97e7b3d601672
Install script.
setup.py
setup.py
Python
0
@@ -0,0 +1,2021 @@ +#!/usr/bin/env python%0A%0A# Copyright (c) 2012 SEOmoz%0A#%0A# Permission is hereby granted, free of charge, to any person obtaining%0A# a copy of this software and associated documentation files (the%0A# %22Software%22), to deal in the Software without restriction, including%0A# without limitation the rights to use, copy, modify, merge, publish,%0A# distribute, sublicense, and/or sell copies of the Software, and to%0A# permit persons to whom the Software is furnished to do so, subject to%0A# the following conditions:%0A#%0A# The above copyright notice and this permission notice shall be%0A# included in all copies or substantial portions of the Software.%0A#%0A# THE SOFTWARE IS PROVIDED %22AS IS%22, WITHOUT WARRANTY OF ANY KIND,%0A# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF%0A# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND%0A# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE%0A# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION%0A# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION%0A# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.%0A%0Atry:%0A%09from setuptools import setup%0Aexcept ImportError:%0A%09from distutils.core import setup%0A%0Asetup(%0A%09name = 'url',%0A%09version = '0.1.0',%0A%09description = 'URL Parsing',%0A%09long_description = '''%0ASome helper functions for parsing URLs, sanitizing them, normalizing them.%0A%0AThis includes support for escaping, unescaping, punycoding, unpunycoding,%0Acleaning parameter and query strings, and a little more sanitization.%0A''',%0A%09author = 'Dan Lecocq',%0A%09author_email = 'dan@seomoz.org',%0A%09url = 'http://github.com/seomoz/url-py',%0A%09py_modules = %5B'url'%5D,%0A%09license = 'MIT',%0A%09platforms = 'Posix; MacOS X',%0A%09test_suite = 'tests.testReppy',%0A%09classifiers = %5B%0A%09%09'License :: OSI Approved :: MIT License',%0A%09%09'Development Status :: 3 - Alpha',%0A%09%09'Environment :: Web Environment',%0A%09%09'Intended Audience :: Developers',%0A%09%09'Topic :: Internet :: WWW/HTTP'%5D,%0A)