commit
stringlengths
40
40
old_file
stringlengths
4
150
new_file
stringlengths
4
150
old_contents
stringlengths
0
3.26k
new_contents
stringlengths
1
4.43k
subject
stringlengths
15
501
message
stringlengths
15
4.06k
lang
stringclasses
4 values
license
stringclasses
13 values
repos
stringlengths
5
91.5k
diff
stringlengths
0
4.35k
b44d34f8bc5264d495dc4c2176654b0bd53bfb8a
mistral/api/wsgi.py
mistral/api/wsgi.py
# Copyright 2015 - StackStorm, 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 ...
# Copyright 2015 - StackStorm, 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 ...
Remove transport from WSGI script
Remove transport from WSGI script The setup_app method no longer requires transport as input. Change-Id: I4caf397a48e30822d423c8cf7d40f2773f9aa951 Closes-Bug: 1443654
Python
apache-2.0
dennybaa/mistral,openstack/mistral,StackStorm/mistral,dennybaa/mistral,openstack/mistral,StackStorm/mistral
--- +++ @@ -14,8 +14,6 @@ from mistral.api import app from mistral import config -from mistral.engine import rpc config.parse_args() -transport = rpc.get_transport() -application = app.setup_app(transport=transport) +application = app.setup_app()
a16b51bb26761f8c4a30c06da4c711dac24ac3e0
mr/preprocessing.py
mr/preprocessing.py
import numpy as np from scipy.ndimage.filters import uniform_filter from scipy.ndimage.fourier import fourier_gaussian def bandpass(image, lshort, llong, threshold=1): """Convolve with a Gaussian to remove short-wavelength noise, and subtract out long-wavelength variations, retaining features of intermedi...
import numpy as np from scipy.ndimage.filters import uniform_filter from scipy.ndimage.fourier import fourier_gaussian import warnings first_run = True try: import pyfftw except ImportError: fftn = np.fft.fftn ifftn = np.fft.ifftn else: def _maybe_align(a): global planned if first_run:...
Add optional dependence on FFTW for faster bandpass
ENH: Add optional dependence on FFTW for faster bandpass
Python
bsd-3-clause
daniorerio/trackpy,daniorerio/trackpy
--- +++ @@ -1,6 +1,26 @@ import numpy as np from scipy.ndimage.filters import uniform_filter from scipy.ndimage.fourier import fourier_gaussian +import warnings + + +first_run = True +try: + import pyfftw +except ImportError: + fftn = np.fft.fftn + ifftn = np.fft.ifftn +else: + def _maybe_align(a): + ...
af05872aaf08a32ea7855b80153c0596835755bd
tests/integration/test_webui.py
tests/integration/test_webui.py
import requests import pytest class TestWebUI(object): def get_page(self, page): return requests.get('http://127.0.0.1' + page) pages = [ { 'page': '/', 'matching_text': 'Diamond', }, { 'page': '/scoreboard', }, { ...
import requests import pytest class TestWebUI(object): def get_page(self, page): return requests.get('http://nginx' + page) pages = [ { 'page': '/', 'matching_text': 'Diamond', }, { 'page': '/scoreboard', }, { 'pa...
Modify hostname for web integration tests
Modify hostname for web integration tests
Python
mit
pwnbus/scoring_engine,pwnbus/scoring_engine,pwnbus/scoring_engine,pwnbus/scoring_engine
--- +++ @@ -4,7 +4,7 @@ class TestWebUI(object): def get_page(self, page): - return requests.get('http://127.0.0.1' + page) + return requests.get('http://nginx' + page) pages = [ {
47b031db83f5cb90f786029a6ffbdb7a599145db
timepiece/context_processors.py
timepiece/context_processors.py
from django.conf import settings from timepiece import models as timepiece from timepiece.forms import QuickSearchForm def timepiece_settings(request): default_famfamfam_url = settings.STATIC_URL + 'images/icons/' famfamfam_url = getattr(settings, 'FAMFAMFAM_URL', default_famfamfam_url) context = { ...
from django.conf import settings from timepiece import models as timepiece from timepiece.forms import QuickSearchForm def timepiece_settings(request): default_famfamfam_url = settings.STATIC_URL + 'images/icons/' famfamfam_url = getattr(settings, 'FAMFAMFAM_URL', default_famfamfam_url) context = { ...
Apply active_entries fix from payroll-reports branch
Apply active_entries fix from payroll-reports branch
Python
mit
gaga3966/django-timepiece,josesanch/django-timepiece,BocuStudio/django-timepiece,dannybrowne86/django-timepiece,josesanch/django-timepiece,BocuStudio/django-timepiece,gaga3966/django-timepiece,BocuStudio/django-timepiece,arbitrahj/django-timepiece,caktus/django-timepiece,arbitrahj/django-timepiece,gaga3966/django-timep...
--- +++ @@ -20,11 +20,14 @@ def active_entries(request): - active_entries = timepiece.Entry.objects.filter( - end_time__isnull=True, - ).exclude( - user=request.user, - ).select_related('user', 'project', 'activity') + active_entries = None + + if request.user.is_authenticated(): + ...
943e920603d5507a37c1b0c835c598972f0f2cff
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...
Check github response before parsing
Check github response before parsing
Python
agpl-3.0
City-of-Helsinki/devheldev,City-of-Helsinki/devheldev,terotic/devheldev,terotic/devheldev,City-of-Helsinki/devheldev,terotic/devheldev
--- +++ @@ -16,13 +16,14 @@ def events(self): events = cache.get('github') if not events: - cache.add('github', - requests.get('https://api.github.com/orgs/' + self.github_org_name + '/events?per_page=20').json(), 60) - events = cache.get('git...
6dc019f3495a940340668fd8039b7911db6273b7
resdk/analysis/_register.py
resdk/analysis/_register.py
"""Patch ReSDK resources with analysis methods.""" from __future__ import absolute_import, division, print_function, unicode_literals from resdk.analysis.alignment import bowtie2, hisat2 from resdk.analysis.chip_seq import macs, rose2 from resdk.analysis.expressions import cuffnorm, cuffquant from resdk.analysis.plots...
"""Patch ReSDK resources with analysis methods.""" from __future__ import absolute_import, division, print_function, unicode_literals from resdk.analysis.alignment import bowtie2, hisat2 from resdk.analysis.chip_seq import macs, rose2 from resdk.analysis.expressions import cuffnorm, cuffquant from resdk.analysis.plots...
Fix import error caught by new version of isort (4.2.8)
Fix import error caught by new version of isort (4.2.8)
Python
apache-2.0
genialis/resolwe-bio-py
--- +++ @@ -6,7 +6,6 @@ from resdk.analysis.expressions import cuffnorm, cuffquant from resdk.analysis.plots import bamliquidator, bamplot from resdk.resources import Collection, Relation, Sample - Collection.run_bamliquidator = bamliquidator Collection.run_bamplot = bamplot
30da968a43434088a7839941118e30d26683679e
storm/tests/conftest.py
storm/tests/conftest.py
# (C) Datadog, Inc. 2010-2016 # All rights reserved # Licensed under Simplified BSD License (see LICENSE) import os import pytest from .common import INSTANCE, HOST from datadog_checks.dev import docker_run, get_here, run_command from datadog_checks.dev.conditions import CheckCommandOutput @pytest.fixture(scope='se...
# (C) Datadog, Inc. 2010-2016 # All rights reserved # Licensed under Simplified BSD License (see LICENSE) import os import pytest from .common import INSTANCE, HOST from datadog_checks.dev import docker_run, get_here, run_command from datadog_checks.dev.conditions import CheckCommandOutput @pytest.fixture(scope='se...
Add the -v flag to work with linux nc
Add the -v flag to work with linux nc
Python
bsd-3-clause
DataDog/integrations-extras,DataDog/integrations-extras,DataDog/integrations-extras,DataDog/integrations-extras,DataDog/integrations-extras
--- +++ @@ -19,7 +19,7 @@ run_command( ['docker', 'cp', 'topology-build:/topology.jar', os.path.join(get_here(), 'compose')] ) - nimbus_condition = CheckCommandOutput(['nc', '-z', HOST, '6627'], 'succeeded') + nimbus_condition = CheckCommandOutput(['nc', '-zv', HOST, '6627'], 'suc...
fba4fdf426b0a29ca06deb67587c2bd804adb017
tbgxmlutils/xmlutils.py
tbgxmlutils/xmlutils.py
#!/usr/bin/env python from xml.dom import minidom import xml.etree.ElementTree as ET import xmltodict def add(k, parent=None, txt=None, attrs=None): if parent is None: handle = ET.Element(k) else: handle = ET.SubElement(parent, k) if txt: handle.text = unicode(txt) try: for k, v in attrs.iteritems...
#!/usr/bin/env python from xml.dom import minidom import lxml.etree as ET import xmltodict def add(k, parent=None, txt=None, attrs=None): if parent is None: handle = ET.Element(k) else: handle = ET.SubElement(parent, k) if txt: handle.text = unicode(txt) try: for k, v in attrs.iteritems(): handle....
Use lxml instead of elementtree.
Use lxml instead of elementtree.
Python
mit
Schwarzschild/TBGXMLUtils
--- +++ @@ -1,7 +1,7 @@ #!/usr/bin/env python from xml.dom import minidom -import xml.etree.ElementTree as ET +import lxml.etree as ET import xmltodict def add(k, parent=None, txt=None, attrs=None):
ac3f56f4ed0826600b9adbbf8dfe3b99ce508ac6
migrations/versions/0334_broadcast_message_number.py
migrations/versions/0334_broadcast_message_number.py
""" Revision ID: 0334_broadcast_message_number Revises: 0333_service_broadcast_provider Create Date: 2020-12-04 15:06:22.544803 """ from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import postgresql revision = '0334_broadcast_message_number' down_revision = '0333_service_broadcast_provider' ...
""" Revision ID: 0334_broadcast_message_number Revises: 0333_service_broadcast_provider Create Date: 2020-12-04 15:06:22.544803 """ from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import postgresql revision = '0334_broadcast_message_number' down_revision = '0333_service_broadcast_provider' ...
Delete unneeded code form migration
Delete unneeded code form migration
Python
mit
alphagov/notifications-api,alphagov/notifications-api
--- +++ @@ -28,16 +28,6 @@ sa.ForeignKeyConstraint(['broadcast_provider_message_id'], ['broadcast_provider_message.id'], ), sa.PrimaryKeyConstraint('broadcast_provider_message_number') ) - op.execute( - """ - INSERT INTO - broadcast_provider_message_number (b...
6f3b0c997f7207279bf836edc94db1ac19d2ce1d
src/rabird/core/logging.py
src/rabird/core/logging.py
''' @date 2013-5-9 @author Hong-She Liang <starofrainnight@gmail.com> ''' import sys import os # Import the global logging unit, not our logging . global_logging = __import__('logging') def load_default_config(): arguments = { 'level': None, 'filename': None, 'filemode'...
''' @date 2013-5-9 @author Hong-She Liang <starofrainnight@gmail.com> ''' import sys import os # Import the global logging unit, not our logging . global_logging = __import__('logging') def load_default_config(): arguments = { 'level': None, 'filename': None, 'filemode'...
Use old style string format method to avoid formatting warning
Use old style string format method to avoid formatting warning
Python
apache-2.0
starofrainnight/rabird.core
--- +++ @@ -23,7 +23,7 @@ for k in list(arguments.keys()): try: - envionment_text = 'PYTHON_LOGGING_{}'.format(k.upper()) + envionment_text = 'PYTHON_LOGGING_%s' % k.upper() arguments[k] = os.environ[envionment_text] except ValueError: pass
26c96aaa57c745840944c2aea5613ff861bb717f
invocations/testing.py
invocations/testing.py
from invoke import ctask as task @task(help={ 'module': "Just runs tests/STRING.py.", 'runner': "Use STRING to run tests instead of 'spec'.", 'opts': "Extra flags for the test runner", 'pty': "Whether to run tests under a pseudo-tty", }) def test(c, module=None, runner=None, opts=None, pty=True): ...
import sys from invoke import ctask as task @task(help={ 'module': "Just runs tests/STRING.py.", 'runner': "Use STRING to run tests instead of 'spec'.", 'opts': "Extra flags for the test runner", 'pty': "Whether to run tests under a pseudo-tty", }) def test(c, module=None, runner=None, opts=None, pty...
Quit coverage task early if no coverage installed
Quit coverage task early if no coverage installed
Python
bsd-2-clause
singingwolfboy/invocations,pyinvoke/invocations,mrjmad/invocations
--- +++ @@ -1,3 +1,5 @@ +import sys + from invoke import ctask as task @@ -28,6 +30,8 @@ """ Run tests w/ coverage enabled, generating HTML, & opening it. """ + if not c.run("which coverage", hide=True, warn=True).ok: + sys.exit("You need to 'pip install coverage' to use this task!") ...
2de7427d06ff33bf8bdfe0424e07b3fb34621b07
shop/user/views.py
shop/user/views.py
# -*- coding: utf-8 -*- """User views.""" from flask import Blueprint, render_template from flask_login import login_required blueprint = Blueprint('user', __name__, url_prefix='/users', static_folder='../static') @blueprint.route('/') @login_required def members(): """List members.""" return render_template...
# -*- coding: utf-8 -*- """User views.""" from flask import Blueprint, render_template from flask_login import login_required blueprint = Blueprint( 'user', __name__, url_prefix='/users', static_folder='../static' ) @blueprint.route('/') @login_required def members(): """List members.""" return rende...
Clean up code a bit
Clean up code a bit
Python
bsd-3-clause
joeirimpan/shop,joeirimpan/shop,joeirimpan/shop
--- +++ @@ -3,7 +3,10 @@ from flask import Blueprint, render_template from flask_login import login_required -blueprint = Blueprint('user', __name__, url_prefix='/users', static_folder='../static') +blueprint = Blueprint( + 'user', __name__, + url_prefix='/users', static_folder='../static' +) @blueprin...
0d3b274d220a9bc229d3ed7c14b231b21d5c8299
dthm4kaiako/poet/settings.py
dthm4kaiako/poet/settings.py
"""Settings for POET application.""" NUM_RESOURCES_PER_FORM = 3 MINIMUM_SUBMISSIONS_PER_RESOURCE = 10
"""Settings for POET application.""" NUM_RESOURCES_PER_FORM = 3 MINIMUM_SUBMISSIONS_PER_RESOURCE = 25
Increase threshold for showing resource submissions
Increase threshold for showing resource submissions
Python
mit
uccser/cs4teachers,uccser/cs4teachers,uccser/cs4teachers,uccser/cs4teachers
--- +++ @@ -1,4 +1,4 @@ """Settings for POET application.""" NUM_RESOURCES_PER_FORM = 3 -MINIMUM_SUBMISSIONS_PER_RESOURCE = 10 +MINIMUM_SUBMISSIONS_PER_RESOURCE = 25
ff59a35d5ea90169e34d65bd9ec3a6177e1faebd
thinglang/execution/stack.py
thinglang/execution/stack.py
class StackFrame(object): def __init__(self, instance): self.instance = instance self.data = {} self.idx = 0 self.return_value = None def __setitem__(self, key, value): print('\tSET<{}> {}: {}'.format(self.idx, key, value)) self.data[key] = (self.idx, value) ...
class StackFrame(object): def __init__(self, instance): self.instance = instance self.data = {} self.idx = 0 self.return_value = None def __setitem__(self, key, value): print('\tSET<{}> {}: {}'.format(self.idx, key, value)) self.data[key] = (self.idx, value) ...
Add index assertion during segment exit and fix segment cleanup logic
Add index assertion during segment exit and fix segment cleanup logic
Python
mit
ytanay/thinglang,ytanay/thinglang,ytanay/thinglang,ytanay/thinglang
--- +++ @@ -26,12 +26,15 @@ self.idx += 1 def exit(self): + assert self.idx > 0, 'Cannot exit lowest stack segment' print('\tDECR<{}> -> <{}>'.format(self.idx, self.idx - 1)) self.data = { key: value for key, value in self.data.items() if value[1] != self.idx + ...
f024e340a6a443bb765b67bbdb811fa44fd3d19b
tests/test_resources.py
tests/test_resources.py
from flask import json from helper import TestCase from models import db, Major class StudentsTestCase(TestCase): def setUp(self): super(StudentsTestCase, self).setUp() with self.appx.app_context(): db.session.add(Major(id=1, university_id=1, name='Major1')) db.session.ad...
from flask import json from helper import TestCase from models import db, Major, Student class StudentsTestCase(TestCase): def setUp(self): super(StudentsTestCase, self).setUp() with self.appx.app_context(): db.session.add(Major(id=1, university_id=1, name='Major1')) db.s...
Improve testing of student patching
Improve testing of student patching
Python
agpl-3.0
SCUEvals/scuevals-api,SCUEvals/scuevals-api
--- +++ @@ -1,6 +1,6 @@ from flask import json from helper import TestCase -from models import db, Major +from models import db, Major, Student class StudentsTestCase(TestCase): @@ -28,3 +28,9 @@ rv = self.app.patch('/students/0', headers=headers, data=json.dumps(data)) self.assertEqual(rv....
938043259eefdec21994489d68b1cf737618ba34
test/test_conversion.py
test/test_conversion.py
import unittest from src import conversion class TestNotationConverter(unittest.TestCase): """Tests for NotationConverter class""" def test_alg_search_good_input_a5(self): """Input with 'a5'""" actual_result = main.TileLine('w').line expected_result = ' ' self.assertEqual(...
"""Tests for conversion module""" import unittest from src import conversion class TestNotationConverter(unittest.TestCase): """Tests for NotationConverter class""" def test_alg_search_good_input_a5(self): """Input with 'a5'""" n_con = conversion.NotationConverter() actual_result = n_c...
Add tests for NotationConverter methods
Add tests for NotationConverter methods
Python
mit
blairck/chess_notation
--- +++ @@ -1,3 +1,5 @@ +"""Tests for conversion module""" + import unittest from src import conversion @@ -5,6 +7,38 @@ """Tests for NotationConverter class""" def test_alg_search_good_input_a5(self): """Input with 'a5'""" - actual_result = main.TileLine('w').line - expected_resu...
b6cfa50e127d3f74247ab148219ef6336e445cca
InvenTree/InvenTree/ready.py
InvenTree/InvenTree/ready.py
import sys def canAppAccessDatabase(): """ Returns True if the apps.py file can access database records. There are some circumstances where we don't want the ready function in apps.py to touch the database """ # If any of the following management commands are being executed, # prevent cu...
import sys def canAppAccessDatabase(): """ Returns True if the apps.py file can access database records. There are some circumstances where we don't want the ready function in apps.py to touch the database """ # If any of the following management commands are being executed, # prevent cu...
Allow data operations to run for 'test'
Allow data operations to run for 'test'
Python
mit
inventree/InvenTree,inventree/InvenTree,SchrodingersGat/InvenTree,SchrodingersGat/InvenTree,inventree/InvenTree,SchrodingersGat/InvenTree,inventree/InvenTree,SchrodingersGat/InvenTree
--- +++ @@ -29,7 +29,6 @@ 'collectstatic', 'makemessages', 'compilemessages', - 'test', ] for cmd in excluded_commands:
fef28556bc4d105feb44345782c632b8d3befa3f
server/acre/settings/dev.py
server/acre/settings/dev.py
from .base import * import os DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': os.environ['RDS_DB_NAME'], 'HOST': os.environ['RDS_HOSTNAME'], 'PORT': os.environ['RDS_PORT'], 'USER': os.environ['RDS_USERNAME'], 'PASSWORD': os.envi...
from .base import * import os DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': os.environ['RDS_DB_NAME'], 'HOST': os.environ['RDS_HOSTNAME'], 'PORT': os.environ['RDS_PORT'], 'USER': os.environ['RDS_USERNAME'], 'PASSWORD': os.envi...
Add acre.one to allowed host
Add acre.one to allowed host
Python
mit
yizhang7210/Acre,yizhang7210/Acre,yizhang7210/Acre,yizhang7210/Acre
--- +++ @@ -12,4 +12,4 @@ } } -ALLOWED_HOSTS = [".us-east-2.elasticbeanstalk.com", "localhost"] +ALLOWED_HOSTS = [".acre.one", ".us-east-2.elasticbeanstalk.com", "localhost"]
1636fe834830ebb6644d17f908f893a3c2a41e33
tests/test_sentences.py
tests/test_sentences.py
# import pytest from sdsc import sentencesegmenter @pytest.mark.parametrize("sentence,expected", ( # 1 ("This is a simple ##@command-2## sentence. This one too.", ["This is a simple ##@command-2## sentence", "This one too"]), # 2 ("This is not a test in one go. openSUSE is not written with a capital ...
# import pytest from sdsc import sentencesegmenter @pytest.mark.parametrize("sentence,expected", ( # 0 - a single simple sentence ("This is a simple sentence.", ["This is a simple sentence"]), # 1 - two simple sentences ("This is a simple ##@command-2## sentence. This one is too.", ["This is a si...
Expand the sentence segmentation tests a little()
Expand the sentence segmentation tests a little()
Python
lgpl-2.1
sknorr/suse-doc-style-checker,sknorr/suse-doc-style-checker,sknorr/suse-doc-style-checker
--- +++ @@ -6,26 +6,36 @@ @pytest.mark.parametrize("sentence,expected", ( - # 1 - ("This is a simple ##@command-2## sentence. This one too.", - ["This is a simple ##@command-2## sentence", "This one too"]), - # 2 + # 0 - a single simple sentence + ("This is a simple sentence.", + ["This is a simpl...
dd7513f4146679d11aff6d528f11927131dc692f
feder/monitorings/factories.py
feder/monitorings/factories.py
from .models import Monitoring from feder.users.factories import UserFactory import factory class MonitoringFactory(factory.django.DjangoModelFactory): name = factory.Sequence(lambda n: 'monitoring-%04d' % n) user = factory.SubFactory(UserFactory) class Meta: model = Monitoring django_get...
from .models import Monitoring from feder.users.factories import UserFactory import factory class MonitoringFactory(factory.django.DjangoModelFactory): name = factory.Sequence(lambda n: 'monitoring-%04d' % n) user = factory.SubFactory(UserFactory) description = factory.Sequence(lambda n: 'description no.%...
Add description and template to MonitoringFactory
Add description and template to MonitoringFactory
Python
mit
watchdogpolska/feder,watchdogpolska/feder,watchdogpolska/feder,watchdogpolska/feder
--- +++ @@ -6,6 +6,9 @@ class MonitoringFactory(factory.django.DjangoModelFactory): name = factory.Sequence(lambda n: 'monitoring-%04d' % n) user = factory.SubFactory(UserFactory) + description = factory.Sequence(lambda n: 'description no.%04d' % n) + template = factory.Sequence(lambda n: + ...
b17e39436bde57558c1a9d6e70330a51dd1d0d19
website/addons/osffiles/utils.py
website/addons/osffiles/utils.py
from website.addons.osffiles.exceptions import FileNotFoundError def get_versions(filename, node): """Return file versions for a :class:`NodeFile`. :raises: FileNotFoundError if file does not exists for the node. """ try: return node.files_versions[filename.replace('.', '_')] except KeyEr...
from website.addons.osffiles.exceptions import FileNotFoundError def get_versions(filename, node): """Return IDs for a file's version records. :param str filename: The name of the file. :param Node node: The node which has the requested file. :return: List of ids (strings) for :class:`NodeFile` recor...
Clarify documentation for get_versions and get_latest_version_number.
Clarify documentation for get_versions and get_latest_version_number.
Python
apache-2.0
bdyetton/prettychart,Johnetordoff/osf.io,caneruguz/osf.io,ZobairAlijan/osf.io,brandonPurvis/osf.io,arpitar/osf.io,GageGaskins/osf.io,DanielSBrown/osf.io,brianjgeiger/osf.io,fabianvf/osf.io,caseyrygt/osf.io,dplorimer/osf,MerlinZhang/osf.io,zkraime/osf.io,zkraime/osf.io,hmoco/osf.io,lamdnhan/osf.io,cosenal/osf.io,lyndsys...
--- +++ @@ -2,7 +2,11 @@ def get_versions(filename, node): - """Return file versions for a :class:`NodeFile`. + """Return IDs for a file's version records. + + :param str filename: The name of the file. + :param Node node: The node which has the requested file. + :return: List of ids (strings) for...
bcb8084cc5e84a6417d4e8580005b5f7cf614005
giturlparse/platforms/bitbucket.py
giturlparse/platforms/bitbucket.py
# Imports from .base import BasePlatform class BitbucketPlatform(BasePlatform): PATTERNS = { 'https': r'https://(?P<_user>.+)@(?P<domain>.+)/(?P<owner>.+)/(?P<repo>.+).git', 'ssh': r'git@(?P<domain>.+)/(?P<owner>.+)/(?P<repo>.+).git' } FORMATS = { 'https': r'https://%(owner)s@%(doma...
# Imports from .base import BasePlatform class BitbucketPlatform(BasePlatform): PATTERNS = { 'https': r'https://(?P<_user>.+)@(?P<domain>.+)/(?P<owner>.+)/(?P<repo>.+).git', 'ssh': r'git@(?P<domain>.+):(?P<owner>.+)/(?P<repo>.+).git' } FORMATS = { 'https': r'https://%(owner)s@%(doma...
Fix bug in BitBucket's SSH url
Fix bug in BitBucket's SSH url
Python
apache-2.0
FriendCode/giturlparse.py,yakky/giturlparse.py,yakky/giturlparse
--- +++ @@ -4,10 +4,10 @@ class BitbucketPlatform(BasePlatform): PATTERNS = { 'https': r'https://(?P<_user>.+)@(?P<domain>.+)/(?P<owner>.+)/(?P<repo>.+).git', - 'ssh': r'git@(?P<domain>.+)/(?P<owner>.+)/(?P<repo>.+).git' + 'ssh': r'git@(?P<domain>.+):(?P<owner>.+)/(?P<repo>.+).git' }...
78665865038cf676290fb1058bd2194e4c506869
__init__.py
__init__.py
_VERSION = 'CVS' _TEMP_DIR = '.SloppyCell' import logging logging.basicConfig() logger = logging.getLogger('__init__') # Check for debugging option. I tried using optparse for this, but ran into # issues with ipython and mpirun, both of which pollute sys.argv. import sys for arg in sys.argv: if arg.startswith('--...
_VERSION = 'CVS' _TEMP_DIR = '.SloppyCell' import logging logging.basicConfig() logger = logging.getLogger('__init__') # Check for debugging option. I tried using optparse for this, but ran into # issues with ipython and mpirun, both of which pollute sys.argv. import sys for arg in sys.argv: if arg.startswith('--...
Fix for annoying pypar directory change
Fix for annoying pypar directory change
Python
bsd-3-clause
GutenkunstLab/SloppyCell,GutenkunstLab/SloppyCell
--- +++ @@ -16,16 +16,20 @@ Utility.enable_debugging_msgs(words[1]) else: Utility.enable_debugging_msgs(None) +import os +currdir = os.getcwd() try: import pypar + os.chdir(currdir) HAVE_PYPAR = True num_procs = pypar.size() my_rank = pypar.rank...
0f9418eed089938e0094f40cc15682ef59e041a1
__init__.py
__init__.py
# -*- coding: utf8 -*- import default_settings from flask.ext.plugins import Plugin from flask import current_app as app from pybossa_gravatar.gravatar import Gravatar from pybossa.model.user import User from sqlalchemy import event __plugin__ = "PyBossaGravatar" __version__ = "0.1.0" gravatar = Gravatar() class P...
# -*- coding: utf8 -*- import default_settings from flask.ext.plugins import Plugin from flask import current_app as app from flask import redirect from pybossa_gravatar.gravatar import Gravatar from pybossa.model.user import User from sqlalchemy import event from flask.ext.login import current_user __plugin__ = "PyB...
Add URL rule to set Gravatar for current user
Add URL rule to set Gravatar for current user
Python
bsd-3-clause
alexandermendes/pybossa-gravatar
--- +++ @@ -3,9 +3,11 @@ import default_settings from flask.ext.plugins import Plugin from flask import current_app as app +from flask import redirect from pybossa_gravatar.gravatar import Gravatar from pybossa.model.user import User from sqlalchemy import event +from flask.ext.login import current_user __pl...
8d8863fe178b085c6ce7500996f9c2d2c8f159f6
umibukela/csv_export.py
umibukela/csv_export.py
from collections import OrderedDict def form_questions(form): d = OrderedDict() children = form['children'] for child in children: if 'pathstr' in child and 'control' not in child: d.update({child['pathstr']: ''}) elif 'children' in child: for minor in child['childr...
from collections import OrderedDict def form_questions(form): d = OrderedDict() children = form['children'] for child in children: if 'pathstr' in child and 'control' not in child and child['type'] != 'group': d.update({child['pathstr']: ''}) elif 'children' in child: ...
Make sure correct type is excluded
Make sure correct type is excluded
Python
mit
Code4SA/umibukela,Code4SA/umibukela,Code4SA/umibukela,Code4SA/umibukela
--- +++ @@ -5,7 +5,7 @@ d = OrderedDict() children = form['children'] for child in children: - if 'pathstr' in child and 'control' not in child: + if 'pathstr' in child and 'control' not in child and child['type'] != 'group': d.update({child['pathstr']: ''}) elif 'ch...
6086b970e6c37ca4f343291a35bbb9e533109c1c
flask_wiki/backend/routes.py
flask_wiki/backend/routes.py
from flask_wiki.backend.backend import api from flask_wiki.backend.views import PageView api.add_resource(PageView, '/pages-list', endpoint='pages-list')
from flask_wiki.backend.backend import api from flask_wiki.backend.views import PageView, PageDetail api.add_resource(PageView, '/pages-list', endpoint='pages-list') api.add_resource(PageDetail, '/pages/<slug>', endpoint='page-detail')
Support for page-detail url added.
Support for page-detail url added.
Python
bsd-2-clause
gcavalcante8808/flask-wiki,gcavalcante8808/flask-wiki,gcavalcante8808/flask-wiki
--- +++ @@ -1,4 +1,5 @@ from flask_wiki.backend.backend import api -from flask_wiki.backend.views import PageView +from flask_wiki.backend.views import PageView, PageDetail api.add_resource(PageView, '/pages-list', endpoint='pages-list') +api.add_resource(PageDetail, '/pages/<slug>', endpoint='page-detail')
76a2248ffe8c64b15a6f7d307b6d7c726e97165c
alerts/cloudtrail_logging_disabled.py
alerts/cloudtrail_logging_disabled.py
#!/usr/bin/env python # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. # Copyright (c) 2017 Mozilla Corporation # # Contributors: # Brandon Myers bmyers@mozilla.com fro...
#!/usr/bin/env python # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. # Copyright (c) 2017 Mozilla Corporation # # Contributors: # Brandon Myers bmyers@mozilla.com fro...
Send Cloudtrail logging disabled alert to MOC
Send Cloudtrail logging disabled alert to MOC
Python
mpl-2.0
mozilla/MozDef,Phrozyn/MozDef,ameihm0912/MozDef,gdestuynder/MozDef,ameihm0912/MozDef,mpurzynski/MozDef,mozilla/MozDef,gdestuynder/MozDef,jeffbryner/MozDef,jeffbryner/MozDef,mpurzynski/MozDef,mpurzynski/MozDef,Phrozyn/MozDef,jeffbryner/MozDef,ameihm0912/MozDef,mozilla/MozDef,ameihm0912/MozDef,jeffbryner/MozDef,gdestuynd...
--- +++ @@ -29,7 +29,7 @@ def onEvent(self, event): category = 'AWSCloudtrail' - tags = ['cloudtrail', 'aws'] + tags = ['cloudtrail', 'aws', 'cloudtrailpagerduty'] severity = 'CRITICAL' summary = 'Cloudtrail Logging Disabled: ' + event['_source']['requestParameters'][...
680f9e27ddef3be13b025cffd2041e7fece35f64
pygraphc/similarity/pysmJaroWinkler.py
pygraphc/similarity/pysmJaroWinkler.py
import py_stringmatching from itertools import combinations from time import time jw = py_stringmatching.JaroWinkler() start = time() log_file = '/home/hs32832011/Git/labeled-authlog/dataset/Hofstede2014/dataset1_perday/Dec 1.log' with open(log_file, 'r') as f: lines = f.readlines() log_length = len(lines) for l...
Add Jaro-Winkler distance based on py_stringmatching
Add Jaro-Winkler distance based on py_stringmatching
Python
mit
studiawan/pygraphc
--- +++ @@ -0,0 +1,25 @@ +import py_stringmatching +from itertools import combinations +from time import time + +jw = py_stringmatching.JaroWinkler() +start = time() +log_file = '/home/hs32832011/Git/labeled-authlog/dataset/Hofstede2014/dataset1_perday/Dec 1.log' +with open(log_file, 'r') as f: + lines = f.readlin...
6099451fe088fe74945bbeedeeee66896bd7ff3d
voctocore/lib/sources/__init__.py
voctocore/lib/sources/__init__.py
import logging from lib.config import Config from lib.sources.decklinkavsource import DeckLinkAVSource from lib.sources.imgvsource import ImgVSource from lib.sources.tcpavsource import TCPAVSource from lib.sources.testsource import TestSource from lib.sources.videoloopsource import VideoLoopSource log = logging.getLo...
import logging from lib.config import Config from lib.sources.decklinkavsource import DeckLinkAVSource from lib.sources.imgvsource import ImgVSource from lib.sources.tcpavsource import TCPAVSource from lib.sources.testsource import TestSource from lib.sources.videoloopsource import VideoLoopSource log = logging.getLo...
Use test sources as the default in configuration (and improve warning message, when falling back to)
Use test sources as the default in configuration (and improve warning message, when falling back to)
Python
mit
voc/voctomix,voc/voctomix
--- +++ @@ -21,15 +21,16 @@ sources[name] = ImgVSource(name) elif kind == 'decklink': sources[name] = DeckLinkAVSource(name, has_audio, has_video) - elif kind == 'test': - sources[name] = TestSource(name, has_audio, has_video) elif kind == 'videoloop': sources[name] = Vi...
3d9d1b10149655030d172de38f9caeb5906d093c
source/lucidity/__init__.py
source/lucidity/__init__.py
# :coding: utf-8 # :copyright: Copyright (c) 2013 Martin Pengelly-Phillips # :license: See LICENSE.txt. from .template import Template
# :coding: utf-8 # :copyright: Copyright (c) 2013 Martin Pengelly-Phillips # :license: See LICENSE.txt. import os import uuid import imp from .template import Template def discover_templates(paths=None, recursive=True): '''Search *paths* for mount points and load templates from them. *paths* should be a li...
Add helper method to load templates from disk.
Add helper method to load templates from disk.
Python
apache-2.0
4degrees/lucidity,nebukadhezer/lucidity,BigRoy/lucidity
--- +++ @@ -2,5 +2,53 @@ # :copyright: Copyright (c) 2013 Martin Pengelly-Phillips # :license: See LICENSE.txt. +import os +import uuid +import imp + from .template import Template + +def discover_templates(paths=None, recursive=True): + '''Search *paths* for mount points and load templates from them. + + ...
74eb0a324acd75f43aa4efa731c7fc289c5987dd
medium/combination-sum-iii/python/combination-sum-iii.py
medium/combination-sum-iii/python/combination-sum-iii.py
class Solution(object): def combinationSum3(self, k, n): """ :type k: int :type n: int :rtype: List[List[int]] """ # Use recursion to resolve the problem # The algorithm complexity is high due to it has to iterate from one # for each call given k, n. ...
Resolve Combination Sum III with recursion
Resolve Combination Sum III with recursion
Python
apache-2.0
shuquan/leetcode
--- +++ @@ -0,0 +1,42 @@ +class Solution(object): + def combinationSum3(self, k, n): + """ + :type k: int + :type n: int + :rtype: List[List[int]] + """ + + # Use recursion to resolve the problem + # The algorithm complexity is high due to it has to iterate from one...
b4d3bae4223671ddda05e864fcd34bd71e188f05
tangled/web/exc.py
tangled/web/exc.py
import datetime import html from webob.exc import HTTPInternalServerError class ConfigurationError(Exception): """Exception used to indicate a configuration error.""" class DebugHTTPInternalServerError(HTTPInternalServerError): """For use in debug mode, mainly for showing tracebacks.""" body_templat...
import datetime import html from webob.exc import HTTPInternalServerError class ConfigurationError(Exception): """Exception used to indicate a configuration error.""" class DebugHTTPInternalServerError(HTTPInternalServerError): """For use in debug mode, mainly for showing tracebacks.""" body_templat...
Add a hack so weird chars don't cause issues
Add a hack so weird chars don't cause issues In DebugHTTPInternalServerError.__init__. Should probably figure out the underlying cause. Or don't inherit from HTTPInternalServerError.
Python
mit
TangledWeb/tangled.web
--- +++ @@ -21,3 +21,7 @@ body_template = self.body_template.format( timestamp=now, content=content) super().__init__(body_template=body_template, *args, **kwargs) + + # HACK + safe_substitue = self.body_template_obj.safe_substitute + self.body_template_obj.substitu...
0e2e30382def1f911987ca22fce5adc6c6b73fb6
airship/__init__.py
airship/__init__.py
import os import json from flask import Flask, render_template def channels_json(station, escaped=False): channels = [{"name": channel} for channel in station.channels()] jsonbody = json.dumps(channels) if escaped: jsonbody = jsonbody.replace("</", "<\\/") return jsonbody def make_airship(s...
import os import json from flask import Flask, render_template def jsonate(obj, escaped): jsonbody = json.dumps(obj) if escaped: jsonbody = jsonbody.replace("</", "<\\/") return jsonbody def channels_json(station, escaped=False): channels = [{"name": channel} for channel in station.channels...
Fix the grefs route in the airship server
Fix the grefs route in the airship server
Python
mit
richo/airship,richo/airship,richo/airship
--- +++ @@ -4,12 +4,21 @@ from flask import Flask, render_template -def channels_json(station, escaped=False): - channels = [{"name": channel} for channel in station.channels()] - jsonbody = json.dumps(channels) +def jsonate(obj, escaped): + jsonbody = json.dumps(obj) if escaped: jsonbody ...
6f83b42ae9aaf9cd23bc8d15b66157a75bbc3aed
util/createCollector.py
util/createCollector.py
import os import sys import subprocesses THIS_SCRIPT_DIRECTORY = os.path.dirname(os.path.abspath(__file__)) fuzzManagerPath = os.path.abspath(os.path.join(THIS_SCRIPT_DIRECTORY, os.pardir, os.pardir, 'FuzzManager')) if not os.path.exists(fuzzManagerPath): print "Please check out Lithium and FuzzManager side-by-si...
import os import sys THIS_SCRIPT_DIRECTORY = os.path.dirname(os.path.abspath(__file__)) fuzzManagerPath = os.path.abspath(os.path.join(THIS_SCRIPT_DIRECTORY, os.pardir, os.pardir, 'FuzzManager')) if not os.path.exists(fuzzManagerPath): print "Please check out Lithium and FuzzManager side-by-side with funfuzz. Li...
Use the signature (cache) directory specified in .fuzzmanagerconf
Use the signature (cache) directory specified in .fuzzmanagerconf
Python
mpl-2.0
nth10sd/funfuzz,MozillaSecurity/funfuzz,MozillaSecurity/funfuzz,MozillaSecurity/funfuzz,nth10sd/funfuzz,nth10sd/funfuzz
--- +++ @@ -1,6 +1,6 @@ import os import sys -import subprocesses + THIS_SCRIPT_DIRECTORY = os.path.dirname(os.path.abspath(__file__)) @@ -14,13 +14,7 @@ def createCollector(tool): assert tool == "DOMFuzz" or tool == "jsfunfuzz" - - sigCacheDir = os.path.join(subprocesses.normExpUserPath("~"), "fuzz...
28add39cbd964d9a26ff8f12c1ee3668b765c7a7
perforce/p4login.py
perforce/p4login.py
#!/usr/bin/env python3 """Script to automate logging into Perforce. Use P4API to log in to the server. """ import P4 def main(): """Log in to the Perforce server.""" # Yep, pretty much that easy. p4 = P4.P4() p4.connect() p4.run_login() if __name__ == "__main__": main()
#!/usr/bin/env python """Script to automate logging into Perforce.""" import subprocess import sys def main(): """Log in to the Perforce server.""" # Yep, pretty much that easy. result = subprocess.check_output(['p4', 'set', '-q', 'P4PASSWD']) passwd = result.strip().split('=')[1] proc = subproce...
Use p4 cli instead of p4 api
Use p4 cli instead of p4 api
Python
bsd-3-clause
nlfiedler/devscripts,nlfiedler/devscripts
--- +++ @@ -1,19 +1,18 @@ -#!/usr/bin/env python3 -"""Script to automate logging into Perforce. +#!/usr/bin/env python +"""Script to automate logging into Perforce.""" -Use P4API to log in to the server. - -""" - -import P4 +import subprocess +import sys def main(): """Log in to the Perforce server.""" ...
ad42da9cb3c944f5bd5e953f947a0be96a4b8e17
astropy/samp/tests/test_hub_proxy.py
astropy/samp/tests/test_hub_proxy.py
from astropy.samp import conf from astropy.samp.hub import SAMPHubServer from astropy.samp.hub_proxy import SAMPHubProxy def setup_module(module): conf.use_internet = False class TestHubProxy: def setup_method(self, method): self.hub = SAMPHubServer(web_profile=False, mode='multiple', pool_size=1)...
from astropy.samp import conf from astropy.samp.hub import SAMPHubServer from astropy.samp.hub_proxy import SAMPHubProxy def setup_module(module): conf.use_internet = False class TestHubProxy: def setup_method(self, method): self.hub = SAMPHubServer(web_profile=False, mode='multiple', pool_size=1)...
Replace `tmpdir` with `tmp_path` in `samp` tests
Replace `tmpdir` with `tmp_path` in `samp` tests
Python
bsd-3-clause
pllim/astropy,mhvk/astropy,lpsinger/astropy,lpsinger/astropy,mhvk/astropy,larrybradley/astropy,pllim/astropy,lpsinger/astropy,lpsinger/astropy,lpsinger/astropy,astropy/astropy,pllim/astropy,astropy/astropy,larrybradley/astropy,pllim/astropy,astropy/astropy,mhvk/astropy,larrybradley/astropy,larrybradley/astropy,astropy/...
--- +++ @@ -38,9 +38,9 @@ self.proxy.unregister(result['samp.private-key']) -def test_custom_lockfile(tmpdir): +def test_custom_lockfile(tmp_path): - lockfile = tmpdir.join('.samptest').realpath().strpath + lockfile = str(tmp_path / '.samptest') hub = SAMPHubServer(web_profile=False, lockf...
b4a92b80d2cfe316d89dbecdf1026486d5288fe0
simulator-perfect.py
simulator-perfect.py
#!/usr/bin/env python3 import timer import sys import utils def simulate(): # A set of files already in the storage seen = set() # The size of the all uploads combined (deduplicated or not) total_in = 0 # The size of the data sent to the service data_in = 0 tmr = timer.Timer() for (...
#!/usr/bin/env python3 import timer import sys import utils def simulate(): # A set of files already in the storage seen = set() # The size of the all uploads combined (deduplicated or not) total_in = 0 # The size of the data sent to the service data_in = 0 tmr = timer.Timer() for (...
Make perfect simulator print data after each upload
Make perfect simulator print data after each upload
Python
apache-2.0
sjakthol/dedup-simulator,sjakthol/dedup-simulator
--- +++ @@ -29,6 +29,8 @@ utils.get_mem_info() ), file=sys.stderr) + print("%i,%i" % (data_in, total_in)) + dedup_percentage = 1 - data_in / total_in print("Simulation complete. stored=%s, uploaded=%s, dedup_percentage=%f" % ( utils.sizeof_fmt(data_in), utils....
1a871cf3bf1fd40342e490599361d57017cdcc65
backend/breach/tests/test_strategy.py
backend/breach/tests/test_strategy.py
from mock import patch from breach.tests.base import RuptureTestCase from breach.strategy import Strategy class StrategyTestCase(RuptureTestCase): @patch('breach.strategy.Sniffer') def test_first_round(self, Sniffer): strategy0 = Strategy(self.victim) work0 = strategy0.get_work() sel...
from mock import patch from breach.tests.base import RuptureTestCase from breach.strategy import Strategy class StrategyTestCase(RuptureTestCase): @patch('breach.strategy.Sniffer') def test_first_round(self, Sniffer): strategy0 = Strategy(self.victim) work0 = strategy0.get_work() sel...
Update first round test, create huffman based on knownalphabet
Update first round test, create huffman based on knownalphabet
Python
mit
dionyziz/rupture,dimriou/rupture,esarafianou/rupture,esarafianou/rupture,dimkarakostas/rupture,dimkarakostas/rupture,esarafianou/rupture,dionyziz/rupture,dimkarakostas/rupture,dionyziz/rupture,esarafianou/rupture,dimkarakostas/rupture,dimkarakostas/rupture,dimriou/rupture,dimriou/rupture,dimriou/rupture,dimriou/rupture...
--- +++ @@ -12,7 +12,7 @@ work0 = strategy0.get_work() self.assertEqual( work0['url'], - 'https://di.uoa.gr/?breach=^testsecret0^1^3^2^5^4^7^6^9^8^' + 'https://di.uoa.gr/?breach=^testsecret0^1^' ) self.assertTrue('amount' in work0) self.a...
91b01e37897ea20f6486118e4dd595439f81006b
ktane/Model/Modules/WiresModule.py
ktane/Model/Modules/WiresModule.py
from enum import Enum from .AbstractModule import AbstractModule, ModuleState class WireColors(Enum): MISSING = 'missing' BLACK = 'black' RED = 'red' WHITE = 'white' BLUE = 'blue' YELLOW = 'yellow' def get_correct_wire(sequence, boolpar): wires_count = get_wires_count(sequence) def ge...
from enum import Enum from .AbstractModule import AbstractModule, ModuleState class WireColors(Enum): MISSING = 'missing' BLACK = 'black' RED = 'red' WHITE = 'white' BLUE = 'blue' YELLOW = 'yellow' def get_correct_wire(sequence, boolpar): wires_count = get_wires_count(sequence) def ge...
Implement Wires helper method get_nth_wire_position
Implement Wires helper method get_nth_wire_position
Python
mit
hanzikl/ktane-controller
--- +++ @@ -21,7 +21,14 @@ def get_nth_wire_position(sequence, n): - NotImplementedError + counter = 0 + for idx, value in enumerate(sequence): + if value != WireColors.MISSING.value: + counter += 1 + if counter == n: + return idx + + return None class WiresMo...
d8d77d4dd98d9287be8a98f0024e5f458bef2b66
tests/test_time.py
tests/test_time.py
from immobilus import immobilus from immobilus.logic import _datetime_to_utc_timestamp from datetime import datetime from time import time def test_time_function(): dt = datetime(1970, 1, 1) assert _datetime_to_utc_timestamp(dt) == 0.0 assert type(_datetime_to_utc_timestamp(dt)) is float assert time...
from immobilus import immobilus from immobilus.logic import _datetime_to_utc_timestamp from datetime import datetime from time import time def test_time_function(): dt = datetime(1970, 1, 1) timestamp = _datetime_to_utc_timestamp(dt) assert timestamp == 0.0 assert type(timestamp) is float assert...
Tidy test - reuse timestamp
Tidy test - reuse timestamp
Python
apache-2.0
pokidovea/immobilus
--- +++ @@ -8,11 +8,12 @@ def test_time_function(): dt = datetime(1970, 1, 1) - assert _datetime_to_utc_timestamp(dt) == 0.0 - assert type(_datetime_to_utc_timestamp(dt)) is float - assert time() != _datetime_to_utc_timestamp(dt) + timestamp = _datetime_to_utc_timestamp(dt) + assert timestamp =...
a9f55a57559a6647c451d38893624be4109be23b
Spiders.py
Spiders.py
''' Created on 2 сент. 2016 г. @author: garet ''' class BaseSpider(): def __init__(self): pass def AddUrls(self, urls): pass def Routing(self, url): pass def SaveCache(self, url, data=None): pass def GetCache(self, url): pass ...
''' Created on 2 сент. 2016 г. @author: garet ''' import queue import sqlite3 class BaseSpider(): def __init__(self): pass def AddUrls(self, urls): pass def Routing(self, url): pass def SaveCache(self, url, data=None): pass def GetCa...
Add SqliteCache for html raw data. Add QueueUrls for list urls.
Add SqliteCache for html raw data. Add QueueUrls for list urls.
Python
bsd-3-clause
SaltusVita/ReoGrab
--- +++ @@ -4,6 +4,8 @@ @author: garet ''' +import queue +import sqlite3 class BaseSpider(): @@ -25,3 +27,64 @@ def Run(self): pass + +class QueueUrls(): + + def __init__(self): + self._urls_queue = queue.Queue() + self._urls_set = set() + + def AddUrls(self, urls): + ...
20eb711953a8981e7b73b59613018514157e352a
spyder_terminal/__init__.py
spyder_terminal/__init__.py
# -*- coding: utf-8 -*- # ----------------------------------------------------------------------------- # Copyright (c) Spyder Project Contributors # # Licensed under the terms of the MIT License # (see LICENSE.txt for details) # ----------------------------------------------------------------------------- """Spyder Te...
# -*- coding: utf-8 -*- # ----------------------------------------------------------------------------- # Copyright (c) Spyder Project Contributors # # Licensed under the terms of the MIT License # (see LICENSE.txt for details) # ----------------------------------------------------------------------------- """Spyder Te...
Set development version number to v0.3.0.dev0
Set development version number to v0.3.0.dev0
Python
mit
spyder-ide/spyder-terminal,andfoy/spyder-terminal,spyder-ide/spyder-terminal,andfoy/spyder-terminal,spyder-ide/spyder-terminal,andfoy/spyder-terminal,spyder-ide/spyder-terminal
--- +++ @@ -11,5 +11,5 @@ PLUGIN_CLASS -VERSION_INFO = (0, 2, 3) +VERSION_INFO = (0, 3, 0, 'dev0') __version__ = '.'.join(map(str, VERSION_INFO))
d28bbd597ddbcbf516f490b5bc0511adb63a4be7
utils/autogen/config.py
utils/autogen/config.py
INPUT_DECL_PATHS = [ "../../target/device/libio/export" # "../../../pia-sdk-repo/iolib/arduino/arduiPIA.h" ] AUTOGEN_TEST = 1 if AUTOGEN_TEST == 1: INPUT_DECL_PATHS = [ "./testSuite/" ] VERSION = '0.0.1' TARGET = 'galileo' OUTPUT_COMP_PATH = '../../target/companion/lib/b...
INPUT_DECL_PATHS = [ "../../target/device/libio/export" # "../../../pia-sdk-repo/iolib/arduino/arduiPIA.h" ] AUTOGEN_TEST = 0 if AUTOGEN_TEST == 1: INPUT_DECL_PATHS = [ "./testSuite/" ] VERSION = '0.0.1' TARGET = 'galileo' OUTPUT_COMP_PATH = '../../target/companion/lib/b...
Set default AUTOGEN_TEST to 0
Set default AUTOGEN_TEST to 0
Python
bsd-3-clause
ilc-opensource/io-js,ilc-opensource/io-js,ilc-opensource/io-js,ilc-opensource/io-js,ilc-opensource/io-js
--- +++ @@ -3,7 +3,7 @@ # "../../../pia-sdk-repo/iolib/arduino/arduiPIA.h" ] -AUTOGEN_TEST = 1 +AUTOGEN_TEST = 0 if AUTOGEN_TEST == 1: INPUT_DECL_PATHS = [
caf18b1cd8923e6d070d2652f9969dabba50e81b
lotteryResult.py
lotteryResult.py
#!/usr/bin/env python import sys import json import requests import hashlib def hashToNumber(txhash,total): result = long(txhash, 16) % total return result def getBlocktxs(blockhash, number, total, startnum): url = "https://blockexplorer.com/api/block/" + blockhash params = dict() resp = requests.get...
#!/usr/bin/env python import sys import json import requests def hashToNumber(txhash, total): result = long(txhash, 16) % total return result def getBlocktxs(blockhash, number, total, startnum): url = "https://blockexplorer.com/api/block/" + blockhash params = dict() resp = requests.get(url=ur...
Format code with pep8 and add timeout to requests
Format code with pep8 and add timeout to requests
Python
mit
planetcoder/readerLottery
--- +++ @@ -3,42 +3,43 @@ import sys import json import requests -import hashlib -def hashToNumber(txhash,total): - result = long(txhash, 16) % total - return result +def hashToNumber(txhash, total): + result = long(txhash, 16) % total + return result + def getBlocktxs(blockhash, number, total, st...
5ec99974a6611cc5993bf56f3f0f4e299a89e29d
txircd/modules/cmd_pass.py
txircd/modules/cmd_pass.py
from twisted.words.protocols import irc from txircd.modbase import Command, Module class PassCommand(Command, Module): def onUse(self, user, params): if user.registered == 0: user.sendMessage(irc.ERR_ALREADYREGISTRED, ":Unauthorized command (already registered)") return if not params: user.sendMessage(ir...
from twisted.words.protocols import irc from txircd.modbase import Command, Module class PassCommand(Command, Module): def onUse(self, user, params): if user.registered == 0: user.sendMessage(irc.ERR_ALREADYREGISTRED, ":Unauthorized command (already registered)") return if not params: user.sendMessage(ir...
Add the function (not class) to actions as is now required
Add the function (not class) to actions as is now required
Python
bsd-3-clause
DesertBus/txircd,Heufneutje/txircd,ElementalAlchemist/txircd
--- +++ @@ -24,7 +24,7 @@ def spawn(): return { "actions": { - "register": [self.passcmd] + "register": [self.passcmd.onRegister] }, "commands": { "PASS": self.passcmd
1dd681517fd1831f3990caa043ea8220f5d1bb90
app/app.py
app/app.py
#!/usr/bin/env python3.5 import os,time,asyncio,json from datetime import datetime from aiohttp import web import logging;logging.basicConfig(level=logging.INFO) from tools.log import Log from tools.httptools import Middleware,Route from tools.template import Template from models import * from tools.con...
#!/usr/bin/env python3.5 import os,time,asyncio,json from datetime import datetime from aiohttp import web import logging;logging.basicConfig(level=logging.INFO) from tools.log import Log from tools.httptools import Middleware,Route from tools.template import Template from models import * from tools.con...
Change Template() to Template.init() in init function
Change Template() to Template.init() in init function
Python
mit
free-free/pyblog,free-free/pyblog,free-free/pyblog,free-free/pyblog
--- +++ @@ -12,7 +12,7 @@ def index(): user=yield from User.findall() print(user) - return Template.render('index.html') + return Template('index.html').render() @Route.get('/user/{id}/comment/{comment}') def user(id,comment): return '<h1>%s,%s</h1>'%(id,comment) @@ -21,7 +21,7 @@ def init(loop): print(M...
178474ceb7227313d039666db3c235c2ee18251e
astropy/tests/image_tests.py
astropy/tests/image_tests.py
import matplotlib from matplotlib import pyplot as plt from astropy.utils.decorators import wraps MPL_VERSION = matplotlib.__version__ ROOT = "http://{server}/testing/astropy/2018-10-24T12:38:34.134556/{mpl_version}/" IMAGE_REFERENCE_DIR = (ROOT.format(server='data.astropy.org', mpl_version=MPL_VERSION[:3] + '.x') +...
import matplotlib from matplotlib import pyplot as plt from astropy.utils.decorators import wraps MPL_VERSION = matplotlib.__version__ # The developer versions of the form 3.1.x+... contain changes that will only # be included in the 3.2.x release, so we update this here. if MPL_VERSION[:3] == '3.1' and '+' in MPL_V...
Use 3.2.x reference images for developer version of Matplotlib
Use 3.2.x reference images for developer version of Matplotlib
Python
bsd-3-clause
pllim/astropy,StuartLittlefair/astropy,mhvk/astropy,stargaser/astropy,stargaser/astropy,mhvk/astropy,mhvk/astropy,saimn/astropy,aleksandr-bakanov/astropy,astropy/astropy,lpsinger/astropy,dhomeier/astropy,aleksandr-bakanov/astropy,MSeifert04/astropy,StuartLittlefair/astropy,saimn/astropy,bsipocz/astropy,dhomeier/astropy...
--- +++ @@ -4,6 +4,11 @@ from astropy.utils.decorators import wraps MPL_VERSION = matplotlib.__version__ + +# The developer versions of the form 3.1.x+... contain changes that will only +# be included in the 3.2.x release, so we update this here. +if MPL_VERSION[:3] == '3.1' and '+' in MPL_VERSION: + MPL_VERSI...
ee43ade86df9eb30455e6026671776b1e5be01e5
pyservice/common.py
pyservice/common.py
DEFAULT_CONFIG = { "protocol": "json", "timeout": 2, "strict": True } def scrub_output(context, whitelist, strict=True): r = context.get("response", None) if r is None: context["response"] = {} return if not strict: return context["response"] = {r[k] for k in whitel...
DEFAULT_CONFIG = { "protocol": "json", "timeout": 2, "strict": True } def scrub_output(context, whitelist, strict=True): r = context.get("response", None) if r is None: context["response"] = {} return if not strict: return context["response"] = {k: r[k] for k in whi...
Fix bug in scrub_output where response was creating set, not dict
Fix bug in scrub_output where response was creating set, not dict
Python
mit
numberoverzero/pyservice
--- +++ @@ -12,4 +12,4 @@ return if not strict: return - context["response"] = {r[k] for k in whitelist} + context["response"] = {k: r[k] for k in whitelist}
41a83c6742f0e688dad5a98761c0f0415c77bac9
outgoing_mail.py
outgoing_mail.py
#!/usr/bin/env python # # Copyright 2010 Eric Entzel <eric@ubermac.net> # from google.appengine.api import mail from google.appengine.ext.webapp import template import os from_address = '"EventBot" <admin@myeventbot.com>' def send(to, template_name, values): path = os.path.join(os.path.dirname(__file__), 'emai...
#!/usr/bin/env python # # Copyright 2010 Eric Entzel <eric@ubermac.net> # from google.appengine.api import mail from google.appengine.ext.webapp import template from google.appengine.api import memcache from datetime import datetime import os from_address = '"EventBot" <admin@myeventbot.com>' email_interval = 10 d...
Use memcache to rate-limit outgoing emails.
Use memcache to rate-limit outgoing emails.
Python
mit
eentzel/myeventbot,eentzel/myeventbot,eentzel/myeventbot,eentzel/myeventbot,eentzel/myeventbot
--- +++ @@ -5,15 +5,26 @@ from google.appengine.api import mail from google.appengine.ext.webapp import template +from google.appengine.api import memcache +from datetime import datetime import os from_address = '"EventBot" <admin@myeventbot.com>' +email_interval = 10 def send(to, template_name, values...
0fdda1366b3657614ee76707e617af255634d50b
moa/device/__init__.py
moa/device/__init__.py
from moa.base import MoaBase class Device(MoaBase): ''' By default, the device does not support multi-threading. ''' _activated_set = None def __init__(self, **kwargs): super(Device, self).__init__(**kwargs) self._activated_set = set() def activate(self, identifier, **kwargs): ...
from moa.base import MoaBase class Device(MoaBase): ''' By default, the device does not support multi-threading. ''' _activated_set = None def __init__(self, **kwargs): super(Device, self).__init__(**kwargs) self._activated_set = set() def activate(self, identifier, **kwargs): ...
Fix device activation remove exception.
Fix device activation remove exception.
Python
mit
matham/moa
--- +++ @@ -30,7 +30,7 @@ else: try: active.remove(identifier) - except ValueError: + except KeyError: pass return bool(old_len and not len(active))
cf7b2bb0569431e97cc316dc41924c78806af5a9
drivers/vnfm/gvnfm/gvnfmadapter/driver/pub/config/config.py
drivers/vnfm/gvnfm/gvnfmadapter/driver/pub/config/config.py
# Copyright 2017 ZTE Corporation. # # 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 2017 ZTE Corporation. # # 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 ...
Add code framework of gvnfm-driver
Add code framework of gvnfm-driver Change-Id: Ibb0dd98a73860f538599328b718040df5f3f7007 Issue-Id: NFVO-132 Signed-off-by: fujinhua <302f4934d283b6f50163b4a7fd9b6c869e0ad64e@zte.com.cn>
Python
apache-2.0
open-o/nfvo,open-o/nfvo,open-o/nfvo,open-o/nfvo,open-o/nfvo
--- +++ @@ -20,14 +20,14 @@ REG_TO_MSB_WHEN_START = True REG_TO_MSB_REG_URL = "/openoapi/microservices/v1/services" REG_TO_MSB_REG_PARAM = { - "serviceName": "ztevmanagerdriver", + "serviceName": "gvnfmdriver", "version": "v1", - "url": "/openoapi/ztevmanagerdriver/v1", + "url": "/openoapi/gvnfmdr...
c4c71dd65675f904c34a0d86a80d5abe7bafdbb1
txircd/modules/cmd_user.py
txircd/modules/cmd_user.py
from twisted.words.protocols import irc from txircd.modbase import Command class UserCommand(Command): def onUse(self, user, params): if user.registered == 0: self.sendMessage(irc.ERR_ALREADYREGISTRED, ":Unauthorized command (already registered)") return if params and len(params) < 4: user.sendMessage(ir...
from twisted.words.protocols import irc from txircd.modbase import Command class UserCommand(Command): def onUse(self, user, data): if not user.username: user.registered -= 1 user.username = data["ident"] user.realname = data["gecos"] if user.registered == 0: user.register() def processParams(self, u...
Update the USER command to take advantage of core capabilities as well
Update the USER command to take advantage of core capabilities as well
Python
bsd-3-clause
ElementalAlchemist/txircd,Heufneutje/txircd,DesertBus/txircd
--- +++ @@ -2,22 +2,30 @@ from txircd.modbase import Command class UserCommand(Command): - def onUse(self, user, params): + def onUse(self, user, data): + if not user.username: + user.registered -= 1 + user.username = data["ident"] + user.realname = data["gecos"] if user.registered == 0: - self.sendMess...
2a980eee73fb79b191126c9ec1c41963dcaf1d9c
aim/db/migration/alembic_migrations/versions/f0c056954eee_sg_rule_remote_group_id.py
aim/db/migration/alembic_migrations/versions/f0c056954eee_sg_rule_remote_group_id.py
# Copyright 2017 Cisco, 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...
# Copyright 2020 Cisco, 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...
Fix date in DB migration
Fix date in DB migration
Python
apache-2.0
noironetworks/aci-integration-module,noironetworks/aci-integration-module
--- +++ @@ -1,4 +1,4 @@ -# Copyright 2017 Cisco, Inc. +# Copyright 2020 Cisco, 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
42062493738a166ddc029d111024b17ffa5cda5f
dataviva/apps/scholar/upload_file.py
dataviva/apps/scholar/upload_file.py
class uploadfile(): def __init__(self, name, type=None, size=None, not_allowed_msg=''): self.name = name self.type = type self.size = size self.not_allowed_msg = not_allowed_msg self.url = "data/%s" % name self.delete_url = "delete/%s" % name self.delete_type...
class UploadFile(): def __init__(self, name, type=None, size=None, not_allowed_msg=''): self.name = name self.type = type self.size = size self.not_allowed_msg = not_allowed_msg self.url = "data/%s" % name self.delete_url = "delete/%s" % name self.delete_type...
Update class name to camelcase pattern.
Update class name to camelcase pattern.
Python
mit
DataViva/dataviva-site,DataViva/dataviva-site,DataViva/dataviva-site,DataViva/dataviva-site
--- +++ @@ -1,4 +1,4 @@ -class uploadfile(): +class UploadFile(): def __init__(self, name, type=None, size=None, not_allowed_msg=''): self.name = name
2c082afb4024cafb530ffab6a62cc6602e75e092
stock_request_picking_type/models/stock_request_order.py
stock_request_picking_type/models/stock_request_order.py
# Copyright 2019 Open Source Integrators # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html). from odoo import api, fields, models class StockRequestOrder(models.Model): _inherit = 'stock.request.order' @api.model def _get_default_picking_type(self): return self.env['stock.picki...
# Copyright 2019 Open Source Integrators # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html). from odoo import api, fields, models class StockRequestOrder(models.Model): _inherit = 'stock.request.order' @api.model def _get_default_picking_type(self): return self.env['stock.picki...
Synchronize Picking Type and Warehouse
[IMP] Synchronize Picking Type and Warehouse [IMP] User write()
Python
agpl-3.0
Vauxoo/stock-logistics-warehouse,Vauxoo/stock-logistics-warehouse,Vauxoo/stock-logistics-warehouse
--- +++ @@ -19,3 +19,12 @@ picking_type_id = fields.Many2one( 'stock.picking.type', 'Operation Type', default=_get_default_picking_type, required=True) + + @api.onchange('warehouse_id') + def onchange_warehouse_picking_id(self): + if self.warehouse_id: + picking_type_id ...
be0a078aa004470a450dddfa5a8e770b2e0ad97c
disk/datadog_checks/disk/__init__.py
disk/datadog_checks/disk/__init__.py
# (C) Datadog, Inc. 2018 # All rights reserved # Licensed under a 3-clause BSD style license (see LICENSE) from .__about__ import __version__ from .disk import Disk all = [ '__version__', 'Disk' ]
# (C) Datadog, Inc. 2018 # All rights reserved # Licensed under a 3-clause BSD style license (see LICENSE) from .__about__ import __version__ # NOQA F401 from .disk import Disk # NOQA F401 all = [ '__version__', 'Disk' ]
Fix flake8 issues and ignore unused
[Disk] Fix flake8 issues and ignore unused
Python
bsd-3-clause
DataDog/integrations-core,DataDog/integrations-core,DataDog/integrations-core,DataDog/integrations-core,DataDog/integrations-core,DataDog/integrations-core,DataDog/integrations-core,DataDog/integrations-core,DataDog/integrations-core,DataDog/integrations-core
--- +++ @@ -1,9 +1,9 @@ # (C) Datadog, Inc. 2018 # All rights reserved # Licensed under a 3-clause BSD style license (see LICENSE) -from .__about__ import __version__ -from .disk import Disk +from .__about__ import __version__ # NOQA F401 +from .disk import Disk # NOQA F401 all = [ - '__version__', 'Disk' + ...
a4f41648cd0318694d551b067309539df475c2d7
tests/test_function_calls.py
tests/test_function_calls.py
from thinglang.runner import run def test_function_calls(): assert run(""" thing Program does start number n = 1 number m = 2 Output.write("before n=", n, " m=", m) self.say_hello() Output.write("after n=", n, " m=", m) does say_hello number n = 3 O...
from thinglang.runner import run def test_zero_arg_function_calls(): assert run(""" thing Program does start number n = 1 number m = 2 Output.write("before n=", n, " m=", m) self.say_hello() Output.write("after n=", n, " m=", m) does say_hello number n = 3 ...
Test for method argument calls
Test for method argument calls
Python
mit
ytanay/thinglang,ytanay/thinglang,ytanay/thinglang,ytanay/thinglang
--- +++ @@ -1,7 +1,7 @@ from thinglang.runner import run -def test_function_calls(): +def test_zero_arg_function_calls(): assert run(""" thing Program does start @@ -19,3 +19,17 @@ hello 3 after n= 1 m= 2 """.strip() + + +def test_multi_arg_function_calls(): + assert run(""" +thing Program ...
ebbc68da19755097b2131d60bc9757ecb4dc6d4c
bundles/auth/models/token.py
bundles/auth/models/token.py
import hashlib import random import string from ext.aboard.model import * def set_value(token): """Randomly create and return a value.""" value = str(token.user) + "_" + str(token.timestamp) len_rand = random.randint(20, 40) to_pick = string.digits + string.ascii_letters + \ "_-+^$" fo...
import hashlib import random import string from ext.aboard.model import * class Token(Model): """A token model.""" id = None user = Integer() timestamp = Integer() value = String(pkey=True) def __init__(self, user=None, timestamp=None): value = None if user and t...
Use the Model constructor to generate a default value
[user] Use the Model constructor to generate a default value
Python
bsd-3-clause
v-legoff/pa-poc2,v-legoff/pa-poc2
--- +++ @@ -3,22 +3,6 @@ import string from ext.aboard.model import * - -def set_value(token): - """Randomly create and return a value.""" - value = str(token.user) + "_" + str(token.timestamp) - len_rand = random.randint(20, 40) - to_pick = string.digits + string.ascii_letters + \ - "_-+^$...
1b40a51e371d10cc37f4d8f8c7557dbc741d690f
butterfly/ImageLayer/HDF5.py
butterfly/ImageLayer/HDF5.py
from Datasource import Datasource import numpy as np import h5py class HDF5(Datasource): pass @classmethod def load_tile(ds, query): Sk,Sj,Si = query.all_scales path = query.OUTPUT.INFO.PATH.VALUE (K0,J0,I0),(K1,J1,I1) = query.source_bounds with h5py.File(path) as fd: ...
from Datasource import Datasource import numpy as np import h5py class HDF5(Datasource): pass @classmethod def load_tile(ds, query): Sk,Sj,Si = query.all_scales path = query.OUTPUT.INFO.PATH.VALUE z0,y0,x0 = query.index_zyx*query.blocksize z1,y1,x1 = query.index_zyx*query.bl...
Fix loading a whole tile into memory.
Fix loading a whole tile into memory.
Python
mit
Rhoana/butterfly,Rhoana/butterfly,Rhoana/butterfly2,Rhoana/butterfly,Rhoana/butterfly
--- +++ @@ -8,9 +8,10 @@ def load_tile(ds, query): Sk,Sj,Si = query.all_scales path = query.OUTPUT.INFO.PATH.VALUE - (K0,J0,I0),(K1,J1,I1) = query.source_bounds + z0,y0,x0 = query.index_zyx*query.blocksize + z1,y1,x1 = query.index_zyx*query.blocksize + query.blocksize ...
78c5580d349d6bec0715a36c13437177a726f7ad
tests/test_isim.py
tests/test_isim.py
import pytest def test_isim(): import os import shutil import tempfile import yaml from fusesoc.edatools import get_edatool from edalize_common import compare_files, files, param_gen, tests_dir, vpi (parameters, args) = param_gen(['plusarg', 'vlogdefine', 'vlogparam']) work_root = tem...
import pytest def test_isim(): import os import shutil from edalize_common import compare_files, setup_backend, tests_dir ref_dir = os.path.join(tests_dir, __name__) paramtypes = ['plusarg', 'vlogdefine', 'vlogparam'] name = 'test_isim_0' tool = 'isim' tool_optio...
Reduce code duplication in isim test
Reduce code duplication in isim test
Python
bsd-2-clause
olofk/fusesoc,olofk/fusesoc,lowRISC/fusesoc,lowRISC/fusesoc
--- +++ @@ -3,29 +3,20 @@ def test_isim(): import os import shutil - import tempfile - import yaml - from fusesoc.edatools import get_edatool - from edalize_common import compare_files, files, param_gen, tests_dir, vpi + from edalize_common import compare_files, setup_backend, tests_dir - ...
1e60c603321729c71895ac5dc19adc669cce4a72
tests/udev_test.py
tests/udev_test.py
#!/usr/bin/python import unittest import mock class UdevTest(unittest.TestCase): def setUp(self): import blivet.udev blivet.udev.os = mock.Mock() blivet.udev.log = mock.Mock() def test_udev_get_device(self): import blivet.udev devices = blivet.udev.global_udev.list_de...
#!/usr/bin/python import unittest import mock class UdevTest(unittest.TestCase): def setUp(self): import blivet.udev self._blivet_os = blivet.udev.os self._blivet_log = blivet.udev.log self._blivet_util = blivet.udev.util blivet.udev.os = mock.Mock() blivet.udev.lo...
Clean up mocking done by udev tests when finished.
Clean up mocking done by udev tests when finished.
Python
lgpl-2.1
dwlehman/blivet,rvykydal/blivet,AdamWill/blivet,rhinstaller/blivet,vpodzime/blivet,AdamWill/blivet,vojtechtrefny/blivet,vojtechtrefny/blivet,vpodzime/blivet,rvykydal/blivet,rhinstaller/blivet,dwlehman/blivet,jkonecny12/blivet,jkonecny12/blivet
--- +++ @@ -7,8 +7,18 @@ def setUp(self): import blivet.udev + self._blivet_os = blivet.udev.os + self._blivet_log = blivet.udev.log + self._blivet_util = blivet.udev.util blivet.udev.os = mock.Mock() blivet.udev.log = mock.Mock() + blivet.udev.util = mock...
c3029a3796437add90cdd6c0033be70fe5766a3a
mapit/middleware/__init__.py
mapit/middleware/__init__.py
import re from .view_error import * class JSONPMiddleware(object): def process_response(self, request, response): # If the response is a redirect, the callback will be dealt # on the next request: if response.status_code == 302: return response else: if requ...
import re from .view_error import * class JSONPMiddleware(object): def process_response(self, request, response): # If the response is a redirect, the callback will be dealt # on the next request: if response.status_code == 302: return response else: cb = re...
Include typeof check in JSONP callback response.
Include typeof check in JSONP callback response. This is more robust, and helps against attacks such as Rosetta Flash: https://miki.it/blog/2014/7/8/abusing-jsonp-with-rosetta-flash/
Python
agpl-3.0
opencorato/mapit,chris48s/mapit,opencorato/mapit,Code4SA/mapit,Code4SA/mapit,opencorato/mapit,Code4SA/mapit,chris48s/mapit,chris48s/mapit
--- +++ @@ -9,8 +9,10 @@ if response.status_code == 302: return response else: - if request.GET.get('callback') and re.match('[a-zA-Z0-9_$.]+$', request.GET.get('callback')): - response.content = request.GET.get('callback').encode('utf-8') + b'(' + response.con...
9c2075f13e2aa8ff7a5c4644208e8de17ebefbab
finding-geodesic-basins-with-scipy.py
finding-geodesic-basins-with-scipy.py
# IPython log file import numpy as np from scipy import sparse from skimage import graph from skimage.graph import _mcp image = np.array([[1, 1, 2, 2], [2, 1, 1, 3], [3, 2, 1, 2], [2, 2, 2, 1]]) mcp = graph.MCP_Geometric(image) destinations = [[0, 0], [3, 3]] costs, traceback = mcp.find_costs(destinations) offsets = ...
# IPython log file # See https://stackoverflow.com/questions/62135639/mcp-geometrics-for-calculating-marketsheds/62144556 import numpy as np from scipy import sparse from skimage import graph from skimage.graph import _mcp image = np.array([[1, 1, 2, 2], [2, 1, 1, 3], [3, 2, 1, 2], [2, 2, 2, 1]]) mcp = graph.MCP_Geom...
Add link to SO question
Add link to SO question
Python
bsd-3-clause
jni/useful-histories
--- +++ @@ -1,4 +1,5 @@ # IPython log file +# See https://stackoverflow.com/questions/62135639/mcp-geometrics-for-calculating-marketsheds/62144556 import numpy as np from scipy import sparse from skimage import graph
897b637ca9de93b7107cd6d6ab76ed0cb485aba9
classifiers/ppmc.py
classifiers/ppmc.py
__author__ = 'sharvey' from classifiers import Classifier from corpus.mysql.reddit import RedditMySQLCorpus from ppm import Trie class RedditPPM(Classifier): corpus = None trie = None user = None reddit = None order = 5 def __init__(self, corpus): self.corpus = corpus def train(...
__author__ = 'sharvey' from classifiers import Classifier from corpus.mysql.reddit import RedditMySQLCorpus from ppm import Trie class RedditPPM(Classifier): corpus = None trie = None user = None reddit = None order = 5 def __init__(self, corpus): self.corpus = corpus def train(...
Add field for test result return
Add field for test result return
Python
mit
worldwise001/stylometry
--- +++ @@ -37,11 +37,7 @@ test_bits += newtrie.bit_encoding del newtrie results.append({'id': row['id'], + 'username': row['username'], 'label': (self.user == row['username']), 'score': tes...
10be9375fb201d7a271babb81ac25c22c70f219b
template.py
template.py
# -*- coding: utf-8 -*- # Copyright (C) 2009-2010, Luis Pedro Coelho <lpc@cmu.edu> # vim: set ts=4 sts=4 sw=4 expandtab smartindent: # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software witho...
# -*- coding: utf-8 -*- # Copyright (C) 2009-2010, Luis Pedro Coelho <lpc@cmu.edu> # vim: set ts=4 sts=4 sw=4 expandtab smartindent: # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software withou...
Remove spaces at the end of lines.
Remove spaces at the end of lines.
Python
mit
luispedro/waldo,luispedro/waldo
--- +++ @@ -1,17 +1,17 @@ # -*- coding: utf-8 -*- # Copyright (C) 2009-2010, Luis Pedro Coelho <lpc@cmu.edu> # vim: set ts=4 sts=4 sw=4 expandtab smartindent: -# +# # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Softwar...
19634d62f5a9b2c1aa9f867c247f46ed7f19ac07
openstack_dashboard/views.py
openstack_dashboard/views.py
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2012 Nebula, 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 # # ...
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2012 Nebula, 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 # # ...
Fix issues with importing the Login form
Fix issues with importing the Login form The Login form lives in openstack_auth.forms and should be directly imported from that file. Change-Id: I42808530024bebb01604adbf4828769812856bf3 Closes-Bug: #1332149 (cherry picked from commit 345ccc9d503e6e55fe46d7813958c0081cc1cffe)
Python
apache-2.0
rickerc/horizon_audit,rickerc/horizon_audit,rickerc/horizon_audit
--- +++ @@ -19,7 +19,7 @@ import horizon -from openstack_auth import views +from openstack_auth import forms def get_user_home(user): @@ -32,7 +32,7 @@ def splash(request): if request.user.is_authenticated(): return shortcuts.redirect(get_user_home(request.user)) - form = views.Login(reque...
552caa1d1fefcc48107eae02091aaca4a39123b4
src/zeit/content/cp/field.py
src/zeit/content/cp/field.py
import zc.form.field import zope.schema.interfaces class DynamicCombination(zc.form.field.Combination): def __init__(self, type_field, type_interface, **kw): self.type_field = type_field self.type_field.__name__ = "combination_00" self.fields = (type_field,) self.type_interface = ...
import zc.form.field import zc.form.interfaces import zope.schema.interfaces class DynamicCombination(zc.form.field.Combination): def __init__(self, type_field, type_interface, **kw): self.type_field = type_field self.type_field.__name__ = "combination_00" self.fields = (type_field,) ...
Support sequences with value_type other than combination
TMS-227: Support sequences with value_type other than combination
Python
bsd-3-clause
ZeitOnline/zeit.content.cp,ZeitOnline/zeit.content.cp
--- +++ @@ -1,4 +1,5 @@ import zc.form.field +import zc.form.interfaces import zope.schema.interfaces @@ -12,16 +13,18 @@ super(zc.form.field.Combination, self).__init__(**kw) def generate_fields(self, selector): - fields = [] + result = [] field = self.type_interface[sele...
0b4097394fd05da204624d1c6093176feb158bb1
ajaxuploader/backends/thumbnail.py
ajaxuploader/backends/thumbnail.py
import os from sorl.thumbnail import get_thumbnail from ajaxuploader.backends.local import LocalUploadBackend class ThumbnailUploadBackend(LocalUploadBackend): def __init__(self, dimension): self._dimension = dimension def upload_complete(self, request, filename): thumbnail = get_thumbna...
import os from django.conf import settings from sorl.thumbnail import get_thumbnail from ajaxuploader.backends.local import LocalUploadBackend class ThumbnailUploadBackend(LocalUploadBackend): DIMENSION = "100x100" def upload_complete(self, request, filename): thumbnail = get_thumbnail(self._path, s...
Use dimension as a constant, so we keep same interface for all backends; also returns full path to the place where image was saved
Use dimension as a constant, so we keep same interface for all backends; also returns full path to the place where image was saved
Python
bsd-3-clause
OnlyInAmerica/django-ajax-uploader,derek-adair/django-ajax-uploader,derek-adair/django-ajax-uploader,skoczen/django-ajax-uploader,brilliant-org/django-ajax-uploader,derek-adair/django-ajax-uploader,brilliant-org/django-ajax-uploader,skoczen/django-ajax-uploader,OnlyInAmerica/django-ajax-uploader,brilliant-org/django-aj...
--- +++ @@ -1,14 +1,14 @@ import os +from django.conf import settings from sorl.thumbnail import get_thumbnail from ajaxuploader.backends.local import LocalUploadBackend class ThumbnailUploadBackend(LocalUploadBackend): - def __init__(self, dimension): - self._dimension = dimension - + DIME...
a3c4f151a9a44aae3528492d4a00a1815c52cda6
website_membership_contact_visibility/models/res_partner.py
website_membership_contact_visibility/models/res_partner.py
# -*- coding: utf-8 -*- # © 2016 Michael Viriyananda # License AGPL-3.0 or later (http://www.gnu.org/licenses/agp from openerp import fields, models class ResPartner(models.Model): _inherit = 'res.partner' website_membership_published = fields.Boolean( string='Visible In The Website', copy=F...
# -*- coding: utf-8 -*- # © 2016 Michael Viriyananda # License AGPL-3.0 or later (http://www.gnu.org/licenses/agp from openerp import fields, models class ResPartner(models.Model): _inherit = 'res.partner' website_membership_published = fields.Boolean( string='Visible Contact Info On The Website', ...
Change the label of "website_membership_published" into "Visible Contact Info On The Website"
Change the label of "website_membership_published" into "Visible Contact Info On The Website"
Python
agpl-3.0
open-synergy/vertical-association
--- +++ @@ -9,6 +9,6 @@ _inherit = 'res.partner' website_membership_published = fields.Boolean( - string='Visible In The Website', + string='Visible Contact Info On The Website', copy=False, default=True)
477faabee7fc674f8ce0c04663b9eff3943e83fa
trac/versioncontrol/web_ui/__init__.py
trac/versioncontrol/web_ui/__init__.py
from trac.versioncontrol.web_ui.browser import * from trac.versioncontrol.web_ui.changeset import * from trac.versioncontrol.web_ui.log import *
from trac.versioncontrol.web_ui.browser import * from trac.versioncontrol.web_ui.changeset import * from trac.versioncontrol.web_ui.log import *
Add missing `svn:eol-style : native` prop, which prevented making clean patches against the early 0.9b1 archives (now both the .zip and the .tar.gz have CRLFs for this file)
Add missing `svn:eol-style : native` prop, which prevented making clean patches against the early 0.9b1 archives (now both the .zip and the .tar.gz have CRLFs for this file) git-svn-id: f68c6b3b1dcd5d00a2560c384475aaef3bc99487@2214 af82e41b-90c4-0310-8c96-b1721e28e2e2
Python
bsd-3-clause
moreati/trac-gitsvn,exocad/exotrac,dokipen/trac,dafrito/trac-mirror,exocad/exotrac,dokipen/trac,exocad/exotrac,dafrito/trac-mirror,moreati/trac-gitsvn,dafrito/trac-mirror,dokipen/trac,moreati/trac-gitsvn,dafrito/trac-mirror,moreati/trac-gitsvn,exocad/exotrac
b56c2063dbb8ea6145048eb8a74bfd2693b2b6f4
app.py
app.py
#!/usr/bin/env python from flask import Flask app = Flask(__name__) @app.route("/ping") def hello(): return "pong" if __name__ == "__main__": app.run()
#!/usr/bin/env python from flask import Flask app = Flask(__name__) @app.route("/ping") def hello(): return "pong" # Returns larger sample JSON from http://json.org/example.html to exercise performance with larger payloads @app.route("/bigger") def big_response(): return '''{ "glossary": { "title":...
Add bigger response payload option of 512B
Add bigger response payload option of 512B
Python
apache-2.0
svanoort/python-client-benchmarks,svanoort/python-client-benchmarks
--- +++ @@ -6,5 +6,31 @@ def hello(): return "pong" +# Returns larger sample JSON from http://json.org/example.html to exercise performance with larger payloads +@app.route("/bigger") +def big_response(): + return '''{ + "glossary": { + "title": "example glossary", + "GlossDiv": { + "...
d7cb9bdd63b381b81bf89c5e3c1cc3031c5928d9
run.py
run.py
""" Entry point for running the sqmpy application standalone """ import os from gevent import monkey monkey.patch_all() from sqmpy.factory import create_app # This line added to support heroku deployment port = int(os.environ.get("PORT", 3000)) app = create_app('../config.py') app.run(host='0.0.0.0', port=port, ...
""" Entry point for running the sqmpy application standalone """ import os from gevent import monkey monkey.patch_all() from sqmpy.factory import create_app # This line added to support heroku deployment port = int(os.environ.get("PORT", 3000)) # Workaround for passing ssh options to underlying library. Since we want...
Add comments and more gitignore
Add comments and more gitignore
Python
bsd-3-clause
mehdisadeghi/sqmpy,mehdisadeghi/sqmpy,mehdisadeghi/sqmpy,simphony/sqmpy,simphony/sqmpy,simphony/sqmpy
--- +++ @@ -9,8 +9,15 @@ # This line added to support heroku deployment port = int(os.environ.get("PORT", 3000)) +# Workaround for passing ssh options to underlying library. Since we want +# to avoid any question upon ssh initialization, therefore we have tp add +# this StrictHostKeyChecking=no to ~/.ssh/config, ...
1f16d194ba78ec8ef50959dc37833ed8d5348c38
tests/ssh_parameters_test.py
tests/ssh_parameters_test.py
#!/usr/bin/env python # -*- coding: utf8 -*- from app.protocols import ssh def ssh_parameters_test(): ss = ssh(hostname = '127.0.0.1', port = 22, username='user', password='password') assert(ss.hostname and ss.port, ss.username and ss.password)
#!/usr/bin/env python # -*- coding: utf8 -*- from app.protocols import ssh def ssh_parameters_test(): ss = ssh(hostname = '127.0.0.1', port = 22, username='user', password='password') assert(ss.hostname and ss.port and ss.username and ss.password)
Fix typo in ssh test
Fix typo in ssh test
Python
mit
rbagrov/xana
--- +++ @@ -5,4 +5,4 @@ def ssh_parameters_test(): ss = ssh(hostname = '127.0.0.1', port = 22, username='user', password='password') - assert(ss.hostname and ss.port, ss.username and ss.password) + assert(ss.hostname and ss.port and ss.username and ss.password)
ca758b2813ae77b795c4318d7d5566cd47ab0ec7
postgres/operations.py
postgres/operations.py
from django.db.migrations.operations.base import Operation from django.db import connection from psycopg2.extras import register_composite class LoadSQLFromScript(Operation): def __init__(self, filename): self.filename = filename @property def reversible(self): return False def state...
from django.db.migrations.operations.base import Operation from django.db import connection from psycopg2.extras import register_composite from .fields.composite import composite_type_created class LoadSQLFromScript(Operation): def __init__(self, filename): self.filename = filename @property def...
Send a signal after creation of composite field.
Send a signal after creation of composite field.
Python
bsd-3-clause
wlanslovenija/django-postgres
--- +++ @@ -2,6 +2,8 @@ from django.db import connection from psycopg2.extras import register_composite +from .fields.composite import composite_type_created + class LoadSQLFromScript(Operation): def __init__(self, filename): @@ -34,6 +36,7 @@ schema_editor.execute('CREATE TYPE %s AS (%s)' % ( ...
7f51b7a74df8e2c8d6756b8c3e95f7fbf47b291b
hashbrown/utils.py
hashbrown/utils.py
from django.conf import settings from .models import Switch def is_active(label, user=None): defaults = getattr(settings, 'HASHBROWN_SWITCH_DEFAULTS', {}) globally_active = defaults[label].get( 'globally_active', False) if label in defaults else False description = defaults[label].get( ...
from django.conf import settings from .models import Switch SETTINGS_KEY = 'HASHBROWN_SWITCH_DEFAULTS' def is_active(label, user=None): defaults = getattr(settings, SETTINGS_KEY, {}) globally_active = defaults[label].get( 'globally_active', False) if label in defaults else False descri...
Use a constant for the 'HASHBROWN_SWITCH_DEFAULTS' settings key so it is easier to re-use.
Use a constant for the 'HASHBROWN_SWITCH_DEFAULTS' settings key so it is easier to re-use.
Python
bsd-2-clause
potatolondon/django-hashbrown
--- +++ @@ -2,8 +2,11 @@ from .models import Switch +SETTINGS_KEY = 'HASHBROWN_SWITCH_DEFAULTS' + + def is_active(label, user=None): - defaults = getattr(settings, 'HASHBROWN_SWITCH_DEFAULTS', {}) + defaults = getattr(settings, SETTINGS_KEY, {}) globally_active = defaults[label].get( 'glob...
df57b55c8ffa2a1948d7442d041415a3f19bbca0
python/Cloudbot/bbm.py
python/Cloudbot/bbm.py
from cloudbot import hook @hook.command("bbmstaff") def bbmStaff(text, message, chan): if chan in ("#bbm-bots", "#bbm-dev", "#bbm-packs", "#builtbrokenmodding", "#builtbroken"): message("Owners: Dmodoomsirius, DarkGuardsman"); message("textureArtist: Morton0000"); message("Developers: Snow...
from cloudbot import hook bbmChannels = ["#bbm-bots","#bbm-dev","#builtbroken","#builtbrokenmodding","#bbm-packs","#icbm","#artillects "] @hook.command("bbmstaff") def bbmStaff(text, message, chan): if any(x in chan for x in bbmChannels): message("Owners: Dmodoomsirius, DarkGuardsman"); #m...
Update and add more commands.
Update and add more commands.
Python
unknown
dmodoomsirius/DmodCode,dmodoomsirius/DmodCode,dsirius/DmodCode,dmodoomsirius/DmodCode,dsirius/DmodCode,dsirius/DmodCode
--- +++ @@ -1,22 +1,34 @@ from cloudbot import hook +bbmChannels = ["#bbm-bots","#bbm-dev","#builtbroken","#builtbrokenmodding","#bbm-packs","#icbm","#artillects "] @hook.command("bbmstaff") def bbmStaff(text, message, chan): - if chan in ("#bbm-bots", "#bbm-dev", "#bbm-packs", "#builtbrokenmodding", "#buil...
a30be93bf4aeef78158898c07252fd29e0303a57
frigg/authentication/models.py
frigg/authentication/models.py
# -*- coding: utf8 -*- from django.contrib.auth.models import AbstractUser from django.utils.functional import cached_property from social.apps.django_app.default.models import UserSocialAuth from frigg.helpers import github class User(AbstractUser): @cached_property def github_token(self): try: ...
# -*- coding: utf8 -*- from django.contrib.auth.models import AbstractUser from django.utils.functional import cached_property from social.apps.django_app.default.models import UserSocialAuth from frigg.helpers import github class User(AbstractUser): @cached_property def github_token(self): try: ...
Fix update permission on user
Fix update permission on user Only run it when user is created, not when it they are saved
Python
mit
frigg/frigg-hq,frigg/frigg-hq,frigg/frigg-hq
--- +++ @@ -16,7 +16,7 @@ return def save(self, *args, **kwargs): - create = hasattr(self, 'id') + create = not hasattr(self, 'id') super(User, self).save(*args, **kwargs) if create: self.update_repo_permissions()
43f647f691f6c279d8e126c8e62e05af81baff38
cal_pipe/update_pipeline_paths.py
cal_pipe/update_pipeline_paths.py
''' Update EVLA pipeline variables to the current system. ''' def update_paths(pipe_dict, ms_path, pipepath): pipe_dict['ms_active'] = ms_path pipe_dict['SDM_name'] = ms_path+".ms" pipe_dict['pipepath'] = pipepath return pipe_dict if __name__ == '__main__': import sys pipe_var_file = st...
''' Update EVLA pipeline variables to the current system. ''' def update_paths(pipe_dict, ms_path, pipepath): pipe_dict['ms_active'] = ms_path pipe_dict['SDM_name'] = ms_path+".ms" pipe_dict['pipepath'] = pipepath return pipe_dict if __name__ == '__main__': import sys pipe_var_file = st...
Change cmd line args to reflect change to CASA
Change cmd line args to reflect change to CASA
Python
mit
e-koch/canfar_scripts,e-koch/canfar_scripts
--- +++ @@ -17,11 +17,11 @@ import sys - pipe_var_file = str(sys.argv[1]) + pipe_var_file = str(sys.argv[5]) - ms_path = str(sys.argv[2]) + ms_path = str(sys.argv[6]) - pipepath = str(sys.argv[3]) + pipepath = str(sys.argv[7]) import shelve
411175d40b449a793528920c3745ca831f6f55e0
debug_toolbar/panels/version.py
debug_toolbar/panels/version.py
import sys import django from django.conf import settings from django.utils.translation import ugettext_lazy as _ from debug_toolbar.panels import DebugPanel class VersionDebugPanel(DebugPanel): """ Panel that displays the Django version. """ name = 'Version' template = 'debug_toolbar/panels/ver...
import sys import django from django.conf import settings from django.utils.translation import ugettext_lazy as _ from debug_toolbar.panels import DebugPanel class VersionDebugPanel(DebugPanel): """ Panel that displays the Django version. """ name = 'Version' template = 'debug_toolbar/panels/ver...
Convert settings.INSTALLED_APPS to list before concatenating django.
Convert settings.INSTALLED_APPS to list before concatenating django. According to the Django documentation settings.INSTALLED_APPS is a tuple. To go for sure that only list + list are concatenated, settings.INSTALLED_APPS is converted to list type before adding ['django'].
Python
bsd-3-clause
stored/django-debug-toolbar,django-debug-toolbar/django-debug-toolbar,megcunningham/django-debug-toolbar,django-debug-toolbar/django-debug-toolbar,spookylukey/django-debug-toolbar,Endika/django-debug-toolbar,ChristosChristofidis/django-debug-toolbar,sidja/django-debug-toolbar,peap/django-debug-toolbar,ivelum/django-deb...
--- +++ @@ -30,7 +30,7 @@ def process_response(self, request, response): versions = {} versions['Python'] = '%d.%d.%d' % sys.version_info[:3] - for app in settings.INSTALLED_APPS + ['django']: + for app in list(settings.INSTALLED_APPS) + ['django']: name = app.split('...
373fd6e9332ca225c1939b5bba675161bdec3596
bika/lims/upgrade/__init__.py
bika/lims/upgrade/__init__.py
# see https://gist.github.com/malthe/704910 import imp import sys def create_modules(module_path): path = "" module = None for element in module_path.split('.'): path += element try: module = __import__(path) except ImportError: new = imp.new_module(path) ...
# see https://gist.github.com/malthe/704910 import imp import sys def create_modules(module_path): path = "" module = None for element in module_path.split('.'): path += element try: module = __import__(path) except ImportError: new = imp.new_module(path) ...
Add return False to be sure all works as expected
Add return False to be sure all works as expected
Python
agpl-3.0
labsanmartin/Bika-LIMS,labsanmartin/Bika-LIMS,veroc/Bika-LIMS,labsanmartin/Bika-LIMS,veroc/Bika-LIMS,veroc/Bika-LIMS,rockfruit/bika.lims,rockfruit/bika.lims
--- +++ @@ -39,4 +39,4 @@ info = qi.upgradeInfo('bika.lims') if info['installedVersion'] > '315': return True - + return False
6168ce884a1234910bace1a026402a21501b499c
buildbot_travis/steps/base.py
buildbot_travis/steps/base.py
from buildbot.process import buildstep from buildbot.process.buildstep import SUCCESS, FAILURE, EXCEPTION from buildbot.process.properties import Properties from twisted.internet import defer from ..travisyml import TravisYml class ConfigurableStep(buildstep.LoggingBuildStep): """ Base class for a step whic...
from buildbot.process import buildstep from buildbot.process.buildstep import SUCCESS, FAILURE, EXCEPTION from buildbot.process.properties import Properties from twisted.internet import defer from ..travisyml import TravisYml class ConfigurableStep(buildstep.LoggingBuildStep): """ Base class for a step whic...
Save .travis.yml into build properties
Save .travis.yml into build properties
Python
unknown
tardyp/buildbot_travis,isotoma/buildbot_travis,tardyp/buildbot_travis,buildbot/buildbot_travis,buildbot/buildbot_travis,isotoma/buildbot_travis,tardyp/buildbot_travis,tardyp/buildbot_travis,buildbot/buildbot_travis
--- +++ @@ -14,6 +14,13 @@ @defer.inlineCallbacks def getStepConfig(self): + config = TravisYml() + + struct = self.build.getProperty(".travis.yml", None) + if struct: + config.parse(struct) + defer.returnValue(config) + log = self.addLog("....
7debde34bd1c5fd903edf4428aa89060da6de037
promgen/celery.py
promgen/celery.py
from __future__ import absolute_import, unicode_literals import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'promgen.settings') app = Celery('promgen') # Using a string here means the worker don't have to serialize # ...
from __future__ import absolute_import, unicode_literals import logging import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'promgen.settings') logger = logging.getLogger(__name__) app = Celery('promgen') # Using a s...
Swap print for logging statement
Swap print for logging statement
Python
mit
kfdm/promgen,kfdm/promgen,kfdm/promgen,kfdm/promgen
--- +++ @@ -1,9 +1,13 @@ from __future__ import absolute_import, unicode_literals + +import logging import os + from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'promgen.settings') +logger = logging.getLogger(__name__) ...
dbfa6398ae84d6920181a750f1447fd1b9a9c521
tests/test_packet.py
tests/test_packet.py
# coding: utf-8 # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. """ Tests for Packet. """ import os import json import pytest from laniakea.core.providers.packet import...
# coding: utf-8 # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. """ Tests for Packet. """ import os import json import pytest from laniakea.core.providers.packet import...
Disable dummy Packet test temporarily
Disable dummy Packet test temporarily
Python
mpl-2.0
nth10sd/laniakea,MozillaSecurity/laniakea,MozillaSecurity/laniakea,nth10sd/laniakea
--- +++ @@ -11,13 +11,14 @@ from laniakea.core.providers.packet import PacketManager -@pytest.fixture -def packet(): - with open(os.path.join(os.getcwd(), 'laniakea/examples/packet.json')) as fo: - conf = json.loads(fo.read()) - return PacketManager(conf) +#@pytest.fixture +#def packet(): +# with...
1239623e7e23d7c51e864f715c0908ef2c0d2765
tests/test_reduce.py
tests/test_reduce.py
import mr_streams as ms import unittest # :::: auxilary functions :::: def sum_reduction(x,y): return x + y class TestMisc(unittest.TestCase): def test_sum_reduce(self): _ = ms.stream([1,2,3,4,5]).reduce(sum_reduction) assert _ is 15 def test_reduce_with_one_element(self): _ = ms...
import mr_streams as ms import unittest # :::: auxilary functions :::: def sum_reduction(x,y): return x + y class TestMisc(unittest.TestCase): def test_sum_reduce(self): _ = ms.stream([1,2,3,4,5]).reduce(sum_reduction) assert _ is 15 def test_initializer(self): _ = ms.stream([1])...
Refactor reduce to handle edge-case streams of length 0 and 1.
Refactor reduce to handle edge-case streams of length 0 and 1.
Python
mit
caffeine-potent/Streamer-Datastructure
--- +++ @@ -11,6 +11,10 @@ _ = ms.stream([1,2,3,4,5]).reduce(sum_reduction) assert _ is 15 + def test_initializer(self): + _ = ms.stream([1]).reduce(sum_reduction, initializer= 1) + assert _ is 2 + def test_reduce_with_one_element(self): _ = ms.stream([1]).reduce(sum...
9a97b9df87f06268ab1075726835da95f4852052
romanesco/format/tree/nested_to_vtktree.py
romanesco/format/tree/nested_to_vtktree.py
from romanesco.format import dict_to_vtkarrays, dict_to_vtkrow import vtk vtk_builder = vtk.vtkMutableDirectedGraph() node_fields = input["node_fields"] edge_fields = input["edge_fields"] dict_to_vtkarrays(input["node_data"], node_fields, vtk_builder.GetVertexData()) if "children" in input and len(input["children"]) >...
from romanesco.format import dict_to_vtkarrays, dict_to_vtkrow import vtk vtk_builder = vtk.vtkMutableDirectedGraph() node_fields = input["node_fields"] edge_fields = input["edge_fields"] dict_to_vtkarrays(input["node_data"], node_fields, vtk_builder.GetVertexData()) if "children" in input and len(input["children"]) >...
Revert "tolerate missing edge data"
Revert "tolerate missing edge data" This reverts commit 93f1f6b24b7e8e61dbbfebe500048db752bc9fed.
Python
apache-2.0
Kitware/romanesco,Kitware/romanesco,Kitware/romanesco,Kitware/romanesco,girder/girder_worker,girder/girder_worker,girder/girder_worker
--- +++ @@ -16,8 +16,7 @@ vtkchild = vtk_builder.AddVertex() vtkparentedge = vtk_builder.AddGraphEdge(vtknode, vtkchild).GetId() dict_to_vtkrow(n["node_data"], vtk_builder.GetVertexData()) - if "edge_data" in n: - dict_to_vtkrow(n["edge_data"], vtk_buil...
5e6e784a5b54f4ac6d1e7841a46772e5aaac9c2d
getpaid/backends/paymill/__init__.py
getpaid/backends/paymill/__init__.py
from django.core.urlresolvers import reverse from django.utils.translation import ugettext_lazy as _ from getpaid.backends import PaymentProcessorBase class PaymentProcessor(PaymentProcessorBase): BACKEND = 'getpaid.backends.paymill' BACKEND_NAME = _('Paymill') BACKEND_ACCEPTED_CURRENCY = ('EUR', 'CZK', 'D...
from django.core.urlresolvers import reverse from django.utils.translation import ugettext_lazy as _ from getpaid.backends import PaymentProcessorBase class PaymentProcessor(PaymentProcessorBase): BACKEND = 'getpaid.backends.paymill' BACKEND_NAME = _('Paymill') BACKEND_ACCEPTED_CURRENCY = ('EUR', 'CZK', 'D...
Add USD to supported currencies in Paymill backend
Add USD to supported currencies in Paymill backend USD was not listed as a supported currency in the init file. This was causing 403 Forbidden errors which were hard to debug, because the Paymill backend simply didn't show up in the payment form and the only error was about unsupported backend.
Python
mit
anih/django-getpaid,glowka/django-getpaid,pawciobiel/django-getpaid,mionch/django-getpaid,dekoza/django-getpaid,dekoza/django-getpaid,mionch/django-getpaid,glowka/django-getpaid,nielsonsantana/django-getpaid,anih/django-getpaid,cypreess/django-getpaid,kamilglod/django-getpaid,pawciobiel/django-getpaid,cypreess/django-g...
--- +++ @@ -6,7 +6,7 @@ BACKEND = 'getpaid.backends.paymill' BACKEND_NAME = _('Paymill') BACKEND_ACCEPTED_CURRENCY = ('EUR', 'CZK', 'DKK', 'HUF', 'ISK', 'ILS', 'LVL', - 'CHF', 'NOK', 'PLN', 'SEK', 'TRY', 'GBP', ) + 'CHF', 'NOK', 'PLN', 'SEK', 'TRY', 'GBP', 'USD', ) def get_gateway_...
b005d0b5eae4328e1482d0571f4dbc7164fef21f
app/eve_api/__init__.py
app/eve_api/__init__.py
VERSION = (0, 1) # Dynamically calculate the version based on VERSION tuple if len(VERSION)>2 and VERSION[2] is not None: str_version = "%d.%d_%s" % VERSION[:3] else: str_version = "%d.%d" % VERSION[:2] __version__ = str_version
Add versioning information to eve_api
Add versioning information to eve_api
Python
bsd-3-clause
nikdoof/test-auth
--- +++ @@ -0,0 +1,11 @@ +VERSION = (0, 1) + +# Dynamically calculate the version based on VERSION tuple +if len(VERSION)>2 and VERSION[2] is not None: + str_version = "%d.%d_%s" % VERSION[:3] +else: + str_version = "%d.%d" % VERSION[:2] + +__version__ = str_version + +
47831156874d31dcf9b8b61118399cb5ac77632c
PyFVCOM/__init__.py
PyFVCOM/__init__.py
""" The FVCOM Python toolbox (PyFvcom) """ __version__ = '1.2' __author__ = 'Pierre Cazenave' __credits__ = ['Pierre Cazenave'] __license__ = 'MIT' __maintainer__ = 'Pierre Cazenave' __email__ = 'pica@pml.ac.uk' import inspect from warnings import warn # Import numpy so we have it across the board. import numpy as n...
""" The FVCOM Python toolbox (PyFvcom) """ __version__ = '1.2' __author__ = 'Pierre Cazenave' __credits__ = ['Pierre Cazenave'] __license__ = 'MIT' __maintainer__ = 'Pierre Cazenave' __email__ = 'pica@pml.ac.uk' import inspect from warnings import warn # Import numpy so we have it across the board. import numpy as n...
Remove the (dodgy) function to convert from an image to data.
Remove the (dodgy) function to convert from an image to data.
Python
mit
pwcazenave/PyFVCOM
--- +++ @@ -20,7 +20,6 @@ from PyFVCOM import cst_tools from PyFVCOM import ctd_tools from PyFVCOM import grid_tools -from PyFVCOM import img2xyz from PyFVCOM import ll2utm from PyFVCOM import ocean_tools from PyFVCOM import stats_tools
9c40a87c5f7d261550c860a69e2679feda53d884
demo_app/demo_app/settings_test.py
demo_app/demo_app/settings_test.py
# -*- coding: utf-8 -*- import warnings from .settings import * # noqa: F403,F401 # Handle system warning as log messages warnings.simplefilter("once") for handler in LOGGING.get("handlers", []): LOGGING["handlers"][handler]["level"] = "CRITICAL" for logger in LOGGING.get("loggers", []): LOGGING["loggers"]...
# -*- coding: utf-8 -*- import warnings from .settings import * # noqa: F403,F401 # Handle system warning as log messages warnings.simplefilter("once") for handler in LOGGING.get("handlers", []): LOGGING["handlers"][handler]["level"] = "CRITICAL" for logger in LOGGING.get("loggers", []): LOGGING["loggers"]...
Unify and simplify for tests.
Unify and simplify for tests.
Python
apache-2.0
pivotal-energy-solutions/django-datatable-view,pivotal-energy-solutions/django-datatable-view,pivotal-energy-solutions/django-datatable-view
751f40ef23250cf9fad1374359393588edee477a
back/blog/models/base.py
back/blog/models/base.py
from sqlalchemy.ext.declarative import declared_attr from blog.lib.database import db class ModelMixin(object): """A base mixin for all models.""" @declared_attr def __tablename__(cls): return cls.__name__.lower() def __str__(self): return '<{} (id={})>'.format(self.__class__.__name_...
from sqlalchemy.ext.declarative import declared_attr from blog.lib.database import db class ModelMixin(object): """A base mixin for all models.""" @declared_attr def __tablename__(cls): return cls.__name__.lower() def __str__(self): return '<{} (id={})>'.format(self.__class__.__name_...
Return "id" key to front instead of "id_".
Return "id" key to front instead of "id_".
Python
mit
astex/living-with-django,astex/living-with-django,astex/living-with-django
--- +++ @@ -20,8 +20,10 @@ def get_dictionary(self): d = {} for column in self.__table__.columns: - key = 'id_' if column.key == 'id' else column.key - d[key] = getattr(self, key) + if column.key == 'id': + d['id'] = getattr(self, 'id_') + ...
564d54c377bf6a8c16cae3681934cc7ba5007c76
bundledApps/wailEndpoint.py
bundledApps/wailEndpoint.py
import tornado.ioloop import tornado.web import requests host = 'localhost' waybackPort = '8080' archiveConfigFile = '/Applications/WAIL.app/config/archive.json' class MainHandler(tornado.web.RequestHandler): def get(self): iwa = isWaybackAccessible() print iwa self.write(iwa) def make_ap...
import tornado.ioloop import tornado.web import requests host = 'localhost' waybackPort = '8080' # Use a separate JSON file that only queries the local WAIL instance for MemGator archiveConfigFile = '/Applications/WAIL.app/config/archive.json' class MainHandler(tornado.web.RequestHandler): def get(self): ...
Add comment to justify separate JSON file existence
Add comment to justify separate JSON file existence
Python
mit
machawk1/wail,machawk1/wail,machawk1/wail,machawk1/wail,machawk1/wail,machawk1/wail,machawk1/wail,machawk1/wail
--- +++ @@ -4,6 +4,7 @@ host = 'localhost' waybackPort = '8080' +# Use a separate JSON file that only queries the local WAIL instance for MemGator archiveConfigFile = '/Applications/WAIL.app/config/archive.json' class MainHandler(tornado.web.RequestHandler):
b32f4955665b8618a9623f6898a15d4da40dc58e
dxtbx/command_line/print_header.py
dxtbx/command_line/print_header.py
def print_header(): import sys from dxtbx.format.Registry import Registry # this will do the lookup for every frame - this is strictly not needed # if all frames are from the same instrument for arg in sys.argv[1:]: format = Registry.find(arg) i = format(arg) print 'Bea...
def print_header(): import sys from dxtbx.format.Registry import Registry # this will do the lookup for every frame - this is strictly not needed # if all frames are from the same instrument for arg in sys.argv[1:]: format = Registry.find(arg) print 'Using header reader: %s' % ...
Print the Format class used
Print the Format class used
Python
bsd-3-clause
dials/dials,dials/dials,dials/dials,dials/dials,dials/dials
--- +++ @@ -7,6 +7,7 @@ for arg in sys.argv[1:]: format = Registry.find(arg) + print 'Using header reader: %s' % format.__name__ i = format(arg) print 'Beam:' print i.get_beam()
c790055fa7e6810703599bc0124507133b8a55fc
crispy_forms/compatibility.py
crispy_forms/compatibility.py
import sys try: basestring except: basestring = str # Python3 PY2 = sys.version_info[0] == 2 if not PY2: text_type = str binary_type = bytes string_types = (str,) integer_types = (int,) else: text_type = unicode binary_type = str string_types = basestring integer_types = (int, ...
import sys try: basestring except: basestring = str # Python3 PY2 = sys.version_info[0] == 2 if not PY2: text_type = str binary_type = bytes string_types = (str,) integer_types = (int,) else: text_type = unicode binary_type = str string_types = basestring integer_types = (int, ...
Fix lru_cache import as memoize
Fix lru_cache import as memoize Thanks to @jcomeauictx for the heads up
Python
mit
scuml/django-crispy-forms,VishvajitP/django-crispy-forms,saydulk/django-crispy-forms,alanwj/django-crispy-forms,schrd/django-crispy-forms,bouttier/django-crispy-forms,smirolo/django-crispy-forms,saydulk/django-crispy-forms,IanLee1521/django-crispy-forms,zixan/django-crispy-forms,Stranger6667/django-crispy-forms,RamezIs...
--- +++ @@ -18,6 +18,8 @@ try: # avoid RemovedInDjango19Warning by using lru_cache where available - from django.utils.lru_cache import lru_cache as memoize + from django.utils.lru_cache import lru_cache + def memoize(function, *args): + return lru_cache()(function) except: from django.u...
3a18c25ef019a9a54475419bfabc4b6e2776df9c
lib/unsubscribe.py
lib/unsubscribe.py
from lxml.html import fromstring as lxml_from_string from unidecode import unidecode UNSUBSCRIBE_MARKERS = [ # English "unsub", "blacklist", "opt-out", "opt out", # French "desinscription", "desinscrire", "desabonner", "desabonnement", "ne souhaitez plus", "ne plus recevoir", "cesser de recevoir" ] def...
from lxml.html import fromstring as lxml_from_string from unidecode import unidecode UNSUBSCRIBE_MARKERS = [ # English "unsub", "blacklist", "opt-out", "opt out", "removealert", "removeme", # French "desinscription", "desinscrire", "desabonner", "desabonnement", "ne souhaitez plus", "ne plus recevoir", "c...
Fix a bug with uppercase links
Fix a bug with uppercase links
Python
mit
sylvinus/reclaim-my-gmail-inbox
--- +++ @@ -5,7 +5,7 @@ UNSUBSCRIBE_MARKERS = [ # English - "unsub", "blacklist", "opt-out", "opt out", + "unsub", "blacklist", "opt-out", "opt out", "removealert", "removeme", # French "desinscription", "desinscrire", "desabonner", "desabonnement", @@ -27,11 +27,10 @@ for element, attribute,...
a9405eaf838842688262689d665f30ae3cebfdea
django_migration_linter/cache.py
django_migration_linter/cache.py
import os import pickle class Cache(dict): def __init__(self, django_folder, database, cache_path): self.filename = os.path.join( cache_path, "{}_{}.pickle".format(django_folder.replace(os.sep, "_"), database), ) if not os.path.exists(os.path.dirname(self.filename)...
import os import pickle class Cache(dict): def __init__(self, django_folder, database, cache_path): self.filename = os.path.join( cache_path, "{}_{}.pickle".format(str(django_folder).replace(os.sep, "_"), database), ) if not os.path.exists(os.path.dirname(self.file...
Support `Path` type for `project_root_path`
feat: Support `Path` type for `project_root_path` Django has switched to using pathlib.Path in startproject. This adds support for these in the project root path config option.
Python
apache-2.0
3YOURMIND/django-migration-linter
--- +++ @@ -6,7 +6,7 @@ def __init__(self, django_folder, database, cache_path): self.filename = os.path.join( cache_path, - "{}_{}.pickle".format(django_folder.replace(os.sep, "_"), database), + "{}_{}.pickle".format(str(django_folder).replace(os.sep, "_"), database),...
593e826b24d83997a5be450be1401e16ec17c07c
application.py
application.py
#!/usr/bin/env python from __future__ import print_function import os from flask.ext.script import Manager, Server from flask.ext.migrate import Migrate, MigrateCommand from app import create_app, db application = create_app(os.getenv('DM_ENVIRONMENT') or 'development') manager = Manager(application) manager.add_...
#!/usr/bin/env python from __future__ import print_function import os from dmutils import init_manager from flask.ext.migrate import Migrate, MigrateCommand from app import create_app, db application = create_app(os.getenv('DM_ENVIRONMENT') or 'development') manager = init_manager(application, 5000, ['./json_sche...
Use new dmutils init_manager to set up reload on schema changes
Use new dmutils init_manager to set up reload on schema changes
Python
mit
alphagov/digitalmarketplace-api,alphagov/digitalmarketplace-api,alphagov/digitalmarketplace-api
--- +++ @@ -4,24 +4,18 @@ import os -from flask.ext.script import Manager, Server +from dmutils import init_manager from flask.ext.migrate import Migrate, MigrateCommand from app import create_app, db application = create_app(os.getenv('DM_ENVIRONMENT') or 'development') -manager = Manager(application) ...
39603bde90ebad7e0d70e41403a9a971867dcbac
backend/breach/views.py
backend/breach/views.py
from django.shortcuts import render from django.http import HttpResponse def get_work(request): return HttpResponse('Not implemented') def work_completed(request): return HttpResponse('Not implemented')
from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt def get_work(request): return HttpResponse('Not implemented') @csrf_exempt def work_completed(request): return HttpResponse('Not implemented')
Allow POST request to work_completed view
Allow POST request to work_completed view
Python
mit
esarafianou/rupture,esarafianou/rupture,dimkarakostas/rupture,esarafianou/rupture,dionyziz/rupture,dimriou/rupture,dimriou/rupture,dionyziz/rupture,dimkarakostas/rupture,dionyziz/rupture,dimriou/rupture,esarafianou/rupture,dimkarakostas/rupture,dimriou/rupture,dionyziz/rupture,dimkarakostas/rupture,dimriou/rupture,dion...
--- +++ @@ -1,8 +1,11 @@ -from django.shortcuts import render from django.http import HttpResponse +from django.views.decorators.csrf import csrf_exempt + def get_work(request): return HttpResponse('Not implemented') + +@csrf_exempt def work_completed(request): return HttpResponse('Not implemented')
a633fd37a4d795e7b565254ef10aaa0f2ad77f31
vcontrol/rest/machines/shutdown.py
vcontrol/rest/machines/shutdown.py
from ..helpers import get_allowed import subprocess import web class ShutdownMachineR: """ This endpoint is for shutting down a running machine. """ allow_origin, rest_url = get_allowed.get_allowed() def GET(self, machine): web.header('Access-Control-Allow-Origin', self.allow_origin) ...
from ..helpers import get_allowed import subprocess import web class ShutdownMachineR: """ This endpoint is for shutting down a running machine. """ allow_origin, rest_url = get_allowed.get_allowed() def GET(self, machine): try: web.header('Access-Control-Allow-Origin', self....
Put the web.header function in a try/except block
Put the web.header function in a try/except block
Python
apache-2.0
cglewis/vcontrol,CyberReboot/vcontrol,CyberReboot/vcontrol,cglewis/vcontrol,CyberReboot/vcontrol,cglewis/vcontrol
--- +++ @@ -2,14 +2,19 @@ import subprocess import web + class ShutdownMachineR: """ This endpoint is for shutting down a running machine. """ allow_origin, rest_url = get_allowed.get_allowed() + def GET(self, machine): - web.header('Access-Control-Allow-Origin', self.allow_orig...
633c3a356a0ed88c00fbb1a5c972171de2255890
dinosaurs/transaction/database.py
dinosaurs/transaction/database.py
from peewee import * db = SqliteDatabase('emails.db') class Transaction(Model): cost = FloatField() address = CharField() tempPass = CharField() domain = CharField(index=True) email = CharField(primary_key=True, unique=True) is_complete = BooleanField(default=False, index=True) class Met...
from datetime import datetime from peewee import * from dinosaurs import settings from dinosaurs.transaction.coin import generate_address db = SqliteDatabase(settings.database) class Transaction(Model): cost = FloatField() address = CharField() started = DateField() tempPass = CharField() doma...
Update what a transaction is
Update what a transaction is
Python
mit
chrisseto/dinosaurs.sexy,chrisseto/dinosaurs.sexy
--- +++ @@ -1,11 +1,18 @@ +from datetime import datetime + from peewee import * -db = SqliteDatabase('emails.db') +from dinosaurs import settings +from dinosaurs.transaction.coin import generate_address + + +db = SqliteDatabase(settings.database) class Transaction(Model): cost = FloatField() address...
820ddf412d09f10977b4bec525d478cc55fe443b
math/prime_test.py
math/prime_test.py
''' prime_test(n) returns a True if n is a prime number else it returns False ''' def prime_test(n): if n <= 1: return False if n==2 or n==3: return True if n%2==0 or n%3==0: return False j = 5 while(j*j <= n): if n%(j)==0 or n%(j+2)==0: return False ...
''' prime_test(n) returns a True if n is a prime number else it returns False ''' def prime_test(n): if n <= 1: return False if n==2 or n==3: return True if n%2==0 or n%3==0: return False j = 5 while(j*j <= n): if n%(j)==0 or n%(j+2)==0: return False ...
Change the return type to boolean
Change the return type to boolean
Python
mit
amaozhao/algorithms,keon/algorithms
--- +++ @@ -24,13 +24,16 @@ # check for factors for i in range(2,num): if (num % i) == 0: - print(num,"is not a prime number") - print(i,"times",num//i,"is",num) + #print(num,"is not a prime number") + #print(i,"times",num//i,"is",num) ...