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
a87d927acc42ba2fe4a82004ce919882024039a9
kboard/board/forms.py
kboard/board/forms.py
from django import forms from django.forms.utils import ErrorList from django_summernote.widgets import SummernoteWidget from .models import Post EMPTY_TITLE_ERROR = "์ œ๋ชฉ์„ ์ž…๋ ฅํ•˜์„ธ์š”" EMPTY_CONTENT_ERROR = "๋‚ด์šฉ์„ ์ž…๋ ฅํ•˜์„ธ์š”" class DivErrorList(ErrorList): def __str__(self): return self.as_divs() def as_divs(sel...
from django import forms from django.forms.utils import ErrorList from django_summernote.widgets import SummernoteWidget from .models import Post EMPTY_TITLE_ERROR = "์ œ๋ชฉ์„ ์ž…๋ ฅํ•˜์„ธ์š”" EMPTY_CONTENT_ERROR = "๋‚ด์šฉ์„ ์ž…๋ ฅํ•˜์„ธ์š”" class DivErrorList(ErrorList): def __str__(self): return self.as_divs() def as_divs(sel...
Remove unnecessary attrs 'name' in title
Remove unnecessary attrs 'name' in title
Python
mit
hyesun03/k-board,cjh5414/kboard,guswnsxodlf/k-board,hyesun03/k-board,darjeeling/k-board,cjh5414/kboard,kboard/kboard,kboard/kboard,kboard/kboard,guswnsxodlf/k-board,hyesun03/k-board,cjh5414/kboard,guswnsxodlf/k-board
c39163bd6e91ca17f123c5919885b90105efc7c4
SimPEG/Mesh/__init__.py
SimPEG/Mesh/__init__.py
from TensorMesh import TensorMesh from CylMesh import CylMesh from Cyl1DMesh import Cyl1DMesh from LogicallyRectMesh import LogicallyRectMesh from TreeMesh import TreeMesh
from TensorMesh import TensorMesh from CylMesh import CylMesh from Cyl1DMesh import Cyl1DMesh from LogicallyRectMesh import LogicallyRectMesh from TreeMesh import TreeMesh from BaseMesh import BaseMesh
Add BaseMesh to the init file.
Add BaseMesh to the init file.
Python
mit
simpeg/discretize,simpeg/simpeg,simpeg/discretize,simpeg/discretize
ee649468df406877ccc51a1042e5657f11caa57d
oauthenticator/tests/test_openshift.py
oauthenticator/tests/test_openshift.py
from pytest import fixture, mark from ..openshift import OpenShiftOAuthenticator from .mocks import setup_oauth_mock def user_model(username): """Return a user model""" return { 'metadata': { 'name': username, } } @fixture def openshift_client(client): setup_oauth_mock(...
from pytest import fixture, mark from ..openshift import OpenShiftOAuthenticator from .mocks import setup_oauth_mock def user_model(username): """Return a user model""" return { 'metadata': { 'name': username, } } @fixture def openshift_client(client): setup_oauth_mock(...
Update test harness to use new REST API path for OpenShift.
Update test harness to use new REST API path for OpenShift.
Python
bsd-3-clause
minrk/oauthenticator,NickolausDS/oauthenticator,jupyter/oauthenticator,jupyter/oauthenticator,maltevogl/oauthenticator,jupyterhub/oauthenticator
47970281f9cdf10f8429cfb88c7fffc3c9c27f2a
python/testData/inspections/PyArgumentListInspection/dictFromKeys.py
python/testData/inspections/PyArgumentListInspection/dictFromKeys.py
print(dict.fromkeys(<warning descr="Parameter 'seq' unfilled">)</warning>) print(dict.fromkeys(['foo', 'bar']))
print(dict.fromkeys(<warning descr="Parameter(s) unfilledPossible callees:dict.fromkeys(seq: Sequence[TypeVar('_T')])dict.fromkeys(seq: Sequence[TypeVar('_T')], value: TypeVar('_S'))">)</warning>) print(dict.fromkeys(['foo', 'bar']))
Fix test data for PyArgumentListInspectionTest.testDictFromKeys.
Fix test data for PyArgumentListInspectionTest.testDictFromKeys.
Python
apache-2.0
signed/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,da1z/intellij-community,allotria/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-communi...
64d00e0c17855baaef6562c08f26f30b17ce38bf
panopticon/gtkvlc.py
panopticon/gtkvlc.py
"""Container classes for VLC under GTK""" import gtk import sys # pylint: disable-msg=R0904 class VLCSlave(gtk.DrawingArea): """VLCSlave provides a playback window with an underlying player Its player can be controlled through the 'player' attribute, which is a vlc.MediaPlayer() instance. """ def...
"""Container classes for VLC under GTK""" import gtk import sys # pylint: disable-msg=R0904 class VLCSlave(gtk.DrawingArea): """VLCSlave provides a playback window with an underlying player Its player can be controlled through the 'player' attribute, which is a vlc.MediaPlayer() instance. """ def...
Refactor and add playback funcs.
Refactor and add playback funcs.
Python
agpl-3.0
armyofevilrobots/Panopticon
d608ba0892da052f2515d6796e88013c0730dc0b
corehq/ex-submodules/auditcare/management/commands/gdpr_scrub_user_auditcare.py
corehq/ex-submodules/auditcare/management/commands/gdpr_scrub_user_auditcare.py
from __future__ import absolute_import from __future__ import unicode_literals from corehq.util.log import with_progress_bar from corehq.util.couch import iter_update, DocUpdate from django.core.management.base import BaseCommand from auditcare.utils.export import navigation_event_ids_by_user import logging from auditc...
from __future__ import absolute_import from __future__ import unicode_literals from corehq.util.log import with_progress_bar from corehq.util.couch import iter_update, DocUpdate from django.core.management.base import BaseCommand from auditcare.utils.export import navigation_event_ids_by_user import logging from auditc...
Update dict instead of doc
Update dict instead of doc
Python
bsd-3-clause
dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq
a96eae8333104f11974f8944f93c66c0f70275d7
telemetry/telemetry/core/platform/power_monitor/ippet_power_monitor_unittest.py
telemetry/telemetry/core/platform/power_monitor/ippet_power_monitor_unittest.py
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import logging import unittest from telemetry import decorators from telemetry.core.platform import win_platform_backend from telemetry.core.platform.power_...
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import logging import unittest from telemetry import decorators from telemetry.core.platform import win_platform_backend from telemetry.core.platform.power_...
Disable IppetPowerMonitorTest.testFindOrInstallIppet which is failing on new trybots.
Disable IppetPowerMonitorTest.testFindOrInstallIppet which is failing on new trybots. BUG=424027 TBR=dtu@chromium.org Review URL: https://codereview.chromium.org/643763005 Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#299833}
Python
bsd-3-clause
catapult-project/catapult,catapult-project/catapult-csm,sahiljain/catapult,benschmaus/catapult,SummerLW/Perf-Insight-Report,catapult-project/catapult-csm,catapult-project/catapult-csm,benschmaus/catapult,catapult-project/catapult,sahiljain/catapult,catapult-project/catapult-csm,SummerLW/Perf-Insight-Report,catapult-pro...
568dce643d9e88ebd9e5b395accb3027e02febb7
backend/conferences/models/duration.py
backend/conferences/models/duration.py
from django.core.validators import MinValueValidator from django.db import models from django.utils.translation import ugettext_lazy as _ class Duration(models.Model): conference = models.ForeignKey( "conferences.Conference", on_delete=models.CASCADE, verbose_name=_("conference"), ...
from django.core.validators import MinValueValidator from django.db import models from django.utils.translation import ugettext_lazy as _ class Duration(models.Model): conference = models.ForeignKey( "conferences.Conference", on_delete=models.CASCADE, verbose_name=_("conference"), ...
Fix Duration.__str__ to show Conference name and code
Fix Duration.__str__ to show Conference name and code
Python
mit
patrick91/pycon,patrick91/pycon
f909d0a49e0e455e34673f2b6efc517bc76738d2
build/fbcode_builder/specs/fbthrift.py
build/fbcode_builder/specs/fbthrift.py
#!/usr/bin/env python # Copyright (c) Facebook, Inc. and its affiliates. from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import specs.folly as folly import specs.fizz as fizz import specs.rsocket as rsocket import spec...
#!/usr/bin/env python # Copyright (c) Facebook, Inc. and its affiliates. from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import specs.folly as folly import specs.fizz as fizz import specs.rsocket as rsocket import spec...
Cut fbcode_builder dep for thrift on krb5
Cut fbcode_builder dep for thrift on krb5 Summary: [Thrift] Cut `fbcode_builder` dep for `thrift` on `krb5`. In the past, Thrift depended on Kerberos and the `krb5` implementation for its transport-layer security. However, Thrift has since migrated fully to Transport Layer Security for its transport-layer security and...
Python
mit
facebook/bistro,facebook/bistro,facebook/bistro,facebook/bistro,facebook/bistro,facebook/bistro
ad042127cadc2fd779bdea4d6853102b5d8d0ad0
api/tests/test_login.py
api/tests/test_login.py
import unittest from api.test import BaseTestCase class TestLogin(BaseTestCase): @unittest.skip("") def test_login(self): login_credentials = { "password": "qwerty@123", "username": "EdwinKato" } response = self.client.post('/api/v1/auth/login', ...
import unittest import json from api.test import BaseTestCase class TestLogin(BaseTestCase): @unittest.skip("") def test_login(self): login_credentials = { "password": "qwerty@123", "username": "EdwinKato" } response = self.client.post('/api/v1/auth/login', ...
Add test for non-registered user
Add test for non-registered user
Python
mit
EdwinKato/bucket-list,EdwinKato/bucket-list,EdwinKato/bucket-list,EdwinKato/bucket-list,EdwinKato/bucket-list
b9c175059f0f2f3321ffd495fd46c6f5770afd22
bluebottle/payouts_dorado/adapters.py
bluebottle/payouts_dorado/adapters.py
import json import requests from django.core.exceptions import ImproperlyConfigured from django.db import connection from requests.exceptions import MissingSchema from bluebottle.clients import properties class PayoutValidationError(Exception): pass class PayoutCreationError(Exception): pass class Dorad...
import json import requests from django.core.exceptions import ImproperlyConfigured from django.db import connection from requests.exceptions import MissingSchema from bluebottle.clients import properties class PayoutValidationError(Exception): pass class PayoutCreationError(Exception): pass class Dorad...
Set the payout status to created BEFORE we call out to dorado. This way we do not override that status that dorado set.
Set the payout status to created BEFORE we call out to dorado. This way we do not override that status that dorado set. BB-9471 #resolve
Python
bsd-3-clause
onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle
a9052428e1eee8ec566bd496e1247dae0873d9c9
test/wordfilter_test.py
test/wordfilter_test.py
import nose from lib.wordfilter import Wordfilter # Run with `python -m test.wordfilter_test` class Wordfilter_test: def setup(self): self.wordfilter = Wordfilter() def teardown(self): self.wordfilter = [] def test_loading(self): assert type(self.wordfilter.blacklist) is list def test_badWords(s...
import nose from lib.wordfilter import Wordfilter # Run with `python -m test.wordfilter_test` class Wordfilter_test: def setup(self): self.wordfilter = Wordfilter() def teardown(self): self.wordfilter = [] def test_loading(self): assert type(self.wordfilter.blacklist) is list def test_badWords(s...
Add another test case - add multiple words
Add another test case - add multiple words
Python
mit
dariusk/wordfilter,dariusk/wordfilter,mwatson/wordfilter,hugovk/wordfilter,mwatson/wordfilter,dariusk/wordfilter,hugovk/wordfilter,mwatson/wordfilter,hugovk/wordfilter,dariusk/wordfilter,hugovk/wordfilter,mwatson/wordfilter
0a6072621570464522cbfa6d939dffccc0fa6503
spacy/cli/converters/iob2json.py
spacy/cli/converters/iob2json.py
# coding: utf8 from __future__ import unicode_literals import cytoolz from ...gold import iob_to_biluo def iob2json(input_data, n_sents=10, *args, **kwargs): """ Convert IOB files into JSON format for use with train cli. """ docs = [] for group in cytoolz.partition_all(n_sents, docs): gr...
# coding: utf8 from __future__ import unicode_literals from ...gold import iob_to_biluo from ...util import minibatch def iob2json(input_data, n_sents=10, *args, **kwargs): """ Convert IOB files into JSON format for use with train cli. """ docs = [] for group in minibatch(docs, n_sents): ...
Remove cytoolz usage in CLI
Remove cytoolz usage in CLI
Python
mit
explosion/spaCy,spacy-io/spaCy,honnibal/spaCy,spacy-io/spaCy,spacy-io/spaCy,spacy-io/spaCy,explosion/spaCy,explosion/spaCy,honnibal/spaCy,explosion/spaCy,spacy-io/spaCy,explosion/spaCy,spacy-io/spaCy,honnibal/spaCy,explosion/spaCy,honnibal/spaCy
fb837585264e6abe4b0488e3a9dd5c5507e69bf6
tensorflow/python/distribute/__init__.py
tensorflow/python/distribute/__init__.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
Fix asan test for various targets.
PSv2: Fix asan test for various targets. PiperOrigin-RevId: 325441069 Change-Id: I1fa1b2b10670f34739323292eab623d5b538142e
Python
apache-2.0
aam-at/tensorflow,cxxgtxy/tensorflow,frreiss/tensorflow-fred,paolodedios/tensorflow,paolodedios/tensorflow,karllessard/tensorflow,yongtang/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,Intel-Corporation/tensorflow,aldian/tensorflow,sarvex/tensorflow,aldian/tensorflow,davidzchen/tensorflow,ten...
35fe7bb6411c8009253bf66fb7739a5d49a7028d
scuole/counties/management/commands/bootstrapcounties.py
scuole/counties/management/commands/bootstrapcounties.py
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals import csv import os from django.conf import settings from django.core.management.base import BaseCommand from django.utils.text import slugify from ...models import County from scuole.states.models import State class Command(BaseComm...
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals import csv import os from django.conf import settings from django.core.management.base import BaseCommand from django.utils.text import slugify from ...models import County from scuole.states.models import State class Command(BaseComm...
Add feedback during county loader
Add feedback during county loader
Python
mit
texastribune/scuole,texastribune/scuole,texastribune/scuole,texastribune/scuole
63241b7fb62166f4a31ef7ece38edf8b36129f63
dictionary/management/commands/writeLiblouisTables.py
dictionary/management/commands/writeLiblouisTables.py
from daisyproducer.dictionary.brailleTables import writeWhiteListTables, writeLocalTables from daisyproducer.dictionary.models import Word from daisyproducer.documents.models import Document from django.core.management.base import BaseCommand class Command(BaseCommand): args = '' help = 'Write Liblouis tables ...
from daisyproducer.dictionary.brailleTables import writeWhiteListTables, writeLocalTables from daisyproducer.dictionary.models import Word from daisyproducer.documents.models import Document from django.core.management.base import BaseCommand class Command(BaseCommand): args = '' help = 'Write Liblouis tables ...
Make sure the verbosity stuff actually works
Make sure the verbosity stuff actually works
Python
agpl-3.0
sbsdev/daisyproducer,sbsdev/daisyproducer,sbsdev/daisyproducer,sbsdev/daisyproducer
69ade2e8dfcaac3769d0b75929eb89cf3e775a74
tests/unit/test_util.py
tests/unit/test_util.py
# -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function, unicode_literals import os from ava.util import time_uuid, base_path, defines, misc class TestTimeUUID(object): def test_uuids_should_be_in_alaphabetical_order(self): old = time_uuid.oid() for i in range(10...
# -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function, unicode_literals import os from ava.util import time_uuid, base_path, defines, misc class TestTimeUUID(object): def test_uuids_should_be_in_alaphabetical_order(self): old = time_uuid.oid() for i in range(10...
Fix issue in get_app_dir() test which is caused by platfrom-dependent problem
Fix issue in get_app_dir() test which is caused by platfrom-dependent problem
Python
apache-2.0
eavatar/eavatar-me,eavatar/eavatar-me,eavatar/eavatar-me,eavatar/eavatar-me
d8af86a0fedb8e7225e5ad97f69cd40c9c2abd8f
nimp/commands/cis_wwise_build_banks.py
nimp/commands/cis_wwise_build_banks.py
# -*- coding: utf-8 -*- from nimp.commands._cis_command import * from nimp.utilities.wwise import * #------------------------------------------------------------------------------- class BuildWwiseBanksCommand(CisCommand): abstract = 0 #-------------------------------------------------------------------------...
# -*- coding: utf-8 -*- from nimp.commands._cis_command import * from nimp.utilities.wwise import * #------------------------------------------------------------------------------- class BuildWwiseBanksCommand(CisCommand): abstract = 0 #-------------------------------------------------------------------------...
Replace "<platform>" with "-p <platform>" in CIS wwise command.
Replace "<platform>" with "-p <platform>" in CIS wwise command. This is what the Buildbot configuration uses, and it makes sense. It used to not break because we were ignoring unknown commandline flags.
Python
mit
dontnod/nimp
99c0804edebd94e0054e324833028ba450806f7f
documentchain/server.py
documentchain/server.py
from flask import Flask, jsonify, request from .chain import DocumentChain from .storage import DiskStorage app = Flask(__name__) chain = DocumentChain(DiskStorage('data/')) @app.route('/entries', methods=['GET', 'POST']) def entries(): if request.method == 'POST': if not request.json: return ...
from flask import Flask, jsonify, request from .chain import DocumentChain from .storage import DiskStorage app = Flask(__name__) chain = DocumentChain(DiskStorage('data/')) @app.route('/entries', methods=['GET', 'POST']) def entry_list(): if request.method == 'POST': if not request.json: retu...
Add entry detail HTTP endpoint
Add entry detail HTTP endpoint
Python
mit
LandRegistry-Attic/concept-system-of-record,LandRegistry-Attic/concept-system-of-record,LandRegistry-Attic/concept-system-of-record
581f16e30aeb465f80fd28a77404b0375bd197d4
code/python/knub/thesis/topic_model.py
code/python/knub/thesis/topic_model.py
import logging, gensim, bz2 from knub.thesis.util.memory import limit_memory logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO) def main(): logging.info("Starting Wikipedia LDA") # limit memory to 32 GB limit_memory(32000) id2word = gensim.corpora.Dictionary.l...
import logging, gensim, bz2 import mkl from knub.thesis.util.memory import limit_memory logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO) mkl.set_num_threads(8) def main(): logging.info("Starting Wikipedia LDA") # limit memory to 32 GB limit_memory(32000) id2...
Set max threads for MKL.
Set max threads for MKL.
Python
apache-2.0
knub/master-thesis,knub/master-thesis,knub/master-thesis,knub/master-thesis
d000a2e3991c54b319bc7166d9d178b739170a46
polling_stations/apps/data_collection/management/commands/import_sheffield.py
polling_stations/apps/data_collection/management/commands/import_sheffield.py
""" Import Sheffield """ from data_collection.management.commands import BaseShpShpImporter class Command(BaseShpShpImporter): """ Imports the Polling Station data from Sheffield """ council_id = 'E08000019' districts_name = 'SCCPollingDistricts2015' stations_name = 'SCCPollingStations2015...
""" Import Sheffield """ from data_collection.management.commands import BaseShpShpImporter class Command(BaseShpShpImporter): """ Imports the Polling Station data from Sheffield """ council_id = 'E08000019' districts_name = 'SCCPollingDistricts2015' stations_name = 'SCCPollingStations2015...
Add polling_district_id in Sheffield import script
Add polling_district_id in Sheffield import script
Python
bsd-3-clause
DemocracyClub/UK-Polling-Stations,andylolz/UK-Polling-Stations,andylolz/UK-Polling-Stations,andylolz/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations,chris48s/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations,chris48s/UK-Polling-Stations,chris48s/UK-Polling-Stations
c1330851105df14367bec5ed87fc3c45b71932fd
project_euler/solutions/problem_35.py
project_euler/solutions/problem_35.py
from typing import List from ..library.sqrt import fsqrt from ..library.number_theory.primes import is_prime, prime_sieve def is_circular_prime(n: int, sieve: List[int]) -> bool: for i in range(len(str(n))): if not is_prime(int(str(n)[i:] + str(n)[:i]), sieve): return False print(n) ...
from typing import List from ..library.base import number_to_list, list_to_number from ..library.sqrt import fsqrt from ..library.number_theory.primes import is_prime, prime_sieve def is_circular_prime(n: int, sieve: List[int]) -> bool: rep_n = number_to_list(n) for i in range(len(rep_n)): if not is...
Make 35 use number_to_list and inverse
Make 35 use number_to_list and inverse
Python
mit
cryvate/project-euler,cryvate/project-euler
299fadcde71558bc1e77ba396cc544619373c2b1
conditional/blueprints/spring_evals.py
conditional/blueprints/spring_evals.py
from flask import Blueprint from flask import render_template from flask import request spring_evals_bp = Blueprint('spring_evals_bp', __name__) @spring_evals_bp.route('/spring_evals/') def display_spring_evals(): # get user data user_name = request.headers.get('x-webauth-user') members = [ ...
from flask import Blueprint from flask import render_template from flask import request spring_evals_bp = Blueprint('spring_evals_bp', __name__) @spring_evals_bp.route('/spring_evals/') def display_spring_evals(): # get user data user_name = request.headers.get('x-webauth-user') members = [ ...
Add social events to spring evals ๐Ÿ˜ฟ
Add social events to spring evals ๐Ÿ˜ฟ
Python
mit
RamZallan/conditional,ComputerScienceHouse/conditional,RamZallan/conditional,ComputerScienceHouse/conditional,RamZallan/conditional,ComputerScienceHouse/conditional
8194f327032c064fe71ba3dc918e28ee2a586b12
sqlalchemy_mixins/serialize.py
sqlalchemy_mixins/serialize.py
from collections.abc import Iterable from .inspection import InspectionMixin class SerializeMixin(InspectionMixin): """Mixin to make model serializable.""" __abstract__ = True def to_dict(self,nested = False, hybrid_attributes = False, exclude = None): """Return dict object with model's data. ...
from collections.abc import Iterable from .inspection import InspectionMixin class SerializeMixin(InspectionMixin): """Mixin to make model serializable.""" __abstract__ = True def to_dict(self,nested = False, hybrid_attributes = False, exclude = None): """Return dict object with model's data. ...
Check if relation objects are class of SerializeMixin
Check if relation objects are class of SerializeMixin
Python
mit
absent1706/sqlalchemy-mixins
5a6c8b1c9c13078462bec7ba254c6a6f95dd3c42
contrib/linux/tests/test_action_dig.py
contrib/linux/tests/test_action_dig.py
#!/usr/bin/env python # Copyright 2020 The StackStorm Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appli...
#!/usr/bin/env python # Copyright 2020 The StackStorm Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appli...
Test that returned result is a str instance
Test that returned result is a str instance
Python
apache-2.0
nzlosh/st2,StackStorm/st2,StackStorm/st2,Plexxi/st2,Plexxi/st2,Plexxi/st2,StackStorm/st2,StackStorm/st2,nzlosh/st2,nzlosh/st2,Plexxi/st2,nzlosh/st2
0ba7c20f3ddea73f8d1f92c66b3ab0abf1ea8861
asciimatics/__init__.py
asciimatics/__init__.py
__author__ = 'Peter Brittain' from .version import version __version__ = version
__author__ = 'Peter Brittain' try: from .version import version except ImportError: # Someone is running straight from the GIT repo - dummy out the version version = "0.0.0" __version__ = version
Patch up version for direct running of code in repo.
Patch up version for direct running of code in repo.
Python
apache-2.0
peterbrittain/asciimatics,peterbrittain/asciimatics
4f24071185140ef98167e470dbac97dcdfc65b90
via/requests_tools/error_handling.py
via/requests_tools/error_handling.py
"""Helpers for capturing requests exceptions.""" from functools import wraps from requests import RequestException, exceptions from via.exceptions import BadURL, UnhandledException, UpstreamServiceError REQUESTS_BAD_URL = ( exceptions.MissingSchema, exceptions.InvalidSchema, exceptions.InvalidURL, e...
"""Helpers for capturing requests exceptions.""" from functools import wraps from requests import RequestException, exceptions from via.exceptions import BadURL, UnhandledException, UpstreamServiceError REQUESTS_BAD_URL = ( exceptions.MissingSchema, exceptions.InvalidSchema, exceptions.InvalidURL, e...
Fix error handling to show error messages
Fix error handling to show error messages We removed this during a refactor, but it means we get very generic messages in the UI instead of the actual error string.
Python
bsd-2-clause
hypothesis/via,hypothesis/via,hypothesis/via
7ab465aaaf69ba114b3411204dd773781a147c41
longclaw/project_template/products/models.py
longclaw/project_template/products/models.py
from django.db import models from wagtail.wagtailcore.fields import RichTextField from longclaw.longclawproducts.models import ProductVariantBase class ProductVariant(ProductVariantBase): # Enter your custom product variant fields here # e.g. colour, size, stock and so on. # Remember, ProductVariantBase p...
from django.db import models from wagtail.wagtailcore.fields import RichTextField from longclaw.longclawproducts.models import ProductVariantBase class ProductVariant(ProductVariantBase): # Enter your custom product variant fields here # e.g. colour, size, stock and so on. # Remember, ProductVariantBase p...
Remove 'stock' field from template products
Remove 'stock' field from template products
Python
mit
JamesRamm/longclaw,JamesRamm/longclaw,JamesRamm/longclaw,JamesRamm/longclaw
0feb1810b1e3ca61ef15deb71aec9fd1eab3f2da
py101/introduction/__init__.py
py101/introduction/__init__.py
"""" Introduction Adventure Author: Ignacio Avas (iavas@sophilabs.com) """ import codecs import io import sys import unittest from story.adventures import AdventureVerificationError, BaseAdventure from story.translation import gettext as _ class TestOutput(unittest.TestCase): "Introduction Adventure test" de...
"""" Introduction Adventure Author: Ignacio Avas (iavas@sophilabs.com) """ import codecs import io import sys import unittest from story.adventures import AdventureVerificationError, BaseAdventure from story.translation import gettext as _ class TestOutput(unittest.TestCase): "Introduction Adventure test" de...
Refactor introduction to make it the same as the other tests
Refactor introduction to make it the same as the other tests
Python
mit
sophilabs/py101
8c159ee5fa6aa1d10cef2268a373b90f6cb72896
px/px_loginhistory.py
px/px_loginhistory.py
def get_users_at(timestamp, last_output=None, now=None): """ Return a set of strings corresponding to which users were logged in from which addresses at a given timestamp. Optional argument last_output is the output of "last". Will be filled in by actually executing "last" if not provided. Opt...
import sys import re USERNAME_PART = "([^ ]+)" DEVICE_PART = "([^ ]+)" ADDRESS_PART = "([^ ]+)?" FROM_PART = "(.*)" DASH_PART = " . " TO_PART = "(.*)" DURATION_PART = "([0-9+:]+)" LAST_RE = re.compile( USERNAME_PART + " +" + DEVICE_PART + " +" + ADDRESS_PART + " +" + FROM_PART + DASH_PART + TO_PART ...
Create regexp to match at least some last lines
Create regexp to match at least some last lines
Python
mit
walles/px,walles/px
daca2bb7810b4c8eaf9f6a0598d8c6b41e0f2e10
froide_theme/settings.py
froide_theme/settings.py
# -*- coding: utf-8 -*- from froide.settings import Base, ThemeBase, HerokuPostmark, HerokuPostmarkS3 # noqa class CustomThemeBase(ThemeBase): FROIDE_THEME = 'froide_theme.theme' SITE_NAME = "My Froide" SITE_EMAIL = "info@example.com" SITE_URL = 'http://localhost:8000' SECRET_URLS = { "...
# -*- coding: utf-8 -*- import os from froide.settings import Base, ThemeBase, HerokuPostmark, HerokuPostmarkS3 # noqa class CustomThemeBase(ThemeBase): FROIDE_THEME = 'froide_theme.theme' SITE_NAME = "My Froide" SITE_EMAIL = "info@example.com" SITE_URL = 'http://localhost:8000' SECRET_URLS = ...
Add own locale directory to LOCALE_PATHS
Add own locale directory to LOCALE_PATHS
Python
mit
CodeforHawaii/uipa_org,CodeforHawaii/uipa_org,CodeforHawaii/uipa_org,okfde/froide-theme
fb22d49ca3ef41a22a5bb68261c77f24d6d39f7b
froide/helper/search.py
froide/helper/search.py
from haystack.fields import NgramField try: from .elasticsearch import SuggestField except ImportError: class SuggestField(NgramField): pass class SearchQuerySetWrapper(object): """ Decorates a SearchQuerySet object using a generator for efficient iteration """ def __init__(self, sqs...
from haystack.fields import NgramField try: from .elasticsearch import SuggestField except ImportError: class SuggestField(NgramField): pass class SearchQuerySetWrapper(object): """ Decorates a SearchQuerySet object using a generator for efficient iteration """ def __init__(self, sqs...
Fix object access on None
Fix object access on None
Python
mit
fin/froide,stefanw/froide,fin/froide,fin/froide,stefanw/froide,stefanw/froide,fin/froide,stefanw/froide,stefanw/froide
3203d685479ba3803a81bd2101afa7f5bced754d
rplugin/python3/deoplete/sources/go.py
rplugin/python3/deoplete/sources/go.py
import deoplete.util from .base import Base class Source(Base): def __init__(self, vim): Base.__init__(self, vim) self.name = 'go' self.mark = '[go]' self.filetypes = ['go'] self.min_pattern_length = 0 self.is_bytepos = True def get_complete_api(self, findstar...
import deoplete.util from .base import Base class Source(Base): def __init__(self, vim): Base.__init__(self, vim) self.name = 'go' self.mark = '[go]' self.filetypes = ['go'] self.input_pattern = '[^. \t0-9]\.\w*' self.is_bytepos = True def get_complete_api(sel...
Add input_pattern instead of min_pattern_length
Add input_pattern instead of min_pattern_length Signed-off-by: Koichi Shiraishi <13fbd79c3d390e5d6585a21e11ff5ec1970cff0c@zchee.io>
Python
mit
zchee/deoplete-go,zchee/deoplete-go
cb73b357d50603a1bce1184b28266fb55a4fd4ae
django_ethereum_events/web3_service.py
django_ethereum_events/web3_service.py
from django.conf import settings from web3 import HTTPProvider, Web3 from web3.middleware import geth_poa_middleware from .utils import Singleton class Web3Service(metaclass=Singleton): """Creates a `web3` instance based on the given Provider.""" def __init__(self, *args, **kwargs): """Initializes ...
from django.conf import settings from web3 import HTTPProvider, Web3 from web3.middleware import geth_poa_middleware from .utils import Singleton class Web3Service(metaclass=Singleton): """Creates a `web3` instance based on the given Provider.""" def __init__(self, *args, **kwargs): """Initializes t...
Change env variables for node setup to single URI varieable
Change env variables for node setup to single URI varieable
Python
mit
artemistomaras/django-ethereum-events,artemistomaras/django-ethereum-events
ee3428d98d9cf322233ac9abfa9cd81513b530e0
medical_medicament_us/__manifest__.py
medical_medicament_us/__manifest__.py
# -*- coding: utf-8 -*- # ยฉ 2016 LasLabs Inc. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { 'name': 'Medical Medicament - US Locale', 'version': '10.0.1.0.0', 'author': "LasLabs, Odoo Community Association (OCA)", 'category': 'Medical', 'depends': [ 'medical_base_u...
# -*- coding: utf-8 -*- # ยฉ 2016 LasLabs Inc. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { 'name': 'Medical Medicament - US Locale', 'version': '10.0.1.0.0', 'author': "LasLabs, Odoo Community Association (OCA)", 'category': 'Medical', 'depends': [ 'medical_base_u...
Add missing dependency * medical.medicament.ndc relates to medical.manufacturer, which does not exist without it defined as a dependency.
[FIX] medical_medicament_us: Add missing dependency * medical.medicament.ndc relates to medical.manufacturer, which does not exist without it defined as a dependency.
Python
agpl-3.0
laslabs/vertical-medical,laslabs/vertical-medical
a4c247f5243c8ee637f1507fb9dc0281541af3b1
pambox/speech/__init__.py
pambox/speech/__init__.py
""" The :mod:`pambox.speech` module gather speech intelligibility models. """ from __future__ import absolute_import from .sepsm import Sepsm from .mrsepsm import MrSepsm from .sii import Sii from .material import Material __all__ = [ 'Sepsm', 'MrSepsm', 'Sii', 'Material' ]
""" The :mod:`pambox.speech` module gather speech intelligibility models. """ from __future__ import absolute_import from .sepsm import Sepsm from .mrsepsm import MrSepsm from .sii import Sii from .material import Material from .experiment import Experiment __all__ = [ 'Sepsm', 'MrSepsm', 'Sii', 'Mate...
Add Experiment to the init file of speech module
Add Experiment to the init file of speech module
Python
bsd-3-clause
achabotl/pambox
e655bbd79c97473003f179a3df165e6e548f121e
letsencryptae/models.py
letsencryptae/models.py
# THIRD PARTY from djangae.fields import CharField from django.db import models class Secret(models.Model): created = models.DateTimeField(auto_now_add=True) url_slug = CharField(primary_key=True) secret = CharField() class Meta(object): ordering = ('-created',) def __unicode__(self): ...
# THIRD PARTY from djangae.fields import CharField from django.db import models class Secret(models.Model): created = models.DateTimeField(auto_now_add=True) url_slug = CharField(primary_key=True) secret = CharField() class Meta(object): ordering = ('-created',) def __unicode__(self): ...
Make sure that there's a dot separating the first and second halves of the secret.
Make sure that there's a dot separating the first and second halves of the secret.
Python
mit
adamalton/letsencrypt-appengine
af3525bf174d0774b61464f9cc8ab8441babc7ae
examples/flask_alchemy/test_demoapp.py
examples/flask_alchemy/test_demoapp.py
import os import unittest import tempfile import demoapp import demoapp_factories class DemoAppTestCase(unittest.TestCase): def setUp(self): demoapp.app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite://' demoapp.app.config['TESTING'] = True self.app = demoapp.app.test_client() self.d...
import unittest import demoapp import demoapp_factories class DemoAppTestCase(unittest.TestCase): def setUp(self): demoapp.app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite://' demoapp.app.config['TESTING'] = True self.app = demoapp.app.test_client() self.db = demoapp.db se...
Remove useless imports from flask alchemy demo
Remove useless imports from flask alchemy demo
Python
mit
FactoryBoy/factory_boy
1f1e1a78f56e890777ca6f88cc30be7710275aea
blackbelt/deployment.py
blackbelt/deployment.py
from subprocess import check_call from blackbelt.handle_github import get_current_branch from blackbelt.messages import post_message def deploy_staging(): branch_name = get_current_branch() post_message("Deploying branch %s to staging" % branch_name, "#deploy-queue") check_call(['grunt', 'deploy', '--a...
from subprocess import check_call from blackbelt.handle_github import get_current_branch from blackbelt.messages import post_message def deploy_staging(): branch_name = get_current_branch() post_message("Deploying branch %s to staging" % branch_name, "#deploy-queue") check_call(['grunt', 'deploy', '--a...
Update deploy and stage with new environ
feat: Update deploy and stage with new environ
Python
mit
apiaryio/black-belt
847e864df300304ac43e995a577eaa93ae452024
streak-podium/render.py
streak-podium/render.py
import matplotlib.pyplot as plt import numpy as np def horizontal_bar(sorted_streaks, sort): """ Render a horizontal bar chart of streaks. Values have already been sorted by sort. """ # Only extract those users & streaks for streaks that are non-zero: users, streaks = zip(*[(user, streak.get(...
import matplotlib.pyplot as plt import numpy as np def horizontal_bar(sorted_streaks, sort): """ Render a horizontal bar chart of streaks. Values have already been sorted by sort. """ # Only extract those users & streaks for streaks that are non-zero: users, streaks = zip(*[(user, streak.get(...
Remove y-axis ticks and top x-axis ticks
Remove y-axis ticks and top x-axis ticks
Python
mit
jollyra/hubot-streak-podium,jollyra/hubot-commit-streak,supermitch/streak-podium,jollyra/hubot-streak-podium,supermitch/streak-podium,jollyra/hubot-commit-streak
1ed49dae9d88e1e277a0eef879dec53ed925417a
highlander/exceptions.py
highlander/exceptions.py
class InvalidPidFileError(Exception): """ An exception when an invalid PID file is read.""" class PidFileExistsError(Exception): """ An exception when a PID file already exists."""
class InvalidPidFileError(Exception): """ An exception when an invalid PID file is read.""" class PidFileExistsError(Exception): """ An exception when a PID file already exists.""" class InvalidPidDirectoryError(Exception): """ An exception when an invalid PID directory is detected."""
Add a new exception since we are making a directory now.
Add a new exception since we are making a directory now.
Python
mit
chriscannon/highlander
644df0955d1a924b72ffdceaea9d8da14100dae0
scipy/weave/tests/test_inline_tools.py
scipy/weave/tests/test_inline_tools.py
from numpy import * from numpy.testing import * from scipy.weave import inline_tools class TestInline(TestCase): """ These are long running tests... I'd like to benchmark these things somehow. """ @dec.slow def test_exceptions(self): a = 3 code = """ if (a < 2)...
from numpy import * from numpy.testing import * from scipy.weave import inline_tools class TestInline(TestCase): """ These are long running tests... I'd like to benchmark these things somehow. """ @dec.slow def test_exceptions(self): a = 3 code = """ if (a < 2)...
Disable weave tests that cause compilation failure, since this causes distutils to do a SystemExit, which break the test suite.
Disable weave tests that cause compilation failure, since this causes distutils to do a SystemExit, which break the test suite. git-svn-id: 003f22d385e25de9cff933a5ea4efd77cb5e7b28@5402 d6536bca-fef9-0310-8506-e4c0a848fbcf
Python
bsd-3-clause
scipy/scipy-svn,lesserwhirls/scipy-cwt,scipy/scipy-svn,jasonmccampbell/scipy-refactor,scipy/scipy-svn,lesserwhirls/scipy-cwt,lesserwhirls/scipy-cwt,jasonmccampbell/scipy-refactor,scipy/scipy-svn,jasonmccampbell/scipy-refactor,lesserwhirls/scipy-cwt,jasonmccampbell/scipy-refactor
8a605f21e6c11b8176214ce7082c892566a6b34e
telethon/tl/message_container.py
telethon/tl/message_container.py
from . import TLObject, GzipPacked from ..extensions import BinaryWriter class MessageContainer(TLObject): constructor_id = 0x73f1f8dc def __init__(self, messages): super().__init__() self.content_related = False self.messages = messages def to_bytes(self): # TODO Change ...
import struct from . import TLObject class MessageContainer(TLObject): constructor_id = 0x73f1f8dc def __init__(self, messages): super().__init__() self.content_related = False self.messages = messages def to_bytes(self): return struct.pack( '<Ii', MessageCon...
Remove BinaryWriter dependency on MessageContainer
Remove BinaryWriter dependency on MessageContainer
Python
mit
LonamiWebs/Telethon,andr-04/Telethon,LonamiWebs/Telethon,expectocode/Telethon,LonamiWebs/Telethon,LonamiWebs/Telethon
56e11c3df02874867626551534693b488db82fb7
example.py
example.py
import os import pickle as pkl from gso import load_up_answers, load_up_questions #for result in load_up_questions("How to write a bubble sort", "python"): #print result #break #question_url = 'https://stackoverflow.com/questions/895371/bubble-sort-homework' #with open("html_dump.pkl", 'wb') as myfile: #...
import os import pickle as pkl from lxml import etree from gso import load_up_answers, load_up_questions #for result in load_up_questions("How to write a bubble sort", "python"): #print result #break #question_url = 'https://stackoverflow.com/questions/895371/bubble-sort-homework' #with open("html_dump.pkl",...
Create wrapper tag for SO html
Create wrapper tag for SO html
Python
mit
mdtmc/gso
3c0fa80bcdd5a493e7415a49566b4eb7524c534b
fabfile.py
fabfile.py
from __future__ import with_statement from fabric.api import local, cd, env, run from fabric.colors import green env.use_ssh_config = True env.user = 'ubuntu' env.hosts = [ 'dhlab-backend' ] PRODUCTION_DIR = 'backend' SUPERVISOR_NAME = 'dhlab_backend' MONGODB_NAME = 'dhlab' def backup_db(): '''Backup loca...
from __future__ import with_statement from fabric.api import local, cd, env, run from fabric.colors import green env.use_ssh_config = True env.user = 'ubuntu' env.hosts = [ 'dhlab-backend' ] PRODUCTION_DIR = 'backend' SUPERVISOR_NAME = 'dhlab_backend' MONGODB_NAME = 'dhlab' def backup_db(): '''Backup loca...
Deploy script now checks to see if virtualenv has the latest dependencies
Deploy script now checks to see if virtualenv has the latest dependencies
Python
mit
DHLabs/keep,9929105/KEEP,DHLabs/keep,9929105/KEEP,DHLabs/keep,9929105/KEEP
423ea9128f01eb74790a3bb5a876c066acc9c2c1
firesim.py
firesim.py
import functools import signal import sys import logging as log from firesimgui import FireSimGUI from lib.arguments import parse_args def sig_handler(app, sig, frame): log.info("Firesim received signal %d. Shutting down.", sig) try: app.quit() except Exception: log.exception...
#!/usr/bin/env python3 import functools import signal import sys import logging as log from firesimgui import FireSimGUI from lib.arguments import parse_args def sig_handler(app, sig, frame): log.info("Firesim received signal %d. Shutting down.", sig) try: app.quit() except Exception: lo...
Add shebang to main script and switch to Unix line endings
Add shebang to main script and switch to Unix line endings
Python
mit
Openlights/firesim
a99378deee9a802bf107d11e79d2df2f77481495
silver/tests/spec/test_plan.py
silver/tests/spec/test_plan.py
# -*- coding: utf-8 -*- # vim: ft=python:sw=4:ts=4:sts=4:et: import json from silver.models import Plan from django.test.client import Client from django.test import TestCase class PlansSpecificationTestCase(TestCase): def setUp(self): self.client = Client() def test_create_plan(self): resp...
# -*- coding: utf-8 -*- # vim: ft=python:sw=4:ts=4:sts=4:et: import json from silver.models import Plan from django.test.client import Client from django.test import TestCase class PlansSpecificationTestCase(TestCase): def setUp(self): self.client = Client() def test_create_plan(self): asse...
Comment out the failing Plan test
Comment out the failing Plan test
Python
apache-2.0
PressLabs/silver,PressLabs/silver,PressLabs/silver
7726e51f2e3bb028700e5fc61779f6edc53cee36
scripts/init_tree.py
scripts/init_tree.py
import os import shutil def main(): cwd = os.getcwd() if not cwd.endswith(os.path.join('FRENSIE', 'scripts')): print 'This script must be run in \"FRENSIE/scipts\"' print 'Your CWD is', cwd return 1 os.chdir('../../') os.mkdir('frensie_build_tree') #os.renames('FRENSIE'...
import os import shutil def main(): cwd = os.getcwd() if not cwd.endswith(os.path.join('FRENSIE', 'scripts')): print 'This script must be run in \"FRENSIE/scipts\"' print 'Your CWD is', cwd return 1 os.chdir('../../') os.mkdir('frensie_build_tree') #os.renames('FRENSIE'...
Update to copy new scripts
Update to copy new scripts
Python
bsd-3-clause
lkersting/SCR-2123,lkersting/SCR-2123,lkersting/SCR-2123,lkersting/SCR-2123
454c3228db731280eeed8d22c6811c2810018222
export_layers/pygimplib/lib/__init__.py
export_layers/pygimplib/lib/__init__.py
#------------------------------------------------------------------------------- # # This file is part of pygimplib. # # Copyright (C) 2014, 2015 khalim19 <khalim19@gmail.com> # # pygimplib is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # t...
#------------------------------------------------------------------------------- # # This file is part of pygimplib. # # Copyright (C) 2014, 2015 khalim19 <khalim19@gmail.com> # # pygimplib is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # t...
Add description for `lib` package
Add description for `lib` package
Python
bsd-3-clause
khalim19/gimp-plugin-export-layers,khalim19/gimp-plugin-export-layers
1b07cb1ec2fbe48af4f38a225c2237846ce8b314
pyramid_es/tests/__init__.py
pyramid_es/tests/__init__.py
import logging def setUp(): log = logging.getLogger('elasticsearch.trace') log.setLevel(logging.CRITICAL)
import logging def setUp(): log = logging.getLogger('elasticsearch.trace') log.addHandler(logging.NullHandler())
Use a better method for silencing 'no handlers found' error
Use a better method for silencing 'no handlers found' error
Python
mit
storborg/pyramid_es
4148c03ce666f12b8b04be7103ae6a969dd0c022
fabfile.py
fabfile.py
from fabric.api import * env.hosts = [ 'shaperia@lynx.uberspace.de' ] env.target_directory = './happyman' def init(): run('git clone -q https://github.com/skyshaper/happyman.git ' + env.target_directory) with cd(env.target_directory): run('virtualenv python_virtualenv') def deploy(): local('...
from fabric.api import * env.hosts = [ 'shaperia@lynx.uberspace.de' ] env.target_directory = './happyman' def init(): run('git clone -q https://github.com/skyshaper/happyman.git ' + env.target_directory) with cd(env.target_directory): run('virtualenv python_virtualenv') def deploy(): local('...
Use included carton executable on deploy
Use included carton executable on deploy
Python
mit
skyshaper/happyman,skyshaper/happyman,skyshaper/happyman
ddb3bcf4e5d5eb5dc4f8bb74313f333e54c385d6
scripts/wall_stop.py
scripts/wall_stop.py
#!/usr/bin/env python import rospy,copy from geometry_msgs.msg import Twist from std_srvs.srv import Trigger, TriggerResponse from pimouse_ros.msg import LightSensorValues class WallStop(): def __init__(self): self.cmd_vel = rospy.Publisher('/cmd_vel',Twist,queue_size=1) self.sensor_values = Light...
#!/usr/bin/env python import rospy,copy from geometry_msgs.msg import Twist from std_srvs.srv import Trigger, TriggerResponse from pimouse_ros.msg import LightSensorValues class WallStop(): def __init__(self): self.cmd_vel = rospy.Publisher('/cmd_vel',Twist,queue_size=1) self.sensor_values = Light...
Reduce the name of a function
Reduce the name of a function
Python
mit
citueda/pimouse_run_corridor,citueda/pimouse_run_corridor
89e22a252adf6494cf59ae2289eb3f9bb1e2a893
sandcats/trivial_tests.py
sandcats/trivial_tests.py
import requests def register_asheesh(): return requests.post( 'http://localhost:3000/register', {'rawHostname': 'asheesh', 'email': 'asheesh@asheesh.org', 'pubkey': open('snakeoil-sample-certs/ssl-cert-snakeoil.pubkey').read()}, )
import requests def register_asheesh(): return requests.post( 'http://localhost:3000/register', {'rawHostname': 'asheesh', 'email': 'asheesh@asheesh.org', 'pubkey': open('snakeoil-sample-certs/ssl-cert-snakeoil.pubkey').read()}, ) def register_asheesh2_bad_key_type(): ...
Add test validating key format validation
Add test validating key format validation
Python
apache-2.0
sandstorm-io/sandcats,sandstorm-io/sandcats,sandstorm-io/sandcats,sandstorm-io/sandcats
b442190966a818338e0e294a6835b30a10753708
tests/providers/test_nfsn.py
tests/providers/test_nfsn.py
# Test for one implementation of the interface from lexicon.providers.nfsn import Provider from integration_tests import IntegrationTests from unittest import TestCase import pytest import os """ Some small info about running live tests. NFSN doesn't have trial accounts, so these tests can only be run by those with ...
# Test for one implementation of the interface from lexicon.providers.nfsn import Provider from integration_tests import IntegrationTests from unittest import TestCase import pytest import os """ Some small info about running live tests. NFSN doesn't have trial accounts, so these tests can only be run by those with ...
Add default NFSN test url
Add default NFSN test url
Python
mit
AnalogJ/lexicon,AnalogJ/lexicon
78c3589bbb80607321cf2b3e30699cde7df08ed8
website/addons/s3/tests/factories.py
website/addons/s3/tests/factories.py
# -*- coding: utf-8 -*- """Factory boy factories for the Box addon.""" import mock from datetime import datetime from dateutil.relativedelta import relativedelta from factory import SubFactory, Sequence from tests.factories import ModularOdmFactory, UserFactory, ProjectFactory, ExternalAccountFactory from website.add...
# -*- coding: utf-8 -*- """Factories for the S3 addon.""" from factory import SubFactory, Sequence from tests.factories import ModularOdmFactory, UserFactory, ProjectFactory, ExternalAccountFactory from website.addons.s3.model import ( S3UserSettings, S3NodeSettings ) class S3AccountFactory(ExternalAccountFac...
Fix docstring, remove unused import
Fix docstring, remove unused import
Python
apache-2.0
SSJohns/osf.io,caseyrollins/osf.io,jnayak1/osf.io,acshi/osf.io,felliott/osf.io,monikagrabowska/osf.io,TomBaxter/osf.io,RomanZWang/osf.io,leb2dg/osf.io,wearpants/osf.io,emetsger/osf.io,acshi/osf.io,chennan47/osf.io,zamattiac/osf.io,mluo613/osf.io,alexschiller/osf.io,chennan47/osf.io,HalcyonChimera/osf.io,baylee-d/osf.io...
09e0073a2aec6abc32a639fb2791af19e17eed1c
test/588-funicular-monorail.py
test/588-funicular-monorail.py
# way 93671417 assert_has_feature( 16, 10486, 25367, 'transit', { 'kind': 'monorail' })
# way 93671417 assert_has_feature( 16, 10486, 25367, 'transit', { 'kind': 'monorail' }) # relation 6060405 assert_has_feature( 16, 18201, 24705, 'transit', { 'kind': 'funicular' })
Add test for funicular feature
Add test for funicular feature
Python
mit
mapzen/vector-datasource,mapzen/vector-datasource,mapzen/vector-datasource
293cbd9ac1ad6c8f53e40fa36c3fdce6d9dda7ec
ynr/apps/uk_results/views/api.py
ynr/apps/uk_results/views/api.py
from rest_framework import viewsets from django_filters import filters, filterset from api.v09.views import ResultsSetPagination from ..models import CandidateResult, ResultSet from ..serializers import CandidateResultSerializer, ResultSetSerializer class CandidateResultViewSet(viewsets.ModelViewSet): queryset ...
from rest_framework import viewsets from django_filters import filters, filterset from django.db.models import Prefetch from api.v09.views import ResultsSetPagination from popolo.models import Membership from ..models import CandidateResult, ResultSet from ..serializers import CandidateResultSerializer, ResultSetSeri...
Speed up results API view
Speed up results API view
Python
agpl-3.0
DemocracyClub/yournextrepresentative,DemocracyClub/yournextrepresentative,DemocracyClub/yournextrepresentative
9da50045cc9d67df8d8d075a6e2a2dc7e9f137ee
tsa/data/sb5b/tweets.py
tsa/data/sb5b/tweets.py
#!/usr/bin/env python import os from tsa.lib import tabular, html xlsx_filepath = '%s/ohio/sb5-b.xlsx' % os.getenv('CORPORA', '.') label_keys = ['For', 'Against', 'Neutral', 'Broken Link', 'Not Applicable'] def read(limit=None): '''Yields dicts with at least 'Labels' and 'Tweet' fields.''' for row in tabular...
#!/usr/bin/env python import os from tsa.lib import tabular, html import logging logger = logging.getLogger(__name__) xlsx_filepath = '%s/ohio/sb5-b.xlsx' % os.getenv('CORPORA', '.') label_keys = ['For', 'Against', 'Neutral', 'Broken Link', 'Not Applicable'] def read(limit=None): '''Yields dicts with at least ...
Add specific iterable-like pickling handler for sb5b tweet data
Add specific iterable-like pickling handler for sb5b tweet data
Python
mit
chbrown/tsa,chbrown/tsa,chbrown/tsa
c916ea93fc4bcd0383ae7a95ae73f2418e122e1f
Orange/tests/__init__.py
Orange/tests/__init__.py
import os import unittest def suite(): test_dir = os.path.dirname(__file__) return unittest.TestLoader().discover(test_dir, ) test_suite = suite() if __name__ == '__main__': unittest.main(defaultTest='suite')
import os import unittest from Orange.widgets.tests import test_settings, test_setting_provider def suite(): test_dir = os.path.dirname(__file__) return unittest.TestSuite([ unittest.TestLoader().discover(test_dir), unittest.TestLoader().loadTestsFromModule(test_settings), unittest.Te...
Test settings when setup.py test is run.
Test settings when setup.py test is run.
Python
bsd-2-clause
marinkaz/orange3,marinkaz/orange3,qPCR4vir/orange3,qusp/orange3,cheral/orange3,kwikadi/orange3,cheral/orange3,cheral/orange3,marinkaz/orange3,marinkaz/orange3,kwikadi/orange3,qusp/orange3,qPCR4vir/orange3,kwikadi/orange3,kwikadi/orange3,qPCR4vir/orange3,kwikadi/orange3,kwikadi/orange3,qPCR4vir/orange3,marinkaz/orange3,...
f7d3fa716cd73c5a066aa0e40c337b50880befea
lc005_longest_palindromic_substring.py
lc005_longest_palindromic_substring.py
"""Leetcode 5. Longest Palindromic Substring Medium Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000. Example 1: Input: "babad" Output: "bab" Note: "aba" is also a valid answer. Example 2: Input: "cbbd" Output: "bb" """ class Solution(object): def ...
"""Leetcode 5. Longest Palindromic Substring Medium Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000. Example 1: Input: "babad" Output: "bab" Note: "aba" is also a valid answer. Example 2: Input: "cbbd" Output: "bb" """ class SolutionNaive(object): ...
Complete naive longest palindromic substring
Complete naive longest palindromic substring
Python
bsd-2-clause
bowen0701/algorithms_data_structures
eab249a092da21d47b07fd9918d4b28dcbc6089b
server/dummy/dummy_server.py
server/dummy/dummy_server.py
#!/usr/bin/env python import BaseHTTPServer ServerClass = BaseHTTPServer.HTTPServer RequestHandlerClass = BaseHTTPServer.BaseHTTPRequestHandler SERVER_NAME = '' SERVER_PORT = 9000 class JsonPostResponder(RequestHandlerClass): def _get_content_from_stream(self, length, stream): return stream.read(length)...
#!/usr/bin/env python import BaseHTTPServer ServerClass = BaseHTTPServer.HTTPServer RequestHandlerClass = BaseHTTPServer.BaseHTTPRequestHandler SERVER_NAME = '' SERVER_PORT = 9000 class JsonPostResponder(RequestHandlerClass): def _get_content_from_stream(self, length, stream): return stream.read(length)...
Clean up content and header output
Clean up content and header output
Python
mit
jonspeicher/Puddle,jonspeicher/Puddle,jonspeicher/Puddle
c788398c2c89a7afcbbf899e7ed4d51fccf114b5
php_coverage/command.py
php_coverage/command.py
import sublime_plugin from php_coverage.finder import CoverageFinder class CoverageCommand(sublime_plugin.TextCommand): """ Base class for a text command which has a coverage file. """ def __init__(self, view, coverage_finder=None): super(CoverageCommand, self).__init__(view) self.co...
import sublime_plugin from php_coverage.data import CoverageDataFactory from php_coverage.finder import CoverageFinder class CoverageCommand(sublime_plugin.TextCommand): """ Base class for a text command which has a coverage file. """ def __init__(self, view, coverage_finder=None): super(Co...
Return coverage data in CoverageCommand::coverage()
Return coverage data in CoverageCommand::coverage()
Python
mit
bradfeehan/SublimePHPCoverage,bradfeehan/SublimePHPCoverage
35a5e8717df9a5bcb60593700aa7e2f291816b0f
test/test_extensions/test_analytics.py
test/test_extensions/test_analytics.py
# encoding: utf-8 import time from web.core.context import Context from web.ext.analytics import AnalyticsExtension def test_analytics_extension(): ctx = Context(response=Context(headers=dict())) ext = AnalyticsExtension() assert not hasattr(ctx, '_start_time') ext.prepare(ctx) assert hasattr(ctx, '_start_...
# encoding: utf-8 import time import pytest from webob import Request from web.core import Application from web.core.context import Context from web.ext.analytics import AnalyticsExtension def endpoint(context): time.sleep(0.1) return "Hi." sample = Application(endpoint, extensions=[AnalyticsExtension()]) def...
Add test for full processing pipeline.
Add test for full processing pipeline.
Python
mit
marrow/WebCore,marrow/WebCore
01a832d1c761eda01ad94f29709c8e76bd7e82fe
project/models.py
project/models.py
import datetime from project import db, bcrypt class User(db.Model): __tablename__ = "users" id = db.Column(db.Integer, primary_key=True) email = db.Column(db.String, unique=True, nullable=False) password = db.Column(db.String, nullable=False) registered_on = db.Column(db.DateTime, nullable=Fal...
import datetime from project import db, bcrypt class User(db.Model): __tablename__ = "users" id = db.Column(db.Integer, primary_key=True) email = db.Column(db.String, unique=True, nullable=False) password = db.Column(db.String, nullable=False) registered_on = db.Column(db.DateTime, nullable=Fal...
Add rating field to User model
Add rating field to User model
Python
mit
dylanshine/streamschool,dylanshine/streamschool
a013cdbe690271c4ec9bc172c994ff5f6e5808c4
test/test_assetstore_model_override.py
test/test_assetstore_model_override.py
import pytest from girder.models.file import File from girder.models.model_base import Model from girder.utility import assetstore_utilities from girder.utility.model_importer import ModelImporter from girder.utility.abstract_assetstore_adapter import AbstractAssetstoreAdapter class Fake(Model): def initialize(se...
import pytest from girder.models.file import File from girder.models.model_base import Model from girder.utility import assetstore_utilities from girder.utility.model_importer import ModelImporter from girder.utility.abstract_assetstore_adapter import AbstractAssetstoreAdapter class Fake(Model): def initialize(se...
Improve clarity of fake assetstore model fixture
Improve clarity of fake assetstore model fixture
Python
apache-2.0
data-exp-lab/girder,girder/girder,manthey/girder,kotfic/girder,Xarthisius/girder,jbeezley/girder,girder/girder,manthey/girder,kotfic/girder,RafaelPalomar/girder,girder/girder,data-exp-lab/girder,girder/girder,manthey/girder,Xarthisius/girder,RafaelPalomar/girder,RafaelPalomar/girder,RafaelPalomar/girder,Kitware/girder,...
817d9c78f939de2b01ff518356ed0414178aaa6d
avalonstar/apps/api/serializers.py
avalonstar/apps/api/serializers.py
# -*- coding: utf-8 -*- from rest_framework import serializers from apps.broadcasts.models import Broadcast, Series from apps.games.models import Game class BroadcastSerializer(serializers.ModelSerializer): class Meta: depth = 1 model = Broadcast class SeriesSerializer(serializers.ModelSerializ...
# -*- coding: utf-8 -*- from rest_framework import serializers from apps.broadcasts.models import Broadcast, Raid, Series from apps.games.models import Game class BroadcastSerializer(serializers.ModelSerializer): class Meta: depth = 1 model = Broadcast class RaidSerializer(serializers.ModelSeri...
Add Raid to the API.
Add Raid to the API.
Python
apache-2.0
bryanveloso/avalonstar-tv,bryanveloso/avalonstar-tv,bryanveloso/avalonstar-tv
1275fec0e485deef75a4e12956acb919a9fb7439
tests/modules/myInitialPythonModule.py
tests/modules/myInitialPythonModule.py
from jtapi import * import os import sys import re import numpy as np from scipy import misc mfilename = re.search('(.*).py', os.path.basename(__file__)).group(1) ######### # input # ######### print('jt - %s:' % mfilename) handles_stream = sys.stdin handles = gethandles(handles_stream) input_args = readinputargs(h...
from jtapi import * import os import sys import re import numpy as np from scipy import misc mfilename = re.search('(.*).py', os.path.basename(__file__)).group(1) ######### # input # ######### print('jt - %s:' % mfilename) handles_stream = sys.stdin handles = gethandles(handles_stream) input_args = readinputargs(h...
Add more detailed print in first module
Add more detailed print in first module
Python
mit
brainy-minds/Jterator,brainy-minds/Jterator,brainy-minds/Jterator,brainy-minds/Jterator
6deebdc7e5c93d5f61cad97870cea7fb445bb860
onitu/utils.py
onitu/utils.py
import time import redis def connect_to_redis(*args, **kwargs): client = redis.Redis(*args, unix_socket_path='redis/redis.sock', **kwargs) while True: try: assert client.ping() except (redis.exceptions.ConnectionError, AssertionError): time.sleep(0.5) else: ...
import time import redis def connect_to_redis(*args, **kwargs): client = redis.Redis( *args, unix_socket_path='redis/redis.sock', decode_responses=True, **kwargs ) while True: try: assert client.ping() except (redis.exceptions.ConnectionError, ...
Convert Redis keys and values to str
Convert Redis keys and values to str
Python
mit
onitu/onitu,onitu/onitu,onitu/onitu
4d410dec85fc944717a6537e9eef2585a53159b6
python_logging_rabbitmq/formatters.py
python_logging_rabbitmq/formatters.py
# coding: utf-8 import logging from socket import gethostname from .compat import json, text_type class JSONFormatter(logging.Formatter): """ Formatter to convert LogRecord into JSON. Thanks to: https://github.com/lobziik/rlog """ def __init__(self, *args, **kwargs): include = kwargs.pop(...
# coding: utf-8 import logging from socket import gethostname from django.core.serializers.json import DjangoJSONEncoder from .compat import json, text_type class JSONFormatter(logging.Formatter): """ Formatter to convert LogRecord into JSON. Thanks to: https://github.com/lobziik/rlog """ def __i...
Use DjangoJSONEncoder for JSON serialization
Use DjangoJSONEncoder for JSON serialization
Python
mit
albertomr86/python-logging-rabbitmq
bce093df2bbcf12d8eec8f812408a0ea88521d10
squid_url_cleaner.py
squid_url_cleaner.py
#!/usr/bin/python import sys from url_cleaner import removeBlackListedParameters while True: line = sys.stdin.readline().strip() urlList = line.split(' ') urlInput = urlList[0] newUrl = removeBlackListedParameters(urlInput) sys.stdout.write('%s%s' % (newUrl, '\n')) sys.stdout.flush()
#!/usr/bin/python import sys import signal from url_cleaner import removeBlackListedParameters def sig_handle(signal, frame): sys.exit(0) while True: signal.signal(signal.SIGINT, sig_handle) signal.signal(signal.SIGTERM, sig_handle) try: line = sys.stdin.readline().strip() urlList =...
Handle signals for daemon processes, removed deprecated python var sub
Handle signals for daemon processes, removed deprecated python var sub
Python
mit
Ladoo/url_cleaner
e71e42ec8b7ee80937a983a80db61f4e450fb764
tests/__init__.py
tests/__init__.py
from json import loads from os import close, unlink from tempfile import mkstemp from unittest import TestCase from cunhajacaiu import app class FlaskTestCase(TestCase): def setUp(self): # set a test db self.db_handler, self.db_path = mkstemp() app.config['SQLALCHEMY_DATABASE_URI'] = 'sq...
from json import loads from os import close, unlink from tempfile import mkstemp from unittest import TestCase from cunhajacaiu import app class FlaskTestCase(TestCase): def setUp(self): # set a test db self.db_handler, self.db_path = mkstemp() app.config['SQLALCHEMY_DATABASE_URI'] = 'sq...
Test the only untested line
Test the only untested line
Python
mit
cuducos/cunhajacaiu,cuducos/cunhajacaiu,cuducos/cunhajacaiu
d773b01721ab090021139fb9a9397cddd89bd487
tests/conftest.py
tests/conftest.py
#!/usr/bin/env python # encoding: utf8 from __future__ import (absolute_import, print_function, division, unicode_literals) # REV - This has no effect - http://stackoverflow.com/q/18558666/656912 def pytest_report_header(config): return "Testing Enigma functionality"
#!/usr/bin/env python # encoding: utf8 from __future__ import (absolute_import, print_function, division, unicode_literals) from crypto_enigma import __version__ def pytest_report_header(config): return "version: {}".format(__version__)
Add logging of tested package version
Add logging of tested package version
Python
bsd-3-clause
orome/crypto-enigma-py
c2731d22adbf2abc29d73f5759d5d9f0fa124f5f
tests/fixtures.py
tests/fixtures.py
from . import uuid def task_crud(self, shotgun, trigger_poll=lambda: None): name = uuid(8) a = shotgun.create('Task', {'content': name}) trigger_poll() b = self.cached.find_one('Task', [('id', 'is', a['id'])], ['content']) self.assertSameEntity(a, b) name += '-2' shotgun.update('Task', a...
from . import uuid def task_crud(self, shotgun, trigger_poll=lambda: None): shot_name = uuid(8) shot = shotgun.create('Shot', {'code': shot_name}) name = uuid(8) task = shotgun.create('Task', {'content': name, 'entity': shot}) trigger_poll() x = self.cached.find_one('Task', [('id', 'is', ta...
Add entity link to basic crud tests
Add entity link to basic crud tests
Python
bsd-3-clause
westernx/sgcache,westernx/sgcache
85b94f0d9caef0b1d22763371b1279ae2f433944
pyinfra_cli/__main__.py
pyinfra_cli/__main__.py
import os import signal import sys import click import gevent import pyinfra from .legacy import run_main_with_legacy_arguments from .main import cli, main # Set CLI mode pyinfra.is_cli = True # Don't write out deploy.pyc/config.pyc etc sys.dont_write_bytecode = True # Make sure imported files (deploy.py/etc) be...
import os import signal import sys import click import gevent import pyinfra from .legacy import run_main_with_legacy_arguments from .main import cli, main # Set CLI mode pyinfra.is_cli = True # Don't write out deploy.pyc/config.pyc etc sys.dont_write_bytecode = True # Make sure imported files (deploy.py/etc) be...
Fix support for older gevent versions.
Fix support for older gevent versions. Gevent 1.5 removed the `gevent.signal` alias, but some older versions do not have the new `signal_handler` function.
Python
mit
Fizzadar/pyinfra,Fizzadar/pyinfra
90132a3e4f9a0a251d9d1738703e6e927a0e23af
pytest_pipeline/utils.py
pytest_pipeline/utils.py
# -*- coding: utf-8 -*- """ pytest_pipeline.utils ~~~~~~~~~~~~~~~~~~~~~ General utilities. :copyright: (c) 2014 Wibowo Arindrarto <bow@bow.web.id> :license: BSD """ import gzip import hashlib import os def file_md5sum(fname, unzip=False, mode="r", blocksize=65536): if unzip: opener...
# -*- coding: utf-8 -*- """ pytest_pipeline.utils ~~~~~~~~~~~~~~~~~~~~~ General utilities. :copyright: (c) 2014 Wibowo Arindrarto <bow@bow.web.id> :license: BSD """ import gzip import hashlib import os def file_md5sum(fname, unzip=False, blocksize=65536, encoding="utf-8"): if unzip: ...
Use 'rb' mode explicitly in file_md5sum and allow for custom encoding
Use 'rb' mode explicitly in file_md5sum and allow for custom encoding
Python
bsd-3-clause
bow/pytest-pipeline
bc16915aa3c4a7cef456da4193bdcdc34117eab0
tests/test_classes.py
tests/test_classes.py
import unittest import os import gzip import bs4 import logging from classes import ( NbaTeam ) class MockRequests: def get(self, url): pass class TestNbaTeamPage(unittest.TestCase): # read html file and ungzip @classmethod def setUpClass(cls): requester = MockRequests() #...
import unittest import os import gzip import bs4 import logging from classes import ( NbaTeam ) logger = logging.getLogger() logger.setLevel(logging.INFO) logger.addHandler(logging.StreamHandler()) class MockRequests: def get(self, url): pass class TestNbaTeamPage(unittest.TestCase): # read html ...
Add more NbaTeam class tests
Add more NbaTeam class tests
Python
mit
arosenberg01/asdata
29baa0a57fe49c790d4ef5dcdde1e744fc83efde
boundary/alarm_create.py
boundary/alarm_create.py
# # Copyright 2015 BMC Software, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in ...
# # Copyright 2015 BMC Software, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in ...
Remove no needed to duplicate parent behaviour
Remove no needed to duplicate parent behaviour
Python
apache-2.0
boundary/pulse-api-cli,jdgwartney/boundary-api-cli,boundary/boundary-api-cli,jdgwartney/pulse-api-cli,boundary/pulse-api-cli,jdgwartney/pulse-api-cli,jdgwartney/boundary-api-cli,boundary/boundary-api-cli
8d7b2597e73ca82e016e635fe0db840070b7bd7a
semillas_backend/users/serializers.py
semillas_backend/users/serializers.py
#from phonenumber_field.serializerfields import PhoneNumberField from rest_framework import serializers from drf_extra_fields.geo_fields import PointField from .models import User class UserSerializer(serializers.ModelSerializer): """ Usage: from rest_framework.renderers import JSONRenderer from ...
#from phonenumber_field.serializerfields import PhoneNumberField from rest_framework import serializers from drf_extra_fields.geo_fields import PointField from .models import User class UserSerializer(serializers.ModelSerializer): """ Usage: from rest_framework.renderers import JSONRenderer from ...
Add uuid to update user serializer
Add uuid to update user serializer
Python
mit
Semillas/semillas_backend,Semillas/semillas_platform,Semillas/semillas_backend,Semillas/semillas_platform,Semillas/semillas_backend,Semillas/semillas_platform,Semillas/semillas_platform,Semillas/semillas_backend
5bc3e6a3fb112b529f738142850860dd98a9d428
tests/runtests.py
tests/runtests.py
import glob import os import unittest def build_test_suite(): suite = unittest.TestSuite() for test_case in glob.glob('tests/test_*.py'): modname = os.path.splitext(test_case)[0] modname = modname.replace('/', '.') module = __import__(modname, {}, {}, ['1']) suite.addTest(unit...
import glob import os import unittest import sys def build_test_suite(): suite = unittest.TestSuite() for test_case in glob.glob('tests/test_*.py'): modname = os.path.splitext(test_case)[0] modname = modname.replace('/', '.') module = __import__(modname, {}, {}, ['1']) suite.ad...
Make unittest return exit code 1 on failure
Make unittest return exit code 1 on failure This is to allow travis to catch test failures
Python
bsd-3-clause
jorgecarleitao/pyglet-gui
d4412f8573dbfc1b06f2a298cc5c3042c6c468e6
tests/test_api.py
tests/test_api.py
from django.test import TestCase from django_snooze import apis class APITestCase(TestCase): def setUp(self): """Sets up an API object to play with. :returns: None """ self.api = apis.api self.api.discover_models() def test_apps(self): """Test if the right ap...
from django.test import TestCase from django_snooze import apis class APITestCase(TestCase): def setUp(self): """Sets up an API object to play with. :returns: None """ self.api = apis.api self.api.discover_models() def test_apps(self): """Test if the right ap...
Test to see if abstract classes sneak in.
Test to see if abstract classes sneak in. Now that get_models has been found to skip abstract classes, we want to test for this in case this behaviour ever changes.
Python
bsd-3-clause
ainmosni/django-snooze,ainmosni/django-snooze
4a9f0f909abb955ca579b3abec7c6ffef83429af
cli_tests.py
cli_tests.py
import unittest from unittest.mock import patch, call from crc import main class CliTests(unittest.TestCase): def test_cli_no_arguments_provided(self): expected_exit_code = -1 argv = [] with patch('sys.exit') as exit_mock: main(argv) self.assertTrue(exit_mock.calle...
#!/usr/bin/env python3 # # Copyright (c) 2021, Nicola Coretti # All rights reserved. import unittest from unittest.mock import patch, call from crc import main class CliTests(unittest.TestCase): def test_cli_no_arguments_provided(self): expected_exit_code = -1 argv = [] with patch('sys.ex...
Add shebang to cli_tets.py module
Add shebang to cli_tets.py module
Python
bsd-2-clause
Nicoretti/crc
1a5583fdba626059e5481e6099b14b8988316dfe
server/superdesk/locators/__init__.py
server/superdesk/locators/__init__.py
# -*- coding: utf-8; -*- # # This file is part of Superdesk. # # Copyright 2013, 2014 Sourcefabric z.u. and contributors. # # For the full copyright and license information, please see the # AUTHORS and LICENSE files distributed with this source code, or # at https://www.sourcefabric.org/superdesk/license import json ...
# -*- coding: utf-8; -*- # # This file is part of Superdesk. # # Copyright 2013, 2014 Sourcefabric z.u. and contributors. # # For the full copyright and license information, please see the # AUTHORS and LICENSE files distributed with this source code, or # at https://www.sourcefabric.org/superdesk/license import json ...
Fix locators reading on ubuntu
Fix locators reading on ubuntu
Python
agpl-3.0
thnkloud9/superdesk,superdesk/superdesk,marwoodandrew/superdesk-aap,ancafarcas/superdesk,ioanpocol/superdesk-ntb,gbbr/superdesk,liveblog/superdesk,plamut/superdesk,pavlovicnemanja92/superdesk,akintolga/superdesk,pavlovicnemanja92/superdesk,pavlovicnemanja/superdesk,verifiedpixel/superdesk,amagdas/superdesk,akintolga/su...
cffaea8986aa300a632d3a0d39219431efe80f9e
rever/__init__.py
rever/__init__.py
import builtins # setup xonsh ctx and execer builtins.__xonsh_ctx__ = {} from xonsh.execer import Execer builtins.__xonsh_execer__ = Execer(xonsh_ctx=builtins.__xonsh_ctx__) from xonsh.shell import Shell builtins.__xonsh_shell__ = Shell(builtins.__xonsh_execer__, ctx=builtins.__xonsh_c...
import builtins # setup xonsh ctx and execer builtins.__xonsh_ctx__ = {} from xonsh.execer import Execer builtins.__xonsh_execer__ = Execer(xonsh_ctx=builtins.__xonsh_ctx__) from xonsh.shell import Shell builtins.__xonsh_shell__ = Shell(builtins.__xonsh_execer__, ctx=builtins.__xonsh_c...
Raise on subproc error everywhere in rever
Raise on subproc error everywhere in rever
Python
bsd-3-clause
ergs/rever,scopatz/rever
1b75e25746305ec47a72874e854744c395cceec6
src/ocspdash/constants.py
src/ocspdash/constants.py
import os import requests.utils from . import __name__, __version__ OCSPDASH_API_VERSION = 'v0' OCSPDASH_DIRECTORY = os.path.join(os.path.expanduser('~'), '.ocspdash') if not os.path.exists(OCSPDASH_DIRECTORY): os.makedirs(OCSPDASH_DIRECTORY) OCSPDASH_DATABASE_PATH = os.path.join(OCSPDASH_DIRECTORY, 'ocspdash...
import os import requests.utils from . import __name__, __version__ OCSPDASH_API_VERSION = 'v0' OCSPDASH_DIRECTORY = os.environ.get('OCSPDASH_DIRECTORY', os.path.join(os.path.expanduser('~'), '.ocspdash')) if not os.path.exists(OCSPDASH_DIRECTORY): os.makedirs(OCSPDASH_DIRECTORY) OCSPDASH_DATABASE_CONNECTION ...
Allow config to be set from environment
Allow config to be set from environment
Python
mit
scolby33/OCSPdash,scolby33/OCSPdash,scolby33/OCSPdash
255ef7b16258c67586d14e6c8d8d531a3553cd3e
bot/games/tests/test_game_queryset.py
bot/games/tests/test_game_queryset.py
from django.test import TestCase from ..models import Game class QuerySetTests(TestCase): def test_get_by_name(self): gta_v = Game.objects.create(name='GTA V') Game.objects.create(name='Grand Theft Auto V', alias_for=gta_v) game = Game.objects.get_by_name('gta V') self.assertEq...
# -*- coding: utf-8 -*- from django.test import TestCase from ..models import Game class QuerySetTests(TestCase): def test_get_by_name(self): gta_v = Game.objects.create(name='GTA V') Game.objects.create(name='Grand Theft Auto V', alias_for=gta_v) game = Game.objects.get_by_name('gta V...
Add extra test for regression
Add extra test for regression
Python
mit
sergei-maertens/discord-bot,sergei-maertens/discord-bot,sergei-maertens/discord-bot
8e131a0382bac04aa8e04a4aeb3f9cf31d36671f
stock_move_description/__openerp__.py
stock_move_description/__openerp__.py
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (C) 2014-15 Agile Business Group sagl # (<http://www.agilebg.com>) # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Publ...
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (C) 2014-15 Agile Business Group sagl # (<http://www.agilebg.com>) # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Publ...
Remove delivery from depends as useless
Remove delivery from depends as useless
Python
agpl-3.0
open-synergy/stock-logistics-workflow,gurneyalex/stock-logistics-workflow,brain-tec/stock-logistics-workflow,Antiun/stock-logistics-workflow,BT-jmichaud/stock-logistics-workflow,Eficent/stock-logistics-workflow,gurneyalex/stock-logistics-workflow,archetipo/stock-logistics-workflow,acsone/stock-logistics-workflow,BT-fga...
d4dd06558287c655477ce9da9542f748d0261695
notebooks/computer_vision/track_meta.py
notebooks/computer_vision/track_meta.py
# See also examples/example_track/track_meta.py for a longer, commented example track = dict( author_username='ryanholbrook', course_name='computer_vision', course_url='https://www.kaggle.com/ryanholbrook/computer-vision' ) lessons = [ dict( # By convention, this should be a lowercase n...
# See also examples/example_track/track_meta.py for a longer, commented example track = dict( author_username='ryanholbrook', course_name='Computer Vision', course_url='https://www.kaggle.com/ryanholbrook/computer-vision' ) lessons = [ {'topic': topic_name} for topic_name in [ 'The Convolut...
Add tracking for lessons 1, 2, 3
Add tracking for lessons 1, 2, 3
Python
apache-2.0
Kaggle/learntools,Kaggle/learntools
2e63438deb6f733e7e905f4ea299aa0bdce88b3c
changes/api/author_build_index.py
changes/api/author_build_index.py
from __future__ import absolute_import, division, unicode_literals from sqlalchemy.orm import joinedload from changes.api.base import APIView from changes.api.auth import get_current_user from changes.models import Author, Build class AuthorBuildIndexAPIView(APIView): def _get_author(self, author_id): i...
from __future__ import absolute_import, division, unicode_literals from sqlalchemy.orm import joinedload from uuid import UUID from changes.api.base import APIView from changes.api.auth import get_current_user from changes.models import Author, Build class AuthorBuildIndexAPIView(APIView): def _get_author(self,...
Validate author_id and return 404 for missing data
Validate author_id and return 404 for missing data
Python
apache-2.0
wfxiang08/changes,dropbox/changes,dropbox/changes,bowlofstew/changes,bowlofstew/changes,dropbox/changes,wfxiang08/changes,wfxiang08/changes,bowlofstew/changes,wfxiang08/changes,bowlofstew/changes,dropbox/changes
00435d8f0cc906878cd6084c78c17cbc5a49b66e
spacy/tests/parser/test_beam_parse.py
spacy/tests/parser/test_beam_parse.py
# coding: utf8 from __future__ import unicode_literals import pytest @pytest.mark.models('en') def test_beam_parse(EN): doc = EN(u'Australia is a country', disable=['ner']) ents = EN.entity(doc, beam_width=2) print(ents)
# coding: utf8 from __future__ import unicode_literals import pytest from ...language import Language from ...pipeline import DependencyParser @pytest.mark.models('en') def test_beam_parse_en(EN): doc = EN(u'Australia is a country', disable=['ner']) ents = EN.entity(doc, beam_width=2) print(ents) def t...
Add extra beam parsing test
Add extra beam parsing test
Python
mit
aikramer2/spaCy,aikramer2/spaCy,aikramer2/spaCy,explosion/spaCy,honnibal/spaCy,honnibal/spaCy,recognai/spaCy,aikramer2/spaCy,explosion/spaCy,honnibal/spaCy,aikramer2/spaCy,spacy-io/spaCy,honnibal/spaCy,recognai/spaCy,spacy-io/spaCy,explosion/spaCy,recognai/spaCy,explosion/spaCy,recognai/spaCy,recognai/spaCy,spacy-io/sp...
671aeff6fbdab93945a7b8a8f242bff9afc6a613
src/odin/fields/future.py
src/odin/fields/future.py
from __future__ import absolute_import from enum import Enum from typing import TypeVar, Optional, Any, Type # noqa from odin.exceptions import ValidationError from . import Field __all__ = ("EnumField",) ET = TypeVar("ET", Enum, Enum) class EnumField(Field): """ Field for handling Python enums. """...
from __future__ import absolute_import from enum import Enum from typing import TypeVar, Optional, Any, Type # noqa from odin.exceptions import ValidationError from . import Field __all__ = ("EnumField",) ET = TypeVar("ET", Enum, Enum) class EnumField(Field): """ Field for handling Python enums. """...
Fix value is "" hand value being None in prepare
Fix value is "" hand value being None in prepare
Python
bsd-3-clause
python-odin/odin
c8c3227cba90a931edb9ae7ee89c5318258a2f25
todoist/managers/live_notifications.py
todoist/managers/live_notifications.py
# -*- coding: utf-8 -*- from .generic import Manager, GetByIdMixin, AllMixin, SyncMixin class LiveNotificationsManager(Manager, GetByIdMixin, AllMixin, SyncMixin): state_name = 'live_notifications' object_type = None # there is no object type associated def set_last_read(self, id): """ ...
# -*- coding: utf-8 -*- from .generic import Manager, GetByIdMixin, AllMixin, SyncMixin class LiveNotificationsManager(Manager, GetByIdMixin, AllMixin, SyncMixin): state_name = 'live_notifications' object_type = None # there is no object type associated def set_last_read(self, id): """ ...
Add support for new is_unread live notification state.
Add support for new is_unread live notification state.
Python
mit
Doist/todoist-python
0fb16c44b13ca467fb8ede67bdc93450712cb2bb
test/tiles/hitile_test.py
test/tiles/hitile_test.py
import dask.array as da import h5py import clodius.tiles.hitile as hghi import numpy as np import os.path as op import tempfile def test_hitile(): array_size = int(1e6) chunk_size = 2**19 data = da.from_array(np.random.random((array_size,)), chunks=(chunk_size,)) with tempfile.TemporaryDirectory() a...
import dask.array as da import h5py import clodius.tiles.hitile as hghi import numpy as np import os.path as op import tempfile def test_hitile(): array_size = int(1e6) chunk_size = 2**19 data = np.random.random((array_size,)) with tempfile.TemporaryDirectory() as td: output_file = op.join(t...
Fix error of applying dask twice
Fix error of applying dask twice
Python
mit
hms-dbmi/clodius,hms-dbmi/clodius
dabc4eb0ad59599a0e801a3af5423861c7dd2105
test_valid_object_file.py
test_valid_object_file.py
from astropy.table import Table TABLE_NAME = 'feder_object_list.csv' def test_table_can_be_read(): objs = Table.read(TABLE_NAME, format='ascii', delimiter=',') columns = ['object', 'ra', 'dec'] for col in columns: assert col in objs.colnames
from astropy.table import Table from astropy.coordinates import ICRS, name_resolve from astropy import units as u TABLE_NAME = 'feder_object_list.csv' MAX_SEP = 5 # arcsec def test_table_can_be_read_and_coords_good(): objs = Table.read(TABLE_NAME, format='ascii', delimiter=',') columns = ['object', 'ra', 'd...
Add test that object coordinates are accurate
Add test that object coordinates are accurate Skips over any cases where simbad cannot resolve the name, so it is not perfect...
Python
bsd-2-clause
mwcraig/feder-object-list
358dc8e31477c27da8f286f19daa736489625035
tests/integ/test_basic.py
tests/integ/test_basic.py
"""Basic scenarios, symmetric tests""" import pytest from bloop import ( BaseModel, Column, GlobalSecondaryIndex, Integer, MissingObjects, ) from .models import User def test_crud(engine): engine.bind(User) user = User(email="user@domain.com", username="user", profile="first") engine...
"""Basic scenarios, symmetric tests""" import pytest from bloop import ( BaseModel, Column, GlobalSecondaryIndex, Integer, MissingObjects, ) from .models import User def test_crud(engine): engine.bind(User) user = User(email="user@domain.com", username="user", profile="first") engine...
Use consistent load for integ test stability
Use consistent load for integ test stability
Python
mit
numberoverzero/bloop,numberoverzero/bloop
2c86118cfa2c75787fea22909aaec767e432151e
tests/test_add_language/decorators.py
tests/test_add_language/decorators.py
# tests.decorators import sys from functools import wraps from StringIO import StringIO from mock import patch def redirect_stdout(func): """temporarily redirect stdout to new output stream""" @wraps(func) def wrapper(*args, **kwargs): original_stdout = sys.stdout out = StringIO() ...
# tests.decorators import sys from functools import wraps from StringIO import StringIO def redirect_stdout(func): """temporarily redirect stdout to new output stream""" @wraps(func) def wrapper(*args, **kwargs): original_stdout = sys.stdout out = StringIO() try: sys.s...
Remove use_user_prefs decorator for add_language
Remove use_user_prefs decorator for add_language
Python
mit
caleb531/youversion-suggest,caleb531/youversion-suggest
bc005622a6fcce2ec53bf93a9b6519f923904a61
turbustat/statistics/stats_warnings.py
turbustat/statistics/stats_warnings.py
# Licensed under an MIT open source license - see LICENSE from __future__ import print_function, absolute_import, division class TurbuStatTestingWarning(Warning): ''' Turbustat.statistics warning for untested methods. '''
# Licensed under an MIT open source license - see LICENSE from __future__ import print_function, absolute_import, division class TurbuStatTestingWarning(Warning): ''' Turbustat.statistics warning for untested methods. ''' class TurbuStatMetricWarning(Warning): ''' Turbustat.statistics warning fo...
Add warning for where a distance metric is being misused
Add warning for where a distance metric is being misused
Python
mit
Astroua/TurbuStat,e-koch/TurbuStat
dfd02ec10a904c5ce52162fa512e0850c789ce32
language_explorer/staging_settings.py
language_explorer/staging_settings.py
# Prod-like, but with resources in different locations # Data sources LANGUAGE_EXPLORER_DB_URL = 'postgresql://esteele@/language_explorer' JPHARVEST_DB_URL = 'postgresql://esteele@/jpharvest' WALS_DB_URL = 'postgresql://esteele@/wals2013' SIL_RCEM_TSV_SOURCE = '/home/esteele/lex_data_bundle/iso-639-3_Retirements.tab' ...
# Prod-like, but with resources in different locations # Data sources LANGUAGE_EXPLORER_DB_URL = 'postgresql://esteele@/language_explorer' JPHARVEST_DB_URL = 'postgresql://esteele@/jpharvest' WALS_DB_URL = 'postgresql://esteele@/wals2013' SIL_RCEM_TSV_SOURCE = '/home/esteele/lex_data_bundle/iso-639-3_Retirements.tab' ...
Use staging for creating a static copy, so refer to in-place assets, not deployed assets
Use staging for creating a static copy, so refer to in-place assets, not deployed assets
Python
mit
edwinsteele/language_explorer,edwinsteele/language_explorer,edwinsteele/language_explorer
db8524c1085c16552e548dc7c702f80747804814
unittesting/helpers/view_test_case.py
unittesting/helpers/view_test_case.py
import sublime from unittest import TestCase class ViewTestCase(TestCase): def setUp(self): self.view = sublime.active_window().new_file() settings = self.view.settings() default_settings = getattr(self.__class__, 'view_settings', {}) for key, value in default_settings.items(): ...
import sublime from unittest import TestCase class ViewTestCase(TestCase): def setUp(self): self.view = sublime.active_window().new_file() settings = self.view.settings() default_settings = getattr(self.__class__, 'view_settings', {}) for key, value in default_settings.items(): ...
Use view.close() to close view.
Use view.close() to close view.
Python
mit
randy3k/UnitTesting,randy3k/UnitTesting,randy3k/UnitTesting,randy3k/UnitTesting
c23acde7428d968016af760afe9624c138fc3074
test/library/gyptest-shared-obj-install-path.py
test/library/gyptest-shared-obj-install-path.py
#!/usr/bin/env python # Copyright (c) 2010 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Verifies that .so files that are order only dependencies are specified by their install location rather than by their alias. """ import...
#!/usr/bin/env python # Copyright (c) 2010 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Verifies that .so files that are order only dependencies are specified by their install location rather than by their alias. """ # Pyth...
Add with_statement import for python2.5.
Add with_statement import for python2.5. See http://www.python.org/dev/peps/pep-0343/ which describes the with statement. Review URL: http://codereview.chromium.org/5690003
Python
bsd-3-clause
csulmone/gyp,csulmone/gyp,csulmone/gyp,csulmone/gyp
5a4317a22f84355de98a09bba408bfba6d895507
examples/g/modulegen.py
examples/g/modulegen.py
#! /usr/bin/env python import sys import pybindgen from pybindgen import ReturnValue, Parameter, Module, Function, FileCodeSink def my_module_gen(out_file): mod = Module('g') mod.add_include('"g.h"') mod.add_function('GDoA', None, []) G = mod.add_cpp_namespace("G") G.add_function('GDoB', None, [...
#! /usr/bin/env python import sys import pybindgen from pybindgen import ReturnValue, Parameter, Module, Function, FileCodeSink def my_module_gen(out_file): mod = Module('g') mod.add_include('"g.h"') mod.add_function('GDoA', None, []) G = mod.add_cpp_namespace("G") G.add_function('GDoB', None, [...
Add wrapping of std::ofstream to the example
Add wrapping of std::ofstream to the example
Python
lgpl-2.1
gjcarneiro/pybindgen,gjcarneiro/pybindgen,cawka/pybindgen-old,cawka/pybindgen-old,ftalbrecht/pybindgen,cawka/pybindgen-old,ftalbrecht/pybindgen,ftalbrecht/pybindgen,gjcarneiro/pybindgen,gjcarneiro/pybindgen,ftalbrecht/pybindgen,cawka/pybindgen-old