commit
stringlengths
40
40
old_file
stringlengths
4
236
new_file
stringlengths
4
236
old_contents
stringlengths
1
3.26k
new_contents
stringlengths
16
4.43k
subject
stringlengths
16
624
message
stringlengths
17
3.29k
lang
stringclasses
5 values
license
stringclasses
13 values
repos
stringlengths
5
91.5k
67752442760221c2e53990bb5dd10f1e045d74a1
nltk_training/information_extraction.py
nltk_training/information_extraction.py
#!/usr/bin/python # -*- coding: UTF-8 -*- from __future__ import division import feedparser, os from BeautifulSoup import BeautifulSoup import nltk, re, pprint from nltk import word_tokenize # from urllib2 import Request as request import urllib2 def ie_preprocess(document): sentences = nltk.sent_tokenize(document) ...
#!/usr/bin/python # -*- coding: UTF-8 -*- from __future__ import division import feedparser, os from BeautifulSoup import BeautifulSoup import nltk, re, pprint from nltk import word_tokenize # from urllib2 import Request as request import urllib2 def ie_preprocess(document): sentences = nltk.sent_tokenize(document) ...
Add lastest updates to script
Add lastest updates to script
Python
apache-2.0
fullbright/gary-reporter,fullbright/gary-reporter
a36adf795f370877a472fa4730a3eb31271b8b23
subversion/bindings/swig/python/tests/run_all.py
subversion/bindings/swig/python/tests/run_all.py
import sys, os bindir = os.path.dirname(sys.argv[0]) sys.path[0:0] = [ os.getcwd(), "%s/.libs" % os.getcwd(), \ "%s/.." % bindir, "%s/../.libs" % bindir ] import unittest import pool import trac.versioncontrol.tests # Run all tests def suite(): """Run all tests""" suite = unittest.TestSuite() ...
import sys, os bindir = os.path.dirname(sys.argv[0]) sys.path[0:0] = [ os.getcwd(), "%s/.libs" % os.getcwd(), \ "%s/.." % bindir, "%s/../.libs" % bindir ] # OSes without RPATH support are going to have to do things here to make # the correct shared libraries be found. if sys.platform == 'cygwin': i...
Make the Python bindings testsuite be able to find the needed shared libraries on Cygwin. Needed to compensate for Windows' complete lack of library RPATHs.
Make the Python bindings testsuite be able to find the needed shared libraries on Cygwin. Needed to compensate for Windows' complete lack of library RPATHs. * subversion/bindings/swig/python/tests/run_all.py: On Cygwin, manipulate $PATH so that the relevant shared libraries are found.
Python
apache-2.0
jmckaskill/subversion,jmckaskill/subversion,jmckaskill/subversion,jmckaskill/subversion,jmckaskill/subversion,jmckaskill/subversion,jmckaskill/subversion,jmckaskill/subversion
ef6c29b6ebd8e3b536dcd63cfce683a6b69897d7
nyuki/workflow/tasks/python_script.py
nyuki/workflow/tasks/python_script.py
import logging from tukio.task import register from tukio.task.holder import TaskHolder log = logging.getLogger(__name__) @register('python_script', 'execute') class PythonScript(TaskHolder): """ Mainly a testing task """ SCHEMA = { 'type': 'object', 'properties': { 'sc...
import logging from tukio.task import register from tukio.task.holder import TaskHolder log = logging.getLogger(__name__) @register('python_script', 'execute') class PythonScript(TaskHolder): """ Mainly a testing task """ SCHEMA = { 'type': 'object', 'properties': { 'sc...
Improve script task to allow multiline
Improve script task to allow multiline
Python
apache-2.0
optiflows/nyuki,optiflows/nyuki,gdraynz/nyuki,gdraynz/nyuki
223b58cb0f9c63543a4d23f75db4450ce93ab86d
readthedocs/builds/forms.py
readthedocs/builds/forms.py
import logging from django import forms from readthedocs.builds.models import VersionAlias, Version from readthedocs.core.utils import trigger_build from readthedocs.projects.models import Project from readthedocs.projects.tasks import clear_artifacts log = logging.getLogger(__name__) class AliasForm(forms.ModelF...
import logging from django import forms from readthedocs.builds.models import VersionAlias, Version from readthedocs.core.utils import trigger_build from readthedocs.projects.models import Project from readthedocs.projects.tasks import clear_artifacts log = logging.getLogger(__name__) class AliasForm(forms.ModelF...
Handle built state tracking on versions
Handle built state tracking on versions
Python
mit
espdev/readthedocs.org,pombredanne/readthedocs.org,espdev/readthedocs.org,stevepiercy/readthedocs.org,rtfd/readthedocs.org,davidfischer/readthedocs.org,istresearch/readthedocs.org,davidfischer/readthedocs.org,rtfd/readthedocs.org,safwanrahman/readthedocs.org,davidfischer/readthedocs.org,rtfd/readthedocs.org,tddv/readth...
b593c9fa9939c7fc524a2d4a1c3a7e337fe8de07
wooey/migrations/0037_populate-jsonfield.py
wooey/migrations/0037_populate-jsonfield.py
# -*- coding: utf-8 -*- # Generated by Django 1.9.13 on 2018-03-04 23:14 from __future__ import unicode_literals from django.db import migrations def populate_default(apps, schema_editor): ScriptParameter = apps.get_model('wooey', 'ScriptParameter') for obj in ScriptParameter.objects.all(): obj.defau...
# -*- coding: utf-8 -*- # Generated by Django 1.9.13 on 2018-03-04 23:14 from __future__ import unicode_literals import json from django.db import migrations def populate_default(apps, schema_editor): ScriptParameter = apps.get_model('wooey', 'ScriptParameter') for obj in ScriptParameter.objects.all(): ...
Convert iniital json field if possible in migration
Convert iniital json field if possible in migration
Python
bsd-3-clause
wooey/Wooey,wooey/Wooey,wooey/Wooey,wooey/Wooey
b6fff4186de098946cc1e4c0204f78936f73044f
tests/basics/tuple1.py
tests/basics/tuple1.py
# basic tuple functionality x = (1, 2, 3 * 4) print(x) try: x[0] = 4 except TypeError: print("TypeError") print(x) try: x.append(5) except AttributeError: print("AttributeError") print(x[1:]) print(x[:-1]) print(x[2:3]) print(x + (10, 100, 10000)) # construction of tuple from large iterator (tests im...
# basic tuple functionality x = (1, 2, 3 * 4) print(x) try: x[0] = 4 except TypeError: print("TypeError") print(x) try: x.append(5) except AttributeError: print("AttributeError") print(x[1:]) print(x[:-1]) print(x[2:3]) print(x + (10, 100, 10000)) # inplace add operator x += (10, 11, 12) print(x) # ...
Add test for tuple inplace add.
tests/basics: Add test for tuple inplace add.
Python
mit
infinnovation/micropython,dmazzella/micropython,henriknelson/micropython,chrisdearman/micropython,deshipu/micropython,AriZuu/micropython,infinnovation/micropython,AriZuu/micropython,puuu/micropython,alex-robbins/micropython,torwag/micropython,SHA2017-badge/micropython-esp32,tralamazza/micropython,chrisdearman/micropyth...
c306e731fde754dc11629ff32f7d0b6afb510e81
controllers/accounts_manager.py
controllers/accounts_manager.py
from flask_restful import Resource class AccountsManager(Resource): """docstring for AccountsManager.""" def get(self): return {"route": "login"} def post(self): return {"route": "register"}
from flask import jsonify, make_response from flask_restful import Resource, reqparse from app.models import User from app.db_instance import save from validator import validate class AccountsManager(Resource): """docstring for AccountsManager.""" def __init__(self): self.parser = reqparse.RequestPars...
Add Register resource to handle user registration and save user data to the database
Add Register resource to handle user registration and save user data to the database
Python
mit
brayoh/bucket-list-api
63c640f2d16b033cc8dff426768cd1c6cbaa5626
Lib/distutils/__init__.py
Lib/distutils/__init__.py
"""distutils The main package for the Python Module Distribution Utilities. Normally used from a setup script as from distutils.core import setup setup (...) """ # This module should be kept compatible with Python 2.1. __revision__ = "$Id$" import sys __version__ = "%d.%d.%d" % sys.version_info[:3] del sys...
"""distutils The main package for the Python Module Distribution Utilities. Normally used from a setup script as from distutils.core import setup setup (...) """ # This module should be kept compatible with Python 2.1. __revision__ = "$Id$" # Distutils version # # Please coordinate with Marc-Andre Lemburg ...
Revert to having static version numbers again.
Revert to having static version numbers again.
Python
mit
sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator
61bfc6ac93db9bf11c88f549c9122ac5b498e3d6
Lib/test/test_contains.py
Lib/test/test_contains.py
from test_support import TestFailed class base_set: def __init__(self, el): self.el = el class set(base_set): def __contains__(self, el): return self.el == el class seq(base_set): def __getitem__(self, n): return [self.el][n] def check(ok, *args): if not ok: raise TestFailed, join(map(str, a...
from test_support import TestFailed class base_set: def __init__(self, el): self.el = el class set(base_set): def __contains__(self, el): return self.el == el class seq(base_set): def __getitem__(self, n): return [self.el][n] def check(ok, *args): if not ok: raise TestFailed, join(map(str, a...
Add tests for char in string -- including required exceptions for non-char in string.
Add tests for char in string -- including required exceptions for non-char in string.
Python
mit
sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator
850e328f024d79623256a8b38ee0f054d4210ce5
src/constants.py
src/constants.py
#!/usr/bin/env python TRAJECTORY = 'linear' if TRAJECTORY == 'linear': SIMULATION_TIME_IN_SECONDS = 80.0 elif TRAJECTORY == 'circular': SIMULATION_TIME_IN_SECONDS = 120.0 elif TRAJECTORY == 'squared': SIMULATION_TIME_IN_SECONDS = 160.0 DELTA_T = 0.1 # this is the sampling time STEPS = int(SIMULATION_TIME_...
#!/usr/bin/env python TRAJECTORY = 'linear' CONTROLLER = 'pid' if TRAJECTORY == 'linear': SIMULATION_TIME_IN_SECONDS = 80.0 elif TRAJECTORY == 'circular': SIMULATION_TIME_IN_SECONDS = 120.0 elif TRAJECTORY == 'squared': SIMULATION_TIME_IN_SECONDS = 160.0 DELTA_T = 0.1 # this is the sampling time STEPS = i...
Create constant to define a controller that will be used
Create constant to define a controller that will be used
Python
mit
bit0001/trajectory_tracking,bit0001/trajectory_tracking
279e56746984aac878d453c09437a6f6514e7342
xpserver_web/models.py
xpserver_web/models.py
from django.db import models from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True) activation_code = models.CharField(max_length=255, default="0000") fcm_registration_id = models.CharField(max_length=255,...
from django.db import models from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True) activation_code = models.CharField(max_length=255, default="0000") fcm_registration_id = models.CharField(max_length=255,...
Change str method of profile
Change str method of profile
Python
mit
xp2017-hackergarden/server,xp2017-hackergarden/server,xp2017-hackergarden/server,xp2017-hackergarden/server
965e2dc74afef720055db315863e038e500fc44d
mangopaysdk/types/dto.py
mangopaysdk/types/dto.py
class Dto(object): """Abstract class for all DTOs (entities and their composites).""" def GetSubObjects(self): """Get array with mapping which property is object and what type of object. To be overridden in child class if has any sub objects. return array """ return ...
class Dto(object): """Abstract class for all DTOs (entities and their composites).""" def __str__(self): return str(self.__to_dict()) def __to_dict(self): data = {} for key in dir(self): if key.startswith("__"): continue # Skip private fields value = getatt...
Add a __str__() method to Dto to make debugging easier
Add a __str__() method to Dto to make debugging easier
Python
mit
chocopoche/mangopay2-python-sdk,Mangopay/mangopay2-python-sdk
23b08d24405badeb88461006d29426ab452a2ac4
hooks/post_gen_project.py
hooks/post_gen_project.py
import os import subprocess src = os.path.join(os.getcwd(), 'src', 'utils', 'prepare-commit-msg.py') dst = os.path.join('.git', 'hooks', 'prepare-commit-msg') process = subprocess.call(['git', 'init']) os.symlink(src, dst)
import os import subprocess src = os.path.join(os.getcwd(), 'src', 'utils', 'prepare-commit-msg.py') dst = os.path.join('.git', 'hooks', 'prepare-commit-msg') subprocess.call(['git', 'init']) os.symlink(src, dst) subprocess.call(['git', 'add', '-A']) subprocess.call(['git', 'commit', '-m', 'Initial commit'])
Add inital commit to post generate hook
Add inital commit to post generate hook
Python
mit
Empiria/matador-cookiecutter
6a80b3c6d27ad494bbc3c9b9d67b6445b0bbfc40
example/sp-wsgi/service_conf.py
example/sp-wsgi/service_conf.py
from saml2.assertion import Policy HOST = '127.0.0.1' PORT = 8087 HTTPS = False # Which groups of entity categories to use POLICY = Policy( { "default": {"entity_categories": ["swamid", "edugain"]} } ) # HTTPS cert information SERVER_CERT = "pki/ssl.crt" SERVER_KEY = "pki/ssl.pem" CERT_CHAIN = ""
from saml2.assertion import Policy HOST = '127.0.0.1' PORT = 8087 HTTPS = False # Which groups of entity categories to use POLICY = Policy( { "default": {"entity_categories": ["swamid", "edugain"]} } ) # HTTPS cert information SERVER_CERT = "pki/mycert.pem" SERVER_KEY = "pki/mykey.pem" CERT_CHAIN = "...
Update example HTTPS cert & key filenames.
Update example HTTPS cert & key filenames. pki/my{cert,key}.pem are used for request payloads; set those as the defaults for HTTPS as well. Note that HTTPS isn't necessarily in a working state - this just gets us a bit closer.
Python
bsd-2-clause
tpazderka/pysaml2,tpazderka/pysaml2,Runscope/pysaml2,Runscope/pysaml2
7bc693102a5394bb73b3df2320fca5a35bebc91f
test/test_vocab.py
test/test_vocab.py
import numpy as np import unittest from torchtext import vocab from collections import Counter class TestVocab(unittest.TestCase): def test_vocab(self): c = Counter(['hello', 'world']) v = vocab.Vocab(c, vectors='glove.test_twitter.27B.200d') self.assertEqual(v.itos, ['<unk>', '<pad>', '...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from collections import Counter import unittest import numpy as np from torchtext import vocab class TestVocab(unittest.TestCase): def test_vocab(self): c = Counter({'hello': 4, 'world': 3, 'ᑌᑎIᑕOᗪᕮ_Tᕮ᙭T': 5, 'freq_too_low': 2}) v = ...
Test vocab min_freq and specials vocab args, as well as unicode input
Test vocab min_freq and specials vocab args, as well as unicode input
Python
bsd-3-clause
pytorch/text,pytorch/text,pytorch/text,pytorch/text
b56712563e4205ccbf8b98deace4197e2f250361
movement.py
movement.py
if __name__ == "__main__": x, y = 0, 0 steps = 0 while True: dir = input('Your current position is %s, %s, where would you like to move to? ' % (str(x), str(y))) directions = { 'north': (0, 1), 'south' : (0, -1), 'east' : (1, 0), ...
if __name__ == "__main__": x, y = 0, 0 steps = 0 while True: dir = input('Your current position is %s, %s, where would you like to move to? ' % (str(x), str(y))) directions = { 'north': (0, 1), 'south' : (0, -1), 'east' : (1, 0), ...
Add abbreviations and space handling
Add abbreviations and space handling
Python
mit
mewturn/Python
c797481691f44f6741d2aa8491c7a112674ddaab
neb/node.py
neb/node.py
from neb.api import TrinityResource from neb.relationship import Relationship from neb.statistic import NodeStatistic class Node(TrinityResource): def create(self, node_id, **kwargs): params = dict(id=node_id, node=kwargs) return self.post(self._node_path(), payload=params) def connect(self, t...
from neb.api import TrinityResource from neb.relationship import Relationship from neb.statistic import NodeStatistic class Node(TrinityResource): def create(self, node_id, **kwargs): params = dict(id=node_id, node=kwargs) return self.post(self._node_path(), payload=params) def connect(self, t...
Allow Node to Node connection.
Allow Node to Node connection.
Python
mit
peplin/neb
9443ba9d5cccde590aa07b2d7c74a7a4ea90fe6d
opps/urls.py
opps/urls.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from django.conf.urls import patterns, url, include from django.contrib import admin admin.autodiscover() urlpatterns = patterns( '', #url(r'^admin/images/mass/', include('opps.images.urls', # namespace='images', app_name='images...
#!/usr/bin/env python # -*- coding: utf-8 -*- from django.conf.urls import patterns, url, include from django.contrib import admin admin.autodiscover() urlpatterns = patterns( '', url(r'^admin/', include(admin.site.urls)), url(r'^redactor/', include('redactor.urls')), url(r'^sitemap', include('opps...
Remove url images mass, not used
Remove url images mass, not used
Python
mit
YACOWS/opps,jeanmask/opps,jeanmask/opps,williamroot/opps,YACOWS/opps,williamroot/opps,jeanmask/opps,YACOWS/opps,opps/opps,opps/opps,williamroot/opps,williamroot/opps,opps/opps,YACOWS/opps,jeanmask/opps,opps/opps
37c63e6ea5c14a0c7aae11581ae32f24eaaa9641
test/layers_test.py
test/layers_test.py
import theanets import numpy as np class TestLayer: def test_build(self): layer = theanets.layers.build('feedforward', nin=2, nout=4) assert isinstance(layer, theanets.layers.Layer) class TestFeedforward: def test_create(self): l = theanets.layers.Feedforward(nin=2, nout=4) a...
import theanets import numpy as np class TestLayer: def test_build(self): layer = theanets.layers.build('feedforward', nin=2, nout=4) assert isinstance(layer, theanets.layers.Layer) class TestFeedforward: def test_create(self): l = theanets.layers.Feedforward(nin=2, nout=4) a...
Update layers test for RNN change.
Update layers test for RNN change.
Python
mit
devdoer/theanets,chrinide/theanets,lmjohns3/theanets
27ee536137a98a317f2cfbb2010fa5fe31037e99
txircd/modules/cmd_user.py
txircd/modules/cmd_user.py
from twisted.words.protocols import irc from txircd.modbase import Command class UserCommand(Command): def onUse(self, user, params): if user.registered == 0: self.sendMessage(irc.ERR_ALREADYREGISTRED, ":Unauthorized command (already registered)") return if params and len(params) < 4: user.sendMessage(ir...
from twisted.words.protocols import irc from txircd.modbase import Command class UserCommand(Command): def onUse(self, user, data): if not user.username: user.registered -= 1 user.username = data["ident"] user.realname = data["gecos"] if user.registered == 0: user.register() def processParams(self, u...
Update the USER command to take advantage of core capabilities as well
Update the USER command to take advantage of core capabilities as well
Python
bsd-3-clause
DesertBus/txircd,Heufneutje/txircd,ElementalAlchemist/txircd
939319ddece1925c8c3152f4437b4848749b85b3
config/fuzz_pox_mesh.py
config/fuzz_pox_mesh.py
from experiment_config_lib import ControllerConfig from sts.topology import MeshTopology from sts.control_flow import Fuzzer from sts.input_traces.input_logger import InputLogger from sts.invariant_checker import InvariantChecker from sts.simulation_state import SimulationConfig # Use POX as our controller command_lin...
from experiment_config_lib import ControllerConfig from sts.topology import MeshTopology from sts.control_flow import Fuzzer from sts.input_traces.input_logger import InputLogger from sts.invariant_checker import InvariantChecker from sts.simulation_state import SimulationConfig # Use POX as our controller command_lin...
Add a config that exercises the Multiplexed socketS
Add a config that exercises the Multiplexed socketS
Python
apache-2.0
ucb-sts/sts,ucb-sts/sts,jmiserez/sts,jmiserez/sts
dc05182f04dcebf61d368fe9f834b37d75b59bfd
Lib/fontmake/errors.py
Lib/fontmake/errors.py
class FontmakeError(Exception): """Base class for all fontmake exceptions.""" pass class TTFAError(FontmakeError): def __init__(self, exitcode): self.exitcode = exitcode def __str__(self): return "ttfautohint command failed: error " + str(self.exitcode)
import os class FontmakeError(Exception): """Base class for all fontmake exceptions. This exception is intended to be chained to the original exception. The main purpose is to provide a source file trail that points to where the explosion came from. """ def __init__(self, msg, source_file): ...
Add source trail logic to FontmakeError and partly TTFAError
Add source trail logic to FontmakeError and partly TTFAError
Python
apache-2.0
googlei18n/fontmake,googlei18n/fontmake,googlefonts/fontmake,googlefonts/fontmake
232db259f2c202e60692563ec05b456b5158449e
django_replicated/router.py
django_replicated/router.py
# -*- coding:utf-8 -*- import random from django.db.utils import DEFAULT_DB_ALIAS from django.conf import settings class ReplicationRouter(object): def __init__(self): self.state_stack = ['master'] self._state_change_enabled = True def set_state_change(self, enabled): self._state_cha...
# -*- coding:utf-8 -*- import random from django.db import connections from django.db.utils import DEFAULT_DB_ALIAS from django.conf import settings def is_alive(db): try: if db.connection is not None and hasattr(db.connection, 'ping'): db.connection.ping() else: db.cursor...
Check if slaves are alive and fallback to other slaves and eventually to master.
Check if slaves are alive and fallback to other slaves and eventually to master.
Python
bsd-3-clause
dmirain/django_replicated,Zunonia/django_replicated,lavr/django_replicated
c13dbbc35faf567cb7a10ccacb1fcd070c8773c1
llvmlite/binding/common.py
llvmlite/binding/common.py
import atexit def _encode_string(s): encoded = s.encode('latin1') return encoded def _decode_string(b): return b.decode('latin1') _encode_string.__doc__ = """Encode a string for use by LLVM.""" _decode_string.__doc__ = """Decode a LLVM character (byte)string.""" _shutting_down = [False] def _at_sh...
import atexit def _encode_string(s): encoded = s.encode('utf-8') return encoded def _decode_string(b): return b.decode('utf-8') _encode_string.__doc__ = """Encode a string for use by LLVM.""" _decode_string.__doc__ = """Decode a LLVM character (byte)string.""" _shutting_down = [False] def _at_shut...
Switch encoding to UTF-8 from latin1
Switch encoding to UTF-8 from latin1 This change was originally made in PR #53, but may no longer be required (and may cause issues with comments in IR that use non-latin1 characters).
Python
bsd-2-clause
numba/llvmlite,numba/llvmlite,numba/llvmlite,numba/llvmlite
d6bc297b71c9cb2bce45bdcd20f99f9fe642cf01
plotting.py
plotting.py
#!/usr/bin/env python """ Set of helper function and variables for plotting. This module provides a set of functions and variables that will be useful for plotting. """ class ColorMarker: def __init__(self): # A list of colors self._colors = ['k', 'b', 'g', 'c', 'm', 'y'] # A list of mar...
#!/usr/bin/env python """ Set of helper function and variables for plotting. This module provides a set of functions and variables that will be useful for plotting. """ class ColorMarker: def __init__(self): # A list of colors self._colors = ['k', 'b', 'g', 'c', 'm', 'y'] # A list of mar...
Fix naming to folliwng naming conventions for mclab
Fix naming to folliwng naming conventions for mclab
Python
mit
secimTools/SECIMTools,secimTools/SECIMTools,secimTools/SECIMTools
a670b598f4416b0e99acd7442e5a51295a5daaa3
tests/test_utils.py
tests/test_utils.py
import os import time import unittest from helpers.utils import sigchld_handler, sigterm_handler, sleep def nop(*args, **kwargs): pass def os_waitpid(a, b): return (0, 0) def time_sleep(_): sigchld_handler(None, None) class TestUtils(unittest.TestCase): def __init__(self, method_name='runTest'...
import os import time import unittest from helpers.utils import reap_children, sigchld_handler, sigterm_handler, sleep def nop(*args, **kwargs): pass def os_waitpid(a, b): return (0, 0) def time_sleep(_): sigchld_handler(None, None) class TestUtils(unittest.TestCase): def __init__(self, method...
Implement unit test for reap_children function
Implement unit test for reap_children function
Python
mit
jinty/patroni,sean-/patroni,jinty/patroni,pgexperts/patroni,sean-/patroni,zalando/patroni,pgexperts/patroni,zalando/patroni
8c19b6dafa599dc284bb8ef740aa0426d9246dc6
linter.py
linter.py
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Bruno JJE # Copyright (c) 2015 Bruno JJE # # License: MIT # """This module exports the Ghdl plugin class.""" from SublimeLinter.lint import Linter class Ghdl(Linter): """Provides an interface to ghdl.""" ...
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Bruno JJE # Copyright (c) 2015 Bruno JJE # # License: MIT # """This module exports the Ghdl plugin class.""" from SublimeLinter.lint import Linter class Ghdl(Linter): """Provides an interface to ghdl.""" ...
Change 'tempfile_suffix' and remove filename check.
Change 'tempfile_suffix' and remove filename check.
Python
mit
BrunoJJE/SublimeLinter-contrib-ghdl
3738df68d89e8eb0743378ecb89659e44cbb999d
troposphere/qldb.py
troposphere/qldb.py
# Copyright (c) 2012-2019, Mark Peek <mark@peek.org> # All rights reserved. # # See LICENSE file for full license. # # *** Do not modify - this file is autogenerated *** # Resource specification version: 6.1.0 from . import AWSObject from troposphere import Tags from .validators import boolean class Ledger(AWSObjec...
# Copyright (c) 2012-2019, Mark Peek <mark@peek.org> # All rights reserved. # # See LICENSE file for full license. # # *** Do not modify - this file is autogenerated *** # Resource specification version: 16.1.0 from . import AWSObject from . import AWSProperty from troposphere import Tags from .validators import bool...
Add AWS::QLDB::Stream per 2020-07-08 update
Add AWS::QLDB::Stream per 2020-07-08 update
Python
bsd-2-clause
cloudtools/troposphere,cloudtools/troposphere
96439cb26a09158f112541025a6c2901b983eae9
tests/test_pay_onetime.py
tests/test_pay_onetime.py
# -*- coding: utf-8 -*- def test_pay_onetime(iamport): # Without 'card_number' payload_notEnough = { 'merchant_uid': 'qwer1234', 'amount': 5000, 'expiry': '2019-03', 'birth': '500203', 'pwd_2digit': '19' } try: iamport.pay_onetime(**payload_notEnough) ...
# -*- coding: utf-8 -*- import string, random def test_pay_onetime(iamport): merchant_uid = ''.join( random.choice(string.ascii_uppercase + string.digits) for _ in range(10) ) # Without 'card_number' payload_not_enough = { 'merchant_uid': merchant_uid, 'amount': 5000,...
Add random merchant_uid for continous testing
Add random merchant_uid for continous testing
Python
mit
iamport/iamport-rest-client-python
55ff308a538b80796b10d12d9acd1f1b84010d17
bluebottle/common/management/commands/makemessages.py
bluebottle/common/management/commands/makemessages.py
import json import tempfile from django.core.management.commands.makemessages import Command as BaseCommand from bluebottle.clients.utils import get_currencies class Command(BaseCommand): """ Extend the makemessages to include some of the fixtures """ fixtures = [ ('bb_projects', 'project_data.json...
import json import os from django.core.management.commands.makemessages import Command as BaseCommand from bluebottle.clients.utils import get_currencies class Command(BaseCommand): """ Extend the makemessages to include some of the fixtures """ fixtures = [ ('bb_projects', 'project_data.json'), ...
Make sure we always use the same filename for the fixtures translations. This way the translations do not contain accidental changes.
Make sure we always use the same filename for the fixtures translations. This way the translations do not contain accidental changes.
Python
bsd-3-clause
onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle
b4ef0f107ca8fefbe556babb00f31c7b88019d50
pydarkstar/__init__.py
pydarkstar/__init__.py
__version__ = 0.1 import pydarkstar.logutils import logging pydarkstar.logutils.setError() try: import sqlalchemy except ImportError as e: logging.exception(e.__class__.__name__) logging.error('pip install sqlalchemy') exit(-1) try: import pymysql except ImportError as e: logging.exception(e...
__version__ = 0.1 import pydarkstar.logutils import logging pydarkstar.logutils.setError() try: import sqlalchemy except ImportError as e: logging.exception(e.__class__.__name__) logging.error('pip install sqlalchemy') exit(-1) try: import pymysql except ImportError as e: logging.exception(e...
Revert "Change imports to relative."
Revert "Change imports to relative." This reverts commit 9d0990249b7e0e46e38a665cb8c32a1ee435c291.
Python
mit
LegionXI/pydarkstar,AdamGagorik/pydarkstar
b220aea07d233a608505ecd73f977a6920e867e0
python/luck-balance.py
python/luck-balance.py
#!/bin/python3 import math import os import random import re import sys def max_luck_balance(contests, num_can_lose): """ Returns a single integer denoting the maximum amount of luck Lena can have after all the contests. """ balance = 0 unimportant_contests = [contest for contest in contests i...
#!/bin/python3 import math import os import random import re import sys def max_luck_balance(contests, num_can_lose): """ Returns a single integer denoting the maximum amount of luck Lena can have after all the contests. """ balance = 0 # We can lose all unimportant contests. unimportant_...
Add dev comments and fix variable naming
Add dev comments and fix variable naming
Python
mit
rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank
29aeca4df24c84cecd48f0893da94624dab0e1c7
manage.py
manage.py
import os from app import create_app from flask.ext.script import Manager app = create_app(os.getenv('FLASK_CONFIG') or 'default') manager = Manager(app) if __name__ == '__main__': manager.run()
import os from app import create_app, db from app.models import User from flask.ext.script import Manager app = create_app(os.getenv('FLASK_CONFIG') or 'default') manager = Manager(app) @manager.command def adduser(email, username, admin=False): """ Register a new user""" from getpass import getpass password ...
Add a custom script command to add a user to the database
Add a custom script command to add a user to the database
Python
mit
finnurtorfa/aflafrettir.is,finnurtorfa/aflafrettir.is,finnurtorfa/aflafrettir.is,finnurtorfa/aflafrettir.is
4ee589cd8fd7e60606524e26a3b69e202242b75c
meinberlin/apps/servicekonto/apps.py
meinberlin/apps/servicekonto/apps.py
from allauth.socialaccount import providers from django.apps import AppConfig from .provider import ServiceKontoProvider class Config(AppConfig): name = 'meinberlin.apps.servicekonto' label = 'meinberlin_servicekonto' def ready(self): providers.registry.register(ServiceKontoProvider)
from allauth.socialaccount import providers from django.apps import AppConfig class Config(AppConfig): name = 'meinberlin.apps.servicekonto' label = 'meinberlin_servicekonto' def ready(self): from .provider import ServiceKontoProvider providers.registry.register(ServiceKontoProvider)
Fix servicekonto import to be lazy on ready
Fix servicekonto import to be lazy on ready
Python
agpl-3.0
liqd/a4-meinberlin,liqd/a4-meinberlin,liqd/a4-meinberlin,liqd/a4-meinberlin
aa780dc20583882c03fe1e3cd37f57c3cf9c7f17
taiga/projects/migrations/0006_auto_20141029_1040.py
taiga/projects/migrations/0006_auto_20141029_1040.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations def update_total_milestones(apps, schema_editor): Project = apps.get_model("projects", "Project") qs = Project.objects.filter(total_milestones__isnull=True) qs.update(total_milestones=0) class Migrat...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations def update_total_milestones(apps, schema_editor): Project = apps.get_model("projects", "Project") qs = Project.objects.filter(total_milestones__isnull=True) qs.update(total_milestones=0) class Migrat...
Add missing parameters (seems bug on django 1.7.x)
Add missing parameters (seems bug on django 1.7.x)
Python
agpl-3.0
xdevelsistemas/taiga-back-community,astronaut1712/taiga-back,astagi/taiga-back,Tigerwhit4/taiga-back,gam-phon/taiga-back,CMLL/taiga-back,dayatz/taiga-back,dycodedev/taiga-back,joshisa/taiga-back,joshisa/taiga-back,rajiteh/taiga-back,19kestier/taiga-back,Zaneh-/bearded-tribble-back,CoolCloud/taiga-back,coopsource/taiga-...
26585bcc2a4da3a53b1b13d4d1728e2533b12140
move_tab.py
move_tab.py
# -*- coding: utf-8 -*- """ Move Tab Plugin for Sublime Text to move tabs around Copyright (c) 2012 Frédéric Massart - FMCorz.net Licensed under The MIT License Redistributions of files must retain the above copyright notice. http://github.com/FMCorz/MoveTab """ import sublime_plugin class MoveTabCommand(sublime...
""" Move Tab Plugin for Sublime Text to move tabs around Copyright (c) 2012 Frédéric Massart - FMCorz.net Licensed under The MIT License Redistributions of files must retain the above copyright notice. http://github.com/FMCorz/MoveTab """ import sublime_plugin class MoveTabCommand(sublime_plugin.WindowCommand): ...
Remove outdated and redundant encoding specifier
Remove outdated and redundant encoding specifier
Python
mit
SublimeText/MoveTab
caaa59ca23d7405ff16726d509e3c0d4e659baec
djstripe/migrations/0023_auto_20170307_0937.py
djstripe/migrations/0023_auto_20170307_0937.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-03-07 09:37 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ...
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-03-07 09:37 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models DJSTRIPE_SUBSCRIBER_MODEL = getattr(settings, "DJSTRIPE_SUBSCRIBER_MODEL", settings.AUTH_USER_MODEL) class Migration(migrations....
Fix migration 0023 subscriber model reference
Fix migration 0023 subscriber model reference
Python
mit
pydanny/dj-stripe,jameshiew/dj-stripe,tkwon/dj-stripe,pydanny/dj-stripe,jleclanche/dj-stripe,jleclanche/dj-stripe,jameshiew/dj-stripe,tkwon/dj-stripe,dj-stripe/dj-stripe,kavdev/dj-stripe,kavdev/dj-stripe,dj-stripe/dj-stripe
a55765af4af8646a3ec95de2e8274b1c5584ee10
nova/policies/fixed_ips.py
nova/policies/fixed_ips.py
# Copyright 2016 Cloudbase Solutions Srl # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless r...
# Copyright 2016 Cloudbase Solutions Srl # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless r...
Add policy description for os-fixed-ips
Add policy description for os-fixed-ips This commit adds policy doc for os-fixed-ips policies. Partial implement blueprint policy-docs Change-Id: Ief255af699cee217ebf963a2c36f9e819ef4ef90
Python
apache-2.0
openstack/nova,jianghuaw/nova,vmturbo/nova,gooddata/openstack-nova,Juniper/nova,rahulunair/nova,Juniper/nova,jianghuaw/nova,jianghuaw/nova,gooddata/openstack-nova,vmturbo/nova,vmturbo/nova,rahulunair/nova,klmitch/nova,mahak/nova,rahulunair/nova,vmturbo/nova,klmitch/nova,mikalstill/nova,Juniper/nova,phenoxim/nova,mahak/...
6d37cb94c13c26ae82bc3b67a7ff03c2a032d7fc
test/test_message.py
test/test_message.py
import quopri from daemail.message import DraftMessage TEXT = 'àéîøü' def test_quopri_text(): msg = DraftMessage() msg.addtext(TEXT) blob = msg.compile() assert isinstance(blob, bytes) assert TEXT.encode('utf-8') not in blob assert quopri.encodestring(TEXT.encode('utf-8')) in blob def test_...
from base64 import b64encode import quopri from daemail.message import DraftMessage TEXT = 'àéîøü\n' # Something in the email module implicitly adds a newline to the body text if # one isn't present, so we need to include one here lest the base64 encodings # not match up. TEXT_ENC = TEXT.encode('utf-8') ...
Make tests forwards-compatible with new email API
Make tests forwards-compatible with new email API
Python
mit
jwodder/daemail
14d4bd44fda88ff512f0a2581539e41d51063744
pyconde/checkin/templatetags/checkin_tags.py
pyconde/checkin/templatetags/checkin_tags.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django import template from django.utils.html import format_html from django.utils.encoding import force_text from django.template.defaultfilters import stringfilter register = template.Library() @register.simple_tag(takes_context=True) def highli...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django import template from django.utils.html import format_html from django.utils.encoding import force_text from django.template.defaultfilters import stringfilter register = template.Library() @register.simple_tag(takes_context=True) def highli...
Make highlight template tag case insensitive
Make highlight template tag case insensitive
Python
bsd-3-clause
pysv/djep,pysv/djep,EuroPython/djep,EuroPython/djep,pysv/djep,pysv/djep,pysv/djep,EuroPython/djep,EuroPython/djep
4af6e0b4c514b65c5bd9251398947e830ce9f26e
quickphotos/templatetags/quickphotos_tags.py
quickphotos/templatetags/quickphotos_tags.py
from django import template from quickphotos.models import Photo register = template.Library() @register.assignment_tag def get_latest_photos(*args, **kwargs): limit = kwargs.pop('limit', None) photos = Photo.objects.all() if args: photos = photos.filter(user__in=args) if limit is not None...
from django import template from quickphotos.models import Photo register = template.Library() @register.assignment_tag def get_latest_photos(*args, **kwargs): limit = kwargs.pop('limit', None) liked_by = kwargs.pop('liked_by', None) photos = Photo.objects.all() if liked_by: photos = photos...
Tag filtering by liked photos
Tag filtering by liked photos
Python
bsd-3-clause
blancltd/django-quick-photos,kmlebedev/mezzanine-instagram-quickphotos
9d846cf6d22eb7a577f09918c2e48f6484a75962
tests/test__utils.py
tests/test__utils.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import import pytest import numpy as np import dask_distance._utils @pytest.mark.parametrize("et, u, v", [ (ValueError, np.zeros((2,), dtype=bool), np.zeros((3,), dtype=bool)), ]) def test__bool_cmp_mtx_cnt_err(et, u, v): with ...
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import import pytest import numpy as np import dask_distance._utils @pytest.mark.parametrize("et, u, v", [ (ValueError, np.zeros((2,), dtype=bool), np.zeros((3,), dtype=bool)), (ValueError, np.zeros((1, 2,), dtype=bool), np.zer...
Test non-1D array error in utils
Test non-1D array error in utils Adds a test for `_bool_cmp_mtx_cnt` to make sure that both arrays are 1D only. Will raise a `ValueError` if this is not the case.
Python
bsd-3-clause
jakirkham/dask-distance
c4153cc69238054ddbdb8b385325f5a8701e98f8
taxiexpress/serializers.py
taxiexpress/serializers.py
from django.forms import widgets from rest_framework import serializers from taxiexpress.models import Customer, Country, State, City, Driver, Travel, Car class CarSerializer(serializers.ModelSerializer): class Meta: model = Car fields = ('plate', 'model', 'company', 'capacity', 'accessible', 'anim...
from django.forms import widgets from rest_framework import serializers from taxiexpress.models import Customer, Country, State, City, Driver, Travel, Car class CarSerializer(serializers.ModelSerializer): class Meta: model = Car fields = ('plate', 'model', 'company', 'capacity', 'accessible', 'anim...
Add filters to Customer serializer
Add filters to Customer serializer
Python
mit
TaxiExpress/server,TaxiExpress/server
458fd49fdf73f5cc338c58b1e741fde42f2f7251
exampleapp/models.py
exampleapp/models.py
from galleries.models import Gallery, ImageModel from django.db import models from imagekit.models import ImageSpec from imagekit.processors.resize import Fit class Photo(ImageModel): thumbnail = ImageSpec([Fit(50, 50)]) full = ImageSpec([Fit(400, 200)]) caption = models.CharField(max_length=100) class ...
from galleries.models import Gallery, ImageModel from django.db import models from imagekit.models import ImageSpec from imagekit.processors import ResizeToFit class Photo(ImageModel): thumbnail = ImageSpec([ResizeToFit(50, 50)]) full = ImageSpec([ResizeToFit(400, 200)]) caption = models.CharField(max_len...
Use (not so) new processor class names
Use (not so) new processor class names
Python
mit
hzdg/django-galleries,hzdg/django-galleries,hzdg/django-galleries
c8ef27115ebe38d19efb857a05fe5a4e7910ee55
website/addons/forward/model.py
website/addons/forward/model.py
# -*- coding: utf-8 -*- from modularodm import fields from modularodm.validators import ( URLValidator, MinValueValidator, MaxValueValidator ) from modularodm.exceptions import ValidationValueError from framework.mongo.utils import sanitized from website.addons.base import AddonNodeSettingsBase class ForwardNo...
# -*- coding: utf-8 -*- from modularodm import fields from modularodm.validators import ( URLValidator, MinValueValidator, MaxValueValidator ) from modularodm.exceptions import ValidationValueError from framework.mongo.utils import sanitized from website.addons.base import AddonNodeSettingsBase class ForwardNo...
Reset values of external link add-on to default when deleted.
Reset values of external link add-on to default when deleted.
Python
apache-2.0
cosenal/osf.io,HalcyonChimera/osf.io,HalcyonChimera/osf.io,lyndsysimon/osf.io,dplorimer/osf,cldershem/osf.io,leb2dg/osf.io,kch8qx/osf.io,ZobairAlijan/osf.io,caseyrygt/osf.io,jmcarp/osf.io,SSJohns/osf.io,arpitar/osf.io,zamattiac/osf.io,RomanZWang/osf.io,alexschiller/osf.io,samchrisinger/osf.io,emetsger/osf.io,SSJohns/os...
ac9c8fe7519ff76b4f4002ae8c50e0185fa4bb88
tools/test_filter.py
tools/test_filter.py
{ 'bslmf_addreference': [ {'OS': 'Windows'} ], 'bslstl_iteratorutil': [ {'OS': 'SunOS'} ], 'bslstl_unorderedmultiset': [ {'OS': 'SunOS'} ], 'bslalg_constructorproxy': [ {'OS': 'AIX', 'library': 'shared_library'} ], 'bsls_atomic' : [ {'case': 7, 'HOST': 'VM', 'policy': 'skip' }, {'cas...
{ 'bslmf_addreference': [ {'OS': 'Windows'} ], 'bslstl_iteratorutil': [ {'OS': 'SunOS'} ], 'bslstl_unorderedmultiset': [ {'OS': 'SunOS'} ], 'bsls_atomic' : [ {'case': 7, 'HOST': 'VM', 'policy': 'skip' }, {'case': 8, 'HOST': 'VM', 'policy': 'skip' }, ], 'bsls_stopwatch' : [ {'case...
Remove exception for bslalg_constructorproxy test driver on AIX shared library builds.
Remove exception for bslalg_constructorproxy test driver on AIX shared library builds.
Python
apache-2.0
abeels/bde,che2/bde,minhlongdo/bde,bloomberg/bde-allocator-benchmarks,bowlofstew/bde,bloomberg/bde-allocator-benchmarks,jmptrader/bde,abeels/bde,dharesign/bde,frutiger/bde,che2/bde,apaprocki/bde,RMGiroux/bde-allocator-benchmarks,idispatch/bde,gbleaney/Allocator-Benchmarks,bloomberg/bde-allocator-benchmarks,idispatch/bd...
121bcbfc873ce45667ec67bc6f22387b43f3aa52
openfisca_web_ui/uuidhelpers.py
openfisca_web_ui/uuidhelpers.py
# -*- coding: utf-8 -*- # OpenFisca -- A versatile microsimulation software # By: OpenFisca Team <contact@openfisca.fr> # # Copyright (C) 2011, 2012, 2013, 2014 OpenFisca Team # https://github.com/openfisca # # This file is part of OpenFisca. # # OpenFisca is free software; you can redistribute it and/or modify # it ...
# -*- coding: utf-8 -*- # OpenFisca -- A versatile microsimulation software # By: OpenFisca Team <contact@openfisca.fr> # # Copyright (C) 2011, 2012, 2013, 2014 OpenFisca Team # https://github.com/openfisca # # This file is part of OpenFisca. # # OpenFisca is free software; you can redistribute it and/or modify # it ...
Use uuid.hex instead of reinventing it.
Use uuid.hex instead of reinventing it.
Python
agpl-3.0
openfisca/openfisca-web-ui,openfisca/openfisca-web-ui,openfisca/openfisca-web-ui
2f1423eb57c21938ce85a07e3a3760901f2a852a
games/objects/basescript.py
games/objects/basescript.py
import datetime from mongoengine_models import Message class Script(object): '''This is a placeholder class used for doing object script things. It's mostly just used for detecting if an object is really a script or not. ''' def __init__(self, mongo_engine_object=None): self.me_obj = mongo_en...
import datetime from mongoengine_models import Message import os import re import random from settings import MAX_DICE_AMOUNT def parse(s): result = re.search(r'^((?P<rolls>\d+)#)?(?P<dice>\d*)d(?P<sides>\d+)(?P<mod>[+-]\d+)?$', s) return (result.group('rolls') or 0, result.group('dice') or 1, ...
Add support for rolling dice for easy random number generation in scripts.
Add support for rolling dice for easy random number generation in scripts.
Python
agpl-3.0
cnelsonsic/SimpleMMO,cnelsonsic/SimpleMMO,cnelsonsic/SimpleMMO
bc19d4d7d2181ee402aafcbb064070852151063c
IPython/html/tests/test_notebookapp.py
IPython/html/tests/test_notebookapp.py
"""Test NotebookApp""" #----------------------------------------------------------------------------- # Copyright (C) 2013 The IPython Development Team # # Distributed under the terms of the BSD License. The full license is in # the file COPYING, distributed as part of this software. #-----------------------------...
"""Test NotebookApp""" #----------------------------------------------------------------------------- # Copyright (C) 2013 The IPython Development Team # # Distributed under the terms of the BSD License. The full license is in # the file COPYING, distributed as part of this software. #-----------------------------...
Test for writing and removing server info files
Test for writing and removing server info files
Python
bsd-3-clause
ipython/ipython,ipython/ipython
53ce60063c8a308cbbe08eddd264dd1e30c93615
jarbas/core/tests/test_loaddatasets_command.py
jarbas/core/tests/test_loaddatasets_command.py
from django.test import TestCase from jarbas.core.management.commands.loaddatasets import Command class TestSerializer(TestCase): def setUp(self): self.command = Command() def test_force_int(self): self.assertEqual(self.command.force_int('1'), 1) self.assertEqual(self.command.force_...
from django.test import TestCase from jarbas.core.management.commands.loaddatasets import Command class TestSerializer(TestCase): def setUp(self): self.command = Command() def test_force_int(self): self.assertEqual(self.command.force_int('1'), 1) self.assertEqual(self.command.force_...
Add loaddatasets serializer tests for real
Add loaddatasets serializer tests for real
Python
mit
marcusrehm/serenata-de-amor,rogeriochaves/jarbas,datasciencebr/serenata-de-amor,rogeriochaves/jarbas,marcusrehm/serenata-de-amor,rogeriochaves/jarbas,Guilhermeslucas/jarbas,datasciencebr/jarbas,rogeriochaves/jarbas,datasciencebr/serenata-de-amor,Guilhermeslucas/jarbas,datasciencebr/jarbas,Guilhermeslucas/jarbas,datasci...
d91d16a53ee01cf384187dcda28f1c4ab6e46e1b
astropy/io/misc/asdf/tags/time/tests/test_timedelta.py
astropy/io/misc/asdf/tags/time/tests/test_timedelta.py
# Licensed under a 3-clause BSD style license - see LICENSE.rst # -*- coding: utf-8 -*- import pytest asdf = pytest.importorskip('asdf') from asdf.tests.helpers import assert_roundtrip_tree from astropy.time import Time, TimeDelta @pytest.mark.parametrize('fmt', Time.FORMATS.keys()) def test_timedelta(fmt, tmpdir)...
# Licensed under a 3-clause BSD style license - see LICENSE.rst # -*- coding: utf-8 -*- import pytest asdf = pytest.importorskip('asdf') from asdf.tests.helpers import assert_roundtrip_tree from astropy.time import Time, TimeDelta @pytest.mark.parametrize('fmt', TimeDelta.FORMATS.keys()) def test_timedelta(fmt, tm...
Fix the ASDF test for TimeDelta formats
Fix the ASDF test for TimeDelta formats
Python
bsd-3-clause
larrybradley/astropy,MSeifert04/astropy,saimn/astropy,bsipocz/astropy,stargaser/astropy,larrybradley/astropy,dhomeier/astropy,saimn/astropy,bsipocz/astropy,mhvk/astropy,saimn/astropy,aleksandr-bakanov/astropy,pllim/astropy,mhvk/astropy,stargaser/astropy,MSeifert04/astropy,pllim/astropy,MSeifert04/astropy,astropy/astrop...
63a32acb6e2f9aadec015361f04283999f75be79
examples/app/localmodule.py
examples/app/localmodule.py
def install_module(app): """Installs this localmodule.""" install_module
class IndexResource(object): def on_get(self, req, res): res.body = 'Hello. This is app.' def install_module(app): """Installs this localmodule.""" app.api.add_route('/', IndexResource())
Add IndexResource to example module.
Add IndexResource to example module.
Python
apache-2.0
slinghq/sling
7b7f626c54694ec72166094ad568254ecfcdce8a
strictyaml/__init__.py
strictyaml/__init__.py
# The all important loader from strictyaml.parser import load # Validators from strictyaml.validators import Optional from strictyaml.validators import Validator from strictyaml.validators import OrValidator from strictyaml.validators import Any from strictyaml.validators import Scalar from strictyaml.validators impor...
# The all important loader from strictyaml.parser import load # Validators from strictyaml.validators import Optional from strictyaml.validators import Validator from strictyaml.validators import OrValidator from strictyaml.validators import Any from strictyaml.validators import Scalar from strictyaml.validators impor...
REFACTOR : Import YAMLError so it is usable as a generic exception.
REFACTOR : Import YAMLError so it is usable as a generic exception.
Python
mit
crdoconnor/strictyaml,crdoconnor/strictyaml
a4e9198194e08b99e11802dd260bd5c203179211
Mollie/API/Object/Customer.py
Mollie/API/Object/Customer.py
from .Base import Base class Customer(Base): @property def id(self): return self.getProperty('id') @property def name(self): return self.getProperty('name') @property def email(self): return self.getProperty('email') @property def locale(self): return...
from .Base import Base class Customer(Base): @property def id(self): return self.getProperty('id') @property def name(self): return self.getProperty('name') @property def email(self): return self.getProperty('email') @property def locale(self): return...
Remove forgotten if in customer.py
Remove forgotten if in customer.py
Python
bsd-2-clause
mollie/mollie-api-python
e6f85eb50ea1de37ba0f2c4ad75997a9da3879a0
changes/api/jobphase_index.py
changes/api/jobphase_index.py
from __future__ import absolute_import from flask import Response from sqlalchemy.orm import joinedload, subqueryload_all from changes.api.base import APIView from changes.api.serializer.models.jobphase import JobPhaseWithStepsSerializer from changes.models import Job, JobPhase, JobStep class JobPhaseIndexAPIView(A...
from __future__ import absolute_import from flask import Response from sqlalchemy.orm import joinedload, subqueryload_all from changes.api.base import APIView from changes.api.serializer.models.jobphase import JobPhaseWithStepsSerializer from changes.models import Job, JobPhase, JobStep class JobPhaseIndexAPIView(A...
Order JobPhase by date started, date created
Order JobPhase by date started, date created
Python
apache-2.0
bowlofstew/changes,wfxiang08/changes,bowlofstew/changes,dropbox/changes,bowlofstew/changes,wfxiang08/changes,wfxiang08/changes,dropbox/changes,dropbox/changes,bowlofstew/changes,dropbox/changes,wfxiang08/changes
202f47bb5903786b0c6a09ea4e27ed558938d2da
dramadive/button_app.py
dramadive/button_app.py
#!/usr/bin/env python3 import os from select import select from sys import exit, stderr from time import sleep WRITE_BYTES = [0x0 for b in range(0, 8)] WRITE_BYTES[0] = 0x08 WRITE_BYTES[7] = 0x02 CLOSED = 0x15 OPEN = 0x17 DOWN = 0x16 def main(): fd_id = os.open('/dev/big_red_button', os.O_RDWR|os.O_NONBLOCK) ...
#!/usr/bin/env python3 import os import requests from select import select from sys import exit, stderr from time import sleep WRITE_BYTES = [0x0 for b in range(0, 8)] WRITE_BYTES[0] = 0x08 WRITE_BYTES[7] = 0x02 CLOSED = 0x15 OPEN = 0x17 DOWN = 0x16 def main(): fd_id = os.open('/dev/big_red_button', os.O_RDWR|os...
Use vendor and product id for udev rules
Use vendor and product id for udev rules
Python
apache-2.0
1stvamp/dramadive-client
c68a69beb03047d7ea388704fbb12074b32216bc
scenarios/UAS/alice_cfg.py
scenarios/UAS/alice_cfg.py
from lib.test_config import AUTH_CREDS as AUTH_CREDS_orig class AUTH_CREDS(AUTH_CREDS_orig): enalgs = ('SHA-256', 'MD5-sess', None) def __init__(self): AUTH_CREDS_orig.__init__(self, 'mightyuser', 's3cr3tpAssw0Rd')
from lib.test_config import AUTH_CREDS as AUTH_CREDS_orig class AUTH_CREDS(AUTH_CREDS_orig): enalgs = ('SHA-256', 'SHA-256-sess', 'MD5-sess', None) def __init__(self): AUTH_CREDS_orig.__init__(self, 'mightyuser', 's3cr3tpAssw0Rd')
Enable SHA-256-sess to see if it works or not.
Enable SHA-256-sess to see if it works or not.
Python
bsd-2-clause
sippy/voiptests,sippy/voiptests
b8ec7503c71c43de8168a7d22cec4c2842382f2d
augur/datasources/downloads/test_downloads_routes.py
augur/datasources/downloads/test_downloads_routes.py
import os import pytest import requests import augur.server @pytest.fixture(scope="module") def downloads_routes(): pass
import os import pytest import requests @pytest.fixture(scope="module") def downloads_routes(): pass
Remove uneccesary import in downloads API test
Remove uneccesary import in downloads API test The test_downloads_routes.py module was uneccessarily importing augur.server due to the remnants of the previous testing architecture. This import was causing the build to error out, so it's been removed. Signed-off-by: Carter Landis <ffc486ac0b21a34cfd7d1170183ed86b0f1b...
Python
mit
OSSHealth/ghdata,OSSHealth/ghdata,OSSHealth/ghdata
033e6dbcbc735101164a7fa4c789e6704a6ee15a
aldryn_apphooks_config/models.py
aldryn_apphooks_config/models.py
# -*- coding: utf-8 -*- from app_data import AppDataField from django.db import models from django.utils.translation import ugettext_lazy as _ from django.utils.encoding import python_2_unicode_compatible @python_2_unicode_compatible class AppHookConfig(models.Model): """ This is the generic (abstract) model ...
# -*- coding: utf-8 -*- from app_data import AppDataField from django.db import models from django.utils.translation import ugettext_lazy as _ from django.utils.encoding import python_2_unicode_compatible @python_2_unicode_compatible class AppHookConfig(models.Model): """ This is the generic (abstract) model ...
Change the str representation of AppHookConfig by using the related CMSApp name instead of the type
Change the str representation of AppHookConfig by using the related CMSApp name instead of the type
Python
bsd-3-clause
aldryn/aldryn-apphooks-config,aldryn/aldryn-apphooks-config,aldryn/aldryn-apphooks-config
2d39aed3dcdb28acc61a6598cca9836665c2674e
cs251tk/student/markdownify/check_submit_date.py
cs251tk/student/markdownify/check_submit_date.py
import os from dateutil.parser import parse from ...common import run, chdir def check_dates(spec_id, username, spec, basedir): """ Port of the CheckDates program from C++ Finds the first submission date for an assignment by comparing first commits for all files in the spec and re...
import os from dateutil.parser import parse from ...common import run, chdir def check_dates(spec_id, username, spec, basedir): """ Port of the CheckDates program from C++ Finds the first submission date for an assignment by comparing first commits for all files in the spec and re...
Modify error check in check_dates()
Modify error check in check_dates()
Python
mit
StoDevX/cs251-toolkit,StoDevX/cs251-toolkit,StoDevX/cs251-toolkit,StoDevX/cs251-toolkit
ab72360da83e3b8d95030394f35a442943f53233
domains/integrator_chains/fmrb_sci_examples/scripts/lqr.py
domains/integrator_chains/fmrb_sci_examples/scripts/lqr.py
#!/usr/bin/env python from __future__ import print_function import roslib; roslib.load_manifest('dynamaestro') import rospy from dynamaestro.msg import VectorStamped from control import lqr import numpy as np class LQRController(rospy.Subscriber): def __init__(self, intopic, outtopic): rospy.Subscriber....
#!/usr/bin/env python from __future__ import print_function import roslib; roslib.load_manifest('dynamaestro') import rospy from dynamaestro.msg import VectorStamped class LQRController(rospy.Subscriber): def __init__(self, intopic, outtopic): rospy.Subscriber.__init__(self, outtopic, VectorStamped, self...
Remove some unused code that unnecessarily introduced depends
Remove some unused code that unnecessarily introduced depends This should be regarded as an update to 9aa5b02e12a2287642a285541c43790a10d6444f that removes unnecessary dependencies for the lqr.py example. In the example provided by 9aa5b02e12a2287642a285541c43790a10d6444f Python code was introduced that led to depend...
Python
bsd-3-clause
fmrchallenge/fmrbenchmark,fmrchallenge/fmrbenchmark,fmrchallenge/fmrbenchmark
687592754a80397e4e44585f232e76b7d3360780
pod_manager/db.py
pod_manager/db.py
import redis from pod_manager.settings import REDIS_HOST, REDIS_PORT, REDIS_DB def get_client(): client = redis.Redis(host=REDIS_HOST, port=REDIS_PORT, db=REDIS_DB) return client
import pickle import redis from pod_manager.settings import REDIS_HOST, REDIS_PORT, REDIS_DB __all__ = [ 'get_client', 'cache_object', 'get_object' ] def get_client(): client = redis.Redis(host=REDIS_HOST, port=REDIS_PORT, db=REDIS_DB) return client def cache_object(client, key, obj, ttl=60): ...
Add cache_object and get_object functions.
Add cache_object and get_object functions.
Python
apache-2.0
racker/pod-manager
57d3f5a78385b07fb4d7f91ac97edb6e9dc850aa
waterbutler/providers/osfstorage/metadata.py
waterbutler/providers/osfstorage/metadata.py
from waterbutler.core import metadata class BaseOsfStorageMetadata: @property def provider(self): return 'osfstorage' class OsfStorageFileMetadata(BaseOsfStorageMetadata, metadata.BaseFileMetadata): @property def name(self): return self.raw['name'] @property def path(self): ...
from waterbutler.core import metadata class BaseOsfStorageMetadata: @property def provider(self): return 'osfstorage' class OsfStorageFileMetadata(BaseOsfStorageMetadata, metadata.BaseFileMetadata): @property def name(self): return self.raw['name'] @property def path(self): ...
Use startswith in favor of indexing
Use startswith in favor of indexing
Python
apache-2.0
CenterForOpenScience/waterbutler,cosenal/waterbutler,icereval/waterbutler,chrisseto/waterbutler,RCOSDP/waterbutler,rafaeldelucena/waterbutler,Johnetordoff/waterbutler,TomBaxter/waterbutler,felliott/waterbutler,rdhyee/waterbutler,kwierman/waterbutler,Ghalko/waterbutler,hmoco/waterbutler
3692d64332768a6a8bd85ac5dbfecaba5c364d4a
tests/util/test_platform.py
tests/util/test_platform.py
import platform from keyring.util.platform_ import ( config_root, data_root, _config_root_Linux, _config_root_Windows, _data_root_Linux, _data_root_Windows, ) def test_platform_Linux(): # rely on the Github Actions workflow to run this on different platforms if platform.system() != "L...
import pytest import platform from keyring.util.platform_ import ( config_root, data_root, _config_root_Linux, _config_root_Windows, _data_root_Linux, _data_root_Windows, ) @pytest.mark.skipif( platform.system() != "Linux", reason="Requires platform.system() == 'Linux'" ) def test_platfor...
Use Pytest's skipif decorator instead of returning to skip assert statements.
Use Pytest's skipif decorator instead of returning to skip assert statements.
Python
mit
jaraco/keyring
ae78135aed5c60c03c247677e9096ce5411b6635
django_olcc/olcc/templatetags/olcc.py
django_olcc/olcc/templatetags/olcc.py
from django import template from bs4 import BeautifulSoup register = template.Library() @register.tag(name='activehref') def do_active_href(parser, token): nodelist = parser.parse(('endactivehref',)) parser.delete_first_token() return ActiveHref(nodelist) class ActiveHref(template.Node): """ Thi...
from django import template from bs4 import BeautifulSoup register = template.Library() @register.tag(name='activehref') def do_active_href(parser, token): nodelist = parser.parse(('endactivehref',)) parser.delete_first_token() return ActiveHref(nodelist) class ActiveHref(template.Node): """ Thi...
Update docstring for the ActiveHref template tag.
Update docstring for the ActiveHref template tag.
Python
mit
twaddington/django-olcc,twaddington/django-olcc,twaddington/django-olcc
1f11ca9f4e4d2560624fd159913d5b35d6bf12e7
chainer/ya/utils/range_logger.py
chainer/ya/utils/range_logger.py
import logging class rangelog: logger = None startlog = "--> Start: {name}" endlog = "<-- End:" # noqa @classmethod def set_logger(cls, logger=None): if logger is None: cls.logger = logging.getLogger() cls.logger.setLevel(getattr(logging, 'INFO')) c...
import logging class rangelog: logger = None startmsg = "--> Start: {name}" endmsg = "<-- End:" # noqa @classmethod def set_logger(cls, logger=None): if logger is None: cls.logger = logging.getLogger() cls.logger.setLevel(getattr(logging, 'INFO')) c...
Add feature to set start/end messages
Add feature to set start/end messages
Python
mit
yasuyuky/chainer-ya-utils
9c45b422e3854551fd1ff3ae1d56ee20d3d6457d
mezzanine/settings/admin.py
mezzanine/settings/admin.py
from django.contrib import admin from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect from django.utils.translation import ugettext_lazy as _ from django.utils.encoding import force_unicode from mezzanine.settings.models import Setting from mezzanine.settings.forms import Setting...
from django.contrib import admin from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect from django.utils.translation import ugettext_lazy as _ from django.utils.encoding import force_unicode from mezzanine.settings.models import Setting from mezzanine.settings.forms import Setting...
Add a redirect on successful update of settings.
Add a redirect on successful update of settings.
Python
bsd-2-clause
wyzex/mezzanine,ZeroXn/mezzanine,stephenmcd/mezzanine,tuxinhang1989/mezzanine,jerivas/mezzanine,cccs-web/mezzanine,damnfine/mezzanine,guibernardino/mezzanine,emile2016/mezzanine,gradel/mezzanine,biomassives/mezzanine,wrwrwr/mezzanine,geodesign/mezzanine,PegasusWang/mezzanine,theclanks/mezzanine,dsanders11/mezzanine,wbt...
210b24b1e04106745b5680d099f31f3a354446e8
test/599-whitewater.py
test/599-whitewater.py
# node 2356117215 assert_has_feature( 16, 34003, 23060, 'pois', { 'kind': 'put_in' }) # way 308154534 assert_has_feature( 13, 2448, 2992, 'roads', { 'kind': 'portage_way' })
# node 3134398100 assert_has_feature( 16, 19591, 23939, 'pois', { 'kind': 'put_in_egress' }) # way 308154534 assert_has_feature( 13, 2448, 2992, 'roads', { 'kind': 'portage_way' })
Use test feature from North America
Use test feature from North America
Python
mit
mapzen/vector-datasource,mapzen/vector-datasource,mapzen/vector-datasource
3c0bc3c382b3abe693b3871ee0c3d40723cb8f28
comics/crawler/crawlers/bunny.py
comics/crawler/crawlers/bunny.py
from comics.crawler.base import BaseComicCrawler from comics.crawler.meta import BaseComicMeta class ComicMeta(BaseComicMeta): name = 'Bunny' language = 'en' url = 'http://bunny-comic.com/' start_date = '2004-08-22' history_capable_days = 14 schedule = 'Mo,Tu,We,Th,Fr' time_zone = -8 ri...
from comics.crawler.base import BaseComicCrawler from comics.crawler.meta import BaseComicMeta class ComicMeta(BaseComicMeta): name = 'Bunny' language = 'en' url = 'http://bunny-comic.com/' start_date = '2004-08-22' history_capable_days = 14 schedule = 'Mo,Tu,We,Th,Fr' time_zone = -8 ri...
Fix Bunny crawler crash on non-date image names
Fix Bunny crawler crash on non-date image names
Python
agpl-3.0
jodal/comics,klette/comics,datagutten/comics,datagutten/comics,klette/comics,klette/comics,jodal/comics,jodal/comics,jodal/comics,datagutten/comics,datagutten/comics
930ad35cee818e2d0b97f840ff0b3b772bd51af3
post_office/management/commands/send_queued_mail.py
post_office/management/commands/send_queued_mail.py
import tempfile import sys from optparse import make_option from django.core.management.base import BaseCommand from ...lockfile import FileLock, FileLocked from ...mail import send_queued from ...logutils import setup_loghandlers logger = setup_loghandlers() default_lockfile = tempfile.gettempdir() + "/post_office...
import tempfile import sys from django.core.management.base import BaseCommand from ...lockfile import FileLock, FileLocked from ...mail import send_queued from ...logutils import setup_loghandlers logger = setup_loghandlers() default_lockfile = tempfile.gettempdir() + "/post_office" class Command(BaseCommand): ...
Switch to using the `add_arguments` method.
Switch to using the `add_arguments` method. This is an alternative to using the `option_list` and `optparse.make_option`. Django deprecated the use of `optparse` in management commands in Django 1.8 and removed it in Django 1.10.
Python
mit
jrief/django-post_office,ui/django-post_office,ui/django-post_office
292277abac516c412d58f1454331d9e38ddda2b3
ca_on_candidates/people.py
ca_on_candidates/people.py
from utils import CSVScraper from datetime import date class OntarioCandidatesPersonScraper(CSVScraper): csv_url = 'https://docs.google.com/spreadsheets/d/e/2PACX-1vQhrWSeOEC9DaNN2iDKcPC9IH701Al0pELevzSO62maI9WXt1TGvFH2fzUkXjUfujc3ontePcroFbT2/pub?output=csv' encoding = 'utf-8' updated_at = date(2018, 1,...
from utils import CSVScraper from datetime import date class OntarioCandidatesPersonScraper(CSVScraper): csv_url = 'https://docs.google.com/spreadsheets/d/e/2PACX-1vQhrWSeOEC9DaNN2iDKcPC9IH701Al0pELevzSO62maI9WXt1TGvFH2fzUkXjUfujc3ontePcroFbT2/pub?gid=881365071&single=true&output=csv' encoding = 'utf-8' ...
Make CSV URL more specific
ca_on_candidates: Make CSV URL more specific
Python
mit
opencivicdata/scrapers-ca,opencivicdata/scrapers-ca
7111a61a66affcb3c60ea207084e537b2109da61
mangaki/mangaki/management/commands/top.py
mangaki/mangaki/management/commands/top.py
from django.core.management.base import BaseCommand, CommandError from django.db.models import Count from django.db import connection from mangaki.models import Rating, Anime from collections import Counter import json import sys class Command(BaseCommand): args = '' help = 'Builds top' def handle(self, *a...
from django.core.management.base import BaseCommand, CommandError from django.db.models import Count from django.db import connection from mangaki.models import Rating, Anime from collections import Counter import json import sys class Command(BaseCommand): args = '' help = 'Builds top' def handle(self, *a...
Add ID to Artist in Top
Add ID to Artist in Top
Python
agpl-3.0
Mako-kun/mangaki,Elarnon/mangaki,Elarnon/mangaki,Mako-kun/mangaki,Mako-kun/mangaki,Elarnon/mangaki
355e0bab150f2e5c5c52b02714dfaef997dda856
regparser/tree/xml_parser/flatsubtree_processor.py
regparser/tree/xml_parser/flatsubtree_processor.py
from regparser.tree.depth import markers as mtypes from regparser.tree.struct import Node from regparser.tree.xml_parser import ( paragraph_processor, simple_hierarchy_processor, us_code) class FlatParagraphProcessor(paragraph_processor.ParagraphProcessor): """Paragraph Processor which does not try to derive ...
from regparser.tree.depth import markers as mtypes from regparser.tree.struct import Node from regparser.tree.xml_parser import ( paragraph_processor, simple_hierarchy_processor, us_code) class FlatParagraphProcessor(paragraph_processor.ParagraphProcessor): """Paragraph Processor which does not try to derive ...
Allow images in EXTRACTs, etc.
Allow images in EXTRACTs, etc.
Python
cc0-1.0
tadhg-ohiggins/regulations-parser,eregs/regulations-parser,eregs/regulations-parser,tadhg-ohiggins/regulations-parser
5e6d62ce7a567282a88530a2db80b775c9c4406e
swf/core.py
swf/core.py
# -*- coding:utf-8 -*- # Copyright (c) 2013, Theo Crevon # Copyright (c) 2013, Greg Leclercq # # See the file LICENSE for copying permission. import boto.swf from . import settings SETTINGS = settings.get() class ConnectedSWFObject(object): """Authenticated object interface Provides the instance attribu...
# -*- coding:utf-8 -*- # Copyright (c) 2013, Theo Crevon # Copyright (c) 2013, Greg Leclercq # # See the file LICENSE for copying permission. import boto.swf from . import settings SETTINGS = settings.get() class ConnectedSWFObject(object): """Authenticated object interface Provides the instance attribu...
Fix ConnectedSWFObject: restrict attributes set by constructor
Fix ConnectedSWFObject: restrict attributes set by constructor - credentials: SETTINGS | kwargs - region: SETTINGS | kwargs | boto.swf.layer1.Layer1.DefaultRegionName - connection: kwargs
Python
mit
botify-labs/python-simple-workflow,botify-labs/python-simple-workflow
862c2bdeaab094afdd61db862be54a8c4b7c08f3
corehq/apps/users/admin.py
corehq/apps/users/admin.py
from django.contrib import admin from django.contrib.auth.admin import UserAdmin from django.contrib.auth.models import User from django_digest.models import PartialDigest, UserNonce from .models import DomainPermissionsMirror class DDUserNonceAdmin(admin.ModelAdmin): list_display = ('user', 'nonce', 'count', '...
from django.contrib import admin from django.contrib.auth.admin import UserAdmin from django.contrib.auth.models import User from django_digest.models import PartialDigest, UserNonce from .models import DomainPermissionsMirror, HQApiKey class DDUserNonceAdmin(admin.ModelAdmin): list_display = ('user', 'nonce', ...
Add ApiKey to Users page in Django Admin
Add ApiKey to Users page in Django Admin
Python
bsd-3-clause
dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq
0470d1243ad2d7e7fd086c2b2f695dc431eaf2ea
pycroscopy/io/translators/df_utils/beps_gen_utils.py
pycroscopy/io/translators/df_utils/beps_gen_utils.py
import numpy as np def combine_in_out_field_loops(in_vec, out_vec): """ Parameters ---------- in_vec out_vec Returns ------- """ return np.vstack((in_vec, out_vec)) def build_loop_from_mat(loop_mat, num_steps): """ Parameters ---------- loop_mat num_steps...
import numpy as np import os beps_image_folder = os.path.abspath(os.path.join(os.path.realpath(__file__), '../beps_data_gen_images')) def combine_in_out_field_loops(in_vec, out_vec): """ Parameters ---------- in_vec out_vec Returns ------- """ return np.vstack((in_vec, out_vec...
Define a path to the image folder for fake beps generator
Define a path to the image folder for fake beps generator Path is defined in beps_gen_utils Users can still provide their own images if they want.
Python
mit
anugrah-saxena/pycroscopy,pycroscopy/pycroscopy
8eaf39db81deeeddd9b9035caa1c249f68d1d96f
ioant/ioant/utils/utils.py
ioant/ioant/utils/utils.py
import os import sys import json def open_file_as_string(filepath): with open(filepath, 'r') as ftemp: templateString = ftemp.read() return templateString def return_absolut_path(script_path, relative_path): return os.path.realpath(os.path.join(script_path, relative_path)) def fetch_json_file_...
import os import sys import json def open_file_as_string(filepath): with open(filepath, 'r') as ftemp: templateString = ftemp.read() return templateString def return_absolut_path(script_path, relative_path): return os.path.realpath(os.path.join(script_path, relative_path)) def fetch_json_file_...
Add function for backward compability
Add function for backward compability
Python
mit
ioants/pypi-packages,ioants/pypi-packages,ioants/pypi-packages
ee0a0b492b5536e0cc8c8e561875254698416eb4
lib/ansible/utils/string_functions.py
lib/ansible/utils/string_functions.py
def isprintable(instring): #http://stackoverflow.com/a/3637294 import string printset = set(string.printable) isprintable = set(instring).issubset(printset) return isprintable def count_newlines_from_end(str): i = len(str) while i > 0: if str[i-1] != '\n': break ...
def isprintable(instring): if isinstance(instring, str): #http://stackoverflow.com/a/3637294 import string printset = set(string.printable) isprintable = set(instring).issubset(printset) return isprintable else: return True def count_newlines_from_end(str): i...
Allow isprintable() util function to work with unicode
Allow isprintable() util function to work with unicode Fixes #6842
Python
mit
thaim/ansible,thaim/ansible
e284968b7e234b30a8a593b298a96b78bb151c03
pyscf/pbc/tdscf/rhf_slow.py
pyscf/pbc/tdscf/rhf_slow.py
""" This module is an alias for `pyscf.tdscf.rhf_slow`. It works with single k-point HF objects. """ from pyscf.tdscf.rhf_slow import *
""" This and other `_slow` modules implement the time-dependent Hartree-Fock procedure. The primary performance drawback is that, unlike other 'fast' routines with an implicit construction of the eigenvalue problem, these modules construct TDHF matrices explicitly via an AO-MO transformation, i.e. with a O(N^5) complex...
Extend a docstring in PBC-Gamma TDHF
Extend a docstring in PBC-Gamma TDHF
Python
apache-2.0
gkc1000/pyscf,gkc1000/pyscf,sunqm/pyscf,sunqm/pyscf,sunqm/pyscf,gkc1000/pyscf,gkc1000/pyscf,sunqm/pyscf,gkc1000/pyscf
01fa3a2ce4181629db2027fd9797e5592bdadada
python/balcaza/t2wrapper.py
python/balcaza/t2wrapper.py
from t2activity import NestedWorkflow from t2types import ListType, String from t2flow import Workflow class WrapperWorkflow(Workflow): def __init__(self, flow): self.flow = flow Workflow.__init__(self, flow.title, flow.author, flow.description) setattr(self.task, flow.name, NestedWorkflow(flow)) nested = ge...
from t2activity import NestedWorkflow from t2types import ListType, String from t2flow import Workflow class WrapperWorkflow(Workflow): def __init__(self, flow): self.flow = flow Workflow.__init__(self, flow.title, flow.author, flow.description) setattr(self.task, flow.name, NestedWorkflow(flow)) nested = ge...
Change wrapper code to use [] notation for attribute access
Change wrapper code to use [] notation for attribute access
Python
lgpl-2.1
jongiddy/balcazapy,jongiddy/balcazapy,jongiddy/balcazapy
ff4b241b33a5e2896110f4575e9aff41a3e04e72
dimod/compatibility23.py
dimod/compatibility23.py
import sys import itertools import inspect from collections import namedtuple _PY2 = sys.version_info.major == 2 if _PY2: range_ = xrange zip_ = itertools.izip def iteritems(d): return d.iteritems() def itervalues(d): return d.itervalues() def iterkeys(d): return d.it...
import sys import itertools import inspect from collections import namedtuple _PY2 = sys.version_info.major == 2 if _PY2: range_ = xrange zip_ = itertools.izip def iteritems(d): return d.iteritems() def itervalues(d): return d.itervalues() def iterkeys(d): return d.it...
Move namedtuple definition outside of argspec function
Move namedtuple definition outside of argspec function
Python
apache-2.0
dwavesystems/dimod,dwavesystems/dimod
fce5851733205a2b15e53971af13f56c42063eb3
qual/calendar.py
qual/calendar.py
from datetime import date, timedelta class DateWithCalendar(object): def __init__(self, calendar_class, date): self.calendar = calendar_class self.date = date def convert_to(self, calendar): return calendar.from_date(self.date) def __eq__(self, other): return self.calendar...
from datetime import date, timedelta class DateWithCalendar(object): def __init__(self, calendar_class, date): self.calendar = calendar_class self.date = date def convert_to(self, calendar): return calendar.from_date(self.date) def __eq__(self, other): return self.calendar...
Add 10 days only in the leap day case too.
Add 10 days only in the leap day case too.
Python
apache-2.0
jwg4/qual,jwg4/calexicon
5fe53a31bd7f37f8d9bd4fbe3796c8a0fa85019a
storm/db.py
storm/db.py
import motor import error from tornado import gen class Connection(object): def __init__(self, host='localhost', port=None, db=None): self.host = host self.port = port self.db = db class Database(object): def __init__(self, connection): if not isinstance(connection, Connectio...
import motor import error from tornado import gen from bson.objectid import ObjectId class Connection(object): def __init__(self, host='localhost', port=None, db=None): self.host = host self.port = port self.db = db class Database(object): def __init__(self, connection): if n...
Make sure looking up by id works correctly
Make sure looking up by id works correctly
Python
mit
ccampbell/storm,liujiantong/storm
93cd0d5dc6388582bbcfdafe21c4f41793af75dc
hamlpy/template/utils.py
hamlpy/template/utils.py
import imp from django.template import loaders from os import listdir from os.path import dirname, splitext MODULE_EXTENSIONS = tuple([suffix[0] for suffix in imp.get_suffixes()]) def get_django_template_loaders(): return [(loader.__name__.rsplit('.', 1)[1], loader) for loader in get_submodules(load...
from importlib import machinery from django.template import loaders from os import listdir from os.path import dirname, splitext MODULE_EXTENSIONS = tuple(machinery.all_suffixes()) def get_django_template_loaders(): return [(loader.__name__.rsplit('.', 1)[1], loader) for loader in get_submodules(loa...
Replace deprecated imp usage with importlib
Replace deprecated imp usage with importlib
Python
mit
nyaruka/django-hamlpy,nyaruka/django-hamlpy
2e88043e2f7a987469f1af5dffa1c4675368c667
tests/schema-validator.py
tests/schema-validator.py
#!/usr/bin/python import os import sys sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)) + "/../third-party/jsonschema") import jsonschema import jsonschema.exceptions def main(argv): if len(argv) < 3: print "Usage: " print "\t" + os.path.basename(__file__) + " <json file> <schema file...
#!/usr/bin/python import os import sys sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)) + "/../third-party/jsonschema") import jsonschema import jsonschema.exceptions def main(argv): if len(argv) < 3: print "Usage: " print "\t" + os.path.basename(__file__) + " <json file> <schema file...
Replace true/false from JSON to python False/True
Replace true/false from JSON to python False/True Signed-off-by: Vivek Galatage <bbe41406aa2af935662c4582fd181c8ca0156a8e@visteon.com>
Python
mit
vivekgalatage/libtracing
b1dae11860d61e3b574c7bd6b332053819675ddb
tests/test_block_cache.py
tests/test_block_cache.py
import angr import logging l = logging.getLogger("angr.tests") import os test_location = str(os.path.join(os.path.dirname(os.path.realpath(__file__)), '../../binaries/tests')) def test_block_cache(): p = angr.Project(os.path.join(test_location, "x86_64", "fauxware"), translation_cache=True) b = p.factory.blo...
import angr import logging l = logging.getLogger("angr.tests") import os test_location = str(os.path.join(os.path.dirname(os.path.realpath(__file__)), '../../binaries/tests')) def test_block_cache(): p = angr.Project(os.path.join(test_location, "x86_64", "fauxware"), translation_cache=True) b = p.factory.blo...
Fix the test case for block cache.
Fix the test case for block cache.
Python
bsd-2-clause
f-prettyland/angr,f-prettyland/angr,axt/angr,chubbymaggie/angr,schieb/angr,schieb/angr,angr/angr,tyb0807/angr,tyb0807/angr,f-prettyland/angr,iamahuman/angr,iamahuman/angr,tyb0807/angr,angr/angr,schieb/angr,iamahuman/angr,chubbymaggie/angr,chubbymaggie/angr,axt/angr,axt/angr,angr/angr
b5744150da20f9b3b0f37704eb91878de21072cf
deploy/scripts/upgrade-web.py
deploy/scripts/upgrade-web.py
#!/usr/bin/python3 import errno import pathlib import platform import sys import subprocess def main(): dist = platform.dist() if dist[0] != 'debian' and dist[0] != 'Ubuntu': print('This script can only be run on Debian GNU/Linux or Ubuntu.') sys.exit(errno.EPERM) workdir = pathlib.Path(_...
#!/usr/bin/python3 import errno import pathlib import platform import sys import subprocess def main(): dist = platform.dist() if dist[0] != 'debian' and dist[0] != 'Ubuntu': print('This script can only be run on Debian GNU/Linux or Ubuntu.') sys.exit(errno.EPERM) workdir = pathlib.Path(_...
Install uwsgi in venv on web upgrade
Install uwsgi in venv on web upgrade
Python
mit
clicheio/cliche,clicheio/cliche,item4/cliche,clicheio/cliche,item4/cliche
2179dee14cfbd58ab8d8779561ac3826fe8892dd
custom/enikshay/reports/views.py
custom/enikshay/reports/views.py
from django.http.response import JsonResponse from django.utils.decorators import method_decorator from django.views.generic.base import View from corehq.apps.domain.decorators import login_and_domain_required from corehq.apps.locations.models import SQLLocation from corehq.apps.userreports.reports.filters.choice_prov...
from collections import namedtuple from django.http.response import JsonResponse from django.utils.decorators import method_decorator from django.views.generic.base import View from corehq.apps.domain.decorators import login_and_domain_required from corehq.apps.userreports.reports.filters.choice_providers import Choi...
Use LocationChoiceProvider in enikshay location view
Use LocationChoiceProvider in enikshay location view
Python
bsd-3-clause
dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq
acaacbea4fbfdcc0f1f0c5e0aa9a837dee439d08
saau/sections/image_provider.py
saau/sections/image_provider.py
import json import inspect from os.path import join, exists def not_implemented(): frame_info = inspect.currentframe().f_back msg = '' if 'self' in frame_info.f_locals: self = frame_info.f_locals['self'] try: msg += self.__name__ + '#' # for static/class methods excep...
import inspect import json from os.path import exists, join from pathlib import Path from typing import Any, Union from ..services import Services PathOrStr = Union[str,Path] def not_implemented(): frame_info = inspect.currentframe().f_back msg = '' if 'self' in frame_info.f_locals: self = fram...
Add types to ImageProvider and RequiresData
Add types to ImageProvider and RequiresData
Python
mit
Mause/statistical_atlas_of_au
6a10f2f08825480edc7b84ca00d84c36873cbdf4
devs/tools/adapt-es-path.py
devs/tools/adapt-es-path.py
#!/usr/bin/env python3 """ Use to apply patches from ES upstream with: git apply --reject \ <(curl -L https://github.com/elastic/elasticsearch/pull/<NUMBER>.diff | ./devs/tools/adapt-es-path.py) """ import sys def main(): for line in sys.stdin: sys.stdout.write( line ...
#!/usr/bin/env python3 """ Use to apply patches from ES upstream with: git apply --reject \ <(curl -L https://github.com/elastic/elasticsearch/pull/<NUMBER>.diff | ./devs/tools/adapt-es-path.py) """ import sys def main(): for line in sys.stdin: sys.stdout.write( line ...
Update dev tool for applying ES patches
Update dev tool for applying ES patches Adds path rewrite for `test/framework` -> `es/es-testing/`
Python
apache-2.0
crate/crate,crate/crate,EvilMcJerkface/crate,EvilMcJerkface/crate,EvilMcJerkface/crate,crate/crate
37be9141cbcafb51ebef4ba76a5c2f1dcd9449d1
example/test1_autograder.py
example/test1_autograder.py
from nose.tools import eq_ as assert_eq @score(problem="hello", points=0.5) def grade_hello1(): """Grade 'hello' with input 'Jessica'""" msg = hello("Jessica") assert_eq(msg, "Hello, Jessica!") @score(problem="hello", points=0.5) def grade_hello2(): """Grade 'hello' with input 'Python'""" msg = he...
from nose.tools import eq_ as assert_eq @score(problem="Problem 1/Part A", points=0.5) def grade_hello1(): """Grade 'hello' with input 'Jessica'""" msg = hello("Jessica") assert_eq(msg, "Hello, Jessica!") @score(problem="Problem 1/Part A", points=0.5) def grade_hello2(): """Grade 'hello' with input ...
Update example autograding code to use heading names
Update example autograding code to use heading names
Python
mit
jhamrick/original-nbgrader,jhamrick/original-nbgrader
271c234ce215c036f54928a7c2910ddda4cea360
dbaas/dbaas/celeryconfig.py
dbaas/dbaas/celeryconfig.py
import os REDIS_PORT = os.getenv('DBAAS_NOTIFICATION_BROKER_PORT', '6379') BROKER_URL = os.getenv( 'DBAAS_NOTIFICATION_BROKER_URL', 'redis://localhost:%s/0' % REDIS_PORT) CELERYD_TASK_TIME_LIMIT = 10800 CELERY_TRACK_STARTED = True CELERY_IGNORE_RESULT = False CELERY_RESULT_BACKEND = 'djcelery.backends.cache:CacheB...
import os REDIS_PORT = os.getenv('DBAAS_NOTIFICATION_BROKER_PORT', '6379') BROKER_URL = os.getenv( 'DBAAS_NOTIFICATION_BROKER_URL', 'redis://localhost:%s/0' % REDIS_PORT) CELERYD_TASK_TIME_LIMIT = 10800 CELERY_TRACK_STARTED = True CELERY_IGNORE_RESULT = False CELERY_RESULT_BACKEND = 'djcelery.backends.cache:CacheB...
Add celeryd prefetch multiplier setting
Add celeryd prefetch multiplier setting
Python
bsd-3-clause
globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service
d346129fb33f84eaa61ed48f3d4b4f9570062241
server/server/tests/__init__.py
server/server/tests/__init__.py
import pytest from django.contrib.auth.models import User from rest_framework.authtoken.models import Token pytestmark = pytest.mark.django_db(transaction=True) @pytest.fixture def fm_user(): user = User.objects.create_user('fuzzmanager', 'test@example.com', 'test') user.password_raw = 'test' (token, cr...
import pytest from django.contrib.contenttypes.models import ContentType from django.contrib.auth.models import User, Permission from rest_framework.authtoken.models import Token from crashmanager.models import User as CMUser pytestmark = pytest.mark.django_db(transaction=True) @pytest.fixture def fm_user(): use...
Fix Collector and EC2Reporter tests. Token user used for test now requires the correct permissions.
Fix Collector and EC2Reporter tests. Token user used for test now requires the correct permissions.
Python
mpl-2.0
MozillaSecurity/FuzzManager,MozillaSecurity/FuzzManager,MozillaSecurity/FuzzManager,MozillaSecurity/FuzzManager
1455da161123ea778d8e82c2f961fdcf85cd10aa
monitor-checker-http.py
monitor-checker-http.py
#!/usr/bin/env python import pika import json import requests RABBIT_MQ_SERVER = os.environ["RABBIT_MQ_SERVER"] connection = pika.BlockingConnection(pika.ConnectionParameters( RABBIT_MQ_SERVER)) channel = connection.channel() channel.queue_declare(queue='http') def callback(ch, method, properties, bod...
#!/usr/bin/env python import pika import json import requests import os RABBIT_MQ_SERVER = os.environ["RABBIT_MQ_SERVER"] RABBIT_MQ_USER = os.environ["RABBIT_MQ_USER"] RABBIT_MQ_PWD = os.environ["RABBIT_MQ_PWD"] credentials = pika.PlainCredentials(RABBIT_MQ_USER, RABBIT_MQ_PWD) connection = pika.BlockingConnection(p...
Add credentials + code clean up
Add credentials + code clean up
Python
mit
observer-hackaton/monitor-checker-http
7b697cbcddf29412ac94a186817bd9db1880a0f2
nbody/snapshots/util.py
nbody/snapshots/util.py
"""Various utility functions, mostly dealing with input/output""" import os import numpy as np def load_snapshots(directory_name, stack_coords=False): """Loads files by traversing a directory and reading in a filename sorted order""" data = [] for root, dirs, files in os.walk(directory_name): ...
"""Various utility functions, mostly dealing with input/output""" import os import numpy as np def load_snapshots(directory_name, stack_coords=False): """Loads files by traversing a directory and reading in a filename sorted order""" data = [] for root, dirs, files in os.walk(directory_name): ...
Fix csv saving for arbitrary parameter sets
Fix csv saving for arbitrary parameter sets
Python
mit
kostassabulis/nbody-workshop-2015
dfe52966b8ab72cd17687c1f6d15fdadac4d72e2
weasyprint/logger.py
weasyprint/logger.py
# coding: utf-8 """ weasyprint.logging ------------------ Logging setup. The rest of the code gets the logger through this module rather than ``logging.getLogger`` to make sure that it is configured. Logging levels are used for specific purposes: - errors are used for unreachable or unus...
# coding: utf-8 """ weasyprint.logging ------------------ Logging setup. The rest of the code gets the logger through this module rather than ``logging.getLogger`` to make sure that it is configured. Logging levels are used for specific purposes: - errors are used for unreachable or unus...
Set default logging level to WARNING
Set default logging level to WARNING Fixes tests with pytest 3.3.0+
Python
bsd-3-clause
Kozea/WeasyPrint,Kozea/WeasyPrint
6f8efd5e6893491a7ee1c046513210c8ad1e7fc8
sqliteschema/_logger/_logger.py
sqliteschema/_logger/_logger.py
# encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com> """ from __future__ import absolute_import, unicode_literals import tabledata from ._null_logger import NullLogger MODULE_NAME = "sqliteschema" try: from loguru import logger logger.disable(MODULE_NAME) except ImportEr...
# encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com> """ from __future__ import absolute_import, unicode_literals import tabledata from ._null_logger import NullLogger MODULE_NAME = "sqliteschema" _is_enable = False try: from loguru import logger logger.disable(MODULE_NA...
Add check for logging state
Add check for logging state
Python
mit
thombashi/sqliteschema
0c30fe72179a125b41ffb88fec387862c78e6c7c
flaskrst/modules/atom.py
flaskrst/modules/atom.py
# -*- coding: utf-8 -*- """ flask-rst.modules.atom ~~~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2011 by Christoph Heer. :license: BSD, see LICENSE for more details. """ from flask import Blueprint, request, current_app from werkzeug.contrib.atom import AtomFeed, FeedEntry from flaskrst.modules.blog import ...
# -*- coding: utf-8 -*- """ flask-rst.modules.atom ~~~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2011 by Christoph Heer. :license: BSD, see LICENSE for more details. """ from flask import Blueprint, request, current_app from werkzeug.contrib.atom import AtomFeed, FeedEntry from flaskrst.modules.blog import ...
Add more information to the feed entry
Add more information to the feed entry
Python
bsd-3-clause
jarus/flask-rst
038bb5fe10a3b9df18f8c709cddd0c18b2ac694d
parsing/forum/mongo_forum_to_mongod.py
parsing/forum/mongo_forum_to_mongod.py
''' Insert the edx discussion board .mongo files into mongodb database ''' import pymongo import sys import json def connect_to_db_collection(db_name, collection_name): ''' Retrieve collection from given database name and collection name ''' connection = pymongo.Connection('localhost', 27017) db...
''' Insert the edx discussion board .mongo files into mongodb database ''' import pymongo import sys import json def connect_to_db_collection(db_name, collection_name): ''' Retrieve collection from given database name and collection name ''' connection = pymongo.Connection('localhost', 27017) db...
Add function to migrate forum data to mongodb
Add function to migrate forum data to mongodb
Python
mit
andyzsf/edx_data_research,andyzsf/edx_data_research,McGillX/edx_data_research,McGillX/edx_data_research,McGillX/edx_data_research
cc8cc05480e85c9a66450f1655083e87d00ba3f4
usersettings/shortcuts.py
usersettings/shortcuts.py
from django.conf import settings from django.core.exceptions import ImproperlyConfigured def get_usersettings_model(): """ Returns the ``UserSettings`` model that is active in this project. """ from django.db.models import get_model try: app_label, model_name = settings.USERSETTINGS_MODEL...
from django.conf import settings from django.core.exceptions import ImproperlyConfigured def get_usersettings_model(): """ Returns the ``UserSettings`` model that is active in this project. """ from django.db.models import get_model try: app_label, model_name = settings.USERSETTINGS_MODEL...
Update 'get_current_usersettings' to catch 'DoesNotExist' error
Update 'get_current_usersettings' to catch 'DoesNotExist' error
Python
bsd-3-clause
mishbahr/django-usersettings2,mishbahr/django-usersettings2