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
34fff4bf13fa2c4d481a06339981db08239138ae
add test case of petitlyrics
franklai/lyric-get,franklai/lyric-get,franklai/lyric-get,franklai/lyric-get
lyric_engine/tests/test_petitlyrics.py
lyric_engine/tests/test_petitlyrics.py
# coding: utf-8 import os import sys module_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', 'modules') sys.path.append(module_dir) import unittest from petitlyrics import PetitLyrics as Lyric class PetitLyricsTest(unittest.TestCase): def test_url_01(self): url = 'http://petitlyrics.com/lyrics/34690' obj = Lyric(url) obj.parse() self.assertEqual(obj.title, u'Tune The Rainbow') self.assertEqual(obj.artist, u'坂本 真綾') self.assertEqual(obj.lyricist, u'岩里 祐穂') self.assertEqual(obj.composer, u'菅野 よう子') self.assertEqual(len(obj.lyric), 819) def test_url_02(self): url = 'http://petitlyrics.com/lyrics/936622' obj = Lyric(url) obj.parse() self.assertEqual(obj.title, u'RPG') self.assertEqual(obj.artist, u'SEKAI NO OWARI') self.assertEqual(obj.lyricist, u'Saori/Fukase') self.assertEqual(obj.composer, u'Fukase') self.assertEqual(len(obj.lyric), 933) if __name__ == '__main__': unittest.main()
mit
Python
16fd4ba06b6da8ec33a83a8cfe2e38a130fb47b3
Add a module for common plotting routines that will be used.
dalepartridge/seapy,ocefpaf/seapy,powellb/seapy
plot.py
plot.py
#!/usr/bin/env python """ plot.py State Estimation and Analysis for PYthon Module with plotting utilities Written by Brian Powell on 10/18/13 Copyright (c)2013 University of Hawaii under the BSD-License. """ from __future__ import print_function import numpy as np from scipy import ndimage import os import re from matplotlib import pyplot as plt def stackbar(x, y, colors=None, **kwargs): """ Given an array of vectors in y, draw a bar chart for each one stacked on the prior. """ s=y[0,:] if colors is None: colors = [ "" for i in range(0,y.shape[0]) ] plt.bar(x, y[0,:], color=colors[0], **kwargs) for i in range(1,y.shape[0]): plt.bar(x, y[i,:], color=colors[i], bottom=s, **kwargs) s=s+y[i,:]
mit
Python
94d40dfcf574d61df7def99a43d5b9fa0c75e244
Add py solution for 406. Queue Reconstruction by Height
ckclark/leetcode,ckclark/leetcode,ckclark/leetcode,ckclark/leetcode,ckclark/leetcode,ckclark/leetcode
py/queue-reconstruction-by-height.py
py/queue-reconstruction-by-height.py
from collections import defaultdict class Solution(object): def insert(self, now, p, front): lsize = 0 if now.left is None else now.left.val[1] if front <= lsize: if now.left is None: now.left = TreeNode((p, 1)) else: self.insert(now.left, p, front) else: if now.right is None: now.right = TreeNode((p, 1)) else: self.insert(now.right, p, front - lsize - 1) now.val = (now.val[0], now.val[1] + 1) def inOrder(self, cur): if cur: for x in self.inOrder(cur.left): yield x yield cur.val[0] for x in self.inOrder(cur.right): yield x def reconstructQueue(self, people): """ :type people: List[List[int]] :rtype: List[List[int]] """ if not people: return people people.sort(key=lambda x:(-x[0], x[1])) root = TreeNode((people[0], 1)) for p in people[1:]: self.insert(root, p, p[1]) return list(self.inOrder(root))
apache-2.0
Python
8fb97711dd84512a8a654de3dca2bee24689a2a7
add a test for pytestmark
s0undt3ch/pytest-tornado,eugeniy/pytest-tornado
pytest_tornado/test/test_fixtures.py
pytest_tornado/test/test_fixtures.py
import pytest from tornado import gen _used_fixture = False @gen.coroutine def dummy(io_loop): yield gen.Task(io_loop.add_callback) raise gen.Return(True) @pytest.fixture(scope='module') def preparations(): global _used_fixture _used_fixture = True pytestmark = pytest.mark.usefixtures('preparations') @pytest.mark.xfail(pytest.__version__ < '2.7.0', reason='py.test 2.7 adds hookwrapper, fixes collection') @pytest.mark.gen_test def test_uses_pytestmark_fixtures(io_loop): assert (yield dummy(io_loop)) assert _used_fixture
apache-2.0
Python
76ce9117ed92a743734cd5ba7e209617a7664ad1
Add partial benchmarking file for gala
janelia-flyem/gala,jni/gala
benchmarks/bench_gala.py
benchmarks/bench_gala.py
import os from gala import imio, features, agglo, classify rundir = os.path.dirname(__file__) dd = os.path.abspath(os.path.join(rundir, '../tests/example-data')) em3d = features.default.paper_em() def setup_trdata(): wstr = imio.read_h5_stack(os.path.join(dd, 'train-ws.lzf.h5')) prtr = imio.read_h5_stack(os.path.join(dd, 'train-p1.lzf.h5')) gttr = imio.read_h5_stack(os.path.join(dd, 'train-gt.lzf.h5')) return wstr, prtr, gttr def setup_tsdata(): wsts = imio.read_h5_stack(os.path.join(dd, 'test-ws.lzf.h5')) prts = imio.read_h5_stack(os.path.join(dd, 'test-p1.lzf.h5')) gtts = imio.read_h5_stack(os.path.join(dd, 'test-gt.lzf.h5')) return wsts, prts, gtts def setup_trgraph(): ws, pr, ts = setup_trdata() g = agglo.Rag(ws, pr, feature_manager=em3d) return g def setup_tsgraph(): ws, pr, ts = setup_tsdata() g = agglo.Rag(ws, pr, feature_manager=em3d) return g def setup_trexamples(): gt = imio.read_h5_stack(os.path.join(dd, 'train-gt.lzf.h5')) g = setup_trgraph() (X, y, w, e), _ = g.learn_agglomerate(gt, em3d, min_num_epochs=5) y = y[:, 0] return X, y def setup_classifier(): X, y = setup_trexamples() rf = classify.DefaultRandomForest() rf.fit(X, y) return rf def setup_policy(): rf = classify.DefaultRandomForest() cl = agglo.classifier_probability(em3d, rf) return cl def setup_tsgraph_queue(): g = setup_tsgraph() cl = setup_policy() g.merge_priority_function = cl g.rebuild_merge_queue() return g
bsd-3-clause
Python
79fb9449da73e70ef7ed9e1e6862da41fc42ab75
Add finalized source codes
chpoon92/network-analysis-2-anaconda-python
src/hw1.py
src/hw1.py
import networkx as nx import numpy as np import matplotlib.pyplot as plt import pylab G = nx.Graph() G.add_edges_from([('1','2'),('1','4'),('2','3'),('2','4'),('3','4'),('4','5'),('5','6'),('5','7'),('6','7')]) # create the graph print G.nodes(), '\n', G.edges(), '\n', G.degree().values() # check graph is correct adj = nx.adj_matrix(G) print "adjency matrix: \n", adj.todense() # print adjency matrix k_ij = np.outer(G.degree().values(), G.degree().values()) mod = adj - k_ij / (2.*len(G.edges())) print "modularity matrix: \n", mod # suppose we only have 2 communities, we can iterate all the possible situations # and get the optimum partition modval_opt = -100000 z_opt = np.zeros((len(G.nodes()), 2)) for i in range(0, 2**(len(G.nodes())-1)): # iterate all the possible membership partition = np.matrix(map(int, list('{0:07b}'.format(i)))) # get a membership vector directly from the bits of an interger # e.g. i = 2, list('{0:07b}'.format(i)) will give a list # ['0', '0', '0', '0', '0','1','0'] # map(int, list) will change it to be a int list [..., 1, 0] Z = np.transpose(np.concatenate((partition, 1-partition))) # this is a 7x2 membership matrix # print Z, "\n" modval_partition = np.trace(Z.transpose() * mod * Z) / (2*len(G.edges())) if modval_opt < modval_partition: modval_opt = modval_partition z_opt = Z print "\n optimal community membership: \n", z_opt, "\n corresponds to maximum modularity value:\n", modval_opt # print the graph with community in different color and node size propotional to # its degree plt.figure(figsize=(8,6)) pos = nx.spring_layout(G) nx.draw_networkx_nodes(G, pos, node_color=np.array(z_opt.transpose())[0], node_size=400*np.array(G.degree().values()), alpha=0.8, linewidths=0) labels = {} for node in G.nodes(): labels[node] = r'$'+node+'$' nx.draw_networkx_labels(G, pos, labels, font_size=24) nx.draw_networkx_edges(G, pos, width=16, edge_color='g', alpha=0.5) plt.axis('off') plt.show() # for problem 3, to plot your facebook network. For me you can clearly see my #friends is divided into 2 communities. import codecs with codecs.open('myFacebook.gml','r', 'utf8') as f: # don't use networkx.read_gml() functions, it will have lines = f.readlines() # UnicodeDecodeError, use these three lines to load gml fbG = nx.readwrite.gml.parse_gml(lines, relabel=True) # into a networkx graph plt.figure(figsize=(18,12)) pos = nx.spring_layout(fbG) gender = [] wallcount = [] ids = {} deg = [] DegDict = fbG.degree() for name,attr in fbG.node.iteritems(): gender.append(0 if attr['sex'] == 'male' else 1) wallcount.append(attr['wallcount']) ids[name] = attr['id'] deg.append(DegDict[name]) nx.draw_networkx_nodes(fbG, pos, node_color=gender, node_size=200+40*np.array(deg), alpha=0.8, linewidths=0) nx.draw_networkx_edges(fbG, pos, width=1.8, edge_color='black', alpha=0.3) nx.draw_networkx_labels(fbG, pos, labels=ids, font_size=14, font_family='DejaVu Sans') # remove labels=ids will use name as labels plt.axis('off') plt.show()
mit
Python
180faadb24bf3b4d153f1c46c4883bdcc0b987ff
add a manifest (.cvmfspublished) abstraction class
djw8605/cvmfs,cvmfs-testing/cvmfs,DrDaveD/cvmfs,cvmfs/cvmfs,trshaffer/cvmfs,cvmfs-testing/cvmfs,cvmfs-testing/cvmfs,alhowaidi/cvmfsNDN,trshaffer/cvmfs,cvmfs/cvmfs,DrDaveD/cvmfs,Gangbiao/cvmfs,alhowaidi/cvmfsNDN,trshaffer/cvmfs,Gangbiao/cvmfs,djw8605/cvmfs,djw8605/cvmfs,DrDaveD/cvmfs,DrDaveD/cvmfs,djw8605/cvmfs,MicBrain/cvmfs,trshaffer/cvmfs,Gangbiao/cvmfs,cvmfs/cvmfs,DrDaveD/cvmfs,cvmfs/cvmfs,Gangbiao/cvmfs,MicBrain/cvmfs,alhowaidi/cvmfsNDN,MicBrain/cvmfs,cvmfs-testing/cvmfs,alhowaidi/cvmfsNDN,Moliholy/cvmfs,Moliholy/cvmfs,Moliholy/cvmfs,cvmfs-testing/cvmfs,reneme/cvmfs,cvmfs/cvmfs,reneme/cvmfs,reneme/cvmfs,djw8605/cvmfs,MicBrain/cvmfs,MicBrain/cvmfs,Moliholy/cvmfs,DrDaveD/cvmfs,reneme/cvmfs,DrDaveD/cvmfs,reneme/cvmfs,cvmfs/cvmfs,trshaffer/cvmfs,cvmfs/cvmfs,alhowaidi/cvmfsNDN,Moliholy/cvmfs,Gangbiao/cvmfs
python/cvmfs/manifest.py
python/cvmfs/manifest.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Created by René Meusel This file is part of the CernVM File System auxiliary tools. """ import datetime class UnknownManifestField: def __init__(self, key_char): self.key_char = key_char def __str__(self): return self.key_char class ManifestValidityError: def __init__(self, message): Exception.__init__(self, message) class Manifest: """ Wraps information from .cvmfspublished""" def __init__(self, manifest_file): """ Initializes a Manifest object from a file pointer to .cvmfspublished """ for line in manifest_file.readlines(): if len(line) == 0: continue if line[0:2] == "--": break self._read_line(line) self._check_validity() def __str__(self): return "<Manifest for " + self.repository_name + ">" def __repr__(self): return self.__str__() def _read_line(self, line): """ Parse lines that appear in .cvmfspublished """ key_char = line[0] data = line[1:-1] if key_char == "C": self.root_catalog = data elif key_char == "X": self.certificate = data elif key_char == "H": self.history_database = data elif key_char == "T": self.last_modified = datetime.datetime.fromtimestamp(int(data)) elif key_char == "R": self.root_hash = data elif key_char == "D": self.ttl = int(data) elif key_char == "S": self.revision = int(data) elif key_char == "N": self.repository_name = data elif key_char == "L": self.unknown_field1 = data # TODO: ask Jakob what L means else: raise UnknownManifestField(key_char) def _check_validity(self): """ Checks that all mandatory fields are found in .cvmfspublished """ if not hasattr(self, 'root_catalog'): raise ManifestValidityError("Manifest lacks a root catalog entry") if not hasattr(self, 'root_hash'): raise ManifestValidityError("Manifest lacks a root hash entry") if not hasattr(self, 'ttl'): raise ManifestValidityError("Manifest lacks a TTL entry") if not hasattr(self, 'revision'): raise ManifestValidityError("Manifest lacks a revision entry") if not hasattr(self, 'repository_name'): raise ManifestValidityError("Manifest lacks a repository name")
bsd-3-clause
Python
e044dceeb4f6dd91a1e29228cde7906a114f36ba
add ping-listener.py
it-forensics/forensics
src/ping-listener.py
src/ping-listener.py
#!/usr/bin/python # This tool is for educational use only! # Description: Listen on a networkinterface for incomming pings (ICMP packets) # and display this pings on the console # Requirements: scapy + root privileges import sys from scapy.all import * from pprint import * def printusage(): """ Prints usage information """ print "Usage: {0} <iface>".format(sys.argv[0]) print " ---> This tool is for educational use only! <---" if len(sys.argv) < 2: printusage() sys.exit(1) def icmp_callback(packet): # print the whole networkpacket object on the console # TODO: Optimize output... pprint(packet) sniff(prn=icmp_callback, filter="icmp", iface=sys.argv[1], store=0)
mit
Python
a2dd80d7bcd1096b554c43d085eabe1eb858fec8
Add code to create test data
berkeley-stat159/project-delta
code/make_test_data.py
code/make_test_data.py
from __future__ import absolute_import, division, print_function import nibabel as nib import numpy as np import os # Paths to directories containing the test subject's data path_data = "../data/ds005/testsub/" path_BOLD = path_data + "BOLD/task001_testrun/bold.nii.gz" path_behav = path_data + "behav/task001_testrun/behavdata.txt" # Create these directories os.makedirs(path_BOLD) os.makedirs(path_behav) # Give the BOLD data the identity affine for simplicity affine = np.eye(4) # The fMRI data consists of three volumes of shape (3, 3, 3) # Corner elements increase by 1 per unit time # Edge elements increase by 2 per unit time # Center of face elements increase by 3 per unit time # The center element increases by 4 per unit time data = np.array([[[[ 0, 1, 2], [ 1, 3, 5], [ 0, 1, 2]], [[ 1, 3, 5], [ 2, 5, 8], [ 1, 3, 5]], [[ 0, 1, 2], [ 1, 3, 5], [ 0, 1, 2]]], [[[ 1, 3, 5], [ 2, 5, 8], [ 1, 3, 5]], [[ 2, 5, 8], [ 3, 7, 11], [ 2, 5, 8]], [[ 1, 3, 5], [ 2, 5, 8], [ 1, 3, 5]]], [[[ 0, 1, 2], [ 1, 3, 5], [ 0, 1, 2]], [[ 1, 3, 5], [ 2, 5, 8], [ 1, 3, 5]], [[ 0, 1, 2], [ 1, 3, 5], [ 0, 1, 2]]]]) # BOLD.nii contains the above two elements BOLD = nib.nift1.NiftiImage(data, affine) nib.save(BOLD, path_BOLD) # The behavioral data consists of four rows: a row of headers, and one row for # each of three trials that occur at times 0.0, 2.0, and 4.0 behav = "onset\tgain\tloss\tPTval\trespnum\trespcat\tRT\n" behav = behav + "0.00\t10\t20\t-9.80\t4\t0\t1.077\n" behav = behav + "2.00\t20\t20\t0.20\t0\t-1\t0.000\n" behav = behav + "4.00\t30\t20\t10.20\t2\t1\t1.328" # Create behavdata.txt and open to write f = open(path_behav + "behavdata.txt") f.write(behav) f.close()
bsd-3-clause
Python
f2fb5fc41c78ac7722812aa1cdb54078bcbc70fe
Add Node test cases
kovacsbalu/coil,kovacsbalu/coil,tectronics/coil,marineam/coil,tectronics/coil,marineam/coil
coil/test/test_node.py
coil/test/test_node.py
"""Tests for coil.struct.Node""" import unittest from coil import errors from coil.struct import Node class BasicTestCase(unittest.TestCase): def testInit(self): r = Node() a = Node(r, "a") b = Node(a, "b") self.assertEquals(b.node_name, "b") self.assertEquals(b.node_path, "@root.a.b") self.assert_(b.container is a) self.assert_(b.tree_root is r) class PathTestCase(unittest.TestCase): def setUp(self): self.r = Node() self.a = Node(self.r, "a") self.b = Node(self.a, "b") def testRelative(self): self.assertEquals(self.r.relative_path("@root"), ".") self.assertEquals(self.r.relative_path("@root.a"), "a") self.assertEquals(self.r.relative_path("@root.a.b"), "a.b") self.assertEquals(self.r.relative_path("@root.a.b.c"), "a.b.c") self.assertEquals(self.a.relative_path("@root"), "..") self.assertEquals(self.a.relative_path("@root.a"), ".") self.assertEquals(self.a.relative_path("@root.a.b"), "b") self.assertEquals(self.a.relative_path("@root.a.b.c"), "b.c") self.assertEquals(self.b.relative_path("@root"), "...") self.assertEquals(self.b.relative_path("@root.a"), "..") self.assertEquals(self.b.relative_path("@root.a.b"), ".") self.assertEquals(self.b.relative_path("@root.a.b.c"), "c") self.assertEquals(self.b.relative_path("@root.x.y.z"), "...x.y.z") self.assertEquals(self.b.relative_path("@root.a.x.y"), "..x.y") def testAbsolute(self): self.assertEquals(self.r.absolute_path("."), "@root") self.assertEquals(self.r.absolute_path("a"), "@root.a") self.assertEquals(self.r.absolute_path(".a"), "@root.a") self.assertEquals(self.r.absolute_path("a.b"), "@root.a.b") self.assertEquals(self.b.absolute_path("."), "@root.a.b") self.assertEquals(self.b.absolute_path(".."), "@root.a") self.assertEquals(self.b.absolute_path("..."), "@root") self.assertEquals(self.b.absolute_path("x"), "@root.a.b.x") self.assertEquals(self.b.absolute_path(".x"), "@root.a.b.x") self.assertEquals(self.b.absolute_path("..x"), "@root.a.x") self.assertEquals(self.b.absolute_path("...x"), "@root.x") self.assertRaises(errors.CoilError, self.r.absolute_path, "..") self.assertRaises(errors.CoilError, self.a.absolute_path, "...") self.assertRaises(errors.CoilError, self.b.absolute_path, "....")
mit
Python
942b7c519a07a84c7f26077b78c23c60174e1141
Add VCF precalculator
geary/claslite,geary/claslite,geary/claslite,geary/claslite
scripts/precalc.py
scripts/precalc.py
# -*- coding: utf-8 -*- ''' Earth Engine precalculator for CLASlite Requires Python 2.6+ Public Domain where allowed, otherwise: Copyright 2010 Michael Geary - http://mg.to/ Use under MIT, GPL, or any Open Source license: http://www.opensource.org/licenses/ ''' import cgi, json, os, sys, time, urllib2 sys.path.append( os.path.abspath('../web/app') ) import private base = private.private['earth-engine-api'] auth = private.private['earth-engine-auth'] sat = 'LANDSAT/L7_L1T' bbox = '-61.6,-11.4,-60.8,-10.6' def fetch( api ): req = urllib2.Request( url = base + api, headers = { 'Authorization': 'GoogleLogin auth=' + auth } ) try: f = urllib2.urlopen( req, None, 600 ) data = f.read() f.close() return json.loads( data ) except urllib2.HTTPError, error: return error.read() def listImages( sat, bbox ): return fetch( 'list?id=%s&bbox=%s' %( sat, bbox ) )['data'] def calcVCF( id ): return fetch( vcfAPI(id) ) def vcfAPI( id ): return 'value?image={"creator":"CLASLITE/VCFAdjustedImage","args":[{"creator":"CLASLITE/AutoMCU","args":["%s",{"creator":"CLASLITE/Reflectance","args":[{"creator":"CLASLITE/Calibrate","args":["%s"]}]}]},"MOD44B_C4_TREE_2000"]}&fields=vcf_adjustment' %( id, id ) def main(): images = listImages( sat, bbox ) count = len(images) n = 0 for image in images: id = image['id'] n += 1 print 'Loading %d/%d: %s' %( n, count, id ) t = time.time() vcf = calcVCF( id ) t = time.time() - t report( vcf, t ) def report( vcf, t ): adjustment = vcf['data']['properties']['vcf_adjustment'] forest = adjustment['forest_pixel_count'] valid = adjustment['valid_pixel_count'] if valid > 0: percent = forest * 100 / valid else: percent = 0 print '%d seconds, %d%% forest' %( t, percent ) if __name__ == "__main__": main()
unlicense
Python
8b9a8f6443c1a5e184ececa4ec03baabca0973de
Add support for Pocket
foauth/foauth.org,foauth/foauth.org,foauth/oauth-proxy,foauth/foauth.org
services/pocket.py
services/pocket.py
from werkzeug.urls import url_decode import requests import foauth.providers class Pocket(foauth.providers.OAuth2): # General info about the provider provider_url = 'http://getpocket.com/' docs_url = 'http://getpocket.com/developer/docs/overview' category = 'News' # URLs to interact with the API request_token_url = 'https://getpocket.com/v3/oauth/request' authorize_url = 'https://getpocket.com/auth/authorize' access_token_url = 'https://getpocket.com/v3/oauth/authorize' api_domain = 'getpocket.com' available_permissions = [ (None, 'access your saved articles'), ] supports_state = False def get_authorize_params(self, redirect_uri, scopes): params = super(Pocket, self).get_authorize_params(redirect_uri, scopes) r = requests.post(self.request_token_url, data={ 'consumer_key': params['client_id'], 'redirect_uri': redirect_uri, }) data = url_decode(r.content) redirect_uri = '%s&code=%s' % (params['redirect_uri'], data['code']) return { 'request_token': data['code'], 'redirect_uri': redirect_uri, } def get_access_token_response(self, redirect_uri, data): return requests.post(self.get_access_token_url(), { 'consumer_key': self.client_id, 'code': data['code'], 'redirect_uri': redirect_uri }) def parse_token(self, content): data = url_decode(content) data['service_user_id'] = data['username'] return data def bearer_type(self, token, r): r.prepare_url(r.url, {'consumer_key': self.client_id, 'access_token': token}) return r
bsd-3-clause
Python
8244d71a41032e41bd79741ec649fa78c6317efa
add mixins for tweaking smartmin behavior more easily
caktus/smartmin,nyaruka/smartmin,caktus/smartmin,nyaruka/smartmin,caktus/smartmin,nyaruka/smartmin,caktus/smartmin
smartmin/mixins.py
smartmin/mixins.py
# simple mixins that keep you from writing so much code class PassRequestToFormMixin(object): def get_form_kwargs(self): kwargs = super(PassRequestToFormMixin, self).get_form_kwargs() kwargs['request'] = self.request return kwargs
bsd-3-clause
Python
32dd2099f97add61cb31df7af796876a95695bb1
Add a sample permission plugin for illustrating the check on realm resources, related to #6211.
jun66j5/trac-ja,netjunki/trac-Pygit2,walty8/trac,jun66j5/trac-ja,walty8/trac,walty8/trac,jun66j5/trac-ja,walty8/trac,jun66j5/trac-ja,netjunki/trac-Pygit2,netjunki/trac-Pygit2
sample-plugins/public_wiki_policy.py
sample-plugins/public_wiki_policy.py
from fnmatch import fnmatchcase from trac.config import Option from trac.core import * from trac.perm import IPermissionPolicy class PublicWikiPolicy(Component): """Sample permission policy plugin illustrating how to check permission on realms. Don't forget to integrate that plugin in the appropriate place in the list of permission policies: {{{ [trac] permission_policies = PublicWikiPolicy, DefaultPermissionPolicy }}} Then you can configure which pages you want to make public: {{{ [public_wiki] view = Public* modify = PublicSandbox/* }}} """ implements(IPermissionPolicy) view = Option('public_wiki', 'view', 'Public*', """Case-sensitive glob pattern used for granting view permission on all Wiki pages matching it.""") modify = Option('public_wiki', 'modify', 'Public*', """Case-sensitive glob pattern used for granting modify permissions on all Wiki pages matching it.""") def check_permission(self, action, username, resource, perm): if resource: # fine-grained permission check if resource.realm == 'wiki': # wiki realm or resource if resource.id: # ... it's a resource if action == 'WIKI_VIEW': # (think 'VIEW' here) pattern = self.view else: pattern = self.modify if fnmatchcase(resource.id, pattern): return True else: # ... it's a realm return True # this policy ''may'' grant permissions on some wiki pages else: # coarse-grained permission check # # support for the legacy permission checks: no resource specified # and realm information in the action name itself. # if action.startswith('WIKI_'): return True # this policy ''may'' grant permissions on some wiki pages
bsd-3-clause
Python
1c39eb113be409ff304a675ef8a85e96a97b1d87
Add files via upload
EvanMPutnam/RIT_BrickHack_2017_3,EvanMPutnam/RIT_BrickHack_2017_3
basicTwitter.py
basicTwitter.py
''' RIT SPEX: Twitter posting basic. Basic python script for posting to twitter. Pre-Req: Python3 Tweepy library twitter Contributors: Evan Putnam Henry Yaeger John LeBrun Helen O'Connell ''' import tweepy #Tweet a picutre def tweetPicture(api ,picUrl): api.update_with_media(picUrl) #Tweet a post def tweetPost(api, postStr): api.update_status(postStr) def apiSetUp(conKey, conSec, accTok, accSec): ''' Sets up the api object. :param conKey: :param conSec: :param accTok: :param accSec: :return: ''' #Authenicates keys... auth = tweepy.OAuthHandler(conKey, conSec) auth.set_access_token(accTok, accSec) #Api object api = tweepy.API(auth) return api def main(): """ NOTE: Do not send code to others with the consumer keys and access tokens. It will allow them to access your twitter application. This program is simple. Enter 1 to post a twitter text post and 2 for an image post... :return: """ #REPLACE WITH CONSUMER KEYS conKey = "" conSec = "" #REPLACE WITH ACCESS TOKENS accTok = "" accSec = "" if conKey == "" or conSec == "" or accTok == "" or accSec == "": print("WARNING YOU HAVE NOT ENTERERED YOUR INFORMATION") #Authenicates keys... auth = tweepy.OAuthHandler(conKey, conSec) auth.set_access_token(accTok, accSec) #Api object api = tweepy.API(auth) print("Press and enter 1 to post a text tweet") print("Press and enter 2 to post an image tweet") option = int(input("Enter Option(1 or 2):")) if option == 1: post = (input("Enter Post:")) tweetPost(api, post) elif option == 2: print("Image must be in folder of program") imagePath = (input("Enter Image Path:")) tweetPicture(api,imagePath) if __name__ == '__main__': main()
mit
Python
eb170653e64c5a874a773dc37c99dccb4dd42608
Add tools.color module (#41, #36))
a5kin/hecate,a5kin/hecate
xentica/tools/color.py
xentica/tools/color.py
"""A collection of color conversion helpers.""" def hsv2rgb(hue, sat, val): """ Convert HSV color to RGB format. :param hue: Hue value [0, 1] :param sat: Saturation value [0, 1] :param val: Brightness value [0, 1] :returns: tuple (red, green, blue) """ raise NotImplementedError def rgb2hsv(red, green, blue): """ Convert RGB color to HSV format. :param red: Red value [0, 1] :param green: Green value [0, 1] :param blue: Blue value [0, 1] :returns: tuple (hue, sat, val) """ raise NotImplementedError def genome2rgb(genome): """ Convert genome bit value to RGB color. :param genome: Genome as integer (bit) sequence. :returns: tuple (red, green, blue) """ raise NotImplementedError
mit
Python
1d5f1576a5f92c1917fa29c457e4b7ad055f41ca
Add info for [email protected] (#5405)
EmreAtes/spack,matthiasdiener/spack,LLNL/spack,TheTimmy/spack,krafczyk/spack,LLNL/spack,EmreAtes/spack,lgarren/spack,skosukhin/spack,mfherbst/spack,EmreAtes/spack,tmerrick1/spack,matthiasdiener/spack,lgarren/spack,tmerrick1/spack,EmreAtes/spack,LLNL/spack,iulian787/spack,TheTimmy/spack,iulian787/spack,mfherbst/spack,lgarren/spack,tmerrick1/spack,TheTimmy/spack,krafczyk/spack,lgarren/spack,EmreAtes/spack,krafczyk/spack,TheTimmy/spack,skosukhin/spack,iulian787/spack,skosukhin/spack,tmerrick1/spack,krafczyk/spack,iulian787/spack,LLNL/spack,mfherbst/spack,mfherbst/spack,matthiasdiener/spack,skosukhin/spack,LLNL/spack,matthiasdiener/spack,skosukhin/spack,matthiasdiener/spack,TheTimmy/spack,iulian787/spack,tmerrick1/spack,krafczyk/spack,mfherbst/spack,lgarren/spack
var/spack/repos/builtin/packages/mono/package.py
var/spack/repos/builtin/packages/mono/package.py
############################################################################### # Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, [email protected], All rights reserved. # LLNL-CODE-647188 # # For details, see https://github.com/llnl/spack # Please also see the NOTICE and LICENSE files for our notice and the LGPL. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License (as # published by the Free Software Foundation) version 2.1, February 1999. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and # conditions of the GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ############################################################################## from spack import * class Mono(AutotoolsPackage): """Mono is a software platform designed to allow developers to easily create cross platform applications. It is an open source implementation of Microsoft's .NET Framework based on the ECMA standards for C# and the Common Language Runtime. """ homepage = "http://www.mono-project.com/" url = "https://download.mono-project.com/sources/mono/mono-5.0.1.1.tar.bz2" # /usr/share/.mono/keypairs needs to exist or be able to be # created, e.g. https://github.com/gentoo/dotnet/issues/6 variant('patch-folder-path', default=False, description='Point SpecialFolder.CommonApplicationData folder ' 'into Spack installation instead of /usr/share') # Spack's openssl interacts badly with mono's vendored # "boringssl", don't drag it in w/ cmake depends_on('cmake~openssl', type=('build')) depends_on('libiconv') depends_on('perl', type=('build')) version('5.4.0.167', '103c7a737632046a9e9a0b039d752ee1') version('5.0.1.1', '17692c7a797f95ee6f9a0987fda3d486') version('4.8.0.524', 'baeed5b8139a85ad7e291d402a4bcccb') def patch(self): if '+patch-folder-path' in self.spec: before = 'return "/usr/share";' after = 'return "{0}";'.format(self.prefix.share) f = 'mcs/class/corlib/System/Environment.cs' kwargs = {'ignore_absent': False, 'backup': True, 'string': True} filter_file(before, after, f, **kwargs) def configure_args(self): args = [] li = self.spec['libiconv'].prefix args.append('--with-libiconv-prefix={p}'.format(p=li)) return args
############################################################################### # Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, [email protected], All rights reserved. # LLNL-CODE-647188 # # For details, see https://github.com/llnl/spack # Please also see the NOTICE and LICENSE files for our notice and the LGPL. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License (as # published by the Free Software Foundation) version 2.1, February 1999. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and # conditions of the GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ############################################################################## from spack import * class Mono(AutotoolsPackage): """Mono is a software platform designed to allow developers to easily create cross platform applications. It is an open source implementation of Microsoft's .NET Framework based on the ECMA standards for C# and the Common Language Runtime. """ homepage = "http://www.mono-project.com/" url = "https://download.mono-project.com/sources/mono/mono-5.0.1.1.tar.bz2" # /usr/share/.mono/keypairs needs to exist or be able to be # created, e.g. https://github.com/gentoo/dotnet/issues/6 variant('patch-folder-path', default=False, description='Point SpecialFolder.CommonApplicationData folder ' 'into Spack installation instead of /usr/share') # Spack's openssl interacts badly with mono's vendored # "boringssl", don't drag it in w/ cmake depends_on('cmake~openssl', type=('build')) depends_on('libiconv') depends_on('perl', type=('build')) version('5.0.1.1', '17692c7a797f95ee6f9a0987fda3d486') version('4.8.0.524', 'baeed5b8139a85ad7e291d402a4bcccb') def patch(self): if '+patch-folder-path' in self.spec: before = 'return "/usr/share";' after = 'return "{0}";'.format(self.prefix.share) f = 'mcs/class/corlib/System/Environment.cs' kwargs = {'ignore_absent': False, 'backup': True, 'string': True} filter_file(before, after, f, **kwargs) def configure_args(self): args = [] li = self.spec['libiconv'].prefix args.append('--with-libiconv-prefix={p}'.format(p=li)) return args
lgpl-2.1
Python
d03edd6670c130925fa8b947ebde03f2026602c3
remove redundant verbose prints
xfxf/veyepar,yoe/veyepar,CarlFK/veyepar,EricSchles/veyepar,EricSchles/veyepar,yoe/veyepar,yoe/veyepar,xfxf/veyepar,yoe/veyepar,xfxf/veyepar,CarlFK/veyepar,EricSchles/veyepar,yoe/veyepar,xfxf/veyepar,EricSchles/veyepar,CarlFK/veyepar,CarlFK/veyepar,xfxf/veyepar,EricSchles/veyepar,CarlFK/veyepar
dj/scripts/mk_public.py
dj/scripts/mk_public.py
#!/usr/bin/python # mk_public.py - flip state on hosts from private to public # private = not listed, can be seen if you know the url # the presenters have been emaild the URL, # they are encouraged to advertise it. # public = advertised, it is ready for the world to view. # It will be tweeted at @NextDayVideo from steve.richardapi import update_video, MissingRequiredData from steve.restapi import API, get_content import youtube_uploader import gdata.youtube from gdata.media import YOUTUBE_NAMESPACE from atom import ExtensionElement import atom import pw from process import process import pprint from main.models import Show, Location, Episode, Raw_File, Cut_List class mk_public(process): ready_state = 9 def up_richard(self, ep): host = pw.richard[ep.show.client.richard_id] endpoint = 'http://{hostname}/api/v1'.format(hostname=host['host']) api = API(endpoint) vid = ep.public_url.split('/video/')[1].split('/')[0] response = api.video(vid).get( username=host['user'], api_key=host['api_key']) video_data = get_content(response) video_data['state'] = 1 try: update_video(endpoint, host['user'], host['api_key'], vid, video_data) except MissingRequiredData, e: # this shouldn't happen, prolly debugging something. import code code.interact(local=locals()) return True def up_youtube(self, ep): uploader = youtube_uploader.Uploader() uploader.user = ep.show.client.youtube_id return uploader.set_permission( ep.host_url ) def process_ep(self, ep): # set youtube to public # set richard state to live ret = True # if something breaks, this will be false # don't make public if there is no host_url (youtube) if ep.public_url and ep.host_url: ret = ret and self.up_richard(ep) if self.options.verbose: print "Richard public." if ep.host_url: ret = ret and self.up_youtube(ep) if self.options.verbose: print "Youtube public." return ret if __name__ == '__main__': p=mk_public() p.main()
#!/usr/bin/python # mk_public.py - flip state on hosts from private to public # private = not listed, can be seen if you know the url # the presenters have been emaild the URL, # they are encouraged to advertise it. # public = advertised, it is ready for the world to view. # It will be tweeted at @NextDayVideo from steve.richardapi import update_video, MissingRequiredData from steve.restapi import API, get_content import youtube_uploader import gdata.youtube from gdata.media import YOUTUBE_NAMESPACE from atom import ExtensionElement import atom import pw from process import process import pprint from main.models import Show, Location, Episode, Raw_File, Cut_List class mk_public(process): ready_state = 9 def up_richard(self, ep): host = pw.richard[ep.show.client.richard_id] endpoint = 'http://{hostname}/api/v1'.format(hostname=host['host']) api = API(endpoint) vid = ep.public_url.split('/video/')[1].split('/')[0] response = api.video(vid).get( username=host['user'], api_key=host['api_key']) video_data = get_content(response) video_data['state'] = 1 try: update_video(endpoint, host['user'], host['api_key'], vid, video_data) except MissingRequiredData, e: # this shouldn't happen, prolly debugging something. import code code.interact(local=locals()) return True def up_youtube(self, ep): uploader = youtube_uploader.Uploader() uploader.user = ep.show.client.youtube_id return uploader.set_permission( ep.host_url ) def process_ep(self, ep): if self.options.verbose: print ep.id, ep.name # set youtube to public # set richard state to live ret = True # if something breaks, this will be false # don't make public if there is no host_url (youtube) if ep.public_url and ep.host_url: ret = ret and self.up_richard(ep) if self.options.verbose: print "Richard public." if ep.host_url: ret = ret and self.up_youtube(ep) if self.options.verbose: print "Youtube public." return ret if __name__ == '__main__': p=mk_public() p.main()
mit
Python
197fb6ec004c0bf47ec7e2fd25b75564a3ecf6c4
Add tests for logging of rest requests
RafaelPalomar/girder,manthey/girder,manthey/girder,Kitware/girder,girder/girder,kotfic/girder,jbeezley/girder,manthey/girder,Kitware/girder,data-exp-lab/girder,jbeezley/girder,data-exp-lab/girder,Kitware/girder,RafaelPalomar/girder,kotfic/girder,girder/girder,RafaelPalomar/girder,kotfic/girder,manthey/girder,RafaelPalomar/girder,data-exp-lab/girder,girder/girder,RafaelPalomar/girder,data-exp-lab/girder,girder/girder,kotfic/girder,data-exp-lab/girder,kotfic/girder,Kitware/girder,jbeezley/girder,jbeezley/girder
test/audit_logs/test_audit_log.py
test/audit_logs/test_audit_log.py
import datetime import pytest from girder import auditLogger @pytest.fixture def recordModel(): from girder.plugins.audit_logs import Record yield Record() @pytest.fixture def resetLog(): yield auditLogger for handler in auditLogger.handlers: auditLogger.removeHandler(handler) @pytest.mark.plugin('audit_logs') def testAnonymousRestRequestLogging(server, recordModel, resetLog): assert list(recordModel.find()) == [] server.request('/user/me') records = recordModel.find() assert records.count() == 1 record = records[0] assert record['ip'] == '127.0.0.1' assert record['type'] == 'rest.request' assert record['userId'] == None assert isinstance(record['when'], datetime.datetime) assert record['details']['method'] == 'GET' assert record['details']['status'] == 200 assert record['details']['route'] == ['user', 'me'] assert record['details']['params'] == {} @pytest.mark.plugin('audit_logs') def testFailedRestRequestLogging(server, recordModel, resetLog): server.request('/folder', method='POST', params={ 'name': 'Foo', 'parentId': 'foo' }) records = recordModel.find() assert records.count() == 1 details = records[0]['details'] assert details['method'] == 'POST' assert details['status'] == 401 assert details['route'] == ['folder'] assert details['params'] == { 'name': 'Foo', 'parentId': 'foo' } @pytest.mark.plugin('audit_logs') def testAuthenticatedRestRequestLogging(server, recordModel, resetLog, admin): server.request('/user/me', user=admin) records = recordModel.find() assert records.count() == 1 record = records[0] assert record['userId'] == admin['_id']
apache-2.0
Python
9e96a7ff9ad715f58d07341bd571e63ef233ffdb
Create fizzbuzz.py
vladshults/python_modules,vladshults/python_modules
job_interview_algs/fizzbuzz.py
job_interview_algs/fizzbuzz.py
#!/usr/bin/env python # -*- coding: UTF-8 -*- ''' Created on 24 02 2016 @author: vlad ''' def multiple_of_3(number): return number % 3 == 0 def multiple_of_5(number): return number % 5 == 0 for i in range(1, 100): if not multiple_of_3(i) and not multiple_of_5(i): print i continue if multiple_of_3(i) and multiple_of_5(i): print "fizzbuzz" continue else: print ["fizz", "buzz"][multiple_of_5(i)]
mit
Python
8089750d5dccadb0603068eefec869df4f8360cc
Add fizzbuzz.py in strings folder
keon/algorithms,amaozhao/algorithms
strings/fizzbuzz.py
strings/fizzbuzz.py
""" Wtite a function that returns an array containing the numbers from 1 to N, where N is the parametered value. N will never be less than 1. Replace certain values however if any of the following conditions are met: If the value is a multiple of 3: use the value 'Fizz' instead If the value is a multiple of 5: use the value 'Buzz' instead If the value is a multiple of 3 & 5: use the value 'FizzBuzz' instead """ """ There is no fancy algorithm to solve fizz buzz. Iterate from 1 through n Use the mod operator to determine if the current iteration is divisible by: 3 and 5 -> 'FizzBuzz' 3 -> 'Fizz' 5 -> 'Buzz' else -> string of current iteration return the results Complexity: Time: O(n) Space: O(n) """ def fizzbuzz(n): # Validate the input if n < 1: raise ValueError('n cannot be less than one') if n is None: raise TypeError('n cannot be None') result = [] for i in range(1, n+1): if i%3 == 0 and i%5 == 0: result.append('FizzBuzz') elif i%3 == 0: result.append('Fizz') elif i%5 == 0: result.append('Buzz') else: result.append(i) return result # Alternative solution def fizzbuzz_with_helper_func(n): return [fb(m) for m in range(1,n+1)] def fb(m): r = (m % 3 == 0) * "Fizz" + (m % 5 == 0) * "Buzz" return r if r != "" else m
mit
Python
9ea3c14983c7b2e32132f1ffe6bbbe7b4d19000c
Add Flyweight.py
MoriokaReimen/DesignPattern,MoriokaReimen/DesignPattern
Python/Flyweight/Flyweight.py
Python/Flyweight/Flyweight.py
#! /usr/bin/python # -*- coding: utf-8 -*- ''' Flyweight Pattern Author: Kei Nakata Data: Oct.14.2014 ''' class FlyweightFactory(object): def __init__(self): self.instances = dict() def getInstance(self, a, b): if (a, b) not in self.instances: self.instances[(a,b)] = Flyweight(a, b) return self.instances[(a, b)] class Flyweight(object): def __init__(self, a, b): self.a = a self.b = b def method(self): print self.a, self.b if __name__ == '__main__': factory = FlyweightFactory() a = factory.getInstance(1, 2) b = factory.getInstance(3, 2) c = factory.getInstance(1, 2) a.method() b.method() c.method() print id(a) print id(b) print id(c)
mit
Python
868a771e0ba049edd55ddf38db852c4d34824297
Add pod env tests
polyaxon/polyaxon,polyaxon/polyaxon,polyaxon/polyaxon
tests/test_spawner/test_pod_environment.py
tests/test_spawner/test_pod_environment.py
from unittest import TestCase from scheduler.spawners.templates.pod_environment import ( get_affinity, get_node_selector, get_tolerations ) class TestPodEnvironment(TestCase): def test_pod_affinity(self): assert get_affinity(None, None) is None assert get_affinity({'foo': 'bar'}, None) == {'foo': 'bar'} assert get_affinity(None, '{"foo": "bar"}') == {'foo': 'bar'} assert get_affinity({'foo': 'bar'}, '{"foo": "moo"}') == {'foo': 'bar'} def get_pod_node_selector(self): assert get_node_selector(None, None) is None assert get_node_selector({'foo': 'bar'}, None) == {'foo': 'bar'} assert get_node_selector(None, '{"foo": "bar"}') == {'foo': 'bar'} assert get_node_selector({'foo': 'bar'}, '{"foo": "moo"}') == {'foo': 'bar'} def get_pod_tolerations(self): assert get_tolerations(None, None) is None assert get_tolerations([{'foo': 'bar'}], None) == [{'foo': 'bar'}] assert get_tolerations(None, '[{"foo": "bar"}]') == [{'foo': 'bar'}] assert get_tolerations([{'foo': 'bar'}], '[{"foo": "moo"}]') == {'foo': 'bar'}
apache-2.0
Python
1c1e933fa9c6af1aa9d73f276ac7b79c2b86bdc3
add svn-clean-external-file.py
peutipoix/dotfiles,peutipoix/dotfiles
scripts/svn-clean-external-file.py
scripts/svn-clean-external-file.py
# written by Thomas Watnedal # http://stackoverflow.com/questions/239340/automatically-remove-subversion-unversioned-files import os import re def removeall(path): if not os.path.isdir(path): os.remove(path) return files=os.listdir(path) for x in files: fullpath=os.path.join(path, x) if os.path.isfile(fullpath): os.remove(fullpath) elif os.path.isdir(fullpath): removeall(fullpath) os.rmdir(path) unversionedRex = re.compile('^ ?[\?ID] *[1-9 ]*[a-zA-Z]* +(.*)') for l in os.popen('svn status --no-ignore -v').readlines(): match = unversionedRex.match(l) if match: removeall(match.group(1))
unlicense
Python
3ef1e39d476a8b3e41ff0b06dcd6f700c083682d
Add an ABC for all sub classes of `DataController`
MaT1g3R/Roboragi
data_controller/abc.py
data_controller/abc.py
from typing import Dict, Optional from data_controller.enums import Medium, Site from utils.helpers import await_func class DataController: """ An ABC for all classes that deals with database read write. """ __slots__ = () def get_identifier(self, query: str, medium: Medium) -> Optional[Dict[Site, str]]: """ Get the identifier of a given search query. :param query: the search query. :param medium: the medium type. :return: A dict of all identifiers for this search query for all sites, None if nothing is found. """ raise NotImplementedError def set_identifier(self, name: str, medium: Medium, site: Site, identifier: str): """ Set the identifier for a given name. :param name: the name. :param medium: the medium type. :param site: the site. :param identifier: the identifier. """ raise NotImplementedError def get_mal_title(self, id_: str, medium: Medium) -> Optional[str]: """ Get a MAL title by its id. :param id_: th MAL id. :param medium: the medium type. :return: The MAL title if it's found. """ raise NotImplementedError def set_mal_title(self, id_: str, medium: Medium, title: str): """ Set the MAL title for a given id. :param id_: the MAL id. :param medium: The medium type. :param title: The MAL title for the given id. """ raise NotImplementedError def medium_data_by_id(self, id_: str, medium: Medium, site: Site) -> Optional[dict]: """ Get data by id. :param id_: the id. :param medium: the medium type. :param site: the site. :return: the data for that id if found. """ raise NotImplementedError def set_medium_data(self, id_: str, medium: Medium, site: Site, data: dict): """ Set the data for a given id. :param id_: the id. :param medium: the medium type. :param site: the site. :param data: the data for the id. """ raise NotImplementedError async def get_medium_data(self, query: str, medium: Medium, loop=None) -> Optional[dict]: """ Get the cached data for the given search query. :param query: the search query. :param medium: the medium type. :param loop: the asyncio event loop, optional. If None is provided, will use the default event loop. :return: the cached data, for all sites that has the data. """ id_dict = await await_func( self.get_identifier, loop, query, medium ) if not id_dict: return return {site: data for site, data in { site: await await_func(self.medium_data_by_id, loop, id_, medium, site) for site, id_ in id_dict.items()}.items() if data}
mit
Python
2ce67897ade1ce8ae8b0fd00671fe61f4164a2bc
Add missing migration
mikkokeskinen/tunnistamo,mikkokeskinen/tunnistamo
oidc_apis/migrations/0002_add_multiselect_field_ad_groups_option.py
oidc_apis/migrations/0002_add_multiselect_field_ad_groups_option.py
# Generated by Django 2.0.9 on 2018-10-15 08:08 from django.db import migrations import multiselectfield.db.fields class Migration(migrations.Migration): dependencies = [ ('oidc_apis', '0001_initial'), ] operations = [ migrations.AlterField( model_name='api', name='required_scopes', field=multiselectfield.db.fields.MultiSelectField(blank=True, choices=[('email', 'E-mail'), ('profile', 'Profile'), ('address', 'Address'), ('github_username', 'GitHub username'), ('ad_groups', 'AD Groups')], help_text='Select the scopes that this API needs information from. Information from the selected scopes will be included to the API Tokens.', max_length=1000, verbose_name='required scopes'), ), ]
mit
Python
785a5767ee3482fddee37327b4bf3edeed94ff46
Add shootout attempt item definition
leaffan/pynhldb
db/shootout_attempt.py
db/shootout_attempt.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import uuid from db.common import Base from db.specific_event import SpecificEvent from db.player import Player from db.team import Team class ShootoutAttempt(Base, SpecificEvent): __tablename__ = 'shootout_attempts' __autoload__ = True STANDARD_ATTRS = [ "team_id", "player_id", "zone", "goalie_team_id", "goalie_id", "attempt_type", "shot_type", "miss_type", "distance", "on_goal", "scored" ] def __init__(self, event_id, data_dict): self.shootout_attempt_id = uuid.uuid4().urn self.event_id = event_id for attr in self.STANDARD_ATTRS: if attr in data_dict: setattr(self, attr, data_dict[attr]) else: if attr in ['scored', 'on_goal']: setattr(self, attr, False) else: setattr(self, attr, None) def __str__(self): player = Player.find_by_id(self.player_id) goalie = Player.find_by_id(self.goalie_id) plr_team = Team.find_by_id(self.team_id) goalie_team = Team.find_by_id(self.goalie_team_id) if self.attempt_type == 'GOAL': return "Shootout Goal: %s (%s) %s, %d ft. vs. %s (%s)" % ( player.name, plr_team.abbr, self.shot_type, self.distance, goalie.name, goalie_team.abbr) elif self.attempt_type == 'MISS': return "Shootout Miss: %s (%s) %s, %d ft., %s vs. %s (%s)" % ( player.name, plr_team.abbr, self.shot_type, self.distance, self.miss_type, goalie.name, goalie_team.abbr) elif self.attempt_type == 'SHOT': return "Shootout Shot: %s (%s) %s, %d ft. vs. %s (%s)" % ( player.name, plr_team.abbr, self.shot_type, self.distance, goalie.name, goalie_team.abbr)
mit
Python
1dcf698a286dcdf0f2c5a70d3e9bb2b32d046604
add TestBEvents, currently skipped
alphatwirl/alphatwirl,TaiSakuma/AlphaTwirl,TaiSakuma/AlphaTwirl,alphatwirl/alphatwirl,alphatwirl/alphatwirl,alphatwirl/alphatwirl
tests/unit/Events/test_BEvents.py
tests/unit/Events/test_BEvents.py
from AlphaTwirl.Events import BEvents as Events from AlphaTwirl.Events import Branch import unittest import ROOT ##____________________________________________________________________________|| inputPath = '/Users/sakuma/work/cms/c150130_RA1_data/c150130_01_PHYS14/20150331_SingleMu/TTJets/treeProducerSusyAlphaT/tree.root' treeName = 'tree' ##____________________________________________________________________________|| @unittest.skip("skip BEvents") class TestBEvents(unittest.TestCase): def test_branch(self): inputFile = ROOT.TFile.Open(inputPath) tree = inputFile.Get(treeName) events = Events(tree) jet_pt = events.jet_pt met_pt = events.met_pt self.assertIsInstance(jet_pt, Branch) self.assertIsInstance(met_pt, Branch) self.assertEqual(0, len(jet_pt)) self.assertEqual(1, len(met_pt)) self.assertEqual(0.0, met_pt[0]) tree.GetEntry(0) self.assertEqual(2, len(jet_pt)) self.assertEqual(1, len(met_pt)) self.assertEqual(124.55626678466797, jet_pt[0]) self.assertEqual(86.90544128417969, jet_pt[1]) self.assertAlmostEqual(43.783382415771484, met_pt[0]) tree.GetEntry(1) self.assertEqual(3, len(jet_pt)) self.assertEqual(1, len(met_pt)) self.assertEqual(112.48554992675781, jet_pt[0]) self.assertEqual(52.32780075073242, jet_pt[1]) self.assertEqual(48.861289978027344, jet_pt[2]) self.assertAlmostEqual(20.483951568603516, met_pt[0]) ##____________________________________________________________________________||
bsd-3-clause
Python
05a8129787d32bb605fee9b85c1c11e8c582c43e
Add messages utility tests
Brickstertwo/git-commands
tests/unit/utils/test_messages.py
tests/unit/utils/test_messages.py
import mock import sys import unittest from bin.commands.utils import messages class TestMessages(unittest.TestCase): def setUp(self): # store private methods so they can be restored after tests that mock them self._print = messages._print def tearDown(self): messages._print = self._print @mock.patch('__builtin__.print') def test__print(self, mock_print): # given message = 'message' prefix = 'a prefix:' quiet = False exit_ = False file_ = sys.stdout # then messages._print(message, prefix, quiet, exit_, file_) # then mock_print.assert_called_once_with(prefix + ' ' + message, file=file_) @mock.patch('__builtin__.print') def test__print_quiet(self, mock_print): # given message = 'message' prefix = 'a prefix:' quiet = True exit_ = False file_ = sys.stdout # then messages._print(message, prefix, quiet, exit_, file_) # then mock_print.assert_not_called() @mock.patch('__builtin__.print') def test__print_andExit(self, mock_print): # given message = 'message' prefix = 'a prefix:' quiet = False exit_ = True file_ = sys.stdout # then try: messages._print(message, prefix, quiet, exit_, file_) self.fail('expected to exit but did not') # pragma: no cover except SystemExit: pass # then mock_print.assert_called_once_with(prefix + ' ' + message, file=file_) def test__print_messageNotAStr(self): # when with self.assertRaises(AssertionError) as context: messages._print(123) # then self.assertEqual(context.exception.message, 'message must be a str') def test__print_prefixNotAStr(self): # when with self.assertRaises(AssertionError) as context: messages._print('message', prefix=123) # then self.assertEqual(context.exception.message, 'prefix must be a str') def test__print_quietNotABool(self): # when with self.assertRaises(AssertionError) as context: messages._print('message', quiet='false') # then self.assertEqual(context.exception.message, 'quiet must be a bool') def test__print_exitNotABool(self): # when with self.assertRaises(AssertionError) as context: messages._print('message', exit_='false') # then self.assertEqual(context.exception.message, 'exit must be a bool') @mock.patch('bin.commands.utils.messages._print') def test_error(self, mock_print): # given message = 'the message' prefix = 'error prefix' exit_ = False # when messages.error(message, prefix=prefix, exit_=exit_) # then mock_print.assert_called_once_with(message, prefix=prefix, exit_=exit_, file_=sys.stderr) @mock.patch('bin.commands.utils.messages._print') def test_warn(self, mock_print): # given message = 'the message' # when messages.warn(message) # then mock_print.assert_called_once_with(message, prefix='warn:') @mock.patch('bin.commands.utils.messages._print') def test_usage(self, mock_print): # given message = 'the message' # when messages.usage(message) # then mock_print.assert_called_once_with(message, prefix='usage:') @mock.patch('bin.commands.utils.messages._print') def test_info(self, mock_print): # given message = 'the message' quiet = True # when messages.info(message, quiet) # then mock_print.assert_called_once_with(message, quiet=quiet)
mit
Python
adf65027521124ea89e9c6c5ee2baf7366b2da46
Add example settings file for makam extractors
MTG/pycompmusic
compmusic/extractors/makam/settings.example.py
compmusic/extractors/makam/settings.example.py
token = "" # Dunya API Token
agpl-3.0
Python
9722bc3fc0a3cf8c95e91571b4b085e07e5a124c
Create 6kyu_message_from_aliens.py
Orange9000/Codewars,Orange9000/Codewars
Solutions/6kyu/6kyu_message_from_aliens.py
Solutions/6kyu/6kyu_message_from_aliens.py
import re from collections import Counter d={ '|-|':'h', '[-':'e', '()':'o', '3]':'b', '_|':'l', '|':'i', '^|':'p', '/`':'y', ')(':'o', '?/':'r', '\/':'a', '|\|':'n', '</':'k', '~|~':'t', '=/':'f', ')|':'d', '|_|':'u', '(':'c', '-[':'e', '~\_':'s', '-[':'e', ']3':'b', '_/~':'z', '/\\/\\':'w', '<>':'x', '/\\':'v', '|/\|':'m', '_)(':'q', 'T_':'j', ',_(':'g', '__':' ' } def decode(m): splitters=["]","}",".","'","+"] splitter=[i for i,j in Counter(m).most_common()][0] r=[] for f in re.split('('+re.escape(splitter)+')+', m[::-1]): try: r.append(d[f]) except: continue return ''.join(r)
mit
Python
125c75ea246c2d95f0addbb31b2d82dde588f21d
Add a unit test for KaggleKernelCredentials.
Kaggle/docker-python,Kaggle/docker-python
tests/test_kaggle_kernel_credentials.py
tests/test_kaggle_kernel_credentials.py
import unittest from kaggle_secrets import GcpTarget from kaggle_gcp import KaggleKernelCredentials class TestKaggleKernelCredentials(unittest.TestCase): def test_default_target(self): creds = KaggleKernelCredentials() self.assertEqual(GcpTarget.BIGQUERY, creds.target)
apache-2.0
Python
5e7f29a66e440e440b1f7a4848d17bb7ae01139b
Update from template.
ionelmc/python-nameless
ci/bootstrap.py
ci/bootstrap.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import, print_function, unicode_literals import os import sys from os.path import exists from os.path import join if __name__ == "__main__": base_path = join(".tox", "configure") if sys.platform == "win32": bin_path = join(base_path, "Scripts") else: bin_path = join(base_path, "bin") if not exists(base_path): import subprocess print("Bootstrapping ...") try: subprocess.check_call(["virtualenv", base_path]) except Exception: subprocess.check_call([sys.executable, "-m", "virtualenv", base_path]) print("Installing `jinja2` and `matrix` into bootstrap environment ...") subprocess.check_call([join(bin_path, "pip"), "install", "jinja2", "matrix"]) activate = join(bin_path, "activate_this.py") exec(compile(open(activate, "rb").read(), activate, "exec"), dict(__file__=activate)) import jinja2 import matrix jinja = jinja2.Environment( loader=jinja2.FileSystemLoader(join("ci", "templates")), trim_blocks=True, lstrip_blocks=True, keep_trailing_newline=True ) tox_environments = {} for (alias, conf) in matrix.from_file("setup.cfg").items(): python = conf["python_versions"] deps = conf["dependencies"] if "coverage_flags" in conf: cover = {"false": False, "true": True}[conf["coverage_flags"].lower()] if "environment_variables" in conf: env_vars = conf["environment_variables"] tox_environments[alias] = { "python": "python" + python if "py" not in python else python, "deps": deps.split(), } if "coverage_flags" in conf: tox_environments[alias].update(cover=cover) if "environment_variables" in conf: tox_environments[alias].update(env_vars=env_vars.split()) for name in os.listdir(join("ci", "templates")): with open(name, "w") as fh: fh.write(jinja.get_template(name).render(tox_environments=tox_environments)) print("Wrote {}".format(name)) print("DONE.")
bsd-2-clause
Python
db76495b4f41021e2613d79b6f5cb30c96fb4290
Add PriorityStore and PriorityItem
SanDisk-Open-Source/desmod,bgmerrell/desmod
desmod/prioritystore.py
desmod/prioritystore.py
from collections import namedtuple from heapq import heappush, heappop from simpy import Store class PriorityItem(namedtuple('PriorityItem', 'priority item')): def __lt__(self, other): return self.priority < other.priority class PriorityStore(Store): def _do_put(self, event): if len(self.items) < self._capacity: heappush(self.items, event.item) event.succeed() def _do_get(self, event): if self.items: event.succeed(heappop(self.items))
mit
Python
c74170968b3a200f17af083f027fe3b657cf6041
Add giveup function (#12)
singer-io/singer-python
singer/requests.py
singer/requests.py
def giveup_on_http_4xx_except_429(error): response = error.response if response is None: return False return not (response.status_code == 429 or response.status_code >= 500)
apache-2.0
Python
b59745e72a3c0a98da517f00e95fbafcff0cee3d
Remove unnecessary import.
lildadou/Flexget,lildadou/Flexget,lildadou/Flexget
tests/test_charts_snep_input.py
tests/test_charts_snep_input.py
from __future__ import unicode_literals, division, absolute_import from tests import FlexGetBase, use_vcr class TestChartsSnepInput(FlexGetBase): __yaml__ = """ tasks: test: charts_snep_input: radio """ @use_vcr def test_input(self): self.execute_task('test') assert len(self.task.entries) == 60, 'Produces %i entries, expected 60' % len(self.task.entries)
mit
Python
ce01cc61ea62c717503d991826e6b9915b23900b
Fix usage print
LeoTsui/6.858_lab,emzhang/6858lab2,darkmatter08/6858_labs_1_to_4,LeoTsui/6.858_lab,rychipman/858-labs,darkmatter08/6858_labs_1_to_4,rychipman/858-labs,rychipman/858-labs,darkmatter08/6858_labs_1_to_4,LeoTsui/6.858_lab,rychipman/858-labs,darkmatter08/6858_labs_1_to_4,emzhang/6858lab2,LeoTsui/6.858_lab,rychipman/858-labs,darkmatter08/6858_labs_1_to_4,emzhang/6858lab2,emzhang/6858lab2,LeoTsui/6.858_lab,emzhang/6858lab2
check-bugs.py
check-bugs.py
#!/usr/bin/python import sys import re import pprint import collections Head = collections.namedtuple("Head", "file line") def parse(pn): ans = collections.defaultdict(str) head = None for l in open(pn): # ignore comments if l.startswith("#"): continue # found a header m = re.match("^\[(\S+):(\d+)\]+.*", l) if m: head = Head._make(m.groups()) continue # collect descriptions if head: ans[head] += l # chomp return dict((h, d.strip()) for (h, d) in ans.items()) def say_pass(reason): print "\033[1;32mPASS\033[m", reason def say_fail(reason): print "\033[1;31mFAIL\033[m", reason def stat_summary(ans): print("Summary:") for (h, d) in ans.items(): desc = d.split("\n")[0] print(" %-8s %+4s | %-30s .." % (h.file, h.line, desc)) if len(ans) >= 5: say_pass("found enough bugs") else: say_fail("found %s bugs, but need at least 5" % len(ans)) if __name__ == "__main__": if len(sys.argv) != 2: print("usage: %s [bugs.txt]" % sys.argv[0]) exit(1) ans = parse(sys.argv[1]) stat_summary(ans)
#!/usr/bin/python import sys import re import pprint import collections Head = collections.namedtuple("Head", "file line") def parse(pn): ans = collections.defaultdict(str) head = None for l in open(pn): # ignore comments if l.startswith("#"): continue # found a header m = re.match("^\[(\S+):(\d+)\]+.*", l) if m: head = Head._make(m.groups()) continue # collect descriptions if head: ans[head] += l # chomp return dict((h, d.strip()) for (h, d) in ans.items()) def say_pass(reason): print "\033[1;32mPASS\033[m", reason def say_fail(reason): print "\033[1;31mFAIL\033[m", reason def stat_summary(ans): print("Summary:") for (h, d) in ans.items(): desc = d.split("\n")[0] print(" %-8s %+4s | %-30s .." % (h.file, h.line, desc)) if len(ans) >= 5: say_pass("found enough bugs") else: say_fail("found %s bugs, but need at least 5" % len(ans)) if __name__ == "__main__": if len(sys.argv) != 2: print("usage: %s [bugs.txt]", sys.argv[0]) exit(1) ans = parse(sys.argv[1]) stat_summary(ans)
mit
Python
d6fa7713556582bab54efc3ba53d27b411d8e23c
update import statements
Ezhil-Language-Foundation/open-tamil,atvKumar/open-tamil,atvKumar/open-tamil,atvKumar/open-tamil,Ezhil-Language-Foundation/open-tamil,arcturusannamalai/open-tamil,Ezhil-Language-Foundation/open-tamil,tuxnani/open-telugu,Ezhil-Language-Foundation/open-tamil,arcturusannamalai/open-tamil,tshrinivasan/open-tamil,tshrinivasan/open-tamil,tuxnani/open-telugu,Ezhil-Language-Foundation/open-tamil,tshrinivasan/open-tamil,tshrinivasan/open-tamil,arcturusannamalai/open-tamil,Ezhil-Language-Foundation/open-tamil,arcturusannamalai/open-tamil,tshrinivasan/open-tamil,atvKumar/open-tamil,arcturusannamalai/open-tamil,tshrinivasan/open-tamil,atvKumar/open-tamil,tuxnani/open-telugu,tshrinivasan/open-tamil,Ezhil-Language-Foundation/open-tamil,arcturusannamalai/open-tamil,atvKumar/open-tamil,Ezhil-Language-Foundation/open-tamil,tuxnani/open-telugu,atvKumar/open-tamil,arcturusannamalai/open-tamil,tuxnani/open-telugu,Ezhil-Language-Foundation/open-tamil
tamil/__init__.py
tamil/__init__.py
# -*- coding: utf-8 -*- # # (C) 2013 Muthiah Annamalai <[email protected]> # Library provides various encoding services for Tamil libraries # import utf8 import tscii import txt2unicode import txt2ipa def printchar( letters ): for c in letters: print(c, u"\\u%04x"%ord(c)) P = lambda x: u" ".join(x)
# -*- coding: utf-8 -*- # # (C) 2013 Muthiah Annamalai <[email protected]> # Library provides various encoding services for Tamil libraries # from . import utf8 from . import tscii from . import txt2unicode from . import txt2ipa def printchar( letters ): for c in letters: print(c, u"\\u%04x"%ord(c)) P = lambda x: u" ".join(x)
mit
Python
97a8c8c2baffdeaf6b710cf875d2f8641b999338
Create adapter_16mers.py
hackseq/2017_project_6,hackseq/2017_project_6,hackseq/2017_project_6,hackseq/2017_project_6
select_random_subset/adapter_16mers.py
select_random_subset/adapter_16mers.py
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Sat Oct 21 14:15:18 2017 @author: nikka.keivanfar """ #see also: adapters.fa P5 = 'AATGATACGGCGACCACCGA' P7 = 'CAAGCAGAAGACGGCATACGAGAT' read1 = 'GATCTACACTCTTTCCCTACACGACGCTC' read2 = 'GTGACTGGAGTTCAGACGTGT' adapters = [P5, P7, read1, read2] #to do: streamline loops for all adapters combined P5_kmers = {} P7_kmers = {} read1_kmers = {} read2_kmers = {} k = 16 #P5 16mers for i in range(len(P5) - k + 1): kmer = P5[i:i+k] if P5_kmers.has_key(kmer): P5_kmers[kmer] += 1 else: P5_kmers[kmer] = 1 for kmer, count in P5_kmers.items(): print kmer + "\t" + str(count) P5mers = set(kmer) #P7 16mers for i in range(len(P7) - k + 1): kmer = P7[i:i+k] if P7_kmers.has_key(kmer): P7_kmers[kmer] += 1 else: P7_kmers[kmer] = 1 for kmer, count in P7_kmers.items(): print kmer + "\t" + str(count) P7mers = set(kmer) #read1 16mers for i in range(len(read1) - k + 1): kmer = read1[i:i+k] if read1_kmers.has_key(kmer): read1_kmers[kmer] += 1 else: read1_kmers[kmer] = 1 for kmer, count in read1_kmers.items(): print kmer + "\t" + str(count) read1mers = set(kmer) #read2 16mers for i in range(len(read2) - k + 1): kmer = read2[i:i+k] if read2_kmers.has_key(kmer): read2_kmers[kmer] += 1 else: read2_kmers[kmer] = 1 for kmer, count in read2_kmers.items(): print kmer + "\t" + str(count) read2mers = set(kmer)
mit
Python
cfabe41b0d2f0cea143360fa1610baaaa87f8946
add python wrapper for network builder
Lemma1/MAC-POSTS,Lemma1/MAC-POSTS,Lemma1/MAC-POSTS,Lemma1/MAC-POSTS,Lemma1/MAC-POSTS,Lemma1/MAC-POSTS,Lemma1/MAC-POSTS
side_project/network_builder/MNM_nb.py
side_project/network_builder/MNM_nb.py
import os import numpy as np import networkx as nx DLINK_ENUM = ['CTM', 'LQ', 'LTM', 'PQ'] DNODE_ENUM = ['FWJ', 'GRJ', 'DMOND', 'DMDND'] class MNM_dlink(): def __init__(self): self.ID = None self.len = None self.typ = None self.ffs = None self.cap = None self.rhoj = None self.lanes = None def __init__(self, ID, length, typ, ffs, cap, rhoj, lanes): self.ID = ID self.length = length #mile self.typ = typ #type self.ffs = ffs #mile/h self.cap = cap #v/hour self.rhoj = rhoj #v/miles self.lanes = lanes #num of lanes def is_ok(self, unit_time = 5): assert(self.length > 0.0) assert(self.ffs > 0.0) assert(self.cap > 0.0) assert(self.rhoj > 0.0) assert(self.lanes > 0) assert(self.typ in DLINK_ENUM) assert(self.cap / self.ffs < self.rhoj) assert(unit_time * self.ffs / 3600 >= self.length) class MNM_dnode(): def __init__(self): self.ID = None self.typ = None def __init__(self, ID, typ): self.ID = ID self.typ = typ def is_ok(self): assert(self.typ in DNODE_ENUM) class MNM_demand(): def __init__(self): self.demand_dict = dict() def add_demand(self, O, D, demand, overwriting = False): assert(type(demand) is np.ndarray) assert(len(demand.shape) == 1) if O not in self.demand_dict.keys(): self.demand_dict[O] = dict() if (not overwriting) and (D in self.demand_dict[O].keys()): raise("Error, exists OD demand already") else: self.demand_dict[O][D] = demand class MNM_od(): def __init__(self): self.O_dict = dict() self.D_dict = dict() def add_origin(self, O, Onode_ID, overwriting = False): if (not overwriting) and (O in self.O_dict.keys()): raise("Error, exists origin node already") else: self.O_dict[O] = Onode_ID def add_destination(self, D, Dnode_ID, overwriting = False): if (not overwriting) and (D in self.D_dict.keys()): raise("Error, exists destination node already") else: self.D_dict[D] = Dnode_ID class MNM_graph(): def __init__(self): self.graph = nx.DiGraph() self.edgeID_dict = nx.DiGraph() def add_edge(self, s, e, ID, create_node = False, overwriting = False): if (not overwriting) and ((s,e) in self.graph.edges()): raise("Error, exists edge in graph") elif (not create_node) and s in self.graph.nodes(): raise("Error, exists start node of edge in graph") elif (not create_node) and e in self.graph.nodes(): raige("Error, exists end node of edge in graph") else: self.graph.add_edge(s, e, ID = ID) self.edgeID_dict[ID] = (s, e) def add_node(self, node, overwriting = True): if (not overwriting) and node in self.graph.nodes(): raise("Error, exists node in graph") else: self.graph.add_node(node) class MNM_routing(): def __init__(self): print "MNM_routing" class MNM_routing_fixed(MNM_routing): def __init__(self): super(MNM_routing_fixed, self).__init__() self.required_items = ['num_path', 'choice_portion', 'route_frq', 'path_table'] class MNM_routing_adaptive(MNM_routing): """docstring for MNM_routing_adaptive""" def __init__(self): super(MNM_routing_adaptive, self).__init__() self.required_items = ['route_frq'] class MNM_routing_hybrid(MNM_routing): """docstring for MNM_routing_hybrid""" def __init__(self): super(MNM_routing_hybrid, self).__init__() self.required_items = [] class MNM_config(): def __init__(self): print "MNM_config" class MNM_network_builder(): def __init__(self): print "Test"
mit
Python
ca043c2d3fe5fbdd37f372e8a3ad8bfd1b501c89
Correct Workitem._execute monkeypatch
bmya/odoo_addons,odoocn/odoo_addons,chadyred/odoo_addons,tiexinliu/odoo_addons,ovnicraft/odoo_addons,odoocn/odoo_addons,odoocn/odoo_addons,ovnicraft/odoo_addons,tiexinliu/odoo_addons,chadyred/odoo_addons,ovnicraft/odoo_addons,chadyred/odoo_addons,bmya/odoo_addons,bmya/odoo_addons,tiexinliu/odoo_addons
smile_action_rule/workflow/workitem.py
smile_action_rule/workflow/workitem.py
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2014 Smile (<http://www.smile.fr>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from openerp import registry from openerp.workflow.workitem import WorkflowItem native_execute = WorkflowItem._execute def new_execute(self, activity, stack): if not registry(self.session.cr.dbname).get('base.action.rule'): return native_execute(self, activity, stack) cr, uid, ids = self.session.cr, self.session.uid, [self.record.id] # Retrieve the action rules to possibly execute rule_obj = registry(self.session.cr.dbname)['base.action.rule'] rules = rule_obj._get_action_rules_on_wkf(cr, uid, activity['id']) # Check preconditions pre_ids = {} for rule in rules: if rule.kind not in ('on_create', 'on_create_or_write'): pre_ids[rule] = rule_obj._filter(cr, uid, rule, rule.filter_pre_id, ids) # Call original method result = native_execute(self, activity, stack) # Check postconditions, and execute actions on the records that satisfy them for rule in rules: if rule.kind != 'on_unlink': post_ids = rule_obj._filter(cr, uid, rule, rule.filter_id, pre_ids[rule]) else: post_ids = pre_ids[rule] if post_ids: rule_obj._process(cr, uid, rule, post_ids) return result WorkflowItem._execute = new_execute
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2014 Smile (<http://www.smile.fr>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from openerp import registry from openerp.workflow.workitem import WorkflowItem native_execute = WorkflowItem._execute def new_execute(self, activity, stack): cr, uid, ids = self.session.cr, self.session.uid, [self.record.id] # Retrieve the action rules to possibly execute rule_obj = registry(self.session.cr.dbname)['base.action.rule'] rules = rule_obj._get_action_rules_on_wkf(cr, uid, activity['id']) # Check preconditions pre_ids = {} for rule in rules: if rule.kind not in ('on_create', 'on_create_or_write'): pre_ids[rule] = rule_obj._filter(cr, uid, rule, rule.filter_pre_id, ids) # Call original method result = native_execute(self, activity, stack) # Check postconditions, and execute actions on the records that satisfy them for rule in rules: if rule.kind != 'on_unlink': post_ids = rule_obj._filter(cr, uid, rule, rule.filter_id, pre_ids[rule]) else: post_ids = pre_ids[rule] if post_ids: rule_obj._process(cr, uid, rule, post_ids) return result WorkflowItem._execute = new_execute
agpl-3.0
Python
107e33ab3982f3f7fb56a1a2ac2b0eec0b67091b
Use universal newlines in gyp_helper.
ondra-novak/chromium.src,anirudhSK/chromium,Jonekee/chromium.src,M4sse/chromium.src,hujiajie/pa-chromium,crosswalk-project/chromium-crosswalk-efl,Chilledheart/chromium,ondra-novak/chromium.src,jaruba/chromium.src,dushu1203/chromium.src,mohamed--abdel-maksoud/chromium.src,patrickm/chromium.src,Fireblend/chromium-crosswalk,ltilve/chromium,timopulkkinen/BubbleFish,hgl888/chromium-crosswalk-efl,ChromiumWebApps/chromium,zcbenz/cefode-chromium,krieger-od/nwjs_chromium.src,axinging/chromium-crosswalk,zcbenz/cefode-chromium,hgl888/chromium-crosswalk,zcbenz/cefode-chromium,anirudhSK/chromium,markYoungH/chromium.src,dednal/chromium.src,M4sse/chromium.src,anirudhSK/chromium,ltilve/chromium,Just-D/chromium-1,dushu1203/chromium.src,Jonekee/chromium.src,pozdnyakov/chromium-crosswalk,markYoungH/chromium.src,littlstar/chromium.src,Pluto-tv/chromium-crosswalk,hujiajie/pa-chromium,littlstar/chromium.src,mogoweb/chromium-crosswalk,dushu1203/chromium.src,jaruba/chromium.src,krieger-od/nwjs_chromium.src,ltilve/chromium,hujiajie/pa-chromium,markYoungH/chromium.src,hujiajie/pa-chromium,TheTypoMaster/chromium-crosswalk,dednal/chromium.src,zcbenz/cefode-chromium,bright-sparks/chromium-spacewalk,Pluto-tv/chromium-crosswalk,Fireblend/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,ondra-novak/chromium.src,fujunwei/chromium-crosswalk,hujiajie/pa-chromium,ChromiumWebApps/chromium,PeterWangIntel/chromium-crosswalk,bright-sparks/chromium-spacewalk,mohamed--abdel-maksoud/chromium.src,chuan9/chromium-crosswalk,anirudhSK/chromium,zcbenz/cefode-chromium,dednal/chromium.src,zcbenz/cefode-chromium,pozdnyakov/chromium-crosswalk,nacl-webkit/chrome_deps,dednal/chromium.src,TheTypoMaster/chromium-crosswalk,anirudhSK/chromium,bright-sparks/chromium-spacewalk,axinging/chromium-crosswalk,hujiajie/pa-chromium,axinging/chromium-crosswalk,mogoweb/chromium-crosswalk,Jonekee/chromium.src,hgl888/chromium-crosswalk,anirudhSK/chromium,krieger-od/nwjs_chromium.src,dushu1203/chromium.src,hgl888/chromium-crosswalk,hgl888/chromium-crosswalk,anirudhSK/chromium,littlstar/chromium.src,jaruba/chromium.src,mohamed--abdel-maksoud/chromium.src,Chilledheart/chromium,dednal/chromium.src,M4sse/chromium.src,zcbenz/cefode-chromium,markYoungH/chromium.src,TheTypoMaster/chromium-crosswalk,timopulkkinen/BubbleFish,dednal/chromium.src,mohamed--abdel-maksoud/chromium.src,mogoweb/chromium-crosswalk,zcbenz/cefode-chromium,jaruba/chromium.src,markYoungH/chromium.src,nacl-webkit/chrome_deps,M4sse/chromium.src,anirudhSK/chromium,PeterWangIntel/chromium-crosswalk,mogoweb/chromium-crosswalk,M4sse/chromium.src,bright-sparks/chromium-spacewalk,M4sse/chromium.src,Jonekee/chromium.src,M4sse/chromium.src,markYoungH/chromium.src,nacl-webkit/chrome_deps,mohamed--abdel-maksoud/chromium.src,axinging/chromium-crosswalk,fujunwei/chromium-crosswalk,ondra-novak/chromium.src,mohamed--abdel-maksoud/chromium.src,ChromiumWebApps/chromium,ChromiumWebApps/chromium,hgl888/chromium-crosswalk-efl,Jonekee/chromium.src,ChromiumWebApps/chromium,ChromiumWebApps/chromium,patrickm/chromium.src,TheTypoMaster/chromium-crosswalk,M4sse/chromium.src,M4sse/chromium.src,Fireblend/chromium-crosswalk,krieger-od/nwjs_chromium.src,krieger-od/nwjs_chromium.src,mogoweb/chromium-crosswalk,Fireblend/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,anirudhSK/chromium,mogoweb/chromium-crosswalk,Chilledheart/chromium,zcbenz/cefode-chromium,ChromiumWebApps/chromium,pozdnyakov/chromium-crosswalk,jaruba/chromium.src,fujunwei/chromium-crosswalk,mogoweb/chromium-crosswalk,dednal/chromium.src,anirudhSK/chromium,pozdnyakov/chromium-crosswalk,chuan9/chromium-crosswalk,hgl888/chromium-crosswalk,Fireblend/chromium-crosswalk,ltilve/chromium,fujunwei/chromium-crosswalk,ondra-novak/chromium.src,ondra-novak/chromium.src,Chilledheart/chromium,patrickm/chromium.src,Just-D/chromium-1,ltilve/chromium,hujiajie/pa-chromium,krieger-od/nwjs_chromium.src,littlstar/chromium.src,dushu1203/chromium.src,ChromiumWebApps/chromium,pozdnyakov/chromium-crosswalk,timopulkkinen/BubbleFish,nacl-webkit/chrome_deps,chuan9/chromium-crosswalk,timopulkkinen/BubbleFish,nacl-webkit/chrome_deps,ltilve/chromium,M4sse/chromium.src,bright-sparks/chromium-spacewalk,zcbenz/cefode-chromium,PeterWangIntel/chromium-crosswalk,nacl-webkit/chrome_deps,hujiajie/pa-chromium,dednal/chromium.src,jaruba/chromium.src,anirudhSK/chromium,Jonekee/chromium.src,patrickm/chromium.src,timopulkkinen/BubbleFish,chuan9/chromium-crosswalk,Chilledheart/chromium,TheTypoMaster/chromium-crosswalk,hgl888/chromium-crosswalk,krieger-od/nwjs_chromium.src,hgl888/chromium-crosswalk-efl,crosswalk-project/chromium-crosswalk-efl,dushu1203/chromium.src,bright-sparks/chromium-spacewalk,nacl-webkit/chrome_deps,hgl888/chromium-crosswalk-efl,Pluto-tv/chromium-crosswalk,chuan9/chromium-crosswalk,hgl888/chromium-crosswalk-efl,TheTypoMaster/chromium-crosswalk,krieger-od/nwjs_chromium.src,patrickm/chromium.src,chuan9/chromium-crosswalk,hgl888/chromium-crosswalk-efl,bright-sparks/chromium-spacewalk,PeterWangIntel/chromium-crosswalk,hgl888/chromium-crosswalk,jaruba/chromium.src,PeterWangIntel/chromium-crosswalk,axinging/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,Just-D/chromium-1,zcbenz/cefode-chromium,mogoweb/chromium-crosswalk,markYoungH/chromium.src,Chilledheart/chromium,patrickm/chromium.src,pozdnyakov/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,timopulkkinen/BubbleFish,hgl888/chromium-crosswalk-efl,hgl888/chromium-crosswalk-efl,Fireblend/chromium-crosswalk,ltilve/chromium,Jonekee/chromium.src,fujunwei/chromium-crosswalk,nacl-webkit/chrome_deps,littlstar/chromium.src,axinging/chromium-crosswalk,timopulkkinen/BubbleFish,mohamed--abdel-maksoud/chromium.src,PeterWangIntel/chromium-crosswalk,Just-D/chromium-1,nacl-webkit/chrome_deps,axinging/chromium-crosswalk,Pluto-tv/chromium-crosswalk,Jonekee/chromium.src,dushu1203/chromium.src,mohamed--abdel-maksoud/chromium.src,Just-D/chromium-1,Pluto-tv/chromium-crosswalk,jaruba/chromium.src,Pluto-tv/chromium-crosswalk,hgl888/chromium-crosswalk-efl,Pluto-tv/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,ltilve/chromium,ondra-novak/chromium.src,Just-D/chromium-1,pozdnyakov/chromium-crosswalk,Fireblend/chromium-crosswalk,krieger-od/nwjs_chromium.src,ondra-novak/chromium.src,krieger-od/nwjs_chromium.src,Fireblend/chromium-crosswalk,hgl888/chromium-crosswalk,chuan9/chromium-crosswalk,dushu1203/chromium.src,markYoungH/chromium.src,Pluto-tv/chromium-crosswalk,dushu1203/chromium.src,timopulkkinen/BubbleFish,littlstar/chromium.src,mohamed--abdel-maksoud/chromium.src,M4sse/chromium.src,nacl-webkit/chrome_deps,timopulkkinen/BubbleFish,littlstar/chromium.src,Jonekee/chromium.src,hujiajie/pa-chromium,Just-D/chromium-1,anirudhSK/chromium,ChromiumWebApps/chromium,fujunwei/chromium-crosswalk,dushu1203/chromium.src,ChromiumWebApps/chromium,crosswalk-project/chromium-crosswalk-efl,hgl888/chromium-crosswalk-efl,patrickm/chromium.src,ondra-novak/chromium.src,mogoweb/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,Jonekee/chromium.src,pozdnyakov/chromium-crosswalk,timopulkkinen/BubbleFish,mogoweb/chromium-crosswalk,markYoungH/chromium.src,axinging/chromium-crosswalk,dushu1203/chromium.src,chuan9/chromium-crosswalk,dednal/chromium.src,axinging/chromium-crosswalk,fujunwei/chromium-crosswalk,Just-D/chromium-1,hujiajie/pa-chromium,hgl888/chromium-crosswalk,bright-sparks/chromium-spacewalk,pozdnyakov/chromium-crosswalk,Chilledheart/chromium,axinging/chromium-crosswalk,patrickm/chromium.src,markYoungH/chromium.src,mohamed--abdel-maksoud/chromium.src,Jonekee/chromium.src,Fireblend/chromium-crosswalk,jaruba/chromium.src,krieger-od/nwjs_chromium.src,PeterWangIntel/chromium-crosswalk,timopulkkinen/BubbleFish,jaruba/chromium.src,axinging/chromium-crosswalk,dednal/chromium.src,fujunwei/chromium-crosswalk,fujunwei/chromium-crosswalk,ChromiumWebApps/chromium,crosswalk-project/chromium-crosswalk-efl,PeterWangIntel/chromium-crosswalk,patrickm/chromium.src,Chilledheart/chromium,bright-sparks/chromium-spacewalk,PeterWangIntel/chromium-crosswalk,hujiajie/pa-chromium,pozdnyakov/chromium-crosswalk,Chilledheart/chromium,pozdnyakov/chromium-crosswalk,littlstar/chromium.src,jaruba/chromium.src,ChromiumWebApps/chromium,TheTypoMaster/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,Pluto-tv/chromium-crosswalk,chuan9/chromium-crosswalk,Just-D/chromium-1,ltilve/chromium,markYoungH/chromium.src,mohamed--abdel-maksoud/chromium.src,nacl-webkit/chrome_deps,dednal/chromium.src
build/gyp_helper.py
build/gyp_helper.py
# Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # This file helps gyp_chromium and landmines correctly set up the gyp # environment from chromium.gyp_env on disk import os SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__)) CHROME_SRC = os.path.dirname(SCRIPT_DIR) def apply_gyp_environment_from_file(file_path): """Reads in a *.gyp_env file and applies the valid keys to os.environ.""" if not os.path.exists(file_path): return with open(file_path, 'rU') as f: file_contents = f.read() try: file_data = eval(file_contents, {'__builtins__': None}, None) except SyntaxError, e: e.filename = os.path.abspath(file_path) raise supported_vars = ( 'CC', 'CHROMIUM_GYP_FILE', 'CHROMIUM_GYP_SYNTAX_CHECK', 'CXX', 'GYP_DEFINES', 'GYP_GENERATOR_FLAGS', 'GYP_GENERATOR_OUTPUT', 'GYP_GENERATORS', ) for var in supported_vars: file_val = file_data.get(var) if file_val: if var in os.environ: print 'INFO: Environment value for "%s" overrides value in %s.' % ( var, os.path.abspath(file_path) ) else: os.environ[var] = file_val def apply_chromium_gyp_env(): if 'SKIP_CHROMIUM_GYP_ENV' not in os.environ: # Update the environment based on chromium.gyp_env path = os.path.join(os.path.dirname(CHROME_SRC), 'chromium.gyp_env') apply_gyp_environment_from_file(path)
# Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # This file helps gyp_chromium and landmines correctly set up the gyp # environment from chromium.gyp_env on disk import os SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__)) CHROME_SRC = os.path.dirname(SCRIPT_DIR) def apply_gyp_environment_from_file(file_path): """Reads in a *.gyp_env file and applies the valid keys to os.environ.""" if not os.path.exists(file_path): return with open(file_path) as f: file_contents = f.read() try: file_data = eval(file_contents, {'__builtins__': None}, None) except SyntaxError, e: e.filename = os.path.abspath(file_path) raise supported_vars = ( 'CC', 'CHROMIUM_GYP_FILE', 'CHROMIUM_GYP_SYNTAX_CHECK', 'CXX', 'GYP_DEFINES', 'GYP_GENERATOR_FLAGS', 'GYP_GENERATOR_OUTPUT', 'GYP_GENERATORS', ) for var in supported_vars: file_val = file_data.get(var) if file_val: if var in os.environ: print 'INFO: Environment value for "%s" overrides value in %s.' % ( var, os.path.abspath(file_path) ) else: os.environ[var] = file_val def apply_chromium_gyp_env(): if 'SKIP_CHROMIUM_GYP_ENV' not in os.environ: # Update the environment based on chromium.gyp_env path = os.path.join(os.path.dirname(CHROME_SRC), 'chromium.gyp_env') apply_gyp_environment_from_file(path)
bsd-3-clause
Python
fbbaa3fc5b99eed88e039c232f129aaeab0a6f54
Bring table test coverage to 100%
caleb531/cache-simulator
tests/test_table.py
tests/test_table.py
#!/usr/bin/env python3 import nose.tools as nose from table import Table def test_init_default(): """should initialize table with required parameters and default values""" table = Table(num_cols=5, width=78) nose.assert_equal(table.num_cols, 5) nose.assert_equal(table.width, 78) nose.assert_equal(table.alignment, 'left') nose.assert_equal(table.title, None) nose.assert_equal(table.header, []) nose.assert_equal(table.rows, []) def test_init_optional(): """should initialize table with optional parameters if supplied""" table = Table(num_cols=5, width=78, alignment='right', title='Cache') nose.assert_equal(table.num_cols, 5) nose.assert_equal(table.width, 78) nose.assert_equal(table.alignment, 'right') nose.assert_equal(table.title, 'Cache') def test_get_separator(): """should return the correct ASCII separator string""" table = Table(num_cols=5, width=78) nose.assert_equal(table.get_separator(), '-' * 78) def test_str_title(): """should correctly display title""" table = Table(num_cols=5, width=12, title='Cache') nose.assert_regexp_matches( ''.join(('Cache'.center(12), '\n', ('-' * 12))), str(table)) def test_str_no_title(): """should not display title if not originally supplied""" table = Table(num_cols=5, width=12) nose.assert_equal(str(table).strip(), '') class TestAlignment(object): def _test_str_align(self, alignment, just): table_width = 16 num_cols = 2 col_width = table_width // num_cols table = Table( num_cols=num_cols, width=table_width, alignment=alignment) table.header = ['First', 'Last'] table.rows.append(['Bob', 'Smith']) table.rows.append(['John', 'Earl']) nose.assert_equal(str(table), '{}{}\n{}\n{}{}\n{}{}'.format( just('First', col_width), just('Last', col_width), '-' * table_width, just('Bob', col_width), just('Smith', col_width), just('John', col_width), just('Earl', col_width))) def test_str_align_left(self): """should correctly display table when left-aligned""" self._test_str_align( alignment='left', just=str.ljust) def test_str_align_center(self): """should correctly display table when center-aligned""" self._test_str_align( alignment='center', just=str.center) def test_str_align_right(self): """should correctly display table when right-aligned""" self._test_str_align( alignment='right', just=str.rjust)
mit
Python
f392a90ae12a5f9aab04b22e82d493d0f93db9fd
Add first test
9seconds/sshrc,9seconds/concierge
tests/test_utils.py
tests/test_utils.py
def test_ok(): assert True
mit
Python
e56a9781f4e7e8042c29c9e54966659c87c5c05c
Add a test for our more general views.
hello-base/web,hello-base/web,hello-base/web,hello-base/web
tests/test_views.py
tests/test_views.py
import pytest from django.core.urlresolvers import reverse def test_site_view(client): response = client.get(reverse('site-home')) assert response.status_code == 200 assert 'landings/home_site.html' in [template.name for template in response.templates]
apache-2.0
Python
675b7fc917b5f99120ca4d6dcb79b3e821dbe72a
add Olin specific script
corydolphin/mailman-downloader
downloadOlin.py
downloadOlin.py
import os from downloadMailmanArchives import main class Struct: def __init__(self, **entries): self.__dict__.update(entries) if __name__ == '__main__': args = { 'archive_root_url': ['https://lists.olin.edu/mailman/private/carpediem/', 'https://lists.olin.edu/mailman/private/helpme/'], 'password' : os.environ.get('ARCHIVE_LOGIN', "fail"), 'username' : os.environ.get('ARCHIVE_PASS', "fail"), 'force' : True, 'dest' : './archives' } main(Struct(**args))
mit
Python
a46f0a709747dbe90f0495e7e6b12c7b511baa7f
Delete duplicate wapp images
kingspp/Ubuntu-AIO,kingspp/Ubuntu-AIO
dupe_deleter.py
dupe_deleter.py
""" # Install QPython3 for android # https://github.com/qpython-android/qpython3/releases # Execute the below script in QPython3 """ import os, hashlib from operator import itemgetter from itertools import groupby image_list = [] folder_list = [r'/storage/emulated/0/whatsapp/media/whatsapp images/', r'/storage/emulated/0/whatsapp/media/whatsapp images/Sent'] for folder in folder_list: file_list = os.listdir(folder) for img_file in file_list: file_path = os.path.join(folder, img_file) if os.path.isfile(file_path): try: image_list.append([file_path, hashlib.sha1(open(file_path, 'rb').read()).hexdigest()]) except IOError: raise Exception('Error reading the file') image_list.sort(key=itemgetter(1)) groups = groupby(image_list, itemgetter(1)) for (img_hash, img_list_same_hash) in groups: z = [img for img in img_list_same_hash] i = 1 while i < len(z): os.remove(z[i][0]) print('Deleted ' + z[i][0]) i += 1
mit
Python
9f4452983e38d002e141ed0d2a9c865656a553ce
add todo stuff
Padavan/khren
main.py
main.py
#!/usr/bin/env python # __author__ = 'Dmitry Shihaleev' # __version__= '0.2' # __email__ = '[email protected]' # __license__ = 'MIT License'
mit
Python
ab7c0d05a6bcf8be83409ccd96f2ed4a6fe65a73
Create main.py
mosajjal/ircbackdoor
main.py
main.py
#!/usr/bin/env python3 import sys import socket import string HOST = "chat.freenode.net" # You can change this to whatever you want PORT = 6667 NICK = "Your Nick Name" IDENT = "Your Identity" REALNAME = "Your REAL Name" MASTER = "The Master of this particular Slave" CHANNEL = "The Channel To join" readbuffer = "" s = socket.socket() s.connect((HOST, PORT)) # sets the nickname inside IRC channel s.send(bytes("NICK %s\r\n" % NICK, "UTF-8")) # Connects to the server using the provided inforamtion above. The 'bla' is irrelevent s.send(bytes("USER %s %s bla :%s\r\n" % (IDENT, HOST, REALNAME), "UTF-8")) # Joins the Channel s.send(bytes("JOIN #%s \r\n" % (CHANNEL), "UTF-8")) # starts a conversation with the 'master' when joining s.send(bytes("PRIVMSG %s :Hello Master\r\n" % MASTER, "UTF-8")) while True: readbuffer = readbuffer+s.recv(1024).decode("UTF-8") temp = str.split(readbuffer, "\n") readbuffer = temp.pop() for line in temp: line = str.rstrip(line) line = str.split(line) if(line[0] == "PING"): s.send(bytes("PONG %s\r\n" % line[1], "UTF-8")) if(line[1] == "PRIVMSG"): sender = "" for char in line[0]: if(char == "!"): break if(char != ":"): sender += char size = len(line) i = 3 message = "" while(i < size): message += line[i] + " " i = i + 1 message.lstrip(":") s.send(bytes("PRIVMSG %s %s \r\n" % (sender, message), "UTF-8")) for index, i in enumerate(line): print(line[index])
mit
Python
12490fa92e54becca77c70d124d807b19d71afa1
Create main.py
paranut1/waypoint,paranut1/waypoint,paranut1/waypoint
main.py
main.py
# waypointviewer.py Waypoint Viewer Google Maps/Google AppEngine application # Copyright (C) 2011 Tom Payne # # 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/>. import json from google.appengine.api.urlfetch import fetch from google.appengine.ext import webapp from google.appengine.ext.webapp import template from google.appengine.ext.webapp.util import run_wsgi_app import os.path import waypoint class MainPage(webapp.RequestHandler): def get(self): template_values = dict((key, self.request.get(key)) for key in ('kml', 'logo', 'tsk', 'title', 'wpt')) path = os.path.join(os.path.dirname(__file__), 'templates', 'index.html') self.response.out.write(template.render(path, template_values)) class WaypointviewerJs(webapp.RequestHandler): def get(self): template_values = dict((key, self.request.get(key)) for key in ('kml', 'logo', 'tsk', 'wpt')) path = os.path.join(os.path.dirname(__file__), 'templates', 'waypointviewer.js') self.response.headers['content-type'] = 'text/javascript' self.response.out.write(template.render(path, template_values)) class Wpt2json(webapp.RequestHandler): def get(self): debug = self.request.get('debug') wpt = self.request.get('wpt') response = fetch(wpt) content = response.content.decode('latin_1') feature_collection = waypoint.feature_collection(content.splitlines(), debug=debug) if debug: feature_collection_properties['content'] = content feature_collection_properties['content_was_truncated'] = response.content_was_truncated feature_collection_properties['final_url'] = response.final_url headers = dict((key, response.headers[key]) for key in response.headers) feature_collection_properties['headers'] = headers feature_collection_properties['status_code'] = response.status_code keywords = {'indent': 4, 'sort_keys': True} else: keywords = {} self.response.headers['content-type'] = 'application/json' self.response.out.write(json.dumps(feature_collection, **keywords)) app = webapp.WSGIApplication([('/', MainPage), ('/waypointviewer.js', WaypointviewerJs), ('/wpt2json.json', Wpt2json)], debug=True) def main(): run_wsgi_app(app) if __name__ == '__main__': main()
agpl-3.0
Python
34847fbe0e04a2da8957a0ba5de92856ca73c8cc
Add missing migration
brianjgeiger/osf.io,mattclark/osf.io,aaxelb/osf.io,cslzchen/osf.io,baylee-d/osf.io,HalcyonChimera/osf.io,icereval/osf.io,laurenrevere/osf.io,leb2dg/osf.io,sloria/osf.io,baylee-d/osf.io,HalcyonChimera/osf.io,aaxelb/osf.io,caseyrollins/osf.io,adlius/osf.io,sloria/osf.io,mattclark/osf.io,sloria/osf.io,Johnetordoff/osf.io,felliott/osf.io,mfraezz/osf.io,icereval/osf.io,mattclark/osf.io,cslzchen/osf.io,adlius/osf.io,crcresearch/osf.io,erinspace/osf.io,cslzchen/osf.io,adlius/osf.io,binoculars/osf.io,laurenrevere/osf.io,Johnetordoff/osf.io,erinspace/osf.io,cslzchen/osf.io,mfraezz/osf.io,felliott/osf.io,saradbowman/osf.io,chennan47/osf.io,felliott/osf.io,CenterForOpenScience/osf.io,Johnetordoff/osf.io,TomBaxter/osf.io,CenterForOpenScience/osf.io,pattisdr/osf.io,HalcyonChimera/osf.io,laurenrevere/osf.io,pattisdr/osf.io,Johnetordoff/osf.io,mfraezz/osf.io,caseyrollins/osf.io,saradbowman/osf.io,chennan47/osf.io,CenterForOpenScience/osf.io,TomBaxter/osf.io,adlius/osf.io,crcresearch/osf.io,leb2dg/osf.io,icereval/osf.io,chennan47/osf.io,pattisdr/osf.io,brianjgeiger/osf.io,binoculars/osf.io,mfraezz/osf.io,binoculars/osf.io,HalcyonChimera/osf.io,baylee-d/osf.io,brianjgeiger/osf.io,crcresearch/osf.io,caseyrollins/osf.io,TomBaxter/osf.io,CenterForOpenScience/osf.io,brianjgeiger/osf.io,felliott/osf.io,aaxelb/osf.io,leb2dg/osf.io,aaxelb/osf.io,erinspace/osf.io,leb2dg/osf.io
osf/migrations/0054_auto_20170823_1555.py
osf/migrations/0054_auto_20170823_1555.py
# -*- coding: utf-8 -*- # Generated by Django 1.11.4 on 2017-08-23 20:55 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('osf', '0053_add_quickfiles'), ] operations = [ migrations.AlterField( model_name='abstractnode', name='type', field=models.CharField(choices=[('osf.node', 'node'), ('osf.collection', 'collection'), ('osf.registration', 'registration'), ('osf.quickfilesnode', 'quick files node')], db_index=True, max_length=255), ), ]
apache-2.0
Python
4102ab8fc24265aaee1ecbf673bec260b3b3e5df
add max sub arr impl
YcheLanguageStudio/PythonStudy
bioinformatics/dynamic_programming/max_sum_sub_arr1.py
bioinformatics/dynamic_programming/max_sum_sub_arr1.py
def max_sum_sub_arr(arr): score_vector = [0 for _ in range(len(arr))] def max_sum_sub_arr_detail(beg_idx): if beg_idx >= len(arr): return 0 elif arr[beg_idx] >= 0: score_vector[beg_idx] = arr[beg_idx] + max_sum_sub_arr_detail(beg_idx + 1) return score_vector[beg_idx] else: score_vector[beg_idx] = max(0, arr[beg_idx] + max_sum_sub_arr_detail(beg_idx + 1)) return score_vector[beg_idx] max_sum_sub_arr_detail(0) print score_vector return max(score_vector) if __name__ == '__main__': print max_sum_sub_arr([1, -2, 3, 10, -4, 7, 2, -5])
mit
Python
1043acdfe324e02bc2a8629ef8a47d6ae9befd7c
Add python script to get ECC608 Public Key
google/aiyprojects-raspbian,google/aiyprojects-raspbian,google/aiyprojects-raspbian,google/aiyprojects-raspbian,google/aiyprojects-raspbian
src/aiy/_drivers/_ecc608_pubkey.py
src/aiy/_drivers/_ecc608_pubkey.py
#!/usr/bin/env python3 import base64 import ctypes import sys CRYPTO_ADDRESS_DICT = { 'Vision Bonnet': 0x60, 'Voice Bonnet': 0x62, } class AtcaIfaceCfgLong(ctypes.Structure): _fields_ = ( ('iface_type', ctypes.c_ulong), ('devtype', ctypes.c_ulong), ('slave_address', ctypes.c_ubyte), ('bus', ctypes.c_ubyte), ('baud', ctypes.c_ulong) ) def main(): try: cryptolib = ctypes.cdll.LoadLibrary('libcryptoauth.so') except Exception: print('Unable to load crypto library, SW authentication required') sys.exit() try: for name, addr in CRYPTO_ADDRESS_DICT.items(): cfg = AtcaIfaceCfgLong.in_dll(cryptolib, 'cfg_ateccx08a_i2c_default') cfg.slave_address = addr << 1 cfg.bus = 1 # ARM I2C cfg.devtype = 3 # ECC608 status = cryptolib.atcab_init(cryptolib.cfg_ateccx08a_i2c_default) if status == 0: # Found a valid crypto chip. break else: cryptolib.atcab_release() if status: raise Exception serial = ctypes.create_string_buffer(9) status = cryptolib.atcab_read_serial_number(ctypes.byref(serial)) if status: raise Exception serial = ''.join('%02X' % x for x in serial.raw) print('Serial Number: %s\n' % serial, file=sys.stderr) pubkey = ctypes.create_string_buffer(64) status = cryptolib.atcab_genkey_base(0, 0, None, ctypes.byref(pubkey)) if status: raise Exception public_key = bytearray.fromhex( '3059301306072A8648CE3D020106082A8648CE3D03010703420004') + bytes(pubkey.raw) public_key = '-----BEGIN PUBLIC KEY-----\n' + \ base64.b64encode(public_key).decode('ascii') + '\n-----END PUBLIC KEY-----' print(public_key) status = cryptolib.atcab_release() if status: raise Exception except Exception: print('Unable to communicate with crypto, SW authentication required') if __name__ == '__main__': main()
apache-2.0
Python
b04503bddfa3b0d737308ac8ecb7f06ac866e6eb
Create __init__.py
scienceopen/histutils,scienceopen/histutils
__init__.py
__init__.py
mit
Python
0b891e401bf0e671d3bc6f0347a456f1cc5b07b3
add __init__.py for root package
nakagami/janome,mocobeta/janome,nakagami/janome,mocobeta/janome
__init__.py
__init__.py
import sysdic
apache-2.0
Python
14f175c294ec6b5dcd75887a031386c1c9d7060d
add __main__
minacle/yarh
__main__.py
__main__.py
from . import parser import sys if len(sys.argv) == 1: print("compile yarh to html") print("usage: yarh [YARH_FILE]...") print(" yarh -- [YARH_STRING]") print(" yarh [YARH_FILE]... -- [YARH_STRING]") sys.exit(1) fromfile = True for arg in sys.argv[1:]: if arg == "--": fromfile = False continue if fromfile: f = open(arg, "r") print(parser.parseyarh(f.read()).html()) else: print(parser.parseyarh(arg).html()) fromfile = True break if not fromfile: print(parser.parseyarh(sys.stdin.read()).html())
bsd-2-clause
Python
e29c8e2d55464ac765db60a5cc213bb943b60742
add [[Portal:Beer]] and [[Portal:Wine]] tagging request script
legoktm/legobot-old,legoktm/legobot-old
trunk/portalbeer.py
trunk/portalbeer.py
#!usr/bin/python import sys, os, re sys.path.append(os.environ['HOME'] + '/stuffs/pywiki/pywikipedia') import wikipedia as wiki site = wiki.getSite() page = 'Portal:Beer/Selected picture/' #get page list pages = [] num = 0 content = """\ {{Selected picture | image = | size = | caption = | text = | credit = | link = }} """ while num <=50: num +=1 pages.append(wiki.Page(site,page + str(num))) #for page in pages: # print page # wiki.showDiff(page.get(), content) # page.put(content, 'Updating per [[WP:BOTREQ]]') raw_content = """\ {{Selected picture | image = | size = | caption = | text = | credit = | link = }} [[Category:Wine Portal]] """ pagewine = 'Portal:Wine/Selected picture/' pages1 = [] num = 0 while num <50: num +=1 pages1.append(wiki.Page(site,pagewine + str(num))) for page in pages1: print page try: wikitext = page.get() newtext = re.sub('Portal:Wine/Selected picture/Layout','Selected picture', wikitext) wiki.showDiff(wikitext, newtext) page.put(newtext, 'Updating per [[WP:BOTREQ]]') except wiki.NoPage: page.put(raw_content, 'Updating per [[WP:BOTREQ]]')
mit
Python
b56525d084ccbf1fe569900338f00a37e763d7dd
Add test_runtime_performance test
openstack/congress,ramineni/my_congress,ramineni/my_congress,ramineni/my_congress,ekcs/congress,openstack/congress,ramineni/my_congress,ekcs/congress,ekcs/congress,ekcs/congress
congress/tests/policy/test_runtime_performance.py
congress/tests/policy/test_runtime_performance.py
# Copyright (c) 2015 VMware, Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # from congress.openstack.common import log as logging from congress.policy import base from congress.policy.compile import Literal from congress.policy import runtime from congress.tests import base as testbase from congress.tests import helper LOG = logging.getLogger(__name__) NREC_THEORY = 'non-recursive theory' DB_THEORY = 'database' class TestRuntimePerformance(testbase.TestCase): """Tests for Runtime performance that are not specific to any theory. To run one test: nosetests -v \ congress/tests/policy/test_runtime_performance.py:TestRuntimePerformance.test_foo To collect profiling data: python -m cProfile -o profile.out `which nosetests` -v \ congress/tests/policy/test_runtime_performance.py:TestRuntimePerformance.test_foo To parse and sort profiling data in different ways: import pstats pstats.Stats('profile.out').strip_dirs().sort_stats("cum").print_stats() pstats.Stats('profile.out').strip_dirs().sort_stats("time").print_stats() pstats.Stats('profile.out').strip_dirs().sort_stats("calls").print_stats() """ def setUp(self): super(TestRuntimePerformance, self).setUp() self._runtime = runtime.Runtime() self._runtime.create_policy(NREC_THEORY, kind=base.NONRECURSIVE_POLICY_TYPE) self._runtime.create_policy(DB_THEORY, kind=base.DATABASE_POLICY_TYPE) self._runtime.debug_mode() self._runtime.insert('', target=NREC_THEORY) def _create_event(self, table, tuple_, insert, target): return runtime.Event(Literal.create_from_table_tuple(table, tuple_), insert=insert, target=target) def test_insert_nonrecursive(self): MAX = 100 th = NREC_THEORY for i in range(MAX): self._runtime.insert('r(%d)' % i, th) def test_insert_database(self): MAX = 100 th = DB_THEORY for i in range(MAX): self._runtime.insert('r(%d)' % i, th) def test_update_nonrecursive(self): MAX = 10000 th = NREC_THEORY updates = [self._create_event('r', (i,), True, th) for i in range(MAX)] self._runtime.update(updates) def test_update_database(self): MAX = 1000 th = DB_THEORY updates = [self._create_event('r', (i,), True, th) for i in range(MAX)] self._runtime.update(updates) def test_indexing(self): MAX = 100 th = NREC_THEORY for table in ('a', 'b', 'c'): updates = [self._create_event(table, (i,), True, th) for i in range(MAX)] self._runtime.update(updates) # With indexing, this query should take O(n) time where n is MAX. # Without indexing, this query will take O(n^3). self._runtime.insert('d(x) :- a(x), b(x), c(x)', th) ans = ' '.join(['d(%d)' % i for i in range(MAX)]) self.assertTrue(helper.datalog_equal(self._runtime.select('d(x)', th), ans)) def test_select(self): # with different types of policies (exercise indexing, large sets, # many joins, etc) pass def test_simulate(self): # We're interested in latency here. We think the cost will be the sum # of the simulate call + the cost to do and undo the evaluation, so # this test should focus on the cost specific to the simulate call, so # the the test should do a minimal amount of evaluation. pass def test_runtime_initialize_tables(self): MAX = 1000 formulas = [('p', 1, 2, 'foo', 'bar', i) for i in range(MAX)] th = NREC_THEORY self._runtime.initialize_tables(['p'], formulas, th)
apache-2.0
Python
525a6d214d3f6f9731c16bbf10ed150d1fa24021
Create betweenness.py
vitongos/mbitschool-bigdata-neo4j
src/betweenness.py
src/betweenness.py
''' Created on Feb 20, 2019 @author: Victor ''' from neo4j.v1 import GraphDatabase, basic_auth driver = GraphDatabase.driver("bolt://localhost") session = driver.session() query = '''CALL algo.betweenness.sampled.stream(null, null, {strategy:'random', probability:1.0, maxDepth:1, direction: 'both'}) YIELD nodeId, centrality MATCH (actor) WHERE id(actor) = nodeId and exists(actor.name) RETURN actor.name AS actor,centrality ORDER BY centrality DESC LIMIT 10;''' result = session.run(query) print("Top Central Nodes") print("-----------------") for record in result: print("%s %s" % (record["actor"].ljust(25, " "), record["centrality"])) session.close()
mit
Python
2e467774d83e14baf6fb2fec1fa4e0f6c1f8f88d
Disable webrtc benchmark on Android
axinging/chromium-crosswalk,Pluto-tv/chromium-crosswalk,Jonekee/chromium.src,krieger-od/nwjs_chromium.src,Pluto-tv/chromium-crosswalk,jaruba/chromium.src,Jonekee/chromium.src,littlstar/chromium.src,TheTypoMaster/chromium-crosswalk,ltilve/chromium,Pluto-tv/chromium-crosswalk,fujunwei/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,Jonekee/chromium.src,dushu1203/chromium.src,axinging/chromium-crosswalk,krieger-od/nwjs_chromium.src,dednal/chromium.src,TheTypoMaster/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,dednal/chromium.src,ondra-novak/chromium.src,krieger-od/nwjs_chromium.src,axinging/chromium-crosswalk,Chilledheart/chromium,PeterWangIntel/chromium-crosswalk,Fireblend/chromium-crosswalk,ondra-novak/chromium.src,axinging/chromium-crosswalk,jaruba/chromium.src,hgl888/chromium-crosswalk,fujunwei/chromium-crosswalk,ltilve/chromium,jaruba/chromium.src,crosswalk-project/chromium-crosswalk-efl,dushu1203/chromium.src,dushu1203/chromium.src,crosswalk-project/chromium-crosswalk-efl,crosswalk-project/chromium-crosswalk-efl,ondra-novak/chromium.src,dushu1203/chromium.src,mohamed--abdel-maksoud/chromium.src,PeterWangIntel/chromium-crosswalk,Just-D/chromium-1,dednal/chromium.src,mohamed--abdel-maksoud/chromium.src,axinging/chromium-crosswalk,bright-sparks/chromium-spacewalk,dushu1203/chromium.src,crosswalk-project/chromium-crosswalk-efl,PeterWangIntel/chromium-crosswalk,krieger-od/nwjs_chromium.src,ondra-novak/chromium.src,M4sse/chromium.src,krieger-od/nwjs_chromium.src,hgl888/chromium-crosswalk-efl,jaruba/chromium.src,TheTypoMaster/chromium-crosswalk,M4sse/chromium.src,fujunwei/chromium-crosswalk,Fireblend/chromium-crosswalk,M4sse/chromium.src,mohamed--abdel-maksoud/chromium.src,dushu1203/chromium.src,markYoungH/chromium.src,chuan9/chromium-crosswalk,dednal/chromium.src,Pluto-tv/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,dednal/chromium.src,dushu1203/chromium.src,chuan9/chromium-crosswalk,hgl888/chromium-crosswalk,M4sse/chromium.src,markYoungH/chromium.src,dednal/chromium.src,chuan9/chromium-crosswalk,littlstar/chromium.src,crosswalk-project/chromium-crosswalk-efl,ondra-novak/chromium.src,crosswalk-project/chromium-crosswalk-efl,dednal/chromium.src,Just-D/chromium-1,jaruba/chromium.src,mohamed--abdel-maksoud/chromium.src,fujunwei/chromium-crosswalk,hgl888/chromium-crosswalk,markYoungH/chromium.src,Pluto-tv/chromium-crosswalk,jaruba/chromium.src,jaruba/chromium.src,bright-sparks/chromium-spacewalk,Pluto-tv/chromium-crosswalk,Jonekee/chromium.src,bright-sparks/chromium-spacewalk,Fireblend/chromium-crosswalk,hgl888/chromium-crosswalk-efl,crosswalk-project/chromium-crosswalk-efl,mohamed--abdel-maksoud/chromium.src,PeterWangIntel/chromium-crosswalk,bright-sparks/chromium-spacewalk,krieger-od/nwjs_chromium.src,dushu1203/chromium.src,TheTypoMaster/chromium-crosswalk,dushu1203/chromium.src,ltilve/chromium,Jonekee/chromium.src,Chilledheart/chromium,dednal/chromium.src,bright-sparks/chromium-spacewalk,ltilve/chromium,Jonekee/chromium.src,littlstar/chromium.src,jaruba/chromium.src,markYoungH/chromium.src,hgl888/chromium-crosswalk-efl,hgl888/chromium-crosswalk-efl,mohamed--abdel-maksoud/chromium.src,crosswalk-project/chromium-crosswalk-efl,ondra-novak/chromium.src,M4sse/chromium.src,dednal/chromium.src,markYoungH/chromium.src,ltilve/chromium,mohamed--abdel-maksoud/chromium.src,krieger-od/nwjs_chromium.src,dushu1203/chromium.src,mohamed--abdel-maksoud/chromium.src,axinging/chromium-crosswalk,Chilledheart/chromium,Jonekee/chromium.src,Just-D/chromium-1,M4sse/chromium.src,jaruba/chromium.src,hgl888/chromium-crosswalk-efl,ondra-novak/chromium.src,Just-D/chromium-1,TheTypoMaster/chromium-crosswalk,markYoungH/chromium.src,fujunwei/chromium-crosswalk,dednal/chromium.src,littlstar/chromium.src,Jonekee/chromium.src,fujunwei/chromium-crosswalk,Fireblend/chromium-crosswalk,axinging/chromium-crosswalk,Fireblend/chromium-crosswalk,Chilledheart/chromium,Jonekee/chromium.src,hgl888/chromium-crosswalk-efl,mohamed--abdel-maksoud/chromium.src,chuan9/chromium-crosswalk,bright-sparks/chromium-spacewalk,Chilledheart/chromium,bright-sparks/chromium-spacewalk,chuan9/chromium-crosswalk,Chilledheart/chromium,krieger-od/nwjs_chromium.src,hgl888/chromium-crosswalk,axinging/chromium-crosswalk,Chilledheart/chromium,Just-D/chromium-1,TheTypoMaster/chromium-crosswalk,ltilve/chromium,Just-D/chromium-1,Chilledheart/chromium,dednal/chromium.src,Fireblend/chromium-crosswalk,hgl888/chromium-crosswalk,markYoungH/chromium.src,fujunwei/chromium-crosswalk,hgl888/chromium-crosswalk-efl,Jonekee/chromium.src,markYoungH/chromium.src,hgl888/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,Fireblend/chromium-crosswalk,Just-D/chromium-1,ltilve/chromium,Pluto-tv/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,axinging/chromium-crosswalk,hgl888/chromium-crosswalk-efl,littlstar/chromium.src,fujunwei/chromium-crosswalk,markYoungH/chromium.src,PeterWangIntel/chromium-crosswalk,Just-D/chromium-1,M4sse/chromium.src,hgl888/chromium-crosswalk-efl,TheTypoMaster/chromium-crosswalk,bright-sparks/chromium-spacewalk,bright-sparks/chromium-spacewalk,jaruba/chromium.src,markYoungH/chromium.src,ondra-novak/chromium.src,chuan9/chromium-crosswalk,axinging/chromium-crosswalk,dushu1203/chromium.src,hgl888/chromium-crosswalk,chuan9/chromium-crosswalk,axinging/chromium-crosswalk,hgl888/chromium-crosswalk,Chilledheart/chromium,Just-D/chromium-1,M4sse/chromium.src,chuan9/chromium-crosswalk,M4sse/chromium.src,PeterWangIntel/chromium-crosswalk,littlstar/chromium.src,mohamed--abdel-maksoud/chromium.src,Pluto-tv/chromium-crosswalk,Fireblend/chromium-crosswalk,littlstar/chromium.src,ondra-novak/chromium.src,jaruba/chromium.src,littlstar/chromium.src,krieger-od/nwjs_chromium.src,PeterWangIntel/chromium-crosswalk,M4sse/chromium.src,hgl888/chromium-crosswalk,krieger-od/nwjs_chromium.src,ltilve/chromium,krieger-od/nwjs_chromium.src,Pluto-tv/chromium-crosswalk,M4sse/chromium.src,Jonekee/chromium.src,markYoungH/chromium.src,Fireblend/chromium-crosswalk,ltilve/chromium,chuan9/chromium-crosswalk,fujunwei/chromium-crosswalk,hgl888/chromium-crosswalk-efl
tools/perf/benchmarks/webrtc.py
tools/perf/benchmarks/webrtc.py
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from measurements import webrtc import page_sets from telemetry import benchmark @benchmark.Disabled('android') # crbug.com/390233 class WebRTC(benchmark.Benchmark): """Obtains WebRTC metrics for a real-time video tests.""" test = webrtc.WebRTC page_set = page_sets.WebrtcCasesPageSet
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from measurements import webrtc import page_sets from telemetry import benchmark class WebRTC(benchmark.Benchmark): """Obtains WebRTC metrics for a real-time video tests.""" test = webrtc.WebRTC page_set = page_sets.WebrtcCasesPageSet
bsd-3-clause
Python
d9e11e2c5f14cee0ead87ced9afe85bdd299ab35
Add python script to extract
sukanyapatra/Disatweet
extract_text.py
extract_text.py
import json f=open('raw.json') g=open('extracted1','a') i=1 for s in f: j=json.loads(s) j=j['text'] h=json.dumps(j) number=str(i) + ':' + ' ' g.write(h) g.write('\n\n') i=i+1
mit
Python
370d3a122fa0bfc4c6f57a5cd6e518968205611a
add another linechart example showing new features
yelster/python-nvd3,mgx2/python-nvd3,oz123/python-nvd3,pignacio/python-nvd3,liang42hao/python-nvd3,Coxious/python-nvd3,vdloo/python-nvd3,oz123/python-nvd3,BibMartin/python-nvd3,mgx2/python-nvd3,mgx2/python-nvd3,pignacio/python-nvd3,BibMartin/python-nvd3,liang42hao/python-nvd3,liang42hao/python-nvd3,oz123/python-nvd3,BibMartin/python-nvd3,yelster/python-nvd3,vdloo/python-nvd3,Coxious/python-nvd3,yelster/python-nvd3,Coxious/python-nvd3,vdloo/python-nvd3,pignacio/python-nvd3
examples/lineChartXY.py
examples/lineChartXY.py
#!/usr/bin/python # -*- coding: utf-8 -*- """ Examples for Python-nvd3 is a Python wrapper for NVD3 graph library. NVD3 is an attempt to build re-usable charts and chart components for d3.js without taking away the power that d3.js gives you. Project location : https://github.com/areski/python-nvd3 """ from nvd3 import lineChart import math from numpy import sin,pi,linspace output_file = open('test_lineChartXY.html', 'w') chart = lineChart(name="lineChart", date=False, x_format="f",y_format="f", width=500, height=500, show_legend=False) #lissajous parameters of a/b a = [1,3,5,3] b = [1,5,7,4] delta = pi/2 t = linspace(-pi,pi,300) for i in range(0,4): x = sin(a[i] * t + delta) y = sin(b[i] * t) chart.add_serie(y=y, x=x, name='lissajous-n%d' % i, color='red' if i == 0 else 'black') chart.buildhtml() output_file.write(chart.htmlcontent) output_file.close()
mit
Python
aa4a3011775c12c19d690bbca91a07df4e033b1f
add urls for admin, zinnia, and serving static files
mwcz/phyton,mwcz/phyton,mwcz/phyton,mwcz/phyton,mwcz/phyton,mwcz/phyton
src/phyton/urls.py
src/phyton/urls.py
from django.conf.urls import patterns, include, url from django.contrib import admin from django.conf import settings from django.conf.urls.static import static admin.autodiscover() urlpatterns = patterns('', # Admin URLs url(r'^admin/doc/', include('django.contrib.admindocs.urls')), url(r'^admin/', include(admin.site.urls)), # Zinnia's URLs url(r'^weblog/', include('zinnia.urls')), url(r'^comments/', include('django.contrib.comments.urls')), ) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
agpl-3.0
Python
b31def01a04a6ddb90e780985e43e8ad8e57e457
Create uber.py
jasuka/pyBot,jasuka/pyBot
modules/uber.py
modules/uber.py
def uber(self): self.send_chan("Moi")
mit
Python
27ab8b0436d784f44220512a91e699006b735d82
test mpi
ratnania/pyccel,ratnania/pyccel
tests/test_mpi.py
tests/test_mpi.py
# coding: utf-8 ierr = mpi_init() comm = mpi_comm_world print("mpi_comm = ", comm) size, ierr = mpi_comm_size(comm) print("mpi_size = ", size) rank, ierr = mpi_comm_rank(comm) print("mpi_rank = ", rank) #abort, ierr = mpi_abort(comm) #print("mpi_abort = ", abort) ierr = mpi_finalize()
mit
Python
2ad40dc0e7f61e37ab768bedd53572959a088bb0
Make app package
andela-akiura/bucketlist
app/__init__.py
app/__init__.py
from flask import Flask def create_app(config_name): pass
mit
Python
4981a1fa0d94020e20a8e7714af62a075f7d7874
delete customers
devops-alpha-s17/customers,devops-alpha-s17/customers
delete_customers.py
delete_customers.py
@app.route('/customers/<int:id>', methods=['DELETE']) def delete_customers(id): index = [i for i, customer in enumerate(customers) if customer['id'] == id] if len(index) > 0: del customers[index[0]] return make_response('', HTTP_204_NO_CONTENT)
apache-2.0
Python
bc34aa231a3838ad7686541ed4bce58374a40b19
Create __init__.py
janpipek/physt
physt/__init__.py
physt/__init__.py
mit
Python
2b6c13f883a8e914a3f719447b508430c2d51e5a
Add Tower Label module (#21485)
thaim/ansible,thaim/ansible
lib/ansible/modules/web_infrastructure/ansible_tower/tower_label.py
lib/ansible/modules/web_infrastructure/ansible_tower/tower_label.py
#!/usr/bin/python #coding: utf-8 -*- # (c) 2017, Wayne Witzel III <[email protected]> # # This module is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This software is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this software. If not, see <http://www.gnu.org/licenses/>. ANSIBLE_METADATA = {'status': ['preview'], 'supported_by': 'community', 'version': '1.0'} DOCUMENTATION = ''' --- module: tower_label version_added: "2.3" short_description: create, update, or destroy Ansible Tower label. description: - Create, update, or destroy Ansible Tower labels. See U(https://www.ansible.com/tower) for an overview. options: name: description: - Name to use for the label. required: True default: null organization: description: - Organization the label should be applied to. required: True default: null state: description: - Desired state of the resource. required: False default: "present" choices: ["present", "absent"] tower_host: description: - URL to your Tower instance. required: False default: null tower_username: description: - Username for your Tower instance. required: False default: null tower_password: description: - Password for your Tower instance. required: False default: null tower_verify_ssl: description: - Dis/allow insecure connections to Tower. If C(no), SSL certificates will not be validated. This should only be used on personally controlled sites using self-signed certificates. required: False default: True tower_config_file: description: - Path to the Tower config file. See notes. required: False default: null requirements: - "python >= 2.6" - "ansible-tower-cli >= 3.0.3" notes: - If no I(config_file) is provided we will attempt to use the tower-cli library defaults to find your Tower host information. - I(config_file) should contain Tower configuration in the following format host=hostname username=username password=password ''' EXAMPLES = ''' - name: Add label to tower organization tower_label name: Custom Label organization: My Organization state: present tower_config_file: "~/tower_cli.cfg" ''' try: import tower_cli import tower_cli.utils.exceptions as exc from tower_cli.conf import settings from ansible.module_utils.ansible_tower import tower_auth_config, tower_check_mode HAS_TOWER_CLI = True except ImportError: HAS_TOWER_CLI = False def main(): module = AnsibleModule( argument_spec = dict( name = dict(required=True), organization = dict(required=True), tower_host = dict(), tower_username = dict(), tower_password = dict(no_log=True), tower_verify_ssl = dict(type='bool', default=True), tower_config_file = dict(type='path'), state = dict(choices=['present', 'absent'], default='present'), ), supports_check_mode=True ) if not HAS_TOWER_CLI: module.fail_json(msg='ansible-tower-cli required for this module') name = module.params.get('name') organization = module.params.get('organization') state = module.params.get('state') json_output = {'label': name, 'state': state} tower_auth = tower_auth_config(module) with settings.runtime_values(**tower_auth): tower_check_mode(module) label = tower_cli.get_resource('label') try: org_res = tower_cli.get_resource('organization') org = org_res.get(name=organization) if state == 'present': result = label.modify(name=name, organization=org['id'], create_on_missing=True) json_output['id'] = result['id'] elif state == 'absent': result = label.delete(name=name, organization=org['id']) except (exc.NotFound) as excinfo: module.fail_json(msg='Failed to update label, organization not found: {0}'.format(excinfo), changed=False) except (exc.ConnectionError, exc.BadRequest, exc.NotFound) as excinfo: module.fail_json(msg='Failed to update label: {0}'.format(excinfo), changed=False) json_output['changed'] = result['changed'] module.exit_json(**json_output) from ansible.module_utils.basic import AnsibleModule if __name__ == '__main__': main()
mit
Python
e93bbc1b5091f9b6d583437aea05aa59c8233d2d
add audiotsmcli
Muges/audiotsm
examples/audiotsmcli.py
examples/audiotsmcli.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ audiotsmcli ~~~~~~~~~~~ Change the speed of an audio file without changing its pitch. """ import argparse import os from audiotsm.ola import ola from audiotsm.io.wav import WavReader, WavWriter def main(): """Change the speed of an audio file without changing its pitch.""" # Parse command line arguments parser = argparse.ArgumentParser(description=( "Change the speed of an audio file without changing its pitch.")) parser.add_argument('-s', '--speed', metavar="S", type=float, default=1., help=("Set the speed ratio (e.g 0.5 to play at half " "speed)")) parser.add_argument('-l', '--frame-length', metavar='N', type=int, default=None, help=("Set the frame length to N.")) parser.add_argument('-a', '--analysis-hop', metavar='N', type=int, default=None, help=("Set the analysis hop to N.")) parser.add_argument('--synthesis-hop', metavar='N', type=int, default=None, help=("Set the synthesis hop to N.")) parser.add_argument('input_filename', metavar='INPUT_FILENAME', type=str, help=("The audio input file")) parser.add_argument('output_filename', metavar='OUTPUT_FILENAME', type=str, help=("The audio output file")) args = parser.parse_args() if not os.path.isfile(args.input_filename): parser.error( 'The input file "{}" does not exist.'.format(args.input_filename)) # Get TSM method parameters parameters = {} if args.speed is not None: parameters['speed'] = args.speed if args.frame_length is not None: parameters['frame_length'] = args.frame_length if args.analysis_hop is not None: parameters['analysis_hop'] = args.analysis_hop if args.speed is not None: parameters['speed'] = args.speed # Get input and output files input_filename = args.input_filename output_filename = args.output_filename # Run the TSM procedure with WavReader(input_filename) as reader: channels = reader.channels with WavWriter(output_filename, channels, reader.samplerate) as writer: tsm = ola(channels, **parameters) finished = False while not (finished and reader.empty): tsm.read_from(reader) _, finished = tsm.write_to(writer) finished = False while not finished: _, finished = tsm.flush_to(writer) if __name__ == "__main__": main()
mit
Python
2b1dc56193f3a81e5aba237f3ad59aa9113dcb6e
Create ui.py
taygetea/scatterplot-visualizer
ui.py
ui.py
from visual import * from visual.controls import * import wx import scatterplot import ui_functions debug = True L = 320 Hgraph = 400 # Create a window. Note that w.win is the wxPython "Frame" (the window). # window.dwidth and window.dheight are the extra width and height of the window # compared to the display region inside the window. If there is a menu bar, # there is an additional height taken up, of amount window.menuheight. # The default style is wx.DEFAULT_FRAME_STYLE; the style specified here # does not enable resizing, minimizing, or full-sreening of the window. w = window(width=2*(L+window.dwidth), height=L+window.dheight+window.menuheight+Hgraph, menus=False, title='Widgets', style=wx.SYSTEM_MENU | wx.CAPTION | wx.CLOSE_BOX) # Place a 3D display widget in the left half of the window. d = 20 disp = display(window=w, x=d, y=d, width=L*d, height=L*d, background=color.black, center=vector(.5,.5,.5), range = 1) # Place buttons, radio buttons, a scrolling text object, and a slider # in the right half of the window. Positions and sizes are given in # terms of pixels, and pos(0,0) is the upper left corner of the window. p = w.panel # Refers to the full region of the window in which to place widgets m = wx.MenuBar() file_menu = wx.Menu() view_menu = wx.Menu() options_menu = wx.Menu() edit_menu = wx.Menu() item = file_menu.Append(-1, "Load Data\tCtrl-L", "Load") w.win.Bind(wx.EVT_MENU, ui_functions.open_file, item) file_menu.AppendSeparator() item = file_menu.Append(-1, "Open Plot\tCtrl-O", "Open") item = file_menu.Append(-1, "Save Plot\tCtrl-S", "Save") file_menu.AppendSeparator() item = file_menu.Append(-1, "Export\tCtrl-E", "Export") file_menu.AppendSeparator() item = file_menu.Append(-1, "Quit\tCtrl-Q", "Exit") w.win.Bind(wx.EVT_MENU, w._OnExitApp, item) item = edit_menu.Append(-1, 'Undo\tCtrl-Z', 'Make box cyan') item = edit_menu.Append(-1, 'Redo\tCtrl-Y', 'Make box cyan') edit_menu.AppendSeparator() item = edit_menu.Append(-1, 'Cut\tCtrl-X', 'Make box cyan') item = edit_menu.Append(-1, 'Copy\tCtrl-C', 'Make box cyan') item = edit_menu.Append(-1, 'Paste\tCtrl-V', 'Make box cyan') edit_menu.AppendSeparator() item = edit_menu.Append(-1, 'Select All\tCtrl-A', 'Make box cyan') item = view_menu.Append(-1, 'Frame limits', 'Make box cyan') item = view_menu.Append(-1, 'Equalise Axes', 'Make box cyan') item = view_menu.Append(-1, 'Restore Default View', 'Make box cyan') item = view_menu.Append(-1, 'Show Toolbar', 'Make box cyan') item = options_menu.Append(-1, 'Titles & Labels', 'Make box cyan') item = options_menu.Append(-1, 'Axes', 'Make box cyan') w.win.Bind(wx.EVT_MENU, ui_functions.toggle_axes, item) item = options_menu.Append(-1, 'Grid', 'Make box cyan') w.win.Bind(wx.EVT_MENU, ui_functions.toggle_grid, item) item = options_menu.Append(-1, 'Data Points', 'Make box cyan') item = options_menu.Append(-1, 'Export Formats', 'Make box cyan') m.Append(file_menu, '&File') m.Append(edit_menu, '&Edit') m.Append(view_menu, '&View') m.Append(options_menu, '&Options') if debug: scatterplot.import_datafile('points.csv') w.win.SetMenuBar(m) while True: rate(100)
mit
Python
6dd52499de049d76a1bea5914f47dc5b6aae23d7
Add gspread example
voidabhi/python-scripts,voidabhi/python-scripts,voidabhi/python-scripts,voidabhi/python-scripts,voidabhi/python-scripts
xl.py
xl.py
#!/usr/bin/python #csv upload to gsheet import logging import json import gspread import time import re from oauth2client.client import SignedJwtAssertionCredentials from Naked.toolshed.shell import muterun_rb logging.basicConfig(filename='/var/log/gspread.log',format='%(asctime)s %(levelname)s:%(message)s',level=logging.INFO) filename = '<google sheet name>' #OAuth login json_key = json.load(open('oauth.json')) """ JSON in the form: { "private_key_id": "", "private_key": "", "client_email": "", "client_id": "", "type": "service_account" } """ scope = ['https://spreadsheets.google.com/feeds'] credentials = SignedJwtAssertionCredentials(json_key['client_email'], json_key['private_key'], scope) gc = gspread.authorize(credentials) if gc: logging.info('OAuth succeeded') else: logging.warn('Oauth failed') now = time.strftime("%c") # get data from ruby script response = muterun_rb('script') if response: logging.info('Data collected') else: logging.warn('Could not collect data') csv = response.stdout csv = re.sub('/|"|,[0-9][0-9][0-9]Z|Z', '', csv) csv_lines = csv.split('\n') #get columns and rows for cell list column = len(csv_lines[0].split(",")) row = 1 for line in csv_lines: row += 1 #create cell range columnletter = chr((column - 1) + ord('A')) cell_range = 'A1:%s%s' % (columnletter, row) #open the worksheet and create a new sheet wks = gc.open(filename) if wks: logging.info('%s file opened for writing', filename) else: logging.warn('%s file could not be opened', filename) sheet = wks.add_worksheet(title=now, rows=(row + 2), cols=(column + 2)) cell_list = sheet.range(cell_range) #create values list csv = re.split("\n|,", csv) for item, cell in zip(csv, cell_list): cell.value = item # Update in batch if sheet.update_cells(cell_list): logging.info('upload to %s sheet in %s file done', now, filename) else: logging.warn('upload to %s sheet in %s file failed', now, filename)
mit
Python
3e10a9fcb15e06699aa90016917b4ec5ec857faa
Solve task #506
Zmiecer/leetcode,Zmiecer/leetcode
506.py
506.py
class Solution(object): def findRelativeRanks(self, nums): """ :type nums: List[int] :rtype: List[str] """ def reverse_numeric(x, y): return y - x kek = sorted(nums, cmp=reverse_numeric) l = len(nums) if l > 0: nums[nums.index(kek[0])] = "Gold Medal" if l > 1: nums[nums.index(kek[1])] = "Silver Medal" if l > 2: nums[nums.index(kek[2])] = "Bronze Medal" if l > 3: for i in range(3, l): nums[nums.index(kek[i])] = str(i + 1) return nums
mit
Python
0040a9e9417ab8becac64701b3c4fc6d94410a21
Create Mc3.py
monhustla/line-bot-sdk-python
Mc3.py
Mc3.py
# -*- coding: utf-8 -*- """Mc3 module.""" import cmd2 from linebot.models import ( MessageEvent, TextMessage, TextSendMessage, SourceUser, SourceGroup, SourceRoom, TemplateSendMessage, ConfirmTemplate, MessageTemplateAction, ButtonsTemplate, URITemplateAction, PostbackTemplateAction, CarouselTemplate, CarouselColumn, PostbackEvent, StickerMessage, StickerSendMessage, LocationMessage, LocationSendMessage, ImageMessage, VideoMessage, AudioMessage, UnfollowEvent, FollowEvent, JoinEvent, LeaveEvent, BeaconEvent, ImageSendMessage,VideoSendMessage ) from aq import (aq, map, boss) from arena import arena from aw import aw from mcoccalendars import calendar #from prestigetest import inputchamp class Mc3(cmd2.Cmd): trigger = 'Mc3 ' def __init__(self, line_bot_api, event): self.line_bot_api = line_bot_api self.event = event super(Mc3, self).__init__() def default(self, line): #self.line_bot_api.reply_message(self.event.reply_token, # TextSendMessage(text="Oops! You've entered an invalid command please type " + # self.trigger + "list to view available commands")) return False def do_list(self, line): self.line_bot_api.reply_message( self.event.reply_token, TextSendMessage(text="Make sure all commands start with the 'Mc3' trigger and there are no spaces after the last letter in the command!"+'\n'+ "Example:'Mc3 aq'"+'\n'+ '\n'+ "Command List:"+'\n'+ "abilities"+'\n'+ "aq"+'\n'+ "aw"+'\n'+ "arena"+'\n'+ "calendars"+'\n'+ "duels"+'\n'+ "masteries"+'\n'+ "prestige"+'\n'+ "prestige tools"+'\n'+ "special quests"+'\n'+ "synergies"+'\n'+ "support"+'\n'+ "Inputting champs has changed, please see new syntax in 'Mc3 prestige tools'")) return True; def do_aq(self, line): _aq = aq(self.line_bot_api, self.event) return _aq.process(line.parsed.args) def do_map(self, line): _map = map(self.line_bot_api, self.event) return _map.process(line.parsed.args) def do_boss(self, line): _boss = boss(self.line_bot_api, self.event) return _boss.process(line.parsed.args) def do_arena(self, line): _arena = arena(self.line_bot_api, self.event) return _arena.process(line.parsed.args) def do_aw(self, line): _aw = aw(self.line_bot_api, self.event) return _aw.process(line.parsed.args) def do_calendar(self, line): _calendar = calendar(self.line_bot_api, self.event) return _calendar.process(line.parsed.args) #def do_inputchamp(self, line): # _inputchamp=inputchamp(self.line_bot_api, self.event,self.events, self.user) #return _inputchamp.splitname(line) def do_help(self, line): return self.do_list(line); def do_EOF(self, line): return True def process(self, line): return self.onecmd(line);
apache-2.0
Python
6c3867275693d4a771b9ff8df55aab18818344cd
add first app
RyouZhang/nori,RyouZhang/noir
app.py
app.py
import tornado.ioloop import tornado.web class MainHandler(tornado.web.RequestHandler): def get(self): self.write("Hello, world") def make_app(): return tornado.web.Application([ (r"/", MainHandler), ]) if __name__ == "__main__": app = make_app() app.listen(8888) tornado.ioloop.IOLoop.current().start()
mit
Python
8080153c65f4aa1d875a495caeee290fb1945081
Add migration
Harvard-ATG/media_management_api,Harvard-ATG/media_management_api
media_management_api/media_auth/migrations/0005_delete_token.py
media_management_api/media_auth/migrations/0005_delete_token.py
# Generated by Django 3.2.7 on 2021-09-15 20:00 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('media_auth', '0004_auto_20160209_1902'), ] operations = [ migrations.DeleteModel( name='Token', ), ]
bsd-3-clause
Python
40b0f1cd33a053be5ab528b4a50bda404f0756dc
Add managment command Add_images_to_sections
praekelt/molo-gem,praekelt/molo-gem,praekelt/molo-gem
gem/management/commands/Add_images_to_sections.py
gem/management/commands/Add_images_to_sections.py
from __future__ import absolute_import, unicode_literals import csv from babel import Locale from django.core.management.base import BaseCommand from wagtail.wagtailimages.tests.utils import Image from molo.core.models import Languages, SectionPage, Main, SectionIndexPage class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument('csv_name', type=str) parser.add_argument('locale', type=str) def handle(self, *args, **options): csv_name = options.get('csv_name', None) locale_code = options.get('locale', None) mains = Main.objects.all() sections = {} with open(csv_name) as sections_images: reader = csv.reader(sections_images) if mains: for row in reader: key = row[0] sections[key] = row[1:] for main in mains: section_index = SectionIndexPage.objects.child_of(main).first() main_lang = Languages.for_site(main.get_site()).languages.filter( is_active=True, is_main_language=True).first() translated_sections = SectionPage.objects.descendant_of( section_index).filter( languages__language__is_main_language=False).live() for translated_section in translated_sections: translated_section.image = None translated_section.save_revision().publish() if section_index and main_lang: if main_lang.locale == locale_code: for section_slug in sections: section = SectionPage.objects.descendant_of( section_index).filter(slug=section_slug).first() if section: for image_title in sections.get(section_slug): image = Image.objects.filter( title=image_title + ".jpg").first() if image: section.image = image section.extra_style_hints = section.slug section.save_revision().publish() else: self.stdout.write(self.style.NOTICE( 'Image "%s" does not exist in "%s"' % (image_title, main))) else: self.stdout.write(self.style.ERROR( 'section "%s" does not exist in "%s"' % (section_slug, main.get_site()))) else: self.stdout.write(self.style.NOTICE( 'Main language of "%s" is not "%s".' ' The main language is "%s"' % (main.get_site(), locale_code, main_lang))) else: if not section_index: self.stdout.write(self.style.NOTICE( 'Section Index Page does not exist in "%s"' % main)) if not main_lang: self.stdout.write(self.style.NOTICE( 'Main language does not exist in "%s"' % main))
bsd-2-clause
Python
69b900580e614ce494b9d1be0bee61464470cef7
Create 6kyu_digital_root.py
Orange9000/Codewars,Orange9000/Codewars
Solutions/6kyu_digital_root.py
Solutions/6kyu_digital_root.py
from functools import reduce def digital_root(n): while n>10: n = reduce(lambda x,y: x+y, [int(d) for d in str(n)]) return n
mit
Python
6c08f3d3441cf660de910b0f3c49c3385f4469f4
Add "Secret" channel/emoji example
rapptz/discord.py,Harmon758/discord.py,Rapptz/discord.py,Harmon758/discord.py
examples/secret.py
examples/secret.py
import typing import discord from discord.ext import commands bot = commands.Bot(command_prefix=commands.when_mentioned, description="Nothing to see here!") # the `hidden` keyword argument hides it from the help command. @bot.group(hidden=True) async def secret(ctx: commands.Context): """What is this "secret" you speak of?""" if ctx.invoked_subcommand is None: await ctx.send('Shh!', delete_after=5) def create_overwrites(ctx, *objects): """This is just a helper function that creates the overwrites for the voice/text channels. A `discord.PermissionOverwrite` allows you to determine the permissions of an object, whether it be a `discord.Role` or a `discord.Member`. In this case, the `view_channel` permission is being used to hide the channel from being viewed by whoever does not meet the criteria, thus creating a secret channel. """ # a dict comprehension is being utilised here to set the same permission overwrites # for each `discord.Role` or `discord.Member`. overwrites = { obj: discord.PermissionOverwrite(view_channel=True) for obj in objects } # prevents the default role (@everyone) from viewing the channel # if it isn't already allowed to view the channel. overwrites.setdefault(ctx.guild.default_role, discord.PermissionOverwrite(view_channel=False)) # makes sure the client is always allowed to view the channel. overwrites[ctx.guild.me] = discord.PermissionOverwrite(view_channel=True) return overwrites # since these commands rely on guild related features, # it is best to lock it to be guild-only. @secret.command() @commands.guild_only() async def text(ctx: commands.Context, name: str, *objects: typing.Union[discord.Role, discord.Member]): """This makes a text channel with a specified name that is only visible to roles or members that are specified. """ overwrites = create_overwrites(ctx, *objects) await ctx.guild.create_text_channel( name, overwrites=overwrites, topic='Top secret text channel. Any leakage of this channel may result in serious trouble.', reason='Very secret business.', ) @secret.command() @commands.guild_only() async def voice(ctx: commands.Context, name: str, *objects: typing.Union[discord.Role, discord.Member]): """This does the same thing as the `text` subcommand but instead creates a voice channel. """ overwrites = create_overwrites(ctx, *objects) await ctx.guild.create_voice_channel( name, overwrites=overwrites, reason='Very secret business.' ) @secret.command() @commands.guild_only() async def emoji(ctx: commands.Context, emoji: discord.PartialEmoji, *roles: discord.Role): """This clones a specified emoji that only specified roles are allowed to use. """ # fetch the emoji asset and read it as bytes. emoji_bytes = await emoji.url.read() # the key parameter here is `roles`, which controls # what roles are able to use the emoji. await ctx.guild.create_custom_emoji( name=emoji.name, image=emoji_bytes, roles=roles, reason='Very secret business.' ) bot.run('token')
mit
Python
e0338d39f611b2ca3f202151c49fc6a4b35bd580
Add WallBuilder
zhaoshengshi/practicepython-exercise
exercise/WallBuilder.py
exercise/WallBuilder.py
#!/usr/bin/env python3 class Block(object): def __init__(self, width, height, **attr): self.__width = width self.__height = height def __eq__(self, another): return (self.__width == another.__width) and \ (self.__height == another.__height) class Brick(Block): pass class Layer(Block): def build(self, brick, **more): pass class Wall(Block): pass class WallBuilder(object): def __init__(self, brick, *more): self.__bricks = [brick] for i in more: if i not in self.__bricks: self.__bricks.append(i) def get(x, y, z): m1 = (z//x) m2 = (z//y) return [(i, j) for i in range(0, m1+1) for j in range(0, m2+1) if (x*i + y*j) == z] b1 = Brick(2, 1) b2 = Brick(3, 1) c = WallBuilder(b1, b2) pass
apache-2.0
Python
8a30bcc511647ed0c994cb2103dd5bed8d4671a8
Create B_Temperature.py
Herpinemmanuel/Oceanography
Cas_4/Temperature/B_Temperature.py
Cas_4/Temperature/B_Temperature.py
import numpy as np import matplotlib.pyplot as plt import matplotlib.colors as colors import cartopy.crs as ccrs from xmitgcm import open_mdsdataset from cartopy.mpl.gridliner import LONGITUDE_FORMATTER, LATITUDE_FORMATTER plt.ion() dir0 = '/homedata/bderembl/runmit/test_southatlgyre3' ds0 = open_mdsdataset(dir0,prefix=['T']) nt = 0 nz = 0 while (nt < 150) : nt = nt+1 print(nt) plt.figure(1) ax = plt.subplot(projection=ccrs.PlateCarree()); ds0['T'][nt,nz,:,:].plot.pcolormesh('XC', 'YC',ax=ax,vmin=-10,vmax=35,cmap='ocean') plt.title('Case 4 : Temperature ') plt.text(5,5,nt,ha='center',wrap=True) ax.coastlines() gl = ax.gridlines(draw_labels=True, alpha = 0.5, linestyle='--'); gl.xlabels_top = False gl.ylabels_right = False gl.xformatter = LONGITUDE_FORMATTER gl.yformatter = LATITUDE_FORMATTER if (nt < 10): plt.savefig('Temperature_cas4-'+'00'+str(nt)+'.png') plt.clf() elif (nt > 9) and (nt < 100): plt.savefig('Temperature_cas4-'+'0'+str(nt)+'.png') plt.clf() else: plt.savefig('Temperature_cas4-'+str(nt)+'.png') plt.clf()
mit
Python
a70490e52bde05d2afc6ea59416a50e11119d060
Add migration for Comment schema upgrade. ...
sjuxax/raggregate
raggregate/rg_migrations/versions/002_Add_metadata_to_Comment_to_allow_it_to_masquerade_as_epistle.py
raggregate/rg_migrations/versions/002_Add_metadata_to_Comment_to_allow_it_to_masquerade_as_epistle.py
from sqlalchemy import * from migrate import * from raggregate.guid_recipe import GUID def upgrade(migrate_engine): meta = MetaData(bind=migrate_engine) comments = Table('comments', meta, autoload=True) unreadc = Column('unread', Boolean, default=True) in_reply_toc = Column('in_reply_to', GUID, nullable=True) unreadc.create(comments) in_reply_toc.create(comments) def downgrade(migrate_engine): # Operations to reverse the above upgrade go here. meta = MetaData(bind=migrate_engine) comments = Table('comments', meta, autoload=True) comments.c.unread.drop() comments.c.in_reply_to.drop()
apache-2.0
Python
88d480f2c97bf7779afea34798c6c082f127f3a6
Add missing client.py (#703)
webcomponents/webcomponents.org,customelements/v2,customelements/v2,andymutton/v2,andymutton/beta,webcomponents/webcomponents.org,andymutton/beta,customelements/v2,webcomponents/webcomponents.org,andymutton/v2,andymutton/v2,andymutton/beta,customelements/v2,andymutton/beta,andymutton/v2
client/client.py
client/client.py
import webapp2 import re class RedirectResource(webapp2.RequestHandler): def get(self, path): path = re.sub(r'/$', '', path) self.redirect('/community/%s' % path, permanent=True) # pylint: disable=invalid-name app = webapp2.WSGIApplication([ webapp2.Route(r'/<:.*>', handler=RedirectResource), ], debug=True)
apache-2.0
Python
38cf2a9f0c964c69df084d80ded6cf161ba7eb16
Add elf read elf file.
somat/samber
elf.py
elf.py
import sys from elftools.elf.elffile import ELFFile from elftools.common.exceptions import ELFError from elftools.elf.segments import NoteSegment class ReadELF(object): def __init__(self, file): self.elffile = ELFFile(file) def get_build(self): for segment in self.elffile.iter_segments(): if isinstance(segment, NoteSegment): for note in segment.iter_notes(): print note def main(): if(len(sys.argv) < 2): print "Missing argument" sys.exit(1) with open(sys.argv[1], 'rb') as file: try: readelf = ReadELF(file) readelf.get_build() except ELFError as err: sys.stderr.write('ELF error: %s\n' % err) sys.exit(1) if __name__ == '__main__': main()
mit
Python
d2f13fb17d3f9998af1a175dfd4e2bea4544fb3d
add example to just serialize matrix
geektoni/shogun,shogun-toolbox/shogun,geektoni/shogun,besser82/shogun,sorig/shogun,Saurabh7/shogun,geektoni/shogun,lisitsyn/shogun,karlnapf/shogun,karlnapf/shogun,Saurabh7/shogun,geektoni/shogun,sorig/shogun,Saurabh7/shogun,lambday/shogun,karlnapf/shogun,besser82/shogun,shogun-toolbox/shogun,karlnapf/shogun,Saurabh7/shogun,Saurabh7/shogun,geektoni/shogun,besser82/shogun,lisitsyn/shogun,shogun-toolbox/shogun,lisitsyn/shogun,sorig/shogun,karlnapf/shogun,shogun-toolbox/shogun,Saurabh7/shogun,sorig/shogun,lisitsyn/shogun,lambday/shogun,lisitsyn/shogun,besser82/shogun,karlnapf/shogun,sorig/shogun,besser82/shogun,Saurabh7/shogun,Saurabh7/shogun,lisitsyn/shogun,lambday/shogun,shogun-toolbox/shogun,lambday/shogun,besser82/shogun,lambday/shogun,sorig/shogun,lambday/shogun,geektoni/shogun,Saurabh7/shogun,shogun-toolbox/shogun
examples/undocumented/python_modular/serialization_matrix_modular.py
examples/undocumented/python_modular/serialization_matrix_modular.py
from modshogun import * from numpy import array parameter_list=[[[[1.0,2,3],[4,5,6]]]] def serialization_matrix_modular(m): feats=RealFeatures(array(m)) #feats.io.set_loglevel(0) fstream = SerializableAsciiFile("foo.asc", "w") feats.save_serializable(fstream) l=Labels(array([1.0,2,3])) fstream = SerializableAsciiFile("foo2.asc", "w") l.save_serializable(fstream) os.unlink("foo.asc") os.unlink("foo2.asc") if __name__=='__main__': print 'Serialization Matrix Modular' serialization_matrix_modular(*parameter_list[0])
bsd-3-clause
Python
e7f1439cae37facaedce9c33244b58584e219869
Initialize P01_sendingEmail
JoseALermaIII/python-tutorials,JoseALermaIII/python-tutorials
books/AutomateTheBoringStuffWithPython/Chapter16/P01_sendingEmail.py
books/AutomateTheBoringStuffWithPython/Chapter16/P01_sendingEmail.py
# This program uses the smtplib module to send emails # Connecting to an SMTP Server import smtplib with open('smtp_info') as config: # smtp_cfg = [email, password, smtp server, port] smtp_cfg = config.read().splitlines() smtp_obj = smtplib.SMTP_SSL(smtp_cfg[2], smtp_cfg[3]) print(type(smtp_obj))
mit
Python
e86047546693290556494bf00b493aa4ae770482
add binding.gyp for node-gyp
pconstr/rawhash,pconstr/rawhash,pconstr/rawhash,pconstr/rawhash
binding.gyp
binding.gyp
{ "targets": [ { "target_name": "rawhash", "sources": [ "src/rawhash.cpp", "src/MurmurHash3.h", "src/MurmurHash3.cpp" ], 'cflags': [ '<!@(pkg-config --cflags libsparsehash)' ], 'conditions': [ [ 'OS=="linux" or OS=="freebsd" or OS=="openbsd" or OS=="solaris"', { 'cflags_cc!': ['-fno-rtti', '-fno-exceptions'], 'cflags_cc+': ['-frtti', '-fexceptions'], }], ['OS=="mac"', { 'xcode_settings': { 'GCC_ENABLE_CPP_RTTI': 'YES', 'GCC_ENABLE_CPP_EXCEPTIONS': 'YES' } }] ] } ] }
mit
Python
888b27db4d91ebba91eb935532f961943453b7c8
add update command to new certificate data model
hacklabr/paralapraca,hacklabr/paralapraca,hacklabr/paralapraca
paralapraca/management/commands/update_certificate_templates.py
paralapraca/management/commands/update_certificate_templates.py
# -*- coding: utf-8 -*- from django.core.management.base import BaseCommand from django.core.files import File from core.models import CertificateTemplate from timtec.settings import STATIC_ROOT from paralapraca.models import CertificateData, Contract import os class Command(BaseCommand): help = 'Create certificate and receipt templates data for CertificateTemplate existent' receipt_text = '<p>inscrita no cadastro de pessoa f&iacute;sica sob o n&uacute;mero {CPF}&nbsp;</p>\ <p>participou do <em>{MODULO}</em></p>\ <p>no Ambiente Virtual de Aprendizagem do Programa Paralaprac&aacute;.</p>' certificate_text = '<p style="text-align: center;">inscrita no cadastro de pessoa f&iacute;sica sob o n&uacute;mero&nbsp;{CPF}</p>\ <p style="text-align: center;">concluiu o&nbsp;<strong>{MODULO}</strong>,</p>\ <p style="text-align: center;">com carga hor&aacute;ria total de 40 horas, no&nbsp;</p>\ <p style="text-align: center;">Ambiente Virtual de Aprendizagem&nbsp;do Programa Paralaprac&aacute;.</p>' def handle(self, *files, **options): types = CertificateData.TYPES cts = CertificateTemplate.objects.all() plpc = Contract.objects.first() plpc_path = os.path.join(STATIC_ROOT, 'img/site-logo-orange.svg') avante_path = os.path.join(STATIC_ROOT, 'img/logo-avante.png') plpc_logo = File(open(plpc_path, 'r')) avante_logo = File(open(avante_path, 'r')) for ct in cts: ct.base_logo = avante_logo ct.save() cdr = CertificateData(contract=plpc, type=types[0][0], certificate_template=ct, site_logo=plpc_logo, text=self.receipt_text) cdr.save() ct.pk = None ct.save() cdc = CertificateData(contract=plpc, type=types[1][0], certificate_template=ct, site_logo=plpc_logo, text=self.certificate_text) cdc.save()
agpl-3.0
Python
a0d3ae80a2f4f9ae76aaa4d672be460ce3a657d4
add command to populate change messages
dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq
corehq/apps/users/management/commands/add_location_change_message.py
corehq/apps/users/management/commands/add_location_change_message.py
from django.core.management.base import BaseCommand from django.db.models import Q from corehq.apps.users.audit.change_messages import UserChangeMessage from corehq.apps.users.models import UserHistory class Command(BaseCommand): help = "Add locations removed change messages on commcare user's User History records " \ "for https://github.com/dimagi/commcare-hq/pull/30253/commits/76996b5a129be4e95f5c5bedd0aba74c50088d15" def add_arguments(self, parser): parser.add_argument( '--save', action='store_true', dest='save', default=False, help="actually update records else just log", ) def handle(self, *args, **options): save = options['save'] # since we need locations removed, filter for update logs records = UserHistory.objects.filter( Q(changes__has_key='location_id') | Q(changes__has_key='assigned_location_ids'), user_type='CommCareUser', action=UserHistory.UPDATE, ) with open("add_location_change_message.csv", "w") as _file: for record in records: updated = False if 'location_id' in record.changes and record.changes['location_id'] is None: if 'location' not in record.change_messages: record.change_messages.update(UserChangeMessage.primary_location_removed()) updated = True if record.changes.get('assigned_location_ids') == []: if 'assigned_locations' not in record.change_messages: record.change_messages.update(UserChangeMessage.assigned_locations_info([])) updated = True if updated: _file.write( f"{record.pk},{record.user_id},{record.changes},{record.change_messages}\n" ) if save: record.save()
bsd-3-clause
Python
fb133e260722fd02cb6f14ede15dbdb1fdf91af7
Add gtk dependencies tests
mpsonntag/bulk-rename,mpsonntag/bulk-rename
test/test_dependencies.py
test/test_dependencies.py
""" Copyright (c) 2017, Michael Sonntag ([email protected]) All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted under the terms of the BSD License. See LICENSE file in the root of the project. """ import unittest class DependencyTest(unittest.TestCase): """ This class checks for non python gtk3 dependencies. This Class will be removed, it is testing how travis and conda can play nice with gtk3. """ def test_gi_dependency(self): has_error = False try: import gi except (ImportError, ValueError) as _: has_error = True self.assertFalse(has_error) def test_pygtkcompat(self): has_error = False try: import gi import pygtkcompat pygtkcompat.enable() pygtkcompat.enable_gtk(version='3.0') except (ImportError, ValueError) as _: has_error = True self.assertFalse(has_error) def test_gtk(self): has_error = False try: import gi import pygtkcompat pygtkcompat.enable() pygtkcompat.enable_gtk(version='3.0') import gtk except (ImportError, ValueError) as _: has_error = True self.assertFalse(has_error) def test_gobject(self): has_error = False try: import gi import pygtkcompat pygtkcompat.enable() pygtkcompat.enable_gtk(version='3.0') import gtk import gobject except (ImportError, ValueError) as _: has_error = True self.assertFalse(has_error)
bsd-3-clause
Python
c09356487360ec373c98ec50800a450a3966a60f
define prompt function
Upper-Polo/weather-app
lib.py
lib.py
# weather-app # lib.py # Classes and functions for weather-app. # Function definitions. # --------------------- # Prompt for user input. Accepts a prompt message we want to show. def prompt(msg): return input(msg)
mit
Python
e6bd5bbb3a46413b1ad164e0ef6ab66e89d9c95f
Add buildbot.py
steinwurf/stub,steinwurf/stub
buildbot.py
buildbot.py
#!/usr/bin/env python # encoding: utf-8 project_name = 'stub' def configure(options): pass def build(options): pass def run_tests(options): pass def coverage_settings(options): options['required_line_coverage'] = 80.0
bsd-3-clause
Python
97ea4f9019dcd5d4c01b4d5715297f25bc6aaf91
Create bytesize.py
stkyle/stk,stkyle/stk,stkyle/stk
bytesize.py
bytesize.py
# -*- coding: utf-8 -*- """ @author: stk """ import sys import itertools from collections import defaultdict _ver = sys.version_info #: Python 2.x? _is_py2 = (_ver[0] == 2) #: Python 3.x? _is_py3 = (_ver[0] == 3) if _is_py2: builtin_str = str bytes = str str = unicode basestring = basestring numeric_types = (int, long, float) integer_types = (int, long) elif _is_py3: builtin_str = str str = str bytes = bytes basestring = (str, bytes) numeric_types = (int, float) integer_types = (int,) class _CaseInsensitiveDict(dict): """CaseInsensitiveDict with aliasing.""" def _k(self, key): """get normalized key.""" k = key.upper() if isinstance(key, basestring) else key return self.get_alias(k) or k def __init__(self, *args, **kwargs): super(_CaseInsensitiveDict, self).__init__(*args, **kwargs) self._pseudonyms = defaultdict(list) self._convert_keys() def set_alias(self, key, aliaslist): self._pseudonyms[key] = set([key]+aliaslist) def get_alias(self, key): alias = None for k, aliaslist in iter(self._pseudonyms.items()): if key in aliaslist: alias = k break return alias def __getitem__(self, key): return super(_CaseInsensitiveDict, self).__getitem__(self._k(key)) def __setitem__(self, key, value): super(_CaseInsensitiveDict, self).__setitem__(self._k(key), value) def _convert_keys(self): """normalize keys set during dict constructor.""" for k in list(self.keys()): v = super(_CaseInsensitiveDict, self).pop(k) self.__setitem__(k, v) B = SZ_B,SUFFIX_B = 1<<0, 'B' KB = SZ_KB,SUFFIX_KB = 1<<10, 'KB' MB = SZ_MB,SUFFIX_MB = 1<<20, 'MB' GB = SZ_GB,SUFFIX_GB = 1<<30, 'GB' TB = SZ_TB,SUFFIX_TB = 1<<40, 'TB' PB = SZ_PB,SUFFIX_PB = 1<<50, 'PB' EB = SZ_EB,SUFFIX_EB = 1<<60, 'EB' ZB = SZ_ZB,SUFFIX_ZB = 1<<70, 'ZB' YB = SZ_YB,SUFFIX_YB = 1<<80, 'YB' _size_list = [B, KB, MB, GB, TB, PB, EB, ZB, YB] _size_names = [suffix for _,suffix in _size_list] _size_multipliers = [mult for mult,_ in _size_list] size_map = _CaseInsensitiveDict(zip(_size_names, _size_multipliers)) size_map.set_alias(SUFFIX_B, ['BYTE', 'BYTES', '']) size_map.set_alias(SUFFIX_KB, ['KILO', 'KILOS', 'KILOBYTE', 'KILOBYTES', 'K']) size_map.set_alias(SUFFIX_MB, ['MEGA', 'MEGAS', 'MEGABYTE', 'MEGABYTES', 'M']) size_map.set_alias(SUFFIX_GB, ['GIGA', 'GIGAS', 'GIGABYTE', 'GIGABYTES', 'G']) size_map.set_alias(SUFFIX_TB, ['TERA', 'TERAS', 'TERABYTE', 'TERABYTES', 'T']) size_map.set_alias(SUFFIX_PB, ['PETA', 'PETAS', 'PETABYTE', 'PETABYTES', 'P']) size_map.set_alias(SUFFIX_EB, ['EXA', 'EXABS', 'EXABYTE', 'EXABYTES', 'E']) size_map.set_alias(SUFFIX_ZB, ['ZETA', 'ZETTA', 'EXABYTE', 'EXABYTES', 'E']) size_map.set_alias(SUFFIX_YB, ['YOTA', 'YOTTA', 'YOTTABYTE','YOTTABYTES', 'Y']) class ByteSize(int): def as_unit(self, unit_suffix): dividend, divisor = self, size_map[unit_suffix] k = 1.0 if divisor>1 else 1 return dividend/(k*divisor) def __new__(cls, value): kv = [''.join(x) for _, x in itertools.groupby(str(value), key=str.isdigit)] if not kv or len(kv) > 2: raise ValueError('invalid ByteSize Val: %s' % str(value)) multiplicand, multiplier = (kv+['B'])[:2] multiplicand = int(multiplicand) multiplier = size_map[str(multiplier).strip()] bytesize = multiplicand*multiplier return int.__new__(cls, bytesize)
mit
Python
399cd799ae993412a6ad2455b8e11f4019aa9509
Add models admin
TailorDev/django-tailordev-biblio,TailorDev/django-tailordev-biblio,TailorDev/django-tailordev-biblio,TailorDev/django-tailordev-biblio
td_biblio/admin.py
td_biblio/admin.py
# -*- coding: utf-8 -*- from django.contrib import admin from .models import Author, Editor, Journal, Publisher, Entry, Collection class AbstractHumanAdmin(admin.ModelAdmin): list_display = ('last_name', 'first_name') class AuthorAdmin(AbstractHumanAdmin): pass class EditorAdmin(AbstractHumanAdmin): pass class JournalAdmin(admin.ModelAdmin): pass class PublisherAdmin(admin.ModelAdmin): pass class EntryAdmin(admin.ModelAdmin): list_display = ('title', 'type', 'publication_date', 'journal') list_filter = ('publication_date', 'journal', 'authors') date_hierarchy = 'publication_date' class CollectionAdmin(admin.ModelAdmin): pass admin.site.register(Author, AuthorAdmin) admin.site.register(Editor, EditorAdmin) admin.site.register(Journal, JournalAdmin) admin.site.register(Publisher, PublisherAdmin) admin.site.register(Entry, EntryAdmin) admin.site.register(Collection, CollectionAdmin)
mit
Python
6d3f6951d846c50fcc1ff011f9129a4e1e3f7de1
Add unit tests for BMI version of storm
mdpiper/storm,csdms-contrib/storm,mdpiper/storm,csdms-contrib/storm
testing/test_storm_bmi.py
testing/test_storm_bmi.py
#! /usr/bin/env python # # Tests for the BMI version of `storm`. # # Call with: # $ nosetests -sv # # Mark Piper ([email protected]) from nose.tools import * import os import shutil from subprocess import call # Global variables start_dir = os.getcwd() data_dir = os.path.join(start_dir, 'testing', 'data') input_file1 = os.path.join(data_dir, 'test1.in') input_file2 = os.path.join(data_dir, 'test2.in') build_dir = os.path.join(start_dir, 'build') exe = './bmi/storm' # Fixtures ------------------------------------------------------------- def setup_module(): ''' Called before any tests are performed. ''' print('*** BMI tests') os.mkdir(build_dir) os.chdir(build_dir) def teardown_module(): ''' Called after all tests have completed. ''' os.chdir(start_dir) shutil.rmtree(build_dir) # Tests ---------------------------------------------------------------- def test_configure(): ''' Test whether CMake executes successfully ''' call(['cmake', '..']) def test_compile(): ''' Test whether `storm` compiles ''' call(['make']) def test_without_input_file(): ''' Check that storm runs without an input file ''' r = call([exe]) assert_equal(r, 0) def test_with_singlestep_input_file(): ''' Check that storm runs with a one-step input file ''' r = call([exe, input_file1]) assert_equal(r, 0) def test_with_multistep_input_file(): ''' Check that storm runs with a multi-step input file ''' r = call([exe, input_file2]) assert_equal(r, 0)
mit
Python
9ef0e5e6dc50af7d5ccc27cc4d41abce72b51456
Create runcount.py
suzannerohrback/somaticCNVpipeline,suzannerohrback/somaticCNVpipeline
bin/runcount.py
bin/runcount.py
#!/usr/bin/python
mit
Python
671a5abc1f04930c749745c2ec0a59000d6e69a8
Add profile_rec script. (transplanted from ab55d87908f16cf7e2fac0a1938b280204a612bf)
alex/routes,mikepk/routes,bbangert/routes,webknjaz/routes,mikepk/pybald-routes
tests/test_functional/profile_rec.py
tests/test_functional/profile_rec.py
import profile import pstats import tempfile import os import time from routes import Mapper def bench_rec(n): m = Mapper() m.connect('', controller='articles', action='index') m.connect('admin', controller='admin/general', action='index') m.connect('admin/comments/article/:article_id/:action/:id', controller = 'admin/comments', action = None, id=None) m.connect('admin/trackback/article/:article_id/:action/:id', controller='admin/trackback', action=None, id=None) m.connect('admin/content/:action/:id', controller='admin/content') m.connect('xml/:action/feed.xml', controller='xml') m.connect('xml/articlerss/:id/feed.xml', controller='xml', action='articlerss') m.connect('index.rdf', controller='xml', action='rss') m.connect('articles', controller='articles', action='index') m.connect('articles/page/:page', controller='articles', action='index', requirements = {'page':'\d+'}) m.connect( 'articles/:year/:month/:day/page/:page', controller='articles', action='find_by_date', month = None, day = None, requirements = {'year':'\d{4}', 'month':'\d{1,2}','day':'\d{1,2}'}) m.connect('articles/category/:id', controller='articles', action='category') m.connect('pages/*name', controller='articles', action='view_page') m.create_regs(['content','admin/why', 'admin/user']) start = time.time() for x in range(1,n): a = m.match('/content') a = m.match('/content/list') a = m.match('/content/show/10') a = m.match('/admin/user') a = m.match('/admin/user/list') a = m.match('/admin/user/show/bbangert') a = m.match('/admin/user/show/bbangert/dude') a = m.match('/admin/why/show/bbangert') a = m.match('/content/show/10/20') a = m.match('/food') end = time.time() ts = time.time() for x in range(1,n): pass en = time.time() total = end-start-(en-ts) per_url = total / (n*10) print "Recognition\n" print "%s ms/url" % (per_url*1000) print "%s urls/s\n" % (1.00/per_url) def do_profile(cmd, globals, locals, sort_order, callers): fd, fn = tempfile.mkstemp() try: if hasattr(profile, 'runctx'): profile.runctx(cmd, globals, locals, fn) else: raise NotImplementedError( 'No profiling support under Python 2.3') stats = pstats.Stats(fn) stats.strip_dirs() # calls,time,cumulative and cumulative,calls,time are useful stats.sort_stats(*sort_order or ('cumulative', 'calls', 'time')) if callers: stats.print_callers(.3) else: stats.print_stats(.3) finally: os.remove(fn) def main(n=300): do_profile('bench_rec(%s)' % n, globals(), locals(), ('time', 'cumulative', 'calls'), None) if __name__ == '__main__': main()
mit
Python
5c5bf274c72ef67a3a2a2e5d6713df910026dcdb
Add hash plugin
Muzer/smartbot,thomasleese/smartbot-old,tomleese/smartbot,Cyanogenoid/smartbot
plugins/hash.py
plugins/hash.py
import hashlib import sys class Plugin: def on_command(self, bot, msg): if len(sys.argv) >= 2: algorithm = sys.argv[1] contents = " ".join(sys.argv[2:]) if not contents: contents = sys.stdin.read().strip() h = hashlib.new(algorithm) h.update(bytes(contents, "utf-8")) print(h.hexdigest()) else: print(self.on_help(bot)) def on_help(self, bot): return "Usage: hash <algorithm> <contents>"
mit
Python
086371f56748da9fb68acc4aaa10094b6cf24fcb
Revert "Remove pgjsonb returner unit tests"
saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt
tests/unit/returners/test_pgjsonb.py
tests/unit/returners/test_pgjsonb.py
# -*- coding: utf-8 -*- ''' tests.unit.returners.pgjsonb_test ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Unit tests for the PGJsonb returner (pgjsonb). ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging # Import Salt Testing libs from tests.support.mixins import LoaderModuleMockMixin from tests.support.unit import TestCase, skipIf from tests.support.mock import ( MagicMock, NO_MOCK, NO_MOCK_REASON, patch ) # Import Salt libs import salt.returners.pgjsonb as pgjsonb log = logging.getLogger(__name__) @skipIf(NO_MOCK, NO_MOCK_REASON) class PGJsonbCleanOldJobsTestCase(TestCase, LoaderModuleMockMixin): ''' Tests for the local_cache.clean_old_jobs function. ''' def setup_loader_modules(self): return {pgjsonb: {'__opts__': {'keep_jobs': 1, 'archive_jobs': 0}}} def test_clean_old_jobs_purge(self): ''' Tests that the function returns None when no jid_root is found. ''' connect_mock = MagicMock() with patch.object(pgjsonb, '_get_serv', connect_mock): with patch.dict(pgjsonb.__salt__, {'config.option': MagicMock()}): self.assertEqual(pgjsonb.clean_old_jobs(), None) def test_clean_old_jobs_archive(self): ''' Tests that the function returns None when no jid_root is found. ''' connect_mock = MagicMock() with patch.object(pgjsonb, '_get_serv', connect_mock): with patch.dict(pgjsonb.__salt__, {'config.option': MagicMock()}): with patch.dict(pgjsonb.__opts__, {'archive_jobs': 1}): self.assertEqual(pgjsonb.clean_old_jobs(), None)
apache-2.0
Python
077607b1b7fe705992c9f59f7dc94f2386aef4bb
add memcached
sassoftware/testutils,sassoftware/testutils,sassoftware/testutils
testutils/servers/memcache_server.py
testutils/servers/memcache_server.py
# # Copyright (c) SAS Institute Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import signal from testutils import sock_utils from testutils import subprocutil class MemcacheServer(object): def __init__(self, port=None): self.port = port if port else sock_utils.findPorts(num=1)[0] self.server = subprocutil.GenericSubprocess( args=['memcached', '-p', str(self.port), ], ) def start(self): self.server.start() sock_utils.tryConnect('::', self.port, abortFunc=self.server.check) def check(self): return self.server.check() def stop(self): self.server.kill(signum=signal.SIGQUIT, timeout=3) def reset(self): pass def getHostPort(self): return '127.0.0.1:%d' % self.port
apache-2.0
Python