commit stringlengths 40 40 | subject stringlengths 4 1.73k | repos stringlengths 5 127k | old_file stringlengths 2 751 | new_file stringlengths 2 751 | new_contents stringlengths 1 8.98k | old_contents stringlengths 0 6.59k | license stringclasses 13
values | lang stringclasses 23
values |
|---|---|---|---|---|---|---|---|---|
1cb55e4feec981efdf629b01ed7508f825b6c2c0 | add comment TODO | z0rkuM/stockbros,z0rkuM/stockbros,z0rkuM/stockbros,z0rkuM/stockbros | StockIndicators/StockIndicators.py | StockIndicators/StockIndicators.py | #!flask/bin/python
from flask import Blueprint, jsonify
api_si = Blueprint('api_si', __name__)
#TODO: probar a meter token de seguridad a ver se funciona
@api_si.route("/stock_indicators")
def get_stock_indicators():
return jsonify(stock_indicators=[
{"username": "alice", "user_id": 1},
{"username... | #!flask/bin/python
from flask import Blueprint, jsonify
api_si = Blueprint('api_si', __name__)
@api_si.route("/stock_indicators")
def get_stock_indicators():
return jsonify(stock_indicators=[
{"username": "alice", "user_id": 1},
{"username": "bob", "user_id": 2}
])
| mit | Python |
13a5e797bf3c268ae42dda79c75959ca0602096f | Update unit tests script. | ciechowoj/master,ciechowoj/master,ciechowoj/master | unit_test.py | unit_test.py | #!/usr/bin/python3
import glob
import re
import subprocess
import os
import os.path
def atoi(text):
return int(text) if text.isdigit() else text
def natural_keys(text):
'''
alist.sort(key=natural_keys) sorts in human order
http://nedbatchelder.com/blog/200712/human_sorting.html
(See Toothy's impl... | #!/usr/bin/python3
import glob
import re
import subprocess
import os
import os.path
def atoi(text):
return int(text) if text.isdigit() else text
def natural_keys(text):
'''
alist.sort(key=natural_keys) sorts in human order
http://nedbatchelder.com/blog/200712/human_sorting.html
(See Toothy's impl... | mit | Python |
7ccb8d443fe3dda236d05ff4ed13e067a6893872 | create a changeset against local before changing local; we'll use this later | sassoftware/conary,sassoftware/conary,sassoftware/conary,sassoftware/conary,sassoftware/conary | updatecmd.py | updatecmd.py | #
# Copyright (c) 2004 Specifix, Inc.
# All rights reserved
#
import changeset
import os
import sys
import util
import versions
def doUpdate(repos, db, cfg, pkg, versionStr = None):
cs = None
if not os.path.exists(cfg.root):
util.mkdirChain(cfg.root)
if os.path.exists(pkg):
# there is ... | #
# Copyright (c) 2004 Specifix, Inc.
# All rights reserved
#
import changeset
import os
import sys
import util
import versions
def doUpdate(repos, db, cfg, pkg, versionStr = None):
cs = None
if not os.path.exists(cfg.root):
util.mkdirChain(cfg.root)
if os.path.exists(pkg):
# there is ... | apache-2.0 | Python |
6aea68d6c1de498583c42839a3a31ef25f51e17e | Complete alg_breadth_first_search.py | bowen0701/algorithms_data_structures | alg_breadth_first_search.py | alg_breadth_first_search.py | from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
import numpy as np
def bfs(graph_adj_d, start_vertex):
visit_queue = []
visit_queue.insert(0, start_vertex)
distance_d = {v: np.inf for v in graph_adj_d.keys()}
distance_d[start_vertex] = 0
... | from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
def bfs():
pass
def main():
# Small word ladder graph.
graph_adj_d = {
'fool': {'cool', 'pool', 'foil', 'foul'},
'foul': {'fool', 'foil'},
'foil': {'fool', 'foul', 'fail'}... | bsd-2-clause | Python |
649029d2ad04eb5afd618b40ccd62993d69e389f | Complete alg_percentile_selection.py | bowen0701/algorithms_data_structures | alg_percentile_selection.py | alg_percentile_selection.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import random
def select_percentile(ls, k):
"""Kth percentile selection algorithm.
Just select the kth element, without caring about
the relative ordering of the rest of them.
The algorithm per... | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
def select_percentile(a_list, k):
"""Select list's kth percentile.
Just select the kth element, without caring about
the relative ordering of the rest of them.
"""
pass
def main():
pass
if __na... | bsd-2-clause | Python |
7de37a5ba8164b757a6a8ed64f80ee379ff7a3ad | fix some bugs | XiaowenLin/cs598rk | scripts/extract_computer_and_accessories.py | scripts/extract_computer_and_accessories.py | from scripts.rake import *
import json
# get review texts aggregated by asin id
def get_rdd(base, input, num_part):
base_dir = os.path.join(base)
input_path = os.path.join(input)
file_name = os.path.join(base_dir, input_path)
# load data
... | from scripts.rake import *
import json
# get review texts aggregated by asin id
def get_rdd(base, input, num_part):
base_dir = os.path.join(base)
input_path = os.path.join(input)
file_name = os.path.join(base_dir, input_path)
# load data
... | mit | Python |
ab533cf55e87571e757f545d5eaad6f8f62cc31f | Make worker resource plot responsive | mrocklin/distributed,broxtronix/distributed,dask/distributed,mrocklin/distributed,amosonn/distributed,broxtronix/distributed,mrocklin/distributed,amosonn/distributed,blaze/distributed,dask/distributed,dask/distributed,blaze/distributed,broxtronix/distributed,dask/distributed,amosonn/distributed | distributed/diagnostics/worker_monitor.py | distributed/diagnostics/worker_monitor.py | from __future__ import print_function, division, absolute_import
from collections import defaultdict
from itertools import chain
from toolz import pluck
from ..utils import ignoring
with ignoring(ImportError):
from bokeh.models import ColumnDataSource, DataRange1d, Range1d
from bokeh.palettes import Spectra... | from __future__ import print_function, division, absolute_import
from collections import defaultdict
from itertools import chain
from toolz import pluck
from ..utils import ignoring
with ignoring(ImportError):
from bokeh.models import ColumnDataSource, DataRange1d, Range1d
from bokeh.palettes import Spectra... | bsd-3-clause | Python |
6e65bf0ce5334e2242fee0c36886cfda29a1f4a4 | Make build.py baseimage pulling optional | avatao/challenge-engine,avatao-content/challenge-toolbox,avatao/challenge-engine,avatao/challenge-engine,avatao-content/challenge-toolbox,avatao/challenge-engine,avatao-content/challenge-toolbox,avatao/challenge-engine,avatao-content/challenge-toolbox,avatao-content/challenge-toolbox,avatao/challenge-engine,avatao-cont... | build.py | build.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# -*- mode: python; -*-
import logging
import subprocess
import sys
import time
import os
from common import get_sys_args, yield_dockerfiles
from common import run_cmd, init_logger
def build_image(repo_path, repo_name):
for dockerfile, image in yield_dockerfiles(rep... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# -*- mode: python; -*-
import logging
import subprocess
import sys
import time
from common import get_sys_args, yield_dockerfiles
from common import run_cmd, init_logger
def build_image(repo_path, repo_name):
for dockerfile, image in yield_dockerfiles(repo_path, re... | apache-2.0 | Python |
b68669f07aba05a4e96f900df71d6179382cd6f1 | bump version | arnehilmann/yum-repos,arnehilmann/yumrepos,arnehilmann/yumrepos,arnehilmann/yum-repos | build.py | build.py | from pybuilder.core import use_plugin, init, Author, task
use_plugin("python.core")
use_plugin("python.unittest")
use_plugin("python.integrationtest")
use_plugin("python.install_dependencies")
use_plugin("python.flake8")
use_plugin("python.coverage")
use_plugin("python.distutils")
use_plugin('copy_resources')
use_plug... | from pybuilder.core import use_plugin, init, Author, task
use_plugin("python.core")
use_plugin("python.unittest")
use_plugin("python.integrationtest")
use_plugin("python.install_dependencies")
use_plugin("python.flake8")
use_plugin("python.coverage")
use_plugin("python.distutils")
use_plugin('copy_resources')
use_plug... | apache-2.0 | Python |
83b12f568ba8843ac6bff4c5179d8200d88505b0 | Fix an issue where the .VERSION file output from build.py had multiple commit hashes | jenkinsci/coverity-plugin,jenkinsci/coverity-plugin,jenkinsci/coverity-plugin,jenkinsci/coverity-plugin | build.py | build.py | #/*******************************************************************************
# * Copyright (c) 2016 Synopsys, Inc
# * All rights reserved. This program and the accompanying materials
# * are made available under the terms of the Eclipse Public License v1.0
# * which accompanies this distribution, and is available ... | #/*******************************************************************************
# * Copyright (c) 2016 Synopsys, Inc
# * All rights reserved. This program and the accompanying materials
# * are made available under the terms of the Eclipse Public License v1.0
# * which accompanies this distribution, and is available ... | epl-1.0 | Python |
fe55a3e5ba9f4a368d39fcc3316a471df547d714 | Bump version to 0.8.1+dev | python-hyper/h11 | h11/_version.py | h11/_version.py | # This file must be kept very simple, because it is consumed from several
# places -- it is imported by h11/__init__.py, execfile'd by setup.py, etc.
# We use a simple scheme:
# 1.0.0 -> 1.0.0+dev -> 1.1.0 -> 1.1.0+dev
# where the +dev versions are never released into the wild, they're just what
# we stick into the ... | # This file must be kept very simple, because it is consumed from several
# places -- it is imported by h11/__init__.py, execfile'd by setup.py, etc.
# We use a simple scheme:
# 1.0.0 -> 1.0.0+dev -> 1.1.0 -> 1.1.0+dev
# where the +dev versions are never released into the wild, they're just what
# we stick into the ... | mit | Python |
0e3e9028598c8ebe49c3aec98fbfb584e8f5223b | Check both category_links and resource_link | uw-it-aca/myuw,uw-it-aca/myuw,uw-it-aca/myuw,uw-it-aca/myuw | myuw/management/commands/check_reslinks.py | myuw/management/commands/check_reslinks.py | """
Test all the links in the CSV for non-200 status codes (after redirects).
"""
import logging
import sys
import urllib3
from django.core.mail import send_mail
from django.core.management.base import BaseCommand, CommandError
from myuw.dao.category_links import Res_Links, Resource_Links
from myuw.util.settings impor... | """
Test all the links in the CSV for non-200 status codes (after redirects).
"""
import logging
import sys
import urllib3
from django.core.mail import send_mail
from django.core.management.base import BaseCommand, CommandError
from myuw.dao.category_links import Res_Links
from myuw.util.settings import get_cronjob_re... | apache-2.0 | Python |
d242870d99634edc4b077b045fe5489039a3c821 | add shebang to targetselection script | desihub/desitarget,desihub/desitarget | bin/targetselection.py | bin/targetselection.py | #!/usr/bin/env python
import numpy
from desitarget.io import read_tractor, write_targets
from desitarget.cuts import LRG, ELG, BGS, QSO
from desitarget import targetmask
from argparse import ArgumentParser
ap = ArgumentParser()
ap.add_argument("--type", choices=["tractor"], default="tractor", help="Assume a type fo... | import numpy
from desitarget.io import read_tractor, write_targets
from desitarget.cuts import LRG, ELG, BGS, QSO
from desitarget import targetmask
from argparse import ArgumentParser
ap = ArgumentParser()
ap.add_argument("--type", choices=["tractor"], default="tractor", help="Assume a type for src files")
ap.add_ar... | bsd-3-clause | Python |
22a76a55c373af8f64717b10542b7230e63e9583 | update person caches to 1hr | uw-it-aca/canvas-sis-provisioner,uw-it-aca/canvas-sis-provisioner,uw-it-aca/canvas-sis-provisioner,uw-it-aca/canvas-sis-provisioner | sis_provisioner/cache.py | sis_provisioner/cache.py | from restclients.cache_implementation import TimedCache
import re
class RestClientsCache(TimedCache):
""" A custom cache implementation for Canvas """
url_policies = {}
url_policies["sws"] = (
(re.compile(r"^/student/v5/term/"), 60 * 60 * 10),
(re.compile(r"^/student/v5/course/"), 60 * 5)... | from restclients.cache_implementation import TimedCache
import re
class RestClientsCache(TimedCache):
""" A custom cache implementation for Canvas """
url_policies = {}
url_policies["sws"] = (
(re.compile(r"^/student/v5/term/"), 60 * 60 * 10),
(re.compile(r"^/student/v5/course/"), 60 * 5)... | apache-2.0 | Python |
909b14f4d4b82c72e8f3987c1ef82cc075520cb1 | add @ | h4llow3En/IAmTalkingToYouBot | botpi.py | botpi.py | import re
re_pi = re.compile(r'(?:^|\s)(((P|p)i)|(π)|(3(\.|,)14\d*))').search
message = "@{name}, eigentlich is π ja 3.1415926535897932384626433832795028841971693\
9937510582097494... aber rechne lieber mit 3, das ist wesentlich einfacher!"
def check_pi(bot_stuff):
match = re_pi(bot_stuff['message'])
print(... | import re
re_pi = re.compile(r'(?:^|\s)(((P|p)i)|(π)|(3(\.|,)14\d*))').search
message = "{name}, eigentlich is π ja 3.1415926535897932384626433832795028841971693\
9937510582097494... aber rechne lieber mit 3, das ist wesentlich einfacher!"
def check_pi(bot_stuff):
match = re_pi(bot_stuff['message'])
print(m... | mit | Python |
d43fecb6f645dabf1740cd42aaf25191353a1b77 | add curriculum to cache policy | uw-it-aca/canvas-sis-provisioner,uw-it-aca/canvas-sis-provisioner,uw-it-aca/canvas-sis-provisioner,uw-it-aca/canvas-sis-provisioner | sis_provisioner/cache.py | sis_provisioner/cache.py | from django.conf import settings
from memcached_clients import RestclientPymemcacheClient
from uw_kws import ENCRYPTION_KEY_URL, ENCRYPTION_CURRENT_KEY_URL
import re
ONE_MINUTE = 60
ONE_HOUR = 60 * 60
ONE_DAY = 60 * 60 * 24
ONE_WEEK = 60 * 60 * 24 * 7
ONE_MONTH = 60 * 60 * 24 * 30
NONPERSONAL_NETID_EXCEPTION_GROUP = g... | from django.conf import settings
from memcached_clients import RestclientPymemcacheClient
from uw_kws import ENCRYPTION_KEY_URL, ENCRYPTION_CURRENT_KEY_URL
import re
ONE_MINUTE = 60
ONE_HOUR = 60 * 60
ONE_DAY = 60 * 60 * 24
ONE_WEEK = 60 * 60 * 24 * 7
ONE_MONTH = 60 * 60 * 24 * 30
NONPERSONAL_NETID_EXCEPTION_GROUP = g... | apache-2.0 | Python |
9bb76df67c436d091d85d75c6968ede89d9194b7 | add testing framework | niilohlin/objective-tools,niilohlin/objective-tools | statistics/test.py | statistics/test.py | import unittest
from numberOfPublicMethods import *
class Tests(unittest.TestCase):
@staticmethod
def listOfOCClasses():
return [
ObjectiveCClass(publicMethods=4, className="TestClass4"),
ObjectiveCClass(publicMethods=5, className="TestClass5"),
Objectiv... | from numberOfPublicMethods import *
def headersIsClass():
return headers()[0] == "class.h"
def propertiesIs4():
return parseFile("class.h") == ObjectiveCClass(publicMethods=4, className="TestClass")
if __name__ == "__main__":
print(headersIsClass())
print(propertiesIs4())
print(calculateAveragePu... | mit | Python |
b689cadb696ce07372588b368a6d3709f636ca8a | Edit descriptions | nerevu/prometheus-api,nerevu/prometheus-api,nerevu/prometheus-api | manage.py | manage.py | from os.path import abspath
from flask import current_app as app
from app import create_app, db
# from app.model import init_db, populate_db()
from flask.ext.script import Manager
manager = Manager(create_app)
manager.add_option('-m', '--cfgmode', dest='config_mode', default='Development')
manager.add_option('-f', '-... | from os.path import abspath
from flask import current_app as app
from app import create_app, db
# from app.model import init_db, populate_db()
from flask.ext.script import Manager
manager = Manager(create_app)
manager.add_option('-m', '--cfgmode', dest='config_mode', default='Development')
manager.add_option('-f', '-... | mit | Python |
15a37d1e86d9217eec218aadbe53d633335460ae | Fix block name. | alexsilva/django-xadmin,alexsilva/django-xadmin,alexsilva/django-xadmin,alexsilva/django-xadmin | xadmin/templatetags/xadmin_tags.py | xadmin/templatetags/xadmin_tags.py | from django import template
from django.template import Library
from django.utils import six
from django.utils.safestring import mark_safe
from xadmin.util import static, vendor as util_vendor
register = Library()
@register.simple_tag(takes_context=True)
def view_block(context, block_name, *args, **kwargs):
if '... | from django import template
from django.template import Library
from django.utils import six
from django.utils.safestring import mark_safe
from xadmin.util import static, vendor as util_vendor
register = Library()
@register.simple_tag(takes_context=True)
def view_block(context, block_name, *args, **kwargs):
if '... | bsd-3-clause | Python |
1eb025811e5cc7df5b0185d34f053379d52b26ab | Remove create_admin command | renalreg/radar,renalreg/radar,renalreg/radar,renalreg/radar | manage.py | manage.py | from flask_script import Manager
from radar.app import create_app
from radar.lib.database import db
from radar.lib import fixtures
app = create_app('settings.py')
manager = Manager(app)
@manager.command
def create_tables():
db.drop_all()
db.create_all()
@manager.command
def drop_tables():
db.drop_all... | from flask_script import Manager
from radar.app import create_app
from radar.lib.database import db
from radar.models.users import User
from radar.lib import fixtures
app = create_app('settings.py')
manager = Manager(app)
@manager.command
def create_tables():
db.drop_all()
db.create_all()
@manager.comman... | agpl-3.0 | Python |
74959fa6f12d5be7491f1fbf3d99b1678486c311 | bump version for release | srikalyan/slacksocket,bcicen/slacksocket,vektorlab/slacksocket,graywizardx/slacksocket,hfwang/slacksocket | slacksocket/version.py | slacksocket/version.py | version = '0.5.0'
| version = '0.4.4'
| mit | Python |
e3e3b59654133bd33c708343976825bb0c68d6f1 | use development config as default | cenkalti/pypi-notifier,cenkalti/pypi-notifier | manage.py | manage.py | #!/usr/bin/env python
import os
import errno
import logging
from flask import current_app
from flask.ext.script import Manager
from pypi_notifier import create_app, db, models, cache
logging.basicConfig(level=logging.DEBUG)
manager = Manager(create_app)
try:
# Must be a class name from config.py
config =... | #!/usr/bin/env python
import os
import errno
import logging
from flask import current_app
from flask.ext.script import Manager
from pypi_notifier import create_app, db, models, cache
logging.basicConfig(level=logging.DEBUG)
manager = Manager(create_app)
# Must be a class name from config.py
config = os.environ['P... | mit | Python |
26fc40f3ca729147e838af4d98362484bed776df | Simplify main function in problem58.py | mjwestcott/projecteuler,mjwestcott/projecteuler,mjwestcott/projecteuler | euler_python/problem58.py | euler_python/problem58.py | """
problem58.py
Starting with 1 and spiralling anticlockwise in the following way, a square
spiral with side length 7 is formed.
37 36 35 34 33 32 31
38 17 16 15 14 13 30
39 18 5 4 3 12 29
40 19 6 1 2 11 28
41 20 7 8 9 10 27
42 21 22 23 24 25 26
43 44 45 46 47 48 49
It is intere... | """
problem58.py
Starting with 1 and spiralling anticlockwise in the following way, a square
spiral with side length 7 is formed.
37 36 35 34 33 32 31
38 17 16 15 14 13 30
39 18 5 4 3 12 29
40 19 6 1 2 11 28
41 20 7 8 9 10 27
42 21 22 23 24 25 26
43 44 45 46 47 48 49
It is intere... | mit | Python |
68e32ab4c763461ffbbea6a3ed698f66fdb48d4d | Use only user_id and course_id during the kNN computation: speedup is 5x Previously most time was consumed in db queries and suprisingly in __hash__ methods (seem that hashing a django model takes longer that hashing a int) | UrLab/beta402,UrLab/DocHub,UrLab/DocHub,UrLab/beta402,UrLab/beta402,UrLab/DocHub,UrLab/DocHub | catalog/predictions.py | catalog/predictions.py | from catalog.models import Course
import collections
from django.contrib.contenttypes.models import ContentType
from actstream.models import Follow
def distance(v1, v2):
absolute_difference = [abs(c1 - c2) for c1, c2 in zip(v1, v2)]
distance = sum(absolute_difference)
return distance
def get_users_follo... | from users.models import User
from catalog.models import Course
import collections
from django.contrib.contenttypes.models import ContentType
from actstream.models import Follow
def distance(v1, v2):
absolute_difference = [abs(c1 - c2) for c1, c2 in zip(v1, v2)]
distance = sum(absolute_difference)
return ... | agpl-3.0 | Python |
797c4405aa2b75da9b7bdbb7e0e26f8bae3308b6 | handle BadPickleGet on restore | felipecruz/coopy,felipecruz/coopy | coopy/restore.py | coopy/restore.py | import logging
import fileutils
from snapshot import SnapshotManager
from foundation import RestoreClock
from cPickle import Unpickler, BadPickleGet
logger = logging.getLogger("coopy")
LOG_PREFIX = '[RESTORE] '
def restore(system, basedir):
#save current clock
current_clock = system._clock
#restore from... | import logging
import fileutils
from snapshot import SnapshotManager
from foundation import RestoreClock
from cPickle import Unpickler
logger = logging.getLogger("coopy")
LOG_PREFIX = '[RESTORE] '
def restore(system, basedir):
#save current clock
current_clock = system._clock
#restore from snapshot... | bsd-3-clause | Python |
4c9b8a55d26df7421decdc05236499f61583ab38 | fix smart folder content getter | ecreall/nova-ideo,ecreall/nova-ideo,ecreall/nova-ideo,ecreall/nova-ideo,ecreall/nova-ideo | novaideo/utilities/smart_folder_utility.py | novaideo/utilities/smart_folder_utility.py | # -*- coding: utf8 -*-
# Copyright (c) 2014 by Ecreall under licence AGPL terms
# avalaible on http://www.gnu.org/licenses/agpl.html
# licence: AGPL
# author: Amen Souissi
from hypatia.util import ResultSet
from substanced.util import get_oid, find_objectmap
from novaideo.views.filter import (
find_entities)
fro... | # -*- coding: utf8 -*-
# Copyright (c) 2014 by Ecreall under licence AGPL terms
# avalaible on http://www.gnu.org/licenses/agpl.html
# licence: AGPL
# author: Amen Souissi
from substanced.util import get_oid
from dace.util import get_obj
from novaideo.views.filter import (
find_entities)
from novaideo.utilities.... | agpl-3.0 | Python |
70db54eba970f8e8f6c42587675f1525002ea12f | Update wrong status code stated in docstring | timothycrosley/hug,timothycrosley/hug,timothycrosley/hug | hug/redirect.py | hug/redirect.py | """hug/redirect.py
Implements convience redirect methods that raise a redirection exception when called
Copyright (C) 2016 Timothy Edmund Crosley
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the Software... | """hug/redirect.py
Implements convience redirect methods that raise a redirection exception when called
Copyright (C) 2016 Timothy Edmund Crosley
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the Software... | mit | Python |
1db7ef99aef8691600d74b23a751c6a753e2a5da | Update : Enhancing timer function and exec times storage | oleiade/Hurdles | hurdles/base.py | hurdles/base.py | # -*- coding:utf-8 -*-
# Copyright (c) 2012 theo crevon
#
# See the file LICENSE for copying permission.
import time
from collections import namedtuple
from functools import wraps
from inspect import getmembers, ismethod
ExecTimeCollection = namedtuple('ExecTimeCollection', ['times', 'scale'])
def extra_setup(se... | # -*- coding:utf-8 -*-
# Copyright (c) 2012 theo crevon
#
# See the file LICENSE for copying permission.
import time
from functools import wraps
from inspect import getmembers, ismethod
def time_it(func, *args, **kwargs):
"""
Decorator whichs times a function execution.
"""
start = time.time()
... | mit | Python |
aebe8c0b586b408b55b13d8ddd3a974c194455a6 | Update categorical_braninhoo_example.py | schevalier/Whetlab-Python-Client,schevalier/Whetlab-Python-Client | examples/categorical_braninhoo_example.py | examples/categorical_braninhoo_example.py | # In this example we will optimize the 'Braninhoo' optimization benchmark with a small twist to
# demonstrate how to set up a categorical variable. There is also a constraint on the function.
import whetlab
import numpy as np
# Define parameters to optimize
parameters = { 'X' : {'type':'float','min':0,'max':15,'size... | import whetlab
import numpy as np
# Define parameters to optimize
parameters = { 'X' : {'type':'float','min':0,'max':15,'size':1},
'Y' : {'type':'float','min':-5,'max':10,'size':1},
'Z' : {'type': 'enum', 'options': ['bad','Good!','OK']}}
#access_token = ''
name = 'Categorical Braninhoo'
... | bsd-3-clause | Python |
c3c986e08dadf3ecdd4f94eca6abf36c22a1c209 | Update DB/ Deploy | alexbotello/BastionBot | models.py | models.py | from sqlalchemy import create_engine, Column, String
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
def db_connect():
"""
Performs database connection
Returns sqlalchemy engine instance
"""
return create_engine('postgres://fcvxvbdsuotypy:a3b010cca1f... | from sqlalchemy import create_engine, Column, String
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
def db_connect():
"""
Performs database connection
Returns sqlalchemy engine instance
"""
return create_engine('postgres://fbcmeskynsvati:aURfAdENt6-... | mit | Python |
fac8a172a16da011bab9e41afc52f24f833687fc | Simplify the date calculation | bbolli/twitter-monday | monday.py | monday.py | #! /usr/bin/env python
"""Run this during the week to write last week's short-form entry"""
from __future__ import print_function
from datetime import datetime, timedelta
import errno
import operator
import os
import sys
def sunday_after(dt, offset=1):
"""offset == 3 means 3rd Sunday from now, -2 means two Sun... | #! /usr/bin/env python
"""Run this during the week to write last week's short-form entry"""
from __future__ import print_function
from datetime import datetime, timedelta
import errno
import operator
import os
import sys
def sunday_after(dt, offset=1):
"""offset == 3 means 3rd Sunday from now, -2 means two Sun... | mit | Python |
d4ef5e2cb956d7ac7b28497cdc849f7c2bc85712 | add radio by default | dinoperovic/django-shop-catalog,dinoperovic/django-shop-catalog | shop_catalog/settings.py | shop_catalog/settings.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
SLUG_FIELD_HELP_TEXT = _(
'Can only contain the letters a-z, A-Z, digits, minus and underscores, '
'and can\'t start with a digit.')
PRODUCT_CHANGE_FORM_TE... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
SLUG_FIELD_HELP_TEXT = _(
'Can only contain the letters a-z, A-Z, digits, minus and underscores, '
'and can\'t start with a digit.')
PRODUCT_CHANGE_FORM_TE... | bsd-3-clause | Python |
0b635ffb77acb362c34769a72dfd6d0063c32f38 | Handle range of success codes | chargehound/chargehound-python | chargehound/api_requestor.py | chargehound/api_requestor.py | from __future__ import unicode_literals
import chargehound
import requests
from chargehound.error import create_chargehound_error
from chargehound.version import VERSION
class APIRequestor(object):
def parse_response(self, response):
payload = response.json()
if response.status_code < 400:
... | from __future__ import unicode_literals
import chargehound
import requests
from chargehound.error import create_chargehound_error
from chargehound.version import VERSION
class APIRequestor(object):
def parse_response(self, response):
payload = response.json()
if response.status_code == 200:
... | mit | Python |
41537854b93137b9455c194645778d05e94ec33c | Fix error when deleting directories. | Sable/mclab-ide,Sable/mclab-ide,Sable/mclab-ide,Sable/mclab-ide,Sable/mclab-ide,Sable/mclab-ide | ide/projects.py | ide/projects.py | import errno
import os
import shutil
WORKSPACE_DIR = os.path.expanduser('~/mclab-ide-projects')
def get_all_projects():
mkdir_p(WORKSPACE_DIR)
return map(Project, os.listdir(WORKSPACE_DIR))
def mkdir_p(path):
try:
os.makedirs(path)
except OSError as e:
if e.errno != errno.EEXIST or ... | import errno
import os
import shutil
WORKSPACE_DIR = os.path.expanduser('~/mclab-ide-projects')
def get_all_projects():
mkdir_p(WORKSPACE_DIR)
return map(Project, os.listdir(WORKSPACE_DIR))
def mkdir_p(path):
try:
os.makedirs(path)
except OSError as e:
if e.errno != errno.EEXIST or ... | apache-2.0 | Python |
30089f005f62e84367aa6affd5acbd4920f8086a | fix installation on Arch | rr-/dotfiles,rr-/dotfiles,rr-/dotfiles | cfg/search/__main__.py | cfg/search/__main__.py | from pathlib import Path
from libdotfiles import HOME_DIR, PKG_DIR, packages, util
FZF_DIR = HOME_DIR / ".fzf"
if util.distro_name() == "arch":
packages.try_install("fzf") # super opener
packages.try_install("the_silver_searcher") # fzf dependency
packages.try_install("ripgrep") # super grep (shell)
... | from pathlib import Path
from libdotfiles import HOME_DIR, PKG_DIR, packages, util
FZF_DIR = HOME_DIR / ".fzf"
if util.distro_name() == "arch":
packages.try_install("fzf") # super opener
packages.try_install(
"silver-searcher-git"
) # super grep (vim-fzf dependency)
packages.try_install("ri... | mit | Python |
a2efba8d942171249b3ed2f28497d84f81cbbb06 | Add lint test and format generated code (#4114) | googleapis/google-cloud-java,googleapis/google-cloud-java,googleapis/google-cloud-java | java-language/google-cloud-language/synth.py | java-language/google-cloud-language/synth.py | # Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, s... | # Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, s... | apache-2.0 | Python |
743b2593113a19382e60c3968897c871d98e20a8 | add alternate shorthand arguments, simplify shell execution | willfarrell/alfred-debugger,willfarrell/alfred-debugger | alfred.py | alfred.py | #!/usr/bin/python
import argparse, subprocess, re, sys
VERSION="0.1";
parser = argparse.ArgumentParser(description='''Execute a test''',)
parser.add_argument('-f', '--file', type=str, required=True, help="Filename of php file (ex 'script.php')")
parser.add_argument('-q', '--query', type=str, required=True, help="Valu... | #!/usr/bin/python
import argparse, subprocess, re, sys
VERSION="0.1";
parser = argparse.ArgumentParser(description='''Execute a test''',)
parser.add_argument('--file', type=str, required=True, help="Filename of php file (ex 'script.php')")
parser.add_argument('--query', type=str, required=True, help="Value to repla... | mit | Python |
9c720cf806364e4eaf40da24691bc224a9288485 | Clean combo script | ustwo/mastermind,ustwo/mastermind | combo.py | combo.py | from libmproxy import filt
import proxyswitch as pswitch
def enable():
settings = ('127.0.0.1', '8080')
pswitch.enable(*settings)
def disable():
pswitch.disable()
def start(context, argv):
context.log(">>> start")
enable()
context.filter = filt.parse("~d ustwo.com")
def request(context, flo... | from flask import Flask
from libmproxy import filt
import proxyswitch as pswitch
# app = Flask('proxapp')
# @app.route('/')
# def hello_world():
# return 'Hello World!'
# @app.route('/foo')
# def foo():
# return 'foo'
def enable():
settings = ('127.0.0.1', '8080')
pswitch.enable(*settings)
def disa... | mit | Python |
250e166f02642e9d3c41f3854b6e9e12c560daba | update script for battle | haozai309/hello_python | battle.py | battle.py |
# Welcome to Battleship
# http://www.codecademy.com/courses/python-beginner-en-4XuFm/0/1?curriculum_id=4f89dab3d788890003000096
""" In this project you will build a simplified, one-player version of the
classic board game Battleship! In this version of the game, there will be a
single ship hidden in a random locati... |
# Welcome to Battleship
# http://www.codecademy.com/courses/python-beginner-en-4XuFm/0/1?curriculum_id=4f89dab3d788890003000096
""" In this project you will build a simplified, one-player version of the
classic board game Battleship! In this version of the game, there will be a
single ship hidden in a random locati... | apache-2.0 | Python |
3566e9a4d59779c1fca5cfa3031d03a1bb5a72ba | remove process executor option | sciyoshi/CheesePrism,whitmo/CheesePrism,sciyoshi/CheesePrism,whitmo/CheesePrism,whitmo/CheesePrism | cheeseprism/wsgiapp.py | cheeseprism/wsgiapp.py | from .jenv import EnvFactory
from cheeseprism.auth import BasicAuthenticationPolicy
from cheeseprism.resources import App
from pyramid.config import Configurator
from pyramid.session import UnencryptedCookieSessionFactoryConfig
from pyramid.settings import asbool
import futures
import logging
import os
logger = logg... | from .jenv import EnvFactory
from cheeseprism.auth import BasicAuthenticationPolicy
from cheeseprism.resources import App
from functools import partial
from pyramid.config import Configurator
from pyramid.session import UnencryptedCookieSessionFactoryConfig
from pyramid.settings import asbool
import futures
import logg... | bsd-2-clause | Python |
8eb938086a77a11cb2df8c83f872b9daa519f858 | fix pyhon3 compat issues in rename. | cournape/Bento,cournape/Bento,cournape/Bento,cournape/Bento | bento/compat/rename.py | bento/compat/rename.py | import os.path
import os
import random
import errno
def rename(src, dst):
"Atomic rename on windows."
# This is taken from mercurial
try:
os.rename(src, dst)
except OSError:
# If dst exists, rename will fail on windows, and we cannot
# unlink an opened file. Instead, the destina... | import os.path
import os
import random
def rename(src, dst):
"Atomic rename on windows."
# This is taken from mercurial
try:
os.rename(src, dst)
except OSError, err:
# If dst exists, rename will fail on windows, and we cannot
# unlink an opened file. Instead, the destination is ... | bsd-3-clause | Python |
b61a45c13ffa82356f896f0914d2f28dabea7a7f | Include credentials for heat calling self | redhat-openstack/heat,pshchelo/heat,gonzolino/heat,cwolferh/heat-scratch,cryptickp/heat,takeshineshiro/heat,openstack/heat,steveb/heat,cryptickp/heat,dims/heat,rh-s/heat,maestro-hybrid-cloud/heat,jasondunsmore/heat,rdo-management/heat,pratikmallya/heat,jasondunsmore/heat,cwolferh/heat-scratch,takeshineshiro/heat,noiron... | heat/engine/clients/os/heat_plugin.py | heat/engine/clients/os/heat_plugin.py | #
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# ... | #
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# ... | apache-2.0 | Python |
05c210f1a5f83ebbea2319f48ba58eb054b32ce2 | fix indent | komsit37/sublime-q,komsit37/sublime-q,komsit37/sublime-q | q_out_panel.py | q_out_panel.py | from . import chain
#show_q_output
class QOutPanelCommand(chain.ChainCommand):
def do(self, edit, input=None):
panel = self.view.window().get_output_panel("q")
syntax_file = "Packages/q KDB/syntax/q_output.tmLanguage"
try:
panel.set_syntax_file(syntax_file)
except Exception:
print("Unable to load synta... | from . import chain
#show_q_output
class QOutPanelCommand(chain.ChainCommand):
def do(self, edit, input=None):
panel = self.view.window().get_output_panel("q")
syntax_file = "Packages/q KDB/syntax/q_output.tmLanguage"
try:
sublime.load_binary_resource(syntax_file)
except Exception:... | mit | Python |
62398ce1fde0402a9c4b77ff018e47716ba1fdd3 | allow restricting the refresh_useractions command by user | tndatacommons/tndata_backend,tndatacommons/tndata_backend,izzyalonso/tndata_backend,tndatacommons/tndata_backend,izzyalonso/tndata_backend,izzyalonso/tndata_backend,izzyalonso/tndata_backend,tndatacommons/tndata_backend | tndata_backend/goals/management/commands/refresh_useractions.py | tndata_backend/goals/management/commands/refresh_useractions.py | import logging
from django.contrib.auth import get_user_model
from django.core.management.base import BaseCommand, CommandError
from django.db.models import Q
from goals.models import CustomAction, UserAction
logger = logging.getLogger("loggly_logs")
class Command(BaseCommand):
help = 'Updates the next_trigger... | import logging
from django.core.management.base import BaseCommand
from goals.models import CustomAction, UserAction
logger = logging.getLogger("loggly_logs")
class Command(BaseCommand):
help = 'Updates the next_trigger_date field for stale UserActions and CustomActions.'
def handle(self, *args, **options)... | mit | Python |
5b6587cbe03ff79a29a400fb1f9b29d889b4edc5 | Make executable | Rosuav/shed,Rosuav/shed,Rosuav/shed,Rosuav/shed,Rosuav/shed | appid.py | appid.py | #!/usr/bin/env python3
# Find a Steam appid given its name
import json
import os.path
import sys
from fuzzywuzzy import process, fuzz # ImportError? pip install 'fuzzywuzzy[speedup]'
CACHE_FILE = os.path.abspath(__file__ + "/../appid.json")
try:
with open(CACHE_FILE) as f:
appids = json.load(f)
except FileNotFound... | # Find a Steam appid given its name
import json
import os.path
import sys
from fuzzywuzzy import process, fuzz # ImportError? pip install 'fuzzywuzzy[speedup]'
CACHE_FILE = os.path.abspath(__file__ + "/../appid.json")
try:
with open(CACHE_FILE) as f:
appids = json.load(f)
except FileNotFoundError:
import requests... | mit | Python |
d2d090383d93e89bd8ce07d533715612cf472152 | Support lists of nodes in astpp | Suor/flaws | astpp.py | astpp.py | """
A pretty-printing dump function for the ast module. The code was copied from
the ast.dump function and modified slightly to pretty-print.
Alex Leone (acleone ~AT~ gmail.com), 2010-01-30
"""
from ast import *
def dump(node, annotate_fields=True, include_attributes=False, indent=' '):
"""
Return a format... | """
A pretty-printing dump function for the ast module. The code was copied from
the ast.dump function and modified slightly to pretty-print.
Alex Leone (acleone ~AT~ gmail.com), 2010-01-30
"""
from ast import *
def dump(node, annotate_fields=True, include_attributes=False, indent=' '):
"""
Return a format... | bsd-2-clause | Python |
a1996022dd288b5a986cd07b2694f5af514296e4 | Delete unnecessary annotation in examples/bucket_policy.py | aliyun/aliyun-oss-python-sdk | examples/bucket_policy.py | examples/bucket_policy.py |
import os
import oss2
import json
# 以下代码展示了bucket_policy相关API的用法,
# 具体policy书写规则参考官网文档说明
# 首先初始化AccessKeyId、AccessKeySecret、Endpoint等信息。
# 通过环境变量获取,或者把诸如“<你的AccessKeyId>”替换成真实的AccessKeyId等。
#
# 以杭州区域为例,Endpoint可以是:
# http://oss-cn-hangzhou.aliyuncs.com
# https://oss-cn-hangzhou.aliyuncs.com
access_key_id = os.ge... |
import os
import oss2
import json
# 以下代码展示了bucket_policy相关API的用法,
# 具体policy书写规则参考官网文档说明
# 首先初始化AccessKeyId、AccessKeySecret、Endpoint等信息。
# 通过环境变量获取,或者把诸如“<你的AccessKeyId>”替换成真实的AccessKeyId等。
#
# 以杭州区域为例,Endpoint可以是:
# http://oss-cn-hangzhou.aliyuncs.com
# https://oss-cn-hangzhou.aliyuncs.com
# 分别以HTTP、HTTPS协议访问。
... | mit | Python |
3665b8859f72ec416682857ab22f7e29fc30f0df | Add field on cached alignments to store more information | cmunk/protwis,protwis/protwis,fosfataza/protwis,cmunk/protwis,fosfataza/protwis,protwis/protwis,protwis/protwis,fosfataza/protwis,cmunk/protwis,cmunk/protwis,fosfataza/protwis | alignment/models.py | alignment/models.py | from django.db import models
# Create your models here.
class AlignmentConsensus(models.Model):
slug = models.SlugField(max_length=100, unique=True)
alignment = models.BinaryField()
gn_consensus = models.BinaryField(blank=True) # Store conservation calculation for each GN | from django.db import models
# Create your models here.
class AlignmentConsensus(models.Model):
slug = models.SlugField(max_length=100, unique=True)
alignment = models.BinaryField() | apache-2.0 | Python |
61e9b3db58c124cf41ede9fc9a3ad9c01e5bff81 | add select related query for group social links | tomaszroszko/django-social-links | sociallinks/templatetags/sociallink_tags.py | sociallinks/templatetags/sociallink_tags.py | # -*- coding: utf-8 -*-
from django import template
from django.contrib.contenttypes.models import ContentType
from sociallinks.models import SocialLink, SocialLinkGroup
register = template.Library()
@register.assignment_tag
def obj_social_links(obj):
"""return list of social links for obj. Obj is instance of a... | # -*- coding: utf-8 -*-
from django import template
from django.contrib.contenttypes.models import ContentType
from sociallinks.models import SocialLink, SocialLinkGroup
register = template.Library()
@register.assignment_tag
def obj_social_links(obj):
"""return list of social links for obj. Obj is instance of a... | bsd-3-clause | Python |
709a7139b4f3acaace53e79c7ca1adafd8f24027 | Use tempfile to save modifications | malramsay64/MD-Molecules-Hoomd,malramsay64/MD-Molecules-Hoomd | basic.py | basic.py | """Run a basic simulation"""
import os
import tempfile
import hoomd
from hoomd import md
import molecule
import numpy as np
import pandas
import TimeDep
import gsd.hoomd
from StepSize import generate_steps
def run_npt(snapshot, temp, steps, **kwargs):
"""Initialise a hoomd simulation"""
with hoomd.context.i... | """Run a basic simulation"""
import os
import hoomd
import molecule
import numpy as np
import pandas
import TimeDep
from hoomd import md
import gsd.hoomd
from StepSize import generate_steps
def run_npt(snapshot, temp, steps, **kwargs):
"""Initialise a hoomd simulation"""
with hoomd.context.initialize(kwargs... | mit | Python |
5d8e6e47964d80f380db27acd120136a43e80550 | Fix tool description in argparse help | sot/aimpoint_mon,sot/aimpoint_mon | aimpoint_mon/make_web_page.py | aimpoint_mon/make_web_page.py | #!/usr/bin/env python
import os
import argparse
import json
from pathlib import Path
from jinja2 import Template
import pyyaks.logger
def get_opt():
parser = argparse.ArgumentParser(description='Make aimpoint monitor web page')
parser.add_argument("--data-root",
default=".",
... | #!/usr/bin/env python
import os
import argparse
import json
from pathlib import Path
from jinja2 import Template
import pyyaks.logger
def get_opt():
parser = argparse.ArgumentParser(description='Get aimpoint drift data '
'from aspect solution files')
parser.add_argument(... | bsd-2-clause | Python |
b31217a1a0ed68e0dfee2fdea87aad569c73573f | update batch timing | codeforamerica/westsac-urban-land-locator,codeforamerica/westsac-urban-land-locator,codeforamerica/westsac-urban-land-locator,codeforamerica/westsac-urban-land-locator | clock.py | clock.py | from apscheduler.schedulers.blocking import BlockingScheduler
from farmsList.imports import every_night_at_1am
from rq import Queue
from worker import conn
import logging
logging.basicConfig()
q = Queue(connection=conn)
sched = BlockingScheduler()
@sched.scheduled_job('cron', hour=21, minute=14)# hour=1)
def schedule... | from apscheduler.schedulers.blocking import BlockingScheduler
from farmsList.imports import every_night_at_1am
from rq import Queue
from worker import conn
import logging
logging.basicConfig()
q = Queue(connection=conn)
sched = BlockingScheduler()
@sched.scheduled_job('cron', hour=21, minute=11)# hour=1)
def schedule... | bsd-3-clause | Python |
a34994bb6ae23f04627ab384fa2c2905997925a9 | Revert rendering. | NejcZupec/tictactoe,NejcZupec/tictactoe,NejcZupec/tictactoe | web/views.py | web/views.py | import json
from django.http import Http404, HttpResponse
from django.views.generic import TemplateView
from django.shortcuts import redirect, render
from .models import Game, Player
from .utils import create_new_game, generate_unique_anonymous_username, calculate_stats
class HomeView(TemplateView):
template_na... | import json
from django.http import Http404, HttpResponse
from django.views.generic import TemplateView
from django.shortcuts import redirect, render
from django.template.loader import render_to_string
from .models import Game, Player
from .utils import create_new_game, generate_unique_anonymous_username, calculate_s... | apache-2.0 | Python |
f958ef0179f72adb4b8c7243fc30395de1c31d6b | add authentication now required by https://issues.apache.org/jira | remibergsma/cloudstack-docs-rn,apache/cloudstack-docs-rn,remibergsma/cloudstack-docs-rn,apache/cloudstack-docs-rn,apache/cloudstack-docs-rn,remibergsma/cloudstack-docs-rn | utils/jira.py | utils/jira.py | #!/usr/bin/env python
# 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
# "L... | #!/usr/bin/env python
# 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
# "L... | apache-2.0 | Python |
b631482e00e59224cb32682f6a9d221748368158 | Remove os package | prontotools/zendesk-tickets-machine,prontotools/zendesk-tickets-machine,prontotools/zendesk-tickets-machine,prontotools/zendesk-tickets-machine | fabfile.py | fabfile.py | from datetime import datetime
from fabric.api import (
cd,
env,
local,
put,
run,
sudo,
task
)
PRODUCTION_IP = '54.154.235.243'
PROJECT_DIRECTORY = '/home/ubuntu/ztm/'
BACKUP_DIRECTORY = '/home/ubuntu/backup/'
COMPOSE_FILE = 'compose-production.yml'
@task
def production():
env.run = ... | from datetime import datetime
import os
from fabric.api import (
cd,
env,
local,
put,
run,
sudo,
task
)
PRODUCTION_IP = '54.154.235.243'
PROJECT_DIRECTORY = '/home/ubuntu/ztm/'
BACKUP_DIRECTORY = '/home/ubuntu/backup/'
COMPOSE_FILE = 'compose-production.yml'
@task
def production():
... | mit | Python |
ea2b67cd016492f1869f50f899360c3151977e79 | Fix docstring term | uccser/cs-unplugged,uccser/cs-unplugged,uccser/cs-unplugged,uccser/cs-unplugged | csunplugged/topics/management/commands/_GlossaryTermsLoader.py | csunplugged/topics/management/commands/_GlossaryTermsLoader.py | """Custom loader for loading glossary terms."""
import os.path
from django.db import transaction
from utils.BaseLoader import BaseLoader
from topics.models import GlossaryTerm
class GlossaryTermsLoader(BaseLoader):
"""Custom loader for loading glossary terms."""
def __init__(self, glossary_folder_path, glo... | """Custom loader for loading glossary terms."""
import os.path
from django.db import transaction
from utils.BaseLoader import BaseLoader
from topics.models import GlossaryTerm
class GlossaryTermsLoader(BaseLoader):
"""Custom loader for loading glossary terms."""
def __init__(self, glossary_folder_path, glo... | mit | Python |
179308a7061b2e0b1bb10d5c7757a611196608db | change fabfile | fabiansinz/pipecontrol,fabiansinz/pipecontrol,fabiansinz/pipecontrol | fabfile.py | fabfile.py | from distutils.util import strtobool
from fabric.api import local, abort, run, sudo
from fabric.context_managers import cd, settings, hide, shell_env
from fabric.contrib.console import confirm
from getpass import getpass
from fabric.utils import puts
from fabric.state import env
env.control_dir = 'pipecontrol'
def w... | from distutils.util import strtobool
from fabric.api import local, abort, run, sudo
from fabric.context_managers import cd, settings, hide, shell_env
from fabric.contrib.console import confirm
from getpass import getpass
from fabric.utils import puts
from fabric.state import env
env.control_dir = 'pipecontrol'
def w... | mit | Python |
3d2b08a971ded9fa4bf3a3d7c69c15e589b6adab | add v0.8.1 (#21798) | LLNL/spack,LLNL/spack,LLNL/spack,LLNL/spack,LLNL/spack | var/spack/repos/builtin/packages/py-parso/package.py | var/spack/repos/builtin/packages/py-parso/package.py | # Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class PyParso(PythonPackage):
"""Parso is a Python parser that supports error recovery and round... | # Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class PyParso(PythonPackage):
"""Parso is a Python parser that supports error recovery and round... | lgpl-2.1 | Python |
deb2bb30b6f584a7a899d7c161605efadee468cf | add optional /geo suffix to /pollingstations | DemocracyClub/UK-Polling-Stations,chris48s/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations,chris48s/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations,chris48s/UK-Polling-Stations | polling_stations/api/pollingstations.py | polling_stations/api/pollingstations.py | from rest_framework.decorators import list_route
from rest_framework.mixins import ListModelMixin
from rest_framework.viewsets import GenericViewSet
from rest_framework_gis.serializers import GeoFeatureModelSerializer
from pollingstations.models import PollingStation
class PollingStationSerializer(GeoFeatureModelSeri... | from rest_framework.mixins import ListModelMixin
from rest_framework.viewsets import GenericViewSet
from rest_framework_gis.serializers import GeoFeatureModelSerializer
from pollingstations.models import PollingStation
class PollingStationSerializer(GeoFeatureModelSerializer):
class Meta:
model = Polling... | bsd-3-clause | Python |
f961c1031285c5852e46f880668b963d27245ace | Rename _table to table | davidrobles/mlnd-capstone-code | examples/tictactoe-qlearning.py | examples/tictactoe-qlearning.py | import random
from capstone.environment import Environment
from capstone.game import TicTacToe
from capstone.mdp import GameMDP
from capstone.player import AlphaBeta, RandPlayer
from capstone.util import ZobristHashing
class TabularQLearning(object):
def __init__(self, env, policy=RandPlayer(), alpha=0.1, gamma=... | import random
from capstone.environment import Environment
from capstone.game import TicTacToe
from capstone.mdp import GameMDP
from capstone.player import AlphaBeta, RandPlayer
from capstone.util import ZobristHashing
class TabularQLearning(object):
def __init__(self, env, policy=RandPlayer(), alpha=0.1, gamma=... | mit | Python |
dc40793ad27704c83dbbd2e923bf0cbcd7cb00ed | Handle both event instanciation from object and from serialized events | polyaxon/polyaxon,polyaxon/polyaxon,polyaxon/polyaxon | polyaxon/event_manager/event_service.py | polyaxon/event_manager/event_service.py | from libs.services import Service
class EventService(Service):
__all__ = ('record', 'setup')
event_manager = None
def can_handle(self, event_type):
return isinstance(event_type, str) and self.event_manager.knows(event_type)
def get_event(self, event_type, event_data=None, instance=None, **k... | from libs.services import Service
class EventService(Service):
__all__ = ('record', 'setup')
event_manager = None
def can_handle(self, event_type):
return isinstance(event_type, str) and self.event_manager.knows(event_type)
def get_event(self, event_type, instance, **kwargs):
return... | apache-2.0 | Python |
19e5608b2d8d16e2c80390927658e8f322dd10e6 | Add new encodings. (#3292) | tswast/google-cloud-python,calpeyser/google-cloud-python,tartavull/google-cloud-python,dhermes/google-cloud-python,dhermes/google-cloud-python,calpeyser/google-cloud-python,googleapis/google-cloud-python,GoogleCloudPlatform/gcloud-python,dhermes/gcloud-python,jonparrott/google-cloud-python,googleapis/google-cloud-pytho... | speech/google/cloud/speech/encoding.py | speech/google/cloud/speech/encoding.py | # Copyright 2016 Google 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 writing, ... | # Copyright 2016 Google 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 writing, ... | apache-2.0 | Python |
b2f2fcd9322837ea096a28ae584c8d236232c5a5 | remove jython2.5 compat code | bozzzzo/qpid-proton,astitcher/qpid-proton,bozzzzo/qpid-proton,gemmellr/qpid-proton-j,Karm/qpid-proton,ssorj/qpid-proton,gemmellr/qpid-proton,alanconway/qpid-proton,prestona/qpid-proton,kgiusti/qpid-proton,apache/qpid-proton,prestona/qpid-proton,prestona/qpid-proton,Karm/qpid-proton,ChugR/qpid-proton,ChugR/qpid-proton,a... | proton-j/src/main/resources/cproton.py | proton-j/src/main/resources/cproton.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... | #
# 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... | apache-2.0 | Python |
27354d34f4f9117c0a3167f4af7d3e3c83d51c59 | bump version # from 0.6.0 -> 0.7.0 | simonsdave/cloudfeaster,simonsdave/cloudfeaster,simonsdave/cloudfeaster | cloudfeaster/__init__.py | cloudfeaster/__init__.py | __version__ = '0.7.0'
| __version__ = '0.6.0'
| mit | Python |
38d298a81aa8fcd85b16b3879c1665085e5450be | Add description where student should add logic | introprogramming/exercises,introprogramming/exercises,introprogramming/exercises | exercises/control_flow/prime.py | exercises/control_flow/prime.py | #!/bin/python
def is_prime(integer):
"""Determines weather integer is prime, returns a boolean value"""
# add logic here to make sure number < 2 are not prime
for i in range(2, integer):
if integer % i == 0:
return False
return True
print("Should be False (0): %r" % is_prime(0... | #!/bin/python
def is_prime(integer):
"""Determines weather integer is prime, returns a boolean value"""
for i in range(2, integer):
if integer % i == 0:
return False
return True
print("Should be False (0): %r" % is_prime(0))
print("Should be False (1): %r" % is_prime(1))
print("Sho... | mit | Python |
d5b326d8d368d2ac75c6e078572df8c28704c163 | Use the app string version of foreign keying. It prevents a circular import. | AeroNotix/django-timetracker,AeroNotix/django-timetracker,AeroNotix/django-timetracker | vcs/models.py | vcs/models.py | from django.db import models
class Activity(models.Model):
group = models.CharField(max_length=4)
grouptype = models.TextField()
groupdetail = models.TextField()
details = models.TextField()
disabled = models.BooleanField()
time = models.DecimalField(decimal_places=2, max_digits=10)
unique_... | from django.db import models
class Activity(models.Model):
group = models.CharField(max_length=4)
grouptype = models.TextField()
groupdetail = models.TextField()
details = models.TextField()
disabled = models.BooleanField()
time = models.DecimalField(decimal_places=2, max_digits=10)
unique_... | bsd-3-clause | Python |
3b001eac78349e1e3f6235b14def0fa6752f6fba | add more dedup special cases | total-impact/software,total-impact/software,total-impact/software,total-impact/depsy,Impactstory/depsy,total-impact/depsy,Impactstory/depsy,total-impact/depsy,Impactstory/depsy,total-impact/software,total-impact/depsy,Impactstory/depsy | models/dedup_special_cases.py | models/dedup_special_cases.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
data = [
{
"main_profile": ("Hadley Wickham", "cran:reshape"),
"people_to_merge": [
("Hadley Wickham", "cran:GGally")
]
},
{
"main_profile": ("Barry Rowlingson", "cran:geonames"),
"people_to_merge": [
("B. S. Rowlingson", "cran:lgcp"),
("Barry Rowlingson"... | #!/usr/bin/python
# -*- coding: utf-8 -*-
data = [
{
"main_profile": ("Hadley Wickham", "cran:reshape"),
"people_to_merge": [
("Hadley Wickham", "cran:GGally")
]
},
{
"main_profile": ("Barry Rowlingson", "cran:geonames"),
"people_to_merge": [
("B. S. Rowlingson", "cran:lgcp"),
("Barry Rowlingson"... | mit | Python |
1163bc40a15eb2461c6ead570db8a8d211f1f5be | Sort room table by room name by default | agdsn/pycroft,lukasjuhrich/pycroft,agdsn/pycroft,lukasjuhrich/pycroft,agdsn/pycroft,lukasjuhrich/pycroft,agdsn/pycroft,lukasjuhrich/pycroft,agdsn/pycroft | web/blueprints/facilities/tables.py | web/blueprints/facilities/tables.py | from web.blueprints.helpers.table import BootstrapTable, Column
class SiteTable(BootstrapTable):
def __init__(self, *a, **kw):
super().__init__(*a, columns=[
Column('site', 'Site', formatter='table.linkFormatter'),
Column('buildings', 'Buildings', formatter='table.multiBtnFormatter... | from web.blueprints.helpers.table import BootstrapTable, Column
class SiteTable(BootstrapTable):
def __init__(self, *a, **kw):
super().__init__(*a, columns=[
Column('site', 'Site', formatter='table.linkFormatter'),
Column('buildings', 'Buildings', formatter='table.multiBtnFormatter... | apache-2.0 | Python |
1abbca6200fa3da0a3216b18b1385f3575edb49a | Move import of Django's get_version into django-registration's get_version, to avoid dependency-order problems. | myimages/django-registration,Troyhy/django-registration,futurecolors/django-registration,hacklabr/django-registration,akvo/django-registration,sandipagr/django-registration,futurecolors/django-registration,liberation/django-registration,euanlau/django-registration,tdruez/django-registration,Troyhy/django-registration,g... | registration/__init__.py | registration/__init__.py | VERSION = (0, 9, 0, 'beta', 1)
def get_version():
from django.utils.version import get_version as django_get_version
return django_get_version(VERSION) # pragma: no cover
| from django.utils.version import get_version as django_get_version
VERSION = (0, 9, 0, 'beta', 1)
def get_version():
return django_get_version(VERSION) # pragma: no cover
| bsd-3-clause | Python |
db5cb125fb9b0dd4d3b781d0b85250bdc7a52cba | fix error msg | efiop/dvc,dmpetrov/dataversioncontrol,dataversioncontrol/dvc,dmpetrov/dataversioncontrol,dataversioncontrol/dvc,efiop/dvc | dvc/command/add.py | dvc/command/add.py | from dvc.exceptions import DvcException
from dvc.command.common.base import CmdBase
class CmdAdd(CmdBase):
def run(self):
for target in self.args.targets:
try:
self.project.add(target)
except DvcException as ex:
self.project.logger.error('Failed to a... | from dvc.exceptions import DvcException
from dvc.command.common.base import CmdBase
class CmdAdd(CmdBase):
def run(self):
for target in self.args.targets:
try:
self.project.add(target)
except DvcException as ex:
self.project.logger.error('Failed to a... | apache-2.0 | Python |
b5d32a3b1b8e85222497c4736c0c6707003dc848 | Fix broken database IO tests. | live-clones/pybtex | pybtex/tests/database_test/__init__.py | pybtex/tests/database_test/__init__.py | # Copyright (C) 2009 Andrey Golovizin
#
# This program 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
# (at your option) any later version.
#
# This program is distribut... | # Copyright (C) 2009 Andrey Golovizin
#
# This program 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
# (at your option) any later version.
#
# This program is distribut... | mit | Python |
37d01f6088b1cf5673f66f4532dd51c73a0156f1 | Fix grammar in login error message | sehmaschine/django-rest-framework,arpheno/django-rest-framework,ajaali/django-rest-framework,adambain-vokal/django-rest-framework,buptlsl/django-rest-framework,aericson/django-rest-framework,YBJAY00000/django-rest-framework,VishvajitP/django-rest-framework,werthen/django-rest-framework,xiaotangyuan/django-rest-framewor... | rest_framework/authtoken/serializers.py | rest_framework/authtoken/serializers.py | from django.contrib.auth import authenticate
from django.utils.translation import ugettext_lazy as _
from rest_framework import serializers
class AuthTokenSerializer(serializers.Serializer):
username = serializers.CharField()
password = serializers.CharField()
def validate(self, attrs):
username... | from django.contrib.auth import authenticate
from django.utils.translation import ugettext_lazy as _
from rest_framework import serializers
class AuthTokenSerializer(serializers.Serializer):
username = serializers.CharField()
password = serializers.CharField()
def validate(self, attrs):
username... | bsd-2-clause | Python |
059090cd945f51ed0281a967e1ba9502d2dc0a40 | Fix unittest | gpetretto/pymatgen,mbkumar/pymatgen,aykol/pymatgen,dongsenfo/pymatgen,matk86/pymatgen,xhqu1981/pymatgen,nisse3000/pymatgen,tschaume/pymatgen,davidwaroquiers/pymatgen,mbkumar/pymatgen,gVallverdu/pymatgen,ndardenne/pymatgen,johnson1228/pymatgen,vorwerkc/pymatgen,davidwaroquiers/pymatgen,richardtran415/pymatgen,montoyjh/p... | pymatgen/apps/borg/tests/test_queen.py | pymatgen/apps/borg/tests/test_queen.py | # coding: utf-8
# Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License.
from __future__ import division, unicode_literals
"""
Created on Mar 18, 2012
"""
__author__ = "Shyue Ping Ong"
__copyright__ = "Copyright 2012, The Materials Project"
__version__ = "0.1"
__maintainer__ = "S... | # coding: utf-8
# Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License.
from __future__ import division, unicode_literals
"""
Created on Mar 18, 2012
"""
__author__ = "Shyue Ping Ong"
__copyright__ = "Copyright 2012, The Materials Project"
__version__ = "0.1"
__maintainer__ = "S... | mit | Python |
098219137bdf30d7ac1c321f7973e14bfc82bda4 | Add configuration for PyBullet Ant. | google-research/batch-ppo | agents/scripts/configs.py | agents/scripts/configs.py | # Copyright 2017 The TensorFlow Agents Authors.
#
# 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 ag... | # Copyright 2017 The TensorFlow Agents Authors.
#
# 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 ag... | apache-2.0 | Python |
215439b43c27271c95fc208bf683a19619c81b8d | Add 3D slic tests (gray not working yet) | almarklein/scikit-image,chriscrosscutler/scikit-image,michaelaye/scikit-image,emon10005/scikit-image,blink1073/scikit-image,almarklein/scikit-image,keflavich/scikit-image,GaZ3ll3/scikit-image,SamHames/scikit-image,paalge/scikit-image,pratapvardhan/scikit-image,juliusbierk/scikit-image,ofgulban/scikit-image,keflavich/sc... | skimage/segmentation/tests/test_slic.py | skimage/segmentation/tests/test_slic.py | import itertools as it
import numpy as np
from numpy.testing import assert_equal, assert_array_equal
from skimage.segmentation import slic
def test_color_2d():
rnd = np.random.RandomState(0)
img = np.zeros((20, 21, 3))
img[:10, :10, 0] = 1
img[10:, :10, 1] = 1
img[10:, 10:, 2] = 1
img += 0.01 ... | import numpy as np
from numpy.testing import assert_equal, assert_array_equal
from skimage.segmentation import slic
def test_color():
rnd = np.random.RandomState(0)
img = np.zeros((20, 21, 3))
img[:10, :10, 0] = 1
img[10:, :10, 1] = 1
img[10:, 10:, 2] = 1
img += 0.01 * rnd.normal(size=img.shap... | bsd-3-clause | Python |
52eb6a3d8188c5e8fbabbe4f4822d0c4ececf48b | Add option to see all available ldap attributes via ldapsearch command | Princeton-CDH/django-pucas,Princeton-CDH/django-pucas | pucas/management/commands/ldapsearch.py | pucas/management/commands/ldapsearch.py | from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
from pucas.ldap import LDAPSearch, LDAPSearchException
class Command(BaseCommand):
help = 'Look up one or more users in LDAP by netid'
def add_arguments(self, parser):
parser.add_argument('netid', narg... | from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
from pucas.ldap import LDAPSearch, LDAPSearchException
class Command(BaseCommand):
help = 'Look up one or more users in LDAP by netid'
def add_arguments(self, parser):
parser.add_argument('netid', narg... | apache-2.0 | Python |
ea3a390a88c63a566df567d245e22e505f17dcfe | Remove test_TextFile_bad_extension | jstutters/Plumbium | tests/test_artefacts.py | tests/test_artefacts.py | import pytest
from pirec import artefacts
def test_Artefact_basename():
"""basename() should strip the extension from an artefact filename."""
img = artefacts.Artefact('foo.nii.gz', '.nii.gz', exists=False)
assert img.basename == 'foo'
def test_Artefact_dirname():
"""dirname() should return the path... | import pytest
from pirec import artefacts
def test_Artefact_basename():
"""basename() should strip the extension from an artefact filename."""
img = artefacts.Artefact('foo.nii.gz', '.nii.gz', exists=False)
assert img.basename == 'foo'
def test_Artefact_dirname():
"""dirname() should return the path... | mit | Python |
cd9a51ab2fe6b99c0665b8f499363a4d557b4a4d | Modify script which split your region in smaller sample | aguijarro/DataSciencePython | DataWrangling/CaseStudy/sample_file.py | DataWrangling/CaseStudy/sample_file.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import xml.etree.ElementTree as ET # Use cElementTree or lxml if too slow
import os
OSM_FILE = "san-francisco-bay_california.osm" # Replace this with your osm file
SAMPLE_FILE = "sample_sfb.osm"
k = 20 # Parameter: take every k-th top level element
def get_element(osm... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import xml.etree.ElementTree as ET # Use cElementTree or lxml if too slow
import os
OSM_FILE = "san-francisco-bay_california.osm" # Replace this with your osm file
SAMPLE_FILE = "sample_sfb.osm"
k = 20 # Parameter: take every k-th top level element
def get_element(osm... | mit | Python |
cd79441f0c11fbc36f2f0b0098196373006718e4 | Update binstar-push.py | INGEOTEC/b4msa | continuous-integration/binstar-push.py | continuous-integration/binstar-push.py | import os
import glob
# import subprocess
# import traceback
from binstar_client.scripts import cli
def get_token():
token = None
if os.environ.get('TRAVIS_BRANCH', None) == 'master' or os.environ.get('APPVEYOR_REPO_BRANCH', None) == 'master':
token = os.environ.get('BINSTAR_TOKEN', None)
return t... | import os
import glob
# import subprocess
# import traceback
from binstar_client.scripts import cli
def get_token():
token = None
if os.environ.get('TRAVIS_BRANCH', None) == 'master' or os.environ.get('APPVEYOR_REPO_BRANCH', None) == 'master':
token = os.environ.get('BINSTAR_TOKEN', None)
return t... | apache-2.0 | Python |
b7777486ef36a20e148e3a3d81846f2b330e8622 | Enable fullpath to be used in get_filenames | jason-neal/equanimous-octo-tribble,jason-neal/equanimous-octo-tribble,jason-neal/equanimous-octo-tribble | octotribble/Get_filenames.py | octotribble/Get_filenames.py | #!/usr/bin/env python
# -*- coding: utf8 -*-
"""Get names of files that match regular expression.
Possibly better to use the glob module.
"""
import fnmatch
import os
from typing import List
# TODO: Try glob.glob
def get_filenames(path, regexp, regexp2=None, fullpath=False):
# type: (str, str, str) -> List[str... | #!/usr/bin/env python
# -*- coding: utf8 -*-
"""Get names of files that match regular expression.
Possibly better to use the glob module.
"""
import fnmatch
import os
from typing import List
# TODO: Try glob.glob
def get_filenames(path, regexp, regexp2=None):
# type: (str, str, str) -> List[str]
"""Regexp ... | mit | Python |
0f0ef471e6bb9d873c890df2f538a00bbcae9637 | print removed | akshaybabloo/gollahalli-com,akshaybabloo/gollahalli-com,akshaybabloo/gollahalli-com | viewer/templatetags/custom_tags.py | viewer/templatetags/custom_tags.py | from django import template
import markdown
import datetime
register = template.Library()
@register.filter()
def custom_date(value):
date = datetime.datetime.strptime(value, '%a, %d %b %Y %H:%M:%S %z')
return date.strftime('%d, %b %Y')
@register.filter()
def markdown_data(value):
return markdown.markdo... | from django import template
import markdown
import datetime
register = template.Library()
@register.filter()
def custom_date(value):
date = datetime.datetime.strptime(value, '%a, %d %b %Y %H:%M:%S %z')
return date.strftime('%d, %b %Y')
@register.filter()
def markdown_data(value):
return markdown.markdo... | mit | Python |
0bac442df6fec974aec8cf6d9e4147a2e75cf139 | Switch from VERSION to $VERSION in model migration. | praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go | go/vumitools/conversation/migrators.py | go/vumitools/conversation/migrators.py | from vumi.persist.model import ModelMigrator
class ConversationMigrator(ModelMigrator):
def migrate_from_unversioned(self, mdata):
# Copy stuff that hasn't changed between versions
mdata.copy_values(
'conversation_type',
'start_timestamp', 'end_timestamp', 'created_at',
... | from vumi.persist.model import ModelMigrator
class ConversationMigrator(ModelMigrator):
def migrate_from_unversioned(self, mdata):
# Copy stuff that hasn't changed between versions
mdata.copy_values(
'conversation_type',
'start_timestamp', 'end_timestamp', 'created_at',
... | bsd-3-clause | Python |
fd7348951e46763dcd06cb673a6b01f6894efe4e | Set version as 0.8.8.1 | Alignak-monitoring-contrib/alignak-webui,Alignak-monitoring-contrib/alignak-webui,Alignak-monitoring-contrib/alignak-webui | alignak_webui/__init__.py | alignak_webui/__init__.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# pylint: disable=global-statement
# Copyright (c) 2015-2017:
# Frederic Mohier, frederic.mohier@alignak.net
#
"""
Alignak - Web User Interface
"""
# Package name
__pkg_name__ = u"alignak_webui"
# Checks types for PyPI keywords
# Used for:
# - PyPI keywords
# - dir... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# pylint: disable=global-statement
# Copyright (c) 2015-2017:
# Frederic Mohier, frederic.mohier@alignak.net
#
"""
Alignak - Web User Interface
"""
# Package name
__pkg_name__ = u"alignak_webui"
# Checks types for PyPI keywords
# Used for:
# - PyPI keywords
# - dir... | agpl-3.0 | Python |
2ed5c92aabd349337579792b20613854370aa2ac | add log test | ll1l11/pymysql-test,ll1l11/pymysql-test | kfdda/views/general.py | kfdda/views/general.py | # -*- coding: utf-8 -*-
from flask import Blueprint
from flask.views import MethodView
from ..core import db, logger
from ..exceptions import NoError, FormValidationError
from ..forms.login import LoginForm
from ..models.user import User
from ..tasks import add
bp = Blueprint('general', __name__)
class IndexView(... | # -*- coding: utf-8 -*-
from flask import Blueprint
from flask.views import MethodView
from ..core import db, logger
from ..exceptions import NoError, FormValidationError
from ..forms.login import LoginForm
from ..models.user import User
from ..tasks import add
bp = Blueprint('general', __name__)
class IndexView(... | mit | Python |
83a62e80d1b7551f0ccebf4bc95bba27c6bf94bc | Add compound nouns tests | pwdyson/inflect.py,jazzband/inflect | tests/test_compounds.py | tests/test_compounds.py | import inflect
p = inflect.engine()
def test_compound_1():
assert p.singular_noun("hello-out-there") == "hello-out-there"
def test_compound_2():
assert p.singular_noun("hello out there") == "hello out there"
def test_compound_3():
assert p.singular_noun("continue-to-operate") == "continue-to-operate"... | import inflect
p = inflect.engine()
def test_compound_1():
assert p.singular_noun("hello-out-there") == "hello-out-there"
def test_compound_2():
assert p.singular_noun("hello out there") == "hello out there"
def test_compound_3():
assert p.singular_noun("continue-to-operate") == "continue-to-operate"... | mit | Python |
828e75919bd71912baf75a64010efcfcd93d07f1 | Update library magic to be recursive | baubie/SpikeDB,baubie/SpikeDB,baubie/SpikeDB,baubie/SpikeDB | library_magic.py | library_magic.py | import sys
import subprocess
import shutil
copied = []
def update_libraries(executable):
# Find all the dylib files and recursively add dependencies
print "\nChecking dependencies of " + executable
otool_cmd = ["otool", "-L",executable]
execfolder = executable.rsplit("/",1)[0]
otool_out = subprocess.check_outp... | import sys
import subprocess
import shutil
executable = sys.argv[1]
execfolder = sys.argv[1].rsplit("/",1)[0]
libdir = execfolder+"/lib"
otool_cmd = ["otool", "-L",executable]
# Run otool
otool_out = subprocess.check_output(otool_cmd).split("\n\t")
# Find all the dylib files
for l in otool_out:
s = l.split(".dylib"... | bsd-3-clause | Python |
62cd48f8a0fc83261af5c4275a38102fc983d3ff | Increase failure tolerance for the Dashboard | IATI/IATI-Website-Tests | tests/test_dashboard.py | tests/test_dashboard.py | from datetime import datetime, timedelta
from dateutil import parser as date_parser
import pytest
import pytz
from web_test_base import *
class TestIATIDashboard(WebTestBase):
requests_to_load = {
'Dashboard Homepage': {
'url': 'http://dashboard.iatistandard.org/'
}
}
def test_... | from datetime import datetime, timedelta
from dateutil import parser as date_parser
import pytest
import pytz
from web_test_base import *
class TestIATIDashboard(WebTestBase):
requests_to_load = {
'Dashboard Homepage': {
'url': 'http://dashboard.iatistandard.org/'
}
}
def test_... | mit | Python |
c076fb75d40b85b593bd569eaf7f6e13ab95cdd8 | Replace Pykka internals misuse with proxies | glogiotatidis/mopidy,SuperStarPL/mopidy,tkem/mopidy,rawdlite/mopidy,mokieyue/mopidy,jmarsik/mopidy,priestd09/mopidy,jcass77/mopidy,liamw9534/mopidy,swak/mopidy,ali/mopidy,diandiankan/mopidy,jmarsik/mopidy,dbrgn/mopidy,bencevans/mopidy,jmarsik/mopidy,pacificIT/mopidy,pacificIT/mopidy,kingosticks/mopidy,pacificIT/mopidy,... | mopidy/frontends/mpd/actor.py | mopidy/frontends/mpd/actor.py | import logging
import sys
import pykka
from mopidy import settings
from mopidy.core import CoreListener
from mopidy.frontends.mpd import session
from mopidy.utils import encoding, network, process
logger = logging.getLogger('mopidy.frontends.mpd')
class MpdFrontend(pykka.ThreadingActor, CoreListener):
"""
... | import logging
import sys
import pykka
from mopidy import settings
from mopidy.core import CoreListener
from mopidy.frontends.mpd import session
from mopidy.utils import encoding, network, process
logger = logging.getLogger('mopidy.frontends.mpd')
class MpdFrontend(pykka.ThreadingActor, CoreListener):
"""
... | apache-2.0 | Python |
c68833f3c464720b676080705d2df4f7e37c4392 | fix template render() expect Context and not dict | nickburlett/feincms,feincms/feincms,pjdelport/feincms,feincms/feincms,nickburlett/feincms,michaelkuty/feincms,hgrimelid/feincms,matthiask/feincms2-content,mjl/feincms,joshuajonah/feincms,michaelkuty/feincms,nickburlett/feincms,mjl/feincms,hgrimelid/feincms,matthiask/django-content-editor,hgrimelid/feincms,matthiask/fei... | feincms/tests/applicationcontent_urls.py | feincms/tests/applicationcontent_urls.py | """
This is a dummy module used to test the ApplicationContent
"""
from django import template
from django.conf.urls.defaults import *
from django.http import HttpResponse, HttpResponseRedirect
def module_root(request):
return 'module_root'
def args_test(request, kwarg1, kwarg2):
return HttpResponse(u'%s-%... | """
This is a dummy module used to test the ApplicationContent
"""
from django import template
from django.conf.urls.defaults import *
from django.http import HttpResponse, HttpResponseRedirect
def module_root(request):
return 'module_root'
def args_test(request, kwarg1, kwarg2):
return HttpResponse(u'%s-%... | bsd-3-clause | Python |
8b364a2b9eaff5e038d47a114746458de56b4ed5 | fix apitype casing for underscore classes | telamonian/saga-python,mehdisadeghi/saga-python,luis-rr/saga-python,luis-rr/saga-python,telamonian/saga-python,mehdisadeghi/saga-python,luis-rr/saga-python | saga/base.py | saga/base.py |
import string
import saga.utils.logger
import saga.engine.engine
class SimpleBase (object) :
""" This is a very simple API base class which just initializes
the self._logger and self._engine members, but does not perform any further
initialization, nor any adaptor binding. This base is used for API clas... |
import string
import saga.utils.logger
import saga.engine.engine
class SimpleBase (object) :
""" This is a very simple API base class which just initializes
the self._logger and self._engine members, but does not perform any further
initialization, nor any adaptor binding. This base is used for API clas... | mit | Python |
bfc248e92afdc02a8b3089d7a2a5194b7f55c2fe | add in the split out setup_ufw_rules to the api and setupnode | bretth/woven | woven/api.py | woven/api.py | #!/usr/bin/env python
"""
The full public woven api
"""
from fabric.state import env
from woven.decorators import run_once_per_node, run_once_per_version
from woven.deployment import deploy_files, mkdirs
from woven.deployment import upload_template
from woven.environment import check_settings, deployment_root, set_e... | #!/usr/bin/env python
"""
The full public woven api
"""
from fabric.state import env
from woven.decorators import run_once_per_node, run_once_per_version
from woven.deployment import deploy_files, mkdirs
from woven.deployment import upload_template
from woven.environment import check_settings, deployment_root, set_e... | bsd-3-clause | Python |
dbb153b4681a1fa73f93855e86d3657e4fff9bfb | remove self | SiLab-Bonn/pyBAR | tests/test_interface.py | tests/test_interface.py | ''' Script to check the readout system interface (software + FPGA firmware).
A global register test is performed with pyBAR and a simulation of the FPGA + FE-I4.
'''
import unittest
import shutil
import mock
from Queue import Empty
import subprocess
import time
import os
from pybar.run_manager import RunManager
from p... | ''' Script to check the readout system interface (software + FPGA firmware).
A global register test is performed with pyBAR and a simulation of the FPGA + FE-I4.
'''
import unittest
import shutil
import mock
from Queue import Empty
import subprocess
import time
import os
from pybar.run_manager import RunManager
from p... | bsd-3-clause | Python |
2c67dd081895d00ffb33e29d8750b3f80121dfe5 | Change import | suchow/judicious,suchow/judicious,suchow/judicious | tests/test_judicious.py | tests/test_judicious.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Tests for `judicious` package."""
import pytest
import judicious
@pytest.fixture
def response():
"""Sample pytest fixture.
See more at: http://doc.pytest.org/en/latest/fixture.html
"""
# import requests
# return requests.get('https://github.com... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Tests for `judicious` package."""
import pytest
from judicious import judicious
@pytest.fixture
def response():
"""Sample pytest fixture.
See more at: http://doc.pytest.org/en/latest/fixture.html
"""
# import requests
# return requests.get('htt... | mit | Python |
9a278ac9ea0c124cfd108f276bc5d74da6c5c50c | Update notebook test | GPflow/GPflow | tests/test_notebooks.py | tests/test_notebooks.py | # Copyright 2017 the GPflow authors.
#
# 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 writi... | # Copyright 2017 the GPflow authors.
#
# 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 writi... | apache-2.0 | Python |
be412947c0fe30dd659298cd7641b5a701310f7d | add auth option | dmahugh/gitdata | gitdata.py | gitdata.py | """GitHub query CLI.
cli() --------------> Handle command-line arguments.
"""
import os
import click
from click.testing import CliRunner
#------------------------------------------------------------------------------
CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help'])
@click.group(context_settings=CONTEXT_SE... | """GitHub query CLI.
cli() --------------> Handle command-line arguments.
"""
import os
import click
from click.testing import CliRunner
#------------------------------------------------------------------------------
@click.group()
@click.version_option(version='1.0', prog_name='Photerino')
def cli():
"""\b
... | mit | Python |
049d734486627224b87cba72c575450515060c55 | fix split | tlevine/vlermv | vlermv/_s3.py | vlermv/_s3.py | import tempfile
import boto
from ._abstract import AbstractVlermv
def split(x):
return tuple(x.split('/'))
class S3Vlermv(AbstractVlermv):
def __init__(self, bucketname, *args, connect_s3 = boto.connect_s3, **kwargs):
super(S3Vlermv, self).__init__(**kwargs)
self.bucket = connect_s3().creat... | import tempfile
import boto
from ._abstract import AbstractVlermv
def split(x):
return x.split('/')
class S3Vlermv(AbstractVlermv):
def __init__(self, bucketname, *args, connect_s3 = boto.connect_s3, **kwargs):
super(S3Vlermv, self).__init__(**kwargs)
self.bucket = connect_s3().create_bucke... | agpl-3.0 | Python |
394473b6d8fb9898a19bb7e3bd2141a59572adec | 更新 modules users/apps.py, 修正 PEP8 警告 | yrchen/CommonRepo,yrchen/CommonRepo,yrchen/CommonRepo,yrchen/CommonRepo | commonrepo/users/apps.py | commonrepo/users/apps.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from django.apps import AppConfig
from actstream import registry
class UsersAppConfig(AppConfig):
name = 'commonrepo.users'
def ready(self):
registry.register(self.get_model('User'))
import commonrepo.users.sig... | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from django.apps import AppConfig
from actstream import registry
class UsersAppConfig(AppConfig):
name = 'commonrepo.users'
def ready(self):
registry.register(self.get_model('User'))
import commonrepo.users.sign... | apache-2.0 | Python |
dfa39db42cc5ce2c29da2ec0c388865ec7f41030 | Add allow field to form | trbs/django-oauth-toolkit,DeskConnect/django-oauth-toolkit,jensadne/django-oauth-toolkit,vmalavolta/django-oauth-toolkit,JensTimmerman/django-oauth-toolkit,JensTimmerman/django-oauth-toolkit,Gr1N/django-oauth-toolkit,andrefsp/django-oauth-toolkit,jensadne/django-oauth-toolkit,drgarcia1986/django-oauth-toolkit,bleib1dj/... | oauth2_provider/forms.py | oauth2_provider/forms.py | from django import forms
class AllowForm(forms.Form):
allow = forms.BooleanField(required=False)
redirect_uri = forms.URLField(widget=forms.HiddenInput())
scopes = forms.CharField(required=False, widget=forms.HiddenInput())
client_id = forms.CharField(widget=forms.HiddenInput())
state = forms.Char... | from django import forms
class AllowForm(forms.Form):
redirect_uri = forms.URLField(widget=forms.HiddenInput())
scopes = forms.CharField(required=False, widget=forms.HiddenInput())
client_id = forms.CharField(widget=forms.HiddenInput())
state = forms.CharField(required=False, widget=forms.HiddenInput(... | bsd-2-clause | Python |
b0ff934a2e20916f9e777874b795c9d0942a48e4 | use app.cfg from its proper place | CottageLabs/OpenArticleGauge,CottageLabs/OpenArticleGauge,CottageLabs/OpenArticleGauge | openarticlegauge/core.py | openarticlegauge/core.py | import os, requests, json, redis
from flask import Flask
from openarticlegauge import config, licenses
from flask.ext.login import LoginManager, current_user
login_manager = LoginManager()
def create_app():
app = Flask(__name__)
configure_app(app)
if app.config['INITIALISE_INDEX']: initialise_index(app)
... | import os, requests, json, redis
from flask import Flask
from openarticlegauge import config, licenses
from flask.ext.login import LoginManager, current_user
login_manager = LoginManager()
def create_app():
app = Flask(__name__)
configure_app(app)
if app.config['INITIALISE_INDEX']: initialise_index(app)
... | bsd-3-clause | Python |
da1dbddaa47e087b19dbeb1b256b337a3e77ed73 | Fix os not defined | amolenaar/gaphor,amolenaar/gaphor | gaphor/services/tests/test_properties.py | gaphor/services/tests/test_properties.py | import os
import tempfile
from unittest import TestCase
from gaphor.services.properties import FileBackend, Properties
class MockEventManager(list):
def handle(self, event):
self.append(event)
class TestProperties(TestCase):
def setUp(self):
self.tmpdir = tempfile.mkdtemp()
backend ... | import tempfile
from unittest import TestCase
from gaphor.services.properties import FileBackend, Properties
class MockEventManager(list):
def handle(self, event):
self.append(event)
class TestProperties(TestCase):
def setUp(self):
self.tmpdir = tempfile.mkdtemp()
backend = FileBack... | lgpl-2.1 | Python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.