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
d220f56a72a6481b33e7c75acf2f92bb89c17561
app/utils/html.py
app/utils/html.py
from typing import Iterable, Tuple def gallery(samples: Iterable[Tuple[str, str]], *, refresh: bool = False) -> str: lines = [] for url, template in samples: if refresh: url += "?time=0" lines.append( f""" <a href="{template or url}"> <img s...
from typing import Iterable, Tuple def gallery(samples: Iterable[Tuple[str, str]], *, refresh: bool = False) -> str: lines = [] for url, template in samples: if refresh: url += "?time=0" else: url += "?width=300&height=300" lines.append( f""" ...
Use padding on the index
Use padding on the index
Python
mit
jacebrowning/memegen,jacebrowning/memegen
deb70e977ad59a84fbafe2251f60f2da1d4abf20
astral/api/app.py
astral/api/app.py
#!/usr/bin/env python import threading import tornado.httpserver import tornado.ioloop import tornado.web from astral.conf import settings from urls import url_patterns class NodeWebAPI(tornado.web.Application): def __init__(self): tornado.web.Application.__init__(self, url_patterns, **se...
#!/usr/bin/env python import threading import tornado.httpserver import tornado.ioloop import tornado.web from astral.conf import settings from urls import url_patterns class NodeWebAPI(tornado.web.Application): def __init__(self): tornado.web.Application.__init__(self, url_patterns, **se...
Use shortcut listen() for starting the HTTPServer.
Use shortcut listen() for starting the HTTPServer.
Python
mit
peplin/astral
06ae3ea593d4af5379307c2383e113000883db45
gooey/gui/application.py
gooey/gui/application.py
''' Main runner entry point for Gooey. ''' import wx # wx.html and wx.xml imports required here to make packaging with # pyinstaller on OSX possible without manually specifying `hidden_imports` # in the build.spec import wx.html import wx.xml import wx.richtext # Need to be imported before the wx.App object...
''' Main runner entry point for Gooey. ''' import wx # wx.html and wx.xml imports required here to make packaging with # pyinstaller on OSX possible without manually specifying `hidden_imports` # in the build.spec import wx.html import wx.xml import wx.richtext # Need to be imported before the wx.App object...
Use program_name instead of script file name in macOS menu
Use program_name instead of script file name in macOS menu
Python
mit
chriskiehl/Gooey
ad888e5c5423fcb2419c497597990868216edfe3
pubrunner/__init__.py
pubrunner/__init__.py
from pubrunner.command_line import * from pubrunner.upload import * from pubrunner.FTPClient import * from pubrunner.getresource import * from pubrunner.pubrun import pubrun,cleanWorkingDirectory from pubrunner.convert import * def loadYAML(yamlFilename): yamlData = None with open(yamlFilename,'r') as f: try: ...
from pubrunner.command_line import * from pubrunner.upload import * from pubrunner.FTPClient import * from pubrunner.getresource import * from pubrunner.pubrun import pubrun,cleanWorkingDirectory from pubrunner.convert import * from pubrunner.pubmed_hash import pubmed_hash def loadYAML(yamlFilename): yamlData = None...
Make pubmed hash accessible to API
Make pubmed hash accessible to API
Python
mit
jakelever/pubrunner,jakelever/pubrunner
74d0e710711f1b499ab32784b751adc55e8b7f00
python/bonetrousle.py
python/bonetrousle.py
#!/bin/python3 import os import sys # n: the integer number of sticks to buy # k: the integer number of box sizes the store carries # b: the integer number of boxes to buy def bonetrousle(n, k, b): if (minimumValue(k, b) <= n <= maximumValue(k, b)): return boxesToBuy(n, k, b) else: return -1 ...
#!/bin/python3 import os import sys # n: the integer number of sticks to buy # k: the integer number of box sizes the store carries # b: the integer number of boxes to buy def bonetrousle(n, k, b): if (minimumValue(k, b) <= n <= maximumValue(k, b)): return boxesToBuy(n, k, b) else: return -1 ...
Implement minimum and maximum values
Implement minimum and maximum values
Python
mit
rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank
7aa89902f8af2ca1f4b3c9e356a62062cc74696b
bot/anime_searcher.py
bot/anime_searcher.py
from itertools import chain from typing import Iterable from minoshiro import Medium, Minoshiro, Site from minoshiro.helpers import get_synonyms class AnimeSearcher(Minoshiro): async def get(self, query: str, medium: Medium, sites: Iterable[Site] = None, *, timeout=3): sites = sites if ...
from typing import Iterable from minoshiro import Medium, Minoshiro, Site from minoshiro.helpers import get_synonyms class AnimeSearcher(Minoshiro): async def get(self, query: str, medium: Medium, sites: Iterable[Site] = None, *, timeout=3): sites = sites if sites else list(Site) ...
Update anime searcher implementation to use super class methods
Update anime searcher implementation to use super class methods
Python
apache-2.0
MaT1g3R/YasenBaka
1ba0f715a0730dbc575bd1998f2edc69fab60fc5
project_task_add_very_high/__openerp__.py
project_task_add_very_high/__openerp__.py
# -*- coding: utf-8 -*- # Copyright 2016 Onestein (<http://www.onestein.eu>) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "Project Task Add Very High", "summary": "Adds an extra option 'Very High' on tasks", "version": "8.0.1.0.0", "author": "Onestein", "license": ...
# -*- coding: utf-8 -*- # Copyright 2016 Onestein (<http://www.onestein.eu>) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "Project Task Add Very High", "summary": "Adds an extra option 'Very High' on tasks", "version": "8.0.1.0.0", "author": "Onestein, Odoo Community A...
Add OCA in authors list
Add OCA in authors list
Python
agpl-3.0
ddico/project,OCA/project-service,dreispt/project-service,NeovaHealth/project-service,dreispt/project,acsone/project,acsone/project-service
729a814f976ceffba0092ba56efca8ccea06e6e6
apps/profiles/views.py
apps/profiles/views.py
from django.views.generic import DetailView, UpdateView from django.core.urlresolvers import reverse_lazy from braces.views import LoginRequiredMixin from .models import User from .forms import ProfileUpdateForm class ProfileDetailView(DetailView): ''' Displays the user profile information ''' model...
from django.views.generic import DetailView, UpdateView from django.core.urlresolvers import reverse_lazy from django.contrib import messages from django.utils.translation import ugettext_lazy as _ from braces.views import LoginRequiredMixin from .models import User from .forms import ProfileUpdateForm class Profil...
Add message on profile form save
Add message on profile form save
Python
mit
SoPR/horas,SoPR/horas,SoPR/horas,SoPR/horas
1892fc910e2a23971248121b44ff120ddc118270
src/sentry/api/authentication.py
src/sentry/api/authentication.py
from __future__ import absolute_import from django.contrib.auth.models import AnonymousUser from django.utils.crypto import constant_time_compare from rest_framework.authentication import BasicAuthentication from rest_framework.exceptions import AuthenticationFailed from sentry.models import ApiKey, ProjectKey clas...
from __future__ import absolute_import from django.contrib.auth.models import AnonymousUser from django.utils.crypto import constant_time_compare from rest_framework.authentication import BasicAuthentication from rest_framework.exceptions import AuthenticationFailed from sentry.app import raven from sentry.models imp...
Add API key to context
Add API key to context
Python
bsd-3-clause
fotinakis/sentry,daevaorn/sentry,hongliang5623/sentry,ngonzalvez/sentry,looker/sentry,fuziontech/sentry,mitsuhiko/sentry,felixbuenemann/sentry,kevinlondon/sentry,BuildingLink/sentry,kevinlondon/sentry,Natim/sentry,wujuguang/sentry,ewdurbin/sentry,kevinastone/sentry,alexm92/sentry,ifduyue/sentry,zenefits/sentry,drcapule...
b8850bd7d457ebb14220213d18a6aa779d64b547
nirum/validate.py
nirum/validate.py
""":mod:`nirum.validate` ~~~~~~~~~~~~~~~~~~~~~~~~ """ __all__ = 'validate_boxed_type', 'validate_record_type' def validate_boxed_type(boxed, type_hint): if not isinstance(boxed, type_hint): raise TypeError('{0} expected, found: {1}'.format(type_hint, ...
""":mod:`nirum.validate` ~~~~~~~~~~~~~~~~~~~~~~~~ """ __all__ = 'validate_boxed_type', 'validate_record_type' def validate_boxed_type(boxed, type_hint): if not isinstance(boxed, type_hint): raise TypeError('{0} expected, found: {1}'.format(type_hint, ...
Return its argument in validators
Return its argument in validators
Python
mit
spoqa/nirum-python,spoqa/nirum-python
1f884083b612637b64f26532c221b7341c3dda8c
services/voicedetection/voicedetection.py
services/voicedetection/voicedetection.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import angus.cloud conn = angus.connect() service = conn.services.get_service('voice_detection', version=1) job = service.process({'sound': open("./sound.wav", 'rb'), 'sensitivity':0.7}) print job.result
import angus.cloud conn = angus.connect() service = conn.services.get_service('voice_detection', version=1) job = service.process({'sound': open("./sound.wav", 'rb'), 'sensitivity':0.7}) print job.result
Clean script header in voice detection.
Clean script header in voice detection.
Python
apache-2.0
angus-ai/angus-doc,angus-ai/angus-doc,angus-ai/angus-doc
93956645792f92cffc11f4e2c72a8df1b0b82a02
tests/runalldoctests.py
tests/runalldoctests.py
import doctest import glob import pkg_resources try: pkg_resources.require('OWSLib') except (ImportError, pkg_resources.DistributionNotFound): pass testfiles = glob.glob('*.txt') for file in testfiles: doctest.testfile(file)
import doctest import getopt import glob import sys import pkg_resources try: pkg_resources.require('OWSLib') except (ImportError, pkg_resources.DistributionNotFound): pass def run(pattern): if pattern is None: testfiles = glob.glob('*.txt') else: testfiles = glob.glob(pattern) fo...
Add option to pick single test file from the runner
Add option to pick single test file from the runner
Python
bsd-3-clause
menegon/OWSLib,QuLogic/OWSLib,jachym/OWSLib,kwilcox/OWSLib,robmcmullen/OWSLib,KeyproOy/OWSLib,geopython/OWSLib,jaygoldfinch/OWSLib,JuergenWeichand/OWSLib,geographika/OWSLib,daf/OWSLib,ocefpaf/OWSLib,daf/OWSLib,bird-house/OWSLib,tomkralidis/OWSLib,datagovuk/OWSLib,dblodgett-usgs/OWSLib,b-cube/OWSLib,gfusca/OWSLib,mbertr...
5b8a39dc0fc5e383c30451a819c8e1542fd6f7ed
OpenSearchInNewTab.py
OpenSearchInNewTab.py
import re from threading import Timer import sublime_plugin import sublime DEFAULT_NAME = 'Find Results' ALT_NAME_BASE = 'Find Results ' class OpenSearchInNewTab(sublime_plugin.EventListener): # set a bit changed name # so the tab won't be bothered # during new search def on_activated(self, view): ...
import re from threading import Timer import sublime_plugin import sublime DEFAULT_NAME = 'Find Results' ALT_NAME_BASE = 'Find Results ' class OpenSearchInNewTab(sublime_plugin.EventListener): # set a bit changed name # so the tab won't be bothered # during new search def on_activated(self, view): ...
Remove unnecessary scratch file flag
Remove unnecessary scratch file flag
Python
mit
everyonesdesign/OpenSearchInNewTab
0a96055a08b27d195920ad88141676b02937e029
django_pytest/test_runner.py
django_pytest/test_runner.py
class TestRunner(object): def __init__(self, verbosity=1, interactive=True, failfast=True, **kwargs): self.verbosity = verbosity self.interactive = interactive self.failfast = failfast def run_tests(self, test_labels): import pytest import sys if test_labels is ...
class TestRunner(object): def __init__(self, verbosity=1, interactive=True, failfast=True, **kwargs): self.verbosity = verbosity self.interactive = interactive self.failfast = failfast def run_tests(self, test_labels, extra_tests=None): import pytest import sys ...
Make run_tests a function to make it fully backwards compatible
Make run_tests a function to make it fully backwards compatible
Python
bsd-3-clause
0101/django-pytest,buchuki/django-pytest
61677883825eefcbdc2b1c943b1ce33b26def264
PrinterApplication.py
PrinterApplication.py
from Cura.Wx.WxApplication import WxApplication from Cura.Wx.MainWindow import MainWindow class PrinterApplication(WxApplication): def __init__(self): super(PrinterApplication, self).__init__() def run(self): window = MainWindow("Cura Printer") window.Show() super(Print...
from Cura.Wx.WxApplication import WxApplication from Cura.Wx.MainWindow import MainWindow class PrinterApplication(WxApplication): def __init__(self): super(PrinterApplication, self).__init__() def run(self): self._plugin_registry.loadPlugins({ "type": "StorageDevice" }) ...
Load all storage plugins in the printer application
Load all storage plugins in the printer application
Python
agpl-3.0
totalretribution/Cura,Curahelper/Cura,senttech/Cura,lo0ol/Ultimaker-Cura,markwal/Cura,fieldOfView/Cura,ynotstartups/Wanhao,ynotstartups/Wanhao,quillford/Cura,bq/Ultimaker-Cura,ad1217/Cura,derekhe/Cura,senttech/Cura,hmflash/Cura,Curahelper/Cura,lo0ol/Ultimaker-Cura,DeskboxBrazil/Cura,derekhe/Cura,DeskboxBrazil/Cura,tota...
e6ef3a1c609de227bff34a811910f08b3e5e69c9
Lib/sandbox/pyem/__init__.py
Lib/sandbox/pyem/__init__.py
#! /usr/bin/env python # Last Change: Sat Jun 09 10:00 PM 2007 J from info import __doc__ from gauss_mix import GmParamError, GM from gmm_em import GmmParamError, GMM, EM #from online_em import OnGMM as _OnGMM #import examples as _examples __all__ = filter(lambda s:not s.startswith('_'), dir()) from numpy.testing i...
#! /usr/bin/env python # Last Change: Sun Jul 22 11:00 AM 2007 J raise ImportError( """pyem has been moved to scikits and renamed to em. Please install scikits.learn instead, and change your import to the following: from scickits.learn.machine import em.""") from info import __doc__ from gauss_mix import GmParamErr...
Raise an import error when importing pyem as it has been moved to scikits.
Raise an import error when importing pyem as it has been moved to scikits. git-svn-id: 003f22d385e25de9cff933a5ea4efd77cb5e7b28@3179 d6536bca-fef9-0310-8506-e4c0a848fbcf
Python
bsd-3-clause
scipy/scipy-svn,lesserwhirls/scipy-cwt,jasonmccampbell/scipy-refactor,lesserwhirls/scipy-cwt,lesserwhirls/scipy-cwt,scipy/scipy-svn,jasonmccampbell/scipy-refactor,scipy/scipy-svn,jasonmccampbell/scipy-refactor,scipy/scipy-svn,jasonmccampbell/scipy-refactor,lesserwhirls/scipy-cwt
e7ee29f03dd83a795828de92aba654e9a7db3dd4
deflect/views.py
deflect/views.py
from __future__ import unicode_literals import base32_crockford import logging from django.db.models import F from django.http import Http404 from django.http import HttpResponsePermanentRedirect from django.shortcuts import get_object_or_404 from django.utils.timezone import now from .models import RedirectURL from...
from __future__ import unicode_literals import base32_crockford import logging from django.db.models import F from django.http import Http404 from django.http import HttpResponsePermanentRedirect from django.shortcuts import get_object_or_404 from django.utils.timezone import now from .models import RedirectURL from...
Improve comment and logging text
Improve comment and logging text
Python
bsd-3-clause
jbittel/django-deflect
3ba8af66d0c6ebbdd4a3799b819a72292da2c6c5
netmiko/citrix/netscaler_ssh.py
netmiko/citrix/netscaler_ssh.py
import time from netmiko.base_connection import BaseConnection class NetscalerSSH(BaseConnection): """ Netscaler SSH class. """ def session_preparation(self): """Prepare the session after the connection has been established.""" # 0 will defer to the global delay factor delay_factor ...
import time from netmiko.base_connection import BaseConnection class NetscalerSSH(BaseConnection): """ Netscaler SSH class. """ def session_preparation(self): """Prepare the session after the connection has been established.""" # 0 will defer to the global delay factor delay_factor ...
Make return character an attribute
Make return character an attribute
Python
mit
ktbyers/netmiko,ktbyers/netmiko
62017dc7dc210d09e8f6753ad86365ac679f4a0a
oscar/apps/catalogue/categories.py
oscar/apps/catalogue/categories.py
from django.db.models import get_model Category = get_model('catalogue', 'category') def create_from_sequence(bits): """ Create categories from an iterable """ if len(bits) == 1: # Get or create root node try: root = Category.objects.get(depth=1, name=bits[0]) exce...
from django.db.models import get_model Category = get_model('catalogue', 'category') def create_from_sequence(bits): """ Create categories from an iterable """ if len(bits) == 1: # Get or create root node name = bits[0] try: # Category names should be unique at the...
Rework category creation from breadcrumbs
Rework category creation from breadcrumbs We now handle MultipleObjectsReturned exceptions, which are possible as we are looking up based on non-unique filters.
Python
bsd-3-clause
vovanbo/django-oscar,adamend/django-oscar,MatthewWilkes/django-oscar,manevant/django-oscar,django-oscar/django-oscar,WadeYuChen/django-oscar,elliotthill/django-oscar,sasha0/django-oscar,WillisXChen/django-oscar,jinnykoo/wuyisj,Jannes123/django-oscar,makielab/django-oscar,WadeYuChen/django-oscar,lijoantony/django-oscar,...
09102cb87c41330d1ae670f0e1cea00037c74b5b
src/librement/profile/models.py
src/librement/profile/models.py
from django.db import models from django_enumfield import EnumField from librement.utils.user_data import PerUserData from .enums import AccountEnum, CountryEnum class Profile(PerUserData('profile')): account_type = EnumField(AccountEnum) organisation = models.CharField(max_length=100, blank=True) add...
from django.db import models from django_enumfield import EnumField from librement.utils.user_data import PerUserData from .enums import AccountEnum, CountryEnum class Profile(PerUserData('profile')): account_type = EnumField(AccountEnum) organisation = models.CharField(max_length=100, blank=True) add...
Add model for storing multiple email addresses.
Add model for storing multiple email addresses. Signed-off-by: Chris Lamb <29e6d179a8d73471df7861382db6dd7e64138033@debian.org>
Python
agpl-3.0
rhertzog/librement,rhertzog/librement,rhertzog/librement
402d30d840e7e1d8885412cce7bee2897150a1cf
widelanguagedemo/public/views.py
widelanguagedemo/public/views.py
# -*- coding: utf-8 -*- # # views.py # wide-language-index-demo # """ Public facing frontpage. """ import json import random from flask import (Blueprint, request, render_template, redirect) from . import forms from ..index import util blueprint = Blueprint('public', __name__, static_folder="../static") @bluep...
# -*- coding: utf-8 -*- # # views.py # wide-language-index-demo # """ Public facing frontpage. """ import json import random from flask import (Blueprint, request, render_template, redirect) from . import forms from ..index import util blueprint = Blueprint('public', __name__, static_folder="../static") @bluep...
Fix an error when no samples were found.
Fix an error when no samples were found.
Python
bsd-3-clause
larsyencken/wide-language-demo,larsyencken/wide-language-demo,larsyencken/wide-language-demo,larsyencken/wide-language-demo,larsyencken/wide-language-demo
cbd6097cc070967963587441e6fdcf40f7c5293b
st2common/st2common/jinja/filters/data.py
st2common/st2common/jinja/filters/data.py
# Licensed to the StackStorm, Inc ('StackStorm') under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use th...
# Licensed to the StackStorm, Inc ('StackStorm') under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use th...
Set default_flow_style for yaml jinja filter
Set default_flow_style for yaml jinja filter
Python
apache-2.0
Plexxi/st2,nzlosh/st2,lakshmi-kannan/st2,StackStorm/st2,lakshmi-kannan/st2,tonybaloney/st2,StackStorm/st2,Plexxi/st2,nzlosh/st2,tonybaloney/st2,peak6/st2,tonybaloney/st2,StackStorm/st2,peak6/st2,nzlosh/st2,StackStorm/st2,peak6/st2,nzlosh/st2,lakshmi-kannan/st2,Plexxi/st2,Plexxi/st2
042720760a71b5e372489af2335c2fccc5b4905b
ynr/apps/uk_results/views/api.py
ynr/apps/uk_results/views/api.py
from rest_framework import viewsets from django_filters import filters, filterset from api.v09.views import ResultsSetPagination from ..models import CandidateResult, ResultSet from ..serializers import CandidateResultSerializer, ResultSetSerializer class CandidateResultViewSet(viewsets.ModelViewSet): queryset ...
from rest_framework import viewsets from django_filters import filters, filterset from api.v09.views import ResultsSetPagination from ..models import CandidateResult, ResultSet from ..serializers import CandidateResultSerializer, ResultSetSerializer class CandidateResultViewSet(viewsets.ModelViewSet): queryset ...
Update filter args and fix name
Update filter args and fix name The newer version of django-filter uses `field_name` rather than `name`
Python
agpl-3.0
DemocracyClub/yournextrepresentative,DemocracyClub/yournextrepresentative,DemocracyClub/yournextrepresentative
853108e1c5cd9fca27d0f1dc8324b4b2a4d4b871
pyqode/python/plugins/pyqode_python_plugin.py
pyqode/python/plugins/pyqode_python_plugin.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # # pyQode - Python/Qt Code Editor widget # Copyright 2013, Colin Duquesnoy <colin.duquesnoy@gmail.com> # # This software is released under the LGPLv3 license. # You should have received a copy of the GNU Lesser General Public License # along with this program. If not, see ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # # pyQode - Python/Qt Code Editor widget # Copyright 2013, Colin Duquesnoy <colin.duquesnoy@gmail.com> # # This software is released under the LGPLv3 license. # You should have received a copy of the GNU Lesser General Public License # along with this program. If not, see ...
Fix bug with python plugin and pyside
Fix bug with python plugin and pyside
Python
mit
pyQode/pyqode.python,mmolero/pyqode.python,pyQode/pyqode.python,zwadar/pyqode.python
e9605bd92e67c7f5daf7011f871c3a9d915abe76
core/urls/base.py
core/urls/base.py
from django.conf.urls import patterns, url, include from django.conf.urls.static import static from core.views import Home, register # Use this file to import all other url from game_website import settings urlpatterns = patterns( # Examples: # url(r'^blog/', include('blog.urls')), '', url(r'^$', Home...
from django.conf.urls import patterns, url, include from django.conf.urls.static import static from core.views import Home, register # Use this file to import all other url from game_website import settings urlpatterns = patterns( # Examples: # url(r'^blog/', include('blog.urls')), '', url(r'^$', Home...
Make logout redirect to home
Make logout redirect to home
Python
mit
joshsamara/game-website,joshsamara/game-website,joshsamara/game-website
198181baa0b095d120b456e7191c0c49c98b3c03
conans/client/generators/xcode.py
conans/client/generators/xcode.py
from conans.model import Generator from conans.paths import BUILD_INFO_XCODE class XCodeGenerator(Generator): template = ''' HEADER_SEARCH_PATHS = $(inherited) {include_dirs} LIBRARY_SEARCH_PATHS = $(inherited) {lib_dirs} OTHER_LDFLAGS = $(inherited) {linker_flags} {libs} GCC_PREPROCESSOR_DEFINITIONS = $(inheri...
from conans.model import Generator from conans.paths import BUILD_INFO_XCODE class XCodeGenerator(Generator): template = ''' HEADER_SEARCH_PATHS = $(inherited) {include_dirs} LIBRARY_SEARCH_PATHS = $(inherited) {lib_dirs} OTHER_LDFLAGS = $(inherited) {linker_flags} {libs} GCC_PREPROCESSOR_DEFINITIONS = $(inheri...
Fix copy and paste error
Fix copy and paste error
Python
mit
conan-io/conan,conan-io/conan,luckielordie/conan,dragly/conan,lasote/conan,dragly/conan,tivek/conan,luckielordie/conan,memsharded/conan,conan-io/conan,memsharded/conan,birsoyo/conan,lasote/conan,memsharded/conan,mropert/conan,Xaltotun/conan,memsharded/conan,Xaltotun/conan,mropert/conan,birsoyo/conan,tivek/conan
80bb5557f78268545139cd37f593278e35979fd5
corehq/mobile_flags.py
corehq/mobile_flags.py
from collections import namedtuple MobileFlag = namedtuple('MobileFlag', 'slug label') MULTIPLE_APPS_UNLIMITED = MobileFlag( 'multiple_apps_unlimited', 'Enable unlimited multiple apps' )
from collections import namedtuple MobileFlag = namedtuple('MobileFlag', 'slug label') MULTIPLE_APPS_UNLIMITED = MobileFlag( 'multiple_apps_unlimited', 'Enable unlimited multiple apps' ) ADVANCED_SETTINGS_ACCESS = MobileFlag( 'advanced_settings_access', 'Enable access to advanced settings' )
Add Flag enum for settings access
Add Flag enum for settings access
Python
bsd-3-clause
dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq
26e2feb6f2dfe74ade46cf871167101599c0acba
app/timetables/models.py
app/timetables/models.py
from __future__ import unicode_literals from django.db import models from common.mixins import ForceCapitalizeMixin class Weekday(ForceCapitalizeMixin, models.Model): """Model representing the day of the week.""" name = models.CharField(max_length=60, unique=True) capitalized_field_names = ('name',) ...
from __future__ import unicode_literals from django.db import models from django.core.exceptions import ValidationError from django.utils.translation import ugettext_lazy as _ from common.mixins import ForceCapitalizeMixin class Weekday(ForceCapitalizeMixin, models.Model): """Model representing the day of the w...
Update clean method to ensure that meal end_time is not same as or less than meal start_time
Update clean method to ensure that meal end_time is not same as or less than meal start_time
Python
mit
teamtaverna/core
922c6350fda965068927611348bdd9127ee405d9
scaffolder/commands/vcs.py
scaffolder/commands/vcs.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from optparse import make_option from optparse import OptionParser from scaffolder.core.commands import BaseCommand from scaffolder.vcs import VCS class VcsCommand(BaseCommand): option_list = BaseCommand.option_list + ( make_option( "-u", ...
#!/usr/bin/env python # -*- coding: utf-8 -*- from optparse import make_option from optparse import OptionParser from scaffolder.core.commands import BaseCommand from scaffolder.vcs import VCS class VcsCommand(BaseCommand): option_list = BaseCommand.option_list + ( make_option( "-u", ...
Remove __init__ method, not needed.
VcsCommand: Remove __init__ method, not needed.
Python
mit
goliatone/minions
7d6ecfe52f60ac07c57bbd6e966cded11ce40e4c
scripts/hydrafw-version.py
scripts/hydrafw-version.py
import sys from optparse import OptionParser from datetime import * from git import * if __name__=="__main__": usage = """ %prog outfile.txt""" parser = OptionParser(usage=usage) (options, args) = parser.parse_args() if len(args)==1: sys.stdout = open(args[0], 'w') git=Repo().git print '#define HYDRAFW_GIT_TA...
import sys from optparse import OptionParser from datetime import * from git import * if __name__=="__main__": usage = """ %prog outfile.txt""" parser = OptionParser(usage=usage) (options, args) = parser.parse_args() if len(args)==1: sys.stdout = open(args[0], 'w') git=Repo().git print '#define HYDRAFW_GIT_TA...
Fix python script dirty flag for firmware version
Fix python script dirty flag for firmware version
Python
apache-2.0
Baldanos/hydrafw,hydrabus/hydrafw,hydrabus/hydrafw,hydrabus/hydrafw,Baldanos/hydrafw,Baldanos/hydrafw
7420d9208067f5144b301ff00d962b0b84e2a0f3
tinymce/settings.py
tinymce/settings.py
import os from django.conf import settings DEFAULT_CONFIG = getattr(settings, 'TINYMCE_DEFAULT_CONFIG', {'theme': "simple", 'relative_urls': False}) USE_SPELLCHECKER = getattr(settings, 'TINYMCE_SPELLCHECKER', False) USE_COMPRESSOR = getattr(settings, 'TINYMCE_COMPRESSOR', False) USE_FILEBROWSER = getattr(s...
import os from django.conf import settings DEFAULT_CONFIG = getattr(settings, 'TINYMCE_DEFAULT_CONFIG', {'theme': "simple", 'relative_urls': False}) USE_SPELLCHECKER = getattr(settings, 'TINYMCE_SPELLCHECKER', False) USE_COMPRESSOR = getattr(settings, 'TINYMCE_COMPRESSOR', False) USE_FILEBROWSER = getattr(s...
Use STATIC_URL/STATIC_ROOT when using django.contrib.staticfiles (django 1.3)
Use STATIC_URL/STATIC_ROOT when using django.contrib.staticfiles (django 1.3)
Python
mit
pterk/django-tinymce,pterk/django-tinymce
287609cc21ae7024507a662b2afe13520fdf8eb7
tests/test_mysql.py
tests/test_mysql.py
import unittest import logging; logger = logging.getLogger() from checks.db.mysql import MySql class TestMySql(unittest.TestCase): def setUp(self): # This should run on pre-2.7 python so no skiptest try: import MySQLdb self.mysql = MySql(logger) except ImportError: ...
import unittest import logging; logger = logging.getLogger() from checks.db.mysql import MySql from tests.common import load_check import time class TestMySql(unittest.TestCase): def testChecks(self): agentConfig = { 'mysql_server': 'localhost', 'mysql_user': "datadog", 'mysql_pas...
Fix mysql check to use checks.d version
Fix mysql check to use checks.d version
Python
bsd-3-clause
eeroniemi/dd-agent,indeedops/dd-agent,relateiq/dd-agent,Shopify/dd-agent,remh/dd-agent,huhongbo/dd-agent,darron/dd-agent,jamesandariese/dd-agent,jraede/dd-agent,eeroniemi/dd-agent,urosgruber/dd-agent,jvassev/dd-agent,eeroniemi/dd-agent,polynomial/dd-agent,lookout/dd-agent,jvassev/dd-agent,Mashape/dd-agent,Shopify/dd-ag...
5b99fa7adf8ce65309f47d6456ecba32b02995a4
tests/utils.py
tests/utils.py
import os import sphinx_tests_util from xml.etree import ElementTree from xml.dom import minidom # ============================================================================= # Utility functions def srcdir(name): test_root = os.path.abspath(os.path.dirname(__file__)) return os.path.join(test_r...
import os import sphinx_tests_util from xml.etree import ElementTree from xml.dom import minidom # ============================================================================= # Utility functions def srcdir(name): test_root = os.path.abspath(os.path.dirname(__file__)) return os.path.join(test_r...
Use fresh build environment by default in tests
Use fresh build environment by default in tests
Python
apache-2.0
t4ngo/sphinxcontrib-traceables
f54fd0bf65d731b4f25cfc2ddffb8d6f472e0d7c
examples/eiger_use_case.py
examples/eiger_use_case.py
'''Virtual datasets: The 'Eiger' use case https://support.hdfgroup.org/HDF5/docNewFeatures/VDS/HDF5-VDS-requirements-use-cases-2014-12-10.pdf ''' import h5py import numpy as np files = ['1.h5', '2.h5', '3.h5', '4.h5', '5.h5'] entry_key = 'data' # where the data is inside of the source files. sh = h5py.File(files[0]...
'''Virtual datasets: The 'Eiger' use case https://support.hdfgroup.org/HDF5/docNewFeatures/VDS/HDF5-VDS-requirements-use-cases-2014-12-10.pdf ''' import h5py import numpy as np files = ['1.h5', '2.h5', '3.h5', '4.h5', '5.h5'] entry_key = 'data' # where the data is inside of the source files. sh = h5py.File(files[0]...
Fix layout for Eiger example
Fix layout for Eiger example
Python
bsd-3-clause
h5py/h5py,h5py/h5py,h5py/h5py
dd2c92bea635d7cfc93b437ce32266126bceb1e9
qipipe/helpers/bolus_arrival.py
qipipe/helpers/bolus_arrival.py
class BolusArrivalError(Exception): pass def bolus_arrival_index(time_series): """ Determines the DCE bolus arrival series index. The bolus arrival is the first series with a difference in average signal larger than double the difference from first two points. :param time_series: the 4D NiFT...
class BolusArrivalError(Exception): pass def bolus_arrival_index(time_series): """ Determines the DCE bolus arrival time point index. The bolus arrival is the first occurence of a difference in average signal larger than double the difference from first two points. :param time_series: the 4D...
Change series to time point.
Change series to time point.
Python
bsd-2-clause
ohsu-qin/qipipe
ffd1ba9eee804fdd55e86908b158a4ad94f2f366
Tools/idle/ZoomHeight.py
Tools/idle/ZoomHeight.py
# Sample extension: zoom a window to maximum height import re import sys class ZoomHeight: menudefs = [ ('windows', [ ('_Zoom Height', '<<zoom-height>>'), ]) ] windows_keydefs = { '<<zoom-height>>': ['<Alt-F2>'], } unix_keydefs = { '<<zoom-height>>': ...
# Sample extension: zoom a window to maximum height import re import sys class ZoomHeight: menudefs = [ ('windows', [ ('_Zoom Height', '<<zoom-height>>'), ]) ] windows_keydefs = { '<<zoom-height>>': ['<Alt-F2>'], } unix_keydefs = { '<<zoom-height>>': ...
Use only the height to decide whether to zoom in or out.
Use only the height to decide whether to zoom in or out.
Python
mit
sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator
1d0570ca75419f441aa1324de78051534efba74b
search_engine.py
search_engine.py
import requests from bs4 import BeautifulSoup def download_url(url): r = requests.get(url) if r.status_code != 200: raise Exception('Non-OK status code: {}'.format(r.status_code)) return r.text def parse_text(html): bs = BeautifulSoup(html, 'html.parser') return bs.select('div.usertext-b...
import requests from bs4 import BeautifulSoup import os.path from base64 import b16encode import time def download_reddit_url(url): assert url.startswith('https://www.reddit.com/r/learnprogramming') headers = {'User-Agent':'JustSearch bot version 0.1'} r = requests.get(url, headers=headers) if r.statu...
Create files with posts and can go to the next page.
Create files with posts and can go to the next page.
Python
mit
tori-smile/JustSearch
f2294b289b6eaa9c103f667dd3252429aac360e1
tools/miranda/miranda_parser.py
tools/miranda/miranda_parser.py
import sys # get hits from miranda scans cap = "" with open (sys.argv[1]) as infile1: for line1 in infile1: line1 = line1.strip() if "%" in line1 and "Forward:" not in line1: #print(line1) cap = cap + line1 + "\n" allregnettf = open(sys.argv[2], "w") allregnettf.write(cap) a...
import sys # get hits from miranda scans with open(sys.argv[1]) as infile1: with open(sys.argv[2], "w") as outfile: for line1 in infile1: if "%" in line1 and "Forward:" not in line1: outfile.write(line1)
Write output on the file.
Write output on the file.
Python
mit
anilthanki/tgac-galaxytools,TGAC/earlham-galaxytools,anilthanki/tgac-galaxytools,TGAC/earlham-galaxytools,TGAC/earlham-galaxytools,TGAC/earlham-galaxytools,TGAC/tgac-galaxytools,PerlaTroncosoRey/tgac-galaxytools,wjurkowski/earlham-galaxytools,TGAC/tgac-galaxytools,anilthanki/tgac-galaxytools,anilthanki/tgac-galaxytools...
d70e563c3119e59de2ae23a77724e0fd803b768b
Python/tests.py
Python/tests.py
import unittest from BKKCrypt import BKKCrypt import urllib.request class TestEncodeStrings(unittest.TestCase): def test_simple_strings(self): self.assertEqual(BKKCrypt('adminadmin'), 'adminadmin') self.assertEqual(BKKCrypt('hunter2'), 'hunter2') self.assertEqual(BKKCrypt('password'), 'pas...
import unittest from BKKCrypt import BKKCrypt import urllib.request class TestEncodeStrings(unittest.TestCase): def test_simple_strings(self): self.assertEqual(BKKCrypt('adminadmin'), 'adminadmin') self.assertEqual(BKKCrypt('hunter2'), 'hunter2') self.assertEqual(BKKCrypt('password'), 'pas...
Remove trailing newlines from test cases
Remove trailing newlines from test cases
Python
mit
moszinet/BKKCrypt,moszinet/BKKCrypt,moszinet/BKKCrypt,moszinet/BKKCrypt,moszinet/BKKCrypt,moszinet/BKKCrypt,moszinet/BKKCrypt,moszinet/BKKCrypt,moszinet/BKKCrypt,moszinet/BKKCrypt,moszinet/BKKCrypt,moszinet/BKKCrypt,moszinet/BKKCrypt,moszinet/BKKCrypt,moszinet/BKKCrypt,moszinet/BKKCrypt,moszinet/BKKCrypt,moszinet/BKKCr...
45542f012b3dc6d089bc991529523a4ea6401b35
br_rss/boilerroomtv/management/commands/scrape_all.py
br_rss/boilerroomtv/management/commands/scrape_all.py
from django.core.management.base import BaseCommand from boilerroomtv.tasks import scrape_genres, scrape_all_recordings, scrape_channels class Command(BaseCommand): def handle(self, *args, **options): scrape_genres() scrape_all_recordings() scrape_channels()
from django.core.management.base import BaseCommand from ...tasks import scrape_genres, scrape_all_recordings, scrape_channels class Command(BaseCommand): def handle(self, *args, **options): scrape_genres() scrape_all_recordings() scrape_channels()
Use relative import in command.
Use relative import in command.
Python
mpl-2.0
jeffbr13/br-rss,jeffbr13/br-rss
d3f0d83b0c783d2f15a6f5eaf6fd4ace426307a6
tests/__init__.py
tests/__init__.py
import os import sys import unittest def suite(): MODULE_DIR = os.path.join(os.path.dirname(__file__), '..') MODULE_DIR = os.path.abspath(MODULE_DIR) sys.path.insert(0, MODULE_DIR) sys.path.insert(0, os.path.dirname(__file__)) SUB_UNITS = os.path.dirname(__file__) SUB_UNITS = os.listdir(SUB_U...
from os import walk, chdir from os.path import join, dirname, splitext, abspath, relpath import sys import unittest MODULE_DIR = join(dirname(__file__), '..') MODULE_DIR = abspath(MODULE_DIR) def walker(opath='.'): for path, folders, files in walk(opath): for filename in files: if filename.st...
Rework for tests in subdirectories
Rework for tests in subdirectories
Python
mit
Mause/pytransperth,Mause/pytransperth
db0ef5f31d82729f654d1d07fa39c1168aa5e5f7
tests/__init__.py
tests/__init__.py
# -*- coding: utf-8 -*- # # (C) Pywikipedia bot team, 2007 # # Distributed under the terms of the MIT license. # __version__ = '$Id$' import os import pywikibot.data.api from pywikibot.data.api import Request as _original_Request from pywikibot.data.api import CachedRequest class TestRequest(CachedRequest): def...
# -*- coding: utf-8 -*- # # (C) Pywikipedia bot team, 2007 # # Distributed under the terms of the MIT license. # __version__ = '$Id$' import os import pywikibot.data.api from pywikibot.data.api import Request as _original_Request from pywikibot.data.api import CachedRequest class TestRequest(CachedRequest): def...
Disable printing of API parameters which could leak private info and were generally not useful
Disable printing of API parameters which could leak private info and were generally not useful Change-Id: I8a8a8d10799df4f61e4465fe60b6c7efbefbd962
Python
mit
npdoty/pywikibot,PersianWikipedia/pywikibot-core,trishnaguha/pywikibot-core,jayvdb/pywikibot-core,emijrp/pywikibot-core,wikimedia/pywikibot-core,xZise/pywikibot-core,happy5214/pywikibot-core,hasteur/g13bot_tools_new,jayvdb/pywikibot-core,magul/pywikibot-core,h4ck3rm1k3/pywikibot-core,TridevGuha/pywikibot-core,hasteur/g...
96776b33fcf2ebbd2de4748c38d8be9c63fdec71
tests/conftest.py
tests/conftest.py
from django.conf import settings from django.core.management import call_command def pytest_configure(): settings.configure( ROOT_URLCONF='tests.urls', ALLOWED_HOSTS=['testserver'], DATABASES={ 'default': { 'ENGINE': 'django.db.backends.sqlite3', ...
from django.conf import settings from django.core.management import call_command def pytest_configure(): settings.configure( ROOT_URLCONF='tests.urls', ALLOWED_HOSTS=['testserver'], DATABASES={ 'default': { 'ENGINE': 'django.db.backends.sqlite3', ...
Replace --noinput with interactive=False in syncdb command call
Replace --noinput with interactive=False in syncdb command call
Python
bsd-2-clause
yprez/django-rest-assured,pombredanne/django-rest-assured,ydaniv/django-rest-assured
40711cb50189c4c39ed5a60c16910646a00f9acc
docker/types/daemon.py
docker/types/daemon.py
import socket try: import requests.packages.urllib3 as urllib3 except ImportError: import urllib3 class CancellableStream(object): """ Stream wrapper for real-time events, logs, etc. from the server. Example: >>> events = client.events() >>> for event in events: ... pri...
import socket try: import requests.packages.urllib3 as urllib3 except ImportError: import urllib3 class CancellableStream(object): """ Stream wrapper for real-time events, logs, etc. from the server. Example: >>> events = client.events() >>> for event in events: ... pri...
Fix cancellable streams on Windows clients + HTTPS transport
Fix cancellable streams on Windows clients + HTTPS transport Signed-off-by: Joffrey F <2e95f49799afcec0080c0aeb8813776d949e0768@docker.com>
Python
apache-2.0
youhong316/docker-py,docker/docker-py,funkyfuture/docker-py,funkyfuture/docker-py,docker/docker-py,vdemeester/docker-py,youhong316/docker-py,vdemeester/docker-py
07b7efdc848deeb7634f23cdb878774a99c9c535
ambassador/tests/t_grpc_bridge.py
ambassador/tests/t_grpc_bridge.py
import json from kat.harness import Query from abstract_tests import AmbassadorTest, ServiceType, EGRPC class AcceptanceGrpcBridgeTest(AmbassadorTest): target: ServiceType def init(self): self.target = EGRPC() def config(self): yield self, self.format(""" --- apiVersion: ambassador/v0 ...
from kat.harness import Query from abstract_tests import AmbassadorTest, ServiceType, EGRPC class AcceptanceGrpcBridgeTest(AmbassadorTest): target: ServiceType def init(self): self.target = EGRPC() def config(self): yield self, self.format(""" --- apiVersion: ambassador/v0 kind: Module...
Clean up existing gRPC bridge test (make it like t_tcpmapping.py)
Clean up existing gRPC bridge test (make it like t_tcpmapping.py) - Remove redundant HTTP status assertions - Adjust formatting - Remove unused import
Python
apache-2.0
datawire/ambassador,datawire/ambassador,datawire/ambassador,datawire/ambassador,datawire/ambassador
957422118d31def826d336f26152de1d0399fe4e
py/src/ai/h2o/sparkling/H2OConf.py
py/src/ai/h2o/sparkling/H2OConf.py
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not us...
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not us...
Remove deprecated method H2OContext.getOrCreate with sparkSession or SparkContext argument
[SW-1971][FollowUp] Remove deprecated method H2OContext.getOrCreate with sparkSession or SparkContext argument
Python
apache-2.0
h2oai/sparkling-water,h2oai/sparkling-water,h2oai/sparkling-water,h2oai/sparkling-water
daf68a1475530f4f0cb2e78e2ccf6ecbca821a8e
rfb_utils/prefs_utils.py
rfb_utils/prefs_utils.py
from ..rman_constants import RFB_PREFS_NAME import bpy def get_addon_prefs(): try: addon = bpy.context.preferences.addons[RFB_PREFS_NAME] return addon.preferences except: return None def get_pref(pref_name='', default=None): """ Return the value of a preference Args: p...
from ..rman_constants import RFB_PREFS_NAME import bpy def get_addon_prefs(): try: addon = bpy.context.preferences.addons[RFB_PREFS_NAME] return addon.preferences except: # try looking for all variants of RFB_PREFS_NAME for k, v in bpy.context.preferences.addons.items(): ...
Add some fallback code when looking for our prefs object.
Add some fallback code when looking for our prefs object.
Python
mit
prman-pixar/RenderManForBlender,adminradio/RenderManForBlender,prman-pixar/RenderManForBlender
753b2b6d04d0808e92dec0337d75a821d171e8e6
sahara/tests/__init__.py
sahara/tests/__init__.py
# Copyright (c) 2014 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) 2014 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...
Apply monkeypatching from eventlet before the tests starts
Apply monkeypatching from eventlet before the tests starts This should prevent issues with classes which may not have been otherwise instrumented (and sahara_engine and sahara_all do the instrumentation at the beginning anyway). Issues have been notices with eventlet 0.20.1 which now instruments subprocess. Change-I...
Python
apache-2.0
openstack/sahara,openstack/sahara
901bd73c61fbc6d9d8971ec1ce12e64100e633cb
base/settings/testing.py
base/settings/testing.py
# -*- coding: utf-8 -*- import os from .base import Base as Settings class Testing(Settings): # Database Configuration. # ------------------------------------------------------------------ DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME...
# -*- coding: utf-8 -*- import os from .base import Base as Settings class Testing(Settings): # Database Configuration. # ------------------------------------------------------------------ DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME...
Fix the Celery configuration under test settings.
Fix the Celery configuration under test settings.
Python
apache-2.0
hello-base/web,hello-base/web,hello-base/web,hello-base/web
0b152333c30d061df64376bb036c5fcd20896c36
go/billing/urls.py
go/billing/urls.py
from django.conf.urls import patterns, url from go.billing import views urlpatterns = patterns( '', url( r'^(?P<statement_id>[\d]+)', views.statement_view, name='pdf_statement') )
from django.conf.urls import patterns, url from go.billing import views urlpatterns = patterns( '', url( r'^statement/(?P<statement_id>[\d]+)', views.statement_view, name='pdf_statement') )
Move statement PDF URL off the root of the billing URL namespace.
Move statement PDF URL off the root of the billing URL namespace.
Python
bsd-3-clause
praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go
86ec56b0de1e822af2e03fedd2a67a3c555a7d18
versebot/regex.py
versebot/regex.py
""" VerseBot for reddit By Matthieu Grieger regex.py Copyright (c) 2015 Matthieu Grieger (MIT License) """ import re def find_verses(message_body): """ Uses regex to search comment body for verse quotations. Returns a list of matches if found, None otherwise. """ regex = (r"(?<=\[)(?P<book>[\d\w\s]+)...
""" VerseBot for reddit By Matthieu Grieger regex.py Copyright (c) 2015 Matthieu Grieger (MIT License) """ import re def find_verses(message_body): """ Uses regex to search comment body for verse quotations. Returns a list of matches if found, None otherwise. """ regex = (r"(?<=\[)(?P<book>[\d\w\s]+)...
Fix return value from find_verses()
Fix return value from find_verses()
Python
mit
Matthew-Arnold/slack-versebot,Matthew-Arnold/slack-versebot
9bebf1c0cc9c0a03cde23fb1b92ae983f1fc3fa8
examples/check_args.py
examples/check_args.py
from __future__ import print_function @check.arg(0, check.int_value(min=0)) @check.arg(1, check.int_value(min=0)) def add_positive_integers(int1, int2): return int1 + int2 def main(): print(add_positive_integers(1, 5)) print(add_positive_integers(0, 5)) print(add_positive_integers(-1, 5)) if __nam...
from __future__ import print_function from collections import defaultdict def check_arg(arg_id, *constraints): return ArgCheckAdder(arg_id, *constraints) def check_int_value(min=None, max=None): def constraint(arg_id, args, kwargs): assert isinstance(args[arg_id], int) assert args[arg_id] >=...
Make isolated arg check example
Make isolated arg check example
Python
mit
explosion/thinc,explosion/thinc,explosion/thinc,spacy-io/thinc,spacy-io/thinc,spacy-io/thinc,explosion/thinc
f58cce56103b98e783fa0df5bae0ae0985f7dc8e
rmake_plugins/multinode_client/nodetypes.py
rmake_plugins/multinode_client/nodetypes.py
import inspect import sys import types from rmake.lib.apiutils import thaw, freeze class NodeType(object): nodeType = 'UNKNOWN' def __init__(self): pass def freeze(self): return (self.nodeType, self.__dict__) @classmethod def thaw(class_, d): return class_(**d) class Cli...
import inspect import sys import types from rmake.lib.apiutils import thaw, freeze _nodeTypes = {} class _NodeTypeRegistrar(type): def __init__(self, name, bases, dict): type.__init__(self, name, bases, dict) _nodeTypes[self.nodeType] = self class NodeType(object): __metaclass__ = _NodeType...
Use metaclasses to register node types.
Use metaclasses to register node types.
Python
apache-2.0
sassoftware/rmake3,sassoftware/rmake3,sassoftware/rmake,sassoftware/rmake,sassoftware/rmake3,sassoftware/rmake
222a87ef324f66baf8113020b41d336c459ab847
stdnum/fi/__init__.py
stdnum/fi/__init__.py
# __init__.py - collection of Finnish numbers # coding: utf-8 # # Copyright (C) 2012 Arthur de Jong # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, ...
# __init__.py - collection of Finnish numbers # coding: utf-8 # # Copyright (C) 2012 Arthur de Jong # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, ...
Add alias to hetu in for finnish personal id code
Add alias to hetu in for finnish personal id code
Python
lgpl-2.1
holvi/python-stdnum,holvi/python-stdnum,arthurdejong/python-stdnum,arthurdejong/python-stdnum,holvi/python-stdnum,arthurdejong/python-stdnum
563a905a48a5d4059463f25c5467a52a9d9c79c5
groove/timezone.py
groove/timezone.py
from datetime import datetime, date from django.utils import timezone def datetime_midnight(year, month, day): """ Returns a timezone aware datetime object of a date at midnight, using the current timezone. """ return timezone.make_aware(datetime(year, month, day), timezone.get_current_timezone(...
from datetime import datetime, date from django.utils import timezone def datetime_midnight(year, month, day): """ Returns a timezone aware datetime object of a date at midnight, using the current timezone. """ return timezone.make_aware(datetime(year, month, day), timezone.get_current_timezone(...
Add function for creating a datetime aware object
Add function for creating a datetime aware object
Python
bsd-2-clause
funkbit/django-groove
b2de891e75dc84e809b9c35222e6bc8fe44c3d37
test_arg.py
test_arg.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function, division import unittest as ut import numpy as np import ARG.arg as arg class ARGTestCase(ut.TestCase): def test_truisms(self): """Test parameter class""" param = arg.ARGparams() self.assertTrue(isinsta...
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function, division import unittest as ut import numpy as np import ARG.arg as arg class ARGTestCase(ut.TestCase): def test_param_class(self): """Test parameter class.""" param = arg.ARGparams() self.assertIsInst...
Test functions a, b, c
Test functions a, b, c
Python
mit
khrapovs/argamma
369b0499d02531e7058f4f0d6c5051b9058701aa
metadata_to_json_and_fnamesmap.py
metadata_to_json_and_fnamesmap.py
#! /usr/bin/env python # -*- coding: utf-8 -*- """Turn Excel metadata from SMVK into JSON-file for further processing. Input: Excel-file Processing: strip whitespace etc Output: JSON-file `cypern_metadata.json" containg dict in the current directory """ import pandas as pd import argparse def main(): """Illustra...
#! /usr/bin/env python # -*- coding: utf-8 -*- """Turn Excel metadata from SMVK into JSON-file for further processing. Input: Excel-file Processing: strip whitespace etc Output: JSON-file `cypern_metadata.json" containg dict in the current directory """ import pandas as pd import argparse def strip(text): try: ...
Read sheetname 'Cypern' and strip column names
Read sheetname 'Cypern' and strip column names
Python
mit
mattiasostmar/SMVK-Cypern_2017-01
0c4bdc2d27fb289979004c7e0a0b9d0bf0a764cf
main.py
main.py
# -*- coding: utf-8 -*- import numpy as np import universe seed = 91231 n_trials = 20 n_steps = 1000 steps_to_reward = 9 max_reward = n_steps // steps_to_reward * 5. uni = universe.Universe('grid_world', world='2d_world0') uni.show() reward = [] for i in range(n_trials): np.random.seed(1234 + i) uni.res...
# -*- coding: utf-8 -*- import matplotlib.pyplot as plt import numpy as np import universe seed = 91231 n_trials = 20 n_steps = 1000 steps_to_reward = 14 max_reward = n_steps // steps_to_reward * 5. uni = universe.Universe('grid_world', world='2d_world1') uni.show() reward = [] for i in range(n_trials): rewa...
Add trial cumulative reward plot
Add trial cumulative reward plot
Python
mit
jakobj/python-tdl
52c8b8d2676024ff07722115c815ecdd04dd000c
etrago/cluster/analyses/config.py
etrago/cluster/analyses/config.py
# -*- coding: utf-8 -*- """ """ from os import path root_path = '/home/openego/pf_results/' \ 'snapshot-clustering-results-k10-cyclic-withpypsaweighting/' clustered_path = path.join(root_path, 'daily') original_path = path.join(root_path, 'original') plot_path = root_path
# -*- coding: utf-8 -*- """ """ from os import path root_path = path.join(path.expanduser('~'),'pf_results/' \ 'snapshot-clustering-results-k10-cyclic/') clustered_path = path.join(root_path, 'daily') original_path = path.join(root_path, 'original') plot_path = root_path
Set path automatically to home of user
Set path automatically to home of user
Python
agpl-3.0
openego/eTraGo
cf9ba0d497127d5261c8bee5eebe0e8f12aabf3a
armstrong/core/arm_wells/views.py
armstrong/core/arm_wells/views.py
from django.core.exceptions import ImproperlyConfigured from django.views.generic import TemplateView class SimpleWellView(TemplateView): def render_to_response(self, context, **response_kwargs): if not 'params' in context: raise ImproperlyConfigured( "Expects `params` to b...
from django.core.exceptions import ImproperlyConfigured from django.views.generic import TemplateView from django.utils.translation import ugettext as _ class SimpleWellView(TemplateView): def render_to_response(self, context, **response_kwargs): if not 'params' in context: raise ImproperlyCon...
Make these exception messages translatable
Make these exception messages translatable
Python
apache-2.0
armstrong/armstrong.core.arm_wells,dmclain/armstrong.core.arm_wells,armstrong/armstrong.core.arm_wells,texastribune/armstrong.core.arm_wells,texastribune/armstrong.core.arm_wells,dmclain/armstrong.core.arm_wells,armstrong/armstrong.core.arm_wells
b7f07248834857e89f2f8312785a3a1f343c27c3
quickstart/python/understand/example-2/create_joke_intent.6.x.py
quickstart/python/understand/example-2/create_joke_intent.6.x.py
# Download the helper library from https://www.twilio.com/docs/python/install from twilio.rest import Client # Your Account Sid and Auth Token from twilio.com/console account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' auth_token = 'your_auth_token' client = Client(account_sid, auth_token) assistant_sid = 'UAXXXXXXXXX...
# Download the helper library from https://www.twilio.com/docs/python/install from twilio.rest import Client # Your Account Sid and Auth Token from twilio.com/console account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' auth_token = 'your_auth_token' client = Client(account_sid, auth_token) # Create a new intent named ...
Update to use assistant SID inline
Update to use assistant SID inline Maintaining consistency with the auto-generated code samples for Understand, which don't allow for our variable-named placeholder values
Python
mit
TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets
7cf4578297667bc8b6405e99828818de87e3ba9a
extensions/ExtGameController.py
extensions/ExtGameController.py
from python_cowbull_game.GameController import GameController from python_cowbull_game.GameMode import GameMode class ExtGameController(GameController): additional_modes = [ GameMode(mode="SuperTough", priority=6, digits=10, digit_type=0), GameMode(mode="hexTough", priority=5, digits=3, guesses_al...
from python_cowbull_game.GameController import GameController from python_cowbull_game.GameMode import GameMode class ExtGameController(GameController): additional_modes = [ GameMode(mode="SuperTough", priority=6, digits=10, digit_type=0), GameMode(mode="hexTough", priority=5, digits=3, guesses_al...
Update extensions and GameController subclass
Update extensions and GameController subclass
Python
apache-2.0
dsandersAzure/python_cowbull_server,dsandersAzure/python_cowbull_server
641a12d42bea5a78f8b1188ea758075fec6ef445
irclogview/urls.py
irclogview/urls.py
from django.conf.urls.defaults import * urlpatterns = patterns('irclogview.views', url(r'^(?P<name>[^/]+)/(?P<year>\d{4})(?P<month>\d{2})(?P<day>\d{2})/$', 'show_log', name='irclogview_show'), url(r'^(?P<name>[^/]+)/$', 'channel_index', name='irclogview_channel'), url(r'^$', 'index', name='irclogview_index...
from django.conf.urls.defaults import patterns, url from django.conf import settings urlpatterns = patterns('', url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}), ) urlpatterns += patterns('irclogview.views', url(r'^(?P<name>[^/]+)/(?P<year>\d{4})(?P<mon...
Set /media/ as static folder
Set /media/ as static folder
Python
agpl-3.0
BlankOn/irclogview,fajran/irclogview,BlankOn/irclogview,fajran/irclogview
b32614df983402081cad272f486fcffcd3a18fc1
scripts/tests/data_util_test.py
scripts/tests/data_util_test.py
from data_util import DataManager import sys import data_util import numpy as np sys.path.append("../") # DataInstance = DataManager("../../data/train", "../../data/test", 128) # batch_input, batch_output, is_epoch_increase = DataInstance.get_batch() # print (np.shape(batch_input)) data_util.save_to_disk("../../data/tr...
import sys import numpy as np sys.path.append("../") import data_util # DataInstance = DataManager("../../data/train", "../../data/test", 128) # batch_input, batch_output, is_epoch_increase = DataInstance.get_batch() # print (np.shape(batch_input)) data_util.save_to_disk("../../data/train", "../../data/test")
Fix a bug on loding module
Fix a bug on loding module
Python
apache-2.0
Lucklyric/NLP-NER-CNN
1941cba46978fb7f8182ddb3eddf2d77002b28f7
api/base/middleware.py
api/base/middleware.py
from framework.transactions import handlers class TokuTransactionsMiddleware(object): """TokuMX transaction middleware.""" def process_request(self, request): handlers.transaction_before_request() def process_response(self, request, response): return handlers.transaction_after_request(res...
from framework.transactions import handlers, commands class TokuTransactionsMiddleware(object): """TokuMX transaction middleware.""" def process_request(self, request): handlers.transaction_before_request() def process_exception(self, request, exception): commands.rollback() def proc...
Make sure transaction is rolled back if an exception is raised
Make sure transaction is rolled back if an exception is raised
Python
apache-2.0
TomHeatwole/osf.io,asanfilippo7/osf.io,fabianvf/osf.io,chrisseto/osf.io,dplorimer/osf,monikagrabowska/osf.io,chrisseto/osf.io,TomBaxter/osf.io,doublebits/osf.io,cwisecarver/osf.io,cwisecarver/osf.io,icereval/osf.io,jnayak1/osf.io,haoyuchen1992/osf.io,laurenrevere/osf.io,ckc6cz/osf.io,doublebits/osf.io,njantrania/osf.io...
2394de5f46d264e2a585b6cd4b87e4a45c99cfeb
cast_convert/__init__.py
cast_convert/__init__.py
from . import * from .convert import * from .media_info import * from .watch import *
__version__ = '0.1.5.18' from .cmd import cmd as command from .watch import * from . import * from .convert import * from .media_info import * @click.command(help="Print version") def version(): print(__version__) command.add_command(version)
Add version and version command
Add version and version command
Python
agpl-3.0
thismachinechills/cast_convert
073fc87b0641685bf228ca530927d793c919d40d
hoomd/filter/custom.py
hoomd/filter/custom.py
"""Contains a class for custom particle filters in Python.""" from abc import ABCMeta, abstractmethod class CustomFilter(metaclass=ABCMeta): """Abstract base class for custom particle filters. The class allows the definition of particle filters in Python (see `hoomd.filter.ParticleFilter`. """ @ab...
"""Contains a class for custom particle filters in Python.""" from abc import ABC, abstractmethod from collections.abc import Hashable, Callable class CustomFilter(Hashable, Callable): """Abstract base class for custom particle filters. The class allows the definition of particle filters in Python (see `h...
Change the inherited classes of hoomd.filter.CustomFilter
Change the inherited classes of hoomd.filter.CustomFilter CustomFilter inherits now from Hashable and Callable
Python
bsd-3-clause
joaander/hoomd-blue,joaander/hoomd-blue,joaander/hoomd-blue,joaander/hoomd-blue,joaander/hoomd-blue,joaander/hoomd-blue
27f409721a9f59b61d6fe01bad11733a7559bda0
hotohete/production.py
hotohete/production.py
import dj_database_url from hotohete.settings import * db_from_env = dj_database_url.config(conn_max_age=500) DATABASES['default'].update(db_from_env) ALLOWED_HOSTS = [ 'hotohete.herokuapp.com', 'localhost', '127.0.0.1' ]
import dj_database_url from hotohete.settings import * db_from_env = dj_database_url.config(conn_max_age=500) DATABASES['default'].update(db_from_env) ALLOWED_HOSTS = [ 'hotohete.herokuapp.com', 'hotohetestaging.herokuapp.com', 'localhost', '127.0.0.1' ]
Add stating to allowed hosts
Add stating to allowed hosts
Python
mit
wen96/hotohete,wen96/hotohete,wen96/hotohete,wen96/hotohete
4723e5aaf60d7fcf823d5fa72b67ef3331daa049
extruder/extrude_template.py
extruder/extrude_template.py
from __future__ import print_function, division, absolute_import from argparse import ArgumentParser def main(args=None): if args is None: parser = ArgumentParser('Tool for generating skeleton package-' 'building directory.') parser.add_argument('--appveyor-secret'...
from __future__ import print_function, division, absolute_import from argparse import ArgumentParser import os import shutil from jinja2 import Environment, FileSystemLoader def main(args=None): """ Copy all of the files needed from the source distribution to the current directory. """ if args ...
Implement script for creating skeleton build setup
Implement script for creating skeleton build setup
Python
bsd-3-clause
astropy/conda-build-tools,astropy/conda-build-tools
7a7856d9ec56de91325c7bf7c62ff25c0241badc
tests/test_connect.py
tests/test_connect.py
import pypuppetdb def test_connect_api(): puppetdb = pypuppetdb.connect() assert puppetdb.version == 'v4'
import pypuppetdb def test_connect_api(): puppetdb = pypuppetdb.connect() assert puppetdb.version == 'v4' def test_connect_with_statement(): with pypuppetdb.connect() as puppetdb: assert puppetdb.version == 'v4'
Add test for creating connection with 'with' statement.
Add test for creating connection with 'with' statement.
Python
apache-2.0
puppet-community/pypuppetdb,voxpupuli/pypuppetdb
da1518d1e810ca227e84f110d4d42d1480040bc8
tests/test_twitter.py
tests/test_twitter.py
# -*- coding: utf-8 -*- import pytest import tweepy import vcr from secrets import TWITTER_ACCESS, TWITTER_SECRET from secrets import TWITTER_CONSUMER_ACCESS, TWITTER_CONSUMER_SECRET class TestTweepyIntegration(): """Test class to ensure tweepy functionality works as expected""" # Class level client to use a...
# -*- coding: utf-8 -*- import pytest import vcr from inet.sources.twitter import api class TestTweepyIntegration(): """Test class to ensure tweepy functionality works as expected""" @vcr.use_cassette('fixtures/vcr_cassettes/twitter.yaml') def test_authd(self): assert api.verify_credentials() is ...
Change tests to pull in twitter client from package
Change tests to pull in twitter client from package
Python
mit
nestauk/inet
bfc0ce1298b9fe7a640dc31c6e5729d1c6360945
langs/pystartup.py
langs/pystartup.py
# Add auto-completion and a stored history file of commands to your Python # interactive interpreter. Requires Python 2.0+, readline. Autocomplete is # bound to the Esc key by default (you can change it - see readline docs). # # Set an environment variable to point to it: "export PYTHONSTARTUP=foo" # # Note that PYTHO...
# Add auto-completion and a stored history file of commands to your Python # interactive interpreter. Requires Python 2.0+, readline. Autocomplete is # bound to the Esc key by default (you can change it - see readline docs). # # Set an environment variable to point to it: "export PYTHONSTARTUP=foo" # # Note that PYTHO...
Add json true/false/none in python repl
Add json true/false/none in python repl https://mobile.twitter.com/mitsuhiko/status/1229385843585974272/photo/2
Python
mit
keith/dotfiles,keith/dotfiles,keith/dotfiles,keith/dotfiles,keith/dotfiles,keith/dotfiles
2489ed6ff3d812888de4a0a2c45995389499d648
thread_output_ctrl.py
thread_output_ctrl.py
import Queue import wx, wx.stc from editor_fonts import init_stc_style class ThreadOutputCtrl(wx.stc.StyledTextCtrl): def __init__(self, parent, style=wx.TE_READONLY): wx.stc.StyledTextCtrl.__init__(self, parent) init_stc_style(self) self.SetIndent(4) self.SetTabWidth(8) sel...
import threading import wx, wx.stc from editor_fonts import init_stc_style class ThreadOutputCtrl(wx.stc.StyledTextCtrl): def __init__(self, parent, style=wx.TE_READONLY): wx.stc.StyledTextCtrl.__init__(self, parent) init_stc_style(self) self.SetIndent(4) self.SetTabWidth(8) ...
Use a lock-protected list instead of a Queue.
Use a lock-protected list instead of a Queue.
Python
mit
shaurz/devo
336313ac982b9de278aca6e0f74f6820ef5b2526
landlab/grid/structured_quad/tests/test_links.py
landlab/grid/structured_quad/tests/test_links.py
import numpy as np from numpy.testing import assert_array_equal from nose.tools import raises, assert_true from landlab.grid.structured_quad.nodes import status_with_perimeter_as_boundary from landlab.grid.structured_quad.links import active_link_ids from landlab.grid.base import CORE_NODE, FIXED_VALUE_BOUNDARY, CLO...
import numpy as np from numpy.testing import assert_array_equal from nose.tools import raises, assert_equal from landlab.grid.structured_quad.nodes import status_with_perimeter_as_boundary from landlab.grid.structured_quad.links import active_link_ids from landlab.grid.base import CORE_NODE, FIXED_VALUE_BOUNDARY, CL...
Test of index arrays of type int.
Test of index arrays of type int.
Python
mit
ManuSchmi88/landlab,amandersillinois/landlab,SiccarPoint/landlab,cmshobe/landlab,amandersillinois/landlab,SiccarPoint/landlab,cmshobe/landlab,laijingtao/landlab,RondaStrauch/landlab,Carralex/landlab,Carralex/landlab,ManuSchmi88/landlab,cmshobe/landlab,Carralex/landlab,landlab/landlab,csherwood-usgs/landlab,ManuSchmi88/...
2be4b1b67ca17a400c6d22e8e29e0a4f1c69c0cc
dakota_utils/models/hydrotrend.py
dakota_utils/models/hydrotrend.py
#! /usr/bin/env python # # A module for working with HydroTrend. # # Mark Piper (mark.piper@colorado.edu) import numpy as np def load_series(output_file): ''' Reads a column of text containing HydroTrend output. Returns a numpy array, or None on an error. ''' try: series = np.loadtxt(outp...
#! /usr/bin/env python # # A module for working with HydroTrend. # # Mark Piper (mark.piper@colorado.edu) from subprocess import call import numpy as np def load(output_file): ''' Reads a column of text containing HydroTrend output. Returns a numpy array, or None on an error. ''' try: ser...
Add call() function, rename load() function
Add call() function, rename load() function Slowly encapsulating the run_hydrotrend.py script used in the Dakota experiments.
Python
mit
mdpiper/dakota-experiments,mdpiper/dakota-experiments,mcflugen/dakota-experiments,mdpiper/dakota-experiments,mcflugen/dakota-experiments
c231987c532885fa7bc5e8d2afc8b7a30a2ce297
bayesian_methods_for_hackers/simulate_messages_ch02.py
bayesian_methods_for_hackers/simulate_messages_ch02.py
import json import matplotlib import numpy as np import pymc as pm from matplotlib import pyplot as plt def main(): matplotlibrc_path = '/home/noel/repo/playground/matplotlibrc.json' matplotlib.rcParams.update(json.load(open(matplotlibrc_path))) tau = pm.rdiscrete_uniform(0, 80) print tau alpha ...
import json import matplotlib import numpy as np import pymc as pm from matplotlib import pyplot as plt def main(): tau = pm.rdiscrete_uniform(0, 80) print tau alpha = 1. / 20. lambda_1, lambda_2 = pm.rexponential(alpha, 2) print lambda_1, lambda_2 data = np.r_[pm.rpoisson(lambda_1, tau), pm...
Change of repo name. Update effected paths
Change of repo name. Update effected paths
Python
mit
noelevans/sandpit,noelevans/sandpit,noelevans/sandpit,noelevans/sandpit,noelevans/sandpit,noelevans/sandpit
7310fdd86cebd1c8b28d960f0211e350fbf07a62
handlers/login.py
handlers/login.py
from rorn.Box import LoginBox, ErrorBox, WarningBox, SuccessBox from rorn.Session import delay from User import User from Button import Button from utils import * @get('login') def login(handler, request): handler.title('Login') if handler.session['user']: print WarningBox('Logged In', 'You are already logged in ...
from rorn.Box import LoginBox, ErrorBox, WarningBox, SuccessBox from rorn.Session import delay from User import User from Button import Button from utils import * @get('login') def login(handler, request): handler.title('Login') if handler.session['user']: print WarningBox('Logged In', 'You are already logged in ...
Clear reset key on user activity
Clear reset key on user activity
Python
mit
mrozekma/Sprint,mrozekma/Sprint,mrozekma/Sprint
018eab65881a2279efca88e1448dba0708a4dfe1
django_excel_to_model/management/commands/model_create_utils/django_tables2_utils.py
django_excel_to_model/management/commands/model_create_utils/django_tables2_utils.py
from django_excel_to_model.management.commands.model_create_utils.attribute_generator import ClassAttributeCreator import django_tables2 as tables def get_django_tables2_from_dict(data_dict): c = ClassAttributeCreator() table_meta_class = type("Meta", (), { "attrs": {'class': 'table table-striped tabl...
from django_excel_to_model.management.commands.model_create_utils.attribute_generator import ClassAttributeCreator import django_tables2 as tables def get_django_tables2_from_dict(data_dict): c = ClassAttributeCreator() table_meta_class = type("Meta", (), { "attrs": {'class': 'table table-striped tabl...
Remove sort function by default for table generated from dict.
Remove sort function by default for table generated from dict.
Python
bsd-3-clause
weijia/django-excel-to-model,weijia/django-excel-to-model
2f28efa4bef5759392a46fe3457c87c94911e1ba
tools/api-client/python/interactive_mode.py
tools/api-client/python/interactive_mode.py
# Here's an example of stuff to copy and paste into an interactive Python interpreter to get a connection loaded. # Or you can load it with 'python -i interactive-mode.py'. # Set some variables. bmrc = "~/.bmrc" site = "www" bmutilspath = "./lib" # Import everything, make a connection, and try to log in. import jso...
# Here's an example of stuff to copy and paste into an interactive Python # interpreter to get a connection loaded. # Or you can load it with 'python -i interactive_mode.py'. # Set some variables. bmrc = "~/.bmrc" site = "www" bmutilspath = "./lib" # Import everything, make a connection, and try to log in. import j...
Print the JSON dump, so it's prettier.
Print the JSON dump, so it's prettier.
Python
bsd-3-clause
dwvanstone/buttonmen,dwvanstone/buttonmen,dwvanstone/buttonmen,dwvanstone/buttonmen,dwvanstone/buttonmen,dwvanstone/buttonmen
db8dea37028432c89e098728970fbaa265e49359
bookmarks/core/models.py
bookmarks/core/models.py
from __future__ import unicode_literals from django.db import models from django.utils import timezone from taggit.managers import TaggableManager class Bookmark(models.Model): title = models.CharField(max_length=200, blank=True, null=True) description = models.TextField(blank=True, null=True) date_adde...
from __future__ import unicode_literals from django.db import models from django.utils import timezone from taggit.managers import TaggableManager class Bookmark(models.Model): title = models.CharField(max_length=200, blank=True, null=True) description = models.TextField(blank=True, null=True) date_adde...
Increase max length of url field.
Increase max length of url field.
Python
mit
tom-henderson/bookmarks,tom-henderson/bookmarks,tom-henderson/bookmarks
17c81bb4acb51907f6a4df9a1a436611e730c15d
test/geocoders/teleport.py
test/geocoders/teleport.py
# -*- coding: UTF-8 -*- from geopy.geocoders import Teleport from test.geocoders.util import GeocoderTestBase class TeleportTestCaseUnitTest(GeocoderTestBase): def test_user_agent_custom(self): geocoder = Teleport( user_agent='my_user_agent/1.0' ) self.assertEqual(geocoder.hea...
# -*- coding: UTF-8 -*- from geopy.geocoders import Teleport from test.geocoders.util import GeocoderTestBase class TeleportTestCaseUnitTest(GeocoderTestBase): def test_user_agent_custom(self): geocoder = Teleport( user_agent='my_user_agent/1.0' ) self.assertEqual(geocoder.hea...
Use http scheme to reduce test times
Use http scheme to reduce test times
Python
mit
magnushiie/geopy,magnushiie/geopy
d29e87eeb062df4d52c0c744919be4cae770fc2c
testing/config/settings/__init__.py
testing/config/settings/__init__.py
# include settimgs from daiquiri from daiquiri.core.settings.django import * from daiquiri.core.settings.celery import * from daiquiri.core.settings.daiquiri import * from daiquiri.core.settings.logging import * from daiquiri.core.settings.vendor import * from daiquiri.archive.settings import * from daiquiri.auth.sett...
# include settimgs from daiquiri from daiquiri.core.settings.django import * from daiquiri.core.settings.celery import * from daiquiri.core.settings.daiquiri import * from daiquiri.core.settings.logging import * from daiquiri.core.settings.vendor import * from daiquiri.archive.settings import * from daiquiri.auth.sett...
Add registry settings to testing
Add registry settings to testing
Python
apache-2.0
aipescience/django-daiquiri,aipescience/django-daiquiri,aipescience/django-daiquiri
069d658291276e237ce6304c306a1676ba94a650
pricing/get-lookup-pricing/get-lookup-pricing.py
pricing/get-lookup-pricing/get-lookup-pricing.py
from twilio.rest import TwilioPricingClient, TwilioLookupsClient #auth credentials account_sid = "ACCOUNT_SID" auth_token = "AUTH_TOKEN" #Use Lookup API to get country code / MCC / MNC that corresponds to given phone number phone_number = "+15108675309" print "Find outbound SMS price to:",phone_number client = Twili...
from twilio.rest import TwilioPricingClient, TwilioLookupsClient #auth credentials account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" auth_token = "{{ auth_token }}" #Use Lookup API to get country code / MCC / MNC that corresponds to given phone number phone_number = "+15108675309" print "Find outbound SMS price to:...
Correct errors in pricing snippets
Correct errors in pricing snippets
Python
mit
TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,teoreteetik/api-snippets,TwilioDevEd/api-snippets,teoreteetik/api-snippets,teoreteetik/api-snippets,TwilioDevEd/api-snippets,teoreteetik/api-snippets,TwilioDevEd/api-snippets,teoreteetik/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,teoreteetik/api-snip...
f3b87dcad47e77a3383de6fef17080661471a4a3
facturapdf/generators.py
facturapdf/generators.py
import re from reportlab import platypus from facturapdf import flowables, helper def element(item): elements = { 'framebreak': {'class': platypus.FrameBreak}, 'simpleline': {'class': flowables.SimpleLine, 'cast': {0: float, 1: float}}, 'paragraph': {'class': flowables.Paragraph}, ...
import re from reportlab import platypus from facturapdf import flowables, helper def element(item): elements = { 'framebreak': {'class': platypus.FrameBreak}, 'simpleline': {'class': flowables.SimpleLine, 'cast': {0: float, 1: float}}, 'paragraph': {'class': flowables.Paragraph}, ...
Use dict iteration compatible with Python 2 and 3
Use dict iteration compatible with Python 2 and 3
Python
bsd-3-clause
initios/factura-pdf
00bedbd90c46d4cabcd22748bee047732d29417c
members/guardianfetch.py
members/guardianfetch.py
#!/usr/bin/python import urllib, re base = 'http://politics.guardian.co.uk' out = open('../rawdata/mpinfo/guardian-mpsurls2005.txt', 'w') for i in range(-272, -266): url = '%s/person/browse/mps/az/0,,%d,00.html' % (base, i) fp = urllib.urlopen(url) index = fp.read() fp.close() m = re.findall('<a href="(/person/0...
#!/usr/bin/python import sys sys.path.append("../pyscraper") import urllib, re base = 'http://politics.guardian.co.uk' from BeautifulSoup import BeautifulSoup out = open('../rawdata/mpinfo/guardian-mpsurls2005.txt', 'w') for i in range(-272, -266): url = '%s/person/browse/mps/az/0,,%d,00.html' % (base, i) fp = urllib...
Update for new person page format
Update for new person page format git-svn-id: 285608342ca21a36fbe1c940a1767f009072314d@8369 9cc54934-f9f6-0310-8a8d-e8e977684441
Python
agpl-3.0
henare/parlparse,henare/parlparse,spudmind/parlparse,spudmind/parlparse,henare/parlparse,spudmind/parlparse,spudmind/parlparse,henare/parlparse,henare/parlparse,spudmind/parlparse
d9971a831a622f606d62825957c970a791d53d75
symaps_proxies/settings/base.py
symaps_proxies/settings/base.py
# -*- coding: utf-8 -*- AWS_VPCS = [ { 'CidrBlock': '15.0.0.0/16', 'Tags': [ { 'Key': 'Name', 'Value': 'symaps-prod-proxies' } ], 'create_internet_gateway': True }, { 'CidrBlock': '16.0.0.0/16', 'Tags': ...
# -*- coding: utf-8 -*- AWS_VPCS = [ { 'CidrBlock': '15.0.0.0/16', 'Tags': [ { 'Key': 'Name', 'Value': 'symaps-prod-proxies' } ], 'create_internet_gateway': True, 'subnets': [ { 'CidrBlock': ...
Simplify the aws vpcs settings for testing
Simplify the aws vpcs settings for testing
Python
mit
davidlonjon/aws-proxies,davidlonjon/aws-proxies
830f8281f80f363be8433be562ea52b817ceefe3
engine/extensions/pychan/tools.py
engine/extensions/pychan/tools.py
# coding: utf-8 ### Functools ### def applyOnlySuitable(func,**kwargs): """ This nifty little function takes another function and applies it to a dictionary of keyword arguments. If the supplied function does not expect one or more of the keyword arguments, these are silently discarded. The result of the applicat...
# coding: utf-8 ### Functools ### def applyOnlySuitable(func,**kwargs): """ This nifty little function takes another function and applies it to a dictionary of keyword arguments. If the supplied function does not expect one or more of the keyword arguments, these are silently discarded. The result of the applicat...
Simplify callback creation with a functional utility function.
PyChan: Simplify callback creation with a functional utility function.
Python
lgpl-2.1
cbeck88/fifengine,gravitystorm/fifengine,cbeck88/fifengine,cbeck88/fifengine,fifengine/fifengine,fifengine/fifengine,Niektory/fifengine,gravitystorm/fifengine,fifengine/fifengine,Niektory/fifengine,gravitystorm/fifengine,gravitystorm/fifengine,Niektory/fifengine,cbeck88/fifengine
a2274f52e4567de4209e3394060fe62276ad3546
test/mitmproxy/test_examples.py
test/mitmproxy/test_examples.py
import glob from mitmproxy import utils, script from mitmproxy.proxy import config from . import tservers def test_load_scripts(): example_dir = utils.Data(__name__).path("../../examples") scripts = glob.glob("%s/*.py" % example_dir) tmaster = tservers.TestMaster(config.ProxyConfig()) for f in scrip...
import glob from mitmproxy import utils, script from mitmproxy.proxy import config from netlib import tutils as netutils from netlib.http import Headers from . import tservers, tutils from examples import ( modify_form, ) def test_load_scripts(): example_dir = utils.Data(__name__).path("../../examples") ...
Add tests for modify_form example
Add tests for modify_form example
Python
mit
xaxa89/mitmproxy,vhaupert/mitmproxy,ddworken/mitmproxy,gzzhanghao/mitmproxy,Kriechi/mitmproxy,zlorb/mitmproxy,StevenVanAcker/mitmproxy,vhaupert/mitmproxy,ddworken/mitmproxy,dwfreed/mitmproxy,mosajjal/mitmproxy,jvillacorta/mitmproxy,gzzhanghao/mitmproxy,mhils/mitmproxy,dwfreed/mitmproxy,tdickers/mitmproxy,cortesi/mitmpr...
59119f8a3f97b833559404a5f89cc66243fe06ca
opal/tests/test_views.py
opal/tests/test_views.py
""" Unittests for opal.views """ from django.test import TestCase from opal import views class ColumnContextTestCase(TestCase): pass
""" Unittests for opal.views """ from opal.core.test import OpalTestCase from opal import models from opal import views class BaseViewTestCase(OpalTestCase): def setUp(self): self.patient = models.Patient.objects.create() self.episode = self.patient.create_episode() def get_request(self, path...
Add some extra View tests
Add some extra View tests
Python
agpl-3.0
khchine5/opal,khchine5/opal,khchine5/opal
7ddaa5a5f9bee7e21c1221950c50c8688e815e01
wtforms/ext/sqlalchemy/__init__.py
wtforms/ext/sqlalchemy/__init__.py
import warnings warnings.warn( 'wtforms.ext.sqlalchemy is deprecated, and will be removed in WTForms 3.0. ' 'Instead transition to the excellent WTForms-Alchemy package: ' 'https://github.com/kvesteri/wtforms-alchemy', DeprecationWarning )
import warnings warnings.warn( 'wtforms.ext.sqlalchemy is deprecated, and will be removed in WTForms 3.0. ' 'The package has been extracted to a separate package wtforms_sqlalchemy: ' 'https://github.com/wtforms/wtforms-sqlalchemy .\n' 'Or alternately, check out the WTForms-Alchemy package which provid...
Add pointer to WTForms-SQLAlchemy in Deprecation
Add pointer to WTForms-SQLAlchemy in Deprecation Closes #221
Python
bsd-3-clause
crast/wtforms,cklein/wtforms,wtforms/wtforms
b7cee426db61801fd118758bb2f47944f3b8fd37
binaryornot/check.py
binaryornot/check.py
#!/usr/bin/env python # -*- coding: utf-8 -*- def get_starting_chunk(filename): with(filename, 'r') as f: chunk = open(filename).read(1024) return chunk def is_binary_string(bytes_to_check): """ :param bytes: A chunk of bytes to check. :returns: True if appears to be a binary, otherwi...
#!/usr/bin/env python # -*- coding: utf-8 -*- def get_starting_chunk(filename): with open(filename, 'r') as f: chunk = f.read(1024) return chunk def is_binary_string(bytes_to_check): """ :param bytes: A chunk of bytes to check. :returns: True if appears to be a binary, otherwise False...
Fix file opening and make tests pass.
Fix file opening and make tests pass.
Python
bsd-3-clause
hackebrot/binaryornot,0k/binaryornot,hackebrot/binaryornot,hackebrot/binaryornot,pombredanne/binaryornot,audreyr/binaryornot,pombredanne/binaryornot,audreyr/binaryornot,0k/binaryornot,pombredanne/binaryornot,audreyr/binaryornot
2be9da941fbbf17a54abd79ecae80d0245c1912e
moulinette/utils/stream.py
moulinette/utils/stream.py
from threading import Thread from Queue import Queue, Empty # Read from a stream --------------------------------------------------- class NonBlockingStreamReader: """A non-blocking stream reader Open a separate thread which reads lines from the stream whenever data becomes available and stores the data...
import threading import Queue # Read from a stream --------------------------------------------------- class AsynchronousFileReader(threading.Thread): """ Helper class to implement asynchronous reading of a file in a separate thread. Pushes read lines on a queue to be consumed in another thread. ...
Use a new asynchronous file reader helper
[ref] Use a new asynchronous file reader helper
Python
agpl-3.0
YunoHost/moulinette
bab058be7b830a38d75eebf53170a805e726308c
keyring/util/platform.py
keyring/util/platform.py
import os import sys # While we support Python 2.4, use a convoluted technique to import # platform from the stdlib. # With Python 2.5 or later, just do "from __future__ import absolute_import" # and "import platform" exec('__import__("platform", globals=dict())') platform = sys.modules['platform'] def _data_root_W...
import os import sys # While we support Python 2.4, use a convoluted technique to import # platform from the stdlib. # With Python 2.5 or later, just do "from __future__ import absolute_import" # and "import platform" exec('__import__("platform", globals=dict())') platform = sys.modules['platform'] def _data_root_W...
Fix regression on Windows XP in determining data root
Fix regression on Windows XP in determining data root
Python
mit
jaraco/keyring
eb22ca95b79e115130c957614ca9d07237360cf8
src/django_registration/signals.py
src/django_registration/signals.py
""" Custom signals sent during the registration and activation processes. """ from django.dispatch import Signal # A new user has registered. user_registered = Signal(providing_args=["user", "request"]) # A user has activated his or her account. user_activated = Signal(providing_args=["user", "request"])
""" Custom signals sent during the registration and activation processes. """ from django.dispatch import Signal # A new user has registered. # Provided args: user, request user_registered = Signal() # A user has activated his or her account. # Provided args: user, request user_activated = Signal()
Fix RemovedInDjango40Warning from Signal arguments
Fix RemovedInDjango40Warning from Signal arguments Fix to removove the following warning I've started to see when running unittest in my django project. """/<path to venv/lib/python3.7/site-packages/django_registration/signals.py:13: RemovedInDjango40Warning: The providing_args argument is deprecated. As it is purely...
Python
bsd-3-clause
ubernostrum/django-registration
d63eec8ec53b4a20d4ac5149b7eb7cfa2d094e2d
calc.py
calc.py
"""calc.py: A simple Python calculator.""" import sys def add_all(nums): return sum(nums) def multiply_all(nums): return reduce(lambda a, b: a * b, nums) if __name__ == '__main__': command = sys.argv[1] nums = map(float, sys.argv[2:]) if command == 'add': print(add_all(nums)) elif c...
"""calc.py: A simple Python calculator.""" import sys def add_all(nums): return sum(nums) def multiply_all(nums): return reduce(lambda a, b: a * b, nums) if __name__ == '__main__': command = sys.argv[1] nums = map(float, sys.argv[2:]) if command == 'add': print(add_all(nums)) elif c...
Add usage message if instruction not recognized
Add usage message if instruction not recognized
Python
bsd-3-clause
martaenciso/calc
303384ff5345e08dfd50ef78871742f0dd2903b6
src/main/python/pgshovel/utilities/__init__.py
src/main/python/pgshovel/utilities/__init__.py
import importlib import sys from contextlib import contextmanager def load(path): """ Loads a module member from a lookup path (using ``path.to.module:member`` syntax.) """ module, name = path.split(':') return getattr(importlib.import_module(module), name) @contextmanager def import_extras(...
import importlib import operator import sys from contextlib import contextmanager def load(path): """ Loads a module member from a lookup path. Paths are composed of two sections: a module path, and an attribute path, separated by a colon. For example:: >>> from pgshovel.utilities impor...
Allow deep attribute access in dynamic loading utility.
Allow deep attribute access in dynamic loading utility. Summary: This will help for parameterizing access to methods of singleton objects, such as the `msgpack` codec: >>> from pgshovel.utilities import load >>> load('pgshovel.contrib.msgpack:codec.decode') <bound method MessagePackCodec.decode of <pgshov...
Python
apache-2.0
fuziontech/pgshovel,disqus/pgshovel,fuziontech/pgshovel,disqus/pgshovel,fuziontech/pgshovel
f6540575792beb2306736e967e5399df58c50337
qutip/tests/test_heom.py
qutip/tests/test_heom.py
""" Tests for qutip.nonmarkov.heom. """ from qutip.nonmarkov.heom import ( BathExponent, Bath, BosonicBath, DrudeLorentzBath, DrudeLorentzPadeBath, UnderDampedBath, FermionicBath, LorentzianBath, LorentzianPadeBath, HEOMSolver, HSolverDL, ) class TestBathAPI: def test_...
""" Tests for qutip.nonmarkov.heom. """ from qutip.nonmarkov.heom import ( BathExponent, Bath, BosonicBath, DrudeLorentzBath, DrudeLorentzPadeBath, UnderDampedBath, FermionicBath, LorentzianBath, LorentzianPadeBath, HEOMSolver, HSolverDL, HierarchyADOs, HierarchyADOs...
Test that HierarchyADOs and HierarchyADOsState are part of the HEOM api.
Test that HierarchyADOs and HierarchyADOsState are part of the HEOM api.
Python
bsd-3-clause
cgranade/qutip,qutip/qutip,qutip/qutip,cgranade/qutip
4c1116f592731885f87421d8d3e85fa51fc785f9
apps/home/views.py
apps/home/views.py
# (c) Crown Owned Copyright, 2016. Dstl. from django.core.urlresolvers import reverse from django.shortcuts import redirect from django.views.generic.base import View class Home(View): # Get the homepage. If the user isn't logged in, (we can find no trace # of the user) or they are logged in but somehow...
# (c) Crown Owned Copyright, 2016. Dstl. from django.core.urlresolvers import reverse from django.shortcuts import redirect from django.views.generic.base import View from django.contrib.auth import login class Home(View): # Get the homepage. If the user isn't logged in, (we can find no trace # of the us...
Handle the user id coming in via a header.
Handle the user id coming in via a header.
Python
mit
dstl/lighthouse,dstl/lighthouse,dstl/lighthouse,dstl/lighthouse,dstl/lighthouse
564e611d7cb0b94e71c53e69971a49c312a0f7f8
tob-api/tob_api/custom_settings_ongov.py
tob-api/tob_api/custom_settings_ongov.py
''' Enclose property names in double quotes in order to JSON serialize the contents in the API ''' CUSTOMIZATIONS = { "serializers": { "Location": { "includeFields":{ "id", "verifiableOrgId", ...
''' Enclose property names in double quotes in order to JSON serialize the contents in the API ''' CUSTOMIZATIONS = { "serializers": { "Location": { "includeFields":[ "id", "verifiableOrgId", ...
Fix ongov customs settings formatting.
Fix ongov customs settings formatting.
Python
apache-2.0
swcurran/TheOrgBook,WadeBarnes/TheOrgBook,swcurran/TheOrgBook,swcurran/TheOrgBook,WadeBarnes/TheOrgBook,swcurran/TheOrgBook,WadeBarnes/TheOrgBook,WadeBarnes/TheOrgBook,WadeBarnes/TheOrgBook,swcurran/TheOrgBook
1f7c21280b7135f026f1ff807ffc50c97587f6fd
project/api/managers.py
project/api/managers.py
# Django from django.contrib.auth.models import BaseUserManager class UserManager(BaseUserManager): def create_user(self, email, password='', **kwargs): user = self.model( email=email, password='', is_active=True, **kwargs ) user.save(using=...
# Django from django.contrib.auth.models import BaseUserManager class UserManager(BaseUserManager): def create_user(self, email, password='', person, **kwargs): user = self.model( email=email, password='', person=person, is_active=True, **kwargs...
Update manager for Person requirement
Update manager for Person requirement
Python
bsd-2-clause
barberscore/barberscore-api,barberscore/barberscore-api,dbinetti/barberscore,dbinetti/barberscore,dbinetti/barberscore-django,dbinetti/barberscore-django,barberscore/barberscore-api,barberscore/barberscore-api