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
60838f03a516859bee97c8133bb9e11e8fc61c39
perf_insights/perf_insights/local_file_trace_handle.py
perf_insights/perf_insights/local_file_trace_handle.py
# Copyright (c) 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import gzip import os import shutil import tempfile from perf_insights import trace_handle class LocalFileTraceHandle(trace_handle.TraceHandle): def ...
# Copyright (c) 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from perf_insights import trace_handle class LocalFileTraceHandle(trace_handle.TraceHandle): def __init__(self, run_info, filename): super(LocalFi...
Revert gunzip in python from performance insights mapping
Revert gunzip in python from performance insights mapping Reverts ade2e1a90cc69169b8c613606b44ac7503b64503. This appears to be causing significant contention on at least z840 machines. Only ~12 d8 instances run at any given time despite -j48. As noted in https://github.com/catapult-project/catapult/issues/1193 the sp...
Python
bsd-3-clause
SummerLW/Perf-Insight-Report,catapult-project/catapult,catapult-project/catapult,catapult-project/catapult-csm,0x90sled/catapult,catapult-project/catapult,sahiljain/catapult,0x90sled/catapult,catapult-project/catapult-csm,catapult-project/catapult-csm,benschmaus/catapult,SummerLW/Perf-Insight-Report,benschmaus/catapult...
8f011917dc991165e2ae10b492bd3713a30f4126
axes/__init__.py
axes/__init__.py
__version__ = '2.0.0' def get_version(): return __version__
__version__ = '2.0.0' default_app_config = "axes.apps.AppConfig" def get_version(): return __version__
Add `default_app_config` so you can just use `axes` in `INSTALLED_APPS`
Add `default_app_config` so you can just use `axes` in `INSTALLED_APPS`
Python
mit
jazzband/django-axes,svenhertle/django-axes,django-pci/django-axes
bb4701103101c698f6afdc05bce02a186d228d89
celery/views.py
celery/views.py
"""celery.views""" from django.http import HttpResponse from celery.task import is_done, delay_task from celery.result import AsyncResult from carrot.serialization import serialize as JSON_dump def is_task_done(request, task_id): """Returns task execute status in JSON format.""" response_data = {"task": {"id"...
"""celery.views""" from django.http import HttpResponse from celery.task import is_done, delay_task from celery.result import AsyncResult from carrot.serialization import serialize as JSON_dump def is_task_done(request, task_id): """Returns task execute status in JSON format.""" response_data = {"task": {"id"...
Send back a mimetype for JSON response.
Send back a mimetype for JSON response.
Python
bsd-3-clause
frac/celery,ask/celery,frac/celery,mitsuhiko/celery,cbrepo/celery,cbrepo/celery,mitsuhiko/celery,ask/celery,WoLpH/celery,WoLpH/celery
2f9ba8bb4c6c25777ddce19be94fdb0675174810
konstrukteur/HtmlParser.py
konstrukteur/HtmlParser.py
# # Konstrukteur - Static website generator # Copyright 2013 Sebastian Fastner # __all__ = ["parse"] from jasy.env.State import session from jasy.core import Console from bs4 import BeautifulSoup def parse(filename): """ HTML parser class for Konstrukteur """ page = {} parsedContent = BeautifulSoup(open(filenam...
# # Konstrukteur - Static website generator # Copyright 2013 Sebastian Fastner # __all__ = ["parse"] from jasy.env.State import session from jasy.core import Console from bs4 import BeautifulSoup def parse(filename): """ HTML parser class for Konstrukteur """ page = {} parsedContent = BeautifulSoup(open(filenam...
Fix if no paragraph is in page
Fix if no paragraph is in page
Python
mit
fastner/konstrukteur,fastner/konstrukteur,fastner/konstrukteur
db45127fa93b495337df3e39a1c4622fce297ada
skimage/io/tests/test_io.py
skimage/io/tests/test_io.py
import os from numpy.testing import assert_array_equal, raises, run_module_suite import numpy as np import skimage.io as io from skimage.io._plugins.plugin import plugin_store 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)...
import os from numpy.testing import assert_array_equal, raises, run_module_suite import numpy as np import skimage.io as io from skimage.io._plugins.plugin import plugin_store 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)...
Fix test so it doesn't have side-effects
Fix test so it doesn't have side-effects
Python
bsd-3-clause
chintak/scikit-image,ajaybhat/scikit-image,robintw/scikit-image,bsipocz/scikit-image,michaelpacer/scikit-image,Britefury/scikit-image,juliusbierk/scikit-image,ofgulban/scikit-image,paalge/scikit-image,emon10005/scikit-image,paalge/scikit-image,blink1073/scikit-image,michaelaye/scikit-image,ClinicalGraphics/scikit-image...
4844f948cbac10b729b739b8c516943290bcbb70
cle/backends/pe/regions.py
cle/backends/pe/regions.py
from ..region import Section class PESection(Section): """ Represents a section for the PE format. """ def __init__(self, pe_section, remap_offset=0): super().__init__( pe_section.Name.decode(), pe_section.Misc_PhysicalAddress, pe_section.VirtualAddress + rem...
from ..region import Section class PESection(Section): """ Represents a section for the PE format. """ def __init__(self, pe_section, remap_offset=0): super().__init__( pe_section.Name.decode(), pe_section.PointerToRawData, pe_section.VirtualAddress + remap_o...
Fix PE backend file offset of section
Fix PE backend file offset of section
Python
bsd-2-clause
angr/cle
7261c5f96d52dba7f8a12716994e753910ceda64
tests/context_managers.py
tests/context_managers.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from contextlib import contextmanager from io import BytesIO import sys import mock_modules import yv_suggest.shared as yvs @contextmanager def redirect_stdout(): """temporarily redirect stdout to new output stream""" original_stdout = sys.stdout out = BytesI...
#!/usr/bin/env python # -*- coding: utf-8 -*- from contextlib import contextmanager from io import BytesIO import sys import mock_modules import yv_suggest.shared as yvs @contextmanager def redirect_stdout(): """temporarily redirect stdout to new output stream""" original_stdout = sys.stdout out = BytesI...
Add finally blocks to ensure tests always clean up
Add finally blocks to ensure tests always clean up
Python
mit
caleb531/youversion-suggest,caleb531/youversion-suggest
a7bb3eebdfa71ad87301fb84d54fd6de0249ec29
bin/initialize_data.py
bin/initialize_data.py
from twitterbot.twitter_bot import get_redis def add_data(redis, key, data): for item in data: redis.sadd(key, item.encode('utf-8')) redis = get_redis('127.0.0.1:6379') redis.delete('adjectives', 'sentences') adjectives = ('smart', 'helpful', 'kind', 'hard-working', 'meticulous', 'diligent') add_data(r...
from twitterbot.twitter_bot import get_redis def add_data(redis, key, data): for item in data: redis.sadd(key, item.encode('utf-8')) redis = get_redis() redis.delete('adjectives', 'sentences') adjectives = ('smart', 'helpful', 'kind', 'hard-working', 'meticulous', 'diligent') add_data(redis, 'adjective...
Use redis configuration when initializing data
Use redis configuration when initializing data
Python
mit
jessamynsmith/twitterbot,jessamynsmith/heartbot,jessamynsmith/twitterbot,jessamynsmith/heartbot
9f484e6eb4fcf37f5515d62eb80be6a0f8d5a097
swteams/views.py
swteams/views.py
import iris.views from teams.models import Team def activity(request, slug, *args, **kw): template_name = 'teams/activity.html' team = get_object_or_404(Team, slug=slug) template_context = { 'group': team, } return render_to_response(template_name, template_context, RequestContext(request)...
from django.shortcuts import get_object_or_404, render_to_response from django.template.context import RequestContext import iris.views from teams.models import Team def activity(request, slug, *args, **kw): template_name = 'teams/activity.html' team = get_object_or_404(Team, slug=slug) template_context ...
Fix team activity history view (was missing imports)
Fix team activity history view (was missing imports)
Python
apache-2.0
snswa/swsites,snswa/swsites,snswa/swsites
becc6b8913e85e55d3dcb3a9dcd3287718833990
tests/prov_test_common.py
tests/prov_test_common.py
import platform import re import subprocess from time import sleep def verify_provisioned(akt_info, conf): # Verify that device HAS provisioned. stdout, stderr, retcode = run_subprocess([str(akt_info), '--config', str(conf), '--wait-until-provisioned']) machine = platform.node() if (b'Device ID: ' not...
import platform import re import subprocess def verify_provisioned(akt_info, conf): # Verify that device HAS provisioned. stdout, stderr, retcode = run_subprocess([str(akt_info), '--config', str(conf), '--wait-until-provisioned']) machine = platform.node() if (b'Device ID: ' not in stdout or ...
Fix a python undefined name in test scripts
Fix a python undefined name in test scripts Signed-off-by: Laurent Bonnans <0909bc0a3d1b0c91d8e00372b9633e8e9ea958de@here.com>
Python
mpl-2.0
advancedtelematic/sota_client_cpp,advancedtelematic/aktualizr,advancedtelematic/aktualizr,advancedtelematic/sota_client_cpp,advancedtelematic/aktualizr,advancedtelematic/aktualizr
01a71f10f94d9e7b7c90d19540df8015455ae2ad
commands/say.py
commands/say.py
from CommandTemplate import CommandTemplate class Command(CommandTemplate): triggers = ['say', 'do'] helptext = "Makes the bot say the provided text in the provided channel (format 'say [channel/user] text')" adminOnly = True showInCommandList = False def execute(self, bot, user, target, triggerInMsg, msg, msgW...
from CommandTemplate import CommandTemplate class Command(CommandTemplate): triggers = ['say', 'do', 'notice'] helptext = "Makes the bot say the provided text in the provided channel (format 'say [channel/user] text')" adminOnly = True showInCommandList = False def execute(self, bot, user, target, triggerInMsg,...
Move to sendMessage command for message sending. Also add 'notice' trigger, because why not
Move to sendMessage command for message sending. Also add 'notice' trigger, because why not
Python
mit
Didero/DideRobot
0472c1cabdfdf0f8a193552dac3370ae93bbdaed
scripts/get_top_hashtags.py
scripts/get_top_hashtags.py
import json import sys from collections import Counter f = open(sys.argv[1], 'r') topk = int(sys.argv[2]) if len(sys.argv) > 2 and sys.argv[2].isdigit() else 10 hashtags = [] for line in f: if line.startswith('{'): hashtags.extend(json.loads(line)['hashtags']) hashtagCounter = Counter([hashtag.lower() for ...
import json import sys from collections import Counter f = open(sys.argv[1], 'r') topk = int(sys.argv[2]) if len(sys.argv) > 2 and sys.argv[2].isdigit() else 10 hashtagCounter = Counter([hashtag.lower() for line in f if line.startswith('{') for hashtag in json.loads(line)['hashtags'] ]) for (hashtag, count) in hashta...
Use a more compact functional style for instantiating hashtagCounter
Use a more compact functional style for instantiating hashtagCounter
Python
mpl-2.0
aDataAlchemist/election-tweets
cd300ebffd8974b5c9fe98e8368f26dc029ae41b
tests/schemas.py
tests/schemas.py
from marshmallow import Schema, fields class PetSchema(Schema): id = fields.Int(dump_only=True) name = fields.Str() class SampleSchema(Schema): runs = fields.Nested('RunSchema', many=True, exclude=('sample',)) count = fields.Int() class RunSchema(Schema): sample = fields.Nested(SampleSchema, ...
from marshmallow import Schema, fields class PetSchema(Schema): id = fields.Int(dump_only=True) name = fields.Str() class SampleSchema(Schema): runs = fields.Nested('RunSchema', many=True, exclude=('sample',)) count = fields.Int() class RunSchema(Schema): sample = fields.Nested(SampleSchema, ...
Add schema with Dict field
Add schema with Dict field
Python
mit
marshmallow-code/smore,marshmallow-code/apispec
7064916ddd2913856b9493670ca2d525fd412b06
crmapp/urls.py
crmapp/urls.py
from django.conf.urls import patterns, include, url from django.contrib import admin admin.autodiscover() from marketing.views import HomePage urlpatterns = patterns('', # Marketing pages url(r'^$', HomePage.as_view(), name="home"), # Subscriber related URLs url(r'^signup/$', 'crmapp.subscr...
from django.conf.urls import patterns, include, url from django.contrib import admin admin.autodiscover() from marketing.views import HomePage urlpatterns = patterns('', # Marketing pages url(r'^$', HomePage.as_view(), name="home"), # Subscriber related URLs url(r'^signup/$', 'crmapp.subscr...
Create the Login Page > Create the Login & Logout URLs
Create the Login Page > Create the Login & Logout URLs
Python
mit
deenaariff/Django,tabdon/crmeasyapp,tabdon/crmeasyapp
8a0c17f39fd63a90b24ed79bd5bde4d52622e41d
irc/message.py
irc/message.py
class Tag(object): """ An IRC message tag ircv3.net/specs/core/message-tags-3.2.html """ @staticmethod def parse(item): key, sep, value = item.partition('=') value = value.replace('\\:', ';') value = value.replace('\\s', ' ') value = value.replace('\\n', '\n') ...
from __future__ import print_function class Tag(object): """ An IRC message tag ircv3.net/specs/core/message-tags-3.2.html """ @staticmethod def parse(item): r""" >>> Tag.parse('x') == {'key': 'x', 'value': None} True >>> Tag.parse('x=yes') == {'key': 'x', 'value': ...
Add tests for tag parsing
Add tests for tag parsing
Python
mit
jaraco/irc
6e6bffc19873260696822bb3f4a821ce4ea6f4a3
consulrest/keyvalue.py
consulrest/keyvalue.py
import json import re import requests class KeyValue(object): def __init__(self, url): self._url = "%s/kv" % url def _get(self, key, recurse=None, keys=None): url = self._url + '/' + key if recurse is not None: url += '?recurse' if keys is not None: u...
import json import re import requests class KeyValue(object): def __init__(self, url): self._url = "%s/kv" % url def _get(self, key, recurse=None, keys=None): url = self._url + '/' + key params = dict() if recurse is not None: params['recurse'] = True if k...
Use params dictionary instead of appending to the end of URL string
Use params dictionary instead of appending to the end of URL string
Python
mit
vcoque/consul-ri
8dc265ac0c2bbea683d900f64c5080a23879c9da
spacy/tests/lang/da/test_exceptions.py
spacy/tests/lang/da/test_exceptions.py
# coding: utf-8 from __future__ import unicode_literals import pytest @pytest.mark.parametrize('text', ["ca.", "m.a.o.", "Jan.", "Dec."]) def test_da_tokenizer_handles_abbr(da_tokenizer, text): tokens = da_tokenizer(text) assert len(tokens) == 1 def test_da_tokenizer_handles_exc_in_text(da_tokenizer): te...
# coding: utf-8 from __future__ import unicode_literals import pytest @pytest.mark.parametrize('text', ["ca.", "m.a.o.", "Jan.", "Dec."]) def test_da_tokenizer_handles_abbr(da_tokenizer, text): tokens = da_tokenizer(text) assert len(tokens) == 1 def test_da_tokenizer_handles_exc_in_text(da_tokenizer): te...
Add test for tokenization of 'i.' for Danish.
Add test for tokenization of 'i.' for Danish.
Python
mit
explosion/spaCy,aikramer2/spaCy,recognai/spaCy,recognai/spaCy,spacy-io/spaCy,honnibal/spaCy,spacy-io/spaCy,spacy-io/spaCy,recognai/spaCy,honnibal/spaCy,recognai/spaCy,spacy-io/spaCy,spacy-io/spaCy,spacy-io/spaCy,explosion/spaCy,explosion/spaCy,honnibal/spaCy,explosion/spaCy,aikramer2/spaCy,explosion/spaCy,aikramer2/spa...
4687e306797e96c85165fabea3ad1fc005469aa1
tools/telemetry/telemetry/internal/platform/profiler/android_screen_recorder_profiler.py
tools/telemetry/telemetry/internal/platform/profiler/android_screen_recorder_profiler.py
# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import os import subprocess from telemetry.internal.platform import profiler from telemetry.internal import util from telemetry.internal.backends.chrome imp...
# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import os import subprocess from telemetry.core import util from telemetry.internal.platform import profiler from telemetry.internal.backends.chrome import ...
Fix an import path in the Android screen recorder
telemetry: Fix an import path in the Android screen recorder Review URL: https://codereview.chromium.org/1301613004 Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#343960}
Python
bsd-3-clause
ltilve/ChromiumGStreamerBackend,ltilve/ChromiumGStreamerBackend,CapOM/ChromiumGStreamerBackend,ltilve/ChromiumGStreamerBackend,ltilve/ChromiumGStreamerBackend,CapOM/ChromiumGStreamerBackend,CapOM/ChromiumGStreamerBackend,CapOM/ChromiumGStreamerBackend,CapOM/ChromiumGStreamerBackend,ltilve/ChromiumGStreamerBackend,CapOM...
7e19c3058615f4599ed7339e2bd157b72cd51018
test_dimuon.py
test_dimuon.py
from dimuon import * from nose.tools import * from math import pi class DummyParticle: def __init__(self, q): self.q = q def test_no_particles(): particles = [] pairs = find_pairs(particles) assert len(pairs) == 0 def test_one_particle(): pos = DummyParticle(+1) particles = [pos] ...
from dimuon import * from nose.tools import * from math import pi class DummyParticle: def __init__(self, q): self.q = q def test_no_particles(): particles = [] pairs = find_pairs(particles) assert len(pairs) == 0 def test_one_particle(): pos = DummyParticle(+1) particles = [pos] ...
Test pair mass for non-zero mass particles
Test pair mass for non-zero mass particles
Python
mit
benwaugh/dimuon
59fa966d43e4fd66669c3390464f60f323cf2865
tests/changes/api/serializer/models/test_command.py
tests/changes/api/serializer/models/test_command.py
from datetime import datetime from changes.api.serializer import serialize from changes.config import db from changes.models import Command from changes.testutils import TestCase class CommandSerializerTest(TestCase): def test_simple(self): project = self.create_project() build = self.create_buil...
from datetime import datetime from changes.api.serializer import serialize from changes.config import db from changes.models import Command from changes.testutils import TestCase class CommandSerializerTest(TestCase): def test_simple(self): project = self.create_project() build = self.create_buil...
Add tests for env serialization
Add tests for env serialization
Python
apache-2.0
dropbox/changes,bowlofstew/changes,wfxiang08/changes,bowlofstew/changes,bowlofstew/changes,dropbox/changes,wfxiang08/changes,wfxiang08/changes,dropbox/changes,bowlofstew/changes,dropbox/changes,wfxiang08/changes
7ac3e48d1934e7a749590d875a3f5e4423fa6c72
linked_list.py
linked_list.py
#!/usr/bin/env python class SinglyLinked(object): def __init__(self): pass def insert(self, val): # insert val at beginning of list pass def pop(self): # pops first value from list and returns it pass def size(self): # returns length of list p...
#!/usr/bin/env python class Node(object): def __init__(self, data, nextNode=None): self.data = data self.nextNode = nextNode class LinkedList(object): def __init__(self, firstNode=None): self.firstNode = firstNode def insert(self, newNode): # insert newNode at beginning ...
Create Node class; construct insert method
Create Node class; construct insert method
Python
mit
jwarren116/data-structures
51931a0ba263cd16f14780df664c093764d0bad7
tests/integrations/test_urls.py
tests/integrations/test_urls.py
import pytest pytestmark = pytest.mark.django_db def test_admin_interface(client): response = client.get('/admin/login/') assert response.status_code == 200
import pytest pytestmark = pytest.mark.django_db def test_admin_interface(client): public_urls = [ '/admin/login/', '/', '/about/', '/privacy/', ] for url in public_urls: response = client.get('/admin/login/') assert response.status_code == 200
Add test to check for public urls
Add test to check for public urls
Python
mit
fossevents/fossevents.in,fossevents/fossevents.in,vipul-sharma20/fossevents.in,vipul-sharma20/fossevents.in,vipul-sharma20/fossevents.in,aniketmaithani/fossevents.in,fossevents/fossevents.in,aniketmaithani/fossevents.in,vipul-sharma20/fossevents.in,aniketmaithani/fossevents.in,fossevents/fossevents.in,aniketmaithani/fo...
6cfb0ca69b43784d495920865f0a250f7d16ff84
trump/extensions/loader.py
trump/extensions/loader.py
from imp import find_module, load_module import os class SourceExtension(object): def __init__(self, mod): self.initialized = False self.mod = mod self.renew = mod.renew self.Source = mod.Source def __call__(self, _ses, **kwargs): if not self.initialized or self.renew: ...
from imp import find_module, load_module import os class SourceExtension(object): def __init__(self, mod): self.initialized = False self.mod = mod self.renew = mod.renew self.Source = mod.Source def __call__(self, _ses, **kwargs): if not self.initialized or self.renew: ...
Use full path to find mods
Use full path to find mods
Python
bsd-3-clause
jnmclarty/trump,Equitable/trump
758553edd8da7adbfeb2d291c83442dce77c748c
spotify/__init__.py
spotify/__init__.py
from __future__ import unicode_literals import os from cffi import FFI __version__ = '2.0.0a1' header_file = os.path.join(os.path.dirname(__file__), 'api.processed.h') header = open(header_file).read() header += '#define SPOTIFY_API_VERSION ...\n' ffi = FFI() ffi.cdef(header) lib = ffi.verify('#include "libspoti...
from __future__ import unicode_literals import os from cffi import FFI __version__ = '2.0.0a1' header_file = os.path.join(os.path.dirname(__file__), 'api.processed.h') header = open(header_file).read() header += '#define SPOTIFY_API_VERSION ...\n' ffi = FFI() ffi.cdef(header) lib = ffi.verify('#include "libspoti...
Use a class decorator to add enum values to classes
Use a class decorator to add enum values to classes
Python
apache-2.0
jodal/pyspotify,kotamat/pyspotify,felix1m/pyspotify,jodal/pyspotify,kotamat/pyspotify,jodal/pyspotify,mopidy/pyspotify,felix1m/pyspotify,kotamat/pyspotify,mopidy/pyspotify,felix1m/pyspotify
99e0e90552c16067cfd41c9e89464311494c5a85
kitsune/sumo/management/commands/nunjucks_precompile.py
kitsune/sumo/management/commands/nunjucks_precompile.py
import os import subprocess from django.conf import settings from django.core.management.base import BaseCommand ROOT = os.path.realpath( os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..')) path = lambda *a: os.path.join(ROOT, *a) class Command(BaseCommand): help = 'Precompiles nunjuck te...
import os import subprocess from django.conf import settings from django.core.management.base import BaseCommand ROOT = os.path.realpath( os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..')) path = lambda *a: os.path.join(ROOT, *a) class Command(BaseCommand): help = 'Precompiles nunjuck te...
Fix nunjucks command so travis is happy
Fix nunjucks command so travis is happy
Python
bsd-3-clause
rlr/kitsune,orvi2014/kitsune,silentbob73/kitsune,H1ghT0p/kitsune,MziRintu/kitsune,feer56/Kitsune1,philipp-sumo/kitsune,safwanrahman/kitsune,turtleloveshoes/kitsune,H1ghT0p/kitsune,orvi2014/kitsune,safwanrahman/linuxdesh,safwanrahman/kitsune,Osmose/kitsune,Osmose/kitsune,NewPresident1/kitsune,H1ghT0p/kitsune,MziRintu/ki...
c82574aec4ee413198f54473cb47508a6b271f9a
dmf_device_ui/client.py
dmf_device_ui/client.py
import sys import zmq import time def main(): port = 5000 if len(sys.argv) > 1: port = sys.argv[1] int(port) bind_addr = "tcp://localhost:%s" % port context = zmq.Context() socket = context.socket(zmq.SUB) socket.connect(bind_addr) socket.setsockopt(zmq.SUBSCRIBE,'') print "Listening for events ...
import sys import zmq import time def main(): port = 5000 if len(sys.argv) > 1: port = sys.argv[1] int(port) bind_addr = "tcp://localhost:%s" % port context = zmq.Context() socket = context.socket(zmq.SUB) socket.connect(bind_addr) socket.setsockopt(zmq.SUBSCRIBE,'') ...
Replace spaces with tabs, quit on <Ctrl+C>
Replace spaces with tabs, quit on <Ctrl+C>
Python
lgpl-2.1
wheeler-microfluidics/dmf-device-ui
dad970e9db2d3985a4995982d91a995898c8781b
virtool/handlers/updates.py
virtool/handlers/updates.py
import virtool.app import virtool.updates from virtool.handlers.utils import json_response async def get(req): db = req.app["db"] settings = req.app["settings"] repo = settings.get("software_repo") server_version = virtool.app.find_server_version() await virtool.updates.get_releases(repo, server...
import virtool.app import virtool.updates from virtool.handlers.utils import json_response async def get(req): # db = req.app["db"] settings = req.app["settings"] repo = settings.get("software_repo") server_version = virtool.app.find_server_version() releases = await virtool.updates.get_releases...
Make retrieval of releases from GitHub functional
Make retrieval of releases from GitHub functional
Python
mit
igboyes/virtool,virtool/virtool,virtool/virtool,igboyes/virtool
a978a7ed7f40ac7a77aa31ec89a3bb8ae58abb61
ecommerce/courses/migrations/0006_auto_20171204_1036.py
ecommerce/courses/migrations/0006_auto_20171204_1036.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.7 on 2017-12-04 10:36 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): def add_created_modified_date(apps, schema_editor): Course = apps.get_model('courses', 'Course') courses...
# -*- coding: utf-8 -*- # Generated by Django 1.10.7 on 2017-12-04 10:36 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): def add_created_modified_date(apps, schema_editor): Course = apps.get_model('courses', 'Course') Histori...
Fix migration issue Fixed 'Course' object has no attribute 'history' issue in the migration
Fix migration issue Fixed 'Course' object has no attribute 'history' issue in the migration
Python
agpl-3.0
edx/ecommerce,edx/ecommerce,eduNEXT/edunext-ecommerce,eduNEXT/edunext-ecommerce,eduNEXT/edunext-ecommerce,edx/ecommerce,edx/ecommerce,eduNEXT/edunext-ecommerce
434b3e94f461c995a5e2f421acca29897495f0a8
setup.py
setup.py
from distutils.core import setup setup( name = 'respite', version = '0.6.1', description = "Respite conforms Django to Representational State Transfer (REST)", author = "Johannes Gorset", author_email = "jgorset@gmail.com", url = "http://github.com/jgorset/respite", packages = ['respite'] )...
from distutils.core import setup setup( name = 'respite', version = '0.6.1', description = "Respite conforms Django to Representational State Transfer (REST)", author = "Johannes Gorset", author_email = "jgorset@gmail.com", url = "http://github.com/jgorset/respite", packages = ['respite', '...
Add 'lib' and 'serializers' to packages
Add 'lib' and 'serializers' to packages
Python
mit
jgorset/django-respite,jgorset/django-respite,jgorset/django-respite
41bba7238fcbe2624ccd294c8ac54f805a781603
setup.py
setup.py
from distutils.core import setup import py2exe setup( console=[{'script': 'check_forbidden.py', 'version': '1.3.0', }], options={'py2exe': {'bundle_files': 2}} ) ''' cd dropbox/codes/check_forbidden py -3.4 setup.py py2exe '''
''' cd dropbox/codes/check_forbidden py -3.4 setup.py py2exe Libraries used: import tkinter import tkinter.filedialog import csv import os import re from time import sleep import zipfile ''' from distutils.core import setup import py2exe setup( console=[{'author': 'Shun Sakurai', ...
Reduce the size of the dist folder
Reduce the size of the dist folder
Python
mit
ShunSakurai/check_forbidden,ShunSakurai/check_forbidden
5c1bf492a8308473aa9704823fa3200d08b7a730
win_unc/unc_directory.py
win_unc/unc_directory.py
class UncDirectory(object): def __init__(self, path, username=None, password=None): self.path = path self.username = username self.password = password def __eq__(self, other): try: return (self.get_normalized_path() == other.get_normalized_path() ...
class UncDirectory(object): def __init__(self, path, username=None, password=None): if hasattr(path, 'path') and hasattr(path, 'username') and hasattr(path, 'password'): self.path = path.path self.username = path.username self.password = path.password else: ...
Support cloning in UncDirectory constructor
Support cloning in UncDirectory constructor
Python
mit
nithinphilips/py_win_unc,CovenantEyes/py_win_unc
8f4bc11db358a1db227690149fe1780e600d6328
integration_tests/tests/test_startup.py
integration_tests/tests/test_startup.py
from system import auto_power_on, runlevel from tests.base import RestartPerSuite from utils import TestEvent @runlevel(1) class StartupTest(RestartPerSuite): def wait_for_lcl(self, lcl, message): ev = TestEvent() lcl.on_disable = ev.set self.power_on_obc() self.assertTr...
from system import auto_power_on, runlevel from tests.base import RestartPerSuite from utils import TestEvent @runlevel(1) class StartupTest(RestartPerSuite): def setup_lcl(self, lcl, message): ev = TestEvent() lcl.on_disable = ev.set return lambda : self.assertTrue(ev.wait_for_c...
Merge together all eps startup tests to reduce run time.
[integration_tests] Merge together all eps startup tests to reduce run time.
Python
agpl-3.0
PW-Sat2/PWSat2OBC,PW-Sat2/PWSat2OBC,PW-Sat2/PWSat2OBC,PW-Sat2/PWSat2OBC
b9379e3c8667d062ec6511ad07f2525ea0b2f5ef
tests/test_statepoint_sourcesep/test_statepoint_sourcesep.py
tests/test_statepoint_sourcesep/test_statepoint_sourcesep.py
#!/usr/bin/env python import sys sys.path.insert(0, '..') from testing_harness import * class SourcepointTestHarness(TestHarness): def _test_output_created(self): """Make sure statepoint.* and source* have been created.""" TestHarness._test_output_created(self) source = glob.glob(os.path....
#!/usr/bin/env python import sys sys.path.insert(0, '..') from testing_harness import * class SourcepointTestHarness(TestHarness): def _test_output_created(self): """Make sure statepoint.* and source* have been created.""" TestHarness._test_output_created(self) source = glob.glob(os.path....
Make test cleanup source file
Make test cleanup source file
Python
mit
amandalund/openmc,mit-crpg/openmc,shikhar413/openmc,walshjon/openmc,bhermanmit/openmc,mjlong/openmc,paulromano/openmc,samuelshaner/openmc,smharper/openmc,liangjg/openmc,paulromano/openmc,mit-crpg/openmc,shikhar413/openmc,wbinventor/openmc,walshjon/openmc,wbinventor/openmc,wbinventor/openmc,wbinventor/openmc,kellyrowlan...
a4f78af5b2973b044337dc430118fc270e527220
allauth/socialaccount/providers/keycloak/provider.py
allauth/socialaccount/providers/keycloak/provider.py
# -*- coding: utf-8 -*- from allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider class KeycloakAccount(ProviderAccount): def get_avatar_url(self): return self.account.extra_data.get('picture') def to_str(self): ...
# -*- coding: utf-8 -*- from allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider class KeycloakAccount(ProviderAccount): def get_avatar_url(self): return self.account.extra_data.get('picture') def to_str(self): ...
Use preferred_username claim for username
fix(keycloak): Use preferred_username claim for username As per the OpenID Connect spec the standard username claim is `preferred_username`. By default Keycloak confirms to OpenID Connect spec and provides a `preferred_username` claim, but no `username` claim in the profile scope. ref: https://openid.net/specs/openi...
Python
mit
pennersr/django-allauth,rsalmaso/django-allauth,pennersr/django-allauth,rsalmaso/django-allauth,rsalmaso/django-allauth,pennersr/django-allauth
2f039066530533b1a8ae82076ed745c1f2e03688
app-tasks/rf/src/rf/uploads/geotiff/create_images.py
app-tasks/rf/src/rf/uploads/geotiff/create_images.py
import os from rf.models import Image from rf.utils.io import Visibility from .io import get_geotiff_size_bytes, get_geotiff_resolution from .create_bands import create_geotiff_bands def create_geotiff_image(organizationId, tif_path, sourceuri, filename=None, visibility=Visibility.PRIVATE, ...
import os from rf.models import Image from rf.utils.io import Visibility from .io import get_geotiff_size_bytes, get_geotiff_resolution from .create_bands import create_geotiff_bands def create_geotiff_image(organizationId, tif_path, sourceuri, filename=None, visibility=Visibility.PRIVATE, ...
Add ability to define band create function for geotiff images
Add ability to define band create function for geotiff images This commit makes defining bands for custom geotiffs more flexible by allowing passing custom functions for defining bands for different datasources or other variables - subsequent commits for MODIS take advantage of this
Python
apache-2.0
raster-foundry/raster-foundry,aaronxsu/raster-foundry,azavea/raster-foundry,azavea/raster-foundry,aaronxsu/raster-foundry,aaronxsu/raster-foundry,azavea/raster-foundry,azavea/raster-foundry,azavea/raster-foundry,raster-foundry/raster-foundry,raster-foundry/raster-foundry,aaronxsu/raster-foundry
a76741e81b2c9b9b91f9ffefe08784051f083d8e
stock_traceability_operation/models/stock_production_lot.py
stock_traceability_operation/models/stock_production_lot.py
# -*- coding: utf-8 -*- # © 2015 Numérigraphe # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from openerp import api, models, exceptions from openerp.tools.safe_eval import safe_eval class StockProductionLot(models.Model): _inherit = "stock.production.lot" @api.multi def action_tra...
# -*- coding: utf-8 -*- # © 2015 Numérigraphe # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from openerp import api, models, exceptions from openerp.tools.safe_eval import safe_eval class StockProductionLot(models.Model): _inherit = "stock.production.lot" @api.multi def action_tra...
Fix a missing filter in lot traceability
Fix a missing filter in lot traceability When we search for lot traceability we first search for the corresponding stock moves. But whenever these moves contain extra quants, we need to filter the ones of the wrong lots.
Python
agpl-3.0
kmee/stock-logistics-warehouse,acsone/stock-logistics-warehouse,factorlibre/stock-logistics-warehouse,open-synergy/stock-logistics-warehouse
2acb5a2eb7ae0a0f8ea8423a7da5a7a8b9f07151
fore/mailer.py
fore/mailer.py
# Import smtplib for the actual sending function import smtplib from email.mime.text import MIMEText import apikeys def AlertMessage(message, subject='Glitch System Message', me=apikeys.system_email, you=apikeys.admin_email): msg = MIMEText(message) msg['Subject'] = subject msg['From'] = me msg['To'] = you # Se...
# Import smtplib for the actual sending function import smtplib from email.mime.text import MIMEText import apikeys def AlertMessage(message, subject='Glitch System Message', me=apikeys.system_email, you=apikeys.admin_email): msg = MIMEText(message) msg['Subject'] = subject msg['From'] = me msg['To'] = you # Se...
Move test message into function.
Move test message into function.
Python
artistic-2.0
Rosuav/appension,MikeiLL/appension,Rosuav/appension,MikeiLL/appension,Rosuav/appension,MikeiLL/appension,Rosuav/appension,MikeiLL/appension
52c04b66ca9474c8c7b33c8781a02e3573eb5676
main.py
main.py
import os, os.path import string import cherrypy class StringGenerator(object): @cherrypy.expose def index(self): return open('test-carte.html') if __name__ == '__main__': conf = { '/': { 'tools.sessions.on': True, 'tools.staticdir.root': os.path.abspath(os.getcwd...
import os, os.path import string import cherrypy class StringGenerator(object): @cherrypy.expose def index(self): return open('test-carte.html') if __name__ == '__main__': conf = { '/': { 'tools.sessions.on': True, 'tools.staticdir.root': os.path.abspath(os.getcwd...
Change server.socket_host to allow acces over the network
Change server.socket_host to allow acces over the network
Python
mit
guillaume-havard/proto-map,guillaume-havard/proto-map,guillaume-havard/proto-map
4b630e8223f178ad25eef0e2ecf31f838445d2a0
nose2/tests/functional/test_coverage.py
nose2/tests/functional/test_coverage.py
import os.path from nose2.tests._common import FunctionalTestCase class TestCoverage(FunctionalTestCase): def test_run(self): proc = self.runIn( 'scenario/test_with_module', '-v', '--with-coverage', '--coverage=lib/' ) STATS = ' 8 ...
import os.path import platform from nose2.compat import unittest from nose2.tests._common import FunctionalTestCase class TestCoverage(FunctionalTestCase): @unittest.skipIf( platform.python_version_tuple()[:2] == ('3', '2'), 'coverage package does not support python 3.2') def test_run(self): ...
Disable coverage test on python3.2
Disable coverage test on python3.2
Python
bsd-2-clause
little-dude/nose2,ojengwa/nose2,little-dude/nose2,ptthiem/nose2,ojengwa/nose2,ptthiem/nose2
e677e01c3046efebcdbee9fe68cd4896a58d60bf
vumi/middleware/__init__.py
vumi/middleware/__init__.py
"""Middleware classes to process messages on their way in and out of workers. """ from vumi.middleware.base import ( TransportMiddleware, ApplicationMiddleware, MiddlewareStack, create_middlewares_from_config, setup_middlewares_from_config) __all__ = [ 'TransportMiddleware', 'ApplicationMiddleware', 'Midd...
"""Middleware classes to process messages on their way in and out of workers. """ from vumi.middleware.base import ( BaseMiddleware, TransportMiddleware, ApplicationMiddleware, MiddlewareStack, create_middlewares_from_config, setup_middlewares_from_config) __all__ = [ 'BaseMiddleware', 'TransportMiddl...
Add BaseMiddleware to vumi.middleware API for 3rd-party middleware that wants to support both transports and applications.
Add BaseMiddleware to vumi.middleware API for 3rd-party middleware that wants to support both transports and applications.
Python
bsd-3-clause
TouK/vumi,harrissoerja/vumi,vishwaprakashmishra/xmatrix,harrissoerja/vumi,TouK/vumi,harrissoerja/vumi,vishwaprakashmishra/xmatrix,vishwaprakashmishra/xmatrix,TouK/vumi
4946ae0305a6add9247149784cea62823272b39e
seleniumlogin/__init__.py
seleniumlogin/__init__.py
from importlib import import_module from django.contrib.auth import SESSION_KEY, BACKEND_SESSION_KEY, HASH_SESSION_KEY def force_login(user, driver, base_url): from django.conf import settings SessionStore = import_module(settings.SESSION_ENGINE).SessionStore selenium_login_start_page = getattr(settings, ...
from importlib import import_module from django.contrib.auth import SESSION_KEY, BACKEND_SESSION_KEY, HASH_SESSION_KEY def force_login(user, driver, base_url): from django.conf import settings SessionStore = import_module(settings.SESSION_ENGINE).SessionStore selenium_login_start_page = getattr(settings, ...
Add domain to cookie to set cookie for PhantomJS
Add domain to cookie to set cookie for PhantomJS
Python
mit
feffe/django-selenium-login,feffe/django-selenium-login
ff725b4ae24c58cb126c1d49ce58a69d9b32d3b0
app/soc/models/timeline.py
app/soc/models/timeline.py
#!/usr/bin/env python2.5 # # Copyright 2008 the Melange 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 applic...
#!/usr/bin/env python2.5 # # Copyright 2008 the Melange 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 applic...
Add help text for program_end date.
Add help text for program_end date. Fixes 1411.
Python
apache-2.0
rhyolight/nupic.son,rhyolight/nupic.son,rhyolight/nupic.son
3a428dea9a27709e50bcf84666df6281a0337691
httphandler.py
httphandler.py
from BaseHTTPServer import BaseHTTPRequestHandler from StringIO import StringIO class HTTPRequest(BaseHTTPRequestHandler): """ This class is just an incapsulation of BaseHTTPRequestHandler, so it can be created from string. Code from: http://stackoverflow.com/questions/2115410/does-python-have-a-m...
from BaseHTTPServer import BaseHTTPRequestHandler from StringIO import StringIO class HTTPRequest(BaseHTTPRequestHandler): """ This class is just an incapsulation of BaseHTTPRequestHandler, so it can be created from string. Code from: http://stackoverflow.com/questions/2115410/does-python-have-a-m...
Add raw request field to request
Add raw request field to request
Python
mit
Zloool/manyfaced-honeypot
498e23919b09bfd782da4bb52f19f7c21aa14277
plantcv/plantcv/color_palette.py
plantcv/plantcv/color_palette.py
# Color palette returns an array of colors (rainbow) import numpy as np from plantcv.plantcv import params def color_palette(num): """color_palette: Returns a list of colors length num Inputs: num = number of colors to return. Returns: colors = a list of color lists (RGB values) ...
# Color palette returns an array of colors (rainbow) from matplotlib import pyplot as plt import numpy as np from plantcv.plantcv import params def color_palette(num): """color_palette: Returns a list of colors length num Inputs: num = number of colors to return. Returns: colors = a ...
Move import back to the top
Move import back to the top
Python
mit
stiphyMT/plantcv,danforthcenter/plantcv,danforthcenter/plantcv,stiphyMT/plantcv,stiphyMT/plantcv,danforthcenter/plantcv
2b8da13d4a5495082553e94047dbbd78a07905fc
insert-temp.py
insert-temp.py
#!/usr/bin/python import string import sqlite3 as lite import sys from random import randint def getTemp(): tempFile = open('/sys/bus/w1/devices/28-00000529fbad/w1_slave', 'r') contents = tempFile.read() contentsList = string.split(contents) temp = contentsList[-1] tempFile.close() return temp def insertTemp(...
#!/usr/bin/python import string import sqlite3 as lite import sys from random import randint def getTemp(): tempFile = open('/sys/bus/w1/devices/28-00000529fbad/w1_slave', 'r') contents = tempFile.read() contentsList = string.split(contents) temp = contentsList[-1] tempFile.close() return temp def insertTemp(...
Remove Pull of Data from DB
Remove Pull of Data from DB
Python
mit
eddturtle/WeatherPi,eddturtle/WeatherPi
b059f5128576d468ab0109da8d01bfdc50f6db56
accelerator/tests/contexts/analyze_judging_context.py
accelerator/tests/contexts/analyze_judging_context.py
from accelerator.tests.factories import ( CriterionFactory, CriterionOptionSpecFactory, ) from accelerator.tests.contexts.judge_feedback_context import ( JudgeFeedbackContext, ) from accelerator.models import ( JUDGING_FEEDBACK_STATUS_COMPLETE, JudgeApplicationFeedback, ) class AnalyzeJudgingConte...
from accelerator.tests.factories import ( CriterionFactory, CriterionOptionSpecFactory, ) from accelerator.tests.contexts.judge_feedback_context import ( JudgeFeedbackContext, ) from accelerator.models import ( JUDGING_FEEDBACK_STATUS_COMPLETE, JudgeApplicationFeedback, ) class AnalyzeJudgingConte...
Add is_active and default args to AnalyzeJudgingContext
Add is_active and default args to AnalyzeJudgingContext
Python
mit
masschallenge/django-accelerator,masschallenge/django-accelerator
24d58fb9650c5253eb24c4596a49daa18b8b2807
tests.py
tests.py
import os from os.path import isdir import pytest from filesystem_tree import FilesystemTree @pytest.yield_fixture def fs(): fs = FilesystemTree() yield fs fs.remove() def test_it_can_be_instantiated(): assert FilesystemTree().__class__.__name__ == 'FilesystemTree' def test_args_go_to_mk_not_root(...
import os from os.path import isdir import pytest from filesystem_tree import FilesystemTree @pytest.yield_fixture def fs(): fs = FilesystemTree() yield fs fs.remove() def test_it_can_be_instantiated(): assert FilesystemTree().__class__.__name__ == 'FilesystemTree' def test_args_go_to_mk_not_root(...
Add a test for making a file
Add a test for making a file
Python
mit
gratipay/filesystem_tree.py,gratipay/filesystem_tree.py
b7a17837a618a9d03cb8c94f3ee9765e48d83f57
froide/helper/api_utils.py
froide/helper/api_utils.py
from collections import OrderedDict from rest_framework.pagination import LimitOffsetPagination from rest_framework.response import Response from rest_framework.serializers import ListSerializer from rest_framework.utils.serializer_helpers import ReturnDict class CustomLimitOffsetPagination(LimitOffsetPagination): ...
from collections import OrderedDict from rest_framework.pagination import LimitOffsetPagination from rest_framework.response import Response from rest_framework.serializers import ListSerializer from rest_framework.utils.serializer_helpers import ReturnDict class CustomLimitOffsetPagination(LimitOffsetPagination): ...
Make facet context optional for public body search
Make facet context optional for public body search For search backends that don't support faceting
Python
mit
stefanw/froide,stefanw/froide,stefanw/froide,fin/froide,fin/froide,stefanw/froide,fin/froide,fin/froide,stefanw/froide
7a00293d602c1997777fb90331fcbf7cde1b0838
tweet.py
tweet.py
#!/usr/bin/env python from twython import Twython from credentials import * from os import urandom def random_tweet(account): # https://docs.python.org/2/library/codecs.html#python-specific-encodings status = urandom(140).decode('utf-8', errors='ignore') tweet = account.update_status(status=status) # Gotta like t...
#!/usr/bin/env python from twython import Twython from credentials import * from os import urandom def random_tweet(account): # https://docs.python.org/2/library/codecs.html status = urandom(400).decode('utf-8', errors='ignore') status = status[0:140] tweet = account.update_status(status=status) # Gotta like thi...
Make sure we fill all 140 possible characters.
Make sure we fill all 140 possible characters.
Python
mit
chrisma/dev-urandom,chrisma/dev-urandom
6439b3999f729c1689889845d879c2cb3b54266c
test/benchmarks/performance_vs_serial/linear_fft_pipeline.py
test/benchmarks/performance_vs_serial/linear_fft_pipeline.py
""" Test a pipeline with repeated FFTs and inverse FFTs """ from timeit import default_timer as timer import numpy as np import bifrost as bf from bifrost import pipeline as bfp from bifrost import blocks as blocks from bifrost_benchmarks import PipelineBenchmarker class GPUFFTBenchmarker(PipelineBenchmarker): """...
""" Test a pipeline with repeated FFTs and inverse FFTs """ from timeit import default_timer as timer import numpy as np import bifrost as bf from bifrost import pipeline as bfp from bifrost import blocks as blocks from bifrost_benchmarks import PipelineBenchmarker class GPUFFTBenchmarker(PipelineBenchmarker): """...
Switch to using block chainer
Switch to using block chainer
Python
bsd-3-clause
ledatelescope/bifrost,ledatelescope/bifrost,ledatelescope/bifrost,ledatelescope/bifrost
07549339c6b0e4b1c98a11799ca95e90cbf109cd
homedisplay/control_milight/management/commands/listen_433.py
homedisplay/control_milight/management/commands/listen_433.py
from control_milight.utils import process_automatic_trigger from django.conf import settings from django.core.management.base import BaseCommand, CommandError import serial import time import logging logger = logging.getLogger("%s.%s" % ("homecontroller", __name__)) class Command(BaseCommand): args = '' help ...
from control_milight.utils import process_automatic_trigger from django.conf import settings from django.core.management.base import BaseCommand, CommandError import serial import time import logging logger = logging.getLogger("%s.%s" % ("homecontroller", __name__)) class Command(BaseCommand): args = '' help ...
Move ITEM_MAP to method variable
Move ITEM_MAP to method variable
Python
bsd-3-clause
ojarva/home-info-display,ojarva/home-info-display,ojarva/home-info-display,ojarva/home-info-display
3b3c51cbf77085b4d5ccdbbc41a3c7ee8b67b713
turtle-trading.py
turtle-trading.py
def initialize(context): """ Set up algorithm. """ # https://www.quantopian.com/help#available-futures context.markets = [ continuous_future('US'), continuous_future('TY'), continuous_future('SB'), continuous_future('SF'), continuous_future('BP'), cont...
def initialize(context): """ Set up algorithm. """ # https://www.quantopian.com/help#available-futures context.markets = [ continuous_future('US'), continuous_future('TY'), continuous_future('SB'), continuous_future('SF'), continuous_future('BP'), cont...
Delete markets that stopped trading.
Delete markets that stopped trading.
Python
mit
vyq/turtle-trading
79d80db7b67c787bf970dd8c593e505bb8915a21
bond_analytics_project/bond_analytics_project/urls.py
bond_analytics_project/bond_analytics_project/urls.py
"""bond_analytics_project URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.9/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='h...
"""bond_analytics_project URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.9/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='h...
Add djangorestframework DefaultRouter instance and registered BondViewSet.
Add djangorestframework DefaultRouter instance and registered BondViewSet.
Python
mit
bsmukasa/bond_analytics
7e1ed9cca3e02488d8d189d22e6fca35c0bec108
xmantissa/test/test_siteroot.py
xmantissa/test/test_siteroot.py
from twisted.trial import unittest from axiom.store import Store from axiom.item import Item from axiom.attributes import text from xmantissa.website import PrefixURLMixin, WebSite from xmantissa.ixmantissa import ISiteRootPlugin from zope.interface import implements class Dummy: def __init__(self, pfx): ...
from twisted.trial import unittest from axiom.store import Store from axiom.item import Item from axiom.attributes import text from xmantissa.website import PrefixURLMixin, WebSite from xmantissa.ixmantissa import ISiteRootPlugin from zope.interface import implements class Dummy: def __init__(self, pfx): ...
Fix boken test - install WebSite before trying to locateChild
Fix boken test - install WebSite before trying to locateChild
Python
mit
twisted/mantissa,twisted/mantissa,twisted/mantissa
74d9bf3818b2c93e78028b5ff24e4c0b7e231ce1
scripts/downgrade-pip-on-pypy.py
scripts/downgrade-pip-on-pypy.py
""" Downgrade to pip < 20.2 when running on PyPy because pip 20.2 (the most recent release at the time of writing) breaks compatibility with PyPy, thereby causing Travis CI builds of py2deb to fail as well. For more details please refer to https://github.com/pypa/pip/issues/8653. """ import pip import platform import ...
""" Downgrade to pip < 20.2 when running on PyPy. Unfortunately pip 20.2 (the most recent release at the time of writing) breaks compatibility with PyPy, thereby causing Travis CI builds of py2deb to fail as well. For details please refer to https://github.com/pypa/pip/issues/8653. """ import pip import platform impo...
Fix flake8 "violations" in new PyPy compensation script
Fix flake8 "violations" in new PyPy compensation script
Python
mit
paylogic/py2deb,paylogic/py2deb
8e2ec397f4e0c66e3f22056202d0d0829cdd64ac
publishing/serializers.py
publishing/serializers.py
from rest_framework import serializers from models import Page class PageSerializer(serializers.ModelSerializer): parent = serializers.PrimaryKeyRelatedField(required=False) children = serializers.PrimaryKeyRelatedField(many=True, required=False) class Meta: model = Page fields = ( ...
from rest_framework import serializers from models import Page class PageSerializer(serializers.ModelSerializer): parent = serializers.PrimaryKeyRelatedField(required=False) children = serializers.PrimaryKeyRelatedField(many=True, required=False, read_only=True) class Meta: model = Page ...
Make the children field in the api read only.
Make the children field in the api read only.
Python
mit
olofsj/django-simple-publishing,olofsj/django-simple-publishing
612d54c6f8eace7b4c87d5771059bfb55a4c583f
pyspectator/monitoring.py
pyspectator/monitoring.py
from abc import ABCMeta, abstractmethod from threading import Timer class AbcMonitor(metaclass=ABCMeta): """Base class for entities, which require repeating event. Attributes: monitoring (bool): indicator activity of monitor. monitoring_latency (int, float): frequency of execution monitor's a...
from abc import ABCMeta, abstractmethod from threading import Timer class AbcMonitor(metaclass=ABCMeta): """Base class for entities, which require repeating event. Attributes: monitoring (bool): indicator activity of monitor. monitoring_latency (int, float): frequency of execution monitor's a...
Support of "with" statement in class "AbsMonitor".
Support of "with" statement in class "AbsMonitor".
Python
bsd-3-clause
uzumaxy/pyspectator
02e7251da64c9a2853c2e05a2b93b862268a840c
SixTrack/pytools/fix_cdblocks.py
SixTrack/pytools/fix_cdblocks.py
#!/usr/bin/env python import sys assert len(sys.argv) == 3, "Usage: to_replace filename" to_replace = sys.argv[1] filename = sys.argv[2] lines_in = open(filename,'r').readlines() #print '+ca '+to_replace i = 0 num_replaced = 0 while True: line = lines_in[i] #print line if line.startswith('+ca '+t...
#!/usr/bin/env python import sys assert len(sys.argv) == 3, "Usage: to_replace filename" to_replace = sys.argv[1] filename = sys.argv[2] lines_in = open(filename,'r').readlines() #print '+ca '+to_replace i = 0 num_replaced = 0 numspaces = 6 # default value while True: line = lines_in[i] #print line ...
Indent the use statements correctly
Indent the use statements correctly
Python
lgpl-2.1
SixTrack/SixTrack,SixTrack/SixTrack,SixTrack/SixTrack,SixTrack/SixTrack,SixTrack/SixTrack,SixTrack/SixTrack
71ffcd1ed4447090b43b3424548f46c5230a1045
tasks.py
tasks.py
#!/usr/bin/env python3 import subprocess from invoke import task @task def test(cover=False): # Run tests using nose called with coverage code = subprocess.call(['coverage', 'run', '-m', 'nose', '--rednose']) # Also generate coverage reports when --cover flag is given if cover and code == 0: ...
# Project tasks (for use with invoke task runner) import subprocess from invoke import task @task def test(cover=False): if cover: # Run tests via coverage and generate reports if --cover flag is given code = subprocess.call(['coverage', 'run', '-m', 'nose', '--rednose']) # Only show cove...
Improve efficiency of test task
Improve efficiency of test task
Python
mit
caleb531/ssh-wp-backup,caleb531/ssh-wp-backup
5fa4bbf781117c20357cf6f477e0298047e11094
engine/migrate.py
engine/migrate.py
import store rstore = store.RedisStore() def populate_terminations(): for game in rstore.all_games(): rstore.set_game(game["game_id"], game["game"]) def populate_game_ids(): keys = rstore.rconn.keys("chess:games:*:game") game_ids = [k.split(":")[-2] for k in keys] rstore.rconn.sadd("chess:gam...
import store rstore = store.RedisStore() def populate_terminations(): for game in rstore.all_games(): rstore.set_game(game["game_id"], game["game"]) def populate_game_ids(): keys = rstore.rconn.keys("chess:games:*:game") game_ids = [k.split(":")[-2] for k in keys] rstore.rconn.sadd("chess:gam...
Print player emails in migration script.
Print player emails in migration script.
Python
mit
haldean/chess,haldean/chess,haldean/chess
5805f84500ebca762ec2c7e34f344bf3c2406a8d
examples/pywapi-example.py
examples/pywapi-example.py
#!/usr/bin/env python import pywapi weather_com_result = pywapi.get_weather_from_weather_com('10001') yahoo_result = pywapi.get_weather_from_yahoo('10001') noaa_result = pywapi.get_weather_from_noaa('KJFK') print "Weather.com says: It is " + string.lower(weather_com_result['current_conditions']['text']) + " and " + ...
#!/usr/bin/env python import pywapi weather_com_result = pywapi.get_weather_from_weather_com('10001') yahoo_result = pywapi.get_weather_from_yahoo('10001') noaa_result = pywapi.get_weather_from_noaa('KJFK') print "Weather.com says: It is " + weather_com_result['current_conditions']['text'].lower() + " and " + weathe...
Fix error in example script
Fix error in example script
Python
mit
qetzal/python-weather-api,esteban22x/python-weather-api,dreamable/python-weather-api,alinahid477/python-weather-api,sirspamalot/python-weather-api,gmassei/python-weather-api,handyfreak/python-weather-api,jtasker/python-weather-api
f3ec19e0893db4fbbad8848dec8f63a09d7ffd06
alg_sum_list.py
alg_sum_list.py
from __future__ import absolute_import from __future__ import print_function from __future__ import division def sum_list_iter(num_ls): """Sum number list by for loop.""" _sum = 0 for num in num_ls: _sum += num return _sum def sum_list_recur(num_ls): """Sum number list by recursion.""" ...
from __future__ import absolute_import from __future__ import print_function from __future__ import division def sum_list_recur(a_list): """Sum list by recursion. Time complexity: O(n), where n is the list length. Space complexity: O(n). """ if len(a_list) == 1: return a_list[0] else:...
Add time/space complexity; revise var's
Add time/space complexity; revise var's
Python
bsd-2-clause
bowen0701/algorithms_data_structures
ea79df2314afc4bf8e2747800120a7d5d005ece7
reviewboard/notifications/templatetags/markdown_email.py
reviewboard/notifications/templatetags/markdown_email.py
from __future__ import unicode_literals import markdown from django import template from django.utils.safestring import mark_safe from djblets.markdown import markdown_unescape register = template.Library() @register.filter def markdown_email_html(text, is_rich_text): if not is_rich_text: return text ...
from __future__ import unicode_literals import markdown from django import template from django.utils.safestring import mark_safe from djblets.markdown import markdown_unescape register = template.Library() @register.filter def markdown_email_html(text, is_rich_text): if not is_rich_text: return text ...
Add a couple missing Markdown extensions for e-mail rendering.
Add a couple missing Markdown extensions for e-mail rendering. The Markdown e-mail rendering code wasn't correctly rendering lists or strings with double-underscores separating words, due to missing a couple of extensions. This adds those missing extensions, bringing some consistency. Testing Done: Tested the e-mail ...
Python
mit
reviewboard/reviewboard,chipx86/reviewboard,chipx86/reviewboard,brennie/reviewboard,reviewboard/reviewboard,reviewboard/reviewboard,chipx86/reviewboard,brennie/reviewboard,brennie/reviewboard,reviewboard/reviewboard,brennie/reviewboard,chipx86/reviewboard
e8548c26df021d9eff7c056338e3442beeed9397
cactusbot/handlers/spam.py
cactusbot/handlers/spam.py
"""Handle incoming spam messages.""" from ..handler import Handler import logging class SpamHandler(Handler): """Spam handler.""" MAX_SCORE = 16 MAX_EMOTES = 6 ALLOW_LINKS = False def __init__(self): self.logger = logging.getLogger(__name__) def on_message(self, packet): ""...
"""Handle incoming spam messages.""" from ..handler import Handler import logging class SpamHandler(Handler): """Spam handler.""" MAX_SCORE = 16 MAX_EMOTES = 6 ALLOW_LINKS = False def __init__(self): self.logger = logging.getLogger(__name__) def on_message(self, packet): ""...
Move for loop to generator comprehension
Move for loop to generator comprehension
Python
mit
CactusDev/CactusBot
3c49598aaaceaa73b7aeb033d4dffd21a14ecf7c
src/account.py
src/account.py
#!/usr/bin/env python3 import sqlite3 import os from os.path import expanduser def connect_db(): # get home dir dir_config = expanduser("~") + "/.config/becon" # check if config dir exists if not (os.path.exists(dir_config)): os.makedirs(dir_config) # connexion to db database = dir_c...
#!/usr/bin/env python3 # coding: utf8 import sqlite3 import os import sys import hashlib import getpass from os.path import expanduser def connect_db(): # get home dir dir_config = expanduser("~") + "/.config/becon" # check if config dir exists if not (os.path.exists(dir_config)): os.makedirs...
Create user, read input from stdin and hash password with sha
Create user, read input from stdin and hash password with sha
Python
mit
cboin/becon
96300cfe78916e7ddc65a48d85cece55ef34ea01
scrapers/examples/test.py
scrapers/examples/test.py
# This line keeps pyflakes from getting mad when it can't find the `scheduler` # object declared in narcissa.py. scheduler = globals()['scheduler'] # Write everything inside one giant function so that function can be scheduled # for later execution. def scrape_test(): """ This scraper illustrates the followin...
# This line keeps pyflakes from getting mad when it can't find the `scheduler` # object declared in narcissa.py. scheduler = globals()['scheduler'] # Write everything inside one giant function so that function can be scheduled # for later execution. # This function MUST be named uniquely so it doesn't interfere with...
Add note about naming functions uniquely
Add note about naming functions uniquely
Python
mit
mplewis/narcissa
7d98adbfd08cbb72b6a9cc4ffe585756203b4e43
app/__init__.py
app/__init__.py
# -*- coding: utf-8 -*- import logging from flask import Flask from flask_socketio import SocketIO from logging.handlers import RotatingFileHandler app = Flask(__name__) app.config.from_object('config') app.config.from_envvar('POSIO_SETTINGS') socketio = SocketIO(app) from app import views file_handler = RotatingF...
# -*- coding: utf-8 -*- import logging from os import environ from flask import Flask from flask_socketio import SocketIO from logging.handlers import RotatingFileHandler app = Flask(__name__) app.config.from_object('config') # Override config if needed if 'POSIO_SETTINGS' in environ: app.config.from_envvar('POSI...
Check if custom config file is set
Check if custom config file is set
Python
mit
abrenaut/posio,abrenaut/posio,abrenaut/posio
035fb3211fca0a1627db08f7e91f27cd1addeef6
froide/publicbody/forms.py
froide/publicbody/forms.py
from django import forms from django.utils.translation import ugettext_lazy as _ from froide.helper.form_utils import JSONMixin from .models import PublicBody from .widgets import PublicBodySelect class PublicBodyForm(JSONMixin, forms.Form): publicbody = forms.ModelChoiceField( queryset=PublicBody.o...
from django import forms from django.utils.translation import ugettext_lazy as _ from froide.helper.form_utils import JSONMixin from .models import PublicBody from .widgets import PublicBodySelect class PublicBodyForm(JSONMixin, forms.Form): publicbody = forms.ModelChoiceField( queryset=PublicBody.o...
Add uniform API for public body widgets
Add uniform API for public body widgets
Python
mit
fin/froide,fin/froide,stefanw/froide,fin/froide,fin/froide,stefanw/froide,stefanw/froide,stefanw/froide,stefanw/froide
50bab0199e2d209dc177f5e3b5f193330048e403
blinktCP.py
blinktCP.py
#!/usr/bin/env python # Blue Dot Blinkt Colour Picker # 02/06/2017 # David Glaude from bluedot import BlueDot import colorsys import time import blinkt last_time = time.time() def setall(r,g,b): for x in range(blinkt.NUM_PIXELS): blinkt.set_pixel(x, r, g, b) blinkt.show() def move(pos): h=((po...
#!/usr/bin/env python # Blue Dot Blinkt Colour Picker # 02/06/2017 # David Glaude from bluedot import BlueDot import colorsys import time import blinkt last_time = time.time() def setall(r,g,b): # for x in range(blinkt.NUM_PIXELS): # blinkt.set_pixel(x, r, g, b) blinkt.set_all(r, g, b) blinkt.sho...
Use the Blinkt! library set_all rather than to loop on 8 pixels.
Use the Blinkt! library set_all rather than to loop on 8 pixels.
Python
mit
dglaude/Blue-Dot-Colour-Picker
d0000ab4c650379667ff018290d2d67d026c330c
reaper.py
reaper.py
#!/usr/bin/env python import boto import base64 import json from datetime import datetime def seconds_from_hours(hours): return hours * 60 * 60 def should_kill(instance): attributes = instance.get_attribute("userData") if attributes['userData'] == None: return False user_data = base64.b64d...
#!/usr/bin/env python import boto import base64 import json from datetime import datetime def seconds_from_hours(hours): return hours * 60 * 60 def should_kill(instance): attributes = instance.get_attribute("userData") if attributes['userData'] == None: print "Instance has no userdata" ...
Add debugging to the repear script
Add debugging to the repear script
Python
mit
kyleconroy/popfly
7673e33186bb5f48d9f1c35deb55fca91553d526
mopidy_soundcloud/actor.py
mopidy_soundcloud/actor.py
from __future__ import unicode_literals import logging import pykka from mopidy import backend from .library import SoundCloudLibraryProvider from .soundcloud import SoundCloudClient logger = logging.getLogger(__name__) class SoundCloudBackend(pykka.ThreadingActor, backend.Backend): def __init__(self, config...
from __future__ import unicode_literals import logging import pykka from mopidy import backend from .library import SoundCloudLibraryProvider from .soundcloud import SoundCloudClient logger = logging.getLogger(__name__) class SoundCloudBackend(pykka.ThreadingActor, backend.Backend): def __init__(self, config...
Handle track that can't be played
Handle track that can't be played
Python
mit
mopidy/mopidy-soundcloud,yakumaa/mopidy-soundcloud
377ec226eb1cb8f0e5ea4bca06d8a0db0905b87d
comrade/core/decorators.py
comrade/core/decorators.py
def singleton(cls): instances = {} def getinstance(): if cls not in instances: instances[cls] = cls() return instances[cls] return getinstance
def singleton(cls): instances = {} def getinstance(): if cls not in instances: instances[cls] = cls() return instances[cls] return getinstance def authorized(test_func, unauthorized_url=None): """ Decorator for views that checks that the user passes the given test, r...
Add decorator for checking if a user is authorized to access a page.
Add decorator for checking if a user is authorized to access a page.
Python
mit
bueda/django-comrade
d146036998d3595730b3de5f03fd7ac6e63ae498
src/sentry/api/serializers/models/organization_member.py
src/sentry/api/serializers/models/organization_member.py
from __future__ import absolute_import from sentry.api.serializers import Serializer, register from sentry.models import OrganizationMember @register(OrganizationMember) class OrganizationMemberSerializer(Serializer): def serialize(self, obj, attrs, user): d = { 'id': str(obj.id), ...
from __future__ import absolute_import from sentry.api.serializers import Serializer, register from sentry.models import OrganizationMember @register(OrganizationMember) class OrganizationMemberSerializer(Serializer): def serialize(self, obj, attrs, user): if obj.user: user_data = {'id': obj....
Add user ID to member
Add user ID to member
Python
bsd-3-clause
BuildingLink/sentry,JamesMura/sentry,looker/sentry,looker/sentry,BuildingLink/sentry,jean/sentry,JackDanger/sentry,mvaled/sentry,zenefits/sentry,JamesMura/sentry,jean/sentry,daevaorn/sentry,BuildingLink/sentry,BuildingLink/sentry,mitsuhiko/sentry,fotinakis/sentry,beeftornado/sentry,ifduyue/sentry,daevaorn/sentry,fotina...
15492594186b6a0dcea510e6896310f5e45368fc
instance/serializers.py
instance/serializers.py
""" Instance serializers (API representation) """ #pylint: disable=no-init from rest_framework import serializers from .models import OpenStackServer, OpenEdXInstance class OpenStackServerSerializer(serializers.ModelSerializer): pk = serializers.HyperlinkedIdentityField(view_name='api:openstackserver-detail') ...
""" Instance serializers (API representation) """ #pylint: disable=no-init from rest_framework import serializers from .models import OpenStackServer, OpenEdXInstance class OpenStackServerSerializer(serializers.ModelSerializer): pk_url = serializers.HyperlinkedIdentityField(view_name='api:openstackserver-detail...
Include both the numerical instance.pk & its API URL
API: Include both the numerical instance.pk & its API URL
Python
agpl-3.0
open-craft/opencraft,omarkhan/opencraft,open-craft/opencraft,omarkhan/opencraft,omarkhan/opencraft,open-craft/opencraft,omarkhan/opencraft,brousch/opencraft,brousch/opencraft,brousch/opencraft,open-craft/opencraft,open-craft/opencraft
0a005806afb436a2ad01275a969ae6afc3c5a72c
cloud_browser/__init__.py
cloud_browser/__init__.py
"""Cloud browser application. Provides a simple filesystem-like browser interface for cloud blob datastores. """ VERSION = (0, 4, 0) __version__ = ".".join(str(v) for v in VERSION) __version_full__ = __version__
"""Cloud browser application. Provides a simple filesystem-like browser interface for cloud blob datastores. """ VERSION = (0, 0, 0) # placeholder, real value is set by `fab sdist` __version__ = ".".join(str(v) for v in VERSION) __version_full__ = __version__
Make it explicit that VERSION is a placeholder
Make it explicit that VERSION is a placeholder
Python
mit
ryan-roemer/django-cloud-browser,ryan-roemer/django-cloud-browser,ryan-roemer/django-cloud-browser
0997b216ea520aca2d8d62ac31a238c7280302ca
bananas/admin/api/serializers.py
bananas/admin/api/serializers.py
from django.contrib.auth import password_validation from django.utils.translation import ugettext_lazy as _ from rest_framework import serializers class AuthenticationSerializer(serializers.Serializer): username = serializers.CharField(label=_("Username"), write_only=True) password = serializers.CharField(lab...
from django.contrib.auth.password_validation import password_validators_help_texts from django.utils.translation import ugettext_lazy as _ from rest_framework import serializers class AuthenticationSerializer(serializers.Serializer): username = serializers.CharField(label=_("Username"), write_only=True) passw...
Use plain password help text instead of html
Use plain password help text instead of html
Python
mit
5monkeys/django-bananas,5monkeys/django-bananas,5monkeys/django-bananas
cc7de0147d773722db026d2571cc94c6ee01c9e0
new/energies/zeeman.py
new/energies/zeeman.py
class FixedZeeman(object): def __init__(self, H, multiplier=1, name='fixedzeeman'): if not isinstance(H, (list, tuple)) or len(H) != 3: raise ValueError('H must be a 3-element tuple or list.') else: self.H = H if not isinstance(multiplier, (float, int)): ...
import numpy as np class FixedZeeman(object): def __init__(self, H, multiplier=1, name='fixedzeeman'): if not isinstance(H, (list, tuple, np.ndarray)) or len(H) != 3: raise ValueError('H must be a 3-element tuple or list.') else: self.H = H if not isinstance(multipl...
Add numpy array as a possibility for setting external magnetic field.
Add numpy array as a possibility for setting external magnetic field.
Python
bsd-2-clause
fangohr/oommf-python,fangohr/oommf-python,fangohr/oommf-python
5796a54d10eb3baebda51e3420a818a251406a5c
python/test.py
python/test.py
import sys from PyQt5 import QtWidgets from QHexEdit import QHexEdit, QHexEditData class HexEdit(QHexEdit): def __init__(self, fileName=None): super(HexEdit, self).__init__() file = open(fileName) data = file.read() self.setData(data) self.setReadOnly(False) if __name__ ...
import sys from PyQt5 import QtWidgets, QtGui from QHexEdit import QHexEdit, QHexEditData if __name__ == '__main__': app = QtWidgets.QApplication(sys.argv) # QHexEditData* hexeditdata = QHexEditData::fromFile("test.py"); hexeditdata = QHexEditData.fromFile('test.py') # QHexEdit* hexedit = new QHexEdi...
Test more stuff in python
Test more stuff in python
Python
mit
parallaxinc/QHexEdit,parallaxinc/QHexEdit
60bfd29c5f21c3daf43a1b150048f57c147dbaf2
inet/sources/twitter.py
inet/sources/twitter.py
# -*- coding: utf-8 -*- import tweepy from .constants import TWITTER_ACCESS, TWITTER_SECRET from .constants import TWITTER_CONSUMER_ACCESS, TWITTER_CONSUMER_SECRET _auth = tweepy.OAuthHandler(TWITTER_CONSUMER_ACCESS, TWITTER_CONSUMER_SECRET) _auth.set_access_token(TWITTER_ACCESS, TWITTER_SECRET) twitter_client = twe...
# -*- coding: utf-8 -*- import tweepy from .constants import TWITTER_ACCESS, TWITTER_SECRET from .constants import TWITTER_CONSUMER_ACCESS, TWITTER_CONSUMER_SECRET _auth = tweepy.OAuthHandler(TWITTER_CONSUMER_ACCESS, TWITTER_CONSUMER_SECRET) _auth.set_access_token(TWITTER_ACCESS, TWITTER_SECRET) twitter_client = twe...
Set wait on rate limit to True
Set wait on rate limit to True
Python
mit
nestauk/inet
de75ec4f92c424b22f1d64dc43b3d8259b96fde0
coverart_redirect/loggers.py
coverart_redirect/loggers.py
import raven import raven.transport.threaded_requests from raven.handlers.logging import SentryHandler from raven.conf import setup_logging import logging class MissingRavenClient(raven.Client): """Raven client class that is used as a placeholder. This is done to make sure that calls to functions in the clien...
import raven import raven.transport.threaded_requests from raven.handlers.logging import SentryHandler from raven.conf import setup_logging from werkzeug.exceptions import HTTPException from exceptions import KeyboardInterrupt import logging class MissingRavenClient(raven.Client): """Raven client class that is us...
Exclude HTTP exceptions from logging by Raven
Exclude HTTP exceptions from logging by Raven
Python
mit
metabrainz/coverart_redirect,metabrainz/coverart_redirect,metabrainz/coverart_redirect
38d5e165363f55dfedea94397ca85634bf800941
libqtile/layout/sublayouts.py
libqtile/layout/sublayouts.py
from base import SubLayout, Rect from Xlib import Xatom class TopLevelSubLayout(SubLayout): ''' This class effectively wraps a sublayout, and automatically adds a floating sublayout, ''' def __init__(self, sublayout_data, clientStack, theme): WrappedSubLayout, args = sublayout_data S...
from base import SubLayout, Rect from Xlib import Xatom class TopLevelSubLayout(SubLayout): ''' This class effectively wraps a sublayout, and automatically adds a floating sublayout, ''' def __init__(self, sublayout_data, clientStack, theme): WrappedSubLayout, args = sublayout_data S...
Update floating sublayout to use floatDimensions
Update floating sublayout to use floatDimensions
Python
mit
himaaaatti/qtile,dequis/qtile,cortesi/qtile,kopchik/qtile,zordsdavini/qtile,frostidaho/qtile,nxnfufunezn/qtile,himaaaatti/qtile,EndPointCorp/qtile,zordsdavini/qtile,encukou/qtile,kynikos/qtile,flacjacket/qtile,bavardage/qtile,kseistrup/qtile,soulchainer/qtile,jdowner/qtile,apinsard/qtile,rxcomm/qtile,ramnes/qtile,EndPo...
a0443783c880cf90b11886e3180e842e2c17a77a
tests/gtype.py
tests/gtype.py
import unittest from common import gobject, gtk class GTypeTest(unittest.TestCase): def testBoolType(self): store = gtk.ListStore(gobject.TYPE_BOOLEAN) assert store.get_column_type(0) == gobject.TYPE_BOOLEAN store = gtk.ListStore('gboolean') assert store.get_column_type(0) == gobje...
import unittest from common import gobject, gtk class GTypeTest(unittest.TestCase): def checkType(self, expected, *objects): # Silly method to check pyg_type_from_object store = gtk.ListStore(expected) val = store.get_column_type(0) assert val == expected, \ ...
Test various other types aswell
Test various other types aswell
Python
lgpl-2.1
thiblahute/pygobject,atizo/pygobject,atizo/pygobject,nzjrs/pygobject,choeger/pygobject-cmake,Distrotech/pygobject,pexip/pygobject,davidmalcolm/pygobject,jdahlin/pygobject,MathieuDuponchelle/pygobject,GNOME/pygobject,davidmalcolm/pygobject,thiblahute/pygobject,davibe/pygobject,davibe/pygobject,jdahlin/pygobject,pexip/py...
fde3cb61225f66414f41eac141fb68651a3fe1c9
tests/stats.py
tests/stats.py
# Copyright (C) 2010 Peter Teichman import unittest from instatrace.stats import Statistic class testStatistic(unittest.TestCase): def testName(self): name = "test_stat" s = Statistic(name, []) self.assertEqual(name, s.name)
# Copyright (C) 2010 Peter Teichman import unittest from instatrace.stats import Statistics class testStatistics(unittest.TestCase): def testStats(self): name = "test_stat" s = Statistics() s.add_sample(name, 1) s.add_sample(name, 2) s.add_sample(name, 3) test_st...
Implement testStatistics with count, total, mean, and stddev checks
Implement testStatistics with count, total, mean, and stddev checks
Python
mit
pteichman/instatrace
37900e6c4bd8c16b2fef1be0c978f4f0567b09a3
nn/embedding/embeddings.py
nn/embedding/embeddings.py
import tensorflow as tf from .. import var_init def embeddings(*, id_space_size, embedding_size): return tf.Variable(var_init.normal([id_space_size, embedding_size]))
import tensorflow as tf from ..variable import variable def embeddings(*, id_space_size, embedding_size): return variable([id_space_size, embedding_size])
Use variable module instead of var_init
Use variable module instead of var_init
Python
unlicense
raviqqe/tensorflow-extenteten,raviqqe/tensorflow-extenteten
0bfd715ca0bae0929f2a06bdb42bdb0c95aea6dd
grafeno/_parse_freeling.py
grafeno/_parse_freeling.py
#!/usr/bin/env python3 from subprocess import Popen, PIPE import subprocess as subp import json import re regex = re.compile('}\s*{') def parse (sentence, lang): '''Calls the freeling process to obtain the dependency parse of a text.''' config = "grafeno/freeling_deps_"+lang+".cfg" proc = Popen(["analyze...
#!/usr/bin/env python3 from subprocess import Popen, PIPE import subprocess as subp import os import json import re regex = re.compile('}\s*{') def parse (sentence, lang): '''Calls the freeling process to obtain the dependency parse of a text.''' config = os.path.dirname(__file__)+"/freeling_deps_"+lang+".cf...
Make freeling configuration available independent of execution path
Make freeling configuration available independent of execution path
Python
agpl-3.0
agarsev/grafeno,agarsev/grafeno,agarsev/grafeno
7060a7c85cf82fae9e018f1c82a1d8181bd5214d
library/tests/factories.py
library/tests/factories.py
from django.conf import settings import factory from factory.fuzzy import FuzzyText from ..models import Book, BookSpecimen class BookFactory(factory.django.DjangoModelFactory): title = factory.Sequence(lambda n: "Test book %03d" % n) summary = "This is a test summary" section = 1 lang = settings.LA...
from django.conf import settings import factory from factory.fuzzy import FuzzyText from ..models import Book, BookSpecimen class BookFactory(factory.django.DjangoModelFactory): title = factory.Sequence(lambda n: "Test book {0}".format(n)) summary = "This is a test summary" section = 1 lang = settin...
Use format for string formatting
Use format for string formatting
Python
agpl-3.0
Lcaracol/ideasbox.lan,ideascube/ideascube,ideascube/ideascube,ideascube/ideascube,Lcaracol/ideasbox.lan,ideascube/ideascube,Lcaracol/ideasbox.lan
f2a47110c9416a1efcf2a4346303377afedc2315
builders/horizons_telnet.py
builders/horizons_telnet.py
#!/usr/bin/env python2.7 #import argparse from telnetlib import Telnet def main(in_path, out_path): lines = read_lines(open(in_path)) tn = Telnet('horizons.jpl.nasa.gov', 6775) out = open(out_path, 'w') for line in lines: print(repr(line)) tn.write(line.encode('ascii') + b'\r\n') ...
#!/usr/bin/env python2.7 #import argparse from telnetlib import Telnet def main(in_path, out_path): lines = read_lines(open(in_path)) tn = Telnet('horizons.jpl.nasa.gov', 6775) out = open(out_path, 'w') for line in lines: print(repr(line)) tn.write(line.encode('ascii') + b'\r\n') ...
Speed up the telnet process for HORIZONS
Speed up the telnet process for HORIZONS Be very patient waiting for the other end to start its reply, but then only wait 1s for the rest of the data.
Python
mit
exoanalytic/python-skyfield,ozialien/python-skyfield,exoanalytic/python-skyfield,skyfielders/python-skyfield,ozialien/python-skyfield,GuidoBR/python-skyfield,GuidoBR/python-skyfield,skyfielders/python-skyfield
565841a8ccfe9675cfbee89564506bc1967314b7
trunk/scons-tools/gmcs.py
trunk/scons-tools/gmcs.py
import os.path import SCons.Builder import SCons.Node.FS import SCons.Util csccom = "$CSC $CSCFLAGS $_CSCLIBPATH -r:$_CSCLIBS -out:${TARGET.abspath} $SOURCES" csclibcom = "$CSC -t:library $CSCLIBFLAGS $_CSCLIBPATH $_CSCLIBS -out:${TARGET.abspath} $SOURCES" McsBuilder = SCons.Builder.Builder(action = '$CSCCOM', ...
import os.path import SCons.Builder import SCons.Node.FS import SCons.Util csccom = "$CSC $CSCFLAGS $_CSCLIBPATH -r:$_CSCLIBS -out:${TARGET.abspath} $SOURCES" csclibcom = "$CSC -t:library $CSCLIBFLAGS $_CSCLIBPATH $_CSCLIBS -out:${TARGET.abspath} $SOURCES" McsBuilder = SCons.Builder.Builder(action = '$CSCCOM', ...
Use -platform:anycpu while compiling .NET assemblies
Use -platform:anycpu while compiling .NET assemblies git-svn-id: 8d82213adbbc6b1538a984bace977d31fcb31691@349 2f5d681c-ba19-11dd-a503-ed2d4bea8bb5
Python
lgpl-2.1
shutej/tapcfg,shutej/tapcfg,shutej/tapcfg,shutej/tapcfg,shutej/tapcfg,shutej/tapcfg,shutej/tapcfg
63ce9ac2a46f74704810d62e22c0b75ca071442a
minesweeper/minesweeper.py
minesweeper/minesweeper.py
import re class InvalidBoard(ValueError): pass def board(b): if not is_valid_board(b): raise InvalidBoard("Board is malformed and thus invalid") b = [[ch for ch in row] for row in b] for i in range(1, len(b)-1): for j in range(1, len(b[0])-1): if b[i][j] == " ": ...
import re class InvalidBoard(ValueError): pass def board(b): if not is_valid_board(b): raise InvalidBoard("Board is malformed and thus invalid") b = [[ch for ch in row] for row in b] for i in range(1, len(b)-1): for j in range(1, len(b[0])-1): if b[i][j] == " ": ...
Add note regarding use of bool in validation
Add note regarding use of bool in validation
Python
agpl-3.0
CubicComet/exercism-python-solutions
fbe6722fd74b5e260892f5664226bc66d5424d79
kindred/Token.py
kindred/Token.py
class Token: """ Individual word with lemma, part-of-speech and location in text. :ivar word: Unprocessed word :ivar lemma: Lemmatized word :ivar partofspeech: Part-of-speech of word :ivar startPos: Start position of token in sentence :ivar endPos: End position of token in sentence """ def __init__(self,w...
class Token: """ Individual word with lemma, part-of-speech and location in text. :ivar word: Unprocessed word :ivar lemma: Lemmatized word :ivar partofspeech: Part-of-speech of word :ivar startPos: Start position of token in document text (note: not the sentence text) :ivar endPos: End position of token in d...
Fix mistaken document about token pos
Fix mistaken document about token pos
Python
mit
jakelever/kindred,jakelever/kindred
26d2e74c93036962aa266fc1484e77d47d36a446
rnacentral/portal/migrations/0010_add_precomputed_rna_type.py
rnacentral/portal/migrations/0010_add_precomputed_rna_type.py
from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('portal', '0009_add_precomputed_rna_table'), ] operations = [ migrations.AddField("RnaPrecomputed", "rna_type", models.CharField(max_length=250)) ...
from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('portal', '0009_add_precomputed_rna_table'), ] operations = [ # rna_type is a / seperated field that represents the set of rna_types # for a ...
Add a doc to the migration
Add a doc to the migration This should probably be encoded better somehow.
Python
apache-2.0
RNAcentral/rnacentral-webcode,RNAcentral/rnacentral-webcode,RNAcentral/rnacentral-webcode,RNAcentral/rnacentral-webcode
dabc17d149eebd8c6fa61780291fd229bd7bea99
oysterapp/oyster/management/commands/update_recurring_tasks.py
oysterapp/oyster/management/commands/update_recurring_tasks.py
import datetime from django.core.management.base import BaseCommand from oysterapp.oyster.models import TaskRule class Command(BaseCommand): help = "Creates tasks based off task rules" def handle(self, *args, **options): now = datetime.datetime.now() last_run = TaskRule.objects.order_by('-u...
import datetime import pytz from django.core.management.base import BaseCommand from oysterapp.oyster.models import TaskRule class Command(BaseCommand): help = "Creates tasks based off task rules" def handle(self, *args, **options): now = datetime.datetime.now().replace(tzinfo=pytz.UTC) las...
Update datetime with timezone add more print statements for debugging
Update datetime with timezone add more print statements for debugging
Python
unlicense
averymanderson/oysterap,averymanderson/OysterWebApp,averymanderson/oysterap,averymanderson/OysterWebApp,averymanderson/OysterWebApp,averymanderson/oysterap
da9f9028e3a757e81affb34ad2ff9dc61a1ddd8a
merlin/engine/battle.py
merlin/engine/battle.py
class Prepare(object): """ Prepare the champions for the battle! Usage: hero = Prepare(name="Aragorn", base_attack=100, base_hp=100) or like this: aragorn = {"name": "Aragorn", "base_attack": 100, "base_hp": 100} hero = Prepare(**aragorn) """ def __init__(self, name, b...
class Prepare(object): """ Prepare the champions for the battle! """ def __init__(self, name, base_attack, base_hp): self.name = name self.base_attack = base_attack self.base_hp = base_hp @property def status(self): return self.__dict__ def attack(self, ...
Create a collect method for get droppable items
Create a collect method for get droppable items
Python
mit
lerrua/merlin-engine
e1edb506113a0fd8104931def710188f5d507f06
crispy/gui/widgets/plotwidget.py
crispy/gui/widgets/plotwidget.py
# coding: utf-8 from silx.gui.plot import PlotWindow class PlotWidget(PlotWindow): def __init__(self, *args): super(PlotWidget, self).__init__() self.setActiveCurveHandling(False) self.setGraphXLabel('Energy (eV)') self.setGraphYLabel('Absorption cross section (a.u.)') def plo...
# coding: utf-8 from silx.gui.plot import PlotWindow class PlotWidget(PlotWindow): def __init__(self, *args): super(PlotWidget, self).__init__(logScale=False, grid=True, aspectRatio=False, yInverted=False, roi=False, mask=False, print_=False) self.setActiveCurveHand...
Remove unused icons of the PlotWindow
Remove unused icons of the PlotWindow
Python
mit
mretegan/crispy,mretegan/crispy
d01a5cdf950b7421703e2a018ee0306935e79555
sugar/activity/__init__.py
sugar/activity/__init__.py
import gtk from sugar.graphics.grid import Grid settings = gtk.settings_get_default() grid = Grid() sizes = 'gtk-large-toolbar=%d, %d' % (grid.dimension(1), grid.dimension(1)) settings.set_string_property('gtk-icon-sizes', sizes, '') settings.set_string_property('gtk-font-name', 'Sans 14', '') def get_default_type...
import gtk from sugar.graphics.grid import Grid settings = gtk.settings_get_default() grid = Grid() sizes = 'gtk-large-toolbar=%d, %d' % (grid.dimension(1), grid.dimension(1)) settings.set_string_property('gtk-icon-sizes', sizes, '') def get_default_type(activity_type): """Get the activity default type. It's ...
Move font size in the theme
Move font size in the theme
Python
lgpl-2.1
Daksh/sugar-toolkit-gtk3,puneetgkaur/backup_sugar_sugartoolkit,ceibal-tatu/sugar-toolkit-gtk3,gusDuarte/sugar-toolkit-gtk3,tchx84/debian-pkg-sugar-toolkit-gtk3,gusDuarte/sugar-toolkit-gtk3,samdroid-apps/sugar-toolkit-gtk3,sugarlabs/sugar-toolkit-gtk3,tchx84/debian-pkg-sugar-toolkit-gtk3,puneetgkaur/sugar-toolkit-gtk3,t...
2c2deea36a7e040244152a345eb672e62c519c76
pulse_actions/publisher.py
pulse_actions/publisher.py
""" This module is currently an experiment in publishing messages to pulse. It might become a real pulse publisher one day. """ import os import sys from pulse_actions.authentication import (get_user_and_password, AuthenticationError) from mozillapulse.publishers import GenericPublisher from mozillapulse.config ...
""" This module is currently an experiment in publishing messages to pulse. It might become a real pulse publisher one day. """ import os import sys from pulse_actions.authentication import ( get_user_and_password, AuthenticationError ) from mozillapulse.publishers import GenericPublisher from mozillapulse.c...
Handle failing to publish to pulse
Handle failing to publish to pulse
Python
mpl-2.0
armenzg/pulse_actions,mozilla/pulse_actions,adusca/pulse_actions
c3671ec17770d431a374b373a4e2b055ee1e3809
2019/aoc2019/day13.py
2019/aoc2019/day13.py
from typing import TextIO from aoc2019.intcode import Computer, read_program def part1(data: TextIO) -> int: computer = Computer(read_program(data)) computer.run() screen = {} while computer.output: x = computer.output.popleft() y = computer.output.popleft() val = computer....
import statistics from typing import TextIO, Tuple, Dict from aoc2019.intcode import Computer, read_program def render_screen(computer: Computer, screen: Dict[Tuple[int, int], int]): while computer.output: x = computer.output.popleft() y = computer.output.popleft() val = computer.output.p...
Implement 2019 day 13 part 2
Implement 2019 day 13 part 2
Python
mit
bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adv...
2e9b11d3dc6dcb8301870f9219878d18e5fafa71
conftest.py
conftest.py
import pytest def pytest_addoption(parser): _add_cuda_option(parser) def pytest_configure(config): _register_cuda_marker(config) def pytest_runtest_setup(item): _setup_cuda_marker(item) def _add_cuda_option(parser): parser.addoption("--cuda", action="store", metavar="LIMIT_NUM", default=-1, ...
import pytest import os def pytest_configure(config): _register_cuda_marker(config) def pytest_runtest_setup(item): _setup_cuda_marker(item) def _register_cuda_marker(config): config.addinivalue_line("markers", "cuda(num=1): mark tests needing the specified number of NVIDIA GPUs.") def _setup_cuda_ma...
Use XCHAINER_TEST_CUDA_LIMIT env int pytest
Use XCHAINER_TEST_CUDA_LIMIT env int pytest
Python
mit
hvy/chainer,hvy/chainer,ktnyt/chainer,niboshi/chainer,okuta/chainer,keisuke-umezawa/chainer,niboshi/chainer,chainer/chainer,chainer/chainer,jnishi/chainer,ktnyt/chainer,chainer/chainer,ktnyt/chainer,jnishi/chainer,keisuke-umezawa/chainer,chainer/chainer,pfnet/chainer,jnishi/chainer,tkerola/chainer,keisuke-umezawa/chain...
82dcd51c59eecccac4e7d9ee1dac754b27ff9ed2
mzalendo/feedback/views.py
mzalendo/feedback/views.py
from django.shortcuts import render_to_response from django.template import RequestContext from django.views.decorators.csrf import csrf_protect from models import Feedback from forms import FeedbackForm @csrf_protect def add(request): """Gather feedback for a page, and if it is ok show a thanks message and link ...
from django.shortcuts import render_to_response from django.template import RequestContext from django.views.decorators.csrf import csrf_protect from models import Feedback from forms import FeedbackForm import re @csrf_protect def add(request): """Gather feedback for a page, and if it is ok show a thanks messa...
Mark feedback comments starting with a html tag as spammy
Mark feedback comments starting with a html tag as spammy
Python
agpl-3.0
ken-muturi/pombola,mysociety/pombola,hzj123/56th,hzj123/56th,mysociety/pombola,ken-muturi/pombola,hzj123/56th,Hutspace/odekro,geoffkilpin/pombola,patricmutwiri/pombola,mysociety/pombola,patricmutwiri/pombola,patricmutwiri/pombola,hzj123/56th,Hutspace/odekro,ken-muturi/pombola,Hutspace/odekro,patricmutwiri/pombola,Hutsp...
23e809db71889cec7b2af03b978ecb339853fe51
satchless/cart/views.py
satchless/cart/views.py
from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect from django.views.generic.simple import direct_to_template from . import models from . import forms def cart(request, typ): cart = models.Cart.objects.get_or_create_from_request(request, typ) if request.method == 'POST': ...
from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect from django.shortcuts import render_to_response from django.template import RequestContext from . import models from . import forms def cart(request, typ): cart = models.Cart.objects.get_or_create_from_request(request, typ) ...
Allow prefixed templates for different cart types
Allow prefixed templates for different cart types
Python
bsd-3-clause
taedori81/satchless,fusionbox/satchless,fusionbox/satchless,fusionbox/satchless