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
a08483b5fc55556b46c08e988ac297b1dffaed48
app/utils/utilities.py
app/utils/utilities.py
from re import search from flask import g from flask_restplus import abort from flask_httpauth import HTTPBasicAuth from app.models.user import User from instance.config import Config auth = HTTPBasicAuth() def validate_email(email): ''' Method to check that a valid email is provided ''' email_re = r"(^[a-zA-Z0...
from re import search from flask import g, request from flask_httpauth import HTTPTokenAuth from app.models.user import User auth = HTTPTokenAuth(scheme='Token') def validate_email(email): ''' Method to check that a valid email is provided ''' email_re = r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)" ...
Implement HTTPTokenAuth Store user data in global
Implement HTTPTokenAuth Store user data in global
Python
mit
Elbertbiggs360/buckelist-api
463e0ab2a77734cf6787d9cb788a57e7dd53ff06
games/admin.py
games/admin.py
from django.contrib import admin from .models import Game, Framework, Release, Asset class GameAdmin(admin.ModelAdmin): pass class FrameworkAdmin(admin.ModelAdmin): pass class ReleaseAdmin(admin.ModelAdmin): pass class AssetAdmin(admin.ModelAdmin): list_display = ['__unicode__', 'release'] ad...
from django.contrib import admin from .models import Game, Framework, Release, Asset class GameAdmin(admin.ModelAdmin): list_display = ['name', 'uuid', 'owner', 'framework', 'public'] class FrameworkAdmin(admin.ModelAdmin): pass class ReleaseAdmin(admin.ModelAdmin): pass class AssetAdmin(admin.Mode...
Add fields to the game display in Admin
Add fields to the game display in Admin
Python
mit
stackmachine/bearweb,stackmachine/bearweb,stackmachine/bearweb,stackmachine/bearweb,stackmachine/bearweb,stackmachine/bearweb
0a336447546442ab5d48716223713135a4812adf
get_problem.py
get_problem.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import sys from bs4 import BeautifulSoup from requests import get, codes def match_soup_class(target, mode='class'): def do_match(tag): classes = tag.get(mode, []) return all(c in classes for c in target) return do_match def main(): if len(...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import sys from bs4 import BeautifulSoup from requests import get, codes def match_soup_class(target, mode='class'): def do_match(tag): classes = tag.get(mode, []) return all(c in classes for c in target) return do_match def main(): if len(...
ADD comment for python file
ADD comment for python file
Python
mit
byung-u/ProjectEuler
42b4837570fd936c5a7593026fc4868c38d4b09d
base/management/commands/revision_count.py
base/management/commands/revision_count.py
# -*- encoding: utf-8 -*- from django.core.management.base import BaseCommand from django.apps import apps # from reversion import revisions as reversion from reversion.models import Version from reversion.errors import RegistrationError class Command(BaseCommand): help = "Count reversion records for each mode...
# -*- encoding: utf-8 -*- from django.core.management.base import BaseCommand from django.apps import apps # from reversion import revisions as reversion from reversion.models import Version from reversion.errors import RegistrationError class Command(BaseCommand): help = "Count reversion records for each mode...
Add titles to columns and use write instead of print
Add titles to columns and use write instead of print
Python
apache-2.0
pkimber/base,pkimber/base,pkimber/base,pkimber/base
8b7aa0a540c7927b53adf6368e9cb8476816d941
asciibooth/statuses.py
asciibooth/statuses.py
# encoding: UTF-8 import random from . import config def sampler(source): def reshuffle(): copy = list(source) random.shuffle(copy) return copy stack = reshuffle() lastitem = '' while True: try: item = stack.pop() if item == lastitem: ...
# encoding: UTF-8 import random from . import config def sampler(source): def reshuffle(): copy = list(source) random.shuffle(copy) return copy stack = reshuffle() lastitem = '' while True: try: item = stack.pop() if item == lastitem: ...
Add configuration options for randomness
Add configuration options for randomness
Python
cc0-1.0
jnv/asciibooth,jnv/asciibooth
0d023a51283d477e4b3d02059361b003a91134e0
jaspyx/scope.py
jaspyx/scope.py
class Scope(object): tmp_index = 0 def __init__(self, parent=None): self.parent = parent self.prefix = [] self.declarations = {} self.globals = set() self.inherited = True def prefixed(self, name): return '.'.join(self.prefix + [name]) def declare(self,...
class Scope(object): def __init__(self, parent=None): self.parent = parent self.prefix = [] self.declarations = {} self.globals = set() self.inherited = True def prefixed(self, name): return '.'.join(self.prefix + [name]) def declare(self, name, var=True): ...
Remove temp var allocation code.
Remove temp var allocation code.
Python
mit
ztane/jaspyx,iksteen/jaspyx
4524b88eef8a46d40c4d353c3561401ac3689878
bookmarks/urls.py
bookmarks/urls.py
from django.conf.urls import patterns, url # for voting from voting.views import vote_on_object from bookmarks.models import Bookmark urlpatterns = patterns('', url(r'^$', 'bookmarks.views.bookmarks', name="all_bookmarks"), url(r'^your_bookmarks/$', 'bookmarks.views.your_bookmarks', name="your_bookmarks"), ...
from django.conf.urls import patterns, url from django.views.decorators.csrf import csrf_exempt # for voting from voting.views import vote_on_object from bookmarks.models import Bookmark urlpatterns = patterns('', url(r'^$', 'bookmarks.views.bookmarks', name="all_bookmarks"), url(r'^your_bookmarks/$', 'bookma...
Disable csrf checks for voting
Disable csrf checks for voting
Python
mit
incuna/incuna-bookmarks,incuna/incuna-bookmarks
c2b0f66d5760d61444b4909e40c45993780cd473
examples/champion.py
examples/champion.py
import cassiopeia as cass from cassiopeia.core import Champion def test_cass(): #annie = Champion(name="Annie", region="NA") annie = Champion(name="Annie") print(annie.name) print(annie.title) print(annie.title) for spell in annie.spells: print(spell.name, spell.keywords) print(ann...
import cassiopeia as cass from cassiopeia.core import Champion def test_cass(): #annie = Champion(name="Annie", region="NA") annie = Champion(name="Annie") print(annie.name) print(annie.title) print(annie.title) for spell in annie.spells: print(spell.name, spell.keywords) print(ann...
Remove `return`, get Ziggs instead of Renekton, since we're saving as Ziggs
Remove `return`, get Ziggs instead of Renekton, since we're saving as Ziggs
Python
mit
robrua/cassiopeia,meraki-analytics/cassiopeia,10se1ucgo/cassiopeia
f22eff612427dc5f530858bb47326d69b48aa68a
darchan/urls.py
darchan/urls.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.conf.urls import patterns, url urlpatterns = patterns( 'darchan.views', url(r'^view_matrix/$', 'v_view_last_matrix', name='view_last_matrix'), url(r'^view_matrix/(?P<builder_id>\d+)/(?P<depth>\d+)/$', 'v_view_matrix', name=...
# -*- coding: utf-8 -*- # from __future__ import unicode_literals from django.conf.urls import url from darchan import views urlpatterns = [ url(r'^view_matrix/$', views.v_view_last_matrix, name='view_last_matrix'), url(r'^view_matrix/(?P<builder_id>\d+)/(?P<depth>\d+)/$', views.v_view_matrix, ...
Update support to Django 1.9
Update support to Django 1.9
Python
mpl-2.0
Pawamoy/django-archan,Pawamoy/django-archan,Pawamoy/django-archan
7e2d6cfa6b6a536d1df6e2d2d523a4bb4094f5eb
src/poliastro/plotting/misc.py
src/poliastro/plotting/misc.py
from poliastro.bodies import ( Earth, Jupiter, Mars, Mercury, Neptune, Saturn, Uranus, Venus, ) from poliastro.plotting.core import OrbitPlotter2D, OrbitPlotter3D from poliastro.twobody import Orbit def plot_solar_system(outer=True, epoch=None, use_3d=False): """ Plots the whol...
from typing import Union from poliastro.bodies import ( Earth, Jupiter, Mars, Mercury, Neptune, Saturn, Uranus, Venus, ) from poliastro.plotting.core import OrbitPlotter2D, OrbitPlotter3D from poliastro.twobody import Orbit def plot_solar_system(outer=True, epoch=None, use_3d=False): ...
Set frame only when using 2D
Set frame only when using 2D
Python
mit
Juanlu001/poliastro,Juanlu001/poliastro,Juanlu001/poliastro,poliastro/poliastro
40347e45646aa57c9181cb289dfa88a3b3eb3396
experiment/models.py
experiment/models.py
from django.db import models from experiment_session.models import ExperimentSession from django.core.validators import MinValueValidator class Experiment(models.Model): LIGHTOFF_FIXED = 'fixed' LIGHTOFF_WAITING = 'waiting' _LIGHTOFF_CHOICES = ( (LIGHTOFF_FIXED, 'Fixed'), (LIGHTOFF_WAITING...
from django.db import models from experiment_session.models import ExperimentSession from django.core.validators import MinValueValidator class Experiment(models.Model): LIGHTOFF_FIXED = 'fixed' LIGHTOFF_WAITING = 'waiting' _LIGHTOFF_CHOICES = ( (LIGHTOFF_FIXED, 'Fixed'), (LIGHTOFF_WAITING...
Allow empty strings as instructions
Allow empty strings as instructions
Python
mit
piotrb5e3/1023alternative-backend
04944ccd83e924fed6b351a6073d837a5ce639e9
sevenbridges/models/compound/price_breakdown.py
sevenbridges/models/compound/price_breakdown.py
import six from sevenbridges.meta.resource import Resource from sevenbridges.meta.fields import StringField class Breakdown(Resource): """ Breakdown resource contains price breakdown by storage and computation. """ storage = StringField(read_only=True) computation = StringField(read_only=True) ...
import six from sevenbridges.meta.resource import Resource from sevenbridges.meta.fields import StringField class Breakdown(Resource): """ Breakdown resource contains price breakdown by storage and computation. """ storage = StringField(read_only=True) computation = StringField(read_only=True) ...
Add data_transfer to price breakdown
Add data_transfer to price breakdown
Python
apache-2.0
sbg/sevenbridges-python
9b0d5796c1e48a3bf294971dc129499876936a36
send2trash/plat_osx.py
send2trash/plat_osx.py
# Copyright 2017 Virgil Dupras # This software is licensed under the "BSD" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.hardcoded.net/licenses/bsd_license from platform import mac_ver from sys import version_info # If macOS is ...
# Copyright 2017 Virgil Dupras # This software is licensed under the "BSD" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.hardcoded.net/licenses/bsd_license from platform import mac_ver from sys import version_info # NOTE: versio...
Change conditional for macos pyobjc usage
Change conditional for macos pyobjc usage macOS 11.x will occasionally identify as 10.16, since there was no real reason to prevent on all supported platforms allow.
Python
bsd-3-clause
hsoft/send2trash
c09b468583c97d7831478119614b231be0d24afa
scripts/generate_input_syntax.py
scripts/generate_input_syntax.py
#!/usr/bin/env python import sys, os # get the location of this script app_path = os.path.abspath(os.path.dirname(sys.argv[0])) # this script is actually in the scripts subdirectory, so go up a level app_path += '/..' # Set the name of the application here and moose directory relative to the application app_name = 'f...
#!/usr/bin/env python import sys, os # get the location of this script app_path = os.path.abspath(os.path.dirname(sys.argv[0])) # Set the name of the application here and moose directory relative to the application app_name = 'falcon' MOOSE_DIR = os.path.abspath(os.path.join(app_path, '..', '..' 'moose')) FRAMEWORK_...
Update scripts to reflect new MOOSE_DIR definition
Update scripts to reflect new MOOSE_DIR definition r25009
Python
lgpl-2.1
idaholab/falcon,aeslaughter/falcon,idaholab/falcon,aeslaughter/falcon,idaholab/falcon,idaholab/falcon,aeslaughter/falcon
6dbd72af13f017d9b1681da49f60aaf69f0a9e41
tests/transformer_test_case.py
tests/transformer_test_case.py
class TransformerTestCase(object): def get_pattern_for_spec(self, patterns, spec): for pattern in patterns: if pattern.search(spec): return pattern
from spec2scl import settings from spec2scl import specfile class TransformerTestCase(object): def make_prep(self, spec): # just create one of settings.RUNTIME_SECTIONS, so that we can test all the matching return '%prep\n' + spec def get_pattern_for_spec(self, handler, spec_text): spe...
Improve our custom test case
Improve our custom test case - create a make_prep method that allows quick creation of prep section from anything for good testing of custom transformers (that usually don't transform header section) - improve get_pattern_for_spec with section checking
Python
mit
mbooth101/spec2scl,sclorg/spec2scl
4de9bee656041c9cfcd91ec61d294460f6427d77
lib/database.py
lib/database.py
class Database: def __init__(self, db): self.db = db self.cursor = db.cursor() def disconnect(self): self.cursor.close() self.db.close() def query(self, sql): self.cursor.execute(sql) return self.cursor.fetchall() def insert(self, sql): self.cu...
import pymysql class Database: def __init__(self, db): self.db = db self.cursor = db.cursor() def disconnect(self): self.cursor.close() self.db.close() def query(self, sql): try: self.cursor.execute(sql) return self.cursor.fetchall() ...
Reconnect if the connection times out.
Reconnect if the connection times out.
Python
mit
aquaticpond/pyqodbc
8657f7aef8944eae718cabaaa7dfd25d2ec95960
conditions/__init__.py
conditions/__init__.py
from .conditions import * from .exceptions import * from .fields import * from .lists import * from .types import *
from .conditions import Condition, CompareCondition from .exceptions import UndefinedConditionError, InvalidConditionError from .fields import ConditionsWidget, ConditionsFormField, ConditionsField from .lists import CondList, CondAllList, CondAnyList, eval_conditions from .types import conditions_from_module __all__...
Replace star imports with explicit imports
PEP8: Replace star imports with explicit imports
Python
isc
RevolutionTech/django-conditions,RevolutionTech/django-conditions,RevolutionTech/django-conditions
7d79e6f0404b04ababaca3d8c50b1e682fd64222
chainer/initializer.py
chainer/initializer.py
import typing as tp # NOQA from chainer import types # NOQA from chainer import utils class Initializer(object): """Initializes array. It initializes the given array. Attributes: dtype: Data type specifier. It is for type check in ``__call__`` function. """ def __init__(...
import typing as tp # NOQA from chainer import types # NOQA from chainer import utils class Initializer(object): """Initializes array. It initializes the given array. Attributes: dtype: Data type specifier. It is for type check in ``__call__`` function. """ def __init__(...
Fix error messages in get_fans
Fix error messages in get_fans
Python
mit
niboshi/chainer,tkerola/chainer,niboshi/chainer,keisuke-umezawa/chainer,okuta/chainer,chainer/chainer,wkentaro/chainer,niboshi/chainer,okuta/chainer,okuta/chainer,wkentaro/chainer,pfnet/chainer,okuta/chainer,hvy/chainer,wkentaro/chainer,keisuke-umezawa/chainer,keisuke-umezawa/chainer,keisuke-umezawa/chainer,chainer/cha...
3786d778f583f96cb4dce37a175d2c460a020724
cnxauthoring/events.py
cnxauthoring/events.py
# -*- coding: utf-8 -*- # ### # Copyright (c) 2013, Rice University # This software is subject to the provisions of the GNU Affero General # Public License version 3 (AGPLv3). # See LICENCE.txt for details. # ### from pyramid.events import NewRequest def add_cors_headers(request, response): settings = request.reg...
# -*- coding: utf-8 -*- # ### # Copyright (c) 2013, Rice University # This software is subject to the provisions of the GNU Affero General # Public License version 3 (AGPLv3). # See LICENCE.txt for details. # ### from pyramid.events import NewRequest def add_cors_headers(request, response): settings = request.reg...
Fix Access-Control-Allow-Origin to return the request origin
Fix Access-Control-Allow-Origin to return the request origin request.host is the host part of the request url. For example, if webview is trying to access http://localhost:8080/users/profile, request. It's the Origin field in the headers that we should be matching.
Python
agpl-3.0
Connexions/cnx-authoring
a4b0830b7336694dacc822077c2ce6901be4929b
widgy/contrib/widgy_mezzanine/search_indexes.py
widgy/contrib/widgy_mezzanine/search_indexes.py
from haystack import indexes from widgy.contrib.widgy_mezzanine import get_widgypage_model from widgy.templatetags.widgy_tags import render_root from widgy.utils import html_to_plaintext from .signals import widgypage_pre_index WidgyPage = get_widgypage_model() class PageIndex(indexes.SearchIndex, indexes.Indexabl...
from haystack import indexes from widgy.contrib.widgy_mezzanine import get_widgypage_model from widgy.templatetags.widgy_tags import render_root from widgy.utils import html_to_plaintext from .signals import widgypage_pre_index WidgyPage = get_widgypage_model() class PageIndex(indexes.SearchIndex, indexes.Indexabl...
Index the URL of the WidgyPage.
Index the URL of the WidgyPage. This way, you don't have to fetch the page object when you want to put a link in the search results.
Python
apache-2.0
j00bar/django-widgy,j00bar/django-widgy,j00bar/django-widgy
46741fdbda00a8b1574dfdf0689c8a26454d28f6
actions/cloudbolt_plugins/aws/poll_for_init_complete.py
actions/cloudbolt_plugins/aws/poll_for_init_complete.py
import sys import time from infrastructure.models import Server from jobs.models import Job TIMEOUT = 600 def is_reachable(server): """ :type server: Server """ instance_id = server.ec2serverinfo.instance_id ec2_region = server.ec2serverinfo.ec2_region rh = server.resource_handler.cast() ...
import time from jobs.models import Job TIMEOUT = 600 def is_reachable(server): instance_id = server.ec2serverinfo.instance_id ec2_region = server.ec2serverinfo.ec2_region rh = server.resource_handler.cast() rh.connect_ec2(ec2_region) wc = rh.resource_technology.work_class instance = wc.ge...
Clean up poll for init complete script
Clean up poll for init complete script
Python
apache-2.0
CloudBoltSoftware/cloudbolt-forge,CloudBoltSoftware/cloudbolt-forge,CloudBoltSoftware/cloudbolt-forge,CloudBoltSoftware/cloudbolt-forge
fd77039104175a4b5702b46b21a2fa223676ddf4
bowser/Database.py
bowser/Database.py
import json import redis class Database(object): def __init__(self): self.redis = redis.StrictRedis(host='redis', port=6379, db=0) def set_data_of_server_channel(self, server, channel, data): self.redis.hmset(server, {channel: json.dumps(data)}) def fetch_data_of_server_channel(self, ser...
import json import redis class Database(object): def __init__(self): self.redis = redis.StrictRedis(host='redis', port=6379, db=0) def set_data_of_server_channel(self, server, channel, data): self.redis.hmset(server, {channel: json.dumps(data)}) def fetch_data_of_server_channel(self, ser...
Raise KeyErrors for missing data in redis
fix: Raise KeyErrors for missing data in redis
Python
mit
kevinkjt2000/discord-minecraft-server-status
3f166b110d4e8623966ca29c71445973da4876f9
armstrong/hatband/forms.py
armstrong/hatband/forms.py
from django import forms from django.db import models from . import widgets RICH_TEXT_DBFIELD_OVERRIDES = { models.TextField: {'widget': widgets.RichTextWidget}, } class BackboneFormMixin(object): class Media: js = ( 'hatband/js/jquery-1.6.2.min.js', 'hatband/js/under...
from django import forms from django.conf import settings from django.db import models from . import widgets RICH_TEXT_DBFIELD_OVERRIDES = { models.TextField: {'widget': widgets.RichTextWidget}, } class BackboneFormMixin(object): if getattr(settings, "ARMSTRONG_ADMIN_PROVIDE_STATIC", True): class Me...
Make it possible to turn off admin JS
Make it possible to turn off admin JS
Python
apache-2.0
armstrong/armstrong.hatband,armstrong/armstrong.hatband,texastribune/armstrong.hatband,armstrong/armstrong.hatband,texastribune/armstrong.hatband,texastribune/armstrong.hatband
e369824a1bd337e9245d010b93734832af4e0376
cetacean/response.py
cetacean/response.py
#!/usr/bin/env python # encoding: utf-8 import json import re from .resource import Resource class Response(Resource): """Represents an HTTP response that is hopefully a HAL document.""" def __init__(self, response): """Pass it a Requests response object. :response: A response object from ...
#!/usr/bin/env python # encoding: utf-8 import json import re from .resource import Resource class Response(Resource): """Represents an HTTP response that is hopefully a HAL document.""" _hal_regex = re.compile(r"application/hal\+json") def __init__(self, response): """Pass it a Requests respo...
Move _hal_regex to class scope.
Move _hal_regex to class scope.
Python
mit
nanorepublica/cetacean-python,benhamill/cetacean-python
46db910f9b9a150b785ea3b36a9e4f73db326d78
loader.py
loader.py
from etl import get_local_handles, ingest_feeds, CSV_ETL_CLASSES from local import LocalConfig from interface import Marcotti if __name__ == "__main__": settings = LocalConfig() marcotti = Marcotti(settings) with marcotti.create_session() as sess: for entity, etl_class in CSV_ETL_CLASSES: ...
import os import logging from etl import get_local_handles, ingest_feeds, CSV_ETL_CLASSES from local import LocalConfig from interface import Marcotti LOG_FORMAT = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s: %(message)s') ch = logging.FileHandler(os.path.join(LocalConfig().LOG_DIR, 'marcotti.log')) ch...
Add logging messages to data ingestion tool
Add logging messages to data ingestion tool
Python
mit
soccermetrics/marcotti-mls
dfc6b2d2d8cda75349dfab33d9639b5ea24cc520
contentcuration/contentcuration/ricecooker_versions.py
contentcuration/contentcuration/ricecooker_versions.py
import xmlrpclib from socket import gaierror VERSION_OK = "0.5.13" try: pypi = xmlrpclib.ServerProxy('https://pypi.python.org/pypi') VERSION_OK = pypi.package_releases('ricecooker')[0] except gaierror: pass VERSION_OK_MESSAGE = "Ricecooker v{} is up-to-date." VERSION_SOFT_WARNING = "0.5.6" VERSION_SOFT_W...
import xmlrpclib from socket import gaierror, error VERSION_OK = "0.6.0" try: pypi = xmlrpclib.ServerProxy('https://pypi.python.org/pypi') VERSION_OK = pypi.package_releases('ricecooker')[0] except (gaierror, error): pass VERSION_OK_MESSAGE = "Ricecooker v{} is up-to-date." VERSION_SOFT_WARNING = "0.5.6"...
Add error handling to reduce dependency on pypi
Add error handling to reduce dependency on pypi
Python
mit
DXCanas/content-curation,DXCanas/content-curation,jayoshih/content-curation,jayoshih/content-curation,jayoshih/content-curation,jayoshih/content-curation,fle-internal/content-curation,fle-internal/content-curation,fle-internal/content-curation,fle-internal/content-curation,DXCanas/content-curation,DXCanas/content-curat...
6a83ff3a2d1aca0a3663a36ca9502d3d86ea2a93
pirx/base.py
pirx/base.py
class Settings(object): def __init__(self): self._settings = {} def __setattr__(self, name, value): if name.startswith('_'): super(Settings, self).__setattr__(name, value) else: self._settings[name] = value def write(self): for name, value in self._s...
import collections class Settings(object): def __init__(self): self._settings = collections.OrderedDict() def __setattr__(self, name, value): if name.startswith('_'): super(Settings, self).__setattr__(name, value) else: self._settings[name] = value def wri...
Store settings with the OrderedDict
Store settings with the OrderedDict
Python
mit
piotrekw/pirx
6cfc9de7fe8fd048a75845a69bdeefc7c742bae4
oneall/django_oneall/management/commands/emaillogin.py
oneall/django_oneall/management/commands/emaillogin.py
# -*- coding: utf-8 -*- from django.core.management.base import BaseCommand from django.core.urlresolvers import reverse from ...auth import EmailTokenAuthBackend class Command(BaseCommand): help = "E-mail login without sending the actual e-mail." def add_arguments(self, parser): parser.add_argument...
# -*- coding: utf-8 -*- from django.core.mail import EmailMessage from django.core.management.base import BaseCommand from django.core.urlresolvers import reverse from ...auth import EmailTokenAuthBackend class Command(BaseCommand): help = "Issues an e-mail login token." def add_arguments(self, parser): ...
Add the possibility of testing SMTP from the command-line.
Add the possibility of testing SMTP from the command-line.
Python
mit
leandigo/django-oneall,ckot/django-oneall,leandigo/django-oneall,ckot/django-oneall
7a936665eff8a6a8f6889334ad2238cbfcded18b
member.py
member.py
import requests from credentials import label_id from gmailauth import refresh access_token = refresh() headers = {'Authorization': ('Bearer ' + access_token)} def list_messages(headers): params = {'labelIds': label_id, 'q': 'newer_than:3d'} r = requests.get('https://www.googleapis.com/gmail/v1/users...
import requests from base64 import urlsafe_b64decode from credentials import label_id, url1, url2 from gmailauth import refresh # access_token = refresh() headers = {'Authorization': ('Bearer ' + access_token)} def list_messages(headers): params = {'labelIds': label_id, 'q': 'newer_than:2d'} r = requ...
Return the order details URL from email body.
Return the order details URL from email body. There is currently no Agile API method that will return the order details for an activity so the URL from the email must be used in conjunction with a web scraper to get the relevant details.
Python
mit
deadlyraptor/reels
ed11fa0ebc365b8a7b0f31c8b09bf23b891e44b6
discover_tests.py
discover_tests.py
""" Simple auto test discovery. From http://stackoverflow.com/a/17004409 """ import os import sys import unittest def additional_tests(): setup_file = sys.modules['__main__'].__file__ setup_dir = os.path.abspath(os.path.dirname(setup_file)) return unittest.defaultTestLoader.discover(setup_dir)
""" Simple auto test discovery. From http://stackoverflow.com/a/17004409 """ import os import sys import unittest if not hasattr(unittest.defaultTestLoader, 'discover'): import unittest2 as unittest def additional_tests(): setup_file = sys.modules['__main__'].__file__ setup_dir = os.path.abspath(os.path....
Allow test discovery on Py26 with unittest2
Allow test discovery on Py26 with unittest2
Python
mit
QuLogic/python-future,michaelpacer/python-future,PythonCharmers/python-future,QuLogic/python-future,krischer/python-future,PythonCharmers/python-future,krischer/python-future,michaelpacer/python-future
63f04662f5ca22443ab6080f559ac898302cf103
tests/integration/conftest.py
tests/integration/conftest.py
def pytest_collection_modifyitems(session, config, items): # Ensure that all tests with require a redeploy are run after # tests that don't need a redeploy. final_list = [] on_redeploy_tests = [] for item in items: if item.get_marker('on_redeploy') is not None: on_redeploy_tests....
DEPLOY_TEST_BASENAME = 'test_features.py' def pytest_collection_modifyitems(session, config, items): # Ensure that all tests with require a redeploy are run after # tests that don't need a redeploy. start, end = _get_start_end_index(DEPLOY_TEST_BASENAME, items) marked = [] unmarked = [] for it...
Reorder redeploy tests within a single module
Reorder redeploy tests within a single module The original code for on_redeploy was making the assumption that there was only one integration test file. When test_package.py was added, the tests always failed because the redeploy tests were run *after* the package tests which messed with the module scope fixtures. No...
Python
apache-2.0
awslabs/chalice
7a0c0e6ed56e847b7b6300c1a0b4a427f26b296d
app/PRESUBMIT.py
app/PRESUBMIT.py
#!/usr/bin/python # Copyright (c) 2009 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Makes sure that the app/ code is cpplint clean.""" INCLUDE_CPP_FILES_ONLY = ( r'.*\.cc$', r'.*\.h$' ) EXCLUDE = ( # Autogener...
#!/usr/bin/python # Copyright (c) 2009 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Makes sure that the app/ code is cpplint clean.""" INCLUDE_CPP_FILES_ONLY = ( r'.*\.cc$', r'.*\.h$' ) EXCLUDE = ( # Autogener...
Make all changes to app/ run on all trybot platforms, not just the big three. Anyone who's changing a header here may break the chromeos build.
Make all changes to app/ run on all trybot platforms, not just the big three. Anyone who's changing a header here may break the chromeos build. BUG=none TEST=none Review URL: http://codereview.chromium.org/2838027 git-svn-id: dd90618784b6a4b323ea0c23a071cb1c9e6f2ac7@51000 4ff67af0-8c30-449e-8e8b-ad334ec8d88c
Python
bsd-3-clause
wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser
d42314b323aa0f8c764d72a5ebebc0e7d5ac88f3
nova/api/openstack/compute/schemas/v3/create_backup.py
nova/api/openstack/compute/schemas/v3/create_backup.py
# Copyright 2014 NEC Corporation. All rights reserved. # # 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 ...
# Copyright 2014 NEC Corporation. All rights reserved. # # 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 ...
Remove param check for backup type on v2.1 API
Remove param check for backup type on v2.1 API The backup type is only used by glance, so nova check it make no sense; currently we have daily and weekly as only valid param but someone may add 'monthly' as param. nova should allow it and delegate the error. This patch removes check on v2.1 API. Change-Id: I59bbc0f58...
Python
apache-2.0
devendermishrajio/nova,affo/nova,projectcalico/calico-nova,whitepages/nova,klmitch/nova,jianghuaw/nova,cernops/nova,Stavitsky/nova,fnordahl/nova,blueboxgroup/nova,CEG-FYP-OpenStack/scheduler,Francis-Liu/animated-broccoli,j-carpentier/nova,joker946/nova,hanlind/nova,rajalokan/nova,zhimin711/nova,silenceli/nova,ruslanlom...
720c6dbf9831b2b2ff701d0ca88303189583b9c4
opps/api/__init__.py
opps/api/__init__.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from django.http import HttpResponse from django.contrib.auth import authenticate from piston.handler import BaseHandler as Handler from opps.api.models import ApiKey class BaseHandler(Handler): def read(self, request): base = self.model.objects if ...
#!/usr/bin/env python # -*- coding: utf-8 -*- from django.http import HttpResponse from django.contrib.auth import authenticate from piston.handler import BaseHandler as Handler from opps.api.models import ApiKey class BaseHandler(Handler): def read(self, request): base = self.model.objects if ...
Add method appendModel on api BaseHandler
Add method appendModel on api BaseHandler
Python
mit
YACOWS/opps,opps/opps,jeanmask/opps,opps/opps,williamroot/opps,YACOWS/opps,williamroot/opps,opps/opps,YACOWS/opps,williamroot/opps,williamroot/opps,YACOWS/opps,opps/opps,jeanmask/opps,jeanmask/opps,jeanmask/opps
54c4e434276b242de56529e63bb6c5c61d891412
indico/modules/events/surveys/tasks.py
indico/modules/events/surveys/tasks.py
# This file is part of Indico. # Copyright (C) 2002 - 2015 European Organization for Nuclear Research (CERN). # # Indico is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 3 of the # License, or (a...
# This file is part of Indico. # Copyright (C) 2002 - 2015 European Organization for Nuclear Research (CERN). # # Indico is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 3 of the # License, or (a...
Use safer condition for survey start notification
Use safer condition for survey start notification
Python
mit
mvidalgarcia/indico,ThiefMaster/indico,pferreir/indico,indico/indico,mic4ael/indico,DirkHoffmann/indico,ThiefMaster/indico,indico/indico,ThiefMaster/indico,indico/indico,mic4ael/indico,indico/indico,OmeGak/indico,OmeGak/indico,pferreir/indico,DirkHoffmann/indico,mic4ael/indico,DirkHoffmann/indico,OmeGak/indico,DirkHoff...
fff234587be9b63270b345345f607df381031bdc
opendebates/tests/test_context_processors.py
opendebates/tests/test_context_processors.py
import urlparse from django.test import TestCase, override_settings from mock import patch, Mock from opendebates.context_processors import global_vars from opendebates.tests.factories import SubmissionFactory class NumberOfVotesTest(TestCase): def test_number_of_votes(self): mock_request = Mock() ...
import urlparse from django.test import TestCase, override_settings from mock import patch, Mock from opendebates.context_processors import global_vars from opendebates.tests.factories import SubmissionFactory class NumberOfVotesTest(TestCase): def test_number_of_votes(self): mock_request = Mock() ...
Fix test_email_url() after changes to email templating for sharing emails
Fix test_email_url() after changes to email templating for sharing emails
Python
apache-2.0
caktus/django-opendebates,caktus/django-opendebates,caktus/django-opendebates,ejucovy/django-opendebates,ejucovy/django-opendebates,ejucovy/django-opendebates,caktus/django-opendebates,ejucovy/django-opendebates
d0461fa033bdca4fffeff718219f8b71123449d7
pskb_website/models/__init__.py
pskb_website/models/__init__.py
""" Public model API """ from .article import search_for_article from .article import get_available_articles from .article import read_article from .article import save_article from .article import delete_article from .article import branch_article from .article import branch_or_save_article from .article import get_a...
""" Public model API """ from .article import search_for_article from .article import get_available_articles from .article import read_article from .article import save_article from .article import delete_article from .article import branch_article from .article import branch_or_save_article from .article import get_a...
Remove some functions from exported model API that are not used outside model layer
Remove some functions from exported model API that are not used outside model layer - Just some refactoring to trim down the number of things exported that aren't necessary at this time.
Python
agpl-3.0
paulocheque/guides-cms,pluralsight/guides-cms,pluralsight/guides-cms,paulocheque/guides-cms,paulocheque/guides-cms,pluralsight/guides-cms
77d264bd25e0556eb3680b845de22b62d2ebd3e6
bouncer/embed_detector.py
bouncer/embed_detector.py
import fnmatch import re from urllib.parse import urlparse # Hardcoded URL patterns where client is assumed to be embedded. # # Only the hostname and path are included in the pattern. The path must be # specified; use "example.com/*" to match all URLs on a particular domain. # # Patterns are shell-style wildcards ('*'...
import fnmatch import re from urllib.parse import urlparse # Hardcoded URL patterns where client is assumed to be embedded. # # Only the hostname and path are included in the pattern. The path must be # specified; use "example.com/*" to match all URLs on a particular domain. # # Patterns are shell-style wildcards ('*'...
Add APA websites to URL patterns where client is known to be embedded.
Add APA websites to URL patterns where client is known to be embedded. URL patterns provided by Kadidra McCloud at APA. Fixes https://github.com/hypothesis/product-backlog/issues/814
Python
bsd-2-clause
hypothesis/bouncer,hypothesis/bouncer,hypothesis/bouncer
ab035185e2c2023280c29aa5239deac820ec873d
openprescribing/openprescribing/settings/e2etest.py
openprescribing/openprescribing/settings/e2etest.py
from __future__ import absolute_import from .test import * DATABASES = { "default": { "ENGINE": "django.contrib.gis.db.backends.postgis", "NAME": utils.get_env_setting("E2E_DB_NAME"), "USER": utils.get_env_setting("DB_USER"), "PASSWORD": utils.get_env_setting("DB_PASS"), "HO...
from __future__ import absolute_import from .test import * DATABASES = { "default": { "ENGINE": "django.contrib.gis.db.backends.postgis", "NAME": utils.get_env_setting("E2E_DB_NAME"), "USER": utils.get_env_setting("DB_USER"), "PASSWORD": utils.get_env_setting("DB_PASS"), "HO...
Use real measure definitions in e2e tests
Use real measure definitions in e2e tests
Python
mit
ebmdatalab/openprescribing,annapowellsmith/openpresc,ebmdatalab/openprescribing,annapowellsmith/openpresc,ebmdatalab/openprescribing,ebmdatalab/openprescribing,annapowellsmith/openpresc,annapowellsmith/openpresc
0bb36aebdf0766c9244c6e317df89ddda86361b0
polls/admin.py
polls/admin.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.contrib import admin from .models import Question, Choice, Answer class ChoiceInline(admin.TabularInline): model = Choice class QuestionAdmin(admin.ModelAdmin): inlines = [ ChoiceInline, ] admin.site.register(Question, ...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.contrib import admin from .models import Question, Choice, Answer class ChoiceInline(admin.TabularInline): model = Choice def copy_question(modeladmin, request, queryset): for orig in queryset: q = Question(question_text="Ko...
Allow Questions to be copied
Allow Questions to be copied
Python
apache-2.0
gerard-/votingapp,gerard-/votingapp
6ca27fba516ddc63ad6bae98b20e5f9a42b37451
examples/plotting/file/image.py
examples/plotting/file/image.py
import numpy as np from bokeh.plotting import * from bokeh.objects import Range1d N = 1000 x = np.linspace(0, 10, N) y = np.linspace(0, 10, N) xx, yy = np.meshgrid(x, y) d = np.sin(xx)*np.cos(yy) output_file("image.html", title="image.py example") image( image=[d], x=[0], y=[0], dw=[10], dh=[10], palette=["Spe...
import numpy as np from bokeh.plotting import * N = 1000 x = np.linspace(0, 10, N) y = np.linspace(0, 10, N) xx, yy = np.meshgrid(x, y) d = np.sin(xx)*np.cos(yy) output_file("image.html", title="image.py example") image( image=[d], x=[0], y=[0], dw=[10], dh=[10], palette=["Spectral-11"], x_range=[0, 10], y...
Fix example and remove extraneous import.
Fix example and remove extraneous import.
Python
bsd-3-clause
birdsarah/bokeh,srinathv/bokeh,justacec/bokeh,eteq/bokeh,saifrahmed/bokeh,eteq/bokeh,rothnic/bokeh,dennisobrien/bokeh,deeplook/bokeh,draperjames/bokeh,tacaswell/bokeh,daodaoliang/bokeh,abele/bokeh,abele/bokeh,phobson/bokeh,Karel-van-de-Plassche/bokeh,percyfal/bokeh,ericdill/bokeh,timsnyder/bokeh,CrazyGuo/bokeh,ptitjano...
5d8b217659fdd4a7248a60b430a24fe909bca805
test/test_acoustics.py
test/test_acoustics.py
import numpy as np import pyfds as fds def test_acoustic_material(): water = fds.AcousticMaterial(1500, 1000) water.bulk_viscosity = 1e-3 water.shear_viscosity = 1e-3 assert np.isclose(water.absorption_coef, 7e-3 / 3)
import numpy as np import pyfds as fds def test_acoustic_material(): water = fds.AcousticMaterial(1500, 1000) water.bulk_viscosity = 1e-3 water.shear_viscosity = 1e-3 assert np.isclose(water.absorption_coef, 7e-3 / 3) def test_acoustic1d_create_matrices(): fld = fds.Acoustic1D(t_delta=1, t_sampl...
Add test case for Acoustic1D.create_matrices().
Add test case for Acoustic1D.create_matrices().
Python
bsd-3-clause
emtpb/pyfds
ebd9949177db3e2db51b47b74254908e300edc13
process_test.py
process_test.py
""" Copyright 2016 EMBL-European Bioinformatics Institute Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed...
""" Copyright 2016 EMBL-European Bioinformatics Institute 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...
Test script to work out the method for creating tasks
Test script to work out the method for creating tasks
Python
apache-2.0
Multiscale-Genomics/mg-process-fastq,Multiscale-Genomics/mg-process-fastq,Multiscale-Genomics/mg-process-fastq
8d55ea0cfbafc9f6dc1044ba27c3313c36ea73c6
pombola/south_africa/templatetags/za_people_display.py
pombola/south_africa/templatetags/za_people_display.py
from django import template register = template.Library() NO_PLACE_ORGS = ('parliament', 'national-assembly', ) MEMBER_ORGS = ('parliament', 'national-assembly', ) @register.assignment_tag() def should_display_place(organisation): return organisation.slug not in NO_PLACE_ORGS @register.assignment_tag() def sh...
from django import template register = template.Library() NO_PLACE_ORGS = ('parliament', 'national-assembly', ) MEMBER_ORGS = ('parliament', 'national-assembly', ) @register.assignment_tag() def should_display_place(organisation): if not organisation: return True return organisation.slug not in NO_P...
Fix display of people on constituency office page
[ZA] Fix display of people on constituency office page This template tag was being called without an organisation, so in production it was just silently failing, but in development it was raising an exception. This adds an extra check so that if there is no organisation then we just short circuit and return `True`.
Python
agpl-3.0
mysociety/pombola,mysociety/pombola,mysociety/pombola,mysociety/pombola,mysociety/pombola,mysociety/pombola
e44dc4d68845845f601803f31e10833a24cdb27c
prosite_app.py
prosite_app.py
#!/bin/env python3 # Prosite regular expressions matcher # Copyright (c) 2014 Tomasz Truszkowski # All rights reserved. import prosite_matcher if __name__ == '__main__': print("\n Hi, this is Prosite Matcher! \n") sequence = input("Sequence: ") regex = input("Regular expression: ") prositeMatcher = prosite_mat...
#!/bin/env python3 # Prosite regular expressions matcher # Copyright (c) 2014 Tomasz Truszkowski # All rights reserved. import prosite_matcher if __name__ == '__main__': print("\n Hi, this is Prosite Matcher! \n") sequence = input("Sequence: ") regex = input("Regular expression: ") if sequence != None and sequ...
Add check for empty sequence or regex.
Add check for empty sequence or regex.
Python
mit
stack-overflow/py_finite_state
017aa00a7b1f7a4a8a95f9c41576d4595d4085af
src/python/SparkSQLTwitter.py
src/python/SparkSQLTwitter.py
# A simple demo for working with SparkSQL and Tweets from pyspark import SparkContext, SparkConf from pyspark.sql import HiveContext, Row, IntegerType import json import sys if __name__ == "__main__": inputFile = sys.argv[1] conf = SparkConf().setAppName("SparkSQLTwitter") sc = SparkContext() hiveCtx =...
# A simple demo for working with SparkSQL and Tweets from pyspark import SparkContext, SparkConf from pyspark.sql import HiveContext, Row from pyspark.sql.types import IntegerType import json import sys if __name__ == "__main__": inputFile = sys.argv[1] conf = SparkConf().setAppName("SparkSQLTwitter") sc =...
Fix IntegerType import for Spark SQL
Fix IntegerType import for Spark SQL
Python
mit
DINESHKUMARMURUGAN/learning-spark,mohitsh/learning-spark,shimizust/learning-spark,JerryTseng/learning-spark,databricks/learning-spark,qingkaikong/learning-spark-examples,huixiang/learning-spark,qingkaikong/learning-spark-examples,obinsanni/learning-spark,bhagatsingh/learning-spark,holdenk/learning-spark-examples,NBSW/l...
4b172a9b2b9a9a70843bd41ad858d6f3120769b0
tests/test_funcargs.py
tests/test_funcargs.py
from django.test.client import Client from pytest_django.client import RequestFactory pytest_plugins = ['pytester'] def test_params(testdir): testdir.makeconftest(""" import os, sys import pytest_django as plugin sys.path.insert(0, os.path.realpath(os.path.join(os.path.dirname(plugin.__fil...
from django.test.client import Client from pytest_django.client import RequestFactory import py pytest_plugins = ['pytester'] def test_params(testdir): # Setting up the path isn't working - plugin.__file__ points to the wrong place return testdir.makeconftest(""" import os, sys import...
Disable params test for now
Disable params test for now
Python
bsd-3-clause
ojake/pytest-django,pelme/pytest-django,hoh/pytest-django,thedrow/pytest-django,pombredanne/pytest_django,felixonmars/pytest-django,ktosiek/pytest-django,RonnyPfannschmidt/pytest_django,aptivate/pytest-django,davidszotten/pytest-django,reincubate/pytest-django,bforchhammer/pytest-django,tomviner/pytest-django,bfirsh/py...
849552b1a2afdd89552e7c0395fc7be1786d5cbc
pybossa/auth/user.py
pybossa/auth/user.py
# -*- coding: utf8 -*- # This file is part of PyBossa. # # Copyright (C) 2013 SF Isle of Man Limited # # PyBossa 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...
# -*- coding: utf8 -*- # This file is part of PyBossa. # # Copyright (C) 2013 SF Isle of Man Limited # # PyBossa 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...
Exclude it from coverage as these permissions are not used yet.
Exclude it from coverage as these permissions are not used yet.
Python
agpl-3.0
PyBossa/pybossa,PyBossa/pybossa,CulturePlex/pybossa,jean/pybossa,inteligencia-coletiva-lsd/pybossa,harihpr/tweetclickers,stefanhahmann/pybossa,stefanhahmann/pybossa,geotagx/pybossa,geotagx/pybossa,CulturePlex/pybossa,OpenNewsLabs/pybossa,proyectos-analizo-info/pybossa-analizo-info,proyectos-analizo-info/pybossa-analizo...
5c9bdb1260562f0623807ce9a5751d33c806374a
pyfr/nputil.py
pyfr/nputil.py
# -*- coding: utf-8 -*- import numpy as np _npeval_syms = {'__builtins__': None, 'exp': np.exp, 'log': np.log, 'sin': np.sin, 'asin': np.arcsin, 'cos': np.cos, 'acos': np.arccos, 'tan': np.tan, 'atan': np.arctan, 'atan2': np.arctan2, 'ab...
# -*- coding: utf-8 -*- import numpy as np def npaligned(shape, dtype, alignb=32): nbytes = np.prod(shape)*np.dtype(dtype).itemsize buf = np.zeros(nbytes + alignb, dtype=np.uint8) off = -buf.ctypes.data % alignb return buf[off:nbytes + off].view(dtype).reshape(shape) _npeval_syms = {'__builtins__'...
Add support for allocating aligned NumPy arrays.
Add support for allocating aligned NumPy arrays.
Python
bsd-3-clause
tjcorona/PyFR,tjcorona/PyFR,BrianVermeire/PyFR,Aerojspark/PyFR,iyer-arvind/PyFR,tjcorona/PyFR
126c58d78360e69c2d16a40f9396a8158844e2b1
tests/test_creators.py
tests/test_creators.py
""" Test the post methods. """ def test_matrix_creation_endpoint(client): response = client.post('/matrix', { 'bibliography': '12312312', 'fields': 'title,description', }) print(response.json()) assert response.status_code == 200
""" Test the post methods. """ from condor.models import Bibliography def test_matrix_creation_endpoint(client, session): bib = Bibliography(eid='123', description='lorem') session.add(bib) session.flush() response = client.post('/matrix', { 'bibliography': '123', 'fields': 'title,des...
Create test for matrix post endpoint
Create test for matrix post endpoint
Python
mit
odarbelaeze/condor-api
e94d39bf330312dc46697a689b56f7518ebd501c
footer/magic/images.py
footer/magic/images.py
#import PIL import cairosvg from django.template import Template, Context def make_svg(context): svg_tmpl = Template(""" <svg xmlns="http://www.w3.org/2000/svg" width="500" height="600" viewBox="0 0 500 400"> <text x="0" y="0" font-family="Verdana" font-size="10" fill="blue" dy="0"> {{ n...
#import PIL import cairosvg from django.template import Template, Context def make_svg(context): svg_tmpl = Template(""" <svg xmlns="http://www.w3.org/2000/svg" width="500" height="600" viewBox="0 0 500 400"> <text x="0" y="0" font-family="Verdana" font-size="10" fill="blue" dy="0"> {{ n...
Add some color to SVG key/values
Add some color to SVG key/values
Python
mit
mihow/footer,mihow/footer,mihow/footer,mihow/footer
ebdafecea8c5b6597a7b2e2822afc98b9c47bb05
toast/math/__init__.py
toast/math/__init__.py
def lerp(fromValue, toValue, step): return fromValue + (toValue - fromValue) * step
def lerp(fromValue, toValue, percent): return fromValue + (toValue - fromValue) * percent
Refactor to lerp param names.
Refactor to lerp param names.
Python
mit
JoshuaSkelly/Toast,JSkelly/Toast
b2e743a19f13c898b2d95595a7a7175eca4bdb2c
results/urls.py
results/urls.py
__author__ = 'ankesh' from django.conf.urls import patterns, url import views urlpatterns = patterns('', url(r'^(?P<filename>[a-zA-Z0-9]+)/$', views.show_result, name='showResult'), url(r'^compare/(?P<filename>[a-zA-Z0-9]+)/$', views.compare_result, name='compareResult'), )
__author__ = 'ankesh' from django.conf.urls import patterns, url import views urlpatterns = patterns('', url(r'^(?P<filename>[a-zA-Z0-9]+)/$', views.show_result, name='showResult'), url(r'^compare/(?P<filename>[a-zA-Z0-9]+)/$', views.compare_result, name='compareResult'), url(r'^recent/$', views.recent_re...
Update URLs to include recent results
Update URLs to include recent results
Python
bsd-2-clause
ankeshanand/benchmark,ankeshanand/benchmark,ankeshanand/benchmark,ankeshanand/benchmark
7e3dfe47598401f4d5b96a377927473bb8adc244
bush/aws/base.py
bush/aws/base.py
from bush.aws.session import create_session class AWSBase: # USAGE = "" # SUB_COMMANDS = [] def __init__(self, options, resource_name): self.name = resource_name self.options = options self.session = create_session(options) self.resource = self.session.resource(resource_na...
from bush.aws.session import create_session class AWSBase: # USAGE = "" # SUB_COMMANDS = [] def __init__(self, options, resource_name): self.name = resource_name self.options = options self.session = create_session(options) @property def resource(self): if not has...
Set resource and client when it is needed
Set resource and client when it is needed
Python
mit
okamos/bush
2425f5a3b0b3f465eec86de9873696611dfda04a
example_project/users/social_pipeline.py
example_project/users/social_pipeline.py
import hashlib from rest_framework.response import Response def auto_logout(*args, **kwargs): """Do not compare current user with new one""" return {'user': None} def save_avatar(strategy, details, user=None, *args, **kwargs): """Get user avatar from social provider.""" if user: backend_name...
import hashlib from rest_framework.response import Response def auto_logout(*args, **kwargs): """Do not compare current user with new one""" return {'user': None} def save_avatar(strategy, details, user=None, *args, **kwargs): """Get user avatar from social provider.""" if user: backend_name...
Fix error message in example project
Fix error message in example project
Python
mit
st4lk/django-rest-social-auth,st4lk/django-rest-social-auth,st4lk/django-rest-social-auth
20f6df95d302ea79d11208ada6218a2c99d397e3
common.py
common.py
import json from base64 import b64encode # http://stackoverflow.com/a/4256027/212555 def del_none(o): """ Delete keys with the value ``None`` in a dictionary, recursively. This alters the input so you may wish to ``copy`` the dict first. """ if isinstance(o, dict): d = o else: ...
import json from base64 import b64encode # http://stackoverflow.com/a/4256027/212555 def del_none(o): """ Delete keys with the value ``None`` in a dictionary, recursively. This alters the input so you may wish to ``copy`` the dict first. """ if isinstance(o, dict): d = o.copy() else:...
Make a copy of dicts before deleting things from them when printing.
Make a copy of dicts before deleting things from them when printing.
Python
bsd-2-clause
brendanlong/mpeg-ts-inspector,brendanlong/mpeg-ts-inspector
fd7027ae889d61949998ea02fbb56dbc8e6005a4
polling_stations/apps/data_importers/management/commands/import_cheltenham.py
polling_stations/apps/data_importers/management/commands/import_cheltenham.py
from data_importers.management.commands import BaseHalaroseCsvImporter class Command(BaseHalaroseCsvImporter): council_id = "CHT" addresses_name = ( "2022-05-05/2022-02-25T12:48:35.558843/polling_station_export-2022-02-25.csv" ) stations_name = ( "2022-05-05/2022-02-25T12:48:35.558843/...
from data_importers.management.commands import BaseHalaroseCsvImporter class Command(BaseHalaroseCsvImporter): council_id = "CHT" addresses_name = ( "2022-05-05/2022-02-25T12:48:35.558843/polling_station_export-2022-02-25.csv" ) stations_name = ( "2022-05-05/2022-02-25T12:48:35.558843/...
Fix to CHT station name
Fix to CHT station name
Python
bsd-3-clause
DemocracyClub/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations
f2cdd8eb42afb9db5465e062544631684cabd24f
wagtail/contrib/wagtailfrontendcache/signal_handlers.py
wagtail/contrib/wagtailfrontendcache/signal_handlers.py
from django.db import models from django.db.models.signals import post_delete from wagtail.wagtailcore.models import Page from wagtail.wagtailcore.signals import page_published from wagtail.contrib.wagtailfrontendcache.utils import purge_page_from_cache def page_published_signal_handler(instance, **kwargs): pur...
from django.db import models from wagtail.wagtailcore.models import Page from wagtail.wagtailcore.signals import page_published, page_unpublished from wagtail.contrib.wagtailfrontendcache.utils import purge_page_from_cache def page_published_signal_handler(instance, **kwargs): purge_page_from_cache(instance) ...
Use page_unpublished signal in frontend cache invalidator
Use page_unpublished signal in frontend cache invalidator
Python
bsd-3-clause
Pennebaker/wagtail,chrxr/wagtail,jorge-marques/wagtail,jnns/wagtail,kurtw/wagtail,jorge-marques/wagtail,kaedroho/wagtail,WQuanfeng/wagtail,willcodefortea/wagtail,chimeno/wagtail,JoshBarr/wagtail,nimasmi/wagtail,zerolab/wagtail,torchbox/wagtail,kaedroho/wagtail,nutztherookie/wagtail,jorge-marques/wagtail,Klaudit/wagtail...
add50f0356756469c1ee1e52f13faee7df85f280
tests/rest/rest_test_suite.py
tests/rest/rest_test_suite.py
import sys import os sys.path.append(os.path.join(os.path.dirname(__file__), "../")) from http_test_suite import HTTPTestSuite from mozdef_util.utilities.dot_dict import DotDict import mock from configlib import OptionParser class RestTestDict(DotDict): @property def __dict__(self): return self c...
import sys import os sys.path.append(os.path.join(os.path.dirname(__file__), "../")) from http_test_suite import HTTPTestSuite from mozdef_util.utilities.dot_dict import DotDict import mock from configlib import OptionParser import importlib class RestTestDict(DotDict): @property def __dict__(self): ...
Fix import path for rest plugins
Fix import path for rest plugins
Python
mpl-2.0
mozilla/MozDef,mozilla/MozDef,mpurzynski/MozDef,mpurzynski/MozDef,mozilla/MozDef,mpurzynski/MozDef,jeffbryner/MozDef,jeffbryner/MozDef,mozilla/MozDef,mpurzynski/MozDef,jeffbryner/MozDef,jeffbryner/MozDef
5b516cd3e6363c4c995022c358fabeb0cc543115
tests/test_route_requester.py
tests/test_route_requester.py
import unittest from pydirections.route_requester import DirectionsRequest from pydirections.exceptions import InvalidModeError, InvalidAPIKeyError, InvalidAlternativeError class TestOptionalParameters(unittest.TestCase): requester = DirectionsRequest(origin="San Francisco, CA", destination="Palo Alto, CA") def tes...
import unittest from pydirections.route_requester import DirectionsRequest from pydirections.exceptions import InvalidModeError, InvalidAPIKeyError, InvalidAlternativeError requester = DirectionsRequest(origin="San Francisco, CA", destination="Palo Alto, CA") class TestOptionalParameters(unittest.TestCase): def test...
Fix bug in unit tests
Fix bug in unit tests
Python
apache-2.0
apranav19/pydirections
9b720026722ce92a8c0e05aa041d6e861c5e4e82
changes/api/jobstep_deallocate.py
changes/api/jobstep_deallocate.py
from __future__ import absolute_import, division, unicode_literals from changes.api.base import APIView from changes.constants import Status from changes.config import db from changes.jobs.sync_job_step import sync_job_step from changes.models import JobStep class JobStepDeallocateAPIView(APIView): def post(sel...
from __future__ import absolute_import, division, unicode_literals from changes.api.base import APIView from changes.constants import Status from changes.config import db from changes.jobs.sync_job_step import sync_job_step from changes.models import JobStep class JobStepDeallocateAPIView(APIView): def post(sel...
Allow running jobsteps to be deallocated
Allow running jobsteps to be deallocated
Python
apache-2.0
dropbox/changes,bowlofstew/changes,dropbox/changes,bowlofstew/changes,bowlofstew/changes,dropbox/changes,wfxiang08/changes,wfxiang08/changes,dropbox/changes,bowlofstew/changes,wfxiang08/changes,wfxiang08/changes
64cd71fd171cd1b76b111aedc94423006176f811
src/tldt/cli.py
src/tldt/cli.py
import argparse import tldt def main(): parser = argparse.ArgumentParser(description="cacat") parser.add_argument("head_repo") parser.add_argument("head_sha") parser.add_argument("base_repo") parser.add_argument("base_sha") args = parser.parse_args() tldt.main(head_repo=args.head_repo, ...
import argparse import os.path import tldt def main(): user_home = os.path.expanduser("~") parser = argparse.ArgumentParser(description="cacat") parser.add_argument("head_repo") parser.add_argument("head_sha") parser.add_argument("base_repo") parser.add_argument("base_sha") parser.add_arg...
Add configuration file option with default to ~/tldt.ini
Add configuration file option with default to ~/tldt.ini
Python
unlicense
rciorba/tldt,rciorba/tldt
45e04697303eb85330bd61f1b386e483fc42f49b
src/oscar/templatetags/currency_filters.py
src/oscar/templatetags/currency_filters.py
from decimal import Decimal as D from decimal import InvalidOperation from babel.numbers import format_currency from django import template from django.conf import settings from django.utils.translation import get_language, to_locale register = template.Library() @register.filter(name='currency') def currency(value...
from decimal import Decimal as D from decimal import InvalidOperation from babel.numbers import format_currency from django import template from django.conf import settings from django.utils.translation import get_language, to_locale register = template.Library() @register.filter(name='currency') def currency(value...
Fix for missing default in currency filter
Fix for missing default in currency filter
Python
bsd-3-clause
solarissmoke/django-oscar,solarissmoke/django-oscar,django-oscar/django-oscar,solarissmoke/django-oscar,solarissmoke/django-oscar,django-oscar/django-oscar,django-oscar/django-oscar,django-oscar/django-oscar
6cf42d661facf1c11de545959b91c073709eac8e
webapp_tests.py
webapp_tests.py
#!/usr/bin/env python import os import webapp import unittest class WebappTestExtractingServiceDomainsFromLinks(unittest.TestCase): #def setUp(self): # self.app = webapp.app.test_client() def test_extract_service_domain_from_link(self): status, domain = webapp.extract_service_domain_from_link(...
#!/usr/bin/env python import os import webapp import unittest class WebappTestExtractingServiceDomainsFromLinks(unittest.TestCase): #def setUp(self): # self.app = webapp.app.test_client() def test_extract_service_domain_from_link(self): status, domain = webapp.extract_service_domain_from_link(...
Add a test for extracting service domain from a link
Add a test for extracting service domain from a link
Python
mit
alphagov/service-domain-checker
2f6dc1d43bd402152c7807e905cc808899a640d2
mail/views.py
mail/views.py
import logging from django.core.mail import EmailMessage from django.http import JsonResponse from django.middleware import csrf from django.views.decorators.csrf import csrf_exempt from django.shortcuts import redirect from rest_framework.decorators import api_view @csrf_exempt @api_view(['POST', 'GET']) def send_c...
import logging from django.core.mail import EmailMessage from django.http import JsonResponse from django.middleware import csrf from django.views.decorators.csrf import csrf_exempt from django.shortcuts import redirect from rest_framework.decorators import api_view @csrf_exempt @api_view(['POST', 'GET']) def send_c...
Change bulk order email address to Tory
Change bulk order email address to Tory
Python
agpl-3.0
openstax/openstax-cms,openstax/openstax-cms,Connexions/openstax-cms,openstax/openstax-cms,Connexions/openstax-cms,openstax/openstax-cms
c12a1b53166c34c074e018fcc149a0aa2db56b43
helpscout/models/folder.py
helpscout/models/folder.py
# -*- coding: utf-8 -*- # Copyright 2017-TODAY LasLabs Inc. # License MIT (https://opensource.org/licenses/MIT). import properties from .. import BaseModel class Folder(BaseModel): name = properties.String( 'Folder name', required=True, ) type = properties.StringChoice( 'The typ...
# -*- coding: utf-8 -*- # Copyright 2017-TODAY LasLabs Inc. # License MIT (https://opensource.org/licenses/MIT). import properties from .. import BaseModel class Folder(BaseModel): name = properties.String( 'Folder name', required=True, ) type = properties.StringChoice( 'The typ...
Add 'team' to Folder type options
[ADD] Add 'team' to Folder type options
Python
mit
LasLabs/python-helpscout
bccfc6d3c0035e2a5668607ebb7dd6047ee1942f
kokki/cookbooks/mdadm/recipes/default.py
kokki/cookbooks/mdadm/recipes/default.py
from kokki import * if env.config.mdadm.arrays: Package("mdadm") Execute("mdadm-update-conf", action = "nothing", command = ("(" "echo DEVICE partitions > /etc/mdadm/mdadm.conf" "; mdadm --detail --scan >> /etc/mdadm/mdadm.conf" ")" )) for array in env.config.mdadm.arrays: en...
from kokki import * if env.config.mdadm.arrays: Package("mdadm") Execute("mdadm-update-conf", action = "nothing", command = ("(" "echo DEVICE partitions > /etc/mdadm/mdadm.conf" "; mdadm --detail --scan >> /etc/mdadm/mdadm.conf" ")" )) for array in env.config.mdadm.arrays: fs...
Fix to mounting mdadm raid arrays
Fix to mounting mdadm raid arrays
Python
bsd-3-clause
samuel/kokki
4f2e23fe260e5f061d7d57821908492f14a2c56a
withtool/subprocess.py
withtool/subprocess.py
import subprocess def run(command): try: subprocess.check_call(command, shell=True) except: pass
import subprocess def run(command): try: subprocess.check_call(command, shell=True) except Exception: pass
Set expected exception class in "except" block
Set expected exception class in "except" block Fix issue E722 of flake8
Python
mit
renanivo/with
ff308a17c79fe2c27dcb2a1f888ee1332f6fdc11
events.py
events.py
# encoding: utf-8 import Natural.util as util import sublime, sublime_plugin class PerformEventListener(sublime_plugin.EventListener): """Suggest subroutine completions for the perform statement.""" def on_query_completions(self, view, prefix, points): if not util.is_natural_file(view): ...
# encoding: utf-8 import Natural.util as util import sublime, sublime_plugin class PerformEventListener(sublime_plugin.EventListener): """Suggest subroutine completions for the perform statement.""" def on_query_completions(self, view, prefix, points): if not util.is_natural_file(view): ...
Add a ruler to column 72
Add a ruler to column 72
Python
mit
andref/Unnatural-Sublime-Package
5a2f848badcdf9bf968e23cfb55f53eb023d18a4
tests/helper.py
tests/helper.py
import unittest import os import yaml from functools import wraps from cmd import init_db, seed_db from models import db from scuevals_api import create_app class TestCase(unittest.TestCase): def setUp(self): app = create_app() app.config['SQLALCHEMY_DATABASE_URI'] = os.environ['TEST_DATABASE_URL'...
import unittest import os import yaml from functools import wraps from flask_jwt_simple import create_jwt from cmd import init_db, seed_db from models import db, Student from scuevals_api import create_app class TestCase(unittest.TestCase): def setUp(self): app = create_app() app.config['SQLALCHEM...
Add authentication to base TestCase
Add authentication to base TestCase
Python
agpl-3.0
SCUEvals/scuevals-api,SCUEvals/scuevals-api
9ed0848a869fc3a4e16890af609259d18b622056
ideascaly/utils.py
ideascaly/utils.py
# IdeaScaly # Copyright 2015 Jorge Saldivar # See LICENSE for details. import six import dateutil.parser from datetime import datetime def parse_datetime(str_date): date_is = dateutil.parser.parse(str_date) return date_is def parse_html_value(html): return html[html.find('>')+1:html.rfind('<')] def ...
# IdeaScaly # Copyright 2015 Jorge Saldivar # See LICENSE for details. import six import dateutil.parser from datetime import datetime def parse_datetime(str_date): try: date_is = dateutil.parser.parse(str_date) return date_is except: print("Invalid date: %s" % str_date) retu...
Add try except to the method that parse idea datetime
Add try except to the method that parse idea datetime
Python
mit
joausaga/ideascaly
811421407379dedc217795000f6f2cbe54510f96
kolibri/core/utils/urls.py
kolibri/core/utils/urls.py
from django.urls import reverse from six.moves.urllib.parse import urljoin from kolibri.utils.conf import OPTIONS def reverse_remote( baseurl, viewname, urlconf=None, args=None, kwargs=None, current_app=None ): # Get the reversed URL reversed_url = reverse( viewname, urlconf=urlconf, args=args, k...
from django.urls import reverse from six.moves.urllib.parse import urljoin from kolibri.utils.conf import OPTIONS def reverse_remote( baseurl, viewname, urlconf=None, args=None, kwargs=None, current_app=None ): # Get the reversed URL reversed_url = reverse( viewname, urlconf=urlconf, args=args, k...
Truncate rather than replace to prevent erroneous substitutions.
Truncate rather than replace to prevent erroneous substitutions.
Python
mit
learningequality/kolibri,learningequality/kolibri,learningequality/kolibri,learningequality/kolibri
fe873844448d4123520e9bd6afe3231d4c952850
job_runner/wsgi.py
job_runner/wsgi.py
""" WSGI config for job_runner project. This module contains the WSGI application used by Django's development server and any production WSGI deployments. It should expose a module-level variable named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover this application via the ``WSGI_APPLICATION...
""" WSGI config for job_runner project. This module contains the WSGI application used by Django's development server and any production WSGI deployments. It should expose a module-level variable named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover this application via the ``WSGI_APPLICATION...
Update default settings to development.
Update default settings to development.
Python
bsd-3-clause
spilgames/job-runner,spilgames/job-runner
741133b4fa502fc585c771abef96b6213d3f5214
pyheufybot/modules/nickservidentify.py
pyheufybot/modules/nickservidentify.py
from module_interface import Module, ModuleType from message import IRCResponse, ResponseType from pyheufybot import globalvars class NickServIdentify(Module): def __init__(self): self.moduleType = ModuleType.PASSIVE self.messageTypes = ["USER"] self.helpText = "Attempts to log into NickSer...
from pyheufybot.module_interface import Module, ModuleType from pyheufybot.message import IRCResponse, ResponseType from pyheufybot import globalvars class NickServIdentify(Module): def __init__(self): self.moduleType = ModuleType.PASSIVE self.messageTypes = ["USER"] self.helpText = "Attemp...
Fix the syntax for NickServ logins
Fix the syntax for NickServ logins
Python
mit
Heufneutje/PyHeufyBot,Heufneutje/PyHeufyBot
34bd55b33e865c65386f934c7ac0b89f3cc76485
edgedb/lang/common/shell/reqs.py
edgedb/lang/common/shell/reqs.py
## # Copyright (c) 2010 Sprymix Inc. # All rights reserved. # # See LICENSE for details. ## from metamagic import app from metamagic.exceptions import MetamagicError class UnsatisfiedRequirementError(MetamagicError): pass class CommandRequirement: pass class ValidApplication(CommandRequirement): def...
## # Copyright (c) 2010 Sprymix Inc. # All rights reserved. # # See LICENSE for details. ## from metamagic.exceptions import MetamagicError class UnsatisfiedRequirementError(MetamagicError): pass class CommandRequirement: pass
Drop 'metamagic.app' package. Long live Node.
app: Drop 'metamagic.app' package. Long live Node.
Python
apache-2.0
edgedb/edgedb,edgedb/edgedb,edgedb/edgedb
63a7b11d3ae51a944bf2e70637dea503e455c2f5
fontdump/cli.py
fontdump/cli.py
#!/usr/bin/env python # -*- coding: utf-8 -*-# from collections import OrderedDict import requests import cssutils USER_AGENTS = OrderedDict() USER_AGENTS['woff'] = 'Mozilla/5.0 AppleWebKit/537.36 Chrome/30', # Chrome USER_AGENTS['ttf'] = 'Mozilla/5.0 (Linux; U; Android 2.1-update1;)', #Andord 2 USER_AGENTS['eot'] = ...
#!/usr/bin/env python # -*- coding: utf-8 -*-# import requests import cssutils USER_AGENTS = { 'woff': 'Mozilla/5.0 AppleWebKit/537.36 Chrome/30', # Chrome 'eot': 'Mozilla/4.0 (compatible; MSIE 6.0;)', # IE6 'ttf': 'Mozilla/5.0 (Linux; U; Android 2.1-update1;)', #Andord 2 'svg': 'Mozilla/4.0 (iPad; CPU...
Revert "The order of the formats matters. Use OrderedDict instead of dict"
Revert "The order of the formats matters. Use OrderedDict instead of dict" I can't rely on the order of dict. The control flow is more complex. This reverts commit 3389ed71971ddacd185bbbf8fe667a8651108c70.
Python
mit
glasslion/fontdump
ff9d613897774f3125f2b28905528962b1761deb
core/timeline.py
core/timeline.py
from collections import Counter from matplotlib import pyplot as plt import datetime def create_timeline( data ): if len(data) == 0: print "Dataset empty." return dates = map( lambda d: d['date'], data ) timeline_data = Counter( dates ) x_axis = sorted( timeline_data ) y_axis = []...
from collections import Counter from matplotlib import pyplot as plt import datetime import data_loader def create_timeline( data ): if len(data) == 0: print "Dataset empty." return dates = map( lambda d: d['date'], data ) timeline_data = Counter( dates ) x_axis = sorted( timeline_dat...
Add standalone method for using from command line
Add standalone method for using from command line
Python
mit
HIIT/hybra-core,HIIT/hybra-core,HIIT/hybra-core,HIIT/hybra-core,HIIT/hybra-core
62f9608d50898d0a82e013d54454ed1edb004cff
fab_deploy/joyent/setup.py
fab_deploy/joyent/setup.py
from fabric.api import run, sudo from fabric.contrib.files import append from fab_deploy.base import setup as base_setup class JoyentMixin(object): def _set_profile(self): append('/etc/profile', 'CC="gcc -m64"; export CC', use_sudo=True) append('/etc/profile', 'LDSHARED="gcc -m64 -G"; export LDS...
from fabric.api import run, sudo from fabric.contrib.files import append from fab_deploy.base import setup as base_setup class JoyentMixin(object): def _set_profile(self): append('/etc/profile', 'CC="gcc -m64"; export CC', use_sudo=True) append('/etc/profile', 'LDSHARED="gcc -m64 -G"; export LDS...
Add environ vars for joyent
Add environ vars for joyent
Python
mit
ff0000/red-fab-deploy2,ff0000/red-fab-deploy2,ff0000/red-fab-deploy2
fc3cf6966f66f0929c48b1f24bede295fb3aec35
Wahji-dev/setup/removeWahji.py
Wahji-dev/setup/removeWahji.py
#deletes wahji content import os, shutil, platform def rem(loc): os.chdir(loc) print "deleting content" """delete them folder and its contents""" shutil.rmtree("themes") """delete .wahji file""" os.remove(".wahji") """delete 4040.html file""" os.remove("404.html") """delete content folder""" shutil....
#deletes wahji content import os, shutil, platform def rem(loc): os.chdir(loc) site = raw_input("Input site folder: ") print "Are you sure you want to delete", site, "Y/N: " confirm = raw_input() if confirm == "Y" or confirm == "y": """delete site folder""" shutil.rmtree(site) print "Deleting site" ...
Remove now asks for site file to be deleted
Remove now asks for site file to be deleted
Python
mit
mborn319/Wahji,mborn319/Wahji,mborn319/Wahji
6b55f079d595700cd84d12d4f351e52614d291c5
openacademy/model/openacademy_session.py
openacademy/model/openacademy_session.py
# -*- coding: utf-8 -*- from openerp import fields,models class Session(models.Model): _name = 'openacademy.session' name = fields.Char(required=True) start_date = fields.Date() duration = fields.Float(digits=(6,2), help="Duration in days") seats = fields.Integer(string="Number of seats") inst...
# -*- coding: utf-8 -*- from openerp import fields,models class Session(models.Model): _name = 'openacademy.session' name = fields.Char(required=True) start_date = fields.Date() duration = fields.Float(digits=(6,2), help="Duration in days") seats = fields.Integer(string="Number of seats") ins...
Add domain ir and ilike
[REF] openacademy: Add domain ir and ilike
Python
apache-2.0
arogel/openacademy-project
91d104a25db499ccef54878dcbfce42dbb4aa932
taskin/task.py
taskin/task.py
import abc def do_flow(flow, result=None): for item in flow: print(item, result) result = item(result) return result class MapTask(object): def __init__(self, args, task): self.args = args self.task = task self.pool = Pool(cpu_count()) def iter_input(self, i...
from multiprocessing import Pool as ProcessPool from multiprocessing.dummy import Pool as ThreadPool from multiprocessing import cpu_count def do_flow(flow, result=None): for item in flow: print(item, result) result = item(result) return result class PoolAPI(object): def map(self, *args,...
Add totally untested pools ;)
Add totally untested pools ;)
Python
bsd-3-clause
ionrock/taskin
247c4dcaf3e1c1f9c069ab8a2fc06cfcd75f8ea9
UM/Util.py
UM/Util.py
# Copyright (c) 2016 Ultimaker B.V. # Uranium is released under the terms of the AGPLv3 or higher. ## Convert a value to a boolean # # \param \type{bool|str|int} any value. # \return \type{bool} def parseBool(value): return value in [True, "True", "true", 1]
# Copyright (c) 2016 Ultimaker B.V. # Uranium is released under the terms of the AGPLv3 or higher. ## Convert a value to a boolean # # \param \type{bool|str|int} any value. # \return \type{bool} def parseBool(value): return value in [True, "True", "true", "Yes", "yes", 1]
Add "Yes" as an option for parsing bools
Add "Yes" as an option for parsing bools CURA-2204
Python
agpl-3.0
onitake/Uranium,onitake/Uranium
6e3ddfc47487a8841a79d6265c96ba63005fccec
bnw_handlers/command_onoff.py
bnw_handlers/command_onoff.py
# -*- coding: utf-8 -*- #from twisted.words.xish import domish from base import * import random import bnw_core.bnw_objects as objs @require_auth @defer.inlineCallbacks def cmd_on(request): """ Включение доставки сообщений """ _ = yield objs.User.mupdate({'name':request.user['name']},{'$set':{'off':False}},s...
# -*- coding: utf-8 -*- #from twisted.words.xish import domish from base import * import random import bnw_core.bnw_objects as objs @require_auth @defer.inlineCallbacks def cmd_on(request): """ Включение доставки сообщений """ _ = yield objs.User.mupdate({'name':request.user['name']},{'$set':{'off':False}},s...
Fix on/off if there is no 'off' field.
Fix on/off if there is no 'off' field.
Python
bsd-2-clause
un-def/bnw,stiletto/bnw,un-def/bnw,stiletto/bnw,ojab/bnw,ojab/bnw,stiletto/bnw,un-def/bnw,ojab/bnw,stiletto/bnw,un-def/bnw,ojab/bnw
bbef6c5f235fc3320c9c748a32cb3af04d3903d1
list_all_users_in_group.py
list_all_users_in_group.py
#! /usr/bin/env python # -*- coding: utf-8 -*- import grp import pwd import inspect import argparse def list_all_users_in_group(groupname): """Get list of all users of group. Get sorted list of all users of group GROUP, including users with main group GROUP. Origin in https://github.com/vazhnov/list...
#! /usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function import grp import pwd import inspect import argparse def list_all_users_in_group(groupname): """Get list of all users of group. Get sorted list of all users of group GROUP, including users with main group GROUP. Ori...
Fix pylint: Unnecessary parens after u'print' keyword (superfluous-parens)
Fix pylint: Unnecessary parens after u'print' keyword (superfluous-parens)
Python
cc0-1.0
vazhnov/list_all_users_in_group
82e82805eae5b070aec49816977d2f50ff274d30
controllers/api/api_match_controller.py
controllers/api/api_match_controller.py
import json import webapp2 from controllers.api.api_base_controller import ApiBaseController from helpers.model_to_dict import ModelToDict from models.match import Match class ApiMatchControllerBase(ApiBaseController): CACHE_KEY_FORMAT = "apiv2_match_controller_{}" # (match_key) CACHE_VERSION = 2 CAC...
import json import webapp2 from controllers.api.api_base_controller import ApiBaseController from helpers.model_to_dict import ModelToDict from models.match import Match class ApiMatchControllerBase(ApiBaseController): def __init__(self, *args, **kw): super(ApiMatchControllerBase, self).__init__(*args...
Move cache key out of base class
Move cache key out of base class
Python
mit
josephbisch/the-blue-alliance,bvisness/the-blue-alliance,bdaroz/the-blue-alliance,bvisness/the-blue-alliance,fangeugene/the-blue-alliance,1fish2/the-blue-alliance,phil-lopreiato/the-blue-alliance,synth3tk/the-blue-alliance,jaredhasenklein/the-blue-alliance,tsteward/the-blue-alliance,nwalters512/the-blue-alliance,phil-l...
b2771e6b33bd889c971b77e1b30c1cc5a0b9eb24
platform.py
platform.py
# Copyright 2014-present PlatformIO <contact@platformio.org> # # 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 applicabl...
# Copyright 2014-present PlatformIO <contact@platformio.org> # # 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 applicabl...
Use appropriate package for mxchip_az3166
Use appropriate package for mxchip_az3166
Python
apache-2.0
platformio/platform-ststm32,platformio/platform-ststm32
1096d0f13ebbc5900c21626a5caf6276b36229d8
Lib/test/test_coding.py
Lib/test/test_coding.py
import test.test_support, unittest import os class CodingTest(unittest.TestCase): def test_bad_coding(self): module_name = 'bad_coding' self.verify_bad_module(module_name) def test_bad_coding2(self): module_name = 'bad_coding2' self.verify_bad_module(module_name) def veri...
import test.test_support, unittest import os class CodingTest(unittest.TestCase): def test_bad_coding(self): module_name = 'bad_coding' self.verify_bad_module(module_name) def test_bad_coding2(self): module_name = 'bad_coding2' self.verify_bad_module(module_name) def veri...
Fix a test failure on non-UTF-8 locales: bad_coding2.py is encoded in utf-8.
Fix a test failure on non-UTF-8 locales: bad_coding2.py is encoded in utf-8.
Python
mit
sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator
37588d466928e9f25b55d627772120f16df095ec
model_presenter.py
model_presenter.py
import matplotlib # Do not use X for plotting matplotlib.use('Agg') import matplotlib.pyplot as plt from matplotlib.dates import DateFormatter from matplotlib.ticker import FormatStrFormatter from tempfile import NamedTemporaryFile def plot_to_file(symbol, timestamp, close, score): fig, ax1 = plt.subplots() ...
import matplotlib # Do not use X for plotting matplotlib.use('Agg') import matplotlib.pyplot as plt from matplotlib.dates import DateFormatter from matplotlib.ticker import FormatStrFormatter from tempfile import NamedTemporaryFile def plot_to_file(symbol, timestamp, close, score): fig, ax1 = plt.subplots() ...
Compress the images to be sent
Compress the images to be sent
Python
mit
cjluo/money-monkey
9901044b2b3218714a3c807e982db518aa97a446
djangoautoconf/features/bae_settings.py
djangoautoconf/features/bae_settings.py
################################## # Added for BAE ################################## try: CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 'LOCATION': const.CACHE_ADDR, 'TIMEOUT': 60, } } except: pass try: fro...
################################## # Added for BAE ################################## try: CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 'LOCATION': const.CACHE_ADDR, 'TIMEOUT': 60, } } except: pass try: fr...
Move BAE secret into try catch block
Move BAE secret into try catch block
Python
bsd-3-clause
weijia/djangoautoconf,weijia/djangoautoconf
3ed807b44289c00d6a82b0c253f7ff8072336fdd
changes/jobs/cleanup_tasks.py
changes/jobs/cleanup_tasks.py
from __future__ import absolute_import from datetime import datetime, timedelta from changes.config import queue from changes.constants import Status from changes.models.task import Task from changes.queue.task import TrackedTask CHECK_TIME = timedelta(minutes=60) EXPIRE_TIME = timedelta(days=7) # NOTE: This isn't...
from __future__ import absolute_import from datetime import datetime, timedelta from changes.config import queue, statsreporter from changes.constants import Status from changes.models.task import Task from changes.queue.task import TrackedTask CHECK_TIME = timedelta(minutes=60) EXPIRE_TIME = timedelta(days=7) # N...
Make periodic expired task deletion more efficient
Make periodic expired task deletion more efficient Summary: Also adds tracking for the number of tasks deleted at each run. Test Plan: None Reviewers: paulruan Reviewed By: paulruan Subscribers: changesbot, anupc Differential Revision: https://tails.corp.dropbox.com/D232735
Python
apache-2.0
dropbox/changes,dropbox/changes,dropbox/changes,dropbox/changes
dd8c85a49a31693f43e6f6877a0657d63cbc1b01
auth0/v2/device_credentials.py
auth0/v2/device_credentials.py
from .rest import RestClient class DeviceCredentials(object): """Auth0 connection endpoints Args: domain (str): Your Auth0 domain, e.g: 'username.auth0.com' jwt_token (str): An API token created with your account's global keys. You can create one by using the token generator in ...
from .rest import RestClient class DeviceCredentials(object): """Auth0 connection endpoints Args: domain (str): Your Auth0 domain, e.g: 'username.auth0.com' jwt_token (str): An API token created with your account's global keys. You can create one by using the token generator in ...
Remove default arguments for user_id, client_id and type
Remove default arguments for user_id, client_id and type
Python
mit
auth0/auth0-python,auth0/auth0-python
24ea32f71faab214a6f350d2d48b2f5715d8262d
manage.py
manage.py
from flask_restful import Api from flask_migrate import Migrate, MigrateCommand from flask_script import Manager from app import app from app import db from app.auth import Register, Login from app.bucketlist_api import BucketList, BucketListEntry from app.bucketlist_items import BucketListItems, BucketListItemSingle ...
from flask_restful import Api from flask_migrate import Migrate, MigrateCommand from flask_script import Manager from app import app, db from app.auth import Register, Login from app.bucketlist_api import BucketLists, BucketListSingle from app.bucketlist_items import BucketListItems, BucketListItemSingle migrate = Mig...
Set urls for bucketlist items endpoints
Set urls for bucketlist items endpoints
Python
mit
andela-bmwenda/cp2-bucketlist-api
638a1c434ef8202774675581c3659511fa9d1cd3
vehicles/management/commands/import_edinburgh.py
vehicles/management/commands/import_edinburgh.py
from django.contrib.gis.geos import Point from busstops.models import Service from ...models import Vehicle, VehicleLocation, VehicleJourney from ..import_live_vehicles import ImportLiveVehiclesCommand class Command(ImportLiveVehiclesCommand): url = 'http://tfeapp.com/live/vehicles.php' source_name = 'TfE' ...
from django.contrib.gis.geos import Point from busstops.models import Service from ...models import Vehicle, VehicleLocation, VehicleJourney from ..import_live_vehicles import ImportLiveVehiclesCommand class Command(ImportLiveVehiclesCommand): url = 'http://tfeapp.com/live/vehicles.php' source_name = 'TfE' ...
Fix null Edinburgh journey code or destination
Fix null Edinburgh journey code or destination
Python
mpl-2.0
jclgoodwin/bustimes.org.uk,jclgoodwin/bustimes.org.uk,jclgoodwin/bustimes.org.uk,jclgoodwin/bustimes.org.uk
c9da64ac1c90abdee8fc72488a4bef58a95aa7c6
biwako/bin/fields/compounds.py
biwako/bin/fields/compounds.py
import io from .base import Field, DynamicValue, FullyDecoded class SubStructure(Field): def __init__(self, structure, *args, **kwargs): self.structure = structure super(SubStructure, self).__init__(*args, **kwargs) def read(self, file): value = self.structure(file) ...
import io from .base import Field, DynamicValue, FullyDecoded class SubStructure(Field): def __init__(self, structure, *args, **kwargs): self.structure = structure super(SubStructure, self).__init__(*args, **kwargs) def read(self, file): value = self.structure(file) ...
Fix List to use the new decoding system
Fix List to use the new decoding system
Python
bsd-3-clause
gulopine/steel
1e5e2a236277dc9ba11f9fe4aff3279f692da3f7
ploy/tests/conftest.py
ploy/tests/conftest.py
from mock import patch import pytest import os import shutil import tempfile class Directory: def __init__(self, directory): self.directory = directory def __getitem__(self, name): path = os.path.join(self.directory, name) assert not os.path.relpath(path, self.directory).startswith('....
from mock import patch import pytest import os import shutil import tempfile class Directory: def __init__(self, directory): self.directory = directory def __getitem__(self, name): path = os.path.join(self.directory, name) assert not os.path.relpath(path, self.directory).startswith('....
Add convenience function to read tempdir files.
Add convenience function to read tempdir files.
Python
bsd-3-clause
fschulze/ploy,ployground/ploy
854709e1c2f5351c8e7af49e238fe54632f23ff5
takeyourmeds/settings/defaults/apps.py
takeyourmeds/settings/defaults/apps.py
INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'allauth', 'allauth.account', 'djcelery', 'rest_framework', 'takeyourmeds.api', 'takeyourmeds.reminder', 'takeyou...
INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.sites', 'django.contrib.staticfiles', 'allauth', 'allauth.account', 'djcelery', 'rest_framework', 'takeyourmeds.api', 'takeyour...
Return .sites to INSTALLED_APPS until we drop allauth
Return .sites to INSTALLED_APPS until we drop allauth
Python
mit
takeyourmeds/takeyourmeds-web,takeyourmeds/takeyourmeds-web,takeyourmeds/takeyourmeds-web,takeyourmeds/takeyourmeds-web
bf142af653dec7eb781faf6a45385a411bdfeee2
scripts/lib/paths.py
scripts/lib/paths.py
details_source = './source/details/' xml_source = './source/raw_xml/' course_dest = './source/courses/' info_path = './courses/info.json' term_dest = './courses/terms/' mappings_path = './related-data/generated/' handmade_path = './related-data/handmade/' def find_details_subdir(clbid): str_clbid ...
details_source = './source/details/' xml_source = './source/raw_xml/' course_dest = './source/courses/' info_path = './build/info.json' term_dest = './build/terms/' mappings_path = './related-data/generated/' handmade_path = './related-data/handmade/' def find_details_subdir(clbid): str_clbid = st...
Put the build stuff back in /build
Put the build stuff back in /build
Python
mit
StoDevX/course-data-tools,StoDevX/course-data-tools
a1cf7353917bbcee569cb8b6bb0d6277ee41face
dependency_injector/__init__.py
dependency_injector/__init__.py
"""Dependency injector.""" from .catalog import AbstractCatalog from .catalog import override from .providers import Provider from .providers import Delegate from .providers import Factory from .providers import Singleton from .providers import ExternalDependency from .providers import Class from .providers import Ob...
"""Dependency injector.""" from .catalog import AbstractCatalog from .catalog import override from .providers import Provider from .providers import Delegate from .providers import Factory from .providers import Singleton from .providers import ExternalDependency from .providers import Class from .providers import Ob...
Add Injection into __all__ list of top level package
Add Injection into __all__ list of top level package
Python
bsd-3-clause
rmk135/dependency_injector,ets-labs/dependency_injector,rmk135/objects,ets-labs/python-dependency-injector
43ee2b8cfde4d0276cfd561063554705462001cf
openmm/run_test.py
openmm/run_test.py
#!/usr/bin/env python from simtk import openmm # Check major version number assert openmm.Platform.getOpenMMVersion() == '7.1', "openmm.Platform.getOpenMMVersion() = %s" % openmm.Platform.getOpenMMVersion() # Check git hash assert openmm.version.git_revision == '1e5b258c0df6ab8b4350fd2c3cbf6c6f7795847c', "openmm.ver...
#!/usr/bin/env python from simtk import openmm # Check major version number assert openmm.Platform.getOpenMMVersion() == '7.1', "openmm.Platform.getOpenMMVersion() = %s" % openmm.Platform.getOpenMMVersion() # Check git hash assert openmm.version.git_revision == '9567ddb304c48d336e82927adf2761e8780e9270', "openmm.ver...
Update git hash in test
Update git hash in test
Python
mit
peastman/conda-recipes,cwehmeyer/conda-recipes,jchodera/conda-recipes,peastman/conda-recipes,swails/conda-recipes,cwehmeyer/conda-recipes,cwehmeyer/conda-recipes,swails/conda-recipes,swails/conda-recipes,jchodera/conda-recipes,omnia-md/conda-recipes,jchodera/conda-recipes,omnia-md/conda-recipes,cwehmeyer/conda-recipes,...
37f08dab37601b7621743467d6b78fb0306b5054
lcapy/config.py
lcapy/config.py
# SymPy symbols to exclude exclude = ('C', 'O', 'S', 'N', 'E', 'E1', 'Q') # Aliases for SymPy symbols aliases = {'delta': 'DiracDelta', 'step': 'Heaviside', 'u': 'Heaviside', 'j': 'I'} # String replacements when printing as LaTeX. For example, SymPy uses # theta for Heaviside's step. latex_string_map = {...
# SymPy symbols to exclude exclude = ('C', 'O', 'S', 'N', 'E', 'E1', 'Q', 'beta', 'gamma', 'zeta') # Aliases for SymPy symbols aliases = {'delta': 'DiracDelta', 'step': 'Heaviside', 'u': 'Heaviside', 'j': 'I'} # String replacements when printing as LaTeX. For example, SymPy uses # theta for Heaviside's s...
Exclude beta, gamma, zeta functions
Exclude beta, gamma, zeta functions
Python
lgpl-2.1
mph-/lcapy