commit stringlengths 40 40 | old_file stringlengths 4 150 | new_file stringlengths 4 150 | old_contents stringlengths 0 3.26k | new_contents stringlengths 1 4.43k | subject stringlengths 15 501 | message stringlengths 15 4.06k | lang stringclasses 4
values | license stringclasses 13
values | repos stringlengths 5 91.5k | diff stringlengths 0 4.35k |
|---|---|---|---|---|---|---|---|---|---|---|
54ab8be3e994f17077d83b0c719fc44a60b889e5 | tests/settings.py | tests/settings.py | import os
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'import_export',
'core',
]
SITE_ID = 1
ROOT_URLCONF = "urls"
DEBUG = True
STATIC_URL = '/static/'
if os.environ.get('IMPORT_EX... | import os
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'import_export',
'core',
]
SITE_ID = 1
ROOT_URLCONF = "urls"
DEBUG = True
STATIC_URL = '/static/'
SECRET_KEY = '2n6)=vnp8@bu0o... | Add required SECRET_KEY to test app | Add required SECRET_KEY to test app
| Python | bsd-2-clause | Akoten/django-import-export,luto/django-import-export,bmihelac/django-import-export,bmihelac/django-import-export,rhunwicks/django-import-export,bmihelac/django-import-export,ylteq/dj-import-export,ylteq/dj-import-export,copperleaftech/django-import-export,luto/django-import-export,pajod/django-import-export,piran/djan... | ---
+++
@@ -20,6 +20,8 @@
STATIC_URL = '/static/'
+SECRET_KEY = '2n6)=vnp8@bu0om9d05vwf7@=5vpn%)97-!d*t4zq1mku%0-@j'
+
if os.environ.get('IMPORT_EXPORT_TEST_TYPE') == 'mysql-innodb':
IMPORT_EXPORT_USE_TRANSACTIONS = True
DATABASES = { |
c65c9fafbdd96f20c7a87ce88ff594edcd490b49 | numpy/distutils/command/install.py | numpy/distutils/command/install.py |
from distutils.command.install import *
from distutils.command.install import install as old_install
class install(old_install):
def finalize_options (self):
old_install.finalize_options(self)
self.install_lib = self.install_libbase
|
import os
from distutils.command.install import *
from distutils.command.install import install as old_install
from distutils.file_util import write_file
class install(old_install):
def finalize_options (self):
old_install.finalize_options(self)
self.install_lib = self.install_libbase
def ru... | Fix bdist_rpm for path names containing spaces. | Fix bdist_rpm for path names containing spaces.
git-svn-id: 77a43f9646713b91fea7788fad5dfbf67e151ece@2013 94b884b6-d6fd-0310-90d3-974f1d3f35e1
| Python | bsd-3-clause | chadnetzer/numpy-gaurdro,illume/numpy3k,illume/numpy3k,chadnetzer/numpy-gaurdro,Ademan/NumPy-GSoC,teoliphant/numpy-refactor,chadnetzer/numpy-gaurdro,Ademan/NumPy-GSoC,illume/numpy3k,efiring/numpy-work,teoliphant/numpy-refactor,teoliphant/numpy-refactor,teoliphant/numpy-refactor,jasonmccampbell/numpy-refactor-sprint,Ade... | ---
+++
@@ -1,9 +1,34 @@
+import os
from distutils.command.install import *
from distutils.command.install import install as old_install
+from distutils.file_util import write_file
class install(old_install):
def finalize_options (self):
old_install.finalize_options(self)
self.install_... |
763e8b3d8cab43fb314a2dd6b5ebb60c2d482a52 | deploy_latest_build.py | deploy_latest_build.py | #! /usr/bin/python
# Copyright 2014 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by... | #! /usr/bin/python
# Copyright 2014 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by... | Fix deploy CLI arg parsing | Fix deploy CLI arg parsing
| Python | apache-2.0 | alancutter/web-animations-perf-bot | ---
+++
@@ -16,12 +16,13 @@
from __future__ import print_function
-from list_builds import list_builds
+from list_builds import list_every_build
from get_build import ensure_build_file
from deploy_build import deploy_build
def main():
- build = list_builds('every')[-1]
+ args = parse_argsets([chromium_src... |
c51fbf651ae04341233dd16f4b93b1c6b8f3d30b | observatory/emaillist/views.py | observatory/emaillist/views.py | from emaillist.models import EmailExclusion
from django.shortcuts import render_to_response
def remove_email(request, email):
if email[-1] == '/':
email = email[:-1]
#Only exclude an email once
if EmailExclusion.excluded(email):
return
#Exclude the email
exclude = EmailExclusion(e... | from emaillist.models import EmailExclusion
from django.shortcuts import render_to_response
def remove_email(request, email):
if email[-1] == '/':
email = email[:-1]
#Only exclude an email once
if EmailExclusion.excluded(email):
return render_to_response('emaillist/email_removed.html')
... | Abort early with removed if nothing needs to be done | Abort early with removed if nothing needs to be done
| Python | isc | rcos/Observatory,rcos/Observatory,rcos/Observatory,rcos/Observatory,rcos/Observatory,rcos/Observatory | ---
+++
@@ -7,7 +7,7 @@
#Only exclude an email once
if EmailExclusion.excluded(email):
- return
+ return render_to_response('emaillist/email_removed.html')
#Exclude the email
exclude = EmailExclusion(email=email) |
1205f30111b5f4789e3d68a1ff62bdb5b5597fc4 | pytest-{{cookiecutter.plugin_name}}/tests/test_{{cookiecutter.plugin_name}}.py | pytest-{{cookiecutter.plugin_name}}/tests/test_{{cookiecutter.plugin_name}}.py | # -*- coding: utf-8 -*-
def test_bar_fixture(testdir):
"""Make sure that pytest accepts our fixture."""
# create a temporary pytest test module
testdir.makepyfile("""
def test_sth(bar):
assert bar == "europython2015"
""")
# run pytest with the following cmd args
result = t... | # -*- coding: utf-8 -*-
def test_bar_fixture(testdir):
"""Make sure that pytest accepts our fixture."""
# create a temporary pytest test module
testdir.makepyfile("""
def test_sth(bar):
assert bar == "europython2015"
""")
# run pytest with the following cmd args
result = t... | Implement a test for an ini option | Implement a test for an ini option
| Python | mit | pytest-dev/cookiecutter-pytest-plugin,s0undt3ch/cookiecutter-pytest-plugin | ---
+++
@@ -33,3 +33,31 @@
'{{cookiecutter.plugin_name}}:',
'*--foo=DEST_FOO*Set the value for the fixture "bar".',
])
+
+
+def test_hello_ini_setting(testdir):
+ testdir.makeini("""
+ [pytest]
+ HELLO = world
+ """)
+
+ testdir.makepyfile("""
+ import pytest
+
+ ... |
f89dbcf6a140e02a4d5d7a89872c0c066a1dd869 | panoptes_client/classification.py | panoptes_client/classification.py | from __future__ import absolute_import, division, print_function
from panoptes_client.panoptes import LinkResolver, PanoptesObject
class Classification(PanoptesObject):
_api_slug = 'classifications'
_link_slug = 'classification'
_edit_attributes = ( )
@classmethod
def where(cls, **kwargs):
... | from __future__ import absolute_import, division, print_function
from panoptes_client.panoptes import LinkResolver, PanoptesObject
class Classification(PanoptesObject):
_api_slug = 'classifications'
_link_slug = 'classification'
_edit_attributes = ( )
@classmethod
def where(cls, **kwargs):
... | Fix typo in documentation for Classification | Fix typo in documentation for Classification
| Python | apache-2.0 | zooniverse/panoptes-python-client | ---
+++
@@ -22,7 +22,7 @@
Examples::
- my_classifications = Classifiction.where()
+ my_classifications = Classification.where()
my_proj_123_classifications = Classification.where(project_id=123)
all_proj_123_classifications = Classification.where( |
67c1855f75a3c29bc650c193235576f6b591c805 | payment_redsys/__manifest__.py | payment_redsys/__manifest__.py | # Copyright 2017 Tecnativa - Sergio Teruel
# Copyright 2020 Tecnativa - João Marques
{
"name": "Pasarela de pago Redsys",
"category": "Payment Acquirer",
"summary": "Payment Acquirer: Redsys Implementation",
"version": "14.0.2.0.0",
"author": "Tecnativa," "Odoo Community Association (OCA)",
"we... | # Copyright 2017 Tecnativa - Sergio Teruel
# Copyright 2020 Tecnativa - João Marques
{
"name": "Pasarela de pago Redsys",
"category": "Payment Acquirer",
"summary": "Payment Acquirer: Redsys Implementation",
"version": "14.0.2.0.0",
"author": "Tecnativa," "Odoo Community Association (OCA)",
"we... | Put real package on pypi | [IMP] payment_redsys: Put real package on pypi
| Python | agpl-3.0 | cubells/l10n-spain,cubells/l10n-spain,cubells/l10n-spain | ---
+++
@@ -9,7 +9,7 @@
"author": "Tecnativa," "Odoo Community Association (OCA)",
"website": "https://github.com/OCA/l10n-spain",
"depends": ["payment", "website_sale"],
- "external_dependencies": {"python": ["Crypto.Cipher.DES3"]},
+ "external_dependencies": {"python": ["pycrypto"]},
"data... |
a0e835cbf382cb55ff872bb8d6cc57a5326a82de | ckanext/ckanext-apicatalog_scheming/ckanext/apicatalog_scheming/validators.py | ckanext/ckanext-apicatalog_scheming/ckanext/apicatalog_scheming/validators.py | from ckan.common import _
import ckan.lib.navl.dictization_functions as df
def lower_if_exists(s):
return s.lower() if s else s
def upper_if_exists(s):
return s.upper() if s else s
def valid_resources(private, context):
package = context.get('package')
if not private or private == u'False':
... | from ckan.common import _
import ckan.lib.navl.dictization_functions as df
def lower_if_exists(s):
return s.lower() if s else s
def upper_if_exists(s):
return s.upper() if s else s
def valid_resources(private, context):
package = context.get('package')
if package and (not private or private == u'F... | Fix package resource validator for new packages | LK-271: Fix package resource validator for new packages
| Python | mit | vrk-kpa/api-catalog,vrk-kpa/api-catalog,vrk-kpa/api-catalog,vrk-kpa/api-catalog | ---
+++
@@ -12,7 +12,7 @@
def valid_resources(private, context):
package = context.get('package')
- if not private or private == u'False':
+ if package and (not private or private == u'False'):
for resource in package.resources:
if resource.extras.get('valid_content') == 'no':
... |
417c838dcda8e6117f23f13a6edac02c8582e67f | tests/print_view_controller_hierarchy_test.py | tests/print_view_controller_hierarchy_test.py | """Tests for scripts/print_view_controller_hierarchy.py."""
import re
import unittest
from test_utils import import_utils
import_utils.prepare_lldb_import_or_exit()
import lldb
import_utils.prepare_for_scripts_imports()
from scripts import print_view_controller_hierarchy
class PrintViewControllerHierarchyTest(unit... | """Tests for scripts/print_view_controller_hierarchy.py."""
import re
import unittest
from test_utils import import_utils
import_utils.prepare_lldb_import_or_exit()
import lldb
import_utils.prepare_for_scripts_imports()
from scripts import print_view_controller_hierarchy
class PrintViewControllerHierarchyTest(unit... | Detach debugger from process after each test. | Detach debugger from process after each test.
| Python | mit | mrhappyasthma/HappyDebugging,mrhappyasthma/happydebugging | ---
+++
@@ -32,4 +32,4 @@
expected_output_regex = r'<ViewController 0x\w{12}>, state: appeared, view: <UIView 0x\w{12}>'
self.assertTrue(re.match(expected_output_regex,
result.GetOutput().rstrip()))
- debugger.Terminate()
+ debugger.DeleteTarget(target) |
8c75327dfc6f6d6bc3097813db9dc4ae0e46489a | private_storage/permissions.py | private_storage/permissions.py | """
Possible functions for the ``PRIVATE_STORAGE_AUTH_FUNCTION`` setting.
"""
def allow_authenticated(private_file):
try:
return private_file.request.user.is_authenticated()
except AttributeError:
# Using user.is_authenticated() and user.is_anonymous() as a method is deprecated since Django 2.... | """
Possible functions for the ``PRIVATE_STORAGE_AUTH_FUNCTION`` setting.
"""
import django
if django.VERSION >= (1, 10):
def allow_authenticated(private_file):
return private_file.request.user.is_authenticated
def allow_staff(private_file):
request = private_file.request
return reques... | Change the permission checks, provide distinct versions for Django 1.10+ | Change the permission checks, provide distinct versions for Django 1.10+
| Python | apache-2.0 | edoburu/django-private-storage | ---
+++
@@ -1,29 +1,27 @@
"""
Possible functions for the ``PRIVATE_STORAGE_AUTH_FUNCTION`` setting.
"""
+import django
+if django.VERSION >= (1, 10):
+ def allow_authenticated(private_file):
+ return private_file.request.user.is_authenticated
-def allow_authenticated(private_file):
- try:
- ... |
abc46de12891bf1c30f4424ccd36c0aecf761261 | tests/conftest.py | tests/conftest.py | # -*- coding: utf-8 -*-
"""
tests.conftest
~~~~~~~~~~~~~~~~~~~~~
Fixtures for tests.
:copyright: (c) 2017 Yoan Tournade.
:license: MIT, see LICENSE for more details.
"""
import pytest
import subprocess
import time
@pytest.fixture(scope="function")
def latex_on_http_api_url():
appProcess = subp... | # -*- coding: utf-8 -*-
"""
tests.conftest
~~~~~~~~~~~~~~~~~~~~~
Fixtures for tests.
:copyright: (c) 2017 Yoan Tournade.
:license: MIT, see LICENSE for more details.
"""
import pytest
import subprocess
import time
@pytest.fixture(scope="function")
def latex_on_http_api_url():
appProcess = subp... | Reduce delay for waiting for server start betweeb tests | Reduce delay for waiting for server start betweeb tests
| Python | agpl-3.0 | YtoTech/latex-on-http,YtoTech/latex-on-http | ---
+++
@@ -14,7 +14,8 @@
@pytest.fixture(scope="function")
def latex_on_http_api_url():
appProcess = subprocess.Popen(['make', 'start'])
- time.sleep(1)
+ # appProcess = subprocess.Popen(['make', 'debug'])
+ time.sleep(0.5)
yield 'http://localhost:8080/'
print("teardown latex_on_http_api")
... |
4035afc6fa7f47219a39ad66f902bb90c6e81aa1 | pyopenapi/scanner/type_reducer.py | pyopenapi/scanner/type_reducer.py | from __future__ import absolute_import
from ..scan import Dispatcher
from ..errs import SchemaError
from ..spec.v3_0_0.objects import Operation
from ..utils import scope_compose
from ..consts import private
class TypeReduce(object):
""" Type Reducer, collect Operation & Model
spreaded in Resources put in a glo... | from __future__ import absolute_import
from ..scan import Dispatcher
from ..errs import SchemaError
from ..spec.v3_0_0.objects import Operation as Op3
from ..spec.v2_0.objects import Operation as Op2
from ..utils import scope_compose
from ..consts import private
class TypeReduce(object):
""" Type Reducer, collect ... | Allow to reduce Operations in 2.0 and 3.0.0 to App.op | Allow to reduce Operations in 2.0 and 3.0.0 to App.op
| Python | mit | mission-liao/pyopenapi | ---
+++
@@ -1,7 +1,8 @@
from __future__ import absolute_import
from ..scan import Dispatcher
from ..errs import SchemaError
-from ..spec.v3_0_0.objects import Operation
+from ..spec.v3_0_0.objects import Operation as Op3
+from ..spec.v2_0.objects import Operation as Op2
from ..utils import scope_compose
from ..c... |
093202349a971ba20982976f464853e657ea3237 | tests/test_cli.py | tests/test_cli.py | # Copyright 2013 Donald Stufft
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, so... | # Copyright 2013 Donald Stufft
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, so... | Add test for upload functionality | Add test for upload functionality
| Python | apache-2.0 | beni55/twine,dstufft/twine,jamesblunt/twine,mhils/twine,sigmavirus24/twine,pypa/twine,warner/twine,reinout/twine | ---
+++
@@ -14,9 +14,20 @@
from __future__ import absolute_import, division, print_function
from __future__ import unicode_literals
+import pretend
import pytest
from twine import cli
+import twine.commands.upload
+
+
+def test_dispatch_to_subcommand(monkeypatch):
+ replaced_main = pretend.call_recorder(la... |
af722fd8c8590b92293aa35e94e8cdf675fc50b8 | discode_server/config/base_config.py | discode_server/config/base_config.py | import os
from urllib import parse
DEBUG = False
DATABASE_SA = os.environ.get('HEROKU_POSTGRESQL_CHARCOAL_URL')
bits = parse.urlparse(DATABASE_SA)
DATABASE = {
'user': bits.username,
'database': bits.path[1:],
'password': bits.password,
'host': bits.hostname,
'port': bits.port,
}
# 8 worker * 1... | import os
from urllib import parse
DEBUG = False
DATABASE_SA = os.environ.get('HEROKU_POSTGRESQL_CHARCOAL_URL')
bits = parse.urlparse(DATABASE_SA)
DATABASE = {
'user': bits.username,
'database': bits.path[1:],
'password': bits.password,
'host': bits.hostname,
'port': bits.port,
}
# 8 worker * 1... | Switch back to 8 workers | Switch back to 8 workers
| Python | bsd-2-clause | d0ugal/discode-server,d0ugal/discode-server,d0ugal/discode-server | ---
+++
@@ -17,4 +17,4 @@
# 8 worker * 10 connections = 80 connectionso
# pgbouncer is setup for 100, so we have a few extra to play with
-WORKER_COUNT = 1
+WORKER_COUNT = 8 |
9aa2f8ebc2a9a0d9b74f2d22a3eb6d7ed3212008 | xirvik/logging.py | xirvik/logging.py | from logging.handlers import SysLogHandler
import logging
import sys
syslogh = None
def cleanup():
global syslogh
if syslogh:
syslogh.close()
logging.shutdown()
def get_logger(name,
level=logging.INFO,
verbose=False,
debug=False,
sys... | from logging.handlers import SysLogHandler
import logging
import sys
syslogh = None
def cleanup():
global syslogh
if syslogh:
syslogh.close()
logging.shutdown()
def get_logger(name,
level=logging.INFO,
verbose=False,
debug=False,
sys... | Put level in log message for xirvik.* | Put level in log message for xirvik.*
| Python | mit | Tatsh/xirvik-tools | ---
+++
@@ -27,7 +27,7 @@
log.setLevel(level if not debug else logging.DEBUG)
channel = logging.StreamHandler(sys.stdout if debug else sys.stderr)
- channel.setFormatter(logging.Formatter('%(asctime)s - %(message)s'))
+ channel.setFormatter(logging.Formatter('%(asctime)s - %(levelnam... |
661fafef2c1f86459a11683704945a1a83e4f760 | lib/tagnews/geoloc/geocode_list.py | lib/tagnews/geoloc/geocode_list.py | import geocoder
import time
def lat_longs_from_geo_strings(lst):
lats_lons = []
for addr_str in lst:
g = geocoder.google(addr_str)
if g.latlng is None:
time.sleep(.5)
lats_lons.extend(lat_longs_from_geo_strings([addr_str]))
else:
lats_lons.append(g.la... | import geocoder
import time
# don't make more than 1 request per second
last_request_time = 0
def get_lat_longs_from_geostrings(geostring_list, provider='osm'):
"""
Geo-code each geostring in `geostring_list` into lat/long values.
Also return the full response from the geocoding service.
Inputs
... | Add documentation, tweak rate limit handling, remove unused function. | Add documentation, tweak rate limit handling, remove unused function.
| Python | mit | chicago-justice-project/article-tagging,chicago-justice-project/article-tagging,kbrose/article-tagging,kbrose/article-tagging | ---
+++
@@ -1,30 +1,41 @@
import geocoder
import time
-def lat_longs_from_geo_strings(lst):
- lats_lons = []
- for addr_str in lst:
- g = geocoder.google(addr_str)
- if g.latlng is None:
- time.sleep(.5)
- lats_lons.extend(lat_longs_from_geo_strings([addr_str]))
- ... |
e58efc792984b7ba366ebea745caa70e6660a41b | scrapyard/yts.py | scrapyard/yts.py | import cache
import network
import scraper
YTS_URL = 'http://yts.re'
################################################################################
def movie(movie_info):
magnet_infos = []
json_data = network.json_get_cached_optional(YTS_URL + '/api/listimdb.json', expiration=cache.HOUR, params={ 'imdb_id'... | import cache
import network
import scraper
import urllib
YTS_URL = 'http://yts.re'
################################################################################
def movie(movie_info):
magnet_infos = []
json_data = network.json_get_cached_optional(YTS_URL + '/api/v2/list_movies.json', expiration=cache.HOUR... | Upgrade YTS to API v2 | Upgrade YTS to API v2
| Python | mit | sharkone/scrapyard | ---
+++
@@ -1,6 +1,7 @@
import cache
import network
import scraper
+import urllib
YTS_URL = 'http://yts.re'
@@ -8,10 +9,14 @@
def movie(movie_info):
magnet_infos = []
- json_data = network.json_get_cached_optional(YTS_URL + '/api/listimdb.json', expiration=cache.HOUR, params={ 'imdb_id': movie_info... |
90ea0d2113b576e47284e7ab38ff95887437cc4b | website/jdevents/models.py | website/jdevents/models.py | from django.db import models
from mezzanine.core.models import Displayable, RichText
class RepeatType(models.Model):
DAILY = 'daily'
WEEKLY = 'weekly',
MONTHLY = 'monthly'
REPEAT_CHOICES = (
(DAILY, 'REPEAT_DAILY'),
(WEEKLY, 'REPEAT_WEEKLY'),
(MONTHLY, 'REPEAT_MONTHLY')
)
... | from django.db import models
from django.utils.translation import ugettext_lazy as _
from mezzanine.core.models import Displayable, RichText
class RepeatType(models.Model):
DAILY = 'daily'
WEEKLY = 'weekly',
MONTHLY = 'monthly'
REPEAT_CHOICES = (
(DAILY, _('Daily')),
(WEEKLY, _('Weekl... | Fix text for repeated events. | Fix text for repeated events.
| Python | mit | jonge-democraten/website,jonge-democraten/website,jonge-democraten/website,jonge-democraten/website | ---
+++
@@ -1,4 +1,5 @@
from django.db import models
+from django.utils.translation import ugettext_lazy as _
from mezzanine.core.models import Displayable, RichText
@@ -8,9 +9,9 @@
MONTHLY = 'monthly'
REPEAT_CHOICES = (
- (DAILY, 'REPEAT_DAILY'),
- (WEEKLY, 'REPEAT_WEEKLY'),
- ... |
8745f809597ec76d6fb785a356d4c611fa1afde3 | server/server.py | server/server.py | from logging import FileHandler
from app import app
from api import api
from models import db
import os
from flask import request
app.config.from_pyfile('../server.cfg')
@app.route("/edit_graph_style", methods=['GET','POST'])
def edit_graph_style():
filename = os.path.dirname(os.path.abspath(__file__)) + "/grap... | from logging import FileHandler
from app import app
from api import api
from models import db
import os
from flask import request
app.config.from_pyfile('../server.cfg')
@app.route("/edit_graph_style", methods=['GET','POST'])
def edit_graph_style():
style_path = app.config['GRAPH_STYLE_PATH']
if request.me... | Use the right graph style path in the editor | Use the right graph style path in the editor
| Python | mit | UoMCS/syllabus-visualisation,UoMCS/syllabus-visualisation,UoMCS/syllabus-visualisation | ---
+++
@@ -10,13 +10,13 @@
@app.route("/edit_graph_style", methods=['GET','POST'])
def edit_graph_style():
- filename = os.path.dirname(os.path.abspath(__file__)) + "/graph_style.json"
+ style_path = app.config['GRAPH_STYLE_PATH']
if request.method == 'POST':
- with open(filename, 'w') as f:
... |
a16d832dd739088aaa7d3b31bd9c94783ad2ac37 | website/config.py | website/config.py | SQLALCHEMY_DATABASE_URI = 'sqlite:////tmp/test.db'
SQLALCHEMY_TRACK_MODIFICATIONS = True
# SQLALCHEMY_ECHO = False
SECRET_KEY = '\xfb\x12\xdf\xa1@i\xd6>V\xc0\xbb\x8fp\x16#Z\x0b\x81\xeb\x16'
DEBUG = True
DEFAULT_HOST = '0.0.0.0' # use public IPs
DEFAULT_PORT = 5000
| import os
base_dir = os.path.abspath(os.path.dirname(__file__))
databases_dir = os.path.join(base_dir, 'databases')
SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(databases_dir, 'app.db')
SQLALCHEMY_TRACK_MODIFICATIONS = True
# SQLALCHEMY_ECHO = False
SECRET_KEY = '\xfb\x12\xdf\xa1@i\xd6>V\xc0\xbb\x8fp\x16#Z\x... | Store the temporary database permanently | Store the temporary database permanently
so it does not require db_create after resteing /tmp
| Python | lgpl-2.1 | reimandlab/ActiveDriverDB,reimandlab/ActiveDriverDB,reimandlab/Visualistion-Framework-for-Genome-Mutations,reimandlab/Visualistion-Framework-for-Genome-Mutations,reimandlab/Visualisation-Framework-for-Genome-Mutations,reimandlab/Visualisation-Framework-for-Genome-Mutations,reimandlab/Visualisation-Framework-for-Genome-... | ---
+++
@@ -1,4 +1,9 @@
-SQLALCHEMY_DATABASE_URI = 'sqlite:////tmp/test.db'
+import os
+base_dir = os.path.abspath(os.path.dirname(__file__))
+databases_dir = os.path.join(base_dir, 'databases')
+
+
+SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(databases_dir, 'app.db')
SQLALCHEMY_TRACK_MODIFICATIONS = True
... |
453e2c9c30c98a6077acefff7d36a277b77c052c | tests/conftest.py | tests/conftest.py |
from __future__ import absolute_import
import contextlib
import os.path
import pytest
import sqlite3
from git_code_debt.create_tables import create_schema
from git_code_debt.create_tables import populate_metric_ids
from git_code_debt.repo_parser import RepoParser
class Sandbox(object):
def __init__(self, direc... |
from __future__ import absolute_import
import contextlib
import os.path
import pytest
import sqlite3
from git_code_debt.create_tables import create_schema
from git_code_debt.create_tables import populate_metric_ids
from git_code_debt.repo_parser import RepoParser
class Sandbox(object):
def __init__(self, direc... | Use git:// for tests instead. | Use git:// for tests instead.
| Python | mit | Yelp/git-code-debt,ucarion/git-code-debt,Yelp/git-code-debt,Yelp/git-code-debt,ucarion/git-code-debt,Yelp/git-code-debt,ucarion/git-code-debt | ---
+++
@@ -37,6 +37,6 @@
@pytest.yield_fixture(scope='session')
def cloneable():
- repo_parser = RepoParser('git@github.com:asottile/git-code-debt')
+ repo_parser = RepoParser('git://github.com/asottile/git-code-debt')
with repo_parser.repo_checked_out():
yield repo_parser.tempdir |
5abb4d9b5bfe88e9617839f5558e5b31dbf02f5b | 19-getBlockHits.py | 19-getBlockHits.py | # We have to import the minecraft api module to do anything in the minecraft world
from mcpi.minecraft import *
from mcpi.block import *
from blockData import *
# this means that the file can be imported without executing anything in this code block
if __name__ == "__main__":
"""
First thing you do is create... | # We have to import the minecraft api module to do anything in the minecraft world
from mcpi.minecraft import *
from mcpi.block import *
from blockData import *
# this means that the file can be imported without executing anything in this code block
if __name__ == "__main__":
"""
First thing you do is create... | Remove code that is not used | Remove code that is not used
Function call not required so removed
| Python | bsd-3-clause | hashbangstudio/Python-Minecraft-Examples | ---
+++
@@ -16,9 +16,6 @@
# Any communication with the world must use this object
mc = Minecraft.create()
- # Get the current tile/block that the player is located at in the world
- playerPosition = mc.player.getTilePos()
-
while(True):
hits = mc.events.pollBlockHits()
... |
a58c3cbfa2c0147525e1afb355e355a9edeb22f8 | discussion/admin.py | discussion/admin.py | from django.contrib import admin
from discussion.models import Comment, Discussion, Post
class CommentInline(admin.TabularInline):
exclude = ('user',)
extra = 1
model = Comment
class PostAdmin(admin.ModelAdmin):
inlines = (CommentInline,)
list_filter = ('discussion',)
class DiscussionAdmin(adm... | from django.contrib import admin
from discussion.models import Comment, Discussion, Post
class CommentInline(admin.TabularInline):
extra = 1
model = Comment
raw_id_fields = ('user',)
class PostAdmin(admin.ModelAdmin):
inlines = (CommentInline,)
list_filter = ('discussion',)
class DiscussionAdm... | Add user back onto the comment inline for posts | Add user back onto the comment inline for posts
| Python | bsd-2-clause | lehins/lehins-discussion,lehins/lehins-discussion,incuna/django-discussion,incuna/django-discussion,lehins/lehins-discussion | ---
+++
@@ -3,9 +3,9 @@
class CommentInline(admin.TabularInline):
- exclude = ('user',)
extra = 1
model = Comment
+ raw_id_fields = ('user',)
class PostAdmin(admin.ModelAdmin): |
675627ee810859b405b0aca422cd85f6545581a1 | django_olcc/urls.py | django_olcc/urls.py | from django.conf import settings
from django.conf.urls.defaults import patterns, include, url
from django.contrib import admin
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.views.generic.simple import direct_to_template
# Enable the django admin
admin.autodiscover()
urlpatterns = pat... | from django.conf import settings
from django.conf.urls.defaults import patterns, include, url
from django.contrib import admin
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.views.generic.simple import direct_to_template
# Enable the django admin
admin.autodiscover()
urlpatterns = pat... | Fix a buggy url conf for heroku. | Fix a buggy url conf for heroku.
| Python | mit | twaddington/django-olcc,twaddington/django-olcc,twaddington/django-olcc | ---
+++
@@ -32,6 +32,6 @@
urlpatterns += staticfiles_urlpatterns()
else:
urlpatterns += patterns('',
- (r'^static/(?P.*)$', 'django.views.static.serve',
+ (r'^static/(.*)$', 'django.views.static.serve',
{'document_root': settings.STATIC_ROOT}),
) |
b81045a1fbfb826226fa9b6f6d0258f72a66c8fe | api/base/exceptions.py | api/base/exceptions.py |
from rest_framework import status
from rest_framework.exceptions import APIException
def json_api_exception_handler(exc, context):
""" Custom exception handler that returns errors object as an array """
# Import inside method to avoid errors when the OSF is loaded without Django
from rest_framework.view... |
from rest_framework import status
from rest_framework.exceptions import APIException
def json_api_exception_handler(exc, context):
""" Custom exception handler that returns errors object as an array """
# Import inside method to avoid errors when the OSF is loaded without Django
from rest_framework.view... | Handle tuple error formatting same as list | Handle tuple error formatting same as list
| Python | apache-2.0 | chrisseto/osf.io,rdhyee/osf.io,acshi/osf.io,billyhunt/osf.io,RomanZWang/osf.io,baylee-d/osf.io,emetsger/osf.io,hmoco/osf.io,samanehsan/osf.io,crcresearch/osf.io,acshi/osf.io,abought/osf.io,brianjgeiger/osf.io,sbt9uc/osf.io,TomBaxter/osf.io,rdhyee/osf.io,kwierman/osf.io,GageGaskins/osf.io,mluke93/osf.io,zachjanicki/osf.... | ---
+++
@@ -22,7 +22,7 @@
errors.append({key: value})
else:
errors.append({'detail': {key: value}})
- elif isinstance(message, list):
+ elif isinstance(message, (list, tuple)):
for error in message:
errors.append({'... |
b181390c9e0613fed773e05a037b89cd24b225b0 | data_preparation.py | data_preparation.py | # importing modules/ libraries
import pandas as pd
import numpy as np
orders_prior_df = pd.read_csv('Data/orders_prior_sample.csv')
print('length of orders_prior_df:', len(orders_prior_df))
order_products_prior_df = pd.read_csv('Data/order_products_prior_sample.csv')
print('length of order_products_prior_df:', len(or... | # importing modules/ libraries
import pandas as pd
import numpy as np
orders_prior_df = pd.read_csv('Data/orders_prior_sample.csv')
order_products_prior_df = pd.read_csv('Data/order_products_prior_sample.csv')
grouped = order_products_prior_df.groupby('order_id', as_index = False)
grouped_data = pd.DataFrame()
gro... | Merge prior order_to_card_order with order id | feat: Merge prior order_to_card_order with order id
| Python | mit | rjegankumar/instacart_prediction_model | ---
+++
@@ -3,12 +3,10 @@
import numpy as np
orders_prior_df = pd.read_csv('Data/orders_prior_sample.csv')
-print('length of orders_prior_df:', len(orders_prior_df))
order_products_prior_df = pd.read_csv('Data/order_products_prior_sample.csv')
-print('length of order_products_prior_df:', len(order_products_pri... |
314a4088e65f8d9f619b9ddcf53e339ced11124e | app/eve_proxy/views.py | app/eve_proxy/views.py | from django.core.urlresolvers import reverse
from django.http import HttpResponse, HttpResponseNotFound, HttpResponseServerError
from django.views.generic import View
from eve_proxy.models import CachedDocument
class EVEAPIProxyView(View):
"""Allows for standard EVE API calls to be proxied through your applicati... | from django.core.urlresolvers import reverse
from django.http import HttpResponse, HttpResponseNotFound, HttpResponseServerError
from django.views.generic import View
from eve_proxy.models import CachedDocument
class EVEAPIProxyView(View):
"""Allows for standard EVE API calls to be proxied through your applicati... | Fix authenticated calls for APIs already in the DB | Fix authenticated calls for APIs already in the DB
| Python | bsd-3-clause | nikdoof/test-auth | ---
+++
@@ -25,7 +25,7 @@
return HttpResponse('No Service ID provided.')
#try:
- cached_doc = CachedDocument.objects.api_query(url_path, params, exceptions=False)
+ cached_doc = CachedDocument.objects.api_query(url_path, dict(params), exceptions=False)
#except:
... |
402075770c43be3505bf6c38b713175fe8c202b4 | seleniumbase/config/proxy_list.py | seleniumbase/config/proxy_list.py | """
Proxy Server "Phone Book".
Simplify running browser tests through a proxy server
by adding your frequently-used proxies here.
Now you can do something like this on the command line:
"pytest SOME_TEST.py --proxy=proxy1"
Format of PROXY_LIST server entries:
* "ip_address:port" OR "username:password@ip_address:po... | """
Proxy Server "Phone Book".
Simplify running browser tests through a proxy server
by adding your frequently-used proxies here.
Now you can do something like this on the command line:
"pytest SOME_TEST.py --proxy=proxy1"
Format of PROXY_LIST server entries:
* "ip_address:port" OR "username:password@ip_address:po... | Refresh the proxy example list | Refresh the proxy example list
| Python | mit | mdmintz/SeleniumBase,seleniumbase/SeleniumBase,seleniumbase/SeleniumBase,mdmintz/SeleniumBase,seleniumbase/SeleniumBase,mdmintz/SeleniumBase,seleniumbase/SeleniumBase,mdmintz/SeleniumBase | ---
+++
@@ -21,7 +21,6 @@
PROXY_LIST = {
"example1": "52.187.121.7:3128", # (Example) - set your own proxy here
"example2": "193.32.6.6:8080", # (Example) - set your own proxy here
- "example3": "185.204.208.78:8080", # (Example) - set your own proxy here
"proxy1": None,
"proxy2": None,
... |
86a26e7e6e37e5414511caef27888ec0aa019ca4 | imap_cli/imap/fetch.py | imap_cli/imap/fetch.py | # -*- coding: utf-8 -*-
"""IMAP lib fetch helpers"""
import collections
import logging
import os
from imap_cli import const
app_name = os.path.splitext(os.path.basename(__file__))[0]
log = logging.getLogger(app_name)
def fetch(ctx, message_set=None, message_parts=None):
"""Return mails corresponding to mai... | # -*- coding: utf-8 -*-
"""IMAP lib fetch helpers"""
import collections
import logging
import os
from imap_cli import const
app_name = os.path.splitext(os.path.basename(__file__))[0]
log = logging.getLogger(app_name)
def fetch(ctx, message_set=None, message_parts=None):
"""Return mails corresponding to mai... | Read mail given a UID instead of mail_id | Read mail given a UID instead of mail_id
| Python | mit | Gentux/imap-cli,Gentux/imap-cli | ---
+++
@@ -34,6 +34,6 @@
request_message_parts = '({})'.format(' '.join(message_parts)
if isinstance(message_parts, collections.Iterable)
else message_parts)
- typ, data = ctx.mail_account.fetch(request_message_set, request... |
23ce6ba3c22ec05caa4bdfa4714667929ecaaa76 | tests/test_index.py | tests/test_index.py | """Unit Testing for Index view."""
import pytest
@pytest.mark.usefixtures("session", "test_app")
class TestIndex:
"""Test the index page call."""
def test_index(self, test_app):
"""Test that the index returns a html doc."""
rv = test_app.get('/')
assert "<!DOCTYPE html>" in rv.data
| """Unit Testing for Index view."""
import pytest
@pytest.mark.usefixtures("session", "test_app")
class TestIndex:
"""Test the index page call."""
def test_index(self, test_app):
"""Test that the index returns a html doc."""
rv = test_app.get('/')
assert b'<!DOCTYPE html>' in rv.data
| Fix for inspecting app get data | Fix for inspecting app get data
Needed a binary string comparision
| Python | mit | paulaylingdev/blogsite,paulaylingdev/blogsite | ---
+++
@@ -9,4 +9,4 @@
def test_index(self, test_app):
"""Test that the index returns a html doc."""
rv = test_app.get('/')
- assert "<!DOCTYPE html>" in rv.data
+ assert b'<!DOCTYPE html>' in rv.data |
a33957db32006d663112a1e6a7f0832bb0bdbedd | zerver/management/commands/process_signups.py | zerver/management/commands/process_signups.py | from __future__ import absolute_import
from postmonkey import PostMonkey
from django.core.management.base import BaseCommand
from django.conf import settings
from zerver.lib.queue import SimpleQueueClient
class Command(BaseCommand):
pm = PostMonkey(settings.MAILCHIMP_API_KEY, timeout=10)
def subscribe(self,... | from __future__ import absolute_import
from postmonkey import PostMonkey, MailChimpException
from django.core.management.base import BaseCommand
from django.conf import settings
import logging
from zerver.lib.queue import SimpleQueueClient
class Command(BaseCommand):
pm = PostMonkey(settings.MAILCHIMP_API_KEY, ... | Handle mailchimp error 214 (duplicate email) in signup worker | Handle mailchimp error 214 (duplicate email) in signup worker
(imported from commit cb34c153fc96bca7c8faed01d019aa2433fcf568)
| Python | apache-2.0 | esander91/zulip,peiwei/zulip,so0k/zulip,johnnygaddarr/zulip,bastianh/zulip,bastianh/zulip,brainwane/zulip,eastlhu/zulip,verma-varsha/zulip,PhilSk/zulip,grave-w-grave/zulip,jeffcao/zulip,PhilSk/zulip,karamcnair/zulip,swinghu/zulip,sup95/zulip,aakash-cr7/zulip,MariaFaBella85/zulip,kaiyuanheshang/zulip,samatdav/zulip,dawr... | ---
+++
@@ -1,8 +1,10 @@
from __future__ import absolute_import
-from postmonkey import PostMonkey
+from postmonkey import PostMonkey, MailChimpException
from django.core.management.base import BaseCommand
from django.conf import settings
+
+import logging
from zerver.lib.queue import SimpleQueueClient
@@ -... |
420307bcbd846e746d1a203115e0f5c21d8068e4 | api/guids/views.py | api/guids/views.py | from django import http
from rest_framework.exceptions import NotFound
from rest_framework import permissions as drf_permissions
from framework.guid.model import Guid
from framework.auth.oauth_scopes import CoreScopes, ComposedScopes
from api.base.exceptions import EndpointNotImplementedError
from api.base import perm... | from django import http
from rest_framework.exceptions import NotFound
from rest_framework import permissions as drf_permissions
from framework.guid.model import Guid
from framework.auth.oauth_scopes import CoreScopes, ComposedScopes
from api.base.exceptions import EndpointNotImplementedError
from api.base import perm... | Add documentation to the /v2/guids/<guid> endpoint | Add documentation to the /v2/guids/<guid> endpoint
| Python | apache-2.0 | kwierman/osf.io,jnayak1/osf.io,monikagrabowska/osf.io,caseyrollins/osf.io,DanielSBrown/osf.io,doublebits/osf.io,asanfilippo7/osf.io,mfraezz/osf.io,pattisdr/osf.io,aaxelb/osf.io,DanielSBrown/osf.io,RomanZWang/osf.io,TomHeatwole/osf.io,chrisseto/osf.io,TomBaxter/osf.io,CenterForOpenScience/osf.io,TomBaxter/osf.io,cslzche... | ---
+++
@@ -10,6 +10,16 @@
class GuidRedirect(JSONAPIBaseView):
+ """Find an item by its guid.
+
+ This endpoint will redirect you to the most appropriate URL given an OSF GUID. For example, /v2/guids/{node_id},
+ will redirect to /v2/nodes/{node_id} while /v2/guids/{user_id} will redirect to /v2/users/... |
4644255816c8657b6578754b42fe7b9c2a7d4715 | haystack_panel/__init__.py | haystack_panel/__init__.py | # -*- coding: utf-8 -*-
"""
haystack_panel
~~~~~~~~~~~~~~
:copyright: (c) 2012 by Chris Streeter.
:license: See LICENSE for more details.
"""
import pkg_resources
try:
__version__ = pkg_resources.get_distribution('haystack_panel').version
except Exception, e:
__version__ = 'unknown'
__title__ = 'haystack... | # -*- coding: utf-8 -*-
"""
haystack_panel
~~~~~~~~~~~~~~
:copyright: (c) 2014 by Chris Streeter.
:license: See LICENSE for more details.
"""
import pkg_resources
try:
__version__ = pkg_resources.get_distribution('haystack_panel').version
except Exception, e:
__version__ = 'unknown'
__title__ = 'haystack... | Update copyright date and fix my name | Update copyright date and fix my name
| Python | mit | streeter/django-haystack-panel | ---
+++
@@ -4,7 +4,7 @@
haystack_panel
~~~~~~~~~~~~~~
-:copyright: (c) 2012 by Chris Streeter.
+:copyright: (c) 2014 by Chris Streeter.
:license: See LICENSE for more details.
"""
@@ -19,6 +19,6 @@
__title__ = 'haystack_panel'
__author__ = 'Chris Streeter'
-__copyright__ = 'Copyright 2012 Chris Streter'
+... |
5cc511e2e7d685fe8c2983c14d42a4fcfa704c6b | heufybot/utils/__init__.py | heufybot/utils/__init__.py | # Taken from txircd:
# https://github.com/ElementalAlchemist/txircd/blob/8832098149b7c5f9b0708efe5c836c8160b0c7e6/txircd/utils.py#L9
def _enum(**enums):
return type('Enum', (), enums)
ModeType = _enum(LIST=0, PARAM_SET=1, PARAM_UNSET=2, NO_PARAM=3)
ModuleLoadType = _enum(LOAD=0, UNLOAD=1, ENABLE=2, DISABLE=3)
def... | # Taken from txircd:
# https://github.com/ElementalAlchemist/txircd/blob/8832098149b7c5f9b0708efe5c836c8160b0c7e6/txircd/utils.py#L9
def _enum(**enums):
return type('Enum', (), enums)
ModeType = _enum(LIST=0, PARAM_SET=1, PARAM_UNSET=2, NO_PARAM=3)
ModuleLoadType = _enum(LOAD=0, UNLOAD=1, ENABLE=2, DISABLE=3)
def... | Add a helper function to grab network names | Add a helper function to grab network names
| Python | mit | Heufneutje/PyHeufyBot,Heufneutje/PyHeufyBot | ---
+++
@@ -23,3 +23,6 @@
# Not all "users" have idents and hostnames
nick = prefix
return nick, None, None
+
+def networkName(bot, server):
+ return bot.servers[server].supportHelper.network |
2240342e941f850d93cc6606007121159e3eb362 | surveys/tests.py | surveys/tests.py | from django.test import TestCase
from studygroups.models import Course
from .community_feedback import calculate_course_ratings
class TestCommunityFeedback(TestCase):
fixtures = ['test_courses.json', 'test_studygroups.json', 'test_applications.json', 'test_survey_responses.json']
def test_calculate_course_r... | from django.test import TestCase
from studygroups.models import Course
from .community_feedback import calculate_course_ratings
import json
class TestCommunityFeedback(TestCase):
fixtures = ['test_courses.json', 'test_studygroups.json', 'test_applications.json', 'test_survey_responses.json']
def test_calcul... | Update test to compare dictionaries, rather than json string | Update test to compare dictionaries, rather than json string
| Python | mit | p2pu/learning-circles,p2pu/learning-circles,p2pu/learning-circles,p2pu/learning-circles | ---
+++
@@ -2,6 +2,7 @@
from studygroups.models import Course
from .community_feedback import calculate_course_ratings
+import json
class TestCommunityFeedback(TestCase):
@@ -16,9 +17,10 @@
calculate_course_ratings(course)
- expected_rating_step_counts = '{"5": 2, "4": 1, "3": 0, "2": 0, ... |
981e576635ed1830a30fd65e65d745825f73342a | nova/db/sqlalchemy/migrate_repo/versions/034_change_instance_id_in_migrations.py | nova/db/sqlalchemy/migrate_repo/versions/034_change_instance_id_in_migrations.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 OpenStack LLC.
# 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/... | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 OpenStack LLC.
# 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/... | Delete FK before dropping instance_id column. | Delete FK before dropping instance_id column. | Python | apache-2.0 | Juniper/nova,Francis-Liu/animated-broccoli,yrobla/nova,ruslanloman/nova,zhimin711/nova,mikalstill/nova,maoy/zknova,redhat-openstack/nova,adelina-t/nova,mandeepdhami/nova,maoy/zknova,russellb/nova,j-carpentier/nova,usc-isi/extra-specs,psiwczak/openstack,tudorvio/nova,apporc/nova,vladikr/nova_drafts,tudorvio/nova,houshen... | ---
+++
@@ -15,7 +15,9 @@
# License for the specific language governing permissions and limitations
# under the License.from sqlalchemy import *
-from sqlalchemy import Column, Integer, String, MetaData, Table
+from sqlalchemy import Column, ForeignKeyConstraint, Integer, String
+from sqlalchemy import Meta... |
98fe7592af636e0f9c4e7017a1502b7d3539dd6c | src/ggrc/migrations/versions/20160510122526_44ebc240800b_remove_response_relationships.py | src/ggrc/migrations/versions/20160510122526_44ebc240800b_remove_response_relationships.py | # Copyright (C) 2016 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: goodson@google.com
# Maintained By: goodson@google.com
"""
Remove relationships related to deleted response objects
Create Date: 2016-05-10 12:25:... | # Copyright (C) 2016 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: goodson@google.com
# Maintained By: goodson@google.com
"""
Remove relationships related to deleted response objects
Create Date: 2016-05-10 12:25:... | Change use of quotation marks | Change use of quotation marks
| Python | apache-2.0 | josthkko/ggrc-core,edofic/ggrc-core,kr41/ggrc-core,edofic/ggrc-core,j0gurt/ggrc-core,VinnieJohns/ggrc-core,NejcZupec/ggrc-core,VinnieJohns/ggrc-core,j0gurt/ggrc-core,plamut/ggrc-core,selahssea/ggrc-core,j0gurt/ggrc-core,kr41/ggrc-core,AleksNeStu/ggrc-core,josthkko/ggrc-core,selahssea/ggrc-core,andrei-karalionak/ggrc-co... | ---
+++
@@ -23,13 +23,15 @@
def upgrade():
"""Upgrade database schema and/or data, creating a new revision."""
op.execute(
- 'DELETE FROM relationships '
- 'WHERE source_type IN '
- ' ("Response", "DocumentationResponse", "InterviewResponse",'
- ' "PopulationSampleResponse") ... |
8ac0582ad601bbe2db3c21d0e4f578a7f8178f74 | pox.py | pox.py | #!/usr/bin/python
from pox.core import core
import pox.openflow.openflow
import pox.topology.topology
import pox.openflow.of_01
import pox.dumb_l3_switch.dumb_l3_switch
# Set default log level
import logging
logging.basicConfig(level=logging.DEBUG)
# Turn on extra info for event exceptions
import pox.lib.revent.reve... | #!/usr/bin/python
from pox.core import core
import pox.openflow.openflow
import pox.topology.topology
import pox.openflow.of_01
import pox.dumb_l3_switch.dumb_l3_switch
# Set default log level
import logging
logging.basicConfig(level=logging.DEBUG)
# Turn on extra info for event exceptions
import pox.lib.revent.reve... | Put some useful stuff into CLI's locals | Put some useful stuff into CLI's locals
| Python | apache-2.0 | chenyuntc/pox,kulawczukmarcin/mypox,denovogroup/pox,chenyuntc/pox,andiwundsam/_of_normalize,waltznetworks/pox,xAKLx/pox,kulawczukmarcin/mypox,pthien92/sdn,noxrepo/pox,noxrepo/pox,PrincetonUniversity/pox,denovogroup/pox,carlye566/IoT-POX,xAKLx/pox,pthien92/sdn,VamsikrishnaNallabothu/pox,jacobq/csci5221-viro-project,Vams... | ---
+++
@@ -32,5 +32,5 @@
traceback.print_exc()
import code
- code.interact('Ready.')
+ code.interact('Ready.', local=locals())
pox.core.core.quit() |
23e1d5d8dbac5bba45f50092d4d10aba6e0ed730 | cortex/__init__.py | cortex/__init__.py | from .dataset import Dataset, Volume, Vertex, VolumeRGB, VertexRGB, Volume2D, Vertex2D
from . import align, volume, quickflat, webgl, segment, options
from .database import db
from .utils import *
from .quickflat import make_figure as quickshow
load = Dataset.from_file
try:
from . import webgl
from .webgl import sh... | from .dataset import Dataset, Volume, Vertex, VolumeRGB, VertexRGB, Volume2D, Vertex2D
from . import align, volume, quickflat, webgl, segment, options
from .database import db
from .utils import *
from .quickflat import make_figure as quickshow
try:
from . import formats
except ImportError:
raise ImportError("You ar... | Add warning for source directory import | Add warning for source directory import
| Python | bsd-2-clause | gallantlab/pycortex,gallantlab/pycortex,gallantlab/pycortex,gallantlab/pycortex,gallantlab/pycortex | ---
+++
@@ -3,6 +3,11 @@
from .database import db
from .utils import *
from .quickflat import make_figure as quickshow
+
+try:
+ from . import formats
+except ImportError:
+ raise ImportError("You are running pycortex from the source directory. Don't do that!")
load = Dataset.from_file
|
3d974d0fd2e98e8030a04cf1dfbb7e05d2dd7539 | tests/ml/test_fasttext_helpers.py | tests/ml/test_fasttext_helpers.py | import pandas
import unittest
import cocoscore.ml.fasttext_helpers as fth
class CVTest(unittest.TestCase):
def test_train_call_parameters(self):
pass
if __name__ == '__main__':
unittest.main()
| import pandas
import unittest
import cocoscore.ml.fasttext_helpers as fth
class CVTest(unittest.TestCase):
train_path = 'ft_simple_test.txt'
ft_path = '/home/lib/fastText'
model_path = 'testmodel'
def test_train_call_parameters(self):
train_call, compress_call = fth.get_fasttext_train_calls(... | Add testcase for correct fastText predict and compress calls | Add testcase for correct fastText predict and compress calls
| Python | mit | JungeAlexander/cocoscore | ---
+++
@@ -5,9 +5,18 @@
class CVTest(unittest.TestCase):
+ train_path = 'ft_simple_test.txt'
+ ft_path = '/home/lib/fastText'
+ model_path = 'testmodel'
def test_train_call_parameters(self):
- pass
+ train_call, compress_call = fth.get_fasttext_train_calls(self.train_path, {'-aaa':... |
5d136086e8bdc222cf2ec51f2ad23e2746c5c2b7 | Recording/save/replay.py | Recording/save/replay.py | import h5py
import time
from SimpleCV import Image
recordFilename = '20130727_17h34_simpleTrack'
print recordFilename + '.hdf5'
#recordFile = h5py.File('20130722_21h53_simpleTrack.hdf5')
recordFile = h5py.File(recordFilename + '.hdf5', 'r')
imgs = recordFile.get('image')
img = imgs[100,:,:,:]
r = img[:,:,0]
g = img[:,... | import h5py
import time
import sys
from SimpleCV import Image, Display
#recordFilename = '/media/bat/DATA/Baptiste/Nautilab/kite_project/robokite/ObjectTracking/filming_small_kite_20130805_14h03_simpleTrack.hdf5'
print('')
print('This script is used to display the images saved in hdf5 file generated by simpleTrack.py ... | Increase display size Use argument for filename Make a movie from images | Increase display size
Use argument for filename
Make a movie from images
| Python | mit | baptistelabat/robokite,baptistelabat/robokite,baptistelabat/robokite,baptistelabat/robokite,baptistelabat/robokite,baptistelabat/robokite,baptistelabat/robokite,baptistelabat/robokite | ---
+++
@@ -1,16 +1,37 @@
import h5py
import time
-from SimpleCV import Image
-recordFilename = '20130727_17h34_simpleTrack'
-print recordFilename + '.hdf5'
-#recordFile = h5py.File('20130722_21h53_simpleTrack.hdf5')
-recordFile = h5py.File(recordFilename + '.hdf5', 'r')
+import sys
+from SimpleCV import Image, Di... |
55ebad2bd0e47f8806154e8db4f160847db33add | example.py | example.py | from ADIF_log import ADIF_log
import datetime
import os
# Create a new log...
log = ADIF_log('Py-ADIF Example')
entry = log.newEntry()
# New entry from K6BSD to WD1CKS
entry['OPerator'] = 'K6BSD'
entry['Call'] = 'WD1CKS'
entry['QSO_Date']=datetime.datetime.now().strftime('%Y%m%d')
entry['baNd']='20M'
entry['mODe']='P... | from ADIF_log import ADIF_log
import datetime
import os
# Create a new log...
log = ADIF_log('Py-ADIF Example')
entry = log.newEntry()
# New entry from K6BSD to WD1CKS
entry['OPerator'] = 'K6BSD'
entry['Call'] = 'WD1CKS'
entry['QSO_Date']=datetime.datetime.now().strftime('%Y%m%d')
entry['baNd']='20M'
entry['mODe']='P... | Use differing cases after reading the log back... case is still insensitve. | Use differing cases after reading the log back... case is still insensitve.
| Python | bsd-2-clause | K6BSD/Py-ADIF | ---
+++
@@ -31,7 +31,7 @@
# Read example.adx back...
newlog = ADIF_log('Py-ADIF Example', file='example.adx')
-print newlog[0]['CALL'],' band: ',newlog[0]['BAND']
+print newlog[0]['call'],' band: ',newlog[0]['band']
# Clean up... nothing interesting here...
os.remove('example.adif') |
ca50295c71432dde32eff813e5bd05b7a8e40ad1 | cdflib/__init__.py | cdflib/__init__.py | import os
from . import cdfread
from . import cdfwrite
from .epochs import CDFepoch as cdfepoch
# This function determines if we are reading or writing a file
def CDF(path, cdf_spec=None, delete=False, validate=None):
if (os.path.exists(path)):
if delete:
os.remove(path)
return
... | import os
from . import cdfread
from . import cdfwrite
from .epochs import CDFepoch as cdfepoch
# This function determines if we are reading or writing a file
def CDF(path, cdf_spec=None, delete=False, validate=None):
path = os.path.expanduser(path)
if (os.path.exists(path)):
if delete:
o... | Expand user path when reading CDF | Expand user path when reading CDF
| Python | mit | MAVENSDC/cdflib | ---
+++
@@ -7,6 +7,7 @@
def CDF(path, cdf_spec=None, delete=False, validate=None):
+ path = os.path.expanduser(path)
if (os.path.exists(path)):
if delete:
os.remove(path) |
07225cc0d019bb47e9d250f17639804242efcaa8 | sea/contrib/extensions/celery/cmd.py | sea/contrib/extensions/celery/cmd.py | import sys
from celery.__main__ import main as celerymain
from sea import create_app
from sea.cli import jobm
def celery(argv, app):
if argv[0] == "inspect":
from sea.contrib.extensions.celery import empty_celeryapp
empty_celeryapp.load_config(app)
sys.argv = (
["celery"] + a... | import sys
from celery.__main__ import main as celerymain
from sea import create_app
from sea.cli import jobm
def celery(argv, app):
if argv[0] == "inspect":
from sea.contrib.extensions.celery import empty_celeryapp
empty_celeryapp.load_config(app)
sys.argv = (
["celery"]
... | Change the ordering of celery global options | Change the ordering of celery global options
| Python | mit | shanbay/sea,yandy/sea,yandy/sea | ---
+++
@@ -11,13 +11,16 @@
from sea.contrib.extensions.celery import empty_celeryapp
empty_celeryapp.load_config(app)
sys.argv = (
- ["celery"] + argv
+ ["celery"]
+ ["-A", "sea.contrib.extensions.celery.empty_celeryapp.capp"]
+ + argv
... |
001c955ffe8aef9ea3f0c6c5bcf8a857c3c10aeb | securethenews/sites/wagtail_hooks.py | securethenews/sites/wagtail_hooks.py | from wagtail.contrib.modeladmin.options import ModelAdmin, modeladmin_register
from .models import Site
class SiteAdmin(ModelAdmin):
model = Site
menu_label = 'News Sites'
menu_icon = 'site'
add_to_settings_menu = False
list_display = ('name', 'domain', 'score')
def score(self, obj):
... | from wagtail.contrib.modeladmin.options import ModelAdmin, modeladmin_register
from .models import Site
class SiteAdmin(ModelAdmin):
model = Site
menu_label = 'News Sites'
menu_icon = 'site'
add_to_settings_menu = False
list_display = ('name', 'domain', 'score', 'grade')
def score(self, obj... | Add grade to list display for News Sites | Add grade to list display for News Sites
| Python | agpl-3.0 | freedomofpress/securethenews,DNSUsher/securethenews,freedomofpress/securethenews,DNSUsher/securethenews,freedomofpress/securethenews,freedomofpress/securethenews,DNSUsher/securethenews | ---
+++
@@ -9,12 +9,16 @@
menu_icon = 'site'
add_to_settings_menu = False
- list_display = ('name', 'domain', 'score')
+ list_display = ('name', 'domain', 'score', 'grade')
def score(self, obj):
return '{} / 100'.format(obj.scans.latest().score)
score.short_description = 'Score'... |
648c2af40cd6cae40eafadd2233802543ec70472 | zipview/views.py | zipview/views.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import zipfile
from django.views.generic import View
from django.http import HttpResponse
from django.core.files.base import ContentFile
from django.utils.six import b
class BaseZipView(View):
"""A base view to zip and stream several files."""
... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import zipfile
from django.views.generic import View
from django.http import HttpResponse
from django.core.files.base import ContentFile
from django.utils.six import b
class BaseZipView(View):
"""A base view to zip and stream several files."""
... | Remove debug code commited by mistake | Remove debug code commited by mistake
| Python | mit | thibault/django-zipview | ---
+++
@@ -21,7 +21,6 @@
raise NotImplementedError()
def get_archive_name(self, request):
- import pdb; pdb.set_trace()
return self.zipfile_name
def get(self, request, *args, **kwargs): |
3974760a4406060061017f03bb7eabe5b1937a23 | keystone/contrib/s3/core.py | keystone/contrib/s3/core.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
"""Main entry point into the S3 Credentials service.
TODO-DOCS
"""
import base64
import hmac
from hashlib import sha1
from keystone import config
from keystone.common import wsgi
from keystone.contrib import ec2
CONF = config.CONF
def check_signature(creds_ref, creden... | # vim: tabstop=4 shiftwidth=4 softtabstop=4
"""Main entry point into the S3 Credentials service.
TODO-DOCS
"""
import base64
import hmac
from hashlib import sha1
from keystone import config
from keystone.common import wsgi
from keystone.contrib import ec2
CONF = config.CONF
class S3Extension(wsgi.ExtensionRoute... | Make it as a subclass. | Make it as a subclass.
as advised by termie make it as a subclass instead of patching the
method.
| Python | apache-2.0 | rajalokan/keystone,dsiddharth/access-keys,townbull/keystone-dtrust,klmitch/keystone,cbrucks/keystone_ldap,openstack/keystone,promptworks/keystone,takeshineshiro/keystone,ilay09/keystone,openstack/keystone,openstack/keystone,rodrigods/keystone,rickerc/keystone_audit,ging/keystone,dstanek/keystone,klmitch/keystone,reeshu... | ---
+++
@@ -17,27 +17,21 @@
CONF = config.CONF
-def check_signature(creds_ref, credentials):
- signature = credentials['signature']
- msg = base64.urlsafe_b64decode(str(credentials['token']))
- key = str(creds_ref['secret'])
- signed = base64.encodestring(hmac.new(key, msg, sha1).digest()).strip()
-
... |
6f13946610745e348816e156c1c575d3ccd7ef8c | event_registration_analytic/models/sale_order.py | event_registration_analytic/models/sale_order.py | # -*- coding: utf-8 -*-
# (c) 2016 Alfredo de la Fuente - AvanzOSC
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
from openerp import api, models
class SaleOrder(models.Model):
_inherit = 'sale.order'
@api.multi
def action_button_confirm(self):
project_obj = self.env['project.pr... | # -*- coding: utf-8 -*-
# (c) 2016 Alfredo de la Fuente - AvanzOSC
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
from openerp import api, models
class SaleOrder(models.Model):
_inherit = 'sale.order'
@api.multi
def action_button_confirm(self):
project_obj = self.env['project.pr... | Fix bug when in sales order lines there is a nonrecurring service. | [FIX] event_registration_analytic: Fix bug when in sales order lines there is a nonrecurring service.
| Python | agpl-3.0 | avanzosc/event-wip | ---
+++
@@ -12,13 +12,14 @@
project_obj = self.env['project.project']
event_obj = self.env['event.event']
res = super(SaleOrder, self).action_button_confirm()
- cond = [('analytic_account_id', '=', self.project_id.id)]
- project = project_obj.search(cond, limit=1)
- con... |
e6ed108a655b4eb1ef4ba78e66eceacaab304414 | config/__init__.py | config/__init__.py | """
This module is responsible for handling configuration and files related to it,
including calibration parameters.
"""
import configparser
import os
"""
Default options
"""
#TODO: more default options...
_CONFIG_DEFAULTS = {
"paths": {
# default database path is ../db/test.db relative to this file
... | """
This module is responsible for handling configuration and files related to it,
including calibration parameters.
"""
import configparser
import os
"""
Default options
"""
#TODO: more default options...
_CONFIG_DEFAULTS = {
"paths": {
# default database path is ../db/test.db relative to this file
... | Add some calibration default values. | Add some calibration default values.
| Python | mit | mgunyho/kiltiskahvi | ---
+++
@@ -17,6 +17,11 @@
"db_path": os.path.join(
os.path.dirname(os.path.dirname(__file__)),
"db/test.db"),
+ },
+
+ "calibration" : {
+ "sensor_min_value" : 0,
+ "sensor_max_value" : 1024,
},
} |
47cffaad7aa484ea6f291d160bbf18d875a30f68 | edx_course_discovery/settings/production.py | edx_course_discovery/settings/production.py | from os import environ
import yaml
from edx_course_discovery.settings.base import *
from edx_course_discovery.settings.utils import get_env_setting
DEBUG = False
TEMPLATE_DEBUG = DEBUG
ALLOWED_HOSTS = ['*']
LOGGING = environ.get('LOGGING', LOGGING)
CONFIG_FILE = get_env_setting('EDX_COURSE_DISCOVERY_CFG')
with op... | from os import environ
import yaml
from edx_course_discovery.settings.base import *
from edx_course_discovery.settings.utils import get_env_setting
DEBUG = False
TEMPLATE_DEBUG = DEBUG
ALLOWED_HOSTS = ['*']
LOGGING = environ.get('LOGGING', LOGGING)
CONFIG_FILE = get_env_setting('COURSE_DISCOVERY_CFG')
with open(C... | Fix the name of the COURSE_DISCOVERY_CFG variable to match what is configured in edx/configuration | Fix the name of the COURSE_DISCOVERY_CFG variable to match what is configured in edx/configuration
| Python | agpl-3.0 | edx/course-discovery,cpennington/course-discovery,edx/course-discovery,edx/course-discovery,edx/course-discovery | ---
+++
@@ -12,7 +12,7 @@
LOGGING = environ.get('LOGGING', LOGGING)
-CONFIG_FILE = get_env_setting('EDX_COURSE_DISCOVERY_CFG')
+CONFIG_FILE = get_env_setting('COURSE_DISCOVERY_CFG')
with open(CONFIG_FILE) as f:
config_from_yaml = yaml.load(f)
vars().update(config_from_yaml) |
733890e0267d07c4d312427a30f136589a85626e | loom/test/test_benchmark.py | loom/test/test_benchmark.py | import loom.benchmark
DATASET = 'dd-100-100-0.5'
def test_shuffle():
loom.benchmark.shuffle(DATASET, profile=None)
def test_infer():
loom.benchmark.infer(DATASET, profile=None)
def test_checkpoint():
loom.benchmark.load_checkpoint(DATASET)
loom.benchmark.infer_checkpoint(DATASET, profile=None)
... | import loom.benchmark
DATASET = 'dd-100-100-0.5'
def test_shuffle():
loom.benchmark.shuffle(DATASET, profile=None)
def test_infer():
loom.benchmark.infer(DATASET, profile=None)
def test_checkpoint():
loom.benchmark.load_checkpoint(DATASET, period_sec=1)
loom.benchmark.infer_checkpoint(DATASET, pr... | Reduce test checkpoint period for faster tests | Reduce test checkpoint period for faster tests
| Python | bsd-3-clause | posterior/loom,priorknowledge/loom,posterior/loom,priorknowledge/loom,fritzo/loom,priorknowledge/loom,posterior/loom,fritzo/loom,fritzo/loom | ---
+++
@@ -12,7 +12,7 @@
def test_checkpoint():
- loom.benchmark.load_checkpoint(DATASET)
+ loom.benchmark.load_checkpoint(DATASET, period_sec=1)
loom.benchmark.infer_checkpoint(DATASET, profile=None)
|
8872d476f146505b40e4734a5872863a4e1ece50 | ddsc_incron/notify.py | ddsc_incron/notify.py | from __future__ import absolute_import
import logging.config
import os
import sys
from ddsc_incron.celery import celery
from ddsc_incron.settings import LOGGING
def main():
logging.config.dictConfig(LOGGING)
logger = logging.getLogger("ddsc_incron.notify")
logger.info("New file to import: {0}".format(
... | from __future__ import absolute_import
import logging.config
import os
import sys
from ddsc_incron.celery import celery
from ddsc_incron.settings import LOGGING
def main():
logging.config.dictConfig(LOGGING)
logger = logging.getLogger("ddsc_incron.notify")
logger.info("New file to import: {0}".format(
... | Correct module name in send_task | Correct module name in send_task
| Python | mit | ddsc/ddsc-incron | ---
+++
@@ -14,7 +14,7 @@
logger.info("New file to import: {0}".format(
os.path.join(sys.argv[1], sys.argv[2]))
)
- celery.send_task("ddsc_worker.importer.new_file_detected",
+ celery.send_task("ddsc_worker.tasks.new_file_detected",
kwargs={'pathDir': (sys.argv[1] + '/'), 'fileName':... |
a818fa21ed03161a24974b4980d633a724482ec6 | dimod/package_info.py | dimod/package_info.py | __version__ = '1.0.0.dev7'
__author__ = 'D-Wave Systems Inc.'
__authoremail__ = 'acondello@dwavesys.com'
__description__ = 'A shared API for binary quadratic model samplers.'
| __version__ = '0.6.0.dev'
__author__ = 'D-Wave Systems Inc.'
__authoremail__ = 'acondello@dwavesys.com'
__description__ = 'A shared API for binary quadratic model samplers.'
| Update version 1.0.0.dev7 -> 0.6.0.dev | Update version 1.0.0.dev7 -> 0.6.0.dev
| Python | apache-2.0 | oneklc/dimod,oneklc/dimod | ---
+++
@@ -1,4 +1,4 @@
-__version__ = '1.0.0.dev7'
+__version__ = '0.6.0.dev'
__author__ = 'D-Wave Systems Inc.'
__authoremail__ = 'acondello@dwavesys.com'
__description__ = 'A shared API for binary quadratic model samplers.' |
cb0f732545ea851af46a7c96525d6b5b418b8673 | chatterbot/__init__.py | chatterbot/__init__.py | """
ChatterBot is a machine learning, conversational dialog engine.
"""
from .chatterbot import ChatBot
__version__ = '0.7.1'
__author__ = 'Gunther Cox'
__email__ = 'gunthercx@gmail.com'
__url__ = 'https://github.com/gunthercox/ChatterBot'
__all__ = (
'ChatBot',
)
| """
ChatterBot is a machine learning, conversational dialog engine.
"""
from .chatterbot import ChatBot
__version__ = '0.7.2'
__author__ = 'Gunther Cox'
__email__ = 'gunthercx@gmail.com'
__url__ = 'https://github.com/gunthercox/ChatterBot'
__all__ = (
'ChatBot',
)
| Update release version to 0.7.2 | Update release version to 0.7.2 | Python | bsd-3-clause | vkosuri/ChatterBot,gunthercox/ChatterBot | ---
+++
@@ -3,7 +3,7 @@
"""
from .chatterbot import ChatBot
-__version__ = '0.7.1'
+__version__ = '0.7.2'
__author__ = 'Gunther Cox'
__email__ = 'gunthercx@gmail.com'
__url__ = 'https://github.com/gunthercox/ChatterBot' |
4e42f231c28501442666137bf270fdfcc22c9da9 | micropress/views.py | micropress/views.py | from django.views.generic.list_detail import object_list, object_detail
import models
def _limit_articles(realm_object_id=None, realm_slug=None,
realm_slug_field='slug', **kwargs):
queryset = models.Article.objects.all()
if realm_object_id:
queryset = queryset.filter(realm__pk=real... | from django.views.generic.list_detail import object_list, object_detail
import models
def _limit_articles(realm_object_id=None, realm_slug=None,
realm_slug_field='realm__slug', **kwargs):
queryset = models.Article.objects.all()
if realm_object_id:
queryset = queryset.filter(realm__... | Fix realm_slug_field to follow a join back to the realm's slug field. | Fix realm_slug_field to follow a join back to the realm's slug field.
| Python | mit | jbradberry/django-micro-press,jbradberry/django-micro-press | ---
+++
@@ -3,7 +3,7 @@
def _limit_articles(realm_object_id=None, realm_slug=None,
- realm_slug_field='slug', **kwargs):
+ realm_slug_field='realm__slug', **kwargs):
queryset = models.Article.objects.all()
if realm_object_id:
queryset = queryset.filter(rea... |
ddeabd76c4277c35d1e583d1a2034ba2c047d128 | spacy/__init__.py | spacy/__init__.py | import pathlib
from .util import set_lang_class, get_lang_class
from . import en
from . import de
from . import zh
try:
basestring
except NameError:
basestring = str
set_lang_class(en.English.lang, en.English)
set_lang_class(de.German.lang, de.German)
set_lang_class(zh.Chinese.lang, zh.Chinese)
def loa... | import pathlib
from .util import set_lang_class, get_lang_class
from . import en
from . import de
from . import zh
try:
basestring
except NameError:
basestring = str
set_lang_class(en.English.lang, en.English)
set_lang_class(de.German.lang, de.German)
set_lang_class(zh.Chinese.lang, zh.Chinese)
def loa... | Fix mistake loading GloVe vectors. GloVe vectors now loaded by default if present, as promised. | Fix mistake loading GloVe vectors. GloVe vectors now loaded by default if present, as promised.
| Python | mit | spacy-io/spaCy,raphael0202/spaCy,raphael0202/spaCy,explosion/spaCy,Gregory-Howard/spaCy,spacy-io/spaCy,oroszgy/spaCy.hu,honnibal/spaCy,banglakit/spaCy,recognai/spaCy,raphael0202/spaCy,oroszgy/spaCy.hu,spacy-io/spaCy,oroszgy/spaCy.hu,spacy-io/spaCy,banglakit/spaCy,explosion/spaCy,Gregory-Howard/spaCy,recognai/spaCy,bang... | ---
+++
@@ -25,7 +25,9 @@
path = util.match_best_version(target_name, target_version, path)
if isinstance(overrides.get('vectors'), basestring):
- vectors = util.match_best_version(overrides.get('vectors'), None, path)
+ vectors_path = util.match_best_version(overrides.get('vectors'), None, ... |
80d557749f18ede24af7fc528a9d415af44d94f5 | tests/distributions/test_normal.py | tests/distributions/test_normal.py | import tensorprob as tp
def make_normal():
mu = tp.Scalar('mu')
sigma = tp.Scalar('sigma', lower=0)
distribution = tp.Normal(mu, sigma)
return mu, sigma, distribution
def test_init():
mu, sigma, distribution = make_normal()
assert(distribution.mu is mu)
assert(distribution.sigma is sigma... | import tensorprob as tp
def make_normal():
mu = tp.Scalar('mu')
sigma = tp.Scalar('sigma', lower=0)
distribution = tp.Normal(mu, sigma)
return mu, sigma, distribution
def test_init():
mu, sigma, distribution = make_normal()
assert(distribution.mu is mu)
assert(distribution.sigma is sigma... | Fix broken test in the most correct way possible ;) | Fix broken test in the most correct way possible ;)
| Python | mit | ibab/tensorfit,tensorprob/tensorprob,ibab/tensorprob | ---
+++
@@ -15,7 +15,4 @@
def test_pdf():
- mu, sigma, distribution = make_normal()
- mu.assign(0.0)
- sigma.assign(1.0)
- assert(distribution.log_pdf())
+ pass |
51e3f7a1fbb857b00a3102287849bc925198d473 | tests/helpers/mixins/assertions.py | tests/helpers/mixins/assertions.py | import json
class AssertionsAssertionsMixin:
def assertSortedEqual(self, one, two):
"""Assert that the sorted of the two equal"""
self.assertEqual(sorted(one), sorted(two))
def assertJsonDictEqual(self, one, two):
"""Assert the two dictionaries are the same, print out as json if not"""... | from harpoon.errors import HarpoonError
from contextlib import contextmanager
import json
class NotSpecified(object):
"""Tell the difference between empty and None"""
class AssertionsAssertionsMixin:
def assertSortedEqual(self, one, two):
"""Assert that the sorted of the two equal"""
self.ass... | Add a fuzzyAssertRaisesError helper for checking against HarpoonError | Add a fuzzyAssertRaisesError helper for checking against HarpoonError
| Python | mit | delfick/harpoon,realestate-com-au/harpoon,delfick/harpoon,realestate-com-au/harpoon | ---
+++
@@ -1,4 +1,10 @@
+from harpoon.errors import HarpoonError
+
+from contextlib import contextmanager
import json
+
+class NotSpecified(object):
+ """Tell the difference between empty and None"""
class AssertionsAssertionsMixin:
def assertSortedEqual(self, one, two):
@@ -16,3 +22,37 @@
p... |
992edb9ec2184f3029f1d964d6079dc28876d8ff | src/Note/tests.py | src/Note/tests.py | from django.test import TestCase
# Create your tests here.
| from django.test import TestCase
from note.models import Page
# Create your tests here.
class PageMethodTests(TestCase):
def test_extract_tags(self):
""" Test la méthode d'extraction de tag """
p = Page()
p.text = """#test
Un test #plus long
Test un #tag.compose
Pi... | Test unitaire pour l'extraction des Tags | Test unitaire pour l'extraction des Tags
| Python | mit | MaximeRaynal/SimpleNote,MaximeRaynal/SimpleNote,MaximeRaynal/SimpleNote,MaximeRaynal/SimpleNote | ---
+++
@@ -1,3 +1,19 @@
from django.test import TestCase
+from note.models import Page
# Create your tests here.
+
+class PageMethodTests(TestCase):
+
+ def test_extract_tags(self):
+ """ Test la méthode d'extraction de tag """
+ p = Page()
+ p.text = """#test
+ Un test #plus long
... |
43e118ccc68bcbfd91a56a6572e8543d2172a79c | bot/logger/message_sender/reusable/__init__.py | bot/logger/message_sender/reusable/__init__.py | from bot.api.api import Api
from bot.logger.message_sender import MessageSender
class ReusableMessageSender(MessageSender):
def __init__(self, api: Api, separator):
self.api = api
self.separator = separator
def send(self, text):
if self._is_new():
self._send_new(text)
... | from bot.api.domain import Message
from bot.logger.message_sender import MessageSender
from bot.logger.message_sender.api import ApiMessageSender
from bot.logger.message_sender.message_builder import MessageBuilder
class ReusableMessageSender(MessageSender):
def __init__(self, sender: ApiMessageSender, builder: M... | Refactor ReusableMessageSender to be resilient against errors on first message api call, whose result is needed to get the message_id to edit further. | Refactor ReusableMessageSender to be resilient against errors on first message api call, whose result is needed to get the message_id to edit further.
Also, an upper limit has been added to avoid errors because of too long messages.
| Python | agpl-3.0 | alvarogzp/telegram-bot,alvarogzp/telegram-bot | ---
+++
@@ -1,26 +1,50 @@
-from bot.api.api import Api
+from bot.api.domain import Message
from bot.logger.message_sender import MessageSender
+from bot.logger.message_sender.api import ApiMessageSender
+from bot.logger.message_sender.message_builder import MessageBuilder
class ReusableMessageSender(MessageSend... |
e76ab1f6be50e9011c4c8c0cd62815fcfdbfd28e | utils/templatetags/form_helpers.py | utils/templatetags/form_helpers.py | from django import template
from django.forms.widgets import CheckboxInput
register = template.Library()
@register.inclusion_tag("_form_field.html")
def smart_field_render(field):
"""
Renders a form field in different label / input orders
depending if it's a checkbox or not.
Also knows to only output... | from django import template
from django.forms.widgets import CheckboxInput
register = template.Library()
@register.inclusion_tag("_form_field.html")
def smart_field_render(field):
"""
Renders a form field in different label / input orders
depending if it's a checkbox or not.
Also knows to only output... | Handle exceptions in the is_checkbox filter | Handle exceptions in the is_checkbox filter
| Python | agpl-3.0 | pculture/unisubs,wevoice/wesub,wevoice/wesub,pculture/unisubs,pculture/unisubs,wevoice/wesub,wevoice/wesub,pculture/unisubs | ---
+++
@@ -33,4 +33,7 @@
@register.filter
def is_checkbox(field):
- return isinstance(field.field.widget, CheckboxInput)
+ try:
+ return isinstance(field.field.widget, CheckboxInput)
+ except StandardError:
+ return False |
8a2fb9001581f66babf59b062af266a1c332f175 | debacl/__init__.py | debacl/__init__.py | """
DeBaCl is a Python library for estimation of density level set trees and
nonparametric density-based clustering. Level set trees are based on the
statistically-principled definition of clusters as modes of a probability
density function. They are particularly useful for analyzing structure in
complex datasets that ... | """
DeBaCl is a Python library for estimation of density level set trees and
nonparametric density-based clustering. Level set trees are based on the
statistically-principled definition of clusters as modes of a probability
density function. They are particularly useful for analyzing structure in
complex datasets that ... | Add tree constructors and LevelSetTree to the debacl namespace. | Add tree constructors and LevelSetTree to the debacl namespace.
| Python | bsd-3-clause | CoAxLab/DeBaCl | ---
+++
@@ -9,5 +9,8 @@
modularity and user customizability.
"""
-import level_set_tree
-import utils
+from level_set_tree import construct_tree
+from level_set_tree import construct_tree_from_graph
+from level_set_tree import load_tree
+
+from level_set_tree import LevelSetTree |
315f98dc949a52fa56ade36276cafcc8f3d562da | dog_giffter.py | dog_giffter.py | #!/usr/bin/env python
import urllib
import json
import yaml
credentials = yaml.load(file("credentials.yml", 'r'))
def main():
data=json.loads(urllib.urlopen("http://api.giphy.com/v1/gifs/search?q=cute+dog&api_key=" + credentials["giphy"]["key"] + "&limit=25").read())
print json.dumps(data, sort_keys=True, in... | #!/usr/bin/env python
import urllib.request
import json
import yaml
credentials = yaml.load(open("credentials.yml", 'r'))
def main():
data=json.loads(urllib.request.urlopen("http://api.giphy.com/v1/gifs/search?q=cute+dog&api_key=" + credentials["giphy"]["key"] + "&limit=25").read())
print(json.dumps(data, so... | Change file to run with python3 | Change file to run with python3
| Python | mit | brandonsoto/Dog_Giffter | ---
+++
@@ -1,16 +1,16 @@
#!/usr/bin/env python
-import urllib
+import urllib.request
import json
import yaml
-credentials = yaml.load(file("credentials.yml", 'r'))
+credentials = yaml.load(open("credentials.yml", 'r'))
def main():
- data=json.loads(urllib.urlopen("http://api.giphy.com/v1/gifs/search?q=c... |
0889a9743d3563ecccaec6106549ef887c327a72 | news/views.py | news/views.py | import json
import requests
from time import sleep
from django.http import HttpResponse
from .models import NewsFeed
HACKER_NEWS_API_URL = 'http://api.ihackernews.com/page'
def get_news(request=None):
feed = NewsFeed.objects.latest()
return json.dumps(feed.json)
# View for updating the feed
def update_fe... | import json
import requests
from time import sleep
from django.http import HttpResponse
from .models import NewsFeed
HACKER_NEWS_API_URL = 'http://api.ihackernews.com/page'
def get_news(request=None):
feed = NewsFeed.objects.latest()
return json.dumps(feed.json)
# View for updating the feed
def update_fe... | Add num_tries to the feed update. If there are more than 10 tries, the requests must stop | Add num_tries to the feed update. If there are more than 10 tries, the requests must stop
| Python | mit | jgasteiz/fuzzingtheweb,jgasteiz/fuzzingtheweb,jgasteiz/fuzzingtheweb | ---
+++
@@ -22,15 +22,16 @@
# Will document this soon.
-def get_feed(feed):
+def get_feed(feed, num_tries=10):
r = requests.get(HACKER_NEWS_API_URL)
if r.status_code == 200:
feed.json = r.text
feed.save()
- else:
+ elif num_tries > 0:
+ num_tries = num_tries - 1
... |
6191f08963b636391982b976f59bd36ae8cce7e0 | vocab/api.py | vocab/api.py | from merriam_webster.api import CollegiateDictionary, WordNotFoundException
from translate.translate import translate_word
DICTIONARY = CollegiateDictionary('d59bdd56-d417-42d7-906e-6804b3069c90')
def lookup_term(language, term):
# If the language is English, use the Merriam-Webster API.
# Otherwise, use Wo... | from merriam_webster.api import CollegiateDictionary, WordNotFoundException
from translate.translate import translate_word
DICTIONARY = CollegiateDictionary('d59bdd56-d417-42d7-906e-6804b3069c90')
def lookup_term(language, term):
# If the language is English, use the Merriam-Webster API.
# Otherwise, use Wo... | Fix malformed data bugs in lookup_term() | Fix malformed data bugs in lookup_term()
| Python | mit | dellsystem/bookmarker,dellsystem/bookmarker,dellsystem/bookmarker | ---
+++
@@ -17,15 +17,16 @@
return e.message
definitions = [
- '({function}) {d}'.format(function=entry.function, d=d)
+ u'({function}) {d}'.format(function=entry.function, d=d)
for entry in response
for d, _ in entry.senses
]
else:... |
4019c093f8c75c032e71e3005a3b294db5a8b005 | taverna_api/settings/production.py | taverna_api/settings/production.py | from .base import *
import dj_database_url
DEBUG = dotenv.get('DEBUG')
ALLOWED_HOSTS = ['*']
# Honor the 'X-Forwarded-Proto' header for request.is_secure()
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
DATABASES = {
'default': dj_database_url.config()
}
DATABASES['default']['CONN_MAX_AGE'] = 50... | from .base import *
import dj_database_url
BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
DEBUG = dotenv.get('DEBUG')
ALLOWED_HOSTS = ['*']
# Honor the 'X-Forwarded-Proto' header for request.is_secure()
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
DATABASES... | Update base directory setting for heroku | Update base directory setting for heroku
| Python | mit | teamtaverna/core | ---
+++
@@ -1,6 +1,8 @@
from .base import *
import dj_database_url
+
+BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
DEBUG = dotenv.get('DEBUG')
ALLOWED_HOSTS = ['*'] |
81d1f0352e22e5af13acca4f0d900c7b01da5dd9 | migrations/versions/307a4fbe8a05_.py | migrations/versions/307a4fbe8a05_.py | """alter table challenge
Revision ID: 307a4fbe8a05
Revises: d6b40a745e5
Create Date: 2017-04-19 14:39:20.255958
"""
# revision identifiers, used by Alembic.
revision = '307a4fbe8a05'
down_revision = 'd6b40a745e5'
from alembic import op
def upgrade():
try:
op.create_index(op.f('ix_challenge_serial'), '... | """alter table challenge
Revision ID: 307a4fbe8a05
Revises: 1edda52b619f
Create Date: 2017-04-19 14:39:20.255958
"""
# revision identifiers, used by Alembic.
revision = '307a4fbe8a05'
down_revision = '1edda52b619f'
from alembic import op
def upgrade():
try:
op.create_index(op.f('ix_challenge_serial'),... | Fix history chain of DB migrations. | Fix history chain of DB migrations.
| Python | agpl-3.0 | wheldom01/privacyidea,jh23453/privacyidea,wheldom01/privacyidea,privacyidea/privacyidea,jh23453/privacyidea,privacyidea/privacyidea,jh23453/privacyidea,privacyidea/privacyidea,privacyidea/privacyidea,privacyidea/privacyidea,wheldom01/privacyidea,jh23453/privacyidea,jh23453/privacyidea,jh23453/privacyidea,privacyidea/pr... | ---
+++
@@ -1,14 +1,14 @@
"""alter table challenge
Revision ID: 307a4fbe8a05
-Revises: d6b40a745e5
+Revises: 1edda52b619f
Create Date: 2017-04-19 14:39:20.255958
"""
# revision identifiers, used by Alembic.
revision = '307a4fbe8a05'
-down_revision = 'd6b40a745e5'
+down_revision = '1edda52b619f'
from al... |
67d4f376586c912f852b98c75f7de04aeb05979a | pag/words.py | pag/words.py | """Get words from files in "src/dictionary/"."""
import os
def get_word_list(filepath):
"""
Get a list of words from a file.
Input: file name
Output: dict with formula {word: [synonym, synonym]}"""
filepath = os.path.abspath(filepath)
assert os.path.isfile(filepath), 'Must be a file'
... | """Get words from files in "src/dictionary/"."""
import os
def get_word_list(filepath):
"""
Get a list of words from a file.
Input: file name
Output: dict with formula {word: [synonym, synonym]}"""
filepath = os.path.abspath(filepath)
assert os.path.isfile(filepath), 'Must be a file'
... | Remove useless and confusing code | Remove useless and confusing code
| Python | mit | allanburleson/python-adventure-game,disorientedperson/python-adventure-game | ---
+++
@@ -13,23 +13,20 @@
f = open(filepath, 'r')
contents = f.read()
txt = contents.strip().split('\n')
- if ':' in contents:
- ntxt = txt[:]
- for line in txt:
- if line[0] == '#':
- ntxt.remove(ntxt[ntxt.index(line)])
- elif ':' not in line:
- ... |
ce0b30775aedce3be7f25e61ec751116bb192cdc | src/hamcrest/core/core/__init__.py | src/hamcrest/core/core/__init__.py | from __future__ import absolute_import
"""Fundamental matchers of objects and values, and composite matchers."""
from hamcrest.core.core.allof import all_of
from hamcrest.core.core.anyof import any_of
from hamcrest.core.core.described_as import described_as
from hamcrest.core.core.is_ import is_
from hamcrest.core.cor... | from __future__ import absolute_import
"""Fundamental matchers of objects and values, and composite matchers."""
from hamcrest.core.core.allof import all_of
from hamcrest.core.core.anyof import any_of
from hamcrest.core.core.described_as import described_as
from hamcrest.core.core.is_ import is_
from hamcrest.core.cor... | Add not_ alias of is_not for better readability of negations | Add not_ alias of is_not for better readability of negations
Example:
>> assert_that(alist, is_not(has_item(item)))
can be
>>assert_that(alist, not_(has_item(item))) | Python | bsd-3-clause | nitishr/PyHamcrest,msabramo/PyHamcrest,msabramo/PyHamcrest,nitishr/PyHamcrest | ---
+++
@@ -10,6 +10,7 @@
from hamcrest.core.core.isinstanceof import instance_of
from hamcrest.core.core.isnone import none, not_none
from hamcrest.core.core.isnot import is_not
+not_ = is_not
from hamcrest.core.core.issame import same_instance
from hamcrest.core.core.raises import calling, raises
|
c9cd82b616dc91db991fb2714cdd50ffa319a7be | dsub/_dsub_version.py | dsub/_dsub_version.py | # Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | # Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | Update dsub version to 0.4.5.dev0 | Update dsub version to 0.4.5.dev0
PiperOrigin-RevId: 358198209
| Python | apache-2.0 | DataBiosphere/dsub,DataBiosphere/dsub | ---
+++
@@ -26,4 +26,4 @@
0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ...
"""
-DSUB_VERSION = '0.4.4'
+DSUB_VERSION = '0.4.5.dev0' |
7bd606d40372d874f49016ea381270e34c7c7d58 | database/initialize.py | database/initialize.py | """ Just the SQL Alchemy ORM tutorial """
import sqlalchemy
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String
engine = create_engine('sqlite:///:memory:', echo=True)
Base = declarative_base()
class User(Base):
__tablename_... | """ Just the SQL Alchemy ORM tutorial """
import sqlalchemy
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String
from sqlalchemy.orm import sessionmaker
engine = create_engine('sqlite:///:memory:', echo=True)
Base = declarative_ba... | Insert a user into a table | Insert a user into a table
| Python | mit | b-ritter/python-notes,b-ritter/python-notes | ---
+++
@@ -4,6 +4,7 @@
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String
+from sqlalchemy.orm import sessionmaker
engine = create_engine('sqlite:///:memory:', echo=True)
@@ -23,3 +24,9 @@
if __name__ == "__main__":
... |
e7759b4bae27de4a5bc4e3226287279bf64dfb5f | core/dbt/task/clean.py | core/dbt/task/clean.py | import os.path
import os
import shutil
from dbt.task.base import ProjectOnlyTask
from dbt.logger import GLOBAL_LOGGER as logger
class CleanTask(ProjectOnlyTask):
def __is_project_path(self, path):
proj_path = os.path.abspath('.')
return not os.path.commonprefix(
[proj_path, os.path.a... | import os.path
import os
import shutil
from dbt.task.base import ProjectOnlyTask
from dbt.logger import GLOBAL_LOGGER as logger
class CleanTask(ProjectOnlyTask):
def __is_project_path(self, path):
proj_path = os.path.abspath('.')
return not os.path.commonprefix(
[proj_path, os.path.a... | Update error message with error warning | Update error message with error warning | Python | apache-2.0 | analyst-collective/dbt,fishtown-analytics/dbt,fishtown-analytics/dbt,fishtown-analytics/dbt,analyst-collective/dbt | ---
+++
@@ -36,5 +36,5 @@
shutil.rmtree(path, True)
logger.info(" Cleaned {}/*".format(path))
else:
- logger.info("{}/* cannot be cleaned".format(path))
+ logger.info("ERROR: not cleaning {}/* because it is protected".format(path))
... |
a5e85fa144eb95b166ce4daa15780c5f4044b386 | shcol/cli.py | shcol/cli.py | from __future__ import print_function
import argparse
import shcol
import sys
__all__ = ['main']
def main(cmd_args):
parser = argparse.ArgumentParser(
description='Generate columnized output for given string items.',
version='shcol {}'.format(shcol.__version__)
)
parser.add_argument(
... | from __future__ import print_function
import argparse
import shcol
import sys
__all__ = ['main']
def main(cmd_args):
parser = argparse.ArgumentParser(
description='Generate columnized output for given string items.',
version='shcol {}'.format(shcol.__version__)
)
item_help = (
'an... | Document behavior when item args are omitted. | Document behavior when item args are omitted.
| Python | bsd-2-clause | seblin/shcol | ---
+++
@@ -11,9 +11,11 @@
description='Generate columnized output for given string items.',
version='shcol {}'.format(shcol.__version__)
)
- parser.add_argument(
- 'items', nargs='*', metavar='item', help='an item to columnize'
+ item_help = (
+ 'an item to columnize\n'
+ ... |
9c4aadaeae4076553b32724097ed23a74ff14ab6 | webapp/settings/development.py | webapp/settings/development.py | from .base import *
DEBUG = True
# TEMPLATES[1]['DEBUG'] = True
DATABASES = {
'default': {
# 'ENGINE': 'django.db.backends.sqlite3',
# 'NAME': os.path.join(BASE_DIR, '..', 'tmp', 'db.sqlite3'),
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'compass_webapp_dev',
... | from .base import *
DEBUG = True
# TEMPLATES[1]['DEBUG'] = True
DATABASES = {
'default': {
# 'ENGINE': 'django.db.backends.sqlite3',
# 'NAME': os.path.join(BASE_DIR, '..', 'tmp', 'db.sqlite3'),
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'compass_webapp_dev',
... | Remove django-extensions from dev settings | Remove django-extensions from dev settings
| Python | apache-2.0 | patrickspencer/compass,patrickspencer/compass-python,patrickspencer/compass-python,patrickspencer/compass-python,patrickspencer/compass,patrickspencer/compass-python,patrickspencer/compass-python,patrickspencer/compass,patrickspencer/compass,patrickspencer/compass | ---
+++
@@ -18,9 +18,7 @@
}
DEVELOPMENT_APPS = [
- 'django.contrib.admin',
'debug_toolbar',
- 'django_extensions',
]
INSTALLED_APPS += DEVELOPMENT_APPS |
bfd90f5ab5354d57fa80143c9f2fb897465d52dd | src/core/templatetags/debug_tools.py | src/core/templatetags/debug_tools.py | from django import template
from utils.logger import get_logger
logger = get_logger(__name__)
register = template.Library()
class TraceNode(template.Node):
def render(self, context):
try:
from nose import tools
tools.set_trace() # Debugger will stop here
except I... | from django import template
from utils.logger import get_logger
logger = get_logger(__name__)
register = template.Library()
class TraceNode(template.Node):
"""
Allows you to set a trace inside a template.
Usage:
{% load debug_tools %}
...
{% set_trace %}
"""
def render(self, context... | Add docstring with usage instructions | Add docstring with usage instructions
| Python | agpl-3.0 | BirkbeckCTP/janeway,BirkbeckCTP/janeway,BirkbeckCTP/janeway,BirkbeckCTP/janeway | ---
+++
@@ -7,6 +7,13 @@
class TraceNode(template.Node):
+ """
+ Allows you to set a trace inside a template.
+ Usage:
+ {% load debug_tools %}
+ ...
+ {% set_trace %}
+ """
def render(self, context):
try: |
bd18f52c2ee41bbc9c33a3b98fdac1ce2ea18ea7 | rest/urls.py | rest/urls.py | # Author: Braedy Kuzma
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^posts/$', views.PostsView.as_view(), name='posts'),
url(r'^posts/(?P<pid>[0-9a-fA-F\-]+)/$', views.PostView.as_view(),
name='post'),
url(r'^posts/(?P<pid>[0-9a-fA-F\-]+)/comments/$',
views.Com... | # Author: Braedy Kuzma
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^posts/$', views.PostsView.as_view(), name='posts'),
url(r'^posts/(?P<pid>[0-9a-fA-F\-]+)/$', views.PostView.as_view(),
name='post'),
url(r'^posts/(?P<pid>[0-9a-fA-F\-]+)/comments/$',
views.Com... | Revert "Handle second service UUID better." | Revert "Handle second service UUID better."
Realized I actually made the url parsing worse, this isn't what we wanted.
| Python | apache-2.0 | CMPUT404W17T06/CMPUT404-project,CMPUT404W17T06/CMPUT404-project,CMPUT404W17T06/CMPUT404-project | ---
+++
@@ -16,6 +16,6 @@
url(r'^friendrequest/$', views.FriendRequestView.as_view(),
name='friendrequest'),
url(r'^author/(?P<aid>[0-9a-fA-F\-]+)/friends/'
- r'(?P<other>[\w\-\.]+(:\d{2,5})?(/[0-9a-fA-F\-]+)*/)$',
+ r'(?P<other>[\w\-\.]+(:\d{2,5})?(/\w+)*/)$',
views.AuthorIs... |
6b558dd7fe2bbab52e56ab54cb0143baff532e8d | mkdocs/gh_deploy.py | mkdocs/gh_deploy.py | from __future__ import print_function
import subprocess
import os
def gh_deploy(config):
if not os.path.exists('.git'):
print('Cannot deploy - this directory does not appear to be a git repository')
return
print("Copying '%s' to `gh-pages` branch and pushing to GitHub." % config['site_dir'])
... | from __future__ import print_function
import subprocess
import os
def gh_deploy(config):
if not os.path.exists('.git'):
print('Cannot deploy - this directory does not appear to be a git repository')
return
print("Copying '%s' to `gh-pages` branch and pushing to GitHub." % config['site_dir'])
... | Check for CNAME file when using gh-deploy | Check for CNAME file when using gh-deploy
If a CNAME file exists in the gh-pages branch, we should read it and use that URL as the expected GitHub pages location. For branches without a CNAME file, we will try to determine the URL using the origin URL.
| Python | bsd-2-clause | cazzerson/mkdocs,michaelmcandrew/mkdocs,jeoygin/mkdocs,kubikusrubikus/mkdocs,justinkinney/mkdocs,jpush/mkdocs,peter1000/mkdocs,mkdocs/mkdocs,justinkinney/mkdocs,mkdocs/mkdocs,hhg2288/mkdocs,lbenet/mkdocs,vi4m/mkdocs,lukfor/mkdocs,mlzummo/mkdocs,lukfor/mkdocs,mlzummo/mkdocs,ramramps/mkdocs,xeechou/mkblogs,simonfork/mkdo... | ---
+++
@@ -14,7 +14,17 @@
except:
return
- # TODO: Also check for CNAME file
+ # Does this repository have a CNAME set for GitHub pages?
+ if os.path.isfile('CNAME'):
+ # This GitHub pages repository has a CNAME configured.
+ with(open('CNAME', 'r')) as f:
+ cname_ho... |
6eed59360d6e2fabf1fe1d590449bce8a1c6af2e | run_daily.py | run_daily.py | import sys
import os
import datetime
print "====================="
print str(datetime.datetime.now())+": the daily job has started"
print "Current directory is "+os.getcwd()
sys.path.append(os.getcwd())
import pyvalue.jobs as jobs
#jobs.update_sp500_yahoofinance_stock_quote()
jobs.update_nasdaq_etf_yahoofinance_stock... | import sys
import os
import datetime
print "====================="
print str(datetime.datetime.now())+": the daily job has started"
print "Current directory is "+os.getcwd()
sys.path.append(os.getcwd())
import pyvalue.jobs as jobs
jobs.update_sp500_yahoofinance_stock_quote()
jobs.update_nasdaq_etf_yahoofinance_stock_... | Add dividend pay date and ex-diviend date into yahoo daily quote | Add dividend pay date and ex-diviend date into yahoo daily quote
| Python | apache-2.0 | ltangt/pyvalue | ---
+++
@@ -8,7 +8,7 @@
sys.path.append(os.getcwd())
import pyvalue.jobs as jobs
-#jobs.update_sp500_yahoofinance_stock_quote()
+jobs.update_sp500_yahoofinance_stock_quote()
jobs.update_nasdaq_etf_yahoofinance_stock_quote()
print "====================="
print str(datetime.datetime.now())+": the daily job has f... |
726a982145a5da2530056e2012853848b07d0460 | django_snooze/utils.py | django_snooze/utils.py | # -*- coding: utf-8 -*-
import json
from django.http import HttpResponse
def json_response(content, status_code=200, headers={}):
"""
Simple function to serialise content and return a valid HTTP response.
It takes three parameters:
- content (required): the content to serialise.
- status... | # -*- coding: utf-8 -*-
import json
from django.http import HttpResponse
def json_response(content, status_code=200, headers={}):
"""
Simple function to serialise content and return a valid HTTP response.
It takes three parameters:
- content (required): the content to serialise.
- statu... | Fix the Content-Type header of the json_response | Fix the Content-Type header of the json_response
Seems I forgot to add the correct Content-Type header to the json_response
utility. This has now been fixed.
| Python | bsd-3-clause | ainmosni/django-snooze,ainmosni/django-snooze | ---
+++
@@ -3,6 +3,7 @@
import json
from django.http import HttpResponse
+
def json_response(content, status_code=200, headers={}):
"""
@@ -16,6 +17,7 @@
response = HttpResponse()
response.write(json.dumps(content))
response.status_code = status_code
+ response['Content-Type'] = 'applica... |
4615a9e26f9a6064572d409ccf8a79a7ab584a38 | carson/__init__.py | carson/__init__.py | from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config.from_object('carson.default_settings')
db = SQLAlchemy(app)
from . import api
from . import models
| from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config.from_object('carson.default_settings')
app.config.from_envvar('CARSON_SETTINGS', silent=True)
db = SQLAlchemy(app)
from . import api
from . import models
| Allow overwriting of config from envvar | Allow overwriting of config from envvar
| Python | mit | SylverStudios/carson | ---
+++
@@ -4,6 +4,7 @@
app = Flask(__name__)
app.config.from_object('carson.default_settings')
+app.config.from_envvar('CARSON_SETTINGS', silent=True)
db = SQLAlchemy(app)
|
56e559171ff707703de4cd195b77a30d12eb6315 | cihai/__about__.py | cihai/__about__.py | __title__ = 'cihai'
__package_name__ = 'cihai'
__version__ = '0.9.0a3'
__description__ = 'Library for CJK (chinese, japanese, korean) language data.'
__author__ = 'Tony Narlock'
__email__ = 'tony@git-pull.com'
__github__ = 'https://github.com/cihai/cihai'
__pypi__ = 'https://pypi.org/project/cihai/'
__license__ = 'MIT'... | __title__ = 'cihai'
__package_name__ = 'cihai'
__version__ = '0.9.0a3'
__description__ = 'Library for CJK (chinese, japanese, korean) language data.'
__author__ = 'Tony Narlock'
__email__ = 'tony@git-pull.com'
__github__ = 'https://github.com/cihai/cihai'
__pypi__ = 'https://pypi.org/project/cihai/'
__license__ = 'MIT'... | Update copyright year to be continuous | Update copyright year to be continuous
| Python | mit | cihai/cihai,cihai/cihai | ---
+++
@@ -7,4 +7,4 @@
__github__ = 'https://github.com/cihai/cihai'
__pypi__ = 'https://pypi.org/project/cihai/'
__license__ = 'MIT'
-__copyright__ = 'Copyright 2013-2018 cihai software foundation'
+__copyright__ = 'Copyright 2013- cihai software foundation' |
3ffc8172337d25c67e5216d4eafd5289091ef411 | aioes/__init__.py | aioes/__init__.py | import re
import sys
from collections import namedtuple
from .client import Elasticsearch
__all__ = ('Elasticsearch',)
__version__ = '0.1.0a'
version = __version__ + ' , Python ' + sys.version
VersionInfo = namedtuple('VersionInfo',
'major minor micro releaselevel serial')
def _parse_v... | import re
import sys
from collections import namedtuple
from .client import Elasticsearch
__all__ = ('Elasticsearch',)
__version__ = '0.1.0a'
version = __version__ + ' , Python ' + sys.version
VersionInfo = namedtuple('VersionInfo',
'major minor micro releaselevel serial')
def _parse_v... | Make version format PEP 440 compatible | Make version format PEP 440 compatible
| Python | apache-2.0 | aio-libs/aioes | ---
+++
@@ -24,7 +24,7 @@
major = int(match.group('major'))
minor = int(match.group('minor'))
micro = int(match.group('micro'))
- levels = {'rc': 'candidate',
+ levels = {'c': 'candidate',
'a': 'alpha',
'b': 'beta',
None... |
2cae3a623bce4336f55ef8ec12f1de1dcfb8a637 | test/test_view.py | test/test_view.py | import pytest
| from PySide import QtGui
import qmenuview
def test_title(qtbot):
title = 'Test title'
qmenuview.MenuView(title)
assert qmenuview.title() == title
def test_parent(qtbot):
p = QtGui.QWidget()
qmenuview.MenuView(parent=p)
assert qmenuview.parent() is p
| Add first simple title and parent test | Add first simple title and parent test
| Python | bsd-3-clause | storax/qmenuview | ---
+++
@@ -1 +1,15 @@
-import pytest
+from PySide import QtGui
+
+import qmenuview
+
+
+def test_title(qtbot):
+ title = 'Test title'
+ qmenuview.MenuView(title)
+ assert qmenuview.title() == title
+
+
+def test_parent(qtbot):
+ p = QtGui.QWidget()
+ qmenuview.MenuView(parent=p)
+ assert qmenuview.... |
c290c132368a93856066513d474078c2a2b22e39 | polyaxon/libs/paths.py | polyaxon/libs/paths.py | import logging
import os
import shutil
logger = logging.getLogger('polyaxon.libs.paths')
def delete_path(path):
if not os.path.exists(path):
return
try:
if os.path.isfile(path):
os.remove(path)
else:
shutil.rmtree(path)
except OSError:
logger.warnin... | import logging
import os
import shutil
logger = logging.getLogger('polyaxon.libs.paths')
def delete_path(path):
if not os.path.exists(path):
return
try:
if os.path.isfile(path):
os.remove(path)
else:
shutil.rmtree(path)
except OSError:
logger.warnin... | Add exception handling for FileExistsError | Add exception handling for FileExistsError
| Python | apache-2.0 | polyaxon/polyaxon,polyaxon/polyaxon,polyaxon/polyaxon | ---
+++
@@ -42,5 +42,8 @@
tmp_path = get_tmp_path(dir_name)
if os.path.exists(tmp_path):
return tmp_path
- shutil.copytree(path, tmp_path)
+ try:
+ shutil.copytree(path, tmp_path)
+ except FileExistsError as e:
+ logger.warning('Path already exists `%s`, exception %s', path, ... |
15f0b27759b6c831d4196d7c067e6eb95927e5aa | ato_children/api/filters.py | ato_children/api/filters.py | import django_filters
from ..models import Gift
class GiftFilter(django_filters.FilterSet):
"""docstring for GiftFilter"""
class Meta:
model = Gift
fields = ['region']
| import django_filters
from ..models import Gift
class GiftFilter(django_filters.FilterSet):
"""docstring for GiftFilter"""
class Meta:
model = Gift
fields = ['region', 'status']
| Enable status filter in API | Enable status filter in API
| Python | mit | webknjaz/webchallenge-ato-children,webknjaz/webchallenge-ato-children,webknjaz/webchallenge-ato-children,webknjaz/webchallenge-ato-children | ---
+++
@@ -7,4 +7,4 @@
"""docstring for GiftFilter"""
class Meta:
model = Gift
- fields = ['region']
+ fields = ['region', 'status'] |
89a5f257cd1fb285db78b6178e9418fbf48fdaf4 | YouKnowShit/DownloadFilesRename.py | YouKnowShit/DownloadFilesRename.py | import requests
import bs4
import os
import urllib.request
import shutil
import re
distDir = 'F:\\utorrent\\WEST'
p = re.compile(r'(\D+\d+)\w*(.\w+)')
filenames = os.listdir(distDir)
upperfilenames = []
print(filenames)
for filenamepref in filenames:
if (filenamepref.find('_') > 0):
filenameprefit = fil... | import os
import re
distDir = 'H:\\temp'
p = re.compile(r'(\D+\d+)\w*(.\w+)')
filenames = os.listdir(distDir)
upperfilenames = []
print(filenames)
for filenamepref in filenames:
if filenamepref.find('_') > 0:
filenameprefit = filenamepref[filenamepref.index('_'):]
else:
filenameprefit = file... | Remove [thz.la] from file names. | Remove [thz.la] from file names.
| Python | mit | jiangtianyu2009/PiSoftCake | ---
+++
@@ -1,12 +1,8 @@
-import requests
-import bs4
import os
-import urllib.request
-import shutil
import re
-distDir = 'F:\\utorrent\\WEST'
+distDir = 'H:\\temp'
p = re.compile(r'(\D+\d+)\w*(.\w+)')
@@ -14,12 +10,13 @@
upperfilenames = []
print(filenames)
for filenamepref in filenames:
- if (file... |
82396b5033d1dce52e0504a3703d62cdd5bc047b | tests/functions_tests/test_copy.py | tests/functions_tests/test_copy.py | import unittest
import numpy
import chainer
from chainer import functions
from chainer import gradient_check
class Copy(unittest.TestCase):
def setUp(self):
self.x_data = numpy.random.uniform(
-1, 1, (10, 5)).astype(numpy.float32)
self.gy = numpy.random.uniform(-1, 1, (10, 5)).astyp... | import unittest
import numpy
import chainer
from chainer import functions
from chainer import gradient_check
from chainer import testing
class Copy(unittest.TestCase):
def setUp(self):
self.x_data = numpy.random.uniform(
-1, 1, (10, 5)).astype(numpy.float32)
self.gy = numpy.random.u... | Make test module for Copy runnable | Make test module for Copy runnable
| Python | mit | cupy/cupy,kuwa32/chainer,cupy/cupy,hvy/chainer,niboshi/chainer,cupy/cupy,AlpacaDB/chainer,niboshi/chainer,1986ks/chainer,ktnyt/chainer,tigerneil/chainer,t-abe/chainer,wkentaro/chainer,truongdq/chainer,jnishi/chainer,cemoody/chainer,ikasumi/chainer,aonotas/chainer,chainer/chainer,wkentaro/chainer,keisuke-umezawa/chainer... | ---
+++
@@ -5,6 +5,7 @@
import chainer
from chainer import functions
from chainer import gradient_check
+from chainer import testing
class Copy(unittest.TestCase):
@@ -25,3 +26,6 @@
y.grad = self.gy
y.backward()
gradient_check.assert_allclose(x.grad, self.gy, atol=0, rtol=0)
+
+
+te... |
77faa07a81fcb03351c2926c36c716097cad9a79 | backdrop/collector/write.py | backdrop/collector/write.py | import datetime
import logging
import pytz
import requests
import json
class JsonEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime.datetime):
if obj.tzinfo is None:
obj = obj.replace(tzinfo=pytz.UTC)
return obj.isoformat()
return... | import datetime
import logging
import pytz
import requests
import json
class JsonEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime.datetime):
if obj.tzinfo is None:
obj = obj.replace(tzinfo=pytz.UTC)
return obj.isoformat()
return... | Include URL and response body on HTTP failure | Include URL and response body on HTTP failure
It's quite awkward to diagnose exceptions caused by HTTP errors when you
don't have the URL and response body, so this should help.
| Python | mit | gds-attic/backdrop-collector,gds-attic/backdrop-collector,alphagov/performanceplatform-collector,alphagov/performanceplatform-collector,alphagov/performanceplatform-collector | ---
+++
@@ -33,6 +33,10 @@
data=json.dumps(records, cls=JsonEncoder)
)
+ try:
+ response.raise_for_status()
+ except:
+ logging.error('[Backdrop: {}]\n{}'.format(self.url, response.text))
+ raise
+
logging.debug("[Backdrop] " + response.t... |
25325ee55852eb65e58c13c46660701b1cdd803f | music/migrations/0020_auto_20151028_0925.py | music/migrations/0020_auto_20151028_0925.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
def set_total_duration_as_duration(apps, schema_editor):
Music = apps.get_model("music", "Music")
for music in Music.objects.all():
music.total_duration = music.duration
music.save()
cla... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
def set_total_duration_as_duration(apps, schema_editor):
Music = apps.get_model("music", "Music")
for music in Music.objects.all():
music.total_duration = music.duration
music.save()
cla... | Delete timer_end in same migration as total_duration | Delete timer_end in same migration as total_duration
| Python | mit | Amoki/Amoki-Music,Amoki/Amoki-Music,Amoki/Amoki-Music | ---
+++
@@ -36,4 +36,8 @@
field=models.PositiveIntegerField(null=True),
preserve_default=True,
),
+ migrations.RemoveField(
+ model_name='music',
+ name='timer_end',
+ ),
] |
c90462cc685d95c8fb03858f266691123fc37049 | auth_mac/models.py | auth_mac/models.py | from django.db import models
from django.contrib.auth.models import User
class Credentials(models.Model):
"Keeps track of issued MAC credentials"
user = models.ForeignKey(User)
expiry = models.DateTimeField("Expires On")
identifier = models.CharField("MAC Key Identifier", max_length=16, null=True, blank=True)
... | from django.db import models
from django.contrib.auth.models import User
import datetime
def default_expiry_time():
return datetime.datetime.now() + datetime.timedelta(days=1)
def random_string():
return User.objects.make_random_password(16)
class Credentials(models.Model):
"Keeps track of issued MAC credentia... | Create credentials with random keys, identifiers, and expiry a day in the future.. | Create credentials with random keys, identifiers, and expiry a day in the future..
| Python | mit | ndevenish/auth_mac | ---
+++
@@ -1,13 +1,23 @@
from django.db import models
from django.contrib.auth.models import User
+import datetime
+
+def default_expiry_time():
+ return datetime.datetime.now() + datetime.timedelta(days=1)
+
+def random_string():
+ return User.objects.make_random_password(16)
class Credentials(models.Model):... |
11d6bc9cbea154c7526c31c6cb4d88b102826cc9 | eloqua/endpoints_v2.py | eloqua/endpoints_v2.py | """
API MAPPING FOR Eloqua API V2
"""
mapping_table = {
'content_type': 'application/json',
'path_prefix': '/API/REST/2.0',
# Campaigns
'get_campaign': {
'method': 'GET',
'path': '/assets/campaign/{{campaign_id}}',
'valid_params': ['depth']
},
'list_campaigns': {
... | """
API MAPPING FOR Eloqua API V2
"""
mapping_table = {
'content_type': 'application/json',
'path_prefix': '/API/REST/2.0',
# Campaigns
'get_campaign': {
'method': 'GET',
'path': '/assets/campaign/{{campaign_id}}',
'valid_params': ['depth']
},
'list_campaigns': {
... | Add operation to update campaign. | Add operation to update campaign.
| Python | mit | alexcchan/eloqua | ---
+++
@@ -30,7 +30,8 @@
'activate_campaign': {
'method': 'POST',
'path': '/assets/campaign/active/{{campaign_id}}',
- 'valid_params': ['activateNow','scheduledFor','runAsUserId']
+ 'valid_params': ['activateNow','scheduledFor','runAsUserId'],
+ 'status': 201
},
... |
72fcd8f8ec44bf11fa1ed746de188ee4312150c3 | apps/sumo/urls.py | apps/sumo/urls.py | from django.conf import settings
from django.conf.urls.defaults import patterns, url, include
from django.views.generic.simple import redirect_to
from sumo import views
services_patterns = patterns('',
url('^/monitor$', views.monitor, name='sumo.monitor'),
url('^/version$', views.version_check, name='sumo.ve... | from django.conf import settings
from django.conf.urls.defaults import patterns, url, include
from django.views.generic.base import RedirectView
from sumo import views
services_patterns = patterns('',
url('^/monitor$', views.monitor, name='sumo.monitor'),
url('^/version$', views.version_check, name='sumo.ver... | Switch to class based generic views. | Switch to class based generic views.
| Python | bsd-3-clause | feer56/Kitsune1,iDTLabssl/kitsune,silentbob73/kitsune,YOTOV-LIMITED/kitsune,mozilla/kitsune,rlr/kitsune,anushbmx/kitsune,anushbmx/kitsune,iDTLabssl/kitsune,silentbob73/kitsune,silentbob73/kitsune,iDTLabssl/kitsune,brittanystoroz/kitsune,safwanrahman/kitsune,orvi2014/kitsune,feer56/Kitsune2,turtleloveshoes/kitsune,MikkC... | ---
+++
@@ -1,6 +1,6 @@
from django.conf import settings
from django.conf.urls.defaults import patterns, url, include
-from django.views.generic.simple import redirect_to
+from django.views.generic.base import RedirectView
from sumo import views
@@ -19,10 +19,10 @@
url('^locales$', views.locales, name='su... |
0ce28daf74ebff5a087ccda7db9d6bcfc77dfdf6 | telemetry/telemetry/internal/backends/chrome_inspector/inspector_serviceworker.py | telemetry/telemetry/internal/backends/chrome_inspector/inspector_serviceworker.py | # Copyright 2017 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from telemetry.core import exceptions
class InspectorServiceWorker(object):
def __init__(self, inspector_websocket, timeout):
self._websocket = inspe... | # Copyright 2017 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from telemetry.internal.backends.chrome_inspector import inspector_websocket
from telemetry.core import exceptions
class InspectorServiceWorker(object):
d... | Handle error code METHOD_NOT_FOUND_CODE in InspectorServiceWorker.StopAllWorkers() | Handle error code METHOD_NOT_FOUND_CODE in InspectorServiceWorker.StopAllWorkers()
DevTools method ServiceWorker.stopAllWorkers is supported from M63, so
calling this can return METHOD_NOT_FOUND_CODE error in previous browser.
This CL make InspectorServiceWorker.StopAllWorkers() handle this error.
If it receives this ... | Python | bsd-3-clause | catapult-project/catapult,catapult-project/catapult,catapult-project/catapult,catapult-project/catapult,catapult-project/catapult,catapult-project/catapult,catapult-project/catapult | ---
+++
@@ -2,12 +2,12 @@
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
+from telemetry.internal.backends.chrome_inspector import inspector_websocket
from telemetry.core import exceptions
-
class InspectorServiceWorker(object):
- def __init__(self, insp... |
2ee3de95eac0ca26b5d7567291a1e03478fd95ff | extras/gallery_sync.py | extras/gallery_sync.py | #!/usr/bin/env python
"""Script to upload pictures to the gallery.
This script scans a local picture folder to determine which patients
have not yet been created in the gallery. It then creates the missing
patients.
"""
from getpass import getpass
import requests
API_URL = 'http://localhost:8000/gallery/api/patie... | #!/usr/bin/env python
"""Script to upload pictures to the gallery.
This script scans a local picture folder to determine which patients
have not yet been created in the gallery. It then creates the missing
patients.
"""
from getpass import getpass
import os
import requests
API_URL = 'http://localhost:8000/gallery... | Add method to find pictures. | Add method to find pictures.
| Python | mit | cdriehuys/chmvh-website,cdriehuys/chmvh-website,cdriehuys/chmvh-website | ---
+++
@@ -8,6 +8,7 @@
"""
from getpass import getpass
+import os
import requests
@@ -16,6 +17,21 @@
API_USER = 'chathan'
API_PASSWORD = getpass('API Password: ')
+
+LOCAL_FOLDER = input('Local folder to sync from: ')
+
+PICTURE_EXTENSIONS = ('jpg', 'jpeg', 'png')
+
+
+def crawl_pictures(start_folder):
... |
810a3760191c8ec8b04d192857710bfc9418ed20 | wger/weight/tests/test_csv_export.py | wger/weight/tests/test_csv_export.py | # This file is part of wger Workout Manager.
#
# wger Workout Manager is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# wger W... | # This file is part of wger Workout Manager.
#
# wger Workout Manager is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# wger W... | Fix weight CSV export test | Fix weight CSV export test
| Python | agpl-3.0 | wger-project/wger,wger-project/wger,DeveloperMal/wger,kjagoo/wger_stark,rolandgeider/wger,wger-project/wger,petervanderdoes/wger,rolandgeider/wger,petervanderdoes/wger,DeveloperMal/wger,kjagoo/wger_stark,kjagoo/wger_stark,rolandgeider/wger,rolandgeider/wger,kjagoo/wger_stark,petervanderdoes/wger,DeveloperMal/wger,wger-... | ---
+++
@@ -35,7 +35,7 @@
self.assertEqual(response.status_code, 200)
self.assertEqual(response['Content-Type'], 'text/csv')
self.assertEqual(response['Content-Disposition'],
- 'attachment; filename=weightdata-test.csv')
+ 'attachment; filenam... |
09b2f0ca34d2f541d2f22a02961106d6edf52805 | ipyvolume/__init__.py | ipyvolume/__init__.py | from __future__ import absolute_import
from ._version import __version__
from . import styles
from . import examples
from . import datasets
from . import embed
from .widgets import (Mesh,
Scatter,
Volume,
Figure,
quickquiver,
... | from __future__ import absolute_import
from ._version import __version__
from . import styles
from . import examples
from . import datasets
from . import embed
from .widgets import (Mesh,
Scatter,
Volume,
Figure,
quickquiver,
... | Fix typo causing error in imports. | Fix typo causing error in imports.
| Python | mit | maartenbreddels/ipyvolume,maartenbreddels/ipyvolume,maartenbreddels/ipyvolume,maartenbreddels/ipyvolume | ---
+++
@@ -50,7 +50,7 @@
xyzlabel,
view,
style,
- plot_plane',
+ plot_plane,
selector_default)
def _jupyter_nbextension_paths(): |
799a03a2f40186518063a12f531239071aad7d72 | evesrp/util/request.py | evesrp/util/request.py | from __future__ import unicode_literals
from flask import Request
from itertools import repeat, chain
class AcceptRequest(Request):
_json_mimetypes = ['application/json',]
_html_mimetypes = ['text/html', 'application/xhtml+xml']
_xml_mimetypes = ['application/xml', 'text/xml']
_rss_mimetypes = ['a... | from __future__ import unicode_literals
from flask import Request
class AcceptRequest(Request):
_json_mimetypes = ['application/json',]
_html_mimetypes = ['text/html', 'application/xhtml+xml']
_xml_mimetypes = ['application/xml', 'text/xml']
_rss_mimetypes = ['application/rss+xml', 'application/rd... | Revert "Assign quality values when checking MIME types" | Revert "Assign quality values when checking MIME types"
This reverts commit b06842f3d5dea138f2962f91105926d889157773.
| Python | bsd-2-clause | paxswill/evesrp,paxswill/evesrp,paxswill/evesrp | ---
+++
@@ -1,6 +1,5 @@
from __future__ import unicode_literals
from flask import Request
-from itertools import repeat, chain
class AcceptRequest(Request):
@@ -13,12 +12,12 @@
_rss_mimetypes = ['application/rss+xml', 'application/rdf+xml']
- _known_mimetypes = list(chain(
- zip(_html_mimety... |
989601aef4d8a1eeb7cf873ebd2f93ad89b67e54 | tests/install_tests/test_build.py | tests/install_tests/test_build.py | from distutils import ccompiler
from distutils import sysconfig
import unittest
import pytest
from install import build
class TestCheckVersion(unittest.TestCase):
def setUp(self):
self.compiler = ccompiler.new_compiler()
sysconfig.customize_compiler(self.compiler)
self.settings = build.... | from distutils import ccompiler
from distutils import sysconfig
import unittest
import pytest
from install import build
class TestCheckVersion(unittest.TestCase):
def setUp(self):
self.compiler = ccompiler.new_compiler()
sysconfig.customize_compiler(self.compiler)
self.settings = build.... | Fix to check HIP version | Fix to check HIP version
| Python | mit | cupy/cupy,cupy/cupy,cupy/cupy,cupy/cupy | ---
+++
@@ -15,6 +15,7 @@
self.settings = build.get_compiler_setting(False)
@pytest.mark.gpu
+ @pytest.mark.skipIf(build.use_hip, reason='For CUDA environment')
def test_check_cuda_version(self):
with self.assertRaises(RuntimeError):
build.get_cuda_version()
@@ -22,6 +23,... |
b3407617c723d5bac579074262166ac6790be9d6 | gcloud/dns/__init__.py | gcloud/dns/__init__.py | # Copyright 2015 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | # Copyright 2015 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | Add top-level 'SCOPE' alias for DNS. | Add top-level 'SCOPE' alias for DNS.
| Python | apache-2.0 | tartavull/google-cloud-python,dhermes/gcloud-python,jonparrott/gcloud-python,tswast/google-cloud-python,googleapis/google-cloud-python,Fkawala/gcloud-python,waprin/google-cloud-python,tseaver/google-cloud-python,daspecster/google-cloud-python,tswast/google-cloud-python,GoogleCloudPlatform/gcloud-python,calpeyser/google... | ---
+++
@@ -21,3 +21,6 @@
from gcloud.dns.client import Client
from gcloud.dns.connection import Connection
+
+
+SCOPE = Connection.SCOPE |
8c15f6cde0698fdb35e0142e07730ddf0980682c | appengine/config_service/common.py | appengine/config_service/common.py | # Copyright 2015 The Swarming Authors. All rights reserved.
# Use of this source code is governed by the Apache v2.0 license that can be
# found in the LICENSE file.
import re
################################################################################
## Config set patterns.
SERVICE_ID_PATTERN = '[a-z0-9\-]+'
S... | # Copyright 2015 The Swarming Authors. All rights reserved.
# Use of this source code is governed by the Apache v2.0 license that can be
# found in the LICENSE file.
import re
################################################################################
## Config set patterns.
SERVICE_ID_PATTERN = '[a-z0-9\-_]+'
... | Allow _ in service and project ids | Allow _ in service and project ids
We use dash to nest projects (infra-internal), so it cannot be used for
word separation (depot_tools).
R=vadimsh@chromium.org
BUG=
Review URL: https://codereview.chromium.org/1185823003.
| Python | apache-2.0 | luci/luci-py,luci/luci-py,luci/luci-py,luci/luci-py | ---
+++
@@ -7,7 +7,7 @@
################################################################################
## Config set patterns.
-SERVICE_ID_PATTERN = '[a-z0-9\-]+'
+SERVICE_ID_PATTERN = '[a-z0-9\-_]+'
SERVICE_ID_RGX = re.compile('^%s$' % SERVICE_ID_PATTERN)
SERVICE_CONFIG_SET_RGX = re.compile('^services/(%s)$'... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.