commit stringlengths 40 40 | old_file stringlengths 4 150 | new_file stringlengths 4 150 | old_contents stringlengths 0 3.26k | new_contents stringlengths 1 4.43k | subject stringlengths 15 501 | message stringlengths 15 4.06k | lang stringclasses 4
values | license stringclasses 13
values | repos stringlengths 5 91.5k | diff stringlengths 0 4.35k |
|---|---|---|---|---|---|---|---|---|---|---|
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 | ---
+++
@@ -1,5 +1,12 @@
class Transformer(object):
- class Feats():
+ """
+ Base class for all transformer
+ """
+
+ class Feats:
+ """
+ Define feats on dataset
+ """
exclude = None
def __init__(self):
@@ -7,7 +14,23 @@
getattr(self.Feats, fi... |
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 | ---
+++
@@ -16,6 +16,6 @@
for division in Division.get(self.division_id).children('school_district'):
organization.add_post(role='Chair', label=division.name, division_id=division.id)
for i in range (0, 15): # XXX made-up number
- organization.add_post(role='Trustee ... |
a3f33b31a572302609e44c47fff895c988ac9396 | web/cse191_web/util.py | web/cse191_web/util.py | import traceback
from . import client
from . import app
from .thrift import lang_thrift
import os.path
import random
servers = []
with open(os.path.join(os.path.dirname(__file__), 'servers'), 'r') as f:
for l in f:
ip, _, port = l.partition(':')
servers.append((ip, int(port)))
def get_server():
... | import traceback
from . import client
from . import app
from .thrift import lang_thrift
import os.path
import random
servers = []
try:
servers_file = os.path.join(os.path.dirname(__file__), 'servers')
with open(server_file, 'r') as f:
for l in f:
ip, _, port = l.partition(':')
s... | Fix setting servers through runserver commandline | Fix setting servers through runserver commandline
| Python | mit | jamesmkwan/cse191,jamesmkwan/cse191,jamesmkwan/cse191,jamesmkwan/cse191 | ---
+++
@@ -6,10 +6,14 @@
import random
servers = []
-with open(os.path.join(os.path.dirname(__file__), 'servers'), 'r') as f:
- for l in f:
- ip, _, port = l.partition(':')
- servers.append((ip, int(port)))
+try:
+ servers_file = os.path.join(os.path.dirname(__file__), 'servers')
+ with op... |
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 | ---
+++
@@ -4,3 +4,4 @@
from .Auction import Auction
from .Bid import Bid
from .Invoice import Invoice
+from .auctions.DoubleBlindAuction import DoubleBlindAuction |
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 | ---
+++
@@ -1,3 +1,20 @@
+'''
+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 circ... |
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 | ---
+++
@@ -1,5 +1,7 @@
import os
+import re
def hdfs_make_qualified(path):
- return path if 'CF_HADOOP_DEFAULT_FS' not in os.environ else os.environ['CF_HADOOP_DEFAULT_FS'] + path
+ return path if (re.match(r'[.]*://[.]*', path) or 'CF_HADOOP_DEFAULT_FS' not in os.environ) \
+ else os.environ['CF_... |
f99efce15513216ae4bd1462daeee8b0d12d2a1e | zsl/testing/db.py | zsl/testing/db.py | from __future__ import (absolute_import, division,
print_function, unicode_literals)
from builtins import *
from sqlalchemy.engine import Engine
from zsl import inject
from zsl.db.model.sql_alchemy import metadata
class DbTestCase(object):
@inject(engine=Engine)
def createSchema(self... | from __future__ import (absolute_import, division,
print_function, unicode_literals)
from builtins import *
from sqlalchemy.engine import Engine
from zsl import inject
from zsl.db.model.sql_alchemy import metadata
class DbTestCase(object):
@inject(engine=Engine)
def createSchema(self... | Add newline at the end of the file. | Add newline at the end of the file.
| Python | mit | AtteqCom/zsl,AtteqCom/zsl | ---
+++
@@ -13,3 +13,5 @@
def createSchema(self, engine):
metadata.bind = engine
metadata.create_all(engine)
+
+ |
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 | ---
+++
@@ -1,7 +1,7 @@
import mechanize
import os
-class McGillException(Exception):
+class error(Exception):
pass
urls = {
@@ -19,11 +19,11 @@
if pin is None:
pin = os.environ.get('MCGILL_PIN', None)
if sid is None or pin is None:
- raise McGillException('McGill ID or PIN not p... |
b16bd0e8f85aa2895536bf1fe833d07bacc1790e | pyQuantuccia/setup.py | pyQuantuccia/setup.py | import setuptools
setuptools.setup(
name='pyQuantuccia',
packages=['pyQuantuccia']
) | import setuptools
setuptools.setup(
name='pyQuantuccia',
packages=['pyQuantuccia']
)
| Add newline at end of file. | Add newline at end of file.
| Python | bsd-3-clause | jwg4/pyQuantuccia,jwg4/pyQuantuccia | |
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 | ---
+++
@@ -12,6 +12,17 @@
# See the License for the specific language governing permissions and
# limitations under the License.
+"""
+ If you are running the application within docker using the provided
+ Dockerfile and docker-compose then you will need to change the MONGO_HOST
+ option to use the corr... |
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 | ---
+++
@@ -4,18 +4,24 @@
sippy_path = None
try:
- opts, args = getopt.getopt(sys.argv[1:], 's:S:i:o:b')
+ opts, args = getopt.getopt(sys.argv[1:], 'rS:')
except getopt.GetoptError:
usage()
+ out_realtime = False
for o, a in opts:
if o == '-S':
s... |
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/... | ---
+++
@@ -14,7 +14,7 @@
page = HomePage(base_url, selenium).open()
initial = page.footer.language
# avoid selecting the same language or locales that have homepage redirects
- excluded = [initial, 'ja', 'zh-TW', 'zh-CN']
+ excluded = [initial, 'ja', 'ja-JP-mac', 'zh-TW', 'zh-CN']
available... |
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 | ---
+++
@@ -3,7 +3,14 @@
example app to test running an app as subprocess within pty
"""
from __future__ import print_function, unicode_literals
-import time
+import sys, time
+
+
+PY3 = sys.version_info[0] >= 3
+
+if PY3:
+ raw_input = input
+
# http://stackoverflow.com/questions/287871/print-in-terminal-wi... |
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 | ---
+++
@@ -24,8 +24,11 @@
# is taken. We exploit this below.
# TextIO is missing on some older Pythons.
-if 'TextIO' in globals():
- TextIO = typing.TextIO
+if 'TextIO' not in globals():
+ try:
+ TextIO = typing.TextIO
+ except ImportError:
+ TextIO = None # type: ignore
else:
TextIO... |
a75f415c9795fd4b3caf28cb1f6b8d708f4a4672 | django/santropolFeast/meal/models.py | django/santropolFeast/meal/models.py | from django.db import models
from django.utils.translation import ugettext_lazy as _
class Meal(models.Model):
class Meta:
verbose_name_plural = _('Meals')
#Meal information
nom = models.CharField(max_length=50, verbose_name=_('Name'))
description = models.TextFields(verbose_name=_('Description'))
ingredients ... | from django.db import models
from django.utils.translation import ugettext_lazy as _
class Meal(models.Model):
class Meta:
verbose_name_plural = _('meals')
#Meal information
nom = models.CharField(max_length=50, verbose_name=_('name'))
description = models.TextFields(verbose_name=_('description'))
ingredients ... | Use standart i18n key in meal model | Use standart i18n key in meal model | Python | agpl-3.0 | madmath/sous-chef,savoirfairelinux/santropol-feast,savoirfairelinux/sous-chef,savoirfairelinux/sous-chef,savoirfairelinux/santropol-feast,madmath/sous-chef,savoirfairelinux/santropol-feast,savoirfairelinux/sous-chef,madmath/sous-chef | ---
+++
@@ -3,26 +3,26 @@
class Meal(models.Model):
class Meta:
- verbose_name_plural = _('Meals')
+ verbose_name_plural = _('meals')
#Meal information
- nom = models.CharField(max_length=50, verbose_name=_('Name'))
- description = models.TextFields(verbose_name=_('Description'))
+ nom = models.CharField(m... |
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 | ---
+++
@@ -26,7 +26,9 @@
return IRCResponse(ResponseType.Say, 'Only my admins can tell me to %s' % message.Command, message.ReplyTo)
if len(message.ParameterList) > 0:
+ HubbeBot.channels.remove(message.ReplyTo)
return IRCResponse(ResponseType.Raw, 'PART %s :%s... |
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 | ---
+++
@@ -31,7 +31,8 @@
# Trait definitions:
#---------------------------------------------------------------------------
- # Is multiselect enabled for a CustomEditor?
+ #-- CustomEditor traits ----------------------------------------------------
+
# True: Must be a List of Dates... |
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 | ---
+++
@@ -3,7 +3,8 @@
from django.shortcuts import render
from django.views.generic import TemplateView
-from est_client.forms import ClientCreateForm
+from est_client.forms import (ClientCreateForm, CompanyCreateForm,
+ CompanyListForm)
from est_quote.forms import QuoteCreateForm,... |
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 | ---
+++
@@ -1,6 +1,17 @@
'''
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
+ '''
+ wit... |
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 | ---
+++
@@ -6,8 +6,8 @@
text = indexes.CharField(document=True, use_template=True)
content_auto = indexes.EdgeNgramField(model_attr='position__person__name')
compensation = indexes.FloatField(model_attr='compensation', null=True)
- title = indexes.CharField(model_attr='title__name', faceted=True)
- ... |
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 | ---
+++
@@ -1,6 +1,7 @@
from nose.tools import eq_
-from orges.invoker.simple import SimpleInvoker
+# from orges.invoker.simple import SimpleInvoker
+from orges.invoker.multiprocess import MultiProcessInvoker
from orges.invoker.pluggable import PluggableInvoker
from orges.main import custom_optimize
@@ -9,7 +1... |
d24ac637870a5e3e701a172212e38f733acc4fd8 | webcomix/tests/test_docker.py | webcomix/tests/test_docker.py | import docker
import pytest
from webcomix.docker import DockerManager, CONTAINER_NAME
@pytest.fixture
def cleanup_container():
yield None
client = docker.from_env()
for container in client.containers().list():
if container.attrs["Config"]["Image"] == CONTAINER_NAME:
container.kill()
d... | import docker
import pytest
from webcomix.docker import DockerManager, CONTAINER_NAME
@pytest.fixture
def cleanup_container():
yield None
client = docker.from_env()
for container in client.containers.list():
if container.attrs["Config"]["Image"] == CONTAINER_NAME:
container.kill()
def... | Use Docker API property in fixture | Use Docker API property in fixture
| Python | mit | J-CPelletier/webcomix,J-CPelletier/webcomix | ---
+++
@@ -7,7 +7,7 @@
def cleanup_container():
yield None
client = docker.from_env()
- for container in client.containers().list():
+ for container in client.containers.list():
if container.attrs["Config"]["Image"] == CONTAINER_NAME:
container.kill()
|
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 | ---
+++
@@ -6,14 +6,13 @@
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 syft.lib.python.dict import Dict
# ... |
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 | ---
+++
@@ -1,5 +1,5 @@
from django.conf import settings
-from django.utils import importlib
+import importlib
def import_from_string(val, setting_name): |
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 | ---
+++
@@ -9,6 +9,7 @@
menu_order = 300
list_display = ('first_name', 'last_name', 'production', 'role')
list_filter = ('role', 'production')
+ ordering = ('-production',)
search_fields = ('first_name', 'last_name', 'biography')
wagtailmodeladmin_register(PeopleAdmin) |
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... | ---
+++
@@ -11,8 +11,8 @@
info = json.load(fh)
if sys.platform == 'darwin':
- assert sorted(info['files']) == [u'lib/libpng.dylib', u'lib/libpng16.16.dylib', u'lib/libpng16.dylib']
- elif sys.platform == 'linux2':
+ assert sorted(info['files']) == ['lib/libpng.dylib', 'lib/libpng16.16... |
fe54b9af317d057ab5f4ef8dca8fe7d32846892e | nazs/samba/module.py | nazs/samba/module.py | from nazs.core import module
from nazs.core.commands import run
from nazs.core.sudo import root
from django.utils.translation import ugettext as _
import os
import logging
logger = logging.getLogger(__name__)
class Samba(module.Module):
"""
Samba 4 module, it deploys samba AD and file server
"""
E... | from nazs.core import module
from nazs.core.commands import run
from nazs.core.sudo import root
from django.utils.translation import ugettext as _
import os
import logging
logger = logging.getLogger(__name__)
class Samba(module.Module):
"""
Samba 4 module, it deploys samba AD and file server
"""
E... | Use os.remove instead of os.unlink | Use os.remove instead of os.unlink
It's easier to understand
| Python | agpl-3.0 | exekias/droplet,exekias/droplet,exekias/droplet | ---
+++
@@ -24,7 +24,7 @@
"""
with root():
if os.path.exists(self.ETC_FILE):
- os.unlink(self.ETC_FILE)
+ os.remove(self.ETC_FILE)
run("samba-tool domain provision "
" --domain='zentyal' " |
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 | ---
+++
@@ -8,10 +8,13 @@
cur_process = psutil.Process()
all_processes = [cur_process] + cur_process.children(recursive=True)
rss = sum([p.memory_info().rss for p in all_processes])
+ mem_limit = os.environ.get('MEM_LIMIT', None)
+ if mem_limit is not None:
+ mem_limit = int(mem_limit)
... |
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 | ---
+++
@@ -1,9 +1,9 @@
databases = {
'mysql': {
'driver': 'mysql',
- 'host': '',
- 'database': '',
- 'user': '',
+ 'host': '127.0.0.1',
+ 'database': 'salam_bot',
+ 'user': 'root',
'password': '',
'prefix': ''
} |
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 | ---
+++
@@ -1,11 +1,16 @@
from sympy.abc import *
+from sympy.core.symbol import Symbol
-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)
+... |
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 | ---
+++
@@ -3,6 +3,15 @@
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):
@@ -14,6 +23,8 @@
def ... |
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 | ---
+++
@@ -3,7 +3,7 @@
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()
+ df.index = df.index.to_series().str.strip()
if trim_all:
df = df.applymap(lambda x: x.strip() if type(... |
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 | ---
+++
@@ -5,7 +5,7 @@
from config import basedir
from app import create_app, db
-from app.models import User
+from app.models import User, Dictionary
app = create_app(os.getenv("MYDICTIONARY_CONFIG") or "default")
@@ -13,7 +13,7 @@
manager = Manager(app)
def make_shell_context():
- return dict(app=a... |
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 | ---
+++
@@ -19,8 +19,8 @@
@app.route('/predict/', methods=['POST'])
def predict():
- sequence = flask.request.get_json(force=True)['sequence']
- resp = predict_structure.delay(sequence)
+ params = flask.request.get_json(force=True)
+ resp = predict_structure.delay(params['sequence'])
return succe... |
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 | ---
+++
@@ -20,7 +20,7 @@
email = EmailMessage(subject,
message_body,
'noreply@openstax.org',
- ["mwharrison@rice.edu"],
+ to_address,
reply_to=[from_string])
... |
7e2a14079d9b3112371facf3e31e20600e0136d4 | src/wrapt/__init__.py | src/wrapt/__init__.py | __version_info__ = ('1', '14', '0rc1')
__version__ = '.'.join(__version_info__)
from .wrappers import (ObjectProxy, CallableObjectProxy, FunctionWrapper,
BoundFunctionWrapper, WeakFunctionProxy, PartialCallableObjectProxy,
resolve_path, apply_patch, wrap_object, wrap_object_attribute,
function_... | __version_info__ = ('1', '14', '0')
__version__ = '.'.join(__version_info__)
from .wrappers import (ObjectProxy, CallableObjectProxy, FunctionWrapper,
BoundFunctionWrapper, WeakFunctionProxy, PartialCallableObjectProxy,
resolve_path, apply_patch, wrap_object, wrap_object_attribute,
function_wra... | Increment version to 1.14.0 for release. | Increment version to 1.14.0 for release.
| Python | bsd-2-clause | GrahamDumpleton/wrapt,GrahamDumpleton/wrapt | ---
+++
@@ -1,4 +1,4 @@
-__version_info__ = ('1', '14', '0rc1')
+__version_info__ = ('1', '14', '0')
__version__ = '.'.join(__version_info__)
from .wrappers import (ObjectProxy, CallableObjectProxy, FunctionWrapper, |
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 | ---
+++
@@ -11,4 +11,12 @@
obj.SetLoadAddress(0xffff, lldb.SBTarget())
obj.OffsetAddress(sys.maxint)
obj.GetDescription(lldb.SBStream())
+ obj.GetSectionType()
+ obj.GetSymbolContext(lldb.eSymbolContextEverything)
+ obj.GetModule()
+ obj.GetCompileUnit()
+ obj.GetFunction()
+ obj.GetB... |
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 | ---
+++
@@ -25,7 +25,7 @@
position = models.CharField(max_length=12, choices=POSITIONS)
- override_kicker = models.CharField(max_length=64, default='')
- override_title = models.CharField(max_length=265, default='')
- override_description = models.TextField(default='')
- override_background_color... |
5762826eb7b44d36bf4a3b1e50acd637ef7375c1 | dashboard/utils.py | dashboard/utils.py | from django.core.cache import cache
from django.utils import crypto
GENERATION_KEY_NAME = 'metric:generation'
def generation_key(timeout=60 * 60 * 365):
"""
A random key to be used in cache calls that allows
invalidating all values created with it. Use it with
the version parameter of cache.get/set.... | from django.core.cache import cache
from django.utils import crypto
GENERATION_KEY_NAME = 'metric:generation'
def generation_key(timeout=60 * 60 * 24 * 365):
"""
A random key to be used in cache calls that allows
invalidating all values created with it. Use it with
the version parameter of cache.get... | Fix typo in timeout of generation cache key. | Fix typo in timeout of generation cache key.
| Python | bsd-3-clause | gnarf/djangoproject.com,nanuxbe/django,xavierdutreilh/djangoproject.com,django/djangoproject.com,django/djangoproject.com,vxvinh1511/djangoproject.com,django/djangoproject.com,rmoorman/djangoproject.com,django/djangoproject.com,nanuxbe/django,rmoorman/djangoproject.com,xavierdutreilh/djangoproject.com,django/djangoproj... | ---
+++
@@ -5,7 +5,7 @@
GENERATION_KEY_NAME = 'metric:generation'
-def generation_key(timeout=60 * 60 * 365):
+def generation_key(timeout=60 * 60 * 24 * 365):
"""
A random key to be used in cache calls that allows
invalidating all values created with it. Use it with |
8a446ddb58615c7d5258887b7a0684fdcf85a356 | basic_modeling_interface/__init__.py | basic_modeling_interface/__init__.py | """The Basic Model Interface."""
from .bmi import Bmi
__all__ = ['Bmi']
__version__ = 0.1.0
| """The Basic Model Interface."""
from .bmi import Bmi
__all__ = ['Bmi']
__version__ = '0.1.0'
| Fix error with version number | Fix error with version number
| Python | mit | bmi-forum/bmi-python,bmi-forum/bmi-python | ---
+++
@@ -3,4 +3,4 @@
__all__ = ['Bmi']
-__version__ = 0.1.0
+__version__ = '0.1.0' |
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 | ---
+++
@@ -1,26 +1,44 @@
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'),... |
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 | ---
+++
@@ -1,3 +1,9 @@
+"""Produce SVG versions of active plots for display by the rich Qt frontend.
+"""
+#-----------------------------------------------------------------------------
+# Imports
+#-----------------------------------------------------------------------------
+
# Standard library imports
from cStr... |
69a7ec786841dc9d8422e31d8f0a513300d80c29 | seed_stage_based_messaging/testsettings.py | seed_stage_based_messaging/testsettings.py | from seed_stage_based_messaging.settings import * # flake8: noqa
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'TESTSEKRET'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_DEBUG = True
CELERY_TASK_EAGER_PROPAGATES = True
CELERY_TASK_ALWAYS_E... | from seed_stage_based_messaging.settings import * # noqa: F403
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'TESTSEKRET'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_DEBUG = True
CELERY_TASK_EAGER_PROPAGATES = True
CELERY_TASK_ALWAYS_EAG... | Fix noqa comments for new version of flake8 | Fix noqa comments for new version of flake8
| Python | bsd-3-clause | praekelt/seed-stage-based-messaging,praekelt/seed-stage-based-messaging,praekelt/seed-staged-based-messaging | ---
+++
@@ -1,4 +1,4 @@
-from seed_stage_based_messaging.settings import * # flake8: noqa
+from seed_stage_based_messaging.settings import * # noqa: F403
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'TESTSEKRET'
@@ -27,7 +27,7 @@
# REST Framework conf defaults
-REST_FRAME... |
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 | ---
+++
@@ -2,30 +2,40 @@
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][... |
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 | ---
+++
@@ -29,7 +29,7 @@
except (KeyError, AttributeError):
return False
-
+@requires_userinfo
def valid(test):
"""
Verify if server certificate is valid |
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 | ---
+++
@@ -11,5 +11,8 @@
def load_fdp_task(package, callback, connection_string=None):
if connection_string is not None:
_set_connection_string(connection_string)
- FDPLoader.load_fdp_to_db(package, get_engine())
- ret = requests.get(callback)
+ try:
+ FDPLoader.load_fdp_to_db(package,... |
4f88bc0022417872002d0c19a32cb26c3eb0c7ae | stella/__init__.py | stella/__init__.py | #!/usr/bin/env python
import logging
import faulthandler
from . import analysis
from . import codegen
_f = open('faulthandler.err', 'w')
faulthandler.enable(_f)
def wrap(f, debug=True, p=False, ir=False, lazy=False, opt=None, stats=None):
if debug:
logging.getLogger().setLevel(logging.DEBUG)
else:
... | #!/usr/bin/env python
import logging
import faulthandler
from . import analysis
from . import codegen
_f = open('faulthandler.err', 'w')
faulthandler.enable(_f)
def wrap(f, debug=True, p=False, ir=False, lazy=False, opt=None, stats=None):
if debug:
logging.getLogger().setLevel(logging.DEBUG)
else:
... | Add option to save ir to a text file | Add option to save ir to a text file
| Python | apache-2.0 | squisher/stella,squisher/stella,squisher/stella,squisher/stella | ---
+++
@@ -28,8 +28,12 @@
if lazy:
return prog
- elif ir:
+ elif ir == True:
return prog.module.getLlvmIR()
+ elif type(ir) == str:
+ with open(ir, 'w') as fh:
+ fh.write(prog.module.getLlvmIR())
+ return
elif p:
... |
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... | ---
+++
@@ -21,7 +21,7 @@
{
"name": "Move existing attachments to filesystem",
"version": "1.0",
- "author": "Therp BV",
+ "author": "Therp BV,Odoo Community Association (OCA)",
"license": "AGPL-3",
"complexity": "normal",
"category": "Knowledge Management", |
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 | ---
+++
@@ -40,5 +40,7 @@
def test_area():
"""
-
+ Verify area of circle
"""
+ c = Circle(5)
+ assert c.area == 25 |
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 | ---
+++
@@ -16,7 +16,7 @@
input_type = "text"
- def render(self, name, value, attrs=None):
+ def render(self, name, value, attrs=None, renderer=None):
if attrs:
attrs.update(self.attrs)
attrs["type"] = "hidden" |
6d7c91419c128fde3f3a9a68942dedf61c7c8b3c | server.py | server.py | import flask
import psycopg2
app = flask.Flask(__name__)
db = psycopg2.connect('postgres://rpitours:rpitours@localhost:5432/rpitours')
def make_tour():
tour = {
'id': 1,
'name': 'Test Tour',
'waypoints': [
(5, 2),
(2, 3),
(1, 4),
(4, 4)
],
'landmarks': [
{
'name': 'A Place',
'descrip... | import flask
import psycopg2
DB_URL = 'postgres://rpitours:rpitours@localhost:5432/rpitours'
app = flask.Flask(__name__)
def get_db():
db = getattr(flask.g, 'database', None)
if db is None:
db = flask.g.database = psycopg2.connect(DB_URL)
return db
def make_tour():
tour = {
'id': 1,
'name': 'Test Tour',
... | Move database connection code into thread-local context | Move database connection code into thread-local context
| Python | mit | wtg/RPI_Tours_Server | ---
+++
@@ -1,8 +1,15 @@
import flask
import psycopg2
+DB_URL = 'postgres://rpitours:rpitours@localhost:5432/rpitours'
+
app = flask.Flask(__name__)
-db = psycopg2.connect('postgres://rpitours:rpitours@localhost:5432/rpitours')
+
+def get_db():
+ db = getattr(flask.g, 'database', None)
+ if db is None:
+ db = f... |
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 | ---
+++
@@ -20,6 +20,13 @@
specification = spec_factory(default_section=Section("Dalton Maag OpenType"))
specification.set_check_filter(check_filter)
specification.auto_register(
- globals(), spec_imports=['fontbakery.specifications.opentype'])
+ globals(), spec_imports=["fontbakery.specifications.... |
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 | ---
+++
@@ -25,3 +25,25 @@
def standardize(x):
return (x - np.nanmean(x)) / np.nanstd(x)
+
+
+def kl_divergence(P, Q):
+ '''
+ Kullback Leidler Divergence
+
+ Parameters
+ ----------
+
+ P,Q : numpy.ndarray
+ Two Discrete Probability distributions
+
+ Returns
+ -------
+
+ kl_di... |
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 | ---
+++
@@ -26,15 +26,18 @@
"""
args = parse(argv=argv)
- if args.subparser_name == "profile":
- from dodocs.profiles import main
- main(args)
- # elif args.subparser_name == "mkvenv":
- # from dodocs.venvs import create
- # create(args)
- # elif args.subparser_name ==... |
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 | ---
+++
@@ -1,28 +1,28 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
import os
-import pytest
import sys
-from mediawords.tm.guess_date import guess_date, McGuessDateException
+from mediawords.tm.guess_date import guess_date
-def main():
- if (len(sys.argv) < 2):
- sys.stderr.write('usage: ' + s... |
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 | ---
+++
@@ -25,7 +25,7 @@
@classmethod
def output(cls, pin, status):
- print("Mock: output GPIO pin {} to {}".format(pin, status))
+ pass
@classmethod
def add_event_detect(cls, pin, status, **kwargs): |
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 | ---
+++
@@ -27,8 +27,11 @@
location = LocationSerializer()
organisation = OrganisationSerializer()
distance = DistanceField()
+ categories = serializers.SlugRelatedField(
+ slug_field='code', many=True, read_only=True)
class Meta:
model = Office
fields = (
- ... |
f6b60723983997a5a0a9328d9a569aeb9b7f9e71 | dist/tools/kconfiglib/riot_menuconfig.py | dist/tools/kconfiglib/riot_menuconfig.py | #!/usr/bin/env python
""" Menuconfig variant which uses RiotKconfig as base class """
import menuconfig
from riot_kconfig import standard_riot_kconfig
# keep documentation from the original tool
__doc__ = menuconfig.__doc__
if __name__ == "__main__":
menuconfig.menuconfig(standard_riot_kconfig(__doc__))
| #!/usr/bin/env python3
""" Menuconfig variant which uses RiotKconfig as base class """
import menuconfig
from riot_kconfig import standard_riot_kconfig
# keep documentation from the original tool
__doc__ = menuconfig.__doc__
if __name__ == "__main__":
menuconfig.menuconfig(standard_riot_kconfig(__doc__))
| Use python3 for RIOT adaption of menuconfig | dist/tools/kconfiglib: Use python3 for RIOT adaption of menuconfig
| Python | lgpl-2.1 | OlegHahm/RIOT,authmillenon/RIOT,miri64/RIOT,jasonatran/RIOT,RIOT-OS/RIOT,RIOT-OS/RIOT,miri64/RIOT,kaspar030/RIOT,OTAkeys/RIOT,ant9000/RIOT,miri64/RIOT,OTAkeys/RIOT,kYc0o/RIOT,miri64/RIOT,authmillenon/RIOT,OTAkeys/RIOT,kaspar030/RIOT,kYc0o/RIOT,jasonatran/RIOT,ant9000/RIOT,authmillenon/RIOT,RIOT-OS/RIOT,authmillenon/RIO... | ---
+++
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
""" Menuconfig variant which uses RiotKconfig as base class """
import menuconfig
from riot_kconfig import standard_riot_kconfig |
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 | ---
+++
@@ -1,8 +1,9 @@
from corehq.apps.users.models import CommCareUser
-def _users_by_location(location_id, include_docs):
- return CommCareUser.view(
+def _users_by_location(location_id, include_docs, wrap):
+ view = CommCareUser.view if wrap else CommCareUser.get_db().view
+ return view(
'... |
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 | ---
+++
@@ -3,6 +3,7 @@
__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,
@@ -10,5 +11,5 @@
percentage, decimal_percentage,
total_seco... |
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 | ---
+++
@@ -1,8 +1,6 @@
"""Dispatch from command-line arguments to functions."""
import re
from collections import OrderedDict
-
-from docopt import docopt
__all__ = ('dispatch', 'DispatchError')
@@ -29,6 +27,7 @@
return decorator
def __call__(self, *args, **kwargs):
+ from docopt impor... |
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 | ---
+++
@@ -46,5 +46,4 @@
source_path = 'docs/'
-is_prerelease = True
hide_page_contents = ('search', '404', 'contents') |
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 | ---
+++
@@ -1,5 +1,4 @@
-import collections
-
+from src.data import meta
from src.puzzle.problems import crossword_problem
@@ -7,14 +6,12 @@
def identify(line):
- scores = {}
+ scores = meta.Meta()
for t in _PROBLEM_TYPES:
score = t.score(line)
if score:
scores[t] = t.score(line)
- # ... |
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... | ---
+++
@@ -1,9 +1,17 @@
-VERSION = (1, 0, 'post-release-SVN')
+VERSION = (1, 1, 0, 'alpha', 0)
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-... |
2a5da76476fe3b13274b5c6d14f605d4b768047e | hack/utils/command.py | hack/utils/command.py | #!/usr/bin/env python
"""
Copyright 2018 Google LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to ... | #!/usr/bin/env python
"""
Copyright 2018 Google LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to ... | Disable debug output to avoid hanging on prow | Disable debug output to avoid hanging on prow
| Python | apache-2.0 | GoogleCloudPlatform/gke-managed-certs,GoogleCloudPlatform/gke-managed-certs | ---
+++
@@ -35,7 +35,7 @@
if info is not None:
print("### {0}".format(info))
- print("### Executing $ {0}".format(command))
+ #print("### Executing $ {0}".format(command))
p = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)
output = filter(None, p.communicate()[0].split("\n"))
retur... |
3732b2ee099989ed46e264f031b9b47c414cf6c6 | imagekit/importers.py | imagekit/importers.py | import re
import sys
class ProcessorImporter(object):
"""
The processors were moved to the PILKit project so they could be used
separtely from ImageKit (which has a bunch of Django dependencies). However,
there's no real need to expose this fact (and we want to maintain backwards
compatibility), s... | import re
import sys
class ProcessorImporter(object):
"""
The processors were moved to the PILKit project so they could be used
separtely from ImageKit (which has a bunch of Django dependencies). However,
there's no real need to expose this fact (and we want to maintain backwards
compatibility), s... | Insert importer at beginning of list | Insert importer at beginning of list
| Python | bsd-3-clause | tawanda/django-imagekit,FundedByMe/django-imagekit,tawanda/django-imagekit,FundedByMe/django-imagekit | ---
+++
@@ -26,4 +26,4 @@
return import_module(new_name)
-sys.meta_path.append(ProcessorImporter())
+sys.meta_path.insert(0, ProcessorImporter()) |
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 | ---
+++
@@ -1,5 +1,5 @@
from django.test import TestCase
-from ..models import Temperature, HeartBeats
+from ..models import Temperature, HeartBeats, Breathing
class TemperatureTest(TestCase):
@@ -26,3 +26,16 @@
self.assertIsNotNone(heartBeats)
self.assertTrue(isinstance(heartBeats, HeartBeats... |
96c08c28ac9c812a209bde504dfbb3d0aea023d3 | valohai_cli/cli.py | valohai_cli/cli.py | import pkgutil
from importlib import import_module
import click
from . import commands as commands_module
command_modules = sorted(c[1] for c in pkgutil.iter_modules(commands_module.__path__))
class PluginCLI(click.MultiCommand):
def list_commands(self, ctx):
return command_modules
def get_command(... | import pkgutil
from importlib import import_module
import click
from . import commands as commands_module
from .utils import match_prefix
command_modules = sorted(c[1] for c in pkgutil.iter_modules(commands_module.__path__))
class PluginCLI(click.MultiCommand):
def list_commands(self, ctx):
return comm... | Allow invoking commands by unique prefix | Allow invoking commands by unique prefix
| Python | mit | valohai/valohai-cli | ---
+++
@@ -4,6 +4,8 @@
import click
from . import commands as commands_module
+from .utils import match_prefix
+
command_modules = sorted(c[1] for c in pkgutil.iter_modules(commands_module.__path__))
@@ -13,8 +15,26 @@
def get_command(self, ctx, name):
if name in command_modules:
- ... |
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 | ---
+++
@@ -1,9 +1,12 @@
class VirtualMachine:
- def __init__(self, ram_size=256, stack_size=32):
+ 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_si... |
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 | ---
+++
@@ -1,9 +1,10 @@
class VirtualMachine:
- def __init__(self, ram_size=256, executing=True):
- self.data = [None]*ram_size
+ def __init__(self, ram_size=512, executing=True):
+ self.data = {i: None for i in range(ram_size)}
self.stack = []
self.executing = executing
... |
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 | ---
+++
@@ -2,7 +2,7 @@
import logging
from datetime import datetime, timedelta
from celery.decorators import task
-from eve_proxy.models import CachedDocument
+from eve_proxy.models import CachedDocument, ApiAccessLog
@task(ignore_result=True)
def clear_stale_cache(cache_extension=0): |
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 | ---
+++
@@ -16,8 +16,10 @@
def openConnection():
config = TestConfig()
mgd = Midgard.Connection()
- mgd.open_config(config)
- return mgd
+ if mgd.open_config(config) is True:
+ return mgd
+ print mgd.get_error_string()
+ return None
class TestMethods(unittest.TestCase):
def test... |
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 | ---
+++
@@ -1,5 +1,6 @@
# -*- coding: utf-8 -*-
+import sys
import subprocess as subp
@@ -10,6 +11,8 @@
cmd = 'if hash {} 2/dev/null; then ' \
'echo 1; else echo 0; fi'.format(dep)
available = subp.check_output(cmd, shell=True, stderr=subp.STDOUT)
+ if s... |
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 | ---
+++
@@ -5,3 +5,39 @@
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 this test because we'll need to specify namespaces.
+ "... |
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 | ---
+++
@@ -1,12 +1,12 @@
from django.test import TestCase
-from member.models import Member
+from member.models import Member, Client
from datetime import date
class MemberTestCase(TestCase):
def setUp(self):
- Member.objects.create(firstname='Katrina', birthdate=date(1980, 4, 19))
+ Memb... |
825f2ff3726bc4bc04ad8adb5583bfbf26fe6319 | fileshack/admin.py | fileshack/admin.py | from .models import *
from django.contrib import admin
class StoreAdmin(admin.ModelAdmin):
list_display = ("__unicode__",)
class ItemAdmin(admin.ModelAdmin):
pass
admin.site.register(Store, StoreAdmin)
admin.site.register(Item, ItemAdmin)
| from .models import *
from django.contrib import admin
class StoreAdmin(admin.ModelAdmin):
list_display = ("__str__",)
class ItemAdmin(admin.ModelAdmin):
pass
admin.site.register(Store, StoreAdmin)
admin.site.register(Item, ItemAdmin)
| Fix ref to non-existent __unicode__ function | Fix ref to non-existent __unicode__ function
| Python | mit | peterkuma/fileshackproject,peterkuma/fileshackproject,peterkuma/fileshackproject | ---
+++
@@ -2,7 +2,7 @@
from django.contrib import admin
class StoreAdmin(admin.ModelAdmin):
- list_display = ("__unicode__",)
+ list_display = ("__str__",)
class ItemAdmin(admin.ModelAdmin):
pass |
255dd790c1075c5caaf21042dc8b056330a9e846 | services/qrcode/qrcode_fromwebcam.py | services/qrcode/qrcode_fromwebcam.py | #!/usr/bin/env python
import StringIO
import angus
import cv2
import numpy as np
if __name__ == '__main__':
### Web cam index might be different from 0 on your setup.
stream_index = 0
cap = cv2.VideoCapture(stream_index)
if not cap.isOpened():
print "Cannot open stream of index " + str(stream... | #!/usr/bin/env python
import StringIO
import angus
import cv2
import numpy as np
if __name__ == '__main__':
### Web cam index might be different from 0 on your setup.
stream_index = 0
cap = cv2.VideoCapture(stream_index)
if not cap.isOpened():
print "Cannot open stream of index " + str(stream... | Remove useless parenthesis in qrcode python demo | Remove useless parenthesis in qrcode python demo
| Python | apache-2.0 | angus-ai/angus-doc,angus-ai/angus-doc,angus-ai/angus-doc | ---
+++
@@ -20,7 +20,7 @@
service = conn.services.get_service("qrcode_decoder", version=1)
service.enable_session()
- while(cap.isOpened()):
+ while cap.isOpened():
ret, frame = cap.read()
if frame is None:
break |
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 | ---
+++
@@ -1,14 +1,23 @@
# -*- coding: utf-8 -*-
-from marshmallow import Schema, fields
+from marshmallow import Schema, fields, validates_schema, ValidationError
__author__ = 'lundberg'
-class FluxStandardAction(Schema):
+class EduidSchema(Schema):
class Meta:
strict = True
+
+ @valida... |
b67a460ea0c1dd8b7b820c8d151afb69ba17fbb3 | volunteers/migrations/0002_tasktemplate_primary.py | volunteers/migrations/0002_tasktemplate_primary.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.16 on 2018-11-25 21:06
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_depend... | # -*- coding: utf-8 -*-
# Generated by Django 1.11.16 on 2018-11-25 21:06
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_depend... | Remove initial migration for 002 | Remove initial migration for 002
| Python | agpl-3.0 | FOSDEM/volunteers,FOSDEM/volunteers,jrial/fosdem-volunteers,jrial/fosdem-volunteers,FOSDEM/volunteers,FOSDEM/volunteers,jrial/fosdem-volunteers,jrial/fosdem-volunteers | ---
+++
@@ -11,7 +11,7 @@
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
- ('volunteers', '0001_initial'),
+# ('volunteers', '0001_initial'),
]
operations = [ |
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... | ---
+++
@@ -2,6 +2,7 @@
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
@@ -17,6 +18,10 @@
db.start_transaction()
ContentType.objects.filter(app_lab... |
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 | ---
+++
@@ -4,6 +4,7 @@
LicenseSummarySerializer,
UserSummarySerializer,
IdentitySummarySerializer,
+ ImageSummarySerializer,
ImageVersionSummarySerializer)
from api.v2.serializers.fields import ProviderMachineRelatedField
@@ -25,6 +26,7 @@
user = UserSummarySerializer(source='created_b... |
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... | ---
+++
@@ -29,5 +29,4 @@
'py', config=True,
help="Extension of the file that should be written to disk")
- def _output_mimetype_default(self):
- return 'text/x-python'
+ output_mimetype = 'text/x-python' |
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 | ---
+++
@@ -1,17 +1,19 @@
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.termi... |
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 | ---
+++
@@ -33,3 +33,11 @@
def test_path_management_factory(self):
factories.TrailFactory()
+
+ def test_path_in_bounds_existing_factory(self):
+ factories.PathFactory.create()
+ factories.PathInBoundsExistingGeomFactory()
+
+ def test_path_in_bounds_not_existing_factory(self):
+ ... |
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 | ---
+++
@@ -1,7 +1,7 @@
import time
import os
+import tempfile
-from tempfile import NamedTemporaryFile
from sys import platform as _platform
from gtts import gTTS
@@ -27,13 +27,12 @@
print('To say out loud : {}'.format(sentence))
tts = gTTS(text=sentence, lang='en')
if ... |
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 | ---
+++
@@ -1,4 +1,5 @@
from django.conf import settings
+from django.contrib.sites.models import Site
from django.utils import timezone
import pytz
@@ -7,6 +8,7 @@
def core_context(self):
"""Context processor for elements appearing on every page."""
context = {}
+ context["conference_title"] = Sit... |
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... | ---
+++
@@ -25,11 +25,12 @@
:param elem:
:return: anpa category list qcode
"""
- category = elem.get('content')[:1].upper()
- if category in ('S', 'R', 'F'):
- return [{'qcode': 'S'}]
- if category == 'Z':
- return [{'qcode': 'V'}]
+ if elem... |
1e14cf9011820c4e65fc779df976596dae225735 | project_template/icekit_settings.py | project_template/icekit_settings.py | # Do not commit secrets to VCS.
# Local environment variables will be loaded from `.env.local`.
# Additional environment variables will be loaded from `.env.$DOTENV`.
# Local settings will be imported from `icekit_settings_local.py`
from icekit.project.settings.calculated import *
# OVERRIDE ########################... | # Do not commit secrets to VCS.
# Local environment variables will be loaded from `.env.local`.
# Additional environment variables will be loaded from `.env.$DOTENV`.
# Local settings will be imported from `icekit_settings_local.py`
from icekit.project.settings.calculated import *
# OVERRIDE ########################... | Add press releases to dashboard panel | Add press releases to dashboard panel
| Python | mit | ic-labs/django-icekit,ic-labs/django-icekit,ic-labs/django-icekit,ic-labs/django-icekit | ---
+++
@@ -29,11 +29,6 @@
FEATURED_APPS[0]['models']['glamkit_articles.Article'] = {
'verbose_name_plural': 'Articles',
}
-
-ICEKIT['LAYOUT_TEMPLATES'] += (
- (
- SITE_NAME,
- os.path.join(PROJECT_DIR, 'templates/layouts'),
- 'layouts',
- ),
-)
+FEATURED_APPS[0]['models']['icekit_pr... |
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 | ---
+++
@@ -25,8 +25,6 @@
def convert_to_utf8_str(arg):
# written by Michael Norton (http://docondev.blogspot.com/)
- if isinstance(arg, bytes):
- arg = arg.decode('ascii')
if isinstance(arg, six.text_type):
arg = arg.encode('utf-8')
elif not isinstance(arg, bytes): |
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 | ---
+++
@@ -50,3 +50,6 @@
pass_with_salt = password + user.salt
user.password = hashlib.sha224(pass_with_salt.encode()).hexdigest()
user.save()
+
+ def __repr__(self):
+ return '<User %r>' % self.username |
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 | ---
+++
@@ -16,6 +16,10 @@
"""Return the show feed URL with different protocol."""
if len(kwargs) != 2:
raise TemplateSyntaxError(_('"show_url" tag takes exactly two keyword arguments.'))
- current_site = get_current_site(context['request'])
+ try:
+ request = context['request']
+ e... |
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 | ---
+++
@@ -1,9 +1,24 @@
"""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 express... |
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 | ---
+++
@@ -2,6 +2,7 @@
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): |
06ce6272209b9a8749156b69dfa22aa9130f743a | tests_tf/test_mnist_tutorial_jsma.py | tests_tf/test_mnist_tutorial_jsma.py | import unittest
import numpy as np
class TestMNISTTutorialJSMA(unittest.TestCase):
def test_mnist_tutorial_jsma(self):
np.random.seed(42)
import tensorflow as tf
tf.set_random_seed(42)
from tutorials import mnist_tutorial_jsma
# Run the MNIST tutorial on a dataset of red... | import unittest
import numpy as np
class TestMNISTTutorialJSMA(unittest.TestCase):
def test_mnist_tutorial_jsma(self):
np.random.seed(42)
import tensorflow as tf
tf.set_random_seed(42)
from tutorials import mnist_tutorial_jsma
# Run the MNIST tutorial on a dataset of red... | Revert cherry-picked jsma tutorial constant change | Revert cherry-picked jsma tutorial constant change
| Python | mit | fartashf/cleverhans,openai/cleverhans,carlini/cleverhans,cleverhans-lab/cleverhans,cihangxie/cleverhans,carlini/cleverhans,cleverhans-lab/cleverhans,cleverhans-lab/cleverhans | ---
+++
@@ -16,7 +16,7 @@
jsma_tutorial_args = {'train_start': 0,
'train_end': 1000,
'test_start': 0,
- 'test_end': 166,
+ 'test_end': 1666,
'viz_enabled': Fa... |
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 | ---
+++
@@ -4,7 +4,7 @@
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'lims.settings')
-app = Celery('lims', broker='redis://localhost', backend='redis')
+app = Celery('lims', broker=os.environ.get('REDIS_URL', 'redis://127.0.0.1:6379'), backend='redis')
app.config_from_object('django.conf:settings', namespac... |
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 | ---
+++
@@ -5,19 +5,55 @@
"""
#-------------------------------------------------------------------------------
-__version__ = "1.0.0"
+__version__ = '2.0.0'
+
+#-------------------------------------------------------------------------------
import hou
+HOUDINI_MAJOR_VERSION = hou.applicationVersion()[0]
+
+
... |
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 | ---
+++
@@ -1,4 +1,5 @@
-import youtube_dl, os
+import os, youtube_dl
+from youtube_dl import YoutubeDL
from multiprocessing.pool import ThreadPool
from youtube_dl.utils import DownloadError
from datetime import datetime
@@ -6,34 +7,49 @@
class Download:
- link = ""
+ link = ''
done = False
er... |
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 | ---
+++
@@ -40,3 +40,9 @@
label=_('Organisation'),
queryset=Organisation.objects,
required=False, empty_label=None)
+
+ def clean(self):
+ cleaned_data = super().clean()
+ if cleaned_data.get('receivers') == str(models.PROJECT) and \
+ not cleaned... |
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 | ---
+++
@@ -1,4 +1,5 @@
import os
+import sys
from .. import run_python_module, run_command
from .base import BaseTestApp
@@ -29,6 +30,9 @@
def test_check_version(self):
"""Is the version the same regardless of how we run nbgrader?"""
- out1 = run_command(["nbgrader", "--version"])
+ ... |
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 | ---
+++
@@ -20,6 +20,10 @@
@property
def crypto(self):
return self.envcfg['crypto']
+
+ @property
+ def extcreds(self):
+ return self.envcfg['extcreds']
def __init__(self, requested_env):
cfg_file = "%s/envcfg.json" % ( os.environ.get("OPENARC_CFG_DIR") ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.