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 |
|---|---|---|---|---|---|---|---|---|---|---|
93ba327a3198c587d791aeb1d285f6e7f339df20 | app/grandchallenge/archives/models.py | app/grandchallenge/archives/models.py | from django.db import models
from grandchallenge.core.models import UUIDModel
from grandchallenge.cases.models import Image
from grandchallenge.patients.models import Patient
class Archive(UUIDModel):
"""
Model for archive. Contains a collection of images
"""
name = models.CharField(max_length=255, d... | from django.db import models
from grandchallenge.core.models import UUIDModel
from grandchallenge.cases.models import Image
from grandchallenge.patients.models import Patient
class Archive(UUIDModel):
"""
Model for archive. Contains a collection of images
"""
name = models.CharField(max_length=255, d... | Add args and kwargs to delete method | Add args and kwargs to delete method
| Python | apache-2.0 | comic/comic-django,comic/comic-django,comic/comic-django,comic/comic-django,comic/comic-django | ---
+++
@@ -18,5 +18,7 @@
def delete(self, *args, **kwargs):
# Remove all related patients and other models via cascading
- Patient.objects.filter(study__image__archive__id=self.id).delete()
+ Patient.objects.filter(study__image__archive__id=self.id).delete(
+ *args, **kwargs
... |
056c2922bd8304d054915bca10c9510148d96398 | isAccessedInFunction.py | isAccessedInFunction.py | #! /usr/bin/env python
import subprocess, sys, re
try:
classfile = sys.argv[1]
functionRE = re.compile(sys.argv[2])
toSearch = re.compile(sys.argv[3])
except (re.error, IndexError) as e:
print("""usage: %s classfile functionregex searchregex
Will disassemble classfile, then search for searchregex in... | #! /usr/bin/env python
import subprocess, sys, re
try:
classfile = sys.argv[1]
functionRE = re.compile(sys.argv[2])
toSearch = re.compile(sys.argv[3])
except (re.error, IndexError) as e:
print("""usage: %s classfile functionregex searchregex
Will disassemble classfile, then search for searchregex in... | Improve detection of function start. | Improve detection of function start.
| Python | apache-2.0 | FAU-Inf2/AuDoscore,FAU-Inf2/AuDoscore | ---
+++
@@ -26,7 +26,8 @@
foundWantedStringInWantedFunction = False
for line in iter(proc.stdout.readline,''):
if not insideWantedFunction:
- if functionRE.search(line):
+ if len(line) >= 3 and line[0:2] == ' ' and line[2] != ' ' \
+ and functionRE.search(line):
insid... |
f1754acb58fe9088e90692f5200babff3fa49bdf | src/zeit/cms/tests/test_celery.py | src/zeit/cms/tests/test_celery.py | import datetime
import zeit.cms.celery
import zeit.cms.testing
@zeit.cms.celery.CELERY.task()
def task(context, datetime):
pass
class CeleryTaskTest(zeit.cms.testing.ZeitCmsTestCase):
def test_registering_task_without_json_serializable_arguments_raises(self):
now = datetime.datetime.now()
w... | import datetime
import zeit.cms.celery
import zeit.cms.testing
@zeit.cms.celery.CELERY.task()
def dummy_task(context, datetime):
"""Dummy task to test our framework."""
class CeleryTaskTest(zeit.cms.testing.ZeitCmsTestCase):
"""Testing ..celery.TransactionAwareTask."""
def test_registering_task_without... | Improve naming and add docstrings. | ZON-3409: Improve naming and add docstrings.
| Python | bsd-3-clause | ZeitOnline/zeit.cms,ZeitOnline/zeit.cms,ZeitOnline/zeit.cms,ZeitOnline/zeit.cms | ---
+++
@@ -4,26 +4,27 @@
@zeit.cms.celery.CELERY.task()
-def task(context, datetime):
- pass
+def dummy_task(context, datetime):
+ """Dummy task to test our framework."""
class CeleryTaskTest(zeit.cms.testing.ZeitCmsTestCase):
+ """Testing ..celery.TransactionAwareTask."""
def test_register... |
ea287daca69d0385c2792cd0021a0b1a23fb912b | helpers/datadog_reporting.py | helpers/datadog_reporting.py | import os
import yaml
from dogapi import dog_stats_api, dog_http_api
def setup():
"""
Initialize connection to datadog during locust startup.
Reads the datadog api key from (in order):
1) An environment variable named DATADOG_API_KEY
2) the DATADOG_API_KEY of a yaml file at
2a) the enviro... | import os
import yaml
from dogapi import dog_stats_api, dog_http_api
def setup():
"""
Initialize connection to datadog during locust startup.
Reads the datadog api key from (in order):
1) An environment variable named DATADOG_API_KEY
2) the DATADOG_API_KEY of a yaml file at
2a) the enviro... | Fix reading of API key from yaml file. | Fix reading of API key from yaml file.
| Python | apache-2.0 | edx/edx-load-tests,edx/edx-load-tests,edx/edx-load-tests,edx/edx-load-tests | ---
+++
@@ -18,8 +18,9 @@
api_key = os.environ.get('DATADOG_API_KEY')
if api_key is None:
- server_vars_path = os.environ.get('ANSIBLE_VARS', '/edx/app/edx_ansible/server-vars.yaml')
- server_vars = yaml.safe_load(server_vars_path)
+ server_vars_path = os.environ.get('ANSIBLE_VARS', '... |
8548822ed0755a17cc3dc95cac582683a1ffb11c | linguist/models/base.py | linguist/models/base.py | # -*- coding: utf-8 -*-
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.utils.encoding import python_2_unicode_compatible
from .. import settings
@python_2_unicode_compatible
class Translation(models.Model):
"""
A Translation.
"""
identifier = models.C... | # -*- coding: utf-8 -*-
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.utils.encoding import python_2_unicode_compatible
from .. import settings
@python_2_unicode_compatible
class Translation(models.Model):
"""
A Translation.
"""
identifier = models.C... | Rename content field to field_value. | Rename content field to field_value.
| Python | mit | ulule/django-linguist | ---
+++
@@ -32,8 +32,8 @@
verbose_name=_('field name'),
help_text=_('The model field name for this translation.'))
- content = models.TextField(
- verbose_name=_('content'),
+ field_value = models.TextField(
+ verbose_name=_('field value'),
null=True,
help_tex... |
b7fd4b9db379fc9bc28f22f6608c804e9f08e181 | oonib/input/handlers.py | oonib/input/handlers.py | import glob
import json
import os
import yaml
from oonib.handlers import OONIBHandler
from oonib import config
class InputDescHandler(OONIBHandler):
def get(self, inputID):
#XXX return the input descriptor
# see oonib.md in ooni-spec
bn = os.path.basename(inputID) + ".desc"
try:
... | import glob
import json
import os
import yaml
from oonib.handlers import OONIBHandler
from oonib import config, log
class InputDescHandler(OONIBHandler):
def get(self, inputID):
bn = os.path.basename(inputID) + ".desc"
try:
f = open(os.path.join(config.main.input_dir, bn))
... | Implement input API as spec'd in oonib.md | Implement input API as spec'd in oonib.md
| Python | bsd-2-clause | DoNotUseThisCodeJUSTFORKS/ooni-backend,DoNotUseThisCodeJUSTFORKS/ooni-backend,dstufft/ooni-backend,dstufft/ooni-backend | ---
+++
@@ -1,28 +1,25 @@
import glob
import json
import os
-
import yaml
from oonib.handlers import OONIBHandler
-
-from oonib import config
+from oonib import config, log
class InputDescHandler(OONIBHandler):
def get(self, inputID):
- #XXX return the input descriptor
- # see oonib.md in... |
e85102e3c5e76c0e695aef2eb14ba973fb0da660 | lobster/commands/elk.py | lobster/commands/elk.py | from lobster.core.command import Command
class Elk_Update(Command):
@property
def help(self):
return 'update Kibana objects'
def setup(self, argparser):
pass
def run(self, args):
args.config.elk.update_kibana()
class Elk_Cleanup(Command):
@property
def help(self):
... | from lobster.core.command import Command
class ElkUpdate(Command):
@property
def help(self):
return 'update Kibana objects'
def setup(self, argparser):
pass
def run(self, args):
args.config.elk.update_kibana()
class ElkCleanup(Command):
@property
def help(self):
... | Change class names to CamelCase | Change class names to CamelCase
| Python | mit | matz-e/lobster,matz-e/lobster,matz-e/lobster | ---
+++
@@ -1,7 +1,7 @@
from lobster.core.command import Command
-class Elk_Update(Command):
+class ElkUpdate(Command):
@property
def help(self):
return 'update Kibana objects'
@@ -13,7 +13,7 @@
args.config.elk.update_kibana()
-class Elk_Cleanup(Command):
+class ElkCleanup(Command... |
8ecc24ab865ff9dec647fe69d78af0a63f0a902a | nap/rest/models.py | nap/rest/models.py | from __future__ import unicode_literals
from .. import http
from .publisher import Publisher
from django.db import transaction
from django.shortcuts import get_object_or_404
class ModelPublisher(Publisher):
'''A Publisher with useful methods to publish Models'''
@property
def model(self):
'''By... | from __future__ import unicode_literals
from .. import http
from ..shortcuts import get_object_or_404
from .publisher import Publisher
from django.db import transaction
class ModelPublisher(Publisher):
'''A Publisher with useful methods to publish Models'''
@property
def model(self):
'''By defa... | Use our own get_object_or_404 for ModelPublisher.get_object | Use our own get_object_or_404 for ModelPublisher.get_object
| Python | bsd-3-clause | MarkusH/django-nap,limbera/django-nap | ---
+++
@@ -1,10 +1,10 @@
from __future__ import unicode_literals
from .. import http
+from ..shortcuts import get_object_or_404
from .publisher import Publisher
from django.db import transaction
-from django.shortcuts import get_object_or_404
class ModelPublisher(Publisher): |
1599d4ed14fb3d7c7e551c9f6ce3f86d9df17cbd | mammoth/writers/html.py | mammoth/writers/html.py | from __future__ import unicode_literals
from .abc import Writer
import cgi
class HtmlWriter(Writer):
def __init__(self):
self._fragments = []
def text(self, text):
self._fragments.append(_escape_html(text))
def start(self, name, attributes=None):
attribute_string = _gen... | from __future__ import unicode_literals
from xml.sax.saxutils import escape
from .abc import Writer
class HtmlWriter(Writer):
def __init__(self):
self._fragments = []
def text(self, text):
self._fragments.append(_escape_html(text))
def start(self, name, attributes=None):
... | Use xml.sax.saxutils.escape instead of deprecated cgi.escape | Use xml.sax.saxutils.escape instead of deprecated cgi.escape
```
/usr/local/lib/python3.6/dist-packages/mammoth/writers/html.py:34: DeprecationWarning: cgi.escape is deprecated, use html.escape instead
return cgi.escape(text, quote=True)
```
| Python | bsd-2-clause | mwilliamson/python-mammoth | ---
+++
@@ -1,8 +1,7 @@
from __future__ import unicode_literals
+from xml.sax.saxutils import escape
from .abc import Writer
-
-import cgi
class HtmlWriter(Writer):
@@ -31,7 +30,7 @@
def _escape_html(text):
- return cgi.escape(text, quote=True)
+ return escape(text, {'"': """})
def _gene... |
7c91429412119f887e611c5f6a52a5ebc32a99b0 | tof_server/map_model.py | tof_server/map_model.py | """Model for handling operations on map data"""
import json
def persist_map(map_data, metadata, cursor, player_id):
"""Method for persisting map data"""
serialized_map_data = json.dumps(map_data)
map_sql = """INSERT INTO maps
(download_code, map_hash, player_id)
VALUES (%s,... | """Model for handling operations on map data"""
import json
def persist_map(map_data, metadata, cursor, player_id):
"""Method for persisting map data"""
serialized_map_data = json.dumps(map_data)
map_sql = """INSERT INTO maps
(download_code, map_hash, player_id)
VALUES (%s,... | Change map download code to be case insensitive | Change map download code to be case insensitive
| Python | mit | P1X-in/Tanks-of-Freedom-Server | ---
+++
@@ -23,7 +23,7 @@
def find_map(map_code, cursor):
"""Method for retrieving map data"""
map_code_sql = "SELECT id FROM maps WHERE download_code = %s"
- cursor.execute(map_code_sql, (map_code,))
+ cursor.execute(map_code_sql, (map_code.upper(),))
map_id = cursor.fetchone()
if not ma... |
bb190d54324e15ed6ce99845047228eaef5e57cb | test_core.py | test_core.py | #!/usr/bin/env python
from ookoobah import core
from ookoobah import utils
game = core.Game()
utils.populate_grid_from_string(game.grid, """
######
#>..\#
#.#..#
#....#
#.\./#
######
""")
game.start()
for n in range(10):
print utils.dump_grid_to_string(game.grid, game.ball)
game.step... | #!/usr/bin/env python
from ookoobah import core
from ookoobah import utils
game = core.Game()
utils.populate_grid_from_string(game.grid, """
######
#>..\#
#.#..#
#....#
#.\./#
######
""")
game.start()
print "hit <enter> to render next; ^C to abort"
while True:
print utils.dump_grid_to_st... | Make the core dumper interactive | test: Make the core dumper interactive
| Python | mit | vickenty/ookoobah,vickenty/ookoobah,vickenty/ookoobah,vickenty/ookoobah,vickenty/ookoobah | ---
+++
@@ -15,6 +15,8 @@
""")
game.start()
-for n in range(10):
+print "hit <enter> to render next; ^C to abort"
+while True:
print utils.dump_grid_to_string(game.grid, game.ball)
game.step()
+ raw_input() |
7f2d9b94bdcbfb90870591d7cb497bb0aa2ac069 | test/test_yeast.py | test/test_yeast.py | import unittest
from yeast_harness import *
class TestYeast(unittest.TestCase):
def test_single_c_source(self):
mk = Makefile(
spores=SporeFile(
sources=CSourceFile('tree'),
products='static_lib',
path='tree'),
name='Makefile')
... | import unittest
from yeast_harness import *
class TestYeast(unittest.TestCase):
def test_single_c_source(self):
mk = Makefile(
spores=SporeFile(
sources=CSourceFile('tree'),
products='static_lib',
path='tree'),
name='Makefile')
... | Create initial test case for large tree | Create initial test case for large tree
| Python | mit | sjanhunen/yeast,sjanhunen/moss,sjanhunen/gnumake-molds,sjanhunen/moss | ---
+++
@@ -17,3 +17,19 @@
mk.create_sources()
self.assertEqual(mk.make(), 0)
self.assertEqual(mk.make('-q'), 0)
+
+ def test_large_source_tree(self):
+
+ make_sources = lambda: [CSourceFile('tree') for _ in range(10)]
+ make_spore = lambda: SporeFile(
+ sour... |
77d0fe3daec4f6e4f9166dcd32943b21384a2073 | tests/test_core.py | tests/test_core.py | from grazer.core import crawler
from bs4 import BeautifulSoup
def test_extract_links():
text = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title"><b>The Dormouse's story</b></p>
<p class="story">Once upon a time there were three little sisters; and their names were... | from grazer.core import crawler
from bs4 import BeautifulSoup
def test_extract_links():
text = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title"><b>The Dormouse's story</b></p>
<p class="story">Once upon a time there were three little sisters; and their names were... | Test to validate trimming scenario | Test to validate trimming scenario
| Python | mit | CodersOfTheNight/verata | ---
+++
@@ -30,3 +30,8 @@
def test_link_trimmer():
result = crawler.trim_link("http://example.com/lacie", "http://example.com")
assert result == "/lacie"
+
+
+def test_trim_link_without_trailing_slash():
+ result = crawler.trim_link("http://example.com", "http://example.com")
+ assert result == "http... |
3f5ac069710679201cb0a3a041a0ca75186c9e03 | version.py | version.py | major = 0
minor=0
patch=16
branch="master"
timestamp=1376507917.4 | major = 0
minor=0
patch=17
branch="master"
timestamp=1376509025.95 | Tag commit for v0.0.17-master generated by gitmake.py | Tag commit for v0.0.17-master generated by gitmake.py
| Python | mit | ryansturmer/gitmake | ---
+++
@@ -1,5 +1,5 @@
major = 0
minor=0
-patch=16
+patch=17
branch="master"
-timestamp=1376507917.4
+timestamp=1376509025.95 |
fdc23d97064220e1042bcf7a7cb9714f476c4219 | busstops/management/commands/import_operators.py | busstops/management/commands/import_operators.py | """
Usage:
./manage.py import_operators < NOC_db.csv
"""
from busstops.management.import_from_csv import ImportFromCSVCommand
from busstops.models import Operator
class Command(ImportFromCSVCommand):
@staticmethod
def get_region_id(region_id):
if region_id in ('ADMIN', 'Admin', ''):
... | """
Usage:
./manage.py import_operators < NOC_db.csv
"""
from busstops.management.import_from_csv import ImportFromCSVCommand
from busstops.models import Operator
class Command(ImportFromCSVCommand):
@staticmethod
def get_region_id(region_id):
if region_id in ('ADMIN', 'Admin', ''):
... | Stop importing clearly duplicate operators (like the First Manchester operator without a name) | Stop importing clearly duplicate operators (like the First Manchester operator without a name)
| Python | mpl-2.0 | jclgoodwin/bustimes.org.uk,stev-0/bustimes.org.uk,jclgoodwin/bustimes.org.uk,jclgoodwin/bustimes.org.uk,jclgoodwin/bustimes.org.uk,stev-0/bustimes.org.uk,stev-0/bustimes.org.uk,stev-0/bustimes.org.uk,stev-0/bustimes.org.uk | ---
+++
@@ -22,6 +22,9 @@
@classmethod
def handle_row(cls, row):
"Given a CSV row (a list), returns an Operator object"
+ if row['Duplicate'] != 'OK':
+ return None
+
operator_id = row['NOCCODE'].replace('=', '')
if operator_id == 'TVSR': |
4f27be336a58d0bba66a4f7ab57126d9dd734ab9 | talks/views.py | talks/views.py | from django.shortcuts import render, get_object_or_404
from config.utils import get_active_event
from .models import Talk
def list_talks(request):
event = get_active_event()
talks = event.talks.prefetch_related(
'applicants',
'applicants__user',
'skill_level',
'sponsor',
... | from django.shortcuts import render, get_object_or_404
from config.utils import get_active_event
from .models import Talk
def list_talks(request):
event = get_active_event()
talks = event.talks.prefetch_related(
'applicants',
'applicants__user',
'skill_level',
'sponsor',
... | Revert "Temporarily make talks visible only to committee" | Revert "Temporarily make talks visible only to committee"
This reverts commit 57050b7025acb3de66024fe01255849a5ba5f1fc.
| Python | bsd-3-clause | WebCampZg/conference-web,WebCampZg/conference-web,WebCampZg/conference-web | ---
+++
@@ -14,12 +14,6 @@
'sponsor',
).order_by('-keynote', 'title')
- # Temporary hack to let only admins & committee members see the talks
- user = request.user
- permitted = user.is_authenticated and (user.is_superuser or user.is_talk_committee_member())
- if not permitted:
- ta... |
2161910a53604bdc48027c5c4e71f9af4228cbaa | keras/backend/common.py | keras/backend/common.py | import numpy as np
# the type of float to use throughout the session.
_FLOATX = 'float32'
_EPSILON = 10e-8
def epsilon():
return _EPSILON
def set_epsilon(e):
global _EPSILON
_EPSILON = e
def floatx():
return _FLOATX
def set_floatx(floatx):
global _FLOATX
if floatx not in {'float32', 'fl... | import numpy as np
# the type of float to use throughout the session.
_FLOATX = 'float32'
_EPSILON = 10e-8
def epsilon():
return _EPSILON
def set_epsilon(e):
global _EPSILON
_EPSILON = e
def floatx():
return _FLOATX
def set_floatx(floatx):
global _FLOATX
if floatx not in {'float32', 'fl... | Fix floatx encoding on Python3 | Fix floatx encoding on Python3 | Python | apache-2.0 | keras-team/keras,nebw/keras,daviddiazvico/keras,kemaswill/keras,DeepGnosis/keras,keras-team/keras,dolaameng/keras,relh/keras,kuza55/keras | ---
+++
@@ -22,8 +22,7 @@
global _FLOATX
if floatx not in {'float32', 'float64'}:
raise Exception('Unknown floatx type: ' + str(floatx))
- if isinstance(floatx, unicode):
- floatx = floatx.encode('ascii')
+ floatx = floatx.encode('ascii')
_FLOATX = floatx
|
5bb7cc09df33debb46eba17d12f078f043131db0 | kicad_footprint_load.py | kicad_footprint_load.py | import pcbnew
import sys
import os
pretties = []
for dirname, dirnames, filenames in os.walk(sys.argv[1]):
# don't go into any .git directories.
if '.git' in dirnames:
dirnames.remove('.git')
for filename in filenames:
if (not os.path.isdir(filename)) and (os.path.splitext(filename)[-1] ==... | import pcbnew
import sys
import os
pretties = []
for dirname, dirnames, filenames in os.walk(sys.argv[1]):
# don't go into any .git directories.
if '.git' in dirnames:
dirnames.remove('.git')
for filename in filenames:
if (not os.path.isdir(filename)) and (os.path.splitext(filename)[-1] ==... | Document kicad python unicode bug | Document kicad python unicode bug
| Python | mit | monostable/haskell-kicad-data,monostable/haskell-kicad-data,kasbah/haskell-kicad-data | ---
+++
@@ -19,6 +19,9 @@
try:
list_of_footprints = src_plugin.FootprintEnumerate(libpath)
except UnicodeDecodeError:
+ # pcbnew python modules (at least git-7d6230a and v4.x) have an issue
+ # with loading unicode paths
+ # https://bugs.launchpad.net/kicad/+bug/1740881
... |
ce42ab724ad8a76dd04e24e4df6d20d96255989f | kitchen/lib/__init__.py | kitchen/lib/__init__.py | import os
import json
from kitchen.settings import KITCHEN_LOCATION
def load_data(data_type):
retval = []
nodes_dir = os.path.join(KITCHEN_LOCATION, data_type)
if not os.path.isdir(nodes_dir):
raise IOError('Invalid data type or kitchen location. Check your settings.')
for filename in os.listd... | import os
import json
from kitchen.settings import KITCHEN_LOCATION
def load_data(data_type):
retval = []
nodes_dir = os.path.join(KITCHEN_LOCATION, data_type)
if not os.path.isdir(nodes_dir):
raise IOError('Invalid data type or kitchen location. Check your settings.')
for filename in os.listd... | Allow list to be sorted by a key in the node's data | Allow list to be sorted by a key in the node's data
| Python | apache-2.0 | edelight/kitchen,edelight/kitchen,edelight/kitchen,edelight/kitchen | ---
+++
@@ -15,5 +15,7 @@
entry['data'] = json.load(f)
f.close()
retval.append(entry)
- return retval
+ return sort_list_by_data_key(retval, 'chef_environment')
+def sort_list_by_data_key(old_list, key):
+ return sorted(old_list, key=lambda k: k['data'][key]) |
74a3fe9d83c3ccf2f6972277df3a34c47bc06c26 | slave/skia_slave_scripts/run_gyp.py | slave/skia_slave_scripts/run_gyp.py | #!/usr/bin/env python
# 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.
""" Run GYP to generate project files. """
from build_step import BuildStep
import sys
class RunGYP(BuildStep):
def _Run(self)... | #!/usr/bin/env python
# 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.
""" Run GYP to generate project files. """
from build_step import BuildStep
import sys
class RunGYP(BuildStep):
def __init__(s... | Increase timeout for RunGYP step BUG=skia:1631 (SkipBuildbotRuns) | Increase timeout for RunGYP step
BUG=skia:1631
(SkipBuildbotRuns)
git-svn-id: 32fc27f4dcfb6c0385cd9719852b95fe6680452d@11229 2bbb7eff-a529-9590-31e7-b0007b416f81
| Python | bsd-3-clause | Tiger66639/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbo... | ---
+++
@@ -10,6 +10,12 @@
class RunGYP(BuildStep):
+ def __init__(self, timeout=15000, no_output_timeout=10000,
+ **kwargs):
+ super(RunGYP, self).__init__(timeout=timeout,
+ no_output_timeout=no_output_timeout,
+ **kwargs)
+
d... |
96ef8f3f2c81822df635a373496d2f638178f85a | backend/project_name/settings/test.py | backend/project_name/settings/test.py | from .base import * # noqa
SECRET_KEY = "test"
DATABASES = {
"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": base_dir_join("db.sqlite3"),}
}
STATIC_ROOT = "staticfiles"
STATIC_URL = "/static/"
MEDIA_ROOT = "mediafiles"
MEDIA_URL = "/media/"
DEFAULT_FILE_STORAGE = "django.core.files.storage.FileSy... | from .base import * # noqa
SECRET_KEY = "test"
DATABASES = {
"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": base_dir_join("db.sqlite3"),}
}
STATIC_ROOT = base_dir_join('staticfiles')
STATIC_URL = '/static/'
MEDIA_ROOT = base_dir_join('mediafiles')
MEDIA_URL = '/media/'
DEFAULT_FILE_STORAGE = "dj... | Revert "Fix ci build by adjust static root and media root path" | Revert "Fix ci build by adjust static root and media root path"
This reverts commit e502c906
| Python | mit | vintasoftware/django-react-boilerplate,vintasoftware/django-react-boilerplate,vintasoftware/django-react-boilerplate,vintasoftware/django-react-boilerplate | ---
+++
@@ -7,11 +7,11 @@
"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": base_dir_join("db.sqlite3"),}
}
-STATIC_ROOT = "staticfiles"
-STATIC_URL = "/static/"
+STATIC_ROOT = base_dir_join('staticfiles')
+STATIC_URL = '/static/'
-MEDIA_ROOT = "mediafiles"
-MEDIA_URL = "/media/"
+MEDIA_ROOT = bas... |
f365c36cb726f6ace05cf05f1a11635337963270 | src/nodeconductor_saltstack/sharepoint/extension.py | src/nodeconductor_saltstack/sharepoint/extension.py | from nodeconductor.core import NodeConductorExtension
class SharepointExtension(NodeConductorExtension):
@staticmethod
def django_app():
return 'nodeconductor_saltstack.sharepoint'
@staticmethod
def rest_urls():
from .urls import register_in
return register_in
@staticmet... | from nodeconductor.core import NodeConductorExtension
class SharepointExtension(NodeConductorExtension):
@staticmethod
def django_app():
return 'nodeconductor_saltstack.sharepoint'
@staticmethod
def rest_urls():
from .urls import register_in
return register_in
@staticmet... | Increase default sync frequency for SP | Increase default sync frequency for SP
| Python | mit | opennode/nodeconductor-saltstack | ---
+++
@@ -18,7 +18,7 @@
return {
'sharepoint-sync-tenants': {
'task': 'nodeconductor.sharepoint.sync_tenants',
- 'schedule': timedelta(minutes=30),
+ 'schedule': timedelta(minutes=10),
'args': ()
},
} |
74c770b8b457b14a297193e0cd8e9d5bb6b4b031 | utils/retry.py | utils/retry.py | import time
import urllib2
import socket
from google.appengine.api import datastore_errors
from google.appengine.runtime import apiproxy_errors
MAX_ATTEMPTS = 10
def retry(func, *args, **kwargs):
for attempt in range(MAX_ATTEMPTS):
if attempt:
seconds = min(300, 2 ** attempt)
pri... | import logging
import time
import urllib2
import socket
from google.appengine.api import datastore_errors
from google.appengine.runtime import apiproxy_errors
MAX_ATTEMPTS = 10
def retry(func, *args, **kwargs):
for attempt in range(MAX_ATTEMPTS):
if attempt:
seconds = min(300, 2 ** attempt)
... | Use logging module for debug messages, not stdout. | Use logging module for debug messages, not stdout.
| Python | mit | jcrocholl/nxdom,jcrocholl/nxdom | ---
+++
@@ -1,3 +1,4 @@
+import logging
import time
import urllib2
import socket
@@ -12,15 +13,15 @@
for attempt in range(MAX_ATTEMPTS):
if attempt:
seconds = min(300, 2 ** attempt)
- print "Attempt %d of %d will start in %d seconds." % (
- attempt + 1, MAX_ATTE... |
b2d121a2ee8750afd0f4d527c80371bd501f841c | neo/io/nixio_fr.py | neo/io/nixio_fr.py | from neo.io.basefromrawio import BaseFromRaw
from neo.rawio.nixrawio import NIXRawIO
# This class subjects to limitations when there are multiple asymmetric blocks
class NixIO(NIXRawIO, BaseFromRaw):
name = 'NIX IO'
_prefered_signal_group_mode = 'group-by-same-units'
_prefered_units_group_mode = 'split... | from neo.io.basefromrawio import BaseFromRaw
from neo.rawio.nixrawio import NIXRawIO
# This class subjects to limitations when there are multiple asymmetric blocks
class NixIO(NIXRawIO, BaseFromRaw):
name = 'NIX IO'
_prefered_signal_group_mode = 'group-by-same-units'
_prefered_units_group_mode = 'split... | Use Python2 compatible super() call | [nixio] Use Python2 compatible super() call
| Python | bsd-3-clause | NeuralEnsemble/python-neo,JuliaSprenger/python-neo,samuelgarcia/python-neo,INM-6/python-neo,rgerkin/python-neo,apdavison/python-neo | ---
+++
@@ -17,8 +17,10 @@
def read_block(self, block_index=0, lazy=False, signal_group_mode=None,
units_group_mode=None, load_waveforms=False):
- bl = super().read_block(block_index, lazy, signal_group_mode,
- units_group_mode, load_waveforms)
+ ... |
0c67cff030592cd44023444a5f10eef6570bfdf0 | odinweb/testing.py | odinweb/testing.py | """
Testing Helpers
~~~~~~~~~~~~~~~
Collection of Mocks and Tools for testing APIs.
"""
from odin.codecs import json_codec
from odinweb.constants import Method
class MockRequest(object):
"""
Mocked Request object
"""
def __init__(self, query=None, post=None, headers=None, method=Method.GET, body=''... | """
Testing Helpers
~~~~~~~~~~~~~~~
Collection of Mocks and Tools for testing APIs.
"""
from typing import Dict, Any
from odin.codecs import json_codec
try:
from urllib.parse import urlparse, parse_qs
except ImportError:
from urlparse import urlparse, parse_qs
from odinweb.constants import Method
class Mo... | Expand Mock Request to include path and built in URL parsing. | Expand Mock Request to include path and built in URL parsing.
| Python | bsd-3-clause | python-odin/odinweb,python-odin/odinweb | ---
+++
@@ -5,22 +5,40 @@
Collection of Mocks and Tools for testing APIs.
"""
+from typing import Dict, Any
+
from odin.codecs import json_codec
+try:
+ from urllib.parse import urlparse, parse_qs
+except ImportError:
+ from urlparse import urlparse, parse_qs
from odinweb.constants import Method
cl... |
8da30d3752fd6a056891960aa2892bcd8001c79b | lintreview/processor.py | lintreview/processor.py | import logging
import lintreview.tools as tools
from lintreview.diff import DiffCollection
from lintreview.review import Problems
from lintreview.review import Review
log = logging.getLogger(__name__)
class Processor(object):
def __init__(self, client, number, head, target_path):
self._client = client
... | import logging
import lintreview.tools as tools
from lintreview.diff import DiffCollection
from lintreview.review import Problems
from lintreview.review import Review
log = logging.getLogger(__name__)
class Processor(object):
def __init__(self, client, number, head, target_path):
self._client = client
... | Make check against None instead of falsey things. | Make check against None instead of falsey things.
| Python | mit | markstory/lint-review,markstory/lint-review,adrianmoisey/lint-review,zoidbergwill/lint-review,zoidbergwill/lint-review,adrianmoisey/lint-review,zoidbergwill/lint-review,markstory/lint-review | ---
+++
@@ -27,7 +27,7 @@
self._problems.set_changes(self._changes)
def run_tools(self, repo_config):
- if not self._changes:
+ if self._changes is None:
raise RuntimeError('No loaded changes, cannot run tools. '
'Try calling load_changes firs... |
f62ccee6bffa4dff9047a2f4b7499412dd3e2fb1 | tomviz/python/SwapAxes.py | tomviz/python/SwapAxes.py | def transform(dataset, axis1, axis2):
"""Swap two axes in a dataset"""
data_py = dataset.active_scalars
dataset.active_scalars = data_py.swapaxes(axis1, axis2)
| def transform(dataset, axis1, axis2):
"""Swap two axes in a dataset"""
import numpy as np
data_py = dataset.active_scalars
swapped = data_py.swapaxes(axis1, axis2)
dataset.active_scalars = np.asfortranarray(swapped)
| Convert array back to fortran before setting | Convert array back to fortran before setting
Unfortunately, it looks like numpy.ndarray.swapaxes converts
the ordering from Fortran to C. When this happens, a warning
message will be printed to the console later that a conversion to
Fortran ordering is required.
Instead of printing the warning, just convert it back t... | Python | bsd-3-clause | OpenChemistry/tomviz,OpenChemistry/tomviz,OpenChemistry/tomviz,OpenChemistry/tomviz | ---
+++
@@ -1,5 +1,8 @@
def transform(dataset, axis1, axis2):
"""Swap two axes in a dataset"""
+ import numpy as np
+
data_py = dataset.active_scalars
- dataset.active_scalars = data_py.swapaxes(axis1, axis2)
+ swapped = data_py.swapaxes(axis1, axis2)
+ dataset.active_scalars = np.asfortranar... |
5558b19b46fbe1db6f25b227ac581095fedcff2e | us_ignite/maps/views.py | us_ignite/maps/views.py | import json
from django.core.serializers.json import DjangoJSONEncoder
from django.http import HttpResponse
from django.template.response import TemplateResponse
from us_ignite.maps.models import Location
def location_list(request):
"""Shows a list of locations in a map."""
object_list = Location.published.... | from django.template.response import TemplateResponse
from us_ignite.common.response import json_response
from us_ignite.maps.models import Location
def location_list(request):
"""Shows a list of locations in a map."""
object_list = Location.published.select_related('category').all()
context = {
... | Update ``maps`` to use the ``json_response`` function. | Update ``maps`` to use the ``json_response`` function.
| Python | bsd-3-clause | us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite | ---
+++
@@ -1,9 +1,6 @@
-import json
-
-from django.core.serializers.json import DjangoJSONEncoder
-from django.http import HttpResponse
from django.template.response import TemplateResponse
+from us_ignite.common.response import json_response
from us_ignite.maps.models import Location
@@ -38,5 +35,4 @@
... |
497b0c8e9581cee76398c18c78ea8eb4362ef5b2 | project/editorial/views/__init__.py | project/editorial/views/__init__.py | from braces.views import UserPassesTestMixin
class CustomUserTest(UserPassesTestMixin):
"""User must be a member of this organization to view this content.
This also requires that a user be logged in, so it's not needed to use this
with LoginRequiredMixin.
"""
def test_func(self, user):
... | from braces.views import UserPassesTestMixin
class CustomUserTest(UserPassesTestMixin):
"""User must be a member of this organization to view this content.
This also requires that a user be logged in, so it's not needed to use this
with LoginRequiredMixin.
"""
def test_func(self, user):
... | Fix API call for is-superuser. | Fix API call for is-superuser.
| Python | mit | ProjectFacet/facet,ProjectFacet/facet,ProjectFacet/facet,ProjectFacet/facet,ProjectFacet/facet | ---
+++
@@ -11,7 +11,7 @@
def test_func(self, user):
""""User must be a super"""
- if user.is_superuser():
+ if user.is_superuser:
# Superuser can use all views
return True
|
89f631bcaa4a48a4f65989975031efbbbd59e522 | l10n_ch_mis_reports/__manifest__.py | l10n_ch_mis_reports/__manifest__.py | # Copyright 2018 Camptocamp SA
# Copyright 2015 Agile Business Group
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
{
'name': 'Switzerland - MIS reports',
'summary': 'Specific MIS reports for switzerland localization',
'version': '11.0.1.0.0',
'author': "Camptocamp,Odoo Community ... | # Copyright 2018 Camptocamp SA
# Copyright 2015 Agile Business Group
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
{
'name': 'Switzerland - MIS reports',
'summary': 'Specific MIS reports for switzerland localization',
'version': '11.0.1.1.0',
'author': "Camptocamp,Odoo Community ... | Fix dependency to mis_builder_budget to remove runbot warning | Fix dependency to mis_builder_budget to remove runbot warning
| Python | agpl-3.0 | brain-tec/l10n-switzerland,brain-tec/l10n-switzerland,brain-tec/l10n-switzerland | ---
+++
@@ -5,14 +5,14 @@
{
'name': 'Switzerland - MIS reports',
'summary': 'Specific MIS reports for switzerland localization',
- 'version': '11.0.1.0.0',
+ 'version': '11.0.1.1.0',
'author': "Camptocamp,Odoo Community Association (OCA)",
'category': 'Localization',
'website': 'https:... |
9bdf9455344b83fc28c5ecceafba82036bb2c75d | foodsaving/management/tests/test_makemessages.py | foodsaving/management/tests/test_makemessages.py | from unittest.mock import patch
from django.test import TestCase
from ..commands.makemessages import Command as MakeMessagesCommand
from django_jinja.management.commands.makemessages import Command as DjangoJinjaMakeMessagesCommand
makemessages = MakeMessagesCommand
django_jinja_makemessages = DjangoJinjaMakeMessages... | from unittest.mock import patch
from django.test import TestCase
from ..commands.makemessages import Command as MakeMessagesCommand
from django_jinja.management.commands.makemessages import Command as DjangoJinjaMakeMessagesCommand
makemessages = MakeMessagesCommand
django_jinja_makemessages = DjangoJinjaMakeMessages... | Fix makemessages test to look for jinja2 | Fix makemessages test to look for jinja2
| Python | agpl-3.0 | yunity/foodsaving-backend,yunity/yunity-core,yunity/foodsaving-backend,yunity/yunity-core,yunity/foodsaving-backend | ---
+++
@@ -15,12 +15,8 @@
}
modified_options = MakeMessagesCommand.update_options(**options)
- self.assertIn('jinja', modified_options['extensions'])
+ self.assertIn('jinja2', modified_options['extensions'])
self.assertIn('en', modified_options['locale'])
-
- options... |
b6308afbc33f80b621e68c3d2b635fe64666c51a | wcontrol/conf/config.py | wcontrol/conf/config.py | import os
basedir = os.path.abspath(os.path.dirname(__file__))
# forms wtf config
WTF_CSRF_ENABLED = True
SECRET_KEY = 'impossible-to-guess'
# sqlalchemy database config
SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir, 'app.db')
SQLALCHEMY_MIGRATE_REPO = os.path.join(basedir, 'db_repository')
SQLALCHEMY... | import os
basedir = os.path.abspath(os.path.dirname(__file__))
# forms wtf config
WTF_CSRF_ENABLED = True
SECRET_KEY = 'impossible-to-guess'
# sqlalchemy database config
SQLALCHEMY_DATABASE_URI = os.environ.get('WCONTROL_DB',
'sqlite:///wcontrol/db/app.db')
SQLALCHEMY_MIGRATE_... | Use a env var to get DB path | Use a env var to get DB path
| Python | mit | pahumadad/weight-control,pahumadad/weight-control,pahumadad/weight-control,pahumadad/weight-control | ---
+++
@@ -6,7 +6,8 @@
SECRET_KEY = 'impossible-to-guess'
# sqlalchemy database config
-SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir, 'app.db')
+SQLALCHEMY_DATABASE_URI = os.environ.get('WCONTROL_DB',
+ 'sqlite:///wcontrol/db/app.db')
SQLALCHEMY_MIGRATE_R... |
58d3efa146f006fe518b02234b4eb0d6708cecc8 | examples/web_ws.py | examples/web_ws.py | #!/usr/bin/env python3
"""Example for aiohttp.web websocket server
"""
import os
from aiohttp import web
WS_FILE = os.path.join(os.path.dirname(__file__), 'websocket.html')
async def wshandler(request):
resp = web.WebSocketResponse()
available = resp.can_prepare(request)
if not available:
with... | #!/usr/bin/env python3
"""Example for aiohttp.web websocket server
"""
import os
from aiohttp import web
WS_FILE = os.path.join(os.path.dirname(__file__), 'websocket.html')
async def wshandler(request):
resp = web.WebSocketResponse()
available = resp.can_prepare(request)
if not available:
with... | Send welcome message at very first of communication channel | Send welcome message at very first of communication channel
| Python | apache-2.0 | rutsky/aiohttp,arthurdarcet/aiohttp,arthurdarcet/aiohttp,KeepSafe/aiohttp,rutsky/aiohttp,KeepSafe/aiohttp,KeepSafe/aiohttp,rutsky/aiohttp,arthurdarcet/aiohttp | ---
+++
@@ -18,6 +18,8 @@
return web.Response(body=fp.read(), content_type='text/html')
await resp.prepare(request)
+
+ await resp.send_str('Welcome!!!')
try:
print('Someone joined.') |
2c914f6e438906296860983a01e593ab1f9a5cd7 | CloudSQLReplicator/google/cloud/pontem/sql/replicator/__init__.py | CloudSQLReplicator/google/cloud/pontem/sql/replicator/__init__.py | # Copyright 2018 The Pontem Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable l... | # Copyright 2018 The Pontem Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable l... | Update the UA used in CloudSQLReplicator | Update the UA used in CloudSQLReplicator
| Python | apache-2.0 | GoogleCloudPlatform/pontem,GoogleCloudPlatform/pontem | ---
+++
@@ -15,4 +15,5 @@
"""Pontem SQL Replicator."""
__version__ = '0.0.1'
-__package_name__ = 'cloudsql-replicator'
+__package_name__ = 'cloudsql-replication'
+ |
5dbea33ce9d2b2d9354a8e86e271c087723dc748 | events/cms_plugins.py | events/cms_plugins.py | from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool
import datetime
from django.utils.translation import ugettext as _
from events.models import CalendarEventsPlugin as CalendarEventsPluginModel
from events.models import AllEventsPlugin as AllEventsPluginModel
from events.models import Eve... | from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool
import datetime
from django.utils.translation import ugettext as _
from events.models import CalendarEventsPlugin as CalendarEventsPluginModel
from events.models import AllEventsPlugin as AllEventsPluginModel
from events.models import Eve... | Update context for one calendar | Update context for one calendar
| Python | bsd-3-clause | theherk/django-theherk-events | ---
+++
@@ -14,7 +14,7 @@
module = _("TheHerk")
def render(self, context, instance, placeholder):
- events = Event.objects.filter(calendar__id=instance.calendar).filter(end__gte=datetime.date.today()).order_by('start')[:instance.number_to_show]
+ events = Event.objects.filter(calendar__id=in... |
5a4e9d19f75bb02dc359099931310c7e6dd1ac99 | web/extras/contentment/components/folder/controller.py | web/extras/contentment/components/folder/controller.py | # encoding: utf-8
"""Basic folder controller.
Additional views on asset contents.
"""
import datetime
from web.extras.contentment.api import action, view
from web.extras.contentment.components.asset.controller import AssetController
log = __import__('logging').getLogger(__name__)
__all__ = ['FolderController']
... | # encoding: utf-8
"""Basic folder controller.
Additional views on asset contents.
"""
import datetime
from web.extras.contentment.api import action, view
from web.extras.contentment.components.asset.controller import AssetController
log = __import__('logging').getLogger(__name__)
__all__ = ['FolderController']
... | Change default year to maximal available year, not current year. | Change default year to maximal available year, not current year.
| Python | mit | marrow/contentment,marrow/contentment | ---
+++
@@ -36,6 +36,12 @@
years = sorted(list(set(years)))
+ if year > max(years):
+ year = years[-1]
+
+ elif year < min(years):
+ yeare = years[0]
+
filter_range = (datetime.datetime(year, 1, 1, 0, 0, 0), datetime.datetime(ye... |
a4f03e82b72287027a57101fe67f7fc26d312801 | url_shortener/__init__.py | url_shortener/__init__.py | # -*- coding: utf-8 -*-
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config.from_object('url_shortener.default_config')
app.config.from_envvar('URL_SHORTENER_CONFIGURATION')
db = SQLAlchemy(app)
| # -*- coding: utf-8 -*-
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config.from_object('url_shortener.default_config')
"""
From http://flask-sqlalchemy.pocoo.org/2.1/config/:
"SQLALCHEMY_TRACK_MODIFICATIONS - If set to True, Flask-SQLAlchemy
will track modifications of ... | Set SQLALCHEMY_TRACK_MODIFICATIONS option to False | Set SQLALCHEMY_TRACK_MODIFICATIONS option to False
This commit adds code responsible for setting SQLALCHEMY_TRACK_MODIFICATION
option to False. This option is provided by Flask-SQLAlchemy extension and
relates to event system provided by this extension. This project uses event
system provided by SQLAlchemy library, no... | Python | mit | piotr-rusin/url-shortener,piotr-rusin/url-shortener | ---
+++
@@ -6,5 +6,18 @@
app = Flask(__name__)
app.config.from_object('url_shortener.default_config')
+"""
+From http://flask-sqlalchemy.pocoo.org/2.1/config/:
+
+"SQLALCHEMY_TRACK_MODIFICATIONS - If set to True, Flask-SQLAlchemy
+will track modifications of objects and emit signals. The default is
+None, which e... |
d9f26a1d2831546517aec163a447dcf83cc80701 | decisiontree/tests/urls.py | decisiontree/tests/urls.py | from django.conf.urls import include
from django.contrib import admin
admin.autodiscover()
urlpatterns = [
(r'^admin/', include(admin.site.urls)),
(r'^account/', include('rapidsms.urls.login_logout')),
(r'^scheduler/', include('rapidsms.contrib.scheduler.urls')),
(r'^tree/', include('decisiontree.ur... | from django.conf.urls import include
from django.contrib import admin
admin.autodiscover()
urlpatterns = [
(r'^admin/', include(admin.site.urls)),
(r'^account/', include('rapidsms.urls.login_logout')),
(r'^tree/', include('decisiontree.urls')),
]
| Remove reference to the scheduler, which was removed. | Remove reference to the scheduler, which was removed.
| Python | bsd-3-clause | caktus/rapidsms-decisiontree-app,caktus/rapidsms-decisiontree-app,caktus/rapidsms-decisiontree-app | ---
+++
@@ -8,6 +8,5 @@
urlpatterns = [
(r'^admin/', include(admin.site.urls)),
(r'^account/', include('rapidsms.urls.login_logout')),
- (r'^scheduler/', include('rapidsms.contrib.scheduler.urls')),
(r'^tree/', include('decisiontree.urls')),
] |
61b4f72045ea683a83a358d5d66bd32f7711598b | services/serializers.py | services/serializers.py | from rest_framework import serializers
from .models import Service, Category, ServicePhoto
class CategorySerializer(serializers.ModelSerializer):
class Meta:
model = Category
fields = ('id', 'name', 'photo', 'order')
class ServicePhotoSerializer(serializers.ModelSerializer):
"""
"""
... | from rest_framework import serializers
from .models import Service, Category, ServicePhoto
from semillas_backend.users.serializers import UserSerializer
class CategorySerializer(serializers.ModelSerializer):
class Meta:
model = Category
fields = ('id', 'name', 'photo', 'order')
class ServicePho... | Add user serialized to ServiceSerializer | Add user serialized to ServiceSerializer
| Python | mit | Semillas/semillas_backend,Semillas/semillas_platform,Semillas/semillas_backend,Semillas/semillas_platform,Semillas/semillas_platform,Semillas/semillas_backend,Semillas/semillas_backend,Semillas/semillas_platform | ---
+++
@@ -1,6 +1,7 @@
from rest_framework import serializers
from .models import Service, Category, ServicePhoto
+from semillas_backend.users.serializers import UserSerializer
class CategorySerializer(serializers.ModelSerializer):
@@ -26,6 +27,7 @@
"""
category = CategorySerializer()
photos ... |
b5a43a7fdfc69abfa687d2b31a2add0d52ed5235 | motobot/core_plugins/ctcp.py | motobot/core_plugins/ctcp.py | from motobot import match, Notice, Eat, __VERSION__
from time import strftime, localtime
@match(r'\x01(.+)\x01', priority=Priority.max)
def ctcp_match(bot, context, message, match):
mapping = {
'VERSION': 'MotoBot Version ' + __VERSION__,
'FINGER': 'Oh you dirty man!',
'TIME': strftime('%a... | from motobot import match, Notice, Eat, Priority, __VERSION__
from time import strftime, localtime
@match(r'\x01(.+)\x01', priority=Priority.max)
def ctcp_match(bot, context, message, match):
ctcp_response = {
'VERSION': 'MotoBot Version ' + __VERSION__,
'FINGER': 'Oh you dirty man!',
'TIM... | Fix CTCP import and naming bug | Fix CTCP import and naming bug
| Python | mit | Motoko11/MotoBot | ---
+++
@@ -1,10 +1,10 @@
-from motobot import match, Notice, Eat, __VERSION__
+from motobot import match, Notice, Eat, Priority, __VERSION__
from time import strftime, localtime
@match(r'\x01(.+)\x01', priority=Priority.max)
def ctcp_match(bot, context, message, match):
- mapping = {
+ ctcp_response = {... |
54c46aaafe5b99b4da01911b4133dfaace7f6a43 | _priorityQ.py | _priorityQ.py | import bin_heap as bh
class Priority(object):
"""docstring for priority"""
def __init__(self):
self.bin_heap = bh
def insert(self, item, rank):
bh.push(item, rank)
def pop(self):
item = self.bin_heap.pop()
return item
def peek(self, item):
return item
| import bin_heap as bh
class Priority(object):
"""docstring for priority"""
def __init__(self):
self.bin_heap = bh()
def insert(self, item, rank):
bh.push(item, rank)
def pop(self):
item = self.bin_heap.pop()
return item
def peek(self, item):
return item
| Fix typo; bin_heap will now properly instate | Fix typo; bin_heap will now properly instate
| Python | mit | jwarren116/data-structures | ---
+++
@@ -4,7 +4,7 @@
class Priority(object):
"""docstring for priority"""
def __init__(self):
- self.bin_heap = bh
+ self.bin_heap = bh()
def insert(self, item, rank):
bh.push(item, rank) |
376fcbd76bb2f0de3c738ac66ac5526b6685d18a | plim/extensions.py | plim/extensions.py | from docutils.core import publish_parts
import coffeescript
from scss import Scss
from stylus import Stylus
from .util import as_unicode
def rst_to_html(source):
# This code was taken from http://wiki.python.org/moin/ReStructuredText
# You may also be interested in http://www.tele3.cz/jbar/rest/about.html
... | from docutils.core import publish_parts
import coffeescript
from scss import Scss
from stylus import Stylus
from .util import as_unicode
def rst_to_html(source):
# This code was taken from http://wiki.python.org/moin/ReStructuredText
# You may also be interested in http://www.tele3.cz/jbar/rest/about.html
... | Fix execjs.ProgramError: Error: Cannot find module 'nib' for -stylus | Fix execjs.ProgramError: Error: Cannot find module 'nib' for -stylus
| Python | mit | kxxoling/Plim | ---
+++
@@ -24,5 +24,5 @@
def stylus_to_css(source):
- compiler = Stylus(plugins={'nib':{}})
+ compiler = Stylus()
return as_unicode('<style>{css}</style>').format(css=compiler.compile(source).strip()) |
db1c0183b3d42c611eaefa77f4b3bc4f33cb8267 | django_classified/admin.py | django_classified/admin.py | # -*- coding:utf-8 -*-
from django.contrib import admin
from sorl.thumbnail.admin import AdminImageMixin
from .models import Section, Group, Item, Image, Area
class ImageInline(AdminImageMixin, admin.StackedInline):
model = Image
extra = 5
class ItemAdmin(admin.ModelAdmin):
prepopulated_fields = {'slu... | # -*- coding:utf-8 -*-
from django.contrib import admin
from sorl.thumbnail.admin import AdminImageMixin
from .models import Section, Group, Item, Image, Area
class ImageInline(AdminImageMixin, admin.StackedInline):
model = Image
extra = 5
class ItemAdmin(admin.ModelAdmin):
prepopulated_fields = {'slu... | Allow to search items by description. | Allow to search items by description.
| Python | mit | inoks/dcf,inoks/dcf | ---
+++
@@ -14,7 +14,7 @@
prepopulated_fields = {'slug': ('title',), }
list_display = ('title', 'group', 'area', 'user', 'is_active', 'posted', 'updated')
list_filter = ('area', 'group', 'is_active', 'posted',)
- search_fields = ('title', 'user__email')
+ search_fields = ('title', 'description', ... |
33448ac669e192143655560dd52299e7069585ac | django_token/middleware.py | django_token/middleware.py | from django import http
from django.contrib import auth
from django.core import exceptions
class TokenMiddleware(object):
"""
Middleware that authenticates against a token in the http authorization
header.
"""
get_response = None
def __init__(self, get_response=None):
sel... | from django import http
from django.contrib import auth
from django.core import exceptions
class TokenMiddleware(object):
"""
Middleware that authenticates against a token in the http authorization
header.
"""
get_response = None
def __init__(self, get_response=None):
sel... | Fix for byte literals compatibility. | Fix for byte literals compatibility.
| Python | mit | jasonbeverage/django-token | ---
+++
@@ -23,10 +23,9 @@
return self.get_response(request)
def process_request(self, request):
- auth_header = request.META.get('HTTP_AUTHORIZATION', b'')
- auth_header = auth_header.partition(b' ')
+ auth_header = str(request.META.get('HTTP_AUTHORIZATION', '')).partition(' ')
... |
b929573e051f84ecc15020889fde6f6d798daa18 | pmxbot/__init__.py | pmxbot/__init__.py | # -*- coding: utf-8 -*-
# vim:ts=4:sw=4:noexpandtab
from __future__ import absolute_import
import socket
import logging
from .dictlib import ConfigDict
config = ConfigDict(
bot_nickname = 'pmxbot',
database = 'sqlite:pmxbot.sqlite',
server_host = 'localhost',
server_port = 6667,
use_ssl = False,
password = No... | # -*- coding: utf-8 -*-
# vim:ts=4:sw=4:noexpandtab
from __future__ import absolute_import
import socket
import logging as _logging
from .dictlib import ConfigDict
config = ConfigDict(
bot_nickname = 'pmxbot',
database = 'sqlite:pmxbot.sqlite',
server_host = 'localhost',
server_port = 6667,
use_ssl = False,
p... | Fix issue with conflated pmxbot.logging | Fix issue with conflated pmxbot.logging
| Python | mit | yougov/pmxbot,yougov/pmxbot,yougov/pmxbot | ---
+++
@@ -4,7 +4,7 @@
from __future__ import absolute_import
import socket
-import logging
+import logging as _logging
from .dictlib import ConfigDict
@@ -30,6 +30,6 @@
librarypaste = 'http://paste.jaraco.com',
)
config['logs URL'] = 'http://' + socket.getfqdn()
-config['log level'] = logging.INFO
+con... |
108c11d5187f7ec4647351c924df8cd881020b8a | falmer/matte/views.py | falmer/matte/views.py | from rest_framework import views, serializers
from rest_framework.decorators import permission_classes
from rest_framework.parsers import FileUploadParser
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from falmer.content.serializers import WagtailImageSerializer
fr... | from rest_framework import views, serializers
from rest_framework.decorators import permission_classes
from rest_framework.parsers import FileUploadParser
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from falmer.content.serializers import WagtailImageSerializer
fr... | Return error for image upload | Return error for image upload
| Python | mit | sussexstudent/falmer,sussexstudent/falmer,sussexstudent/falmer,sussexstudent/falmer | ---
+++
@@ -37,3 +37,9 @@
'ok': True,
'data': WagtailImageSerializer(instance=image).data
}, status=200)
+ else:
+ print('file upload issue', image.errors)
+ return Response({
+ 'ok': False,
+ 'errors': image.err... |
17cc0e9ab4f32e74c9a03124e38628c0f6640f40 | nodeconductor/quotas/serializers.py | nodeconductor/quotas/serializers.py | from rest_framework import serializers
from nodeconductor.quotas import models, utils
from nodeconductor.core.serializers import GenericRelatedField
class QuotaSerializer(serializers.HyperlinkedModelSerializer):
scope = GenericRelatedField(related_models=utils.get_models_with_quotas(), read_only=True)
class... | from rest_framework import serializers
from nodeconductor.quotas import models, utils
from nodeconductor.core.serializers import GenericRelatedField
class QuotaSerializer(serializers.HyperlinkedModelSerializer):
scope = GenericRelatedField(related_models=utils.get_models_with_quotas(), read_only=True)
class... | Make quota usage read only (nc-263) | Make quota usage read only (nc-263)
| Python | mit | opennode/nodeconductor,opennode/nodeconductor,opennode/nodeconductor | ---
+++
@@ -10,7 +10,7 @@
class Meta(object):
model = models.Quota
fields = ('url', 'uuid', 'name', 'limit', 'usage', 'scope')
- read_only_fields = ('uuid', 'name')
+ read_only_fields = ('uuid', 'name', 'scope', 'usage')
lookup_field = 'uuid'
# TODO: cleanup after ... |
2e9b87a7409f1995f96867270361f23a9fc3d1ab | flaskext/clevercss.py | flaskext/clevercss.py | # -*- coding: utf-8 -*-
"""
flaskext.clevercss
~~~~~~~~~~~~~
A small Flask extension that makes it easy to use cleverCSS with your Flask
application.
:copyright: (c) 2010 by Steve Losh.
:copyright: (c) 2011 by Sujan Shakya.
:license: MIT, see LICENSE for more details.
"""
import os
import... | # -*- coding: utf-8 -*-
"""
flaskext.clevercss
~~~~~~~~~~~~~
A small Flask extension that makes it easy to use cleverCSS with your Flask
application.
:copyright: (c) 2010 by Steve Losh.
:copyright: (c) 2011 by Sujan Shakya.
:license: MIT, see LICENSE for more details.
"""
import os
import... | Fix for specifying the static directory in later versions of flask | Fix for specifying the static directory in later versions of flask | Python | mit | suzanshakya/flask-clevercss,suzanshakya/flask-clevercss | ---
+++
@@ -18,7 +18,7 @@
def clevercss(app):
@app.before_request
def _render_clever_css():
- static_dir = app.root_path + app.static_path
+ static_dir = os.path.join(app.root_path, app._static_folder)
clever_paths = []
for path, subdirs, filenames in os.walk(static_dir): |
ac31a10d00508ddd354d9c30055d2955b306d516 | duct/protocol/sflow/protocol/utils.py | duct/protocol/sflow/protocol/utils.py | import struct, socket
def unpack_address(u):
addrtype = u.unpack_uint()
if self.addrtype == 1:
self.address = u.unpack_fopaque(4)
if self.addrtype == 2:
self.address = u.unpack_fopaque(16)
return self.address
class IPv4Address(object):
def __init__(self, addr_int):
... | import struct, socket
def unpack_address(u):
addrtype = u.unpack_uint()
if addrtype == 1:
address = u.unpack_fopaque(4)
if addrtype == 2:
address = u.unpack_fopaque(16)
return address
class IPv4Address(object):
def __init__(self, addr_int):
self.addr_int = addr_int
... | Fix bad transposition of utility function in sflow | Fix bad transposition of utility function in sflow
| Python | mit | ducted/duct,ducted/duct,ducted/duct,ducted/duct | ---
+++
@@ -4,13 +4,13 @@
def unpack_address(u):
addrtype = u.unpack_uint()
- if self.addrtype == 1:
- self.address = u.unpack_fopaque(4)
+ if addrtype == 1:
+ address = u.unpack_fopaque(4)
- if self.addrtype == 2:
- self.address = u.unpack_fopaque(16)
+ if addrtype == 2:
+ ... |
2045856aa66cef7b81d9e617fd29fc9ca19276d7 | pwned/src/pwned.py | pwned/src/pwned.py | import hashlib, sys, urllib.request
def main():
hash = hashlib.sha1(bytes(sys.argv[1], "utf-8"))
digest = hash.hexdigest().upper()
url = f"https://api.pwnedpasswords.com/range/{digest[:5]}"
request = urllib.request.Request(url, headers={"User-Agent":"API-Programming-Exercise"})
page = urllib.request.urlopen(requ... | import hashlib, sys, urllib.request
def main():
hash = hashlib.sha1(bytes(sys.argv[1], "utf-8"))
digest = hash.hexdigest().upper()
url = f"https://api.pwnedpasswords.com/range/{digest[:5]}"
request = urllib.request.Request(url, headers={"User-Agent":"API-Programming-Exercise"})
page = urllib.request.urlopen(requ... | Add output when password is not found | Add output when password is not found | Python | agpl-3.0 | 0x424D/crappy,0x424D/crappy | ---
+++
@@ -15,6 +15,8 @@
if digest[:5] + tmp[0] == digest:
print(f"{sys.argv[1]} was found")
print(f"Hash {digest}, {tmp[1]} occurrences")
+ else:
+ print(f"Password {sys.argv[1]} was not found")
if __name__ == "__main__":
main() |
9fb302a4e8d5d69fa4c9727c72f7953f26d1f13f | SyncOnSave.py | SyncOnSave.py | import sublime, sublime_plugin
import subprocess
import threading
DEBUG = False
# Base rsync command template: rsync -arv <local> <remote>
base_cmd = "rsync -arv {0} {1}"
class SyncOnSaveCommand(sublime_plugin.EventListener):
def on_post_save(self, view):
""" Sync directory containing the current directo... | from __future__ import print_function
import sublime, sublime_plugin
import subprocess
import threading
DEBUG = False
# Base rsync command template: rsync -arv <local> <remote>
base_cmd = "rsync -arv {0} {1}"
class SyncOnSaveCommand(sublime_plugin.EventListener):
def on_post_save(self, view):
""" Sync d... | Add Sublime Text 3 support | Add Sublime Text 3 support
| Python | mit | aldld/SyncOnSave | ---
+++
@@ -1,3 +1,5 @@
+from __future__ import print_function
+
import sublime, sublime_plugin
import subprocess
import threading
@@ -21,7 +23,7 @@
cmd = base_cmd.format(synced_dir, remote)
if DEBUG:
- print cmd
+ print(cmd)
... |
34c38e0cfe5e880e678704c4d473f082787fca64 | rest_framework/authtoken/management/commands/drf_create_token.py | rest_framework/authtoken/management/commands/drf_create_token.py | from django.contrib.auth import get_user_model
from django.core.management.base import BaseCommand
from rest_framework.authtoken.models import Token
UserModel = get_user_model()
class Command(BaseCommand):
help = 'Create DRF Token for a given user'
def create_user_token(self, username):
user = User... | from django.contrib.auth import get_user_model
from django.core.management.base import BaseCommand, CommandError
from rest_framework.authtoken.models import Token
UserModel = get_user_model()
class Command(BaseCommand):
help = 'Create DRF Token for a given user'
def create_user_token(self, username):
... | Use self.sdtout and CommandError to print output | Use self.sdtout and CommandError to print output
| Python | bsd-2-clause | dmwyatt/django-rest-framework,ossanna16/django-rest-framework,jpadilla/django-rest-framework,tomchristie/django-rest-framework,jpadilla/django-rest-framework,kgeorgy/django-rest-framework,kgeorgy/django-rest-framework,tomchristie/django-rest-framework,tomchristie/django-rest-framework,ossanna16/django-rest-framework,jp... | ---
+++
@@ -1,5 +1,5 @@
from django.contrib.auth import get_user_model
-from django.core.management.base import BaseCommand
+from django.core.management.base import BaseCommand, CommandError
from rest_framework.authtoken.models import Token
@@ -23,7 +23,9 @@
try:
token = self.create_user_t... |
f7f3907da8ec31cafaec3d7e82755cfa344ed60e | performance/web.py | performance/web.py | class Request:
GET = 'get'
POST = 'post'
def __init__(self, url, type, data=None):
self.url = url
self.type = type
self.data = data
class RequestData:
def __init__(self, data=None):
self.data = data
def for_type(self, type=Request.GET):
if type is Request.... | import requests
from time import time
class Client:
def __init__(self):
pass
class Request:
GET = 'get'
POST = 'post'
def __init__(self, url, type, data=None):
self.url = url
self.type = type
self.data = data
def do(self):
try:
data = ''
... | Create Error-classes, Client class and do function for Request | Create Error-classes, Client class and do function for Request
| Python | mit | BakeCode/performance-testing,BakeCode/performance-testing | ---
+++
@@ -1,3 +1,12 @@
+import requests
+from time import time
+
+
+class Client:
+ def __init__(self):
+ pass
+
+
class Request:
GET = 'get'
POST = 'post'
@@ -7,6 +16,27 @@
self.type = type
self.data = data
+ def do(self):
+ try:
+ data = ''
+ ... |
112d12aa4622b77a55f0f90b6c0cb7c3ac3d407e | CommandException.py | CommandException.py | class CommandException(Exception):
"""
This custom exception can be thrown by commands when something goes wrong during execution.
The parameter is a message sent to the source that called the command (a channel or a user)
"""
def __init__(self, displayMessage=None, shouldLogError=True):
"""
Create a new Comm... | class CommandException(Exception):
"""
This custom exception can be thrown by commands when something goes wrong during execution.
The parameter is a message sent to the source that called the command (a channel or a user)
"""
def __init__(self, displayMessage=None, shouldLogError=True):
"""
Create a new Comm... | Fix wrong class in 'super()' call | Fix wrong class in 'super()' call
Oops
| Python | mit | Didero/DideRobot | ---
+++
@@ -28,4 +28,4 @@
Create a new InputException. The display message will be shown to the user
:param displayMessage: The message to show to the user that called the command. This message should explain how the input should be correctly formatted
"""
- super(CommandException, self).__init__(displayMes... |
7c6a128b707db738d0a89c2897b35ed7d783ade0 | plugins/basic_info_plugin.py | plugins/basic_info_plugin.py | import string
import textwrap
from veryprettytable import VeryPrettyTable
from plugins import BasePlugin
__author__ = 'peter'
class BasicInfoPlugin(BasePlugin):
name = 'BasicInfoPlugin'
short_description = 'Basic info:'
default = True
description = textwrap.dedent('''
This plugin provides some ba... | import string
import textwrap
from veryprettytable import VeryPrettyTable
from plugins import BasePlugin
__author__ = 'peter'
class BasicInfoPlugin(BasePlugin):
name = 'BasicInfoPlugin'
short_description = 'Basic info:'
default = True
description = textwrap.dedent('''
This plugin provides some ba... | Add punctuation to basic info | Add punctuation to basic info
| Python | mit | Sakartu/stringinfo | ---
+++
@@ -22,9 +22,9 @@
if len(self.args['STRING']) > 1:
result += '{0}:\n'.format(s)
table = VeryPrettyTable()
- table.field_names = ['Length', '# Digits', '# Alpha', '# unprintable']
+ table.field_names = ['Length', '# Digits', '# Alpha', '# Punct.'... |
c1f63f381b167d6bfe701a36e998727cf4ed3bec | client/software/resources/modules/hardware_auto_find.py | client/software/resources/modules/hardware_auto_find.py | #I got this code on http://stackoverflow.com/questions/12090503/listing-available-com-ports-with-python
#So, yeah. I didn't wrote this code :-P
import sys
import glob
import serial
def serial_ports():
""" Lists serial port names
:raises EnvironmentError:
On unsupported or unknown platforms
:returns:
A list... | #I got this code on http://stackoverflow.com/questions/12090503/listing-available-com-ports-with-python
#So, yeah. I didn't wrote this code :-P
import sys
import glob
import serial
def serial_ports():
""" Lists serial port names
:raises EnvironmentError:
On unsupported or unknown platforms
:returns:
A list... | Make hardware search only on USB on Ubuntu Linux | Make hardware search only on USB on Ubuntu Linux
| Python | mit | MU-Software/Project_Musica_for_Contest | ---
+++
@@ -16,7 +16,8 @@
ports = ['COM%s' % (i + 1) for i in range(256)]
elif sys.platform.startswith('linux') or sys.platform.startswith('cygwin'):
# this excludes your current terminal "/dev/tty"
- ports = glob.glob('/dev/tty[A-Za-z]*')
+ # ports = glob.glob('/dev/tty[A-Za-z]*')
+ ports = glob.glob('/de... |
171144db2109e4bbe357b44ca37ad5578e1c3996 | config.py | config.py | FFMPEG_PATH = '/usr/local/bin/ffmpeg'
VIDEO_CODEC = 'h264' # used with ffprobe to detect whether or not we need to encode
VIDEO_ENCODER = 'h264_omx'
AUDIO_CODEC = 'aac' # used with ffprobe to detect whether or not we need to encode
AUDIO_ENCODER = 'aac'
BITRATE = '2500k'
INPUT_EXTS = ['.mkv']
OUTPUT_EXT = '.mp4'
| FFMPEG_PATH = '/usr/local/bin/ffmpeg'
VIDEO_CODEC = 'h264' # used with ffprobe to detect whether or not we need to encode
VIDEO_ENCODER = 'h264_omx'
AUDIO_CODEC = 'aac' # used with ffprobe to detect whether or not we need to encode
AUDIO_ENCODER = 'aac'
BITRATE = '2500k'
INPUT_EXTS = ['.mkv', '.mp4']
OUTPUT_EXT = '... | Add mp4 as input ext | Add mp4 as input ext
| Python | mit | danielbreves/auto_encoder | ---
+++
@@ -8,5 +8,5 @@
BITRATE = '2500k'
-INPUT_EXTS = ['.mkv']
+INPUT_EXTS = ['.mkv', '.mp4']
OUTPUT_EXT = '.mp4' |
1bd344a3ccda43f4ac1d4b94b1a18fc816c9b6ae | slurmscale/jobs/jobs.py | slurmscale/jobs/jobs.py | """Get info about jobs running on this cluster."""
import pyslurm
from job import Job
class Jobs(object):
"""A service object to inspect jobs."""
@property
def _jobs(self):
"""Fetch fresh data."""
return pyslurm.job().get()
def list(self):
"""List the current jobs on the clu... | """Get info about jobs running on this cluster."""
import pyslurm
from job import Job
class Jobs(object):
"""A service object to inspect jobs."""
@property
def _jobs(self):
"""Fetch fresh data."""
return pyslurm.job().get()
def list(self, states=None):
"""
List the c... | Add ability to filter job list by job state | Add ability to filter job list by job state
| Python | mit | afgane/slurmscale,afgane/slurmscale | ---
+++
@@ -12,7 +12,26 @@
"""Fetch fresh data."""
return pyslurm.job().get()
- def list(self):
- """List the current jobs on the cluster."""
+ def list(self, states=None):
+ """
+ List the current jobs on the cluster.
+
+ :type states: List of ``str``
+ :p... |
d3f73b55dc68ec18fb5f4c43dcff59f3766d752f | mica/starcheck/__init__.py | mica/starcheck/__init__.py | from .starcheck import get_starcheck_catalog, main, get_mp_dir
| from .starcheck import get_starcheck_catalog, get_starcheck_catalog_at_date, main, get_mp_dir
| Add get_starcheck_catalog_at_date to top level items in mica.starcheck | Add get_starcheck_catalog_at_date to top level items in mica.starcheck
| Python | bsd-3-clause | sot/mica,sot/mica | ---
+++
@@ -1 +1 @@
-from .starcheck import get_starcheck_catalog, main, get_mp_dir
+from .starcheck import get_starcheck_catalog, get_starcheck_catalog_at_date, main, get_mp_dir |
20d1cd153d54f2eab88197c76c201ed5e7814536 | modules/urbandictionary.py | modules/urbandictionary.py | """Looks up a term from urban dictionary
@package ppbot
@syntax ud <word>
"""
import requests
import json
from modules import *
class Urbandictionary(Module):
def __init__(self, *args, **kwargs):
"""Constructor"""
Module.__init__(self, kwargs=kwargs)
self.url = "http://www.urbandictiona... | """Looks up a term from urban dictionary
@package ppbot
@syntax ud <word>
"""
import requests
import json
from modules import *
class Urbandictionary(Module):
def __init__(self, *args, **kwargs):
"""Constructor"""
Module.__init__(self, kwargs=kwargs)
self.url = "http://www.urbandictiona... | Fix another exception for ud when def isn't found | Fix another exception for ud when def isn't found
| Python | mit | billyvg/piebot | ---
+++
@@ -35,7 +35,7 @@
definition['example'] = definition['example'].replace("\r", " ").replace("\n", " ")
message = "%(word)s (%(thumbs_up)d/%(thumbs_down)d): %(definition)s (ex: %(example)s)" % (definition)
self.msg(event['target'], message[:450])
- e... |
137b834f166eea13781311b1f050f0eaf2e1d610 | podcasts/management/commands/updatepodcasts.py | podcasts/management/commands/updatepodcasts.py | from django.core.management import BaseCommand
from podcasts.models import Podcast
class Command(BaseCommand):
help = 'Initialize podcasts with data from their RSS feeds'
def handle(self, *args, **kwargs):
for podcast in Podcast.objects.all():
podcast.update()
| from django.core.management import BaseCommand
from optparse import make_option
from podcasts.models import Podcast
class Command(BaseCommand):
help = 'Initialize podcasts with data from their RSS feeds'
option_list = BaseCommand.option_list + (
make_option(
'--only-new',
actio... | Make it optional to only update metadata of new podcasts | Make it optional to only update metadata of new podcasts
| Python | mit | matachi/sputnik,matachi/sputnik,matachi/sputnik,matachi/sputnik | ---
+++
@@ -1,10 +1,22 @@
from django.core.management import BaseCommand
+from optparse import make_option
from podcasts.models import Podcast
class Command(BaseCommand):
help = 'Initialize podcasts with data from their RSS feeds'
+ option_list = BaseCommand.option_list + (
+ make_option(
+ ... |
06122b26a944455576b41501cae6fb73af1bf901 | post/tests/urls.py | post/tests/urls.py | from django.conf.urls import patterns, include
urlpatterns = patterns(
(r'^jmbo/', include('jmbo.urls')),
(r'^comments/', include('django.contrib.comments.urls')),
(r'^post/', include('post.urls')),
)
| from django.conf.urls import patterns, include
urlpatterns = patterns(
'',
(r'^jmbo/', include('jmbo.urls')),
(r'^comments/', include('django.contrib.comments.urls')),
(r'^post/', include('post.urls')),
)
| Use correct url pattern format | Use correct url pattern format
| Python | bsd-3-clause | praekelt/jmbo-post,praekelt/jmbo-post | ---
+++
@@ -2,6 +2,7 @@
urlpatterns = patterns(
+ '',
(r'^jmbo/', include('jmbo.urls')),
(r'^comments/', include('django.contrib.comments.urls')),
(r'^post/', include('post.urls')), |
aee157ce27aa4f00a798b87e07583dc795265eb4 | methodAndKnottiness/reliability.py | methodAndKnottiness/reliability.py | import sys
count = 0
for line in sys.stdin:
if count == 0:
B = int(line)
elif count == 1:
N = int(line)
else:
c, r = line.rstrip().split(' ')
cost = int(c)
reliability = float(r)
count+=1
print("Fin")
| import sys, math
count = 0
cost=[]
reliability=[]
# Read input. Budget, number of machines, cost and reliability
for line in sys.stdin:
if count == 0:
B = int(line)
elif count == 1:
N = int(line)
else:
c, r = line.rstrip().split(' ')
cost.append(int(c))
reliability.... | Save point, got code written but need to figure out the base probabilities | Save point, got code written but need to figure out the base probabilities
| Python | mit | scrasmussen/ProsaicOeuvre,scrasmussen/ProsaicOeuvre,scrasmussen/ProsaicOeuvre | ---
+++
@@ -1,6 +1,10 @@
-import sys
+import sys, math
count = 0
+cost=[]
+reliability=[]
+
+# Read input. Budget, number of machines, cost and reliability
for line in sys.stdin:
if count == 0:
B = int(line)
@@ -8,10 +12,31 @@
N = int(line)
else:
c, r = line.rstrip().split(' '... |
56ff6b21e9530edf823a9ff178b4b24702df4ace | badgus/urls.py | badgus/urls.py | from django.conf import settings
from django.conf.urls.defaults import *
from .profiles import urls as profiles_urls
from django.views.generic.simple import direct_to_template
from django.contrib import admin
admin.autodiscover()
import badger
badger.autodiscover()
from funfactory import monkeypatches
monkeypatche... | from django.conf import settings
from django.conf.urls.defaults import *
from .profiles import urls as profiles_urls
from django.views.generic.simple import direct_to_template
from funfactory import monkeypatches
monkeypatches.patch()
import badger
badger.autodiscover()
from django.contrib import admin
admin.autod... | Change the monkey patching order | Change the monkey patching order
| Python | bsd-3-clause | lmorchard/badg.us,deepankverma/badges.mozilla.org,mozilla/badges.mozilla.org,lmorchard/badg.us,deepankverma/badges.mozilla.org,lmorchard/badg.us,mozilla/badg.us,mozilla/badges.mozilla.org,mozilla/badg.us,mozilla/badges.mozilla.org,lmorchard/badg.us,mozilla/badg.us,deepankverma/badges.mozilla.org,deepankverma/badges.moz... | ---
+++
@@ -5,14 +5,14 @@
from django.views.generic.simple import direct_to_template
-from django.contrib import admin
-admin.autodiscover()
+from funfactory import monkeypatches
+monkeypatches.patch()
import badger
badger.autodiscover()
-from funfactory import monkeypatches
-monkeypatches.patch()
+from dj... |
a6dd8aee6a3b6272372532a19fba3d830d40612a | neo/test/io/test_axonio.py | neo/test/io/test_axonio.py | # encoding: utf-8
"""
Tests of io.axonio
"""
try:
import unittest2 as unittest
except ImportError:
import unittest
from neo.io import AxonIO
from neo.test.io.common_io_test import BaseTestIO
class TestAxonIO(BaseTestIO, unittest.TestCase):
files_to_test = ['File_axon_1.abf',
'File_a... | # encoding: utf-8
"""
Tests of io.axonio
"""
try:
import unittest2 as unittest
except ImportError:
import unittest
from neo.io import AxonIO
from neo.test.io.common_io_test import BaseTestIO
class TestAxonIO(BaseTestIO, unittest.TestCase):
files_to_test = ['File_axon_1.abf',
'File_a... | Test with file from Jackub | Test with file from Jackub
git-svn-id: 0eea5547755d67006ec5687992a7464f0ad96b59@379 acbc63fc-6c75-0410-9d68-8fa99cba188a
| Python | bsd-3-clause | SummitKwan/python-neo,mschmidt87/python-neo,rgerkin/python-neo,jakobj/python-neo,CINPLA/python-neo,apdavison/python-neo,theunissenlab/python-neo,samuelgarcia/python-neo,guangxingli/python-neo,mgr0dzicki/python-neo,JuliaSprenger/python-neo,NeuralEnsemble/python-neo,npyoung/python-neo,INM-6/python-neo,tclose/python-neo,t... | ---
+++
@@ -16,7 +16,12 @@
files_to_test = ['File_axon_1.abf',
'File_axon_2.abf',
'File_axon_3.abf',
- 'File_axon_4.abf',]
+ 'File_axon_4.abf',
+ 'File_axon_5.abf',
+ 'File_axon_6.abf',
+ ... |
99a1ce2ecee6dd761113515da5c89b8c7da5537f | Python/Algorithm.py | Python/Algorithm.py | class Algorithm:
"""
Algorithm Class
Base class for the page substitution algorithms.
"""
def __init__(self, input = []):
"""
Algorithm Constructor.
Parameters
----------
input : list
A list containing the the input page swap.
"""
if not input: #If the list is empty throw an exception.
raise... | class Algorithm:
"""
Algorithm Class
Base class for the page substitution algorithms.
"""
def __init__(self, input = []):
"""
Algorithm Constructor.
Parameters
----------
input : list
A list containing the the input page swap.
"""
if not input: #If the list is empty throw an exception.
raise... | Fix logic error under preparePageFrames | Fix logic error under preparePageFrames
| Python | mit | caiomcg/OS-PageSubstitution | ---
+++
@@ -43,6 +43,14 @@
list
The list with initialized Page frames
"""
- pageFrame = [self.pages[x] for x in range(0, self.blocks)] #Create the page frame with elements passed by the user.
- self.removeChuncks(self.pages, 0, self.blocks) #Remove part of the list that is on the page frame
+ pageFrame =... |
81cf4bc40fd23ba8e93b0e4bc96eff8e866c014b | redis_commands/parse.py | redis_commands/parse.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
import lxml.etree, lxml.html
import re
url = "http://redis.io"
output = "output.txt"
f = open(output, "w");
tree = lxml.html.parse("download/raw.dat").getroot()
commands = tree.find_class("command")
data = {}
for command in commands:
for row in command.findall('a'):
... | #!/usr/bin/python
# -*- coding: utf-8 -*-
import lxml.etree, lxml.html
import re
url = "http://redis.io"
output = "output.txt"
f = open(output, "w");
tree = lxml.html.parse("download/raw.dat").getroot()
commands = tree.find_class("command")
data = {}
for command in commands:
for row in command.findall('a'):
... | Remove double slashes in the Redis commands urls | Remove double slashes in the Redis commands urls
| Python | apache-2.0 | souravbadami/zeroclickinfo-fathead,p12tic/zeroclickinfo-fathead,samskeller/zeroclickinfo-fathead,rasikapohankar/zeroclickinfo-fathead,thinker3197/zeroclickinfo-fathead,thinker3197/zeroclickinfo-fathead,souravbadami/zeroclickinfo-fathead,rasikapohankar/zeroclickinfo-fathead,p12tic/zeroclickinfo-fathead,nikhilsingh291/ze... | ---
+++
@@ -17,7 +17,7 @@
for command in commands:
for row in command.findall('a'):
- command_url = "%s/%s" % (url, row.get('href'))
+ command_url = "%s%s" % (url, row.get('href'))
for sibling in command.itersiblings():
usage = "" |
b499cf14eeb3d793a06d74c5eb2f581d49a9926e | jupyter_kernel/magics/python_magic.py | jupyter_kernel/magics/python_magic.py | # Copyright (c) Calico Development Team.
# Distributed under the terms of the Modified BSD License.
# http://calicoproject.org/
from jupyter_kernel import Magic, option
class PythonMagic(Magic):
env = {}
def line_python(self, *args):
"""%python CODE - evaluate code as Python"""
code = " ".joi... | # Copyright (c) Calico Development Team.
# Distributed under the terms of the Modified BSD License.
# http://calicoproject.org/
from jupyter_kernel import Magic, option
class PythonMagic(Magic):
env = {}
def line_python(self, *args):
"""%python CODE - evaluate code as Python"""
code = " ".joi... | Use Python2/3 compatible form of exec | Use Python2/3 compatible form of exec
| Python | bsd-3-clause | Calysto/metakernel | ---
+++
@@ -17,7 +17,7 @@
return eval(code.strip(), self.env)
except:
try:
- exec code.strip() in self.env
+ exec(code.strip(), self.env)
except Exception as exc:
return "Error: " + str(exc)
if "retval" in self.env... |
01b9d47976dd68a3fe9ae2656e423a03edb5187d | examples/source.py | examples/source.py | """Test client that connects and sends infinite data."""
import sys
from tulip import *
def dprint(*args):
print('source:', *args, file=sys.stderr)
class Client(Protocol):
data = b'x'*16*1024
def connection_made(self, tr):
dprint('connecting to', tr.get_extra_info('addr'))
self.tr ... | """Test client that connects and sends infinite data."""
import sys
from tulip import *
def dprint(*args):
print('source:', *args, file=sys.stderr)
class Client(Protocol):
data = b'x'*16*1024
def connection_made(self, tr):
dprint('connecting to', tr.get_extra_info('addr'))
self.tr ... | Fix logic around lost connection. | Fix logic around lost connection.
| Python | apache-2.0 | leetreveil/tulip,overcastcloud/trollius,leetreveil/tulip,overcastcloud/trollius,leetreveil/tulip,overcastcloud/trollius | ---
+++
@@ -20,10 +20,12 @@
self.write_some_data()
def write_some_data(self):
+ if self.lost:
+ dprint('lost already')
+ return
dprint('writing', len(self.data), 'bytes')
self.tr.write(self.data)
- if not self.lost:
- self.loop.call_soon... |
9ce7de86b7d9c1e9288fa5c09f97414516cabc63 | corehq/apps/reports/filters/urls.py | corehq/apps/reports/filters/urls.py | from django.conf.urls import url
from .api import (
EmwfOptionsView,
CaseListFilterOptions,
DeviceLogUsers,
DeviceLogIds,
MobileWorkersOptionsView,
ReassignCaseOptions,
)
from .location import LocationGroupFilterOptions
urlpatterns = [
url(r'^emwf_options/$', EmwfOptionsView.as_view(), name... | from django.conf.urls import url
from .api import (
EmwfOptionsView,
CaseListFilterOptions,
DeviceLogUsers,
DeviceLogIds,
MobileWorkersOptionsView,
ReassignCaseOptions,
)
from .location import LocationGroupFilterOptions
urlpatterns = [
url(r'^emwf_options/$', EmwfOptionsView.as_view(), nam... | Fix bad merge and formatting | Fix bad merge and formatting
| Python | bsd-3-clause | dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq | ---
+++
@@ -11,14 +11,13 @@
from .location import LocationGroupFilterOptions
urlpatterns = [
- url(r'^emwf_options/$', EmwfOptionsView.as_view(), name='emwf_options'),
- url(r'^users_options/$', MobileWorkersOptionsView.as_view(), name=MobileWorkersOptionsView.urlname),
- url(r'^new_emwf_options/$', Locatio... |
7186faebdb22f4aacffb2e0603fe6918f6b89ee7 | rrd_data_source.py | rrd_data_source.py | class RRDDataSource(object):
name = ""
data_source_type = ""
heartbeat = ""
temp_value = 0
def __init__(self, name, data_source_type, heartbeat):
self.name = name
self.data_source_type = data_source_type
self.heartbeat = heartbeat
| class RRDDataSource(object):
name = ""
data_source_type = ""
heartbeat = ""
temp_value = 0
def __init__(self, name, data_source_type, heartbeat, temp_value=None):
self.name = name
self.data_source_type = data_source_type
self.heartbeat = heartbeat
self.temp_value = t... | Add temp_value (optional) parameter to RRDDataSource constructor. | Add temp_value (optional) parameter to RRDDataSource constructor.
| Python | mit | netgroup/OSHI-monitoring,StefanoSalsano/OSHI-monitoring,ferrarimarco/OSHI-monitoring,StefanoSalsano/OSHI-monitoring,netgroup/OSHI-monitoring,ferrarimarco/OSHI-monitoring | ---
+++
@@ -4,7 +4,8 @@
heartbeat = ""
temp_value = 0
- def __init__(self, name, data_source_type, heartbeat):
+ def __init__(self, name, data_source_type, heartbeat, temp_value=None):
self.name = name
self.data_source_type = data_source_type
self.heartbeat = heartbeat
+ ... |
ff65a3e1b0f061100a20462dea4f654b02707a6f | fig/cli/command.py | fig/cli/command.py | from docker import Client
import logging
import os
import re
import yaml
from ..project import Project
from .docopt_command import DocoptCommand
from .formatter import Formatter
from .utils import cached_property
log = logging.getLogger(__name__)
class Command(DocoptCommand):
@cached_property
def client(self... | from docker import Client
import logging
import os
import re
import yaml
import socket
from ..project import Project
from .docopt_command import DocoptCommand
from .formatter import Formatter
from .utils import cached_property
from .errors import UserError
log = logging.getLogger(__name__)
class Command(DocoptComman... | Check default socket and localhost:4243 for Docker daemon | Check default socket and localhost:4243 for Docker daemon
| Python | apache-2.0 | MSakamaki/compose,alexisbellido/docker.github.io,prologic/compose,KevinGreene/compose,phiroict/docker,calou/compose,rillig/docker.github.io,docker/docker.github.io,phiroict/docker,vlajos/compose,ekristen/compose,JimGalasyn/docker.github.io,albers/compose,zhangspook/compose,charleswhchan/compose,talolard/compose,nhumric... | ---
+++
@@ -3,11 +3,13 @@
import os
import re
import yaml
+import socket
from ..project import Project
from .docopt_command import DocoptCommand
from .formatter import Formatter
from .utils import cached_property
+from .errors import UserError
log = logging.getLogger(__name__)
@@ -16,8 +18,26 @@
de... |
036a89ce97d8160fe6b4cb10a95f3cf9e8a855ff | Lib/test/test_openpty.py | Lib/test/test_openpty.py | # Test to see if openpty works. (But don't worry if it isn't available.)
import os
from test.test_support import verbose, TestFailed, TestSkipped
try:
if verbose:
print "Calling os.openpty()"
master, slave = os.openpty()
if verbose:
print "(master, slave) = (%d, %d)"%(master, slave)
except... | # Test to see if openpty works. (But don't worry if it isn't available.)
import os
from test.test_support import verbose, TestFailed, TestSkipped
try:
if verbose:
print "Calling os.openpty()"
master, slave = os.openpty()
if verbose:
print "(master, slave) = (%d, %d)"%(master, slave)
except... | Remove bogus test; the master is not a terminal on Solaris and HP-UX. | Remove bogus test; the master is not a terminal on Solaris and HP-UX.
| Python | mit | sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator | ---
+++
@@ -12,8 +12,6 @@
except AttributeError:
raise TestSkipped, "No openpty() available."
-if not os.isatty(master):
- raise TestFailed, "Master-end of pty is not a terminal."
if not os.isatty(slave):
raise TestFailed, "Slave-end of pty is not a terminal."
|
301f22b9b2de2a27dd2e3faa27ccb9c70266e938 | pybossa/api/project_stats.py | pybossa/api/project_stats.py | # -*- coding: utf8 -*-
# This file is part of PYBOSSA.
#
# Copyright (C) 2015 Scifabric LTD.
#
# PYBOSSA is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your op... | # -*- coding: utf8 -*-
# This file is part of PYBOSSA.
#
# Copyright (C) 2015 Scifabric LTD.
#
# PYBOSSA is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your op... | Fix _select_attributes from project api | Fix _select_attributes from project api
| Python | agpl-3.0 | PyBossa/pybossa,PyBossa/pybossa,Scifabric/pybossa,Scifabric/pybossa | ---
+++
@@ -18,6 +18,7 @@
"""
PYBOSSA api module for exposing domain object ProjectStats via an API.
"""
+import copy
from flask import request
from pybossa.model.project_stats import ProjectStats
from api_base import APIBase
@@ -30,9 +31,10 @@
__class__ = ProjectStats
def _select_attributes(self, s... |
88da3432dc0676cbe74c0d9f170fbd6f18f97f8a | examples/tornado_server.py | examples/tornado_server.py | from tornado import ioloop, web
from jsonrpcserver import method, async_dispatch as dispatch
@method
async def ping():
return "pong"
class MainHandler(web.RequestHandler):
async def post(self):
request = self.request.body.decode()
response = await dispatch(request)
print(response)
... | from tornado import ioloop, web
from jsonrpcserver import method, async_dispatch as dispatch
@method
async def ping() -> str:
return "pong"
class MainHandler(web.RequestHandler):
async def post(self) -> None:
request = self.request.body.decode()
response = await dispatch(request)
if ... | Remove unwanted print statement from example | Remove unwanted print statement from example
| Python | mit | bcb/jsonrpcserver | ---
+++
@@ -3,15 +3,14 @@
@method
-async def ping():
+async def ping() -> str:
return "pong"
class MainHandler(web.RequestHandler):
- async def post(self):
+ async def post(self) -> None:
request = self.request.body.decode()
response = await dispatch(request)
- print(resp... |
0605e11672b76aa9582ed8024006b524f90d0c79 | tools/pinboost_debugme.py | tools/pinboost_debugme.py | #!/usr/bin/env python
import sys, os, tempfile
pid = int(sys.argv[1])
mytid = int(sys.argv[2])
# FIXME: optionally attach GDB to each thread since GDB won't find Pintool threads by itself
#for tid in os.listdir('/proc/%d/task' % pid):
# tid = int(tid)
# print "Starting screen with GDB for thread %d; resume using s... | #!/usr/bin/env python
import sys, os, tempfile
pid = int(sys.argv[1])
mytid = int(sys.argv[2])
# FIXME: optionally attach GDB to each thread since GDB won't find Pintool threads by itself
#for tid in os.listdir('/proc/%d/task' % pid):
# tid = int(tid)
# print >> sys.stderr, "Starting screen with GDB for thread %d;... | Write GDB debug session information to stderr, as stdout will be redirected to a log file | [pinboost] Write GDB debug session information to stderr, as stdout will be redirected to a log file
| Python | mit | abanaiyan/sniper,abanaiyan/sniper,abanaiyan/sniper,abanaiyan/sniper,abanaiyan/sniper | ---
+++
@@ -8,7 +8,7 @@
# FIXME: optionally attach GDB to each thread since GDB won't find Pintool threads by itself
#for tid in os.listdir('/proc/%d/task' % pid):
# tid = int(tid)
-# print "Starting screen with GDB for thread %d; resume using screen -r gdb-%d" % (tid, tid)
+# print >> sys.stderr, "Starting scr... |
91825c1883d0d95c593707a1f3f9d4f85b9154f1 | instana/options.py | instana/options.py | import logging
class Options(object):
service = ''
agent_host = ''
agent_port = 0
log_level = logging.ERROR
def __init__(self, **kwds):
self.__dict__.update(kwds)
| import logging
class Options(object):
service = ''
agent_host = ''
agent_port = 0
log_level = logging.WARN
def __init__(self, **kwds):
self.__dict__.update(kwds)
| Switch default log level to WARN | Switch default log level to WARN
| Python | mit | instana/python-sensor,instana/python-sensor | ---
+++
@@ -5,7 +5,7 @@
service = ''
agent_host = ''
agent_port = 0
- log_level = logging.ERROR
+ log_level = logging.WARN
def __init__(self, **kwds):
self.__dict__.update(kwds) |
e44f4ce0db6c56309107bc7280ac4e2b41616ab2 | modules/git/git.py | modules/git/git.py | import os
import os.path
import subprocess
from module import Module
class git(Module):
def __init__(self, scrap):
super(git, self).__init__(scrap)
scrap.register_event("git", "msg", self.distribute)
self.register_cmd("version", self.git_version)
self.register_cmd("update", self.up... | import os
import os.path
import subprocess
from module import Module
class git(Module):
def __init__(self, scrap):
super(git, self).__init__(scrap)
scrap.register_event("git", "msg", self.distribute)
self.register_cmd("version", self.git_version)
self.register_cmd("update", self.up... | Use subprocess to update, seems silly to use both subprocess and os.systemm in the same module. update also reports if the version hasn't changed. | Use subprocess to update, seems silly to use both subprocess and os.systemm in the same module. update also reports if the version hasn't changed.
| Python | mit | tcoppi/scrappy,johnmiked15/scrappy,johnmiked15/scrappy,tcoppi/scrappy | ---
+++
@@ -26,10 +26,12 @@
if not os.path.exists(".git"):
c.privmsg(event.target, "Scrappy not running from a git repo")
else:
- self.git_version(server, event, bot)
- os.system("git pull")
- c.privmsg(event.target, "Scrappy updated! You may need to %sr... |
d5b0234cca1bbab1a0bd20091df44380aca71ee8 | tslearn/tests/test_svm.py | tslearn/tests/test_svm.py | import numpy as np
from tslearn.metrics import cdist_gak
from tslearn.svm import TimeSeriesSVC
__author__ = 'Romain Tavenard romain.tavenard[at]univ-rennes2.fr'
def test_svm_gak():
n, sz, d = 15, 10, 3
rng = np.random.RandomState(0)
time_series = rng.randn(n, sz, d)
labels = rng.randint(low=0, high=... | import numpy as np
from tslearn.metrics import cdist_gak
from tslearn.svm import TimeSeriesSVC, TimeSeriesSVR
__author__ = 'Romain Tavenard romain.tavenard[at]univ-rennes2.fr'
def test_gamma_value_svm():
n, sz, d = 5, 10, 3
rng = np.random.RandomState(0)
time_series = rng.randn(n, sz, d)
labels = rn... | Change test name and test SVR too | Change test name and test SVR too
| Python | bsd-2-clause | rtavenar/tslearn | ---
+++
@@ -1,22 +1,24 @@
import numpy as np
from tslearn.metrics import cdist_gak
-from tslearn.svm import TimeSeriesSVC
+from tslearn.svm import TimeSeriesSVC, TimeSeriesSVR
__author__ = 'Romain Tavenard romain.tavenard[at]univ-rennes2.fr'
-def test_svm_gak():
- n, sz, d = 15, 10, 3
+def test_gamma_va... |
e731c3a4a8590f5cddd23fd2f9af265749f08a38 | code_snippets/guides-agentchecks-methods.py | code_snippets/guides-agentchecks-methods.py | self.gauge( ... ) # Sample a gauge metric
self.increment( ... ) # Increment a counter metric
self.decrement( ... ) # Decrement a counter metric
self.histogram( ... ) # Sample a histogram metric
self.rate( ... ) # Sample a point, with the rate calculated at the end of the check
| self.gauge( ... ) # Sample a gauge metric
self.increment( ... ) # Increment a counter metric
self.decrement( ... ) # Decrement a counter metric
self.histogram( ... ) # Sample a histogram metric
self.rate( ... ) # Sample a point, with the rate calculated at the end of the check
self.count( ... ) # Sample a raw coun... | Document AgentCheck count and monotonic_count methods | Document AgentCheck count and monotonic_count methods
| Python | bsd-3-clause | inokappa/documentation,macobo/documentation,macobo/documentation,jhotta/documentation,jhotta/documentation,inokappa/documentation,macobo/documentation,macobo/documentation,inokappa/documentation,jhotta/documentation,jhotta/documentation,jhotta/documentation,jhotta/documentation,inokappa/documentation,inokappa/documenta... | ---
+++
@@ -7,3 +7,7 @@
self.histogram( ... ) # Sample a histogram metric
self.rate( ... ) # Sample a point, with the rate calculated at the end of the check
+
+self.count( ... ) # Sample a raw count metric
+
+self.monotonic_count( ... ) # Sample an increasing counter metric |
6da466984143d2a9176870583ca5dba8d1b9764c | test/integration/test_graylogapi.py | test/integration/test_graylogapi.py | import pytest
from pygraylog.pygraylog import graylogapi
def test_get():
api = graylogapi.GraylogAPI('http://echo.jsontest.com/one/two',
username = 'Zack',
password = 'Zack')
res = api._get()
expected = {
'one': 'two'
}
assert res == expected
def test_post():
api = gr... | import pytest
from pygraylog.pygraylog import graylogapi
def test_get():
api = graylogapi.GraylogAPI('http://echo.jsontest.com/one/two',
username = 'Zack',
password = 'Zack')
res = api._get()
expected = "{\"one\": \"two\"}\n"
assert res == expected
def test_post():
api = graylogap... | Modify test to reflect that api returns string response. | Modify test to reflect that api returns string response.
| Python | apache-2.0 | zmallen/pygraylog | ---
+++
@@ -6,9 +6,7 @@
username = 'Zack',
password = 'Zack')
res = api._get()
- expected = {
- 'one': 'two'
- }
+ expected = "{\"one\": \"two\"}\n"
assert res == expected
def test_post(): |
4ba0b5fe7f31d4353e9c091b03df7324d1c20e88 | heat/common/pluginutils.py | heat/common/pluginutils.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
# ... | #
# 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
# ... | Fix no message attribute in exception | Fix no message attribute in exception
For py35, message attribute in exception seems removed.
We should directly get the string message from exception object
if message attribute not presented. And since get message attribute
already been deprecated. We should remove sopport on
exception.message after we fully jump to... | Python | apache-2.0 | noironetworks/heat,noironetworks/heat,openstack/heat,openstack/heat | ---
+++
@@ -12,6 +12,7 @@
# under the License.
from oslo_log import log as logging
+import six
LOG = logging.getLogger(__name__)
@@ -21,5 +22,6 @@
LOG.warning('Encountered exception while loading %(module_name)s: '
'"%(message)s". Not using %(name)s.',
{'module_name'... |
dd63394499c7c629033e76afa0196dfe48547da2 | corehq/messaging/smsbackends/tropo/models.py | corehq/messaging/smsbackends/tropo/models.py | from urllib import urlencode
from urllib2 import urlopen
from corehq.apps.sms.util import clean_phone_number
from corehq.apps.sms.models import SQLSMSBackend
from dimagi.ext.couchdbkit import *
from corehq.messaging.smsbackends.tropo.forms import TropoBackendForm
from django.conf import settings
class SQLTropoBackend... | from urllib import urlencode
from urllib2 import urlopen
from corehq.apps.sms.util import clean_phone_number
from corehq.apps.sms.models import SQLSMSBackend
from dimagi.ext.couchdbkit import *
from corehq.messaging.smsbackends.tropo.forms import TropoBackendForm
from django.conf import settings
class SQLTropoBackend... | Add opt in/out keywords for tropo | Add opt in/out keywords for tropo
| Python | bsd-3-clause | dimagi/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq | ---
+++
@@ -33,6 +33,14 @@
def get_sms_rate_limit(self):
return 60
+ @classmethod
+ def get_opt_in_keywords(cls):
+ return ['START']
+
+ @classmethod
+ def get_opt_out_keywords(cls):
+ return ['STOP']
+
def send(self, msg, *args, **kwargs):
phone_number = clean_... |
ed48c19844ee4f78c897c26555bdba9977a9a6ac | bluebottle/test/test_runner.py | bluebottle/test/test_runner.py | from django.test.runner import DiscoverRunner
from django.db import connection
from tenant_schemas.utils import get_tenant_model
from bluebottle.test.utils import InitProjectDataMixin
class MultiTenantRunner(DiscoverRunner, InitProjectDataMixin):
def setup_databases(self, *args, **kwargs):
result = supe... | from django.test.runner import DiscoverRunner
from django.db import connection
from tenant_schemas.utils import get_tenant_model
from bluebottle.test.utils import InitProjectDataMixin
class MultiTenantRunner(DiscoverRunner, InitProjectDataMixin):
def setup_databases(self, *args, **kwargs):
result = supe... | Make it possible to run tests with --keepdb | Make it possible to run tests with --keepdb
| Python | bsd-3-clause | onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle | ---
+++
@@ -13,7 +13,7 @@
# Create secondary tenant
connection.set_schema_to_public()
tenant_domain = 'testserver2'
- tenant2 = get_tenant_model()(
+ tenant2, _created = get_tenant_model().objects.get_or_create(
domain_url=tenant_domain,
schema_name='... |
25395cbd3536c1bc2ee1a6bc44a34ea7fc5b2a13 | src/priestLogger.py | src/priestLogger.py | import logging
from logging.handlers import TimedRotatingFileHandler
class PriestLogger:
def __init__(self):
logHandler = TimedRotatingFileHandler("C:\\lucas\\PriestPy\\Dropbox\\logs\\HowToPriest",when="midnight",backupCount=365)
logFormatter = logging.Formatter('%(asctime)s - %(message)s')
logHandler.setForma... | import logging
from logging.handlers import TimedRotatingFileHandler
from time import sleep
class PriestLogger:
def __init__(self):
logHandler = TimedRotatingFileHandler("C:\\lucas\\PriestPy\\Dropbox\\logs\\HowToPriest",when="midnight",backupCount=365)
logFormatter = logging.Formatter('%(asctime)s - %(message)s'... | Fix for conflict in opening file | Fix for conflict in opening file
| Python | mit | lgkern/PriestPy | ---
+++
@@ -1,5 +1,6 @@
import logging
from logging.handlers import TimedRotatingFileHandler
+from time import sleep
class PriestLogger:
@@ -12,4 +13,11 @@
self.logger.setLevel( logging.INFO )
def log(self, message):
- self.logger.info(message.channel.name + ' - ' + message.author.name+': ' + message.... |
7e0ef4ba74bf2d6ea93f49d88c58378e7a1f9106 | fabfile.py | fabfile.py | from fusionbox.fabric_helpers import *
env.roledefs = {
'dev': ['dev.fusionbox.com'],
}
env.project_name = 'django-widgy'
env.short_name = 'widgy'
env.tld = ''
def stage_with_docs(pip=False, migrate=False, syncdb=False, branch=None):
stage(pip=pip, migrate=migrate, syncdb=syncdb, branch=branch)
... | from fusionbox.fabric_helpers import *
env.roledefs = {
'dev': ['dev.fusionbox.com'],
}
env.project_name = 'django-widgy'
env.short_name = 'widgy'
env.tld = ''
_stage = stage
def stage(pip=False, migrate=False, syncdb=False, branch=None):
_stage(pip=pip, migrate=migrate, syncdb=syncdb, branch=br... | Make this one role, stage | Make this one role, stage
| Python | apache-2.0 | j00bar/django-widgy,j00bar/django-widgy,j00bar/django-widgy | ---
+++
@@ -9,11 +9,11 @@
env.tld = ''
-def stage_with_docs(pip=False, migrate=False, syncdb=False, branch=None):
- stage(pip=pip, migrate=migrate, syncdb=syncdb, branch=branch)
+_stage = stage
+def stage(pip=False, migrate=False, syncdb=False, branch=None):
+ _stage(pip=pip, migrate=migrate, syncdb=syncdb... |
78af66131240f79e43fba811cb8769b1911fa013 | services/fitbit.py | services/fitbit.py | import foauth.providers
class Fitbit(foauth.providers.OAuth1):
# General info about the provider
provider_url = 'https://www.fitbit.com/'
docs_url = 'https://dev.fitbit.com/'
category = 'Fitness'
# URLs to interact with the API
request_token_url = 'https://api.fitbit.com/oauth/request_token'
... | import requests
import foauth.providers
class Fitbit(foauth.providers.OAuth2):
# General info about the provider
provider_url = 'https://www.fitbit.com/'
docs_url = 'https://dev.fitbit.com/'
category = 'Fitness'
# URLs to interact with the API
authorize_url = 'https://www.fitbit.com/oauth2/a... | Upgrade Fitbit to OAuth 2.0 | Upgrade Fitbit to OAuth 2.0
| Python | bsd-3-clause | foauth/foauth.org,foauth/foauth.org,foauth/foauth.org | ---
+++
@@ -1,21 +1,50 @@
+import requests
+
import foauth.providers
-class Fitbit(foauth.providers.OAuth1):
+class Fitbit(foauth.providers.OAuth2):
# General info about the provider
provider_url = 'https://www.fitbit.com/'
docs_url = 'https://dev.fitbit.com/'
category = 'Fitness'
# UR... |
20bc9544830f329c07c8f80e2f38a7fc9fdb3245 | tests/unit/utils/test_yamldumper.py | tests/unit/utils/test_yamldumper.py | # -*- coding: utf-8 -*-
'''
Unit tests for salt.utils.yamldumper
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
# Import Salt Libs
import salt.utils.yamldumper
# Import Salt Testing Libs
from tests.support.unit import TestCase, skipIf
from tests.support.mock imp... | # -*- coding: utf-8 -*-
'''
Unit tests for salt.utils.yamldumper
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
# Import Salt Libs
import salt.utils.yamldumper
# Import Salt Testing Libs
from tests.support.unit import TestCase, skipIf
from tests.support.mock imp... | Update docs for yamldumper test | Update docs for yamldumper test
| Python | apache-2.0 | saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt | ---
+++
@@ -17,7 +17,7 @@
@skipIf(NO_MOCK, NO_MOCK_REASON)
class YamlDumperTestCase(TestCase):
'''
- TestCase for salt.utils.yamlloader module
+ TestCase for salt.utils.yamldumper module
'''
def test_yaml_dump(self):
''' |
936021e0a7b2f23935f4580c5140c1292a37cf82 | runbot_pylint/__openerp__.py | runbot_pylint/__openerp__.py | {
'name': 'Runbot Pylint',
'category': 'Website',
'summary': 'Runbot',
'version': '1.0',
'description': "Runbot",
'author': 'OpenERP SA',
'depends': ['runbot'],
'external_dependencies': {
},
'data': [
"view/runbot_pylint_view.xml"
],
'installable': True,
}
| {
'name': 'Runbot Pylint',
'category': 'Website',
'summary': 'Runbot',
'version': '1.0',
'description': "Runbot",
'author': 'OpenERP SA',
'depends': ['runbot'],
'external_dependencies': {
'bin': ['pylint'],
},
'data': [
"view/runbot_pylint_view.xml"
],
'in... | Add external depedencies to pylint bin | Add external depedencies to pylint bin
| Python | agpl-3.0 | amoya-dx/runbot-addons | ---
+++
@@ -7,6 +7,7 @@
'author': 'OpenERP SA',
'depends': ['runbot'],
'external_dependencies': {
+ 'bin': ['pylint'],
},
'data': [
"view/runbot_pylint_view.xml" |
2823efda9d6ec2a14606c9e22ef8085f111d8842 | isort/pylama_isort.py | isort/pylama_isort.py | import os
import sys
from contextlib import contextmanager
from typing import Any, Dict, List
from pylama.lint import Linter as BaseLinter
from . import api
@contextmanager
def supress_stdout():
stdout = sys.stdout
with open(os.devnull, "w") as devnull:
sys.stdout = devnull
yield
sys... | import os
import sys
from contextlib import contextmanager
from typing import Any, Dict, List
from pylama.lint import Linter as BaseLinter
from . import api
@contextmanager
def supress_stdout():
stdout = sys.stdout
with open(os.devnull, "w") as devnull:
sys.stdout = devnull
yield
sys... | Fix pylama isort integration not to include check=True redundly | Fix pylama isort integration not to include check=True redundly
| Python | mit | PyCQA/isort,PyCQA/isort | ---
+++
@@ -25,7 +25,7 @@
def run(self, path: str, **meta: Any) -> List[Dict[str, Any]]:
"""Lint the file. Return an array of error dicts if appropriate."""
with supress_stdout():
- if api.check_file(path, check=True):
+ if api.check_file(path):
return [
... |
c52e8e27d7b245722e10887dc97440481d0871f4 | scraper/political_parties.py | scraper/political_parties.py | import re
import requests
import lxml.html
from parliament.models import PoliticalParty
def create_parties():
url = 'https://www.tweedekamer.nl/kamerleden/fracties'
page = requests.get(url)
tree = lxml.html.fromstring(page.content)
rows = tree.xpath("//ul[@class='reset grouped-list']/li/a")
for... | import re
import requests
import lxml.html
from parliament.models import PoliticalParty
def create_parties():
url = 'https://www.tweedekamer.nl/kamerleden/fracties'
page = requests.get(url)
tree = lxml.html.fromstring(page.content)
rows = tree.xpath("//ul[@class='reset grouped-list']/li/a")
for... | Update party info after creation | Update party info after creation
| Python | mit | openkamer/openkamer,openkamer/openkamer,openkamer/openkamer,openkamer/openkamer | ---
+++
@@ -24,10 +24,11 @@
name_short = name
# print('name: ' + name)
# print('short: ' + name_short)
- if PoliticalParty.find_party(name):
+ party = PoliticalParty.find_party(name)
+ if party:
print('WARNING: party already exists!')
else:
... |
01cc82642273af950caedba471ed4cc9e788b615 | alapage/urls.py | alapage/urls.py | # -*- coding: utf-8 -*-
from django.conf.urls import url
from alapage.views import HomepageView, PageView, PagesmapView
urlpatterns = []
urlpatterns.append(
url(r'^sitemap/$', PagesmapView.as_view(), name="alapage-map"))
#urlpatterns.append(url(r'^alapage/wizard/$', PageWizardView.as_view(), name="alapage-wizar... | from django.conf.urls import url
from alapage.views import HomepageView, PageView, PagesmapView
urlpatterns = [
url(r'^sitemap/?$', PagesmapView.as_view(), name="alapage-map"),
url(r'^(?P<url>.*?)?$', PageView.as_view(), name="page-view"),
url(r'^', HomepageView.as_view(), name="home-view"),
]
| Fix url regex for no trailing slash | Fix url regex for no trailing slash
| Python | mit | synw/django-alapage,synw/django-alapage,synw/django-alapage | ---
+++
@@ -1,15 +1,9 @@
-# -*- coding: utf-8 -*-
-
from django.conf.urls import url
from alapage.views import HomepageView, PageView, PagesmapView
-urlpatterns = []
-
-urlpatterns.append(
- url(r'^sitemap/$', PagesmapView.as_view(), name="alapage-map"))
-#urlpatterns.append(url(r'^alapage/wizard/$', PageWiz... |
491d2ad7cea58597e15b095b94930b6ff1dbf4d2 | createdb.py | createdb.py | from chalice.extensions import db
from chalice import init_app
from chalice.blog.models import Tag, Post
from chalice.auth.models import User
if __name__ == '__main__':
app = init_app()
with app.test_request_context():
db.create_all()
post = Post( 'This is a title', 'The classic hello world her... | from chalice.extensions import db
from chalice import init_app
from chalice.blog.models import Tag, Post
from chalice.auth.models import User
if __name__ == '__main__':
app = init_app()
with app.test_request_context():
db.create_all()
user = User(app.config['CHALICE_USER'], app.config['CHALICE_... | Remove dummy post from created.py script. Initial user now taken from config. | Remove dummy post from created.py script.
Initial user now taken from config.
| Python | bsd-2-clause | andrimarjonsson/chalice,andrimarjonsson/chalice | ---
+++
@@ -7,10 +7,7 @@
app = init_app()
with app.test_request_context():
db.create_all()
- post = Post( 'This is a title', 'The classic hello world here.')
- post.tags = ['rant', 'programming']
- db.session.add(post)
- user = User('andrimar', 'testpass')
+ user ... |
e8422ac65a4557257d9697b8dfcb538a02e5f6f0 | pixelated/common/__init__.py | pixelated/common/__init__.py | import ssl
import logging
from logging.handlers import SysLogHandler
from threading import Timer
logger = logging.getLogger('pixelated.startup')
def init_logging(name, level=logging.INFO, config_file=None):
global logger
logger_name = 'pixelated.%s' % name
logging.basicConfig(level=level)
if config_... | import ssl
import logging
from logging.handlers import SysLogHandler
from threading import Timer
logger = logging.getLogger('pixelated.startup')
def init_logging(name, level=logging.INFO, config_file=None):
global logger
logger_name = 'pixelated.%s' % name
logging.basicConfig(level=level)
if config_... | Revert "Downgraded SSL version to TLS 1 until we have the requests library fixed" | Revert "Downgraded SSL version to TLS 1 until we have the requests library fixed"
- TLS1.2 does not work on older pythons (like on MacOSX)
but it works as intended on current linux versions
so enable it if possible
This reverts commit 666630f2a01bdeb7becc3cd3b324c076eaf1567d.
Conflicts:
pixelated/common/__init_... | Python | agpl-3.0 | pixelated-project/pixelated-dispatcher,pixelated-project/pixelated-dispatcher,pixelated/pixelated-dispatcher,pixelated/pixelated-dispatcher,pixelated/pixelated-dispatcher,pixelated-project/pixelated-dispatcher | ---
+++
@@ -24,7 +24,10 @@
def latest_available_ssl_version():
- return ssl.PROTOCOL_TLSv1
+ try:
+ return ssl.PROTOCOL_TLSv1_2
+ except AttributeError:
+ return ssl.PROTOCOL_TLSv1
class Watchdog: |
d7ea84800b89255137300b8e8d83b4b6abfc30b2 | src/oscar/apps/voucher/receivers.py | src/oscar/apps/voucher/receivers.py | from oscar.apps.basket import signals
def track_voucher_addition(basket, voucher, **kwargs):
voucher.num_basket_additions += 1
voucher.save()
def track_voucher_removal(basket, voucher, **kwargs):
voucher.num_basket_additions -= 1
voucher.save()
signals.voucher_addition.connect(track_voucher_additi... | from django.db.models import F
from oscar.apps.basket import signals
def track_voucher_addition(basket, voucher, **kwargs):
voucher.num_basket_additions += 1
voucher.__class__._default_manager.filter(pk=voucher.pk).update(
num_basket_additions=F('num_basket_additions') + 1,
)
def track_voucher_r... | Fix race condition when tracking num_basket_additions on a voucher | Fix race condition when tracking num_basket_additions on a voucher
| Python | bsd-3-clause | jmt4/django-oscar,mexeniz/django-oscar,michaelkuty/django-oscar,pasqualguerrero/django-oscar,binarydud/django-oscar,saadatqadri/django-oscar,jmt4/django-oscar,michaelkuty/django-oscar,nickpack/django-oscar,pasqualguerrero/django-oscar,okfish/django-oscar,sasha0/django-oscar,okfish/django-oscar,sasha0/django-oscar,bnprk... | ---
+++
@@ -1,14 +1,19 @@
+from django.db.models import F
from oscar.apps.basket import signals
def track_voucher_addition(basket, voucher, **kwargs):
voucher.num_basket_additions += 1
- voucher.save()
+ voucher.__class__._default_manager.filter(pk=voucher.pk).update(
+ num_basket_additions=F(... |
691dae3963d049664605084438714b2850bd0933 | linter.py | linter.py | #
# linter.py
# Linter for SublimeLinter4, a code checking framework for Sublime Text 3
#
# Written by Markus Liljedahl
# Copyright (c) 2017 Markus Liljedahl
#
# License: MIT
#
"""This module exports the AnsibleLint plugin class."""
from SublimeLinter.lint import Linter, util
class AnsibleLint(Linter):
"""Provi... | #
# linter.py
# Linter for SublimeLinter4, a code checking framework for Sublime Text 3
#
# Written by Markus Liljedahl
# Copyright (c) 2017 Markus Liljedahl
#
# License: MIT
#
"""This module exports the AnsibleLint plugin class."""
from SublimeLinter.lint import Linter, util
class AnsibleLint(Linter):
"""Provi... | Update to support SublimeLinter 4 | Update to support SublimeLinter 4
| Python | mit | mliljedahl/SublimeLinter-contrib-ansible-lint | ---
+++
@@ -22,8 +22,8 @@
version_requirement = '>= 3.0.1'
# linter settings
- cmd = ('ansible-lint', '${args}', '${file}')
- regex = r'.+:(?P<line>\d+): \[(?P<error>.z+)\] (?P<message>.+)'
+ cmd = ('ansible-lint', '${args}', '@')
+ regex = r'^.+:(?P<line>\d+): \[.(?P<error>.+)\] (?P<message>.... |
84597d8b8135af36056f968d10699c206dd06942 | adapter/terminal.py | adapter/terminal.py | import os
import socket
import subprocess
import string
import logging
log = logging.getLogger('terminal')
class Terminal:
def __init__(self, tty, socket):
self.tty = tty
self.socket = socket
def __del__(self):
self.socket.close()
TIMEOUT = 1 # Timeout in seconds for child opening a ... | import os
import socket
import subprocess
import string
import logging
log = logging.getLogger('terminal')
class Terminal:
def __init__(self, tty, socket):
self.tty = tty
self.socket = socket
def __del__(self):
self.socket.close()
TIMEOUT = 3 # Timeout in seconds for child opening a ... | Use bash's built-in tcp support, drop dependency on netcat. | Use bash's built-in tcp support, drop dependency on netcat.
| Python | mit | vadimcn/vscode-lldb,vadimcn/vscode-lldb,NeroProtagonist/vscode-lldb,NeroProtagonist/vscode-lldb,NeroProtagonist/vscode-lldb,vadimcn/vscode-lldb,NeroProtagonist/vscode-lldb,vadimcn/vscode-lldb,NeroProtagonist/vscode-lldb,vadimcn/vscode-lldb,vadimcn/vscode-lldb,vadimcn/vscode-lldb | ---
+++
@@ -14,29 +14,33 @@
def __del__(self):
self.socket.close()
-TIMEOUT = 1 # Timeout in seconds for child opening a socket and sending the tty name
+TIMEOUT = 3 # Timeout in seconds for child opening a socket and sending the tty name
def create():
- socket_path = '/tmp/vscode-lldb-%d.sock' ... |
a27a525650571b6f3756edf7f0fdf82d724f22d3 | performance/web.py | performance/web.py | import requests
from time import time
class Client:
def __init__(self, host, requests, do_requests_counter):
self.host = host
self.requests = requests
self.counter = do_requests_counter
class Request:
GET = 'get'
POST = 'post'
def __init__(self, url, type=GET, data=None):
... | import requests
from time import time
class Client:
def __init__(self, host, requests, do_requests_counter):
self.host = host
self.requests = requests
self.counter = do_requests_counter
class Request:
GET = 'get'
POST = 'post'
def __init__(self, url, type=GET, data=None):
... | Update function name and return value | Update function name and return value
| Python | mit | BakeCode/performance-testing,BakeCode/performance-testing | ---
+++
@@ -38,9 +38,9 @@
def __init__(self, data=None):
self.data = data
- def for_type(self, type=Request.GET):
+ def get_converted(self, type=Request.GET):
if type is Request.GET:
- return data
+ return self.data
class RequestTypeError(Exception): |
a3dd19f7825bcbc65c666dc5e45af1084c061a12 | {{cookiecutter.extension_name}}/{{cookiecutter.extension_name}}/__init__.py | {{cookiecutter.extension_name}}/{{cookiecutter.extension_name}}/__init__.py | from IPython.display import display
import json
# Running `npm run build` will create static resources in the static
# directory of this Python package (and create that directory if necessary).
def _jupyter_labextension_paths():
return [{
'name': '{{cookiecutter.extension_name}}',
'src': 'static... | from IPython.display import display, JSON
import json
# Running `npm run build` will create static resources in the static
# directory of this Python package (and create that directory if necessary).
def _jupyter_labextension_paths():
return [{
'name': '{{cookiecutter.extension_name}}',
'src': '... | Use sub-class of IPython.display.JSON vs. display function | Use sub-class of IPython.display.JSON vs. display function
| Python | cc0-1.0 | gnestor/mimerender-cookiecutter,jupyterlab/mimerender-cookiecutter,jupyterlab/mimerender-cookiecutter,gnestor/mimerender-cookiecutter | ---
+++
@@ -1,4 +1,4 @@
-from IPython.display import display
+from IPython.display import display, JSON
import json
@@ -21,14 +21,25 @@
}]
-# A display function that can be used within a notebook. E.g.:
+# A display class that can be used within a notebook. E.g.:
# from {{cookiecutter.extension_name}... |
9d6975b2a07315d7fe907ed332300409d226085c | flycam.py | flycam.py | import capture
from picamera import PiCamera
import time
def image_cap_loop(camera, status=None):
"""Set image parameters, capture image, set wait time, repeat"""
resolution = (854, 480)
camera.rotation = 90
latest = capture.cap(camera, resolution, status)
status = latest[0]
size = capture.im... | import capture
from picamera import PiCamera
import time
def image_cap_loop(camera, status=None):
"""Set image parameters, capture image, set wait time, repeat"""
resolution = (854, 480)
camera.rotation = 90
latest = capture.cap(camera, resolution, status)
status = latest[0]
size = capture.im... | Adjust image size to 150k. | Adjust image size to 150k.
| Python | mit | gnfrazier/YardCam | ---
+++
@@ -12,7 +12,7 @@
status = latest[0]
size = capture.image_size(latest[1])
capture.copy_latest(latest[1])
- day = 100000 # image size when light is good
+ day = 150000 # image size when light is good
if size > day:
wait = 60
else: |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.