commit stringlengths 40 40 | old_file stringlengths 5 117 | new_file stringlengths 5 117 | old_contents stringlengths 0 1.93k | new_contents stringlengths 19 3.3k | subject stringlengths 17 320 | message stringlengths 18 3.28k | lang stringclasses 1
value | license stringclasses 13
values | repos stringlengths 7 42.4k | completion stringlengths 19 3.3k | prompt stringlengths 21 3.65k |
|---|---|---|---|---|---|---|---|---|---|---|---|
c170765132d6f24b08a4e40274df589813cebf85 | neutron/cmd/__init__.py | neutron/cmd/__init__.py | # 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 by applicable law or agreed to in... | # 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 by applicable law or agreed to in... | Fix logging error for Guru Meditation Report | Fix logging error for Guru Meditation Report
Currently, invoking any of the commands under neutron/cmd will trigger a
"No handlers could be found" error for Guru Meditation Report. This is
interupting the notify.sh script that is called by dibbler-client during the
IPv6 Prefix Delegation workflow.
This patch adds a l... | Python | apache-2.0 | mahak/neutron,klmitch/neutron,openstack/neutron,openstack/neutron,huntxu/neutron,openstack/neutron,noironetworks/neutron,wolverineav/neutron,mahak/neutron,wolverineav/neutron,bigswitch/neutron,cloudbase/neutron,dims/neutron,MaximNevrov/neutron,klmitch/neutron,eayunstack/neutron,sebrandon1/neutron,noironetworks/neutron,... | # 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 by applicable law or agreed to in... | Fix logging error for Guru Meditation Report
Currently, invoking any of the commands under neutron/cmd will trigger a
"No handlers could be found" error for Guru Meditation Report. This is
interupting the notify.sh script that is called by dibbler-client during the
IPv6 Prefix Delegation workflow.
This patch adds a l... |
e121493b7bab8f4cdd8485248a9acd7babb643c8 | setup.py | setup.py | # -*- coding: utf-8 -*-
#
# setup.py
# colorific
#
"""
Package information for colorific.
"""
import sys
# check for the supported Python version
version = tuple(sys.version_info[:2])
if version != (2, 7):
sys.stderr.write('colorific requires Python 2.7 (you have %d.%d)\n' %\
version)
sys.stder... | # -*- coding: utf-8 -*-
#
# setup.py
# colorific
#
"""
Package information for colorific.
"""
import sys
# check for the supported Python version
version = tuple(sys.version_info[:2])
if version != (2, 7):
sys.stderr.write('colorific requires Python 2.7 (you have %d.%d)\n' %
version)
sys.stderr... | Use the pillow master branch directly. | Use the pillow master branch directly.
| Python | isc | 99designs/colorific | # -*- coding: utf-8 -*-
#
# setup.py
# colorific
#
"""
Package information for colorific.
"""
import sys
# check for the supported Python version
version = tuple(sys.version_info[:2])
if version != (2, 7):
sys.stderr.write('colorific requires Python 2.7 (you have %d.%d)\n' %
version)
sys.stderr... | Use the pillow master branch directly.
# -*- coding: utf-8 -*-
#
# setup.py
# colorific
#
"""
Package information for colorific.
"""
import sys
# check for the supported Python version
version = tuple(sys.version_info[:2])
if version != (2, 7):
sys.stderr.write('colorific requires Python 2.7 (you have %d.%d)\... |
725ada91ff4b15aa97784a21e6cebd02fa2dd55c | split_dataset.py | split_dataset.py | import os
import numpy as np
data_dir = "data/dataset/"
jpg_filenames = list(filter(lambda x: x[-3:] == "jpg", os.listdir(data_dir)))
# Randomly select the test dataset
test_percentage = 0.1
n_test = round(len(jpg_filenames) * test_percentage)
if n_test == 0: n_test = 1
# Randomly select the images for testing
test... | Add script to split the dataset | Add script to split the dataset
| Python | mit | SetaSouto/license-plate-detection | import os
import numpy as np
data_dir = "data/dataset/"
jpg_filenames = list(filter(lambda x: x[-3:] == "jpg", os.listdir(data_dir)))
# Randomly select the test dataset
test_percentage = 0.1
n_test = round(len(jpg_filenames) * test_percentage)
if n_test == 0: n_test = 1
# Randomly select the images for testing
test... | Add script to split the dataset
| |
c552bfd620682d76afe17f6a70f901500e090b10 | Day1/PrimeTestCases.py | Day1/PrimeTestCases.py | #prime numbers function test cases
import unittest
from prime import prime_numbers
class PrimeTest(unittest.TestCase):
def test_returns_prime_numbers(self):
self.assertListEqual(prime_numbers(6), [2,3,5], msg="Range of 0-6 should return [2,3,5] as the prime numbers")
def test_input_is_a_number(self):
... | Add test cases for prime numbers generator | Add test cases for prime numbers generator
| Python | mit | JoshuaOndieki/joshua-ondieki-bootcamp-19 | #prime numbers function test cases
import unittest
from prime import prime_numbers
class PrimeTest(unittest.TestCase):
def test_returns_prime_numbers(self):
self.assertListEqual(prime_numbers(6), [2,3,5], msg="Range of 0-6 should return [2,3,5] as the prime numbers")
def test_input_is_a_number(self):
... | Add test cases for prime numbers generator
| |
1fa57ad194735cc7f6b4170d2c296d9c8b3ce4c3 | website_analytics_piwik/__openerp__.py | website_analytics_piwik/__openerp__.py | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# This module copyright (C) 2015 Therp BV <http://therp.nl>.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of th... | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# This module copyright (C) 2015 Therp BV <http://therp.nl>.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of th... | Add Odoo Community Association (OCA) in authors | Add Odoo Community Association (OCA) in authors
| Python | agpl-3.0 | incaser/website,pedrobaeza/website,Benniphx/website,LasLabs/website,Antiun/website,acsone/website,open-synergy/website,hbrunn/website,BT-jmichaud/website,gfcapalbo/website,brain-tec/website,sergio-incaser/website,nicolas-petit/website,syci/website-odoo,xpansa/website,open-synergy/website,Yajo/website,nicolas-petit/webs... | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# This module copyright (C) 2015 Therp BV <http://therp.nl>.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of th... | Add Odoo Community Association (OCA) in authors
# -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# This module copyright (C) 2015 Therp BV <http://therp.nl>.
#
# This program is free software: you can redistribu... |
88210804900c48a895c6ed90ae20dd08dc32e162 | alfred_listener/views.py | alfred_listener/views.py | from flask import Blueprint, request, json
from alfred_db.models import Repository, Commit
from .database import db
from .helpers import parse_hook_data
webhooks = Blueprint('webhooks', __name__)
@webhooks.route('/', methods=['POST'])
def handler():
payload = request.form.get('payload', '')
try:
pa... | from flask import Blueprint, request, json
from alfred_db.models import Repository, Commit
from .database import db
from .helpers import parse_hook_data
webhooks = Blueprint('webhooks', __name__)
@webhooks.route('/', methods=['POST'])
def handler():
payload = request.form.get('payload')
try:
payloa... | Improve loading of payload from json | Improve loading of payload from json
| Python | isc | alfredhq/alfred-listener | from flask import Blueprint, request, json
from alfred_db.models import Repository, Commit
from .database import db
from .helpers import parse_hook_data
webhooks = Blueprint('webhooks', __name__)
@webhooks.route('/', methods=['POST'])
def handler():
payload = request.form.get('payload')
try:
payloa... | Improve loading of payload from json
from flask import Blueprint, request, json
from alfred_db.models import Repository, Commit
from .database import db
from .helpers import parse_hook_data
webhooks = Blueprint('webhooks', __name__)
@webhooks.route('/', methods=['POST'])
def handler():
payload = request.form.... |
ad757857b7878904c6d842e115074c4fac24bed7 | tweetar.py | tweetar.py | import twitter
import urllib2
NOAA_URL = "http://weather.noaa.gov/pub/data/observations/metar/stations/*station_id*.TXT"
def retrieve_and_post(conf):
post = False
pull_url = NOAA_URL.replace('*station_id*', conf['station'])
request = urllib2.Request(pull_url, None)
response = urllib2.urlopen(request)... | import twitter
import urllib2
NOAA_URL = "http://weather.noaa.gov/pub/data/observations/metar/stations/*station_id*.TXT"
def retrieve_and_post(conf):
post = False
pull_url = NOAA_URL.replace('*station_id*', conf['station'])
request = urllib2.Request(pull_url, None)
response = urllib2.urlopen(request)... | Use .get instead of getattr, dummy. | Use .get instead of getattr, dummy.
| Python | bsd-3-clause | adamfast/python-tweetar | import twitter
import urllib2
NOAA_URL = "http://weather.noaa.gov/pub/data/observations/metar/stations/*station_id*.TXT"
def retrieve_and_post(conf):
post = False
pull_url = NOAA_URL.replace('*station_id*', conf['station'])
request = urllib2.Request(pull_url, None)
response = urllib2.urlopen(request)... | Use .get instead of getattr, dummy.
import twitter
import urllib2
NOAA_URL = "http://weather.noaa.gov/pub/data/observations/metar/stations/*station_id*.TXT"
def retrieve_and_post(conf):
post = False
pull_url = NOAA_URL.replace('*station_id*', conf['station'])
request = urllib2.Request(pull_url, None)
... |
d6832747545a541eba13f823a38e7fca054cab9d | labelingbot/__init__.py | labelingbot/__init__.py | import os
from flask import Flask
from flask_bootstrap import Bootstrap
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
import telegram
from config import config
APP_ROOT_PATH = os.path.dirname(os.path.abspath(__file__))
APP_STATIC_PATH = os.path.join(APP_ROOT_PATH, 'static')
APP_TEMPLA... | import os
from flask import Flask
from flask_bootstrap import Bootstrap
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
import telegram
from config import config
APP_ROOT_PATH = os.path.dirname(os.path.abspath(__file__))
APP_STATIC_PATH = os.path.join(APP_ROOT_PATH, 'static')
APP_TEMPLA... | Fix templates path error (template -> templates) | Fix templates path error (template -> templates)
| Python | mit | Lee-W/Sentence-Labeling-Bot,Lee-W/Sentence-Labeling-Bot | import os
from flask import Flask
from flask_bootstrap import Bootstrap
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
import telegram
from config import config
APP_ROOT_PATH = os.path.dirname(os.path.abspath(__file__))
APP_STATIC_PATH = os.path.join(APP_ROOT_PATH, 'static')
APP_TEMPLA... | Fix templates path error (template -> templates)
import os
from flask import Flask
from flask_bootstrap import Bootstrap
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
import telegram
from config import config
APP_ROOT_PATH = os.path.dirname(os.path.abspath(__file__))
APP_STATIC_PATH ... |
cecea26672d74a026383c08ebf26bc72ab2ee66c | pingparsing/_pingtransmitter.py | pingparsing/_pingtransmitter.py | # encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com>
"""
from __future__ import absolute_import
from __future__ import unicode_literals
import platform
import dataproperty
class PingTransmitter(object):
def __init__(self):
self.destination_host = ""
self.waittime = 1
... | # encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com>
"""
from __future__ import absolute_import
from __future__ import unicode_literals
from collections import namedtuple
import platform
import dataproperty
PingResult = namedtuple("PingResult", "stdout stderr returncode")
class PingTrans... | Change ping result error handling to return values instead of raise exception | Change ping result error handling to return values instead of raise exception
| Python | mit | thombashi/pingparsing,thombashi/pingparsing | # encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com>
"""
from __future__ import absolute_import
from __future__ import unicode_literals
from collections import namedtuple
import platform
import dataproperty
PingResult = namedtuple("PingResult", "stdout stderr returncode")
class PingTrans... | Change ping result error handling to return values instead of raise exception
# encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com>
"""
from __future__ import absolute_import
from __future__ import unicode_literals
import platform
import dataproperty
class PingTransmitter(object):
def... |
d568e040293da3438293fb007a762fd35b8c7483 | extras/client.py | extras/client.py | import os
from email.utils import formatdate
from datetime import datetime
from time import mktime
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'keybar.settings')
import django
django.setup()
from django.conf import settings
from httpsig.requests_auth import HTTPSignatureAuth
import requests
from keybar.models.u... | import os
from email.utils import formatdate
from datetime import datetime
from time import mktime
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'keybar.settings')
import django
django.setup()
from django.conf import settings
from httpsig.requests_auth import HTTPSignatureAuth
import requests
from keybar.models.u... | Fix path, use rsa-sha256 algorithm to actually use the rsa-base verification | Fix path, use rsa-sha256 algorithm to actually use the rsa-base verification
| Python | bsd-3-clause | keybar/keybar | import os
from email.utils import formatdate
from datetime import datetime
from time import mktime
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'keybar.settings')
import django
django.setup()
from django.conf import settings
from httpsig.requests_auth import HTTPSignatureAuth
import requests
from keybar.models.u... | Fix path, use rsa-sha256 algorithm to actually use the rsa-base verification
import os
from email.utils import formatdate
from datetime import datetime
from time import mktime
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'keybar.settings')
import django
django.setup()
from django.conf import settings
from httpsi... |
ca144b8254691e9633ddedb7ad11b2c4919b8b77 | app/stores/views/search.py | app/stores/views/search.py | from django.views.generic import ListView
from haystack.query import SearchQuerySet
from haystack.utils.geo import Point, D
from ..models import Store
from ..utils import caching_geo_lookup
class DistanceSearchView(ListView):
template_name = 'stores/store_search.html'
distance = 25
def get_location(self... | from django.views.generic import ListView
from haystack.query import SearchQuerySet
from haystack.utils.geo import Point, D
from ..models import Store
from ..utils import caching_geo_lookup
class DistanceSearchView(ListView):
template_name = 'stores/store_search.html'
distance = 25
def get_location(self... | Convert the lat/lng to floats for Point. | Convert the lat/lng to floats for Point.
| Python | bsd-3-clause | nikdoof/vapemap,nikdoof/vapemap | from django.views.generic import ListView
from haystack.query import SearchQuerySet
from haystack.utils.geo import Point, D
from ..models import Store
from ..utils import caching_geo_lookup
class DistanceSearchView(ListView):
template_name = 'stores/store_search.html'
distance = 25
def get_location(self... | Convert the lat/lng to floats for Point.
from django.views.generic import ListView
from haystack.query import SearchQuerySet
from haystack.utils.geo import Point, D
from ..models import Store
from ..utils import caching_geo_lookup
class DistanceSearchView(ListView):
template_name = 'stores/store_search.html'
... |
c3029a3796437add90cdd6c0033be70fe5766a3a | mapit/middleware/__init__.py | mapit/middleware/__init__.py | import re
from .view_error import *
class JSONPMiddleware(object):
def process_response(self, request, response):
# If the response is a redirect, the callback will be dealt
# on the next request:
if response.status_code == 302:
return response
else:
if requ... | import re
from .view_error import *
class JSONPMiddleware(object):
def process_response(self, request, response):
# If the response is a redirect, the callback will be dealt
# on the next request:
if response.status_code == 302:
return response
else:
cb = re... | Include typeof check in JSONP callback response. | Include typeof check in JSONP callback response.
This is more robust, and helps against attacks such as Rosetta Flash:
https://miki.it/blog/2014/7/8/abusing-jsonp-with-rosetta-flash/
| Python | agpl-3.0 | opencorato/mapit,chris48s/mapit,opencorato/mapit,Code4SA/mapit,Code4SA/mapit,opencorato/mapit,Code4SA/mapit,chris48s/mapit,chris48s/mapit | import re
from .view_error import *
class JSONPMiddleware(object):
def process_response(self, request, response):
# If the response is a redirect, the callback will be dealt
# on the next request:
if response.status_code == 302:
return response
else:
cb = re... | Include typeof check in JSONP callback response.
This is more robust, and helps against attacks such as Rosetta Flash:
https://miki.it/blog/2014/7/8/abusing-jsonp-with-rosetta-flash/
import re
from .view_error import *
class JSONPMiddleware(object):
def process_response(self, request, response):
# If th... |
ddeabd76c4277c35d1e583d1a2034ba2c047d128 | spacy/__init__.py | spacy/__init__.py | import pathlib
from .util import set_lang_class, get_lang_class
from . import en
from . import de
from . import zh
try:
basestring
except NameError:
basestring = str
set_lang_class(en.English.lang, en.English)
set_lang_class(de.German.lang, de.German)
set_lang_class(zh.Chinese.lang, zh.Chinese)
def loa... | import pathlib
from .util import set_lang_class, get_lang_class
from . import en
from . import de
from . import zh
try:
basestring
except NameError:
basestring = str
set_lang_class(en.English.lang, en.English)
set_lang_class(de.German.lang, de.German)
set_lang_class(zh.Chinese.lang, zh.Chinese)
def loa... | Fix mistake loading GloVe vectors. GloVe vectors now loaded by default if present, as promised. | Fix mistake loading GloVe vectors. GloVe vectors now loaded by default if present, as promised.
| Python | mit | spacy-io/spaCy,raphael0202/spaCy,raphael0202/spaCy,explosion/spaCy,Gregory-Howard/spaCy,spacy-io/spaCy,oroszgy/spaCy.hu,honnibal/spaCy,banglakit/spaCy,recognai/spaCy,raphael0202/spaCy,oroszgy/spaCy.hu,spacy-io/spaCy,oroszgy/spaCy.hu,spacy-io/spaCy,banglakit/spaCy,explosion/spaCy,Gregory-Howard/spaCy,recognai/spaCy,bang... | import pathlib
from .util import set_lang_class, get_lang_class
from . import en
from . import de
from . import zh
try:
basestring
except NameError:
basestring = str
set_lang_class(en.English.lang, en.English)
set_lang_class(de.German.lang, de.German)
set_lang_class(zh.Chinese.lang, zh.Chinese)
def loa... | Fix mistake loading GloVe vectors. GloVe vectors now loaded by default if present, as promised.
import pathlib
from .util import set_lang_class, get_lang_class
from . import en
from . import de
from . import zh
try:
basestring
except NameError:
basestring = str
set_lang_class(en.English.lang, en.English... |
5d2110059731069a6a29a31d2b9f02bb2743e90b | scripts/cleanup-images.py | scripts/cleanup-images.py | #!/usr/bin/python
import os, sys
import pwd
if os.geteuid():
print >> sys.stderr, "Script must be run as root to manipulate permissions"
sys.exit(1)
from conary import dbstore
from mint import config
apacheGid = pwd.getpwnam('apache')[3]
isogenUid = pwd.getpwnam('isogen')[2]
cfg = config.MintConfig()
cfg.r... | #!/usr/bin/python
import os, sys
import pwd
if os.geteuid():
print >> sys.stderr, "Script must be run as root to manipulate permissions"
sys.exit(1)
from conary import dbstore
from mint import config
apacheGid = pwd.getpwnam('apache')[3]
isogenUid = pwd.getpwnam('isogen')[2]
cfg = config.MintConfig()
cfg.r... | Kill off another hardcoded path | Kill off another hardcoded path
| Python | apache-2.0 | sassoftware/mint,sassoftware/mint,sassoftware/mint,sassoftware/mint,sassoftware/mint | #!/usr/bin/python
import os, sys
import pwd
if os.geteuid():
print >> sys.stderr, "Script must be run as root to manipulate permissions"
sys.exit(1)
from conary import dbstore
from mint import config
apacheGid = pwd.getpwnam('apache')[3]
isogenUid = pwd.getpwnam('isogen')[2]
cfg = config.MintConfig()
cfg.r... | Kill off another hardcoded path
#!/usr/bin/python
import os, sys
import pwd
if os.geteuid():
print >> sys.stderr, "Script must be run as root to manipulate permissions"
sys.exit(1)
from conary import dbstore
from mint import config
apacheGid = pwd.getpwnam('apache')[3]
isogenUid = pwd.getpwnam('isogen')[2]... |
21d940192fa390b1a2de3183e099194bceaeeafe | tests/test_arrays.py | tests/test_arrays.py | from thinglang.thinglang import run
def test_simple_arrays():
assert run("""
thing Program
does start
array names = ["yotam", "andrew", "john"]
Output.write(names)
""").output == """['yotam', 'andrew', 'john']"""
| from thinglang.thinglang import run
def test_simple_arrays():
assert run("""
thing Program
does start
array names = ["yotam", "andrew", "john"]
Output.write(names)
""").output == """['yotam', 'andrew', 'john']"""
def test_array_initialization_over_function_calls():
assert run("""
th... | Add test for more complex array initization case | Add test for more complex array initization case
| Python | mit | ytanay/thinglang,ytanay/thinglang,ytanay/thinglang,ytanay/thinglang | from thinglang.thinglang import run
def test_simple_arrays():
assert run("""
thing Program
does start
array names = ["yotam", "andrew", "john"]
Output.write(names)
""").output == """['yotam', 'andrew', 'john']"""
def test_array_initialization_over_function_calls():
assert run("""
th... | Add test for more complex array initization case
from thinglang.thinglang import run
def test_simple_arrays():
assert run("""
thing Program
does start
array names = ["yotam", "andrew", "john"]
Output.write(names)
""").output == """['yotam', 'andrew', 'john']"""
|
bf8c008742dd921865f18f10b1c925c485406343 | django_lightweight_queue/management/commands/queue_configuration.py | django_lightweight_queue/management/commands/queue_configuration.py | from django.core.management.base import NoArgsCommand
from ... import app_settings
class Command(NoArgsCommand):
def handle_noargs(self, **options):
print "django-lightweight-queue"
print "========================"
print
print "{0:<15} {1:>5}".format("Queue name", "Concurrency")
... | Add a quick way to show the current queue configuration. | Add a quick way to show the current queue configuration.
Signed-off-by: Chris Lamb <711c73f64afdce07b7e38039a96d2224209e9a6c@thread.com>
| Python | bsd-3-clause | prophile/django-lightweight-queue,prophile/django-lightweight-queue,thread/django-lightweight-queue,lamby/django-lightweight-queue,thread/django-lightweight-queue | from django.core.management.base import NoArgsCommand
from ... import app_settings
class Command(NoArgsCommand):
def handle_noargs(self, **options):
print "django-lightweight-queue"
print "========================"
print
print "{0:<15} {1:>5}".format("Queue name", "Concurrency")
... | Add a quick way to show the current queue configuration.
Signed-off-by: Chris Lamb <711c73f64afdce07b7e38039a96d2224209e9a6c@thread.com>
| |
7153c2be456084dfdd7cc346d62a6eb0fcaa2a31 | teuthology/config.py | teuthology/config.py | import os
import yaml
import logging
CONF_FILE = os.path.join(os.environ['HOME'], '.teuthology.yaml')
log = logging.getLogger(__name__)
class _Config(object):
"""
This class is intended to unify teuthology's many configuration files and
objects. Currently it serves as a convenient interface to
~/.te... | import os
import yaml
import logging
CONF_FILE = os.path.join(os.environ['HOME'], '.teuthology.yaml')
log = logging.getLogger(__name__)
class _Config(object):
"""
This class is intended to unify teuthology's many configuration files and
objects. Currently it serves as a convenient interface to
~/.te... | Add doc noting Inktank's lockserver URL | Add doc noting Inktank's lockserver URL
Since I just removed it from lockstatus.py.
| Python | mit | t-miyamae/teuthology,robbat2/teuthology,michaelsevilla/teuthology,michaelsevilla/teuthology,t-miyamae/teuthology,zhouyuan/teuthology,ivotron/teuthology,dreamhost/teuthology,ktdreyer/teuthology,dmick/teuthology,SUSE/teuthology,SUSE/teuthology,yghannam/teuthology,dmick/teuthology,dmick/teuthology,caibo2014/teuthology,cep... | import os
import yaml
import logging
CONF_FILE = os.path.join(os.environ['HOME'], '.teuthology.yaml')
log = logging.getLogger(__name__)
class _Config(object):
"""
This class is intended to unify teuthology's many configuration files and
objects. Currently it serves as a convenient interface to
~/.te... | Add doc noting Inktank's lockserver URL
Since I just removed it from lockstatus.py.
import os
import yaml
import logging
CONF_FILE = os.path.join(os.environ['HOME'], '.teuthology.yaml')
log = logging.getLogger(__name__)
class _Config(object):
"""
This class is intended to unify teuthology's many configura... |
f8eb5325b03f09a0b207680c29ba4a8cff89bec8 | v2functions/sbqueue-trigger-sbqueue-out-binding/__init__.py | v2functions/sbqueue-trigger-sbqueue-out-binding/__init__.py | import logging
import azure.functions as func
def main(msgIn: func.ServiceBusMessage, msgOut: func.Out[str]):
body = msgIn.get_body().decode('utf-8')
logging.info(f'Processed Service Bus Queue message: {body}')
msgOut.set(msgbody)
| import logging
import azure.functions as func
def main(msgIn: func.ServiceBusMessage, msgOut: func.Out[str]):
body = msgIn.get_body().decode('utf-8')
logging.info(f'Processed Service Bus Queue message: {body}')
msgOut.set(body)
| Fix var name in service bus function | Fix var name in service bus function
...i am a horrible programmer | Python | mit | yokawasa/azure-functions-python-samples,yokawasa/azure-functions-python-samples,yokawasa/azure-functions-python-samples | import logging
import azure.functions as func
def main(msgIn: func.ServiceBusMessage, msgOut: func.Out[str]):
body = msgIn.get_body().decode('utf-8')
logging.info(f'Processed Service Bus Queue message: {body}')
msgOut.set(body)
| Fix var name in service bus function
...i am a horrible programmer
import logging
import azure.functions as func
def main(msgIn: func.ServiceBusMessage, msgOut: func.Out[str]):
body = msgIn.get_body().decode('utf-8')
logging.info(f'Processed Service Bus Queue message: {body}')
msgOut.set(msgbody)
|
de613623c638b923a6bbfb6c33c373794d654000 | setup.py | setup.py | from distutils.core import setup
setup(
name='django_dust',
description='Distributed Upload STorage for Django. A file backend that mirrors all incoming media files to several servers',
packages=[
'django_dust',
'django_dust.management',
'django_dust.management.commands',
'... | from distutils.core import setup
import os.path
with open(os.path.join(os.path.dirname(__file__), 'README.md')) as f:
long_description = f.read().partition('\n\n\n')[0].partition('\n\n')[2]
setup(
name='django_dust',
version='0.1',
description='Distributed Upload STorage for Django, a file backend '
... | Add version, long description and classifiers. | Add version, long description and classifiers.
| Python | bsd-3-clause | aaugustin/django-resto | from distutils.core import setup
import os.path
with open(os.path.join(os.path.dirname(__file__), 'README.md')) as f:
long_description = f.read().partition('\n\n\n')[0].partition('\n\n')[2]
setup(
name='django_dust',
version='0.1',
description='Distributed Upload STorage for Django, a file backend '
... | Add version, long description and classifiers.
from distutils.core import setup
setup(
name='django_dust',
description='Distributed Upload STorage for Django. A file backend that mirrors all incoming media files to several servers',
packages=[
'django_dust',
'django_dust.management',
... |
575580d005802d1920402b385bfe963bb4390fac | data/Crumb_data/Crumb_data_loading.py | data/Crumb_data/Crumb_data_loading.py |
# coding: utf-8
# In[ ]:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
#import sys #(just for version number)
#import matplotlib #(just for version number)
#print('Python version ' + sys.version)
#print('Pandas version ' + pd.__version__)
#print('Matplotlib version ' + matplotlib.__ve... | Add an example python code for loading the resulting data | Add an example python code for loading the resulting data
| Python | bsd-3-clause | mirams/PyHillFit,mirams/PyHillFit,mirams/PyHillFit |
# coding: utf-8
# In[ ]:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
#import sys #(just for version number)
#import matplotlib #(just for version number)
#print('Python version ' + sys.version)
#print('Pandas version ' + pd.__version__)
#print('Matplotlib version ' + matplotlib.__ve... | Add an example python code for loading the resulting data
| |
d76398b40844e969439d495d4ea3604e5b2011b4 | mock-recipe-server/test_mock_server.py | mock-recipe-server/test_mock_server.py | """
Tests for the mock-server itself.
"""
from utils import APIPath
def test_testcase_difference(root_path):
"""Ensure that different testcases output different data."""
recipes = set()
testcase_paths = (
APIPath(path, 'http://example.com')
for path in root_path.path.iterdir() if path.is_... | """
Tests for the mock-server itself.
"""
from utils import APIPath
def test_testcase_difference(root_path):
"""Ensure that different testcases output different data."""
recipes = set()
testcase_paths = (
APIPath(path, 'http://example.com')
for path in root_path.path.iterdir() if path.is_... | Handle error testcases in mock-server tests. | Handle error testcases in mock-server tests.
| Python | mpl-2.0 | Osmose/normandy,Osmose/normandy,mozilla/normandy,mozilla/normandy,mozilla/normandy,Osmose/normandy,Osmose/normandy,mozilla/normandy | """
Tests for the mock-server itself.
"""
from utils import APIPath
def test_testcase_difference(root_path):
"""Ensure that different testcases output different data."""
recipes = set()
testcase_paths = (
APIPath(path, 'http://example.com')
for path in root_path.path.iterdir() if path.is_... | Handle error testcases in mock-server tests.
"""
Tests for the mock-server itself.
"""
from utils import APIPath
def test_testcase_difference(root_path):
"""Ensure that different testcases output different data."""
recipes = set()
testcase_paths = (
APIPath(path, 'http://example.com')
fo... |
19af4b5c8c849750dd0885ea4fcfb651545b7985 | migrations/002_add_month_start.py | migrations/002_add_month_start.py | """
Add _week_start_at field to all documents in all collections
"""
from backdrop.core.bucket import utc
from backdrop.core.records import Record
import logging
log = logging.getLogger(__name__)
def up(db):
for name in db.collection_names():
log.info("Migrating collection: {0}".format(name))
col... | """
Add _week_start_at field to all documents in all collections
"""
from backdrop.core.bucket import utc
from backdrop.core.records import Record
import logging
log = logging.getLogger(__name__)
def up(db):
for name in db.collection_names():
log.info("Migrating collection: {0}".format(name))
col... | Remove disallowed fields before resaving on migrations. | Remove disallowed fields before resaving on migrations.
- TODO: fix this properly.
| Python | mit | alphagov/backdrop,alphagov/backdrop,alphagov/backdrop | """
Add _week_start_at field to all documents in all collections
"""
from backdrop.core.bucket import utc
from backdrop.core.records import Record
import logging
log = logging.getLogger(__name__)
def up(db):
for name in db.collection_names():
log.info("Migrating collection: {0}".format(name))
col... | Remove disallowed fields before resaving on migrations.
- TODO: fix this properly.
"""
Add _week_start_at field to all documents in all collections
"""
from backdrop.core.bucket import utc
from backdrop.core.records import Record
import logging
log = logging.getLogger(__name__)
def up(db):
for name in db.colle... |
35b67e00e378df43a657c56bd751e7059ef45c38 | benchexec/tools/witnesslint.py | benchexec/tools/witnesslint.py | import benchexec.result as result
import benchexec.tools.template
class Tool(benchexec.tools.template.BaseTool2):
"""
Tool info for the witness checker (witnesslint)
(https://github.com/sosy-lab/sv-witnesses)
"""
def executable(self, tool_locator):
return tool_locator.find_executable("wit... | Add tool info for the witness linter. | Add tool info for the witness linter.
| Python | apache-2.0 | ultimate-pa/benchexec,ultimate-pa/benchexec,sosy-lab/benchexec,ultimate-pa/benchexec,ultimate-pa/benchexec,dbeyer/benchexec,sosy-lab/benchexec,sosy-lab/benchexec,sosy-lab/benchexec,dbeyer/benchexec,ultimate-pa/benchexec,dbeyer/benchexec,dbeyer/benchexec,ultimate-pa/benchexec,sosy-lab/benchexec,sosy-lab/benchexec | import benchexec.result as result
import benchexec.tools.template
class Tool(benchexec.tools.template.BaseTool2):
"""
Tool info for the witness checker (witnesslint)
(https://github.com/sosy-lab/sv-witnesses)
"""
def executable(self, tool_locator):
return tool_locator.find_executable("wit... | Add tool info for the witness linter.
| |
abce02dc1a30b869300eee36b29d5e61320d64c5 | test.py | test.py | #!/usr/bin/env python
import os
import subprocess
import time
import glob
import unittest
class ZxSpecTestCase(unittest.TestCase):
def setUp(self):
clean()
def tearDown(self):
clean()
def test_zx_spec_header_displayed(self):
ZX_SPEC_OUTPUT_FILE = "printout.txt"
proc = sub... | #!/usr/bin/env python
import os
import subprocess
import time
import glob
import unittest
class ZxSpecTestCase(unittest.TestCase):
@classmethod
def setUpClass(self):
clean()
self.output = run_zx_spec()
def test_zx_spec_header_displayed(self):
self.assertRegexpMatches(self.output, ... | Add timeout for printout production | Add timeout for printout production
| Python | mit | rhargreaves/zx-spec | #!/usr/bin/env python
import os
import subprocess
import time
import glob
import unittest
class ZxSpecTestCase(unittest.TestCase):
@classmethod
def setUpClass(self):
clean()
self.output = run_zx_spec()
def test_zx_spec_header_displayed(self):
self.assertRegexpMatches(self.output, ... | Add timeout for printout production
#!/usr/bin/env python
import os
import subprocess
import time
import glob
import unittest
class ZxSpecTestCase(unittest.TestCase):
def setUp(self):
clean()
def tearDown(self):
clean()
def test_zx_spec_header_displayed(self):
ZX_SPEC_OUTPUT_FILE... |
355e0bab150f2e5c5c52b02714dfaef997dda856 | regparser/tree/xml_parser/flatsubtree_processor.py | regparser/tree/xml_parser/flatsubtree_processor.py | from regparser.tree.depth import markers as mtypes
from regparser.tree.struct import Node
from regparser.tree.xml_parser import (
paragraph_processor, simple_hierarchy_processor, us_code)
class FlatParagraphProcessor(paragraph_processor.ParagraphProcessor):
"""Paragraph Processor which does not try to derive ... | from regparser.tree.depth import markers as mtypes
from regparser.tree.struct import Node
from regparser.tree.xml_parser import (
paragraph_processor, simple_hierarchy_processor, us_code)
class FlatParagraphProcessor(paragraph_processor.ParagraphProcessor):
"""Paragraph Processor which does not try to derive ... | Allow images in EXTRACTs, etc. | Allow images in EXTRACTs, etc.
| Python | cc0-1.0 | tadhg-ohiggins/regulations-parser,eregs/regulations-parser,eregs/regulations-parser,tadhg-ohiggins/regulations-parser | from regparser.tree.depth import markers as mtypes
from regparser.tree.struct import Node
from regparser.tree.xml_parser import (
paragraph_processor, simple_hierarchy_processor, us_code)
class FlatParagraphProcessor(paragraph_processor.ParagraphProcessor):
"""Paragraph Processor which does not try to derive ... | Allow images in EXTRACTs, etc.
from regparser.tree.depth import markers as mtypes
from regparser.tree.struct import Node
from regparser.tree.xml_parser import (
paragraph_processor, simple_hierarchy_processor, us_code)
class FlatParagraphProcessor(paragraph_processor.ParagraphProcessor):
"""Paragraph Process... |
74e46d577bab048a473862b070d8abfb1db00ea1 | workup/migrations/0005_auto_20160826_0620.py | workup/migrations/0005_auto_20160826_0620.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
import workup.validators
class Migration(migrations.Migration):
dependencies = [
('workup', '0004_auto_20160328_1425'),
]
operations = [
migrations.AlterField(
model_name... | Add migration for updates to workup (smallintegerfield -> charfield to fix vitals thing). | Add migration for updates to workup (smallintegerfield -> charfield to fix vitals thing).
| Python | mit | SaturdayNeighborhoodHealthClinic/clintools,SaturdayNeighborhoodHealthClinic/clintools,SaturdayNeighborhoodHealthClinic/clintools | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
import workup.validators
class Migration(migrations.Migration):
dependencies = [
('workup', '0004_auto_20160328_1425'),
]
operations = [
migrations.AlterField(
model_name... | Add migration for updates to workup (smallintegerfield -> charfield to fix vitals thing).
| |
55a330149a05c456012f2570c2151a82ac8435b2 | images/singleuser/user-config.py | images/singleuser/user-config.py | import os
mylang = 'test'
family = 'wikipedia'
custom_path = os.path.expanduser('~/user-config.py')
if os.path.exists(custom_path):
with open(custom_path, 'rb') as f:
exec(compile(f.read(), custom_path, 'exec'), globals())
del f
# Clean up temp variables, since pwb issues a warning otherwise
# to he... | import os
mylang = 'test'
family = 'wikipedia'
custom_path = os.path.expanduser('~/user-config.py')
if os.path.exists(custom_path):
with open(custom_path, 'rb') as f:
exec(compile(f.read(), custom_path, 'exec'), globals())
del f
# Clean up temp variables, since pwb issues a warning otherwise
# to he... | Revert to previous way of setting 'authenticate' | Revert to previous way of setting 'authenticate'
This reverts commit a055f97a342f670171f30095cabfd4ba1bfdad17.
This reverts commit 4cec5250a3f9058fea5af5ef432a5b230ca94963.
| Python | mit | yuvipanda/paws,yuvipanda/paws | import os
mylang = 'test'
family = 'wikipedia'
custom_path = os.path.expanduser('~/user-config.py')
if os.path.exists(custom_path):
with open(custom_path, 'rb') as f:
exec(compile(f.read(), custom_path, 'exec'), globals())
del f
# Clean up temp variables, since pwb issues a warning otherwise
# to he... | Revert to previous way of setting 'authenticate'
This reverts commit a055f97a342f670171f30095cabfd4ba1bfdad17.
This reverts commit 4cec5250a3f9058fea5af5ef432a5b230ca94963.
import os
mylang = 'test'
family = 'wikipedia'
custom_path = os.path.expanduser('~/user-config.py')
if os.path.exists(custom_path):
with o... |
8404143e9335374979d028ffabbc9f7369a11e80 | admin/genkwh_remesa_cobrament_cron.py | admin/genkwh_remesa_cobrament_cron.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
from erppeek import Client
import configdb
import datetime
'''
Script que agafa les inversions en esborrany i genera les factures de cobrament i les afegeix a la remesa.
python admin/genkwh_remesa_cobrament_cron.py
'''
def crear_remesa_generation(O):i
... | Add script to do investment generation payment order | Add script to do investment generation payment order
| Python | agpl-3.0 | Som-Energia/invoice-janitor | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
from erppeek import Client
import configdb
import datetime
'''
Script que agafa les inversions en esborrany i genera les factures de cobrament i les afegeix a la remesa.
python admin/genkwh_remesa_cobrament_cron.py
'''
def crear_remesa_generation(O):i
... | Add script to do investment generation payment order
| |
d1ab1b7e7edf74f89274e48718fac0b6ac6d191d | dthm4kaiako/config/__init__.py | dthm4kaiako/config/__init__.py | """Configuration for Django system."""
__version__ = "0.14.0"
__version_info__ = tuple(
[
int(num) if num.isdigit() else num
for num in __version__.replace("-", ".", 1).split(".")
]
)
| """Configuration for Django system."""
__version__ = "0.14.1"
__version_info__ = tuple(
[
int(num) if num.isdigit() else num
for num in __version__.replace("-", ".", 1).split(".")
]
)
| Increment version number to 0.14.1 | Increment version number to 0.14.1
| Python | mit | uccser/cs4teachers,uccser/cs4teachers,uccser/cs4teachers,uccser/cs4teachers | """Configuration for Django system."""
__version__ = "0.14.1"
__version_info__ = tuple(
[
int(num) if num.isdigit() else num
for num in __version__.replace("-", ".", 1).split(".")
]
)
| Increment version number to 0.14.1
"""Configuration for Django system."""
__version__ = "0.14.0"
__version_info__ = tuple(
[
int(num) if num.isdigit() else num
for num in __version__.replace("-", ".", 1).split(".")
]
)
|
a11ed2f8db4d755764a94f9e71bd28e4e3cf582b | py/subarray-sum-equals-k.py | py/subarray-sum-equals-k.py | from collections import Counter
class Solution(object):
def subarraySum(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
subsum = [0]
for i, n in enumerate(nums):
subsum.append(subsum[-1] + n)
c = Counter()
an... | Add py solution for 560. Subarray Sum Equals K | Add py solution for 560. Subarray Sum Equals K
560. Subarray Sum Equals K: https://leetcode.com/problems/subarray-sum-equals-k/
| Python | apache-2.0 | ckclark/leetcode,ckclark/leetcode,ckclark/leetcode,ckclark/leetcode,ckclark/leetcode,ckclark/leetcode | from collections import Counter
class Solution(object):
def subarraySum(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
subsum = [0]
for i, n in enumerate(nums):
subsum.append(subsum[-1] + n)
c = Counter()
an... | Add py solution for 560. Subarray Sum Equals K
560. Subarray Sum Equals K: https://leetcode.com/problems/subarray-sum-equals-k/
| |
b80eae0285af97d8fe954a5df667e03b004efa12 | instrument-classification/leaderboard.py | instrument-classification/leaderboard.py | import glob
import numpy as np
import pandas as pd
def load_df(file_name):
model_id = file_name.split('/')[4]
df = pd.read_csv(file_name)
df.rename(columns={'Unnamed: 0': 'split'}, inplace=True)
df['model_id'] = model_id
if 'auc' not in df.columns:
df['auc'] = np.nan
df = df[['model_id'... | import glob
import numpy as np
import pandas as pd
def load_df(file_name):
model_id = file_name.split('/')[4]
df = pd.read_csv(file_name)
df.rename(columns={'Unnamed: 0': 'split'}, inplace=True)
df['model_id'] = model_id
if 'auc' not in df.columns:
df['auc'] = np.nan
df = df[['model_id'... | Fix ordering of latest models on the leader board. | Fix ordering of latest models on the leader board.
| Python | mit | bzamecnik/ml-playground,bzamecnik/ml-playground,bzamecnik/ml,bzamecnik/ml,bzamecnik/ml | import glob
import numpy as np
import pandas as pd
def load_df(file_name):
model_id = file_name.split('/')[4]
df = pd.read_csv(file_name)
df.rename(columns={'Unnamed: 0': 'split'}, inplace=True)
df['model_id'] = model_id
if 'auc' not in df.columns:
df['auc'] = np.nan
df = df[['model_id'... | Fix ordering of latest models on the leader board.
import glob
import numpy as np
import pandas as pd
def load_df(file_name):
model_id = file_name.split('/')[4]
df = pd.read_csv(file_name)
df.rename(columns={'Unnamed: 0': 'split'}, inplace=True)
df['model_id'] = model_id
if 'auc' not in df.columns... |
26250bf43e659c03576a4d7e4d986b622a18bb48 | swifpy/dictionary.py | swifpy/dictionary.py | import typing as tp
import builtins as py
from .optional import Optional, optional
K = tp.TypeVar('K')
V = tp.TypeVar('V')
class Dictionary(tp.Generic[K, V], tp.Iterable[tp.Tuple[K, V]]):
def __init__(self, entries: tp.Dict[K, V]) -> None:
self._entries: tp.Dict[K, V] = py.dict(entries)
def __getite... | import typing as tp
import builtins as py
from .optional import Optional, optional
K = tp.TypeVar('K')
V = tp.TypeVar('V')
class Dictionary(tp.Generic[K, V], tp.Iterable[tp.Tuple[K, V]]):
def __init__(self, entries: tp.Dict[K, V]) -> None:
self._entries: tp.Dict[K, V] = py.dict(entries)
def __getite... | Implement `keys` and `values` of `Dictionary` | Implement `keys` and `values` of `Dictionary`
| Python | mit | koher/swifpy | import typing as tp
import builtins as py
from .optional import Optional, optional
K = tp.TypeVar('K')
V = tp.TypeVar('V')
class Dictionary(tp.Generic[K, V], tp.Iterable[tp.Tuple[K, V]]):
def __init__(self, entries: tp.Dict[K, V]) -> None:
self._entries: tp.Dict[K, V] = py.dict(entries)
def __getite... | Implement `keys` and `values` of `Dictionary`
import typing as tp
import builtins as py
from .optional import Optional, optional
K = tp.TypeVar('K')
V = tp.TypeVar('V')
class Dictionary(tp.Generic[K, V], tp.Iterable[tp.Tuple[K, V]]):
def __init__(self, entries: tp.Dict[K, V]) -> None:
self._entries: tp.... |
b30d02bd077f1b7785c41e567aa4c4b44bba6a29 | backend/unimeet/mail/__init__.py | backend/unimeet/mail/__init__.py | __all__ = ['mail']
from .mail import send_mail, SUBJECTS
| __all__ = ['mail']
from .mail import send_mail, SUBJECTS, send_contact_form, send_contact_response
| Add send_contact_{form,response} functions to mail init | Add send_contact_{form,response} functions to mail init
| Python | mit | dimkarakostas/unimeet,dimkarakostas/unimeet,dimkarakostas/unimeet,dimkarakostas/unimeet | __all__ = ['mail']
from .mail import send_mail, SUBJECTS, send_contact_form, send_contact_response
| Add send_contact_{form,response} functions to mail init
__all__ = ['mail']
from .mail import send_mail, SUBJECTS
|
22b5f7ecc6057252ec77d037522b5783c5f86c1f | mcmodfixes.py | mcmodfixes.py | #!/usr/bin/python
# Fixes and mod-specific data for various mods' mcmod.info files
DEP_BLACKLIST = set((
"mod_MinecraftForge", # we always have Forge
"Forge", # typo for mod_MinecraftForge
"Industrialcraft", # typo for IC2
"GUI_Api", # typo for GuiAPI and not needed on server
))
DEP_ADDITIONS... | #!/usr/bin/python
# Fixes and mod-specific data for various mods' mcmod.info files
DEP_BLACKLIST = set((
"mod_MinecraftForge", # we always have Forge
"Forge", # typo for mod_MinecraftForge
"Industrialcraft", # typo for IC2
"GUI_Api", # typo for GuiAPI and not needed on server
"EurysCore", # rep... | Add mcmod.info fix for SlopesAndCorners SlimevoidLib dependency | Add mcmod.info fix for SlopesAndCorners SlimevoidLib dependency
| Python | bsd-3-clause | agaricusb/ModAnalyzer,agaricusb/ModAnalyzer | #!/usr/bin/python
# Fixes and mod-specific data for various mods' mcmod.info files
DEP_BLACKLIST = set((
"mod_MinecraftForge", # we always have Forge
"Forge", # typo for mod_MinecraftForge
"Industrialcraft", # typo for IC2
"GUI_Api", # typo for GuiAPI and not needed on server
"EurysCore", # rep... | Add mcmod.info fix for SlopesAndCorners SlimevoidLib dependency
#!/usr/bin/python
# Fixes and mod-specific data for various mods' mcmod.info files
DEP_BLACKLIST = set((
"mod_MinecraftForge", # we always have Forge
"Forge", # typo for mod_MinecraftForge
"Industrialcraft", # typo for IC2
"GUI_Api", ... |
5d6d2a02963cadd9b0a5c148fb6906fa63148052 | booster_bdd/features/environment.py | booster_bdd/features/environment.py | """Module with code to be run before and after certain events during the testing."""
import os
from src.support import helpers
def before_all(_context):
"""Perform the setup before the first event."""
if not helpers.is_user_logged_in():
username = os.getenv("OSIO_USERNAME")
password = os.geten... | """Module with code to be run before and after certain events during the testing."""
import os
from src.support import helpers
def before_all(_context):
"""Perform the setup before the first event."""
if not helpers.is_user_logged_in():
username = os.getenv("OSIO_USERNAME")
password = os.geten... | Check for env. variable existence | Check for env. variable existence
| Python | apache-2.0 | ldimaggi/fabric8-test,ldimaggi/fabric8-test,ldimaggi/fabric8-test,ldimaggi/fabric8-test,ldimaggi/fabric8-test,ldimaggi/fabric8-test | """Module with code to be run before and after certain events during the testing."""
import os
from src.support import helpers
def before_all(_context):
"""Perform the setup before the first event."""
if not helpers.is_user_logged_in():
username = os.getenv("OSIO_USERNAME")
password = os.geten... | Check for env. variable existence
"""Module with code to be run before and after certain events during the testing."""
import os
from src.support import helpers
def before_all(_context):
"""Perform the setup before the first event."""
if not helpers.is_user_logged_in():
username = os.getenv("OSIO_USE... |
38359ccf2e1269ea01ecb0df274ff47ea18b4e19 | setup.py | setup.py | from os.path import join
from setuptools import setup, find_packages
long_description = (open('README.rst').read() +
open('CHANGES.rst').read() +
open('TODO.rst').read())
def get_version():
with open(join('model_utils', '__init__.py')) as f:
for line in f:
... | from os.path import join
from setuptools import setup, find_packages
long_description = (open('README.rst').read() +
open('CHANGES.rst').read() +
open('TODO.rst').read())
def get_version():
with open(join('model_utils', '__init__.py')) as f:
for line in f:
... | Fix case of Django dependency. Thanks Travis Swicegood. | Fix case of Django dependency. Thanks Travis Swicegood.
| Python | bsd-3-clause | yeago/django-model-utils,carljm/django-model-utils,timmygee/django-model-utils,timmygee/django-model-utils,yeago/django-model-utils,nemesisdesign/django-model-utils,nemesisdesign/django-model-utils,patrys/django-model-utils,patrys/django-model-utils,carljm/django-model-utils | from os.path import join
from setuptools import setup, find_packages
long_description = (open('README.rst').read() +
open('CHANGES.rst').read() +
open('TODO.rst').read())
def get_version():
with open(join('model_utils', '__init__.py')) as f:
for line in f:
... | Fix case of Django dependency. Thanks Travis Swicegood.
from os.path import join
from setuptools import setup, find_packages
long_description = (open('README.rst').read() +
open('CHANGES.rst').read() +
open('TODO.rst').read())
def get_version():
with open(join('model_uti... |
28af79e1f4362db812247911b3cda1831bed75bf | utils/result_analysis.py | utils/result_analysis.py | __author__ = 'quinnosha'
"""Tools for viewing and analyzing prediction results
.. moduleauthor:: Quinn Osha
"""
from os.path import abspath, dirname, join
from utils.data_paths import RESULTS_DIR_PATH
def find_lowest_rmse(rmse_file_name):
rmse_file_path = join(RESULTS_DIR_PATH, rmse_file_name)
read_format ... | Add script to find lowest rmse result values | Add script to find lowest rmse result values
| Python | mit | jvanbrug/netflix,jvanbrug/netflix | __author__ = 'quinnosha'
"""Tools for viewing and analyzing prediction results
.. moduleauthor:: Quinn Osha
"""
from os.path import abspath, dirname, join
from utils.data_paths import RESULTS_DIR_PATH
def find_lowest_rmse(rmse_file_name):
rmse_file_path = join(RESULTS_DIR_PATH, rmse_file_name)
read_format ... | Add script to find lowest rmse result values
| |
51b7fba10a85136877c8a918d4d24d5a431a2a7f | mzalendo/run_all_tests_with_coverage.py | mzalendo/run_all_tests_with_coverage.py | #!/bin/bash
find . -name '*.pyc' -delete
coverage erase
OMIT="$(python -c 'import sys; print sys.prefix')"
coverage run --omit=$OMIT ./manage.py test \
core \
feedback \
hansard \
helpers \
images \
info \
scorecards \
search ... | #!/bin/bash
find . -name '*.pyc' -delete
coverage erase
OMIT="$(python -c 'import sys; print sys.prefix')/*"
coverage run --omit=$OMIT ./manage.py test \
core \
feedback \
hansard \
helpers \
images \
info \
scorecards \
search ... | Correct the --omit parameter for coverage.py | Correct the --omit parameter for coverage.py
Despite what some things on the web suggest, you seem to need
to have a wildcard at the end of a path in the --omit list.
| Python | agpl-3.0 | hzj123/56th,patricmutwiri/pombola,ken-muturi/pombola,patricmutwiri/pombola,mysociety/pombola,mysociety/pombola,ken-muturi/pombola,ken-muturi/pombola,patricmutwiri/pombola,geoffkilpin/pombola,ken-muturi/pombola,hzj123/56th,patricmutwiri/pombola,ken-muturi/pombola,mysociety/pombola,mysociety/pombola,hzj123/56th,mysociety... | #!/bin/bash
find . -name '*.pyc' -delete
coverage erase
OMIT="$(python -c 'import sys; print sys.prefix')/*"
coverage run --omit=$OMIT ./manage.py test \
core \
feedback \
hansard \
helpers \
images \
info \
scorecards \
search ... | Correct the --omit parameter for coverage.py
Despite what some things on the web suggest, you seem to need
to have a wildcard at the end of a path in the --omit list.
#!/bin/bash
find . -name '*.pyc' -delete
coverage erase
OMIT="$(python -c 'import sys; print sys.prefix')"
coverage run --omit=$OMIT ./manage.py te... |
a16fd23027b5d3f1378f5b9f75958d0f3ef2a124 | bandit/__init__.py | bandit/__init__.py | """
django-email-bandit is a Django email backend for hijacking email sending in a test environment.
"""
__version_info__ = {
'major': 0,
'minor': 2,
'micro': 0,
'releaselevel': 'final',
}
def get_version():
"""
Return the formatted version information
"""
vers = ["%(major)i.%(minor)... | """
django-email-bandit is a Django email backend for hijacking email sending in a test environment.
"""
__version_info__ = {
'major': 1,
'minor': 0,
'micro': 0,
'releaselevel': 'dev',
}
def get_version():
"""
Return the formatted version information
"""
vers = ["%(major)i.%(minor)i"... | Bump version number to reflect dev status. | Bump version number to reflect dev status.
| Python | bsd-3-clause | caktus/django-email-bandit,vericant/django-email-bandit,caktus/django-email-bandit | """
django-email-bandit is a Django email backend for hijacking email sending in a test environment.
"""
__version_info__ = {
'major': 1,
'minor': 0,
'micro': 0,
'releaselevel': 'dev',
}
def get_version():
"""
Return the formatted version information
"""
vers = ["%(major)i.%(minor)i"... | Bump version number to reflect dev status.
"""
django-email-bandit is a Django email backend for hijacking email sending in a test environment.
"""
__version_info__ = {
'major': 0,
'minor': 2,
'micro': 0,
'releaselevel': 'final',
}
def get_version():
"""
Return the formatted version informa... |
6c40079139e714ff145e0a4adff8c3a537172ef5 | erpnext/patches/v4_1/fix_delivery_and_billing_status_for_draft_so.py | erpnext/patches/v4_1/fix_delivery_and_billing_status_for_draft_so.py | # Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import frappe
def execute():
frappe.db.sql("""update `tabSales Order` set delivery_status = 'Not Delivered'
where delivery_status = 'Delivered' ... | # Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import frappe
def execute():
frappe.db.sql("""update `tabSales Order` set delivery_status = 'Not Delivered'
where delivery_status = 'Delivered' ... | Update delivery and billing status in SO | Update delivery and billing status in SO
| Python | agpl-3.0 | gangadharkadam/saloon_erp,njmube/erpnext,Tejal011089/fbd_erpnext,anandpdoshi/erpnext,SPKian/Testing,indictranstech/focal-erpnext,mbauskar/helpdesk-erpnext,4commerce-technologies-AG/erpnext,mbauskar/helpdesk-erpnext,indictranstech/vestasi-erpnext,indictranstech/internal-erpnext,indictranstech/phrerp,indictranstech/buyba... | # Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import frappe
def execute():
frappe.db.sql("""update `tabSales Order` set delivery_status = 'Not Delivered'
where delivery_status = 'Delivered' ... | Update delivery and billing status in SO
# Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import frappe
def execute():
frappe.db.sql("""update `tabSales Order` set delivery_status = 'Not Delivere... |
a668afc87465989e85153c9bd2a608ba0ba54d9b | tests/test_containers.py | tests/test_containers.py | try:
from http.server import SimpleHTTPRequestHandler
except ImportError:
from SimpleHTTPServer import SimpleHTTPRequestHandler
try:
from socketserver import TCPServer
except ImportError:
from SocketServer import TCPServer
import os
import threading
import unittest
import glob, os
import containers
... | try:
from http.server import SimpleHTTPRequestHandler
except ImportError:
from SimpleHTTPServer import SimpleHTTPRequestHandler
try:
from socketserver import TCPServer
except ImportError:
from SocketServer import TCPServer
import glob
import os
import sys
import threading
import unittest
import conta... | Add test that aci was downloaded | Add test that aci was downloaded
| Python | mit | kragniz/containers | try:
from http.server import SimpleHTTPRequestHandler
except ImportError:
from SimpleHTTPServer import SimpleHTTPRequestHandler
try:
from socketserver import TCPServer
except ImportError:
from SocketServer import TCPServer
import glob
import os
import sys
import threading
import unittest
import conta... | Add test that aci was downloaded
try:
from http.server import SimpleHTTPRequestHandler
except ImportError:
from SimpleHTTPServer import SimpleHTTPRequestHandler
try:
from socketserver import TCPServer
except ImportError:
from SocketServer import TCPServer
import os
import threading
import unittest
im... |
d4eb11f846da5b38a56599ca18d68fd2344dec7c | DilipadCorpus.py | DilipadCorpus.py | """Class to access dilipad corpus."""
import gensim
import glob
import codecs
class DilipadCorpus(gensim.corpora.TextCorpus):
def get_texts(self):
for txt in self.input:
with codecs.open(txt, 'rb', 'utf8') as f:
words = f.read().split()
yield words
def __l... | Add class to access dilipad text data | Add class to access dilipad text data
Currently only the nouns (topic words) are accessed. This class must be
updated to also return the opinion words of a text. The idea is to have
such a corpus per perspective for cross perspective topic modeling.
| Python | apache-2.0 | NLeSC/cptm,NLeSC/cptm | """Class to access dilipad corpus."""
import gensim
import glob
import codecs
class DilipadCorpus(gensim.corpora.TextCorpus):
def get_texts(self):
for txt in self.input:
with codecs.open(txt, 'rb', 'utf8') as f:
words = f.read().split()
yield words
def __l... | Add class to access dilipad text data
Currently only the nouns (topic words) are accessed. This class must be
updated to also return the opinion words of a text. The idea is to have
such a corpus per perspective for cross perspective topic modeling.
| |
74f915946c346238b6badb7c494cefa356cf6f84 | busineme/core/views.py | busineme/core/views.py | """Busine-me API
Universidade de Brasilia - FGA
Técnicas de Programação, 2/2015
@file views.py
Views (on classic MVC, controllers) with methods that control the requisitions
for the user authentication and manipulation.
"""
from django.views.generic import View
from core.serializers import serialize_objects
from .mode... | """Busine-me API
Universidade de Brasilia - FGA
Técnicas de Programação, 2/2015
@file views.py
Views (on classic MVC, controllers) with methods that control the requisitions
for the user authentication and manipulation.
"""
from django.views.generic import View
from core.serializers import serialize_objects
from .mode... | Change name getbusline name method | Change name getbusline name method
| Python | agpl-3.0 | aldarionsevero/busine.meAPI,aldarionsevero/busine.meAPI | """Busine-me API
Universidade de Brasilia - FGA
Técnicas de Programação, 2/2015
@file views.py
Views (on classic MVC, controllers) with methods that control the requisitions
for the user authentication and manipulation.
"""
from django.views.generic import View
from core.serializers import serialize_objects
from .mode... | Change name getbusline name method
"""Busine-me API
Universidade de Brasilia - FGA
Técnicas de Programação, 2/2015
@file views.py
Views (on classic MVC, controllers) with methods that control the requisitions
for the user authentication and manipulation.
"""
from django.views.generic import View
from core.serializers... |
1c55fdc21062a7090a76fc7316c93d6ed4647d53 | tests/rules_tests/grammarManipulation_tests/RemoveTest.py | tests/rules_tests/grammarManipulation_tests/RemoveTest.py | #!/usr/bin/env python
"""
:Author Patrik Valkovic
:Created 23.06.2017 16:39
:Licence GNUv3
Part of grammpy
"""
from unittest import main, TestCase
from grammpy import Rule as _R, Grammar
from rules_tests.grammar import *
class RemoveTest(TestCase):
def __init__(self, *args):
super().__init__(*args)
... | Add file for rule remove tests | Add file for rule remove tests
| Python | mit | PatrikValkovic/grammpy | #!/usr/bin/env python
"""
:Author Patrik Valkovic
:Created 23.06.2017 16:39
:Licence GNUv3
Part of grammpy
"""
from unittest import main, TestCase
from grammpy import Rule as _R, Grammar
from rules_tests.grammar import *
class RemoveTest(TestCase):
def __init__(self, *args):
super().__init__(*args)
... | Add file for rule remove tests
| |
3ff8b3de2b9f0d1de1414bad12d06d931e7919cd | utils/create_tree_from_metadata.py | utils/create_tree_from_metadata.py | #!/usr/bin/env python
"""
A utility to create a Girder hierarchy from metadata.json.
Useful in testing the monkeybrains plugin to set up a hierarchy,
then set_metadata.py can be run to add the metadata.
"""
import argparse
import json
import requests.packages.urllib3
from girder_client import GirderClient
requests... | Add utility to create test tree | Add utility to create test tree
| Python | apache-2.0 | girder/monkeybrains,girder/monkeybrains,girder/monkeybrains | #!/usr/bin/env python
"""
A utility to create a Girder hierarchy from metadata.json.
Useful in testing the monkeybrains plugin to set up a hierarchy,
then set_metadata.py can be run to add the metadata.
"""
import argparse
import json
import requests.packages.urllib3
from girder_client import GirderClient
requests... | Add utility to create test tree
| |
97b2e90f4f9a4f3c08f4556856aec1d31b44749a | flocker/control/_clusterstate.py | flocker/control/_clusterstate.py | # Copyright Hybrid Logic Ltd. See LICENSE file for details.
"""
Combine and retrieve current cluster state.
"""
from twisted.application.service import Service
from ._model import Deployment, Node
class ClusterStateService(Service):
"""
Store known current cluster state, and combine partial updates with
... | # Copyright Hybrid Logic Ltd. See LICENSE file for details.
"""
Combine and retrieve current cluster state.
"""
from twisted.application.service import Service
from ._model import Deployment, Node
class ClusterStateService(Service):
"""
Store known current cluster state, and combine partial updates with
... | Address review comment: Link to issue. | Address review comment: Link to issue.
| Python | apache-2.0 | achanda/flocker,runcom/flocker,Azulinho/flocker,mbrukman/flocker,jml/flocker,moypray/flocker,AndyHuu/flocker,agonzalezro/flocker,Azulinho/flocker,moypray/flocker,w4ngyi/flocker,moypray/flocker,jml/flocker,LaynePeng/flocker,hackday-profilers/flocker,adamtheturtle/flocker,LaynePeng/flocker,1d4Nf6/flocker,w4ngyi/flocker,a... | # Copyright Hybrid Logic Ltd. See LICENSE file for details.
"""
Combine and retrieve current cluster state.
"""
from twisted.application.service import Service
from ._model import Deployment, Node
class ClusterStateService(Service):
"""
Store known current cluster state, and combine partial updates with
... | Address review comment: Link to issue.
# Copyright Hybrid Logic Ltd. See LICENSE file for details.
"""
Combine and retrieve current cluster state.
"""
from twisted.application.service import Service
from ._model import Deployment, Node
class ClusterStateService(Service):
"""
Store known current cluster s... |
1e5ec4a2923757ca79c8a55b056fd13872cac963 | foyer/tests/test_xml_writer.py | foyer/tests/test_xml_writer.py | import glob
import itertools as it
import os
import parmed as pmd
from pkg_resources import resource_filename
import pytest
from foyer import Forcefield
from foyer.tests.utils import atomtype
from foyer.xml_writer import write_foyer
def test_write_xml(filename, ff_file):
structure = pmd.loadfile(filename)
forc... | import parmed as pmd
import pytest
import os
from pkg_resources import resource_filename
from foyer import Forcefield
from foyer.xml_writer import write_foyer
OPLS_TESTFILES_DIR = resource_filename('foyer', 'opls_validation')
def test_write_xml():
top = os.path.join(OPLS_TESTFILES_DIR, 'benzene/benzene.top')
... | Update xml writer test to work | Update xml writer test to work
| Python | mit | iModels/foyer,mosdef-hub/foyer,mosdef-hub/foyer,iModels/foyer | import parmed as pmd
import pytest
import os
from pkg_resources import resource_filename
from foyer import Forcefield
from foyer.xml_writer import write_foyer
OPLS_TESTFILES_DIR = resource_filename('foyer', 'opls_validation')
def test_write_xml():
top = os.path.join(OPLS_TESTFILES_DIR, 'benzene/benzene.top')
... | Update xml writer test to work
import glob
import itertools as it
import os
import parmed as pmd
from pkg_resources import resource_filename
import pytest
from foyer import Forcefield
from foyer.tests.utils import atomtype
from foyer.xml_writer import write_foyer
def test_write_xml(filename, ff_file):
structure ... |
476d8663b8b85ca902703eeee697ae5be0eefabb | lc0118_pascal_triangle.py | lc0118_pascal_triangle.py | """Leetcode 118. Pascal's Triangle
Easy
URL: https://leetcode.com/problems/pascals-triangle/
Given a non-negative integer numRows, generate the first numRows of
Pascal's triangle.
In Pascal's triangle, each number is the sum of the two numbers directly
above it.
Example:
Input: 5
Output:
[
[1],
[1,1],
... | """Leetcode 118. Pascal's Triangle
Easy
URL: https://leetcode.com/problems/pascals-triangle/
Given a non-negative integer numRows, generate the first numRows of
Pascal's triangle.
In Pascal's triangle, each number is the sum of the two numbers directly
above it.
Example:
Input: 5
Output:
[
[1],
[1,1],
... | Refactor by using array T | Refactor by using array T
| Python | bsd-2-clause | bowen0701/algorithms_data_structures | """Leetcode 118. Pascal's Triangle
Easy
URL: https://leetcode.com/problems/pascals-triangle/
Given a non-negative integer numRows, generate the first numRows of
Pascal's triangle.
In Pascal's triangle, each number is the sum of the two numbers directly
above it.
Example:
Input: 5
Output:
[
[1],
[1,1],
... | Refactor by using array T
"""Leetcode 118. Pascal's Triangle
Easy
URL: https://leetcode.com/problems/pascals-triangle/
Given a non-negative integer numRows, generate the first numRows of
Pascal's triangle.
In Pascal's triangle, each number is the sum of the two numbers directly
above it.
Example:
Input: 5
Output... |
21a6ddca55c8b5da70d806afa18f08ac20cb04c0 | src/zsl/interface/webservice/performers/method.py | src/zsl/interface/webservice/performers/method.py | """
:mod:`zsl.interface.webservice.performers.method`
-------------------------------------------------
.. moduleauthor:: Martin Babka
"""
from __future__ import unicode_literals
import logging
from importlib import import_module, reload
import sys
from zsl.router.method import get_method_packages
def call_expose... | """
:mod:`zsl.interface.webservice.performers.method`
-------------------------------------------------
.. moduleauthor:: Martin Babka
"""
from __future__ import unicode_literals
import logging
from importlib import import_module
import sys
from zsl.router.method import get_method_packages
def call_exposers_in_me... | Remove the unused import and fix testing library | Remove the unused import and fix testing library
| Python | mit | AtteqCom/zsl,AtteqCom/zsl | """
:mod:`zsl.interface.webservice.performers.method`
-------------------------------------------------
.. moduleauthor:: Martin Babka
"""
from __future__ import unicode_literals
import logging
from importlib import import_module
import sys
from zsl.router.method import get_method_packages
def call_exposers_in_me... | Remove the unused import and fix testing library
"""
:mod:`zsl.interface.webservice.performers.method`
-------------------------------------------------
.. moduleauthor:: Martin Babka
"""
from __future__ import unicode_literals
import logging
from importlib import import_module, reload
import sys
from zsl.router.m... |
f75d06702274257215229b83c4ff74de3dc72463 | nnpy/tests.py | nnpy/tests.py | from __future__ import print_function
import nnpy, unittest
class Tests(unittest.TestCase):
def test_basic(self):
pub = nnpy.Socket(nnpy.AF_SP, nnpy.PUB)
pub.bind('inproc://foo')
self.assertEqual(pub.getsockopt(nnpy.SOL_SOCKET, nnpy.DOMAIN), 1)
sub = nnpy.Socket(nnpy.AF_SP, nnpy.S... | from __future__ import print_function
import nnpy, unittest
class Tests(unittest.TestCase):
def test_basic(self):
pub = nnpy.Socket(nnpy.AF_SP, nnpy.PUB)
pub.setsockopt(nnpy.SOL_SOCKET, nnpy.IPV4ONLY, 0)
pub.bind('inproc://foo')
self.assertEqual(pub.getsockopt(nnpy.SOL_SOCKET, nnpy... | Add some more test coverage | Add some more test coverage
| Python | mit | nanomsg/nnpy | from __future__ import print_function
import nnpy, unittest
class Tests(unittest.TestCase):
def test_basic(self):
pub = nnpy.Socket(nnpy.AF_SP, nnpy.PUB)
pub.setsockopt(nnpy.SOL_SOCKET, nnpy.IPV4ONLY, 0)
pub.bind('inproc://foo')
self.assertEqual(pub.getsockopt(nnpy.SOL_SOCKET, nnpy... | Add some more test coverage
from __future__ import print_function
import nnpy, unittest
class Tests(unittest.TestCase):
def test_basic(self):
pub = nnpy.Socket(nnpy.AF_SP, nnpy.PUB)
pub.bind('inproc://foo')
self.assertEqual(pub.getsockopt(nnpy.SOL_SOCKET, nnpy.DOMAIN), 1)
sub = n... |
eac2211956d49d9da957492bbac1bcdc85b1e40d | openprescribing/frontend/management/commands/load_development_data.py | openprescribing/frontend/management/commands/load_development_data.py | from django.core.management import call_command
from django.core.management.base import BaseCommand
from frontend.tests.test_api_spending import TestAPISpendingViewsPPUTable
class Command(BaseCommand):
help = 'Loads sample data intended for use in local development'
def handle(self, *args, **options):
... | from django.core.management import call_command
from django.core.management.base import BaseCommand
from frontend.models import ImportLog, PPUSaving
from frontend.tests.test_api_spending import ApiTestBase, TestAPISpendingViewsPPUTable
class Command(BaseCommand):
help = 'Loads sample data intended for use in lo... | Add extra development data so the All England page loads | Add extra development data so the All England page loads
Previously the absence of the PPU ImportLog entry caused the page to
throw an error.
| Python | mit | ebmdatalab/openprescribing,annapowellsmith/openpresc,ebmdatalab/openprescribing,ebmdatalab/openprescribing,annapowellsmith/openpresc,annapowellsmith/openpresc,annapowellsmith/openpresc,ebmdatalab/openprescribing | from django.core.management import call_command
from django.core.management.base import BaseCommand
from frontend.models import ImportLog, PPUSaving
from frontend.tests.test_api_spending import ApiTestBase, TestAPISpendingViewsPPUTable
class Command(BaseCommand):
help = 'Loads sample data intended for use in lo... | Add extra development data so the All England page loads
Previously the absence of the PPU ImportLog entry caused the page to
throw an error.
from django.core.management import call_command
from django.core.management.base import BaseCommand
from frontend.tests.test_api_spending import TestAPISpendingViewsPPUTable
... |
ab094c32b1bcea2978796d6118bf43365571f2b7 | stacker_blueprints/security_rules.py | stacker_blueprints/security_rules.py | from troposphere.ec2 import SecurityGroupIngress, SecurityGroupEgress
from stacker.blueprints.base import Blueprint
CLASS_MAP = {
"IngressRules": SecurityGroupIngress,
"EgressRules": SecurityGroupEgress,
}
class SecurityGroupRules(Blueprint):
"""Used to add Ingress/Egress rules to existing security group... | Add new, low-level security group rule blueprint | Add new, low-level security group rule blueprint
This should make it super simple to have a stack that
maintains security group rules on security groups built in other
stacks. Mostly useful for rules that glue two stacks together
(like adding a rule to allow instances in your webserver stack to
talk to your RDS databa... | Python | bsd-2-clause | remind101/stacker_blueprints,remind101/stacker_blueprints | from troposphere.ec2 import SecurityGroupIngress, SecurityGroupEgress
from stacker.blueprints.base import Blueprint
CLASS_MAP = {
"IngressRules": SecurityGroupIngress,
"EgressRules": SecurityGroupEgress,
}
class SecurityGroupRules(Blueprint):
"""Used to add Ingress/Egress rules to existing security group... | Add new, low-level security group rule blueprint
This should make it super simple to have a stack that
maintains security group rules on security groups built in other
stacks. Mostly useful for rules that glue two stacks together
(like adding a rule to allow instances in your webserver stack to
talk to your RDS databa... | |
c06d4ddc54bbe4b10dd0722f5a76d9cb7550da53 | tests/test_config.py | tests/test_config.py | from pytest import fixture
from oshino.config import Config, RiemannConfig
@fixture
def base_config():
return Config({"riemann": {"host": "localhost",
"port": 5555
},
"interval": 5
})
def test_base_config_get_ri... | from pytest import fixture
from oshino.config import Config, RiemannConfig
@fixture
def base_config():
return Config({"riemann": {"host": "localhost",
"port": 5555
},
"interval": 5
})
@fixture
def incomplete_con... | Test case when there's no riemann config | Test case when there's no riemann config
| Python | mit | CodersOfTheNight/oshino | from pytest import fixture
from oshino.config import Config, RiemannConfig
@fixture
def base_config():
return Config({"riemann": {"host": "localhost",
"port": 5555
},
"interval": 5
})
@fixture
def incomplete_con... | Test case when there's no riemann config
from pytest import fixture
from oshino.config import Config, RiemannConfig
@fixture
def base_config():
return Config({"riemann": {"host": "localhost",
"port": 5555
},
"interval": 5
... |
4f577eabc45acb6e9a8880d062daa225cc76d64c | logparser/logs/micro/micro.py | logparser/logs/micro/micro.py | # Log Parser for RTI Connext.
#
# Copyright 2016 Real-Time Innovations, 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
#
# ... | # Log Parser for RTI Connext.
#
# Copyright 2016 Real-Time Innovations, 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
#
# ... | Check if module and error code exist | Check if module and error code exist
| Python | apache-2.0 | rticommunity/rticonnextdds-logparser,rticommunity/rticonnextdds-logparser | # Log Parser for RTI Connext.
#
# Copyright 2016 Real-Time Innovations, 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
#
# ... | Check if module and error code exist
# Log Parser for RTI Connext.
#
# Copyright 2016 Real-Time Innovations, 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... |
0bcecfdf33f42f85bb9a8e32e79686a41fb5226a | django_validator/exceptions.py | django_validator/exceptions.py | from rest_framework import status
import rest_framework.exceptions
class ValidationError(rest_framework.exceptions.ValidationError):
code = ''
def __init__(self, detail, code=None, status_code=status.HTTP_400_BAD_REQUEST):
super(ValidationError, self).__init__(detail)
self.status_code = statu... | from rest_framework import status
import rest_framework.exceptions
class ValidationError(rest_framework.exceptions.APIException):
code = ''
def __init__(self, detail, code=None, status_code=status.HTTP_400_BAD_REQUEST):
super(ValidationError, self).__init__(detail)
self.code = code
se... | Fix Validation import error in older DRF. | Fix Validation import error in older DRF.
| Python | mit | romain-li/django-validator,romain-li/django-validator | from rest_framework import status
import rest_framework.exceptions
class ValidationError(rest_framework.exceptions.APIException):
code = ''
def __init__(self, detail, code=None, status_code=status.HTTP_400_BAD_REQUEST):
super(ValidationError, self).__init__(detail)
self.code = code
se... | Fix Validation import error in older DRF.
from rest_framework import status
import rest_framework.exceptions
class ValidationError(rest_framework.exceptions.ValidationError):
code = ''
def __init__(self, detail, code=None, status_code=status.HTTP_400_BAD_REQUEST):
super(ValidationError, self).__init... |
42851304fecec95c32eebd618aae192743aab5d4 | src/ggrc_risk_assessment_v2/migrations/versions/20141121231826_1347acbb4dc2_add_unique_constraint_to_threat_actors.py | src/ggrc_risk_assessment_v2/migrations/versions/20141121231826_1347acbb4dc2_add_unique_constraint_to_threat_actors.py |
"""Add unique constraint to threat actors
Revision ID: 1347acbb4dc2
Revises: 5ada65dc60b3
Create Date: 2014-11-21 23:18:26.689048
"""
# revision identifiers, used by Alembic.
revision = '1347acbb4dc2'
down_revision = '5ada65dc60b3'
from alembic import op
def upgrade():
op.create_unique_constraint('uq_t_actors'... | Add unique constraint on Threat Actor title | Add unique constraint on Threat Actor title
| Python | apache-2.0 | prasannav7/ggrc-core,kr41/ggrc-core,andrei-karalionak/ggrc-core,NejcZupec/ggrc-core,plamut/ggrc-core,VinnieJohns/ggrc-core,j0gurt/ggrc-core,prasannav7/ggrc-core,selahssea/ggrc-core,hyperNURb/ggrc-core,VinnieJohns/ggrc-core,VinnieJohns/ggrc-core,plamut/ggrc-core,kr41/ggrc-core,AleksNeStu/ggrc-core,hasanalom/ggrc-core,j0... |
"""Add unique constraint to threat actors
Revision ID: 1347acbb4dc2
Revises: 5ada65dc60b3
Create Date: 2014-11-21 23:18:26.689048
"""
# revision identifiers, used by Alembic.
revision = '1347acbb4dc2'
down_revision = '5ada65dc60b3'
from alembic import op
def upgrade():
op.create_unique_constraint('uq_t_actors'... | Add unique constraint on Threat Actor title
| |
ce0f4a30cad570557ad67122333041806d411adc | tasks.py | tasks.py | from invoke import Collection
from invocations import docs
from invocations.checks import blacken
from invocations.packaging import release
from invocations.pytest import test, coverage
ns = Collection(test, coverage, release, blacken, docs)
ns.configure({"packaging": {"sign": True}})
| from invoke import Collection
from invocations import docs
from invocations.checks import blacken
from invocations.packaging import release
from invocations.pytest import test, coverage
ns = Collection(test, coverage, release, blacken, docs)
ns.configure(
{"packaging": {"sign": True, "changelog_file": "docs/chang... | Set changelog_file for invocations release task, which now dry-runs ok | Set changelog_file for invocations release task, which now dry-runs ok
| Python | bsd-2-clause | bitprophet/lexicon | from invoke import Collection
from invocations import docs
from invocations.checks import blacken
from invocations.packaging import release
from invocations.pytest import test, coverage
ns = Collection(test, coverage, release, blacken, docs)
ns.configure(
{"packaging": {"sign": True, "changelog_file": "docs/chang... | Set changelog_file for invocations release task, which now dry-runs ok
from invoke import Collection
from invocations import docs
from invocations.checks import blacken
from invocations.packaging import release
from invocations.pytest import test, coverage
ns = Collection(test, coverage, release, blacken, docs)
ns.c... |
dec17e4d8eb88610fbe81aeef84ea41b76b0e398 | ListItems.py | ListItems.py | import os
import json
import re
###############################################
# Run this from the root of the assets folder #
###############################################
# Some code from http://www.lifl.fr/~riquetd/parse-a-json-file-with-comments.html
# "Parse a JSON file with comments"
comment_re = re.compile... | Add a python script to list all items | Add a python script to list all items
Saves the item name, item path, and image path into "items.json"
| Python | mit | McSimp/starbound-research | import os
import json
import re
###############################################
# Run this from the root of the assets folder #
###############################################
# Some code from http://www.lifl.fr/~riquetd/parse-a-json-file-with-comments.html
# "Parse a JSON file with comments"
comment_re = re.compile... | Add a python script to list all items
Saves the item name, item path, and image path into "items.json"
| |
51466e360320267afab41704caecebac0dff1dc2 | src/example/bench_wsh.py | src/example/bench_wsh.py | # Copyright 2011, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the f... | Add a handler for performing client load testing. | Add a handler for performing client load testing.
Review URL: http://codereview.appspot.com/3844044
git-svn-id: a751b5b3dcfba0ee4592a85c40d2fdd063ca0d53@379 4ff78f4a-9131-11de-b045-6380ec9940d4
| Python | bsd-3-clause | XiaonuoGantan/pywebsocket,XiaonuoGantan/pywebsocket | # Copyright 2011, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the f... | Add a handler for performing client load testing.
Review URL: http://codereview.appspot.com/3844044
git-svn-id: a751b5b3dcfba0ee4592a85c40d2fdd063ca0d53@379 4ff78f4a-9131-11de-b045-6380ec9940d4
| |
87707340ac82f852937dae546380b5d5327f5bc7 | txlege84/core/views.py | txlege84/core/views.py | from django.views.generic import ListView
from bills.mixins import AllSubjectsMixin
from core.mixins import ConveneTimeMixin
from legislators.mixins import AllLegislatorsMixin, ChambersMixin
from explainers.models import Explainer
from topics.models import Topic
class LandingView(AllSubjectsMixin, AllLegislatorsMix... | from django.views.generic import ListView
from core.mixins import ConveneTimeMixin
from explainers.models import Explainer
from topics.models import Topic
class LandingView(ConveneTimeMixin, ListView):
model = Topic
template_name = 'landing.html'
def get_context_data(self, **kwargs):
context = ... | Remove unneeded mixins from LandingView | Remove unneeded mixins from LandingView
| Python | mit | texastribune/txlege84,texastribune/txlege84,texastribune/txlege84,texastribune/txlege84 | from django.views.generic import ListView
from core.mixins import ConveneTimeMixin
from explainers.models import Explainer
from topics.models import Topic
class LandingView(ConveneTimeMixin, ListView):
model = Topic
template_name = 'landing.html'
def get_context_data(self, **kwargs):
context = ... | Remove unneeded mixins from LandingView
from django.views.generic import ListView
from bills.mixins import AllSubjectsMixin
from core.mixins import ConveneTimeMixin
from legislators.mixins import AllLegislatorsMixin, ChambersMixin
from explainers.models import Explainer
from topics.models import Topic
class Landin... |
3736d7fb32e20a64591f949d6ff431430447d421 | stock.py | stock.py | class Stock:
def __init__(self, symbol):
self.symbol = symbol
self.price_history = []
@property
def price(self):
return self.price_history[-1] if self.price_history else None
def update(self, timestamp, price):
if price < 0:
raise ValueError("price should no... | import bisect
import collections
PriceEvent = collections.namedtuple("PriceEvent", ["timestamp", "price"])
class Stock:
def __init__(self, symbol):
self.symbol = symbol
self.price_history = []
@property
def price(self):
return self.price_history[-1].price if self.price_history el... | Add a named tuple PriceEvent sub class and update methods accordingly. | Add a named tuple PriceEvent sub class and update methods accordingly.
| Python | mit | bsmukasa/stock_alerter | import bisect
import collections
PriceEvent = collections.namedtuple("PriceEvent", ["timestamp", "price"])
class Stock:
def __init__(self, symbol):
self.symbol = symbol
self.price_history = []
@property
def price(self):
return self.price_history[-1].price if self.price_history el... | Add a named tuple PriceEvent sub class and update methods accordingly.
class Stock:
def __init__(self, symbol):
self.symbol = symbol
self.price_history = []
@property
def price(self):
return self.price_history[-1] if self.price_history else None
def update(self, timestamp, pri... |
110c362e3e8436700707c2306d115b3b2476a79d | core/models.py | core/models.py |
from os import makedirs
from os.path import join, exists
from urllib import urlretrieve
from django.conf import settings
from social_auth.signals import socialauth_registered
def create_profile(sender, user, response, details, **kwargs):
try:
# twitter
photo_url = response["profile_image_url"]
... |
from os import makedirs
from os.path import join, exists
from urllib import urlretrieve
from django.conf import settings
from django.contrib.auth.models import User
from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver
from social_auth.signals import socialau... | Add initial account balance for users. | Add initial account balance for users.
| Python | bsd-2-clause | stephenmcd/gamblor,stephenmcd/gamblor |
from os import makedirs
from os.path import join, exists
from urllib import urlretrieve
from django.conf import settings
from django.contrib.auth.models import User
from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver
from social_auth.signals import socialau... | Add initial account balance for users.
from os import makedirs
from os.path import join, exists
from urllib import urlretrieve
from django.conf import settings
from social_auth.signals import socialauth_registered
def create_profile(sender, user, response, details, **kwargs):
try:
# twitter
pho... |
37f137003d1b6e9f7361db38e0de109e0327fc42 | setup.py | setup.py | from setuptools import setup, find_packages
__version__ = "0.0.1"
description = "A buildout recipe to create .deb packages"
setup(
name='vdt.recipe.debian',
version=__version__,
description=description,
long_description=description,
classifiers=[
"Framework :: Buildout",
"Program... | from setuptools import setup, find_packages
__version__ = "0.0.1"
description = "A buildout recipe to create .deb packages"
setup(
name='vdt.recipe.debian',
version=__version__,
description=description,
long_description=description,
classifiers=[
"Framework :: Buildout",
"Program... | Remove dependency as plugin is configurable | Remove dependency as plugin is configurable
| Python | bsd-3-clause | devopsconsulting/vdt.recipe.version | from setuptools import setup, find_packages
__version__ = "0.0.1"
description = "A buildout recipe to create .deb packages"
setup(
name='vdt.recipe.debian',
version=__version__,
description=description,
long_description=description,
classifiers=[
"Framework :: Buildout",
"Program... | Remove dependency as plugin is configurable
from setuptools import setup, find_packages
__version__ = "0.0.1"
description = "A buildout recipe to create .deb packages"
setup(
name='vdt.recipe.debian',
version=__version__,
description=description,
long_description=description,
classifiers=[
... |
ddae9e02ab2bc9099fcb215ba5803210767f72a5 | common/lib/xmodule/xmodule/edxnotes_utils.py | common/lib/xmodule/xmodule/edxnotes_utils.py | """
Utilities related to edXNotes.
"""
import sys
def edxnotes(cls):
"""
Conditional decorator that loads edxnotes only when they exist.
"""
if "edxnotes" in sys.modules:
from edxnotes.decorators import edxnotes as notes
return notes(cls)
else:
return cls
| """
Utilities related to edXNotes.
"""
import sys
def edxnotes(cls):
"""
Conditional decorator that loads edxnotes only when they exist.
"""
if "lms.djangoapps.edxnotes" in sys.modules:
from lms.djangoapps.edxnotes.decorators import edxnotes as notes
return notes(cls)
else:
... | Use fully-qualified edxnotes app name when checking if installed | Use fully-qualified edxnotes app name when checking if installed
| Python | agpl-3.0 | angelapper/edx-platform,stvstnfrd/edx-platform,arbrandes/edx-platform,arbrandes/edx-platform,edx/edx-platform,eduNEXT/edunext-platform,EDUlib/edx-platform,EDUlib/edx-platform,angelapper/edx-platform,edx/edx-platform,eduNEXT/edx-platform,angelapper/edx-platform,EDUlib/edx-platform,edx/edx-platform,stvstnfrd/edx-platform... | """
Utilities related to edXNotes.
"""
import sys
def edxnotes(cls):
"""
Conditional decorator that loads edxnotes only when they exist.
"""
if "lms.djangoapps.edxnotes" in sys.modules:
from lms.djangoapps.edxnotes.decorators import edxnotes as notes
return notes(cls)
else:
... | Use fully-qualified edxnotes app name when checking if installed
"""
Utilities related to edXNotes.
"""
import sys
def edxnotes(cls):
"""
Conditional decorator that loads edxnotes only when they exist.
"""
if "edxnotes" in sys.modules:
from edxnotes.decorators import edxnotes as notes
... |
1c2ade08262259bb952424d7605d5fc68e038d73 | scripts/generate_labos_aggrega.py | scripts/generate_labos_aggrega.py | #!/usr/bin/env python
from csv import reader
with open("data/public/labos.departements.csv") as f:
data = list(reader(f))
output = {}
keys = data.pop(0)
keys.remove("LABO")
keys.remove("DEPARTEMENT")
for row in data:
if not row[0]:
continue
if row[0] not in output:
output[row[0]] = dict({... | #!/usr/bin/env python
from csv import reader
with open("data/public/labos.departements.csv") as f:
data = list(reader(f))
output = {}
keys = data.pop(0)
keys.remove("LABO")
keys.remove("DEPARTEMENT")
for row in data:
if not row[0]:
continue
if row[0] not in output:
output[row[0]] = dict({... | Make aggregation script compatible with python 3 | Make aggregation script compatible with python 3
| Python | agpl-3.0 | regardscitoyens/sunshine-data,regardscitoyens/sunshine-data,regardscitoyens/sunshine-data,regardscitoyens/sunshine-data,regardscitoyens/sunshine-data,regardscitoyens/sunshine-data | #!/usr/bin/env python
from csv import reader
with open("data/public/labos.departements.csv") as f:
data = list(reader(f))
output = {}
keys = data.pop(0)
keys.remove("LABO")
keys.remove("DEPARTEMENT")
for row in data:
if not row[0]:
continue
if row[0] not in output:
output[row[0]] = dict({... | Make aggregation script compatible with python 3
#!/usr/bin/env python
from csv import reader
with open("data/public/labos.departements.csv") as f:
data = list(reader(f))
output = {}
keys = data.pop(0)
keys.remove("LABO")
keys.remove("DEPARTEMENT")
for row in data:
if not row[0]:
continue
if row... |
2544eab8770577b3dfe3ae4559965393eab69a45 | python/tag_img.py | python/tag_img.py | import requests
import json
# Tag an image based on detected visual content which mean running a CNN on top of it.
# https://pixlab.io/#/cmd?id=tagimg for more info.
# Target Image: Change to any link or switch to POST if you want to upload your image directly, refer to the sample set for more info.
img = 'https://s-... | Tag an image based on detected visual content which mean running a CNN on top of it. | Tag an image based on detected visual content which mean running a CNN on top of it. | Python | bsd-2-clause | symisc/pixlab,symisc/pixlab,symisc/pixlab | import requests
import json
# Tag an image based on detected visual content which mean running a CNN on top of it.
# https://pixlab.io/#/cmd?id=tagimg for more info.
# Target Image: Change to any link or switch to POST if you want to upload your image directly, refer to the sample set for more info.
img = 'https://s-... | Tag an image based on detected visual content which mean running a CNN on top of it.
| |
b0e614ea7ac59b6b869155b9ac8ea370cb56f83d | cardinal/decorators.py | cardinal/decorators.py | import functools
def command(triggers):
def wrap(f):
@functools.wraps(f)
def inner(*args, **kwargs):
return f(*args, **kwargs)
inner.commands = triggers
return inner
return wrap
def help(line):
def wrap(f):
@functools.wraps(f)
def inner(*args, ... | import functools
def command(triggers):
if isinstance(triggers, basestring):
triggers = [triggers]
def wrap(f):
@functools.wraps(f)
def inner(*args, **kwargs):
return f(*args, **kwargs)
inner.commands = triggers
return inner
return wrap
def help(line)... | Allow for single trigger in @command decorator | Allow for single trigger in @command decorator
| Python | mit | BiohZn/Cardinal,JohnMaguire/Cardinal | import functools
def command(triggers):
if isinstance(triggers, basestring):
triggers = [triggers]
def wrap(f):
@functools.wraps(f)
def inner(*args, **kwargs):
return f(*args, **kwargs)
inner.commands = triggers
return inner
return wrap
def help(line)... | Allow for single trigger in @command decorator
import functools
def command(triggers):
def wrap(f):
@functools.wraps(f)
def inner(*args, **kwargs):
return f(*args, **kwargs)
inner.commands = triggers
return inner
return wrap
def help(line):
def wrap(f):
... |
dfd6e69b0a6202ed562360201e123e40c7aa1cc9 | bin/template.py | bin/template.py | #! /usr/bin/env python
import jinja2
import sys
import re
import os
KEY_REGEX = re.compile('([A-Z]+)=(\w+)')
def main():
args = sys.argv[1:]
if len(args) < 1:
raise Exception('args too short {}'.format(args))
template_file = args[0]
keyword_args = args[1:]
if not os.path.exists(templat... | #! /usr/bin/env python
import jinja2
import sys
import re
import os
KEY_REGEX = re.compile('([A-Z]+)=(.+)')
def main():
args = sys.argv[1:]
if len(args) < 1:
raise Exception('args too short {}'.format(args))
template_file = args[0]
keyword_args = args[1:]
if not os.path.exists(template... | Fix the regex so that it catches all characters to the right of the equals-sign. | Fix the regex so that it catches all characters to the right of the equals-sign.
| Python | mit | BedquiltDB/bedquilt-core | #! /usr/bin/env python
import jinja2
import sys
import re
import os
KEY_REGEX = re.compile('([A-Z]+)=(.+)')
def main():
args = sys.argv[1:]
if len(args) < 1:
raise Exception('args too short {}'.format(args))
template_file = args[0]
keyword_args = args[1:]
if not os.path.exists(template... | Fix the regex so that it catches all characters to the right of the equals-sign.
#! /usr/bin/env python
import jinja2
import sys
import re
import os
KEY_REGEX = re.compile('([A-Z]+)=(\w+)')
def main():
args = sys.argv[1:]
if len(args) < 1:
raise Exception('args too short {}'.format(args))
temp... |
9937823496db32a4d3eac3eee0fa4d310ea07e11 | dvhb_hybrid/files/models.py | dvhb_hybrid/files/models.py | import uuid
from django.conf import settings
from django.contrib.postgres.fields import JSONField
from django.db import models
from django.utils.translation import ugettext_lazy as _
from ..models import UpdatedMixin
from .storages import image_storage
class Image(UpdatedMixin, models.Model):
author = models.Fo... | import uuid
from django.conf import settings
from django.contrib.postgres.fields import JSONField
from django.contrib.postgres.indexes import GinIndex
from django.db import models
from django.utils.translation import ugettext_lazy as _
from ..models import UpdatedMixin
from .storages import image_storage
class Imag... | Add index for image metainformation | Add index for image metainformation
| Python | mit | dvhbru/dvhb-hybrid | import uuid
from django.conf import settings
from django.contrib.postgres.fields import JSONField
from django.contrib.postgres.indexes import GinIndex
from django.db import models
from django.utils.translation import ugettext_lazy as _
from ..models import UpdatedMixin
from .storages import image_storage
class Imag... | Add index for image metainformation
import uuid
from django.conf import settings
from django.contrib.postgres.fields import JSONField
from django.db import models
from django.utils.translation import ugettext_lazy as _
from ..models import UpdatedMixin
from .storages import image_storage
class Image(UpdatedMixin, ... |
427931c5c8847d01e4ce563a9c605a78eceb39f3 | amplpy/amplpython/__init__.py | amplpy/amplpython/__init__.py | # -*- coding: utf-8 -*-
import os
import sys
import ctypes
import platform
if platform.system() == 'Windows':
libbase = os.path.join(os.path.dirname(__file__), 'cppinterface', 'lib')
lib32 = os.path.join(libbase, 'intel32')
lib64 = os.path.join(libbase, 'amd64')
from glob import glob
try:
i... | # -*- coding: utf-8 -*-
import os
import sys
import ctypes
import platform
if platform.system().startswith(('Windows', 'MSYS', 'CYGWIN', 'MINGW')):
libbase = os.path.join(os.path.dirname(__file__), 'cppinterface', 'lib')
lib32 = os.path.join(libbase, 'intel32')
lib64 = os.path.join(libbase, 'amd64')
fr... | Add basic support for MSYS, CYGWIN, and MINGW | Add basic support for MSYS, CYGWIN, and MINGW
| Python | bsd-3-clause | ampl/amplpy,ampl/amplpy,ampl/amplpy | # -*- coding: utf-8 -*-
import os
import sys
import ctypes
import platform
if platform.system().startswith(('Windows', 'MSYS', 'CYGWIN', 'MINGW')):
libbase = os.path.join(os.path.dirname(__file__), 'cppinterface', 'lib')
lib32 = os.path.join(libbase, 'intel32')
lib64 = os.path.join(libbase, 'amd64')
fr... | Add basic support for MSYS, CYGWIN, and MINGW
# -*- coding: utf-8 -*-
import os
import sys
import ctypes
import platform
if platform.system() == 'Windows':
libbase = os.path.join(os.path.dirname(__file__), 'cppinterface', 'lib')
lib32 = os.path.join(libbase, 'intel32')
lib64 = os.path.join(libbase, 'amd64... |
0749c47bb280230ae5b1e2cda23773d3b10b2491 | redis_check.py | redis_check.py | #!/usr/bin/env python3
import sys
import redis
import redis.exceptions
host = sys.argv[1]
host = host.strip('\r\n')
port = 6379
timeout = 5
try:
db = redis.StrictRedis(host=host, port=port, socket_timeout=timeout)
i = db.info()
ver = i.get('redis_version')
siz = db.dbsize()
print('[+] {0}:{1}... | #!/usr/bin/env python3
import sys
import redis
import redis.exceptions
host = sys.argv[1]
host = host.strip('\r\n')
port = 6379
timeout = 5
try:
db = redis.StrictRedis(host=host, port=port, socket_timeout=timeout)
i = db.info()
ver = i.get('redis_version')
siz = db.dbsize()
print('[+] {0}:{1}... | Make output easier to parse with cli tools. | Make output easier to parse with cli tools.
| Python | bsd-3-clause | averagesecurityguy/research | #!/usr/bin/env python3
import sys
import redis
import redis.exceptions
host = sys.argv[1]
host = host.strip('\r\n')
port = 6379
timeout = 5
try:
db = redis.StrictRedis(host=host, port=port, socket_timeout=timeout)
i = db.info()
ver = i.get('redis_version')
siz = db.dbsize()
print('[+] {0}:{1}... | Make output easier to parse with cli tools.
#!/usr/bin/env python3
import sys
import redis
import redis.exceptions
host = sys.argv[1]
host = host.strip('\r\n')
port = 6379
timeout = 5
try:
db = redis.StrictRedis(host=host, port=port, socket_timeout=timeout)
i = db.info()
ver = i.get('redis_version')
... |
83f84b9ebc9309e8aadd2668ad2f6a49383b8199 | setup.py | setup.py | from setuptools import find_packages, setup
setup(
name="ebisearch",
version="0.0.1",
author="Berenice Batut",
author_email="berenice.batut@gmail.com",
description=("A Python library for interacting with EBI Search's API"),
license="MIT",
keywords="api api-client ebi",
url="https://gith... | from setuptools import find_packages, setup
setup(
name="ebisearch",
version="0.0.1",
author="Berenice Batut",
author_email="berenice.batut@gmail.com",
description=("A Python library for interacting with EBI Search's API"),
license="MIT",
keywords="api api-client ebi",
url="https://gith... | Add ebi_metagenomics as package script | Add ebi_metagenomics as package script
| Python | mit | bebatut/ebisearch | from setuptools import find_packages, setup
setup(
name="ebisearch",
version="0.0.1",
author="Berenice Batut",
author_email="berenice.batut@gmail.com",
description=("A Python library for interacting with EBI Search's API"),
license="MIT",
keywords="api api-client ebi",
url="https://gith... | Add ebi_metagenomics as package script
from setuptools import find_packages, setup
setup(
name="ebisearch",
version="0.0.1",
author="Berenice Batut",
author_email="berenice.batut@gmail.com",
description=("A Python library for interacting with EBI Search's API"),
license="MIT",
keywords="ap... |
20d21b851d02bbcf8c6a0f065b9f05f5e0bfc662 | geodj/youtube.py | geodj/youtube.py | from gdata.youtube.service import YouTubeService, YouTubeVideoQuery
from django.utils.encoding import smart_str
import re
class YoutubeMusic:
def __init__(self):
self.service = YouTubeService()
def search(self, artist):
query = YouTubeVideoQuery()
query.vq = artist
query.orderb... | from gdata.youtube.service import YouTubeService, YouTubeVideoQuery
from django.utils.encoding import smart_str
import re
class YoutubeMusic:
def __init__(self):
self.service = YouTubeService()
def search(self, artist):
query = YouTubeVideoQuery()
query.vq = artist
query.orderb... | Use format=5 in YT search to prevent "embedding disabled" | Use format=5 in YT search to prevent "embedding disabled"
| Python | mit | 6/GeoDJ,6/GeoDJ | from gdata.youtube.service import YouTubeService, YouTubeVideoQuery
from django.utils.encoding import smart_str
import re
class YoutubeMusic:
def __init__(self):
self.service = YouTubeService()
def search(self, artist):
query = YouTubeVideoQuery()
query.vq = artist
query.orderb... | Use format=5 in YT search to prevent "embedding disabled"
from gdata.youtube.service import YouTubeService, YouTubeVideoQuery
from django.utils.encoding import smart_str
import re
class YoutubeMusic:
def __init__(self):
self.service = YouTubeService()
def search(self, artist):
query = YouTube... |
3f5149841163ab3e79fbd69990e53791281ec4a6 | opps/articles/templatetags/article_tags.py | opps/articles/templatetags/article_tags.py | # -*- coding: utf-8 -*-
from django import template
from django.conf import settings
from django.utils import timezone
from opps.articles.models import ArticleBox
register = template.Library()
@register.simple_tag
def get_articlebox(slug, channel_slug=None, template_name=None):
if channel_slug:
slug = s... | # -*- coding: utf-8 -*-
from django import template
from django.conf import settings
from django.utils import timezone
from opps.articles.models import ArticleBox
register = template.Library()
@register.simple_tag
def get_articlebox(slug, channel_slug=None, template_name=None):
if channel_slug:
slug = s... | Add validate published on templatetag get all articlebox | Add validate published on templatetag get all articlebox
| Python | mit | jeanmask/opps,opps/opps,jeanmask/opps,jeanmask/opps,williamroot/opps,YACOWS/opps,YACOWS/opps,opps/opps,opps/opps,opps/opps,jeanmask/opps,YACOWS/opps,williamroot/opps,YACOWS/opps,williamroot/opps,williamroot/opps | # -*- coding: utf-8 -*-
from django import template
from django.conf import settings
from django.utils import timezone
from opps.articles.models import ArticleBox
register = template.Library()
@register.simple_tag
def get_articlebox(slug, channel_slug=None, template_name=None):
if channel_slug:
slug = s... | Add validate published on templatetag get all articlebox
# -*- coding: utf-8 -*-
from django import template
from django.conf import settings
from django.utils import timezone
from opps.articles.models import ArticleBox
register = template.Library()
@register.simple_tag
def get_articlebox(slug, channel_slug=None, ... |
7b3276708417284242b4e0c9a13c6194dcc83aa7 | quickstartup/contacts/views.py | quickstartup/contacts/views.py | # coding: utf-8
from django.core.urlresolvers import reverse
from django.views.generic import CreateView
from django.utils.translation import ugettext_lazy as _
from django.contrib import messages
from .forms import ContactForm
class ContactView(CreateView):
template_name = 'contacts/contact.html'
form_cla... | # coding: utf-8
from django.core.urlresolvers import reverse
from django.views.generic import CreateView
from django.utils.translation import ugettext_lazy as _
from django.contrib import messages
from .forms import ContactForm
class ContactView(CreateView):
template_name = 'contacts/contact.html'
form_cla... | Set flash message *after* message sending | Set flash message *after* message sending
| Python | mit | georgeyk/quickstartup,georgeyk/quickstartup,osantana/quickstartup,osantana/quickstartup,osantana/quickstartup,georgeyk/quickstartup | # coding: utf-8
from django.core.urlresolvers import reverse
from django.views.generic import CreateView
from django.utils.translation import ugettext_lazy as _
from django.contrib import messages
from .forms import ContactForm
class ContactView(CreateView):
template_name = 'contacts/contact.html'
form_cla... | Set flash message *after* message sending
# coding: utf-8
from django.core.urlresolvers import reverse
from django.views.generic import CreateView
from django.utils.translation import ugettext_lazy as _
from django.contrib import messages
from .forms import ContactForm
class ContactView(CreateView):
template_... |
1cdb773f0d20dcdb1a66a4a6a52eff35398b1296 | getBlocks.py | getBlocks.py | #!/usr/bin/python
import subprocess
import argparse
def readArguments():
parser = argparse.ArgumentParser()
parser.add_argument('-f','--file', action="store", dest="file", required=True, help="File to shred")
args = parser.parse_args()
return args
def checkFile(file):
'''
Check if file exist in HDFS
''... | #!/usr/bin/python
import subprocess
import shlex
import argparse
def readArguments():
parser = argparse.ArgumentParser()
parser.add_argument('-f','--file', action="store", dest="file", required=True, help="File to shred")
args = parser.parse_args()
return args
def checkFile(file):
'''
Check if file exist... | Use shlex to split command line | Use shlex to split command line
| Python | apache-2.0 | monolive/hdfs-shred | #!/usr/bin/python
import subprocess
import shlex
import argparse
def readArguments():
parser = argparse.ArgumentParser()
parser.add_argument('-f','--file', action="store", dest="file", required=True, help="File to shred")
args = parser.parse_args()
return args
def checkFile(file):
'''
Check if file exist... | Use shlex to split command line
#!/usr/bin/python
import subprocess
import argparse
def readArguments():
parser = argparse.ArgumentParser()
parser.add_argument('-f','--file', action="store", dest="file", required=True, help="File to shred")
args = parser.parse_args()
return args
def checkFile(file):
'''
... |
042844d918d34a16f18ea9ab2c09694e81c25623 | bluebottle/categories/migrations/0008_authenticated-permissions.py | bluebottle/categories/migrations/0008_authenticated-permissions.py | # -*- coding: utf-8 -*-
# Generated by Django 1.10.8 on 2019-02-22 08:58
from __future__ import unicode_literals
from django.db import migrations
from bluebottle.utils.utils import update_group_permissions
def add_group_permissions(apps, schema_editor):
group_perms = {
'Authenticated': {
'pe... | Add read categories permission to authenticated users | Add read categories permission to authenticated users
| Python | bsd-3-clause | onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle | # -*- coding: utf-8 -*-
# Generated by Django 1.10.8 on 2019-02-22 08:58
from __future__ import unicode_literals
from django.db import migrations
from bluebottle.utils.utils import update_group_permissions
def add_group_permissions(apps, schema_editor):
group_perms = {
'Authenticated': {
'pe... | Add read categories permission to authenticated users
| |
6424d1998d10d4d5e1165e7c530d414e86e1067b | tests/example_project/tests/test_newman/helpers.py | tests/example_project/tests/test_newman/helpers.py | from djangosanetesting import SeleniumTestCase
class NewmanTestCase(SeleniumTestCase):
fixtures = ['newman_admin_user']
SUPERUSER_USERNAME = u"superman"
SUPERUSER_PASSWORD = u"xxx"
NEWMAN_URI = "/newman/"
def __init__(self):
super(NewmanTestCase, self).__init__()
self.elements = ... | from djangosanetesting import SeleniumTestCase
class NewmanTestCase(SeleniumTestCase):
fixtures = ['newman_admin_user']
SUPERUSER_USERNAME = u"superman"
SUPERUSER_PASSWORD = u"xxx"
NEWMAN_URI = "/newman/"
def __init__(self):
super(NewmanTestCase, self).__init__()
self.elements = ... | Use class for logout instead of href, to please IE8 | Use class for logout instead of href, to please IE8
| Python | bsd-3-clause | WhiskeyMedia/ella,MichalMaM/ella,petrlosa/ella,petrlosa/ella,WhiskeyMedia/ella,ella/ella,whalerock/ella,MichalMaM/ella,whalerock/ella,whalerock/ella | from djangosanetesting import SeleniumTestCase
class NewmanTestCase(SeleniumTestCase):
fixtures = ['newman_admin_user']
SUPERUSER_USERNAME = u"superman"
SUPERUSER_PASSWORD = u"xxx"
NEWMAN_URI = "/newman/"
def __init__(self):
super(NewmanTestCase, self).__init__()
self.elements = ... | Use class for logout instead of href, to please IE8
from djangosanetesting import SeleniumTestCase
class NewmanTestCase(SeleniumTestCase):
fixtures = ['newman_admin_user']
SUPERUSER_USERNAME = u"superman"
SUPERUSER_PASSWORD = u"xxx"
NEWMAN_URI = "/newman/"
def __init__(self):
super(Newm... |
9756366d7bca75c0ea89ce1fface6a7d224f54f7 | web/api/__init__.py | web/api/__init__.py | from flask import Blueprint
from . import v0
bp = Blueprint('api', __name__)
v0.api.init_app(bp)
def errorpage(e):
code = getattr(e, 'code', 500)
if code == 404:
return jsonify(msg=str(e))
return jsonify(msg="error", code=code)
| from flask import Blueprint
from . import v0
bp = Blueprint('api', __name__)
v0.api.init_app(bp)
def errorpage(e):
return v0.api.handle_error(e)
| Improve error handling of sipa API | Improve error handling of sipa API
| Python | apache-2.0 | agdsn/pycroft,lukasjuhrich/pycroft,agdsn/pycroft,agdsn/pycroft,agdsn/pycroft,lukasjuhrich/pycroft,agdsn/pycroft,lukasjuhrich/pycroft,lukasjuhrich/pycroft | from flask import Blueprint
from . import v0
bp = Blueprint('api', __name__)
v0.api.init_app(bp)
def errorpage(e):
return v0.api.handle_error(e)
| Improve error handling of sipa API
from flask import Blueprint
from . import v0
bp = Blueprint('api', __name__)
v0.api.init_app(bp)
def errorpage(e):
code = getattr(e, 'code', 500)
if code == 404:
return jsonify(msg=str(e))
return jsonify(msg="error", code=code)
|
a1ef84da0df661a9371df23a623daf2b51304e89 | scripts/domain/effects.py | scripts/domain/effects.py |
class Effects:
def attack(self, player, dices):
pass
def defend(self, player, dmg, dodge):
pass
def dispute(self, player, attrName):
pass
| Add first version of the Effects base class | Add first version of the Effects base class
| Python | mit | VinGarcia/jit-rpg-system |
class Effects:
def attack(self, player, dices):
pass
def defend(self, player, dmg, dodge):
pass
def dispute(self, player, attrName):
pass
| Add first version of the Effects base class
| |
3c722947d8ece448dec7ce9f82c2a477c667c4a8 | setup.py | setup.py | from setuptools import setup
setup(
name='playlistfromsong',
packages=['playlistfromsong'],
version='0.22',
description='An offline music station generator',
author='schollz',
url='https://github.com/schollz/playlistfromsong',
author_email='hypercube.platforms@gmail.com',
download_url='... | from setuptools import setup
setup(
name='playlistfromsong',
packages=['playlistfromsong'],
version='1.0.0',
description='An offline music station generator',
author='schollz',
url='https://github.com/schollz/playlistfromsong',
author_email='hypercube.platforms@gmail.com',
download_url=... | Upgrade to 1.0.0 (switch to semantic versioning) | Upgrade to 1.0.0 (switch to semantic versioning)
| Python | mit | schollz/playlistfromsong | from setuptools import setup
setup(
name='playlistfromsong',
packages=['playlistfromsong'],
version='1.0.0',
description='An offline music station generator',
author='schollz',
url='https://github.com/schollz/playlistfromsong',
author_email='hypercube.platforms@gmail.com',
download_url=... | Upgrade to 1.0.0 (switch to semantic versioning)
from setuptools import setup
setup(
name='playlistfromsong',
packages=['playlistfromsong'],
version='0.22',
description='An offline music station generator',
author='schollz',
url='https://github.com/schollz/playlistfromsong',
author_email='... |
10db5e8b893a84e765162535f64e1ede81d48b47 | empty_check.py | empty_check.py | from django.core.exceptions import ValidationError
class EmptyCheck(object):
def __call__(self, value):
if len(value.strip()) == 0:
raise ValidationError("Value cannot be empty")
| from django.core.exceptions import ValidationError
# Usage example in a custom form
# firstname = forms.CharField(validators = [EmptyCheck()])
class EmptyCheck(object):
def __call__(self, value):
if len(value.strip()) == 0:
raise ValidationError("Value cannot be empty")
| Add comment to show usage example | Add comment to show usage example | Python | mit | vishalsodani/django-empty-check-validator | from django.core.exceptions import ValidationError
# Usage example in a custom form
# firstname = forms.CharField(validators = [EmptyCheck()])
class EmptyCheck(object):
def __call__(self, value):
if len(value.strip()) == 0:
raise ValidationError("Value cannot be empty")
| Add comment to show usage example
from django.core.exceptions import ValidationError
class EmptyCheck(object):
def __call__(self, value):
if len(value.strip()) == 0:
raise ValidationError("Value cannot be empty")
|
a26f3ee3df1f70302bc524e3a8decb1a1266aadd | devito/data/meta.py | devito/data/meta.py | from devito.tools import Tag
__all__ = ['DOMAIN', 'OWNED', 'HALO', 'NOPAD', 'FULL',
'LEFT', 'RIGHT', 'CENTER']
class DataRegion(Tag):
pass
DOMAIN = DataRegion('domain')
OWNED = DataRegion('owned') # within DOMAIN
HALO = DataRegion('halo')
NOPAD = DataRegion('nopad') # == DOMAIN+HALO
FULL = DataReg... | from devito.tools import Tag
__all__ = ['DOMAIN', 'OWNED', 'HALO', 'NOPAD', 'FULL',
'LEFT', 'RIGHT', 'CENTER']
class DataRegion(Tag):
pass
DOMAIN = DataRegion('domain')
OWNED = DataRegion('owned') # within DOMAIN
HALO = DataRegion('halo')
NOPAD = DataRegion('nopad') # == DOMAIN+HALO
FULL = DataReg... | Add static value to LEFT, CENTER, RIGHT | data: Add static value to LEFT, CENTER, RIGHT
| Python | mit | opesci/devito,opesci/devito | from devito.tools import Tag
__all__ = ['DOMAIN', 'OWNED', 'HALO', 'NOPAD', 'FULL',
'LEFT', 'RIGHT', 'CENTER']
class DataRegion(Tag):
pass
DOMAIN = DataRegion('domain')
OWNED = DataRegion('owned') # within DOMAIN
HALO = DataRegion('halo')
NOPAD = DataRegion('nopad') # == DOMAIN+HALO
FULL = DataReg... | data: Add static value to LEFT, CENTER, RIGHT
from devito.tools import Tag
__all__ = ['DOMAIN', 'OWNED', 'HALO', 'NOPAD', 'FULL',
'LEFT', 'RIGHT', 'CENTER']
class DataRegion(Tag):
pass
DOMAIN = DataRegion('domain')
OWNED = DataRegion('owned') # within DOMAIN
HALO = DataRegion('halo')
NOPAD = DataR... |
02cfc3a53bf3f38dc676359eace0e258bfda682a | plotly/graph_objs/__init__.py | plotly/graph_objs/__init__.py | """
graph_objs
==========
This package imports definitions for all of Plotly's graph objects. For more
information, run help(Obj) on any of the following objects defined here.
"""
from __future__ import absolute_import
from plotly.graph_objs.graph_objs import *
__all__ = ["Data",
"Annotations",
... | """
graph_objs
==========
This package imports definitions for all of Plotly's graph objects. For more
information, run help(Obj) on any of the following objects defined here.
The reason for the package graph_objs and the module graph_objs is to provide
a clearer API for users.
"""
from . graph_objs import (
Dat... | Remove the `import *`. Explicitly import what we want to expose. | Remove the `import *`. Explicitly import what we want to expose.
Before __all__ was used to manage these. But it's clearer to
just import what we want users to see.
| Python | mit | plotly/plotly.py,plotly/python-api,plotly/plotly.py,ee-in/python-api,plotly/plotly.py,ee-in/python-api,plotly/python-api,ee-in/python-api,plotly/python-api | """
graph_objs
==========
This package imports definitions for all of Plotly's graph objects. For more
information, run help(Obj) on any of the following objects defined here.
The reason for the package graph_objs and the module graph_objs is to provide
a clearer API for users.
"""
from . graph_objs import (
Dat... | Remove the `import *`. Explicitly import what we want to expose.
Before __all__ was used to manage these. But it's clearer to
just import what we want users to see.
"""
graph_objs
==========
This package imports definitions for all of Plotly's graph objects. For more
information, run help(Obj) on any of the followin... |
a1229bd5cc1446c11950232ee551acfc99092fcf | kaiser_shift.py | kaiser_shift.py | #!/usr/bin/env python2.7
# ##### BEGIN AGPL LICENSE BLOCK #####
# This file is part of SimpleMMO.
#
# Copyright (C) 2012 Charles Nelson
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, e... | Add a dumb language "translator" function. | Add a dumb language "translator" function.
| Python | agpl-3.0 | cnelsonsic/SimpleMMO,cnelsonsic/SimpleMMO,cnelsonsic/SimpleMMO | #!/usr/bin/env python2.7
# ##### BEGIN AGPL LICENSE BLOCK #####
# This file is part of SimpleMMO.
#
# Copyright (C) 2012 Charles Nelson
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, e... | Add a dumb language "translator" function.
| |
cd88e724f7f2f8293a509db3dc0558904beee6e4 | tools/test/psa/psa_target_config_test.py | tools/test/psa/psa_target_config_test.py | #!/usr/bin/env python
"""
Copyright (c) 2019-2020 ARM Limited. All rights reserved.
SPDX-License-Identifier: Apache-2.0
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/licens... | Add a script to validate PSA targets | psa: Add a script to validate PSA targets
Add a script to parse `targets.json` to identify PSA targets and ensure
mandatory parameters are configured correctly for all PSA targets.
Signed-off-by: Devaraj Ranganna <53e2fcb007e5c6e2caf46b91114119a655266f64@arm.com>
| Python | apache-2.0 | mbedmicro/mbed,mbedmicro/mbed,mbedmicro/mbed,mbedmicro/mbed,mbedmicro/mbed | #!/usr/bin/env python
"""
Copyright (c) 2019-2020 ARM Limited. All rights reserved.
SPDX-License-Identifier: Apache-2.0
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/licens... | psa: Add a script to validate PSA targets
Add a script to parse `targets.json` to identify PSA targets and ensure
mandatory parameters are configured correctly for all PSA targets.
Signed-off-by: Devaraj Ranganna <53e2fcb007e5c6e2caf46b91114119a655266f64@arm.com>
| |
fcfceb59cbd368ddaee87906d3f53f15bbb30072 | examples/tornado/auth_demo.py | examples/tornado/auth_demo.py | from mongrel2.config import *
main = Server(
uuid="f400bf85-4538-4f7a-8908-67e313d515c2",
access_log="/logs/access.log",
error_log="/logs/error.log",
chroot="./",
default_host="localhost",
name="test",
pid_file="/run/mongrel2.pid",
port=6767,
hosts = [
Host(name="localhost"... | from mongrel2.config import *
main = Server(
uuid="f400bf85-4538-4f7a-8908-67e313d515c2",
access_log="/logs/access.log",
error_log="/logs/error.log",
chroot="./",
default_host="localhost",
name="test",
pid_file="/run/mongrel2.pid",
port=6767,
hosts = [
Host(name="localhost"... | Add the settings to the authdemo. | Add the settings to the authdemo. | Python | bsd-3-clause | solidrails/mongrel2,solidrails/mongrel2,solidrails/mongrel2,solidrails/mongrel2 | from mongrel2.config import *
main = Server(
uuid="f400bf85-4538-4f7a-8908-67e313d515c2",
access_log="/logs/access.log",
error_log="/logs/error.log",
chroot="./",
default_host="localhost",
name="test",
pid_file="/run/mongrel2.pid",
port=6767,
hosts = [
Host(name="localhost"... | Add the settings to the authdemo.
from mongrel2.config import *
main = Server(
uuid="f400bf85-4538-4f7a-8908-67e313d515c2",
access_log="/logs/access.log",
error_log="/logs/error.log",
chroot="./",
default_host="localhost",
name="test",
pid_file="/run/mongrel2.pid",
port=6767,
hosts... |
b5454286a2cfce07f4971b7bc56dd131402f8fe3 | iati/__init__.py | iati/__init__.py | """A top-level namespace package for IATI."""
__import__('pkg_resources').declare_namespace(__name__)
from .codelists import Code, Codelist # noqa: F401
from .data import Dataset # noqa: F401
from .rulesets import Rule, Ruleset # noqa: F401
from .rulesets import RuleAtLeastOne, RuleDateOrder, RuleDependent, RuleNoM... | """A top-level namespace package for IATI."""
from .codelists import Code, Codelist # noqa: F401
from .data import Dataset # noqa: F401
from .rulesets import Rule, Ruleset # noqa: F401
from .rulesets import RuleAtLeastOne, RuleDateOrder, RuleDependent, RuleNoMoreThanOne, RuleRegexMatches, RuleRegexNoMatches, RuleSta... | Fix pylint error after iati.core -> iati | Fix pylint error after iati.core -> iati
| Python | mit | IATI/iati.core,IATI/iati.core | """A top-level namespace package for IATI."""
from .codelists import Code, Codelist # noqa: F401
from .data import Dataset # noqa: F401
from .rulesets import Rule, Ruleset # noqa: F401
from .rulesets import RuleAtLeastOne, RuleDateOrder, RuleDependent, RuleNoMoreThanOne, RuleRegexMatches, RuleRegexNoMatches, RuleSta... | Fix pylint error after iati.core -> iati
"""A top-level namespace package for IATI."""
__import__('pkg_resources').declare_namespace(__name__)
from .codelists import Code, Codelist # noqa: F401
from .data import Dataset # noqa: F401
from .rulesets import Rule, Ruleset # noqa: F401
from .rulesets import RuleAtLeast... |
3b30a036f9f9fb861c0ed1711b5bd967756a072d | flask_cors/__init__.py | flask_cors/__init__.py | # -*- coding: utf-8 -*-
"""
flask_cors
~~~~
Flask-CORS is a simple extension to Flask allowing you to support cross
origin resource sharing (CORS) using a simple decorator.
:copyright: (c) 2014 by Cory Dolphin.
:license: MIT, see LICENSE for more details.
"""
from .decorator import cross_origin... | # -*- coding: utf-8 -*-
"""
flask_cors
~~~~
Flask-CORS is a simple extension to Flask allowing you to support cross
origin resource sharing (CORS) using a simple decorator.
:copyright: (c) 2014 by Cory Dolphin.
:license: MIT, see LICENSE for more details.
"""
from .decorator import cross_origin... | Disable logging for flask_cors by default | Disable logging for flask_cors by default
| Python | mit | corydolphin/flask-cors,ashleysommer/sanic-cors | # -*- coding: utf-8 -*-
"""
flask_cors
~~~~
Flask-CORS is a simple extension to Flask allowing you to support cross
origin resource sharing (CORS) using a simple decorator.
:copyright: (c) 2014 by Cory Dolphin.
:license: MIT, see LICENSE for more details.
"""
from .decorator import cross_origin... | Disable logging for flask_cors by default
# -*- coding: utf-8 -*-
"""
flask_cors
~~~~
Flask-CORS is a simple extension to Flask allowing you to support cross
origin resource sharing (CORS) using a simple decorator.
:copyright: (c) 2014 by Cory Dolphin.
:license: MIT, see LICENSE for more detai... |
064578b33fd4a58ce427dd4547deb3859ab56ebb | corehq/blobs/migrations/0007_blobmeta_migrated_check.py | corehq/blobs/migrations/0007_blobmeta_migrated_check.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.14 on 2019-01-05 00:21
from __future__ import unicode_literals
from __future__ import absolute_import
from __future__ import print_function
import sys
import traceback
from django.core.management import call_command
from django.db import connections, migrations
from... | Add blob metadata migration check | Add blob metadata migration check | Python | bsd-3-clause | dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq | # -*- coding: utf-8 -*-
# Generated by Django 1.11.14 on 2019-01-05 00:21
from __future__ import unicode_literals
from __future__ import absolute_import
from __future__ import print_function
import sys
import traceback
from django.core.management import call_command
from django.db import connections, migrations
from... | Add blob metadata migration check
| |
1766a5acc5c948288b4cd81c62d0c1507c55f727 | cinder/brick/initiator/host_driver.py | cinder/brick/initiator/host_driver.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2013 OpenStack Foundation.
# 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.apac... | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2013 OpenStack Foundation.
# 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.apac... | Check if dir exists before calling listdir | Check if dir exists before calling listdir
Changes along the way to how we clean up and detach after
copying an image to a volume exposed a problem in the cleanup
of the brick/initiator routines.
The clean up in the initiator detach was doing a blind listdir
of /dev/disk/by-path, however due to detach and cleanup bei... | Python | apache-2.0 | petrutlucian94/cinder,Paul-Ezell/cinder-1,CloudServer/cinder,Datera/cinder,nikesh-mahalka/cinder,alex8866/cinder,j-griffith/cinder,cloudbase/cinder,openstack/cinder,julianwang/cinder,redhat-openstack/cinder,tlakshman26/cinder-bug-fix-volume-conversion-full,Akrog/cinder,Hybrid-Cloud/cinder,CloudServer/cinder,tlakshman26... | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2013 OpenStack Foundation.
# 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.apac... | Check if dir exists before calling listdir
Changes along the way to how we clean up and detach after
copying an image to a volume exposed a problem in the cleanup
of the brick/initiator routines.
The clean up in the initiator detach was doing a blind listdir
of /dev/disk/by-path, however due to detach and cleanup bei... |
849fbdf724528df99f2ac53d389274f7c2631f11 | invitation/admin.py | invitation/admin.py | from django.contrib import admin
from invitation.models import InvitationKey, InvitationUser, InvitationRequest, InvitationCode
class InvitationKeyAdmin(admin.ModelAdmin):
list_display = ('__unicode__', 'from_user', 'date_invited', 'key_expired')
class InvitationUserAdmin(admin.ModelAdmin):
list_display = (... | from django.contrib import admin
from invitation.models import InvitationKey, InvitationUser, InvitationRequest, InvitationCode
class InvitationKeyAdmin(admin.ModelAdmin):
list_display = ('__unicode__', 'from_user', 'date_invited', 'key_expired')
class InvitationUserAdmin(admin.ModelAdmin):
list_display = (... | Improve the invite_user action name. | Improve the invite_user action name. | Python | bsd-3-clause | adieu/django-invitation | from django.contrib import admin
from invitation.models import InvitationKey, InvitationUser, InvitationRequest, InvitationCode
class InvitationKeyAdmin(admin.ModelAdmin):
list_display = ('__unicode__', 'from_user', 'date_invited', 'key_expired')
class InvitationUserAdmin(admin.ModelAdmin):
list_display = (... | Improve the invite_user action name.
from django.contrib import admin
from invitation.models import InvitationKey, InvitationUser, InvitationRequest, InvitationCode
class InvitationKeyAdmin(admin.ModelAdmin):
list_display = ('__unicode__', 'from_user', 'date_invited', 'key_expired')
class InvitationUserAdmin(ad... |
57d49b185d1daf0e6a27e0daee8960c2816615cc | alg_kruskal_minimum_spanning_tree.py | alg_kruskal_minimum_spanning_tree.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
def kruskal():
"""Kruskal's algorithm for minimum spanning tree in weighted graph.
Time complexity for graph G(V, E): TBD.
"""
pass
def main():
w_graph_d = {
'a': {'b': 1, 'd': 4, 'e': 3},
... | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
def kruskal():
"""Kruskal's algorithm for minimum spanning tree
in weighted graph.
Time complexity for graph G(V, E):
O(|E|+|V|+|E|log(|V|)) = O(|E|log(|V|^2)) = O(|E|log(|V|)).
"""
pass
def ma... | Revise doc string and add time complexity | Revise doc string and add time complexity
| Python | bsd-2-clause | bowen0701/algorithms_data_structures | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
def kruskal():
"""Kruskal's algorithm for minimum spanning tree
in weighted graph.
Time complexity for graph G(V, E):
O(|E|+|V|+|E|log(|V|)) = O(|E|log(|V|^2)) = O(|E|log(|V|)).
"""
pass
def ma... | Revise doc string and add time complexity
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
def kruskal():
"""Kruskal's algorithm for minimum spanning tree in weighted graph.
Time complexity for graph G(V, E): TBD.
"""
pass
def main():
w_graph_d = ... |
6172eafbaf65b859462985056bb33490b98b0749 | peloid/app/shell/service.py | peloid/app/shell/service.py | from twisted.cred import portal
from twisted.conch import manhole_ssh
from twisted.conch.checkers import SSHPublicKeyDatabase
from carapace.util import ssh as util
from peloid.app.shell import gameshell, setupshell
def getGameShellFactory(**namespace):
game = None
sshRealm = gameshell.TerminalRealm(namespac... | from twisted.cred import portal
from twisted.conch import manhole_ssh
from twisted.conch.checkers import SSHPublicKeyDatabase
from carapace.util import ssh as util
from peloid.app import mud
from peloid.app.shell import gameshell, setupshell
def getGameShellFactory(**namespace):
game = mud.Game()
sshRealm =... | Use the new Game class. | Use the new Game class.
| Python | mit | oubiwann/peloid | from twisted.cred import portal
from twisted.conch import manhole_ssh
from twisted.conch.checkers import SSHPublicKeyDatabase
from carapace.util import ssh as util
from peloid.app import mud
from peloid.app.shell import gameshell, setupshell
def getGameShellFactory(**namespace):
game = mud.Game()
sshRealm =... | Use the new Game class.
from twisted.cred import portal
from twisted.conch import manhole_ssh
from twisted.conch.checkers import SSHPublicKeyDatabase
from carapace.util import ssh as util
from peloid.app.shell import gameshell, setupshell
def getGameShellFactory(**namespace):
game = None
sshRealm = gameshe... |
b6cfa50e127d3f74247ab148219ef6336e445cca | InvenTree/InvenTree/ready.py | InvenTree/InvenTree/ready.py | import sys
def canAppAccessDatabase():
"""
Returns True if the apps.py file can access database records.
There are some circumstances where we don't want the ready function in apps.py
to touch the database
"""
# If any of the following management commands are being executed,
# prevent cu... | import sys
def canAppAccessDatabase():
"""
Returns True if the apps.py file can access database records.
There are some circumstances where we don't want the ready function in apps.py
to touch the database
"""
# If any of the following management commands are being executed,
# prevent cu... | Allow data operations to run for 'test' | Allow data operations to run for 'test'
| Python | mit | inventree/InvenTree,inventree/InvenTree,SchrodingersGat/InvenTree,SchrodingersGat/InvenTree,inventree/InvenTree,SchrodingersGat/InvenTree,inventree/InvenTree,SchrodingersGat/InvenTree | import sys
def canAppAccessDatabase():
"""
Returns True if the apps.py file can access database records.
There are some circumstances where we don't want the ready function in apps.py
to touch the database
"""
# If any of the following management commands are being executed,
# prevent cu... | Allow data operations to run for 'test'
import sys
def canAppAccessDatabase():
"""
Returns True if the apps.py file can access database records.
There are some circumstances where we don't want the ready function in apps.py
to touch the database
"""
# If any of the following management comm... |
91049834c3f30dcb838ac45167e93aa1bc92a913 | fluent_faq/pagetypes/faqpage/page_type_plugins.py | fluent_faq/pagetypes/faqpage/page_type_plugins.py | from fluent_pages.admin import HtmlPageAdmin
from fluent_pages.extensions import page_type_pool, PageTypePlugin
from .models import FaqPage
@page_type_pool.register
class FaqPagePlugin(PageTypePlugin):
"""
Plugin binding the FaqPage model as pagetype.
"""
model = FaqPage
model_admin = HtmlPageAdmi... | from fluent_pages.adminui import HtmlPageAdmin
from fluent_pages.extensions import page_type_pool, PageTypePlugin
from .models import FaqPage
@page_type_pool.register
class FaqPagePlugin(PageTypePlugin):
"""
Plugin binding the FaqPage model as pagetype.
"""
model = FaqPage
model_admin = HtmlPageAd... | Prepare Django 1.7 compatibility, use new fluent_pages.adminui module | Prepare Django 1.7 compatibility, use new fluent_pages.adminui module
| Python | apache-2.0 | edoburu/django-fluent-faq,edoburu/django-fluent-faq | from fluent_pages.adminui import HtmlPageAdmin
from fluent_pages.extensions import page_type_pool, PageTypePlugin
from .models import FaqPage
@page_type_pool.register
class FaqPagePlugin(PageTypePlugin):
"""
Plugin binding the FaqPage model as pagetype.
"""
model = FaqPage
model_admin = HtmlPageAd... | Prepare Django 1.7 compatibility, use new fluent_pages.adminui module
from fluent_pages.admin import HtmlPageAdmin
from fluent_pages.extensions import page_type_pool, PageTypePlugin
from .models import FaqPage
@page_type_pool.register
class FaqPagePlugin(PageTypePlugin):
"""
Plugin binding the FaqPage model ... |
06907e310169db7084f9e40f93e60182ba6e6423 | python/animationBase.py | python/animationBase.py | #!/usr/bin/env python
from rgbmatrix import RGBMatrix
import sys, time
from ball import Ball
rows = 16
chains = 1
parallel = 1
ledMatrix = RGBMatrix(rows, chains, parallel)
numRows = 16
height = ledMatrix.height
width = ledMatrix.width
ball = Ball(5, 9, 4)
try:
print "Press Ctrl + C to stop executing"
while True:
... | #!/usr/bin/env python
from rgbmatrix import RGBMatrix
import sys, time
from ball import Ball
rows = 16
chains = 1
parallel = 1
ledMatrix = RGBMatrix(rows, chains, parallel)
numRows = 16
height = ledMatrix.height
width = ledMatrix.width
red = Ball(5, 9, 4)
blue = Ball(6, 9, 2, 2, 0, 0, 255)
try:
print "Press Ctrl + ... | Add two balls to animation | Add two balls to animation
| Python | mit | DarkAce65/rpi-led-matrix,DarkAce65/rpi-led-matrix | #!/usr/bin/env python
from rgbmatrix import RGBMatrix
import sys, time
from ball import Ball
rows = 16
chains = 1
parallel = 1
ledMatrix = RGBMatrix(rows, chains, parallel)
numRows = 16
height = ledMatrix.height
width = ledMatrix.width
red = Ball(5, 9, 4)
blue = Ball(6, 9, 2, 2, 0, 0, 255)
try:
print "Press Ctrl + ... | Add two balls to animation
#!/usr/bin/env python
from rgbmatrix import RGBMatrix
import sys, time
from ball import Ball
rows = 16
chains = 1
parallel = 1
ledMatrix = RGBMatrix(rows, chains, parallel)
numRows = 16
height = ledMatrix.height
width = ledMatrix.width
ball = Ball(5, 9, 4)
try:
print "Press Ctrl + C to s... |
79c9ee6107b841986054915c23f8456c80097c5b | osgtest/tests/test_13_gridftp.py | osgtest/tests/test_13_gridftp.py | import os
import osgtest.library.core as core
import unittest
class TestStartGridFTP(unittest.TestCase):
def test_01_start_gridftp(self):
core.config['gridftp.pid-file'] = '/var/run/globus-gridftp-server.pid'
core.state['gridftp.started-server'] = False
if not core.rpm_is_installed('globu... | import os
from osgtest.library import core, osgunittest
import unittest
class TestStartGridFTP(osgunittest.OSGTestCase):
def test_01_start_gridftp(self):
core.config['gridftp.pid-file'] = '/var/run/globus-gridftp-server.pid'
core.state['gridftp.started-server'] = False
core.skip_ok_unless... | Update 13_gridftp to use OkSkip functionality | Update 13_gridftp to use OkSkip functionality
git-svn-id: 884a03e47e2adb735d896e55bb5ad6bc3421ba19@16527 4e558342-562e-0410-864c-e07659590f8c
| Python | apache-2.0 | efajardo/osg-test,efajardo/osg-test | import os
from osgtest.library import core, osgunittest
import unittest
class TestStartGridFTP(osgunittest.OSGTestCase):
def test_01_start_gridftp(self):
core.config['gridftp.pid-file'] = '/var/run/globus-gridftp-server.pid'
core.state['gridftp.started-server'] = False
core.skip_ok_unless... | Update 13_gridftp to use OkSkip functionality
git-svn-id: 884a03e47e2adb735d896e55bb5ad6bc3421ba19@16527 4e558342-562e-0410-864c-e07659590f8c
import os
import osgtest.library.core as core
import unittest
class TestStartGridFTP(unittest.TestCase):
def test_01_start_gridftp(self):
core.config['gridftp.pid... |
8b4b5705907e1ec5f9dd3148560dc1bf4cd5b9b7 | bin/detail/get_nmake_environment.py | bin/detail/get_nmake_environment.py | # Copyright (c) 2014, Ruslan Baratov
# All rights reserved.
import detail.util
import os
import sys
def get(arch, vs_version):
vs_path_env = 'VS{}0COMNTOOLS'.format(vs_version)
vs_path = os.getenv(vs_path_env)
if not vs_path:
sys.exit(
'Environment variable {} is empty, '
'looks like Visual ... | # Copyright (c) 2014, Ruslan Baratov
# All rights reserved.
import detail.util
import os
import sys
def get(arch, vs_version):
vs_path_env = 'VS{}0COMNTOOLS'.format(vs_version)
vs_path = os.getenv(vs_path_env)
if not vs_path:
sys.exit(
'Environment variable {} is empty, '
'looks like Visual ... | Fix vcvarsall_dir for Visual Studio 2017 | polly.py: Fix vcvarsall_dir for Visual Studio 2017
[skip ci]
| Python | bsd-2-clause | idscan/polly,idscan/polly,ruslo/polly,ruslo/polly | # Copyright (c) 2014, Ruslan Baratov
# All rights reserved.
import detail.util
import os
import sys
def get(arch, vs_version):
vs_path_env = 'VS{}0COMNTOOLS'.format(vs_version)
vs_path = os.getenv(vs_path_env)
if not vs_path:
sys.exit(
'Environment variable {} is empty, '
'looks like Visual ... | polly.py: Fix vcvarsall_dir for Visual Studio 2017
[skip ci]
# Copyright (c) 2014, Ruslan Baratov
# All rights reserved.
import detail.util
import os
import sys
def get(arch, vs_version):
vs_path_env = 'VS{}0COMNTOOLS'.format(vs_version)
vs_path = os.getenv(vs_path_env)
if not vs_path:
sys.exit(
'... |
ba9c1108a15bac713e7bda987865f8c4c1db92c7 | timm/loss/binary_cross_entropy.py | timm/loss/binary_cross_entropy.py | import torch
import torch.nn as nn
import torch.nn.functional as F
class DenseBinaryCrossEntropy(nn.Module):
""" BCE using one-hot from dense targets w/ label smoothing
NOTE for experiments comparing CE to BCE /w label smoothing, may remove
"""
def __init__(self, smoothing=0.1):
super(DenseBin... | Add a BCE loss impl that converts dense targets to sparse /w smoothing as an alternate to CE w/ smoothing. For training experiments. | Add a BCE loss impl that converts dense targets to sparse /w smoothing as an alternate to CE w/ smoothing. For training experiments.
| Python | apache-2.0 | rwightman/pytorch-image-models,rwightman/pytorch-image-models | import torch
import torch.nn as nn
import torch.nn.functional as F
class DenseBinaryCrossEntropy(nn.Module):
""" BCE using one-hot from dense targets w/ label smoothing
NOTE for experiments comparing CE to BCE /w label smoothing, may remove
"""
def __init__(self, smoothing=0.1):
super(DenseBin... | Add a BCE loss impl that converts dense targets to sparse /w smoothing as an alternate to CE w/ smoothing. For training experiments.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.