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
15f482fbb7b1b98b48545f6e5ab3986859c38e55
watchman/main.py
watchman/main.py
from __future__ import print_function import sys import os from sh import cd, hg def _get_subdirectories(current_dir): return [directory for directory in os.listdir(current_dir) if os.path.isdir(os.path.join(current_dir, directory)) and directory[0] != '.'] def check(): current_work...
from __future__ import print_function import sys import os from sh import cd, hg def _get_subdirectories(current_dir): return [directory for directory in os.listdir(current_dir) if os.path.isdir(os.path.join(current_dir, directory)) and directory[0] != '.'] def check(): current_work...
Remove change dir commands and now it sends directly.
Remove change dir commands and now it sends directly.
Python
mit
alephmelo/watchman
88647bd762da9619c066c9bd79e48cb234247707
geotagging/views.py
geotagging/views.py
from django.http import HttpResponseRedirect from django.shortcuts import render_to_response from django.template import RequestContext from django.contrib.contenttypes.models import ContentType from geotagging.models import Point def add_edit_point(request, content_type_id, object_id, template=Non...
from django.http import HttpResponseRedirect from django.shortcuts import render_to_response from django.template import RequestContext from django.contrib.contenttypes.models import ContentType from django.core.exceptions import ObjectDoesNotExist from geotagging.models import Point def add_edit_point(request, cont...
Fix a bug when you try to add a geo tag to an object that does not have already one
Fix a bug when you try to add a geo tag to an object that does not have already one
Python
bsd-3-clause
uclastudentmedia/django-geotagging,uclastudentmedia/django-geotagging,uclastudentmedia/django-geotagging
ef11a6388dabd07afb3d11f7b097226e68fdf243
project/estimation/models.py
project/estimation/models.py
from .. import db class Question(db.Model): id = db.Column(db.Integer, primary_key=True) text = db.Column(db.String(240), unique=True, index=True) answer = db.Column(db.Numeric)
from .. import db class Question(db.Model): id = db.Column(db.Integer, primary_key=True) text = db.Column(db.String(240), unique=True, index=True) answer = db.Column(db.Numeric) class Estimate(db.Model): id = db.Column(db.Integer, primary_key=True) user_id = db.Column(db.Integer, db.ForeignKey('us...
Add model to keep track of users' estimates.
Add model to keep track of users' estimates.
Python
mit
rahimnathwani/measure-anything
224269d0794d1037213b429c0fcb7c5953129230
aldryn_config.py
aldryn_config.py
# -*- coding: utf-8 -*- from aldryn_client import forms class Form(forms.BaseForm): def to_settings(self, cleaned_data, settings_dict): settings_dict['MIDDLEWARE_CLASSES'].append( 'country_segment.middleware.ResolveCountryCodeMiddleware') return settings_dict
# -*- coding: utf-8 -*- from aldryn_client import forms class Form(forms.BaseForm): def to_settings(self, cleaned_data, settings_dict): country_mw = 'country_segment.middleware.ResolveCountryCodeMiddleware' if country_mw not in settings_dict['MIDDLEWARE_CLASSES']: for position, mw in enumerate(s...
Put the middleware near the top (again).
Put the middleware near the top (again).
Python
bsd-3-clause
aldryn/aldryn-country-segment
be7c5fc964ce3386df2bf246f12838e4ba2a2cb6
saleor/core/utils/filters.py
saleor/core/utils/filters.py
from __future__ import unicode_literals def get_sort_by_choices(filter): return [(choice[0], choice[1].lower()) for choice in filter.filters['sort_by'].field.choices[1::2]] def get_now_sorted_by(filter, fields): sort_by = filter.form.cleaned_data.get('sort_by') if sort_by: sort_by = ...
from __future__ import unicode_literals def get_sort_by_choices(filter): return [(choice[0], choice[1].lower()) for choice in filter.filters['sort_by'].field.choices[1::2]] def get_now_sorted_by(filter, fields, default_sort='name'): sort_by = filter.form.cleaned_data.get('sort_by') if sort_b...
Add default_sort param to get_now_sorting_by
Add default_sort param to get_now_sorting_by
Python
bsd-3-clause
UITools/saleor,UITools/saleor,UITools/saleor,maferelo/saleor,mociepka/saleor,maferelo/saleor,mociepka/saleor,mociepka/saleor,UITools/saleor,maferelo/saleor,UITools/saleor
2ad47f6ce00246cbf54639438d9279b8a7fa9b29
python/tests/t_envoy_logs.py
python/tests/t_envoy_logs.py
import pytest, re from kat.utils import ShellCommand from abstract_tests import AmbassadorTest, ServiceType, HTTP access_log_entry_regex = re.compile('^ACCESS \\[.*?\\] \\\"GET \\/ambassador') class EnvoyLogPathTest(AmbassadorTest): target: ServiceType log_path: str def init(self): self.target ...
import pytest, re from kat.utils import ShellCommand from abstract_tests import AmbassadorTest, ServiceType, HTTP access_log_entry_regex = re.compile('^MY_REQUEST 200 .*') class EnvoyLogTest(AmbassadorTest): target: ServiceType log_path: str def init(self): self.target = HTTP() self.log...
Test for Envoy logs format
Test for Envoy logs format Signed-off-by: Alvaro Saurin <5b2d0c210c4a9fd6aeaf2eaedf8273be993c90c2@datawire.io>
Python
apache-2.0
datawire/ambassador,datawire/ambassador,datawire/ambassador,datawire/ambassador,datawire/ambassador
7adfe4822bf75d1df2dc2a566b3b26c9fd494431
rest_framework_jwt/compat.py
rest_framework_jwt/compat.py
from distutils.version import StrictVersion import rest_framework from rest_framework import serializers from django.forms import widgets if StrictVersion(rest_framework.VERSION) < StrictVersion('3.0.0'): class Serializer(serializers.Serializer): pass class PasswordField(serializers.CharField): ...
from distutils.version import StrictVersion import rest_framework from rest_framework import serializers from django.forms import widgets DRF_VERSION_INFO = StrictVersion(rest_framework.VERSION).version DRF2 = DRF_VERSION_INFO[0] == 2 DRF3 = DRF_VERSION_INFO[0] == 3 if DRF2: class Serializer(serializers.Serial...
Use request.data in DRF >= 3
Use request.data in DRF >= 3
Python
mit
orf/django-rest-framework-jwt,shanemgrey/django-rest-framework-jwt,GetBlimp/django-rest-framework-jwt,blaklites/django-rest-framework-jwt,plentific/django-rest-framework-jwt,ArabellaTech/django-rest-framework-jwt
b8139440a2509d5b197889664f9ec34be9296210
form_designer/contrib/cms_plugins/form_designer_form/cms_plugins.py
form_designer/contrib/cms_plugins/form_designer_form/cms_plugins.py
from form_designer.contrib.cms_plugins.form_designer_form.models import CMSFormDefinition from form_designer.views import process_form from form_designer import settings from cms.plugin_base import CMSPluginBase from cms.plugin_pool import plugin_pool from django.utils.translation import ugettext as _ class FormDes...
from form_designer.contrib.cms_plugins.form_designer_form.models import CMSFormDefinition from form_designer.views import process_form from form_designer import settings from cms.plugin_base import CMSPluginBase from cms.plugin_pool import plugin_pool from django.utils.translation import ugettext as _ class FormDes...
Disable caching so CSRF tokens are not cached.
Disable caching so CSRF tokens are not cached.
Python
bsd-3-clause
USGM/django-form-designer,USGM/django-form-designer
21f209b618850d15734c476bd3c1b359b9a7426e
infosystem/queue.py
infosystem/queue.py
import flask from pika import BlockingConnection, PlainCredentials, ConnectionParameters class RabbitMQ: def __init__(self): self.url = flask.current_app.config['ORMENU_QUEUE_URL'] self.port = flask.current_app.config['ORMENU_QUEUE_PORT'] self.virtual_host = \ flask.current_ap...
import flask from pika import BlockingConnection, PlainCredentials, ConnectionParameters class RabbitMQ: def __init__(self): self.url = flask.current_app.config['INFOSYSTEM_QUEUE_URL'] self.port = flask.current_app.config['INFOSYSTEM_QUEUE_PORT'] self.virtual_host = \ flask.cu...
Use INFOSYSTEM enviroment for Queue
Use INFOSYSTEM enviroment for Queue
Python
apache-2.0
samueldmq/infosystem
305ba7ee3fff41a7d866968c5332394301c0e83f
digi/wagtail_hooks.py
digi/wagtail_hooks.py
from wagtail.contrib.modeladmin.options import \ ModelAdmin, ModelAdminGroup, modeladmin_register from .models import Indicator, FooterLinkSection class IndicatorAdmin(ModelAdmin): model = Indicator menu_icon = 'user' class FooterLinkSectionAdmin(ModelAdmin): model = FooterLinkSection menu_icon ...
from wagtail.contrib.modeladmin.options import \ ModelAdmin, ModelAdminGroup, modeladmin_register from .models import Indicator, FooterLinkSection from django.utils.html import format_html from wagtail.wagtailcore import hooks class IndicatorAdmin(ModelAdmin): model = Indicator menu_icon = 'user' class ...
Enable HTML source editing in the content editor
Enable HTML source editing in the content editor
Python
mit
terotic/digihel,City-of-Helsinki/digihel,terotic/digihel,City-of-Helsinki/digihel,City-of-Helsinki/digihel,terotic/digihel,City-of-Helsinki/digihel
60497ba61c80863cd0414e39a9cd12b42b519897
chainer/training/extensions/value_observation.py
chainer/training/extensions/value_observation.py
from chainer.training import extension import time def observe_value(key, target_func): """Returns a trainer extension to continuously record a value. Args: key (str): Key of observation to record. target_func (function): Function that returns the value to record. It must take one...
import time from chainer.training import extension def observe_value(key, target_func): """Returns a trainer extension to continuously record a value. Args: key (str): Key of observation to record. target_func (function): Function that returns the value to record. It must take on...
Split system import and project import
Split system import and project import
Python
mit
cupy/cupy,chainer/chainer,keisuke-umezawa/chainer,wkentaro/chainer,okuta/chainer,ktnyt/chainer,wkentaro/chainer,jnishi/chainer,tkerola/chainer,keisuke-umezawa/chainer,jnishi/chainer,niboshi/chainer,delta2323/chainer,keisuke-umezawa/chainer,ktnyt/chainer,chainer/chainer,ysekky/chainer,chainer/chainer,keisuke-umezawa/cha...
14ea472acfce8b5317a8c8c970db901501ea34c0
_tests/macro_testing/runner.py
_tests/macro_testing/runner.py
# -*- coding: utf-8 -*- import os, os.path import sys import unittest from macrotest import JSONSpecMacroTestCaseFactory def JSONTestCaseLoader(tests_path, recursive=False): """ Load JSON specifications for Jinja2 macro test cases from the given path and returns the resulting test classes. This fun...
# -*- coding: utf-8 -*- import os, os.path import sys import unittest from macrotest import JSONSpecMacroTestCaseFactory def JSONTestCaseLoader(tests_path, recursive=False): """ Load JSON specifications for Jinja2 macro test cases from the given path and returns the resulting test classes. This fun...
Make the paths not relative, so tests can be run from anywhere.
Make the paths not relative, so tests can be run from anywhere.
Python
cc0-1.0
kave/cfgov-refresh,kave/cfgov-refresh,kave/cfgov-refresh,kave/cfgov-refresh
90699f4fa6c1ce2b02e81a8fef9bfafd2175fa7f
kmapper/__init__.py
kmapper/__init__.py
from .kmapper import KeplerMapper from .kmapper import cluster from .kmapper import Cover from .kmapper import GraphNerve
from .kmapper import KeplerMapper from .kmapper import cluster from .cover import Cover from .nerve import GraphNerve import pkg_resources __version__ = pkg_resources.get_distribution('kmapper').version
Add __version__ variable to package
Add __version__ variable to package
Python
mit
MLWave/kepler-mapper,MLWave/kepler-mapper,MLWave/kepler-mapper
884852eeb2dec07dccefc26595f097ec9ae8532b
forum/forms.py
forum/forms.py
from django.forms import ModelForm,Textarea from .models import Post class PostForm(ModelForm): class Meta: model = Post fields = ('subject','body') widgets = { 'body': Textarea( attrs={ 'data-provide':'markdown', ...
from django.forms import ModelForm,Textarea,TextInput from .models import Post class PostForm(ModelForm): class Meta: model = Post fields = ('subject','body') widgets = { 'subject': TextInput(attrs={'autofocus':'autofocus'}), 'body': Textarea( ...
Add autofocus to subject field
Add autofocus to subject field
Python
mit
Kromey/fbxnano,Kromey/akwriters,Kromey/fbxnano,Kromey/akwriters,Kromey/fbxnano,Kromey/fbxnano,Kromey/akwriters,Kromey/akwriters
1b7634e3a98919df5f2f4d54c57bb72dfbf308df
py3-test/tests.py
py3-test/tests.py
# -*- coding: utf-8 -*- import nose.tools as nt from asyncio import get_event_loop from asyncio import sleep as async_sleep from pyee import EventEmitter def test_async_emit(): """Test that event_emitters can handle wrapping coroutines """ ee = EventEmitter() loop = get_event_loop() class Sense...
# -*- coding: utf-8 -*- import nose.tools as nt from asyncio import Future, gather, get_event_loop, sleep from pyee import EventEmitter def test_async_emit(): """Test that event_emitters can handle wrapping coroutines """ loop = get_event_loop() ee = EventEmitter(loop=loop) future = Future() ...
Rewrite asyncio test to use futures
Rewrite asyncio test to use futures
Python
mit
jfhbrook/pyee
a8bb719061a68b5d322868768203476c4ee1e9b9
gnocchi/cli.py
gnocchi/cli.py
# Copyright (c) 2013 Mirantis Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writ...
# Copyright (c) 2013 Mirantis Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writ...
Connect to database before upgrading it
Connect to database before upgrading it This change ensure we are connected to the database before we upgrade it. Change-Id: Ia0be33892a99897ff294d004f4d935f3753e6200
Python
apache-2.0
idegtiarov/gnocchi-rep,leandroreox/gnocchi,sileht/gnocchi,idegtiarov/gnocchi-rep,gnocchixyz/gnocchi,sileht/gnocchi,idegtiarov/gnocchi-rep,gnocchixyz/gnocchi,leandroreox/gnocchi
82740c7956a2bae0baceedd658b9ad9352254ad0
nlppln/wfgenerator.py
nlppln/wfgenerator.py
from scriptcwl import WorkflowGenerator as WFGenerator from .utils import CWL_PATH class WorkflowGenerator(WFGenerator): def __init__(self, working_dir=None, copy_steps=True): WFGenerator.__init__(self, steps_dir=CWL_PATH, working_dir=working_dir, copy_steps=copy_steps) ...
from scriptcwl import WorkflowGenerator as WFGenerator from .utils import CWL_PATH class WorkflowGenerator(WFGenerator): def __init__(self, working_dir=None): WFGenerator.__init__(self, steps_dir=CWL_PATH, working_dir=working_dir) def save(self, fname, validate=True, wd=True, inline=False, relative=...
Update to use newest (unreleased) scriptcwl options
Update to use newest (unreleased) scriptcwl options
Python
apache-2.0
WhatWorksWhenForWhom/nlppln,WhatWorksWhenForWhom/nlppln,WhatWorksWhenForWhom/nlppln
b728470c61fbd742052e5befb4c27adbacef1a7e
pinax_theme_bootstrap/templatetags/pinax_theme_bootstrap_tags.py
pinax_theme_bootstrap/templatetags/pinax_theme_bootstrap_tags.py
from django import template from django.contrib.messages.utils import get_level_tags LEVEL_TAGS = get_level_tags() register = template.Library() @register.simple_tag() def get_message_tags(message): """ Returns tags for a message """ level_name = LEVEL_TAGS[message.level] if level_name == u"err...
from django import template from django.contrib.messages.utils import get_level_tags LEVEL_TAGS = get_level_tags() register = template.Library() @register.simple_tag() def get_message_tags(message): """ Returns the message's level_tag prefixed with Bootstrap's "alert-" prefix along with any tags includ...
Use level_tag to be consistent with Django >= 1.7
Use level_tag to be consistent with Django >= 1.7
Python
mit
grahamu/pinax-theme-bootstrap,jacobwegner/pinax-theme-bootstrap,foraliving/foraliving,jacobwegner/pinax-theme-bootstrap,druss16/danslist,druss16/danslist,foraliving/foraliving,foraliving/foraliving,grahamu/pinax-theme-bootstrap,jacobwegner/pinax-theme-bootstrap,grahamu/pinax-theme-bootstrap,druss16/danslist
fec7885d2632b887002f0071f4898faf52dd927c
chainerx/__init__.py
chainerx/__init__.py
import sys if sys.version_info[0] < 3: _available = False else: try: from chainerx import _core _available = True except Exception: _available = False if _available: from numpy import dtype, bool_, int8, int16, int32, int64, uint8, float32, float64 # NOQA from chainerx....
import sys if sys.version_info[0] < 3: _available = False else: try: from chainerx import _core _available = True except Exception: _available = False if _available: from numpy import dtype, bool_, int8, int16, int32, int64, uint8, float32, float64 # NOQA from chainerx....
Raise an error on dummy class init
Raise an error on dummy class init
Python
mit
okuta/chainer,jnishi/chainer,chainer/chainer,ktnyt/chainer,ktnyt/chainer,okuta/chainer,hvy/chainer,niboshi/chainer,ktnyt/chainer,chainer/chainer,ktnyt/chainer,hvy/chainer,wkentaro/chainer,jnishi/chainer,jnishi/chainer,okuta/chainer,wkentaro/chainer,keisuke-umezawa/chainer,niboshi/chainer,chainer/chainer,keisuke-umezawa...
f16c8f696a282da6c04de6b7530f1d0316eda88b
providers/edu/harvarddataverse/normalizer.py
providers/edu/harvarddataverse/normalizer.py
import arrow import dateparser from share.normalize import * class Person(Parser): given_name = ParseName(ctx).first family_name = ParseName(ctx).last additional_name = ParseName(ctx).middle suffix = ParseName(ctx).suffix class Contributor(Parser): person = Delegate(Person, ctx) cited_name...
import arrow import dateparser from share.normalize import * class Person(Parser): given_name = ParseName(ctx).first family_name = ParseName(ctx).last additional_name = ParseName(ctx).middle suffix = ParseName(ctx).suffix class Contributor(Parser): person = Delegate(Person, ctx) cited_name...
Handle missing fields in dataverse
Handle missing fields in dataverse
Python
apache-2.0
CenterForOpenScience/SHARE,laurenbarker/SHARE,aaxelb/SHARE,aaxelb/SHARE,laurenbarker/SHARE,zamattiac/SHARE,zamattiac/SHARE,CenterForOpenScience/SHARE,laurenbarker/SHARE,CenterForOpenScience/SHARE,zamattiac/SHARE,aaxelb/SHARE
3327c204f34a725a2d070beb24a7a5a66d414930
migrations/versions/538eeb160af6_.py
migrations/versions/538eeb160af6_.py
"""empty message Revision ID: 538eeb160af6 Revises: 1727fb4309d8 Create Date: 2015-09-17 04:22:21.262285 """ # revision identifiers, used by Alembic. revision = '538eeb160af6' down_revision = '1727fb4309d8' from alembic import op import sqlalchemy as sa def upgrade(): ### commands auto generated by Alembic - ...
"""empty message Revision ID: 538eeb160af6 Revises: 1727fb4309d8 Create Date: 2015-09-17 04:22:21.262285 """ # revision identifiers, used by Alembic. revision = '538eeb160af6' down_revision = '6b9d673d8e30' from alembic import op import sqlalchemy as sa def upgrade(): ### commands auto generated by Alembic - ...
Update alembic order for merging
Update alembic order for merging
Python
apache-2.0
bunjiboys/security_monkey,stackArmor/security_monkey,markofu/security_monkey,bunjiboys/security_monkey,bunjiboys/security_monkey,markofu/security_monkey,markofu/security_monkey,Netflix/security_monkey,stackArmor/security_monkey,Netflix/security_monkey,Netflix/security_monkey,stackArmor/security_monkey,Netflix/security_...
d2d822a9fb60bbc8ded7f9e3c70d91cf25f794b2
src/volunteers/models.py
src/volunteers/models.py
from django.db import models from django.utils.translation import ugettext_lazy as _ from django.core.validators import MinValueValidator class Volunteer(models.Model): first_name = models.CharField(_('First name'), max_length=100) last_name = models.CharField(_('Last name'), max_length=100) age = models....
from django.db import models from django.utils.translation import ugettext_lazy as _ from django.core.validators import MinValueValidator class Volunteer(models.Model): first_name = models.CharField(_('First name'), max_length=100) last_name = models.CharField(_('Last name'), max_length=100) age = models....
Add group name to volunteer string representation
Add group name to volunteer string representation
Python
mit
mrts/foodbank-campaign,mrts/foodbank-campaign,mrts/foodbank-campaign,mrts/foodbank-campaign
e1111ad6e8802b3c90df55e05eb695d6db9005e4
import_script/create_users.py
import_script/create_users.py
#!/usr/bin/python import django.contrib.auth.models as auth_models import django.contrib.contenttypes as contenttypes def main(): # Read only user: # auth_models.User.objects.create_user('cube', 'toolkit_admin_readonly@localhost', '***REMOVED***') # Read/write user: user_rw = auth_models.User.objects...
#!/usr/bin/python import django.contrib.auth.models as auth_models import django.contrib.contenttypes as contenttypes def get_password(): print "*" * 80 password = raw_input("Please enter string to use as admin password: ") check_password = None while check_password != password: print ...
Remove cube credentials from import script
Remove cube credentials from import script
Python
agpl-3.0
BenMotz/cubetoolkit,BenMotz/cubetoolkit,BenMotz/cubetoolkit,BenMotz/cubetoolkit
c89abd6a285225313c91ba03c0fd8ab2cfed399d
setup.py
setup.py
#!/usr/bin/env python import os import urllib import zipfile script_path = os.path.dirname(os.path.realpath(__file__)) packer_archive_path = script_path + "/packer.zip" bin_path = script_path + "/bin" if not os.path.isfile(bin_path + "/packer"): if not os.path.exists(bin_path): os.makedirs(bin_path) ...
#!/usr/bin/env python import os import urllib import zipfile script_path = os.path.dirname(os.path.realpath(__file__)) packer_archive_path = script_path + "/packer.zip" bin_path = script_path + "/bin" if not os.path.isfile(bin_path + "/packer"): if not os.path.exists(bin_path): os.makedirs(bin_path) ...
Fix false positive octal syntax warning
Fix false positive octal syntax warning
Python
unlicense
dharmab/centos-vagrant
3d888afa88326c97246947141c357509c2f72bbc
setup.py
setup.py
from distutils.core import setup setup( name='firebase-token-generator', version='1.2', author='Greg Soltis', author_email='greg@firebase.com', py_modules=['firebase_token_generator'], license='LICENSE', url='https://github.com/firebase/firebase-token-generator-python', description='A u...
from distutils.core import setup setup( name='firebase-token-generator', version='1.3', author='Greg Soltis', author_email='greg@firebase.com', zip_safe=False, py_modules=['firebase_token_generator'], license='LICENSE', url='https://github.com/firebase/firebase-token-generator-python', ...
Set zip_safe=False. Bump version to 1.3.
Set zip_safe=False. Bump version to 1.3.
Python
mit
googlearchive/firebase-token-generator-python
ee2d27eca45768a07a562405cf4431cb8d2b09bf
setup.py
setup.py
from distutils.core import setup setup(name='pyresttest', version='0.1', description='Python Rest Testing', maintainer='Naveen Malik', maintainer_email='jewzaam@gmail.com', url='https://github.com/svanoort/pyresttest', py_modules=['resttest','pycurl_benchmark','test_resttest'], license='Apa...
from distutils.core import setup setup(name='pyresttest', version='0.1', description='Python Rest Testing', maintainer='Sam Van Oort', maintainer_email='acetonespam@gmail.com', url='https://github.com/svanoort/pyresttest', py_modules=['resttest','test_resttest'], license='Apache License, Ve...
Set maintainer and add dependencies to distutils config
Set maintainer and add dependencies to distutils config
Python
apache-2.0
sunyanhui/pyresttest,satish-suradkar/pyresttest,suvarnaraju/pyresttest,wirewit/pyresttest,netjunki/pyresttest,MorrisJobke/pyresttest,wirewit/pyresttest,suvarnaraju/pyresttest,svanoort/pyresttest,alazaro/pyresttest,sunyanhui/pyresttest,TimYi/pyresttest,MorrisJobke/pyresttest,holdenweb/pyresttest,TimYi/pyresttest,alazaro...
8fea58292e41352b0b58947f4182dd32ff4f225d
opps/fields/models.py
opps/fields/models.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from django.db import models from django.utils.translation import ugettext_lazy as _ from opps.boxes.models import OPPS_APPS FIELD_TYPE = ( ('checkbox', _('CheckBox')), ('radio', _('Radio')), ('text', _('Text')), ('textarea', _('TextArea')), ) class Fie...
#!/usr/bin/env python # -*- coding: utf-8 -*- from django.db import models from django.utils.translation import ugettext_lazy as _ from opps.boxes.models import OPPS_APPS FIELD_TYPE = ( ('checkbox', _('CheckBox')), ('radio', _('Radio')), ('text', _('Text')), ('textarea', _('TextArea')), ) class Fie...
Add new model option to add field options if exist (radio/checkbox)
Add new model option to add field options if exist (radio/checkbox)
Python
mit
williamroot/opps,jeanmask/opps,jeanmask/opps,williamroot/opps,YACOWS/opps,williamroot/opps,opps/opps,opps/opps,YACOWS/opps,jeanmask/opps,jeanmask/opps,YACOWS/opps,opps/opps,williamroot/opps,YACOWS/opps,opps/opps
6f83fb7dd071786dc01a015addbdb541e7eaf7db
meinberlin/apps/documents/migrations/0002_rename_document_to_chapter.py
meinberlin/apps/documents/migrations/0002_rename_document_to_chapter.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations from django.db import models class Migration(migrations.Migration): dependencies = [ ('meinberlin_documents', '0001_initial'), ] operations = [ migrations.RenameModel( old_name='...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations from django.db import models class Migration(migrations.Migration): atomic=False dependencies = [ ('meinberlin_documents', '0001_initial'), ] operations = [ migrations.RenameModel( ...
Work around a migration issue in sqlite
apps/documents: Work around a migration issue in sqlite
Python
agpl-3.0
liqd/a4-meinberlin,liqd/a4-meinberlin,liqd/a4-meinberlin,liqd/a4-meinberlin
3d2f19ff097cf144efd9135c52e4d584193f9ddb
tohu/v7/custom_generator/tohu_items_class.py
tohu/v7/custom_generator/tohu_items_class.py
import attr __all__ = ["make_tohu_items_class"] def make_tohu_items_class(clsname, field_names): """ Parameters ---------- clsname: string Name of the class to be created. field_names: list of strings Names of the field attributes of the class to be created. """ item_cls ...
import attr __all__ = ["make_tohu_items_class"] def make_tohu_items_class(clsname, field_names): """ Parameters ---------- clsname: string Name of the class to be created. field_names: list of strings Names of the field attributes of the class to be created. """ item_cls ...
Add attribute 'is_unset' so that the interface is consistent with MissingTohuItemsCls
Add attribute 'is_unset' so that the interface is consistent with MissingTohuItemsCls
Python
mit
maxalbert/tohu
445b80562e038bc3749930d44e00eda55edaa180
ci_scripts/buildLinuxWheels.py
ci_scripts/buildLinuxWheels.py
from subprocess import call, check_output import sys import os isPython3 = sys.version_info.major == 3 # https://stackoverflow.com/a/3357357 command = 'git log --format=%B -n 1'.split() out = check_output(command) if b'build wheels' not in out.lower() or not isPython3: exit(0) path = os.path.abspath(argv[1]) ca...
from subprocess import call, check_output import sys import os isPython3 = sys.version_info.major == 3 # https://stackoverflow.com/a/3357357 command = 'git log --format=%B -n 1'.split() out = check_output(command) if b'build wheels' not in out.lower() or not isPython3: exit(0) path = os.path.abspath(sys.argv[1]...
Fix build wheels and upload 4.
Fix build wheels and upload 4.
Python
bsd-3-clause
jr-garcia/AssimpCy,jr-garcia/AssimpCy
a10407bf4d9dd404d734985717aa7bcebfa0981d
api/digital_ocean.py
api/digital_ocean.py
""" @fileoverview Digital Ocean API @author David Parlevliet @version 20130315 @preserve Copyright 2013 David Parlevliet. Digital Ocean API ================= Class to get the server details via the Digital Ocean API. """ import urllib2 import json class Api(): group_name = "Digital Ocean" client_key = None ap...
""" @fileoverview Digital Ocean API @author David Parlevliet @version 20130315 @preserve Copyright 2013 David Parlevliet. Digital Ocean API ================= Class to get the server details via the Digital Ocean API. """ import urllib2 import json class Api(): group_name = "Digital Ocean" client_key = None ap...
Return a helpful exception if API is uncontactable
Return a helpful exception if API is uncontactable
Python
mit
dparlevliet/elastic-firewall,dparlevliet/elastic-firewall,dparlevliet/elastic-firewall
7ff6c9d85eef03c225b511f39bbb07796b47659f
datapipe/history.py
datapipe/history.py
class History: def __init__(self): self.conn = sqlite3.connect('.history.db')
import sqlite3 class History: def __init__(self, path): self.conn = sqlite3.connect(path)
Make database filepath configurable on History
Make database filepath configurable on History
Python
mit
ibab/datapipe
fd4539942dafe622d3f7a7d183db3d69f95a00c4
shop/urls/cart.py
shop/urls/cart.py
from django.conf.urls.defaults import url, patterns from shop.views.cart import CartDetails, CartItemDetail urlpatterns = patterns('', url(r'^delete/$', CartDetails.as_view(action='delete'), # DELETE name='cart_delete'), url('^item/$', CartDetails.as_view(action='post'), # POST name='cart_i...
from django.conf.urls.defaults import url, patterns from shop.views.cart import CartDetails, CartItemDetail urlpatterns = patterns('', url(r'^delete/$', CartDetails.as_view(action='delete'), # DELETE name='cart_delete'), url('^item/$', CartDetails.as_view(action='post'), # POST name='cart_i...
Make sure that ID will not match the first CartItems rule EVERY time ("//" was in regex).
Make sure that ID will not match the first CartItems rule EVERY time ("//" was in regex).
Python
bsd-3-clause
schacki/django-shop,khchine5/django-shop,khchine5/django-shop,dwx9/test,febsn/django-shop,DavideyLee/django-shop,awesto/django-shop,jrief/django-shop,dwx9/test,thenewguy/django-shop,thenewguy/django-shop,bmihelac/django-shop,pjdelport/django-shop,creimers/django-shop,creimers/django-shop,jrief/django-shop,bmihelac/djan...
10948cd88d51383e13af0a116703984752092c6a
jenkinsapi_tests/systests/test_jenkins_matrix.py
jenkinsapi_tests/systests/test_jenkins_matrix.py
''' System tests for `jenkinsapi.jenkins` module. ''' import re import time import unittest from jenkinsapi_tests.systests.base import BaseSystemTest from jenkinsapi_tests.systests.job_configs import MATRIX_JOB from jenkinsapi_tests.test_utils.random_strings import random_string class TestMatrixJob(BaseSystemTest): ...
''' System tests for `jenkinsapi.jenkins` module. ''' import re import time import unittest from jenkinsapi_tests.systests.base import BaseSystemTest from jenkinsapi_tests.systests.job_configs import MATRIX_JOB from jenkinsapi_tests.test_utils.random_strings import random_string class TestMatrixJob(BaseSystemTest): ...
Tidy up this test - still quite bad & useless.
Tidy up this test - still quite bad & useless.
Python
mit
imsardine/jenkinsapi,salimfadhley/jenkinsapi,JohnLZeller/jenkinsapi,JohnLZeller/jenkinsapi,aerickson/jenkinsapi,domenkozar/jenkinsapi,zaro0508/jenkinsapi,imsardine/jenkinsapi,zaro0508/jenkinsapi,jduan/jenkinsapi,mistermocha/jenkinsapi,domenkozar/jenkinsapi,salimfadhley/jenkinsapi,zaro0508/jenkinsapi,mistermocha/jenkins...
238ba8cec34ec02dc521f25ef1ada6e230194c32
kitsune/kbadge/migrations/0002_auto_20181023_1319.py
kitsune/kbadge/migrations/0002_auto_20181023_1319.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('kbadge', '0001_initial'), ] operations = [ migrations.RunSQL( "UPDATE badger_badge SET image = CONCAT('uploads/', image)...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('kbadge', '0001_initial'), ] operations = [ migrations.RunSQL( "UPDATE badger_badge SET image = CONCAT('uploads/', image)...
Add WHERE clause to SQL data migration.
Add WHERE clause to SQL data migration.
Python
bsd-3-clause
mozilla/kitsune,anushbmx/kitsune,anushbmx/kitsune,anushbmx/kitsune,mozilla/kitsune,mozilla/kitsune,mozilla/kitsune,anushbmx/kitsune
4651d3b5666fe3ddf3bd92b31ee6ffe4a72ce94e
core/api/__init__.py
core/api/__init__.py
import os from flask import Flask, jsonify from flask_pymongo import PyMongo, BSONObjectIdConverter from werkzeug.exceptions import HTTPException, default_exceptions from core.api import settings def create_app(environment=None): app = Flask('veritrans') app.url_map.converters['ObjectId'] = BSONObjectIdConv...
import os from flask import Flask, jsonify from flask_pymongo import PyMongo, BSONObjectIdConverter from werkzeug.exceptions import HTTPException, default_exceptions from core.api import settings def create_app(environment=None): app = Flask('veritrans') app.url_map.converters['ObjectId'] = BSONObjectIdConv...
Use Production config unless specified
Use Production config unless specified
Python
mit
onyb/veritrans-payment-portals
ced218643784838d68961a926cc0dd18c3a3f01f
skald/geometry.py
skald/geometry.py
# -*- coding: utf-8 -*- from collections import namedtuple Size = namedtuple("Size", ["width", "height"]) Rectangle = namedtuple("Rectangle", ["x0", "y0", "x1", "y1"]) class Point(namedtuple("Point", ["x", "y"])): """Point in a two-dimensional space. Named tuple implementation that allows for addition and su...
# -*- coding: utf-8 -*- from collections import namedtuple Size = namedtuple("Size", ["width", "height"]) class Rectangle(namedtuple("Rectangle", ["x0", "y0", "x1", "y1"])): def __contains__(self, other): """Check if this rectangle and `other` overlaps eachother. Essentially this is a bit of a ha...
Add intersection test for rectangles
Add intersection test for rectangles
Python
mit
bjornarg/skald,bjornarg/skald
8f03f51c89aeea44943f9cb0b39330e676ae0089
utils.py
utils.py
import vx from contextlib import contextmanager from functools import partial import sys from io import StringIO def _expose(f=None, name=None): if f is None: return partial(_expose, name=name) if name is None: name = f.__name__.lstrip('_') if getattr(vx, name, None) is not None: ...
import vx from contextlib import contextmanager from functools import partial import sys from io import StringIO def _expose(f=None, name=None): if f is None: return partial(_expose, name=name) if name is None: name = f.__name__.lstrip('_') if getattr(vx, name, None) is not None: ...
Change repeat command to return a list of the results of the repeated commands
Change repeat command to return a list of the results of the repeated commands
Python
mit
philipdexter/vx,philipdexter/vx
822e6123cc598b4f6a0eafedfb2f0d0cbfba5f37
currencies/migrations/0003_auto_20151216_1906.py
currencies/migrations/0003_auto_20151216_1906.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations from extra_countries.models import ExtraCountry def add_currencies_with_countries(apps, schema_editor): # We can't import the model directly as it may be a newer # version than this migration expects. We use the...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations from extra_countries.models import ExtraCountry def add_currencies_with_countries(apps, schema_editor): # We can't import the model directly as it may be a newer # version than this migration expects. We use the...
Fix currencies seeding, so it won't have empty currencies
Fix currencies seeding, so it won't have empty currencies
Python
mit
openspending/cosmopolitan,kiote/cosmopolitan
041b271baa7ae0bbd20c30ac4f70b42fda267e93
mozillians/groups/__init__.py
mozillians/groups/__init__.py
from django.apps import AppConfig CIS_GROUPS = [ 'cis_whitelist', 'nda' ] default_app_config = 'mozillians.groups.GroupConfig' class GroupConfig(AppConfig): name = 'mozillians.groups'
from django.apps import AppConfig CIS_GROUPS = [ 'cis_whitelist', 'nda', 'open-innovation-reps-council' ] default_app_config = 'mozillians.groups.GroupConfig' class GroupConfig(AppConfig): name = 'mozillians.groups'
Add a group in the whitelist.
Add a group in the whitelist.
Python
bsd-3-clause
mozilla/mozillians,akatsoulas/mozillians,mozilla/mozillians,johngian/mozillians,mozilla/mozillians,mozilla/mozillians,akatsoulas/mozillians,akatsoulas/mozillians,johngian/mozillians,johngian/mozillians,johngian/mozillians,akatsoulas/mozillians
199c9bae8e2ad42ee1c8699c678dd56d6074b2de
main/models.py
main/models.py
from django.db import models from django.contrib.auth.models import User import string, random from django import forms # Create your models here. def _generate_default_hashtag(): return "".join(random.choice(string.lowercase) for i in range(3)) class Wall(models.Model): hashtag = models.CharField(max_length=20...
from django.db import models from django.contrib.auth.models import User import string, random from django import forms # Create your models here. def _generate_default_hashtag(): return "".join(random.choice(string.lowercase) for i in range(3)) class Wall(models.Model): hashtag = models.CharField(max_length=20...
Return sms_keyword as wall name
Return sms_keyword as wall name
Python
mit
Aaron1011/texting_wall
b6ec3ba9efae7b6b291391b0333e80f2e9fc6fa0
src/waldur_mastermind/invoices/migrations/0053_invoiceitem_uuid.py
src/waldur_mastermind/invoices/migrations/0053_invoiceitem_uuid.py
import uuid from django.db import migrations import waldur_core.core.fields def gen_uuid(apps, schema_editor): InvoiceItem = apps.get_model('invoices', 'InvoiceItem') for row in InvoiceItem.objects.all(): row.uuid = uuid.uuid4().hex row.save(update_fields=['uuid']) class Migration(migratio...
import uuid from django.db import migrations, models import waldur_core.core.fields def gen_uuid(apps, schema_editor): InvoiceItem = apps.get_model('invoices', 'InvoiceItem') for row in InvoiceItem.objects.all(): row.uuid = uuid.uuid4().hex row.save(update_fields=['uuid']) class Migration(...
Fix database migration script for UUID field in invoice item model.
Fix database migration script for UUID field in invoice item model.
Python
mit
opennode/waldur-mastermind,opennode/waldur-mastermind,opennode/waldur-mastermind,opennode/waldur-mastermind
9b19d366c7e1cf41ffc6af4eaed789995ddc5cc2
byceps/blueprints/core_admin/views.py
byceps/blueprints/core_admin/views.py
""" byceps.blueprints.core_admin.views ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2018 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from ...services.brand import service as brand_service from ...util.framework.blueprint import create_blueprint from ..authorization.registry impor...
""" byceps.blueprints.core_admin.views ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2018 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from ...services.brand import service as brand_service from ...util.framework.blueprint import create_blueprint from ..authorization.registry impor...
Generalize name of function to inject admin template variables
Generalize name of function to inject admin template variables
Python
bsd-3-clause
homeworkprod/byceps,m-ober/byceps,m-ober/byceps,homeworkprod/byceps,homeworkprod/byceps,m-ober/byceps
6ac683ca1905fbf17dd63c1264609e770439fa7f
test/integration/targets/module_utils/library/test_env_override.py
test/integration/targets/module_utils/library/test_env_override.py
#!/usr/bin/python from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.json_utils import data from ansible.module_utils.mork import data as mork_data results = {"json_utils": data, "mork": mork_data} AnsibleModule(argument_spec=dict()).exit_json(**results)
#!/usr/bin/python # Most of these names are only available via PluginLoader so pylint doesn't # know they exist # pylint: disable=no-name-in-module from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.json_utils import data from ansible.module_utils.mork import data as mork_data results = {"j...
Disable pylint check for names existing in modules for test data
Disable pylint check for names existing in modules for test data This test data imports from modules which are only available via PluginLoader for this test case. So pylint doesn't know anything about them
Python
mit
thaim/ansible,thaim/ansible
7872abf00b24a504fccba576b13ecdd140e0135f
pybb/read_tracking.py
pybb/read_tracking.py
def update_read_tracking(topic, user): tracking = user.readtracking #if last_read > last_read - don't check topics if tracking.last_read and tracking.last_read > (topic.last_post.updated or topic.last_post.created): return if isinstance(track...
def update_read_tracking(topic, user): tracking = user.readtracking #if last_read > last_read - don't check topics if tracking.last_read and tracking.last_read > (topic.last_post.updated or topic.last_post.created): return if isinstance(track...
Fix bug in read tracking system
Fix bug in read tracking system
Python
bsd-2-clause
ttyS15/pybbm,onecue/pybbm,katsko/pybbm,katsko/pybbm,wengole/pybbm,wengole/pybbm,webu/pybbm,acamposruiz/quecoins,springmerchant/pybbm,NEERAJIITKGP/pybbm,webu/pybbm,concentricsky/pybbm,skolsuper/pybbm,hovel/pybbm,NEERAJIITKGP/pybbm,hovel/pybbm,webu/pybbm,artfinder/pybbm,onecue/pybbm,katsko/pybbm,ttyS15/pybbm,wengole/pybb...
346ffdb3e3836e2931f838a6dd929a325da0d5e6
tests/test_arithmetic.py
tests/test_arithmetic.py
from intervals import Interval class TestArithmeticOperators(object): def test_add_operator(self): assert Interval(1, 2) + Interval(1, 2) == Interval(2, 4) def test_sub_operator(self): assert Interval(1, 3) - Interval(1, 2) == Interval(-1, 2) def test_isub_operator(self): range_ ...
from pytest import mark from intervals import Interval class TestArithmeticOperators(object): def test_add_operator(self): assert Interval(1, 2) + Interval(1, 2) == Interval(2, 4) def test_sub_operator(self): assert Interval(1, 3) - Interval(1, 2) == Interval(-1, 2) def test_isub_operato...
Add some tests for intersection
Add some tests for intersection
Python
bsd-3-clause
kvesteri/intervals
4cfd8771b91c7c2b9f28ca4b9776e9770683093b
frigg/builds/admin.py
frigg/builds/admin.py
# -*- coding: utf8 -*- from django.contrib import admin from .models import Build, BuildResult, Project class BuildResultInline(admin.StackedInline): model = BuildResult readonly_fields = ('result_log', 'succeeded', 'return_code') extra = 0 max_num = 0 class BuildInline(admin.TabularInline): mo...
# -*- coding: utf8 -*- from django.contrib import admin from django.template.defaultfilters import pluralize from .models import Build, BuildResult, Project class BuildResultInline(admin.StackedInline): model = BuildResult readonly_fields = ('result_log', 'succeeded', 'return_code') extra = 0 max_num...
Add restart_build action to BuildAdmin
Add restart_build action to BuildAdmin
Python
mit
frigg/frigg-hq,frigg/frigg-hq,frigg/frigg-hq
b1b1392d2f268a5c74fd21c826a3ea6387567cab
froide/bounce/apps.py
froide/bounce/apps.py
from django.apps import AppConfig from django.utils.translation import ugettext_lazy as _ class BounceConfig(AppConfig): name = 'froide.bounce' verbose_name = _('Bounce') def ready(self): from froide.account import account_canceled account_canceled.connect(cancel_user) def cancel_user(...
import json from django.apps import AppConfig from django.utils.translation import ugettext_lazy as _ class BounceConfig(AppConfig): name = 'froide.bounce' verbose_name = _('Bounce') def ready(self): from froide.account import account_canceled from froide.account.export import registry ...
Add user data export for bounce handling
Add user data export for bounce handling
Python
mit
fin/froide,fin/froide,stefanw/froide,stefanw/froide,fin/froide,stefanw/froide,stefanw/froide,fin/froide,stefanw/froide
f9d7f69d7e8ae1dceaba09ac4412438076261744
tests/test_completion.py
tests/test_completion.py
import os import subprocess import sys from pathlib import Path import typer from typer.testing import CliRunner from first_steps import tutorial001 as mod runner = CliRunner() app = typer.Typer() app.command()(mod.main) def test_show_completion(): result = subprocess.run( [ "bash", ...
import os import subprocess import sys from pathlib import Path import typer from typer.testing import CliRunner from first_steps import tutorial001 as mod runner = CliRunner() app = typer.Typer() app.command()(mod.main) def test_show_completion(): result = subprocess.run( [ "bash", ...
Update completion tests, checking for printed message
:white_check_mark: Update completion tests, checking for printed message
Python
mit
tiangolo/typer,tiangolo/typer
83ea38ee5616b1637cc2d983d4518d83793c7b72
lint/events.py
lint/events.py
from collections import defaultdict import traceback LINT_START = 'LINT_START' LINT_RESULT = 'LINT_RESULT' LINT_END = 'LINT_END' listeners = defaultdict(set) def subscribe(topic, fn): listeners[topic].add(fn) def unsubscribe(topic, fn): try: listeners[topic].remove(fn) except KeyError: ...
from collections import defaultdict import traceback LINT_START = 'LINT_START' # (buffer_id) LINT_RESULT = 'LINT_RESULT' # (buffer_id, linter_name, errors) LINT_END = 'LINT_END' # (buffer_id) listeners = defaultdict(set) def subscribe(topic, fn): listeners[topic].add(fn) def unsubscribe(topic, fn...
Add very brief comments about the event types
Add very brief comments about the event types
Python
mit
SublimeLinter/SublimeLinter3,SublimeLinter/SublimeLinter3
4286d2d6a685571c70a8f48c3cd6802d13c4acef
braid/postgres.py
braid/postgres.py
from fabric.api import sudo, quiet from braid import package from pipes import quote def install(): package.install(['postgresql-9.1', 'postgresql-server-dev-9.1']) def _runQuery(query): with quiet(): return sudo('psql --no-align --no-readline --no-password --quiet ' '--tuples-on...
from fabric.api import sudo, hide from braid import package from pipes import quote def install(): package.install(['postgresql-9.1', 'postgresql-server-dev-9.1']) def _runQuery(query): with hide('running', 'output'): return sudo('psql --no-align --no-readline --no-password --quiet ' ...
Make _runQuery to fail if the query fails, but still hide the execution messages
Make _runQuery to fail if the query fails, but still hide the execution messages
Python
mit
alex/braid,alex/braid
92d253fdce108162ab2ce05dd38da971ca42293d
keystone/contrib/kds/common/service.py
keystone/contrib/kds/common/service.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 t...
# 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 t...
Restructure KDS options to be more like Keystone's options
Restructure KDS options to be more like Keystone's options Restructure the KDS options to be more closely aligned with the way Keystone options work and allowing movement towards not registering the options on import. This will also prevent KDS options from appearing in the Keystone auto-generated sample config. Chan...
Python
apache-2.0
rushiagr/keystone,jumpstarter-io/keystone,reeshupatel/demo,dstanek/keystone,idjaw/keystone,jonnary/keystone,vivekdhayaal/keystone,MaheshIBM/keystone,klmitch/keystone,rajalokan/keystone,rajalokan/keystone,nuxeh/keystone,ging/keystone,rushiagr/keystone,takeshineshiro/keystone,ilay09/keystone,nuxeh/keystone,roopali8/keyst...
eaa13f9005a8aaf8c748a98de697b03eee9e675b
salt/client/netapi.py
salt/client/netapi.py
# encoding: utf-8 ''' The main entry point for salt-api ''' from __future__ import absolute_import # Import python libs import logging # Import salt-api libs import salt.loader import salt.utils.process logger = logging.getLogger(__name__) class NetapiClient(object): ''' Start each netapi module that is con...
# encoding: utf-8 ''' The main entry point for salt-api ''' from __future__ import absolute_import # Import python libs import logging # Import salt-api libs import salt.loader import salt.utils.process logger = logging.getLogger(__name__) class NetapiClient(object): ''' Start each netapi module that is con...
Add log error if we run salt-api w/ no config
Add log error if we run salt-api w/ no config Currently, the salt-api script will exit with no error or hint of why it failed if there is no netapi module configured. Added a short line if we find no api modules to start, warning the user that the config may be missing. Fixes #28240
Python
apache-2.0
saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt
0f1ed52e7525ea5f41d63642bca1eaeb9d5af8ba
emission/core/wrapper/labelprediction.py
emission/core/wrapper/labelprediction.py
# Based on modeprediction.py import emission.core.wrapper.wrapperbase as ecwb class Labelprediction(ecwb.WrapperBase): props = {"trip_id": ecwb.WrapperBase.Access.WORM, # the trip that this is part of "prediction": ecwb.WrapperBase.Access.WORM, # What we predict "start_ts": ecwb.Wrapp...
# Based on modeprediction.py import emission.core.wrapper.wrapperbase as ecwb # The "prediction" data structure is a list of label possibilities, each one consisting of a set of labels and a probability: # [ # {"labels": {"labeltype1": "labelvalue1", "labeltype2": "labelvalue2"}, "p": 0.61}, # {"labels": {"label...
Add comments explaining prediction data structure
Add comments explaining prediction data structure
Python
bsd-3-clause
shankari/e-mission-server,shankari/e-mission-server,shankari/e-mission-server,shankari/e-mission-server,e-mission/e-mission-server,e-mission/e-mission-server,e-mission/e-mission-server,e-mission/e-mission-server
4e483d6443e809f9e7e1a59c3fe959fd5f42f938
simple-cipher/simple_cipher.py
simple-cipher/simple_cipher.py
import math import secrets from string import ascii_lowercase class Cipher(object): def __init__(self, key=None): if not key: key = Cipher._random_key() if not key.isalpha() or not key.islower(): raise ValueError("Key must consist only of lowercase letters") self.ke...
import math import secrets from string import ascii_lowercase class Cipher(object): def __init__(self, key=None): if not key: key = self._random_key() if not key.isalpha() or not key.islower(): raise ValueError("Key must consist only of lowercase letters") self.key ...
Use super() and self within the Cipher and Caesar classes
Use super() and self within the Cipher and Caesar classes
Python
agpl-3.0
CubicComet/exercism-python-solutions
5ca96beb26dd2ab5285a57f5cade6f01160df368
joequery/blog/posts/code/notes-on-dynamic-programming-part-1/meta.py
joequery/blog/posts/code/notes-on-dynamic-programming-part-1/meta.py
title="Notes on dynamic programming - part 1" description=""" Part 1 of extensive notes discussing the fundamentals of dynamic programming. Examples in these notes include the Fibonacci sequence and Warshall's algorithm. Pseudocode and Python implementations of the algorithms are provided. """ time="2012-12-10 Mon 02:...
title="Notes on dynamic programming - part 1" description=""" Part 1 of extensive notes discussing the fundamentals of dynamic programming. Examples in these notes include the Fibonacci sequence, the Binomial Formula, and Warshall's algorithm. Python implementations of the algorithms are provided. """ time="2012-12-10...
Update description and timestamp for dynamic programming part 1
Update description and timestamp for dynamic programming part 1
Python
mit
joequery/joequery.me,joequery/joequery.me,joequery/joequery.me,joequery/joequery.me
c04b9813b5d6d3f8bc8eaa7be2d49d32f150aaf2
tests/test_authentication.py
tests/test_authentication.py
import unittest from flask import json from api import db from api.BucketListAPI import app from instance.config import application_config class AuthenticationTestCase(unittest.TestCase): def setUp(self): app.config.from_object(application_config['TestingEnv']) self.client = app.test_client() ...
import unittest from flask import json from api import db from api.BucketListAPI import app from instance.config import application_config class AuthenticationTestCase(unittest.TestCase): def setUp(self): app.config.from_object(application_config['TestingEnv']) self.client = app.test_client() ...
Add test for user with missing credentials
Add test for user with missing credentials
Python
mit
patlub/BucketListAPI,patlub/BucketListAPI
47f1b47f37da4f9a3444a2ac6cc7b7a0affafbf3
node_bridge.py
node_bridge.py
import os import platform import subprocess IS_MACOS = platform.system() == 'Darwin' IS_WINDOWS = platform.system() == 'Windows' def node_bridge(data, bin, args=[]): env = None startupinfo = None if IS_MACOS: # GUI apps on macOS doesn't contain .bashrc/.zshrc set paths env = os.environ.copy() env['PATH'] += ...
import os import platform import subprocess IS_MACOS = platform.system() == 'Darwin' IS_WINDOWS = platform.system() == 'Windows' def node_bridge(data, bin, args=[]): env = None startupinfo = None if IS_MACOS: # GUI apps on macOS doesn't contain .bashrc/.zshrc set paths env = os.environ.copy() env['PATH'] += ...
Add support for `n` Node.js version manager
Add support for `n` Node.js version manager
Python
mit
sindresorhus/sublime-autoprefixer,sindresorhus/sublime-autoprefixer,sindresorhus/sublime-autoprefixer
c7660db45e0275a685a6cc450fd4341a69c52b92
threaded_multihost/fields.py
threaded_multihost/fields.py
from django.db.models import ForeignKey from django.contrib.auth.models import User import threadlocals class UserField(ForeignKey): """ UserField By defaults, foreign key to User; null=True, blank=True """ def __init__(self, **kwargs): kwargs.setdefault('null', True) kwargs.setdefa...
from django.db.models import ForeignKey from django.contrib.auth.models import User import threadlocals class UserField(ForeignKey): """ UserField By defaults, foreign key to User; null=True, blank=True """ def __init__(self, **kwargs): kwargs.setdefault('to', User) kwargs.setdefaul...
Patch from chrischambers to enable south migrations.
Patch from chrischambers to enable south migrations.
Python
bsd-3-clause
diver-in-sky/django-threaded-multihost
305e88780fc2d3638fb3a9f33bfec8d6c295535e
feincms/views/base.py
feincms/views/base.py
from django.contrib.auth.decorators import permission_required from django.shortcuts import get_object_or_404, render_to_response from django.template import RequestContext from feincms.module.page.models import Page def build_page_response(page, request): response = page.setup_request(request) if respo...
from django.contrib.auth.decorators import permission_required from django.shortcuts import get_object_or_404, render_to_response from django.template import RequestContext from feincms.module.page.models import Page def _build_page_response(page, request): response = page.setup_request(request) if resp...
Make sure we invoke the response processors even for app content.
Make sure we invoke the response processors even for app content.
Python
bsd-3-clause
matthiask/feincms2-content,joshuajonah/feincms,nickburlett/feincms,nickburlett/feincms,hgrimelid/feincms,feincms/feincms,mjl/feincms,mjl/feincms,joshuajonah/feincms,pjdelport/feincms,matthiask/django-content-editor,feincms/feincms,matthiask/feincms2-content,matthiask/django-content-editor,hgrimelid/feincms,pjdelport/fe...
fc472d043e81c2b5687a0f83dbbdd0dd02b73e35
flowtype/commands/exec_flow.py
flowtype/commands/exec_flow.py
import os import json import threading import subprocess import sublime class ExecFlowCommand(threading.Thread): """Threaded class used for running flow commands in a different thread. The subprocess must be threaded so we don't lockup the UI. """ def __init__(self, cmd, content): """Initia...
import os import json import threading import subprocess import sublime class ExecFlowCommand(threading.Thread): """Threaded class used for running flow commands in a different thread. The subprocess must be threaded so we don't lockup the UI. """ def __init__(self, cmd, content): """Initia...
Add error output to exec error messages
Add error output to exec error messages e.g. for an error like "env: ‘node’: No such file or directory" the sublime console was only reporting "exited with code 127" which wasn't very helpful in determining the cause.
Python
mit
Pegase745/sublime-flowtype
3aa13efa28b4ededa465541a7db8df5fc5878ce3
tempora/tests/test_timing.py
tempora/tests/test_timing.py
import datetime import time import contextlib import os from unittest import mock from tempora import timing def test_IntervalGovernor(): """ IntervalGovernor should prevent a function from being called more than once per interval. """ func_under_test = mock.MagicMock() # to look like a funct...
import datetime import time import contextlib import os from unittest import mock import pytest from tempora import timing def test_IntervalGovernor(): """ IntervalGovernor should prevent a function from being called more than once per interval. """ func_under_test = mock.MagicMock() # to loo...
Rewrite alt_tz as proper fixture. Skip when tzset isn't available.
Rewrite alt_tz as proper fixture. Skip when tzset isn't available.
Python
mit
jaraco/tempora
c43820a2e26dd4f87c36b986a9a0af80b409f659
sentence_extractor.py
sentence_extractor.py
import textract import sys import os import re import random ################################### # Extracts text from a pdf file and # selects one sentence, which it # then prints. # # Created by Fredrik Omstedt. ################################### # Extracts texts from pdf files. If given a directory, the # program ...
import textract import sys import os import re import random ################################### # Extracts text from a pdf file and # selects one sentence, which it # then prints. # # Created by Fredrik Omstedt. ################################### # Extracts texts from pdf files. If given a directory, the # program ...
Update regex to match sentences starting with ÅÄÖ
Update regex to match sentences starting with ÅÄÖ
Python
mit
Xaril/sentence-extractor,Xaril/sentence-extractor
c8cc1f8e0e9b6d7dfb29ff9aef04bf2b5867cceb
genomediff/records.py
genomediff/records.py
class Metadata(object): def __init__(self, name, value): self.name = name self.value = value def __repr__(self): return "Metadata({}, {})".format(repr(self.name), repr(self.value)) def __eq__(self, other): return self.__dict__ == other.__dict__ class Record(object): d...
class Metadata(object): def __init__(self, name, value): self.name = name self.value = value def __repr__(self): return "Metadata({}, {})".format(repr(self.name), repr(self.value)) def __eq__(self, other): return self.__dict__ == other.__dict__ class Record(object): d...
Raise AttributeError if key does not exist when trying to get it from a Record
Raise AttributeError if key does not exist when trying to get it from a Record
Python
mit
biosustain/genomediff-python
9aace6d89642e5025692b25e2c6253544ed580a6
social_auth/models.py
social_auth/models.py
"""Social auth models""" from django.db import models from django.contrib.auth.models import User class UserSocialAuth(models.Model): """Social Auth association model""" user = models.ForeignKey(User, related_name='social_auth') provider = models.CharField(max_length=32) uid = models.TextField() ...
"""Social auth models""" from django.db import models from django.contrib.auth.models import User class UserSocialAuth(models.Model): """Social Auth association model""" user = models.ForeignKey(User, related_name='social_auth') provider = models.CharField(max_length=32) uid = models.TextField() ...
Remove max_length from TextFields and replace short text fields with CharFields
Remove max_length from TextFields and replace short text fields with CharFields
Python
bsd-3-clause
michael-borisov/django-social-auth,krvss/django-social-auth,thesealion/django-social-auth,lovehhf/django-social-auth,sk7/django-social-auth,dongguangming/django-social-auth,czpython/django-social-auth,beswarm/django-social-auth,adw0rd/django-social-auth,MjAbuz/django-social-auth,VishvajitP/django-social-auth,MjAbuz/dja...
eca73e0c57042593f7e65446e26e63790c5cf2aa
notes/admin.py
notes/admin.py
# # Copyright (c) 2009 Brad Taylor <brad@getcoded.net> # # This program is free software: you can redistribute it and/or modify it under # the terms of the GNU Affero General Public License as published by the Free # Software Foundation, either version 3 of the License, or (at your option) any # later version. # # This...
# # Copyright (c) 2009 Brad Taylor <brad@getcoded.net> # # This program is free software: you can redistribute it and/or modify it under # the terms of the GNU Affero General Public License as published by the Free # Software Foundation, either version 3 of the License, or (at your option) any # later version. # # This...
Complete removal of reversion usage
Complete removal of reversion usage
Python
agpl-3.0
leonhandreke/snowy,NoUsername/PrivateNotesExperimental,jaredjennings/snowy,GNOME/snowy,sandyarmstrong/snowy,syskill/snowy,syskill/snowy,NoUsername/PrivateNotesExperimental,sandyarmstrong/snowy,jaredjennings/snowy,jaredjennings/snowy,widox/snowy,jaredjennings/snowy,nekohayo/snowy,nekohayo/snowy,widox/snowy,GNOME/snowy,l...
630ba21f3b08dcd2685297b057cbee4b6abee6f7
us_ignite/sections/models.py
us_ignite/sections/models.py
from django.db import models class Sponsor(models.Model): name = models.CharField(max_length=255) website = models.URLField(max_length=500) image = models.ImageField(upload_to="sponsor") order = models.IntegerField(default=0) class Meta: ordering = ('order', ) def __unicode__(self): ...
from django.db import models class Sponsor(models.Model): name = models.CharField(max_length=255) website = models.URLField(max_length=500) image = models.ImageField( upload_to="sponsor", help_text='This image is not post processed. ' 'Please make sure it has the right design specs.') ...
Add help text describing the image field functionality.
Add help text describing the image field functionality.
Python
bsd-3-clause
us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite
850d5189d3159f7cab6c509a2dd58c9f427c0bfc
examples/python/find_events.py
examples/python/find_events.py
from gi.repository import Zeitgeist log = Zeitgeist.Log.get_default() def callback (x): print x log.get_events([x for x in xrange(100)], None, callback, None)
from gi.repository import Zeitgeist, Gtk log = Zeitgeist.Log.get_default() def callback (x): print x log.get_events([x for x in xrange(100)], None, callback, None) Gtk.main()
Add loop to the python example
Add loop to the python example
Python
lgpl-2.1
freedesktop-unofficial-mirror/zeitgeist__zeitgeist,freedesktop-unofficial-mirror/zeitgeist__zeitgeist,freedesktop-unofficial-mirror/zeitgeist__zeitgeist,freedesktop-unofficial-mirror/zeitgeist__zeitgeist,freedesktop-unofficial-mirror/zeitgeist__zeitgeist
9cfd402c8f95c016953eda752e1bd91302d6c8c0
translations/lantmateriet.py
translations/lantmateriet.py
def filterTags(attrs): res = {} if 'NAMN' in attrs: res['name'] = attrs['NAMN'] if 'TATNR' in attrs: res['ref:se:scb'] = attrs['TATNR'] if attrs.get('BEF') is not None: bef = int(attrs.get('BEF')) # This is an approximation based on http://wiki.openstreetmap.org/wiki...
def filterTags(attrs): res = {} if 'NAMN' in attrs: res['name'] = attrs['NAMN'] if 'TATNR' in attrs: res['ref:se:scb'] = attrs['TATNR'] if attrs.get('BEF') is not None: bef = int(attrs.get('BEF')) # This is an approximation based on http://wiki.openstreetmap.org/wiki...
Add population to the tags
LM: Add population to the tags
Python
bsd-3-clause
andpe/swegov-to-osm
d13c674a7286f1af9cd13babe2cb5c429b5b3bfa
scripts/update_guide_stats.py
scripts/update_guide_stats.py
#!/usr/bin/env python # Licensed under a 3-clause BSD style license - see LICENSE.rst from mica.stats import update_guide_stats update_guide_stats.main() import os table_file = mica.stats.guide_stats.TABLE_FILE file_stat = os.stat(table_file) if file_stat.st_size > 200e6: print(""" Warning: {tfile} is larger than...
#!/usr/bin/env python # Licensed under a 3-clause BSD style license - see LICENSE.rst import os import argparse from mica.stats import update_guide_stats import mica.stats.guide_stats # Cheat and pass options directly. Needs entrypoint scripts opt = argparse.Namespace(datafile=mica.stats.guide_stats.TABLE_FILE, ...
Update guide stat script to pass datafile
Update guide stat script to pass datafile
Python
bsd-3-clause
sot/mica,sot/mica
5914b9a4d1d086f1a92309c0895aa7dd11761776
conf_site/accounts/tests/test_registration.py
conf_site/accounts/tests/test_registration.py
from factory import Faker, fuzzy from django.contrib.auth import get_user_model from django.test import TestCase from django.urls import reverse class UserRegistrationTestCase(TestCase): def test_registration_view(self): """Verify that user registration view loads properly.""" response = self.cli...
from django.contrib.auth import get_user_model from django.test import TestCase from django.urls import reverse from factory import fuzzy from faker import Faker class UserRegistrationTestCase(TestCase): def test_registration_view(self): """Verify that user registration view loads properly.""" re...
Change imports in user registration test.
Change imports in user registration test.
Python
mit
pydata/conf_site,pydata/conf_site,pydata/conf_site
9a7100aaf0207fe93b28d7e473a4b5c1cd6061fe
vumi/application/__init__.py
vumi/application/__init__.py
"""The vumi.application API.""" __all__ = ["ApplicationWorker", "SessionManager"] from vumi.application.base import ApplicationWorker from vumi.application.session import SessionManager
"""The vumi.application API.""" __all__ = ["ApplicationWorker", "SessionManager", "TagpoolManager"] from vumi.application.base import ApplicationWorker from vumi.application.session import SessionManager from vumi.application.tagpool import TagpoolManager
Add TagpoolManager to vumi.application API.
Add TagpoolManager to vumi.application API.
Python
bsd-3-clause
vishwaprakashmishra/xmatrix,vishwaprakashmishra/xmatrix,TouK/vumi,harrissoerja/vumi,TouK/vumi,vishwaprakashmishra/xmatrix,harrissoerja/vumi,TouK/vumi,harrissoerja/vumi
2479b4a51b733ce8ba989d8f01b48791492d9f21
cogs/utils/dataIO.py
cogs/utils/dataIO.py
import redis_collections import threading import time import __main__ class RedisDict(redis_collections.Dict): def __init__(self, **kwargs): super().__init__(**kwargs) self.die = False self.thread = threading.Thread(target=self.update_loop, daemon=True, name=kwargs['key']) self.thr...
import redis_collections import threading import time # noinspection PyUnresolvedReferences import __main__ class RedisDict(redis_collections.Dict): def __init__(self, **kwargs): super().__init__(**kwargs) self.die = False self.thread = threading.Thread(target=self.update_loop, daemon=True...
Make config sync more efficient
Make config sync more efficient
Python
mit
Thessia/Liara
87a3025196b0b3429cab1f439cd10728e99d982f
skimage/transform/__init__.py
skimage/transform/__init__.py
from .hough_transform import * from .radon_transform import * from .finite_radon_transform import * from .integral import * from ._geometric import (warp, warp_coords, estimate_transform, SimilarityTransform, AffineTransform, ProjectiveTransform, PolynomialTransform, ...
from .hough_transform import * from .radon_transform import * from .finite_radon_transform import * from .integral import * from ._geometric import (warp, warp_coords, estimate_transform, SimilarityTransform, AffineTransform, ProjectiveTransform, PolynomialTransform, ...
Add missing imports in transform module.
BUG: Add missing imports in transform module.
Python
bsd-3-clause
emon10005/scikit-image,bsipocz/scikit-image,blink1073/scikit-image,youprofit/scikit-image,rjeli/scikit-image,SamHames/scikit-image,almarklein/scikit-image,rjeli/scikit-image,emon10005/scikit-image,almarklein/scikit-image,youprofit/scikit-image,chintak/scikit-image,almarklein/scikit-image,paalge/scikit-image,vighneshbir...
ed3c03ac4f213f3882e28f25ae0596a7021928cd
test/ParseableInterface/Inputs/make-unreadable.py
test/ParseableInterface/Inputs/make-unreadable.py
import platform import subprocess import sys if platform.system() == 'Windows': import ctypes AdvAPI32 = ctypes.windll.Advapi32 from ctypes.wintypes import POINTER UNLEN = 256 GetUserNameW = AdvAPI32.GetUserNameW GetUserNameW.argtypes = ( ctypes.c_wchar_p, # _In_Out_ lpBuf...
import platform import subprocess import sys if platform.system() == 'Windows': import ctypes AdvAPI32 = ctypes.windll.Advapi32 from ctypes.wintypes import POINTER UNLEN = 256 GetUserNameW = AdvAPI32.GetUserNameW GetUserNameW.argtypes = ( ctypes.c_wchar_p, # _In_Out_ lpBuf...
Fix handling of Network Service username.
[windows] Fix handling of Network Service username. In Windows Server 2016 at least, the Network Service user (the one being used by the CI machine) is returned as Host$, which icacls doesn't understand. Turn the name into something that icacls if we get a name that ends with a dollar.
Python
apache-2.0
atrick/swift,hooman/swift,harlanhaskins/swift,shahmishal/swift,stephentyrone/swift,jmgc/swift,devincoughlin/swift,ahoppen/swift,tkremenek/swift,xedin/swift,shahmishal/swift,xwu/swift,xedin/swift,harlanhaskins/swift,harlanhaskins/swift,sschiau/swift,shajrawi/swift,karwa/swift,gribozavr/swift,apple/swift,CodaFi/swift,aho...
8f68e3f3ab63d67d3e7fc1c8cd63c6c9d03729a2
Channels/News_Channel/lz77.py
Channels/News_Channel/lz77.py
import glob import os import subprocess """This is used to decompress the news.bin files.""" def decompress(file): with open(file, "rb") as source_file: read = source_file.read() tail = read[320:] with open(file + ".2", "w+") as dest_file: dest_file.write(tail) FNULL = open(os.devnull, "w+") de...
import glob import os import subprocess """This is used to decompress the news.bin files.""" def decompress(file): with open(file, "rb") as source_file: read = source_file.read() tail = read[320:] with open(file + ".2", "w+") as dest_file: dest_file.write(tail) FNULL = open(os.devnull, "w+") de...
Comment about the hex part
Comment about the hex part
Python
agpl-3.0
RiiConnect24/File-Maker,RiiConnect24/File-Maker
794a75ed410fe39ba2376ebcab75d21cc5e9fee0
common/safeprint.py
common/safeprint.py
import multiprocessing, sys, datetime print_lock = multiprocessing.Lock() def safeprint(content): with print_lock: sys.stdout.write(("[" + str(multiprocessing.current_process().pid) + "] " + datetime.datetime.now().strftime('%H%M%S') + ": " + str(content) + '\r\n'))
import multiprocessing, sys, datetime print_lock = multiprocessing.RLock() def safeprint(content): string = "[" + str(multiprocessing.current_process().pid) + "] " + datetime.datetime.now().strftime('%H%M%S') + ": " + str(content) + '\r\n' with print_lock: sys.stdout.write(string)
Reduce the amount of time locking
Reduce the amount of time locking
Python
mit
gappleto97/Senior-Project
b79ed827f7211efbcdef95286bf2d4113d6e8b88
posts/views.py
posts/views.py
from django.shortcuts import get_object_or_404 from django.views.generic.dates import ArchiveIndexView from django.views.generic.edit import FormView from .models import Entry, Category from .forms import ContactForm class CategoryView(ArchiveIndexView): model = Entry date_field = 'date' paginate_by = 20 ...
from django.shortcuts import get_object_or_404 from django.views.generic.dates import ArchiveIndexView from django.views.generic.edit import FormView from .models import Entry, Category from .forms import ContactForm class CategoryView(ArchiveIndexView): model = Entry date_field = 'date' paginate_by = 20 ...
Fix ordering of category view
Fix ordering of category view Signed-off-by: Michal Čihař <a2df1e659c9fd2578de0a26565357cb273292eeb@cihar.com>
Python
agpl-3.0
nijel/photoblog,nijel/photoblog
df99ee50e7d7a677aec4e30af10283399a8edb8c
dlstats/configuration.py
dlstats/configuration.py
import configobj import validate import os def _get_filename(): """Return the configuration file path.""" appname = 'dlstats' if os.name == 'posix': if os.path.isfile(os.environ["HOME"]+'/.'+appname): return os.environ["HOME"]+'/.'+appname elif os.path.isfile('/etc/'+appname): ...
import configobj import validate import os def _get_filename(): """Return the configuration file path.""" appname = 'dlstats' if os.name == 'posix': if "HOME" in os.environ: if os.path.isfile(os.environ["HOME"]+'/.'+appname): return os.environ["HOME"]+'/.'+appname ...
Test for environment variable existence
Test for environment variable existence
Python
agpl-3.0
Widukind/dlstats,MichelJuillard/dlstats,MichelJuillard/dlstats,mmalter/dlstats,mmalter/dlstats,Widukind/dlstats,mmalter/dlstats,MichelJuillard/dlstats
3838e44a397fdb4b605ead875b7c6ebc5787644d
jal_stats/stats/serializers.py
jal_stats/stats/serializers.py
from rest_framework import serializers from .models import Activity, Datapoint class ActivitySerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Activity fields = ('user', 'full_description', 'units', 'url') class DatapointSerializer(serializers.HyperlinkedModelSerializer): ...
from rest_framework import serializers from .models import Activity, Datapoint class ActivitySerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Activity fields = ('id', 'user', 'full_description', 'units', 'url') class DatapointSerializer(serializers.HyperlinkedModelSerializ...
Add 'id' to both Serializers
Add 'id' to both Serializers
Python
mit
jal-stats/django
ec1e0cd1fa8bab59750032942643a7abc8700642
cspreports/models.py
cspreports/models.py
#LIBRARIES from django.db import models from django.utils.html import escape from django.utils.safestring import mark_safe class CSPReport(models.Model): class Meta(object): ordering = ('-created',) created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) ...
# STANDARD LIB import json #LIBRARIES from django.db import models from django.utils.html import escape from django.utils.safestring import mark_safe class CSPReport(models.Model): class Meta(object): ordering = ('-created',) created = models.DateTimeField(auto_now_add=True) modified = models.D...
Revert removing data which is still used
Revert removing data which is still used This was removed in b1bc34e9a83cb3af5dd11baa1236f2b65ab823f9 but is still used in admin.py.
Python
mit
adamalton/django-csp-reports
271b4cd3795cbe0e5e013ac53c3ea26ca08e7a1a
IPython/utils/importstring.py
IPython/utils/importstring.py
# encoding: utf-8 """ A simple utility to import something by its string name. Authors: * Brian Granger """ #----------------------------------------------------------------------------- # Copyright (C) 2008-2011 The IPython Development Team # # Distributed under the terms of the BSD License. The full license is...
# encoding: utf-8 """ A simple utility to import something by its string name. Authors: * Brian Granger """ #----------------------------------------------------------------------------- # Copyright (C) 2008-2011 The IPython Development Team # # Distributed under the terms of the BSD License. The full license is...
Fix error in test suite startup with dotted import names.
Fix error in test suite startup with dotted import names. Detected first on ubuntu 12.04, but the bug is generic, we just hadn't seen it before. Will push straight to master as this will begin causing problems as more people upgrade.
Python
bsd-3-clause
ipython/ipython,ipython/ipython
14869bd8c58a393caec488e95d51c282ccf23d0d
katagawa/sql/__init__.py
katagawa/sql/__init__.py
""" SQL generators for Katagawa. """ import abc import typing class Token(abc.ABC): """ Base class for a token. """ def __init__(self, subtokens: typing.List['Token']): """ :param subtokens: Any subtokens this token has. """ self.subtokens = subtokens @abc.abstract...
""" SQL generators for Katagawa. """ import abc import typing class Token(abc.ABC): """ Base class for a token. """ __slots__ = () def __init__(self, subtokens: typing.List['Token']): """ :param subtokens: Any subtokens this token has. """ self.subtokens = subtoke...
Add aliased ABC for tokens with an alias.
Add aliased ABC for tokens with an alias.
Python
mit
SunDwarf/asyncqlio
7844df0c4f32c9cc1f5833aba4712680461f77b5
test/on_yubikey/cli_piv/test_misc.py
test/on_yubikey/cli_piv/test_misc.py
import unittest from ..framework import cli_test_suite from .util import DEFAULT_MANAGEMENT_KEY @cli_test_suite def additional_tests(ykman_cli): class Misc(unittest.TestCase): def setUp(self): ykman_cli('piv', 'reset', '-f') def test_info(self): output = ykman_cli('piv',...
import unittest from ykman.piv import OBJ from .util import DEFAULT_MANAGEMENT_KEY from ..framework import cli_test_suite from .util import DEFAULT_MANAGEMENT_KEY @cli_test_suite def additional_tests(ykman_cli): class Misc(unittest.TestCase): def setUp(self): ykman_cli('piv', 'reset', '-f') ...
Test that invalid cert crashes export-certificate but not info
Test that invalid cert crashes export-certificate but not info
Python
bsd-2-clause
Yubico/yubikey-manager,Yubico/yubikey-manager
1c3c092afae1946e72a87cca8792bd012bee23e4
ktbs_bench/utils/decorators.py
ktbs_bench/utils/decorators.py
from functools import wraps from inspect import getcallargs from timer import Timer def bench(f): """Times a function given specific arguments.""" # TODO mettre args (n_repeat, func) qui execute n_repeat fois et applique un reduce(res, func) @wraps(f) def wrapped(*args, **kwargs): timer = Ti...
from functools import wraps from inspect import getcallargs from timer import Timer def bench(f): """Decorator to time a function. Parameters ---------- f : function The function to time. Returns ------- call_signature : str The signature of the function call, with param...
Add docstrings and fix call of call_signature.
Add docstrings and fix call of call_signature. For the fix: call_signature has been moved before executing the actual call, if the call is made before then it might change arguments if they are references.
Python
mit
ktbs/ktbs-bench,ktbs/ktbs-bench
15be3bd492a0808713c6ae6981ecb99acacd5297
allauth/socialaccount/providers/trello/provider.py
allauth/socialaccount/providers/trello/provider.py
from allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth.provider import OAuthProvider class TrelloAccount(ProviderAccount): def get_profile_url(self): return None def get_avatar_url(self): return None class TrelloProvider(OAuthProvider): ...
from allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth.provider import OAuthProvider class TrelloAccount(ProviderAccount): def get_profile_url(self): return None def get_avatar_url(self): return None class TrelloProvider(OAuthProvider): ...
Use 'scope' in TrelloProvider auth params. Allows overriding from django settings.
feat(TrelloProvider): Use 'scope' in TrelloProvider auth params. Allows overriding from django settings.
Python
mit
AltSchool/django-allauth,AltSchool/django-allauth,AltSchool/django-allauth
a35b6e46bd9d443f07391f37f5e0e384e37608bb
nbgrader/tests/test_nbgrader_feedback.py
nbgrader/tests/test_nbgrader_feedback.py
from .base import TestBase from nbgrader.api import Gradebook import os class TestNbgraderFeedback(TestBase): def _setup_db(self): dbpath = self._init_db() gb = Gradebook(dbpath) gb.add_assignment("Problem Set 1") gb.add_student("foo") gb.add_student("bar") return ...
from .base import TestBase from nbgrader.api import Gradebook import os import shutil class TestNbgraderFeedback(TestBase): def _setup_db(self): dbpath = self._init_db() gb = Gradebook(dbpath) gb.add_assignment("ps1") gb.add_student("foo") return dbpath def test_help(...
Update tests for nbgrader feedback
Update tests for nbgrader feedback
Python
bsd-3-clause
jhamrick/nbgrader,alope107/nbgrader,ellisonbg/nbgrader,EdwardJKim/nbgrader,modulexcite/nbgrader,EdwardJKim/nbgrader,ellisonbg/nbgrader,jdfreder/nbgrader,MatKallada/nbgrader,jupyter/nbgrader,MatKallada/nbgrader,jupyter/nbgrader,dementrock/nbgrader,jhamrick/nbgrader,EdwardJKim/nbgrader,jupyter/nbgrader,jupyter/nbgrader,m...
0749c47bb280230ae5b1e2cda23773d3b10b2491
redis_check.py
redis_check.py
#!/usr/bin/env python3 import sys import redis import redis.exceptions host = sys.argv[1] host = host.strip('\r\n') port = 6379 timeout = 5 try: db = redis.StrictRedis(host=host, port=port, socket_timeout=timeout) i = db.info() ver = i.get('redis_version') siz = db.dbsize() print('[+] {0}:{1}...
#!/usr/bin/env python3 import sys import redis import redis.exceptions host = sys.argv[1] host = host.strip('\r\n') port = 6379 timeout = 5 try: db = redis.StrictRedis(host=host, port=port, socket_timeout=timeout) i = db.info() ver = i.get('redis_version') siz = db.dbsize() print('[+] {0}:{1}...
Make output easier to parse with cli tools.
Make output easier to parse with cli tools.
Python
bsd-3-clause
averagesecurityguy/research
8e53b65b5f28a02f8ee980b9f53a57e7cdd077bd
main.py
main.py
import places from character import Character import actions import options from multiple_choice import MultipleChoice def combat(character): """ takes in a character, returns outcome of fight """ return actions.Attack(character.person).get_outcome(character) def main(): """ The goal is to h...
import places from character import Character import actions import options from multiple_choice import MultipleChoice def main(): """ The goal is to have the main function operate as follows: Set up the initial state Display the initial message Display the initial options Choo...
Refactor combat code to be more concise
Refactor combat code to be more concise
Python
apache-2.0
SageBerg/St.GeorgeGame,SageBerg/St.GeorgeGame,SageBerg/St.GeorgeGame,SageBerg/St.GeorgeGame
75d6e88de0ed8f8cb081de15ce0d3949a78c9ded
efselab/build.py
efselab/build.py
#!/usr/bin/env python3 from distutils.core import setup, Extension MODULES_TO_BUILD = ["fasthash", "suc", "lemmatize"] for module in MODULES_TO_BUILD: setup( name=module, ext_modules=[ Extension( name=module, sources=['%s.c' % module], li...
#!/usr/bin/env python3 from distutils.core import setup, Extension MODULES_TO_BUILD = ["fasthash", "suc", "lemmatize"] def main(): for module in MODULES_TO_BUILD: setup( name=module, ext_modules=[ Extension( name=module, sourc...
Put module in method to enable calls from libraries.
Put module in method to enable calls from libraries. Former-commit-id: e614cec07ee71723be5b114163fe835961f6811c
Python
mit
EmilStenstrom/json-tagger,EmilStenstrom/json-tagger,EmilStenstrom/json-tagger,EmilStenstrom/json-tagger,EmilStenstrom/json-tagger
1763b533bf33a8e450b4cf8d6f55d4ffaf6b2bea
tests/window/WINDOW_CAPTION.py
tests/window/WINDOW_CAPTION.py
#!/usr/bin/env python '''Test that the window caption can be set. Expected behaviour: Two windows will be opened, one with the caption "Window caption 1" counting up every second; the other with a Unicode string including some non-ASCII characters. Press escape or close either window to finished the ...
#!/usr/bin/env python '''Test that the window caption can be set. Expected behaviour: Two windows will be opened, one with the caption "Window caption 1" counting up every second; the other with a Unicode string including some non-ASCII characters. Press escape or close either window to finished the ...
Make windows bigger in this test so the captions can be read.
Make windows bigger in this test so the captions can be read. Index: tests/window/WINDOW_CAPTION.py =================================================================== --- tests/window/WINDOW_CAPTION.py (revision 777) +++ tests/window/WINDOW_CAPTION.py (working copy) @@ -19,8 +19,8 @@ class WINDOW_CAPTION(unittest....
Python
bsd-3-clause
mammadori/pyglet,oktayacikalin/pyglet,oktayacikalin/pyglet,theblacklion/pyglet,mammadori/pyglet,oktayacikalin/pyglet,theblacklion/pyglet,oktayacikalin/pyglet,mammadori/pyglet,theblacklion/pyglet,theblacklion/pyglet,oktayacikalin/pyglet,mammadori/pyglet,theblacklion/pyglet
10f72ab0428ddf51b47bc95b64b2a532c8e670a5
auth0/v2/authentication/enterprise.py
auth0/v2/authentication/enterprise.py
import requests class Enterprise(object): def __init__(self, domain): self.domain = domain def saml_login(self, client_id, connection): """ """ return requests.get( 'https://%s/samlp/%s' % (self.domain, client_id), params={'connection': connection} ...
from .base import AuthenticationBase class Enterprise(AuthenticationBase): def __init__(self, domain): self.domain = domain def saml_metadata(self, client_id): return self.get(url='https://%s/samlp/metadata/%s' % (self.domain, cli...
Refactor Enterprise class to use AuthenticationBase
Refactor Enterprise class to use AuthenticationBase
Python
mit
auth0/auth0-python,auth0/auth0-python
acec9342e392fed103e5d6b78470251d2cf535d6
timpani/webserver/webserver.py
timpani/webserver/webserver.py
import flask import os.path import datetime import urllib.parse from .. import configmanager from . import controllers FILE_LOCATION = os.path.abspath(os.path.dirname(__file__)) STATIC_PATH = os.path.abspath(os.path.join(FILE_LOCATION, "../../static")) CONFIG_PATH = os.path.abspath(os.path.join(FILE_LOCATION, "../../c...
import flask import os.path import datetime import urllib.parse from .. import database from .. import configmanager from . import controllers FILE_LOCATION = os.path.abspath(os.path.dirname(__file__)) STATIC_PATH = os.path.abspath(os.path.join(FILE_LOCATION, "../../static")) CONFIG_PATH = os.path.abspath(os.path.join...
Add teardown request instead of usesDatabase decorator
Add teardown request instead of usesDatabase decorator
Python
mit
ollien/Timpani,ollien/Timpani,ollien/Timpani
967ec17d15f07191e6d42fc122eb5e731605ad67
git_code_debt/repo_parser.py
git_code_debt/repo_parser.py
import collections import contextlib import shutil import subprocess import tempfile from util.iter import chunk_iter Commit = collections.namedtuple('Commit', ['sha', 'date', 'name']) class RepoParser(object): def __init__(self, git_repo, ref): self.git_repo = git_repo self.ref = ref s...
import collections import contextlib import shutil import subprocess import tempfile from util.iter import chunk_iter Commit = collections.namedtuple('Commit', ['sha', 'date', 'name']) class RepoParser(object): def __init__(self, git_repo): self.git_repo = git_repo self.tempdir = None @con...
Change sha fetching to use --parent-only and removed ref parameter
Change sha fetching to use --parent-only and removed ref parameter
Python
mit
ucarion/git-code-debt,Yelp/git-code-debt,ucarion/git-code-debt,ucarion/git-code-debt,Yelp/git-code-debt,Yelp/git-code-debt,Yelp/git-code-debt
a1583d181170302df72fc0a97e5db7f6300061b3
tests/__init__.py
tests/__init__.py
#
import os DATADIR = os.path.abspath('docs/data') FILES = ['test_uk.shp', 'test_uk.shx', 'test_uk.dbf', 'test_uk.prj'] def create_zipfile(zipfilename): import zipfile with zipfile.ZipFile(zipfilename, 'w') as zip: for filename in FILES: zip.write(os.path.join(DATADIR, filename), filename) ...
Create derived test data files if they do not exist when running nosetests
Create derived test data files if they do not exist when running nosetests
Python
bsd-3-clause
perrygeo/Fiona,rbuffat/Fiona,perrygeo/Fiona,johanvdw/Fiona,Toblerity/Fiona,rbuffat/Fiona,Toblerity/Fiona
34031f2b16303bcff69a7b52ec3e85ce35103c96
src/hunter/const.py
src/hunter/const.py
import collections import os import site import sys from distutils.sysconfig import get_python_lib SITE_PACKAGES_PATHS = set() if hasattr(site, 'getsitepackages'): SITE_PACKAGES_PATHS.update(site.getsitepackages()) if hasattr(site, 'getusersitepackages'): SITE_PACKAGES_PATHS.add(site.getusersitepackages()) SIT...
import collections import os import site import sys from distutils.sysconfig import get_python_lib SITE_PACKAGES_PATHS = set() if hasattr(site, 'getsitepackages'): SITE_PACKAGES_PATHS.update(site.getsitepackages()) if hasattr(site, 'getusersitepackages'): SITE_PACKAGES_PATHS.add(site.getusersitepackages()) SIT...
Sort by longest path (assuming stdlib stuff will be in the longest).
Sort by longest path (assuming stdlib stuff will be in the longest).
Python
bsd-2-clause
ionelmc/python-hunter
d1edcb2f59d96168e94ec748633221a2d5f95b99
colorise/color_tools.py
colorise/color_tools.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """Functions for converting and comparing colors.""" import colorsys import math import operator def hls_to_rgb(hue, lightness, saturation): """Convert HLS (hue, lightness, saturation) values to RGB.""" return tuple(int(math.ceil(c * 255.)) for ...
#!/usr/bin/env python # -*- coding: utf-8 -*- """Functions for converting and comparing colors.""" import colorsys import math import operator def hls_to_rgb(hue, lightness, saturation): """Convert HLS (hue, lightness, saturation) values to RGB.""" return tuple(int(math.ceil(c * 255.)) for ...
Remove unused color distance function
Remove unused color distance function
Python
bsd-3-clause
MisanthropicBit/colorise
2c0ff93e3ef5e6914a85e4fc3443f0432337854e
text_processor.py
text_processor.py
from urllib.request import urlopen def fetch_words(): with urlopen('http://sixty-north.com/c/t.txt') as story: story_words = [] word_list = '' for line in story: line_words = line.decode('utf-8').split() for word in line_words: story_words.append(wor...
from urllib.request import urlopen def fetch_words(): with urlopen('http://sixty-north.com/c/t.txt') as story: story_words = [] word_list = '' for line in story: line_words = line.decode('utf-8').split() for word in line_words: story_words.append(wor...
Move main execution to function
Move main execution to function
Python
mit
kentoj/python-fundamentals
83ceca04758c6546c41d5bc7f96583d838f25e11
src/mmw/apps/user/backends.py
src/mmw/apps/user/backends.py
# -*- coding: utf-8 -*- from django.core.exceptions import ObjectDoesNotExist from django.contrib.auth.backends import BaseBackend from django.contrib.auth.models import User from apps.user.models import ItsiUser, ConcordUser class SSOAuthenticationBackend(BaseBackend): """ A custom authentication back-end f...
# -*- coding: utf-8 -*- from django.core.exceptions import ObjectDoesNotExist from django.contrib.auth.backends import BaseBackend from django.contrib.auth.models import User from apps.user.models import ItsiUser, ConcordUser class SSOAuthenticationBackend(BaseBackend): """ A custom authentication back-end f...
Add request parameter to backend.authenticate
Add request parameter to backend.authenticate Without this, the signature of our custom backend does not match that of the function call. This signature is tested in django.contrib.auth.authenticate here: https://github.com/django/django/blob/fdf209eab8949ddc345aa0212b349c79fc6fdebb/django/contrib/auth/__init__.py#L69...
Python
apache-2.0
WikiWatershed/model-my-watershed,WikiWatershed/model-my-watershed,WikiWatershed/model-my-watershed,WikiWatershed/model-my-watershed,WikiWatershed/model-my-watershed
e3919de815594c73c35c265380c66ef14a51acbd
__init__.py
__init__.py
import sys import marshal import os.path if not hasattr(sys, 'implementation'): raise ImportError('Python 3.3 or newer is required') PY_TAG = sys.implementation.cache_tag PY_VERSION = sys.hexversion if PY_TAG is None: # Never seen this to be true, but Python documentation # mentions that it's possib...
import sys import marshal import os.path if not hasattr(sys, 'implementation'): raise ImportError('Python 3.3 or newer is required') if sys.implementation.cache_tag is None: raise ImportError('cannot load the bundle since module caching is disabled') PY_TAG = sys.implementation.cache_tag PY_VERSION = ...
Rewrite the initial bootstrapping mechanism.
Rewrite the initial bootstrapping mechanism.
Python
mit
pyos/dg