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
99fba41b7392b1e5e4216145f1e8913698b60914
mopidy_gmusic/commands.py
mopidy_gmusic/commands.py
import gmusicapi from mopidy import commands from oauth2client.client import OAuth2WebServerFlow class GMusicCommand(commands.Command): def __init__(self): super().__init__() self.add_child("login", LoginCommand()) class LoginCommand(commands.Command): def run(self, args, config): oa...
import gmusicapi from mopidy import commands from oauth2client.client import OAuth2WebServerFlow class GMusicCommand(commands.Command): def __init__(self): super().__init__() self.add_child("login", LoginCommand()) class LoginCommand(commands.Command): def run(self, args, config): oa...
Remove Python 2 compatibility code
py3: Remove Python 2 compatibility code
Python
apache-2.0
hechtus/mopidy-gmusic,mopidy/mopidy-gmusic
8521837cc3f57e11278fc41bfd0e5d106fc140fe
deflect/views.py
deflect/views.py
from __future__ import unicode_literals import base32_crockford import logging from django.db.models import F from django.http import Http404 from django.http import HttpResponsePermanentRedirect from django.shortcuts import get_object_or_404 from django.utils.timezone import now from .models import ShortURL from .m...
from __future__ import unicode_literals import base32_crockford import logging from django.db.models import F from django.http import Http404 from django.http import HttpResponsePermanentRedirect from django.shortcuts import get_object_or_404 from django.utils.timezone import now from .models import ShortURL from .m...
Simplify database query when looking up an alias
Simplify database query when looking up an alias
Python
bsd-3-clause
jbittel/django-deflect
c322e4f2202f3b004a4f41bd4c2786f88292cf37
deconstrst/deconstrst.py
deconstrst/deconstrst.py
# -*- coding: utf-8 -*- import argparse import sys from os import path from builder import DeconstJSONBuilder from sphinx.application import Sphinx from sphinx.builders import BUILTIN_BUILDERS def build(argv): """ Invoke Sphinx with locked arguments to generate JSON content. """ parser = argparse.A...
# -*- coding: utf-8 -*- from __future__ import print_function import argparse import sys import os from builder import DeconstJSONBuilder from sphinx.application import Sphinx from sphinx.builders import BUILTIN_BUILDERS def build(argv): """ Invoke Sphinx with locked arguments to generate JSON content. ...
Validate the presence of CONTENT_STORE.
Validate the presence of CONTENT_STORE.
Python
apache-2.0
ktbartholomew/preparer-sphinx,ktbartholomew/preparer-sphinx,deconst/preparer-sphinx,deconst/preparer-sphinx
88de184c1d9daa79e47873b0bd8912ea67b32ec1
app/__init__.py
app/__init__.py
from flask import Flask import base64 import json from config import config as configs from flask.ext.elasticsearch import FlaskElasticsearch from dmutils import init_app, flask_featureflags feature_flags = flask_featureflags.FeatureFlag() elasticsearch_client = FlaskElasticsearch() def create_app(config_name): ...
from flask import Flask import base64 import json from config import config as configs from flask.ext.elasticsearch import FlaskElasticsearch from dmutils import init_app, flask_featureflags feature_flags = flask_featureflags.FeatureFlag() elasticsearch_client = FlaskElasticsearch() def create_app(config_name): ...
Change the VCAP_SERVICE key for elasticsearch
Change the VCAP_SERVICE key for elasticsearch GOV.UK PaaS have recently changed the name of their elasticsearch service in preparation for migration. This quick fix will work until elasticsearch-compose is withdrawn; a future solution should use a more robust way of determining the elasticsearch URI.
Python
mit
alphagov/digitalmarketplace-search-api,alphagov/digitalmarketplace-search-api
15f1abef288411539b512f6bdb572c4a54aa5447
airflow/migrations/versions/127d2bf2dfa7_add_dag_id_state_index_on_dag_run_table.py
airflow/migrations/versions/127d2bf2dfa7_add_dag_id_state_index_on_dag_run_table.py
# # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the ...
# # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the ...
Correct down_revision dag_id/state index creation
[AIRFLOW-810] Correct down_revision dag_id/state index creation Due to revert the revision were not correct anymore and an unclean build environment would still consider it for alembic migrations.
Python
apache-2.0
lyft/incubator-airflow,artwr/airflow,mrkm4ntr/incubator-airflow,stverhae/incubator-airflow,hamedhsn/incubator-airflow,OpringaoDoTurno/airflow,dgies/incubator-airflow,preete-dixit-ck/incubator-airflow,AllisonWang/incubator-airflow,gilt/incubator-airflow,mtagle/airflow,malmiron/incubator-airflow,sekikn/incubator-airflow,...
c037f405de773a3c9e9a7affedf2ee154a3c1766
django_q/migrations/0003_auto_20150708_1326.py
django_q/migrations/0003_auto_20150708_1326.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('django_q', '0002_auto_20150630_1624'), ] operations = [ migrations.AlterModelOptions( name='failure', ...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('django_q', '0002_auto_20150630_1624'), ] operations = [ migrations.AlterModelOptions( name='failure', ...
Remove and replace task.id field, instead of Alter
Remove and replace task.id field, instead of Alter
Python
mit
Koed00/django-q
423d9b9e294ef20fafbb1cb67a6c54c38112cddb
bot/multithreading/worker.py
bot/multithreading/worker.py
import queue import threading class Worker: def __init__(self, name: str, work_queue: queue.Queue, error_handler: callable): self.name = name self.queue = work_queue # using an event instead of a boolean flag to avoid race conditions between threads self.end = threading.Event() ...
import queue import threading class Worker: def __init__(self, name: str, work_queue: queue.Queue, error_handler: callable): self.name = name self.queue = work_queue # using an event instead of a boolean flag to avoid race conditions between threads self.end = threading.Event() ...
Improve Worker resistance against external code exceptions
Improve Worker resistance against external code exceptions
Python
agpl-3.0
alvarogzp/telegram-bot,alvarogzp/telegram-bot
66e2e3bee9996a0cb55c7b802a638e42bc72ccbe
zazu/plugins/astyle_styler.py
zazu/plugins/astyle_styler.py
# -*- coding: utf-8 -*- """astyle plugin for zazu""" import zazu.styler import zazu.util __author__ = "Nicholas Wiles" __copyright__ = "Copyright 2017" class AstyleStyler(zazu.styler.Styler): """Astyle plugin for code styling""" def style_file(self, file, verbose, dry_run): """Run astyle on a file""...
# -*- coding: utf-8 -*- """astyle plugin for zazu""" import zazu.styler import zazu.util __author__ = "Nicholas Wiles" __copyright__ = "Copyright 2017" class AstyleStyler(zazu.styler.Styler): """Astyle plugin for code styling""" def style_file(self, file, verbose, dry_run): """Run astyle on a file""...
Use formatted flag on astyle to simplify code
Use formatted flag on astyle to simplify code
Python
mit
stopthatcow/zazu,stopthatcow/zazu
887cb1b1a021b6d4a1952fdeb178e602d8cabfdc
clifford/test/__init__.py
clifford/test/__init__.py
from .test_algebra_initialisation import * from .test_clifford import * from .test_io import * from .test_g3c_tools import * from .test_tools import * from .test_g3c_CUDA import * import unittest def run_all_tests(): unittest.main()
import os import pytest def run_all_tests(*args): """ Invoke pytest, forwarding options to pytest.main """ pytest.main([os.path.dirname(__file__)] + list(args))
Fix `clifford.test.run_all_tests` to use pytest
Fix `clifford.test.run_all_tests` to use pytest Closes gh-91. Tests can be run with ```python import clifford.test clifford.test.run_all_tests() ```
Python
bsd-3-clause
arsenovic/clifford,arsenovic/clifford
9633f3ee1a3431cb373a4652afbfc2cd8b3b4c23
test_utils/anki/__init__.py
test_utils/anki/__init__.py
import sys from unittest.mock import MagicMock class MockAnkiModules: """ I'd like to get rid of the situation when this is required, but for now this helps with the situation that anki modules are not available during test runtime. """ modules_list = ['anki', 'anki.hooks', 'anki.exporting', 'anki...
from typing import List from typing import Optional import sys from unittest.mock import MagicMock class MockAnkiModules: """ I'd like to get rid of the situation when this is required, but for now this helps with the situation that anki modules are not available during test runtime. """ module_na...
Allow specifying modules to be mocked
Allow specifying modules to be mocked
Python
mit
Stvad/CrowdAnki,Stvad/CrowdAnki,Stvad/CrowdAnki
deb87fefcc7fa76de3ae29ae58e816e49184d100
openfisca_core/model_api.py
openfisca_core/model_api.py
# -*- coding: utf-8 -*- from datetime import date # noqa analysis:ignore from numpy import maximum as max_, minimum as min_, logical_not as not_, where, select # noqa analysis:ignore from .columns import ( # noqa analysis:ignore AgeCol, BoolCol, DateCol, EnumCol, FixedStrCol, FloatCol, ...
# -*- coding: utf-8 -*- from datetime import date # noqa analysis:ignore from numpy import ( # noqa analysis:ignore logical_not as not_, maximum as max_, minimum as min_, round as round_, select, where, ) from .columns import ( # noqa analysis:ignore AgeCol, BoolCol, DateCol, ...
Add numpy.round to model api
Add numpy.round to model api
Python
agpl-3.0
openfisca/openfisca-core,openfisca/openfisca-core
ccd2afdc687c3d6b7d01bed130e1b0097a4fdc2d
src/damis/run_experiment.py
src/damis/run_experiment.py
import sys from damis.models import Experiment exp_pk = sys.argv[1] exp = Experiment.objects.get(pk=exp_pk) exp.status = 'FINISHED' exp.save()
import sys from damis.models import Experiment, Connection from damis.settings import BUILDOUT_DIR from os.path import splitext from algorithms.preprocess import transpose def transpose_data_callable(X, c, *args, **kwargs): X_absolute = BUILDOUT_DIR + '/var/www' + X Y = '%s_transposed%s' % splitext(X) Y_ab...
Implement experiment workflow execution with transpose method.
Implement experiment workflow execution with transpose method.
Python
agpl-3.0
InScience/DAMIS-old,InScience/DAMIS-old
00cea9f8e51f53f338e19adf0165031d2f9cad77
c2corg_ui/templates/utils/format.py
c2corg_ui/templates/utils/format.py
import bbcode import markdown import html from c2corg_ui.format.wikilinks import C2CWikiLinkExtension _markdown_parser = None _bbcode_parser = None def _get_markdown_parser(): global _markdown_parser if not _markdown_parser: extensions = [ C2CWikiLinkExtension(), ] _mark...
import bbcode import markdown import html from c2corg_ui.format.wikilinks import C2CWikiLinkExtension from markdown.extensions.nl2br import Nl2BrExtension from markdown.extensions.toc import TocExtension _markdown_parser = None _bbcode_parser = None def _get_markdown_parser(): global _markdown_parser if no...
Enable markdown extensions for TOC and linebreaks
Enable markdown extensions for TOC and linebreaks
Python
agpl-3.0
Courgetteandratatouille/v6_ui,Courgetteandratatouille/v6_ui,olaurendeau/v6_ui,c2corg/v6_ui,c2corg/v6_ui,c2corg/v6_ui,Courgetteandratatouille/v6_ui,olaurendeau/v6_ui,olaurendeau/v6_ui,c2corg/v6_ui,Courgetteandratatouille/v6_ui,olaurendeau/v6_ui
53f7acf5fc04ca6f86456fda95504ba41046d860
openedx/features/specializations/templatetags/sso_meta_tag.py
openedx/features/specializations/templatetags/sso_meta_tag.py
from django import template from django.template import Template register = template.Library() @register.simple_tag(takes_context=True) def sso_meta(context): return Template('<meta name="title" content="${ title }">' + ' ' + '<meta name="description" content="${ subtitle }">' + ' ' + ...
from django import template from django.template.loader import get_template register = template.Library() @register.simple_tag(takes_context=True) def sso_meta(context): return get_template('features/specializations/sso_meta_template.html').render(context.flatten())
Add Django Custom Tag SSO
Add Django Custom Tag SSO
Python
agpl-3.0
philanthropy-u/edx-platform,philanthropy-u/edx-platform,philanthropy-u/edx-platform,philanthropy-u/edx-platform
27bf030df4c2f46eef8cdcd9441bd5d21a22e5cc
parkings/api/public/urls.py
parkings/api/public/urls.py
from django.conf.urls import include, url from rest_framework.routers import DefaultRouter from .parking_area import PublicAPIParkingAreaViewSet from .parking_area_statistics import PublicAPIParkingAreaStatisticsViewSet router = DefaultRouter() router.register(r'parking_area', PublicAPIParkingAreaViewSet) router.regi...
from django.conf.urls import include, url from rest_framework.routers import DefaultRouter from .parking_area import PublicAPIParkingAreaViewSet from .parking_area_statistics import PublicAPIParkingAreaStatisticsViewSet router = DefaultRouter() router.register(r'parking_area', PublicAPIParkingAreaViewSet, base_name='...
Fix public API root view links
Fix public API root view links
Python
mit
tuomas777/parkkihubi
1eb3df5ca3c86effa85ba76a8bdf549f3560f3a5
landscapesim/serializers/regions.py
landscapesim/serializers/regions.py
import json from rest_framework import serializers from landscapesim.models import Region class ReportingUnitSerializer(serializers.Serializer): type = serializers.SerializerMethodField() properties = serializers.SerializerMethodField() geometry = serializers.SerializerMethodField() class Meta: ...
import json from rest_framework import serializers from django.core.urlresolvers import reverse from landscapesim.models import Region class ReportingUnitSerializer(serializers.Serializer): type = serializers.SerializerMethodField() properties = serializers.SerializerMethodField() geometry = serializers...
Add reporting unit URL to region serializer.
Add reporting unit URL to region serializer.
Python
bsd-3-clause
consbio/landscapesim,consbio/landscapesim,consbio/landscapesim
521b4fbec142306fad2347a5dd3a56aeec2f9498
events/search_indexes.py
events/search_indexes.py
from haystack import indexes from .models import Event, Place, PublicationStatus from django.utils.html import strip_tags class EventIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) autosuggest = indexes.EdgeNgramField(model_attr='name') start_time ...
from haystack import indexes from .models import Event, Place, PublicationStatus from django.utils.html import strip_tags class EventIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) autosuggest = indexes.EdgeNgramField(model_attr='name') start_time ...
Remove deleted places from place index
Remove deleted places from place index
Python
mit
aapris/linkedevents,aapris/linkedevents,tuomas777/linkedevents,City-of-Helsinki/linkedevents,City-of-Helsinki/linkedevents,tuomas777/linkedevents,City-of-Helsinki/linkedevents,tuomas777/linkedevents,aapris/linkedevents
84f4626a623283c3c4d98d9be0ccd69fe837f772
download_data.py
download_data.py
#!/usr/bin/env python from lbtoolbox.download import download import os import inspect import tarfile def here(f): me = inspect.getsourcefile(here) return os.path.join(os.path.dirname(os.path.abspath(me)), f) def download_extract(url, into): fname = download(url, into) print("Extracting...") w...
#!/usr/bin/env python from lbtoolbox.download import download import os import inspect import tarfile def here(f): me = inspect.getsourcefile(here) return os.path.join(os.path.dirname(os.path.abspath(me)), f) def download_extract(urlbase, name, into): print("Downloading " + name) fname = download(...
Update download URL and add more output to downloader.
Update download URL and add more output to downloader.
Python
mit
lucasb-eyer/BiternionNet
c94c86df52184af6b07dcf58951688cea178b8e6
dmoj/executors/LUA.py
dmoj/executors/LUA.py
from .base_executor import ScriptExecutor class Executor(ScriptExecutor): ext = '.lua' name = 'LUA' command = 'lua' address_grace = 131072 test_program = "io.write(io.read('*all'))" @classmethod def get_version_flags(cls, command): return ['-v']
from .base_executor import ScriptExecutor class Executor(ScriptExecutor): ext = '.lua' name = 'LUA' command = 'lua' command_paths = ['lua', 'lua5.3', 'lua5.2', 'lua5.1'] address_grace = 131072 test_program = "io.write(io.read('*all'))" @classmethod def get_version_flags(cls, command):...
Make lua autoconfig work better.
Make lua autoconfig work better.
Python
agpl-3.0
DMOJ/judge,DMOJ/judge,DMOJ/judge
7cef87a81278c227db0cb07329d1b659dbd175b3
mail_factory/models.py
mail_factory/models.py
# -*- coding: utf-8 -*- import django from django.conf import settings from django.utils.importlib import import_module from django.utils.module_loading import module_has_submodule def autodiscover(): """Auto-discover INSTALLED_APPS mails.py modules.""" for app in settings.INSTALLED_APPS: module = '...
# -*- coding: utf-8 -*- import django from django.conf import settings from django.utils.module_loading import module_has_submodule try: from importlib import import_module except ImportError: # Compatibility for python-2.6 from django.utils.importlib import import_module def autodiscover(): """Auto...
Use standard library instead of django.utils.importlib
Use standard library instead of django.utils.importlib > django.utils.importlib is a compatibility library for when Python 2.6 was > still supported. It has been obsolete since Django 1.7, which dropped support > for Python 2.6, and is removed in 1.9 per the deprecation cycle. > Use Python's import_module function ins...
Python
bsd-3-clause
novafloss/django-mail-factory,novafloss/django-mail-factory
ad276d549eebe9c6fe99a629a76f02fc04b2bd51
tests/test_pubannotation.py
tests/test_pubannotation.py
import kindred def test_pubannotation(): corpus = kindred.pubannotation.load('bionlp-st-gro-2013-development') assert isinstance(corpus,kindred.Corpus) fileCount = len(corpus.documents) entityCount = sum([ len(d.entities) for d in corpus.documents ]) relationCount = sum([ len(d.relations) for d in corpus.docum...
import kindred def test_pubannotation(): corpus = kindred.pubannotation.load('bionlp-st-gro-2013-development') assert isinstance(corpus,kindred.Corpus) fileCount = len(corpus.documents) entityCount = sum([ len(d.entities) for d in corpus.documents ]) relationCount = sum([ len(d.relations) for d in corpus.docum...
Simplify pubannotation test to not check exact numbers
Simplify pubannotation test to not check exact numbers
Python
mit
jakelever/kindred,jakelever/kindred
0f62dc9ba898db96390658107e9ebe9930f8b90a
mmiisort/main.py
mmiisort/main.py
from isort import SortImports import itertools import mothermayi.colors import mothermayi.errors def plugin(): return { 'name' : 'isort', 'pre-commit' : pre_commit, } def do_sort(filename): results = SortImports(filename) return results.in_lines != results.out_lines def ge...
from isort import SortImports import mothermayi.colors import mothermayi.errors def plugin(): return { 'name' : 'isort', 'pre-commit' : pre_commit, } def do_sort(filename): results = SortImports(filename) return results.in_lines != results.out_lines def get_status(had_chan...
Make plugin work in python 3
Make plugin work in python 3 Python 3 doesn't have itertools.izip, just the builtin, zip. This logic allows us to pull out either one depending on python version
Python
mit
EliRibble/mothermayi-isort
014c8ca68b196c78b9044b194b762cdb3dfe6c78
app/hooks/views.py
app/hooks/views.py
from __future__ import absolute_import from __future__ import unicode_literals from app import app, webhooks @webhooks.hook( app.config.get('GITLAB_HOOK','/hooks/gitlab'), handler='gitlab') class Gitlab: def issue(self, data): pass def push(self, data): pass def tag_push(self, da...
from __future__ import absolute_import from __future__ import unicode_literals from app import app, webhooks @webhooks.hook( app.config.get('GITLAB_HOOK','/hooks/gitlab'), handler='gitlab') class Gitlab: def issue(self, data): # if the repository belongs to a group check if a channel with the same...
Add comment description of methods for gitlab hook
Add comment description of methods for gitlab hook
Python
apache-2.0
pipex/gitbot,pipex/gitbot,pipex/gitbot
6ecada90e944ee976197e0ee79baf1d711a20803
cla_public/apps/base/forms.py
cla_public/apps/base/forms.py
# -*- coding: utf-8 -*- "Base forms" from flask_wtf import Form from wtforms import StringField, TextAreaField from cla_public.apps.base.fields import MultiRadioField from cla_public.apps.base.constants import FEEL_ABOUT_SERVICE, \ HELP_FILLING_IN_FORM class FeedbackForm(Form): difficulty = TextAreaField(u'D...
# -*- coding: utf-8 -*- "Base forms" from flask_wtf import Form from wtforms import StringField, TextAreaField from cla_public.apps.base.fields import MultiRadioField from cla_public.apps.base.constants import FEEL_ABOUT_SERVICE, \ HELP_FILLING_IN_FORM from cla_public.apps.checker.honeypot import Honeypot class...
Add honeypot field to feedback form
Add honeypot field to feedback form
Python
mit
ministryofjustice/cla_public,ministryofjustice/cla_public,ministryofjustice/cla_public,ministryofjustice/cla_public
4c76a99e1d72820a367d2195fbd3edc1b0af30fd
organizer/models.py
organizer/models.py
from django.db import models # Model Field Reference # https://docs.djangoproject.com/en/1.8/ref/models/fields/ class Tag(models.Model): name = models.CharField(max_length=31) slug = models.SlugField() class Startup(models.Model): name = models.CharField(max_length=31) slug = models.SlugField() ...
from django.db import models # Model Field Reference # https://docs.djangoproject.com/en/1.8/ref/models/fields/ class Tag(models.Model): name = models.CharField( max_length=31, unique=True) slug = models.SlugField( max_length=31, unique=True, help_text='A label for URL config...
Add options to Tag model fields.
Ch03: Add options to Tag model fields. [skip ci] Field options allow us to easily customize behavior of a field. Global Field Options: https://docs.djangoproject.com/en/1.8/ref/models/fields/#help-text https://docs.djangoproject.com/en/1.8/ref/models/fields/#unique The max_length field option is defined in ...
Python
bsd-2-clause
jambonrose/DjangoUnleashed-1.8,jambonrose/DjangoUnleashed-1.8
e2fbf646b193284fc5d01684193b9c5aeb415efe
generate_html.py
generate_html.py
from jinja2 import Environment, FileSystemLoader import datetime import json env = Environment(loader=FileSystemLoader('templates'), autoescape=True) names_template = env.get_template('names.html') area_template = env.get_template('areas.html') with open("output/templates.js") as templatesjs: templates = templat...
from jinja2 import Environment, FileSystemLoader import datetime import json env = Environment(loader=FileSystemLoader('templates'), autoescape=True) names_template = env.get_template('names.html') area_template = env.get_template('areas.html') with open("output/templates.js") as templatesjs: templates = templat...
Fix due to merge conflicts
Fix due to merge conflicts
Python
agpl-3.0
TalkAboutLocal/local-news-engine,TalkAboutLocal/local-news-engine,TalkAboutLocal/local-news-engine,TalkAboutLocal/local-news-engine
0ed9e159fa606c9dbdb90dfc64fcb357e9f9cedb
plenum/test/test_request.py
plenum/test/test_request.py
from indy_common.types import Request def test_request_all_identifiers_returns_empty_list_for_request_without_signatures(): req = Request() assert req.all_identifiers == []
from plenum.common.request import Request def test_request_all_identifiers_returns_empty_list_for_request_without_signatures(): req = Request() assert req.all_identifiers == []
Fix wrong import in test
Fix wrong import in test Signed-off-by: Sergey Khoroshavin <b770466c7a06c5fe47531d5f0e31684f1131354d@dsr-corporation.com>
Python
apache-2.0
evernym/zeno,evernym/plenum
0241e253c68ca6862a3da26d29a649f65c27ae36
demos/chatroom/experiment.py
demos/chatroom/experiment.py
"""Coordination chatroom game.""" import dallinger as dlgr from dallinger.config import get_config try: unicode = unicode except NameError: # Python 3 unicode = str config = get_config() def extra_settings(): config.register('network', unicode) config.register('n', int) class CoordinationChatroom...
"""Coordination chatroom game.""" import dallinger as dlgr from dallinger.compat import unicode from dallinger.config import get_config config = get_config() def extra_settings(): config.register('network', unicode) config.register('n', int) class CoordinationChatroom(dlgr.experiments.Experiment): """...
Use compat for unicode import
Use compat for unicode import
Python
mit
Dallinger/Dallinger,jcpeterson/Dallinger,jcpeterson/Dallinger,jcpeterson/Dallinger,Dallinger/Dallinger,Dallinger/Dallinger,jcpeterson/Dallinger,Dallinger/Dallinger,Dallinger/Dallinger,jcpeterson/Dallinger
8033b00ebbcb8e294f47ee558e76ee260ec18d2b
orglog-config.py
orglog-config.py
org = "servo" ignore_repos = ["skia", "skia-snapshots", "cairo", "libpng", "libcss", "libhubbub", "libparserutils", "libwapcaplet", "pixman"] count_forks = ["glutin","rust-openssl"] # Path to where we'll dump the bare checkouts. Must end in / clones_dir = "repos/" # Path to the concatenated log log_...
org = "servo" ignore_repos = ["skia", "skia-snapshots", "cairo", "libpng", "libcss", "libhubbub", "libparserutils", "libwapcaplet", "pixman", "libfreetype2"] count_forks = ["glutin","rust-openssl"] # Path to where we'll dump the bare checkouts. Must end in / clones_dir = "repos/" # P...
Remove libfreetype2, which should have been omitted and was breaking the scripts
Remove libfreetype2, which should have been omitted and was breaking the scripts
Python
mit
servo/servo-org-stats,servo/servo-org-stats,servo/servo-org-stats
1dfff48a5ddb910b4abbcf8e477b3dda9d606a49
scripts/maf_split_by_src.py
scripts/maf_split_by_src.py
#!/usr/bin/env python2.3 """ Read a MAF from stdin and break into a set of mafs containing no more than a certain number of columns """ usage = "usage: %prog" import sys, string import bx.align.maf from optparse import OptionParser import psyco_full INF="inf" def __main__(): # Parse command line arguments ...
#!/usr/bin/env python2.3 """ Read a MAF from stdin and break into a set of mafs containing no more than a certain number of columns """ usage = "usage: %prog" import sys, string import bx.align.maf from optparse import OptionParser import psyco_full INF="inf" def __main__(): # Parse command line arguments ...
Allow splitting by a particular component (by index)
Allow splitting by a particular component (by index)
Python
mit
bxlab/bx-python,bxlab/bx-python,bxlab/bx-python
ead9192b4c2acb21df917dfe116785343e9a59a6
scripts/patches/transfer.py
scripts/patches/transfer.py
patches = [ { "op": "move", "from": "/ResourceTypes/AWS::Transfer::Server/Properties/Protocols/ItemType", "path": "/ResourceTypes/AWS::Transfer::Server/Properties/Protocols/PrimitiveItemType", }, { "op": "replace", "path": "/ResourceTypes/AWS::Transfer::Server/Propert...
patches = [ { "op": "move", "from": "/ResourceTypes/AWS::Transfer::Server/Properties/Protocols/ItemType", "path": "/ResourceTypes/AWS::Transfer::Server/Properties/Protocols/PrimitiveItemType", }, { "op": "replace", "path": "/ResourceTypes/AWS::Transfer::Server/Propert...
Fix spec issue with Transfer::Server ProtocolDetails
Fix spec issue with Transfer::Server ProtocolDetails
Python
bsd-2-clause
cloudtools/troposphere,cloudtools/troposphere
4fe19797ba2fb12239ae73da60bb3e726b23ffe9
web/forms.py
web/forms.py
from django.contrib.auth.forms import UserCreationForm, UserChangeForm from .models import UniqueEmailUser class UniqueEmailUserCreationForm(UserCreationForm): """ A form that creates a UniqueEmailUser. """ def __init__(self, *args, **kargs): super(UniqueEmailUserCreationForm, self).__init__...
from django.contrib.auth.forms import UserCreationForm, UserChangeForm from .models import UniqueEmailUser class UniqueEmailUserCreationForm(UserCreationForm): """ A form that creates a UniqueEmailUser. """ class Meta: model = UniqueEmailUser fields = ("email",) class UniqueEmailUs...
Fix bug in admin user editing
Fix bug in admin user editing Fixes KeyError when creating or editing a UniqueEmailUser in the admin interface.
Python
mit
uppercounty/uppercounty,uppercounty/uppercounty,uppercounty/uppercounty
89225ed0c7ec627ee32fd973d5f1fb95da173be2
djangae/contrib/locking/memcache.py
djangae/contrib/locking/memcache.py
import random import time from datetime import datetime from django.core.cache import cache class MemcacheLock(object): def __init__(self, identifier, cache, unique_value): self.identifier = identifier self._cache = cache self.unique_value = unique_value @classmethod def acquire(...
import random import time from datetime import datetime from django.core.cache import cache class MemcacheLock(object): def __init__(self, identifier, unique_value): self.identifier = identifier self.unique_value = unique_value @classmethod def acquire(cls, identifier, wait=True, steal_a...
Remove pointless `_cache` attribute on MemcacheLock class.
Remove pointless `_cache` attribute on MemcacheLock class. If this was doing anything useful, I have no idea what it was.
Python
bsd-3-clause
potatolondon/djangae,potatolondon/djangae
a715821c75521e25172805c98d204fc4e24a4641
CodeFights/circleOfNumbers.py
CodeFights/circleOfNumbers.py
#!/usr/local/bin/python # Code Fights Circle of Numbers Problem def circleOfNumbers(n, firstNumber): pass def main(): tests = [ ["crazy", "dsbaz"], ["z", "a"] ] for t in tests: res = circleOfNumbers(t[0], t[1]) if t[2] == res: print("PASSED: circleOfNumbe...
#!/usr/local/bin/python # Code Fights Circle of Numbers Problem def circleOfNumbers(n, firstNumber): mid = n / 2 return (mid + firstNumber if firstNumber < mid else firstNumber - mid) def main(): tests = [ [10, 2, 7], [10, 7, 2], [4, 1, 3], [6, 3, 0] ] for t in t...
Solve Code Fights circle of numbers problem
Solve Code Fights circle of numbers problem
Python
mit
HKuz/Test_Code
9ac662557d6313190621c0c84a2c6923e0e9fa72
nodeconductor/logging/middleware.py
nodeconductor/logging/middleware.py
from __future__ import unicode_literals import threading _locals = threading.local() def get_event_context(): return getattr(_locals, 'context', None) def set_event_context(context): _locals.context = context def reset_event_context(): if hasattr(_locals, 'context'): del _locals.context de...
from __future__ import unicode_literals import threading _locals = threading.local() def get_event_context(): return getattr(_locals, 'context', None) def set_event_context(context): _locals.context = context def reset_event_context(): if hasattr(_locals, 'context'): del _locals.context de...
Update event context instead of replace (NC-529)
Update event context instead of replace (NC-529)
Python
mit
opennode/nodeconductor,opennode/nodeconductor,opennode/nodeconductor
93a95afe231910d9f683909994692fadaf107057
readme_renderer/markdown.py
readme_renderer/markdown.py
# Copyright 2014 Donald Stufft # # 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, so...
# Copyright 2014 Donald Stufft # # 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, so...
Make md.render have the same API as rst.render
Make md.render have the same API as rst.render
Python
apache-2.0
pypa/readme,pypa/readme_renderer
2279aa0c450d53b04f774d9441e4fc0647466581
bottery/message.py
bottery/message.py
import os from datetime import datetime import attr from jinja2 import Environment, FileSystemLoader, select_autoescape @attr.s class Message: id = attr.ib() platform = attr.ib() user = attr.ib() text = attr.ib() timestamp = attr.ib() raw = attr.ib() @property def datetime(self): ...
import os from datetime import datetime import attr from jinja2 import Environment, FileSystemLoader, select_autoescape @attr.s class Message: id = attr.ib() platform = attr.ib() user = attr.ib() text = attr.ib() timestamp = attr.ib() raw = attr.ib() @property def datetime(self): ...
Send platform name to defaul template context
Send platform name to defaul template context
Python
mit
rougeth/bottery
22b697729d1ee43d322aa1187b3a5f6101f836a5
odin/__init__.py
odin/__init__.py
__authors__ = "Tim Savage" __author_email__ = "tim@savage.company" __copyright__ = "Copyright (C) 2014 Tim Savage" __version__ = "1.0" # Disable logging if an explicit handler is not added try: import logging logging.getLogger('odin').addHandler(logging.NullHandler()) except AttributeError: pass # Fallbac...
# Disable logging if an explicit handler is not added import logging logging.getLogger('odin.registration').addHandler(logging.NullHandler()) __authors__ = "Tim Savage" __author_email__ = "tim@savage.company" __copyright__ = "Copyright (C) 2014 Tim Savage" __version__ = "1.0" from odin.fields import * # noqa from od...
Remove Python 2.6 backwards compatibility
Remove Python 2.6 backwards compatibility
Python
bsd-3-clause
python-odin/odin
59daf205869c42b3797aa9dbaaa97930cbca2417
nanshe_workflow/ipy.py
nanshe_workflow/ipy.py
__author__ = "John Kirkham <kirkhamj@janelia.hhmi.org>" __date__ = "$Nov 10, 2015 17:09$" try: from IPython.utils.shimmodule import ShimWarning except ImportError: class ShimWarning(Warning): """Warning issued by IPython 4.x regarding deprecated API.""" pass import warnings with warnings.cat...
__author__ = "John Kirkham <kirkhamj@janelia.hhmi.org>" __date__ = "$Nov 10, 2015 17:09$" import json import re try: from IPython.utils.shimmodule import ShimWarning except ImportError: class ShimWarning(Warning): """Warning issued by IPython 4.x regarding deprecated API.""" pass import warn...
Add function to check if nbserverproxy is running
Add function to check if nbserverproxy is running Provides a simple check to see if the `nbserverproxy` is installed and running. As this is a Jupyter server extension and this code is run from the notebook, we can't simply import `nbserverproxy`. In fact that wouldn't even work when using the Python 2 kernel even tho...
Python
apache-2.0
nanshe-org/nanshe_workflow,DudLab/nanshe_workflow
99d16198b5b61ba13a441a6546ccd1f7ce0b91bc
test/symbols/show_glyphs.py
test/symbols/show_glyphs.py
#!/usr/bin/env python # -*- coding: utf-8 -*- devicons_start = "e700" devicons_end = "e7c5" print "Devicons" for ii in xrange(int(devicons_start, 16), int(devicons_end, 16) + 1): print unichr(ii), custom_start = "e5fa" custom_end = "e62b" print "\nCustom" for ii in xrange(int(custom_start, 16), int(custom_end, ...
#!/usr/bin/env python # -*- coding: utf-8 -*- devicons_start = "e700" devicons_end = "e7c5" print "Devicons" for ii in xrange(int(devicons_start, 16), int(devicons_end, 16) + 1): print unichr(ii), custom_start = "e5fa" custom_end = "e62b" print "\nCustom" for ii in xrange(int(custom_start, 16), int(custom_end, ...
Add octicons in font test script
Add octicons in font test script
Python
mit
mkofinas/prompt-support,mkofinas/prompt-support
c35e004ae3b2b9b8338673078f8ee523ac79e005
alg_shell_sort.py
alg_shell_sort.py
from __future__ import absolute_import from __future__ import print_function from __future__ import division def _gap_insertion_sort(a_list, start, gap): for i in range(start + gap, len(a_list), gap): current_value = a_list[i] position = i while (position >= gap) and (a_list[position - ga...
from __future__ import absolute_import from __future__ import print_function from __future__ import division def _gap_insertion_sort(a_list, start, gap): for i in range(start + gap, len(a_list), gap): current_value = a_list[i] position = i while (position >= gap) and (a_list[position - ga...
Revise print() in shell_sort() & main()
Revise print() in shell_sort() & main()
Python
bsd-2-clause
bowen0701/algorithms_data_structures
29061254e99f8e02e8285c3ebc965866c8c9d378
testing/chess_engine_fight.py
testing/chess_engine_fight.py
#!/usr/bin/python import subprocess, os, sys if len(sys.argv) < 2: print('Must specify file names of 2 chess engines') for i in range(len(sys.argv)): print(str(i) + ': ' + sys.argv[i]) sys.exit(1) generator = './' + sys.argv[-2] checker = './' + sys.argv[-1] game_file = 'game.pgn' count = 0 whil...
#!/usr/bin/python import subprocess, os, sys if len(sys.argv) < 2: print('Must specify file names of 2 chess engines') for i in range(len(sys.argv)): print(str(i) + ': ' + sys.argv[i]) sys.exit(1) generator = './' + sys.argv[-2] checker = './' + sys.argv[-1] game_file = 'game.pgn' count = 0 whil...
Check that engine fight files are deleted before test
Check that engine fight files are deleted before test
Python
mit
MarkZH/Genetic_Chess,MarkZH/Genetic_Chess,MarkZH/Genetic_Chess,MarkZH/Genetic_Chess,MarkZH/Genetic_Chess
8c637c0f70908a00713014ef2d2ff72e3d5a81dc
prerequisites.py
prerequisites.py
#!/usr/bin/env python import sys # Check that we are in an activated virtual environment try: import os virtual_env = os.environ['VIRTUAL_ENV'] except KeyError: print("It doesn't look like you are in an activated virtual environment.") print("Did you make one?") print("Did you activate it?") ...
#!/usr/bin/env python import sys # Check that we are in an activated virtual environment try: import os virtual_env = os.environ['VIRTUAL_ENV'] except KeyError: print("It doesn't look like you are in an activated virtual environment.") print("Did you make one?") print("Did you activate it?") ...
Use django.get_version in prerequisite checker
Use django.get_version in prerequisite checker
Python
mit
mpirnat/django-tutorial-v2
2a724872cba5c48ddbd336f06460aa2ad851c6d0
Pilot3/P3B5/p3b5.py
Pilot3/P3B5/p3b5.py
import os import candle file_path = os.path.dirname(os.path.realpath(__file__)) lib_path2 = os.path.abspath(os.path.join(file_path, '..', '..', 'common')) sys.path.append(lib_path2) REQUIRED = [ 'learning_rate', 'learning_rate_min', 'momentum', 'weight_decay', 'grad_clip', 'seed', 'unro...
import os import sys import candle file_path = os.path.dirname(os.path.realpath(__file__)) lib_path2 = os.path.abspath(os.path.join(file_path, '..', '..', 'common')) sys.path.append(lib_path2) REQUIRED = [ 'learning_rate', 'learning_rate_min', 'momentum', 'weight_decay', 'grad_clip', 'seed'...
Fix missing import for sys
Fix missing import for sys
Python
mit
ECP-CANDLE/Benchmarks,ECP-CANDLE/Benchmarks,ECP-CANDLE/Benchmarks
7729c90679a74f268d7b0fd88c954fb583830794
parser.py
parser.py
import webquery from lxml import etree import inspect from expression import Expression from collections import defaultdict class Parser(object): registry = defaultdict(dict) @classmethod def __init_subclass__(cls): for name, member in inspect.getmembers(cls): if isinstance(member, Ex...
import webquery from lxml import etree import inspect from expression import Expression from collections import defaultdict class Parser(object): registry = defaultdict(dict) @classmethod def __init_subclass__(cls): for name, member in inspect.getmembers(cls): if isinstance(member, Ex...
Add ability to customize URL
Add ability to customize URL
Python
apache-2.0
shiplu/webxpath
b6813731696a03e04367ea3286092320391080e9
puresnmp/__init__.py
puresnmp/__init__.py
""" This module contains the high-level functions to access the library. Care is taken to make this as pythonic as possible and hide as many of the gory implementations as possible. """ from x690.types import ObjectIdentifier # !!! DO NOT REMOVE !!! The following import triggers the processing of SNMP # Types and th...
""" This module contains the high-level functions to access the library. Care is taken to make this as pythonic as possible and hide as many of the gory implementations as possible. """ from x690.types import ObjectIdentifier # !!! DO NOT REMOVE !!! The following import triggers the processing of SNMP # Types and th...
Fix false-positive of a type-check
Fix false-positive of a type-check
Python
mit
exhuma/puresnmp,exhuma/puresnmp
bf5dd490cec02827d51c887506ce1f55d5012893
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__ # 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...
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...
Update URL for baseline images
Update URL for baseline images
Python
bsd-3-clause
mhvk/astropy,StuartLittlefair/astropy,larrybradley/astropy,StuartLittlefair/astropy,pllim/astropy,astropy/astropy,aleksandr-bakanov/astropy,mhvk/astropy,saimn/astropy,dhomeier/astropy,StuartLittlefair/astropy,stargaser/astropy,dhomeier/astropy,stargaser/astropy,mhvk/astropy,StuartLittlefair/astropy,bsipocz/astropy,dhom...
030e64d7aee6c3f0b3a0d0508ac1d5ece0bf4a40
astroquery/fermi/__init__.py
astroquery/fermi/__init__.py
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ Access to Fermi Gamma-ray Space Telescope data. http://fermi.gsfc.nasa.gov http://fermi.gsfc.nasa.gov/ssc/data/ """ from astropy.config import ConfigurationItem FERMI_URL = ConfigurationItem('fermi_url', ['http://fermi.g...
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ Access to Fermi Gamma-ray Space Telescope data. http://fermi.gsfc.nasa.gov http://fermi.gsfc.nasa.gov/ssc/data/ """ from astropy.config import ConfigurationItem FERMI_URL = ConfigurationItem('fermi_url', ['http://fermi.g...
Clean up namespace to get rid of sphinx warnings
Clean up namespace to get rid of sphinx warnings
Python
bsd-3-clause
imbasimba/astroquery,imbasimba/astroquery,ceb8/astroquery,ceb8/astroquery
ef98ba0f2aa660b85a4116d46679bf30321f2a05
scipy/spatial/transform/__init__.py
scipy/spatial/transform/__init__.py
""" Spatial Transformations (:mod:`scipy.spatial.transform`) ======================================================== .. currentmodule:: scipy.spatial.transform This package implements various spatial transformations. For now, only rotations are supported. Rotations in 3 dimensions ------------------------- .. autos...
""" Spatial Transformations (:mod:`scipy.spatial.transform`) ======================================================== .. currentmodule:: scipy.spatial.transform This package implements various spatial transformations. For now, only rotations are supported. Rotations in 3 dimensions ------------------------- .. autos...
Add RotationSpline into __all__ of spatial.transform
MAINT: Add RotationSpline into __all__ of spatial.transform
Python
bsd-3-clause
grlee77/scipy,pizzathief/scipy,endolith/scipy,Eric89GXL/scipy,gertingold/scipy,aeklant/scipy,anntzer/scipy,tylerjereddy/scipy,ilayn/scipy,scipy/scipy,matthew-brett/scipy,jor-/scipy,endolith/scipy,ilayn/scipy,person142/scipy,Eric89GXL/scipy,nmayorov/scipy,lhilt/scipy,arokem/scipy,endolith/scipy,ilayn/scipy,WarrenWeckess...
4c85300c5458053ac08a393b00513c80baf28031
reqon/deprecated/__init__.py
reqon/deprecated/__init__.py
import rethinkdb as r from . import coerce, geo, operators, terms from .coerce import COERSIONS from .operators import BOOLEAN, EXPRESSIONS, MODIFIERS from .terms import TERMS from .exceptions import ReqonError, InvalidTypeError, InvalidFilterError def query(query): try: reql = r.db(query['$db']).table(q...
import rethinkdb as r from . import coerce, geo, operators, terms from .coerce import COERSIONS from .operators import BOOLEAN, EXPRESSIONS, MODIFIERS from .terms import TERMS from .exceptions import ReqonError, InvalidTypeError, InvalidFilterError def query(query): try: reql = r.db(query['$db']).table(q...
Fix arguments order of reqon.deprecated.build_terms().
Fix arguments order of reqon.deprecated.build_terms().
Python
mit
dmpayton/reqon
05715aca84152c78cf0b4d5d7b751ecfa3a9f35a
tinyblog/views/__init__.py
tinyblog/views/__init__.py
from datetime import datetime from django.http import Http404 from django.shortcuts import render_to_response, get_object_or_404 from django.template import RequestContext from django.views.generic import ( ArchiveIndexView, YearArchiveView, MonthArchiveView, ) from tinyblog.models import Post def post(re...
from datetime import datetime from django.http import Http404 from django.shortcuts import get_object_or_404 from django.views.generic import ( ArchiveIndexView, YearArchiveView, MonthArchiveView, DetailView, ) from tinyblog.models import Post class TinyBlogPostView(DetailView): template_name = 't...
Switch the main post detail view to a CBV
Switch the main post detail view to a CBV
Python
bsd-3-clause
dominicrodger/tinyblog,dominicrodger/tinyblog
fcf626b6cb898bba294f8f4e2ecd2ff57cd144a0
scripts/syscalls.py
scripts/syscalls.py
import sim, syscall_strings, platform if platform.architecture()[0] == '64bit': __syscall_strings = syscall_strings.syscall_strings_64 else: __syscall_strings = syscall_strings.syscall_strings_32 def syscall_name(syscall_number): return '%s[%d]' % (__syscall_strings.get(syscall_number, 'unknown'), syscall_numbe...
import sim, syscall_strings, sys if sys.maxsize == 2**31-1: __syscall_strings = syscall_strings.syscall_strings_32 else: __syscall_strings = syscall_strings.syscall_strings_64 def syscall_name(syscall_number): return '%s[%d]' % (__syscall_strings.get(syscall_number, 'unknown'), syscall_number) class LogSyscall...
Use different way to determine 32/64-bit which returns mode of current binary, not of the system
[scripts] Use different way to determine 32/64-bit which returns mode of current binary, not of the system
Python
mit
abanaiyan/sniper,abanaiyan/sniper,abanaiyan/sniper,abanaiyan/sniper,abanaiyan/sniper
4d641110454f114d1f179d306fb63166e66fd6cf
src/foremast/slacknotify/slack_notification.py
src/foremast/slacknotify/slack_notification.py
"""Notify Slack channel.""" import time from ..utils import get_properties, get_template, post_slack_message class SlackNotification: """Post slack notification. Inform users about infrastructure changes to prod* accounts. """ def __init__(self, app=None, env=None, prop_path=None): self.inf...
"""Notify Slack channel.""" import time from ..utils import get_properties, get_template, post_slack_message class SlackNotification: """Post slack notification. Inform users about infrastructure changes to prod* accounts. """ def __init__(self, app=None, env=None, prop_path=None): timestam...
Move timestamp before dict for insertion
fix: Move timestamp before dict for insertion
Python
apache-2.0
gogoair/foremast,gogoair/foremast
7e11e57ee4f9fc1dc3c967c9b2d26038a7727f72
wqflask/wqflask/database.py
wqflask/wqflask/database.py
# Module to initialize sqlalchemy with flask import os import sys from string import Template from typing import Tuple from urllib.parse import urlparse import importlib import MySQLdb from sqlalchemy import create_engine from sqlalchemy.orm import scoped_session, sessionmaker from sqlalchemy.ext.declarative import d...
# Module to initialize sqlalchemy with flask import os import sys from string import Template from typing import Tuple from urllib.parse import urlparse import importlib import MySQLdb def sql_uri(): """Read the SQL_URI from the environment or settings file.""" return os.environ.get( "SQL_URI", read_...
Delete unused function and imports.
Delete unused function and imports. * wqflask/wqflask/database.py: Remove unused sqlalchemy imports. (read_from_pyfile): Delete it.
Python
agpl-3.0
genenetwork/genenetwork2,genenetwork/genenetwork2,genenetwork/genenetwork2,genenetwork/genenetwork2
bdcca9f505c185fa0ade4e93a88b8dabc85f9176
pysearch/urls.py
pysearch/urls.py
from django.conf.urls import patterns, include, url from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', 'pysearch.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^admin/', include(admin.site.urls)), url(r'^search/', inclu...
from django.conf.urls import patterns, include, url from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', 'pysearch.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^search/', include('search.urls')), )
Remove access to admin site
Remove access to admin site
Python
mit
nh0815/PySearch,nh0815/PySearch
5c787be025ca99da339aae221b714bd1d8f2d0bd
route/station.py
route/station.py
from flask import request from flask.ext import restful from route.base import api from model.base import db from model.user import User import logging class StationAPI(restful.Resource): def post(self): data = request.get_json() station = Station(data['name'], data['address'], data['address2'], data['...
from flask import request from flask.ext import restful from route.base import api from model.base import db from model.user import User import logging class StationAPI(restful.Resource): def post(self): data = request.get_json() station = Station(data['name'], data['address'], data['address2'], data['...
Add start of get funtion
Add start of get funtion
Python
mit
hexa4313/velov-companion-server,hexa4313/velov-companion-server
d64e85f96483e6b212adca38ca5fa89c64508701
froide_campaign/listeners.py
froide_campaign/listeners.py
from .models import Campaign, InformationObject def connect_info_object(sender, **kwargs): reference = kwargs.get('reference') if reference is None: return if 'campaign' not in reference: return try: campaign, slug = reference['campaign'].split('@', 1) except (ValueError, I...
from .models import Campaign, InformationObject def connect_info_object(sender, **kwargs): reference = kwargs.get('reference') if not reference: return if not reference.startswith('campaign:'): return namespace, campaign_value = reference.split(':', 1) try: campaign, slug =...
Adjust to new reference handling
Adjust to new reference handling
Python
mit
okfde/froide-campaign,okfde/froide-campaign,okfde/froide-campaign
b5fa4f9eb11575ddd8838bc53817854de831337f
dumpling/views.py
dumpling/views.py
from django.conf import settings from django.shortcuts import get_object_or_404 from django.views.generic import DetailView from .models import Page class PageView(DetailView): context_object_name = 'page' def get_queryset(self): return Page.objects.published().prefetch_related('pagewidget__widget')...
from django.conf import settings from django.shortcuts import get_object_or_404, render from django.views.generic import DetailView from .models import Page class PageView(DetailView): context_object_name = 'page' def get_queryset(self): return Page.objects.published().prefetch_related('pagewidget_s...
Fix prefetch. Add styles view
Fix prefetch. Add styles view
Python
mit
funkybob/dumpling,funkybob/dumpling
5cf66e26259f5b4c78e61530822fa19dfc117206
settings_test.py
settings_test.py
INSTALLED_APPS = ( 'oauth_tokens', 'taggit', 'vkontakte_groups', ) OAUTH_TOKENS_VKONTAKTE_CLIENT_ID = 3430034 OAUTH_TOKENS_VKONTAKTE_CLIENT_SECRET = 'b0FwzyKtO8QiQmgWQMTz' OAUTH_TOKENS_VKONTAKTE_SCOPE = ['ads,wall,photos,friends,stats'] OAUTH_TOKENS_VKONTAKTE_USERNAME = '+919665223715' OAUTH_TOKENS_VKONTAK...
INSTALLED_APPS = ( 'oauth_tokens', 'taggit', 'vkontakte_groups', ) OAUTH_TOKENS_VKONTAKTE_CLIENT_ID = 3430034 OAUTH_TOKENS_VKONTAKTE_CLIENT_SECRET = 'b0FwzyKtO8QiQmgWQMTz' OAUTH_TOKENS_VKONTAKTE_SCOPE = ['ads,wall,photos,friends,stats'] OAUTH_TOKENS_VKONTAKTE_USERNAME = '+919665223715' OAUTH_TOKENS_VKONTAK...
Fix RuntimeError: maximum recursion depth
Fix RuntimeError: maximum recursion depth
Python
bsd-3-clause
ramusus/django-vkontakte-groups-statistic,ramusus/django-vkontakte-groups-statistic,ramusus/django-vkontakte-groups-statistic
a81fbdd334dc475554e77bbb71ae00985f2d23c4
eventlog/stats.py
eventlog/stats.py
from datetime import datetime, timedelta from django.contrib.auth.models import User def stats(): return { "used_site_last_thirty_days": User.objects.filter(log__timestamp__gt=datetime.now() - timedelta(days=30)).distinct().count(), "used_site_last_seven_days": User.objects.filter(log__timestamp_...
from datetime import datetime, timedelta from django.contrib.auth.models import User def used_active(days): used = User.objects.filter( log__timestamp__gt=datetime.now() - timedelta(days=days) ).distinct().count() active = User.objects.filter( log__timestamp__gt=datetime.now() - time...
Add active_seven and active_thirty users
Add active_seven and active_thirty users
Python
bsd-3-clause
ConsumerAffairs/django-eventlog-ca,rosscdh/pinax-eventlog,KleeTaurus/pinax-eventlog,jawed123/pinax-eventlog,pinax/pinax-eventlog
850803d02868e20bc637f777ee201ac778c63606
lms/djangoapps/edraak_misc/utils.py
lms/djangoapps/edraak_misc/utils.py
from courseware.access import has_access from django.conf import settings def is_certificate_allowed(user, course): return (course.has_ended() and settings.FEATURES.get('ENABLE_ISSUE_CERTIFICATE') or has_access(user, 'staff', course.id))
from courseware.access import has_access from django.conf import settings def is_certificate_allowed(user, course): if not settings.FEATURES.get('ENABLE_ISSUE_CERTIFICATE'): return False return course.has_ended() or has_access(user, 'staff', course.id)
Disable certificate for all if ENABLE_ISSUE_CERTIFICATE == False
Disable certificate for all if ENABLE_ISSUE_CERTIFICATE == False
Python
agpl-3.0
Edraak/edx-platform,Edraak/edx-platform,Edraak/circleci-edx-platform,Edraak/circleci-edx-platform,Edraak/circleci-edx-platform,Edraak/edx-platform,Edraak/edx-platform,Edraak/circleci-edx-platform,Edraak/circleci-edx-platform,Edraak/edx-platform
b3a144e9dfba915d186fd1243515172780611689
models/waifu_model.py
models/waifu_model.py
from models.base_model import BaseModel from datetime import datetime from models.user_model import UserModel from peewee import CharField, TextField, DateTimeField, IntegerField, ForeignKeyField WAIFU_SHARING_STATUS_PRIVATE = 1 WAIFU_SHARING_STATUS_PUBLIC_MODERATION = 2 WAIFU_SHARING_STATUS_PUBLIC = 3 class WaifuMo...
from models.base_model import BaseModel from datetime import datetime from models.user_model import UserModel from peewee import CharField, TextField, DateTimeField, IntegerField, ForeignKeyField WAIFU_SHARING_STATUS_PRIVATE = 1 WAIFU_SHARING_STATUS_PUBLIC_MODERATION = 2 WAIFU_SHARING_STATUS_PUBLIC = 3 class WaifuMo...
Add users count to json representation.
Add users count to json representation.
Python
cc0-1.0
sketchturnerr/WaifuSim-backend,sketchturnerr/WaifuSim-backend
0474872ea9db994928fa6848b89b847b4fc80986
smst/__init__.py
smst/__init__.py
__version__ = '0.2.0'
# _ _ # ___ _ __ ___ ___ | |_ ___ ___ | |___ # / __| '_ ` _ \/ __| | __/ _ \ / _ \| / __| # \__ \ | | | | \__ \ | || (_) | (_) | \__ \ # |___/_| |_| |_|___/ \__\___/ \___/|_|___/ # # ~ Spectral Modeling Synthesis Tools ~ # __version__ = '0.2.0'
Add a nice banner made using the figlet tool.
Add a nice banner made using the figlet tool.
Python
agpl-3.0
bzamecnik/sms-tools,bzamecnik/sms-tools,bzamecnik/sms-tools
f6841a527bd8b52aa88c4c3b5980a0001387f33e
scoring/models/regressors.py
scoring/models/regressors.py
from sklearn.ensemble import RandomForestRegressor as randomforest from sklearn.svm import SVR as svm from sklearn.pls import PLSRegression as pls from .neuralnetwork import neuralnetwork __all__ = ['randomforest', 'svm', 'pls', 'neuralnetwork']
from sklearn.ensemble import RandomForestRegressor from sklearn.svm import SVR from sklearn.pls import PLSRegression from .neuralnetwork import neuralnetwork __all__ = ['randomforest', 'svm', 'pls', 'neuralnetwork'] class randomforest(RandomForestRegressor): pass class svm(SVR): pass class svm(PLSRegressio...
Make models inherit from sklearn
Make models inherit from sklearn
Python
bsd-3-clause
mwojcikowski/opendrugdiscovery
0855f9b5a9d36817139e61937419553f6ad21f78
symposion/proposals/urls.py
symposion/proposals/urls.py
from django.conf.urls.defaults import * urlpatterns = patterns("symposion.proposals.views", url(r"^submit/$", "proposal_submit", name="proposal_submit"), url(r"^submit/(\w+)/$", "proposal_submit_kind", name="proposal_submit_kind"), url(r"^(\d+)/$", "proposal_detail", name="proposal_detail"), url(r"^(\...
from django.conf.urls import patterns, url urlpatterns = patterns("symposion.proposals.views", url(r"^submit/$", "proposal_submit", name="proposal_submit"), url(r"^submit/([\w-]+)/$", "proposal_submit_kind", name="proposal_submit_kind"), url(r"^(\d+)/$", "proposal_detail", name="proposal_detail"), url...
Allow dashes in proposal kind slugs
Allow dashes in proposal kind slugs We can see from the setting PROPOSAL_FORMS that at least one proposal kind, Sponsor Tutorial, has a slug with a dash in it: sponsor-tutorial. Yet the URL pattern for submitting a proposal doesn't accept dashes in the slug. Fix it.
Python
bsd-3-clause
njl/pycon,pyconjp/pyconjp-website,njl/pycon,Diwahars/pycon,smellman/sotmjp-website,pyconjp/pyconjp-website,pyconjp/pyconjp-website,PyCon/pycon,osmfj/sotmjp-website,njl/pycon,Diwahars/pycon,PyCon/pycon,pyconjp/pyconjp-website,osmfj/sotmjp-website,osmfj/sotmjp-website,PyCon/pycon,osmfj/sotmjp-website,smellman/sotmjp-webs...
da9c0743657ecc890c2a8503ea4bbb681ae00178
tests/chainer_tests/functions_tests/math_tests/test_arctanh.py
tests/chainer_tests/functions_tests/math_tests/test_arctanh.py
import unittest from chainer import testing import chainer.functions as F import numpy def make_data(shape, dtype): # Input values close to -1 or 1 would make tests unstable x = numpy.random.uniform(-0.9, 0.9, shape).astype(dtype, copy=False) gy = numpy.random.uniform(-1, 1, shape).astype(dtype, copy=Fal...
import unittest from chainer import testing import chainer.functions as F import numpy def make_data(shape, dtype): # Input values close to -1 or 1 would make tests unstable x = numpy.random.uniform(-0.9, 0.9, shape).astype(dtype, copy=False) gy = numpy.random.uniform(-1, 1, shape).astype(dtype, copy=Fal...
Call testing.run_module at the end of the test
Call testing.run_module at the end of the test
Python
mit
okuta/chainer,keisuke-umezawa/chainer,wkentaro/chainer,wkentaro/chainer,okuta/chainer,chainer/chainer,niboshi/chainer,okuta/chainer,pfnet/chainer,chainer/chainer,tkerola/chainer,chainer/chainer,niboshi/chainer,keisuke-umezawa/chainer,okuta/chainer,wkentaro/chainer,hvy/chainer,wkentaro/chainer,niboshi/chainer,niboshi/ch...
584891ce58c3e979a5d6871ba7a6ff0a9e01d780
routes/student_vote.py
routes/student_vote.py
from aiohttp import web from db_helper import get_project_id, get_most_recent_group, get_user_id from permissions import view_only, value_set @view_only("join_projects") @value_set("student_choosable") async def on_submit(request): session = request.app["session"] cookies = request.cookies post = await r...
from aiohttp import web from db_helper import get_project_id, get_user_id, can_choose_project from permissions import view_only, value_set @view_only("join_projects") @value_set("student_choosable") async def on_submit(request): session = request.app["session"] cookies = request.cookies post = await requ...
Check if student can choose a project before allowing them to join it
Check if student can choose a project before allowing them to join it
Python
agpl-3.0
wtsi-hgi/CoGS-Webapp,wtsi-hgi/CoGS-Webapp,wtsi-hgi/CoGS-Webapp
92ab5c0878ba528fb49a42fde64dd4d6474bc1e8
app/models.py
app/models.py
from app import db class User(db.Model): __tablename__ = 'users' username = db.Column(db.String(64), nullable=False, unique=True, primary_key=True) password = db.Column(db.String(192), nullable=False) def __init__(self, username, password): self.username = username self.password = p...
from app import db class User(db.Model): __tablename__ = 'users' username = db.Column(db.String(64), nullable=False, unique=True, primary_key=True) password = db.Column(db.String(192), nullable=False) def __init__(self, username, password): self.username = username self.password = p...
Update order of patient attributes in model.
Update order of patient attributes in model.
Python
mit
jawrainey/atc,jawrainey/atc
eefff91804317f4fb2c518446ab8e2072af4d87f
app/models.py
app/models.py
from django.db import models import mongoengine from mongoengine import Document, EmbeddedDocument from mongoengine.fields import * # Create your models here. class Greeting(models.Model): when = models.DateTimeField('date created', auto_now_add=True) MONGODB_URI = 'mongodb+srv://fikaadmin:ZJ6TtyTZMXA@fikanoted...
from django.db import models import mongoengine from mongoengine import Document, EmbeddedDocument from mongoengine.fields import * import os # Create your models here. class Greeting(models.Model): when = models.DateTimeField('date created', auto_now_add=True) USER = os.getenv('DATABASE_USER') PASWORD = os.gete...
Remove username and password from repository
Remove username and password from repository
Python
mit
gmkou/FikaNote,gmkou/FikaNote,gmkou/FikaNote
556cef75198e3a5a8ac3e8f523c54b0b2df6a2c1
mousestyles/data/tests/test_data.py
mousestyles/data/tests/test_data.py
"""Standard test data. """ from __future__ import (absolute_import, division, print_function, unicode_literals) import numpy as np from numpy.testing import assert_equal import mousestyles.data as data def test_all_features_mousedays_11bins(): all_features = data.all_feature_data() ...
"""Standard test data. """ from __future__ import (absolute_import, division, print_function, unicode_literals) import numpy as np from numpy.testing import assert_equal import mousestyles.data as data def test_all_features_loader(): all_features = data.load_all_features() assert_eq...
Test for new data loader
TST: Test for new data loader Just a start, should probably add a more detailed test later.
Python
bsd-2-clause
berkeley-stat222/mousestyles,togawa28/mousestyles,changsiyao/mousestyles
1e10fa30998f63359ddd26d9804bd32a837c2cab
armstrong/esi/tests/_utils.py
armstrong/esi/tests/_utils.py
from django.conf import settings from django.test import TestCase as DjangoTestCase import fudge class TestCase(DjangoTestCase): def setUp(self): self._original_settings = settings def tearDown(self): settings = self._original_settings
from django.conf import settings from django.http import HttpRequest from django.test import TestCase as DjangoTestCase import fudge def with_fake_request(func): def inner(self, *args, **kwargs): request = fudge.Fake(HttpRequest) fudge.clear_calls() result = func(self, request, *args, **kw...
Add in a decorator for generating fake request objects for test cases
Add in a decorator for generating fake request objects for test cases
Python
bsd-3-clause
armstrong/armstrong.esi
c8896c3eceb6ef7ffc6eef16af849597a8f7b8e2
Lib/test/test_sunaudiodev.py
Lib/test/test_sunaudiodev.py
from test_support import verbose, TestFailed import sunaudiodev import os def findfile(file): if os.path.isabs(file): return file import sys for dn in sys.path: fn = os.path.join(dn, file) if os.path.exists(fn): return fn return file def play_sound_file(path): fp = open(path, 'r') data = fp.read() ...
from test_support import verbose, TestFailed import sunaudiodev import os def findfile(file): if os.path.isabs(file): return file import sys path = sys.path try: path = [os.path.dirname(__file__)] + path except NameError: pass for dn in path: fn = os.path.join(dn, file) if os.path.exists(fn): return fn ...
Make this test work when imported from the interpreter instead of run from regrtest.py (it still works there too, of course).
Make this test work when imported from the interpreter instead of run from regrtest.py (it still works there too, of course).
Python
mit
sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator
675e0a29f780d6053d942dce4f80c6d934f3785a
Python/tigre/utilities/Ax.py
Python/tigre/utilities/Ax.py
from _Ax import _Ax_ext import numpy as np import copy def Ax(img, geo, angles, projection_type="Siddon"): if img.dtype != np.float32: raise TypeError("Input data should be float32, not "+ str(img.dtype)) if not np.isreal(img).all(): raise ValueError("Complex types not compatible for ...
from _Ax import _Ax_ext import numpy as np import copy def Ax(img, geo, angles, projection_type="Siddon"): if img.dtype != np.float32: raise TypeError("Input data should be float32, not "+ str(img.dtype)) if not np.isreal(img).all(): raise ValueError("Complex types not compatible for ...
Check the shape of input data earlier
Check the shape of input data earlier Using geo.nVoxel to check the input img shape earlier, before geo is casted to float32 (geox). We should use any() instead of all(), since "!=" is used?
Python
bsd-3-clause
CERN/TIGRE,CERN/TIGRE,CERN/TIGRE,CERN/TIGRE
08d6c4414d72b5431d5a50013058f325f38d7b1c
txdbus/test/test_message.py
txdbus/test/test_message.py
import os import unittest from txdbus import error, message class MessageTester(unittest.TestCase): def test_too_long(self): class E(message.ErrorMessage): _maxMsgLen = 1 def c(): E('foo.bar', 5) self.assertRaises(error.MarshallingError, c) def test_r...
import os import unittest from txdbus import error, message class MessageTester(unittest.TestCase): def test_too_long(self): class E(message.ErrorMessage): _maxMsgLen = 1 def c(): E('foo.bar', 5) self.assertRaises(error.MarshallingError, c) def test_r...
Fix message tests after in message.parseMessage args three commits ago
Fix message tests after in message.parseMessage args three commits ago (three commits ago is 08a6c170daa79e74ba538c928e183f441a0fb441)
Python
mit
cocagne/txdbus
84c2c987151451180281f1aecb0483321462340c
influxalchemy/__init__.py
influxalchemy/__init__.py
""" InfluxDB Alchemy. """ from .client import InfluxAlchemy from .measurement import Measurement __version__ = "0.1.0"
""" InfluxDB Alchemy. """ import pkg_resources from .client import InfluxAlchemy from .measurement import Measurement try: __version__ = pkg_resources.get_distribution(__package__).version except pkg_resources.DistributionNotFound: # pragma: no cover __version__ = None # pragma: no cove...
Use package version for __version__
Use package version for __version__
Python
mit
amancevice/influxalchemy
fc6e3c276ee638fbb4409fa00d470817205f2028
lib/awsflow/test/workflow_testing_context.py
lib/awsflow/test/workflow_testing_context.py
from awsflow.core import AsyncEventLoop from awsflow.context import ContextBase class WorkflowTestingContext(ContextBase): def __init__(self): self._event_loop = AsyncEventLoop() def __enter__(self): self._context = self.get_context() self.set_context(self) self._event_loop....
from awsflow.core import AsyncEventLoop from awsflow.context import ContextBase class WorkflowTestingContext(ContextBase): def __init__(self): self._event_loop = AsyncEventLoop() def __enter__(self): try: self._context = self.get_context() except AttributeError: ...
Fix context setting on the test context
Fix context setting on the test context
Python
apache-2.0
darjus/botoflow,boto/botoflow
b3fb2ba913a836a1e198795019870e318879d5f7
dictionary/forms.py
dictionary/forms.py
from django import forms from django.forms.models import BaseModelFormSet from django.utils.translation import ugettext_lazy as _ class BaseWordFormSet(BaseModelFormSet): def add_fields(self, form, index): super(BaseWordFormSet, self).add_fields(form, index) form.fields["isLocal"] = forms.BooleanF...
from django import forms from django.forms.models import BaseModelFormSet from django.utils.translation import ugettext_lazy as _ class BaseWordFormSet(BaseModelFormSet): def add_fields(self, form, index): super(BaseWordFormSet, self).add_fields(form, index) form.fields["isLocal"] = forms.BooleanF...
Make sure the isLocal BooleanField is not required
Make sure the isLocal BooleanField is not required
Python
agpl-3.0
sbsdev/daisyproducer,sbsdev/daisyproducer,sbsdev/daisyproducer,sbsdev/daisyproducer
e34b7c8d9e869ac1be10e8ae3d71cea794044e13
docs/blender-sphinx-build.py
docs/blender-sphinx-build.py
import os import site # get site-packages into sys.path import sys # add local addons folder to sys.path so blender finds it sys.path = ( [os.path.join(os.path.dirname(__file__), '..', 'scripts', 'addons')] + sys.path ) # run sphinx builder # this assumes that the builder is called as # "blender --backgro...
import os import site # get site-packages into sys.path import sys # add local addons folder to sys.path so blender finds it sys.path = ( [os.path.join(os.path.dirname(__file__), '..')] + sys.path ) # run sphinx builder # this assumes that the builder is called as # "blender --background --factory-startup...
Correct sys.path when generating docs.
Correct sys.path when generating docs.
Python
bsd-3-clause
nightstrike/blender_nif_plugin,amorilia/blender_nif_plugin,amorilia/blender_nif_plugin,nightstrike/blender_nif_plugin
2f60d4665a960578ab97bdaf313893ec366c24f1
kdb/default_config.py
kdb/default_config.py
# Module: defaults # Date: 14th May 2008 # Author: James Mills, prologic at shortcircuit dot net dot au """defaults - System Defaults This module contains default configuration and sane defaults for various parts of the system. These defaults are used by the environment initially when no environment has been ...
# Module: defaults # Date: 14th May 2008 # Author: James Mills, prologic at shortcircuit dot net dot au """defaults - System Defaults This module contains default configuration and sane defaults for various parts of the system. These defaults are used by the environment initially when no environment has been ...
Enable remote, rmessage and rnotify plugins by default
Enable remote, rmessage and rnotify plugins by default
Python
mit
prologic/kdb,prologic/kdb,prologic/kdb
6eca222d0bc36b2573a09c1345d940239f8e9d4d
documents/models.py
documents/models.py
from django.db import models from django.urls import reverse class Document(models.Model): FILE_TYPES = ('md', 'txt') repo = models.ForeignKey('interface.Repo', related_name='documents') path = models.TextField() filename = models.TextField() body = models.TextField(blank=True) commit_date = ...
from django.db import models from django.urls import reverse class Document(models.Model): FILE_TYPES = ('md', 'txt') repo = models.ForeignKey('interface.Repo', related_name='documents') path = models.TextField() filename = models.TextField() body = models.TextField(blank=True) commit_date = ...
Move Document.__str__ to named method
Move Document.__str__ to named method
Python
mit
ZeroCater/Eyrie,ZeroCater/Eyrie,ZeroCater/Eyrie
89d9987f742fa74fc3646ccc163610d0c9400d75
dewbrick/utils.py
dewbrick/utils.py
import tldextract import pyphen from random import choice TITLES = ('Mister', 'Little Miss') SUFFIXES = ('Destroyer of Worlds', 'the Monkey Botherer', 'PhD') def generate_name(domain): title = choice(TITLES) _parts = tldextract.extract(domain) _parts = [_parts.subdomain, _parts.domain] parts = [] ...
import tldextract import pyphen from random import choice TITLES = ('Mister', 'Little Miss', 'Señor', 'Queen') SUFFIXES = ('Destroyer of Worlds', 'the Monkey Botherer', 'PhD', 'Ah-gowan-gowan-gowan') def generate_name(domain): title = choice(TITLES) _parts = tldextract.extract(domain) _parts...
Add more titles and suffixes
Add more titles and suffixes
Python
apache-2.0
ohmygourd/dewbrick,ohmygourd/dewbrick,ohmygourd/dewbrick
e9814c857bdbf3d163352abddade1d12f0e30810
mbaas/settings_jenkins.py
mbaas/settings_jenkins.py
from mbaas.settings import * INSTALLED_APPS += ('django_nose',) TEST_RUNNER = 'django_nose.NoseTestSuiteRunner' NOSE_ARGS = [ '--cover-erase', '--with-xunit', '--with-coverage', '--cover-xml', '--cover-html', '--cover-package=accounts,push', ] DATABASES = { 'default': { 'ENGINE': 'dj...
from mbaas.settings import * INSTALLED_APPS += ('django_nose',) TEST_RUNNER = 'django_nose.NoseTestSuiteRunner' NOSE_ARGS = [ '--with-xunit', '--with-coverage', '--cover-xml', '--cover-html', '--cover-package=accounts,push', ] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqli...
Remove clear before test results
Remove clear before test results
Python
apache-2.0
nnsnodnb/django-mbaas,nnsnodnb/django-mbaas,nnsnodnb/django-mbaas
4b4ed18f01c13c321285463628bb0a3b70a75ac5
test/conftest.py
test/conftest.py
import functools import os.path import shutil import sys import tempfile import pytest @pytest.fixture(scope="function") def HOME(tmpdir): home = os.path.join(tmpdir, 'john') os.mkdir(home) # NOTE: homely._utils makes use of os.environ['HOME'], so we need to # destroy any homely modules that may have...
import functools import os.path import shutil import sys import tempfile import pytest @pytest.fixture(scope="function") def HOME(tmpdir): old_home = os.environ['HOME'] try: home = os.path.join(tmpdir, 'john') os.mkdir(home) # NOTE: homely._utils makes use of os.environ['HOME'], so w...
Rework HOME fixture so it doesn't leave os.environ corrupted
Rework HOME fixture so it doesn't leave os.environ corrupted
Python
mit
phodge/homely,phodge/homely
4be8c3f8164fe0973d6277ea0d827b777cd4a988
locations/pipelines.py
locations/pipelines.py
# -*- coding: utf-8 -*- # Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html from scrapy.exceptions import DropItem class DuplicatesPipeline(object): def __init__(self): self.ids_seen = set(...
# -*- coding: utf-8 -*- # Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html from scrapy.exceptions import DropItem class DuplicatesPipeline(object): def __init__(self): self.ids_seen = set(...
Include spider name in item dedupe pipeline
Include spider name in item dedupe pipeline
Python
mit
iandees/all-the-places,iandees/all-the-places,iandees/all-the-places
edd5adc9be2a700421bd8e98af825322796b8714
dns/models.py
dns/models.py
from google.appengine.ext import db TOP_LEVEL_DOMAINS = 'com net org biz info'.split() class Lookup(db.Model): """ The datastore key name is the domain name, without top level. IP address fields use 0 (zero) for NXDOMAIN because None is returned for missing properties. Updates since 2010-01-01 ...
from google.appengine.ext import db TOP_LEVEL_DOMAINS = """ com net org biz info ag am at be by ch ck de es eu fm in io is it la li ly me mobi ms name ru se sh sy tel th to travel tv us """.split() # Omitting nu, ph, st, ws because they don't seem to have NXDOMAIN. class UpgradeStringProperty(db.IntegerProperty): ...
Upgrade Lookup model to Expando and DNS result properties from integer to string.
Upgrade Lookup model to Expando and DNS result properties from integer to string.
Python
mit
jcrocholl/nxdom,jcrocholl/nxdom
00cbac852e83eb1f3ddc03ed70ad32494f16fdbf
caslogging.py
caslogging.py
""" file: caslogging.py author: Ben Grawi <bjg1568@rit.edu> date: October 2013 description: Sets up the logging information for the CAS Reader """ from config import config import logging as root_logging # Set up the logger logger = root_logging.getLogger() logger.setLevel(root_logging.INFO) logger_for...
""" file: caslogging.py author: Ben Grawi <bjg1568@rit.edu> date: October 2013 description: Sets up the logging information for the CAS Reader """ from config import config import logging as root_logging # Set up the logger logger = root_logging.getLogger() logger.setLevel(root_logging.INFO) logger_for...
Fix of the logging system exception
Fix of the logging system exception Added a format to the date for the logging system. '%Y-%m-%d %H:%M:%S’. Fixed an exception opening the logging file because the variable name was not written correctly.
Python
mit
bumper-app/bumper-bianca,bumper-app/bumper-bianca
8bacd0f657a931754d8c03e2de86c5e00ac5f791
modoboa/lib/cryptutils.py
modoboa/lib/cryptutils.py
# coding: utf-8 from Crypto.Cipher import AES import base64 import random import string from modoboa.lib import parameters def random_key(l=16): """Generate a random key :param integer l: the key's length :return: a string """ char_set = string.digits + string.letters + string.punctuation ret...
# coding: utf-8 """Crypto related utilities.""" import base64 import random import string from Crypto.Cipher import AES from modoboa.lib import parameters def random_key(l=16): """Generate a random key. :param integer l: the key's length :return: a string """ population = string.digits + strin...
Make sure key has the required size.
Make sure key has the required size. see #867
Python
isc
tonioo/modoboa,modoboa/modoboa,bearstech/modoboa,carragom/modoboa,tonioo/modoboa,modoboa/modoboa,bearstech/modoboa,carragom/modoboa,bearstech/modoboa,bearstech/modoboa,modoboa/modoboa,carragom/modoboa,modoboa/modoboa,tonioo/modoboa
61cef22952451df6345355ad596b38cb92697256
flocker/test/test_flocker.py
flocker/test/test_flocker.py
# Copyright Hybrid Logic Ltd. See LICENSE file for details. """ Tests for top-level ``flocker`` package. """ from sys import executable from subprocess import check_output, STDOUT from twisted.trial.unittest import SynchronousTestCase class WarningsTests(SynchronousTestCase): """ Tests for warning suppres...
# Copyright Hybrid Logic Ltd. See LICENSE file for details. """ Tests for top-level ``flocker`` package. """ from sys import executable from subprocess import check_output, STDOUT from twisted.trial.unittest import SynchronousTestCase from twisted.python.filepath import FilePath import flocker class WarningsTest...
Make sure flocker package can be imported even if it's not installed.
Make sure flocker package can be imported even if it's not installed.
Python
apache-2.0
beni55/flocker,hackday-profilers/flocker,achanda/flocker,adamtheturtle/flocker,mbrukman/flocker,Azulinho/flocker,w4ngyi/flocker,agonzalezro/flocker,agonzalezro/flocker,1d4Nf6/flocker,moypray/flocker,AndyHuu/flocker,lukemarsden/flocker,wallnerryan/flocker-profiles,mbrukman/flocker,w4ngyi/flocker,Azulinho/flocker,LaynePe...
879b093f29135750906f5287e132991de42ea1fe
mqtt/tests/test_client.py
mqtt/tests/test_client.py
import time from django.test import TestCase from django.contrib.auth.models import User from django.conf import settings from rest_framework.renderers import JSONRenderer from rest_framework.parsers import JSONParser from io import BytesIO import json from login.models import Profile, AmbulancePermission, HospitalP...
import time from django.test import TestCase from django.contrib.auth.models import User from django.conf import settings from rest_framework.renderers import JSONRenderer from rest_framework.parsers import JSONParser from io import BytesIO import json from login.models import Profile, AmbulancePermission, HospitalP...
Add more time to mqtt.test.client
Add more time to mqtt.test.client
Python
bsd-3-clause
EMSTrack/WebServerAndClient,EMSTrack/WebServerAndClient,EMSTrack/WebServerAndClient
384822f44d0731f425698cc67115d179d8d13e4c
examples/mastery.py
examples/mastery.py
import cassiopeia as cass from cassiopeia.core import Summoner def test_cass(): name = "Kalturi" masteries = cass.get_masteries() for mastery in masteries: print(mastery.name) if __name__ == "__main__": test_cass()
import cassiopeia as cass def print_masteries(): for mastery in cass.get_masteries(): print(mastery.name) if __name__ == "__main__": print_masteries()
Remove redundant import, change function name.
Remove redundant import, change function name.
Python
mit
10se1ucgo/cassiopeia,meraki-analytics/cassiopeia,robrua/cassiopeia
e49638c1b2f844e3fa74e00b0d0a96b7c9774c24
test/test_box.py
test/test_box.py
from nex import box def test_glue_flex(): h_box = box.HBox(contents=[box.Glue(dimen=100, stretch=50, shrink=20), box.Glue(dimen=10, stretch=350, shrink=21)], set_glue=False) assert h_box.stretch == [50 + 350] assert h_box.shrink == [20 + 21] def test_g...
from nex.dampf.dvi_document import DVIDocument from nex import box, box_writer def test_glue_flex(): h_box = box.HBox(contents=[box.Glue(dimen=100, stretch=50, shrink=20), box.Glue(dimen=10, stretch=350, shrink=21)], set_glue=False) assert h_box.stretch == [...
Add basic test for box writer
Add basic test for box writer
Python
mit
eddiejessup/nex
76f1ae6bfc6ad22cc06c012a6b96cbf6b12b8d8a
registration/admin.py
registration/admin.py
from django.contrib import admin from registration.models import RegistrationProfile class RegistrationAdmin(admin.ModelAdmin): list_display = ('__unicode__', 'activation_key_expired') search_fields = ('user__username', 'user__first_name') admin.site.register(RegistrationProfile, RegistrationAdmin)
from django.contrib import admin from registration.models import RegistrationProfile class RegistrationAdmin(admin.ModelAdmin): list_display = ('__unicode__', 'activation_key_expired') raw_id_fields = ['user'] search_fields = ('user__username', 'user__first_name') admin.site.register(RegistrationProfil...
Use raw_id_fields for the relation from RegistrationProfile to User, for sites which have huge numbers of users.
Use raw_id_fields for the relation from RegistrationProfile to User, for sites which have huge numbers of users.
Python
bsd-3-clause
stefankoegl/django-registration-couchdb,ogirardot/django-registration,andresdouglas/django-registration,bruth/django-registration2,stefankoegl/django-couchdb-utils,ogirardot/django-registration,ratio/django-registration,danielsokolowski/django-registration,wuyuntao/django-registration,stefankoegl/django-couchdb-utils,s...
921421e4d9e2d536596980e14286db5faa83dd5c
egpackager/cli.py
egpackager/cli.py
#!/usr/bin/env python import click import sys from egpackager.datasources import GspreadDataSource @click.group() def cli(): ''' ''' pass @cli.command() def register(): click.echo(click.style('Initialized the database', fg='green')) @cli.command() def list(): click.echo(click.style('Dropped ...
#!/usr/bin/env python import click import sys from egpackager.registry import RegistryManager @click.group() @click.pass_context def cli(ctx): ''' ''' ctx.obj = {} ctx.obj['MANAGER'] = RegistryManager() @cli.command() @click.pass_context @click.option('--type', type=click.Choice(['gspread']), help...
Add basic options for the CLI
Add basic options for the CLI
Python
mit
VUEG/egpackager
bd2d1869894b30eb83eb11ec6e9814e7ab2d4168
panda/api/activity_log.py
panda/api/activity_log.py
#!/usr/bin/env python from tastypie import fields from tastypie.authorization import DjangoAuthorization from panda.api.utils import PandaApiKeyAuthentication, PandaModelResource, PandaSerializer from panda.models import ActivityLog class ActivityLogResource(PandaModelResource): """ API resource for DataUpl...
#!/usr/bin/env python from tastypie import fields from tastypie.authorization import DjangoAuthorization from tastypie.exceptions import ImmediateHttpResponse from tastypie.http import HttpConflict from panda.api.utils import PandaApiKeyAuthentication, PandaModelResource, PandaSerializer from django.db import Integri...
Return 409 for duplicate activity logging.
Return 409 for duplicate activity logging.
Python
mit
ibrahimcesar/panda,PalmBeachPost/panda,ibrahimcesar/panda,NUKnightLab/panda,pandaproject/panda,datadesk/panda,newsapps/panda,ibrahimcesar/panda,newsapps/panda,pandaproject/panda,PalmBeachPost/panda,PalmBeachPost/panda,NUKnightLab/panda,pandaproject/panda,pandaproject/panda,ibrahimcesar/panda,ibrahimcesar/panda,PalmBeac...
fb69cb186b4c82ae5f64551dc65a3ed948650b5e
voteswap/urls.py
voteswap/urls.py
"""voteswap URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.9/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-ba...
"""voteswap URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.9/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-ba...
Make signup just point to landing page
Make signup just point to landing page
Python
mit
sbuss/voteswap,sbuss/voteswap,sbuss/voteswap,sbuss/voteswap
8bf5edab5cebb0e713d67c0ec5f866b2d63d537b
wdom/__init__.py
wdom/__init__.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from wdom.log import configure_logger configure_logger()
#!/usr/bin/env python3 # -*- coding: utf-8 -*-
Revert configure logger at initialization
Revert configure logger at initialization
Python
mit
miyakogi/wdom,miyakogi/wdom,miyakogi/wdom
b07964e8b243b151e64af86cb09a37e980f94eb1
vantage/utils.py
vantage/utils.py
import binascii import base64 import click def to_base64(value): value = base64.urlsafe_b64encode(value.encode("utf-8")).decode("utf-8") return f"base64:{value}" def from_base64(value): if value.startswith("base64:"): try: value = base64.urlsafe_b64decode(value[7:]).decode("utf-8") ...
import binascii import base64 import click def to_base64(value): value = base64.urlsafe_b64encode(value.encode("utf-8")).decode("utf-8") return f"base64:{value}" def from_base64(value): if value.startswith("base64:"): try: value = base64.urlsafe_b64decode(value[7:]).decode("utf-8") ...
Add optional env kwargs to logging method
Add optional env kwargs to logging method
Python
mit
vantage-org/vantage,vantage-org/vantage
f11cf81bec8c1590aa8cbeb65209b493f96dd766
general/zipUnzip.py
general/zipUnzip.py
import os import zipfile import zipfile try: import zlib mode= zipfile.ZIP_DEFLATED except: mode= zipfile.ZIP_STORED def unzipDir(inputDir): for root, dirs, files in os.walk(inputDir): for f in files: if f.endswith('.zip'): inFile = os.path.join(root, f) ...
import os import zipfile import zipfile try: import zlib mode= zipfile.ZIP_DEFLATED except: mode= zipfile.ZIP_STORED def unzipDir(inputDir): for root, dirs, files in os.walk(inputDir): for f in files: if f.endswith('.zip'): inFile = os.path.join(root, f) ...
Create output dir if does not exist.
Create output dir if does not exist.
Python
mit
borchert/metadata-tools
f9a4ad56230de8c057e259b14fb14a309b2de0c0
homedisplay/control_milight/management/commands/run_timed.py
homedisplay/control_milight/management/commands/run_timed.py
from control_milight.models import LightAutomation from control_milight.views import update_lightstate from django.conf import settings from django.core.management.base import BaseCommand, CommandError from django.utils.timezone import now from ledcontroller import LedController import datetime import redis class Com...
from control_milight.models import LightAutomation from control_milight.views import update_lightstate from django.conf import settings from django.core.management.base import BaseCommand, CommandError from django.utils.timezone import now from ledcontroller import LedController import datetime import redis class Com...
Change morning transition color to white
Change morning transition color to white Fixes #25
Python
bsd-3-clause
ojarva/home-info-display,ojarva/home-info-display,ojarva/home-info-display,ojarva/home-info-display
50784afbb0c95f435c1a25e0840438e406349bbb
plyer/facades/uniqueid.py
plyer/facades/uniqueid.py
'''UniqueID facade. Returns the following depending on the platform: * **Android**: Android ID * **OS X**: Serial number of the device * **Linux**: Serial number using lshw * **Windows**: MachineGUID from regkey Simple Example -------------- To get the unique ID:: >>> from plyer import uniqueid >>> uniquei...
'''UniqueID facade. Returns the following depending on the platform: * **Android**: Android ID * **OS X**: Serial number of the device * **Linux**: Serial number using lshw * **Windows**: MachineGUID from regkey * **iOS**: UUID Simple Example -------------- To get the unique ID:: >>> from plyer import uniqueid...
Add description for iOS in facade
Add description for iOS in facade
Python
mit
kivy/plyer,kived/plyer,kivy/plyer,KeyWeeUsr/plyer,KeyWeeUsr/plyer,kived/plyer,kivy/plyer,KeyWeeUsr/plyer