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 |
|---|---|---|---|---|---|---|---|---|---|---|
857ae593c14ea2401f0bb21d53d8e464fc7d3cb2 | server/constants.py | server/constants.py | """App constants"""
STUDENT_ROLE = 'student'
GRADER_ROLE = 'grader'
STAFF_ROLE = 'staff'
INSTRUCTOR_ROLE = 'instructor'
LAB_ASSISTANT_ROLE = 'lab assistant'
VALID_ROLES = [STUDENT_ROLE, GRADER_ROLE, STAFF_ROLE, INSTRUCTOR_ROLE, LAB_ASSISTANT_ROLE]
STAFF_ROLES = [GRADER_ROLE, STAFF_ROLE, INSTRUCTOR_ROLE]
GRADE_TAGS = [... | """App constants"""
STUDENT_ROLE = 'student'
GRADER_ROLE = 'grader'
STAFF_ROLE = 'staff'
INSTRUCTOR_ROLE = 'instructor'
LAB_ASSISTANT_ROLE = 'lab_assistant'
VALID_ROLES = [STUDENT_ROLE, GRADER_ROLE, STAFF_ROLE, INSTRUCTOR_ROLE, LAB_ASSISTANT_ROLE]
STAFF_ROLES = [GRADER_ROLE, STAFF_ROLE, INSTRUCTOR_ROLE]
GRADE_TAGS = [... | Change lab assistant constant to one word | Change lab assistant constant to one word
| Python | apache-2.0 | Cal-CS-61A-Staff/ok,Cal-CS-61A-Staff/ok,Cal-CS-61A-Staff/ok,Cal-CS-61A-Staff/ok,Cal-CS-61A-Staff/ok | ---
+++
@@ -4,7 +4,7 @@
GRADER_ROLE = 'grader'
STAFF_ROLE = 'staff'
INSTRUCTOR_ROLE = 'instructor'
-LAB_ASSISTANT_ROLE = 'lab assistant'
+LAB_ASSISTANT_ROLE = 'lab_assistant'
VALID_ROLES = [STUDENT_ROLE, GRADER_ROLE, STAFF_ROLE, INSTRUCTOR_ROLE, LAB_ASSISTANT_ROLE]
STAFF_ROLES = [GRADER_ROLE, STAFF_ROLE, INSTRUC... |
697d56dcd4aae19e6cb2351eb39a5c195f8ed029 | instana/instrumentation/urllib3.py | instana/instrumentation/urllib3.py | import opentracing.ext.tags as ext
import opentracing
import wrapt
@wrapt.patch_function_wrapper('urllib3', 'PoolManager.urlopen')
def urlopen_with_instana(wrapped, instance, args, kwargs):
try:
span = opentracing.global_tracer.start_span("urllib3")
span.set_tag(ext.HTTP_URL, args[1])
span... | from __future__ import absolute_import
import opentracing.ext.tags as ext
import instana
import opentracing
import wrapt
@wrapt.patch_function_wrapper('urllib3', 'PoolManager.urlopen')
def urlopen_with_instana(wrapped, instance, args, kwargs):
try:
span = instana.internal_tracer.start_span("urllib3")
... | Expand 5xx coverage; log exceptions | Expand 5xx coverage; log exceptions
| Python | mit | instana/python-sensor,instana/python-sensor | ---
+++
@@ -1,4 +1,6 @@
+from __future__ import absolute_import
import opentracing.ext.tags as ext
+import instana
import opentracing
import wrapt
@@ -6,21 +8,21 @@
@wrapt.patch_function_wrapper('urllib3', 'PoolManager.urlopen')
def urlopen_with_instana(wrapped, instance, args, kwargs):
try:
- span... |
f48c15a6b0c09db26a0f1b0e8846acf1c5e8cc62 | plyer/platforms/ios/gyroscope.py | plyer/platforms/ios/gyroscope.py | '''
iOS Gyroscope
---------------------
'''
from plyer.facades import Gyroscope
from pyobjus import autoclass
from pyobjus.dylib_manager import load_framework
load_framework('/System/Library/Frameworks/UIKit.framework')
UIDevice = autoclass('UIDevice')
device = UIDevice.currentDevice()
class IosGyroscope(Gyroscop... | '''
iOS Gyroscope
---------------------
'''
from plyer.facades import Gyroscope
from pyobjus import autoclass
from pyobjus.dylib_manager import load_framework
load_framework('/System/Library/Frameworks/UIKit.framework')
UIDevice = autoclass('UIDevice')
device = UIDevice.currentDevice()
class IosGyroscope(Gyroscop... | Add method for uncalibrated values of iOS Gyroscope | Add method for uncalibrated values of iOS Gyroscope
| Python | mit | KeyWeeUsr/plyer,KeyWeeUsr/plyer,kivy/plyer,KeyWeeUsr/plyer,kivy/plyer,kivy/plyer | ---
+++
@@ -25,17 +25,30 @@
else:
self.bridge.motionManager.setGyroUpdateInterval_(0.1)
+ self.bridge.motionManager.setDeviceMotionUpdateInterval_(0.1)
+
def _enable(self):
self.bridge.startGyroscope()
+ self.bridge.startDeviceMotion()
def _disable(self):
... |
03bc712bca2001042fd856add659854d27b0a5b9 | src/ansible/urls.py | src/ansible/urls.py | from django.conf.urls import url
from ansible.forms import AnsibleForm1, AnsibleForm2
from ansible.views import (
PlaybookWizard, PlaybookListView, PlaybookDetailView,
PlaybookFileCreateView, PlaybookFileEditView, PlaybookFileView
)
from . import views
urlpatterns = [
url(r'^create/$', PlaybookWizard.as_v... | from django.conf.urls import url
from ansible.forms import AnsibleForm1, AnsibleForm2
from ansible.views import (
PlaybookWizard, PlaybookListView, PlaybookDetailView,
PlaybookFileCreateView, PlaybookFileEditView, PlaybookFileView
)
from . import views
urlpatterns = [
url(r'^create/$', PlaybookWizard.as_v... | Rewrite URLs for playbook app | Rewrite URLs for playbook app
| Python | bsd-3-clause | lozadaOmr/ansible-admin,lozadaOmr/ansible-admin,lozadaOmr/ansible-admin | ---
+++
@@ -13,10 +13,10 @@
url(r'^(?P<pk>[-\w]+)/$',
PlaybookDetailView.as_view(), name='playbook-detail'
),
- url(r'^(?P<pk>[-\w]+)/files/new/$',
+ url(r'^(?P<pk>[-\w]+)/new/$',
PlaybookFileCreateView.as_view(), name='playbook-file-create'
),
- url(r'^(?P<pk>[-\w]+)/files/(... |
9bcacb5488d32e9e4483c0b54abfa548885148d2 | tamarackcollector/worker.py | tamarackcollector/worker.py | import json
import requests
import time
from collections import Counter
from multiprocessing import Process, Queue
from queue import Empty
shared_queue = None
def datetime_by_minute(dt):
return dt.replace(second=0, microsecond=0).isoformat() + 'Z'
def process_jobs(url, app_id, queue):
while True:
... | import json
import requests
import time
from collections import Counter
from multiprocessing import Process, Queue
from queue import Empty
shared_queue = None
def datetime_by_minute(dt):
return dt.replace(second=0, microsecond=0).isoformat() + 'Z'
def process_jobs(url, app_id, queue):
while True:
... | Send request_count and error_count outside sensor_data | Send request_count and error_count outside sensor_data
| Python | bsd-3-clause | tamarackapp/tamarack-collector-py | ---
+++
@@ -32,12 +32,14 @@
'sensor_data': Counter(),
'timestamp': minute,
'endpoint': endpoint,
+ 'request_count': 0,
+ 'error_count': 0,
}
- sensor_data = by_minute[(minute, endpoint)][... |
46dda5e761d3752fce26b379cc8542e3f5244376 | examples/fabfile.py | examples/fabfile.py | """Example of integration between Fabric and Datadog.
"""
from fabric.api import *
from fabric.colors import *
from dogapi.fab import setup, notify
setup(api_key = "YOUR API KEY HERE")
# Make sure @notify is just below @task
@task(default=True, alias="success")
@notify
def sweet_task(some_arg, other_arg):
"""Alw... | """Example of integration between Fabric and Datadog.
"""
from fabric.api import *
from fabric.colors import *
from dogapi.fab import setup, notify
setup(api_key = "YOUR API KEY HERE")
# Make sure @notify is just below @task
@notify
@task(default=True, alias="success")
def sweet_task(some_arg, other_arg):
"""Alw... | Make sure @ notify is the first decorator | Make sure @ notify is the first decorator
fixes #91 | Python | bsd-3-clause | DataDog/dogapi,DataDog/dogapi | ---
+++
@@ -8,14 +8,14 @@
setup(api_key = "YOUR API KEY HERE")
# Make sure @notify is just below @task
+@notify
@task(default=True, alias="success")
-@notify
def sweet_task(some_arg, other_arg):
"""Always succeeds"""
print(green("My sweet task always runs properly."))
+@notify
@task(alias="failure"... |
3680c9e874df4daf2981d524a311d292293ca6d6 | scrapi/settings/travis-dist.py | scrapi/settings/travis-dist.py | DEBUG = False
BROKER_URL = 'amqp://guest@localhost'
RECORD_HTTP_TRANSACTIONS = False
CELERY_EAGER_PROPAGATES_EXCEPTIONS = True
RAW_PROCESSING = ['cassandra', 'postgres']
NORMALIZED_PROCESSING = ['elasticsearch', 'cassandra', 'postgres']
RESPONSE_PROCESSING = 'postgres'
SENTRY_DSN = None
USE_FLUENTD = False
CASSA... | DEBUG = False
BROKER_URL = 'amqp://guest@localhost'
RECORD_HTTP_TRANSACTIONS = False
CELERY_EAGER_PROPAGATES_EXCEPTIONS = True
RAW_PROCESSING = ['cassandra', 'postgres']
NORMALIZED_PROCESSING = ['elasticsearch', 'cassandra', 'postgres']
RESPONSE_PROCESSING = 'cassandra'
SENTRY_DSN = None
USE_FLUENTD = False
CASS... | Change resp processing to cassandra -- need to fix tests for postgres | Change resp processing to cassandra -- need to fix tests for postgres
| Python | apache-2.0 | mehanig/scrapi,felliott/scrapi,fabianvf/scrapi,mehanig/scrapi,erinspace/scrapi,CenterForOpenScience/scrapi,felliott/scrapi,CenterForOpenScience/scrapi,fabianvf/scrapi,erinspace/scrapi | ---
+++
@@ -8,7 +8,7 @@
RAW_PROCESSING = ['cassandra', 'postgres']
NORMALIZED_PROCESSING = ['elasticsearch', 'cassandra', 'postgres']
-RESPONSE_PROCESSING = 'postgres'
+RESPONSE_PROCESSING = 'cassandra'
SENTRY_DSN = None
|
235bf56a4f80475f618a62db15844d7a004dd967 | scripts/TestFontCompilation.py | scripts/TestFontCompilation.py | from string import split
from os import remove
from mojo.roboFont import version
from jkRFoTools.FontChooser import ProcessFonts
def test_compilation(font):
temp_font = font.copy(showUI=False)
for g in temp_font:
g.clear()
if font.path is None:
return "ERROR: The font needs to be sav... | from os import remove
from os.path import exists
from mojo.roboFont import version
from jkRFoTools.FontChooser import ProcessFonts
from fontCompiler.compiler import FontCompilerOptions
from fontCompiler.emptyCompiler import EmptyOTFCompiler
def test_compilation(font):
if font.path is None:
return "ERROR:... | Use EmptyOTFCompiler for test compilation | Use EmptyOTFCompiler for test compilation
| Python | mit | jenskutilek/RoboFont,jenskutilek/RoboFont | ---
+++
@@ -1,39 +1,36 @@
-from string import split
from os import remove
+from os.path import exists
from mojo.roboFont import version
from jkRFoTools.FontChooser import ProcessFonts
+from fontCompiler.compiler import FontCompilerOptions
+from fontCompiler.emptyCompiler import EmptyOTFCompiler
+
def test_com... |
61e6fbbba42256f0a4b9d8b6ad25575ec6c21fee | scripts/datachain/datachain.py | scripts/datachain/datachain.py |
import os
import sys
import MySQLdb
sys.path.append('D:\\Projects\\PySQLKits\\lib\\simplequery')
from table_data import *
from simplequery import *
def get_mysql_connection():
args = {'host':'localhost', 'user':'root', 'passwd':'root', 'db':"test"}
conn = MySQLdb.connect(**args)
with conn.cursor() as c:... |
import os
from os.path import dirname
import sys
import MySQLdb
root_path = dirname(dirname(os.getcwd()))
require_path = os.path.join(root_path, 'lib\\simplequery')
sys.path.append(require_path)
from table_data import *
from simplequery import *
def get_mysql_connection():
args = {'host':'localhost', 'user':'r... | Refactor import path and usage | Refactor import path and usage
| Python | mit | healerkx/PySQLKits,healerkx/PySQLKits | ---
+++
@@ -1,8 +1,13 @@
import os
+from os.path import dirname
import sys
import MySQLdb
-sys.path.append('D:\\Projects\\PySQLKits\\lib\\simplequery')
+
+root_path = dirname(dirname(os.getcwd()))
+require_path = os.path.join(root_path, 'lib\\simplequery')
+sys.path.append(require_path)
+
from table_data import... |
fd2d61e6b9ce22a404ab404dcf4b4a53fe91f81a | aybu/controlpanel/handlers/base.py | aybu/controlpanel/handlers/base.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Copyright 2010 Asidev s.r.l.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by app... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Copyright 2010 Asidev s.r.l.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by app... | Set request language in admin panel if user request a different language | Set request language in admin panel if user request a different language
| Python | apache-2.0 | asidev/aybu-controlpanel | ---
+++
@@ -17,7 +17,8 @@
"""
import logging
-from aybu.core.models import User
+from pyramid.httpexceptions import HTTPBadRequest
+from aybu.core.models import Language
class BaseHandler(object):
@@ -30,10 +31,13 @@
self.request.template_helper.section = 'admin'
self.log = logging.getLogge... |
0e04613306defe11f1c358a594352008120c7b41 | datasets/admin.py | datasets/admin.py | from django.contrib import admin
from datasets.models import Dataset, Sound, Vote, Taxonomy, DatasetRelease, TaxonomyNode
class TaxonomyNodeAdmin(admin.ModelAdmin):
fields = ('node_id', 'name', 'description', 'citation_uri', 'faq', 'omitted', 'list_freesound_examples',
'list_freesound_examples_verif... | from django.contrib import admin
from datasets.models import Dataset, Sound, Vote, Taxonomy, DatasetRelease, TaxonomyNode
class TaxonomyNodeAdmin(admin.ModelAdmin):
fields = ('node_id', 'name', 'description', 'citation_uri', 'faq', 'omitted', 'list_freesound_examples',
'list_freesound_examples_verif... | Add Admin beginner task field TaxonomyNode | Add Admin beginner task field TaxonomyNode
| Python | agpl-3.0 | MTG/freesound-datasets,MTG/freesound-datasets,MTG/freesound-datasets,MTG/freesound-datasets | ---
+++
@@ -4,7 +4,7 @@
class TaxonomyNodeAdmin(admin.ModelAdmin):
fields = ('node_id', 'name', 'description', 'citation_uri', 'faq', 'omitted', 'list_freesound_examples',
- 'list_freesound_examples_verification')
+ 'list_freesound_examples_verification', 'beginner_task')
admin.... |
39228ca69262511b1d0efbfc437dda19c097d530 | logger.py | logger.py | from time import strftime
"""logger.py: A simple logging module"""
__author__ = "Prajesh Ananthan"
def printDebug(text):
print(strftime('%d/%b/%Y %H:%M:%S DEBUG | {}'.format(text)))
def printInfo(text):
print(strftime('%d/%b/%Y %H:%M:%S INFO | {}'.format(text)))
def printWarning(text):
print(strftim... | from time import strftime
"""logger.py: A simple logging module"""
__author__ = "Prajesh Ananthan"
def DEBUG(text):
print(strftime('%d/%b/%Y %H:%M:%S DEBUG | {}'.format(text)))
def INFO(text):
print(strftime('%d/%b/%Y %H:%M:%S INFO | {}'.format(text)))
def WARNING(text):
print(strftime('%d/%b/%Y %H:... | Update on the method names | Update on the method names
| Python | mit | prajesh-ananthan/Tools | ---
+++
@@ -5,13 +5,17 @@
__author__ = "Prajesh Ananthan"
-def printDebug(text):
+def DEBUG(text):
print(strftime('%d/%b/%Y %H:%M:%S DEBUG | {}'.format(text)))
-def printInfo(text):
+def INFO(text):
print(strftime('%d/%b/%Y %H:%M:%S INFO | {}'.format(text)))
-def printWarning(text):
+def WARNIN... |
fb5fc6e62a3c1b018d8f68cc37e4d541226a564b | integration-tests/features/steps/gremlin.py | integration-tests/features/steps/gremlin.py | """Tests for Gremlin database."""
import os
import requests
from behave import given, then, when
from urllib.parse import urljoin
@when('I access Gremlin API')
def gremlin_url_access(context):
"""Access the Gremlin service API using the HTTP POST method."""
post_query(context, "")
def post_query(context, q... | """Tests for Gremlin database."""
import os
import requests
from behave import given, then, when
from urllib.parse import urljoin
from src.json_utils import *
@when('I access Gremlin API')
def gremlin_url_access(context):
"""Access the Gremlin service API using the HTTP POST method."""
post_query(context, ""... | Test step for check the Gremlin response structure | Test step for check the Gremlin response structure
| Python | apache-2.0 | tisnik/fabric8-analytics-common,jpopelka/fabric8-analytics-common,jpopelka/fabric8-analytics-common,tisnik/fabric8-analytics-common,tisnik/fabric8-analytics-common,jpopelka/fabric8-analytics-common | ---
+++
@@ -4,6 +4,7 @@
from behave import given, then, when
from urllib.parse import urljoin
+from src.json_utils import *
@when('I access Gremlin API')
@@ -16,3 +17,36 @@
"""Post the already constructed query to the Gremlin."""
data = {"gremlin": query}
context.response = requests.post(conte... |
0bd469751034c9a9bc9c3b6f396885670722a692 | manage.py | manage.py | #!/usr/bin/env python
import os
from flask_script import Manager, Server
from flask_script.commands import ShowUrls, Clean
from mothership import create_app
from mothership.models import db
# default to dev config because no one should use this in
# production anyway
env = os.environ.get('MOTHERSHIP_ENV', 'dev')
app... | #!/usr/bin/env python
import os
from flask_script import Manager, Server
from flask_script.commands import ShowUrls, Clean
from mothership import create_app
from mothership.models import db
# default to dev config because no one should use this in
# production anyway
env = os.environ.get('MOTHERSHIP_ENV', 'dev')
app... | Remove comment for running under uwsgi | Remove comment for running under uwsgi | Python | mit | afl-mothership/afl-mothership,afl-mothership/afl-mothership,afl-mothership/afl-mothership,afl-mothership/afl-mothership | ---
+++
@@ -38,6 +38,3 @@
if __name__ == "__main__":
manager.run()
-
-
-# ./venv/bin/uwsgi --http 0.0.0.0:8000 --home venv --wsgi-file manage.py --callable app --master --catch-exceptions |
243f973ee1757b7b8426e9e4b62de2a272d82407 | protocols/urls.py | protocols/urls.py | from django.conf.urls import patterns, url
urlpatterns = patterns('protocols.views',
url(r'^archive/$', 'list_all_protocols', name='list_all_protocols'),
url(r'^add/$', 'add', name='add_protocol'),
)
| from django.conf.urls import patterns, url
urlpatterns = patterns('protocols.views',
url(r'^archive/$', 'list_all_protocols', name='list_all_protocols'),
url(r'^add/$', 'add', name='add_protocol'),
url(r'^page/(?P<page>.*)/$', 'listing', name='pagination')
)
| Add url for listing protocols | Add url for listing protocols
| Python | mit | Hackfmi/Diaphanum,Hackfmi/Diaphanum | ---
+++
@@ -4,4 +4,5 @@
urlpatterns = patterns('protocols.views',
url(r'^archive/$', 'list_all_protocols', name='list_all_protocols'),
url(r'^add/$', 'add', name='add_protocol'),
+ url(r'^page/(?P<page>.*)/$', 'listing', name='pagination')
) |
ef98d8bf242bfd182b4e5c8675db599182a371a5 | metpy/io/__init__.py | metpy/io/__init__.py | # Copyright (c) 2015,2016,2018 MetPy Developers.
# Distributed under the terms of the BSD 3-Clause License.
# SPDX-License-Identifier: BSD-3-Clause
"""MetPy's IO module contains classes for reading files. These classes are written
to take both file names (for local files) or file-like objects; this allows reading files... | # Copyright (c) 2015,2016,2018 MetPy Developers.
# Distributed under the terms of the BSD 3-Clause License.
# SPDX-License-Identifier: BSD-3-Clause
"""Classes for reading various file formats.
These classes are written to take both file names (for local files) or file-like objects;
this allows reading files that are a... | Make io module docstring conform to standards | MNT: Make io module docstring conform to standards
Picked up by pydocstyle 3.0.
| Python | bsd-3-clause | Unidata/MetPy,ShawnMurd/MetPy,ahaberlie/MetPy,jrleeman/MetPy,dopplershift/MetPy,jrleeman/MetPy,Unidata/MetPy,ahaberlie/MetPy,dopplershift/MetPy | ---
+++
@@ -1,10 +1,11 @@
# Copyright (c) 2015,2016,2018 MetPy Developers.
# Distributed under the terms of the BSD 3-Clause License.
# SPDX-License-Identifier: BSD-3-Clause
-"""MetPy's IO module contains classes for reading files. These classes are written
-to take both file names (for local files) or file-like o... |
d483d47ec6670a0be82c323397d995e8f2fb506c | sphinxcontrib/openstreetmap.py | sphinxcontrib/openstreetmap.py | # -*- coding: utf-8 -*-
"""
sphinxcontrib.openstreetmap
===========================
Embed OpenStreetMap on your documentation.
:copyright: Copyright 2015 HAYASHI Kentaro <kenhys@gmail.com>
:license: BSD, see LICENSE for details.
"""
from docutils import nodes
from docutils.parsers.rst import directives
from sphi... | # -*- coding: utf-8 -*-
"""
sphinxcontrib.openstreetmap
===========================
Embed OpenStreetMap on your documentation.
:copyright: Copyright 2015 HAYASHI Kentaro <kenhys@gmail.com>
:license: BSD, see LICENSE for details.
"""
from docutils import nodes
from docutils.parsers.rst import directives
from sphi... | Use id as required parameter | Use id as required parameter
| Python | bsd-2-clause | kenhys/sphinxcontrib-openstreetmap,kenhys/sphinxcontrib-openstreetmap | ---
+++
@@ -19,7 +19,7 @@
"""Directive for embedding OpenStreetMap"""
has_content = False
option_spec = {
- 'name': directives.unchanged,
+ 'id': directives.unchanged,
'label': directives.unchanged
}
|
2f222b5ea9816f55c5a07c42650a7803b92241a4 | cogs/routes/login.py | cogs/routes/login.py | """
Copyright (c) 2017 Genome Research Ltd.
Authors:
* Simon Beal <sb48@sanger.ac.uk>
* Christopher Harrison <ch12@sanger.ac.uk>
This program 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... | """
Copyright (c) 2017 Genome Research Ltd.
Authors:
* Simon Beal <sb48@sanger.ac.uk>
* Christopher Harrison <ch12@sanger.ac.uk>
This program 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... | Use the user that has been threaded through the request by the authentication middleware | Use the user that has been threaded through the request by the authentication middleware
NOTE If the DummyAuthenticator is being used, then this will be the root
user in every request, per the semantics of the original
| Python | agpl-3.0 | wtsi-hgi/CoGS-Webapp,wtsi-hgi/CoGS-Webapp,wtsi-hgi/CoGS-Webapp | ---
+++
@@ -35,11 +35,8 @@
post_req = await request.post()
user_type = post_req["type"]
- # FIXME The user is already fetched in the authentication middleware
- # or fails upon an authentication error (e.g., no such user)
- db = request.app["db"]
- user = db.get_user_by_id(1)
+ user = reque... |
8e3cc5821f3b597b256eb9f586380f3b3cfd35a8 | qnd/experiment.py | qnd/experiment.py | import tensorflow as tf
from .flag import FLAGS, FlagAdder
from .estimator import def_estimator
from .inputs import def_def_train_input_fn
from .inputs import def_def_eval_input_fn
def def_def_experiment_fn():
adder = FlagAdder()
works_with = lambda name: "Works only with {}".format(name)
train_help = w... | import tensorflow as tf
from .flag import FLAGS, FlagAdder
from .estimator import def_estimator
from .inputs import DataUse, def_def_train_input_fn, def_def_eval_input_fn
def def_def_experiment_fn():
adder = FlagAdder()
for use in DataUse:
use = use.value
adder.add_flag("{}_steps".format(use... | Fix outdated command line help | Fix outdated command line help
| Python | unlicense | raviqqe/tensorflow-qnd,raviqqe/tensorflow-qnd | ---
+++
@@ -2,19 +2,20 @@
from .flag import FLAGS, FlagAdder
from .estimator import def_estimator
-from .inputs import def_def_train_input_fn
-from .inputs import def_def_eval_input_fn
+from .inputs import DataUse, def_def_train_input_fn, def_def_eval_input_fn
def def_def_experiment_fn():
adder = FlagAd... |
b65a55189b7294547e14bea7593047f8f00518d6 | partner_communication/models/res_partner.py | partner_communication/models/res_partner.py | # -*- encoding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2016 Compassion CH (http://www.compassion.ch)
# Releasing children from poverty in Jesus' name
# @author: Emanuel Cino <ecino@compassion.ch>
#
# The licence is in the file __openerp__.p... | # -*- encoding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2016 Compassion CH (http://www.compassion.ch)
# Releasing children from poverty in Jesus' name
# @author: Emanuel Cino <ecino@compassion.ch>
#
# The licence is in the file __openerp__.p... | Change delivery of communication to manual digital by default | Change delivery of communication to manual digital by default
| Python | agpl-3.0 | CompassionCH/compassion-modules,ecino/compassion-modules,maxime-beck/compassion-modules,eicher31/compassion-modules,eicher31/compassion-modules,CompassionCH/compassion-modules,eicher31/compassion-modules,CompassionCH/compassion-modules,ecino/compassion-modules,maxime-beck/compassion-modules,ecino/compassion-modules,eic... | ---
+++
@@ -24,7 +24,7 @@
##########################################################################
global_communication_delivery_preference = fields.Selection(
selection='_get_delivery_preference',
- default='auto_digital',
+ default='digital',
required=True,
help=... |
2609042ba2a11089561d3c9d9f0542f263619951 | src/models/event.py | src/models/event.py | from flock import db
class Event(db.Model):
id = db.Column(db.Integer, primary_key=True)
def __init__(self):
pass
| from flock import db
class Event(db.Model):
id = db.Column(db.Integer, primary_key=True)
owner_id = db.Column(db.Integer, foreign_key('user.id'), primary_key=True)
def __init__(self):
pass
| Add owner as a primary, foreign key | Add owner as a primary, foreign key | Python | agpl-3.0 | DavidJFelix/hatchit,DavidJFelix/hatchit,DavidJFelix/hatchit | ---
+++
@@ -3,6 +3,7 @@
class Event(db.Model):
id = db.Column(db.Integer, primary_key=True)
+ owner_id = db.Column(db.Integer, foreign_key('user.id'), primary_key=True)
def __init__(self):
pass |
ffee30cb1a5b9e477a7456bcd753a45c2a02fb4f | glance_registry_local_check.py | glance_registry_local_check.py | #!/usr/bin/env python
from maas_common import (status_ok, status_err, metric, get_keystone_client,
get_auth_ref)
from requests import Session
from requests import exceptions as exc
def check(auth_ref):
keystone = get_keystone_client(auth_ref)
tenant_id = keystone.tenant_id
auth_t... | #!/usr/bin/env python
from maas_common import (status_ok, status_err, metric, get_keystone_client,
get_auth_ref)
from requests import Session
from requests import exceptions as exc
def check(auth_ref):
keystone = get_keystone_client(auth_ref)
tenant_id = keystone.tenant_id
auth_t... | Send proper response time even if non-200 | Send proper response time even if non-200
| Python | apache-2.0 | claco/rpc-openstack,robb-romans/rpc-openstack,cloudnull/rpc-maas,mattt416/rpc-openstack,stevelle/rpc-openstack,nrb/rpc-openstack,npawelek/rpc-maas,xeregin/rpc-openstack,xeregin/rpc-openstack,shannonmitchell/rpc-openstack,cfarquhar/rpc-openstack,git-harry/rpc-openstack,sigmavirus24/rpc-openstack,prometheanfire/rpc-opens... | ---
+++
@@ -26,17 +26,16 @@
r = s.get('%s/images' % registry_endpoint, verify=False, timeout=10)
except (exc.ConnectionError,
exc.HTTPError,
- exc.Timeout) as e:
+ exc.Timeout):
api_status = 0
milliseconds = -1
except Exception as e:
sta... |
6a462d6cbf1d82e9e600b997185a265bcd35b6e4 | jsonrpc/__init__.py | jsonrpc/__init__.py | __version = (1, 0, 4)
__version__ = version = '.'.join(map(str, __version))
__project__ = PROJECT = __name__
#from .jsonrpc import JSONRPCProtocol, JSONRPCRequest, JSONRPCResponse
#from .exceptions import *
# lint_ignore=W0611,W0401
| __version = (1, 0, 5)
__version__ = version = '.'.join(map(str, __version))
__project__ = PROJECT = __name__
#from .jsonrpc import JSONRPCProtocol, JSONRPCRequest, JSONRPCResponse
#from .exceptions import *
# lint_ignore=W0611,W0401
| Update version: add python 3.3 to classifiers. | Update version: add python 3.3 to classifiers.
| Python | mit | pavlov99/json-rpc | ---
+++
@@ -1,4 +1,4 @@
-__version = (1, 0, 4)
+__version = (1, 0, 5)
__version__ = version = '.'.join(map(str, __version))
__project__ = PROJECT = __name__ |
0cebce08025844ae1e0154b7332779be0567e9ab | ipywidgets/widgets/__init__.py | ipywidgets/widgets/__init__.py | from .widget import Widget, CallbackDispatcher, register, widget_serialization
from .domwidget import DOMWidget
from .trait_types import Color, EventfulDict, EventfulList
from .widget_bool import Checkbox, ToggleButton, Valid
from .widget_button import Button
from .widget_box import Box, FlexBox, Proxy, PlaceProxy, H... | from .widget import Widget, CallbackDispatcher, register, widget_serialization
from .domwidget import DOMWidget
from .trait_types import Color, EventfulDict, EventfulList
from .widget_bool import Checkbox, ToggleButton, Valid
from .widget_button import Button
from .widget_box import Box, FlexBox, Proxy, PlaceProxy, H... | Add ScrollableDropdown import to ipywidgets | Add ScrollableDropdown import to ipywidgets
| Python | bsd-3-clause | ipython/ipywidgets,cornhundred/ipywidgets,SylvainCorlay/ipywidgets,ipython/ipywidgets,jupyter-widgets/ipywidgets,cornhundred/ipywidgets,SylvainCorlay/ipywidgets,SylvainCorlay/ipywidgets,ipython/ipywidgets,SylvainCorlay/ipywidgets,cornhundred/ipywidgets,jupyter-widgets/ipywidgets,ipython/ipywidgets,ipython/ipywidgets,ju... | ---
+++
@@ -11,7 +11,7 @@
from .widget_int import IntText, BoundedIntText, IntSlider, IntProgress, IntRangeSlider
from .widget_color import ColorPicker
from .widget_output import Output
-from .widget_selection import RadioButtons, ToggleButtons, Dropdown, Select, SelectMultiple
+from .widget_selection import Radio... |
f0c7e1b8a2de6f7e9445e2158cf679f399df6545 | jupyternotify/jupyternotify.py | jupyternotify/jupyternotify.py | # see https://ipython.org/ipython-doc/3/config/custommagics.html
# for more details on the implementation here
import uuid
from IPython.core.getipython import get_ipython
from IPython.core.magic import Magics, magics_class, cell_magic
from IPython.display import display, Javascript
from pkg_resources import resource_f... | # see https://ipython.org/ipython-doc/3/config/custommagics.html
# for more details on the implementation here
import uuid
from IPython.core.getipython import get_ipython
from IPython.core.magic import Magics, magics_class, cell_magic
from IPython.display import display, Javascript
from pkg_resources import resource_f... | Make this work with python2 too. | Make this work with python2 too.
| Python | bsd-3-clause | ShopRunner/jupyter-notify,ShopRunner/jupyter-notify | ---
+++
@@ -11,7 +11,7 @@
@magics_class
class JupyterNotifyMagics(Magics):
def __init__(self, shell):
- super().__init__(shell)
+ super(JupyterNotifyMagics, self).__init__(shell)
with open(resource_filename("jupyternotify", "js/init.js")) as jsFile:
jsString = jsFile.read()
... |
582fb412560ce068e2ac516a64ab1979beaccdb2 | keystonemiddleware_echo/app.py | keystonemiddleware_echo/app.py | # 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, software
# distributed under t... | # 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, software
# distributed under t... | Use pprint instead of json for formatting | Use pprint instead of json for formatting
json.dumps fails to print anything for an object. I would prefer to show
a representation of the object rather than filter it out so rely on
pprint instead.
| Python | apache-2.0 | jamielennox/keystonemiddleware-echo | ---
+++
@@ -10,7 +10,7 @@
# License for the specific language governing permissions and limitations
# under the License.
-import json
+import pprint
import webob.dec
@@ -18,9 +18,8 @@
def echo_app(request):
"""A WSGI application that echoes the CGI environment to the user."""
return webob.Response... |
ac173dd3eace738b705ad5924aa830d3c3dffcf6 | Instanssi/admin_screenshow/forms.py | Instanssi/admin_screenshow/forms.py | # -*- coding: utf-8 -*-
from django import forms
from django.core.exceptions import ValidationError
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit, Layout, Fieldset, ButtonHolder
from Instanssi.screenshow.models import Sponsor,Message,IRCMessage
import os
class MessageForm(forms.Mod... | # -*- coding: utf-8 -*-
from django import forms
from django.core.exceptions import ValidationError
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit, Layout, Fieldset, ButtonHolder
from Instanssi.screenshow.models import Sponsor,Message,IRCMessage
import os
class IRCMessageForm(forms.... | Add form for irc messages. | admin_screenshow: Add form for irc messages.
| Python | mit | Instanssi/Instanssi.org,Instanssi/Instanssi.org,Instanssi/Instanssi.org,Instanssi/Instanssi.org | ---
+++
@@ -6,6 +6,26 @@
from crispy_forms.layout import Submit, Layout, Fieldset, ButtonHolder
from Instanssi.screenshow.models import Sponsor,Message,IRCMessage
import os
+
+class IRCMessageForm(forms.ModelForm):
+ def __init__(self, *args, **kwargs):
+ super(IRCMessageForm, self).__init__(*args, **kwa... |
4cf402558c084be208bbf0f4e682b2a06894738e | scikits/learn/datasets/__init__.py | scikits/learn/datasets/__init__.py | from base import load_diabetes
from base import load_digits
from base import load_files
from base import load_iris
from mlcomp import load_mlcomp
| from .base import load_diabetes
from .base import load_digits
from .base import load_files
from .base import load_iris
from .mlcomp import load_mlcomp
| Use relative imports in datasets. | Use relative imports in datasets.
| Python | bsd-3-clause | shikhardb/scikit-learn,imaculate/scikit-learn,IndraVikas/scikit-learn,bhargav/scikit-learn,yonglehou/scikit-learn,q1ang/scikit-learn,yanlend/scikit-learn,pypot/scikit-learn,theoryno3/scikit-learn,lbishal/scikit-learn,466152112/scikit-learn,icdishb/scikit-learn,IshankGulati/scikit-learn,wazeerzulfikar/scikit-learn,spall... | ---
+++
@@ -1,5 +1,5 @@
-from base import load_diabetes
-from base import load_digits
-from base import load_files
-from base import load_iris
-from mlcomp import load_mlcomp
+from .base import load_diabetes
+from .base import load_digits
+from .base import load_files
+from .base import load_iris
+from .mlcomp import... |
634d645f949f7dbff8c4e9300eebe01158649a83 | datafilters/views.py | datafilters/views.py | from django.views.generic.list import MultipleObjectMixin
__all__ = ('FilterFormMixin',)
class FilterFormMixin(MultipleObjectMixin):
"""
Mixin that adds filtering behaviour for Class Based Views.
Changed in a way that can play nicely with other CBV simply by overriding the get_queryset(self) and
get_... | from django.views.generic.list import MultipleObjectMixin
__all__ = ('FilterFormMixin',)
class FilterFormMixin(MultipleObjectMixin):
"""
Mixin that adds filtering behaviour for Class Based Views.
"""
filter_form_cls = None
use_filter_chaining = False
context_filterform_name = 'filterform'
... | Add docstrings to the view mixin | Add docstrings to the view mixin
| Python | mit | zorainc/django-datafilters,freevoid/django-datafilters,zorainc/django-datafilters | ---
+++
@@ -6,19 +6,24 @@
class FilterFormMixin(MultipleObjectMixin):
"""
Mixin that adds filtering behaviour for Class Based Views.
- Changed in a way that can play nicely with other CBV simply by overriding the get_queryset(self) and
- get_context_data(self, **kwargs) method.
"""
filter_f... |
4b127103d8bea8e9dc9793e92abee9f7a111a018 | doc/Manual/config.py | doc/Manual/config.py | from Synopsis.Config import Base
class Config (Base):
class Formatter (Base.Formatter):
class HTML (Base.Formatter.HTML):
toc_output = 'links.toc'
pages = [
'ScopePages',
'ModuleListingJS',
'ModuleIndexer',
'FileTreeJS',
'InheritanceTree',
'InheritanceGraph',
'NameIndex',
'FilePages',
'... | from Synopsis.Config import Base
class Config (Base):
class Formatter (Base.Formatter):
class HTML (Base.Formatter.HTML):
toc_output = 'links.toc'
pages = [
'ScopePages',
'ModuleListingJS',
'ModuleIndexer',
'FileTreeJS',
'InheritanceTree',
'InheritanceGraph',
'NameIndex',
'FilePages',
(... | Use custom modules in modules.py | Use custom modules in modules.py
| Python | lgpl-2.1 | stefanseefeld/synopsis,stefanseefeld/synopsis,stefanseefeld/synopsis,stefanseefeld/synopsis,stefanseefeld/synopsis,stefanseefeld/synopsis | ---
+++
@@ -12,8 +12,19 @@
'InheritanceGraph',
'NameIndex',
'FilePages',
+ ('modules.py', 'ConfScopeJS'),
'FramesIndex'
]
+ synopsis_pages = pages
+
+ # Add custom comment formatter
+ comment_formatters = [
+ 'summary', 'javadoc', 'section',
+ ('modules.py', 'RefCommentFormatter')
+ ... |
26f437d7d33c0531e53ea42a5aea247c445ec5b3 | flumotion/common/compat.py | flumotion/common/compat.py | # -*- Mode: Python -*-
# vi:si:et:sw=4:sts=4:ts=4
#
# Flumotion - a streaming media server
# Copyright (C) 2004,2005 Fluendo, S.L. (www.fluendo.com). All rights reserved.
# This file may be distributed and/or modified under the terms of
# the GNU General Public License version 2 as published by
# the Free Software Fou... | # -*- Mode: Python -*-
# vi:si:et:sw=4:sts=4:ts=4
#
# Flumotion - a streaming media server
# Copyright (C) 2004,2005 Fluendo, S.L. (www.fluendo.com). All rights reserved.
# This file may be distributed and/or modified under the terms of
# the GNU General Public License version 2 as published by
# the Free Software Fou... | Check for 2.8, not 1.8 | Check for 2.8, not 1.8
| Python | lgpl-2.1 | timvideos/flumotion,timvideos/flumotion,timvideos/flumotion,Flumotion/flumotion,flumotion-mirror/flumotion,Flumotion/flumotion,flumotion-mirror/flumotion,Flumotion/flumotion,Flumotion/flumotion | ---
+++
@@ -29,7 +29,7 @@
# gobject.type_register() if we don't need it
def type_register(type):
(major, minor, patch) = gtk.pygtk_version
- if(major <= 1 and minor < 8):
+ if(major <= 2 and minor < 8):
gobject.type_register(type)
elif(not (hasattr(type, '__gtype_name__' or hasattr(type, '__gproperties... |
b26fc811872caf3393be0a6b6c0800f5335ad2df | netbox/utilities/metadata.py | netbox/utilities/metadata.py | from rest_framework.metadata import SimpleMetadata
from django.utils.encoding import force_str
from utilities.api import ContentTypeField
class ContentTypeMetadata(SimpleMetadata):
def get_field_info(self, field):
field_info = super().get_field_info(field)
if hasattr(field, 'queryset') and not fi... | from rest_framework.metadata import SimpleMetadata
from django.utils.encoding import force_str
from utilities.api import ContentTypeField
class ContentTypeMetadata(SimpleMetadata):
def get_field_info(self, field):
field_info = super().get_field_info(field)
if hasattr(field, 'queryset') and not fi... | Sort the list for consistent output | Sort the list for consistent output
| Python | apache-2.0 | digitalocean/netbox,digitalocean/netbox,digitalocean/netbox,digitalocean/netbox | ---
+++
@@ -15,4 +15,5 @@
}
for choice_value, choice_name in field.choices.items()
]
+ field_info['choices'].sort(key=lambda item: item['display_name'])
return field_info |
7cdbf0c989109c089c758d28b68f5f1925ebf388 | securedrop/worker.py | securedrop/worker.py | import os
from redis import Redis
from rq import Queue
queue_name = 'test' if os.environ.get('SECUREDROP_ENV') == 'test' else 'default'
q = Queue(name=queue_name, connection=Redis())
def enqueue(*args, **kwargs):
q.enqueue(*args, **kwargs)
| import os
from redis import Redis
from rq import Queue
queue_name = 'test' if os.environ.get('SECUREDROP_ENV') == 'test' else 'default'
# `srm` can take a long time on large files, so allow it run for up to an hour
q = Queue(name=queue_name, connection=Redis(), default_timeout=3600)
def enqueue(*args, **kwargs):
... | Increase job timeout for securely deleting files | Increase job timeout for securely deleting files
| Python | agpl-3.0 | garrettr/securedrop,kelcecil/securedrop,jaseg/securedrop,jeann2013/securedrop,jeann2013/securedrop,chadmiller/securedrop,micahflee/securedrop,micahflee/securedrop,pwplus/securedrop,harlo/securedrop,ageis/securedrop,ageis/securedrop,jeann2013/securedrop,kelcecil/securedrop,micahflee/securedrop,harlo/securedrop,jrosco/se... | ---
+++
@@ -5,7 +5,8 @@
queue_name = 'test' if os.environ.get('SECUREDROP_ENV') == 'test' else 'default'
-q = Queue(name=queue_name, connection=Redis())
+# `srm` can take a long time on large files, so allow it run for up to an hour
+q = Queue(name=queue_name, connection=Redis(), default_timeout=3600)
def enq... |
0b9e8795318922c1c7699932d8a6e984ce00b13d | mmstats/__init__.py | mmstats/__init__.py | version = __version__ = '0.6.2'
from .defaults import *
from .fields import *
from .models import *
| version = __version__ = '0.7.0-dev'
from .defaults import *
from .fields import *
from .models import *
| Bump to 0.7.0 development version | Bump to 0.7.0 development version
| Python | bsd-3-clause | schmichael/mmstats,schmichael/mmstats,schmichael/mmstats,schmichael/mmstats | ---
+++
@@ -1,4 +1,4 @@
-version = __version__ = '0.6.2'
+version = __version__ = '0.7.0-dev'
from .defaults import *
from .fields import * |
e2b7ebf9a559a50462f64ca15a7688166fd4de9f | modules/music/gs.py | modules/music/gs.py | import subprocess
from grooveshark import Client
client = Client()
client.init()
def get_song_url(song_name):
song = client.search(song_name).next()
return song.stream.url
def play_song_url(song_url):
subprocess.call(['cvlc', song_url])
def play_song(song_name):
play_song_url(get_song_url(song_name)... | import subprocess
from grooveshark import Client
client = Client()
client.init()
def get_song_url(song_name):
song = client.search(song_name).next()
return song.stream.url
def play_song_url(song_url):
subprocess.call(['cvlc', '--play-and-exit', song_url])
def play_song(song_name):
play_song_url(get_... | Make vlc exit at end of play | Make vlc exit at end of play
| Python | mit | adelq/mirror | ---
+++
@@ -9,7 +9,7 @@
return song.stream.url
def play_song_url(song_url):
- subprocess.call(['cvlc', song_url])
+ subprocess.call(['cvlc', '--play-and-exit', song_url])
def play_song(song_name):
play_song_url(get_song_url(song_name)) |
268753ad6e4c3345e821c541e1851ee7f7a2b649 | eachday/tests/test_resource_utils.py | eachday/tests/test_resource_utils.py | from eachday.tests.base import BaseTestCase
import json
class TestResourceUtils(BaseTestCase):
def test_invalid_json_error(self):
''' Test that an invalid JSON body has a decent error message '''
resp = self.client.post(
'/register',
data='{"invalid": json}',
co... | from eachday.resources import LoginResource
from eachday.tests.base import BaseTestCase
from unittest.mock import patch
import json
class TestResourceUtils(BaseTestCase):
def test_invalid_json_error(self):
''' Test that an invalid JSON body has a decent error message '''
resp = self.client.post(
... | Add test for exception handling in flask app | Add test for exception handling in flask app
| Python | mit | bcongdon/EachDay,bcongdon/EachDay,bcongdon/EachDay,bcongdon/EachDay | ---
+++
@@ -1,4 +1,6 @@
+from eachday.resources import LoginResource
from eachday.tests.base import BaseTestCase
+from unittest.mock import patch
import json
@@ -14,3 +16,30 @@
self.assertEqual(resp.status_code, 400)
self.assertEqual(data['status'], 'error')
self.assertEqual(data['err... |
24089dfb12c3ecbec40423acf4d3c89c0b833f40 | share/models/util.py | share/models/util.py | import zlib
import base64
import binascii
from django.db import models
from django.core import exceptions
class ZipField(models.Field):
def db_type(self, connection):
return 'bytea'
def pre_save(self, model_instance, add):
value = getattr(model_instance, self.attname)
assert isinsta... | import zlib
import base64
import binascii
from django.db import models
from django.core import exceptions
class ZipField(models.Field):
def db_type(self, connection):
return 'bytea'
def pre_save(self, model_instance, add):
value = getattr(model_instance, self.attname)
assert isinsta... | Make it just return the string if it is not base64 | Make it just return the string if it is not base64
| Python | apache-2.0 | CenterForOpenScience/SHARE,aaxelb/SHARE,laurenbarker/SHARE,CenterForOpenScience/SHARE,zamattiac/SHARE,laurenbarker/SHARE,aaxelb/SHARE,zamattiac/SHARE,laurenbarker/SHARE,zamattiac/SHARE,aaxelb/SHARE,CenterForOpenScience/SHARE | ---
+++
@@ -30,10 +30,10 @@
assert value
if value is None or isinstance(value, ZipField):
return value
- # TODO: Not sure if this is necessary or just solving a temporary error
try:
- base64.decodestring(bytes(value, 'utf8'))
+ base64.decodebytes(by... |
8c8f26ffe52e2df68a8f7ba87871f260a5023406 | measurement/measures/energy.py | measurement/measures/energy.py | from measurement.base import MeasureBase
__all__ = [
'Energy'
]
class Energy(MeasureBase):
STANDARD_UNIT = 'J'
UNITS = {
'c': 4.18400,
'C': 4184.0,
'J': 1.0,
'eV': 1.602177e-9,
'tonne_tnt': 4184000000,
}
ALIAS = {
'joule': 'J',
'calorie': '... | from measurement.base import MeasureBase
__all__ = [
'Energy'
]
class Energy(MeasureBase):
STANDARD_UNIT = 'J'
UNITS = {
'c': 4.18400,
'C': 4184.0,
'J': 1.0,
'eV': 1.602177e-19,
'tonne_tnt': 4184000000,
}
ALIAS = {
'joule': 'J',
'calorie': ... | Correct factor for electron volt | Correct factor for electron volt
| Python | mit | yggdr/python-measurement,coddingtonbear/python-measurement | ---
+++
@@ -12,7 +12,7 @@
'c': 4.18400,
'C': 4184.0,
'J': 1.0,
- 'eV': 1.602177e-9,
+ 'eV': 1.602177e-19,
'tonne_tnt': 4184000000,
}
ALIAS = { |
9aa60f5da016468b345fac4499454ca4abeb8b3f | ansible/roles/cumulus/files/amis.py | ansible/roles/cumulus/files/amis.py | import boto.ec2
import sys
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('aws_access_key_id')
parser.add_argument('aws_secret_access_key')
parser.add_argument('region')
config = parser.parse_args()
conn = boto.ec2.connect_to_region(config.region,
aws_access_k... | import boto.ec2
import sys
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('aws_access_key_id')
parser.add_argument('aws_secret_access_key')
parser.add_argument('region')
config = parser.parse_args()
conn = boto.ec2.connect_to_region(config.region,
aws_access_... | Fix python 3 incompatible print statement | Fix python 3 incompatible print statement
| Python | apache-2.0 | Kitware/HPCCloud-deploy,Kitware/HPCCloud-deploy,Kitware/HPCCloud-deploy | ---
+++
@@ -1,6 +1,7 @@
import boto.ec2
import sys
import argparse
+
parser = argparse.ArgumentParser()
parser.add_argument('aws_access_key_id')
@@ -17,4 +18,4 @@
for image in images:
values.append('"%s": "%s"' % (image.name, image.id))
-print ','.join(values)
+print( ','.join(values)) |
4047f744debb73d64de03bc0e7f16d2bbd308529 | ores/wsgi/routes/__init__.py | ores/wsgi/routes/__init__.py |
from . import scores
from . import ui
def configure(config, bp, score_processor):
@bp.route("/", methods=["GET"])
def index():
return render_template("home.html")
bp = scores.configure(config, bp, score_processor)
bp = ui.configure(config, bp)
return bp
|
from . import scores
from . import ui
def configure(config, bp, score_processor):
@bp.route("/", methods=["GET"])
def index():
return ui.render_template("home.html")
bp = scores.configure(config, bp, score_processor)
bp = ui.configure(config, bp)
return bp
| FIX 'render_template not defined' error | FIX 'render_template not defined' error
This was appearing if you try to open 'http://host:port/'
| Python | mit | he7d3r/ores,wiki-ai/ores,he7d3r/ores,he7d3r/ores,wiki-ai/ores,wiki-ai/ores | ---
+++
@@ -7,7 +7,7 @@
@bp.route("/", methods=["GET"])
def index():
- return render_template("home.html")
+ return ui.render_template("home.html")
bp = scores.configure(config, bp, score_processor)
bp = ui.configure(config, bp) |
eb368c344075ce78606d4656ebfb19c7e7ccdf50 | src/054.py | src/054.py | from path import dirpath
def ans():
lines = open(dirpath() + '054.txt').readlines()
cards = [line.strip().split() for line in lines]
return None
if __name__ == '__main__':
print(ans())
| from collections import (
defaultdict,
namedtuple,
)
from path import dirpath
def _value(rank):
try:
return int(rank)
except ValueError:
return 10 + 'TJQKA'.index(rank)
def _sort_by_rank(hand):
return list(reversed(sorted(
hand,
key=lambda card: _value(card[0]),
... | Write some logic for 54 | Write some logic for 54
| Python | mit | mackorone/euler | ---
+++
@@ -1,9 +1,95 @@
+from collections import (
+ defaultdict,
+ namedtuple,
+)
from path import dirpath
+
+
+def _value(rank):
+ try:
+ return int(rank)
+ except ValueError:
+ return 10 + 'TJQKA'.index(rank)
+
+
+def _sort_by_rank(hand):
+ return list(reversed(sorted(
+ hand,... |
88517c2f458a0e94b1a526bf99e565571353ed56 | flicktor/__main__.py | flicktor/__main__.py | from flicktor import subcommands
def main():
parser = subcommands._argpaser()
args = parser.parse_args()
try:
args.func(args)
# except AttributeError:
# parser.print_help()
except KeyboardInterrupt:
print("bye.")
if __name__ == '__main__':
main()
| from flicktor import subcommands
def main():
parser = subcommands._argpaser()
args = parser.parse_args()
try:
if hasattr(args, "func"):
args.func(args)
else:
parser.print_help()
except KeyboardInterrupt:
print("bye.")
if __name__ == '__main__':
... | Print help when subcommand is not supecified | Print help when subcommand is not supecified
| Python | mit | minamorl/flicktor | ---
+++
@@ -5,9 +5,12 @@
parser = subcommands._argpaser()
args = parser.parse_args()
try:
- args.func(args)
- # except AttributeError:
- # parser.print_help()
+ if hasattr(args, "func"):
+ args.func(args)
+ else:
+ parser.print_help()
+
+
exc... |
6c19837ec2d29e2ad48c09b6287e64c825830bc9 | prototypes/regex/__init__.py | prototypes/regex/__init__.py | # coding: utf-8
"""
regex
~~~~~
This is a prototype for an implementation of regular expressions. The goal
of this prototype is to develop a completely transparent implementation,
that can be better reasoned about and used in a parser.
Note that as of now "regular expressions" actually means *... | # coding: utf-8
"""
regex
~~~~~
This is a prototype for an implementation of regular expressions. The goal
of this prototype is to develop a completely transparent implementation,
that can be better reasoned about and used in a parser. This is not meant
to be an implementation that will see rea... | Add warning about real-world usage | Add warning about real-world usage
| Python | bsd-3-clause | DasIch/editor | ---
+++
@@ -5,7 +5,10 @@
This is a prototype for an implementation of regular expressions. The goal
of this prototype is to develop a completely transparent implementation,
- that can be better reasoned about and used in a parser.
+ that can be better reasoned about and used in a parser. This is not... |
1b5ad9a8e2b06218d511ce8f97521235c14a9507 | src/app.py | src/app.py | import os
import json
import random
import flask
from hashlib import md5
records = {}
# Create a hash table of all records.
for record in json.loads(open('data/records-2015.json').read())['records']:
records[md5(str(record['id']).encode('utf-8')).hexdigest()] = record
app = flask.Flask(__name__)
@app.route('/... | import os
import json
import random
import flask
import requests
import hashlib
DNZ_URL = 'http://api.digitalnz.org/v3/records/'
DNZ_KEY = os.environ.get('DNZ_KEY')
records = {}
# TODO This should be switched to records associated with days.
# Create a hash table of all records.
for record in json.loads(open('data/re... | Add method to query DNZ Metadata API | Add method to query DNZ Metadata API
| Python | mit | judsonsam/tekautoday,judsonsam/tekautoday,judsonsam/tekautoday,judsonsam/tekautoday | ---
+++
@@ -2,14 +2,18 @@
import json
import random
import flask
+import requests
+import hashlib
-from hashlib import md5
-
+DNZ_URL = 'http://api.digitalnz.org/v3/records/'
+DNZ_KEY = os.environ.get('DNZ_KEY')
records = {}
+# TODO This should be switched to records associated with days.
# Create a hash tab... |
c458126baac92e1152026f51a9d3a544e8c6826f | testsV2/ut_repy2api_copycontext.py | testsV2/ut_repy2api_copycontext.py | """
Check that copy and repr of _context SafeDict don't result in inifinite loop
"""
#pragma repy
# Create an almost shallow copy of _context
# Contained self-reference is moved from _context to _context_copy
_context_copy = _context.copy()
repr(_context)
repr(_context_copy)
| """
Check that copy and repr of _context SafeDict don't result in infinite loop
"""
#pragma repy
# Create an "almost" shallow copy of _context, i.e. the contained reference
# to _context is not copied as such but is changed to reference the new
# _context_copy.
# In consequence repr immediately truncates the contained... | Update comment in copycontext unit test | Update comment in copycontext unit test
Following @vladimir-v-diaz's review comment this change adds
more information about how repr works with Python dicts and with
repy's SafeDict to the unit test's comments.
Even more information can be found on the issue tracker
SeattleTestbed/repy_v2#97.
| Python | mit | SeattleTestbed/repy_v2 | ---
+++
@@ -1,10 +1,15 @@
"""
-Check that copy and repr of _context SafeDict don't result in inifinite loop
+Check that copy and repr of _context SafeDict don't result in infinite loop
"""
#pragma repy
-# Create an almost shallow copy of _context
-# Contained self-reference is moved from _context to _context_cop... |
d10199e4e3cd5b0557cf2dc2f4aea1014f18a290 | lib/wordfilter.py | lib/wordfilter.py | import os
import json
class Wordfilter:
def __init__(self):
# json is in same directory as this class, given by __location__.
__location__ = os.path.realpath(
os.path.join(os.getcwd(), os.path.dirname(__file__)))
with open(os.path.join(__location__, 'badwords.json')) as f:
self.blacklist = ... | import os
import json
class Wordfilter:
def __init__(self):
# json is in same directory as this class, given by __location__.
__location__ = os.path.realpath(
os.path.join(os.getcwd(), os.path.dirname(__file__)))
with open(os.path.join(__location__, 'badwords.json')) as f:
self.blacklist = ... | Fix AttributeError: 'list' object has no attribute 'lower' | Fix AttributeError: 'list' object has no attribute 'lower'
| Python | mit | dariusk/wordfilter,hugovk/wordfilter,hugovk/wordfilter,mwatson/wordfilter,hugovk/wordfilter,dariusk/wordfilter,mwatson/wordfilter,dariusk/wordfilter,mwatson/wordfilter,mwatson/wordfilter,dariusk/wordfilter,hugovk/wordfilter | ---
+++
@@ -16,9 +16,9 @@
return True
return False
-
+
def addWords(self, words):
- self.blacklist.extend(words.lower())
+ self.blacklist.extend([word.lower() for word in words]])
def clearList(self):
self.blacklist = [] |
322d8f90f86c40a756716a79e7e5719196687ece | saic/paste/search_indexes.py | saic/paste/search_indexes.py | import datetime
from haystack.indexes import *
from haystack import site
from models import Paste, Commit
class CommitIndex(RealTimeSearchIndex):
text = CharField(document=True, use_template=True)
commit = CharField(model_attr='commit')
created = DateField(model_attr='created')
user = CharField(model_a... | import datetime
from haystack.indexes import *
from haystack import site
from models import Paste, Commit
class CommitIndex(RealTimeSearchIndex):
text = CharField(document=True, use_template=True)
commit = CharField(model_attr='commit')
created = DateField(model_attr='created')
user = CharField(model_a... | Update search index to look for all objects. | Update search index to look for all objects.
| Python | bsd-3-clause | justinvh/gitpaste,GarrettHeel/quark-paste,GarrettHeel/quark-paste,justinvh/gitpaste,justinvh/gitpaste,justinvh/gitpaste,GarrettHeel/quark-paste | ---
+++
@@ -9,6 +9,9 @@
created = DateField(model_attr='created')
user = CharField(model_attr='owner', null=True)
+ def index_queryset(self):
+ return Commit.objects.all()
+
class PasteIndex(RealTimeSearchIndex):
text = CharField(document=True, use_template=True)
@@ -17,6 +20,9 @@
l... |
1bda3fa8b3bffaca38b26191602e74d0afeaad19 | app/views.py | app/views.py | from flask import render_template, request, Blueprint
import json
from app.state import state
index = Blueprint('index', __name__, template_folder='templates')
@index.route('/', methods=['POST', 'GET'])
def show():
if request.method == 'GET':
return render_template('index.html',
program = '... | from flask import render_template, request, Blueprint
import json
from app.state import state
index = Blueprint('index', __name__, template_folder='templates')
@index.route('/', methods=['GET'])
def show():
if request.method == 'GET':
return render_template('index.html') | Remove old web ui backend | Remove old web ui backend
| Python | mit | njbbaer/unicorn-remote,njbbaer/unicorn-remote,njbbaer/unicorn-remote | ---
+++
@@ -5,37 +5,8 @@
index = Blueprint('index', __name__, template_folder='templates')
-@index.route('/', methods=['POST', 'GET'])
+@index.route('/', methods=['GET'])
def show():
-
+
if request.method == 'GET':
- return render_template('index.html',
- program = 'ascii_text',
- ... |
5fcc90741e443133695c65e04b26fc9d1313e530 | djangae/models.py | djangae/models.py | from django.db import models
from djangae import patches
class CounterShard(models.Model):
count = models.PositiveIntegerField()
# Apply our django patches
patches.patch()
| from django.db import models
from djangae import patches
class CounterShard(models.Model):
count = models.PositiveIntegerField()
class Meta:
app_label = "djangae"
# Apply our django patches
patches.patch()
| Fix a warning in 1.8 | Fix a warning in 1.8
| Python | bsd-3-clause | wangjun/djangae,trik/djangae,martinogden/djangae,asendecka/djangae,grzes/djangae,leekchan/djangae,chargrizzle/djangae,grzes/djangae,martinogden/djangae,armirusco/djangae,potatolondon/djangae,SiPiggles/djangae,kirberich/djangae,potatolondon/djangae,armirusco/djangae,asendecka/djangae,leekchan/djangae,SiPiggles/djangae,c... | ---
+++
@@ -6,5 +6,8 @@
class CounterShard(models.Model):
count = models.PositiveIntegerField()
+ class Meta:
+ app_label = "djangae"
+
# Apply our django patches
patches.patch() |
3d9b7fe808f2c8a64e0b834c0a67fa53631e5235 | dbaas/api/integration_credential.py | dbaas/api/integration_credential.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from rest_framework import viewsets, serializers
from integrations.credentials.models import IntegrationCredential
from .environment import EnvironmentSerializer
from .integration_type import IntegrationTypeSerializer
class IntegrationCr... | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from rest_framework import viewsets, serializers
from integrations.credentials.models import IntegrationCredential
from .environment import EnvironmentSerializer
from .integration_type import IntegrationTypeSerializer
class IntegrationCr... | Add project to integration credential api fields | Add project to integration credential api fields
| Python | bsd-3-clause | globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service | ---
+++
@@ -13,7 +13,7 @@
class Meta:
model = IntegrationCredential
- fields = ('user', 'password', 'integration_type', 'token', 'secret', 'endpoint', 'environments')
+ fields = ('user', 'password', 'integration_type', 'token', 'secret', 'endpoint', 'environments',"project",)
class ... |
eb6e89409296443369b73f5a0475ef8903700037 | servers/curioecho_streams.py | servers/curioecho_streams.py | from curio import Kernel, new_task, run_server
from socket import *
async def echo_handler(client, addr):
print('Connection from', addr)
try:
client.setsockopt(IPPROTO_TCP, TCP_NODELAY, 1)
except (OSError, NameError):
pass
reader, writer = client.make_streams()
async with reader, wr... | from curio import Kernel, new_task, run_server
from socket import *
async def echo_handler(client, addr):
print('Connection from', addr)
try:
client.setsockopt(IPPROTO_TCP, TCP_NODELAY, 1)
except (OSError, NameError):
pass
reader, writer = client.make_streams()
async with reader, wr... | Use explicit read buffer size in curio/streams bench | Use explicit read buffer size in curio/streams bench
| Python | mit | MagicStack/vmbench,MagicStack/vmbench,MagicStack/vmbench,MagicStack/vmbench,MagicStack/vmbench | ---
+++
@@ -10,7 +10,7 @@
reader, writer = client.make_streams()
async with reader, writer:
while True:
- data = await reader.read()
+ data = await reader.read(102400)
if not data:
break
await writer.write(data) |
db78e585c9b2edfdf9ccb5025d429b2e25f641fd | jupyterhub_config.py | jupyterhub_config.py | import os
import re
c = get_config()
c.JupyterHub.hub_ip = '0.0.0.0'
c.DockerSpawner.use_docker_client_env = True
c.DockerSpawner.tls_assert_hostname = True
c.JupyterHub.spawner_class = 'dockerspawner.DockerSpawner'
c.JupyterHub.authenticator_class = 'oauthenticator.GitHubOAuthenticator'
c.JupyterHub.login_url = '... | import os
import re
c = get_config()
c.JupyterHub.hub_ip = '0.0.0.0'
c.JupyterHub.spawner_class = 'dockerspawner.DockerSpawner'
c.DockerSpawner.tls_verify = True
c.DockerSpawner.tls_ca = "/etc/docker/ca.pem"
c.DockerSpawner.tls_cert = "/etc/docker/server-cert.pem"
c.DockerSpawner.tls_key = "/etc/docker/server-key.pe... | Configure TLS for the DockerSpawner. | Configure TLS for the DockerSpawner.
| Python | apache-2.0 | smashwilson/jupyterhub-carina,smashwilson/jupyterhub-carina | ---
+++
@@ -4,10 +4,12 @@
c = get_config()
c.JupyterHub.hub_ip = '0.0.0.0'
-c.DockerSpawner.use_docker_client_env = True
-c.DockerSpawner.tls_assert_hostname = True
c.JupyterHub.spawner_class = 'dockerspawner.DockerSpawner'
+c.DockerSpawner.tls_verify = True
+c.DockerSpawner.tls_ca = "/etc/docker/ca.pem"
+c.Do... |
0de3ca1439acec9191932a51e222aabc8b957047 | mosql/__init__.py | mosql/__init__.py | # -*- coding: utf-8 -*-
VERSION = (0, 11,)
__author__ = 'Mosky <http://mosky.tw>'
__version__ = '.'.join(str(v) for v in VERSION)
| # -*- coding: utf-8 -*-
VERSION = (0, 12,)
__author__ = 'Mosky <http://mosky.tw>'
__version__ = '.'.join(str(v) for v in VERSION)
| Change the version to v0.12 | Change the version to v0.12
| Python | mit | moskytw/mosql | ---
+++
@@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
-VERSION = (0, 11,)
+VERSION = (0, 12,)
__author__ = 'Mosky <http://mosky.tw>'
__version__ = '.'.join(str(v) for v in VERSION) |
1dfec537de941e32a13905a2aab7352439961bd3 | entrypoint.py | entrypoint.py | #!/usr/bin/python3
#
# Define containerized environment for running Diosix on Qemu
#
# On Google Cloud Run: Creates HTTP server on port 8080
# or whatever was specified using the PORT system variable.
# Outputs via the HTTP port. This requires K_SERVICE to be set.
#
# On all other environments: Log to stdout
#
# syntax... | #!/usr/bin/python3
#
# Define containerized environment for running Diosix on Qemu
#
# On Google Cloud Run: Creates HTTP server on port 8080
# or whatever was specified using the PORT system variable.
# Outputs via the HTTP port. This requires K_SERVICE to be set.
#
# On all other environments: Log to stdout
#
# syntax... | Debug Google Cloud Run support | Debug Google Cloud Run support
| Python | mit | diodesign/diosix | ---
+++
@@ -23,13 +23,13 @@
if __name__ == "__main__":
if (os.environ.get('K_SERVICE')) != '':
print('Running HTTP service for Google Cloud')
- app = Flask(__name__)
- @app.route('/')
- def ContainerService():
- return 'Container built. Use docker images and docker run i... |
3bf9853e83bf8d95844b58acac0d027b0ef5b863 | fbanalysis.py | fbanalysis.py | import random
import operator
def get_sentiment(current_user, users, threads):
friend_msg_count = {}
for user in users.keys():
friend_msg_count[user] = 0
for thread in threads:
for comment in thread:
try:
sender = comment['from']['id']
if sender n... | import random
import operator
def get_sentiment(current_user, users, threads):
friend_msg_count = {}
for user in users.keys():
friend_msg_count[user] = 0
for thread in threads:
for comment in thread:
try:
sender = comment['from']['id']
if sender n... | Change romance to outlook, outlook to volume | Change romance to outlook, outlook to volume
| Python | mit | tomshen/dearstalker,tomshen/dearstalker | ---
+++
@@ -15,29 +15,15 @@
friend_msg_count[sender] += 1
friend_msg_count[current_user['id']] = None
max_comments = float(max(friend_msg_count.values()))
- def outlook(user):
+ def volume(user):
if user['id'] not in friend_msg_count:
print '%s not found in message c... |
ebd7a18402168ae7a27f771e1a27daffa88791d0 | file_stats.py | file_stats.py | from heapq import heappush, heappushpop, heappop
import os
from pathlib import Path
import sys
from typing import List, Tuple
N_LARGEST = 50
"""Number of long file names to list."""
def main():
try:
root = sys.argv[1]
except IndexError:
root = Path.home() / 'Dropbox (Springboard)'
leng... | from heapq import heappush, heappushpop
import os
from pathlib import Path
import sys
from typing import List, Tuple
N_LARGEST = 50
"""Number of long file names to list."""
def main():
try:
root = sys.argv[1]
except IndexError:
root = Path.home() / 'Dropbox (Springboard)'
lengths: List... | Print stats highest to lowest | Print stats highest to lowest
| Python | apache-2.0 | blokeley/dfb,blokeley/backup_dropbox | ---
+++
@@ -1,4 +1,4 @@
-from heapq import heappush, heappushpop, heappop
+from heapq import heappush, heappushpop
import os
from pathlib import Path
import sys
@@ -41,21 +41,22 @@
def heap_to_max(heap, item, max_size=N_LARGEST):
- if len(heap) >= max_size:
- heappushpop(heap, item)
+ """... |
82ab7f6e618367b5544fe71dea57f793ebb6b453 | auth0/v2/client.py | auth0/v2/client.py | from .rest import RestClient
class Client(object):
"""Docstring for Client. """
def __init__(self, domain, jwt_token):
url = 'https://%s/api/v2/clients' % domain
self.client = RestClient(endpoint=url, jwt=jwt_token)
def all(self, fields=[], include_fields=True):
params = {'fiel... | from .rest import RestClient
class Client(object):
"""Docstring for Client. """
def __init__(self, domain, jwt_token):
url = 'https://%s/api/v2/clients' % domain
self.client = RestClient(endpoint=url, jwt=jwt_token)
def all(self, fields=[], include_fields=True):
"""Retrieves a ... | Add docstring for Client.all() method | Add docstring for Client.all() method
| Python | mit | auth0/auth0-python,auth0/auth0-python | ---
+++
@@ -11,6 +11,20 @@
self.client = RestClient(endpoint=url, jwt=jwt_token)
def all(self, fields=[], include_fields=True):
+ """Retrieves a list of all client applications.
+
+ Important: The client_secret and encryption_key attributes can only be
+ retrieved with the read:cl... |
e5a0fcb1fac87ea23bf032bfb266f5eea89d4c21 | pyranha/__init__.py | pyranha/__init__.py | # Copyright (c) 2012 John Reese
# Licensed under the MIT License
from __future__ import absolute_import, division
engine = None
ui = None
def async_engine_command(command, network=None, params=None):
"""Send a command to the current backend engine."""
return engine.async_command(command, network, params)
de... | # Copyright (c) 2012 John Reese
# Licensed under the MIT License
from __future__ import absolute_import, division
engine = None
ui = None
def async_engine_command(command, network=None, params=None):
"""Send a command to the current backend engine."""
return engine.async_command(command, network, params)
de... | Use gtk ui by default | Use gtk ui by default
| Python | mit | jreese/pyranha | ---
+++
@@ -14,7 +14,7 @@
"""Send a message to the current frontend user interface."""
return ui.async_message(message_type, network, content)
-def start(frontend='stdout'):
+def start(frontend='gtk'):
"""Initialize both the backend and frontend, and wait for them to mutually exit."""
global eng... |
c7af37a407a2cab7319f910830c6149addcde7d1 | djangoautoconf/tastypie_utils.py | djangoautoconf/tastypie_utils.py | from tastypie.authorization import DjangoAuthorization
from tastypie.resources import ModelResource
from req_with_auth import DjangoUserAuthentication
def create_tastypie_resource_class(class_inst):
resource_class = type(class_inst.__name__ + "Resource", (ModelResource, ), {
"Meta": type("Meta", (), {
... | from tastypie.authorization import DjangoAuthorization
from tastypie.resources import ModelResource
from req_with_auth import DjangoUserAuthentication
import re
def class_name_to_low_case(class_name):
s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', class_name)
return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower(... | Fix tastypie resource name issue. | Fix tastypie resource name issue.
| Python | bsd-3-clause | weijia/djangoautoconf,weijia/djangoautoconf | ---
+++
@@ -1,15 +1,27 @@
from tastypie.authorization import DjangoAuthorization
from tastypie.resources import ModelResource
from req_with_auth import DjangoUserAuthentication
+import re
-def create_tastypie_resource_class(class_inst):
+def class_name_to_low_case(class_name):
+ s1 = re.sub('(.)([A-Z][a-z]+... |
b60fabed64fc926066fc41f59a637dbfe2ac0bf9 | emstrack/forms.py | emstrack/forms.py | from django.contrib.gis.forms import widgets
class LeafletPointWidget(widgets.BaseGeometryWidget):
template_name = 'leaflet/leaflet.html'
class Media:
css = {
'all': ('https://cdnjs.cloudflare.com/ajax/libs/leaflet/v0.7.7/leaflet.css',
'leaflet/css/location_form.css',
... | from django.contrib.gis.forms import widgets
class LeafletPointWidget(widgets.BaseGeometryWidget):
template_name = 'leaflet/leaflet.html'
class Media:
css = {
'all': ('https://cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.7/leaflet.css',
'leaflet/css/location_form.css',
... | Update leaflet request to be over https | Update leaflet request to be over https
| Python | bsd-3-clause | EMSTrack/WebServerAndClient,EMSTrack/WebServerAndClient,EMSTrack/WebServerAndClient | ---
+++
@@ -5,12 +5,12 @@
class Media:
css = {
- 'all': ('https://cdnjs.cloudflare.com/ajax/libs/leaflet/v0.7.7/leaflet.css',
+ 'all': ('https://cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.7/leaflet.css',
'leaflet/css/location_form.css',
'... |
20d63ba3fa1a9780d4a13c5119ae97a772efb502 | teardown_tests.py | teardown_tests.py | #!/usr/bin/env python
import os
import shutil
import sys
if not os.environ.get("TEST_NOTEBOOKS"):
sys.exit(0)
for each in list(sys.argv[1:]) + [
"reg.h5",
"reg_sub.h5",
"reg_f_f0.h5",
"reg_wt.h5",
"reg_norm.h5",
"reg_dict.h5",
"reg_post.h5",
"reg_traces.h5",
"reg_rois.h5",
... | #!/usr/bin/env python
import os
import shutil
import sys
if not os.environ.get("TEST_NOTEBOOKS"):
sys.exit(0)
for each in list(sys.argv[1:]) + [
"reg.h5",
"reg_sub.h5",
"reg_f_f0.h5",
"reg_wt.h5",
"reg_norm.h5",
"reg_dict.h5",
"reg_post.h5",
"reg_traces.h5",
"reg_rois.h5",
... | Remove test Zarr files after completion. | Remove test Zarr files after completion.
| Python | apache-2.0 | nanshe-org/nanshe_workflow,DudLab/nanshe_workflow | ---
+++
@@ -20,6 +20,16 @@
"reg_traces.h5",
"reg_rois.h5",
"reg_proj.h5",
+ "reg.zarr",
+ "reg_sub.zarr",
+ "reg_f_f0.zarr",
+ "reg_wt.zarr",
+ "reg_norm.zarr",
+ "reg_dict.zarr",
+ "reg_post.zarr",
+ "reg_traces.zarr",
+ "reg_rois.zarr",
+ "reg_proj.zarr",
"reg_proj.... |
b0105f42f13b81741b4be2b52e295b906aa0c144 | service/__init__.py | service/__init__.py | import logging
from logging import config
from flask import Flask
import dateutil
import dateutil.parser
import json
from flask_login import LoginManager
from config import CONFIG_DICT
app = Flask(__name__)
app.config.update(CONFIG_DICT)
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login... | import logging
from logging import config
from flask import Flask
import dateutil
import dateutil.parser
import json
from flask_login import LoginManager
from config import CONFIG_DICT
app = Flask(__name__)
app.config.update(CONFIG_DICT)
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login... | Set cookie protection mode to strong | Set cookie protection mode to strong
| Python | mit | LandRegistry/digital-register-frontend,LandRegistry/digital-register-frontend,LandRegistry/digital-register-frontend,LandRegistry/digital-register-frontend | ---
+++
@@ -15,6 +15,7 @@
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = '/login'
+login_manager.session_protection = "strong"
def format_datetime(value): |
58b5a991d91101b9149014def8e93fe70852ae32 | measurement/views.py | measurement/views.py | from .models import Measurement
from rest_framework import viewsets
from graph.serializers import MeasurementGraphSeriesSerializer
from rest_framework.exceptions import ParseError
from api.permissions import IsPatient
from rest_framework.permissions import IsAuthenticated
from rest_framework.views import APIView
from d... | from .models import Measurement
from rest_framework import viewsets
from graph.serializers import MeasurementGraphSeriesSerializer
from rest_framework.exceptions import ParseError
from api.permissions import IsPatient
from rest_framework.permissions import IsAuthenticated
from rest_framework.views import APIView
from d... | Update measurements endpoint of current patient | Update measurements endpoint of current patient
| Python | mit | sigurdsa/angelika-api | ---
+++
@@ -7,6 +7,7 @@
from rest_framework.views import APIView
from django.core.exceptions import PermissionDenied
from rest_framework.response import Response
+from patient.serializers import PatientGraphSeriesSerializer
class CurrentPatientMeasurements(APIView):
@@ -29,6 +30,5 @@
if 'T' == type a... |
68086a879b13040d62a8958bcb4839d6661f9d0c | knowledge_repo/app/auth_providers/ldap.py | knowledge_repo/app/auth_providers/ldap.py | from flask import request, render_template, redirect, url_for
from ldap3 import Server, Connection, ALL
from ldap3.core.exceptions import LDAPSocketOpenError
from ..models import User
from ..auth_provider import KnowledgeAuthProvider
class LdapAuthProvider(KnowledgeAuthProvider):
_registry_keys = ['ldap']
d... | from ..auth_provider import KnowledgeAuthProvider
from ..models import User
from flask import (
redirect,
render_template,
request,
url_for,
)
from ldap3 import Server, Connection, ALL
class LdapAuthProvider(KnowledgeAuthProvider):
_registry_keys = ['ldap']
def init(self):
if not sel... | Sort import statements in another file | Sort import statements in another file
| Python | apache-2.0 | airbnb/knowledge-repo,airbnb/knowledge-repo,airbnb/knowledge-repo,airbnb/knowledge-repo,airbnb/knowledge-repo | ---
+++
@@ -1,9 +1,12 @@
-from flask import request, render_template, redirect, url_for
+from ..auth_provider import KnowledgeAuthProvider
+from ..models import User
+from flask import (
+ redirect,
+ render_template,
+ request,
+ url_for,
+)
from ldap3 import Server, Connection, ALL
-from ldap3.core.exc... |
1c6b06f240d4388b3e140e3d9ab610711616f539 | src/python/expedient/clearinghouse/resources/models.py | src/python/expedient/clearinghouse/resources/models.py | '''
@author: jnaous
'''
from django.db import models
from expedient.clearinghouse.aggregate.models import Aggregate
from expedient.common.extendable.models import Extendable
from expedient.clearinghouse.slice.models import Slice
class Resource(Extendable):
'''
Generic model of a resource.
@param aggre... | '''
@author: jnaous
'''
from django.db import models
from expedient.clearinghouse.aggregate.models import Aggregate
from expedient.common.extendable.models import Extendable
from expedient.clearinghouse.slice.models import Slice
from datetime import datetime
class Resource(Extendable):
'''
Generic model of a r... | Add functions to manage status change timestamp better | Add functions to manage status change timestamp better
| Python | bsd-3-clause | avlach/univbris-ocf,avlach/univbris-ocf,avlach/univbris-ocf,avlach/univbris-ocf | ---
+++
@@ -5,6 +5,7 @@
from expedient.clearinghouse.aggregate.models import Aggregate
from expedient.common.extendable.models import Extendable
from expedient.clearinghouse.slice.models import Slice
+from datetime import datetime
class Resource(Extendable):
'''
@@ -18,16 +19,20 @@
name = models... |
570264014456ea0405af28feb92af7639fb7b7e3 | metaopt/invoker/util/determine_package.py | metaopt/invoker/util/determine_package.py | """
Utility that detects the package of a given object.
"""
from __future__ import division, print_function, with_statement
import inspect
import os
def determine_package(some_object):
"""
Resolves a call by object to a call by package.
- Determine absolute package name of the given object.
- When th... | """
Utility that detects the package of a given object.
"""
from __future__ import division, print_function, with_statement
import inspect
import os
def determine_package(some_object):
"""
Resolves a call by object to a call by package.
- Determine absolute package name of the given object.
- When th... | Fix a bug (?) in detmine_package | Fix a bug (?) in detmine_package
Canditates have their first character removed if it is ".".
| Python | bsd-3-clause | cigroup-ol/metaopt,cigroup-ol/metaopt,cigroup-ol/metaopt | ---
+++
@@ -22,6 +22,10 @@
for directory in module_path.split(os.sep)[::-1]:
prefix.append(directory)
candidate = ".".join(prefix[::-1] + [module_name])
+
+ if candidate.startswith("."):
+ candidate = candidate[1:]
+
try:
__import__(name=candidate, global... |
5ee2d734ac3279e142ba7df561ee13c64f236cb8 | tests/testtrim.py | tests/testtrim.py | from __future__ import print_function, division
from cutadapt.seqio import ColorspaceSequence
from cutadapt.adapters import ColorspaceAdapter, PREFIX
from cutadapt.scripts.cutadapt import AdapterCutter
def test_cs_5p():
read = ColorspaceSequence("name", "0123", "DEFG", "T")
adapter = ColorspaceAdapter("CG", PREFIX,... | from __future__ import print_function, division
from cutadapt.seqio import ColorspaceSequence, Sequence
from cutadapt.adapters import Adapter, ColorspaceAdapter, PREFIX, BACK
from cutadapt.scripts.cutadapt import AdapterCutter
def test_cs_5p():
read = ColorspaceSequence("name", "0123", "DEFG", "T")
adapter = Colors... | Test for bug: too many trimmed bases reported | Test for bug: too many trimmed bases reported
| Python | mit | Chris7/cutadapt,marcelm/cutadapt | ---
+++
@@ -1,7 +1,7 @@
from __future__ import print_function, division
-from cutadapt.seqio import ColorspaceSequence
-from cutadapt.adapters import ColorspaceAdapter, PREFIX
+from cutadapt.seqio import ColorspaceSequence, Sequence
+from cutadapt.adapters import Adapter, ColorspaceAdapter, PREFIX, BACK
from cuta... |
729cea9ae07f7264b765813cac00e869f66069ff | tools/allBuild.py | tools/allBuild.py | import os
import buildFirefox
import buildChrome
os.chdir(os.path.dirname(os.path.abspath(__file__)))
buildFirefox.run()
buildChrome.run() | import os
import buildFirefox
import buildChrome
os.chdir(os.path.dirname(os.path.abspath(__file__)))
filenames = ['header.js', 'guild_page.js', 'core.js']
with open('tgarmory.js', 'w') as outfile:
for fname in filenames:
with open(fname) as infile:
outfile.write(infile.read())
buildFirefox.r... | Prepare for file concat build system | Prepare for file concat build system
| Python | mit | ZergRael/tgarmory | ---
+++
@@ -3,5 +3,12 @@
import buildChrome
os.chdir(os.path.dirname(os.path.abspath(__file__)))
+
+filenames = ['header.js', 'guild_page.js', 'core.js']
+with open('tgarmory.js', 'w') as outfile:
+ for fname in filenames:
+ with open(fname) as infile:
+ outfile.write(infile.read())
+
buildF... |
b53ebee86c36dfe52e8a11fb8c4f3cec99878fc9 | gitlabform/gitlab/merge_requests.py | gitlabform/gitlab/merge_requests.py | from gitlabform.gitlab.core import GitLabCore
class GitLabMergeRequests(GitLabCore):
def create_mr(self, project_and_group_name, source_branch, target_branch, title, description=None):
pid = self._get_project_id(project_and_group_name)
data = {
"id": pid,
"source_branch": ... | from gitlabform.gitlab.core import GitLabCore
class GitLabMergeRequests(GitLabCore):
def create_mr(self, project_and_group_name, source_branch, target_branch, title, description=None):
pid = self._get_project_id(project_and_group_name)
data = {
"id": pid,
"source_branch": ... | Add update MR method (for internal use for now) | Add update MR method (for internal use for now)
| Python | mit | egnyte/gitlabform,egnyte/gitlabform | ---
+++
@@ -19,6 +19,10 @@
pid = self._get_project_id(project_and_group_name)
return self._make_requests_to_api("projects/%s/merge_request/%s/merge" % (pid, mr_id), method='PUT')
+ def update_mr(self, project_and_group_name, mr_id, data): # NOT iid, like API docs suggest!
+ pid = self._... |
badc84447ad6a596317c93e7c393e6021da8a18f | park_api/security.py | park_api/security.py | def file_is_allowed(file):
t = file.endswith(".py")
t &= "__Init__" not in file.title()
t &= "Sample_City" not in file.title()
return t
| def file_is_allowed(file):
t = file.endswith(".py")
t &= "__Init__" not in file.title()
t &= "Sample_City" not in file.title()
t &= "Frankfurt" not in file.title() # See offenesdresden/ParkAPI#153
return t
| Disable Frankfurt until requests is fixed | Disable Frankfurt until requests is fixed
ref #153
| Python | mit | offenesdresden/ParkAPI,offenesdresden/ParkAPI | ---
+++
@@ -2,4 +2,5 @@
t = file.endswith(".py")
t &= "__Init__" not in file.title()
t &= "Sample_City" not in file.title()
+ t &= "Frankfurt" not in file.title() # See offenesdresden/ParkAPI#153
return t |
7cf37b966049cfc47ef200ad8ae69763d98185c5 | collector/description/normal/L2.py | collector/description/normal/L2.py | from __future__ import absolute_import
import math, utilities.operator
from ...weight import WeightDict, normalize_exp
from .L1 import phase_description
# Normalised distances and L2-normalised (Euclidean norm) collector sets
collector_weights = \
WeightDict(normalize_exp, (utilities.operator.square, math.sqrt),
... | from __future__ import absolute_import
import math, utilities.operator
from ...weight import WeightDict, normalize_exp
from .L1 import descriptions
# Normalised distances and L2-normalised (Euclidean norm) collector sets
weights = \
WeightDict(normalize_exp, (utilities.operator.square, math.sqrt),
tags=('normal... | Update secondary collector description module | Update secondary collector description module
| Python | mit | davidfoerster/schema-matching | ---
+++
@@ -1,10 +1,10 @@
from __future__ import absolute_import
import math, utilities.operator
from ...weight import WeightDict, normalize_exp
-from .L1 import phase_description
+from .L1 import descriptions
# Normalised distances and L2-normalised (Euclidean norm) collector sets
-collector_weights = \
+wei... |
eb57469f1b14dfd5c2e74f2bbb774513e0662a6c | installer/installer_config/forms.py | installer/installer_config/forms.py | from django import forms
from django.forms.models import ModelForm
from installer_config.models import EnvironmentProfile, UserChoice
class EnvironmentForm(ModelForm):
packages = forms.ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple,
queryset=UserChoice.... | from django import forms
from django.forms.models import ModelForm
from installer_config.models import EnvironmentProfile, UserChoice
class EnvironmentForm(ModelForm):
choices = forms.ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple,
queryset=UserChoice.o... | Remove steps from Env Prof form | Remove steps from Env Prof form
| Python | mit | alibulota/Package_Installer,ezPy-co/ezpy,alibulota/Package_Installer,ezPy-co/ezpy | ---
+++
@@ -4,9 +4,9 @@
class EnvironmentForm(ModelForm):
- packages = forms.ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple,
+ choices = forms.ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple,
queryset=UserChoice.objects.all())
... |
4e94cef9f6617827341af443ac428b9ccc190535 | lib/recommend-by-url.py | lib/recommend-by-url.py | # -*- coding: utf-8 -*-
from newspaper import Article
from goose import Goose
import json
import sys
article = Article(sys.argv[1])
article.download()
article.parse()
article.nlp()
published = ''
if article.publish_date:
published = article.publish_date.strftime("%Y-%m-%d %H:%M:%S")
# Get body with goose
g = Goos... | # -*- coding: utf-8 -*-
from newspaper import Article
from goose import Goose
import requests
import json
import sys
article = Article(sys.argv[1])
article.download()
if not article.html:
r = requests.get(sys.argv[1], verify=False, headers={ 'User-Agent': 'Mozilla/5.0' })
article.set_html(r.text)
article.parse()... | Improve reliablity of python article fetcher | Improve reliablity of python article fetcher
| Python | mit | lateral/feed-feeder,lateral/feed-feeder,lateral/feed-feeder,lateral/feed-feeder | ---
+++
@@ -1,12 +1,17 @@
# -*- coding: utf-8 -*-
from newspaper import Article
from goose import Goose
+import requests
import json
import sys
article = Article(sys.argv[1])
article.download()
+if not article.html:
+ r = requests.get(sys.argv[1], verify=False, headers={ 'User-Agent': 'Mozilla/5.0' })
+ ... |
c6de39b01b8eac10edbb6f95d86285075bf8a9ab | conanfile.py | conanfile.py | from conans import ConanFile
class ArgsConan(ConanFile):
name = "cfgfile"
version = "0.2.8.2"
url = "https://github.com/igormironchik/cfgfile.git"
license = "MIT"
description = "Header-only library for reading/saving configuration files with schema defined in sources."
exports = "cfgfile/*", "... | from conans import ConanFile, CMake
class ArgsConan(ConanFile):
name = "cfgfile"
version = "0.2.8.2"
url = "https://github.com/igormironchik/cfgfile.git"
license = "MIT"
description = "Header-only library for reading/saving configuration files with schema defined in sources."
exports = "cfgfil... | Add build step into Conan recipe. | Add build step into Conan recipe.
| Python | mit | igormironchik/cfgfile | ---
+++
@@ -1,4 +1,4 @@
-from conans import ConanFile
+from conans import ConanFile, CMake
class ArgsConan(ConanFile):
@@ -8,6 +8,11 @@
license = "MIT"
description = "Header-only library for reading/saving configuration files with schema defined in sources."
exports = "cfgfile/*", "COPYING", "gene... |
222e2a70f9c2d4ce7cb4a26d717c6bcce1e3f344 | tests/utils.py | tests/utils.py | import os
import pytest
from tests.consts import examples_path
from valohai_yaml import parse
def _load_config(filename, roundtrip):
with open(os.path.join(examples_path, filename), 'r') as infp:
config = parse(infp)
if roundtrip:
config = parse(config.serialize())
return config
def co... | import os
import pytest
from tests.consts import examples_path
from valohai_yaml import parse
def _load_config(filename, roundtrip):
with open(os.path.join(examples_path, filename), 'r') as infp:
config = parse(infp)
if roundtrip:
config = parse(config.serialize())
return config
def co... | Add nicer ids for tests | Add nicer ids for tests
| Python | mit | valohai/valohai-yaml | ---
+++
@@ -15,7 +15,7 @@
def config_fixture(name):
- @pytest.fixture(params=[False, True])
+ @pytest.fixture(params=[False, True], ids=['direct', 'roundtrip'])
def _config_fixture(request):
return _load_config(name, roundtrip=request.param)
|
fa9e488c3fa008fa2c9b08a787ea9c2655bd3d02 | tests/test_discuss.py | tests/test_discuss.py | import pytest
from web_test_base import *
class TestIATIDiscuss(WebTestBase):
requests_to_load = {
'IATI Discuss': {
'url': 'http://discuss.iatistandard.org/'
}
}
def test_contains_links(self, loaded_request):
"""
Test that each page contains links to the define... | import pytest
from web_test_base import *
class TestIATIDiscuss(WebTestBase):
requests_to_load = {
'IATI Discuss': {
'url': 'http://discuss.iatistandard.org/'
}
, 'IATI Discuss Welcome Thread': {
'url': 'http://discuss.iatistandard.org/t/welcome-to-iati-discuss/6'
... | Add test for Discuss Welcome | Add test for Discuss Welcome
This ensures the welcome post is sufficiently welcoming.
The XPaths are based on the page with Javascript disabled. As such,
they will not correctly match if Javascript is enabled.
| Python | mit | IATI/IATI-Website-Tests | ---
+++
@@ -5,6 +5,9 @@
requests_to_load = {
'IATI Discuss': {
'url': 'http://discuss.iatistandard.org/'
+ }
+ , 'IATI Discuss Welcome Thread': {
+ 'url': 'http://discuss.iatistandard.org/t/welcome-to-iati-discuss/6'
}
}
@@ -15,3 +18,24 @@
r... |
0d6d1e735e3c149f6adec370832949a81b930a56 | tests/test_driller.py | tests/test_driller.py | import nose
import driller
import logging
l = logging.getLogger("driller.tests.test_driller")
import os
bin_location = str(os.path.join(os.path.dirname(os.path.realpath(__file__)), '../../binaries'))
def test_drilling_cgc():
'''
test drilling on the cgc binary, palindrome.
'''
binary = "cgc_scored_e... | import nose
import driller
import logging
l = logging.getLogger("driller.tests.test_driller")
import os
bin_location = str(os.path.join(os.path.dirname(os.path.realpath(__file__)), '../../binaries-private'))
def test_drilling_cgc():
'''
test drilling on the cgc binary, palindrome.
'''
binary = "cgc_... | Update binaries path with private repo | Update binaries path with private repo
| Python | bsd-2-clause | shellphish/driller | ---
+++
@@ -5,7 +5,7 @@
l = logging.getLogger("driller.tests.test_driller")
import os
-bin_location = str(os.path.join(os.path.dirname(os.path.realpath(__file__)), '../../binaries'))
+bin_location = str(os.path.join(os.path.dirname(os.path.realpath(__file__)), '../../binaries-private'))
def test_drilling_cgc()... |
9ae8283e06b0b72213fc8084909ae9c2c2b3e553 | build/android/pylib/gtest/gtest_config.py | build/android/pylib/gtest/gtest_config.py | # Copyright (c) 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Configuration file for android gtest suites."""
# Add new suites here before upgrading them to the stable list below.
EXPERIMENTAL_TEST_SUITES = [
... | # Copyright (c) 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Configuration file for android gtest suites."""
# Add new suites here before upgrading them to the stable list below.
EXPERIMENTAL_TEST_SUITES = [
... | Move component_unittest to android main waterfall and cq | Move component_unittest to android main waterfall and cq
These are existing tests that moved to the component_unittest
target. They have been running on the FYI bots for a few days
without issue.
BUG=
Android bot script change. Ran through android trybots.
NOTRY=true
Review URL: https://chromiumcodereview.appspot.co... | Python | bsd-3-clause | jaruba/chromium.src,fujunwei/chromium-crosswalk,ltilve/chromium,Chilledheart/chromium,jaruba/chromium.src,ondra-novak/chromium.src,Chilledheart/chromium,Jonekee/chromium.src,timopulkkinen/BubbleFish,anirudhSK/chromium,dushu1203/chromium.src,timopulkkinen/BubbleFish,anirudhSK/chromium,anirudhSK/chromium,dednal/chromium.... | ---
+++
@@ -7,7 +7,6 @@
# Add new suites here before upgrading them to the stable list below.
EXPERIMENTAL_TEST_SUITES = [
'TestWebKitAPI',
- 'components_unittests',
'sandbox_linux_unittests',
'webkit_unit_tests',
]
@@ -19,6 +18,7 @@
'android_webview_unittests',
'base_unittests',
'... |
f74636d6944b45753d274f6a993678863a368961 | tests/test_testapp.py | tests/test_testapp.py |
import json
import ckanapi
import unittest
import paste.fixture
def wsgi_app(environ, start_response):
status = '200 OK'
headers = [('Content-type', 'application/json')]
path = environ['PATH_INFO']
if path == '/api/action/hello_world':
response = {'success': True, 'result': 'how are you?'}
... |
import json
import ckanapi
import unittest
import paste.fixture
def wsgi_app(environ, start_response):
status = '200 OK'
headers = [('Content-type', 'application/json')]
path = environ['PATH_INFO']
if path == '/api/action/hello_world':
response = {'success': True, 'result': 'how are you?'}
... | Fix a couple of tests | Fix a couple of tests
Fix a couple of tests that were broken by commit 7e068a3.
| Python | mit | LaurentGoderre/ckanapi,perceptron-XYZ/ckanapi,xingyz/ckanapi,metaodi/ckanapi,wardi/ckanapi,eawag-rdm/ckanapi | ---
+++
@@ -28,16 +28,14 @@
def test_simple(self):
self.assertEquals(
- self.ckan.action.hello_world()['result'],
- 'how are you?')
+ self.ckan.action.hello_world(), 'how are you?')
def test_invalid(self):
self.assertRaises(
ckanapi.Validatio... |
210e9a6e6b20f724a6d464b5a1c842c8b71eceae | testsuite/N806_py3.py | testsuite/N806_py3.py | # python3 only
#: Okay
VAR1, *VAR2, VAR3 = 1, 2, 3
#: Okay
[VAR1, *VAR2, VAR3] = (1, 2, 3)
#: N806
def extended_unpacking_ok():
Var1, *Var2, Var3 = 1, 2, 3
#: N806
def extended_unpacking_not_ok():
[Var1, *Var2, Var3] = (1, 2, 3)
#: Okay
def assing_to_unpack_ok():
a, *[b] = 1, 2
#: N806
def assing_to_unpack_... | # python3 only
#: Okay
VAR1, *VAR2, VAR3 = 1, 2, 3
#: Okay
[VAR1, *VAR2, VAR3] = (1, 2, 3)
#: N806
def extended_unpacking_not_ok():
Var1, *Var2, Var3 = 1, 2, 3
#: N806
def extended_unpacking_not_ok():
[Var1, *Var2, Var3] = (1, 2, 3)
#: Okay
def assing_to_unpack_ok():
a, *[b] = 1, 2
#: N806
def assing_to_unp... | Fix typo test case name | Fix typo test case name
| Python | mit | flintwork/pep8-naming | ---
+++
@@ -4,7 +4,7 @@
#: Okay
[VAR1, *VAR2, VAR3] = (1, 2, 3)
#: N806
-def extended_unpacking_ok():
+def extended_unpacking_not_ok():
Var1, *Var2, Var3 = 1, 2, 3
#: N806
def extended_unpacking_not_ok(): |
8ae4594d4f4157568db0dc5cad4d07b8f1142218 | src/common/utils.py | src/common/utils.py | from passlib.hash import pbkdf2_sha512
class Utils:
@staticmethod
def hash_password(password):
"""
Hashes a password using sha512 -> pbkdf2_sha512 encrypted password
"""
return pbkdf2_sha512.encrypt(password)
@staticmethod
def check_hashed_password(password, hashed_password):
"""
Checks the password ... | import re
from passlib.hash import pbkdf2_sha512
class Utils:
@staticmethod
def email_is_valid(email):
email_address_matcher = re.compile('^[\w-]+@([\w-]+\.)+[\w]+$')
return True if email_address_matcher.match(email) else False
@staticmethod
def hash_password(password):
"""
Hashes a password using sha512... | Add static method for email address | Add static method for email address
| Python | apache-2.0 | asimonia/pricing-alerts,asimonia/pricing-alerts | ---
+++
@@ -1,6 +1,12 @@
+import re
from passlib.hash import pbkdf2_sha512
class Utils:
+
+ @staticmethod
+ def email_is_valid(email):
+ email_address_matcher = re.compile('^[\w-]+@([\w-]+\.)+[\w]+$')
+ return True if email_address_matcher.match(email) else False
@staticmethod
def hash_password(password): |
f4d9e55cf3dbed0cf21661c33a6efbc98093d1f8 | paypal.py | paypal.py | #!/usr/bin/env python3
import argparse
import csv
parser = argparse.ArgumentParser()
parser.add_argument('--config', help='path to file containing column header mappings', required=True)
parser.add_argument('--csv-file', help='path to CSV file', required=True)
parser.add_argument('--skip-headers', help='skip first li... | #!/usr/bin/env python3
import argparse
import csv
parser = argparse.ArgumentParser()
parser.add_argument('--config', help='path to file containing column header mappings', required=True)
parser.add_argument('--csv-file', help='path to CSV file', required=True)
parser.add_argument('--skip-headers', help='skip first li... | Tweak PayPal output to use Payee and Memo fields | Tweak PayPal output to use Payee and Memo fields
| Python | mit | pwaring/csv2qif | ---
+++
@@ -26,7 +26,8 @@
else:
print('D' + row['date'])
print('T' + row['gross'])
- print('P' + row['description'])
+ print('P' + row['from_name'])
+ print('M' + row['description'])
print('^')
# Process fee as separate tr... |
439cbfbfa6b16fdd0d24f91adb55eb510802ab8c | inbox/ignition.py | inbox/ignition.py | from sqlalchemy import create_engine
from inbox.sqlalchemy_ext.util import ForceStrictMode
from inbox.config import db_uri, config
DB_POOL_SIZE = config.get_required('DB_POOL_SIZE')
def main_engine(pool_size=DB_POOL_SIZE, max_overflow=5):
engine = create_engine(db_uri(),
listeners=[Fo... | from sqlalchemy import create_engine
from inbox.sqlalchemy_ext.util import ForceStrictMode
from inbox.config import db_uri, config
DB_POOL_SIZE = config.get_required('DB_POOL_SIZE')
def main_engine(pool_size=DB_POOL_SIZE, max_overflow=5):
engine = create_engine(db_uri(),
listeners=[Fo... | Set pool_recycle to deal with MySQL closing idle connections. | Set pool_recycle to deal with MySQL closing idle connections.
See http://docs.sqlalchemy.org/en/latest/dialects/mysql.html#connection-timeouts
| Python | agpl-3.0 | PriviPK/privipk-sync-engine,EthanBlackburn/sync-engine,wakermahmud/sync-engine,closeio/nylas,Eagles2F/sync-engine,EthanBlackburn/sync-engine,wakermahmud/sync-engine,Eagles2F/sync-engine,PriviPK/privipk-sync-engine,ErinCall/sync-engine,nylas/sync-engine,EthanBlackburn/sync-engine,PriviPK/privipk-sync-engine,nylas/sync-e... | ---
+++
@@ -12,6 +12,7 @@
isolation_level='READ COMMITTED',
echo=False,
pool_size=pool_size,
+ pool_recycle=3600,
max_overflow=max_overflow,
connect_arg... |
71324420df350bba5423006a444927e33c1a5ae2 | dddp/apps.py | dddp/apps.py | """Django DDP app config."""
from __future__ import print_function
from django.apps import AppConfig
from django.conf import settings, ImproperlyConfigured
from django.db import DatabaseError
from django.db.models import signals
from dddp import autodiscover
from dddp.models import Connection
class DjangoDDPConfig... | """Django DDP app config."""
from __future__ import print_function
from django.apps import AppConfig
from django.conf import settings, ImproperlyConfigured
from dddp import autodiscover
class DjangoDDPConfig(AppConfig):
"""Django app config for django-ddp."""
api = None
name = 'dddp'
verbose_name... | Remove unused imports from AppConfig module. | Remove unused imports from AppConfig module.
| Python | mit | commoncode/django-ddp,django-ddp/django-ddp,commoncode/django-ddp,django-ddp/django-ddp,commoncode/django-ddp,django-ddp/django-ddp,commoncode/django-ddp,django-ddp/django-ddp | ---
+++
@@ -4,11 +4,8 @@
from django.apps import AppConfig
from django.conf import settings, ImproperlyConfigured
-from django.db import DatabaseError
-from django.db.models import signals
from dddp import autodiscover
-from dddp.models import Connection
class DjangoDDPConfig(AppConfig): |
0f0d404f36115d6410b3ba5eed9e9f9f2fb2461f | carnetdumaker/context_processors.py | carnetdumaker/context_processors.py | """
Extra context processors for the CarnetDuMaker app.
"""
from django.contrib.sites.shortcuts import get_current_site
from django.utils.translation import ugettext_lazy as _
def app_constants(request):
"""
Constants context processor.
:param request: the current request.
:return: All constants for ... | """
Extra context processors for the CarnetDuMaker app.
"""
from django.contrib.sites.shortcuts import get_current_site
from django.utils.translation import ugettext_lazy as _
def app_constants(request):
"""
Constants context processor.
:param request: the current request.
:return: All constants for ... | Add missing facebook and google verif codes | Add missing facebook and google verif codes
| Python | agpl-3.0 | TamiaLab/carnetdumaker,TamiaLab/carnetdumaker,TamiaLab/carnetdumaker,TamiaLab/carnetdumaker | ---
+++
@@ -21,9 +21,9 @@
'COPYRIGHT': _('TamiaLab 2015'),
'DESCRIPTION': _('L\'esprit du Do It Yourself'),
'TWITTER_USERNAME': 'carnetdumaker',
- 'GOOGLE_SITE_VERIFICATION_CODE': '', # TODO
+ 'GOOGLE_SITE_VERIFICATION_CODE': 't3KwbPbJCHz-enFYH50Hcd8PDN8NW... |
b8f9b2664f8782a028ce27a361f2a7a28eb925aa | cloudenvy/commands/envy_snapshot.py | cloudenvy/commands/envy_snapshot.py | from cloudenvy.envy import Envy
class EnvySnapshot(object):
"""Create a snapshot of an ENVy."""
def __init__(self, argparser):
self._build_subparser(argparser)
def _build_subparser(self, subparsers):
subparser = subparsers.add_parser('snapshot', help='snapshot help')
subparser.se... | from cloudenvy.envy import Envy
class EnvySnapshot(object):
"""Create a snapshot of an ENVy."""
def __init__(self, argparser):
self._build_subparser(argparser)
def _build_subparser(self, subparsers):
subparser = subparsers.add_parser('snapshot', help='snapshot help')
subparser.se... | Remove out-of-date comment about snapshot UX | Remove out-of-date comment about snapshot UX
| Python | apache-2.0 | cloudenvy/cloudenvy | ---
+++
@@ -16,9 +16,6 @@
return subparser
- #TODO(jakedahn): The entire UX for this needs to be talked about, refer to
- # https://github.com/bcwaldon/cloudenvy/issues/27 for any
- # discussion, if you're curious.
def run(self, config, args):
envy = E... |
b0fef4ed92cde72305a2d85f3e96adde93f82547 | tests/test_py35/test_resp.py | tests/test_py35/test_resp.py | import pytest
import aiohttp
from aiohttp import web
@pytest.mark.run_loop
async def test_await(create_server, loop):
async def handler(request):
return web.HTTPOk()
app, url = await create_server()
app.router.add_route('GET', '/', handler)
resp = await aiohttp.get(url+'/', loop=loop)
a... | import pytest
import aiohttp
from aiohttp import web
@pytest.mark.run_loop
async def test_await(create_server, loop):
async def handler(request):
return web.HTTPOk()
app, url = await create_server()
app.router.add_route('GET', '/', handler)
resp = await aiohttp.get(url+'/', loop=loop)
a... | Add test for context manager | Add test for context manager
| Python | apache-2.0 | juliatem/aiohttp,playpauseandstop/aiohttp,juliatem/aiohttp,Eyepea/aiohttp,mind1master/aiohttp,z2v/aiohttp,decentfox/aiohttp,jashandeep-sohi/aiohttp,pfreixes/aiohttp,vaskalas/aiohttp,hellysmile/aiohttp,AraHaanOrg/aiohttp,moden-py/aiohttp,rutsky/aiohttp,z2v/aiohttp,vaskalas/aiohttp,elastic-coders/aiohttp,singulared/aioht... | ---
+++
@@ -32,3 +32,18 @@
assert resp.status == 200
assert resp.connection is not None
assert resp.connection is None
+
+
+@pytest.mark.run_loop
+async def test_client_api_context_manager(create_server, loop):
+
+ async def handler(request):
+ return web.HTTPOk()
+
+ app, url = aw... |
e1e7189bbe859d6dfa6f883d2ff46ff1faed4842 | scrape.py | scrape.py | import scholarly
import requests
_SEARCH = '/scholar?q=\"{}\"&as_ylo={}&as_yhi={}'
def search(query, start_year, end_year):
"""Search by scholar query and return a generator of Publication objects"""
soup = scholarly._get_soup(
_SEARCH.format(requests.utils.quote(query),
str(star... | import scholarly
import requests
_EXACT_SEARCH = '/scholar?q="{}"'
_START_YEAR = '&as_ylo={}'
_END_YEAR = '&as_yhi={}'
def search(query, exact=True, start_year=None, end_year=None):
"""Search by scholar query and return a generator of Publication objects"""
url = _EXACT_SEARCH.format(requests.utils.quote(query... | Make year range arguments optional in search | Make year range arguments optional in search
| Python | mit | Spferical/cure-alzheimers-fund-tracker,Spferical/cure-alzheimers-fund-tracker,Spferical/cure-alzheimers-fund-tracker | ---
+++
@@ -1,16 +1,21 @@
import scholarly
import requests
-_SEARCH = '/scholar?q=\"{}\"&as_ylo={}&as_yhi={}'
-def search(query, start_year, end_year):
+_EXACT_SEARCH = '/scholar?q="{}"'
+_START_YEAR = '&as_ylo={}'
+_END_YEAR = '&as_yhi={}'
+def search(query, exact=True, start_year=None, end_year=None):
"""S... |
182c02b28a6ffee8744b48e39d378dca505f9287 | testsuite/error-dupes/run.py | testsuite/error-dupes/run.py | #!/usr/bin/env python
command = "echo 'Without repeated errors:' >> out.txt 2>&1 ;\n"
command += testshade("-g 2 2 test")
command += "echo 'With repeated errors:' >> out.txt 2>&1 ;\n"
command += testshade("--options error_repeats=1 -g 2 2 test")
| #!/usr/bin/env python
command = "echo Without repeated errors:>> out.txt 2>&1 ;\n"
command += testshade("-g 2 2 test")
command += "echo With repeated errors:>> out.txt 2>&1 ;\n"
command += testshade("--options error_repeats=1 -g 2 2 test")
| Fix test output to not fail on Windows | Fix test output to not fail on Windows
| Python | bsd-3-clause | aconty/OpenShadingLanguage,brechtvl/OpenShadingLanguage,aconty/OpenShadingLanguage,lgritz/OpenShadingLanguage,aconty/OpenShadingLanguage,brechtvl/OpenShadingLanguage,lgritz/OpenShadingLanguage,lgritz/OpenShadingLanguage,brechtvl/OpenShadingLanguage,lgritz/OpenShadingLanguage,aconty/OpenShadingLanguage,imageworks/OpenSh... | ---
+++
@@ -1,7 +1,7 @@
#!/usr/bin/env python
-command = "echo 'Without repeated errors:' >> out.txt 2>&1 ;\n"
+command = "echo Without repeated errors:>> out.txt 2>&1 ;\n"
command += testshade("-g 2 2 test")
-command += "echo 'With repeated errors:' >> out.txt 2>&1 ;\n"
+command += "echo With repeated errors:>... |
a6b9077bf093b64f3b993d032b166586195ae011 | pyutrack/cli/util.py | pyutrack/cli/util.py | import collections
import click
def admin_command(fn):
fn.__doc__ += ' [Admin only]'
return fn
class PyutrackContext(object):
def __init__(self, connection, config, debug=False):
self.connection = connection
self.config = config
self.debug = debug
self.format = None
... | import collections
import click
def admin_command(fn):
fn.__doc__ += ' [Admin only]'
return fn
class PyutrackContext(object):
def __init__(self, connection, config, debug=False):
self.connection = connection
self.config = config
self.debug = debug
self.format = None
... | Fix issue with uninitialised response | Fix issue with uninitialised response
| Python | mit | alisaifee/pyutrack,alisaifee/pyutrack | ---
+++
@@ -19,7 +19,10 @@
format = self.format or format
oneline = format == 'oneline'
line_sep = '\n' if format else '\n\n'
- if isinstance(data, collections.Iterable):
+ resp = ''
+ if isinstance(data, six.string_types):
+ resp = data
+ elif isinsta... |
667a3d2803529c5b14fd17c6877961646615f2fd | python2/raygun4py/middleware/wsgi.py | python2/raygun4py/middleware/wsgi.py | import logging
from raygun4py import raygunprovider
log = logging.getLogger(__name__)
class Provider(object):
def __init__(self, app, apiKey):
self.app = app
self.sender = raygunprovider.RaygunSender(apiKey)
def __call__(self, environ, start_response):
if not self.sender:
... | import logging
from raygun4py import raygunprovider
log = logging.getLogger(__name__)
class Provider(object):
def __init__(self, app, apiKey):
self.app = app
self.sender = raygunprovider.RaygunSender(apiKey)
def __call__(self, environ, start_response):
if not self.sender:
... | Fix WSGI middleware to call close() on the iterable instead of checking if it's callable, and reraising the exception if one results as per spec. Also call sender correctly | Fix WSGI middleware to call close() on the iterable instead of checking if it's callable, and reraising the exception if one results as per spec. Also call sender correctly
| Python | mit | MindscapeHQ/raygun4py | ---
+++
@@ -16,29 +16,26 @@
if not self.sender:
log.error("Raygun-WSGI: Cannot send as provider not attached")
+ iterable = None
+
try:
- chunk = self.app(environ, start_response)
+ iterable = self.app(environ, start_response)
+ for event in ite... |
95bb764e78e623310dff1ae48eabf4271b452406 | penchy/jobs/__init__.py | penchy/jobs/__init__.py | from penchy.jobs import jvms, tools, filters, workloads
from penchy.jobs.job import Job, SystemComposition, NodeSetting
from penchy.jobs.dependency import Edge
JVM = jvms.JVM
# all job elements that are interesting for the user have to be enumerated here
__all__ = [
# job
'Job',
'NodeSetting',
'System... | from penchy.jobs import jvms, tools, filters, workloads
from penchy.jobs.job import Job, SystemComposition, NodeSetting
JVM = jvms.JVM
# all job elements that are interesting for the user have to be enumerated here
__all__ = [
# job
'Job',
'NodeSetting',
'SystemComposition',
# jvms
'JVM',
... | Remove Edge from jobs package. | jobs: Remove Edge from jobs package.
Signed-off-by: Michael Markert <5eb998b7ac86da375651a4cd767b88c9dad25896@googlemail.com>
| Python | mit | fhirschmann/penchy,fhirschmann/penchy | ---
+++
@@ -1,6 +1,5 @@
from penchy.jobs import jvms, tools, filters, workloads
from penchy.jobs.job import Job, SystemComposition, NodeSetting
-from penchy.jobs.dependency import Edge
JVM = jvms.JVM
@@ -10,8 +9,6 @@
'Job',
'NodeSetting',
'SystemComposition',
- # dependencies
- 'Edge',
... |
dbc16598a87403f52324bca3d50132fc9303ee90 | reviewboard/hostingsvcs/gitorious.py | reviewboard/hostingsvcs/gitorious.py | from django import forms
from django.utils.translation import ugettext_lazy as _
from reviewboard.hostingsvcs.forms import HostingServiceForm
from reviewboard.hostingsvcs.service import HostingService
class GitoriousForm(HostingServiceForm):
gitorious_project_name = forms.CharField(
label=_('Project name... | from django import forms
from django.utils.translation import ugettext_lazy as _
from reviewboard.hostingsvcs.forms import HostingServiceForm
from reviewboard.hostingsvcs.service import HostingService
class GitoriousForm(HostingServiceForm):
gitorious_project_name = forms.CharField(
label=_('Project name... | Fix the raw paths for Gitorious | Fix the raw paths for Gitorious
Gitorious have changed the raw orl paths, making impossible to use a Gitorious
repository.
This patch has been tested in production at
http://reviewboard.chakra-project.org/r/27/diff/#index_header
Reviewed at http://reviews.reviewboard.org/r/3649/diff/#index_header
| Python | mit | KnowNo/reviewboard,brennie/reviewboard,1tush/reviewboard,chipx86/reviewboard,davidt/reviewboard,brennie/reviewboard,bkochendorfer/reviewboard,KnowNo/reviewboard,sgallagher/reviewboard,reviewboard/reviewboard,beol/reviewboard,1tush/reviewboard,brennie/reviewboard,custode/reviewboard,sgallagher/reviewboard,1tush/reviewbo... | ---
+++
@@ -28,10 +28,10 @@
'Git': {
'path': 'git://gitorious.org/%(gitorious_project_name)s/'
'%(gitorious_repo_name)s.git',
- 'mirror_path': 'http://git.gitorious.org/'
+ 'mirror_path': 'https://gitorious.org/'
'%(gitorious... |
318e322fbc29dd20d56dc311c71ae60e010a7cdf | ooni/resources/__init__.py | ooni/resources/__init__.py | from ooni.settings import config
from ooni.utils import unzip, gunzip
from ooni.deckgen.processors import citizenlab_test_lists
from ooni.deckgen.processors import namebench_dns_servers
config.read_config_file()
__version__ = "0.0.1"
inputs = {
"namebench-dns-servers.csv": {
"url": "https://namebench.go... | from ooni.settings import config
from ooni.utils import unzip, gunzip
from ooni.deckgen.processors import citizenlab_test_lists
from ooni.deckgen.processors import namebench_dns_servers
config.read_config_file()
__version__ = "0.0.1"
inputs = {
"namebench-dns-servers.csv": {
"url": "https://namebench.go... | Use HTTPS URLs for MaxMind resources | Use HTTPS URLs for MaxMind resources
| Python | bsd-2-clause | lordappsec/ooni-probe,Karthikeyan-kkk/ooni-probe,Karthikeyan-kkk/ooni-probe,kdmurray91/ooni-probe,0xPoly/ooni-probe,juga0/ooni-probe,Karthikeyan-kkk/ooni-probe,0xPoly/ooni-probe,juga0/ooni-probe,lordappsec/ooni-probe,kdmurray91/ooni-probe,lordappsec/ooni-probe,kdmurray91/ooni-probe,juga0/ooni-probe,kdmurray91/ooni-prob... | ---
+++
@@ -25,14 +25,14 @@
geoip = {
"GeoIPASNum.dat.gz": {
- "url": "http://www.maxmind.com/download/"
+ "url": "https://www.maxmind.com/download/"
"geoip/database/asnum/GeoIPASNum.dat.gz",
"action": gunzip,
"action_args": [config.advanced.geoip_data_dir],
... |
ae55577e4cea64a0052eb0c219641435c9c0210c | samples/model-builder/init_sample.py | samples/model-builder/init_sample.py | # Copyright 2021 Google LLC
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2021 Google LLC
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | Update init sample to import inside of function. | chore: Update init sample to import inside of function.
PiperOrigin-RevId: 485079470
| Python | apache-2.0 | googleapis/python-aiplatform,googleapis/python-aiplatform | ---
+++
@@ -15,7 +15,6 @@
from typing import Optional
from google.auth import credentials as auth_credentials
-from google.cloud import aiplatform
# [START aiplatform_sdk_init_sample]
@@ -27,6 +26,9 @@
credentials: Optional[auth_credentials.Credentials] = None,
encryption_spec_key_name: Optional[s... |
cba8ec4754ed3516ba3f873b0879c8379e8f93ab | data_structures/bitorrent/server/udp.py | data_structures/bitorrent/server/udp.py | #!/usr/bin/env python
import struct
from twisted.internet.protocol import DatagramProtocol
from twisted.internet import reactor
class Announce(DatagramProtocol):
def parse_connection(self, data):
connection, action, transaction_id = struct.unpack("!qii", data)
message = struct.pack('!iiq', action, transac... | #!/usr/bin/env python
import struct
from twisted.internet.protocol import DatagramProtocol
from twisted.internet import reactor
from announce.torrent import Torrent
class Announce(DatagramProtocol):
def parse_connection(self, data):
connection, action, transaction_id = struct.unpack("!qii", data)
message... | Send back announce response to client | Send back announce response to client
| Python | apache-2.0 | vtemian/university_projects,vtemian/university_projects,vtemian/university_projects | ---
+++
@@ -3,6 +3,8 @@
from twisted.internet.protocol import DatagramProtocol
from twisted.internet import reactor
+
+from announce.torrent import Torrent
class Announce(DatagramProtocol):
@@ -12,16 +14,31 @@
message = struct.pack('!iiq', action, transaction_id, connection)
return message
- def... |
2ef0ccfbf337d0ef1870c5a1191b2bcdcffd1f9e | dbaas/backup/admin/log_configuration.py | dbaas/backup/admin/log_configuration.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from django.contrib import admin
import logging
LOG = logging.getLogger(__name__)
class LogConfigurationAdmin(admin.ModelAdmin):
list_filter = ("environment", "engine_type")
list_display = ("environment", "engine_type", "rete... | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from django.contrib import admin
import logging
LOG = logging.getLogger(__name__)
class LogConfigurationAdmin(admin.ModelAdmin):
list_filter = ("environment", "engine_type")
list_display = ("environment", "engine_type", "rete... | Add new fields on LogConfiguration model | Add new fields on LogConfiguration model
| Python | bsd-3-clause | globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service | ---
+++
@@ -12,4 +12,5 @@
list_filter = ("environment", "engine_type")
list_display = ("environment", "engine_type", "retention_days",
- "filer_path", "mount_point_path", "log_path")
+ "filer_path", "mount_point_path", "log_path",
+ "cron_minute", "... |
446923b12942f351f2f40d035f0c1e6f9dcb8813 | __init__.py | __init__.py | # Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import os
import sys
# Add the third_party/ dir to our search path so that we can find the
# modules in there automatically. This isn't normal, so d... | # Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import os
import sys
# Add the third_party/ dir to our search path so that we can find the
# modules in there automatically. This isn't normal, so d... | Add <chrome>/src/third_party dir to PYTHONPATH for Chrome checkouts. | Add <chrome>/src/third_party dir to PYTHONPATH for Chrome checkouts.
If chromite is living inside the Chrome checkout under
<chrome_root>/src/third_party/chromite, its dependencies will be
checked out to <chrome_root>/src/third_party instead of the normal
chromite/third_party location due to git-submodule limitations ... | Python | bsd-3-clause | coreos/chromite,bpsinc-native/src_third_party_chromite,bpsinc-native/src_third_party_chromite,bpsinc-native/src_third_party_chromite,zhang0137/chromite,chadversary/chromiumos.chromite,coreos/chromite,zhang0137/chromite,coreos/chromite,zhang0137/chromite,chadversary/chromiumos.chromite | ---
+++
@@ -8,14 +8,26 @@
# Add the third_party/ dir to our search path so that we can find the
# modules in there automatically. This isn't normal, so don't replicate
# this pattern elsewhere.
-_third_party = os.path.normpath(os.path.join(os.path.dirname(os.path.realpath(
- __file__)), 'third_party'))
-sys.pa... |
16cd3b501755c6d45b39b46ca8179cc0dc015125 | main/admin/lan.py | main/admin/lan.py | from django.contrib import admin
from django.forms import model_to_dict
from django.utils.timezone import now
from main.models import Lan, Event
class EventInline(admin.TabularInline):
model = Event
show_change_link = True
fields = ('name', 'url', 'start', 'end')
@admin.register(Lan)
class LanAdmin(ad... | from django.contrib import admin
from django.forms import model_to_dict
from django.utils.timezone import now
from main.models import Lan, Event
class EventInline(admin.TabularInline):
model = Event
show_change_link = True
fields = ('name', 'url', 'start', 'end')
@admin.register(Lan)
class LanAdmin(ad... | Remove schedule from admin too | Remove schedule from admin too
| Python | mit | bomjacob/htxaarhuslan,bomjacob/htxaarhuslan,bomjacob/htxaarhuslan | ---
+++
@@ -24,7 +24,7 @@
'fields': ('seats',)
}),
('Tekst', {
- 'fields': ('name', 'schedule', 'blurb')
+ 'fields': ('name', 'blurb')
}),
('Betaling', {
'fields': ('paytypes', 'price', 'payphone') |
f497259869ba0f920d8a7eaac45bd320566c4808 | examples/Interactivity/circlepainter.py | examples/Interactivity/circlepainter.py | size(800, 800)
import time
colormode(RGB)
speed(60)
def setup():
# ovallist is the list of ovals we created by moving the mouse.
global ovallist
stroke(0)
strokewidth(1)
ovallist = []
class Blob:
def __init__(self, x, y, c, r):
self.x, self.y = x, y
self.color = c
self... | size(800, 800)
import time
colormode(RGB)
speed(60)
def setup():
# ovallist is the list of ovals we created by moving the mouse.
global ovallist
stroke(0)
strokewidth(1)
ovallist = []
class Blob:
def __init__(self, x, y, c, r):
self.x, self.y = x, y
self.color = c
self... | Use of circle() instead of oval() | Use of circle() instead of oval()
| Python | mit | karstenw/nodebox-pyobjc,karstenw/nodebox-pyobjc | ---
+++
@@ -21,7 +21,8 @@
fill(self.color)
stroke(0)
strokewidth(1)
- oval(self.x-self.radius, self.y-self.radius, self.radius*2, self.radius*2)
+ circle(self.x, self.y, self.radius)
+ # oval(self.x-self.radius, self.y-self.radius, self.radius*2, self.radius*2)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.