commit
stringlengths
40
40
old_file
stringlengths
4
150
new_file
stringlengths
4
150
old_contents
stringlengths
0
3.26k
new_contents
stringlengths
1
4.43k
subject
stringlengths
15
501
message
stringlengths
15
4.06k
lang
stringclasses
4 values
license
stringclasses
13 values
repos
stringlengths
5
91.5k
diff
stringlengths
0
4.35k
5d98c4109322d3346609fdb1bf44cfd4a16dc94c
project_management/tests/test_main.py
project_management/tests/test_main.py
""" Test main pm functionality """ from cement.utils import test from pmtools import PmController, PmApp from test_default import config_defaults, PmTestApp class PmMainTest(test.CementTestCase): app_class = PmTestApp def test_1_help(self): app = self.make_app(argv=['--help']) app.setup() ...
Add tests for main app
Add tests for main app
Python
mit
SciLifeLab/scilifelab,kate-v-stepanova/scilifelab,senthil10/scilifelab,senthil10/scilifelab,SciLifeLab/scilifelab,jun-wan/scilifelab,SciLifeLab/scilifelab,jun-wan/scilifelab,senthil10/scilifelab,jun-wan/scilifelab,kate-v-stepanova/scilifelab,SciLifeLab/scilifelab,kate-v-stepanova/scilifelab,kate-v-stepanova/scilifelab,...
--- +++ @@ -0,0 +1,23 @@ +""" +Test main pm functionality +""" + +from cement.utils import test +from pmtools import PmController, PmApp +from test_default import config_defaults, PmTestApp + +class PmMainTest(test.CementTestCase): + app_class = PmTestApp + + def test_1_help(self): + app = self.make_app(...
68b5e3438b771afe4a70019a12fdd6d60a587c7e
py/1-bit-and-2-bit-characters.py
py/1-bit-and-2-bit-characters.py
class Solution(object): def isOneBitCharacter(self, bits): """ :type bits: List[int] :rtype: bool """ s0, s1 = True, False for i, b in enumerate(bits[:-1]): if b == 1: s0, s1 = s1 and bits[i - 1] == 1, s0 else: s...
Add py solution for 717. 1-bit and 2-bit Characters
Add py solution for 717. 1-bit and 2-bit Characters 717. 1-bit and 2-bit Characters: https://leetcode.com/problems/1-bit-and-2-bit-characters/
Python
apache-2.0
ckclark/leetcode,ckclark/leetcode,ckclark/leetcode,ckclark/leetcode,ckclark/leetcode,ckclark/leetcode
--- +++ @@ -0,0 +1,14 @@ +class Solution(object): + def isOneBitCharacter(self, bits): + """ + :type bits: List[int] + :rtype: bool + """ + s0, s1 = True, False + for i, b in enumerate(bits[:-1]): + if b == 1: + s0, s1 = s1 and bits[i - 1] == 1, s...
0738a6a4739db2a34659e469b4d262a971bc4938
heppyplotlib/errorcalc.py
heppyplotlib/errorcalc.py
"""Functions for calculating errors by combining different datasets.""" import math def asymmetric_hessian_error(value_lists): """Calculate the asymmetric hessian error from a list of datasets, where the first dataset stems from a PDF CV run.""" lows = [] highs = [] transposed_value_lists = zip(*v...
Add a calc function for asymmetric hessian errors
Add a calc function for asymmetric hessian errors
Python
mit
ebothmann/heppyplotlib
--- +++ @@ -0,0 +1,23 @@ +"""Functions for calculating errors by combining different datasets.""" + +import math + +def asymmetric_hessian_error(value_lists): + """Calculate the asymmetric hessian error from a list of datasets, + where the first dataset stems from a PDF CV run.""" + lows = [] + highs = []...
aeb657dae9decb0ea25361e530fdbe0399a1650e
tests/test_validators.py
tests/test_validators.py
""" test_validators ~~~~~~~~~~~~~~ Unittests for bundled validators. :copyright: 2007-2008 by James Crasta, Thomas Johansson. :license: MIT, see LICENSE.txt for details. """ from py.test import raises from wtforms.validators import ValidationError, length, url, not_empty, email, ip_addres...
Add first basic unittests using py.test
Add first basic unittests using py.test
Python
bsd-3-clause
mfa/wtforms-clone,maxcountryman/wtforms,mfa/wtforms-clone
--- +++ @@ -0,0 +1,60 @@ +""" + test_validators + ~~~~~~~~~~~~~~ + + Unittests for bundled validators. + + :copyright: 2007-2008 by James Crasta, Thomas Johansson. + :license: MIT, see LICENSE.txt for details. +""" + +from py.test import raises +from wtforms.validators import ValidationError, l...
a205a7032aa72111e1cb44f4989363b4e64be28a
tools/download-wheels.py
tools/download-wheels.py
#!/usr/bin/env python """ Download NumPy wheels from Anaconda staging area. """ import sys import os import re import shutil import argparse import urllib3 from bs4 import BeautifulSoup __version__ = '0.1' ANACONDA_INDEX = 'https://anaconda.org/multibuild-wheels-staging/numpy/files' ANACONDA_FILES = 'https://anacon...
Add tool for downloading release wheels from Anaconda.
ENH: Add tool for downloading release wheels from Anaconda. This is a simplified version of terryfy::wheel-uploader that has two advantages over the original: - It works with Anaconda where our wheels are now stored. - It is simplified to match the NumPY workflow.
Python
bsd-3-clause
mattip/numpy,pdebuyl/numpy,endolith/numpy,abalkin/numpy,mhvk/numpy,mhvk/numpy,charris/numpy,seberg/numpy,pbrod/numpy,mattip/numpy,numpy/numpy,pbrod/numpy,jakirkham/numpy,pdebuyl/numpy,seberg/numpy,pbrod/numpy,jakirkham/numpy,pdebuyl/numpy,simongibbons/numpy,charris/numpy,endolith/numpy,grlee77/numpy,grlee77/numpy,mhvk/...
--- +++ @@ -0,0 +1,79 @@ +#!/usr/bin/env python +""" +Download NumPy wheels from Anaconda staging area. + +""" +import sys +import os +import re +import shutil +import argparse + +import urllib3 +from bs4 import BeautifulSoup + +__version__ = '0.1' + +ANACONDA_INDEX = 'https://anaconda.org/multibuild-wheels-staging/n...
a49ace410d239a0e8ccce8b2780b0ff2eb9e6dfb
protogeni/test/consoleurl.py
protogeni/test/consoleurl.py
#! /usr/bin/env python # # Copyright (c) 2008-2014 University of Utah and the Flux Group. # # {{{GENIPUBLIC-LICENSE # # GENI Public License # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and/or hardware specification (the "Work") to # deal in the Work without rest...
Test script to get console url for a sliver.
Test script to get console url for a sliver.
Python
agpl-3.0
nmc-probe/emulab-nome,nmc-probe/emulab-nome,nmc-probe/emulab-nome,nmc-probe/emulab-nome,nmc-probe/emulab-nome,nmc-probe/emulab-nome,nmc-probe/emulab-nome,nmc-probe/emulab-nome,nmc-probe/emulab-nome,nmc-probe/emulab-nome,nmc-probe/emulab-nome
--- +++ @@ -0,0 +1,81 @@ +#! /usr/bin/env python +# +# Copyright (c) 2008-2014 University of Utah and the Flux Group. +# +# {{{GENIPUBLIC-LICENSE +# +# GENI Public License +# +# Permission is hereby granted, free of charge, to any person obtaining +# a copy of this software and/or hardware specification (the "Work...
93feee9e6d4221e6c876413055ee8be659ddeb36
pythran/tests/rosetta/yin_and_yang.py
pythran/tests/rosetta/yin_and_yang.py
# from http://rosettacode.org/wiki/Yin_and_yang#Python import math def yinyang(n=3): radii = [i * n for i in [1, 3, 6]] ranges = [list(range(-r, r+1)) for r in radii] squares = [[ (x,y) for x in rnge for y in rnge] for rnge in ranges] circles = [[ (x,y) for x,y in sqrpoints if math.hypot(x,y) <= radi...
Handle Y' rosetta code series
Handle Y' rosetta code series A very beautiful one, that once again raised a lot of errors...
Python
bsd-3-clause
pombredanne/pythran,pbrunet/pythran,hainm/pythran,artas360/pythran,pbrunet/pythran,serge-sans-paille/pythran,serge-sans-paille/pythran,pombredanne/pythran,pbrunet/pythran,hainm/pythran,pombredanne/pythran,hainm/pythran,artas360/pythran,artas360/pythran
--- +++ @@ -0,0 +1,25 @@ +# from http://rosettacode.org/wiki/Yin_and_yang#Python +import math +def yinyang(n=3): + radii = [i * n for i in [1, 3, 6]] + ranges = [list(range(-r, r+1)) for r in radii] + squares = [[ (x,y) for x in rnge for y in rnge] + for rnge in ranges] + circles = [[ (x,y) for x,y in sqrpoint...
39bb9d8408cde59525a576119d28399c49e092f9
mars.py
mars.py
import requests rover_url = 'https://api.nasa.gov/mars-photos/api/v1/rovers/curiosity/photos' parameters = {'api_key': 'DEMO_KEY', 'sol': '1324'} response = requests.get(rover_url, params=parameters).json() print(len(response['photos'])) for photo in response['photos']: print(photo['img_src'])
Print out image URLs from Mars
Print out image URLs from Mars
Python
mit
sagnew/PhoningHome
--- +++ @@ -0,0 +1,10 @@ +import requests + +rover_url = 'https://api.nasa.gov/mars-photos/api/v1/rovers/curiosity/photos' +parameters = {'api_key': 'DEMO_KEY', 'sol': '1324'} + +response = requests.get(rover_url, params=parameters).json() + +print(len(response['photos'])) +for photo in response['photos']: + print...
a066aba57d828d25a692ae1dda31797ea7046ddf
test.py
test.py
from ringcentral import SDK from config import USERNAME, EXTENSION, PASSWORD, APP_KEY, APP_SECRET, SERVER # Before you start # Rename credentials-sample.ini to credentials.ini # Edit credentials.ini with information about your app and your creds sdk = SDK(APP_KEY, APP_SECRET, SERVER) platform = sdk.platform() platfor...
Test file to get started with APIs
Test file to get started with APIs
Python
mit
ringcentral/ringcentral-python
--- +++ @@ -0,0 +1,13 @@ +from ringcentral import SDK +from config import USERNAME, EXTENSION, PASSWORD, APP_KEY, APP_SECRET, SERVER + +# Before you start +# Rename credentials-sample.ini to credentials.ini +# Edit credentials.ini with information about your app and your creds + +sdk = SDK(APP_KEY, APP_SECRET, SERVER...
f03734d273914ab5ce31cf0e28f86732ddb35b0c
tests/test_casefold.py
tests/test_casefold.py
# -*- coding: utf-8 -*- from irc3.testing import BotTestCase class TestCasefold(BotTestCase): config = dict(includes=['irc3.plugins.casefold']) def test_ascii(self): bot = self.callFTU(server_config={'CASEMAPPING': 'ascii'}) self.assertEquals(bot.casefold('#testchan\\123[]56'), ...
Add testcase for casefold plugin
Add testcase for casefold plugin
Python
mit
mrhanky17/irc3,mrhanky17/irc3,gawel/irc3
--- +++ @@ -0,0 +1,27 @@ +# -*- coding: utf-8 -*- +from irc3.testing import BotTestCase + + +class TestCasefold(BotTestCase): + + config = dict(includes=['irc3.plugins.casefold']) + + def test_ascii(self): + bot = self.callFTU(server_config={'CASEMAPPING': 'ascii'}) + + self.assertEquals(bot.casef...
980cf50a2bf6c42cbd689c1b7e1abcadd45f0f1e
tests/test_frontend.py
tests/test_frontend.py
# -*- coding: utf-8 -*- # # This file is part of pypuppetdbquery. # Copyright © 2016 Chris Boot <bootc@bootc.net> # # 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.or...
Add unit tests for pypuppetdbquery.parse()
Add unit tests for pypuppetdbquery.parse()
Python
apache-2.0
bootc/pypuppetdbquery
--- +++ @@ -0,0 +1,65 @@ +# -*- coding: utf-8 -*- +# +# This file is part of pypuppetdbquery. +# Copyright © 2016 Chris Boot <bootc@bootc.net> +# +# 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 Lice...
443456f94a92f1844b99965ffcf3679bd939d42c
tests/test_moving_eddies.py
tests/test_moving_eddies.py
from parcels import Particle, ParticleSet, JITParticle, JITParticleSet from parcels import NEMOGrid, ParticleFile, AdvectionRK4 from argparse import ArgumentParser pclasses = {'scipy': (Particle, ParticleSet), 'jit': (JITParticle, JITParticleSet)} def moving_eddies(grid, npart, mode='jit', verbose=False...
Add simple test setup that follows two particles
MovingEddies: Add simple test setup that follows two particles
Python
mit
OceanPARCELS/parcels,OceanPARCELS/parcels
--- +++ @@ -0,0 +1,66 @@ +from parcels import Particle, ParticleSet, JITParticle, JITParticleSet +from parcels import NEMOGrid, ParticleFile, AdvectionRK4 +from argparse import ArgumentParser + + +pclasses = {'scipy': (Particle, ParticleSet), + 'jit': (JITParticle, JITParticleSet)} + + +def moving_eddies(g...
5735595d4a465b2cc9f52bdd1fc524c0d26d60cb
tests/test_task_statuses.py
tests/test_task_statuses.py
from taiga.requestmaker import RequestMaker, RequestMakerException from taiga.models.base import InstanceResource, ListResource from taiga.models import TaskStatus, TaskStatuses from taiga import TaigaAPI import taiga.exceptions import json import requests import unittest from mock import patch from .tools import creat...
Add tests for task statuses
Add tests for task statuses
Python
mit
bameda/python-taiga,mlq/python-taiga,jespino/python-taiga,bameda/python-taiga,mlq/python-taiga,erikw/python-taiga,jespino/python-taiga,erikw/python-taiga,nephila/python-taiga
--- +++ @@ -0,0 +1,24 @@ +from taiga.requestmaker import RequestMaker, RequestMakerException +from taiga.models.base import InstanceResource, ListResource +from taiga.models import TaskStatus, TaskStatuses +from taiga import TaigaAPI +import taiga.exceptions +import json +import requests +import unittest +from mock i...
96ed9d514541b18419b97d5187237f6fdba7b3c7
tohu/v3/dependency_graph.py
tohu/v3/dependency_graph.py
import logging import re from graphviz import Digraph from IPython.display import SVG __all__ = ['DependencyGraph'] logger = logging.getLogger('tohu') class DependencyGraph: NODE_ATTR = dict(shape='box', style='filled', fillcolor='white') def __init__(self, *, scale=1.0, name=None, graph_attr=None): ...
Add class to support dependency graph visualisation
Add class to support dependency graph visualisation
Python
mit
maxalbert/tohu
--- +++ @@ -0,0 +1,53 @@ +import logging +import re +from graphviz import Digraph +from IPython.display import SVG + +__all__ = ['DependencyGraph'] + +logger = logging.getLogger('tohu') + + +class DependencyGraph: + + NODE_ATTR = dict(shape='box', style='filled', fillcolor='white') + + def __init__(self, *, sca...
b54f1755d6f792a97eaa06a83cadbb72d045402f
testtube/decorators.py
testtube/decorators.py
class RequireModule(object): """Decorator that raises import error if specified module isn't found.""" def __init__(self, module_name): self.module_name = module_name def _require_module(self): try: __import__(self.module_name) except ImportError: raise Impo...
Add a RequireModule decorator for use by helpers
Add a RequireModule decorator for use by helpers This eliminates the need for _require in helpers.
Python
mit
blaix/testtube,thomasw/testtube,beck/testtube
--- +++ @@ -0,0 +1,19 @@ +class RequireModule(object): + """Decorator that raises import error if specified module isn't found.""" + + def __init__(self, module_name): + self.module_name = module_name + + def _require_module(self): + try: + __import__(self.module_name) + excep...
55ee1a6609a5dfd922cce78fd4faeb64cd2d3c7d
run.py
run.py
"""Hacked-together development server for feedreader. Runs the feedreader server under the /api prefix, serves URI not containing a dot public/index.html, servers everything else to public. """ import tornado.ioloop import tornado.web import feedreader.main class PrefixedFallbackHandler(tornado.web.FallbackHandler...
Add new dev server to replace tape
Add new dev server to replace tape
Python
mit
tdryer/feeder,tdryer/feeder
--- +++ @@ -0,0 +1,44 @@ +"""Hacked-together development server for feedreader. + +Runs the feedreader server under the /api prefix, serves URI not containing a +dot public/index.html, servers everything else to public. +""" + +import tornado.ioloop +import tornado.web + +import feedreader.main + + +class PrefixedFal...
3764459fb9a8995a1476cc7a36c88a98dc9d4685
scipy-example/fitsincos.py
scipy-example/fitsincos.py
""" Given the set of points generated by f(x) = 0.5 * cos(2 * x) + 2 * sin(0.5 * x) with some noise, use Levenberg-Marquardt algorithm to find the model of the form f(x) = a * cos(b * x) + b * sin(a * x) to fit all the points. """ import numpy as np import scipy.optimize as scipy_opt def sincos_func(x_data, a, b): ...
Add scipy sin cos example
Add scipy sin cos example
Python
mit
truongduy134/levenberg-marquardt,truongduy134/levenberg-marquardt,truongduy134/levenberg-marquardt
--- +++ @@ -0,0 +1,46 @@ +""" Given the set of points generated by +f(x) = 0.5 * cos(2 * x) + 2 * sin(0.5 * x) with some noise, +use Levenberg-Marquardt algorithm to find the model of the form +f(x) = a * cos(b * x) + b * sin(a * x) to fit all the points. +""" + +import numpy as np +import scipy.optimize as scipy_opt...
4091fa177dcaeaac0a36fefee8f5b3cac4c6202b
oscar/apps/dashboard/catalogue/fields.py
oscar/apps/dashboard/catalogue/fields.py
from django import forms from django.template import Context, Template class ProductImageMultipleChoiceField(forms.ModelMultipleChoiceField): """ Field that renders a ProductImage as a thumbnail and text instead of just as text. """ # Using the low-level Template API instead of storing it in a sep...
Add field to render image many-to-many as checkboxes with thumbnails.
Add field to render image many-to-many as checkboxes with thumbnails.
Python
bsd-3-clause
sonofatailor/django-oscar,sonofatailor/django-oscar,sonofatailor/django-oscar,sonofatailor/django-oscar
--- +++ @@ -0,0 +1,33 @@ +from django import forms +from django.template import Context, Template + +class ProductImageMultipleChoiceField(forms.ModelMultipleChoiceField): + """ + Field that renders a ProductImage as a thumbnail and text instead of + just as text. + """ + + # Using the low-level Templa...
767f241a930ac0dea5fd3cb7fcb3dc6837d5648b
tests/test_cmatrices.py
tests/test_cmatrices.py
# to run this test, from directory above: # setenv PYTHONPATH /path/to/pyradiomics/radiomics # nosetests --nocapture -v tests/test_features.py import logging from nose_parameterized import parameterized import numpy import six from radiomics import cMatsEnabled, getFeatureClasses from testUtils import custom_name_fu...
Add testing for C extensions
ENH: Add testing for C extensions Testing compares matrices calculated by python algorithms to those calculated by the C extension. Tests the calculation of surface area in a similar manner. Testing fails if C extension is not available or if any element in the matrix differs more than 1e-3 from the corresponding elem...
Python
bsd-3-clause
Radiomics/pyradiomics,Radiomics/pyradiomics,Radiomics/pyradiomics,Radiomics/pyradiomics
--- +++ @@ -0,0 +1,72 @@ +# to run this test, from directory above: +# setenv PYTHONPATH /path/to/pyradiomics/radiomics +# nosetests --nocapture -v tests/test_features.py + +import logging + +from nose_parameterized import parameterized +import numpy +import six + +from radiomics import cMatsEnabled, getFeatureClasse...
c49f193c1ad516bfec52eab64c7dc2508d35f53d
app/grandchallenge/retina_core/migrations/0002_auto_20190225_1228.py
app/grandchallenge/retina_core/migrations/0002_auto_20190225_1228.py
# Generated by Django 2.1.7 on 2019-02-25 12:28 from django.db import migrations from django.contrib.auth.models import User, Group from django.conf import settings from guardian.shortcuts import assign_perm, remove_perm # Permission types PERMISSION_TYPES = ("view", "add", "change", "delete") # Existing annotation ...
Add migration for setting retina annotation permissions
Add migration for setting retina annotation permissions
Python
apache-2.0
comic/comic-django,comic/comic-django,comic/comic-django,comic/comic-django,comic/comic-django
--- +++ @@ -0,0 +1,72 @@ +# Generated by Django 2.1.7 on 2019-02-25 12:28 + +from django.db import migrations +from django.contrib.auth.models import User, Group +from django.conf import settings +from guardian.shortcuts import assign_perm, remove_perm + +# Permission types +PERMISSION_TYPES = ("view", "add", "change...
2a25e583933325c032c53e885b6dcac04e8061bb
tests/queue/test_file.py
tests/queue/test_file.py
''' Unit tests for `tilequeue.queue.file`. ''' from tilequeue.queue import OutputFileQueue from tilequeue import tile from ModestMaps.Core import Coordinate import unittest import StringIO class TestQueue(unittest.TestCase): def setUp(self): self.test_tile_coords = [ (0, 0, 0), (1...
Add unit tests for queue.file
Add unit tests for queue.file tests/queue/test_file.py -Add a bunch of `unittest` unit tests for most/all of the functions in `tilequeue.queue.file`, as per all of the recent work there.
Python
mit
tilezen/tilequeue,mapzen/tilequeue
--- +++ @@ -0,0 +1,82 @@ +''' +Unit tests for `tilequeue.queue.file`. +''' + +from tilequeue.queue import OutputFileQueue +from tilequeue import tile +from ModestMaps.Core import Coordinate +import unittest +import StringIO + +class TestQueue(unittest.TestCase): + + def setUp(self): + self.test_tile_coords ...
f89ba4c5a9ada2ce84c9d46d6100fc5aec13f758
examples/stories/movie_lister/apps_db_csv.py
examples/stories/movie_lister/apps_db_csv.py
"""A naive example of dependency injection in Python. Example implementation of dependency injection in Python from Martin Fowler's article about dependency injection and inversion of control: http://www.martinfowler.com/articles/injection.html This mini application uses ``movies`` library, that is configured to wor...
Add example of catalog copying into MovieLister example
Add example of catalog copying into MovieLister example
Python
bsd-3-clause
rmk135/dependency_injector,rmk135/objects,ets-labs/python-dependency-injector,ets-labs/dependency_injector
--- +++ @@ -0,0 +1,76 @@ +"""A naive example of dependency injection in Python. + +Example implementation of dependency injection in Python from Martin Fowler's +article about dependency injection and inversion of control: + +http://www.martinfowler.com/articles/injection.html + +This mini application uses ``movies``...
7fc5855aa3aa7e554aeb6faf9ae05567c7a4910c
monitor_website_status.py
monitor_website_status.py
#!/usr/bin/python import urllib2 from BeautifulSoup import BeautifulSoup from StringIO import StringIO from datetime import datetime, timedelta import subprocess WEBSITE = 'http://www.newsdiffs.org/browse/' MAX_TIME = timedelta(hours=1) EMAILS = 'ecprice@mit.edu jenny8lee@gmail.com price@mit.edu'.split() def send_al...
Add monitor script for website.
Add monitor script for website.
Python
mit
bjowi/newsdiffs,flupzor/newsdiffs,amandabee/newsdiffs,flupzor/bijgeschaafd,bjowi/newsdiffs,flupzor/bijgeschaafd,catcosmo/newsdiffs,flupzor/newsdiffs,catcosmo/newsdiffs,catcosmo/newsdiffs,flupzor/bijgeschaafd,COLABORATI/newsdiffs,COLABORATI/newsdiffs,flupzor/newsdiffs,bjowi/newsdiffs,flupzor/bijgeschaafd,flupzor/newsdif...
--- +++ @@ -0,0 +1,44 @@ +#!/usr/bin/python + +import urllib2 +from BeautifulSoup import BeautifulSoup +from StringIO import StringIO +from datetime import datetime, timedelta +import subprocess + +WEBSITE = 'http://www.newsdiffs.org/browse/' +MAX_TIME = timedelta(hours=1) +EMAILS = 'ecprice@mit.edu jenny8lee@gmail.c...
1340ff25daef84e66841476eaff9446886cda0b5
minsem.py
minsem.py
#!/usr/bin/env python from collections import OrderedDict class DataToken: def __init__(self, line: str): ( self.offset, self.word, self.lowercase_lemma, self.pos_tag, self.mwe_tag, self.parent_offset, self.strength, ...
Implement reading from data files
Implement reading from data files Reads files and stores contents in new DataSentence/DataToken constructions.
Python
mit
pdarragh/MinSem
--- +++ @@ -0,0 +1,79 @@ +#!/usr/bin/env python + +from collections import OrderedDict + + +class DataToken: + def __init__(self, line: str): + ( + self.offset, + self.word, + self.lowercase_lemma, + self.pos_tag, + self.mwe_tag, + self.paren...
d95181d8de55c77e10aca390a40074d5ef0a7bb2
angr/procedures/java_lang/string_equals.py
angr/procedures/java_lang/string_equals.py
from ..java import JavaSimProcedure import logging l = logging.getLogger('angr.procedures.java.string.equals') class StringEquals(JavaSimProcedure): NO_RET = True __provides__ = ( ("java.lang.String", "equals(java.lang.String)"), ) def run(self, str_1, str_2): l.info("Called SimPro...
Add dummy Simprocedure for java.lang.string.equals
Add dummy Simprocedure for java.lang.string.equals
Python
bsd-2-clause
schieb/angr,schieb/angr,iamahuman/angr,angr/angr,angr/angr,schieb/angr,angr/angr,iamahuman/angr,iamahuman/angr
--- +++ @@ -0,0 +1,16 @@ +from ..java import JavaSimProcedure +import logging + +l = logging.getLogger('angr.procedures.java.string.equals') + +class StringEquals(JavaSimProcedure): + + NO_RET = True + + __provides__ = ( + ("java.lang.String", "equals(java.lang.String)"), + ) + + def run(self, str...
390430b676d88dbe26d28a5551257b3013aee19b
copy_selected_photos.py
copy_selected_photos.py
import pandas as pd def main(): # create a directory for selected photos print 'mkdir photos_las_vegas_food_drinks' # load data about selected photos selected_photos_business = pd.read_csv('las_vegas_food_drinks.csv') # for each photo generate copy command for photo_id in selected_ph...
Add copying of selected photos to a new directory
Add copying of selected photos to a new directory
Python
mit
aysent/yelp-photo-explorer
--- +++ @@ -0,0 +1,16 @@ +import pandas as pd + +def main(): + + # create a directory for selected photos + print 'mkdir photos_las_vegas_food_drinks' + + # load data about selected photos + selected_photos_business = pd.read_csv('las_vegas_food_drinks.csv') + + # for each photo generate copy c...
868c29b23d74ef2dced64eed545995d43f0256ef
registries/serializers.py
registries/serializers.py
from rest_framework import serializers from registries.models import Organization from gwells.models import ProvinceState class DrillerListSerializer(serializers.ModelSerializer): province_state = serializers.ReadOnlyField() class Meta: model = Organization # Using all fields for now ...
Add simple driller list serializer
Add simple driller list serializer
Python
apache-2.0
rstens/gwells,rstens/gwells,bcgov/gwells,rstens/gwells,rstens/gwells,bcgov/gwells,bcgov/gwells,bcgov/gwells
--- +++ @@ -0,0 +1,26 @@ +from rest_framework import serializers +from registries.models import Organization +from gwells.models import ProvinceState + +class DrillerListSerializer(serializers.ModelSerializer): + province_state = serializers.ReadOnlyField() + + class Meta: + model = Organization + + ...
dd0fd45f1324696144267da78a6fe62a8fc346cf
lpthw/ex24.py
lpthw/ex24.py
print "Let's practice everything." print 'You\'d need to know \'bout escapes with \\ that do \n newlines and \t tabs." poem = """ \t the lovely world wtih logic so firmly planted cannot discern \n the needs of love nor comprehend passion from intuition and requires an explanation \n\t\twhere there is none. """ print ...
Add work for Exercise 24
Add work for Exercise 24
Python
mit
jaredmanning/learning,jaredmanning/learning
--- +++ @@ -0,0 +1,43 @@ +print "Let's practice everything." +print 'You\'d need to know \'bout escapes with \\ that do \n newlines and \t tabs." + +poem = """ +\t the lovely world +wtih logic so firmly planted +cannot discern \n the needs of love +nor comprehend passion from intuition +and requires an explanation +\...
610396a7caa1c23532369d4bc5e382dbc21cba60
tests/chainer_tests/training_tests/extensions_tests/test_plot_report.py
tests/chainer_tests/training_tests/extensions_tests/test_plot_report.py
import unittest from chainer.training import extensions class TestPlotReport(unittest.TestCase): def test_available(self): try: from matplotlib import pyplot # NOQA available = True except ImportError: available = False self.assertEqual(extensions.Pl...
Fix PlotReport.available and write test
Fix PlotReport.available and write test
Python
mit
ktnyt/chainer,hvy/chainer,jnishi/chainer,anaruse/chainer,chainer/chainer,okuta/chainer,cupy/cupy,niboshi/chainer,cupy/cupy,ysekky/chainer,niboshi/chainer,keisuke-umezawa/chainer,tkerola/chainer,okuta/chainer,chainer/chainer,ktnyt/chainer,rezoo/chainer,wkentaro/chainer,jnishi/chainer,aonotas/chainer,keisuke-umezawa/chai...
--- +++ @@ -0,0 +1,15 @@ +import unittest + +from chainer.training import extensions + + +class TestPlotReport(unittest.TestCase): + + def test_available(self): + try: + from matplotlib import pyplot # NOQA + available = True + except ImportError: + available = False...
4dd4557796acca3046806a9504d8d6bcb78ca16d
test/test_UrbanDict.py
test/test_UrbanDict.py
#!/usr/bin/env python ### # Copyright (c) 2004, Kevin Murphy # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, # t...
Test cases for UrbanDict plugin
Test cases for UrbanDict plugin
Python
bsd-3-clause
kblin/supybot-gsoc,ProgVal/Limnoria-test,raboof/supybot,Ban3/Limnoria,Ban3/Limnoria,jeffmahoney/supybot,mazaclub/mazabot-core,buildbot/supybot,mazaclub/mazabot-core,frumiousbandersnatch/supybot-code,prashantpawar/supybot-rothbot,ProgVal/Limnoria-test,haxwithaxe/supybot
--- +++ @@ -0,0 +1,50 @@ +#!/usr/bin/env python + +### +# Copyright (c) 2004, Kevin Murphy +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# +# * Redistributions of source code must retai...
263194056dbd749681f36823b77bb0ba2c76e379
tests/test_es.py
tests/test_es.py
# -*- coding: utf-8 -*- """Elasticsearch client test cases.""" import unittest from sqlalchemy import types as sql_types from esis.es import Mapping class MappingTest(unittest.TestCase): """Test translation from SQL schema to Elasticsearch mapping.""" def test_mapping_types(self): """Test mapping...
Add Elasticsearch mapping test case
Add Elasticsearch mapping test case
Python
mit
jcollado/esis
--- +++ @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +"""Elasticsearch client test cases.""" + +import unittest + +from sqlalchemy import types as sql_types + +from esis.es import Mapping + + +class MappingTest(unittest.TestCase): + + """Test translation from SQL schema to Elasticsearch mapping.""" + + def test_ma...
32f48a7f16fe5657ac02ea5c8521ecb068e4ac77
pontoon/base/migrations/0013_add_en_US.py
pontoon/base/migrations/0013_add_en_US.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations def add_back_source_locales(apps, schema_editor): Locale = apps.get_model('base', 'Locale') Locale.objects.create( code='en', name='English', nplurals=2, plural_rule='(n !=...
Add en and en-US locales back to locale list.
Add en and en-US locales back to locale list. Both are source locales and shouldn't have been removed.
Python
bsd-3-clause
mozilla/pontoon,Osmose/pontoon,mastizada/pontoon,mathjazz/pontoon,vivekanand1101/pontoon,sudheesh001/pontoon,mastizada/pontoon,participedia/pontoon,participedia/pontoon,jotes/pontoon,m8ttyB/pontoon,yfdyh000/pontoon,sudheesh001/pontoon,jotes/pontoon,vivekanand1101/pontoon,Osmose/pontoon,Osmose/pontoon,sudheesh001/pontoo...
--- +++ @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +from __future__ import unicode_literals + +from django.db import models, migrations + + +def add_back_source_locales(apps, schema_editor): + Locale = apps.get_model('base', 'Locale') + Locale.objects.create( + code='en', + name='English', + ...
82943db5942f6d0749776efb1b1acf928af97a1c
example.py
example.py
#!/usr/bin/env python3 import numpy as np import rust_sorting as rs array = np.zeros((5,), dtype=np.int8) rs.quicksort(array) print("Python done!")
Call quicksort from Python; it works!
Call quicksort from Python; it works!
Python
bsd-3-clause
nbigaouette/rust-sorting,nbigaouette/rust-sorting,nbigaouette/rust-sorting
--- +++ @@ -0,0 +1,12 @@ +#!/usr/bin/env python3 + +import numpy as np +import rust_sorting as rs + + +array = np.zeros((5,), dtype=np.int8) + + +rs.quicksort(array) + +print("Python done!")
b12dd992da93d43e5acf1d42cee0f7d34f8367bf
spam/tests/fake_params.py
spam/tests/fake_params.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import os DATASET_PATH = os.path.join( os.path.dirname(__file__), 'test_dataset', ) DATASET_SUBDIRS = [ { 'name': 'enron1', 'total_count': 5, 'ham_count': 3, 'spam_count': 2, 'path': os.path.join(DATASET_PATH, 'enron1'...
Add fake params from test.
Add fake params from test.
Python
mit
benigls/spam,benigls/spam
--- +++ @@ -0,0 +1,47 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +import os + + +DATASET_PATH = os.path.join( + os.path.dirname(__file__), + 'test_dataset', +) + +DATASET_SUBDIRS = [ + { + 'name': 'enron1', + 'total_count': 5, + 'ham_count': 3, + 'spam_count': 2, + ...
0cdf73f158e425db0ab65d70966b18ef9f4af1c6
test/test_services_view.py
test/test_services_view.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2015-2016: # Matthieu Estrada, ttamalfor@gmail.com # # This file is part of (AlignakApp). # # (AlignakApp) 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 Sof...
Add unit tests for services_view.py
Add unit tests for services_view.py
Python
agpl-3.0
Alignak-monitoring-contrib/alignak-app,Alignak-monitoring-contrib/alignak-app
--- +++ @@ -0,0 +1,61 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +# Copyright (c) 2015-2016: +# Matthieu Estrada, ttamalfor@gmail.com +# +# This file is part of (AlignakApp). +# +# (AlignakApp) is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero General Public L...
78e84abea9b0cc41bdb1aa8b9ea5c9953a37941d
bdbcontrib/contrib_exp.py
bdbcontrib/contrib_exp.py
from bayeslite.shell.hook import bayesdb_shell_cmd from bdbcontrib.general_utils import ArgparseError, ArgumentParser import bdbexp experiments = { 'haystacks' : bdbexp.haystacks, 'hyperparams' : bdbexp.hyperparams, 'infer' : bdbexp.infer, 'kl_divergence' : bdbexp.kl_divergence, 'permute' : bdbexp...
Add hooks for inference experiments.
Add hooks for inference experiments.
Python
apache-2.0
probcomp/bdbcontrib,probcomp/bdbcontrib
--- +++ @@ -0,0 +1,48 @@ +from bayeslite.shell.hook import bayesdb_shell_cmd +from bdbcontrib.general_utils import ArgparseError, ArgumentParser + +import bdbexp + +experiments = { + 'haystacks' : bdbexp.haystacks, + 'hyperparams' : bdbexp.hyperparams, + 'infer' : bdbexp.infer, + 'kl_divergence' : bdbexp....
c860d536710d2d9546924b00aef7de4f516e38a5
tools/fixup_io_tilegrid.py
tools/fixup_io_tilegrid.py
import database import tiles import json from os import path """ Despite Lattice assigning them the same tile type; "odd" and "even" top/left/right IO locations have slightly different routing - swapped output tristate and data This script fixes this by patching tile names """ for f, d in [("LIFCL", "LIFCL-40")]: ...
Add tool to fix IO tilegrid
Add tool to fix IO tilegrid Signed-off-by: David Shah <bfcdf3e6ca6cef45543bfbb57509c92aec9a39fb@ds0.me>
Python
isc
gatecat/prjoxide,gatecat/prjoxide,gatecat/prjoxide
--- +++ @@ -0,0 +1,71 @@ +import database +import tiles +import json +from os import path + +""" +Despite Lattice assigning them the same tile type; "odd" and "even" top/left/right IO +locations have slightly different routing - swapped output tristate and data + +This script fixes this by patching tile names +""" + ...
c0f06b64c15d74be26be2cd9e6d593e5c5cae2a9
tools/xml_select_minmax.py
tools/xml_select_minmax.py
#! /usr/bin/python3 import sys import argparse import xml_utils as u import os from argparse import RawTextHelpFormatter ##---------------------------------------------------------- ## for each label that has more than the mininum count, select the ## largest subset less than the maxinum count. ## writes out to...
Select a subset for each label. If the label image count is greater than min, return the greatest number of images less than or equal to the max. The images will be evenly distributed across years, seasons and days.
Select a subset for each label. If the label image count is greater than min, return the greatest number of images less than or equal to the max. The images will be evenly distributed across years, seasons and days.
Python
mit
hypraptive/bearid,hypraptive/bearid,hypraptive/bearid
--- +++ @@ -0,0 +1,51 @@ +#! /usr/bin/python3 + +import sys +import argparse +import xml_utils as u +import os +from argparse import RawTextHelpFormatter + +##---------------------------------------------------------- +## for each label that has more than the mininum count, select the +## largest subset less than ...
5e1c8f5bbe3cd8927b60a08b2784f7d2ea8263f2
src/backend/live_classify_local_camera.py
src/backend/live_classify_local_camera.py
import openface import numpy as np import os import cv2 import pickle id_name = ["Alec", "Greg", "Phong", "Emil"] def classify(aligned_face, net, clf, le): rep = net.forward(aligned_face) predictions = clf.predict_proba(rep.reshape((1, len(rep)))).ravel() maxI = np.argmax(predictions) person = le.inv...
Use the model to classify face in local camera.
Use the model to classify face in local camera.
Python
apache-2.0
xphongvn/smart-attendance-system-ta,xphongvn/smart-attendance-system-ta,xphongvn/smart-attendance-system-ta
--- +++ @@ -0,0 +1,65 @@ +import openface +import numpy as np +import os +import cv2 +import pickle + +id_name = ["Alec", "Greg", "Phong", "Emil"] + + +def classify(aligned_face, net, clf, le): + rep = net.forward(aligned_face) + predictions = clf.predict_proba(rep.reshape((1, len(rep)))).ravel() + maxI = np...
d2c83bf007a36a47754ec862d592c7c97b3145b9
plugins/callbacks/timer.py
plugins/callbacks/timer.py
import os import datetime from datetime import datetime, timedelta class CallbackModule(object): """ This callback module tells you how long your plays ran for. """ start_time = datetime.now() def __init__(self): start_time = datetime.now() print "Timer plugin is active." ...
Add simple plugin that times ansible-playbook runs.
Add simple plugin that times ansible-playbook runs.
Python
mit
thaim/ansible,thaim/ansible
--- +++ @@ -0,0 +1,27 @@ +import os +import datetime +from datetime import datetime, timedelta + + +class CallbackModule(object): + """ + This callback module tells you how long your plays ran for. + """ + + start_time = datetime.now() + + def __init__(self): + start_time = datetime.now() + ...
f4e0254eada3a6dd3aaa794926c5cc82e993b180
setup/bin/swc-nano-installer.py
setup/bin/swc-nano-installer.py
#!/usr/bin/env python """Software Carpentry Nano Installer for Windows Installs nano and makes it the default editor in msysgit To use: 1. Install Python 2. Install msysgit http://code.google.com/p/msysgit/downloads/list?q=full+installer+official+git 3. Run swc_nano_installer.py You should be able to simply d...
Add a Nano installer for Windows
Add a Nano installer for Windows 1. Downloads and installs Nano into the users home directory 2. Adds Nano to the path 3. Makes Nano the default editor
Python
bsd-2-clause
selimnairb/2014-02-25-swctest,selimnairb/2014-02-25-swctest,selimnairb/2014-02-25-swctest,selimnairb/2014-02-25-swctest,selimnairb/2014-02-25-swctest,selimnairb/2014-02-25-swctest
--- +++ @@ -0,0 +1,73 @@ +#!/usr/bin/env python + +"""Software Carpentry Nano Installer for Windows + +Installs nano and makes it the default editor in msysgit + +To use: + +1. Install Python +2. Install msysgit + http://code.google.com/p/msysgit/downloads/list?q=full+installer+official+git +3. Run swc_nano_install...
910793402dccc02c853618f93917c5f42c42a3da
GatewayMonitor/GatewayMonitorService.py
GatewayMonitor/GatewayMonitorService.py
# # A sample service to be 'compiled' into an exe-file with py2exe. # # See also # setup.py - the distutils' setup script # setup.cfg - the distutils' config file for this # README.txt - detailed usage notes # # A minimal service, doing nothing else than # - write 'start' and 'stop' entries into th...
Add gateway monitor Windows service
Add gateway monitor Windows service
Python
mit
isis-ammo/ammo-gateway,isis-ammo/ammo-gateway,isis-ammo/ammo-gateway,isis-ammo/ammo-gateway,isis-ammo/ammo-gateway,isis-ammo/ammo-gateway
--- +++ @@ -0,0 +1,60 @@ +# +# A sample service to be 'compiled' into an exe-file with py2exe. +# +# See also +# setup.py - the distutils' setup script +# setup.cfg - the distutils' config file for this +# README.txt - detailed usage notes +# +# A minimal service, doing nothing else than +# - write 'start...
c73b8a7503f21e16171ea1b0b40180bd1624f4d3
social/apps/flask_app/routes.py
social/apps/flask_app/routes.py
from flask import g, Blueprint from flask.ext.login import login_required, login_user from social.actions import do_auth, do_complete, do_disconnect from social.apps.flask_app.utils import strategy social_auth = Blueprint('social', __name__) @social_auth.route('/login/<string:backend>/', methods=('GET', 'POST')) @...
from flask import g, Blueprint, request from flask.ext.login import login_required, login_user from social.actions import do_auth, do_complete, do_disconnect from social.apps.flask_app.utils import strategy social_auth = Blueprint('social', __name__) @social_auth.route('/login/<string:backend>/', methods=('GET', '...
Support remember flag when calling login on flask app
Support remember flag when calling login on flask app
Python
bsd-3-clause
lamby/python-social-auth,lneoe/python-social-auth,henocdz/python-social-auth,ononeor12/python-social-auth,cjltsod/python-social-auth,JJediny/python-social-auth,henocdz/python-social-auth,henocdz/python-social-auth,ariestiyansyah/python-social-auth,mathspace/python-social-auth,rsteca/python-social-auth,jneves/python-soc...
--- +++ @@ -1,4 +1,4 @@ -from flask import g, Blueprint +from flask import g, Blueprint, request from flask.ext.login import login_required, login_user from social.actions import do_auth, do_complete, do_disconnect @@ -19,8 +19,8 @@ def complete(backend, *args, **kwargs): """Authentication complete view, ov...
50b2dccd24c756f5f09e6b9f4e2442abeed7f5c7
st2api/tests/unit/controllers/v1/test_alias_execution_rbac.py
st2api/tests/unit/controllers/v1/test_alias_execution_rbac.py
# Licensed to the StackStorm, Inc ('StackStorm') under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use th...
Add a regression test case for alias execution and live action context user.
Add a regression test case for alias execution and live action context user. Verify that the user inside the context is correctly set to the authenticated user which triggered the alias execution.
Python
apache-2.0
Plexxi/st2,StackStorm/st2,lakshmi-kannan/st2,nzlosh/st2,pixelrebel/st2,dennybaa/st2,pixelrebel/st2,pixelrebel/st2,peak6/st2,StackStorm/st2,peak6/st2,punalpatel/st2,dennybaa/st2,lakshmi-kannan/st2,armab/st2,emedvedev/st2,tonybaloney/st2,dennybaa/st2,tonybaloney/st2,armab/st2,lakshmi-kannan/st2,punalpatel/st2,peak6/st2,P...
--- +++ @@ -0,0 +1,73 @@ +# Licensed to the StackStorm, Inc ('StackStorm') under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You under the Apache License, Version 2.0 +# (th...
b1083460378166b23bfe379dfb228d4cf5236255
app/grandchallenge/profiles/utils.py
app/grandchallenge/profiles/utils.py
from django.conf import settings from grandchallenge.subdomains.utils import reverse def signin_redirect(redirect=None, user=None): """ Redirect user after successful sign in. First looks for a ``requested_redirect``. If not supplied will fall-back to the user specific account page. If all fails, wil...
Create method for redirect after signin
Create method for redirect after signin
Python
apache-2.0
comic/comic-django,comic/comic-django,comic/comic-django,comic/comic-django,comic/comic-django
--- +++ @@ -0,0 +1,24 @@ +from django.conf import settings + +from grandchallenge.subdomains.utils import reverse + + +def signin_redirect(redirect=None, user=None): + """ + Redirect user after successful sign in. + First looks for a ``requested_redirect``. If not supplied will fall-back to + the user spe...
64f820b18190034a2285e996cd2f66fc100c2f54
cogbot/extensions/jira.py
cogbot/extensions/jira.py
import re import urllib.parse from discord.ext import commands from discord.ext.commands import Context from cogbot.cog_bot import CogBot class Jira: REPORT_PATTERN = re.compile('^(mc-)?(\d+)$', re.IGNORECASE) def __init__(self, bot: CogBot, ext: str): self.bot = bot @commands.command(pass_con...
Add extension to search JIRA for bug reports
Add extension to search JIRA for bug reports
Python
mit
Arcensoth/cogbot
--- +++ @@ -0,0 +1,31 @@ +import re +import urllib.parse + +from discord.ext import commands +from discord.ext.commands import Context + +from cogbot.cog_bot import CogBot + + +class Jira: + REPORT_PATTERN = re.compile('^(mc-)?(\d+)$', re.IGNORECASE) + + def __init__(self, bot: CogBot, ext: str): + self....
201e63722b102ee453610a955e3014d3c772a8fa
ceph_deploy/tests/parser/test_purge.py
ceph_deploy/tests/parser/test_purge.py
import pytest from ceph_deploy.cli import get_parser class TestParserPurge(object): def setup(self): self.parser = get_parser() def test_purge_help(self, capsys): with pytest.raises(SystemExit): self.parser.parse_args('purge --help'.split()) out, err = capsys.readouterr(...
Add tests for argparse purge
[RM-11742] Add tests for argparse purge Signed-off-by: Travis Rhoden <e5e44d6dbac12e32e01c3bb8b67940d8b42e225b@redhat.com>
Python
mit
osynge/ceph-deploy,codenrhoden/ceph-deploy,Vicente-Cheng/ceph-deploy,SUSE/ceph-deploy,branto1/ceph-deploy,imzhulei/ceph-deploy,SUSE/ceph-deploy-to-be-deleted,ceph/ceph-deploy,SUSE/ceph-deploy-to-be-deleted,Vicente-Cheng/ceph-deploy,isyippee/ceph-deploy,zhouyuan/ceph-deploy,ceph/ceph-deploy,zhouyuan/ceph-deploy,shenhequ...
--- +++ @@ -0,0 +1,32 @@ +import pytest + +from ceph_deploy.cli import get_parser + + +class TestParserPurge(object): + + def setup(self): + self.parser = get_parser() + + def test_purge_help(self, capsys): + with pytest.raises(SystemExit): + self.parser.parse_args('purge --help'.split(...
fbbd0a3f55c1e79ebf6ae7b872697611740edb24
foobar.py
foobar.py
# -*- coding: utf-8 -*- class TreeElement(object): def __repr__(self): return u'{}'.format(self.__class__.__name__) class Token(TreeElement): def __init__(self, value): if isinstance(value, TreeElement): raise TypeError self._value = value def __repr__(self): ...
Implement Token and Not, And, Or classes
Implement Token and Not, And, Or classes
Python
mit
hackebrot/i-am-bool
--- +++ @@ -0,0 +1,116 @@ +# -*- coding: utf-8 -*- + + +class TreeElement(object): + def __repr__(self): + return u'{}'.format(self.__class__.__name__) + + +class Token(TreeElement): + def __init__(self, value): + if isinstance(value, TreeElement): + raise TypeError + self._value...
cf4dc3f65049c23f4a20140cf5092f3c5a771a6a
administrator/tests/models/test_user.py
administrator/tests/models/test_user.py
from django.test import TestCase from administrator.models import User, UserManager class UserManagerTestCase(TestCase): valid_email = 'example@example.com' valid_username = 'foobar' valid_password = 'qwerty123' def setUp(self): self.user_manager = UserManager() self.user_manager.mod...
Add tests for User model
Add tests for User model
Python
mit
Social-projects-Rivne/Rv-025.Python,Social-projects-Rivne/Rv-025.Python,Social-projects-Rivne/Rv-025.Python
--- +++ @@ -0,0 +1,52 @@ +from django.test import TestCase + +from administrator.models import User, UserManager + + +class UserManagerTestCase(TestCase): + valid_email = 'example@example.com' + valid_username = 'foobar' + valid_password = 'qwerty123' + + def setUp(self): + self.user_manager = User...
b9a8be97bc445edac024a35d644d5c86419a7f3a
ReactAndroid/src/main/third-party/android-support-for-standalone-apps/v7/appcompat/res-unpacker.py
ReactAndroid/src/main/third-party/android-support-for-standalone-apps/v7/appcompat/res-unpacker.py
import contextlib import os import shutil import sys import tempfile import zipfile # Helper that unpacks the contents of the res folder of an .aar file # into given destination. @contextlib.contextmanager def cleanup(path): yield path shutil.rmtree(path) if __name__ == '__main__': with zipfile.ZipFile(s...
Build code depending on resources from the appcompat library with both Buck and Gradle
Build code depending on resources from the appcompat library with both Buck and Gradle Reviewed By: sdwilsh Differential Revision: D2844961 fb-gh-sync-id: 686a9f253eb370a9dc8cc33ca1c4e8453f89210a
Python
bsd-3-clause
hammerandchisel/react-native,jaggs6/react-native,ultralame/react-native,alin23/react-native,yamill/react-native,doochik/react-native,iodine/react-native,Swaagie/react-native,facebook/react-native,exponentjs/react-native,corbt/react-native,makadaw/react-native,arthuralee/react-native,jevakallio/react-native,forcedotcom/...
--- +++ @@ -0,0 +1,20 @@ +import contextlib +import os +import shutil +import sys +import tempfile +import zipfile + +# Helper that unpacks the contents of the res folder of an .aar file +# into given destination. + +@contextlib.contextmanager +def cleanup(path): + yield path + shutil.rmtree(path) + +if __name_...
359726a1085b00936e7e7ee3f876b09f72988921
dipy/utils/tests/test_tripwire.py
dipy/utils/tests/test_tripwire.py
""" Testing tripwire module. """ from ..tripwire import TripWire, is_tripwire, TripWireError from nose import SkipTest from nose.tools import (assert_true, assert_false, assert_raises, assert_equal, assert_not_equal) def test_is_tripwire(): assert_false(is_tripwire(object())) assert_...
Add a test for TripWire.
TST: Add a test for TripWire.
Python
bsd-3-clause
StongeEtienne/dipy,villalonreina/dipy,villalonreina/dipy,nilgoyyou/dipy,FrancoisRheaultUS/dipy,matthieudumont/dipy,StongeEtienne/dipy,nilgoyyou/dipy,matthieudumont/dipy,FrancoisRheaultUS/dipy
--- +++ @@ -0,0 +1,29 @@ +""" Testing tripwire module. +""" + +from ..tripwire import TripWire, is_tripwire, TripWireError + +from nose import SkipTest +from nose.tools import (assert_true, assert_false, assert_raises, + assert_equal, assert_not_equal) + + +def test_is_tripwire(): + assert_f...
1103c498635480d516eeebbec615f8d13db51bb7
api/tests/test_topic_api.py
api/tests/test_topic_api.py
import pytz from datetime import datetime, timedelta from django.test import TestCase from api.factories import TopicFactory from rest_framework.test import APIRequestFactory, force_authenticate from api.factories import UserFactory from api.serializers import TopicSerializer from api.views.topics import TopicViewSet ...
Write tests for active and inactive list routes
Write tests for active and inactive list routes
Python
mit
frostblooded/kanq,frostblooded/kanq,frostblooded/kanq,frostblooded/kanq,frostblooded/kanq
--- +++ @@ -0,0 +1,51 @@ +import pytz +from datetime import datetime, timedelta +from django.test import TestCase + +from api.factories import TopicFactory +from rest_framework.test import APIRequestFactory, force_authenticate +from api.factories import UserFactory +from api.serializers import TopicSerializer +from a...
fb876d0ddc12fa89db5e3bec519ad4e93e914b8d
designate/tests/unit/api/test_version.py
designate/tests/unit/api/test_version.py
# 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 t...
Add basic api version test coverage
Add basic api version test coverage Change-Id: Idb04e81ce5954ca8b5e387dc7c0776fdf7d08779
Python
apache-2.0
openstack/designate,openstack/designate,openstack/designate
--- +++ @@ -0,0 +1,78 @@ +# 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 writi...
964895852bb9acbe866c1a7bc7ba98b972100fa8
readthedocs/builds/migrations/0014_migrate-doctype-from-project-to-version.py
readthedocs/builds/migrations/0014_migrate-doctype-from-project-to-version.py
# -*- coding: utf-8 -*- # Generated by Django 1.11.27 on 2020-01-14 17:40 from django.db import migrations from django.db.models import OuterRef, Subquery def forwards_func(apps, schema_editor): """Migrate ``Project.documentation_type`` to ``Version.documentation_type``.""" Version = apps.get_model('builds',...
Migrate documentation_type from Project to Version
Migrate documentation_type from Project to Version
Python
mit
rtfd/readthedocs.org,rtfd/readthedocs.org,rtfd/readthedocs.org,rtfd/readthedocs.org
--- +++ @@ -0,0 +1,30 @@ +# -*- coding: utf-8 -*- +# Generated by Django 1.11.27 on 2020-01-14 17:40 + +from django.db import migrations +from django.db.models import OuterRef, Subquery + + +def forwards_func(apps, schema_editor): + """Migrate ``Project.documentation_type`` to ``Version.documentation_type``.""" + ...
adca0c2ff48b716e9ac3ef706d66d86943fb29b7
cpm_data/migrations/0015_add_jury_members_to_seasons_12_14.py
cpm_data/migrations/0015_add_jury_members_to_seasons_12_14.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from functools import partial from django.db import migrations def add_to_season(apps, schema_editor, season_name, jury_names): JuryMember = apps.get_model('cpm_data.JuryMember') Season = apps.get_model('cpm_data.Season') SeasonJuryMember =...
Add jury to 2012-2014 - take the data from results pages
Add jury to 2012-2014 - take the data from results pages
Python
unlicense
kinaklub/next.filmfest.by,kinaklub/next.filmfest.by,kinaklub/next.filmfest.by,kinaklub/next.filmfest.by
--- +++ @@ -0,0 +1,63 @@ +# -*- coding: utf-8 -*- +from __future__ import unicode_literals + +from functools import partial + +from django.db import migrations + + +def add_to_season(apps, schema_editor, season_name, jury_names): + JuryMember = apps.get_model('cpm_data.JuryMember') + Season = apps.get_model('cp...
48a37b00bb73ea0398644e0eb22c50c34919b325
examples/non_terminating_checks_test.py
examples/non_terminating_checks_test.py
from seleniumbase import BaseCase class MyTestClass(BaseCase): def test_non_terminating_checks(self): self.open('http://xkcd.com/993/') self.wait_for_element('#comic') self.check_assert_element('img[alt="Brand Identity"]') self.check_assert_element('img[alt="Rocket Ship"]') # Wil...
Add example test for non-terminating checks
Add example test for non-terminating checks
Python
mit
mdmintz/SeleniumBase,possoumous/Watchers,possoumous/Watchers,ktp420/SeleniumBase,mdmintz/SeleniumBase,seleniumbase/SeleniumBase,seleniumbase/SeleniumBase,ktp420/SeleniumBase,ktp420/SeleniumBase,possoumous/Watchers,mdmintz/seleniumspot,seleniumbase/SeleniumBase,seleniumbase/SeleniumBase,mdmintz/seleniumspot,mdmintz/Sele...
--- +++ @@ -0,0 +1,15 @@ +from seleniumbase import BaseCase + + +class MyTestClass(BaseCase): + + def test_non_terminating_checks(self): + self.open('http://xkcd.com/993/') + self.wait_for_element('#comic') + self.check_assert_element('img[alt="Brand Identity"]') + self.check_assert_ele...
6e02077b0aab178a2d8100a26811a485a74852f2
flexget/plugins/urlrewrite_shortened.py
flexget/plugins/urlrewrite_shortened.py
from __future__ import unicode_literals, division, absolute_import import logging from urlparse import urlparse from flexget import plugin from flexget.utils import requests from flexget.event import event log = logging.getLogger('shortened') class UrlRewriteShortened(object): """Shortened url rewriter.""" ...
Add url rewriter for shortened urls
Add url rewriter for shortened urls
Python
mit
ratoaq2/Flexget,gazpachoking/Flexget,qvazzler/Flexget,Flexget/Flexget,X-dark/Flexget,poulpito/Flexget,LynxyssCZ/Flexget,offbyone/Flexget,poulpito/Flexget,X-dark/Flexget,sean797/Flexget,malkavi/Flexget,tsnoam/Flexget,JorisDeRieck/Flexget,Pretagonist/Flexget,jawilson/Flexget,OmgOhnoes/Flexget,Pretagonist/Flexget,qvazzler...
--- +++ @@ -0,0 +1,24 @@ +from __future__ import unicode_literals, division, absolute_import +import logging +from urlparse import urlparse + +from flexget import plugin +from flexget.utils import requests +from flexget.event import event + +log = logging.getLogger('shortened') + + +class UrlRewriteShortened(object):...
2ffcae174d7ff10aa816b8fb839c9c0ae6fb3689
bidwire/alembic/versions/a1b42c9006a7_absolute_massgov_eopss_url.py
bidwire/alembic/versions/a1b42c9006a7_absolute_massgov_eopss_url.py
"""absolute_massgov_eopss_url Revision ID: a1b42c9006a7 Revises: 9b30b0fe231a Create Date: 2017-06-26 00:02:45.998655 """ from alembic import op import sqlalchemy as sa from sqlalchemy.orm.session import Session import os import sys sys.path.append(os.path.dirname(os.path.dirname(__file__))) from document import Doc...
Add database migration to make all Massgov Eopss URLs absolute.
Add database migration to make all Massgov Eopss URLs absolute.
Python
mit
RagtagOpen/bidwire,RagtagOpen/bidwire,RagtagOpen/bidwire
--- +++ @@ -0,0 +1,44 @@ +"""absolute_massgov_eopss_url + +Revision ID: a1b42c9006a7 +Revises: 9b30b0fe231a +Create Date: 2017-06-26 00:02:45.998655 + +""" +from alembic import op +import sqlalchemy as sa +from sqlalchemy.orm.session import Session + +import os +import sys +sys.path.append(os.path.dirname(os.path.dir...
cfca3ecf6d36611ff0ffe3537f01c2711e94f87e
kpub/tests/test_counts.py
kpub/tests/test_counts.py
import kpub def test_annual_count(): # Does the cumulative count match the annual count? db = kpub.PublicationDB() annual = db.get_annual_publication_count() cumul = db.get_annual_publication_count_cumulative() assert annual['k2'][2010] == 0 # K2 didn't exist in 2010 # The first K2 papers sta...
Add unit test for get_annual_publication_count
Add unit test for get_annual_publication_count
Python
mit
KeplerGO/kpub
--- +++ @@ -0,0 +1,12 @@ +import kpub + + +def test_annual_count(): + # Does the cumulative count match the annual count? + db = kpub.PublicationDB() + annual = db.get_annual_publication_count() + cumul = db.get_annual_publication_count_cumulative() + assert annual['k2'][2010] == 0 # K2 didn't exist i...
d0b98a062eaca03dba53f610bb4b326d769464e9
foundation/organisation/migrations/0008_auto_20160707_0752.py
foundation/organisation/migrations/0008_auto_20160707_0752.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('organisation', '0007_add_old_project_bool_to_project_model'), ] operations = [ migrations.AlterField( model_name...
Add updated help text for order in networkgroup
Add updated help text for order in networkgroup
Python
mit
okfn/website,okfn/foundation,okfn/website,okfn/website,okfn/foundation,okfn/foundation,okfn/foundation,okfn/website
--- +++ @@ -0,0 +1,19 @@ +# -*- coding: utf-8 -*- +from __future__ import unicode_literals + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('organisation', '0007_add_old_project_bool_to_project_model'), + ] + + operations = [ + migr...
3075a2dfcd51b932fd142e51e6bdc1694ab4e750
gitlabform/gitlabform/test/test_tags.py
gitlabform/gitlabform/test/test_tags.py
from gitlabform.gitlabform.test import ( run_gitlabform, ) class TestArchiveProject: def test__archive_project(self, gitlab, group, project): group_and_project = f"{group}/{project}" config = f""" projects_and_groups: {group_and_project}: project: a...
Add tests for protected tags
Add tests for protected tags
Python
mit
egnyte/gitlabform,egnyte/gitlabform
--- +++ @@ -0,0 +1,81 @@ +from gitlabform.gitlabform.test import ( + run_gitlabform, +) + + +class TestArchiveProject: + def test__archive_project(self, gitlab, group, project): + group_and_project = f"{group}/{project}" + + config = f""" + projects_and_groups: + {group_and_project...
1ac9175d661cc3d42416f3f55c5c8212467c612c
make_plots.py
make_plots.py
"""Make plots of the results of Dakotathon experiments.""" import numpy as np import matplotlib.pyplot as mpl def read_dat_header(dat_file): try: with open(dat_file, 'r') as fp: names = fp.readline().split() except IOError: pass else: return names def read_dat_file(...
Read Dakota tabular graphics output file
Read Dakota tabular graphics output file
Python
mit
mdpiper/AGU-2016
--- +++ @@ -0,0 +1,35 @@ +"""Make plots of the results of Dakotathon experiments.""" + +import numpy as np +import matplotlib.pyplot as mpl + + + +def read_dat_header(dat_file): + try: + with open(dat_file, 'r') as fp: + names = fp.readline().split() + except IOError: + pass + else: ...
38978ce807966a1367ae2ad95dc81f87a08c2ca3
pbm2sh.py
pbm2sh.py
import sys import re with open(sys.argv[1]) as f: magic = f.readline().strip() if magic != "P1": print "Expected file to start with P1" sys.exit(1) f.readline() # Ignore comment line w, h = [int(n) for n in f.readline().strip().split(" ")] pixels = re.sub(r"[^01]", "", f.read()) ...
Add script to generate script from pbm files
Add script to generate script from pbm files
Python
mit
pib/gpio_ssd1306,pib/gpio_ssd1306
--- +++ @@ -0,0 +1,32 @@ +import sys +import re + +with open(sys.argv[1]) as f: + magic = f.readline().strip() + if magic != "P1": + print "Expected file to start with P1" + sys.exit(1) + + f.readline() # Ignore comment line + w, h = [int(n) for n in f.readline().strip().split(" ")] + pix...
5de36454db293c03039bec3c8c628995f07825b0
src/txkube/_compat.py
src/txkube/_compat.py
# Copyright Least Authority Enterprises. # See LICENSE for details. """ Helpers for Python 2/3 compatibility. """ from json import dumps from twisted.python.compat import unicode def dumps_bytes(obj): """ Serialize ``obj`` to JSON formatted ``bytes``. """ b = dumps(obj) if isinstance(b, unicode)...
Add a dumps_bytes() helper method to handle Python 2/3 compatibility.
Add a dumps_bytes() helper method to handle Python 2/3 compatibility.
Python
mit
LeastAuthority/txkube
--- +++ @@ -0,0 +1,19 @@ +# Copyright Least Authority Enterprises. +# See LICENSE for details. + +""" +Helpers for Python 2/3 compatibility. +""" + +from json import dumps + +from twisted.python.compat import unicode + +def dumps_bytes(obj): + """ + Serialize ``obj`` to JSON formatted ``bytes``. + """ + b...
d7f184dd7c41bb3cacba5f77c81ae961b3a12760
subsample_bam_file.py
subsample_bam_file.py
#!/usr/bin/env python """ This script subsamples the alignments of a BAM file. For this a likelihood (0.0 < p(keep) < 1.0) of keeping all alignments of a read has to be provided. All alignments of a read are treated the same (i.e. are discarded or kept). """ import argparse import random import sys import pysam __d...
Add script to subsample bam file entries
Add script to subsample bam file entries
Python
isc
konrad/kuf_bio_scripts
--- +++ @@ -0,0 +1,52 @@ +#!/usr/bin/env python +""" + +This script subsamples the alignments of a BAM file. For this a +likelihood (0.0 < p(keep) < 1.0) of keeping all alignments of a read +has to be provided. All alignments of a read are treated the same +(i.e. are discarded or kept). + +""" + +import argparse +imp...
67120e72883d4a5fd86dca2fba26599e65e7ea39
every_election/apps/elections/management/commands/add_referendum.py
every_election/apps/elections/management/commands/add_referendum.py
from django.core.management import BaseCommand from elections.models import ( Election, ElectionType, ModerationHistory, ModerationStatuses, ) from organisations.models.organisations import Organisation class Command(BaseCommand): help = """ Adds an election with an election type of referendu...
Add management command to add a refendeum election
Add management command to add a refendeum election - Added to allow us to add Croydon referendum initially, with the possibility of being able to use again in the future as required
Python
bsd-3-clause
DemocracyClub/EveryElection,DemocracyClub/EveryElection,DemocracyClub/EveryElection
--- +++ @@ -0,0 +1,103 @@ +from django.core.management import BaseCommand + +from elections.models import ( + Election, + ElectionType, + ModerationHistory, + ModerationStatuses, +) +from organisations.models.organisations import Organisation + + +class Command(BaseCommand): + help = """ + Adds an e...
c008d60fda4f3e3d58d123ab4a972016e669a7dc
tests/test_summary_downloader.py
tests/test_summary_downloader.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import itertools import tempfile from zipfile import ZipFile from utils.summary_downloader import SummaryDownloader def test_download_unzipped(): date = "Oct 24, 2016" tgt_dir = tempfile.mkdtemp(prefix='sdl_test_') prefixes = ["ES", "FC", "GS", "P...
Add tests for download of game summaries
Add tests for download of game summaries
Python
mit
leaffan/pynhldb
--- +++ @@ -0,0 +1,57 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +import os +import itertools +import tempfile +from zipfile import ZipFile + +from utils.summary_downloader import SummaryDownloader + + +def test_download_unzipped(): + + date = "Oct 24, 2016" + tgt_dir = tempfile.mkdtemp(prefix='sdl_te...
02a8a627bfffb1b0cda4455a2c639e92ef1d7a46
lib/portbuild/qthreads.py
lib/portbuild/qthreads.py
#! /usr/bin/env python import threading import time from pika.adapters import BlockingConnection class QueueThread(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.name = self.__class__.__name__ self.connection = BlockingConnection() self._stop = threading.Event() sel...
Add queue thread convenience classes.
Add queue thread convenience classes.
Python
bsd-2-clause
flz/portbuild-ng
--- +++ @@ -0,0 +1,48 @@ +#! /usr/bin/env python + +import threading +import time + +from pika.adapters import BlockingConnection + +class QueueThread(threading.Thread): + def __init__(self): + threading.Thread.__init__(self) + self.name = self.__class__.__name__ + self.connection = BlockingConnection() + ...
71b308f123aff1b4498fe14188380a6352d34d49
numba/tests/builtins/test_builtin_pow.py
numba/tests/builtins/test_builtin_pow.py
# adapted from cython/tests/run/builtin_pow.pyx """ >>> pow3(2,3,5) 3 >>> pow3(3,3,5) 2 >>> pow3_const() 3 >>> pow2(2,3) 8 >>> pow2(3,3) 27 >>> pow2_const() 8 """ @autojit(backend='ast') def pow3(a,b,c): return pow(a,b,c) @autojit(backend='ast') def pow3_const(): return pow(2,3,5) @autojit(backend='ast')...
Add testcase for pow builtin
Add testcase for pow builtin
Python
bsd-2-clause
stefanseefeld/numba,GaZ3ll3/numba,sklam/numba,gdementen/numba,numba/numba,gmarkall/numba,cpcloud/numba,gmarkall/numba,pitrou/numba,jriehl/numba,sklam/numba,pombredanne/numba,stonebig/numba,pitrou/numba,gdementen/numba,shiquanwang/numba,cpcloud/numba,stefanseefeld/numba,stefanseefeld/numba,pitrou/numba,stuartarchibald/n...
--- +++ @@ -0,0 +1,39 @@ +# adapted from cython/tests/run/builtin_pow.pyx + +""" +>>> pow3(2,3,5) +3 +>>> pow3(3,3,5) +2 + +>>> pow3_const() +3 + +>>> pow2(2,3) +8 +>>> pow2(3,3) +27 + +>>> pow2_const() +8 +""" + +@autojit(backend='ast') +def pow3(a,b,c): + return pow(a,b,c) + +@autojit(backend='ast') +def pow3_co...
cf5a5594ebecc03c1087f09575dba1a480b575f3
tests/test_authjob.py
tests/test_authjob.py
from disco.test import DiscoJobTestFixture, DiscoTestCase from disco.ddfs import DDFS from disco.util import ddfs_name from cStringIO import StringIO class AuthJobTestCase(DiscoJobTestFixture, DiscoTestCase): input = [] @staticmethod def map(e, params): return [(e.strip(), '')] @property ...
Add a test case for auth protected inputs.
Add a test case for auth protected inputs.
Python
bsd-3-clause
seabirdzh/disco,pombredanne/disco,ktkt2009/disco,ErikDubbelboer/disco,pooya/disco,pombredanne/disco,pooya/disco,oldmantaiter/disco,pooya/disco,seabirdzh/disco,beni55/disco,ktkt2009/disco,ErikDubbelboer/disco,oldmantaiter/disco,discoproject/disco,simudream/disco,mwilliams3/disco,pavlobaron/disco_playground,ktkt2009/disc...
--- +++ @@ -0,0 +1,29 @@ +from disco.test import DiscoJobTestFixture, DiscoTestCase + +from disco.ddfs import DDFS +from disco.util import ddfs_name + +from cStringIO import StringIO + +class AuthJobTestCase(DiscoJobTestFixture, DiscoTestCase): + input = [] + + @staticmethod + def map(e, params): + re...
e6a57c43a693f71069778ddca3a28d5c73b75830
nova/scheduler/multi.py
nova/scheduler/multi.py
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright (c) 2010 Openstack, LLC. # Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # ...
Allow different schedulers for compute and volume.
Allow different schedulers for compute and volume.
Python
apache-2.0
n0ano/ganttclient
--- +++ @@ -0,0 +1,73 @@ +# vim: tabstop=4 shiftwidth=4 softtabstop=4 + +# Copyright (c) 2010 Openstack, LLC. +# Copyright 2010 United States Government as represented by the +# Administrator of the National Aeronautics and Space Administration. +# All Rights Reserved. +# +# Licensed under the Apache License, Vers...
a32477899c7d21a82382f4c274cac129074b3e32
pombola/kenya/management/commands/kenya_import_2017_photos.py
pombola/kenya/management/commands/kenya_import_2017_photos.py
from __future__ import print_function import csv from os.path import abspath, dirname, exists, join import shutil from django.conf import settings from django.core.files.storage import FileSystemStorage from django.core.management.base import BaseCommand from images.models import Image from pombola.core.models import...
Add a script to import elected candidates' photos from YNR
Add a script to import elected candidates' photos from YNR This script uses the YNR IDs that the kenya_import_2017_election_results command added to import the photos from YNR and add them to the appropriate person in Mzalendo. If there were existing photos of the person, the YNR photo is not set as primary, otherwise...
Python
agpl-3.0
mysociety/pombola,mysociety/pombola,mysociety/pombola,mysociety/pombola,mysociety/pombola,mysociety/pombola
--- +++ @@ -0,0 +1,68 @@ +from __future__ import print_function + +import csv +from os.path import abspath, dirname, exists, join +import shutil + +from django.conf import settings +from django.core.files.storage import FileSystemStorage +from django.core.management.base import BaseCommand +from images.models import ...
0aef588b92adc6ccc175a6b6d34784ff4d7e290d
coprocess/bindings/python/sample_server.py
coprocess/bindings/python/sample_server.py
import coprocess_object_pb2 import grpc, time _ONE_DAY_IN_SECONDS = 60 * 60 * 24 from concurrent import futures def MyPreMiddleware(coprocess_object): coprocess_object.request.set_headers["myheader"] = "myvalue" return coprocess_object def MyPostMiddleware(coprocess_object): coprocess_object.request.set_head...
import coprocess_object_pb2 import grpc, time, json _ONE_DAY_IN_SECONDS = 60 * 60 * 24 from concurrent import futures def MyPreMiddleware(coprocess_object): coprocess_object.request.set_headers["myheader"] = "myvalue" return coprocess_object def MyPostMiddleware(coprocess_object): coprocess_object.request.se...
Adjust gRPC/Python sample to handle events.
Adjust gRPC/Python sample to handle events.
Python
mpl-2.0
mvdan/tyk,nebolsin/tyk,mvdan/tyk,nebolsin/tyk,nebolsin/tyk,mvdan/tyk,nebolsin/tyk,nebolsin/tyk,mvdan/tyk,lonelycode/tyk,lonelycode/tyk,nebolsin/tyk,nebolsin/tyk,lonelycode/tyk,mvdan/tyk,mvdan/tyk,nebolsin/tyk,mvdan/tyk,mvdan/tyk
--- +++ @@ -1,6 +1,6 @@ import coprocess_object_pb2 -import grpc, time +import grpc, time, json _ONE_DAY_IN_SECONDS = 60 * 60 * 24 @@ -16,7 +16,6 @@ class MyDispatcher(coprocess_object_pb2.DispatcherServicer): def Dispatch(self, coprocess_object, context): - if coprocess_object.hook_name == "MyPreM...
3e45602583a7760a5fb7b5beb47405b4dddd0f63
run_tests.py
run_tests.py
#!/usr/bin/python import optparse import sys # Install the Python unittest2 package before you run this script. import unittest2 USAGE = """%prog SDK_PATH Run unit tests for App Engine apps. The SDK Path is probably /usr/local/google_appengine on Mac OS SDK_PATH Path to the SDK installation""" def main(sdk_path,...
#!/usr/bin/python import optparse import sys # Install the Python unittest2 package before you run this script. import unittest2 USAGE = """%prog SDK_PATH Run unit tests for App Engine apps. The SDK Path is probably /usr/local/google_appengine on Mac OS SDK_PATH Path to the SDK installation""" def main(sdk_path,...
Exit with code 1 if tests fail.
Exit with code 1 if tests fail. Fixes #621 and Travis.
Python
mit
josephbisch/the-blue-alliance,1fish2/the-blue-alliance,nwalters512/the-blue-alliance,verycumbersome/the-blue-alliance,phil-lopreiato/the-blue-alliance,fangeugene/the-blue-alliance,the-blue-alliance/the-blue-alliance,1fish2/the-blue-alliance,bdaroz/the-blue-alliance,1fish2/the-blue-alliance,jaredhasenklein/the-blue-alli...
--- +++ @@ -15,9 +15,14 @@ sys.path.insert(0, sdk_path) import dev_appserver dev_appserver.fix_sys_path() - + suite = unittest2.loader.TestLoader().discover("tests", test_pattern) - unittest2.TextTestRunner(verbosity=2).run(suite) + tests = unittest2.TextTestRunner(verbosity=2).run(suite...
c881b3176b122cdefe406d02e640600e6d4f4727
migrations/versions/ec3035d61f8b_.py
migrations/versions/ec3035d61f8b_.py
"""Add status column to tickets. Revision ID: ec3035d61f8b Revises: 0397e48c5db8 Create Date: 2020-08-30 21:04:30.936267 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = 'ec3035d61f8b' down_revision = '0397e48c5db8' branch_labels = None depends_on = None def u...
Add ticket's status column migration.
Add ticket's status column migration.
Python
mpl-2.0
mrf345/FQM,mrf345/FQM,mrf345/FQM,mrf345/FQM
--- +++ @@ -0,0 +1,28 @@ +"""Add status column to tickets. + +Revision ID: ec3035d61f8b +Revises: 0397e48c5db8 +Create Date: 2020-08-30 21:04:30.936267 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = 'ec3035d61f8b' +down_revision = '0397e48c5db8' +bran...
9d501aaa9d443e450224388854f053683ca2baae
permute/tests/test_npc.py
permute/tests/test_npc.py
from __future__ import division, print_function, absolute_import from nose.plugins.attrib import attr from nose.tools import assert_raises, raises import numpy as np from scipy.stats import norm from ..npc import (fisher, liptak, tippett) def test_fisher(): pvalues = np.lin...
Add tests for combining functions
TST: Add tests for combining functions
Python
bsd-2-clause
qqqube/permute,statlab/permute,kellieotto/permute,jarrodmillman/permute,kellieotto/permute
--- +++ @@ -0,0 +1,32 @@ +from __future__ import division, print_function, absolute_import + +from nose.plugins.attrib import attr +from nose.tools import assert_raises, raises + +import numpy as np +from scipy.stats import norm + +from ..npc import (fisher, + liptak, + tippett) + ...
827802f111fbe5c2f9a50b74a46afdef5eae2a2d
salt/pillar/nacl.py
salt/pillar/nacl.py
# -*- coding: utf-8 -*- ''' Decrypt pillar data through the builtin NACL renderer In most cases, you'll want to make this the last external pillar used. For example, to pair with the builtin stack pillar you could do something like this: .. code:: yaml nacl.config: keyfile: /root/.nacl ext_pillar: ...
Decrypt NACL passwords on ext_pillar
Decrypt NACL passwords on ext_pillar
Python
apache-2.0
saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt
--- +++ @@ -0,0 +1,29 @@ +# -*- coding: utf-8 -*- + +''' +Decrypt pillar data through the builtin NACL renderer + +In most cases, you'll want to make this the last external pillar used. For +example, to pair with the builtin stack pillar you could do something like +this: + +.. code:: yaml + + nacl.config: + ...
ce8dc2152a508ea359159a917ea469a106065503
modules/neural_network.py
modules/neural_network.py
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Thu Apr 27 14:10:49 2017 @author: daniele """ import tensorflow as tf import os import numpy as np import matplotlib.pyplot as plt
Add (currently empty) neural netowrks module
feat: Add (currently empty) neural netowrks module
Python
mit
dangall/Kaggle-MobileODT-Cancer-Screening
--- +++ @@ -0,0 +1,17 @@ +#!/usr/bin/env python2 +# -*- coding: utf-8 -*- +""" +Created on Thu Apr 27 14:10:49 2017 + +@author: daniele +""" + +import tensorflow as tf + +import os + +import numpy as np +import matplotlib.pyplot as plt + + +
f8b6d9a1bb12087c25e60df03f9f40c435f1a949
tests/test_archive.py
tests/test_archive.py
#!/usr/bin/env python # -*- coding: utf8 -*- try: import unittest2 as unittest except ImportError: import unittest import agate import agateremote class TestArchive(agate.AgateTestCase): def setUp(self): self.archive = agateremote.Archive('https://github.com/vincentarelbundock/Rdatasets/raw/maste...
#!/usr/bin/env python # -*- coding: utf8 -*- try: import unittest2 as unittest except ImportError: import unittest import agate import agateremote class TestArchive(agate.AgateTestCase): def setUp(self): self.archive = agateremote.Archive('https://github.com/vincentarelbundock/Rdatasets/raw/maste...
Update test for recent version of agate
Update test for recent version of agate
Python
mit
wireservice/agate-remote,onyxfish/agate-remote
--- +++ @@ -16,6 +16,6 @@ def test_get_table(self): table = self.archive.get_table('sandwich/PublicSchools.csv') - self.assertColumnNames(table, ['', 'Expenditure', 'Income']) + self.assertColumnNames(table, ('a', 'Expenditure', 'Income')) self.assertColumnTypes(table, [agate.Te...
533160e303fd73a8e6f53ebc7e6430bba8888bbb
tests/test_player_draft.py
tests/test_player_draft.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from db.player_draft import PlayerDraft from db.team import Team def test_find_by_id(): pdft = PlayerDraft.find_by_player_id(8475883) # Frederik Andersen assert len(pdft) == 2 pdft = PlayerDraft.find_by_player_id(8466145) # Nick Boynton assert len(pdft)...
Add tests for player draft items
Add tests for player draft items
Python
mit
leaffan/pynhldb
--- +++ @@ -0,0 +1,39 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +from db.player_draft import PlayerDraft +from db.team import Team + + +def test_find_by_id(): + pdft = PlayerDraft.find_by_player_id(8475883) # Frederik Andersen + assert len(pdft) == 2 + pdft = PlayerDraft.find_by_player_id(8466145...
517c29e34a1bc43df60cbabad998a1c0581e7b21
pybossa/error/__init__.py
pybossa/error/__init__.py
# -*- coding: utf8 -*- # This file is part of PyBossa. # # Copyright (C) 2013 SF Isle of Man Limited # # PyBossa 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...
Refactor HTTP Error status in a module
Refactor HTTP Error status in a module
Python
agpl-3.0
stefanhahmann/pybossa,jean/pybossa,geotagx/geotagx-pybossa-archive,harihpr/tweetclickers,OpenNewsLabs/pybossa,inteligencia-coletiva-lsd/pybossa,geotagx/geotagx-pybossa-archive,inteligencia-coletiva-lsd/pybossa,geotagx/pybossa,OpenNewsLabs/pybossa,PyBossa/pybossa,harihpr/tweetclickers,geotagx/pybossa,stefanhahmann/pybos...
--- +++ @@ -0,0 +1,70 @@ +# -*- coding: utf8 -*- +# This file is part of PyBossa. +# +# Copyright (C) 2013 SF Isle of Man Limited +# +# PyBossa 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...
17c69212ff5ea1a5991dc89ba1ca7365c8d666c2
firmware/common/binsize.py
firmware/common/binsize.py
#!/usr/bin/env python from subprocess import Popen, PIPE class app(object): def __init__(self): pass motolink = app() motolink.name = "ch" motolink.path = "build/ch.elf" motolink.max_ccm = 4*1024 motolink.max_ram = 12*1024 motolink.max_rom = 64*1024 APPS = [motolink] for app in APPS: ccm = 0 ...
Add a Python script to get ROM and RAM usage.
Add a Python script to get ROM and RAM usage.
Python
apache-2.0
romainreignier/robot2017,romainreignier/robot2017,romainreignier/robot2017,romainreignier/robot2017
--- +++ @@ -0,0 +1,62 @@ +#!/usr/bin/env python + +from subprocess import Popen, PIPE + + +class app(object): + def __init__(self): + pass + + +motolink = app() +motolink.name = "ch" +motolink.path = "build/ch.elf" +motolink.max_ccm = 4*1024 +motolink.max_ram = 12*1024 +motolink.max_rom = 64*1024 + +APPS = ...
4f189c20fc535f780e905e6fee7351329240d8fc
tyr/clusters/mongo.py
tyr/clusters/mongo.py
import logging class MongoCluster(object): log = logging.getLogger('Clusters.Mongo') log.setLevel(logging.DEBUG) ch = logging.StreamHandler() ch.setLevel(logging.DEBUG) formatter = logging.Formatter( '%(asctime)s [%(name)s] %(levelname)s: %(message)s', datefmt = '%H:%M:%S')...
Set up logging for a MongoDB cluster
Set up logging for a MongoDB cluster
Python
unlicense
hudl/Tyr
--- +++ @@ -0,0 +1,14 @@ +import logging + +class MongoCluster(object): + + log = logging.getLogger('Clusters.Mongo') + log.setLevel(logging.DEBUG) + ch = logging.StreamHandler() + ch.setLevel(logging.DEBUG) + formatter = logging.Formatter( + '%(asctime)s [%(name)s] %(levelname)s: %(message)...
feafbefbc7de1f71cfa50af51139c4a09a306012
socketio-client.py
socketio-client.py
import websocket, httplib, sys, asyncore ''' connect to the socketio server 1. perform the HTTP handshake 2. open a websocket connection ''' def connect(server, port): print("connecting to: %s:%d" %(server, port)) conn = httplib.HTTPConnection(server + ":" + str(port)) conn.request('...
Add socket io client example
Add socket io client example
Python
mit
voidabhi/python-scripts,voidabhi/python-scripts,voidabhi/python-scripts,voidabhi/python-scripts,voidabhi/python-scripts
--- +++ @@ -0,0 +1,49 @@ +import websocket, httplib, sys, asyncore + +''' + connect to the socketio server + 1. perform the HTTP handshake + 2. open a websocket connection ''' +def connect(server, port): + + print("connecting to: %s:%d" %(server, port)) + + conn = httplib.HTTPConnection(server...
c56efa68fbc878d307391910de9c521e5f2a6673
python/dynamic_class.py
python/dynamic_class.py
# -*- coding:utf-8 -*- class CanDoSomething(object): message = "You don't have permission" def has_permission(self, request, view): return True class CanDoSomethingOrReadOnly(CanDoSomething): def has_permission(self, request, view): return False class HasPermissionToDo(object): ...
Add python dynamic class sample
Add python dynamic class sample
Python
mit
aiden0z/snippets,aiden0z/snippets,aiden0z/snippets,aiden0z/snippets,aiden0z/snippets,aiden0z/snippets
--- +++ @@ -0,0 +1,36 @@ +# -*- coding:utf-8 -*- + + +class CanDoSomething(object): + + message = "You don't have permission" + + def has_permission(self, request, view): + return True + + +class CanDoSomethingOrReadOnly(CanDoSomething): + + def has_permission(self, request, view): + return Fal...
1dd8120dab6cdec4097bea1193a5b5b68d3bfe4f
salt/modules/win_groupadd.py
salt/modules/win_groupadd.py
''' Manage groups on Windows ''' def __virtual__(): ''' Set the group module if the kernel is Windows ''' return 'group' if __grains__['kernel'] == 'Windows' else False def add(name): ''' Add the specified group CLI Example:: salt '*' group.add foo ''' cmd = 'net localg...
Add Windows support to group add Add, remove and get info on Local Windows Groups
Add Windows support to group add Add, remove and get info on Local Windows Groups
Python
apache-2.0
saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt
--- +++ @@ -0,0 +1,90 @@ +''' +Manage groups on Windows +''' + +def __virtual__(): + ''' + Set the group module if the kernel is Windows + ''' + return 'group' if __grains__['kernel'] == 'Windows' else False + + +def add(name): + ''' + Add the specified group + + CLI Example:: + + salt '*'...
a04dddb09c276300c9a11dcbbe331ce2a32cff29
convert.py
convert.py
from AppKit import NSApplication, NSImage, NSImageCurrentFrame, NSGIFFileType; import sys, os dirname = sys.argv[1] files = os.listdir(dirname) for f in files: if '.gif' not in f: continue fName = os.path.join(dirname, f) tName=os.path.basename(fName) dir='/tmp/frames/' os.system('rm -rf %s && mkdi...
Convert script for .gif -> spritesheet.
Convert script for .gif -> spritesheet.
Python
mit
Mytherin/PokemonAI,Mytherin/PokemonAI,Mytherin/PokemonAI
--- +++ @@ -0,0 +1,27 @@ +from AppKit import NSApplication, NSImage, NSImageCurrentFrame, NSGIFFileType; import sys, os + +dirname = sys.argv[1] +files = os.listdir(dirname) +for f in files: + if '.gif' not in f: continue + fName = os.path.join(dirname, f) + tName=os.path.basename(fName) + dir='/tmp/frame...
ed7cc112adb6d54f1c2b79b941ab5455a17d9442
FlaskApp/app_ls.py
FlaskApp/app_ls.py
import subprocess import datetime from flask import Flask, render_template, redirect, url_for, request app = Flask(__name__) @app.route('/') def index(): return render_template('index.html') @app.route('/outlet') def rf_outlet(): return render_template('rf-outlet.html') @app.route('/hello/<name>') def he...
Add subprocess trial for webserver app
Add subprocess trial for webserver app
Python
bsd-3-clause
kbsezginel/raspberry-pi,kbsezginel/raspberry-pi,kbsezginel/raspberry-pi,kbsezginel/raspberry-pi
--- +++ @@ -0,0 +1,57 @@ +import subprocess +import datetime +from flask import Flask, render_template, redirect, url_for, request + +app = Flask(__name__) + + +@app.route('/') +def index(): + return render_template('index.html') + + +@app.route('/outlet') +def rf_outlet(): + return render_template('rf-outlet.h...
b6e8d93b661b4e65ecc6f5c150fcc1b1a4f26dc3
utils.py
utils.py
from numpy import array, cross, eye, dot from scipy.linalg import expm3,norm from math import sin, cos def rotate(axis, vector, angle): if axis == 'x': m = array([ [1, 0, 0], [0, cos(angle), -sin(angle)], [0, sin(angle), cos(angle)] ]) elif axis == 'y': ...
Add silly un-mathy rotation function
Add silly un-mathy rotation function
Python
mit
kirberich/3dscanner
--- +++ @@ -0,0 +1,27 @@ +from numpy import array, cross, eye, dot +from scipy.linalg import expm3,norm +from math import sin, cos + +def rotate(axis, vector, angle): + if axis == 'x': + m = array([ + [1, 0, 0], + [0, cos(angle), -sin(angle)], + [0, sin(angle), cos(angle)] +...
a1f13dd46cdd68f72002ba13d4875af659694f94
models/base_olims_model.py
models/base_olims_model.py
import copy def add_a_field(cls, field): setattr(cls, field.string, field) pass def add_a_getter(cls, field): fieldname = field.string getter_template = copy.deepcopy(field.get_getterTemplate()) getter_template.__doc__ = "get%s - method to get value of field: %s" % (fieldname,fieldname) getter...
import copy def add_a_field(cls, field): setattr(cls, field.string, field) pass def add_a_getter(cls, field): fieldname = field.string getter_template = copy.deepcopy(field.get_getterTemplate()) getter_template.__doc__ = "get%s - method to get value of field: %s" % (fieldname,fieldname) getter...
Make comment of 'add_a_getter' method
Make comment of 'add_a_getter' method
Python
agpl-3.0
sciCloud/OLiMS,yasir1brahim/OLiMS,sciCloud/OLiMS,sciCloud/OLiMS
--- +++ @@ -29,7 +29,7 @@ # 2. make getter methods for each model variable defined in step 1 for field in schema: add_a_field(cls, field) - add_a_getter(cls, field) +# add_a_getter(cls, field) pass pass pass
ba9214f7fca609948130d2ae56bb19805b79d59c
tests/rules/test_git_branch_list.py
tests/rules/test_git_branch_list.py
from thefuck import shells from thefuck.rules.git_branch_list import match, get_new_command from tests.utils import Command def test_match(): assert match(Command('git branch list'), None) def test_not_match(): assert not match(Command(), None) assert not match(Command('git commit'), None) assert not...
Add a test for git_branch_list rule
Add a test for git_branch_list rule
Python
mit
beni55/thefuck,mlk/thefuck,zhangzhishan/thefuck,AntonChankin/thefuck,suxinde2009/thefuck,nvbn/thefuck,NguyenHoaiNam/thefuck,levythu/thefuck,PLNech/thefuck,redreamality/thefuck,thinkerchan/thefuck,princeofdarkness76/thefuck,BertieJim/thefuck,ostree/thefuck,bigplus/thefuck,vanita5/thefuck,beni55/thefuck,sekaiamber/thefuc...
--- +++ @@ -0,0 +1,18 @@ +from thefuck import shells +from thefuck.rules.git_branch_list import match, get_new_command +from tests.utils import Command + +def test_match(): + assert match(Command('git branch list'), None) + + +def test_not_match(): + assert not match(Command(), None) + assert not match(Comma...
cecd767ef94f4bc890b8b19d2404528a7c4170bb
setup.py
setup.py
from setuptools import setup setup(name='LpSchedule', version='0.1', description='A API for Lviv Polytechnik schedule', author='Stepanov Valentyn', author_email='mr.valentyn.stepanov@gmail.com', url='http://example.com', install_requires=['Flask>=0.10.1', 'Flask-Script>=2.0.5','...
Add pythonic way to install
Add pythonic way to install
Python
mit
stenvix/lpschedule,stepanov-valentin/lpschedule,stepanov-valentin/lpschedule,stenvix/lpschedule,stepanov-valentin/lpschedule,stepanov-valentin/lpschedule,stenvix/lpschedule,stenvix/lpschedule
--- +++ @@ -0,0 +1,15 @@ +from setuptools import setup + +setup(name='LpSchedule', + version='0.1', + description='A API for Lviv Polytechnik schedule', + author='Stepanov Valentyn', + author_email='mr.valentyn.stepanov@gmail.com', + url='http://example.com', + install_requires=['Flask>=0...
95edd6f6d3076e78b995b9b02e7d32938734cbf2
setup.py
setup.py
from distutils.core import setup setup( name='udiskie', version='0.3.8', description='Removable disk automounter for udisks', author='Byron Clark', author_email='byron@theclarkfamily.name', url='http://bitbucket.org/byronclark/udiskie', license='MIT', packages=[ 'udiskie', ]...
from distutils.core import setup setup( name='udiskie', version='0.3.9', description='Removable disk automounter for udisks', author='Byron Clark', author_email='byron@theclarkfamily.name', url='http://bitbucket.org/byronclark/udiskie', license='MIT', packages=[ 'udiskie', ]...
Prepare for next development cycle.
Prepare for next development cycle.
Python
mit
coldfix/udiskie,khardix/udiskie,coldfix/udiskie,pstray/udiskie,pstray/udiskie,mathstuf/udiskie
--- +++ @@ -2,7 +2,7 @@ setup( name='udiskie', - version='0.3.8', + version='0.3.9', description='Removable disk automounter for udisks', author='Byron Clark', author_email='byron@theclarkfamily.name',
acf0b48055c339e67ead4b85c90a07ffdce60bf1
py/max-consecutive-ones.py
py/max-consecutive-ones.py
class Solution(object): def findMaxConsecutiveOnes(self, nums): """ :type nums: List[int] :rtype: int """ n = 0 m = 0 for c in nums: if c == 0: n = 0 else: n += 1 m = max(n, m) return ...
Add py solution for 485. Max Consecutive Ones
Add py solution for 485. Max Consecutive Ones 485. Max Consecutive Ones: https://leetcode.com/problems/max-consecutive-ones/
Python
apache-2.0
ckclark/leetcode,ckclark/leetcode,ckclark/leetcode,ckclark/leetcode,ckclark/leetcode,ckclark/leetcode
--- +++ @@ -0,0 +1,16 @@ +class Solution(object): + def findMaxConsecutiveOnes(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + n = 0 + m = 0 + for c in nums: + if c == 0: + n = 0 + else: + n += 1 +...
d86d117963ac87bfb11e731ea98d1803b2fcd609
test/test_utils.py
test/test_utils.py
# Copyright 2021 Sean Vig # # 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, sof...
Add test on anonymous file
Add test on anonymous file
Python
apache-2.0
flacjacket/pywayland
--- +++ @@ -0,0 +1,31 @@ +# Copyright 2021 Sean Vig +# +# 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 applica...
43cb60efabfdaab77fa2c8eee1a5d8730a321db1
samples/query_interfaces.py
samples/query_interfaces.py
#!/usr/bin/env python import requests from orionsdk import SwisClient npm_server = 'localhost' username = 'admin' password = '' verify = False if not verify: from requests.packages.urllib3.exceptions import InsecureRequestWarning requests.packages.urllib3.disable_warnings(InsecureRequestWarning) def main()...
Add example for pulling interfaces.
Add example for pulling interfaces.
Python
apache-2.0
solarwinds/orionsdk-python
--- +++ @@ -0,0 +1,39 @@ +#!/usr/bin/env python +import requests +from orionsdk import SwisClient + + +npm_server = 'localhost' +username = 'admin' +password = '' + +verify = False +if not verify: + from requests.packages.urllib3.exceptions import InsecureRequestWarning + requests.packages.urllib3.disable_warni...
358cdd4b89221cbb02e7b04fc83cebb06570b03a
mezzanine/twitter/defaults.py
mezzanine/twitter/defaults.py
""" Default settings for the ``mezzanine.twitter`` app. Each of these can be overridden in your project's settings module, just like regular Django settings. The ``editable`` argument for each controls whether the setting is editable via Django's admin. Thought should be given to how a setting is actually used before ...
""" Default settings for the ``mezzanine.twitter`` app. Each of these can be overridden in your project's settings module, just like regular Django settings. The ``editable`` argument for each controls whether the setting is editable via Django's admin. Thought should be given to how a setting is actually used before ...
Update the default twitter query since it's been flooded by movie tweets.
Update the default twitter query since it's been flooded by movie tweets.
Python
bsd-2-clause
readevalprint/mezzanine,theclanks/mezzanine,dovydas/mezzanine,scarcry/snm-mezzanine,industrydive/mezzanine,ryneeverett/mezzanine,mush42/mezzanine,AlexHill/mezzanine,industrydive/mezzanine,spookylukey/mezzanine,eino-makitalo/mezzanine,Cajoline/mezzanine,Cajoline/mezzanine,webounty/mezzanine,gradel/mezzanine,dekomote/mez...
--- +++ @@ -31,7 +31,7 @@ label=_("Default Twitter Query"), description=_("Twitter query to use for the default query type."), editable=True, - default="#django", + default="django mezzanine", ) register_setting(
d79a7f4e8be3cc9f0eb27da562bd0f1143005368
examples/power_on_swarm.py
examples/power_on_swarm.py
#!/usr/bin/python import time import sys from psphere.client import Client from psphere.managedobjects import VirtualMachine scatter_secs = 8 nodes = sys.argv[1:] client = Client() print("Powering on %s VMs" % len(nodes)) print("Estimated run time with %s seconds sleep between each power on: %s" % (scatter_...
Add a new example of powering on many VMs at once
Add a new example of powering on many VMs at once
Python
apache-2.0
graphite-server/psphere,jkinred/psphere
--- +++ @@ -0,0 +1,32 @@ +#!/usr/bin/python + +import time +import sys + +from psphere.client import Client +from psphere.managedobjects import VirtualMachine + +scatter_secs = 8 + +nodes = sys.argv[1:] + +client = Client() + +print("Powering on %s VMs" % len(nodes)) +print("Estimated run time with %s seconds sleep b...
eb77b1335afb9d9e29d39ca9ff4e3f0fa3d89a8d
Lib/test/test_pwd.py
Lib/test/test_pwd.py
import pwd import string verbose = 0 if __name__ == '__main__': verbose = 1 entries = pwd.getpwall() for e in entries: name = e[0] uid = e[2] if verbose: print name, uid dbuid = pwd.getpwuid(uid) if dbuid[0] <> name: print 'Mismatch in pwd.getpwuid()' dbname = pwd.getpwnam(name) if ...
Test of the pwd module
Test of the pwd module
Python
mit
sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator
--- +++ @@ -0,0 +1,70 @@ +import pwd +import string + +verbose = 0 +if __name__ == '__main__': + verbose = 1 + +entries = pwd.getpwall() + +for e in entries: + name = e[0] + uid = e[2] + if verbose: + print name, uid + dbuid = pwd.getpwuid(uid) + if dbuid[0] <> name: + print 'Mismatch in pwd.getpwui...
ea5bd5fe05c6d2a9580f5ca6c2238971c28e36bc
apps/plea/migrations/0026_caseoffencefilter.py
apps/plea/migrations/0026_caseoffencefilter.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('plea', '0025_auto_20151210_1526'), ] operations = [ migrations.CreateModel( name='CaseOffenceFilter', ...
Add migration for CaseOffenceFilter model
Add migration for CaseOffenceFilter model
Python
mit
ministryofjustice/manchester_traffic_offences_pleas,ministryofjustice/manchester_traffic_offences_pleas,ministryofjustice/manchester_traffic_offences_pleas,ministryofjustice/manchester_traffic_offences_pleas
--- +++ @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +from __future__ import unicode_literals + +from django.db import models, migrations + + +class Migration(migrations.Migration): + + dependencies = [ + ('plea', '0025_auto_20151210_1526'), + ] + + operations = [ + migrations.CreateModel( + ...