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
1c4fbca7ce0b1ad16159f62e1485a3485f1878bb
oidstub.py
oidstub.py
"""Stand-in module for those without the speed-enhanced tuple-OID implementation""" def OID( value ): """Null function to pretend to be oid.OID""" return str(value)
"""Stand-in module for those without the speed-enhanced tuple-OID implementation""" USE_STRING_OIDS = True def OID( value ): """Null function to pretend to be oid.OID""" return str(value)
Declare use of string OIDs
Declare use of string OIDs
Python
bsd-3-clause
mmattice/TwistedSNMP
431fdabc5c103c9581758543359a54f650d24bcf
nodes/cpu_node.py
nodes/cpu_node.py
from node import Node from model.cpu import CPU from extraction.http.cpu_cw_http import CpuCwHTTP class CPUNode(Node): label = "CPU" def __init__(self, service, timespan): super(CPUNode, self).__init__(service, timespan) def load_entities(self): return CpuCwHTTP(self.service, self.timespan).load_ent...
from node import Node from model.cpu import CPU from extraction.http.cpu_cw_http import CpuCwHTTP class CPUNode(Node): label = "CPU" def __init__(self, service, timespan): super(CPUNode, self).__init__(service, timespan) def load_entities(self): return CpuCwHTTP(self.service, self.timespan).load_ent...
Remove CloudWave specific context expansion
Remove CloudWave specific context expansion
Python
apache-2.0
sealuzh/ContextBasedAnalytics,sealuzh/ContextBasedAnalytics,sealuzh/ContextBasedAnalytics
8db347eaae51ea5f0a591bcecd5ba38263379aae
seqio/__init__.py
seqio/__init__.py
# Copyright 2021 The SeqIO Authors. # # 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 wr...
# Copyright 2021 The SeqIO Authors. # # 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 wr...
Make loggers part of the top-level SeqIO API.
Make loggers part of the top-level SeqIO API. PiperOrigin-RevId: 400711636
Python
apache-2.0
google/seqio
484eaaf6349a631f483af12acd358bce5ca567d5
zeeko/messages/setup_package.py
zeeko/messages/setup_package.py
# -*- coding: utf-8 -*- from __future__ import absolute_import import glob import os import copy import zmq from distutils.core import Extension def get_extensions(**kwargs): """Get the Cython extensions""" this_directory = os.path.dirname(__file__) this_name = __name__.split(".")[:-1] extension...
# -*- coding: utf-8 -*- from __future__ import absolute_import import glob import os import copy from distutils.core import Extension def get_extensions(**kwargs): """Get the Cython extensions""" import zmq this_directory = os.path.dirname(__file__) this_name = __name__.split(".")[:-1] ...
Fix stray zmq import in egg_info
Fix stray zmq import in egg_info
Python
bsd-3-clause
alexrudy/Zeeko,alexrudy/Zeeko
5c447d46a8a62407549650ada98131968ace9921
spyc/scheduler.py
spyc/scheduler.py
from spyc.graph import Vertex, find_cycle, topological_sort class Scheduler(object): def __init__(self): self.specs = {} def ensure(self, spec): """Require that ``spec`` is satisfied.""" if spec.key() in self.specs: self.specs[spec.key()].data.merge(spec) else: ...
from spyc.graph import Vertex, find_cycle, topological_sort class CircularDependency(Exception): pass class Scheduler(object): def __init__(self): self.specs = {} def ensure(self, spec): """Require that ``spec`` is satisfied.""" if spec.key() in self.specs: self.spe...
Raise a more useful error for circular deps.
Raise a more useful error for circular deps.
Python
lgpl-2.1
zenhack/spyc
01e629b43be83cd5ba37f7a3ecbf60c73d8ed2e6
calexicon/internal/tests/test_julian.py
calexicon/internal/tests/test_julian.py
import unittest from datetime import date as vanilla_date from calexicon.internal.julian import distant_julian_to_gregorian, julian_to_gregorian, is_julian_leap_year class TestJulian(unittest.TestCase): def test_is_gregorian_leap_year(self): self.assertTrue(is_julian_leap_year(2000)) self.assert...
import unittest from datetime import date as vanilla_date from calexicon.internal.julian import distant_julian_to_gregorian, julian_to_gregorian from calexicon.internal.julian import is_julian_leap_year class TestJulian(unittest.TestCase): def test_is_gregorian_leap_year(self): self.assertTrue(is_julian...
Split long import line up into two.
Split long import line up into two.
Python
apache-2.0
jwg4/calexicon,jwg4/qual
c0a74c86e772185d35f0e6049e0ce04fcdb30793
chatterbot/adapters/io/multi_adapter.py
chatterbot/adapters/io/multi_adapter.py
from .io import IOAdapter class MultiIOAdapter(IOAdapter): def __init__(self, **kwargs): super(MultiIOAdapter, self).__init__(**kwargs) self.adapters = [] def process_input(self, *args, **kwargs): """ Returns data retrieved from the input source. """ if self....
from .io import IOAdapter class MultiIOAdapter(IOAdapter): def __init__(self, **kwargs): super(MultiIOAdapter, self).__init__(**kwargs) self.adapters = [] def process_input(self, *args, **kwargs): """ Returns data retrieved from the input source. """ if self....
Fix first io adapter being called twice.
Fix first io adapter being called twice.
Python
bsd-3-clause
Reinaesaya/OUIRL-ChatBot,maclogan/VirtualPenPal,Reinaesaya/OUIRL-ChatBot,Gustavo6046/ChatterBot,davizucon/ChatterBot,gunthercox/ChatterBot,vkosuri/ChatterBot
ec4b2fc266eb033dab9319c4d2f8ece6fd23170a
src/start_scraping.py
src/start_scraping.py
from main import initiate_shame # Testing this initiate_shame(1141922, 2016)
from main import initiate_shame initiate_shame(1141922, 2017) initiate_shame(144768, 2017)
Update script file for the season
Update script file for the season
Python
mit
troym9731/fantasy_football
ffd4c59f4916087eac0977355a638508757c80fd
taskmonitor/models.py
taskmonitor/models.py
from celery import states from django.db import models STATES_CHOICES = zip(states.ALL_STATES, states.ALL_STATES) class TaskStatus(models.Model): """ Task status. With this the status of celery tasks can be monitored, more reliably than depending on the broker or celery itself. """ status =...
from celery import states from django.db import models ALL_STATES = sorted(states.ALL_STATES) STATES_CHOICES = zip(ALL_STATES, ALL_STATES) class TaskStatus(models.Model): """ Task status. With this the status of celery tasks can be monitored, more reliably than depending on the broker or celery itse...
Fix neverending creation of migrations on heroku
Fix neverending creation of migrations on heroku
Python
agpl-3.0
HelloLily/hellolily,HelloLily/hellolily,HelloLily/hellolily,HelloLily/hellolily
227d4c152367292e8b0b8801d9ce6179af92432a
python/014_longest_common_prefix.py
python/014_longest_common_prefix.py
""" Write a function to find the longest common prefix string amongst an array of strings. """ class Solution(object): def longestCommonPrefix(self, strs): """ :type strs: List[str] :rtype: str """ if len(strs)==0: return "" lcp=list(strs[0]) for i...
""" Write a function to find the longest common prefix string amongst an array of strings. """ class Solution(object): def longestCommonPrefix(self, strs): """ :type strs: List[str] :rtype: str """ if strs is None or strs == "": return "" lcp = list(strs[0...
Add test case to 014
Add test case to 014
Python
mit
ufjfeng/leetcode-jf-soln,ufjfeng/leetcode-jf-soln
d7c293fb430c31c237e3aca7ba469f0237b18d8d
scikits/talkbox/linpred/__init__.py
scikits/talkbox/linpred/__init__.py
import levinson_lpc from levinson_lpc import * __all__ = levinson_lpc.__all__
import levinson_lpc from levinson_lpc import * __all__ = levinson_lpc.__all__ from common import lpcres __all__ += ['lpcres']
Add lpcres in linpred namespace.
Add lpcres in linpred namespace.
Python
mit
cournape/talkbox,cournape/talkbox
674fa7692c71524541d8797a65968e5e605454e7
testrail/suite.py
testrail/suite.py
from datetime import datetime import api from project import Project class Suite(object): def __init__(self, content): self._content = content self.api = api.API() @property def id(self): return self._content.get('id') @property def completed_on(self): try: ...
from datetime import datetime import api from helper import TestRailError from project import Project class Suite(object): def __init__(self, content): self._content = content self.api = api.API() @property def id(self): return self._content.get('id') @property def compl...
Add setters for project, name, and description.
Add setters for project, name, and description.
Python
mit
travispavek/testrail-python,travispavek/testrail
e704d8cb63e76bb1f5b1da6fec7ae4f65d7710f1
tests/__init__.py
tests/__init__.py
import sys try: # noinspection PyPackageRequirements import unittest2 as unittest sys.modules['unittest'] = unittest except ImportError: import unittest from goless.backends import current as be class BaseTests(unittest.TestCase): """ Base class for unit tests. Yields in setup and teardow...
import sys try: # noinspection PyPackageRequirements import unittest2 as unittest sys.modules['unittest'] = unittest except ImportError: import unittest from goless.backends import current as be class BaseTests(unittest.TestCase): """ Base class for unit tests. Yields in setup and teardow...
Add comment in BaseTests tearDown
Add comment in BaseTests tearDown
Python
apache-2.0
rgalanakis/goless,rgalanakis/goless
c4e0a132461dba798739b752a04fe3ff66af17ab
tests/high_level_curl_test.py
tests/high_level_curl_test.py
#! /usr/bin/env python # -*- coding: utf-8 -*- # vi:ts=4:et # uses the high level interface import curl import unittest from . import appmanager setup_module, teardown_module = appmanager.setup(('app', 8380)) class RelativeUrlTest(unittest.TestCase): def setUp(self): self.curl = curl.Curl('http://localh...
#! /usr/bin/env python # -*- coding: utf-8 -*- # vi:ts=4:et # uses the high level interface import curl import unittest from . import appmanager setup_module, teardown_module = appmanager.setup(('app', 8380)) class RelativeUrlTest(unittest.TestCase): def setUp(self): self.curl = curl.Curl('http://localh...
Fix test suite on python 3 - high level curl object returns result as bytes
Fix test suite on python 3 - high level curl object returns result as bytes
Python
lgpl-2.1
pycurl/pycurl,pycurl/pycurl,pycurl/pycurl
17d91eff7de5517aa89330a08f3c84fa46d02538
tests/test_exc.py
tests/test_exc.py
# -*- coding: utf-8 -*- import pytest from cihai import exc def test_base_exception(): with pytest.raises( exc.CihaiException, message="Make sure no one removes or renames base CihaiException", ): raise exc.CihaiException() with pytest.raises(Exception, message="Extends python b...
# -*- coding: utf-8 -*- import pytest from cihai import exc def test_base_exception(): with pytest.raises(exc.CihaiException): raise exc.CihaiException() # Make sure its base of CihaiException with pytest.raises(Exception): raise exc.CihaiException() # Extends python base exception
Update exception test for pytest 5+
Update exception test for pytest 5+ pytest 3 had message for raises, this is removed in current versions.
Python
mit
cihai/cihai,cihai/cihai
1d0e75959f4511cbca10cb223b01c3a29d3660ec
tmhmm/__init__.py
tmhmm/__init__.py
from collections import Counter, defaultdict import numpy as np from tmhmm.model import parse from tmhmm.hmm import viterbi, forward, backward __all__ = ['predict'] GROUP_NAMES = ('i', 'm', 'o') def predict(sequence, header, model_or_filelike, compute_posterior=True): if isinstance(model_or_filelike, tuple...
from collections import defaultdict import numpy as np from tmhmm.model import parse from tmhmm.hmm import viterbi, forward, backward __all__ = ['predict'] GROUP_NAMES = ('i', 'm', 'o') def predict(sequence, header, model_or_filelike, compute_posterior=True): if isinstance(model_or_filelike, tuple): ...
Remove unused group counts variable
Remove unused group counts variable
Python
mit
dansondergaard/tmhmm.py
ff8f1067ac95a8f3fbb4c02e510da033623edeee
gargoyle/helpers.py
gargoyle/helpers.py
""" gargoyle.helpers ~~~~~~~~~~~~~~~~ :copyright: (c) 2010 DISQUS. :license: Apache License 2.0, see LICENSE for more details. """ from django.http import HttpRequest class MockRequest(HttpRequest): """ A mock request object which stores a user instance and the ip address. """ def __init__(self, ...
""" gargoyle.helpers ~~~~~~~~~~~~~~~~ :copyright: (c) 2010 DISQUS. :license: Apache License 2.0, see LICENSE for more details. """ from django.http import HttpRequest class MockRequest(HttpRequest): """ A mock request object which stores a user instance and the ip address. """ def __init__(self, ...
Set POST/GET/COOKIES on MockRequest so repr works
Set POST/GET/COOKIES on MockRequest so repr works
Python
apache-2.0
disqus/gutter-django,nkovshov/gargoyle,nkovshov/gargoyle,nkovshov/gargoyle,frewsxcv/gargoyle,brilliant-org/gargoyle,frewsxcv/gargoyle,YPlan/gargoyle,roverdotcom/gargoyle,monokrome/gargoyle,monokrome/gargoyle,disqus/gutter,vikingco/gargoyle,disqus/gutter-django,blueprinthealth/gargoyle,YPlan/gargoyle,graingert/gutter-dj...
347e3f9092bf1f48e116cafceef8db255e293b1f
test/test_packages.py
test/test_packages.py
import pytest @pytest.mark.parametrize("name", [ ("apt-file"), ("apt-transport-https"), ("atsar"), ("blktrace"), ("ca-certificates"), ("chromium-browser"), ("cron"), ("curl"), ("diod"), ("docker-engine"), ("git"), ("gnupg"), ("handbrake"), ("handbrake-cli"), ("haveged"), ("htop"), ("i...
import pytest @pytest.mark.parametrize("name", [ ("apt-file"), ("apt-transport-https"), ("atsar"), ("blktrace"), ("ca-certificates"), ("chromium-browser"), ("cron"), ("curl"), ("diod"), ("docker-engine"), ("fonts-font-awesome"), ("git"), ("gnupg"), ("handbrake"), ("handbrake-cli"), ("ha...
Add new packages to tests
Add new packages to tests
Python
mit
wicksy/laptop-build,wicksy/laptop-build,wicksy/laptop-build,wicksy/laptop-build
7c1a6fdc82ccdf8469d95e1e77897fab6e25d551
hammock/__init__.py
hammock/__init__.py
import types from version import __version__ from .model import Model from .collection import Collection class Hammock(object): def __init__(self, collections=(), authenticators=(), storage=None): if type(collections) == types.ModuleType: collection_classes = [] for k,v in collections.__dict__.items(): ...
import types from version import __version__ from .model import Model from .collection import Collection class Hammock(object): def __init__(self, collections=(), authenticators=(), storage=None): if type(collections) == types.ModuleType: collection_classes = [] for k,v in collections.__dict__.items(): ...
Make sure we don't include Collection when pulling collections from a module
Make sure we don't include Collection when pulling collections from a module
Python
mit
cooper-software/cellardoor
e4e930587e6ad145dbdbf1f742b942d63bf645a2
wandb/git_repo.py
wandb/git_repo.py
from git import Repo, exc import os class GitRepo(object): def __init__(self, root=None, remote="origin", lazy=True): self.remote_name = remote self.root = root self._repo = None if not lazy: self.repo @property def repo(self): if self._repo is None: ...
from git import Repo, exc import os class GitRepo(object): def __init__(self, root=None, remote="origin", lazy=True): self.remote_name = remote self.root = root self._repo = None if not lazy: self.repo @property def repo(self): if self._repo is None: ...
Handle no git user configured
Handle no git user configured
Python
mit
wandb/client,wandb/client,wandb/client
194748bfbc67741275fd36eb2eaafbde55caeabb
django_emarsys/management/commands/emarsys_sync_events.py
django_emarsys/management/commands/emarsys_sync_events.py
# -*- coding: utf-8 -*- from django.core.management import BaseCommand from ...event import sync_events class Command(BaseCommand): def handle(self, *args, **options): num_new_events, num_updated_ids, num_deleted_ids, \ unsynced_event_names = sync_events() print("{} new events, {} ev...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.core.management import BaseCommand from ...event import sync_events class Command(BaseCommand): def handle(self, *args, **options): num_new_events, num_updated_ids, num_deleted_ids, \ unsynced_event_names = sync_eve...
Fix issue with management command log output and non ascii event names
Fix issue with management command log output and non ascii event names
Python
mit
machtfit/django-emarsys,machtfit/django-emarsys
a2abc6342162c9158551b810f4d666d6d13dcd15
client/python/plot_request_times.py
client/python/plot_request_times.py
import requests r = requests.get('http://localhost:8081/monitor_results/1') print(r.json()) for monitoring_data in r.json(): print 'URL: ' + monitoring_data['urlToMonitor']['url']
import requests from plotly.offline import plot import plotly.graph_objs as go r = requests.get('http://localhost:8081/monitor_results/1') print(r.json()) # build traces for plotting from monitoring data request_times = list() timestamps = list() timestamp = 0 url = r.json()[0]['urlToMonitor']['url'] for monitoring_d...
Add prototype for plotting client
Add prototype for plotting client
Python
mit
gernd/simple-site-mon
cc2f0900b02891e0ab23133778065a6f6768cd5c
setup.py
setup.py
from distutils.core import setup setup( name = 'furs_fiscal', packages = ['furs_fiscal'], version = '0.1.0', description = 'Python library for simplified communication with FURS (Financna uprava Republike Slovenije).', author = 'Boris Savic', author_email = 'boris70@gmail.com', url = 'https://github.com/b...
from distutils.core import setup setup( name = 'furs_fiscal', packages = ['furs_fiscal'], version = '0.1.3', description = 'Python library for simplified communication with FURS (Financna uprava Republike Slovenije).', author = 'Boris Savic', author_email = 'boris70@gmail.com', url = 'https://github.com/b...
Add test_certificate.pem to the release
Add test_certificate.pem to the release
Python
mit
boris-savic/python-furs-fiscal
5ea25bc6c72e5c934e56a90c44f8019ad176bb27
comet/utility/test/test_spawn.py
comet/utility/test/test_spawn.py
import sys from twisted.trial import unittest from twisted.python import failure from ..spawn import SpawnCommand class DummyEvent(object): text = "" class SpawnCommandProtocolTestCase(unittest.TestCase): def test_good_process(self): spawn = SpawnCommand(sys.executable) d = spawn(DummyEvent(...
import sys from twisted.trial import unittest from twisted.python import failure from twisted.python import util from ..spawn import SpawnCommand class DummyEvent(object): def __init__(self, text=None): self.text = text class SpawnCommandProtocolTestCase(unittest.TestCase): def test_good_process(sel...
Test that spawned process actually writes data
Test that spawned process actually writes data
Python
bsd-2-clause
jdswinbank/Comet,jdswinbank/Comet
078f00ae743c2e16df76653090298ba56b277caf
pegasus/metrics/__init__.py
pegasus/metrics/__init__.py
import sys import logging def init_logging(): logFormat = "%(asctime)s %(levelname)s %(filename)s:%(lineno)s %(message)s" logFormatter = logging.Formatter(fmt=logFormat) logHandler = logging.StreamHandler(stream=sys.stderr) logHandler.setFormatter(logFormatter) log = logging.getLogger(__name__) ...
import sys import logging def init_logging(): logFormat = "%(asctime)s %(levelname)s %(filename)s:%(lineno)s %(message)s" logFormatter = logging.Formatter(fmt=logFormat) logHandler = logging.StreamHandler() logHandler.setFormatter(logFormatter) log = logging.getLogger(__name__) log.addHandler(l...
Use default argument for StreamHandler (which is what want, sys.stderr) because they changed the name of the keyword argument in 2.7
Use default argument for StreamHandler (which is what want, sys.stderr) because they changed the name of the keyword argument in 2.7
Python
apache-2.0
pegasus-isi/pegasus-metrics,pegasus-isi/pegasus-metrics,pegasus-isi/pegasus-metrics
cb39de495da5256e6e44773036f78d704f0d563d
tapioca_instagram/tapioca_instagram.py
tapioca_instagram/tapioca_instagram.py
# coding: utf-8 from tapioca import (JSONAdapterMixin, TapiocaAdapter, generate_wrapper_from_adapter) from .resource_mapping import RESOURCE_MAPPING class InstagramClientAdapter(JSONAdapterMixin, TapiocaAdapter): api_root = 'https://api.instagram.com/v1/' resource_mapping = RESOURCE_MAP...
# coding: utf-8 from tapioca import (JSONAdapterMixin, TapiocaAdapter, generate_wrapper_from_adapter) from .resource_mapping import RESOURCE_MAPPING class InstagramClientAdapter(JSONAdapterMixin, TapiocaAdapter): api_root = 'https://api.instagram.com/v1/' resource_mapping = RESOURCE_MAP...
Fix KeyError exception when called with no parameters
Fix KeyError exception when called with no parameters
Python
mit
vintasoftware/tapioca-instagram
93ed6f7db7060893214571bf5ec8a633fffa48ab
python/completers/cpp/clang_helpers.py
python/completers/cpp/clang_helpers.py
#!/usr/bin/env python # # Copyright (C) 2011, 2012 Strahinja Val Markovic <val@markovic.io> # # This file is part of YouCompleteMe. # # YouCompleteMe is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either ve...
#!/usr/bin/env python # # Copyright (C) 2011, 2012 Strahinja Val Markovic <val@markovic.io> # # This file is part of YouCompleteMe. # # YouCompleteMe is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either ve...
Fix bug with removing flag after "-c"
Fix bug with removing flag after "-c" -c does not take an argument. Why did I think it did?
Python
mit
nikmartin/dotfiles
c7fb70585b0c488d523a4ff173e3b0675029e90b
cmsplugin_filer_link/cms_plugins.py
cmsplugin_filer_link/cms_plugins.py
from __future__ import unicode_literals from cms.plugin_base import CMSPluginBase from cms.plugin_pool import plugin_pool from django.utils.translation import ugettext as _ from django.conf import settings from .models import FilerLinkPlugin class FilerLinkPlugin(CMSPluginBase): module = 'Filer' model = File...
from __future__ import unicode_literals from cms.plugin_base import CMSPluginBase from cms.plugin_pool import plugin_pool from django.utils.translation import ugettext as _ from django.conf import settings from .models import FilerLinkPlugin class FilerLinkPlugin(CMSPluginBase): module = 'Filer' model = File...
Revert "Add "page_link" to "raw_id_fields" to prevent the run of "decompress""
Revert "Add "page_link" to "raw_id_fields" to prevent the run of "decompress"" This reverts commit 4a85ecaaae1452e74acc485d032f00e8bedace47.
Python
bsd-3-clause
yvess/cmsplugin-filer,divio/cmsplugin-filer,alsoicode/cmsplugin-filer,creimers/cmsplugin-filer,jschneier/cmsplugin-filer,stefanfoulis/cmsplugin-filer,brightinteractive/cmsplugin-filer,nephila/cmsplugin-filer,creimers/cmsplugin-filer,jschneier/cmsplugin-filer,brightinteractive/cmsplugin-filer,skirsdeda/cmsplugin-filer,d...
dafa014fa5c4788affd2712b68ef5bee56b5e600
engine/game.py
engine/game.py
from .gobject import GObject from . import signals class Game(GObject): def __init__(self): self.maps = {} self.player = None def run(self): pass def handle_signals(self): signals.handle_signals(self) @staticmethod def reg_signal(*args): signals.reg_signal...
from .gobject import GObject from . import signals import time class Game(GObject): def __init__(self): self.maps = {} self.player = None def run(self): while True: self.handle_signals() time.sleep(0.3) def handle_signals(self): signals.handle_signa...
Handle signals with default interface
Handle signals with default interface
Python
bsd-3-clause
entwanne/NAGM
9858837add5105f2f4e78abe84930c4e164071b9
examples/me.py
examples/me.py
from buffer.api import API from buffer.user import User token = '1/714ebdb617705ef9491a81fb21c1da42' api = API(client_id='51cc6dd5f882a8ba18000055', client_secret='83b019d154cae4d2c734d813b33e5e53') r = api.get('user.json?') print r.content #user = User(api=api)
from buffer.api import API from buffer.user import User token = '1/714ebdb617705ef9491a81fb21c1da42' api = API(client_id='51cc6dd5f882a8ba18000055', client_secret='83b019d154cae4d2c734d813b33e5e53', access_token=token) user = User(api=api) print user.id
Create first examples that used the actual API
Create first examples that used the actual API
Python
mit
vtemian/buffpy,bufferapp/buffer-python
dac3c4f163c694b9b083247e72189996e5e2125c
just/json_.py
just/json_.py
import json def read(fn): if fn.endswith(".jsonl"): raise TypeError("JSON Newline format can only be read by iread") with open(fn) as f: return json.load(f) def append(obj, fn): with open(fn, "a+") as f: f.write(json.dumps(obj) + "\n") def write(obj, fn): with open(fn, "w")...
import json def read(fn): if fn.endswith(".jsonl"): raise TypeError("JSON Newline format can only be read by iread") with open(fn) as f: return json.load(f) def append(obj, fn): with open(fn, "a+") as f: f.write(json.dumps(obj) + "\n") def write(obj, fn): with open(fn, "w")...
Add detailed error message to jsonl parsing
Add detailed error message to jsonl parsing
Python
agpl-3.0
kootenpv/just
60cbe21d95cc6e079979022a505dcc2099bd30c1
cla_public/libs/call_centre_availability.py
cla_public/libs/call_centre_availability.py
import datetime from flask.ext.babel import lazy_gettext as _ def time_choice(time): display_format = "%I:%M %p" end = time + datetime.timedelta(minutes=30) display_string = time.strftime(display_format).lstrip("0") + " - " + end.strftime(display_format).lstrip("0") return time.strftime("%H%M"), displ...
import datetime from cla_public.libs.utils import get_locale from flask.ext.babel import lazy_gettext as _ def time_choice(time): display_format = "%I:%M %p" end = time + datetime.timedelta(minutes=30) display_string = time.strftime(display_format).lstrip("0") + " - " + end.strftime(display_format).lstrip...
Add welsh days ordinal suffix
Add welsh days ordinal suffix
Python
mit
ministryofjustice/cla_public,ministryofjustice/cla_public,ministryofjustice/cla_public,ministryofjustice/cla_public
c33bbe44708ccf60f4a0cf759b3f38b739b7fb5d
PartyUPLambda/purge.py
PartyUPLambda/purge.py
""" Scan through the Samples table for oldish entries and remove them. """ import json import boto3 import time import decimal from boto3.dynamodb.conditions import Key, Attr def purge_item(item, batch): response = batch.delete_item( Key={ 'event' : item['event'], 'id': item['id'] ...
""" Scan through the Samples table for oldish entries and remove them. """ import logging import json import boto3 import time import decimal from boto3.dynamodb.conditions import Key, Attr logger = logging.getLogger() logger.setLevel(logging.ERROR) def purge_item(item, batch): response = batch.delete_item( ...
Add error logging to aid tracking down future issues.
Add error logging to aid tracking down future issues.
Python
mit
SandcastleApps/partyup,SandcastleApps/partyup,SandcastleApps/partyup
3f750865762e7751ce0cbd4a171d68e9d1d5a8a6
contrib/tempest/tempest/cli/manilaclient.py
contrib/tempest/tempest/cli/manilaclient.py
# Copyright 2014 Mirantis Inc. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by...
# Copyright 2014 Mirantis Inc. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by...
Fix tempest compatibility for cli tests
Fix tempest compatibility for cli tests Commit https://github.com/openstack/tempest/commit/2474f41f made changes to tempest project that are inconsistent with our plugin. Make our plugin use latest changes to keep compatibility. Change-Id: I08d28b40fdd9ad54a0bcce30647d796943332116
Python
apache-2.0
bswartz/manila,jcsp/manila,bswartz/manila,weiting-chen/manila,sajuptpm/manila,openstack/manila,NetApp/manila,redhat-openstack/manila,sajuptpm/manila,vponomaryov/manila,weiting-chen/manila,NetApp/manila,jcsp/manila,vponomaryov/manila,redhat-openstack/manila,openstack/manila,scality/manila,scality/manila
0a9aed9427b0b36d71a2e8fee74db74690727b15
hardware/gpio/LEDblink_gpiozero.py
hardware/gpio/LEDblink_gpiozero.py
from gpiozero import LED import time # GPIO 24 ... LED ... 470 ohm resistor ... GND led = LED(24) try: led.blink() time.sleep(20) except KeyboardInterrupt: led.off()
from gpiozero import LED import time # GPIO 24 ... LED ... 470 ohm resistor ... GND led = LED(24) try: led.blink() time.sleep(20) except KeyboardInterrupt: led.off() print "done"
Print message on completion, to aid debugging
Print message on completion, to aid debugging
Python
mit
claremacrae/raspi_code,claremacrae/raspi_code,claremacrae/raspi_code
92cb843c1b6ada9b63038ed1ce22f83ee6146aff
jazzy/scope.py
jazzy/scope.py
import uuid class Scope: def __init__(self): self.pc = 0; self.variables = {} self.lvalue = self self.rvalue = self self.stack = [1,2,3] self.name = uuid.uuid1() def GetVar(self, name): if name in self.variables: return self.variables[name] ...
import uuid class Scope: def __init__(self): self.pc = 0; self.variables = {} self.lvalue = self self.rvalue = self self.stack = [1,2,3] self.name = uuid.uuid1() def GetVar(self, name): if name in self.variables: return self.variables[name] ...
Add functions to get/set variables addresses
Add functions to get/set variables addresses Since some of the jaz commands depend on the address of an variable, made function to obtain it.
Python
mit
joewashear007/jazzy
c407c067495d76ebed7c36ef005861c80fdcfdce
textx/__init__.py
textx/__init__.py
__version__ = "1.6.dev"
from textx.metamodel import metamodel_from_file, metamodel_from_str # noqa from textx.langapi import get_language, iter_languages # noqa __version__ = "1.6.dev"
Make metamodel factory methods and lang API available in textx package.
Make metamodel factory methods and lang API available in textx package.
Python
mit
igordejanovic/textX,igordejanovic/textX,igordejanovic/textX
0e044d1ad8b6fb2b0ac2126bb0fccfa05de9da14
file_transfer/datamover/__init__.py
file_transfer/datamover/__init__.py
from .connectors import (GithubConnector, S3Connector, FTPConnector, LocalConnector) from .transporters import (BaltradToS3, LocalToS3) from .s3enram import S3EnramHandler from .utils import (parse_filename, extract_month_updates, parse_coverage_month, coverage_to_csv)
from .connectors import (GithubConnector, S3Connector, FTPConnector, LocalConnector) from .transporters import (BaltradToS3, LocalToS3) from .s3enram import S3EnramHandler from .utils import (parse_filename, extract_month_updates, parse_coverage_month, coverage_to_csv, ...
Add csv handling to module
Add csv handling to module
Python
mit
enram/data-repository,enram/data-repository,enram/data-repository,enram/infrastructure,enram/data-repository,enram/infrastructure
abc1d2095f18f6c7ff129f3b8bf9eae2d7a6239a
skimage/io/tests/test_io.py
skimage/io/tests/test_io.py
import os from numpy.testing import * import numpy as np import skimage.io as io from skimage import data_dir def test_stack_basic(): x = np.arange(12).reshape(3, 4) io.push(x) assert_array_equal(io.pop(), x) @raises(ValueError) def test_stack_non_array(): io.push([[1, 2, 3]]) def test_imread_u...
import os from numpy.testing import * import numpy as np import skimage.io as io from skimage import data_dir def test_stack_basic(): x = np.arange(12).reshape(3, 4) io.push(x) assert_array_equal(io.pop(), x) @raises(ValueError) def test_stack_non_array(): io.push([[1, 2, 3]]) def test_imread_u...
Fix file URI in test (2nd attempt)
BUG: Fix file URI in test (2nd attempt)
Python
bsd-3-clause
WarrenWeckesser/scikits-image,SamHames/scikit-image,chintak/scikit-image,chintak/scikit-image,juliusbierk/scikit-image,oew1v07/scikit-image,blink1073/scikit-image,bsipocz/scikit-image,bennlich/scikit-image,youprofit/scikit-image,dpshelio/scikit-image,newville/scikit-image,dpshelio/scikit-image,GaZ3ll3/scikit-image,ofgu...
4e699d94c84f1123f36a331926ca77af3f86b474
tensorflow/python/profiler/traceme.py
tensorflow/python/profiler/traceme.py
# Copyright 2019 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
# Copyright 2019 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
Remove tf_export from TraceMe Python API.
Remove tf_export from TraceMe Python API. PiperOrigin-RevId: 262247599
Python
apache-2.0
cxxgtxy/tensorflow,karllessard/tensorflow,jhseu/tensorflow,tensorflow/tensorflow,jhseu/tensorflow,yongtang/tensorflow,renyi533/tensorflow,petewarden/tensorflow,renyi533/tensorflow,freedomtan/tensorflow,renyi533/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow-experimental_link_static_libraries...
759f6a2e4ced9ce9beeda01e638f109d946050b1
server/migrations/0006_auto_20150811_0811.py
server/migrations/0006_auto_20150811_0811.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('server', '0005_auto_20150717_1827'), ] operations = [ migrations.AddField( model_name='machine', nam...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import get_object_or_404 from django.db import models, migrations def add_initial_date(apps, schema_editor): Machine = apps.get_model("server", "Machine") for machine in Machine.objects.all(): if not machine.first_che...
Add in the first checkin date if it doesn't exist
Add in the first checkin date if it doesn't exist
Python
apache-2.0
sheagcraig/sal,salopensource/sal,salopensource/sal,macjustice/sal,chasetb/sal,salopensource/sal,sheagcraig/sal,erikng/sal,macjustice/sal,erikng/sal,chasetb/sal,chasetb/sal,erikng/sal,macjustice/sal,macjustice/sal,sheagcraig/sal,erikng/sal,sheagcraig/sal,chasetb/sal,salopensource/sal
343d0bcdeb6981ca90673de342eb6064ca62c24e
pip_deploy.py
pip_deploy.py
import subprocess subprocess.call('python setup.py sdist') subprocess.call('python setup.py sdist bdist_wheel upload')
import subprocess subprocess.call('python setup.py sdist') subprocess.call('python setup.py bdist_wheel --universal') subprocess.call('twine upload dist/*')
Update pip deploy script to use twine
Update pip deploy script to use twine
Python
mit
partrita/Gooey,chriskiehl/Gooey,codingsnippets/Gooey
7a98cd1c58985da9230ba5861731b6f252d2c611
source/update.py
source/update.py
"""updates subreddit css with compiled sass""" import time import sass import praw def css() -> str: """compiles sass and returns css""" return sass.compile(filename="index.scss", output_style="compressed") def uid() -> str: """return date and time""" return "Subreddit upload on {}".format(time.str...
"""updates subreddit css with compiled sass""" import os import time from typing import List, Dict, Any, Tuple import praw import sass WebhookResponse = Dict[str, Any] # pylint: disable=C0103 def css() -> str: """compiles sass and returns css""" return sass.compile(filename="index.scss", output_style="compr...
Check for changed files from webhook
Check for changed files from webhook Prevents uploading everything, only the changed assets
Python
mit
neoliberal/css-updater
e6b5c93a8c23fcea84768a8b50708ef7ef78dcd8
functionaltests/api/base.py
functionaltests/api/base.py
# -*- coding: utf-8 -*- # # Copyright 2013 - Noorul Islam K M # # 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 applic...
# -*- coding: utf-8 -*- # # Copyright 2013 - Noorul Islam K M # # 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 applic...
Fix functionaltests (imported tempest code has changed)
Fix functionaltests (imported tempest code has changed) get_auth_provider now takes an argument. Change-Id: I4a80ef3fdf2914854268459cf1080a46922e93d5
Python
apache-2.0
gilbertpilz/solum,ed-/solum,ed-/solum,gilbertpilz/solum,openstack/solum,devdattakulkarni/test-solum,gilbertpilz/solum,stackforge/solum,openstack/solum,ed-/solum,stackforge/solum,devdattakulkarni/test-solum,ed-/solum,gilbertpilz/solum
32994f27d1644415e8cd4a22f1b47d4938d3620c
fulfil_client/oauth.py
fulfil_client/oauth.py
from requests_oauthlib import OAuth2Session class Session(OAuth2Session): client_id = None client_secret = None def __init__(self, subdomain, **kwargs): client_id = self.client_id client_secret = self.client_secret self.fulfil_subdomain = subdomain if not (client_id and c...
from requests_oauthlib import OAuth2Session class Session(OAuth2Session): client_id = None client_secret = None def __init__(self, subdomain, **kwargs): client_id = self.client_id client_secret = self.client_secret self.fulfil_subdomain = subdomain if not (client_id and c...
Add provision to pass extra args in auth url
Add provision to pass extra args in auth url
Python
isc
fulfilio/fulfil-python-api,sharoonthomas/fulfil-python-api
c7d5a39fd21c2d5c9c5f8a2b88b5e09c98e9e776
ovp_users/emails.py
ovp_users/emails.py
from ovp_core.emails import BaseMail class UserMail(BaseMail): """ This class is responsible for firing emails for Users """ def __init__(self, user, async_mail=None): super(UserMail, self).__init__(user.email, async_mail) def sendWelcome(self, context={}): """ Sent when user registers """ ...
from ovp_core.emails import BaseMail class UserMail(BaseMail): """ This class is responsible for firing emails for Users """ def __init__(self, user, async_mail=None): super(UserMail, self).__init__(user.email, async_mail) def sendWelcome(self, context={}): """ Sent when user registers """ ...
Revert "pass 'user_email' on sendRecoveryToken's context"
Revert "pass 'user_email' on sendRecoveryToken's context" This info is already sent as 'email' on context. This reverts commit a366c2ed02cd7dda54607fe5e6a317603d442b47.
Python
agpl-3.0
OpenVolunteeringPlatform/django-ovp-users,OpenVolunteeringPlatform/django-ovp-users
387ca6153d0f584f3caf27add6cf01d1da081fc3
plasmapy/physics/__init__.py
plasmapy/physics/__init__.py
# 'physics' is a tentative name for this subpackage. Another # possibility is 'plasma'. The organization is to be decided by v0.1. from .parameters import Alfven_speed, ion_sound_speed, thermal_speed, kappa_thermal_speed, gyrofrequency, gyroradius, plasma_frequency, Debye_length, Debye_number, inertial_length, magne...
# 'physics' is a tentative name for this subpackage. Another # possibility is 'plasma'. The organization is to be decided by v0.1. from .parameters import Alfven_speed, ion_sound_speed, thermal_speed, kappa_thermal_speed, gyrofrequency, gyroradius, plasma_frequency, Debye_length, Debye_number, inertial_length, magne...
Add classical_transport to init file
Add classical_transport to init file
Python
bsd-3-clause
StanczakDominik/PlasmaPy
2d45775e3823cf5a27df92350cbc89963aecc84c
gym/envs/tests/test_registration.py
gym/envs/tests/test_registration.py
# -*- coding: utf-8 -*- from gym import error, envs from gym.envs import registration from gym.envs.classic_control import cartpole def test_make(): env = envs.make('CartPole-v0') assert env.spec.id == 'CartPole-v0' assert isinstance(env, cartpole.CartPoleEnv) def test_make_deprecated(): try: ...
# -*- coding: utf-8 -*- from gym import error, envs from gym.envs import registration from gym.envs.classic_control import cartpole def test_make(): env = envs.make('CartPole-v0') assert env.spec.id == 'CartPole-v0' assert isinstance(env, cartpole.CartPoleEnv) def test_make_deprecated(): try: ...
Fix broken registration test to handle new DeprecatedEnv error
Fix broken registration test to handle new DeprecatedEnv error
Python
mit
d1hotpep/openai_gym,d1hotpep/openai_gym,dianchen96/gym,machinaut/gym,Farama-Foundation/Gymnasium,machinaut/gym,dianchen96/gym,Farama-Foundation/Gymnasium
7599f60a0e64f1d1d076695af67a212be751a89b
tests/rules_tests/grammarManipulation_tests/InactiveRulesTest.py
tests/rules_tests/grammarManipulation_tests/InactiveRulesTest.py
#!/usr/bin/env python """ :Author Patrik Valkovic :Created 23.06.2017 16:39 :Licence GNUv3 Part of grammpy """ from unittest import main, TestCase from grammpy import Grammar, Nonterminal, Rule as _R from ..grammar import * class InactiveRulesTest(TestCase): def __init__(self, *args): super().__init__(*...
#!/usr/bin/env python """ :Author Patrik Valkovic :Created 23.06.2017 16:39 :Licence GNUv3 Part of grammpy """ from unittest import main, TestCase from grammpy import Grammar, Nonterminal, Rule as _R from ..grammar import * class InactiveRulesTest(TestCase): def __init__(self, *args): super().__init__(*...
Add test when rule with inactive is passed
Add test when rule with inactive is passed
Python
mit
PatrikValkovic/grammpy
e9541dbd1959b7a2ad1ee9145d3168c5898fe204
python/generate_sorl_xml.py
python/generate_sorl_xml.py
#!/usr/bin/env python3 import sys from message import Message from persistence import Persistence from const import XML_FILE_EXTENSION message = Persistence.get_message_from_file(sys.argv[1]) if (message is not None): Persistence.message_to_solr_xml(message, sys.argv[2] + message.identifier + XML_FILE_EXTENSION...
#!/usr/bin/env python3 import sys from document import Document from persistence import Persistence from const import XML_FILE_EXTENSION document = Persistence.get_document_from_file(sys.argv[1]) if (document is not None): Persistence.document_to_solr_xml(document, sys.argv[2] + document.identifier + XML_FILE_E...
Fix wrong naming in generate...py
Fix wrong naming in generate...py Signed-off-by: Fabio Benigno <7de248c2f6c04081ad3a3569b5954b1b677fee3b@gmail.com>
Python
apache-2.0
fpbfabio/newsgroups1000s,fpbfabio/dblp_data_processing
76afe0ef2f45ff7ff62dd5ea4d1217ce794770ba
us_ignite/snippets/management/commands/snippets_load_fixtures.py
us_ignite/snippets/management/commands/snippets_load_fixtures.py
from django.core.management.base import BaseCommand from us_ignite.snippets.models import Snippet FIXTURES = [ { 'slug': 'home-box', 'name': 'UP NEXT: LOREM IPSUM', 'body': '', 'url_text': 'GET INVOLVED', 'url': '', }, { 'slug': 'featured', 'name': ...
from django.core.management.base import BaseCommand from us_ignite.snippets.models import Snippet FIXTURES = [ { 'slug': 'home-box', 'name': 'UP NEXT: LOREM IPSUM', 'body': '', 'url_text': 'GET INVOLVED', 'url': '', }, { 'slug': 'featured', 'name': ...
Load initial fixture for the welcome email.
Load initial fixture for the welcome email. https://github.com/madewithbytes/us_ignite/issues/172
Python
bsd-3-clause
us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite
b8386212826701131e3c5aaaadef726df97f6646
api/serializers.py
api/serializers.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.contrib.auth.models import User from rest_framework import serializers from core.models import Timesheet, Task, Entry class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ('id'...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.contrib.auth.models import User from rest_framework import serializers from core.models import Timesheet, Task, Entry class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ('id'...
Add complete field to task and timesheet api
Add complete field to task and timesheet api
Python
bsd-2-clause
Leahelisabeth/timestrap,overshard/timestrap,cdubz/timestrap,Leahelisabeth/timestrap,overshard/timestrap,muhleder/timestrap,Leahelisabeth/timestrap,cdubz/timestrap,overshard/timestrap,muhleder/timestrap,cdubz/timestrap,muhleder/timestrap,Leahelisabeth/timestrap
ffb42ba8e9b0a5d7a269ee9d13a5347f4ffee563
mama_cas/tests/test_callbacks.py
mama_cas/tests/test_callbacks.py
from django.test import TestCase from .factories import UserFactory from mama_cas.callbacks import user_model_attributes from mama_cas.callbacks import user_name_attributes class CallbacksTests(TestCase): url = 'http://www.example.com/' def setUp(self): self.user = UserFactory() def test_user_n...
from django.test import TestCase from .factories import UserFactory from mama_cas.callbacks import user_model_attributes from mama_cas.callbacks import user_name_attributes class CallbacksTests(TestCase): def setUp(self): self.user = UserFactory() def test_user_name_attributes(self): """ ...
Test short_name for user name attributes callback
Test short_name for user name attributes callback
Python
bsd-3-clause
jbittel/django-mama-cas,orbitvu/django-mama-cas,orbitvu/django-mama-cas,jbittel/django-mama-cas
8c0d1acf6ea41adc3743a4e190eaf777188282c0
nova/policies/floating_ip_pools.py
nova/policies/floating_ip_pools.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...
Introduce scope_types in FIP pools
Introduce scope_types in FIP pools Appropriate scope_type for nova case: - https://specs.openstack.org/openstack/nova-specs/specs/ussuri/approved/policy-defaults-refresh.html#scope This commit introduce scope_type for FIP pools policies as 'system' and 'project' Partial implement blueprint policy-defaults-refresh-de...
Python
apache-2.0
mahak/nova,mahak/nova,klmitch/nova,openstack/nova,klmitch/nova,openstack/nova,mahak/nova,klmitch/nova,openstack/nova,klmitch/nova
67c6ecff4d5c65cd5b919bb1316f188bc6ab1098
tests/python_tests/test_core_device.py
tests/python_tests/test_core_device.py
import pytest import xchainer def test_device(): device = xchainer.get_current_device() xchainer.set_current_device('cpu') assert str(xchainer.get_current_device()) == '<Device cpu>' xchainer.set_current_device('cuda') assert str(xchainer.get_current_device()) == '<Device cuda>' with pytes...
import pytest import xchainer def test_device(): cpu1 = xchainer.Device('cpu') cpu2 = xchainer.Device('cpu') cuda = xchainer.Device('cuda') assert cpu1 == cpu2 assert not (cpu1 != cpu2) assert not (cpu1 == cuda) assert cpu1 != cuda with pytest.raises(xchainer.DeviceError): xc...
Add tests for python device
Add tests for python device
Python
mit
okuta/chainer,keisuke-umezawa/chainer,chainer/chainer,ktnyt/chainer,ktnyt/chainer,ktnyt/chainer,wkentaro/chainer,hvy/chainer,jnishi/chainer,okuta/chainer,hvy/chainer,pfnet/chainer,niboshi/chainer,niboshi/chainer,wkentaro/chainer,hvy/chainer,tkerola/chainer,jnishi/chainer,niboshi/chainer,jnishi/chainer,keisuke-umezawa/c...
3c798673cfb5f7e63e2aebb300ba7cc92c72fa8a
aggregator/base.py
aggregator/base.py
from abc import ABCMeta, abstractmethod import requests from bs4 import BeautifulSoup def make_soup(url): response = requests.get(url) soup = BeautifulSoup(response.text, 'html.parser') return soup class Aggregator(metaclass=ABCMeta): base_url = '' @abstractmethod def extract(self): pass @abstractm...
import collections from abc import ABCMeta, abstractmethod import requests from bs4 import BeautifulSoup Article = collections.namedtuple('Article', ['source', 'title', 'url', 'author', 'date_published']) def make_soup(url): response = requests.get(url) soup = BeautifulSoup(response.text, 'html.par...
Define new abstract methods and namedtuple
Define new abstract methods and namedtuple
Python
apache-2.0
footynews/fn_backend
9da3f2a835fa2aaba5d91ffe31b3fcaf8d83a4c9
snake/main.py
snake/main.py
import os import sys from snake.core import Snake SNAKEFILE_LOADED = False def abort(msg): print >> sys.stderr, "Error: %s" % msg sys.exit(1) def load_snakefile(path, fail_silently=False): global SNAKEFILE_LOADED if not SNAKEFILE_LOADED: sys.path.insert(0, path) try: r...
import imp import os import sys from snake.core import Snake def abort(msg): print >> sys.stderr, "Error: %s" % msg sys.exit(1) def get_ascending_paths(path): paths = [] while True: paths.append(path) path, tail = os.path.split(path) if not tail: break return ...
Improve the way snakefile loading works
Improve the way snakefile loading works
Python
bsd-2-clause
yumike/snake
b2239ab0329f129da21f3ab82eaf9543b95fc01b
pal/services/joke_service.py
pal/services/joke_service.py
import re from pal.services.service import Service from pal.services.service import wrap_response class JokeService(Service): _JOKES = { 'open the pod bay doors pal': "I'm sorry, Jeff, I'm afraid I can't do that.", 'laws of robotics': "1. A robot may not injure a human bei...
import re from pal.services.service import Service from pal.services.service import wrap_response class JokeService(Service): _JOKES = { 'pod bay doors': "I'm sorry Jeff, I'm afraid I can't do that.", 'laws of robotics': "1. A robot may not injure a human being or, through...
Add Waldo joke and simplify HAL joke
Add Waldo joke and simplify HAL joke
Python
bsd-3-clause
Machyne/pal,Machyne/pal,Machyne/pal,Machyne/pal
c046d7915c08221e4a84a01edf3ca08a27a931a8
opps/api/urls.py
opps/api/urls.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from django.conf.urls import patterns, url from piston.resource import Resource from opps.containers.api import ContainerHandler, ContainerBoxHandler container = Resource(handler=ContainerHandler) containerbox = Resource(handler=ContainerBoxHandler) urlpatterns = patte...
#!/usr/bin/env python # -*- coding: utf-8 -*- from django.conf.urls import patterns, url from piston.resource import Resource from opps.containers.api import ContainerHandler, ContainerBoxHandler container = Resource(handler=ContainerHandler) containerbox = Resource(handler=ContainerBoxHandler) urlpatterns = patte...
Set emitter format json in api
Set emitter format json in api
Python
mit
williamroot/opps,jeanmask/opps,williamroot/opps,opps/opps,jeanmask/opps,williamroot/opps,williamroot/opps,opps/opps,YACOWS/opps,YACOWS/opps,jeanmask/opps,opps/opps,YACOWS/opps,YACOWS/opps,jeanmask/opps,opps/opps
5b2a63706d2f9d2853ba1f6ad8d1cf80f8c07676
tohu/__init__.py
tohu/__init__.py
from .v4.base import * from .v4.primitive_generators import * from .v4.derived_generators import * from .v4.dispatch_generators import * from .v4.custom_generator import CustomGenerator from .v4.logging import logger from .v4.utils import print_generated_sequence from .v4 import base from .v4 import primitive_generator...
from distutils.version import StrictVersion from platform import python_version min_supported_python_version = '3.6' if StrictVersion(python_version()) < StrictVersion(min_supported_python_version): error_msg = ( "Tohu requires Python {min_supported_python_version} or greater to run " "(currently ...
Check Python version at startup
Check Python version at startup
Python
mit
maxalbert/tohu
3bf41213abc7ddd8421e11c2149b536c255c13eb
pixpack/utils.py
pixpack/utils.py
#!/usr/bin/env python3 # utility.py # PixPack Photo Organiser # It contains some useful functions to increase user experience import locale import os def sys_trans_var(): # check system language sys_loc = locale.getlocale() sys_lang = sys_loc[0] # system default language if sys_lang == 'en_EN' or sys...
#!/usr/bin/env python3 # utility.py # PixPack Photo Organiser # It contains some useful functions to increase user experience import locale import os def sys_trans_var(): # check system language sys_loc = locale.getlocale() sys_lang = sys_loc[0] # system default language if sys_lang == 'en_EN' or sys...
Store the duplicated items separately in related folder
Store the duplicated items separately in related folder
Python
mit
OrhanOdabasi/PixPack,OrhanOdabasi/PixPack
dcb62a352b7473779f1cc907c920c9b42ee9ceac
django_extensions/management/commands/print_settings.py
django_extensions/management/commands/print_settings.py
from django.core.management.base import BaseCommand from django.conf import settings class Command(BaseCommand): help = "Print the active Django settings." def handle(self, *args, **options): for key in dir(settings): if key.startswith('__'): continue value = ...
""" print_settings ============== Django command similar to 'diffsettings' but shows all active Django settings. """ from django.core.management.base import NoArgsCommand from django.conf import settings from optparse import make_option class Command(NoArgsCommand): """print_settings command""" help = "Pri...
Make output format configurable (simple, pprint, json, yaml)
Make output format configurable (simple, pprint, json, yaml) $ pylint django-extensions/django_extensions/management/commands/print_settings.py | grep rated No config file found, using default configuration Your code has been rated at 10.00/10 (previous run: 10.00/10)
Python
mit
lamby/django-extensions,barseghyanartur/django-extensions,dpetzold/django-extensions,jpadilla/django-extensions,Moulde/django-extensions,marctc/django-extensions,levic/django-extensions,kevgathuku/django-extensions,bionikspoon/django-extensions,atchariya/django-extensions,maroux/django-extensions,frewsxcv/django-extens...
a1ec7fbf4bb00d2a24dfba0acf6baf18d1b016ee
froide/comments/forms.py
froide/comments/forms.py
from django import forms from django.utils.translation import gettext_lazy as _ from django_comments.forms import ( CommentForm as DjangoCommentForm, COMMENT_MAX_LENGTH ) class CommentForm(DjangoCommentForm): name = forms.CharField( label=_('Name'), required=True, help_text=_('You...
from django import forms from django.utils.translation import gettext_lazy as _ from django_comments.forms import ( CommentForm as DjangoCommentForm, COMMENT_MAX_LENGTH ) class CommentForm(DjangoCommentForm): name = forms.CharField( label=_('Name'), required=True, max_length=50, ...
Add max length to comment field
Add max length to comment field
Python
mit
fin/froide,fin/froide,stefanw/froide,fin/froide,stefanw/froide,stefanw/froide,fin/froide,stefanw/froide,stefanw/froide
06458ef8dd3db840c37127a6a4c0c41ed2ffe6f4
pybossa/sentinel/__init__.py
pybossa/sentinel/__init__.py
from redis import sentinel, StrictRedis class Sentinel(object): def __init__(self, app=None): self.app = app self.master = StrictRedis() self.slave = self.master if app is not None: # pragma: no cover self.init_app(app) def init_app(self, app): self.connec...
from redis import sentinel, StrictRedis class Sentinel(object): def __init__(self, app=None): self.app = app self.master = StrictRedis() self.slave = self.master if app is not None: # pragma: no cover self.init_app(app) def init_app(self, app): self.connec...
Add retry on timeout option to sentinel connection
Add retry on timeout option to sentinel connection
Python
agpl-3.0
geotagx/pybossa,inteligencia-coletiva-lsd/pybossa,jean/pybossa,geotagx/pybossa,OpenNewsLabs/pybossa,PyBossa/pybossa,OpenNewsLabs/pybossa,jean/pybossa,PyBossa/pybossa,Scifabric/pybossa,inteligencia-coletiva-lsd/pybossa,Scifabric/pybossa
ec92c0cedb6da3180284273926ccfe05ac334729
snippets/base/middleware.py
snippets/base/middleware.py
from django.core.urlresolvers import resolve from snippets.base.views import fetch_snippets class FetchSnippetsMiddleware(object): """ If the incoming request is for the fetch_snippets view, execute the view and return it before other middleware can run. fetch_snippets is a very very basic view that...
from django.core.urlresolvers import resolve from snippets.base.views import fetch_snippets class FetchSnippetsMiddleware(object): """ If the incoming request is for the fetch_snippets view, execute the view and return it before other middleware can run. fetch_snippets is a very very basic view that...
Disable New Relic's apdex metric on non-fetch_snippets views.
Disable New Relic's apdex metric on non-fetch_snippets views. New Relic doesn't allow us to set different thresholds for different pages across the site, so in order to get valuable metrics on the main view for snippets, fetch_snippets, we need to disable apdex for the admin interface and public snippets views, which ...
Python
mpl-2.0
akatsoulas/snippets-service,schalkneethling/snippets-service,mozilla/snippets-service,mozilla/snippets-service,mozilla/snippets-service,mozmar/snippets-service,schalkneethling/snippets-service,Osmose/snippets-service,bensternthal/snippets-service,akatsoulas/snippets-service,mozmar/snippets-service,glogiotatidis/snippet...
439f0326cc71cf19e41137745aedeec391727207
src/sentry/web/frontend/organization_api_keys.py
src/sentry/web/frontend/organization_api_keys.py
from __future__ import absolute_import from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect from sentry.models import ApiKey, OrganizationMemberType from sentry.web.frontend.base import OrganizationView class OrganizationApiKeysView(OrganizationView): required_access = Organ...
from __future__ import absolute_import from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect from operator import or_ from sentry.models import ApiKey, OrganizationMemberType from sentry.web.frontend.base import OrganizationView DEFAULT_SCOPES = [ 'project:read', 'event:re...
Set default scopes to read
Set default scopes to read
Python
bsd-3-clause
pauloschilling/sentry,llonchj/sentry,JamesMura/sentry,hongliang5623/sentry,gg7/sentry,gencer/sentry,BuildingLink/sentry,llonchj/sentry,ifduyue/sentry,kevinastone/sentry,drcapulet/sentry,BayanGroup/sentry,Kryz/sentry,1tush/sentry,kevinlondon/sentry,beeftornado/sentry,beeftornado/sentry,felixbuenemann/sentry,JamesMura/se...
2c26434b7dcd71530d453989372b8d67d90ad3c7
rwt/scripts.py
rwt/scripts.py
import sys import tokenize def run(cmdline): """ Execute the script as if it had been invoked naturally. """ namespace = dict() filename = cmdline[0] namespace['__file__'] = filename namespace['__name__'] = '__main__' sys.argv[:] = cmdline open_ = getattr(tokenize, 'open', open) script = open_(filename).re...
import sys import ast import tokenize def read_deps(script, var_name='__requires__'): """ Given a script path, read the dependencies from the indicated variable (default __requires__). Does not execute the script, so expects the var_name to be assigned a static list of strings. """ with open(script) as stream:...
Add routine for loading deps from a script.
Add routine for loading deps from a script.
Python
mit
jaraco/rwt
dec97fd68509cabfd53dcf588952b3b25d3e0e17
normandy/base/urls.py
normandy/base/urls.py
from django.conf.urls import include, url from normandy.base import views from normandy.base.api import views as api_views from normandy.base.api.routers import MixedViewRouter # API Router router = MixedViewRouter() router.register("user", api_views.UserViewSet) router.register("group", api_views.GroupViewSet) ur...
from django.conf.urls import include, url from normandy.base import views from normandy.base.api import views as api_views from normandy.base.api.routers import MixedViewRouter # API Router router = MixedViewRouter() router.register("user", api_views.UserViewSet) router.register("group", api_views.GroupViewSet) ur...
Make service info available on v3 API
Make service info available on v3 API
Python
mpl-2.0
mozilla/normandy,mozilla/normandy,mozilla/normandy,mozilla/normandy
767b9867a1e28063fae33ea46478372818b5a129
cla_backend/apps/core/views.py
cla_backend/apps/core/views.py
from django.views import defaults from sentry_sdk import capture_message, push_scope def page_not_found(request, *args, **kwargs): with push_scope() as scope: scope.set_tag("type", "404") scope.set_extra("path", request.path) capture_message("Page not found", level="error") return de...
from django.views import defaults from sentry_sdk import capture_message, push_scope def page_not_found(request, *args, **kwargs): with push_scope() as scope: scope.set_tag("path", request.path) for i, part in enumerate(request.path.strip("/").split("/")): scope.set_tag("path_{}".forma...
Tag sentry event with each part of path
Tag sentry event with each part of path
Python
mit
ministryofjustice/cla_backend,ministryofjustice/cla_backend,ministryofjustice/cla_backend,ministryofjustice/cla_backend
e08c7352fc5de7e098e434bfc1f2df4384c3405a
tests/base.py
tests/base.py
import unittest import glob import os import mmstats class MmstatsTestCase(unittest.TestCase): def setUp(self): super(MmstatsTestCase, self).setUp() self.path = mmstats.DEFAULT_PATH # Clean out stale mmstats files for fn in glob.glob(os.path.join(self.path, 'test*.mmstats')): ...
import unittest import glob import os import mmstats class MmstatsTestCase(unittest.TestCase): @property def files(self): return glob.glob(os.path.join(self.path, 'test*.mmstats')) def setUp(self): super(MmstatsTestCase, self).setUp() self.path = mmstats.DEFAULT_PATH # ...
Refactor test harness file discovery
Refactor test harness file discovery
Python
bsd-3-clause
schmichael/mmstats,schmichael/mmstats,schmichael/mmstats,schmichael/mmstats
35b08e6e7e60a440fe33b7120843766b9f2592c6
tests/urls.py
tests/urls.py
from django.conf.urls import include, url from django.contrib import admin from . import views urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url('foo/', views.MyView.as_view(), name='class-view'), url('bar/', views.MyAPIView.as_view(), name='api-view'), url('', views.my_view, name='funct...
from django.conf.urls import include, url from django.contrib import admin from . import views from incuna_test_utils.compat import DJANGO_LT_17 if DJANGO_LT_17: admin.autodiscover() urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url('foo/', views.MyView.as_view(), name='class-view'), u...
Add compatibility with django < 1.7
Add compatibility with django < 1.7
Python
bsd-2-clause
incuna/incuna-test-utils,incuna/incuna-test-utils
c0de670c5b8b78280ee588ee31a75cf8b3f44799
lms/djangoapps/commerce/migrations/0001_data__add_ecommerce_service_user.py
lms/djangoapps/commerce/migrations/0001_data__add_ecommerce_service_user.py
# -*- coding: utf-8 -*- from django.conf import settings from django.contrib.auth import get_user_model from django.contrib.auth.models import User from django.db import migrations, models USERNAME = settings.ECOMMERCE_SERVICE_WORKER_USERNAME EMAIL = USERNAME + '@fake.email' def forwards(apps, schema_editor): "...
# -*- coding: utf-8 -*- from django.conf import settings from django.contrib.auth import get_user_model from django.contrib.auth.models import User from django.db import migrations, models USERNAME = settings.ECOMMERCE_SERVICE_WORKER_USERNAME EMAIL = USERNAME + '@fake.email' def forwards(apps, schema_editor): "...
Fix sandboax builds, because of signal chains, UserProfile table must be predent before adding a User
Fix sandboax builds, because of signal chains, UserProfile table must be predent before adding a User
Python
agpl-3.0
arbrandes/edx-platform,eduNEXT/edx-platform,stvstnfrd/edx-platform,stvstnfrd/edx-platform,EDUlib/edx-platform,arbrandes/edx-platform,angelapper/edx-platform,arbrandes/edx-platform,eduNEXT/edunext-platform,EDUlib/edx-platform,stvstnfrd/edx-platform,edx/edx-platform,EDUlib/edx-platform,edx/edx-platform,stvstnfrd/edx-plat...
47ddf999dd7ef8cd7600710ad6ad7611dd55a218
bin/testNetwork.py
bin/testNetwork.py
#!/usr/bin/python3 import subprocess import os from time import sleep env = {} HOME = os.environ.get("HOME", "/root") scannerConf = open(HOME+"/scanner.conf", "rt") while True: in_line = scannerConf.readline() if not in_line: break in_line = in_line[:-1] key, value = in_line.split("=") env...
#!/usr/bin/python3 import subprocess import os from time import sleep env = {} HOME = os.environ.get("HOME", "/root") scannerConf = open(HOME+"/scanner.conf", "rt") while True: in_line = scannerConf.readline() if not in_line: break in_line = in_line[:-1] key, value = in_line.split("=") env...
Change the config dictionary key validation
Change the config dictionary key validation
Python
apache-2.0
starksm64/NativeRaspberryPiBeaconParser,starksm64/NativeRaspberryPiBeaconParser,starksm64/NativeRaspberryPiBeaconParser,starksm64/NativeRaspberryPiBeaconParser,starksm64/NativeRaspberryPiBeaconParser
22e16ba6e2bf7135933895162744424e89ca514d
article/tests/article_admin_tests.py
article/tests/article_admin_tests.py
from django.contrib.auth.models import User from django.test import TestCase, override_settings, Client from django.test import RequestFactory from mock import MagicMock from wagtail.wagtailsearch.backends.elasticsearch import Elasticsearch from django.db import DataError, IntegrityError from django.core.exceptions imp...
from django.contrib.auth.models import User from django.test import TestCase, override_settings, Client from django.test import RequestFactory from mock import MagicMock from wagtail.wagtailsearch.backends.elasticsearch import Elasticsearch from django.db import DataError, IntegrityError from django.core.exceptions imp...
Fix test for storing article without any content
Fix test for storing article without any content
Python
bsd-3-clause
PARINetwork/pari,PARINetwork/pari,PARINetwork/pari,PARINetwork/pari
d12be3446cad8b3fa3ae9a1860b3bd6ed20a1d9e
cass-prototype/reddit/api/serializers.py
cass-prototype/reddit/api/serializers.py
from reddit.models import Blog from rest_framework import serializers class BlogSerializer(serializers.Serializer): blog_id = serializers.UUIDField() created_at = serializers.DateTimeField() user = serializers.CharField() description = serializers.CharField() def create(self, validated_data): ...
from reddit.models import Blog from rest_framework import serializers class BlogSerializer(serializers.Serializer): blog_id = serializers.UUIDField() created_at = serializers.DateTimeField() user = serializers.CharField() description = serializers.CharField() def create(self, validated_data): ...
Fix to API Update to allow PATCH
Fix to API Update to allow PATCH
Python
mit
WilliamQLiu/django-cassandra-prototype,WilliamQLiu/django-cassandra-prototype
d8e0c07363069e664dcb6071bc84e8ecc0706739
plugins/join_on_invite/plugin.py
plugins/join_on_invite/plugin.py
class InviteJoinPlugin(object): """Simple plugin that joins a channel if an invite is given.""" callback_id = None """ID generated when callback was added for the irc.invite event""" def __init__(self, cardinal): """Register our callback and save the callback ID""" self.callback_id = c...
from cardinal.decorators import event class InviteJoinPlugin(object): """Simple plugin that joins a channel if an invite is given.""" @event('irc.invite') def join_channel(self, cardinal, user, channel): """Callback for irc.invite that joins a channel""" cardinal.join(channel) def setup...
Use join_on_invite as @event decorator example
Use join_on_invite as @event decorator example
Python
mit
JohnMaguire/Cardinal,BiohZn/Cardinal
bc32e0aadfe2d83d8acb2f219f2fb6bf5f5bb150
ehriportal/portal/management/commands/geocode_addresses.py
ehriportal/portal/management/commands/geocode_addresses.py
"""Geocode Contact objects.""" import sys from geopy import geocoders from django.core.management.base import BaseCommand, CommandError from portal import models class Command(BaseCommand): """Set lat/long fields on contacts with a street address, currently just using Google's geocoder.""" def handle(...
"""Geocode Contact objects.""" import sys import time from geopy import geocoders from django.core.management.base import BaseCommand, CommandError from portal import models class Command(BaseCommand): """Set lat/long fields on contacts with a street address, currently just using Google's geocoder.""" ...
Fix logging, add a sleep to molify Google's rate limit.
Fix logging, add a sleep to molify Google's rate limit.
Python
mit
mikesname/ehri-collections,mikesname/ehri-collections,mikesname/ehri-collections
082076cce996593c9959fc0743f13b62d2e4842b
chared/__init__.py
chared/__init__.py
# Copyright (c) 2011 Vit Suchomel and Jan Pomikalek # All rights reserved. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. try: __version__ = 'v' + __import__('pkg_resources').get_distribution('chared').version except: __version__ =...
# Copyright (c) 2011 Vit Suchomel and Jan Pomikalek # All rights reserved. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. try: __version__ = 'v' + __import__('pkg_resources').get_distribution('chared').version except: import re ...
Make sure the version is displayed as r<revision number> if the information about the package version is not available.
Make sure the version is displayed as r<revision number> if the information about the package version is not available.
Python
bsd-2-clause
gilesbrown/chared,xmichelf/chared
2db4fda62c2eec2d5424448fcd57bedd91ad2e64
test_support/test_fdbsql.py
test_support/test_fdbsql.py
DATABASES = { 'default': { 'ENGINE': 'django_fdbsql', 'NAME': 'django_default', 'OPTIONS': { 'supports_sequence_reset': True, 'use_sequence_reset_function': True, }, }, 'other': { 'ENGINE': 'django_fdbsql', 'NAME': 'django_other', }...
# https://docs.djangoproject.com/en/1.7/internals/contributing/writing-code/unit-tests/#using-another-settings-module DATABASES = { 'default': { 'ENGINE': 'django_fdbsql', 'NAME': 'django_default', 'OPTIONS': { 'supports_sequence_reset': True, 'use_sequence_reset_func...
Use sqlite3 for 'other' database test config
Use sqlite3 for 'other' database test config
Python
mit
freyley/sql-layer-adapter-django
d63463d8dc8acb4445b01fcebeeb6a20ea1d7b9b
tests/unit/test_template.py
tests/unit/test_template.py
import json import pytest from path import Path from formica import cli @pytest.fixture def logger(mocker): return mocker.patch('formica.cli.logger') def test_template_calls_template(tmpdir, logger): with Path(tmpdir): with open('test.template.json', 'w') as f: f.write('{"Description": ...
import json import yaml import pytest from path import Path from formica import cli @pytest.fixture def logger(mocker): return mocker.patch('formica.cli.logger') def test_template_calls_template(tmpdir, logger): with Path(tmpdir): with open('test.template.json', 'w') as f: f.write('{"De...
Test yaml argument for template command
Test yaml argument for template command
Python
mit
flomotlik/formica
cd71740daaf4f1f770b7d6959e2865ed50b76bd7
tilequeue/query/__init__.py
tilequeue/query/__init__.py
import tilequeue.query.postgres make_db_data_fetcher = postgres.make_db_data_fetcher
import tilequeue.query.postgres make_db_data_fetcher = tilequeue.query.postgres.make_db_data_fetcher
Fix error identified by flake8.
Fix error identified by flake8.
Python
mit
mapzen/tilequeue,tilezen/tilequeue
0e6646de573dc04360634828cdb3b7da8cc31d2b
cobe/instatrace.py
cobe/instatrace.py
# Copyright (C) 2010 Peter Teichman import math import time def singleton(cls): instances = {} def getinstance(): if cls not in instances: instances[cls] = cls() return instances[cls] return getinstance @singleton class Instatrace: def __init__(self): self._fd = No...
# Copyright (C) 2010 Peter Teichman import math import time def singleton(cls): instances = {} def getinstance(): if cls not in instances: instances[cls] = cls() return instances[cls] return getinstance @singleton class Instatrace: def __init__(self): self._fd = No...
Allow Instatrace().init(None) to disable tracing at runtime
Allow Instatrace().init(None) to disable tracing at runtime
Python
mit
meska/cobe,pteichman/cobe,DarkMio/cobe,wodim/cobe-ng,LeMagnesium/cobe,tiagochiavericosta/cobe,wodim/cobe-ng,DarkMio/cobe,LeMagnesium/cobe,meska/cobe,tiagochiavericosta/cobe,pteichman/cobe
3d2f9087e62006f8a5f19476ae23324a4cfa7793
regex.py
regex.py
import re import sys f = open ('/var/local/meTypesetTests/tests/testOutput/'+sys.argv[1] +'/nlm/out.xml', "r") print ("open operation complete") fd = f.read() s = '' fd = pattern = re.compile(r'(?:(&#\d*|>))(.*?)(?=(&#\d*|<))') for e in re.findall(pattern, fd): s += ' ' s += e[1] s = re.sub('-', ' ', s) s = re.sub...
import re import sys f = open ('/var/local/meTypesetTests/tests/testOutput/'+sys.argv[1] +'/nlm/out.xml', "r") print ("open operation complete") fd = f.read() s = '' fd = re.sub(r'\&lt.*?\&gt\;', ' ', fd) pattern = re.compile(r'(?:(&#\d*|>))(.*?)(?=(&#\d*|<))') for e in re.findall(pattern, fd): s += ' ' s += e[1] ...
Update of work over prior couple weeks.
Update of work over prior couple weeks.
Python
mit
jnicolls/meTypeset-Test,jnicolls/Joseph
0946379d23131aeec07dc29bebd4e57d95298d00
recipes/sos-notebook/run_test.py
recipes/sos-notebook/run_test.py
# Test that sos kernel is installed import jupyter_client try: jupyter_client.kernelspec.get_kernel_spec('sos') except jupyter_client.kernelspec.NoSuchKernel: print('sos kernel was not installed') print('The following kernels are installed:') print('jupyter_client.kernelspec.find_kernel_specs()') ...
# Test that sos kernel is installed import jupyter_client try: jupyter_client.kernelspec.get_kernel_spec('sos') except jupyter_client.kernelspec.NoSuchKernel: print('sos kernel was not installed') print('The following kernels are installed:') print('jupyter_client.kernelspec.find_kernel_specs()') ...
Use longer TIMEOUT defined in sos_notebook.test_utils.
Use longer TIMEOUT defined in sos_notebook.test_utils.
Python
bsd-3-clause
SylvainCorlay/staged-recipes,synapticarbors/staged-recipes,jochym/staged-recipes,mcs07/staged-recipes,ceholden/staged-recipes,igortg/staged-recipes,goanpeca/staged-recipes,johanneskoester/staged-recipes,isuruf/staged-recipes,scopatz/staged-recipes,chrisburr/staged-recipes,petrushy/staged-recipes,asmeurer/staged-recipes...
c54ea6322177f8665173ae0faa2d34d37a70dea6
setup.py
setup.py
from distutils.core import setup import skyfield # safe, because __init__.py contains no import statements setup( name='skyfield', version=skyfield.__version__, description=skyfield.__doc__.split('\n', 1)[0], long_description=open('README.rst', 'rb').read().decode('utf-8'), license='MIT', auth...
from distutils.core import setup import skyfield # safe, because __init__.py contains no import statements setup( name='skyfield', version=skyfield.__version__, description=skyfield.__doc__.split('\n', 1)[0], long_description=open('README.rst', 'rb').read().decode('utf-8'), license='MIT', auth...
Add pytz as a test requirement
Add pytz as a test requirement
Python
mit
skyfielders/python-skyfield,skyfielders/python-skyfield
3581c3c71bdf3ff84961df4b328f0bfc2adf0bc7
apps/provider/urls.py
apps/provider/urls.py
from __future__ import absolute_import from __future__ import unicode_literals from django.conf.urls import patterns, include, url from .views import * urlpatterns = patterns('', url(r'^pjson/push$', pjson_provider_push, name="pjson_provider_push"), url(r'^fhir/practitioner/push$', fhir_practitioner_push, ...
from __future__ import absolute_import from __future__ import unicode_literals from django.conf.urls import patterns, include, url from .views import * urlpatterns = patterns('', url(r'^pjson/push$', pjson_provider_push, name="pjson_provider_push"), url(r'^fhir/practitioner/push$', fhir_practitioner_push, ...
Add url for update vs. push for pract and org
Add url for update vs. push for pract and org
Python
apache-2.0
TransparentHealth/hhs_oauth_client,TransparentHealth/hhs_oauth_client,TransparentHealth/hhs_oauth_client,TransparentHealth/hhs_oauth_client
f994ab4a70a55706eeff133dd484dfd80a68e108
bin/isy_showevents.py
bin/isy_showevents.py
#!/usr/local/bin/python2.7 -u __author__ = "Peter Shipley" import os import keyring import ConfigParser from ISY.IsyEvent import ISYEvent def main() : config = ConfigParser.ConfigParser() config.read(os.path.expanduser('~/isy.cfg')) server = ISYEvent() # you can subscribe to multiple devices...
#!/usr/local/bin/python2.7 -u __author__ = "Peter Shipley" import os import ConfigParser from ISY.IsyEvent import ISYEvent def main() : config = ConfigParser.ConfigParser() config.read(os.path.expanduser('~/home.cfg')) server = ISYEvent() isy_addr = config.get('isy', 'addr') isy_user = c...
Remove keyring and change to basic cfg file handling
Remove keyring and change to basic cfg file handling
Python
bsd-2-clause
fxstein/ISYlib-python
ff9f64da2d43591cacfbec1a147fda4b82539c1d
serial_reader.py
serial_reader.py
#!/usr/bin/env python from argparse import ArgumentParser import serial def run(device, baud): with serial.Serial(device, baud, timeout=0.1) as ser: while True: line = ser.readline() if line: print line if __name__ == '__main__': parser = ArgumentParser() p...
#!/usr/bin/env python from argparse import ArgumentParser import sys import serial def run(device, baud): with serial.Serial(device, baud, timeout=0.1) as ser: while True: line = ser.readline() if line: sys.stdout.write(line) if __name__ == '__main__': parser =...
Use sys.stdout.write to get rid of extra newlines
Use sys.stdout.write to get rid of extra newlines
Python
unlicense
recursify/serial-debug-tool
8ffd26f4fddb0c367e61a46af6427eab6c244ea8
south/signals.py
south/signals.py
""" South-specific signals """ from django.dispatch import Signal # Sent at the start of the migration of an app pre_migrate = Signal(providing_args=["app"]) # Sent after each successful migration of an app post_migrate = Signal(providing_args=["app"]) # Sent after each run of a particular migration in a direction ...
""" South-specific signals """ from django.dispatch import Signal from django.conf import settings # Sent at the start of the migration of an app pre_migrate = Signal(providing_args=["app"]) # Sent after each successful migration of an app post_migrate = Signal(providing_args=["app"]) # Sent after each run of a par...
Add a compatibility hook to deal with creating django.contrib.auth permissions on migrated models.
Add a compatibility hook to deal with creating django.contrib.auth permissions on migrated models.
Python
apache-2.0
theatlantic/django-south,theatlantic/django-south
46a568690a9a284ddc350519a15e092e1211d073
reviewboard/site/urlresolvers.py
reviewboard/site/urlresolvers.py
from __future__ import unicode_literals from django.core.urlresolvers import NoReverseMatch, reverse def local_site_reverse(viewname, request=None, local_site_name=None, args=None, kwargs=None, *func_args, **func_kwargs): """Reverses a URL name, returning a working URL. This works muc...
from __future__ import unicode_literals from django.core.urlresolvers import NoReverseMatch, reverse def local_site_reverse(viewname, request=None, local_site_name=None, local_site=None, args=None, kwargs=None, *func_args, **func_kwargs): """Reverses a URL name, retu...
Allow local_site_reverse to take an actual LocalSite.
Allow local_site_reverse to take an actual LocalSite. local_site_reverse was able to take a LocalSite's name, or a request object, but if you actually had a LocalSite (or None), you'd have to write your own conditional to extract the name and pass it. Now, local_site_reverse can take a LocalSite. This saves a databas...
Python
mit
custode/reviewboard,custode/reviewboard,bkochendorfer/reviewboard,custode/reviewboard,brennie/reviewboard,reviewboard/reviewboard,KnowNo/reviewboard,sgallagher/reviewboard,custode/reviewboard,sgallagher/reviewboard,brennie/reviewboard,davidt/reviewboard,chipx86/reviewboard,KnowNo/reviewboard,chipx86/reviewboard,KnowNo/...
c488252462a2cb860111a4826f01883e7c16b3aa
numpy/distutils/setup.py
numpy/distutils/setup.py
#!/usr/bin/env python def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('distutils',parent_package,top_path) config.add_subpackage('command') config.add_subpackage('fcompiler') config.add_data_dir('tests') config.add_d...
#!/usr/bin/env python def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('distutils',parent_package,top_path) config.add_subpackage('command') config.add_subpackage('fcompiler') config.add_data_dir('tests') config.add_d...
Make the gfortran/vs2003 hack source file known to distutils.
Make the gfortran/vs2003 hack source file known to distutils. git-svn-id: 77a43f9646713b91fea7788fad5dfbf67e151ece@6650 94b884b6-d6fd-0310-90d3-974f1d3f35e1
Python
bsd-3-clause
chadnetzer/numpy-gaurdro,Ademan/NumPy-GSoC,Ademan/NumPy-GSoC,teoliphant/numpy-refactor,illume/numpy3k,Ademan/NumPy-GSoC,teoliphant/numpy-refactor,chadnetzer/numpy-gaurdro,Ademan/NumPy-GSoC,illume/numpy3k,jasonmccampbell/numpy-refactor-sprint,efiring/numpy-work,efiring/numpy-work,chadnetzer/numpy-gaurdro,efiring/numpy-w...
a7f7d8ff9f8279ec2c1f3981b1507001f1f94394
test/completion/docstring.py
test/completion/docstring.py
""" Test docstrings in functions and classes, which are used to infer types """ def f(a, b): """ asdfasdf :param a: blablabla :type a: str """ #? str() a #? b def g(a, b): """ asdfasdf Arguments: a (str): blablabla """ #? str() a #? b
""" Test docstrings in functions and classes, which are used to infer types """ def f(a, b): """ asdfasdf :param a: blablabla :type a: str """ #? str() a #? b def g(a, b): """ asdfasdf Arguments: a (str): blablabla """ #? str() a #? b def e(a, b):...
Add tests for epydoc formated dosctring
Add tests for epydoc formated dosctring
Python
mit
mfussenegger/jedi,flurischt/jedi,dwillmer/jedi,tjwei/jedi,WoLpH/jedi,jonashaag/jedi,mfussenegger/jedi,flurischt/jedi,jonashaag/jedi,tjwei/jedi,dwillmer/jedi,WoLpH/jedi
92d5991a37c3f269e9a7e59ab5edd90b45699930
test/style_test.py
test/style_test.py
import glob import os import pep8 class TestCodeFormat: def test_pep8(self): def match(*p): s = list(p) + ['*.py'] return glob.glob(os.path.join(*s)) pep8style = pep8.StyleGuide(config_file='setup.cfg') result = pep8style.check_files( match('examples') +...
import glob import os import pep8 class TestCodeFormat: def test_pep8(self): def match(*p): s = list(p) + ['*.py'] return glob.glob(os.path.join(*s)) pep8style = pep8.StyleGuide(config_file='setup.cfg') result = pep8style.check_files( match('examples') +...
Include scripts in style check.
Include scripts in style check.
Python
mit
EmbodiedCognition/pagoda,EmbodiedCognition/pagoda
cfd710e0035c885fab926690d7ea450f3f9c3845
setup.py
setup.py
from distutils.core import setup import os, glob, string, shutil # Packages packages = ['neuroimaging', 'neuroimaging.statistics', 'neuroimaging.image', 'neuroimaging.reference', 'neuroimaging.data', 'neuroimaging.image.formats', 'neuroimaging.image.formats.analyze', 'neuroimaging.fmri', 'neuroimaging.fmri.fmristat',...
import os, glob, string, shutil from distutils.core import setup # Packages packages = ['neuroimaging', 'neuroimaging.statistics', 'neuroimaging.image', 'neuroimaging.reference', 'neuroimaging.data', 'neuroimaging.image.formats', 'neuroimaging.image.formats.analyze', 'neuroimaging.fmri', 'neuroimaging.fmri.fmristat',...
Test edit - to check svn email hook
Test edit - to check svn email hook
Python
bsd-3-clause
matthew-brett/draft-statsmodels,matthew-brett/draft-statsmodels
5958f80d456a43654c5013d38569554940e754f4
tests/dojo_test.py
tests/dojo_test.py
import unittest from src.dojo import Dojo class TestCreateRoom (unittest.TestCase): def setUp(self): self.dojo = Dojo() self.test_office = self.dojo.create_room("office", "test") self.test_living_space = self.dojo.create_room("living_space", "test living space") def test_create_room_...
import unittest from src.dojo import Dojo class TestCreateRoom (unittest.TestCase): def setUp(self): self.dojo = Dojo() self.test_office = self.dojo.create_room("office", "test") self.test_living_space = self.dojo.create_room("living_space", "test living space") def test_create_room_...
Change test for multiple rooms to use test set-up
Change test for multiple rooms to use test set-up
Python
mit
EdwinKato/Space-Allocator,EdwinKato/Space-Allocator
67a12d44699e4bb8e3b6895ab10c9bb2477ed7fc
tests/fd_io.py
tests/fd_io.py
from filedes.test.base import BaseFDTestCase from filedes import FD import os import errno class TestFDIO(BaseFDTestCase): def testReadWrite(self): r, w = os.pipe() self.assertEquals(FD(w).write("OK"), 2) self.assertEquals(FD(r).read(2), "OK") FD(r).close() FD(w).close() ...
from filedes.test.base import BaseFDTestCase from filedes import FD import os import errno class TestFDIO(BaseFDTestCase): def testReadWrite(self): r, w = os.pipe() self.assertEquals(FD(w).write("OK"), 2) self.assertEquals(FD(r).read(2), "OK") FD(r).close() FD(w).close() ...
Check for EBADF in write-to-closed fd test case
Check for EBADF in write-to-closed fd test case
Python
isc
fmoo/python-filedes,fmoo/python-filedes
912b8a90472fc39f7c5d3b8e1e44b57aa88c0b02
setup.py
setup.py
#!/usr/bin/env python from distutils.core import setup setup(name='Numspell', version='0.9', description='A Python module for spelling numbers', author='Alexei Sholik', author_email='alcosholik@gmail.com', url='https://github.com/alco/numspell', license="MIT", packages=['nums...
#!/usr/bin/env python from distutils.core import setup setup(name='Numspell', version='0.9', description='A Python module for spelling numbers', author='Alexei Sholik', author_email='alcosholik@gmail.com', url='https://github.com/alco/numspell', license="MIT", packages=['nums...
Add more idiomatic (and also portable) way to install `spellnum` script
Add more idiomatic (and also portable) way to install `spellnum` script
Python
mit
alco/numspell,alco/numspell
5004b500284ec1d0f709b3069867757770601c44
mla_game/apps/transcript/management/commands/recalculate_phrase_game_mappings.py
mla_game/apps/transcript/management/commands/recalculate_phrase_game_mappings.py
from django.core.management.base import BaseCommand from django.conf import settings from ...models import TranscriptPhrase from ...tasks import assign_current_game phrase_positive_limit = settings.TRANSCRIPT_PHRASE_POSITIVE_CONFIDENCE_LIMIT phrase_negative_limit = settings.TRANSCRIPT_PHRASE_NEGATIVE_CONFIDENCE_LIMIT...
from django.core.management.base import BaseCommand from django.conf import settings from ...models import TranscriptPhraseVote from ...tasks import assign_current_game phrase_positive_limit = settings.TRANSCRIPT_PHRASE_POSITIVE_CONFIDENCE_LIMIT phrase_negative_limit = settings.TRANSCRIPT_PHRASE_NEGATIVE_CONFIDENCE_L...
Update only phrases with user input
Update only phrases with user input
Python
mit
WGBH/FixIt,WGBH/FixIt,WGBH/FixIt
05b5a4390c7109bb8c0778c547883c41272769fb
examples/oauth.py
examples/oauth.py
import tweepy # == OAuth Authentication == # # This mode of authentication is the new preferred way # of authenticating with Twitter. # The consumer keys can be found on your application's Details # page located at https://dev.twitter.com/apps (under "OAuth settings") consumer_key="" consumer_secret="" # The access ...
import tweepy # == OAuth Authentication == # # This mode of authentication is the new preferred way # of authenticating with Twitter. # The consumer keys can be found on your application's Details # page located at https://dev.twitter.com/apps (under "OAuth settings") consumer_key="" consumer_secret="" # The access ...
Change to make sure tweepy use SSL
Change to make sure tweepy use SSL I had some problems using Tweepy and I realized it was because it didn't always use SSL. So I propose to add a line to make sure the connexion we use is secure.
Python
mit
vishnugonela/tweepy,iamjakob/tweepy,srimanthd/tweepy,sa8/tweepy,awangga/tweepy,zhenv5/tweepy,kcompher/tweepy,damchilly/tweepy,edsu/tweepy,cogniteev/tweepy,yared-bezum/tweepy,truekonrads/tweepy,tweepy/tweepy,Choko256/tweepy,elijah513/tweepy,tsablic/tweepy,hackebrot/tweepy,rudraksh125/tweepy,atomicjets/tweepy,IsaacHaze/t...
1d8f7d4a57b145fa3f8cce12a55b02eb0a754581
crypto/envelope.py
crypto/envelope.py
""" Sealed envelope example from Princeton course 'Intro to Crypto and Cryptocurrencies' https://www.youtube.com/watch?v=fOMVZXLjKYo """ import hashlib def commit(key, msg): m = hashlib.sha256() m.update(key) m.update(msg) return { "hash": m.hexdigest(), "key": key } def verify(co...
""" Sealed envelope example from Princeton course 'Intro to Crypto and Cryptocurrencies' https://www.youtube.com/watch?v=fOMVZXLjKYo """ import hashlib def commit(key, msg): m = hashlib.sha256() m.update(key) m.update(msg) return { "hash": m.hexdigest(), "key": key } def verify(co...
Make the key 'more secure'
Make the key 'more secure'
Python
mit
b-ritter/python-notes,b-ritter/python-notes