commit stringlengths 40 40 | old_file stringlengths 4 150 | new_file stringlengths 4 150 | old_contents stringlengths 0 3.26k | new_contents stringlengths 1 4.43k | subject stringlengths 15 501 | message stringlengths 15 4.06k | lang stringclasses 4
values | license stringclasses 13
values | repos stringlengths 5 91.5k | diff stringlengths 0 4.35k |
|---|---|---|---|---|---|---|---|---|---|---|
668f5f588998040cadc320eccc2689551d348bc3 | anki/statsbg.py | anki/statsbg.py | # from subtlepatterns.com
bg = """\
iVBORw0KGgoAAAANSUhEUgAAABIAAAANCAMAAACTkM4rAAAAM1BMVEXy8vLz8/P5+fn19fXt7e329vb4+Pj09PTv7+/u7u739/fw8PD7+/vx8fHr6+v6+vrs7Oz2LjW2AAAAkUlEQVR42g3KyXHAQAwDQYAQj12ItvOP1qqZZwMMPVnd06XToQvz4L2HDQ2iRgkvA7yPPB+JD+OUPnfzZ0JNZh6kkQus5NUmR7g4Jpxv5XN6nYWNmtlq9o3zuK6w3XRsE1pQIEGPIsdtTP3m2cYwlPv6... | # from subtlepatterns.com
#
# The lines are too long.
# flake8: noqa
bg = """\
iVBORw0KGgoAAAANSUhEUgAAABIAAAANCAMAAACTkM4rAAAAM1BMVEXy8vLz8/P5+fn19fXt7e329vb4+Pj09PTv7+/u7u739/fw8PD7+/vx8fHr6+v6+vrs7Oz2LjW2AAAAkUlEQVR42g3KyXHAQAwDQYAQj12ItvOP1qqZZwMMPVnd06XToQvz4L2HDQ2iRgkvA7yPPB+JD+OUPnfzZ0JNZh6kkQus5NUmR7g4Jpxv5XN6n... | Make flake8 ignore the bg image. | Make flake8 ignore the bg image.
| Python | agpl-3.0 | ospalh/libanki3 | ---
+++
@@ -1,4 +1,7 @@
# from subtlepatterns.com
+#
+# The lines are too long.
+# flake8: noqa
bg = """\
iVBORw0KGgoAAAANSUhEUgAAABIAAAANCAMAAACTkM4rAAAAM1BMVEXy8vLz8/P5+fn19fXt7e329vb4+Pj09PTv7+/u7u739/fw8PD7+/vx8fHr6+v6+vrs7Oz2LjW2AAAAkUlEQVR42g3KyXHAQAwDQYAQj12ItvOP1qqZZwMMPVnd06XToQvz4L2HDQ2iRgkvA7yPPB+JD+OUP... |
ec96669641c9b753c3ce74ce432213a17b0403fe | tests/aggregate_tests.py | tests/aggregate_tests.py | #!/usr/bin/env python
"""
<Program Name>
aggregate_tests.py
<Author>
Konstantin Andrianov.
Zane Fisher.
<Started>
January 26, 2013.
August 2013.
Modified previous behavior that explicitly imported individual
unit tests. -Zane Fisher
<Copyright>
See LICENSE for licensing information.
<Purpose>
Ru... | #!/usr/bin/env python
"""
<Program Name>
aggregate_tests.py
<Author>
Konstantin Andrianov.
Zane Fisher.
<Started>
January 26, 2013.
August 2013.
Modified previous behavior that explicitly imported individual
unit tests. -Zane Fisher
<Copyright>
See LICENSE for licensing information.
<Purpose>
Ru... | Copy and call in-toto's check_usable_gpg function | Copy and call in-toto's check_usable_gpg function
Set environment variable in test aggregate script that may be
used to skip tests if gpg is not available on the test system.
| Python | mit | secure-systems-lab/securesystemslib,secure-systems-lab/securesystemslib | ---
+++
@@ -31,10 +31,30 @@
from __future__ import division
from __future__ import unicode_literals
+import os
import sys
import unittest
+import subprocess
+
+def check_usable_gpg():
+ """Set `TEST_SKIP_GPG` environment variable if neither gpg2 nor gpg is
+ available. """
+ os.environ["TEST_SKIP_GPG"] = "1"... |
593d152bd6eec64bc8ee504020ba0e5e2345966c | wafer/pages/views.py | wafer/pages/views.py | from django.http import Http404
from django.core.exceptions import PermissionDenied
from django.views.generic import DetailView, TemplateView, UpdateView
from wafer.pages.models import Page
from wafer.pages.forms import PageForm
class ShowPage(DetailView):
template_name = 'wafer.pages/page.html'
model = Page... | from django.http import Http404
from django.core.exceptions import PermissionDenied
from django.views.generic import DetailView, TemplateView, UpdateView
from wafer.pages.models import Page
from wafer.pages.forms import PageForm
class ShowPage(DetailView):
template_name = 'wafer.pages/page.html'
model = Page... | Remove unneeded field specifier from EditPage form to make Django 1.8 happy | Remove unneeded field specifier from EditPage form to make Django 1.8 happy
| Python | isc | CTPUG/wafer,CarlFK/wafer,CTPUG/wafer,CarlFK/wafer,CTPUG/wafer,CarlFK/wafer,CTPUG/wafer,CarlFK/wafer | ---
+++
@@ -15,7 +15,6 @@
template_name = 'wafer.pages/page_form.html'
model = Page
form_class = PageForm
- fields = ['name', 'content']
def slug(request, url): |
3e12e61144fe4cd08f755130dde23066879521d1 | InteractiveCommandLine.UnitTest.py | InteractiveCommandLine.UnitTest.py | import unittest
import MockMockMock
from InteractiveCommandLine import *
class CommandLineCommandExecution( unittest.TestCase ):
def setUp( self ):
self.command = Command()
self.optionHandler = MockMockMock.Mock( "optionHandler" )
self.command.addOption( "option", self.optionHandler )
... | import unittest
import MockMockMock
from InteractiveCommandLine import *
class CommandLineCommandExecution( unittest.TestCase ):
def setUp( self ):
self.command = Command()
self.optionHandler = MockMockMock.Mock( "optionHandler" )
self.command.addOption( "option", self.optionHandler )
... | Fix unit tests for CommandContainer | Fix unit tests for CommandContainer
| Python | mit | jacquev6/InteractiveCommandLine | ---
+++
@@ -16,14 +16,17 @@
def tearDown( self ):
self.execute.tearDown()
+
+ def __executeProgram( self, *arguments ):
+ CommandContainer.execute( self.program, *arguments )
def testWithoutArguments( self ):
self.execute.expect()
- self.program.executeWithArgument... |
22f94c5bb08ee6ae816109bdc06eab9e1974884a | app/models/cnes_professional.py | app/models/cnes_professional.py | from sqlalchemy import Column, Integer, String, func
from app import db
class CnesProfessional(db.Model):
__tablename__ = 'cnes_professional'
year = Column(Integer, primary_key=True)
region = Column(String(1), primary_key=True)
mesoregion = Column(String(4), primary_key=True)
mic... | from sqlalchemy import Column, Integer, String, func
from app import db
class CnesProfessional(db.Model):
__tablename__ = 'cnes_professional'
year = Column(Integer, primary_key=True)
region = Column(String(1), primary_key=True)
mesoregion = Column(String(4), primary_key=True)
mic... | Add CBO column to cnes professional | Add CBO column to cnes professional
| Python | mit | daniel1409/dataviva-api,DataViva/dataviva-api | ---
+++
@@ -10,6 +10,7 @@
state = Column(String(2), primary_key=True)
municipality = Column(String(7), primary_key=True)
cnes = Column(String(7), primary_key=True)
+ cbo = Column(String(2), primary_key=True)
@classmethod
def dimensions(cls):
@@ -20,6 +21,7... |
432a204f209e9470791b68297cb8453ab6ba32a8 | python3.7/app/main.py | python3.7/app/main.py | def application(env, start_response):
start_response('200 OK', [('Content-Type', 'text/html')])
return [b"Hello World from a default Nginx uWSGI Python 3.6 app in a\
Docker container (default)"]
| def application(env, start_response):
start_response('200 OK', [('Content-Type', 'text/html')])
return [b"Hello World from a default Nginx uWSGI Python 3.7 app in a\
Docker container (default)"]
| Update the message in the default Python3.7 app | Update the message in the default Python3.7 app
to show Python3.7 instead of Python3.6
| Python | apache-2.0 | tiangolo/uwsgi-nginx-docker,tiangolo/uwsgi-nginx-docker | ---
+++
@@ -1,4 +1,4 @@
def application(env, start_response):
start_response('200 OK', [('Content-Type', 'text/html')])
- return [b"Hello World from a default Nginx uWSGI Python 3.6 app in a\
+ return [b"Hello World from a default Nginx uWSGI Python 3.7 app in a\
Docker container (default)"] |
66e0e8e2cb202ca3f4832bf728bfd53c084d6f62 | appengine_config.py | appengine_config.py | """Configuration."""
import logging
import os
import re
from google.appengine.ext.appstats import recording
logging.info('Loading %s from %s', __name__, __file__)
# Custom webapp middleware to add Appstats.
def webapp_add_wsgi_middleware(app):
app = recording.appstats_wsgi_middleware(app)
return app
# Custom A... | """Configuration."""
import logging
import os
import re
from google.appengine.ext.appstats import recording
logging.info('Loading %s from %s', __name__, __file__)
# Custom webapp middleware to add Appstats.
def webapp_add_wsgi_middleware(app):
app = recording.appstats_wsgi_middleware(app)
return app
# Custom A... | Improve custom appstats path normalization. | Improve custom appstats path normalization.
| Python | apache-2.0 | rietveld-codereview/rietveld,openlabs/cr.openlabs.co.in,salomon1184/rietveld,foolonhill/rietveld,andyzsf/rietveld,arg0/rietveld,google-code-export/rietveld,berkus/rietveld,aungzanbaw/rietveld,v3ss0n/rietveld,DeanHere/rietveld,draem0507/rietveld,rietveld-codereview/rietveld,andyzsf/rietveld,dushmis/rietveld,robfig/rietv... | ---
+++
@@ -19,6 +19,12 @@
return '/user/X'
if path.startswith('/user_popup/'):
return '/user_popup/X'
+ if '/diff/' in path:
+ return '/X/diff/...'
+ if '/diff2/' in path:
+ return '/X/diff2/...'
+ if '/patch/' in path:
+ return '/X/patch/...'
if path.startswith('/... |
8868cc4e8379002c62db7f69ca77ec8449930321 | src/adhocracy_core/adhocracy_core/scripts/import_resources.py | src/adhocracy_core/adhocracy_core/scripts/import_resources.py | """Import/create resources into the system.
This is registered as console script 'import_resources' in setup.py.
"""
# pragma: no cover
import argparse
import inspect
import logging
import sys
import transaction
from pyramid.paster import bootstrap
from adhocracy_core import scripts
def import_resources():
"... | """Import/create resources into the system.
This is registered as console script 'import_resources' in setup.py.
"""
# pragma: no cover
import argparse
import inspect
import logging
import sys
import transaction
from pyramid.paster import bootstrap
from . import import_resources as main_import_resources
def impo... | Fix import resources command line wrapper | Fix import resources command line wrapper
| Python | agpl-3.0 | liqd/adhocracy3.mercator,liqd/adhocracy3.mercator,fhartwig/adhocracy3.mercator,liqd/adhocracy3.mercator,fhartwig/adhocracy3.mercator,liqd/adhocracy3.mercator,liqd/adhocracy3.mercator,fhartwig/adhocracy3.mercator,fhartwig/adhocracy3.mercator,fhartwig/adhocracy3.mercator,fhartwig/adhocracy3.mercator,liqd/adhocracy3.merca... | ---
+++
@@ -13,7 +13,7 @@
from pyramid.paster import bootstrap
-from adhocracy_core import scripts
+from . import import_resources as main_import_resources
def import_resources():
@@ -40,6 +40,6 @@
args = parser.parse_args()
env = bootstrap(args.ini_file)
logging.basicConfig(stream=sys.stdout... |
dec3aaaefe2afdf4d3ce19dc808257ea49cc2b00 | hsml.py | hsml.py | # -*- coding: utf-8 -*-
"""A small module for computing the smoothing length of a Gadget/Arepo simulation."""
import numpy as np
def get_smooth_length(bar):
"""Figures out if the particles are from AREPO or GADGET
and computes the smoothing length.
Note the Volume array in HDF5 is comoving and this return... | # -*- coding: utf-8 -*-
"""A small module for computing the smoothing length of a Gadget/Arepo simulation."""
import numpy as np
def get_smooth_length(bar):
"""Figures out if the particles are from AREPO or GADGET
and computes the smoothing length.
Note the Volume array in HDF5 is comoving and this return... | Fix for old numpy versions without cbrt | Fix for old numpy versions without cbrt
| Python | mit | sbird/fake_spectra,sbird/fake_spectra,sbird/fake_spectra | ---
+++
@@ -25,4 +25,8 @@
#There is a different kernel definition, as in gadget the kernel goes from 0 to 2,
#whereas I put it between zero and 1.
radius=np.array(bar["SmoothingLength"],dtype=np.float32)/2
+ except AttributeError:
+ #This is for really old numpys without cbrts
+ ... |
dcfb5116ba5f068afa354d063a4ab33bce853715 | numba/sigutils.py | numba/sigutils.py | from __future__ import print_function, division, absolute_import
from numba import types, typing
def is_signature(sig):
return isinstance(sig, (str, tuple))
def normalize_signature(sig):
if isinstance(sig, str):
return normalize_signature(parse_signature(sig))
elif isinstance(sig, tuple):
... | from __future__ import print_function, division, absolute_import
from numba import types, typing
def is_signature(sig):
"""
Return whether *sig* is a valid signature specification (for user-facing
APIs).
"""
return isinstance(sig, (str, tuple, typing.Signature))
def normalize_signature(sig):
... | Add docstrings and fix failures | Add docstrings and fix failures
| Python | bsd-2-clause | pitrou/numba,GaZ3ll3/numba,pitrou/numba,gdementen/numba,ssarangi/numba,gmarkall/numba,stonebig/numba,stonebig/numba,seibert/numba,GaZ3ll3/numba,gmarkall/numba,stonebig/numba,IntelLabs/numba,seibert/numba,pombredanne/numba,numba/numba,seibert/numba,jriehl/numba,pitrou/numba,numba/numba,stefanseefeld/numba,IntelLabs/numb... | ---
+++
@@ -4,10 +4,19 @@
def is_signature(sig):
- return isinstance(sig, (str, tuple))
+ """
+ Return whether *sig* is a valid signature specification (for user-facing
+ APIs).
+ """
+ return isinstance(sig, (str, tuple, typing.Signature))
def normalize_signature(sig):
+ """
+ From ... |
14cd040eb2be66bbdc62b788a4e3da1ef1297458 | doc/transaction_example.py | doc/transaction_example.py | from txpostgres import txpostgres
from twisted.internet import reactor
from twisted.python import log, util
# connect to the database
conn = txpostgres.Connection()
d = conn.connect('dbname=postgres')
# define a callable that will execute inside a transaction
def interaction(cur):
# the parameter is a txpostgres... | from txpostgres import txpostgres
from twisted.internet import reactor
from twisted.python import log
# connect to the database
conn = txpostgres.Connection()
d = conn.connect('dbname=postgres')
# define a callable that will execute inside a transaction
def interaction(cur):
# the parameter is a txpostgres Curso... | Remove unused import in the example. | Remove unused import in the example.
| Python | mit | wulczer/txpostgres | ---
+++
@@ -1,7 +1,7 @@
from txpostgres import txpostgres
from twisted.internet import reactor
-from twisted.python import log, util
+from twisted.python import log
# connect to the database
conn = txpostgres.Connection() |
ff28ca5797c4468dbe58d78d55b5df6b8878ac36 | test_pep438.py | test_pep438.py | #!/usr/bin/env python
import unittest
import pep438
if __name__ == '__main__':
unittest.main()
| #!/usr/bin/env python
import unittest
import sys
from io import StringIO
from clint.textui import core
import pep438
class patch_io(object):
streams = ('stdout', 'stdin', 'stderr')
def __init__(self):
for stream in self.streams:
setattr(self, stream, StringIO())
setattr(self... | Add a basic command line test | Add a basic command line test
| Python | mit | treyhunner/pep438 | ---
+++
@@ -1,6 +1,46 @@
#!/usr/bin/env python
import unittest
+import sys
+from io import StringIO
+
+from clint.textui import core
import pep438
+
+
+class patch_io(object):
+
+ streams = ('stdout', 'stdin', 'stderr')
+
+ def __init__(self):
+ for stream in self.streams:
+ setattr(self, s... |
a026e6c82cb6391fe7f04c85fb1c09f89fefc7de | frigg/deployments/serializers.py | frigg/deployments/serializers.py | from rest_framework import serializers
from .models import PRDeployment
class PRDeploymentSerializer(serializers.ModelSerializer):
class Meta:
model = PRDeployment
fields = (
'id',
'image',
'log',
'port',
'succeeded',
'start... | from rest_framework import serializers
from .models import PRDeployment
class PRDeploymentSerializer(serializers.ModelSerializer):
class Meta:
model = PRDeployment
fields = (
'id',
'image',
'tasks',
'port',
'succeeded',
'sta... | Add tasks and remove log from deployment serializer | Add tasks and remove log from deployment serializer
| Python | mit | frigg/frigg-hq,frigg/frigg-hq,frigg/frigg-hq | ---
+++
@@ -10,7 +10,7 @@
fields = (
'id',
'image',
- 'log',
+ 'tasks',
'port',
'succeeded',
'start_time', |
b35e8fa3cde243aa444aa056d60f7a37b61e825b | tests/commands/test_usage.py | tests/commands/test_usage.py | import os
import subprocess
import pytest
def test_list_subcommands_has_all_scripts():
"""Tests if the output from running `fontbakery --list-subcommands` matches
the fontbakery scripts within the bin folder."""
import fontbakery.commands
commands_dir = os.path.dirname(fontbakery.commands.__file__)
... | import os
import subprocess
import pytest
def test_list_subcommands_has_all_scripts():
"""Tests if the output from running `fontbakery --list-subcommands` matches
the fontbakery scripts within the bin folder."""
import fontbakery.commands
commands_dir = os.path.dirname(fontbakery.commands.__file__)
scri... | Add usage tests for check-ufo-sources and check-specification | Add usage tests for check-ufo-sources and check-specification
| Python | apache-2.0 | googlefonts/fontbakery,googlefonts/fontbakery,graphicore/fontbakery,graphicore/fontbakery,moyogo/fontbakery,graphicore/fontbakery,moyogo/fontbakery,moyogo/fontbakery,googlefonts/fontbakery | ---
+++
@@ -5,23 +5,40 @@
def test_list_subcommands_has_all_scripts():
- """Tests if the output from running `fontbakery --list-subcommands` matches
+ """Tests if the output from running `fontbakery --list-subcommands` matches
the fontbakery scripts within the bin folder."""
- import fontbakery.comma... |
ab78faab8e3536c49f829ccbd71540a93485a7cb | website/jdevents/models.py | website/jdevents/models.py | from django.db import models
from django.utils.translation import ugettext_lazy as _
from mezzanine.core.models import Displayable, RichText
class RepeatType(models.Model):
DAILY = 'daily'
WEEKLY = 'weekly',
MONTHLY = 'monthly'
REPEAT_CHOICES = (
(DAILY, _('Daily')),
(WEEKLY, _('Weekl... | from django.db import models
from django.utils.translation import ugettext_lazy as _
from mezzanine.core.models import Displayable, RichText
class Event(Displayable, RichText):
"""
Main object for each event.
Derives from Displayable, which by default
- it is related to a certain Site ob... | Delete database support for repeated events. | Delete database support for repeated events.
Events already support multiple occurences, and we will create an
API to automatically add occurences in a repeating manner (every week,
every month).
Including event repeat data in database would make things a lot more
complex.
| Python | mit | jonge-democraten/website,jonge-democraten/website,jonge-democraten/website,jonge-democraten/website | ---
+++
@@ -2,19 +2,6 @@
from django.utils.translation import ugettext_lazy as _
from mezzanine.core.models import Displayable, RichText
-
-class RepeatType(models.Model):
- DAILY = 'daily'
- WEEKLY = 'weekly',
- MONTHLY = 'monthly'
-
- REPEAT_CHOICES = (
- (DAILY, _('Daily')),
- (WEEKLY... |
a28f4b6562527ac09f765ff72e034b6122b2fa8b | yolk/__init__.py | yolk/__init__.py | """yolk.
Author: Rob Cakebread <cakebread at gmail>
License : BSD
"""
__version__ = '0.8a0'
| """yolk.
Author: Rob Cakebread <cakebread at gmail>
License : BSD
"""
__version__ = '0.8'
| Increment minor version to 0.8 | Increment minor version to 0.8
| Python | bsd-3-clause | myint/yolk,myint/yolk | ---
+++
@@ -6,4 +6,4 @@
"""
-__version__ = '0.8a0'
+__version__ = '0.8' |
f34a5d682832749dbf0011d162bf4c7c18892b45 | zerver/apps.py | zerver/apps.py |
import logging
from typing import Any, Dict
from django.apps import AppConfig
from django.conf import settings
from django.core.cache import cache
from django.db.models.signals import post_migrate
def flush_cache(sender: AppConfig, **kwargs: Any) -> None:
logging.info("Clearing memcached cache after migrations")... |
import logging
from typing import Any, Dict
from django.apps import AppConfig
from django.conf import settings
from django.core.cache import cache
from django.db.models.signals import post_migrate
def flush_cache(sender: AppConfig, **kwargs: Any) -> None:
logging.info("Clearing memcached cache after migrations")... | Document the weird unused import for signal registration. | signals: Document the weird unused import for signal registration.
| Python | apache-2.0 | timabbott/zulip,tommyip/zulip,zulip/zulip,andersk/zulip,andersk/zulip,eeshangarg/zulip,kou/zulip,eeshangarg/zulip,eeshangarg/zulip,showell/zulip,brainwane/zulip,andersk/zulip,rishig/zulip,synicalsyntax/zulip,andersk/zulip,tommyip/zulip,hackerkid/zulip,kou/zulip,zulip/zulip,showell/zulip,eeshangarg/zulip,shubhamdhama/zu... | ---
+++
@@ -16,6 +16,11 @@
name = "zerver" # type: str
def ready(self) -> None:
+ # We import zerver.signals here for the side effect of
+ # registering the user_logged_in signal receiver. This import
+ # needs to be here (rather than e.g. at top-of-file) to avoid
+ # running... |
55e506489e93bad1d000acd747a272103e789a59 | rml/element.py | rml/element.py | ''' Representation of an element
@param element_type: type of the element
@param length: length of the element
'''
import pkg_resources
from rml.exceptions import ConfigException
pkg_resources.require('cothread')
from cothread.catools import caget
class Element(object):
def __init__(self, element_type, length, **... | ''' Representation of an element
@param element_type: type of the element
@param length: length of the element
'''
import pkg_resources
from rml.exceptions import ConfigException
pkg_resources.require('cothread')
from cothread.catools import caget
class Element(object):
def __init__(self, element_type, length, **... | Add support for y field of a pv | Add support for y field of a pv
| Python | apache-2.0 | willrogers/pml,razvanvasile/RML,willrogers/pml | ---
+++
@@ -14,9 +14,9 @@
self.length = length
self.families = set()
- # Getting the pv value
- self.pv = kwargs.get('pv', None)
- self._field = {}
+ # For storing the pv. Dictionary where keys are fields and
+ # values are pv names
+ self.pv = dict()
... |
eab72cdb7e58b5398ace19c74569b1eb35ea91f8 | toolbox/plugins/standard_object_features.py | toolbox/plugins/standard_object_features.py | from pluginsystem import object_feature_computation_plugin
import vigra
from vigra import numpy as np
class StandardObjectFeatures(object_feature_computation_plugin.ObjectFeatureComputationPlugin):
"""
Computes the standard vigra region features
"""
worksForDimensions = [2, 3]
omittedFeatures = ["G... | from pluginsystem import object_feature_computation_plugin
import vigra
from vigra import numpy as np
class StandardObjectFeatures(object_feature_computation_plugin.ObjectFeatureComputationPlugin):
"""
Computes the standard vigra region features
"""
worksForDimensions = [2, 3]
omittedFeatures = ["G... | Fix default region feature computation plugin | Fix default region feature computation plugin
| Python | mit | chaubold/hytra,chaubold/hytra,chaubold/hytra | ---
+++
@@ -10,7 +10,7 @@
omittedFeatures = ["Global<Maximum >", "Global<Minimum >", 'Histogram', 'Weighted<RegionCenter>']
def computeFeatures(self, rawImage, labelImage, frameNumber):
- return vigra.analysis.extractRegionFeatures(rawImage.astype('float32'),
- ... |
0b8075e8eb8fb52a9407bfa92d61e5a5363f8861 | src/example/dump_camera_capabilities.py | src/example/dump_camera_capabilities.py | import pysony
import fnmatch
camera = pysony.SonyAPI()
#camera = pysony.SonyAPI(QX_ADDR='http://192.168.122.1:8080/')
mode = camera.getAvailableApiList()
print "Available calls:"
for x in (mode["result"]):
for y in x:
print y
filtered = fnmatch.filter(x, "*Supported*")
print "--"
for x in filtered:... | import pysony
import time
import fnmatch
print "Searching for camera"
search = pysony.ControlPoint()
cameras = search.discover()
if len(cameras):
camera = pysony.SonyAPI(QX_ADDR=cameras[0])
else:
print "No camera found, aborting"
quit()
mode = camera.getAvailableApiList()
# For those cameras which nee... | Add automatic searching capability. Note that camera may return different capabilities depending on its mode dial. | Add automatic searching capability.
Note that camera may return different capabilities depending on its mode dial.
| Python | mit | Bloodevil/sony_camera_api,mungewell/sony_camera_api,Bloodevil/sony_camera_api | ---
+++
@@ -1,10 +1,27 @@
import pysony
+import time
import fnmatch
-camera = pysony.SonyAPI()
-#camera = pysony.SonyAPI(QX_ADDR='http://192.168.122.1:8080/')
+print "Searching for camera"
+
+search = pysony.ControlPoint()
+cameras = search.discover()
+
+if len(cameras):
+ camera = pysony.SonyAPI(QX_ADDR=came... |
fb71c13e0995957f1879d8e8ce047f347777564e | testing/test_BioMagick.py | testing/test_BioMagick.py | #!/usr/bin/env python
# ----------------------------------------------------------------------------------------------
# Created by: Lee & Matt
#
# Description: Contains unit test for BioID Class
# ----------------------------------------------------------------------------------------------
# ========================... | #!/usr/bin/env python
# ----------------------------------------------------------------------------------------------
# Created by: Lee & Matt
#
# Description: Contains unit test for BioID Class
# ----------------------------------------------------------------------------------------------
# ========================... | Disable end-to-end tests for debugging (will re-enable later!) | Disable end-to-end tests for debugging (will re-enable later!)
| Python | mit | LeeBergstrand/BioMagick,LeeBergstrand/BioMagick | ---
+++
@@ -28,6 +28,10 @@
@staticmethod
def check_conversion(input_files, expected_outputs, output_formats, alphabet):
+ # Disable for debugging
+ assert True
+ return
+
# Set up CLI arguments
args = "-i %s -f %s -a %s" % (",".join(input_files), ",".join(output_formats), alphabet)
|
3c3ceddf3c7d92e6e66017c0980102421e9bbe43 | tests/test_integration.py | tests/test_integration.py | import os
import types
from unittest import TestCase
from yoconfigurator.base import read_config
from yoconfig import configure_services
from pycloudflare.services import CloudFlareService
app_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
conf = read_config(app_dir)
class ZonesTest(TestCase)... | import os
import types
from unittest import TestCase
from yoconfigurator.base import read_config
from yoconfig import configure_services
from pycloudflare.services import CloudFlareService
app_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
conf = read_config(app_dir)
class ZonesTest(TestCase)... | Use next to get the zone | Use next to get the zone
| Python | mit | yola/pycloudflare,gnowxilef/pycloudflare | ---
+++
@@ -21,6 +21,6 @@
self.assertIsInstance(zone, dict)
def test_get_zone(self):
- zone_id = self.cloudflare.get_zones()[0]['id']
+ zone_id = next(self.cloudflare.iter_zones())['id']
zone = self.cloudflare.get_zone(zone_id)
self.assertIsInstance(zone, dict) |
dbb15e4919c5d54d2e755cea700cc287bf164ad4 | bom_data_parser/climate_data_online.py | bom_data_parser/climate_data_online.py | import os
import numpy as np
import pandas as pd
import zipfile
from bom_data_parser import mapper
def read_climate_data_online_csv(fname):
df = pd.read_csv(fname, parse_dates={'Date': [2,3,4]})
column_names = []
for column in df.columns:
column_names.append(mapper.convert_key(column))
df.co... | import os
import numpy as np
import pandas as pd
import zipfile
from bom_data_parser import mapper
def read_climate_data_online_csv(fname):
df = pd.read_csv(fname, parse_dates={'Date': [2,3,4]})
column_names = []
for column in df.columns:
column_names.append(mapper.convert_key(column))
df.co... | Handle just the zip file name when splitting | Handle just the zip file name when splitting
This fixes a bug where the zip file name isn't correctly handled when
splitting on the '.'. This causes a failure if passing a relative path
(e.g '../'). Would also be a problem if directories had periods in their
name.
| Python | bsd-3-clause | amacd31/bom_data_parser,amacd31/bom_data_parser | ---
+++
@@ -36,10 +36,8 @@
..note: Requires the filename to have been unchanged because it is used for identifying the contained data file.
"""
- filename = fname.split('.')[0]
- with zipfile.ZipFile('{0}.zip'.format(filename)) as zf:
- #notes = zf.read('{0}_Note.txt'.format(filename))
- ... |
e8030cfb3daee6b7e467f50a215fbffc5ef90223 | api/preprint_providers/serializers.py | api/preprint_providers/serializers.py | from rest_framework import serializers as ser
from api.base.serializers import JSONAPISerializer
class PreprintProviderSerializer(JSONAPISerializer):
filterable_fields = frozenset([
'name',
'description',
'id'
])
name = ser.CharField(required=True)
description = ser.CharFiel... | from rest_framework import serializers as ser
from website.settings import API_DOMAIN
from api.base.settings.defaults import API_BASE
from api.base.serializers import JSONAPISerializer, LinksField
class PreprintProviderSerializer(JSONAPISerializer):
filterable_fields = frozenset([
'name',
'descri... | Add links field and related methods to link to a given provider's preprints from the preprint provider serializer | Add links field and related methods to link to a given provider's preprints from the preprint provider serializer
| Python | apache-2.0 | CenterForOpenScience/osf.io,icereval/osf.io,laurenrevere/osf.io,HalcyonChimera/osf.io,cslzchen/osf.io,binoculars/osf.io,acshi/osf.io,chrisseto/osf.io,adlius/osf.io,cwisecarver/osf.io,cslzchen/osf.io,erinspace/osf.io,mluo613/osf.io,mluo613/osf.io,mluo613/osf.io,caseyrollins/osf.io,rdhyee/osf.io,aaxelb/osf.io,monikagrabo... | ---
+++
@@ -1,7 +1,8 @@
from rest_framework import serializers as ser
-from api.base.serializers import JSONAPISerializer
-
+from website.settings import API_DOMAIN
+from api.base.settings.defaults import API_BASE
+from api.base.serializers import JSONAPISerializer, LinksField
class PreprintProviderSerializer(J... |
9be04ea1030b423b7414dbd386ae2db2f4761f07 | third_party/bunch/bunch/python3_compat.py | third_party/bunch/bunch/python3_compat.py | import platform
_IS_PYTHON_3 = (platform.version() >= '3')
identity = lambda x : x
# u('string') replaces the forwards-incompatible u'string'
if _IS_PYTHON_3:
u = identity
else:
import codecs
def u(string):
return codecs.unicode_escape_decode(string)[0]
# dict.iteritems(), dict.iterkeys() is als... | import sys
_IS_PYTHON_3 = (sys.version[0] >= '3')
identity = lambda x : x
# u('string') replaces the forwards-incompatible u'string'
if _IS_PYTHON_3:
u = identity
else:
import codecs
def u(string):
return codecs.unicode_escape_decode(string)[0]
# dict.iteritems(), dict.iterkeys() is also incompa... | Fix Python 3 version detection in bunch | Fix Python 3 version detection in bunch
| Python | apache-2.0 | mbrukman/cloud-launcher,mbrukman/cloud-launcher,mbrukman/cloud-launcher,mbrukman/cloud-launcher | ---
+++
@@ -1,6 +1,6 @@
-import platform
+import sys
-_IS_PYTHON_3 = (platform.version() >= '3')
+_IS_PYTHON_3 = (sys.version[0] >= '3')
identity = lambda x : x
|
dd171296a980dcc0349cf54b2afd6d2399cfb981 | numba/tests/matmul_usecase.py | numba/tests/matmul_usecase.py | import sys
try:
import scipy.linalg.cython_blas
has_blas = True
except ImportError:
has_blas = False
import numba.unittest_support as unittest
# The "@" operator only compiles on Python 3.5+.
has_matmul = sys.version_info >= (3, 5)
if has_matmul:
code = """if 1:
def matmul_usecase(x, y):
... | import sys
try:
import scipy.linalg.cython_blas
has_blas = True
except ImportError:
has_blas = False
import numba.unittest_support as unittest
from numba.numpy_support import version as numpy_version
# The "@" operator only compiles on Python 3.5+.
# It is only supported by Numpy 1.10+.
has_matmul = sys... | Fix test failure on Numpy 1.9 and Python 3.5 | Fix test failure on Numpy 1.9 and Python 3.5
The "@" operator between arrays is only supported by Numpy 1.10+.
| Python | bsd-2-clause | numba/numba,cpcloud/numba,stuartarchibald/numba,numba/numba,stefanseefeld/numba,gmarkall/numba,sklam/numba,stefanseefeld/numba,stefanseefeld/numba,jriehl/numba,IntelLabs/numba,seibert/numba,IntelLabs/numba,seibert/numba,stuartarchibald/numba,stonebig/numba,cpcloud/numba,sklam/numba,cpcloud/numba,stefanseefeld/numba,skl... | ---
+++
@@ -7,10 +7,12 @@
has_blas = False
import numba.unittest_support as unittest
+from numba.numpy_support import version as numpy_version
# The "@" operator only compiles on Python 3.5+.
-has_matmul = sys.version_info >= (3, 5)
+# It is only supported by Numpy 1.10+.
+has_matmul = sys.version_info >... |
4e62f8292802aade03637dbbd05be56b9fad7d61 | utils/snapshot_widgets.py | utils/snapshot_widgets.py |
"""
Alternative interact function that creates a single static figure that can
be viewed online, e.g. on Github or nbviewer, or for use with nbconvert.
"""
from __future__ import print_function
print("Will create static figures with single value of parameters")
def interact(f, **kwargs):
fargs = {}
for key ... |
"""
Alternative interact function that creates a single static figure that can
be viewed online, e.g. on Github or nbviewer, or for use with nbconvert.
"""
from __future__ import print_function
print("Will create static figures with single value of parameters")
def interact(f, **kwargs):
fargs = {}
for key ... | Use t=0.2 instead of t=0 for static widget output. | Use t=0.2 instead of t=0 for static widget output.
| Python | bsd-3-clause | maojrs/riemann_book,maojrs/riemann_book,maojrs/riemann_book | ---
+++
@@ -15,4 +15,7 @@
fargs[key] = kwargs[key].value
except:
pass # if initial value not set for this parameter
+ if ('t' in fargs.keys()):
+ if fargs['t'] == 0:
+ fargs['t'] = 0.2
f(**fargs) |
6e5b13859b8a795b08189dde7ce1aab4cca18827 | address/apps.py | address/apps.py | from django.apps import AppConfig
class AddressConfig(AppConfig):
"""
Define config for the member app so that we can hook in signals.
"""
name = "address"
| from django.apps import AppConfig
class AddressConfig(AppConfig):
"""
Define config for the member app so that we can hook in signals.
"""
name = "address"
default_auto_field = "django.db.models.AutoField"
| Set default ID field to AutoField | :bug: Set default ID field to AutoField
Resolves #168
| Python | bsd-3-clause | furious-luke/django-address,furious-luke/django-address,furious-luke/django-address | ---
+++
@@ -7,3 +7,4 @@
"""
name = "address"
+ default_auto_field = "django.db.models.AutoField" |
2095b3f18926a9ab08faeae634f4f4653e4b7590 | admin/manage.py | admin/manage.py | from freeposte import manager, db
from freeposte.admin import models
@manager.command
def flushdb():
""" Flush the database
"""
db.drop_all()
@manager.command
def initdb():
""" Initialize the database
"""
db.create_all()
@manager.command
def admin(localpart, domain_name, password):
"""... | from freeposte import manager, db
from freeposte.admin import models
from passlib import hash
@manager.command
def flushdb():
""" Flush the database
"""
db.drop_all()
@manager.command
def initdb():
""" Initialize the database
"""
db.create_all()
@manager.command
def admin(localpart, domain... | Fix the admin creation command | Fix the admin creation command
| Python | mit | kaiyou/freeposte.io,kaiyou/freeposte.io,kaiyou/freeposte.io,kaiyou/freeposte.io | ---
+++
@@ -1,5 +1,6 @@
from freeposte import manager, db
from freeposte.admin import models
+from passlib import hash
@manager.command
@@ -20,7 +21,7 @@
def admin(localpart, domain_name, password):
""" Create an admin user
"""
- domain = models.Domain(name=domain)
+ domain = models.Domain(nam... |
87e5d0e5e92ed5f94e4238e73453934abc7835dd | src/tutorials/code/python/chat/5.py | src/tutorials/code/python/chat/5.py | from chatty import create
import config
from tornado.ioloop import PeriodicCallback, IOLoop
from functools import partial
if __name__ == "__main__":
chat = create(config)
# Tell chat to authenticate with the beam server. It'll throw
# a chatty.errors.NotAuthenticatedError if it fails.
chat.authenticate(config.C... | from chatty import create
import config
from tornado.ioloop import PeriodicCallback, IOLoop
if __name__ == "__main__":
chat = create(config)
# Tell chat to authenticate with the beam server. It'll throw
# a chatty.errors.NotAuthenticatedError if it fails.
chat.authenticate(config.CHANNEL)
# Han... | Replace partial with a function definition | Replace partial with a function definition
Fix indentation, as well. | Python | mit | WatchBeam/developers,WatchBeam/developers,WatchBeam/developers,WatchBeam/developers,WatchBeam/developers | ---
+++
@@ -2,24 +2,27 @@
import config
from tornado.ioloop import PeriodicCallback, IOLoop
-from functools import partial
if __name__ == "__main__":
chat = create(config)
-# Tell chat to authenticate with the beam server. It'll throw
-# a chatty.errors.NotAuthenticatedError if it fails.
-chat.authent... |
b6e40edee998170fafe92096447a0f54e9adb86f | tracker/src/main/scripts/launch-workflow.py | tracker/src/main/scripts/launch-workflow.py | import sys
import os
import uuid
from time import sleep
if len(sys.argv) != 3:
print "Wrong number of args"
exit(1)
workflow_name = sys.argv[1]
num_runs = int(sys.argv[2])
for this_run in range(num_runs):
run_uuid = uuid.uuid4()
launch_command = "airflow trigger_dag -r " + run_uuid + " ... | import sys
import os
import uuid
from time import sleep
if len(sys.argv) != 3:
print "Wrong number of args"
exit(1)
workflow_name = sys.argv[1]
num_runs = int(sys.argv[2])
for this_run in range(num_runs):
run_uuid = str(uuid.uuid4())
launch_command = "airflow trigger_dag -r " + run_uuid... | Convert run uuid to string | Convert run uuid to string
| Python | mit | llevar/germline-regenotyper,llevar/germline-regenotyper | ---
+++
@@ -12,7 +12,7 @@
for this_run in range(num_runs):
- run_uuid = uuid.uuid4()
+ run_uuid = str(uuid.uuid4())
launch_command = "airflow trigger_dag -r " + run_uuid + " " + workflow_name
print("Launching workflow with command: " + launch_command) |
d3cc8fdbad2ca6888e33b119faae68d691ab291e | tests/system/test_lets-do-dns_script.py | tests/system/test_lets-do-dns_script.py | import os
import subprocess
from requests import get, delete
def test_pre_authentication_hook(env):
os.environ.update({
'DO_API_KEY': env.key,
'DO_DOMAIN': env.domain,
'CERTBOT_DOMAIN': '%s.%s' % (env.hostname, env.domain),
'CERTBOT_VALIDATION': env.auth_token,
})
record_i... | import os
import subprocess
from requests import get, delete, post
def test_pre_authentication_hook(env):
os.environ.update({
'DO_API_KEY': env.key,
'DO_DOMAIN': env.domain,
'CERTBOT_DOMAIN': '%s.%s' % (env.hostname, env.domain),
'CERTBOT_VALIDATION': env.auth_token,
})
re... | Test Post-Authentication Hook Process Works | Test Post-Authentication Hook Process Works
This is my second system level test, and it's currently failing. My
next steps are to work on the integration test, followed by a slew
of unit tests to start testing driving the final design of the
program to handle this second, and possibly final, piece.
| Python | apache-2.0 | Jitsusama/lets-do-dns | ---
+++
@@ -1,6 +1,6 @@
import os
import subprocess
-from requests import get, delete
+from requests import get, delete, post
def test_pre_authentication_hook(env):
@@ -25,3 +25,29 @@
record_data['data'] == env.auth_token)
delete(request_uri, headers=env.auth_header)
+
+
+def test_post_auth... |
c96000a231d5bbf60a310e091b9895bfb249c115 | conditional/blueprints/spring_evals.py | conditional/blueprints/spring_evals.py | from flask import Blueprint
from flask import render_template
from flask import request
spring_evals_bp = Blueprint('spring_evals_bp', __name__)
@spring_evals_bp.route('/spring_evals/')
def display_spring_evals():
# get user data
user_name = request.headers.get('x-webauth-user')
members = [
... | from flask import Blueprint
from flask import render_template
from flask import request
spring_evals_bp = Blueprint('spring_evals_bp', __name__)
@spring_evals_bp.route('/spring_evals/')
def display_spring_evals():
# get user data
user_name = request.headers.get('x-webauth-user')
members = [
... | FIx house meeting schema spring evals | FIx house meeting schema spring evals
| Python | mit | ComputerScienceHouse/conditional,RamZallan/conditional,RamZallan/conditional,ComputerScienceHouse/conditional,RamZallan/conditional,ComputerScienceHouse/conditional | ---
+++
@@ -14,8 +14,7 @@
{
'name': "Liam Middlebrook",
'committee_meetings': 24,
- 'house_meetings_missed': 0,
- 'house_meetings_comments': "",
+ 'house_meetings_missed': [{'date': "aprial fools fayas ... |
d8cb207348a86b1bf9593f882a97eccdf48461df | lsv_compassion/model/invoice_line.py | lsv_compassion/model/invoice_line.py | # -*- encoding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2015 Compassion CH (http://www.compassion.ch)
# Releasing children from poverty in Jesus' name
# @author: Emanuel Cino <ecino@compassion.ch>
#
# The licence is in the file __open... | # -*- encoding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2015 Compassion CH (http://www.compassion.ch)
# Releasing children from poverty in Jesus' name
# @author: Emanuel Cino <ecino@compassion.ch>
#
# The licence is in the file __open... | Change child_name to related field. | Change child_name to related field.
| Python | agpl-3.0 | Secheron/compassion-switzerland,ecino/compassion-switzerland,eicher31/compassion-switzerland,eicher31/compassion-switzerland,CompassionCH/compassion-switzerland,CompassionCH/compassion-switzerland,CompassionCH/compassion-switzerland,MickSandoz/compassion-switzerland,ecino/compassion-switzerland,ndtran/compassion-switze... | ---
+++
@@ -15,17 +15,7 @@
class invoice_line(orm.Model):
_inherit = 'account.invoice.line'
- def _get_child_name(self, cr, uid, ids, name, dict, context=None):
- res = {}
- for line in self.browse(cr, uid, ids, context):
- child_name = ''
- if line.contract_id and line.... |
f50f892e2ad2108342f53406ea86f65f89eeaafb | PythonScript/Helper/Helper.py | PythonScript/Helper/Helper.py | # This Python file uses the following encoding: utf-8
def main():
try:
fileName = "MengZi_Traditional.md"
filePath = "../../source/" + fileName
content = None
with open(filePath,'r') as file:
content = file.read().decode("utf-8")
content = content.replace(u"「",u'“... | # This Python file uses the following encoding: utf-8
def Convert(content):
tradtionalToSimplified = {
u"「":u"“",
u"」":u"”",
u"『":u"‘",
u"』":u"’",
}
for key in tradtionalToSimplified:
content = content.replace(key, tradtionalToSimplified[key])
return content
... | Use Convert() to simplify code | Use Convert() to simplify code
| Python | mit | fan-jiang/Dujing | ---
+++
@@ -1,15 +1,25 @@
# This Python file uses the following encoding: utf-8
+
+def Convert(content):
+ tradtionalToSimplified = {
+ u"「":u"“",
+ u"」":u"”",
+ u"『":u"‘",
+ u"』":u"’",
+
+ }
+ for key in tradtionalToSimplified:
+ content = content.replace(key, tradtiona... |
3ef3a5f4b0453af2d6853bc017fe4c44b9ee90ab | migrations/versions/45a35ac9bfe_create_lr_uprn_column_with_a_gin_index.py | migrations/versions/45a35ac9bfe_create_lr_uprn_column_with_a_gin_index.py | """Create lr_uprn column with a GIN index
Revision ID: 45a35ac9bfe
Revises: 2bbd8de7dcb
Create Date: 2015-09-22 10:36:04.307515
"""
# revision identifiers, used by Alembic.
revision = '45a35ac9bfe'
down_revision = '2bbd8de7dcb'
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresq... | """Create lr_uprn column with a GIN index
Revision ID: 45a35ac9bfe
Revises: 2bbd8de7dcb
Create Date: 2015-09-22 10:36:04.307515
"""
# revision identifiers, used by Alembic.
revision = '45a35ac9bfe'
down_revision = '2bbd8de7dcb'
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresq... | Fix not nullable field for lr-uprns to be nullable | Fix not nullable field for lr-uprns to be nullable
| Python | mit | LandRegistry/digital-register-api,LandRegistry/digital-register-api | ---
+++
@@ -16,7 +16,7 @@
def upgrade():
### commands auto generated by Alembic - please adjust! ###
- op.add_column('title_register_data', sa.Column('lr_uprns', postgresql.ARRAY(sa.String()), nullable=False))
+ op.add_column('title_register_data', sa.Column('lr_uprns', postgresql.ARRAY(sa.String()), nu... |
c2c488210b2c1ec3b1edfba1e510d228fa5e74d2 | partner_communication_switzerland/migrations/12.0.1.1.2/post-migration.py | partner_communication_switzerland/migrations/12.0.1.1.2/post-migration.py | from openupgradelib import openupgrade
def migrate(cr, installed_version):
if not installed_version:
return
# Update data
openupgrade.load_xml(
cr, "partner_communication_switzerland", "data/onboarding_process.xml")
| from openupgradelib import openupgrade
def migrate(cr, installed_version):
if not installed_version:
return
# Copy start_date over onboarding_start_date
cr.execute("""
UPDATE recurring_contract
SET onboarding_start_date = start_date
WHERE is_first_sponsorship = true
""... | Include migration for current runnning onboarding processes | Include migration for current runnning onboarding processes
| Python | agpl-3.0 | CompassionCH/compassion-switzerland,eicher31/compassion-switzerland,CompassionCH/compassion-switzerland,eicher31/compassion-switzerland,eicher31/compassion-switzerland,CompassionCH/compassion-switzerland | ---
+++
@@ -5,6 +5,12 @@
if not installed_version:
return
+ # Copy start_date over onboarding_start_date
+ cr.execute("""
+ UPDATE recurring_contract
+ SET onboarding_start_date = start_date
+ WHERE is_first_sponsorship = true
+ """)
# Update data
openupgrade.lo... |
049e21dd2d4e90120bfe297696cffa5000028854 | dynd/benchmarks/benchmark_arithmetic.py | dynd/benchmarks/benchmark_arithmetic.py | import numpy as np
from dynd import nd, ndt
from benchrun import Benchmark, clock
class ArithemticBenchmark(Benchmark):
parameters = ('size',)
size = [100000, 10000000]
def run(self, size):
a = nd.uniform(dst_tp = ndt.type('{} * float64'.format(size)))
b = nd.uniform(dst_tp = ndt.type('{} * float64'.f... | import numpy as np
from dynd import nd, ndt
from benchrun import Benchmark, clock
class ArithmeticBenchmark(Benchmark):
parameters = ('size',)
size = [100000, 10000000, 100000000]
def run(self, size):
a = nd.uniform(dst_tp = ndt.type('{} * float64'.format(size)))
b = nd.uniform(dst_tp = ndt.type('{} *... | Add one bigger size to arithmetic benchmark | Add one bigger size to arithmetic benchmark
| Python | bsd-2-clause | michaelpacer/dynd-python,insertinterestingnamehere/dynd-python,pombredanne/dynd-python,pombredanne/dynd-python,cpcloud/dynd-python,ContinuumIO/dynd-python,michaelpacer/dynd-python,izaid/dynd-python,michaelpacer/dynd-python,insertinterestingnamehere/dynd-python,izaid/dynd-python,mwiebe/dynd-python,izaid/dynd-python,mwie... | ---
+++
@@ -4,9 +4,9 @@
from benchrun import Benchmark, clock
-class ArithemticBenchmark(Benchmark):
+class ArithmeticBenchmark(Benchmark):
parameters = ('size',)
- size = [100000, 10000000]
+ size = [100000, 10000000, 100000000]
def run(self, size):
a = nd.uniform(dst_tp = ndt.type('{} * float64'... |
a34a34c1bf897b5681e7a421ea53ca5e9d065ab8 | src/zeit/cms/tagging/testing.py | src/zeit/cms/tagging/testing.py | # Copyright (c) 2011 gocept gmbh & co. kg
# See also LICENSE.txt
import mock
import zeit.cms.tagging.tag
class TaggingHelper(object):
"""Mixin for tests which need some tagging infrastrucutre."""
def get_tag(self, code):
tag = zeit.cms.tagging.tag.Tag(code, code)
tag.disabled = False
... | # Copyright (c) 2011 gocept gmbh & co. kg
# See also LICENSE.txt
import mock
import zeit.cms.tagging.tag
class TaggingHelper(object):
"""Mixin for tests which need some tagging infrastrucutre."""
def get_tag(self, code):
tag = zeit.cms.tagging.tag.Tag(code, code)
return tag
def setup_ta... | Remove superfluous variable ('disabled' is a concept of zeit.intrafind and doesn't belong here) | Remove superfluous variable ('disabled' is a concept of zeit.intrafind and doesn't belong here)
| Python | bsd-3-clause | ZeitOnline/zeit.cms,ZeitOnline/zeit.cms,ZeitOnline/zeit.cms,ZeitOnline/zeit.cms | ---
+++
@@ -10,7 +10,6 @@
def get_tag(self, code):
tag = zeit.cms.tagging.tag.Tag(code, code)
- tag.disabled = False
return tag
def setup_tags(self, *codes): |
cf7086620df23d8af15f7c9898edf39f64965549 | dbaas/workflow/steps/util/region_migration/check_instances_status.py | dbaas/workflow/steps/util/region_migration/check_instances_status.py | # -*- coding: utf-8 -*-
import logging
from util import full_stack
from workflow.steps.util.base import BaseStep
from workflow.exceptions.error_codes import DBAAS_0020
LOG = logging.getLogger(__name__)
class DecreaseTTL(BaseStep):
def __unicode__(self):
return "Checking instances status..."
def do(... | # -*- coding: utf-8 -*-
import logging
from util import full_stack
from workflow.steps.util.base import BaseStep
from workflow.exceptions.error_codes import DBAAS_0020
from drivers.base import ConnectionError
LOG = logging.getLogger(__name__)
class CheckInstancesStatus(BaseStep):
def __unicode__(self):
... | Add step to check instances status | Add step to check instances status
| Python | bsd-3-clause | globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service | ---
+++
@@ -3,17 +3,31 @@
from util import full_stack
from workflow.steps.util.base import BaseStep
from workflow.exceptions.error_codes import DBAAS_0020
+from drivers.base import ConnectionError
LOG = logging.getLogger(__name__)
-class DecreaseTTL(BaseStep):
+class CheckInstancesStatus(BaseStep):
d... |
c416c998d73e27713fd57ec97c70bacb2390f8c9 | DashDoc.py | DashDoc.py | import sublime
import sublime_plugin
import os
import subprocess
def syntax_name(view):
syntax = os.path.basename(view.settings().get('syntax'))
syntax = os.path.splitext(syntax)[0]
return syntax
def docset_prefix(view, settings):
syntax_docset_map = settings.get('syntax_docset_map', {})
syntax ... | import sublime
import sublime_plugin
import os
import subprocess
def syntax_name(view):
syntax = os.path.basename(view.settings().get('syntax'))
syntax = os.path.splitext(syntax)[0]
return syntax
def camel_case(word):
return ''.join(w.capitalize() if i > 0 else w
for i, w in enume... | Use Dash's new CamelCase convention to lookup words that contain whitespace | Use Dash's new CamelCase convention to lookup words that contain whitespace
- Example: converting "create table" into "createTable" will lookup "CREATE TABLE"
| Python | apache-2.0 | farcaller/DashDoc | ---
+++
@@ -8,6 +8,11 @@
syntax = os.path.basename(view.settings().get('syntax'))
syntax = os.path.splitext(syntax)[0]
return syntax
+
+
+def camel_case(word):
+ return ''.join(w.capitalize() if i > 0 else w
+ for i, w in enumerate(word.split()))
def docset_prefix(view, settin... |
4983713ae15079872a8838e702b235f095f913b3 | examples/list_people.py | examples/list_people.py | #! /usr/bin/python
# See README.txt for information and build instructions.
import addressbook_pb2
import sys
# Iterates though all people in the AddressBook and prints info about them.
def ListPeople(address_book):
for person in address_book.person:
print "Person ID:", person.id
print " Name:", person.na... | #! /usr/bin/python
# See README.txt for information and build instructions.
import addressbook_pb2
import sys
# Iterates though all people in the AddressBook and prints info about them.
def ListPeople(address_book):
for person in address_book.person:
print "Person ID:", person.id
print " Name:", person.na... | Make Python example output identical to C++ and Java by removing redundant spaces. | Make Python example output identical to C++ and Java by removing redundant
spaces.
| Python | bsd-3-clause | nilavghosh/Protocol-Buffers-Fork,nilavghosh/Protocol-Buffers-Fork,nilavghosh/Protocol-Buffers-Fork,nilavghosh/Protocol-Buffers-Fork,nilavghosh/Protocol-Buffers-Fork | ---
+++
@@ -15,11 +15,11 @@
for phone_number in person.phone:
if phone_number.type == addressbook_pb2.Person.MOBILE:
- print " Mobile phone #: ",
+ print " Mobile phone #:",
elif phone_number.type == addressbook_pb2.Person.HOME:
- print " Home phone #: ",
+ print " ... |
0ce491e39b4cb866b2b749692dbaed8cb1cf6dac | plots/views.py | plots/views.py | # Create your views here.
from django.template import RequestContext
from django.shortcuts import render_to_response
from django.utils import simplejson
from django.http import HttpResponse, Http404
from .models import BenchmarkLogs, MachineInfo
def rawdata(request, type):
if type == "AvgVGRvsProcessor":
def dr... | # Create your views here.
from django.template import RequestContext
from django.shortcuts import render_to_response
from django.utils import simplejson
from django.http import HttpResponse, Http404
from .models import BenchmarkLogs, MachineInfo
def rawdata(request, type):
#if type == "AvgVGRvsProcessor":
ret... | Add a stub return to ensure the project builds. | Add a stub return to ensure the project builds.
| Python | bsd-2-clause | ankeshanand/benchmark,ankeshanand/benchmark,ankeshanand/benchmark,ankeshanand/benchmark | ---
+++
@@ -7,8 +7,8 @@
from .models import BenchmarkLogs, MachineInfo
def rawdata(request, type):
- if type == "AvgVGRvsProcessor":
-
+ #if type == "AvgVGRvsProcessor":
+ return
def draw(request, type):
type_dict = {'type': type} |
02f77babc6195426fdb5c495d44ede6af6fbec8f | mangopaysdk/entities/userlegal.py | mangopaysdk/entities/userlegal.py | from mangopaysdk.entities.entitybase import EntityBase
from mangopaysdk.entities.user import User
from mangopaysdk.tools.enums import PersonType
from mangopaysdk.tools.enums import KYCLevel
class UserLegal (User):
def __init__(self, id = None):
super(UserLegal, self).__init__(id)
self._setPersonT... | from mangopaysdk.entities.entitybase import EntityBase
from mangopaysdk.entities.user import User
from mangopaysdk.tools.enums import PersonType
from mangopaysdk.tools.enums import KYCLevel
class UserLegal (User):
def __init__(self, id = None):
super(UserLegal, self).__init__(id)
self._setPersonT... | Add LegalRepresentativeProofOfIdentity to legal user | Add LegalRepresentativeProofOfIdentity to legal user | Python | mit | chocopoche/mangopay2-python-sdk,Mangopay/mangopay2-python-sdk | ---
+++
@@ -29,10 +29,12 @@
self._statute = None
self._proofOfRegistration = None
self._shareholderDeclaration = None
+ self._legalRepresentativeProofOfIdentity = None
def GetReadOnlyProperties(self):
properties = super(UserLegal, self).GetReadOnlyProperties()
... |
732fb749247c94fe0dbf3b98ca691d139970bc48 | tests/doctests/test_doctests.py | tests/doctests/test_doctests.py | import os
import doctest
import unittest
DOCTEST_FILES = []
for root, dirs, files in os.walk("."):
if ".hg%s" % os.path.sep not in root:
for f in files:
if f.endswith(".doctest"):
DOCTEST_FILES.append(f)
DOCTEST_FILES = ["../../README.txt", "../../lib/restler/__init__.py"] + ... | import os
import doctest
import unittest
DOCTEST_FILES = []
for root, dirs, files in os.walk("."):
if ".hg%s" % os.path.sep not in root:
for f in files:
if f.endswith(".doctest"):
DOCTEST_FILES.append(f)
DOCTEST_FILES = ["../../lib/restler/__init__.py"] + DOCTEST_FILES
print ... | Fix broken (doc) test looking for the removed README.txt | Fix broken (doc) test looking for the removed README.txt
| Python | mit | xuru/substrate,xuru/substrate,xuru/substrate | ---
+++
@@ -11,7 +11,7 @@
if f.endswith(".doctest"):
DOCTEST_FILES.append(f)
-DOCTEST_FILES = ["../../README.txt", "../../lib/restler/__init__.py"] + DOCTEST_FILES
+DOCTEST_FILES = ["../../lib/restler/__init__.py"] + DOCTEST_FILES
print "Running ", DOCTEST_FILES
#DOCTEST_FILES = [] |
c8981212ea1d8c9e89c00135d164cde7fc53832d | docs/source/conf.py | docs/source/conf.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#
import os
import sys
sys.path.... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#
import os
import sys
sys.path.... | Add links to source code in documentation | Add links to source code in documentation
| Python | mit | numberly/mongo-thingy | ---
+++
@@ -18,6 +18,7 @@
# ones.
extensions = [
"sphinx.ext.autodoc",
+ "sphinx.ext.viewcode",
]
# The master toctree document. |
88ac847fd9a53e25253f72216ee2fad3fa8353a2 | python/main.py | python/main.py | import ctypes
stringtools = ctypes.CDLL("../target/libstringtools-261cf0fc14ce408c.so")
print(stringtools.count_substrings("banana", "na"))
| import ctypes
stringtools = ctypes.CDLL("../target/libstringtools-261cf0fc14ce408c.so")
print(stringtools.count_substrings(b"banana", b"na"))
| Use byte strings for Python example. | Use byte strings for Python example.
| Python | mit | zsiciarz/rust-ffi-stringtools,zsiciarz/rust-ffi-stringtools,zsiciarz/rust-ffi-stringtools,zsiciarz/rust-ffi-stringtools,zsiciarz/rust-ffi-stringtools,zsiciarz/rust-ffi-stringtools,zsiciarz/rust-ffi-stringtools | ---
+++
@@ -1,4 +1,4 @@
import ctypes
stringtools = ctypes.CDLL("../target/libstringtools-261cf0fc14ce408c.so")
-print(stringtools.count_substrings("banana", "na"))
+print(stringtools.count_substrings(b"banana", b"na")) |
1830c3ba2c124b0ef1d16a0ba2e092fd3281179b | myuw_mobile/views/api/library.py | myuw_mobile/views/api/library.py | import logging
from django.http import HttpResponse
from django.utils import simplejson as json
from myuw_mobile.views.rest_dispatch import RESTDispatch, data_not_found
from myuw_mobile.dao.library import get_account_info_for_current_user
from myuw_mobile.logger.timer import Timer
from myuw_mobile.logger.logresp import... | import logging
from django.http import HttpResponse
from django.utils import simplejson as json
from myuw_mobile.views.rest_dispatch import RESTDispatch, data_not_found
from myuw_mobile.dao.library import get_account_info_for_current_user
from myuw_mobile.logger.timer import Timer
from myuw_mobile.logger.logresp import... | Add param for turning on date formating. | Add param for turning on date formating.
| Python | apache-2.0 | uw-it-aca/myuw,uw-it-aca/myuw,fanglinfang/myuw,uw-it-aca/myuw,fanglinfang/myuw,fanglinfang/myuw,uw-it-aca/myuw | ---
+++
@@ -26,6 +26,6 @@
return data_not_found()
log_success_response(logger, timer)
- resp_json = myaccount.json_data()
+ resp_json = myaccount.json_data(full_name_format=True)
logger.debug(resp_json)
return HttpResponse(json.dumps(resp_json)) |
c47769005ba2eccebbd8561fd4b245d6af820821 | app/settings.py | app/settings.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Flask application default config:
# http://flask.pocoo.org/docs/config/#configuring-from-files
# https://github.com/mbr/flask-appconfig
project_name = u'Skeleton'
class Default(object):
APP_NAME = project_name
DEBUG = False
TESTING = False
JS_LOG_LE... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Flask application default config:
# http://flask.pocoo.org/docs/config/#configuring-from-files
# https://github.com/mbr/flask-appconfig
project_name = u'Ninhursag'
class Default(object):
APP_NAME = project_name
DEBUG = False
TESTING = False
JS_LOG_L... | Change app name to Ninhursag. | Change app name to Ninhursag.
| Python | mit | peterhil/ninhursag,peterhil/ninhursag,peterhil/ninhursag,peterhil/ninhursag | ---
+++
@@ -6,7 +6,7 @@
# https://github.com/mbr/flask-appconfig
-project_name = u'Skeleton'
+project_name = u'Ninhursag'
class Default(object): |
c32118b2157e6c2cfd435461ee23edfa79aa917e | api/__init__.py | api/__init__.py | import ConfigParser
from peewee import *
config = ConfigParser.RawConfigParser()
config.read('server.conf')
database = SqliteDatabase('gallery.db')
from collection import CollectionModel
from album import AlbumModel
from user import UserModel, UserResource
from photo import PhotoModel
database.create_tables([Photo... | import ConfigParser
from peewee import *
config = ConfigParser.RawConfigParser()
config.read('server.conf')
database = SqliteDatabase('gallery.db', threadlocals=True)
from collection import CollectionModel
from album import AlbumModel
from user import UserModel, UsersResource
from photo import PhotoModel
database.... | Set local threads to true for peewee | Set local threads to true for peewee
| Python | unlicense | karousel/karousel | ---
+++
@@ -5,11 +5,11 @@
config = ConfigParser.RawConfigParser()
config.read('server.conf')
-database = SqliteDatabase('gallery.db')
+database = SqliteDatabase('gallery.db', threadlocals=True)
from collection import CollectionModel
from album import AlbumModel
-from user import UserModel, UserResource
+from ... |
8c5f317a090a23f10adcc837645bd25a8b5626f8 | shap/models/_model.py | shap/models/_model.py | import numpy as np
from .._serializable import Serializable, Serializer, Deserializer
class Model(Serializable):
""" This is the superclass of all models.
"""
def __init__(self, model=None):
""" Wrap a callable model as a SHAP Model object.
"""
if isinstance(model, Model):
... | import numpy as np
from .._serializable import Serializable, Serializer, Deserializer
from torch import Tensor
class Model(Serializable):
""" This is the superclass of all models.
"""
def __init__(self, model=None):
""" Wrap a callable model as a SHAP Model object.
"""
if isinstan... | Check SHAP Model call type | Check SHAP Model call type
| Python | mit | slundberg/shap,slundberg/shap,slundberg/shap,slundberg/shap | ---
+++
@@ -1,5 +1,6 @@
import numpy as np
from .._serializable import Serializable, Serializer, Deserializer
+from torch import Tensor
class Model(Serializable):
@@ -18,7 +19,9 @@
self.output_names = model.output_names
def __call__(self, *args):
- return np.array(self.inner_model(*a... |
1ab4e03a0925deb57a7eafab2043d55f480988f1 | misc/toml_to_json.py | misc/toml_to_json.py | #!/usr/bin/env python
# Takes in toml, dumps it out as json
# Run pip install toml to install the toml module
import json
import sys
import toml
fh = open(sys.argv[1])
try:
data = toml.load(fh)
except toml.TomlDecodeError, e:
print e
sys.exit(1)
print json.dumps(data, indent=4, sort_keys=True)
| #!/usr/bin/env python3
# Takes in toml, dumps it out as json
# Run pip install toml to install the toml module
import json
import sys
import toml
if len(sys.argv) > 1:
fh = open(sys.argv[1])
else:
fh = sys.stdin
try:
data = toml.load(fh)
except toml.TomlDecodeError as e:
print(e)
sys.exit(1)
print... | Switch toml to json script to python 3 | Switch toml to json script to python 3
| Python | mit | mivok/tools,mivok/tools,mivok/tools,mivok/tools | ---
+++
@@ -1,14 +1,18 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
# Takes in toml, dumps it out as json
# Run pip install toml to install the toml module
import json
import sys
import toml
-fh = open(sys.argv[1])
+if len(sys.argv) > 1:
+ fh = open(sys.argv[1])
+else:
+ fh = sys.stdin
+
try:
... |
9dbaf58fd3dc9c3c976afcbf264fa6cfff09a7a0 | django_prometheus/migrations.py | django_prometheus/migrations.py | from django.db import connections
from django.db.backends.dummy.base import DatabaseWrapper
from django.db.migrations.executor import MigrationExecutor
from prometheus_client import Gauge
unapplied_migrations = Gauge(
'django_migrations_unapplied_total',
'Count of unapplied migrations by database connection',
... | from django.db import connections
from django.db.backends.dummy.base import DatabaseWrapper
from prometheus_client import Gauge
unapplied_migrations = Gauge(
'django_migrations_unapplied_total',
'Count of unapplied migrations by database connection',
['connection'])
applied_migrations = Gauge(
'django... | Fix the import of MigrationExecutor to be lazy. | Fix the import of MigrationExecutor to be lazy.
MigrationExecutor checks at import time whether apps are all
loaded. This doesn't work as they are usually not if your app is
imported by adding it to INSTALLED_APPS. Importing the MigrationExecutor
locally solves this problem as ExportMigration is only called once the
d... | Python | apache-2.0 | obytes/django-prometheus,korfuri/django-prometheus,obytes/django-prometheus,korfuri/django-prometheus | ---
+++
@@ -1,6 +1,5 @@
from django.db import connections
from django.db.backends.dummy.base import DatabaseWrapper
-from django.db.migrations.executor import MigrationExecutor
from prometheus_client import Gauge
unapplied_migrations = Gauge(
@@ -27,6 +26,14 @@
This is meant to be called during app startup... |
746c06ba70cd2854a86ea8bc45fc8e3e6192f67c | app.py | app.py | # coding: utf-8
import os
import time
from twython import Twython
import requests
APP_KEY = os.environ.get('APP_KEY')
APP_SECRET = os.environ.get('APP_SECRET')
OAUTH_TOKEN = os.environ.get('OAUTH_TOKEN')
OAUTH_TOKEN_SECRET = os.environ.get('OAUTH_TOKEN_SECRET')
twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OA... | # coding: utf-8
import os
import time
from twython import Twython
import requests
APP_KEY = os.environ.get('APP_KEY')
APP_SECRET = os.environ.get('APP_SECRET')
OAUTH_TOKEN = os.environ.get('OAUTH_TOKEN')
OAUTH_TOKEN_SECRET = os.environ.get('OAUTH_TOKEN_SECRET')
twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OA... | Add hashtag for currency name and symbol | Add hashtag for currency name and symbol | Python | mit | erickgnavar/coinstats | ---
+++
@@ -21,6 +21,7 @@
Change in 1h: {percent_change_1h}%
Market cap: ${market_cap_usd}
Ranking: {rank}
+#{name} #{symbol}
"""
if currency['percent_change_1h'] > 0:
currency['percent_change_1h'] = '+{}'.format(currency['percent_change_1h']) |
8c17e811dd9bf2a2b1c815fefb661260f624e83f | app.py | app.py | from urlparse import urlparse
import logging
import os
from flask import Flask
import pymongo
app = Flask(__name__)
_logger = logging.getLogger(__name__)
db = None
def get_connection():
global db
if db:
return db
config = urlparse(os.environ.get('MONGOHQ_URL', 'http://localhost:27017/db'))
db... | from urlparse import urlparse
import logging
import os
from flask import Flask
import pymongo
HOST= '0.0.0.0'
PORT = int(os.environ.get('PORT', 5000))
MONGO_URL = os.environ.get('MONGOHQ_URL', 'http://localhost:27017/db')
DEBUG = True
app = Flask(__name__)
_logger = logging.getLogger(__name__)
db = None
def get_con... | Move configuration variables to constants. | Move configuration variables to constants.
| Python | apache-2.0 | lnickers2004/mongo-web-shell,pilliq/mongo-web-shell,mongodb-labs/mongo-web-shell,pilliq/mongo-web-shell,lnickers2004/mongo-web-shell,10gen-labs/mongo-web-shell,ecbtln/mongo-web-shell,rcchan/mongo-web-shell,FuegoFro/mongo-web-shell,mcomella/mongo-web-shell,mcomella/mongo-web-shell,xl76/mongo-web-shell,10gen-labs/mongo-w... | ---
+++
@@ -4,6 +4,11 @@
from flask import Flask
import pymongo
+
+HOST= '0.0.0.0'
+PORT = int(os.environ.get('PORT', 5000))
+MONGO_URL = os.environ.get('MONGOHQ_URL', 'http://localhost:27017/db')
+DEBUG = True
app = Flask(__name__)
_logger = logging.getLogger(__name__)
@@ -13,7 +18,7 @@
global db
i... |
07c40f2c47c81843c8fd183f8fad7e489fb2d814 | sirius/LI_V00/record_names.py | sirius/LI_V00/record_names.py |
from . import families as _families
def get_record_names(subsystem=None):
"""Return a dictionary of record names for given subsystem
each entry is another dictionary of model families whose
values are the indices in the pyaccel model of the magnets
that belong to the family. The magnet models ca be s... |
from . import families as _families
def get_record_names(subsystem=None):
"""Return a dictionary of record names for given subsystem
each entry is another dictionary of model families whose
values are the indices in the pyaccel model of the magnets
that belong to the family. The magnet models ca be s... | Change linac mode pv to fake pvs | Change linac mode pv to fake pvs
| Python | mit | lnls-fac/sirius | ---
+++
@@ -8,7 +8,7 @@
values are the indices in the pyaccel model of the magnets
that belong to the family. The magnet models ca be segmented,
in which case the value is a python list of lists."""
- _dict = {'LIPA-MODE':{}}
+ _dict = {}
return _dict
|
26c725d3e6b1d5737a0efcbcd2371ff066a13a86 | tests/test_utils.py | tests/test_utils.py | from expert_tourist.utils import gmaps_url_to_coords
from tests.tests import BaseTestConfig
class TestUtils(BaseTestConfig):
def test_url_to_coords(self):
url = 'http://maps.google.co.cr/maps?q=9.8757875656828,-84.03733452782035'
lat, long = gmaps_url_to_coords(url)
self.assertEqual(lat, 9... | from unittest import TestCase
from expert_tourist.utils import gmaps_url_to_coords
class TestUtils(TestCase):
def test_url_to_coords(self):
url = 'http://maps.google.co.cr/maps?q=9.8757875656828,-84.03733452782035'
lat, long = gmaps_url_to_coords(url)
self.assertEqual(lat, 9.875787565682... | Refactor test to implement 87ceac3 changes | Refactor test to implement 87ceac3 changes
| Python | mit | richin13/expert-tourist | ---
+++
@@ -1,7 +1,9 @@
+from unittest import TestCase
+
from expert_tourist.utils import gmaps_url_to_coords
-from tests.tests import BaseTestConfig
-class TestUtils(BaseTestConfig):
+class TestUtils(TestCase):
+
def test_url_to_coords(self):
url = 'http://maps.google.co.cr/maps?q=9.8757875656828,-8... |
b2aba5cbdfbe59fee7bc595298a732c9aa1f9b51 | tests/test_utils.py | tests/test_utils.py | """Tests for the ``utils`` module."""
from mock import patch, Mock as mock
from nose.tools import *
from facepy import *
patch = patch('requests.session')
def mock():
global mock_request
mock_request = patch.start()().request
def unmock():
patch.stop()
@with_setup(mock, unmock)
def test_get_applicati... | """Tests for the ``utils`` module."""
from mock import patch, Mock as mock
from nose.tools import *
from facepy import *
patch = patch('requests.session')
def mock():
global mock_request
mock_request = patch.start()().request
def unmock():
patch.stop()
@with_setup(mock, unmock)
def test_get_applicati... | Make test_get_application_access_token_raises_error compatible with Python < 2.7 | Make test_get_application_access_token_raises_error compatible with Python < 2.7
| Python | mit | merwok-forks/facepy,jwjohns/facepy,jgorset/facepy,Spockuto/facepy,liorshahverdi/facepy,jwjohns/facepy,buzzfeed/facepy | ---
+++
@@ -36,5 +36,7 @@
def test_get_application_access_token_raises_error():
mock_request.return_value.content = 'An unknown error occurred'
- with assert_raises(GraphAPI.FacebookError):
- get_application_access_token('<application id>', '<application secret key>')
+ assert_raises(
+ Gr... |
34e2cf61bf686542f21bc8d840f17b13ca137fe3 | Main.py | Main.py | """Main Module of PDF Splitter"""
import argparse
from PyPDF2 import PdfFileWriter
from Util import all_pdf_files_in_directory, split_on_condition, concat_pdf_pages
parser = \
argparse.ArgumentParser(
description='Split all the pages of multiple PDF files in a directory by document number'
)
parser.a... | """Main Module of PDF Splitter"""
import argparse
import os
from PyPDF2 import PdfFileWriter
from Util import all_pdf_files_in_directory, split_on_condition, concat_pdf_pages
parser = \
argparse.ArgumentParser(
description='Split all the pages of multiple PDF files in a directory by document number'
... | Use flush and fsync to ensure data is written to disk | Use flush and fsync to ensure data is written to disk
| Python | mit | shunghsiyu/pdf-processor | ---
+++
@@ -1,5 +1,6 @@
"""Main Module of PDF Splitter"""
import argparse
+import os
from PyPDF2 import PdfFileWriter
@@ -35,5 +36,7 @@
output_filename = '{0:05}.pdf'.format(idx)
with open(output_filename, 'wb') as output_file:
pdf_writer.write(output_file)
+ output_fi... |
727f1de69a3f2211d97a2c5ed412eacb90d11619 | cov/templatetags/cov_tag.py | cov/templatetags/cov_tag.py | from django import template
from ..models import Covoiturage
from django.utils import timezone
register = template.Library()
@register.inclusion_tag('cov/cov_block.html', takes_context=True)
def get_cov(context, nb):
list_cov = Covoiturage.objects.select_related('poster').all().filter(good_until__gte=timezone.now())... | from django import template
from ..models import Covoiturage
from django.utils import timezone
register = template.Library()
@register.inclusion_tag('cov/cov_block.html', takes_context=True)
def get_cov(context, nb):
return {
'cov' : Covoiturage.objects.select_related('poster').filter(
good_until... | Fix : cov list is fetch in one queries (before it was fetched twice) | Fix : cov list is fetch in one queries (before it was fetched twice)
| Python | agpl-3.0 | rezometz/paiji2,rezometz/paiji2,rezometz/paiji2 | ---
+++
@@ -6,10 +6,9 @@
@register.inclusion_tag('cov/cov_block.html', takes_context=True)
def get_cov(context, nb):
- list_cov = Covoiturage.objects.select_related('poster').all().filter(good_until__gte=timezone.now()).order_by('good_until')[:nb]
- print list_cov
- ctx_data = {
- 'cov' : list_cov,
+ retur... |
c1dfbc8e8b3ae29436c584d906636ea541dfb6a8 | apps/storybase_asset/embedable_resource/__init__.py | apps/storybase_asset/embedable_resource/__init__.py | import re
from exceptions import UrlNotMatched
class EmbedableResource(object):
resource_providers = []
@classmethod
def register(cls, provider_cls):
cls.resource_providers.append(provider_cls)
@classmethod
def get_html(cls, url):
for provider_cls in cls.resource_providers:
... | import re
from exceptions import UrlNotMatched
class EmbedableResource(object):
resource_providers = []
@classmethod
def register(cls, provider_cls):
cls.resource_providers.append(provider_cls)
@classmethod
def get_html(cls, url):
for provider_cls in cls.resource_providers:
... | Allow embedding of Google Docs by URL | Allow embedding of Google Docs by URL
| Python | mit | denverfoundation/storybase,denverfoundation/storybase,denverfoundation/storybase,denverfoundation/storybase | ---
+++
@@ -28,12 +28,22 @@
def get_html(self, url):
raise UrlNotMatched
+
class GoogleSpreadsheetProvider(EmbedableResourceProvider):
url_pattern = r'^https://docs.google.com/spreadsheet/pub\?key=[0-9a-zA-Z]+'
- def get_html(self, url):
+ def get_html(self, url, width=500, height=300):
... |
8f7623c4b09d85c09327c37030fa2328e77853b1 | qfbv.py | qfbv.py | from config import *
class QFBV:
def preamble(self):
print "(set-logic QF_BV)"
print ""
# Enumerate all the variables, for each match round.
for i in range(NUMROUNDS):
for j in range(NUMMATCHES):
for k in range(NUMSLOTS):
print "(declare-fun {0} () (_ BitVec {1}))".format(self.project(i, j, k), ... | from config import *
import re
class QFBV:
def preamble(self):
print "(set-logic QF_BV)"
print ""
# Enumerate all the variables, for each match round.
for i in range(NUMROUNDS):
for j in range(NUMMATCHES):
for k in range(NUMSLOTS):
print "(declare-fun {0} () (_ BitVec {1}))".format(self.project(... | Read variable data for qf_bv | Read variable data for qf_bv
| Python | bsd-2-clause | jmorse/numbness | ---
+++
@@ -1,4 +1,5 @@
from config import *
+import re
class QFBV:
def preamble(self):
@@ -17,3 +18,8 @@
pass
+ def read_variable(self, expr1):
+ string, = expr1
+ regex = "round_([0-9]+)_match_([0-9]+)_slot_([0-9]+)"
+ result = re.match(regex, string)
+ return int(result.group(1)), int(result.group(... |
626c74d727140646d6123e2d86a828401d87abe0 | spam.py | spam.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from sklearn.cross_validation import train_test_split
from spam.common import DATASET_META
from spam.common.utils import get_file_path_list
from spam.preprocess import Preprocess
file_path_list = get_file_path_list(DATASET_META)
# transform list of tuple into two list
... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import pandas as pd
from sklearn.cross_validation import train_test_split
from spam.common import DATASET_META
from spam.common.utils import get_file_path_list
from spam.preprocess import preprocess
file_path_list = get_file_path_list(DATASET_META)
# transform list of ... | Add pandas to generate csv. | Add pandas to generate csv.
| Python | mit | benigls/spam,benigls/spam | ---
+++
@@ -1,11 +1,12 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
+import pandas as pd
from sklearn.cross_validation import train_test_split
from spam.common import DATASET_META
from spam.common.utils import get_file_path_list
-from spam.preprocess import Preprocess
+from spam.preprocess import preproc... |
987eb13b24fcb6b89b9bbe08a9bc73f40b85538c | onirim/card/_door.py | onirim/card/_door.py | from onirim.card._base import ColorCard
from onirim.card._location import LocationKind
def _openable(door_card, card):
"""Check if the door can be opened by another card."""
return card.kind == LocationKind.key and door_card.color == card.color
def _may_open(door_card, content):
"""Check if the door may ... | from onirim.card._base import ColorCard
from onirim.card._location import LocationKind
def _is_openable(door_card, card):
"""Check if the door can be opened by another card."""
return card.kind == LocationKind.key and door_card.color == card.color
def _may_open(door_card, content):
"""Check if the door ... | Remove key while opening a door | Remove key while opening a door
| Python | mit | cwahbong/onirim-py | ---
+++
@@ -2,22 +2,26 @@
from onirim.card._location import LocationKind
-def _openable(door_card, card):
+def _is_openable(door_card, card):
"""Check if the door can be opened by another card."""
return card.kind == LocationKind.key and door_card.color == card.color
+
def _may_open(door_card, conte... |
d7343ac93dbfb62b3f425711b8df9929a1d6f1ad | malcolm/core/mapmeta.py | malcolm/core/mapmeta.py | from collections import OrderedDict
from loggable import Loggable
from malcolm.core.attributemeta import AttributeMeta
class MapMeta(Loggable):
"""A meta object to store a set of attribute metas"""
def __init__(self, name):
super(MapMeta, self).__init__(logger_name=name)
self.name = name
... | from collections import OrderedDict
from loggable import Loggable
from malcolm.core.attributemeta import AttributeMeta
class MapMeta(Loggable):
"""An object containing a set of AttributeMeta objects"""
def __init__(self, name):
super(MapMeta, self).__init__(logger_name=name)
self.name = nam... | Remove uneccesary dict definition, clarify doc string | Remove uneccesary dict definition, clarify doc string
| Python | apache-2.0 | dls-controls/pymalcolm,dls-controls/pymalcolm,dls-controls/pymalcolm | ---
+++
@@ -5,13 +5,13 @@
class MapMeta(Loggable):
- """A meta object to store a set of attribute metas"""
+ """An object containing a set of AttributeMeta objects"""
def __init__(self, name):
super(MapMeta, self).__init__(logger_name=name)
self.name = name
- self.elements... |
8e2187d2519b4008a36f5c85910b7e7e2efc16f9 | braid/config.py | braid/config.py | """
Support for multiple environments based on python configuration files.
"""
from __future__ import print_function, absolute_import
import os
from twisted.python.filepath import FilePath
from fabric.api import env, task
from braid.settings import ENVIRONMENTS
CONFIG_DIRS = [
'~/.config/braid',
]
def loadE... | """
Support for multiple environments based on python configuration files.
"""
from __future__ import print_function, absolute_import
import os
from twisted.python.filepath import FilePath
from fabric.api import env, task
from braid.settings import ENVIRONMENTS
CONFIG_DIRS = [
'~/.config/braid',
]
#FIXME: H... | Put environment name into environment. | Put environment name into environment.
| Python | mit | alex/braid,alex/braid | ---
+++
@@ -16,6 +16,8 @@
CONFIG_DIRS = [
'~/.config/braid',
]
+
+#FIXME: How to handle module level initialization here?
def loadEnvironmentConfig(envFile):
"""
@@ -39,7 +41,6 @@
for envFile in confDir.globChildren('*.env'):
loadEnvironmentConfig(envFile)
-
loadEnvironments()
... |
6ac0598982f90b23d772d6b3cba802ad5fad5459 | watchman/management/commands/watchman.py | watchman/management/commands/watchman.py | from __future__ import absolute_import
import json
from optparse import make_option
from django.core.management.base import BaseCommand, CommandError
from watchman.utils import get_checks
class Command(BaseCommand):
help = 'Runs the default django-watchman checks'
option_list = BaseCommand.option_list + (... | from __future__ import absolute_import
import json
from optparse import make_option
from django.core.management.base import BaseCommand, CommandError
from watchman.utils import get_checks
class Command(BaseCommand):
help = 'Runs the default django-watchman checks'
option_list = BaseCommand.option_list + (... | Use `self.stdout.write` instead of `print` | Use `self.stdout.write` instead of `print`
| Python | bsd-3-clause | JBKahn/django-watchman,blag/django-watchman,mwarkentin/django-watchman,blag/django-watchman,JBKahn/django-watchman,ulope/django-watchman,mwarkentin/django-watchman,gerlachry/django-watchman,gerlachry/django-watchman,ulope/django-watchman | ---
+++
@@ -47,4 +47,4 @@
if '"ok": false' in resp:
raise CommandError(resp)
elif print_all_checks:
- print resp
+ self.stdout.write(resp) |
5d5bbcd380300c5fd786fac59bf360a287b99c3b | oauthenticator/__init__.py | oauthenticator/__init__.py | # include github, bitbucket, google here for backward-compatibility
# don't add new oauthenticators here.
from .oauth2 import *
from .github import *
from .bitbucket import *
from .google import *
from ._version import __version__, version_info
| # include github, bitbucket, google here for backward-compatibility
# don't add new oauthenticators here.
from .oauth2 import *
from .github import *
from .bitbucket import *
from .google import *
from .generic import *
from ._version import __version__, version_info
| Add the GenericHandler to the init file | Add the GenericHandler to the init file
| Python | bsd-3-clause | santi81/oauthenticator,santi81/oauthenticator | ---
+++
@@ -4,5 +4,6 @@
from .github import *
from .bitbucket import *
from .google import *
+from .generic import *
from ._version import __version__, version_info |
05cf5f3729ffbceeb2436322b2aac5285d7228de | wsgi.py | wsgi.py | # Copyright 2017 Jonathan Anderson
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
... | # Copyright 2017 Jonathan Anderson
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
... | Print registration code in WSGI app. | Print registration code in WSGI app.
Otherwise, how will we know what it is?
| Python | bsd-2-clause | trombonehero/nerf-herder,trombonehero/nerf-herder,trombonehero/nerf-herder | ---
+++
@@ -21,5 +21,13 @@
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+import config
import webapp
+
application = webapp.create_app()
+
+if config.REGISTRATION_IS_OPEN:
+ print(" * Registration is OPE... |
beb06f3377a5e3e52f5756a1ecbf4197c7a3e99e | base/components/correlations/managers.py | base/components/correlations/managers.py | # -*- coding: utf-8 -*-
from datetime import date
from django.contrib.contenttypes.models import ContentType
from django.db import models
class CorrelationManager(models.Manager):
def update_or_create(self, instance, timestamp, attribute):
# Membership is a special case. Since most groups are static
... | # -*- coding: utf-8 -*-
from datetime import date
from django.contrib.contenttypes.models import ContentType
from django.db import models
class CorrelationManager(models.Manager):
def update_or_create(self, instance, timestamp, attribute):
ctype = ContentType.objects.get_for_model(instance.sender)
... | Remove the Membership special case. We want everything correlated. | Remove the Membership special case. We want everything correlated.
| Python | apache-2.0 | hello-base/web,hello-base/web,hello-base/web,hello-base/web | ---
+++
@@ -7,14 +7,6 @@
class CorrelationManager(models.Manager):
def update_or_create(self, instance, timestamp, attribute):
- # Membership is a special case. Since most groups are static
- # (or non-generational), the date the group is formed is the same as
- # the date its members joi... |
1025121c19af4d1ea224abc8f37120cb9f24210d | Scripts/RoboFabUFO/ImportFontFromUFO.py | Scripts/RoboFabUFO/ImportFontFromUFO.py | #FLM: Import .ufo File into FontLab
from robofab.world import NewFont
from robofab.interface.all.dialogs import GetFolder
path = GetFolder("Please select a .ufo")
if path is not None:
font = NewFont()
font.readUFO(path, doProgress=True)
font.update()
print 'DONE!'
| #FLM: Import .ufo File into FontLab
from robofab.world import NewFont
from robofab.interface.all.dialogs import GetFileOrFolder
path = GetFileOrFolder("Please select a .ufo")
if path is not None:
font = NewFont()
font.readUFO(path, doProgress=True)
font.update()
print 'DONE!'
| Use GetFileOrFolder for the dialog. | Use GetFileOrFolder for the dialog.
git-svn-id: 68c5a305180a392494b23cb56ff711ec9d5bf0e2@493 b5fa9d6c-a76f-4ffd-b3cb-f825fc41095c
| Python | bsd-3-clause | jamesgk/robofab,daltonmaag/robofab,bitforks/robofab,schriftgestalt/robofab,moyogo/robofab,schriftgestalt/robofab,miguelsousa/robofab,anthrotype/robofab,daltonmaag/robofab,anthrotype/robofab,jamesgk/robofab,miguelsousa/robofab,moyogo/robofab | ---
+++
@@ -1,9 +1,9 @@
#FLM: Import .ufo File into FontLab
from robofab.world import NewFont
-from robofab.interface.all.dialogs import GetFolder
+from robofab.interface.all.dialogs import GetFileOrFolder
-path = GetFolder("Please select a .ufo")
+path = GetFileOrFolder("Please select a .ufo")
if path is not ... |
7eb83427b8134d5fa51357371e95b398d95a5b96 | dayonetools/services/__init__.py | dayonetools/services/__init__.py | """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... | """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... | Add hack for broken timezone support in dayone | Add hack for broken timezone support in dayone
| Python | mit | durden/dayonetools | ---
+++
@@ -27,12 +27,16 @@
from datetime import datetime
now = datetime.utcnow()
+ # FIXME: The current version of day one does not support timezone data
+ # correctly. So, if we enter midnight here then every entry is off by a
+ # day.
+
# Don't know the hour, minute, etc. so just assume ... |
4a5e6373692798eb4d48c294d3262c93902b27de | zou/app/blueprints/crud/schedule_item.py | zou/app/blueprints/crud/schedule_item.py | from zou.app.models.schedule_item import ScheduleItem
from .base import BaseModelResource, BaseModelsResource
class ScheduleItemsResource(BaseModelsResource):
def __init__(self):
BaseModelsResource.__init__(self, ScheduleItem)
class ScheduleItemResource(BaseModelResource):
def __init__(self):
... | from zou.app.models.schedule_item import ScheduleItem
from .base import BaseModelResource, BaseModelsResource
from zou.app.services import user_service
class ScheduleItemsResource(BaseModelsResource):
def __init__(self):
BaseModelsResource.__init__(self, ScheduleItem)
class ScheduleItemResource(BaseMo... | Allow schedule edition by supervisors | [schedule] Allow schedule edition by supervisors
| Python | agpl-3.0 | cgwire/zou | ---
+++
@@ -1,6 +1,8 @@
from zou.app.models.schedule_item import ScheduleItem
from .base import BaseModelResource, BaseModelsResource
+
+from zou.app.services import user_service
class ScheduleItemsResource(BaseModelsResource):
@@ -12,6 +14,9 @@
def __init__(self):
BaseModelResource.__init__(se... |
fb5bc5d789986df53844d8f0620db95f349e4096 | sch/__init__.py | sch/__init__.py | import os
if hasattr(os, 'add_dll_directory'):
os.add_dll_directory("$<TARGET_FILE_DIR:sch-core::sch-core>")
from . sch import *
| import os
if hasattr(os, 'add_dll_directory'):
os.add_dll_directory("$<TARGET_FILE_DIR:sch-core::sch-core>")
os.add_dll_directory("$<TARGET_FILE_DIR:Boost::serialization>")
from . sch import *
| Add the Boost DLL directory to the search path as well | Add the Boost DLL directory to the search path as well
| Python | bsd-2-clause | jrl-umi3218/sch-core-python,jrl-umi3218/sch-core-python | ---
+++
@@ -1,5 +1,6 @@
import os
if hasattr(os, 'add_dll_directory'):
os.add_dll_directory("$<TARGET_FILE_DIR:sch-core::sch-core>")
+ os.add_dll_directory("$<TARGET_FILE_DIR:Boost::serialization>")
from . sch import * |
a2d6c32305577640bcd111fa1011bea61d7ca9e7 | packages/mono-llvm-2-10.py | packages/mono-llvm-2-10.py | GitHubTarballPackage ('mono', 'llvm', '2.10', '943edbc1a93df204d687d82d34d2b2bdf9978f4e',
configure = 'CFLAGS="-m32" CPPFLAGS="-m32" CXXFLAGS="-m32" LDFLAGS="-m32" ./configure --prefix="%{prefix}" --enable-optimized --enable-targets="x86 x86_64" --target=i386-apple-darwin10.8.0',
override_properties = { 'make': 'make... | GitHubTarballPackage ('mono', 'llvm', '2.10', '943edbc1a93df204d687d82d34d2b2bdf9978f4e',
configure = './configure --prefix="%{prefix}" --enable-optimized --enable-targets="x86 x86_64" --target=i386-apple-darwin10.8.0',
override_properties = { 'make': 'make' }
)
| Fix llvm so it doesn't corrupt the env when configuring itself | Fix llvm so it doesn't corrupt the env when configuring itself
| Python | mit | BansheeMediaPlayer/bockbuild,mono/bockbuild,mono/bockbuild,BansheeMediaPlayer/bockbuild,BansheeMediaPlayer/bockbuild | ---
+++
@@ -1,4 +1,4 @@
GitHubTarballPackage ('mono', 'llvm', '2.10', '943edbc1a93df204d687d82d34d2b2bdf9978f4e',
- configure = 'CFLAGS="-m32" CPPFLAGS="-m32" CXXFLAGS="-m32" LDFLAGS="-m32" ./configure --prefix="%{prefix}" --enable-optimized --enable-targets="x86 x86_64" --target=i386-apple-darwin10.8.0',
+ configur... |
1343ca5b426132c0a9c916abd516a69ddd5f3aa4 | cle/__init__.py | cle/__init__.py | """
CLE is an extensible binary loader. Its main goal is to take an executable program and any libraries it depends on and
produce an address space where that program is loaded and ready to run.
The primary interface to CLE is the Loader class.
"""
__version__ = (9, 0, "gitrolling")
if bytes is str:
raise Except... | """
CLE is an extensible binary loader. Its main goal is to take an executable program and any libraries it depends on and
produce an address space where that program is loaded and ready to run.
The primary interface to CLE is the Loader class.
"""
__version__ = (9, 1, "gitrolling")
if bytes is str:
raise Except... | Fix version tuple for 9.1 | Fix version tuple for 9.1 [ci skip]
| Python | bsd-2-clause | angr/cle | ---
+++
@@ -5,7 +5,7 @@
The primary interface to CLE is the Loader class.
"""
-__version__ = (9, 0, "gitrolling")
+__version__ = (9, 1, "gitrolling")
if bytes is str:
raise Exception("This module is designed for python 3 only. Please install an older version to use python 2.") |
6910fe840a2b54d7848adcaa032d4303aee0ceec | dedupe/convenience.py | dedupe/convenience.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Convenience functions for in memory deduplication
"""
import collections
import dedupe.core
def dataSample(data, sample_size):
'''Randomly sample pairs of records from a data dictionary'''
data_list = data.values()
random_pairs = dedupe.core.randomPair... | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Convenience functions for in memory deduplication
"""
import collections
import dedupe.core
def dataSample(data, sample_size):
'''Randomly sample pairs of records from a data dictionary'''
data_list = data.values()
random_pairs = dedupe.core.randomPair... | Index of the list should be an int | Index of the list should be an int
| Python | mit | nmiranda/dedupe,davidkunio/dedupe,tfmorris/dedupe,datamade/dedupe,nmiranda/dedupe,01-/dedupe,pombredanne/dedupe,davidkunio/dedupe,dedupeio/dedupe,neozhangthe1/dedupe,neozhangthe1/dedupe,01-/dedupe,datamade/dedupe,pombredanne/dedupe,dedupeio/dedupe,dedupeio/dedupe-examples,tfmorris/dedupe | ---
+++
@@ -16,7 +16,7 @@
data_list = data.values()
random_pairs = dedupe.core.randomPairs(len(data_list), sample_size)
- return tuple((data_list[k1], data_list[k2]) for k1, k2 in random_pairs)
+ return tuple((data_list[int(k1)], data_list[int(k2)]) for k1, k2 in random_pairs)
def blockData(dat... |
1d3bd1fe50806180c8fb6889b1bed28f602608d6 | couchdb/tests/__main__.py | couchdb/tests/__main__.py | # -*- coding: utf-8 -*-
#
# Copyright (C) 2007 Christopher Lenz
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution.
import unittest
from couchdb.tests import client, couch_tests, design, couchhttp, \
... | # -*- coding: utf-8 -*-
#
# Copyright (C) 2007 Christopher Lenz
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution.
import unittest
from couchdb.tests import client, couch_tests, design, couchhttp, \
... | Include loader tests in test suite | Include loader tests in test suite
| Python | bsd-3-clause | djc/couchdb-python,djc/couchdb-python | ---
+++
@@ -9,7 +9,8 @@
import unittest
from couchdb.tests import client, couch_tests, design, couchhttp, \
- multipart, mapping, view, package, tools
+ multipart, mapping, view, package, tools, \
+ loader
def suite():
@@ -23,6 +24,7 ... |
bf18c698596be9de094d94cdc52d95186fc37e6a | configReader.py | configReader.py | class ConfigReader():
def __init__(self):
self.keys={}
#Read Keys from file
def readKeys(self):
keysFile=open("config.txt","r")
fileLines=keysFile.readlines()
keysFile.close()
self.keys.clear()
for item in fileLines:
#If last char is \n
if (item[-1]=='\n'):
item=item[:-1]
#If a commented ... | class ConfigReader():
def __init__(self,name="config.txt"):
self.keys={}
self.name = name
#Read Keys from file
def readKeys(self):
keysFile=open(self.name,"r")
fileLines=keysFile.readlines()
keysFile.close()
self.keys.clear()
for item in fileLines:
#If last char is \n
if (item[-1]=='\n'):
ite... | Add mode for changing what file it is, and fix a bug where a line without an equals wouldn't work | Add mode for changing what file it is, and fix a bug where a line without an equals wouldn't work
| Python | mit | ollien/PyConfigReader | ---
+++
@@ -1,10 +1,10 @@
class ConfigReader():
- def __init__(self):
+ def __init__(self,name="config.txt"):
self.keys={}
-
+ self.name = name
#Read Keys from file
def readKeys(self):
- keysFile=open("config.txt","r")
+ keysFile=open(self.name,"r")
fileLines=keysFile.readlines()
keysFile.close()
... |
4e30a58386afb5b34bd83c8115c55e5d09b8f631 | common/views.py | common/views.py | from django.shortcuts import render
from common.models.Furniture import Furniture
from common.models.Plan import Plan
def overlay(request, floor=1):
edit_rooms = False
if request.method == 'POST':
if 'floor' in request.POST:
floor = request.POST['floor']
if 'edit_rooms' in request.... | from django.shortcuts import render
from common.models.Furniture import Furniture
from common.models.Plan import Plan
def overlay(request, floor=1):
edit_rooms = False
if request.method == 'POST':
if 'floor' in request.POST:
floor = request.POST['floor']
if 'edit_rooms' in request.... | Improve performance by prefetching where needed | Improve performance by prefetching where needed
| Python | agpl-3.0 | Pajn/RAXA-Django,Pajn/RAXA-Django | ---
+++
@@ -11,7 +11,7 @@
if 'edit_rooms' in request.POST:
edit_rooms = True
- rooms = Plan.objects.filter(floor=floor)
- furnitures = Furniture.objects.filter(floor=floor)
+ rooms = Plan.objects.select_related('room__id').filter(floor=floor)
+ furnitures = Furniture.objects.select... |
e7cbed6df650851b2d44bf48f2b94291822f0b91 | recipes/sos-notebook/run_test.py | recipes/sos-notebook/run_test.py | # Test that sos kernel is installed
import jupyter_client
try:
jupyter_client.kernelspec.get_kernel_spec('sos')
except jupyter_client.kernelspec.NoSuchKernel:
print('sos kernel was not installed')
print('The following kernels are installed:')
print('jupyter_client.kernelspec.find_kernel_specs()')
... | # Test that sos kernel is installed
import jupyter_client
try:
jupyter_client.kernelspec.get_kernel_spec('sos')
except jupyter_client.kernelspec.NoSuchKernel:
print('sos kernel was not installed')
print('The following kernels are installed:')
print('jupyter_client.kernelspec.find_kernel_specs()')
... | Add test of kernel switch. | Add test of kernel switch.
| Python | bsd-3-clause | kwilcox/staged-recipes,scopatz/staged-recipes,patricksnape/staged-recipes,asmeurer/staged-recipes,mcs07/staged-recipes,patricksnape/staged-recipes,birdsarah/staged-recipes,mcs07/staged-recipes,hadim/staged-recipes,basnijholt/staged-recipes,goanpeca/staged-recipes,synapticarbors/staged-recipes,kwilcox/staged-recipes,asm... | ---
+++
@@ -9,3 +9,25 @@
print('The following kernels are installed:')
print('jupyter_client.kernelspec.find_kernel_specs()')
print(jupyter_client.kernelspec.find_kernel_specs())
+
+# Test that sos kernel is functional
+
+import unittest
+
+from ipykernel.tests.utils import execute, wait_for_idle, asse... |
49fd5a646f329be1147b43b8c2c611f1424abe22 | spacy/about.py | spacy/about.py | # inspired from:
# https://python-packaging-user-guide.readthedocs.org/en/latest/single_source_version/
# https://github.com/pypa/warehouse/blob/master/warehouse/__about__.py
__title__ = 'spacy'
__version__ = '2.0.2.dev1'
__summary__ = 'Industrial-strength Natural Language Processing (NLP) with Python and Cython'
__ur... | # inspired from:
# https://python-packaging-user-guide.readthedocs.org/en/latest/single_source_version/
# https://github.com/pypa/warehouse/blob/master/warehouse/__about__.py
__title__ = 'spacy'
__version__ = '2.0.2'
__summary__ = 'Industrial-strength Natural Language Processing (NLP) with Python and Cython'
__uri__ =... | Set version for 2.0.2 release | Set version for 2.0.2 release
| Python | mit | honnibal/spaCy,spacy-io/spaCy,explosion/spaCy,spacy-io/spaCy,aikramer2/spaCy,explosion/spaCy,explosion/spaCy,honnibal/spaCy,honnibal/spaCy,explosion/spaCy,explosion/spaCy,explosion/spaCy,spacy-io/spaCy,spacy-io/spaCy,recognai/spaCy,honnibal/spaCy,spacy-io/spaCy,recognai/spaCy,aikramer2/spaCy,recognai/spaCy,recognai/spa... | ---
+++
@@ -3,13 +3,13 @@
# https://github.com/pypa/warehouse/blob/master/warehouse/__about__.py
__title__ = 'spacy'
-__version__ = '2.0.2.dev1'
+__version__ = '2.0.2'
__summary__ = 'Industrial-strength Natural Language Processing (NLP) with Python and Cython'
__uri__ = 'https://spacy.io'
__author__ = 'Explosi... |
d101b7f023db1583ca7b65899bfdef296f838ad2 | openspending/ui/validation/source.py | openspending/ui/validation/source.py | from urlparse import urlparse
from openspending.validation.model.common import mapping
from openspending.validation.model.common import key
from openspending.validation.model.predicates import chained, \
nonempty_string
def valid_url(url):
parsed = urlparse(url)
if parsed.scheme.lower() not in ('http', 'h... | from urlparse import urlparse
from openspending.validation.model.common import mapping
from openspending.validation.model.common import key
from openspending.validation.model.predicates import chained, \
nonempty_string
def valid_url(url):
parsed = urlparse(url)
if parsed.scheme.lower() not in ('http', '... | Fix PEP8 issues in openspending/ui/validation. | Fix PEP8 issues in openspending/ui/validation.
| Python | agpl-3.0 | CivicVision/datahub,openspending/spendb,CivicVision/datahub,spendb/spendb,spendb/spendb,johnjohndoe/spendb,USStateDept/FPA_Core,nathanhilbert/FPA_Core,openspending/spendb,spendb/spendb,USStateDept/FPA_Core,USStateDept/FPA_Core,johnjohndoe/spendb,openspending/spendb,nathanhilbert/FPA_Core,johnjohndoe/spendb,pudo/spendb,... | ---
+++
@@ -5,21 +5,19 @@
from openspending.validation.model.predicates import chained, \
nonempty_string
+
def valid_url(url):
parsed = urlparse(url)
if parsed.scheme.lower() not in ('http', 'https'):
return "Only HTTP/HTTPS web addresses are supported " \
- "at the moment.... |
fb8921f17d1cecfc1c61612092709c526b70e0ab | dsub/_dsub_version.py | dsub/_dsub_version.py | # Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | # Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | Update dsub version to 0.3.0 | Update dsub version to 0.3.0
PiperOrigin-RevId: 241766455
| Python | apache-2.0 | DataBiosphere/dsub,DataBiosphere/dsub | ---
+++
@@ -26,4 +26,4 @@
0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ...
"""
-DSUB_VERSION = '0.3.0.dev0'
+DSUB_VERSION = '0.3.0' |
2769f038a70e1003c23908b1e917abd08058512b | aldryn_newsblog/admin.py | aldryn_newsblog/admin.py | from django.contrib import admin
from aldryn_apphooks_config.admin import BaseAppHookConfig
from cms.admin.placeholderadmin import PlaceholderAdmin, FrontendEditableAdmin
from parler.admin import TranslatableAdmin
from .models import Article, MockCategory, MockTag, NewsBlogConfig
class ArticleAdmin(TranslatableAdmi... | from django.contrib import admin
from aldryn_apphooks_config.admin import BaseAppHookConfig
from aldryn_people.models import Person
from cms.admin.placeholderadmin import PlaceholderAdmin, FrontendEditableAdmin
from parler.admin import TranslatableAdmin
from .models import Article, MockCategory, MockTag, NewsBlogConf... | Set Article.author to a Person instance (if it exists for current user) | Set Article.author to a Person instance (if it exists for current user)
| Python | bsd-3-clause | czpython/aldryn-newsblog,mkoistinen/aldryn-newsblog,czpython/aldryn-newsblog,mkoistinen/aldryn-newsblog,czpython/aldryn-newsblog,mkoistinen/aldryn-newsblog,czpython/aldryn-newsblog | ---
+++
@@ -1,6 +1,7 @@
from django.contrib import admin
from aldryn_apphooks_config.admin import BaseAppHookConfig
+from aldryn_people.models import Person
from cms.admin.placeholderadmin import PlaceholderAdmin, FrontendEditableAdmin
from parler.admin import TranslatableAdmin
@@ -13,8 +14,12 @@
def a... |
23fc2bbd22aa8d45301207b0608634df4414707f | panoptes_client/classification.py | panoptes_client/classification.py | from panoptes_client.panoptes import LinkResolver, PanoptesObject
class Classification(PanoptesObject):
_api_slug = 'classifications'
_link_slug = 'classification'
_edit_attributes = ( )
LinkResolver.register(Classification)
| from panoptes_client.panoptes import LinkResolver, PanoptesObject
class Classification(PanoptesObject):
_api_slug = 'classifications'
_link_slug = 'classification'
_edit_attributes = ( )
@classmethod
def where(cls, **kwargs):
scope = kwargs.pop('scope', None)
if not scope:
... | Add scope kwarg to Classification.where() | Add scope kwarg to Classification.where()
| Python | apache-2.0 | zooniverse/panoptes-python-client | ---
+++
@@ -1,8 +1,16 @@
from panoptes_client.panoptes import LinkResolver, PanoptesObject
+
class Classification(PanoptesObject):
_api_slug = 'classifications'
_link_slug = 'classification'
_edit_attributes = ( )
+ @classmethod
+ def where(cls, **kwargs):
+ scope = kwargs.pop('scope... |
24b52024b76206b59a650cee477773ad5836b175 | labonneboite/importer/conf/lbbdev.py | labonneboite/importer/conf/lbbdev.py | import os
# --- importer input directory of DPAE and ETABLISSEMENT exports
INPUT_SOURCE_FOLDER = '/srv/lbb/data'
# --- job 1/8 & 2/8 : check_etablissements & extract_etablissements
JENKINS_ETAB_PROPERTIES_FILENAME = os.path.join(os.environ["WORKSPACE"], "properties.jenkins")
MINIMUM_OFFICES_TO_BE_EXTRACTED_PER_DEPART... | import os
# --- importer input directory of DPAE and ETABLISSEMENT exports
INPUT_SOURCE_FOLDER = '/srv/lbb/data'
# --- job 1/8 & 2/8 : check_etablissements & extract_etablissements
JENKINS_ETAB_PROPERTIES_FILENAME = os.path.join(os.environ["WORKSPACE"], "properties.jenkins")
MINIMUM_OFFICES_TO_BE_EXTRACTED_PER_DEPART... | Fix evolution threshold for dpt 77 | Fix evolution threshold for dpt 77
The threshold HIGH_SCORE_COMPANIES_DIFF_MAX which is the max percentage
of difference between number of companies in lbb from one importer cycle
to another was set to 70, and it reached 73 for the department 77. This
threshold has now been set to 75.
| Python | agpl-3.0 | StartupsPoleEmploi/labonneboite,StartupsPoleEmploi/labonneboite,StartupsPoleEmploi/labonneboite,StartupsPoleEmploi/labonneboite | ---
+++
@@ -15,7 +15,7 @@
# --- job 5/8 : compute_scores
SCORE_COEFFICIENT_OF_VARIATION_MAX = 2.0
RMSE_MAX = 1500 # On 2017.03.15 departement 52 reached RMSE=1141
-HIGH_SCORE_COMPANIES_DIFF_MAX = 70
+HIGH_SCORE_COMPANIES_DIFF_MAX = 75 # On 2019.05.03 departement 77 reached HIGH_SCORE_COMPANIES_DIFF_MAX~=73
# ... |
b9882cc9d12aef06091727c76263039b30f0c4ce | numscons/tools/ifort.py | numscons/tools/ifort.py | import sys
import warnings
from SCons.Util import \
WhereIs
from SCons.Tool.ifort import \
generate as old_generate
def generate_linux(env):
ifort = WhereIs('ifort')
if not ifort:
warnings.warn("ifort not found")
return old_generate(env)
def generate(env):
if sys.platform.star... | import sys
import warnings
from SCons.Util import \
WhereIs
from SCons.Tool.ifort import \
generate as old_generate
from numscons.tools.intel_common import get_abi
def generate_linux(env):
ifort = WhereIs('ifort')
if not ifort:
warnings.warn("ifort not found")
return old_generate(... | Add initial support for win32 fortran compiler support. | Add initial support for win32 fortran compiler support.
| Python | bsd-3-clause | cournape/numscons,cournape/numscons,cournape/numscons | ---
+++
@@ -6,15 +6,35 @@
from SCons.Tool.ifort import \
generate as old_generate
+from numscons.tools.intel_common import get_abi
+
def generate_linux(env):
ifort = WhereIs('ifort')
if not ifort:
warnings.warn("ifort not found")
return old_generate(env)
+def generate_win32(env)... |
8fd451b266f3441184220061cb25227530c0d256 | collector/classes/service.py | collector/classes/service.py | # -*- coding: utf-8 -*-
import string
def sanitise_string(messy_str):
"""Whitelist characters in a string"""
valid_chars = ' {0}{1}'.format(string.ascii_letters, string.digits)
return u''.join(char for char in messy_str if char in valid_chars).strip()
class Service(object):
def __init__(self, numeri... | # -*- coding: utf-8 -*-
import string
def sanitise_string(messy_str):
"""Whitelist characters in a string"""
valid_chars = ' {0}{1}'.format(string.ascii_letters, string.digits)
return u''.join(char for char in messy_str if char in valid_chars).strip()
class Service(object):
def __init__(self, numeri... | Handle empty cells in the spreadsheet | Handle empty cells in the spreadsheet
| Python | mit | alphagov/backdrop-transactions-explorer-collector,alphagov/backdrop-transactions-explorer-collector | ---
+++
@@ -35,7 +35,7 @@
def handle_bad_data(self, datum):
# TODO: Should we be more explicit about non-requested (***) data?
- if datum == '' or datum == '-' or datum == '***':
+ if datum == '' or datum == '-' or datum == '***' or datum == None:
return None
elif n... |
fffbf30ab4f64cbfad939529dde416280a68b125 | addons/osfstorage/settings/defaults.py | addons/osfstorage/settings/defaults.py | # encoding: utf-8
import importlib
import os
import logging
from website import settings
logger = logging.getLogger(__name__)
DEFAULT_REGION_NAME = 'N. Virginia'
DEFAULT_REGION_ID = 'us-east-1'
WATERBUTLER_CREDENTIALS = {
'storage': {}
}
WATERBUTLER_SETTINGS = {
'storage': {
'provider': 'filesystem... | # encoding: utf-8
import importlib
import os
import logging
from website import settings
logger = logging.getLogger(__name__)
DEFAULT_REGION_NAME = 'United States'
DEFAULT_REGION_ID = 'us'
WATERBUTLER_CREDENTIALS = {
'storage': {}
}
WATERBUTLER_SETTINGS = {
'storage': {
'provider': 'filesystem',
... | Adjust OSF Storage default region names | Adjust OSF Storage default region names | Python | apache-2.0 | pattisdr/osf.io,pattisdr/osf.io,brianjgeiger/osf.io,mattclark/osf.io,HalcyonChimera/osf.io,Johnetordoff/osf.io,adlius/osf.io,aaxelb/osf.io,saradbowman/osf.io,mfraezz/osf.io,HalcyonChimera/osf.io,felliott/osf.io,saradbowman/osf.io,aaxelb/osf.io,Johnetordoff/osf.io,cslzchen/osf.io,erinspace/osf.io,adlius/osf.io,baylee-d/... | ---
+++
@@ -7,8 +7,8 @@
logger = logging.getLogger(__name__)
-DEFAULT_REGION_NAME = 'N. Virginia'
-DEFAULT_REGION_ID = 'us-east-1'
+DEFAULT_REGION_NAME = 'United States'
+DEFAULT_REGION_ID = 'us'
WATERBUTLER_CREDENTIALS = {
'storage': {} |
944db8255306a666f290775fec01f5ab33de2eb0 | test/integration/022_bigquery_test/test_bigquery_adapter_specific.py | test/integration/022_bigquery_test/test_bigquery_adapter_specific.py | """"Test adapter specific config options."""
from pprint import pprint
from test.integration.base import DBTIntegrationTest, use_profile
import textwrap
import yaml
class TestBigqueryAdapterSpecific(DBTIntegrationTest):
@property
def schema(self):
return "bigquery_test_022"
@property
def mo... | """"Test adapter specific config options."""
from pprint import pprint
from test.integration.base import DBTIntegrationTest, use_profile
import textwrap
import yaml
class TestBigqueryAdapterSpecific(DBTIntegrationTest):
@property
def schema(self):
return "bigquery_test_022"
@property
def mo... | Remove unnecessary code for print debug | Remove unnecessary code for print debug
| Python | apache-2.0 | analyst-collective/dbt,analyst-collective/dbt | ---
+++
@@ -35,8 +35,6 @@
def test_bigquery_hours_to_expiration(self):
_, stdout = self.run_dbt_and_capture(['--debug', 'run'])
- pprint(stdout)
-
self.assertIn(
'expiration_timestamp=TIMESTAMP_ADD(CURRENT_TIMESTAMP(), INTERVAL '
'4 hour)', stdout) |
2aa81349f2fae2f782c5174720ea7d2ab406c946 | ditto/multitenancy/middleware.py | ditto/multitenancy/middleware.py | from django.conf import settings
from django.conf.urls import patterns, include, url
from django.conf.urls.static import static
class FakeTenant(object):
is_main = lambda self: False
is_configured = lambda self: True
id = 'di'
def chat_host(self):
if settings.DEBUG:
return 'netwo... | from django.conf import settings
from django.conf.urls import patterns, include, url
from django.conf.urls.static import static
from django.views.generic import RedirectView
class FakeTenant(object):
is_main = lambda self: False
is_configured = lambda self: True
id = 'di'
def chat_host(self):
... | Fix 404 when no path in URL | Fix 404 when no path in URL
| Python | bsd-3-clause | Kvoti/ditto,Kvoti/ditto,Kvoti/ditto,Kvoti/ditto,Kvoti/ditto | ---
+++
@@ -1,6 +1,7 @@
from django.conf import settings
from django.conf.urls import patterns, include, url
from django.conf.urls.static import static
+from django.views.generic import RedirectView
class FakeTenant(object):
@@ -26,6 +27,10 @@
return tuple(
patterns(
'',
+ ... |
721c4d0cd4e99b4c45eeee813375e7d0050ef970 | doc/pyplots/plot_qualitative2.py | doc/pyplots/plot_qualitative2.py | # -*- coding: utf-8 -*-
"""Plot to demonstrate the qualitative2 colormap.
"""
import numpy as np
import matplotlib.pyplot as plt
from typhon.plots import (figsize, mpl_colors)
fig, ax = plt.subplots(figsize=figsize(10))
ax.set_prop_cycle(color=mpl_colors('qualitative2', 7))
for c in np.arange(7):
X = np.random... | # -*- coding: utf-8 -*-
"""Plot to demonstrate the qualitative2 colormap.
"""
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
from typhon.plots import (figsize, mpl_colors)
# Create an iterator to conveniently change the marker in the following plot.
markers = (m for m in Lin... | Change marker as an example. | Change marker as an example.
| Python | mit | atmtools/typhon,atmtools/typhon | ---
+++
@@ -5,16 +5,20 @@
import numpy as np
import matplotlib.pyplot as plt
+from matplotlib.lines import Line2D
from typhon.plots import (figsize, mpl_colors)
+# Create an iterator to conveniently change the marker in the following plot.
+markers = (m for m in Line2D.filled_markers)
+
fig, ax = plt.subp... |
fac512af9a65cb07e7f43ad167d32fe9934c1c78 | books/CrackingCodesWithPython/Chapter20/vigenereDictionaryHacker.py | books/CrackingCodesWithPython/Chapter20/vigenereDictionaryHacker.py | # Vigenère Cipher Dictionary Hacker
# https://www.nostarch.com/crackingcodes/ (BSD Licensed)
import detectEnglish, vigenereCipher, pyperclip
def main():
ciphertext = """Tzx isnz eccjxkg nfq lol mys bbqq I lxcz."""
hackedMessage = hackVigenereDictionary(ciphertext)
if hackedMessage != None:
print(... | # Vigenère Cipher Dictionary Hacker
# https://www.nostarch.com/crackingcodes/ (BSD Licensed)
import detectEnglish, vigenereCipher, pyperclip
def main():
ciphertext = """Tzx isnz eccjxkg nfq lol mys bbqq I lxcz."""
hackedMessage = hackVigenereDictionary(ciphertext)
if hackedMessage != None:
print... | Update vigenereDicitonaryHacker: fixed PEP8 spacing | Update vigenereDicitonaryHacker: fixed PEP8 spacing
| Python | mit | JoseALermaIII/python-tutorials,JoseALermaIII/python-tutorials | ---
+++
@@ -2,6 +2,7 @@
# https://www.nostarch.com/crackingcodes/ (BSD Licensed)
import detectEnglish, vigenereCipher, pyperclip
+
def main():
ciphertext = """Tzx isnz eccjxkg nfq lol mys bbqq I lxcz."""
@@ -21,7 +22,7 @@
fo.close()
for word in lines:
- word = word.strip() # Remove the ... |
197aa546b2043602a622340bdec220bdc67e13dd | prince/plot/mpl/util.py | prince/plot/mpl/util.py | import matplotlib.cm as cm
import matplotlib.colors as clr
import matplotlib.pyplot as plt
from ..palettes import SEABORN
def create_discrete_cmap(n):
"""Create an n-bin discrete colormap."""
if n <= len(SEABORN):
colors = list(SEABORN.values())[:n]
else:
base = plt.cm.get_cmap('Paired')
... | import matplotlib.cm as cm
import matplotlib.colors as clr
import matplotlib.pyplot as plt
from ..palettes import SEABORN
def create_discrete_cmap(n):
"""Create an n-bin discrete colormap."""
if n <= len(SEABORN):
colors = list(SEABORN.values())[:n]
else:
base = plt.cm.get_cmap('Paired')
... | Fix AttributeError on ListedColormap from_list method | Fix AttributeError on ListedColormap from_list method
| Python | mit | MaxHalford/Prince | ---
+++
@@ -13,7 +13,7 @@
base = plt.cm.get_cmap('Paired')
color_list = base([(i + 1) / (n + 1) for i in range(n)])
cmap_name = base.name + str(n)
- return base.from_list(cmap_name, color_list, n)
+ return clr.LinearSegmentedColormap.from_list(cmap_name, color_list, n)
re... |
c4b7532987958573dafe01621cdd254db63bf8ea | bfg9000/builtins/hooks.py | bfg9000/builtins/hooks.py | import functools
from six import iteritems
_all_builtins = {}
class _Binder(object):
def __init__(self, args, fn):
self._args = args
self._fn = fn
class _FunctionBinder(_Binder):
def bind(self, **kwargs):
# XXX: partial doesn't forward the docstring of the function.
return f... | import functools
import inspect
import sys
from six import iteritems
_all_builtins = {}
class _Binder(object):
def __init__(self, args, fn):
self._args = args
self._fn = fn
class _FunctionBinder(_Binder):
def bind(self, **kwargs):
pre_args = tuple(kwargs[i] for i in self._args)
... | Change how the wrappers work for builtin functions so that docs get forwarded correctly | Change how the wrappers work for builtin functions so that docs get forwarded correctly
| Python | bsd-3-clause | jimporter/bfg9000,jimporter/bfg9000,jimporter/bfg9000,jimporter/bfg9000 | ---
+++
@@ -1,4 +1,6 @@
import functools
+import inspect
+import sys
from six import iteritems
_all_builtins = {}
@@ -12,8 +14,17 @@
class _FunctionBinder(_Binder):
def bind(self, **kwargs):
- # XXX: partial doesn't forward the docstring of the function.
- return functools.partial(self._fn,... |
b3b281c9bf789c44a9a2b2d750e4dd8cf789dd1a | playserver/webserver.py | playserver/webserver.py | import flask
from . import track
app = flask.Flask(__name__)
@app.route("/")
def root():
return "{} by {} - {}"
| import flask
from . import track
app = flask.Flask(__name__)
@app.route("/")
def root():
song = track.getCurrentSong()
artist = track.getCurrentArtist()
album = track.getCurrentAlbum()
return "{} by {} - {}".format(song, artist, album)
| Add song display to root page | Add song display to root page
| Python | mit | ollien/playserver,ollien/playserver,ollien/playserver | ---
+++
@@ -5,4 +5,7 @@
@app.route("/")
def root():
- return "{} by {} - {}"
+ song = track.getCurrentSong()
+ artist = track.getCurrentArtist()
+ album = track.getCurrentAlbum()
+ return "{} by {} - {}".format(song, artist, album) |
6ccc85832aeff2ca9800cd9e2af8461515ff680d | cartography/midi_utils.py | cartography/midi_utils.py | import mido
def open_output():
return open_steinberg_output()
def get_steinberg_device_name():
output_names = [n for n in mido.get_output_names() if 'steinberg' in n.lower()]
if len(output_names) != 1:
raise Exception(f"Found the following steinberg MIDI devices: {output_names}. Expected only on... | import mido
def open_output():
return open_steinberg_output()
def get_steinberg_device_name():
output_names = [n for n in mido.get_output_names() if 'steinberg' in n.lower()]
if len(output_names) != 1:
raise Exception(f"Found the following steinberg MIDI devices: {output_names}. Expected only on... | Add dump presets and utils | Add dump presets and utils
| Python | mit | tingled/synthetic-cartography,tingled/synthetic-cartography | ---
+++
@@ -13,7 +13,7 @@
def open_steinberg_output():
- return mido.open_output(get_steinberg_device_name())
+ return mido.open_output(get_steinberg_device_name(), autoreset=True)
def open_steinberg_input(): |
883b8d3ebdf006bb6c9b28b234936231f0eac442 | l10n_br_nfse/__manifest__.py | l10n_br_nfse/__manifest__.py | # Copyright 2019 KMEE INFORMATICA LTDA
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "NFS-e",
"summary": """
NFS-e""",
"version": "14.0.1.7.0",
"license": "AGPL-3",
"author": "KMEE, Odoo Community Association (OCA)",
"maintainers": ["gabrielcardoso21", "mileo... | # Copyright 2019 KMEE INFORMATICA LTDA
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "NFS-e",
"summary": """
NFS-e""",
"version": "14.0.1.7.0",
"license": "AGPL-3",
"author": "KMEE, Odoo Community Association (OCA)",
"maintainers": ["gabrielcardoso21", "mileo... | Update python lib erpbrasil.assinatura version 1.4.0 | l10n_br_nfse: Update python lib erpbrasil.assinatura version 1.4.0
| Python | agpl-3.0 | akretion/l10n-brazil,akretion/l10n-brazil,OCA/l10n-brazil,OCA/l10n-brazil,akretion/l10n-brazil,OCA/l10n-brazil | ---
+++
@@ -13,7 +13,7 @@
"external_dependencies": {
"python": [
"erpbrasil.edoc",
- "erpbrasil.assinatura-nopyopenssl",
+ "erpbrasil.assinatura",
"erpbrasil.transmissao",
"erpbrasil.base",
], |
0eabc95105fecfd4b960b1c135f589f0eea9de2a | flaskrst/modules/staticpages/__init__.py | flaskrst/modules/staticpages/__init__.py | # -*- coding: utf-8 -*-
"""
flask-rst.modules.staticfiles
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2011 by Christoph Heer.
:license: BSD, see LICENSE for more details.
"""
import os
from flask import current_app, render_template
from flaskrst.parsers import rstDocument
from flaskrst.modules impo... | # -*- coding: utf-8 -*-
"""
flask-rst.modules.staticfiles
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2011 by Christoph Heer.
:license: BSD, see LICENSE for more details.
"""
import os
from flask import current_app, render_template
from flaskrst.parsers import rstDocument
from flaskrst.modules impo... | Support of static pages inside of a directory | Support of static pages inside of a directory
| Python | bsd-3-clause | jarus/flask-rst | ---
+++
@@ -16,10 +16,12 @@
static_pages = Blueprint('static_pages', __name__, \
template_folder='templates')
-@static_pages.route('/', defaults={'file_name': 'index'})
-@static_pages.route('/<file_name>')
-def show(file_name):
- rst_file = os.path.join(current_app.config['SOURCE'], fi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.