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
a5beccfa3574f4fcb1b6030737b728e65803791f
numpy/array_api/_typing.py
numpy/array_api/_typing.py
""" This file defines the types for type annotations. These names aren't part of the module namespace, but they are used in the annotations in the function signatures. The functions in the module are only valid for inputs that match the given type annotations. """ __all__ = [ "Array", "Device", "Dtype", ...
""" This file defines the types for type annotations. These names aren't part of the module namespace, but they are used in the annotations in the function signatures. The functions in the module are only valid for inputs that match the given type annotations. """ __all__ = [ "Array", "Device", "Dtype", ...
Fix invalid parameter types used in `Dtype`
MAINT: Fix invalid parameter types used in `Dtype`
Python
bsd-3-clause
anntzer/numpy,charris/numpy,mattip/numpy,endolith/numpy,mhvk/numpy,charris/numpy,mhvk/numpy,jakirkham/numpy,seberg/numpy,endolith/numpy,pdebuyl/numpy,jakirkham/numpy,rgommers/numpy,seberg/numpy,numpy/numpy,rgommers/numpy,anntzer/numpy,charris/numpy,pdebuyl/numpy,endolith/numpy,mhvk/numpy,seberg/numpy,endolith/numpy,rgo...
e743bcddbc53d51142f3e1277919a3f65afaad90
tests/conftest.py
tests/conftest.py
import base64 import betamax import os credentials = [os.environ.get('GH_USER', 'foo').encode(), os.environ.get('GH_PASSWORD', 'bar').encode()] with betamax.Betamax.configure() as config: config.cassette_library_dir = 'tests/cassettes' record_mode = 'never' if os.environ.get('TRAVIS_GH3') else...
import base64 import betamax import os credentials = [os.environ.get('GH_USER', 'foo').encode(), os.environ.get('GH_PASSWORD', 'bar').encode()] with betamax.Betamax.configure() as config: config.cassette_library_dir = 'tests/cassettes' record_mode = 'never' if os.environ.get('TRAVIS_GH3') else...
Revert "For travis, let us print the mode"
Revert "For travis, let us print the mode" This reverts commit 0c8e9c36219214cf08b33c0ff1812e6cefa53353.
Python
bsd-3-clause
sigmavirus24/github3.py,agamdua/github3.py,christophelec/github3.py,jim-minter/github3.py,ueg1990/github3.py,degustaf/github3.py,balloob/github3.py,h4ck3rm1k3/github3.py,icio/github3.py,wbrefvem/github3.py,krxsky/github3.py,itsmemattchung/github3.py
166ca44e70221e35a8e0bd36b5b21ba51f7032ca
FAUSTPy/__init__.py
FAUSTPy/__init__.py
""" A set of classes used to dynamically wrap FAUST DSP programs in Python. This package defines three types: - PythonUI is an implementation of the UIGlue C struct. - FAUSTDsp wraps the DSP struct. - FAUST integrates the other two, sets up the CFFI environment (defines the data types and API) and compiles the FAUST...
#/usr/bin/env python """ A set of classes used to dynamically wrap FAUST DSP programs in Python. This package defines three types: - PythonUI is an implementation of the UIGlue C struct. - FAUSTDsp wraps the DSP struct. - FAUST integrates the other two, sets up the CFFI environment (defines the data types and API) ...
Add shebang line to package init file.
Add shebang line to package init file.
Python
mit
marcecj/faust_python
63a23acabd83cbf32c85ad667da0aed9ae0599e6
unitTestUtils/parseXML.py
unitTestUtils/parseXML.py
#!/usr/bin/python # -*- coding: utf-8 -*- from __future__ import print_function from xml.etree.ElementTree import ParseError import xml.etree.ElementTree as ET import glob import sys def eprint(*args, **kwargs): print(*args, file=sys.stderr, **kwargs) def parse(): for infile in glob.glob('*.xml'): tr...
#!/usr/bin/python # -*- coding: utf-8 -*- from __future__ import print_function from xml.etree.ElementTree import ParseError import xml.etree.ElementTree as ET import glob import sys def eprint(*args, **kwargs): print(*args, file=sys.stderr, **kwargs) def parse(): for infile in glob.glob('*.xml'): tr...
Add more verbose error to reporte on Travis parserXML.py
Add more verbose error to reporte on Travis parserXML.py
Python
apache-2.0
wkrzemien/j-pet-framework,wkrzemien/j-pet-framework,wkrzemien/j-pet-framework,wkrzemien/j-pet-framework,wkrzemien/j-pet-framework
1916d1effbad1a26b95594b909c30b3732df3580
polling_stations/apps/data_collection/management/commands/import_shape_shape.py
polling_stations/apps/data_collection/management/commands/import_shape_shape.py
""" Import COUNCIL """ import sys from data_collection.management.commands import BaseShpShpImporter class Command(BaseShpShpImporter): """ Imports the Polling Station data from COUNCIL """ council_id = 'your_councilid' districts_name = 'name_without_.shp' stations_name = 'your.shp' ...
""" Import COUNCIL """ import sys from data_collection.management.commands import BaseShpShpImporter class Command(BaseShpShpImporter): """ Imports the Polling Station data from COUNCIL """ council_id = 'your_councilid' districts_name = 'name_without_.shp' stations_name = 'your.shp' ...
Update Shape&Shape importer - shapes don't have named fields!
Update Shape&Shape importer - shapes don't have named fields!
Python
bsd-3-clause
DemocracyClub/UK-Polling-Stations,chris48s/UK-Polling-Stations,chris48s/UK-Polling-Stations,andylolz/UK-Polling-Stations,chris48s/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations,andylolz/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations,andylolz/UK-Polling-Stations
c1eafa32f9fafa859a0fcaf047f4a80b9bc52969
setup.py
setup.py
#!/usr/bin/env python import os from glob import glob from distutils.core import setup setup( name='whisper', version='0.9.10', url='https://launchpad.net/graphite', author='Chris Davis', author_email='chrismd@gmail.com', license='Apache Software License 2.0', description='Fixed size round-robin style ...
#!/usr/bin/env python import os from glob import glob from distutils.core import setup setup( name='whisper', version='0.9.10', url='https://launchpad.net/graphite', author='Chris Davis', author_email='chrismd@gmail.com', license='Apache Software License 2.0', description='Fixed size round-robin style ...
Add PyPI classifiers for python versions
Add PyPI classifiers for python versions
Python
apache-2.0
penpen/whisper,deniszh/whisper,graphite-server/whisper,alexandreboisvert/whisper,akbooer/whisper,graphite-project/whisper,cbowman0/whisper,piotr1212/whisper,kerlandsson/whisper,obfuscurity/whisper
1f5183c345444f35891927014d92510b66b96f5b
setup.py
setup.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from distutils.core import setup import pypandoc long_description = pypandoc.convert('README.md', 'rst') setup( name='robber', version='1.0.0', description='BDD / TDD assertion library for Python', long_description=long_description, author='Tao Liang',...
#!/usr/bin/env python # -*- coding: utf-8 -*- from distutils.core import setup setup( name='robber', version='1.0.1', description='BDD / TDD assertion library for Python', author='Tao Liang', author_email='tao@synapse-ai.com', url='https://github.com/vesln/robber.py', packages=[ 'ro...
Remove the dependency on pypandoc. It's unfortunate but we don't want to add dependency just for readability on pypi.
Remove the dependency on pypandoc. It's unfortunate but we don't want to add dependency just for readability on pypi.
Python
mit
vesln/robber.py,taoenator/robber.py
efaeb8fe4458cd6b214896ad72f3d41c25c23313
misc/python/botan/__init__.py
misc/python/botan/__init__.py
from _botan import * init = LibraryInitializer() class SymmetricKey(OctetString): pass class InitializationVector(OctetString): pass def Filter(name, key = None, iv = None, dir = None): if key != None and iv != None and dir != None: return make_filter(name, key, iv, dir) elif key != None and...
from _botan import * # Initialize the library when the module is imported init = LibraryInitializer() class SymmetricKey(OctetString): pass class InitializationVector(OctetString): pass def Filter(name, key = None, iv = None, dir = None): if key != None and iv != None and dir != None: return mak...
Remove an old version of the Filter() wrapper function
Remove an old version of the Filter() wrapper function
Python
bsd-2-clause
Rohde-Schwarz-Cybersecurity/botan,webmaster128/botan,Rohde-Schwarz-Cybersecurity/botan,randombit/botan,webmaster128/botan,randombit/botan,Rohde-Schwarz-Cybersecurity/botan,Rohde-Schwarz-Cybersecurity/botan,webmaster128/botan,randombit/botan,webmaster128/botan,webmaster128/botan,Rohde-Schwarz-Cybersecurity/botan,randomb...
3a37211f09c000f0fcb41ca076cb98b90bfae030
eb_sqs/urls.py
eb_sqs/urls.py
from __future__ import absolute_import, unicode_literals from django.conf.urls import url from eb_sqs.views import process_task app_name = 'eb_sqs' urlpatterns = [ url(r'^process$', process_task, name='process_task'), ]
from __future__ import absolute_import, unicode_literals from django.conf.urls import url from eb_sqs.views import process_task urlpatterns = [ url(r'^process$', process_task, name='process_task'), ]
Remove unnecessary global variable assignment
Remove unnecessary global variable assignment
Python
mit
cuda-networks/django-eb-sqs,cuda-networks/django-eb-sqs
1270c31dcf35c17a26a282605d2e04ffd2e8d985
tests/test_ftp.py
tests/test_ftp.py
from wex.url import URL expected_lines = [ b"FTP/1.0 200 OK\r\n", b"X-wex-url: ftp://anonymous:me@ftp.kernel.org/pub/site/README\r\n", b"\r\n", b"This directory contains files related to the operation of the\n", ] expected_content = b''.join(expected_lines) url = 'ftp://anonymous:me@ftp.kernel.org/pub...
from wex.url import URL url = 'ftp://anonymous:me@speedtest.tele2.net/1KB.zip' expected_lines = [ b"FTP/1.0 200 OK\r\n", b"X-wex-url: " + url + "\r\n", b"\r\n", ] expected_content = b''.join(expected_lines) def test_ftp_read(): readables = list(URL(url).get()) assert len(readables) == 1 r0 =...
Switch ftp server now ftp.kernel.org closed
Switch ftp server now ftp.kernel.org closed
Python
bsd-3-clause
eBay/wextracto,gilessbrown/wextracto,gilessbrown/wextracto,eBay/wextracto
749c1254a240053d2ca2abb1cc88d5eb7ae284eb
tests/test_tcv.py
tests/test_tcv.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Test for the tcv module """
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Test for the tcv module """ def test_placeholder(): """ Write real tests... """ assert True
Add an empty placeholder tests.
Add an empty placeholder tests.
Python
isc
wagdav/tcvpy
d1c1d257a3fb54c6acef4c66c8ed639f48a0c426
bibliopixel/control/artnet.py
bibliopixel/control/artnet.py
import collections, copy, queue from . import control from .. util import artnet_message, log, server_cache, udp QUEUE_TIMEOUT = 0.1 class ArtNet(control.ExtractedControl): def __init__(self, *args, ip_address, port=artnet_message.UDP_PORT, **kwds): super().__init__(*args, **kwds) self.address = ...
import collections, copy, queue from . import control from .. util import artnet_message, log, server_cache, udp QUEUE_TIMEOUT = 0.1 class ArtNet(control.ExtractedControl): def __init__(self, *args, ip_address, port=artnet_message.UDP_PORT, **kwds): super().__init__(*args, **kwds) self.address = ...
Remove test that crashes ArtNet receiver
Remove test that crashes ArtNet receiver
Python
mit
rec/BiblioPixel,ManiacalLabs/BiblioPixel,rec/BiblioPixel,ManiacalLabs/BiblioPixel,rec/BiblioPixel,ManiacalLabs/BiblioPixel,rec/BiblioPixel,ManiacalLabs/BiblioPixel
5cd66754dc4a53bf9e0631733541c2ed5e4be06e
pvextractor/tests/test_gui.py
pvextractor/tests/test_gui.py
import pytest from distutils.version import LooseVersion import matplotlib as mpl from ..gui import PVSlicer from .test_slicer import make_test_hdu try: import PyQt5 PYQT5OK = True except ImportError: PYQT5OK = False if LooseVersion(mpl.__version__) < LooseVersion('2'): MPLOK = True else: MPLO...
import numpy as np from ..gui import PVSlicer from .test_slicer import make_test_hdu def test_gui(): hdu = make_test_hdu() pv = PVSlicer(hdu, clim=(-0.02, 2)) pv.show(block=False) xy_data = np.array([[0.0, 0.1, 0.5, 1.0, 0.5], [0.0, 0.3, 0.4, 0.9, 1.4]]).T x, y = pv.ax...
Make GUI test more robust to HiDPI displays
Make GUI test more robust to HiDPI displays
Python
bsd-3-clause
radio-astro-tools/pvextractor,keflavich/pvextractor
72a5d74496d8cfd3d2216ac9b5f5ef2d4b054ed0
backend/loader/model/datafile.py
backend/loader/model/datafile.py
from dataitem import DataItem class DataFile(DataItem): def __init__(self, name, access, owner): super(DataFile, self).__init__(name, access, owner, "datafile") self.checksum = "" self.size = 0 self.location = "" self.mediatype = "" self.conditions = [] self....
from dataitem import DataItem class DataFile(DataItem): def __init__(self, name, access, owner): super(DataFile, self).__init__(name, access, owner, "datafile") self.checksum = "" self.size = 0 self.location = "" self.mediatype = "" self.conditions = [] self....
Add parent so we can track versions.
Add parent so we can track versions.
Python
mit
materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org
90d933a957509da4189b8f793e27ac563b73264b
reddit_adzerk/adzerkads.py
reddit_adzerk/adzerkads.py
from pylons import c, g from r2.lib.pages import Ads as BaseAds class Ads(BaseAds): def __init__(self): BaseAds.__init__(self) adzerk_test_srs = g.live_config.get("adzerk_test_srs") if adzerk_test_srs and c.site.name in adzerk_test_srs: if c.secure: self.ad_url...
from pylons import c, g from r2.lib.pages import Ads as BaseAds class Ads(BaseAds): def __init__(self): BaseAds.__init__(self) adzerk_test_srs = g.live_config.get("adzerk_test_srs") if adzerk_test_srs and c.site.name in adzerk_test_srs: url_key = "adzerk_https_url" if c.secure...
Use c.request_origin for frame origin.
Use c.request_origin for frame origin.
Python
bsd-3-clause
madbook/reddit-plugin-adzerk,madbook/reddit-plugin-adzerk,madbook/reddit-plugin-adzerk
d1c5e7971814d5aeedec11bb7610680a4c5a0000
text_processor.py
text_processor.py
from urllib.request import urlopen def fetch_words(): with urlopen('http://sixty-north.com/c/t.txt') as story: story_words = [] for line in story: line_words = line.decode('utf-8').split() for word in line_words: story_words.append(word) return story...
"""Retrieve and print words from a URL. Usage: python3 text_processor.py <URL> """ import sys from urllib.request import urlopen def fetch_words(url): """Fetch a list of words from a URL. Args: url: The URL of a UTF-8 text document. Returns: A UTF-8-decoded list of strings contain...
Document module with docstrings (Google format)
Document module with docstrings (Google format)
Python
mit
kentoj/python-fundamentals
de6dbe4fa15691cb1a7ec4077e6aaf0eca4e1d48
PRESUBMIT.py
PRESUBMIT.py
# Copyright (c) 2011 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. """Top-level presubmit script for GYP. See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts for more details about the presubmit...
# Copyright (c) 2011 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Top-level presubmit script for GYP. See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts for more details about the presubmit API built...
Fix the license header regex.
Fix the license header regex. Most of the files are attributed to Google Inc so I used this instead of Chromium Authors. R=mark@chromium.org BUG= TEST= Review URL: http://codereview.chromium.org/7108074
Python
bsd-3-clause
witwall/gyp,witwall/gyp,witwall/gyp,witwall/gyp,witwall/gyp
52a95cb48d0829d864d25b5e8c380c0e58d51b16
coaster/docflow.py
coaster/docflow.py
# -*- coding: utf-8 -*- from __future__ import absolute_import import docflow from werkzeug.exceptions import Forbidden __all__ = ['WorkflowStateException', 'WorkflowTransitionException', 'WorkflowPermissionException', 'WorkflowState', 'WorkflowStateGroup', 'DocumentWorkflow'] class WorkflowStateException(d...
# -*- coding: utf-8 -*- from __future__ import absolute_import from flask import g import docflow from werkzeug.exceptions import Forbidden __all__ = ['WorkflowStateException', 'WorkflowTransitionException', 'WorkflowPermissionException', 'WorkflowState', 'WorkflowStateGroup', 'InteractiveTransition', 'Docume...
Update for Docflow 0.3.2 and PermissionMixin
Update for Docflow 0.3.2 and PermissionMixin
Python
bsd-2-clause
hasgeek/coaster
293a1f63b7a3011c36a0cba71874b92be460e1aa
app/views.py
app/views.py
from app import app from app.models import Post from flask import render_template @app.route('/') @app.route('/page/<int:page>') def blog(page=1): """View the blog.""" posts = Post.query.filter_by(visible=True) \ .order_by(Post.published.desc()) if posts: pagination = posts.p...
from flask import render_template, send_file from app import app from app.models import Post @app.route('/') @app.route('/page/<int:page>') def blog(page=1): """View the blog.""" posts = Post.query.filter_by(visible=True) \ .order_by(Post.published.desc()) if posts: paginati...
Add route for admin panel
Add route for admin panel
Python
mit
thebitstick/Flask-Blog,thebitstick/Flask-Blog
cd1edf946fcf8b22b5f78f4a1db393b777951527
website/files/utils.py
website/files/utils.py
from osf.models.base import generate_object_id def copy_files(src, target_node, parent=None, name=None): """Copy the files from src to the target node :param Folder src: The source to copy children from :param Node target_node: The node to copy files to :param Folder parent: The parent of to attach th...
def copy_files(src, target_node, parent=None, name=None): """Copy the files from src to the target node :param Folder src: The source to copy children from :param Node target_node: The node to copy files to :param Folder parent: The parent of to attach the clone of src to, if applicable """ ass...
Use clone() method from BaseModel to copy most recent fileversion
Use clone() method from BaseModel to copy most recent fileversion
Python
apache-2.0
adlius/osf.io,felliott/osf.io,HalcyonChimera/osf.io,mattclark/osf.io,HalcyonChimera/osf.io,pattisdr/osf.io,mfraezz/osf.io,cslzchen/osf.io,caseyrollins/osf.io,mfraezz/osf.io,saradbowman/osf.io,pattisdr/osf.io,aaxelb/osf.io,aaxelb/osf.io,adlius/osf.io,brianjgeiger/osf.io,aaxelb/osf.io,cslzchen/osf.io,cslzchen/osf.io,case...
659036918e2c90b47c83c640eef62eaeec42b35a
opps/contrib/notifications/models.py
opps/contrib/notifications/models.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from django.db import models from django.utils.translation import ugettext_lazy as _ from opps.core.models import Publishable from opps.db import Db NOTIFICATION_TYPE = ( (u'json', _(u'JSON')), (u'text', _(u'Text')), (u'html', _(u'HTML')), ) cla...
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from django.db import models from django.utils.translation import ugettext_lazy as _ from opps.core.models import Publishable from opps.db import Db NOTIFICATION_TYPE = ( (u'json', _(u'JSON')), (u'text', _(u'Text')), (u'html', _(u'HTML')), ) cla...
Update save Notification, save in nosql database
Update save Notification, save in nosql database
Python
mit
williamroot/opps,opps/opps,jeanmask/opps,jeanmask/opps,YACOWS/opps,williamroot/opps,YACOWS/opps,YACOWS/opps,opps/opps,jeanmask/opps,williamroot/opps,williamroot/opps,opps/opps,jeanmask/opps,opps/opps,YACOWS/opps
632470cad13b7bfe88c52d4aafd9cbf9fff37b07
rasterio/tool.py
rasterio/tool.py
import code import collections import logging import sys import numpy import rasterio logger = logging.getLogger('rasterio') Stats = collections.namedtuple('Stats', ['min', 'max', 'mean']) def main(banner, dataset): def show(source): """Show a raster using matplotlib. The raster may be eith...
import code import collections import logging import sys import numpy import rasterio logger = logging.getLogger('rasterio') Stats = collections.namedtuple('Stats', ['min', 'max', 'mean']) def main(banner, dataset): def show(source, cmap='gray'): """Show a raster using matplotlib. The raste...
Add colormap option to show().
Add colormap option to show().
Python
bsd-3-clause
perrygeo/rasterio,perrygeo/rasterio,clembou/rasterio,johanvdw/rasterio,njwilson23/rasterio,clembou/rasterio,clembou/rasterio,johanvdw/rasterio,njwilson23/rasterio,snorfalorpagus/rasterio,brendan-ward/rasterio,kapadia/rasterio,youngpm/rasterio,kapadia/rasterio,sgillies/rasterio,kapadia/rasterio,brendan-ward/rasterio,joh...
841d89ea9199bfad94c74b75f2bab5ae2690ede4
numba/tests/broken_issues/test_closure_modulo.py
numba/tests/broken_issues/test_closure_modulo.py
from numba import autojit import numpy as np print np.zeros(10).dtype @autojit def closure_modulo(a, b): c = np.zeros(10) @jit('f8[:]()') def foo(): c[0] = a % b return c return foo() print closure_modulo(100, 48)
from numba import autojit @autojit def closure_modulo(a, b): @jit('int32()') def foo(): return a % b return foo() print closure_modulo(100, 48)
Simplify and cleanup previous commit.
Simplify and cleanup previous commit.
Python
bsd-2-clause
ssarangi/numba,stefanseefeld/numba,pitrou/numba,pombredanne/numba,cpcloud/numba,stefanseefeld/numba,gdementen/numba,seibert/numba,sklam/numba,pombredanne/numba,IntelLabs/numba,IntelLabs/numba,numba/numba,gdementen/numba,ssarangi/numba,pombredanne/numba,shiquanwang/numba,stuartarchibald/numba,stonebig/numba,IntelLabs/nu...
845fe88451dfc8e3505d4481e8160344942d3fdf
telethon/tl/patched/__init__.py
telethon/tl/patched/__init__.py
from .. import types, alltlobjects from ..custom.message import Message as _Message class MessageEmpty(_Message, types.MessageEmpty): pass types.MessageEmpty = MessageEmpty alltlobjects.tlobjects[MessageEmpty.CONSTRUCTOR_ID] = MessageEmpty class MessageService(_Message, types.MessageService): pass types.Mes...
from .. import types, alltlobjects from ..custom.message import Message as _Message class MessageEmpty(_Message, types.MessageEmpty): pass types.MessageEmpty = MessageEmpty alltlobjects.tlobjects[MessageEmpty.CONSTRUCTOR_ID] = MessageEmpty class MessageService(_Message, types.MessageService): pass types.Mes...
Fix definition typo in patched module
Fix definition typo in patched module
Python
mit
LonamiWebs/Telethon,LonamiWebs/Telethon,LonamiWebs/Telethon,LonamiWebs/Telethon
7906153b4718f34ed31c193a8e80b171e567209c
go/routers/keyword/view_definition.py
go/routers/keyword/view_definition.py
from django import forms from go.router.view_definition import RouterViewDefinitionBase, EditRouterView class KeywordForm(forms.Form): keyword = forms.CharField() target_endpoint = forms.CharField() class BaseKeywordFormSet(forms.formsets.BaseFormSet): @staticmethod def initial_from_config(data): ...
from django import forms from go.router.view_definition import RouterViewDefinitionBase, EditRouterView class KeywordForm(forms.Form): keyword = forms.CharField() target_endpoint = forms.CharField() class BaseKeywordFormSet(forms.formsets.BaseFormSet): @staticmethod def initial_from_config(data): ...
Remove unnecessary and broken DELETE check.
Remove unnecessary and broken DELETE check.
Python
bsd-3-clause
praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go
25ec9d2ee99437d0b68f53c9a4f1f5bc72ecf71f
app/utils.py
app/utils.py
def get_or_create(model, **kwargs): """ Returns an instance of model and whether or not it already existed in a tuple. """ instance = model.query.filter_by(**kwargs).first() if instance: return instance, False else: instance = model(**kwargs) return instance, True
from urllib.parse import urlparse, urljoin from flask import request def get_or_create(model, **kwargs): """ Returns an instance of model and whether or not it already existed in a tuple. """ instance = model.query.filter_by(**kwargs).first() if instance: return instance, False else: in...
Add utility function for checking URL safety
Add utility function for checking URL safety
Python
mit
Encrylize/MyDictionary,Encrylize/MyDictionary,Encrylize/MyDictionary
7d761d538c501cefb5e6acf62d3f0e945584b5ec
src/django_integration.py
src/django_integration.py
# -*- coding: utf-8 -*- # Libraries from datetime import datetime # Django stuff from Instanssi.kompomaatti.misc.events import get_upcoming from Instanssi.screenshow.models import IRCMessage from Instanssi.kompomaatti.models import Event def django_get_event(event_id): try: return Event.objects.get(pk=e...
# -*- coding: utf-8 -*- # Libraries from django.utils import timezone # Django stuff from Instanssi.kompomaatti.misc.events import get_upcoming from Instanssi.screenshow.models import IRCMessage from Instanssi.kompomaatti.models import Event def django_get_event(event_id): try: return Event.objects.get(...
Use timezone library for dates
Use timezone library for dates
Python
mit
Instanssi/KompomaattiBot
91d6021fb0db6052570f1a0305a141e1af13b6e3
localeurl/models.py
localeurl/models.py
from django.conf import settings from django.core import urlresolvers from django.utils import translation from localeurl import utils def reverse(*args, **kwargs): reverse_kwargs = kwargs.get('kwargs', {}) locale = utils.supported_language(reverse_kwargs.pop('locale', translation.get_language())) ...
from django.conf import settings from django.core import urlresolvers from django.utils import translation from localeurl import utils def reverse(*args, **kwargs): reverse_kwargs = kwargs.get('kwargs', {}) if reverse_kwargs!=None: locale = utils.supported_language(reverse_kwargs.pop('locale', ...
Handle situation when kwargs is None
Handle situation when kwargs is None
Python
mit
carljm/django-localeurl,gonnado/django-localeurl,extertioner/django-localeurl
d367f32d6b8269d402305714eb95fe708f8e2b0d
junction/conferences/serializers.py
junction/conferences/serializers.py
from rest_framework import serializers from .models import Conference, ConferenceVenue, Room class ConferenceSerializer(serializers.HyperlinkedModelSerializer): status = serializers.CharField(source='get_status_display') class Meta: model = Conference fields = ('id', 'name', 'slug', 'descrip...
from rest_framework import serializers from .models import Conference, ConferenceVenue, Room class ConferenceSerializer(serializers.HyperlinkedModelSerializer): status = serializers.CharField(source='get_status_display') class Meta: model = Conference fields = ('id', 'name', 'slug', 'descrip...
Add latitude and longitude in api
Add latitude and longitude in api
Python
mit
ChillarAnand/junction,praba230890/junction,nava45/junction,pythonindia/junction,ChillarAnand/junction,ChillarAnand/junction,pythonindia/junction,nava45/junction,nava45/junction,farhaanbukhsh/junction,nava45/junction,praba230890/junction,farhaanbukhsh/junction,pythonindia/junction,ChillarAnand/junction,pythonindia/junct...
101784851bf8c7add95bba7dbb4277114b7a3098
refugeedata/mailings/tasks.py
refugeedata/mailings/tasks.py
from django_rq import job from .. import utils @job def send_sms(to, body): utils.send_sms(to=to, body=body)
from django_rq import job from .. import utils @job def send_sms(to, body): for number in to: send_single_sms.delay([to], body) @job def send_single_sms(to, body): utils.send_sms(to=to, body=body)
Split SMS sending into multiple jobs (to get around Heroku timeout)
Split SMS sending into multiple jobs (to get around Heroku timeout)
Python
mit
ukch/refugeedata,ukch/refugeedata,ukch/refugeedata,ukch/refugeedata
7ffe4749d1c8f5315775a50a9f7b6eb632c6a258
scorecard/tests/test_views.py
scorecard/tests/test_views.py
import json from django.test import ( TransactionTestCase, Client, override_settings, ) from . import ( import_data, ) from .resources import ( GeographyResource, MunicipalityProfileResource, MedianGroupResource, RatingCountGroupResource, ) @override_settings( SITE_ID=2, STAT...
import json from infrastructure.models import FinancialYear from django.test import ( TransactionTestCase, Client, override_settings, ) from . import ( import_data, ) from .resources import ( GeographyResource, MunicipalityProfileResource, MedianGroupResource, RatingCountGroupResource,...
Create a financial year to test with
Create a financial year to test with
Python
mit
Code4SA/municipal-data,Code4SA/municipal-data,Code4SA/municipal-data,Code4SA/municipal-data
54d88ef6ebfacbb2924ca9bc94935ed81fc90244
migrations/versions/1815829d365_.py
migrations/versions/1815829d365_.py
"""empty message Revision ID: 1815829d365 Revises: 3fcddd64a72 Create Date: 2016-02-09 17:58:47.362133 """ # revision identifiers, used by Alembic. revision = '1815829d365' down_revision = '3fcddd64a72' from alembic import op import sqlalchemy as sa def upgrade(): ### commands auto generated by Alembic - plea...
"""empty message Revision ID: 1815829d365 Revises: 3fcddd64a72 Create Date: 2016-02-09 17:58:47.362133 """ # revision identifiers, used by Alembic. revision = '1815829d365' down_revision = '3fcddd64a72' from alembic import op import sqlalchemy as sa def upgrade(): ### commands auto generated by Alembic - plea...
Fix index for title without geo abr
Fix index for title without geo abr
Python
mit
LandRegistry/system-of-record,LandRegistry/system-of-record
c87f75334aa7253ad209bdd4d88c2429723e51d1
admin/desk/urls.py
admin/desk/urls.py
from django.conf.urls import url from admin.desk import views urlpatterns = [ url(r'^$', views.DeskCaseList.as_view(), name='cases'), url(r'^customer/(?P<user_id>[a-z0-9]+)/$', views.DeskCustomer.as_view(), name='customer'), url(r'^cases/(?P<user_id>[a-z0-9]+)/$', views.DeskCaseList.as_view(), ...
from django.conf.urls import url from admin.desk import views urlpatterns = [ url(r'^customer/(?P<user_id>[a-z0-9]+)/$', views.DeskCustomer.as_view(), name='customer'), url(r'^cases/(?P<user_id>[a-z0-9]+)/$', views.DeskCaseList.as_view(), name='user_cases'), ]
Remove unused bare desk URL
Remove unused bare desk URL
Python
apache-2.0
hmoco/osf.io,aaxelb/osf.io,laurenrevere/osf.io,pattisdr/osf.io,caneruguz/osf.io,CenterForOpenScience/osf.io,baylee-d/osf.io,HalcyonChimera/osf.io,brianjgeiger/osf.io,saradbowman/osf.io,chrisseto/osf.io,cwisecarver/osf.io,mfraezz/osf.io,monikagrabowska/osf.io,leb2dg/osf.io,acshi/osf.io,crcresearch/osf.io,alexschiller/os...
a2e63f05d7992058b09a3d8e72b91e022cb94ef1
core/urls.py
core/urls.py
from django.conf.urls import include, url from django.views.generic import TemplateView from tastypie.api import Api from .api import ImageResource, ThumbnailResource, PinResource, UserResource v1_api = Api(api_name='v1') v1_api.register(ImageResource()) v1_api.register(ThumbnailResource()) v1_api.register(PinResour...
from django.conf.urls import include, url from django.views.generic import TemplateView from tastypie.api import Api from .api import ImageResource, ThumbnailResource, PinResource, UserResource v1_api = Api(api_name='v1') v1_api.register(ImageResource()) v1_api.register(ThumbnailResource()) v1_api.register(PinResour...
Correct the name for specified pin
Fix: Correct the name for specified pin
Python
bsd-2-clause
pinry/pinry,lapo-luchini/pinry,lapo-luchini/pinry,pinry/pinry,pinry/pinry,pinry/pinry,lapo-luchini/pinry,lapo-luchini/pinry
9a5dc452f181fac45a8c0efcd3f70e116efefc2a
erpnext/patches/v7_0/setup_account_table_for_expense_claim_type_if_exists.py
erpnext/patches/v7_0/setup_account_table_for_expense_claim_type_if_exists.py
from __future__ import unicode_literals import frappe def execute(): frappe.reload_doc("hr", "doctype", "expense_claim_type") for expense_claim_type in frappe.get_all("Expense Claim Type", fields=["name", "default_account"]): if expense_claim_type.default_account: doc = frappe.get_doc("Expense Claim Type", ex...
from __future__ import unicode_literals import frappe def execute(): frappe.reload_doc("hr", "doctype", "expense_claim_type") frappe.reload_doc("hr", "doctype", "expense_claim_account") for expense_claim_type in frappe.get_all("Expense Claim Type", fields=["name", "default_account"]): if expense_claim_type.defa...
Patch fixed for expense claim type
Patch fixed for expense claim type
Python
agpl-3.0
njmube/erpnext,indictranstech/erpnext,geekroot/erpnext,geekroot/erpnext,gsnbng/erpnext,Aptitudetech/ERPNext,indictranstech/erpnext,njmube/erpnext,indictranstech/erpnext,njmube/erpnext,geekroot/erpnext,geekroot/erpnext,indictranstech/erpnext,njmube/erpnext,gsnbng/erpnext,gsnbng/erpnext,gsnbng/erpnext
b89982f7b66b46f4338ff2758219d7419e36d6ba
lms/djangoapps/api_manager/management/commands/migrate_orgdata.py
lms/djangoapps/api_manager/management/commands/migrate_orgdata.py
import json from django.contrib.auth.models import Group from django.core.management.base import BaseCommand from api_manager.models import GroupProfile, Organization class Command(BaseCommand): """ Migrates legacy organization data and user relationships from older Group model approach to newer concrete Org...
import json from django.contrib.auth.models import Group from django.core.management.base import BaseCommand from api_manager.models import GroupProfile, Organization class Command(BaseCommand): """ Migrates legacy organization data and user relationships from older Group model approach to newer concrete Org...
Tweak to migration in order to accomodate old names for data fields and allow for if data fields were not present
Tweak to migration in order to accomodate old names for data fields and allow for if data fields were not present
Python
agpl-3.0
edx-solutions/edx-platform,edx-solutions/edx-platform,edx-solutions/edx-platform,edx-solutions/edx-platform
3d1edf98284979ae8eade5804e44fb312bece1b0
sir/schema/__init__.py
sir/schema/__init__.py
# Copyright (c) 2014 Wieland Hoffmann # License: MIT, see LICENSE for details from mbdata import models from . import modelext from .searchentities import SearchEntity as E, SearchField as F SearchRecording = E(modelext.CustomRecording, [ F("mbid", "gid"), F("recording", "name"), F("arid", "artist_credit....
# Copyright (c) 2014 Wieland Hoffmann # License: MIT, see LICENSE for details from mbdata import models from . import modelext from .searchentities import SearchEntity as E, SearchField as F SearchRecording = E(modelext.CustomRecording, [ F("mbid", "gid"), F("recording", "name"), F("arid", "artist_credit....
Add missing release group fields
schema: Add missing release group fields
Python
mit
jeffweeksio/sir
3141b73ddeb14184062ab5ff4436ebb87de02253
dayonetools/services/__init__.py
dayonetools/services/__init__.py
"""Common services code""" from datetime import datetime import importlib AVAILABLE_SERVICES = ['habit_list', 'idonethis', 'nikeplus'] SERVICES_PKG = 'dayonetools.services' def get_service_module(service_name): """Import given service from dayonetools.services package""" module = '%s.%s' % (SERVICES_PKG, s...
"""Common services code""" AVAILABLE_SERVICES = ['habit_list', 'idonethis', 'nikeplus'] def get_service_module(service_name): """Import given service from dayonetools.services package""" import importlib services_pkg = 'dayonetools.services' module = '%s.%s' % (services_pkg, service_name) retur...
Move some imports internal so importing services package is not so cluttered
Move some imports internal so importing services package is not so cluttered
Python
mit
durden/dayonetools
93ea521678c283d8211aed9ca88db6c5dc068362
process_pic.py
process_pic.py
from pic import Picture from path import Path import argparse, json parser = argparse.ArgumentParser( description= "Process the picture or the directory, given the json config file") parser.add_argument("path", help="Path for the picture or the directory") parser.add_argument( "-n", "--nb_faces", ty...
from pic import Picture from path import Path import argparse parser = argparse.ArgumentParser( description= "Process the picture or the directory, given the json config file") parser.add_argument("path", help="Path for the picture or the directory") parser.add_argument( "-n", "--nb_faces", type=int...
Add a function to read json config files
Add a function to read json config files
Python
mit
Dixneuf19/fuzzy-octo-disco
4218d2a4d711f5a516423b1f4aa2685fc5a456b3
app/brain/user_management/account_updater.py
app/brain/user_management/account_updater.py
from flask_login import current_user from app.brain.user_management.change_password_result import ChangePasswordResult from app.brain.utilities import hash_password class AccountUpdater(object): @staticmethod def change_password(old_password, new_password, confirm_password): if new_password != confir...
from flask_login import current_user from app.brain.user_management.change_password_result import ChangePasswordResult from app.brain.utilities import hash_password from app.service import UsersService class AccountUpdater(object): @staticmethod def change_password(old_password, new_password, confirm_passwor...
Put in call to to UsersService to actually change password
Put in call to to UsersService to actually change password
Python
mit
pbraunstein/trackercise,pbraunstein/trackercise,pbraunstein/trackercise,pbraunstein/trackercise,pbraunstein/trackercise
88238ca8a0c3169e9350434ecd517eafdb118b88
pybinding/greens.py
pybinding/greens.py
import numpy as np import _pybinding from .results import LDOSpoint __all__ = ['Greens', 'make_kpm'] class Greens: def __init__(self, impl: _pybinding.Greens): self.impl = impl def calc_ldos(self, energy: np.ndarray, broadening: float, position: tuple, sublattice: int=-1): return LDOSpoint(...
import numpy as np import _pybinding from .results import LDOSpoint __all__ = ['Greens', 'make_kpm'] class Greens: def __init__(self, impl: _pybinding.Greens): self.impl = impl def report(self, shortform=False): return self.impl.report(shortform) def calc_ldos(self, energy: np.ndarray,...
Add report() method to Greens
Add report() method to Greens
Python
bsd-2-clause
dean0x7d/pybinding,MAndelkovic/pybinding,MAndelkovic/pybinding,dean0x7d/pybinding,MAndelkovic/pybinding,dean0x7d/pybinding
63cf6f6228490c9944711106cd134254eafac3ca
regressors/plots.py
regressors/plots.py
# -*- coding: utf-8 -*- """This module contains functions for making plots relevant to regressors.""" from __future__ import print_function from __future__ import division from __future__ import absolute_import from __future__ import unicode_literals
# -*- coding: utf-8 -*- """This module contains functions for making plots relevant to regressors.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import matplotlib.pyplot as plt import seaborn.apionly as sns from ...
Add function to make residuals plot
Add function to make residuals plot
Python
isc
nsh87/regressors
61cebe12c001bb42350d8e9e99a7fa7d26fc7667
openedx/stanford/lms/lib/courseware_search/lms_filter_generator.py
openedx/stanford/lms/lib/courseware_search/lms_filter_generator.py
""" Custom override of SearchFilterGenerator to use course tiles for discovery search. """ from search.filter_generator import SearchFilterGenerator from branding_stanford.models import TileConfiguration from lms.lib.courseware_search.lms_filter_generator import LmsSearchFilterGenerator class TileSearchFilterGenerat...
""" Custom override of SearchFilterGenerator to use course tiles for discovery search. """ from search.filter_generator import SearchFilterGenerator from branding_stanford.models import TileConfiguration from lms.lib.courseware_search.lms_filter_generator import LmsSearchFilterGenerator class TileSearchFilterGenerat...
Use stanford search logic only if configured
Use stanford search logic only if configured
Python
agpl-3.0
Stanford-Online/edx-platform,Stanford-Online/edx-platform,Stanford-Online/edx-platform,Stanford-Online/edx-platform
7e71e011fc4266b1edf21a0028cf878a71ab23fe
PyOpenWorm/plot.py
PyOpenWorm/plot.py
from PyOpenWorm import * class Plot(DataObject): """ Object for storing plot data in PyOpenWorm. Must be instantiated with a 2D list of coordinates. """ def __init__(self, data=False, *args, **kwargs): DataObject.__init__(self, **kwargs) Plot.DatatypeProperty('_data_string', self...
from PyOpenWorm import * class Plot(DataObject): """ Object for storing plot data in PyOpenWorm. Must be instantiated with a 2D list of coordinates. """ def __init__(self, data=False, *args, **kwargs): DataObject.__init__(self, **kwargs) Plot.DatatypeProperty('_data_string', self...
Add data setter and getter for Plot
Add data setter and getter for Plot
Python
mit
gsarma/PyOpenWorm,openworm/PyOpenWorm,openworm/PyOpenWorm,gsarma/PyOpenWorm
d080871e248cdf457fd1ff0023b5a651456d5b0b
openfisca_senegal/survey_scenarios.py
openfisca_senegal/survey_scenarios.py
# -*- coding: utf-8 -*- from openfisca_senegal import CountryTaxBenefitSystem as SenegalTaxBenefitSystem from openfisca_survey_manager.scenarios import AbstractSurveyScenario class SenegalSurveyScenario(AbstractSurveyScenario): id_variable_by_entity_key = dict( famille = 'id_famille', ) role...
# -*- coding: utf-8 -*- from openfisca_senegal import CountryTaxBenefitSystem as SenegalTaxBenefitSystem from openfisca_survey_manager.scenarios import AbstractSurveyScenario class SenegalSurveyScenario(AbstractSurveyScenario): id_variable_by_entity_key = dict( famille = 'id_famille', ) role...
Fix survey_scenario (use core v20 syntax)
Fix survey_scenario (use core v20 syntax)
Python
agpl-3.0
openfisca/senegal
d7b89cf5e8a0102034b0d9ed7f28fbe7fb0bc167
cartoframes/viz/helpers/color_category_layer.py
cartoframes/viz/helpers/color_category_layer.py
from __future__ import absolute_import from ..layer import Layer def color_category_layer(source, value, top=11, palette='bold', title='', othersLabel='Others'): return Layer( source, style={ 'point': { 'color': 'ramp(top(${0}, {1}), {2})'.format(value, top, palette) ...
from __future__ import absolute_import from ..layer import Layer def color_category_layer(source, value, top=11, palette='bold', title=''): return Layer( source, style={ 'point': { 'color': 'ramp(top(${0}, {1}), {2})'.format(value, top, palette) }, ...
Use fixed value in the helper
Use fixed value in the helper
Python
bsd-3-clause
CartoDB/cartoframes,CartoDB/cartoframes
c39e824119498fb6d669367fb53249b609edbaf2
main.py
main.py
import requests import os import shutil client_id = '' # Imgur application Client ID, fill this in. directory_name = 'Imgur Albums\\' # Directory for the images to be stored def scrape(album_id): ''' (str) -> list of str Given an Imgur album ID, scrapes all the images within the album into a folder. Re...
import requests import os import shutil client_id = '' # Imgur application Client ID, fill this in. directory_name = 'Imgur Albums\\' # Directory for the images to be stored def scrape(album_id): ''' (str) -> list of str Given an Imgur album ID, scrapes all the images within the album into a folder. Re...
Raise exception instead of returnning it
Raise exception instead of returnning it
Python
mit
kevinleung987/Imgur-Album-Scraper
8f84ce069159cb7d0dfb95a2a28f992a8a4f3556
client.py
client.py
import threading import select class Client(object): def __init__(self, sock, address, host): self.socket = sock self.server = host self.address = address self.connected = True self.exit_request = False self.thread = ClientThread(self) self.thread.start() ...
import threading import select class Client(object): def __init__(self, sock, address, host): self.socket = sock self.server = host self.address = address self.connected = True self.exit_request = False self.thread = ClientThread(self) self.thread.start() ...
Add on_receive and send methods.
Add on_receive and send methods. on_receive method is called when a new data is got. send method is used to send data to the client.
Python
mit
Mariusz-v7/WebSocketServer-Python-
2dde683b0a43a6339e446e37aab2726aaca65d83
config.py
config.py
# Screen size WIDTH = 320 HEIGHT = 240 SCREEN_SIZE = (WIDTH, HEIGHT) # Update delay in ms DELAY = 100 ALIVE_IMG_PATH="data/alive.png" DEAD_IMG_PATH="data/dead.png" CURSOR_DEAD_IMG_PATH="data/cursor.png" CURSOR_ALIVE_IMG_PATH="data/cursor_alive.png" ALIVE_IMG = None DEAD_IMG = None
# Screen size WIDTH = 320 HEIGHT = 240 SCREEN_SIZE = (WIDTH, HEIGHT) # Update delay in ms # On ETN it's already pretty slow DELAY = 0 ALIVE_IMG_PATH="data/alive.png" DEAD_IMG_PATH="data/dead.png" CURSOR_DEAD_IMG_PATH="data/cursor.png" CURSOR_ALIVE_IMG_PATH="data/cursor_alive.png" ALIVE_IMG = None DEAD_IMG = None
Set delay to 0, because ETN is slow.
Set delay to 0, because ETN is slow.
Python
mit
dzeban/PyGameOfLife
dfca6054fd32c0904bc027dcddb347c378adf954
dumper/file_uploader.py
dumper/file_uploader.py
import ftplib import ntpath import logging import urllib.parse import win32clipboard class FileUploader: def __init__(self, config): self._host = config['Server']['host'] self._user = config['Server']['user'] self._passwd = config['Server']['password'] self._path =...
import ftplib import ntpath import logging import urllib.parse import win32clipboard class FileUploader: def __init__(self, config): self._host = config['Server']['host'] self._user = config['Server']['user'] self._passwd = config['Server']['password'] self._path =...
Add copy url to clipboard setting
Add copy url to clipboard setting
Python
mit
yschua/dumper
93b1f8e67b1154fd595a938ca41877eb76c7e995
lcd.py
lcd.py
from telnetlib import Telnet import time tn = Telnet('192.168.1.15', 13666, None) #tn.interact() tn.write("hello\n") tn.write("screen_add s1\n") tn.write("screen_set s1 -priority 1\n") tn.write("widget_add s1 w1 string\n") tn.write("widget_add s1 w2 string\n") tn.write("widget_set s1 w1 1 1 {It is a truth u}\n") tn.w...
#!/usr/bin/env python from telnetlib import Telnet import time import sys tn = Telnet('192.168.1.15', 13666, None) pipe_contents = sys.stdin.read() pipe_contents = pipe_contents.replace('\n', ' ') tn.write("hello\n") tn.write("screen_add s1\n") tn.write("screen_set s1 -priority 1\n") tn.write("widget_add s1 w1 strin...
Read standard input instead of hard-coded strings.
Read standard input instead of hard-coded strings.
Python
mit
zimolzak/Raspberry-Pi-newbie,zimolzak/Raspberry-Pi-newbie,zimolzak/Raspberry-Pi-newbie,zimolzak/Raspberry-Pi-newbie,zimolzak/Raspberry-Pi-newbie
b4cefb5f1a5541b9b7312878790f6fe65412e010
rst2pdf/utils.py
rst2pdf/utils.py
#$HeadURL$ #$LastChangedDate$ #$LastChangedRevision$ import sys from reportlab.platypus import PageBreak, Spacer from flowables import * import shlex from log import log def parseRaw (data): '''Parse and process a simple DSL to handle creation of flowables. Supported (can add others on request): ...
# -*- coding: utf-8 -*- #$HeadURL$ #$LastChangedDate$ #$LastChangedRevision$ import sys from reportlab.platypus import PageBreak, Spacer from flowables import * import shlex from log import log def parseRaw (data): '''Parse and process a simple DSL to handle creation of flowables. Supported (can...
Fix encoding (thanks to Yasushi Masuda)
Fix encoding (thanks to Yasushi Masuda)
Python
mit
rafaelmartins/rst2pdf,rafaelmartins/rst2pdf
61c6c2687af9de1d5ccded1f1cb866a7638d8c31
tests/test_director.py
tests/test_director.py
from pydirections.director import Director from unittest import TestCase class TestModeValidity(TestCase): def test_invalid_mode(self): """ Tests the is_valid_mode function for an invalid input """ default_error_message = "The mode: {0} is invalid" invalid_mode = "flying" self.assertFalse(Director.is_...
from pydirections.director import Director from unittest import TestCase import re class TestModeValidity(TestCase): def test_invalid_mode(self): """ Tests the is_valid_mode function for an invalid input """ default_error_message = "The mode: {0} is invalid" invalid_mode = "flying" self.assertFalse(Di...
Add tests for data pre-processing in fetch_directions
Add tests for data pre-processing in fetch_directions
Python
apache-2.0
apranav19/pydirections
a3330105ca36ec758723e2f456ed56e107afec9e
textblob/exceptions.py
textblob/exceptions.py
# -*- coding: utf-8 -*- MISSING_CORPUS_MESSAGE = """ Looks like you are missing some required data for this feature. To download the necessary data, simply run curl https://raw.github.com/sloria/TextBlob/master/download_corpora.py | python Or use the NLTK downloader to download the missing data: http://nltk.org...
# -*- coding: utf-8 -*- MISSING_CORPUS_MESSAGE = """ Looks like you are missing some required data for this feature. To download the necessary data, simply run python -m textblob.download_corpora Or use the NLTK downloader to download the missing data: http://nltk.org/data.html If this doesn't fix the problem, ...
Fix download command in error message
Fix download command in error message
Python
mit
adelq/TextBlob,IrisSteenhout/TextBlob,freakynit/TextBlob,beni55/TextBlob,dipeshtech/TextBlob,sloria/TextBlob,nvoron23/TextBlob,jonmcoe/TextBlob,sargam111/python,jcalbert/TextBlob,Windy-Ground/TextBlob,laugustyniak/TextBlob
f43248112a867bc819ced274901db25cebe397b7
roledb/serializers.py
roledb/serializers.py
from rest_framework import serializers from roledb.models import User class UserSerializer(serializers.ModelSerializer): roles = serializers.SerializerMethodField('role_data') attributes = serializers.SerializerMethodField('attribute_data') class Meta: model = User fields = ('username', 'roles', 'attr...
from rest_framework import serializers from roledb.models import User class UserSerializer(serializers.ModelSerializer): roles = serializers.SerializerMethodField('role_data') attributes = serializers.SerializerMethodField('attribute_data') class Meta: model = User fields = ('username','first_name','l...
Send first_name and last_name in JSON.
Send first_name and last_name in JSON.
Python
mit
educloudalliance/eca-auth-data,educloudalliance/eca-auth-data
be1e23f068fbc34587caa0a796e259e42ed6f7c6
utils.py
utils.py
import re import textwrap import html2text text_maker = html2text.HTML2Text() text_maker.body_width = 0 def strip_html_tags(text): return re.sub('<[^<]+?>', '', text) def html_to_md(string, strip_html=True, markdown=False): if strip_html: string = strip_html_tags(string) if markdown: s...
import re import textwrap import html2text text_maker = html2text.HTML2Text() text_maker.body_width = 0 def strip_html_tags(text): return re.sub('<[^<]+?>', '', text) def html_to_md(string, strip_html=True, markdown=False): if not string: return 'No Description Found' if strip_html: st...
Handle Nonetype values in `html_to_md`
Handle Nonetype values in `html_to_md`
Python
mit
avinassh/Laozi,avinassh/Laozi
f56ee0bd67652d22de75989cfd7a752641aee91e
ex11+12.py
ex11+12.py
# Upper is ex11, lower part is ex 12 # Both print out are same, but ex11 needs 8 lines, # ex 12 just need it for 4 lines. print "How old are you?", # Becasue can't use print and value in same line age = raw_input() # That's why need two lines to do so. print "How tall are you?", height = raw_input() print "Ho...
# Upper is ex11, lower part is ex 12 # Both print out are same, but ex11 needs 8 lines, # ex 12 just need it for 4 lines. print "How old are you?", #Becasue can't use print and value in same line age = raw_input() # That's why need two lines to do so. print "How tall are you?", height = raw_input() print "Ho...
Revert "Review ex11 and ex12"
Revert "Review ex11 and ex12" This reverts commit e5fe21acd40e9ebeae548e906747702783058d06.
Python
mpl-2.0
joievoyage/LPTHW_EXsss,vanzaj/LPTHW_EXsss
94ec32865674f9f9b0dcecafec73d1e2930ccfdb
runtime/__init__.py
runtime/__init__.py
import builtins import operator import functools from ..compile import varary builtins.__dict__.update({ # Runtime counterparts of some stuff in `Compiler.builtins`. '$': lambda f, *xs: f(*xs) , ':': lambda f, *xs: f(*xs) , ',': lambda a, *xs: (a,) + xs , '<': operator.lt , '<=': operator.le , '=...
import builtins import operator import functools from ..compile import varary builtins.__dict__.update({ # Runtime counterparts of some stuff in `Compiler.builtins`. '$': lambda f, *xs: f(*xs) , ':': lambda f, *xs: f(*xs) , ',': lambda a, *xs: (a,) + xs , '<': operator.lt , '<=': operator.le , '=...
Add a runtime version of if.
Add a runtime version of if. elif/else can't have runtime versions 'cause they are purely syntactic.
Python
mit
pyos/dg
ceef52c348bb3f4477c3d031d024c89eb7379039
ooni/resources/cli.py
ooni/resources/cli.py
import sys from twisted.python import usage from ooni.resources import __version__ from ooni.resources import update class Options(usage.Options): synopsis = """%s""" optParameters = [] def opt_version(self): print("ooniresources version: %s" % __version__) sys.exit(0) def run(): ...
import sys from twisted.python import usage from ooni.resources import __version__ from ooni.resources import update class Options(usage.Options): synopsis = """%s""" optFlags = [ ["update-inputs", None, "Update the resources needed for inputs"] ] optParameters = [] def opt_version(sel...
Make the update-inputs command an option
Make the update-inputs command an option
Python
bsd-2-clause
Karthikeyan-kkk/ooni-probe,lordappsec/ooni-probe,0xPoly/ooni-probe,kdmurray91/ooni-probe,Karthikeyan-kkk/ooni-probe,0xPoly/ooni-probe,lordappsec/ooni-probe,lordappsec/ooni-probe,juga0/ooni-probe,juga0/ooni-probe,kdmurray91/ooni-probe,kdmurray91/ooni-probe,juga0/ooni-probe,Karthikeyan-kkk/ooni-probe,juga0/ooni-probe,lor...
a9b225d033d0462f47e4adecef2ef90fc0bf2318
docs/conf.py
docs/conf.py
# Configuration file for the Sphinx documentation builder. # # For the full list of built-in configuration values, see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html # -- Project information ----------------------------------------------------- # https://www.sphinx-doc.org/en/master...
# Configuration file for the Sphinx documentation builder. # # For the full list of built-in configuration values, see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html # -- Project information ----------------------------------------------------- # https://www.sphinx-doc.org/en/master...
Correct path to parent dir
Correct path to parent dir
Python
mit
galaxyproject/gravity
8dd41fab9a43ef43d5f2dc27e11bdbda3c23bc56
soapbox/tests/urls.py
soapbox/tests/urls.py
from django.conf.urls import patterns, url from django.views.generic import TemplateView urlpatterns = patterns( '', url(r'^$', TemplateView.as_view( template_name='soapboxtest/test_success.html')), url(r'^foo/$', TemplateView.as_view( template_name='soapboxtest/tes...
from django.conf.urls import url from django.views.generic import TemplateView urlpatterns = [ url(r'^$', TemplateView.as_view( template_name='soapboxtest/test_success.html')), url(r'^foo/$', TemplateView.as_view( template_name='soapboxtest/test_success.html')), url...
Stop using patterns() in the test URLs.
Stop using patterns() in the test URLs.
Python
bsd-3-clause
ubernostrum/django-soapbox,ubernostrum/django-soapbox
4418a08553572ca18187472cc32e5044229333f2
django/applications/catmaid/management/commands/catmaid_set_user_profiles_to_default.py
django/applications/catmaid/management/commands/catmaid_set_user_profiles_to_default.py
from django.conf import settings from django.contrib.auth.models import User from django.core.management.base import NoArgsCommand, CommandError class Command(NoArgsCommand): help = "Set the user profile settings of every user to the defaults" def handle_noargs(self, **options): for u in User.objects....
from django.conf import settings from django.contrib.auth.models import User from django.core.management.base import NoArgsCommand, CommandError from optparse import make_option class Command(NoArgsCommand): help = "Set the user profile settings of every user to the defaults" option_list = NoArgsCommand.opti...
Add explicit anonymous user update parameter to user profile command
Add explicit anonymous user update parameter to user profile command The set_user_profiles_to_default management command should only update the anonymous user if explicitely stated. This commit adds the '--update-anon-user' switch to do let the user state that also the anonymous user's profile should be updated with t...
Python
agpl-3.0
fzadow/CATMAID,htem/CATMAID,htem/CATMAID,fzadow/CATMAID,fzadow/CATMAID,fzadow/CATMAID,htem/CATMAID,htem/CATMAID
69e6db7a4a28ff1f50bd4f12f550a2b65f05eb38
utils/dusk/__init__.py
utils/dusk/__init__.py
""" 'Dusk' command system for Amethyst. Based loosely (heh) off of discord.py's ext command system. TODO: refactor arg parsing probably. """ from .context import Context # NOQA from .command import * # NOQA from .command_holder import CommandHolder # NOQA from .constants import * # NOQA
""" 'Dusk' command system for Amethyst. Based loosely (heh) off of discord.py's ext command system. """ from .context import Context # NOQA from .command import * # NOQA from .command_holder import CommandHolder # NOQA from .constants import * # NOQA __version__ = "1.0.0"
Remove obsolete TODO and add version
Remove obsolete TODO and add version
Python
mit
awau/Amethyst,HexadecimalPython/Xeili
a31a3a9fd5f9f26bc9e06b7c682a9544f71806ad
tests/basics/dict_fromkeys.py
tests/basics/dict_fromkeys.py
d = dict.fromkeys([1, 2, 3, 4]) l = list(d.keys()) l.sort() print(l) d = dict.fromkeys([1, 2, 3, 4], 42) l = list(d.values()) l.sort() print(l)
d = dict.fromkeys([1, 2, 3, 4]) l = list(d.keys()) l.sort() print(l) d = dict.fromkeys([1, 2, 3, 4], 42) l = list(d.values()) l.sort() print(l) # argument to fromkeys is a generator d = dict.fromkeys(i + 1 for i in range(1)) print(d)
Add test for dict.fromkeys where arg is a generator.
tests/basics: Add test for dict.fromkeys where arg is a generator. Improves coverage because it tests the case where the arg does not have a __len__ slot.
Python
mit
AriZuu/micropython,toolmacher/micropython,deshipu/micropython,infinnovation/micropython,swegener/micropython,adafruit/micropython,adafruit/micropython,TDAbboud/micropython,torwag/micropython,hiway/micropython,MrSurly/micropython,TDAbboud/micropython,trezor/micropython,cwyark/micropython,swegener/micropython,pozetroninc...
9ee301c525600cfeb8b8ca3d59f75ff9b7823008
test/buildbot/buildbot_config/master/schedulers.py
test/buildbot/buildbot_config/master/schedulers.py
""" This module contains the logic which returns the set of schedulers to use for the build master. """ from buildbot.changes.filter import ChangeFilter from buildbot.schedulers.basic import SingleBranchScheduler def get_schedulers(): # Run the unit tests for master master_unit = SingleBranchScheduler(name="f...
""" This module contains the logic which returns the set of schedulers to use for the build master. """ from buildbot.changes.filter import ChangeFilter from buildbot.schedulers.basic import ( Dependent, SingleBranchScheduler) def get_schedulers(): # Run the unit tests for master master_unit = SingleB...
Make the acceptance tests dependent on the unit tests passing
Buildbot: Make the acceptance tests dependent on the unit tests passing
Python
mit
zsjohny/vagrant,bheuvel/vagrant,lonniev/vagrant,dharmab/vagrant,petems/vagrant,tjanez/vagrant,senglin/vagrant,benh57/vagrant,lonniev/vagrant,tomfanning/vagrant,cgvarela/vagrant,gpkfr/vagrant,krig/vagrant,philoserf/vagrant,philwrenn/vagrant,modulexcite/vagrant,tschortsch/vagrant,bmhatfield/vagrant,mitchellh/vagrant,tbar...
727939269aef168513ad6d62913e20f0af95b4e6
dduplicated/hashs.py
dduplicated/hashs.py
import hashlib import os def get_hash(path): return get_md5(path) def get_md5(path): hash_md5 = hashlib.md5() if os.path.isfile(path): with open(path, "rb") as file: while True: buffer = file.read(4096) if not buffer: break hash_md5.update(buffer) return hash_md5.hexdigest()
import hashlib import os def get_hash(path): return get_md5(path) # MD5 methods is based on second answer from: https://exceptionshub.com/get-md5-hash-of-big-files-in-python.html def get_md5(path): hash_md5 = hashlib.md5() if os.path.isfile(path): with open(path, "rb") as file: while True: buffer = file.re...
Add reference to md5 method.
Add reference to md5 method.
Python
mit
messiasthi/dduplicated-cli
9cc3cf8a2911fedce7f08d2412388154c24a9ed1
engine.py
engine.py
# Use x, y coords for unit positions # (97, 56) ... (104, 56) # ... ... # (97, 49) ... (104, 49) # # Algebraic notation for a position is: # algebraic_pos = chr(x) + chr(y) def _coord_to_algebraic(coord): x, y = coord return chr(x) + chr(y) def _algebraic_to_coord(algebraic): x, y = algebrai...
# Use x, y coords for unit positions # (97, 56) ... (104, 56) # ... ... # (97, 49) ... (104, 49) # # Algebraic notation for a position is: # algebraic_pos = chr(x) + chr(y) def _coord_to_algebraic(coord): x, y = coord return chr(x) + chr(y) def _algebraic_to_coord(algebraic): x, y = algebrai...
Add Piece() to serve as the parent class for all chess pieces
Add Piece() to serve as the parent class for all chess pieces
Python
mit
EyuelAbebe/gamer,EyuelAbebe/gamer
3784b04109b2ca92633a788cc02562898064282c
factor.py
factor.py
import numpy as np def LU(A): m = A.shape[0] U = A.copy() L = np.eye( m ) for j in range(m): for i in range(j+1,m): L[i,j] = U[i,j]/U[j,j] U[i,:] -= L[i,j]*U[j,:] return L, U
import numpy as np def LU(A): r"""Factor a square matrix by Gaussian elimination. The argument A should be a square matrix (an m-by-m numpy array). The outputs L and U are also m-by-m. L is lower-triangular with unit diagonal entries and U is strictly upper-triangular. This impl...
Add docstring, with an example.
Add docstring, with an example.
Python
bsd-2-clause
ketch/rock-solid-code-demo
e26a49220835cd3df14820be7b400dc045092bb9
examples/load_ui_base_instance.py
examples/load_ui_base_instance.py
import sys import os os.environ["QT_PREFERRED_BINDING"] = "PySide" from Qt import QtWidgets, load_ui def setup_ui(uifile, base_instance=None): ui = load_ui(uifile) if not base_instance: return ui else: for member in dir(ui): if not member.startswith('__') and \ ...
import sys import os # Set preferred binding # os.environ["QT_PREFERRED_BINDING"] = "PySide" from Qt import QtWidgets, load_ui def setup_ui(uifile, base_instance=None): ui = load_ui(uifile) if not base_instance: return ui else: for member in dir(ui): if not member.startswith(...
Remove preffered binding, use obj.__class__ instead of type()
Remove preffered binding, use obj.__class__ instead of type()
Python
mit
mottosso/Qt.py,fredrikaverpil/Qt.py,mottosso/Qt.py,fredrikaverpil/Qt.py
1975b33b5f251198b59a772a38b6302fbea89017
tests/test_create_template.py
tests/test_create_template.py
# -*- coding: utf-8 -*- """ test_create_template -------------------- """ import os import pytest import subprocess def run_tox(plugin): """Run the tox suite of the newly created plugin.""" try: subprocess.check_call([ 'tox', plugin, '-c', os.path.join(plugin, 't...
# -*- coding: utf-8 -*- """ test_create_template -------------------- """ import os import pytest import subprocess def run_tox(plugin): """Run the tox suite of the newly created plugin.""" try: subprocess.check_call([ 'tox', plugin, '-c', os.path.join(plugin, 't...
Extend test to check for the exit code and for an exception
Extend test to check for the exit code and for an exception
Python
mit
pytest-dev/cookiecutter-pytest-plugin
36213a31a1870cf38ec0ce3d208c6a2072e2b133
acapi/tests/test_client.py
acapi/tests/test_client.py
import os import requests import requests_mock import unittest from .. import Client @requests_mock.Mocker() class TestClient(unittest.TestCase): """Tests the Acquia Cloud API client class.""" req = None """ def setup(self, ): " "" Set up the tests with the mock requests ...
import os import requests import requests_mock import unittest from .. import Client from ..exceptions import AcquiaCloudException @requests_mock.Mocker() class TestClient(unittest.TestCase): """Tests the Acquia Cloud API client class.""" req = None """ def setup(self, ): " "" ...
Add test for failing to find credentials
Add test for failing to find credentials
Python
mit
skwashd/python-acquia-cloud
ee24b8b57bc73947cd5140aca15389861b33ab00
gui/qt.py
gui/qt.py
from lib.version import AMON_VERSION from lib.keybase import KeybaseUser from lib.gmail import GmailUser from lib.addresses import AddressBook import lib.gpg as gpg import sys import logging import json from PyQt4 import QtGui class Amon(QtGui.QMainWindow): def __init__(self): super(Amon, self).__init__(...
from lib.version import AMON_VERSION from lib.keybase import KeybaseUser from lib.gmail import GmailUser from lib.addresses import AddressBook import lib.gpg as gpg import sys import logging import json from PyQt4 import QtGui class Amon(QtGui.QMainWindow): def __init__(self): super(Amon, self).__init__(...
Update Qt gui to have status bar and menu bar
Update Qt gui to have status bar and menu bar
Python
unlicense
CodingAnarchy/Amon
7dced29bcf8b2b5f5220f5dbfeaf631d9d5fc409
examples/backtest.py
examples/backtest.py
import time import logging from pythonjsonlogger import jsonlogger from flumine import FlumineBacktest, clients from strategies.lowestlayer import LowestLayer logger = logging.getLogger() custom_format = "%(asctime) %(levelname) %(message)" log_handler = logging.StreamHandler() formatter = jsonlogger.JsonFormatter(c...
import time import logging from pythonjsonlogger import jsonlogger from flumine import FlumineBacktest, clients from strategies.lowestlayer import LowestLayer logger = logging.getLogger() custom_format = "%(asctime) %(levelname) %(message)" log_handler = logging.StreamHandler() formatter = jsonlogger.JsonFormatter(c...
Comment to say using logging.CRITICAL is faster
Comment to say using logging.CRITICAL is faster
Python
mit
liampauling/flumine
245628bf53bf7255ccd5aa15d21ff8c1f5751ef8
examples/listdevs.py
examples/listdevs.py
#!/usr/bin/env python import usb1 def main(): context = usb1.USBContext() for device in context.getDeviceList(skip_on_error=True): print str(device) if __name__ == '__main__': main()
#!/usr/bin/env python import usb1 def main(): context = usb1.USBContext() for device in context.getDeviceList(skip_on_error=True): print 'ID %04x:%04x' % (device.getVendorID(), device.getProductID()), '->'.join(str(x) for x in ['Bus %03i' % (device.getBusNumber(), )] + device.getPortNumberList()), 'Dev...
Modify listdev to exercise getPortNumberList .
examples: Modify listdev to exercise getPortNumberList .
Python
lgpl-2.1
vpelletier/python-libusb1,vpelletier/python-libusb1
0668a4bba21e44a028cb008b03165f63eba5b457
acute/models.py
acute/models.py
""" acute models. """ from django.db.models import fields from opal import models class Demographics(models.Demographics): pass class Location(models.Location): pass class Allergies(models.Allergies): pass class Diagnosis(models.Diagnosis): pass class PastMedicalHistory(models.PastMedicalHistory): pass class Treatmen...
""" acute models. """ from django.db.models import fields from opal import models class Demographics(models.Demographics): pass class Location(models.Location): pass class Allergies(models.Allergies): pass class Diagnosis(models.Diagnosis): pass class PastMedicalHistory(models.PastMedicalHistory): pass class Treatmen...
Rename Clerking -> Seen by
Rename Clerking -> Seen by closes #1
Python
agpl-3.0
openhealthcare/acute,openhealthcare/acute,openhealthcare/acute
eb606f58b695dbb215b46cec3c895045e811bbad
scanpointgenerator/maskedgenerator.py
scanpointgenerator/maskedgenerator.py
class Factory(object): def __init__(self, generator, roi): self.generator = generator self.roi = roi def iterator(self): for point in self.generator.iterator(): if self.roi.contains_point(point): yield point
class MaskedGenerator(object): def __init__(self, generator, roi): self.generator = generator self.roi = roi def iterator(self): for point in self.generator.iterator(): if self.roi.contains_point(point): yield point
Rename Factory class to MaskedGenerator
Rename Factory class to MaskedGenerator
Python
apache-2.0
dls-controls/scanpointgenerator
861d4f9773193a03d1f53c6e0c3f78d48b096d45
juliet_importer.py
juliet_importer.py
import os class loader: modules = {}; def __init__(self): self.load_modules(); def load_modules(self, path="./modules/"): # Consider adding recursive sorting at some point in the future names = os.listdir(path); pwd = os.getcwd(); os.chdir(path); for name in names:...
import os import imp modules = {} def load_modules(path="./modules/"): # Consider adding recursive sorting at some point in the future names = os.listdir(path) for name in names: if not name.endswith(".py"): continue print("Importing module {0}".format(name)) name = name.split('.')[0] ...
Remove superfluous class from importer
Remove superfluous class from importer
Python
bsd-2-clause
halfbro/juliet
99592279585c27ad2c41f50d49c1e3264173eae6
actions/actions.py
actions/actions.py
#!/usr/bin/python import sys import os sys.path.append('hooks/') import subprocess from charmhelpers.core.hookenv import action_fail from utils import ( pause_unit, resume_unit, ) def pause(args): """Pause the Ceilometer services. @raises Exception should the service fail to stop. """ pause_un...
#!/usr/bin/python import sys import os sys.path.append('hooks/') import subprocess from charmhelpers.core.hookenv import action_fail from utils import ( pause_unit, resume_unit, ) def pause(args): """Pause the hacluster services. @raises Exception should the service fail to stop. """ pause_uni...
Fix copy and pasta error
Fix copy and pasta error
Python
apache-2.0
CanonicalBootStack/charm-hacluster,CanonicalBootStack/charm-hacluster,CanonicalBootStack/charm-hacluster
16945303e5092bbd37f914ea10936d95e054f703
harvesting_blog_data.py
harvesting_blog_data.py
import os import sys import json import feedparser from bs4 import BeautifulSoup FEED_URL = 'http://g1.globo.com/dynamo/rss2.xml' def cleanHtml(html): return BeautifulSoup(html, 'lxml').get_text() fp = feedparser.parse(FEED_URL) print "Fetched %s entries from '%s'" % (len(fp.entries[0].title), fp.feed.title) b...
# -*- coding: UTF-8 -*- import os import sys import json import feedparser from bs4 import BeautifulSoup FEED_URL = 'http://g1.globo.com/dynamo/rss2.xml' fp = feedparser.parse(FEED_URL) print "Fetched %s entries from '%s'" % (len(fp.entries[0].title), fp.feed.title) blog_posts = [] for e in fp.entries: blog_po...
Add G1 example and utf-8
Add G1 example and utf-8
Python
apache-2.0
fabriciojoc/redes-sociais-web,fabriciojoc/redes-sociais-web
9c2951d794bb27952606cae77da1ebcd0d651e72
aiodownload/api.py
aiodownload/api.py
# -*- coding: utf-8 -*- from aiodownload import AioDownloadBundle, AioDownload import asyncio def one(url, download=None): return [s for s in swarm([url], download=download)][0] def swarm(urls, download=None): return [e for e in each(urls, download=download)] def each(iterable, url_map=None, download=N...
# -*- coding: utf-8 -*- from aiodownload import AioDownloadBundle, AioDownload import asyncio def one(url, download=None): return [s for s in swarm([url], download=download)][0] def swarm(urls, download=None): return [e for e in each(urls, download=download)] def each(iterable, url_map=None, download=N...
Fix - needed to provide create_task a function, not a class
Fix - needed to provide create_task a function, not a class
Python
mit
jelloslinger/aiodownload
633f84411e26201233e3c68c584b236363f79f62
server/conf/vhosts/available/token.py
server/conf/vhosts/available/token.py
import core.provider.authentication as authentication import core.notify.dispatcher as notify import core.notify.plugins.available.changes as changes import core.provider.storage as storage import core.resource.base as resource import conf.vhosts.available.default as default class VHost(default.VHost): host = ['lo...
import core.provider.authentication as authentication import core.notify.dispatcher as notify import core.notify.plugins.available.changes as changes import core.provider.storage as storage import core.resource.base as resource import conf.vhosts.available.default as default class VHost(default.VHost): host = ['lo...
Allow access to root leaves.
Allow access to root leaves.
Python
mit
slaff/attachix,slaff/attachix,slaff/attachix
7da1326848cba8ff7bf61dde4583a12e5bad8ae2
centinel/backend.py
centinel/backend.py
import requests import config def get_recommended_versions(): return request("/versions") def get_experiments(): return request("/experiments") def get_results(): return request("/results") def get_clients(): return request("/clients") def request(slug): url = "%s%s" % (config.server_url, slug)...
import requests import config def request(slug): url = "%s%s" % (config.server_url, slug) req = requests.get(url) if req.status_code != requests.codes.ok: raise req.raise_for_status() return req.json() def get_recommended_versions(): return request("/versions") def get_experiments(): ...
Raise exception if status code is not ok
Raise exception if status code is not ok
Python
mit
JASONews/centinel,iclab/centinel,lianke123321/centinel,lianke123321/centinel,Ashish1805/centinel,rpanah/centinel,rpanah/centinel,ben-jones/centinel,iclab/centinel,lianke123321/centinel,iclab/centinel,rpanah/centinel
5225392a305e8e83a5a0fae91d3c2090914f2e5c
resolwe/flow/executors/docker.py
resolwe/flow/executors/docker.py
"""Local workflow executor""" from __future__ import absolute_import, division, print_function, unicode_literals import os import shlex import subprocess from django.conf import settings from .local import FlowExecutor as LocalFlowExecutor class FlowExecutor(LocalFlowExecutor): def start(self): contain...
"""Local workflow executor""" from __future__ import absolute_import, division, print_function, unicode_literals import os import random import shlex import subprocess from django.conf import settings from .local import FlowExecutor as LocalFlowExecutor class FlowExecutor(LocalFlowExecutor): def start(self): ...
Set random container name for tests
Set random container name for tests
Python
apache-2.0
jberci/resolwe,jberci/resolwe,genialis/resolwe,genialis/resolwe
304a7da03072dbe6e099bbda37fb8aca0567e64b
organizer/models.py
organizer/models.py
from django.db import models # Model Field Reference # https://docs.djangoproject.com/en/1.8/ref/models/fields/ class Tag(models.Model): name = models.CharField(max_length=31) slug = models.SlugField() class Startup(models.Model): name = models.CharField(max_length=31) slug = models.SlugField() ...
from django.db import models # Model Field Reference # https://docs.djangoproject.com/en/1.8/ref/models/fields/ class Tag(models.Model): name = models.CharField(max_length=31) slug = models.SlugField() class Startup(models.Model): name = models.CharField(max_length=31) slug = models.SlugField() ...
Define Startup model related fields.
Ch03: Define Startup model related fields. [skip ci] https://docs.djangoproject.com/en/1.8/ref/models/fields/#manytomanyfield A many-to-many relationship allows for different models to be related to many of the other. For instance, students may take many classes, and classes are taught to many students. In our co...
Python
bsd-2-clause
jambonrose/DjangoUnleashed-1.8,jambonrose/DjangoUnleashed-1.8
748e2e51a9ead7be4047e112aad2ed07a3d7a2c9
systemvm/patches/debian/config/opt/cloud/bin/cs_dhcp.py
systemvm/patches/debian/config/opt/cloud/bin/cs_dhcp.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
Check both ip and hosts when building dhcp bag
Check both ip and hosts when building dhcp bag
Python
apache-2.0
GabrielBrascher/cloudstack,resmo/cloudstack,resmo/cloudstack,resmo/cloudstack,jcshen007/cloudstack,GabrielBrascher/cloudstack,wido/cloudstack,wido/cloudstack,DaanHoogland/cloudstack,wido/cloudstack,wido/cloudstack,GabrielBrascher/cloudstack,DaanHoogland/cloudstack,resmo/cloudstack,DaanHoogland/cloudstack,wido/cloudstac...
855724c4e52a55d141e2ef72cf7181710fb33d44
dwitter/user/urls.py
dwitter/user/urls.py
from django.conf.urls import url from . import views urlpatterns = [ url(r'^(?P<url_username>[a-z0-9]*)$', views.user_feed, {'page_nr':'1'}, name='user_feed'), url(r'^(?P<url_username>[a-z0-9]*)/(?P<page_nr>\d+)$', views.user_feed, name='user_feed_page'), ]
from django.conf.urls import url from . import views urlpatterns = [ url(r'^(?P<url_username>\w+)$', views.user_feed, {'page_nr':'1'}, name='user_feed'), url(r'^(?P<url_username>\w+)/(?P<page_nr>\d+)$', views.user_feed, name='user_feed_page'), ]
Fix error when usernames have capital characters
Fix error when usernames have capital characters
Python
apache-2.0
lionleaf/dwitter,lionleaf/dwitter,lionleaf/dwitter
93a7616d949494888f5357f5491aa3278e7de234
cupy/logic/truth.py
cupy/logic/truth.py
import cupy def all(a, axis=None, out=None, keepdims=False): assert isinstance(a, cupy.ndarray) return a.all(axis=axis, out=out, keepdims=keepdims) def any(a, axis=None, out=None, keepdims=False): assert isinstance(a, cupy.ndarray) return a.any(axis=axis, out=out, keepdims=keepdims)
import cupy def all(a, axis=None, out=None, keepdims=False): """Tests whether all array elements along a given axis evaluate to True. Args: a (cupy.ndarray): Input array. axis (int or tuple of ints): Along which axis to compute all. The flattened array is used by default. ...
Add documents of cupy.all and cupy.any function
Add documents of cupy.all and cupy.any function
Python
mit
cupy/cupy,cupy/cupy,cupy/cupy,cupy/cupy
4785a5e8d639dea1a9cf767d2c77f6bd9dbe2433
leapp/cli/upgrade/__init__.py
leapp/cli/upgrade/__init__.py
from leapp.utils.clicmd import command, command_opt from leapp.repository.scan import find_and_scan_repositories from leapp.config import get_config from leapp.logger import configure_logger def load_repositories_from(name, repo_path, manager=None): if get_config().has_option('repositories', name): repo_p...
from leapp.utils.clicmd import command, command_opt from leapp.repository.scan import find_and_scan_repositories from leapp.config import get_config from leapp.logger import configure_logger def load_repositories_from(name, repo_path, manager=None): if get_config().has_option('repositories', name): repo_p...
Add back missing manager creation
leapp: Add back missing manager creation
Python
lgpl-2.1
leapp-to/prototype,vinzenz/prototype,leapp-to/prototype,vinzenz/prototype,vinzenz/prototype,leapp-to/prototype,vinzenz/prototype,leapp-to/prototype
6e1a211ff1834f8047261d51737afcb0412075b5
memleak.py
memleak.py
import torch from torch import FloatTensor, LongTensor from torch.autograd import Variable from torch import nn, optim from torch.nn import Parameter from tqdm import trange import util, logging, os, psutil import hyper logging.basicConfig(filename='memleak.log',level=logging.INFO) torch.manual_seed(2) B = 256 M =...
import torch from torch import FloatTensor, LongTensor from torch.autograd import Variable from torch import nn, optim from torch.nn import Parameter from tqdm import trange import util, logging, os, psutil import hyper logging.basicConfig(filename='memleak.log',level=logging.INFO) torch.manual_seed(2) B = 256 M =...
Add logging of memory use
Add logging of memory use
Python
mit
MaestroGraph/sparse-hyper
95d71d5a84f05de7d655fd788a4139c3a1316d74
text/__init__.py
text/__init__.py
#! /usr/bin/env python import os def get_files(path, ext=None): """ Get all files in directory path, optionally with the specified extension """ if ext is None: ext = '' return [ os.path.abspath(fname) for fname in os.listdir(path) if os.path.isfile(fname) ...
#! /usr/bin/env python import os def get_files(path, ext=None): """ Get all files in directory path, optionally with the specified extension """ if ext is None: ext = '' return [ os.path.abspath(fname) for fname in os.listdir(path) if os.path.isfile(fname) ...
Add function to generate a blob of text from a list of files
Add function to generate a blob of text from a list of files
Python
mit
IanLee1521/utilities
9891fa25d905bb2aa34c9c55fc420d29438f9499
leonardo_ckeditor/__init__.py
leonardo_ckeditor/__init__.py
from django.apps import AppConfig from .ckeditor_config import DEFAULT_CONFIG default_app_config = 'leonardo_ckeditor.Config' LEONARDO_APPS = [ 'leonardo_ckeditor', 'ckeditor', 'ckeditor_uploader' ] LEONARDO_CONFIG = { 'CKEDITOR_UPLOAD_PATH': ('uploads/', ('CKEditor upload directory')), 'CKEDIT...
from django.apps import AppConfig from .ckeditor_config import DEFAULT_CONFIG default_app_config = 'leonardo_ckeditor.Config' LEONARDO_APPS = [ 'leonardo_ckeditor', 'ckeditor', 'ckeditor_uploader' ] LEONARDO_CONFIG = { 'CKEDITOR_UPLOAD_PATH': ('', ('CKEditor upload directory')), 'CKEDITOR_CONFI...
Use upload widget in the default state.
Use upload widget in the default state.
Python
bsd-3-clause
leonardo-modules/leonardo-ckeditor,leonardo-modules/leonardo-ckeditor
532bebd01822917f89ec18080bf8e5a75c16832d
config_template.py
config_template.py
chatbot_ubuntu = { 'path': '', 'model_id': '', 'python_env': '' } chatbot_swisscom = { 'path': '', 'model_id': '', 'python_env': '' } chatbot_ubuntu_seq2seq = { 'socket_address': '', 'socket_port': '' } ate = { 'path': '', 'python_env': '' } neuroate = { 'path': '', 'pyth...
chatbot_ubuntu = { 'path': '', 'model_id': '', 'python_env': '' } chatbot_swisscom = { 'path': '', 'model_id': '', 'python_env': '' } chatbot_ubuntu_seq2seq = { 'socket_address': '', 'socket_port': '' } ate = { 'path': '', 'python_env': '' } neuroate = { 'path': '', 'pyth...
Add churn entry in the file
Add churn entry in the file
Python
mit
nachoaguadoc/aimlx-demos,nachoaguadoc/aimlx-demos,nachoaguadoc/aimlx-demos
e4452ff7e8c27e2e8315c2edb8627a2e92ca86e3
panoptes_cli/scripts/panoptes.py
panoptes_cli/scripts/panoptes.py
import click import os import yaml from panoptes_client import Panoptes @click.group() @click.option( '--endpoint', type=str ) @click.pass_context def cli(ctx, endpoint): ctx.config_dir = os.path.join(os.environ['HOME'], '.panoptes') ctx.config_file = os.path.join(ctx.config_dir, 'config.yml') ctx.conf...
import click import os import yaml from panoptes_client import Panoptes @click.group() @click.option( '--endpoint', type=str ) @click.pass_context def cli(ctx, endpoint): ctx.config_dir = os.path.expanduser('~/.panoptes/') ctx.config_file = os.path.join(ctx.config_dir, 'config.yml') ctx.config = { ...
Use os.path.expanduser to find config directory
Use os.path.expanduser to find config directory Works on Windows and Unix.
Python
apache-2.0
zooniverse/panoptes-cli
57a477985f3591258dee8a5cbf4ba2a173c749fc
dashboard/views.py
dashboard/views.py
from django.contrib.auth.decorators import login_required from django.contrib.contenttypes.models import ContentType from django.db.models import Q from django.shortcuts import render_to_response from django.template.context import RequestContext from actstream.models import Action from teams.models import Team @lo...
from django.contrib.auth.decorators import login_required from django.contrib.contenttypes.models import ContentType from django.db.models import Q from django.shortcuts import render_to_response from django.template.context import RequestContext from actstream.models import Action from teams.models import Team @lo...
Fix dashboard bug when user is not in any teams.
Fix dashboard bug when user is not in any teams.
Python
apache-2.0
snswa/swsites,snswa/swsites,snswa/swsites
7ebd46c4a698b642dd1da355e413eb1bc9ce2727
learntris.py
learntris.py
#!/usr/bin/env python import sys class Grid(object): def __init__(self): self.board = [[None] * 10 for i in range(22)] self.score = 0 self.lines_clear = 0 def draw_board(self): current_board = self.board for row in current_board: row = map(lambda...
#!/usr/bin/env python import sys class Grid(object): def __init__(self): self.board = [[None] * 10 for i in range(22)] self.score = 0 self.lines_clear = 0 def draw_board(self): current_board = self.board for row in current_board: row = map(lambda...
Update rest of functions with new data structure; Passes Test 8
Update rest of functions with new data structure; Passes Test 8
Python
mit
mosegontar/learntris
604102af89c0f3ab3b9562b3baa246f24de3fe90
locations/spiders/la_salsa.py
locations/spiders/la_salsa.py
# -*- coding: utf-8 -*- import scrapy from locations.items import GeojsonPointItem import json import re class LaSalsaSpider(scrapy.Spider): name = "la_salsa" allowed_domains = ["www.lasalsa.com"] start_urls = ( 'http://lasalsa.com/wp-content/themes/lasalsa-main/locations-search.php?lat=0&lng=0&rad...
# -*- coding: utf-8 -*- import scrapy from locations.items import GeojsonPointItem class LaSalsaSpider(scrapy.Spider): name = "la_salsa" allowed_domains = ["www.lasalsa.com"] start_urls = ( 'http://lasalsa.com/wp-content/themes/lasalsa-main/locations-search.php?lat=0&lng=0&radius=99999999', )...
Use xpath instead of regex
Use xpath instead of regex
Python
mit
iandees/all-the-places,iandees/all-the-places,iandees/all-the-places
7588bab65a098cbc0b5e2ba2c1b9a45b08adfc46
fsspec/__init__.py
fsspec/__init__.py
try: from importlib.metadata import entry_points except ImportError: # python < 3.8 try: from importlib_metadata import entry_points except ImportError: entry_points = None from . import caching from ._version import get_versions from .core import get_fs_token_paths, open, open_files, ope...
try: from importlib.metadata import entry_points except ImportError: # python < 3.8 try: from importlib_metadata import entry_points except ImportError: entry_points = None from . import caching from ._version import get_versions from .core import get_fs_token_paths, open, open_files, ope...
Make the exceptions valid on fsspec module level
Make the exceptions valid on fsspec module level
Python
bsd-3-clause
intake/filesystem_spec,fsspec/filesystem_spec,fsspec/filesystem_spec
c126950f653169ad3d5035ea1580a7c4c7250f22
test/test_Spectrum.py
test/test_Spectrum.py
#!/usr/bin/env python3 from __future__ import division, print_function import pytest import sys # Add Spectrum location to path sys.path.append('../') import Spectrum # Test using hypothesis def test_spectrum_assigns_data(): x = [1,2,3,4,5,6] y = [1,1,0.9,0.95,1,1] spec = Spectrum(x, y) assert spec...
#!/usr/bin/env python3 from __future__ import division, print_function import pytest import sys # Add Spectrum location to path sys.path.append('../') import Spectrum # Test using hypothesis def test_spectrum_assigns_data(): x = [1,2,3,4,5,6] y = [1,1,0.9,0.95,1,1] z = 2200*x spec = Spectrum.Spectr...
Fix test to pass, get class from module and add wavelength assignment
Fix test to pass, get class from module and add wavelength assignment
Python
mit
jason-neal/spectrum_overload,jason-neal/spectrum_overload,jason-neal/spectrum_overload
1c01423e0cccd64ab249a9749f04cf3e155d3f53
setup.py
setup.py
from distutils.core import setup with open('README.md') as readme: with open('HISTORY.md') as history: long_description = readme.read() + '\n\n' + history.read() try: import pypandoc long_description = pypandoc.convert(long_description, 'rst') except(IOError, ImportError): long_description = ...
from distutils.core import setup with open('README.md') as readme: with open('HISTORY.md') as history: long_description = readme.read() + '\n\n' + history.read() try: import pypandoc long_description = pypandoc.convert(long_description, 'rst', 'markdown') except(IOError, ImportError): long_de...
Convert md to rst readme specially for PyPi
Convert md to rst readme specially for PyPi
Python
mit
sashgorokhov/argparse-autogen
08335e060311994a897b95302fc54a0a2b196614
mdx_linkify/__init__.py
mdx_linkify/__init__.py
from mdx_linkify.mdx_linkify import makeExtension
import sys is_python3 = sys.version_info >= (3, 0) if is_python3: from mdx_linkify.mdx_linkify import makeExtension else: from mdx_linkify import makeExtension assert makeExtension # Silences pep8.
Fix import for python2 and pypy
Fix import for python2 and pypy
Python
mit
daGrevis/mdx_linkify