commit stringlengths 40 40 | old_file stringlengths 4 236 | new_file stringlengths 4 236 | old_contents stringlengths 1 3.26k | new_contents stringlengths 16 4.43k | subject stringlengths 16 624 | message stringlengths 17 3.29k | lang stringclasses 5
values | license stringclasses 13
values | repos stringlengths 5 91.5k |
|---|---|---|---|---|---|---|---|---|---|
f02282be3cf2901a9fd6c816f1b4c37b09abdc7b | addons/base/models/hooks.py | addons/base/models/hooks.py | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2014-2015 Anthony Minotti <anthony@minotti.cool>.
#
#
# This file is part of Yameo framework.
#
# Yameo framework is free software: you can redistribute it and/or modify
# it under the terms of the G... | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2014-2015 Anthony Minotti <anthony@minotti.cool>.
#
#
# This file is part of Yameo framework.
#
# Yameo framework is free software: you can redistribute it and/or modify
# it under the terms of the G... | Test if ressource is hookable before write/update | Test if ressource is hookable before write/update
| Python | agpl-3.0 | aminotti/yameo,aminotti/yameo |
5bbd106aa49f13550ee93c173f7f8684e4fa1d4b | biothings/tests/test_query.py | biothings/tests/test_query.py | '''
Biothings Query Component Common Tests
'''
import os
from nose.core import main
from biothings.tests import BiothingsTestCase
class QueryTests(BiothingsTestCase):
''' Test against server specified in environment variable BT_HOST
and BT_API or MyGene.info production server V3 by def... | '''
Biothings Query Component Common Tests
'''
import os
from nose.core import main
from biothings.tests import BiothingsTestCase
class QueryTests(BiothingsTestCase):
''' Test against server specified in environment variable BT_HOST
and BT_API or MyGene.info production server V3 by def... | Change match all query syntax | Change match all query syntax
| Python | apache-2.0 | biothings/biothings.api,biothings/biothings.api |
c8918e5ee06c3f7ec84124ebfccddb738dca2bfb | test/python_api/default-constructor/sb_communication.py | test/python_api/default-constructor/sb_communication.py | """
Fuzz tests an object after the default construction to make sure it does not crash lldb.
"""
import sys
import lldb
def fuzz_obj(obj):
broadcaster = obj.GetBroadcaster()
# Do fuzz testing on the broadcaster obj, it should not crash lldb.
import sb_broadcaster
sb_broadcaster.fuzz_obj(broadcaster)
... | """
Fuzz tests an object after the default construction to make sure it does not crash lldb.
"""
import sys
import lldb
def fuzz_obj(obj):
broadcaster = obj.GetBroadcaster()
# Do fuzz testing on the broadcaster obj, it should not crash lldb.
import sb_broadcaster
sb_broadcaster.fuzz_obj(broadcaster)
... | Add a fuzz call for SBCommunication: obj.connect(None). | Add a fuzz call for SBCommunication: obj.connect(None).
git-svn-id: 4c4cc70b1ef44ba2b7963015e681894188cea27e@146912 91177308-0d34-0410-b5e6-96231b3b80d8
| Python | apache-2.0 | llvm-mirror/lldb,apple/swift-lldb,llvm-mirror/lldb,apple/swift-lldb,llvm-mirror/lldb,llvm-mirror/lldb,apple/swift-lldb,apple/swift-lldb,apple/swift-lldb,llvm-mirror/lldb,apple/swift-lldb |
4b111c035f92f941cff4b6885d2fa01ddcb1657e | titanembeds/database/custom_redislite.py | titanembeds/database/custom_redislite.py | import urlparse
from limits.storage import Storage
from redislite import Redis
import time
class LimitsRedisLite(Storage): # For Python Limits
STORAGE_SCHEME = "redislite"
def __init__(self, uri, **options):
self.redis_instance = Redis(urlparse.urlparse(uri).netloc)
def check(self):
return... | import urlparse
from limits.storage import Storage
from redislite import Redis
import time
class LimitsRedisLite(Storage): # For Python Limits
STORAGE_SCHEME = "redislite"
def __init__(self, uri, **options):
self.redis_instance = Redis(urlparse.urlparse(uri).netloc)
def check(self):
return... | Fix custom redislite to account for the none errors | Fix custom redislite to account for the none errors
| Python | agpl-3.0 | TitanEmbeds/Titan,TitanEmbeds/Titan,TitanEmbeds/Titan |
63c81a18bd95876cad1bd4c1269d38e18ee3e817 | wikichatter/TalkPageParser.py | wikichatter/TalkPageParser.py | import mwparserfromhell as mwp
from . import IndentTree
from . import WikiComments as wc
class Page:
def __init__(self):
self.indent = -2
def __str__(self):
return "Talk_Page"
class Section:
def __init__(self, heading):
self.heading = heading
self.indent = -1
def __st... | import mwparserfromhell as mwp
from . import IndentTree
from . import WikiComments as wc
class Page:
def __init__(self):
self.indent = -2
def __str__(self):
return "Talk_Page"
class Section:
def __init__(self, heading):
self.heading = heading
self.indent = -1
def __st... | Make mwparserfromhell skip style tags | Make mwparserfromhell skip style tags
Since we do not really care if '' and ''' tags are processed
as plaintext or not, and not processing them as plaintext
causes #10
| Python | mit | kjschiroo/WikiChatter |
cd0f4758bcb8eacab0a6a1f21f3c4287b2d24995 | vumi/blinkenlights/heartbeat/__init__.py | vumi/blinkenlights/heartbeat/__init__.py |
from vumi.blinkenlights.heartbeat.publisher import (HeartBeatMessage,
HeartBeatPublisher)
from vumi.blinkenlights.heartbeat.monitor import HeartBeatMonitor
__all__ = ["HeartBeatMessage", "HeartBeatPublisher", "HeartBeatMonitor"]
|
from vumi.blinkenlights.heartbeat.publisher import (HeartBeatMessage,
HeartBeatPublisher)
__all__ = ["HeartBeatMessage", "HeartBeatPublisher"]
| Resolve a cyclical dependency issue | Resolve a cyclical dependency issue
| Python | bsd-3-clause | vishwaprakashmishra/xmatrix,TouK/vumi,harrissoerja/vumi,TouK/vumi,harrissoerja/vumi,vishwaprakashmishra/xmatrix,TouK/vumi,vishwaprakashmishra/xmatrix,harrissoerja/vumi |
a5a9807bb4c473442716201b6b220be62d764af4 | tailor/listeners/filelistener.py | tailor/listeners/filelistener.py | from tailor.utils.sourcefile import num_lines_in_file, file_too_long
class FileListener:
# pylint: disable=too-few-public-methods
def __init__(self, printer, filepath):
self.__printer = printer
self.__filepath = filepath
def verify(self, max_lines):
self.__verify_file_length(max_... | from tailor.types.location import Location
from tailor.utils.sourcefile import num_lines_in_file, file_too_long
class FileListener:
# pylint: disable=too-few-public-methods
def __init__(self, printer, filepath):
self.__printer = printer
self.__filepath = filepath
def verify(self, max_lin... | Use Location namedtuple when calling printer | Use Location namedtuple when calling printer
| Python | mit | sleekbyte/tailor,sleekbyte/tailor,sleekbyte/tailor,sleekbyte/tailor,sleekbyte/tailor |
c23570f528b3ad27e256ea402fc02231b528b000 | django_messages/urls.py | django_messages/urls.py | from django.conf.urls import patterns, url
from django.views.generic import RedirectView
from django_messages.views import *
urlpatterns = patterns('',
url(r'^$', RedirectView.as_view(url='inbox/'), name='messages_redirect'),
url(r'^inbox/$', inbox, name='messages_inbox'),
url(r'^outbox/$', outbox, name='... | from django.conf.urls import patterns, url
from django.views.generic import RedirectView
from django_messages.views import *
urlpatterns = patterns('',
url(r'^$', RedirectView.as_view(permanent=True, url='inbox/'), name='messages_redirect'),
url(r'^inbox/$', inbox, name='messages_inbox'),
url(r'^outbox/$'... | Set an explicit value because Default value of 'RedirectView.permanent' will change from True to False in Django 1.9. | Set an explicit value because Default value of 'RedirectView.permanent' will change from True to False in Django 1.9. | Python | bsd-3-clause | arneb/django-messages,JordanReiter/django-messages,brajeshvit/Messagemodule,nikhil-above/django-messages,tobiasgoecke/django-messages,brajeshvit/Messagemodule,JordanReiter/django-messages,gustavoam/django-messages,tobiasgoecke/django-messages,procrasti/django-messages,Chris7/django-messages,gustavoam/django-messages,ni... |
93cb07ed61f17a1debbe353963120ab117598f3f | src/yunohost/utils/yunopaste.py | src/yunohost/utils/yunopaste.py | # -*- coding: utf-8 -*-
import requests
import json
import errno
from moulinette.core import MoulinetteError
def yunopaste(data):
paste_server = "https://paste.yunohost.org"
try:
r = requests.post("%s/documents" % paste_server, data=data, timeout=30)
except Exception as e:
raise Mouline... | # -*- coding: utf-8 -*-
import requests
import json
import errno
from moulinette.core import MoulinetteError
def yunopaste(data):
paste_server = "https://paste.yunohost.org"
try:
r = requests.post("%s/documents" % paste_server, data=data, timeout=30)
except Exception as e:
raise Mouline... | Add status code to error message | Add status code to error message
| Python | agpl-3.0 | YunoHost/yunohost,YunoHost/moulinette-yunohost,YunoHost/moulinette-yunohost,YunoHost/moulinette-yunohost,YunoHost/moulinette-yunohost,YunoHost/yunohost,YunoHost/moulinette-yunohost,YunoHost/yunohost,YunoHost/yunohost |
f3eee368e13ee37048d52bde0d067efea057fef8 | monkeylearn/extraction.py | monkeylearn/extraction.py | # -*- coding: utf-8 -*-
from __future__ import (
print_function, unicode_literals, division, absolute_import)
from six.moves import range
from monkeylearn.utils import SleepRequestsMixin, MonkeyLearnResponse, HandleErrorsMixin
from monkeylearn.settings import DEFAULT_BASE_ENDPOINT, DEFAULT_BATCH_SIZE
class Extra... | # -*- coding: utf-8 -*-
from __future__ import (
print_function, unicode_literals, division, absolute_import)
from six.moves import range
from monkeylearn.utils import SleepRequestsMixin, MonkeyLearnResponse, HandleErrorsMixin
from monkeylearn.settings import DEFAULT_BASE_ENDPOINT, DEFAULT_BATCH_SIZE
class Extra... | Support for extra parameters in extractors | Support for extra parameters in extractors
| Python | mit | monkeylearn/monkeylearn-python |
edd06989628e90d4fdfa98e4af84720d815322f9 | pinax/likes/migrations/0001_initial.py | pinax/likes/migrations/0001_initial.py | # -*- coding: utf-8 -*-
# Generated by Django 1.9.1 on 2016-01-29 16:12
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
depen... | # -*- coding: utf-8 -*-
# Generated by Django 1.9.1 on 2016-01-29 16:12
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
depen... | Drop features removed in Django 2.0 | Drop features removed in Django 2.0
Field.rel and Field.remote_field.to are removed
https://docs.djangoproject.com/en/dev/releases/2.0/#features-removed-in-2-0
| Python | mit | pinax/pinax-likes |
c9cb55a4a9f3409a3c22edd0d5a8b6bfbdca1208 | mopidy_somafm/__init__.py | mopidy_somafm/__init__.py | from __future__ import unicode_literals
import os
from mopidy import config, exceptions, ext
__version__ = '0.3.0'
class Extension(ext.Extension):
dist_name = 'Mopidy-SomaFM'
ext_name = 'somafm'
version = __version__
def get_default_config(self):
conf_file = os.path.join(os.path.dirname(__... | from __future__ import unicode_literals
import os
from mopidy import config, ext
__version__ = '0.3.0'
class Extension(ext.Extension):
dist_name = 'Mopidy-SomaFM'
ext_name = 'somafm'
version = __version__
def get_default_config(self):
conf_file = os.path.join(os.path.dirname(__file__), 'e... | Remove dependency check done by Mopidy | Remove dependency check done by Mopidy
| Python | mit | AlexandrePTJ/mopidy-somafm |
6894db57f74cf4c813e470d9cee1def9cf14cc3d | megaprojects/scripts.py | megaprojects/scripts.py | def migrate_posts_to_articles():
from django.core.files import base
from articles.models import Article, Image
from blog.models import Post
for p in Post.objects.all():
a = Article()
a.author = p.author
a.body = p.body
a.enable_comments = p.enable_comments
a.pub... | def migrate_posts_to_articles():
from articles.models import Article
from blog.models import Post
for p in Post.objects.all():
try:
Article.objects.get(shortuuid=p.shortuuid)
continue
except Article.DoesNotExist:
a = Article()
a.author = p.aut... | Update post -> article migration script, include all fields | Update post -> article migration script, include all fields
| Python | apache-2.0 | megaprojectske/megaprojects.co.ke,megaprojectske/megaprojects.co.ke,megaprojectske/megaprojects.co.ke |
ce05cf03738572bbe52de0e649ad25480a1f65f1 | networkzero/__init__.py | networkzero/__init__.py | from .discovery import advertise, unadvertise, discover
from .messenger import (
send_command, wait_for_command,
send_request, wait_for_request, send_reply,
publish_news, wait_for_news
)
from .core import address | # -*- coding: utf-8 -*-
"""networkzero - easy network discovery & messaging
Aimed at a classrom or club situation, networkzero makes it simpler to
have several machines or several processes on one machine discovering
each other and talking across a network. Typical examples would include:
* Sending commands to a robo... | Put some high-level module docs together, including a simple example | Put some high-level module docs together, including a simple example
| Python | mit | tjguk/networkzero,tjguk/networkzero,tjguk/networkzero |
d13b3d89124d03f563c2ee2143ae16eec7d0b191 | tests/Epsilon_tests/ImportTest.py | tests/Epsilon_tests/ImportTest.py | #!/usr/bin/env python
"""
:Author Patrik Valkovic
:Created 23.06.2017 16:39
:Licence GNUv3
Part of grammpy
"""
from unittest import TestCase, main
from grammpy import EPS
from grammpy import EPSILON
class ImportTest(TestCase):
def test_idSame(self):
self.assertEqual(id(EPS), id(EPSILON))... | #!/usr/bin/env python
"""
:Author Patrik Valkovic
:Created 23.06.2017 16:39
:Licence GNUv3
Part of grammpy
"""
from unittest import TestCase, main
from grammpy import EPS
from grammpy import EPSILON
class ImportTest(TestCase):
def test_idSame(self):
self.assertEqual(id(EPS),id(EPSILON)... | Revert "Add tests to compare epsilon with another objects" | Revert "Add tests to compare epsilon with another objects"
This reverts commit ae4b4fe5fb5c5774720dd3a14549aa88bde91043.
| Python | mit | PatrikValkovic/grammpy |
8d40cbd1d2cf431454dcfd9a9088be73687e7c1a | skimage/viewer/__init__.py | skimage/viewer/__init__.py | try:
from .qt import QtGui as _QtGui
except ImportError as e:
raise ImportError('Viewer requires Qt')
from .viewers import ImageViewer, CollectionViewer
| import warnings
try:
from .viewers import ImageViewer, CollectionViewer
except ImportError as e:
warnings.warn('Viewer requires Qt')
| Allow viewer package to import without Qt | Allow viewer package to import without Qt
| Python | bsd-3-clause | pratapvardhan/scikit-image,paalge/scikit-image,youprofit/scikit-image,michaelaye/scikit-image,blink1073/scikit-image,newville/scikit-image,warmspringwinds/scikit-image,pratapvardhan/scikit-image,juliusbierk/scikit-image,ajaybhat/scikit-image,jwiggins/scikit-image,chriscrosscutler/scikit-image,robintw/scikit-image,GaZ3l... |
0d9c151d9f61d03e57f815d99158e1b90c9dca5e | erpnext/education/doctype/instructor/instructor.py | erpnext/education/doctype/instructor/instructor.py | # -*- coding: utf-8 -*-
# Copyright (c) 2015, Frappe Technologies and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe import _
from frappe.model.document import Document
from frappe.model.naming import set_name_by_naming_series
class Ins... | # -*- coding: utf-8 -*-
# Copyright (c) 2015, Frappe Technologies and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe import _
from frappe.model.document import Document
from frappe.model.naming import set_name_by_naming_series
class Ins... | Exclude current record while validating duplicate employee | fix: Exclude current record while validating duplicate employee | Python | agpl-3.0 | gsnbng/erpnext,gsnbng/erpnext,gsnbng/erpnext,gsnbng/erpnext |
22bca7f50c9db97aaa79c1199b385b0f59968328 | client/tests/tests_msgpack.py | client/tests/tests_msgpack.py | import unittest
from msgpack import *
class MessagePackTestCase(unittest.TestCase):
"""
This is not really a comprehensive test suite for messagepack but instead a
way to learn how to use the api.
"""
def test_can_pack_fixarray(self):
"""
Checks that we can pack a fix array (len(ar... | import unittest
from msgpack import *
class MessagePackTestCase(unittest.TestCase):
"""
This is not really a comprehensive test suite for messagepack but instead a
way to learn how to use the api.
"""
def test_can_pack_fixarray(self):
"""
Checks that we can pack a fix array (len(ar... | Add an example showing stream unpacking | Add an example showing stream unpacking
| Python | bsd-2-clause | cvra/can-bootloader,cvra/can-bootloader,cvra/can-bootloader,cvra/can-bootloader |
0ba44cc7a8e906be42d98599b59e28ad142648b7 | blogApp/forms/upload_image.py | blogApp/forms/upload_image.py | from django import forms
from crispy_forms.helper import FormHelper
from crispy_forms.bootstrap import FormActions, Div
from crispy_forms.layout import Layout, Field, HTML, Button, Submit, Reset
class UploadImageForm(forms.Form):
helper = FormHelper()
helper.form_tag = False
helper.form_class = 'form-hori... | from django import forms
from crispy_forms.helper import FormHelper
from crispy_forms.bootstrap import FormActions, Div, AppendedText
from crispy_forms.layout import Layout, Field, HTML, Button, Submit, Reset
class UploadImageForm(forms.Form):
helper = FormHelper()
helper.form_tag = False
helper.form_clas... | Append 'px' to end of image upload form resize field | Append 'px' to end of image upload form resize field
| Python | mit | SPARLab/BikeMaps,SPARLab/BikeMaps,SPARLab/BikeMaps |
90991af1b5c50c106bf18b743c9e29e9aafd5f32 | pony_server/api/urls.py | pony_server/api/urls.py | from django.conf.urls.defaults import *
from piston.resource import Resource
from pony_server.api.handlers import PackageHandler, RootHandler, BuildHandler, TagHandler
package_handler = Resource(PackageHandler)
root_handler = Resource(RootHandler)
build_handler = Resource(BuildHandler)
tag_handler = Resource(TagHandle... | from django.conf.urls.defaults import *
from piston.resource import Resource
from pony_server.api.handlers import PackageHandler, RootHandler, BuildHandler, TagHandler
package_handler = Resource(PackageHandler)
root_handler = Resource(RootHandler)
build_handler = Resource(BuildHandler)
tag_handler = Resource(TagHandle... | Remove package namespace in the URLS since it was useless. | Remove package namespace in the URLS since it was useless. | Python | mit | ericholscher/devmason-server,ericholscher/devmason-server |
2f76c0629ee1ff995718300f268b27cc3bd532f1 | ddsc_api/views.py | ddsc_api/views.py | # (c) Nelen & Schuurmans. MIT licensed, see LICENSE.rst.
from __future__ import print_function, unicode_literals
from __future__ import absolute_import, division
from collections import OrderedDict
from rest_framework.reverse import reverse
from rest_framework.views import APIView
from rest_framework.response import... | # (c) Nelen & Schuurmans. MIT licensed, see LICENSE.rst.
from __future__ import print_function, unicode_literals
from __future__ import absolute_import, division
from collections import OrderedDict
from rest_framework.reverse import reverse
from rest_framework.views import APIView
from rest_framework.response import... | Add collageitems to the view. | Add collageitems to the view.
| Python | mit | ddsc/ddsc-api,ddsc/ddsc-api |
b93644f758baa3f3a4e4ea506e8f0305d6503305 | pathvalidate/_interface.py | pathvalidate/_interface.py | # encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from __future__ import absolute_import, unicode_literals
import abc
from ._common import _validate_null_string, is_pathlike_obj
from ._six import add_metaclass, text_type
@add_metaclass(abc.ABCMeta)
class NameSanitizer(objec... | # encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from __future__ import absolute_import, unicode_literals
import abc
from ._common import _validate_null_string, is_pathlike_obj
from ._six import add_metaclass, text_type
@add_metaclass(abc.ABCMeta)
class NameSanitizer(objec... | Modify a function call argument | Modify a function call argument
| Python | mit | thombashi/pathvalidate |
5d278330812618d55ba4efafcb097e3f5ee6db04 | project/category/views.py | project/category/views.py | from flask import render_template, Blueprint, url_for, \
redirect, flash, request
from project.models import Category, Webinar
category_blueprint = Blueprint('category', __name__,)
@category_blueprint.route('/categories')
def index():
categories = Category.query.all()
return render_template('category/ca... | from flask import render_template, Blueprint, url_for, \
redirect, flash, request
from project.models import Category, Webinar
category_blueprint = Blueprint('category', __name__,)
@category_blueprint.route('/categories')
def index():
categories = Category.query.all()
return render_template('category/ca... | Add basic view to see category show page | Add basic view to see category show page
| Python | mit | dylanshine/streamschool,dylanshine/streamschool |
9689887cbdc59c29c8a13bfa82eb1391ce691631 | zephyr/decorator.py | zephyr/decorator.py | import types
class TornadoAsyncException(Exception): pass
class _DefGen_Return(BaseException):
def __init__(self, value):
self.value = value
def returnResponse(value):
raise _DefGen_Return(value)
def asynchronous(method):
def wrapper(request, *args, **kwargs):
try:
v = method... | import types
class TornadoAsyncException(Exception): pass
class _DefGen_Return(BaseException):
def __init__(self, value):
self.value = value
def returnResponse(value):
raise _DefGen_Return(value)
def asynchronous(method):
def wrapper(request, *args, **kwargs):
try:
v = method... | Copy the csrf_exempt attribute in @asynchronous | Copy the csrf_exempt attribute in @asynchronous
Needed for @csrf_exempt to work.
(imported from commit 563ab11b0d26262511e9a6d9cc2735b0b835a391)
| Python | apache-2.0 | blaze225/zulip,Cheppers/zulip,xuanhan863/zulip,dnmfarrell/zulip,RobotCaleb/zulip,esander91/zulip,wweiradio/zulip,vikas-parashar/zulip,zulip/zulip,luyifan/zulip,grave-w-grave/zulip,amallia/zulip,hafeez3000/zulip,fw1121/zulip,Gabriel0402/zulip,jackrzhang/zulip,umkay/zulip,he15his/zulip,glovebx/zulip,ufosky-server/zulip,T... |
6cb38efab37f8953c8ba56662ba512af0f84432f | tests/semver_test.py | tests/semver_test.py | # -*- coding: utf-8 -*-
from unittest import TestCase
from semver import compare
from semver import match
from semver import parse
class TestSemver(TestCase):
def test_should_parse_version(self):
self.assertEquals(
parse("1.2.3-alpha.1.2+build.11.e0f985a"),
{'major': 1,
... | # -*- coding: utf-8 -*-
from unittest import TestCase
from semver import compare
from semver import match
from semver import parse
class TestSemver(TestCase):
def test_should_parse_version(self):
self.assertEquals(
parse("1.2.3-alpha.1.2+build.11.e0f985a"),
{'major': 1,
... | Add tests for error cases that proves incompatibility with Python 2.5 and early versions. | Add tests for error cases that proves incompatibility with Python 2.5 and early versions.
| Python | bsd-3-clause | python-semver/python-semver,k-bx/python-semver |
c783af3af004ec2de31b85045d1c517f5c3a9ccc | tests/v6/test_date_generator.py | tests/v6/test_date_generator.py | import datetime as dt
from .context import tohu
from tohu.v6.primitive_generators import Date
def test_single_date():
g = Date(start="2018-01-01", end="2018-01-01")
dates = g.generate(100, seed=12345)
assert all([x == dt.date(2018, 1, 1) for x in dates])
def test_date_range():
g = Date(start="1999-... | import datetime as dt
from .context import tohu
from tohu.v6.primitive_generators import Date
def test_single_date():
g = Date(start="2018-01-01", end="2018-01-01")
dates = g.generate(100, seed=12345)
assert all([x == dt.date(2018, 1, 1) for x in dates])
def test_date_range():
g = Date(start="1999-... | Add test for start/end values | Add test for start/end values
| Python | mit | maxalbert/tohu |
50df670d1c338c72d43b39a26ecb31d94d6161d7 | tools/addvariable.py | tools/addvariable.py | #!/usr/bin/env python
import sys
sys.path.append('..')
from cli import *
from optparse import OptionParser
parse = OptionParser()
parse.add_option('-a', '--variable', dest='variables',
help='Add variable',
default=[], action='append', type=str)
parse.add_option('-r', '--random', des... | #!/usr/bin/env python
import sys
sys.path.append('..')
from cli import *
from optparse import OptionParser
parse = OptionParser()
parse.add_option('-a', '--variable', dest='variables',
help='Add variable',
default=[], action='append', type=str)
parse.add_option('-r', '--random', dest=... | Add --list to variable tool. | Tools: Add --list to variable tool.
| Python | agpl-3.0 | MerlijnWajer/SRL-Stats |
55cc4ce70ec5da104ae3078dc0fed023153b3de8 | ForumSite/urls.py | ForumSite/urls.py | from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'ForumSite.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^', include('Forum.urls'), {'forum_id':0}),
url(r'^admi... | from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'ForumSite.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^', include('Forum.urls'), {'forum_id':0}),
url(r'^(?P<... | Test project allow multiple forums | Test project allow multiple forums
| Python | mit | Galbar/django-forum,Galbar/django-forum |
1be9c51d4029c0fa32f7071072c171db42d21c83 | doc-src/index.py | doc-src/index.py | import countershape
from countershape import Page, Directory, PythonModule
import countershape.grok
this.layout = countershape.Layout("_layout.html")
this.markdown = "rst"
ns.docTitle = "Countershape Manual"
ns.docMaintainer = "Aldo Cortesi"
ns.docMaintainerEmail = "dev@nullcube.com"
ns.copyright = "Copyright Nullcub... | import countershape
from countershape import Page, Directory, PythonModule
import countershape.grok
this.layout = countershape.Layout("_layout.html")
this.markdown = "rst"
ns.docTitle = "Countershape Manual"
ns.docMaintainer = "Aldo Cortesi"
ns.docMaintainerEmail = "dev@nullcube.com"
ns.copyright = "Copyright Nullcub... | Move structure to a separate directory | Move structure to a separate directory
| Python | mit | mhils/countershape,cortesi/countershape,samtaufa/countershape,mhils/countershape,cortesi/countershape,samtaufa/countershape |
f0dc0309518e8862ac7ad785d97a485df538b965 | grip/constants.py | grip/constants.py | # The supported extensions, as defined by https://github.com/github/markup
supported_extensions = ['.md', '.markdown']
# The default filenames when no file is provided
default_filenames = map(lambda ext: 'README' + ext, supported_extensions)
| # The supported extensions, as defined by https://github.com/github/markup
supported_extensions = ['.md', '.markdown']
# The default filenames when no file is provided
default_filenames = ['README' + ext for ext in supported_extensions]
| Fix map resolving to empty list on Python 3. | Fix map resolving to empty list on Python 3.
| Python | mit | jbarreras/grip,mgoddard-pivotal/grip,jbarreras/grip,ssundarraj/grip,joeyespo/grip,mgoddard-pivotal/grip,joeyespo/grip,ssundarraj/grip |
2f85d8985bf4089e39d2510190bf6dedea91fe5b | polling_stations/apps/addressbase/migrations/0001_initial.py | polling_stations/apps/addressbase/migrations/0001_initial.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import django.contrib.gis.db.models.fields
class Migration(migrations.Migration):
replaces = [('addressbase', '0001_initial'), ('addressbase', '0002_auto_20160611_1700'), ('addressbase', '0003_auto_20160611_... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import django.contrib.gis.db.models.fields
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Address',
fields=[
... | Convert squashed migration to regular migration | Convert squashed migration to regular migration
This confuses the hell out of me every time
| Python | bsd-3-clause | chris48s/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations,chris48s/UK-Polling-Stations,chris48s/UK-Polling-Stations |
bce11d469177eb4287d9d926b9880e7528bd53c0 | thumbnails/cache_backends.py | thumbnails/cache_backends.py | # -*- coding: utf-8 -*-
class BaseCacheBackend(object):
def get(self, thumbnail_name):
if isinstance(thumbnail_name, list):
thumbnail_name = ''.join(thumbnail_name)
return self._get(thumbnail_name)
def set(self, thumbnail):
thumbnail_name = thumbnail.name
if isins... | # -*- coding: utf-8 -*-
class BaseCacheBackend(object):
def get(self, thumbnail_name):
if isinstance(thumbnail_name, list):
thumbnail_name = ''.join(thumbnail_name)
return self._get(thumbnail_name)
def set(self, thumbnail):
return self._set(thumbnail.name, thumbnail)
... | Remove unecessary code in cache backend _set | Remove unecessary code in cache backend _set
| Python | mit | python-thumbnails/python-thumbnails,relekang/python-thumbnails |
b8e9a572098a5eaccf5aadde1b46bfc51da2face | tests/test_check_step_UDFs.py | tests/test_check_step_UDFs.py | from scripts.check_step_UDFs import CheckStepUDFs
from tests.test_common import TestEPP
from unittest.mock import Mock, patch, PropertyMock
class TestCheckStepUDFs(TestEPP):
def setUp(self):
self.patched_process = patch.object(
CheckStepUDFs,
'process',
new_callable=Pr... | from scripts.check_step_UDFs import CheckStepUDFs
from tests.test_common import TestEPP
from unittest.mock import Mock, patch, PropertyMock
class TestCheckStepUDFs(TestEPP):
def setUp(self):
self.patched_process = patch.object(
CheckStepUDFs,
'process',
new_callable=Pr... | Add test to check sys.exit was called with the expected exit status | Add test to check sys.exit was called with the expected exit status
| Python | mit | EdinburghGenomics/clarity_scripts,EdinburghGenomics/clarity_scripts |
43fc2f23b80083f89ae1e982bfdee5d4e0322556 | tests/test_command_version.py | tests/test_command_version.py | import sys
from twisted.trial import unittest
from twisted.internet import defer
import scrapy
from scrapy.utils.testproc import ProcessTest
class VersionTest(ProcessTest, unittest.TestCase):
command = 'version'
@defer.inlineCallbacks
def test_output(self):
encoding = getattr(sys.stdout, 'encod... | import sys
from twisted.trial import unittest
from twisted.internet import defer
import scrapy
from scrapy.utils.testproc import ProcessTest
class VersionTest(ProcessTest, unittest.TestCase):
command = 'version'
@defer.inlineCallbacks
def test_output(self):
encoding = getattr(sys.stdout, 'encod... | Increase coverage of version command | Increase coverage of version command
| Python | bsd-3-clause | tagatac/scrapy,nowopen/scrapy,hwsyy/scrapy,Lucifer-Kim/scrapy,mlyundin/scrapy,elacuesta/scrapy,KublaikhanGeek/scrapy,Ryezhang/scrapy,github-account-because-they-want-it/scrapy,ENjOyAbLE1991/scrapy,yidongliu/scrapy,famorted/scrapy,avtoritet/scrapy,Preetwinder/scrapy,eLRuLL/scrapy,foromer4/scrapy,godfreyy/scrapy,Kublaikh... |
3a3cb923babfbba4234e646dc40c0a9b6364d207 | apps/announcements/management/commands/tweetannouncements.py | apps/announcements/management/commands/tweetannouncements.py | """
Management command to cross-publish announcements on Twitter.
"""
from django.core.management.base import NoArgsCommand
from ...models import AnnouncementTwitterCrossPublication
class Command(NoArgsCommand):
"""
A management command which cross-publish on Twitter any pending announcements
currently ... | """
Management command to cross-publish announcements on Twitter.
"""
from django.core.management.base import NoArgsCommand
from apps.dbmutex import MutexLock,AlreadyLockedError, LockTimeoutError
from ...models import AnnouncementTwitterCrossPublication
class Command(NoArgsCommand):
"""
A management comman... | Add mutex to the "tweetannouncement" management command. | Add mutex to the "tweetannouncement" management command.
| Python | agpl-3.0 | TamiaLab/carnetdumaker,TamiaLab/carnetdumaker,TamiaLab/carnetdumaker,TamiaLab/carnetdumaker |
cef4c09d59bb5666565cf6d7e7453fc6eb87316d | circuits/app/dropprivileges.py | circuits/app/dropprivileges.py | from pwd import getpwnam
from grp import getgrnam
from traceback import format_exc
from os import getuid, setgroups, setgid, setuid, umask
from circuits.core import handler, BaseComponent
class DropPrivileges(BaseComponent):
def init(self, user="nobody", group="nobody", **kwargs):
self.user = user
... | from pwd import getpwnam
from grp import getgrnam
from traceback import format_exc
from os import getuid, setgroups, setgid, setuid, umask
from circuits.core import handler, BaseComponent
class DropPrivileges(BaseComponent):
def init(self, user="nobody", group="nobody", umask=0o077, **kwargs):
self.use... | Allow to set umask in DropPrivileges | Allow to set umask in DropPrivileges
| Python | mit | eriol/circuits,nizox/circuits,eriol/circuits,eriol/circuits |
897dd874a34ddfc164ea7dbd4bfd5eaffd02aabd | tests/QtUiTools/bug_376.py | tests/QtUiTools/bug_376.py | import unittest
import os
from helper import UsesQApplication
from PySide import QtCore, QtGui
from PySide.QtUiTools import QUiLoader
class BugTest(UsesQApplication):
def testCase(self):
w = QtGui.QWidget()
loader = QUiLoader()
filePath = os.path.join(os.path.dirname(__file__), 'test.ui')... | import unittest
import os
from helper import UsesQApplication
from PySide import QtCore, QtGui
from PySide.QtUiTools import QUiLoader
class BugTest(UsesQApplication):
def testCase(self):
w = QtGui.QWidget()
loader = QUiLoader()
filePath = os.path.join(os.path.dirname(__file__), 'test.ui')... | Replace type() comparison with isinstance. | Replace type() comparison with isinstance.
type() comparison won't work due to weakproxy.
Reviewer: Luciano Wolf <c353ae890f0e6de8473e43011f009ccd38a3c452@openbossa.org>
Reviewer: Hugo Lima <e250cbdf6b5a11059e9d944a6e5e9282be80d14c@openbossa.org>
Reviewer: Renato Filho <16af9705e5a16d85aed275f2f9e8171326ec17f6@openbo... | Python | lgpl-2.1 | gbaty/pyside2,enthought/pyside,RobinD42/pyside,pankajp/pyside,M4rtinK/pyside-android,PySide/PySide,BadSingleton/pyside2,M4rtinK/pyside-bb10,IronManMark20/pyside2,M4rtinK/pyside-android,BadSingleton/pyside2,pankajp/pyside,PySide/PySide,pankajp/pyside,IronManMark20/pyside2,gbaty/pyside2,enthought/pyside,RobinD42/pyside,B... |
adddfdb946ab45a186535ab4dcfc8848cf914dc0 | allmychanges/validators.py | allmychanges/validators.py | import re
from django.core import validators
class URLValidator(validators.URLValidator):
"""Custom url validator to include git urls and urls with http+ like prefixes
"""
regex = re.compile(
r'^(?:(?:(?:(?:http|git|hg|rechttp)\+)?' # optional http+ or git+ or hg+
r'(?:http|ftp|)s?|git... | import re
from django.core import validators
class URLValidator(validators.URLValidator):
"""Custom url validator to include git urls and urls with http+ like prefixes
"""
regex = re.compile(
r'^(?:(?:(?:(?:http|git|hg|rechttp|feed|rss|atom)\+)?' # optional http+ or git+ or hg+
r'(?:ht... | Allow feed, rss, and atom prefixes in URL validator. | Allow feed, rss, and atom prefixes in URL validator.
| Python | bsd-2-clause | AllMyChanges/allmychanges.com,AllMyChanges/allmychanges.com,AllMyChanges/allmychanges.com,AllMyChanges/allmychanges.com |
7e5240967e926c47301318df4833dd9af1fe9c7c | tests/test_address_book.py | tests/test_address_book.py | from unittest import TestCase
class AddressBookTestCase(TestCase):
def test_add_person(self):
person = Person(
'John',
'Doe',
['Russian Federation, Kemerovo region, Kemerovo, Kirova street 23, apt. 42'],
['+79834772053']
)
self.address_book.... | from unittest import TestCase
from address_book import AddressBook, Person
class AddressBookTestCase(TestCase):
def test_add_person(self):
address_book = AddressBook()
person = Person(
'John',
'Doe',
['Russian Federation, Kemerovo region, Kemerovo, Kirova stre... | Update person addition test to create address book inside test func + import needed classes from the package | Update person addition test to create address book inside test func + import needed classes from the package
| Python | mit | dizpers/python-address-book-assignment |
03d695a5ed30dcdfb3941a105318a059b9bd9768 | sorting/insertion_sort.py | sorting/insertion_sort.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
def insertion_sort(a):
for i in range(1, len(a)):
current_val = a[i]
j = i
while j > 0 and a[j-1] > current_val:
a[j] = a[j-1]
j -= 1
a[j] = current_val
return a
if __name__ == '__main__':
d = [34,2,24,12... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
def insertion_sort(a):
for i in range(1, len(a)):
current_val = a[i]
j = i
while j > 0 and a[j-1] > current_val:
a[j] = a[j-1]
j -= 1
a[j] = current_val
return a
def insertion_sort2(a):
for i in range(0, ... | Add two other implement of insertion sort | Add two other implement of insertion sort
| Python | mit | hongta/practice-python,hongta/practice-python |
7a651446413b2391284fd13f7df9b9c6ae1b78a7 | InvenTree/key.py | InvenTree/key.py | # Generate a SECRET_KEY file
import random
import string
import os
fn = 'secret_key.txt'
def generate_key():
return ''.join(random.choices(string.digits + string.ascii_letters + string.punctuation, k=50))
if __name__ == '__main__':
# Ensure key file is placed in same directory as this script
path = os.pat... | # Generate a SECRET_KEY file
import random
import string
import os
fn = 'secret_key.txt'
def generate_key():
options = string.digits + string.ascii_letters + string.punctuation
key = ''.join([random.choice(options) for i in range(50)])
return key
if __name__ == '__main__':
# Ensure key file is plac... | Use random.choice instead of random.choices | Use random.choice instead of random.choices
- Allows compatibility with python3.5
| Python | mit | SchrodingersGat/InvenTree,SchrodingersGat/InvenTree,inventree/InvenTree,inventree/InvenTree,inventree/InvenTree,SchrodingersGat/InvenTree,inventree/InvenTree,SchrodingersGat/InvenTree |
3965aa953fb8a68140531c1f3ab112082b75f343 | netconsole.py | netconsole.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import socket, sys
from datetime import datetime
from threading import Thread
def recv():
global client
while True:
data, client = server.recvfrom(max_size)
sys.stdout.write(data)
def send():
while True :
server_input = sys.stdin.readline()
if server_input ==... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import socket, sys
from datetime import datetime
from threading import Thread
HOST = '' # Symbolic name meaning all available interfaces
PORT = 6666 # Default netconsole client IN Port
def recv():
global client
while True:
data, client = server.recvfrom(max_size)
... | Set Netconsole default listen port to 6666 | Set Netconsole default listen port to 6666
according to linux/Documentation/networking/netconsole.txt
| Python | mit | danielk1031/netconsole |
481c57e552b5d52051a6ce34a836f2db1c41d13f | InstagramAPI/src/http/Response/ReelsTrayFeedResponse.py | InstagramAPI/src/http/Response/ReelsTrayFeedResponse.py | from InstagramAPI.src.http.Response.Objects.Item import Item
from InstagramAPI.src.http.Response.Objects.Tray import Tray
from .Response import Response
class ReelsTrayFeedResponse(Response):
def __init__(self, response):
self.trays = None
if self.STATUS_OK == response['status']:
tra... | from InstagramAPI.src.http.Response.Objects.Item import Item
from InstagramAPI.src.http.Response.Objects.Tray import Tray
from .Response import Response
class ReelsTrayFeedResponse(Response):
def __init__(self, response):
self.trays = None
if self.STATUS_OK == response['status']:
tra... | Make sure that tray items is a list This fixes an exception when tray['items'] is None. The same conditional check is added for response['tray']. | Make sure that tray items is a list
This fixes an exception when tray['items'] is None. The same conditional check is added for response['tray'].
| Python | mit | danleyb2/Instagram-API |
6e1befa9021494f5a63ccf2943570765d5b4c6e6 | SessionManager.py | SessionManager.py | import sublime
import sublime_plugin
from datetime import datetime
from .modules import messages
from .modules import serialize
from .modules import settings
from .modules.session import Session
def plugin_loaded():
settings.load()
def error_message(errno):
sublime.error_message(messages.e... | import sublime
import sublime_plugin
from datetime import datetime
from .modules import messages
from .modules import serialize
from .modules import settings
from .modules.session import Session
def plugin_loaded():
settings.load()
def error_message(errno):
sublime.error_message(messages.e... | Make "is_saveable" a staticmethod of SaveSession | Make "is_saveable" a staticmethod of SaveSession
| Python | mit | Zeeker/sublime-SessionManager |
6b4b51a7f8e89e023c933f99aaa3a8329c05e750 | salt/runners/ssh.py | salt/runners/ssh.py | # utf-8
'''
A Runner module interface on top of the salt-ssh Python API
This allows for programmatic use from salt-api, the Reactor, Orchestrate, etc.
'''
import salt.client.ssh.client
def cmd(
tgt,
fun,
arg=(),
timeout=None,
expr_form='glob',
kwarg=None):
'''
E... | # -*- coding: utf-8 -*-
'''
A Runner module interface on top of the salt-ssh Python API.
This allows for programmatic use from salt-api, the Reactor, Orchestrate, etc.
'''
# Import Python Libs
from __future__ import absolute_import
# Import Salt Libs
import salt.client.ssh.client
def cmd(
tgt,
fun,... | Fix pylint errors that snuck into 2015.2 | Fix pylint errors that snuck into 2015.2
| Python | apache-2.0 | saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt |
82ff9fc32b472acf357166ea823f9e082288e818 | scapy/asn1packet.py | scapy/asn1packet.py | ## This file is part of Scapy
## See http://www.secdev.org/projects/scapy for more informations
## Copyright (C) Philippe Biondi <phil@secdev.org>
## This program is published under a GPLv2 license
"""
Packet holding data in Abstract Syntax Notation (ASN.1).
"""
from packet import *
class ASN1_Packet(Packet):
AS... | ## This file is part of Scapy
## See http://www.secdev.org/projects/scapy for more informations
## Copyright (C) Philippe Biondi <phil@secdev.org>
## This program is published under a GPLv2 license
"""
Packet holding data in Abstract Syntax Notation (ASN.1).
"""
from packet import *
class ASN1_Packet(Packet):
AS... | Add cache support for ASN1_Packet() | Add cache support for ASN1_Packet()
--HG--
branch : fix-padding-after-pull-request-18
| Python | apache-2.0 | mytliulei/Scapy,mytliulei/Scapy |
38be74ac4370ff0f1c30864b037eed3af8cc643f | packagename/__init__.py | packagename/__init__.py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
# Packages may add whatever they like to this file, but
# should keep this content at the top.
# ----------------------------------------------------------------------------
from ._astropy_init import *
# --------------------------------------------------... | # Licensed under a 3-clause BSD style license - see LICENSE.rst
# Packages may add whatever they like to this file, but
# should keep this content at the top.
# ----------------------------------------------------------------------------
from ._astropy_init import *
# --------------------------------------------------... | Add missing import in incantation | Add missing import in incantation | Python | bsd-3-clause | alexrudy/Zeeko,alexrudy/Zeeko |
8f5fdcb2d66d013a5f5e888344704d0a1fbfd881 | flask_limiter/errors.py | flask_limiter/errors.py | """
errors and exceptions
"""
from werkzeug.exceptions import HTTPException
def _patch_werkzeug():
import pkg_resources
if pkg_resources.get_distribution("werkzeug").version < "0.9":
# sorry, for touching your internals :).
import werkzeug._internal # pragma: no cover
werkzeug._interna... | """
errors and exceptions
"""
from distutils.version import LooseVersion
from werkzeug.exceptions import HTTPException
def _patch_werkzeug():
import pkg_resources
werkzeug_version = pkg_resources.get_distribution("werkzeug").version
if LooseVersion(werkzeug_version) < LooseVersion("0.9"):
# sorry,... | Fix version comparison of Werkzeug. | Fix version comparison of Werkzeug.
| Python | mit | alisaifee/flask-limiter,alisaifee/flask-limiter,joshfriend/flask-limiter,joshfriend/flask-limiter |
4a597ff48f5fd22ab1c6317e8ab1e65a887da284 | dosagelib/__pyinstaller/hook-dosagelib.py | dosagelib/__pyinstaller/hook-dosagelib.py | # SPDX-License-Identifier: MIT
# Copyright (C) 2016-2022 Tobias Gruetzmacher
from PyInstaller.utils.hooks import collect_data_files, collect_submodules, copy_metadata
hiddenimports = collect_submodules('dosagelib.plugins')
datas = copy_metadata('dosage') + collect_data_files('dosagelib')
| # SPDX-License-Identifier: MIT
# Copyright (C) 2016-2022 Tobias Gruetzmacher
from PyInstaller.utils.hooks import collect_data_files, collect_submodules, copy_metadata
hiddenimports = ['dosagelib.data'] + collect_submodules('dosagelib.plugins')
datas = copy_metadata('dosage') + collect_data_files('dosagelib')
| Make sure dosagelib.data is importable | PyInstaller: Make sure dosagelib.data is importable
| Python | mit | webcomics/dosage,webcomics/dosage |
f84df81f060746567b611a2071ff1a161fcf3206 | generic_links/models.py | generic_links/models.py | # -*- coding: UTF-8 -*-
from django import VERSION
from django.conf import settings
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.db import models
from django.utils.translation import ugettext_lazy as _
def get_user_model_fk_ref... | # -*- coding: UTF-8 -*-
from django.contrib.auth import get_user_model
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.db import models
from django.utils.translation import ugettext_lazy as _
class GenericLink(models.Model):
"... | Make User model compatible with Django 2.x | Make User model compatible with Django 2.x
| Python | bsd-3-clause | matagus/django-generic-links,matagus/django-generic-links |
ace25952c3590f2b130b064815c90658f4495cb5 | code/marv/marv/app/wsgi.py | code/marv/marv/app/wsgi.py | # -*- coding: utf-8 -*-
#
# Copyright 2016 - 2018 Ternaris.
# SPDX-License-Identifier: AGPL-3.0-only
import os
from marv_cli import setup_logging
setup_logging(os.environ.get('MARV_LOGLEVEL', 'info'))
config = os.environ['MARV_CONFIG']
app_root = os.environ['MARV_APPLICATION_ROOT']
import marv.app
import marv.site
... | # -*- coding: utf-8 -*-
#
# Copyright 2016 - 2018 Ternaris.
# SPDX-License-Identifier: AGPL-3.0-only
import os
from marv_cli import setup_logging
setup_logging(os.environ.get('MARV_LOGLEVEL', 'info'))
config = os.environ['MARV_CONFIG']
app_root = os.environ.get('MARV_APPLICATION_ROOT') or '/'
import marv.app
import... | Make fetching application root from env less error-prone | [marv] Make fetching application root from env less error-prone
| Python | agpl-3.0 | ternaris/marv-robotics,ternaris/marv-robotics |
94a944b01953ed75bfbefbd11ed62ca438cd9200 | accounts/tests/test_models.py | accounts/tests/test_models.py | """accounts app unittests for models
"""
from django.test import TestCase
from django.contrib.auth import get_user_model
USER = get_user_model()
TEST_EMAIL = 'newvisitor@example.com'
class UserModelTest(TestCase):
"""Tests for passwordless user model.
"""
def test_user_valid_with_only_email(self):
... | """accounts app unittests for models
"""
from django.test import TestCase
from django.contrib.auth import get_user_model
from django.core.exceptions import ValidationError
USER = get_user_model()
TEST_EMAIL = 'newvisitor@example.com'
class UserModelTest(TestCase):
"""Tests for passwordless user model.
"""... | Add test for unsupplied email for user model | Add test for unsupplied email for user model
| Python | mit | randomic/aniauth-tdd,randomic/aniauth-tdd |
e52b134704951f4ff66a24e348bd20c5a3e85391 | adhocracy4/filters/filters.py | adhocracy4/filters/filters.py | import django_filters
class PagedFilterSet(django_filters.FilterSet):
"""Removes page parameters from the query when applying filters."""
page_kwarg = 'page'
def __init__(self, data, *args, **kwargs):
if self.page_kwarg in data:
# Create a mutable copy
data = data.copy()
... | import django_filters
class PagedFilterSet(django_filters.FilterSet):
"""Removes page parameters from the query when applying filters."""
page_kwarg = 'page'
def __init__(self, data, *args, **kwargs):
if self.page_kwarg in data:
# Create a mutable copy
data = data.copy()
... | Make constructor of DefaultFilterSet compatible | Make constructor of DefaultFilterSet compatible
- arguments had different names than FilterSet before
| Python | agpl-3.0 | liqd/adhocracy4,liqd/adhocracy4,liqd/adhocracy4,liqd/adhocracy4 |
a450d2ead6a8174fe47fdec5557b85cddef759e8 | analysis/plot-single-trial.py | analysis/plot-single-trial.py | import climate
import lmj.plot
import source
def main(subject):
subj = source.Subject(subject)
trial = subj.blocks[0].trials[0]
trial.load()
ax = lmj.plot.axes(111, projection='3d', aspect='equal')
x, y, z = trial.marker('r-fing-index')
ax.plot(x, z, zs=y)
x, y, z = trial.marker('l-fing-... | import climate
import lmj.plot
import source
import plots
@climate.annotate(
subjects='plot data from these subjects',
marker=('plot data for this mocap marker', 'option'),
trial_num=('plot data for this trial', 'option', None, int),
)
def main(marker='r-fing-index', trial_num=0, *subjects):
with plo... | Expand single-trial plot to include multiple subjects. | Expand single-trial plot to include multiple subjects.
| Python | mit | lmjohns3/cube-experiment,lmjohns3/cube-experiment,lmjohns3/cube-experiment |
691f2f8c1bf9a5e13c66913dcbb205dfdbba8fa8 | tests/core/test_runner/test_yaml_runner.py | tests/core/test_runner/test_yaml_runner.py | from openfisca_core.tools.test_runner import _run_test
from openfisca_core.errors import VariableNotFound
import pytest
class TaxBenefitSystem:
def __init__(self):
self.variables = {}
def get_package_metadata(self):
return {"name": "Test", "version": "Test"}
class Simulation:
def __in... | from openfisca_core.tools.test_runner import _run_test, _get_tax_benefit_system
from openfisca_core.errors import VariableNotFound
import pytest
class TaxBenefitSystem:
def __init__(self):
self.variables = {}
def get_package_metadata(self):
return {"name": "Test", "version": "Test"}
de... | Add unit test for test_runner _get_tax_benefit_system | Add unit test for test_runner _get_tax_benefit_system
| Python | agpl-3.0 | openfisca/openfisca-core,openfisca/openfisca-core |
b700cc013be2236c50937876b974891355842782 | esis/__init__.py | esis/__init__.py | # -*- coding: utf-8 -*-
"""Elastic Search Index & Search."""
__author__ = 'Javier Collado'
__email__ = 'jcollado@nowsecure.com'
__version__ = '0.2.0'
from esis.es import Client
| # -*- coding: utf-8 -*-
"""Elastic Search Index & Search."""
from esis.es import Client
__author__ = 'Javier Collado'
__email__ = 'jcollado@nowsecure.com'
__version__ = '0.2.0'
| Move import to the top of the file | Move import to the top of the file
| Python | mit | jcollado/esis |
128f6f722f14ac1a202559ffe373304928f7c842 | patients/tests/test_views.py | patients/tests/test_views.py | from django.test import TestCase, Client
from should_dsl import should, should_not
from django.db.models.query import QuerySet
class TestVies(TestCase):
def setUp(self):
self.client = Client()
#Valores de testes:
#Testar para 1 Paciente retornado.
#Testar para mais de 1 Paciente retor... | from django.test import TestCase, Client
from should_dsl import should, should_not
from django.db.models.query import QuerySet
from patients.views import search_patient
from patients.models import Paciente
class TestVies(TestCase):
def setUp(self):
self.client = Client()
#Valores de testes:
#Test... | Create assert true in teste_view | Create assert true in teste_view
| Python | mit | msfernandes/anato-hub,msfernandes/anato-hub,msfernandes/anato-hub,msfernandes/anato-hub |
9cfc5c5acf568b56f4f150e3040827e5856b52c2 | insertion_sort.py | insertion_sort.py | def insertion_sort(un_list):
for idx in range(1, len(un_list)):
current = un_list[idx]
position = idx
while position > 0 and un_list[position-1] > current:
un_list[position] = un_list[position-1]
position = position - 1
un_list[position] = current
if __name... | def insertion_sort(un_list):
for idx in range(1, len(un_list)):
current = un_list[idx]
position = idx
while position > 0 and un_list[position-1] > current:
un_list[position] = un_list[position-1]
position = position - 1
un_list[position] = current
if __name... | Update module with timeit testing for best and worst case scenarios. | Update module with timeit testing for best and worst case scenarios.
| Python | mit | jonathanstallings/data-structures |
ce7e025607cbd871bc4840f7ebf3c3af8b8e1881 | flycam.py | flycam.py | import capture
from picamera import PiCamera
import time
def image_cap_loop(camera):
"""Set image parameters, capture image, set wait time, repeat"""
images = 18
status = None
resolution = (854, 480)
latest = capture.cap(camera, resolution, status)
status = latest[0]
size = capture.image... | 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)
latest = capture.cap(camera, resolution, status)
status = latest[0]
size = capture.image_size(latest[1])
... | Adjust day size to 100k. Change status flag placement. | Adjust day size to 100k. Change status flag placement.
| Python | mit | gnfrazier/YardCam |
c7785ff4367de929392b85f73a396e987cfe4606 | apps/chats/models.py | apps/chats/models.py | from django.db import models
from django.contrib.auth.models import User
from django.utils.text import truncate_words
from automatic_timestamps.models import TimestampModel
class Chat(TimestampModel):
"""
A chat is a single or multi-line text excerpt from a chat (usually
purposefully out of context) post... | from django.db import models
from django.contrib.auth.models import User
from django.utils.text import truncate_words
from automatic_timestamps.models import TimestampModel
class Chat(TimestampModel):
"""
A chat is a single or multi-line text excerpt from a chat (usually
purposefully out of context) post... | Add HTML representation of chat | Add HTML representation of chat
| Python | mit | tofumatt/quotes,tofumatt/quotes |
2c74cc83f2060cf0ea6198a955fbbe2f07e2dd05 | apps/chats/models.py | apps/chats/models.py | from django.db import models
from django.contrib.auth.models import User
from django.utils.text import truncate_words
from automatic_timestamps.models import TimestampModel
class Chat(TimestampModel):
"""
A collection of chat items (quotes), ordered by their created_at values,
grouped together like a cha... | from django.db import models
from django.contrib.auth.models import User
from django.utils.text import truncate_words
from automatic_timestamps.models import TimestampModel
class Chat(TimestampModel):
"""
A collection of chat items (quotes), ordered by their created_at values,
grouped together like a cha... | Clean up Quote model code | Clean up Quote model code
| Python | mit | tofumatt/quotes,tofumatt/quotes |
f36baf09fbbe62ff2fef97528f2d00df43797b43 | flow/__init__.py | flow/__init__.py | from model import BaseModel
from feature import Feature, JSONFeature, TextFeature, CompressedFeature, \
PickleFeature
from extractor import Node, Graph, Aggregator, NotEnoughData
from bytestream import ByteStream, ByteStreamFeature
from data import \
IdProvider, UuidProvider, UserSpecifiedIdProvider, KeyBui... | from model import BaseModel
from feature import Feature, JSONFeature, TextFeature, CompressedFeature, \
PickleFeature
from extractor import Node, Graph, Aggregator, NotEnoughData
from bytestream import ByteStream, ByteStreamFeature
from data import \
IdProvider, UuidProvider, UserSpecifiedIdProvider, KeyBui... | Add NumpyFeature to top-level exports | Add NumpyFeature to top-level exports
| Python | mit | JohnVinyard/featureflow,JohnVinyard/featureflow |
41a04ca380dca8d2b358f84bd7982f0ea01ac7f2 | camoco/Config.py | camoco/Config.py | #!/usr/env/python3
import os
import configparser
global cf
cf = configparser.ConfigParser()
cf._interpolation = configparser.ExtendedInterpolation()
cf_file = os.path.expanduser('~/.camoco.conf')
default_config = '''
[options]
basedir = ~/.camoco/
testdir = ~/.camoco/
[logging]
log_level = verbose
[test]
refge... | #!/usr/env/python3
import os
import configparser
global cf
cf = configparser.ConfigParser()
cf._interpolation = configparser.ExtendedInterpolation()
cf_file = os.path.expanduser('~/.camoco.conf')
default_config = '''
[options]
basedir = ~/.camoco/
testdir = ~/.camoco/
[logging]
log_level = verbose
[test]
force... | Add force option for testing. | Add force option for testing.
| Python | mit | schae234/Camoco,schae234/Camoco |
b9a752c8f6ea7fd9ada1ec283b7aaaa2eaf4b271 | src/gui/loggers_ui/urls.py | src/gui/loggers_ui/urls.py | from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.MainPage.as_view(), name='index'),
url(r'^(?P<ses_id>[a-zA-Z0-9]+)/$', views.SessionPage.as_view(),
name='Session'),
url(r'^GlobalMap/$', views.GlobalMap.as_view(),
name='GlobalMap')... | from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.MainPage.as_view(), name='index'),
url(r'^GlobalMap/$', views.GlobalMap.as_view(),
name='GlobalMap'),
url(r'^(?P<ses_id>[a-zA-Z0-9]+)/$', views.SessionPage.as_view(),
name='Session')... | Move global map url before session url. | gui: Move global map url before session url.
| Python | mit | alberand/tserver,alberand/tserver,alberand/tserver,alberand/tserver |
b9d1dcf614faa949975bc5296be451abd2594835 | repository/presenter.py | repository/presenter.py | import logger
import datetime
def out(counter, argv, elapsed_time = None):
sum_lines = sum(counter.values())
blue = '\033[94m'
grey = '\033[0m'
endcolor = '\033[0m'
italic = '\x1B[3m'
eitalic = '\x1B[23m'
template = '{0:>7.2%} {3}{2}{4}'
if argv.show_absolute > 0:
template =... | import logger
import datetime
def out(counter, argv, elapsed_time = None):
sum_lines = sum(counter.values())
blue = '\033[94m'
grey = '\033[0m'
endcolor = '\033[0m'
italic = '\x1B[3m'
eitalic = '\x1B[23m'
template = '{0:>7.2%} {3}{2}{4}'
if argv.show_absolute > 0:
template =... | Fix small issue with `--top-n` command switch | Fix small issue with `--top-n` command switch
| Python | mit | moacirosa/git-current-contributors,moacirosa/git-current-contributors |
94d2fb9241874d7feb89aa6fee6bc14b76e3a441 | grains/grains.py | grains/grains.py | # File: grains.py
# Purpose: Write a program that calculates the number of grains of wheat
# on a chessboard given that the number on each square doubles.
# Programmer: Amal Shehu
# Course: Exercism
# Date: Sunday 18 September 2016, 05:25 PM
| # File: grains.py
# Purpose: Write a program that calculates the number of grains of wheat
# on a chessboard given that the number on each square doubles.
# Programmer: Amal Shehu
# Course: Exercism
# Date: Sunday 18 September 2016, 05:25 PM
board = [x for x in range(1, 65)]
grains... | Add two lists with square and grain numbers | Add two lists with square and grain numbers
| Python | mit | amalshehu/exercism-python |
c833f55999f6fd9029626d1b794c86b2b5b11256 | post_office/test_settings.py | post_office/test_settings.py | # -*- coding: utf-8 -*-
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
},
}
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
'TIMEOUT': 36000,
'KEY_PREFIX': 'post-office',
},
'post_office': {
'BACKEND'... | # -*- coding: utf-8 -*-
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
},
}
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
'TIMEOUT': 36000,
'KEY_PREFIX': 'post-office',
},
'post_office': {
'BACKEND'... | Use "DjangoTestSuiteRunner" to in Django 1.6. | Use "DjangoTestSuiteRunner" to in Django 1.6.
| Python | mit | CasherWest/django-post_office,carrerasrodrigo/django-post_office,fapelhanz/django-post_office,RafRaf/django-post_office,ui/django-post_office,jrief/django-post_office,yprez/django-post_office,JostCrow/django-post_office,ui/django-post_office,LeGast00n/django-post_office,CasherWest/django-post_office,ekohl/django-post_o... |
d8ae8f7bccdbe8eace5bb67b94a75a8003cc30b6 | github/models.py | github/models.py | import json, requests
from wagtail.wagtailadmin.edit_handlers import FieldPanel
from wagtail.wagtailcore.models import Page, Orderable
import django.utils.dateparse as dateparse
from django.db import models
from django.core.cache import cache
class GithubOrgIndexPage(Page):
github_org_name = models.CharField(defa... | import json, requests
from wagtail.wagtailadmin.edit_handlers import FieldPanel
from wagtail.wagtailcore.models import Page, Orderable
import django.utils.dateparse as dateparse
from django.db import models
from django.core.cache import cache
class GithubOrgIndexPage(Page):
github_org_name = models.CharField(defa... | Fix github top_events if events empty | Fix github top_events if events empty
| Python | agpl-3.0 | terotic/devheldev,terotic/devheldev,City-of-Helsinki/devheldev,terotic/devheldev,City-of-Helsinki/devheldev,City-of-Helsinki/devheldev |
9f0e5c941c769c4d7c1cbdfcdcf98ddf643173d0 | cea/interfaces/dashboard/server/__init__.py | cea/interfaces/dashboard/server/__init__.py | """
The /server api blueprint is used by cea-worker processes to manage jobs and files.
"""
from __future__ import print_function
from __future__ import division
from flask import Blueprint
from flask_restplus import Api
from .jobs import api as jobs
from .streams import api as streams
__author__ = "Daren Thomas"
__... | """
The /server api blueprint is used by cea-worker processes to manage jobs and files.
"""
from __future__ import print_function
from __future__ import division
from flask import Blueprint, current_app
from flask_restplus import Api, Resource
from .jobs import api as jobs
from .streams import api as streams
__autho... | Add server alive and shutdown api endpoints | Add server alive and shutdown api endpoints
| Python | mit | architecture-building-systems/CityEnergyAnalyst,architecture-building-systems/CityEnergyAnalyst,architecture-building-systems/CityEnergyAnalyst |
92f98b24eb1718f200ea75874b932e8335dbb35c | frappe/patches/v14_0/set_document_expiry_default.py | frappe/patches/v14_0/set_document_expiry_default.py | import frappe
def execute():
frappe.db.set_value("System Settings", "System Settings", "document_share_key_expiry", 30)
frappe.db.set_value("System Settings", "System Settings", "allow_older_web_view_links", 1)
| import frappe
def execute():
frappe.db.set_value("System Settings", "System Settings", {
"document_share_key_expiry": 30,
"allow_older_web_view_links": 1
})
| Set values in a single query | refactor: Set values in a single query
| Python | mit | StrellaGroup/frappe,yashodhank/frappe,yashodhank/frappe,StrellaGroup/frappe,yashodhank/frappe,frappe/frappe,frappe/frappe,StrellaGroup/frappe,frappe/frappe,yashodhank/frappe |
e9964a0f96777c5aae83349ccde3d14fbd04353b | contrib/generate-gresource-xml.py | contrib/generate-gresource-xml.py | #!/usr/bin/python3
# pylint: disable=invalid-name,missing-docstring
#
# Copyright (C) 2022 Richard Hughes <richard@hughsie.com>
#
# SPDX-License-Identifier: LGPL-2.1+
import sys
import os
import xml.etree.ElementTree as ET
if len(sys.argv) < 2:
print("not enough arguments")
sys.exit(1)
root = ET.Element("gr... | #!/usr/bin/python3
# pylint: disable=invalid-name,missing-docstring
#
# Copyright (C) 2022 Richard Hughes <richard@hughsie.com>
#
# SPDX-License-Identifier: LGPL-2.1+
import sys
import os
import xml.etree.ElementTree as ET
if len(sys.argv) < 2:
print("not enough arguments")
sys.exit(1)
root = ET.Element("gr... | Fix compile when using python 3.7 or older | trivial: Fix compile when using python 3.7 or older
Signed-off-by: Richard Hughes <320bca71fc381a4a025636043ca86e734e31cf8b@hughsie.com>
| Python | lgpl-2.1 | fwupd/fwupd,fwupd/fwupd,fwupd/fwupd,fwupd/fwupd |
cc9aa5c8e612cf4fcd79cbe8f4c1ff64c94b0b0e | saleor/product/views.py | saleor/product/views.py | from __future__ import unicode_literals
from django.http import HttpResponsePermanentRedirect
from django.contrib import messages
from django.shortcuts import get_object_or_404
from django.template.response import TemplateResponse
from django.utils.translation import ugettext as _
from .forms import ProductForm
from ... | from __future__ import unicode_literals
from django.http import HttpResponsePermanentRedirect
from django.contrib import messages
from django.shortcuts import get_object_or_404, redirect
from django.template.response import TemplateResponse
from django.utils.translation import ugettext as _
from .forms import Product... | Add missing redirect after POST in product details | Add missing redirect after POST in product details
| Python | bsd-3-clause | itbabu/saleor,dashmug/saleor,jreigel/saleor,hongquan/saleor,avorio/saleor,UITools/saleor,hongquan/saleor,arth-co/saleor,rchav/vinerack,mociepka/saleor,avorio/saleor,paweltin/saleor,laosunhust/saleor,spartonia/saleor,taedori81/saleor,UITools/saleor,arth-co/saleor,maferelo/saleor,laosunhust/saleor,KenMutemi/saleor,avorio... |
c961fbf4be3152efc10d2d67d2f62fdae047ccab | datapipe/targets/filesystem.py | datapipe/targets/filesystem.py | import os
from ..target import Target
class LocalFile(Target):
def __init__(self, path):
self._path = path
super(LocalFile, self).__init__()
self._timestamp = 0
def identifier(self):
return self._path
def exists(self):
return os.path.exists(self._path)
def pat... | import os
from ..target import Target
class LocalFile(Target):
def __init__(self, path):
self._path = path
super(LocalFile, self).__init__()
if self.exists():
self._memory['timestamp'] = os.path.getmtime(self._path)
else:
self._memory['timestamp'] = 0
de... | Fix unnecessary recomputation of file targets | Fix unnecessary recomputation of file targets
| Python | mit | ibab/datapipe |
9ae5b882b987cd56fe20996733a828171b18aa3a | polygraph/types/tests/test_object_type.py | polygraph/types/tests/test_object_type.py | from collections import OrderedDict
from unittest import TestCase
from graphql.type.definition import GraphQLField, GraphQLObjectType
from graphql.type.scalars import GraphQLString
from polygraph.types.definitions import PolygraphNonNull
from polygraph.types.fields import String
from polygraph.types.object_type impor... | from collections import OrderedDict
from unittest import TestCase
from graphql.type.definition import GraphQLField, GraphQLObjectType
from graphql.type.scalars import GraphQLString
from polygraph.types.definitions import PolygraphNonNull
from polygraph.types.fields import String, Int
from polygraph.types.object_type ... | Add tests around ObjectType Meta | Add tests around ObjectType Meta
| Python | mit | polygraph-python/polygraph |
9cb2bf5d1432bf45666f939356bfe7057d8e5960 | server/mod_auth/auth.py | server/mod_auth/auth.py | from flask import Response
from flask_login import login_user
from server.models import User
from server.login_manager import login_manager
@login_manager.user_loader
def load_user(user_id):
"""Returns a user from the database based on their id"""
return User.query.filter_by(id=user_id).first()
def handle_... | import flask
from flask_login import login_user
from server.models import User
from server.login_manager import login_manager
@login_manager.user_loader
def load_user(user_id: int) -> User:
"""Returns a user from the database based on their id
:param user_id: a users unique id
:return: User object with c... | Add type declartions and docstrings | Add type declartions and docstrings
| Python | mit | ganemone/ontheside,ganemone/ontheside,ganemone/ontheside |
f1b78e050a2b4e8e648e6570c1d2e8688f104899 | bin/pylama/lint/extensions.py | bin/pylama/lint/extensions.py | """Load extensions."""
import os
import sys
CURDIR = os.path.abspath(os.path.dirname(__file__))
sys.path.insert(0, os.path.join(CURDIR, '..', '..', 'deps'))
LINTERS = {}
try:
from pylama.lint.pylama_mccabe import Linter
LINTERS['mccabe'] = Linter()
except ImportError:
pass
try:
from pylama.lint.py... | """Load extensions."""
import os
import sys
CURDIR = os.path.abspath(os.path.dirname(__file__))
sys.path.insert(0, os.path.join(CURDIR, '..', '..', 'deps'))
LINTERS = {}
try:
from pylama.lint.pylama_mccabe import Linter
LINTERS['mccabe'] = Linter()
except ImportError:
pass
try:
from pylama.lint.py... | Fix import Linter from pylam_pylint | Fix import Linter from pylam_pylint
| Python | mit | AtomLinter/linter-pylama |
66d13005993553a849449539e6daf6551a616c4b | indra/sources/isi/__init__.py | indra/sources/isi/__init__.py | """
This module provides an input interface and processor to the ISI reading
system.
The reader is set up to run within a Docker container.
For the ISI reader to run, set the Docker memory and swap space to the maximum.
For processing nxml files, install the nxml2txt utility
(https://github.com/spyysalo/nxml2txt) and ... | """
This module provides an input interface and processor to the ISI reading
system.
The reader is set up to run within a Docker container.
For the ISI reader to run, set the Docker memory and swap space to the maximum.
"""
from .api import process_text, process_nxml, process_preprocessed, \
process_output_folder... | Remove deprecated comment about nxml2text | Remove deprecated comment about nxml2text
| Python | bsd-2-clause | sorgerlab/belpy,sorgerlab/belpy,johnbachman/belpy,johnbachman/belpy,johnbachman/indra,sorgerlab/indra,sorgerlab/belpy,bgyori/indra,johnbachman/indra,sorgerlab/indra,sorgerlab/indra,bgyori/indra,bgyori/indra,johnbachman/belpy,johnbachman/indra |
dadc13021684976599bed4c949d28d9ebd296eb8 | linter.py | linter.py | #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Gavin Elster
# Copyright (c) 2015 Gavin Elster
#
# License: MIT
#
"""This module exports the SlimLint plugin class."""
from SublimeLinter.lint import RubyLinter
class SlimLint(RubyLinter):
"""Provides an inte... | #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Gavin Elster
# Copyright (c) 2015 Gavin Elster
#
# License: MIT
#
"""This module exports the SlimLint plugin class."""
import os
from SublimeLinter.lint import RubyLinter, util
class SlimLint(RubyLinter):
"""... | Add functionality to find rubocop config | Add functionality to find rubocop config
Once it's found, we set it as an environment variable for the rubocop
linter to pick up.
| Python | mit | elstgav/SublimeLinter-slim-lint |
d0f67d9ac8236e83a77b84e33ba7217c7e8f67b9 | bird/utils.py | bird/utils.py | def noise_mask(spectrogram):
print("noise_mask is undefined")
def structure_mask(spectrogram):
print("structure_mask is undefined")
def extract_signal(mask, spectrogram):
print("extract_signal is undefined")
| import numpy as np
import os
import sys
import subprocess
import wave
import wave
from scipy import signal
from scipy import fft
from matplotlib import pyplot as plt
MLSP_DATA_PATH="/home/darksoox/gits/bird-species-classification/mlsp_contest_dataset/"
def noise_mask(spectrogram):
print("noise_mask is undefined")... | Add draft of spectrogram computions. | Add draft of spectrogram computions.
| Python | mit | johnmartinsson/bird-species-classification,johnmartinsson/bird-species-classification |
09b5a3f531a3d0498aae21f2c8014b77df5f8d41 | version.py | version.py | # Update uProxy version in all relevant places.
#
# Run with:
# python version.py <new version>
# e.g. python version.py 0.8.10
import json
import collections
import sys
import re
manifest_files = [
'src/chrome/app/dist_build/manifest.json',
'src/chrome/app/dev_build/manifest.json',
'src... | # Update uProxy version in all relevant places.
#
# Run with:
# python version.py <new version>
# e.g. python version.py 0.8.10
import json
import collections
import sys
import re
manifest_files = [
'src/chrome/app/manifest.json',
'src/chrome/extension/manifest.json',
'src/firefox/packag... | Update manifest files being bumped. | Update manifest files being bumped.
| Python | apache-2.0 | itplanes/uproxy,chinarustin/uproxy,uProxy/uproxy,dhkong88/uproxy,dhkong88/uproxy,MinFu/uproxy,itplanes/uproxy,jpevarnek/uproxy,dhkong88/uproxy,jpevarnek/uproxy,chinarustin/uproxy,roceys/uproxy,roceys/uproxy,dhkong88/uproxy,uProxy/uproxy,uProxy/uproxy,qida/uproxy,chinarustin/uproxy,roceys/uproxy,chinarustin/uproxy,MinFu... |
b022b2f017ed102d8e194427b92dce8cdc8918f9 | manage.py | manage.py | #!/usr/bin/env python
"""
Run the Varda REST server.
To setup the database:
create database varda;
create database vardacelery;
create database vardaresults;
grant all privileges on varda.* to varda@localhost identified by 'varda';
grant all privileges on vardacelery.* to varda@localhost identifie... | #!/usr/bin/env python
"""
Run the Varda REST server.
To setup the database:
create database varda;
create database vardacelery;
create database vardaresults;
grant all privileges on varda.* to varda@localhost identified by 'varda';
grant all privileges on vardacelery.* to varda@localhost identifie... | Add note on Varda server start | Add note on Varda server start
| Python | mit | varda/varda,sndrtj/varda |
50130fa011104806cc66331fe5a6ebc3f98c9d5c | vistrails/packages/tej/widgets.py | vistrails/packages/tej/widgets.py | from __future__ import division
from PyQt4 import QtGui
from vistrails.gui.modules.source_configure import SourceConfigurationWidget
class ShellSourceConfigurationWidget(SourceConfigurationWidget):
"""Configuration widget for SubmitShellJob.
Allows the user to edit a shell script that will be run on the se... | from __future__ import division
from vistrails.gui.modules.source_configure import SourceConfigurationWidget
from vistrails.gui.modules.string_configure import TextEditor
class ShellSourceConfigurationWidget(SourceConfigurationWidget):
"""Configuration widget for SubmitShellJob.
Allows the user to edit a sh... | Use smart text editor in tej.SubmitShellJob | Use smart text editor in tej.SubmitShellJob
| Python | bsd-3-clause | minesense/VisTrails,VisTrails/VisTrails,hjanime/VisTrails,hjanime/VisTrails,hjanime/VisTrails,minesense/VisTrails,VisTrails/VisTrails,hjanime/VisTrails,minesense/VisTrails,VisTrails/VisTrails,VisTrails/VisTrails,minesense/VisTrails,minesense/VisTrails,hjanime/VisTrails,VisTrails/VisTrails |
09c24ac93b6e697b48c52b614fe92f7978fe2320 | linter.py | linter.py | #
# linter.py
# Linter for SublimeLinter4, a code checking framework for Sublime Text 3
#
# Written by Jack Cherng
# Copyright (c) 2017-2019 jfcherng
#
# License: MIT
#
from SublimeLinter.lint import Linter
import sublime
class Iverilog(Linter):
# http://www.sublimelinter.com/en/stable/linter_attributes.html
... | #
# linter.py
# Linter for SublimeLinter4, a code checking framework for Sublime Text 3
#
# Written by Jack Cherng
# Copyright (c) 2017-2019 jfcherng
#
# License: MIT
#
from SublimeLinter.lint import Linter
import sublime
class Iverilog(Linter):
# http://www.sublimelinter.com/en/stable/linter_attributes.html
... | Add iverilog flags reference URL | Add iverilog flags reference URL
Signed-off-by: Jack Cherng <159f0f32a62cc912ca55f89bb5e06807cf019bc7@gmail.com>
| Python | mit | jfcherng/SublimeLinter-contrib-iverilog,jfcherng/SublimeLinter-contrib-iverilog |
db41b744b4fea9d16ad53cb7915ddee5ddcffed0 | scheduler.py | scheduler.py | import logging
import os
from apscheduler.schedulers.blocking import BlockingScheduler
from raven.base import Client as RavenClient
import warner
import archiver
import announcer
import flagger
raven_client = RavenClient()
logger = logging.getLogger(__name__)
# When testing changes, set the "TEST_SCHEDULE" envvar... | import logging
import os
from apscheduler.schedulers.blocking import BlockingScheduler
from raven.base import Client as RavenClient
import warner
import archiver
import announcer
import flagger
raven_client = RavenClient()
logger = logging.getLogger(__name__)
# When testing changes, set the "TEST_SCHEDULE" envvar... | Revert "Re-raise even when capturing by Sentry" | Revert "Re-raise even when capturing by Sentry"
This reverts commit 3fe290fe02390e79910e7ded87070d6e03a705a5.
| Python | apache-2.0 | randsleadershipslack/destalinator,royrapoport/destalinator,royrapoport/destalinator,randsleadershipslack/destalinator,TheConnMan/destalinator,TheConnMan/destalinator |
11f758dc6c4ee3b64d47ac133c4b7f57cd4fc25b | contrib/performance/report.py | contrib/performance/report.py | import sys, pickle
def main():
statistics = pickle.load(file(sys.argv[1]))
if len(sys.argv) == 2:
print 'Available benchmarks'
print '\t' + '\n\t'.join(statistics.keys())
return
statistics = statistics[sys.argv[2]]
if len(sys.argv) == 3:
print 'Available parameters'
... | import sys, pickle
from benchlib import select
def main():
if len(sys.argv) < 5:
print 'Usage: %s <datafile> <benchmark name> <parameter value> <metric> [command]' % (sys.argv[0],)
else:
stat, samples = select(pickle.load(file(sys.argv[1])), *sys.argv[2:5])
if len(sys.argv) == 5:
... | Use stats.select() instead of re-implementing all of this. | Use stats.select() instead of re-implementing all of this.
This is preparation for being able to squash statistics in different ways.
git-svn-id: 81e381228600e5752b80483efd2b45b26c451ea2@6563 e27351fd-9f3e-4f54-a53b-843176b1656c
| Python | apache-2.0 | trevor/calendarserver,trevor/calendarserver,trevor/calendarserver |
76f0e242341aba7ce57f50d3d13f2e0da1dcb750 | cycli/buffer.py | cycli/buffer.py | from prompt_toolkit.buffer import Buffer
from prompt_toolkit.filters import Condition
class CypherBuffer(Buffer):
def __init__(self, *args, **kwargs):
@Condition
def is_multiline():
text = self.document.text
return not self.user_wants_out(text)
super(self.__class_... | from prompt_toolkit.buffer import Buffer
from prompt_toolkit.filters import Condition
class CypherBuffer(Buffer):
def __init__(self, *args, **kwargs):
@Condition
def is_multiline():
text = self.document.text
return not self.user_wants_out(text)
super(self.__class_... | Allow double return to execute query | Allow double return to execute query
If there’s a double return the text will end with “\n”. Closes #5.
| Python | mit | nicolewhite/cycli,nicolewhite/cycli,ikwattro/cycli |
746c3a55b5935199a293f05d042c0029029d970a | planetstack/openstack_observer/steps/sync_images.py | planetstack/openstack_observer/steps/sync_images.py | import os
import base64
from django.db.models import F, Q
from xos.config import Config
from observer.openstacksyncstep import OpenStackSyncStep
from core.models.image import Image
class SyncImages(OpenStackSyncStep):
provides=[Image]
requested_interval=0
observes=Image
def fetch_pending(self, deleted... | import os
import base64
from django.db.models import F, Q
from xos.config import Config
from observer.openstacksyncstep import OpenStackSyncStep
from core.models.image import Image
class SyncImages(OpenStackSyncStep):
provides=[Image]
requested_interval=0
observes=Image
def fetch_pending(self, deleted... | Check the existence of the images_path | Check the existence of the images_path
ERROR:planetstack.log:[Errno 2] No such file or directory: '/opt/xos/images' BEG TRACEBACK
Traceback (most recent call last):
File "/opt/xos/observer/event_loop.py", line 349, in sync
failed_objects = sync_step(failed=list(self.failed_step_objects), deletion=deletion)
Fil... | Python | apache-2.0 | open-cloud/xos,cboling/xos,opencord/xos,cboling/xos,zdw/xos,open-cloud/xos,opencord/xos,zdw/xos,cboling/xos,cboling/xos,cboling/xos,zdw/xos,open-cloud/xos,zdw/xos,opencord/xos |
22de2eb4263de87f93f243af8200029e08da37db | tests/test_cli_bands.py | tests/test_cli_bands.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Author: Dominik Gresch <greschd@gmx.ch>
import os
import pytest
import tempfile
import numpy as np
import bandstructure_utils as bs
from click.testing import CliRunner
import tbmodels
from tbmodels._cli import cli
from parameters import SAMPLES_DIR
def test_cli_ban... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Author: Dominik Gresch <greschd@gmx.ch>
import os
import pytest
import tempfile
import numpy as np
import bandstructure_utils as bs
from click.testing import CliRunner
import tbmodels
from tbmodels._cli import cli
from parameters import SAMPLES_DIR
def test_cli_ban... | Add absolute tolerance to allclose test | Add absolute tolerance to allclose test
| Python | apache-2.0 | Z2PackDev/TBmodels,Z2PackDev/TBmodels |
2c8077039573296ecbc31ba9b7c5d6463cf39124 | cmakelists_parsing/parsing.py | cmakelists_parsing/parsing.py | # -*- coding: utf-8 -*-
'''A CMakeLists parser using funcparserlib.
The parser is based on [examples of the CMakeLists format][1].
[1]: http://www.vtk.org/Wiki/CMake/Examples
'''
from __future__ import unicode_literals, print_function
import re
import pypeg2 as p
import list_fix
class Arg(p.str):
grammar = ... | # -*- coding: utf-8 -*-
'''A CMakeLists parser using funcparserlib.
The parser is based on [examples of the CMakeLists format][1].
[1]: http://www.vtk.org/Wiki/CMake/Examples
'''
from __future__ import unicode_literals, print_function
import re
import pypeg2 as p
import list_fix
class Arg(p.str):
grammar = ... | Fix up output by including endls. | Fix up output by including endls.
| Python | apache-2.0 | wjwwood/parse_cmake,ijt/cmakelists_parsing |
050319a4a5257b8f98d5dfcb1651b6b6f50a5b98 | pysqli/core/__init__.py | pysqli/core/__init__.py | #-*- coding:utf-8 -*-
## @package Core
# Core module contains everything required to SQLinject.
# @author Damien "virtualabs" Cauquil <virtualabs@gmail.com>
from context import Context, InbandContext, BlindContext
from dbms import DBMS, allow, dbms
from injector import GetInjector, PostInjector, CookieInjector, UserA... | #-*- coding:utf-8 -*-
## @package Core
# Core module contains everything required to SQLinject.
# @author Damien "virtualabs" Cauquil <virtualabs@gmail.com>
from context import Context, InbandContext, BlindContext
from dbms import DBMS, allow, dbms
from injector import GetInjector, PostInjector, CookieInjector, UserA... | Fix a regression inserted previously. | Fix a regression inserted previously.
| Python | mit | sysdream/pysqli,sysdream/pysqli |
bb5f027fa6573c913d90fa91d9920b40d48fbe62 | flask-app/nickITAPI/app.py | flask-app/nickITAPI/app.py | from flask import Flask, Response
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello, World!'
@app.route('/<id>')
def example(id=None):
resp = Response(id)
resp.headers['Access-Control-Allow-Origin'] = 'http://localhost:3000'
return resp
| from flask import Flask, Response
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello, World!'
@app.route('/search/<query>')
def example(query=None):
resp = Response(id)
resp.headers['Access-Control-Allow-Origin'] = 'http://localhost:3000'
return resp
| Add query capture in flask. | Add query capture in flask.
| Python | mit | cthit/nickIT,cthit/nickIT,cthit/nickIT |
ed64d0611ccf047c1da8ae85d13c89c77dfe1930 | packages/grid/backend/grid/tests/utils/auth.py | packages/grid/backend/grid/tests/utils/auth.py | # stdlib
from typing import Dict
# third party
from fastapi import FastAPI
from httpx import AsyncClient
async def authenticate_user(
app: FastAPI, client: AsyncClient, email: str, password: str
) -> Dict[str, str]:
user_login = {"email": email, "password": password}
res = await client.post(app.url_path_... | # stdlib
from typing import Dict
# third party
from fastapi import FastAPI
from httpx import AsyncClient
OWNER_EMAIL = "info@openmined.org"
OWNER_PWD = "changethis"
async def authenticate_user(
app: FastAPI, client: AsyncClient, email: str, password: str
) -> Dict[str, str]:
user_login = {"email": email, "p... | ADD constant test variables OWNER_EMAIL / OWNER_PWD | ADD constant test variables OWNER_EMAIL / OWNER_PWD
| Python | apache-2.0 | OpenMined/PySyft,OpenMined/PySyft,OpenMined/PySyft,OpenMined/PySyft |
fb3a0db023161fbf5b08147dfac1b56989918bf6 | tvseries/core/models.py | tvseries/core/models.py | from tvseries.ext import db
class TVSerie(db.Model):
__table_args__ = {'sqlite_autoincrement': True}
id = db.Column(db.Integer(),
nullable=False, unique=True,
autoincrement=True, primary_key=True)
name = db.Column(db.String(50), unique=True, nullable=False)
descri... | from tvseries.ext import db
class TVSerie(db.Model):
id = db.Column(db.Integer(),
nullable=False, unique=True,
autoincrement=True, primary_key=True)
name = db.Column(db.String(50), unique=True, nullable=False)
description = db.Column(db.Text, nullable=True)
episod... | Remove autoincrement sqlite paramether from model | Remove autoincrement sqlite paramether from model
| Python | mit | rafaelhenrique/flask_tutorial,python-sorocaba/flask_tutorial,python-sorocaba/flask_tutorial,rafaelhenrique/flask_tutorial,python-sorocaba/flask_tutorial |
72045f86b25b396160e1a4c9237e977ed575afb2 | apps/catalogue/constants.py | apps/catalogue/constants.py | # -*- coding: utf-8 -*-
# This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
# Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
#
from django.utils.translation import ugettext_lazy as _
LICENSES = {
'http://creativecommons.org/licenses/by-sa/3.0/': {
'icon'... | # -*- coding: utf-8 -*-
# This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
# Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
#
from django.utils.translation import ugettext_lazy as _
LICENSES = {
'http://creativecommons.org/licenses/by-sa/3.0/': {
'icon'... | Support for 'deed.pl' license URL. | Support for 'deed.pl' license URL.
| Python | agpl-3.0 | fnp/wolnelektury,fnp/wolnelektury,fnp/wolnelektury,fnp/wolnelektury |
c830e66431dab010309b4ad92ef38c418ec7029b | models.py | models.py | import datetime
from flask import url_for
from Simpoll import db
class Poll(db.Document):
created_at = db.DateTimeField(default=datetime.datetime.now, required=True)
question = db.StringField(max_length=255, required=True)
option1 = db.StringField(max_length=255, required=True)
option2 = db.StringFiel... | import datetime
from flask import url_for
from Simpoll import db
class Poll(db.Document):
created_at = db.DateTimeField(default=datetime.datetime.now, required=True)
question = db.StringField(max_length=255, required=True)
option1 = db.StringField(max_length=255, required=True)
option2 = db.StringFiel... | Add default votes and topscores | Add default votes and topscores
| Python | mit | dpuleri/simpoll_backend,dpuleri/simpoll_backend,dpuleri/simpoll_backend,dpuleri/simpoll_backend |
041afe6cec2fadd37b8e18fb1ac8a01cf9050dbf | xpserver_api/urls.py | xpserver_api/urls.py | from xpserver_api import views
from django.conf.urls import url, include
from rest_framework import routers
from xpserver_api.serializers import UserViewSet
router = routers.DefaultRouter()
router.register(r'users', UserViewSet)
urlpatterns = [
url(r'^', include(router.urls)),
url(r'^activate_account/$', view... | from xpserver_api import views
from django.conf.urls import url, include
from rest_framework import routers
from xpserver_api.serializers import UserViewSet
router = routers.DefaultRouter()
router.register(r'users', UserViewSet)
urlpatterns = [
url(r'^', include(router.urls)),
url(r'^api-auth/', include('rest... | Add login/logout for DRF web interface | Add login/logout for DRF web interface
| Python | mit | xp2017-hackergarden/server,xp2017-hackergarden/server,xp2017-hackergarden/server,xp2017-hackergarden/server |
c7f91d43fc833e43f20c3412ed1fe89c84a39704 | forumuser/tests/test_views.py | forumuser/tests/test_views.py | from django.core.urlresolvers import reverse
from forumuser.tests.factories import UserFactory
from thatforum.test_helpers import ThatForumTestCase
class TestUserListView(ThatForumTestCase):
def setUp(self):
self.user = UserFactory()
self.list_url = reverse('user:list')
def test_non_logged_i... | from django.core.urlresolvers import reverse
from forumuser.tests.factories import UserFactory
from thatforum.test_helpers import ThatForumTestCase
class TestUserListView(ThatForumTestCase):
def setUp(self):
self.user = UserFactory()
self.list_url = reverse('user:list')
def test_non_logged_i... | Remove logged in user test from forumuser | Remove logged in user test from forumuser
| Python | mit | hellsgate1001/thatforum_django,hellsgate1001/thatforum_django,hellsgate1001/thatforum_django |
2546bb13065f35f4ddbfee76c63717e0692beabf | rst2pdf/utils.py | rst2pdf/utils.py | #$HeadURL$
#$LastChangedDate$
#$LastChangedRevision$
import sys
from reportlab.platypus import PageBreak, Spacer
from flowables import *
import shlex
from log import log
def parseRaw (data):
'''Parse and process a simple DSL to handle creation of flowables.
Supported (can add others on request):
... | # -*- coding: utf-8 -*-
#$HeadURL$
#$LastChangedDate$
#$LastChangedRevision$
import sys
from reportlab.platypus import PageBreak, Spacer
from flowables import *
import shlex
from log import log
def parseRaw (data):
'''Parse and process a simple DSL to handle creation of flowables.
Supported (can... | Fix encoding (thanks to Yasushi Masuda) | Fix encoding (thanks to Yasushi Masuda)
| Python | mit | rst2pdf/rst2pdf,pombreda/rst2pdf,rst2pdf/rst2pdf,liuyi1112/rst2pdf,liuyi1112/rst2pdf,pombreda/rst2pdf |
e7a4402736518ae27cc87d4cdb22d411de2fc301 | packages/mono.py | packages/mono.py | class MonoPackage (Package):
def __init__ (self):
Package.__init__ (self, 'mono', '2.10',
sources = [
'http://ftp.novell.com/pub/%{name}/sources/%{name}/%{name}-%{version}.tar.bz2',
'patches/mono-runtime-relocation.patch'
],
configure_flags = [
'--with-jit=yes',
'--with-ikvm=no',
'--with... | class MonoPackage (Package):
def __init__ (self):
Package.__init__ (self, 'mono', '2.10',
sources = [
'http://ftp.novell.com/pub/%{name}/sources/%{name}/%{name}-%{version}.tar.bz2',
'patches/mono-runtime-relocation.patch'
],
configure_flags = [
'--with-jit=yes',
'--with-ikvm=no',
'--with... | Fix shell syntax for non bash shells | Fix shell syntax for non bash shells
The custom make command in mono.py is executed with the default shell,
which on some systems doesn't support the fancy for loop syntax, like
dash on Ubuntu.
| Python | mit | mono/bockbuild,BansheeMediaPlayer/bockbuild,BansheeMediaPlayer/bockbuild,bl8/bockbuild,mono/bockbuild,BansheeMediaPlayer/bockbuild,bl8/bockbuild,bl8/bockbuild |
99f53e007aac85aba162136dfa8ce131c965308b | pale/__init__.py | pale/__init__.py | import inspect
import types
import adapters
import arguments
import config
import context
from endpoint import Endpoint
from resource import NoContentResource, Resource, ResourceList
ImplementationModule = "_pale__api_implementation"
def is_pale_module(obj):
is_it = isinstance(obj, types.ModuleType) and \
... | import inspect
import types
from . import adapters
from . import arguments
from . import config
from . import context
from .endpoint import Endpoint
from .resource import NoContentResource, Resource, ResourceList
ImplementationModule = "_pale__api_implementation"
def is_pale_module(obj):
is_it = isinstance(obj, ... | Add dots to pale things | Add dots to pale things
| Python | mit | Loudr/pale |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.