commit stringlengths 40 40 | old_file stringlengths 4 236 | new_file stringlengths 4 236 | old_contents stringlengths 1 3.26k | new_contents stringlengths 16 4.43k | subject stringlengths 16 624 | message stringlengths 17 3.29k | lang stringclasses 5
values | license stringclasses 13
values | repos stringlengths 5 91.5k |
|---|---|---|---|---|---|---|---|---|---|
81215120afffe54b17be3f38bbc2ac292452c0c4 | addons/mail/models/ir_attachment.py | addons/mail/models/ir_attachment.py | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models
class IrAttachment(models.Model):
_inherit = 'ir.attachment'
@api.multi
def _post_add_create(self):
""" Overrides behaviour when the attachment is created throu... | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models
class IrAttachment(models.Model):
_inherit = 'ir.attachment'
@api.multi
def _post_add_create(self):
""" Overrides behaviour when the attachment is created throu... | Revert "[FIX] mail: remove attachment as main at unlink" | Revert "[FIX] mail: remove attachment as main at unlink"
This reverts commit abc45b1
Since by default the ondelete attribute of a many2one is `set null`,
this was completely unnecessary to begin with.
Bug caused by this commit:
Unlink a record that has some attachments.
The unlink first removes the record, then its r... | Python | agpl-3.0 | ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo |
17cdaa0cf7313e4edf5ef28ea2634410bd085d4f | rsk_mind/transformer/transformer.py | rsk_mind/transformer/transformer.py | class Transformer(object):
class Feats():
exclude = None
def __init__(self):
for field in self.get_feats():
getattr(self.Feats, field).bind(field, self)
def get_feats(self):
return [x for x in dir(self.Feats) if not (x.startswith('__') or x in ['exclude'])]
def get... | class Transformer(object):
"""
Base class for all transformer
"""
class Feats:
"""
Define feats on dataset
"""
exclude = None
def __init__(self):
for field in self.get_feats():
getattr(self.Feats, field).bind(field, self)
def get_fea... | Add documentation and some methods | Add documentation and some methods
| Python | mit | rsk-mind/rsk-mind-framework |
1ea4e06fb3dc08a27a37b379e9ba2fffd5303625 | ca_on_school_boards_english_public/__init__.py | ca_on_school_boards_english_public/__init__.py | from utils import CanadianJurisdiction
from opencivicdata.divisions import Division
from pupa.scrape import Organization
class OntarioEnglishPublicSchoolBoards(CanadianJurisdiction):
classification = 'legislature' # just to avoid clash
division_id = 'ocd-division/country:ca/province:on'
division_name = '... | from utils import CanadianJurisdiction
from opencivicdata.divisions import Division
from pupa.scrape import Organization
class OntarioEnglishPublicSchoolBoards(CanadianJurisdiction):
classification = 'legislature' # just to avoid clash
division_id = 'ocd-division/country:ca/province:on'
division_name = '... | Fix where the seat number appears | Fix where the seat number appears
| Python | mit | opencivicdata/scrapers-ca,opencivicdata/scrapers-ca |
9f18d05091abfb6b13914c4b29970ed6fc5d367d | penelophant/models/__init__.py | penelophant/models/__init__.py | """ Penelophant Models """
from .User import User
from .UserAuthentication import UserAuthentication
from .Auction import Auction
from .Bid import Bid
from .Invoice import Invoice
| """ Penelophant Models """
from .User import User
from .UserAuthentication import UserAuthentication
from .Auction import Auction
from .Bid import Bid
from .Invoice import Invoice
from .auctions.DoubleBlindAuction import DoubleBlindAuction
| Load in the double blind auction | Load in the double blind auction
| Python | apache-2.0 | kevinoconnor7/penelophant,kevinoconnor7/penelophant |
d89093f739cf5c953fb81d1c5c3e6dde5e90fb0c | check-if-a-given-sequence-of-moves-for-a-robot-is-circular-or-not.py | check-if-a-given-sequence-of-moves-for-a-robot-is-circular-or-not.py | from operator import add
import math
moves = raw_input("Enter the moves: ")
start_position = [0,0]
current_position = [0,0]
'''
heading = [1,90] - 1 step North
[1, -90] - 1 step South
[1,0] - East
[1,360] - West
'''
heading = [1,0]
for move in moves:
if move.upper() == "G":
angle = heading[1]
ste... | '''
URL: http://www.geeksforgeeks.org/check-if-a-given-sequence-of-moves-for-a-robot-is-circular-or-not/
====
Python 2.7 compatible
Problem statement:
====================
Given a sequence of moves for a robot, check if the sequence is circular or not. A sequence of moves is circular if first and last positions of r... | Check if path is circular or not. Write from correct repository. | [Correct]: Check if path is circular or not. Write from correct
repository.
| Python | apache-2.0 | MayankAgarwal/GeeksForGeeks |
ab3dc6466b617a5bf5a0bec2c122eca645c1d29f | cloudera-framework-assembly/src/main/resources/python/script_util.py | cloudera-framework-assembly/src/main/resources/python/script_util.py | import os
def hdfs_make_qualified(path):
return path if 'CF_HADOOP_DEFAULT_FS' not in os.environ else os.environ['CF_HADOOP_DEFAULT_FS'] + path
| import os
import re
def hdfs_make_qualified(path):
return path if (re.match(r'[.]*://[.]*', path) or 'CF_HADOOP_DEFAULT_FS' not in os.environ) \
else os.environ['CF_HADOOP_DEFAULT_FS'] + path
| Update python script util to detect if paths are already fully qualified | Update python script util to detect if paths are already fully qualified
| Python | apache-2.0 | ggear/cloudera-framework,ggear/cloudera-framework,ggear/cloudera-framework |
16c8f23cd6ad9f9a10592bb40d1a18eb2c673d34 | common.py | common.py | import mechanize
import os
class McGillException(Exception):
pass
urls = {
'login': 'twbkwbis.P_WWWLogin',
'transcript': 'bzsktran.P_Display_Form?user_type=S&tran_type=V'
}
_base_url = 'https://banweb.mcgill.ca/pban1/%s'
urls = {k: _base_url % v for k,v in urls.items()}
browser = mechanize.Browser()
def... | import mechanize
import os
class error(Exception):
pass
urls = {
'login': 'twbkwbis.P_WWWLogin',
'transcript': 'bzsktran.P_Display_Form?user_type=S&tran_type=V'
}
_base_url = 'https://banweb.mcgill.ca/pban1/%s'
urls = {k: _base_url % v for k,v in urls.items()}
browser = mechanize.Browser()
def login(sid... | Rename McGillException to error (mcgill.error) | Rename McGillException to error (mcgill.error)
| Python | mit | isbadawi/minerva |
f158cecd2e5155a0e8bb2e04d097db5a7b146836 | pitchfork/config/config.example.py | pitchfork/config/config.example.py | # Copyright 2014 Dave Kludt
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, s... | # Copyright 2014 Dave Kludt
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, s... | Add in helper documenation to assist with docker container run | Add in helper documenation to assist with docker container run
| Python | apache-2.0 | rackerlabs/pitchfork,rackerlabs/pitchfork,oldarmyc/pitchfork,rackerlabs/pitchfork,oldarmyc/pitchfork,oldarmyc/pitchfork |
21e47557da10e1f4bb14e32d15194bf95211882a | python/getmonotime.py | python/getmonotime.py | import getopt, sys
if __name__ == '__main__':
sippy_path = None
try:
opts, args = getopt.getopt(sys.argv[1:], 's:S:i:o:b')
except getopt.GetoptError:
usage()
for o, a in opts:
if o == '-S':
sippy_path = a.strip()
continue
if sippy_path != None:
... | import getopt, sys
if __name__ == '__main__':
sippy_path = None
try:
opts, args = getopt.getopt(sys.argv[1:], 'rS:')
except getopt.GetoptError:
usage()
out_realtime = False
for o, a in opts:
if o == '-S':
sippy_path = a.strip()
continue
if o... | Add an option to also output realtime along with monotime. | Add an option to also output realtime along with monotime.
| Python | bsd-2-clause | sippy/rtpproxy,jevonearth/rtpproxy,dsanders11/rtpproxy,sippy/rtpproxy,synety-jdebp/rtpproxy,jevonearth/rtpproxy,dsanders11/rtpproxy,jevonearth/rtpproxy,jevonearth/rtpproxy,synety-jdebp/rtpproxy,synety-jdebp/rtpproxy,sippy/rtpproxy,dsanders11/rtpproxy,synety-jdebp/rtpproxy |
5bd17a3088c2d1958d86efc4411b575c123e6275 | tests/functional/test_l10n.py | tests/functional/test_l10n.py | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
import random
import pytest
from ..pages.home import HomePage
@pytest.mark.nondestructive
def test_change_language(b... | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
import random
import pytest
from ..pages.home import HomePage
@pytest.mark.nondestructive
def test_change_language(b... | Exclude ja-JP-mac on homepage language select functional test | Exclude ja-JP-mac on homepage language select functional test
| Python | mpl-2.0 | hoosteeno/bedrock,flodolo/bedrock,gauthierm/bedrock,gauthierm/bedrock,alexgibson/bedrock,sgarrity/bedrock,l-hedgehog/bedrock,mkmelin/bedrock,flodolo/bedrock,Sancus/bedrock,analytics-pros/mozilla-bedrock,glogiotatidis/bedrock,gauthierm/bedrock,craigcook/bedrock,mozilla/bedrock,alexgibson/bedrock,mermi/bedrock,hoosteeno/... |
62febcd8d6fcefdf2db3f411807fcf96c91228b8 | tests/example_app.py | tests/example_app.py | # -*- coding: utf-8 -*-
"""
example app to test running an app as subprocess within pty
"""
from __future__ import print_function, unicode_literals
import time
# http://stackoverflow.com/questions/287871/print-in-terminal-with-colors-using-python
class bcolors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGRE... | # -*- coding: utf-8 -*-
"""
example app to test running an app as subprocess within pty
"""
from __future__ import print_function, unicode_literals
import sys, time
PY3 = sys.version_info[0] >= 3
if PY3:
raw_input = input
# http://stackoverflow.com/questions/287871/print-in-terminal-with-colors-using-python
cl... | Define raw_input as input under Python 3 | Define raw_input as input under Python 3
| Python | mit | finklabs/inquirer,finklabs/whaaaaat |
a0f09e23dd19f0cf223034f9b787a4f038cd995d | testsuite/driver/my_typing.py | testsuite/driver/my_typing.py | """
This module provides some type definitions and backwards compatibility shims
for use in the testsuite driver.
The testsuite driver can be typechecked using mypy [1].
[1] http://mypy-lang.org/
"""
try:
from typing import *
import typing
except:
# The backwards compatibility stubs must live in another... | """
This module provides some type definitions and backwards compatibility shims
for use in the testsuite driver.
The testsuite driver can be typechecked using mypy [1].
[1] http://mypy-lang.org/
"""
try:
from typing import *
import typing
except:
# The backwards compatibility stubs must live in another... | Simplify Python <3.5 fallback for TextIO | testsuite: Simplify Python <3.5 fallback for TextIO
(cherry picked from commit d092d8598694c23bc07cdcc504dff52fa5f33be1)
| Python | bsd-3-clause | sdiehl/ghc,sdiehl/ghc,sdiehl/ghc,sdiehl/ghc,sdiehl/ghc,sdiehl/ghc,sdiehl/ghc |
63fd5cf2c05f1b3e343e315184d99c3b46ed0a33 | Functions/Leave.py | Functions/Leave.py | '''
Created on Dec 20, 2011
@author: Tyranic-Moron
'''
from IRCMessage import IRCMessage
from IRCResponse import IRCResponse, ResponseType
from Function import Function
import GlobalVars
import re
class Instantiate(Function):
Help = "leave/gtfo - makes the bot leave the current channel"
def GetResponse(sel... | '''
Created on Dec 20, 2011
@author: Tyranic-Moron
'''
from IRCMessage import IRCMessage
from IRCResponse import IRCResponse, ResponseType
from Function import Function
import GlobalVars
import re
class Instantiate(Function):
Help = "leave/gtfo - makes the bot leave the current channel"
def GetResponse(sel... | Update list of channels when leaving one. | Update list of channels when leaving one.
| Python | mit | HubbeKing/Hubbot_Twisted |
0aa9b8e4cb9cf542a0eaed81664d6c2bb310c19d | enthought/traits/ui/editors/date_editor.py | enthought/traits/ui/editors/date_editor.py | #------------------------------------------------------------------------------
#
# Copyright (c) 2008, Enthought, Inc.
# All rights reserved.
#
# This software is provided without warranty under the terms of the BSD
# license included in enthought/LICENSE.txt and may be redistributed only
# under the conditions... | #------------------------------------------------------------------------------
#
# Copyright (c) 2008, Enthought, Inc.
# All rights reserved.
#
# This software is provided without warranty under the terms of the BSD
# license included in enthought/LICENSE.txt and may be redistributed only
# under the conditions... | Add inter-month padding trait to factory. | Add inter-month padding trait to factory.
| Python | bsd-3-clause | burnpanck/traits,burnpanck/traits |
67ab3d4565fe2467c2eb58e77176fd0ccf7d1d65 | estmator_project/estmator_project/views.py | estmator_project/estmator_project/views.py | from django.contrib.auth.decorators import login_required
from django.http import HttpResponse, HttpResponseNotAllowed
from django.shortcuts import render
from django.views.generic import TemplateView
from est_client.forms import ClientCreateForm
from est_quote.forms import QuoteCreateForm, ClientListForm
class Inde... | from django.contrib.auth.decorators import login_required
from django.http import HttpResponse, HttpResponseNotAllowed
from django.shortcuts import render
from django.views.generic import TemplateView
from est_client.forms import (ClientCreateForm, CompanyCreateForm,
CompanyListForm)
from... | Add new company forms to menu view | Add new company forms to menu view
| Python | mit | Estmator/EstmatorApp,Estmator/EstmatorApp,Estmator/EstmatorApp |
72c4a1285eac5f70dfae243e911e0ab3c540d870 | sconsole/static.py | sconsole/static.py | '''
Holds static data components, like the palette
'''
def get_palette(theme='std'):
'''
Return the preferred palette theme
Themes:
std
The standard theme used by the console
'''
if theme == 'bright':
return [
('banner', 'white', 'dark blue')
]
... | '''
Holds static data components, like the palette
'''
def msg(msg, logfile='console_log.txt'):
'''
Send a message to a logfile, defaults to console_log.txt.
This is useful to replace a print statement since curses does put
a bit of a damper on this
'''
with open(logfile, 'a+') as fp_:
... | Add a logmsg utility function | Add a logmsg utility function
| Python | apache-2.0 | saltstack/salt-console |
f0a143065981d2dcee9ceacd3c2f30cfeb073025 | tx_salaries/search_indexes.py | tx_salaries/search_indexes.py | from haystack import indexes
from tx_salaries.models import Employee
class EmployeeIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
content_auto = indexes.EdgeNgramField(model_attr='position__person__name')
compensation = indexes.FloatField(model_at... | from haystack import indexes
from tx_salaries.models import Employee
class EmployeeIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
content_auto = indexes.EdgeNgramField(model_attr='position__person__name')
compensation = indexes.FloatField(model_at... | Index posts instead of employee titles to fix search results | Index posts instead of employee titles to fix search results
| Python | apache-2.0 | texastribune/tx_salaries,texastribune/tx_salaries |
7462a6da95443606c4219a6b2ccb8cf422f94037 | orges/test/integration/test_main.py | orges/test/integration/test_main.py | from nose.tools import eq_
from orges.invoker.simple import SimpleInvoker
from orges.invoker.pluggable import PluggableInvoker
from orges.main import custom_optimize
from orges.optimizer.gridsearchoptimizer import GridSearchOptimizer
import orges.test.utils as utils
def test_custom_optimize_running_too_long_aborts(... | from nose.tools import eq_
# from orges.invoker.simple import SimpleInvoker
from orges.invoker.multiprocess import MultiProcessInvoker
from orges.invoker.pluggable import PluggableInvoker
from orges.main import custom_optimize
from orges.optimizer.gridsearchoptimizer import GridSearchOptimizer
import orges.test.util... | Change test to use MultiProcessInvoker | Change test to use MultiProcessInvoker
| Python | bsd-3-clause | cigroup-ol/metaopt,cigroup-ol/metaopt,cigroup-ol/metaopt |
916441874a3bca016e950557230f7b3a84b3ee97 | packages/grid/backend/grid/utils.py | packages/grid/backend/grid/utils.py | # stdlib
from typing import Any
from typing import Optional
# third party
from nacl.signing import SigningKey
# syft absolute
from syft import flags
from syft.core.common.message import SyftMessage
from syft.core.io.address import Address
from syft.core.node.common.action.exception_action import ExceptionMessage
from... | # stdlib
from typing import Any
from typing import Optional
# third party
from nacl.signing import SigningKey
# syft absolute
from syft.core.common.message import SyftMessage
from syft.core.io.address import Address
from syft.core.node.common.action.exception_action import ExceptionMessage
from syft.lib.python.dict i... | Replace SyftClient calls -> Direct Node calls - This avoids to build client ast for every single request making the backend faster | Replace SyftClient calls -> Direct Node calls
- This avoids to build client ast for every single request
making the backend faster
| Python | apache-2.0 | OpenMined/PySyft,OpenMined/PySyft,OpenMined/PySyft,OpenMined/PySyft |
51b1f612ab8058da89cc8aaa6b1db99139c7eda0 | versions/settings.py | versions/settings.py | from django.conf import settings
from django.utils import importlib
def import_from_string(val, setting_name):
"""
Attempt to import a class from a string representation.
Based on the method of the same name in Django Rest Framework.
"""
try:
parts = val.split('.')
module_path, cla... | from django.conf import settings
import importlib
def import_from_string(val, setting_name):
"""
Attempt to import a class from a string representation.
Based on the method of the same name in Django Rest Framework.
"""
try:
parts = val.split('.')
module_path, class_name = '.'.join... | Use python 2.7+ standard importlib instead of deprecated django importlib | Use python 2.7+ standard importlib instead of deprecated django importlib
| Python | apache-2.0 | swisscom/cleanerversion,anfema/cleanerversion,anfema/cleanerversion,pretix/cleanerversion,pretix/cleanerversion,swisscom/cleanerversion,swisscom/cleanerversion,pretix/cleanerversion,anfema/cleanerversion |
befce70e7931f5949a7db10af4bae2cb4c21ba08 | localore/people/wagtail_hooks.py | localore/people/wagtail_hooks.py | from wagtailmodeladmin.options import ModelAdmin, wagtailmodeladmin_register
from .models import Person
class PeopleAdmin(ModelAdmin):
model = Person
menu_icon = 'group'
menu_label = 'Team'
menu_order = 300
list_display = ('first_name', 'last_name', 'production', 'role')
list_filter = ('role',... | from wagtailmodeladmin.options import ModelAdmin, wagtailmodeladmin_register
from .models import Person
class PeopleAdmin(ModelAdmin):
model = Person
menu_icon = 'group'
menu_label = 'Team'
menu_order = 300
list_display = ('first_name', 'last_name', 'production', 'role')
list_filter = ('role',... | Order people by associated production. | Order people by associated production.
| Python | mpl-2.0 | ghostwords/localore,ghostwords/localore,ghostwords/localore |
19f86127b5c1b738684f493354b2f532f0f58634 | tests/test-recipes/metadata/always_include_files_glob/run_test.py | tests/test-recipes/metadata/always_include_files_glob/run_test.py | import os
import sys
import json
def main():
prefix = os.environ['PREFIX']
info_file = os.path.join(prefix, 'conda-meta',
'always_include_files_regex-0.1-0.json')
with open(info_file, 'r') as fh:
info = json.load(fh)
if sys.platform == 'darwin':
assert sor... | import os
import sys
import json
def main():
prefix = os.environ['PREFIX']
info_file = os.path.join(prefix, 'conda-meta',
'always_include_files_regex-0.1-0.json')
with open(info_file, 'r') as fh:
info = json.load(fh)
if sys.platform == 'darwin':
assert sor... | Check for sys.platform == linux, not linux2 | Check for sys.platform == linux, not linux2
| Python | bsd-3-clause | sandhujasmine/conda-build,shastings517/conda-build,rmcgibbo/conda-build,mwcraig/conda-build,sandhujasmine/conda-build,sandhujasmine/conda-build,rmcgibbo/conda-build,shastings517/conda-build,dan-blanchard/conda-build,dan-blanchard/conda-build,ilastik/conda-build,mwcraig/conda-build,shastings517/conda-build,ilastik/conda... |
8cb4f5d8879c573a4fe690c4f53c2b0a99d18d69 | nbresuse/handlers.py | nbresuse/handlers.py | import os
import json
import psutil
from notebook.utils import url_path_join
from notebook.base.handlers import IPythonHandler
def get_metrics():
cur_process = psutil.Process()
all_processes = [cur_process] + cur_process.children(recursive=True)
rss = sum([p.memory_info().rss for p in all_processes])
r... | import os
import json
import psutil
from notebook.utils import url_path_join
from notebook.base.handlers import IPythonHandler
def get_metrics():
cur_process = psutil.Process()
all_processes = [cur_process] + cur_process.children(recursive=True)
rss = sum([p.memory_info().rss for p in all_processes])
m... | Handle case of memory limit not set. | Handle case of memory limit not set.
| Python | bsd-2-clause | yuvipanda/nbresuse,yuvipanda/nbresuse |
3fa14c2c1663fe04301b4f98cc59f2d385d8f876 | config/database.py | config/database.py | databases = {
'mysql': {
'driver': 'mysql',
'host': '',
'database': '',
'user': '',
'password': '',
'prefix': ''
}
}
| databases = {
'mysql': {
'driver': 'mysql',
'host': '127.0.0.1',
'database': 'salam_bot',
'user': 'root',
'password': '',
'prefix': ''
}
}
| Change db configs to default for CI | Change db configs to default for CI
| Python | mit | erjanmx/salam-bot |
15dd5b534e8c16c78195739eb78cc1e271564542 | symcalc.py | symcalc.py | from sympy.abc import *
from flask import Flask, request
app = Flask(__name__)
@app.route('/code', methods=['GET', 'POST'])
def code():
return str(eval(request.json['code']))
if __name__ == "__main__":
app.run(debug=True, port=80)
| from sympy.abc import *
from sympy.core.symbol import Symbol
while True:
try:
line = input('')
print()
if '=' in line:
exec(line)
else:
_ = eval(line)
print(_)
except EOFError:
continue
except Exception as e:
print('Error:'... | Use local console input to drive the calc | Use local console input to drive the calc
| Python | mit | boppreh/symcalc |
13ba81df82f2c43838066ec9cd0fa1222324349f | srsly/util.py | srsly/util.py | # coding: utf8
from __future__ import unicode_literals
from pathlib import Path
import sys
def force_path(location, require_exists=True):
if not isinstance(location, Path):
location = Path(location)
if require_exists and not location.exists():
raise ValueError("Can't read file: {}".format(loc... | # coding: utf8
from __future__ import unicode_literals
from pathlib import Path
import sys
is_python2 = sys.version_info[0] == 2
is_python3 = sys.version_info[0] == 3
if is_python2:
basestring_ = basestring # noqa: F821
else:
basestring_ = str
def force_path(location, require_exists=True):
if not isi... | Improve compat handling in force_string | Improve compat handling in force_string
If we know we already have a string, no need to force it into a strinbg
| Python | mit | explosion/srsly,explosion/srsly,explosion/srsly,explosion/srsly |
74815ade33a3e9e76da43e01e74752ff502e99d1 | datadict/datadict_utils.py | datadict/datadict_utils.py | import pandas as pd
def load_datadict(filepath, trim_index=True, trim_all=False):
df = pd.read_csv(filepath, index_col=0)
if trim_index:
df.index = df.index.str.strip()
if trim_all:
df = df.applymap(lambda x: x.strip() if type(x) is str else x)
return df
def insert_rows_at(main_df, ind... | import pandas as pd
def load_datadict(filepath, trim_index=True, trim_all=False):
df = pd.read_csv(filepath, index_col=0)
if trim_index:
df.index = df.index.to_series().str.strip()
if trim_all:
df = df.applymap(lambda x: x.strip() if type(x) is str else x)
return df
def insert_rows_at(... | Fix issue where pandas.Index doesn't have str method | Fix issue where pandas.Index doesn't have str method
(Index.str was only introduced in pandas 0.19.2)
| Python | bsd-3-clause | sibis-platform/ncanda-data-integration,sibis-platform/ncanda-datacore,sibis-platform/ncanda-datacore,sibis-platform/ncanda-datacore,sibis-platform/ncanda-data-integration |
fc7c52a489a6113b7b26607c42c6f5b38b2feb85 | manage.py | manage.py | import os
import coverage
from flask_script import Manager, Shell
from flask_migrate import Migrate, MigrateCommand
from config import basedir
from app import create_app, db
from app.models import User
app = create_app(os.getenv("MYDICTIONARY_CONFIG") or "default")
migrate = Migrate(app, db)
manager = Manager(app)
... | import os
import coverage
from flask_script import Manager, Shell
from flask_migrate import Migrate, MigrateCommand
from config import basedir
from app import create_app, db
from app.models import User, Dictionary
app = create_app(os.getenv("MYDICTIONARY_CONFIG") or "default")
migrate = Migrate(app, db)
manager = Ma... | Add Dictionary to shell context | Add Dictionary to shell context
| Python | mit | Encrylize/MyDictionary,Encrylize/MyDictionary,Encrylize/MyDictionary |
24e48a82c627996332a73608d139f9ce8713642d | cref/app/web/views.py | cref/app/web/views.py | import flask
from cref.app.web import app
from cref.app.web.tasks import predict_structure
def success(result):
return flask.jsonify({
'status': 'success',
'retval': result
})
def failure(reason='Unknown'):
return flask.jsonify({
'status': 'failure',
'reason': reason
... | import flask
from cref.app.web import app
from cref.app.web.tasks import predict_structure
def success(result):
return flask.jsonify({
'status': 'success',
'retval': result
})
def failure(reason='Unknown'):
return flask.jsonify({
'status': 'failure',
'reason': reason
... | Add method to serve prediction result files | Add method to serve prediction result files
| Python | mit | mchelem/cref2,mchelem/cref2,mchelem/cref2 |
f2d6c7781ab1555cc3392ff9a642a2cb208580f8 | mail/views.py | mail/views.py | from django.shortcuts import redirect
from django.http import JsonResponse
from django.core.mail import EmailMessage
from django.middleware import csrf
from rest_framework.decorators import api_view
@api_view(['POST', 'GET'])
def send_contact_message(request):
if request.method == 'POST':
to_address = re... | from django.shortcuts import redirect
from django.http import JsonResponse
from django.core.mail import EmailMessage
from django.middleware import csrf
from rest_framework.decorators import api_view
@api_view(['POST', 'GET'])
def send_contact_message(request):
if request.method == 'POST':
to_address = re... | Revert "change to field for testing" | Revert "change to field for testing"
| Python | agpl-3.0 | openstax/openstax-cms,openstax/openstax-cms,openstax/openstax-cms,openstax/openstax-cms,Connexions/openstax-cms,Connexions/openstax-cms |
161cdf644aa9b8575f42dab537c5e3e01a186ec6 | test/python_api/default-constructor/sb_address.py | test/python_api/default-constructor/sb_address.py | """
Fuzz tests an object after the default construction to make sure it does not crash lldb.
"""
import sys
import lldb
def fuzz_obj(obj):
obj.GetFileAddress()
obj.GetLoadAddress(lldb.SBTarget())
obj.SetLoadAddress(0xffff, lldb.SBTarget())
obj.OffsetAddress(sys.maxint)
obj.GetDescription(lldb.SBSt... | """
Fuzz tests an object after the default construction to make sure it does not crash lldb.
"""
import sys
import lldb
def fuzz_obj(obj):
obj.GetFileAddress()
obj.GetLoadAddress(lldb.SBTarget())
obj.SetLoadAddress(0xffff, lldb.SBTarget())
obj.OffsetAddress(sys.maxint)
obj.GetDescription(lldb.SBSt... | Add new SBAddress APIs to the fuzz tests. | Add new SBAddress APIs to the fuzz tests.
git-svn-id: b33bab8abb5b18c12ee100cd7761ab452d00b2b0@137625 91177308-0d34-0410-b5e6-96231b3b80d8
| Python | apache-2.0 | llvm-mirror/lldb,llvm-mirror/lldb,apple/swift-lldb,llvm-mirror/lldb,llvm-mirror/lldb,apple/swift-lldb,apple/swift-lldb,llvm-mirror/lldb,apple/swift-lldb,apple/swift-lldb,apple/swift-lldb |
70e7b932c1c6013306a53f47c14d969d4ada8ab4 | api/home/models.py | api/home/models.py | from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.db import models
POSITIONS = (
('HERO', 'Hero'),
('SEC_1', 'Secondary 1'),
('SEC_2', 'Secondary 2'),
('THIRD_1', 'Third 1'),
('THIRD_2', 'Third 2'),
('THIRD_3'... | from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.db import models
POSITIONS = (
('HERO', 'Hero'),
('SEC_1', 'Secondary 1'),
('SEC_2', 'Secondary 2'),
('THIRD_1', 'Third 1'),
('THIRD_2', 'Third 2'),
('THIRD_3'... | Allow overrides to be blank | Allow overrides to be blank
| Python | mit | urfonline/api,urfonline/api,urfonline/api |
cdf3686150309800cb28f584b64b9175aa4b5662 | tests/unit_tests/gather_tests/MameSink_test.py | tests/unit_tests/gather_tests/MameSink_test.py | import pytest
from cps2_zmq.gather import MameSink
@pytest.mark.parametrize("message, expected",[
({'wid': 420, 'message': 'closing'}, 'worksink closing'),
({'wid': 420, 'message': 'threaddead'}, '420 is dead'),
({'wid': 420, 'message': 'some result'}, 'another message'),
])
def test_process_message(messag... | import pytest
from cps2_zmq.gather import MameSink
@pytest.fixture(scope="module")
def sink():
sink = MameSink.MameSink("inproc://frommockworkers")
yield sink
sink.cleanup()
class TestSink(object):
@pytest.fixture(autouse=True)
def refresh(self, sink):
pass
yield
sink._msgs... | Test Class now returns to base state between different groups of tests | Test Class now returns to base state between different groups of tests
| Python | mit | goosechooser/cps2-zmq |
8ecc9ec44437fea301ab8bdf6ed8b9b9a2a5c242 | IPython/zmq/pylab/backend_payload_svg.py | IPython/zmq/pylab/backend_payload_svg.py | # Standard library imports
from cStringIO import StringIO
# System library imports.
from matplotlib.backends.backend_svg import new_figure_manager
from matplotlib._pylab_helpers import Gcf
# Local imports.
from backend_payload import add_plot_payload
def show():
""" Deliver a SVG payload.
"""
figure_man... | """Produce SVG versions of active plots for display by the rich Qt frontend.
"""
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
# Standard library imports
from cStringIO import StringIO
# System li... | Fix svg rich backend to correctly show multiple figures. | Fix svg rich backend to correctly show multiple figures.
| Python | bsd-3-clause | ipython/ipython,ipython/ipython |
d1504f3c3129c926bd9897a6660669f146e64c38 | cachupy/cachupy.py | cachupy/cachupy.py | import datetime
class Cache:
EXPIRE_IN = 'expire_in'
def __init__(self):
self.store = {}
def get(self, key):
"""Gets a value based upon a key."""
self._check_expiry(key)
return self.store[key]['value']
def set(self, dictionary, expire_in):
"""Sets a d... | import datetime
class Cache:
EXPIRE_IN = 'expire_in'
VALUE = 'value'
def __init__(self):
self.lock = False
self.store = {}
def get(self, key):
"""Gets a value based upon a key."""
self._check_expiry(key)
return self.store[key][Cache.VALUE]
def set... | Change signature of set() method. | Change signature of set() method.
| Python | mit | patrickbird/cachupy |
a470ce2a7557216be5cb36cdf3d895ea486e6d64 | src/testers/tls.py | src/testers/tls.py | # -*- coding: utf-8 -*-
import ssl
from src.testers.decorators import requires_userinfo
@requires_userinfo
def available(test):
"""
Check if MongoDB is compiled with OpenSSL support
"""
return 'OpenSSLVersion' in test.tester.info \
or 'openssl' in test.tester.info
@requires_userinfo
def... | # -*- coding: utf-8 -*-
import ssl
from src.testers.decorators import requires_userinfo
@requires_userinfo
def available(test):
"""
Check if MongoDB is compiled with OpenSSL support
"""
return 'OpenSSLVersion' in test.tester.info \
or 'openssl' in test.tester.info
@requires_userinfo
def... | Fix ServerSelectionTimeoutError: No servers found yet | Fix ServerSelectionTimeoutError: No servers found yet
| Python | mit | stampery/mongoaudit |
36e00778befd9e6763236b771a77184d31c3c885 | babbage_fiscal/tasks.py | babbage_fiscal/tasks.py | from celery import Celery
import requests
from .config import get_engine, _set_connection_string
from .loader import FDPLoader
app = Celery('fdp_loader')
app.config_from_object('babbage_fiscal.celeryconfig')
@app.task
def load_fdp_task(package, callback, connection_string=None):
if connection_string is not None:... | from celery import Celery
import requests
from .config import get_engine, _set_connection_string
from .loader import FDPLoader
app = Celery('fdp_loader')
app.config_from_object('babbage_fiscal.celeryconfig')
@app.task
def load_fdp_task(package, callback, connection_string=None):
if connection_string is not None:... | Add more info to the callback | Add more info to the callback
| Python | mit | openspending/babbage.fiscal-data-package |
5089846e116fdd386de692f187f7c03304cfcd1d | attachments_to_filesystem/__openerp__.py | attachments_to_filesystem/__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 ... | # -*- 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 ... | Add Odoo Community Association (OCA) in authors | Add Odoo Community Association (OCA) in authors
| Python | agpl-3.0 | xpansa/knowledge,Endika/knowledge,sergiocorato/knowledge,algiopensource/knowledge,anas-taji/knowledge,acsone/knowledge,acsone/knowledge,ClearCorp-dev/knowledge,xpansa/knowledge,Endika/knowledge,Endika/knowledge,sergiocorato/knowledge,jobiols/knowledge,anas-taji/knowledge,xpansa/knowledge,ClearCorp/knowledge,ClearCorp-d... |
6973cc19a9d4fb4e0867a98fced1c4c33fc0cee8 | students/psbriant/session08/test_circle.py | students/psbriant/session08/test_circle.py | """
Name: Paul Briant
Date: 11/22/16
Class: Introduction to Python
Session: 08
Assignment: circle lab
Description:
Tests for Circle lab
"""
# -------------------------------Imports----------------------------------------
import math
from circle import Circle
# -------------------------------Functions-----------------... | """
Name: Paul Briant
Date: 11/22/16
Class: Introduction to Python
Session: 08
Assignment: circle lab
Description:
Tests for Circle lab
"""
# -------------------------------Imports----------------------------------------
import math
from circle import Circle
# -------------------------------Functions-----------------... | Add test for area property of circle. | Add test for area property of circle.
| Python | unlicense | weidnem/IntroPython2016,UWPCE-PythonCert/IntroPython2016,weidnem/IntroPython2016,UWPCE-PythonCert/IntroPython2016,UWPCE-PythonCert/IntroPython2016,weidnem/IntroPython2016 |
24fd3b98f06b30d8827ba472dc305514ed71a5e5 | cropimg/widgets.py | cropimg/widgets.py | from django.forms.widgets import Input, ClearableFileInput
from django.template.loader import render_to_string
class CIImgWidget(ClearableFileInput):
def render(self, name, value, attrs=None):
try:
attrs["data-value"] = getattr(value, "url", "")
except ValueError: # attribute has no f... | from django.forms.widgets import Input, ClearableFileInput
from django.template.loader import render_to_string
class CIImgWidget(ClearableFileInput):
def render(self, name, value, attrs=None):
try:
attrs["data-value"] = getattr(value, "url", "")
except ValueError: # attribute has no f... | Make compatible with Django >2.1 | Make compatible with Django >2.1
| Python | mit | rewardz/cropimg-django,rewardz/cropimg-django,rewardz/cropimg-django |
eacc66e5a9ab3310c75924dcb340e4944e9424d4 | tests/specifications/external_spec_test.py | tests/specifications/external_spec_test.py | from fontbakery.checkrunner import Section
from fontbakery.fonts_spec import spec_factory
def check_filter(checkid, font=None, **iterargs):
if checkid in (
"com.google.fonts/check/035", # ftxvalidator
"com.google.fonts/check/036", # ots-sanitize
"com.google.fonts/check/037", # Font Validator
... | from fontbakery.checkrunner import Section
from fontbakery.fonts_spec import spec_factory
def check_filter(checkid, font=None, **iterargs):
if checkid in (
"com.google.fonts/check/035", # ftxvalidator
"com.google.fonts/check/036", # ots-sanitize
"com.google.fonts/check/037", # Font Validator
... | Test for expected and unexpected checks | Test for expected and unexpected checks
| Python | apache-2.0 | googlefonts/fontbakery,graphicore/fontbakery,graphicore/fontbakery,googlefonts/fontbakery,googlefonts/fontbakery,moyogo/fontbakery,moyogo/fontbakery,moyogo/fontbakery,graphicore/fontbakery |
6adbbe71dcde926fbd9288b4a43b45ff1a339cdc | turbustat/statistics/stats_utils.py | turbustat/statistics/stats_utils.py |
import numpy as np
def hellinger(data1, data2):
'''
Calculate the Hellinger Distance between two datasets.
Parameters
----------
data1 : numpy.ndarray
1D array.
data2 : numpy.ndarray
1D array.
Returns
-------
distance : float
Distance value.
'''
d... |
import numpy as np
def hellinger(data1, data2):
'''
Calculate the Hellinger Distance between two datasets.
Parameters
----------
data1 : numpy.ndarray
1D array.
data2 : numpy.ndarray
1D array.
Returns
-------
distance : float
Distance value.
'''
d... | Move KL Div to utils file | Move KL Div to utils file
| Python | mit | e-koch/TurbuStat,Astroua/TurbuStat |
cd219d5ee0ecbd54705c5add4239cef1513b8c2a | dodocs/__init__.py | dodocs/__init__.py | """Main function
Copyright (c) 2015 Francesco Montesano
MIT Licence
"""
import sys
import colorama
from dodocs.cmdline import parse
__version__ = "0.0.1"
colorama.init(autoreset=True)
def main(argv=None):
"""
Main code
Parameters
----------
argv : list of strings, optional
command l... | """Main function
Copyright (c) 2015 Francesco Montesano
MIT Licence
"""
import sys
import colorama
from dodocs.cmdline import parse
__version__ = "0.0.1"
colorama.init(autoreset=True)
def main(argv=None):
"""
Main code
Parameters
----------
argv : list of strings, optional
command l... | Use args.func. Deal with failures, default "profile' | Use args.func. Deal with failures, default "profile'
| Python | mit | montefra/dodocs |
f8b28c73e0bb46aaa760d4c4afadd75feacbe57a | tools/benchmark/benchmark_date_guessing.py | tools/benchmark/benchmark_date_guessing.py | #!/usr/bin/env python
import os
import pytest
import sys
from mediawords.tm.guess_date import guess_date, McGuessDateException
def main():
if (len(sys.argv) < 2):
sys.stderr.write('usage: ' + sys.argv[0] + ' <directory of html files>')
exit()
directory = os.fsencode(sys.argv[1]).decode("utf-... | #!/usr/bin/env python3
import os
import sys
from mediawords.tm.guess_date import guess_date
def benchmark_date_guessing():
"""Benchmark Python date guessing code."""
if len(sys.argv) < 2:
sys.exit("Usage: %s <directory of html files>" % sys.argv[0])
directory = sys.argv[1]
for file in os.l... | Clean up date guessing benchmarking code | Clean up date guessing benchmarking code
* Remove unused imports
* use sys.exit(message) instead of exit()
* Use Pythonic way to call main function (if __name__ == '__main__')
* Reformat code
* Avoid encoding / decoding things to / from UTF-8
| Python | agpl-3.0 | berkmancenter/mediacloud,berkmancenter/mediacloud,berkmancenter/mediacloud,berkmancenter/mediacloud,berkmancenter/mediacloud |
a459c9bd1135ede49e9b2f55a633f86d7cdb81e2 | tests/mocks/RPi.py | tests/mocks/RPi.py | # -*- coding: utf-8 -*-
"""
Mocks for tests on other HW than Raspberry Pi.
"""
class GPIO(object):
BOARD = 'board'
IN = 'in'
OUT = 'out'
PUD_UP = 'pud_up'
FALLING = 'falling'
HIGH = 'high'
LOW = 'low'
@classmethod
def setmode(cls, mode):
print("Mock: set GPIO mode {}".fo... | # -*- coding: utf-8 -*-
"""
Mocks for tests on other HW than Raspberry Pi.
"""
class GPIO(object):
BOARD = 'board'
IN = 'in'
OUT = 'out'
PUD_UP = 'pud_up'
FALLING = 'falling'
HIGH = 'high'
LOW = 'low'
@classmethod
def setmode(cls, mode):
print("Mock: set GPIO mode {}".fo... | Remove print message in mocks | Remove print message in mocks
| Python | mit | werdeil/pibooth,werdeil/pibooth |
7e015e6955dfe392649b5ca0cdeb5a7701700f24 | laalaa/apps/advisers/serializers.py | laalaa/apps/advisers/serializers.py | from rest_framework import serializers
from rest_framework_gis import serializers as gis_serializers
from .models import Location, Office, Organisation
class DistanceField(serializers.ReadOnlyField):
def to_representation(self, obj):
# miles
return obj.mi
class OrganisationSerializer(serializer... | from rest_framework import serializers
from rest_framework_gis import serializers as gis_serializers
from .models import Location, Office, Organisation
class DistanceField(serializers.ReadOnlyField):
def to_representation(self, obj):
# miles
return obj.mi
class OrganisationSerializer(serializer... | Add list of category codes to offices | Add list of category codes to offices
| Python | mit | ministryofjustice/laa-legal-adviser-api,ministryofjustice/laa-legal-adviser-api,ministryofjustice/laa-legal-adviser-api |
c568f4d3ea475f341490bc81e89c28016e8412a2 | corehq/apps/locations/dbaccessors.py | corehq/apps/locations/dbaccessors.py | from corehq.apps.users.models import CommCareUser
def _users_by_location(location_id, include_docs):
return CommCareUser.view(
'locations/users_by_location_id',
startkey=[location_id],
endkey=[location_id, {}],
include_docs=include_docs,
).all()
def get_users_by_location_id(l... | from corehq.apps.users.models import CommCareUser
def _users_by_location(location_id, include_docs, wrap):
view = CommCareUser.view if wrap else CommCareUser.get_db().view
return view(
'locations/users_by_location_id',
startkey=[location_id],
endkey=[location_id, {}],
include_d... | Allow getting the unwrapped doc | Allow getting the unwrapped doc
| Python | bsd-3-clause | qedsoftware/commcare-hq,dimagi/commcare-hq,puttarajubr/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,puttarajubr/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,puttarajubr/commcare-hq,qedsoftware/commcare-hq,puttarajubr/commcare-hq |
39256f49c952dbd5802d5321c8a74b2c41934e38 | timedelta/__init__.py | timedelta/__init__.py | import os
__version__ = open(os.path.join(os.path.dirname(__file__), "VERSION")).read().strip()
try:
from fields import TimedeltaField
from helpers import (
divide, multiply, modulo,
parse, nice_repr,
percentage, decimal_percentage,
total_seconds
)
except ImportError:
... | import os
__version__ = open(os.path.join(os.path.dirname(__file__), "VERSION")).read().strip()
try:
import django
from fields import TimedeltaField
from helpers import (
divide, multiply, modulo,
parse, nice_repr,
percentage, decimal_percentage,
total_seconds
)
excep... | Fix running on unconfigured virtualenv. | Fix running on unconfigured virtualenv.
| Python | bsd-3-clause | sookasa/django-timedelta-field |
7a7b6351f21c95b3620059984470b0b7619c1e9d | docopt_dispatch.py | docopt_dispatch.py | """Dispatch from command-line arguments to functions."""
import re
from collections import OrderedDict
from docopt import docopt
__all__ = ('dispatch', 'DispatchError')
__author__ = 'Vladimir Keleshev <vladimir@keleshev.com>'
__version__ = '0.0.0'
__license__ = 'MIT'
__keywords__ = 'docopt dispatch function adapter ... | """Dispatch from command-line arguments to functions."""
import re
from collections import OrderedDict
__all__ = ('dispatch', 'DispatchError')
__author__ = 'Vladimir Keleshev <vladimir@keleshev.com>'
__version__ = '0.0.0'
__license__ = 'MIT'
__keywords__ = 'docopt dispatch function adapter kwargs'
__url__ = 'https://... | Load docopt lazily (so that setup.py works) | Load docopt lazily (so that setup.py works)
| Python | mit | keleshev/docopt-dispatch |
e50fdd79a49adce75559ea07024d056b6b386761 | docs/config/all.py | docs/config/all.py | # Global configuration information used across all the
# translations of documentation.
#
# Import the base theme configuration
from cakephpsphinx.config.all import *
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout t... | # Global configuration information used across all the
# translations of documentation.
#
# Import the base theme configuration
from cakephpsphinx.config.all import *
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout t... | Remove pre-release flag as 2.x is mainline now | Remove pre-release flag as 2.x is mainline now
| Python | mit | cakephp/chronos |
0b7686f14f47cc00665cfe3d6a396a5c14e6b9b3 | src/puzzle/heuristics/analyze.py | src/puzzle/heuristics/analyze.py | import collections
from src.puzzle.problems import crossword_problem
_PROBLEM_TYPES = set()
def identify(line):
scores = {}
for t in _PROBLEM_TYPES:
score = t.score(line)
if score:
scores[t] = t.score(line)
# Return sorted values, highest first.
return collections.OrderedDict(
sorted(sc... | from src.data import meta
from src.puzzle.problems import crossword_problem
_PROBLEM_TYPES = set()
def identify(line):
scores = meta.Meta()
for t in _PROBLEM_TYPES:
score = t.score(line)
if score:
scores[t] = t.score(line)
return scores
def identify_all(lines):
return map(identify, lines)
... | Switch identify to Meta object. | Switch identify to Meta object.
| Python | mit | PhilHarnish/forge,PhilHarnish/forge,PhilHarnish/forge,PhilHarnish/forge,PhilHarnish/forge,PhilHarnish/forge |
8e608c2155a4a466f1a4bf87df05c4e4ebd90c1c | django/__init__.py | django/__init__.py | VERSION = (1, 0, 'post-release-SVN')
def get_version():
"Returns the version as a human-format string."
v = '.'.join([str(i) for i in VERSION[:-1]])
if VERSION[-1]:
from django.utils.version import get_svn_revision
v = '%s-%s-%s' % (v, VERSION[-1], get_svn_revision())
return v
| VERSION = (1, 1, 0, 'alpha', 0)
def get_version():
version = '%s.%s' % (VERSION[0], VERSION[1])
if VERSION[2]:
version = '%s.%s' % (version, VERSION[2])
if VERSION[3:] == ('alpha', 0):
version = '%s pre-alpha' % version
else:
version = '%s %s' % (version, VERSION[3])
if ... | Update django.VERSION in trunk per previous discussion | Update django.VERSION in trunk per previous discussion
git-svn-id: 4f9f921b081c523744c7bf24d959a0db39629563@9103 bcc190cf-cafb-0310-a4f2-bffc1f526a37
| Python | bsd-3-clause | blindroot/django,lsqtongxin/django,jgoclawski/django,blighj/django,fenginx/django,riklaunim/django-custom-multisite,jn7163/django,alrifqi/django,ryangallen/django,charettes/django,eugena/django,AndrewGrossman/django,yakky/django,eugena/django,denys-duchier/django,EliotBerriot/django,dwightgunning/django,hassanabidpk/dj... |
5daf394146660b28d5d51795e5220729a9836347 | babyonboard/api/tests/test_models.py | babyonboard/api/tests/test_models.py | from django.test import TestCase
from ..models import Temperature, HeartBeats
class TemperatureTest(TestCase):
"""Test class for temperature model"""
def setUp(self):
Temperature.objects.create(temperature=20.5)
def test_create_temperature(self):
temperature = Temperature.objects.get(tem... | from django.test import TestCase
from ..models import Temperature, HeartBeats, Breathing
class TemperatureTest(TestCase):
"""Test class for temperature model"""
def setUp(self):
Temperature.objects.create(temperature=20.5)
def test_create_temperature(self):
temperature = Temperature.obje... | Implement tests for breathing model | Implement tests for breathing model
| Python | mit | BabyOnBoard/BabyOnBoard-API,BabyOnBoard/BabyOnBoard-API |
9b8f1dc59b528c57122c6bebef52cfe0545fa3a5 | virtual_machine.py | virtual_machine.py | class VirtualMachine:
def __init__(self, ram_size=256, stack_size=32):
self.data = [None]*ram_size
self.stack = [None]*stack_size
self.stack_size = stack_size
self.stack_top = 0
def push(self, value):
"""Push something onto the stack."""
if self.stack_top+1 > sel... | class VirtualMachine:
def __init__(self, bytecodes, ram_size=256, stack_size=32, executing=True):
self.bytecodes = bytecodes
self.data = [None]*ram_size
self.stack = [None]*stack_size
self.stack_size = stack_size
self.stack_top = 0
self.executing = executing
s... | Add run() to the vm, which iterates through all the bytecodes and executes them | Add run() to the vm, which iterates through all the bytecodes and executes them
| Python | bsd-3-clause | darbaga/simple_compiler |
44c74743d25b1fa15d1cb1337f2c4e2d306ac6da | virtual_machine.py | virtual_machine.py | class VirtualMachine:
def __init__(self, ram_size=256, executing=True):
self.data = [None]*ram_size
self.stack = []
self.executing = executing
self.pc = 0
def push(self, value):
"""Push something onto the stack."""
self.stack += [value]
def pop(self):
... | class VirtualMachine:
def __init__(self, ram_size=512, executing=True):
self.data = {i: None for i in range(ram_size)}
self.stack = []
self.executing = executing
self.pc = 0
self.devices_start = 256
def push(self, value):
"""Push something onto the stack."""
... | Add facilities to register virtual devices with the vm | Add facilities to register virtual devices with the vm
| Python | bsd-3-clause | darbaga/simple_compiler |
69742860652f84fccf0bac80f0e72bb03ddf64b1 | eve_proxy/tasks.py | eve_proxy/tasks.py | from django.conf import settings
import logging
from datetime import datetime, timedelta
from celery.decorators import task
from eve_proxy.models import CachedDocument
@task(ignore_result=True)
def clear_stale_cache(cache_extension=0):
log = clear_stale_cache.get_logger()
time = datetime.utcnow() - timedelta(... | from django.conf import settings
import logging
from datetime import datetime, timedelta
from celery.decorators import task
from eve_proxy.models import CachedDocument, ApiAccessLog
@task(ignore_result=True)
def clear_stale_cache(cache_extension=0):
log = clear_stale_cache.get_logger()
time = datetime.utcnow(... | Fix the log autoclean job | Fix the log autoclean job
| Python | bsd-3-clause | nikdoof/test-auth |
13b4d336f5556be0210b703aaee05e3b5224fb05 | tests/GIR/test_001_connection.py | tests/GIR/test_001_connection.py | # coding=utf-8
import sys
import struct
import unittest
from test_000_config import TestConfig
from gi.repository import Midgard, GObject
class TestConnection(Midgard.Connection):
def __init__(self):
Midgard.init()
Midgard.Connection.__init__(self)
@staticmethod
def openConnection():
config = Test... | # coding=utf-8
import sys
import struct
import unittest
from test_000_config import TestConfig
from gi.repository import Midgard, GObject
class TestConnection(Midgard.Connection):
def __init__(self):
Midgard.init()
Midgard.Connection.__init__(self)
@staticmethod
def openConnection():
config = Test... | Return Midgard.Connection if one is opened. None otherwise | Return Midgard.Connection if one is opened. None otherwise
| Python | lgpl-2.1 | midgardproject/midgard-core,piotras/midgard-core,midgardproject/midgard-core,piotras/midgard-core,midgardproject/midgard-core,piotras/midgard-core,piotras/midgard-core,midgardproject/midgard-core |
bdcfb1ff4c076485a5fc3b00beaf81becec0717b | tests/utils/DependencyChecker.py | tests/utils/DependencyChecker.py | # -*- coding: utf-8 -*-
import subprocess as subp
class DependencyChecker(object):
def _check_test_dependencies(self):
for dep in self.DEPENDENCIES:
cmd = 'if hash {} 2/dev/null; then ' \
'echo 1; else echo 0; fi'.format(dep)
available = subp.check_output(cmd, s... | # -*- coding: utf-8 -*-
import sys
import subprocess as subp
class DependencyChecker(object):
def _check_test_dependencies(self):
for dep in self.DEPENDENCIES:
cmd = 'if hash {} 2/dev/null; then ' \
'echo 1; else echo 0; fi'.format(dep)
available = subp.check_ou... | Fix binary to str conversion | release/0.6.2: Fix binary to str conversion
| Python | bsd-3-clause | nok/sklearn-porter |
1f59870fd321be570ce6cfead96307fcc3366e09 | d1lod/tests/test_sesame_interface.py | d1lod/tests/test_sesame_interface.py | import pytest
from d1lod.sesame import Store, Repository, Interface
from d1lod import dataone
def test_interface_can_be_created(interface):
assert isinstance(interface, Interface)
| import pytest
from d1lod.sesame import Store, Repository, Interface
from d1lod import dataone
def test_interface_can_be_created(interface):
assert isinstance(interface, Interface)
def test_can_add_a_dataset():
"""Test whether the right triples are added when we add a known dataset.
We pass the store to... | Add repository test for adding a dataset | Add repository test for adding a dataset
| Python | apache-2.0 | ec-geolink/d1lod,ec-geolink/d1lod,ec-geolink/d1lod,ec-geolink/d1lod |
5b9a76dc525f480a08ccbbedcbb3866faa5a50f3 | django/santropolFeast/member/tests.py | django/santropolFeast/member/tests.py | from django.test import TestCase
from member.models import Member
from datetime import date
class MemberTestCase(TestCase):
def setUp(self):
Member.objects.create(firstname='Katrina', birthdate=date(1980, 4, 19))
def test_age_on_date(self):
"""The age on given date is properly computed"""
... | from django.test import TestCase
from member.models import Member, Client
from datetime import date
class MemberTestCase(TestCase):
def setUp(self):
Member.objects.create(firstname='Katrina', lastname='Heide', birthdate=date(1980, 4, 19))
def test_age_on_date(self):
"""The age on given date ... | Add unit test on __str__ function | Add unit test on __str__ function
| Python | agpl-3.0 | madmath/sous-chef,madmath/sous-chef,savoirfairelinux/sous-chef,savoirfairelinux/santropol-feast,savoirfairelinux/sous-chef,savoirfairelinux/santropol-feast,madmath/sous-chef,savoirfairelinux/santropol-feast,savoirfairelinux/sous-chef |
2e0030966f1f0baed8b9fda5e18cd01d8d0495d5 | src/eduid_common/api/schemas/base.py | src/eduid_common/api/schemas/base.py | # -*- coding: utf-8 -*-
from marshmallow import Schema, fields
__author__ = 'lundberg'
class FluxStandardAction(Schema):
class Meta:
strict = True
type = fields.String(required=True)
payload = fields.Raw(required=False)
error = fields.Boolean(required=False)
meta = fields.Raw(required=... | # -*- coding: utf-8 -*-
from marshmallow import Schema, fields, validates_schema, ValidationError
__author__ = 'lundberg'
class EduidSchema(Schema):
class Meta:
strict = True
@validates_schema(pass_original=True)
def check_unknown_fields(self, data, original_data):
for key in original_... | Add a schema with some functionality to inherit from | Add a schema with some functionality to inherit from
| Python | bsd-3-clause | SUNET/eduid-common |
857cbff1e8ec6e4db4ac25ad10a41311f3afcd66 | pombola/core/migrations/0049_del_userprofile.py | pombola/core/migrations/0049_del_userprofile.py | # encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
from django.db.utils import DatabaseError
from django.contrib.contenttypes.models import ContentType
class Migration(SchemaMigration):
def forwards(self, orm):
# Do the deletes in ... | # encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from south.models import MigrationHistory
from django.db import models
from django.db.utils import DatabaseError
from django.contrib.contenttypes.models import ContentType
class Migration(SchemaMigration):
def forwards... | Delete entries from the South migration history too | Delete entries from the South migration history too
| Python | agpl-3.0 | mysociety/pombola,mysociety/pombola,patricmutwiri/pombola,hzj123/56th,patricmutwiri/pombola,geoffkilpin/pombola,ken-muturi/pombola,mysociety/pombola,patricmutwiri/pombola,hzj123/56th,geoffkilpin/pombola,hzj123/56th,mysociety/pombola,ken-muturi/pombola,hzj123/56th,mysociety/pombola,patricmutwiri/pombola,ken-muturi/pombo... |
df48b6854b8c57cfc48747a266c10a0fc4e78d70 | api/v2/serializers/details/image_version.py | api/v2/serializers/details/image_version.py | from core.models import ApplicationVersion as ImageVersion
from rest_framework import serializers
from api.v2.serializers.summaries import (
LicenseSummarySerializer,
UserSummarySerializer,
IdentitySummarySerializer,
ImageVersionSummarySerializer)
from api.v2.serializers.fields import ProviderMachineRel... | from core.models import ApplicationVersion as ImageVersion
from rest_framework import serializers
from api.v2.serializers.summaries import (
LicenseSummarySerializer,
UserSummarySerializer,
IdentitySummarySerializer,
ImageSummarySerializer,
ImageVersionSummarySerializer)
from api.v2.serializers.fiel... | Add 'image' to the attrs for VersionDetails | Add 'image' to the attrs for VersionDetails
| Python | apache-2.0 | CCI-MOC/GUI-Backend,CCI-MOC/GUI-Backend,CCI-MOC/GUI-Backend,CCI-MOC/GUI-Backend |
ca4cede86022cc7784214cc1823e9b2886e3625b | IPython/nbconvert/exporters/python.py | IPython/nbconvert/exporters/python.py | """Python script Exporter class"""
#-----------------------------------------------------------------------------
# Copyright (c) 2013, the IPython Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#----------... | """Python script Exporter class"""
#-----------------------------------------------------------------------------
# Copyright (c) 2013, the IPython Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#----------... | Make output_mimetype accessible from the class. | Make output_mimetype accessible from the class.
Traitlets are only accessible by instantiating the class. There's no
clear reason that this needs to be a traitlet, anyway.
| Python | bsd-3-clause | cornhundred/ipywidgets,ipython/ipywidgets,jupyter-widgets/ipywidgets,cornhundred/ipywidgets,ipython/ipywidgets,SylvainCorlay/ipywidgets,cornhundred/ipywidgets,ipython/ipywidgets,cornhundred/ipywidgets,jupyter-widgets/ipywidgets,SylvainCorlay/ipywidgets,jupyter-widgets/ipywidgets,ipython/ipywidgets,ipython/ipywidgets,ju... |
8ddd296052cfe9c8293806af397bb746fd2ebd19 | IPython/html/terminal/__init__.py | IPython/html/terminal/__init__.py | import os
from terminado import NamedTermManager
from .handlers import TerminalHandler, NewTerminalHandler, TermSocket
from . import api_handlers
def initialize(webapp):
shell = os.environ.get('SHELL', 'sh')
webapp.terminal_manager = NamedTermManager(shell_command=[shell])
handlers = [
(r"/terminal... | import os
from terminado import NamedTermManager
from IPython.html.utils import url_path_join as ujoin
from .handlers import TerminalHandler, NewTerminalHandler, TermSocket
from . import api_handlers
def initialize(webapp):
shell = os.environ.get('SHELL', 'sh')
webapp.terminal_manager = NamedTermManager(shell_... | Put terminal handlers under base_url | Put terminal handlers under base_url
| Python | bsd-3-clause | ipython/ipython,ipython/ipython |
29315da6d17dd30c957afb1b297cc4d6d335a284 | geotrek/core/tests/test_factories.py | geotrek/core/tests/test_factories.py | from django.test import TestCase
from .. import factories
class CoreFactoriesTest(TestCase):
"""
Ensure factories work as expected.
Here we just call each one to ensure they do not trigger any random
error without verifying any other expectation.
"""
def test_path_factory(self):
fact... | from django.test import TestCase
from .. import factories
class CoreFactoriesTest(TestCase):
"""
Ensure factories work as expected.
Here we just call each one to ensure they do not trigger any random
error without verifying any other expectation.
"""
def test_path_factory(self):
fact... | Add cover test : core factories | Add cover test : core factories
| Python | bsd-2-clause | GeotrekCE/Geotrek-admin,GeotrekCE/Geotrek-admin,makinacorpus/Geotrek,makinacorpus/Geotrek,GeotrekCE/Geotrek-admin,GeotrekCE/Geotrek-admin,makinacorpus/Geotrek,makinacorpus/Geotrek |
1101ce85635e49ad3cbd1f88e7dae1b77f45514c | ava/text_to_speech/__init__.py | ava/text_to_speech/__init__.py | import time
import os
from tempfile import NamedTemporaryFile
from sys import platform as _platform
from gtts import gTTS
from pygame import mixer
from .playsound import playsound
from ..components import _BaseComponent
class TextToSpeech(_BaseComponent):
def __init__(self, queues):
super().__init__(qu... | import time
import os
import tempfile
from sys import platform as _platform
from gtts import gTTS
from pygame import mixer
from .playsound import playsound
from ..components import _BaseComponent
class TextToSpeech(_BaseComponent):
def __init__(self, queues):
super().__init__(queues)
self.queue... | Add better handling of temp file | Add better handling of temp file
| Python | mit | ava-project/AVA |
c692038646417dfcd2e41f186b5814b3978847b6 | conf_site/core/context_processors.py | conf_site/core/context_processors.py | from django.conf import settings
from django.utils import timezone
import pytz
def core_context(self):
"""Context processor for elements appearing on every page."""
context = {}
context["google_analytics_id"] = settings.GOOGLE_ANALYTICS_PROPERTY_ID
context["sentry_public_dsn"] = settings.SENTRY_PUBLI... | from django.conf import settings
from django.contrib.sites.models import Site
from django.utils import timezone
import pytz
def core_context(self):
"""Context processor for elements appearing on every page."""
context = {}
context["conference_title"] = Site.objects.get_current().name
context["google_... | Fix conference title context processor. | Fix conference title context processor.
| Python | mit | pydata/conf_site,pydata/conf_site,pydata/conf_site |
5f40bbf76cacb491b52d41536935ac0442f8aaba | superdesk/io/feed_parsers/pa_nitf.py | superdesk/io/feed_parsers/pa_nitf.py | #!/usr/bin/env python
# -*- coding: utf-8; -*-
#
# This file is part of Superdesk.
#
# Copyright 2013, 2014, 2015 Sourcefabric z.u. and contributors.
#
# For the full copyright and license information, please see the
# AUTHORS and LICENSE files distributed with this source code, or
# at https://www.sourcefabric.org/sup... | #!/usr/bin/env python
# -*- coding: utf-8; -*-
#
# This file is part of Superdesk.
#
# Copyright 2013, 2014, 2015 Sourcefabric z.u. and contributors.
#
# For the full copyright and license information, please see the
# AUTHORS and LICENSE files distributed with this source code, or
# at https://www.sourcefabric.org/sup... | Use a set for comparison | Use a set for comparison
| Python | agpl-3.0 | superdesk/superdesk-core,mdhaman/superdesk-core,petrjasek/superdesk-core,superdesk/superdesk-core,superdesk/superdesk-core,petrjasek/superdesk-core,marwoodandrew/superdesk-core,superdesk/superdesk-core,mugurrus/superdesk-core,mugurrus/superdesk-core,mdhaman/superdesk-core,ioanpocol/superdesk-core,mdhaman/superdesk-core... |
53b920751de0e620792511df406805a5cea420cb | ideascaly/utils.py | ideascaly/utils.py | # IdeaScaly
# Copyright 2015 Jorge Saldivar
# See LICENSE for details.
import six
import dateutil.parser
def parse_datetime(str_date):
try:
date_is = dateutil.parser.parse(str_date)
return date_is
except:
return None
def parse_html_value(html):
return html[html.find('>')+1:html.r... | # IdeaScaly
# Copyright 2015 Jorge Saldivar
# See LICENSE for details.
import six
import dateutil.parser
def parse_datetime(str_date):
try:
date_is = dateutil.parser.parse(str_date)
return date_is
except:
return None
def parse_html_value(html):
return html[html.find('>')+1:html.r... | Remove conditional that checked type of arg | Remove conditional that checked type of arg
| Python | mit | joausaga/ideascaly |
526b1028925a59957e805b29fc624dae318661ef | finances/models.py | finances/models.py | import os
import hashlib
import datetime
import peewee
database = peewee.Proxy()
class BaseModel(peewee.Model):
class Meta:
database = database
class User(BaseModel):
id = peewee.IntegerField(primary_key=True)
name = peewee.CharField(unique=True)
password = peewee.CharField()
salt = p... | import os
import hashlib
import datetime
import peewee
database = peewee.Proxy()
class BaseModel(peewee.Model):
class Meta:
database = database
class User(BaseModel):
id = peewee.IntegerField(primary_key=True)
name = peewee.CharField(unique=True)
password = peewee.CharField()
salt = p... | Add __repr__ for User model | Add __repr__ for User model
| Python | mit | Afonasev/YourFinances |
149e9e2aab4922634e0ab5f130f9a08f9fda7d17 | podcast/templatetags/podcast_tags.py | podcast/templatetags/podcast_tags.py | from __future__ import unicode_literals
import re
from django import template
from django.contrib.sites.shortcuts import get_current_site
from django.contrib.syndication.views import add_domain
from django.template import TemplateSyntaxError
from django.utils.translation import ugettext_lazy as _
register = template... | from __future__ import unicode_literals
import re
from django import template
from django.contrib.sites.shortcuts import get_current_site
from django.contrib.syndication.views import add_domain
from django.template import TemplateSyntaxError
from django.utils.translation import ugettext_lazy as _
register = template... | Handle request in context error | Handle request in context error
| Python | bsd-3-clause | richardcornish/django-itunespodcast,richardcornish/django-itunespodcast,richardcornish/django-applepodcast,richardcornish/django-applepodcast |
8931025d53f472c3f1cb9c320eb796f0ea14274e | dddp/msg.py | dddp/msg.py | """Django DDP utils for DDP messaging."""
from dddp import THREAD_LOCAL as this
def obj_change_as_msg(obj, msg):
"""Generate a DDP msg for obj with specified msg type."""
serializer = this.serializer
data = serializer.serialize([obj])[0]
# collection name is <app>.<model>
name = data['model']
... | """Django DDP utils for DDP messaging."""
from copy import deepcopy
from dddp import THREAD_LOCAL as this
from django.db.models.expressions import ExpressionNode
def obj_change_as_msg(obj, msg):
"""Generate a DDP msg for obj with specified msg type."""
# check for F expressions
exps = [
name for n... | Support serializing objects that are saved with F expressions by reading field values for F expressions from database explicitly before serializing. | Support serializing objects that are saved with F expressions by reading field values for F expressions from database explicitly before serializing.
| Python | mit | django-ddp/django-ddp,commoncode/django-ddp,django-ddp/django-ddp,commoncode/django-ddp,commoncode/django-ddp,commoncode/django-ddp,django-ddp/django-ddp,django-ddp/django-ddp |
c81cc838d6e8109020dafae7e4ed1ff5aa7ebb88 | invoke/__init__.py | invoke/__init__.py | from ._version import __version_info__, __version__ # noqa
from .tasks import task, ctask, Task # noqa
from .collection import Collection # noqa
from .context import Context # noqa
def run(command, **kwargs):
"""
Invoke ``command`` in a subprocess and return a `.Result` object.
This function is simpl... | from ._version import __version_info__, __version__ # noqa
from .tasks import task, ctask, Task # noqa
from .collection import Collection # noqa
from .context import Context # noqa
from .config import Config # noqa
def run(command, **kwargs):
"""
Invoke ``command`` in a subprocess and return a `.Result` o... | Add Config to root convenience imports | Add Config to root convenience imports
| Python | bsd-2-clause | pyinvoke/invoke,mattrobenolt/invoke,frol/invoke,mkusz/invoke,pfmoore/invoke,mkusz/invoke,pyinvoke/invoke,mattrobenolt/invoke,pfmoore/invoke,kejbaly2/invoke,kejbaly2/invoke,tyewang/invoke,frol/invoke,singingwolfboy/invoke |
931fca0b7cca4a631388eeb6114145c8d4ff6e18 | lims/celery.py | lims/celery.py | import os
from celery import Celery
from celery.schedules import crontab
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'lims.settings')
app = Celery('lims', broker='redis://localhost', backend='redis')
app.config_from_object('django.conf:settings', namespace='CELERY')
app.autodiscover_tasks()
app.conf.beat_schedul... | import os
from celery import Celery
from celery.schedules import crontab
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'lims.settings')
app = Celery('lims', broker=os.environ.get('REDIS_URL', 'redis://127.0.0.1:6379'), backend='redis')
app.config_from_object('django.conf:settings', namespace='CELERY')
app.autodisco... | Extend time period at which deadline processing happens | Extend time period at which deadline processing happens
| Python | mit | GETLIMS/LIMS-Backend,GETLIMS/LIMS-Backend |
15b3e52e75dddcd09b1fff807e836c60a0c62a03 | python2.7libs/createDlp.py | python2.7libs/createDlp.py | #-------------------------------------------------------------------------------
## Description
"""
Create Cache Dependency by just cliking.
"""
#-------------------------------------------------------------------------------
__version__ = "1.0.0"
import hou
def main():
sel_cache = hou.ui.selectFile(title="Selec... | #-------------------------------------------------------------------------------
## Description
"""
Create Cache Dependency by just cliking.
"""
#-------------------------------------------------------------------------------
__version__ = '2.0.0'
#---------------------------------------------------------------------... | Add functionality to Create DLP tool. | Add functionality to Create DLP tool.
| Python | mit | takavfx/Bento |
a34ce653f262888c17ae92e348adb0892b74a94c | download.py | download.py | import youtube_dl, os
from multiprocessing.pool import ThreadPool
from youtube_dl.utils import DownloadError
from datetime import datetime
from uuid import uuid4
class Download:
link = ""
done = False
error = False
started = None
uuid = ""
total = 0
finished = 0
title = ""
def __i... | import os, youtube_dl
from youtube_dl import YoutubeDL
from multiprocessing.pool import ThreadPool
from youtube_dl.utils import DownloadError
from datetime import datetime
from uuid import uuid4
class Download:
link = ''
done = False
error = False
started = None
uuid = ''
total = 0
finishe... | Use hooks for progress updates | Use hooks for progress updates
| Python | mit | pielambr/PLDownload,pielambr/PLDownload |
7c607bff6fa043c5d380403d673ac6690a7277cc | meinberlin/apps/newsletters/forms.py | meinberlin/apps/newsletters/forms.py | from django import forms
from django.apps import apps
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from adhocracy4.projects.models import Project
from . import models
Organisation = apps.get_model(settings.A4_ORGANISATIONS_MODEL)
class NewsletterForm(forms.ModelForm):
... | from django import forms
from django.apps import apps
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from adhocracy4.projects.models import Project
from . import models
Organisation = apps.get_model(settings.A4_ORGANISATIONS_MODEL)
class NewsletterForm(forms.ModelForm):
... | Validate for no project selection in newsletter | Validate for no project selection in newsletter
| Python | agpl-3.0 | liqd/a4-meinberlin,liqd/a4-meinberlin,liqd/a4-meinberlin,liqd/a4-meinberlin |
94172dc29d9ccbce1c2ac752ce09baefafbf8a6c | nbgrader/tests/apps/test_nbgrader.py | nbgrader/tests/apps/test_nbgrader.py | import os
from .. import run_python_module, run_command
from .base import BaseTestApp
class TestNbGrader(BaseTestApp):
def test_help(self):
"""Does the help display without error?"""
run_python_module(["nbgrader", "--help-all"])
def test_no_subapp(self):
"""Is the help displayed whe... | import os
import sys
from .. import run_python_module, run_command
from .base import BaseTestApp
class TestNbGrader(BaseTestApp):
def test_help(self):
"""Does the help display without error?"""
run_python_module(["nbgrader", "--help-all"])
def test_no_subapp(self):
"""Is the help di... | Fix issue with how nbgrader is called | Fix issue with how nbgrader is called
| Python | bsd-3-clause | jhamrick/nbgrader,jhamrick/nbgrader,jupyter/nbgrader,ellisonbg/nbgrader,EdwardJKim/nbgrader,jupyter/nbgrader,jupyter/nbgrader,EdwardJKim/nbgrader,ellisonbg/nbgrader,jhamrick/nbgrader,ellisonbg/nbgrader,jupyter/nbgrader,EdwardJKim/nbgrader,ellisonbg/nbgrader,jhamrick/nbgrader,EdwardJKim/nbgrader,jupyter/nbgrader |
8af349128b725e47b89f28ddc005d142a44c5765 | openarc/env.py | openarc/env.py | #!/usr/bin/env python2.7
import os
import json
class OAEnv(object):
@property
def static_http_root(self):
if self.envcfg['httpinfo']['secure'] is True:
security = "https://"
else:
security = "http://"
return "%s%s" % ( security, self.envcfg['httpinfo']['httproo... | #!/usr/bin/env python2.7
import os
import json
class OAEnv(object):
@property
def static_http_root(self):
if self.envcfg['httpinfo']['secure'] is True:
security = "https://"
else:
security = "http://"
return "%s%s" % ( security, self.envcfg['httpinfo']['httproo... | Allow retrieval of external api credentials | Allow retrieval of external api credentials
| Python | bsd-3-clause | kchoudhu/openarc |
935552df10dc3a17cf3edb897e83861bbeaae803 | tests/test_thread.py | tests/test_thread.py | import os
import unittest
from common import gobject, gtk, testhelper
# Enable PyGILState API
os.environ['PYGTK_USE_GIL_STATE_API'] = ''
gobject.threads_init()
class TestThread(unittest.TestCase):
def from_thread_cb(self, test, enum):
assert test == self.obj
assert int(enum) == 0
assert ... | import os
import unittest
from common import gobject, gtk, testhelper
# Enable PyGILState API
os.environ['PYGTK_USE_GIL_STATE_API'] = ''
gobject.threads_init()
class TestThread(unittest.TestCase):
def from_thread_cb(self, test, enum):
assert test == self.obj
assert int(enum) == 0
assert ... | Add pygtk_postinstall.py Updated Deprecate gtk.idle_add and friends. Merge | Add pygtk_postinstall.py Updated Deprecate gtk.idle_add and friends. Merge
* Makefile.am: Add pygtk_postinstall.py
* docs/random/missing-symbols: Updated
* gtk/__init__.py: Deprecate gtk.idle_add and friends.
* gtk/gtk.defs: Merge in 2.6 api, for GtkLabel functions,
thanks to Gian Mario Tagliaretti, fixes bug #16... | Python | lgpl-2.1 | choeger/pygobject-cmake,GNOME/pygobject,nzjrs/pygobject,atizo/pygobject,pexip/pygobject,jdahlin/pygobject,davibe/pygobject,Distrotech/pygobject,sfeltman/pygobject,pexip/pygobject,choeger/pygobject-cmake,MathieuDuponchelle/pygobject,alexef/pygobject,alexef/pygobject,alexef/pygobject,sfeltman/pygobject,davidmalcolm/pygob... |
6621bef05b2d4cb3fc138622194fe39765ebcb7c | tests/unit/helper.py | tests/unit/helper.py | import mock
import github3
import unittest
MockedSession = mock.create_autospec(github3.session.GitHubSession)
def build_url(self, *args, **kwargs):
# We want to assert what is happening with the actual calls to the
# Internet. We can proxy this.
return github3.session.GitHubSession().build_url(*args, **... | import mock
import github3
import unittest
def build_url(self, *args, **kwargs):
# We want to assert what is happening with the actual calls to the
# Internet. We can proxy this.
return github3.session.GitHubSession().build_url(*args, **kwargs)
class UnitHelper(unittest.TestCase):
# Sub-classes must... | Fix the issue where the mock is persisting calls | Fix the issue where the mock is persisting calls
| Python | bsd-3-clause | krxsky/github3.py,jim-minter/github3.py,agamdua/github3.py,degustaf/github3.py,christophelec/github3.py,wbrefvem/github3.py,h4ck3rm1k3/github3.py,sigmavirus24/github3.py,ueg1990/github3.py,icio/github3.py,balloob/github3.py,itsmemattchung/github3.py |
ededa7c9c616ac97dd6ce8638c6b959a0c51663c | examples/oauth/jupyterhub_config.py | examples/oauth/jupyterhub_config.py | # Configuration file for Jupyter Hub
c = get_config()
# spawn with Docker
c.JupyterHub.spawner_class = 'dockerspawner.DockerSpawner'
# The docker instances need access to the Hub, so the default loopback port doesn't work:
from IPython.utils.localinterfaces import public_ips
c.JupyterHub.hub_ip = public_ips()[0]
# ... | # Configuration file for Jupyter Hub
c = get_config()
# spawn with Docker
c.JupyterHub.spawner_class = 'dockerspawner.DockerSpawner'
# The docker instances need access to the Hub, so the default loopback port doesn't work:
from jupyter_client.localinterfaces import public_ips
c.JupyterHub.hub_ip = public_ips()[0]
#... | Replace legacy ipython import with jupyter_client | Replace legacy ipython import with jupyter_client | Python | bsd-3-clause | jhamrick/dockerspawner,jupyter/dockerspawner,quantopian/dockerspawner,Fokko/dockerspawner,Fokko/dockerspawner,minrk/dockerspawner,quantopian/dockerspawner,minrk/dockerspawner,jupyter/dockerspawner,jhamrick/dockerspawner |
5831ce15a94d1941e0521bae328f0ede48bfbe8b | juliet_importer.py | juliet_importer.py | import os
import imp
modules = {}
def load_modules(path="./modules/"): # Consider adding recursive searching at some point in the future
modules['juliet_module'] = imp.load_source('juliet_module', path + "juliet_module.py")
names = os.listdir(path)
for name in names:
if not name.endswith(".py"): c... | import os
import imp
modules = {}
def load_modules(path="./modules/"):
try:
modules['juliet_module'] = imp.load_source('juliet_module', path + "juliet_module.py")
except ImportError as e:
print("Error importing module {0} from directory {1}".format(name,os.getcwd()))
print(e)
... | Add recursive search to import function | Add recursive search to import function
| Python | bsd-2-clause | halfbro/juliet |
381e89972bf4d12daae7aa399f1348a215fa85d9 | jira/exceptions.py | jira/exceptions.py | import json
class JIRAError(Exception):
"""General error raised for all problems in operation of the client."""
def __init__(self, status_code=None, text=None, url=None):
self.status_code = status_code
self.text = text
self.url = url
def __str__(self):
if self.text:
... | import json
class JIRAError(Exception):
"""General error raised for all problems in operation of the client."""
def __init__(self, status_code=None, text=None, url=None):
self.status_code = status_code
self.text = text
self.url = url
def __str__(self):
if self.text:
... | Fix for empty errorMessages, moved length check to main logic for deciding which error message to use and added check for 'errors' in the response. | Fix for empty errorMessages, moved length check to main logic for deciding which error
message to use and added check for 'errors' in the response. | Python | bsd-2-clause | pycontribs/jira,jameskeane/jira-python,rayyen/jira,pycontribs/jira,dbaxa/jira,coddingtonbear/jira,milo-minderbinder/jira,systemadev/jira-python,tsarnowski/jira-python,kinow/jira,jameskeane/jira-python,awurster/jira,stevencarey/jira,VikingDen/jira,awurster/jira,kinow/jira,m42e/jira,VikingDen/jira,tsarnowski/jira-python,... |
2050385a5f5fdcffe333ae17463d6469af0b5cd8 | mopidy/__init__.py | mopidy/__init__.py | from __future__ import unicode_literals
import sys
import warnings
from distutils.version import StrictVersion as SV
import pykka
if not (2, 7) <= sys.version_info < (3,):
sys.exit(
'Mopidy requires Python >= 2.7, < 3, but found %s' %
'.'.join(map(str, sys.version_info[:3])))
if (isinstance(pyk... | from __future__ import unicode_literals
import platform
import sys
import warnings
from distutils.version import StrictVersion as SV
import pykka
if not (2, 7) <= sys.version_info < (3,):
sys.exit(
'ERROR: Mopidy requires Python 2.7, but found %s.' %
platform.python_version())
if (isinstance(py... | Update Python and Pykka version check error messages | Update Python and Pykka version check error messages
| Python | apache-2.0 | jmarsik/mopidy,adamcik/mopidy,priestd09/mopidy,woutervanwijk/mopidy,glogiotatidis/mopidy,tkem/mopidy,bencevans/mopidy,hkariti/mopidy,jcass77/mopidy,pacificIT/mopidy,vrs01/mopidy,ali/mopidy,bencevans/mopidy,mokieyue/mopidy,rawdlite/mopidy,swak/mopidy,tkem/mopidy,rawdlite/mopidy,jcass77/mopidy,woutervanwijk/mopidy,swak/m... |
fb042cd3ff15f35672e543f040053859c18cff24 | timedelta/templatetags/timedelta.py | timedelta/templatetags/timedelta.py | from django import template
register = template.Library()
# Don't really like using relative imports, but no choice here!
from ..helpers import nice_repr, iso8601_repr, total_seconds as _total_seconds
@register.filter(name='timedelta')
def timedelta(value, display="long"):
return nice_repr(value, display)
@regis... | from django import template
register = template.Library()
# Don't really like using relative imports, but no choice here!
from ..helpers import nice_repr, iso8601_repr, total_seconds as _total_seconds
@register.filter(name='timedelta')
def timedelta(value, display="long"):
if value is None:
return value
... | Allow for calling our filters on objects that are None | Allow for calling our filters on objects that are None
| Python | bsd-3-clause | sookasa/django-timedelta-field |
e000f5db7bf8aee6b3ae267824491d03b20fbb36 | saau/sections/transportation/data.py | saau/sections/transportation/data.py | from operator import attrgetter, itemgetter
from itertools import chain
from ...utils.py3_hook import with_hook
with with_hook():
from arcrest import Catalog
import numpy as np
def get_layers(service):
layers = service.layers
return {
layer.name: layer
for layer in layers
}
def men... | from operator import itemgetter
from itertools import chain
from ...utils.py3_hook import with_hook
with with_hook():
from arcrest import Catalog
import numpy as np
def get_layers(service):
layers = service.layers
return {
layer.name: layer
for layer in layers
}
def mend_extent(ext... | Remove map and filter use | Remove map and filter use
| Python | mit | Mause/statistical_atlas_of_au |
fc6806608c5e407882248185bca57afa712e065a | byceps/blueprints/news_admin/forms.py | byceps/blueprints/news_admin/forms.py | """
byceps.blueprints.news_admin.forms
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2017 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
import re
from wtforms import StringField, TextAreaField
from wtforms.validators import InputRequired, Length, Optional, Regexp
from ...util.l10n ... | """
byceps.blueprints.news_admin.forms
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2017 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
import re
from wtforms import StringField, TextAreaField
from wtforms.validators import InputRequired, Length, Optional, Regexp
from ...util.l10n ... | Fix validation of news creation form | Fix validation of news creation form
| Python | bsd-3-clause | m-ober/byceps,m-ober/byceps,m-ober/byceps,homeworkprod/byceps,homeworkprod/byceps,homeworkprod/byceps |
4bd41e0e9381ef1c29b1a912a5d8d6ac99b03f4c | capstone/rl/learners/qlearning.py | capstone/rl/learners/qlearning.py | from ..learner import Learner
from ..policies import RandomPolicy
from ..util import max_action_value
from ..value_functions import TabularF
from ...utils import check_random_state
class QLearning(Learner):
def __init__(self, env, policy=None, qf=None, alpha=0.1, gamma=0.99,
n_episodes=1000, ran... | from ..learner import Learner
from ..policies import RandomPolicy
from ..util import max_action_value
from ..value_functions import TabularF
from ...utils import check_random_state
class QLearning(Learner):
def __init__(self, env, policy=None, qf=None, learning_rate=0.1,
discount_factor=0.99, n_... | Rename alpha -> learning_rate and gamma -> discount_factor | Rename alpha -> learning_rate and gamma -> discount_factor
| Python | mit | davidrobles/mlnd-capstone-code |
0167e246b74789cc0181b603520ec7f58ef7b5fe | pandas/core/api.py | pandas/core/api.py |
# pylint: disable=W0614,W0401,W0611
import numpy as np
from pandas.core.algorithms import factorize, match, unique, value_counts
from pandas.core.common import isnull, notnull, save, load
from pandas.core.categorical import Categorical, Factor
from pandas.core.format import (set_printoptions, reset_printoptions,
... |
# pylint: disable=W0614,W0401,W0611
import numpy as np
from pandas.core.algorithms import factorize, match, unique, value_counts
from pandas.core.common import isnull, notnull, save, load
from pandas.core.categorical import Categorical, Factor
from pandas.core.format import (set_printoptions, reset_printoptions,
... | Add new core.config API functions to the pandas top level module | ENH: Add new core.config API functions to the pandas top level module
| Python | bsd-3-clause | pandas-dev/pandas,GuessWhoSamFoo/pandas,TomAugspurger/pandas,toobaz/pandas,MJuddBooth/pandas,cython-testbed/pandas,TomAugspurger/pandas,nmartensen/pandas,cython-testbed/pandas,DGrady/pandas,DGrady/pandas,datapythonista/pandas,kdebrab/pandas,dsm054/pandas,Winand/pandas,linebp/pandas,dsm054/pandas,toobaz/pandas,jmmease/p... |
ebcdf90a44d3ae87be8032f89bec26697e22cbf3 | alexandra/__init__.py | alexandra/__init__.py | """
Python support for Alexa applications.
Because like everything Amazon it involves a ton of tedious boilerplate.
"""
import logging
logging.getLogger(__name__).addHandler(logging.NullHandler())
from alexandra.app import Application
from alexandra.session import Session
from alexandra.util import respond, repromp... | # flake8: noqa
"""
Python support for Alexa applications.
Because like everything Amazon it involves a ton of tedious boilerplate.
"""
import logging
logging.getLogger(__name__).addHandler(logging.NullHandler())
from alexandra.app import Application
from alexandra.session import Session
from alexandra.util import r... | Add a noqa to init | Add a noqa to init
| Python | isc | erik/alexandra |
2cb7c80bc4358631b897e3ea91d3c7eff684f69b | pmxbot/__init__.py | pmxbot/__init__.py | # -*- coding: utf-8 -*-
# vim:ts=4:sw=4:noexpandtab
from __future__ import absolute_import
import socket
import logging
from .dictlib import ConfigDict
config = ConfigDict(
bot_nickname = 'pmxbot',
database = 'sqlite:pmxbot.sqlite',
server_host = 'localhost',
server_port = 6667,
use_ssl = False,
password = No... | # -*- coding: utf-8 -*-
# vim:ts=4:sw=4:noexpandtab
from __future__ import absolute_import
import socket
import logging as _logging
from .dictlib import ConfigDict
config = ConfigDict(
bot_nickname = 'pmxbot',
database = 'sqlite:pmxbot.sqlite',
server_host = 'localhost',
server_port = 6667,
use_ssl = False,
p... | Fix issue with conflated pmxbot.logging | Fix issue with conflated pmxbot.logging
| Python | bsd-3-clause | jawilson/pmxbot,jawilson/pmxbot |
c5c2d3c411ba38a7b110044e04657ae6584be861 | scripts/helpers.py | scripts/helpers.py |
def printSnapshot(doc):
print(u'Created {} => {}'.format(doc.id, doc.to_dict()))
def queryUsers(db):
users_ref = db.collection(u'users')
docs = users_ref.get()
docList = list()
for doc in docs:
docList.append(doc)
return docList
def queryRequests(db):
requests_ref = db.collection(u'requests')
doc... |
def printSnapshot(doc):
print(u'Created {} => {}'.format(doc.id, doc.to_dict()))
def queryUsers(db):
users_ref = db.collection(u'users')
docs = users_ref.get()
docList = list()
for doc in docs:
docList.append(doc)
return docList
def queryRequests(db):
requests_ref = db.collection(u'requests')
doc... | Add script to clean the message table | Add script to clean the message table
| Python | mit | frinder/frinder-app,frinder/frinder-app,frinder/frinder-app |
2f6c82d74592c80b5042c0b808a658650896cbec | rebulk/__init__.py | rebulk/__init__.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Define simple search patterns in bulk to perform advanced matching on any string
"""
from .rebulk import Rebulk
from .match import Match
from .rules import Rule
from .pattern import REGEX_AVAILABLE
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Define simple search patterns in bulk to perform advanced matching on any string
"""
from .rebulk import Rebulk
from .match import Match
from .rules import Rule, AppendMatchRule, RemoveMatchRule
from .pattern import REGEX_AVAILABLE
| Add global imports for rules classes | Add global imports for rules classes
| Python | mit | Toilal/rebulk |
75092d41fc93306ddc640463886e80620cbcbf46 | pemi/transforms.py | pemi/transforms.py | def isblank(value):
return (
value is not False
and value != 0
and value != float(0)
and not bool(value)
)
def concatenate(delimiter=''):
def _concatenate(row):
return delimiter.join(row)
return _concatenate
def nvl(default=''):
def _nvl(r... | import pandas as pd
def isblank(value):
return (
value is not False
and value != 0
and value != float(0)
and (value is None or pd.isnull(value) or not value)
)
def concatenate(delimiter=''):
def _concatenate(row):
return delimiter.join(row)
return _concatenate
... | Revert "DE-1903 - fix isblank() error" | Revert "DE-1903 - fix isblank() error"
This reverts commit 27fd096d9641971f34cb0811fc2240ebc4f3450b.
| Python | mit | inside-track/pemi |
fd7fb7ade0fc879e24543f13c39b00de073004bc | setuptools/tests/py26compat.py | setuptools/tests/py26compat.py | import sys
import tarfile
import contextlib
def _tarfile_open_ex(*args, **kwargs):
"""
Extend result as a context manager.
"""
return contextlib.closing(tarfile.open(*args, **kwargs))
tarfile_open = _tarfile_open_ex if sys.version_info < (2,7) else tarfile.open
| import sys
import tarfile
import contextlib
def _tarfile_open_ex(*args, **kwargs):
"""
Extend result as a context manager.
"""
return contextlib.closing(tarfile.open(*args, **kwargs))
if sys.version_info[:2] < (2, 7) or (3, 0) <= sys.version_info[:2] < (3, 2):
tarfile_open = _tarfile_open_ex
else:
tarfile... | Fix "AttributeError: 'TarFile' object has no attribute '__exit__'" with Python 3.1. | Fix "AttributeError: 'TarFile' object has no attribute '__exit__'" with Python 3.1.
| Python | mit | pypa/setuptools,pypa/setuptools,pypa/setuptools |
6830f29022746838677ecca420aeff190943c5ed | random/__init__.py | random/__init__.py | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | Remove remnants of internal project naming in one docstring. | Remove remnants of internal project naming in one docstring.
PiperOrigin-RevId: 263530441
| Python | apache-2.0 | google/tf-quant-finance,google/tf-quant-finance |
0eb7ddce9f425c30c70bc1442618deb72c530911 | networks/models.py | networks/models.py | from django.db import models
from helpers import models as helpermodels
# Create your models here.
class Networks(models.Model):
POLICIES = (
('reject', 'Reject'),
('drop', 'Ignore'),
('accept', 'Accept'),
)
name = models.CharField(max_length=30)
interface... | from django.db import models
from helpers.models import IPNetworkField
# Create your models here.
class Network(models.Model):
POLICIES = (
('reject', 'Reject'),
('drop', 'Ignore'),
('accept', 'Accept'),
)
name = models.CharField(max_length=30)
interface =... | Fix Network model name; better import | Fix Network model name; better import
| Python | mit | Kromey/piroute,Kromey/piroute,Kromey/piroute |
563e7d5bc2fadd35b0fc71d45c949aa0b2e872a9 | example/example/tasksapp/run_tasks.py | example/example/tasksapp/run_tasks.py | import os
import time
from dj_experiment.tasks.tasks import longtime_add, netcdf_save
from example.settings import (DJ_EXPERIMENT_BASE_DATA_DIR,
DJ_EXPERIMENT_DATA_DIR)
if __name__ == '__main__':
result = longtime_add.delay(1, 2)
# at this time, our task is not finished, so it wi... | import os
import time
from dj_experiment.tasks.tasks import longtime_add, netcdf_save
from example.settings import DJ_EXPERIMENT_BASE_DATA_DIR
if __name__ == '__main__':
result = longtime_add.delay(1, 2)
# at this time, our task is not finished, so it will return False
print 'Task finished? ', result.read... | Fix wrong path composition for data directory | Fix wrong path composition for data directory
| Python | mit | francbartoli/dj-experiment,francbartoli/dj-experiment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.