commit
stringlengths
40
40
old_file
stringlengths
4
236
new_file
stringlengths
4
236
old_contents
stringlengths
1
3.26k
new_contents
stringlengths
16
4.43k
subject
stringlengths
16
624
message
stringlengths
17
3.29k
lang
stringclasses
5 values
license
stringclasses
13 values
repos
stringlengths
5
91.5k
1a594aec0b5af4c815c90d9a19abdf941fb5f5e4
cogs/command_log.py
cogs/command_log.py
import logging class CommandLog: """A simple cog to log commands executed.""" def __init__(self): self.log = logging.getLogger('liara.command_log') async def on_command(self, ctx): kwargs = ', '.join(['{}={}'.format(k, repr(v)) for k, v in ctx.kwargs.items()]) args = 'with argumen...
import logging class CommandLog: """A simple cog to log commands executed.""" def __init__(self): self.log = logging.getLogger('liara.command_log') async def on_command(self, ctx): kwargs = ', '.join(['{}={}'.format(k, repr(v)) for k, v in ctx.kwargs.items()]) args = 'with argumen...
Add the shard ID to the command log
Add the shard ID to the command log
Python
mit
Thessia/Liara
cdcc2dd6342b47e1387beca54677ff7114fc48ec
cms/tests/test_externals.py
cms/tests/test_externals.py
from django.test import TestCase from ..externals import External try: from contextlib import GeneratorContextManager except ImportError: from contextlib import _GeneratorContextManager as GeneratorContextManager from types import FunctionType class TestExternals(TestCase): def test_load(self): ...
from django.test import TestCase from ..externals import External try: from contextlib import GeneratorContextManager except ImportError: from contextlib import _GeneratorContextManager as GeneratorContextManager from types import FunctionType class TestExternals(TestCase): def test_load(self): ...
Improve test coverage of externals.
Improve test coverage of externals.
Python
bsd-3-clause
dan-gamble/cms,jamesfoley/cms,dan-gamble/cms,lewiscollard/cms,jamesfoley/cms,dan-gamble/cms,jamesfoley/cms,danielsamuels/cms,danielsamuels/cms,lewiscollard/cms,lewiscollard/cms,danielsamuels/cms,jamesfoley/cms
67eeb5c7638b15a7f01f60260408fd3aefad549a
meinberlin/apps/offlineevents/templatetags/offlineevent_tags.py
meinberlin/apps/offlineevents/templatetags/offlineevent_tags.py
from functools import cmp_to_key from django import template from adhocracy4.modules.models import Module from adhocracy4.phases.models import Phase from meinberlin.apps.offlineevents.models import OfflineEvent register = template.Library() @register.assignment_tag def offlineevents_and_modules_sorted(project): ...
from functools import cmp_to_key from django import template from adhocracy4.modules.models import Module from adhocracy4.phases.models import Phase from meinberlin.apps.offlineevents.models import OfflineEvent register = template.Library() @register.assignment_tag def offlineevents_and_modules_sorted(project): ...
Make comparison of dates more explicit
Make comparison of dates more explicit
Python
agpl-3.0
liqd/a4-meinberlin,liqd/a4-meinberlin,liqd/a4-meinberlin,liqd/a4-meinberlin
dc04ba245522fe5b9376aa30621bffd8c02b600a
huxley/__init__.py
huxley/__init__.py
# Copyright (c) 2013 Facebook # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing,...
# Copyright (c) 2013 Facebook # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing,...
Fix __version__ missing for setuptools
Fix __version__ missing for setuptools
Python
apache-2.0
ijl/gossamer,ijl/gossamer
336d778a49e0e09996ea647b8a1c3c9e414dd313
jenkins/test/validators/common.py
jenkins/test/validators/common.py
''' Provide common utils to validators ''' import subprocess import sys # Run cli command. By default, exit when an error occurs def run_cli_cmd(cmd, exit_on_fail=True): '''Run a command and return its output''' print "Running system command: " + cmd proc = subprocess.Popen(cmd, bufsize=-1, stderr=subproce...
''' Provide common utils to validators ''' import subprocess import sys # Run cli command. By default, exit when an error occurs def run_cli_cmd(cmd, exit_on_fail=True): '''Run a command and return its output''' print "Running system command: " + " ".join(cmd) proc = subprocess.Popen(cmd, bufsize=-1, stder...
Fix logging for system commands in CI
Fix logging for system commands in CI
Python
apache-2.0
tiwillia/openshift-tools,joelsmith/openshift-tools,tiwillia/openshift-tools,openshift/openshift-tools,joelddiaz/openshift-tools,joelddiaz/openshift-tools,twiest/openshift-tools,joelsmith/openshift-tools,blrm/openshift-tools,ivanhorvath/openshift-tools,rhdedgar/openshift-tools,rhdedgar/openshift-tools,drewandersonnz/ope...
111019266e15f59a358c0842815cd7368d89982f
rbm2m/views/public.py
rbm2m/views/public.py
# -*- coding: utf-8 -*- import logging from flask import Blueprint, render_template, request, send_from_directory, current_app from ..webapp import db from ..action import export_manager, genre_manager, exporter bp = Blueprint('public', __name__) logger = logging.getLogger(__name__) @bp.route('/yml') def yml(): ...
# -*- coding: utf-8 -*- import logging from flask import Blueprint, render_template, request, send_from_directory, current_app from ..webapp import db from ..action import export_manager, genre_manager, exporter bp = Blueprint('public', __name__) logger = logging.getLogger(__name__) @bp.route('/yml') def yml(): ...
Use HTTP_X_REAL_IP to determine client ip address
Use HTTP_X_REAL_IP to determine client ip address
Python
apache-2.0
notapresent/rbm2m,notapresent/rbm2m
30c97e8a377b40f42855d38167768f9eb8e374fc
base/views.py
base/views.py
from .utils import SESSION_KEY_CURRENT_OS from .forms import OSForm class CurrentOSMixin(object): allowed_oses = OSForm.OS_CHOICES def get_context_data(self, **kwargs): """Inject current active OS key and the choice form into context. """ # Zip the 2-tuple into a [keys, values] gener...
from .utils import SESSION_KEY_CURRENT_OS from .forms import OSForm class CurrentOSMixin(object): allowed_oses = OSForm.OS_CHOICES def get_context_data(self, **kwargs): """Inject current active OS key and the choice form into context. """ # Zip the 2-tuple into a [keys, values] gener...
Use form variable instead hard-coding
Use form variable instead hard-coding
Python
mit
djangogirlstaipei/djangogirlstaipei,djangogirlstaipei/djangogirlstaipei,djangogirlstaipei/djangogirlstaipei
621432d1bafe54220ad22afc285aae1c71de0875
custom/icds_reports/tasks.py
custom/icds_reports/tasks.py
import os from celery.schedules import crontab from celery.task import periodic_task from django.conf import settings from django.db import connections @periodic_task(run_every=crontab(minute=0, hour=0), acks_late=True) def move_ucr_data_into_aggregation_tables(): if hasattr(settings, "ICDS_UCR_DATABASE_ALIAS"...
import logging import os from celery.schedules import crontab from celery.task import periodic_task from django.conf import settings from django.db import connections celery_task_logger = logging.getLogger('celery.task') @periodic_task(run_every=crontab(minute=0, hour=0), acks_late=True) def move_ucr_data_into_agg...
Add logging to icds reports task
Add logging to icds reports task
Python
bsd-3-clause
dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq
352ab7fa385835bd68b42eb60a5b149bcfb28865
pyblogit/posts.py
pyblogit/posts.py
""" pyblogit.posts ~~~~~~~~~~~~~~ This module contains the data model to represent blog posts and methods to manipulate it. """ class post(object): def __init__(self, post_id, title, url, author, content, images, labels, status): self._post_id = post_id self._title = title sel...
""" pyblogit.posts ~~~~~~~~~~~~~~ This module contains the data model to represent blog posts and methods to manipulate it. """ class post(object): """The post data model""" def __init__(self, post_id, title, url, author, content, images, labels, status): self._post_id = post_id s...
Add docstring to Post class
Add docstring to Post class
Python
mit
jamalmoir/pyblogit
7d0300b8571fc0732818e194644a6a669c69ffeb
src/Spill/runtests.py
src/Spill/runtests.py
import subprocess import unittest import glob def runTestcase(self, input_file, result_file): spillProg = subprocess.Popen(['./spill', input_file],stdout=subprocess.PIPE) idProg = subprocess.Popen(['./id', result_file],stdout=subprocess.PIPE) with open(result_file) as results: self.assertEqual(spil...
import subprocess import unittest import glob def runTestcase(self, input_file, result_file): spillProg = subprocess.Popen(['runghc', '-i../../src', 'Main.hs', input_file],stdout=subprocess.PIPE) idProg = subprocess.Popen(['runghc', '-i../../src', 'Id.hs', result_file],stdout=subprocess.PIPE) with open(res...
Use runghc instead of executables
Use runghc instead of executables
Python
bsd-3-clause
mhuesch/scheme_compiler,mhuesch/scheme_compiler
c47df6cf4533676c33ca3466cb269657df3e228f
intexration/__main__.py
intexration/__main__.py
import argparse import logging.config import os from intexration import settings from intexration.server import Server # Logger logging.config.fileConfig(settings.LOGGING_FILE) def main(): parser = argparse.ArgumentParser() parser.add_argument('-host', help='Change the hostname') parser.add_argument('-po...
import argparse import logging.config from intexration import settings from intexration.server import Server # Logger logging.config.fileConfig(settings.LOGGING_FILE) def main(): parser = argparse.ArgumentParser() parser.add_argument('-host', help='Change the hostname') parser.add_argument('-port', help=...
Set config contained a bug after refactoring
Set config contained a bug after refactoring
Python
apache-2.0
JDevlieghere/InTeXration,JDevlieghere/InTeXration
0d8282f31b74b6546f07fa37e88b59ed12e945c8
scripts/test_import_optional.py
scripts/test_import_optional.py
#!/usr/bin/env python3 import os import subprocess import sys neonc = sys.argv[1] executor = sys.argv[2:] out = subprocess.check_output([neonc, "t/import-optional-missing.neon"], env={"NEONPATH": "t/compile-time-only"}, stderr=subprocess.STDOUT, universal_newlines=True) sys.stdout.write(out) if "not found" in out: ...
#!/usr/bin/env python3 import os import subprocess import sys neonc = sys.argv[1] executor = sys.argv[2:] out = subprocess.check_output([neonc, "-o", "tmp/import-optional-missing.neonx", "t/import-optional-missing.neon"], env={"NEONPATH": "t/compile-time-only"}, stderr=subprocess.STDOUT, universal_newlines=True) sys...
Fix up import optional test to use temporary compiled file
Fix up import optional test to use temporary compiled file
Python
mit
ghewgill/neon-lang,ghewgill/neon-lang,ghewgill/neon-lang,ghewgill/neon-lang,ghewgill/neon-lang,ghewgill/neon-lang,ghewgill/neon-lang,ghewgill/neon-lang,ghewgill/neon-lang,ghewgill/neon-lang
c9587decdb67474959e1957378f6a4987e4c320a
apps/welcome/urls.py
apps/welcome/urls.py
from django.conf.urls.defaults import * # Smrtr # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', url(r'^1$', 'welcome.views.profile', name='welcome-1' ), url(r'^2$', 'network.views.search', {'next': 'home'}, name='welcome-2'...
from django.conf.urls.defaults import * from django.core.urlresolvers import reverse # Smrtr # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', url(r'^1$', 'welcome.views.profile', name='welcome-1' ), url(r'^2$', 'network.view...
Add select modules to the welcome steps. Redirect fixes to skip
Add select modules to the welcome steps. Redirect fixes to skip
Python
bsd-3-clause
mfitzp/smrtr,mfitzp/smrtr
725bfcc3484826083c3e6cdca71b4af41b37a9c9
runtests.py
runtests.py
#!/usr/bin/env python import sys from django.conf import settings from django.core.management import execute_from_command_line if not settings.configured: settings.configure( DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', } }, INST...
#!/usr/bin/env python import sys from django.conf import settings from django.core.management import execute_from_command_line if not settings.configured: settings.configure( DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', } }, INST...
Make sure tests are found in Django 1.6
Make sure tests are found in Django 1.6
Python
apache-2.0
jpotterm/django-fluent-contents,ixc/django-fluent-contents,edoburu/django-fluent-contents,jpotterm/django-fluent-contents,ixc/django-fluent-contents,django-fluent/django-fluent-contents,jpotterm/django-fluent-contents,ixc/django-fluent-contents,django-fluent/django-fluent-contents,django-fluent/django-fluent-contents,e...
8fcf73183f895b6dc1dc7ebff847cbb2465c2b93
main.py
main.py
#!/usr/bin/env python3
#!/usr/bin/env python3 import argparse import discord import asyncio class commands(): async def test(client, message, args): await client.send_message(message.channel, "Tested!") async def testedit(client, message, args): sleep_time = 5 if len(args) > 0: try: sleep_time = int(args[0]) except: pass m...
Add chat command framework and basic test commands.
Add chat command framework and basic test commands.
Python
agpl-3.0
TransportLayer/TransportLayerBot-Discord
c7b57235b669c3fac99bc1380d667fdd71e8ca3c
main.py
main.py
import slackclient import time import os slackClient = slackclient.SlackClient(os.environ["SLACK_TOKEN"]) slackClient.rtm_connect() while True: print(slackClient.rtm_read()) time.sleep(5)
import slackclient import time import os slackClient = slackclient.SlackClient(os.environ["SLACK_TOKEN"]) slackClient.rtm_connect() slackClient.api_call("channels.join", name="#electrical") while True: for message in slackClient.rtm_read(): print(message) if message["type"] == "team_join": ...
Add welcome message pinging using real time api
Add welcome message pinging using real time api
Python
mit
ollien/Slack-Welcome-Bot
39650fe82bea3fc2bc036b8292f6f0b783b2b4d6
ecmd-core/pyapi/init/__init__.py
ecmd-core/pyapi/init/__init__.py
# import the right SWIG module depending on Python version from sys import version_info from sys import path as sys_path from os import path as os_path if version_info[0] >= 3: sys_path.insert(0, os_path.join(os_path.dirname(__file__), "python3")) from .python3 import * else: sys_path.insert(0, os_path.join...
# import the right SWIG module depending on Python version from sys import version_info from sys import path as sys_path from os import path as os_path if version_info[0] >= 3: sys_path.append(os_path.join(os_path.dirname(__file__), "python3")) from .python3 import * else: sys_path.append(os_path.join(os_pa...
Append version specific path to os.path rather than prepend
pyapi: Append version specific path to os.path rather than prepend Other code might depend on os.path[0] being the path of the executed script, and there is no need for our new path to be at the front.
Python
apache-2.0
open-power/eCMD,open-power/eCMD,open-power/eCMD,open-power/eCMD,open-power/eCMD
52abe8ef49f77ce859cba0a9042ea5761fcbcd90
fusionpy/__init__.py
fusionpy/__init__.py
#!/usr/bin/python from __future__ import print_function __all__ = ['Fusion', 'FusionCollection', 'FusionError', 'FusionRequester', 'HttpFusionRequester'] class FusionError(IOError): def __init__(self, response, request_body=None, message=None, url=None): if message is None: message = "" ...
#!/usr/bin/python from __future__ import print_function __all__ = ['Fusion', 'FusionCollection', 'FusionError', 'FusionRequester', 'HttpFusionRequester'] class FusionError(IOError): def __init__(self, response, request_body=None, message=None, url=None): """ :param response: The HTTP response, hav...
Deal with strings in the first param to the FusionError constructor
Deal with strings in the first param to the FusionError constructor
Python
mit
ke4roh/fusionpy
3b66c6d8e2945d783904ba0f220772861e8e20ef
linguine/ops/StanfordCoreNLP.py
linguine/ops/StanfordCoreNLP.py
#!/usr/bin/env python import os """ Performs some core NLP operations as a proof of concept for the library. """ from stanford_corenlp_pywrapper import CoreNLP class StanfordCoreNLP: proc = None """ When the JSON segments return from the CoreNLP library, they separate the data acquired from eac...
#!/usr/bin/env python import os """ Performs some core NLP operations as a proof of concept for the library. """ from stanford_corenlp_pywrapper import CoreNLP class StanfordCoreNLP: proc = None """ When the JSON segments return from the CoreNLP library, they separate the data acquired from eac...
Allow relative paths for corenlp deps
Allow relative paths for corenlp deps
Python
mit
rigatoni/linguine-python,Pastafarians/linguine-python
56df83132b6885f8ef753fee42a39daff72f2f12
celery_app.py
celery_app.py
from flask import g from app import app, app_mongo from celery import Celery celery = Celery(app.import_name, broker=app.config['CELERY_BROKER_URL'], backend=app.config["CELERY_RESULT_BACKEND"]) celery.conf.update(app.config) task_base = celery.Task class ContextTask(task_base): abstract = True def __call_...
from flask import g from app import app, app_mongo from celery import Celery celery = Celery(app.import_name, broker=app.config['CELERY_BROKER_URL'], backend=app.config["CELERY_RESULT_BACKEND"]) celery.conf.update(app.config) task_base = celery.Task class ContextTask(task_base): abstract = True def __call_...
Add json to accepted celery content
Add json to accepted celery content celery.conf.CELERY_ACCEPT_CONTENT accepts only json
Python
mit
tritanium-industries/TITDev,macalik/TITDev,tritanium-industries/TITDev,macalik/TITDev,tritanium-industries/TITDev,macalik/TITDev
c09e01d6d7b98d2f2b0a99fea20988d422c1a1bd
test_collision/test_worlds.py
test_collision/test_worlds.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ test_collision.test_worlds """ from __future__ import unicode_literals, print_function, absolute_import import unittest import bullet class DiscreteDynamicsWorldTestCase(unittest.TestCase): def setUp(self): pass def test_ctor(self): pass ...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ test_collision.test_worlds """ from __future__ import unicode_literals, print_function, absolute_import import unittest import bullet class DiscreteDynamicsWorldTestCase(unittest.TestCase): def setUp(self): self.solver = bullet.btSequentialImpulseConstra...
Add tests for implemented methods
Add tests for implemented methods
Python
mit
Klumhru/boost-python-bullet,Klumhru/boost-python-bullet,Klumhru/boost-python-bullet
d82e1ab6b94df47b9b9693cf09162f1f579e9eee
django_countries/widgets.py
django_countries/widgets.py
from django.conf import settings from django.forms import widgets from django.utils.safestring import mark_safe COUNTRY_CHANGE_HANDLER = """ this.nextSibling.src = this.nextSibling.src.replace(/[a-z_]{2}(\.[a-zA-Z]*)$/, (this.value.toLowerCase() || '__') + '$1'); """ FLAG_IMAGE = """<img style="margin: 6px 4px; posit...
from django.conf import settings from django.forms import widgets from django.utils.safestring import mark_safe COUNTRY_CHANGE_HANDLER = """ this.nextSibling.src = %s.replace('{code}', this.value.toLowerCase() || '__').replace('{code_upper}', this.value.toUpperCase() || '__'); """ FLAG_IMAGE = """<img style="margin: ...
Use the original COUNTRIES_FLAG_URL string for the JS replace.
Use the original COUNTRIES_FLAG_URL string for the JS replace.
Python
mit
velfimov/django-countries,pimlie/django-countries,schinckel/django-countries,fladi/django-countries,SmileyChris/django-countries,jrfernandes/django-countries,rahimnathwani/django-countries
9d961fb5f50882de687278996365233dc0794123
scripts/get_images.py
scripts/get_images.py
#!/usr/bin/env python3 import requests from bs4 import BeautifulSoup from urllib.parse import urlparse import urllib.request import os def save_file(url, filename): if (os.path.exists(filename)): print(filename + ' already exists locally') pass urllib.request.urlretrieve(url, filename) def g...
#!/usr/bin/env python3 import requests from bs4 import BeautifulSoup from urllib.parse import urlparse import urllib.request import os def save_file(url, filename): if (os.path.exists(filename)): print(filename + ' already exists locally') pass urllib.request.urlretrieve(url, filename) def g...
Fix image download path, thanks @cmrn
Fix image download path, thanks @cmrn
Python
mit
makehackvoid/govhack2014,makehackvoid/govhack2014
0b64ca640cff92a4e01d68b91a6f3147cc22ebd4
myuw_mobile/logger/logresp.py
myuw_mobile/logger/logresp.py
from myuw_mobile.dao.gws import Member from myuw_mobile.logger.logback import log_time def log_response_time(logger, message, timer): log_time(logger, message, timer) def log_success_response(logger, timer): log_time(logger, get_identity() + 'fulfilled', timer) def log_data_not_...
from myuw_mobile.dao.gws import Member from myuw_mobile.dao.sws import Schedule from myuw_mobile.logger.logback import log_time def log_response_time(logger, message, timer): log_time(logger, message, timer) def log_success_response(logger, timer): log_time(logger, get_identity() + 'fulfilled',...
Switch to use Schedule for identifying campus.
Switch to use Schedule for identifying campus.
Python
apache-2.0
fanglinfang/myuw,uw-it-aca/myuw,uw-it-aca/myuw,uw-it-aca/myuw,uw-it-aca/myuw,fanglinfang/myuw,fanglinfang/myuw
5178318df905ed1a68d312adb3936e8748789b2b
tests/test_views.py
tests/test_views.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ test_django-watchman ------------ Tests for `django-watchman` views module. """ import json import unittest from mock import patch from watchman import views class TestWatchman(unittest.TestCase): def setUp(self): pass @patch('watchman.views.che...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ test_django-watchman ------------ Tests for `django-watchman` views module. """ import json import unittest from mock import patch from watchman import views class TestWatchman(unittest.TestCase): def setUp(self): pass @patch('watchman.views.che...
Test exception handling in `check_database`
Test exception handling in `check_database`
Python
bsd-3-clause
JBKahn/django-watchman,mwarkentin/django-watchman,mwarkentin/django-watchman,ulope/django-watchman,gerlachry/django-watchman,blag/django-watchman,JBKahn/django-watchman,blag/django-watchman,gerlachry/django-watchman,ulope/django-watchman
3f317fd63bb5b0b762661c112a8d27075b705d92
openpassword/keychain_item.py
openpassword/keychain_item.py
from Crypto.Cipher import AES from base64 import b64decode import json from openpassword.pkcs_utils import strip_byte_padding from openpassword.openssl_utils import derive_openssl_key class KeychainItem: def __init__(self, item): self.encrypted = b64decode(item["encrypted"]) def decrypt(self, decrypt...
from Crypto.Cipher import AES from base64 import b64decode import json from openpassword.pkcs_utils import strip_byte_padding from openpassword.openssl_utils import derive_openssl_key class KeychainItem: def __init__(self, item): self.encrypted = b64decode(item["encrypted"]) def decrypt(self, decrypt...
Make KeychainItem _decode method static
Make KeychainItem _decode method static
Python
mit
openpassword/blimey,openpassword/blimey
182a9498fd2ef5a6cc973ea42fc99b47505ae4f4
app/submitter/convert_payload_0_0_2.py
app/submitter/convert_payload_0_0_2.py
def convert_answers_to_payload_0_0_2(answer_store, schema, routing_path): """ Convert answers into the data format below 'data': [ { 'value': 'Joe Bloggs', 'block_id': 'household-composition', 'answer_id': 'household-full-name', 'group_id': 'multiple-q...
def convert_answers_to_payload_0_0_2(answer_store, schema, routing_path): """ Convert answers into the data format below 'data': [ { 'value': 'Joe Bloggs', 'answer_id': 'household-full-name', 'group_instance': 0, 'answer_instance': 0 }, ...
Remove group_id & block_id from payload docstring
Remove group_id & block_id from payload docstring
Python
mit
ONSdigital/eq-survey-runner,ONSdigital/eq-survey-runner,ONSdigital/eq-survey-runner,ONSdigital/eq-survey-runner
7447de560c064d251ec58ca35814f476005335ae
budgetsupervisor/transactions/forms.py
budgetsupervisor/transactions/forms.py
from django import forms from django.conf import settings from django.utils.dateparse import parse_datetime import os from .saltedge import SaltEdge from .models import Transaction, Category from decimal import Decimal class ImportTransactionsForm(forms.Form): def import_transactions(self): app = SaltEdge...
from django import forms from django.conf import settings from django.utils.dateparse import parse_datetime import os from .saltedge import SaltEdge from .models import Transaction, Category from decimal import Decimal class ImportTransactionsForm(forms.Form): def import_transactions(self): app = SaltEdge...
Reduce number of database queries
Reduce number of database queries
Python
mit
ltowarek/budget-supervisor
d58576bc658f1433351c0cf9ac0225537e17f472
cobe/brain.py
cobe/brain.py
# Copyright (C) 2012 Peter Teichman import itertools import logging from cobe.analysis import ( AccentNormalizer, StemNormalizer, TokenNormalizer, WhitespaceAnalyzer) from cobe.kvstore import SqliteStore from cobe.model import Model from cobe.search import RandomWalkSearcher log = logging.getLogger(__name__) c...
# Copyright (C) 2012 Peter Teichman import itertools import logging from cobe.analysis import ( AccentNormalizer, StemNormalizer, WhitespaceAnalyzer) from cobe.kvstore import SqliteStore from cobe.model import Model from cobe.search import RandomWalkSearcher log = logging.getLogger(__name__) class StandardAnal...
Remove unused import of TokenNormalizer
Remove unused import of TokenNormalizer Fixes the build
Python
mit
wodim/cobe-ng,LeMagnesium/cobe,pteichman/cobe,tiagochiavericosta/cobe,meska/cobe,pteichman/cobe,LeMagnesium/cobe,wodim/cobe-ng,tiagochiavericosta/cobe,DarkMio/cobe,meska/cobe,DarkMio/cobe
49bc3e16e260765b76cb1015aa655cc7f57055d2
benchmarks.py
benchmarks.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Standalone benchmark runner """ import cProfile import pstats import profile import numpy as np print("Running Rust, Python, and C++ benchmarks. 100 points, 50 runs.\n") # calibrate pr = profile.Profile() calibration = np.mean([pr.calibrate(10000) for x in xrange(5)]...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Standalone benchmark runner """ import cProfile import pstats import profile import numpy as np print("Running Rust, Python, and C++ benchmarks. 100 points, 50 runs.\n") # calibrate print("Calibrating system") pr = profile.Profile() calibration = np.mean([pr.calibrat...
Fix up disgraceful benchmark code
Fix up disgraceful benchmark code
Python
mit
urschrei/pypolyline,urschrei/pypolyline,urschrei/pypolyline
d4b962c599a751db46e4dec2ead9828a3529c453
getTwitter.py
getTwitter.py
import urllib2 from BeautifulSoup import * print 'Welcome to the Get Twitter tool. This tool will allow you to download a page from Twitter to be used to extract the data' userResponse = raw_input("Please enter the full URL from the Tweet page") response = urllib2.urlopen(userResponse) html = response.read() soup = ...
import time import urllib2 from BeautifulSoup import * # from bs4 import * print 'Welcome to the Get Twitter tool. This tool will allow you to download a page from Twitter to be used to extract the data.' print "Current date & time {}".format(time.strftime("%c")) userResponse = raw_input("Please enter the full URL f...
Call html page the date and time of get request
Call html page the date and time of get request The html file that is outputted how has the current date and time as its name
Python
artistic-2.0
christaylortf/FinalYearProject
dcddc500ec8ae45c1a33a43e1727cc38c7b7e001
blox/utils.py
blox/utils.py
# -*- coding: utf-8 -*- from __future__ import absolute_import import ast import sys import struct try: import ujson as json except ImportError: import json PY3 = sys.version_info[0] == 3 if PY3: string_types = str, else: string_types = basestring, def flatten_dtype(dtype): dtype = str(dtype)...
# -*- coding: utf-8 -*- from __future__ import absolute_import import ast import sys import struct import functools try: import ujson as json json_dumps = json.dumps except ImportError: import json json_dumps = functools.partial(json.dumps, separators=',:') PY3 = sys.version_info[0] == 3 if PY3: ...
Write compact json when using built-in json.dumps
Write compact json when using built-in json.dumps
Python
mit
aldanor/blox
f41b06ca9a61b75bdb6cef0a0c534755ca80a513
tests/unit/test_pathologic_models.py
tests/unit/test_pathologic_models.py
# -*- coding: utf-8 -*- ####################################################################### # Name: test_pathologic_models # Purpose: Test for grammar models that could lead to infinite loops are # handled properly. # Author: Igor R. Dejanović <igor DOT dejanovic AT gmail DOT com> # Copyright: (c) 2014 Igor R. De...
# -*- coding: utf-8 -*- ####################################################################### # Name: test_pathologic_models # Purpose: Test for grammar models that could lead to infinite loops are # handled properly. # Author: Igor R. Dejanović <igor DOT dejanovic AT gmail DOT com> # Copyright: (c) 2014 Igor R. De...
Fix in test for pathologic grammars.
Fix in test for pathologic grammars.
Python
mit
leiyangyou/Arpeggio,leiyangyou/Arpeggio
1f65142b754478570a3733f4c0abbf3ef24d9c7e
photutils/utils/_optional_deps.py
photutils/utils/_optional_deps.py
# Licensed under a 3-clause BSD style license - see LICENSE.rst """Checks for optional dependencies using lazy import from `PEP 562 <https://www.python.org/dev/peps/pep-0562/>`_. """ import importlib # This list is a duplicate of the dependencies in setup.cfg "all". optional_deps = ['scipy', 'matplotlib', 'scikit-imag...
# Licensed under a 3-clause BSD style license - see LICENSE.rst """Checks for optional dependencies using lazy import from `PEP 562 <https://www.python.org/dev/peps/pep-0562/>`_. """ import importlib # This list is a duplicate of the dependencies in setup.cfg "all". # Note that in some cases the package names are diff...
Fix for package name differences
Fix for package name differences
Python
bsd-3-clause
larrybradley/photutils,astropy/photutils
120520e44d7dfcf3079bfdc9a118d28b5620cb14
polymorphic/formsets/utils.py
polymorphic/formsets/utils.py
""" Internal utils """ def add_media(dest, media): """ Optimized version of django.forms.Media.__add__() that doesn't create new objects. """ dest.add_css(media._css) dest.add_js(media._js)
""" Internal utils """ import django def add_media(dest, media): """ Optimized version of django.forms.Media.__add__() that doesn't create new objects. Only required for Django < 2.0 """ if django.VERSION >= (2, 0): dest += media else: dest.add_css(media._css) dest.add...
Fix `add_media` util for Django 2.0
Fix `add_media` util for Django 2.0 Neither `add_css` nor `add_js` exist in Django 2.0 because the method for adding `Media` classes together has changed. Ref: https://github.com/django/django/commit/c19b56f633e172b3c02094cbe12d28865ee57772
Python
bsd-3-clause
chrisglass/django_polymorphic,chrisglass/django_polymorphic
2ee763ae1e4564a57692cb7161f99daab4ae77b7
cookiecutter/main.py
cookiecutter/main.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ cookiecutter.main ----------------- Main entry point for the `cookiecutter` command. The code in this module is also a good example of how to use Cookiecutter as a library rather than a script. """ import argparse import os from .find import find_template from .gen...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ cookiecutter.main ----------------- Main entry point for the `cookiecutter` command. The code in this module is also a good example of how to use Cookiecutter as a library rather than a script. """ import argparse import os from .cleanup import remove_repo from .fi...
Clean up after cloned repo if needed. (partial checkin)
Clean up after cloned repo if needed. (partial checkin)
Python
bsd-3-clause
atlassian/cookiecutter,dajose/cookiecutter,luzfcb/cookiecutter,foodszhang/cookiecutter,Springerle/cookiecutter,willingc/cookiecutter,utek/cookiecutter,takeflight/cookiecutter,takeflight/cookiecutter,willingc/cookiecutter,stevepiercy/cookiecutter,vincentbernat/cookiecutter,cguardia/cookiecutter,0k/cookiecutter,nhomar/co...
8be5a5bcbd228599ce7a4f226638feb3dc3318a8
python/examples/encode_message.py
python/examples/encode_message.py
#!/usr/bin/env python3 import os import sys # Add the Python root directory (fusion-engine-client/python/) to the import search path to enable FusionEngine imports # if this application is being run directly out of the repository and is not installed as a pip package. root_dir = os.path.normpath(os.path.join(os.path....
#!/usr/bin/env python3 import os import sys # Add the Python root directory (fusion-engine-client/python/) to the import search path to enable FusionEngine imports # if this application is being run directly out of the repository and is not installed as a pip package. root_dir = os.path.normpath(os.path.join(os.path....
Print the message in the encode example.
Print the message in the encode example.
Python
mit
PointOneNav/fusion-engine-client,PointOneNav/fusion-engine-client,PointOneNav/fusion-engine-client
14ebd4a0e570102e97fb65bbb0813d85e763c743
plyer/facades/notification.py
plyer/facades/notification.py
''' Notification =========== The :class:`Notification` provides access to public methods to create notifications. Simple Examples --------------- To send notification:: >>> from plyer import notification >>> title = 'plyer' >>> message = 'This is an example.' >>> notification.notify(title=title, mes...
''' Notification =========== The :class:`Notification` provides access to public methods to create notifications. Simple Examples --------------- To send notification:: >>> from plyer import notification >>> title = 'plyer' >>> message = 'This is an example.' >>> notification.notify(title=title, mes...
Add note about Windows icon format
Add note about Windows icon format
Python
mit
KeyWeeUsr/plyer,kivy/plyer,KeyWeeUsr/plyer,KeyWeeUsr/plyer,kivy/plyer,kivy/plyer
d53b05f648053d46c6b4b7353d9acb96d6c18179
inventory/models.py
inventory/models.py
import uuid from django.db import models from django.contrib.auth.models import User from django.utils.translation import ugettext as _ from symposion.conference.models import Conference from root.models import Base class Tshirt(Base): """ Model to store the different types of tshirt. """ gender = models.C...
import uuid from django.db import models from django.contrib.auth.models import User from django.utils.translation import ugettext as _ from symposion.conference.models import Conference from root.models import Base class Tshirt(Base): """ Model to store the different types of tshirt. """ gender = models.C...
Move size from UserTshirt to Tshirt
inventory: Move size from UserTshirt to Tshirt
Python
mit
PyConPune/pune.pycon.org,PyConPune/pune.pycon.org,PyConPune/pune.pycon.org
3a42b33124d6036dacee85867e484cb25d32a903
IPython/terminal/pt_inputhooks/qt.py
IPython/terminal/pt_inputhooks/qt.py
import sys from IPython.external.qt_for_kernel import QtCore, QtGui def inputhook(context): app = QtCore.QCoreApplication.instance() if not app: return event_loop = QtCore.QEventLoop(app) if sys.platform == 'win32': # The QSocketNotifier method doesn't appear to work on Windows. ...
import sys from IPython.external.qt_for_kernel import QtCore, QtGui # If we create a QApplication, keep a reference to it so that it doesn't get # garbage collected. _appref = None def inputhook(context): global _appref app = QtCore.QCoreApplication.instance() if not app: _appref = app = QtGui.QAp...
Create a QApplication for inputhook if one doesn't already exist
Create a QApplication for inputhook if one doesn't already exist Closes gh-9784
Python
bsd-3-clause
ipython/ipython,ipython/ipython
d95dd9d3acbd56fd91b67cdfcc1fa9d1758770eb
lino_noi/lib/tickets/__init__.py
lino_noi/lib/tickets/__init__.py
# -*- coding: UTF-8 -*- # Copyright 2016 Luc Saffre # License: BSD (see file COPYING for details) """Fixtures specific for the Team variant of Lino Noi. .. autosummary:: :toctree: models """ from lino_xl.lib.tickets import * class Plugin(Plugin): """Adds the :mod:`lino_xl.lib.votes` plugin. """ ...
# -*- coding: UTF-8 -*- # Copyright 2016 Luc Saffre # License: BSD (see file COPYING for details) """Fixtures specific for the Team variant of Lino Noi. .. autosummary:: :toctree: models """ from lino_xl.lib.tickets import * class Plugin(Plugin): """Adds the :mod:`lino_xl.lib.votes` plugin. """ ...
Move asigned menu and dashboard items to noi/tickets
Move asigned menu and dashboard items to noi/tickets
Python
bsd-2-clause
khchine5/noi,lsaffre/noi,lsaffre/noi,khchine5/noi,lsaffre/noi,lino-framework/noi,lino-framework/noi
2848badf17fd77138ee9e0b3999805e7e60d24c0
tests/builtins/test_dict.py
tests/builtins/test_dict.py
from .. utils import TranspileTestCase, BuiltinFunctionTestCase class DictTests(TranspileTestCase): pass class BuiltinDictFunctionTests(BuiltinFunctionTestCase, TranspileTestCase): functions = ["dict"] not_implemented = [ 'test_bytearray', 'test_frozenset', 'test_list', ...
from .. utils import TranspileTestCase, BuiltinFunctionTestCase class DictTests(TranspileTestCase): pass class BuiltinDictFunctionTests(BuiltinFunctionTestCase, TranspileTestCase): functions = ["dict"] not_implemented = [ 'test_bytearray', 'test_list', 'test_str', ]
Fix “Unexpected success” by removing ‘test_frozenset’ from BuiltinDictFunctionTests.not_implementeed
Fix “Unexpected success” by removing ‘test_frozenset’ from BuiltinDictFunctionTests.not_implementeed
Python
bsd-3-clause
cflee/voc,freakboy3742/voc,freakboy3742/voc,cflee/voc
535dbef3caf4130cc8543be4aa54c8ce820a5b56
tests/builtins/test_list.py
tests/builtins/test_list.py
from .. utils import TranspileTestCase, BuiltinFunctionTestCase class ListTests(TranspileTestCase): pass class BuiltinListFunctionTests(BuiltinFunctionTestCase, TranspileTestCase): functions = ["list"] not_implemented = [ 'test_bool', 'test_bytearray', 'test_bytes', 'tes...
from .. utils import TranspileTestCase, BuiltinFunctionTestCase class ListTests(TranspileTestCase): pass class BuiltinListFunctionTests(BuiltinFunctionTestCase, TranspileTestCase): functions = ["list"] not_implemented = [ 'test_bytearray', 'test_bytes', 'test_class', 'te...
Mark some builtin list() tests as passing
Mark some builtin list() tests as passing - This is due to the earlier fixed TypeError message.
Python
bsd-3-clause
cflee/voc,glasnt/voc,pombredanne/voc,gEt-rIgHt-jR/voc,ASP1234/voc,Felix5721/voc,freakboy3742/voc,pombredanne/voc,Felix5721/voc,freakboy3742/voc,gEt-rIgHt-jR/voc,glasnt/voc,cflee/voc,ASP1234/voc
2d25e6e70df357d19d9e873d94ac57d25bd7e6aa
local.py
local.py
import gntp import Growl class GNTPRegister(gntp.GNTPRegister): def send(self): print 'Sending Registration' growl = Growl.GrowlNotifier( applicationName = self.headers['Application-Name'], notifications = self.notifications, defaultNotifications = self.defaultNotifications, ) growl.register() ...
import gntp import Growl class GNTPRegister(gntp.GNTPRegister): def send(self): print 'Sending Local Registration' growl = Growl.GrowlNotifier( applicationName = self.headers['Application-Name'], notifications = self.notifications, defaultNotifications = self.defaultNotifications, ) growl.registe...
Disable icon temporarily and adjust the debug print statements
Disable icon temporarily and adjust the debug print statements
Python
mit
kfdm/gntp-regrowl
381a266830bbc92bdf6cacb9e4a1ff7044c07c19
setup.py
setup.py
from distutils.core import setup setup( name='rest-server', version='0.1.0', url="http://github.io/boundary/rest-server", author='David Gwartney', author_email='david_gwartney@bmc.com', packages=['restserver', ], entry_points={ 'console_scripts': [ 'rest-server = restser...
from distutils.core import setup setup( name='rest-server', version='0.2.2', url="http://github.io/boundary/rest-server", author='David Gwartney', author_email='david_gwartney@bmc.com', packages=['restserver', ], entry_points={ 'console_scripts': [ 'rest-server = restser...
Increment version ; certs to package
Increment version ; certs to package
Python
apache-2.0
boundary/rest-server
ce8f864d3254acc19595e35dcb0b1e75efeb6b34
setup.py
setup.py
import os, sys sys.path.insert(0, os.path.abspath(os.path.dirname(__file__))) from distutils.core import setup import wtforms setup( name='WTForms', version=wtforms.__version__, url='http://wtforms.simplecodes.com/', license='BSD', author='Thomas Johansson, James Crasta', author_email='wtforms...
import os, sys sys.path.insert(0, os.path.abspath(os.path.dirname(__file__))) from distutils.core import setup import wtforms setup( name='WTForms', version=wtforms.__version__, url='http://wtforms.simplecodes.com/', license='BSD', author='Thomas Johansson, James Crasta', author_email='wtforms...
Make sure ext.csrf is installed with WTForms
Make sure ext.csrf is installed with WTForms
Python
bsd-3-clause
Khan/wtforms
fa55a1a93dd53023159c4a21963361d9678e52cf
setup.py
setup.py
from distutils.core import setup setup( name='pyenvsettings', version='1.0.0', author='Hugo Osvaldo Barrera', author_email='hugo@barrera.io', packages=['envsettings'], package_data={'': ['logging.json']}, url='https://github.com/hobarrera/envsettings', license='ISC', description="R...
from distutils.core import setup setup( name='pyenvsettings', version='1.0.0', author='Hugo Osvaldo Barrera', author_email='hugo@barrera.io', packages=['envsettings'], url='https://github.com/hobarrera/envsettings', license='ISC', description="Read settings from environment variables."...
Remove reference to inexistent file.
Remove reference to inexistent file.
Python
isc
hobarrera/envsettings,hobarrera/envsettings
4cf871af11eb08b3b5b8671c4b5042c6f9f2f344
tests/test__pycompat.py
tests/test__pycompat.py
#!/usr/bin/env python # -*- coding: utf-8 -*-
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import import dask_distance._pycompat def test_irange(): r = dask_distance._pycompat.irange(5) assert not isinstance(r, list) assert list(r) == [0, 1, 2, 3, 4]
Add a basic test for irange
Add a basic test for irange Make sure `irange` is there, it doesn't return a list, and it acts like `range` on some test arguments.
Python
bsd-3-clause
jakirkham/dask-distance
6ab01b1e26184bf296cf58939db5299f07cd68f5
malcolm/modules/pmac/parts/__init__.py
malcolm/modules/pmac/parts/__init__.py
from .compoundmotorsinkportspart import CompoundMotorSinkPortsPart, \ APartName, ARbv, AGroup from .cssourceportspart import CSSourcePortsPart, APartName, ARbv, AGroup from .cspart import CSPart, AMri from .pmacchildpart import PmacChildPart, AMri, APartName from .pmacstatuspart import PmacStatusPart from .pmactraj...
from .compoundmotorsinkportspart import CompoundMotorSinkPortsPart, \ APartName, ARbv, AGroup from .cssourceportspart import CSSourcePortsPart, APartName, ARbv, AGroup from .cspart import CSPart, AMri from .pmacchildpart import PmacChildPart, AMri, APartName from .pmacstatuspart import PmacStatusPart from .pmactraj...
Add beamselectorpart to the PMAC module
Add beamselectorpart to the PMAC module
Python
apache-2.0
dls-controls/pymalcolm,dls-controls/pymalcolm,dls-controls/pymalcolm
147197f5640f9c008b73832f6b15316e1966da1c
BlockServer/epics/archiver_wrapper.py
BlockServer/epics/archiver_wrapper.py
#This file is part of the ISIS IBEX application. #Copyright (C) 2012-2016 Science & Technology Facilities Council. #All rights reserved. # #This program is distributed in the hope that it will be useful. #This program and the accompanying materials are made available under the #terms of the Eclipse Public License v1.0 ...
#This file is part of the ISIS IBEX application. #Copyright (C) 2012-2016 Science & Technology Facilities Council. #All rights reserved. # #This program is distributed in the hope that it will be useful. #This program and the accompanying materials are made available under the #terms of the Eclipse Public License v1.0 ...
Read returned page, just to make sure
Read returned page, just to make sure
Python
bsd-3-clause
ISISComputingGroup/EPICS-inst_servers,ISISComputingGroup/EPICS-inst_servers
14fdcdd5193816cc171120ba31112411aa0fd43d
rackattack/physical/coldreclaim.py
rackattack/physical/coldreclaim.py
import time import logging import multiprocessing.pool from rackattack.physical.ipmi import IPMI class ColdReclaim: _CONCURRENCY = 8 _pool = None def __init__(self, hostname, username, password, hardReset): self._hostname = hostname self._username = username self._password = pas...
import time import logging import multiprocessing.pool from rackattack.physical.ipmi import IPMI class ColdReclaim: _CONCURRENCY = 8 _pool = None def __init__(self, hostname, username, password, hardReset): self._hostname = hostname self._username = username self._password = pas...
Stop using soft ipmi resets until figuring out why it does not work in a lot of cases
Stop using soft ipmi resets until figuring out why it does not work in a lot of cases
Python
apache-2.0
eliran-stratoscale/rackattack-physical,eliran-stratoscale/rackattack-physical,Stratoscale/rackattack-physical,Stratoscale/rackattack-physical
44351d1e48159825226478df13c648aaa83018db
reportlab/test/test_tools_pythonpoint.py
reportlab/test/test_tools_pythonpoint.py
"""Tests for the PythonPoint tool. """ import os, sys, string from reportlab.test import unittest from reportlab.test.utils import makeSuiteForClasses, outputfile import reportlab class PythonPointTestCase(unittest.TestCase): "Some very crude tests on PythonPoint." def test0(self): "Test if pythonp...
"""Tests for the PythonPoint tool. """ import os, sys, string from reportlab.test import unittest from reportlab.test.utils import makeSuiteForClasses, outputfile import reportlab class PythonPointTestCase(unittest.TestCase): "Some very crude tests on PythonPoint." def test0(self): "Test if pythonp...
Fix buglet in compact testing
Fix buglet in compact testing
Python
bsd-3-clause
kanarelo/reportlab,kanarelo/reportlab,Distrotech/reportlab,Distrotech/reportlab,kanarelo/reportlab,Distrotech/reportlab,Distrotech/reportlab,Distrotech/reportlab,kanarelo/reportlab,kanarelo/reportlab
77c97ea46280b395d0c2c1c02941f5eb6d88fde6
rest_framework_json_api/mixins.py
rest_framework_json_api/mixins.py
""" Class Mixins. """ class MultipleIDMixin(object): """ Override get_queryset for multiple id support """ def get_queryset(self): """ Override :meth:``get_queryset`` """ ids = dict(self.request.QUERY_PARAMS).get('ids[]') if ids: self.queryset = self....
""" Class Mixins. """ class MultipleIDMixin(object): """ Override get_queryset for multiple id support """ def get_queryset(self): """ Override :meth:``get_queryset`` """ ids = dict(getattr(self.request, 'query_params', self.request.QUERY_PARAMS)).get('ids[]') if...
Fix for deprecation of `request.QUERY_PARAMS` in DRF 3.2`
Fix for deprecation of `request.QUERY_PARAMS` in DRF 3.2`
Python
bsd-2-clause
Instawork/django-rest-framework-json-api,aquavitae/django-rest-framework-json-api,lukaslundgren/django-rest-framework-json-api,django-json-api/django-rest-framework-json-api,leo-naeka/rest_framework_ember,kaldras/django-rest-framework-json-api,schtibe/django-rest-framework-json-api,hnakamur/django-rest-framework-json-a...
cd3c1f1fbacd4d1a113249af0faf298d5afa540f
wikifork-convert.py
wikifork-convert.py
#!/usr/bin/env python3 from geojson import Feature, Point, FeatureCollection, dumps wikitext = open('wiki-fork', 'r') output = open('output.geojson', 'w') geo_output = [] for line in wikitext: split = line.split('"') coord = split[0].strip(' ') coord = coord.split(',') name = split[1].strip() ...
#!/usr/bin/env python3 import urllib.request from geojson import Feature, Point, FeatureCollection, dumps wiki = urllib.request.urlopen("https://wiki.archlinux.org/index.php/ArchMap/List") wiki_source = wiki.read() wikitext_start = wiki_source.find(b'<pre>', wiki_source.find(b'<pre>') + 1) + 5 wikitext_end = wiki_s...
Switch to parsing the wiki - UNTESTED
Switch to parsing the wiki - UNTESTED
Python
unlicense
guyfawcus/ArchMap,maelstrom59/ArchMap,guyfawcus/ArchMap,guyfawcus/ArchMap,maelstrom59/ArchMap
80d671aa79f306bb17eed006bc99eaa6e6a17bd5
molecule/default/tests/test_default.py
molecule/default/tests/test_default.py
import datetime import os import pytest import testinfra.utils.ansible_runner testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner( os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all') @pytest.mark.parametrize("name", [ "lorem", "ipsum", ]) @pytest.mark.parametrize("dir", [ ".vimrc", ...
import os import pytest import testinfra.utils.ansible_runner testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner( os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all') @pytest.mark.parametrize("name", [ "lorem", "ipsum", ]) @pytest.mark.parametrize("file", [ ".vimrc", ]) def test_back...
Simplify backup-file test (and rename)
Simplify backup-file test (and rename)
Python
mit
ctorgalson/ansible-role-janus,ctorgalson/ansible-role-janus
64b3c094187b629e81a743c51a7a7849444b8920
app/PRESUBMIT.py
app/PRESUBMIT.py
#!/usr/bin/python # Copyright (c) 2009 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Makes sure that the app/ code is cpplint clean.""" INCLUDE_CPP_FILES_ONLY = ( r'.*\.cc$', r'.*\.h$' ) EXCLUDE = ( # Autogener...
#!/usr/bin/python # Copyright (c) 2009 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Makes sure that the app/ code is cpplint clean.""" INCLUDE_CPP_FILES_ONLY = ( r'.*\.cc$', r'.*\.h$' ) EXCLUDE = ( # Autogener...
Make all changes to app/ run on all trybot platforms, not just the big three. Anyone who's changing a header here may break the chromeos build.
Make all changes to app/ run on all trybot platforms, not just the big three. Anyone who's changing a header here may break the chromeos build. BUG=none TEST=none Review URL: http://codereview.chromium.org/2838027 git-svn-id: http://src.chromium.org/svn/trunk/src@51000 4ff67af0-8c30-449e-8e8b-ad334ec8d88c Former-co...
Python
bsd-3-clause
meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-u...
affc010ccb741bbaba3b63eb565844a090bab51f
distarray/tests/test_client.py
distarray/tests/test_client.py
import unittest from IPython.parallel import Client from distarray.client import DistArrayContext class TestDistArrayContext(unittest.TestCase): def setUp(self): self.client = Client() self.dv = self.client[:] def test_create_DAC(self): '''Can we create a plain vanilla context?''' ...
import unittest from IPython.parallel import Client from distarray.client import DistArrayContext class TestDistArrayContext(unittest.TestCase): def setUp(self): self.client = Client() self.dv = self.client[:] def test_create_DAC(self): '''Can we create a plain vanilla context?''' ...
Test indexing for block and cyclic dist types.
Test indexing for block and cyclic dist types.
Python
bsd-3-clause
RaoUmer/distarray,enthought/distarray,enthought/distarray,RaoUmer/distarray
dae6cf8ebe2c2eb0f7c004190c9a3d76a65df918
django_enumfield/validators.py
django_enumfield/validators.py
from django.utils.translation import gettext as _ import six from django_enumfield.exceptions import InvalidStatusOperationError def validate_valid_transition(enum, from_value, to_value): """ Validate that to_value is a valid choice and that to_value is a valid transition from from_value. """ validat...
from django.utils.translation import gettext as _ from django.utils import six from django_enumfield.exceptions import InvalidStatusOperationError def validate_valid_transition(enum, from_value, to_value): """ Validate that to_value is a valid choice and that to_value is a valid transition from from_value. ...
Use Django's bundled six version instead of requiring to install another one.
Use Django's bundled six version instead of requiring to install another one.
Python
mit
jessamynsmith/django-enumfield,5monkeys/django-enumfield,lamby/django-enumfield,lamby/django-enumfield,joar/django-enumfield,fcurella/django-enumfield
9b82ab1ad03c758b6f33e1e5ff6a2b73ff68fccc
tests/test_core_lexer.py
tests/test_core_lexer.py
# -*- coding: utf-8 -*- import sshrc.core.lexer as lexer import pytest @pytest.mark.parametrize("input_, output_", ( ("", ""), (" ", ""), (" #", ""), ("# ", ""), (" # dsfsdfsdf sdfsdfsd", ""), (" a", " a"), (" a# sdfsfdf", " a"), (" a # sdfsfsd x xxxxxxx # sdfs...
# -*- coding: utf-8 -*- import sshrc.core.lexer as lexer import pytest @pytest.mark.parametrize("input_, output_", ( ("", ""), (" ", ""), (" #", ""), ("# ", ""), (" # dsfsdfsdf sdfsdfsd", ""), (" a", " a"), (" a# sdfsfdf", " a"), (" a # sdfsfsd x xxxxxxx # sdfs...
Add tests for get/split indent
Add tests for get/split indent
Python
mit
9seconds/sshrc,9seconds/concierge
2fc71f9b83db5d0ff9e73572ceb49011f916bcf5
calebasse/views.py
calebasse/views.py
# -*- coding: utf-8 -*- from django.shortcuts import render, redirect from django.template.defaultfilters import slugify from cbv import HOME_SERVICE_COOKIE, TemplateView from calebasse.ressources.models import Service APPLICATIONS = ( (u'Gestion des dossiers', 'dossiers'), (u'Agenda', 'agenda'), ...
# -*- coding: utf-8 -*- from django.shortcuts import render, redirect from django.template.defaultfilters import slugify from cbv import HOME_SERVICE_COOKIE, TemplateView from calebasse.ressources.models import Service APPLICATIONS = ( (u'Gestion des dossiers', 'dossiers'), (u'Agenda', 'agenda'), ...
Reorder the service buttons display.
Reorder the service buttons display.
Python
agpl-3.0
ZTH1970/alcide,ZTH1970/alcide,ZTH1970/alcide,ZTH1970/alcide,ZTH1970/alcide
4848baf76e4972401530b624816ba48cb08d9398
appconf/utils.py
appconf/utils.py
import sys def import_attribute(import_path, exception_handler=None): from django.utils.importlib import import_module module_name, object_name = import_path.rsplit('.', 1) try: module = import_module(module_name) except: # pragma: no cover if callable(exception_handler): ...
import sys def import_attribute(import_path, exception_handler=None): try: from importlib import import_module except ImportError: from django.utils.importlib import import_module module_name, object_name = import_path.rsplit('.', 1) try: module = import_module(module_name) ...
Use import_module from standard library if exists
Use import_module from standard library if exists Django 1.8+ drops `django.utils.importlib`. I imagine because that is because an older version of Python (either 2.5 and/or 2.6) is being dropped. I haven't checked older versions but `importlib` exists in Python 2.7.
Python
bsd-3-clause
diox/django-appconf,carltongibson/django-appconf,django-compressor/django-appconf,jezdez/django-appconf,jessehon/django-appconf,treyhunner/django-appconf,jezdez-archive/django-appconf
cdaf1c4a9a99a7f089470e8ceaaa226124a42cf0
digdag-cli/src/main/resources/digdag/cli/tasks/__init__.py
digdag-cli/src/main/resources/digdag/cli/tasks/__init__.py
class MyWorkflow(object): def __init__(self): pass def step3(self, session_time = None): print "Step3 of session %s" % session_time
class MyWorkflow(object): def __init__(self): pass def step3(self, session_time = None): print("Step3 of session {0}".format(session_time))
Fix an example of python task
Fix an example of python task The original python print method doesn't work on python3. print(format) method works on python2 and python 3.
Python
apache-2.0
treasure-data/digdag,treasure-data/digdag,treasure-data/digdag,treasure-data/digdag,treasure-data/digdag,KimuraTakaumi/digdag,KimuraTakaumi/digdag,treasure-data/digdag,KimuraTakaumi/digdag,treasure-data/digdag,KimuraTakaumi/digdag,KimuraTakaumi/digdag,KimuraTakaumi/digdag
62ba442ac447dbb4482dd15f70075d224d0e5a0e
scripts/test_conda_build_log.py
scripts/test_conda_build_log.py
import pytest import log_parser import os @pytest.fixture def parsed_log(): logname = os.path.join(os.path.split(os.path.abspath(__file__))[0], 'build.log') gen = list(log_parser.read_log_from_script(logname)) parsed = {built_name: log_parser.parse_conda_build(lines) ...
import pytest import log_parser import os @pytest.fixture def parsed_log(): logname = os.path.join(os.path.split(os.path.abspath(__file__))[0], 'build.log') gen = list(log_parser.read_log_from_script(logname)) parsed = {built_name: log_parser.parse_conda_build(lines) ...
Make sure there is an error field
TST: Make sure there is an error field
Python
bsd-3-clause
NSLS-II/lightsource2-recipes,NSLS-II/auto-build-tagged-recipes,NSLS-II/lightsource2-recipes,NSLS-II/auto-build-tagged-recipes,NSLS-II/lightsource2-recipes,NSLS-II/lightsource2-recipes
cad7093a3175868944acf1d2f62bad523e4f8a41
tests/unit/utils/test_thin.py
tests/unit/utils/test_thin.py
# -*- coding: utf-8 -*- ''' :codeauthor: :email:`Bo Maryniuk <bo@suse.de>` ''' from __future__ import absolute_import, print_function, unicode_literals import datetime from tests.support.unit import TestCase, skipIf from tests.support.mock import ( NO_MOCK, NO_MOCK_REASON, MagicMock, patch) from s...
# -*- coding: utf-8 -*- ''' :codeauthor: :email:`Bo Maryniuk <bo@suse.de>` ''' from __future__ import absolute_import, print_function, unicode_literals import datetime from tests.support.unit import TestCase, skipIf from tests.support.mock import ( NO_MOCK, NO_MOCK_REASON, MagicMock, patch) from s...
Add unit test for missing dependencies on get_ext_tops
Add unit test for missing dependencies on get_ext_tops
Python
apache-2.0
saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt
cb073dc49efffad56d880f63fd709e5a803e7cf6
blog/admin.py
blog/admin.py
from django.contrib import admin # Register your models here. from .models import Post from .models import UserProfile from .models import SocialMedia class ArticleAdmin(admin.ModelAdmin): list_display = ("title", "category", "created", "updated", "status") search_fields = ("title", "category", "content") ...
from django.contrib import admin # Register your models here. from .models import Post from .models import UserProfile from .models import SocialMedia class PostAdmin(admin.ModelAdmin): list_display = ("title", "category", "created", "updated", "status") search_fields = ("title", "category", "content") ...
Rename model Article to Post
Rename model Article to Post
Python
apache-2.0
andreztz/DjangoBlog,andreztz/DjangoBlog,andreztz/DjangoBlog
158eb354c4860456bf12910c5f737b07c0a313a3
.meta_yaml_replacer.py
.meta_yaml_replacer.py
#!/usr/bin/env python # Copyright (c) 2016, Michael Boyle # See LICENSE file for details: <https://github.com/moble/quaternion/blob/master/LICENSE> from __future__ import print_function import fileinput from auto_version import calculate_version version_string = calculate_version() f = fileinput.FileInput('meta.ya...
#!/usr/bin/env python # Copyright (c) 2016, Michael Boyle # See LICENSE file for details: <https://github.com/moble/quaternion/blob/master/LICENSE> from __future__ import print_function import fileinput from auto_version import calculate_version version_string = calculate_version().replace('+dirty', '') f = filein...
Remove "+dirty" from conda versions
Remove "+dirty" from conda versions
Python
mit
moble/quaternion,moble/quaternion
117b202a1c28282a2c27a545c3da29df9e5675ec
ds_unordered_list.py
ds_unordered_list.py
from __future__ import print_function class List(object): """List class.""" def __init__(self): pass def add(self, item): pass def remove(self, item): pass def search(self, item): pass def is_empty(self): pass def length(self): pass ...
from __future__ import print_function class Node(object): """Node class as building block for unordered list.""" def __init__(self, init_data): pass def get_data(self): pass def get_next(self): pass def set_data(self, new_data): pass def set_next(self, new_n...
Add node class for unordered list building block
Add node class for unordered list building block
Python
bsd-2-clause
bowen0701/algorithms_data_structures
65a6f21e992cc51238c6916895e9cf2f2b2bab21
driver_code_test.py
driver_code_test.py
import SimpleCV as scv from SimpleCV import Image import cv2 import time from start_camera import start_camera import threading def take_50_pictures(): camera_thread = threading.Thread(target=start_camera) camera_thread.start() from get_images_from_pi import get_image, valid_image time.sleep(2) count = 0 w...
import SimpleCV as scv from SimpleCV import Image import cv2 import time from start_camera import start_camera import threading def take_50_pictures(): camera_thread = threading.Thread(target=start_camera) camera_thread.start() from get_images_from_pi import get_image, valid_image time.sleep(2) count = 0 w...
Make detect stop sign function for Henry to add into class
Make detect stop sign function for Henry to add into class
Python
mit
jwarshaw/RaspberryDrive
c84c4ce448f367be0d1759ad20fc8dc58de8fc89
requests_aws_sign/requests_aws_sign.py
requests_aws_sign/requests_aws_sign.py
try: from urllib.parse import urlparse except ImportError: from urlparse import urlparse from botocore.auth import SigV4Auth from botocore.awsrequest import AWSRequest import requests class AWSV4Sign(requests.auth.AuthBase): """ AWS V4 Request Signer for Requests. """ def __init__(self, crede...
try: from urllib.parse import urlparse, urlencode, parse_qs except ImportError: from urlparse import urlparse, parse_qs from urllib import urlencode from botocore.auth import SigV4Auth from botocore.awsrequest import AWSRequest import requests class AWSV4Sign(requests.auth.AuthBase): """ AWS V4 Re...
Handle special characters by urlencode, like 'q=id:123'
Handle special characters by urlencode, like 'q=id:123'
Python
isc
jmenga/requests-aws-sign
69a94a60d04991ba5f8c25276455dedc3a0b898c
setup.py
setup.py
from distutils.core import setup setup( name='pypicache', version='0.1', description='PyPI caching and proxying server', author='Michael Twomey', author_email='mick@twomeylee.name', url='http://readthedocs.org/projects/pypicache/', packages=['pypicache'], )
from distutils.core import setup setup( name='pypicache', version='0.1', description='PyPI caching and proxying server', author='Michael Twomey', author_email='mick@twomeylee.name', url='http://readthedocs.org/projects/pypicache/', packages=['pypicache'], package_data={ 'pypicac...
Install assets when installing the package.
Install assets when installing the package.
Python
bsd-2-clause
micktwomey/pypicache
384fd7ba49ad0cfcb173656a5e31475e8c9b49b3
setup.py
setup.py
from distutils.core import setup import nagios setup(name='nagios-api', version=nagios.version, description='Control nagios using an API', author='Mark Smith', author_email='mark@qq.is', license='BSD New (3-clause) License', long_description=open('README.md').read(), url='http...
from distutils.core import setup import nagios setup(name='nagios-api', version=nagios.version, description='Control nagios using an API', author='Mark Smith', author_email='mark@qq.is', license='BSD New (3-clause) License', long_description=open('README.md').read(), url='http...
Use install_requires arg so dependencies are installed
Use install_requires arg so dependencies are installed
Python
bsd-3-clause
zorkian/nagios-api,zorkian/nagios-api
632c13c31e915a36b81fc60e305dd168bb4e679f
setup.py
setup.py
from distutils.core import setup setup( name = "linode-python", version = "1.1", description = "Python bindings for Linode API", author = "TJ Fontaine", author_email = "tjfontaine@gmail.com", url = "https://github.com/tjfontaine/linode-python", packages = ['linode'], )
from distutils.core import setup setup( name = "linode-python", version = "1.1", description = "Python bindings for Linode API", author = "TJ Fontaine", author_email = "tjfontaine@gmail.com", url = "https://github.com/tjfontaine/linode-python", packages = ['linode'], extras_require = { ...
Add an extra_requires for requests
Add an extra_requires for requests This will let folks do: pip install linode-python[requests] ... to install requests alongside linode-python. Fixes #23 comment 2
Python
mit
ryanshawty/linode-python,tjfontaine/linode-python
9cf9a1d70a5d453dfd217c1ba148eccdc630912e
FetchStats/Plugins/Facter.py
FetchStats/Plugins/Facter.py
from FetchStats import Fetcher class Facter(Fetcher): import yaml def __init__(self): self.context = 'facter' self._load_data() def _load_data(self): try: output = self._exec('facter -p --yaml') self.facts = self.yaml.load(output) self._loaded(T...
from FetchStats import Fetcher class Facter(Fetcher): import yaml def __init__(self): self.context = 'facter' self._load_data() def _load_data(self): try: output = self._exec('facter -p --yaml') self.facts = self.yaml.load(output) self._loaded(T...
Watch for missing facter command
Watch for missing facter command
Python
mit
pombredanne/jsonstats,pombredanne/jsonstats,RHInception/jsonstats,RHInception/jsonstats
4b418cee7bcf1f2d47674a94c5070f40771f54f5
BayesClassification.py
BayesClassification.py
#!/usr/bin/python # coding: latin-1 #------------------------------------------------------------------------------# # Artificial Intelligence - Bayes Classification Algorithms # # ============================================================================ # # Organization: HE-Arc Engineering ...
#!/usr/bin/python # coding: latin-1 #------------------------------------------------------------------------------# # Artificial Intelligence - Bayes Classification Algorithms # # ============================================================================ # # Organization: HE-Arc Engineering ...
Add DataFile class to split words of a line and count it
Add DataFile class to split words of a line and count it
Python
apache-2.0
Chavjoh/BayesClassificationPython
9ee6b2e61fccf7ebc6b3e90370f78ffcf948969d
webserver/home/views.py
webserver/home/views.py
from django.views.generic import TemplateView from competition.models import Competition class HomePageView(TemplateView): template_name = "home/home.html" def get_context_data(self, **kwargs): context = super(HomePageView, self).get_context_data(**kwargs) my_competitions = Competition.objec...
from django.views.generic import TemplateView from competition.models import Competition class HomePageView(TemplateView): template_name = "home/home.html" def get_context_data(self, **kwargs): context = super(HomePageView, self).get_context_data(**kwargs) if not self.request.user.is_an...
Check if user is not anonymous on homepage
Check if user is not anonymous on homepage
Python
bsd-3-clause
siggame/webserver,siggame/webserver,siggame/webserver
db20e918844890979a6af6bfa3b3e74c09914728
utilities/test_find_pairs_pt.py
utilities/test_find_pairs_pt.py
# Test code for find_pairs_pt.py import pytest import find_pairs_pt as fp def test_one_pair(): assert fp.find_pairs_simple([1,9]) == [(1,9)] assert fp.find_pairs([1,9]) == [(1,9)] ''' >>> find_pairs_simple([9]) >>> find_pairs_simple([1,9]) 1,9 >>> find_pairs_simple([9,1]) ...
# Test code for find_pairs_pt.py import pytest import find_pairs_pt as fp def test_no_pairs(): test_array = [9] response = [] assert fp.find_pairs_simple(test_array) == response assert fp.find_pairs(test_array) == response def test_one_pair(): test_array = [1,9] response = [(...
Simplify format for test creation
Simplify format for test creation
Python
mit
daveinnyc/various,daveinnyc/various,daveinnyc/various,daveinnyc/various,daveinnyc/various,daveinnyc/various,daveinnyc/various
53b176674f1d72396b066705e502b5fcbee16a91
vulyk/plugins/dummy/__init__.py
vulyk/plugins/dummy/__init__.py
import json import logging from werkzeug.utils import import_string logger = logging.getLogger(__name__) def get_task(request): return json.dumps({}) def configure(self_settings): """ Getting plugin's default settings, overwriting them with settings from local_settings.py, returns list of setting...
import json import logging from werkzeug.utils import import_string logger = logging.getLogger(__name__) def get_task(request): return json.dumps({}) def configure(self_settings): """ Getting plugin's default settings, overwriting them with settings from local_settings.py, returns dict of setting...
Fix return format of plugin's settings
Fix return format of plugin's settings
Python
bsd-3-clause
mrgambal/vulyk,mrgambal/vulyk,mrgambal/vulyk
7b634eb825e2e102caf862e8753012c35f14ee3f
yerba/__init__.py
yerba/__init__.py
# -*- coding: utf-8 -*- """ yerba: ------ A is a distributed job management framework copyright: (c) 2014 by Evan Briones license: MIT, refer to LICENSE for details """ __version__ = "0.4-dev"
# -*- coding: utf-8 -*- """ yerba: ------ A is a distributed job management framework Copyright (c) 2014 CoGe License: MIT, refer to LICENSE for details """ __version__ = "0.4-dev"
Change copyright holder to "CoGe"
Change copyright holder to "CoGe"
Python
bsd-2-clause
LyonsLab/Yerba,LyonsLab/Yerba
72d89466e40fadeb246b6d69ab0e7035f6bcc8da
gql/transport/requests.py
gql/transport/requests.py
from __future__ import absolute_import import requests from graphql.execution import ExecutionResult from graphql.language.printer import print_ast from .http import HTTPTransport class RequestsHTTPTransport(HTTPTransport): def __init__(self, auth=None, *args, **kwargs): super(RequestsHTTPTransport, sel...
from __future__ import absolute_import import requests from graphql.execution import ExecutionResult from graphql.language.printer import print_ast from .http import HTTPTransport class RequestsHTTPTransport(HTTPTransport): def __init__(self, auth=None, *args, **kwargs): super(RequestsHTTPTransport, sel...
Raise exception if HTTP request failed
Raise exception if HTTP request failed
Python
mit
graphql-python/gql
c72f021248eaf2b969967eb8663e72f888c5fba7
admin/preprints/serializers.py
admin/preprints/serializers.py
from website.project.taxonomies import Subject from admin.nodes.serializers import serialize_node def serialize_preprint(preprint): return { 'id': preprint._id, 'date_created': preprint.date_created, 'modified': preprint.date_modified, 'provider': preprint.provider, 'node'...
from website.project.taxonomies import Subject from admin.nodes.serializers import serialize_node def serialize_preprint(preprint): return { 'id': preprint._id, 'date_created': preprint.date_created, 'modified': preprint.date_modified, 'provider': preprint.provider, 'node'...
Add a bit of subject error handling just in case
Add a bit of subject error handling just in case
Python
apache-2.0
cslzchen/osf.io,Johnetordoff/osf.io,hmoco/osf.io,adlius/osf.io,pattisdr/osf.io,icereval/osf.io,cslzchen/osf.io,chrisseto/osf.io,mfraezz/osf.io,brianjgeiger/osf.io,HalcyonChimera/osf.io,chennan47/osf.io,Johnetordoff/osf.io,cwisecarver/osf.io,Nesiehr/osf.io,caseyrollins/osf.io,crcresearch/osf.io,HalcyonChimera/osf.io,bin...
ae21969815351e84912d1d69be77e20450619acf
pyconll/conllable.py
pyconll/conllable.py
""" Holds the Conllable interface, which is a marker interface to show that a class is a Conll object, such as a treebank, sentence, or token, and therefore has a conll method. """ class Conllable: """ A Conllable mixin to indicate that the component can be converted into a CoNLL representation. """ ...
""" Holds the Conllable interface, which is a marker interface to show that a class is a Conll object, such as a treebank, sentence, or token, and therefore has a conll method. """ import abc class Conllable: """ A Conllable mixin to indicate that the component can be converted into a CoNLL representatio...
Define Conllable with an abstract method.
Define Conllable with an abstract method.
Python
mit
pyconll/pyconll,pyconll/pyconll
173f874c4cf911fc9a35e0e039f164cb625fdccc
imager/ImagerProfile/models.py
imager/ImagerProfile/models.py
from django.db import models from django.contrib.auth.models import User class ImagerProfile(models.Model): user = models.OneToOneField(User) profile_picture = models.ImageField(null=True) picture_privacy = models.BooleanField(default=False) phone_number = models.CharField(max_length=15) # X(XXX) X...
from __future__ import unicode_literals from django.db import models from django.contrib.auth.models import User from django.utils.encoding import python_2_unicode_compatible @python_2_unicode_compatible class ImagerProfile(models.Model): user = models.OneToOneField(User, related_name='profile') profile_pict...
Add string representation of class, is_active method, and first draft of active class method
Add string representation of class, is_active method, and first draft of active class method
Python
mit
nbeck90/django-imager,nbeck90/django-imager
e049017d8abfdee80a0d825af996cb5de2d63657
commands/seen.py
commands/seen.py
#*Flays seen function @command("seen") def seen(nick,user,channel,message): with db as conn: with conn.cursor() as cursor: cursor.execute("SELECT time, nick, message, channel from log where nick = %s order by time desc limit 1;", (message,)) row = cursor.fetchone() if row == None: say(channel, "No rec...
#*Flays seen function @command("seen") def seen(nick,user,channel,message): if db == None: return with db as conn: with conn.cursor() as cursor: cursor.execute("SELECT time, nick, message, channel from log where nick = %s order by time desc limit 1;", (message,)) row = cursor.fetchone() if row == None: ...
Handle case where db is not connected
Handle case where db is not connected
Python
unlicense
ccowmu/botler
58cd5650900a426363c7e0b8fb9bf7d2f881f95b
quickadmin/config.py
quickadmin/config.py
from distutils.version import StrictVersion from django import get_version QADMIN_DEFAULT_EXCLUDES = [ 'django.contrib.sessions', 'django.contrib.admin', 'django.contrib.contenttypes', 'django.contrib.messages', 'django.contrib.comments', 'django.contrib.flatpages', 'django.contrib.sitema...
from distutils.version import StrictVersion from django import get_version QADMIN_DEFAULT_EXCLUDES = [ 'django.contrib.sessions', 'django.contrib.auth', 'django.contrib.admin', 'django.contrib.contenttypes', 'django.contrib.messages', 'django.contrib.comments', 'django.contrib.flatpages',...
Add Django auth as a stock application
Add Django auth as a stock application
Python
mit
zniper/django-quickadmin
88221a3afbf8daa692a344ab7bb7f8d396d547f8
basis_set_exchange/__init__.py
basis_set_exchange/__init__.py
''' Basis Set Exchange Contains utilities for reading, writing, and converting basis set information ''' # Just import the basic user API from .api import (get_basis, lookup_basis_by_role, get_metadata, get_reference_data, get_all_basis_names, get_references, get_basis_family, filter_basis_sets, get...
''' Basis Set Exchange Contains utilities for reading, writing, and converting basis set information ''' # Just import the basic user API from .api import (get_basis, lookup_basis_by_role, get_metadata, get_reference_data, get_all_basis_names, get_references, get_basis_family, filter_basis_sets, get...
Make get_archive_types visible to top-level
Make get_archive_types visible to top-level
Python
bsd-3-clause
MOLSSI-BSE/basis_set_exchange
1ea64f77c3fd3c779c8da43d68c282946a654771
sbt-client.py
sbt-client.py
#!/bin/env python import socket import sys from sys import argv from os import getcwd if len(argv) < 2: print "Usage: client <command>" sys.exit(-1) try: f = file("%s/target/sbt-server-port" % getcwd(), "r") port = int(f.read()) f.close() s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ...
#!/bin/env python import socket import sys from sys import argv from os import getcwd if len(argv) < 2: print "Usage: client <command>" sys.exit(-1) try: f = file("%s/target/sbt-server-port" % getcwd(), "r") port = int(f.read()) f.close() s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ...
Fix client script exit on exception
Fix client script exit on exception
Python
mit
pfn/sbt-simple-server
90860fbe9d5b21b51ade753bdc6dfefc15cb31ac
menpodetect/pico/conversion.py
menpodetect/pico/conversion.py
from menpo.shape import PointDirectedGraph import numpy as np def pointgraph_from_circle(fitting): y, x = fitting.center radius = fitting.diameter / 2.0 return PointDirectedGraph(np.array(((y, x), (y + radius, x), (y + radius,...
from menpo.shape import PointDirectedGraph import numpy as np def pointgraph_from_circle(fitting): diameter = fitting.diameter radius = diameter / 2.0 y, x = fitting.center y -= radius x -= radius return PointDirectedGraph(np.array(((y, x), (y + diameter...
Fix the circle to rectangle code
Fix the circle to rectangle code Was totally incorrect previously
Python
bsd-3-clause
jabooth/menpodetect,jabooth/menpodetect,yuxiang-zhou/menpodetect,yuxiang-zhou/menpodetect
7bb4e910ae8869c1108e306ee418b2c2bce8aa88
flask_app.py
flask_app.py
from flask import Flask from flask_caching import Cache import main app = Flask(__name__) cache = Cache(app, config={'CACHE_TYPE': 'simple'}) @app.route('/') def display_available(): content = ('<html>' + '<head>' + '<title>Restaurant Menu Parser</title>' + '</head>'...
from flask import Flask from flask_caching import Cache import main app = Flask(__name__) cache = Cache(app, config={'CACHE_TYPE': 'simple'}) @app.route('/') def display_available(): content = ('<html>' + '<head>' + '<title>Restaurant Menu Parser</title>' + '</head>...
Add request handler for specific restaurant.
Add request handler for specific restaurant.
Python
bsd-3-clause
talavis/kimenu
4494f4835245990ed5380cbf9800eef5d74986e6
utils.py
utils.py
#!/usr/bin/env python import argparse import sys def parse_basic_args(args=sys.argv[1:]): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument( '--input', '-i', metavar='FILE', default=sys.stdin, type=argparse.FileType('r'), help='the file to process (default: std...
#!/usr/bin/env python import argparse import sys def parse_basic_args(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument( '--input', '-i', metavar='FILE', default=sys.stdin, type=argparse.FileType('r'), help='the file to process (default: stdin)', ) p...
Remove args parameter from parse_basic_args
Remove args parameter from parse_basic_args This is already handled by argparse.
Python
mit
cdown/srt
345a8e338e1c5256bc8e5e78d0595a76d1ceff84
nbtutor/__init__.py
nbtutor/__init__.py
# -*- coding: utf-8 -*- """ nbtutor - a small utility to indicate which cells should be cleared (exercises). """ try: from nbconvert.preprocessors.base import Preprocessor except ImportError: from IPython.nbconvert.preprocessors.base import Preprocessor class ClearExercisePreprocessor(Preprocessor): def...
# -*- coding: utf-8 -*- """ nbtutor - a small utility to indicate which cells should be cleared (exercises). """ import os try: from nbconvert.preprocessors.base import Preprocessor except ImportError: from IPython.nbconvert.preprocessors.base import Preprocessor class ClearExercisePreprocessor(Preprocessor...
Fix the output file name for solution
Fix the output file name for solution
Python
bsd-2-clause
jorisvandenbossche/nbtutor,jorisvandenbossche/nbtutor
493aef6b9965bd4fd83fac8a4cdd790b2d8010e2
chainercv/links/connection/seblock.py
chainercv/links/connection/seblock.py
import chainer import chainer.functions as F import chainer.links as L class SEBlock(chainer.Chain): """A squeeze-and-excitation block. This block is part of squeeze-and-excitation networks. Channel-wise multiplication weights are inferred from and applied to input feature map. Please refer to `the ...
import chainer import chainer.functions as F import chainer.links as L class SEBlock(chainer.Chain): """A squeeze-and-excitation block. This block is part of squeeze-and-excitation networks. Channel-wise multiplication weights are inferred from and applied to input feature map. Please refer to `the ...
Simplify SEBlock by broadcast of binary op
Simplify SEBlock by broadcast of binary op instead of explicit broadcast_to. The main motivation of this change is to simplify the exported ONNX, but this would also improve performance.
Python
mit
chainer/chainercv,pfnet/chainercv,chainer/chainercv
16f7e964341b2a0861011b33d3e4aedd937cead5
usr/examples/14-WiFi-Shield/fw_update.py
usr/examples/14-WiFi-Shield/fw_update.py
# WINC Firmware Update Script # # To start have a successful firmware update create a "firmware" folder on the # uSD card and but a bin file in it. The firmware update code will load that # new firmware onto the WINC module. import network # Init wlan module in Download mode. wlan = network.WINC(True) #print("Firmwar...
# WINC Firmware Update Script # # To start have a successful firmware update create a "firmware" folder on the # uSD card and but a bin file in it. The firmware update code will load that # new firmware onto the WINC module. import network # Init wlan module in Download mode. wlan = network.WINC(mode=network.WINC.MOD...
Fix WINC fw update script.
Fix WINC fw update script.
Python
mit
iabdalkader/openmv,kwagyeman/openmv,kwagyeman/openmv,openmv/openmv,kwagyeman/openmv,openmv/openmv,iabdalkader/openmv,openmv/openmv,iabdalkader/openmv,kwagyeman/openmv,iabdalkader/openmv,openmv/openmv
29974fba6810e1be7e8a2ba8322bd8c78a9012d0
numpy/_array_api/_dtypes.py
numpy/_array_api/_dtypes.py
import numpy as np # Note: we use dtype objects instead of dtype classes. The spec does not # require any behavior on dtypes other than equality. int8 = np.dtype('int8') int16 = np.dtype('int16') int32 = np.dtype('int32') int64 = np.dtype('int64') uint8 = np.dtype('uint8') uint16 = np.dtype('uint16') uint32 = np.dtype...
import numpy as np # Note: we use dtype objects instead of dtype classes. The spec does not # require any behavior on dtypes other than equality. int8 = np.dtype('int8') int16 = np.dtype('int16') int32 = np.dtype('int32') int64 = np.dtype('int64') uint8 = np.dtype('uint8') uint16 = np.dtype('uint16') uint32 = np.dtype...
Use tuples for internal type lists in the array API
Use tuples for internal type lists in the array API These are easier for type checkers to handle.
Python
bsd-3-clause
pdebuyl/numpy,rgommers/numpy,jakirkham/numpy,endolith/numpy,charris/numpy,mattip/numpy,mhvk/numpy,pdebuyl/numpy,seberg/numpy,simongibbons/numpy,seberg/numpy,mattip/numpy,jakirkham/numpy,pdebuyl/numpy,mhvk/numpy,simongibbons/numpy,numpy/numpy,jakirkham/numpy,rgommers/numpy,charris/numpy,simongibbons/numpy,anntzer/numpy,...
0599961b1509d7b8e0bec310b40a62f11a55cc8f
src/tagversion/entrypoints.py
src/tagversion/entrypoints.py
""" tagversion Entrypoints """ import logging import sys from tagversion.argparse import ArgumentParser from tagversion.git import GitVersion from tagversion.write import WriteFile def main(): logging.basicConfig(level=logging.WARNING) parser = ArgumentParser() subcommand = parser.add_subparsers(dest='s...
""" tagversion Entrypoints """ import logging import os import sys from tagversion.argparse import ArgumentParser from tagversion.git import GitVersion from tagversion.write import WriteFile LOG_LEVEL = os.environ.get('LOG_LEVEL', 'warning') def main(): logging.basicConfig(level=getattr(logging, LOG_LEVEL.upper...
Allow log level to be changed via environment variable
Allow log level to be changed via environment variable
Python
bsd-2-clause
rca/tag-version,rca/tag-version
eee5018475e01286be3ee5b396e213762923484e
announcements/forms.py
announcements/forms.py
from django import forms from django.contrib.auth.models import User from django.utils.translation import ugettext_lazy as _ try: from notification import models as notification except ImportError: notification = None from announcements.models import Announcement class AnnouncementAdminForm(forms.ModelForm)...
from django import forms from django.contrib.auth.models import User from django.utils.translation import ugettext_lazy as _ try: from notification import models as notification except ImportError: notification = None from announcements.models import Announcement class AnnouncementAdminForm(forms.ModelForm)...
Use the new interface to notification.send to explicitly override the default behavior and queue notifications for announcements.
Use the new interface to notification.send to explicitly override the default behavior and queue notifications for announcements. git-svn-id: 0d26805d86c51913b6a91884701d7ea9499c7fc0@37 4e50ab13-fc4d-0410-b010-e1608ea6a288
Python
mit
pinax/django-announcements,pinax/pinax-announcements,arthur-wsw/pinax-announcements,edx/django-announcements,percipient/django-announcements,ntucker/django-announcements,brosner/django-announcements,datafyit/django-announcements,datafyit/django-announcements,GeoNode/geonode-announcements,rizumu/django-announcements,sta...
edf67fb99af11fbf9b62b1a67dd9992a247fe326
setup_directory.py
setup_directory.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import division, print_function, absolute_import import argparse import os import subprocess as sp from contextlib import contextmanager import tempfile try: import urllib.request as urllib2 except ImportError: import urllib2 MINICONDA_URL = 'https...
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import division, print_function, absolute_import import argparse import os import subprocess as sp from contextlib import contextmanager import tempfile try: import urllib.request as urllib2 except ImportError: import urllib2 MINICONDA_URL = 'https...
Add change directory context manager
Add change directory context manager
Python
mit
NGTS/pipeline-output-analysis-setup-script
ff85fc05e179e451dabb1f20781dfc5a90314d71
scripts/adb-wrapper.py
scripts/adb-wrapper.py
import subprocess import sys import re # Note: no output will be printed until the entire test suite has finished result = subprocess.run(sys.argv[1], shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) successRegex = re.compile('OK \(\d+ tests\)') print(result.stderr) print(result.s...
import subprocess import sys import re # Note: no output will be printed until the entire test suite has finished p = subprocess.Popen(sys.argv[1], shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) stdoutResult, stderrResult = p.communicate() successRegex = re.compile('OK \(\d+ test...
Refactor the python wrapper script because apparently apt-get doesn't install 3.5, and subprocess.run() is only in 3.5
Refactor the python wrapper script because apparently apt-get doesn't install 3.5, and subprocess.run() is only in 3.5
Python
apache-2.0
sbosley/squidb,yahoo/squidb,yahoo/squidb,sbosley/squidb,sbosley/squidb,sbosley/squidb,sbosley/squidb,yahoo/squidb,yahoo/squidb,yahoo/squidb
7d79c6072482d7a2de515d7ca567225100e7b6e9
tests/test_stock.py
tests/test_stock.py
import unittest from datetime import datetime from stock import Stock class StockTest(unittest.TestCase): def test_new_stock_price(self): """A new stock should have a price that is None. """ stock = Stock("GOOG") self.assertIsNone(stock.price) def test_stock_update(self): ...
import unittest from datetime import datetime from stock import Stock class StockTest(unittest.TestCase): def test_new_stock_price(self): """A new stock should have a price that is None. """ stock = Stock("GOOG") self.assertIsNone(stock.price) def test_stock_update(self): ...
Update negative price exception test to use assertRaises.
Update negative price exception test to use assertRaises.
Python
mit
bsmukasa/stock_alerter
1e31f9bda61c6421a3788f28d75ba45c4838b1bd
bin/isbn_format.py
bin/isbn_format.py
#!/usr/bin/env python import sys import os import yaml import isbnlib metafile = sys.argv[1] metadata = open(metafile, 'r').read() yamldata = yaml.load(metadata) identifier = {} for id in yamldata["identifier"]: if "key" in id: isbnlike = isbnlib.get_isbnlike(id["text"])[0] if isbnlib.is_isbn13(...
#!/usr/bin/env python import sys import os import yaml import isbnlib metafile = sys.argv[1] metadata = open(metafile, 'r').read() yamldata = yaml.load(metadata) identifier = {} if "identifier" in yamldata: for id in yamldata["identifier"]: if "key" in id: isbnlike = isbnlib.get_isbnlike(id[...
Handle case of no identifiers at all in meta data
Handle case of no identifiers at all in meta data
Python
agpl-3.0
alerque/casile,alerque/casile,alerque/casile,alerque/casile,alerque/casile
e880522e226b593be2985cdc85cb0ebd87e53a98
astral/models/tests/factories.py
astral/models/tests/factories.py
import factory import faker import random import uuid from astral.models.stream import Stream from astral.models.node import Node from astral.models.ticket import Ticket ELIXIR_CREATION = lambda class_to_create, **kwargs: class_to_create(**kwargs) factory.Factory.set_creation_function(ELIXIR_CREATION) class Stream...
import factory import faker import random import uuid from astral.models.stream import Stream from astral.models.node import Node from astral.models.ticket import Ticket ELIXIR_CREATION = lambda class_to_create, **kwargs: class_to_create(**kwargs) factory.Factory.set_creation_function(ELIXIR_CREATION) class Stream...
Make sure streams always have a source.
Make sure streams always have a source.
Python
mit
peplin/astral