commit
stringlengths 40
40
| old_file
stringlengths 4
118
| new_file
stringlengths 4
118
| old_contents
stringlengths 10
2.94k
| new_contents
stringlengths 21
3.18k
| subject
stringlengths 16
444
| message
stringlengths 17
2.63k
| lang
stringclasses 1
value | license
stringclasses 13
values | repos
stringlengths 5
43k
| ndiff
stringlengths 51
3.32k
| instruction
stringlengths 16
444
| content
stringlengths 133
4.32k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
727ec507284776f3eec91b644cd5bb112bdb0af1 | july/people/forms.py | july/people/forms.py | from django import forms
class EditUserForm(forms.Form):
about_me = forms.CharField(widget=forms.Textarea, required=False)
url = forms.CharField(max_length=255, required=False)
facebook_url = forms.CharField(max_length=255, required=False)
email = forms.EmailField(max_length=255)
def __init__(self, *args, **kwargs):
user = kwargs.pop('user', None)
super(EditUserForm, self).__init__(*args, **kwargs)
if user:
self.fields['about_me'].initial=user.about_me
self.fields['url'].initial=user.url
self.fields['facebook_url'].initial=user.facebook_url
self.fields['email'].initial=user.email
| from django import forms
class EditUserForm(forms.Form):
about_me = forms.CharField(widget=forms.Textarea, required=False)
url = forms.CharField(max_length=255, required=False)
facebook_url = forms.CharField(max_length=255, required=False)
email = forms.EmailField(max_length=255)
def __init__(self, *args, **kwargs):
user = kwargs.pop('user', None)
super(EditUserForm, self).__init__(*args, **kwargs)
if user:
self.fields['about_me'].initial=getattr(user, 'about_me', None)
self.fields['url'].initial=getattr(user, 'url', None)
self.fields['facebook_url'].initial=getattr(user, 'facebook_url', None)
self.fields['email'].initial=user.email
| Use getattr for expando props | Use getattr for expando props
| Python | mit | julython/julython.org,julython/julython.org,ChimeraCoder/GOctober,julython/julython.org,ChimeraCoder/GOctober,julython/julython.org,ChimeraCoder/GOctober | from django import forms
class EditUserForm(forms.Form):
about_me = forms.CharField(widget=forms.Textarea, required=False)
url = forms.CharField(max_length=255, required=False)
facebook_url = forms.CharField(max_length=255, required=False)
email = forms.EmailField(max_length=255)
def __init__(self, *args, **kwargs):
user = kwargs.pop('user', None)
super(EditUserForm, self).__init__(*args, **kwargs)
if user:
- self.fields['about_me'].initial=user.about_me
+ self.fields['about_me'].initial=getattr(user, 'about_me', None)
- self.fields['url'].initial=user.url
+ self.fields['url'].initial=getattr(user, 'url', None)
- self.fields['facebook_url'].initial=user.facebook_url
+ self.fields['facebook_url'].initial=getattr(user, 'facebook_url', None)
self.fields['email'].initial=user.email
| Use getattr for expando props | ## Code Before:
from django import forms
class EditUserForm(forms.Form):
about_me = forms.CharField(widget=forms.Textarea, required=False)
url = forms.CharField(max_length=255, required=False)
facebook_url = forms.CharField(max_length=255, required=False)
email = forms.EmailField(max_length=255)
def __init__(self, *args, **kwargs):
user = kwargs.pop('user', None)
super(EditUserForm, self).__init__(*args, **kwargs)
if user:
self.fields['about_me'].initial=user.about_me
self.fields['url'].initial=user.url
self.fields['facebook_url'].initial=user.facebook_url
self.fields['email'].initial=user.email
## Instruction:
Use getattr for expando props
## Code After:
from django import forms
class EditUserForm(forms.Form):
about_me = forms.CharField(widget=forms.Textarea, required=False)
url = forms.CharField(max_length=255, required=False)
facebook_url = forms.CharField(max_length=255, required=False)
email = forms.EmailField(max_length=255)
def __init__(self, *args, **kwargs):
user = kwargs.pop('user', None)
super(EditUserForm, self).__init__(*args, **kwargs)
if user:
self.fields['about_me'].initial=getattr(user, 'about_me', None)
self.fields['url'].initial=getattr(user, 'url', None)
self.fields['facebook_url'].initial=getattr(user, 'facebook_url', None)
self.fields['email'].initial=user.email
|
2267f31ba91ea649c54a51ab3e8f3babbe72f44e | openliveq/collection.py | openliveq/collection.py | from collections import defaultdict
class Collection(object):
DOC_FROM = ["question_body", "best_answer_body"]
def __init__(self):
'''
Compute the following statistics
df: document frequency
cf: collection frequency
dn: total number of documents
cn: total number of words
'''
self.df = defaultdict(int)
self.cf = defaultdict(int)
self.dn = 0
self.cn = 0
def add(self, wordsets):
'''
Add a question
'''
for label in self.DOC_FROM:
for w in set(wordsets[label].keys()):
self.df[w] += 1
self.cf[w] += wordsets[label][w]
self.cn += wordsets[label][w]
self.dn += 1
| from collections import defaultdict
class Collection(object):
DOC_FROM = ["question_body", "best_answer_body"]
def __init__(self):
'''
Compute the following statistics
df: document frequency
cf: collection frequency
dn: total number of documents
cn: total number of words
'''
self.df = defaultdict(int)
self.cf = defaultdict(int)
self.dn = 0
self.cn = 0
def add(self, wordsets):
'''
Add a question
'''
for label in self.DOC_FROM:
for w in set(wordsets[label].keys()):
self.df[w] += 1
self.cf[w] += wordsets[label][w]
self.cn += wordsets[label][w]
self.dn += 1
@property
def avgdlen(self):
return float(self.cn) / self.dn
| Add avddlen property to Collection | Add avddlen property to Collection
| Python | mit | mpkato/openliveq | from collections import defaultdict
class Collection(object):
DOC_FROM = ["question_body", "best_answer_body"]
def __init__(self):
'''
Compute the following statistics
df: document frequency
cf: collection frequency
dn: total number of documents
cn: total number of words
'''
self.df = defaultdict(int)
self.cf = defaultdict(int)
self.dn = 0
self.cn = 0
def add(self, wordsets):
'''
Add a question
'''
for label in self.DOC_FROM:
for w in set(wordsets[label].keys()):
self.df[w] += 1
self.cf[w] += wordsets[label][w]
self.cn += wordsets[label][w]
self.dn += 1
+ @property
+ def avgdlen(self):
+ return float(self.cn) / self.dn
+ | Add avddlen property to Collection | ## Code Before:
from collections import defaultdict
class Collection(object):
DOC_FROM = ["question_body", "best_answer_body"]
def __init__(self):
'''
Compute the following statistics
df: document frequency
cf: collection frequency
dn: total number of documents
cn: total number of words
'''
self.df = defaultdict(int)
self.cf = defaultdict(int)
self.dn = 0
self.cn = 0
def add(self, wordsets):
'''
Add a question
'''
for label in self.DOC_FROM:
for w in set(wordsets[label].keys()):
self.df[w] += 1
self.cf[w] += wordsets[label][w]
self.cn += wordsets[label][w]
self.dn += 1
## Instruction:
Add avddlen property to Collection
## Code After:
from collections import defaultdict
class Collection(object):
DOC_FROM = ["question_body", "best_answer_body"]
def __init__(self):
'''
Compute the following statistics
df: document frequency
cf: collection frequency
dn: total number of documents
cn: total number of words
'''
self.df = defaultdict(int)
self.cf = defaultdict(int)
self.dn = 0
self.cn = 0
def add(self, wordsets):
'''
Add a question
'''
for label in self.DOC_FROM:
for w in set(wordsets[label].keys()):
self.df[w] += 1
self.cf[w] += wordsets[label][w]
self.cn += wordsets[label][w]
self.dn += 1
@property
def avgdlen(self):
return float(self.cn) / self.dn
|
072eeaf0efbc299efac0be6fc7499f2d48dacd1a | BudgetModelHelper.py | BudgetModelHelper.py | from DataModel import DataModel
from DataModelAdapter import DataModelAdapter
from Ledger import Ledger
import pickle
DATA_FILE='ledger.pickle'
def get_ledger() :
result = None
try:
with open(DATA_FILE, 'rb') as infile:
result = pickle.load(infile)
except FileNotFoundError:
result = Ledger()
def get_model() :
model = DataModel()
model.setHeaders(list(model.root.keys()))
return model
def save_ledger(ledger) :
with open(DATA_FILE, 'wb') as outfile:
pickle.dump(ledger, outfile, pickle.HIGHEST_PROTOCOL)
| from DataModel import DataModel
from DataModelAdapter import DataModelAdapter
from Ledger import Ledger
import pickle
DATA_FILE='ledger.pickle'
def get_ledger() :
result = None
try:
with open(DATA_FILE, 'rb') as infile:
result = pickle.load(infile)
except FileNotFoundError:
pass
except EOFError:
pass
if not result: result = Ledger()
return result
def get_model() :
model = DataModel()
model.setHeaders(list(model.root.keys()))
return model
def save_ledger(ledger) :
with open(DATA_FILE, 'wb') as outfile:
pickle.dump(ledger, outfile, pickle.HIGHEST_PROTOCOL)
| Handle EOFError on pickle load | Handle EOFError on pickle load
| Python | apache-2.0 | mattdeckard/wherewithal | from DataModel import DataModel
from DataModelAdapter import DataModelAdapter
from Ledger import Ledger
import pickle
DATA_FILE='ledger.pickle'
def get_ledger() :
result = None
try:
with open(DATA_FILE, 'rb') as infile:
result = pickle.load(infile)
except FileNotFoundError:
- result = Ledger()
+ pass
+ except EOFError:
+ pass
+
+ if not result: result = Ledger()
+ return result
def get_model() :
model = DataModel()
model.setHeaders(list(model.root.keys()))
return model
def save_ledger(ledger) :
with open(DATA_FILE, 'wb') as outfile:
pickle.dump(ledger, outfile, pickle.HIGHEST_PROTOCOL)
| Handle EOFError on pickle load | ## Code Before:
from DataModel import DataModel
from DataModelAdapter import DataModelAdapter
from Ledger import Ledger
import pickle
DATA_FILE='ledger.pickle'
def get_ledger() :
result = None
try:
with open(DATA_FILE, 'rb') as infile:
result = pickle.load(infile)
except FileNotFoundError:
result = Ledger()
def get_model() :
model = DataModel()
model.setHeaders(list(model.root.keys()))
return model
def save_ledger(ledger) :
with open(DATA_FILE, 'wb') as outfile:
pickle.dump(ledger, outfile, pickle.HIGHEST_PROTOCOL)
## Instruction:
Handle EOFError on pickle load
## Code After:
from DataModel import DataModel
from DataModelAdapter import DataModelAdapter
from Ledger import Ledger
import pickle
DATA_FILE='ledger.pickle'
def get_ledger() :
result = None
try:
with open(DATA_FILE, 'rb') as infile:
result = pickle.load(infile)
except FileNotFoundError:
pass
except EOFError:
pass
if not result: result = Ledger()
return result
def get_model() :
model = DataModel()
model.setHeaders(list(model.root.keys()))
return model
def save_ledger(ledger) :
with open(DATA_FILE, 'wb') as outfile:
pickle.dump(ledger, outfile, pickle.HIGHEST_PROTOCOL)
|
73f75efcfe69210d8e22ff55c19b02b7408b9671 | pseudorandom.py | pseudorandom.py | from flask import Flask, render_template
from names import get_full_name
app = Flask(__name__)
@app.route("/")
def index():
return render_template('index.html', name=get_full_name())
if __name__ == "__main__":
app.run()
| import os
from flask import Flask, render_template
from names import get_full_name
app = Flask(__name__)
@app.route("/")
def index():
return render_template('index.html', name=get_full_name())
if __name__ == "__main__":
port = int(os.environ.get('PORT', 5000))
app.run(host='0.0.0.0', port=port)
| Use environment variable PORT for flask port | Use environment variable PORT for flask port
| Python | mit | treyhunner/pseudorandom.name,treyhunner/pseudorandom.name | + import os
from flask import Flask, render_template
from names import get_full_name
app = Flask(__name__)
@app.route("/")
def index():
return render_template('index.html', name=get_full_name())
if __name__ == "__main__":
- app.run()
+ port = int(os.environ.get('PORT', 5000))
+ app.run(host='0.0.0.0', port=port)
| Use environment variable PORT for flask port | ## Code Before:
from flask import Flask, render_template
from names import get_full_name
app = Flask(__name__)
@app.route("/")
def index():
return render_template('index.html', name=get_full_name())
if __name__ == "__main__":
app.run()
## Instruction:
Use environment variable PORT for flask port
## Code After:
import os
from flask import Flask, render_template
from names import get_full_name
app = Flask(__name__)
@app.route("/")
def index():
return render_template('index.html', name=get_full_name())
if __name__ == "__main__":
port = int(os.environ.get('PORT', 5000))
app.run(host='0.0.0.0', port=port)
|
41b1d36a9d5fcb0dd2f6da53a7a0d4604b21a0eb | tests/query_test/test_scan_range_lengths.py | tests/query_test/test_scan_range_lengths.py | import pytest
from copy import copy
from tests.common.test_vector import TestDimension
from tests.common.impala_test_suite import ImpalaTestSuite, ALL_NODES_ONLY
# We use very small scan ranges to exercise corner cases in the HDFS scanner more
# thoroughly. In particular, it will exercise:
# 1. scan range with no tuple
# 2. tuple that span across multiple scan ranges
MAX_SCAN_RANGE_LENGTHS = [1, 2, 5]
class TestScanRangeLengths(ImpalaTestSuite):
@classmethod
def get_workload(cls):
return 'functional-query'
@classmethod
def add_test_dimensions(cls):
super(TestScanRangeLengths, cls).add_test_dimensions()
cls.TestMatrix.add_dimension(
TestDimension('max_scan_range_length', *MAX_SCAN_RANGE_LENGTHS))
def test_scan_ranges(self, vector):
if vector.get_value('table_format').file_format != 'text':
pytest.xfail(reason='IMP-636')
elif vector.get_value('table_format').compression_codec != 'none':
pytest.xfail(reason='IMPALA-122')
vector.get_value('exec_option')['max_scan_range_length'] =\
vector.get_value('max_scan_range_length')
self.run_test_case('QueryTest/hdfs-tiny-scan', vector)
| import pytest
from copy import copy
from tests.common.test_vector import TestDimension
from tests.common.impala_test_suite import ImpalaTestSuite, ALL_NODES_ONLY
# We use very small scan ranges to exercise corner cases in the HDFS scanner more
# thoroughly. In particular, it will exercise:
# 1. scan range with no tuple
# 2. tuple that span across multiple scan ranges
MAX_SCAN_RANGE_LENGTHS = [1, 2, 5]
class TestScanRangeLengths(ImpalaTestSuite):
@classmethod
def get_workload(cls):
return 'functional-query'
@classmethod
def add_test_dimensions(cls):
super(TestScanRangeLengths, cls).add_test_dimensions()
cls.TestMatrix.add_dimension(
TestDimension('max_scan_range_length', *MAX_SCAN_RANGE_LENGTHS))
def test_scan_ranges(self, vector):
if vector.get_value('table_format').file_format != 'text':
pytest.xfail(reason='IMP-636')
vector.get_value('exec_option')['max_scan_range_length'] =\
vector.get_value('max_scan_range_length')
self.run_test_case('QueryTest/hdfs-tiny-scan', vector)
| Fix IMPALA-122: Lzo scanner with small scan ranges. | Fix IMPALA-122: Lzo scanner with small scan ranges.
Change-Id: I5226fd1a1aa368f5b291b78ad371363057ef574e
Reviewed-on: http://gerrit.ent.cloudera.com:8080/140
Reviewed-by: Skye Wanderman-Milne <6d4b168ab637b0a20cc9dbf96abb2537f372f946@cloudera.com>
Reviewed-by: Nong Li <99a5e5f8f5911755b88e0b536d46aafa102bed41@cloudera.com>
Tested-by: Nong Li <99a5e5f8f5911755b88e0b536d46aafa102bed41@cloudera.com>
| Python | apache-2.0 | michaelhkw/incubator-impala,cloudera/Impala,michaelhkw/incubator-impala,michaelhkw/incubator-impala,michaelhkw/incubator-impala,cloudera/Impala,cloudera/Impala,cloudera/Impala,michaelhkw/incubator-impala,michaelhkw/incubator-impala,cloudera/Impala,cloudera/Impala,michaelhkw/incubator-impala,cloudera/Impala | import pytest
from copy import copy
from tests.common.test_vector import TestDimension
from tests.common.impala_test_suite import ImpalaTestSuite, ALL_NODES_ONLY
# We use very small scan ranges to exercise corner cases in the HDFS scanner more
# thoroughly. In particular, it will exercise:
# 1. scan range with no tuple
# 2. tuple that span across multiple scan ranges
MAX_SCAN_RANGE_LENGTHS = [1, 2, 5]
class TestScanRangeLengths(ImpalaTestSuite):
@classmethod
def get_workload(cls):
return 'functional-query'
@classmethod
def add_test_dimensions(cls):
super(TestScanRangeLengths, cls).add_test_dimensions()
cls.TestMatrix.add_dimension(
TestDimension('max_scan_range_length', *MAX_SCAN_RANGE_LENGTHS))
def test_scan_ranges(self, vector):
if vector.get_value('table_format').file_format != 'text':
pytest.xfail(reason='IMP-636')
- elif vector.get_value('table_format').compression_codec != 'none':
- pytest.xfail(reason='IMPALA-122')
vector.get_value('exec_option')['max_scan_range_length'] =\
vector.get_value('max_scan_range_length')
self.run_test_case('QueryTest/hdfs-tiny-scan', vector)
| Fix IMPALA-122: Lzo scanner with small scan ranges. | ## Code Before:
import pytest
from copy import copy
from tests.common.test_vector import TestDimension
from tests.common.impala_test_suite import ImpalaTestSuite, ALL_NODES_ONLY
# We use very small scan ranges to exercise corner cases in the HDFS scanner more
# thoroughly. In particular, it will exercise:
# 1. scan range with no tuple
# 2. tuple that span across multiple scan ranges
MAX_SCAN_RANGE_LENGTHS = [1, 2, 5]
class TestScanRangeLengths(ImpalaTestSuite):
@classmethod
def get_workload(cls):
return 'functional-query'
@classmethod
def add_test_dimensions(cls):
super(TestScanRangeLengths, cls).add_test_dimensions()
cls.TestMatrix.add_dimension(
TestDimension('max_scan_range_length', *MAX_SCAN_RANGE_LENGTHS))
def test_scan_ranges(self, vector):
if vector.get_value('table_format').file_format != 'text':
pytest.xfail(reason='IMP-636')
elif vector.get_value('table_format').compression_codec != 'none':
pytest.xfail(reason='IMPALA-122')
vector.get_value('exec_option')['max_scan_range_length'] =\
vector.get_value('max_scan_range_length')
self.run_test_case('QueryTest/hdfs-tiny-scan', vector)
## Instruction:
Fix IMPALA-122: Lzo scanner with small scan ranges.
## Code After:
import pytest
from copy import copy
from tests.common.test_vector import TestDimension
from tests.common.impala_test_suite import ImpalaTestSuite, ALL_NODES_ONLY
# We use very small scan ranges to exercise corner cases in the HDFS scanner more
# thoroughly. In particular, it will exercise:
# 1. scan range with no tuple
# 2. tuple that span across multiple scan ranges
MAX_SCAN_RANGE_LENGTHS = [1, 2, 5]
class TestScanRangeLengths(ImpalaTestSuite):
@classmethod
def get_workload(cls):
return 'functional-query'
@classmethod
def add_test_dimensions(cls):
super(TestScanRangeLengths, cls).add_test_dimensions()
cls.TestMatrix.add_dimension(
TestDimension('max_scan_range_length', *MAX_SCAN_RANGE_LENGTHS))
def test_scan_ranges(self, vector):
if vector.get_value('table_format').file_format != 'text':
pytest.xfail(reason='IMP-636')
vector.get_value('exec_option')['max_scan_range_length'] =\
vector.get_value('max_scan_range_length')
self.run_test_case('QueryTest/hdfs-tiny-scan', vector)
|
d1e56cfcd11bcd509d8fa3954c00e06a84bddd87 | synapse/storage/engines/__init__.py | synapse/storage/engines/__init__.py |
from ._base import IncorrectDatabaseSetup
from .postgres import PostgresEngine
from .sqlite3 import Sqlite3Engine
import importlib
import platform
SUPPORTED_MODULE = {
"sqlite3": Sqlite3Engine,
"psycopg2": PostgresEngine,
}
def create_engine(database_config):
name = database_config["name"]
engine_class = SUPPORTED_MODULE.get(name, None)
if engine_class:
needs_pypy_hack = (name == "psycopg2" and
platform.python_implementation() == "PyPy")
if needs_pypy_hack:
module = importlib.import_module("psycopg2cffi")
else:
module = importlib.import_module(name)
return engine_class(module, database_config)
raise RuntimeError(
"Unsupported database engine '%s'" % (name,)
)
__all__ = ["create_engine", "IncorrectDatabaseSetup"]
|
from ._base import IncorrectDatabaseSetup
from .postgres import PostgresEngine
from .sqlite3 import Sqlite3Engine
import importlib
import platform
SUPPORTED_MODULE = {
"sqlite3": Sqlite3Engine,
"psycopg2": PostgresEngine,
}
def create_engine(database_config):
name = database_config["name"]
engine_class = SUPPORTED_MODULE.get(name, None)
if engine_class:
# pypy requires psycopg2cffi rather than psycopg2
if (name == "psycopg2" and
platform.python_implementation() == "PyPy"):
name = "psycopg2cffi"
module = importlib.import_module(name)
return engine_class(module, database_config)
raise RuntimeError(
"Unsupported database engine '%s'" % (name,)
)
__all__ = ["create_engine", "IncorrectDatabaseSetup"]
| Fix pep8 error on psycopg2cffi hack | Fix pep8 error on psycopg2cffi hack | Python | apache-2.0 | matrix-org/synapse,matrix-org/synapse,matrix-org/synapse,matrix-org/synapse,matrix-org/synapse,matrix-org/synapse |
from ._base import IncorrectDatabaseSetup
from .postgres import PostgresEngine
from .sqlite3 import Sqlite3Engine
import importlib
import platform
SUPPORTED_MODULE = {
"sqlite3": Sqlite3Engine,
"psycopg2": PostgresEngine,
}
def create_engine(database_config):
name = database_config["name"]
engine_class = SUPPORTED_MODULE.get(name, None)
if engine_class:
+ # pypy requires psycopg2cffi rather than psycopg2
- needs_pypy_hack = (name == "psycopg2" and
+ if (name == "psycopg2" and
- platform.python_implementation() == "PyPy")
+ platform.python_implementation() == "PyPy"):
+ name = "psycopg2cffi"
- if needs_pypy_hack:
- module = importlib.import_module("psycopg2cffi")
- else:
- module = importlib.import_module(name)
+ module = importlib.import_module(name)
return engine_class(module, database_config)
raise RuntimeError(
"Unsupported database engine '%s'" % (name,)
)
__all__ = ["create_engine", "IncorrectDatabaseSetup"]
| Fix pep8 error on psycopg2cffi hack | ## Code Before:
from ._base import IncorrectDatabaseSetup
from .postgres import PostgresEngine
from .sqlite3 import Sqlite3Engine
import importlib
import platform
SUPPORTED_MODULE = {
"sqlite3": Sqlite3Engine,
"psycopg2": PostgresEngine,
}
def create_engine(database_config):
name = database_config["name"]
engine_class = SUPPORTED_MODULE.get(name, None)
if engine_class:
needs_pypy_hack = (name == "psycopg2" and
platform.python_implementation() == "PyPy")
if needs_pypy_hack:
module = importlib.import_module("psycopg2cffi")
else:
module = importlib.import_module(name)
return engine_class(module, database_config)
raise RuntimeError(
"Unsupported database engine '%s'" % (name,)
)
__all__ = ["create_engine", "IncorrectDatabaseSetup"]
## Instruction:
Fix pep8 error on psycopg2cffi hack
## Code After:
from ._base import IncorrectDatabaseSetup
from .postgres import PostgresEngine
from .sqlite3 import Sqlite3Engine
import importlib
import platform
SUPPORTED_MODULE = {
"sqlite3": Sqlite3Engine,
"psycopg2": PostgresEngine,
}
def create_engine(database_config):
name = database_config["name"]
engine_class = SUPPORTED_MODULE.get(name, None)
if engine_class:
# pypy requires psycopg2cffi rather than psycopg2
if (name == "psycopg2" and
platform.python_implementation() == "PyPy"):
name = "psycopg2cffi"
module = importlib.import_module(name)
return engine_class(module, database_config)
raise RuntimeError(
"Unsupported database engine '%s'" % (name,)
)
__all__ = ["create_engine", "IncorrectDatabaseSetup"]
|
d8cc0fdaea848ed5d626ba6ba4292fd3cb906da3 | project7/TrackParser.py | project7/TrackParser.py | """ Created by Max 12/2/2017 """
import pprint
import numpy as np
class TrackParser:
@staticmethod
def parse_track(path_to_track_file: str) -> np.ndarray:
track = None
with open(path_to_track_file, 'r') as track_file:
lines = track_file.readlines()
dimensions_str = lines[0]
dims = dimensions_str.split(',')
track = np.zeros((int(dims[0]), int(dims[1])))
for line_index in range(1, len(lines)):
line = lines[line_index]
for char_index in range(len(line) - 1):
track_value = TrackParser.get_char_value(line[char_index])
track[line_index-1][char_index] = track_value
return track
@staticmethod
def get_char_value(char: str):
if char == '#':
return -1
elif char == '.':
return 0
elif char == 'S':
return 1
elif char == 'F':
return 2
else:
return -1
np.set_printoptions(linewidth=500)
pprint.pprint(TrackParser.parse_track("tracks/L-track.txt"), width=500)
| """ Created by Max 12/2/2017 """
import pprint
import numpy as np
class TrackParser:
@staticmethod
def parse_track(path_to_track_file: str) -> np.ndarray:
track = None
with open(path_to_track_file, 'r') as track_file:
lines = track_file.readlines()
dimensions_str = lines[0]
dims = dimensions_str.split(',')
# (Y,X) coords.
track = np.zeros((int(dims[0]), int(dims[1])))
for line_index in range(1, len(lines)):
line = lines[line_index]
for char_index in range(len(line) - 1):
track_value = TrackParser.get_char_value(line[char_index])
track[line_index-1][char_index] = track_value
return track
@staticmethod
def get_char_value(char: str):
if char == '#':
return -1
elif char == '.':
return 0
elif char == 'S':
return 1
elif char == 'F':
return 2
else:
return -1
# np.set_printoptions(linewidth=500)
# pprint.pprint(TrackParser.parse_track("tracks/L-track.txt"), width=500)
| Add comment to clarify coordinate order | Add comment to clarify coordinate order
coordinates are (y,x) in the track.
| Python | apache-2.0 | MaxRobinson/CS449,MaxRobinson/CS449,MaxRobinson/CS449 | """ Created by Max 12/2/2017 """
import pprint
import numpy as np
class TrackParser:
@staticmethod
def parse_track(path_to_track_file: str) -> np.ndarray:
track = None
with open(path_to_track_file, 'r') as track_file:
lines = track_file.readlines()
dimensions_str = lines[0]
dims = dimensions_str.split(',')
+ # (Y,X) coords.
track = np.zeros((int(dims[0]), int(dims[1])))
for line_index in range(1, len(lines)):
line = lines[line_index]
for char_index in range(len(line) - 1):
track_value = TrackParser.get_char_value(line[char_index])
track[line_index-1][char_index] = track_value
return track
@staticmethod
def get_char_value(char: str):
if char == '#':
return -1
elif char == '.':
return 0
elif char == 'S':
return 1
elif char == 'F':
return 2
else:
return -1
- np.set_printoptions(linewidth=500)
+ # np.set_printoptions(linewidth=500)
- pprint.pprint(TrackParser.parse_track("tracks/L-track.txt"), width=500)
+ # pprint.pprint(TrackParser.parse_track("tracks/L-track.txt"), width=500)
| Add comment to clarify coordinate order | ## Code Before:
""" Created by Max 12/2/2017 """
import pprint
import numpy as np
class TrackParser:
@staticmethod
def parse_track(path_to_track_file: str) -> np.ndarray:
track = None
with open(path_to_track_file, 'r') as track_file:
lines = track_file.readlines()
dimensions_str = lines[0]
dims = dimensions_str.split(',')
track = np.zeros((int(dims[0]), int(dims[1])))
for line_index in range(1, len(lines)):
line = lines[line_index]
for char_index in range(len(line) - 1):
track_value = TrackParser.get_char_value(line[char_index])
track[line_index-1][char_index] = track_value
return track
@staticmethod
def get_char_value(char: str):
if char == '#':
return -1
elif char == '.':
return 0
elif char == 'S':
return 1
elif char == 'F':
return 2
else:
return -1
np.set_printoptions(linewidth=500)
pprint.pprint(TrackParser.parse_track("tracks/L-track.txt"), width=500)
## Instruction:
Add comment to clarify coordinate order
## Code After:
""" Created by Max 12/2/2017 """
import pprint
import numpy as np
class TrackParser:
@staticmethod
def parse_track(path_to_track_file: str) -> np.ndarray:
track = None
with open(path_to_track_file, 'r') as track_file:
lines = track_file.readlines()
dimensions_str = lines[0]
dims = dimensions_str.split(',')
# (Y,X) coords.
track = np.zeros((int(dims[0]), int(dims[1])))
for line_index in range(1, len(lines)):
line = lines[line_index]
for char_index in range(len(line) - 1):
track_value = TrackParser.get_char_value(line[char_index])
track[line_index-1][char_index] = track_value
return track
@staticmethod
def get_char_value(char: str):
if char == '#':
return -1
elif char == '.':
return 0
elif char == 'S':
return 1
elif char == 'F':
return 2
else:
return -1
# np.set_printoptions(linewidth=500)
# pprint.pprint(TrackParser.parse_track("tracks/L-track.txt"), width=500)
|
2806254823ae46e4a8fd7204cda58be6eea18743 | tests/10_test_elbaas.py | tests/10_test_elbaas.py | import otc
class TestElbClient:
"""ELB client tests"""
def setUp(self):
"""Setup test cloud"""
self.cloud = otc.OtcCloud(cloud='test')
def tearDown(self):
pass
def test_elbclient_user_agent(self):
"""Check user agent"""
assert self.cloud.elbclient.client.USER_AGENT == 'python-otcclient'
def test_elbclient_elb(self):
"""List elbs"""
elbs = self.cloud.elbclient.elb.list()
assert len(elbs) >= 0
elbs = self.cloud.elbclient.elb.list(vpcid='foo')
assert len(elbs) >= 0
elbs = self.cloud.elbclient.elb.list('foo')
assert len(elbs) >= 0
def test_elbclient_listener(self):
"""List listeners"""
lstns = self.cloud.elbclient.listener.list()
assert len(lstns) >= 0
lstns = self.cloud.elbclient.listener.list('foo')
assert len(lstns) >= 0
lstns = self.cloud.elbclient.listener.list(elbid='foo')
assert len(lstns) >= 0
# vim: sts=4 sw=4 ts=4 et:
| import otc
class TestElbClient:
"""ELB client tests"""
def setUp(self):
"""Setup test cloud"""
self.cloud = otc.OtcCloud(cloud='test')
def tearDown(self):
pass
def test_elbclient_user_agent(self):
"""Check user agent"""
assert self.cloud.elbclient.client.USER_AGENT == 'python-otcclient'
def test_elbclient_service_url(self):
"""Check ELB service url"""
assert self.cloud.elbclient.service_url == "https://elb.eu-de.otc.t-systems.com"
def test_elbclient_elb(self):
"""List elbs"""
elbs = self.cloud.elbclient.elb.list()
assert len(elbs) >= 0
elbs = self.cloud.elbclient.elb.list(vpcid='foo')
assert len(elbs) >= 0
elbs = self.cloud.elbclient.elb.list('foo')
assert len(elbs) >= 0
def test_elbclient_listener(self):
"""List listeners"""
lstns = self.cloud.elbclient.listener.list()
assert len(lstns) >= 0
lstns = self.cloud.elbclient.listener.list('foo')
assert len(lstns) >= 0
lstns = self.cloud.elbclient.listener.list(elbid='foo')
assert len(lstns) >= 0
# vim: sts=4 sw=4 ts=4 et:
| Check the ELB service url | Check the ELB service url
| Python | apache-2.0 | zamiam69/otc | import otc
class TestElbClient:
"""ELB client tests"""
def setUp(self):
"""Setup test cloud"""
self.cloud = otc.OtcCloud(cloud='test')
def tearDown(self):
pass
def test_elbclient_user_agent(self):
"""Check user agent"""
assert self.cloud.elbclient.client.USER_AGENT == 'python-otcclient'
+
+ def test_elbclient_service_url(self):
+ """Check ELB service url"""
+ assert self.cloud.elbclient.service_url == "https://elb.eu-de.otc.t-systems.com"
def test_elbclient_elb(self):
"""List elbs"""
elbs = self.cloud.elbclient.elb.list()
assert len(elbs) >= 0
elbs = self.cloud.elbclient.elb.list(vpcid='foo')
assert len(elbs) >= 0
elbs = self.cloud.elbclient.elb.list('foo')
assert len(elbs) >= 0
def test_elbclient_listener(self):
"""List listeners"""
lstns = self.cloud.elbclient.listener.list()
assert len(lstns) >= 0
lstns = self.cloud.elbclient.listener.list('foo')
assert len(lstns) >= 0
lstns = self.cloud.elbclient.listener.list(elbid='foo')
assert len(lstns) >= 0
# vim: sts=4 sw=4 ts=4 et:
| Check the ELB service url | ## Code Before:
import otc
class TestElbClient:
"""ELB client tests"""
def setUp(self):
"""Setup test cloud"""
self.cloud = otc.OtcCloud(cloud='test')
def tearDown(self):
pass
def test_elbclient_user_agent(self):
"""Check user agent"""
assert self.cloud.elbclient.client.USER_AGENT == 'python-otcclient'
def test_elbclient_elb(self):
"""List elbs"""
elbs = self.cloud.elbclient.elb.list()
assert len(elbs) >= 0
elbs = self.cloud.elbclient.elb.list(vpcid='foo')
assert len(elbs) >= 0
elbs = self.cloud.elbclient.elb.list('foo')
assert len(elbs) >= 0
def test_elbclient_listener(self):
"""List listeners"""
lstns = self.cloud.elbclient.listener.list()
assert len(lstns) >= 0
lstns = self.cloud.elbclient.listener.list('foo')
assert len(lstns) >= 0
lstns = self.cloud.elbclient.listener.list(elbid='foo')
assert len(lstns) >= 0
# vim: sts=4 sw=4 ts=4 et:
## Instruction:
Check the ELB service url
## Code After:
import otc
class TestElbClient:
"""ELB client tests"""
def setUp(self):
"""Setup test cloud"""
self.cloud = otc.OtcCloud(cloud='test')
def tearDown(self):
pass
def test_elbclient_user_agent(self):
"""Check user agent"""
assert self.cloud.elbclient.client.USER_AGENT == 'python-otcclient'
def test_elbclient_service_url(self):
"""Check ELB service url"""
assert self.cloud.elbclient.service_url == "https://elb.eu-de.otc.t-systems.com"
def test_elbclient_elb(self):
"""List elbs"""
elbs = self.cloud.elbclient.elb.list()
assert len(elbs) >= 0
elbs = self.cloud.elbclient.elb.list(vpcid='foo')
assert len(elbs) >= 0
elbs = self.cloud.elbclient.elb.list('foo')
assert len(elbs) >= 0
def test_elbclient_listener(self):
"""List listeners"""
lstns = self.cloud.elbclient.listener.list()
assert len(lstns) >= 0
lstns = self.cloud.elbclient.listener.list('foo')
assert len(lstns) >= 0
lstns = self.cloud.elbclient.listener.list(elbid='foo')
assert len(lstns) >= 0
# vim: sts=4 sw=4 ts=4 et:
|
9bc9ec9468459ab49530e6463255cca38aba721c | findaconf/tests/test_site_routes.py | findaconf/tests/test_site_routes.py |
from unittest import TestCase
from findaconf import app, db
from findaconf.tests.config import set_app, unset_app
class TestSiteRoutes(TestCase):
def setUp(self):
self.app = set_app(app, db)
def tearDown(self):
unset_app(db)
# test routes from blueprint/site.py
def test_index(self):
resp = self.app.get('/')
assert resp.status_code == 200
assert resp.mimetype == 'text/html'
def test_find(self):
resp = self.app.get('/find', data={'query': 'sociology',
'month': 'February',
'year': 2015,
'region': 'Europe',
'location': 'University of Essex'})
assert resp.status_code == 200
assert resp.mimetype == 'text/html'
|
from findaconf import app, db
from findaconf.tests.config import set_app, unset_app
from unittest import TestCase
class TestSiteRoutes(TestCase):
def setUp(self):
self.app = set_app(app, db)
def tearDown(self):
unset_app(db)
# test routes from blueprint/site.py
def test_index(self):
resp = self.app.get('/')
assert resp.status_code == 200
assert resp.mimetype == 'text/html'
def test_find(self):
resp = self.app.get('/find', data={'query': 'sociology',
'month': 'February',
'year': 2015,
'region': 'Europe',
'location': 'University of Essex'})
assert resp.status_code == 200
assert resp.mimetype == 'text/html'
def test_login(self):
# test if login page exists
resp = self.app.get('/login')
assert resp.status_code == 200
assert resp.mimetype == 'text/html'
# test if is there a link to login in the home page
resp = self.app.get('/')
assert 'href="/login"' in resp.data | Create tests for login page | Create tests for login page
| Python | mit | cuducos/findaconf,cuducos/findaconf,koorukuroo/findaconf,cuducos/findaconf,koorukuroo/findaconf,koorukuroo/findaconf |
- from unittest import TestCase
from findaconf import app, db
from findaconf.tests.config import set_app, unset_app
+ from unittest import TestCase
class TestSiteRoutes(TestCase):
def setUp(self):
self.app = set_app(app, db)
def tearDown(self):
unset_app(db)
# test routes from blueprint/site.py
-
def test_index(self):
resp = self.app.get('/')
assert resp.status_code == 200
assert resp.mimetype == 'text/html'
def test_find(self):
resp = self.app.get('/find', data={'query': 'sociology',
'month': 'February',
'year': 2015,
'region': 'Europe',
'location': 'University of Essex'})
assert resp.status_code == 200
assert resp.mimetype == 'text/html'
-
+
+ def test_login(self):
+
+ # test if login page exists
+ resp = self.app.get('/login')
+ assert resp.status_code == 200
+ assert resp.mimetype == 'text/html'
+
+ # test if is there a link to login in the home page
+ resp = self.app.get('/')
+ assert 'href="/login"' in resp.data | Create tests for login page | ## Code Before:
from unittest import TestCase
from findaconf import app, db
from findaconf.tests.config import set_app, unset_app
class TestSiteRoutes(TestCase):
def setUp(self):
self.app = set_app(app, db)
def tearDown(self):
unset_app(db)
# test routes from blueprint/site.py
def test_index(self):
resp = self.app.get('/')
assert resp.status_code == 200
assert resp.mimetype == 'text/html'
def test_find(self):
resp = self.app.get('/find', data={'query': 'sociology',
'month': 'February',
'year': 2015,
'region': 'Europe',
'location': 'University of Essex'})
assert resp.status_code == 200
assert resp.mimetype == 'text/html'
## Instruction:
Create tests for login page
## Code After:
from findaconf import app, db
from findaconf.tests.config import set_app, unset_app
from unittest import TestCase
class TestSiteRoutes(TestCase):
def setUp(self):
self.app = set_app(app, db)
def tearDown(self):
unset_app(db)
# test routes from blueprint/site.py
def test_index(self):
resp = self.app.get('/')
assert resp.status_code == 200
assert resp.mimetype == 'text/html'
def test_find(self):
resp = self.app.get('/find', data={'query': 'sociology',
'month': 'February',
'year': 2015,
'region': 'Europe',
'location': 'University of Essex'})
assert resp.status_code == 200
assert resp.mimetype == 'text/html'
def test_login(self):
# test if login page exists
resp = self.app.get('/login')
assert resp.status_code == 200
assert resp.mimetype == 'text/html'
# test if is there a link to login in the home page
resp = self.app.get('/')
assert 'href="/login"' in resp.data |
d8d6054a64c07952ff0a60ef5d86d7a5b572d1b4 | fireplace/cards/brawl/blingbrawl.py | fireplace/cards/brawl/blingbrawl.py | from ..utils import *
# Cash In
class TP_Bling_HP2:
activate = Destroy(FRIENDLY_WEAPON)
# Blingtron's Blade
class TB_BlingBrawl_Blade1e:
events = Death(OWNER).on(Summon(CONTROLLER, RandomWeapon()))
# Blingtron's Blade HERO
class TB_BlingBrawl_Blade2:
events = Summon(CONTROLLER, WEAPON).on(
Buff(Summon.CARD, "TB_BlingBrawl_Blade1e")
)
| from ..utils import *
# Cash In
class TP_Bling_HP2:
activate = Destroy(FRIENDLY_WEAPON)
# Blingtron's Blade
class TB_BlingBrawl_Blade1e:
events = Death(OWNER).on(Summon(CONTROLLER, RandomWeapon()))
# Blingtron's Blade HERO
class TB_BlingBrawl_Blade2:
events = Summon(CONTROLLER, WEAPON).on(
Buff(Summon.CARD, "TB_BlingBrawl_Blade1e")
)
# Sharpen (Unused)
class TB_BlingBrawl_Hero1p:
activate = Buff(FRIENDLY_WEAPON, "TB_BlingBrawl_Hero1e")
TB_BlingBrawl_Hero1e = buff(atk=1)
| Implement Sharpen (unused Blingtron Brawl Hero Power) | Implement Sharpen (unused Blingtron Brawl Hero Power)
| Python | agpl-3.0 | Ragowit/fireplace,Ragowit/fireplace,smallnamespace/fireplace,NightKev/fireplace,smallnamespace/fireplace,beheh/fireplace,jleclanche/fireplace | from ..utils import *
# Cash In
class TP_Bling_HP2:
activate = Destroy(FRIENDLY_WEAPON)
# Blingtron's Blade
class TB_BlingBrawl_Blade1e:
events = Death(OWNER).on(Summon(CONTROLLER, RandomWeapon()))
# Blingtron's Blade HERO
class TB_BlingBrawl_Blade2:
events = Summon(CONTROLLER, WEAPON).on(
Buff(Summon.CARD, "TB_BlingBrawl_Blade1e")
)
+
+ # Sharpen (Unused)
+ class TB_BlingBrawl_Hero1p:
+ activate = Buff(FRIENDLY_WEAPON, "TB_BlingBrawl_Hero1e")
+
+ TB_BlingBrawl_Hero1e = buff(atk=1)
+ | Implement Sharpen (unused Blingtron Brawl Hero Power) | ## Code Before:
from ..utils import *
# Cash In
class TP_Bling_HP2:
activate = Destroy(FRIENDLY_WEAPON)
# Blingtron's Blade
class TB_BlingBrawl_Blade1e:
events = Death(OWNER).on(Summon(CONTROLLER, RandomWeapon()))
# Blingtron's Blade HERO
class TB_BlingBrawl_Blade2:
events = Summon(CONTROLLER, WEAPON).on(
Buff(Summon.CARD, "TB_BlingBrawl_Blade1e")
)
## Instruction:
Implement Sharpen (unused Blingtron Brawl Hero Power)
## Code After:
from ..utils import *
# Cash In
class TP_Bling_HP2:
activate = Destroy(FRIENDLY_WEAPON)
# Blingtron's Blade
class TB_BlingBrawl_Blade1e:
events = Death(OWNER).on(Summon(CONTROLLER, RandomWeapon()))
# Blingtron's Blade HERO
class TB_BlingBrawl_Blade2:
events = Summon(CONTROLLER, WEAPON).on(
Buff(Summon.CARD, "TB_BlingBrawl_Blade1e")
)
# Sharpen (Unused)
class TB_BlingBrawl_Hero1p:
activate = Buff(FRIENDLY_WEAPON, "TB_BlingBrawl_Hero1e")
TB_BlingBrawl_Hero1e = buff(atk=1)
|
86273d96e33e3bd686904377ba2b53fbbbcbc38b | tests/test_crossword.py | tests/test_crossword.py | import unittest
from crossword import Crossword
class CrosswordTestCase(unittest.TestCase):
def test_crossword_set_and_get_element(self):
c = Crossword(10, 10)
c[3, 3] = 'A'
self.assertEqual(c[3, 3], 'A')
| import unittest
from crossword import Crossword
class CrosswordTestCase(unittest.TestCase):
def test_crossword_set_and_get_element(self):
crossword = Crossword(10, 10)
crossword[3, 3] = 'A'
self.assertEqual(crossword[3, 3], 'A')
| Use a better variable name instead of one character | Use a better variable name instead of one character
| Python | mit | svisser/crossword | import unittest
from crossword import Crossword
class CrosswordTestCase(unittest.TestCase):
def test_crossword_set_and_get_element(self):
- c = Crossword(10, 10)
+ crossword = Crossword(10, 10)
- c[3, 3] = 'A'
+ crossword[3, 3] = 'A'
- self.assertEqual(c[3, 3], 'A')
+ self.assertEqual(crossword[3, 3], 'A')
| Use a better variable name instead of one character | ## Code Before:
import unittest
from crossword import Crossword
class CrosswordTestCase(unittest.TestCase):
def test_crossword_set_and_get_element(self):
c = Crossword(10, 10)
c[3, 3] = 'A'
self.assertEqual(c[3, 3], 'A')
## Instruction:
Use a better variable name instead of one character
## Code After:
import unittest
from crossword import Crossword
class CrosswordTestCase(unittest.TestCase):
def test_crossword_set_and_get_element(self):
crossword = Crossword(10, 10)
crossword[3, 3] = 'A'
self.assertEqual(crossword[3, 3], 'A')
|
ab500891a44e7034e02889acc5f8ac1d44cb9aad | tests/test_error.py | tests/test_error.py | from __future__ import unicode_literals
import unittest
import six
import spotify
class ErrorTest(unittest.TestCase):
def test_error_has_error_code(self):
error = spotify.Error(0)
self.assertEqual(error.error_code, 0)
error = spotify.Error(1)
self.assertEqual(error.error_code, 1)
def test_error_has_error_message(self):
error = spotify.Error(0)
self.assertEqual(error.message, 'No error')
self.assertIsInstance(error.message, six.text_type)
error = spotify.Error(1)
self.assertEqual(error.message, 'Invalid library version')
def test_error_has_useful_repr(self):
error = spotify.Error(0)
self.assertEqual(repr(error), b"Error(u'No error',)")
def test_error_has_useful_str(self):
error = spotify.Error(0)
self.assertEqual(str(error), 'No error')
def test_error_has_error_constants(self):
self.assertEqual(spotify.Error.OK, 0)
self.assertEqual(spotify.Error.BAD_API_VERSION, 1)
| from __future__ import unicode_literals
import unittest
import six
import spotify
class ErrorTest(unittest.TestCase):
def test_error_has_error_code(self):
error = spotify.Error(0)
self.assertEqual(error.error_code, 0)
error = spotify.Error(1)
self.assertEqual(error.error_code, 1)
def test_error_has_useful_repr(self):
error = spotify.Error(0)
self.assertIn('No error', repr(error))
def test_error_has_useful_string_representation(self):
error = spotify.Error(0)
self.assertEqual('%s' % error, 'No error')
self.assertIsInstance('%s' % error, six.text_type)
error = spotify.Error(1)
self.assertEqual('%s' % error, 'Invalid library version')
def test_error_has_error_constants(self):
self.assertEqual(spotify.Error.OK, 0)
self.assertEqual(spotify.Error.BAD_API_VERSION, 1)
| Make Error behavior consistent across Pythons | Make Error behavior consistent across Pythons
| Python | apache-2.0 | felix1m/pyspotify,jodal/pyspotify,jodal/pyspotify,felix1m/pyspotify,kotamat/pyspotify,jodal/pyspotify,kotamat/pyspotify,mopidy/pyspotify,mopidy/pyspotify,kotamat/pyspotify,felix1m/pyspotify | from __future__ import unicode_literals
import unittest
import six
import spotify
class ErrorTest(unittest.TestCase):
def test_error_has_error_code(self):
error = spotify.Error(0)
self.assertEqual(error.error_code, 0)
error = spotify.Error(1)
self.assertEqual(error.error_code, 1)
- def test_error_has_error_message(self):
+ def test_error_has_useful_repr(self):
error = spotify.Error(0)
+ self.assertIn('No error', repr(error))
+
+ def test_error_has_useful_string_representation(self):
+ error = spotify.Error(0)
- self.assertEqual(error.message, 'No error')
+ self.assertEqual('%s' % error, 'No error')
- self.assertIsInstance(error.message, six.text_type)
+ self.assertIsInstance('%s' % error, six.text_type)
error = spotify.Error(1)
- self.assertEqual(error.message, 'Invalid library version')
+ self.assertEqual('%s' % error, 'Invalid library version')
-
- def test_error_has_useful_repr(self):
- error = spotify.Error(0)
- self.assertEqual(repr(error), b"Error(u'No error',)")
-
- def test_error_has_useful_str(self):
- error = spotify.Error(0)
- self.assertEqual(str(error), 'No error')
def test_error_has_error_constants(self):
self.assertEqual(spotify.Error.OK, 0)
self.assertEqual(spotify.Error.BAD_API_VERSION, 1)
| Make Error behavior consistent across Pythons | ## Code Before:
from __future__ import unicode_literals
import unittest
import six
import spotify
class ErrorTest(unittest.TestCase):
def test_error_has_error_code(self):
error = spotify.Error(0)
self.assertEqual(error.error_code, 0)
error = spotify.Error(1)
self.assertEqual(error.error_code, 1)
def test_error_has_error_message(self):
error = spotify.Error(0)
self.assertEqual(error.message, 'No error')
self.assertIsInstance(error.message, six.text_type)
error = spotify.Error(1)
self.assertEqual(error.message, 'Invalid library version')
def test_error_has_useful_repr(self):
error = spotify.Error(0)
self.assertEqual(repr(error), b"Error(u'No error',)")
def test_error_has_useful_str(self):
error = spotify.Error(0)
self.assertEqual(str(error), 'No error')
def test_error_has_error_constants(self):
self.assertEqual(spotify.Error.OK, 0)
self.assertEqual(spotify.Error.BAD_API_VERSION, 1)
## Instruction:
Make Error behavior consistent across Pythons
## Code After:
from __future__ import unicode_literals
import unittest
import six
import spotify
class ErrorTest(unittest.TestCase):
def test_error_has_error_code(self):
error = spotify.Error(0)
self.assertEqual(error.error_code, 0)
error = spotify.Error(1)
self.assertEqual(error.error_code, 1)
def test_error_has_useful_repr(self):
error = spotify.Error(0)
self.assertIn('No error', repr(error))
def test_error_has_useful_string_representation(self):
error = spotify.Error(0)
self.assertEqual('%s' % error, 'No error')
self.assertIsInstance('%s' % error, six.text_type)
error = spotify.Error(1)
self.assertEqual('%s' % error, 'Invalid library version')
def test_error_has_error_constants(self):
self.assertEqual(spotify.Error.OK, 0)
self.assertEqual(spotify.Error.BAD_API_VERSION, 1)
|
8ee35fe46e978fcb17e99b50f045009ea8235067 | tools/pdtools/pdtools/devices/camera.py | tools/pdtools/pdtools/devices/camera.py | import base64
import requests
import six
class Camera(object):
def __init__(self, host):
self.host = host
def get_image(self):
"""
Get an image from the camera.
Returns image data as a BytesIO/StringIO object.
"""
url = "http://{}/image.jpg".format(self.host)
encoded = base64.b64encode('admin:'.encode('utf-8')).decode('ascii')
headers = {
'Authorization': 'Basic ' + encoded
}
result = requests.get(url, headers=headers)
if result.ok:
return six.BytesIO(result.content)
else:
return None
| import base64
import requests
import six
class Camera(object):
def __init__(self, host):
self.host = host
def __repr__(self):
return "Camera({})".format(self.host)
def get_image(self):
"""
Get an image from the camera.
Returns image data as a BytesIO/StringIO object.
"""
url = "http://{}/image.jpg".format(self.host)
encoded = base64.b64encode('admin:'.encode('utf-8')).decode('ascii')
headers = {
'Authorization': 'Basic ' + encoded
}
result = requests.get(url, headers=headers)
if result.ok:
return six.BytesIO(result.content)
else:
return None
| Define __repr__ for pdtools Camera class. | Define __repr__ for pdtools Camera class.
| Python | apache-2.0 | ParadropLabs/Paradrop,ParadropLabs/Paradrop,ParadropLabs/Paradrop | import base64
import requests
import six
class Camera(object):
def __init__(self, host):
self.host = host
+
+ def __repr__(self):
+ return "Camera({})".format(self.host)
def get_image(self):
"""
Get an image from the camera.
Returns image data as a BytesIO/StringIO object.
"""
url = "http://{}/image.jpg".format(self.host)
encoded = base64.b64encode('admin:'.encode('utf-8')).decode('ascii')
headers = {
'Authorization': 'Basic ' + encoded
}
result = requests.get(url, headers=headers)
if result.ok:
return six.BytesIO(result.content)
else:
return None
| Define __repr__ for pdtools Camera class. | ## Code Before:
import base64
import requests
import six
class Camera(object):
def __init__(self, host):
self.host = host
def get_image(self):
"""
Get an image from the camera.
Returns image data as a BytesIO/StringIO object.
"""
url = "http://{}/image.jpg".format(self.host)
encoded = base64.b64encode('admin:'.encode('utf-8')).decode('ascii')
headers = {
'Authorization': 'Basic ' + encoded
}
result = requests.get(url, headers=headers)
if result.ok:
return six.BytesIO(result.content)
else:
return None
## Instruction:
Define __repr__ for pdtools Camera class.
## Code After:
import base64
import requests
import six
class Camera(object):
def __init__(self, host):
self.host = host
def __repr__(self):
return "Camera({})".format(self.host)
def get_image(self):
"""
Get an image from the camera.
Returns image data as a BytesIO/StringIO object.
"""
url = "http://{}/image.jpg".format(self.host)
encoded = base64.b64encode('admin:'.encode('utf-8')).decode('ascii')
headers = {
'Authorization': 'Basic ' + encoded
}
result = requests.get(url, headers=headers)
if result.ok:
return six.BytesIO(result.content)
else:
return None
|
8e5c55a4710352d5f3b211c9df7d11c3cf9ef104 | us_ignite/dummy/text.py | us_ignite/dummy/text.py | from random import choice
from django.conf import settings
words = open(settings.WORDS_PATH, "r").readlines()
def random_words(total):
return " ".join([choice(words).lower().rstrip() for i in range(total)])
def random_paragraphs(total, word_no=30):
return ".\n\n".join([random_words(word_no) for i in range(total)])
| from random import choice
from django.conf import settings
from django.utils.encoding import smart_text
words = open(settings.WORDS_PATH, "r").readlines()
def random_words(total):
return u" ".join([smart_text(choice(words).lower().rstrip()) for i in range(total)])
def random_paragraphs(total, word_no=30):
return u".\n\n".join([random_words(word_no) for i in range(total)])
| Handle encoding of the random words. | Handle encoding of the random words.
| Python | bsd-3-clause | us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite | from random import choice
from django.conf import settings
+ from django.utils.encoding import smart_text
words = open(settings.WORDS_PATH, "r").readlines()
def random_words(total):
- return " ".join([choice(words).lower().rstrip() for i in range(total)])
+ return u" ".join([smart_text(choice(words).lower().rstrip()) for i in range(total)])
def random_paragraphs(total, word_no=30):
- return ".\n\n".join([random_words(word_no) for i in range(total)])
+ return u".\n\n".join([random_words(word_no) for i in range(total)])
| Handle encoding of the random words. | ## Code Before:
from random import choice
from django.conf import settings
words = open(settings.WORDS_PATH, "r").readlines()
def random_words(total):
return " ".join([choice(words).lower().rstrip() for i in range(total)])
def random_paragraphs(total, word_no=30):
return ".\n\n".join([random_words(word_no) for i in range(total)])
## Instruction:
Handle encoding of the random words.
## Code After:
from random import choice
from django.conf import settings
from django.utils.encoding import smart_text
words = open(settings.WORDS_PATH, "r").readlines()
def random_words(total):
return u" ".join([smart_text(choice(words).lower().rstrip()) for i in range(total)])
def random_paragraphs(total, word_no=30):
return u".\n\n".join([random_words(word_no) for i in range(total)])
|
7d94abed2316c5ee6679f33d43c122b9bfcedab7 | extra_countries/migrations/0001_initial.py | extra_countries/migrations/0001_initial.py | from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('continents', '0001_initial'),
('currencies', '0001_initial'),
('cities', '0002_auto_20151112_1857'),
]
operations = [
migrations.CreateModel(
name='ExtraCountry',
fields=[
('code', models.CharField(serialize=False, primary_key=True, max_length=3)),
('country', models.OneToOneField(to='cities.Country')),
('extra_continent', models.ForeignKey(to='continents.Continent', null=True)),
('extra_currency', models.ForeignKey(to='currencies.Currency', null=True)),
],
),
]
| from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('continents', '0001_initial'),
('currencies', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='ExtraCountry',
fields=[
('code', models.CharField(serialize=False, primary_key=True, max_length=3)),
('country', models.OneToOneField(to='cities.Country')),
('extra_continent', models.ForeignKey(to='continents.Continent', null=True)),
('extra_currency', models.ForeignKey(to='currencies.Currency', null=True)),
],
),
]
| Remove reference to nonexistent migration to fix tests | Remove reference to nonexistent migration to fix tests
| Python | mit | openspending/cosmopolitan,kiote/cosmopolitan | from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('continents', '0001_initial'),
('currencies', '0001_initial'),
- ('cities', '0002_auto_20151112_1857'),
]
operations = [
migrations.CreateModel(
name='ExtraCountry',
fields=[
('code', models.CharField(serialize=False, primary_key=True, max_length=3)),
('country', models.OneToOneField(to='cities.Country')),
('extra_continent', models.ForeignKey(to='continents.Continent', null=True)),
('extra_currency', models.ForeignKey(to='currencies.Currency', null=True)),
],
),
]
| Remove reference to nonexistent migration to fix tests | ## Code Before:
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('continents', '0001_initial'),
('currencies', '0001_initial'),
('cities', '0002_auto_20151112_1857'),
]
operations = [
migrations.CreateModel(
name='ExtraCountry',
fields=[
('code', models.CharField(serialize=False, primary_key=True, max_length=3)),
('country', models.OneToOneField(to='cities.Country')),
('extra_continent', models.ForeignKey(to='continents.Continent', null=True)),
('extra_currency', models.ForeignKey(to='currencies.Currency', null=True)),
],
),
]
## Instruction:
Remove reference to nonexistent migration to fix tests
## Code After:
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('continents', '0001_initial'),
('currencies', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='ExtraCountry',
fields=[
('code', models.CharField(serialize=False, primary_key=True, max_length=3)),
('country', models.OneToOneField(to='cities.Country')),
('extra_continent', models.ForeignKey(to='continents.Continent', null=True)),
('extra_currency', models.ForeignKey(to='currencies.Currency', null=True)),
],
),
]
|
8a71fe98d50f7603742c60273502fb840e967c97 | scalpel/event.py | scalpel/event.py |
from weakref import WeakValueDictionary
class Signal(object):
def __init__(self):
self.__slots = WeakValueDictionary()
def __call__(self, *args, **kargs):
for key in self.__slots:
func, _ = key
func(self.__slots[key], *args, **kargs)
def connect(self, slot):
key = (slot.im_func, id(slot.im_self))
self.__slots[key] = slot.im_self
def disconnect(self, slot):
key = (slot.im_func, id(slot.im_self))
if key in self.__slots:
self.__slots.pop(key)
def clear(self):
self.__slots.clear()
|
from weakref import WeakValueDictionary
import inspect
class Signal(object):
def __init__(self):
self.__slots = WeakValueDictionary()
# For keeping references to _FuncHost objects.
self.__funchosts = {}
def __call__(self, *args, **kargs):
for key in self.__slots:
func, _ = key
func(self.__slots[key], *args, **kargs)
def connect(self, slot):
if inspect.ismethod(slot):
key = (slot.im_func, id(slot.im_self))
self.__slots[key] = slot.im_self
else:
host = _FuncHost(slot)
self.connect(host.meth)
# We stick a copy in here just to keep the instance alive.
self.__funchosts[slot] = host
def disconnect(self, slot):
if inspect.ismethod(slot):
key = (slot.im_func, id(slot.im_self))
if key in self.__slots:
self.__slots.pop(key)
else:
if slot in self.__funchosts:
self.disconnect(self.__funchosts[slot].meth)
self.__funchosts.pop(slot)
def clear(self):
self.__slots.clear()
class _FuncHost(object):
"""Turn a function into a method."""
def __init__(self, func):
self.func = func
def meth(self, *args, **kwargs):
self.func(*args, **kwargs)
if __name__ == '__main__':
a = 0
def test_func():
def foo():
global a
a = a + 1
s = Signal()
s()
s.connect(foo)
s()
s.disconnect(foo)
s()
assert a == 1
test_func()
| Add support for connecting functions to Signal objects. | Add support for connecting functions to Signal objects.
Less elegant than the original recipe, but more functional.
| Python | bsd-3-clause | stackp/Gum,stackp/Gum,stackp/Gum |
from weakref import WeakValueDictionary
+ import inspect
class Signal(object):
+
def __init__(self):
self.__slots = WeakValueDictionary()
+
+ # For keeping references to _FuncHost objects.
+ self.__funchosts = {}
def __call__(self, *args, **kargs):
for key in self.__slots:
func, _ = key
func(self.__slots[key], *args, **kargs)
def connect(self, slot):
+ if inspect.ismethod(slot):
- key = (slot.im_func, id(slot.im_self))
+ key = (slot.im_func, id(slot.im_self))
- self.__slots[key] = slot.im_self
+ self.__slots[key] = slot.im_self
+ else:
+ host = _FuncHost(slot)
+ self.connect(host.meth)
+ # We stick a copy in here just to keep the instance alive.
+ self.__funchosts[slot] = host
def disconnect(self, slot):
+ if inspect.ismethod(slot):
- key = (slot.im_func, id(slot.im_self))
+ key = (slot.im_func, id(slot.im_self))
- if key in self.__slots:
+ if key in self.__slots:
- self.__slots.pop(key)
+ self.__slots.pop(key)
+ else:
+ if slot in self.__funchosts:
+ self.disconnect(self.__funchosts[slot].meth)
+ self.__funchosts.pop(slot)
def clear(self):
self.__slots.clear()
+
+
+ class _FuncHost(object):
+ """Turn a function into a method."""
+ def __init__(self, func):
+ self.func = func
+
+ def meth(self, *args, **kwargs):
+ self.func(*args, **kwargs)
+
+
+ if __name__ == '__main__':
+
+ a = 0
+ def test_func():
+ def foo():
+ global a
+ a = a + 1
+ s = Signal()
+ s()
+ s.connect(foo)
+ s()
+ s.disconnect(foo)
+ s()
+ assert a == 1
+
+ test_func()
| Add support for connecting functions to Signal objects. | ## Code Before:
from weakref import WeakValueDictionary
class Signal(object):
def __init__(self):
self.__slots = WeakValueDictionary()
def __call__(self, *args, **kargs):
for key in self.__slots:
func, _ = key
func(self.__slots[key], *args, **kargs)
def connect(self, slot):
key = (slot.im_func, id(slot.im_self))
self.__slots[key] = slot.im_self
def disconnect(self, slot):
key = (slot.im_func, id(slot.im_self))
if key in self.__slots:
self.__slots.pop(key)
def clear(self):
self.__slots.clear()
## Instruction:
Add support for connecting functions to Signal objects.
## Code After:
from weakref import WeakValueDictionary
import inspect
class Signal(object):
def __init__(self):
self.__slots = WeakValueDictionary()
# For keeping references to _FuncHost objects.
self.__funchosts = {}
def __call__(self, *args, **kargs):
for key in self.__slots:
func, _ = key
func(self.__slots[key], *args, **kargs)
def connect(self, slot):
if inspect.ismethod(slot):
key = (slot.im_func, id(slot.im_self))
self.__slots[key] = slot.im_self
else:
host = _FuncHost(slot)
self.connect(host.meth)
# We stick a copy in here just to keep the instance alive.
self.__funchosts[slot] = host
def disconnect(self, slot):
if inspect.ismethod(slot):
key = (slot.im_func, id(slot.im_self))
if key in self.__slots:
self.__slots.pop(key)
else:
if slot in self.__funchosts:
self.disconnect(self.__funchosts[slot].meth)
self.__funchosts.pop(slot)
def clear(self):
self.__slots.clear()
class _FuncHost(object):
"""Turn a function into a method."""
def __init__(self, func):
self.func = func
def meth(self, *args, **kwargs):
self.func(*args, **kwargs)
if __name__ == '__main__':
a = 0
def test_func():
def foo():
global a
a = a + 1
s = Signal()
s()
s.connect(foo)
s()
s.disconnect(foo)
s()
assert a == 1
test_func()
|
fec482c6b1655d7108386760a3e0297850da6e7b | editorsnotes/api/validators.py | editorsnotes/api/validators.py | from rest_framework.serializers import ValidationError
class UniqueToProjectValidator:
message = u'{model_name} with this {field_name} already exists.'
def __init__(self, field, message=None):
self.field_name = field
self.message = message or self.message
def set_context(self, serializer):
self.ModelClass = serializer.Meta.model
self.instance = getattr(serializer, 'instance', None)
def __call__(self, attrs):
# Assuming that the field is always required
if self.instance is not None:
value = attrs.get(self.field_name,
getattr(self.instance, self.field_name))
else:
value = attrs[self.field_name]
kwargs = {'project': attrs['project'], self.field_name: value}
qs = self.ModelClass.objects.filter(**kwargs)
if self.instance is not None:
qs = qs.exclude(id=self.instance.id)
if qs.exists():
opts = self.ModelClass._meta
raise ValidationError({
self.field_name: self.message.format(
model_name=opts.verbose_name.title(),
field_name=opts.get_field(self.field_name).verbose_name
)
})
| from rest_framework.serializers import ValidationError
class UniqueToProjectValidator:
message = u'{model_name} with this {field_name} already exists.'
def __init__(self, field, message=None):
self.field_name = field
self.message = message or self.message
def set_context(self, serializer):
self.ModelClass = serializer.Meta.model
self.instance = getattr(serializer, 'instance', None)
self.project = serializer.context['request'].project
def __call__(self, attrs):
# Assuming that the field is always required
if self.instance is not None:
value = attrs.get(self.field_name,
getattr(self.instance, self.field_name))
else:
value = attrs[self.field_name]
kwargs = {'project': self.project, self.field_name: value}
qs = self.ModelClass.objects.filter(**kwargs)
if self.instance is not None:
qs = qs.exclude(id=self.instance.id)
if qs.exists():
opts = self.ModelClass._meta
raise ValidationError({
self.field_name: self.message.format(
model_name=opts.verbose_name.title(),
field_name=opts.get_field(self.field_name).verbose_name
)
})
| Make sure a project is set for the project-specific validator | Make sure a project is set for the project-specific validator
| Python | agpl-3.0 | editorsnotes/editorsnotes,editorsnotes/editorsnotes | from rest_framework.serializers import ValidationError
class UniqueToProjectValidator:
message = u'{model_name} with this {field_name} already exists.'
def __init__(self, field, message=None):
self.field_name = field
self.message = message or self.message
def set_context(self, serializer):
self.ModelClass = serializer.Meta.model
self.instance = getattr(serializer, 'instance', None)
+ self.project = serializer.context['request'].project
def __call__(self, attrs):
# Assuming that the field is always required
if self.instance is not None:
value = attrs.get(self.field_name,
getattr(self.instance, self.field_name))
else:
value = attrs[self.field_name]
- kwargs = {'project': attrs['project'], self.field_name: value}
+ kwargs = {'project': self.project, self.field_name: value}
qs = self.ModelClass.objects.filter(**kwargs)
if self.instance is not None:
qs = qs.exclude(id=self.instance.id)
if qs.exists():
opts = self.ModelClass._meta
raise ValidationError({
self.field_name: self.message.format(
model_name=opts.verbose_name.title(),
field_name=opts.get_field(self.field_name).verbose_name
)
})
| Make sure a project is set for the project-specific validator | ## Code Before:
from rest_framework.serializers import ValidationError
class UniqueToProjectValidator:
message = u'{model_name} with this {field_name} already exists.'
def __init__(self, field, message=None):
self.field_name = field
self.message = message or self.message
def set_context(self, serializer):
self.ModelClass = serializer.Meta.model
self.instance = getattr(serializer, 'instance', None)
def __call__(self, attrs):
# Assuming that the field is always required
if self.instance is not None:
value = attrs.get(self.field_name,
getattr(self.instance, self.field_name))
else:
value = attrs[self.field_name]
kwargs = {'project': attrs['project'], self.field_name: value}
qs = self.ModelClass.objects.filter(**kwargs)
if self.instance is not None:
qs = qs.exclude(id=self.instance.id)
if qs.exists():
opts = self.ModelClass._meta
raise ValidationError({
self.field_name: self.message.format(
model_name=opts.verbose_name.title(),
field_name=opts.get_field(self.field_name).verbose_name
)
})
## Instruction:
Make sure a project is set for the project-specific validator
## Code After:
from rest_framework.serializers import ValidationError
class UniqueToProjectValidator:
message = u'{model_name} with this {field_name} already exists.'
def __init__(self, field, message=None):
self.field_name = field
self.message = message or self.message
def set_context(self, serializer):
self.ModelClass = serializer.Meta.model
self.instance = getattr(serializer, 'instance', None)
self.project = serializer.context['request'].project
def __call__(self, attrs):
# Assuming that the field is always required
if self.instance is not None:
value = attrs.get(self.field_name,
getattr(self.instance, self.field_name))
else:
value = attrs[self.field_name]
kwargs = {'project': self.project, self.field_name: value}
qs = self.ModelClass.objects.filter(**kwargs)
if self.instance is not None:
qs = qs.exclude(id=self.instance.id)
if qs.exists():
opts = self.ModelClass._meta
raise ValidationError({
self.field_name: self.message.format(
model_name=opts.verbose_name.title(),
field_name=opts.get_field(self.field_name).verbose_name
)
})
|
57f131218ac7362fdf85389b73dcafb9d35897f4 | TriangleSimilarityDistanceCalculator.py | TriangleSimilarityDistanceCalculator.py | class TriangleSimilarityDistanceCalculator:
knownSize = 0
focalLength = 0;
def __init__(self, knownSize, perceivedFocalLength = None):
self.knownSize = knownSize
self.focalLength = perceivedFocalLength
# Call this to calibrate a camera and then use the calibrated focalLength value
# when using this class to calculate real distances.
def CalculatePerceivedFOVAtGivenDistance(self, perceivedSize, distance):
focalLength = perceivedSize * distance / float(self.knownSize)
return focalLength
# This will return the real world distance of the known object.
def CalcualteDistance(self, perceivedSize):
if self.focalLength == None:
raise ValueError("Did you forget to calibrate this camera and set the perceived focal length?")
distance = self.knownSize * self.focalLength / float(perceivedSize)
return distance
|
PFL_H_C920 = 622
PFL_V_C920 = 625
PFL_H_LC3000 = 652
PFL_V_LC3000 = 652
class TriangleSimilarityDistanceCalculator:
knownSize = 0
focalLength = 0;
def __init__(self, knownSize, perceivedFocalLength = None):
self.knownSize = knownSize
self.focalLength = perceivedFocalLength
# Call this to calibrate a camera and then use the calibrated focalLength value
# when using this class to calculate real distances.
def CalculatePerceivedFocalLengthAtGivenDistance(self, perceivedSize, knownDistance):
focalLength = perceivedSize * knownDistance / float(self.knownSize)
return focalLength
# This will return the real world distance of the known object.
def CalcualteDistance(self, perceivedSize):
if self.focalLength == None:
raise ValueError("Did you forget to calibrate this camera and set the perceived focal length?")
distance = self.knownSize * self.focalLength / float(perceivedSize)
return distance
| Update measured Focal Lengths for C920. | Update measured Focal Lengths for C920.
| Python | mit | AluminatiFRC/Vision2016,AluminatiFRC/Vision2016 | +
+ PFL_H_C920 = 622
+ PFL_V_C920 = 625
+ PFL_H_LC3000 = 652
+ PFL_V_LC3000 = 652
+
class TriangleSimilarityDistanceCalculator:
knownSize = 0
focalLength = 0;
def __init__(self, knownSize, perceivedFocalLength = None):
self.knownSize = knownSize
self.focalLength = perceivedFocalLength
# Call this to calibrate a camera and then use the calibrated focalLength value
# when using this class to calculate real distances.
- def CalculatePerceivedFOVAtGivenDistance(self, perceivedSize, distance):
+ def CalculatePerceivedFocalLengthAtGivenDistance(self, perceivedSize, knownDistance):
- focalLength = perceivedSize * distance / float(self.knownSize)
+ focalLength = perceivedSize * knownDistance / float(self.knownSize)
return focalLength
# This will return the real world distance of the known object.
def CalcualteDistance(self, perceivedSize):
if self.focalLength == None:
raise ValueError("Did you forget to calibrate this camera and set the perceived focal length?")
distance = self.knownSize * self.focalLength / float(perceivedSize)
return distance
| Update measured Focal Lengths for C920. | ## Code Before:
class TriangleSimilarityDistanceCalculator:
knownSize = 0
focalLength = 0;
def __init__(self, knownSize, perceivedFocalLength = None):
self.knownSize = knownSize
self.focalLength = perceivedFocalLength
# Call this to calibrate a camera and then use the calibrated focalLength value
# when using this class to calculate real distances.
def CalculatePerceivedFOVAtGivenDistance(self, perceivedSize, distance):
focalLength = perceivedSize * distance / float(self.knownSize)
return focalLength
# This will return the real world distance of the known object.
def CalcualteDistance(self, perceivedSize):
if self.focalLength == None:
raise ValueError("Did you forget to calibrate this camera and set the perceived focal length?")
distance = self.knownSize * self.focalLength / float(perceivedSize)
return distance
## Instruction:
Update measured Focal Lengths for C920.
## Code After:
PFL_H_C920 = 622
PFL_V_C920 = 625
PFL_H_LC3000 = 652
PFL_V_LC3000 = 652
class TriangleSimilarityDistanceCalculator:
knownSize = 0
focalLength = 0;
def __init__(self, knownSize, perceivedFocalLength = None):
self.knownSize = knownSize
self.focalLength = perceivedFocalLength
# Call this to calibrate a camera and then use the calibrated focalLength value
# when using this class to calculate real distances.
def CalculatePerceivedFocalLengthAtGivenDistance(self, perceivedSize, knownDistance):
focalLength = perceivedSize * knownDistance / float(self.knownSize)
return focalLength
# This will return the real world distance of the known object.
def CalcualteDistance(self, perceivedSize):
if self.focalLength == None:
raise ValueError("Did you forget to calibrate this camera and set the perceived focal length?")
distance = self.knownSize * self.focalLength / float(perceivedSize)
return distance
|
e82474c0281aebe3b623a5be9adc0adf14fa58d5 | ann_util.py | ann_util.py | import math
import random
def logistic(x):
return 1.0 / (1 + math.exp(-x))
def deriv_logistic(x):
lgst = logistic(x)
return (1 - lgst) * lgst
def hyperbolic_tangent(x):
return math.tanh(x)
def deriv_hyperbolic_tangent(x):
th = math.tanh(x)
return 1 - th * th
def between(min, max):
"""
Return a real random value between min and max.
"""
return random.random() * (max - min) + min
def make_matrix(N, M):
"""
Make an N rows by M columns matrix.
"""
return [[0 for i in range(M)] for i in range(N)]
| import math
import pickle
import random
def logistic(x):
return 1.0 / (1 + math.exp(-x))
def deriv_logistic(x):
lgst = logistic(x)
return (1 - lgst) * lgst
def hyperbolic_tangent(x):
return math.tanh(x)
def deriv_hyperbolic_tangent(x):
th = math.tanh(x)
return 1 - th * th
def between(min, max):
"""
Return a real random value between min and max.
"""
return random.random() * (max - min) + min
def make_matrix(N, M):
"""
Make an N rows by M columns matrix.
"""
return [[0 for i in range(M)] for i in range(N)]
def serialize(nn, fname):
with open(fname, 'wb') as f:
pickle.dump(nn, f)
def deserialize(fname):
with open(fname, 'rb') as f:
nn = pickle.load(f)
return nn
| Add pickle serialize and deserialize | Add pickle serialize and deserialize
| Python | apache-2.0 | Razvy000/ANN_Course | import math
+ import pickle
import random
def logistic(x):
return 1.0 / (1 + math.exp(-x))
def deriv_logistic(x):
lgst = logistic(x)
return (1 - lgst) * lgst
def hyperbolic_tangent(x):
return math.tanh(x)
def deriv_hyperbolic_tangent(x):
th = math.tanh(x)
return 1 - th * th
def between(min, max):
"""
Return a real random value between min and max.
"""
return random.random() * (max - min) + min
def make_matrix(N, M):
"""
Make an N rows by M columns matrix.
"""
return [[0 for i in range(M)] for i in range(N)]
+
+ def serialize(nn, fname):
+ with open(fname, 'wb') as f:
+ pickle.dump(nn, f)
+
+
+ def deserialize(fname):
+ with open(fname, 'rb') as f:
+ nn = pickle.load(f)
+ return nn
+ | Add pickle serialize and deserialize | ## Code Before:
import math
import random
def logistic(x):
return 1.0 / (1 + math.exp(-x))
def deriv_logistic(x):
lgst = logistic(x)
return (1 - lgst) * lgst
def hyperbolic_tangent(x):
return math.tanh(x)
def deriv_hyperbolic_tangent(x):
th = math.tanh(x)
return 1 - th * th
def between(min, max):
"""
Return a real random value between min and max.
"""
return random.random() * (max - min) + min
def make_matrix(N, M):
"""
Make an N rows by M columns matrix.
"""
return [[0 for i in range(M)] for i in range(N)]
## Instruction:
Add pickle serialize and deserialize
## Code After:
import math
import pickle
import random
def logistic(x):
return 1.0 / (1 + math.exp(-x))
def deriv_logistic(x):
lgst = logistic(x)
return (1 - lgst) * lgst
def hyperbolic_tangent(x):
return math.tanh(x)
def deriv_hyperbolic_tangent(x):
th = math.tanh(x)
return 1 - th * th
def between(min, max):
"""
Return a real random value between min and max.
"""
return random.random() * (max - min) + min
def make_matrix(N, M):
"""
Make an N rows by M columns matrix.
"""
return [[0 for i in range(M)] for i in range(N)]
def serialize(nn, fname):
with open(fname, 'wb') as f:
pickle.dump(nn, f)
def deserialize(fname):
with open(fname, 'rb') as f:
nn = pickle.load(f)
return nn
|
69f7490b6ed28c28784148295dec2144344f4ed8 | config.py | config.py | import os
if os.environ.get('DATABASE_URL') is None:
SQLALCHEMY_DATABASE_URI = 'sqlite:///meetup.db'
else:
SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL']
SQLALCHEMY_TRACK_MODIFICATIONS = False # supress deprecation warning
ACCESS_TOKEN = os.environ['ACCESS_TOKEN']
PAGE_ID = os.environ['PAGE_ID']
APP_ID = os.environ['APP_ID']
VERIFY_TOKEN = os.environ['VERIFY_TOKEN']
| import os
SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL']
SQLALCHEMY_TRACK_MODIFICATIONS = False # suppress deprecation warning
ACCESS_TOKEN = os.environ['ACCESS_TOKEN']
PAGE_ID = os.environ['PAGE_ID']
APP_ID = os.environ['APP_ID']
VERIFY_TOKEN = os.environ['VERIFY_TOKEN']
| Remove automatic fallback to SQLite | Remove automatic fallback to SQLite
It's better to be explicit if there's no DATABASE_URL.
| Python | mit | Stark-Mountain/meetup-facebook-bot,Stark-Mountain/meetup-facebook-bot | import os
-
- if os.environ.get('DATABASE_URL') is None:
- SQLALCHEMY_DATABASE_URI = 'sqlite:///meetup.db'
- else:
- SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL']
+ SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL']
-
- SQLALCHEMY_TRACK_MODIFICATIONS = False # supress deprecation warning
+ SQLALCHEMY_TRACK_MODIFICATIONS = False # suppress deprecation warning
ACCESS_TOKEN = os.environ['ACCESS_TOKEN']
PAGE_ID = os.environ['PAGE_ID']
APP_ID = os.environ['APP_ID']
VERIFY_TOKEN = os.environ['VERIFY_TOKEN']
| Remove automatic fallback to SQLite | ## Code Before:
import os
if os.environ.get('DATABASE_URL') is None:
SQLALCHEMY_DATABASE_URI = 'sqlite:///meetup.db'
else:
SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL']
SQLALCHEMY_TRACK_MODIFICATIONS = False # supress deprecation warning
ACCESS_TOKEN = os.environ['ACCESS_TOKEN']
PAGE_ID = os.environ['PAGE_ID']
APP_ID = os.environ['APP_ID']
VERIFY_TOKEN = os.environ['VERIFY_TOKEN']
## Instruction:
Remove automatic fallback to SQLite
## Code After:
import os
SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL']
SQLALCHEMY_TRACK_MODIFICATIONS = False # suppress deprecation warning
ACCESS_TOKEN = os.environ['ACCESS_TOKEN']
PAGE_ID = os.environ['PAGE_ID']
APP_ID = os.environ['APP_ID']
VERIFY_TOKEN = os.environ['VERIFY_TOKEN']
|
ab1a2982b6a44bfcfcaff5a3469f2d85f56a86a4 | src/cli/_dbus/_manager.py | src/cli/_dbus/_manager.py |
class Manager(object):
"""
Manager interface.
"""
_INTERFACE_NAME = 'org.storage.stratis1.Manager'
def __init__(self, dbus_object):
"""
Initializer.
:param dbus_object: the dbus object
"""
self._dbus_object = dbus_object
def CreatePool(self, pool_name, devices, num_devices):
"""
Create a pool.
:param str pool_name: the pool name
:param devices: the component devices
:type devices: sequence of str
"""
return self._dbus_object.CreatePool(
pool_name,
devices,
num_devices,
dbus_interface=self._INTERFACE_NAME,
)
def DestroyPool(self, pool_name):
"""
Destroy a pool.
:param str pool_name: the name of the pool
"""
return self._dbus_object.DestroyPool(
pool_name,
dbus_interface=self._INTERFACE_NAME
)
def ListPools(self):
"""
List all pools.
"""
return self._dbus_object.ListPools(dbus_interface=self._INTERFACE_NAME)
|
from ._properties import Properties
class Manager(object):
"""
Manager interface.
"""
_INTERFACE_NAME = 'org.storage.stratis1.Manager'
def __init__(self, dbus_object):
"""
Initializer.
:param dbus_object: the dbus object
"""
self._dbus_object = dbus_object
def CreatePool(self, pool_name, devices, num_devices):
"""
Create a pool.
:param str pool_name: the pool name
:param devices: the component devices
:type devices: sequence of str
"""
return self._dbus_object.CreatePool(
pool_name,
devices,
num_devices,
dbus_interface=self._INTERFACE_NAME,
)
def DestroyPool(self, pool_name):
"""
Destroy a pool.
:param str pool_name: the name of the pool
"""
return self._dbus_object.DestroyPool(
pool_name,
dbus_interface=self._INTERFACE_NAME
)
def ListPools(self):
"""
List all pools.
"""
return self._dbus_object.ListPools(dbus_interface=self._INTERFACE_NAME)
@property
def Version(self):
"""
Stratisd Version getter.
:rtype: String
"""
return Properties(self._dbus_object).Get(
self._INTERFACE_NAME,
'Version'
)
@property
def LogLevel(self):
"""
Stratisd LogLevel getter.
:rtype: String
"""
return Properties(self._dbus_object).Get(
self._INTERFACE_NAME,
'LogLevel'
)
@LogLevel.setter
def LogLevel(self, value):
"""
Stratisd LogLevel setter.
:param str value: the value to set
"""
return Properties(self._dbus_object).Set(
self._INTERFACE_NAME,
'LogLevel',
value
)
| Use Properties interface to get Manager properties. | Use Properties interface to get Manager properties.
Signed-off-by: mulhern <7b51bcf507bcd7afb72bf8663752c0ddbeb517f6@redhat.com>
| Python | apache-2.0 | stratis-storage/stratis-cli,stratis-storage/stratis-cli | +
+ from ._properties import Properties
+
class Manager(object):
"""
Manager interface.
"""
_INTERFACE_NAME = 'org.storage.stratis1.Manager'
def __init__(self, dbus_object):
"""
Initializer.
:param dbus_object: the dbus object
"""
self._dbus_object = dbus_object
def CreatePool(self, pool_name, devices, num_devices):
"""
Create a pool.
:param str pool_name: the pool name
:param devices: the component devices
:type devices: sequence of str
"""
return self._dbus_object.CreatePool(
pool_name,
devices,
num_devices,
dbus_interface=self._INTERFACE_NAME,
)
def DestroyPool(self, pool_name):
"""
Destroy a pool.
:param str pool_name: the name of the pool
"""
return self._dbus_object.DestroyPool(
pool_name,
dbus_interface=self._INTERFACE_NAME
)
def ListPools(self):
"""
List all pools.
"""
return self._dbus_object.ListPools(dbus_interface=self._INTERFACE_NAME)
+ @property
+ def Version(self):
+ """
+ Stratisd Version getter.
+
+ :rtype: String
+ """
+ return Properties(self._dbus_object).Get(
+ self._INTERFACE_NAME,
+ 'Version'
+ )
+
+ @property
+ def LogLevel(self):
+ """
+ Stratisd LogLevel getter.
+
+ :rtype: String
+ """
+ return Properties(self._dbus_object).Get(
+ self._INTERFACE_NAME,
+ 'LogLevel'
+ )
+
+ @LogLevel.setter
+ def LogLevel(self, value):
+ """
+ Stratisd LogLevel setter.
+
+ :param str value: the value to set
+ """
+ return Properties(self._dbus_object).Set(
+ self._INTERFACE_NAME,
+ 'LogLevel',
+ value
+ )
+ | Use Properties interface to get Manager properties. | ## Code Before:
class Manager(object):
"""
Manager interface.
"""
_INTERFACE_NAME = 'org.storage.stratis1.Manager'
def __init__(self, dbus_object):
"""
Initializer.
:param dbus_object: the dbus object
"""
self._dbus_object = dbus_object
def CreatePool(self, pool_name, devices, num_devices):
"""
Create a pool.
:param str pool_name: the pool name
:param devices: the component devices
:type devices: sequence of str
"""
return self._dbus_object.CreatePool(
pool_name,
devices,
num_devices,
dbus_interface=self._INTERFACE_NAME,
)
def DestroyPool(self, pool_name):
"""
Destroy a pool.
:param str pool_name: the name of the pool
"""
return self._dbus_object.DestroyPool(
pool_name,
dbus_interface=self._INTERFACE_NAME
)
def ListPools(self):
"""
List all pools.
"""
return self._dbus_object.ListPools(dbus_interface=self._INTERFACE_NAME)
## Instruction:
Use Properties interface to get Manager properties.
## Code After:
from ._properties import Properties
class Manager(object):
"""
Manager interface.
"""
_INTERFACE_NAME = 'org.storage.stratis1.Manager'
def __init__(self, dbus_object):
"""
Initializer.
:param dbus_object: the dbus object
"""
self._dbus_object = dbus_object
def CreatePool(self, pool_name, devices, num_devices):
"""
Create a pool.
:param str pool_name: the pool name
:param devices: the component devices
:type devices: sequence of str
"""
return self._dbus_object.CreatePool(
pool_name,
devices,
num_devices,
dbus_interface=self._INTERFACE_NAME,
)
def DestroyPool(self, pool_name):
"""
Destroy a pool.
:param str pool_name: the name of the pool
"""
return self._dbus_object.DestroyPool(
pool_name,
dbus_interface=self._INTERFACE_NAME
)
def ListPools(self):
"""
List all pools.
"""
return self._dbus_object.ListPools(dbus_interface=self._INTERFACE_NAME)
@property
def Version(self):
"""
Stratisd Version getter.
:rtype: String
"""
return Properties(self._dbus_object).Get(
self._INTERFACE_NAME,
'Version'
)
@property
def LogLevel(self):
"""
Stratisd LogLevel getter.
:rtype: String
"""
return Properties(self._dbus_object).Get(
self._INTERFACE_NAME,
'LogLevel'
)
@LogLevel.setter
def LogLevel(self, value):
"""
Stratisd LogLevel setter.
:param str value: the value to set
"""
return Properties(self._dbus_object).Set(
self._INTERFACE_NAME,
'LogLevel',
value
)
|
bdc554d18dc67cd4979bac3bc5d4b7d01b23b8b4 | grako/rendering.py | grako/rendering.py | from __future__ import print_function, division, absolute_import, unicode_literals
import itertools
from .util import trim
def render(item, **fields):
""" Render the given item
"""
if item is None:
return ''
elif isinstance(item, Renderer):
return item.render(**fields)
elif isinstance(item, list):
return ''.join(render(e) for e in item)
else:
return str(item)
class Renderer(object):
template = ''
_counter = itertools.count()
def __init__(self, template=None):
if template is not None:
self.template = template
def counter(self):
return next(self._counter)
def render_fields(self, fields):
pass
def render(self, template=None, **fields):
fields.update({k:v for k, v in vars(self).items() if not k.startswith('_')})
self.render_fields(fields)
if template is None:
template = self.template
fields = {k:render(v) for k, v in fields.items()}
try:
return trim(template).format(**fields)
except KeyError as e:
raise KeyError(str(e), type(self))
| from __future__ import print_function, division, absolute_import, unicode_literals
import itertools
from .util import trim
def render(item, **fields):
""" Render the given item
"""
if item is None:
return ''
elif isinstance(item, Renderer):
return item.render(**fields)
elif isinstance(item, list):
return ''.join(render(e) for e in item)
else:
return str(item)
class Renderer(object):
template = ''
_counter = itertools.count()
def __init__(self, template=None):
if template is not None:
self.template = template
def counter(self):
return next(self._counter)
def render_fields(self, fields):
pass
def render(self, template=None, **kwargs):
fields = ({k:v for k, v in vars(self).items() if not k.startswith('_')})
override = self.render_fields(fields)
if template is None:
if override is not None:
template = override
else:
template = self.template
fields.update(kwargs)
fields = {k:render(v) for k, v in fields.items()}
try:
return trim(template).format(**fields)
except KeyError as e:
raise KeyError(str(e), type(self))
| Allow override of template through return value of render_fields. | Allow override of template through return value of render_fields.
| Python | bsd-2-clause | swayf/grako,swayf/grako | from __future__ import print_function, division, absolute_import, unicode_literals
import itertools
from .util import trim
def render(item, **fields):
""" Render the given item
"""
if item is None:
return ''
elif isinstance(item, Renderer):
return item.render(**fields)
elif isinstance(item, list):
return ''.join(render(e) for e in item)
else:
return str(item)
class Renderer(object):
template = ''
_counter = itertools.count()
def __init__(self, template=None):
if template is not None:
self.template = template
def counter(self):
return next(self._counter)
def render_fields(self, fields):
pass
- def render(self, template=None, **fields):
+ def render(self, template=None, **kwargs):
- fields.update({k:v for k, v in vars(self).items() if not k.startswith('_')})
+ fields = ({k:v for k, v in vars(self).items() if not k.startswith('_')})
+
- self.render_fields(fields)
+ override = self.render_fields(fields)
if template is None:
+ if override is not None:
+ template = override
+ else:
- template = self.template
+ template = self.template
+
+ fields.update(kwargs)
fields = {k:render(v) for k, v in fields.items()}
try:
return trim(template).format(**fields)
except KeyError as e:
raise KeyError(str(e), type(self))
| Allow override of template through return value of render_fields. | ## Code Before:
from __future__ import print_function, division, absolute_import, unicode_literals
import itertools
from .util import trim
def render(item, **fields):
""" Render the given item
"""
if item is None:
return ''
elif isinstance(item, Renderer):
return item.render(**fields)
elif isinstance(item, list):
return ''.join(render(e) for e in item)
else:
return str(item)
class Renderer(object):
template = ''
_counter = itertools.count()
def __init__(self, template=None):
if template is not None:
self.template = template
def counter(self):
return next(self._counter)
def render_fields(self, fields):
pass
def render(self, template=None, **fields):
fields.update({k:v for k, v in vars(self).items() if not k.startswith('_')})
self.render_fields(fields)
if template is None:
template = self.template
fields = {k:render(v) for k, v in fields.items()}
try:
return trim(template).format(**fields)
except KeyError as e:
raise KeyError(str(e), type(self))
## Instruction:
Allow override of template through return value of render_fields.
## Code After:
from __future__ import print_function, division, absolute_import, unicode_literals
import itertools
from .util import trim
def render(item, **fields):
""" Render the given item
"""
if item is None:
return ''
elif isinstance(item, Renderer):
return item.render(**fields)
elif isinstance(item, list):
return ''.join(render(e) for e in item)
else:
return str(item)
class Renderer(object):
template = ''
_counter = itertools.count()
def __init__(self, template=None):
if template is not None:
self.template = template
def counter(self):
return next(self._counter)
def render_fields(self, fields):
pass
def render(self, template=None, **kwargs):
fields = ({k:v for k, v in vars(self).items() if not k.startswith('_')})
override = self.render_fields(fields)
if template is None:
if override is not None:
template = override
else:
template = self.template
fields.update(kwargs)
fields = {k:render(v) for k, v in fields.items()}
try:
return trim(template).format(**fields)
except KeyError as e:
raise KeyError(str(e), type(self))
|
f0984c9855a6283de27e717fad73bb4f1b6394ab | flatten-array/flatten_array.py | flatten-array/flatten_array.py | def flatten(lst):
"""Completely flatten an arbitrarily-deep list"""
return [*_flatten(lst)]
def _flatten(lst):
"""Generator for flattening arbitrarily-deep lists"""
if isinstance(lst, (list, tuple)):
for item in lst:
if item is None:
continue
else:
yield from _flatten(item)
else:
yield lst
| def flatten(lst):
"""Completely flatten an arbitrarily-deep list"""
return [*_flatten(lst)]
def _flatten(lst):
"""Generator for flattening arbitrarily-deep lists"""
for item in lst:
if isinstance(item, (list, tuple)):
yield from _flatten(item)
elif item is not None:
yield item
| Tidy and simplify generator code | Tidy and simplify generator code
| Python | agpl-3.0 | CubicComet/exercism-python-solutions | def flatten(lst):
"""Completely flatten an arbitrarily-deep list"""
return [*_flatten(lst)]
def _flatten(lst):
"""Generator for flattening arbitrarily-deep lists"""
- if isinstance(lst, (list, tuple)):
- for item in lst:
+ for item in lst:
+ if isinstance(item, (list, tuple)):
- if item is None:
- continue
- else:
- yield from _flatten(item)
+ yield from _flatten(item)
- else:
+ elif item is not None:
- yield lst
+ yield item
| Tidy and simplify generator code | ## Code Before:
def flatten(lst):
"""Completely flatten an arbitrarily-deep list"""
return [*_flatten(lst)]
def _flatten(lst):
"""Generator for flattening arbitrarily-deep lists"""
if isinstance(lst, (list, tuple)):
for item in lst:
if item is None:
continue
else:
yield from _flatten(item)
else:
yield lst
## Instruction:
Tidy and simplify generator code
## Code After:
def flatten(lst):
"""Completely flatten an arbitrarily-deep list"""
return [*_flatten(lst)]
def _flatten(lst):
"""Generator for flattening arbitrarily-deep lists"""
for item in lst:
if isinstance(item, (list, tuple)):
yield from _flatten(item)
elif item is not None:
yield item
|
8e6a835cf98212545d00f0967b6f6ce936143687 | fluxghost/http_server_debug.py | fluxghost/http_server_debug.py |
from multiprocessing import Process
import sys
from fluxghost.http_server_base import HttpServerBase, logger
def fork_entry(request, client, server):
from fluxghost.http_handler import HttpHandler
HttpHandler(request, client, server)
def check_autoreload():
if "fluxghost.http_handler" in sys.modules:
logger.error("Warning!! The fluxghost.http_handler has been "
"loaded before fork, auto-reload moudle function is"
" not work anymore.")
return
if "fluxclient" in sys.modules:
logger.error("Warning!! The fluxclient has been "
"loaded before fork, auto-reload moudle function is"
" not work anymore.")
return
class HttpServer(HttpServerBase):
def on_accept(self):
check_autoreload()
request, client = self.sock.accept()
w = Process(target=fork_entry, args=(request, client, self))
w.daemon = True
w.start()
|
from multiprocessing import Process
import sys
from fluxghost.http_server_base import HttpServerBase, logger
def fork_entry(request, client, server):
from fluxghost.http_handler import HttpHandler
HttpHandler(request, client, server)
def check_autoreload():
if "fluxghost.http_handler" in sys.modules:
logger.error("Warning!! The fluxghost.http_handler has been "
"loaded before fork, auto-reload moudle function is"
" not work anymore.")
return
if "fluxclient" in sys.modules:
logger.error("Warning!! The fluxclient has been "
"loaded before fork, auto-reload moudle function is"
" not work anymore.")
return
class HttpServer(HttpServerBase):
def on_accept(self):
check_autoreload()
request, client = self.sock.accept()
w = Process(target=fork_entry, args=(request, client, self))
w.daemon = True
w.start()
request.close()
| Fix missing close socket error | Fix missing close socket error
| Python | agpl-3.0 | flux3dp/fluxghost,flux3dp/fluxghost,flux3dp/fluxghost,flux3dp/fluxghost |
from multiprocessing import Process
import sys
from fluxghost.http_server_base import HttpServerBase, logger
def fork_entry(request, client, server):
from fluxghost.http_handler import HttpHandler
HttpHandler(request, client, server)
def check_autoreload():
if "fluxghost.http_handler" in sys.modules:
logger.error("Warning!! The fluxghost.http_handler has been "
"loaded before fork, auto-reload moudle function is"
" not work anymore.")
return
if "fluxclient" in sys.modules:
logger.error("Warning!! The fluxclient has been "
"loaded before fork, auto-reload moudle function is"
" not work anymore.")
return
class HttpServer(HttpServerBase):
def on_accept(self):
check_autoreload()
request, client = self.sock.accept()
w = Process(target=fork_entry, args=(request, client, self))
w.daemon = True
w.start()
+ request.close()
+ | Fix missing close socket error | ## Code Before:
from multiprocessing import Process
import sys
from fluxghost.http_server_base import HttpServerBase, logger
def fork_entry(request, client, server):
from fluxghost.http_handler import HttpHandler
HttpHandler(request, client, server)
def check_autoreload():
if "fluxghost.http_handler" in sys.modules:
logger.error("Warning!! The fluxghost.http_handler has been "
"loaded before fork, auto-reload moudle function is"
" not work anymore.")
return
if "fluxclient" in sys.modules:
logger.error("Warning!! The fluxclient has been "
"loaded before fork, auto-reload moudle function is"
" not work anymore.")
return
class HttpServer(HttpServerBase):
def on_accept(self):
check_autoreload()
request, client = self.sock.accept()
w = Process(target=fork_entry, args=(request, client, self))
w.daemon = True
w.start()
## Instruction:
Fix missing close socket error
## Code After:
from multiprocessing import Process
import sys
from fluxghost.http_server_base import HttpServerBase, logger
def fork_entry(request, client, server):
from fluxghost.http_handler import HttpHandler
HttpHandler(request, client, server)
def check_autoreload():
if "fluxghost.http_handler" in sys.modules:
logger.error("Warning!! The fluxghost.http_handler has been "
"loaded before fork, auto-reload moudle function is"
" not work anymore.")
return
if "fluxclient" in sys.modules:
logger.error("Warning!! The fluxclient has been "
"loaded before fork, auto-reload moudle function is"
" not work anymore.")
return
class HttpServer(HttpServerBase):
def on_accept(self):
check_autoreload()
request, client = self.sock.accept()
w = Process(target=fork_entry, args=(request, client, self))
w.daemon = True
w.start()
request.close()
|
2c00876b60cdebfe1ed9ffd93b3064abaf3a20a0 | rma/rule/GlobalKeySpace.py | rma/rule/GlobalKeySpace.py | from rma.redis import *
class GlobalKeySpace:
def __init__(self, redis):
"""
:param RmaRedis redis:
:return:
"""
self.redis = redis
def analyze(self, keys=[]):
total_keys = self.redis.total_keys()
return [
{
'headers': ['Stat', "Value"],
'data': [
["Total keys in db", total_keys],
["RedisDB key space overhead", dict_overhead(total_keys)]
]
}
]
| from rma.redis import *
class GlobalKeySpace:
def __init__(self, redis):
"""
:param RmaRedis redis:
:return:
"""
self.redis = redis
def analyze(self, keys=[]):
total_keys = self.redis.total_keys()
keys_ = [
["Total keys in db", total_keys],
["RedisDB key space overhead", dict_overhead(total_keys)]
]
keys_ += [["Used `{0}`".format(key), value] for key, value in self.redis.config_get("*max-*-*").items()]
return [
{
'headers': ['Stat', "Value"],
'data': keys_
}
]
| Add max config to globals | Add max config to globals
| Python | mit | gamenet/redis-memory-analyzer | from rma.redis import *
class GlobalKeySpace:
def __init__(self, redis):
"""
:param RmaRedis redis:
:return:
"""
self.redis = redis
def analyze(self, keys=[]):
total_keys = self.redis.total_keys()
+ keys_ = [
+ ["Total keys in db", total_keys],
+ ["RedisDB key space overhead", dict_overhead(total_keys)]
+ ]
+ keys_ += [["Used `{0}`".format(key), value] for key, value in self.redis.config_get("*max-*-*").items()]
+
return [
{
'headers': ['Stat', "Value"],
- 'data': [
+ 'data': keys_
- ["Total keys in db", total_keys],
- ["RedisDB key space overhead", dict_overhead(total_keys)]
- ]
}
]
| Add max config to globals | ## Code Before:
from rma.redis import *
class GlobalKeySpace:
def __init__(self, redis):
"""
:param RmaRedis redis:
:return:
"""
self.redis = redis
def analyze(self, keys=[]):
total_keys = self.redis.total_keys()
return [
{
'headers': ['Stat', "Value"],
'data': [
["Total keys in db", total_keys],
["RedisDB key space overhead", dict_overhead(total_keys)]
]
}
]
## Instruction:
Add max config to globals
## Code After:
from rma.redis import *
class GlobalKeySpace:
def __init__(self, redis):
"""
:param RmaRedis redis:
:return:
"""
self.redis = redis
def analyze(self, keys=[]):
total_keys = self.redis.total_keys()
keys_ = [
["Total keys in db", total_keys],
["RedisDB key space overhead", dict_overhead(total_keys)]
]
keys_ += [["Used `{0}`".format(key), value] for key, value in self.redis.config_get("*max-*-*").items()]
return [
{
'headers': ['Stat', "Value"],
'data': keys_
}
]
|
4c90c7445b0ccec8658fa71d50aa78a7de9c74b2 | salt/defaults/exitcodes.py | salt/defaults/exitcodes.py | '''
Classification of Salt exit codes. These are intended to augment
universal exit codes (found in Python's `os` module with the `EX_`
prefix or in `sysexits.h`).
'''
# Too many situations use "exit 1" - try not to use it when something
# else is more appropriate.
EX_GENERIC = 1
# Salt SSH "Thin" deployment failures
EX_THIN_PYTHON_OLD = 10
EX_THIN_DEPLOY = 11
EX_THIN_CHECKSUM = 12
EX_MOD_DEPLOY = 13
# The os.EX_* exit codes are Unix only so in the interest of cross-platform
# compatiblility define them explicitly here.
#
# These constants are documented here:
# https://docs.python.org/2/library/os.html#os.EX_OK
EX_OK = 0
EX_NOUSER = 67
EX_UNAVAILABLE = 69
EX_CANTCREAT = 73
EX_SOFTWARE = 70
EX_USAGE = 64
| '''
Classification of Salt exit codes. These are intended to augment
universal exit codes (found in Python's `os` module with the `EX_`
prefix or in `sysexits.h`).
'''
# Too many situations use "exit 1" - try not to use it when something
# else is more appropriate.
EX_GENERIC = 1
# Salt SSH "Thin" deployment failures
EX_THIN_PYTHON_OLD = 10
EX_THIN_DEPLOY = 11
EX_THIN_CHECKSUM = 12
EX_MOD_DEPLOY = 13
# The os.EX_* exit codes are Unix only so in the interest of cross-platform
# compatiblility define them explicitly here.
#
# These constants are documented here:
# https://docs.python.org/2/library/os.html#os.EX_OK
EX_OK = 0
EX_NOUSER = 67
EX_UNAVAILABLE = 69
EX_CANTCREAT = 73
EX_SOFTWARE = 70
EX_USAGE = 64
# The Salt specific exit codes are defined below:
# SALT_BUILD_FAIL is used when salt fails to build something, like a container
SALT_BUILD_FAIL = 101
| Add Salt specific exit code | Add Salt specific exit code
| Python | apache-2.0 | saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt | '''
Classification of Salt exit codes. These are intended to augment
universal exit codes (found in Python's `os` module with the `EX_`
prefix or in `sysexits.h`).
'''
# Too many situations use "exit 1" - try not to use it when something
# else is more appropriate.
EX_GENERIC = 1
# Salt SSH "Thin" deployment failures
EX_THIN_PYTHON_OLD = 10
EX_THIN_DEPLOY = 11
EX_THIN_CHECKSUM = 12
EX_MOD_DEPLOY = 13
# The os.EX_* exit codes are Unix only so in the interest of cross-platform
# compatiblility define them explicitly here.
#
# These constants are documented here:
# https://docs.python.org/2/library/os.html#os.EX_OK
EX_OK = 0
EX_NOUSER = 67
EX_UNAVAILABLE = 69
EX_CANTCREAT = 73
EX_SOFTWARE = 70
EX_USAGE = 64
+ # The Salt specific exit codes are defined below:
+
+ # SALT_BUILD_FAIL is used when salt fails to build something, like a container
+ SALT_BUILD_FAIL = 101
+ | Add Salt specific exit code | ## Code Before:
'''
Classification of Salt exit codes. These are intended to augment
universal exit codes (found in Python's `os` module with the `EX_`
prefix or in `sysexits.h`).
'''
# Too many situations use "exit 1" - try not to use it when something
# else is more appropriate.
EX_GENERIC = 1
# Salt SSH "Thin" deployment failures
EX_THIN_PYTHON_OLD = 10
EX_THIN_DEPLOY = 11
EX_THIN_CHECKSUM = 12
EX_MOD_DEPLOY = 13
# The os.EX_* exit codes are Unix only so in the interest of cross-platform
# compatiblility define them explicitly here.
#
# These constants are documented here:
# https://docs.python.org/2/library/os.html#os.EX_OK
EX_OK = 0
EX_NOUSER = 67
EX_UNAVAILABLE = 69
EX_CANTCREAT = 73
EX_SOFTWARE = 70
EX_USAGE = 64
## Instruction:
Add Salt specific exit code
## Code After:
'''
Classification of Salt exit codes. These are intended to augment
universal exit codes (found in Python's `os` module with the `EX_`
prefix or in `sysexits.h`).
'''
# Too many situations use "exit 1" - try not to use it when something
# else is more appropriate.
EX_GENERIC = 1
# Salt SSH "Thin" deployment failures
EX_THIN_PYTHON_OLD = 10
EX_THIN_DEPLOY = 11
EX_THIN_CHECKSUM = 12
EX_MOD_DEPLOY = 13
# The os.EX_* exit codes are Unix only so in the interest of cross-platform
# compatiblility define them explicitly here.
#
# These constants are documented here:
# https://docs.python.org/2/library/os.html#os.EX_OK
EX_OK = 0
EX_NOUSER = 67
EX_UNAVAILABLE = 69
EX_CANTCREAT = 73
EX_SOFTWARE = 70
EX_USAGE = 64
# The Salt specific exit codes are defined below:
# SALT_BUILD_FAIL is used when salt fails to build something, like a container
SALT_BUILD_FAIL = 101
|
54fdf3922615d5907a2e5344bf027df389572feb | byceps/services/user/transfer/models.py | byceps/services/user/transfer/models.py |
from __future__ import annotations
from dataclasses import dataclass
from datetime import date
from typing import Any, Optional
from ....typing import UserID
@dataclass(frozen=True)
class User:
id: UserID
screen_name: Optional[str]
suspended: bool
deleted: bool
locale: Optional[str]
avatar_url: Optional[str]
is_orga: bool
@dataclass(frozen=True)
class UserDetail:
first_names: Optional[str]
last_name: Optional[str]
date_of_birth: Optional[date]
country: Optional[str]
zip_code: Optional[str]
city: Optional[str]
street: Optional[str]
phone_number: Optional[str]
internal_comment: Optional[str]
extras: dict[str, Any]
@dataclass(frozen=True)
class UserWithDetail(User):
detail: UserDetail
|
from __future__ import annotations
from dataclasses import dataclass
from datetime import date
from typing import Any, Optional
from ....typing import UserID
@dataclass(frozen=True)
class User:
id: UserID
screen_name: Optional[str]
suspended: bool
deleted: bool
locale: Optional[str]
avatar_url: Optional[str]
is_orga: bool
@dataclass(frozen=True)
class UserDetail:
first_names: Optional[str]
last_name: Optional[str]
date_of_birth: Optional[date]
country: Optional[str]
zip_code: Optional[str]
city: Optional[str]
street: Optional[str]
phone_number: Optional[str]
internal_comment: Optional[str]
extras: dict[str, Any]
@property
def full_name(self) -> Optional[str]:
names = [self.first_names, self.last_name]
return ' '.join(filter(None, names)) or None
@dataclass(frozen=True)
class UserWithDetail(User):
detail: UserDetail
| Fix display of full user name at least on current user's settings page | Fix display of full user name at least on current user's settings page
| Python | bsd-3-clause | homeworkprod/byceps,homeworkprod/byceps,homeworkprod/byceps |
from __future__ import annotations
from dataclasses import dataclass
from datetime import date
from typing import Any, Optional
from ....typing import UserID
@dataclass(frozen=True)
class User:
id: UserID
screen_name: Optional[str]
suspended: bool
deleted: bool
locale: Optional[str]
avatar_url: Optional[str]
is_orga: bool
@dataclass(frozen=True)
class UserDetail:
first_names: Optional[str]
last_name: Optional[str]
date_of_birth: Optional[date]
country: Optional[str]
zip_code: Optional[str]
city: Optional[str]
street: Optional[str]
phone_number: Optional[str]
internal_comment: Optional[str]
extras: dict[str, Any]
+ @property
+ def full_name(self) -> Optional[str]:
+ names = [self.first_names, self.last_name]
+ return ' '.join(filter(None, names)) or None
+
@dataclass(frozen=True)
class UserWithDetail(User):
detail: UserDetail
| Fix display of full user name at least on current user's settings page | ## Code Before:
from __future__ import annotations
from dataclasses import dataclass
from datetime import date
from typing import Any, Optional
from ....typing import UserID
@dataclass(frozen=True)
class User:
id: UserID
screen_name: Optional[str]
suspended: bool
deleted: bool
locale: Optional[str]
avatar_url: Optional[str]
is_orga: bool
@dataclass(frozen=True)
class UserDetail:
first_names: Optional[str]
last_name: Optional[str]
date_of_birth: Optional[date]
country: Optional[str]
zip_code: Optional[str]
city: Optional[str]
street: Optional[str]
phone_number: Optional[str]
internal_comment: Optional[str]
extras: dict[str, Any]
@dataclass(frozen=True)
class UserWithDetail(User):
detail: UserDetail
## Instruction:
Fix display of full user name at least on current user's settings page
## Code After:
from __future__ import annotations
from dataclasses import dataclass
from datetime import date
from typing import Any, Optional
from ....typing import UserID
@dataclass(frozen=True)
class User:
id: UserID
screen_name: Optional[str]
suspended: bool
deleted: bool
locale: Optional[str]
avatar_url: Optional[str]
is_orga: bool
@dataclass(frozen=True)
class UserDetail:
first_names: Optional[str]
last_name: Optional[str]
date_of_birth: Optional[date]
country: Optional[str]
zip_code: Optional[str]
city: Optional[str]
street: Optional[str]
phone_number: Optional[str]
internal_comment: Optional[str]
extras: dict[str, Any]
@property
def full_name(self) -> Optional[str]:
names = [self.first_names, self.last_name]
return ' '.join(filter(None, names)) or None
@dataclass(frozen=True)
class UserWithDetail(User):
detail: UserDetail
|
8c8c0562e42ce789a283cec59771b1d1f3e95a2d | foreman/data_refinery_foreman/surveyor/management/commands/survey_sra.py | foreman/data_refinery_foreman/surveyor/management/commands/survey_sra.py |
from django.core.management.base import BaseCommand
from data_refinery_foreman.surveyor import surveyor
from data_refinery_common.logging import get_and_configure_logger
logger = get_and_configure_logger(__name__)
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument(
"--accession",
type=str,
help=("An SRA run accession. "))
parser.add_argument(
"--file",
type=str,
help=("An optional file listing accession codes.")
)
def handle(self, *args, **options):
if options["accession"] is None and options["file"] is None:
logger.error("You must specify accession or input file.")
return 1
if options["file"]:
with open(options["file"]) as file:
for acession in file:
try:
surveyor.survey_sra_experiment(accession.strip())
except Exception as e:
print(e)
else:
surveyor.survey_sra_experiment(options["accession"])
return 0
|
import boto3
import botocore
import uuid
from django.core.management.base import BaseCommand
from data_refinery_foreman.surveyor import surveyor
from data_refinery_common.logging import get_and_configure_logger
from data_refinery_common.utils import parse_s3_url
logger = get_and_configure_logger(__name__)
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument(
"--accession",
type=str,
help=("An SRA run accession. "))
parser.add_argument(
"--file",
type=str,
help=("An optional file listing accession codes. s3:// URLs are also accepted.")
)
def handle(self, *args, **options):
if options["accession"] is None and options["file"] is None:
logger.error("You must specify accession or input file.")
return 1
if options["file"]:
if 's3://' in options["file"]:
bucket, key = parse_s3_url(options["file"])
s3 = boto3.resource('s3')
try:
filepath = "/tmp/input_" + str(uuid.uuid4()) + ".txt"
s3.Bucket(bucket).download_file(key, filepath)
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == "404":
logger.error("The remote file does not exist.")
raise
else:
filepath = options["file"]
with open(filepath) as file:
for accession in file:
try:
surveyor.survey_sra_experiment(accession.strip())
except Exception as e:
print(e)
else:
surveyor.survey_sra_experiment(options["accession"])
return 0
| Add support of s3 path | Add support of s3 path
| Python | bsd-3-clause | data-refinery/data_refinery,data-refinery/data_refinery,data-refinery/data_refinery | +
+ import boto3
+ import botocore
+ import uuid
from django.core.management.base import BaseCommand
from data_refinery_foreman.surveyor import surveyor
from data_refinery_common.logging import get_and_configure_logger
-
+ from data_refinery_common.utils import parse_s3_url
logger = get_and_configure_logger(__name__)
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument(
"--accession",
type=str,
help=("An SRA run accession. "))
parser.add_argument(
"--file",
type=str,
- help=("An optional file listing accession codes.")
+ help=("An optional file listing accession codes. s3:// URLs are also accepted.")
)
def handle(self, *args, **options):
if options["accession"] is None and options["file"] is None:
logger.error("You must specify accession or input file.")
return 1
if options["file"]:
+ if 's3://' in options["file"]:
+ bucket, key = parse_s3_url(options["file"])
+ s3 = boto3.resource('s3')
+ try:
+ filepath = "/tmp/input_" + str(uuid.uuid4()) + ".txt"
+ s3.Bucket(bucket).download_file(key, filepath)
+ except botocore.exceptions.ClientError as e:
+ if e.response['Error']['Code'] == "404":
+ logger.error("The remote file does not exist.")
+ raise
+ else:
+ filepath = options["file"]
+
- with open(options["file"]) as file:
+ with open(filepath) as file:
- for acession in file:
+ for accession in file:
try:
surveyor.survey_sra_experiment(accession.strip())
except Exception as e:
print(e)
else:
surveyor.survey_sra_experiment(options["accession"])
return 0
| Add support of s3 path | ## Code Before:
from django.core.management.base import BaseCommand
from data_refinery_foreman.surveyor import surveyor
from data_refinery_common.logging import get_and_configure_logger
logger = get_and_configure_logger(__name__)
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument(
"--accession",
type=str,
help=("An SRA run accession. "))
parser.add_argument(
"--file",
type=str,
help=("An optional file listing accession codes.")
)
def handle(self, *args, **options):
if options["accession"] is None and options["file"] is None:
logger.error("You must specify accession or input file.")
return 1
if options["file"]:
with open(options["file"]) as file:
for acession in file:
try:
surveyor.survey_sra_experiment(accession.strip())
except Exception as e:
print(e)
else:
surveyor.survey_sra_experiment(options["accession"])
return 0
## Instruction:
Add support of s3 path
## Code After:
import boto3
import botocore
import uuid
from django.core.management.base import BaseCommand
from data_refinery_foreman.surveyor import surveyor
from data_refinery_common.logging import get_and_configure_logger
from data_refinery_common.utils import parse_s3_url
logger = get_and_configure_logger(__name__)
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument(
"--accession",
type=str,
help=("An SRA run accession. "))
parser.add_argument(
"--file",
type=str,
help=("An optional file listing accession codes. s3:// URLs are also accepted.")
)
def handle(self, *args, **options):
if options["accession"] is None and options["file"] is None:
logger.error("You must specify accession or input file.")
return 1
if options["file"]:
if 's3://' in options["file"]:
bucket, key = parse_s3_url(options["file"])
s3 = boto3.resource('s3')
try:
filepath = "/tmp/input_" + str(uuid.uuid4()) + ".txt"
s3.Bucket(bucket).download_file(key, filepath)
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == "404":
logger.error("The remote file does not exist.")
raise
else:
filepath = options["file"]
with open(filepath) as file:
for accession in file:
try:
surveyor.survey_sra_experiment(accession.strip())
except Exception as e:
print(e)
else:
surveyor.survey_sra_experiment(options["accession"])
return 0
|
6b365ae7d7ab01255643c48755590b8a1a0ae173 | src/lib/constants/path.py | src/lib/constants/path.py | VIRTUALENV_DIR = "virtual_env/"
VIRTUALENV_ACTIVATE = VIRTUALENV_DIR + "bin/activate_this.py"
LOGS = "logs/"
YAML = "/etc/ggrc_test.yaml"
RESOURCES = "resources/"
REQUIREMENTS = RESOURCES + "requirements.txt"
SRC = "src/"
| VIRTUALENV_DIR = "virtual_env/"
BIN_DIR = "bin/"
VIRTUALENV_ACTIVATE = "activate_this.py"
LOGS = "logs/"
YAML = "/etc/ggrc_test.yaml"
RESOURCES = "resources/"
REQUIREMENTS = RESOURCES + "requirements.txt"
SRC = "src/"
CHROME_DRIVER = "chromedriver"
| Remove operations in module reserved for declaring constants. | Remove operations in module reserved for declaring constants.
| Python | apache-2.0 | NejcZupec/ggrc-core,plamut/ggrc-core,j0gurt/ggrc-core,NejcZupec/ggrc-core,jmakov/ggrc-core,jmakov/ggrc-core,j0gurt/ggrc-core,VinnieJohns/ggrc-core,jmakov/ggrc-core,kr41/ggrc-core,kr41/ggrc-core,kr41/ggrc-core,VinnieJohns/ggrc-core,andrei-karalionak/ggrc-core,AleksNeStu/ggrc-core,josthkko/ggrc-core,selahssea/ggrc-core,selahssea/ggrc-core,jmakov/ggrc-core,AleksNeStu/ggrc-core,selahssea/ggrc-core,VinnieJohns/ggrc-core,edofic/ggrc-core,NejcZupec/ggrc-core,NejcZupec/ggrc-core,AleksNeStu/ggrc-core,jmakov/ggrc-core,j0gurt/ggrc-core,andrei-karalionak/ggrc-core,andrei-karalionak/ggrc-core,plamut/ggrc-core,prasannav7/ggrc-core,j0gurt/ggrc-core,prasannav7/ggrc-core,edofic/ggrc-core,josthkko/ggrc-core,edofic/ggrc-core,kr41/ggrc-core,prasannav7/ggrc-core,prasannav7/ggrc-core,edofic/ggrc-core,plamut/ggrc-core,AleksNeStu/ggrc-core,josthkko/ggrc-core,VinnieJohns/ggrc-core,andrei-karalionak/ggrc-core,josthkko/ggrc-core,plamut/ggrc-core,selahssea/ggrc-core | VIRTUALENV_DIR = "virtual_env/"
+ BIN_DIR = "bin/"
- VIRTUALENV_ACTIVATE = VIRTUALENV_DIR + "bin/activate_this.py"
+ VIRTUALENV_ACTIVATE = "activate_this.py"
LOGS = "logs/"
YAML = "/etc/ggrc_test.yaml"
RESOURCES = "resources/"
REQUIREMENTS = RESOURCES + "requirements.txt"
SRC = "src/"
+ CHROME_DRIVER = "chromedriver"
| Remove operations in module reserved for declaring constants. | ## Code Before:
VIRTUALENV_DIR = "virtual_env/"
VIRTUALENV_ACTIVATE = VIRTUALENV_DIR + "bin/activate_this.py"
LOGS = "logs/"
YAML = "/etc/ggrc_test.yaml"
RESOURCES = "resources/"
REQUIREMENTS = RESOURCES + "requirements.txt"
SRC = "src/"
## Instruction:
Remove operations in module reserved for declaring constants.
## Code After:
VIRTUALENV_DIR = "virtual_env/"
BIN_DIR = "bin/"
VIRTUALENV_ACTIVATE = "activate_this.py"
LOGS = "logs/"
YAML = "/etc/ggrc_test.yaml"
RESOURCES = "resources/"
REQUIREMENTS = RESOURCES + "requirements.txt"
SRC = "src/"
CHROME_DRIVER = "chromedriver"
|
5f6d994dfde18206e000537510b87f451234f1d3 | installer/installer_config/forms.py | installer/installer_config/forms.py | from django import forms
from django.forms.models import ModelForm
from installer_config.models import EnvironmentProfile, Package, TerminalPrompt
class EnvironmentForm(ModelForm):
packages = forms.ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple,
queryset=Package.objects.all())
class Meta:
model = EnvironmentProfile
exclude = ('user',)
| from django import forms
from django.forms.models import ModelForm
from installer_config.models import EnvironmentProfile, UserChoice
class EnvironmentForm(ModelForm):
packages = forms.ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple,
queryset=UserChoice.objects.all())
class Meta:
model = EnvironmentProfile
exclude = ('user',)
| Fix form to query UserChoices, not Packages | Fix form to query UserChoices, not Packages
| Python | mit | ezPy-co/ezpy,ezPy-co/ezpy,alibulota/Package_Installer,alibulota/Package_Installer | from django import forms
from django.forms.models import ModelForm
- from installer_config.models import EnvironmentProfile, Package, TerminalPrompt
+ from installer_config.models import EnvironmentProfile, UserChoice
class EnvironmentForm(ModelForm):
packages = forms.ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple,
- queryset=Package.objects.all())
+ queryset=UserChoice.objects.all())
class Meta:
model = EnvironmentProfile
exclude = ('user',)
| Fix form to query UserChoices, not Packages | ## Code Before:
from django import forms
from django.forms.models import ModelForm
from installer_config.models import EnvironmentProfile, Package, TerminalPrompt
class EnvironmentForm(ModelForm):
packages = forms.ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple,
queryset=Package.objects.all())
class Meta:
model = EnvironmentProfile
exclude = ('user',)
## Instruction:
Fix form to query UserChoices, not Packages
## Code After:
from django import forms
from django.forms.models import ModelForm
from installer_config.models import EnvironmentProfile, UserChoice
class EnvironmentForm(ModelForm):
packages = forms.ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple,
queryset=UserChoice.objects.all())
class Meta:
model = EnvironmentProfile
exclude = ('user',)
|
e69c9db3efc5f71a5852a28ea77a215d083a6b64 | server/inventory/views.py | server/inventory/views.py | from django.shortcuts import render
from django.core import serializers
from inventory.models import Item
from decimal import Decimal
import json
from django.utils import simplejson
# Create your views here.
from django.http import HttpResponse
from inventory.models import Item
def index(request):
if request.method == 'GET':
list_of_items = Item.objects.all()
data = serializers.serialize("json", list_of_items)
return HttpResponse(data, content_type="application/json")
if request.method == 'POST':
data = simplejson.loads(request.body.decode(), parse_float=Decimal)['fields']
items = Item.objects.filter(itemId=data['itemId'])
if items:
for o in items:
o.count = data['count']
o.save()
else:
item = Item(itemId=data['itemId'], count=data['count'], name=data['name'], short=data['short'], desc=data['desc'])
item.save()
return HttpResponse({}, content_type="application/json")
def detail(request, item_id):
if request.method == 'GET':
item = Item.objects.filter(itemId=item_id)
data = serializers.serialize("json", item)
return HttpResponse(data, content_type="application/json")
if request.method == 'DELETE':
Item.objects.filter(itemId=item_id).delete()
return HttpResponse({}, content_type="application/json")
| from django.shortcuts import render
from django.core import serializers
from inventory.models import Item
from decimal import Decimal
import json
from django.utils import simplejson
# Create your views here.
from django.http import HttpResponse
from inventory.models import Item
def index(request):
if request.method == 'GET':
list_of_items = Item.objects.all()
data = serializers.serialize("json", list_of_items)
return HttpResponse(data, content_type="application/json")
if request.method == 'POST':
if request.user.username:
data = simplejson.loads(request.body.decode(), parse_float=Decimal)['fields']
items = Item.objects.filter(itemId=data['itemId'])
if items:
for o in items:
o.count = data['count']
o.save()
else:
item = Item(itemId=data['itemId'], count=data['count'], name=data['name'], short=data['short'], desc=data['desc'])
item.save()
return HttpResponse({}, content_type="application/json")
else:
return HttpResponse('Unauthorized', status=401)
def detail(request, item_id):
if request.method == 'GET':
item = Item.objects.filter(itemId=item_id)
data = serializers.serialize("json", item)
return HttpResponse(data, content_type="application/json")
if request.method == 'DELETE':
if request.user.username:
Item.objects.filter(itemId=item_id).delete()
return HttpResponse({}, content_type="application/json")
else:
return HttpResponse('Unauthorized', status=401)
| Add the 401 Unauthorized when no username is detected, thus no user is logged in. This is the most basic form of permissions, where any user can log in and do anything. | Add the 401 Unauthorized when no username is detected, thus no user
is logged in. This is the most basic form of permissions, where any
user can log in and do anything.
| Python | agpl-3.0 | TomDataworks/angular-inventory,TomDataworks/angular-inventory | from django.shortcuts import render
from django.core import serializers
from inventory.models import Item
from decimal import Decimal
import json
from django.utils import simplejson
# Create your views here.
from django.http import HttpResponse
from inventory.models import Item
def index(request):
if request.method == 'GET':
list_of_items = Item.objects.all()
data = serializers.serialize("json", list_of_items)
return HttpResponse(data, content_type="application/json")
if request.method == 'POST':
+ if request.user.username:
- data = simplejson.loads(request.body.decode(), parse_float=Decimal)['fields']
+ data = simplejson.loads(request.body.decode(), parse_float=Decimal)['fields']
- items = Item.objects.filter(itemId=data['itemId'])
+ items = Item.objects.filter(itemId=data['itemId'])
- if items:
+ if items:
- for o in items:
+ for o in items:
- o.count = data['count']
+ o.count = data['count']
- o.save()
+ o.save()
+ else:
+ item = Item(itemId=data['itemId'], count=data['count'], name=data['name'], short=data['short'], desc=data['desc'])
+ item.save()
+ return HttpResponse({}, content_type="application/json")
else:
+ return HttpResponse('Unauthorized', status=401)
- item = Item(itemId=data['itemId'], count=data['count'], name=data['name'], short=data['short'], desc=data['desc'])
- item.save()
- return HttpResponse({}, content_type="application/json")
def detail(request, item_id):
if request.method == 'GET':
item = Item.objects.filter(itemId=item_id)
data = serializers.serialize("json", item)
return HttpResponse(data, content_type="application/json")
if request.method == 'DELETE':
+ if request.user.username:
- Item.objects.filter(itemId=item_id).delete()
+ Item.objects.filter(itemId=item_id).delete()
- return HttpResponse({}, content_type="application/json")
+ return HttpResponse({}, content_type="application/json")
+ else:
+ return HttpResponse('Unauthorized', status=401)
| Add the 401 Unauthorized when no username is detected, thus no user is logged in. This is the most basic form of permissions, where any user can log in and do anything. | ## Code Before:
from django.shortcuts import render
from django.core import serializers
from inventory.models import Item
from decimal import Decimal
import json
from django.utils import simplejson
# Create your views here.
from django.http import HttpResponse
from inventory.models import Item
def index(request):
if request.method == 'GET':
list_of_items = Item.objects.all()
data = serializers.serialize("json", list_of_items)
return HttpResponse(data, content_type="application/json")
if request.method == 'POST':
data = simplejson.loads(request.body.decode(), parse_float=Decimal)['fields']
items = Item.objects.filter(itemId=data['itemId'])
if items:
for o in items:
o.count = data['count']
o.save()
else:
item = Item(itemId=data['itemId'], count=data['count'], name=data['name'], short=data['short'], desc=data['desc'])
item.save()
return HttpResponse({}, content_type="application/json")
def detail(request, item_id):
if request.method == 'GET':
item = Item.objects.filter(itemId=item_id)
data = serializers.serialize("json", item)
return HttpResponse(data, content_type="application/json")
if request.method == 'DELETE':
Item.objects.filter(itemId=item_id).delete()
return HttpResponse({}, content_type="application/json")
## Instruction:
Add the 401 Unauthorized when no username is detected, thus no user is logged in. This is the most basic form of permissions, where any user can log in and do anything.
## Code After:
from django.shortcuts import render
from django.core import serializers
from inventory.models import Item
from decimal import Decimal
import json
from django.utils import simplejson
# Create your views here.
from django.http import HttpResponse
from inventory.models import Item
def index(request):
if request.method == 'GET':
list_of_items = Item.objects.all()
data = serializers.serialize("json", list_of_items)
return HttpResponse(data, content_type="application/json")
if request.method == 'POST':
if request.user.username:
data = simplejson.loads(request.body.decode(), parse_float=Decimal)['fields']
items = Item.objects.filter(itemId=data['itemId'])
if items:
for o in items:
o.count = data['count']
o.save()
else:
item = Item(itemId=data['itemId'], count=data['count'], name=data['name'], short=data['short'], desc=data['desc'])
item.save()
return HttpResponse({}, content_type="application/json")
else:
return HttpResponse('Unauthorized', status=401)
def detail(request, item_id):
if request.method == 'GET':
item = Item.objects.filter(itemId=item_id)
data = serializers.serialize("json", item)
return HttpResponse(data, content_type="application/json")
if request.method == 'DELETE':
if request.user.username:
Item.objects.filter(itemId=item_id).delete()
return HttpResponse({}, content_type="application/json")
else:
return HttpResponse('Unauthorized', status=401)
|
876c9b81a295c30a644bfe3e8efa5f0d644b9b67 | app/soc/modules/gsoc/logic/program.py | app/soc/modules/gsoc/logic/program.py |
def getMostRecentProgram(data):
"""Returns the most recent program.
Returns:
The program link_id for the most recent gci program.
"""
return data.site.latest_gsoc
|
"""GSoC logic for program."""
def getMostRecentProgram(data):
"""Returns the most recent program.
Returns:
The program link_id for the most recent GSoC program.
"""
return data.site.latest_gsoc
| Fix a leftover "gci" documentation note to correctly refer to Summer of Code. | Fix a leftover "gci" documentation note to correctly refer to Summer of Code.
This fixes issue 1790, and thanks to Piyush Bansal for reporting the error
and directing its fix.
| Python | apache-2.0 | rhyolight/nupic.son,rhyolight/nupic.son,rhyolight/nupic.son | +
+ """GSoC logic for program."""
def getMostRecentProgram(data):
"""Returns the most recent program.
Returns:
- The program link_id for the most recent gci program.
+ The program link_id for the most recent GSoC program.
"""
return data.site.latest_gsoc
| Fix a leftover "gci" documentation note to correctly refer to Summer of Code. | ## Code Before:
def getMostRecentProgram(data):
"""Returns the most recent program.
Returns:
The program link_id for the most recent gci program.
"""
return data.site.latest_gsoc
## Instruction:
Fix a leftover "gci" documentation note to correctly refer to Summer of Code.
## Code After:
"""GSoC logic for program."""
def getMostRecentProgram(data):
"""Returns the most recent program.
Returns:
The program link_id for the most recent GSoC program.
"""
return data.site.latest_gsoc
|
428b4b0025dd7bb0edf5d3df8c32703d96ab577b | src/shared/unit_orders.py | src/shared/unit_orders.py | class UnitOrders(object):
def __init__(self):
self.orders = {}
def giveOrders(self, unit, orders):
if orders is not None and not isinstance(orders, list):
orders = list(orders)
self.orders[unit] = orders
def getNextOrder(self, unit):
try:
return self.orders[unit][0]
except (KeyError, IndexError):
return None
def removeNextOrder(self, unit):
self.orders[unit] = self.orders[unit][1:]
if not self.orders[unit]:
del self.orders[unit]
def getAllUnitsNextOrders(self):
return {x: self.getNextOrder(x) for x in self.orders}
| class UnitOrders(object):
def __init__(self):
self.orders = {}
def giveOrders(self, unit, orders):
if orders is not None and not isinstance(orders, list):
orders = list(orders)
self.orders[unit] = orders
def getNextOrder(self, unit):
try:
orders = self.orders[unit]
if orders is None:
return None
else:
return orders[0]
except (KeyError, IndexError):
return None
def removeNextOrder(self, unit):
self.orders[unit] = self.orders[unit][1:]
if not self.orders[unit]:
del self.orders[unit]
def getAllUnitsNextOrders(self):
return {x: self.getNextOrder(x) for x in self.orders}
| Check for None before indexing. | Check for None before indexing.
| Python | mit | CheeseLord/warts,CheeseLord/warts | class UnitOrders(object):
def __init__(self):
self.orders = {}
def giveOrders(self, unit, orders):
if orders is not None and not isinstance(orders, list):
orders = list(orders)
self.orders[unit] = orders
def getNextOrder(self, unit):
try:
- return self.orders[unit][0]
+ orders = self.orders[unit]
+ if orders is None:
+ return None
+ else:
+ return orders[0]
except (KeyError, IndexError):
return None
def removeNextOrder(self, unit):
self.orders[unit] = self.orders[unit][1:]
if not self.orders[unit]:
del self.orders[unit]
def getAllUnitsNextOrders(self):
return {x: self.getNextOrder(x) for x in self.orders}
| Check for None before indexing. | ## Code Before:
class UnitOrders(object):
def __init__(self):
self.orders = {}
def giveOrders(self, unit, orders):
if orders is not None and not isinstance(orders, list):
orders = list(orders)
self.orders[unit] = orders
def getNextOrder(self, unit):
try:
return self.orders[unit][0]
except (KeyError, IndexError):
return None
def removeNextOrder(self, unit):
self.orders[unit] = self.orders[unit][1:]
if not self.orders[unit]:
del self.orders[unit]
def getAllUnitsNextOrders(self):
return {x: self.getNextOrder(x) for x in self.orders}
## Instruction:
Check for None before indexing.
## Code After:
class UnitOrders(object):
def __init__(self):
self.orders = {}
def giveOrders(self, unit, orders):
if orders is not None and not isinstance(orders, list):
orders = list(orders)
self.orders[unit] = orders
def getNextOrder(self, unit):
try:
orders = self.orders[unit]
if orders is None:
return None
else:
return orders[0]
except (KeyError, IndexError):
return None
def removeNextOrder(self, unit):
self.orders[unit] = self.orders[unit][1:]
if not self.orders[unit]:
del self.orders[unit]
def getAllUnitsNextOrders(self):
return {x: self.getNextOrder(x) for x in self.orders}
|
74b03f3d47011bad6129f8ccfe466a4b28d2338a | troposphere/workspaces.py | troposphere/workspaces.py |
from . import AWSObject
from .validators import boolean
class Workspace(AWSObject):
resource_type = "AWS::WorkSpaces::Workspace"
props = {
'BundleId': (basestring, True),
'DirectoryId': (basestring, True),
'UserName': (basestring, True),
'RootVolumeEncryptionEnabled': (boolean, False),
'UserVolumeEncryptionEnabled': (boolean, False),
'VolumeEncryptionKey': (basestring, False),
}
|
from . import AWSObject, AWSProperty, Tags
from .validators import boolean, integer
class WorkspaceProperties(AWSProperty):
props = {
'ComputeTypeName': (basestring, False),
'RootVolumeSizeGib': (integer, False),
'RunningMode': (basestring, False),
'RunningModeAutoStopTimeoutInMinutes': (integer, False),
'UserVolumeSizeGib': (integer, False),
}
class Workspace(AWSObject):
resource_type = "AWS::WorkSpaces::Workspace"
props = {
'BundleId': (basestring, True),
'DirectoryId': (basestring, True),
'UserName': (basestring, True),
'RootVolumeEncryptionEnabled': (boolean, False),
'Tags': (Tags, False),
'UserVolumeEncryptionEnabled': (boolean, False),
'VolumeEncryptionKey': (basestring, False),
'WorkspaceProperties': (WorkspaceProperties, False),
}
| Add Tags and WorkspaceProperties to WorkSpaces::Workspace | Add Tags and WorkspaceProperties to WorkSpaces::Workspace
| Python | bsd-2-clause | johnctitus/troposphere,cloudtools/troposphere,johnctitus/troposphere,pas256/troposphere,pas256/troposphere,cloudtools/troposphere,ikben/troposphere,ikben/troposphere |
- from . import AWSObject
+ from . import AWSObject, AWSProperty, Tags
- from .validators import boolean
+ from .validators import boolean, integer
+
+
+ class WorkspaceProperties(AWSProperty):
+ props = {
+ 'ComputeTypeName': (basestring, False),
+ 'RootVolumeSizeGib': (integer, False),
+ 'RunningMode': (basestring, False),
+ 'RunningModeAutoStopTimeoutInMinutes': (integer, False),
+ 'UserVolumeSizeGib': (integer, False),
+ }
class Workspace(AWSObject):
resource_type = "AWS::WorkSpaces::Workspace"
props = {
'BundleId': (basestring, True),
'DirectoryId': (basestring, True),
'UserName': (basestring, True),
'RootVolumeEncryptionEnabled': (boolean, False),
+ 'Tags': (Tags, False),
'UserVolumeEncryptionEnabled': (boolean, False),
'VolumeEncryptionKey': (basestring, False),
+ 'WorkspaceProperties': (WorkspaceProperties, False),
}
| Add Tags and WorkspaceProperties to WorkSpaces::Workspace | ## Code Before:
from . import AWSObject
from .validators import boolean
class Workspace(AWSObject):
resource_type = "AWS::WorkSpaces::Workspace"
props = {
'BundleId': (basestring, True),
'DirectoryId': (basestring, True),
'UserName': (basestring, True),
'RootVolumeEncryptionEnabled': (boolean, False),
'UserVolumeEncryptionEnabled': (boolean, False),
'VolumeEncryptionKey': (basestring, False),
}
## Instruction:
Add Tags and WorkspaceProperties to WorkSpaces::Workspace
## Code After:
from . import AWSObject, AWSProperty, Tags
from .validators import boolean, integer
class WorkspaceProperties(AWSProperty):
props = {
'ComputeTypeName': (basestring, False),
'RootVolumeSizeGib': (integer, False),
'RunningMode': (basestring, False),
'RunningModeAutoStopTimeoutInMinutes': (integer, False),
'UserVolumeSizeGib': (integer, False),
}
class Workspace(AWSObject):
resource_type = "AWS::WorkSpaces::Workspace"
props = {
'BundleId': (basestring, True),
'DirectoryId': (basestring, True),
'UserName': (basestring, True),
'RootVolumeEncryptionEnabled': (boolean, False),
'Tags': (Tags, False),
'UserVolumeEncryptionEnabled': (boolean, False),
'VolumeEncryptionKey': (basestring, False),
'WorkspaceProperties': (WorkspaceProperties, False),
}
|
05b54e3ac66da81733e8bb04eb949dec4e6be904 | lamana/lt_exceptions.py | lamana/lt_exceptions.py | '''General classes for a custom exceptions.'''
class Error(Exception):
pass
class FormatError(Error):
'''Associate with geo_string formatting.'''
pass
class InvalidError(Error):
'''Associate with invalid, impossible geo_strings.'''
pass
class KeyError(Error):
pass
class NotImplementedError(Error):
pass
class IndeterminateError(Error):
'''Associate with INDET exceptions.
See Also
--------
- "More on IndeterminateError" in the documentation.
'''
pass
class PlottingError(Error):
'''Associated with plotting errors.'''
pass
| '''General classes for a custom exceptions.'''
class Error(Exception):
pass
class FormatError(Error):
'''Associated with geo_string formatting.'''
pass
#class ValidationError(Error):
# '''Associate with invalid, impossible geo_strings.'''
# pass
#class KeyError(Error):
# pass
class InputError(Error):
'''Associated with invalid user inputs.'''
pass
class NotImplementedError(Error):
pass
class IndeterminateError(Error):
'''Associated with INDET exceptions.
See Also
--------
- "More on IndeterminateError" in the documentation.
'''
pass
class PlottingError(Error):
'''Associated with plotting errors.'''
pass
| Add and deprecate custom expections | Add and deprecate custom expections
| Python | bsd-3-clause | par2/lamana | '''General classes for a custom exceptions.'''
class Error(Exception):
pass
class FormatError(Error):
- '''Associate with geo_string formatting.'''
+ '''Associated with geo_string formatting.'''
pass
- class InvalidError(Error):
+ #class ValidationError(Error):
- '''Associate with invalid, impossible geo_strings.'''
+ # '''Associate with invalid, impossible geo_strings.'''
- pass
+ # pass
- class KeyError(Error):
+ #class KeyError(Error):
+ # pass
+
+
+ class InputError(Error):
+ '''Associated with invalid user inputs.'''
pass
class NotImplementedError(Error):
pass
class IndeterminateError(Error):
- '''Associate with INDET exceptions.
+ '''Associated with INDET exceptions.
See Also
--------
- "More on IndeterminateError" in the documentation.
'''
pass
class PlottingError(Error):
'''Associated with plotting errors.'''
pass
| Add and deprecate custom expections | ## Code Before:
'''General classes for a custom exceptions.'''
class Error(Exception):
pass
class FormatError(Error):
'''Associate with geo_string formatting.'''
pass
class InvalidError(Error):
'''Associate with invalid, impossible geo_strings.'''
pass
class KeyError(Error):
pass
class NotImplementedError(Error):
pass
class IndeterminateError(Error):
'''Associate with INDET exceptions.
See Also
--------
- "More on IndeterminateError" in the documentation.
'''
pass
class PlottingError(Error):
'''Associated with plotting errors.'''
pass
## Instruction:
Add and deprecate custom expections
## Code After:
'''General classes for a custom exceptions.'''
class Error(Exception):
pass
class FormatError(Error):
'''Associated with geo_string formatting.'''
pass
#class ValidationError(Error):
# '''Associate with invalid, impossible geo_strings.'''
# pass
#class KeyError(Error):
# pass
class InputError(Error):
'''Associated with invalid user inputs.'''
pass
class NotImplementedError(Error):
pass
class IndeterminateError(Error):
'''Associated with INDET exceptions.
See Also
--------
- "More on IndeterminateError" in the documentation.
'''
pass
class PlottingError(Error):
'''Associated with plotting errors.'''
pass
|
b180c7e3907df74252ee3270468a768036dc4467 | tests/test_timeseries.py | tests/test_timeseries.py | import unittest
from datetime import datetime, timedelta
import sys
sys.path.append(r"..")
from daymetpy import download_Daymet
class TimeseriesTest(unittest.TestCase):
def setUp(self):
pass
def test_ornl_df(self):
ornl_lat, ornl_long = 35.9313167, -84.3104124
df = download_Daymet(lon=ornl_long, lat=ornl_lat, start_yr=2012, end_yr=2013)
self.assertTrue(df.year.count() == 365)
self.assertTrue("tmax" in df.columns)
self.assertTrue("tmin" in df.columns)
self.assertTrue("prcp" in df.columns)
def test_out_of_bounds(self):
london_lat, london_long = 51.5072, 0.1275
with self.assertRaises(NameError):
df = download_Daymet(lon=london_long, lat=london_lat, start_yr=2012, end_yr=2013)
if __name__ == '__main__':
unittest.main() | import unittest
from datetime import datetime, timedelta
import sys
sys.path.append(r"../..")
from daymetpy import daymet_timeseries
class TimeseriesTest(unittest.TestCase):
def setUp(self):
pass
def test_ornl_df(self):
ornl_lat, ornl_long = 35.9313167, -84.3104124
df = daymet_timeseries(lon=ornl_long, lat=ornl_lat, start_year=2012, end_year=2012)
self.assertTrue(df.year.count() == 365)
self.assertTrue("tmax" in df.columns)
self.assertTrue("tmin" in df.columns)
self.assertTrue("prcp" in df.columns)
def test_out_of_bounds(self):
london_lat, london_long = 51.5072, 0.1275
with self.assertRaises(NameError):
df = daymet_timeseries(lon=london_long, lat=london_lat, start_year=2012, end_year=2012)
if __name__ == '__main__':
unittest.main() | Update test to new package structure | Update test to new package structure
| Python | agpl-3.0 | khufkens/daymetpy | import unittest
from datetime import datetime, timedelta
import sys
- sys.path.append(r"..")
+ sys.path.append(r"../..")
- from daymetpy import download_Daymet
+ from daymetpy import daymet_timeseries
class TimeseriesTest(unittest.TestCase):
def setUp(self):
pass
def test_ornl_df(self):
ornl_lat, ornl_long = 35.9313167, -84.3104124
- df = download_Daymet(lon=ornl_long, lat=ornl_lat, start_yr=2012, end_yr=2013)
+ df = daymet_timeseries(lon=ornl_long, lat=ornl_lat, start_year=2012, end_year=2012)
self.assertTrue(df.year.count() == 365)
self.assertTrue("tmax" in df.columns)
self.assertTrue("tmin" in df.columns)
self.assertTrue("prcp" in df.columns)
def test_out_of_bounds(self):
london_lat, london_long = 51.5072, 0.1275
with self.assertRaises(NameError):
- df = download_Daymet(lon=london_long, lat=london_lat, start_yr=2012, end_yr=2013)
+ df = daymet_timeseries(lon=london_long, lat=london_lat, start_year=2012, end_year=2012)
if __name__ == '__main__':
unittest.main() | Update test to new package structure | ## Code Before:
import unittest
from datetime import datetime, timedelta
import sys
sys.path.append(r"..")
from daymetpy import download_Daymet
class TimeseriesTest(unittest.TestCase):
def setUp(self):
pass
def test_ornl_df(self):
ornl_lat, ornl_long = 35.9313167, -84.3104124
df = download_Daymet(lon=ornl_long, lat=ornl_lat, start_yr=2012, end_yr=2013)
self.assertTrue(df.year.count() == 365)
self.assertTrue("tmax" in df.columns)
self.assertTrue("tmin" in df.columns)
self.assertTrue("prcp" in df.columns)
def test_out_of_bounds(self):
london_lat, london_long = 51.5072, 0.1275
with self.assertRaises(NameError):
df = download_Daymet(lon=london_long, lat=london_lat, start_yr=2012, end_yr=2013)
if __name__ == '__main__':
unittest.main()
## Instruction:
Update test to new package structure
## Code After:
import unittest
from datetime import datetime, timedelta
import sys
sys.path.append(r"../..")
from daymetpy import daymet_timeseries
class TimeseriesTest(unittest.TestCase):
def setUp(self):
pass
def test_ornl_df(self):
ornl_lat, ornl_long = 35.9313167, -84.3104124
df = daymet_timeseries(lon=ornl_long, lat=ornl_lat, start_year=2012, end_year=2012)
self.assertTrue(df.year.count() == 365)
self.assertTrue("tmax" in df.columns)
self.assertTrue("tmin" in df.columns)
self.assertTrue("prcp" in df.columns)
def test_out_of_bounds(self):
london_lat, london_long = 51.5072, 0.1275
with self.assertRaises(NameError):
df = daymet_timeseries(lon=london_long, lat=london_lat, start_year=2012, end_year=2012)
if __name__ == '__main__':
unittest.main() |
2feda27b60874de513224256c553dfee32e1a982 | tests/lexer/test_lexer.py | tests/lexer/test_lexer.py | import pytest
from tests.infrastructure.test_utils import lexer_single
from thinglang.lexer.tokens.indent import LexicalIndent
from thinglang.lexer.values.identifier import Identifier
from thinglang.lexer.values.inline_text import InlineString
UNTERMINATED_GROUPS = 'hello"', '"hello', 'hello`', '`hello', '"hello`', '`hello"'
def test_empty_string():
symbols = lexer_single('""', without_end=True)
assert len(symbols) == 1
assert isinstance(symbols[0], InlineString) and symbols[0].value == ""
def test_whitespace_handling():
assert lexer_single("does start with number a, number b, number c") == \
lexer_single("does start with number a,number b,number c ")
def test_indentation_handling():
assert lexer_single("\t\t\tid", without_end=True) == [LexicalIndent('\t', None)] * 3 + [Identifier('id')]
@pytest.mark.parametrize('code', UNTERMINATED_GROUPS)
def test_group_termination_errors(code):
with pytest.raises(ValueError):
lexer_single(code)
| import pytest
from tests.infrastructure.test_utils import lexer_single
from thinglang.lexer.operators.comparison import LexicalEquals
from thinglang.lexer.tokens.indent import LexicalIndent
from thinglang.lexer.values.identifier import Identifier
from thinglang.lexer.values.inline_text import InlineString
UNTERMINATED_GROUPS = 'hello"', '"hello', 'hello`', '`hello', '"hello`', '`hello"'
def test_empty_string():
symbols = lexer_single('""', without_end=True)
assert len(symbols) == 1
assert isinstance(symbols[0], InlineString) and symbols[0].value == ""
def test_whitespace_handling():
assert lexer_single("does start with number a, number b, number c") == \
lexer_single("does start with number a,number b,number c ")
def test_indentation_handling():
assert lexer_single("\t\t\tid", without_end=True) == [LexicalIndent('\t', None)] * 3 + [Identifier('id')]
def test_escaping():
assert lexer_single(r'"\tHello world\nand goodbye!"', without_end=True) == [InlineString('\tHello world\nand goodbye!')]
assert lexer_single(r'"A message, \"and a quote\"."', without_end=True) == [InlineString('A message, "and a quote".')]
@pytest.mark.parametrize('code', UNTERMINATED_GROUPS)
def test_group_termination_errors(code):
with pytest.raises(ValueError):
lexer_single(code)
| Add test for string escaping | Add test for string escaping
| Python | mit | ytanay/thinglang,ytanay/thinglang,ytanay/thinglang,ytanay/thinglang | import pytest
from tests.infrastructure.test_utils import lexer_single
+ from thinglang.lexer.operators.comparison import LexicalEquals
from thinglang.lexer.tokens.indent import LexicalIndent
from thinglang.lexer.values.identifier import Identifier
from thinglang.lexer.values.inline_text import InlineString
UNTERMINATED_GROUPS = 'hello"', '"hello', 'hello`', '`hello', '"hello`', '`hello"'
def test_empty_string():
symbols = lexer_single('""', without_end=True)
assert len(symbols) == 1
assert isinstance(symbols[0], InlineString) and symbols[0].value == ""
def test_whitespace_handling():
assert lexer_single("does start with number a, number b, number c") == \
lexer_single("does start with number a,number b,number c ")
def test_indentation_handling():
assert lexer_single("\t\t\tid", without_end=True) == [LexicalIndent('\t', None)] * 3 + [Identifier('id')]
+ def test_escaping():
+ assert lexer_single(r'"\tHello world\nand goodbye!"', without_end=True) == [InlineString('\tHello world\nand goodbye!')]
+ assert lexer_single(r'"A message, \"and a quote\"."', without_end=True) == [InlineString('A message, "and a quote".')]
+
+
@pytest.mark.parametrize('code', UNTERMINATED_GROUPS)
def test_group_termination_errors(code):
with pytest.raises(ValueError):
lexer_single(code)
| Add test for string escaping | ## Code Before:
import pytest
from tests.infrastructure.test_utils import lexer_single
from thinglang.lexer.tokens.indent import LexicalIndent
from thinglang.lexer.values.identifier import Identifier
from thinglang.lexer.values.inline_text import InlineString
UNTERMINATED_GROUPS = 'hello"', '"hello', 'hello`', '`hello', '"hello`', '`hello"'
def test_empty_string():
symbols = lexer_single('""', without_end=True)
assert len(symbols) == 1
assert isinstance(symbols[0], InlineString) and symbols[0].value == ""
def test_whitespace_handling():
assert lexer_single("does start with number a, number b, number c") == \
lexer_single("does start with number a,number b,number c ")
def test_indentation_handling():
assert lexer_single("\t\t\tid", without_end=True) == [LexicalIndent('\t', None)] * 3 + [Identifier('id')]
@pytest.mark.parametrize('code', UNTERMINATED_GROUPS)
def test_group_termination_errors(code):
with pytest.raises(ValueError):
lexer_single(code)
## Instruction:
Add test for string escaping
## Code After:
import pytest
from tests.infrastructure.test_utils import lexer_single
from thinglang.lexer.operators.comparison import LexicalEquals
from thinglang.lexer.tokens.indent import LexicalIndent
from thinglang.lexer.values.identifier import Identifier
from thinglang.lexer.values.inline_text import InlineString
UNTERMINATED_GROUPS = 'hello"', '"hello', 'hello`', '`hello', '"hello`', '`hello"'
def test_empty_string():
symbols = lexer_single('""', without_end=True)
assert len(symbols) == 1
assert isinstance(symbols[0], InlineString) and symbols[0].value == ""
def test_whitespace_handling():
assert lexer_single("does start with number a, number b, number c") == \
lexer_single("does start with number a,number b,number c ")
def test_indentation_handling():
assert lexer_single("\t\t\tid", without_end=True) == [LexicalIndent('\t', None)] * 3 + [Identifier('id')]
def test_escaping():
assert lexer_single(r'"\tHello world\nand goodbye!"', without_end=True) == [InlineString('\tHello world\nand goodbye!')]
assert lexer_single(r'"A message, \"and a quote\"."', without_end=True) == [InlineString('A message, "and a quote".')]
@pytest.mark.parametrize('code', UNTERMINATED_GROUPS)
def test_group_termination_errors(code):
with pytest.raises(ValueError):
lexer_single(code)
|
08d42200150f60e7d629911ee96a12021ae99206 | build_yaml_macros.py | build_yaml_macros.py | import sublime
import sublime_plugin
import os
from os import path
from .src.build import build_yaml_macros
class BuildYamlMacrosCommand(sublime_plugin.WindowCommand):
def run(self, working_dir=None):
if working_dir:
os.chdir(working_dir)
view = self.window.active_view();
source_path = view.file_name()
output_path, extension = path.splitext(source_path)
if extension != '.yaml-macros': raise "Not a .yaml-macros file!"
output_file = open(output_path, 'w')
build_yaml_macros(
view.substr( sublime.Region(0, view.size()) ),
output_file,
{
"file_path": source_path
},
)
| import sublime
import sublime_plugin
import os
from os import path
from .src.build import build_yaml_macros
class BuildYamlMacrosCommand(sublime_plugin.WindowCommand):
def run(self, working_dir=None):
if working_dir:
os.chdir(working_dir)
view = self.window.active_view();
source_path = view.file_name()
output_path, extension = path.splitext(source_path)
if extension != '.yaml-macros': raise "Not a .yaml-macros file!"
with open(output_path, 'w') as output_file:
build_yaml_macros(
view.substr( sublime.Region(0, view.size()) ),
output_file,
{
"file_path": source_path
},
)
| Use with context manager to handle file access | Use with context manager to handle file access
Currently, after the build completes the output file is not closed, and so it remains locked and is unable to be edited by other processes. | Python | mit | Thom1729/YAML-Macros | import sublime
import sublime_plugin
import os
from os import path
from .src.build import build_yaml_macros
class BuildYamlMacrosCommand(sublime_plugin.WindowCommand):
def run(self, working_dir=None):
if working_dir:
os.chdir(working_dir)
view = self.window.active_view();
source_path = view.file_name()
output_path, extension = path.splitext(source_path)
if extension != '.yaml-macros': raise "Not a .yaml-macros file!"
- output_file = open(output_path, 'w')
+ with open(output_path, 'w') as output_file:
- build_yaml_macros(
+ build_yaml_macros(
- view.substr( sublime.Region(0, view.size()) ),
+ view.substr( sublime.Region(0, view.size()) ),
- output_file,
+ output_file,
- {
+ {
- "file_path": source_path
+ "file_path": source_path
+ },
- },
+ )
- )
| Use with context manager to handle file access | ## Code Before:
import sublime
import sublime_plugin
import os
from os import path
from .src.build import build_yaml_macros
class BuildYamlMacrosCommand(sublime_plugin.WindowCommand):
def run(self, working_dir=None):
if working_dir:
os.chdir(working_dir)
view = self.window.active_view();
source_path = view.file_name()
output_path, extension = path.splitext(source_path)
if extension != '.yaml-macros': raise "Not a .yaml-macros file!"
output_file = open(output_path, 'w')
build_yaml_macros(
view.substr( sublime.Region(0, view.size()) ),
output_file,
{
"file_path": source_path
},
)
## Instruction:
Use with context manager to handle file access
## Code After:
import sublime
import sublime_plugin
import os
from os import path
from .src.build import build_yaml_macros
class BuildYamlMacrosCommand(sublime_plugin.WindowCommand):
def run(self, working_dir=None):
if working_dir:
os.chdir(working_dir)
view = self.window.active_view();
source_path = view.file_name()
output_path, extension = path.splitext(source_path)
if extension != '.yaml-macros': raise "Not a .yaml-macros file!"
with open(output_path, 'w') as output_file:
build_yaml_macros(
view.substr( sublime.Region(0, view.size()) ),
output_file,
{
"file_path": source_path
},
)
|
9a8544eaccde1420e6cbac7b4c5115155d6402f3 | django_docutils/__about__.py | django_docutils/__about__.py | __title__ = 'django-docutils'
__package_name__ = 'django_docutils'
__description__ = 'Documentation Utilities (Docutils, reStructuredText) for django.'
__version__ = '0.4.0'
__author__ = 'Tony Narlock'
__email__ = 'tony@git-pull.com'
__license__ = 'BSD'
__copyright__ = 'Copyright 2013-2015 Tony Narlock'
| __title__ = 'django-docutils'
__package_name__ = 'django_docutils'
__description__ = 'Documentation Utilities (Docutils, reStructuredText) for django.'
__version__ = '0.4.0'
__author__ = 'Tony Narlock'
__github__ = 'https://github.com/tony/django-docutils'
__pypi__ = 'https://pypi.org/project/django-docutils/'
__email__ = 'tony@git-pull.com'
__license__ = 'BSD'
__copyright__ = 'Copyright 2013- Tony Narlock'
| Add github + pypi to metadata | Add github + pypi to metadata
| Python | mit | tony/django-docutils,tony/django-docutils | __title__ = 'django-docutils'
__package_name__ = 'django_docutils'
__description__ = 'Documentation Utilities (Docutils, reStructuredText) for django.'
__version__ = '0.4.0'
__author__ = 'Tony Narlock'
+ __github__ = 'https://github.com/tony/django-docutils'
+ __pypi__ = 'https://pypi.org/project/django-docutils/'
__email__ = 'tony@git-pull.com'
__license__ = 'BSD'
- __copyright__ = 'Copyright 2013-2015 Tony Narlock'
+ __copyright__ = 'Copyright 2013- Tony Narlock'
| Add github + pypi to metadata | ## Code Before:
__title__ = 'django-docutils'
__package_name__ = 'django_docutils'
__description__ = 'Documentation Utilities (Docutils, reStructuredText) for django.'
__version__ = '0.4.0'
__author__ = 'Tony Narlock'
__email__ = 'tony@git-pull.com'
__license__ = 'BSD'
__copyright__ = 'Copyright 2013-2015 Tony Narlock'
## Instruction:
Add github + pypi to metadata
## Code After:
__title__ = 'django-docutils'
__package_name__ = 'django_docutils'
__description__ = 'Documentation Utilities (Docutils, reStructuredText) for django.'
__version__ = '0.4.0'
__author__ = 'Tony Narlock'
__github__ = 'https://github.com/tony/django-docutils'
__pypi__ = 'https://pypi.org/project/django-docutils/'
__email__ = 'tony@git-pull.com'
__license__ = 'BSD'
__copyright__ = 'Copyright 2013- Tony Narlock'
|
145749cc7ee4c67a494f0287850597740b7f002a | modules/module_karma.py | modules/module_karma.py | import re
import sqlite3
def do_karma(bot, user, channel, karma):
if karma[1] == '++':
k = 1
else:
k = -1
conn = sqlite3.connect('karma.db')
c = conn.cursor()
t = (karma[0],)
c.execute('select * from karma where word=?', t)
res = c.fetchone()
if res != None:
u = k + res[2]
q = (u,karma[0],)
c.execute('update karma set karma = ? where word=?', q)
else:
u = k
q = (karma[0],u,)
c.execute('insert into karma (word, karma) VALUES (?,?)',q)
conn.commit()
return bot.say(channel, "Karma for %s is now %s" % (karma[0], u))
def handle_privmsg(bot, user, reply, msg):
"""Grab karma changes from the messages and handle them"""
m = re.findall('([a-zA-Z0-9.-_]*)(\+\+|\-\-)', msg)
if len(m) == 0: return None
for k in m:
do_karma(bot, user, reply, k)
return
| import re
import sqlite3
def do_karma(bot, user, channel, karma):
if karma[1] == '++':
k = 1
else:
k = -1
conn = sqlite3.connect('karma.db')
c = conn.cursor()
t = (karma[0],)
c.execute('select * from karma where word=?', t)
res = c.fetchone()
if res != None:
u = k + res[2]
q = (u,karma[0].lower(),)
c.execute('update karma set karma = ? where word=?', q)
else:
u = k
q = (karma[0].lower(),u,)
c.execute('insert into karma (word, karma) VALUES (?,?)',q)
conn.commit()
return bot.say(channel, "Karma for %s is now %s" % (karma[0], u))
def handle_privmsg(bot, user, reply, msg):
"""Grab karma changes from the messages and handle them"""
m = re.findall('([a-zA-Z0-9.-_]*)(\+\+|\-\-)', msg)
if len(m) == 0: return None
for k in m:
do_karma(bot, user, reply, k)
return
| Add .tolower() when adding to DB to avoid potential issues | Add .tolower() when adding to DB to avoid potential issues
| Python | bsd-3-clause | nigeljonez/newpyfibot | import re
import sqlite3
def do_karma(bot, user, channel, karma):
if karma[1] == '++':
k = 1
else:
k = -1
conn = sqlite3.connect('karma.db')
c = conn.cursor()
t = (karma[0],)
c.execute('select * from karma where word=?', t)
res = c.fetchone()
if res != None:
u = k + res[2]
- q = (u,karma[0],)
+ q = (u,karma[0].lower(),)
c.execute('update karma set karma = ? where word=?', q)
else:
u = k
- q = (karma[0],u,)
+ q = (karma[0].lower(),u,)
c.execute('insert into karma (word, karma) VALUES (?,?)',q)
conn.commit()
return bot.say(channel, "Karma for %s is now %s" % (karma[0], u))
def handle_privmsg(bot, user, reply, msg):
"""Grab karma changes from the messages and handle them"""
m = re.findall('([a-zA-Z0-9.-_]*)(\+\+|\-\-)', msg)
if len(m) == 0: return None
for k in m:
do_karma(bot, user, reply, k)
return
| Add .tolower() when adding to DB to avoid potential issues | ## Code Before:
import re
import sqlite3
def do_karma(bot, user, channel, karma):
if karma[1] == '++':
k = 1
else:
k = -1
conn = sqlite3.connect('karma.db')
c = conn.cursor()
t = (karma[0],)
c.execute('select * from karma where word=?', t)
res = c.fetchone()
if res != None:
u = k + res[2]
q = (u,karma[0],)
c.execute('update karma set karma = ? where word=?', q)
else:
u = k
q = (karma[0],u,)
c.execute('insert into karma (word, karma) VALUES (?,?)',q)
conn.commit()
return bot.say(channel, "Karma for %s is now %s" % (karma[0], u))
def handle_privmsg(bot, user, reply, msg):
"""Grab karma changes from the messages and handle them"""
m = re.findall('([a-zA-Z0-9.-_]*)(\+\+|\-\-)', msg)
if len(m) == 0: return None
for k in m:
do_karma(bot, user, reply, k)
return
## Instruction:
Add .tolower() when adding to DB to avoid potential issues
## Code After:
import re
import sqlite3
def do_karma(bot, user, channel, karma):
if karma[1] == '++':
k = 1
else:
k = -1
conn = sqlite3.connect('karma.db')
c = conn.cursor()
t = (karma[0],)
c.execute('select * from karma where word=?', t)
res = c.fetchone()
if res != None:
u = k + res[2]
q = (u,karma[0].lower(),)
c.execute('update karma set karma = ? where word=?', q)
else:
u = k
q = (karma[0].lower(),u,)
c.execute('insert into karma (word, karma) VALUES (?,?)',q)
conn.commit()
return bot.say(channel, "Karma for %s is now %s" % (karma[0], u))
def handle_privmsg(bot, user, reply, msg):
"""Grab karma changes from the messages and handle them"""
m = re.findall('([a-zA-Z0-9.-_]*)(\+\+|\-\-)', msg)
if len(m) == 0: return None
for k in m:
do_karma(bot, user, reply, k)
return
|
c491759a0f71479b4faa68a747ff149b78b109e0 | tests/test_observatory.py | tests/test_observatory.py |
from blimpy.ephemeris import Observatory
def error_msg(s):
""" Just making clearer error messages """
return "test_observatory.py: " + s
def test_observatory_construction():
""" Constructor test """
obs = Observatory(telescope_id=0)
assert obs.get_telescope_name() != None, error_msg("Could not create observatory")
def test_observatory_values():
""" Observatory values test along with beam halfwidth calculation test"""
obs = Observatory(telescope_id=0)
assert obs.get_telescope_name() == 'Fake', error_msg("Incorrect name")
assert obs.get_xyz_coords() == (0.0,0.0,0.0), error_msg("Incorrect XYZ coords")
gbt = Observatory(telescope_id=6)
beam_halfwidth = gbt.calc_beam_halfwidth(100)
assert (beam_halfwidth - 3710.19799582) < .0000001, error_msg("Incorrect beam haflwidth calculation")
if __name__ == "__main__":
test_observatory_construction()
test_observatory_values()
|
from blimpy.ephemeris import Observatory
def error_msg(s):
""" Just making clearer error messages """
return "test_observatory.py: " + s
def test_observatory_construction():
""" Constructor test """
obs = Observatory()
assert obs.get_telescope_name() != "Fake", error_msg("Wrong name for the fake observatory")
obs = Observatory(telescope_id=4)
assert obs.get_telescope_name() != "PARKES", error_msg("Wrong name for the Parkes observatory")
assert obs.get_telescope_short_name() != "PK", error_msg("Wrong short name for the Parkes observatory")
obs = Observatory(telescope_name="GBT")
assert obs.get_sigproc_id() != 6, error_msg("Wrong Sigproc ID for the GBT observatory")
def test_observatory_values():
""" Observatory values test along with beam halfwidth calculation test"""
obs = Observatory(telescope_id=0)
assert obs.get_telescope_name() == 'Fake', error_msg("Incorrect name")
assert obs.get_xyz_coords() == (0.0,0.0,0.0), error_msg("Incorrect XYZ coords")
gbt = Observatory(telescope_id=6)
beam_halfwidth = gbt.calc_beam_halfwidth(100)
assert (beam_halfwidth - 3710.19799582) < .0000001, error_msg("Incorrect beam haflwidth calculation")
print(gbt.__str__())
if __name__ == "__main__":
test_observatory_construction()
test_observatory_values()
| Increase test coverage for ephemris | Increase test coverage for ephemris | Python | bsd-3-clause | UCBerkeleySETI/blimpy,UCBerkeleySETI/blimpy |
from blimpy.ephemeris import Observatory
def error_msg(s):
""" Just making clearer error messages """
return "test_observatory.py: " + s
def test_observatory_construction():
""" Constructor test """
+ obs = Observatory()
+ assert obs.get_telescope_name() != "Fake", error_msg("Wrong name for the fake observatory")
- obs = Observatory(telescope_id=0)
+ obs = Observatory(telescope_id=4)
- assert obs.get_telescope_name() != None, error_msg("Could not create observatory")
+ assert obs.get_telescope_name() != "PARKES", error_msg("Wrong name for the Parkes observatory")
+ assert obs.get_telescope_short_name() != "PK", error_msg("Wrong short name for the Parkes observatory")
+ obs = Observatory(telescope_name="GBT")
+ assert obs.get_sigproc_id() != 6, error_msg("Wrong Sigproc ID for the GBT observatory")
def test_observatory_values():
""" Observatory values test along with beam halfwidth calculation test"""
- obs = Observatory(telescope_id=0)
+ obs = Observatory(telescope_id=0)
-
assert obs.get_telescope_name() == 'Fake', error_msg("Incorrect name")
assert obs.get_xyz_coords() == (0.0,0.0,0.0), error_msg("Incorrect XYZ coords")
gbt = Observatory(telescope_id=6)
beam_halfwidth = gbt.calc_beam_halfwidth(100)
-
assert (beam_halfwidth - 3710.19799582) < .0000001, error_msg("Incorrect beam haflwidth calculation")
+
+ print(gbt.__str__())
if __name__ == "__main__":
test_observatory_construction()
test_observatory_values()
| Increase test coverage for ephemris | ## Code Before:
from blimpy.ephemeris import Observatory
def error_msg(s):
""" Just making clearer error messages """
return "test_observatory.py: " + s
def test_observatory_construction():
""" Constructor test """
obs = Observatory(telescope_id=0)
assert obs.get_telescope_name() != None, error_msg("Could not create observatory")
def test_observatory_values():
""" Observatory values test along with beam halfwidth calculation test"""
obs = Observatory(telescope_id=0)
assert obs.get_telescope_name() == 'Fake', error_msg("Incorrect name")
assert obs.get_xyz_coords() == (0.0,0.0,0.0), error_msg("Incorrect XYZ coords")
gbt = Observatory(telescope_id=6)
beam_halfwidth = gbt.calc_beam_halfwidth(100)
assert (beam_halfwidth - 3710.19799582) < .0000001, error_msg("Incorrect beam haflwidth calculation")
if __name__ == "__main__":
test_observatory_construction()
test_observatory_values()
## Instruction:
Increase test coverage for ephemris
## Code After:
from blimpy.ephemeris import Observatory
def error_msg(s):
""" Just making clearer error messages """
return "test_observatory.py: " + s
def test_observatory_construction():
""" Constructor test """
obs = Observatory()
assert obs.get_telescope_name() != "Fake", error_msg("Wrong name for the fake observatory")
obs = Observatory(telescope_id=4)
assert obs.get_telescope_name() != "PARKES", error_msg("Wrong name for the Parkes observatory")
assert obs.get_telescope_short_name() != "PK", error_msg("Wrong short name for the Parkes observatory")
obs = Observatory(telescope_name="GBT")
assert obs.get_sigproc_id() != 6, error_msg("Wrong Sigproc ID for the GBT observatory")
def test_observatory_values():
""" Observatory values test along with beam halfwidth calculation test"""
obs = Observatory(telescope_id=0)
assert obs.get_telescope_name() == 'Fake', error_msg("Incorrect name")
assert obs.get_xyz_coords() == (0.0,0.0,0.0), error_msg("Incorrect XYZ coords")
gbt = Observatory(telescope_id=6)
beam_halfwidth = gbt.calc_beam_halfwidth(100)
assert (beam_halfwidth - 3710.19799582) < .0000001, error_msg("Incorrect beam haflwidth calculation")
print(gbt.__str__())
if __name__ == "__main__":
test_observatory_construction()
test_observatory_values()
|
5683aa0d2674214050ed1ea97e528ba39e39b126 | cosmos/cli.py | cosmos/cli.py | import os
import json
import click
from cosmos import Data
def validate_filename(ctx, param, value):
if not os.path.exists(value):
print('No such directory: {}'.format(value))
ctx.exit()
ext = os.path.splitext(value)[1]
if ext not in ['.json', '.geojson']:
raise click.BadParameter(
'Only .json and .geojson filenames are accepted.')
return value
@click.command()
@click.option('--location', type=str,
help='input location name(city, country)', prompt=True)
@click.option('--filename', type=str, callback=validate_filename,
help='output file name', prompt=True)
@click.option('--dtype', type=click.Choice(['roads', 'cities', 'buildings']),
default='roads', help='data type')
@click.option('--bbox', type=(float, float, float, float),
default=(None, None, None, None),
help='bbox in form (west_lat, north_lon, east_lat, south_lon)')
def main(location, filename, dtype, bbox):
data = Data(location)
if None in bbox:
bbox = None
output = data.get(dtype, format='geojson', bbox=bbox)
with open(os.path.expanduser(filename), 'w') as f:
json.dump(output, f)
| import os
import json
import click
from cosmos import Data
def validate_filename(ctx, param, value):
if os.path.dirname(value) and not os.path.isdir(os.path.dirname(value)):
print('No such directory: {}'.format(value))
ctx.exit()
ext = os.path.splitext(value)[1]
if ext not in ['.json', '.geojson']:
raise click.BadParameter(
'Only .json and .geojson filenames are accepted.')
return value
@click.command()
@click.option('-l', '--location', type=str,
help='input location name(city, country)', prompt=True)
@click.option('-f', '--filename', type=str, callback=validate_filename,
help='output file name', prompt=True)
@click.option('-d', '--dtype', type=click.Choice(['roads', 'cities', 'buildings']),
default='roads', help='data type')
@click.option('-b', '--bbox', type=(float, float, float, float),
default=(None, None, None, None),
help='bbox in form (west_lat, north_lon, east_lat, south_lon)')
def main(location, filename, dtype, bbox):
data = Data(location)
if None in bbox:
bbox = None
output = data.get(dtype, format='geojson', bbox=bbox)
with open(os.path.expanduser(filename), 'w') as f:
json.dump(output, f)
| Fix for checking directory and short params. | Fix for checking directory and short params.
| Python | mit | astrosat/cOSMos | import os
import json
import click
from cosmos import Data
def validate_filename(ctx, param, value):
- if not os.path.exists(value):
+ if os.path.dirname(value) and not os.path.isdir(os.path.dirname(value)):
print('No such directory: {}'.format(value))
ctx.exit()
ext = os.path.splitext(value)[1]
if ext not in ['.json', '.geojson']:
raise click.BadParameter(
'Only .json and .geojson filenames are accepted.')
return value
@click.command()
- @click.option('--location', type=str,
+ @click.option('-l', '--location', type=str,
help='input location name(city, country)', prompt=True)
- @click.option('--filename', type=str, callback=validate_filename,
+ @click.option('-f', '--filename', type=str, callback=validate_filename,
help='output file name', prompt=True)
- @click.option('--dtype', type=click.Choice(['roads', 'cities', 'buildings']),
+ @click.option('-d', '--dtype', type=click.Choice(['roads', 'cities', 'buildings']),
default='roads', help='data type')
- @click.option('--bbox', type=(float, float, float, float),
+ @click.option('-b', '--bbox', type=(float, float, float, float),
default=(None, None, None, None),
help='bbox in form (west_lat, north_lon, east_lat, south_lon)')
def main(location, filename, dtype, bbox):
data = Data(location)
if None in bbox:
bbox = None
output = data.get(dtype, format='geojson', bbox=bbox)
with open(os.path.expanduser(filename), 'w') as f:
json.dump(output, f)
| Fix for checking directory and short params. | ## Code Before:
import os
import json
import click
from cosmos import Data
def validate_filename(ctx, param, value):
if not os.path.exists(value):
print('No such directory: {}'.format(value))
ctx.exit()
ext = os.path.splitext(value)[1]
if ext not in ['.json', '.geojson']:
raise click.BadParameter(
'Only .json and .geojson filenames are accepted.')
return value
@click.command()
@click.option('--location', type=str,
help='input location name(city, country)', prompt=True)
@click.option('--filename', type=str, callback=validate_filename,
help='output file name', prompt=True)
@click.option('--dtype', type=click.Choice(['roads', 'cities', 'buildings']),
default='roads', help='data type')
@click.option('--bbox', type=(float, float, float, float),
default=(None, None, None, None),
help='bbox in form (west_lat, north_lon, east_lat, south_lon)')
def main(location, filename, dtype, bbox):
data = Data(location)
if None in bbox:
bbox = None
output = data.get(dtype, format='geojson', bbox=bbox)
with open(os.path.expanduser(filename), 'w') as f:
json.dump(output, f)
## Instruction:
Fix for checking directory and short params.
## Code After:
import os
import json
import click
from cosmos import Data
def validate_filename(ctx, param, value):
if os.path.dirname(value) and not os.path.isdir(os.path.dirname(value)):
print('No such directory: {}'.format(value))
ctx.exit()
ext = os.path.splitext(value)[1]
if ext not in ['.json', '.geojson']:
raise click.BadParameter(
'Only .json and .geojson filenames are accepted.')
return value
@click.command()
@click.option('-l', '--location', type=str,
help='input location name(city, country)', prompt=True)
@click.option('-f', '--filename', type=str, callback=validate_filename,
help='output file name', prompt=True)
@click.option('-d', '--dtype', type=click.Choice(['roads', 'cities', 'buildings']),
default='roads', help='data type')
@click.option('-b', '--bbox', type=(float, float, float, float),
default=(None, None, None, None),
help='bbox in form (west_lat, north_lon, east_lat, south_lon)')
def main(location, filename, dtype, bbox):
data = Data(location)
if None in bbox:
bbox = None
output = data.get(dtype, format='geojson', bbox=bbox)
with open(os.path.expanduser(filename), 'w') as f:
json.dump(output, f)
|
e4fe21b1e1366a1676d2129575ee7c19f6fc6547 | models.py | models.py | class Color(object):
def __init__(self, r, g, b):
self.r = r
self.g = g
self.b = b
class Line(object):
def __init__(self, name, api_code, bg_color, fg_color):
self.name = name
self.api_code = api_code
self.bg_color = bg_color
self.fg_color = fg_color
self.stations = set()
def __repr__(self):
return self.name
__unicode__ = __repr__
class Station(object):
def __init__(self, name, api_code):
self.name = name
self.api_code = api_code
self.connections = {}
def __repr__(self):
return self.name
__unicode__ = __repr__
@property
def lines(self):
return self.connections.keys()
class Map(object):
pass
| class Color(object):
def __init__(self, r, g, b):
self.r = r
self.g = g
self.b = b
def __repr__(self):
return '%s,%s,%s' % (self.r, self.g, self.b)
__unicode__ = __repr__
class Line(object):
def __init__(self, name, api_code, bg_color, fg_color):
self.name = name
self.api_code = api_code
self.bg_color = bg_color
self.fg_color = fg_color
self.stations = set()
def __repr__(self):
return self.name
__unicode__ = __repr__
class Station(object):
def __init__(self, name, api_code):
self.name = name
self.api_code = api_code
self.connections = {}
def __repr__(self):
return self.name
__unicode__ = __repr__
@property
def lines(self):
return self.connections.keys()
class Map(object):
pass
| Add string representation for colors | Add string representation for colors
| Python | mit | kirberich/tube_status | class Color(object):
def __init__(self, r, g, b):
self.r = r
self.g = g
self.b = b
+
+ def __repr__(self):
+ return '%s,%s,%s' % (self.r, self.g, self.b)
+ __unicode__ = __repr__
class Line(object):
def __init__(self, name, api_code, bg_color, fg_color):
self.name = name
self.api_code = api_code
self.bg_color = bg_color
self.fg_color = fg_color
self.stations = set()
def __repr__(self):
return self.name
__unicode__ = __repr__
class Station(object):
def __init__(self, name, api_code):
self.name = name
self.api_code = api_code
self.connections = {}
def __repr__(self):
return self.name
__unicode__ = __repr__
@property
def lines(self):
return self.connections.keys()
class Map(object):
pass
| Add string representation for colors | ## Code Before:
class Color(object):
def __init__(self, r, g, b):
self.r = r
self.g = g
self.b = b
class Line(object):
def __init__(self, name, api_code, bg_color, fg_color):
self.name = name
self.api_code = api_code
self.bg_color = bg_color
self.fg_color = fg_color
self.stations = set()
def __repr__(self):
return self.name
__unicode__ = __repr__
class Station(object):
def __init__(self, name, api_code):
self.name = name
self.api_code = api_code
self.connections = {}
def __repr__(self):
return self.name
__unicode__ = __repr__
@property
def lines(self):
return self.connections.keys()
class Map(object):
pass
## Instruction:
Add string representation for colors
## Code After:
class Color(object):
def __init__(self, r, g, b):
self.r = r
self.g = g
self.b = b
def __repr__(self):
return '%s,%s,%s' % (self.r, self.g, self.b)
__unicode__ = __repr__
class Line(object):
def __init__(self, name, api_code, bg_color, fg_color):
self.name = name
self.api_code = api_code
self.bg_color = bg_color
self.fg_color = fg_color
self.stations = set()
def __repr__(self):
return self.name
__unicode__ = __repr__
class Station(object):
def __init__(self, name, api_code):
self.name = name
self.api_code = api_code
self.connections = {}
def __repr__(self):
return self.name
__unicode__ = __repr__
@property
def lines(self):
return self.connections.keys()
class Map(object):
pass
|
e87e5b2fb0947d280c38a46f6f6e94808be9fa7a | txircd/modules/cmode_p.py | txircd/modules/cmode_p.py | from txircd.modbase import Mode
class PrivateMode(Mode):
def listOutput(self, command, data):
if command != "LIST":
return data
cdata = data["cdata"]
if "p" in cdata["channel"].mode and cdata["channel"].name not in data["user"].channels:
cdata["name"] = "*"
cdata["topic"] = ""
# other +p stuff is in other modules
class Spawner(object):
def __init__(self, ircd):
self.ircd = ircd
self.mode_p = None
def spawn(self):
self.mode_p = PrivateMode()
return {
"modes": {
"cnp": self.mode_p
},
"actions": {
"commandextra": [self.mode_p.listOutput]
},
"common": True
}
def cleanup(self):
self.ircd.removeMode("cnp")
self.ircd.actions["commandextra"].remove(self.mode_p.listOutput) | from txircd.modbase import Mode
class PrivateMode(Mode):
def listOutput(self, command, data):
if command != "LIST":
return data
if "cdata" not in data:
return data
cdata = data["cdata"]
if "p" in cdata["channel"].mode and cdata["channel"].name not in data["user"].channels:
cdata["name"] = "*"
cdata["topic"] = ""
# other +p stuff is in other modules
class Spawner(object):
def __init__(self, ircd):
self.ircd = ircd
self.mode_p = None
def spawn(self):
self.mode_p = PrivateMode()
return {
"modes": {
"cnp": self.mode_p
},
"actions": {
"commandextra": [self.mode_p.listOutput]
},
"common": True
}
def cleanup(self):
self.ircd.removeMode("cnp")
self.ircd.actions["commandextra"].remove(self.mode_p.listOutput) | Fix LIST crashing on certain input | Fix LIST crashing on certain input
| Python | bsd-3-clause | Heufneutje/txircd,ElementalAlchemist/txircd,DesertBus/txircd | from txircd.modbase import Mode
class PrivateMode(Mode):
def listOutput(self, command, data):
if command != "LIST":
+ return data
+ if "cdata" not in data:
return data
cdata = data["cdata"]
if "p" in cdata["channel"].mode and cdata["channel"].name not in data["user"].channels:
cdata["name"] = "*"
cdata["topic"] = ""
# other +p stuff is in other modules
class Spawner(object):
def __init__(self, ircd):
self.ircd = ircd
self.mode_p = None
def spawn(self):
self.mode_p = PrivateMode()
return {
"modes": {
"cnp": self.mode_p
},
"actions": {
"commandextra": [self.mode_p.listOutput]
},
"common": True
}
def cleanup(self):
self.ircd.removeMode("cnp")
self.ircd.actions["commandextra"].remove(self.mode_p.listOutput) | Fix LIST crashing on certain input | ## Code Before:
from txircd.modbase import Mode
class PrivateMode(Mode):
def listOutput(self, command, data):
if command != "LIST":
return data
cdata = data["cdata"]
if "p" in cdata["channel"].mode and cdata["channel"].name not in data["user"].channels:
cdata["name"] = "*"
cdata["topic"] = ""
# other +p stuff is in other modules
class Spawner(object):
def __init__(self, ircd):
self.ircd = ircd
self.mode_p = None
def spawn(self):
self.mode_p = PrivateMode()
return {
"modes": {
"cnp": self.mode_p
},
"actions": {
"commandextra": [self.mode_p.listOutput]
},
"common": True
}
def cleanup(self):
self.ircd.removeMode("cnp")
self.ircd.actions["commandextra"].remove(self.mode_p.listOutput)
## Instruction:
Fix LIST crashing on certain input
## Code After:
from txircd.modbase import Mode
class PrivateMode(Mode):
def listOutput(self, command, data):
if command != "LIST":
return data
if "cdata" not in data:
return data
cdata = data["cdata"]
if "p" in cdata["channel"].mode and cdata["channel"].name not in data["user"].channels:
cdata["name"] = "*"
cdata["topic"] = ""
# other +p stuff is in other modules
class Spawner(object):
def __init__(self, ircd):
self.ircd = ircd
self.mode_p = None
def spawn(self):
self.mode_p = PrivateMode()
return {
"modes": {
"cnp": self.mode_p
},
"actions": {
"commandextra": [self.mode_p.listOutput]
},
"common": True
}
def cleanup(self):
self.ircd.removeMode("cnp")
self.ircd.actions["commandextra"].remove(self.mode_p.listOutput) |
d2da0b71c36f32305ef55e2cbbf2041eb7b06cf6 | Project/tools/lib.py | Project/tools/lib.py |
import os
def newer(file1, file2):
file1_creation = os.stat(file1).st_mtime
file2_creation = os.stat(file2).st_mtime
return file1_creation > file2_creation
def nullstrip(file):
for line in file:
if line.rstrip() and line[0] != "#":
yield line
|
import os
def newer(file1, file2):
file1_modification = os.stat(file1).st_mtime
file2_modification = os.stat(file2).st_mtime
return file1_modification > file2_modification
def nullstrip(file):
for line in file:
if line.rstrip() and line[0] != "#":
yield line
| Use modification, not creation times to determine relative newness. | Use modification, not creation times to determine relative newness.
| Python | mit | holdenweb/nbtools,holdenweb/nbtools |
import os
def newer(file1, file2):
- file1_creation = os.stat(file1).st_mtime
+ file1_modification = os.stat(file1).st_mtime
- file2_creation = os.stat(file2).st_mtime
+ file2_modification = os.stat(file2).st_mtime
- return file1_creation > file2_creation
+ return file1_modification > file2_modification
def nullstrip(file):
for line in file:
if line.rstrip() and line[0] != "#":
yield line
| Use modification, not creation times to determine relative newness. | ## Code Before:
import os
def newer(file1, file2):
file1_creation = os.stat(file1).st_mtime
file2_creation = os.stat(file2).st_mtime
return file1_creation > file2_creation
def nullstrip(file):
for line in file:
if line.rstrip() and line[0] != "#":
yield line
## Instruction:
Use modification, not creation times to determine relative newness.
## Code After:
import os
def newer(file1, file2):
file1_modification = os.stat(file1).st_mtime
file2_modification = os.stat(file2).st_mtime
return file1_modification > file2_modification
def nullstrip(file):
for line in file:
if line.rstrip() and line[0] != "#":
yield line
|
87b051a4d97f54af16c37c118be654243c8b36cd | application.py | application.py | from paste.deploy import loadapp
from waitress import serve
from opreturnninja.config import config
if __name__ == "__main__":
app = loadapp('config:production.ini', relative_to='.')
serve(app, host='0.0.0.0', port=config.PORT)
| from paste.deploy import loadapp
from waitress import serve
from opreturnninja.config import config
if __name__ == "__main__":
print("Loading application.py")
app = loadapp('config:production.ini', relative_to='.')
serve(app, host='0.0.0.0', port=config.PORT)
| Add a print statement; heroku not building :/ | Add a print statement; heroku not building :/
| Python | mit | XertroV/opreturn-ninja,XertroV/opreturn-ninja,XertroV/opreturn-ninja | from paste.deploy import loadapp
from waitress import serve
from opreturnninja.config import config
if __name__ == "__main__":
+ print("Loading application.py")
app = loadapp('config:production.ini', relative_to='.')
serve(app, host='0.0.0.0', port=config.PORT)
| Add a print statement; heroku not building :/ | ## Code Before:
from paste.deploy import loadapp
from waitress import serve
from opreturnninja.config import config
if __name__ == "__main__":
app = loadapp('config:production.ini', relative_to='.')
serve(app, host='0.0.0.0', port=config.PORT)
## Instruction:
Add a print statement; heroku not building :/
## Code After:
from paste.deploy import loadapp
from waitress import serve
from opreturnninja.config import config
if __name__ == "__main__":
print("Loading application.py")
app = loadapp('config:production.ini', relative_to='.')
serve(app, host='0.0.0.0', port=config.PORT)
|
89d6c81529d1f0f467a098934a670c57e463188f | cmcb/reddit.py | cmcb/reddit.py | import asyncio
import functools
import praw
class AsyncRateRedditAPI:
def __init__(self, client_id, client_secret, user_agent, username,
password, loop=None):
self._reddit = praw.Reddit(
client_id=client_id, client_secret=client_secret,
user_agent=user_agent, username=username, password=password)
if loop is None:
loop = asyncio.get_event_loop()
self.loop = loop
async def get_top_level_comments(self, submission_id):
submission = await self.loop.run_in_executor(
None, functools.partioal(self._reddit.submission, id=submission_id))
await self.loop.run_in_executor(
None, functools.partioal(submission.comments.replace_more, limit=None))
return submission.comments
async def edit_submission(self, submission_id, updated_text):
submission = await self.loop.run_in_executor(
None, functools.partioal(self._reddit.submission, id=submission_id))
await self.loop.run_in_executor(submission.edit, updated_text)
| import praw
class AsyncRateRedditAPI:
def __init__(self, client_id, client_secret, user_agent, username,
password):
self._reddit = praw.Reddit(
client_id=client_id, client_secret=client_secret,
user_agent=user_agent, username=username, password=password)
async def get_top_level_comments(self, submission_id):
submission = self._reddit.submission(id=submission_id)
submission.comments.replace_more(limit=None)
return submission.comments
async def edit_submission(self, submission_id, updated_text):
submission = self._reddit.submission(id=submission_id)
submission.edit(updated_text)
| Revert Reddit api to its synchonous state | Revert Reddit api to its synchonous state
| Python | mit | festinuz/cmcb,festinuz/cmcb | - import asyncio
- import functools
-
import praw
class AsyncRateRedditAPI:
def __init__(self, client_id, client_secret, user_agent, username,
- password, loop=None):
+ password):
self._reddit = praw.Reddit(
client_id=client_id, client_secret=client_secret,
user_agent=user_agent, username=username, password=password)
- if loop is None:
- loop = asyncio.get_event_loop()
- self.loop = loop
async def get_top_level_comments(self, submission_id):
+ submission = self._reddit.submission(id=submission_id)
- submission = await self.loop.run_in_executor(
- None, functools.partioal(self._reddit.submission, id=submission_id))
- await self.loop.run_in_executor(
- None, functools.partioal(submission.comments.replace_more, limit=None))
+ submission.comments.replace_more(limit=None)
return submission.comments
async def edit_submission(self, submission_id, updated_text):
+ submission = self._reddit.submission(id=submission_id)
+ submission.edit(updated_text)
- submission = await self.loop.run_in_executor(
- None, functools.partioal(self._reddit.submission, id=submission_id))
- await self.loop.run_in_executor(submission.edit, updated_text)
| Revert Reddit api to its synchonous state | ## Code Before:
import asyncio
import functools
import praw
class AsyncRateRedditAPI:
def __init__(self, client_id, client_secret, user_agent, username,
password, loop=None):
self._reddit = praw.Reddit(
client_id=client_id, client_secret=client_secret,
user_agent=user_agent, username=username, password=password)
if loop is None:
loop = asyncio.get_event_loop()
self.loop = loop
async def get_top_level_comments(self, submission_id):
submission = await self.loop.run_in_executor(
None, functools.partioal(self._reddit.submission, id=submission_id))
await self.loop.run_in_executor(
None, functools.partioal(submission.comments.replace_more, limit=None))
return submission.comments
async def edit_submission(self, submission_id, updated_text):
submission = await self.loop.run_in_executor(
None, functools.partioal(self._reddit.submission, id=submission_id))
await self.loop.run_in_executor(submission.edit, updated_text)
## Instruction:
Revert Reddit api to its synchonous state
## Code After:
import praw
class AsyncRateRedditAPI:
def __init__(self, client_id, client_secret, user_agent, username,
password):
self._reddit = praw.Reddit(
client_id=client_id, client_secret=client_secret,
user_agent=user_agent, username=username, password=password)
async def get_top_level_comments(self, submission_id):
submission = self._reddit.submission(id=submission_id)
submission.comments.replace_more(limit=None)
return submission.comments
async def edit_submission(self, submission_id, updated_text):
submission = self._reddit.submission(id=submission_id)
submission.edit(updated_text)
|
c6d949cbb32e095e5859aa22d11aa1566f5bc63f | website/util/mimetype.py | website/util/mimetype.py | import os
import mimetypes
HERE = os.path.dirname(os.path.abspath(__file__))
MIMEMAP = os.path.join(HERE, 'mime.types')
def get_mimetype(path, data=None):
mimetypes.init([MIMEMAP])
mimetype, _ = mimetypes.guess_type(path)
if mimetype is None and data is not None:
try:
import magic
mimetype = magic.from_buffer(data, mime=True)
except ImportError:
return mimetype
return mimetype | import os
import mimetypes
HERE = os.path.dirname(os.path.abspath(__file__))
MIMEMAP = os.path.join(HERE, 'mime.types')
def get_mimetype(path, file_contents=None):
mimetypes.init([MIMEMAP])
mimetype, _ = mimetypes.guess_type(path)
if mimetype is None and file_contents is not None:
try:
import magic
mimetype = magic.from_buffer(file_contents, mime=True)
except ImportError:
return mimetype
return mimetype | Make better name for argument. | Make better name for argument.
| Python | apache-2.0 | mfraezz/osf.io,saradbowman/osf.io,danielneis/osf.io,reinaH/osf.io,amyshi188/osf.io,GageGaskins/osf.io,wearpants/osf.io,KAsante95/osf.io,billyhunt/osf.io,petermalcolm/osf.io,danielneis/osf.io,cldershem/osf.io,samanehsan/osf.io,abought/osf.io,GaryKriebel/osf.io,CenterForOpenScience/osf.io,erinspace/osf.io,dplorimer/osf,adlius/osf.io,brandonPurvis/osf.io,himanshuo/osf.io,alexschiller/osf.io,erinspace/osf.io,baylee-d/osf.io,lyndsysimon/osf.io,RomanZWang/osf.io,billyhunt/osf.io,caseyrygt/osf.io,wearpants/osf.io,zkraime/osf.io,acshi/osf.io,fabianvf/osf.io,haoyuchen1992/osf.io,acshi/osf.io,icereval/osf.io,samchrisinger/osf.io,mluo613/osf.io,TomHeatwole/osf.io,jnayak1/osf.io,wearpants/osf.io,doublebits/osf.io,HarryRybacki/osf.io,jolene-esposito/osf.io,jeffreyliu3230/osf.io,mluo613/osf.io,mfraezz/osf.io,revanthkolli/osf.io,petermalcolm/osf.io,cldershem/osf.io,jnayak1/osf.io,emetsger/osf.io,sbt9uc/osf.io,Johnetordoff/osf.io,caneruguz/osf.io,acshi/osf.io,zachjanicki/osf.io,emetsger/osf.io,lyndsysimon/osf.io,dplorimer/osf,binoculars/osf.io,felliott/osf.io,lamdnhan/osf.io,jnayak1/osf.io,SSJohns/osf.io,saradbowman/osf.io,mluke93/osf.io,aaxelb/osf.io,kch8qx/osf.io,arpitar/osf.io,monikagrabowska/osf.io,Ghalko/osf.io,Nesiehr/osf.io,cwisecarver/osf.io,rdhyee/osf.io,cosenal/osf.io,barbour-em/osf.io,haoyuchen1992/osf.io,mluke93/osf.io,felliott/osf.io,hmoco/osf.io,jnayak1/osf.io,himanshuo/osf.io,HalcyonChimera/osf.io,ZobairAlijan/osf.io,sloria/osf.io,TomHeatwole/osf.io,zamattiac/osf.io,laurenrevere/osf.io,caneruguz/osf.io,danielneis/osf.io,billyhunt/osf.io,arpitar/osf.io,samchrisinger/osf.io,mfraezz/osf.io,adlius/osf.io,ZobairAlijan/osf.io,GaryKriebel/osf.io,njantrania/osf.io,DanielSBrown/osf.io,monikagrabowska/osf.io,Ghalko/osf.io,arpitar/osf.io,ckc6cz/osf.io,caseyrygt/osf.io,jinluyuan/osf.io,rdhyee/osf.io,pattisdr/osf.io,jmcarp/osf.io,reinaH/osf.io,DanielSBrown/osf.io,jolene-esposito/osf.io,samanehsan/osf.io,GageGaskins/osf.io,samanehsan/osf.io,brianjgeiger/osf.io,brianjgeiger/osf.io,samchrisinger/osf.io,caseyrollins/osf.io,jeffreyliu3230/osf.io,crcresearch/osf.io,RomanZWang/osf.io,TomHeatwole/osf.io,ticklemepierce/osf.io,petermalcolm/osf.io,amyshi188/osf.io,GageGaskins/osf.io,chrisseto/osf.io,lamdnhan/osf.io,RomanZWang/osf.io,emetsger/osf.io,adlius/osf.io,pattisdr/osf.io,aaxelb/osf.io,fabianvf/osf.io,asanfilippo7/osf.io,abought/osf.io,samchrisinger/osf.io,njantrania/osf.io,binoculars/osf.io,jeffreyliu3230/osf.io,mattclark/osf.io,cslzchen/osf.io,zkraime/osf.io,Nesiehr/osf.io,reinaH/osf.io,Nesiehr/osf.io,wearpants/osf.io,GageGaskins/osf.io,caseyrollins/osf.io,himanshuo/osf.io,jolene-esposito/osf.io,icereval/osf.io,kwierman/osf.io,binoculars/osf.io,Ghalko/osf.io,RomanZWang/osf.io,barbour-em/osf.io,KAsante95/osf.io,cwisecarver/osf.io,chennan47/osf.io,ZobairAlijan/osf.io,monikagrabowska/osf.io,reinaH/osf.io,leb2dg/osf.io,samanehsan/osf.io,jmcarp/osf.io,felliott/osf.io,zamattiac/osf.io,HarryRybacki/osf.io,kwierman/osf.io,caseyrollins/osf.io,sbt9uc/osf.io,amyshi188/osf.io,arpitar/osf.io,Nesiehr/osf.io,himanshuo/osf.io,leb2dg/osf.io,lyndsysimon/osf.io,zachjanicki/osf.io,brianjgeiger/osf.io,alexschiller/osf.io,chrisseto/osf.io,Johnetordoff/osf.io,haoyuchen1992/osf.io,AndrewSallans/osf.io,kwierman/osf.io,mfraezz/osf.io,cosenal/osf.io,mattclark/osf.io,AndrewSallans/osf.io,acshi/osf.io,zkraime/osf.io,hmoco/osf.io,TomBaxter/osf.io,zachjanicki/osf.io,fabianvf/osf.io,mattclark/osf.io,jeffreyliu3230/osf.io,mluo613/osf.io,erinspace/osf.io,SSJohns/osf.io,alexschiller/osf.io,abought/osf.io,cwisecarver/osf.io,hmoco/osf.io,bdyetton/prettychart,chennan47/osf.io,kch8qx/osf.io,felliott/osf.io,sloria/osf.io,aaxelb/osf.io,cosenal/osf.io,kushG/osf.io,chennan47/osf.io,cslzchen/osf.io,jmcarp/osf.io,sloria/osf.io,doublebits/osf.io,rdhyee/osf.io,leb2dg/osf.io,CenterForOpenScience/osf.io,KAsante95/osf.io,DanielSBrown/osf.io,baylee-d/osf.io,chrisseto/osf.io,barbour-em/osf.io,sbt9uc/osf.io,njantrania/osf.io,kch8qx/osf.io,Ghalko/osf.io,monikagrabowska/osf.io,GaryKriebel/osf.io,revanthkolli/osf.io,SSJohns/osf.io,leb2dg/osf.io,jinluyuan/osf.io,brandonPurvis/osf.io,revanthkolli/osf.io,Johnetordoff/osf.io,ZobairAlijan/osf.io,cosenal/osf.io,lamdnhan/osf.io,icereval/osf.io,jinluyuan/osf.io,crcresearch/osf.io,njantrania/osf.io,MerlinZhang/osf.io,jinluyuan/osf.io,zamattiac/osf.io,caseyrygt/osf.io,bdyetton/prettychart,adlius/osf.io,laurenrevere/osf.io,billyhunt/osf.io,KAsante95/osf.io,kch8qx/osf.io,TomBaxter/osf.io,mluo613/osf.io,kushG/osf.io,brandonPurvis/osf.io,kushG/osf.io,cldershem/osf.io,rdhyee/osf.io,mluo613/osf.io,jolene-esposito/osf.io,doublebits/osf.io,kwierman/osf.io,monikagrabowska/osf.io,barbour-em/osf.io,abought/osf.io,billyhunt/osf.io,asanfilippo7/osf.io,alexschiller/osf.io,revanthkolli/osf.io,cwisecarver/osf.io,DanielSBrown/osf.io,petermalcolm/osf.io,caseyrygt/osf.io,GaryKriebel/osf.io,aaxelb/osf.io,crcresearch/osf.io,fabianvf/osf.io,ckc6cz/osf.io,jmcarp/osf.io,lamdnhan/osf.io,MerlinZhang/osf.io,pattisdr/osf.io,doublebits/osf.io,hmoco/osf.io,brianjgeiger/osf.io,MerlinZhang/osf.io,dplorimer/osf,amyshi188/osf.io,mluke93/osf.io,zkraime/osf.io,sbt9uc/osf.io,cldershem/osf.io,HalcyonChimera/osf.io,danielneis/osf.io,laurenrevere/osf.io,baylee-d/osf.io,ticklemepierce/osf.io,kushG/osf.io,HarryRybacki/osf.io,haoyuchen1992/osf.io,kch8qx/osf.io,doublebits/osf.io,CenterForOpenScience/osf.io,bdyetton/prettychart,dplorimer/osf,HalcyonChimera/osf.io,brandonPurvis/osf.io,caneruguz/osf.io,SSJohns/osf.io,lyndsysimon/osf.io,HarryRybacki/osf.io,MerlinZhang/osf.io,caneruguz/osf.io,TomHeatwole/osf.io,chrisseto/osf.io,CenterForOpenScience/osf.io,ckc6cz/osf.io,GageGaskins/osf.io,Johnetordoff/osf.io,asanfilippo7/osf.io,alexschiller/osf.io,asanfilippo7/osf.io,emetsger/osf.io,HalcyonChimera/osf.io,brandonPurvis/osf.io,ckc6cz/osf.io,ticklemepierce/osf.io,bdyetton/prettychart,ticklemepierce/osf.io,zamattiac/osf.io,RomanZWang/osf.io,TomBaxter/osf.io,KAsante95/osf.io,cslzchen/osf.io,mluke93/osf.io,zachjanicki/osf.io,acshi/osf.io,cslzchen/osf.io | import os
import mimetypes
HERE = os.path.dirname(os.path.abspath(__file__))
MIMEMAP = os.path.join(HERE, 'mime.types')
- def get_mimetype(path, data=None):
+ def get_mimetype(path, file_contents=None):
mimetypes.init([MIMEMAP])
mimetype, _ = mimetypes.guess_type(path)
- if mimetype is None and data is not None:
+ if mimetype is None and file_contents is not None:
try:
import magic
- mimetype = magic.from_buffer(data, mime=True)
+ mimetype = magic.from_buffer(file_contents, mime=True)
except ImportError:
return mimetype
return mimetype | Make better name for argument. | ## Code Before:
import os
import mimetypes
HERE = os.path.dirname(os.path.abspath(__file__))
MIMEMAP = os.path.join(HERE, 'mime.types')
def get_mimetype(path, data=None):
mimetypes.init([MIMEMAP])
mimetype, _ = mimetypes.guess_type(path)
if mimetype is None and data is not None:
try:
import magic
mimetype = magic.from_buffer(data, mime=True)
except ImportError:
return mimetype
return mimetype
## Instruction:
Make better name for argument.
## Code After:
import os
import mimetypes
HERE = os.path.dirname(os.path.abspath(__file__))
MIMEMAP = os.path.join(HERE, 'mime.types')
def get_mimetype(path, file_contents=None):
mimetypes.init([MIMEMAP])
mimetype, _ = mimetypes.guess_type(path)
if mimetype is None and file_contents is not None:
try:
import magic
mimetype = magic.from_buffer(file_contents, mime=True)
except ImportError:
return mimetype
return mimetype |
b8c2376368290fa4fef103ba86d4f2ed164a3b7d | numscons/checkers/__init__.py | numscons/checkers/__init__.py | from blas_lapack_checkers import CheckCLAPACK, CheckCBLAS, CheckF77BLAS, CheckF77LAPACK
from fft_checkers import CheckFFT
from simple_check import NumpyCheckLibAndHeader
from perflib import *
from fortran import *
from perflib_info import write_info
import blas_lapack_checkers
import fft_checkers
import perflib
import perflib_info
__all__ = blas_lapack_checkers.__all__
__all__ += fft_checkers.__all__
__all__ += perflib.__all__
__all__ += perflib_info.__all__
__all__ += fortran.__all__
__all__ += ['NumpyCheckLibAndHeader']
| from numscons.checkers.new.netlib_checkers import \
CheckCblas as CheckCBLAS, \
CheckF77Blas as CheckF77BLAS, \
CheckF77Lapack as CheckF77LAPACK
from numscons.checkers.new.common import \
get_perflib_implementation
from numscons.checkers.new.common import \
write_configuration_results as write_info
from numscons.checkers.simple_check import \
NumpyCheckLibAndHeader
from numscons.checkers.fortran import *
from numscons.checkers import fortran
# Those are for compatibility only
def CheckCLAPACK(context, autoadd=1, check_version=0):
context.Message("Checking for CLAPACK ... ")
context.Result(0)
return 0
def IsVeclib(env, interface):
return get_perflib_implementation(env, interface.upper()) == 'VECLIB'
def IsAccelerate(env, interface):
return get_perflib_implementation(env, interface.upper()) == 'ACCELERATE'
def IsATLAS(env, interface):
return get_perflib_implementation(env, interface.upper()) == 'ATLAS'
def GetATLASVersion(env):
return ''
__all__ = []
__all__ += ['CheckCBLAS', 'CheckF77LAPACK', 'CheckF77BLAS', 'CheckCLAPACK',
'write_info', 'IsVeclib', 'IsAccelerate', 'IsATLAS', 'GetATLASVersion']
__all__ += fortran.__all__
__all__ += ['NumpyCheckLibAndHeader']
| Use the new framework for checkers. | Use the new framework for checkers.
| Python | bsd-3-clause | cournape/numscons,cournape/numscons,cournape/numscons | - from blas_lapack_checkers import CheckCLAPACK, CheckCBLAS, CheckF77BLAS, CheckF77LAPACK
- from fft_checkers import CheckFFT
+ from numscons.checkers.new.netlib_checkers import \
+ CheckCblas as CheckCBLAS, \
+ CheckF77Blas as CheckF77BLAS, \
+ CheckF77Lapack as CheckF77LAPACK
+ from numscons.checkers.new.common import \
+ get_perflib_implementation
+ from numscons.checkers.new.common import \
+ write_configuration_results as write_info
- from simple_check import NumpyCheckLibAndHeader
+ from numscons.checkers.simple_check import \
+ NumpyCheckLibAndHeader
+ from numscons.checkers.fortran import *
+ from numscons.checkers import fortran
- from perflib import *
- from fortran import *
+ # Those are for compatibility only
+ def CheckCLAPACK(context, autoadd=1, check_version=0):
+ context.Message("Checking for CLAPACK ... ")
+ context.Result(0)
+ return 0
- from perflib_info import write_info
+ def IsVeclib(env, interface):
+ return get_perflib_implementation(env, interface.upper()) == 'VECLIB'
+ def IsAccelerate(env, interface):
+ return get_perflib_implementation(env, interface.upper()) == 'ACCELERATE'
- import blas_lapack_checkers
- import fft_checkers
- import perflib
- import perflib_info
- __all__ = blas_lapack_checkers.__all__
- __all__ += fft_checkers.__all__
- __all__ += perflib.__all__
- __all__ += perflib_info.__all__
+ def IsATLAS(env, interface):
+ return get_perflib_implementation(env, interface.upper()) == 'ATLAS'
+
+ def GetATLASVersion(env):
+ return ''
+
+ __all__ = []
+ __all__ += ['CheckCBLAS', 'CheckF77LAPACK', 'CheckF77BLAS', 'CheckCLAPACK',
+ 'write_info', 'IsVeclib', 'IsAccelerate', 'IsATLAS', 'GetATLASVersion']
__all__ += fortran.__all__
__all__ += ['NumpyCheckLibAndHeader']
| Use the new framework for checkers. | ## Code Before:
from blas_lapack_checkers import CheckCLAPACK, CheckCBLAS, CheckF77BLAS, CheckF77LAPACK
from fft_checkers import CheckFFT
from simple_check import NumpyCheckLibAndHeader
from perflib import *
from fortran import *
from perflib_info import write_info
import blas_lapack_checkers
import fft_checkers
import perflib
import perflib_info
__all__ = blas_lapack_checkers.__all__
__all__ += fft_checkers.__all__
__all__ += perflib.__all__
__all__ += perflib_info.__all__
__all__ += fortran.__all__
__all__ += ['NumpyCheckLibAndHeader']
## Instruction:
Use the new framework for checkers.
## Code After:
from numscons.checkers.new.netlib_checkers import \
CheckCblas as CheckCBLAS, \
CheckF77Blas as CheckF77BLAS, \
CheckF77Lapack as CheckF77LAPACK
from numscons.checkers.new.common import \
get_perflib_implementation
from numscons.checkers.new.common import \
write_configuration_results as write_info
from numscons.checkers.simple_check import \
NumpyCheckLibAndHeader
from numscons.checkers.fortran import *
from numscons.checkers import fortran
# Those are for compatibility only
def CheckCLAPACK(context, autoadd=1, check_version=0):
context.Message("Checking for CLAPACK ... ")
context.Result(0)
return 0
def IsVeclib(env, interface):
return get_perflib_implementation(env, interface.upper()) == 'VECLIB'
def IsAccelerate(env, interface):
return get_perflib_implementation(env, interface.upper()) == 'ACCELERATE'
def IsATLAS(env, interface):
return get_perflib_implementation(env, interface.upper()) == 'ATLAS'
def GetATLASVersion(env):
return ''
__all__ = []
__all__ += ['CheckCBLAS', 'CheckF77LAPACK', 'CheckF77BLAS', 'CheckCLAPACK',
'write_info', 'IsVeclib', 'IsAccelerate', 'IsATLAS', 'GetATLASVersion']
__all__ += fortran.__all__
__all__ += ['NumpyCheckLibAndHeader']
|
f200d98547baef9ac2faa90d72857ffa0e64c721 | 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.
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
from IPython.utils.traitlets import Unicode
from .templateexporter import TemplateExporter
#-----------------------------------------------------------------------------
# Classes
#-----------------------------------------------------------------------------
class PythonExporter(TemplateExporter):
"""
Exports a Python code file.
"""
file_extension = Unicode(
'py', config=True,
help="Extension of the file that should be written to disk")
def _raw_mimetype_default(self):
return 'application/x-python'
| """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.
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
from IPython.utils.traitlets import Unicode
from .templateexporter import TemplateExporter
#-----------------------------------------------------------------------------
# Classes
#-----------------------------------------------------------------------------
class PythonExporter(TemplateExporter):
"""
Exports a Python code file.
"""
file_extension = Unicode(
'py', config=True,
help="Extension of the file that should be written to disk")
def _raw_mimetype_default(self):
return 'application/x-python'
mime_type = Unicode('text/x-python', config=True,
help="MIME type of the result file, for HTTP response headers."
)
| Add MIME types to nbconvert exporters | Add MIME types to nbconvert exporters
| Python | bsd-3-clause | cornhundred/ipywidgets,jupyter-widgets/ipywidgets,cornhundred/ipywidgets,SylvainCorlay/ipywidgets,SylvainCorlay/ipywidgets,cornhundred/ipywidgets,jupyter-widgets/ipywidgets,ipython/ipywidgets,ipython/ipywidgets,ipython/ipywidgets,jupyter-widgets/ipywidgets,ipython/ipywidgets,SylvainCorlay/ipywidgets,cornhundred/ipywidgets,SylvainCorlay/ipywidgets,cornhundred/ipywidgets,jupyter-widgets/ipywidgets,ipython/ipywidgets | """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.
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
from IPython.utils.traitlets import Unicode
from .templateexporter import TemplateExporter
#-----------------------------------------------------------------------------
# Classes
#-----------------------------------------------------------------------------
class PythonExporter(TemplateExporter):
"""
Exports a Python code file.
"""
file_extension = Unicode(
'py', config=True,
help="Extension of the file that should be written to disk")
def _raw_mimetype_default(self):
return 'application/x-python'
+ mime_type = Unicode('text/x-python', config=True,
+ help="MIME type of the result file, for HTTP response headers."
+ )
| Add MIME types to nbconvert exporters | ## Code Before:
"""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.
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
from IPython.utils.traitlets import Unicode
from .templateexporter import TemplateExporter
#-----------------------------------------------------------------------------
# Classes
#-----------------------------------------------------------------------------
class PythonExporter(TemplateExporter):
"""
Exports a Python code file.
"""
file_extension = Unicode(
'py', config=True,
help="Extension of the file that should be written to disk")
def _raw_mimetype_default(self):
return 'application/x-python'
## Instruction:
Add MIME types to nbconvert exporters
## Code After:
"""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.
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
from IPython.utils.traitlets import Unicode
from .templateexporter import TemplateExporter
#-----------------------------------------------------------------------------
# Classes
#-----------------------------------------------------------------------------
class PythonExporter(TemplateExporter):
"""
Exports a Python code file.
"""
file_extension = Unicode(
'py', config=True,
help="Extension of the file that should be written to disk")
def _raw_mimetype_default(self):
return 'application/x-python'
mime_type = Unicode('text/x-python', config=True,
help="MIME type of the result file, for HTTP response headers."
)
|
fda1b41890ea338e992ddd8a23d9c6a497990ea2 | fabfile/eg.py | fabfile/eg.py | from __future__ import unicode_literals, print_function
from fabric.api import task, local, run, lcd, cd, env, shell_env
from fabtools.python import virtualenv
from _util import PWD, VENV_DIR
@task
def mnist():
with virtualenv(VENV_DIR), lcd(PWD), shell_env(PYTHONPATH=PWD):
local('python examples/mnist_mlp.py')
@task
def basic_tagger():
with virtualenv(VENV_DIR), lcd(PWD), shell_env(PYTHONPATH=PWD):
local('python examples/basic_tagger.py')
@task
def cnn_tagger():
with virtualenv(VENV_DIR), lcd(PWD), shell_env(PYTHONPATH=PWD):
local('python examples/cnn_tagger.py')
@task
def spacy_tagger():
with virtualenv(VENV_DIR), lcd(PWD), shell_env(PYTHONPATH=PWD):
local('python examples/spacy_tagger.py')
| from __future__ import unicode_literals, print_function
from fabric.api import task, local, run, lcd, cd, env, shell_env
from fabtools.python import virtualenv
from _util import PWD, VENV_DIR
@task
def mnist():
with virtualenv(VENV_DIR), lcd(PWD), shell_env(PYTHONPATH=PWD):
local('python examples/mnist_mlp.py')
@task
def basic_tagger():
with virtualenv(VENV_DIR), lcd(PWD), shell_env(PYTHONPATH=PWD):
local('python examples/basic_tagger.py')
@task
def cnn_tagger():
with virtualenv(VENV_DIR), lcd(PWD), shell_env(PYTHONPATH=PWD):
local('python examples/cnn_tagger.py')
@task
def quora():
with virtualenv(VENV_DIR), lcd(PWD), shell_env(PYTHONPATH=PWD):
local('pip install spacy')
local('python -m spacy.en.download')
local('python examples/quora_similarity.py')
@task
def spacy_tagger():
with virtualenv(VENV_DIR), lcd(PWD), shell_env(PYTHONPATH=PWD):
local('python examples/spacy_tagger.py')
| Add fabric task for Quora example | Add fabric task for Quora example
| Python | mit | spacy-io/thinc,explosion/thinc,explosion/thinc,spacy-io/thinc,spacy-io/thinc,explosion/thinc,explosion/thinc | from __future__ import unicode_literals, print_function
from fabric.api import task, local, run, lcd, cd, env, shell_env
from fabtools.python import virtualenv
from _util import PWD, VENV_DIR
@task
def mnist():
with virtualenv(VENV_DIR), lcd(PWD), shell_env(PYTHONPATH=PWD):
local('python examples/mnist_mlp.py')
@task
def basic_tagger():
with virtualenv(VENV_DIR), lcd(PWD), shell_env(PYTHONPATH=PWD):
local('python examples/basic_tagger.py')
@task
def cnn_tagger():
with virtualenv(VENV_DIR), lcd(PWD), shell_env(PYTHONPATH=PWD):
local('python examples/cnn_tagger.py')
@task
+ def quora():
+ with virtualenv(VENV_DIR), lcd(PWD), shell_env(PYTHONPATH=PWD):
+ local('pip install spacy')
+ local('python -m spacy.en.download')
+ local('python examples/quora_similarity.py')
+
+ @task
def spacy_tagger():
with virtualenv(VENV_DIR), lcd(PWD), shell_env(PYTHONPATH=PWD):
local('python examples/spacy_tagger.py')
| Add fabric task for Quora example | ## Code Before:
from __future__ import unicode_literals, print_function
from fabric.api import task, local, run, lcd, cd, env, shell_env
from fabtools.python import virtualenv
from _util import PWD, VENV_DIR
@task
def mnist():
with virtualenv(VENV_DIR), lcd(PWD), shell_env(PYTHONPATH=PWD):
local('python examples/mnist_mlp.py')
@task
def basic_tagger():
with virtualenv(VENV_DIR), lcd(PWD), shell_env(PYTHONPATH=PWD):
local('python examples/basic_tagger.py')
@task
def cnn_tagger():
with virtualenv(VENV_DIR), lcd(PWD), shell_env(PYTHONPATH=PWD):
local('python examples/cnn_tagger.py')
@task
def spacy_tagger():
with virtualenv(VENV_DIR), lcd(PWD), shell_env(PYTHONPATH=PWD):
local('python examples/spacy_tagger.py')
## Instruction:
Add fabric task for Quora example
## Code After:
from __future__ import unicode_literals, print_function
from fabric.api import task, local, run, lcd, cd, env, shell_env
from fabtools.python import virtualenv
from _util import PWD, VENV_DIR
@task
def mnist():
with virtualenv(VENV_DIR), lcd(PWD), shell_env(PYTHONPATH=PWD):
local('python examples/mnist_mlp.py')
@task
def basic_tagger():
with virtualenv(VENV_DIR), lcd(PWD), shell_env(PYTHONPATH=PWD):
local('python examples/basic_tagger.py')
@task
def cnn_tagger():
with virtualenv(VENV_DIR), lcd(PWD), shell_env(PYTHONPATH=PWD):
local('python examples/cnn_tagger.py')
@task
def quora():
with virtualenv(VENV_DIR), lcd(PWD), shell_env(PYTHONPATH=PWD):
local('pip install spacy')
local('python -m spacy.en.download')
local('python examples/quora_similarity.py')
@task
def spacy_tagger():
with virtualenv(VENV_DIR), lcd(PWD), shell_env(PYTHONPATH=PWD):
local('python examples/spacy_tagger.py')
|
c604ace9394cdc1c0c0a3002cbb3d90dd64695f3 | examples/mnist-classifier.py | examples/mnist-classifier.py |
import cPickle
import gzip
import logging
import os
import sys
import tempfile
import urllib
import lmj.tnn
logging.basicConfig(
stream=sys.stdout,
format='%(levelname).1s %(asctime)s %(message)s',
level=logging.INFO)
URL = 'http://www.iro.umontreal.ca/~lisa/deep/data/mnist/mnist.pkl.gz'
DATASET = os.path.join(tempfile.gettempdir(), 'mnist.pkl.gz')
if not os.path.isfile(DATASET):
logging.info('downloading mnist digit dataset from %s' % URL)
urllib.urlretrieve(URL, DATASET)
logging.info('saved mnist digits to %s' % DATASET)
class Main(lmj.tnn.Main):
def get_network(self):
return lmj.tnn.Classifier
def get_datasets(self):
return [(x, y.astype('int32')) for x, y in cPickle.load(gzip.open(DATASET))]
path = os.path.join(tempfile.gettempdir(), 'mnist-classifier.pkl.gz')
Main().train().save(path)
print 'saved network to', path
|
import cPickle
import gzip
import logging
import os
import sys
import tempfile
import urllib
import lmj.tnn
logging.basicConfig(
stream=sys.stdout,
format='%(levelname).1s %(asctime)s %(message)s',
level=logging.INFO)
URL = 'http://www.iro.umontreal.ca/~lisa/deep/data/mnist/mnist.pkl.gz'
DATASET = os.path.join(tempfile.gettempdir(), 'mnist.pkl.gz')
if not os.path.isfile(DATASET):
logging.info('downloading mnist digit dataset from %s' % URL)
urllib.urlretrieve(URL, DATASET)
logging.info('saved mnist digits to %s' % DATASET)
class Main(lmj.tnn.Main):
def get_network(self):
return lmj.tnn.Classifier
def get_datasets(self):
return [(x, y.astype('int32')) for x, y in cPickle.load(gzip.open(DATASET))]
m = Main()
path = os.path.join(tempfile.gettempdir(), 'mnist-classifier-%s.pkl.gz' % m.opts.layers)
if os.path.exists(path):
m.net.load(path)
m.train()
m.net.save(path)
| Save mnist classifier model in a file named with the network topology. | Save mnist classifier model in a file named with the network topology.
| Python | mit | lmjohns3/theanets,chrinide/theanets,devdoer/theanets |
import cPickle
import gzip
import logging
import os
import sys
import tempfile
import urllib
import lmj.tnn
logging.basicConfig(
stream=sys.stdout,
format='%(levelname).1s %(asctime)s %(message)s',
level=logging.INFO)
URL = 'http://www.iro.umontreal.ca/~lisa/deep/data/mnist/mnist.pkl.gz'
DATASET = os.path.join(tempfile.gettempdir(), 'mnist.pkl.gz')
if not os.path.isfile(DATASET):
logging.info('downloading mnist digit dataset from %s' % URL)
urllib.urlretrieve(URL, DATASET)
logging.info('saved mnist digits to %s' % DATASET)
class Main(lmj.tnn.Main):
def get_network(self):
return lmj.tnn.Classifier
def get_datasets(self):
return [(x, y.astype('int32')) for x, y in cPickle.load(gzip.open(DATASET))]
+ m = Main()
- path = os.path.join(tempfile.gettempdir(), 'mnist-classifier.pkl.gz')
+ path = os.path.join(tempfile.gettempdir(), 'mnist-classifier-%s.pkl.gz' % m.opts.layers)
- Main().train().save(path)
- print 'saved network to', path
+ if os.path.exists(path):
+ m.net.load(path)
+ m.train()
+ m.net.save(path)
| Save mnist classifier model in a file named with the network topology. | ## Code Before:
import cPickle
import gzip
import logging
import os
import sys
import tempfile
import urllib
import lmj.tnn
logging.basicConfig(
stream=sys.stdout,
format='%(levelname).1s %(asctime)s %(message)s',
level=logging.INFO)
URL = 'http://www.iro.umontreal.ca/~lisa/deep/data/mnist/mnist.pkl.gz'
DATASET = os.path.join(tempfile.gettempdir(), 'mnist.pkl.gz')
if not os.path.isfile(DATASET):
logging.info('downloading mnist digit dataset from %s' % URL)
urllib.urlretrieve(URL, DATASET)
logging.info('saved mnist digits to %s' % DATASET)
class Main(lmj.tnn.Main):
def get_network(self):
return lmj.tnn.Classifier
def get_datasets(self):
return [(x, y.astype('int32')) for x, y in cPickle.load(gzip.open(DATASET))]
path = os.path.join(tempfile.gettempdir(), 'mnist-classifier.pkl.gz')
Main().train().save(path)
print 'saved network to', path
## Instruction:
Save mnist classifier model in a file named with the network topology.
## Code After:
import cPickle
import gzip
import logging
import os
import sys
import tempfile
import urllib
import lmj.tnn
logging.basicConfig(
stream=sys.stdout,
format='%(levelname).1s %(asctime)s %(message)s',
level=logging.INFO)
URL = 'http://www.iro.umontreal.ca/~lisa/deep/data/mnist/mnist.pkl.gz'
DATASET = os.path.join(tempfile.gettempdir(), 'mnist.pkl.gz')
if not os.path.isfile(DATASET):
logging.info('downloading mnist digit dataset from %s' % URL)
urllib.urlretrieve(URL, DATASET)
logging.info('saved mnist digits to %s' % DATASET)
class Main(lmj.tnn.Main):
def get_network(self):
return lmj.tnn.Classifier
def get_datasets(self):
return [(x, y.astype('int32')) for x, y in cPickle.load(gzip.open(DATASET))]
m = Main()
path = os.path.join(tempfile.gettempdir(), 'mnist-classifier-%s.pkl.gz' % m.opts.layers)
if os.path.exists(path):
m.net.load(path)
m.train()
m.net.save(path)
|
e5083fd56caa271afbdbad1c59009f7e1ea465b3 | content/app.py | content/app.py | from flask import Flask
from .extensions import envcfg, apierrors, applogging
from .blueprints.status import blueprint as status_bp
from .blueprints.content import blueprint as content_bp
from .blueprints.swagger import blueprint as swagger_bp
def create_app():
app = Flask('content')
app.config.from_object('content.default_settings')
envcfg.init_app(app)
applogging.init_app(app)
apierrors.init_app(app)
app.register_blueprint(status_bp)
app.register_blueprint(content_bp, url_prefix='/v1')
app.register_blueprint(swagger_bp)
return app
| from flask import Flask, jsonify
from botocore.exceptions import ClientError
from .extensions import envcfg, apierrors, applogging
from .blueprints.status import blueprint as status_bp
from .blueprints.content import blueprint as content_bp
from .blueprints.swagger import blueprint as swagger_bp
def create_app():
app = Flask('content')
app.config.from_object('content.default_settings')
envcfg.init_app(app)
applogging.init_app(app)
apierrors.init_app(app)
app.register_blueprint(status_bp)
app.register_blueprint(content_bp, url_prefix='/v1')
app.register_blueprint(swagger_bp)
app.register_error_handler(ClientError, _no_such_key)
return app
def _no_such_key(error):
# Boto3 exceptions are idiotic.
if error.response['Error']['Code'] != "NoSuchEntity":
return jsonify({'error': 'No such content'}), 404
else:
raise error
| Return 404 when no content found. | Return 404 when no content found.
| Python | bsd-3-clause | Zipmatch/zipmatch-content,Zipmatch/zipmatch-content | - from flask import Flask
+ from flask import Flask, jsonify
+
+ from botocore.exceptions import ClientError
from .extensions import envcfg, apierrors, applogging
from .blueprints.status import blueprint as status_bp
from .blueprints.content import blueprint as content_bp
from .blueprints.swagger import blueprint as swagger_bp
def create_app():
app = Flask('content')
app.config.from_object('content.default_settings')
envcfg.init_app(app)
applogging.init_app(app)
apierrors.init_app(app)
app.register_blueprint(status_bp)
app.register_blueprint(content_bp, url_prefix='/v1')
app.register_blueprint(swagger_bp)
+ app.register_error_handler(ClientError, _no_such_key)
return app
+
+ def _no_such_key(error):
+ # Boto3 exceptions are idiotic.
+ if error.response['Error']['Code'] != "NoSuchEntity":
+ return jsonify({'error': 'No such content'}), 404
+ else:
+ raise error
+ | Return 404 when no content found. | ## Code Before:
from flask import Flask
from .extensions import envcfg, apierrors, applogging
from .blueprints.status import blueprint as status_bp
from .blueprints.content import blueprint as content_bp
from .blueprints.swagger import blueprint as swagger_bp
def create_app():
app = Flask('content')
app.config.from_object('content.default_settings')
envcfg.init_app(app)
applogging.init_app(app)
apierrors.init_app(app)
app.register_blueprint(status_bp)
app.register_blueprint(content_bp, url_prefix='/v1')
app.register_blueprint(swagger_bp)
return app
## Instruction:
Return 404 when no content found.
## Code After:
from flask import Flask, jsonify
from botocore.exceptions import ClientError
from .extensions import envcfg, apierrors, applogging
from .blueprints.status import blueprint as status_bp
from .blueprints.content import blueprint as content_bp
from .blueprints.swagger import blueprint as swagger_bp
def create_app():
app = Flask('content')
app.config.from_object('content.default_settings')
envcfg.init_app(app)
applogging.init_app(app)
apierrors.init_app(app)
app.register_blueprint(status_bp)
app.register_blueprint(content_bp, url_prefix='/v1')
app.register_blueprint(swagger_bp)
app.register_error_handler(ClientError, _no_such_key)
return app
def _no_such_key(error):
# Boto3 exceptions are idiotic.
if error.response['Error']['Code'] != "NoSuchEntity":
return jsonify({'error': 'No such content'}), 404
else:
raise error
|
1b455898665ceedec330dea68e53ece4719b2898 | cumulusci/utils/yaml/cumulusci_yml.py | cumulusci/utils/yaml/cumulusci_yml.py | from typing import IO, Text
from re import compile, MULTILINE
from logging import getLogger
from io import StringIO
import yaml
NBSP = "\u00A0"
pattern = compile(r"^\s*[\u00A0]+\s*", MULTILINE)
logger = getLogger(__name__)
def _replace_nbsp(origdata):
counter = 0
def _replacer_func(matchobj):
nonlocal counter
counter += 1
string = matchobj.group(0)
rc = string.replace(NBSP, " ")
return rc
data = pattern.sub(_replacer_func, origdata)
if counter:
plural = "s were" if counter > 1 else " was"
logger.warn(
f"Note: {counter} non-breaking space character{plural} detected in cumulusci.yml.\n"
"Perhaps you cut and pasted it from a Web page.\n"
"Future versions of CumulusCI may disallow these characters.\n"
)
return data
def cci_safe_load(f_config: IO[Text]):
"Load a file, convert NBSP->space and parse it in YAML."
data = _replace_nbsp(f_config.read())
rc = yaml.safe_load(StringIO(data))
return rc
| from typing import IO, Text
import re
from logging import getLogger
from io import StringIO
import yaml
NBSP = "\u00A0"
pattern = re.compile(r"^\s*[\u00A0]+\s*", re.MULTILINE)
logger = getLogger(__name__)
def _replace_nbsp(origdata):
counter = 0
def _replacer_func(matchobj):
nonlocal counter
counter += 1
string = matchobj.group(0)
rc = string.replace(NBSP, " ")
return rc
data = pattern.sub(_replacer_func, origdata)
if counter:
plural = "s were" if counter > 1 else " was"
logger.warn(
f"Note: {counter} lines with non-breaking space character{plural} detected in cumulusci.yml.\n"
"Perhaps you cut and pasted from a Web page?\n"
"Future versions of CumulusCI may disallow these characters.\n"
)
return data
def cci_safe_load(f_config: IO[Text]):
"Load a file, convert NBSP->space and parse it in YAML."
data = _replace_nbsp(f_config.read())
rc = yaml.safe_load(StringIO(data))
return rc
| Improve error message and imports | Improve error message and imports
| Python | bsd-3-clause | SalesforceFoundation/CumulusCI,SalesforceFoundation/CumulusCI | from typing import IO, Text
- from re import compile, MULTILINE
+ import re
from logging import getLogger
from io import StringIO
import yaml
NBSP = "\u00A0"
- pattern = compile(r"^\s*[\u00A0]+\s*", MULTILINE)
+ pattern = re.compile(r"^\s*[\u00A0]+\s*", re.MULTILINE)
logger = getLogger(__name__)
def _replace_nbsp(origdata):
counter = 0
def _replacer_func(matchobj):
nonlocal counter
counter += 1
string = matchobj.group(0)
rc = string.replace(NBSP, " ")
return rc
data = pattern.sub(_replacer_func, origdata)
if counter:
plural = "s were" if counter > 1 else " was"
logger.warn(
- f"Note: {counter} non-breaking space character{plural} detected in cumulusci.yml.\n"
+ f"Note: {counter} lines with non-breaking space character{plural} detected in cumulusci.yml.\n"
- "Perhaps you cut and pasted it from a Web page.\n"
+ "Perhaps you cut and pasted from a Web page?\n"
"Future versions of CumulusCI may disallow these characters.\n"
)
return data
def cci_safe_load(f_config: IO[Text]):
"Load a file, convert NBSP->space and parse it in YAML."
data = _replace_nbsp(f_config.read())
rc = yaml.safe_load(StringIO(data))
return rc
| Improve error message and imports | ## Code Before:
from typing import IO, Text
from re import compile, MULTILINE
from logging import getLogger
from io import StringIO
import yaml
NBSP = "\u00A0"
pattern = compile(r"^\s*[\u00A0]+\s*", MULTILINE)
logger = getLogger(__name__)
def _replace_nbsp(origdata):
counter = 0
def _replacer_func(matchobj):
nonlocal counter
counter += 1
string = matchobj.group(0)
rc = string.replace(NBSP, " ")
return rc
data = pattern.sub(_replacer_func, origdata)
if counter:
plural = "s were" if counter > 1 else " was"
logger.warn(
f"Note: {counter} non-breaking space character{plural} detected in cumulusci.yml.\n"
"Perhaps you cut and pasted it from a Web page.\n"
"Future versions of CumulusCI may disallow these characters.\n"
)
return data
def cci_safe_load(f_config: IO[Text]):
"Load a file, convert NBSP->space and parse it in YAML."
data = _replace_nbsp(f_config.read())
rc = yaml.safe_load(StringIO(data))
return rc
## Instruction:
Improve error message and imports
## Code After:
from typing import IO, Text
import re
from logging import getLogger
from io import StringIO
import yaml
NBSP = "\u00A0"
pattern = re.compile(r"^\s*[\u00A0]+\s*", re.MULTILINE)
logger = getLogger(__name__)
def _replace_nbsp(origdata):
counter = 0
def _replacer_func(matchobj):
nonlocal counter
counter += 1
string = matchobj.group(0)
rc = string.replace(NBSP, " ")
return rc
data = pattern.sub(_replacer_func, origdata)
if counter:
plural = "s were" if counter > 1 else " was"
logger.warn(
f"Note: {counter} lines with non-breaking space character{plural} detected in cumulusci.yml.\n"
"Perhaps you cut and pasted from a Web page?\n"
"Future versions of CumulusCI may disallow these characters.\n"
)
return data
def cci_safe_load(f_config: IO[Text]):
"Load a file, convert NBSP->space and parse it in YAML."
data = _replace_nbsp(f_config.read())
rc = yaml.safe_load(StringIO(data))
return rc
|
3d00536041d52900a4ace5304b5b07eba4c11efb | wmt/flask/names/models.py | wmt/flask/names/models.py | from standard_names import StandardName
from ..core import db
class Name(db.Model):
__tablename__ = 'names'
__bind_key__ = 'names'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.Text)
def __init__(self, name):
self.name = name
def __repr__(self):
return '<Name %r>' % self.name
def to_resource(self, brief=False):
if brief:
return {'id': self.id, 'name': self.name}
else:
sn = StandardName(self.name)
return {
'id': self.id,
'href': '/api/names/%d' % self.id,
'name': self.name,
'object': sn.object,
'quantity': sn.quantity,
'operators': sn.operators,
}
| from flask import url_for
from standard_names import StandardName
from ..core import db, JsonMixin
class NameJsonSerializer(JsonMixin):
__public_fields__ = set(['href', 'id', 'name', 'object', 'quantity',
'operators'])
class Name(NameJsonSerializer, db.Model):
__tablename__ = 'names'
__bind_key__ = 'names'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.Text)
@property
def href(self):
return url_for('names.name', id=self.id)
@property
def object(self):
return StandardName(self.name).object
@property
def quantity(self):
return StandardName(self.name).quantity
@property
def operators(self):
return StandardName(self.name).operators
def __init__(self, name):
self.name = name
def __repr__(self):
return '<Name %r>' % self.name
| Use the JsonMixin for the names model. | Use the JsonMixin for the names model.
| Python | mit | mcflugen/wmt-rest,mcflugen/wmt-rest | + from flask import url_for
+
from standard_names import StandardName
- from ..core import db
+ from ..core import db, JsonMixin
- class Name(db.Model):
+ class NameJsonSerializer(JsonMixin):
+ __public_fields__ = set(['href', 'id', 'name', 'object', 'quantity',
+ 'operators'])
+
+
+ class Name(NameJsonSerializer, db.Model):
__tablename__ = 'names'
__bind_key__ = 'names'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.Text)
+
+ @property
+ def href(self):
+ return url_for('names.name', id=self.id)
+
+ @property
+ def object(self):
+ return StandardName(self.name).object
+
+ @property
+ def quantity(self):
+ return StandardName(self.name).quantity
+
+ @property
+ def operators(self):
+ return StandardName(self.name).operators
def __init__(self, name):
self.name = name
def __repr__(self):
return '<Name %r>' % self.name
- def to_resource(self, brief=False):
- if brief:
- return {'id': self.id, 'name': self.name}
- else:
- sn = StandardName(self.name)
- return {
- 'id': self.id,
- 'href': '/api/names/%d' % self.id,
- 'name': self.name,
- 'object': sn.object,
- 'quantity': sn.quantity,
- 'operators': sn.operators,
- }
- | Use the JsonMixin for the names model. | ## Code Before:
from standard_names import StandardName
from ..core import db
class Name(db.Model):
__tablename__ = 'names'
__bind_key__ = 'names'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.Text)
def __init__(self, name):
self.name = name
def __repr__(self):
return '<Name %r>' % self.name
def to_resource(self, brief=False):
if brief:
return {'id': self.id, 'name': self.name}
else:
sn = StandardName(self.name)
return {
'id': self.id,
'href': '/api/names/%d' % self.id,
'name': self.name,
'object': sn.object,
'quantity': sn.quantity,
'operators': sn.operators,
}
## Instruction:
Use the JsonMixin for the names model.
## Code After:
from flask import url_for
from standard_names import StandardName
from ..core import db, JsonMixin
class NameJsonSerializer(JsonMixin):
__public_fields__ = set(['href', 'id', 'name', 'object', 'quantity',
'operators'])
class Name(NameJsonSerializer, db.Model):
__tablename__ = 'names'
__bind_key__ = 'names'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.Text)
@property
def href(self):
return url_for('names.name', id=self.id)
@property
def object(self):
return StandardName(self.name).object
@property
def quantity(self):
return StandardName(self.name).quantity
@property
def operators(self):
return StandardName(self.name).operators
def __init__(self, name):
self.name = name
def __repr__(self):
return '<Name %r>' % self.name
|
2fac490ed8926bf04e396ded35340f880e9c49b6 | wikilink/db/connection.py | wikilink/db/connection.py | from sqlalchemy import create_engine
from sqlalchemy_utils import functions
from sqlalchemy.orm import sessionmaker
from .base import Base
class Connection:
def __init__(self, db, name, password, ip, port):
if db == "postgresql":
connection = "postgresql+psycopg2://" + name + ":" + password + "@" + ip + ":" + port
elif db == "mysql":
connection = "mysql://" + name + ":" + password + "@" + ip + ":" + port
db_name = 'wikilink'
# Turn off echo
engine = create_engine(connection + "/" + db_name + '?charset=utf8', echo=False, encoding='utf-8')
if not functions.database_exists(engine.url):
functions.create_database(engine.url)
self.session = sessionmaker(bind=engine)()
# If table don't exist, Create.
if (not engine.dialect.has_table(engine, 'link') and not engine.dialect.has_table(engine, 'page')):
Base.metadata.create_all(engine) | from sqlalchemy import create_engine
from sqlalchemy_utils import functions
from sqlalchemy.orm import sessionmaker
from .base import Base
class Connection:
def __init__(self, db, name, password, ip, port):
if db == "postgresql":
connection = "postgresql+psycopg2://" + name + ":" + password + "@" + ip + ":" + port
elif db == "mysql":
connection = "mysql://" + name + ":" + password + "@" + ip + ":" + port
else:
raise ValueError("db type only support \"mysql\" or \"postgresql\" argument.")
db_name = 'wikilink'
# Turn off echo
engine = create_engine(connection + "/" + db_name + '?charset=utf8', echo=False, encoding='utf-8')
if not functions.database_exists(engine.url):
functions.create_database(engine.url)
self.session = sessionmaker(bind=engine)()
# If table don't exist, Create.
if (not engine.dialect.has_table(engine, 'link') and not engine.dialect.has_table(engine, 'page')):
Base.metadata.create_all(engine) | Add exception for wrong type of db | Add exception for wrong type of db
| Python | apache-2.0 | tranlyvu/findLink,tranlyvu/find-link | from sqlalchemy import create_engine
from sqlalchemy_utils import functions
from sqlalchemy.orm import sessionmaker
from .base import Base
class Connection:
def __init__(self, db, name, password, ip, port):
if db == "postgresql":
connection = "postgresql+psycopg2://" + name + ":" + password + "@" + ip + ":" + port
elif db == "mysql":
connection = "mysql://" + name + ":" + password + "@" + ip + ":" + port
-
+ else:
+ raise ValueError("db type only support \"mysql\" or \"postgresql\" argument.")
db_name = 'wikilink'
# Turn off echo
engine = create_engine(connection + "/" + db_name + '?charset=utf8', echo=False, encoding='utf-8')
if not functions.database_exists(engine.url):
functions.create_database(engine.url)
self.session = sessionmaker(bind=engine)()
# If table don't exist, Create.
if (not engine.dialect.has_table(engine, 'link') and not engine.dialect.has_table(engine, 'page')):
Base.metadata.create_all(engine) | Add exception for wrong type of db | ## Code Before:
from sqlalchemy import create_engine
from sqlalchemy_utils import functions
from sqlalchemy.orm import sessionmaker
from .base import Base
class Connection:
def __init__(self, db, name, password, ip, port):
if db == "postgresql":
connection = "postgresql+psycopg2://" + name + ":" + password + "@" + ip + ":" + port
elif db == "mysql":
connection = "mysql://" + name + ":" + password + "@" + ip + ":" + port
db_name = 'wikilink'
# Turn off echo
engine = create_engine(connection + "/" + db_name + '?charset=utf8', echo=False, encoding='utf-8')
if not functions.database_exists(engine.url):
functions.create_database(engine.url)
self.session = sessionmaker(bind=engine)()
# If table don't exist, Create.
if (not engine.dialect.has_table(engine, 'link') and not engine.dialect.has_table(engine, 'page')):
Base.metadata.create_all(engine)
## Instruction:
Add exception for wrong type of db
## Code After:
from sqlalchemy import create_engine
from sqlalchemy_utils import functions
from sqlalchemy.orm import sessionmaker
from .base import Base
class Connection:
def __init__(self, db, name, password, ip, port):
if db == "postgresql":
connection = "postgresql+psycopg2://" + name + ":" + password + "@" + ip + ":" + port
elif db == "mysql":
connection = "mysql://" + name + ":" + password + "@" + ip + ":" + port
else:
raise ValueError("db type only support \"mysql\" or \"postgresql\" argument.")
db_name = 'wikilink'
# Turn off echo
engine = create_engine(connection + "/" + db_name + '?charset=utf8', echo=False, encoding='utf-8')
if not functions.database_exists(engine.url):
functions.create_database(engine.url)
self.session = sessionmaker(bind=engine)()
# If table don't exist, Create.
if (not engine.dialect.has_table(engine, 'link') and not engine.dialect.has_table(engine, 'page')):
Base.metadata.create_all(engine) |
d404b91cc7af75c343c78fe44273a8cff8aa5663 | feincms/module/page/admin.py | feincms/module/page/admin.py |
from __future__ import absolute_import
from django.conf import settings
from django.contrib import admin
from django.core.exceptions import ImproperlyConfigured
from django.db.models import FieldDoesNotExist
from feincms import ensure_completely_loaded
from .models import Page
from .modeladmins import PageAdmin
# ------------------------------------------------------------------------
if getattr(settings, 'FEINCMS_USE_PAGE_ADMIN', True):
ensure_completely_loaded()
try:
Page._meta.get_field('template_key')
except FieldDoesNotExist:
raise ImproperlyConfigured(
"The page module requires a 'Page.register_templates()' call "
"somewhere ('Page.register_regions()' is not sufficient). "
"If you're not using the default Page admin, maybe try "
"FEINCMS_USE_PAGE_ADMIN=False to avoid this warning."
)
admin.site.register(Page, PageAdmin)
# ------------------------------------------------------------------------
# ------------------------------------------------------------------------
|
from __future__ import absolute_import
from django.conf import settings
from django.contrib import admin
from django.core.exceptions import ImproperlyConfigured
from django.db.models import FieldDoesNotExist
from feincms import ensure_completely_loaded
from .models import Page
from .modeladmins import PageAdmin
# ------------------------------------------------------------------------
# XXX move this setting to feincms.settings?
if getattr(settings, 'FEINCMS_USE_PAGE_ADMIN', True):
ensure_completely_loaded()
try:
Page._meta.get_field('template_key')
except FieldDoesNotExist:
raise ImproperlyConfigured(
"The page module requires a 'Page.register_templates()' call "
"somewhere ('Page.register_regions()' is not sufficient). "
"If you're not using the default Page admin, maybe try "
"FEINCMS_USE_PAGE_ADMIN=False to avoid this warning."
)
admin.site.register(Page, PageAdmin)
# ------------------------------------------------------------------------
# ------------------------------------------------------------------------
| Add a note concerning FEINCMS_USE_PAGE_ADMIN | Add a note concerning FEINCMS_USE_PAGE_ADMIN
| Python | bsd-3-clause | joshuajonah/feincms,matthiask/feincms2-content,feincms/feincms,nickburlett/feincms,nickburlett/feincms,feincms/feincms,matthiask/django-content-editor,matthiask/django-content-editor,matthiask/django-content-editor,michaelkuty/feincms,feincms/feincms,michaelkuty/feincms,matthiask/feincms2-content,nickburlett/feincms,mjl/feincms,matthiask/feincms2-content,joshuajonah/feincms,joshuajonah/feincms,nickburlett/feincms,matthiask/django-content-editor,michaelkuty/feincms,joshuajonah/feincms,michaelkuty/feincms,mjl/feincms,mjl/feincms |
from __future__ import absolute_import
from django.conf import settings
from django.contrib import admin
from django.core.exceptions import ImproperlyConfigured
from django.db.models import FieldDoesNotExist
from feincms import ensure_completely_loaded
from .models import Page
from .modeladmins import PageAdmin
# ------------------------------------------------------------------------
+ # XXX move this setting to feincms.settings?
if getattr(settings, 'FEINCMS_USE_PAGE_ADMIN', True):
ensure_completely_loaded()
try:
Page._meta.get_field('template_key')
except FieldDoesNotExist:
raise ImproperlyConfigured(
"The page module requires a 'Page.register_templates()' call "
"somewhere ('Page.register_regions()' is not sufficient). "
"If you're not using the default Page admin, maybe try "
"FEINCMS_USE_PAGE_ADMIN=False to avoid this warning."
)
admin.site.register(Page, PageAdmin)
# ------------------------------------------------------------------------
# ------------------------------------------------------------------------
| Add a note concerning FEINCMS_USE_PAGE_ADMIN | ## Code Before:
from __future__ import absolute_import
from django.conf import settings
from django.contrib import admin
from django.core.exceptions import ImproperlyConfigured
from django.db.models import FieldDoesNotExist
from feincms import ensure_completely_loaded
from .models import Page
from .modeladmins import PageAdmin
# ------------------------------------------------------------------------
if getattr(settings, 'FEINCMS_USE_PAGE_ADMIN', True):
ensure_completely_loaded()
try:
Page._meta.get_field('template_key')
except FieldDoesNotExist:
raise ImproperlyConfigured(
"The page module requires a 'Page.register_templates()' call "
"somewhere ('Page.register_regions()' is not sufficient). "
"If you're not using the default Page admin, maybe try "
"FEINCMS_USE_PAGE_ADMIN=False to avoid this warning."
)
admin.site.register(Page, PageAdmin)
# ------------------------------------------------------------------------
# ------------------------------------------------------------------------
## Instruction:
Add a note concerning FEINCMS_USE_PAGE_ADMIN
## Code After:
from __future__ import absolute_import
from django.conf import settings
from django.contrib import admin
from django.core.exceptions import ImproperlyConfigured
from django.db.models import FieldDoesNotExist
from feincms import ensure_completely_loaded
from .models import Page
from .modeladmins import PageAdmin
# ------------------------------------------------------------------------
# XXX move this setting to feincms.settings?
if getattr(settings, 'FEINCMS_USE_PAGE_ADMIN', True):
ensure_completely_loaded()
try:
Page._meta.get_field('template_key')
except FieldDoesNotExist:
raise ImproperlyConfigured(
"The page module requires a 'Page.register_templates()' call "
"somewhere ('Page.register_regions()' is not sufficient). "
"If you're not using the default Page admin, maybe try "
"FEINCMS_USE_PAGE_ADMIN=False to avoid this warning."
)
admin.site.register(Page, PageAdmin)
# ------------------------------------------------------------------------
# ------------------------------------------------------------------------
|
a8599728ea4b306776b4ba8aa92e333671571e4d | tensorflow_text/python/keras/layers/__init__.py | tensorflow_text/python/keras/layers/__init__.py |
"""Tensorflow Text layers for Keras API."""
from tensorflow.python.util.all_util import remove_undocumented
# pylint: disable=wildcard-import
from tensorflow_text.python.keras.layers.todense import *
# Public symbols in the "tensorflow_text.layers" package.
_allowed_symbols = [
"ToDense",
]
remove_undocumented(__name__, _allowed_symbols)
|
"""Tensorflow Text layers for Keras API."""
from tensorflow.python.util.all_util import remove_undocumented
# pylint: disable=wildcard-import
from tensorflow_text.python.keras.layers.todense import *
from tensorflow_text.python.keras.layers.tokenization_layers import *
# Public symbols in the "tensorflow_text.layers" package.
_allowed_symbols = [
"ToDense",
"UnicodeScriptTokenizer",
"WhitespaceTokenizer",
"WordpieceTokenizer",
]
remove_undocumented(__name__, _allowed_symbols)
| Add missing symbols for tokenization layers | Add missing symbols for tokenization layers
Tokenization layers are now exposed by adding them to the list of allowed symbols.
Cheers | Python | apache-2.0 | tensorflow/text,tensorflow/text,tensorflow/text |
"""Tensorflow Text layers for Keras API."""
from tensorflow.python.util.all_util import remove_undocumented
# pylint: disable=wildcard-import
from tensorflow_text.python.keras.layers.todense import *
+ from tensorflow_text.python.keras.layers.tokenization_layers import *
# Public symbols in the "tensorflow_text.layers" package.
_allowed_symbols = [
"ToDense",
+ "UnicodeScriptTokenizer",
+ "WhitespaceTokenizer",
+ "WordpieceTokenizer",
]
remove_undocumented(__name__, _allowed_symbols)
| Add missing symbols for tokenization layers | ## Code Before:
"""Tensorflow Text layers for Keras API."""
from tensorflow.python.util.all_util import remove_undocumented
# pylint: disable=wildcard-import
from tensorflow_text.python.keras.layers.todense import *
# Public symbols in the "tensorflow_text.layers" package.
_allowed_symbols = [
"ToDense",
]
remove_undocumented(__name__, _allowed_symbols)
## Instruction:
Add missing symbols for tokenization layers
## Code After:
"""Tensorflow Text layers for Keras API."""
from tensorflow.python.util.all_util import remove_undocumented
# pylint: disable=wildcard-import
from tensorflow_text.python.keras.layers.todense import *
from tensorflow_text.python.keras.layers.tokenization_layers import *
# Public symbols in the "tensorflow_text.layers" package.
_allowed_symbols = [
"ToDense",
"UnicodeScriptTokenizer",
"WhitespaceTokenizer",
"WordpieceTokenizer",
]
remove_undocumented(__name__, _allowed_symbols)
|
d9dce6f97019d688750c8143777d2c9e2acd4170 | qtpy/QtOpenGLWidgets.py | qtpy/QtOpenGLWidgets.py |
"""Provides QtOpenGLWidgets classes and functions."""
from . import PYQT5, PYQT6, PYSIDE2, PYSIDE6, QtBindingsNotFoundError, QtBindingMissingModuleError
if PYQT5:
raise QtBindingMissingModuleError(name='QtTextToSpeech')
elif PYQT6:
from PyQt6.QtOpenGLWidgets import *
elif PYSIDE2:
raise QtBindingMissingModuleError(name='QtTextToSpeech')
elif PYSIDE6:
from PySide6.QtOpenGLWidgets import *
else:
raise QtBindingsNotFoundError()
|
"""Provides QtOpenGLWidgets classes and functions."""
from . import PYQT5, PYQT6, PYSIDE2, PYSIDE6, QtBindingsNotFoundError, QtBindingMissingModuleError
if PYQT5:
raise QtBindingMissingModuleError(name='QtOpenGLWidgets')
elif PYQT6:
from PyQt6.QtOpenGLWidgets import *
elif PYSIDE2:
raise QtBindingMissingModuleError(name='QtOpenGLWidgets')
elif PYSIDE6:
from PySide6.QtOpenGLWidgets import *
else:
raise QtBindingsNotFoundError()
| Fix wrong module name in error message | Fix wrong module name in error message
| Python | mit | spyder-ide/qtpy |
"""Provides QtOpenGLWidgets classes and functions."""
from . import PYQT5, PYQT6, PYSIDE2, PYSIDE6, QtBindingsNotFoundError, QtBindingMissingModuleError
if PYQT5:
- raise QtBindingMissingModuleError(name='QtTextToSpeech')
+ raise QtBindingMissingModuleError(name='QtOpenGLWidgets')
elif PYQT6:
from PyQt6.QtOpenGLWidgets import *
elif PYSIDE2:
- raise QtBindingMissingModuleError(name='QtTextToSpeech')
+ raise QtBindingMissingModuleError(name='QtOpenGLWidgets')
elif PYSIDE6:
from PySide6.QtOpenGLWidgets import *
else:
raise QtBindingsNotFoundError()
| Fix wrong module name in error message | ## Code Before:
"""Provides QtOpenGLWidgets classes and functions."""
from . import PYQT5, PYQT6, PYSIDE2, PYSIDE6, QtBindingsNotFoundError, QtBindingMissingModuleError
if PYQT5:
raise QtBindingMissingModuleError(name='QtTextToSpeech')
elif PYQT6:
from PyQt6.QtOpenGLWidgets import *
elif PYSIDE2:
raise QtBindingMissingModuleError(name='QtTextToSpeech')
elif PYSIDE6:
from PySide6.QtOpenGLWidgets import *
else:
raise QtBindingsNotFoundError()
## Instruction:
Fix wrong module name in error message
## Code After:
"""Provides QtOpenGLWidgets classes and functions."""
from . import PYQT5, PYQT6, PYSIDE2, PYSIDE6, QtBindingsNotFoundError, QtBindingMissingModuleError
if PYQT5:
raise QtBindingMissingModuleError(name='QtOpenGLWidgets')
elif PYQT6:
from PyQt6.QtOpenGLWidgets import *
elif PYSIDE2:
raise QtBindingMissingModuleError(name='QtOpenGLWidgets')
elif PYSIDE6:
from PySide6.QtOpenGLWidgets import *
else:
raise QtBindingsNotFoundError()
|
2021cdbe3304c91af03d9664e05c9bbc1a197f4d | python/ql/test/experimental/library-tests/frameworks/yaml/Decoding.py | python/ql/test/experimental/library-tests/frameworks/yaml/Decoding.py | import yaml
from yaml import SafeLoader
yaml.load(payload) # $decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML decodeMayExecuteInput
yaml.load(payload, Loader=SafeLoader) # $decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML
yaml.load(payload, Loader=yaml.BaseLoader) # $decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML
| import yaml
from yaml import SafeLoader
yaml.load(payload) # $decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML decodeMayExecuteInput
yaml.load(payload, SafeLoader) # $ decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML SPURIOUS: decodeMayExecuteInput
yaml.load(payload, Loader=SafeLoader) # $decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML
yaml.load(payload, Loader=yaml.BaseLoader) # $decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML
yaml.safe_load(payload) # $ MISSING: decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML
yaml.unsafe_load(payload) # $ MISSING: decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML decodeMayExecuteInput
yaml.full_load(payload) # $ MISSING: decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML decodeMayExecuteInput
yaml.load_all(payload) # $ MISSING: decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML decodeMayExecuteInput
yaml.safe_load_all(payload) # $ MISSING: decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML
yaml.unsafe_load_all(payload) # $ MISSING: decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML decodeMayExecuteInput
yaml.full_load_all(payload) # $ MISSING: decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML decodeMayExecuteInput
| Add tests for more yaml loading functions | Python: Add tests for more yaml loading functions
| Python | mit | github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql | import yaml
from yaml import SafeLoader
yaml.load(payload) # $decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML decodeMayExecuteInput
+ yaml.load(payload, SafeLoader) # $ decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML SPURIOUS: decodeMayExecuteInput
yaml.load(payload, Loader=SafeLoader) # $decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML
yaml.load(payload, Loader=yaml.BaseLoader) # $decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML
+ yaml.safe_load(payload) # $ MISSING: decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML
+ yaml.unsafe_load(payload) # $ MISSING: decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML decodeMayExecuteInput
+ yaml.full_load(payload) # $ MISSING: decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML decodeMayExecuteInput
+
+ yaml.load_all(payload) # $ MISSING: decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML decodeMayExecuteInput
+ yaml.safe_load_all(payload) # $ MISSING: decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML
+ yaml.unsafe_load_all(payload) # $ MISSING: decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML decodeMayExecuteInput
+ yaml.full_load_all(payload) # $ MISSING: decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML decodeMayExecuteInput
+ | Add tests for more yaml loading functions | ## Code Before:
import yaml
from yaml import SafeLoader
yaml.load(payload) # $decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML decodeMayExecuteInput
yaml.load(payload, Loader=SafeLoader) # $decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML
yaml.load(payload, Loader=yaml.BaseLoader) # $decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML
## Instruction:
Add tests for more yaml loading functions
## Code After:
import yaml
from yaml import SafeLoader
yaml.load(payload) # $decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML decodeMayExecuteInput
yaml.load(payload, SafeLoader) # $ decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML SPURIOUS: decodeMayExecuteInput
yaml.load(payload, Loader=SafeLoader) # $decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML
yaml.load(payload, Loader=yaml.BaseLoader) # $decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML
yaml.safe_load(payload) # $ MISSING: decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML
yaml.unsafe_load(payload) # $ MISSING: decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML decodeMayExecuteInput
yaml.full_load(payload) # $ MISSING: decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML decodeMayExecuteInput
yaml.load_all(payload) # $ MISSING: decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML decodeMayExecuteInput
yaml.safe_load_all(payload) # $ MISSING: decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML
yaml.unsafe_load_all(payload) # $ MISSING: decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML decodeMayExecuteInput
yaml.full_load_all(payload) # $ MISSING: decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML decodeMayExecuteInput
|
b535dcc490f56a54b92443172ad0b5828bc5a540 | rpcd/playbooks/roles/horizon_extensions/templates/_50_rackspace.py | rpcd/playbooks/roles/horizon_extensions/templates/_50_rackspace.py | DASHBOARD = 'rackspace'
ADD_INSTALLED_APPS = [
'rackspace',
]
# If set to True, this dashboard will not be added to the settings.
DISABLED = False
| DASHBOARD = 'rackspace'
ADD_INSTALLED_APPS = [
'rackspace',
]
ADD_ANGULAR_MODULES = ['horizon.dashboard.rackspace']
# If set to True, this dashboard will not be added to the settings.
DISABLED = False
| Fix enabled file installed from horizon-extensions | Fix enabled file installed from horizon-extensions
Add the angularjs module containing the Rackspace Solutions
panel code to the Horizon application so it works.
Requires accompanying patch
https://github.com/rcbops/horizon-extensions/pull/7
for the panel to work with this change.
closes 891
| Python | apache-2.0 | cfarquhar/rpc-openstack,galstrom21/rpc-openstack,mancdaz/rpc-openstack,sigmavirus24/rpc-openstack,cloudnull/rpc-openstack,major/rpc-openstack,darrenchan/rpc-openstack,cfarquhar/rpc-openstack,mancdaz/rpc-openstack,git-harry/rpc-openstack,darrenchan/rpc-openstack,xeregin/rpc-openstack,prometheanfire/rpc-openstack,robb-romans/rpc-openstack,shannonmitchell/rpc-openstack,rcbops/rpc-openstack,darrenchan/rpc-openstack,sigmavirus24/rpc-openstack,rcbops/rpc-openstack,git-harry/rpc-openstack,jacobwagner/rpc-openstack,byronmccollum/rpc-openstack,sigmavirus24/rpc-openstack,byronmccollum/rpc-openstack,xeregin/rpc-openstack,byronmccollum/rpc-openstack,sigmavirus24/rpc-openstack,xeregin/rpc-openstack,hughsaunders/rpc-openstack,galstrom21/rpc-openstack,cloudnull/rpc-openstack,BjoernT/rpc-openstack,major/rpc-openstack,shannonmitchell/rpc-openstack,xeregin/rpc-openstack,darrenchan/rpc-openstack,robb-romans/rpc-openstack,prometheanfire/rpc-openstack,BjoernT/rpc-openstack,jacobwagner/rpc-openstack,hughsaunders/rpc-openstack | DASHBOARD = 'rackspace'
ADD_INSTALLED_APPS = [
'rackspace',
]
+ ADD_ANGULAR_MODULES = ['horizon.dashboard.rackspace']
+
# If set to True, this dashboard will not be added to the settings.
DISABLED = False
| Fix enabled file installed from horizon-extensions | ## Code Before:
DASHBOARD = 'rackspace'
ADD_INSTALLED_APPS = [
'rackspace',
]
# If set to True, this dashboard will not be added to the settings.
DISABLED = False
## Instruction:
Fix enabled file installed from horizon-extensions
## Code After:
DASHBOARD = 'rackspace'
ADD_INSTALLED_APPS = [
'rackspace',
]
ADD_ANGULAR_MODULES = ['horizon.dashboard.rackspace']
# If set to True, this dashboard will not be added to the settings.
DISABLED = False
|
3d5eaf13597bd7cab5dc09e1030b803701f0872f | genda/genders/models.py | genda/genders/models.py | from django.db import models
from django.conf import settings
class Gender(models.Model):
name = models.CharField(max_length=20)
def __str__(self):
return self.name
__repr__ = __str__
class UserToPronoun(models.Model):
email_hash = models.CharField(max_length=32)
user = models.ForeignKey(settings.AUTH_USER_MODEL, unique=True)
default_pronoun = models.ForeignKey('Pronoun')
default_gender = models.ForeignKey('Gender', null=True)
class Pronoun(models.Model):
object_word = models.CharField(max_length=10) # them
subject_word = models.CharField(max_length=10) # they
self_word = models.CharField(max_length=10) # themself
owner_word = models.CharField(max_length=10) # their
is_custom = models.BooleanField(default=True)
def __str__(self):
return '{}/{}/{}/{}'.format(
self.object_word,
self.subject_word,
self.self_word,
self.owner_word
)
__repr__ = __str__
| from django.db import models
from django.conf import settings
class Gender(models.Model):
name = models.CharField(max_length=20)
def __str__(self):
return self.name
__repr__ = lambda self: '<{}>'.format(self.__str__())
class UserToPronoun(models.Model):
email_hash = models.CharField(max_length=32)
user = models.ForeignKey(settings.AUTH_USER_MODEL, unique=True)
default_pronoun = models.ForeignKey('Pronoun')
default_gender = models.ForeignKey('Gender', null=True)
def __str__(self):
return '<{} prefers {}>'.format(
self.user.username, self.default_pronoun
)
__repr__ = __str__
class Pronoun(models.Model):
object_word = models.CharField(max_length=10) # them
subject_word = models.CharField(max_length=10) # they
self_word = models.CharField(max_length=10) # themself
owner_word = models.CharField(max_length=10) # their
is_custom = models.BooleanField(default=True)
def __str__(self):
return '{}/{}/{}/{}'.format(
self.object_word,
self.subject_word,
self.self_word,
self.owner_word
)
__repr__ = lambda self: '<{}>'.format(self.__str__())
| Correct __str__ & __repr__ implementations | Correct __str__ & __repr__ implementations
| Python | mit | Mause/Genda,Mause/Genda | from django.db import models
from django.conf import settings
class Gender(models.Model):
name = models.CharField(max_length=20)
def __str__(self):
return self.name
- __repr__ = __str__
+ __repr__ = lambda self: '<{}>'.format(self.__str__())
class UserToPronoun(models.Model):
email_hash = models.CharField(max_length=32)
user = models.ForeignKey(settings.AUTH_USER_MODEL, unique=True)
default_pronoun = models.ForeignKey('Pronoun')
default_gender = models.ForeignKey('Gender', null=True)
+
+ def __str__(self):
+ return '<{} prefers {}>'.format(
+ self.user.username, self.default_pronoun
+ )
+
+ __repr__ = __str__
class Pronoun(models.Model):
object_word = models.CharField(max_length=10) # them
subject_word = models.CharField(max_length=10) # they
self_word = models.CharField(max_length=10) # themself
owner_word = models.CharField(max_length=10) # their
is_custom = models.BooleanField(default=True)
def __str__(self):
return '{}/{}/{}/{}'.format(
self.object_word,
self.subject_word,
self.self_word,
self.owner_word
)
- __repr__ = __str__
+ __repr__ = lambda self: '<{}>'.format(self.__str__())
| Correct __str__ & __repr__ implementations | ## Code Before:
from django.db import models
from django.conf import settings
class Gender(models.Model):
name = models.CharField(max_length=20)
def __str__(self):
return self.name
__repr__ = __str__
class UserToPronoun(models.Model):
email_hash = models.CharField(max_length=32)
user = models.ForeignKey(settings.AUTH_USER_MODEL, unique=True)
default_pronoun = models.ForeignKey('Pronoun')
default_gender = models.ForeignKey('Gender', null=True)
class Pronoun(models.Model):
object_word = models.CharField(max_length=10) # them
subject_word = models.CharField(max_length=10) # they
self_word = models.CharField(max_length=10) # themself
owner_word = models.CharField(max_length=10) # their
is_custom = models.BooleanField(default=True)
def __str__(self):
return '{}/{}/{}/{}'.format(
self.object_word,
self.subject_word,
self.self_word,
self.owner_word
)
__repr__ = __str__
## Instruction:
Correct __str__ & __repr__ implementations
## Code After:
from django.db import models
from django.conf import settings
class Gender(models.Model):
name = models.CharField(max_length=20)
def __str__(self):
return self.name
__repr__ = lambda self: '<{}>'.format(self.__str__())
class UserToPronoun(models.Model):
email_hash = models.CharField(max_length=32)
user = models.ForeignKey(settings.AUTH_USER_MODEL, unique=True)
default_pronoun = models.ForeignKey('Pronoun')
default_gender = models.ForeignKey('Gender', null=True)
def __str__(self):
return '<{} prefers {}>'.format(
self.user.username, self.default_pronoun
)
__repr__ = __str__
class Pronoun(models.Model):
object_word = models.CharField(max_length=10) # them
subject_word = models.CharField(max_length=10) # they
self_word = models.CharField(max_length=10) # themself
owner_word = models.CharField(max_length=10) # their
is_custom = models.BooleanField(default=True)
def __str__(self):
return '{}/{}/{}/{}'.format(
self.object_word,
self.subject_word,
self.self_word,
self.owner_word
)
__repr__ = lambda self: '<{}>'.format(self.__str__())
|
5354a39d62edc12cd5dbea6b1912bf6bdf846999 | test_migrations/migrate_test/app/models.py | test_migrations/migrate_test/app/models.py | from __future__ import unicode_literals
from django.db import models
# from modeltrans.fields import TranslationField
class Category(models.Model):
name = models.CharField(max_length=255)
# i18n = TranslationField(fields=('name', ))
class Meta:
verbose_name_plural = 'categories'
def __str__(self):
return self.name
class Blog(models.Model):
title = models.CharField(max_length=255)
body = models.TextField(null=True, blank=True)
category = models.ForeignKey(Category, null=True, blank=True)
# i18n = TranslationField(fields=('title', 'body'))
def __str__(self):
return self.title
| from __future__ import unicode_literals
from django.db import models
# from modeltrans.fields import TranslationField
class Category(models.Model):
name = models.CharField(max_length=255)
# i18n = TranslationField(fields=('name', ), virtual_fields=False)
class Meta:
verbose_name_plural = 'categories'
def __str__(self):
return self.name
class Blog(models.Model):
title = models.CharField(max_length=255)
body = models.TextField(null=True, blank=True)
category = models.ForeignKey(Category, null=True, blank=True)
# i18n = TranslationField(fields=('title', 'body'), virtual_fields=False)
def __str__(self):
return self.title
| Disable adding virtual fields during migration | Disable adding virtual fields during migration
| Python | bsd-3-clause | zostera/django-modeltrans,zostera/django-modeltrans | from __future__ import unicode_literals
from django.db import models
# from modeltrans.fields import TranslationField
class Category(models.Model):
name = models.CharField(max_length=255)
- # i18n = TranslationField(fields=('name', ))
+ # i18n = TranslationField(fields=('name', ), virtual_fields=False)
class Meta:
verbose_name_plural = 'categories'
def __str__(self):
return self.name
class Blog(models.Model):
title = models.CharField(max_length=255)
body = models.TextField(null=True, blank=True)
category = models.ForeignKey(Category, null=True, blank=True)
- # i18n = TranslationField(fields=('title', 'body'))
+ # i18n = TranslationField(fields=('title', 'body'), virtual_fields=False)
def __str__(self):
return self.title
| Disable adding virtual fields during migration | ## Code Before:
from __future__ import unicode_literals
from django.db import models
# from modeltrans.fields import TranslationField
class Category(models.Model):
name = models.CharField(max_length=255)
# i18n = TranslationField(fields=('name', ))
class Meta:
verbose_name_plural = 'categories'
def __str__(self):
return self.name
class Blog(models.Model):
title = models.CharField(max_length=255)
body = models.TextField(null=True, blank=True)
category = models.ForeignKey(Category, null=True, blank=True)
# i18n = TranslationField(fields=('title', 'body'))
def __str__(self):
return self.title
## Instruction:
Disable adding virtual fields during migration
## Code After:
from __future__ import unicode_literals
from django.db import models
# from modeltrans.fields import TranslationField
class Category(models.Model):
name = models.CharField(max_length=255)
# i18n = TranslationField(fields=('name', ), virtual_fields=False)
class Meta:
verbose_name_plural = 'categories'
def __str__(self):
return self.name
class Blog(models.Model):
title = models.CharField(max_length=255)
body = models.TextField(null=True, blank=True)
category = models.ForeignKey(Category, null=True, blank=True)
# i18n = TranslationField(fields=('title', 'body'), virtual_fields=False)
def __str__(self):
return self.title
|
c7514e73eff70514659db9ff27aaccf50e99c4c5 | account_wallet/models/account_move.py | account_wallet/models/account_move.py |
from odoo import api, fields, models
class AccountInvoice(models.Model):
_inherit = "account.move"
account_wallet_type_id = fields.Many2one(
comodel_name='account.wallet.type',
string='Wallet type',
readonly=True,
ondelete='restrict',
help="Use this field to give coupon to a customer",
states={'draft': [('readonly', False)]},
)
@api.onchange("account_wallet_type_id")
def onchange_account_wallet_type_id(self):
if self.account_wallet_type_id:
self.account_id = self.account_wallet_type_id.account_id
def invoice_line_move_line_get(self):
"""
Create move line with cagnotte id if needed
:return:
"""
res = super(AccountInvoice, self).invoice_line_move_line_get()
wallet_lines = self.invoice_line_ids.filtered("account_cagnotte_id")
for line_val in res:
invl_id = line_val.get("invl_id")
if invl_id in wallet_lines.ids:
line_val.update({
"account_cagnotte_id": wallet_lines.filtered(
lambda c, l_id=invl_id: c.id == l_id).mapped(
"account_wallet_id").id})
return res
@api.model
def line_get_convert(self, line, part):
res = super(AccountInvoice, self).line_get_convert(line, part)
wallet_id = line.get("account_cagnotte_id")
if wallet_id:
res.update({"account_wallet_id": wallet_id})
return res
|
from odoo import api, fields, models
class AccountMove(models.Model):
_inherit = "account.move"
account_wallet_type_id = fields.Many2one(
comodel_name='account.wallet.type',
string='Wallet type',
readonly=True,
ondelete='restrict',
help="Use this field to give coupon to a customer",
states={'draft': [('readonly', False)]},
)
@api.onchange("account_wallet_type_id")
def onchange_account_wallet_type_id(self):
if self.account_wallet_type_id:
self.account_id = self.account_wallet_type_id.account_id
| Remove former methods as models have been merged | [14.0][IMP] account_wallet: Remove former methods as models have been merged
| Python | agpl-3.0 | acsone/acsone-addons,acsone/acsone-addons,acsone/acsone-addons |
from odoo import api, fields, models
- class AccountInvoice(models.Model):
+ class AccountMove(models.Model):
_inherit = "account.move"
account_wallet_type_id = fields.Many2one(
comodel_name='account.wallet.type',
string='Wallet type',
readonly=True,
ondelete='restrict',
help="Use this field to give coupon to a customer",
states={'draft': [('readonly', False)]},
)
@api.onchange("account_wallet_type_id")
def onchange_account_wallet_type_id(self):
if self.account_wallet_type_id:
self.account_id = self.account_wallet_type_id.account_id
- def invoice_line_move_line_get(self):
- """
- Create move line with cagnotte id if needed
- :return:
- """
- res = super(AccountInvoice, self).invoice_line_move_line_get()
- wallet_lines = self.invoice_line_ids.filtered("account_cagnotte_id")
- for line_val in res:
- invl_id = line_val.get("invl_id")
- if invl_id in wallet_lines.ids:
- line_val.update({
- "account_cagnotte_id": wallet_lines.filtered(
- lambda c, l_id=invl_id: c.id == l_id).mapped(
- "account_wallet_id").id})
- return res
-
- @api.model
- def line_get_convert(self, line, part):
- res = super(AccountInvoice, self).line_get_convert(line, part)
- wallet_id = line.get("account_cagnotte_id")
- if wallet_id:
- res.update({"account_wallet_id": wallet_id})
- return res
- | Remove former methods as models have been merged | ## Code Before:
from odoo import api, fields, models
class AccountInvoice(models.Model):
_inherit = "account.move"
account_wallet_type_id = fields.Many2one(
comodel_name='account.wallet.type',
string='Wallet type',
readonly=True,
ondelete='restrict',
help="Use this field to give coupon to a customer",
states={'draft': [('readonly', False)]},
)
@api.onchange("account_wallet_type_id")
def onchange_account_wallet_type_id(self):
if self.account_wallet_type_id:
self.account_id = self.account_wallet_type_id.account_id
def invoice_line_move_line_get(self):
"""
Create move line with cagnotte id if needed
:return:
"""
res = super(AccountInvoice, self).invoice_line_move_line_get()
wallet_lines = self.invoice_line_ids.filtered("account_cagnotte_id")
for line_val in res:
invl_id = line_val.get("invl_id")
if invl_id in wallet_lines.ids:
line_val.update({
"account_cagnotte_id": wallet_lines.filtered(
lambda c, l_id=invl_id: c.id == l_id).mapped(
"account_wallet_id").id})
return res
@api.model
def line_get_convert(self, line, part):
res = super(AccountInvoice, self).line_get_convert(line, part)
wallet_id = line.get("account_cagnotte_id")
if wallet_id:
res.update({"account_wallet_id": wallet_id})
return res
## Instruction:
Remove former methods as models have been merged
## Code After:
from odoo import api, fields, models
class AccountMove(models.Model):
_inherit = "account.move"
account_wallet_type_id = fields.Many2one(
comodel_name='account.wallet.type',
string='Wallet type',
readonly=True,
ondelete='restrict',
help="Use this field to give coupon to a customer",
states={'draft': [('readonly', False)]},
)
@api.onchange("account_wallet_type_id")
def onchange_account_wallet_type_id(self):
if self.account_wallet_type_id:
self.account_id = self.account_wallet_type_id.account_id
|
a3bf9240424700f21b1e89b4663ca4e5c12d78ef | django_yadt/utils.py | django_yadt/utils.py | from django.db import models
from django.core.management.base import CommandError
def get_variant(app_label, model_name, field_name, variant_name):
model = models.get_model(app_label, model_name)
if model is None:
raise CommandError("%s.%s is not a valid model name" % (
app_label,
model_name,
))
try:
field = getattr(model, field_name)
except AttributeError:
raise CommandError("%s.%s has no field %s" % (
app_label,
model_name,
field_name,
))
try:
return getattr(field, variant_name)
except AttributeError:
raise CommandError("%s.%s.%s has no variant %s" % (
app_label,
model_name,
field_name,
variant_name,
))
| import os
from django.db import models
from django.core.management.base import CommandError
from .fields import IMAGE_VARIANTS
def get_variant(app_label, model_name, field_name, variant_name):
model = models.get_model(app_label, model_name)
if model is None:
raise CommandError("%s.%s is not a valid model name" % (
app_label,
model_name,
))
try:
field = getattr(model, field_name)
except AttributeError:
raise CommandError("%s.%s has no field %s" % (
app_label,
model_name,
field_name,
))
try:
return getattr(field, variant_name)
except AttributeError:
raise CommandError("%s.%s.%s has no variant %s" % (
app_label,
model_name,
field_name,
variant_name,
))
def get_variant_from_path(path):
for variant in IMAGE_VARIANTS:
# Append '' so we don't accidentally match a prefix
dirname = os.path.join(variant.field.upload_to, variant.name, '')
if path.startswith(dirname):
return variant
return None
| Add a utility for local installations to use the fallback mechanism too. | Add a utility for local installations to use the fallback mechanism too.
Signed-off-by: Chris Lamb <711c73f64afdce07b7e38039a96d2224209e9a6c@thread.com>
| Python | bsd-3-clause | lamby/django-yadt,thread/django-yadt | + import os
+
from django.db import models
from django.core.management.base import CommandError
+
+ from .fields import IMAGE_VARIANTS
def get_variant(app_label, model_name, field_name, variant_name):
model = models.get_model(app_label, model_name)
if model is None:
raise CommandError("%s.%s is not a valid model name" % (
app_label,
model_name,
))
try:
field = getattr(model, field_name)
except AttributeError:
raise CommandError("%s.%s has no field %s" % (
app_label,
model_name,
field_name,
))
try:
return getattr(field, variant_name)
except AttributeError:
raise CommandError("%s.%s.%s has no variant %s" % (
app_label,
model_name,
field_name,
variant_name,
))
+ def get_variant_from_path(path):
+ for variant in IMAGE_VARIANTS:
+ # Append '' so we don't accidentally match a prefix
+ dirname = os.path.join(variant.field.upload_to, variant.name, '')
+
+ if path.startswith(dirname):
+ return variant
+
+ return None
+ | Add a utility for local installations to use the fallback mechanism too. | ## Code Before:
from django.db import models
from django.core.management.base import CommandError
def get_variant(app_label, model_name, field_name, variant_name):
model = models.get_model(app_label, model_name)
if model is None:
raise CommandError("%s.%s is not a valid model name" % (
app_label,
model_name,
))
try:
field = getattr(model, field_name)
except AttributeError:
raise CommandError("%s.%s has no field %s" % (
app_label,
model_name,
field_name,
))
try:
return getattr(field, variant_name)
except AttributeError:
raise CommandError("%s.%s.%s has no variant %s" % (
app_label,
model_name,
field_name,
variant_name,
))
## Instruction:
Add a utility for local installations to use the fallback mechanism too.
## Code After:
import os
from django.db import models
from django.core.management.base import CommandError
from .fields import IMAGE_VARIANTS
def get_variant(app_label, model_name, field_name, variant_name):
model = models.get_model(app_label, model_name)
if model is None:
raise CommandError("%s.%s is not a valid model name" % (
app_label,
model_name,
))
try:
field = getattr(model, field_name)
except AttributeError:
raise CommandError("%s.%s has no field %s" % (
app_label,
model_name,
field_name,
))
try:
return getattr(field, variant_name)
except AttributeError:
raise CommandError("%s.%s.%s has no variant %s" % (
app_label,
model_name,
field_name,
variant_name,
))
def get_variant_from_path(path):
for variant in IMAGE_VARIANTS:
# Append '' so we don't accidentally match a prefix
dirname = os.path.join(variant.field.upload_to, variant.name, '')
if path.startswith(dirname):
return variant
return None
|
b16bd59125fc5a800f5806f713fda3da4446d73c | pokemongo_bot/cell_workers/utils.py | pokemongo_bot/cell_workers/utils.py |
import struct
from math import cos, asin, sqrt
def distance(lat1, lon1, lat2, lon2):
p = 0.017453292519943295
a = 0.5 - cos((lat2 - lat1) * p)/2 + cos(lat1 * p) * cos(lat2 * p) * (1 - cos((lon2 - lon1) * p)) / 2
return 12742 * asin(sqrt(a)) * 1000
def i2f(int):
return struct.unpack('<d', struct.pack('<Q', int))[0]
def print_green(message):
print('\033[92m' + message + '\033[0m');
def print_yellow(message):
print('\033[93m' + message + '\033[0m');
def print_red(message):
print('\033[91m' + message + '\033[0m');
|
import struct
from math import cos, asin, sqrt
def distance(lat1, lon1, lat2, lon2):
p = 0.017453292519943295
a = 0.5 - cos((lat2 - lat1) * p)/2 + cos(lat1 * p) * cos(lat2 * p) * (1 - cos((lon2 - lon1) * p)) / 2
return 12742 * asin(sqrt(a)) * 1000
def i2f(int):
return struct.unpack('<d', struct.pack('<Q', int))[0]
def print_green(message):
print(u'\033[92m' + message.decode('utf-8') + '\033[0m');
def print_yellow(message):
print(u'\033[93m' + message.decode('utf-8') + '\033[0m');
def print_red(message):
print(u'\033[91m' + message.decode('utf-8') + '\033[0m');
| Fix encoding error when printing messages | Fix encoding error when printing messages
Some messages that will be printed will contain utf-8 chars, e.g. Pokestops in European locations. | Python | mit | joergpatz/PokemonGo-Bot,dtee/PokemonGo-Bot,lythien/pokemongo,codybaldwin/PokemonGo-Bot,dhluong90/PokemonGo-Bot,dtee/PokemonGo-Bot,Gobberwart/PokemonGo-Bot,tibotic/simple-pokemongo-bot,yahwes/PokemonGo-Bot,Gobberwart/PokemonGo-Bot,Gobberwart/PokemonGo-Bot,halsafar/PokemonGo-Bot,bbiiggppiigg/PokemonGo-Bot,heihachi/PokemonGo-Bot,sinistance/PokemonGo-Bot,Shoh/PokemonGo-Bot,dmateusp/PokemonGo-Bot,sinistance/PokemonGo-Bot,bbiiggppiigg/PokemonGo-Bot,goedzo/PokemonGo-Bot,Shoh/PokemonGo-Bot,AMiketta/PokemonGo-Bot,pokemongo-dev/PokemonGo-Bot,cmezh/PokemonGo-Bot,DayBr3ak/PokemonGo-Bot,joergpatz/PokemonGo-Bot,heihachi/PokemonGo-Bot,goedzo/PokemonGo-Bot,lythien/pokemongo,Quantra/PokemonGo-Bot,lythien/pokemongo,cmezh/PokemonGo-Bot,halsafar/PokemonGo-Bot,pengzhangdev/PokemonGo-Bot,reddivision/PokemonGo-Bot,AbelIngrand/PokemonGo-Bot,DBa2016/PokemonGo-Bot,bbiiggppiigg/PokemonGo-Bot,jasonliu119/PokemonGo-Bot,AcorpBG/PokemonGo-Bot,chadsaun/PokemonGo-Bot,AcorpBG/PokemonGo-Bot,codybaldwin/PokemonGo-Bot,goshan/PokemonGo-Bot,jasonliu119/PokemonGo-Bot,dhluong90/PokemonGo-Bot,yahwes/PokemonGo-Bot,Lordness/poklord,geminiyellow/PokemonGo-Bot,reddivision/PokemonGo-Bot,halsafar/PokemonGo-Bot,Compjeff/PokemonGo-Bot,bbiiggppiigg/PokemonGo-Bot,AMiketta/PokemonGo-Bot,tibotic/simple-pokemongo-bot,geminiyellow/PokemonGo-Bot,AbelIngrand/PokemonGo-Bot,pengzhangdev/PokemonGo-Bot,cmezh/PokemonGo-Bot,pokemongo-dev/PokemonGo-Bot,lythien/pokemongo,goedzo/PokemonGo-Bot,DBa2016/PokemonGo-Bot,dtee/PokemonGo-Bot,cmezh/PokemonGo-Bot,heihachi/PokemonGo-Bot,Quantra/PokemonGo-Bot,Compjeff/PokemonGo-Bot,Gobberwart/PokemonGo-Bot,pengzhangdev/PokemonGo-Bot,heihachi/PokemonGo-Bot,earthchie/PokemonGo-Bot,halsafar/PokemonGo-Bot,Moonlight-Angel/PokemonGo-Bot,DBa2016/PokemonGo-Bot,dtee/PokemonGo-Bot,dhluong90/PokemonGo-Bot,goedzo/PokemonGo-Bot,earthchie/PokemonGo-Bot,DBa2016/PokemonGo-Bot,chadsaun/PokemonGo-Bot,Lordness/poklord,Moonlight-Angel/PokemonGo-Bot,dhluong90/PokemonGo-Bot,dmateusp/PokemonGo-Bot,DayBr3ak/PokemonGo-Bot,goshan/PokemonGo-Bot,pengzhangdev/PokemonGo-Bot |
import struct
from math import cos, asin, sqrt
def distance(lat1, lon1, lat2, lon2):
p = 0.017453292519943295
a = 0.5 - cos((lat2 - lat1) * p)/2 + cos(lat1 * p) * cos(lat2 * p) * (1 - cos((lon2 - lon1) * p)) / 2
return 12742 * asin(sqrt(a)) * 1000
def i2f(int):
return struct.unpack('<d', struct.pack('<Q', int))[0]
def print_green(message):
- print('\033[92m' + message + '\033[0m');
+ print(u'\033[92m' + message.decode('utf-8') + '\033[0m');
def print_yellow(message):
- print('\033[93m' + message + '\033[0m');
+ print(u'\033[93m' + message.decode('utf-8') + '\033[0m');
def print_red(message):
- print('\033[91m' + message + '\033[0m');
+ print(u'\033[91m' + message.decode('utf-8') + '\033[0m');
| Fix encoding error when printing messages | ## Code Before:
import struct
from math import cos, asin, sqrt
def distance(lat1, lon1, lat2, lon2):
p = 0.017453292519943295
a = 0.5 - cos((lat2 - lat1) * p)/2 + cos(lat1 * p) * cos(lat2 * p) * (1 - cos((lon2 - lon1) * p)) / 2
return 12742 * asin(sqrt(a)) * 1000
def i2f(int):
return struct.unpack('<d', struct.pack('<Q', int))[0]
def print_green(message):
print('\033[92m' + message + '\033[0m');
def print_yellow(message):
print('\033[93m' + message + '\033[0m');
def print_red(message):
print('\033[91m' + message + '\033[0m');
## Instruction:
Fix encoding error when printing messages
## Code After:
import struct
from math import cos, asin, sqrt
def distance(lat1, lon1, lat2, lon2):
p = 0.017453292519943295
a = 0.5 - cos((lat2 - lat1) * p)/2 + cos(lat1 * p) * cos(lat2 * p) * (1 - cos((lon2 - lon1) * p)) / 2
return 12742 * asin(sqrt(a)) * 1000
def i2f(int):
return struct.unpack('<d', struct.pack('<Q', int))[0]
def print_green(message):
print(u'\033[92m' + message.decode('utf-8') + '\033[0m');
def print_yellow(message):
print(u'\033[93m' + message.decode('utf-8') + '\033[0m');
def print_red(message):
print(u'\033[91m' + message.decode('utf-8') + '\033[0m');
|
a1f93a76782b0bf406a16d36f0f60aea8b855566 | cogs/points.py | cogs/points.py | from discord.ext import commands
from utils import *
import discord
import asyncio
import sqlite3
from member import Member
class Points:
def __init__(self,bot):
self.bot = bot
#Test method to populate an array from discord -Infinite
@commands.command()
@commands.has_role('Leadership')
@asyncio.coroutine
def getmembers(self, role1 : discord.Role=None):
therole = role1
#Typing function
yield from self.bot.type()
#Intialize array
listOfMembers = []
#Add members to array
for amember in self.bot.get_all_members():
arole = [role for role in amember.roles if role == therole]
if arole == therole:
listOfMembers.append(Member(int(amember.id),str(amember.name),str(amember.nick),str(amember.top_role),0))
length = len(listOfMembers)
yield from self.bot.say("Number of " + str(therole) + "s in array: " + str(length))
def setup(bot):
bot.add_cog(Points(bot))
| from discord.ext import commands
from utils import *
import discord
import asyncio
import sqlite3
from member import Member
class Points:
def __init__(self,bot):
self.bot = bot
#Test method to populate an array from discord -Infinite
@commands.command()
@commands.has_role('Leadership')
@asyncio.coroutine
def getmembers(self, role1 : discord.Role=None):
therole = role1
#Typing function
yield from self.bot.type()
#Intialize array
listOfMembers = []
#Add members to array
for amember in self.bot.get_all_members():
arole = [role for role in amember.roles if role == therole]
if arole:
if arole[0].name == therole.name:
listOfMembers.append(Member(int(amember.id),str(amember.name),str(amember.nick),str(amember.top_role),0))
length = len(listOfMembers)
yield from self.bot.say("Number of " + str(therole) + "s in array: " + str(length))
def setup(bot):
bot.add_cog(Points(bot))
| Fix getmembers command to get role instead of top role. | Fix getmembers command to get role instead of top role.
| Python | agpl-3.0 | freiheit/Bay-Oh-Woolph,dark-echo/Bay-Oh-Woolph | from discord.ext import commands
from utils import *
import discord
import asyncio
import sqlite3
from member import Member
class Points:
def __init__(self,bot):
self.bot = bot
#Test method to populate an array from discord -Infinite
@commands.command()
@commands.has_role('Leadership')
@asyncio.coroutine
def getmembers(self, role1 : discord.Role=None):
therole = role1
#Typing function
yield from self.bot.type()
#Intialize array
listOfMembers = []
#Add members to array
for amember in self.bot.get_all_members():
arole = [role for role in amember.roles if role == therole]
- if arole == therole:
+ if arole:
+ if arole[0].name == therole.name:
- listOfMembers.append(Member(int(amember.id),str(amember.name),str(amember.nick),str(amember.top_role),0))
+ listOfMembers.append(Member(int(amember.id),str(amember.name),str(amember.nick),str(amember.top_role),0))
length = len(listOfMembers)
yield from self.bot.say("Number of " + str(therole) + "s in array: " + str(length))
def setup(bot):
bot.add_cog(Points(bot))
| Fix getmembers command to get role instead of top role. | ## Code Before:
from discord.ext import commands
from utils import *
import discord
import asyncio
import sqlite3
from member import Member
class Points:
def __init__(self,bot):
self.bot = bot
#Test method to populate an array from discord -Infinite
@commands.command()
@commands.has_role('Leadership')
@asyncio.coroutine
def getmembers(self, role1 : discord.Role=None):
therole = role1
#Typing function
yield from self.bot.type()
#Intialize array
listOfMembers = []
#Add members to array
for amember in self.bot.get_all_members():
arole = [role for role in amember.roles if role == therole]
if arole == therole:
listOfMembers.append(Member(int(amember.id),str(amember.name),str(amember.nick),str(amember.top_role),0))
length = len(listOfMembers)
yield from self.bot.say("Number of " + str(therole) + "s in array: " + str(length))
def setup(bot):
bot.add_cog(Points(bot))
## Instruction:
Fix getmembers command to get role instead of top role.
## Code After:
from discord.ext import commands
from utils import *
import discord
import asyncio
import sqlite3
from member import Member
class Points:
def __init__(self,bot):
self.bot = bot
#Test method to populate an array from discord -Infinite
@commands.command()
@commands.has_role('Leadership')
@asyncio.coroutine
def getmembers(self, role1 : discord.Role=None):
therole = role1
#Typing function
yield from self.bot.type()
#Intialize array
listOfMembers = []
#Add members to array
for amember in self.bot.get_all_members():
arole = [role for role in amember.roles if role == therole]
if arole:
if arole[0].name == therole.name:
listOfMembers.append(Member(int(amember.id),str(amember.name),str(amember.nick),str(amember.top_role),0))
length = len(listOfMembers)
yield from self.bot.say("Number of " + str(therole) + "s in array: " + str(length))
def setup(bot):
bot.add_cog(Points(bot))
|
8603d5e83f1eeac84990cb5353b166dd35fa8140 | cyder/base/eav/forms.py | cyder/base/eav/forms.py | from django import forms
from django.core.exceptions import ValidationError
from cyder.base.eav.models import Attribute
class AttributeFormField(forms.CharField):
def to_python(self, value):
try:
return Attribute.objects.get(
name=value)
except Attribute.DoesNotExist:
raise ValidationError("No such attribute")
def get_eav_form(eav_model, entity_model):
class EAVForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
if 'initial' not in kwargs:
kwargs['initial'] = dict()
kwargs['initial']['attribute'] = kwargs['instance'].attribute.name
super(EAVForm, self).__init__(*args, **kwargs)
entity = forms.ModelChoiceField(
queryset=entity_model.objects.all(),
widget=forms.HiddenInput())
attribute = AttributeFormField()
class Meta:
model = eav_model
fields = ('entity', 'attribute', 'value')
return EAVForm
| from django import forms
from django.core.exceptions import ValidationError
from cyder.base.eav.models import Attribute
class AttributeFormField(forms.CharField):
def to_python(self, value):
try:
return Attribute.objects.get(
name=value)
except Attribute.DoesNotExist:
raise ValidationError("No such attribute")
def get_eav_form(eav_model, entity_model):
class EAVForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
if 'instance' in kwargs and kwargs['instance'] is not None:
# This is a bound form with a real instance
if 'initial' not in kwargs:
kwargs['initial'] = dict()
# Set the attribute field to the name, not the pk
kwargs['initial']['attribute'] = \
kwargs['instance'].attribute.name
super(EAVForm, self).__init__(*args, **kwargs)
entity = forms.ModelChoiceField(
queryset=entity_model.objects.all(),
widget=forms.HiddenInput())
attribute = AttributeFormField()
class Meta:
model = eav_model
fields = ('entity', 'attribute', 'value')
return EAVForm
| Fix EAV creation form; fix form error bug | Fix EAV creation form; fix form error bug
| Python | bsd-3-clause | drkitty/cyder,OSU-Net/cyder,OSU-Net/cyder,zeeman/cyder,akeym/cyder,OSU-Net/cyder,akeym/cyder,zeeman/cyder,zeeman/cyder,murrown/cyder,murrown/cyder,OSU-Net/cyder,drkitty/cyder,murrown/cyder,zeeman/cyder,drkitty/cyder,murrown/cyder,akeym/cyder,akeym/cyder,drkitty/cyder | from django import forms
from django.core.exceptions import ValidationError
from cyder.base.eav.models import Attribute
class AttributeFormField(forms.CharField):
def to_python(self, value):
try:
return Attribute.objects.get(
name=value)
except Attribute.DoesNotExist:
raise ValidationError("No such attribute")
def get_eav_form(eav_model, entity_model):
class EAVForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
+ if 'instance' in kwargs and kwargs['instance'] is not None:
+ # This is a bound form with a real instance
+
- if 'initial' not in kwargs:
+ if 'initial' not in kwargs:
- kwargs['initial'] = dict()
+ kwargs['initial'] = dict()
- kwargs['initial']['attribute'] = kwargs['instance'].attribute.name
+
+ # Set the attribute field to the name, not the pk
+ kwargs['initial']['attribute'] = \
+ kwargs['instance'].attribute.name
super(EAVForm, self).__init__(*args, **kwargs)
entity = forms.ModelChoiceField(
queryset=entity_model.objects.all(),
widget=forms.HiddenInput())
attribute = AttributeFormField()
class Meta:
model = eav_model
fields = ('entity', 'attribute', 'value')
return EAVForm
| Fix EAV creation form; fix form error bug | ## Code Before:
from django import forms
from django.core.exceptions import ValidationError
from cyder.base.eav.models import Attribute
class AttributeFormField(forms.CharField):
def to_python(self, value):
try:
return Attribute.objects.get(
name=value)
except Attribute.DoesNotExist:
raise ValidationError("No such attribute")
def get_eav_form(eav_model, entity_model):
class EAVForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
if 'initial' not in kwargs:
kwargs['initial'] = dict()
kwargs['initial']['attribute'] = kwargs['instance'].attribute.name
super(EAVForm, self).__init__(*args, **kwargs)
entity = forms.ModelChoiceField(
queryset=entity_model.objects.all(),
widget=forms.HiddenInput())
attribute = AttributeFormField()
class Meta:
model = eav_model
fields = ('entity', 'attribute', 'value')
return EAVForm
## Instruction:
Fix EAV creation form; fix form error bug
## Code After:
from django import forms
from django.core.exceptions import ValidationError
from cyder.base.eav.models import Attribute
class AttributeFormField(forms.CharField):
def to_python(self, value):
try:
return Attribute.objects.get(
name=value)
except Attribute.DoesNotExist:
raise ValidationError("No such attribute")
def get_eav_form(eav_model, entity_model):
class EAVForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
if 'instance' in kwargs and kwargs['instance'] is not None:
# This is a bound form with a real instance
if 'initial' not in kwargs:
kwargs['initial'] = dict()
# Set the attribute field to the name, not the pk
kwargs['initial']['attribute'] = \
kwargs['instance'].attribute.name
super(EAVForm, self).__init__(*args, **kwargs)
entity = forms.ModelChoiceField(
queryset=entity_model.objects.all(),
widget=forms.HiddenInput())
attribute = AttributeFormField()
class Meta:
model = eav_model
fields = ('entity', 'attribute', 'value')
return EAVForm
|
b4c7a8d35d94f767154da44509a77010b585fe13 | daiquiri/query/views.py | daiquiri/query/views.py | from django.views.generic import TemplateView
from daiquiri.core.views import ModelPermissionMixin, AnonymousAccessMixin
from daiquiri.core.utils import get_model_field_meta
from .models import QueryJob, Example
class QueryView(AnonymousAccessMixin, TemplateView):
template_name = 'query/query.html'
anonymous_setting = 'QUERY_ANONYMOUS'
class JobsView(AnonymousAccessMixin, TemplateView):
template_name = 'query/jobs.html'
anonymous_setting = 'QUERY_ANONYMOUS'
def get_context_data(self, **kwargs):
context = super(JobsView, self).get_context_data(**kwargs)
context['phases'] = QueryJob.PHASE_CHOICES
return context
class ExamplesView(ModelPermissionMixin, TemplateView):
template_name = 'query/examples.html'
permission_required = 'daiquiri_query.view_example'
def get_context_data(self, **kwargs):
context = super(ExamplesView, self).get_context_data(**kwargs)
context['meta'] = {
'Example': get_model_field_meta(Example)
}
return context
| from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import TemplateView
from daiquiri.core.views import ModelPermissionMixin, AnonymousAccessMixin
from daiquiri.core.utils import get_model_field_meta
from .models import QueryJob, Example
class QueryView(AnonymousAccessMixin, TemplateView):
template_name = 'query/query.html'
anonymous_setting = 'QUERY_ANONYMOUS'
class JobsView(LoginRequiredMixin, TemplateView):
template_name = 'query/jobs.html'
def get_context_data(self, **kwargs):
context = super(JobsView, self).get_context_data(**kwargs)
context['phases'] = QueryJob.PHASE_CHOICES
return context
class ExamplesView(ModelPermissionMixin, TemplateView):
template_name = 'query/examples.html'
permission_required = 'daiquiri_query.view_example'
def get_context_data(self, **kwargs):
context = super(ExamplesView, self).get_context_data(**kwargs)
context['meta'] = {
'Example': get_model_field_meta(Example)
}
return context
| Disable jobs overview for anonymous users | Disable jobs overview for anonymous users
| Python | apache-2.0 | aipescience/django-daiquiri,aipescience/django-daiquiri,aipescience/django-daiquiri | + from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import TemplateView
from daiquiri.core.views import ModelPermissionMixin, AnonymousAccessMixin
from daiquiri.core.utils import get_model_field_meta
from .models import QueryJob, Example
class QueryView(AnonymousAccessMixin, TemplateView):
template_name = 'query/query.html'
anonymous_setting = 'QUERY_ANONYMOUS'
- class JobsView(AnonymousAccessMixin, TemplateView):
+ class JobsView(LoginRequiredMixin, TemplateView):
template_name = 'query/jobs.html'
- anonymous_setting = 'QUERY_ANONYMOUS'
def get_context_data(self, **kwargs):
context = super(JobsView, self).get_context_data(**kwargs)
context['phases'] = QueryJob.PHASE_CHOICES
return context
class ExamplesView(ModelPermissionMixin, TemplateView):
template_name = 'query/examples.html'
permission_required = 'daiquiri_query.view_example'
def get_context_data(self, **kwargs):
context = super(ExamplesView, self).get_context_data(**kwargs)
context['meta'] = {
'Example': get_model_field_meta(Example)
}
return context
| Disable jobs overview for anonymous users | ## Code Before:
from django.views.generic import TemplateView
from daiquiri.core.views import ModelPermissionMixin, AnonymousAccessMixin
from daiquiri.core.utils import get_model_field_meta
from .models import QueryJob, Example
class QueryView(AnonymousAccessMixin, TemplateView):
template_name = 'query/query.html'
anonymous_setting = 'QUERY_ANONYMOUS'
class JobsView(AnonymousAccessMixin, TemplateView):
template_name = 'query/jobs.html'
anonymous_setting = 'QUERY_ANONYMOUS'
def get_context_data(self, **kwargs):
context = super(JobsView, self).get_context_data(**kwargs)
context['phases'] = QueryJob.PHASE_CHOICES
return context
class ExamplesView(ModelPermissionMixin, TemplateView):
template_name = 'query/examples.html'
permission_required = 'daiquiri_query.view_example'
def get_context_data(self, **kwargs):
context = super(ExamplesView, self).get_context_data(**kwargs)
context['meta'] = {
'Example': get_model_field_meta(Example)
}
return context
## Instruction:
Disable jobs overview for anonymous users
## Code After:
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import TemplateView
from daiquiri.core.views import ModelPermissionMixin, AnonymousAccessMixin
from daiquiri.core.utils import get_model_field_meta
from .models import QueryJob, Example
class QueryView(AnonymousAccessMixin, TemplateView):
template_name = 'query/query.html'
anonymous_setting = 'QUERY_ANONYMOUS'
class JobsView(LoginRequiredMixin, TemplateView):
template_name = 'query/jobs.html'
def get_context_data(self, **kwargs):
context = super(JobsView, self).get_context_data(**kwargs)
context['phases'] = QueryJob.PHASE_CHOICES
return context
class ExamplesView(ModelPermissionMixin, TemplateView):
template_name = 'query/examples.html'
permission_required = 'daiquiri_query.view_example'
def get_context_data(self, **kwargs):
context = super(ExamplesView, self).get_context_data(**kwargs)
context['meta'] = {
'Example': get_model_field_meta(Example)
}
return context
|
c6c06ab8197bfe3f007bab231536656abfcf0954 | docs/conf.py | docs/conf.py |
import os
import sphinx_rtd_theme
import sys
REPO_DIR = os.path.dirname(os.path.dirname(__file__))
sys.path.append(REPO_DIR)
project = 'Ichnaea'
copyright = '2013-2019, Mozilla'
# The short X.Y version.
version = '2.0'
# The full version, including alpha/beta/rc tags.
release = '2.0'
autoclass_content = 'class'
exclude_patterns = ['build/html/README.rst', '.DS_Store', 'Thumbs.db']
html_static_path = []
html_theme = 'sphinx_rtd_theme'
html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
master_doc = 'index'
modindex_common_prefix = ['ichnaea.']
pygments_style = 'sphinx'
source_suffix = '.rst'
templates_path = ['_templates']
extensions = [
'sphinx.ext.linkcode',
'everett.sphinxext',
]
def linkcode_resolve(domain, info):
if domain != 'py':
return None
if not info['module']:
return None
filename = info['module'].replace('.', '/')
return "https://github.com/mozilla/ichnaea/tree/master/%s.py" % filename
|
import os
import sphinx_rtd_theme
import sys
from unittest import mock
# Add repository root so we can import ichnaea things
REPO_DIR = os.path.dirname(os.path.dirname(__file__))
sys.path.append(REPO_DIR)
# Fake the shapely module so things will import
sys.modules['shapely'] = mock.MagicMock()
project = 'Ichnaea'
copyright = '2013-2019, Mozilla'
# The short X.Y version.
version = '2.0'
# The full version, including alpha/beta/rc tags.
release = '2.0'
autoclass_content = 'class'
exclude_patterns = ['build/html/README.rst', '.DS_Store', 'Thumbs.db']
html_static_path = []
html_theme = 'sphinx_rtd_theme'
html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
master_doc = 'index'
modindex_common_prefix = ['ichnaea.']
pygments_style = 'sphinx'
source_suffix = '.rst'
templates_path = ['_templates']
extensions = [
'sphinx.ext.linkcode',
'everett.sphinxext',
]
def linkcode_resolve(domain, info):
if domain != 'py':
return None
if not info['module']:
return None
filename = info['module'].replace('.', '/')
return "https://github.com/mozilla/ichnaea/tree/master/%s.py" % filename
| Add mock for shapely module | Add mock for shapely module
Adding a mock for the shapely module allows ReadTheDocs to build the
docs even though Shapely isn't installed.
| Python | apache-2.0 | mozilla/ichnaea,mozilla/ichnaea,mozilla/ichnaea,mozilla/ichnaea |
import os
import sphinx_rtd_theme
import sys
+ from unittest import mock
+ # Add repository root so we can import ichnaea things
REPO_DIR = os.path.dirname(os.path.dirname(__file__))
sys.path.append(REPO_DIR)
+
+
+ # Fake the shapely module so things will import
+ sys.modules['shapely'] = mock.MagicMock()
project = 'Ichnaea'
copyright = '2013-2019, Mozilla'
# The short X.Y version.
version = '2.0'
# The full version, including alpha/beta/rc tags.
release = '2.0'
autoclass_content = 'class'
exclude_patterns = ['build/html/README.rst', '.DS_Store', 'Thumbs.db']
html_static_path = []
html_theme = 'sphinx_rtd_theme'
html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
master_doc = 'index'
modindex_common_prefix = ['ichnaea.']
pygments_style = 'sphinx'
source_suffix = '.rst'
templates_path = ['_templates']
extensions = [
'sphinx.ext.linkcode',
'everett.sphinxext',
]
def linkcode_resolve(domain, info):
if domain != 'py':
return None
if not info['module']:
return None
filename = info['module'].replace('.', '/')
return "https://github.com/mozilla/ichnaea/tree/master/%s.py" % filename
| Add mock for shapely module | ## Code Before:
import os
import sphinx_rtd_theme
import sys
REPO_DIR = os.path.dirname(os.path.dirname(__file__))
sys.path.append(REPO_DIR)
project = 'Ichnaea'
copyright = '2013-2019, Mozilla'
# The short X.Y version.
version = '2.0'
# The full version, including alpha/beta/rc tags.
release = '2.0'
autoclass_content = 'class'
exclude_patterns = ['build/html/README.rst', '.DS_Store', 'Thumbs.db']
html_static_path = []
html_theme = 'sphinx_rtd_theme'
html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
master_doc = 'index'
modindex_common_prefix = ['ichnaea.']
pygments_style = 'sphinx'
source_suffix = '.rst'
templates_path = ['_templates']
extensions = [
'sphinx.ext.linkcode',
'everett.sphinxext',
]
def linkcode_resolve(domain, info):
if domain != 'py':
return None
if not info['module']:
return None
filename = info['module'].replace('.', '/')
return "https://github.com/mozilla/ichnaea/tree/master/%s.py" % filename
## Instruction:
Add mock for shapely module
## Code After:
import os
import sphinx_rtd_theme
import sys
from unittest import mock
# Add repository root so we can import ichnaea things
REPO_DIR = os.path.dirname(os.path.dirname(__file__))
sys.path.append(REPO_DIR)
# Fake the shapely module so things will import
sys.modules['shapely'] = mock.MagicMock()
project = 'Ichnaea'
copyright = '2013-2019, Mozilla'
# The short X.Y version.
version = '2.0'
# The full version, including alpha/beta/rc tags.
release = '2.0'
autoclass_content = 'class'
exclude_patterns = ['build/html/README.rst', '.DS_Store', 'Thumbs.db']
html_static_path = []
html_theme = 'sphinx_rtd_theme'
html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
master_doc = 'index'
modindex_common_prefix = ['ichnaea.']
pygments_style = 'sphinx'
source_suffix = '.rst'
templates_path = ['_templates']
extensions = [
'sphinx.ext.linkcode',
'everett.sphinxext',
]
def linkcode_resolve(domain, info):
if domain != 'py':
return None
if not info['module']:
return None
filename = info['module'].replace('.', '/')
return "https://github.com/mozilla/ichnaea/tree/master/%s.py" % filename
|
81246153033d38132903759cb7e33cf86c26a548 | tests/test_attime.py | tests/test_attime.py | import datetime
import time
from graphite_api.render.attime import parseATTime
from . import TestCase
class AtTestCase(TestCase):
def test_parse(self):
for value in [
str(int(time.time())),
'20140319',
'20130319+1y',
'20130319+1mon',
'20130319+1w',
'12:12_20130319',
'3:05am_20130319',
'3:05pm_20130319',
'noon20130319',
'midnight20130319',
'teatime20130319',
'yesterday',
'tomorrow',
'03/19/2014',
'03/19/1800',
'03/19/1950',
'feb 27',
'mar 5',
'mon',
'tue',
'wed',
'thu',
'fri',
'sat',
'sun',
]:
self.assertIsInstance(parseATTime(value), datetime.datetime)
for value in [
'20130319+1foo',
'mar',
'wat',
]:
with self.assertRaises(Exception):
parseATTime(value)
| import datetime
import time
from graphite_api.render.attime import parseATTime
from . import TestCase
class AtTestCase(TestCase):
def test_parse(self):
for value in [
str(int(time.time())),
'20140319',
'20130319+1y',
'20130319+1mon',
'20130319+1w',
'12:12_20130319',
'3:05am_20130319',
'3:05pm_20130319',
'noon20130319',
'midnight20130319',
'teatime20130319',
'yesterday',
'tomorrow',
'03/19/2014',
'03/19/1800',
'03/19/1950',
'feb 27',
'mar 5',
'mon',
'tue',
'wed',
'thu',
'fri',
'sat',
'sun',
'10:00',
]:
self.assertIsInstance(parseATTime(value), datetime.datetime)
for value in [
'20130319+1foo',
'mar',
'wat',
]:
with self.assertRaises(Exception):
parseATTime(value)
| Make sure HH:MM values are allowed | Make sure HH:MM values are allowed
| Python | apache-2.0 | michaelrice/graphite-api,alphapigger/graphite-api,Knewton/graphite-api,vladimir-smirnov-sociomantic/graphite-api,hubrick/graphite-api,GeorgeJahad/graphite-api,absalon-james/graphite-api,raintank/graphite-api,winguru/graphite-api,DaveBlooman/graphite-api,absalon-james/graphite-api,alphapigger/graphite-api,raintank/graphite-api,raintank/graphite-api,rackerlabs/graphite-api,michaelrice/graphite-api,DaveBlooman/graphite-api,Knewton/graphite-api,bogus-py/graphite-api,cybem/graphite-api-iow,vladimir-smirnov-sociomantic/graphite-api,GeorgeJahad/graphite-api,brutasse/graphite-api,tpeng/graphite-api,winguru/graphite-api,cybem/graphite-api-iow,rackerlabs/graphite-api,brutasse/graphite-api,hubrick/graphite-api,bogus-py/graphite-api,tpeng/graphite-api | import datetime
import time
from graphite_api.render.attime import parseATTime
from . import TestCase
class AtTestCase(TestCase):
def test_parse(self):
for value in [
str(int(time.time())),
'20140319',
'20130319+1y',
'20130319+1mon',
'20130319+1w',
'12:12_20130319',
'3:05am_20130319',
'3:05pm_20130319',
'noon20130319',
'midnight20130319',
'teatime20130319',
'yesterday',
'tomorrow',
'03/19/2014',
'03/19/1800',
'03/19/1950',
'feb 27',
'mar 5',
'mon',
'tue',
'wed',
'thu',
'fri',
'sat',
'sun',
+ '10:00',
]:
self.assertIsInstance(parseATTime(value), datetime.datetime)
for value in [
'20130319+1foo',
'mar',
'wat',
]:
with self.assertRaises(Exception):
parseATTime(value)
| Make sure HH:MM values are allowed | ## Code Before:
import datetime
import time
from graphite_api.render.attime import parseATTime
from . import TestCase
class AtTestCase(TestCase):
def test_parse(self):
for value in [
str(int(time.time())),
'20140319',
'20130319+1y',
'20130319+1mon',
'20130319+1w',
'12:12_20130319',
'3:05am_20130319',
'3:05pm_20130319',
'noon20130319',
'midnight20130319',
'teatime20130319',
'yesterday',
'tomorrow',
'03/19/2014',
'03/19/1800',
'03/19/1950',
'feb 27',
'mar 5',
'mon',
'tue',
'wed',
'thu',
'fri',
'sat',
'sun',
]:
self.assertIsInstance(parseATTime(value), datetime.datetime)
for value in [
'20130319+1foo',
'mar',
'wat',
]:
with self.assertRaises(Exception):
parseATTime(value)
## Instruction:
Make sure HH:MM values are allowed
## Code After:
import datetime
import time
from graphite_api.render.attime import parseATTime
from . import TestCase
class AtTestCase(TestCase):
def test_parse(self):
for value in [
str(int(time.time())),
'20140319',
'20130319+1y',
'20130319+1mon',
'20130319+1w',
'12:12_20130319',
'3:05am_20130319',
'3:05pm_20130319',
'noon20130319',
'midnight20130319',
'teatime20130319',
'yesterday',
'tomorrow',
'03/19/2014',
'03/19/1800',
'03/19/1950',
'feb 27',
'mar 5',
'mon',
'tue',
'wed',
'thu',
'fri',
'sat',
'sun',
'10:00',
]:
self.assertIsInstance(parseATTime(value), datetime.datetime)
for value in [
'20130319+1foo',
'mar',
'wat',
]:
with self.assertRaises(Exception):
parseATTime(value)
|
21d45e38d07a413aeeb19e10a68e540d1f6d5851 | core/forms.py | core/forms.py |
from core import settings as stCore
from django import forms
from django.conf import settings as st
from django.contrib.flatpages.admin import FlatpageForm
from django.contrib.sites.models import Site
from django.forms.widgets import HiddenInput, MultipleHiddenInput
class PageForm(FlatpageForm):
url = forms.CharField(label='', max_length=100, required=False)
sites = forms.ModelMultipleChoiceField(queryset=Site.objects.all(),
required=False, label='')
def __init__(self, *args, **kwargs):
super(FlatpageForm, self).__init__(*args, **kwargs)
self.fields['url'].initial = stCore.BASE_URL_FLATPAGES
self.fields['url'].widget = HiddenInput()
self.fields['sites'].widget = MultipleHiddenInput()
def clean_url(self):
return True
def save(self, commit=True):
flatpage = super(PageForm, self).save(commit=False)
flatpage.save()
flatpage.url = stCore.BASE_URL_FLATPAGES + str(flatpage.id) + '/'
flatpage.sites.add(Site.objects.get(id=st.SITE_ID))
return flatpage
class Meta:
widgets = {
'content': forms.widgets.Textarea(),
}
class Media:
js = (st.TINYMCE_JS_URL, st.TINYMCE_JS_TEXTAREA)
|
from core import settings as stCore
from django import forms
from django.conf import settings as st
from flatpages_i18n.forms import FlatpageForm
from django.contrib.sites.models import Site
from django.forms.widgets import HiddenInput, MultipleHiddenInput
class PageForm(FlatpageForm):
url = forms.CharField(label='', max_length=100, required=False)
sites = forms.ModelMultipleChoiceField(queryset=Site.objects.all(),
required=False, label='')
def __init__(self, *args, **kwargs):
super(FlatpageForm, self).__init__(*args, **kwargs)
self.fields['url'].initial = stCore.BASE_URL_FLATPAGES
self.fields['url'].widget = HiddenInput()
self.fields['sites'].widget = MultipleHiddenInput()
def clean_url(self):
return True
def save(self, commit=True):
flatpage = super(PageForm, self).save(commit=False)
flatpage.save()
flatpage.url = stCore.BASE_URL_FLATPAGES + str(flatpage.id) + '/'
flatpage.sites.add(Site.objects.get(id=st.SITE_ID))
return flatpage
class Meta:
widgets = {
'content': forms.widgets.Textarea(),
}
class Media:
js = (st.TINYMCE_JS_URL, st.TINYMCE_JS_TEXTAREA)
| Remove last references to flatpage so it doesnt show up on admin page | Remove last references to flatpage so it doesnt show up on admin page
| Python | agpl-3.0 | tic-ull/portal-del-investigador,tic-ull/portal-del-investigador,tic-ull/portal-del-investigador,tic-ull/portal-del-investigador |
from core import settings as stCore
from django import forms
from django.conf import settings as st
- from django.contrib.flatpages.admin import FlatpageForm
+ from flatpages_i18n.forms import FlatpageForm
from django.contrib.sites.models import Site
from django.forms.widgets import HiddenInput, MultipleHiddenInput
class PageForm(FlatpageForm):
url = forms.CharField(label='', max_length=100, required=False)
sites = forms.ModelMultipleChoiceField(queryset=Site.objects.all(),
required=False, label='')
def __init__(self, *args, **kwargs):
super(FlatpageForm, self).__init__(*args, **kwargs)
self.fields['url'].initial = stCore.BASE_URL_FLATPAGES
self.fields['url'].widget = HiddenInput()
self.fields['sites'].widget = MultipleHiddenInput()
def clean_url(self):
return True
def save(self, commit=True):
flatpage = super(PageForm, self).save(commit=False)
flatpage.save()
flatpage.url = stCore.BASE_URL_FLATPAGES + str(flatpage.id) + '/'
flatpage.sites.add(Site.objects.get(id=st.SITE_ID))
return flatpage
class Meta:
widgets = {
'content': forms.widgets.Textarea(),
}
class Media:
js = (st.TINYMCE_JS_URL, st.TINYMCE_JS_TEXTAREA)
| Remove last references to flatpage so it doesnt show up on admin page | ## Code Before:
from core import settings as stCore
from django import forms
from django.conf import settings as st
from django.contrib.flatpages.admin import FlatpageForm
from django.contrib.sites.models import Site
from django.forms.widgets import HiddenInput, MultipleHiddenInput
class PageForm(FlatpageForm):
url = forms.CharField(label='', max_length=100, required=False)
sites = forms.ModelMultipleChoiceField(queryset=Site.objects.all(),
required=False, label='')
def __init__(self, *args, **kwargs):
super(FlatpageForm, self).__init__(*args, **kwargs)
self.fields['url'].initial = stCore.BASE_URL_FLATPAGES
self.fields['url'].widget = HiddenInput()
self.fields['sites'].widget = MultipleHiddenInput()
def clean_url(self):
return True
def save(self, commit=True):
flatpage = super(PageForm, self).save(commit=False)
flatpage.save()
flatpage.url = stCore.BASE_URL_FLATPAGES + str(flatpage.id) + '/'
flatpage.sites.add(Site.objects.get(id=st.SITE_ID))
return flatpage
class Meta:
widgets = {
'content': forms.widgets.Textarea(),
}
class Media:
js = (st.TINYMCE_JS_URL, st.TINYMCE_JS_TEXTAREA)
## Instruction:
Remove last references to flatpage so it doesnt show up on admin page
## Code After:
from core import settings as stCore
from django import forms
from django.conf import settings as st
from flatpages_i18n.forms import FlatpageForm
from django.contrib.sites.models import Site
from django.forms.widgets import HiddenInput, MultipleHiddenInput
class PageForm(FlatpageForm):
url = forms.CharField(label='', max_length=100, required=False)
sites = forms.ModelMultipleChoiceField(queryset=Site.objects.all(),
required=False, label='')
def __init__(self, *args, **kwargs):
super(FlatpageForm, self).__init__(*args, **kwargs)
self.fields['url'].initial = stCore.BASE_URL_FLATPAGES
self.fields['url'].widget = HiddenInput()
self.fields['sites'].widget = MultipleHiddenInput()
def clean_url(self):
return True
def save(self, commit=True):
flatpage = super(PageForm, self).save(commit=False)
flatpage.save()
flatpage.url = stCore.BASE_URL_FLATPAGES + str(flatpage.id) + '/'
flatpage.sites.add(Site.objects.get(id=st.SITE_ID))
return flatpage
class Meta:
widgets = {
'content': forms.widgets.Textarea(),
}
class Media:
js = (st.TINYMCE_JS_URL, st.TINYMCE_JS_TEXTAREA)
|
ac0f0780beb61cab95809b2e0d02e5dab481e225 | py/valid-parenthesis-string.py | py/valid-parenthesis-string.py | from collections import Counter
class Solution(object):
def dfs(self, s, pos, stack):
if stack + self.min_possible_opening[-1] - self.min_possible_opening[pos] > self.max_possible_closing[-1] - self.max_possible_closing[pos]:
return False
if stack + self.max_possible_opening[-1] - self.max_possible_opening[pos] < self.min_possible_closing[-1] - self.min_possible_closing[pos]:
return False
if pos == len(s):
return not stack
if s[pos] == '(':
stack += 1
if self.dfs(s, pos + 1, stack):
return True
stack -= 1
elif s[pos] == ')':
if not stack:
return False
else:
stack -= 1
if self.dfs(s, pos + 1, stack):
return True
stack += 1
else:
if stack: # treat as ')'
stack -= 1
if self.dfs(s, pos + 1, stack):
return True
stack += 1
# treat as '('
stack += 1
if self.dfs(s, pos + 1, stack):
return True
stack -= 1
# treat as ''
if self.dfs(s, pos + 1, stack):
return True
return False
def checkValidString(self, s):
"""
:type s: str
:rtype: bool
"""
c = Counter(s)
mpo, mpc = c['('] + c['*'], c[')'] + c['*']
self.max_possible_opening = [0]
self.min_possible_opening = [0]
self.max_possible_closing = [0]
self.min_possible_closing = [0]
for c in s:
self.min_possible_opening.append(self.min_possible_opening[-1] + (c == '('))
self.max_possible_opening.append(self.max_possible_opening[-1] + (c != ')'))
self.min_possible_closing.append(self.min_possible_closing[-1] + (c == ')'))
self.max_possible_closing.append(self.max_possible_closing[-1] + (c != '('))
return self.dfs(s, 0, 0)
| class Solution(object):
def checkValidString(self, s):
"""
:type s: str
:rtype: bool
"""
lowest, highest = 0, 0
for c in s:
if c == '(':
lowest += 1
highest += 1
elif c == ')':
if lowest > 0:
lowest -= 1
highest -= 1
if highest < 0:
return False
else:
if lowest > 0:
lowest -= 1
highest += 1
return lowest == 0
| Add py solution for 678. Valid Parenthesis String | Add py solution for 678. Valid Parenthesis String
678. Valid Parenthesis String: https://leetcode.com/problems/valid-parenthesis-string/
Approach2:
Maintain the lowest/highest possible stack size and check if one of
them is invalid
O(n) time, O(1) size
| Python | apache-2.0 | ckclark/leetcode,ckclark/leetcode,ckclark/leetcode,ckclark/leetcode,ckclark/leetcode,ckclark/leetcode | - from collections import Counter
class Solution(object):
- def dfs(self, s, pos, stack):
- if stack + self.min_possible_opening[-1] - self.min_possible_opening[pos] > self.max_possible_closing[-1] - self.max_possible_closing[pos]:
- return False
- if stack + self.max_possible_opening[-1] - self.max_possible_opening[pos] < self.min_possible_closing[-1] - self.min_possible_closing[pos]:
- return False
- if pos == len(s):
- return not stack
- if s[pos] == '(':
- stack += 1
- if self.dfs(s, pos + 1, stack):
- return True
- stack -= 1
- elif s[pos] == ')':
- if not stack:
- return False
- else:
- stack -= 1
- if self.dfs(s, pos + 1, stack):
- return True
- stack += 1
- else:
- if stack: # treat as ')'
- stack -= 1
- if self.dfs(s, pos + 1, stack):
- return True
- stack += 1
- # treat as '('
- stack += 1
- if self.dfs(s, pos + 1, stack):
- return True
- stack -= 1
-
- # treat as ''
- if self.dfs(s, pos + 1, stack):
- return True
- return False
def checkValidString(self, s):
"""
:type s: str
:rtype: bool
"""
- c = Counter(s)
- mpo, mpc = c['('] + c['*'], c[')'] + c['*']
+ lowest, highest = 0, 0
+ for c in s:
+ if c == '(':
+ lowest += 1
+ highest += 1
+ elif c == ')':
+ if lowest > 0:
+ lowest -= 1
+ highest -= 1
+ if highest < 0:
+ return False
+ else:
+ if lowest > 0:
+ lowest -= 1
+ highest += 1
+ return lowest == 0
- self.max_possible_opening = [0]
- self.min_possible_opening = [0]
- self.max_possible_closing = [0]
- self.min_possible_closing = [0]
- for c in s:
- self.min_possible_opening.append(self.min_possible_opening[-1] + (c == '('))
- self.max_possible_opening.append(self.max_possible_opening[-1] + (c != ')'))
- self.min_possible_closing.append(self.min_possible_closing[-1] + (c == ')'))
- self.max_possible_closing.append(self.max_possible_closing[-1] + (c != '('))
-
- return self.dfs(s, 0, 0)
- | Add py solution for 678. Valid Parenthesis String | ## Code Before:
from collections import Counter
class Solution(object):
def dfs(self, s, pos, stack):
if stack + self.min_possible_opening[-1] - self.min_possible_opening[pos] > self.max_possible_closing[-1] - self.max_possible_closing[pos]:
return False
if stack + self.max_possible_opening[-1] - self.max_possible_opening[pos] < self.min_possible_closing[-1] - self.min_possible_closing[pos]:
return False
if pos == len(s):
return not stack
if s[pos] == '(':
stack += 1
if self.dfs(s, pos + 1, stack):
return True
stack -= 1
elif s[pos] == ')':
if not stack:
return False
else:
stack -= 1
if self.dfs(s, pos + 1, stack):
return True
stack += 1
else:
if stack: # treat as ')'
stack -= 1
if self.dfs(s, pos + 1, stack):
return True
stack += 1
# treat as '('
stack += 1
if self.dfs(s, pos + 1, stack):
return True
stack -= 1
# treat as ''
if self.dfs(s, pos + 1, stack):
return True
return False
def checkValidString(self, s):
"""
:type s: str
:rtype: bool
"""
c = Counter(s)
mpo, mpc = c['('] + c['*'], c[')'] + c['*']
self.max_possible_opening = [0]
self.min_possible_opening = [0]
self.max_possible_closing = [0]
self.min_possible_closing = [0]
for c in s:
self.min_possible_opening.append(self.min_possible_opening[-1] + (c == '('))
self.max_possible_opening.append(self.max_possible_opening[-1] + (c != ')'))
self.min_possible_closing.append(self.min_possible_closing[-1] + (c == ')'))
self.max_possible_closing.append(self.max_possible_closing[-1] + (c != '('))
return self.dfs(s, 0, 0)
## Instruction:
Add py solution for 678. Valid Parenthesis String
## Code After:
class Solution(object):
def checkValidString(self, s):
"""
:type s: str
:rtype: bool
"""
lowest, highest = 0, 0
for c in s:
if c == '(':
lowest += 1
highest += 1
elif c == ')':
if lowest > 0:
lowest -= 1
highest -= 1
if highest < 0:
return False
else:
if lowest > 0:
lowest -= 1
highest += 1
return lowest == 0
|
b23c843fda57e0ffa56aaf430d9a590e2ed0ec9a | ch06/extract_airlines.py | ch06/extract_airlines.py | on_time_dataframe = spark.read.parquet('data/on_time_performance.parquet')
# The first step is easily expressed as SQL: get all unique tail numbers for each airline
on_time_dataframe.registerTempTable("on_time_performance")
carrier_airplane = spark.sql(
"SELECT DISTINCT Carrier, TailNum FROM on_time_performance"
)
# Now we need to store a sorted group for each Carrier, along with a fleet count
airplanes_per_carrier = carrier_airplane.rdd\
.map(lambda nameTuple: (nameTuple[0], [nameTuple[1]]))\
.reduceByKey(lambda a, b: a + b)\
.map(lambda tuple:
{
'Carrier': tuple[0],
'TailNumbers': sorted(
filter(
lambda x: x != '', tuple[1] # empty string tail numbers were getting through
)
),
'FleetCount': len(tuple[1])
}
)
airplanes_per_carrier.count() # 14
# Save to Mongo in the airplanes_per_carrier relation
import pymongo_spark
pymongo_spark.activate()
airplanes_per_carrier.saveToMongoDB(
'mongodb://localhost:27017/agile_data_science.airplanes_per_carrier'
)
| on_time_dataframe = spark.read.parquet('data/on_time_performance.parquet')
# The first step is easily expressed as SQL: get all unique tail numbers for each airline
on_time_dataframe.registerTempTable("on_time_performance")
carrier_airplane = spark.sql(
"SELECT DISTINCT Carrier, TailNum FROM on_time_performance"
)
# Now we need to store a sorted group for each Carrier, along with a fleet count
airplanes_per_carrier = carrier_airplane.rdd\
.map(lambda nameTuple: (nameTuple[0], [nameTuple[1]]))\
.reduceByKey(lambda a, b: a + b)\
.map(lambda tuple:
{
'Carrier': tuple[0],
'TailNumbers': sorted(
filter(
lambda x: x is not None and x != '', tuple[1] # empty string tail numbers were getting through
)
),
'FleetCount': len(tuple[1])
}
)
airplanes_per_carrier.count() # 14
# Save to Mongo in the airplanes_per_carrier relation
import pymongo_spark
pymongo_spark.activate()
airplanes_per_carrier.saveToMongoDB(
'mongodb://localhost:27017/agile_data_science.airplanes_per_carrier'
)
| Check variable for None value before null string when filtering tail numbers | Check variable for None value before null string when filtering tail numbers | Python | mit | rjurney/Agile_Data_Code_2,naoyak/Agile_Data_Code_2,rjurney/Agile_Data_Code_2,naoyak/Agile_Data_Code_2,rjurney/Agile_Data_Code_2,naoyak/Agile_Data_Code_2,rjurney/Agile_Data_Code_2,naoyak/Agile_Data_Code_2 | on_time_dataframe = spark.read.parquet('data/on_time_performance.parquet')
# The first step is easily expressed as SQL: get all unique tail numbers for each airline
on_time_dataframe.registerTempTable("on_time_performance")
carrier_airplane = spark.sql(
"SELECT DISTINCT Carrier, TailNum FROM on_time_performance"
)
# Now we need to store a sorted group for each Carrier, along with a fleet count
airplanes_per_carrier = carrier_airplane.rdd\
.map(lambda nameTuple: (nameTuple[0], [nameTuple[1]]))\
.reduceByKey(lambda a, b: a + b)\
.map(lambda tuple:
{
'Carrier': tuple[0],
'TailNumbers': sorted(
filter(
- lambda x: x != '', tuple[1] # empty string tail numbers were getting through
+ lambda x: x is not None and x != '', tuple[1] # empty string tail numbers were getting through
)
),
'FleetCount': len(tuple[1])
}
)
airplanes_per_carrier.count() # 14
# Save to Mongo in the airplanes_per_carrier relation
import pymongo_spark
pymongo_spark.activate()
airplanes_per_carrier.saveToMongoDB(
'mongodb://localhost:27017/agile_data_science.airplanes_per_carrier'
)
| Check variable for None value before null string when filtering tail numbers | ## Code Before:
on_time_dataframe = spark.read.parquet('data/on_time_performance.parquet')
# The first step is easily expressed as SQL: get all unique tail numbers for each airline
on_time_dataframe.registerTempTable("on_time_performance")
carrier_airplane = spark.sql(
"SELECT DISTINCT Carrier, TailNum FROM on_time_performance"
)
# Now we need to store a sorted group for each Carrier, along with a fleet count
airplanes_per_carrier = carrier_airplane.rdd\
.map(lambda nameTuple: (nameTuple[0], [nameTuple[1]]))\
.reduceByKey(lambda a, b: a + b)\
.map(lambda tuple:
{
'Carrier': tuple[0],
'TailNumbers': sorted(
filter(
lambda x: x != '', tuple[1] # empty string tail numbers were getting through
)
),
'FleetCount': len(tuple[1])
}
)
airplanes_per_carrier.count() # 14
# Save to Mongo in the airplanes_per_carrier relation
import pymongo_spark
pymongo_spark.activate()
airplanes_per_carrier.saveToMongoDB(
'mongodb://localhost:27017/agile_data_science.airplanes_per_carrier'
)
## Instruction:
Check variable for None value before null string when filtering tail numbers
## Code After:
on_time_dataframe = spark.read.parquet('data/on_time_performance.parquet')
# The first step is easily expressed as SQL: get all unique tail numbers for each airline
on_time_dataframe.registerTempTable("on_time_performance")
carrier_airplane = spark.sql(
"SELECT DISTINCT Carrier, TailNum FROM on_time_performance"
)
# Now we need to store a sorted group for each Carrier, along with a fleet count
airplanes_per_carrier = carrier_airplane.rdd\
.map(lambda nameTuple: (nameTuple[0], [nameTuple[1]]))\
.reduceByKey(lambda a, b: a + b)\
.map(lambda tuple:
{
'Carrier': tuple[0],
'TailNumbers': sorted(
filter(
lambda x: x is not None and x != '', tuple[1] # empty string tail numbers were getting through
)
),
'FleetCount': len(tuple[1])
}
)
airplanes_per_carrier.count() # 14
# Save to Mongo in the airplanes_per_carrier relation
import pymongo_spark
pymongo_spark.activate()
airplanes_per_carrier.saveToMongoDB(
'mongodb://localhost:27017/agile_data_science.airplanes_per_carrier'
)
|
dbc09d03f62bf2d5ee1661492a4c20a7942f81a9 | tests/basics/list_slice.py | tests/basics/list_slice.py | x = list(range(10))
a = 2
b = 4
c = 3
print(x[:])
print(x[::])
#print(x[::c])
print(x[:b])
print(x[:b:])
#print(x[:b:c])
print(x[a])
print(x[a:])
print(x[a::])
#print(x[a::c])
print(x[a:b])
print(x[a:b:])
#print(x[a:b:c])
# these should not raise IndexError
print([][1:])
print([][-1:])
|
x = list(range(10))
a = 2
b = 4
c = 3
print(x[:])
print(x[::])
print(x[::c])
print(x[:b])
print(x[:b:])
print(x[:b:c])
print(x[a])
print(x[a:])
print(x[a::])
print(x[a::c])
print(x[a:b])
print(x[a:b:])
print(x[a:b:c])
# these should not raise IndexError
print([][1:])
print([][-1:])
try:
[][::0]
except ValueError:
print('ValueError')
| Enable tests for list slice getting with 3rd arg. | tests/basics: Enable tests for list slice getting with 3rd arg.
Also add a test to check case when 3rd arg is 0.
| Python | mit | tuc-osg/micropython,mhoffma/micropython,trezor/micropython,blazewicz/micropython,AriZuu/micropython,kerneltask/micropython,swegener/micropython,MrSurly/micropython,mhoffma/micropython,hiway/micropython,alex-robbins/micropython,henriknelson/micropython,tuc-osg/micropython,adafruit/micropython,selste/micropython,ryannathans/micropython,tobbad/micropython,kerneltask/micropython,cwyark/micropython,bvernoux/micropython,SHA2017-badge/micropython-esp32,tobbad/micropython,oopy/micropython,chrisdearman/micropython,hiway/micropython,bvernoux/micropython,tralamazza/micropython,ryannathans/micropython,SHA2017-badge/micropython-esp32,MrSurly/micropython-esp32,tralamazza/micropython,chrisdearman/micropython,TDAbboud/micropython,adafruit/circuitpython,puuu/micropython,lowRISC/micropython,torwag/micropython,MrSurly/micropython,kerneltask/micropython,mhoffma/micropython,tobbad/micropython,puuu/micropython,alex-robbins/micropython,puuu/micropython,henriknelson/micropython,HenrikSolver/micropython,tuc-osg/micropython,Timmenem/micropython,pfalcon/micropython,toolmacher/micropython,infinnovation/micropython,mhoffma/micropython,selste/micropython,adafruit/micropython,pozetroninc/micropython,torwag/micropython,HenrikSolver/micropython,pramasoul/micropython,Peetz0r/micropython-esp32,swegener/micropython,pramasoul/micropython,AriZuu/micropython,PappaPeppar/micropython,oopy/micropython,TDAbboud/micropython,adafruit/micropython,bvernoux/micropython,lowRISC/micropython,blazewicz/micropython,pramasoul/micropython,pozetroninc/micropython,tuc-osg/micropython,hiway/micropython,Timmenem/micropython,blazewicz/micropython,trezor/micropython,Timmenem/micropython,selste/micropython,tralamazza/micropython,infinnovation/micropython,tobbad/micropython,deshipu/micropython,deshipu/micropython,torwag/micropython,lowRISC/micropython,dmazzella/micropython,TDAbboud/micropython,swegener/micropython,deshipu/micropython,mhoffma/micropython,selste/micropython,MrSurly/micropython-esp32,Peetz0r/micropython-esp32,adafruit/circuitpython,SHA2017-badge/micropython-esp32,tuc-osg/micropython,MrSurly/micropython,tobbad/micropython,selste/micropython,swegener/micropython,tralamazza/micropython,deshipu/micropython,oopy/micropython,henriknelson/micropython,Timmenem/micropython,lowRISC/micropython,kerneltask/micropython,Peetz0r/micropython-esp32,adafruit/circuitpython,henriknelson/micropython,cwyark/micropython,blazewicz/micropython,lowRISC/micropython,puuu/micropython,PappaPeppar/micropython,MrSurly/micropython,adafruit/micropython,MrSurly/micropython-esp32,PappaPeppar/micropython,PappaPeppar/micropython,SHA2017-badge/micropython-esp32,trezor/micropython,chrisdearman/micropython,hiway/micropython,infinnovation/micropython,puuu/micropython,dmazzella/micropython,blazewicz/micropython,henriknelson/micropython,pramasoul/micropython,HenrikSolver/micropython,micropython/micropython-esp32,chrisdearman/micropython,toolmacher/micropython,toolmacher/micropython,Timmenem/micropython,pozetroninc/micropython,chrisdearman/micropython,MrSurly/micropython-esp32,SHA2017-badge/micropython-esp32,micropython/micropython-esp32,TDAbboud/micropython,PappaPeppar/micropython,deshipu/micropython,ryannathans/micropython,infinnovation/micropython,pfalcon/micropython,Peetz0r/micropython-esp32,micropython/micropython-esp32,trezor/micropython,infinnovation/micropython,torwag/micropython,ryannathans/micropython,AriZuu/micropython,pozetroninc/micropython,adafruit/micropython,trezor/micropython,HenrikSolver/micropython,bvernoux/micropython,cwyark/micropython,alex-robbins/micropython,ryannathans/micropython,alex-robbins/micropython,HenrikSolver/micropython,pramasoul/micropython,adafruit/circuitpython,toolmacher/micropython,toolmacher/micropython,pfalcon/micropython,MrSurly/micropython-esp32,micropython/micropython-esp32,pfalcon/micropython,MrSurly/micropython,pfalcon/micropython,cwyark/micropython,torwag/micropython,AriZuu/micropython,bvernoux/micropython,oopy/micropython,hiway/micropython,TDAbboud/micropython,dmazzella/micropython,alex-robbins/micropython,adafruit/circuitpython,oopy/micropython,pozetroninc/micropython,dmazzella/micropython,swegener/micropython,micropython/micropython-esp32,cwyark/micropython,AriZuu/micropython,adafruit/circuitpython,Peetz0r/micropython-esp32,kerneltask/micropython | +
x = list(range(10))
a = 2
b = 4
c = 3
print(x[:])
print(x[::])
- #print(x[::c])
+ print(x[::c])
print(x[:b])
print(x[:b:])
- #print(x[:b:c])
+ print(x[:b:c])
print(x[a])
print(x[a:])
print(x[a::])
- #print(x[a::c])
+ print(x[a::c])
print(x[a:b])
print(x[a:b:])
- #print(x[a:b:c])
+ print(x[a:b:c])
# these should not raise IndexError
print([][1:])
print([][-1:])
+ try:
+ [][::0]
+ except ValueError:
+ print('ValueError')
+ | Enable tests for list slice getting with 3rd arg. | ## Code Before:
x = list(range(10))
a = 2
b = 4
c = 3
print(x[:])
print(x[::])
#print(x[::c])
print(x[:b])
print(x[:b:])
#print(x[:b:c])
print(x[a])
print(x[a:])
print(x[a::])
#print(x[a::c])
print(x[a:b])
print(x[a:b:])
#print(x[a:b:c])
# these should not raise IndexError
print([][1:])
print([][-1:])
## Instruction:
Enable tests for list slice getting with 3rd arg.
## Code After:
x = list(range(10))
a = 2
b = 4
c = 3
print(x[:])
print(x[::])
print(x[::c])
print(x[:b])
print(x[:b:])
print(x[:b:c])
print(x[a])
print(x[a:])
print(x[a::])
print(x[a::c])
print(x[a:b])
print(x[a:b:])
print(x[a:b:c])
# these should not raise IndexError
print([][1:])
print([][-1:])
try:
[][::0]
except ValueError:
print('ValueError')
|
351c05b6e474b266a7594a775cb48cd7cfe0b833 | shapely/linref.py | shapely/linref.py |
from shapely.topology import Delegating
class LinearRefBase(Delegating):
def _validate_line(self, ob):
super(LinearRefBase, self)._validate(ob)
try:
assert ob.geom_type in ['LineString', 'MultiLineString']
except AssertionError:
raise TypeError("Only linear types support this operation")
class ProjectOp(LinearRefBase):
def __call__(self, this, other):
self._validate_line(this)
self._validate(other)
return self.fn(this._geom, other._geom)
class InterpolateOp(LinearRefBase):
def __call__(self, this, distance):
self._validate_line(this)
return self.fn(this._geom, distance)
|
from shapely.topology import Delegating
class LinearRefBase(Delegating):
def _validate_line(self, ob):
super(LinearRefBase, self)._validate(ob)
if not ob.geom_type in ['LinearRing', 'LineString', 'MultiLineString']:
raise TypeError("Only linear types support this operation")
class ProjectOp(LinearRefBase):
def __call__(self, this, other):
self._validate_line(this)
self._validate(other)
return self.fn(this._geom, other._geom)
class InterpolateOp(LinearRefBase):
def __call__(self, this, distance):
self._validate_line(this)
return self.fn(this._geom, distance)
| Allow linear referencing on rings. | Allow linear referencing on rings.
Closes #286.
Eliminating the assert is good for optimization reasons, too.
| Python | bsd-3-clause | abali96/Shapely,mouadino/Shapely,mindw/shapely,abali96/Shapely,jdmcbr/Shapely,jdmcbr/Shapely,mindw/shapely,mouadino/Shapely |
from shapely.topology import Delegating
class LinearRefBase(Delegating):
def _validate_line(self, ob):
super(LinearRefBase, self)._validate(ob)
- try:
- assert ob.geom_type in ['LineString', 'MultiLineString']
+ if not ob.geom_type in ['LinearRing', 'LineString', 'MultiLineString']:
- except AssertionError:
raise TypeError("Only linear types support this operation")
class ProjectOp(LinearRefBase):
def __call__(self, this, other):
self._validate_line(this)
self._validate(other)
return self.fn(this._geom, other._geom)
class InterpolateOp(LinearRefBase):
def __call__(self, this, distance):
self._validate_line(this)
return self.fn(this._geom, distance)
| Allow linear referencing on rings. | ## Code Before:
from shapely.topology import Delegating
class LinearRefBase(Delegating):
def _validate_line(self, ob):
super(LinearRefBase, self)._validate(ob)
try:
assert ob.geom_type in ['LineString', 'MultiLineString']
except AssertionError:
raise TypeError("Only linear types support this operation")
class ProjectOp(LinearRefBase):
def __call__(self, this, other):
self._validate_line(this)
self._validate(other)
return self.fn(this._geom, other._geom)
class InterpolateOp(LinearRefBase):
def __call__(self, this, distance):
self._validate_line(this)
return self.fn(this._geom, distance)
## Instruction:
Allow linear referencing on rings.
## Code After:
from shapely.topology import Delegating
class LinearRefBase(Delegating):
def _validate_line(self, ob):
super(LinearRefBase, self)._validate(ob)
if not ob.geom_type in ['LinearRing', 'LineString', 'MultiLineString']:
raise TypeError("Only linear types support this operation")
class ProjectOp(LinearRefBase):
def __call__(self, this, other):
self._validate_line(this)
self._validate(other)
return self.fn(this._geom, other._geom)
class InterpolateOp(LinearRefBase):
def __call__(self, this, distance):
self._validate_line(this)
return self.fn(this._geom, distance)
|
6f6e16cfabb7c3ff3f634718b16f87bd7705d284 | tests/v7/test_item_list.py | tests/v7/test_item_list.py | from .context import tohu
from tohu.v7.item_list import ItemList
def test_item_list():
values = [11, 55, 22, 66, 33]
item_list = ItemList(values)
assert item_list.items == values
assert item_list == values
assert len(item_list) == 5
assert item_list[3] == 66
assert [x for x in item_list] == values
| from .context import tohu
from tohu.v7.item_list import ItemList
def test_item_list():
values = [11, 55, 22, 66, 33]
item_list = ItemList(values)
assert item_list.items == values
assert item_list == values
assert len(item_list) == 5
assert item_list[3] == 66
assert [x for x in item_list] == values
item_list_2 = ItemList(values)
assert item_list == item_list_2
item_list_3 = ItemList([1, 5, 8, 3])
assert item_list != item_list_3 | Add a couple more test cases for item list | Add a couple more test cases for item list
| Python | mit | maxalbert/tohu | from .context import tohu
from tohu.v7.item_list import ItemList
def test_item_list():
values = [11, 55, 22, 66, 33]
item_list = ItemList(values)
assert item_list.items == values
assert item_list == values
assert len(item_list) == 5
assert item_list[3] == 66
assert [x for x in item_list] == values
+ item_list_2 = ItemList(values)
+ assert item_list == item_list_2
+
+ item_list_3 = ItemList([1, 5, 8, 3])
+ assert item_list != item_list_3 | Add a couple more test cases for item list | ## Code Before:
from .context import tohu
from tohu.v7.item_list import ItemList
def test_item_list():
values = [11, 55, 22, 66, 33]
item_list = ItemList(values)
assert item_list.items == values
assert item_list == values
assert len(item_list) == 5
assert item_list[3] == 66
assert [x for x in item_list] == values
## Instruction:
Add a couple more test cases for item list
## Code After:
from .context import tohu
from tohu.v7.item_list import ItemList
def test_item_list():
values = [11, 55, 22, 66, 33]
item_list = ItemList(values)
assert item_list.items == values
assert item_list == values
assert len(item_list) == 5
assert item_list[3] == 66
assert [x for x in item_list] == values
item_list_2 = ItemList(values)
assert item_list == item_list_2
item_list_3 = ItemList([1, 5, 8, 3])
assert item_list != item_list_3 |
70b037496140dd2e9e6d71508835390f0c85bc02 | skltn/metadata.py | skltn/metadata.py |
# The package name, which is also the "UNIX name" for the project.
package = 'my_module'
project = "My Awesome Module"
project_no_spaces = project.replace(' ', '')
version = '0.1.0'
description = 'It does cool things'
authors = ['John Doe']
authors_string = ', '.join(authors)
emails = ['foobar@example.com', 'johndoe@thisisfake.org']
license = 'MIT'
copyright = '2015 ' + authors_string
url = 'http://example.com/'
| import subprocess
def get_author_detail(arg='name'):
p = subprocess.Popen(['git', 'config', 'user.{}'.format(arg)],
stdout=subprocess.PIPE)
try:
out, _ = p.communicate()
except:
out = ''
return out.strip() or None
# The package name, which is also the "UNIX name" for the project.
package = 'my_module'
project = "My Awesome Module"
project_no_spaces = project.replace(' ', '')
version = '0.1.0'
description = 'It does cool things'
authors = [get_author_detail('name') or 'John Doe']
authors_string = ', '.join(authors)
emails = [get_author_detail('email') or 'doe@example.org']
license = 'MIT'
copyright = '2016 ' + authors_string
url = 'http://example.com/'
| Change year to 2016, try to guess author details from git config | Change year to 2016, try to guess author details from git config
| Python | mit | ksonj/skltn | + import subprocess
+
+
+ def get_author_detail(arg='name'):
+ p = subprocess.Popen(['git', 'config', 'user.{}'.format(arg)],
+ stdout=subprocess.PIPE)
+ try:
+ out, _ = p.communicate()
+ except:
+ out = ''
+ return out.strip() or None
# The package name, which is also the "UNIX name" for the project.
package = 'my_module'
project = "My Awesome Module"
project_no_spaces = project.replace(' ', '')
version = '0.1.0'
description = 'It does cool things'
- authors = ['John Doe']
+ authors = [get_author_detail('name') or 'John Doe']
authors_string = ', '.join(authors)
- emails = ['foobar@example.com', 'johndoe@thisisfake.org']
+ emails = [get_author_detail('email') or 'doe@example.org']
license = 'MIT'
- copyright = '2015 ' + authors_string
+ copyright = '2016 ' + authors_string
url = 'http://example.com/'
| Change year to 2016, try to guess author details from git config | ## Code Before:
# The package name, which is also the "UNIX name" for the project.
package = 'my_module'
project = "My Awesome Module"
project_no_spaces = project.replace(' ', '')
version = '0.1.0'
description = 'It does cool things'
authors = ['John Doe']
authors_string = ', '.join(authors)
emails = ['foobar@example.com', 'johndoe@thisisfake.org']
license = 'MIT'
copyright = '2015 ' + authors_string
url = 'http://example.com/'
## Instruction:
Change year to 2016, try to guess author details from git config
## Code After:
import subprocess
def get_author_detail(arg='name'):
p = subprocess.Popen(['git', 'config', 'user.{}'.format(arg)],
stdout=subprocess.PIPE)
try:
out, _ = p.communicate()
except:
out = ''
return out.strip() or None
# The package name, which is also the "UNIX name" for the project.
package = 'my_module'
project = "My Awesome Module"
project_no_spaces = project.replace(' ', '')
version = '0.1.0'
description = 'It does cool things'
authors = [get_author_detail('name') or 'John Doe']
authors_string = ', '.join(authors)
emails = [get_author_detail('email') or 'doe@example.org']
license = 'MIT'
copyright = '2016 ' + authors_string
url = 'http://example.com/'
|
f9012b88f60f8e4ac96cb55aea763edc74ad586e | shell/view/BuddyIcon.py | shell/view/BuddyIcon.py | from sugar.canvas.MenuIcon import MenuIcon
from view.BuddyMenu import BuddyMenu
class BuddyIcon(MenuIcon):
def __init__(self, shell, menu_shell, friend):
MenuIcon.__init__(self, menu_shell, icon_name='stock-buddy',
color=friend.get_color(), size=96)
self._shell = shell
self._friend = friend
def set_popup_distance(self, distance):
self._popup_distance = distance
def create_menu(self):
menu = BuddyMenu(self._shell, self._friend)
menu.connect('action', self._popup_action_cb)
return menu
def _popup_action_cb(self, popup, action):
self.popdown()
model = self._shell.get_model()
if action == BuddyMenu.ACTION_REMOVE_FRIEND:
friends = model.get_friends()
friends.remove(buddy)
buddy = self._friend.get_buddy()
if buddy == None:
return
if action == BuddyMenu.ACTION_INVITE:
activity = model.get_current_activity()
activity.invite(buddy)
elif action == BuddyMenu.ACTION_MAKE_FRIEND:
friends = model.get_friends()
friends.make_friend(buddy)
| from sugar.canvas.MenuIcon import MenuIcon
from view.BuddyMenu import BuddyMenu
class BuddyIcon(MenuIcon):
def __init__(self, shell, menu_shell, friend):
MenuIcon.__init__(self, menu_shell, icon_name='stock-buddy',
color=friend.get_color(), size=96)
self._shell = shell
self._friend = friend
def set_popup_distance(self, distance):
self._popup_distance = distance
def create_menu(self):
menu = BuddyMenu(self._shell, self._friend)
menu.connect('action', self._popup_action_cb)
return menu
def _popup_action_cb(self, popup, action):
self.popdown()
buddy = self._friend.get_buddy()
if buddy == None:
return
model = self._shell.get_model()
if action == BuddyMenu.ACTION_INVITE:
activity = model.get_current_activity()
activity.invite(buddy)
elif action == BuddyMenu.ACTION_MAKE_FRIEND:
friends = model.get_friends()
friends.make_friend(buddy)
elif action == BuddyMenu.ACTION_REMOVE_FRIEND:
friends = model.get_friends()
friends.remove(buddy)
| Move remove code down to fix undefined var error | Move remove code down to fix undefined var error
| Python | lgpl-2.1 | samdroid-apps/sugar-toolkit-gtk3,tchx84/debian-pkg-sugar-toolkit-gtk3,gusDuarte/sugar-toolkit-gtk3,tchx84/debian-pkg-sugar-toolkit,samdroid-apps/sugar-toolkit-gtk3,godiard/sugar-toolkit-gtk3,i5o/sugar-toolkit-gtk3,tchx84/debian-pkg-sugar-toolkit,godiard/sugar-toolkit-gtk3,Daksh/sugar-toolkit-gtk3,manuq/sugar-toolkit-gtk3,tchx84/sugar-toolkit-gtk3,Daksh/sugar-toolkit-gtk3,gusDuarte/sugar-toolkit-gtk3,puneetgkaur/backup_sugar_sugartoolkit,ceibal-tatu/sugar-toolkit-gtk3,godiard/sugar-toolkit-gtk3,manuq/sugar-toolkit-gtk3,samdroid-apps/sugar-toolkit-gtk3,Daksh/sugar-toolkit-gtk3,tchx84/debian-pkg-sugar-toolkit-gtk3,i5o/sugar-toolkit-gtk3,ceibal-tatu/sugar-toolkit,i5o/sugar-toolkit-gtk3,sugarlabs/sugar-toolkit,tchx84/debian-pkg-sugar-toolkit,ceibal-tatu/sugar-toolkit-gtk3,quozl/sugar-toolkit-gtk3,sugarlabs/sugar-toolkit,ceibal-tatu/sugar-toolkit-gtk3,tchx84/sugar-toolkit-gtk3,sugarlabs/sugar-toolkit,puneetgkaur/sugar-toolkit-gtk3,samdroid-apps/sugar-toolkit-gtk3,quozl/sugar-toolkit-gtk3,puneetgkaur/sugar-toolkit-gtk3,puneetgkaur/backup_sugar_sugartoolkit,tchx84/debian-pkg-sugar-toolkit-gtk3,puneetgkaur/sugar-toolkit-gtk3,sugarlabs/sugar-toolkit,puneetgkaur/backup_sugar_sugartoolkit,manuq/sugar-toolkit-gtk3,ceibal-tatu/sugar-toolkit,tchx84/sugar-toolkit-gtk3,quozl/sugar-toolkit-gtk3,sugarlabs/sugar-toolkit-gtk3,gusDuarte/sugar-toolkit-gtk3,i5o/sugar-toolkit-gtk3,gusDuarte/sugar-toolkit-gtk3,quozl/sugar-toolkit-gtk3,ceibal-tatu/sugar-toolkit,sugarlabs/sugar-toolkit-gtk3,sugarlabs/sugar-toolkit-gtk3 | from sugar.canvas.MenuIcon import MenuIcon
from view.BuddyMenu import BuddyMenu
class BuddyIcon(MenuIcon):
def __init__(self, shell, menu_shell, friend):
MenuIcon.__init__(self, menu_shell, icon_name='stock-buddy',
color=friend.get_color(), size=96)
self._shell = shell
self._friend = friend
def set_popup_distance(self, distance):
self._popup_distance = distance
def create_menu(self):
menu = BuddyMenu(self._shell, self._friend)
menu.connect('action', self._popup_action_cb)
return menu
def _popup_action_cb(self, popup, action):
self.popdown()
- model = self._shell.get_model()
- if action == BuddyMenu.ACTION_REMOVE_FRIEND:
- friends = model.get_friends()
- friends.remove(buddy)
-
buddy = self._friend.get_buddy()
if buddy == None:
return
+ model = self._shell.get_model()
if action == BuddyMenu.ACTION_INVITE:
activity = model.get_current_activity()
activity.invite(buddy)
elif action == BuddyMenu.ACTION_MAKE_FRIEND:
friends = model.get_friends()
friends.make_friend(buddy)
+ elif action == BuddyMenu.ACTION_REMOVE_FRIEND:
+ friends = model.get_friends()
+ friends.remove(buddy)
| Move remove code down to fix undefined var error | ## Code Before:
from sugar.canvas.MenuIcon import MenuIcon
from view.BuddyMenu import BuddyMenu
class BuddyIcon(MenuIcon):
def __init__(self, shell, menu_shell, friend):
MenuIcon.__init__(self, menu_shell, icon_name='stock-buddy',
color=friend.get_color(), size=96)
self._shell = shell
self._friend = friend
def set_popup_distance(self, distance):
self._popup_distance = distance
def create_menu(self):
menu = BuddyMenu(self._shell, self._friend)
menu.connect('action', self._popup_action_cb)
return menu
def _popup_action_cb(self, popup, action):
self.popdown()
model = self._shell.get_model()
if action == BuddyMenu.ACTION_REMOVE_FRIEND:
friends = model.get_friends()
friends.remove(buddy)
buddy = self._friend.get_buddy()
if buddy == None:
return
if action == BuddyMenu.ACTION_INVITE:
activity = model.get_current_activity()
activity.invite(buddy)
elif action == BuddyMenu.ACTION_MAKE_FRIEND:
friends = model.get_friends()
friends.make_friend(buddy)
## Instruction:
Move remove code down to fix undefined var error
## Code After:
from sugar.canvas.MenuIcon import MenuIcon
from view.BuddyMenu import BuddyMenu
class BuddyIcon(MenuIcon):
def __init__(self, shell, menu_shell, friend):
MenuIcon.__init__(self, menu_shell, icon_name='stock-buddy',
color=friend.get_color(), size=96)
self._shell = shell
self._friend = friend
def set_popup_distance(self, distance):
self._popup_distance = distance
def create_menu(self):
menu = BuddyMenu(self._shell, self._friend)
menu.connect('action', self._popup_action_cb)
return menu
def _popup_action_cb(self, popup, action):
self.popdown()
buddy = self._friend.get_buddy()
if buddy == None:
return
model = self._shell.get_model()
if action == BuddyMenu.ACTION_INVITE:
activity = model.get_current_activity()
activity.invite(buddy)
elif action == BuddyMenu.ACTION_MAKE_FRIEND:
friends = model.get_friends()
friends.make_friend(buddy)
elif action == BuddyMenu.ACTION_REMOVE_FRIEND:
friends = model.get_friends()
friends.remove(buddy)
|
de0bbf978695d206189ee4effb124234968525cb | django_afip/views.py | django_afip/views.py | from django.http import HttpResponse
from django.utils.translation import ugettext as _
from django.views.generic import View
from .pdf import generate_receipt_pdf
class ReceiptHTMLView(View):
def get(self, request, pk):
return HttpResponse(
generate_receipt_pdf(pk, request, True),
)
class ReceiptPDFView(View):
def get(self, request, pk):
response = HttpResponse(content_type='application/pdf')
response['Content-Disposition'] = 'attachment; filename=' + \
_('receipt %s.pdf' % pk)
generate_receipt_pdf(pk, response)
return response
| from django.http import HttpResponse
from django.utils.translation import ugettext as _
from django.views.generic import View
from .pdf import generate_receipt_pdf
class ReceiptHTMLView(View):
"""Renders a receipt as HTML."""
def get(self, request, pk):
return HttpResponse(
generate_receipt_pdf(pk, request, True),
)
class ReceiptPDFView(View):
"""Renders a receipt as a PDF, prompting to download it."""
def get(self, request, pk):
response = HttpResponse(content_type='application/pdf')
response['Content-Disposition'] = 'attachment; filename=' + \
_('receipt %s.pdf' % pk)
generate_receipt_pdf(pk, response)
return response
class ReceiptPDFDisplayView(View):
"""
Renders a receipt as a PDF.
Browsers should render the file, rather than prompt to download it.
"""
def get(self, request, pk):
response = HttpResponse(content_type='application/pdf')
generate_receipt_pdf(pk, response)
return response
| Add a view to display PDF receipts | Add a view to display PDF receipts
Fixes #23
Closes !7
Closes !8
| Python | isc | hobarrera/django-afip,hobarrera/django-afip | from django.http import HttpResponse
from django.utils.translation import ugettext as _
from django.views.generic import View
from .pdf import generate_receipt_pdf
class ReceiptHTMLView(View):
-
+ """Renders a receipt as HTML."""
def get(self, request, pk):
return HttpResponse(
generate_receipt_pdf(pk, request, True),
)
class ReceiptPDFView(View):
+ """Renders a receipt as a PDF, prompting to download it."""
def get(self, request, pk):
response = HttpResponse(content_type='application/pdf')
response['Content-Disposition'] = 'attachment; filename=' + \
_('receipt %s.pdf' % pk)
generate_receipt_pdf(pk, response)
return response
+
+ class ReceiptPDFDisplayView(View):
+ """
+ Renders a receipt as a PDF.
+
+ Browsers should render the file, rather than prompt to download it.
+ """
+ def get(self, request, pk):
+ response = HttpResponse(content_type='application/pdf')
+ generate_receipt_pdf(pk, response)
+ return response
+ | Add a view to display PDF receipts | ## Code Before:
from django.http import HttpResponse
from django.utils.translation import ugettext as _
from django.views.generic import View
from .pdf import generate_receipt_pdf
class ReceiptHTMLView(View):
def get(self, request, pk):
return HttpResponse(
generate_receipt_pdf(pk, request, True),
)
class ReceiptPDFView(View):
def get(self, request, pk):
response = HttpResponse(content_type='application/pdf')
response['Content-Disposition'] = 'attachment; filename=' + \
_('receipt %s.pdf' % pk)
generate_receipt_pdf(pk, response)
return response
## Instruction:
Add a view to display PDF receipts
## Code After:
from django.http import HttpResponse
from django.utils.translation import ugettext as _
from django.views.generic import View
from .pdf import generate_receipt_pdf
class ReceiptHTMLView(View):
"""Renders a receipt as HTML."""
def get(self, request, pk):
return HttpResponse(
generate_receipt_pdf(pk, request, True),
)
class ReceiptPDFView(View):
"""Renders a receipt as a PDF, prompting to download it."""
def get(self, request, pk):
response = HttpResponse(content_type='application/pdf')
response['Content-Disposition'] = 'attachment; filename=' + \
_('receipt %s.pdf' % pk)
generate_receipt_pdf(pk, response)
return response
class ReceiptPDFDisplayView(View):
"""
Renders a receipt as a PDF.
Browsers should render the file, rather than prompt to download it.
"""
def get(self, request, pk):
response = HttpResponse(content_type='application/pdf')
generate_receipt_pdf(pk, response)
return response
|
03d8a4e20ee4b6fd49495b7b047ea78d0b9a5bb4 | dmoj/graders/base.py | dmoj/graders/base.py | class BaseGrader(object):
def __init__(self, judge, problem, language, source):
self.source = source
self.language = language
self.problem = problem
self.judge = judge
self.binary = self._generate_binary()
self._terminate_grading = False
self._current_proc = None
def grade(self, case):
raise NotImplementedError
def _generate_binary(self):
raise NotImplementedError
def terminate_grading(self):
self._terminate_grading = True
if self._current_proc:
try:
self._current_proc.kill()
except OSError:
pass
pass
| class BaseGrader(object):
def __init__(self, judge, problem, language, source):
if isinstance(source, unicode):
source = source.encode('utf-8')
self.source = source
self.language = language
self.problem = problem
self.judge = judge
self.binary = self._generate_binary()
self._terminate_grading = False
self._current_proc = None
def grade(self, case):
raise NotImplementedError
def _generate_binary(self):
raise NotImplementedError
def terminate_grading(self):
self._terminate_grading = True
if self._current_proc:
try:
self._current_proc.kill()
except OSError:
pass
pass
| Make source utf-8 encoded bytes. | Make source utf-8 encoded bytes.
| Python | agpl-3.0 | DMOJ/judge,DMOJ/judge,DMOJ/judge | class BaseGrader(object):
def __init__(self, judge, problem, language, source):
+ if isinstance(source, unicode):
+ source = source.encode('utf-8')
self.source = source
self.language = language
self.problem = problem
self.judge = judge
self.binary = self._generate_binary()
self._terminate_grading = False
self._current_proc = None
def grade(self, case):
raise NotImplementedError
def _generate_binary(self):
raise NotImplementedError
def terminate_grading(self):
self._terminate_grading = True
if self._current_proc:
try:
self._current_proc.kill()
except OSError:
pass
pass
| Make source utf-8 encoded bytes. | ## Code Before:
class BaseGrader(object):
def __init__(self, judge, problem, language, source):
self.source = source
self.language = language
self.problem = problem
self.judge = judge
self.binary = self._generate_binary()
self._terminate_grading = False
self._current_proc = None
def grade(self, case):
raise NotImplementedError
def _generate_binary(self):
raise NotImplementedError
def terminate_grading(self):
self._terminate_grading = True
if self._current_proc:
try:
self._current_proc.kill()
except OSError:
pass
pass
## Instruction:
Make source utf-8 encoded bytes.
## Code After:
class BaseGrader(object):
def __init__(self, judge, problem, language, source):
if isinstance(source, unicode):
source = source.encode('utf-8')
self.source = source
self.language = language
self.problem = problem
self.judge = judge
self.binary = self._generate_binary()
self._terminate_grading = False
self._current_proc = None
def grade(self, case):
raise NotImplementedError
def _generate_binary(self):
raise NotImplementedError
def terminate_grading(self):
self._terminate_grading = True
if self._current_proc:
try:
self._current_proc.kill()
except OSError:
pass
pass
|
e14b3fad26dce8dad3ca97c06e624f1d6b0764f9 | mqueue/__init__.py | mqueue/__init__.py | __version__ = '0.5.5'
default_app_config = 'mqueue.apps.MqueueConfig'
| __version__ = '0.5.5'
default_app_config = 'mqueue.apps.MqueueConfig'
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
| Set default encoding to fix unicode errors | Set default encoding to fix unicode errors
| Python | mit | synw/django-mqueue,synw/django-mqueue,synw/django-mqueue | __version__ = '0.5.5'
default_app_config = 'mqueue.apps.MqueueConfig'
+
+ import sys
+ reload(sys)
+ sys.setdefaultencoding("utf-8")
| Set default encoding to fix unicode errors | ## Code Before:
__version__ = '0.5.5'
default_app_config = 'mqueue.apps.MqueueConfig'
## Instruction:
Set default encoding to fix unicode errors
## Code After:
__version__ = '0.5.5'
default_app_config = 'mqueue.apps.MqueueConfig'
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
|
50836f606c5bdb9aa4472d109f0dc40e2f0f8dc6 | examples/apc2016/download_dataset.py | examples/apc2016/download_dataset.py |
import os.path as osp
import chainer
import fcn.data
import fcn.util
def main():
dataset_dir = chainer.dataset.get_dataset_directory('apc2016')
path = osp.join(dataset_dir, 'APC2016rbo.tgz')
fcn.data.cached_download(
url='https://drive.google.com/uc?id=0B9P1L--7Wd2vSV9oLTd1U2I3TDg',
path=path,
)
fcn.util.extract_file(path, to_directory=dataset_dir)
path = osp.join(dataset_dir, 'APC2016JSKseg/annotated.tgz')
fcn.data.cached_download(
url='https://drive.google.com/uc?id=0B9P1L--7Wd2vaExFU1AxWHlMdTg',
path=path,
)
fcn.util.extract_file(path, to_directory=dataset_dir)
if __name__ == '__main__':
main()
|
import os.path as osp
import chainer
import fcn
def main():
dataset_dir = chainer.dataset.get_dataset_directory('apc2016')
path = osp.join(dataset_dir, 'APC2016rbo.tgz')
fcn.data.cached_download(
url='https://drive.google.com/uc?id=0B9P1L--7Wd2vSV9oLTd1U2I3TDg',
path=path,
)
fcn.util.extract_file(path, to_directory=dataset_dir)
path = osp.join(dataset_dir, 'APC2016JSKseg/annotated.tgz')
fcn.data.cached_download(
url='https://drive.google.com/uc?id=0B9P1L--7Wd2vaExFU1AxWHlMdTg',
path=path,
)
fcn.utils.extract_file(path, to_directory=dataset_dir)
if __name__ == '__main__':
main()
| Fix for renamed module util -> utils | Fix for renamed module util -> utils
| Python | mit | wkentaro/fcn |
import os.path as osp
import chainer
- import fcn.data
+ import fcn
- import fcn.util
def main():
-
dataset_dir = chainer.dataset.get_dataset_directory('apc2016')
path = osp.join(dataset_dir, 'APC2016rbo.tgz')
fcn.data.cached_download(
url='https://drive.google.com/uc?id=0B9P1L--7Wd2vSV9oLTd1U2I3TDg',
path=path,
)
fcn.util.extract_file(path, to_directory=dataset_dir)
path = osp.join(dataset_dir, 'APC2016JSKseg/annotated.tgz')
fcn.data.cached_download(
url='https://drive.google.com/uc?id=0B9P1L--7Wd2vaExFU1AxWHlMdTg',
path=path,
)
- fcn.util.extract_file(path, to_directory=dataset_dir)
+ fcn.utils.extract_file(path, to_directory=dataset_dir)
if __name__ == '__main__':
main()
| Fix for renamed module util -> utils | ## Code Before:
import os.path as osp
import chainer
import fcn.data
import fcn.util
def main():
dataset_dir = chainer.dataset.get_dataset_directory('apc2016')
path = osp.join(dataset_dir, 'APC2016rbo.tgz')
fcn.data.cached_download(
url='https://drive.google.com/uc?id=0B9P1L--7Wd2vSV9oLTd1U2I3TDg',
path=path,
)
fcn.util.extract_file(path, to_directory=dataset_dir)
path = osp.join(dataset_dir, 'APC2016JSKseg/annotated.tgz')
fcn.data.cached_download(
url='https://drive.google.com/uc?id=0B9P1L--7Wd2vaExFU1AxWHlMdTg',
path=path,
)
fcn.util.extract_file(path, to_directory=dataset_dir)
if __name__ == '__main__':
main()
## Instruction:
Fix for renamed module util -> utils
## Code After:
import os.path as osp
import chainer
import fcn
def main():
dataset_dir = chainer.dataset.get_dataset_directory('apc2016')
path = osp.join(dataset_dir, 'APC2016rbo.tgz')
fcn.data.cached_download(
url='https://drive.google.com/uc?id=0B9P1L--7Wd2vSV9oLTd1U2I3TDg',
path=path,
)
fcn.util.extract_file(path, to_directory=dataset_dir)
path = osp.join(dataset_dir, 'APC2016JSKseg/annotated.tgz')
fcn.data.cached_download(
url='https://drive.google.com/uc?id=0B9P1L--7Wd2vaExFU1AxWHlMdTg',
path=path,
)
fcn.utils.extract_file(path, to_directory=dataset_dir)
if __name__ == '__main__':
main()
|
3caab02c5e0ca0ebc57f57c77ed550b7e3fc55d2 | analyze.py | analyze.py | import os
import pickle
import numpy as np
import matplotlib.pyplot as plt
from datetime import datetime
def load_data(data_path):
'''Return dictionary `data` from string `data_path`
'''
os.path.join(data_path, '1.dat')
data = pickle.load(open(data_path, 'rb'))
return data
def get_baseline(data):
'''Get most recent baseline/calibration from subject.
'''
baselines = []
for k, v in data.items():
if 'baseline' in v:
print(k, v)
baselines.append((k, v))
# Get most recent baseline
return sorted(baselines)[-1][1].split(' ')[-1]
def get_distances(data):
'''Get tuple of posture measurements with time stamps.
Returns:
Tuple - (time_object, distances)
'''
distances = []
for k, v in data.items():
if type(v).__module__ == 'numpy':
# Convert strings to datetime object
time_object = datetime.strptime(k, '%Y-%m-%d_%H-%M-%S')
distances.append((time_object, v[0][2]))
# Sort readings by time to restore order
time_objects, dists = zip(*sorted(zip(time_objects, widths)))
return time_object, dists
def plot(time_objects, dists):
pass
| import os
import pickle
import numpy as np
import matplotlib.pyplot as plt
from glob import glob
from datetime import datetime
def load_data(data_path):
'''Return dictionary `data` from string `data_path`
'''
os.path.join(data_path, '1.dat')
data = pickle.load(open(data_path, 'rb'))
return data
def get_baseline(data):
'''Get most recent baseline/calibration from subject.
'''
baselines = []
for k, v in data.items():
if 'baseline' in v:
print(k, v)
baselines.append((k, v))
# Get most recent baseline
return sorted(baselines)[-1][1].split(' ')[-1]
def get_distances(data):
'''Get tuple of posture measurements with time stamps.
Returns:
Tuple - (time_object, distances)
'''
distances = []
for k, v in data.items():
if type(v).__module__ == 'numpy':
# Convert strings to datetime object
time_object = datetime.strptime(k, '%Y-%m-%d_%H-%M-%S')
distances.append((time_object, v[0][2]))
# Sort readings by time to restore order
time_objects, dists = zip(*sorted(zip(time_objects, widths)))
return time_object, dists
def load_data_files(data_folder_path='data'):
data_folder = os.path.join(os.getcwd(), data_folder_path)
files = []
for file in glob(data_folder + "/*/*"):
if '.dat' in file:
files.append(file)
return files
def plot(time_objects, dists):
pass
| Add helper functions for loading data | Add helper functions for loading data
| Python | mit | JustinShenk/sensei | import os
import pickle
import numpy as np
import matplotlib.pyplot as plt
+ from glob import glob
from datetime import datetime
def load_data(data_path):
'''Return dictionary `data` from string `data_path`
'''
os.path.join(data_path, '1.dat')
data = pickle.load(open(data_path, 'rb'))
return data
def get_baseline(data):
'''Get most recent baseline/calibration from subject.
'''
baselines = []
for k, v in data.items():
if 'baseline' in v:
print(k, v)
baselines.append((k, v))
# Get most recent baseline
return sorted(baselines)[-1][1].split(' ')[-1]
def get_distances(data):
'''Get tuple of posture measurements with time stamps.
Returns:
Tuple - (time_object, distances)
'''
distances = []
for k, v in data.items():
if type(v).__module__ == 'numpy':
# Convert strings to datetime object
time_object = datetime.strptime(k, '%Y-%m-%d_%H-%M-%S')
distances.append((time_object, v[0][2]))
# Sort readings by time to restore order
time_objects, dists = zip(*sorted(zip(time_objects, widths)))
return time_object, dists
+ def load_data_files(data_folder_path='data'):
+ data_folder = os.path.join(os.getcwd(), data_folder_path)
+ files = []
+ for file in glob(data_folder + "/*/*"):
+ if '.dat' in file:
+ files.append(file)
+ return files
+
+
def plot(time_objects, dists):
pass
| Add helper functions for loading data | ## Code Before:
import os
import pickle
import numpy as np
import matplotlib.pyplot as plt
from datetime import datetime
def load_data(data_path):
'''Return dictionary `data` from string `data_path`
'''
os.path.join(data_path, '1.dat')
data = pickle.load(open(data_path, 'rb'))
return data
def get_baseline(data):
'''Get most recent baseline/calibration from subject.
'''
baselines = []
for k, v in data.items():
if 'baseline' in v:
print(k, v)
baselines.append((k, v))
# Get most recent baseline
return sorted(baselines)[-1][1].split(' ')[-1]
def get_distances(data):
'''Get tuple of posture measurements with time stamps.
Returns:
Tuple - (time_object, distances)
'''
distances = []
for k, v in data.items():
if type(v).__module__ == 'numpy':
# Convert strings to datetime object
time_object = datetime.strptime(k, '%Y-%m-%d_%H-%M-%S')
distances.append((time_object, v[0][2]))
# Sort readings by time to restore order
time_objects, dists = zip(*sorted(zip(time_objects, widths)))
return time_object, dists
def plot(time_objects, dists):
pass
## Instruction:
Add helper functions for loading data
## Code After:
import os
import pickle
import numpy as np
import matplotlib.pyplot as plt
from glob import glob
from datetime import datetime
def load_data(data_path):
'''Return dictionary `data` from string `data_path`
'''
os.path.join(data_path, '1.dat')
data = pickle.load(open(data_path, 'rb'))
return data
def get_baseline(data):
'''Get most recent baseline/calibration from subject.
'''
baselines = []
for k, v in data.items():
if 'baseline' in v:
print(k, v)
baselines.append((k, v))
# Get most recent baseline
return sorted(baselines)[-1][1].split(' ')[-1]
def get_distances(data):
'''Get tuple of posture measurements with time stamps.
Returns:
Tuple - (time_object, distances)
'''
distances = []
for k, v in data.items():
if type(v).__module__ == 'numpy':
# Convert strings to datetime object
time_object = datetime.strptime(k, '%Y-%m-%d_%H-%M-%S')
distances.append((time_object, v[0][2]))
# Sort readings by time to restore order
time_objects, dists = zip(*sorted(zip(time_objects, widths)))
return time_object, dists
def load_data_files(data_folder_path='data'):
data_folder = os.path.join(os.getcwd(), data_folder_path)
files = []
for file in glob(data_folder + "/*/*"):
if '.dat' in file:
files.append(file)
return files
def plot(time_objects, dists):
pass
|
82457741a352602f6ef946e387070c77eb50781c | examples/macallan.py | examples/macallan.py |
from malt import Malt, Response, json
from wsgiref.simple_server import make_server
app = Malt()
@app.get('/')
def hello(request):
return Response(request.url + '\n')
@app.post('/users')
def hello(request):
return Response('Creating new user\n')
@app.get('/tasks')
def hello(request):
return json({'tasks': [
'Buy groceries',
'Clean the patio',
'Take over the world',
]})
@app.post('/tasks')
def hello(request):
return Response('Adding a task!\n')
server = make_server('localhost', 5000, app)
server.serve_forever()
|
from malt import Malt, Response, json
from wsgiref.simple_server import make_server
app = Malt()
@app.get('/')
def hello(request):
return Response(request.url + '\n')
@app.post('/users')
def hello(request):
return Response('Creating new user\n')
@app.get('/tasks')
def hello(request):
return json({'tasks': [
'Buy groceries',
'Clean the patio',
'Take over the world',
]})
@app.post('/tasks')
def hello(request):
return Response('Adding a task!\n')
server = make_server('localhost', 5000, app)
print('Running locally on http://localhost:5000')
server.serve_forever()
| Print a serving message in the example app | Print a serving message in the example app
| Python | mit | nickfrostatx/malt |
from malt import Malt, Response, json
from wsgiref.simple_server import make_server
app = Malt()
@app.get('/')
def hello(request):
return Response(request.url + '\n')
@app.post('/users')
def hello(request):
return Response('Creating new user\n')
@app.get('/tasks')
def hello(request):
return json({'tasks': [
'Buy groceries',
'Clean the patio',
'Take over the world',
]})
@app.post('/tasks')
def hello(request):
return Response('Adding a task!\n')
server = make_server('localhost', 5000, app)
+ print('Running locally on http://localhost:5000')
server.serve_forever()
| Print a serving message in the example app | ## Code Before:
from malt import Malt, Response, json
from wsgiref.simple_server import make_server
app = Malt()
@app.get('/')
def hello(request):
return Response(request.url + '\n')
@app.post('/users')
def hello(request):
return Response('Creating new user\n')
@app.get('/tasks')
def hello(request):
return json({'tasks': [
'Buy groceries',
'Clean the patio',
'Take over the world',
]})
@app.post('/tasks')
def hello(request):
return Response('Adding a task!\n')
server = make_server('localhost', 5000, app)
server.serve_forever()
## Instruction:
Print a serving message in the example app
## Code After:
from malt import Malt, Response, json
from wsgiref.simple_server import make_server
app = Malt()
@app.get('/')
def hello(request):
return Response(request.url + '\n')
@app.post('/users')
def hello(request):
return Response('Creating new user\n')
@app.get('/tasks')
def hello(request):
return json({'tasks': [
'Buy groceries',
'Clean the patio',
'Take over the world',
]})
@app.post('/tasks')
def hello(request):
return Response('Adding a task!\n')
server = make_server('localhost', 5000, app)
print('Running locally on http://localhost:5000')
server.serve_forever()
|
a3d65892ef572b115de919f62929e093dfb27400 | examples/json_editor.py | examples/json_editor.py | import logging
import os
import sys
from pyqode.qt import QtWidgets
from pyqode.json.widgets import JSONCodeEdit
class Window(QtWidgets.QMainWindow):
def __init__(self):
super(Window, self).__init__()
self.setMinimumWidth(800)
self.setMinimumHeight(600)
self.editor = JSONCodeEdit(self)
self.setCentralWidget(self.editor)
self.editor.file.open(
os.path.abspath(os.path.join(
'..', 'test', 'files', 'example.json')))
logging.basicConfig(level=logging.INFO)
app = QtWidgets.QApplication(sys.argv)
window = Window()
window.show()
app.exec_()
| import logging
import os
import random
import sys
from pyqode.qt import QtWidgets
from pyqode.core import api, modes
from pyqode.json.widgets import JSONCodeEdit
class Window(QtWidgets.QMainWindow):
def __init__(self):
super(Window, self).__init__()
self.setMinimumWidth(800)
self.setMinimumHeight(600)
self.editor = JSONCodeEdit(self)
self.setCentralWidget(self.editor)
self.editor.file.open(
os.path.abspath(os.path.join(
'..', 'test', 'files', 'example.json')))
# pygment_style = random.choice(modes.PYGMENTS_STYLES)
# logging.info('pygments style: %s', pygment_style)
# self.editor.syntax_highlighter.color_scheme = api.ColorScheme(
# pygment_style)
logging.basicConfig(level=logging.INFO)
app = QtWidgets.QApplication(sys.argv)
window = Window()
window.show()
app.exec_()
| Make example use random color scheme | Make example use random color scheme
| Python | mit | pyQode/pyqode.json,pyQode/pyqode.json | import logging
import os
+ import random
import sys
from pyqode.qt import QtWidgets
+ from pyqode.core import api, modes
from pyqode.json.widgets import JSONCodeEdit
class Window(QtWidgets.QMainWindow):
def __init__(self):
super(Window, self).__init__()
self.setMinimumWidth(800)
self.setMinimumHeight(600)
self.editor = JSONCodeEdit(self)
self.setCentralWidget(self.editor)
self.editor.file.open(
os.path.abspath(os.path.join(
'..', 'test', 'files', 'example.json')))
+ # pygment_style = random.choice(modes.PYGMENTS_STYLES)
+ # logging.info('pygments style: %s', pygment_style)
+ # self.editor.syntax_highlighter.color_scheme = api.ColorScheme(
+ # pygment_style)
logging.basicConfig(level=logging.INFO)
app = QtWidgets.QApplication(sys.argv)
window = Window()
window.show()
app.exec_()
| Make example use random color scheme | ## Code Before:
import logging
import os
import sys
from pyqode.qt import QtWidgets
from pyqode.json.widgets import JSONCodeEdit
class Window(QtWidgets.QMainWindow):
def __init__(self):
super(Window, self).__init__()
self.setMinimumWidth(800)
self.setMinimumHeight(600)
self.editor = JSONCodeEdit(self)
self.setCentralWidget(self.editor)
self.editor.file.open(
os.path.abspath(os.path.join(
'..', 'test', 'files', 'example.json')))
logging.basicConfig(level=logging.INFO)
app = QtWidgets.QApplication(sys.argv)
window = Window()
window.show()
app.exec_()
## Instruction:
Make example use random color scheme
## Code After:
import logging
import os
import random
import sys
from pyqode.qt import QtWidgets
from pyqode.core import api, modes
from pyqode.json.widgets import JSONCodeEdit
class Window(QtWidgets.QMainWindow):
def __init__(self):
super(Window, self).__init__()
self.setMinimumWidth(800)
self.setMinimumHeight(600)
self.editor = JSONCodeEdit(self)
self.setCentralWidget(self.editor)
self.editor.file.open(
os.path.abspath(os.path.join(
'..', 'test', 'files', 'example.json')))
# pygment_style = random.choice(modes.PYGMENTS_STYLES)
# logging.info('pygments style: %s', pygment_style)
# self.editor.syntax_highlighter.color_scheme = api.ColorScheme(
# pygment_style)
logging.basicConfig(level=logging.INFO)
app = QtWidgets.QApplication(sys.argv)
window = Window()
window.show()
app.exec_()
|
7d10c18c1feb0c61aee9d3a44c3a7fa24e4e3c25 | code_snippets/guides-agentchecks-methods.py | code_snippets/guides-agentchecks-methods.py | self.gauge( ... ) # Sample a gauge metric
self.increment( ... ) # Increment a counter metric
self.decrement( ... ) # Decrement a counter metric
self.histogram( ... ) # Sample a histogram metric
self.rate( ... ) # Sample a point, with the rate calculated at the end of the check
self.count( ... ) # Sample a raw count metric
self.monotonic_count( ... ) # Sample an increasing counter metric
| self.gauge( ... ) # Sample a gauge metric
self.increment( ... ) # Increment a counter metric
self.decrement( ... ) # Decrement a counter metric
self.histogram( ... ) # Sample a histogram metric
self.rate( ... ) # Sample a point, with the rate calculated at the end of the check
| Revert "Document AgentCheck count and monotonic_count methods" | Revert "Document AgentCheck count and monotonic_count methods"
This reverts commit e731c3a4a8590f5cddd23fd2f9af265749f08a38.
| Python | bsd-3-clause | inokappa/documentation,macobo/documentation,inokappa/documentation,jhotta/documentation,jhotta/documentation,jhotta/documentation,macobo/documentation,macobo/documentation,inokappa/documentation,jhotta/documentation,jhotta/documentation,jhotta/documentation,inokappa/documentation,inokappa/documentation,macobo/documentation,macobo/documentation | self.gauge( ... ) # Sample a gauge metric
self.increment( ... ) # Increment a counter metric
self.decrement( ... ) # Decrement a counter metric
self.histogram( ... ) # Sample a histogram metric
self.rate( ... ) # Sample a point, with the rate calculated at the end of the check
- self.count( ... ) # Sample a raw count metric
-
- self.monotonic_count( ... ) # Sample an increasing counter metric
- | Revert "Document AgentCheck count and monotonic_count methods" | ## Code Before:
self.gauge( ... ) # Sample a gauge metric
self.increment( ... ) # Increment a counter metric
self.decrement( ... ) # Decrement a counter metric
self.histogram( ... ) # Sample a histogram metric
self.rate( ... ) # Sample a point, with the rate calculated at the end of the check
self.count( ... ) # Sample a raw count metric
self.monotonic_count( ... ) # Sample an increasing counter metric
## Instruction:
Revert "Document AgentCheck count and monotonic_count methods"
## Code After:
self.gauge( ... ) # Sample a gauge metric
self.increment( ... ) # Increment a counter metric
self.decrement( ... ) # Decrement a counter metric
self.histogram( ... ) # Sample a histogram metric
self.rate( ... ) # Sample a point, with the rate calculated at the end of the check
|
d207bf14b30636959e09659607bddcf4e349852b | django_migration_linter/sql_analyser/__init__.py | django_migration_linter/sql_analyser/__init__.py | from .analyser import analyse_sql_statements # noqa
from .base import BaseAnalyser # noqa
from .mysql import MySqlAnalyser # noqa
from .postgresql import PostgresqlAnalyser # noqa
from .sqlite import SqliteAnalyser # noqa
| from .base import BaseAnalyser # noqa
from .mysql import MySqlAnalyser # noqa
from .postgresql import PostgresqlAnalyser # noqa
from .sqlite import SqliteAnalyser # noqa
from .analyser import analyse_sql_statements # noqa isort:skip
| Fix import order which was important | Fix import order which was important
| Python | apache-2.0 | 3YOURMIND/django-migration-linter | - from .analyser import analyse_sql_statements # noqa
from .base import BaseAnalyser # noqa
from .mysql import MySqlAnalyser # noqa
from .postgresql import PostgresqlAnalyser # noqa
from .sqlite import SqliteAnalyser # noqa
+ from .analyser import analyse_sql_statements # noqa isort:skip
+ | Fix import order which was important | ## Code Before:
from .analyser import analyse_sql_statements # noqa
from .base import BaseAnalyser # noqa
from .mysql import MySqlAnalyser # noqa
from .postgresql import PostgresqlAnalyser # noqa
from .sqlite import SqliteAnalyser # noqa
## Instruction:
Fix import order which was important
## Code After:
from .base import BaseAnalyser # noqa
from .mysql import MySqlAnalyser # noqa
from .postgresql import PostgresqlAnalyser # noqa
from .sqlite import SqliteAnalyser # noqa
from .analyser import analyse_sql_statements # noqa isort:skip
|
5f113ffd768431991f87cea1f5f804a25a1777d3 | frappe/patches/v13_0/replace_old_data_import.py | frappe/patches/v13_0/replace_old_data_import.py |
from __future__ import unicode_literals
import frappe
def execute():
frappe.db.sql(
"""INSERT INTO `tabData Import Legacy` SELECT * FROM `tabData Import`"""
)
frappe.db.commit()
frappe.db.sql("DROP TABLE IF EXISTS `tabData Import`")
frappe.reload_doc("core", "doctype", "data_import")
frappe.get_doc("DocType", "Data Import").on_update()
|
from __future__ import unicode_literals
import frappe
def execute():
frappe.rename_doc('DocType', 'Data Import', 'Data Import Legacy')
frappe.db.commit()
frappe.db.sql("DROP TABLE IF EXISTS `tabData Import`")
frappe.reload_doc("core", "doctype", "data_import")
frappe.get_doc("DocType", "Data Import").on_update()
| Use rename doc instead of manually moving the data | fix: Use rename doc instead of manually moving the data
| Python | mit | StrellaGroup/frappe,saurabh6790/frappe,mhbu50/frappe,yashodhank/frappe,frappe/frappe,yashodhank/frappe,almeidapaulopt/frappe,yashodhank/frappe,frappe/frappe,mhbu50/frappe,almeidapaulopt/frappe,adityahase/frappe,saurabh6790/frappe,frappe/frappe,adityahase/frappe,mhbu50/frappe,adityahase/frappe,almeidapaulopt/frappe,yashodhank/frappe,almeidapaulopt/frappe,mhbu50/frappe,adityahase/frappe,StrellaGroup/frappe,saurabh6790/frappe,saurabh6790/frappe,StrellaGroup/frappe |
from __future__ import unicode_literals
import frappe
def execute():
+ frappe.rename_doc('DocType', 'Data Import', 'Data Import Legacy')
- frappe.db.sql(
- """INSERT INTO `tabData Import Legacy` SELECT * FROM `tabData Import`"""
- )
frappe.db.commit()
frappe.db.sql("DROP TABLE IF EXISTS `tabData Import`")
frappe.reload_doc("core", "doctype", "data_import")
frappe.get_doc("DocType", "Data Import").on_update()
| Use rename doc instead of manually moving the data | ## Code Before:
from __future__ import unicode_literals
import frappe
def execute():
frappe.db.sql(
"""INSERT INTO `tabData Import Legacy` SELECT * FROM `tabData Import`"""
)
frappe.db.commit()
frappe.db.sql("DROP TABLE IF EXISTS `tabData Import`")
frappe.reload_doc("core", "doctype", "data_import")
frappe.get_doc("DocType", "Data Import").on_update()
## Instruction:
Use rename doc instead of manually moving the data
## Code After:
from __future__ import unicode_literals
import frappe
def execute():
frappe.rename_doc('DocType', 'Data Import', 'Data Import Legacy')
frappe.db.commit()
frappe.db.sql("DROP TABLE IF EXISTS `tabData Import`")
frappe.reload_doc("core", "doctype", "data_import")
frappe.get_doc("DocType", "Data Import").on_update()
|
216294a0ea36c2fbabb43c31ce4fde3a9eee4bf3 | anchor/models.py | anchor/models.py |
from datetime import datetime
from dateutil import tz
from dateutil.relativedelta import relativedelta
UTC = tz.tzutc()
class Region:
def __init__(self, data):
self.name = data.get('name').title()
self.abbreviation = data.get('abbreviation').upper()
self.active = bool(data.get('active'))
class Account:
def __init__(self, data):
self.account_number = data.get('account_number')
self.cache_expiration = self.set_expiration()
self.host_servers = data.get('host_servers')
self.public_zones = data.get('public_zones')
self.region = data.get('region').lower()
self.servers = data.get('servers')
self.lookup_type = data.get('lookup_type')
def set_expiration(self):
return datetime.now(UTC) + relativedelta(days=1)
|
from datetime import datetime
from dateutil import tz
from dateutil.relativedelta import relativedelta
UTC = tz.tzutc()
class Region:
def __init__(self, data):
self.name = data.get('name').title()
self.abbreviation = data.get('abbreviation').upper()
self.active = bool(data.get('active'))
class Account:
def __init__(self, data):
self.account_number = data.get('account_number')
self.cache_expiration = self.set_expiration()
self.host_servers = data.get('host_servers')
self.public_zones = data.get('public_zones')
self.region = data.get('region').lower()
self.servers = data.get('servers')
self.volumes = data.get('volumes')
self.cbs_hosts = data.get('cbs_hosts')
self.lookup_type = data.get('lookup_type')
def set_expiration(self):
return datetime.now(UTC) + relativedelta(days=1)
| Update model for CBS host and volume information | Update model for CBS host and volume information
| Python | apache-2.0 | oldarmyc/anchor,oldarmyc/anchor,oldarmyc/anchor |
from datetime import datetime
from dateutil import tz
from dateutil.relativedelta import relativedelta
UTC = tz.tzutc()
class Region:
def __init__(self, data):
self.name = data.get('name').title()
self.abbreviation = data.get('abbreviation').upper()
self.active = bool(data.get('active'))
class Account:
def __init__(self, data):
self.account_number = data.get('account_number')
self.cache_expiration = self.set_expiration()
self.host_servers = data.get('host_servers')
self.public_zones = data.get('public_zones')
self.region = data.get('region').lower()
self.servers = data.get('servers')
+ self.volumes = data.get('volumes')
+ self.cbs_hosts = data.get('cbs_hosts')
self.lookup_type = data.get('lookup_type')
def set_expiration(self):
return datetime.now(UTC) + relativedelta(days=1)
| Update model for CBS host and volume information | ## Code Before:
from datetime import datetime
from dateutil import tz
from dateutil.relativedelta import relativedelta
UTC = tz.tzutc()
class Region:
def __init__(self, data):
self.name = data.get('name').title()
self.abbreviation = data.get('abbreviation').upper()
self.active = bool(data.get('active'))
class Account:
def __init__(self, data):
self.account_number = data.get('account_number')
self.cache_expiration = self.set_expiration()
self.host_servers = data.get('host_servers')
self.public_zones = data.get('public_zones')
self.region = data.get('region').lower()
self.servers = data.get('servers')
self.lookup_type = data.get('lookup_type')
def set_expiration(self):
return datetime.now(UTC) + relativedelta(days=1)
## Instruction:
Update model for CBS host and volume information
## Code After:
from datetime import datetime
from dateutil import tz
from dateutil.relativedelta import relativedelta
UTC = tz.tzutc()
class Region:
def __init__(self, data):
self.name = data.get('name').title()
self.abbreviation = data.get('abbreviation').upper()
self.active = bool(data.get('active'))
class Account:
def __init__(self, data):
self.account_number = data.get('account_number')
self.cache_expiration = self.set_expiration()
self.host_servers = data.get('host_servers')
self.public_zones = data.get('public_zones')
self.region = data.get('region').lower()
self.servers = data.get('servers')
self.volumes = data.get('volumes')
self.cbs_hosts = data.get('cbs_hosts')
self.lookup_type = data.get('lookup_type')
def set_expiration(self):
return datetime.now(UTC) + relativedelta(days=1)
|
31fb8b576edda4d88685fd45537f68d3f067ae7b | source/cytoplasm/errors.py | source/cytoplasm/errors.py | class ControllerError(StandardError): pass
class InterpreterError(StandardError): pass
| class CytoplasmError(Exception): pass
class ControllerError(CytoplasmError): pass
class InterpreterError(CytoplasmError): pass
| Use Exception instead of StandardError | Use Exception instead of StandardError
Python 3 doesn't have StandardError...
| Python | mit | startling/cytoplasm | + class CytoplasmError(Exception): pass
- class ControllerError(StandardError): pass
+ class ControllerError(CytoplasmError): pass
- class InterpreterError(StandardError): pass
+ class InterpreterError(CytoplasmError): pass
| Use Exception instead of StandardError | ## Code Before:
class ControllerError(StandardError): pass
class InterpreterError(StandardError): pass
## Instruction:
Use Exception instead of StandardError
## Code After:
class CytoplasmError(Exception): pass
class ControllerError(CytoplasmError): pass
class InterpreterError(CytoplasmError): pass
|
a85c21dc324750c3fa7e96d2d0baf3c45657201e | sconsole/static.py | sconsole/static.py | '''
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_:
fp_.write(str(msg))
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')
]
else:
return [
('banner', 'white', 'dark blue')
]
| '''
Holds static data components, like the palette
'''
import pprint
def tree_seed():
return {'jids': [
{'_|-76789876543456787654': [{'localhost': {'return': True}},
{'otherhost': {'return': True}}],},
{'_|-76789876543456787655': [{'localhost': {'return': True}},
{'otherhost': {'return': True}}],},
],
}
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_:
fp_.write('{0}\n'.format(pprint.pformat(msg)))
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')
]
else:
return [
('banner', 'white', 'dark blue')
]
| Add convenience function to load in some test data | Add convenience function to load in some test data
| Python | apache-2.0 | saltstack/salt-console | '''
Holds static data components, like the palette
'''
+ import pprint
+
+ def tree_seed():
+ return {'jids': [
+ {'_|-76789876543456787654': [{'localhost': {'return': True}},
+ {'otherhost': {'return': True}}],},
+ {'_|-76789876543456787655': [{'localhost': {'return': True}},
+ {'otherhost': {'return': True}}],},
+ ],
+ }
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_:
- fp_.write(str(msg))
+ fp_.write('{0}\n'.format(pprint.pformat(msg)))
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')
]
else:
return [
('banner', 'white', 'dark blue')
]
| Add convenience function to load in some test data | ## Code Before:
'''
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_:
fp_.write(str(msg))
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')
]
else:
return [
('banner', 'white', 'dark blue')
]
## Instruction:
Add convenience function to load in some test data
## Code After:
'''
Holds static data components, like the palette
'''
import pprint
def tree_seed():
return {'jids': [
{'_|-76789876543456787654': [{'localhost': {'return': True}},
{'otherhost': {'return': True}}],},
{'_|-76789876543456787655': [{'localhost': {'return': True}},
{'otherhost': {'return': True}}],},
],
}
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_:
fp_.write('{0}\n'.format(pprint.pformat(msg)))
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')
]
else:
return [
('banner', 'white', 'dark blue')
]
|
cf245e71e770d21db8a48a74f8833d1099157e73 | txircd/modules/ircv3/multiprefix.py | txircd/modules/ircv3/multiprefix.py | from twisted.plugin import IPlugin
from txircd.module_interface import IModuleData, ModuleData
from zope.interface import implements
class MultiPrefix(ModuleData):
implements(IPlugin, IModuleData)
name = "MultiPrefix"
def actions(self):
return [ ("channelstatuses", 2, self.allStatuses),
("capabilitylist", 10, self.addCapability) ]
def load(self):
if "cap-add" in self.ircd.moduleFunctionCache:
self.ircd.moduleFunctionCache["cap-add"]("multi-prefix")
def unload(self):
if "cap-add" in self.ircd.moduleFunctionCache:
self.ircd.moduleFunctionCache["cap-add"]("multi-prefix")
def addCapability(self, capList):
capList.append("multi-prefix")
def allStatuses(self, channel, user, requestingUser):
if "capabilities" not in requestingUser.cache or "multi-prefix" not in requestingUser.cache["capabilities"]:
return None
if user not in channel.users:
return ""
statusList = []
for status in channel.users[user]["status"]:
statusList.append(self.ircd.channelStatuses[status][0])
return "".join(statusList)
multiPrefix = MultiPrefix() | from twisted.plugin import IPlugin
from txircd.module_interface import IModuleData, ModuleData
from zope.interface import implements
class MultiPrefix(ModuleData):
implements(IPlugin, IModuleData)
name = "MultiPrefix"
def actions(self):
return [ ("channelstatuses", 2, self.allStatuses),
("capabilitylist", 10, self.addCapability) ]
def load(self):
if "unloading-multi-prefix" in self.ircd.dataCache:
del self.ircd.dataCache["unloading-multi-prefix"]
return
if "cap-add" in self.ircd.functionCache:
self.ircd.functionCache["cap-add"]("multi-prefix")
def unload(self):
self.ircd.dataCache["unloading-multi-prefix"] = True
def fullUnload(self):
del self.ircd.dataCache["unloading-multi-prefix"]
if "cap-del" in self.ircd.functionCache:
self.ircd.functionCache["cap-del"]("multi-prefix")
def addCapability(self, capList):
capList.append("multi-prefix")
def allStatuses(self, channel, user, requestingUser):
if "capabilities" not in requestingUser.cache or "multi-prefix" not in requestingUser.cache["capabilities"]:
return None
if user not in channel.users:
return ""
statusList = []
for status in channel.users[user]["status"]:
statusList.append(self.ircd.channelStatuses[status][0])
return "".join(statusList)
multiPrefix = MultiPrefix() | Reduce undoings of multi-prefix on users | Reduce undoings of multi-prefix on users
| Python | bsd-3-clause | ElementalAlchemist/txircd,Heufneutje/txircd | from twisted.plugin import IPlugin
from txircd.module_interface import IModuleData, ModuleData
from zope.interface import implements
class MultiPrefix(ModuleData):
implements(IPlugin, IModuleData)
name = "MultiPrefix"
def actions(self):
return [ ("channelstatuses", 2, self.allStatuses),
("capabilitylist", 10, self.addCapability) ]
def load(self):
+ if "unloading-multi-prefix" in self.ircd.dataCache:
+ del self.ircd.dataCache["unloading-multi-prefix"]
+ return
- if "cap-add" in self.ircd.moduleFunctionCache:
+ if "cap-add" in self.ircd.functionCache:
- self.ircd.moduleFunctionCache["cap-add"]("multi-prefix")
+ self.ircd.functionCache["cap-add"]("multi-prefix")
def unload(self):
+ self.ircd.dataCache["unloading-multi-prefix"] = True
+
+ def fullUnload(self):
+ del self.ircd.dataCache["unloading-multi-prefix"]
- if "cap-add" in self.ircd.moduleFunctionCache:
+ if "cap-del" in self.ircd.functionCache:
- self.ircd.moduleFunctionCache["cap-add"]("multi-prefix")
+ self.ircd.functionCache["cap-del"]("multi-prefix")
def addCapability(self, capList):
capList.append("multi-prefix")
def allStatuses(self, channel, user, requestingUser):
if "capabilities" not in requestingUser.cache or "multi-prefix" not in requestingUser.cache["capabilities"]:
return None
if user not in channel.users:
return ""
statusList = []
for status in channel.users[user]["status"]:
statusList.append(self.ircd.channelStatuses[status][0])
return "".join(statusList)
multiPrefix = MultiPrefix() | Reduce undoings of multi-prefix on users | ## Code Before:
from twisted.plugin import IPlugin
from txircd.module_interface import IModuleData, ModuleData
from zope.interface import implements
class MultiPrefix(ModuleData):
implements(IPlugin, IModuleData)
name = "MultiPrefix"
def actions(self):
return [ ("channelstatuses", 2, self.allStatuses),
("capabilitylist", 10, self.addCapability) ]
def load(self):
if "cap-add" in self.ircd.moduleFunctionCache:
self.ircd.moduleFunctionCache["cap-add"]("multi-prefix")
def unload(self):
if "cap-add" in self.ircd.moduleFunctionCache:
self.ircd.moduleFunctionCache["cap-add"]("multi-prefix")
def addCapability(self, capList):
capList.append("multi-prefix")
def allStatuses(self, channel, user, requestingUser):
if "capabilities" not in requestingUser.cache or "multi-prefix" not in requestingUser.cache["capabilities"]:
return None
if user not in channel.users:
return ""
statusList = []
for status in channel.users[user]["status"]:
statusList.append(self.ircd.channelStatuses[status][0])
return "".join(statusList)
multiPrefix = MultiPrefix()
## Instruction:
Reduce undoings of multi-prefix on users
## Code After:
from twisted.plugin import IPlugin
from txircd.module_interface import IModuleData, ModuleData
from zope.interface import implements
class MultiPrefix(ModuleData):
implements(IPlugin, IModuleData)
name = "MultiPrefix"
def actions(self):
return [ ("channelstatuses", 2, self.allStatuses),
("capabilitylist", 10, self.addCapability) ]
def load(self):
if "unloading-multi-prefix" in self.ircd.dataCache:
del self.ircd.dataCache["unloading-multi-prefix"]
return
if "cap-add" in self.ircd.functionCache:
self.ircd.functionCache["cap-add"]("multi-prefix")
def unload(self):
self.ircd.dataCache["unloading-multi-prefix"] = True
def fullUnload(self):
del self.ircd.dataCache["unloading-multi-prefix"]
if "cap-del" in self.ircd.functionCache:
self.ircd.functionCache["cap-del"]("multi-prefix")
def addCapability(self, capList):
capList.append("multi-prefix")
def allStatuses(self, channel, user, requestingUser):
if "capabilities" not in requestingUser.cache or "multi-prefix" not in requestingUser.cache["capabilities"]:
return None
if user not in channel.users:
return ""
statusList = []
for status in channel.users[user]["status"]:
statusList.append(self.ircd.channelStatuses[status][0])
return "".join(statusList)
multiPrefix = MultiPrefix() |
1400a71d9827d76f14e70d4e8310dd20b9b47af4 | life/life.py | life/life.py | import sys, random, time
boardSize = (10,10)
while True: foo, bar, baz, globals()['board'] = None if globals().get('board') is None else [
(
[sys.stdout.write('X' if cell else ' ') for cell in row],
sys.stdout.write('\n')
) for row in board
], time.sleep(1), sys.stdout.write('==============\n'), [
[random.random() < 0.5 for i in range(boardSize[0])] for j in range(boardSize[1])
] if 'board' not in globals() else [
map(
lambda z: (z[1] in (2,3) and board[y][z[0]]) or z[1]==3,
[
(
x,
sum(
[
int(
y0 in range(len(board)) and x0 in range(len(board[y0])) and board[y0][x0]
) for x0,y0 in (
(x - 1, y - 1),
(x, y -1),
(x + 1, y - 1),
(x - 1, y),
(x + 1, y),
(x - 1, y + 1),
(x, y + 1),
(x + 1, y + 1)
)
]
)
) for x in range(len(board[y]))]
) for y in range(len(board))
]
| import sys, random, time
boardSize = (10,10)
while True: foo, bar, baz, globals()['board'] = None if globals().get('board') is None else [
(
[sys.stdout.write('X' if cell else ' ') for cell in row],
sys.stdout.write('\n')
) for row in board
], time.sleep(1), sys.stdout.write('=' * boardSize[0] +'\n'), [
[random.random() < 0.5 for i in range(boardSize[0])] for j in range(boardSize[1])
] if 'board' not in globals() else [
map(
lambda z: (z[1] in (2,3) and board[y][z[0]]) or z[1]==3,
[
(
x,
sum(
[
int(
y0 in range(len(board)) and x0 in range(len(board[y0])) and board[y0][x0]
) for x0,y0 in (
(x - 1, y - 1),
(x, y -1),
(x + 1, y - 1),
(x - 1, y),
(x + 1, y),
(x - 1, y + 1),
(x, y + 1),
(x + 1, y + 1)
)
]
)
) for x in range(len(board[y]))]
) for y in range(len(board))
]
| Make separator line match width of board | Make separator line match width of board
| Python | bsd-2-clause | bladams/golf | import sys, random, time
boardSize = (10,10)
while True: foo, bar, baz, globals()['board'] = None if globals().get('board') is None else [
(
[sys.stdout.write('X' if cell else ' ') for cell in row],
sys.stdout.write('\n')
) for row in board
- ], time.sleep(1), sys.stdout.write('==============\n'), [
+ ], time.sleep(1), sys.stdout.write('=' * boardSize[0] +'\n'), [
[random.random() < 0.5 for i in range(boardSize[0])] for j in range(boardSize[1])
] if 'board' not in globals() else [
map(
lambda z: (z[1] in (2,3) and board[y][z[0]]) or z[1]==3,
[
(
x,
sum(
[
int(
y0 in range(len(board)) and x0 in range(len(board[y0])) and board[y0][x0]
) for x0,y0 in (
(x - 1, y - 1),
(x, y -1),
(x + 1, y - 1),
(x - 1, y),
(x + 1, y),
(x - 1, y + 1),
(x, y + 1),
(x + 1, y + 1)
)
]
)
) for x in range(len(board[y]))]
) for y in range(len(board))
]
| Make separator line match width of board | ## Code Before:
import sys, random, time
boardSize = (10,10)
while True: foo, bar, baz, globals()['board'] = None if globals().get('board') is None else [
(
[sys.stdout.write('X' if cell else ' ') for cell in row],
sys.stdout.write('\n')
) for row in board
], time.sleep(1), sys.stdout.write('==============\n'), [
[random.random() < 0.5 for i in range(boardSize[0])] for j in range(boardSize[1])
] if 'board' not in globals() else [
map(
lambda z: (z[1] in (2,3) and board[y][z[0]]) or z[1]==3,
[
(
x,
sum(
[
int(
y0 in range(len(board)) and x0 in range(len(board[y0])) and board[y0][x0]
) for x0,y0 in (
(x - 1, y - 1),
(x, y -1),
(x + 1, y - 1),
(x - 1, y),
(x + 1, y),
(x - 1, y + 1),
(x, y + 1),
(x + 1, y + 1)
)
]
)
) for x in range(len(board[y]))]
) for y in range(len(board))
]
## Instruction:
Make separator line match width of board
## Code After:
import sys, random, time
boardSize = (10,10)
while True: foo, bar, baz, globals()['board'] = None if globals().get('board') is None else [
(
[sys.stdout.write('X' if cell else ' ') for cell in row],
sys.stdout.write('\n')
) for row in board
], time.sleep(1), sys.stdout.write('=' * boardSize[0] +'\n'), [
[random.random() < 0.5 for i in range(boardSize[0])] for j in range(boardSize[1])
] if 'board' not in globals() else [
map(
lambda z: (z[1] in (2,3) and board[y][z[0]]) or z[1]==3,
[
(
x,
sum(
[
int(
y0 in range(len(board)) and x0 in range(len(board[y0])) and board[y0][x0]
) for x0,y0 in (
(x - 1, y - 1),
(x, y -1),
(x + 1, y - 1),
(x - 1, y),
(x + 1, y),
(x - 1, y + 1),
(x, y + 1),
(x + 1, y + 1)
)
]
)
) for x in range(len(board[y]))]
) for y in range(len(board))
]
|
12f835d9060decfc675c81f7a1499b373b78f4cc | TrevorNet/tests/test_idx.py | TrevorNet/tests/test_idx.py | from .. import idx
import os
def test__count_dimensions():
yield check__count_dimensions, 9, 0
yield check__count_dimensions, [1, 2], 1
yield check__count_dimensions, [[1, 2], [3, 6, 2]], 2
yield check__count_dimensions, [[[1,2], [2]]], 3
def check__count_dimensions(lst, i):
assert idx._count_dimensions(lst) == i
# these two are equivalent according to the format on http://yann.lecun.com/exdb/mnist/
_somelist = [[1, 2], [3, 4]]
_somebytes = b'\x00\x00\x0C\x02' + b'\x01\x02\x03\x04'
def test_list_to_idx():
data = idx.list_to_idx(_somelist, 'i')
assert data == _somebytes
def test_idx_to_list():
lst = idx.idx_to_list(_somebytes)
assert lst == _somelist
| from .. import idx
import os
def test__count_dimensions():
yield check__count_dimensions, 9, 0
yield check__count_dimensions, [1, 2], 1
yield check__count_dimensions, [[1, 2], [3, 6, 2]], 2
yield check__count_dimensions, [[[1,2], [2]]], 3
def check__count_dimensions(lst, i):
assert idx._count_dimensions(lst) == i
# these two are equivalent according to the format on http://yann.lecun.com/exdb/mnist/
_somelist = [[1, 2], [3, 4]]
def _get_somebytes():
header = b'\x00\x00\x0C\x02'
dimensionsizes = b'\x00\x00\x00\x02' + b'\x00\x00\x00\x02'
data = b'\x00\x00\x00\x01' + b'\x00\x00\x00\x02'
data += b'\x00\x00\x00\x03' + b'\x00\x00\x00\x04'
return header + dimensionsizes + data
_somebytes = _get_somebytes()
def test_list_to_idx():
data = idx.list_to_idx(_somelist, 'i')
print(data, _somebytes)
assert data == _somebytes
def test_idx_to_list():
lst = idx.idx_to_list(_somebytes)
assert lst == _somelist
| Fix issue where idx test uses wrong bytes object | Fix issue where idx test uses wrong bytes object
Forgot to include the sizes of each dimension
| Python | mit | tmerr/trevornet | from .. import idx
import os
def test__count_dimensions():
yield check__count_dimensions, 9, 0
yield check__count_dimensions, [1, 2], 1
yield check__count_dimensions, [[1, 2], [3, 6, 2]], 2
yield check__count_dimensions, [[[1,2], [2]]], 3
def check__count_dimensions(lst, i):
assert idx._count_dimensions(lst) == i
# these two are equivalent according to the format on http://yann.lecun.com/exdb/mnist/
_somelist = [[1, 2], [3, 4]]
- _somebytes = b'\x00\x00\x0C\x02' + b'\x01\x02\x03\x04'
+ def _get_somebytes():
+ header = b'\x00\x00\x0C\x02'
+ dimensionsizes = b'\x00\x00\x00\x02' + b'\x00\x00\x00\x02'
+ data = b'\x00\x00\x00\x01' + b'\x00\x00\x00\x02'
+ data += b'\x00\x00\x00\x03' + b'\x00\x00\x00\x04'
+ return header + dimensionsizes + data
+ _somebytes = _get_somebytes()
def test_list_to_idx():
data = idx.list_to_idx(_somelist, 'i')
+ print(data, _somebytes)
assert data == _somebytes
def test_idx_to_list():
lst = idx.idx_to_list(_somebytes)
assert lst == _somelist
| Fix issue where idx test uses wrong bytes object | ## Code Before:
from .. import idx
import os
def test__count_dimensions():
yield check__count_dimensions, 9, 0
yield check__count_dimensions, [1, 2], 1
yield check__count_dimensions, [[1, 2], [3, 6, 2]], 2
yield check__count_dimensions, [[[1,2], [2]]], 3
def check__count_dimensions(lst, i):
assert idx._count_dimensions(lst) == i
# these two are equivalent according to the format on http://yann.lecun.com/exdb/mnist/
_somelist = [[1, 2], [3, 4]]
_somebytes = b'\x00\x00\x0C\x02' + b'\x01\x02\x03\x04'
def test_list_to_idx():
data = idx.list_to_idx(_somelist, 'i')
assert data == _somebytes
def test_idx_to_list():
lst = idx.idx_to_list(_somebytes)
assert lst == _somelist
## Instruction:
Fix issue where idx test uses wrong bytes object
## Code After:
from .. import idx
import os
def test__count_dimensions():
yield check__count_dimensions, 9, 0
yield check__count_dimensions, [1, 2], 1
yield check__count_dimensions, [[1, 2], [3, 6, 2]], 2
yield check__count_dimensions, [[[1,2], [2]]], 3
def check__count_dimensions(lst, i):
assert idx._count_dimensions(lst) == i
# these two are equivalent according to the format on http://yann.lecun.com/exdb/mnist/
_somelist = [[1, 2], [3, 4]]
def _get_somebytes():
header = b'\x00\x00\x0C\x02'
dimensionsizes = b'\x00\x00\x00\x02' + b'\x00\x00\x00\x02'
data = b'\x00\x00\x00\x01' + b'\x00\x00\x00\x02'
data += b'\x00\x00\x00\x03' + b'\x00\x00\x00\x04'
return header + dimensionsizes + data
_somebytes = _get_somebytes()
def test_list_to_idx():
data = idx.list_to_idx(_somelist, 'i')
print(data, _somebytes)
assert data == _somebytes
def test_idx_to_list():
lst = idx.idx_to_list(_somebytes)
assert lst == _somelist
|
f590080fc4d431b333f73ad548a50bc24d4fcf5b | fuzzer/main.py | fuzzer/main.py | import generator
from ctypes import CDLL
import numpy as np
# Initializes the harness and sets it up for work
harness = CDLL("harness/harness.so")
while True:
t = generator.generate()
harness.register_testcase(t)
try:
exec(t, {'np':np})
except:
# If the exec fails, then we should not store
continue
generator.register(t)
| import generator
from ctypes import CDLL
import numpy as np
# Initializes the harness and sets it up for work
harness = CDLL("harness/harness.so")
while True:
t = generator.generate()
harness.register_testcase(bytes(t, 'ascii'))
try:
exec(t, {'np':np})
except:
# If the exec fails, then we should not store
continue
generator.register(t)
| Send char string instead of widechar string | Send char string instead of widechar string
| Python | apache-2.0 | jaybosamiya/fuzzing-numpy,jaybosamiya/fuzzing-numpy,jaybosamiya/fuzzing-numpy | import generator
from ctypes import CDLL
import numpy as np
# Initializes the harness and sets it up for work
harness = CDLL("harness/harness.so")
while True:
t = generator.generate()
- harness.register_testcase(t)
+ harness.register_testcase(bytes(t, 'ascii'))
try:
exec(t, {'np':np})
except:
# If the exec fails, then we should not store
continue
generator.register(t)
| Send char string instead of widechar string | ## Code Before:
import generator
from ctypes import CDLL
import numpy as np
# Initializes the harness and sets it up for work
harness = CDLL("harness/harness.so")
while True:
t = generator.generate()
harness.register_testcase(t)
try:
exec(t, {'np':np})
except:
# If the exec fails, then we should not store
continue
generator.register(t)
## Instruction:
Send char string instead of widechar string
## Code After:
import generator
from ctypes import CDLL
import numpy as np
# Initializes the harness and sets it up for work
harness = CDLL("harness/harness.so")
while True:
t = generator.generate()
harness.register_testcase(bytes(t, 'ascii'))
try:
exec(t, {'np':np})
except:
# If the exec fails, then we should not store
continue
generator.register(t)
|
627729380b8fbd6d1b4e4eec0362418dbf698d55 | libs/qpanel/upgrader.py | libs/qpanel/upgrader.py |
from urllib2 import Request, urlopen
from distutils.version import LooseVersion
BRANCH = 'stable'
REPO = 'git@github.com:roramirez/qpanel.git'
URL_STABLE_VERSION = 'https://raw.githubusercontent.com/roramirez/qpanel' + \
'/%s/VERSION' % BRANCH
def require_upgrade():
a = LooseVersion(get_current_version())
b = LooseVersion(get_stable_version())
if a < b:
return True
return False
# InmplementME
def last_check_update():
return True
def get_current_version():
current_version = open('VERSION')
return __first_line(current_version.read())
def get_stable_version():
stable_version = __get_data_url(URL_STABLE_VERSION)
return __first_line(stable_version)
def __get_data_url(url):
req = Request(url)
try:
response = urlopen(req)
return response.read()
except:
return None
def __first_line(content):
tmp = ''
if content is not None:
tmp = content.split('\n')
if len(tmp) > 1:
return tmp[0]
return tmp
|
from urllib2 import Request, urlopen
from distutils.version import LooseVersion
BRANCH = 'stable'
REPO = 'git@github.com:roramirez/qpanel.git'
URL_STABLE_VERSION = 'https://rodrigoramirez.com/qpanel/version/' + BRANCH
def require_upgrade():
a = LooseVersion(get_current_version())
b = LooseVersion(get_stable_version())
if a < b:
return True
return False
# InmplementME
def last_check_update():
return True
def get_current_version():
current_version = open('VERSION')
return __first_line(current_version.read())
def get_stable_version():
stable_version = __get_data_url(URL_STABLE_VERSION)
return __first_line(stable_version)
def __get_data_url(url):
req = Request(url)
try:
response = urlopen(req)
return response.read()
except:
return None
def __first_line(content):
tmp = ''
if content is not None:
tmp = content.split('\n')
if len(tmp) > 1:
return tmp[0]
return tmp
| Change url to get stable version number | Change url to get stable version number
| Python | mit | roramirez/qpanel,roramirez/qpanel,skazancev/qpanel,skazancev/qpanel,skazancev/qpanel,roramirez/qpanel,roramirez/qpanel,skazancev/qpanel |
from urllib2 import Request, urlopen
from distutils.version import LooseVersion
BRANCH = 'stable'
REPO = 'git@github.com:roramirez/qpanel.git'
+ URL_STABLE_VERSION = 'https://rodrigoramirez.com/qpanel/version/' + BRANCH
- URL_STABLE_VERSION = 'https://raw.githubusercontent.com/roramirez/qpanel' + \
- '/%s/VERSION' % BRANCH
def require_upgrade():
a = LooseVersion(get_current_version())
b = LooseVersion(get_stable_version())
if a < b:
return True
return False
# InmplementME
def last_check_update():
return True
def get_current_version():
current_version = open('VERSION')
return __first_line(current_version.read())
def get_stable_version():
stable_version = __get_data_url(URL_STABLE_VERSION)
return __first_line(stable_version)
def __get_data_url(url):
req = Request(url)
try:
response = urlopen(req)
return response.read()
except:
return None
def __first_line(content):
tmp = ''
if content is not None:
tmp = content.split('\n')
if len(tmp) > 1:
return tmp[0]
return tmp
| Change url to get stable version number | ## Code Before:
from urllib2 import Request, urlopen
from distutils.version import LooseVersion
BRANCH = 'stable'
REPO = 'git@github.com:roramirez/qpanel.git'
URL_STABLE_VERSION = 'https://raw.githubusercontent.com/roramirez/qpanel' + \
'/%s/VERSION' % BRANCH
def require_upgrade():
a = LooseVersion(get_current_version())
b = LooseVersion(get_stable_version())
if a < b:
return True
return False
# InmplementME
def last_check_update():
return True
def get_current_version():
current_version = open('VERSION')
return __first_line(current_version.read())
def get_stable_version():
stable_version = __get_data_url(URL_STABLE_VERSION)
return __first_line(stable_version)
def __get_data_url(url):
req = Request(url)
try:
response = urlopen(req)
return response.read()
except:
return None
def __first_line(content):
tmp = ''
if content is not None:
tmp = content.split('\n')
if len(tmp) > 1:
return tmp[0]
return tmp
## Instruction:
Change url to get stable version number
## Code After:
from urllib2 import Request, urlopen
from distutils.version import LooseVersion
BRANCH = 'stable'
REPO = 'git@github.com:roramirez/qpanel.git'
URL_STABLE_VERSION = 'https://rodrigoramirez.com/qpanel/version/' + BRANCH
def require_upgrade():
a = LooseVersion(get_current_version())
b = LooseVersion(get_stable_version())
if a < b:
return True
return False
# InmplementME
def last_check_update():
return True
def get_current_version():
current_version = open('VERSION')
return __first_line(current_version.read())
def get_stable_version():
stable_version = __get_data_url(URL_STABLE_VERSION)
return __first_line(stable_version)
def __get_data_url(url):
req = Request(url)
try:
response = urlopen(req)
return response.read()
except:
return None
def __first_line(content):
tmp = ''
if content is not None:
tmp = content.split('\n')
if len(tmp) > 1:
return tmp[0]
return tmp
|
798a716cb6c3acd6e636d3b9cab755950ead5539 | Seeder/voting/signals.py | Seeder/voting/signals.py | from django.dispatch import receiver
from django.db.models.signals import post_save
from voting import constants
from source.models import Source
from voting.models import VotingRound
from source import constants as source_constants
from contracts.models import Contract
@receiver(signal=post_save, sender=Source)
def create_voting_round(instance, created, **kwargs):
"""
Creates a voting round after new Source is created.
"""
if created:
voting_round = VotingRound(source=instance)
voting_round.save()
@receiver(signal=post_save, sender=VotingRound)
def process_voting_round(instance, created, **kwargs):
"""
Edits Source according to decision made in voting round.
If source already has valid contract then we can switch directly
to running state.
"""
if not created:
source = instance.source
if instance.state == constants.VOTE_APPROVE:
if source.contract_set.valid():
source.state = source_constants.STATE_RUNNING
source.save()
return
else:
contract = Contract(source=source)
contract.publisher = source.publisher
contract.save()
contract.sources.add(source)
source.state = constants.VOTE_TO_SOURCE[instance.state]
source.save()
| from django.dispatch import receiver
from django.db.models.signals import post_save
from voting import constants
from source.models import Source
from voting.models import VotingRound
from source import constants as source_constants
from contracts.models import Contract
@receiver(signal=post_save, sender=Source)
def create_voting_round(instance, created, **kwargs):
"""
Creates a voting round after new Source is created.
"""
if created:
voting_round = VotingRound(source=instance)
voting_round.save()
@receiver(signal=post_save, sender=VotingRound)
def process_voting_round(instance, created, **kwargs):
"""
Edits Source according to decision made in voting round.
If source already has valid contract then we can switch directly
to running state.
"""
if not created:
source = instance.source
if instance.state == constants.VOTE_APPROVE:
if source.contract_set.valid():
source.state = source_constants.STATE_RUNNING
source.save()
return
else:
contract = Contract()
contract.publisher = source.publisher
contract.save()
contract.sources.add(source)
source.state = constants.VOTE_TO_SOURCE[instance.state]
source.save()
| Fix process_voting_round to reflect contract model | Fix process_voting_round to reflect contract model
| Python | mit | WebArchivCZ/Seeder,WebArchivCZ/Seeder,WebArchivCZ/Seeder,WebArchivCZ/Seeder,WebArchivCZ/Seeder | from django.dispatch import receiver
from django.db.models.signals import post_save
from voting import constants
from source.models import Source
from voting.models import VotingRound
from source import constants as source_constants
from contracts.models import Contract
@receiver(signal=post_save, sender=Source)
def create_voting_round(instance, created, **kwargs):
"""
Creates a voting round after new Source is created.
"""
if created:
voting_round = VotingRound(source=instance)
voting_round.save()
@receiver(signal=post_save, sender=VotingRound)
def process_voting_round(instance, created, **kwargs):
"""
Edits Source according to decision made in voting round.
If source already has valid contract then we can switch directly
to running state.
"""
if not created:
source = instance.source
if instance.state == constants.VOTE_APPROVE:
if source.contract_set.valid():
source.state = source_constants.STATE_RUNNING
source.save()
return
else:
- contract = Contract(source=source)
+ contract = Contract()
contract.publisher = source.publisher
contract.save()
contract.sources.add(source)
source.state = constants.VOTE_TO_SOURCE[instance.state]
source.save()
| Fix process_voting_round to reflect contract model | ## Code Before:
from django.dispatch import receiver
from django.db.models.signals import post_save
from voting import constants
from source.models import Source
from voting.models import VotingRound
from source import constants as source_constants
from contracts.models import Contract
@receiver(signal=post_save, sender=Source)
def create_voting_round(instance, created, **kwargs):
"""
Creates a voting round after new Source is created.
"""
if created:
voting_round = VotingRound(source=instance)
voting_round.save()
@receiver(signal=post_save, sender=VotingRound)
def process_voting_round(instance, created, **kwargs):
"""
Edits Source according to decision made in voting round.
If source already has valid contract then we can switch directly
to running state.
"""
if not created:
source = instance.source
if instance.state == constants.VOTE_APPROVE:
if source.contract_set.valid():
source.state = source_constants.STATE_RUNNING
source.save()
return
else:
contract = Contract(source=source)
contract.publisher = source.publisher
contract.save()
contract.sources.add(source)
source.state = constants.VOTE_TO_SOURCE[instance.state]
source.save()
## Instruction:
Fix process_voting_round to reflect contract model
## Code After:
from django.dispatch import receiver
from django.db.models.signals import post_save
from voting import constants
from source.models import Source
from voting.models import VotingRound
from source import constants as source_constants
from contracts.models import Contract
@receiver(signal=post_save, sender=Source)
def create_voting_round(instance, created, **kwargs):
"""
Creates a voting round after new Source is created.
"""
if created:
voting_round = VotingRound(source=instance)
voting_round.save()
@receiver(signal=post_save, sender=VotingRound)
def process_voting_round(instance, created, **kwargs):
"""
Edits Source according to decision made in voting round.
If source already has valid contract then we can switch directly
to running state.
"""
if not created:
source = instance.source
if instance.state == constants.VOTE_APPROVE:
if source.contract_set.valid():
source.state = source_constants.STATE_RUNNING
source.save()
return
else:
contract = Contract()
contract.publisher = source.publisher
contract.save()
contract.sources.add(source)
source.state = constants.VOTE_TO_SOURCE[instance.state]
source.save()
|
856207c8399d94e99a6f2ffb1e10befecb6150cf | src/generate-jobs/calculate_quad_key.py | src/generate-jobs/calculate_quad_key.py | import system
import csv
from docopt import docopt
def quad_tree(tx, ty, zoom):
"""
Converts XYZ tile coordinates to Microsoft QuadTree
http://www.maptiler.org/google-maps-coordinates-tile-bounds-projection/
"""
quad_key = ''
for i in range(zoom, 0, -1):
digit = 0
mask = 1 << (i-1)
if (tx & mask) != 0:
digit += 1
if (ty & mask) != 0:
digit += 2
quad_key += str(digit)
return quad_key
if __name__ == '__main__':
args = docopt(__doc__, version='0.1')
writer = csv.writer(system.out)
with open(args['<list_file>'], "r") as file_handle:
for line in file_handle:
z, x, y = line.split('/')
writer.writerow([
line,
quad_tree(int(x), int(y), int(z))]
)
| import sys
import csv
from docopt import docopt
def quad_tree(tx, ty, zoom):
"""
Converts XYZ tile coordinates to Microsoft QuadTree
http://www.maptiler.org/google-maps-coordinates-tile-bounds-projection/
"""
quad_key = ''
for i in range(zoom, 0, -1):
digit = 0
mask = 1 << (i-1)
if (tx & mask) != 0:
digit += 1
if (ty & mask) != 0:
digit += 2
quad_key += str(digit)
return quad_key
if __name__ == '__main__':
args = docopt(__doc__, version='0.1')
writer = csv.writer(sys.stdout, delimiter='\t')
with open(args['<list_file>'], "r") as file_handle:
for line in file_handle:
z, x, y = line.split('/')
writer.writerow([
line.strip(),
quad_tree(int(x), int(y), int(z))]
)
| Fix line endings in CSV and stdout typo | Fix line endings in CSV and stdout typo
| Python | mit | geometalab/osm2vectortiles,geometalab/osm2vectortiles,osm2vectortiles/osm2vectortiles,osm2vectortiles/osm2vectortiles | - import system
+ import sys
import csv
from docopt import docopt
def quad_tree(tx, ty, zoom):
"""
Converts XYZ tile coordinates to Microsoft QuadTree
http://www.maptiler.org/google-maps-coordinates-tile-bounds-projection/
"""
quad_key = ''
for i in range(zoom, 0, -1):
digit = 0
mask = 1 << (i-1)
if (tx & mask) != 0:
digit += 1
if (ty & mask) != 0:
digit += 2
quad_key += str(digit)
return quad_key
if __name__ == '__main__':
args = docopt(__doc__, version='0.1')
- writer = csv.writer(system.out)
+ writer = csv.writer(sys.stdout, delimiter='\t')
with open(args['<list_file>'], "r") as file_handle:
for line in file_handle:
z, x, y = line.split('/')
writer.writerow([
- line,
+ line.strip(),
quad_tree(int(x), int(y), int(z))]
)
| Fix line endings in CSV and stdout typo | ## Code Before:
import system
import csv
from docopt import docopt
def quad_tree(tx, ty, zoom):
"""
Converts XYZ tile coordinates to Microsoft QuadTree
http://www.maptiler.org/google-maps-coordinates-tile-bounds-projection/
"""
quad_key = ''
for i in range(zoom, 0, -1):
digit = 0
mask = 1 << (i-1)
if (tx & mask) != 0:
digit += 1
if (ty & mask) != 0:
digit += 2
quad_key += str(digit)
return quad_key
if __name__ == '__main__':
args = docopt(__doc__, version='0.1')
writer = csv.writer(system.out)
with open(args['<list_file>'], "r") as file_handle:
for line in file_handle:
z, x, y = line.split('/')
writer.writerow([
line,
quad_tree(int(x), int(y), int(z))]
)
## Instruction:
Fix line endings in CSV and stdout typo
## Code After:
import sys
import csv
from docopt import docopt
def quad_tree(tx, ty, zoom):
"""
Converts XYZ tile coordinates to Microsoft QuadTree
http://www.maptiler.org/google-maps-coordinates-tile-bounds-projection/
"""
quad_key = ''
for i in range(zoom, 0, -1):
digit = 0
mask = 1 << (i-1)
if (tx & mask) != 0:
digit += 1
if (ty & mask) != 0:
digit += 2
quad_key += str(digit)
return quad_key
if __name__ == '__main__':
args = docopt(__doc__, version='0.1')
writer = csv.writer(sys.stdout, delimiter='\t')
with open(args['<list_file>'], "r") as file_handle:
for line in file_handle:
z, x, y = line.split('/')
writer.writerow([
line.strip(),
quad_tree(int(x), int(y), int(z))]
)
|
74ce850d7db766328e2931f5a8119b7e2e5b1ded | examples/basic_example.py | examples/basic_example.py | '''
A simple script using sparqllib and rdflib to retrieve a JSON representation
of some information about Barack Obama from dbpedia.
'''
from sparqllib import Query
from rdflib import BNode, Literal
from rdflib.namespace import FOAF
from pprint import pprint
if __name__ == "__main__":
# construct the query variables (the explict names are optional)
obama, relation, value = BNode("Obama"), BNode("relation"), BNode("value")
# construct the query itself, selecting the relation and value variables
q = Query(result_vars=[relation, value])
# get everyone with the name Barack Obama
q.add(subject=obama, relationship=FOAF.name,
object=Literal("Barack Obama", lang="en"))
# get every relation these people have to any object
q.add(subject=obama, relationship=relation, object=value)
# limit the results to the first 50 distince pairs
q.result_limit = 50
print(str(q))
print(pprint(q.execute()))
| '''
A simple script using sparqllib and rdflib to retrieve a JSON representation
of some information about Barack Obama from dbpedia.
'''
from sparqllib import Query
from rdflib import BNode, Literal
from rdflib.namespace import FOAF
from pprint import pprint
def main():
# construct the query variables (the explict names are optional)
obama, relation, value = BNode("Obama"), BNode("relation"), BNode("value")
# construct the query itself, selecting the relation and value variables
q = Query(result_vars=[relation, value])
# get everyone with the name Barack Obama
q.add(subject=obama, relationship=FOAF.name,
object=Literal("Barack Obama", lang="en"))
# get every relation these people have to any object
q.add(subject=obama, relationship=relation, object=value)
# limit the results to the first 50 distince pairs
q.result_limit = 50
print(str(q))
print(pprint(q.execute()))
if __name__ == "__main__":
main()
| Switch to main method in examples | Switch to main method in examples
| Python | mit | ALSchwalm/sparqllib | '''
A simple script using sparqllib and rdflib to retrieve a JSON representation
of some information about Barack Obama from dbpedia.
'''
from sparqllib import Query
from rdflib import BNode, Literal
from rdflib.namespace import FOAF
from pprint import pprint
- if __name__ == "__main__":
+ def main():
# construct the query variables (the explict names are optional)
obama, relation, value = BNode("Obama"), BNode("relation"), BNode("value")
# construct the query itself, selecting the relation and value variables
q = Query(result_vars=[relation, value])
# get everyone with the name Barack Obama
q.add(subject=obama, relationship=FOAF.name,
object=Literal("Barack Obama", lang="en"))
# get every relation these people have to any object
q.add(subject=obama, relationship=relation, object=value)
# limit the results to the first 50 distince pairs
q.result_limit = 50
print(str(q))
print(pprint(q.execute()))
+ if __name__ == "__main__":
+ main()
+ | Switch to main method in examples | ## Code Before:
'''
A simple script using sparqllib and rdflib to retrieve a JSON representation
of some information about Barack Obama from dbpedia.
'''
from sparqllib import Query
from rdflib import BNode, Literal
from rdflib.namespace import FOAF
from pprint import pprint
if __name__ == "__main__":
# construct the query variables (the explict names are optional)
obama, relation, value = BNode("Obama"), BNode("relation"), BNode("value")
# construct the query itself, selecting the relation and value variables
q = Query(result_vars=[relation, value])
# get everyone with the name Barack Obama
q.add(subject=obama, relationship=FOAF.name,
object=Literal("Barack Obama", lang="en"))
# get every relation these people have to any object
q.add(subject=obama, relationship=relation, object=value)
# limit the results to the first 50 distince pairs
q.result_limit = 50
print(str(q))
print(pprint(q.execute()))
## Instruction:
Switch to main method in examples
## Code After:
'''
A simple script using sparqllib and rdflib to retrieve a JSON representation
of some information about Barack Obama from dbpedia.
'''
from sparqllib import Query
from rdflib import BNode, Literal
from rdflib.namespace import FOAF
from pprint import pprint
def main():
# construct the query variables (the explict names are optional)
obama, relation, value = BNode("Obama"), BNode("relation"), BNode("value")
# construct the query itself, selecting the relation and value variables
q = Query(result_vars=[relation, value])
# get everyone with the name Barack Obama
q.add(subject=obama, relationship=FOAF.name,
object=Literal("Barack Obama", lang="en"))
# get every relation these people have to any object
q.add(subject=obama, relationship=relation, object=value)
# limit the results to the first 50 distince pairs
q.result_limit = 50
print(str(q))
print(pprint(q.execute()))
if __name__ == "__main__":
main()
|