commit
stringlengths 40
40
| subject
stringlengths 4
1.73k
| repos
stringlengths 5
127k
| old_file
stringlengths 2
751
| new_file
stringlengths 2
751
| new_contents
stringlengths 1
8.98k
| old_contents
stringlengths 0
6.59k
| license
stringclasses 13
values | lang
stringclasses 23
values |
---|---|---|---|---|---|---|---|---|
f2413f05bc64818297541112f42e2a8d5ae72cbe | Create test_setup.py | CoDaS-Lab/image_analysis | test_setup.py | test_setup.py | import wget
import os
test_files_path = os.getcwd() + '/image-analysis/test/test_data/'
# test files will be here whether is data, images, videos ect.
test_files = ["https://s3.amazonaws.com/testcodas/test_video.mp4"]
for file_path in test_files:
wget.download(file_path, test_files_path)
| apache-2.0 | Python |
|
c54c948531cd73b0c0dd78b6bc8a1c5245886c97 | add visualise.py | hiromu/mothur_bruteforce,hiromu/mothur_bruteforce | visualize.py | visualize.py | #!/usr/bin/env python
import json
import math
import numpy
import os
import re
import sys
if __name__ == '__main__':
if len(sys.argv) < 3:
print('usage: %s [result dir] [output html]' % sys.argv[0])
sys.exit()
result = [[], [], [], []]
for filename in os.listdir(sys.argv[1]):
match = re.match('([0-9]+)_([0-9]+).result', filename)
if not match:
continue
average, size = map(int, match.groups())
name = 'Average: %d, Size: %d' % (average, size)
matrix = numpy.loadtxt(os.path.join(sys.argv[1], filename), dtype = str)
data = matrix[1:,1:].astype(int)
result[0].append([numpy.mean(data[:,3]), numpy.mean(data[:,4]), len(data), name])
result[1].append([numpy.median(data[:,3]), numpy.median(data[:,4]), len(data), name])
result[2].append([numpy.amin(data[:,3]), numpy.amin(data[:,4]), len(data), name])
result[3].append([numpy.amax(data[:,3]), numpy.amax(data[:,4]), len(data), name])
path = os.path.join(os.path.dirname(__file__), 'html')
with open(os.path.join(path, 'template.html')) as input:
with open(sys.argv[2], 'w') as output:
relpath = os.path.relpath(path, os.path.dirname(sys.argv[2]))
html = input.read()
format = [relpath] * 5 + map(json.dumps, result)
output.write(html % tuple(format))
| mit | Python |
|
6c61c2d367e698861657d4cfc9bba0ba3789f197 | add naive bayes | CMPS242-fsgh/project | nb.py | nb.py | import numpy as np
class NaiveBayes:
def __init__(self):
self._prior = None
self._mat = None
def train(self, X, y):
y = np.matrix(y)
p1 = y*X
p2 = (1-y)*X
p = np.vstack([
np.log(p1+1) - np.log(p1.sum() + p1.shape[1]),
np.log(p2+1) - np.log(p2.sum() + p2.shape[1])])
pri = np.matrix([[float(y.sum())/y.shape[1]], [1 - float(y.sum())/y.shape[1] ]])
self._prior = np.log(pri)
self._mat = p
return p, pri
def predict_many(self, mat):
logp = self._mat*mat.T + self._prior
ans = (np.sign(logp[0] - logp[1]) + 1)/2
return ans.A1
def validate(self, mat, real_y):
predict_y = self.predict_many(mat)
return (predict_y == real_y).sum()
if __name__ == '__main__':
import loader
from sklearn.feature_extraction.text import HashingVectorizer
d = loader.DataLoader()
g = d.alldata()
def iter_data(n, y, cat):
c = 0
for business in g:
if c % 1000 == 0:
print c, '/', n
if c<n:
if cat.decode('utf-8') in business.categories:
y[c] = 1
else:
y[c] = 0
yield "".join(business.reviews)
else:
return
c += 1
# f = open('data/yelp.csv')
# def iter_data(n, y, cat):
# c = 0
# for line in f:
# if c % 1000 == 0:
# print c, '/', n
# if c < n:
# b_id, categories, review = line.split('\t')
# categories = categories.split(',')
# if cat in categories:
# y[c] = 1
# else:
# y[c] = 0
# yield review
# else:
# return
# c += 1
n = 4000
y = np.zeros(n)
v = HashingVectorizer(stop_words='english', non_negative=True, norm=None)
mat = v.transform(iter_data(n, y, 'Restaurants'))
print 'data readed', mat.shape, y.shape
nt = 1000
yt = np.zeros(nt)
mt = v.transform(iter_data(nt, yt, 'Restaurants'))
#print yt
print 'our code',
mm = NaiveBayes()
mm.train(mat, y)
print float(mm.validate(mt, yt))/nt
from sklearn.naive_bayes import MultinomialNB
model = MultinomialNB()
clf = model.fit(mat, y)
print 'model trained'
s = model.score(mt, yt)
print s
| mit | Python |
|
9a33761f33c4f49a27d72944c231cb447353d81e | Add problem 10 | severinkaderli/Project-Euler-Python | 010.py | 010.py | #!/usr/bin/env python3
# Author: Severin Kaderli <severin.kaderli@gmail.com>
#
# Project Euler - Problem 10:
# Find the sum of all the primes below two million.
def get_prime_numbers(n):
"""Gets all prime numbers below n."""
primes, sieve = [], [True] * n
for i in range(2, n):
if sieve[i]:
primes.append(i)
for j in range(i*i, n, i):
sieve[j] = False
return primes
def get_prime_sum(n = 2000000):
"""Calculate the sum of all prime numbers below n."""
return sum(get_prime_numbers(n))
if __name__ == "__main__":
print(get_prime_sum(2000000))
| mit | Python |
|
d075d188d541090ad8d3a5c4cf583ba10063aa88 | Move timing to right location for staging. | ProjectFacet/facet,ProjectFacet/facet,ProjectFacet/facet,ProjectFacet/facet,ProjectFacet/facet | project/project/timing.py | project/project/timing.py | import time
from django.utils.deprecation import MiddlewareMixin
class TimingMiddleware(object):
"""Times a request and adds timing information to the content.
Adds an attribute, `_timing`, onto the request, and uses this at the end
of the rendering chain to find the time difference. It replaces a token in
the HTML, "<!-- RENDER_TIME -->", with the rendered time.
"""
# Keep these out here so they can be modified in Django settings.
REQUEST_ANNOTATION_KEY = "_timing"
REPLACE = b"<!-- RENDER_TIME -->"
REPLACE_TEMPLATE = b"<span>Handsomely rendered in %ims.</span>"
def __init__(self, get_response):
self.get_response = get_response
# One-time configuration and initialization.
def __call__(self, request):
setattr(request, self.REQUEST_ANNOTATION_KEY, time.time())
response = self.get_response(request)
then = getattr(request, self.REQUEST_ANNOTATION_KEY, None)
if then and hasattr(response, 'content'):
now = time.time()
msg = self.REPLACE_TEMPLATE % (int((now - then) * 1000))
response.content = response.content.replace(self.REPLACE, msg)
return response | mit | Python |
|
2e503a58a1f9893d25cf2dbb2c885bc9834faebf | Create urls.py | raiderrobert/django-webhook | tests/urls.py | tests/urls.py | from django.conf.urls import url, include
from webhook.base import WebhookBase
class WebhookView(WebhookBase):
def process_webhook(self, data, meta):
pass
urlpatterns = [
url(r'^webhook-receiver', WebhookView.as_view(), name='web_hook'),
]
| mit | Python |
|
0b3bfeb06a4594a2c188e623835c3a54262cca5d | Write initial Bible book HTML parser | caleb531/youversion-suggest,caleb531/youversion-suggest | utilities/book_parser.py | utilities/book_parser.py | # utilities.book_parser
# coding=utf-8
from __future__ import unicode_literals
import yvs.shared as shared
from HTMLParser import HTMLParser
class BookParser(HTMLParser):
# Resets parser variables (implicitly called on instantiation)
def reset(self):
HTMLParser.reset(self)
self.depth = 0
self.in_book = False
self.book_depth = 0
self.books = []
self.book_name_parts = []
# Detects the start of a book link
def handle_starttag(self, tag, attrs):
attr_dict = dict(attrs)
self.depth += 1
if 'data-book' in attr_dict:
self.in_book = True
self.book_depth = self.depth
self.books.append({
'id': attr_dict['data-book']
})
# Detects the end of a book link
def handle_endtag(self, tag):
if self.in_book and self.depth == self.book_depth:
self.in_book = False
self.books[-1]['name'] = ''.join(self.book_name_parts).strip()
# Empty the list containing the book name parts
del self.book_name_parts[:]
self.depth -= 1
# Handles the book name contained within the current book link
def handle_data(self, content):
if self.in_book:
self.book_name_parts.append(content)
# Handles all HTML entities within the book name
def handle_charref(self, name):
if self.in_book:
char = shared.eval_html_charref(name)
self.book_name_parts.append(char)
| mit | Python |
|
7b2d3aedbc2f78119974c9e724b37b2b336297d1 | Add device_hive_api.py | devicehive/devicehive-python | devicehive/device_hive_api.py | devicehive/device_hive_api.py | from devicehive.handler import Handler
from devicehive.device_hive import DeviceHive
class ApiCallHandler(Handler):
"""Api call handler class."""
def __init__(self, api, call, *call_args, **call_kwargs):
super(ApiCallHandler, self).__init__(api)
self._call = call
self._call_args = call_args
self._call_kwargs = call_kwargs
self._call_result = None
@property
def call_result(self):
return self._call_result
def handle_connect(self):
self._call_result = getattr(self.api, self._call)(*self._call_args,
**self._call_kwargs)
self.api.disconnect()
class DeviceHiveApi(object):
"""Device hive api class."""
def __init__(self, transport_url, **options):
self._transport_url = transport_url
self._options = options
def _call(self, call, *call_args, **call_kwargs):
device_hive = DeviceHive(ApiCallHandler, call, *call_args,
**call_kwargs)
device_hive.connect(self._transport_url, **self._options)
return device_hive.transport.handler.handler.call_result
def get_info(self):
return self._call('get_info')
def get_cluster_info(self):
return self._call('get_cluster_info')
| apache-2.0 | Python |
|
1d4e462188e95b1270d45f95112c2458cbeb7b2f | Add definitions.py | franckbrignoli/twitter-bot-detection | definitions.py | definitions.py |
def API_launch():
global app_config
global tweepy
# Twitter API configuration
consumer_key = app_config.twitter["consumer_key"]
consumer_secret = app_config.twitter["consumer_secret"]
access_token = app_config.twitter["access_token"]
access_token_secret = app_config.twitter["access_token_secret"]
# Start
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
return api
def followers_list(number_followers=200):
global api
followers = api.followers(count=number_followers)
followers_name = []
for follower in followers:
followers_name.append(str(follower.screen_name))
return followers_name
def create_db(database_name='bot_detection.db'):
global sqlite3
conn = sqlite3.connect(database_name)
def create_table(database_name='bot_detection.db'):
global sqlite3
conn = sqlite3.connect(database_name)
conn.execute('''CREATE TABLE TWEETS
(ID INT PRIMARY KEY NOT NULL,
NAME TEXT NOT NULL,
DATE TEXT NOT NULL,
TEXT TEXT NOT NULL,
MENTIONS TEXT NOT NULL);''')
conn.close()
def feed_table(ID ,NAME,DATE ,TEXT,MENTIONS,database_name='bot_detection.db'):
global sqlite3
conn = sqlite3.connect(database_name)
conn.execute("INSERT INTO TWEETS (ID,NAME,DATE,TEXT,MENTIONS) VALUES (?,?,?,?,?)"
,(ID, NAME ,DATE,TEXT, MENTIONS))
conn.commit()
conn.close()
def tweet_info(follower,tweets_number=100):
global api
global json
global unicodedata
user_info = api.user_timeline(screen_name = follower,count = tweets_number)
tweet = {}
name_mentions = []
for i,status in enumerate(user_info):
tweet = status._json
text = tweet['text']
date = tweet['created_at']
entities = tweet['entities']
user_mentions = entities['user_mentions']
for mention in user_mentions:
dict_mentions = mention
name_mentions = dict_mentions['screen_name']
ID_string = i
name_string = follower
text_string = unicodedata.normalize('NFKD', text).encode('ascii','ignore')
date_string = unicodedata.normalize('NFKD', date).encode('ascii','ignore')
name_mentions_string = unicodedata.normalize('NFKD', name_mentions).encode('ascii','ignore')
feed_table(ID_string,
name_string,
text_string,
date_string,
name_mentions_string)
| mit | Python |
|
32067112c7e0d681b84975b0e9b2fe974f1440ac | Add IINet module | teto/i3pystatus,schroeji/i3pystatus,richese/i3pystatus,eBrnd/i3pystatus,yang-ling/i3pystatus,enkore/i3pystatus,facetoe/i3pystatus,enkore/i3pystatus,fmarchenko/i3pystatus,teto/i3pystatus,richese/i3pystatus,drwahl/i3pystatus,Arvedui/i3pystatus,eBrnd/i3pystatus,facetoe/i3pystatus,fmarchenko/i3pystatus,juliushaertl/i3pystatus,ncoop/i3pystatus,juliushaertl/i3pystatus,ncoop/i3pystatus,asmikhailov/i3pystatus,yang-ling/i3pystatus,m45t3r/i3pystatus,asmikhailov/i3pystatus,m45t3r/i3pystatus,drwahl/i3pystatus,schroeji/i3pystatus,Arvedui/i3pystatus | i3pystatus/iinet.py | i3pystatus/iinet.py | import requests
from i3pystatus import IntervalModule
from i3pystatus.core.color import ColorRangeModule
__author__ = 'facetoe'
class IINet(IntervalModule, ColorRangeModule):
"""
Check IINet Internet usage.
Requires `requests` and `colour`
Formatters:
* `{percentage_used}` — percentage of your quota that is used
* `{percentage_available}` — percentage of your quota that is available
"""
settings = (
"format",
("username", "Username for IINet"),
("password", "Password for IINet"),
("start_color", "Beginning color for color range"),
("end_color", "End color for color range")
)
format = '{percent_used}'
start_color = "#00FF00"
end_color = "#FF0000"
username = None
password = None
keyring_backend = None
def init(self):
self.token = None
self.service_token = None
self.colors = self.get_hex_color_range(self.start_color, self.end_color, 100)
def set_tokens(self):
if not self.token or not self.service_token:
response = requests.get('https://toolbox.iinet.net.au/cgi-bin/api.cgi?'
'_USERNAME=%(username)s&'
'_PASSWORD=%(password)s'
% self.__dict__).json()
if self.valid_response(response):
self.token = response['token']
self.service_token = self.get_service_token(response['response']['service_list'])
else:
raise Exception("Failed to retrieve token for user: %s" % self.username)
def get_service_token(self, service_list):
for service in service_list:
if service['pk_v'] == self.username:
return service['s_token']
raise Exception("Failed to retrieve service token for user: %s" % self.username)
def valid_response(self, response):
return "success" in response and response['success'] == 1
def run(self):
self.set_tokens()
usage = self.get_usage()
allocation = usage['allocation']
used = usage['used']
percent_used = self.percentage(used, allocation)
percent_avaliable = self.percentage(allocation - used, allocation)
color = self.get_gradient(percent_used, self.colors)
usage['percent_used'] = '{0:.2f}%'.format(percent_used)
usage['percent_available'] = '{0:.2f}%'.format(percent_avaliable)
self.output = {
"full_text": self.format.format(**usage),
"color": color
}
def get_usage(self):
response = requests.get('https://toolbox.iinet.net.au/cgi-bin/api.cgi?Usage&'
'_TOKEN=%(token)s&'
'_SERVICE=%(service_token)s' % self.__dict__).json()
if self.valid_response(response):
for traffic_type in response['response']['usage']['traffic_types']:
if traffic_type['name'] == 'anytime':
return traffic_type
else:
raise Exception("Failed to retrieve usage information for: %s" % self.username)
| mit | Python |
|
045a10457cd87e37ef5862de55e344db5e9228cf | Add configfile.py | jhogan/commonpy,jhogan/epiphany-py | configfile.py | configfile.py | # vim: set et ts=4 sw=4 fdm=marker
"""
MIT License
Copyright (c) 2016 Jesse Hogan
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
# TODO Write Tests
from entities import *
from accounts import *
import yaml
class configfile(entity):
_instance = None
@classmethod
def getinstance(cls):
if cls._instance == None:
cls._instance = configfile()
return cls._instance
@property
def file(self):
return self._file
@file.setter
def file(self, v):
self._file = v
self.load()
@property
def accounts(self):
return self._accounts
@accounts.setter
def accounts(self, v):
self._accounts = v
def clear(self):
self._accounts = accounts()
def load(self):
self.clear()
with open(self.file, 'r') as stream:
cfg = yaml.load(stream)
for acct in cfg['accounts']:
self.accounts += account.create(acct)
| mit | Python |
|
2275ae52e336bd2e07e32fa3a2559926734c3567 | add pyunit for PUBDEV-1480 | mathemage/h2o-3,h2oai/h2o-dev,madmax983/h2o-3,pchmieli/h2o-3,YzPaul3/h2o-3,michalkurka/h2o-3,mathemage/h2o-3,mathemage/h2o-3,h2oai/h2o-3,h2oai/h2o-dev,mathemage/h2o-3,h2oai/h2o-3,h2oai/h2o-dev,h2oai/h2o-3,jangorecki/h2o-3,YzPaul3/h2o-3,jangorecki/h2o-3,h2oai/h2o-3,michalkurka/h2o-3,h2oai/h2o-dev,michalkurka/h2o-3,madmax983/h2o-3,michalkurka/h2o-3,madmax983/h2o-3,h2oai/h2o-3,pchmieli/h2o-3,pchmieli/h2o-3,pchmieli/h2o-3,madmax983/h2o-3,jangorecki/h2o-3,spennihana/h2o-3,h2oai/h2o-dev,spennihana/h2o-3,spennihana/h2o-3,YzPaul3/h2o-3,h2oai/h2o-dev,YzPaul3/h2o-3,michalkurka/h2o-3,spennihana/h2o-3,madmax983/h2o-3,mathemage/h2o-3,spennihana/h2o-3,h2oai/h2o-3,YzPaul3/h2o-3,h2oai/h2o-3,pchmieli/h2o-3,jangorecki/h2o-3,michalkurka/h2o-3,michalkurka/h2o-3,jangorecki/h2o-3,spennihana/h2o-3,h2oai/h2o-dev,YzPaul3/h2o-3,madmax983/h2o-3,h2oai/h2o-3,mathemage/h2o-3,spennihana/h2o-3,madmax983/h2o-3,jangorecki/h2o-3,YzPaul3/h2o-3,pchmieli/h2o-3,mathemage/h2o-3,pchmieli/h2o-3,jangorecki/h2o-3 | h2o-py/tests/testdir_jira/pyunit_NOPASS_INTERNAL_pubdev_1480_medium.py | h2o-py/tests/testdir_jira/pyunit_NOPASS_INTERNAL_pubdev_1480_medium.py | import sys, os
sys.path.insert(1, "../../")
import h2o, tests
def pubdev_1480():
if not tests.hadoop_namenode_is_accessible(): raise(EnvironmentError, "Not running on H2O internal network. No access to HDFS.")
train = h2o.import_file("hdfs://mr-0xd6/datasets/kaggle/sf.crime.train.gz")
test = h2o.import_file("hdfs://mr-0xd6/datasets/kaggle/sf.crime.test.gz")
model = h2o.gbm(x=train[range(2,9)], y=train[1])
predictions = model.predict(test)
results_dir = os.path.normpath(os.path.join(os.path.dirname(os.path.realpath(__file__)),"..","results"))
h2o.download_csv(predictions, os.path.join(results_dir,"predictions.csv"))
if __name__ == "__main__":
tests.run_test(sys.argv, pubdev_1480)
| apache-2.0 | Python |
|
b16f6ea8a723fa064a78e014ab767be1a797e613 | Create cab.py | stkyle/stk,stkyle/stk,stkyle/stk | cab.py | cab.py | """
Work with *.cab files
"""
from ctypes import pythonapi
from ctypes import cdll
from ctypes import cast
import ctypes as _ctypes
libc = cdll[_ctypes.util.find_library('c')]
libcab = cdll[_ctypes.util.find_library('cabinet')]
PyMem_Malloc = pythonapi.PyMem_Malloc
PyMem_Malloc.restype = _ctypes.c_size_t
PyMem_Malloc.argtypes = [_ctypes.c_size_t]
strncpy = libc.strncpy
strncpy.restype = _ctypes.c_char_p
strncpy.argtypes = [_ctypes.c_char_p, _ctypes.c_char_p, _ctypes.c_size_t]
HOOKFUNC = _ctypes.CFUNCTYPE(_ctypes.c_char_p, _ctypes.c_void_p, _ctypes.c_void_p, _ctypes.c_char_p)
# typedef struct {
# DWORD cbStruct;
# DWORD dwReserved1;
# DWORD dwReserved2;
# DWORD dwFileVersionMS;
# DWORD dwFileVersionLS;
# } CABINETDLLVERSIONINFO, *PCABINETDLLVERSIONINFO;
class CABINETDLLVERSIONINFO(_ctypes.Structure):
_fields_ = [('cbStruct', _ctypes.c_double),
('dwReserved1', _ctypes.c_double),
('dwReserved2', _ctypes.c_double),
('dwFileVersionMS', _ctypes.c_double),
('dwFileVersionLS', _ctypes.c_double)]
libcab.DllGetVersion.restype = CABINETDLLVERSIONINFO
| mit | Python |
|
e17adde73c146ded7ed5a1a347f104a5e7a09f62 | Add bzl macro. | google/tink,google/tink,google/tink,google/tink,google/tink,google/tink,google/tink,google/tink | tools/testing/python/py23.bzl | tools/testing/python/py23.bzl | """Macro to generate python 2 and 3 binaries."""
def py23_binary(name, **kwargs):
"""Generates python 2 and 3 binaries. Accepts any py_binary arguments."""
native.py_binary(
name = name + "2",
python_version = "PY2",
**kwargs
)
native.py_binary(
name = name + "3",
python_version = "PY3",
**kwargs
)
| apache-2.0 | Python |
|
596f432eb7d4b3fa5d1bf5dec33cc882546e8233 | Add a script to convert a GRLevelX colortable file to a dict data structure (and optionally boundaries for norm) for use with Matplotlib. | ahill818/MetPy,ahaberlie/MetPy,ahaberlie/MetPy,Unidata/MetPy,Unidata/MetPy,jrleeman/MetPy,ShawnMurd/MetPy,dopplershift/MetPy,deeplycloudy/MetPy,jrleeman/MetPy,dopplershift/MetPy | trunk/metpy/vis/util/gr2_to_mpl_colortable.py | trunk/metpy/vis/util/gr2_to_mpl_colortable.py | #!/usr/bin/env python
# This script is used to convert colortables from GRLevelX to data for a
# matplotlib colormap
import sys
from optparse import OptionParser
#Set up command line options
opt_parser = OptionParser(usage="usage: %prog [options] colortablefile")
opt_parser.add_option("-s", "--scale", action="store_true", dest="scale",
help="Scale size of colortable entries by thresholds in file.")
opts,args = opt_parser.parse_args()
if not args:
print "You must pass the colortable file as the commandline argument."
opt_parser.print_help()
sys.exit(-1)
fname = args[0]
scaleTable = opts.scale
colors = []
thresholds = []
#Initial color should end up not used by MPL
prev = [0., 0., 0.]
for line in open(fname, 'r'):
if line.startswith("Color:"):
# This ignores the word "Color:" and the threshold
# and converts the rest to float
parts = line.split()
thresholds.append(float(parts[1]))
color_info = [float(x)/255. for x in parts[2:]]
if not prev:
prev = info[:3]
colors.append(zip(prev, color_info[:3]))
prev = color_info[3:]
# Add the last half of the last line, if necessary
if prev:
colors.append(zip(prev,prev))
colordict = dict(red=[], green=[], blue=[])
num_entries = float(len(colors) - 1)
offset = min(thresholds)
scale = 1. / (max(thresholds) - offset)
for i,(t,(r,g,b)) in enumerate(zip(thresholds, colors)):
if scaleTable:
norm = (t - offset) * scale
else:
norm = i / num_entries
colordict['red'].append((norm,) + r)
colordict['green'].append((norm,) + g)
colordict['blue'].append((norm,) + b)
# Output as code that can be copied and pasted into a python script. Repr()
# would work here, but wouldn't be as human-readable.
print '{'
num_colors = len(colordict.keys())
for n,k in enumerate(sorted(colordict.keys())):
print "'%s' :" % k
num = len(colordict[k])
for i,line in enumerate(colordict[k]):
if i == 0:
print ' [%s,' % repr(line)
elif i == num - 1:
if n == num_colors - 1:
print ' %s]' % repr(line)
else:
print ' %s],' % repr(line)
else:
print " %s," % repr(line)
print '}'
if not scaleTable:
print repr(thresholds)
| bsd-3-clause | Python |
|
a041c683475f78d6101fe1741a561a6c00492007 | add pautils, to host various utility functions like loading the P2TH keys into the local or remote node over JSON-RPC. | PeerAssets/pypeerassets,backpacker69/pypeerassets | pypeerassets/pautils.py | pypeerassets/pautils.py |
'''miscellaneous utilities.'''
def testnet_or_mainnet(node):
'''check if local node is configured to testnet or mainnet'''
q = node.getinfo()
if q["testnet"] is True:
return "testnet"
else:
return "mainnet"
def load_p2th_privkeys_into_node(node):
if testnet_or_mainnet(node) is "testnet":
assert testnet_PAPROD_addr in node.getaddressbyaccount()
try:
node.importprivkey(testnet_PAPROD)
assert testnet_PAPROD_addr in node.getaddressbyaccount()
except Exception:
return {"error": "Loading P2TH privkey failed."}
else:
try:
node.importprivkey(mainnet_PAPROD)
assert mainnet_PAPROD_addr in node.getaddressbyaccount()
except Exception:
return {"error": "Loading P2TH privkey failed."}
def load_test_p2th_privkeys_into_node(node):
if testnet_or_mainnet(node) is "testnet":
try:
node.importprivkey(testnet_PATEST)
assert testnet_PATEST_addr in node.getaddressbyaccount()
except Exception:
return {"error": "Loading P2TH privkey failed."}
else:
try:
node.importprivkey(mainnet_PATEST)
assert mainnet_PATEST_addr in node.getaddressbyaccount()
except Exception:
return {"error": "Loading P2TH privkey failed."}
| bsd-3-clause | Python |
|
7012a90cd1468da95c8939a0f0c1193766595ae8 | Add event spooler module | ColtonProvias/pytest-watch,rakjin/pytest-watch,blueyed/pytest-watch,joeyespo/pytest-watch | pytest_watch/spooler.py | pytest_watch/spooler.py | # -*- coding: utf-8
from multiprocessing import Queue, Process, Event
class Timer(Process):
def __init__(self, interval, function, args=[], kwargs={}):
super(Timer, self).__init__()
self.interval = interval
self.function = function
self.args = args
self.kwargs = kwargs
self.finished = Event()
def cancel(self):
self.finished.set()
def run(self):
self.finished.wait(self.interval)
if not self.finished.is_set():
self.function(*self.args, **self.kwargs)
self.finished.set()
class EventSpooler(object):
def __init__(self, cooldown, callback):
self.cooldown = cooldown
self.callback = callback
self.inbox = Queue()
self.outbox = Queue()
def enqueue(self, event):
self.inbox.put(event)
Timer(self.cooldown, self.process).start()
def process(self):
self.outbox.put(self.inbox.get())
if self.inbox.empty():
self.callback([self.outbox.get() for _ in range(self.outbox.qsize())])
| mit | Python |
|
0ff9373de6e11d7040b6b289cb3239a9ee9a924d | Fix haproxy agent unit test to be runnable alone by tox | aristanetworks/neutron,takeshineshiro/neutron,redhat-openstack/neutron,bigswitch/neutron,glove747/liberty-neutron,mattt416/neutron,vijayendrabvs/hap,suneeth51/neutron,sasukeh/neutron,chitr/neutron,asgard-lab/neutron,Juniper/neutron,infobloxopen/neutron,jumpojoy/neutron,huntxu/neutron,alexandrucoman/vbox-neutron-agent,netscaler/neutron,vveerava/Openstack,shahbazn/neutron,jacknjzhou/neutron,SmartInfrastructures/neutron,openstack/neutron,vveerava/Openstack,vbannai/neutron,JioCloud/neutron,vijayendrabvs/hap,barnsnake351/neutron,wolverineav/neutron,vijayendrabvs/ssl-neutron,klmitch/neutron,Comcast/neutron,leeseuljeong/leeseulstack_neutron,NeCTAR-RC/neutron,pnavarro/neutron,cloudbase/neutron,bigswitch/neutron,kaiweifan/neutron,zhhf/charging,cloudbase/neutron-virtualbox,bgxavier/neutron,rdo-management/neutron,javaos74/neutron,infobloxopen/neutron,eonpatapon/neutron,zhhf/charging,noironetworks/neutron,yamahata/neutron,yamahata/tacker,antonioUnina/neutron,sajuptpm/neutron-ipam,paninetworks/neutron,leeseulstack/openstack,citrix-openstack-build/neutron,citrix-openstack-build/neutron,eonpatapon/neutron,vijayendrabvs/hap,virtualopensystems/neutron,neoareslinux/neutron,blueboxgroup/neutron,kaiweifan/neutron,sajuptpm/neutron-ipam,dims/neutron,klmitch/neutron,javaos74/neutron,SamYaple/neutron,jacknjzhou/neutron,vbannai/neutron,mattt416/neutron,rickerc/neutron_audit,MaximNevrov/neutron,paninetworks/neutron,pnavarro/neutron,Juniper/contrail-dev-neutron,SmartInfrastructures/neutron,eayunstack/neutron,Stavitsky/neutron,netscaler/neutron,igor-toga/local-snat,takeshineshiro/neutron,NeCTAR-RC/neutron,waltBB/neutron_read,cernops/neutron,Metaswitch/calico-neutron,jerryz1982/neutron,yamahata/tacker,wenhuizhang/neutron,igor-toga/local-snat,vivekanand1101/neutron,beagles/neutron_hacking,rickerc/neutron_audit,Juniper/neutron,rickerc/neutron_audit,silenci/neutron,cisco-openstack/neutron,vveerava/Openstack,vivekanand1101/neutron,bgxavier/neutron,beagles/neutron_hacking,miyakz1192/neutron,netscaler/neutron,kaiweifan/neutron,dhanunjaya/neutron,aristanetworks/neutron,skyddv/neutron,JioCloud/neutron,virtualopensystems/neutron,neoareslinux/neutron,Juniper/contrail-dev-neutron,watonyweng/neutron,leeseulstack/openstack,adelina-t/neutron,JianyuWang/neutron,blueboxgroup/neutron,CiscoSystems/neutron,barnsnake351/neutron,Stavitsky/neutron,yanheven/neutron,sebrandon1/neutron,virtualopensystems/neutron,magic0704/neutron,huntxu/neutron,vijayendrabvs/ssl-neutron,sajuptpm/neutron-ipam,mmnelemane/neutron,antonioUnina/neutron,leeseuljeong/leeseulstack_neutron,mandeepdhami/neutron,asgard-lab/neutron,projectcalico/calico-neutron,Juniper/contrail-dev-neutron,sasukeh/neutron,vbannai/neutron,apporc/neutron,blueboxgroup/neutron,swdream/neutron,yanheven/neutron,Comcast/neutron,wenhuizhang/neutron,wolverineav/neutron,jumpojoy/neutron,leeseuljeong/leeseulstack_neutron,openstack/neutron,Comcast/neutron,CiscoSystems/neutron,waltBB/neutron_read,yamahata/neutron,mahak/neutron,oeeagle/quantum,zhhf/charging,noironetworks/neutron,CiscoSystems/vespa,swdream/neutron,SamYaple/neutron,apporc/neutron,yuewko/neutron,yuewko/neutron,miyakz1192/neutron,gkotton/neutron,mahak/neutron,dims/neutron,citrix-openstack-build/neutron,dhanunjaya/neutron,openstack/neutron,CiscoSystems/vespa,oeeagle/quantum,ntt-sic/neutron,sebrandon1/neutron,watonyweng/neutron,yamahata/tacker,mandeepdhami/neutron,cisco-openstack/neutron,Juniper/neutron,mahak/neutron,skyddv/neutron,cloudbase/neutron-virtualbox,yamahata/neutron,cernops/neutron,shahbazn/neutron,adelina-t/neutron,vijayendrabvs/ssl-neutron,leeseulstack/openstack,gkotton/neutron,gopal1cloud/neutron,gopal1cloud/neutron,MaximNevrov/neutron,CiscoSystems/vespa,redhat-openstack/neutron,eayunstack/neutron,cloudbase/neutron,CiscoSystems/neutron,projectcalico/calico-neutron,Metaswitch/calico-neutron,ntt-sic/neutron,ntt-sic/neutron,alexandrucoman/vbox-neutron-agent,beagles/neutron_hacking,glove747/liberty-neutron,mmnelemane/neutron,rdo-management/neutron,gkotton/neutron,silenci/neutron,JianyuWang/neutron,suneeth51/neutron,chitr/neutron,jerryz1982/neutron,magic0704/neutron | neutron/tests/unit/services/loadbalancer/drivers/haproxy/test_agent.py | neutron/tests/unit/services/loadbalancer/drivers/haproxy/test_agent.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright 2013 New Dream Network, LLC (DreamHost)
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
#
# @author: Mark McClain, DreamHost
import contextlib
import mock
from oslo.config import cfg
from neutron.services.loadbalancer.drivers.haproxy import agent
from neutron.tests import base
class TestLbaasService(base.BaseTestCase):
def setUp(self):
super(TestLbaasService, self).setUp()
self.addCleanup(cfg.CONF.reset)
def test_start(self):
with mock.patch.object(
agent.rpc_service.Service, 'start'
) as mock_start:
mgr = mock.Mock()
agent_service = agent.LbaasAgentService('host', 'topic', mgr)
agent_service.start()
self.assertTrue(mock_start.called)
def test_main(self):
logging_str = 'neutron.agent.common.config.setup_logging'
with contextlib.nested(
mock.patch(logging_str),
mock.patch.object(agent.service, 'launch'),
mock.patch.object(agent, 'eventlet'),
mock.patch('sys.argv'),
mock.patch.object(agent.manager, 'LbaasAgentManager'),
mock.patch.object(cfg.CONF, 'register_opts')
) as (mock_logging, mock_launch, mock_eventlet, sys_argv, mgr_cls, ro):
agent.main()
self.assertTrue(mock_eventlet.monkey_patch.called)
mock_launch.assert_called_once_with(mock.ANY)
| # vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright 2013 New Dream Network, LLC (DreamHost)
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
#
# @author: Mark McClain, DreamHost
import contextlib
import mock
from oslo.config import cfg
from neutron.services.loadbalancer.drivers.haproxy import agent
from neutron.tests import base
class TestLbaasService(base.BaseTestCase):
def setUp(self):
super(TestLbaasService, self).setUp()
self.addCleanup(cfg.CONF.reset)
cfg.CONF.register_opts(agent.OPTS)
def test_start(self):
with mock.patch.object(
agent.rpc_service.Service, 'start'
) as mock_start:
mgr = mock.Mock()
agent_service = agent.LbaasAgentService('host', 'topic', mgr)
agent_service.start()
self.assertTrue(mock_start.called)
def test_main(self):
logging_str = 'neutron.agent.common.config.setup_logging'
with contextlib.nested(
mock.patch(logging_str),
mock.patch.object(agent.service, 'launch'),
mock.patch.object(agent, 'eventlet'),
mock.patch('sys.argv'),
mock.patch.object(agent.manager, 'LbaasAgentManager')
) as (mock_logging, mock_launch, mock_eventlet, sys_argv, mgr_cls):
agent.main()
self.assertTrue(mock_eventlet.monkey_patch.called)
mock_launch.assert_called_once_with(mock.ANY)
| apache-2.0 | Python |
e4ef868660878e1ad1749be915b88ab6fea929b5 | Add asyncio example | timofurrer/w1thermsensor,timofurrer/w1thermsensor | examples/async.py | examples/async.py | """
w1thermsensor
~~~~~~~~~~~~~
A Python package and CLI tool to work with w1 temperature sensors.
:copyright: (c) 2020 by Timo Furrer <tuxtimo@gmail.com>
:license: MIT, see LICENSE for more details.
"""
import asyncio
from w1thermsensor import AsyncW1ThermSensor
async def main():
# initialize sensor with first available sensor
sensor = AsyncW1ThermSensor()
# continuously read temperature from sensor
while True:
temperature = await sensor.get_temperature()
print(f"Temperature: {temperature:.3f}")
await asyncio.sleep(1)
if __name__ == "__main__":
asyncio.run(main())
| mit | Python |
|
ef4aeb1e16245c76e7d10091b6fc8b0b289d635f | Split IP validation to a module | danclegg/py-sony | validateIp.py | validateIp.py | #!/usr/bin/env python
import socket
def parse(ip):
# parse and validate ip address
try:
socket.inet_pton(socket.AF_INET,ip)
return "valid"
except socket.error, e:
try:
socket.inet_pton(socket.AF_INET6,ip)
return "valid"
except:
print "ERROR: %s" % e
| apache-2.0 | Python |
|
d0ce887da3043106da1b875a46b6fe1bc0ce7145 | Create 0018_auto_20201109_0655.py | PeteAndersen/swarfarm,porksmash/swarfarm,PeteAndersen/swarfarm,porksmash/swarfarm,porksmash/swarfarm,porksmash/swarfarm,PeteAndersen/swarfarm,PeteAndersen/swarfarm | herders/migrations/0018_auto_20201109_0655.py | herders/migrations/0018_auto_20201109_0655.py | # Generated by Django 2.2.17 on 2020-11-09 14:55
import django.contrib.postgres.fields
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('herders', '0017_auto_20200808_1642'),
]
operations = [
migrations.AlterField(
model_name='artifactinstance',
name='effects_value',
field=django.contrib.postgres.fields.ArrayField(base_field=models.FloatField(blank=True, null=True), blank=True, default=list, help_text='Bonus value of this effect', size=4),
),
]
| apache-2.0 | Python |
|
f9db946f9b067495d2785d46efe447371e22eb26 | Add tex2pdf function | PythonSanSebastian/docstamp | docstamp/pdflatex.py | docstamp/pdflatex.py | # coding=utf-8
# -------------------------------------------------------------------------------
# Author: Alexandre Manhaes Savio <alexsavio@gmail.com>
# Grupo de Inteligencia Computational <www.ehu.es/ccwintco>
# Universidad del Pais Vasco UPV/EHU
#
# 2015, Alexandre Manhaes Savio
# Use this at your own risk!
# -------------------------------------------------------------------------------
import os
import shutil
import os.path as op
from glob import glob
from .commands import call_command
from .filenames import remove_ext
def tex2pdf(tex_file, output_file=None, output_format='pdf'):
""" Call PDFLatex to convert TeX files to PDF.
Parameters
----------
tex_file: str
Path to the input LateX file.
output_file: str
Path to the output PDF file.
If None, will use the same output directory as the tex_file.
output_format: str
Output file format. Choices: 'pdf' or 'dvi'. Default: 'pdf'
Returns
-------
return_value
PDFLatex command call return value.
"""
if not op.exists(tex_file):
raise IOError('Could not find file {}.'.format(tex_file))
if output_format != 'pdf' and output_format != 'dvi':
raise ValueError("Invalid output format given {}. Can only accept 'pdf' or 'dvi'.".format(output_format))
cmd_name = 'pdflatex'
args_strings = ' '
if output_file is not None:
args_strings += '-output-directory={} '.format(op.abspath(op.dirname(output_file)))
if output_file:
args_strings += '-output-format={} '.format(output_format)
result_dir = op.dirname(output_file)
else:
result_dir = op.dirname(tex_file)
args_strings += tex_file
ret = call_command(cmd_name, args_strings.split())
result_file = op.join(result_dir, remove_ext(op.basename(tex_file)) + '.' + output_format)
if op.exists(result_file):
shutil.move(result_file, output_file)
else:
raise IOError('Could not find PDFLatex result file.')
[os.remove(f) for f in glob(op.join(result_dir, '*.aux'))]
[os.remove(f) for f in glob(op.join(result_dir, '*.log'))]
return ret
| apache-2.0 | Python |
|
96a9d00ea20dee3ffd9114b4a094868ed7ae2413 | add createmask.py | DuinoDu/label_ellipse | createMask.py | createMask.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
python createmask.py [voc-like dir]
'''
import os, sys
import numpy as np
import cv2
def parsexml(xmlfile):
tree = ET.parse(xmlfile)
width = int(tree.find('size').find('width').text)
height = int(tree.find('size').find('height').text)
objs = tree.findall('object')
for index, obj in enumerate(objs):
name = obj.find('name').text.lower()
bbox = obj.find('bndbox')
x0 = int(bbox.find('x').text)
y0 = int(bbox.find('y').text)
a = int(bbox.find('a').text)
b = int(bbox.find('b').text)
angle = int(bbox.find('angle').text)
break
return width, height, x, y, a, b, angle
def createmask(argv):
annodir = os.path.join(argv[0], 'Annotations')
maskdir = os.path.join(argv[0], 'JPEGImagesMask')
if not os.path.exists(maskdir):
os.makedirs(maskdir)
annofiles = sorted([os.path.join(annodir, x) for x in sorted(os.listdir(annodir)) if x.endswith('.xml')])
for xmlfile in annofiles:
w, h, x, y, a, b, angle = parsexml(xmlfile)
img = np.zeros(shape=(h, w, 1))
delta = 4
cv2.ellipse(img, (x, y), (a-delta, b-delta), anble, 0, 360, 255, -1)
cv2.imshow(img)
cv2.waitKey(0)
return
def main():
import sys
if len(sys.argv) != 2:
print(__doc__)
return
createmask(sys.argv)
if __name__ == "__main__":
main()
| mit | Python |
|
45bc2562d3afd3674929e56425b597b54e74ba24 | Create Legends.py | mayankdcoder/Matplotlib | Legends.py | Legends.py | #Draws Legends, Titles and Labels using matplotlib
import matplotlib.pyplot as plt
x = [1, 2, 3]
y = [5, 7, 4]
x1 = [1, 2, 3]
y1 = [10, 14, 12]
plt.plot(x, y, label='First Line')
plt.plot(x1, y1, label='Second Line')
plt.xlabel('X Axis')
plt.ylabel('Y Axis')
plt.title('This is a Title')
plt.legend()
plt.show()
| mit | Python |
|
3adbcb8bc7fb4c805e7933a362b62f70873d4f9f | Add emergency_scale module | Yelp/paasta,Yelp/paasta,somic/paasta,gstarnberger/paasta,gstarnberger/paasta,somic/paasta | paasta_tools/paasta_cli/cmds/emergency_scale.py | paasta_tools/paasta_cli/cmds/emergency_scale.py | #!/usr/bin/env python
# Copyright 2015 Yelp Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from service_configuration_lib import DEFAULT_SOA_DIR
from paasta_tools.paasta_cli.utils import execute_paasta_serviceinit_on_remote_master
from paasta_tools.paasta_cli.utils import figure_out_service_name
from paasta_tools.paasta_cli.utils import lazy_choices_completer
from paasta_tools.paasta_cli.utils import list_services
from paasta_tools.paasta_cli.utils import list_instances
from paasta_tools.utils import compose_job_id
from paasta_tools.utils import list_clusters
def add_subparser(subparsers):
status_parser = subparsers.add_parser(
'emergency-scale',
description="Scale a PaaSTA service instance",
help=("Scale a PaaSTA service instance by scaling it up or down to n instances (for Marathon apps)"))
status_parser.add_argument(
'-s', '--service',
help="Service that you want to scale. Like 'example_service'.",
).completer = lazy_choices_completer(list_services)
status_parser.add_argument(
'-i', '--instance',
help="Instance of the service that you want to scale. Like 'main' or 'canary'.",
required=True,
).completer = lazy_choices_completer(list_instances)
status_parser.add_argument(
'-c', '--cluster',
help="The PaaSTA cluster that has the service instance you want to scale. Like 'norcal-prod'.",
required=True,
).completer = lazy_choices_completer(list_clusters)
status_parser.add_argument(
'-a', '--appid',
help="The complete marathon appid to scale. Like 'example-service.main.gitf0cfd3a0.config7a2a00b7",
required=False,
)
status_parser.add_argument(
'-y', '--yelpsoa-config-root',
default=DEFAULT_SOA_DIR,
required=False,
help="Path to root of yelpsoa-configs checkout",
)
status_parser.add_argument(
'--delta',
default=0,
required=True,
help="Number of instances you want to scale up (positive number) or down (negative number)",
)
status_parser.set_defaults(command=paasta_emergency_scale)
def paasta_emergency_scale(args):
"""Performs an emergency scale on a given service instance on a given cluster
Warning: This command does not permanently scale the service. The next time the service is updated
(config change, deploy, bounce, etc.), those settings will override the emergency scale.
If you want this scale to be permanant, adjust the relevant config file to reflect that.
For example, this can be done for Marathon apps by setting 'instances: n'
"""
service = figure_out_service_name(args, soa_dir=args.yelpsoa_config_root)
print "Performing an emergency scale on %s..." % compose_job_id(service, args.instance)
output = execute_paasta_serviceinit_on_remote_master('scale', args.cluster, service, args.instance,
app_id=args.appid, delta=args.delta)
print "Output: %s" % output
print "%s" % "\n".join(paasta_emergency_scale.__doc__.splitlines()[-7:])
| apache-2.0 | Python |
|
29090add692e6c32a75e123be6cd201949efd6ce | Add elasticsearch-administer | qedsoftware/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq | scripts/elasticsearch-administer.py | scripts/elasticsearch-administer.py | """
Utilities for administering elasticsearch
"""
from argparse import ArgumentParser, RawDescriptionHelpFormatter
from collections import namedtuple
import json
import sys
from elasticsearch import Elasticsearch
from elasticsearch.client import ClusterClient, NodesClient, CatClient
def pprint(data):
print json.dumps(data, indent=4)
def confirm(msg):
if raw_input(msg + "\n(y/n)") != 'y':
sys.exit()
Node = namedtuple("Node", "name node_id docs")
def get_nodes_info(es):
nc = NodesClient(es)
stats = nc.stats(metric="indices", index_metric="docs")
return [Node(info['name'], node_id, info['indices']['docs'])
for node_id, info in stats['nodes'].items()]
def cluster_status(es):
cluster = ClusterClient(es)
print "\nCLUSTER HEALTH"
pprint(cluster.health())
print "\nPENDING TASKS"
pprint(cluster.pending_tasks())
print "\nNODES"
for node in get_nodes_info(es):
print node.name, node.docs
print "\nSHARD ALLOCATION"
cat = CatClient(es)
print cat.allocation(v=True)
def shard_status(es):
cat = CatClient(es)
print cat.shards(v=True)
def cluster_settings(es):
cluster = ClusterClient(es)
pprint(cluster.get_settings())
def decommission_node(es):
cluster = ClusterClient(es)
print "The nodes are:"
nodes = get_nodes_info(es)
for node in nodes:
print node.name, node.docs
confirm("Are you sure you want to decommission a node?")
node_name = raw_input("Which one would you like to decommission?\nname:")
names = [node.name for node in nodes]
if node_name not in names:
print "You must enter one of {}".format(", ".join(names))
return
confirm("This will remove all shards from {}, okay?".format(node_name))
cmd = {"transient": {"cluster.routing.allocation.exclude._name": node_name}}
pprint(cluster.put_settings(cmd))
print "The node is now being decommissioned."
commands = {
'cluster_status': cluster_status,
'cluster_settings': cluster_settings,
'decommission_node': decommission_node,
'shard_status': shard_status,
}
def main():
parser = ArgumentParser(description=__doc__, formatter_class=RawDescriptionHelpFormatter)
parser.add_argument('host_url')
parser.add_argument('command', choices=commands.keys())
args = parser.parse_args()
es = Elasticsearch([{'host': args.host_url, 'port': 9200}])
commands[args.command](es)
if __name__ == "__main__":
main()
| bsd-3-clause | Python |
|
eee700f46e1edee1133722ee94992abda1ad6a4c | Add GYP build for zlib | AlphaStaxLLC/rackspace-monitoring-agent,cp16net/virgo-base,cp16net/virgo-base,cp16net/virgo-base,cp16net/virgo-base,virgo-agent-toolkit/rackspace-monitoring-agent,kaustavha/rackspace-monitoring-agent,AlphaStaxLLC/rackspace-monitoring-agent,kaustavha/rackspace-monitoring-agent,christopherjwang/rackspace-monitoring-agent,cp16net/virgo-base,christopherjwang/rackspace-monitoring-agent,virgo-agent-toolkit/rackspace-monitoring-agent | deps/zlib.gyp | deps/zlib.gyp | {
'target_defaults': {
'conditions': [
['OS != "win"', {
'defines': [
'_LARGEFILE_SOURCE',
'_FILE_OFFSET_BITS=64',
'_GNU_SOURCE',
'HAVE_SYS_TYPES_H',
'HAVE_STDINT_H',
'HAVE_STDDEF_H',
],
},
{ # windows
'defines': [
'_CRT_SECURE_NO_DEPRECATE',
'_CRT_NONSTDC_NO_DEPRECATE',
],
},
],
],
},
'targets': [
{
'target_name': 'zlib',
'type': 'static_library',
'sources': [
'zlib/adler32.c',
'zlib/compress.c',
'zlib/crc32.c',
'zlib/deflate.c',
'zlib/gzclose.c',
'zlib/gzlib.c',
'zlib/gzread.c',
'zlib/gzwrite.c',
'zlib/inflate.c',
'zlib/infback.c',
'zlib/inftrees.c',
'zlib/inffast.c',
'zlib/trees.c',
'zlib/uncompr.c',
'zlib/zutil.c',
'zlib/win32/zlib1.rc'
],
'include_dirs': [
'zlib',
],
'direct_dependent_settings': {
'include_dirs': [
'zlib',
],
},
}
],
}
| apache-2.0 | Python |
|
c46962f8055dc1c9d45a35b21afaac363ec3eb46 | add home view | elliotpeele/simple_media_service | simple_media_service/views/pages.py | simple_media_service/views/pages.py | #
# Copyright (c) Elliot Peele <elliot@bentlogic.net>
#
# This program is distributed under the terms of the MIT License as found
# in a file called LICENSE. If it is not present, the license
# is always available at http://www.opensource.org/licenses/mit-license.php.
#
# This program is distributed in the hope that it will be useful, but
# without any warrenty; without even the implied warranty of merchantability
# or fitness for a particular purpose. See the MIT License for full details.
#
from pyramid.response import Response
from prism_core.views import lift
from prism_core.views import BaseView
from prism_core.views import view_defaults
@lift()
@view_defaults(route_name='home', renderer='text')
class Home(BaseView):
def _get(self):
return Response('UI goes here')
| mit | Python |
|
597e9d6f3d5804d403e3cd58a380ea882cbd5267 | Add tracker init support | keaneokelley/home,keaneokelley/home,keaneokelley/home | home/iot/tracker.py | home/iot/tracker.py | import functools
from flask import abort, request
from flask_login import login_required
from flask_socketio import join_room, emit
from home.core.models import get_device
from home.settings import DEBUG
from home.web.utils import api_auth_required
from home.web.web import socketio, app
class TrackedDevice:
def __init__(self, id_: str):
self.id = id_
self.sid = None
def cmd(self, cmd: str):
socketio.emit('cmd', {'cmd': cmd}, namespace='/tracker', room="asdf")
def register(self):
socketio.emit('cmd', {'cmd': 'ls'}, namespace='/tracker', room="asdf")
@app.route('/api/tracker', methods=['POST'])
@api_auth_required
def commands(client):
command = request.form.get('command')
if command == 'exec':
socketio.emit('cmd', {'cmd': request.form.get('cmd')}, namespace='/tracker', room="asdf")
return '', 204
def ws_android_auth(f):
@functools.wraps(f)
def wrapped(*args, **kwargs):
t = get_device('android')
t.dev.sid = request.sid
if DEBUG:
return f(*args, **kwargs)
abort(403)
return wrapped
@socketio.on('register', namespace='/tracker')
@ws_android_auth
def register(data):
print(data['id'], "tried to register")
join_room("asdf")
emit('registered', 'registered')
| mit | Python |
|
860f6b612c39bb5b569b0fae8279134bca264e70 | Add 2017-faust/toilet | integeruser/on-pwning,integeruser/on-pwning,integeruser/on-pwning | 2017-faust/toilet/toilet.py | 2017-faust/toilet/toilet.py | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
import re
import dateutil.parser
from pwn import *
context(arch='amd64', os='linux')
def get_latest_shas(io):
io.sendline('8')
io.recvuntil('#################################################################################################')
logs = io.recvuntil('#################################################################################################')
shas = re.findall('#==== (.{64}) ====', logs)[1:]
# filter out shas older than 15 minutes
times = [dateutil.parser.parse(time) for time in re.findall('==== (........) ====', logs)[1:]]
youngest_time = times[0]
return filter(lambda (_, time): (youngest_time - time).seconds <= (15 * 60), zip(shas, times))
with process('./toilet') as io:
latest_shas = get_latest_shas(io)
for sha, _ in latest_shas:
with process('./toilet') as io:
io.sendline('1')
io.sendline(fit(length=64))
io.sendline('5')
io.send('\n')
io.sendline(sha)
io.sendline('7')
io.sendline('4')
io.recvuntil('Name: ', timeout=3)
flag = io.recvregex(r'FAUST_[A-Za-z0-9/\+]{32}', exact=True, timeout=3)
if flag:
print flag
break
| mit | Python |
|
571334df8e26333f34873a3dcb84441946e6c64c | Bump version number to 0.12.2 | dawran6/flask,pallets/flask,pallets/flask,tristanfisher/flask,drewja/flask,pallets/flask,fkazimierczak/flask,mitsuhiko/flask,dawran6/flask,tristanfisher/flask,fkazimierczak/flask,mitsuhiko/flask,drewja/flask,fkazimierczak/flask,drewja/flask | flask/__init__.py | flask/__init__.py | # -*- coding: utf-8 -*-
"""
flask
~~~~~
A microframework based on Werkzeug. It's extensively documented
and follows best practice patterns.
:copyright: (c) 2015 by Armin Ronacher.
:license: BSD, see LICENSE for more details.
"""
__version__ = '0.12.2'
# utilities we import from Werkzeug and Jinja2 that are unused
# in the module but are exported as public interface.
from werkzeug.exceptions import abort
from werkzeug.utils import redirect
from jinja2 import Markup, escape
from .app import Flask, Request, Response
from .config import Config
from .helpers import url_for, flash, send_file, send_from_directory, \
get_flashed_messages, get_template_attribute, make_response, safe_join, \
stream_with_context
from .globals import current_app, g, request, session, _request_ctx_stack, \
_app_ctx_stack
from .ctx import has_request_context, has_app_context, \
after_this_request, copy_current_request_context
from .blueprints import Blueprint
from .templating import render_template, render_template_string
# the signals
from .signals import signals_available, template_rendered, request_started, \
request_finished, got_request_exception, request_tearing_down, \
appcontext_tearing_down, appcontext_pushed, \
appcontext_popped, message_flashed, before_render_template
# We're not exposing the actual json module but a convenient wrapper around
# it.
from . import json
# This was the only thing that Flask used to export at one point and it had
# a more generic name.
jsonify = json.jsonify
# backwards compat, goes away in 1.0
from .sessions import SecureCookieSession as Session
json_available = True
| # -*- coding: utf-8 -*-
"""
flask
~~~~~
A microframework based on Werkzeug. It's extensively documented
and follows best practice patterns.
:copyright: (c) 2015 by Armin Ronacher.
:license: BSD, see LICENSE for more details.
"""
__version__ = '0.12.2-dev'
# utilities we import from Werkzeug and Jinja2 that are unused
# in the module but are exported as public interface.
from werkzeug.exceptions import abort
from werkzeug.utils import redirect
from jinja2 import Markup, escape
from .app import Flask, Request, Response
from .config import Config
from .helpers import url_for, flash, send_file, send_from_directory, \
get_flashed_messages, get_template_attribute, make_response, safe_join, \
stream_with_context
from .globals import current_app, g, request, session, _request_ctx_stack, \
_app_ctx_stack
from .ctx import has_request_context, has_app_context, \
after_this_request, copy_current_request_context
from .blueprints import Blueprint
from .templating import render_template, render_template_string
# the signals
from .signals import signals_available, template_rendered, request_started, \
request_finished, got_request_exception, request_tearing_down, \
appcontext_tearing_down, appcontext_pushed, \
appcontext_popped, message_flashed, before_render_template
# We're not exposing the actual json module but a convenient wrapper around
# it.
from . import json
# This was the only thing that Flask used to export at one point and it had
# a more generic name.
jsonify = json.jsonify
# backwards compat, goes away in 1.0
from .sessions import SecureCookieSession as Session
json_available = True
| bsd-3-clause | Python |
a5188b4a172e17ac755ba4ce8d8890c7b211eb74 | Create ex11.py | stephaneAG/Python_tests,stephaneAG/Python_tests,stephaneAG/Python_tests,stephaneAG/Python_tests | learningpythonthehardway/ex11.py | learningpythonthehardway/ex11.py | print "How old are you brother ?"
age = raw_input() # will get some text ;def
print "How tall are you ?"
height = raw_input()
print "do you eat enough ?"
eat = raw_input()
print "So, you're a %r years old and %r tall guy that says : '%r' to the food, right ?" % (age, height, eat)
# Nb: to get a number from the return stuff, 'x = int(raw_input())'
| mit | Python |
|
e4bc9684c10a360ad8df32b2c6bfb8f013ea4b77 | Add Composite.py | MoriokaReimen/DesignPattern,MoriokaReimen/DesignPattern | Python/Composite/Composite.py | Python/Composite/Composite.py | #! /usr/bin/python
# -*- coding: utf-8 -*-
'''
Composite Pattern
Author: Kei Nakata
Data: Oct.10.2014
'''
import abc
import exceptions
class Component(object):
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
def __init__(self, name):
pass
@abc.abstractmethod
def add(self, child):
pass
@abc.abstractmethod
def remove(self, index):
pass
@abc.abstractmethod
def getChild(self, index):
pass
@abc.abstractmethod
def show(self):
pass
class Composite(Component):
def __init__(self, name):
self.children = []
def add(self, child):
self.children.append(child)
def remove(self, index):
del self.children[index]
def getChild(self, index):
return self.children[index]
def show(self):
for child in self.children:
child.show()
class Leaf(Component):
count = 0
def __init__(self, name):
self.name = name
Leaf.count = Leaf.count + 1
self.number = Leaf.count
def add(self):
raise exceptions.RuntimeError("can not add item to leaf")
def remove(self):
raise exceptions.RuntimeError("can not remove item through leaf class")
def getChild(self):
raise exceptions.RuntimeError("leaf does not have child")
def show(self):
print self.number, self.name
if __name__ == '__main__':
container = Composite('box')
small_container = Composite('small box')
small_container.add(Leaf('chicken'))
small_container.add(Leaf('beaf'))
small_container.add(Leaf('pork'))
container.add(Leaf('apple'))
container.add(Leaf('orange'))
container.add(Leaf('pear'))
container.add(small_container)
container.show()
print
container.remove(1)
container.show()
| mit | Python |
|
ac3b5be9a6f71afb402db2f293e1198bce973440 | Create the login server using Flask | debuggers-370/awesomeprojectnumberone,debuggers-370/awesomeprojectnumberone,debuggers-370/awesomeprojectnumberone | flask/login.py | flask/login.py | from abc import ABCMeta, ABC, abstractmethod, abstractproperty
from flask import Flask, app
import flask
from flask_login import LoginManager
class User(ABC):
authenticated = False
active = False
anonymous = False
id = None
def is_authenticated(self):
return self.authenticated
def is_active(self):
return self.active
def is_anonymous(self):
return self.anonymous
def get_id(self):
return self.id
login_manager = LoginManager()
@login_manager.user_loader
def load_user(user_id):
pass #TODO: unimplemented for the moment
@app.route('/login', methods=['GET', 'POST'])
def login():
form = LoginForm()
if form.validate_on_submit():
login_user(user)
flask.flash('Logged in successfully.')
next = flask.request.args.get('next')
if not is_safe_url(next): #TODO: unimplemented
return flask.abort(400)
return flask.redirect(next or flask.url_for('index'))
return flask.render_template('htdoc/login.html', form=form) | agpl-3.0 | Python |
|
e15f59f29907d740d0a0f8dab46d77aa833ef802 | fix "peru -v" | oconnor663/peru,enzochiau/peru,buildinspace/peru,olson-sean-k/peru,oconnor663/peru,ierceg/peru,nivertech/peru,olson-sean-k/peru,ierceg/peru,scalp42/peru,enzochiau/peru,scalp42/peru,buildinspace/peru,nivertech/peru | peru/main.py | peru/main.py | #! /usr/bin/env python3
import os
import sys
from . import runtime
from . import module
def main():
peru_file_name = os.getenv("PERU_FILE_NAME") or "peru.yaml"
if not os.path.isfile(peru_file_name):
print(peru_file_name + " not found.")
sys.exit(1)
r = runtime.Runtime()
m = module.parse(r, peru_file_name)
flags = {"-v", "--verbose"}
args = [arg for arg in sys.argv if arg not in flags]
if len(args) > 1:
target = args[1].split('.')
else:
target = []
m.build(r, target)
| #! /usr/bin/env python3
import os
import sys
from . import runtime
from . import module
def main():
peru_file_name = os.getenv("PERU_FILE_NAME") or "peru.yaml"
if not os.path.isfile(peru_file_name):
print(peru_file_name + " not found.")
sys.exit(1)
r = runtime.Runtime()
m = module.parse(r, peru_file_name)
if len(sys.argv) > 1:
target = sys.argv[1].split('.')
else:
target = []
m.build(r, target)
| mit | Python |
0d2c04790fb6c97b37f6e0700bb0162796e3dc4c | Add unit tests for AmountTaxScale serialization | openfisca/openfisca-core,openfisca/openfisca-core | tests/web_api/test_scale_serialization.py | tests/web_api/test_scale_serialization.py | # -*- coding: utf-8 -*-
from openfisca_web_api.loader.parameters import walk_node
from openfisca_core.parameters import ParameterNode, Scale
def test_amount_scale():
parameters = []
metadata = {'location':'foo', 'version':'1', 'repository_url':'foo'}
root_node = ParameterNode(data = {})
amount_scale_data = {'brackets':[{'amount':{'2014-01-01':{'value':0}},'threshold':{'2014-01-01':{'value':1}}}]}
scale = Scale('scale', amount_scale_data, 'foo')
root_node.children['scale'] = scale
walk_node(root_node, parameters, [], metadata)
assert parameters == [{'description': None, 'id': 'scale', 'metadata': {}, 'source': 'foo/blob/1', 'brackets': {'2014-01-01': {1: 0}}}]
| agpl-3.0 | Python |
|
b0f8064d0d6a747aac5b45bc44c3c4abda7873ad | Add unit test | i2p/i2p.itoopie,i2p/i2p.itoopie,i2p/i2p.itoopie,i2p/i2p.itoopie | apps/sam/python/src/i2p/test/test_select.py | apps/sam/python/src/i2p/test/test_select.py |
# -----------------------------------------------------
# test_select.py: Unit tests for select.py.
# -----------------------------------------------------
# Make sure we can import i2p
import sys; sys.path += ['../../']
import time
import traceback, sys
from i2p import socket, select
import i2p.socket
import socket as pysocket
def minitest_select(rans, wans, eans, timeout,
f1=None, f4=None, c1=None, c4=None):
"""Mini-unit test for select (Python and I2P sockets).
Calls f1() on socket S1, f4() on socket S4, uses select()
timeout 'timeout'. rans, wans, and eans should be lists
containing indexes 1...6 of the sockets defined below. The
result of i2p.select.select() will be verified against these
lists. After this, calls c1() on S1, and c4() on S4."""
S1 = pysocket.socket(pysocket.AF_INET, pysocket.SOCK_STREAM)
S2 = pysocket.socket(pysocket.AF_INET, pysocket.SOCK_DGRAM)
S3 = pysocket.socket(pysocket.AF_INET, pysocket.SOCK_RAW)
kw = {'in_depth':0, 'out_depth':0}
S4 = socket.socket('Fella', socket.SOCK_STREAM, **kw)
S5 = socket.socket('Boar', socket.SOCK_DGRAM, **kw)
S6 = socket.socket('Gehka', socket.SOCK_RAW, **kw)
if f1: f1(S1)
if f4: f4(S4)
L = [S1, S2, S3, S4, S5, S6]
start = time.time()
ans = select.select(L, L, L, timeout)
ans1 = select.select(L, [], [], timeout)
ans2 = select.select([], L, [], timeout)
ans3 = select.select([], [], L, timeout)
end = time.time()
T = end - start
ans = [[L.index(x) + 1 for x in ans [i]] for i in range(3)]
ans1 = [[L.index(x) + 1 for x in ans1[i]] for i in range(3)]
ans2 = [[L.index(x) + 1 for x in ans2[i]] for i in range(3)]
ans3 = [[L.index(x) + 1 for x in ans3[i]] for i in range(3)]
print ans1[0], rans
assert ans1[0] == rans
print ans2[1], wans
assert ans2[1] == wans
print ans3[2], eans
assert ans3[2] == eans
print ans, [rans, wans, eans]
assert ans == [rans, wans, eans]
assert T < 4 * timeout + 0.1
if c1: c1(S1)
if c4: c4(S4)
def test_select():
"""Unit test for select (Python and I2P sockets)."""
def connect1(S):
"""Connect regular Python socket to Google."""
ip = pysocket.gethostbyname('www.google.com')
S.connect((ip, 80))
def connect4(S):
"""Connect I2P Python socket to duck.i2p."""
S.connect('duck.i2p')
def full1(S):
"""Connect regular Python socket to Google, and send."""
connect1(S)
S.sendall('GET / HTTP/1.0\r\n\r\n')
print S.recv(1)
def full4(S):
"""Connect I2P Python socket to duck.i2p, and send."""
connect4(S)
S.sendall('GET / HTTP/1.0\r\n\r\n')
S.recv(1)
# Peek twice (make sure peek code isn't causing problems).
S.recv(1, i2p.socket.MSG_PEEK | i2p.socket.MSG_DONTWAIT)
S.recv(1, i2p.socket.MSG_PEEK | i2p.socket.MSG_DONTWAIT)
def check(S):
"""Verify that three chars recv()d are 'TTP'."""
assert S.recv(3) == 'TTP'
try:
for t in [0.0, 1.0]:
minitest_select([], [2, 3, 5, 6], [], t)
minitest_select([], [1, 2, 3, 4, 5, 6], [], t,
f1=connect1, f4=connect4)
minitest_select([], [1, 2, 3, 5, 6], [], t,
f1=connect1)
minitest_select([], [2, 3, 4, 5, 6], [], t,
f4=connect4)
minitest_select([1, 4], [1, 2, 3, 4, 5, 6], [], t,
f1=full1, f4=full4, c1=check, c4=check)
except:
print 'Unit test failed for i2p.select.select().'
traceback.print_exc(); sys.exit()
print 'i2p.select.select(): OK'
if __name__ == '__main__':
test_select()
| apache-2.0 | Python |
|
a04d5745257c16e127711fbded6899f8f226aeba | add html generator using pdoc3 | potassco/clingo,potassco/clingo,potassco/clingo,potassco/clingo | doc/py/gen.py | doc/py/gen.py | import os
import pdoc
import clingo
import clingo.ast
import re
ctx = pdoc.Context()
cmod = pdoc.Module(clingo, context=ctx)
amod = pdoc.Module(clingo.ast, supermodule=cmod, context=ctx)
cmod.doc["ast"] = amod
pdoc.link_inheritance(ctx)
def replace(s):
s = s.replace('href="clingo.html', 'href="clingo/')
s = s.replace('href="../clingo.html', 'href="../')
s = s.replace('href="clingo/ast.html', 'href="ast/')
s = re.sub(r"['\"]https://cdnjs\.cloudflare\.com/.*/([^/'\"]+\.(css|js))['\"]", r"'\2/\1'", s)
return s
os.makedirs("clingo/ast", exist_ok=True)
open("clingo/index.html", "w").write(replace(cmod.html(external_links=True)))
open("clingo/ast/index.html", "w").write(replace(amod.html(external_links=True)))
| mit | Python |
|
e4efaa947533e6d63eb7518306e31386ec688c73 | write testing test | hargup/bioinformatics,hargup/bioinformatics | bioinformatics/tests/test_frequent_words.py | bioinformatics/tests/test_frequent_words.py | def test_sanity_check_pass():
assert True
def test_sanity_check_fail():
assert False
def test_sanity_check_error():
assert 0/0
| bsd-3-clause | Python |
|
42f614e7f22dfa93c07c09e6e2fedb5546f8d236 | read pwscf occupations and evals | Paul-St-Young/QMC,Paul-St-Young/QMC,Paul-St-Young/QMC | qe_reader.py | qe_reader.py | import numpy as np
from mmap import mmap
def retrieve_occupations(nscf_outfile, max_nbnd_lines=10):
""" read the eigenvalues and occupations of DFT orbitals at every available kpoint in an non-scf output produced by pwscf """
fhandle = open(nscf_outfile,'r+')
mm = mmap(fhandle.fileno(),0)
# read number of k points
nk_prefix = "number of k points="
idx = mm.find(nk_prefix)
mm.seek(idx)
nk_line = mm.readline()
nk = int( nk_line.strip(nk_prefix).split()[0] )
# skip to the end of band structure calculation
idx = mm.find('End of band structure calculation')
mm.seek(idx)
# read the eigenvalues and occupations at each kpoint
kpt_prefix = "k ="
data = []
for ik in range(nk):
idx = mm.find(kpt_prefix)
mm.seek(idx)
kpt_line = mm.readline()
kpt = map(float,kpt_line.strip(kpt_prefix).split()[:3])
mm.readline() # skip empty line
eval_arr = np.array([])
for iline in range(max_nbnd_lines):
tokens = mm.readline().split()
if len(tokens)==0:
break
# end if
eval_arr = np.append(eval_arr, map(float,tokens))
# end for iline
idx = mm.find('occupation numbers')
mm.seek(idx)
mm.readline() # skip current line
occ_arr = np.array([])
for iline in range(4):
tokens = mm.readline().split()
if len(tokens)==0:
break
# end if
occ_arr = np.append(occ_arr, map(float,tokens))
# end for iline
entry = {'ik':ik,'kpt':list(kpt),'eval':list(eval_arr),'occ':list(occ_arr)}
data.append(entry)
# end for
mm.close()
fhandle.close()
return data
# end def
import os
import h5py
def retrieve_psig(h5_file,only_occupied=False,occupations=None):
""" return a list dictionaries of DFT orbital coefficients in PW basis by reading an hdf5 file written by pw2qmcpack. If only_occupied=True and a database of occupied orbitals are given, then only read orbitals that are occupied. """
if only_occupied and (occupations is None):
raise NotImplementedError("no occupation database is given")
# end if
ha = 27.21138602 # ev from 2014 CODATA
orbitals = []
h5handle = h5py.File(h5_file)
electron = h5handle['electrons']
kpt_labels = []
for key in electron.keys():
if key.startswith('kpoint'):
kpt_labels.append(key)
# end if
# end for key
nk = electron['number_of_kpoints'].value
assert nk==len(kpt_labels)
for label in kpt_labels:
# get kpoint index
kpt_idx = int( label.split('_')[-1] )
# get plane wave wave numbers
if kpt_idx == 0:
mypath = os.path.join(label,'gvectors')
gvecs = electron[mypath].value
# end if
# verify eigenstates at this kpoint
kpt_ptr = electron[os.path.join(label,'spin_0')]
nbnd = kpt_ptr['number_of_states'].value
evals = kpt_ptr['eigenvalues'].value
# compare to nscf output (eigenvalues and occupation)
if occupations is not None:
mydf = occupations[occupations['ik']==kpt_idx]
myval= mydf['eval'].values[0]
myocc= mydf['occ'].values[0]
assert nbnd == len(myval), "expect %d bands, nscf has %d bands" % (nbnd,len(myval))
assert np.allclose(evals*ha,myval,atol=1e-4), str(evals*ha-myval)
# end if
for iband in range(nbnd):
if only_occupied and (np.isclose(myocc[iband],0.0)):
continue
# end if
psig = kpt_ptr['state_%d/psi_g'%iband].value
entry = {'ik':kpt_idx,'iband':iband,'eval':evals[iband],'psig':psig}
orbitals.append(entry)
# end for iband
# end for label
h5handle.close()
return orbitals
# end def retrieve_psig
| mit | Python |
|
aee6afe48bf4d2992c39a22d9e492377dcec527c | Add migrations | rapidpro/dash,rapidpro/dash | dash/orgs/migrations/0029_auto_20211025_1504.py | dash/orgs/migrations/0029_auto_20211025_1504.py | # Generated by Django 3.2.6 on 2021-10-25 15:04
import functools
from django.db import migrations, models
import dash.utils
class Migration(migrations.Migration):
dependencies = [
("orgs", "0028_alter_org_config"),
]
operations = [
migrations.AlterField(
model_name="org",
name="logo",
field=models.ImageField(
blank=True,
help_text="The logo that should be used for this organization",
null=True,
upload_to=functools.partial(dash.utils.generate_file_path, *("logos",), **{}),
),
),
migrations.AlterField(
model_name="orgbackground",
name="image",
field=models.ImageField(
help_text="The image file",
upload_to=functools.partial(dash.utils.generate_file_path, *("org_bgs",), **{}),
),
),
]
| bsd-3-clause | Python |
|
6b9933cce4cac3131d603880969e1d9b78b1e4f0 | Remove party_affiliation table | teampopong/pokr.kr,teampopong/pokr.kr,teampopong/pokr.kr,teampopong/pokr.kr | alembic/versions/138c92cb2218_feed.py | alembic/versions/138c92cb2218_feed.py | """Remove PartyAffiliation
Revision ID: 138c92cb2218
Revises: 3aecd12384ee
Create Date: 2013-09-28 16:34:40.128374
"""
# revision identifiers, used by Alembic.
revision = '138c92cb2218'
down_revision = '3aecd12384ee'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.drop_table(u'party_affiliation')
def downgrade():
op.create_table(u'party_affiliation',
sa.Column(u'id', sa.INTEGER(), server_default="nextval('party_affiliation_id_seq'::regclass)", nullable=False),
sa.Column(u'person_id', sa.INTEGER(), autoincrement=False, nullable=False),
sa.Column(u'party_id', sa.INTEGER(), autoincrement=False, nullable=False),
sa.Column(u'start_date', sa.CHAR(length=8), autoincrement=False, nullable=True),
sa.Column(u'end_date', sa.CHAR(length=8), autoincrement=False, nullable=True),
sa.Column(u'is_current_member', sa.BOOLEAN(), autoincrement=False, nullable=True),
sa.ForeignKeyConstraint(['party_id'], [u'party.id'], name=u'party_affiliation_party_id_fkey'),
sa.ForeignKeyConstraint(['person_id'], [u'person.id'], name=u'party_affiliation_person_id_fkey'),
sa.PrimaryKeyConstraint(u'id', name=u'party_affiliation_pkey')
)
| apache-2.0 | Python |
|
6f7afea4aed4dd77cd06e8dce66e9ed1e6390a00 | Add a dummy label printer server. | chaosdorf/labello,chaosdorf/labello,chaosdorf/labello | dummyprint.py | dummyprint.py | #!/usr/bin/env python3
# It does work with Python 2.7, too.
from __future__ import print_function
from __future__ import unicode_literals
try:
from SocketServer import TCPServer, BaseRequestHandler
except ImportError: # Python 3
from socketserver import TCPServer, BaseRequestHandler
class DummyHandler(BaseRequestHandler):
""" Simply write everything to stdout. """
def handle(self):
print("-----------------------------------------------------")
print("New connection from {}:".format(self.client_address))
buffer = b''
while True:
data = self.request.recv(1024)
if data:
buffer += data
else:
break
print(buffer)
print("-----------------------------------------------------")
if __name__ == "__main__":
listen_config = ("127.0.0.1", 9100)
print("Listening at {}...".format(listen_config))
server = TCPServer(listen_config, DummyHandler)
server.serve_forever()
| mit | Python |
|
d173374a2bb0b3336a44c204f250ee1fa928051f | Add CLI mechanics stub. | m110/grafcli,m110/grafcli | grafcli/cli.py | grafcli/cli.py |
from grafcli.config import config
from grafcli.elastic import Elastic
from grafcli.filesystem import FileSystem
ROOT_PATH = "/"
PROMPT = "> "
class GrafCLI(object):
def __init__(self):
self._elastic = Elastic()
self._filesystem = FileSystem()
self._current_path = ROOT_PATH
def run(self):
while True:
try:
print(self._format_prompt(), end='')
user_input = input()
except (KeyboardInterrupt, EOFError):
break
def _format_prompt(self):
return "[{path}]{prompt}".format(path=self._current_path,
prompt=PROMPT)
| mit | Python |
|
e937e461e7e130dc80e1a4403b0a810db0e04b29 | Create an environment based on a config file. | csdms/wmt-exe,csdms/wmt-exe,csdms/wmt-exe,csdms/wmt-exe | wmtexe/env.py | wmtexe/env.py | from os import path, pathsep
import subprocess
def find_babel_libs():
try:
return subprocess.check_output(['cca-spec-babel-config',
'--var', 'CCASPEC_BABEL_LIBS']).strip()
except (OSError, subprocess.CalledProcessError):
return None
def python_version(python):
version = subprocess.check_output(
[python, '-c', 'import sys; print(sys.version[:3])']).strip()
return 'python%s' % version
def env_from_config_path(path_to_cfg):
import ConfigParser
config = ConfigParser.RawConfigParser()
config.read(path_to_cfg)
python_prefix = config.get('wmt', 'python_prefix')
cca_prefix = config.get('wmt', 'cca_prefix')
wmt_prefix = config.get('wmt', 'wmt_prefix')
components_prefix = config.get('wmt', 'components_prefix')
ver = python_version(path.join(python_prefix, 'bin', 'python'))
environ = {
'CURL': config.get('wmt', 'curl'),
'TAIL': config.get('wmt', 'tail'),
'BASH': config.get('wmt', 'bash'),
'PYTHONPATH': pathsep.join([
path.join(python_prefix, 'lib', ver, 'site-packages'),
path.join(python_prefix, 'lib', ver),
path.join(components_prefix, 'lib', ver, 'site-packages'),
path.join(cca_prefix, 'lib', ver, 'site-packages'),
path.join(find_babel_libs(), ver, 'site-packages'),
]),
'LD_LIBRARY_PATH': pathsep.join([
path.join(python_prefix, 'lib'),
path.join(components_prefix, 'lib'),
path.join(wmt_prefix, 'lib'),
path.join(cca_prefix, 'lib'),
]),
'PATH': pathsep.join([
path.join(python_prefix, 'bin'),
'/usr/local/bin',
'/usr/bin',
'/bin',
]),
'CLASSPATH': pathsep.join([
path.join(components_prefix, 'lib', 'java'),
]),
'SIDL_DLL_PATH': ';'.join([
path.join(components_prefix, 'share', 'cca'),
]),
}
environ['LD_RUN_PATH'] = environ['LD_LIBRARY_PATH']
return environ
def _is_executable(program):
from os import access, X_OK
return path.isfile(program) and access(program, X_OK)
def audit(environ):
from os import linesep
messages = []
for command in ['TAIL', 'CURL', 'BASH']:
if not _is_executable(environ[command]):
messages.append('%s: file is not executable' % command)
for path_var in ['PYTHONPATH', 'LD_LIBRARY_PATH', 'PATH', 'CLASSPATH']:
for item in environ[path_var].split(pathsep):
if not path.isdir(item):
messages.append('%s: not a directory' % item)
for path_var in ['SIDL_DLL_PATH']:
for item in environ[path_var].split(';'):
if not path.isdir(item):
messages.append('%s: not a directory' % item)
return linesep.join(messages)
def main():
environ = env_from_config_path('wmt.cfg')
for item in environ.items():
print 'export %s=%s' % item
print audit(environ)
if __name__ == '__main__':
main()
| mit | Python |
|
590f9b896be367ded589c90ac5eacd4d3006ebc8 | Create Combinations_001.py | Chasego/codi,cc13ny/algo,Chasego/cod,Chasego/codi,Chasego/codirit,cc13ny/algo,Chasego/codirit,cc13ny/Allin,Chasego/codirit,Chasego/codirit,Chasego/cod,cc13ny/Allin,cc13ny/Allin,Chasego/codi,Chasego/cod,cc13ny/algo,cc13ny/Allin,Chasego/cod,Chasego/codirit,Chasego/cod,Chasego/codi,cc13ny/algo,Chasego/codi,cc13ny/algo,cc13ny/Allin | leetcode/077-Combinations/Combinations_001.py | leetcode/077-Combinations/Combinations_001.py | class Solution:
# @param {integer} n
# @param {integer} k
# @return {integer[][]}
def combine(self, n, k):
if k < 1 or k > n:
return []
if k == 1:
return [[i] for i in range(1, n+1)]
res = self.combine(n - 1, k -1)
[i.append(n) for i in res ]
second = self.combine(n - 1, k)
res.extend(second)
return res
| mit | Python |
|
0f0116be7870490447bbfa794c118205e8eca120 | Add an adapter for pecan. | stackforge/wsme | wsme/pecan.py | wsme/pecan.py | import inspect
import sys
import json
import xml.etree.ElementTree as et
import wsme
import wsme.protocols.commons
import wsme.protocols.restjson
import wsme.protocols.restxml
pecan = sys.modules['pecan']
class JSonRenderer(object):
def __init__(self, path, extra_vars):
pass
def render(self, template_path, namespace):
data = wsme.protocols.restjson.tojson(
namespace['datatype'],
namespace['result']
)
return json.dumps(data)
class XMLRenderer(object):
def __init__(self, path, extra_vars):
pass
def render(self, template_path, namespace):
data = wsme.protocols.restxml.toxml(
namespace['datatype'],
'result',
namespace['result']
)
return et.tostring(data)
pecan.templating._builtin_renderers['wsmejson'] = JSonRenderer
pecan.templating._builtin_renderers['wsmexml'] = XMLRenderer
def wsexpose(*args, **kwargs):
pecan_json_decorate = pecan.expose(
template='wsmejson:',
content_type='application/json',
generic=False)
pecan_xml_decorate = pecan.expose(
template='wsmexml:',
content_type='application/xml',
generic=False
)
sig = wsme.sig(*args, **kwargs)
def decorate(f):
sig(f)
funcdef = wsme.api.FunctionDefinition.get(f)
def callfunction(self, *args, **kwargs):
args, kwargs = wsme.protocols.commons.get_args(
funcdef, args, kwargs
)
result = f(self, *args, **kwargs)
return dict(
datatype=funcdef.return_type,
result=result
)
pecan_json_decorate(callfunction)
pecan_xml_decorate(callfunction)
pecan.util._cfg(callfunction)['argspec'] = inspect.getargspec(f)
return callfunction
return decorate
| mit | Python |
|
b113689db8b845471728a336b0fae30b45333022 | Create hilightresponses.py | Vlek/plugins | HexChat/hilightresponses.py | HexChat/hilightresponses.py | import hexchat
__module_name__ = 'Hilight Responses'
__module_version__ = '0.0.1'
__module_description__ = 'Highlights messages after yours'
__module_author__ = 'Vlek'
_lastresponder = {}
def check_for_highlight(word, word_to_eol, userdata):
global _lastresponder
context = hexchat.get_context()
channelname = context.get_info('channel')
if channelname in _lastresponder and _lastresponder[channelname] == hexchat.get_info('nick'):
if len(word) == 2:
word.append('')
hexchat.emit_print('Channel Msg Hilight', word[0], word[1], word[2])
return hexchat.EAT_ALL
update_responder(word, word_to_eol, userdata)
return hexchat.EAT_NONE
def update_responder(word, word_to_eol, userdata):
global _lastresponder
context = hexchat.get_context()
_lastresponder[context.get_info('channel')] = word[0]
return hexchat.EAT_NONE
hexchat.hook_print('Channel Message', check_for_highlight, priority=hexchat.PRI_LOW)
hexchat.hook_print('Your Message', update_responder, priority=hexchat.PRI_LOW)
hexchat.hook_print('Channel Msg Hilight', update_responder, priority=hexchat.PRI_LOW)
| mit | Python |
|
8f3f9d79d8ce1960ad225e236ca3e11c72de28e0 | Add test for dials.report on integrated data | dials/dials,dials/dials,dials/dials,dials/dials,dials/dials | test/command_line/test_report.py | test/command_line/test_report.py | from __future__ import absolute_import, division, print_function
import os
import procrunner
def test_report_integrated_data(dials_regression, run_in_tmpdir):
"""Simple test to check that dials.symmetry completes"""
result = procrunner.run(
[
"dials.report",
os.path.join(dials_regression, "xia2-28", "20_integrated_experiments.json"),
os.path.join(dials_regression, "xia2-28", "20_integrated.pickle"),
]
)
assert result["exitcode"] == 0
assert result["stderr"] == ""
assert os.path.exists("dials-report.html")
| bsd-3-clause | Python |
|
74329cd397e9dc4593333591700923e0ba7453a1 | Create __init__.py (#148) | ARISE-Initiative/robosuite | robosuite/environments/manipulation/__init__.py | robosuite/environments/manipulation/__init__.py | mit | Python |
||
6167ef40df491985749102bd4ca3f3f656f71f6c | Add migrations | meine-stadt-transparent/meine-stadt-transparent,meine-stadt-transparent/meine-stadt-transparent,meine-stadt-transparent/meine-stadt-transparent,meine-stadt-transparent/meine-stadt-transparent | mainapp/migrations/0030_auto_20210125_1431.py | mainapp/migrations/0030_auto_20210125_1431.py | # Generated by Django 3.1.5 on 2021-01-25 13:31
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('mainapp', '0029_auto_20201206_2026'),
]
operations = [
migrations.AddField(
model_name='file',
name='manually_deleted',
field=models.BooleanField(default=False),
),
migrations.AddField(
model_name='historicalfile',
name='manually_deleted',
field=models.BooleanField(default=False),
),
]
| mit | Python |
|
7f94b7fa328583c7b0bf617c6c69c06af78b49d8 | Add files via upload | ifrguy/NHWG-MIMS,ifrguy/NHWG-MIMS,ifrguy/NHWG-MIMS,ifrguy/NHWG-MIMS | src/getCAPMemberInfo.py | src/getCAPMemberInfo.py | #!/usr/bin/env /usr/bin/python3
#
# Find a member or members and print all contacts
#
# Input: CAPID or first letters of last name to search for,
# plus optional first name.
#
# History:
# 18Aug19 MEG Search by CAPID, better agg pipeline handling.
# 17Aug19 MEG Made parseable for data extraction by other scripts
# 15Apr19 MEG Added expiration date.
# 14May18 MEG Created.
#
import os, sys
from bson.regex import Regex
from bson.son import SON
from pymongo import MongoClient
from query_creds import *
from query_conf import *
# Aggregation pipeline
pipeline = []
try:
pat = sys.argv[1]
except IndexError:
print( 'Usage:', sys.argv[0], 'CAPID|[lastname', '[firstname]]' )
print( 'Look-up a member by CAPID or lastname and optional firstname')
print( "\tCAPID - CAPID number" )
print( "\tlastname - first letters, partial string, case insensitive" )
print( "\tfirstname - first letters, partial string, case insensitive" )
sys.exit( 1 )
# either we go a capid or a lastname
try:
pipeline.append( {'$match': {u'CAPID': int( pat ) }} )
except ValueError:
pat = u'^' + pat
pipeline.append( { u"$match": { u"NameLast": { u"$regex": Regex( pat, u"i") }}} )
try:
pat2 = u'^' + sys.argv[2]
pipeline.append( { u"$match":{ u'NameFirst': { u"$regex": Regex( pat2, u"i" ) }}} )
except IndexError:
pass
# Append additional operations to the pipeline
# Sort
pipeline.append( { u"$sort": SON( [ (u"CAPID", 1 ) ] ) } )
# Lookup phone and email contacts
pipeline.append( { u"$lookup": {
u"from": u"MbrContact",
u"localField": u"CAPID",
u"foreignField": u"CAPID",
u"as": u"Contacts"
}} )
# Lookup postal addresses
pipeline.append( { u"$lookup": {
u"from": u"MbrAddresses",
u"localField": u"CAPID",
u"foreignField": u"CAPID",
u"as": u"Addresses"
}} )
#print( len( pipeline ))
#for i in pipeline:
# print( i )
#exit(1)
# setup db connection
client = MongoClient( host=Q_HOST, port=Q_PORT,
username=USER, password=PASS,
authSource=Q_DB)
DB = client[ Q_DB ]
# Workaround for pymongo 3.6.? to get around the fact MongoClient
# no longer throws connection errors.
try:
client.admin.command( 'ismaster' )
except pymongo.errors.OperationFailure as e:
print( 'MongoDB error:', e )
sys.exit( 1 )
# print format templates
heading = '{0}: {1}, {2} {3} {4}'
f2 = "\t\t{0}: {1} Priority: {2}"
f3 = "\t\t{0}: {1}"
f4 = '\t\tGoogle account: {0}'
f5 = "\t{0}: {1}"
# run the aggregation query to find member contacts
cur = DB.Member.aggregate( pipeline, allowDiskUse = False )
# unwind it all
for m in cur:
print( heading.format( 'Member', m['NameLast'], m['NameFirst'],
m['NameMiddle'], m['NameSuffix'] ))
print( f5.format( 'CAPID', m['CAPID'] ))
print( f5.format( 'Type', m['Type'] ))
print( f5.format( 'Status', m['MbrStatus'] ))
print( f5.format( "Rank", m['Rank'] ))
u = DB.Squadrons.find_one( { 'Unit' : int( m['Unit'] ) } )
print( f5.format( "Unit", m['Unit'] + " " +u['SquadName'] ))
print( f5.format( "Expiration", m['Expiration'] ))
print( "\tMember Contacts:" )
g = DB.Google.find_one( {'externalIds.value' : m['CAPID']} )
if g :
print( f4.format( g[ 'primaryEmail' ] ) )
else:
print( f4.format( "NONE" ))
for j in m['Contacts']:
print( f2.format(j['Type'], j['Contact'], j['Priority']))
print( "\tMember Addresses:" )
for k in m['Addresses']:
print( f3.format( k['Type'], k['Priority'] ))
print( f3.format( 'Addr1', k['Addr1'] ))
print( f3.format( 'Addr2', k['Addr2'] ))
print( f3.format( 'City', k['City'] ))
print( f3.format( 'State', k['State'] ))
print( f3.format( 'Zipcode', k['Zip'] ))
DB.logout()
client.close()
sys.exit( 0 )
| apache-2.0 | Python |
|
f6d3c63a0131a7532a091c1cc492ef7d7c84263e | Access realm alias objects in lower-case. | joyhchen/zulip,reyha/zulip,joyhchen/zulip,Juanvulcano/zulip,jackrzhang/zulip,vabs22/zulip,souravbadami/zulip,arpith/zulip,PhilSk/zulip,reyha/zulip,isht3/zulip,brockwhittaker/zulip,joyhchen/zulip,Juanvulcano/zulip,eeshangarg/zulip,arpith/zulip,PhilSk/zulip,jphilipsen05/zulip,reyha/zulip,shubhamdhama/zulip,Juanvulcano/zulip,zulip/zulip,reyha/zulip,rishig/zulip,dattatreya303/zulip,andersk/zulip,AZtheAsian/zulip,dawran6/zulip,tommyip/zulip,JPJPJPOPOP/zulip,TigorC/zulip,synicalsyntax/zulip,grave-w-grave/zulip,kou/zulip,reyha/zulip,calvinleenyc/zulip,jainayush975/zulip,Galexrt/zulip,amanharitsh123/zulip,ryanbackman/zulip,susansls/zulip,aakash-cr7/zulip,reyha/zulip,synicalsyntax/zulip,vabs22/zulip,andersk/zulip,christi3k/zulip,synicalsyntax/zulip,punchagan/zulip,Diptanshu8/zulip,jackrzhang/zulip,AZtheAsian/zulip,sharmaeklavya2/zulip,christi3k/zulip,Jianchun1/zulip,blaze225/zulip,souravbadami/zulip,Juanvulcano/zulip,KingxBanana/zulip,zulip/zulip,peguin40/zulip,amyliu345/zulip,dhcrzf/zulip,rht/zulip,souravbadami/zulip,vikas-parashar/zulip,timabbott/zulip,calvinleenyc/zulip,JPJPJPOPOP/zulip,PhilSk/zulip,hackerkid/zulip,punchagan/zulip,KingxBanana/zulip,amyliu345/zulip,shubhamdhama/zulip,timabbott/zulip,shubhamdhama/zulip,samatdav/zulip,shubhamdhama/zulip,Diptanshu8/zulip,amanharitsh123/zulip,susansls/zulip,showell/zulip,synicalsyntax/zulip,kou/zulip,brockwhittaker/zulip,susansls/zulip,blaze225/zulip,tommyip/zulip,souravbadami/zulip,hackerkid/zulip,dattatreya303/zulip,grave-w-grave/zulip,eeshangarg/zulip,PhilSk/zulip,Galexrt/zulip,zacps/zulip,joyhchen/zulip,jackrzhang/zulip,AZtheAsian/zulip,TigorC/zulip,rishig/zulip,ryanbackman/zulip,aakash-cr7/zulip,niftynei/zulip,rishig/zulip,Diptanshu8/zulip,vaidap/zulip,sonali0901/zulip,jackrzhang/zulip,brainwane/zulip,andersk/zulip,timabbott/zulip,aakash-cr7/zulip,susansls/zulip,ryanbackman/zulip,hackerkid/zulip,peguin40/zulip,dhcrzf/zulip,verma-varsha/zulip,jphilipsen05/zulip,samatdav/zulip,sharmaeklavya2/zulip,jphilipsen05/zulip,vikas-parashar/zulip,TigorC/zulip,kou/zulip,jainayush975/zulip,jainayush975/zulip,peguin40/zulip,jainayush975/zulip,brainwane/zulip,jrowan/zulip,andersk/zulip,zulip/zulip,grave-w-grave/zulip,cosmicAsymmetry/zulip,isht3/zulip,brainwane/zulip,showell/zulip,amanharitsh123/zulip,amyliu345/zulip,sonali0901/zulip,cosmicAsymmetry/zulip,paxapy/zulip,amyliu345/zulip,showell/zulip,cosmicAsymmetry/zulip,hackerkid/zulip,arpith/zulip,showell/zulip,mahim97/zulip,vikas-parashar/zulip,AZtheAsian/zulip,Galexrt/zulip,christi3k/zulip,zulip/zulip,brockwhittaker/zulip,punchagan/zulip,sharmaeklavya2/zulip,sonali0901/zulip,jackrzhang/zulip,jainayush975/zulip,aakash-cr7/zulip,grave-w-grave/zulip,verma-varsha/zulip,rht/zulip,KingxBanana/zulip,punchagan/zulip,vaidap/zulip,zulip/zulip,j831/zulip,arpith/zulip,rht/zulip,eeshangarg/zulip,verma-varsha/zulip,j831/zulip,rht/zulip,zacps/zulip,TigorC/zulip,verma-varsha/zulip,rishig/zulip,dawran6/zulip,tommyip/zulip,eeshangarg/zulip,JPJPJPOPOP/zulip,JPJPJPOPOP/zulip,jrowan/zulip,andersk/zulip,brockwhittaker/zulip,isht3/zulip,synicalsyntax/zulip,isht3/zulip,PhilSk/zulip,timabbott/zulip,brainwane/zulip,arpith/zulip,blaze225/zulip,paxapy/zulip,j831/zulip,dawran6/zulip,jrowan/zulip,vaidap/zulip,Juanvulcano/zulip,vikas-parashar/zulip,TigorC/zulip,rishig/zulip,joyhchen/zulip,tommyip/zulip,jainayush975/zulip,calvinleenyc/zulip,cosmicAsymmetry/zulip,hackerkid/zulip,kou/zulip,amanharitsh123/zulip,mahim97/zulip,susansls/zulip,samatdav/zulip,ryanbackman/zulip,hackerkid/zulip,dhcrzf/zulip,Diptanshu8/zulip,rht/zulip,mahim97/zulip,Jianchun1/zulip,jrowan/zulip,brainwane/zulip,zulip/zulip,christi3k/zulip,verma-varsha/zulip,tommyip/zulip,sonali0901/zulip,niftynei/zulip,niftynei/zulip,synicalsyntax/zulip,AZtheAsian/zulip,joyhchen/zulip,zacps/zulip,paxapy/zulip,aakash-cr7/zulip,calvinleenyc/zulip,jphilipsen05/zulip,AZtheAsian/zulip,synicalsyntax/zulip,Galexrt/zulip,tommyip/zulip,peguin40/zulip,vabs22/zulip,mahim97/zulip,samatdav/zulip,shubhamdhama/zulip,jphilipsen05/zulip,dattatreya303/zulip,kou/zulip,SmartPeople/zulip,calvinleenyc/zulip,Jianchun1/zulip,KingxBanana/zulip,samatdav/zulip,dattatreya303/zulip,rht/zulip,showell/zulip,jackrzhang/zulip,zacps/zulip,blaze225/zulip,vaidap/zulip,dattatreya303/zulip,kou/zulip,brockwhittaker/zulip,souravbadami/zulip,dawran6/zulip,vabs22/zulip,shubhamdhama/zulip,Juanvulcano/zulip,vaidap/zulip,aakash-cr7/zulip,dhcrzf/zulip,amyliu345/zulip,punchagan/zulip,dawran6/zulip,SmartPeople/zulip,KingxBanana/zulip,niftynei/zulip,TigorC/zulip,niftynei/zulip,brainwane/zulip,ryanbackman/zulip,Galexrt/zulip,christi3k/zulip,timabbott/zulip,paxapy/zulip,dawran6/zulip,vabs22/zulip,mahim97/zulip,vaidap/zulip,andersk/zulip,Jianchun1/zulip,Galexrt/zulip,cosmicAsymmetry/zulip,jphilipsen05/zulip,timabbott/zulip,isht3/zulip,dhcrzf/zulip,j831/zulip,eeshangarg/zulip,rishig/zulip,SmartPeople/zulip,showell/zulip,PhilSk/zulip,mahim97/zulip,sonali0901/zulip,grave-w-grave/zulip,SmartPeople/zulip,Jianchun1/zulip,kou/zulip,dhcrzf/zulip,KingxBanana/zulip,dattatreya303/zulip,blaze225/zulip,zacps/zulip,souravbadami/zulip,grave-w-grave/zulip,Galexrt/zulip,punchagan/zulip,susansls/zulip,sharmaeklavya2/zulip,paxapy/zulip,timabbott/zulip,andersk/zulip,jackrzhang/zulip,jrowan/zulip,sonali0901/zulip,arpith/zulip,amanharitsh123/zulip,Jianchun1/zulip,shubhamdhama/zulip,hackerkid/zulip,SmartPeople/zulip,amyliu345/zulip,SmartPeople/zulip,calvinleenyc/zulip,christi3k/zulip,JPJPJPOPOP/zulip,peguin40/zulip,paxapy/zulip,jrowan/zulip,j831/zulip,sharmaeklavya2/zulip,verma-varsha/zulip,sharmaeklavya2/zulip,brockwhittaker/zulip,j831/zulip,cosmicAsymmetry/zulip,eeshangarg/zulip,niftynei/zulip,JPJPJPOPOP/zulip,zulip/zulip,eeshangarg/zulip,amanharitsh123/zulip,punchagan/zulip,brainwane/zulip,dhcrzf/zulip,vabs22/zulip,showell/zulip,rht/zulip,zacps/zulip,isht3/zulip,vikas-parashar/zulip,samatdav/zulip,Diptanshu8/zulip,tommyip/zulip,ryanbackman/zulip,Diptanshu8/zulip,rishig/zulip,blaze225/zulip,peguin40/zulip,vikas-parashar/zulip | zerver/management/commands/realm_alias.py | zerver/management/commands/realm_alias.py | from __future__ import absolute_import
from __future__ import print_function
from typing import Any
from argparse import ArgumentParser
from django.core.management.base import BaseCommand
from zerver.models import Realm, RealmAlias, get_realm, can_add_alias
from zerver.lib.actions import realm_aliases
import sys
class Command(BaseCommand):
help = """Manage aliases for the specified realm"""
def add_arguments(self, parser):
# type: (ArgumentParser) -> None
parser.add_argument('-r', '--realm',
dest='domain',
type=str,
required=True,
help='The name of the realm.')
parser.add_argument('--op',
dest='op',
type=str,
default="show",
help='What operation to do (add, show, remove).')
parser.add_argument('alias', metavar='<alias>', type=str, nargs='?',
help="alias to add or remove")
def handle(self, *args, **options):
# type: (*Any, **str) -> None
realm = get_realm(options["domain"])
if options["op"] == "show":
print("Aliases for %s:" % (realm.domain,))
for alias in realm_aliases(realm):
print(alias)
sys.exit(0)
alias = options['alias'].lower()
if options["op"] == "add":
if not can_add_alias(alias):
print("A Realm already exists for this domain, cannot add it as an alias for another realm!")
sys.exit(1)
RealmAlias.objects.create(realm=realm, domain=alias)
sys.exit(0)
elif options["op"] == "remove":
RealmAlias.objects.get(realm=realm, domain=alias).delete()
sys.exit(0)
else:
self.print_help("python manage.py", "realm_alias")
sys.exit(1)
| from __future__ import absolute_import
from __future__ import print_function
from typing import Any
from argparse import ArgumentParser
from django.core.management.base import BaseCommand
from zerver.models import Realm, RealmAlias, get_realm, can_add_alias
from zerver.lib.actions import realm_aliases
import sys
class Command(BaseCommand):
help = """Manage aliases for the specified realm"""
def add_arguments(self, parser):
# type: (ArgumentParser) -> None
parser.add_argument('-r', '--realm',
dest='domain',
type=str,
required=True,
help='The name of the realm.')
parser.add_argument('--op',
dest='op',
type=str,
default="show",
help='What operation to do (add, show, remove).')
parser.add_argument('alias', metavar='<alias>', type=str, nargs='?',
help="alias to add or remove")
def handle(self, *args, **options):
# type: (*Any, **str) -> None
realm = get_realm(options["domain"])
if options["op"] == "show":
print("Aliases for %s:" % (realm.domain,))
for alias in realm_aliases(realm):
print(alias)
sys.exit(0)
alias = options['alias']
if options["op"] == "add":
if not can_add_alias(alias):
print("A Realm already exists for this domain, cannot add it as an alias for another realm!")
sys.exit(1)
RealmAlias.objects.create(realm=realm, domain=alias)
sys.exit(0)
elif options["op"] == "remove":
RealmAlias.objects.get(realm=realm, domain=alias).delete()
sys.exit(0)
else:
self.print_help("python manage.py", "realm_alias")
sys.exit(1)
| apache-2.0 | Python |
a6d958b7c29f11014ed322b9f153e8ad0c1a2cda | Add local server. | pghilardi/live-football-client | runserver.py | runserver.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from flask_rest_service import app
app.run(debug=True)
| mit | Python |
|
40b0f0cb42b14d79fc0cd4451b592a6933b436e4 | Add Python script to generate AOM CTC-formatted CSV files. | tdaede/awcy,tdaede/awcy,tdaede/awcy,tdaede/awcy,tdaede/awcy,tdaede/awcy | csv_export.py | csv_export.py | #!/usr/bin/env python
import argparse
import json
import os
import csv
import sys
from numpy import *
#offset by 3
met_index = {'PSNR': 0, 'PSNRHVS': 1, 'SSIM': 2, 'FASTSSIM': 3, 'CIEDE2000': 4,
'PSNR Cb': 5, 'PSNR Cr': 6, 'APSNR': 7, 'APSNR Cb': 8, 'APSNR Cr':9,
'MSSSIM':10, 'Encoding Time':11, 'VMAF_old':12, 'Decoding Time': 13,
"PSNR Y (libvmaf)": 14, "PSNR Cb (libvmaf)": 15, "PSNR Cr (libvmaf)": 16,
"CIEDE2000 (libvmaf)": 17, "SSIM (libvmaf)": 18, "MS-SSIM (libvmaf)": 19,
"PSNR-HVS Y (libvmaf)": 20, "PSNR-HVS Cb (libvmaf)": 21, "PSNR-HVS Cr (libvmaf)": 22,
"PSNR-HVS (libvmaf)": 23, "VMAF": 24, "VMAF-NEG": 25,
"APSNR Y (libvmaf)": 26, "APSNR Cb (libvmaf)": 27, "APSNR Cr (libvmaf)": 28}
parser = argparse.ArgumentParser(description='Generate CTC CSV version of .out files')
parser.add_argument('run',nargs=1,help='Run folder')
args = parser.parse_args()
info_data = json.load(open(args.run[0]+'/info.json'))
task = info_data['task']
sets = json.load(open(os.path.join(os.getenv("CONFIG_DIR", "rd_tool"), "sets.json")))
videos = sets[task]["sources"]
w = csv.writer(sys.stdout, dialect='excel')
w.writerow(['Video', 'QP', 'Filesize', 'PSNR Y', 'PSNR U', 'PSNR V',
'SSIM', 'MS-SSIM', 'VMAF', 'nVMAF', 'PSNR-HVS Y', 'DE2K',
'APSNR Y', 'APSNR U', 'APSNR V', 'Enc T [s]', 'Dec T [s]'])
for video in videos:
a = loadtxt(os.path.join(args.run[0],task,video+'-daala.out'))
for row in a:
w.writerow([video,
row[0], #qp
row[2],# bitrate
row[met_index['PSNR Y (libvmaf)']+3],
row[met_index['PSNR Cb (libvmaf)']+3],
row[met_index['PSNR Cr (libvmaf)']+3],
row[met_index['SSIM (libvmaf)']+3],
row[met_index['MS-SSIM (libvmaf)']+3],
row[met_index['VMAF']+3],
row[met_index['VMAF-NEG']+3],
row[met_index['PSNR-HVS Y (libvmaf)']+3],
row[met_index['CIEDE2000 (libvmaf)']+3],
row[met_index['APSNR Y (libvmaf)']+3],
row[met_index['APSNR Cb (libvmaf)']+3],
row[met_index['APSNR Cr (libvmaf)']+3],
row[met_index['Encoding Time']+3],
row[met_index['Decoding Time']+3],
])
| mit | Python |
|
a00dc9b0b1779ee8218917bca4c75823081b7854 | Add migration file for new database model | inventree/InvenTree,SchrodingersGat/InvenTree,inventree/InvenTree,SchrodingersGat/InvenTree,SchrodingersGat/InvenTree,inventree/InvenTree,SchrodingersGat/InvenTree,inventree/InvenTree | InvenTree/part/migrations/0072_bomitemsubstitute.py | InvenTree/part/migrations/0072_bomitemsubstitute.py | # Generated by Django 3.2.5 on 2021-10-12 23:24
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('part', '0071_alter_partparametertemplate_name'),
]
operations = [
migrations.CreateModel(
name='BomItemSubstitute',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('bom_item', models.ForeignKey(help_text='Parent BOM item', on_delete=django.db.models.deletion.CASCADE, related_name='substitutes', to='part.bomitem', verbose_name='BOM Item')),
('part', models.ForeignKey(help_text='Substitute part', limit_choices_to={'component': True}, on_delete=django.db.models.deletion.CASCADE, related_name='substitute_items', to='part.part', verbose_name='Part')),
],
),
]
| mit | Python |
|
88087c9416103ae7f56749f59cdfabcd19fb14ab | Add a snippet. | jeremiedecock/snippets,jeremiedecock/snippets,jeremiedecock/snippets,jeremiedecock/snippets,jeremiedecock/snippets,jeremiedecock/snippets,jeremiedecock/snippets,jeremiedecock/snippets,jeremiedecock/snippets,jeremiedecock/snippets,jeremiedecock/snippets,jeremiedecock/snippets,jeremiedecock/snippets | python/notion_api/update_a_page_and_its_icon.py | python/notion_api/update_a_page_and_its_icon.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#################################################################
# Install the Python requests library: pip install requests
# http://docs.python-requests.org/en/master/user/quickstart/
#################################################################
# Src: https://developers.notion.com/reference/patch-page
import requests
import json
with open("NOTION_SECRET_TOKEN", "r") as fd:
NOTION_TOKEN = fd.read().strip()
with open("NOTION_DB_ID", "r") as fd:
NOTION_DB_ID = fd.read().strip()
with open("NOTION_PAGE_ID", "r") as fd:
NOTION_PAGE_ID = fd.read().strip()
REQUEST_URL = f"https://api.notion.com/v1/pages/{NOTION_PAGE_ID}"
HEADER_DICT = {
"Authorization": f"Bearer {NOTION_TOKEN}",
"Content-Type": "application/json",
"Notion-Version": "2021-08-16"
}
DATA_DICT = {
"icon": {
"type": "emoji",
"emoji": "\ud83d\udfe0"
},
"properties": {
"Score": {
"rich_text": [
{
"text": {
"content": "Top!"
}
}
]
}
}
}
resp = requests.patch(REQUEST_URL, headers=HEADER_DICT, data=json.dumps(DATA_DICT))
print(json.dumps(resp.json(), sort_keys=False, indent=4))
#with open("db.json", "w") as fd:
# #json.dump(data, fd) # no pretty print
# json.dump(issue_list, fd, sort_keys=False, indent=4) # pretty print format | mit | Python |
|
a962de79938c73b5c0e0459be7b82265bde76b40 | Test case for LSPI on gridworld. | silgon/rlpy,MDPvis/rlpy,imanolarrieta/RL,BerkeleyAutomation/rlpy,imanolarrieta/RL,MDPvis/rlpy,rlpy/rlpy,BerkeleyAutomation/rlpy,BerkeleyAutomation/rlpy,rlpy/rlpy,imanolarrieta/RL,silgon/rlpy,silgon/rlpy,MDPvis/rlpy,rlpy/rlpy | cases/gridworld/lspi.py | cases/gridworld/lspi.py | #!/usr/bin/env python
__author__ = "William Dabney"
from Domains import GridWorld
from Tools import Logger
from Agents import LSPI
from Representations import Tabular
from Policies import eGreedy
from Experiments import Experiment
def make_experiment(id=1, path="./Results/Temp"):
"""
Each file specifying an experimental setup should contain a
make_experiment function which returns an instance of the Experiment
class with everything set up.
@param id: number used to seed the random number generators
@param path: output directory where logs and results are stored
"""
# Experiment variables
max_steps = 10000
num_policy_checks = 10
## Logging
logger = Logger()
## Domain:
# MAZE = '/Domains/GridWorldMaps/1x3.txt'
maze = './Domains/GridWorldMaps/4x5.txt'
domain = GridWorld(maze, noise=0.3, logger=logger)
## Representation
representation = Tabular(domain, logger, discretization=20)
## Policy
policy = eGreedy(representation, logger, epsilon=0.1)
## Agent
agent = LSPI(representation, policy, domain,
logger, max_steps, max_steps/num_policy_checks)
experiment = Experiment(**locals())
return experiment
if __name__ == '__main__':
path = "./Results/Temp/{domain}/{agent}/{representation}/"
experiment = make_experiment(1, path=path)
experiment.run(visualize_steps=False, # should each learning step be shown?
visualize_learning=False, # show performance runs?
visualize_performance=True) # show value function?
experiment.plot()
experiment.save()
| bsd-3-clause | Python |
|
72559b02424b933322b2e5c6c9873a8a6b63ef78 | Add eclipse update script | perdian/dotfiles,perdian/dotfiles,perdian/dotfiles | environments/auto/macos/bin/eclipse-update.py | environments/auto/macos/bin/eclipse-update.py | #!/usr/bin/python
import os
import subprocess
import sys
p2repositoryLocations = [
"http://download.eclipse.org/eclipse/updates/4.7",
"http://download.eclipse.org/releases/oxygen",
"http://dist.springsource.com/release/TOOLS/update/e4.7/",
"http://jeeeyul.github.io/update/",
"http://andrei.gmxhome.de/eclipse/",
"http://www.nodeclipse.org/updates/markdown/",
"http://plantuml.sourceforge.net/updatesitejuno/",
"http://winterwell.com/software/updatesite/",
"https://raw.githubusercontent.com/satyagraha/gfm_viewer/master/p2-composite/"
]
p2features = [
# Feature groups
"org.eclipse.egit" + ".feature.group",
"org.eclipse.jgit" + ".feature.group",
"org.eclipse.epp.mpc" + ".feature.group",
"org.eclipse.wst.common.fproj" + ".feature.group",
"org.eclipse.jst.common.fproj.enablement.jdt" + ".feature.group",
"org.eclipse.jst.enterprise_ui.feature" + ".feature.group",
"org.eclipse.wst.jsdt.feature" + ".feature.group",
"org.eclipse.wst.json_ui.feature" + ".feature.group",
"org.eclipse.wst.web_ui.feature" + ".feature.group",
"org.eclipse.wst.xml_ui.feature" + ".feature.group",
"org.eclipse.wst.xml.xpath2.processor.feature" + ".feature.group",
"org.eclipse.wst.xsl.feature" + ".feature.group",
"org.eclipse.fx.ide.css.feature" + ".feature.group",
"org.eclipse.m2e.logback.feature" + ".feature.group",
"org.eclipse.m2e.feature" + ".feature.group",
"org.eclipse.m2e.wtp.feature" + ".feature.group",
"org.eclipse.m2e.wtp.jaxrs.feature" + ".feature.group",
"org.eclipse.m2e.wtp.jpa.feature" + ".feature.group",
"org.sonatype.m2e.mavenarchiver.feature" + ".feature.group",
"org.springframework.ide.eclipse.feature" + ".feature.group",
"org.springframework.ide.eclipse.autowire.feature" + ".feature.group",
"org.springframework.ide.eclipse.boot.dash.feature" + ".feature.group",
"org.springframework.ide.eclipse.maven.feature" + ".feature.group",
"org.springframework.ide.eclipse.boot.feature" + ".feature.group",
"AnyEditTools" + ".feature.group",
# Direct plugins
"net.jeeeyul.eclipse.themes.ui",
"net.jeeeyul.eclipse.themes",
"net.sourceforge.plantuml.eclipse",
"winterwell.markdown",
"code.satyagraha.gfm.viewer.plugin"
]
if len(sys.argv) < 2:
sys.exit("Location of eclipse installation must be passed as first parameter!")
else:
eclipseApplicationDirectory = os.path.abspath(sys.argv[1])
eclipseBinaryCommandFile = os.path.join(eclipseApplicationDirectory, "Contents/MacOS/eclipse");
subprocess.call([
eclipseBinaryCommandFile,
"-profile", "SDKProfile",
"-noSplash", "-consolelog",
"-application", "org.eclipse.equinox.p2.director",
"-repository", ",".join(p2repositoryLocations),
"-installIU", ",".join(p2features),
"-destination", eclipseApplicationDirectory
])
| mit | Python |
|
b514cf783d53a5c713911729422239c9b0f0ff99 | Add automatic leak detection python script in examples | edkit/edkit-agent,edkit/edkit-agent,edkit/edkit-agent | client/python/examples/edleak_autodetect.py | client/python/examples/edleak_autodetect.py | import sys
import rpc.ws
import edleak.api
import edleak.slice_runner
def usage():
print('autodetect [period] [duration]')
def print_leaker(leaker):
print('-------------------------------')
print('class : ' + leaker['leak_factor']['class'])
print('leak size : ' + str(leaker['leak_factor']['leak']))
print('call-stack: ')
for caller in leaker['stack']:
print(' ' + caller)
if __name__ == '__main__':
if len(sys.argv) != 3:
usage()
sys.exit(-1)
period = int(sys.argv[1])
duration = int(sys.argv[2])
ws_rpc = rpc.ws.WebService("localhost", 8080)
el = edleak.api.EdLeak(ws_rpc)
runner = edleak.slice_runner.SliceRunner(el)
# First run, to find the leakers
print('Starting 1st run...')
asset = runner.run(period, duration)
allocers = asset.getAllocerList()
leakers = [l for l in allocers if l['leak_factor']['leak'] > 0 and
(l['leak_factor']['class'] == 'linear' or
l['leak_factor']['class'] == 'exp')]
if len(leakers) == 0:
print('No leaks found.')
sys.exit(0)
print(str(len(leakers)) + ' leaks found. Starting 2nd run to retrieve callstacks...')
for leaker in leakers:
el.addStackWatch(leaker['id'])
asset = runner.run(period, duration)
allocers = asset.getAllocerList()
leakers = [l for l in allocers if l['leak_factor']['leak'] > 0 and
(l['leak_factor']['class'] == 'linear' or
l['leak_factor']['class'] == 'exp')]
for leaker in leakers:
if len(leaker['stack']) > 1:
print_leaker(leaker)
| mit | Python |
|
c7b756c69f3fce63208d1378ccee8d76e8574f3f | Add basic_bond_seed_file for 5 bonds. | bsmukasa/bond_analytics | bond_analytics_project/basic_bond_seed_file.py | bond_analytics_project/basic_bond_seed_file.py | import datetime
import os
import django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'bond_analytics_project.settings')
django.setup()
from bondapi.models import Bond
test_bond_list = [
dict(name='test_bond_1', face_value=1000, annual_interest=27.5 * 2, annual_coupon_rate=5.50,
market_interest_rate=5.75, issue_date=datetime.date(1978, 1, 26), settlement_date=datetime.date(2007, 1, 26),
maturity_date=datetime.date(2008, 1, 26), term_to_maturity=1.0, bond_price=99.76, bond_valuation=997.6),
dict(name='test_bond_2', face_value=1000, annual_interest=37.5 * 2, annual_coupon_rate=7.50,
market_interest_rate=6.50, issue_date=datetime.date(1991, 2, 16), settlement_date=datetime.date(2007, 2, 16),
maturity_date=datetime.date(2012, 2, 16), term_to_maturity=5.0, bond_price=104.21, bond_valuation=1042.13),
dict(name='test_bond_3', face_value=1000, annual_interest=25.00 * 2, annual_coupon_rate=5.00,
market_interest_rate=7.00, issue_date=datetime.date(1999, 4, 9), settlement_date=datetime.date(2007, 1, 14),
maturity_date=datetime.date(2020, 4, 9), term_to_maturity=13.2, bond_price=82.92, bond_valuation=829.15),
dict(name='test_bond_4', face_value=1000, annual_interest=45.00 * 2, annual_coupon_rate=9.00,
market_interest_rate=7.25, issue_date=datetime.date(1987, 11, 6), settlement_date=datetime.date(2006, 7, 16),
maturity_date=datetime.date(2028, 11, 6), term_to_maturity=22.3, bond_price=119.22, bond_valuation=1192.16),
dict(name='test_bond_5', face_value=1000, annual_interest=35.00 * 2, annual_coupon_rate=7.00,
market_interest_rate=7.25, issue_date=datetime.date(2006, 10, 12), settlement_date=datetime.date(2006, 10, 13),
maturity_date=datetime.date(2036, 10, 13), term_to_maturity=30, bond_price=96.96, bond_valuation=969.58)
]
if __name__ == '__main__':
print('Resetting database.')
Bond.objects.all().delete()
print('Starting seeding.')
for bond in test_bond_list:
new_bond = Bond(
name=bond['name'],
face_value=bond['face_value'],
annual_payment_frequency=2,
annual_coupon_rate=bond['annual_coupon_rate'],
issue_date=bond['issue_date'],
settlement_date=bond['settlement_date'],
maturity_date=bond['maturity_date'],
)
new_bond.save()
print('Bond {} has been created and saved.'.format(new_bond.name))
print('Seeding complete.')
| mit | Python |
|
04da8d531267972554c6300c24a5a7b2c7def59d | add basic unit testing for appliance instances (incomplete) | dssg/wikienergy,dssg/wikienergy,dssg/wikienergy,dssg/wikienergy,dssg/wikienergy | tests/test_appliance_instance.py | tests/test_appliance_instance.py | import sys
sys.path.append('..')
import disaggregator as da
import unittest
import pandas as pd
import numpy as np
class ApplianceInstanceTestCase(unittest.TestCase):
def setUp(self):
indices = [pd.date_range('1/1/2013', periods=96, freq='15T'),
pd.date_range('1/2/2013', periods=96, freq='15T')]
data = [np.zeros(96),np.zeros(96)]
series = [pd.Series(d, index=i) for d,i in zip(data,indices)]
self.traces = [da.ApplianceTrace(s,{}) for s in series]
self.normal_instance = da.ApplianceInstance(self.traces)
def test_get_traces(self):
self.assertIsNotNone(self.normal_instance.get_traces(),
'instance should have traces')
if __name__ == "__main__":
unittest.main()
| mit | Python |
|
879744e19cab5cc7357912ba670d200adfd58be6 | add aur-update | tobi-wan-kenobi/bumblebee-status,tobi-wan-kenobi/bumblebee-status | bumblebee_status/modules/contrib/aur-update.py | bumblebee_status/modules/contrib/aur-update.py | """Check updates for AUR.
Requires the following packages:
* yay (used as default)
Note - You can replace yay by changing the "yay -Qum"
command for your preferred AUR helper. Few examples:
paru -Qum
pikaur -Qua
rua upgrade --printonly
trizen -Su --aur --quiet
yay -Qum
contributed by `ishaanbhimwal <https://github.com/ishaanbhimwal>`_ - many thanks!
"""
import logging
import core.module
import core.widget
import core.decorators
import util.cli
class Module(core.module.Module):
@core.decorators.every(minutes=60)
def __init__(self, config, theme):
super().__init__(config, theme, core.widget.Widget(self.utilization))
self.background = True
self.__packages = 0
self.__error = False
@property
def __format(self):
return self.parameter("format", "Update AUR: {}")
def utilization(self, widget):
return self.__format.format(self.__packages)
def hidden(self):
return self.__packages == 0 and not self.__error
def update(self):
self.__error = False
code, result = util.cli.execute(
"yay -Qum", ignore_errors=True, return_exitcode=True
)
if code == 0:
self.__packages = len(result.strip().split("\n"))
elif code == 2:
self.__packages = 0
else:
self.__error = True
logging.error("yay -Qum exited with {}: {}".format(code, result))
def state(self, widget):
if self.__error:
return "warning"
return self.threshold_state(self.__packages, 1, 100)
# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
| mit | Python |
|
4175f27a03be52baa8b4245df96a03e6bbd22310 | Add test for pygame sound play hook | nickodell/morse-code | modulation_test.py | modulation_test.py | import pygame
import random
from demodulate.cfg import *
from gen_tone import *
if __name__ == "__main__":
pygame.mixer.pre_init(frequency = int(SAMPLE_FREQ), channels = 1)
pygame.mixer.init()
WPM = random.uniform(2,20)
pattern = [1,0,1,1,1,0,0,0,0,0,0,0] # morse code 'A'
#gen_test_data()
data = gen_tone(pattern, WPM)
snd = pygame.sndarray.make_sound(data)
snd.play()
| mit | Python |
|
cfeab0e8f704a4681e1ec887b3ce116839557af9 | update tests to changes in graph_lasso | victorbergelin/scikit-learn,frank-tancf/scikit-learn,adamgreenhall/scikit-learn,zorroblue/scikit-learn,zuku1985/scikit-learn,Aasmi/scikit-learn,jereze/scikit-learn,potash/scikit-learn,phdowling/scikit-learn,kjung/scikit-learn,Akshay0724/scikit-learn,fzalkow/scikit-learn,equialgo/scikit-learn,jaidevd/scikit-learn,466152112/scikit-learn,AlexanderFabisch/scikit-learn,LohithBlaze/scikit-learn,ivannz/scikit-learn,glemaitre/scikit-learn,AnasGhrab/scikit-learn,shangwuhencc/scikit-learn,h2educ/scikit-learn,OshynSong/scikit-learn,ldirer/scikit-learn,zhenv5/scikit-learn,PatrickChrist/scikit-learn,ephes/scikit-learn,plissonf/scikit-learn,fzalkow/scikit-learn,3manuek/scikit-learn,khkaminska/scikit-learn,MohammedWasim/scikit-learn,yanlend/scikit-learn,marcocaccin/scikit-learn,ClimbsRocks/scikit-learn,nelson-liu/scikit-learn,betatim/scikit-learn,ZenDevelopmentSystems/scikit-learn,nesterione/scikit-learn,nomadcube/scikit-learn,djgagne/scikit-learn,krez13/scikit-learn,voxlol/scikit-learn,cainiaocome/scikit-learn,pypot/scikit-learn,nvoron23/scikit-learn,belltailjp/scikit-learn,joshloyal/scikit-learn,UNR-AERIAL/scikit-learn,mayblue9/scikit-learn,belltailjp/scikit-learn,Garrett-R/scikit-learn,mattgiguere/scikit-learn,russel1237/scikit-learn,rishikksh20/scikit-learn,xiaoxiamii/scikit-learn,dsquareindia/scikit-learn,huzq/scikit-learn,ChanderG/scikit-learn,Clyde-fare/scikit-learn,clemkoa/scikit-learn,JsNoNo/scikit-learn,larsmans/scikit-learn,trankmichael/scikit-learn,devanshdalal/scikit-learn,vybstat/scikit-learn,xzh86/scikit-learn,amueller/scikit-learn,madjelan/scikit-learn,ahoyosid/scikit-learn,imaculate/scikit-learn,xubenben/scikit-learn,hugobowne/scikit-learn,hitszxp/scikit-learn,0x0all/scikit-learn,maheshakya/scikit-learn,CVML/scikit-learn,vigilv/scikit-learn,yyjiang/scikit-learn,anurag313/scikit-learn,B3AU/waveTree,harshaneelhg/scikit-learn,pv/scikit-learn,mhdella/scikit-learn,akionakamura/scikit-learn,petosegan/scikit-learn,sonnyhu/scikit-learn,chrsrds/scikit-learn,sinhrks/scikit-learn,rahuldhote/scikit-learn,victorbergelin/scikit-learn,jkarnows/scikit-learn,roxyboy/scikit-learn,pompiduskus/scikit-learn,hainm/scikit-learn,liangz0707/scikit-learn,abhishekgahlot/scikit-learn,hsuantien/scikit-learn,bhargav/scikit-learn,alvarofierroclavero/scikit-learn,yask123/scikit-learn,meduz/scikit-learn,scikit-learn/scikit-learn,ogrisel/scikit-learn,henrykironde/scikit-learn,florian-f/sklearn,procoder317/scikit-learn,tomlof/scikit-learn,MohammedWasim/scikit-learn,hsiaoyi0504/scikit-learn,ChanChiChoi/scikit-learn,simon-pepin/scikit-learn,thilbern/scikit-learn,JPFrancoia/scikit-learn,rajat1994/scikit-learn,NunoEdgarGub1/scikit-learn,yyjiang/scikit-learn,ClimbsRocks/scikit-learn,untom/scikit-learn,RayMick/scikit-learn,jlegendary/scikit-learn,AIML/scikit-learn,cwu2011/scikit-learn,untom/scikit-learn,jblackburne/scikit-learn,shikhardb/scikit-learn,robbymeals/scikit-learn,procoder317/scikit-learn,zhenv5/scikit-learn,xuewei4d/scikit-learn,zorojean/scikit-learn,Srisai85/scikit-learn,fyffyt/scikit-learn,Windy-Ground/scikit-learn,qifeigit/scikit-learn,mattgiguere/scikit-learn,zihua/scikit-learn,MechCoder/scikit-learn,rexshihaoren/scikit-learn,davidgbe/scikit-learn,nrhine1/scikit-learn,davidgbe/scikit-learn,waterponey/scikit-learn,thientu/scikit-learn,rrohan/scikit-learn,MechCoder/scikit-learn,jorik041/scikit-learn,mrshu/scikit-learn,theoryno3/scikit-learn,victorbergelin/scikit-learn,herilalaina/scikit-learn,larsmans/scikit-learn,Clyde-fare/scikit-learn,Aasmi/scikit-learn,jzt5132/scikit-learn,PrashntS/scikit-learn,belltailjp/scikit-learn,tmhm/scikit-learn,mfjb/scikit-learn,vibhorag/scikit-learn,samzhang111/scikit-learn,AlexandreAbraham/scikit-learn,rsivapr/scikit-learn,depet/scikit-learn,alexsavio/scikit-learn,fyffyt/scikit-learn,mblondel/scikit-learn,eickenberg/scikit-learn,ZenDevelopmentSystems/scikit-learn,rahul-c1/scikit-learn,B3AU/waveTree,RomainBrault/scikit-learn,Nyker510/scikit-learn,glennq/scikit-learn,Barmaley-exe/scikit-learn,lin-credible/scikit-learn,ashhher3/scikit-learn,ltiao/scikit-learn,bikong2/scikit-learn,jmetzen/scikit-learn,raghavrv/scikit-learn,pkruskal/scikit-learn,RPGOne/scikit-learn,arabenjamin/scikit-learn,NelisVerhoef/scikit-learn,wazeerzulfikar/scikit-learn,cl4rke/scikit-learn,saiwing-yeung/scikit-learn,jayflo/scikit-learn,walterreade/scikit-learn,potash/scikit-learn,henrykironde/scikit-learn,ssaeger/scikit-learn,vermouthmjl/scikit-learn,spallavolu/scikit-learn,raghavrv/scikit-learn,0asa/scikit-learn,andaag/scikit-learn,potash/scikit-learn,466152112/scikit-learn,ldirer/scikit-learn,alvarofierroclavero/scikit-learn,sonnyhu/scikit-learn,Fireblend/scikit-learn,Fireblend/scikit-learn,wazeerzulfikar/scikit-learn,ChanderG/scikit-learn,rvraghav93/scikit-learn,fabioticconi/scikit-learn,kmike/scikit-learn,mlyundin/scikit-learn,iismd17/scikit-learn,cl4rke/scikit-learn,xzh86/scikit-learn,wzbozon/scikit-learn,huobaowangxi/scikit-learn,Vimos/scikit-learn,zihua/scikit-learn,fabioticconi/scikit-learn,glouppe/scikit-learn,meduz/scikit-learn,fzalkow/scikit-learn,bnaul/scikit-learn,justincassidy/scikit-learn,pv/scikit-learn,cl4rke/scikit-learn,fabianp/scikit-learn,nhejazi/scikit-learn,ankurankan/scikit-learn,shikhardb/scikit-learn,q1ang/scikit-learn,robbymeals/scikit-learn,MatthieuBizien/scikit-learn,massmutual/scikit-learn,RPGOne/scikit-learn,arabenjamin/scikit-learn,ivannz/scikit-learn,kashif/scikit-learn,fabioticconi/scikit-learn,mikebenfield/scikit-learn,wlamond/scikit-learn,kagayakidan/scikit-learn,kashif/scikit-learn,evgchz/scikit-learn,tdhopper/scikit-learn,pypot/scikit-learn,Fireblend/scikit-learn,mrshu/scikit-learn,Achuth17/scikit-learn,sergeyf/scikit-learn,wazeerzulfikar/scikit-learn,mayblue9/scikit-learn,mblondel/scikit-learn,mwv/scikit-learn,mikebenfield/scikit-learn,huobaowangxi/scikit-learn,pianomania/scikit-learn,zaxtax/scikit-learn,IssamLaradji/scikit-learn,shangwuhencc/scikit-learn,vigilv/scikit-learn,rahul-c1/scikit-learn,nesterione/scikit-learn,gclenaghan/scikit-learn,Akshay0724/scikit-learn,jakobworldpeace/scikit-learn,rohanp/scikit-learn,smartscheduling/scikit-learn-categorical-tree,B3AU/waveTree,zorojean/scikit-learn,Nyker510/scikit-learn,AnasGhrab/scikit-learn,marcocaccin/scikit-learn,chrisburr/scikit-learn,AnasGhrab/scikit-learn,jkarnows/scikit-learn,jm-begon/scikit-learn,xyguo/scikit-learn,sanketloke/scikit-learn,eickenberg/scikit-learn,fzalkow/scikit-learn,Adai0808/scikit-learn,mojoboss/scikit-learn,sarahgrogan/scikit-learn,aewhatley/scikit-learn,PrashntS/scikit-learn,Titan-C/scikit-learn,btabibian/scikit-learn,abimannans/scikit-learn,shusenl/scikit-learn,vortex-ape/scikit-learn,tmhm/scikit-learn,costypetrisor/scikit-learn,alexsavio/scikit-learn,plissonf/scikit-learn,jakirkham/scikit-learn,ahoyosid/scikit-learn,zuku1985/scikit-learn,mlyundin/scikit-learn,jkarnows/scikit-learn,xyguo/scikit-learn,PatrickOReilly/scikit-learn,huobaowangxi/scikit-learn,gclenaghan/scikit-learn,terkkila/scikit-learn,liberatorqjw/scikit-learn,trankmichael/scikit-learn,nomadcube/scikit-learn,vybstat/scikit-learn,cauchycui/scikit-learn,qifeigit/scikit-learn,poryfly/scikit-learn,herilalaina/scikit-learn,hrjn/scikit-learn,MartinDelzant/scikit-learn,appapantula/scikit-learn,shusenl/scikit-learn,ogrisel/scikit-learn,samzhang111/scikit-learn,samuel1208/scikit-learn,adamgreenhall/scikit-learn,aewhatley/scikit-learn,luo66/scikit-learn,vshtanko/scikit-learn,rishikksh20/scikit-learn,glennq/scikit-learn,zaxtax/scikit-learn,macks22/scikit-learn,gotomypc/scikit-learn,rahuldhote/scikit-learn,saiwing-yeung/scikit-learn,PatrickOReilly/scikit-learn,rishikksh20/scikit-learn,rsivapr/scikit-learn,bhargav/scikit-learn,jorik041/scikit-learn,liangz0707/scikit-learn,eg-zhang/scikit-learn,alexeyum/scikit-learn,bikong2/scikit-learn,samzhang111/scikit-learn,fbagirov/scikit-learn,jseabold/scikit-learn,mojoboss/scikit-learn,joernhees/scikit-learn,toastedcornflakes/scikit-learn,xiaoxiamii/scikit-learn,tdhopper/scikit-learn,abimannans/scikit-learn,quheng/scikit-learn,appapantula/scikit-learn,Myasuka/scikit-learn,heli522/scikit-learn,untom/scikit-learn,alvarofierroclavero/scikit-learn,hugobowne/scikit-learn,moutai/scikit-learn,simon-pepin/scikit-learn,hdmetor/scikit-learn,rsivapr/scikit-learn,iismd17/scikit-learn,ChanChiChoi/scikit-learn,nvoron23/scikit-learn,bthirion/scikit-learn,mblondel/scikit-learn,ndingwall/scikit-learn,ltiao/scikit-learn,jpautom/scikit-learn,devanshdalal/scikit-learn,glemaitre/scikit-learn,harshaneelhg/scikit-learn,mattilyra/scikit-learn,mattgiguere/scikit-learn,robin-lai/scikit-learn,rajat1994/scikit-learn,AlexanderFabisch/scikit-learn,victorbergelin/scikit-learn,spallavolu/scikit-learn,yyjiang/scikit-learn,ChanChiChoi/scikit-learn,mfjb/scikit-learn,NunoEdgarGub1/scikit-learn,vortex-ape/scikit-learn,RachitKansal/scikit-learn,nhejazi/scikit-learn,meduz/scikit-learn,hainm/scikit-learn,davidgbe/scikit-learn,cybernet14/scikit-learn,f3r/scikit-learn,hugobowne/scikit-learn,ngoix/OCRF,florian-f/sklearn,pompiduskus/scikit-learn,toastedcornflakes/scikit-learn,dsquareindia/scikit-learn,poryfly/scikit-learn,etkirsch/scikit-learn,MartinDelzant/scikit-learn,xwolf12/scikit-learn,Lawrence-Liu/scikit-learn,hitszxp/scikit-learn,nmayorov/scikit-learn,bigdataelephants/scikit-learn,henridwyer/scikit-learn,ningchi/scikit-learn,ElDeveloper/scikit-learn,gclenaghan/scikit-learn,mjudsp/Tsallis,mlyundin/scikit-learn,fabianp/scikit-learn,carrillo/scikit-learn,Djabbz/scikit-learn,jzt5132/scikit-learn,DonBeo/scikit-learn,abimannans/scikit-learn,tmhm/scikit-learn,dsullivan7/scikit-learn,fredhusser/scikit-learn,pratapvardhan/scikit-learn,zorroblue/scikit-learn,IssamLaradji/scikit-learn,themrmax/scikit-learn,kevin-intel/scikit-learn,mxjl620/scikit-learn,rajat1994/scikit-learn,cybernet14/scikit-learn,shenzebang/scikit-learn,JeanKossaifi/scikit-learn,ldirer/scikit-learn,vortex-ape/scikit-learn,mugizico/scikit-learn,arahuja/scikit-learn,AlexRobson/scikit-learn,h2educ/scikit-learn,clemkoa/scikit-learn,chrsrds/scikit-learn,abhishekkrthakur/scikit-learn,dingocuster/scikit-learn,dingocuster/scikit-learn,xyguo/scikit-learn,DonBeo/scikit-learn,wazeerzulfikar/scikit-learn,wlamond/scikit-learn,huzq/scikit-learn,idlead/scikit-learn,shahankhatch/scikit-learn,Djabbz/scikit-learn,bhargav/scikit-learn,akionakamura/scikit-learn,BiaDarkia/scikit-learn,hlin117/scikit-learn,Titan-C/scikit-learn,xwolf12/scikit-learn,cdegroc/scikit-learn,UNR-AERIAL/scikit-learn,imaculate/scikit-learn,manhhomienbienthuy/scikit-learn,Garrett-R/scikit-learn,heli522/scikit-learn,MohammedWasim/scikit-learn,eickenberg/scikit-learn,CVML/scikit-learn,vshtanko/scikit-learn,madjelan/scikit-learn,zhenv5/scikit-learn,rohanp/scikit-learn,cauchycui/scikit-learn,PatrickOReilly/scikit-learn,DSLituiev/scikit-learn,jakobworldpeace/scikit-learn,AIML/scikit-learn,3manuek/scikit-learn,pnedunuri/scikit-learn,qifeigit/scikit-learn,henrykironde/scikit-learn,madjelan/scikit-learn,pianomania/scikit-learn,mwv/scikit-learn,betatim/scikit-learn,vivekmishra1991/scikit-learn,thilbern/scikit-learn,yonglehou/scikit-learn,alexsavio/scikit-learn,liangz0707/scikit-learn,JsNoNo/scikit-learn,espg/scikit-learn,mayblue9/scikit-learn,stylianos-kampakis/scikit-learn,MartinSavc/scikit-learn,liberatorqjw/scikit-learn,jereze/scikit-learn,treycausey/scikit-learn,mattilyra/scikit-learn,huzq/scikit-learn,chrsrds/scikit-learn,dingocuster/scikit-learn,vibhorag/scikit-learn,btabibian/scikit-learn,deepesch/scikit-learn,mxjl620/scikit-learn,billy-inn/scikit-learn,nmayorov/scikit-learn,alvarofierroclavero/scikit-learn,plissonf/scikit-learn,lbishal/scikit-learn,maheshakya/scikit-learn,vinayak-mehta/scikit-learn,altairpearl/scikit-learn,JPFrancoia/scikit-learn,mfjb/scikit-learn,aminert/scikit-learn,mlyundin/scikit-learn,r-mart/scikit-learn,mehdidc/scikit-learn,Obus/scikit-learn,harshaneelhg/scikit-learn,AnasGhrab/scikit-learn,dhruv13J/scikit-learn,CforED/Machine-Learning,Barmaley-exe/scikit-learn,shenzebang/scikit-learn,hainm/scikit-learn,yanlend/scikit-learn,lenovor/scikit-learn,frank-tancf/scikit-learn,fabioticconi/scikit-learn,theoryno3/scikit-learn,0asa/scikit-learn,vinayak-mehta/scikit-learn,voxlol/scikit-learn,waterponey/scikit-learn,dhruv13J/scikit-learn,shikhardb/scikit-learn,r-mart/scikit-learn,AlexRobson/scikit-learn,manashmndl/scikit-learn,evgchz/scikit-learn,anurag313/scikit-learn,idlead/scikit-learn,yyjiang/scikit-learn,olologin/scikit-learn,ndingwall/scikit-learn,anirudhjayaraman/scikit-learn,kashif/scikit-learn,MartinDelzant/scikit-learn,anntzer/scikit-learn,fabianp/scikit-learn,rishikksh20/scikit-learn,AlexRobson/scikit-learn,RachitKansal/scikit-learn,poryfly/scikit-learn,jayflo/scikit-learn,rvraghav93/scikit-learn,sgenoud/scikit-learn,dsullivan7/scikit-learn,saiwing-yeung/scikit-learn,sgenoud/scikit-learn,murali-munna/scikit-learn,aetilley/scikit-learn,mrshu/scikit-learn,YinongLong/scikit-learn,quheng/scikit-learn,henridwyer/scikit-learn,loli/sklearn-ensembletrees,sumspr/scikit-learn,UNR-AERIAL/scikit-learn,ZENGXH/scikit-learn,yask123/scikit-learn,jakirkham/scikit-learn,wanggang3333/scikit-learn,ZenDevelopmentSystems/scikit-learn,mxjl620/scikit-learn,samuel1208/scikit-learn,MohammedWasim/scikit-learn,AlexandreAbraham/scikit-learn,schets/scikit-learn,jorge2703/scikit-learn,bikong2/scikit-learn,xubenben/scikit-learn,jaidevd/scikit-learn,anurag313/scikit-learn,mugizico/scikit-learn,rvraghav93/scikit-learn,cl4rke/scikit-learn,Vimos/scikit-learn,tosolveit/scikit-learn,stylianos-kampakis/scikit-learn,Sentient07/scikit-learn,nelson-liu/scikit-learn,jorik041/scikit-learn,AlexanderFabisch/scikit-learn,espg/scikit-learn,sumspr/scikit-learn,petosegan/scikit-learn,YinongLong/scikit-learn,AlexandreAbraham/scikit-learn,andrewnc/scikit-learn,Sentient07/scikit-learn,Jimmy-Morzaria/scikit-learn,ZENGXH/scikit-learn,JosmanPS/scikit-learn,TomDLT/scikit-learn,r-mart/scikit-learn,MechCoder/scikit-learn,ndingwall/scikit-learn,vinayak-mehta/scikit-learn,herilalaina/scikit-learn,harshaneelhg/scikit-learn,ankurankan/scikit-learn,zorroblue/scikit-learn,NelisVerhoef/scikit-learn,nesterione/scikit-learn,pkruskal/scikit-learn,icdishb/scikit-learn,kjung/scikit-learn,MatthieuBizien/scikit-learn,mhdella/scikit-learn,rrohan/scikit-learn,hitszxp/scikit-learn,fbagirov/scikit-learn,depet/scikit-learn,walterreade/scikit-learn,lucidfrontier45/scikit-learn,andaag/scikit-learn,lesteve/scikit-learn,jorge2703/scikit-learn,vivekmishra1991/scikit-learn,aabadie/scikit-learn,jmetzen/scikit-learn,smartscheduling/scikit-learn-categorical-tree,jzt5132/scikit-learn,khkaminska/scikit-learn,ssaeger/scikit-learn,alexeyum/scikit-learn,tdhopper/scikit-learn,robbymeals/scikit-learn,untom/scikit-learn,aabadie/scikit-learn,Garrett-R/scikit-learn,ZenDevelopmentSystems/scikit-learn,pratapvardhan/scikit-learn,Titan-C/scikit-learn,ycaihua/scikit-learn,wlamond/scikit-learn,procoder317/scikit-learn,ssaeger/scikit-learn,aewhatley/scikit-learn,kevin-intel/scikit-learn,mayblue9/scikit-learn,xiaoxiamii/scikit-learn,macks22/scikit-learn,RayMick/scikit-learn,arjoly/scikit-learn,mehdidc/scikit-learn,simon-pepin/scikit-learn,anntzer/scikit-learn,tomlof/scikit-learn,jmschrei/scikit-learn,phdowling/scikit-learn,CforED/Machine-Learning,zihua/scikit-learn,vivekmishra1991/scikit-learn,aetilley/scikit-learn,lesteve/scikit-learn,smartscheduling/scikit-learn-categorical-tree,PatrickChrist/scikit-learn,pratapvardhan/scikit-learn,herilalaina/scikit-learn,kaichogami/scikit-learn,hlin117/scikit-learn,mojoboss/scikit-learn,toastedcornflakes/scikit-learn,OshynSong/scikit-learn,NunoEdgarGub1/scikit-learn,poryfly/scikit-learn,AlexandreAbraham/scikit-learn,samzhang111/scikit-learn,yonglehou/scikit-learn,shenzebang/scikit-learn,thientu/scikit-learn,xuewei4d/scikit-learn,LohithBlaze/scikit-learn,elkingtonmcb/scikit-learn,MartinSavc/scikit-learn,shyamalschandra/scikit-learn,Obus/scikit-learn,amueller/scikit-learn,IndraVikas/scikit-learn,russel1237/scikit-learn,JPFrancoia/scikit-learn,trungnt13/scikit-learn,nmayorov/scikit-learn,nrhine1/scikit-learn,mojoboss/scikit-learn,walterreade/scikit-learn,jakobworldpeace/scikit-learn,xavierwu/scikit-learn,ilo10/scikit-learn,russel1237/scikit-learn,TomDLT/scikit-learn,pypot/scikit-learn,kaichogami/scikit-learn,khkaminska/scikit-learn,espg/scikit-learn,robin-lai/scikit-learn,samuel1208/scikit-learn,RayMick/scikit-learn,sinhrks/scikit-learn,anurag313/scikit-learn,ky822/scikit-learn,mattilyra/scikit-learn,MartinDelzant/scikit-learn,MatthieuBizien/scikit-learn,cybernet14/scikit-learn,f3r/scikit-learn,UNR-AERIAL/scikit-learn,smartscheduling/scikit-learn-categorical-tree,h2educ/scikit-learn,hitszxp/scikit-learn,marcocaccin/scikit-learn,LiaoPan/scikit-learn,mikebenfield/scikit-learn,0asa/scikit-learn,Nyker510/scikit-learn,vivekmishra1991/scikit-learn,beepee14/scikit-learn,zhenv5/scikit-learn,bnaul/scikit-learn,nesterione/scikit-learn,mattgiguere/scikit-learn,loli/sklearn-ensembletrees,mattilyra/scikit-learn,Lawrence-Liu/scikit-learn,petosegan/scikit-learn,potash/scikit-learn,phdowling/scikit-learn,cainiaocome/scikit-learn,tdhopper/scikit-learn,mjgrav2001/scikit-learn,CVML/scikit-learn,kylerbrown/scikit-learn,aflaxman/scikit-learn,justincassidy/scikit-learn,Achuth17/scikit-learn,mugizico/scikit-learn,btabibian/scikit-learn,RomainBrault/scikit-learn,rsivapr/scikit-learn,zuku1985/scikit-learn,trungnt13/scikit-learn,jorge2703/scikit-learn,madjelan/scikit-learn,beepee14/scikit-learn,theoryno3/scikit-learn,PatrickOReilly/scikit-learn,jseabold/scikit-learn,depet/scikit-learn,ClimbsRocks/scikit-learn,elkingtonmcb/scikit-learn,adamgreenhall/scikit-learn,tosolveit/scikit-learn,manashmndl/scikit-learn,lin-credible/scikit-learn,mjudsp/Tsallis,kmike/scikit-learn,giorgiop/scikit-learn,ogrisel/scikit-learn,fengzhyuan/scikit-learn,mhue/scikit-learn,xubenben/scikit-learn,altairpearl/scikit-learn,AIML/scikit-learn,mblondel/scikit-learn,jjx02230808/project0223,hdmetor/scikit-learn,MartinSavc/scikit-learn,RomainBrault/scikit-learn,wanggang3333/scikit-learn,pkruskal/scikit-learn,B3AU/waveTree,kylerbrown/scikit-learn,aflaxman/scikit-learn,ldirer/scikit-learn,Windy-Ground/scikit-learn,joshloyal/scikit-learn,ssaeger/scikit-learn,kmike/scikit-learn,nikitasingh981/scikit-learn,raghavrv/scikit-learn,moutai/scikit-learn,roxyboy/scikit-learn,ngoix/OCRF,chrisburr/scikit-learn,rahuldhote/scikit-learn,bthirion/scikit-learn,vermouthmjl/scikit-learn,hsiaoyi0504/scikit-learn,xzh86/scikit-learn,CforED/Machine-Learning,alexeyum/scikit-learn,Garrett-R/scikit-learn,michigraber/scikit-learn,0asa/scikit-learn,andrewnc/scikit-learn,altairpearl/scikit-learn,vshtanko/scikit-learn,quheng/scikit-learn,ycaihua/scikit-learn,IssamLaradji/scikit-learn,Barmaley-exe/scikit-learn,giorgiop/scikit-learn,liyu1990/sklearn,simon-pepin/scikit-learn,cwu2011/scikit-learn,djgagne/scikit-learn,jblackburne/scikit-learn,Myasuka/scikit-learn,bigdataelephants/scikit-learn,thientu/scikit-learn,terkkila/scikit-learn,jblackburne/scikit-learn,NelisVerhoef/scikit-learn,waterponey/scikit-learn,stylianos-kampakis/scikit-learn,Myasuka/scikit-learn,NelisVerhoef/scikit-learn,kagayakidan/scikit-learn,equialgo/scikit-learn,robin-lai/scikit-learn,murali-munna/scikit-learn,ankurankan/scikit-learn,nikitasingh981/scikit-learn,joshloyal/scikit-learn,LohithBlaze/scikit-learn,fbagirov/scikit-learn,mugizico/scikit-learn,Vimos/scikit-learn,sumspr/scikit-learn,themrmax/scikit-learn,zorroblue/scikit-learn,jpautom/scikit-learn,vshtanko/scikit-learn,bnaul/scikit-learn,amueller/scikit-learn,xavierwu/scikit-learn,jm-begon/scikit-learn,devanshdalal/scikit-learn,larsmans/scikit-learn,HolgerPeters/scikit-learn,jakirkham/scikit-learn,Myasuka/scikit-learn,zorojean/scikit-learn,DSLituiev/scikit-learn,abhishekgahlot/scikit-learn,jayflo/scikit-learn,jakirkham/scikit-learn,elkingtonmcb/scikit-learn,procoder317/scikit-learn,DonBeo/scikit-learn,nhejazi/scikit-learn,themrmax/scikit-learn,ngoix/OCRF,mwv/scikit-learn,hdmetor/scikit-learn,mjgrav2001/scikit-learn,LohithBlaze/scikit-learn,glemaitre/scikit-learn,lazywei/scikit-learn,akionakamura/scikit-learn,r-mart/scikit-learn,robin-lai/scikit-learn,depet/scikit-learn,JPFrancoia/scikit-learn,russel1237/scikit-learn,aflaxman/scikit-learn,AlexRobson/scikit-learn,jblackburne/scikit-learn,quheng/scikit-learn,mhdella/scikit-learn,djgagne/scikit-learn,heli522/scikit-learn,hrjn/scikit-learn,liyu1990/sklearn,RachitKansal/scikit-learn,xwolf12/scikit-learn,elkingtonmcb/scikit-learn,hrjn/scikit-learn,rsivapr/scikit-learn,luo66/scikit-learn,loli/semisupervisedforests,Vimos/scikit-learn,idlead/scikit-learn,eickenberg/scikit-learn,ivannz/scikit-learn,Obus/scikit-learn,thilbern/scikit-learn,bikong2/scikit-learn,jaidevd/scikit-learn,anntzer/scikit-learn,lucidfrontier45/scikit-learn,abhishekgahlot/scikit-learn,pompiduskus/scikit-learn,clemkoa/scikit-learn,ChanderG/scikit-learn,zuku1985/scikit-learn,Adai0808/scikit-learn,CVML/scikit-learn,jpautom/scikit-learn,saiwing-yeung/scikit-learn,kjung/scikit-learn,Jimmy-Morzaria/scikit-learn,wzbozon/scikit-learn,iismd17/scikit-learn,CforED/Machine-Learning,deepesch/scikit-learn,glennq/scikit-learn,0x0all/scikit-learn,aminert/scikit-learn,costypetrisor/scikit-learn,lenovor/scikit-learn,kmike/scikit-learn,eg-zhang/scikit-learn,abimannans/scikit-learn,loli/semisupervisedforests,ngoix/OCRF,billy-inn/scikit-learn,jayflo/scikit-learn,Jimmy-Morzaria/scikit-learn,frank-tancf/scikit-learn,ChanChiChoi/scikit-learn,shahankhatch/scikit-learn,tomlof/scikit-learn,JeanKossaifi/scikit-learn,maheshakya/scikit-learn,andaag/scikit-learn,vortex-ape/scikit-learn,sumspr/scikit-learn,liyu1990/sklearn,TomDLT/scikit-learn,Garrett-R/scikit-learn,Achuth17/scikit-learn,aabadie/scikit-learn,mikebenfield/scikit-learn,jm-begon/scikit-learn,sgenoud/scikit-learn,chrsrds/scikit-learn,arabenjamin/scikit-learn,billy-inn/scikit-learn,olologin/scikit-learn,abhishekkrthakur/scikit-learn,bhargav/scikit-learn,liyu1990/sklearn,ElDeveloper/scikit-learn,kylerbrown/scikit-learn,shenzebang/scikit-learn,lazywei/scikit-learn,deepesch/scikit-learn,lbishal/scikit-learn,aminert/scikit-learn,gotomypc/scikit-learn,loli/sklearn-ensembletrees,scikit-learn/scikit-learn,ishanic/scikit-learn,appapantula/scikit-learn,florian-f/sklearn,IshankGulati/scikit-learn,IshankGulati/scikit-learn,jmetzen/scikit-learn,ogrisel/scikit-learn,michigraber/scikit-learn,waterponey/scikit-learn,JosmanPS/scikit-learn,glouppe/scikit-learn,imaculate/scikit-learn,betatim/scikit-learn,lazywei/scikit-learn,vigilv/scikit-learn,tawsifkhan/scikit-learn,q1ang/scikit-learn,raghavrv/scikit-learn,sarahgrogan/scikit-learn,shyamalschandra/scikit-learn,icdishb/scikit-learn,jseabold/scikit-learn,ahoyosid/scikit-learn,shahankhatch/scikit-learn,carrillo/scikit-learn,zaxtax/scikit-learn,siutanwong/scikit-learn,ankurankan/scikit-learn,Barmaley-exe/scikit-learn,walterreade/scikit-learn,BiaDarkia/scikit-learn,Akshay0724/scikit-learn,lbishal/scikit-learn,ashhher3/scikit-learn,pnedunuri/scikit-learn,yunfeilu/scikit-learn,petosegan/scikit-learn,jseabold/scikit-learn,jakobworldpeace/scikit-learn,lin-credible/scikit-learn,vibhorag/scikit-learn,anirudhjayaraman/scikit-learn,arahuja/scikit-learn,abhishekkrthakur/scikit-learn,pianomania/scikit-learn,jlegendary/scikit-learn,pianomania/scikit-learn,joshloyal/scikit-learn,xavierwu/scikit-learn,ltiao/scikit-learn,LiaoPan/scikit-learn,rahuldhote/scikit-learn,justincassidy/scikit-learn,costypetrisor/scikit-learn,Sentient07/scikit-learn,tosolveit/scikit-learn,jjx02230808/project0223,mhue/scikit-learn,voxlol/scikit-learn,rahul-c1/scikit-learn,ephes/scikit-learn,davidgbe/scikit-learn,lucidfrontier45/scikit-learn,DSLituiev/scikit-learn,ClimbsRocks/scikit-learn,HolgerPeters/scikit-learn,nrhine1/scikit-learn,trungnt13/scikit-learn,lucidfrontier45/scikit-learn,idlead/scikit-learn,henridwyer/scikit-learn,Sentient07/scikit-learn,466152112/scikit-learn,henridwyer/scikit-learn,chrisburr/scikit-learn,JsNoNo/scikit-learn,eickenberg/scikit-learn,pythonvietnam/scikit-learn,krez13/scikit-learn,Jimmy-Morzaria/scikit-learn,Djabbz/scikit-learn,sergeyf/scikit-learn,PrashntS/scikit-learn,aewhatley/scikit-learn,icdishb/scikit-learn,fbagirov/scikit-learn,ilyes14/scikit-learn,cwu2011/scikit-learn,pnedunuri/scikit-learn,betatim/scikit-learn,vibhorag/scikit-learn,trungnt13/scikit-learn,xiaoxiamii/scikit-learn,glouppe/scikit-learn,ilo10/scikit-learn,krez13/scikit-learn,vermouthmjl/scikit-learn,alexeyum/scikit-learn,macks22/scikit-learn,RPGOne/scikit-learn,mjgrav2001/scikit-learn,yunfeilu/scikit-learn,spallavolu/scikit-learn,Adai0808/scikit-learn,pythonvietnam/scikit-learn,Aasmi/scikit-learn,ky822/scikit-learn,giorgiop/scikit-learn,frank-tancf/scikit-learn,arjoly/scikit-learn,iismd17/scikit-learn,Nyker510/scikit-learn,arahuja/scikit-learn,vybstat/scikit-learn,joernhees/scikit-learn,hainm/scikit-learn,liberatorqjw/scikit-learn,dsquareindia/scikit-learn,3manuek/scikit-learn,manashmndl/scikit-learn,fabianp/scikit-learn,sanketloke/scikit-learn,sergeyf/scikit-learn,schets/scikit-learn,wanggang3333/scikit-learn,gotomypc/scikit-learn,larsmans/scikit-learn,olologin/scikit-learn,toastedcornflakes/scikit-learn,fengzhyuan/scikit-learn,ilyes14/scikit-learn,ningchi/scikit-learn,Akshay0724/scikit-learn,espg/scikit-learn,hrjn/scikit-learn,hsuantien/scikit-learn,jorge2703/scikit-learn,mrshu/scikit-learn,florian-f/sklearn,qifeigit/scikit-learn,jzt5132/scikit-learn,etkirsch/scikit-learn,MartinSavc/scikit-learn,JeanKossaifi/scikit-learn,rexshihaoren/scikit-learn,ashhher3/scikit-learn,ephes/scikit-learn,f3r/scikit-learn,shusenl/scikit-learn,ngoix/OCRF,pythonvietnam/scikit-learn,Djabbz/scikit-learn,ishanic/scikit-learn,marcocaccin/scikit-learn,Aasmi/scikit-learn,vybstat/scikit-learn,ndingwall/scikit-learn,lenovor/scikit-learn,zihua/scikit-learn,bnaul/scikit-learn,terkkila/scikit-learn,nelson-liu/scikit-learn,JsNoNo/scikit-learn,kashif/scikit-learn,kevin-intel/scikit-learn,Windy-Ground/scikit-learn,andaag/scikit-learn,mhue/scikit-learn,shyamalschandra/scikit-learn,ZENGXH/scikit-learn,adamgreenhall/scikit-learn,shangwuhencc/scikit-learn,ivannz/scikit-learn,manhhomienbienthuy/scikit-learn,hsuantien/scikit-learn,lazywei/scikit-learn,DonBeo/scikit-learn,rohanp/scikit-learn,jmetzen/scikit-learn,jaidevd/scikit-learn,466152112/scikit-learn,plissonf/scikit-learn,vinayak-mehta/scikit-learn,eg-zhang/scikit-learn,trankmichael/scikit-learn,hsuantien/scikit-learn,rvraghav93/scikit-learn,arjoly/scikit-learn,tawsifkhan/scikit-learn,xwolf12/scikit-learn,IndraVikas/scikit-learn,yonglehou/scikit-learn,dsullivan7/scikit-learn,alexsavio/scikit-learn,abhishekgahlot/scikit-learn,henrykironde/scikit-learn,kagayakidan/scikit-learn,siutanwong/scikit-learn,gclenaghan/scikit-learn,pv/scikit-learn,gotomypc/scikit-learn,IndraVikas/scikit-learn,larsmans/scikit-learn,IshankGulati/scikit-learn,shahankhatch/scikit-learn,luo66/scikit-learn,fengzhyuan/scikit-learn,liangz0707/scikit-learn,sanketloke/scikit-learn,xubenben/scikit-learn,etkirsch/scikit-learn,schets/scikit-learn,YinongLong/scikit-learn,mattilyra/scikit-learn,JeanKossaifi/scikit-learn,huzq/scikit-learn,PatrickChrist/scikit-learn,tosolveit/scikit-learn,tmhm/scikit-learn,f3r/scikit-learn,arjoly/scikit-learn,sergeyf/scikit-learn,Achuth17/scikit-learn,mhdella/scikit-learn,pv/scikit-learn,Adai0808/scikit-learn,anirudhjayaraman/scikit-learn,manhhomienbienthuy/scikit-learn,loli/semisupervisedforests,moutai/scikit-learn,anirudhjayaraman/scikit-learn,kevin-intel/scikit-learn,fredhusser/scikit-learn,imaculate/scikit-learn,glemaitre/scikit-learn,nelson-liu/scikit-learn,AlexanderFabisch/scikit-learn,meduz/scikit-learn,xuewei4d/scikit-learn,bthirion/scikit-learn,fredhusser/scikit-learn,joernhees/scikit-learn,jlegendary/scikit-learn,mjudsp/Tsallis,yonglehou/scikit-learn,bthirion/scikit-learn,ilyes14/scikit-learn,LiaoPan/scikit-learn,OshynSong/scikit-learn,ilo10/scikit-learn,PrashntS/scikit-learn,0x0all/scikit-learn,kjung/scikit-learn,hugobowne/scikit-learn,jmschrei/scikit-learn,Titan-C/scikit-learn,evgchz/scikit-learn,etkirsch/scikit-learn,cdegroc/scikit-learn,massmutual/scikit-learn,xuewei4d/scikit-learn,sonnyhu/scikit-learn,evgchz/scikit-learn,loli/sklearn-ensembletrees,arahuja/scikit-learn,IndraVikas/scikit-learn,q1ang/scikit-learn,ashhher3/scikit-learn,rohanp/scikit-learn,murali-munna/scikit-learn,NunoEdgarGub1/scikit-learn,nvoron23/scikit-learn,lesteve/scikit-learn,cdegroc/scikit-learn,ningchi/scikit-learn,ElDeveloper/scikit-learn,ElDeveloper/scikit-learn,schets/scikit-learn,huobaowangxi/scikit-learn,aetilley/scikit-learn,eg-zhang/scikit-learn,hsiaoyi0504/scikit-learn,hitszxp/scikit-learn,hlin117/scikit-learn,jpautom/scikit-learn,ycaihua/scikit-learn,luo66/scikit-learn,ahoyosid/scikit-learn,mrshu/scikit-learn,hsiaoyi0504/scikit-learn,massmutual/scikit-learn,kagayakidan/scikit-learn,JosmanPS/scikit-learn,carrillo/scikit-learn,JosmanPS/scikit-learn,nikitasingh981/scikit-learn,loli/sklearn-ensembletrees,manhhomienbienthuy/scikit-learn,nmayorov/scikit-learn,fyffyt/scikit-learn,lbishal/scikit-learn,jmschrei/scikit-learn,florian-f/sklearn,michigraber/scikit-learn,sarahgrogan/scikit-learn,andrewnc/scikit-learn,MatthieuBizien/scikit-learn,nhejazi/scikit-learn,xzh86/scikit-learn,mhue/scikit-learn,fengzhyuan/scikit-learn,shusenl/scikit-learn,arabenjamin/scikit-learn,Fireblend/scikit-learn,thilbern/scikit-learn,treycausey/scikit-learn,murali-munna/scikit-learn,krez13/scikit-learn,samuel1208/scikit-learn,rrohan/scikit-learn,bigdataelephants/scikit-learn,yunfeilu/scikit-learn,RachitKansal/scikit-learn,chrisburr/scikit-learn,ltiao/scikit-learn,xyguo/scikit-learn,kmike/scikit-learn,khkaminska/scikit-learn,IshankGulati/scikit-learn,rahul-c1/scikit-learn,wanggang3333/scikit-learn,belltailjp/scikit-learn,pratapvardhan/scikit-learn,wlamond/scikit-learn,RayMick/scikit-learn,vigilv/scikit-learn,ilo10/scikit-learn,jm-begon/scikit-learn,jereze/scikit-learn,Clyde-fare/scikit-learn,MechCoder/scikit-learn,Srisai85/scikit-learn,YinongLong/scikit-learn,pythonvietnam/scikit-learn,maheshakya/scikit-learn,theoryno3/scikit-learn,fyffyt/scikit-learn,yask123/scikit-learn,q1ang/scikit-learn,glennq/scikit-learn,justincassidy/scikit-learn,andrewnc/scikit-learn,yanlend/scikit-learn,akionakamura/scikit-learn,deepesch/scikit-learn,maheshakya/scikit-learn,pnedunuri/scikit-learn,lucidfrontier45/scikit-learn,mehdidc/scikit-learn,stylianos-kampakis/scikit-learn,yask123/scikit-learn,devanshdalal/scikit-learn,Clyde-fare/scikit-learn,HolgerPeters/scikit-learn,mjudsp/Tsallis,ephes/scikit-learn,vermouthmjl/scikit-learn,tomlof/scikit-learn,HolgerPeters/scikit-learn,jkarnows/scikit-learn,joernhees/scikit-learn,clemkoa/scikit-learn,rexshihaoren/scikit-learn,B3AU/waveTree,aflaxman/scikit-learn,kaichogami/scikit-learn,lesteve/scikit-learn,appapantula/scikit-learn,Srisai85/scikit-learn,sinhrks/scikit-learn,0asa/scikit-learn,lenovor/scikit-learn,jjx02230808/project0223,dhruv13J/scikit-learn,Srisai85/scikit-learn,yunfeilu/scikit-learn,hdmetor/scikit-learn,abhishekgahlot/scikit-learn,RPGOne/scikit-learn,dingocuster/scikit-learn,yanlend/scikit-learn,spallavolu/scikit-learn,xavierwu/scikit-learn,heli522/scikit-learn,ankurankan/scikit-learn,nomadcube/scikit-learn,treycausey/scikit-learn,roxyboy/scikit-learn,shyamalschandra/scikit-learn,loli/semisupervisedforests,depet/scikit-learn,mjudsp/Tsallis,scikit-learn/scikit-learn,fredhusser/scikit-learn,rrohan/scikit-learn,voxlol/scikit-learn,cauchycui/scikit-learn,cybernet14/scikit-learn,h2educ/scikit-learn,carrillo/scikit-learn,dhruv13J/scikit-learn,pkruskal/scikit-learn,cdegroc/scikit-learn,lin-credible/scikit-learn,macks22/scikit-learn,beepee14/scikit-learn,roxyboy/scikit-learn,evgchz/scikit-learn,btabibian/scikit-learn,3manuek/scikit-learn,zaxtax/scikit-learn,phdowling/scikit-learn,Lawrence-Liu/scikit-learn,ngoix/OCRF,aetilley/scikit-learn,costypetrisor/scikit-learn,scikit-learn/scikit-learn,ky822/scikit-learn,sinhrks/scikit-learn,treycausey/scikit-learn,OshynSong/scikit-learn,nikitasingh981/scikit-learn,aabadie/scikit-learn,dsquareindia/scikit-learn,equialgo/scikit-learn,sgenoud/scikit-learn,ky822/scikit-learn,pompiduskus/scikit-learn,moutai/scikit-learn,mfjb/scikit-learn,jlegendary/scikit-learn,olologin/scikit-learn,tawsifkhan/scikit-learn,aminert/scikit-learn,cainiaocome/scikit-learn,ningchi/scikit-learn,amueller/scikit-learn,anntzer/scikit-learn,jmschrei/scikit-learn,themrmax/scikit-learn,PatrickChrist/scikit-learn,massmutual/scikit-learn,hlin117/scikit-learn,mwv/scikit-learn,nomadcube/scikit-learn,Windy-Ground/scikit-learn,billy-inn/scikit-learn,zorojean/scikit-learn,TomDLT/scikit-learn,ilyes14/scikit-learn,jjx02230808/project0223,siutanwong/scikit-learn,0x0all/scikit-learn,icdishb/scikit-learn,cwu2011/scikit-learn,ishanic/scikit-learn,tawsifkhan/scikit-learn,equialgo/scikit-learn,glouppe/scikit-learn,0x0all/scikit-learn,shangwuhencc/scikit-learn,sarahgrogan/scikit-learn,AIML/scikit-learn,kaichogami/scikit-learn,wzbozon/scikit-learn,ycaihua/scikit-learn,beepee14/scikit-learn,BiaDarkia/scikit-learn,ycaihua/scikit-learn,nrhine1/scikit-learn,Obus/scikit-learn,abhishekkrthakur/scikit-learn,ishanic/scikit-learn,liberatorqjw/scikit-learn,jereze/scikit-learn,mehdidc/scikit-learn,sonnyhu/scikit-learn,michigraber/scikit-learn,giorgiop/scikit-learn,cainiaocome/scikit-learn,jorik041/scikit-learn,djgagne/scikit-learn,manashmndl/scikit-learn,dsullivan7/scikit-learn,mjgrav2001/scikit-learn,pypot/scikit-learn,altairpearl/scikit-learn,rajat1994/scikit-learn,rexshihaoren/scikit-learn,trankmichael/scikit-learn,siutanwong/scikit-learn,DSLituiev/scikit-learn,IssamLaradji/scikit-learn,RomainBrault/scikit-learn,ZENGXH/scikit-learn,sgenoud/scikit-learn,BiaDarkia/scikit-learn,LiaoPan/scikit-learn,terkkila/scikit-learn,treycausey/scikit-learn,kylerbrown/scikit-learn,Lawrence-Liu/scikit-learn,nvoron23/scikit-learn,sanketloke/scikit-learn,cauchycui/scikit-learn,bigdataelephants/scikit-learn,robbymeals/scikit-learn,wzbozon/scikit-learn,ChanderG/scikit-learn,thientu/scikit-learn,shikhardb/scikit-learn,mxjl620/scikit-learn | sklearn/covariance/tests/test_graph_lasso.py | sklearn/covariance/tests/test_graph_lasso.py | """ Test the graph_lasso module.
"""
import sys
from StringIO import StringIO
import numpy as np
from scipy import linalg
from sklearn.covariance import graph_lasso, GraphLasso, GraphLassoCV, \
empirical_covariance
from sklearn.datasets.samples_generator import make_sparse_spd_matrix
from sklearn.utils import check_random_state
def test_graph_lasso(random_state=0):
# Sample data from a sparse multivariate normal
dim = 20
n_samples = 100
random_state = check_random_state(random_state)
prec = make_sparse_spd_matrix(dim, alpha=.95,
random_state=random_state)
cov = linalg.inv(prec)
X = random_state.multivariate_normal(np.zeros(dim), cov, size=n_samples)
emp_cov = empirical_covariance(X)
for alpha in (.1, .01):
covs = dict()
for method in ('cd', 'lars'):
cov_, _, costs = graph_lasso(emp_cov, alpha=.1, return_costs=True)
covs[method] = cov_
costs, dual_gap = np.array(costs).T
# Check that the costs always decrease
np.testing.assert_array_less(np.diff(costs), 0)
# Check that the 2 approaches give similar results
np.testing.assert_allclose(covs['cd'], covs['lars'])
# Smoke test the estimator
model = GraphLasso(alpha=.1).fit(X)
np.testing.assert_allclose(model.covariance_, covs['cd'])
def test_graph_lasso_cv(random_state=1):
# Sample data from a sparse multivariate normal
dim = 5
n_samples = 6
random_state = check_random_state(random_state)
prec = make_sparse_spd_matrix(dim, alpha=.96,
random_state=random_state)
cov = linalg.inv(prec)
X = random_state.multivariate_normal(np.zeros(dim), cov, size=n_samples)
# Capture stdout, to smoke test the verbose mode
orig_stdout = sys.stdout
try:
sys.stdout = StringIO()
GraphLassoCV(verbose=10, alphas=3).fit(X)
finally:
sys.stdout = orig_stdout
| """ Test the graph_lasso module.
"""
import sys
from StringIO import StringIO
import numpy as np
from scipy import linalg
from sklearn.covariance import graph_lasso, GraphLasso, GraphLassoCV
from sklearn.datasets.samples_generator import make_sparse_spd_matrix
from sklearn.utils import check_random_state
def test_graph_lasso(random_state=0):
# Sample data from a sparse multivariate normal
dim = 20
n_samples = 100
random_state = check_random_state(random_state)
prec = make_sparse_spd_matrix(dim, alpha=.95,
random_state=random_state)
cov = linalg.inv(prec)
X = random_state.multivariate_normal(np.zeros(dim), cov, size=n_samples)
for alpha in (.1, .01):
covs = dict()
for method in ('cd', 'lars'):
cov_, _, costs = graph_lasso(X, alpha=.1, return_costs=True)
covs[method] = cov_
costs, dual_gap = np.array(costs).T
# Check that the costs always decrease
np.testing.assert_array_less(np.diff(costs), 0)
# Check that the 2 approaches give similar results
np.testing.assert_allclose(covs['cd'], covs['lars'])
# Smoke test the estimator
model = GraphLasso(alpha=.1).fit(X)
np.testing.assert_allclose(model.covariance_, covs['cd'])
def test_graph_lasso_cv(random_state=1):
# Sample data from a sparse multivariate normal
dim = 5
n_samples = 6
random_state = check_random_state(random_state)
prec = make_sparse_spd_matrix(dim, alpha=.96,
random_state=random_state)
cov = linalg.inv(prec)
X = random_state.multivariate_normal(np.zeros(dim), cov, size=n_samples)
# Capture stdout, to smoke test the verbose mode
orig_stdout = sys.stdout
try:
sys.stdout = StringIO()
GraphLassoCV(verbose=10, alphas=3).fit(X)
finally:
sys.stdout = orig_stdout
| bsd-3-clause | Python |
dd9893eec00c16f55b77944509bafe4864319b72 | create main function | plinecom/JobManager | JobManager.py | JobManager.py |
import filelib.parser.ma
import filelib.parser.mb
import os.path
import sys
if __name__ == "__main__":
addFilePath = "/root/test_maya_2015.mb"
if(len(sys.argv) > 1):
addFilePath = sys.argv[1]
(dir,jobExt) = os.path.splitext(addFilePath)
jobExt = jobExt.lower()
if jobExt == ".ma":
fileParser = filelib.parser.ma.FileParserMayaMA(addFilePath, SudioPlugin())
elif jobExt == ".mb":
fileParser = filelib.parser.mb.FileParserMayaMB(addFilePath)
fileParser.parse()
print fileParser.getparam()
# job2 = fileParser.getJob()
#jobfactory = JobFactory();
#job2 = jobfactory.getJob(fileParser.getparam(), SudioPlugin())
| mit | Python |
|
c65731de77f88380f2c816fa9667d153140bfbe1 | Add LDA script | rnowling/pop-gen-models | lda/lda_analysis.py | lda/lda_analysis.py | import sys
from sklearn.lda import LDA
import matplotlib.pyplot as plt
import numpy as np
def read_variants(flname):
fl = open(flname)
markers = []
individuals = []
population_ids = []
population = -1
for ln in fl:
if "Marker" in ln:
if len(individuals) == 0:
continue
marker = dict()
marker["individuals"] = np.array(individuals)
marker["population_labels"] = np.array(population_ids)
markers.append(marker)
population = -1
population_ids = []
individuals = []
elif "Population" in ln:
population += 1
else:
individual = map(float, ln.strip().split())
individuals.append(individual)
population_ids.append(population)
if len(individuals) != 0:
marker = dict()
marker["individuals"] = np.array(individuals)
marker["population_labels"] = np.array(population_ids)
markers.append(marker)
fl.close()
return markers
def plot_scores(markers, flname):
plt.clf()
scores = []
for i, marker in enumerate(markers):
try:
lda = LDA()
lda.fit(marker["individuals"], marker["population_labels"])
scores.append(lda.score(marker["individuals"], marker["population_labels"]))
except:
scores.append(0.0)
plt.hist(scores, bins=np.arange(0.0, 1.0, 0.01))
plt.xlabel("Score", fontsize=18)
plt.ylabel("Occurrences", fontsize=18)
plt.savefig(flname, DPI=200)
def plot_lda_projection(marker, flname):
lda = LDA()
lda.fit(marker["individuals"], marker["population_labels"])
print lda.score(marker["individuals"], marker["population_labels"])
proj = lda.transform(marker["individuals"])
n_samples, n_components = proj.shape
plt.scatter(proj, marker["population_labels"])
plt.xlabel("Component 0", fontsize=18)
plt.ylabel("Population Labels", fontsize=18)
plt.savefig(flname, DPI=200)
if __name__ == "__main__":
variants_fl = sys.argv[1]
#variant_id = int(sys.argv[2])
plot_flname = sys.argv[2]
variants = read_variants(variants_fl)
print len(variants)
#plot_lda_projection(variants[variant_id], plot_flname)
plot_scores(variants, plot_flname)
| apache-2.0 | Python |
|
cf97c95ab9dcb3b1dba6608639471375a1cbef42 | Create afUdimLayout.py | aaronfang/personal_scripts | scripts/afUdimLayout.py | scripts/afUdimLayout.py | import pymel.core as pm
import maya.mel as mel
allSets = pm.ls(sl=1,type="objectSet")
for i in range(0,len(allSets)):
if i<10:
pm.select(allSets[i],r=1,ne=1)
pm.select(hierarchy=1)
mel.eval("ConvertSelectionToUVs;")
pm.polyEditUV(u=i,v=0)
elif i>=10<20:
pm.select(allSets[i],r=1,ne=1)
pm.select(hierarchy=1)
mel.eval("ConvertSelectionToUVs;")
pm.polyEditUV(u=i-10,v=1)
elif i>=20<30:
pm.select(allSets[i],r=1,ne=1)
pm.select(hierarchy=1)
mel.eval("ConvertSelectionToUVs;")
pm.polyEditUV(u=i-20,v=2)
elif i>=30<40:
pm.select(allSets[i],r=1,ne=1)
pm.select(hierarchy=1)
mel.eval("ConvertSelectionToUVs;")
pm.polyEditUV(u=i-30,v=3)
| mit | Python |
|
49f557228a6c826598c48a08f6a0de4ee176d888 | add python script to send ogg audio stream over LCM messages | openhumanoids/oh-distro,openhumanoids/oh-distro,openhumanoids/oh-distro,openhumanoids/oh-distro,openhumanoids/oh-distro,openhumanoids/oh-distro,openhumanoids/oh-distro,openhumanoids/oh-distro | software/tools/tools/scripts/oggStreamLCM.py | software/tools/tools/scripts/oggStreamLCM.py | import bot_core
import lcm
import urllib2
import time
import sys
import os
import select
import subprocess
import threading
# VLC command:
# cvlc <input> --sout '#transcode{acodec=vorb,ab=10,channels=1,samplerate=8000}:std{access=http,mux=ogg,url=localhost:8080}'
# where <input> is a file or a url
serverChannel = 'OGG_SERVER'
clientChannel = 'OGG_CLIENT'
oggUrl = 'http://localhost:8080'
messageSize = 4096
serverThreadRunning = False
serverThread = None
def serverStreamLoop():
stream = urllib2.urlopen(oggUrl)
lcmHandle = lcm.LCM()
m = bot_core.raw_t()
m.utime = 0
totalBytes = 0
global serverThreadRunning
while serverThreadRunning:
m.data = stream.read(messageSize)
if not m.data:
break
m.utime = m.utime + 1
m.length = len(m.data)
totalBytes += m.length
#print 'publishing message %d. %d bytes. total so far: %f kB' % (m.utime, m.length, totalBytes/1024.0)
lcmHandle.publish(serverChannel, m.encode())
print 'stream publisher loop returning'
def handleMessageFromClient(channel, data):
m = bot_core.raw_t.decode(data)
print 'message from client:', m.data
global serverThread, serverThreadRunning
if serverThread:
serverThreadRunning = False
serverThread.join()
serverThread = None
serverThreadRunning = True
serverThread = threading.Thread(target=serverStreamLoop)
serverThread.daemon = True
serverThread.start()
def server():
lcmHandle = lcm.LCM()
subscription = lcmHandle.subscribe(clientChannel, handleMessageFromClient)
while True:
lcmHandle.handle()
oggProc = None
def handleMessageFromServer(channel, data):
m = bot_core.raw_t.decode(data)
oggProc.stdin.write(m.data)
def client():
global oggProc
oggProc = subprocess.Popen(['ogg123', '-'], stdin=subprocess.PIPE, stderr=subprocess.STDOUT)
lcmHandle = lcm.LCM()
m = bot_core.raw_t()
m.utime = 0
m.data = 'restart_stream'
m.length = len(m.data)
lcmHandle.publish(clientChannel, m.encode())
subscription = lcmHandle.subscribe(serverChannel, handleMessageFromServer)
while True:
lcmHandle.handle()
def main():
mode = sys.argv[1]
assert mode in ('--client', '--server')
if mode == '--server':
server()
else:
client()
if __name__ == '__main__':
main()
| bsd-3-clause | Python |
|
76be22f3d1aa86616ecd06a326344f24ff03adbe | Add function to generate uniform addresses | opencleveland/RTAHeatMap,skorasaurus/RTAHeatMap | DataGeneration/GenerateUniformAddresses.py | DataGeneration/GenerateUniformAddresses.py | # The purpose of this script is to generate a uniformly distributed series of
# lat/long coordinates given max/min latitude, max/min longitude, latitude
# resolution, and longitude resolution, where resolution is the desired number
# of degrees between output coordinates
# Outputs a pandas dataframe of lat/long coordinate pairs
import pandas as pd # For the dataframe
import numpy as np # To calculate ranges with float step-values
import math # For math
def GenerateUniformCoordinates(lat_min, lat_max,
lng_min, lng_max,
lat_res, lng_res):
# Calculate the number of rows our output DataFrame will contain so that we
# can pre-allocate the memory for the dataframe using the index property.
nrows_lat = math.ceil((lat_max - lat_min) / lat_res + 1)
nrows_lng = math.ceil((lng_max - lng_min) / lng_res + 1)
nrows = nrows_lat * nrows_lng
# Output some data for debugging
print('Latitude Quantity: ' + str(nrows_lat))
print('Longitude Quantity: ' + str(nrows_lng))
print('Total Number of Rows to Output: ' + str(nrows))
# Instantiate or DataFrame
df = pd.DataFrame(columns = ['lat','lng'], index=np.arange(0, nrows))
# Iterate through each latitude and each longitude calculated with the
# np.arange function, adding lat_res to the max value to ensure that we
# include the max value in the range that we iterate through
row_num = 0
for lat in np.arange(lat_min, lat_max + lat_res, lat_res):
for lng in np.arange(lng_min, lng_max + lng_res, lng_res):
df.loc[row_num] = [lat, lng] #Add the lat/lng pair to the dataframe
row_num += 1 #increment our row number
return df
# These values are the degrees walked per minute at a speed of 3.1 miles per
# hour at 41.4822 deg N and 81.6697 deg W, which is the center of Cleveland
lat_res = 0.000724516
lng_res = 0.000963461
lat_min = 41.227883
lat_max = 41.637051
lng_min = -81.96753
lng_max = -81.438542
output_df = GenerateUniformCoordinates(lat_min, lat_max,
lng_min, lng_max,
lat_res, lng_res)
output_df.to_csv('uniform_addresses.csv') | mit | Python |
|
05f87be4c85036c69abc9404acb824c58d71f101 | Add border operation... Damn that was easy | meshulam/sly | slice_ops.py | slice_ops.py | import slicer
import shapely.ops
import shapely.geometry
def border(sli, amount):
cuts = [cut.polygon(True) for cut in sli.cuts]
cut_outline = shapely.ops.cascaded_union(cuts) \
.buffer(amount / 2)
shape_outline = sli.poly.boundary.buffer(amount)
outlines = cut_outline.union(shape_outline)
newpoly = outlines.intersection(sli.poly)
sli.poly = newpoly
| mit | Python |
|
a3089dd3d9c31d0d705fe54858fdc0ebee76f488 | write a Python client for Sift Science's REST API | MichalKononenko/rmc,shakilkanji/rmc,duaayousif/rmc,sachdevs/rmc,ccqi/rmc,shakilkanji/rmc,rageandqq/rmc,UWFlow/rmc,MichalKononenko/rmc,UWFlow/rmc,shakilkanji/rmc,JGulbronson/rmc,rageandqq/rmc,duaayousif/rmc,rageandqq/rmc,MichalKononenko/rmc,rageandqq/rmc,JGulbronson/rmc,shakilkanji/rmc,JGulbronson/rmc,duaayousif/rmc,rageandqq/rmc,sachdevs/rmc,UWFlow/rmc,UWFlow/rmc,ccqi/rmc,sachdevs/rmc,MichalKononenko/rmc,sachdevs/rmc,UWFlow/rmc,duaayousif/rmc,shakilkanji/rmc,ccqi/rmc,JGulbronson/rmc,ccqi/rmc,duaayousif/rmc,JGulbronson/rmc,MichalKononenko/rmc,ccqi/rmc,sachdevs/rmc | server/sift_client.py | server/sift_client.py | """Python client for Sift Science's REST API
(https://siftscience.com/docs/rest-api).
"""
import json
import logging
import traceback
import requests
API_URL = 'https://api.siftscience.com/v202/events'
sift_logger = logging.getLogger('sift_client')
class Client(object):
def __init__(self, api_key, api_url=API_URL, timeout=2.0):
"""Initialize the client.
Args:
api_key: Your Sift Science API key associated with your customer
account. You can obtain this from
https://siftscience.com/quickstart
api_url: The URL to send events to.
timeout: Number of seconds to wait before failing request. Defaults
to 2 seconds.
"""
self.api_key = api_key
self.url = api_url
self.timeout = timeout
def track(self, event, properties):
"""Track an event and associated properties to the Sift Science client.
This call is blocking.
Args:
event: The name of the event to send. This can either be a reserved
event name such as "$transaction" or "$label" or a custom event
name (that does not start with a $).
properties: A dict of additional event-specific attributes to track
Returns:
A requests.Response object if the track call succeeded, otherwise
a subclass of requests.exceptions.RequestException indicating the
exception that occurred.
"""
headers = { 'Content-type' : 'application/json', 'Accept' : '*/*' }
properties.update({ '$api_key': self.api_key, '$type': event })
try:
response = requests.post(self.url, data=json.dumps(properties),
headers=headers, timeout=self.timeout)
# TODO(david): Wrap the response object in a class
return response
except requests.exceptions.RequestException as e:
sift_logger.warn('Failed to track event: %s' % properties)
sift_logger.warn(traceback.format_exception_only(type(e), e))
return e
| mit | Python |
|
f3f5249c0ac7d41ebf2115fb0b5c7576012bcb38 | Add production settings | ccwang002/biocloud-server-kai,ccwang002/biocloud-server-kai,ccwang002/biocloud-server-kai | src/biocloud/settings/production.py | src/biocloud/settings/production.py | # In production set the environment variable like this:
# DJANGO_SETTINGS_MODULE=my_proj.settings.production
from .base import * # NOQA
import logging.config
# For security and performance reasons, DEBUG is turned off
DEBUG = False
# Must mention ALLOWED_HOSTS in production!
# ALLOWED_HOSTS = []
# Cache the templates in memory for speed-up
loaders = [
(
'django.template.loaders.cached.Loader',
[
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
]
),
]
TEMPLATES[0]['OPTIONS'].update({"loaders": loaders})
TEMPLATES[0]['OPTIONS'].update({"debug": False})
del TEMPLATES[0]['APP_DIRS']
# Email settings
EMAIL_BACKEND = env.email_url()['EMAIL_BACKEND']
EMAIL_HOST = env.email_url()['EMAIL_HOST']
EMAIL_HOST_PASSWORD = env.email_url()['EMAIL_HOST_PASSWORD']
EMAIL_HOST_USER = env.email_url()['EMAIL_HOST_USER']
EMAIL_PORT = env.email_url()['EMAIL_PORT']
EMAIL_USE_TLS = env.email_url()['EMAIL_USE_TLS']
DEFAULT_FROM_EMAIL = SERVER_EMAIL = '{name} <{addr}>'.format(
name='BioCloud Dev',
addr='biocloud@liang2.io',
)
# Securiy related settings
# SECURE_HSTS_SECONDS = 2592000
# SECURE_BROWSER_XSS_FILTER = True
# SECURE_CONTENT_TYPE_NOSNIFF=True
# SESSION_COOKIE_SECURE = True
# CSRF_COOKIE_SECURE = True
# CSRF_COOKIE_HTTPONLY = True
# SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
# X_FRAME_OPTIONS = 'DENY'
# Log everything to the logs directory at the top
LOGFILE_ROOT = join(BASE_DIR, 'logs')
# Reset logging
LOGGING_CONFIG = None
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'verbose': {
'format': (
'[%(asctime)s] %(levelname)s '
'[%(pathname)s:%(lineno)s] %(message)s'
),
'datefmt': "%d/%b/%Y %H:%M:%S"
},
'simple': {
'format': '%(levelname)s %(message)s'
},
},
'handlers': {
'django_log_file': {
'level': 'DEBUG',
'class': 'logging.FileHandler',
'filename': join(LOGFILE_ROOT, 'django.log'),
'formatter': 'verbose'
},
'console': {
'level': 'DEBUG',
'class': 'logging.StreamHandler',
'formatter': 'simple'
},
},
'loggers': {
'django': {
'handlers': ['django_log_file', ],
'propagate': True,
'level': 'DEBUG',
},
}
}
for app in LOCAL_APPS:
app_handler = '%s_log_file' % app
app_log_filepath = '%s.log' % app
LOGGING['loggers'][app] = {
'handlers': [app_handler, 'console', ],
'level': 'DEBUG',
}
LOGGING['handlers'][app_handler] = {
'level': 'DEBUG',
'class': 'logging.FileHandler',
'filename': join(LOGFILE_ROOT, app_log_filepath),
'formatter': 'verbose',
}
logging.config.dictConfig(LOGGING)
| mit | Python |
|
cda1efa55242641accf78162493c3ebb3582399e | Create AM_example.py | Souloist/Audio-Effects | Effects/Amplitude_Modulation/AM_example.py | Effects/Amplitude_Modulation/AM_example.py | # Play a wave file with amplitude modulation.
# Assumes wave file is mono.
# This implementation reads and plays a one frame (sample) at a time (no blocking)
"""
Read a signal from a wave file, do amplitude modulation, play to output
Original: pyrecplay_modulation.py by Gerald Schuller, Octtober 2013
Modified to read a wave file - Ivan Selesnick, September 2015
"""
# f0 = 0 # Normal audio
f0 = 400 # 'Duck' audio
import pyaudio
import struct
import wave
import math
# Open wave file (mono)
input_wavefile = 'author.wav'
# input_wavefile = 'sin01_mono.wav'
# input_wavefile = 'sin01_stereo.wav'
wf = wave.open( input_wavefile, 'rb')
RATE = wf.getframerate()
WIDTH = wf.getsampwidth()
LEN = wf.getnframes()
CHANNELS = wf.getnchannels()
print 'The sampling rate is {0:d} samples per second'.format(RATE)
print 'Each sample is {0:d} bytes'.format(WIDTH)
print 'The signal is {0:d} samples long'.format(LEN)
print 'The signal has {0:d} channel(s)'.format(CHANNELS)
# Open audio stream
p = pyaudio.PyAudio()
stream = p.open(format = p.get_format_from_width(WIDTH),
channels = 1,
rate = RATE,
input = False,
output = True)
print('* Playing...')
# Loop through wave file
for n in range(0, LEN):
# Get sample from wave file
input_string = wf.readframes(1)
# Convert binary string to tuple of numbers
input_tuple = struct.unpack('h', input_string)
# (h: two bytes per sample (WIDTH = 2))
# Use first value (of two if stereo)
input_value = input_tuple[0]
# Amplitude modulation (f0 Hz cosine)
output_value = input_value * math.cos(2*math.pi*f0*n/RATE)
# Convert value to binary string
output_string = struct.pack('h', output_value)
# Write binary string to audio output stream
stream.write(output_string)
print('* Done')
stream.stop_stream()
stream.close()
p.terminate()
| mit | Python |
|
2387d8f269cbe1943db1b1e6304603ccb6901e43 | Add flashcards for powers of two estimation | oldhill/halloween,oldhill/halloween,oldhill/halloween,oldhill/halloween | flashcards.py | flashcards.py | import random
import time
DELAY = 10
while 1:
time.sleep(DELAY)
useful_powers_of_2 = {7, 8, 10, 16, 20, 30, 32, 40}
random_power_of_2 = random.sample(useful_powers_of_2, 1)[0]
print '\nWhat\'s the largest %s bit integer?' % random_power_of_2
time.sleep(DELAY)
print 'Answer: %s' % '{:,}'.format(2 ** random_power_of_2) | mit | Python |
|
7a79c163144b242be57ed8cf45ae4fb5097f11fa | Create defaultlog.py | rtogo/commons | defaultlog.py | defaultlog.py | # -*- coding: utf-8 -*-
"""Console and file logging configuration.
This module automatically configures the logging to use a colored console
format, and a timed rotating log file that rolls over at midnight.
The log formats results in the following outputs:
Console:
[INFO ] This is some info (root)
[DEBUG ] Now this is some debug (parser.ekpo)
File:
[2015-12-29T16:16:55]13748 root INFO This is some info
[2015-12-29T16:16:55]13748 parser.ekpo DEBUG This is some module debug
[2015-12-29T16:16:55]13748 root INFO Some more info
Just put this file into your project structure to use it.
Usage:
from defaultlog import logging
Examples:
Package-level using the root logger
-----------------------------------
# Import the logging module through this customized module
from defaultlog import logging
def main():
# Log using the root logger
logging.info('Program started')
if __name__ == '__main__':
main()
Library code that log to a private logger
-----------------------------------------
# Imports the bult-in logging package
import logging
# Creates a private logger instance
logger = logging.getLogger(__name__)
def do_it():
# Log using the private logger
# It keeps the configuration done in the root logger
logger.info('Doing it')
Dependencies:
coloredlogs
colorama
"""
import logging
import logging.config
import yaml
default_config = \
"""
version: 1
formatters:
console:
format : "[%(levelname)-7s] %(message)s"
datefmt: "%H:%M:%S"
file:
format : "[%(asctime)s]%(thread)-5d %(name)-40s %(levelname)-8s %(message)s"
datefmt: "%Y-%m-%dT%H:%M:%S"
colored:
format : "[%(log_color)s%(levelname)-8s%(reset)s] %(message_log_color)s%(message)s%(reset)s %(name_log_color)s(%(name)s)"
datefmt: "%H:%M:%S"
() : colorlog.ColoredFormatter
log_colors:
DEBUG : white
INFO : bold_green
WARNING : bold_yellow
ERROR : bold_red
CRITICAL: bold_white,bg_red
secondary_log_colors:
message:
INFO : bold_white
WARNING : bold_yellow
ERROR : bold_red
CRITICAL: bold_red
name:
DEBUG : purple
INFO : purple
WARNING : purple
ERROR : purple
CRITICAL: purple
handlers:
console:
level : DEBUG
class : logging.StreamHandler
formatter: colored
stream : ext://sys.stdout
file:
level : DEBUG
class : logging.handlers.TimedRotatingFileHandler
formatter: file
when : midnight
filename : logs/log.log
encoding : utf8
loggers:
custom_module:
handlers: [file]
level: WARNING
root:
handlers: [console, file]
level: DEBUG
disable_existing_loggers: False
"""
try:
config = yaml.load(default_config)
logging.config.dictConfig(config)
except Exception:
logging.exception("Couldn't import logging settings from yaml")
| mit | Python |
|
2acf089d00426d8b61317c6d031aee7696d42b03 | Create script to import Wicklow data | schmave/demschooltools,schmave/demschooltools,schmave/demschooltools,schmave/demschooltools,schmave/demschooltools | import_wicklow.py | import_wicklow.py | import psycopg2
import re
import sys
ORG_ID = 10
conn = psycopg2.connect("dbname=school_crm user=postgres host=localhost port=5432")
cur = conn.cursor()
# cur.execute("set client_encoding to 'latin1'")
def import_names():
cur.execute("DELETE FROM person_tag WHERE person_id in (SELECT person_id from person where organization_id=%d)" % ORG_ID)
cur.execute("DELETE FROM person_tag_change WHERE person_id in (SELECT person_id from person where organization_id=%d)" % ORG_ID)
cur.execute("DELETE FROM person WHERE organization_id=%d" % ORG_ID)
cur.execute("SELECT id from tag where title='Current Student' and organization_id=%d" % ORG_ID)
student_tag_id = int(cur.fetchone()[0])
cur.execute("SELECT id from tag where title='Staff' and organization_id=%d" % ORG_ID)
staff_tag_id = int(cur.fetchone()[0])
is_student = False
for name in open('names.txt'):
if not name.strip():
is_student = True
continue
splits = name.split(' ')
first_name = splits[0].title()
last_name = splits[1].title()
cur.execute("""INSERT into person(
first_name, last_name, organization_id) VALUES
(%s, %s, %s) returning person_id""", (
first_name, last_name, ORG_ID))
person_id = int(cur.fetchone()[0])
cur.execute("INSERT into person_tag (tag_id, person_id) VALUES (%s, %s)",
(student_tag_id if is_student else staff_tag_id, person_id))
cur.execute("INSERT into person_tag_change (tag_id, person_id, creator_id, was_add) VALUES (%s, %s, 1, true)",
(student_tag_id if is_student else staff_tag_id, person_id))
def import_lawbook():
cur.execute("DELETE from entry WHERE section_id in "
"(SELECT s.id from section s join chapter c on s.chapter_id=c.id where organization_id=%d)" % ORG_ID)
cur.execute("DELETE from section WHERE chapter_id in "
"(SELECT id from chapter where organization_id=%d)" % ORG_ID)
cur.execute("DELETE from chapter WHERE organization_id=%d" % ORG_ID)
chapter_id = None
section_id = None
rule_content = ''
rule_num = ''
rule_title = ''
for line in open('lawbook.txt'):
chapter_match = re.match(r'Section (.*) - (.*)', line)
section_match = re.match(r'(\d+) *- *(.*)', line)
rule_match = re.match(r'(\d+\.\d+.*)\t(.*)', line)
if chapter_match or section_match or rule_match:
if rule_num and rule_title and rule_content:
cur.execute("""INSERT into entry(num, title, section_id, content)
VALUES (%s, %s, %s, %s)""", (
rule_num, rule_title, section_id, rule_content))
# print('RULE', rule_num, rule_title, rule_content)
rule_content = ''
if section_match:
cur.execute("""INSERT into section(num, title, chapter_id) VALUES
(%s, %s, %s) returning id""", (
section_match.group(1), section_match.group(2).strip(), chapter_id))
section_id = int(cur.fetchone()[0])
# print('SECTION', section_match.group(1), section_match.group(2))
rule_content = ''
elif rule_match:
rule_content = ''
splits = rule_match.group(1).split('.')
rule_num = splits[1].strip()
rule_title = rule_match.group(2).strip()
elif chapter_match:
cur.execute("""INSERT into chapter (num, title, organization_id)
VALUES (%s, %s, %s) returning id""", (
chapter_match.group(1).strip(), chapter_match.group(2).strip(), ORG_ID))
chapter_id = int(cur.fetchone()[0])
# print(chapter_match.group(1), chapter_match.group(2), chapter_id)
rule_content = ''
else:
rule_content += line
print('Now manually copy over the last chapter')
import_names()
import_lawbook()
conn.commit()
cur.close()
conn.close()
| mit | Python |
|
f8b9e697f4d49f35dda322817ac8ac63d96b6732 | Add failing wait tests | tpouyer/nova-lxd,tpouyer/nova-lxd,Saviq/nova-compute-lxd,Saviq/nova-compute-lxd | nclxd/tests/test_container_utils.py | nclxd/tests/test_container_utils.py | # Copyright 2015 Canonical Ltd
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import mock
from nova import exception
from nova import test
from nclxd.nova.virt.lxd import container_utils
from nclxd import tests
class LXDTestContainerUtils(test.NoDBTestCase):
def setUp(self):
super(LXDTestContainerUtils, self).setUp()
self.ml = tests.lxd_mock()
lxd_patcher = mock.patch('pylxd.api.API',
mock.Mock(return_value=self.ml))
lxd_patcher.start()
self.addCleanup(lxd_patcher.stop)
self.container_utils = container_utils.LXDContainerUtils()
def test_wait_undefined(self):
self.assertRaises(exception.NovaException,
self.container_utils.wait_for_container,
None)
def test_wait_timedout(self):
self.ml.wait_container_operation.return_value = False
self.assertRaises(exception.NovaException,
self.container_utils.wait_for_container,
'fake')
| # Copyright 2015 Canonical Ltd
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
| apache-2.0 | Python |
51ee19f41e6fc48d4791bde97c5d28d55d76cdf4 | Add brute force inplementation | Cosiek/KombiVojager | solvers/BruteForce.py | solvers/BruteForce.py | #!/usr/bin/env python
# encoding: utf-8
from itertools import permutations
from base_solver import BaseSolver
class BruteForceSolver(BaseSolver):
def run_search(self):
# get list of mid nodes names
mid_nodes = []
for node in self.task.mid_nodes:
mid_nodes.append(node.name)
# iterate over permutations generator
best_distance = float('inf')
best_solution = None
cycles = 0
for permutation in permutations(mid_nodes):
# check permutation distance
path = [self.task.start.name, ]
path.extend(permutation)
path.append(self.task.finish.name)
distance = self.task.get_path_distance(path)
# check if this is the best solution so far
if distance < best_distance:
best_distance = distance
best_solution = path
cycles += 1
return best_solution, best_distance, cycles
| mit | Python |
|
46496d8761ae94a349ed3b592ec7ee7e0c7e1a15 | Remove unused import; add missing import | mer-tools/git-repo,testbetta/git-repo-pub,FuangCao/repo,qioixiy/git-repo,jingyu/git-repo,simbasailor/git-repo,testbetta/git-repo-pub,testbetta/repo-pub,TheQtCompany/git-repo,ediTLJ/git-repo,ronan22/repo,aosp-mirror/tools_repo,FlymeOS/repo,ronan22/repo,jingyu/git-repo,zemug/repo,couchbasedeps/git-repo,11NJ/git-repo,chzhong/git-repo,wavecomp/git-repo,CyanogenMod/tools_repo,GerritCodeReview/git-repo,FuangCao/repo,gbraad/git-repo,gabbayo/git-repo,FuangCao/git-repo,chenzilin/git-repo,aosp-mirror/tools_repo,slfyusufu/repo,gbraad/git-repo,slfyusufu/repo,testbetta/repo-pub,lipro-yocto/git-repo,mer-tools/git-repo,nuclearmistake/repo,11NJ/git-repo,kdavis-mozilla/repo-repo,CyanogenMod/tools_repo,wavecomp/git-repo,couchbasedeps/git-repo,dodocat/git-repo,GerritCodeReview/git-repo,frogbywyplay/git-repo,iAlios/git-repo,lipro-yocto/git-repo,simbasailor/git-repo,GatorQue/git-repo-flow,qioixiy/git-repo,kdavis-mozilla/repo-repo,codetutil/git-repo,codetutil/git-repo,lewixliu/git-repo,FlymeOS/repo,xyyangkun/git-repo,iAlios/git-repo,GatorQue/git-repo-flow,dodocat/git-repo,nuclearmistake/repo,gabbayo/git-repo,zemug/repo,chzhong/git-repo,chenzilin/git-repo,frogbywyplay/git-repo,TheQtCompany/git-repo,ediTLJ/git-repo,lewixliu/git-repo,xyyangkun/git-repo,FuangCao/git-repo | gitc_utils.py | gitc_utils.py | #
# Copyright (C) 2015 The Android Open Source Project
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import print_function
import os
import sys
import git_command
import git_config
# TODO (sbasi) - Remove this constant and fetch manifest dir from /gitc/.config
GITC_MANIFEST_DIR = '/usr/local/google/gitc/'
GITC_FS_ROOT_DIR = '/gitc/manifest-rw/'
NUM_BATCH_RETRIEVE_REVISIONID = 300
def _set_project_revisions(projects):
"""Sets the revisionExpr for a list of projects.
Because of the limit of open file descriptors allowed, length of projects
should not be overly large. Recommend calling this function multiple times
with each call not exceeding NUM_BATCH_RETRIEVE_REVISIONID projects.
@param projects: List of project objects to set the revionExpr for.
"""
# Retrieve the commit id for each project based off of it's current
# revisionExpr and it is not already a commit id.
project_gitcmds = [(
project, git_command.GitCommand(None,
['ls-remote',
project.remote.url,
project.revisionExpr],
capture_stdout=True, cwd='/tmp'))
for project in projects if not git_config.IsId(project.revisionExpr)]
for proj, gitcmd in project_gitcmds:
if gitcmd.Wait():
print('FATAL: Failed to retrieve revisionExpr for %s' % project)
sys.exit(1)
proj.revisionExpr = gitcmd.stdout.split('\t')[0]
def generate_gitc_manifest(client_dir, manifest):
"""Generate a manifest for shafsd to use for this GITC client.
@param client_dir: GITC client directory to install the .manifest file in.
@param manifest: XmlManifest object representing the repo manifest.
"""
print('Generating GITC Manifest by fetching revision SHAs for each '
'project.')
project_gitcmd_dict = {}
index = 0
while index < len(manifest.projects):
_set_project_revisions(
manifest.projects[index:(index+NUM_BATCH_RETRIEVE_REVISIONID)])
index += NUM_BATCH_RETRIEVE_REVISIONID
# Save the manifest.
with open(os.path.join(client_dir, '.manifest'), 'w') as f:
manifest.Save(f)
| #
# Copyright (C) 2015 The Android Open Source Project
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import print_function
import os
import shutil
import git_command
import git_config
# TODO (sbasi) - Remove this constant and fetch manifest dir from /gitc/.config
GITC_MANIFEST_DIR = '/usr/local/google/gitc/'
GITC_FS_ROOT_DIR = '/gitc/manifest-rw/'
NUM_BATCH_RETRIEVE_REVISIONID = 300
def _set_project_revisions(projects):
"""Sets the revisionExpr for a list of projects.
Because of the limit of open file descriptors allowed, length of projects
should not be overly large. Recommend calling this function multiple times
with each call not exceeding NUM_BATCH_RETRIEVE_REVISIONID projects.
@param projects: List of project objects to set the revionExpr for.
"""
# Retrieve the commit id for each project based off of it's current
# revisionExpr and it is not already a commit id.
project_gitcmds = [(
project, git_command.GitCommand(None,
['ls-remote',
project.remote.url,
project.revisionExpr],
capture_stdout=True, cwd='/tmp'))
for project in projects if not git_config.IsId(project.revisionExpr)]
for proj, gitcmd in project_gitcmds:
if gitcmd.Wait():
print('FATAL: Failed to retrieve revisionExpr for %s' % project)
sys.exit(1)
proj.revisionExpr = gitcmd.stdout.split('\t')[0]
def generate_gitc_manifest(client_dir, manifest):
"""Generate a manifest for shafsd to use for this GITC client.
@param client_dir: GITC client directory to install the .manifest file in.
@param manifest: XmlManifest object representing the repo manifest.
"""
print('Generating GITC Manifest by fetching revision SHAs for each '
'project.')
project_gitcmd_dict = {}
index = 0
while index < len(manifest.projects):
_set_project_revisions(
manifest.projects[index:(index+NUM_BATCH_RETRIEVE_REVISIONID)])
index += NUM_BATCH_RETRIEVE_REVISIONID
# Save the manifest.
with open(os.path.join(client_dir, '.manifest'), 'w') as f:
manifest.Save(f)
| apache-2.0 | Python |
4dfc0c49cec86f3c03b90fa66e1fc9de2ac665e6 | Add migration file (fix fields) | gems-uff/labsys,gems-uff/labsys,gems-uff/labsys | samples/migrations/0012_auto_20170512_1138.py | samples/migrations/0012_auto_20170512_1138.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2017-05-12 14:38
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('samples', '0011_fluvaccine_date_applied'),
]
operations = [
migrations.AlterField(
model_name='collectedsample',
name='collection_date',
field=models.DateField(blank=True, null=True, verbose_name='Data de coleta'),
),
migrations.AlterField(
model_name='fluvaccine',
name='date_applied',
field=models.DateField(blank=True, null=True, verbose_name='Data de aplicação'),
),
]
| mit | Python |
|
947551083798e3125cf0782df44cc18728c6bca4 | test messages | SUNET/eduid-webapp,SUNET/eduid-webapp,SUNET/eduid-webapp | src/eduid_webapp/security/tests/test_msgs.py | src/eduid_webapp/security/tests/test_msgs.py | # -*- coding: utf-8 -*-
import unittest
from eduid_webapp.security.helpers import SecurityMsg
class MessagesTests(unittest.TestCase):
def test_messages(self):
""""""
self.assertEqual(str(SecurityMsg.out_of_sync.value), 'user-out-of-sync')
self.assertEqual(str(SecurityMsg.stale_reauthn.value), 'security.stale_authn_info')
self.assertEqual(str(SecurityMsg.rm_verified.value), 'nins.verified_no_rm')
self.assertEqual(str(SecurityMsg.rm_success.value), 'nins.success_removal')
self.assertEqual(str(SecurityMsg.temp_problem.value), 'Temporary technical problems')
self.assertEqual(str(SecurityMsg.already_exists.value), 'nins.already_exists')
self.assertEqual(str(SecurityMsg.add_success.value), 'nins.successfully_added')
self.assertEqual(str(SecurityMsg.max_tokens.value), 'security.u2f.max_allowed_tokens')
self.assertEqual(str(SecurityMsg.max_webauthn.value), 'security.webauthn.max_allowed_tokens')
self.assertEqual(str(SecurityMsg.missing_data.value), 'security.u2f.missing_enrollment_data')
self.assertEqual(str(SecurityMsg.u2f_registered.value), 'security.u2f_register_success')
self.assertEqual(str(SecurityMsg.no_u2f.value), 'security.u2f.no_token_found')
self.assertEqual(str(SecurityMsg.no_challenge.value), 'security.u2f.missing_challenge_data')
self.assertEqual(str(SecurityMsg.no_token.value), 'security.u2f.missing_token')
self.assertEqual(str(SecurityMsg.long_desc.value), 'security.u2f.description_to_long')
self.assertEqual(str(SecurityMsg.rm_u2f_success.value), 'security.u2f-token-removed')
self.assertEqual(str(SecurityMsg.no_pdata.value), 'security.webauthn-missing-pdata')
self.assertEqual(str(SecurityMsg.webauthn_success.value), 'security.webauthn_register_success')
self.assertEqual(str(SecurityMsg.no_last.value), 'security.webauthn-noremove-last')
self.assertEqual(str(SecurityMsg.rm_webauthn.value), 'security.webauthn-token-removed')
self.assertEqual(str(SecurityMsg.no_webauthn.value), 'security.webauthn-token-notfound')
| bsd-3-clause | Python |
|
fcfb84838c7bb111fb9710f4984767b2233caed3 | test commit | eahneahn/eahneahn.github.io,eahneahn/eahneahn.github.io,eahneahn/eahneahn.github.io | test.py | test.py | print("Content-Type: text/plain")
print("")
print("Fuck you")
| bsd-3-clause | Python |
|
f4f3429d157988d4823f20d5155b951f8471fb1b | Fix test app | wong2/gunicorn,gtrdotmcs/gunicorn,zhoucen/gunicorn,elelianghh/gunicorn,mvaled/gunicorn,urbaniak/gunicorn,wong2/gunicorn,ccl0326/gunicorn,urbaniak/gunicorn,MrKiven/gunicorn,mvaled/gunicorn,malept/gunicorn,GitHublong/gunicorn,tempbottle/gunicorn,prezi/gunicorn,jamesblunt/gunicorn,gtrdotmcs/gunicorn,1stvamp/gunicorn,malept/gunicorn,pschanely/gunicorn,prezi/gunicorn,ccl0326/gunicorn,ccl0326/gunicorn,z-fork/gunicorn,jamesblunt/gunicorn,zhoucen/gunicorn,pschanely/gunicorn,jamesblunt/gunicorn,zhoucen/gunicorn,1stvamp/gunicorn,ephes/gunicorn,urbaniak/gunicorn,wong2/gunicorn,pschanely/gunicorn,keakon/gunicorn,prezi/gunicorn,tejasmanohar/gunicorn,gtrdotmcs/gunicorn,malept/gunicorn,mvaled/gunicorn,beni55/gunicorn,WSDC-NITWarangal/gunicorn,harrisonfeng/gunicorn,ammaraskar/gunicorn,alex/gunicorn,alex/gunicorn,alex/gunicorn,1stvamp/gunicorn | test.py | test.py |
def app(environ, start_response):
"""Simplest possible application object"""
data = 'Hello, World!\n'
status = '200 OK'
response_headers = [
('Content-type','text/plain'),
('Content-Length', len(data))
]
start_response(status, response_headers)
return [data]
|
from gunicorn.httpserver import WSGIServer
def app(environ, start_response):
"""Simplest possible application object"""
data = 'Hello, World!\n'
status = '200 OK'
response_headers = [
('Content-type','text/plain'),
('Content-Length', len(data))
]
start_response(status, response_headers)
return [data]
if __name__ == '__main__':
server = WSGIServer(("127.0.0.1", 8000), 1, simple_app)
server.run() | mit | Python |
bc0aa69adc5b1e290941c221ddd498d3fb92244e | Add simple recipe tagger experiment | recipi/recipi,recipi/recipi,recipi/recipi | test.py | test.py | import nltk
from nltk.classify import MaxentClassifier
# Set up our training material in a nice dictionary.
training = {
'ingredients': [
'Pastry for 9-inch tart pan',
'Apple cider vinegar',
'3 eggs',
'1/4 cup sugar',
],
'steps': [
'Sift the powdered sugar and cocoa powder together.',
'Coarsely crush the peppercorns using a mortar and pestle.',
'While the vegetables are cooking, scrub the pig ears clean and cut away any knobby bits of cartilage so they will lie flat.',
'Heat the oven to 375 degrees.',
],
}
# Set up a list that will contain all of our tagged examples,
# which we will pass into the classifier at the end.
training_set = []
for key, val in training.items():
for i in val:
# Set up a list we can use for all of our features,
# which are just individual words in this case.
features = []
# Before we can tokenize words, we need to break the
# text out into sentences.
sentences = nltk.sent_tokenize(i)
for sentence in sentences:
features = features + nltk.word_tokenize(sentence)
# For this example, it's a good idea to normalize for case.
# You may or may not need to do this.
features = [i.lower() for i in features]
# Each feature needs a value. A typical use for a case like this
# is to use True or 1, though you can use almost any value for
# a more complicated application or analysis.
features = dict([(i, True) for i in features])
# NLTK expects you to feed a classifier a list of tuples
# where each tuple is (features, tag).
training_set.append((features, key))
def classify(s):
p = classifier.prob_classify(s)
import json
print("%s\n >>> %s, %s\n" % (json.dumps(s), p.max(), p.prob(p.max())))
return (p.max(), p.prob(p.max()))
# Train up our classifier
# TODO: get http://www.umiacs.umd.edu/~hal/megam/version0_91/ working
classifier = MaxentClassifier.train(training_set)
print()
print()
# Test it out!
# You need to feed the classifier your data in the same format you used
# to train it, in this case individual lowercase words.
classify({'apple': True, 'cider': True, 'vinegar': True, 'cocoa': True})
classify({'heat': True, 'oven': True})
classify({'prepare': True, 'oven': True})
classify({'nothing': True})
| isc | Python |
|
5d9200298ab660bee79d7958f8e155023893be08 | Change author | ClearCorp/odoo-costa-rica,ClearCorp-dev/odoo-costa-rica | l10n_cr_account_banking_cr_bcr/__openerp__.py | l10n_cr_account_banking_cr_bcr/__openerp__.py | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Addons modules by CLEARCORP S.A.
# Copyright (C) 2009-TODAY CLEARCORP S.A. (<http://clearcorp.co.cr>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
{
'name': 'BCR Account Banking',
'version': '0.1',
'license': 'AGPL-3',
'author': 'ClearCorp',
'website': 'http://www.clearcorp.co.cr',
'category': 'Accounting & Finance',
'depends': [
'account_banking_ccorp_dg',
],
'init_xml': [],
'update_xml': [],
'demo_xml': [],
'description': '',
'active': False,
'installable': True,
}
| # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Addons modules by CLEARCORP S.A.
# Copyright (C) 2009-TODAY CLEARCORP S.A. (<http://clearcorp.co.cr>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
{
'name': 'BCR Account Banking',
'version': '0.1',
'license': 'AGPL-3',
'author': 'CLEARCORP S.A.',
'website': 'http://www.clearcorp.co.cr',
'category': 'Accounting & Finance',
'depends': [
'account_banking_ccorp',
],
'init_xml': [],
'update_xml': [],
'demo_xml': [],
'description': '',
'active': False,
'installable': True,
}
| agpl-3.0 | Python |
ab458e10742897c692e3d4e4066ed193e141e258 | add filterfuncs module | daler/Pharmacogenomics_Prediction_Pipeline_P3,NCBI-Hackathons/Pharmacogenomics_Prediction_Pipeline_P3,DCGenomics/multiple_myeloma_rnaseq_drug_response_hackathon_v002,DCGenomics/Pharmacogenomics_Prediction_Pipeline_P3,DCGenomics/Pharmacogenomics_Prediction_Pipeline_P3,daler/Pharmacogenomics_Prediction_Pipeline_P3,DCGenomics/Pharmacogenomics_Prediction_Pipeline_P3,NCBI-Hackathons/Pharmacogenomics_Prediction_Pipeline_P3,NCBI-Hackathons/Pharmacogenomics_Prediction_Pipeline_P3,daler/Pharmacogenomics_Prediction_Pipeline_P3,DCGenomics/multiple_myeloma_rnaseq_drug_response_hackathon_v002,DCGenomics/multiple_myeloma_rnaseq_drug_response_hackathon_v002 | filterfuncs.py | filterfuncs.py | from tools import pipeline_helpers
import pandas as pd
def run1(infile, features_label, output_label):
"""
Handle variant data by only keeping rows where 10-90% of samples have
variants.
For CNV data, don't do any filtering.
Otherwise, simply remove rows with zero variance.
"""
if (features_label == 'exome_variants' or 'variants' in output_label):
d = pipeline_helpers.remove_nfrac_variants(infile, nfrac=0.1)
elif features_label == 'cnv':
return pd.read_table(infile, index_col=0)
else:
d = pipeline_helpers.remove_zero_variance(infile)
return d
| cc0-1.0 | Python |
|
b9d5e015b291f27becc682f05a12ec5c6a0cf467 | Implement module to create new pads on collabedit.com. | thsnr/gygax | gygax/modules/pad.py | gygax/modules/pad.py | # -*- coding: utf-8 -*-
"""
:mod:`gygax.modules.pad` --- Module for creating pads on collabedit.com
=======================================================================
"""
from http import client
from gygax.modules import admin
def pad(bot, sender, text):
if not admin.is_admin(sender):
bot.reply("unauthorized")
return
# We can't use urllib, because collabedit uses weird redirects which make
# urllib think we are redirected in an endless loop.
conn = client.HTTPConnection("collabedit.com")
conn.request("GET", "/new")
r1 = conn.getresponse()
if r1.status != 302:
raise Exception("GET /new returned {} {}".format(r1.status, r1.reason))
headers = {"Cookie": r1.getheader("Set-Cookie").split(";")[0]}
r1.read() # Read the response body so we can make a new request.
conn.request("GET", r1.getheader("Location"), headers=headers)
r2 = conn.getresponse()
if r2.status != 302:
raise Exception("GET {} returned {} {}".format(
r1.getheader("Location"), r2.status, r2.reason))
bot.reply("http://collabedit.com{}".format(r2.getheader("Location")))
conn.close()
pad.command = ".pad"
| mit | Python |
|
7cc86a96427cc35824960c01d84fbe8d45364670 | Add admin page for User | shirlei/helios-server,shirlei/helios-server,shirlei/helios-server,shirlei/helios-server,shirlei/helios-server | helios_auth/admin.py | helios_auth/admin.py | from django.contrib import admin
from helios.models import User
class UserAdmin(admin.ModelAdmin):
exclude = ('info', 'token')
admin.site.register(User, UserAdmin) | apache-2.0 | Python |
|
e99700ff985e9821faf390ca6070a0c879eafc20 | Add perkeyavg python example | holdenk/learning-spark-examples,JerryTseng/learning-spark,rex1100/learning-spark,XiaoqingWang/learning-spark,negokaz/learning-spark,jaehyuk/learning-spark,coursera4ashok/learning-spark,asarraf/learning-spark,huydx/learning-spark,databricks/learning-spark,UsterNes/learning-spark,anjuncc/learning-spark-examples,gaoxuesong/learning-spark,huydx/learning-spark,GatsbyNewton/learning-spark,SunGuo/learning-spark,qingkaikong/learning-spark-examples,obinsanni/learning-spark,junwucs/learning-spark,NBSW/learning-spark,kod3r/learning-spark,bhagatsingh/learning-spark,rex1100/learning-spark,tengteng/learning-spark,databricks/learning-spark,jaehyuk/learning-spark,asarraf/learning-spark,kod3r/learning-spark,kpraveen420/learning-spark,diogoaurelio/learning-spark,dsdinter/learning-spark-examples,ellis429/learning-spark-examples,concerned3rdparty/learning-spark,databricks/learning-spark,feynman0825/learning-spark,huixiang/learning-spark,baokunguo/learning-spark-examples,baokunguo/learning-spark-examples,asarraf/learning-spark,anjuncc/learning-spark-examples,kod3r/learning-spark,UsterNes/learning-spark,UsterNes/learning-spark,anjuncc/learning-spark-examples,feynman0825/learning-spark,jindalcastle/learning-spark,mohitsh/learning-spark,shimizust/learning-spark,tengteng/learning-spark,bhagatsingh/learning-spark,tengteng/learning-spark,negokaz/learning-spark,shimizust/learning-spark,bhagatsingh/learning-spark,DINESHKUMARMURUGAN/learning-spark,concerned3rdparty/learning-spark,mohitsh/learning-spark,JerryTseng/learning-spark,GatsbyNewton/learning-spark,mmirolim/learning-spark,dsdinter/learning-spark-examples,obinsanni/learning-spark,NBSW/learning-spark,feynman0825/learning-spark,negokaz/learning-spark,noprom/learning-spark,ramyasrigangula/learning-spark,kpraveen420/learning-spark,kpraveen420/learning-spark,junwucs/learning-spark,diogoaurelio/learning-spark,rex1100/learning-spark,asarraf/learning-spark,mohitsh/learning-spark,huixiang/learning-spark,kpraveen420/learning-spark,diogoaurelio/learning-spark,junwucs/learning-spark,ellis429/learning-spark,JerryTseng/learning-spark,dsdinter/learning-spark-examples,coursera4ashok/learning-spark,NBSW/learning-spark,huixiang/learning-spark,UsterNes/learning-spark,ramyasrigangula/learning-spark,qingkaikong/learning-spark-examples,zaxliu/learning-spark,mohitsh/learning-spark,gaoxuesong/learning-spark,kod3r/learning-spark,diogoaurelio/learning-spark,ellis429/learning-spark,noprom/learning-spark,coursera4ashok/learning-spark,tengteng/learning-spark,feynman0825/learning-spark,XiaoqingWang/learning-spark,baokunguo/learning-spark-examples,ellis429/learning-spark-examples,mmirolim/learning-spark,huydx/learning-spark,UsterNes/learning-spark,bhagatsingh/learning-spark,shimizust/learning-spark,junwucs/learning-spark,NBSW/learning-spark,ellis429/learning-spark,SunGuo/learning-spark,XiaoqingWang/learning-spark,DINESHKUMARMURUGAN/learning-spark,negokaz/learning-spark,jindalcastle/learning-spark,shimizust/learning-spark,ellis429/learning-spark,concerned3rdparty/learning-spark,ramyasrigangula/learning-spark,dsdinter/learning-spark-examples,SunGuo/learning-spark,JerryTseng/learning-spark,gaoxuesong/learning-spark,qingkaikong/learning-spark-examples,qingkaikong/learning-spark-examples,baokunguo/learning-spark-examples,zaxliu/learning-spark,mohitsh/learning-spark,GatsbyNewton/learning-spark,ellis429/learning-spark,NBSW/learning-spark,mmirolim/learning-spark,shimizust/learning-spark,ramyasrigangula/learning-spark,holdenk/learning-spark-examples,holdenk/learning-spark-examples,coursera4ashok/learning-spark,jaehyuk/learning-spark,baokunguo/learning-spark-examples,diogoaurelio/learning-spark,kod3r/learning-spark,ellis429/learning-spark-examples,databricks/learning-spark,asarraf/learning-spark,XiaoqingWang/learning-spark,huydx/learning-spark,noprom/learning-spark,huixiang/learning-spark,ellis429/learning-spark-examples,qingkaikong/learning-spark-examples,jaehyuk/learning-spark,zaxliu/learning-spark,obinsanni/learning-spark,jindalcastle/learning-spark,anjuncc/learning-spark-examples,tengteng/learning-spark,bhagatsingh/learning-spark,negokaz/learning-spark,SunGuo/learning-spark,gaoxuesong/learning-spark,noprom/learning-spark,kpraveen420/learning-spark,jindalcastle/learning-spark,concerned3rdparty/learning-spark,anjuncc/learning-spark-examples,zaxliu/learning-spark,jindalcastle/learning-spark,zaxliu/learning-spark,databricks/learning-spark,ramyasrigangula/learning-spark,ellis429/learning-spark-examples,DINESHKUMARMURUGAN/learning-spark,SunGuo/learning-spark,GatsbyNewton/learning-spark,mmirolim/learning-spark,mmirolim/learning-spark,dsdinter/learning-spark-examples,junwucs/learning-spark,feynman0825/learning-spark,jaehyuk/learning-spark,JerryTseng/learning-spark,gaoxuesong/learning-spark,DINESHKUMARMURUGAN/learning-spark,XiaoqingWang/learning-spark,GatsbyNewton/learning-spark,obinsanni/learning-spark,huydx/learning-spark,noprom/learning-spark,obinsanni/learning-spark,DINESHKUMARMURUGAN/learning-spark,huixiang/learning-spark,holdenk/learning-spark-examples,concerned3rdparty/learning-spark,holdenk/learning-spark-examples,coursera4ashok/learning-spark | src/python/PerKeyAvg.py | src/python/PerKeyAvg.py | """
>>> from pyspark.context import SparkContext
>>> sc = SparkContext('local', 'test')
>>> b = sc.parallelize([("coffee", 1), ("pandas", 2), ("coffee", 3), ("very", 4)])
>>> perKeyAvg(b)
"""
import sys
from pyspark import SparkContext
def perKeyAvg(nums):
"""Compute the avg"""
sumCount = nums.combineByKey((lambda x: (x,1)),
(lambda x, y: (x[0] + y, x[1] + 1)),
(lambda x, y: (x[0] + y[0], x[1] + y[1])))
return sumCount.collectAsMap()
if __name__ == "__main__":
master = "local"
if len(sys.argv) == 2:
master = sys.argv[1]
sc = SparkContext(master, "Sum")
nums = sc.parallelize([("coffee", 1), ("pandas", 2), ("coffee", 3), ("very", 4)])
avg = perKeyAvg(nums)
print avg
| mit | Python |
|
a640bf45c4fb8829888f664e48058d6647473449 | Fix migrations | softwaresaved/fat,softwaresaved/fat,softwaresaved/fat,softwaresaved/fat | lowfat/migrations/0113_merge_20171103_0948.py | lowfat/migrations/0113_merge_20171103_0948.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.5 on 2017-11-03 09:48
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('lowfat', '0112_auto_20171031_1133'),
('lowfat', '0111_auto_20171009_0933'),
]
operations = [
]
| bsd-3-clause | Python |
|
8d2c141ac6c2d1772561d36c38cbbf8140abd9db | Add day 12. | masasin/advent_of_code_2015 | day_12.py | day_12.py | """
http://adventofcode.com/day/11
--- Day 12: JSAbacusFramework.io ---
Santa's Accounting-Elves need help balancing the books after a recent order.
Unfortunately, their accounting software uses a peculiar storage format. That's
where you come in.
They have a JSON document which contains a variety of things: arrays ([1,2,3]),
objects ({"a":1, "b":2}), numbers, and strings. Your first job is to simply find
all of the numbers throughout the document and add them together.
For example:
- [1,2,3] and {"a":2,"b":4} both have a sum of 6.
- [[[3]]] and {"a":{"b":4},"c":-1} both have a sum of 3.
- {"a":[-1,1]} and [-1,{"a":1}] both have a sum of 0.
- [] and {} both have a sum of 0.
You will not encounter any strings containing numbers.
What is the sum of all numbers in the document?
--- Part Two ---
Uh oh - the Accounting-Elves have realized that they double-counted everything
red.
Ignore any object (and all of its children) which has any property with the
value "red". Do this only for objects {...}), not arrays ([...]).
- [1,2,3] still has a sum of 6.
- [1,{"c":"red","b":2},3] now has a sum of 4, because the middle object is
ignored.
- {"d":"red","e":[1,2,3,4],"f":5} now has a sum of 0, because the entire
structure is ignored.
- [1,"red",5] has a sum of 6, because "red" in an array has no effect.
"""
import json
import re
def test_sum_numbers():
assert sum_numbers([1, 2, 3]) == 6
assert sum_numbers({"a": 2, "b": 4}) == 6
assert sum_numbers([[[3]]]) == 3
assert sum_numbers({"a": {"b": 4}, "c": -1}) == 3
assert sum_numbers({"a": [-1, 1]}) == 0
assert sum_numbers([-1, {"a": 1}]) == 0
assert sum_numbers([]) == 0
assert sum_numbers({}) == 0
def test_sum_non_reds():
assert sum_non_reds([1, 2, 3]) == 6
assert sum_non_reds([1, {"c": "red", "b": 2}, 3]) == 4
assert sum_non_reds({"d": "red", "e": [1, 2, 3, 4], "f": 5}) == 0
assert sum_non_reds({"d": "red", "e": [1, 2, {}, 3, 4], "f": 5}) == 0
assert sum_non_reds([1, "red", 5]) == 6
def sum_numbers(s):
return sum(int(i) for i in re.findall(r"(-?\d+)", str(s)))
def sum_non_reds(s):
if isinstance(s, int):
return s
if isinstance(s, list):
return sum(sum_non_reds(i) for i in s)
elif isinstance(s, dict):
if "red" in s.values():
return 0
else:
return sum(sum_non_reds(i) for i in s.values())
return 0
def part_one():
with open("inputs/day_12_input.txt") as fin:
print(sum_numbers(fin.read()))
def part_two():
with open("inputs/day_12_input.txt") as fin:
print(sum_non_reds(json.load(fin)))
if __name__ == "__main__":
part_one()
part_two()
| mit | Python |
|
946c5b14ec95af2e4dde406e94a50e7d5cdc1502 | Create BalanceData.py | vidhyal/WitchMusic | BalanceData.py | BalanceData.py | #Copyright (c) 2016 Vidhya, Nandini
import os
import numpy as np
import operator
from constants import *
FIX_DEV = 0.00000001
rootdir = os.getcwd()
newdir = os.path.join(rootdir,'featurefiles')
def LoadData():
data_file = open(os.path.join(newdir,'out_2.txt'),'r')
unprocessed_data = data_file.readlines()
labels ={}
features ={}
for line in unprocessed_data:
feature_vector = []
split_line = line.split(' ')
for element in split_line[1:-1]:
feature_vector.append(float(element))
track_id = split_line[0]
features[track_id] = feature_vector
data_file.close()
label_file = open(os.path.join(newdir,'labelout.txt'),'r')
label_data = label_file.readlines()
for line in label_data:
split_line = line.split('\t')
track_id = split_line[0]
#print (track_id)
if track_id in features:
labels[split_line[0]] = split_line[1].split('\n')[0]
label_file.close()
for key in features:
feature = features[key]
label = labels[key]
# print feature, label
return features, labels
def writeToFile(key,feature,fp):
fp1 = open(fp,'a')
line = key
for s in feature:
line+= " %f" %float(s)
line+="\n"
fp1.write(line)
def BalanceData(features, labels):
if not os.path.exists('train'):
os.makedirs('train')
traindir = os.path.join(rootdir,'train')
if not os.path.exists('test'):
os.makedirs('test')
testdir = os.path.join(rootdir,'test')
count =0
testFile = open(os.path.join(testdir,'testFile'),'w+')
genreFeat={}
numList ={}
testFeat = {}
trainFeat ={}
genreTestFeat ={}
for genre in genres:
str1 = genre+'.txt'
fout = open(os.path.join(traindir,str1),'w+')
#print fout
delKey =[]
feature_list =[]
test_list =[]
subcount=0
for key in features:
if labels[key] == genre:
delKey.append(key)
subcount=subcount+1
fout.close()
count = count+ subcount
numList[genre] = subcount/2
if subcount != 0:
for key in delKey[:subcount/2]:
trainFeat[key] = features[key]
trainFeat[key].append(key)
feature_list.append(trainFeat[key])
#writeToFile(key, features[key], os.path.join(traindir,str1))
genreFeat[genre] = feature_list
for key in delKey[subcount/2:]:
testFeat[key] = features[key]
testFeat[key].append(key)
test_list.append(testFeat[key])
#writeToFile(key,features[key], os.path.join(testdir,'testFile'))
genreTestFeat[genre] = test_list
for key in delKey:
del features[key]
return genreFeat, numList, count, genreTestFeat
def ConvertToArrays(feats):
features =[]
labels = []
keys = []
for genre in feats:
#print genre
for f in feats[genre]:
features.append(f[:-1])
keys.append(f[-1])
#print features
#input("press enter")
labels.append(genre)
return np.asarray(features), np.asarray(labels), np.asarray(keys)
def GetData():
features, labels =LoadData()
genreFeat,countGenre, count, genreTestFeat = BalanceData(features, labels)
train_features, train_labels, train_keys = ConvertToArrays(genreFeat)
test_features, test_labels, test_keys = ConvertToArrays(genreTestFeat)
return train_features, train_labels, test_features, test_labels, test_keys
| mit | Python |
|
3811bf52733bfbac7e5720f860cced216b530963 | Add a Theme object | geotagx/geotagx-project-template,geotagx/geotagx-project-template | src/theme.py | src/theme.py | # This module is part of the GeoTag-X project builder.
# Copyright (C) 2015 UNITAR.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
class Theme:
path = None
assets = {
"core":{
"js":None,
"css":None
},
"geolocation":{
"js":None,
"css":None
},
"datetime":{
"js":None,
"css":None
},
}
template = None
def __init__(self, path):
"""__init__(path:string)
Instantiates a Theme object from the content of the directory located at
the specified path.
"""
import os
from jinja2 import Environment, FileSystemLoader
valid, message = Theme.isvalidpath(path)
if not valid:
raise Exception(message)
self.path = path
self.template = Environment(loader=FileSystemLoader(searchpath=os.path.join(self.path, "templates"))).get_template("base.html")
def getasset(self, name):
"""getasset(name:string)
Returns the set of assets contained in the bundle with the specified name.
"""
css, js = "", ""
name = name.strip()
bundle = self.assets.get(name, None)
if bundle is None:
print "[Theme::getasset] Warning! Unknown asset bundle '%s'." % name
else:
# If any assets have not been loaded into memory, do so.
empties = filter(lambda item: item[1] is None, bundle.iteritems())
if len(empties) > 0:
import os
basefile = os.path.join(self.path, *["assets", "bundles", "asset.bundle.%s" % name])
for key, _ in empties:
filepath = "%s.%s" % (basefile, key)
try:
with open(filepath, "r") as file:
bundle[key] = file.read()
except IOError:
# If a theme does not contain a specified asset, set its
# value to an empty string. Leaving it as 'None' means
# the script will keep searching for the missing file.
bundle[key] = ""
css = bundle["css"]
js = bundle["js"]
return css, js
def getassets(self, bundles=set()):
"""getassets(bundles:set)
Returns the themes JS and CSS assets, based on the specified bundles.
"""
try: assert type(bundles) is set, "[Theme::getassets] Error! 'bundles' parameter is not a set!"
except AssertionError as error: raise Exception(error)
# The core bundle is always returned, however it is explicitly added to
# the bundle set, it needs to be removed or it will be concatenated to
# the result twice.
if "core" in bundles:
bundles.remove("core")
css, js = self.getasset("core")
for bundle in bundles:
css_, js_ = self.getasset(bundle)
if len(css_) > 0: css += css_
if len(js_) > 0: js += ";" + js_ # ';' makes sure statements between concatenated scripts are separated.
return css, js
@staticmethod
def isvalidpath(path):
"""isvalidpath(path:string)
Returns true if the specified path contains a valid theme, false otherwise.
"""
return (True, None)
| agpl-3.0 | Python |
|
7bace5ca301124f03d7ff98669ac08c0c32da55f | Add example OOP python script | boundary/tsi-lab,jdgwartney/tsi-lab,jdgwartney/tsi-lab,boundary/tsi-lab,jdgwartney/tsi-lab,jdgwartney/tsi-lab,boundary/tsi-lab,boundary/tsi-lab | labs/lab-5/oop.py | labs/lab-5/oop.py | #!/usr/bin/python
#
# Copyright 2016 BMC Software, 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.
#
class Animal(object):
def __init__(self):
self.voice = "???"
def speak(self):
print('A {0} says "{1}"'.format(self.__class__.__name__, self.voice))
class Cat(Animal):
def __init__(self):
super(Cat, self).__init__()
self.voice = 'Meow!'
class Dog(Animal):
def __init__(self):
super(Dog, self).__init__()
self.voice = 'Woof!'
if __name__ == '__main__':
animal = Animal()
animal.speak()
cat = Cat()
cat.speak()
dog = Dog()
dog.speak()
| apache-2.0 | Python |
|
5f2533e090e181d84c3e5567131447aa4326773a | Add libx11 package | trigger-happy/conan-packages | libx11/conanfile.py | libx11/conanfile.py | from conans import ConanFile, AutoToolsBuildEnvironment, tools
import os
class Libx11Conan(ConanFile):
name = "libx11"
version = "1.6.5"
license = "Custom https://cgit.freedesktop.org/xorg/lib/libX11/tree/COPYING"
url = "https://github.com/trigger-happy/conan-packages"
description = "X11 client-side library"
settings = "os", "compiler", "build_type", "arch"
options = {"shared": [True, False]}
default_options = "shared=False"
generators = "cmake"
def source(self):
pkgLink = 'https://xorg.freedesktop.org/releases/individual/lib/libX11-{version}.tar.bz2'.format(version=self.version)
self.run("curl -JOL " + pkgLink)
self.run("tar xf libX11-{version}.tar.bz2".format(version=self.version))
def build(self):
envBuild = AutoToolsBuildEnvironment(self)
installPrefix=os.getcwd()
with tools.chdir("libX11-{version}".format(version=self.version)):
with tools.environment_append(envBuild.vars):
self.run("./configure --prefix={0} --disable-xf86bigfont".format(installPrefix))
self.run("make install")
def package(self):
self.copy("lib/*", dst=".", keep_path=True)
self.copy("include/*", dst=".", keep_path=True)
def package_info(self):
self.cpp_info.libs = ["X11", "X11-xcb"]
| mit | Python |
|
e972bb5127b231bfbdf021597f5c9a32bb6e21c8 | Create gametesting.py | JadedCoder712/Final-Project | gametesting.py | gametesting.py | mit | Python |
||
a83a48f6c9276b86c3cc13aeb000611036a6e3c4 | Make all end-points accepting post | micbou/JediHTTP,micbou/JediHTTP,vheon/JediHTTP,vheon/JediHTTP | jedihttp/handlers.py | jedihttp/handlers.py | import bottle
from bottle import response, request
import json
import jedi
import logging
app = bottle.Bottle( __name__ )
logger = logging.getLogger( __name__ )
@app.post( '/healthy' )
def healthy():
return _Json({})
@app.post( '/ready' )
def ready():
return _Json({})
@app.post( '/completions' )
def completion():
logger.info( 'received /completions request' )
script = _GetJediScript( request.json )
return _Json(
{
'completions': [ {
'name': completion.name,
'description': completion.description,
'docstring': completion.docstring(),
'module_path': completion.module_path,
'line': completion.line,
'column': completion.column
} for completion in script.completions() ]
} )
def _GetJediScript( request_data ):
source = request_data[ 'source' ]
line = request_data[ 'line' ]
col = request_data[ 'col' ]
path = request_data[ 'path' ]
return jedi.Script( source, line, col, path )
def _Json( data ):
response.content_type = 'application/json'
return json.dumps( data )
| import bottle
from bottle import response, request
import json
import jedi
import logging
app = bottle.Bottle( __name__ )
logger = logging.getLogger( __name__ )
@app.get( '/healthy' )
def healthy():
return _Json({})
@app.get( '/ready' )
def ready():
return _Json({})
@app.post( '/completions' )
def completion():
logger.info( 'received /completions request' )
script = _GetJediScript( request.json )
return _Json(
{
'completions': [ {
'name': completion.name,
'description': completion.description,
'docstring': completion.docstring(),
'module_path': completion.module_path,
'line': completion.line,
'column': completion.column
} for completion in script.completions() ]
} )
def _GetJediScript( request_data ):
source = request_data[ 'source' ]
line = request_data[ 'line' ]
col = request_data[ 'col' ]
path = request_data[ 'path' ]
return jedi.Script( source, line, col, path )
def _Json( data ):
response.content_type = 'application/json'
return json.dumps( data )
| apache-2.0 | Python |
64e91bf4a7fb8dae8ae49db64396bdfed12bec63 | Add deploy script for pypi. | mayfield/shellish | deploy.py | deploy.py | """
Deploy this package to PyPi.
If the package is already uploaded (by --version) then this will do nothing.
Reqires Python3.
"""
import http.client
import json
import subprocess
def setup(*args):
o = subprocess.check_output('python3 ./setup.py %s' % ' '.join(args),
shell=True)
return o.decode().rstrip()
name = setup('--name')
version = setup('--version')
print("Package:", name)
print("Version:", version)
print("Checking PyPi...")
piconn = http.client.HTTPSConnection('pypi.python.org')
piconn.request("GET", '/pypi/%s/json' % name)
piresp = piconn.getresponse()
if piresp.status != 200:
exit('PyPi Service Error: %s' % piresp.reason)
piinfo = json.loads(piresp.read().decode())
deployed_versions = list(piinfo['releases'].keys())
if version in deployed_versions:
print("PyPi is already up-to-date for:", version)
exit()
print(setup('sdist', 'upload'))
| mit | Python |
|
03137f65202f5423ea705db601aaea7f18c590f9 | add the main file | WheatonCS/Lexos,WheatonCS/Lexos,WheatonCS/Lexos | lexos/__main__.py | lexos/__main__.py | """Module allowing for ``python -m lexos ...``."""
from lexos import application
application.run()
| mit | Python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.