commit stringlengths 40 40 | old_file stringlengths 4 236 | new_file stringlengths 4 236 | old_contents stringlengths 1 3.26k | new_contents stringlengths 16 4.43k | subject stringlengths 16 624 | message stringlengths 17 3.29k | lang stringclasses 5
values | license stringclasses 13
values | repos stringlengths 5 91.5k |
|---|---|---|---|---|---|---|---|---|---|
1d52996a88eb5aed643fe61ee959bd88373401b3 | filebutler_upload/utils.py | filebutler_upload/utils.py | from datetime import datetime, timedelta
import sys
class ProgressBar(object):
def __init__(self, filename, fmt):
self.filename = filename
self.fmt = fmt
self.progress = 0
self.total = 0
self.time_started = datetime.now()
self.time_updated = self.time_started
d... | from datetime import datetime, timedelta
import sys
class ProgressBar(object):
def __init__(self, filename, fmt):
self.filename = filename
self.fmt = fmt
self.progress = 0
self.total = 0
self.time_started = datetime.now()
self.time_updated = self.time_started
d... | Throw a linebreak in there upon completion | Throw a linebreak in there upon completion
| Python | bsd-3-clause | jhaals/filebutler-upload |
07f96a22afe2d010809d03077d9cdd5ecb43d017 | migrations/0020_change_ds_name_to_non_uniqe.py | migrations/0020_change_ds_name_to_non_uniqe.py | from redash.models import db
from playhouse.migrate import PostgresqlMigrator, migrate
if __name__ == '__main__':
migrator = PostgresqlMigrator(db.database)
with db.database.transaction():
# Change the uniqueness constraint on data source name to be (org, name):
db.database.execute_sql("ALTER ... | from redash.models import db
import peewee
from playhouse.migrate import PostgresqlMigrator, migrate
if __name__ == '__main__':
migrator = PostgresqlMigrator(db.database)
with db.database.transaction():
# Change the uniqueness constraint on data source name to be (org, name):
success = False
... | Update data source unique name migration to support another name of constraint | Update data source unique name migration to support another name of constraint
| Python | bsd-2-clause | akariv/redash,chriszs/redash,jmvasquez/redashtest,pubnative/redash,akariv/redash,amino-data/redash,ninneko/redash,ninneko/redash,denisov-vlad/redash,EverlyWell/redash,ninneko/redash,amino-data/redash,44px/redash,moritz9/redash,guaguadev/redash,moritz9/redash,guaguadev/redash,chriszs/redash,pubnative/redash,44px/redash,... |
169dda227f85f77ac52a4295e8fb7acd1b3184f5 | core/observables/mac_address.py | core/observables/mac_address.py | from __future__ import unicode_literals
import re
from core.observables import Observable
class MacAddress(Observable):
regex = r'(?P<search>(([0-9A-Fa-f]{1,2}[.:-]?){5,7}([0-9A-Fa-f]{1,2})))'
exclude_fields = Observable.exclude_fields
DISPLAY_FIELDS = Observable.DISPLAY_FIELDS
@classmethod
d... | from __future__ import unicode_literals
import re
from core.observables import Observable
class MacAddress(Observable):
regex = r'(?P<search>(([0-9A-Fa-f]{1,2}[.:-]){5,7}([0-9A-Fa-f]{1,2})))'
exclude_fields = Observable.exclude_fields
DISPLAY_FIELDS = Observable.DISPLAY_FIELDS
@classmethod
de... | Make byte-separator mandatory in MAC addresses | Make byte-separator mandatory in MAC addresses
This will prevent false positive (from hash values for example).
| Python | apache-2.0 | yeti-platform/yeti,yeti-platform/yeti,yeti-platform/yeti,yeti-platform/yeti |
bbe835c8aa561d8db58e116f0e55a5b19c4f9ca4 | firecares/sitemaps.py | firecares/sitemaps.py | from django.contrib import sitemaps
from firecares.firestation.models import FireDepartment
from django.db.models import Max
from django.core.urlresolvers import reverse
class BaseSitemap(sitemaps.Sitemap):
protocol = 'https'
def items(self):
return ['media', 'models_performance_score', 'models_commu... | from django.contrib import sitemaps
from firecares.firestation.models import FireDepartment
from django.db.models import Max
from django.core.urlresolvers import reverse
class BaseSitemap(sitemaps.Sitemap):
protocol = 'https'
def items(self):
return ['media', 'models_performance_score', 'models_commu... | Fix sitemap memory consumption during generation | Fix sitemap memory consumption during generation
- Defer ALL FireDepartment fields except for those required to create a sitemap
- Was causing node startup to hang
see #321 | Python | mit | FireCARES/firecares,FireCARES/firecares,FireCARES/firecares,FireCARES/firecares,FireCARES/firecares |
196b9547b4dbcbfbf4891c7fd3ea3b9944018430 | scripts/cronRefreshEdxQualtrics.py | scripts/cronRefreshEdxQualtrics.py | from surveyextractor import QualtricsExtractor
import getopt, sys
# Script for scheduling regular EdxQualtrics updates
# Usage for cron should be "cronRefreshEdxQualtrics.py -m -s -r"
qe = QualtricsExtractor()
opts, args = getopt.getopt(sys.argv[1:], 'amsr', ['--reset', '--loadmeta', '--loadsurveys', '--loadresponses... | from surveyextractor import QualtricsExtractor
import getopt
import sys
### Script for scheduling regular EdxQualtrics updates
### Usage for cron should be "cronRefreshEdxQualtrics.py -m -s -r"
# Append directory for dependencies to PYTHONPATH
sys.path.append("/home/dataman/Code/qualtrics_etl/src/qualtrics_etl/")
qe... | Revert "Revert "Added script for cron job to load surveys to database."" | Revert "Revert "Added script for cron job to load surveys to database.""
This reverts commit 2192219d92713c6eb76593d0c6c29413d040db6a.
| Python | bsd-3-clause | paepcke/json_to_relation,paepcke/json_to_relation,paepcke/json_to_relation,paepcke/json_to_relation |
0b77e09ac16006d1baa6a5f4093b51c1a13863e9 | app/models.py | app/models.py | from app import db
class Digit(db.Model):
id = db.Column(db.INTEGER, primary_key=True)
label = db.Column(db.INTEGER)
tsne_x = db.Column(db.REAL)
tsne_y = db.Column(db.REAL)
tsne_z = db.Column(db.REAL)
array = db.Column(db.String)
image = db.Column(db.BLOB)
def __repr__(self):
r... | from app import db
class Digit(db.Model):
__tablename__ = 'digits'
id = db.Column(db.INTEGER, primary_key=True)
label = db.Column(db.INTEGER)
tsne_x = db.Column(db.REAL)
tsne_y = db.Column(db.REAL)
tsne_z = db.Column(db.REAL)
array = db.Column(db.String)
def __repr__(self):
re... | Add as_dict method to Digit model | Add as_dict method to Digit model
| Python | mit | starcalibre/MNIST3D,starcalibre/MNIST3D,starcalibre/MNIST3D |
e2c92e8b6e8fb10addc73986914014b278598470 | spotpy/examples/spot_setup_standardnormal.py | spotpy/examples/spot_setup_standardnormal.py | '''
Copyright 2015 by Tobias Houska
This file is part of Statistical Parameter Estimation Tool (SPOTPY).
:author: Tobias Houska
This example implements the Rosenbrock function into SPOT.
'''
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ ... | '''
Copyright 2015 by Tobias Houska
This file is part of Statistical Parameter Estimation Tool (SPOTPY).
:author: Tobias Houska
This example implements the Standard Normal function into SPOT.
'''
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __futu... | Fix docstring in standardnormal example | Fix docstring in standardnormal example
| Python | mit | bees4ever/spotpy,bees4ever/spotpy,bees4ever/spotpy,thouska/spotpy,thouska/spotpy,thouska/spotpy |
81de62d46d7daefb2e1eef0d0cc4f5ca5c8aef2f | blog/utils.py | blog/utils.py | from django.shortcuts import get_object_or_404
from .models import Post
class PostGetMixin:
date_field = 'pub_date'
month_url_kwarg = 'month'
year_url_kwarg = 'year'
errors = {
'url_kwargs':
"Generic view {} must be called with "
"year, month, and slug.",
}
d... | from django.shortcuts import get_object_or_404
from .models import Post
class PostGetMixin:
date_field = 'pub_date'
model = Post
month_url_kwarg = 'month'
year_url_kwarg = 'year'
errors = {
'url_kwargs':
"Generic view {} must be called with "
"year, month, and slu... | Use GCBV queryset to get PostGetMixin obj. | Ch18: Use GCBV queryset to get PostGetMixin obj.
| Python | bsd-2-clause | jambonrose/DjangoUnleashed-1.8,jambonrose/DjangoUnleashed-1.8 |
8e58d7cccb837254cc433c7533bff119cc19645d | javascript_settings/templatetags/javascript_settings_tags.py | javascript_settings/templatetags/javascript_settings_tags.py | from django import template
from django.utils import simplejson
from javascript_settings.configuration_builder import \
DEFAULT_CONFIGURATION_BUILDER
register = template.Library()
@register.tag(name='javascript_settings')
def do_javascript_settings(parser, token):
"""
Returns a node with generated c... | import json
from django import template
from javascript_settings.configuration_builder import \
DEFAULT_CONFIGURATION_BUILDER
register = template.Library()
@register.tag(name='javascript_settings')
def do_javascript_settings(parser, token):
"""
Returns a node with generated configuration.
"""
... | Use json instead of django.utils.simplejson. | Use json instead of django.utils.simplejson. | Python | mit | pozytywnie/django-javascript-settings |
e4ad2863236cd36e5860f1d17a06ca05e30216d5 | make_database.py | make_database.py | import sqlite3
CREATE_SONG_QUEUE = '''
CREATE TABLE IF NOT EXISTS
jukebox_song_queue (
spotify_uri TEXT,
has_played INTEGER DEFAULT 0
);
'''
if __name__ == '__main__':
conn = sqlite3.connect('jukebox.db')
cursor = conn.cursor()
cursor.execute(CREATE_SONG_QUEUE)
conn.commit()
conn.close... | import sqlite3
CREATE_SONG_QUEUE = '''
CREATE TABLE IF NOT EXISTS
jukebox_song_queue (
spotify_uri TEXT,
has_played INTEGER DEFAULT 0,
name TEXT,
artist_name TEXT,
artist_uri TEXT,
artist_image TEXT,
album_name TEXT,
album_uri TEXT,
album_image TEXT
);
'''
if __name__ == '__main... | Store more stuff about songs in the queue | Store more stuff about songs in the queue
| Python | mit | projectweekend/Pi-Jukebox,projectweekend/Pi-Jukebox,projectweekend/Pi-Jukebox |
5eb2c6f7e1bf0cc1b73b167a08085fccf77974fe | app/config/aws.py | app/config/aws.py | from boto import ec2, utils
import credstash
class AWSIntanceEnv(object):
def __init__(self):
metadata = utils.get_instance_metadata()
self.instance_id = metadata['instance-id']
self.region = metadata['placement']['availability-zone'][:-1]
conn = ec2.connect_to_region(self.region... | # -*- coding: utf-8 -*-
"""
Dictionary-like class for config settings from AWS credstash
"""
from boto import ec2, utils
import credstash
class AWSIntanceEnv(object):
def __init__(self):
metadata = utils.get_instance_metadata()
self.instance_id = metadata['instance-id']
self.region = met... | Tidy up and doc-comment AWSInstanceEnv class | Tidy up and doc-comment AWSInstanceEnv class
| Python | mit | crossgovernmentservices/csd-notes,crossgovernmentservices/csd-notes,crossgovernmentservices/csd-notes |
58d7592c603509f2bb625e4e2e5cb31ada4a8194 | astropy/nddata/convolution/tests/test_make_kernel.py | astropy/nddata/convolution/tests/test_make_kernel.py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
import numpy as np
from numpy.testing import assert_allclose, assert_equal
from ....tests.helper import pytest
from ..make_kernel import make_kernel
try:
import scipy
HAS_SCIPY = True
except ImportError:
HAS_SCIPY = False
class TestMakeKern... | # Licensed under a 3-clause BSD style license - see LICENSE.rst
import numpy as np
from numpy.testing import assert_allclose
from ....tests.helper import pytest
from ..make_kernel import make_kernel
try:
import scipy
HAS_SCIPY = True
except ImportError:
HAS_SCIPY = False
@pytest.mark.skipif('not HAS_SCI... | Change test for make_kernel(kerneltype='airy') from class to function | Change test for make_kernel(kerneltype='airy') from class to function
| Python | bsd-3-clause | AustereCuriosity/astropy,astropy/astropy,lpsinger/astropy,MSeifert04/astropy,larrybradley/astropy,StuartLittlefair/astropy,dhomeier/astropy,kelle/astropy,joergdietrich/astropy,mhvk/astropy,kelle/astropy,joergdietrich/astropy,StuartLittlefair/astropy,tbabej/astropy,dhomeier/astropy,StuartLittlefair/astropy,mhvk/astropy,... |
9cdd86499013c1deac7caeb8320c34294789f716 | py/garage/garage/asyncs/actors.py | py/garage/garage/asyncs/actors.py | """Asynchronous support for garage.threads.actors."""
__all__ = [
'StubAdapter',
]
from garage.asyncs import futures
class StubAdapter:
"""Wrap all method calls, adding FutureAdapter on their result.
While this simple adapter does not work for all corner cases, for
common cases, it should work fine... | """Asynchronous support for garage.threads.actors."""
__all__ = [
'StubAdapter',
]
from garage.asyncs import futures
class StubAdapter:
"""Wrap all method calls, adding FutureAdapter on their result.
While this simple adapter does not work for all corner cases, for
common cases, it should work fine... | Add _kill_and_join to async actor stub | Add _kill_and_join to async actor stub
| Python | mit | clchiou/garage,clchiou/garage,clchiou/garage,clchiou/garage |
4d40e9db4bd6b58787557e8d5547f69eb67c9b96 | tests/changes/api/test_author_build_index.py | tests/changes/api/test_author_build_index.py | from uuid import uuid4
from changes.config import db
from changes.models import Author
from changes.testutils import APITestCase
class AuthorBuildListTest(APITestCase):
def test_simple(self):
fake_author_id = uuid4()
self.create_build(self.project)
path = '/api/0/authors/{0}/builds/'.fo... | from uuid import uuid4
from changes.config import db
from changes.models import Author
from changes.testutils import APITestCase
class AuthorBuildListTest(APITestCase):
def test_simple(self):
fake_author_id = uuid4()
self.create_build(self.project)
path = '/api/0/authors/{0}/builds/'.fo... | Add additional coverage to author build list | Add additional coverage to author build list
| Python | apache-2.0 | wfxiang08/changes,wfxiang08/changes,dropbox/changes,bowlofstew/changes,bowlofstew/changes,wfxiang08/changes,dropbox/changes,wfxiang08/changes,dropbox/changes,bowlofstew/changes,bowlofstew/changes,dropbox/changes |
5cd9499fcc0c1f9b48216aeca11a7adcd8995a47 | netmiko/mrv/mrv_ssh.py | netmiko/mrv/mrv_ssh.py | """MRV Communications Driver (OptiSwitch)."""
from __future__ import unicode_literals
import time
import re
from netmiko.cisco_base_connection import CiscoSSHConnection
class MrvOptiswitchSSH(CiscoSSHConnection):
"""MRV Communications Driver (OptiSwitch)."""
def session_preparation(self):
"""Prepare ... | """MRV Communications Driver (OptiSwitch)."""
from __future__ import unicode_literals
import time
import re
from netmiko.cisco_base_connection import CiscoSSHConnection
class MrvOptiswitchSSH(CiscoSSHConnection):
"""MRV Communications Driver (OptiSwitch)."""
def session_preparation(self):
"""Prepare ... | Fix for MRV failing to enter enable mode | Fix for MRV failing to enter enable mode
| Python | mit | ktbyers/netmiko,ktbyers/netmiko |
0d2f35ddc27cf4c7155a4d1648c0bbfe0ff3a528 | numpy/_array_api/dtypes.py | numpy/_array_api/dtypes.py | from .. import int8, int16, int32, int64, uint8, uint16, uint32, uint64, float32, float64, bool
__all__ = ['int8', 'int16', 'int32', 'int64', 'uint8', 'uint16', 'uint32', 'uint64', 'float32', 'float64', 'bool']
| from .. import int8, int16, int32, int64, uint8, uint16, uint32, uint64, float32, float64
# Note: This name is changed
from .. import bool_ as bool
__all__ = ['int8', 'int16', 'int32', 'int64', 'uint8', 'uint16', 'uint32', 'uint64', 'float32', 'float64', 'bool']
| Fix the bool name in the array API namespace | Fix the bool name in the array API namespace
| Python | mit | cupy/cupy,cupy/cupy,cupy/cupy,cupy/cupy |
7a0560d8bd9dcb421b54522df92618d439941e69 | bills/urls.py | bills/urls.py | from . import views
from django.conf.urls import url
urlpatterns = [
url(r'^by_topic/', views.bill_list_by_topic),
url(r'^by_location', views.bill_list_by_location),
url(r'^latest_activity/', views.latest_bill_activity),
url(r'^latest/', views.latest_bill_actions),
url(r'^detail/(?P<bill_id>(.*))/... | from . import views
from django.conf.urls import url
urlpatterns = [
url(r'^by_topic/', views.bill_list_by_topic),
url(r'^by_location', views.bill_list_by_location),
url(r'^latest_activity/', views.latest_bill_activity),
url(r'^latest/', views.latest_bill_actions),
url(r'^detail/(?P<bill_session>(... | Change bill detail page to use session and identifier | Change bill detail page to use session and identifier
| Python | mit | jamesturk/tot,jamesturk/tot,jamesturk/tot,jamesturk/tot,jamesturk/tot |
d9f623baaa8e1d1075f9132108ed7bb11eea39b0 | dask/__init__.py | dask/__init__.py | from __future__ import absolute_import, division, print_function
from .core import istask, get
from .context import set_options
try:
from .imperative import do, value
except ImportError:
pass
__version__ = '0.7.3'
| from __future__ import absolute_import, division, print_function
from .core import istask
from .context import set_options
from .async import get_sync as get
try:
from .imperative import do, value
except ImportError:
pass
__version__ = '0.7.3'
| Replace dask.get from core.get to async.get_sync | Replace dask.get from core.get to async.get_sync
We really shouldn't publish core.get anywhere, particularly in the
top level API.
| Python | bsd-3-clause | vikhyat/dask,cowlicks/dask,ContinuumIO/dask,blaze/dask,ContinuumIO/dask,mraspaud/dask,mrocklin/dask,cpcloud/dask,jakirkham/dask,chrisbarber/dask,jakirkham/dask,blaze/dask,mikegraham/dask,pombredanne/dask,gameduell/dask,pombredanne/dask,dask/dask,dask/dask,vikhyat/dask,mrocklin/dask,jcrist/dask,mraspaud/dask,jcrist/dask |
78705f598e7e3325e871bd17ff353a31c71bc399 | opps/articles/forms.py | opps/articles/forms.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django import forms
from .models import Post, Album, Link
from opps.core.widgets import OppsEditor
from opps.db.models.fields.jsonf import JSONFormField
from opps.fields.widgets import JSONField
from opps.fields.models import Field, FieldOption
class PostAdminForm... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from opps.core.widgets import OppsEditor
from opps.containers.forms import ContainerAdminForm
from .models import Post, Album, Link
class PostAdminForm(ContainerAdminForm):
multiupload_link = '/fileupload/image/'
class Meta:
model = Post
widgets ... | Extend all admin form to Container Admin Form (json field) | Extend all admin form to Container Admin Form (json field)
| Python | mit | opps/opps,YACOWS/opps,williamroot/opps,williamroot/opps,YACOWS/opps,opps/opps,YACOWS/opps,jeanmask/opps,jeanmask/opps,YACOWS/opps,opps/opps,jeanmask/opps,williamroot/opps,opps/opps,jeanmask/opps,williamroot/opps |
52c3981b8880085d060f874eb8feace6ac125411 | tests/test_cli_bands.py | tests/test_cli_bands.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Author: Dominik Gresch <greschd@gmx.ch>
import os
import pytest
import tempfile
import bandstructure_utils as bs
from click.testing import CliRunner
import tbmodels
from tbmodels._cli import cli
from parameters import SAMPLES_DIR
def test_cli_bands():
samples_d... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Author: Dominik Gresch <greschd@gmx.ch>
import os
import pytest
import tempfile
import numpy as np
import bandstructure_utils as bs
from click.testing import CliRunner
import tbmodels
from tbmodels._cli import cli
from parameters import SAMPLES_DIR
def test_cli_ban... | Replace exact equality assert with isclose in bands cli | Replace exact equality assert with isclose in bands cli
| Python | apache-2.0 | Z2PackDev/TBmodels,Z2PackDev/TBmodels |
8b4b5eb2506feed164b69efa66b4cdae159182c3 | tests/test_cli_parse.py | tests/test_cli_parse.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# (c) 2015-2018, ETH Zurich, Institut fuer Theoretische Physik
# Author: Dominik Gresch <greschd@gmx.ch>
import pytest
import tempfile
from click.testing import CliRunner
import tbmodels
from tbmodels._cli import cli
@pytest.mark.parametrize('pos_kind', ['wannier', 'ne... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# (c) 2015-2018, ETH Zurich, Institut fuer Theoretische Physik
# Author: Dominik Gresch <greschd@gmx.ch>
"""Tests for the 'parse' CLI command."""
import tempfile
import pytest
from click.testing import CliRunner
import tbmodels
from tbmodels._cli import cli
@pytest.ma... | Fix pre-commit issues in the cli_parse tests. | Fix pre-commit issues in the cli_parse tests.
| Python | apache-2.0 | Z2PackDev/TBmodels,Z2PackDev/TBmodels |
afb400e16c1335531f259218a8b9937de48644e9 | polyaxon/checks/streams.py | polyaxon/checks/streams.py | from checks.base import Check
from checks.results import Result
from libs.api import get_settings_ws_api_url
from libs.http import safe_request
class StreamsCheck(Check):
@classmethod
def run(cls):
response = safe_request(get_settings_ws_api_url(), 'GET')
status_code = response.status_code
... | from checks.base import Check
from checks.results import Result
from libs.api import get_settings_ws_api_url
from libs.http import safe_request
class StreamsCheck(Check):
@classmethod
def run(cls):
response = safe_request('{}/_health'.format(get_settings_ws_api_url()), 'GET')
status_code = re... | Update stream health health api url | Update stream health health api url
| Python | apache-2.0 | polyaxon/polyaxon,polyaxon/polyaxon,polyaxon/polyaxon |
edb04d8e0ae03c9244b7d934fd713efbb94d5a58 | opps/api/urls.py | opps/api/urls.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.conf.urls import patterns, url, include
from tastypie.api import Api
from opps.containers.api import Container
from opps.articles.api import Post
from .conf import settings
_api = Api(api_name=settings.OPPS_API_NAME)
_api.register(Container())
_api.register... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.conf.urls import patterns, url, include
from tastypie.api import Api
from opps.containers.api import Container
from opps.articles.api import Post, Album, Link
from .conf import settings
_api = Api(api_name=settings.OPPS_API_NAME)
_api.register(Container())
... | Add api url to album and link | Add api url to album and link
| Python | mit | williamroot/opps,opps/opps,YACOWS/opps,jeanmask/opps,jeanmask/opps,YACOWS/opps,williamroot/opps,opps/opps,williamroot/opps,jeanmask/opps,opps/opps,williamroot/opps,opps/opps,YACOWS/opps,jeanmask/opps,YACOWS/opps |
7b19611d30dfc9091823ae3d960ab2790dfe9cfc | python/blur_human_faces.py | python/blur_human_faces.py | import requests
import json
imgUrl = 'https://pixlab.io/images/m3.jpg' # Target picture we want to blur any face on
# Detect all human faces in a given image via /facedetect first and blur all of them later via /mogrify.
# https://pixlab.io/cmd?id=facedetect and https://pixlab.io/cmd?id=mogrify for additional informa... | import requests
import json
imgUrl = 'https://pixlab.io/images/m3.jpg' # Target picture we want to blur any face on
# Detect all human faces in a given image via /facedetect first and blur all of them later via /mogrify.
# https://pixlab.io/cmd?id=facedetect and https://pixlab.io/cmd?id=mogrify for additional informa... | Apply a blur filter automatically for each detected face | Apply a blur filter automatically for each detected face | Python | bsd-2-clause | symisc/pixlab,symisc/pixlab,symisc/pixlab |
74ecf023ef13fdba6378d6b50b3eaeb06b9e0c97 | rebuild_dependant_repos.py | rebuild_dependant_repos.py | import os, sys, re, logging
import requests
from github import Github
logging.basicConfig(level=logging.DEBUG)
CIRCLECI_BASEURL = "https://circleci.com/api/v2"
CIRCLECI_ACCESS_TOKEN = os.environ["TAO_CIRCLECI_TOKEN"]
GITHUB_ACCESS_TOKEN = os.environ["TAO_GITHUB_TOKEN"]
g = Github(GITHUB_ACCESS_TOKEN)
if len(sys.argv... | import os, sys, re
import requests
from github import Github
CIRCLECI_BASEURL = "https://circleci.com/api/v2"
CIRCLECI_ACCESS_TOKEN = os.environ["AVATAO_CIRCLECI_TOKEN"]
GITHUB_ACCESS_TOKEN = os.environ["AVATAO_GITHUB_TOKEN"]
g = Github(GITHUB_ACCESS_TOKEN)
if len(sys.argv) < 2:
raise AttributeError("The image na... | Rename env vars & modify query | Rename env vars & modify query
| Python | apache-2.0 | avatao-content/challenge-toolbox,avatao-content/challenge-toolbox,avatao-content/challenge-toolbox,avatao-content/challenge-toolbox,avatao-content/challenge-toolbox,avatao-content/challenge-toolbox,avatao-content/challenge-toolbox,avatao-content/challenge-toolbox,avatao-content/challenge-toolbox |
d98cdb7eae40b5bb11b5d1fc0eacc35ef6bf310d | wye/reports/views.py | wye/reports/views.py | from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from wye.organisations.models import Organisation
from wye.workshops.models import Workshop
from wye.profiles.models import Profile
import datetime
from wye.base.constants import WorkshopStatus
@login_required
def index(requ... | from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from wye.organisations.models import Organisation
from wye.workshops.models import Workshop
from wye.profiles.models import Profile
import datetime
from wye.base.constants import WorkshopStatus
@login_required
def index(requ... | Order filter for report page | Order filter for report page
| Python | mit | pythonindia/wye,pythonindia/wye,pythonindia/wye,pythonindia/wye |
10f7938e37180c0cb3b701223cf6d1855e7d8f93 | watchdog_kj_kultura/main/models.py | watchdog_kj_kultura/main/models.py | from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.utils.encoding import python_2_unicode_compatible
from model_utils.models import TimeStampedModel
from tinymce.models import HTMLField
from django.contrib.sites.models import Site
class SettingsQuerySet(models.QuerySet):
... | from django.db import models
from django.utils.translation import ugettext_lazy as _
from model_utils.models import TimeStampedModel
from tinymce.models import HTMLField
from django.contrib.sites.models import Site
class SettingsQuerySet(models.QuerySet):
pass
class Settings(TimeStampedModel):
site = models... | Drop python_2_unicode_compatible for Settings, fix docs build on rtfd | Drop python_2_unicode_compatible for Settings, fix docs build on rtfd
| Python | mit | watchdogpolska/watchdog-kj-kultura,watchdogpolska/watchdog-kj-kultura,watchdogpolska/watchdog-kj-kultura |
8dcb778c62c3c6722e2f6dabfd97f6f75c349e62 | celery_cgi.py | celery_cgi.py | import os
import logging
from celery import Celery
from temp_config.set_environment import DeployEnv
runtime_env = DeployEnv()
runtime_env.load_deployment_environment()
redis_server = os.environ.get('REDIS_HOSTNAME')
redis_port = os.environ.get('REDIS_PORT')
celery_tasks = [
'hms_flask.modules.hms_controller',
... | import os
import logging
from celery import Celery
from temp_config.set_environment import DeployEnv
runtime_env = DeployEnv()
runtime_env.load_deployment_environment()
redis_server = os.environ.get('REDIS_HOSTNAME')
redis_port = os.environ.get('REDIS_PORT')
celery_tasks = [
'hms_flask.modules.hms_controller',
... | Set celery max tasks child to 1 | Set celery max tasks child to 1 | Python | unlicense | puruckertom/ubertool_ecorest,quanted/ubertool_ecorest,puruckertom/ubertool_ecorest,quanted/ubertool_ecorest,quanted/ubertool_ecorest,puruckertom/ubertool_ecorest,puruckertom/ubertool_ecorest,quanted/ubertool_ecorest |
d84a4efcf880bb668b2721af3f4ce18220e8baab | xvistaprof/reader.py | xvistaprof/reader.py | #!/usr/bin/env python
# encoding: utf-8
"""
Reader for XVISTA .prof tables.
"""
import numpy as np
from astropy.table import Table
from astropy.io import registry
def xvista_table_reader(filename):
dt = [('R', np.float), ('SB', np.float), ('SB_err', np.float),
('ELL', np.float), ('PA', np.float), ('E... | #!/usr/bin/env python
# encoding: utf-8
"""
Reader for XVISTA .prof tables.
"""
import numpy as np
from astropy.table import Table
from astropy.io import registry
def xvista_table_reader(filename):
dt = [('R', np.float), ('SB', np.float), ('SB_err', np.float),
('ELL', np.float), ('PA', np.float), ('EMA... | Use np.genfromtext to handle missing values | Use np.genfromtext to handle missing values
| Python | bsd-2-clause | jonathansick/xvistaprof |
3b5b3afbc66f60df45f0458ffdd0d37b9a7c50d0 | ptoolbox/tags.py | ptoolbox/tags.py | # -*- coding: utf-8 -*-
from datetime import datetime
TAG_WIDTH = 'EXIF ExifImageWidth'
TAG_HEIGHT = 'EXIF ExifImageLength'
TAG_DATETIME = 'Image DateTime'
def parse_time(tags):
tag = tags.get(TAG_DATETIME, None)
if not tag:
raise KeyError(TAG_DATETIME)
return datetime.strptime(str(tag), "%Y:%m:%... | # -*- coding: utf-8 -*-
import struct
from datetime import datetime
TAG_WIDTH = 'EXIF ExifImageWidth'
TAG_HEIGHT = 'EXIF ExifImageLength'
TAG_DATETIME = 'Image DateTime'
def jpeg_size(path):
"""Get image size.
Structure of JPEG file is:
ffd8 [ffXX SSSS DD DD ...] [ffYY SSSS DDDD ...] (S is 16bit si... | Add homemade fast width/height reader for JPEG files | Add homemade fast width/height reader for JPEG files
| Python | mit | vperron/picasa-toolbox |
c46e472755c7b7dd450626e136f31a29ca9a5321 | rbtools/utils/users.py | rbtools/utils/users.py | from __future__ import unicode_literals
import getpass
import logging
import sys
from six.moves import input
from rbtools.api.errors import AuthorizationError
from rbtools.commands import CommandError
def get_authenticated_session(api_client, api_root, auth_required=False):
"""Return an authenticated session.
... | from __future__ import unicode_literals
import getpass
import logging
import sys
from six.moves import input
from rbtools.api.errors import AuthorizationError
from rbtools.commands import CommandError
def get_authenticated_session(api_client, api_root, auth_required=False):
"""Return an authenticated session.
... | Fix a regression in accessing the username for the session. | Fix a regression in accessing the username for the session.
My previous optimization to fetching the user resource along with the
session broke the `get_username()` function, which attempted to follow a
now non-existent link. It's been updated to get the expanded user
resource instead and access the username from that... | Python | mit | reviewboard/rbtools,halvorlu/rbtools,beol/rbtools,datjwu/rbtools,davidt/rbtools,datjwu/rbtools,davidt/rbtools,reviewboard/rbtools,haosdent/rbtools,halvorlu/rbtools,haosdent/rbtools,haosdent/rbtools,reviewboard/rbtools,beol/rbtools,beol/rbtools,datjwu/rbtools,halvorlu/rbtools,davidt/rbtools |
4c124f151c2f8d466840b10e7ed53395b3d587dc | UM/Math/Ray.py | UM/Math/Ray.py | from UM.Math.Vector import Vector
class Ray:
def __init__(self, origin = Vector(), direction = Vector()):
self._origin = origin
self._direction = direction
self._invDirection = 1.0 / direction
@property
def origin(self):
return self._origin
@property
def direction(... | from UM.Math.Vector import Vector
class Ray:
def __init__(self, origin = Vector(), direction = Vector()):
self._origin = origin
self._direction = direction
self._invDirection = 1.0 / direction
@property
def origin(self):
return self._origin
@property
def direction(... | Add a convenience method to get a point along a ray | Add a convenience method to get a point along a ray
| Python | agpl-3.0 | onitake/Uranium,onitake/Uranium |
8494ece12d8fe27c4c76797083c851a96e054286 | PropensityScoreMatching/__init__.py | PropensityScoreMatching/__init__.py | # -*- coding: utf-8 -*-
"""
Created on Mon May 18 15:09:03 2015
@author: Alexander
"""
class Match(object):
'''
Perform matching algorithm on input data and return a list of indicies
corresponding to matches.
'''
def __init__(self, match_type='neighbor'):
self.match_type = match_type
d... | # -*- coding: utf-8 -*-
"""
Created on Mon May 18 15:09:03 2015
@author: Alexander
"""
import statsmodels.api as sm
class Match(object):
'''
Perform matching algorithm on input data and return a list of indicies
corresponding to matches.
'''
def __init__(self, match_type='neighbor'):
self... | Implement propensity score fitting for logit model | Implement propensity score fitting for logit model
| Python | mit | aegorenkov/PropensityScoreMatching |
427629ca4cfe231acd8cd4ad54470038ca03c13e | zerver/migrations/0076_userprofile_emojiset.py | zerver/migrations/0076_userprofile_emojiset.py | # -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-04-23 19:51
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('zerver', '0075_attachment_path_id_unique'),
]
operations = [
migrations.Add... | # -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-04-23 19:51
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('zerver', '0075_attachment_path_id_unique'),
]
operations = [
migrations.Add... | Fix strings in migration 0076. | emoji: Fix strings in migration 0076.
It's arguably a bug that Django puts the value strings into the
migration object, but this was causing test failures.
| Python | apache-2.0 | punchagan/zulip,kou/zulip,synicalsyntax/zulip,vaidap/zulip,brockwhittaker/zulip,j831/zulip,eeshangarg/zulip,jphilipsen05/zulip,jackrzhang/zulip,j831/zulip,shubhamdhama/zulip,brainwane/zulip,verma-varsha/zulip,synicalsyntax/zulip,mahim97/zulip,verma-varsha/zulip,eeshangarg/zulip,showell/zulip,eeshangarg/zulip,andersk/zu... |
eabbd0468e7334dfb5d4866baadb7b4265d8536f | virtool/caches/utils.py | virtool/caches/utils.py | import os
from typing import Union
import virtool.samples.utils
def join_cache_path(settings: dict, cache_id: str):
"""
Create a cache path string given the application settings and cache id.
:param settings: the application settings
:param cache_id: the id of the cache
:return: a cache path
... | """
Utilities used for working with cache files within analysis workflows.
"""
import os
from typing import Union
import virtool.samples.utils
def join_cache_path(settings: dict, cache_id: str):
"""
Create a cache path string given the application settings and cache id.
:param settings: the application... | Update virtool.caches docstrings and typing | Update virtool.caches docstrings and typing
| Python | mit | virtool/virtool,igboyes/virtool,virtool/virtool,igboyes/virtool |
3bef86bd3637642587ed15680249c278504fc4fb | pontoon/administration/management/commands/update_projects.py | pontoon/administration/management/commands/update_projects.py |
import os
from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
from pontoon.administration.views import _update_from_repository
from pontoon.base.models import Project
class Command(BaseCommand):
help = 'Update all projects from their repositories and store changes to... |
import os
import datetime
from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
from pontoon.administration.views import _update_from_repository
from pontoon.base.models import Project
class Command(BaseCommand):
help = 'Update all projects from their repositories and... | Add timestamp and newline to log messages | Add timestamp and newline to log messages
| Python | bsd-3-clause | mathjazz/pontoon,yfdyh000/pontoon,jotes/pontoon,mozilla/pontoon,sudheesh001/pontoon,mathjazz/pontoon,jotes/pontoon,vivekanand1101/pontoon,mastizada/pontoon,jotes/pontoon,m8ttyB/pontoon,Jobava/mirror-pontoon,Jobava/mirror-pontoon,participedia/pontoon,jotes/pontoon,yfdyh000/pontoon,m8ttyB/pontoon,vivekanand1101/pontoon,v... |
f8a6b4d8053a60cfec372d8b91bf294d606055ec | app/admin/routes.py | app/admin/routes.py | from flask import render_template, redirect, url_for, flash, request
from flask.ext.login import login_required, current_user
from . import admin
from .forms import ProfileForm
from .. import db
from ..models import User
@admin.route('/')
@login_required
def index():
return render_template('admin/user.html', user=... | from datetime import datetime
from flask import render_template, redirect, url_for, flash, request
from flask.ext.login import login_required, current_user
from . import admin
from .forms import ProfileForm, PostForm
from .. import db
from ..models import User
@admin.route('/')
@login_required
def index():
return... | Add a route to admin/news/post to post a news story. Uses the PostForm for forms | Add a route to admin/news/post to post a news story. Uses the PostForm for forms
| Python | mit | finnurtorfa/aflafrettir.is,finnurtorfa/aflafrettir.is,finnurtorfa/aflafrettir.is,finnurtorfa/aflafrettir.is |
1b1715c4c44c162f650d6da79f5571ac2c0f994b | utils/get_collection_object_count.py | utils/get_collection_object_count.py | #!/usr/bin/env python
# -*- coding: utf8 -*-
import sys, os
import argparse
from deepharvest.deepharvest_nuxeo import DeepHarvestNuxeo
def main(argv=None):
parser = argparse.ArgumentParser(description='Print count of objects for a given collection.')
parser.add_argument('path', help="Nuxeo path to collection... | #!/usr/bin/env python
# -*- coding: utf8 -*-
import sys, os
import argparse
from deepharvest.deepharvest_nuxeo import DeepHarvestNuxeo
def main(argv=None):
parser = argparse.ArgumentParser(description='Print count of objects for a given collection.')
parser.add_argument('path', help="Nuxeo path to collection... | Update script to use new way of calling class. | Update script to use new way of calling class.
| Python | bsd-3-clause | barbarahui/nuxeo-calisphere,barbarahui/nuxeo-calisphere |
267c6591ef7ab3354b0965902585203fbfe04dee | pybot/http_client.py | pybot/http_client.py | import requests, json
from resources.urls import FACEBOOK_MESSAGES_POST_URL
class HttpClient():
"""
Client which excutes the call to
facebook's messenger api
"""
def submit_request(self, path, method, payload, completion):
assert len(path) > 0
path = self.get_api_url(pa... | import requests, json
from resources.urls import FACEBOOK_MESSAGES_POST_URL
class HttpClient():
"""
Client which excutes the call to
facebook's messenger api
"""
def submit_request(self, path, method, payload, completion):
assert len(path) > 0
path = self.get_api_url(pa... | Change wording to use response | Change wording to use response
| Python | mit | ben-cunningham/pybot,ben-cunningham/python-messenger-bot |
ed044a79347fcde11416c51a5c577fe2cc467050 | pyfr/readers/base.py | pyfr/readers/base.py | # -*- coding: utf-8 -*-
import uuid
from abc import ABCMeta, abstractmethod
class BaseReader(object):
__metaclass__ = ABCMeta
@abstractmethod
def __init__(self):
pass
@abstractmethod
def _to_raw_pyfrm(self):
pass
def to_pyfrm(self):
mesh = self._to_raw_pyfrm()
... | # -*- coding: utf-8 -*-
import re
import uuid
import itertools as it
from abc import ABCMeta, abstractmethod
import numpy as np
class BaseReader(object):
__metaclass__ = ABCMeta
@abstractmethod
def __init__(self):
pass
@abstractmethod
def _to_raw_pyfrm(self):
pass
def _op... | Add some simple optimizations into the mesh reader classes. | Add some simple optimizations into the mesh reader classes.
This yields a ~1.5% performance improvement.
| Python | bsd-3-clause | tjcorona/PyFR,tjcorona/PyFR,BrianVermeire/PyFR,tjcorona/PyFR,Aerojspark/PyFR,iyer-arvind/PyFR |
52f38cd00db200d0520062c27f0d305827edb7d2 | eventkit_cloud/auth/models.py | eventkit_cloud/auth/models.py | from django.contrib.auth.models import User,Group
from django.db import models
from django.contrib.postgres.fields import JSONField
from ..core.models import TimeStampedModelMixin, UIDMixin
class OAuth(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, blank=False)
identification = mod... | from django.contrib.auth.models import User,Group
from django.db import models
from django.contrib.postgres.fields import JSONField
from ..core.models import TimeStampedModelMixin, UIDMixin
class OAuth(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, blank=False)
identification = mod... | Revert "adding delete hook so the attached User object is deleted properly when and OAuth object is deleted." | Revert "adding delete hook so the attached User object is deleted properly when and OAuth object is deleted."
This reverts commit 4c77c36f447d104f492e320ca684e9a737f2b803.
| Python | bsd-3-clause | venicegeo/eventkit-cloud,venicegeo/eventkit-cloud,terranodo/eventkit-cloud,venicegeo/eventkit-cloud,venicegeo/eventkit-cloud,terranodo/eventkit-cloud,venicegeo/eventkit-cloud,terranodo/eventkit-cloud,terranodo/eventkit-cloud,venicegeo/eventkit-cloud |
20c52fdaf8f0eaefd9d857b37d89e7b429cc3013 | tests/functional/test_requests.py | tests/functional/test_requests.py | from tests.lib import run_pip, reset_env
def test_timeout():
reset_env()
result = run_pip("--timeout", "0.01", "install", "-vvv", "INITools",
expect_error=True,
)
assert "Could not fetch URL https://pypi.python.org/simple/INITools/: timed out" in result.stdout
assert "Could not fetch URL h... | def test_timeout(script):
result = script.pip("--timeout", "0.01", "install", "-vvv", "INITools",
expect_error=True,
)
assert "Could not fetch URL https://pypi.python.org/simple/INITools/: timed out" in result.stdout
assert "Could not fetch URL https://pypi.python.org/simple/: timed out" in resu... | Update requests test for the new funcargs | Update requests test for the new funcargs
| Python | mit | natefoo/pip,mujiansu/pip,harrisonfeng/pip,xavfernandez/pip,James-Firth/pip,nthall/pip,mujiansu/pip,graingert/pip,prasaianooz/pip,techtonik/pip,zorosteven/pip,rbtcollins/pip,ianw/pip,prasaianooz/pip,zorosteven/pip,ianw/pip,cjerdonek/pip,tdsmith/pip,habnabit/pip,ChristopherHogan/pip,yati-sagade/pip,alex/pip,zvezdan/pip,f... |
9297f2ffe0750ce4a40a35666ce9abb4bbfa487a | accounts/models.py | accounts/models.py | # coding: utf-8
from django.conf import settings
from django.db import models
from django.utils.translation import ugettext_lazy as _
class UserAccount(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL,
related_name='account')
class Meta:
verbose_nam... | # coding: utf-8
from django.conf import settings
from django.db import models
from django.utils.translation import ugettext_lazy as _
from registration.signals import user_activated
from django.dispatch import receiver
class UserAccount(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL,
... | Add signal hook for Account creation on completed registration | Add signal hook for Account creation on completed registration
| Python | agpl-3.0 | christophmeissner/volunteer_planner,volunteer-planner/volunteer_planner,alper/volunteer_planner,pitpalme/volunteer_planner,pitpalme/volunteer_planner,pitpalme/volunteer_planner,christophmeissner/volunteer_planner,flindenberg/volunteer_planner,juliabiro/volunteer_planner,klinger/volunteer_planner,volunteer-planner/volun... |
fb5e742e0b820af4a14052d9bd12053dcdc36d52 | examples/recurrent-phase.py | examples/recurrent-phase.py | #!/usr/bin/env python
import logging
import numpy as np
import lmj.cli
import lmj.nn
lmj.cli.enable_default_logging()
class Main(lmj.nn.Main):
def get_network(self):
return lmj.nn.recurrent.Autoencoder
def get_datasets(self):
t = np.linspace(0, 4 * np.pi, 256)
train = np.array([np.si... | #!/usr/bin/env python
import logging
import numpy as np
import lmj.cli
import lmj.nn
from matplotlib import pyplot as plt
lmj.cli.enable_default_logging()
T = 256
S = np.linspace(0, 4 * np.pi, T)
def sines(i=0):
return (0.7 * np.sin(S) + 0.3 * np.sin(i * S / 2)).reshape((T, 1))
class Main(lmj.nn.Main):
d... | Fix up recurrent phase test ! Add an output plot to show what the network does with a particular input. | Fix up recurrent phase test ! Add an output plot to show what the network does with a particular input.
| Python | mit | chrinide/theanets,devdoer/theanets,lmjohns3/theanets |
f3ad7f31784ea35da8655efa97ad3dd102e6dddb | django_bundles/management/commands/create_bundle_manifests.py | django_bundles/management/commands/create_bundle_manifests.py | import os
from django.core.management.base import BaseCommand
from django_bundles.core import get_bundles
class Command(BaseCommand):
args = "target_directory"
help = "Writes out files containing the list of input files for each bundle"
requires_model_validation = False
def handle(self, target_dire... | import os
from django.core.management.base import BaseCommand
from django_bundles.core import get_bundles
from django_bundles.processors import processor_pipeline
from django_bundles.utils.files import FileChunkGenerator
class Command(BaseCommand):
args = "target_directory"
help = "Writes out files containi... | Create processed versions of files for manifests | Create processed versions of files for manifests
This means if we have resources which are processed by django templates
then the processing will be done first and thus will yield for example a
valid javascript file
| Python | mit | sdcooke/django_bundles |
6427ef6e05e3add17533c0a86603943c85020eb6 | inonemonth/challenges/templatetags/challenges_extras.py | inonemonth/challenges/templatetags/challenges_extras.py | from django.template import Library
register = Library()
@register.filter
def get_representation_for_user(role, user_role):
if user_role.type == "juror":
if role.type == "clencher":
return "Clencher (de.rouck.robrecht@gmail.com)"
elif role.type == "juror":
if role == user_r... | from django.template import Library
register = Library()
@register.filter
def get_representation_for_user(role, user_role):
if user_role.type == "juror":
if role.type == "clencher":
return "{0} ({1})".format(role.type.capitalize(), role.user.email)
elif role.type == "juror":
... | Increase abstractness for one test method | Increase abstractness for one test method
| Python | mit | robrechtdr/inonemonth,robrechtdr/inonemonth,robrechtdr/inonemonth,robrechtdr/inonemonth |
b158de35c08aa78578f374f125884607468e67d1 | glance/registry/__init__.py | glance/registry/__init__.py | # Copyright 2010-2011 OpenStack Foundation
# 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... | # Copyright 2010-2011 OpenStack Foundation
# 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... | Improve help text of registry server opts | Improve help text of registry server opts
Partial-Bug: #1570946
Change-Id: Iad255d3ab5d96b91f897731f4f29cd804d6b1840
| Python | apache-2.0 | openstack/glance,rajalokan/glance,rajalokan/glance,stevelle/glance,openstack/glance,openstack/glance,stevelle/glance |
62c573fadad1b0268353c2dc21c35ac5b645052a | go/dashboard/tests/utils.py | go/dashboard/tests/utils.py | import json
from go.dashboard import DiamondashApiError, DiamondashApiClient
class FakeDiamondashApiClient(DiamondashApiClient):
def __init__(self):
self.requests = []
self.response = None
def get_requests(self):
return self.requests
def set_error_response(self, code, message):
... | import json
from go.dashboard import DiamondashApiError, DiamondashApiClient
class FakeDiamondashApiClient(DiamondashApiClient):
def __init__(self):
self.requests = []
self._response = None
@property
def response(self):
if isinstance(self._response, Exception):
raise ... | Add raw_request method for FakeDiamondashApiClient to correspond to the recently added DiamondashApiClient.raw_request() | Add raw_request method for FakeDiamondashApiClient to correspond to the recently added DiamondashApiClient.raw_request()
| Python | bsd-3-clause | praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go |
17a18f72e9e2a7df43d2dafe77a17bfe4777d7aa | avena/image.py | avena/image.py | #!/usr/bin/env python2
'''Read and write image files as NumPy arrays'''
from numpy import asarray, float32
from PIL import Image
from . import np
from . import utils
_DEFAULT_DTYPE = float32
_PIL_RGB = {
'R': 0,
'G': 1,
'B': 2,
}
def get_channels(img):
'''Return a list of channels of an image a... | #!/usr/bin/env python2
'''Read and write image files as NumPy arrays'''
from numpy import asarray, float32
from PIL import Image
from . import np
from . import utils
_DEFAULT_DTYPE = float32
_PIL_RGB = {
'R': 0,
'G': 1,
'B': 2,
}
def get_channels(img):
'''Return a list of channels of an image a... | Add an extension parameter to the save function. | Add an extension parameter to the save function.
| Python | isc | eliteraspberries/avena |
8810bd03df781e7ec20fcc2d0fcc7cbf423e9cdc | conda_kapsel/internal/py2_compat.py | conda_kapsel/internal/py2_compat.py | # -*- coding: utf-8 -*-
# ----------------------------------------------------------------------------
# Copyright © 2016, Continuum Analytics, Inc. All rights reserved.
#
# The full license is in the file LICENSE.txt, distributed with this software.
# -------------------------------------------------------------------... | # -*- coding: utf-8 -*-
# ----------------------------------------------------------------------------
# Copyright © 2016, Continuum Analytics, Inc. All rights reserved.
#
# The full license is in the file LICENSE.txt, distributed with this software.
# -------------------------------------------------------------------... | Add more assertions about types in environment | Add more assertions about types in environment
Trying to figure out why things are still failing on windows/py27
| Python | bsd-3-clause | conda/kapsel,conda/kapsel |
2c3ddc18477561f4880c2b857c4aa8a0f8478dfd | src/psycholinguistic_db/psycholinguistic_db_creator.py | src/psycholinguistic_db/psycholinguistic_db_creator.py | #!/usr/bin/env python
# Creates a CSV of psycholinguistic dictionary
# downloaded from web
# Headers
__author__ = 'Somsubhra Bairi'
__email__ = 'somsubhra.bairi@gmail.com'
# All imports
from logger import Logger
# The psycholinguistic database creator
class PsycholinguisticDbCreator:
# Constructor for the da... | #!/usr/bin/env python
# Creates a CSV of psycholinguistic dictionary
# downloaded from web
# Headers
__author__ = 'Somsubhra Bairi'
__email__ = 'somsubhra.bairi@gmail.com'
# All imports
from logger import Logger
from nltk import PorterStemmer
# The psycholinguistic database creator
class PsycholinguisticDbCreato... | Create the psycholinguistic_db according to our needs | Create the psycholinguistic_db according to our needs
| Python | mit | Somsubhra/Enrich,Somsubhra/Enrich,Somsubhra/Enrich |
f55a00cfd81f8f3c88aaaa5a4b3d63ceb4364a11 | books/views.py | books/views.py | from django.shortcuts import redirect
from django.views.decorators.csrf import csrf_exempt
from .models import BookIndex, Book
@csrf_exempt
def book_index(request):
page = BookIndex.objects.all()[0]
return redirect('/api/v2/pages/{}'.format(page.pk))
@csrf_exempt
def book_detail(request, slug):
page = B... | from django.shortcuts import redirect
from django.views.decorators.csrf import csrf_exempt
from .models import BookIndex, Book
@csrf_exempt
def book_index(request):
page = BookIndex.objects.all()[0]
return redirect('/api/v2/pages/{}'.format(page.pk))
@csrf_exempt
def book_detail(request, slug):
try:
... | Return book index page if book not found by slug | Return book index page if book not found by slug
| Python | agpl-3.0 | openstax/openstax-cms,Connexions/openstax-cms,openstax/openstax-cms,openstax/openstax-cms,openstax/openstax-cms,Connexions/openstax-cms |
bf36e307b13148d40e978ebb32151a3ea0e32cf9 | stampman/tests/test_api.py | stampman/tests/test_api.py | import unittest
from stampman.services import pool
class TestAPIEndpoint(unittest.TestCase):
pass
| import unittest
import json
import requests
from stampman import main
class TestAPIRoot(unittest.TestCase):
def setUp(self):
self._port = "8000"
self._path = "http://0.0.0.0"
main.app.config['TESTING'] = True
self._app = main.app.test_client()
def testGetJson(self):
r... | Add unit test for testing flask endpoint | Add unit test for testing flask endpoint
Test GET on the `/` endpoint
| Python | mit | thunderboltsid/stampman |
18ea019bd77d605c367265080aa40382399b324b | test/integration/ggrc/converters/test_import_update.py | test/integration/ggrc/converters/test_import_update.py | # Copyright (C) 2016 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
from integration.ggrc.converters import TestCase
from ggrc import models
class TestImportUpdates(TestCase):
""" Test importing of already existing objects """
def setUp(self):
TestCase.setUp(sel... | # Copyright (C) 2016 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
from integration.ggrc.converters import TestCase
from ggrc import models
class TestImportUpdates(TestCase):
""" Test importing of already existing objects """
def setUp(self):
TestCase.setUp(sel... | Use check response for import update tests | Use check response for import update tests
| Python | apache-2.0 | selahssea/ggrc-core,AleksNeStu/ggrc-core,plamut/ggrc-core,josthkko/ggrc-core,selahssea/ggrc-core,kr41/ggrc-core,andrei-karalionak/ggrc-core,j0gurt/ggrc-core,VinnieJohns/ggrc-core,kr41/ggrc-core,AleksNeStu/ggrc-core,josthkko/ggrc-core,josthkko/ggrc-core,AleksNeStu/ggrc-core,selahssea/ggrc-core,VinnieJohns/ggrc-core,j0gu... |
f9aae4320522af94dde78bac0c30e909ef4ef4e2 | blockbuster/bb_dbconnector_factory.py | blockbuster/bb_dbconnector_factory.py | import logging
import bb_dbconnector_pg
log = logging.getLogger('bb_log.' + __name__)
class DBConnectorInterfaceFactory:
def __init__(self):
pass
@staticmethod
def create():
return bb_dbconnector_pg.PostgresConnector() | import bb_dbconnector_pg
class DBConnectorInterfaceFactory:
def __init__(self):
pass
@staticmethod
def create():
return bb_dbconnector_pg.PostgresConnector() | Remove logger as not used in module | Remove logger as not used in module
| Python | mit | mattstibbs/blockbuster-server,mattstibbs/blockbuster-server |
7972c0fbaf8b46810dd36e0d824c341ea4234b47 | swampdragon_live/models.py | swampdragon_live/models.py | # -*- coding: utf-8 -*-
from django.db.models.signals import post_save, pre_delete
from django.contrib.contenttypes.models import ContentType
from django.dispatch import receiver
from .pushers import push_new_content_for_instance
from .pushers import push_new_content_for_queryset
@receiver(post_save)
def post_save_ha... | # -*- coding: utf-8 -*-
from django.db.models.signals import post_save, pre_delete
from django.contrib.contenttypes.models import ContentType
from django.dispatch import receiver
from .pushers import push_new_content_for_instance
from .pushers import push_new_content_for_queryset
@receiver(post_save)
def post_save_ha... | Optimize number of updates for queryset and instance listeners | Optimize number of updates for queryset and instance listeners
Only push additions to queryset listeners, not instance changes.
Only push changes to instance listeners, not queryset additions.
| Python | mit | mback2k/swampdragon-live,mback2k/swampdragon-live |
f14df4ae507f3161f00ac28648bd53f2bb0bd7c3 | collect_district_court_case_details.py | collect_district_court_case_details.py | import datetime
import pymongo
import os
import sys
import time
from courtreader import readers
# Connect to database
client = pymongo.MongoClient(os.environ['DISTRICT_DB'])
db = client.va_district_court_cases
# Connect to District Court Reader
reader = readers.DistrictCourtReader()
reader.connect()
# Fill in cases
... | import boto.utils
import datetime
import pymongo
import os
import sys
import time
import uuid
from courtreader import readers
# Connect to database
client = pymongo.MongoClient(os.environ['DISTRICT_DB'])
db = client.va_district_court_cases
# Connect to District Court Reader
reader = readers.DistrictCourtReader()
read... | Save scraper settings to database | Save scraper settings to database
This is the first step in allowing multiple processes to run on
different servers. Coming in the next commit!
| Python | mit | bschoenfeld/va-court-scraper,bschoenfeld/va-court-scraper |
1b70aee665720ce10e2e0437fb462745adbd6799 | changes/api/serializer/models/task.py | changes/api/serializer/models/task.py | from changes.api.serializer import Serializer, register
from changes.models import Task
@register(Task)
class TaskSerializer(Serializer):
def serialize(self, instance, attrs):
return {
'id': instance.id.hex,
'objectID': instance.task_id,
'parentObjectID': instance.paren... | from changes.api.serializer import Serializer, register
from changes.models import Task
@register(Task)
class TaskSerializer(Serializer):
def serialize(self, instance, attrs):
if instance.data:
args = instance.data.get('kwargs') or {}
else:
args = {}
return {
... | Fix args when Task.data is empty | Fix args when Task.data is empty
| Python | apache-2.0 | bowlofstew/changes,bowlofstew/changes,bowlofstew/changes,dropbox/changes,wfxiang08/changes,dropbox/changes,bowlofstew/changes,wfxiang08/changes,dropbox/changes,wfxiang08/changes,wfxiang08/changes,dropbox/changes |
0372de11f91e0018eb122f9a6543ecf7cc9e086b | parliament/search/management/commands/consume_indexing_queue.py | parliament/search/management/commands/consume_indexing_queue.py | import itertools
import logging
from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
from haystack import site
import pysolr
logger = logging.getLogger(__name__)
class Command(BaseCommand):
help = "Runs any queued-up search indexing tasks."
def handle(self, **o... | import itertools
import logging
from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
from haystack import site
import pysolr
logger = logging.getLogger(__name__)
class Command(BaseCommand):
help = "Runs any queued-up search indexing tasks."
def handle(self, **o... | Use pysolr instead of haystack in indexing job | Use pysolr instead of haystack in indexing job
| Python | agpl-3.0 | twhyte/openparliament,rhymeswithcycle/openparliament,litui/openparliament,rhymeswithcycle/openparliament,litui/openparliament,rhymeswithcycle/openparliament,litui/openparliament,twhyte/openparliament,twhyte/openparliament |
ee82b77f562ee1d49c2fc724a3fc58b101c0dd2b | src/devilry_qualifiesforexam/devilry_qualifiesforexam/urls.py | src/devilry_qualifiesforexam/devilry_qualifiesforexam/urls.py | from django.conf.urls import patterns, url, include
from django.contrib.auth.decorators import login_required
from django.views.i18n import javascript_catalog
from django.views.decorators.csrf import csrf_protect, ensure_csrf_cookie
from devilry_settings.i18n import get_javascript_catalog_packages
from .views import ... | from django.conf.urls import patterns, url, include
from django.contrib.auth.decorators import login_required
from django.views.i18n import javascript_catalog
from django.views.decorators.csrf import csrf_protect, ensure_csrf_cookie
from devilry_settings.i18n import get_javascript_catalog_packages
from .views import ... | Remove period id from app url. | devilry_qualfiesforexam: Remove period id from app url.
| Python | bsd-3-clause | devilry/devilry-django,devilry/devilry-django,devilry/devilry-django,devilry/devilry-django |
edbcfbf83ab79fff7de00c7a6310c9fceb17df91 | accelerator/migrations/0099_update_program_model.py | accelerator/migrations/0099_update_program_model.py | # Generated by Django 2.2.28 on 2022-04-20 13:05
from django.db import (
migrations,
models,
)
class Migration(migrations.Migration):
dependencies = [
('accelerator', '0098_update_startup_update_20220408_0441'),
]
operations = [
migrations.AddField(
model_name='progr... | # Generated by Django 2.2.28 on 2022-04-20 13:05
import sorl.thumbnail.fields
from django.db import (
migrations,
models,
)
class Migration(migrations.Migration):
dependencies = [
('accelerator', '0098_update_startup_update_20220408_0441'),
]
operations = [
migrations.AddField(
... | Fix image field import and migration | [AC-9452] Fix image field import and migration
| Python | mit | masschallenge/django-accelerator,masschallenge/django-accelerator |
3f2c13ecc64c84b51ecc5867004b9cbc32e375ac | Discord/utilities/errors.py | Discord/utilities/errors.py |
from discord.ext.commands.errors import CommandError
class NotServerOwner(CommandError):
'''Not Server Owner'''
pass
class VoiceNotConnected(CommandError):
'''Voice Not Connected'''
pass
class PermittedVoiceNotConnected(VoiceNotConnected):
'''Permitted, but Voice Not Connected'''
pass
class NotPermittedVoice... |
from discord.ext.commands.errors import CommandError
class NotServerOwner(CommandError):
'''Not Server Owner'''
pass
class VoiceNotConnected(CommandError):
'''Voice Not Connected'''
pass
class PermittedVoiceNotConnected(VoiceNotConnected):
'''Permitted, but Voice Not Connected'''
pass
class NotPermittedVoice... | Remove Audio Not Playing error | [Discord] Remove Audio Not Playing error
| Python | mit | Harmon758/Harmonbot,Harmon758/Harmonbot |
6dfa381b26948b97b7abc3de9f1a02618fd5ad0f | src/geoserver/style.py | src/geoserver/style.py | from geoserver.support import ResourceInfo, atom_link
class Style(ResourceInfo):
def __init__(self,catalog, node):
self.catalog = catalog
self.name = node.find("name").text
self.href = atom_link(node)
self.update()
def update(self):
ResourceInfo.update(self)
self.name = self.metadata.f... | from geoserver.support import ResourceInfo, atom_link
import re
class Style(ResourceInfo):
def __init__(self,catalog, node):
self.catalog = catalog
self.name = node.find("name").text
self.href = atom_link(node)
self.update()
def update(self):
ResourceInfo.update(self)
self.name = self.... | Add body_href method for getting a public url for a Style's body. | Add body_href method for getting a public url for a Style's body.
| Python | mit | cristianzamar/gsconfig,scottp-dpaw/gsconfig,boundlessgeo/gsconfig,Geode/gsconfig,afabiani/gsconfig,garnertb/gsconfig.py |
115dbdecabc74f4f08d07099a4997860ebe5278b | telemetry/telemetry/core/platform/profiler/android_screen_recorder_profiler.py | telemetry/telemetry/core/platform/profiler/android_screen_recorder_profiler.py | # Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import os
import subprocess
from telemetry.core import util
from telemetry.core.backends.chrome import android_browser_finder
from telemetry.core.platform i... | # Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import os
import subprocess
from telemetry.core import util
from telemetry.core.backends.chrome import android_browser_finder
from telemetry.core.platform i... | Fix screen recording with multiple connected devices | telemetry: Fix screen recording with multiple connected devices
Make it possible to use the Android screen recording profiler with
multiple connected devices. Only the screen on the device that is
actually running the telemetry test will get recorded.
BUG=331435
TEST=tools/perf/run_benchmark smoothness.key_mobile_sit... | Python | bsd-3-clause | SummerLW/Perf-Insight-Report,catapult-project/catapult-csm,catapult-project/catapult,catapult-project/catapult-csm,catapult-project/catapult-csm,sahiljain/catapult,benschmaus/catapult,catapult-project/catapult-csm,SummerLW/Perf-Insight-Report,catapult-project/catapult-csm,benschmaus/catapult,sahiljain/catapult,SummerLW... |
c76734ea034f2a48de0eab995c5db5667086e0c8 | common/util/log.py | common/util/log.py | import sublime
def universal_newlines(string):
return string.replace('\r\n', '\n').replace('\r', '\n')
def panel(message, run_async=True):
message = universal_newlines(str(message))
view = sublime.active_window().active_view()
if run_async:
sublime.set_timeout_async(
lambda: view... | import re
import sublime
ANSI_ESCAPE_RE = re.compile(r'\x1B\[[0-?]*[ -/]*[@-~]')
def normalize(string):
return ANSI_ESCAPE_RE.sub('', string.replace('\r\n', '\n').replace('\r', '\n'))
def panel(message, run_async=True):
message = normalize(str(message))
view = sublime.active_window().active_view()
... | Remove ANSI escape sequences from panel output | Remove ANSI escape sequences from panel output
| Python | mit | divmain/GitSavvy,divmain/GitSavvy,divmain/GitSavvy |
a610faf9d64c062ed2dd44a818acc0d12d1f6e0b | django_evolution/compat/picklers.py | django_evolution/compat/picklers.py | """Picklers for working with serialized data."""
from __future__ import unicode_literals
import pickle
class DjangoCompatUnpickler(pickle.Unpickler):
"""Unpickler compatible with changes to Django class/module paths.
This provides compatibility across Django versions for various field types,
updating r... | """Picklers for working with serialized data."""
from __future__ import unicode_literals
import pickle
from django_evolution.compat.datastructures import OrderedDict
class SortedDict(dict):
"""Compatibility for unpickling a SortedDict.
Old signatures may use an old Django ``SortedDict`` structure, which d... | Support loading pickled data referencing SortedDict. | Support loading pickled data referencing SortedDict.
Django used to provide a class called `SortedDict`, which has long been
deprecated in favor of Python's own `OrderedDict`. However, due to the
way that pickling works, older signatures would still attempt to loading
a `SortedDict` class.
This change adds a compatib... | Python | bsd-3-clause | beanbaginc/django-evolution |
4640b75fdb794e29cb6e7bdc03a6697d8f9f3483 | emu/processes/wps_ultimate_question.py | emu/processes/wps_ultimate_question.py | from pywps import Process, LiteralOutput
from pywps.app.Common import Metadata
class UltimateQuestion(Process):
def __init__(self):
inputs = []
outputs = [LiteralOutput('answer', 'Answer to Ultimate Question', data_type='string')]
super(UltimateQuestion, self).__init__(
self._... | from pywps import Process, LiteralOutput
from pywps.app.Common import Metadata
class UltimateQuestion(Process):
def __init__(self):
inputs = []
outputs = [LiteralOutput('answer', 'Answer to Ultimate Question', data_type='string')]
super(UltimateQuestion, self).__init__(
self._... | Make ultimate question ever more ultimate | Make ultimate question ever more ultimate
| Python | apache-2.0 | bird-house/emu |
bf0043ac102cc9eddf03c8db493ae1a985c6a30a | src/nyc_trees/apps/home/urls.py | src/nyc_trees/apps/home/urls.py | # -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from django.conf.urls import patterns, url, include
from apps.home import routes as r
urlpatterns = patterns(
'',
url(r'^$', r.home_page, name='home_page'),
url(r'^progr... | # -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from django.conf.urls import patterns, url, include
from apps.home import routes as r
urlpatterns = patterns(
'',
url(r'^$', r.home_page, name='home_page'),
url(r'^progr... | Fix trailing slash 404 for flat pages and co | Fix trailing slash 404 for flat pages and co
By modifying the URL, flatpage requests without a trailing slash will
always fail, triggering the redirect provided by `APPEND_SLASH`.
This is important because urls that share a common endpoint path were
404ing on a flatpage not found when not constructed with a slash.
| Python | agpl-3.0 | azavea/nyc-trees,maurizi/nyc-trees,azavea/nyc-trees,kdeloach/nyc-trees,kdeloach/nyc-trees,maurizi/nyc-trees,azavea/nyc-trees,maurizi/nyc-trees,kdeloach/nyc-trees,RickMohr/nyc-trees,azavea/nyc-trees,RickMohr/nyc-trees,kdeloach/nyc-trees,RickMohr/nyc-trees,azavea/nyc-trees,maurizi/nyc-trees,kdeloach/nyc-trees,RickMohr/ny... |
cebe1c3b72eb9e0fd4114d5664e269a73bdc06a1 | examples/many_pairwise_correlations.py | examples/many_pairwise_correlations.py | """
Plotting a diagonal correlation matrix
======================================
_thumb: .3, .6
"""
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
sns.set(style="white")
# Generate a large random dataset
rs = np.random.RandomState(33)
d = rs.normal(size=(30, 100))
# Compute the correlatio... | """
Plotting a diagonal correlation matrix
======================================
_thumb: .3, .6
"""
from string import letters
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
sns.set(style="white")
# Generate a large random dataset
rs = np.random.RandomState(33)
d = pd.D... | Use dataframe to show how semantic information is used | Use dataframe to show how semantic information is used
| Python | bsd-3-clause | mia1rab/seaborn,muku42/seaborn,JWarmenhoven/seaborn,mwaskom/seaborn,drewokane/seaborn,jat255/seaborn,phobson/seaborn,bsipocz/seaborn,uhjish/seaborn,arokem/seaborn,tim777z/seaborn,q1ang/seaborn,clarkfitzg/seaborn,dhimmel/seaborn,olgabot/seaborn,Lx37/seaborn,anntzer/seaborn,kyleam/seaborn,oesteban/seaborn,sinhrks/seaborn... |
5fe71408c740697ebe0b268e9fbac93f5932ef63 | froide/foirequest/search_indexes.py | froide/foirequest/search_indexes.py | from haystack import indexes
from haystack import site
from foirequest.models import FoiRequest
class FoiRequestIndex(indexes.SearchIndex):
text = indexes.EdgeNgramField(document=True, use_template=True)
title = indexes.CharField(model_attr='title')
description = indexes.CharField(model_attr='description... | from haystack import indexes
from haystack import site
from foirequest.models import FoiRequest
class FoiRequestIndex(indexes.SearchIndex):
text = indexes.EdgeNgramField(document=True, use_template=True)
title = indexes.CharField(model_attr='title')
description = indexes.CharField(model_attr='description... | Add summary to foirequest search | Add summary to foirequest search | Python | mit | ryankanno/froide,stefanw/froide,LilithWittmann/froide,LilithWittmann/froide,stefanw/froide,fin/froide,fin/froide,stefanw/froide,catcosmo/froide,stefanw/froide,CodeforHawaii/froide,okfse/froide,LilithWittmann/froide,ryankanno/froide,catcosmo/froide,CodeforHawaii/froide,ryankanno/froide,catcosmo/froide,ryankanno/froide,c... |
99aac92ca2a4958b7daff7b64d52c0e58db3554c | opal/tests/test_core_views.py | opal/tests/test_core_views.py | """
Unittests for opal.core.views
"""
from opal.core import test
from opal.core import views
class SerializerTestCase(test.OpalTestCase):
def test_serializer_default_will_super(self):
s = views.OpalSerializer()
with self.assertRaises(TypeError):
s.default(None)
| """
Unittests for opal.core.views
"""
import warnings
from opal.core import test
from opal.core import views
class SerializerTestCase(test.OpalTestCase):
def test_serializer_default_will_super(self):
s = views.OpalSerializer()
with self.assertRaises(TypeError):
s.default(None)
clas... | Add test for warn spelling of build_json_response | Add test for warn spelling of build_json_response
| Python | agpl-3.0 | khchine5/opal,khchine5/opal,khchine5/opal |
a0e432b0ac31ed74256197b1d5df8b6f8a0987db | product/models.py | product/models.py | from django.db import models
from django.utils.translation import pgettext as _
from django_prices.models import PriceField
from satchless.util.models import Subtyped
from satchless.item import ItemRange
from mptt.models import MPTTModel
class Category(MPTTModel):
name = models.CharField(_('Category field', 'nam... | from django.db import models
from django.utils.safestring import mark_safe
from django.utils.translation import pgettext as _
from django_prices.models import PriceField
from mptt.models import MPTTModel
from satchless.item import ItemRange
from satchless.util.models import Subtyped
from unidecode import unidecode
impo... | Replace slug field with get_slug function | Replace slug field with get_slug function
| Python | bsd-3-clause | laosunhust/saleor,mociepka/saleor,paweltin/saleor,mociepka/saleor,jreigel/saleor,taedori81/saleor,UITools/saleor,UITools/saleor,spartonia/saleor,car3oon/saleor,Drekscott/Motlaesaleor,UITools/saleor,HyperManTT/ECommerceSaleor,paweltin/saleor,maferelo/saleor,dashmug/saleor,rodrigozn/CW-Shop,laosunhust/saleor,avorio/saleo... |
c08013dc2fc32582e8636d84be3e2f68dafe11a0 | controller.py | controller.py | """NM-Controller accounts are used to provide secure access to the XMLRPC API. They are normal Unix accounts with a shell that tunnels XMLRPC requests to the API server."""
import accounts
import logger
import tools
class Controller(accounts.Account):
SHELL = '/usr/bin/forward_api_calls' # tunneling shell
... | """NM-Controller accounts are used to provide secure access to the XMLRPC API. They are normal Unix accounts with a shell that tunnels XMLRPC requests to the API server."""
import accounts
import logger
import tools
class Controller(accounts.Account):
SHELL = '/usr/bin/forward_api_calls' # tunneling shell
... | Change to Controller from Delegate shell | Change to Controller from Delegate shell
| Python | bsd-3-clause | dreibh/planetlab-lxc-nodemanager,planetlab/NodeManager,planetlab/NodeManager,planetlab/NodeManager,dreibh/planetlab-lxc-nodemanager,planetlab/NodeManager,dreibh/planetlab-lxc-nodemanager |
21f27eecae407e3baa8f55effd7b19ef2fa9ca6d | jug.py | jug.py | from store import create_directories
import options
import task
def parse_jugfile():
import jugfile
def print_tasks():
for i,t in enumerate(task.alltasks):
print 'Task %s: %s' % (i,t.name)
def execute_tasks():
tasks = task.alltasks
while tasks:
ready = [t for t in tasks if t.can_run()... | from collections import defaultdict
from store import create_directories
import options
import task
import jugfile
def print_tasks():
task_counts = defaultdict(int)
for t in task.alltasks:
task_counts[t.name] += 1
for tnc in task_counts.items():
print 'Task %s: %s' % tnc
task_names = set(t... | Print a little summary when you're done | Print a little summary when you're done
| Python | mit | unode/jug,unode/jug,luispedro/jug,luispedro/jug |
9f9d78fd7a5011f24b5e12249f1276010293d877 | bin/upload_version.py | bin/upload_version.py | #!python
import os
import sys
import json
import requests
if __name__ == '__main__':
version = sys.argv[1]
filepath = sys.argv[2]
filename = filepath.split('/')[-1]
github_token = os.environ['GITHUB_TOKEN']
auth = (github_token, 'x-oauth-basic')
commit_sha = os.environ['CIRCLE_SHA1']
params = json.dumps... | #!python
import os
import sys
import json
import requests
import subprocess
def capture_output(command):
proc = subprocess.Popen(command, stdout=subprocess.PIPE)
return proc.stdout.read()
if __name__ == '__main__':
version = sys.argv[1]
filepath = sys.argv[2]
filename = filepath.split('/')[-1]
... | Update upload script to include checksums | Update upload script to include checksums
| Python | bsd-2-clause | useabode/redash,pubnative/redash,rockwotj/redash,chriszs/redash,getredash/redash,44px/redash,hudl/redash,moritz9/redash,imsally/redash,getredash/redash,alexanderlz/redash,akariv/redash,rockwotj/redash,alexanderlz/redash,44px/redash,guaguadev/redash,vishesh92/redash,imsally/redash,pubnative/redash,easytaxibr/redash,Ever... |
b295e3e64367073550ceb00faa72e6564f08dd55 | pytest_cookies.py | pytest_cookies.py | # -*- coding: utf-8 -*-
import pytest
from cookiecutter.main import cookiecutter
class Cookies(object):
"""Class to provide convenient access to the cookiecutter API."""
error = None
project = None
def __init__(self, template, output_dir):
self._template = template
self._output_dir ... | # -*- coding: utf-8 -*-
import pytest
from cookiecutter.main import cookiecutter
class Cookies(object):
"""Class to provide convenient access to the cookiecutter API."""
exception = None
exit_code = 0
project = None
def __init__(self, template, output_dir):
self._template = template
... | Handle SystemExit errors and add exit_code | Handle SystemExit errors and add exit_code
| Python | mit | hackebrot/pytest-cookies |
4baa59fd3ea90b604a8cdb5f4daf9ddb61f2e34a | aybu/manager/cli/task.py | aybu/manager/cli/task.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Copyright 2010 Asidev s.r.l.
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 app... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Copyright 2010 Asidev s.r.l.
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 app... | Fix error on connection failures | Fix error on connection failures
| Python | apache-2.0 | asidev/aybu-manager-cli,asidev/aybu-manager-cli |
f696e320d66f375779692ec073f15d3d6d466059 | edx_data_research/parsing/parse_sql.py | edx_data_research/parsing/parse_sql.py | import subprocess
from edx_data_research.parsing.parse import Parse
class SQL(Parse):
def __init__(self, args):
super(SQL, self).__init__(args)
self._collections = args.collection
self.sql_file = args.sql_file
def migrate(self):
subprocess.check_call(['mongoimport', '-d', sel... | import subprocess
from edx_data_research.parsing.parse import Parse
class SQL(Parse):
def __init__(self, args):
super(SQL, self).__init__(args)
self._collections = args.collection
self.sql_file = args.sql_file
def migrate(self):
subprocess.check_call(['mongoimport', '-d', sel... | Update mongo import of files to drop existing collection first | Update mongo import of files to drop existing collection first
| Python | mit | McGillX/edx_data_research,McGillX/edx_data_research,McGillX/edx_data_research |
8a44705413d3a01e897d4a922e7c1383b60a2927 | plugins/VersionUpgrade/VersionUpgrade21to22/__init__.py | plugins/VersionUpgrade/VersionUpgrade21to22/__init__.py | # Copyright (c) 2016 Ultimaker B.V.
# Cura is released under the terms of the AGPLv3 or higher.
from . import VersionUpgrade21to22
from UM.i18n import i18nCatalog
catalog = i18nCatalog("cura")
def getMetaData():
return {
"plugin": {
"name": catalog.i18nc("@label", "Version Upgrade 2.1 to 2.2"... | # Copyright (c) 2016 Ultimaker B.V.
# Cura is released under the terms of the AGPLv3 or higher.
from . import VersionUpgrade21to22
from UM.i18n import i18nCatalog
catalog = i18nCatalog("cura")
def getMetaData():
return {
"plugin": {
"name": catalog.i18nc("@label", "Version Upgrade 2.1 to 2.2"... | Update metadata with dynamic config types | Update metadata with dynamic config types
After settings rework, we decided to make the upgrade plug-ins define their own configuration types. This is basically the definition for these configuration types. Only the get_version function is not yet implemented.
Contributes to issue CURA-844.
| Python | agpl-3.0 | Curahelper/Cura,ynotstartups/Wanhao,hmflash/Cura,totalretribution/Cura,hmflash/Cura,Curahelper/Cura,senttech/Cura,fieldOfView/Cura,senttech/Cura,fieldOfView/Cura,totalretribution/Cura,ynotstartups/Wanhao |
3e2c7ca2147b28403761cf57dad6d9173a28dc3d | docs/tasks.py | docs/tasks.py | import invoke
import livereload
import shutil
server = livereload.Server()
@invoke.task
def clean():
shutil.rmtree('./build')
@invoke.task(pre=[clean])
def build():
invoke.run('sphinx-build ./source ./build', pty=True)
@invoke.task(pre=[build])
def serve():
server.watch('./source/*', build)
serve... | import invoke
import livereload
import shutil
server = livereload.Server()
@invoke.task
def clean():
shutil.rmtree('./build')
@invoke.task(pre=[clean])
def build():
invoke.run('sphinx-build ./source ./build', pty=True)
@invoke.task(pre=[build])
def serve():
server.watch('../reqon/', build)
server... | Fix directory watching when serving the docs. | Fix directory watching when serving the docs.
| Python | mit | dmpayton/reqon |
808434912ceb176793a559464f767e2eb52b889d | sanic_limiter/util.py | sanic_limiter/util.py | """
"""
def get_remote_address(request):
"""
:param: request: request object of sanic
:return: the ip address of given request (or 127.0.0.1 if none found)
"""
return request.ip[0] or '127.0.0.1'
| """
"""
def get_remote_address(request):
"""
:param: request: request object of sanic
:return: the ip address of given request (or 127.0.0.1 if none found)
"""
return request.remote_addr or request.ip
| Fix IP keyfunc for reverse proxies | Fix IP keyfunc for reverse proxies
| Python | mit | bohea/sanic-limiter |
093c8ac40ba6154ee4a3d3d1430e5b05e68b2e9e | timpani/webserver/webhelpers.py | timpani/webserver/webhelpers.py | import flask
from .. import auth
import urllib.parse
def checkForSession():
if "uid" in flask.session:
session = auth.validateSession(flask.session["uid"])
if session != None:
return session
return None
def redirectAndSave(path):
flask.session["donePage"] = urllib.parse.urlparse(flask.request.url).path
re... | import flask
from .. import auth
import urllib.parse
def checkForSession():
if "uid" in flask.session:
session = auth.validateSession(flask.session["uid"])
if session != None:
return session
return None
def redirectAndSave(path):
flask.session["donePage"] = urllib.parse.urlparse(flask.request.url).path
re... | Fix legacy return in redirectAndSave | Fix legacy return in redirectAndSave
| Python | mit | ollien/Timpani,ollien/Timpani,ollien/Timpani |
788ca6bbd25bcdb55dc92739e7d08b201344b10b | tools/glidein_top.py | tools/glidein_top.py | #!/bin/env python
#
# glidein_top
#
# Execute a top command in the same glidein as the user job
#
# Usage:
# glidein_top.py <cluster>.<process> [-name <schedd_name>] [-pool <pool_name> ] [-timeout <nr secs>
#
import os
import stat
import sys
sys.path.append("lib")
sys.path.append("../lib")
import glideinMonitor
def... | #!/bin/env python
#
# glidein_top.py
#
# Description:
# Execute a top command on a condor job
#
# Usage:
# glidein_top.py <cluster>.<process> [-name <schedd_name>] [-pool <pool_name> ] [-timeout <nr secs>]
#
# Author:
# Igor Sfiligoi (May 2007)
#
# License:
# Fermitools
#
import sys,os.path
sys.path.append(os.pa... | Change rel paths into abspaths and use helper module | Change rel paths into abspaths and use helper module
| Python | bsd-3-clause | holzman/glideinwms-old,bbockelm/glideinWMS,holzman/glideinwms-old,bbockelm/glideinWMS,holzman/glideinwms-old,bbockelm/glideinWMS,bbockelm/glideinWMS |
85d800d9979fa122e0888af48c2e6a697f9da458 | test/test_sc2replay.py | test/test_sc2replay.py | #!/usr/bin/env python
# coding: utf-8
import os
import unittest
from adjutant import SC2Replay
TEST_DIR = os.path.realpath(os.path.dirname(__file__)) + '/'
class TestSC2Replay(unittest.TestCase):
def setUp(self):
self.replay = SC2Replay(TEST_DIR + 'test.SC2Replay')
def test_init(self):
self... | #!/usr/bin/env python
# coding: utf-8
import os
import unittest
from adjutant import SC2Replay
TEST_DIR = os.path.realpath(os.path.dirname(__file__)) + '/'
class TestSC2Replay(unittest.TestCase):
def setUp(self):
self.replay = SC2Replay(TEST_DIR + 'test.SC2Replay')
def test_init(self):
self... | Add a small test for init with a file arg. | Add a small test for init with a file arg.
| Python | bsd-2-clause | eagleflo/adjutant |
295e356af1e4422fd8e2af9a44b46f5976a5ec39 | tools/test_sneeze.py | tools/test_sneeze.py |
import os
from tempfile import mkdtemp
from shutil import rmtree
from nipy.testing import *
from sneeze import find_pkg, run_nose
import_strings = ["from nipype.interfaces.afni import To3d",
"from nipype.interfaces import afni",
"import nipype.interfaces.afni"]
def test_from_name... |
import os
from tempfile import mkdtemp
from shutil import rmtree
from nipy.testing import *
from sneeze import find_pkg, run_nose
import_strings = ["from nipype.interfaces.afni import To3d, ThreeDRefit",
"from nipype.interfaces import afni",
"import nipype.interfaces.afni",
... | Add more tests for sneeze. | Add more tests for sneeze. | Python | bsd-3-clause | nipy/nipy-labs,alexis-roche/niseg,nipy/nireg,alexis-roche/nipy,alexis-roche/nipy,alexis-roche/nireg,arokem/nipy,bthirion/nipy,alexis-roche/register,nipy/nireg,bthirion/nipy,alexis-roche/nipy,bthirion/nipy,alexis-roche/nipy,arokem/nipy,alexis-roche/niseg,arokem/nipy,bthirion/nipy,arokem/nipy,alexis-roche/register,alexis... |
1f9486cff230beae00e5417d6ad2b1ba28526339 | pson/pson.py | pson/pson.py | import json
from pprint import pprint
def pathparser(path, separator="."):
return path.split(separator)
def pathquery(pson, path, separator=".", missing=None, iterate=True):
if isinstance(path,str) or isinstance(path, unicode):
path = pathparser(path, separator=separator)
coun... | import json
from pprint import pprint
def pathparser(path, separator="."):
return path.split(separator)
def pathquery(pson, path, separator=".", missing=None, iterate=True):
if isinstance(path,str) or isinstance(path, unicode):
path = pathparser(path, separator=separator)
counter = 0
for toke... | Add consistent 4 space indentation | Add consistent 4 space indentation
Applied 4 space indentation all along the main pson.py file.
| Python | mit | imranghory/pson |
da6e9416e12ce71cd3f23ded9bd75dccc62d26fe | fcn/config.py | fcn/config.py | import os.path as osp
def get_data_dir():
this_dir = osp.dirname(osp.abspath(__file__))
return osp.realpath(osp.join(this_dir, '../data'))
def get_logs_dir():
this_dir = osp.dirname(osp.abspath(__file__))
return osp.realpath(osp.join(this_dir, '../logs'))
| import os.path as osp
def get_data_dir():
this_dir = osp.dirname(osp.abspath(__file__))
return osp.realpath(osp.join(this_dir, '_data'))
| Move data directory in package | Move data directory in package
| Python | mit | wkentaro/fcn |
945e978d3249762da9a47300cb43d86966de0354 | wanikani2anki.py | wanikani2anki.py | #! /usr/bin/env python3
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v2.0. If a copy of the MPL was not distributed with this
# file, you can obtain one at http://mozilla.org/MPL/2.0/.
import json
from urllib.request import *
headers = {}
with open('apikey.txt', 'r') as f:
apike... | #! /usr/bin/env python3
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v2.0. If a copy of the MPL was not distributed with this
# file, you can obtain one at http://mozilla.org/MPL/2.0/.
import json
from urllib.error import *
from urllib.request import *
headers = {}
with open('apikey... | Add error handling for GET request. | Add error handling for GET request.
| Python | mpl-2.0 | holocronweaver/wanikani2anki,holocronweaver/wanikani2anki,holocronweaver/wanikani2anki |
393743e391575d6cf4a3bfffb4f53cfa0848c49e | tests/test_donemail.py | tests/test_donemail.py | from mock import Mock
import pytest
import smtplib
from donemail import donemail
BOB = 'bob@example.com'
@pytest.fixture(autouse=True)
def monkeypatch_send_email(monkeypatch):
monkeypatch.setattr('smtplib.SMTP', Mock())
def test_context_manager():
assert_num_emails(0)
with donemail(BOB):
pass
... | from mock import ANY, Mock
import pytest
import smtplib
from donemail import donemail
BOB = 'bob@example.com'
@pytest.fixture(autouse=True)
def monkeypatch_send_email(monkeypatch):
mock_smtp_class = Mock()
mock_smtp_class.return_value = Mock()
monkeypatch.setattr('smtplib.SMTP', mock_smtp_class)
def t... | Check that test emails are sent to BOB | Check that test emails are sent to BOB
| Python | mit | alexandershov/donemail |
634ae735db61ebb211b9e3159ca4dac7861e5553 | cluster/update_jobs.py | cluster/update_jobs.py | from django.contrib.auth.models import User
from models import Job
from interface import get_all_jobs
def run_all():
for user in User.objects.all():
creds = user.credentials.all()
for i, cluster in enumerate(get_all_jobs(user)):
cred = creds[i]
jobs = {}
for jo... | from django.contrib.auth.models import User
from models import Job
from interface import get_all_jobs
def run_all():
for user in User.objects.all():
creds = user.credentials.all()
for i, cluster in enumerate(get_all_jobs(user)):
cred = creds[i]
jobs = {}
jobids... | Add updating of jobs if their state is now unknown | Add updating of jobs if their state is now unknown
| Python | mit | crcollins/chemtools-webapp,crcollins/chemtools-webapp,crcollins/chemtools-webapp,crcollins/chemtools-webapp,crcollins/chemtools-webapp |
27e2c86641bac1b2083a36d0eaf84e79553c39ce | pycom/objects.py | pycom/objects.py | # encoding: utf-8
### Attribute Wrapper
class AttrWrapper(object):
attrs = []
def __setattr__(self, name, value):
if name not in self.attrs:
raise AttributeError("'%s' is not supported" % name)
object.__setattr__(self, name, value)
def __repr__(self):
attrs = []
... | # encoding: utf-8
import six
### Attribute Wrapper
class AttrWrapper(object):
attrs = []
def __setattr__(self, name, value):
if name not in self.attrs:
raise AttributeError("'%s' is not supported" % name)
object.__setattr__(self, name, value)
def __repr__(self):
attrs ... | Fix a bug about the function, 'val'. | Fix a bug about the function, 'val'.
| Python | mit | xgfone/xutils,xgfone/pycom |
23ab67f74fc7c09310638529ccf804ec2271fd6c | pynads/writer.py | pynads/writer.py | from .monad import Monad
from .functor import fmap
class Writer(Monad):
"""Stores a value as well as a log of events that have transpired
with the value.
"""
def __init__(self, v, log):
self.v = v
if not isinstance(log, list):
self.log = [log]
else:
self... | from .utils import _iter_but_not_str_or_map
from .monad import Monad
from .functor import fmap
class Writer(Monad):
"""Stores a value as well as a log of events that have transpired
with the value.
"""
__slots__ = ('v', 'log')
def __init__(self, v, log):
self.v = v
if _iter_but_no... | Use utils._iter_but_not_str_or_map in Writer log creation. | Use utils._iter_but_not_str_or_map in Writer log creation.
| Python | mit | justanr/pynads |
2a06886077c05e1bfae7c28a09cf3489da6e450a | heat/utils.py | heat/utils.py | class LazyPluggable(object):
"""A pluggable backend loaded lazily based on some value."""
def __init__(self, pivot, **backends):
self.__backends = backends
self.__pivot = pivot
self.__backend = None
def __get_backend(self):
if not self.__backend:
print self.__ba... | class LazyPluggable(object):
"""A pluggable backend loaded lazily based on some value."""
def __init__(self, pivot, **backends):
self.__backends = backends
self.__pivot = pivot
self.__backend = None
def __get_backend(self):
if not self.__backend:
backend_name = ... | Remove stray print debug message | Remove stray print debug message
Signed-off-by: Steven Dake <8638f3fce5db0278cfbc239bd581dfc00c29ec9d@redhat.com>
| Python | apache-2.0 | rickerc/heat_audit,maestro-hybrid-cloud/heat,dims/heat,JioCloud/heat,cwolferh/heat-scratch,rh-s/heat,citrix-openstack-build/heat,steveb/heat,JioCloud/heat,steveb/heat-cfntools,Triv90/Heat,openstack/heat,dragorosson/heat,ntt-sic/heat,varunarya10/heat,miguelgrinberg/heat,rdo-management/heat,pratikmallya/heat,takeshineshi... |
faf6f74348ed09f2ba0ebb5a133acc1a04edb737 | main.py | main.py | import cmd
import argparse
from Interface import *
class Lexeme(cmd.Cmd):
intro = "Welcome to Lexeme. Input ? for help and commands"
prompt = "(lexeme) "
def do_list(self, arg):
'List word database.'
listwords()
def do_quit(self, arg):
quit()
def do_add(self, arg):
... | import cmd
import argparse
from Interface import *
class Lexeme(cmd.Cmd):
intro = "Welcome to Lexeme! Input '?' for help and commands."
prompt = "Enter command: "
def do_list(self, arg):
'List word database.'
listwords()
def do_quit(self, arg):
quit()
def do_add(self, ar... | Change prompt and intro message | Change prompt and intro message
| Python | mit | kdelwat/Lexeme |
aa4f8943616adce4dba826924b8d21e1e8164299 | eduid_signup_amp/__init__.py | eduid_signup_amp/__init__.py | from eduid_am.exceptions import UserDoesNotExist
def attribute_fetcher(db, user_id):
attributes = {}
user = db.registered.find_one({'_id': user_id})
if user is None:
raise UserDoesNotExist("No user matching _id='%s'" % user_id)
else:
# white list of valid attributes for security reas... | from eduid_am.exceptions import UserDoesNotExist
def attribute_fetcher(db, user_id):
attributes = {}
user = db.registered.find_one({'_id': user_id})
if user is None:
raise UserDoesNotExist("No user matching _id='%s'" % user_id)
else:
email = user.get('email', None)
if email:
... | Change fields to the schema agreed | Change fields to the schema agreed
| Python | bsd-3-clause | SUNET/eduid-signup-amp |
7784186509e41c72bcf7a4ebbd9b268b49449d35 | user_clipboard/urls.py | user_clipboard/urls.py | from django.conf.urls import patterns, url
from .views import ClipboardFileAPIView, ClipboardImageAPIView
urlpatterns = patterns(
'',
url(r'^images/(?P<pk>\d+)$', ClipboardImageAPIView.as_view(), name="clipboard_images"),
url(r'^images/', ClipboardImageAPIView.as_view(), name="clipboard_images"),
url(... | from django.conf.urls import url
from .views import ClipboardFileAPIView, ClipboardImageAPIView
urlpatterns = [
url(r'^images/(?P<pk>\d+)$', ClipboardImageAPIView.as_view(), name="clipboard_images"),
url(r'^images/', ClipboardImageAPIView.as_view(), name="clipboard_images"),
url(r'^(?P<pk>\d+)$', Clipboar... | Define urlpatterns as a pure list (don't call patterns) | Define urlpatterns as a pure list (don't call patterns) | Python | mit | MagicSolutions/django-user-clipboard,IndustriaTech/django-user-clipboard,MagicSolutions/django-user-clipboard,IndustriaTech/django-user-clipboard |
a56707d815271088c2c19f0c2c415d611886e859 | db/__init__.py | db/__init__.py | import categories # nopep8
import plugins # nopep8
import submitted_plugins # nopep8
import tags # nopep8
| import categories # NOQA: F401
import plugins # NOQA: F401
import submitted_plugins # NOQA: F401
import tags # NOQA: F401
| Update nopep8 instructions to NOQA | Update nopep8 instructions to NOQA
`flake8` seems to have dropped support for `# nopep8` in the 3.x
versions (confirmed by testing with latest and `<3`). This causes our
style checking tests to fail.
Replace these with `# NOQA` and pin them to the specific error we care
about here (F401 unused import).
| Python | mit | jonafato/vim-awesome,vim-awesome/vim-awesome,jonafato/vim-awesome,vim-awesome/vim-awesome,divad12/vim-awesome,jonafato/vim-awesome,vim-awesome/vim-awesome,divad12/vim-awesome,jonafato/vim-awesome,divad12/vim-awesome,vim-awesome/vim-awesome,divad12/vim-awesome,vim-awesome/vim-awesome |
e33a68f14a13c0340b2dfcbb13931d2185735951 | scripts/nanopolish_makerange.py | scripts/nanopolish_makerange.py | from __future__ import print_function
import sys
import argparse
from Bio import SeqIO
parser = argparse.ArgumentParser(description='Partition a genome into a set of overlapping segments')
parser.add_argument('--segment-length', type=int, default=50000)
parser.add_argument('--overlap-length', type=int, default=200)
a... | from __future__ import print_function
import sys
import argparse
from Bio.SeqIO.FastaIO import SimpleFastaParser
parser = argparse.ArgumentParser(description='Partition a genome into a set of overlapping segments')
parser.add_argument('--segment-length', type=int, default=50000)
parser.add_argument('--overlap-length'... | Use Biopython's string based FASTA parser | Use Biopython's string based FASTA parser
This was introduced in Biopython 1.61 back in February 2013,
so the dependencies shouldn't matter.
You could go further here and use a generator expression
over a list comprehension? | Python | mit | jts/nanopolish,jts/nanopolish,jts/nanopolish,jts/nanopolish,jts/nanopolish |
945209957a26d8fc7673795b5bfc5c233ed00e0e | uchicagohvz/game/serializers.py | uchicagohvz/game/serializers.py | from rest_framework import serializers
from uchicagohvz.game.models import *
class KillSerializer(serializers.ModelSerializer):
class Meta:
model = Kill
fields = ('id', 'killer', 'victim', 'location', 'date', 'points')
killer = serializers.SerializerMethodField('get_killer')
victim = serializers.SerializerMeth... | from rest_framework import serializers
from uchicagohvz.game.models import *
class KillSerializer(serializers.ModelSerializer):
class Meta:
model = Kill
fields = ('id', 'killer', 'victim', 'location', 'date', 'points')
killer = serializers.SerializerMethodField()
victim = serializers.SerializerMethodField()
l... | Remove default method_name in SerializerMethodField | Remove default method_name in SerializerMethodField | Python | mit | kz26/uchicago-hvz,kz26/uchicago-hvz,kz26/uchicago-hvz |
9c945162dfb60481c9f5d39c5e42617b030263a9 | mailgun/models.py | mailgun/models.py | import api
import db
from utils import parse_timestamp
import hashlib
import json
def download_logs():
""" Download mailgun logs and store them in the database """
logs = []
skip = 0
# Fetch all unsaved logs and add them to a LIFO queue
while True:
print("fecthing logs starting at {}... | import api
import db
from utils import parse_timestamp
from django.db import transaction
from collections import OrderedDict
import hashlib
import json
@transaction.commit_manually
def download_logs():
""" Download mailgun logs and store them in the database """
# use ordered dict to protect against new logs... | Handle transactions manually when saving downloaded logs | Handle transactions manually when saving downloaded logs
| Python | mit | p2pu/mechanical-mooc,p2pu/mechanical-mooc,p2pu/mechanical-mooc,p2pu/mechanical-mooc |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.